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) SvREFCNT_inc(sv)
71 # define GvCV_set(G, C) (GvCV(G) = (C))
75 # define CvGV_set(C, G) (CvGV(C) = (G))
79 # define CxHASARGS(C) ((C)->blk_sub.hasargs)
83 # define HvNAME_get(H) HvNAME(H)
86 #ifndef gv_fetchpvn_flags
87 # define gv_fetchpvn_flags(A, B, C, D) gv_fetchpv((A), (C), (D))
91 # define cv_clone(P) Perl_cv_clone(aTHX_ (P))
94 #ifndef PERL_MAGIC_tied
95 # define PERL_MAGIC_tied 'P'
98 #ifndef PERL_MAGIC_env
99 # define PERL_MAGIC_env 'E'
102 #ifndef NEGATIVE_INDICES_VAR
103 # define NEGATIVE_INDICES_VAR "NEGATIVE_INDICES"
106 #define SU_HAS_PERL(R, V, S) (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S))))))
107 #define SU_HAS_PERL_EXACT(R, V, S) ((PERL_REVISION == (R)) && (PERL_VERSION == (V)) && (PERL_SUBVERSION == (S)))
109 /* --- Threads and multiplicity -------------------------------------------- */
111 #ifndef SU_MULTIPLICITY
112 # if defined(MULTIPLICITY) || defined(PERL_IMPLICIT_CONTEXT)
113 # define SU_MULTIPLICITY 1
115 # define SU_MULTIPLICITY 0
118 #if SU_MULTIPLICITY && !defined(tTHX)
119 # define tTHX PerlInterpreter*
122 #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))
123 # define SU_THREADSAFE 1
124 # ifndef MY_CXT_CLONE
125 # define MY_CXT_CLONE \
127 my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1)); \
128 Copy(INT2PTR(my_cxt_t*, SvUV(my_cxt_sv)), my_cxtp, 1, my_cxt_t); \
129 sv_setuv(my_cxt_sv, PTR2UV(my_cxtp))
132 # define SU_THREADSAFE 0
134 # define dMY_CXT dNOOP
136 # define MY_CXT su_globaldata
138 # define START_MY_CXT STATIC my_cxt_t MY_CXT;
140 # define MY_CXT_INIT NOOP
142 # define MY_CXT_CLONE NOOP
145 /* --- uplevel() data tokens ----------------------------------------------- */
155 PERL_SI *old_curstackinfo;
166 STATIC su_uplevel_ud *su_uplevel_ud_new(pTHX) {
167 #define su_uplevel_ud_new() su_uplevel_ud_new(aTHX)
171 Newx(sud, 1, su_uplevel_ud);
174 Newx(si, 1, PERL_SI);
175 si->si_stack = newAV();
176 AvREAL_off(si->si_stack);
177 si->si_cxstack = NULL;
185 STATIC void su_uplevel_ud_delete(pTHX_ su_uplevel_ud *sud) {
186 #define su_uplevel_ud_delete(S) su_uplevel_ud_delete(aTHX_ (S))
187 PERL_SI *si = sud->si;
189 Safefree(si->si_cxstack);
190 SvREFCNT_dec(si->si_stack);
200 } su_uplevel_storage;
202 #ifndef SU_UPLEVEL_STORAGE_SIZE
203 # define SU_UPLEVEL_STORAGE_SIZE 4
206 /* --- Global data --------------------------------------------------------- */
208 #define MY_CXT_KEY __PACKAGE__ "::_guts" XS_VERSION
211 char *stack_placeholder;
219 su_uplevel_storage uplevel_storage;
224 /* --- Stack manipulations ------------------------------------------------- */
226 #define SU_SAVE_PLACEHOLDER() save_pptr(&MY_CXT.stack_placeholder)
228 #define SU_SAVE_DESTRUCTOR_SIZE 3
229 #define SU_SAVE_PLACEHOLDER_SIZE 3
231 #define SU_SAVE_SCALAR_SIZE 3
233 #define SU_SAVE_ARY_SIZE 3
234 #define SU_SAVE_AELEM_SIZE 4
236 # define SU_SAVE_ADELETE_SIZE 3
238 # define SU_SAVE_ADELETE_SIZE SU_SAVE_DESTRUCTOR_SIZE
240 #if SU_SAVE_AELEM_SIZE < SU_SAVE_ADELETE_SIZE
241 # define SU_SAVE_AELEM_OR_ADELETE_SIZE SU_SAVE_ADELETE_SIZE
243 # define SU_SAVE_AELEM_OR_ADELETE_SIZE SU_SAVE_AELEM_SIZE
246 #define SU_SAVE_HASH_SIZE 3
247 #define SU_SAVE_HELEM_SIZE 4
248 #define SU_SAVE_HDELETE_SIZE 4
249 #if SU_SAVE_HELEM_SIZE < SU_SAVE_HDELETE_SIZE
250 # define SU_SAVE_HELEM_OR_HDELETE_SIZE SU_SAVE_HDELETE_SIZE
252 # define SU_SAVE_HELEM_OR_HDELETE_SIZE SU_SAVE_HELEM_SIZE
255 #define SU_SAVE_GVCV_SIZE SU_SAVE_DESTRUCTOR_SIZE
257 #if !SU_HAS_PERL(5, 8, 9)
258 # define SU_SAVE_GP_SIZE 6
259 #elif !SU_HAS_PERL(5, 13, 0) || (SU_RELEASE && SU_HAS_PERL_EXACT(5, 13, 0))
260 # define SU_SAVE_GP_SIZE 3
261 #elif !SU_HAS_PERL(5, 13, 8)
262 # define SU_SAVE_GP_SIZE 4
264 # define SU_SAVE_GP_SIZE 3
267 #ifndef SvCANEXISTDELETE
268 # define SvCANEXISTDELETE(sv) \
270 || ((mg = mg_find((SV *) sv, PERL_MAGIC_tied)) \
271 && (stash = SvSTASH(SvRV(SvTIED_obj((SV *) sv, mg)))) \
272 && gv_fetchmethod_autoload(stash, "EXISTS", TRUE) \
273 && gv_fetchmethod_autoload(stash, "DELETE", TRUE) \
278 /* ... Saving array elements ............................................... */
280 STATIC I32 su_av_key2idx(pTHX_ AV *av, I32 key) {
281 #define su_av_key2idx(A, K) su_av_key2idx(aTHX_ (A), (K))
287 /* Added by MJD in perl-5.8.1 with 6f12eb6d2a1dfaf441504d869b27d2e40ef4966a */
288 #if SU_HAS_PERL(5, 8, 1)
289 if (SvRMAGICAL(av)) {
290 const MAGIC * const tied_magic = mg_find((SV *) av, PERL_MAGIC_tied);
292 SV * const * const negative_indices_glob =
293 hv_fetch(SvSTASH(SvRV(SvTIED_obj((SV *) (av), tied_magic))),
294 NEGATIVE_INDICES_VAR, 16, 0);
295 if (negative_indices_glob && SvTRUE(GvSV(*negative_indices_glob)))
301 idx = key + av_len(av) + 1;
315 STATIC void su_adelete(pTHX_ void *ud_) {
316 su_ud_adelete *ud = (su_ud_adelete *) ud_;
318 av_delete(ud->av, ud->idx, G_DISCARD);
319 SvREFCNT_dec(ud->av);
324 STATIC void su_save_adelete(pTHX_ AV *av, I32 idx) {
325 #define su_save_adelete(A, K) su_save_adelete(aTHX_ (A), (K))
328 Newx(ud, 1, su_ud_adelete);
331 SvREFCNT_inc_simple_void(av);
333 SAVEDESTRUCTOR_X(su_adelete, ud);
336 #define SAVEADELETE(A, K) su_save_adelete((A), (K))
338 #endif /* SAVEADELETE */
340 STATIC void su_save_aelem(pTHX_ AV *av, SV *key, SV *val) {
341 #define su_save_aelem(A, K, V) su_save_aelem(aTHX_ (A), (K), (V))
348 idx = su_av_key2idx(av, SvIV(key));
350 if (SvCANEXISTDELETE(av))
351 preeminent = av_exists(av, idx);
353 svp = av_fetch(av, idx, 1);
354 if (!svp || *svp == &PL_sv_undef) croak(PL_no_aelem, idx);
357 save_aelem(av, idx, svp);
359 SAVEADELETE(av, idx);
361 if (val) { /* local $x[$idx] = $val; */
362 SvSetMagicSV(*svp, val);
363 } else { /* local $x[$idx]; delete $x[$idx]; */
364 av_delete(av, idx, G_DISCARD);
368 /* ... Saving hash elements ................................................ */
370 STATIC void su_save_helem(pTHX_ HV *hv, SV *keysv, SV *val) {
371 #define su_save_helem(H, K, V) su_save_helem(aTHX_ (H), (K), (V))
378 if (SvCANEXISTDELETE(hv) || mg_find((SV *) hv, PERL_MAGIC_env))
379 preeminent = hv_exists_ent(hv, keysv, 0);
381 he = hv_fetch_ent(hv, keysv, 1, 0);
382 svp = he ? &HeVAL(he) : NULL;
383 if (!svp || *svp == &PL_sv_undef) croak("Modification of non-creatable hash value attempted, subscript \"%s\"", SvPV_nolen_const(*svp));
385 if (HvNAME_get(hv) && isGV(*svp)) {
386 save_gp((GV *) *svp, 0);
391 save_helem(hv, keysv, svp);
394 const char * const key = SvPV_const(keysv, keylen);
395 SAVEDELETE(hv, savepvn(key, keylen),
396 SvUTF8(keysv) ? -(I32)keylen : (I32)keylen);
399 if (val) { /* local $x{$keysv} = $val; */
400 SvSetMagicSV(*svp, val);
401 } else { /* local $x{$keysv}; delete $x{$keysv}; */
402 (void)hv_delete_ent(hv, keysv, G_DISCARD, HeHASH(he));
406 /* ... Saving code slots from a glob ....................................... */
408 #if !SU_HAS_PERL(5, 10, 0) && !defined(mro_method_changed_in)
409 # define mro_method_changed_in(G) PL_sub_generation++
417 STATIC void su_restore_gvcv(pTHX_ void *ud_) {
418 su_save_gvcv_ud *ud = ud_;
421 GvCV_set(gv, ud->old_cv);
423 mro_method_changed_in(GvSTASH(gv));
428 STATIC void su_save_gvcv(pTHX_ GV *gv) {
429 #define su_save_gvcv(G) su_save_gvcv(aTHX_ (G))
432 Newx(ud, 1, su_save_gvcv_ud);
434 ud->old_cv = GvCV(gv);
438 mro_method_changed_in(GvSTASH(gv));
440 SAVEDESTRUCTOR_X(su_restore_gvcv, ud);
443 /* --- Actions ------------------------------------------------------------- */
449 void (*handler)(pTHX_ void *);
452 #define SU_UD_DEPTH(U) (((su_ud_common *) (U))->depth)
453 #define SU_UD_PAD(U) (((su_ud_common *) (U))->pad)
454 #define SU_UD_ORIGIN(U) (((su_ud_common *) (U))->origin)
455 #define SU_UD_HANDLER(U) (((su_ud_common *) (U))->handler)
457 #define SU_UD_FREE(U) STMT_START { \
458 if (SU_UD_ORIGIN(U)) Safefree(SU_UD_ORIGIN(U)); \
462 /* ... Reap ................................................................ */
469 STATIC void su_call(pTHX_ void *ud_) {
470 su_ud_reap *ud = (su_ud_reap *) ud_;
471 #if SU_HAS_PERL(5, 9, 5)
472 PERL_CONTEXT saved_cx;
479 PerlIO_printf(Perl_debug_log,
480 "%p: @@@ call\n%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
481 ud, ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
490 /* If the recently popped context isn't saved there, it will be overwritten by
491 * the sub scope from call_sv, although it's still needed in our caller. */
493 #if SU_HAS_PERL(5, 9, 5)
494 if (cxstack_ix < cxstack_max)
495 cxix = cxstack_ix + 1;
497 cxix = Perl_cxinc(aTHX);
498 saved_cx = cxstack[cxix];
501 call_sv(ud->cb, G_VOID);
503 #if SU_HAS_PERL(5, 9, 5)
504 cxstack[cxix] = saved_cx;
512 SvREFCNT_dec(ud->cb);
516 STATIC void su_reap(pTHX_ void *ud) {
517 #define su_reap(U) su_reap(aTHX_ (U))
519 PerlIO_printf(Perl_debug_log,
520 "%p: === reap\n%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
521 ud, ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
524 SAVEDESTRUCTOR_X(su_call, ud);
527 /* ... Localize & localize array/hash element .............................. */
537 #define SU_UD_LOCALIZE_FREE(U) STMT_START { \
538 SvREFCNT_dec((U)->elem); \
539 SvREFCNT_dec((U)->val); \
540 SvREFCNT_dec((U)->sv); \
544 STATIC I32 su_ud_localize_init(pTHX_ su_ud_localize *ud, SV *sv, SV *val, SV *elem) {
545 #define su_ud_localize_init(UD, S, V, E) su_ud_localize_init(aTHX_ (UD), (S), (V), (E))
550 SvREFCNT_inc_simple_void(sv);
552 if (SvTYPE(sv) >= SVt_PVGV) {
553 if (!val || !SvROK(val)) { /* local *x; or local *x = $val; */
555 } else { /* local *x = \$val; */
556 t = SvTYPE(SvRV(val));
559 } else if (SvROK(sv)) {
560 croak("Invalid %s reference as the localization target",
561 sv_reftype(SvRV(sv), 0));
564 const char *p = SvPV_const(sv, len), *s;
565 for (s = p, l = len; l > 0 && isSPACE(*s); ++s, --l) { }
571 case '$': t = SVt_PV; break;
572 case '@': t = SVt_PVAV; break;
573 case '%': t = SVt_PVHV; break;
574 case '&': t = SVt_PVCV; break;
575 case '*': t = SVt_PVGV; break;
580 } else if (val) { /* t == SVt_NULL, type can't be inferred from the sigil */
581 if (SvROK(val) && !sv_isobject(val)) {
582 t = SvTYPE(SvRV(val));
594 size = elem ? SU_SAVE_AELEM_OR_ADELETE_SIZE
599 size = elem ? SU_SAVE_HELEM_OR_HDELETE_SIZE
604 size = SU_SAVE_GP_SIZE;
608 size = SU_SAVE_GVCV_SIZE;
612 size = SU_SAVE_SCALAR_SIZE;
615 /* When deref is set, val isn't NULL */
618 ud->val = val ? newSVsv(deref ? SvRV(val) : val) : NULL;
619 ud->elem = SvREFCNT_inc(elem);
625 STATIC void su_localize(pTHX_ void *ud_) {
626 #define su_localize(U) su_localize(aTHX_ (U))
627 su_ud_localize *ud = (su_ud_localize *) ud_;
634 if (SvTYPE(sv) >= SVt_PVGV) {
638 gv = gv_fetchsv(sv, GV_ADDMULTI, t);
641 const char *name = SvPV_const(sv, len);
642 gv = gv_fetchpvn_flags(name, len, GV_ADDMULTI, t);
649 PerlIO_printf(Perl_debug_log, "%p: === localize a %s\n",ud, sv_reftype(z, 0));
650 PerlIO_printf(Perl_debug_log,
651 "%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
652 ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
656 /* Inspired from Alias.pm */
660 su_save_aelem(GvAV(gv), elem, val);
667 su_save_helem(GvHV(gv), elem, val);
673 save_gp(gv, 1); /* hide previous entry in symtab */
679 gv = (GV *) save_scalar(gv);
684 SvSetMagicSV((SV *) gv, val);
687 SU_UD_LOCALIZE_FREE(ud);
690 /* --- Pop a context back -------------------------------------------------- */
694 # define SU_CXNAME PL_block_type[CxTYPE(&cxstack[cxstack_ix])]
696 # define SU_CXNAME "XXX"
700 STATIC void su_pop(pTHX_ void *ud) {
701 #define su_pop(U) su_pop(aTHX_ (U))
702 I32 depth, base, mark, *origin;
703 depth = SU_UD_DEPTH(ud);
706 PerlIO_printf(Perl_debug_log,
708 "%p: leave scope at depth=%2d scope_ix=%2d cur_top=%2d cur_base=%2d\n",
710 ud, depth, PL_scopestack_ix,PL_savestack_ix,PL_scopestack[PL_scopestack_ix])
713 origin = SU_UD_ORIGIN(ud);
714 mark = origin[depth];
715 base = origin[depth - 1];
717 SU_D(PerlIO_printf(Perl_debug_log,
718 "%p: original scope was %*c top=%2d base=%2d\n",
719 ud, 24, ' ', mark, base));
722 SU_D(PerlIO_printf(Perl_debug_log, "%p: clear leftovers\n", ud));
723 PL_savestack_ix = mark;
726 PL_savestack_ix = base;
728 SU_UD_DEPTH(ud) = --depth;
733 if ((pad = SU_UD_PAD(ud))) {
736 SU_D(PerlIO_printf(Perl_debug_log,
737 "%p: push a pad slot at depth=%2d scope_ix=%2d save_ix=%2d\n",
738 ud, depth, PL_scopestack_ix, PL_savestack_ix));
739 SU_SAVE_PLACEHOLDER();
743 SU_D(PerlIO_printf(Perl_debug_log,
744 "%p: push destructor at depth=%2d scope_ix=%2d save_ix=%2d\n",
745 ud, depth, PL_scopestack_ix, PL_savestack_ix));
746 SAVEDESTRUCTOR_X(su_pop, ud);
748 SU_UD_HANDLER(ud)(aTHX_ ud);
751 SU_D(PerlIO_printf(Perl_debug_log,
752 "%p: --- end pop: cur_top=%2d == cur_base=%2d\n",
753 ud, PL_savestack_ix, PL_scopestack[PL_scopestack_ix]));
756 /* --- Initialize the stack and the action userdata ------------------------ */
758 STATIC I32 su_init(pTHX_ void *ud, I32 cxix, I32 size) {
759 #define su_init(U, C, S) su_init(aTHX_ (U), (C), (S))
760 I32 i, depth = 1, pad, offset, *origin;
762 SU_D(PerlIO_printf(Perl_debug_log, "%p: ### init for cx %d\n", ud, cxix));
764 if (size <= SU_SAVE_DESTRUCTOR_SIZE)
767 I32 extra = size - SU_SAVE_DESTRUCTOR_SIZE;
768 pad = extra / SU_SAVE_PLACEHOLDER_SIZE;
769 if (extra % SU_SAVE_PLACEHOLDER_SIZE)
772 offset = SU_SAVE_DESTRUCTOR_SIZE + SU_SAVE_PLACEHOLDER_SIZE * pad;
774 SU_D(PerlIO_printf(Perl_debug_log, "%p: size=%d pad=%d offset=%d\n",
775 ud, size, pad, offset));
777 for (i = cxstack_ix; i > cxix; --i) {
778 PERL_CONTEXT *cx = cxstack + i;
779 switch (CxTYPE(cx)) {
780 #if SU_HAS_PERL(5, 10, 0)
782 SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is block\n", ud, i));
783 /* Given and when blocks are actually followed by a simple block, so skip
785 if (cxix > 0) { /* Implies i > 0 */
786 PERL_CONTEXT *next = cx - 1;
787 if (CxTYPE(next) == CXt_GIVEN || CxTYPE(next) == CXt_WHEN)
793 #if SU_HAS_PERL(5, 11, 0)
796 case CXt_LOOP_LAZYSV:
797 case CXt_LOOP_LAZYIV:
801 SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is loop\n", ud, i));
805 SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is other\n", ud, i));
810 SU_D(PerlIO_printf(Perl_debug_log, "%p: going down to depth %d\n", ud, depth));
812 Newx(origin, depth + 1, I32);
813 origin[0] = PL_scopestack[PL_scopestack_ix - depth];
814 PL_scopestack[PL_scopestack_ix - depth] += size;
815 for (i = depth - 1; i >= 1; --i) {
816 I32 j = PL_scopestack_ix - i;
817 origin[depth - i] = PL_scopestack[j];
818 PL_scopestack[j] += offset;
820 origin[depth] = PL_savestack_ix;
822 SU_UD_ORIGIN(ud) = origin;
823 SU_UD_DEPTH(ud) = depth;
826 /* Make sure the first destructor fires by pushing enough fake slots on the
828 if (PL_savestack_ix + SU_SAVE_DESTRUCTOR_SIZE
829 <= PL_scopestack[PL_scopestack_ix - 1]) {
832 SU_D(PerlIO_printf(Perl_debug_log,
833 "%p: push a fake slot at scope_ix=%2d save_ix=%2d\n",
834 ud, PL_scopestack_ix, PL_savestack_ix));
835 SU_SAVE_PLACEHOLDER();
836 } while (PL_savestack_ix + SU_SAVE_DESTRUCTOR_SIZE
837 <= PL_scopestack[PL_scopestack_ix - 1]);
839 SU_D(PerlIO_printf(Perl_debug_log,
840 "%p: push first destructor at scope_ix=%2d save_ix=%2d\n",
841 ud, PL_scopestack_ix, PL_savestack_ix));
842 SAVEDESTRUCTOR_X(su_pop, ud);
845 for (i = 0; i <= depth; ++i) {
846 I32 j = PL_scopestack_ix - i;
847 PerlIO_printf(Perl_debug_log,
848 "%p: depth=%2d scope_ix=%2d saved_floor=%2d new_floor=%2d\n",
849 ud, i, j, origin[depth - i],
850 i == 0 ? PL_savestack_ix : PL_scopestack[j]);
857 /* --- Unwind stack -------------------------------------------------------- */
859 STATIC void su_unwind(pTHX_ void *ud_) {
861 I32 cxix = MY_CXT.cxix;
862 I32 items = MY_CXT.items - 1;
863 SV **savesp = MY_CXT.savesp;
866 PERL_UNUSED_VAR(ud_);
869 PL_stack_sp = savesp;
871 if (cxstack_ix > cxix)
878 mark = PL_markstack[cxstack[cxix].blk_oldmarksp];
879 *PL_markstack_ptr = PL_stack_sp - PL_stack_base - items;
883 PerlIO_printf(Perl_debug_log,
884 "%p: cx=%d gimme=%s items=%d sp=%d oldmark=%d mark=%d\n",
886 gimme == G_VOID ? "void" : gimme == G_ARRAY ? "list" : "scalar",
887 items, PL_stack_sp - PL_stack_base, *PL_markstack_ptr, mark);
890 PL_op = (OP *) &(MY_CXT.return_op);
891 PL_op = PL_op->op_ppaddr(aTHX);
893 *PL_markstack_ptr = mark;
895 MY_CXT.proxy_op.op_next = PL_op;
896 PL_op = &(MY_CXT.proxy_op);
899 /* --- Uplevel ------------------------------------------------------------- */
901 #ifndef OP_GIMME_REVERSE
902 STATIC U8 su_op_gimme_reverse(U8 gimme) {
905 return OPf_WANT_VOID;
907 return OPf_WANT_LIST;
912 return OPf_WANT_SCALAR;
914 #define OP_GIMME_REVERSE(G) su_op_gimme_reverse(G)
917 #define SU_UPLEVEL_SAVE(f, t) STMT_START { sud->old_##f = PL_##f; PL_##f = (t); } STMT_END
918 #define SU_UPLEVEL_RESTORE(f) STMT_START { PL_##f = sud->old_##f; } STMT_END
920 STATIC su_uplevel_ud *su_uplevel_storage_new(pTHX) {
921 #define su_uplevel_storage_new() su_uplevel_storage_new(aTHX)
925 sud = MY_CXT.uplevel_storage.root;
927 MY_CXT.uplevel_storage.root = sud->next;
928 MY_CXT.uplevel_storage.count--;
930 sud = su_uplevel_ud_new();
936 STATIC void su_uplevel_storage_delete(pTHX_ su_uplevel_ud *sud) {
937 #define su_uplevel_storage_delete(S) su_uplevel_storage_delete(aTHX_ (S))
940 if (MY_CXT.uplevel_storage.count >= SU_UPLEVEL_STORAGE_SIZE) {
941 su_uplevel_ud_delete(sud);
943 sud->next = MY_CXT.uplevel_storage.root;
944 MY_CXT.uplevel_storage.root = sud;
945 MY_CXT.uplevel_storage.count++;
949 #define SU_HAS_EXT_MAGIC SU_HAS_PERL(5, 8, 0)
953 STATIC int su_uplevel_restore_free(pTHX_ SV *sv, MAGIC *mg) {
954 su_uplevel_storage_delete((su_uplevel_ud *) mg->mg_ptr);
959 STATIC MGVTBL su_uplevel_restore_vtbl = {
964 su_uplevel_restore_free
967 #endif /* SU_HAS_EXT_MAGIC */
969 STATIC void su_uplevel_restore(pTHX_ void *sus_) {
970 su_uplevel_ud *sud = sus_;
971 PERL_SI *cur = sud->old_curstackinfo;
972 PERL_SI *si = sud->si;
974 /* When we reach this place, POPSUB has already been called (with our fake
975 * argarray). GvAV(PL_defgv) points to the savearray (that is, what @_ was
976 * before uplevel). argarray is either the fake AV we created in su_uplevel()
977 * or some empty replacement POPSUB creates when @_ is reified. In both cases
978 * we have to destroy it before the context stack is swapped back to its
980 SvREFCNT_dec(cxstack[sud->cxix].blk_sub.argarray);
982 CATCH_SET(sud->old_catch);
984 SvREFCNT_dec(sud->cloned_cv);
986 SU_UPLEVEL_RESTORE(op);
988 /* stack_grow() wants PL_curstack so restore the old stack first */
989 if (PL_curstackinfo == si) {
990 PL_curstack = cur->si_stack;
991 if (sud->old_mainstack)
992 SU_UPLEVEL_RESTORE(mainstack);
993 SU_UPLEVEL_RESTORE(curstackinfo);
996 CV *target_cv = sud->target;
999 /* When we die, the depth of the target CV is not updated because of the
1000 * stack switcheroo. So we have to look at all the frames between the
1001 * uplevel call and the catch block to count how many call frames to the
1002 * target CV were skipped. */
1003 for (i = cur->si_cxix; i > sud->cxix; i--) {
1004 register const PERL_CONTEXT *cx = cxstack + i;
1006 if (CxTYPE(cx) == CXt_SUB) {
1007 if (cx->blk_sub.cv == target_cv)
1012 /* If we died, the replacement stack was already unwinded to the first
1013 * eval frame, and all the contexts down there were popped. We don't have
1014 * to pop manually any context of the original stack, because they must
1015 * have been in the replacement stack as well (since the second was copied
1016 * from the first). Thus we only have to make sure the original stack index
1017 * points to the context just below the first eval scope under the target
1019 for (; i >= 0; i--) {
1020 register const PERL_CONTEXT *cx = cxstack + i;
1022 switch (CxTYPE(cx)) {
1024 if (cx->blk_sub.cv == target_cv)
1036 CvDEPTH(target_cv) = sud->old_depth - levels;
1037 PL_curstackinfo->si_cxix = i - 1;
1039 #if !SU_HAS_PERL(5, 13, 1)
1040 /* Since $@ was maybe localized between the target frame and the uplevel
1041 * call, we forcefully flush the save stack to get rid of it and then
1042 * reset $@ to its proper value. Note that the the call to
1043 * su_uplevel_restore() must happen before the "reset $@" item of the save
1044 * stack is processed, as uplevel was called after the localization.
1045 * Andrew's changes to how $@ was handled, which were mainly integrated
1046 * between perl 5.13.0 and 5.13.1, fixed this. */
1047 if (ERRSV && SvTRUE(ERRSV)) {
1048 register const PERL_CONTEXT *cx = cxstack + i; /* This is the eval scope */
1049 SV *errsv = SvREFCNT_inc(ERRSV);
1050 PL_scopestack_ix = cx->blk_oldscopesp;
1051 leave_scope(PL_scopestack[PL_scopestack_ix]);
1052 sv_setsv(ERRSV, errsv);
1053 SvREFCNT_dec(errsv);
1059 SU_UPLEVEL_RESTORE(curcop);
1061 SvREFCNT_dec(sud->target);
1063 PL_stack_base = AvARRAY(cur->si_stack);
1064 PL_stack_sp = PL_stack_base + AvFILLp(cur->si_stack);
1065 PL_stack_max = PL_stack_base + AvMAX(cur->si_stack);
1067 /* When an exception is thrown from the uplevel'd subroutine,
1068 * su_uplevel_restore() may be called by the LEAVE in die_unwind() (renamed
1069 * die_where() in more recent perls), which has the sad habit of keeping a
1070 * pointer to the current context frame across this call. This means that we
1071 * can't free the temporary context stack we used for the uplevel call right
1072 * now, or that pointer upwards would point to garbage. */
1073 #if SU_HAS_PERL(5, 13, 7)
1074 /* This issue has been fixed in perl with commit 8f89e5a9, which was made
1075 * public in perl 5.13.7. */
1076 su_uplevel_storage_delete(sud);
1077 #elif SU_HAS_EXT_MAGIC
1078 /* If 'ext' magic is available, we work around this by attaching the state
1079 * data to a scalar that will be freed "soon". */
1081 SV *sv = sv_newmortal();
1083 sv_magicext(sv, NULL, PERL_MAGIC_ext, &su_uplevel_restore_vtbl,
1084 (const char *) sud, 0);
1087 /* Otherwise, we just enqueue it back in the global storage list. */
1091 sud->next = MY_CXT.uplevel_storage.root;
1092 MY_CXT.uplevel_storage.root = sud;
1093 MY_CXT.uplevel_storage.count++;
1100 STATIC CV *su_cv_clone(pTHX_ CV *old_cv) {
1101 #define su_cv_clone(C) su_cv_clone(aTHX_ (C))
1104 /* Starting from commit b5c19bd7 (first made public with perl 5.9.0),
1105 * cv_clone() has an assert that checks whether CvDEPTH(CvOUTSIDE(proto)) > 0.
1106 * If this perl has DEBUGGING enabled, we have to fool cv_clone() with a
1108 #if defined(DEBUGGING) && SU_HAS_PERL(5, 9, 0)
1110 CV *outside = CvOUTSIDE(old_cv);
1112 if (outside && CvCLONE(outside) && !CvCLONED(outside))
1113 outside = find_runcv(NULL);
1114 old_depth = CvDEPTH(outside);
1116 CvDEPTH(outside) = 1;
1119 new_cv = cv_clone(old_cv);
1121 #if defined(DEBUGGING) && SU_HAS_PERL(5, 9, 0)
1122 CvDEPTH(outside) = old_depth;
1125 /* Still from commit b5c19bd7, cv_clone() is no longer able to clone named
1126 * subs propery. With this commit, pad_findlex() stores the parent index of a
1127 * fake pad entry in the NV slot of the corresponding pad name SV, but only
1128 * for anonymous subs (since named subs aren't supposed to be cloned in pure
1129 * Perl land). To fix this, we just manually relink the new fake pad entries
1131 * For some reason perl 5.8 crashes too without this, supposedly because of
1132 * other closure bugs. Hence we enable it everywhere. */
1133 if (!CvCLONE(old_cv)) {
1134 const AV *old_padname = (const AV *) AvARRAY(CvPADLIST(old_cv))[0];
1135 AV *old_pad = (AV *) AvARRAY(CvPADLIST(old_cv))[1];
1136 AV *new_pad = (AV *) AvARRAY(CvPADLIST(new_cv))[1];
1137 const SV **old_aryname = (const SV **) AvARRAY(old_padname);
1138 SV **old_ary = AvARRAY(old_pad);
1139 SV **new_ary = AvARRAY(new_pad);
1140 I32 fname = AvFILLp(old_padname);
1141 I32 fpad = AvFILLp(old_pad);
1144 for (ix = fpad; ix > 0; ix--) {
1145 const SV *namesv = (ix <= fname) ? old_aryname[ix] : NULL;
1147 if (namesv && namesv != &PL_sv_undef && SvFAKE(namesv)) {
1148 SvREFCNT_dec(new_ary[ix]);
1149 new_ary[ix] = SvREFCNT_inc(old_ary[ix]);
1157 STATIC I32 su_uplevel(pTHX_ CV *cv, I32 cxix, I32 args) {
1158 #define su_uplevel(C, I, A) su_uplevel(aTHX_ (C), (I), (A))
1160 const PERL_CONTEXT *cx = cxstack + cxix;
1162 PERL_SI *cur = PL_curstackinfo;
1168 I32 old_mark, new_mark;
1175 /* Make PL_stack_sp point just before the CV. */
1176 PL_stack_sp -= args + 1;
1177 old_mark = AvFILLp(PL_curstack) = PL_stack_sp - PL_stack_base;
1180 sud = su_uplevel_storage_new();
1185 SAVEDESTRUCTOR_X(su_uplevel_restore, sud);
1187 si->si_type = cur->si_type;
1189 si->si_prev = cur->si_prev;
1191 /* Allocate enough space for all the elements of the original stack up to the
1192 * target context, plus the forthcoming arguments. */
1193 new_mark = cx->blk_oldsp;
1194 av_extend(si->si_stack, new_mark + 1 + args + 1);
1195 Copy(PL_curstack, AvARRAY(si->si_stack), new_mark + 1, SV *);
1196 AvFILLp(si->si_stack) = new_mark;
1197 SU_POISON(AvARRAY(si->si_stack) + new_mark + 1, args + 1, SV *);
1199 /* Specialized SWITCHSTACK() */
1200 PL_stack_base = AvARRAY(si->si_stack);
1201 old_stack_sp = PL_stack_sp;
1202 PL_stack_sp = PL_stack_base + AvFILLp(si->si_stack);
1203 PL_stack_max = PL_stack_base + AvMAX(si->si_stack);
1207 si->si_markoff = cx->blk_oldmarksp;
1210 /* Copy the context stack up to the context just below the target. */
1211 si->si_cxix = (cxix < 0) ? -1 : (cxix - 1);
1212 if (si->si_cxmax < cxix) {
1213 /* The max size must be at least two so that GROW(max) = (max*3)/2 > max */
1214 si->si_cxmax = (cxix < 4) ? 4 : cxix;
1215 Renew(si->si_cxstack, si->si_cxmax + 1, PERL_CONTEXT);
1217 Copy(cur->si_cxstack, si->si_cxstack, cxix, PERL_CONTEXT);
1218 SU_POISON(si->si_cxstack + cxix, si->si_cxmax + 1 - cxix, PERL_CONTEXT);
1220 target_cv = cx->blk_sub.cv;
1221 sud->target = (CV *) SvREFCNT_inc(target_cv);
1222 sud->old_depth = CvDEPTH(target_cv);
1224 /* blk_oldcop is essentially needed for caller() and stack traces. It has no
1225 * run-time implication, since PL_curcop will be overwritten as soon as we
1226 * enter a sub (a sub starts by a nextstate/dbstate). Hence it's safe to just
1227 * make it point to the blk_oldcop for the target frame, so that caller()
1228 * reports the right file name, line number and lexical hints. */
1229 SU_UPLEVEL_SAVE(curcop, cx->blk_oldcop);
1230 /* Don't reset PL_markstack_ptr, or we would overwrite the mark stack below
1231 * this point. Don't reset PL_curpm either, we want the most recent matches. */
1233 SU_UPLEVEL_SAVE(curstackinfo, si);
1234 /* If those two are equal, we need to fool POPSTACK_TO() */
1235 if (PL_mainstack == PL_curstack)
1236 SU_UPLEVEL_SAVE(mainstack, si->si_stack);
1238 sud->old_mainstack = NULL;
1239 PL_curstack = si->si_stack;
1241 cv = su_cv_clone(cv);
1242 sud->cloned_cv = cv;
1243 CvGV_set(cv, CvGV(target_cv));
1246 /* Both SP and old_stack_sp point just before the CV. */
1247 Copy(old_stack_sp + 2, SP + 1, args, SV *);
1252 Zero(&sub_op, 1, UNOP);
1253 sub_op.op_type = OP_ENTERSUB;
1254 sub_op.op_next = NULL;
1255 sub_op.op_flags = OP_GIMME_REVERSE(gimme) | OPf_STACKED;
1257 sub_op.op_flags |= OPpENTERSUB_DB;
1259 SU_UPLEVEL_SAVE(op, (OP *) &sub_op);
1261 sud->old_catch = CATCH_GET;
1264 if (PL_op = PL_ppaddr[OP_ENTERSUB](aTHX)) {
1265 if (CxHASARGS(cx) && cx->blk_sub.argarray) {
1266 /* The call to pp_entersub() has saved the current @_ (in XS terms,
1267 * GvAV(PL_defgv)) in the savearray member, and has created a new argarray
1268 * with what we put on the stack. But we want to fake up the same arguments
1269 * as the ones in use at the context we uplevel to, so we replace the
1270 * argarray with an unreal copy of the original @_. */
1273 av_extend(av, AvMAX(cx->blk_sub.argarray));
1274 AvFILLp(av) = AvFILLp(cx->blk_sub.argarray);
1275 Copy(AvARRAY(cx->blk_sub.argarray), AvARRAY(av), AvFILLp(av) + 1, SV *);
1276 cxstack[cxix].blk_sub.argarray = av;
1278 SvREFCNT_inc(cxstack[cxix].blk_sub.argarray);
1283 ret = PL_stack_sp - (PL_stack_base + new_mark);
1291 AV *old_stack = sud->old_curstackinfo->si_stack;
1293 if (old_mark + ret > AvMAX(old_stack)) {
1294 /* Specialized EXTEND(old_sp, ret) */
1295 av_extend(old_stack, old_mark + ret + 1);
1296 old_stack_sp = AvARRAY(old_stack) + old_mark;
1299 Copy(PL_stack_sp - ret + 1, old_stack_sp + 1, ret, SV *);
1301 AvFILLp(old_stack) += ret;
1311 /* --- Interpreter setup/teardown ------------------------------------------ */
1313 STATIC void su_teardown(pTHX_ void *param) {
1314 su_uplevel_ud *cur, *prev;
1317 cur = MY_CXT.uplevel_storage.root;
1319 su_uplevel_ud *prev;
1323 su_uplevel_ud_delete(prev);
1330 STATIC void su_setup(pTHX) {
1331 #define su_setup() su_setup(aTHX)
1334 MY_CXT.stack_placeholder = NULL;
1336 /* NewOp() calls calloc() which just zeroes the memory with memset(). */
1337 Zero(&(MY_CXT.return_op), 1, sizeof(MY_CXT.return_op));
1338 MY_CXT.return_op.op_type = OP_RETURN;
1339 MY_CXT.return_op.op_ppaddr = PL_ppaddr[OP_RETURN];
1341 Zero(&(MY_CXT.proxy_op), 1, sizeof(MY_CXT.proxy_op));
1342 MY_CXT.proxy_op.op_type = OP_STUB;
1343 MY_CXT.proxy_op.op_ppaddr = NULL;
1345 MY_CXT.uplevel_storage.root = NULL;
1346 MY_CXT.uplevel_storage.count = 0;
1348 call_atexit(su_teardown, NULL);
1353 /* --- XS ------------------------------------------------------------------ */
1355 #if SU_HAS_PERL(5, 8, 9)
1356 # define SU_SKIP_DB_MAX 2
1358 # define SU_SKIP_DB_MAX 3
1361 /* Skip context sequences of 1 to SU_SKIP_DB_MAX (included) block contexts
1362 * followed by a DB sub */
1364 #define SU_SKIP_DB(C) \
1367 PERL_CONTEXT *base = cxstack; \
1368 PERL_CONTEXT *cx = base + (C); \
1369 while (cx >= base && (C) > skipped && CxTYPE(cx) == CXt_BLOCK) \
1371 if (cx >= base && (C) > skipped) { \
1372 switch (CxTYPE(cx)) { \
1374 if (skipped <= SU_SKIP_DB_MAX && cx->blk_sub.cv == GvCV(PL_DBsub)) \
1375 (C) -= skipped + 1; \
1383 #define SU_GET_CONTEXT(A, B) \
1392 else if (cxix > cxstack_ix) \
1393 cxix = cxstack_ix; \
1396 cxix = cxstack_ix; \
1402 #define SU_GET_LEVEL(A, B) \
1408 level = SvIV(lsv); \
1415 XS(XS_Scope__Upper_unwind); /* prototype to pass -Wmissing-prototypes */
1417 XS(XS_Scope__Upper_unwind) {
1426 PERL_UNUSED_VAR(cv); /* -W */
1427 PERL_UNUSED_VAR(ax); /* -Wall */
1429 SU_GET_CONTEXT(0, items - 1);
1431 PERL_CONTEXT *cx = cxstack + cxix;
1432 switch (CxTYPE(cx)) {
1434 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
1439 MY_CXT.items = items;
1440 /* pp_entersub will want to sanitize the stack after returning from there
1441 * Screw that, we're insane */
1442 if (GIMME_V == G_SCALAR) {
1443 MY_CXT.savesp = PL_stack_sp;
1444 /* dXSARGS calls POPMARK, so we need to match PL_markstack_ptr[1] */
1445 PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
1447 MY_CXT.savesp = NULL;
1449 SAVEDESTRUCTOR_X(su_unwind, NULL);
1454 } while (--cxix >= 0);
1455 croak("Can't return outside a subroutine");
1458 MODULE = Scope::Upper PACKAGE = Scope::Upper
1466 stash = gv_stashpv(__PACKAGE__, 1);
1467 newCONSTSUB(stash, "TOP", newSViv(0));
1468 newCONSTSUB(stash, "SU_THREADSAFE", newSVuv(SU_THREADSAFE));
1470 newXSproto("Scope::Upper::unwind", XS_Scope__Upper_unwind, file, NULL);
1483 MY_CXT.uplevel_storage.root = NULL;
1484 MY_CXT.uplevel_storage.count = 0;
1488 #endif /* SU_THREADSAFE */
1494 I32 cxix = cxstack_ix;
1498 RETVAL = newSViv(cxix);
1508 SU_GET_CONTEXT(0, 0);
1513 RETVAL = newSViv(cxix);
1523 SU_GET_CONTEXT(0, 0);
1524 for (; cxix >= 0; --cxix) {
1525 PERL_CONTEXT *cx = cxstack + cxix;
1526 switch (CxTYPE(cx)) {
1530 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
1532 ST(0) = sv_2mortal(newSViv(cxix));
1544 SU_GET_CONTEXT(0, 0);
1545 for (; cxix >= 0; --cxix) {
1546 PERL_CONTEXT *cx = cxstack + cxix;
1547 switch (CxTYPE(cx)) {
1551 ST(0) = sv_2mortal(newSViv(cxix));
1578 ST(0) = sv_2mortal(newSViv(cxix));
1588 for (cxix = cxstack_ix; cxix > 0; --cxix) {
1589 PERL_CONTEXT *cx = cxstack + cxix;
1590 switch (CxTYPE(cx)) {
1592 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
1602 ST(0) = sv_2mortal(newSViv(cxix));
1611 SU_GET_CONTEXT(0, 0);
1613 PERL_CONTEXT *cx = cxstack + cxix--;
1614 switch (CxTYPE(cx)) {
1618 I32 gimme = cx->blk_gimme;
1620 case G_VOID: XSRETURN_UNDEF; break;
1621 case G_SCALAR: XSRETURN_NO; break;
1622 case G_ARRAY: XSRETURN_YES; break;
1637 SU_GET_CONTEXT(1, 1);
1638 Newx(ud, 1, su_ud_reap);
1639 SU_UD_ORIGIN(ud) = NULL;
1640 SU_UD_HANDLER(ud) = su_reap;
1641 ud->cb = newSVsv(hook);
1642 su_init(ud, cxix, SU_SAVE_DESTRUCTOR_SIZE);
1645 localize(SV *sv, SV *val, ...)
1652 SU_GET_CONTEXT(2, 2);
1653 Newx(ud, 1, su_ud_localize);
1654 SU_UD_ORIGIN(ud) = NULL;
1655 SU_UD_HANDLER(ud) = su_localize;
1656 size = su_ud_localize_init(ud, sv, val, NULL);
1657 su_init(ud, cxix, size);
1660 localize_elem(SV *sv, SV *elem, SV *val, ...)
1667 if (SvTYPE(sv) >= SVt_PVGV)
1668 croak("Can't infer the element localization type from a glob and the value");
1669 SU_GET_CONTEXT(3, 3);
1670 Newx(ud, 1, su_ud_localize);
1671 SU_UD_ORIGIN(ud) = NULL;
1672 SU_UD_HANDLER(ud) = su_localize;
1673 size = su_ud_localize_init(ud, sv, val, elem);
1674 if (ud->type != SVt_PVAV && ud->type != SVt_PVHV) {
1675 SU_UD_LOCALIZE_FREE(ud);
1676 croak("Can't localize an element of something that isn't an array or a hash");
1678 su_init(ud, cxix, size);
1681 localize_delete(SV *sv, SV *elem, ...)
1688 SU_GET_CONTEXT(2, 2);
1689 Newx(ud, 1, su_ud_localize);
1690 SU_UD_ORIGIN(ud) = NULL;
1691 SU_UD_HANDLER(ud) = su_localize;
1692 size = su_ud_localize_init(ud, sv, NULL, elem);
1693 su_init(ud, cxix, size);
1696 uplevel(SV *code, ...)
1699 I32 cxix, ret, args = 0;
1703 if (SvTYPE(code) < SVt_PVCV)
1704 croak("First argument to uplevel must be a code reference");
1705 SU_GET_CONTEXT(1, items - 1);
1707 PERL_CONTEXT *cx = cxstack + cxix;
1708 switch (CxTYPE(cx)) {
1710 croak("Can't uplevel to an eval frame");
1712 croak("Can't uplevel to a format frame");
1714 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
1720 ret = su_uplevel((CV *) code, cxix, args);
1725 } while (--cxix >= 0);
1726 croak("Can't uplevel outside a subroutine");