1 /* This file is part of the Scope::Upper Perl module.
2 * See http://search.cpan.org/dist/Scope-Upper/ */
4 #define PERL_NO_GET_CONTEXT
9 #define __PACKAGE__ "Scope::Upper"
15 /* --- Compatibility ------------------------------------------------------- */
25 #ifndef PERL_UNUSED_VAR
26 # define PERL_UNUSED_VAR(V)
30 # define STMT_START do
34 # define STMT_END while (0)
38 # define SU_D(X) STMT_START X STMT_END
44 # define Newx(v, n, c) New(0, v, n, c)
49 # define SU_POISON(D, N, T) PoisonNew((D), (N), T)
50 # elif defined(Poison)
51 # define SU_POISON(D, N, T) Poison((D), (N), T)
55 # define SU_POISON(D, N, T) NOOP
59 # define SvPV_const(S, L) SvPV(S, L)
62 #ifndef SvPV_nolen_const
63 # define SvPV_nolen_const(S) SvPV_nolen(S)
66 #ifndef SvREFCNT_inc_simple_void
67 # define SvREFCNT_inc_simple_void(sv) ((void) SvREFCNT_inc(sv))
71 # define mPUSHi(I) PUSHs(sv_2mortal(newSViv(I)))
75 # define GvCV_set(G, C) (GvCV(G) = (C))
79 # define CvGV_set(C, G) (CvGV(C) = (G))
83 # define CxHASARGS(C) ((C)->blk_sub.hasargs)
87 # define HvNAME_get(H) HvNAME(H)
90 #ifndef gv_fetchpvn_flags
91 # define gv_fetchpvn_flags(A, B, C, D) gv_fetchpv((A), (C), (D))
95 # define cv_clone(P) Perl_cv_clone(aTHX_ (P))
98 #ifndef PERL_MAGIC_tied
99 # define PERL_MAGIC_tied 'P'
102 #ifndef PERL_MAGIC_env
103 # define PERL_MAGIC_env 'E'
106 #ifndef NEGATIVE_INDICES_VAR
107 # define NEGATIVE_INDICES_VAR "NEGATIVE_INDICES"
110 #define SU_HAS_PERL(R, V, S) (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S))))))
111 #define SU_HAS_PERL_EXACT(R, V, S) ((PERL_REVISION == (R)) && (PERL_VERSION == (V)) && (PERL_SUBVERSION == (S)))
113 /* --- Threads and multiplicity -------------------------------------------- */
115 #ifndef SU_MULTIPLICITY
116 # if defined(MULTIPLICITY) || defined(PERL_IMPLICIT_CONTEXT)
117 # define SU_MULTIPLICITY 1
119 # define SU_MULTIPLICITY 0
122 #if SU_MULTIPLICITY && !defined(tTHX)
123 # define tTHX PerlInterpreter*
126 #if SU_MULTIPLICITY && defined(USE_ITHREADS) && defined(dMY_CXT) && defined(MY_CXT) && defined(START_MY_CXT) && defined(MY_CXT_INIT) && (defined(MY_CXT_CLONE) || defined(dMY_CXT_SV))
127 # define SU_THREADSAFE 1
128 # ifndef MY_CXT_CLONE
129 # define MY_CXT_CLONE \
131 my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1)); \
132 Copy(INT2PTR(my_cxt_t*, SvUV(my_cxt_sv)), my_cxtp, 1, my_cxt_t); \
133 sv_setuv(my_cxt_sv, PTR2UV(my_cxtp))
136 # define SU_THREADSAFE 0
138 # define dMY_CXT dNOOP
140 # define MY_CXT su_globaldata
142 # define START_MY_CXT STATIC my_cxt_t MY_CXT;
144 # define MY_CXT_INIT NOOP
146 # define MY_CXT_CLONE NOOP
149 /* --- unwind() global storage --------------------------------------------- */
159 /* --- uplevel() data tokens and global storage ---------------------------- */
169 PERL_SI *old_curstackinfo;
180 STATIC su_uplevel_ud *su_uplevel_ud_new(pTHX) {
181 #define su_uplevel_ud_new() su_uplevel_ud_new(aTHX)
185 Newx(sud, 1, su_uplevel_ud);
188 Newx(si, 1, PERL_SI);
189 si->si_stack = newAV();
190 AvREAL_off(si->si_stack);
191 si->si_cxstack = NULL;
199 STATIC void su_uplevel_ud_delete(pTHX_ su_uplevel_ud *sud) {
200 #define su_uplevel_ud_delete(S) su_uplevel_ud_delete(aTHX_ (S))
201 PERL_SI *si = sud->si;
203 Safefree(si->si_cxstack);
204 SvREFCNT_dec(si->si_stack);
214 } su_uplevel_storage;
216 #ifndef SU_UPLEVEL_STORAGE_SIZE
217 # define SU_UPLEVEL_STORAGE_SIZE 4
220 /* --- Global data --------------------------------------------------------- */
222 #define MY_CXT_KEY __PACKAGE__ "::_guts" XS_VERSION
225 char *stack_placeholder;
226 su_unwind_storage unwind_storage;
227 su_uplevel_storage uplevel_storage;
232 /* --- Stack manipulations ------------------------------------------------- */
234 #define SU_SAVE_PLACEHOLDER() save_pptr(&MY_CXT.stack_placeholder)
236 #define SU_SAVE_DESTRUCTOR_SIZE 3
237 #define SU_SAVE_PLACEHOLDER_SIZE 3
239 #define SU_SAVE_SCALAR_SIZE 3
241 #define SU_SAVE_ARY_SIZE 3
242 #define SU_SAVE_AELEM_SIZE 4
244 # define SU_SAVE_ADELETE_SIZE 3
246 # define SU_SAVE_ADELETE_SIZE SU_SAVE_DESTRUCTOR_SIZE
248 #if SU_SAVE_AELEM_SIZE < SU_SAVE_ADELETE_SIZE
249 # define SU_SAVE_AELEM_OR_ADELETE_SIZE SU_SAVE_ADELETE_SIZE
251 # define SU_SAVE_AELEM_OR_ADELETE_SIZE SU_SAVE_AELEM_SIZE
254 #define SU_SAVE_HASH_SIZE 3
255 #define SU_SAVE_HELEM_SIZE 4
256 #define SU_SAVE_HDELETE_SIZE 4
257 #if SU_SAVE_HELEM_SIZE < SU_SAVE_HDELETE_SIZE
258 # define SU_SAVE_HELEM_OR_HDELETE_SIZE SU_SAVE_HDELETE_SIZE
260 # define SU_SAVE_HELEM_OR_HDELETE_SIZE SU_SAVE_HELEM_SIZE
263 #define SU_SAVE_GVCV_SIZE SU_SAVE_DESTRUCTOR_SIZE
265 #if !SU_HAS_PERL(5, 8, 9)
266 # define SU_SAVE_GP_SIZE 6
267 #elif !SU_HAS_PERL(5, 13, 0) || (SU_RELEASE && SU_HAS_PERL_EXACT(5, 13, 0))
268 # define SU_SAVE_GP_SIZE 3
269 #elif !SU_HAS_PERL(5, 13, 8)
270 # define SU_SAVE_GP_SIZE 4
272 # define SU_SAVE_GP_SIZE 3
275 #ifndef SvCANEXISTDELETE
276 # define SvCANEXISTDELETE(sv) \
278 || ((mg = mg_find((SV *) sv, PERL_MAGIC_tied)) \
279 && (stash = SvSTASH(SvRV(SvTIED_obj((SV *) sv, mg)))) \
280 && gv_fetchmethod_autoload(stash, "EXISTS", TRUE) \
281 && gv_fetchmethod_autoload(stash, "DELETE", TRUE) \
286 /* ... Saving array elements ............................................... */
288 STATIC I32 su_av_key2idx(pTHX_ AV *av, I32 key) {
289 #define su_av_key2idx(A, K) su_av_key2idx(aTHX_ (A), (K))
295 /* Added by MJD in perl-5.8.1 with 6f12eb6d2a1dfaf441504d869b27d2e40ef4966a */
296 #if SU_HAS_PERL(5, 8, 1)
297 if (SvRMAGICAL(av)) {
298 const MAGIC * const tied_magic = mg_find((SV *) av, PERL_MAGIC_tied);
300 SV * const * const negative_indices_glob =
301 hv_fetch(SvSTASH(SvRV(SvTIED_obj((SV *) (av), tied_magic))),
302 NEGATIVE_INDICES_VAR, 16, 0);
303 if (negative_indices_glob && SvTRUE(GvSV(*negative_indices_glob)))
309 idx = key + av_len(av) + 1;
323 STATIC void su_adelete(pTHX_ void *ud_) {
324 su_ud_adelete *ud = (su_ud_adelete *) ud_;
326 av_delete(ud->av, ud->idx, G_DISCARD);
327 SvREFCNT_dec(ud->av);
332 STATIC void su_save_adelete(pTHX_ AV *av, I32 idx) {
333 #define su_save_adelete(A, K) su_save_adelete(aTHX_ (A), (K))
336 Newx(ud, 1, su_ud_adelete);
339 SvREFCNT_inc_simple_void(av);
341 SAVEDESTRUCTOR_X(su_adelete, ud);
344 #define SAVEADELETE(A, K) su_save_adelete((A), (K))
346 #endif /* SAVEADELETE */
348 STATIC void su_save_aelem(pTHX_ AV *av, SV *key, SV *val) {
349 #define su_save_aelem(A, K, V) su_save_aelem(aTHX_ (A), (K), (V))
356 idx = su_av_key2idx(av, SvIV(key));
358 if (SvCANEXISTDELETE(av))
359 preeminent = av_exists(av, idx);
361 svp = av_fetch(av, idx, 1);
362 if (!svp || *svp == &PL_sv_undef) croak(PL_no_aelem, idx);
365 save_aelem(av, idx, svp);
367 SAVEADELETE(av, idx);
369 if (val) { /* local $x[$idx] = $val; */
370 SvSetMagicSV(*svp, val);
371 } else { /* local $x[$idx]; delete $x[$idx]; */
372 av_delete(av, idx, G_DISCARD);
376 /* ... Saving hash elements ................................................ */
378 STATIC void su_save_helem(pTHX_ HV *hv, SV *keysv, SV *val) {
379 #define su_save_helem(H, K, V) su_save_helem(aTHX_ (H), (K), (V))
386 if (SvCANEXISTDELETE(hv) || mg_find((SV *) hv, PERL_MAGIC_env))
387 preeminent = hv_exists_ent(hv, keysv, 0);
389 he = hv_fetch_ent(hv, keysv, 1, 0);
390 svp = he ? &HeVAL(he) : NULL;
391 if (!svp || *svp == &PL_sv_undef) croak("Modification of non-creatable hash value attempted, subscript \"%s\"", SvPV_nolen_const(*svp));
393 if (HvNAME_get(hv) && isGV(*svp)) {
394 save_gp((GV *) *svp, 0);
399 save_helem(hv, keysv, svp);
402 const char * const key = SvPV_const(keysv, keylen);
403 SAVEDELETE(hv, savepvn(key, keylen),
404 SvUTF8(keysv) ? -(I32)keylen : (I32)keylen);
407 if (val) { /* local $x{$keysv} = $val; */
408 SvSetMagicSV(*svp, val);
409 } else { /* local $x{$keysv}; delete $x{$keysv}; */
410 (void)hv_delete_ent(hv, keysv, G_DISCARD, HeHASH(he));
414 /* ... Saving code slots from a glob ....................................... */
416 #if !SU_HAS_PERL(5, 10, 0) && !defined(mro_method_changed_in)
417 # define mro_method_changed_in(G) PL_sub_generation++
425 STATIC void su_restore_gvcv(pTHX_ void *ud_) {
426 su_save_gvcv_ud *ud = ud_;
429 GvCV_set(gv, ud->old_cv);
431 mro_method_changed_in(GvSTASH(gv));
436 STATIC void su_save_gvcv(pTHX_ GV *gv) {
437 #define su_save_gvcv(G) su_save_gvcv(aTHX_ (G))
440 Newx(ud, 1, su_save_gvcv_ud);
442 ud->old_cv = GvCV(gv);
446 mro_method_changed_in(GvSTASH(gv));
448 SAVEDESTRUCTOR_X(su_restore_gvcv, ud);
451 /* --- Actions ------------------------------------------------------------- */
457 void (*handler)(pTHX_ void *);
460 #define SU_UD_DEPTH(U) (((su_ud_common *) (U))->depth)
461 #define SU_UD_PAD(U) (((su_ud_common *) (U))->pad)
462 #define SU_UD_ORIGIN(U) (((su_ud_common *) (U))->origin)
463 #define SU_UD_HANDLER(U) (((su_ud_common *) (U))->handler)
465 #define SU_UD_FREE(U) STMT_START { \
466 if (SU_UD_ORIGIN(U)) Safefree(SU_UD_ORIGIN(U)); \
470 /* ... Reap ................................................................ */
477 STATIC void su_call(pTHX_ void *ud_) {
478 su_ud_reap *ud = (su_ud_reap *) ud_;
479 #if SU_HAS_PERL(5, 9, 5)
480 PERL_CONTEXT saved_cx;
487 PerlIO_printf(Perl_debug_log,
488 "%p: @@@ call\n%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
489 ud, ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
498 /* If the recently popped context isn't saved there, it will be overwritten by
499 * the sub scope from call_sv, although it's still needed in our caller. */
501 #if SU_HAS_PERL(5, 9, 5)
502 if (cxstack_ix < cxstack_max)
503 cxix = cxstack_ix + 1;
505 cxix = Perl_cxinc(aTHX);
506 saved_cx = cxstack[cxix];
509 call_sv(ud->cb, G_VOID);
511 #if SU_HAS_PERL(5, 9, 5)
512 cxstack[cxix] = saved_cx;
520 SvREFCNT_dec(ud->cb);
524 STATIC void su_reap(pTHX_ void *ud) {
525 #define su_reap(U) su_reap(aTHX_ (U))
527 PerlIO_printf(Perl_debug_log,
528 "%p: === reap\n%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
529 ud, ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
532 SAVEDESTRUCTOR_X(su_call, ud);
535 /* ... Localize & localize array/hash element .............................. */
545 #define SU_UD_LOCALIZE_FREE(U) STMT_START { \
546 SvREFCNT_dec((U)->elem); \
547 SvREFCNT_dec((U)->val); \
548 SvREFCNT_dec((U)->sv); \
552 STATIC I32 su_ud_localize_init(pTHX_ su_ud_localize *ud, SV *sv, SV *val, SV *elem) {
553 #define su_ud_localize_init(UD, S, V, E) su_ud_localize_init(aTHX_ (UD), (S), (V), (E))
558 SvREFCNT_inc_simple_void(sv);
560 if (SvTYPE(sv) >= SVt_PVGV) {
561 if (!val || !SvROK(val)) { /* local *x; or local *x = $val; */
563 } else { /* local *x = \$val; */
564 t = SvTYPE(SvRV(val));
567 } else if (SvROK(sv)) {
568 croak("Invalid %s reference as the localization target",
569 sv_reftype(SvRV(sv), 0));
572 const char *p = SvPV_const(sv, len), *s;
573 for (s = p, l = len; l > 0 && isSPACE(*s); ++s, --l) { }
579 case '$': t = SVt_PV; break;
580 case '@': t = SVt_PVAV; break;
581 case '%': t = SVt_PVHV; break;
582 case '&': t = SVt_PVCV; break;
583 case '*': t = SVt_PVGV; break;
588 } else if (val) { /* t == SVt_NULL, type can't be inferred from the sigil */
589 if (SvROK(val) && !sv_isobject(val)) {
590 t = SvTYPE(SvRV(val));
602 size = elem ? SU_SAVE_AELEM_OR_ADELETE_SIZE
607 size = elem ? SU_SAVE_HELEM_OR_HDELETE_SIZE
612 size = SU_SAVE_GP_SIZE;
616 size = SU_SAVE_GVCV_SIZE;
620 size = SU_SAVE_SCALAR_SIZE;
623 /* When deref is set, val isn't NULL */
626 ud->val = val ? newSVsv(deref ? SvRV(val) : val) : NULL;
627 ud->elem = SvREFCNT_inc(elem);
633 STATIC void su_localize(pTHX_ void *ud_) {
634 #define su_localize(U) su_localize(aTHX_ (U))
635 su_ud_localize *ud = (su_ud_localize *) ud_;
642 if (SvTYPE(sv) >= SVt_PVGV) {
646 gv = gv_fetchsv(sv, GV_ADDMULTI, t);
649 const char *name = SvPV_const(sv, len);
650 gv = gv_fetchpvn_flags(name, len, GV_ADDMULTI, t);
657 PerlIO_printf(Perl_debug_log, "%p: === localize a %s\n",ud, sv_reftype(z, 0));
658 PerlIO_printf(Perl_debug_log,
659 "%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
660 ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
664 /* Inspired from Alias.pm */
668 su_save_aelem(GvAV(gv), elem, val);
675 su_save_helem(GvHV(gv), elem, val);
681 save_gp(gv, 1); /* hide previous entry in symtab */
687 gv = (GV *) save_scalar(gv);
692 SvSetMagicSV((SV *) gv, val);
695 SU_UD_LOCALIZE_FREE(ud);
698 /* --- Pop a context back -------------------------------------------------- */
702 # define SU_CXNAME PL_block_type[CxTYPE(&cxstack[cxstack_ix])]
704 # define SU_CXNAME "XXX"
708 STATIC void su_pop(pTHX_ void *ud) {
709 #define su_pop(U) su_pop(aTHX_ (U))
710 I32 depth, base, mark, *origin;
711 depth = SU_UD_DEPTH(ud);
714 PerlIO_printf(Perl_debug_log,
716 "%p: leave scope at depth=%2d scope_ix=%2d cur_top=%2d cur_base=%2d\n",
718 ud, depth, PL_scopestack_ix,PL_savestack_ix,PL_scopestack[PL_scopestack_ix])
721 origin = SU_UD_ORIGIN(ud);
722 mark = origin[depth];
723 base = origin[depth - 1];
725 SU_D(PerlIO_printf(Perl_debug_log,
726 "%p: original scope was %*c top=%2d base=%2d\n",
727 ud, 24, ' ', mark, base));
730 SU_D(PerlIO_printf(Perl_debug_log, "%p: clear leftovers\n", ud));
731 PL_savestack_ix = mark;
734 PL_savestack_ix = base;
736 SU_UD_DEPTH(ud) = --depth;
741 if ((pad = SU_UD_PAD(ud))) {
744 SU_D(PerlIO_printf(Perl_debug_log,
745 "%p: push a pad slot at depth=%2d scope_ix=%2d save_ix=%2d\n",
746 ud, depth, PL_scopestack_ix, PL_savestack_ix));
747 SU_SAVE_PLACEHOLDER();
751 SU_D(PerlIO_printf(Perl_debug_log,
752 "%p: push destructor at depth=%2d scope_ix=%2d save_ix=%2d\n",
753 ud, depth, PL_scopestack_ix, PL_savestack_ix));
754 SAVEDESTRUCTOR_X(su_pop, ud);
756 SU_UD_HANDLER(ud)(aTHX_ ud);
759 SU_D(PerlIO_printf(Perl_debug_log,
760 "%p: --- end pop: cur_top=%2d == cur_base=%2d\n",
761 ud, PL_savestack_ix, PL_scopestack[PL_scopestack_ix]));
764 /* --- Initialize the stack and the action userdata ------------------------ */
766 STATIC I32 su_init(pTHX_ void *ud, I32 cxix, I32 size) {
767 #define su_init(U, C, S) su_init(aTHX_ (U), (C), (S))
768 I32 i, depth = 1, pad, offset, *origin;
770 SU_D(PerlIO_printf(Perl_debug_log, "%p: ### init for cx %d\n", ud, cxix));
772 if (size <= SU_SAVE_DESTRUCTOR_SIZE)
775 I32 extra = size - SU_SAVE_DESTRUCTOR_SIZE;
776 pad = extra / SU_SAVE_PLACEHOLDER_SIZE;
777 if (extra % SU_SAVE_PLACEHOLDER_SIZE)
780 offset = SU_SAVE_DESTRUCTOR_SIZE + SU_SAVE_PLACEHOLDER_SIZE * pad;
782 SU_D(PerlIO_printf(Perl_debug_log, "%p: size=%d pad=%d offset=%d\n",
783 ud, size, pad, offset));
785 for (i = cxstack_ix; i > cxix; --i) {
786 PERL_CONTEXT *cx = cxstack + i;
787 switch (CxTYPE(cx)) {
788 #if SU_HAS_PERL(5, 10, 0)
790 SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is block\n", ud, i));
791 /* Given and when blocks are actually followed by a simple block, so skip
793 if (cxix > 0) { /* Implies i > 0 */
794 PERL_CONTEXT *next = cx - 1;
795 if (CxTYPE(next) == CXt_GIVEN || CxTYPE(next) == CXt_WHEN)
801 #if SU_HAS_PERL(5, 11, 0)
804 case CXt_LOOP_LAZYSV:
805 case CXt_LOOP_LAZYIV:
809 SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is loop\n", ud, i));
813 SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is other\n", ud, i));
818 SU_D(PerlIO_printf(Perl_debug_log, "%p: going down to depth %d\n", ud, depth));
820 Newx(origin, depth + 1, I32);
821 origin[0] = PL_scopestack[PL_scopestack_ix - depth];
822 PL_scopestack[PL_scopestack_ix - depth] += size;
823 for (i = depth - 1; i >= 1; --i) {
824 I32 j = PL_scopestack_ix - i;
825 origin[depth - i] = PL_scopestack[j];
826 PL_scopestack[j] += offset;
828 origin[depth] = PL_savestack_ix;
830 SU_UD_ORIGIN(ud) = origin;
831 SU_UD_DEPTH(ud) = depth;
834 /* Make sure the first destructor fires by pushing enough fake slots on the
836 if (PL_savestack_ix + SU_SAVE_DESTRUCTOR_SIZE
837 <= PL_scopestack[PL_scopestack_ix - 1]) {
840 SU_D(PerlIO_printf(Perl_debug_log,
841 "%p: push a fake slot at scope_ix=%2d save_ix=%2d\n",
842 ud, PL_scopestack_ix, PL_savestack_ix));
843 SU_SAVE_PLACEHOLDER();
844 } while (PL_savestack_ix + SU_SAVE_DESTRUCTOR_SIZE
845 <= PL_scopestack[PL_scopestack_ix - 1]);
847 SU_D(PerlIO_printf(Perl_debug_log,
848 "%p: push first destructor at scope_ix=%2d save_ix=%2d\n",
849 ud, PL_scopestack_ix, PL_savestack_ix));
850 SAVEDESTRUCTOR_X(su_pop, ud);
853 for (i = 0; i <= depth; ++i) {
854 I32 j = PL_scopestack_ix - i;
855 PerlIO_printf(Perl_debug_log,
856 "%p: depth=%2d scope_ix=%2d saved_floor=%2d new_floor=%2d\n",
857 ud, i, j, origin[depth - i],
858 i == 0 ? PL_savestack_ix : PL_scopestack[j]);
865 /* --- Unwind stack -------------------------------------------------------- */
867 STATIC void su_unwind(pTHX_ void *ud_) {
869 I32 cxix = MY_CXT.unwind_storage.cxix;
870 I32 items = MY_CXT.unwind_storage.items - 1;
871 SV **savesp = MY_CXT.unwind_storage.savesp;
874 PERL_UNUSED_VAR(ud_);
877 PL_stack_sp = savesp;
879 if (cxstack_ix > cxix)
886 mark = PL_markstack[cxstack[cxix].blk_oldmarksp];
887 *PL_markstack_ptr = PL_stack_sp - PL_stack_base - items;
891 PerlIO_printf(Perl_debug_log,
892 "%p: cx=%d gimme=%s items=%d sp=%d oldmark=%d mark=%d\n",
894 gimme == G_VOID ? "void" : gimme == G_ARRAY ? "list" : "scalar",
895 items, PL_stack_sp - PL_stack_base, *PL_markstack_ptr, mark);
898 PL_op = (OP *) &(MY_CXT.unwind_storage.return_op);
899 PL_op = PL_op->op_ppaddr(aTHX);
901 *PL_markstack_ptr = mark;
903 MY_CXT.unwind_storage.proxy_op.op_next = PL_op;
904 PL_op = &(MY_CXT.unwind_storage.proxy_op);
907 /* --- Uplevel ------------------------------------------------------------- */
909 #ifndef OP_GIMME_REVERSE
910 STATIC U8 su_op_gimme_reverse(U8 gimme) {
913 return OPf_WANT_VOID;
915 return OPf_WANT_LIST;
920 return OPf_WANT_SCALAR;
922 #define OP_GIMME_REVERSE(G) su_op_gimme_reverse(G)
925 #define SU_UPLEVEL_SAVE(f, t) STMT_START { sud->old_##f = PL_##f; PL_##f = (t); } STMT_END
926 #define SU_UPLEVEL_RESTORE(f) STMT_START { PL_##f = sud->old_##f; } STMT_END
928 STATIC su_uplevel_ud *su_uplevel_storage_new(pTHX) {
929 #define su_uplevel_storage_new() su_uplevel_storage_new(aTHX)
933 sud = MY_CXT.uplevel_storage.root;
935 MY_CXT.uplevel_storage.root = sud->next;
936 MY_CXT.uplevel_storage.count--;
938 sud = su_uplevel_ud_new();
944 STATIC void su_uplevel_storage_delete(pTHX_ su_uplevel_ud *sud) {
945 #define su_uplevel_storage_delete(S) su_uplevel_storage_delete(aTHX_ (S))
948 if (MY_CXT.uplevel_storage.count >= SU_UPLEVEL_STORAGE_SIZE) {
949 su_uplevel_ud_delete(sud);
951 sud->next = MY_CXT.uplevel_storage.root;
952 MY_CXT.uplevel_storage.root = sud;
953 MY_CXT.uplevel_storage.count++;
957 #define SU_HAS_EXT_MAGIC SU_HAS_PERL(5, 8, 0)
959 #if SU_HAS_EXT_MAGIC && !SU_HAS_PERL(5, 13, 7)
961 STATIC int su_uplevel_restore_free(pTHX_ SV *sv, MAGIC *mg) {
962 su_uplevel_storage_delete((su_uplevel_ud *) mg->mg_ptr);
967 STATIC MGVTBL su_uplevel_restore_vtbl = {
972 su_uplevel_restore_free
975 #endif /* SU_HAS_EXT_MAGIC && !SU_HAS_PERL(5, 13, 7) */
977 STATIC void su_uplevel_restore(pTHX_ void *sus_) {
978 su_uplevel_ud *sud = sus_;
979 PERL_SI *cur = sud->old_curstackinfo;
980 PERL_SI *si = sud->si;
982 /* When we reach this place, POPSUB has already been called (with our fake
983 * argarray). GvAV(PL_defgv) points to the savearray (that is, what @_ was
984 * before uplevel). argarray is either the fake AV we created in su_uplevel()
985 * or some empty replacement POPSUB creates when @_ is reified. In both cases
986 * we have to destroy it before the context stack is swapped back to its
988 SvREFCNT_dec(cxstack[sud->cxix].blk_sub.argarray);
990 CATCH_SET(sud->old_catch);
992 SvREFCNT_dec(sud->cloned_cv);
994 SU_UPLEVEL_RESTORE(op);
996 /* stack_grow() wants PL_curstack so restore the old stack first */
997 if (PL_curstackinfo == si) {
998 PL_curstack = cur->si_stack;
999 if (sud->old_mainstack)
1000 SU_UPLEVEL_RESTORE(mainstack);
1001 SU_UPLEVEL_RESTORE(curstackinfo);
1004 CV *target_cv = sud->target;
1007 /* When we die, the depth of the target CV is not updated because of the
1008 * stack switcheroo. So we have to look at all the frames between the
1009 * uplevel call and the catch block to count how many call frames to the
1010 * target CV were skipped. */
1011 for (i = cur->si_cxix; i > sud->cxix; i--) {
1012 register const PERL_CONTEXT *cx = cxstack + i;
1014 if (CxTYPE(cx) == CXt_SUB) {
1015 if (cx->blk_sub.cv == target_cv)
1020 /* If we died, the replacement stack was already unwinded to the first
1021 * eval frame, and all the contexts down there were popped. We don't have
1022 * to pop manually any context of the original stack, because they must
1023 * have been in the replacement stack as well (since the second was copied
1024 * from the first). Thus we only have to make sure the original stack index
1025 * points to the context just below the first eval scope under the target
1027 for (; i >= 0; i--) {
1028 register const PERL_CONTEXT *cx = cxstack + i;
1030 switch (CxTYPE(cx)) {
1032 if (cx->blk_sub.cv == target_cv)
1044 CvDEPTH(target_cv) = sud->old_depth - levels;
1045 PL_curstackinfo->si_cxix = i - 1;
1047 #if !SU_HAS_PERL(5, 13, 1)
1048 /* Since $@ was maybe localized between the target frame and the uplevel
1049 * call, we forcefully flush the save stack to get rid of it and then
1050 * reset $@ to its proper value. Note that the the call to
1051 * su_uplevel_restore() must happen before the "reset $@" item of the save
1052 * stack is processed, as uplevel was called after the localization.
1053 * Andrew's changes to how $@ was handled, which were mainly integrated
1054 * between perl 5.13.0 and 5.13.1, fixed this. */
1055 if (ERRSV && SvTRUE(ERRSV)) {
1056 register const PERL_CONTEXT *cx = cxstack + i; /* This is the eval scope */
1057 SV *errsv = SvREFCNT_inc(ERRSV);
1058 PL_scopestack_ix = cx->blk_oldscopesp;
1059 leave_scope(PL_scopestack[PL_scopestack_ix]);
1060 sv_setsv(ERRSV, errsv);
1061 SvREFCNT_dec(errsv);
1067 SU_UPLEVEL_RESTORE(curcop);
1069 SvREFCNT_dec(sud->target);
1071 PL_stack_base = AvARRAY(cur->si_stack);
1072 PL_stack_sp = PL_stack_base + AvFILLp(cur->si_stack);
1073 PL_stack_max = PL_stack_base + AvMAX(cur->si_stack);
1075 /* When an exception is thrown from the uplevel'd subroutine,
1076 * su_uplevel_restore() may be called by the LEAVE in die_unwind() (renamed
1077 * die_where() in more recent perls), which has the sad habit of keeping a
1078 * pointer to the current context frame across this call. This means that we
1079 * can't free the temporary context stack we used for the uplevel call right
1080 * now, or that pointer upwards would point to garbage. */
1081 #if SU_HAS_PERL(5, 13, 7)
1082 /* This issue has been fixed in perl with commit 8f89e5a9, which was made
1083 * public in perl 5.13.7. */
1084 su_uplevel_storage_delete(sud);
1085 #elif SU_HAS_EXT_MAGIC
1086 /* If 'ext' magic is available, we work around this by attaching the state
1087 * data to a scalar that will be freed "soon". */
1089 SV *sv = sv_newmortal();
1091 sv_magicext(sv, NULL, PERL_MAGIC_ext, &su_uplevel_restore_vtbl,
1092 (const char *) sud, 0);
1095 /* Otherwise, we just enqueue it back in the global storage list. */
1099 sud->next = MY_CXT.uplevel_storage.root;
1100 MY_CXT.uplevel_storage.root = sud;
1101 MY_CXT.uplevel_storage.count++;
1108 STATIC CV *su_cv_clone(pTHX_ CV *old_cv) {
1109 #define su_cv_clone(C) su_cv_clone(aTHX_ (C))
1112 /* Starting from commit b5c19bd7 (first made public with perl 5.9.0),
1113 * cv_clone() has an assert that checks whether CvDEPTH(CvOUTSIDE(proto)) > 0.
1114 * If this perl has DEBUGGING enabled, we have to fool cv_clone() with a
1116 #if defined(DEBUGGING) && SU_HAS_PERL(5, 9, 0)
1118 CV *outside = CvOUTSIDE(old_cv);
1120 if (outside && CvCLONE(outside) && !CvCLONED(outside))
1121 outside = find_runcv(NULL);
1122 old_depth = CvDEPTH(outside);
1124 CvDEPTH(outside) = 1;
1127 new_cv = cv_clone(old_cv);
1129 #if defined(DEBUGGING) && SU_HAS_PERL(5, 9, 0)
1130 CvDEPTH(outside) = old_depth;
1133 /* Still from commit b5c19bd7, cv_clone() is no longer able to clone named
1134 * subs propery. With this commit, pad_findlex() stores the parent index of a
1135 * fake pad entry in the NV slot of the corresponding pad name SV, but only
1136 * for anonymous subs (since named subs aren't supposed to be cloned in pure
1137 * Perl land). To fix this, we just manually relink the new fake pad entries
1139 * For some reason perl 5.8 crashes too without this, supposedly because of
1140 * other closure bugs. Hence we enable it everywhere. */
1141 if (!CvCLONE(old_cv)) {
1142 const AV *old_padname = (const AV *) AvARRAY(CvPADLIST(old_cv))[0];
1143 AV *old_pad = (AV *) AvARRAY(CvPADLIST(old_cv))[1];
1144 AV *new_pad = (AV *) AvARRAY(CvPADLIST(new_cv))[1];
1145 const SV **old_aryname = (const SV **) AvARRAY(old_padname);
1146 SV **old_ary = AvARRAY(old_pad);
1147 SV **new_ary = AvARRAY(new_pad);
1148 I32 fname = AvFILLp(old_padname);
1149 I32 fpad = AvFILLp(old_pad);
1152 for (ix = fpad; ix > 0; ix--) {
1153 const SV *namesv = (ix <= fname) ? old_aryname[ix] : NULL;
1155 if (namesv && namesv != &PL_sv_undef && SvFAKE(namesv)) {
1156 SvREFCNT_dec(new_ary[ix]);
1157 new_ary[ix] = SvREFCNT_inc(old_ary[ix]);
1165 STATIC I32 su_uplevel(pTHX_ CV *cv, I32 cxix, I32 args) {
1166 #define su_uplevel(C, I, A) su_uplevel(aTHX_ (C), (I), (A))
1168 const PERL_CONTEXT *cx = cxstack + cxix;
1170 PERL_SI *cur = PL_curstackinfo;
1175 I32 old_mark, new_mark;
1182 /* Make PL_stack_sp point just before the CV. */
1183 PL_stack_sp -= args + 1;
1184 old_mark = AvFILLp(PL_curstack) = PL_stack_sp - PL_stack_base;
1187 sud = su_uplevel_storage_new();
1191 SAVEDESTRUCTOR_X(su_uplevel_restore, sud);
1195 si->si_type = cur->si_type;
1197 si->si_prev = cur->si_prev;
1199 si->si_markoff = cx->blk_oldmarksp;
1202 /* Allocate enough space for all the elements of the original stack up to the
1203 * target context, plus the forthcoming arguments. */
1204 new_mark = cx->blk_oldsp;
1205 av_extend(si->si_stack, new_mark + 1 + args + 1);
1206 Copy(PL_curstack, AvARRAY(si->si_stack), new_mark + 1, SV *);
1207 AvFILLp(si->si_stack) = new_mark;
1208 SU_POISON(AvARRAY(si->si_stack) + new_mark + 1, args + 1, SV *);
1210 /* Specialized SWITCHSTACK() */
1211 PL_stack_base = AvARRAY(si->si_stack);
1212 old_stack_sp = PL_stack_sp;
1213 PL_stack_sp = PL_stack_base + AvFILLp(si->si_stack);
1214 PL_stack_max = PL_stack_base + AvMAX(si->si_stack);
1217 /* Copy the context stack up to the context just below the target. */
1218 si->si_cxix = (cxix < 0) ? -1 : (cxix - 1);
1219 if (si->si_cxmax < cxix) {
1220 /* The max size must be at least two so that GROW(max) = (max*3)/2 > max */
1221 si->si_cxmax = (cxix < 4) ? 4 : cxix;
1222 Renew(si->si_cxstack, si->si_cxmax + 1, PERL_CONTEXT);
1224 Copy(cur->si_cxstack, si->si_cxstack, cxix, PERL_CONTEXT);
1225 SU_POISON(si->si_cxstack + cxix, si->si_cxmax + 1 - cxix, PERL_CONTEXT);
1227 target_cv = cx->blk_sub.cv;
1228 sud->target = (CV *) SvREFCNT_inc(target_cv);
1229 sud->old_depth = CvDEPTH(target_cv);
1231 /* blk_oldcop is essentially needed for caller() and stack traces. It has no
1232 * run-time implication, since PL_curcop will be overwritten as soon as we
1233 * enter a sub (a sub starts by a nextstate/dbstate). Hence it's safe to just
1234 * make it point to the blk_oldcop for the target frame, so that caller()
1235 * reports the right file name, line number and lexical hints. */
1236 SU_UPLEVEL_SAVE(curcop, cx->blk_oldcop);
1237 /* Don't reset PL_markstack_ptr, or we would overwrite the mark stack below
1238 * this point. Don't reset PL_curpm either, we want the most recent matches. */
1240 SU_UPLEVEL_SAVE(curstackinfo, si);
1241 /* If those two are equal, we need to fool POPSTACK_TO() */
1242 if (PL_mainstack == PL_curstack)
1243 SU_UPLEVEL_SAVE(mainstack, si->si_stack);
1245 sud->old_mainstack = NULL;
1246 PL_curstack = si->si_stack;
1248 cv = su_cv_clone(cv);
1249 sud->cloned_cv = cv;
1250 CvGV_set(cv, CvGV(target_cv));
1253 /* Both SP and old_stack_sp point just before the CV. */
1254 Copy(old_stack_sp + 2, SP + 1, args, SV *);
1259 Zero(&sub_op, 1, UNOP);
1260 sub_op.op_type = OP_ENTERSUB;
1261 sub_op.op_next = NULL;
1262 sub_op.op_flags = OP_GIMME_REVERSE(gimme) | OPf_STACKED;
1264 sub_op.op_flags |= OPpENTERSUB_DB;
1266 SU_UPLEVEL_SAVE(op, (OP *) &sub_op);
1268 sud->old_catch = CATCH_GET;
1271 if ((PL_op = PL_ppaddr[OP_ENTERSUB](aTHX))) {
1272 if (CxHASARGS(cx) && cx->blk_sub.argarray) {
1273 /* The call to pp_entersub() has saved the current @_ (in XS terms,
1274 * GvAV(PL_defgv)) in the savearray member, and has created a new argarray
1275 * with what we put on the stack. But we want to fake up the same arguments
1276 * as the ones in use at the context we uplevel to, so we replace the
1277 * argarray with an unreal copy of the original @_. */
1280 av_extend(av, AvMAX(cx->blk_sub.argarray));
1281 AvFILLp(av) = AvFILLp(cx->blk_sub.argarray);
1282 Copy(AvARRAY(cx->blk_sub.argarray), AvARRAY(av), AvFILLp(av) + 1, SV *);
1283 cxstack[cxix].blk_sub.argarray = av;
1285 SvREFCNT_inc_simple_void(cxstack[cxix].blk_sub.argarray);
1290 ret = PL_stack_sp - (PL_stack_base + new_mark);
1298 AV *old_stack = sud->old_curstackinfo->si_stack;
1300 if (old_mark + ret > AvMAX(old_stack)) {
1301 /* Specialized EXTEND(old_sp, ret) */
1302 av_extend(old_stack, old_mark + ret + 1);
1303 old_stack_sp = AvARRAY(old_stack) + old_mark;
1306 Copy(PL_stack_sp - ret + 1, old_stack_sp + 1, ret, SV *);
1308 AvFILLp(old_stack) += ret;
1318 /* --- Interpreter setup/teardown ------------------------------------------ */
1320 STATIC void su_teardown(pTHX_ void *param) {
1324 cur = MY_CXT.uplevel_storage.root;
1326 su_uplevel_ud *prev;
1330 su_uplevel_ud_delete(prev);
1337 STATIC void su_setup(pTHX) {
1338 #define su_setup() su_setup(aTHX)
1341 MY_CXT.stack_placeholder = NULL;
1343 /* NewOp() calls calloc() which just zeroes the memory with memset(). */
1344 Zero(&(MY_CXT.unwind_storage.return_op), 1, LISTOP);
1345 MY_CXT.unwind_storage.return_op.op_type = OP_RETURN;
1346 MY_CXT.unwind_storage.return_op.op_ppaddr = PL_ppaddr[OP_RETURN];
1348 Zero(&(MY_CXT.unwind_storage.proxy_op), 1, OP);
1349 MY_CXT.unwind_storage.proxy_op.op_type = OP_STUB;
1350 MY_CXT.unwind_storage.proxy_op.op_ppaddr = NULL;
1352 MY_CXT.uplevel_storage.root = NULL;
1353 MY_CXT.uplevel_storage.count = 0;
1355 call_atexit(su_teardown, NULL);
1360 /* --- XS ------------------------------------------------------------------ */
1362 #if SU_HAS_PERL(5, 8, 9)
1363 # define SU_SKIP_DB_MAX 2
1365 # define SU_SKIP_DB_MAX 3
1368 /* Skip context sequences of 1 to SU_SKIP_DB_MAX (included) block contexts
1369 * followed by a DB sub */
1371 #define SU_SKIP_DB(C) \
1374 PERL_CONTEXT *base = cxstack; \
1375 PERL_CONTEXT *cx = base + (C); \
1376 while (cx >= base && (C) > skipped && CxTYPE(cx) == CXt_BLOCK) \
1378 if (cx >= base && (C) > skipped) { \
1379 switch (CxTYPE(cx)) { \
1381 if (skipped <= SU_SKIP_DB_MAX && cx->blk_sub.cv == GvCV(PL_DBsub)) \
1382 (C) -= skipped + 1; \
1390 #define SU_GET_CONTEXT(A, B) \
1399 else if (cxix > cxstack_ix) \
1400 cxix = cxstack_ix; \
1403 cxix = cxstack_ix; \
1409 #define SU_GET_LEVEL(A, B) \
1415 level = SvIV(lsv); \
1422 XS(XS_Scope__Upper_unwind); /* prototype to pass -Wmissing-prototypes */
1424 XS(XS_Scope__Upper_unwind) {
1433 PERL_UNUSED_VAR(cv); /* -W */
1434 PERL_UNUSED_VAR(ax); /* -Wall */
1436 SU_GET_CONTEXT(0, items - 1);
1438 PERL_CONTEXT *cx = cxstack + cxix;
1439 switch (CxTYPE(cx)) {
1441 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
1445 MY_CXT.unwind_storage.cxix = cxix;
1446 MY_CXT.unwind_storage.items = items;
1447 /* pp_entersub will want to sanitize the stack after returning from there
1448 * Screw that, we're insane */
1449 if (GIMME_V == G_SCALAR) {
1450 MY_CXT.unwind_storage.savesp = PL_stack_sp;
1451 /* dXSARGS calls POPMARK, so we need to match PL_markstack_ptr[1] */
1452 PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
1454 MY_CXT.unwind_storage.savesp = NULL;
1456 SAVEDESTRUCTOR_X(su_unwind, NULL);
1461 } while (--cxix >= 0);
1462 croak("Can't return outside a subroutine");
1465 MODULE = Scope::Upper PACKAGE = Scope::Upper
1473 stash = gv_stashpv(__PACKAGE__, 1);
1474 newCONSTSUB(stash, "TOP", newSViv(0));
1475 newCONSTSUB(stash, "SU_THREADSAFE", newSVuv(SU_THREADSAFE));
1477 newXSproto("Scope::Upper::unwind", XS_Scope__Upper_unwind, file, NULL);
1490 MY_CXT.uplevel_storage.root = NULL;
1491 MY_CXT.uplevel_storage.count = 0;
1495 #endif /* SU_THREADSAFE */
1501 I32 cxix = cxstack_ix;
1515 SU_GET_CONTEXT(0, 0);
1530 SU_GET_CONTEXT(0, 0);
1532 for (; cxix >= 0; --cxix) {
1533 PERL_CONTEXT *cx = cxstack + cxix;
1534 switch (CxTYPE(cx)) {
1538 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
1552 SU_GET_CONTEXT(0, 0);
1554 for (; cxix >= 0; --cxix) {
1555 PERL_CONTEXT *cx = cxstack + cxix;
1556 switch (CxTYPE(cx)) {
1598 for (cxix = cxstack_ix; cxix > 0; --cxix) {
1599 PERL_CONTEXT *cx = cxstack + cxix;
1600 switch (CxTYPE(cx)) {
1602 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
1622 SU_GET_CONTEXT(0, 0);
1625 PERL_CONTEXT *cx = cxstack + cxix--;
1626 switch (CxTYPE(cx)) {
1630 I32 gimme = cx->blk_gimme;
1632 case G_VOID: XSRETURN_UNDEF; break;
1633 case G_SCALAR: XSRETURN_NO; break;
1634 case G_ARRAY: XSRETURN_YES; break;
1649 SU_GET_CONTEXT(1, 1);
1650 Newx(ud, 1, su_ud_reap);
1651 SU_UD_ORIGIN(ud) = NULL;
1652 SU_UD_HANDLER(ud) = su_reap;
1653 ud->cb = newSVsv(hook);
1654 su_init(ud, cxix, SU_SAVE_DESTRUCTOR_SIZE);
1657 localize(SV *sv, SV *val, ...)
1664 SU_GET_CONTEXT(2, 2);
1665 Newx(ud, 1, su_ud_localize);
1666 SU_UD_ORIGIN(ud) = NULL;
1667 SU_UD_HANDLER(ud) = su_localize;
1668 size = su_ud_localize_init(ud, sv, val, NULL);
1669 su_init(ud, cxix, size);
1672 localize_elem(SV *sv, SV *elem, SV *val, ...)
1679 if (SvTYPE(sv) >= SVt_PVGV)
1680 croak("Can't infer the element localization type from a glob and the value");
1681 SU_GET_CONTEXT(3, 3);
1682 Newx(ud, 1, su_ud_localize);
1683 SU_UD_ORIGIN(ud) = NULL;
1684 SU_UD_HANDLER(ud) = su_localize;
1685 size = su_ud_localize_init(ud, sv, val, elem);
1686 if (ud->type != SVt_PVAV && ud->type != SVt_PVHV) {
1687 SU_UD_LOCALIZE_FREE(ud);
1688 croak("Can't localize an element of something that isn't an array or a hash");
1690 su_init(ud, cxix, size);
1693 localize_delete(SV *sv, SV *elem, ...)
1700 SU_GET_CONTEXT(2, 2);
1701 Newx(ud, 1, su_ud_localize);
1702 SU_UD_ORIGIN(ud) = NULL;
1703 SU_UD_HANDLER(ud) = su_localize;
1704 size = su_ud_localize_init(ud, sv, NULL, elem);
1705 su_init(ud, cxix, size);
1708 uplevel(SV *code, ...)
1711 I32 cxix, ret, args = 0;
1715 if (SvTYPE(code) < SVt_PVCV)
1716 croak("First argument to uplevel must be a code reference");
1717 SU_GET_CONTEXT(1, items - 1);
1719 PERL_CONTEXT *cx = cxstack + cxix;
1720 switch (CxTYPE(cx)) {
1722 croak("Can't uplevel to an eval frame");
1724 croak("Can't uplevel to a format frame");
1726 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
1732 /* su_uplevel() takes care of extending the stack if needed. */
1733 ret = su_uplevel((CV *) code, cxix, args);
1738 } while (--cxix >= 0);
1739 croak("Can't uplevel outside a subroutine");