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 /* --- XS helpers ---------------------------------------------------------- */
11 #define XSH_PACKAGE "Scope::Upper"
15 #include "xsh/debug.h"
17 /* --- Compatibility ------------------------------------------------------- */
19 /* perl 5.23.8 onwards has a revamped context system */
20 #if XSH_HAS_PERL(5, 23, 8)
21 # define SU_HAS_NEW_CXT
30 # define MUTABLE_SV(S) ((SV *) (S))
34 # define MUTABLE_AV(A) ((AV *) (A))
38 # define MUTABLE_CV(C) ((CV *) (C))
41 #ifndef PERL_UNUSED_VAR
42 # define PERL_UNUSED_VAR(V)
46 # define Newx(v, n, c) New(0, v, n, c)
51 # define SU_POISON(D, N, T) PoisonNew((D), (N), T)
52 # elif defined(Poison)
53 # define SU_POISON(D, N, T) Poison((D), (N), T)
57 # define SU_POISON(D, N, T) NOOP
61 static SV *su_newSV_type(pTHX_ svtype t) {
66 # define newSV_type(T) su_newSV_type(aTHX_ (T))
70 # define su_newmortal_pvn(S, L) newSVpvn_flags((S), (L), SVs_TEMP)
72 # define su_newmortal_pvn(S, L) sv_2mortal(newSVpvn((S), (L)))
74 #define su_newmortal_pvs(S) su_newmortal_pvn((S), sizeof(S)-1)
77 # define SvPV_const(S, L) SvPV(S, L)
81 # define SvPVX_const(S) SvPVX(S)
84 #ifndef SvPV_nolen_const
85 # define SvPV_nolen_const(S) SvPV_nolen(S)
88 #ifndef SvREFCNT_inc_simple_void
89 # define SvREFCNT_inc_simple_void(sv) ((void) SvREFCNT_inc(sv))
93 # define mPUSHi(I) PUSHs(sv_2mortal(newSViv(I)))
97 # define GvCV_set(G, C) (GvCV(G) = (C))
101 # define CvGV_set(C, G) (CvGV(C) = (G))
105 # define CvSTASH_set(C, S) (CvSTASH(C) = (S))
109 # define CvISXSUB(C) CvXSUB(C)
113 # define PadlistARRAY(P) AvARRAY(P)
114 # define PadARRAY(P) AvARRAY(P)
118 # define CxHASARGS(C) ((C)->blk_sub.hasargs)
123 # define CxGIMME(C) ((C)->blk_gimme & G_WANT)
125 # define CxGIMME(C) ((C)->blk_gimme)
129 #ifndef CxOLD_OP_TYPE
130 # define CxOLD_OP_TYPE(C) (C)->blk_eval.old_op_type
134 # define OutCopFILE(C) CopFILE(C)
137 #ifndef OutCopFILE_len
138 # define OutCopFILE_len(C) strlen(OutCopFILE(C))
142 # define CopHINTS_get(C) ((I32) (C)->op_private & HINT_PRIVATE_MASK)
145 #ifndef CopHINTHASH_get
146 # define CopHINTHASH_get(C) (C)->cop_hints_hash
150 # define COPHH struct refcounted_he
151 # define cophh_2hv(H, F) Perl_refcounted_he_chain_2hv(aTHX_ (H))
155 # define HvNAME_get(H) HvNAME(H)
159 # define HvNAMELEN(H) strlen(HvNAME(H))
162 #ifndef gv_fetchpvn_flags
163 # define gv_fetchpvn_flags(A, B, C, D) gv_fetchpv((A), (C), (D))
167 # define hv_fetchs(H, K, L) hv_fetch((H), (K), sizeof(K)-1, (L))
170 #ifndef OP_GIMME_REVERSE
171 static U8 su_op_gimme_reverse(U8 gimme) {
174 return OPf_WANT_VOID;
176 return OPf_WANT_LIST;
181 return OPf_WANT_SCALAR;
183 #define OP_GIMME_REVERSE(G) su_op_gimme_reverse(G)
188 # define OpSIBLING(O) OP_SIBLING(O)
190 # define OpSIBLING(O) ((O)->op_sibling)
194 #ifndef PERL_MAGIC_tied
195 # define PERL_MAGIC_tied 'P'
198 #ifndef PERL_MAGIC_env
199 # define PERL_MAGIC_env 'E'
202 #ifndef NEGATIVE_INDICES_VAR
203 # define NEGATIVE_INDICES_VAR "NEGATIVE_INDICES"
206 /* --- Error messages ------------------------------------------------------ */
208 static const char su_stack_smash[] = "Cannot target a scope outside of the current stack";
209 static const char su_no_such_target[] = "No targetable %s scope in the current stack";
211 /* --- Unique context ID global storage ------------------------------------ */
213 /* ... Sequence ID counter ................................................. */
220 static su_uv_array su_uid_seq_counter;
224 static perl_mutex su_uid_seq_counter_mutex;
226 #endif /* USE_ITHREADS */
228 static UV su_uid_seq_next(pTHX_ UV depth) {
229 #define su_uid_seq_next(D) su_uid_seq_next(aTHX_ (D))
233 XSH_LOCK(&su_uid_seq_counter_mutex);
235 seqs = su_uid_seq_counter.seqs;
237 if (depth >= su_uid_seq_counter.size) {
240 seqs = PerlMemShared_realloc(seqs, (depth + 1) * sizeof(UV));
241 for (i = su_uid_seq_counter.size; i <= depth; ++i)
244 su_uid_seq_counter.seqs = seqs;
245 su_uid_seq_counter.size = depth + 1;
250 XSH_UNLOCK(&su_uid_seq_counter_mutex);
255 /* ... UID storage ......................................................... */
262 #define SU_UID_ACTIVE 1
264 static UV su_uid_depth(pTHX_ I32 cxix) {
265 #define su_uid_depth(I) su_uid_depth(aTHX_ (I))
270 for (si = PL_curstackinfo->si_prev; si; si = si->si_prev)
271 depth += si->si_cxix + 1;
282 static void su_uid_storage_dup(pTHX_ su_uid_storage *new_cxt, const su_uid_storage *old_cxt, UV max_depth) {
283 #define su_uid_storage_dup(N, O, D) su_uid_storage_dup(aTHX_ (N), (O), (D))
284 su_uid *old_map = old_cxt->map;
287 su_uid *new_map = new_cxt->map;
288 STRLEN old_used = old_cxt->used;
289 STRLEN new_used, new_alloc;
292 new_used = max_depth < old_used ? max_depth : old_used;
293 new_cxt->used = new_used;
295 if (new_used <= new_cxt->alloc) {
296 new_alloc = new_cxt->alloc;
298 new_alloc = new_used;
299 Renew(new_map, new_alloc, su_uid);
300 new_cxt->map = new_map;
301 new_cxt->alloc = new_alloc;
304 for (i = 0; i < new_alloc; ++i) {
305 su_uid *new_uid = new_map + i;
307 if (i < new_used) { /* => i < max_depth && i < old_used */
308 su_uid *old_uid = old_map + i;
310 if (old_uid && (old_uid->flags & SU_UID_ACTIVE)) {
324 /* --- unwind() global storage --------------------------------------------- */
334 /* --- yield() global storage ---------------------------------------------- */
344 /* --- uplevel() data tokens and global storage ---------------------------- */
346 #define SU_UPLEVEL_HIJACKS_RUNOPS XSH_HAS_PERL(5, 8, 0)
351 su_uid_storage tmp_uid_storage;
352 su_uid_storage old_uid_storage;
359 #ifdef SU_HAS_NEW_CXT
360 U8 *cxtypes; /* array of saved context types */
361 I32 gap; /* how many contexts have temporarily CXt_NULLed out */
362 AV* argarray; /* the PL_curpad[0] of the uplevel sub */
367 PERL_SI *old_curstackinfo;
376 #if SU_UPLEVEL_HIJACKS_RUNOPS
377 runops_proc_t old_runops;
381 #ifdef SU_HAS_NEW_CXT
382 /* used to flag a context stack entry whose type has been temporarily
383 * set to CXt_NULL. It relies on perl not using this value for real
386 # define CXp_SU_UPLEVEL_NULLED 0x20
389 static su_uplevel_ud *su_uplevel_ud_new(pTHX) {
390 #define su_uplevel_ud_new() su_uplevel_ud_new(aTHX)
394 Newx(sud, 1, su_uplevel_ud);
397 sud->tmp_uid_storage.map = NULL;
398 sud->tmp_uid_storage.used = 0;
399 sud->tmp_uid_storage.alloc = 0;
401 #ifndef SU_HAS_NEW_CXT
402 Newx(si, 1, PERL_SI);
403 si->si_stack = newAV();
404 AvREAL_off(si->si_stack);
405 si->si_cxstack = NULL;
414 static void su_uplevel_ud_delete(pTHX_ su_uplevel_ud *sud) {
415 #define su_uplevel_ud_delete(S) su_uplevel_ud_delete(aTHX_ (S))
417 #ifndef SU_HAS_NEW_CXT
418 PERL_SI *si = sud->si;
420 Safefree(si->si_cxstack);
421 SvREFCNT_dec(si->si_stack);
425 Safefree(sud->tmp_uid_storage.map);
436 } su_uplevel_storage;
438 #ifndef SU_UPLEVEL_STORAGE_SIZE
439 # define SU_UPLEVEL_STORAGE_SIZE 4
442 /* --- Global data --------------------------------------------------------- */
445 su_unwind_storage unwind_storage;
446 su_yield_storage yield_storage;
447 su_uplevel_storage uplevel_storage;
448 su_uid_storage uid_storage;
451 #define XSH_THREADS_USER_CONTEXT 1
452 #define XSH_THREADS_USER_CLONE_NEEDS_DUP 0
453 #define XSH_THREADS_COMPILE_TIME_PROTECTION 0
457 static void xsh_user_clone(pTHX_ const xsh_user_cxt_t *old_cxt, xsh_user_cxt_t *new_cxt) {
458 new_cxt->uplevel_storage.top = NULL;
459 new_cxt->uplevel_storage.root = NULL;
460 new_cxt->uplevel_storage.count = 0;
461 new_cxt->uid_storage.map = NULL;
462 new_cxt->uid_storage.used = 0;
463 new_cxt->uid_storage.alloc = 0;
465 su_uid_storage_dup(&new_cxt->uid_storage, &old_cxt->uid_storage,
466 old_cxt->uid_storage.used);
471 #endif /* XSH_THREADSAFE */
473 #include "xsh/threads.h"
475 /* --- Stack manipulations ------------------------------------------------- */
477 /* how many slots on the save stack various save types take up */
479 #define SU_SAVE_DESTRUCTOR_SIZE 3 /* SAVEt_DESTRUCTOR_X */
480 #define SU_SAVE_SCALAR_SIZE 3 /* SAVEt_SV */
481 #define SU_SAVE_ARY_SIZE 3 /* SAVEt_AV */
482 #define SU_SAVE_AELEM_SIZE 4 /* SAVEt_AELEM */
483 #define SU_SAVE_HASH_SIZE 3 /* SAVEt_HV */
484 #define SU_SAVE_HELEM_SIZE 4 /* SAVEt_HELEM */
485 #define SU_SAVE_HDELETE_SIZE 4 /* SAVEt_DELETE */
487 #define SU_SAVE_GVCV_SIZE SU_SAVE_DESTRUCTOR_SIZE
489 /* the overhead of save_alloc() but not including any elements,
490 * of which there must be at least 1 */
491 #if XSH_HAS_PERL(5, 14, 0)
492 # define SU_SAVE_ALLOC_SIZE 1 /* SAVEt_ALLOC */
494 # define SU_SAVE_ALLOC_SIZE 2 /* SAVEt_ALLOC */
498 # define SU_SAVE_ADELETE_SIZE 3 /* SAVEt_ADELETE */
500 # define SU_SAVE_ADELETE_SIZE SU_SAVE_DESTRUCTOR_SIZE
503 /* (NB: it was 4 between 5.13.1 and 5.13.7) */
504 #if XSH_HAS_PERL(5, 8, 9)
505 # define SU_SAVE_GP_SIZE 3 /* SAVEt_GP */
507 # define SU_SAVE_GP_SIZE 6 /* SAVEt_GP */
510 /* sometimes we don't know in advance whether we're saving or deleting
511 * an array/hash element. So include enough room for a variable-sized
512 * save_alloc() to pad it to a fixed size.
515 #if SU_SAVE_AELEM_SIZE < SU_SAVE_ADELETE_SIZE
516 # define SU_SAVE_AELEM_OR_ADELETE_SIZE \
517 (SU_SAVE_ADELETE_SIZE + SU_SAVE_ALLOC_SIZE + 1)
518 #elif SU_SAVE_AELEM_SIZE > SU_SAVE_ADELETE_SIZE
519 # define SU_SAVE_AELEM_OR_ADELETE_SIZE \
520 (SU_SAVE_AELEM_SIZE + SU_SAVE_ALLOC_SIZE + 1)
522 # define SU_SAVE_AELEM_OR_ADELETE_SIZE SU_SAVE_AELEM_SIZE
525 #if SU_SAVE_HELEM_SIZE < SU_SAVE_HDELETE_SIZE
526 # define SU_SAVE_HELEM_OR_HDELETE_SIZE \
527 (SU_SAVE_HDELETE_SIZE + SU_SAVE_ALLOC_SIZE + 1)
528 #elif SU_SAVE_HELEM_SIZE > SU_SAVE_HDELETE_SIZE
529 # define SU_SAVE_HELEM_OR_HDELETE_SIZE \
530 (SU_SAVE_HELEM_SIZE + SU_SAVE_ALLOC_SIZE + 1)
532 # define SU_SAVE_HELEM_OR_HDELETE_SIZE SU_SAVE_HELEM_SIZE
536 #ifndef SvCANEXISTDELETE
537 # define SvCANEXISTDELETE(sv) \
539 || ((mg = mg_find((SV *) sv, PERL_MAGIC_tied)) \
540 && (stash = SvSTASH(SvRV(SvTIED_obj((SV *) sv, mg)))) \
541 && gv_fetchmethod_autoload(stash, "EXISTS", TRUE) \
542 && gv_fetchmethod_autoload(stash, "DELETE", TRUE) \
547 /* ... Saving array elements ............................................... */
549 static I32 su_av_key2idx(pTHX_ AV *av, I32 key) {
550 #define su_av_key2idx(A, K) su_av_key2idx(aTHX_ (A), (K))
556 /* Added by MJD in perl-5.8.1 with 6f12eb6d2a1dfaf441504d869b27d2e40ef4966a */
557 #if XSH_HAS_PERL(5, 8, 1)
558 if (SvRMAGICAL(av)) {
559 const MAGIC * const tied_magic = mg_find((SV *) av, PERL_MAGIC_tied);
561 SV * const * const negative_indices_glob = hv_fetch(
562 SvSTASH(SvRV(SvTIED_obj((SV *) (av), tied_magic))),
563 NEGATIVE_INDICES_VAR, sizeof(NEGATIVE_INDICES_VAR)-1, 0
565 if (negative_indices_glob && SvTRUE(GvSV(*negative_indices_glob)))
571 idx = key + av_len(av) + 1;
585 static void su_adelete(pTHX_ void *ud_) {
586 su_ud_adelete *ud = (su_ud_adelete *) ud_;
588 av_delete(ud->av, ud->idx, G_DISCARD);
589 SvREFCNT_dec(ud->av);
594 static void su_save_adelete(pTHX_ AV *av, I32 idx) {
595 #define su_save_adelete(A, K) su_save_adelete(aTHX_ (A), (K))
598 Newx(ud, 1, su_ud_adelete);
601 SvREFCNT_inc_simple_void(av);
603 SAVEDESTRUCTOR_X(su_adelete, ud);
606 #define SAVEADELETE(A, K) su_save_adelete((A), (K))
608 #endif /* SAVEADELETE */
610 static void su_save_aelem(pTHX_ AV *av, SV *key, SV *val) {
611 #define su_save_aelem(A, K, V) su_save_aelem(aTHX_ (A), (K), (V))
618 idx = su_av_key2idx(av, SvIV(key));
620 if (SvCANEXISTDELETE(av))
621 preeminent = av_exists(av, idx);
623 svp = av_fetch(av, idx, 1);
624 if (!svp || *svp == &PL_sv_undef) croak(PL_no_aelem, idx);
627 save_aelem(av, idx, svp);
629 SAVEADELETE(av, idx);
631 if (val) { /* local $x[$idx] = $val; */
632 SvSetMagicSV(*svp, val);
633 } else { /* local $x[$idx]; delete $x[$idx]; */
634 av_delete(av, idx, G_DISCARD);
638 /* ... Saving hash elements ................................................ */
640 static void su_save_helem(pTHX_ HV *hv, SV *keysv, SV *val) {
641 #define su_save_helem(H, K, V) su_save_helem(aTHX_ (H), (K), (V))
648 if (SvCANEXISTDELETE(hv) || mg_find((SV *) hv, PERL_MAGIC_env))
649 preeminent = hv_exists_ent(hv, keysv, 0);
651 he = hv_fetch_ent(hv, keysv, 1, 0);
652 svp = he ? &HeVAL(he) : NULL;
653 if (!svp || *svp == &PL_sv_undef) croak("Modification of non-creatable hash value attempted, subscript \"%s\"", SvPV_nolen_const(*svp));
655 if (HvNAME_get(hv) && isGV(*svp)) {
656 save_gp((GV *) *svp, 0);
661 save_helem(hv, keysv, svp);
664 const char * const key = SvPV_const(keysv, keylen);
665 SAVEDELETE(hv, savepvn(key, keylen),
666 SvUTF8(keysv) ? -(I32)keylen : (I32)keylen);
669 if (val) { /* local $x{$keysv} = $val; */
670 SvSetMagicSV(*svp, val);
671 } else { /* local $x{$keysv}; delete $x{$keysv}; */
672 (void)hv_delete_ent(hv, keysv, G_DISCARD, HeHASH(he));
676 /* ... Saving code slots from a glob ....................................... */
678 #if !XSH_HAS_PERL(5, 10, 0) && !defined(mro_method_changed_in)
679 # define mro_method_changed_in(G) PL_sub_generation++
687 static void su_restore_gvcv(pTHX_ void *ud_) {
688 su_save_gvcv_ud *ud = ud_;
691 GvCV_set(gv, ud->old_cv);
693 mro_method_changed_in(GvSTASH(gv));
698 static void su_save_gvcv(pTHX_ GV *gv) {
699 #define su_save_gvcv(G) su_save_gvcv(aTHX_ (G))
702 Newx(ud, 1, su_save_gvcv_ud);
704 ud->old_cv = GvCV(gv);
708 mro_method_changed_in(GvSTASH(gv));
710 SAVEDESTRUCTOR_X(su_restore_gvcv, ud);
713 /* --- Actions ------------------------------------------------------------- */
716 I32 orig_ix; /* original savestack_ix */
717 I32 offset; /* how much we bumped this savestack index */
725 su_ud_origin_elem *origin;
729 #define SU_UD_TYPE(U) (((su_ud_common *) (U))->type)
730 #define SU_UD_PRIVATE(U) (((su_ud_common *) (U))->private)
731 #define SU_UD_DEPTH(U) (((su_ud_common *) (U))->depth)
732 #define SU_UD_ORIGIN(U) (((su_ud_common *) (U))->origin)
734 #define SU_UD_TYPE_REAP 0
735 #define SU_UD_TYPE_LOCALIZE 1
736 #define SU_UD_TYPE_UID 2
738 #define SU_UD_FREE(U) STMT_START { \
739 if (SU_UD_ORIGIN(U)) Safefree(SU_UD_ORIGIN(U)); \
743 /* ... Reap ................................................................ */
745 #define SU_SAVE_LAST_CX (!XSH_HAS_PERL(5, 8, 4) || (XSH_HAS_PERL(5, 9, 5) && !XSH_HAS_PERL(5, 14, 0)) || XSH_HAS_PERL(5, 15, 0))
752 #define SU_UD_REAP_CB(U) (((su_ud_reap *) (U))->cb)
754 static void su_call(pTHX_ SV *cb) {
757 PERL_CONTEXT saved_cx;
758 #endif /* SU_SAVE_LAST_CX */
762 XSH_D(su_debug_log("@@@ call scope_ix=%2d save_ix=%2d\n",
763 PL_scopestack_ix, PL_savestack_ix));
772 /* If the recently popped context isn't saved there, it will be overwritten by
773 * the sub scope from call_sv, although it's still needed in our caller. */
774 cxix = (cxstack_ix < cxstack_max) ? (cxstack_ix + 1) : Perl_cxinc(aTHX);
775 saved_cx = cxstack[cxix];
776 #endif /* SU_SAVE_LAST_CX */
781 cxstack[cxix] = saved_cx;
782 #endif /* SU_SAVE_LAST_CX */
794 /* ... Localize & localize array/hash element .............................. */
803 #define SU_UD_LOCALIZE_SV(U) (((su_ud_localize *) (U))->sv)
804 #define SU_UD_LOCALIZE_VAL(U) (((su_ud_localize *) (U))->val)
805 #define SU_UD_LOCALIZE_ELEM(U) (((su_ud_localize *) (U))->elem)
807 #define SU_UD_LOCALIZE_FREE(U) STMT_START { \
808 SvREFCNT_dec(SU_UD_LOCALIZE_ELEM(U)); \
809 SvREFCNT_dec(SU_UD_LOCALIZE_VAL(U)); \
810 SvREFCNT_dec(SU_UD_LOCALIZE_SV(U)); \
814 static I32 su_ud_localize_init(pTHX_ su_ud_localize *ud, SV *sv, SV *val, SV *elem) {
815 #define su_ud_localize_init(UD, S, V, E) su_ud_localize_init(aTHX_ (UD), (S), (V), (E))
820 SvREFCNT_inc_simple_void(sv);
822 if (SvTYPE(sv) >= SVt_PVGV) {
823 if (!val || !SvROK(val)) { /* local *x; or local *x = $val; */
825 } else { /* local *x = \$val; */
826 t = SvTYPE(SvRV(val));
829 } else if (SvROK(sv)) {
830 croak("Invalid %s reference as the localization target",
831 sv_reftype(SvRV(sv), 0));
834 const char *p = SvPV_const(sv, len), *s;
835 for (s = p, l = len; l > 0 && isSPACE(*s); ++s, --l) { }
841 case '$': t = SVt_PV; break;
842 case '@': t = SVt_PVAV; break;
843 case '%': t = SVt_PVHV; break;
844 case '&': t = SVt_PVCV; break;
845 case '*': t = SVt_PVGV; break;
850 } else if (val) { /* t == SVt_NULL, type can't be inferred from the sigil */
851 if (SvROK(val) && !sv_isobject(val)) {
852 t = SvTYPE(SvRV(val));
864 size = elem ? SU_SAVE_AELEM_OR_ADELETE_SIZE
869 size = elem ? SU_SAVE_HELEM_OR_HDELETE_SIZE
874 size = SU_SAVE_GP_SIZE;
878 size = SU_SAVE_GVCV_SIZE;
882 size = SU_SAVE_SCALAR_SIZE;
885 /* When deref is set, val isn't NULL */
887 SU_UD_PRIVATE(ud) = t;
890 ud->val = val ? newSVsv(deref ? SvRV(val) : val) : NULL;
891 ud->elem = SvREFCNT_inc(elem);
896 static void su_localize(pTHX_ void *ud_) {
897 #define su_localize(U) su_localize(aTHX_ (U))
898 su_ud_localize *ud = (su_ud_localize *) ud_;
902 svtype t = SU_UD_PRIVATE(ud);
905 if (SvTYPE(sv) >= SVt_PVGV) {
909 /* new perl context implementation frees savestack *before* restoring
910 * PL_curcop. Temporarily restore it prematurely to make gv_fetch*
911 * looks up unqualified var names in the caller's package */
912 #ifdef SU_HAS_NEW_CXT
913 COP *old_cop = PL_curcop;
914 PL_curcop = CX_CUR()->blk_oldcop;
918 gv = gv_fetchsv(sv, GV_ADDMULTI, t);
921 const char *name = SvPV_const(sv, len);
922 gv = gv_fetchpvn_flags(name, len, GV_ADDMULTI, t);
924 #ifdef SU_HAS_NEW_CXT
925 CX_CUR()->blk_oldcop = PL_curcop;
932 su_debug_log("%p: === localize a %s\n",ud, sv_reftype(z, 0));
933 su_debug_log("%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
934 ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
938 /* Inspired from Alias.pm */
942 su_save_aelem(GvAV(gv), elem, val);
949 su_save_helem(GvHV(gv), elem, val);
955 save_gp(gv, 1); /* hide previous entry in symtab */
961 gv = (GV *) save_scalar(gv);
966 SvSetMagicSV((SV *) gv, val);
971 /* ... Unique context ID ................................................... */
973 /* We must pass the index because XSH_CXT.uid_storage might be reallocated
974 * between the UID fetch and the invalidation at the end of scope. */
981 static void su_uid_drop(pTHX_ void *ud_) {
985 XSH_CXT.uid_storage.map[ud->idx].flags &= ~SU_UID_ACTIVE;
992 /* --- Pop a context back -------------------------------------------------- */
995 # define SU_CX_TYPENAME(T) PL_block_type[(T)]
997 # if XSH_HAS_PERL(5, 23, 8)
998 static const char *su_block_type[] = {
1013 # elif XSH_HAS_PERL(5, 11, 0)
1014 static const char *su_block_type[] = {
1028 # elif XSH_HAS_PERL(5, 10, 0)
1029 static const char *su_block_type[] = {
1041 static const char *su_block_type[] = {
1051 # define SU_CX_TYPENAME(T) su_block_type[(T)]
1054 #define SU_CXNAME(C) SU_CX_TYPENAME(CxTYPE(C))
1056 /* for debugging. These indicate how many ENTERs each context type
1057 * does before the PUSHBLOCK */
1059 static const int su_cxt_enter_count[] = {
1060 # if XSH_HAS_PERL(5, 23, 8)
1061 0 /* context pushes no longer do ENTERs */
1062 # elif XSH_HAS_PERL(5, 11, 0)
1063 /* NULL WHEN BLOCK GIVEN LOOP_FOR LOOP_PLAIN LOOP_LAZYSV
1064 * LOOP_LAZYIV SUB FORMAT EVAL SUBST */
1065 0, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 0
1066 # elif XSH_HAS_PERL(5, 10, 0)
1067 /* NULL SUB EVAL LOOP SUBST BLOCK FORMAT WHEN GIVEN */
1068 0, 1, 1, 2, 0, 1, 1, 1, 1
1070 /* NULL SUB EVAL LOOP SUBST BLOCK FORMAT */
1077 /* push at least 'size' slots worth of padding onto the savestack */
1079 static void su_ss_push_padding(pTHX_ void *ud, I32 size) {
1082 if (size < SU_SAVE_ALLOC_SIZE + 1) /* minimum possible SAVEt_ALLOC */
1083 size = SU_SAVE_ALLOC_SIZE + 1;
1085 "%p: push %2d padding at save_ix=%d\n",
1086 ud, size, PL_savestack_ix));
1087 save_alloc((size - SU_SAVE_ALLOC_SIZE)*sizeof(*PL_savestack), 0);
1091 static void su_pop(pTHX_ void *ud);
1095 /* push an su_pop destructor onto the savestack with suitable padding.
1096 * first indicates that this is the first push of a destructor */
1098 static void su_ss_push_destructor(pTHX_ void *ud, I32 depth, bool first) {
1099 su_ud_origin_elem *origin = SU_UD_ORIGIN(ud);
1102 assert(first || origin[depth+1].orig_ix == PL_savestack_ix);
1103 su_ss_push_padding(aTHX_ ud,
1104 (origin[depth].orig_ix + origin[depth].offset) - PL_savestack_ix);
1106 "%p: push destructor at save_ix=%d depth=%d scope_ix=%d\n",
1107 ud, PL_savestack_ix, depth, PL_scopestack_ix));
1108 SAVEDESTRUCTOR_X(su_pop, ud);
1110 PL_savestack_ix <= origin[depth+1].orig_ix + origin[depth+1].offset);
1114 /* this is called during each leave_scope() via SAVEDESTRUCTOR_X */
1116 static void su_pop(pTHX_ void *ud) {
1117 #define su_pop(U) su_pop(aTHX_ (U))
1118 I32 depth, base, mark;
1119 su_ud_origin_elem *origin;
1121 depth = SU_UD_DEPTH(ud);
1122 origin = SU_UD_ORIGIN(ud);
1124 XSH_D(su_debug_log( "%p: ### su_pop: depth=%d\n", ud, depth));
1127 mark = PL_savestack_ix;
1128 base = origin[depth].orig_ix;
1130 XSH_D(su_debug_log("%p: residual savestack frame is %d(+%d)..%d\n",
1131 ud, base, origin[depth].offset, mark));
1134 XSH_D(su_debug_log("%p: clear leftovers at %d..%d\n", ud, base, mark));
1137 assert(PL_savestack_ix == base);
1139 SU_UD_DEPTH(ud) = depth;
1142 su_ss_push_destructor(aTHX_ ud, depth-1, 0);
1144 I32 offset = origin[0].offset; /* grab value before origin is freed */
1145 switch (SU_UD_TYPE(ud)) {
1146 case SU_UD_TYPE_REAP: {
1147 XSH_D(su_debug_log("%p: === reap\n%p: depth=%d scope_ix=%d save_ix=%d\n",
1148 ud, ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix));
1149 SAVEDESTRUCTOR_X(su_call, SU_UD_REAP_CB(ud));
1153 case SU_UD_TYPE_LOCALIZE:
1155 SU_UD_LOCALIZE_FREE(ud);
1157 case SU_UD_TYPE_UID:
1158 SAVEDESTRUCTOR_X(su_uid_drop, ud);
1161 /* perl 5.23.8 onwards is very fussy about the return from leave_scope()
1162 * leaving PL_savestack_ix where it expects it to be */
1163 if (PL_savestack_ix < base + offset) {
1164 I32 gap = (base + offset) - PL_savestack_ix;
1165 assert(gap >= SU_SAVE_ALLOC_SIZE + 1);
1166 su_ss_push_padding(aTHX_ ud, gap);
1168 assert(PL_savestack_ix == base + offset);
1171 XSH_D(su_debug_log("%p: end pop: ss_ix=%d\n", ud, PL_savestack_ix));
1175 /* --- Initialize the stack and the action userdata ------------------------ */
1177 static void su_init(pTHX_ void *ud, I32 cxix, I32 size) {
1178 #define su_init(U, C, S) su_init(aTHX_ (U), (C), (S))
1180 su_ud_origin_elem *origin;
1184 XSH_D(su_debug_log("%p: ### su_init(cxix=%d, size=%d)\n", ud, cxix, size));
1186 depth = PL_scopestack_ix - cxstack[cxix].blk_oldscopesp;
1187 #ifdef SU_HAS_NEW_CXT
1188 depth += (cxstack_ix - cxix); /* each context frame holds 1 scope */
1191 "%p: going down by depth=%d with scope_ix=%d save_ix=%d\n",
1192 ud, depth, PL_scopestack_ix, PL_savestack_ix));
1194 /* Artificially increase the position of each savestack frame boundary
1195 * to make space to squeeze in a 'size' sized entry (first one) or a
1196 * SU_SAVE_DESTRUCTOR_SIZE sized entry (higher ones). In addition, make
1197 * sure that each boundary is higher than the previous, so that *every*
1198 * scope exit triggers a call to leave_scope(). Each scope exit will call
1199 * the su_pop() destructor, which is responsible for: freeing any
1200 * savestack entries below the artificially raised floor; then pushing a
1201 * new destructor in that space. On the final pop, the "real" savestack
1202 * action is pushed rather than another destructor.
1204 * On older perls, savestack frame boundaries are specified by a range of
1205 * scopestack entries (one per ENTER). Each scope entry typically does
1206 * one or two ENTERs followed by a PUSHBLOCK. Thus the
1207 * cx->blku_oldscopesp field set by the PUSHBLOCK points to the next free
1208 * slot, which is one above the last of the ENTERs. In the debugging
1209 * output we indicate that by bracketing the ENTERs directly preceding
1210 * that context push with dashes, e.g.:
1212 * 13b98d8: ------------------
1213 * 13b98d8: ENTER origin[0] scope[3] savestack=3+3
1214 * 13b98d8: ENTER origin[1] scope[4] savestack=9+3
1215 * 13b98d8: cx=1 LOOP_LAZYIV
1216 * 13b98d8: ------------------
1218 * In addition to context stack pushes, other activities can push ENTERs
1219 * too, such as grep expr and XS sub calls.
1221 * For newer perls (SU_HAS_NEW_CXT), a context push no longer does any
1222 * ENTERs; instead the old savestack position is stored in the new
1223 * cx->blk_oldsaveix field; thus this field specifies an additional
1224 * savestack frame boundary point in addition to the scopestack entries,
1225 * and will also need adjusting.
1227 * We record the original and modified position of each boundary in the
1230 * The passed cxix argument represents the scope we wish to inject into;
1231 * we have to adjust all the savestack frame boundaries above (but not
1232 * including) that context.
1235 Newx(origin, depth, su_ud_origin_elem);
1238 cur_scope_ix = cxstack[cxix].blk_oldscopesp;
1239 #ifdef SU_HAS_NEW_CXT
1240 XSH_D(su_debug_log("%p: cx=%-2d %-11s\n",
1241 ud, cur_cx_ix, SU_CXNAME(cxstack+cur_cx_ix)));
1245 for (i = 0; cur_scope_ix < PL_scopestack_ix; i++) {
1249 #ifdef SU_HAS_NEW_CXT
1251 if ( cur_cx_ix <= cxstack_ix
1252 && cur_scope_ix == cxstack[cur_cx_ix].blk_oldscopesp
1254 ixp = &(cxstack[cur_cx_ix++].blk_oldsaveix);
1256 ixp = &PL_scopestack[cur_scope_ix++]; /* an ENTER pushed after cur context */
1261 if (cur_cx_ix <= cxstack_ix) {
1262 if (cur_scope_ix == cxstack[cur_cx_ix].blk_oldscopesp) {
1264 "%p: cx=%-2d %s\n%p: ------------------\n",
1265 ud, cur_cx_ix, SU_CXNAME(cxstack+cur_cx_ix), ud);
1268 else if (cur_scope_ix + su_cxt_enter_count[CxTYPE(cxstack+cur_cx_ix)]
1269 == cxstack[cur_cx_ix].blk_oldscopesp)
1270 su_debug_log("%p: ------------------\n", ud);
1273 ixp = &PL_scopestack[cur_scope_ix++];
1280 /* we have three constraints to satisfy:
1281 * 1) Each adjusted offset must be at least SU_SAVE_DESTRUCTOR_SIZE
1282 * above its unadjusted boundary, so that there is space to inject a
1283 * destructor into the outer scope.
1284 * 2) Each adjusted boundary must be at least SU_SAVE_DESTRUCTOR_SIZE
1285 * higher than the previous adjusted boundary, so that a new
1286 * destructor can be added below the Nth adjusted frame boundary,
1287 * but be within the (N-1)th adjusted frame and so be triggered on
1288 * the next scope exit;
1289 * 3) If the adjustment needs to be greater than SU_SAVE_DESTRUCTOR_SIZE,
1290 * then it should be greater by an amount of at least the minimum
1291 * pad side, so a destructor and padding can be pushed.
1294 offset = SU_SAVE_DESTRUCTOR_SIZE; /* rule 1 */
1295 pad = (origin[i-1].orig_ix + origin[i-1].offset) + offset - (*ixp + offset);
1296 if (pad > 0) { /* rule 2 */
1297 if (pad < SU_SAVE_ALLOC_SIZE + 1) /* rule 3 */
1298 pad = SU_SAVE_ALLOC_SIZE + 1;
1303 origin[i].offset = offset;
1304 origin[i].orig_ix = *ixp;
1307 #ifdef SU_HAS_NEW_CXT
1309 if (ixp == &PL_scopestack[cur_scope_ix-1])
1311 "%p: ENTER origin[%d] scope[%d] savestack=%d+%d\n",
1312 ud, i, cur_scope_ix, origin[i].orig_ix, origin[i].offset);
1315 "%p: cx=%-2d %-11s origin[%d] scope[%d] savestack=%d+%d\n",
1316 ud, cur_cx_ix-1, SU_CXNAME(cxstack+cur_cx_ix-1),
1317 i, cur_scope_ix, origin[i].orig_ix, origin[i].offset);
1321 "%p: ENTER origin[%d] scope[%d] savestack=%d+%d\n",
1322 ud, i, cur_scope_ix, origin[i].orig_ix, origin[i].offset));
1329 SU_UD_DEPTH(ud) = depth;
1330 SU_UD_ORIGIN(ud) = origin;
1332 su_ss_push_destructor(aTHX_ ud, depth-1, 1);
1336 /* --- Unwind stack -------------------------------------------------------- */
1338 static void su_unwind(pTHX_ void *ud_) {
1340 I32 cxix = XSH_CXT.unwind_storage.cxix;
1341 I32 items = XSH_CXT.unwind_storage.items;
1344 PERL_UNUSED_VAR(ud_);
1346 PL_stack_sp = XSH_CXT.unwind_storage.savesp;
1347 #if XSH_HAS_PERL(5, 19, 4)
1350 SV **sp = PL_stack_sp;
1351 for (i = -items + 1; i <= 0; ++i)
1353 sv_2mortal(SvREFCNT_inc(sp[i]));
1357 if (cxstack_ix > cxix)
1360 mark = PL_markstack[cxstack[cxix].blk_oldmarksp];
1361 PUSHMARK(PL_stack_sp - items);
1364 I32 gimme = GIMME_V;
1365 su_debug_log("%p: cx=%d gimme=%s items=%d sp=%d oldmark=%d mark=%d\n",
1367 gimme == G_VOID ? "void" : gimme == G_ARRAY ? "list" : "scalar",
1368 items, PL_stack_sp - PL_stack_base, *PL_markstack_ptr, mark);
1371 PL_op = (OP *) &(XSH_CXT.unwind_storage.return_op);
1372 PL_op = PL_op->op_ppaddr(aTHX);
1374 *PL_markstack_ptr = mark;
1376 XSH_CXT.unwind_storage.proxy_op.op_next = PL_op;
1377 PL_op = &(XSH_CXT.unwind_storage.proxy_op);
1380 /* --- Yield --------------------------------------------------------------- */
1382 #if XSH_HAS_PERL(5, 10, 0)
1383 # define SU_RETOP_SUB(C) ((C)->blk_sub.retop)
1384 # define SU_RETOP_EVAL(C) ((C)->blk_eval.retop)
1385 # define SU_RETOP_LOOP(C) ((C)->blk_loop.my_op->op_lastop->op_next)
1386 # define SU_RETOP_GIVEN(C) ((C)->blk_givwhen.leave_op->op_next)
1388 # define SU_RETOP_SUB(C) ((C)->blk_oldretsp > 0 ? PL_retstack[(C)->blk_oldretsp - 1] : NULL)
1389 # define SU_RETOP_EVAL(C) SU_RETOP_SUB(C)
1390 # define SU_RETOP_LOOP(C) ((C)->blk_loop.last_op->op_next)
1393 static void su_yield(pTHX_ void *ud_) {
1396 const char *which = ud_;
1397 I32 cxix = XSH_CXT.yield_storage.cxix;
1398 I32 items = XSH_CXT.yield_storage.items;
1399 opcode type = OP_NULL;
1403 PERL_UNUSED_VAR(ud_);
1405 cx = cxstack + cxix;
1406 switch (CxTYPE(cx)) {
1408 I32 i, cur = cxstack_ix, n = 1;
1410 /* Is this actually a given/when block? This may occur only when yield was
1411 * called with HERE (or nothing) as the context. */
1412 #if XSH_HAS_PERL(5, 10, 0)
1414 PERL_CONTEXT *prev = cx - 1;
1415 U8 prev_type = CxTYPE(prev);
1416 if ((prev_type == CXt_GIVEN || prev_type == CXt_WHEN)
1417 && (prev->blk_oldcop == cx->blk_oldcop)) {
1420 if (prev_type == CXt_GIVEN)
1429 /* Bare blocks (that appear as do { ... } blocks, map { ... } blocks or
1430 * constant folded blcoks) don't need to save the op to return to anywhere
1431 * since 'last' isn't supposed to work inside them. So we climb higher in
1432 * the context stack until we reach a context that has a return op (i.e. a
1433 * sub, an eval, a format or a real loop), recording how many blocks we
1434 * crossed. Then we follow the op_next chain until we get to the leave op
1435 * that closes the original block, which we are assured to reach since
1436 * everything is static (the blocks we have crossed cannot be evals or
1437 * subroutine calls). */
1438 for (i = cxix + 1; i <= cur; ++i) {
1439 PERL_CONTEXT *cx2 = cxstack + i;
1440 switch (CxTYPE(cx2)) {
1446 o = SU_RETOP_SUB(cx2);
1449 o = SU_RETOP_EVAL(cx2);
1451 #if XSH_HAS_PERL(5, 11, 0)
1452 # if XSH_HAS_PERL(5, 23, 8)
1458 case CXt_LOOP_PLAIN:
1459 case CXt_LOOP_LAZYSV:
1460 case CXt_LOOP_LAZYIV:
1464 o = SU_RETOP_LOOP(cx2);
1473 /* We may find other enter/leave blocks on our way to the matching leave.
1474 * Make sure the depth is incremented/decremented appropriately. */
1475 if (o->op_type == OP_ENTER) {
1477 } else if (o->op_type == OP_LEAVE) {
1491 next = SU_RETOP_SUB(cx);
1494 type = CxTRYBLOCK(cx) ? OP_LEAVETRY : OP_LEAVEEVAL;
1495 next = SU_RETOP_EVAL(cx);
1497 #if XSH_HAS_PERL(5, 11, 0)
1498 # if XSH_HAS_PERL(5, 23, 8)
1504 case CXt_LOOP_PLAIN:
1505 case CXt_LOOP_LAZYSV:
1506 case CXt_LOOP_LAZYIV:
1510 type = OP_LEAVELOOP;
1511 next = SU_RETOP_LOOP(cx);
1513 #if XSH_HAS_PERL(5, 10, 0)
1516 type = OP_LEAVEGIVEN;
1517 next = SU_RETOP_GIVEN(cx);
1521 #if XSH_HAS_PERL(5, 15, 1)
1522 type = OP_LEAVEWHEN;
1525 flags |= OPf_SPECIAL;
1531 croak("%s() can't target a substitution context", which);
1534 croak("%s() doesn't know how to leave a %s context",
1535 which, SU_CXNAME(cxstack + cxix));
1539 PL_stack_sp = XSH_CXT.yield_storage.savesp;
1540 #if XSH_HAS_PERL(5, 19, 4)
1543 SV **sp = PL_stack_sp;
1544 for (i = -items + 1; i <= 0; ++i)
1546 sv_2mortal(SvREFCNT_inc(sp[i]));
1550 if (cxstack_ix > cxix)
1553 /* Copy the arguments passed to yield() where the leave op expects to find
1556 Move(PL_stack_sp - items + 1, PL_stack_base + cx->blk_oldsp + 1, items, SV *);
1557 PL_stack_sp = PL_stack_base + cx->blk_oldsp + items;
1559 flags |= OP_GIMME_REVERSE(cx->blk_gimme);
1561 XSH_CXT.yield_storage.leave_op.op_type = type;
1562 XSH_CXT.yield_storage.leave_op.op_ppaddr = PL_ppaddr[type];
1563 XSH_CXT.yield_storage.leave_op.op_flags = flags;
1564 XSH_CXT.yield_storage.leave_op.op_next = next;
1566 PL_op = (OP *) &(XSH_CXT.yield_storage.leave_op);
1567 PL_op = PL_op->op_ppaddr(aTHX);
1569 XSH_CXT.yield_storage.proxy_op.op_next = PL_op;
1570 PL_op = &(XSH_CXT.yield_storage.proxy_op);
1573 /* --- Uplevel ------------------------------------------------------------- */
1575 #define SU_UPLEVEL_SAVE(f, t) STMT_START { sud->old_##f = PL_##f; PL_##f = (t); } STMT_END
1576 #define SU_UPLEVEL_RESTORE(f) STMT_START { PL_##f = sud->old_##f; } STMT_END
1578 static su_uplevel_ud *su_uplevel_storage_new(pTHX_ I32 cxix) {
1579 #define su_uplevel_storage_new(I) su_uplevel_storage_new(aTHX_ (I))
1584 sud = XSH_CXT.uplevel_storage.root;
1586 XSH_CXT.uplevel_storage.root = sud->next;
1587 XSH_CXT.uplevel_storage.count--;
1589 sud = su_uplevel_ud_new();
1592 sud->next = XSH_CXT.uplevel_storage.top;
1593 XSH_CXT.uplevel_storage.top = sud;
1595 depth = su_uid_depth(cxix);
1596 su_uid_storage_dup(&sud->tmp_uid_storage, &XSH_CXT.uid_storage, depth);
1597 sud->old_uid_storage = XSH_CXT.uid_storage;
1598 XSH_CXT.uid_storage = sud->tmp_uid_storage;
1603 #if XSH_HAS_PERL(5, 13, 7)
1605 static void su_uplevel_storage_delete(pTHX_ su_uplevel_ud *sud) {
1606 #define su_uplevel_storage_delete(S) su_uplevel_storage_delete(aTHX_ (S))
1609 sud->tmp_uid_storage = XSH_CXT.uid_storage;
1610 XSH_CXT.uid_storage = sud->old_uid_storage;
1614 map = sud->tmp_uid_storage.map;
1615 alloc = sud->tmp_uid_storage.alloc;
1616 for (i = 0; i < alloc; ++i)
1617 map[i].flags &= ~SU_UID_ACTIVE;
1619 XSH_CXT.uplevel_storage.top = sud->next;
1621 if (XSH_CXT.uplevel_storage.count >= SU_UPLEVEL_STORAGE_SIZE) {
1622 su_uplevel_ud_delete(sud);
1624 sud->next = XSH_CXT.uplevel_storage.root;
1625 XSH_CXT.uplevel_storage.root = sud;
1626 XSH_CXT.uplevel_storage.count++;
1632 static int su_uplevel_goto_static(const OP *o) {
1633 for (; o; o = OpSIBLING(o)) {
1634 /* goto ops are unops with kids. */
1635 if (!(o->op_flags & OPf_KIDS))
1638 switch (o->op_type) {
1641 /* Don't care about gotos inside eval, as they are forbidden at run time. */
1646 if (su_uplevel_goto_static(((const UNOP *) o)->op_first))
1655 #if !defined(SU_HAS_NEW_CXT) && SU_UPLEVEL_HIJACKS_RUNOPS
1657 static int su_uplevel_goto_runops(pTHX) {
1658 #define su_uplevel_goto_runops() su_uplevel_goto_runops(aTHX)
1664 if (op->op_type == OP_GOTO) {
1665 AV *argarray = NULL;
1668 for (cxix = cxstack_ix; cxix >= 0; --cxix) {
1669 const PERL_CONTEXT *cx = cxstack + cxix;
1671 switch (CxTYPE(cx)) {
1673 if (CxHASARGS(cx)) {
1674 argarray = cx->blk_sub.argarray;
1690 if (XSH_CXT.uplevel_storage.top->cxix == cxix) {
1691 AV *args = GvAV(PL_defgv);
1692 I32 items = AvFILLp(args);
1694 av_extend(argarray, items);
1695 Copy(AvARRAY(args), AvARRAY(argarray), items + 1, SV *);
1696 AvFILLp(argarray) = items;
1701 PL_op = op = op->op_ppaddr(aTHX);
1703 #if !XSH_HAS_PERL(5, 13, 0)
1713 #endif /* SU_UPLEVEL_HIJACKS_RUNOPS */
1715 #define su_at_underscore(C) PadARRAY(PadlistARRAY(CvPADLIST(C))[CvDEPTH(C)])[0]
1717 #ifdef SU_HAS_NEW_CXT
1719 static void su_uplevel_restore_new(pTHX_ void *sus_) {
1720 su_uplevel_ud *sud = sus_;
1723 U8 *saved_cxtypes = sud->cxtypes;
1725 for (i = 0; i < sud->gap; i++) {
1726 PERL_CONTEXT *cx = cxstack + sud->cxix + i;
1727 XSH_D(su_debug_log("su_uplevel_restore: i=%d cxix=%d type %s => %s\n",
1728 i, cx-cxstack, SU_CX_TYPENAME(CxTYPE(cx)),
1729 SU_CX_TYPENAME(saved_cxtypes[i] & CXTYPEMASK)));
1730 cx->cx_type = saved_cxtypes[i];
1732 Safefree(saved_cxtypes);
1734 /* renamed is a copy of callback, but they share the same CvPADLIST.
1735 * At this point any calls to renamed should have exited so that its
1736 * depth is back to that of of callback. At this point its safe to free
1737 * renamed, then undo the extra ref count that was ensuring that callback
1740 assert(sud->renamed);
1741 assert(sud->callback);
1743 CvDEPTH(sud->callback)--;
1744 assert(CvDEPTH(sud->callback) == CvDEPTH(sud->renamed));
1745 if (!CvISXSUB(sud->renamed)) {
1746 CvDEPTH(sud->renamed) = 0;
1747 CvPADLIST(sud->renamed) = NULL;
1749 SvREFCNT_dec(sud->renamed);
1750 SvREFCNT_dec(sud->callback);
1752 SU_UPLEVEL_RESTORE(curcop);
1754 su_uplevel_storage_delete(sud);
1761 /* 5.23.7 and earlier */
1763 static void su_uplevel_restore_old(pTHX_ void *sus_) {
1764 su_uplevel_ud *sud = sus_;
1765 PERL_SI *cur = sud->old_curstackinfo;
1766 PERL_SI *si = sud->si;
1768 #if SU_UPLEVEL_HIJACKS_RUNOPS
1769 if (PL_runops == su_uplevel_goto_runops)
1770 PL_runops = sud->old_runops;
1773 if (sud->callback) {
1774 PERL_CONTEXT *cx = cxstack + sud->cxix;
1775 AV *argarray = MUTABLE_AV(su_at_underscore(sud->callback));
1777 /* We have to fix the pad entry for @_ in the original callback because it
1778 * may have been reified. */
1779 if (AvREAL(argarray)) {
1780 const I32 fill = AvFILLp(argarray);
1781 SvREFCNT_dec(argarray);
1783 AvREAL_off(argarray);
1784 AvREIFY_on(argarray);
1785 av_extend(argarray, fill);
1786 su_at_underscore(sud->callback) = MUTABLE_SV(argarray);
1788 CLEAR_ARGARRAY(argarray);
1791 /* If the old cv member is our renamed CV, it means that this place has been
1792 * reached without a goto() happening, and the old argarray member is
1793 * actually our fake argarray. Destroy it properly in that case. */
1794 if (cx->blk_sub.cv == sud->renamed) {
1795 SvREFCNT_dec(cx->blk_sub.argarray);
1796 cx->blk_sub.argarray = argarray;
1799 CvDEPTH(sud->callback)--;
1800 SvREFCNT_dec(sud->callback);
1803 /* Free the renamed CV. We must do it ourselves so that we can force the
1804 * depth to be 0, or perl would complain about it being "still in use".
1805 * But we *know* that it cannot be so. */
1807 if (!CvISXSUB(sud->renamed)) {
1808 CvDEPTH(sud->renamed) = 0;
1809 CvPADLIST(sud->renamed) = NULL;
1811 SvREFCNT_dec(sud->renamed);
1814 CATCH_SET(sud->old_catch);
1816 SU_UPLEVEL_RESTORE(op);
1818 /* stack_grow() wants PL_curstack so restore the old stack first */
1819 if (PL_curstackinfo == si) {
1820 PL_curstack = cur->si_stack;
1821 if (sud->old_mainstack)
1822 SU_UPLEVEL_RESTORE(mainstack);
1823 SU_UPLEVEL_RESTORE(curstackinfo);
1826 CV *target = sud->target;
1829 /* When we die, the depth of the target CV is not updated because of the
1830 * stack switcheroo. So we have to look at all the frames between the
1831 * uplevel call and the catch block to count how many call frames to the
1832 * target CV were skipped. */
1833 for (i = cur->si_cxix; i > sud->cxix; i--) {
1834 register const PERL_CONTEXT *cx = cxstack + i;
1836 if (CxTYPE(cx) == CXt_SUB) {
1837 if (cx->blk_sub.cv == target)
1842 /* If we died, the replacement stack was already unwinded to the first
1843 * eval frame, and all the contexts down there were popped. We don't have
1844 * to pop manually any context of the original stack, because they must
1845 * have been in the replacement stack as well (since the second was copied
1846 * from the first). Thus we only have to make sure the original stack index
1847 * points to the context just below the first eval scope under the target
1849 for (; i >= 0; i--) {
1850 register const PERL_CONTEXT *cx = cxstack + i;
1852 switch (CxTYPE(cx)) {
1854 if (cx->blk_sub.cv == target)
1866 CvDEPTH(target) = sud->target_depth - levels;
1867 PL_curstackinfo->si_cxix = i - 1;
1869 #if !XSH_HAS_PERL(5, 13, 1)
1870 /* Since $@ was maybe localized between the target frame and the uplevel
1871 * call, we forcefully flush the save stack to get rid of it and then
1872 * reset $@ to its proper value. Note that the the call to
1873 * su_uplevel_restore() must happen before the "reset $@" item of the save
1874 * stack is processed, as uplevel was called after the localization.
1875 * Andrew's changes to how $@ was handled, which were mainly integrated
1876 * between perl 5.13.0 and 5.13.1, fixed this. */
1877 if (ERRSV && SvTRUE(ERRSV)) {
1878 register const PERL_CONTEXT *cx = cxstack + i; /* This is the eval scope */
1879 SV *errsv = SvREFCNT_inc(ERRSV);
1880 PL_scopestack_ix = cx->blk_oldscopesp;
1881 leave_scope(PL_scopestack[PL_scopestack_ix]);
1882 sv_setsv(ERRSV, errsv);
1883 SvREFCNT_dec(errsv);
1889 SU_UPLEVEL_RESTORE(curcop);
1891 SvREFCNT_dec(sud->target);
1893 PL_stack_base = AvARRAY(cur->si_stack);
1894 PL_stack_sp = PL_stack_base + AvFILLp(cur->si_stack);
1895 PL_stack_max = PL_stack_base + AvMAX(cur->si_stack);
1897 /* When an exception is thrown from the uplevel'd subroutine,
1898 * su_uplevel_restore() may be called by the LEAVE in die_unwind() (renamed
1899 * die_where() in more recent perls), which has the sad habit of keeping a
1900 * pointer to the current context frame across this call. This means that we
1901 * can't free the temporary context stack we used for the uplevel call right
1902 * now, or that pointer upwards would point to garbage. */
1903 #if XSH_HAS_PERL(5, 13, 7)
1904 /* This issue has been fixed in perl with commit 8f89e5a9, which was made
1905 * public in perl 5.13.7. */
1906 su_uplevel_storage_delete(sud);
1908 /* Otherwise, we just enqueue it back in the global storage list. */
1912 sud->tmp_uid_storage = XSH_CXT.uid_storage;
1913 XSH_CXT.uid_storage = sud->old_uid_storage;
1915 XSH_CXT.uplevel_storage.top = sud->next;
1916 sud->next = XSH_CXT.uplevel_storage.root;
1917 XSH_CXT.uplevel_storage.root = sud;
1918 XSH_CXT.uplevel_storage.count++;
1927 static CV *su_cv_clone(pTHX_ CV *proto, GV *gv) {
1928 #define su_cv_clone(P, G) su_cv_clone(aTHX_ (P), (G))
1932 cv = MUTABLE_CV(newSV_type(SvTYPE(proto)));
1934 CvFLAGS(cv) = CvFLAGS(proto);
1936 CvFLAGS(cv) &= ~CVf_CVGV_RC;
1938 CvDEPTH(cv) = CvDEPTH(proto);
1940 CvFILE(cv) = CvISXSUB(proto) ? CvFILE(proto) : savepv(CvFILE(proto));
1942 CvFILE(cv) = CvFILE(proto);
1946 #if SU_RELEASE && XSH_HAS_PERL_EXACT(5, 21, 4)
1949 CvSTASH_set(cv, CvSTASH(proto));
1950 /* Commit 4c74a7df, publicized with perl 5.13.3, began to add backrefs to
1951 * stashes. CvSTASH_set() started to do it as well with commit c68d95645
1952 * (which was part of perl 5.13.7). */
1953 #if XSH_HAS_PERL(5, 13, 3) && !XSH_HAS_PERL(5, 13, 7)
1955 Perl_sv_add_backref(aTHX_ CvSTASH(proto), MUTABLE_SV(cv));
1958 if (CvISXSUB(proto)) {
1959 CvXSUB(cv) = CvXSUB(proto);
1960 CvXSUBANY(cv) = CvXSUBANY(proto);
1963 CvROOT(cv) = OpREFCNT_inc(CvROOT(proto));
1965 CvSTART(cv) = CvSTART(proto);
1966 CvPADLIST(cv) = CvPADLIST(proto);
1968 CvOUTSIDE(cv) = CvOUTSIDE(proto);
1969 #ifdef CVf_WEAKOUTSIDE
1970 if (!(CvFLAGS(proto) & CVf_WEAKOUTSIDE))
1972 SvREFCNT_inc_simple_void(CvOUTSIDE(cv));
1973 #ifdef CvOUTSIDE_SEQ
1974 CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(proto);
1978 sv_setpvn(MUTABLE_SV(cv), SvPVX_const(proto), SvCUR(proto));
1990 #ifdef SU_HAS_NEW_CXT
1992 /* this one-shot runops "loop" is designed to be called just before
1993 * execution of the first op following an uplevel()'s entersub. It gets a
1994 * chance to fix up the args as seen by caller(), before immediately
1995 * falling through to the previous runops loop. Note that pp_entersub is
1996 * called directly by call_sv() rather than being called from a runops
2000 static int su_uplevel_runops_hook_entersub(pTHX) {
2003 su_uplevel_ud *sud = XSH_CXT.uplevel_storage.top;
2005 /* Create a new array containing a copy of the original sub's call args,
2006 * then stick it in PL_curpad[0] of the current running sub so that
2007 * thay will be seen by caller().
2010 if (sud->argarray) {
2014 av_extend(av, AvMAX(sud->argarray));
2015 AvFILLp(av) = AvFILLp(sud->argarray);
2016 Copy(AvARRAY(sud->argarray), AvARRAY(av), AvFILLp(av) + 1, SV *);
2018 /* should be referenced by PL_curpad[0] and *_ */
2019 assert(SvREFCNT(PL_curpad[0]) > 1);
2020 SvREFCNT_dec(PL_curpad[0]);
2022 PL_curpad[0] = (SV*)av;
2025 /* undo the temporary runops hook and fall through to a real runops loop. */
2026 assert(sud->old_runops != su_uplevel_runops_hook_entersub);
2027 PL_runops = sud->old_runops;
2034 static I32 su_uplevel_new(pTHX_ CV *callback, I32 cxix, I32 args) {
2039 CV *base_cv = cxstack[cxix].blk_sub.cv;
2042 assert(CxTYPE(&cxstack[cxix]) == CXt_SUB);
2048 /* At this point SP points to the top arg.
2049 * Shuffle the args down by one, eliminating the CV slot */
2050 Move(SP - args + 1, SP - args, args, SV*);
2052 PUSHMARK(SP - args);
2055 sud = su_uplevel_storage_new(cxix);
2058 sud->callback = (CV*)SvREFCNT_inc_simple(callback);
2059 sud->renamed = NULL;
2060 sud->gap = cxstack_ix - cxix + 1;
2061 sud->argarray = NULL;
2064 Newx(saved_cxtypes, sud->gap, U8);
2065 sud->cxtypes = saved_cxtypes;
2067 SAVEDESTRUCTOR_X(su_uplevel_restore_new, sud);
2068 SU_UPLEVEL_SAVE(curcop, cxstack[cxix].blk_oldcop);
2070 /* temporarily change the type of any contexts to NULL, so they're
2071 * invisible to caller() etc. */
2072 for (i = 0; i < sud->gap; i++) {
2073 PERL_CONTEXT *cx = cxstack + cxix + i;
2074 saved_cxtypes[i] = cx->cx_type; /* save type and flags */
2075 XSH_D(su_debug_log("su_uplevel: i=%d cxix=%d type %-11s => %s\n",
2076 i, cx-cxstack, SU_CX_TYPENAME(CxTYPE(cx)), SU_CX_TYPENAME(CXt_NULL)));
2077 cx->cx_type = (CXt_NULL | CXp_SU_UPLEVEL_NULLED);
2080 /* create a copy of the callback with a doctored name (as seen by
2081 * caller). It shares the padlist with callback */
2082 sud->renamed = su_cv_clone(callback, CvGV(base_cv));
2083 sud->old_runops = PL_runops;
2086 if (!CvISXSUB(sud->renamed) && CxHASARGS(&cxstack[cxix])) {
2087 sud->argarray = (AV*)su_at_underscore(base_cv);
2088 assert(PL_runops != su_uplevel_runops_hook_entersub);
2089 /* set up a one-shot runops hook so that we can fake up the
2090 * args as seen by caller() on return from pp_entersub */
2091 PL_runops = su_uplevel_runops_hook_entersub;
2094 CvDEPTH(callback)++; /* match what CvDEPTH(sud->renamed) is about to become */
2096 ret = call_sv((SV*)sud->renamed, gimme);
2105 static I32 su_uplevel_old(pTHX_ CV *callback, I32 cxix, I32 args) {
2107 const PERL_CONTEXT *cx = cxstack + cxix;
2109 PERL_SI *cur = PL_curstackinfo;
2115 I32 old_mark, new_mark;
2122 /* Make PL_stack_sp point just before the CV. */
2123 PL_stack_sp -= args + 1;
2124 old_mark = AvFILLp(PL_curstack) = PL_stack_sp - PL_stack_base;
2127 sud = su_uplevel_storage_new(cxix);
2131 sud->callback = NULL;
2132 sud->renamed = NULL;
2133 SAVEDESTRUCTOR_X(su_uplevel_restore_old, sud);
2137 si->si_type = cur->si_type;
2139 si->si_prev = cur->si_prev;
2141 si->si_markoff = cx->blk_oldmarksp;
2144 /* Allocate enough space for all the elements of the original stack up to the
2145 * target context, plus the forthcoming arguments. */
2146 new_mark = cx->blk_oldsp;
2147 av_extend(si->si_stack, new_mark + 1 + args + 1);
2148 Copy(AvARRAY(PL_curstack), AvARRAY(si->si_stack), new_mark + 1, SV *);
2149 AvFILLp(si->si_stack) = new_mark;
2150 SU_POISON(AvARRAY(si->si_stack) + new_mark + 1, args + 1, SV *);
2152 /* Specialized SWITCHSTACK() */
2153 PL_stack_base = AvARRAY(si->si_stack);
2154 old_stack_sp = PL_stack_sp;
2155 PL_stack_sp = PL_stack_base + AvFILLp(si->si_stack);
2156 PL_stack_max = PL_stack_base + AvMAX(si->si_stack);
2159 /* Copy the context stack up to the context just below the target. */
2160 si->si_cxix = (cxix < 0) ? -1 : (cxix - 1);
2161 if (si->si_cxmax < cxix) {
2162 /* The max size must be at least two so that GROW(max) = (max*3)/2 > max */
2163 si->si_cxmax = (cxix < 4) ? 4 : cxix;
2164 Renew(si->si_cxstack, si->si_cxmax + 1, PERL_CONTEXT);
2166 Copy(cur->si_cxstack, si->si_cxstack, cxix, PERL_CONTEXT);
2167 SU_POISON(si->si_cxstack + cxix, si->si_cxmax + 1 - cxix, PERL_CONTEXT);
2169 target = cx->blk_sub.cv;
2170 sud->target = (CV *) SvREFCNT_inc(target);
2171 sud->target_depth = CvDEPTH(target);
2173 /* blk_oldcop is essentially needed for caller() and stack traces. It has no
2174 * run-time implication, since PL_curcop will be overwritten as soon as we
2175 * enter a sub (a sub starts by a nextstate/dbstate). Hence it's safe to just
2176 * make it point to the blk_oldcop for the target frame, so that caller()
2177 * reports the right file name, line number and lexical hints. */
2178 SU_UPLEVEL_SAVE(curcop, cx->blk_oldcop);
2179 /* Don't reset PL_markstack_ptr, or we would overwrite the mark stack below
2180 * this point. Don't reset PL_curpm either, we want the most recent matches. */
2182 SU_UPLEVEL_SAVE(curstackinfo, si);
2183 /* If those two are equal, we need to fool POPSTACK_TO() */
2184 if (PL_mainstack == PL_curstack)
2185 SU_UPLEVEL_SAVE(mainstack, si->si_stack);
2187 sud->old_mainstack = NULL;
2188 PL_curstack = si->si_stack;
2190 renamed = su_cv_clone(callback, CvGV(target));
2191 sud->renamed = renamed;
2194 /* Both SP and old_stack_sp point just before the CV. */
2195 Copy(old_stack_sp + 2, SP + 1, args, SV *);
2197 PUSHs((SV *) renamed);
2200 Zero(&sub_op, 1, UNOP);
2201 sub_op.op_type = OP_ENTERSUB;
2202 sub_op.op_next = NULL;
2203 sub_op.op_flags = OP_GIMME_REVERSE(gimme) | OPf_STACKED;
2205 sub_op.op_flags |= OPpENTERSUB_DB;
2207 SU_UPLEVEL_SAVE(op, (OP *) &sub_op);
2209 #if SU_UPLEVEL_HIJACKS_RUNOPS
2210 sud->old_runops = PL_runops;
2213 sud->old_catch = CATCH_GET;
2216 if ((PL_op = PL_ppaddr[OP_ENTERSUB](aTHX))) {
2217 PERL_CONTEXT *sub_cx = cxstack + cxstack_ix;
2218 AV *argarray = cx->blk_sub.argarray;
2220 /* If pp_entersub() returns a non-null OP, it means that the callback is not
2223 sud->callback = MUTABLE_CV(SvREFCNT_inc(callback));
2224 CvDEPTH(callback)++;
2226 if (CxHASARGS(cx) && argarray) {
2227 /* The call to pp_entersub() has saved the current @_ (in XS terms,
2228 * GvAV(PL_defgv)) in the savearray member, and has created a new argarray
2229 * with what we put on the stack. But we want to fake up the same arguments
2230 * as the ones in use at the context we uplevel to, so we replace the
2231 * argarray with an unreal copy of the original @_. */
2235 av_extend(av, AvMAX(argarray));
2236 AvFILLp(av) = AvFILLp(argarray);
2237 Copy(AvARRAY(argarray), AvARRAY(av), AvFILLp(av) + 1, SV *);
2238 sub_cx->blk_sub.argarray = av;
2240 SvREFCNT_inc_simple_void(sub_cx->blk_sub.argarray);
2243 if (su_uplevel_goto_static(CvROOT(renamed))) {
2244 #if SU_UPLEVEL_HIJACKS_RUNOPS
2245 if (PL_runops != PL_runops_std) {
2246 if (PL_runops == PL_runops_dbg) {
2248 croak("uplevel() can't execute code that calls goto when debugging flags are set");
2249 } else if (PL_runops != su_uplevel_goto_runops)
2250 croak("uplevel() can't execute code that calls goto with a custom runloop");
2253 PL_runops = su_uplevel_goto_runops;
2254 #else /* SU_UPLEVEL_HIJACKS_RUNOPS */
2255 croak("uplevel() can't execute code that calls goto before perl 5.8");
2256 #endif /* !SU_UPLEVEL_HIJACKS_RUNOPS */
2264 ret = PL_stack_sp - (PL_stack_base + new_mark);
2266 AV *old_stack = sud->old_curstackinfo->si_stack;
2268 if (old_mark + ret > AvMAX(old_stack)) {
2269 /* Specialized EXTEND(old_sp, ret) */
2270 av_extend(old_stack, old_mark + ret + 1);
2271 old_stack_sp = AvARRAY(old_stack) + old_mark;
2274 Copy(PL_stack_sp - ret + 1, old_stack_sp + 1, ret, SV *);
2276 AvFILLp(old_stack) += ret;
2286 /* --- Unique context ID --------------------------------------------------- */
2288 static su_uid *su_uid_storage_fetch(pTHX_ UV depth) {
2289 #define su_uid_storage_fetch(D) su_uid_storage_fetch(aTHX_ (D))
2294 map = XSH_CXT.uid_storage.map;
2295 alloc = XSH_CXT.uid_storage.alloc;
2297 if (depth >= alloc) {
2300 Renew(map, depth + 1, su_uid);
2301 for (i = alloc; i <= depth; ++i) {
2306 XSH_CXT.uid_storage.map = map;
2307 XSH_CXT.uid_storage.alloc = depth + 1;
2310 if (depth >= XSH_CXT.uid_storage.used)
2311 XSH_CXT.uid_storage.used = depth + 1;
2316 static int su_uid_storage_check(pTHX_ UV depth, UV seq) {
2317 #define su_uid_storage_check(D, S) su_uid_storage_check(aTHX_ (D), (S))
2321 if (depth >= XSH_CXT.uid_storage.used)
2324 uid = XSH_CXT.uid_storage.map + depth;
2326 return (uid->seq == seq) && (uid->flags & SU_UID_ACTIVE);
2329 static SV *su_uid_get(pTHX_ I32 cxix) {
2330 #define su_uid_get(I) su_uid_get(aTHX_ (I))
2335 depth = su_uid_depth(cxix);
2336 uid = su_uid_storage_fetch(depth);
2338 if (!(uid->flags & SU_UID_ACTIVE)) {
2341 uid->seq = su_uid_seq_next(depth);
2342 uid->flags |= SU_UID_ACTIVE;
2344 Newx(ud, 1, su_ud_uid);
2345 SU_UD_TYPE(ud) = SU_UD_TYPE_UID;
2347 su_init(ud, cxix, SU_SAVE_DESTRUCTOR_SIZE);
2350 uid_sv = sv_newmortal();
2351 sv_setpvf(uid_sv, "%"UVuf"-%"UVuf, depth, uid->seq);
2358 #define su_grok_number(S, L, VP) grok_number((S), (L), (VP))
2360 #else /* grok_number */
2362 #define IS_NUMBER_IN_UV 0x1
2364 static int su_grok_number(pTHX_ const char *s, STRLEN len, UV *valuep) {
2365 #define su_grok_number(S, L, VP) su_grok_number(aTHX_ (S), (L), (VP))
2369 /* This crude check should be good enough for a fallback implementation.
2370 * Better be too strict than too lax. */
2371 for (i = 0; i < len; ++i) {
2376 tmpsv = sv_newmortal();
2377 sv_setpvn(tmpsv, s, len);
2378 *valuep = sv_2uv(tmpsv);
2380 return IS_NUMBER_IN_UV;
2383 #endif /* !grok_number */
2385 static int su_uid_validate(pTHX_ SV *uid) {
2386 #define su_uid_validate(U) su_uid_validate(aTHX_ (U))
2392 s = SvPV_const(uid, len);
2394 while (p < len && s[p] != '-')
2397 croak("UID contains only one part");
2399 type = su_grok_number(s, p, &depth);
2400 if (type != IS_NUMBER_IN_UV)
2401 croak("First UID part is not an unsigned integer");
2403 ++p; /* Skip '-'. As we used to have p < len, len - (p + 1) >= 0. */
2405 type = su_grok_number(s + p, len - p, &seq);
2406 if (type != IS_NUMBER_IN_UV)
2407 croak("Second UID part is not an unsigned integer");
2409 return su_uid_storage_check(depth, seq);
2412 /* --- Context operations -------------------------------------------------- */
2414 /* Remove sequences of BLOCKs having DB for stash, followed by a SUB context
2415 * for the debugger callback. */
2417 static I32 su_context_skip_db(pTHX_ I32 cxix) {
2418 #define su_context_skip_db(C) su_context_skip_db(aTHX_ (C))
2424 for (i = cxix; i > 0; --i) {
2425 PERL_CONTEXT *cx = cxstack + i;
2427 switch (CxTYPE(cx)) {
2428 #if XSH_HAS_PERL(5, 17, 1)
2429 case CXt_LOOP_PLAIN:
2432 if (cx->blk_oldcop && CopSTASH(cx->blk_oldcop) == GvSTASH(PL_DBgv))
2436 if (cx->blk_sub.cv == GvCV(PL_DBsub)) {
2452 #ifdef SU_HAS_NEW_CXT
2454 /* convert a physical context stack index into the logical equivalent:
2455 * one that ignores all the context frames hidden by uplevel().
2456 * Perl-level functions use logical args (e.g. UP takes an optional logical
2457 * value and returns a logical value), while we use and store *real*
2458 * values internally.
2461 static I32 su_context_real2logical(pTHX_ I32 cxix) {
2462 # define su_context_real2logical(C) su_context_real2logical(aTHX_ (C))
2466 for (i = 0; i <= cxix; i++) {
2468 if (cx->cx_type == (CXt_NULL | CXp_SU_UPLEVEL_NULLED))
2471 XSH_D(su_debug_log("su_context_real2logical: %d => %d\n", cxix, cxix - gaps));
2475 /* convert a logical context stack index (one that ignores all the context
2476 * frames hidden by uplevel) into the physical equivalent
2479 static I32 su_context_logical2real(pTHX_ I32 cxix) {
2480 # define su_context_logical2real(C) su_context_logical2real(aTHX_ (C))
2484 for (i = 0; i <= cxstack_ix; i++) {
2485 PERL_CONTEXT *cx = cxstack + i;
2486 if (cx->cx_type != (CXt_NULL | CXp_SU_UPLEVEL_NULLED))
2491 XSH_D(su_debug_log("su_context_logical2real: %d => %d\n", cxix, i));
2498 # define su_context_real2logical(C) (C)
2499 # define su_context_logical2real(C) (C)
2503 static I32 su_context_normalize_up(pTHX_ I32 cxix) {
2504 #define su_context_normalize_up(C) su_context_normalize_up(aTHX_ (C))
2510 cx = cxstack + cxix;
2511 if (CxTYPE(cx) == CXt_BLOCK) {
2512 PERL_CONTEXT *prev = cx - 1;
2514 switch (CxTYPE(prev)) {
2515 #if XSH_HAS_PERL(5, 10, 0)
2519 #if XSH_HAS_PERL(5, 11, 0)
2520 /* That's the only subcategory that can cause an extra BLOCK context */
2521 case CXt_LOOP_PLAIN:
2525 if (cx->blk_oldcop == prev->blk_oldcop)
2529 if (cx->blk_oldcop && OpSIBLING(cx->blk_oldcop)
2530 && OpSIBLING(cx->blk_oldcop)->op_type == OP_SUBST)
2539 static I32 su_context_normalize_down(pTHX_ I32 cxix) {
2540 #define su_context_normalize_down(C) su_context_normalize_down(aTHX_ (C))
2543 if (cxix >= cxstack_ix)
2546 next = cxstack + cxix + 1;
2547 if (CxTYPE(next) == CXt_BLOCK) {
2548 PERL_CONTEXT *cx = next - 1;
2550 switch (CxTYPE(cx)) {
2551 #if XSH_HAS_PERL(5, 10, 0)
2555 #if XSH_HAS_PERL(5, 11, 0)
2556 /* That's the only subcategory that can cause an extra BLOCK context */
2557 case CXt_LOOP_PLAIN:
2561 if (cx->blk_oldcop == next->blk_oldcop)
2565 if (next->blk_oldcop && OpSIBLING(next->blk_oldcop)
2566 && OpSIBLING(next->blk_oldcop)->op_type == OP_SUBST)
2575 #define su_context_here() su_context_normalize_up(su_context_skip_db(cxstack_ix))
2577 static I32 su_context_gimme(pTHX_ I32 cxix) {
2578 #define su_context_gimme(C) su_context_gimme(aTHX_ (C))
2581 for (i = cxix; i >= 0; --i) {
2582 PERL_CONTEXT *cx = cxstack + i;
2584 switch (CxTYPE(cx)) {
2585 /* gimme is always G_ARRAY for loop contexts. */
2586 #if XSH_HAS_PERL(5, 11, 0)
2587 # if XSH_HAS_PERL(5, 23, 8)
2593 case CXt_LOOP_PLAIN:
2594 case CXt_LOOP_LAZYSV:
2595 case CXt_LOOP_LAZYIV:
2600 const COP *cop = cx->blk_oldcop;
2601 if (cop && OpSIBLING(cop)) {
2602 switch (OpSIBLING(cop)->op_flags & OPf_WANT) {
2605 case OPf_WANT_SCALAR:
2624 /* --- Module setup/teardown ----------------------------------------------- */
2626 static void xsh_user_global_setup(pTHX) {
2629 MUTEX_INIT(&su_uid_seq_counter_mutex);
2631 XSH_LOCK(&su_uid_seq_counter_mutex);
2632 su_uid_seq_counter.seqs = NULL;
2633 su_uid_seq_counter.size = 0;
2634 XSH_UNLOCK(&su_uid_seq_counter_mutex);
2636 stash = gv_stashpv(XSH_PACKAGE, 1);
2637 newCONSTSUB(stash, "TOP", newSViv(0));
2638 newCONSTSUB(stash, "SU_THREADSAFE", newSVuv(XSH_THREADSAFE));
2643 static void xsh_user_local_setup(pTHX_ xsh_user_cxt_t *cxt) {
2645 /* NewOp() calls calloc() which just zeroes the memory with memset(). */
2646 Zero(&(cxt->unwind_storage.return_op), 1, LISTOP);
2647 cxt->unwind_storage.return_op.op_type = OP_RETURN;
2648 cxt->unwind_storage.return_op.op_ppaddr = PL_ppaddr[OP_RETURN];
2650 Zero(&(cxt->unwind_storage.proxy_op), 1, OP);
2651 cxt->unwind_storage.proxy_op.op_type = OP_STUB;
2652 cxt->unwind_storage.proxy_op.op_ppaddr = NULL;
2654 Zero(&(cxt->yield_storage.leave_op), 1, UNOP);
2655 cxt->yield_storage.leave_op.op_type = OP_STUB;
2656 cxt->yield_storage.leave_op.op_ppaddr = NULL;
2658 Zero(&(cxt->yield_storage.proxy_op), 1, OP);
2659 cxt->yield_storage.proxy_op.op_type = OP_STUB;
2660 cxt->yield_storage.proxy_op.op_ppaddr = NULL;
2662 cxt->uplevel_storage.top = NULL;
2663 cxt->uplevel_storage.root = NULL;
2664 cxt->uplevel_storage.count = 0;
2666 cxt->uid_storage.map = NULL;
2667 cxt->uid_storage.used = 0;
2668 cxt->uid_storage.alloc = 0;
2673 static void xsh_user_local_teardown(pTHX_ xsh_user_cxt_t *cxt) {
2676 Safefree(cxt->uid_storage.map);
2678 cur = cxt->uplevel_storage.root;
2680 su_uplevel_ud *prev;
2684 su_uplevel_ud_delete(prev);
2691 static void xsh_user_global_teardown(pTHX) {
2692 XSH_LOCK(&su_uid_seq_counter_mutex);
2693 PerlMemShared_free(su_uid_seq_counter.seqs);
2694 su_uid_seq_counter.size = 0;
2695 XSH_UNLOCK(&su_uid_seq_counter_mutex);
2697 MUTEX_DESTROY(&su_uid_seq_counter_mutex);
2702 /* --- XS ------------------------------------------------------------------ */
2704 /* D is real; B is logical. Returns real. */
2706 #define SU_GET_CONTEXT(A, B, D) \
2715 else if (cxix > cxstack_ix) \
2717 cxix = su_context_logical2real(cxix); \
2724 #define SU_GET_LEVEL(A, B) \
2730 level = SvIV(lsv); \
2737 #if XSH_HAS_PERL(5, 10, 0)
2738 # define SU_INFO_COUNT 11
2740 # define SU_INFO_COUNT 10
2743 XS(XS_Scope__Upper_unwind) {
2752 PERL_UNUSED_VAR(cv); /* -W */
2753 PERL_UNUSED_VAR(ax); /* -Wall */
2755 SU_GET_CONTEXT(0, items - 1, cxstack_ix);
2757 PERL_CONTEXT *cx = cxstack + cxix;
2758 switch (CxTYPE(cx)) {
2760 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2764 XSH_CXT.unwind_storage.cxix = cxix;
2765 XSH_CXT.unwind_storage.items = items;
2766 XSH_CXT.unwind_storage.savesp = PL_stack_sp;
2768 XSH_CXT.unwind_storage.items--;
2769 XSH_CXT.unwind_storage.savesp--;
2771 /* pp_entersub will want to sanitize the stack after returning from there
2772 * Screw that, we're insane!
2773 * dXSARGS calls POPMARK, so we need to match PL_markstack_ptr[1] */
2774 if (GIMME_V == G_SCALAR)
2775 PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
2776 SAVEDESTRUCTOR_X(su_unwind, NULL);
2781 } while (--cxix >= 0);
2782 croak("Can't return outside a subroutine");
2785 static const char su_yield_name[] = "yield";
2787 XS(XS_Scope__Upper_yield) {
2796 PERL_UNUSED_VAR(cv); /* -W */
2797 PERL_UNUSED_VAR(ax); /* -Wall */
2799 SU_GET_CONTEXT(0, items - 1, su_context_here());
2800 XSH_CXT.yield_storage.cxix = cxix;
2801 XSH_CXT.yield_storage.items = items;
2802 XSH_CXT.yield_storage.savesp = PL_stack_sp;
2804 XSH_CXT.yield_storage.items--;
2805 XSH_CXT.yield_storage.savesp--;
2807 /* See XS_Scope__Upper_unwind */
2808 if (GIMME_V == G_SCALAR)
2809 PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
2810 SAVEDESTRUCTOR_X(su_yield, su_yield_name);
2814 static const char su_leave_name[] = "leave";
2816 XS(XS_Scope__Upper_leave) {
2824 PERL_UNUSED_VAR(cv); /* -W */
2825 PERL_UNUSED_VAR(ax); /* -Wall */
2827 XSH_CXT.yield_storage.cxix = su_context_here();
2828 XSH_CXT.yield_storage.items = items;
2829 XSH_CXT.yield_storage.savesp = PL_stack_sp;
2830 /* See XS_Scope__Upper_unwind */
2831 if (GIMME_V == G_SCALAR)
2832 PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
2833 SAVEDESTRUCTOR_X(su_yield, su_leave_name);
2837 MODULE = Scope::Upper PACKAGE = Scope::Upper
2844 newXSproto("Scope::Upper::unwind", XS_Scope__Upper_unwind, file, NULL);
2845 newXSproto("Scope::Upper::yield", XS_Scope__Upper_yield, file, NULL);
2846 newXSproto("Scope::Upper::leave", XS_Scope__Upper_leave, file, NULL);
2858 #endif /* XSH_THREADSAFE */
2866 cxix = su_context_real2logical(su_context_here());
2877 SU_GET_CONTEXT(0, 0, su_context_here());
2880 cxix = su_context_skip_db(cxix);
2881 cxix = su_context_normalize_up(cxix);
2882 cxix = su_context_real2logical(cxix);
2884 warn(su_stack_smash);
2896 SU_GET_CONTEXT(0, 0, cxstack_ix);
2898 for (; cxix >= 0; --cxix) {
2899 PERL_CONTEXT *cx = cxstack + cxix;
2900 switch (CxTYPE(cx)) {
2904 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2906 cxix = su_context_real2logical(cxix);
2911 warn(su_no_such_target, "subroutine");
2920 SU_GET_CONTEXT(0, 0, cxstack_ix);
2922 for (; cxix >= 0; --cxix) {
2923 PERL_CONTEXT *cx = cxstack + cxix;
2924 switch (CxTYPE(cx)) {
2928 cxix = su_context_real2logical(cxix);
2933 warn(su_no_such_target, "eval");
2943 cxix = su_context_here();
2944 while (--level >= 0) {
2946 warn(su_stack_smash);
2950 cxix = su_context_skip_db(cxix);
2951 cxix = su_context_normalize_up(cxix);
2952 cxix = su_context_real2logical(cxix);
2965 for (cxix = cxstack_ix; cxix > 0; --cxix) {
2966 PERL_CONTEXT *cx = cxstack + cxix;
2967 switch (CxTYPE(cx)) {
2969 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2980 warn(su_stack_smash);
2982 cxix = su_context_real2logical(cxix);
2992 SU_GET_CONTEXT(0, 0, cxstack_ix);
2995 PERL_CONTEXT *cx = cxstack + cxix--;
2996 switch (CxTYPE(cx)) {
2998 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
3002 I32 gimme = cx->blk_gimme;
3004 case G_VOID: XSRETURN_UNDEF; break;
3005 case G_SCALAR: XSRETURN_NO; break;
3006 case G_ARRAY: XSRETURN_YES; break;
3019 const PERL_CONTEXT *cx, *dbcx;
3022 SU_GET_CONTEXT(0, 0, su_context_skip_db(cxstack_ix));
3023 cxix = su_context_normalize_up(cxix);
3024 cx = cxstack + cxix;
3026 if (PL_DBsub && cxix && (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT)) {
3027 I32 i = su_context_skip_db(cxix - 1) + 1;
3028 if (i < cxix && CxTYPE(cxstack + i) == CXt_SUB)
3031 cop = cx->blk_oldcop;
3032 EXTEND(SP, SU_INFO_COUNT);
3035 HV *stash = CopSTASH(cop);
3037 PUSHs(su_newmortal_pvn(HvNAME(stash), HvNAMELEN(stash)));
3039 PUSHs(&PL_sv_undef);
3042 PUSHs(su_newmortal_pvn(OutCopFILE(cop), OutCopFILE_len(cop)));
3044 mPUSHi(CopLINE(cop));
3045 /* subroutine (3) and has_args (4) */
3046 switch (CxTYPE(cx)) {
3049 GV *cvgv = CvGV(dbcx->blk_sub.cv);
3050 if (cvgv && isGV(cvgv)) {
3051 SV *sv = sv_newmortal();
3052 gv_efullname3(sv, cvgv, NULL);
3055 PUSHs(su_newmortal_pvs("(unknown)"));
3064 PUSHs(su_newmortal_pvs("(eval)"));
3068 PUSHs(&PL_sv_undef);
3069 PUSHs(&PL_sv_undef);
3072 switch (su_context_gimme(cxix)) {
3079 default: /* G_VOID */
3080 PUSHs(&PL_sv_undef);
3083 /* eval text (6) and is_require (7) */
3084 switch (CxTYPE(cx)) {
3086 if (CxOLD_OP_TYPE(cx) == OP_ENTEREVAL) {
3088 #if XSH_HAS_PERL(5, 17, 4)
3089 PUSHs(newSVpvn_flags(SvPVX(cx->blk_eval.cur_text),
3090 SvCUR(cx->blk_eval.cur_text)-2,
3091 SvUTF8(cx->blk_eval.cur_text)|SVs_TEMP));
3093 PUSHs(cx->blk_eval.cur_text);
3097 } else if (cx->blk_eval.old_namesv) {
3099 PUSHs(sv_mortalcopy(cx->blk_eval.old_namesv));
3105 /* Anything else including eval BLOCK */
3106 PUSHs(&PL_sv_undef);
3107 PUSHs(&PL_sv_undef);
3111 mPUSHi(CopHINTS_get(cop));
3115 #if XSH_HAS_PERL(5, 9, 4)
3116 STRLEN *old_warnings = cop->cop_warnings;
3118 SV *old_warnings = cop->cop_warnings;
3120 if (old_warnings == pWARN_STD) {
3121 if (PL_dowarn & G_WARN_ON)
3122 goto context_info_warnings_on;
3124 #if XSH_HAS_PERL(5, 17, 4)
3125 mask = &PL_sv_undef;
3127 goto context_info_warnings_off;
3129 } else if (old_warnings == pWARN_NONE) {
3130 #if !XSH_HAS_PERL(5, 17, 4)
3131 context_info_warnings_off:
3133 mask = su_newmortal_pvn(WARN_NONEstring, WARNsize);
3134 } else if (old_warnings == pWARN_ALL) {
3136 context_info_warnings_on:
3137 #if XSH_HAS_PERL(5, 8, 7)
3138 bits = get_hv("warnings::Bits", 0);
3140 SV **bits_all = hv_fetchs(bits, "all", FALSE);
3142 mask = sv_mortalcopy(*bits_all);
3146 mask = su_newmortal_pvn(WARN_ALLstring, WARNsize);
3148 #if XSH_HAS_PERL(5, 9, 4)
3149 mask = su_newmortal_pvn((char *) (old_warnings + 1), old_warnings[0]);
3151 mask = sv_mortalcopy(old_warnings);
3156 #if XSH_HAS_PERL(5, 10, 0)
3157 /* hints hash (10) */
3159 COPHH *hints_hash = CopHINTHASH_get(cop);
3161 SV *rhv = sv_2mortal(newRV_noinc((SV *) cophh_2hv(hints_hash, 0)));
3164 PUSHs(&PL_sv_undef);
3168 XSRETURN(SU_INFO_COUNT);
3177 SU_GET_CONTEXT(1, 1, su_context_skip_db(cxstack_ix));
3178 cxix = su_context_normalize_down(cxix);
3179 Newx(ud, 1, su_ud_reap);
3180 SU_UD_TYPE(ud) = SU_UD_TYPE_REAP;
3181 ud->cb = (SvROK(hook) && SvTYPE(SvRV(hook)) >= SVt_PVCV)
3182 ? SvRV(hook) : hook;
3183 SvREFCNT_inc_simple_void(ud->cb);
3184 su_init(ud, cxix, SU_SAVE_DESTRUCTOR_SIZE);
3187 localize(SV *sv, SV *val, ...)
3194 SU_GET_CONTEXT(2, 2, su_context_skip_db(cxstack_ix));
3195 cxix = su_context_normalize_down(cxix);
3196 Newx(ud, 1, su_ud_localize);
3197 SU_UD_TYPE(ud) = SU_UD_TYPE_LOCALIZE;
3198 size = su_ud_localize_init(ud, sv, val, NULL);
3199 su_init(ud, cxix, size);
3202 localize_elem(SV *sv, SV *elem, SV *val, ...)
3209 if (SvTYPE(sv) >= SVt_PVGV)
3210 croak("Can't infer the element localization type from a glob and the value");
3211 SU_GET_CONTEXT(3, 3, su_context_skip_db(cxstack_ix));
3212 cxix = su_context_normalize_down(cxix);
3213 Newx(ud, 1, su_ud_localize);
3214 /* Initialize SU_UD_ORIGIN(ud) in case SU_UD_LOCALIZE_FREE(ud) needs it */
3215 SU_UD_ORIGIN(ud) = NULL;
3216 SU_UD_TYPE(ud) = SU_UD_TYPE_LOCALIZE;
3217 size = su_ud_localize_init(ud, sv, val, elem);
3218 if (SU_UD_PRIVATE(ud) != SVt_PVAV && SU_UD_PRIVATE(ud) != SVt_PVHV) {
3219 SU_UD_LOCALIZE_FREE(ud);
3220 croak("Can't localize an element of something that isn't an array or a hash");
3222 su_init(ud, cxix, size);
3225 localize_delete(SV *sv, SV *elem, ...)
3232 SU_GET_CONTEXT(2, 2, su_context_skip_db(cxstack_ix));
3233 cxix = su_context_normalize_down(cxix);
3234 Newx(ud, 1, su_ud_localize);
3235 SU_UD_TYPE(ud) = SU_UD_TYPE_LOCALIZE;
3236 size = su_ud_localize_init(ud, sv, NULL, elem);
3237 su_init(ud, cxix, size);
3240 uplevel(SV *code, ...)
3243 I32 cxix, ret, args = 0;
3247 if (SvTYPE(code) < SVt_PVCV)
3248 croak("First argument to uplevel must be a code reference");
3249 SU_GET_CONTEXT(1, items - 1, cxstack_ix);
3251 PERL_CONTEXT *cx = cxstack + cxix;
3252 switch (CxTYPE(cx)) {
3254 croak("Can't uplevel to an eval frame");
3256 croak("Can't uplevel to a format frame");
3258 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
3264 /* su_uplevel() takes care of extending the stack if needed. */
3265 #ifdef SU_HAS_NEW_CXT
3266 ret = su_uplevel_new(aTHX_ (CV *) code, cxix, args);
3268 ret = su_uplevel_old(aTHX_ (CV *) code, cxix, args);
3274 } while (--cxix >= 0);
3275 croak("Can't uplevel outside a subroutine");
3284 SU_GET_CONTEXT(0, 0, su_context_here());
3285 uid = su_uid_get(cxix);
3291 validate_uid(SV *uid)
3296 ret = su_uid_validate(uid) ? &PL_sv_yes : &PL_sv_no;