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 #define SU_HAS_NEW_CXT XSH_HAS_PERL(5, 23, 8)
27 # define MUTABLE_SV(S) ((SV *) (S))
31 # define MUTABLE_AV(A) ((AV *) (A))
35 # define MUTABLE_CV(C) ((CV *) (C))
38 #ifndef PERL_UNUSED_VAR
39 # define PERL_UNUSED_VAR(V)
43 # define Newx(v, n, c) New(0, v, n, c)
48 # define SU_POISON(D, N, T) PoisonNew((D), (N), T)
49 # elif defined(Poison)
50 # define SU_POISON(D, N, T) Poison((D), (N), T)
54 # define SU_POISON(D, N, T) NOOP
58 static SV *su_newSV_type(pTHX_ svtype t) {
63 # define newSV_type(T) su_newSV_type(aTHX_ (T))
67 # define su_newmortal_pvn(S, L) newSVpvn_flags((S), (L), SVs_TEMP)
69 # define su_newmortal_pvn(S, L) sv_2mortal(newSVpvn((S), (L)))
71 #define su_newmortal_pvs(S) su_newmortal_pvn((S), sizeof(S)-1)
74 # define SvPV_const(S, L) SvPV(S, L)
78 # define SvPVX_const(S) SvPVX(S)
81 #ifndef SvPV_nolen_const
82 # define SvPV_nolen_const(S) SvPV_nolen(S)
85 #ifndef SvREFCNT_inc_simple_void
86 # define SvREFCNT_inc_simple_void(sv) ((void) SvREFCNT_inc(sv))
90 # define mPUSHi(I) PUSHs(sv_2mortal(newSViv(I)))
94 # define GvCV_set(G, C) (GvCV(G) = (C))
98 # define CvGV_set(C, G) (CvGV(C) = (G))
102 # define CvSTASH_set(C, S) (CvSTASH(C) = (S))
106 # define CvISXSUB(C) CvXSUB(C)
110 # define PadlistARRAY(P) AvARRAY(P)
111 # define PadARRAY(P) AvARRAY(P)
115 # define CxHASARGS(C) ((C)->blk_sub.hasargs)
120 # define CxGIMME(C) ((C)->blk_gimme & G_WANT)
122 # define CxGIMME(C) ((C)->blk_gimme)
126 #ifndef CxOLD_OP_TYPE
127 # define CxOLD_OP_TYPE(C) (C)->blk_eval.old_op_type
131 # define OutCopFILE(C) CopFILE(C)
134 #ifndef OutCopFILE_len
135 # define OutCopFILE_len(C) strlen(OutCopFILE(C))
139 # define CopHINTS_get(C) ((I32) (C)->op_private & HINT_PRIVATE_MASK)
142 #ifndef CopHINTHASH_get
143 # define CopHINTHASH_get(C) (C)->cop_hints_hash
147 # define COPHH struct refcounted_he
148 # define cophh_2hv(H, F) Perl_refcounted_he_chain_2hv(aTHX_ (H))
152 # define HvNAME_get(H) HvNAME(H)
156 # define HvNAMELEN(H) strlen(HvNAME(H))
159 #ifndef gv_fetchpvn_flags
160 # define gv_fetchpvn_flags(A, B, C, D) gv_fetchpv((A), (C), (D))
164 # define hv_fetchs(H, K, L) hv_fetch((H), (K), sizeof(K)-1, (L))
167 #ifndef OP_GIMME_REVERSE
168 static U8 su_op_gimme_reverse(U8 gimme) {
171 return OPf_WANT_VOID;
173 return OPf_WANT_LIST;
178 return OPf_WANT_SCALAR;
180 #define OP_GIMME_REVERSE(G) su_op_gimme_reverse(G)
185 # define OpSIBLING(O) OP_SIBLING(O)
187 # define OpSIBLING(O) ((O)->op_sibling)
191 #ifndef PERL_MAGIC_tied
192 # define PERL_MAGIC_tied 'P'
195 #ifndef PERL_MAGIC_env
196 # define PERL_MAGIC_env 'E'
199 #ifndef NEGATIVE_INDICES_VAR
200 # define NEGATIVE_INDICES_VAR "NEGATIVE_INDICES"
203 /* --- Error messages ------------------------------------------------------ */
205 static const char su_stack_smash[] = "Cannot target a scope outside of the current stack";
206 static const char su_no_such_target[] = "No targetable %s scope in the current stack";
208 /* --- Unique context ID global storage ------------------------------------ */
210 /* ... Sequence ID counter ................................................. */
217 static su_uv_array su_uid_seq_counter;
221 static perl_mutex su_uid_seq_counter_mutex;
223 #endif /* USE_ITHREADS */
225 static UV su_uid_seq_next(pTHX_ UV depth) {
226 #define su_uid_seq_next(D) su_uid_seq_next(aTHX_ (D))
230 XSH_LOCK(&su_uid_seq_counter_mutex);
232 seqs = su_uid_seq_counter.seqs;
234 if (depth >= su_uid_seq_counter.size) {
237 seqs = PerlMemShared_realloc(seqs, (depth + 1) * sizeof(UV));
238 for (i = su_uid_seq_counter.size; i <= depth; ++i)
241 su_uid_seq_counter.seqs = seqs;
242 su_uid_seq_counter.size = depth + 1;
247 XSH_UNLOCK(&su_uid_seq_counter_mutex);
252 /* ... UID storage ......................................................... */
259 #define SU_UID_ACTIVE 1
261 static UV su_uid_depth(pTHX_ I32 cxix) {
262 #define su_uid_depth(I) su_uid_depth(aTHX_ (I))
267 for (si = PL_curstackinfo->si_prev; si; si = si->si_prev)
268 depth += si->si_cxix + 1;
279 static void su_uid_storage_dup(pTHX_ su_uid_storage *new_cxt, const su_uid_storage *old_cxt, UV max_depth) {
280 #define su_uid_storage_dup(N, O, D) su_uid_storage_dup(aTHX_ (N), (O), (D))
281 su_uid *old_map = old_cxt->map;
284 su_uid *new_map = new_cxt->map;
285 STRLEN old_used = old_cxt->used;
286 STRLEN new_used, new_alloc;
289 new_used = max_depth < old_used ? max_depth : old_used;
290 new_cxt->used = new_used;
292 if (new_used <= new_cxt->alloc) {
293 new_alloc = new_cxt->alloc;
295 new_alloc = new_used;
296 Renew(new_map, new_alloc, su_uid);
297 new_cxt->map = new_map;
298 new_cxt->alloc = new_alloc;
301 for (i = 0; i < new_alloc; ++i) {
302 su_uid *new_uid = new_map + i;
304 if (i < new_used) { /* => i < max_depth && i < old_used */
305 su_uid *old_uid = old_map + i;
307 if (old_uid && (old_uid->flags & SU_UID_ACTIVE)) {
321 /* --- unwind() global storage --------------------------------------------- */
331 /* --- yield() global storage ---------------------------------------------- */
341 /* --- uplevel() data tokens and global storage ---------------------------- */
343 #define SU_UPLEVEL_HIJACKS_RUNOPS XSH_HAS_PERL(5, 8, 0)
348 su_uid_storage tmp_uid_storage;
349 su_uid_storage old_uid_storage;
357 U8 *cxtypes; /* array of saved context types */
358 I32 gap; /* how many contexts have temporarily CXt_NULLed out*/
359 AV* argarray; /* the PL_curpad[0] of the uplevel sub */
364 PERL_SI *old_curstackinfo;
373 #if SU_UPLEVEL_HIJACKS_RUNOPS
374 runops_proc_t old_runops;
379 /* used to flag a context stack entry whose type has been temporarily
380 * set to CXt_NULL. It relies on perl not using this value for real
383 # define CXp_SU_UPLEVEL_NULLED 0x20
386 static su_uplevel_ud *su_uplevel_ud_new(pTHX) {
387 #define su_uplevel_ud_new() su_uplevel_ud_new(aTHX)
391 Newx(sud, 1, su_uplevel_ud);
394 sud->tmp_uid_storage.map = NULL;
395 sud->tmp_uid_storage.used = 0;
396 sud->tmp_uid_storage.alloc = 0;
399 Newx(si, 1, PERL_SI);
400 si->si_stack = newAV();
401 AvREAL_off(si->si_stack);
402 si->si_cxstack = NULL;
411 static void su_uplevel_ud_delete(pTHX_ su_uplevel_ud *sud) {
412 #define su_uplevel_ud_delete(S) su_uplevel_ud_delete(aTHX_ (S))
415 PERL_SI *si = sud->si;
417 Safefree(si->si_cxstack);
418 SvREFCNT_dec(si->si_stack);
422 Safefree(sud->tmp_uid_storage.map);
433 } su_uplevel_storage;
435 #ifndef SU_UPLEVEL_STORAGE_SIZE
436 # define SU_UPLEVEL_STORAGE_SIZE 4
439 /* --- Global data --------------------------------------------------------- */
442 su_unwind_storage unwind_storage;
443 su_yield_storage yield_storage;
444 su_uplevel_storage uplevel_storage;
445 su_uid_storage uid_storage;
448 #define XSH_THREADS_USER_CONTEXT 1
449 #define XSH_THREADS_USER_CLONE_NEEDS_DUP 0
450 #define XSH_THREADS_COMPILE_TIME_PROTECTION 0
454 static void xsh_user_clone(pTHX_ const xsh_user_cxt_t *old_cxt, xsh_user_cxt_t *new_cxt) {
455 new_cxt->uplevel_storage.top = NULL;
456 new_cxt->uplevel_storage.root = NULL;
457 new_cxt->uplevel_storage.count = 0;
458 new_cxt->uid_storage.map = NULL;
459 new_cxt->uid_storage.used = 0;
460 new_cxt->uid_storage.alloc = 0;
462 su_uid_storage_dup(&new_cxt->uid_storage, &old_cxt->uid_storage,
463 old_cxt->uid_storage.used);
468 #endif /* XSH_THREADSAFE */
470 #include "xsh/threads.h"
472 /* --- Stack manipulations ------------------------------------------------- */
474 /* how many slots on the save stack various save types take up */
476 #define SU_SAVE_DESTRUCTOR_SIZE 3 /* SAVEt_DESTRUCTOR_X */
477 #define SU_SAVE_SCALAR_SIZE 3 /* SAVEt_SV */
478 #define SU_SAVE_ARY_SIZE 3 /* SAVEt_AV */
479 #define SU_SAVE_AELEM_SIZE 4 /* SAVEt_AELEM */
480 #define SU_SAVE_HASH_SIZE 3 /* SAVEt_HV */
481 #define SU_SAVE_HELEM_SIZE 4 /* SAVEt_HELEM */
482 #define SU_SAVE_HDELETE_SIZE 4 /* SAVEt_DELETE */
484 #define SU_SAVE_GVCV_SIZE SU_SAVE_DESTRUCTOR_SIZE
486 /* the overhead of save_alloc() but not including any elements,
487 * of which there must be at least 1 */
488 #if XSH_HAS_PERL(5, 14, 0)
489 # define SU_SAVE_ALLOC_SIZE 1 /* SAVEt_ALLOC */
491 # define SU_SAVE_ALLOC_SIZE 2 /* SAVEt_ALLOC */
495 # define SU_SAVE_ADELETE_SIZE 3 /* SAVEt_ADELETE */
497 # define SU_SAVE_ADELETE_SIZE SU_SAVE_DESTRUCTOR_SIZE
500 /* (NB: it was 4 between 5.13.1 and 5.13.7) */
501 #if XSH_HAS_PERL(5, 8, 9)
502 # define SU_SAVE_GP_SIZE 3 /* SAVEt_GP */
504 # define SU_SAVE_GP_SIZE 6 /* SAVEt_GP */
507 /* sometimes we don't know in advance whether we're saving or deleting
508 * an array/hash element. So include enough room for a variable-sized
509 * save_alloc() to pad it to a fixed size.
512 #if SU_SAVE_AELEM_SIZE < SU_SAVE_ADELETE_SIZE
513 # define SU_SAVE_AELEM_OR_ADELETE_SIZE \
514 (SU_SAVE_ADELETE_SIZE + SU_SAVE_ALLOC_SIZE + 1)
515 #elif SU_SAVE_AELEM_SIZE > SU_SAVE_ADELETE_SIZE
516 # define SU_SAVE_AELEM_OR_ADELETE_SIZE \
517 (SU_SAVE_AELEM_SIZE + SU_SAVE_ALLOC_SIZE + 1)
519 # define SU_SAVE_AELEM_OR_ADELETE_SIZE SU_SAVE_AELEM_SIZE
522 #if SU_SAVE_HELEM_SIZE < SU_SAVE_HDELETE_SIZE
523 # define SU_SAVE_HELEM_OR_HDELETE_SIZE \
524 (SU_SAVE_HDELETE_SIZE + SU_SAVE_ALLOC_SIZE + 1)
525 #elif SU_SAVE_HELEM_SIZE > SU_SAVE_HDELETE_SIZE
526 # define SU_SAVE_HELEM_OR_HDELETE_SIZE \
527 (SU_SAVE_HELEM_SIZE + SU_SAVE_ALLOC_SIZE + 1)
529 # define SU_SAVE_HELEM_OR_HDELETE_SIZE SU_SAVE_HELEM_SIZE
532 #ifndef SvCANEXISTDELETE
533 # define SvCANEXISTDELETE(sv) \
535 || ((mg = mg_find((SV *) sv, PERL_MAGIC_tied)) \
536 && (stash = SvSTASH(SvRV(SvTIED_obj((SV *) sv, mg)))) \
537 && gv_fetchmethod_autoload(stash, "EXISTS", TRUE) \
538 && gv_fetchmethod_autoload(stash, "DELETE", TRUE) \
543 /* ... Saving array elements ............................................... */
545 static I32 su_av_key2idx(pTHX_ AV *av, I32 key) {
546 #define su_av_key2idx(A, K) su_av_key2idx(aTHX_ (A), (K))
552 /* Added by MJD in perl-5.8.1 with 6f12eb6d2a1dfaf441504d869b27d2e40ef4966a */
553 #if XSH_HAS_PERL(5, 8, 1)
554 if (SvRMAGICAL(av)) {
555 const MAGIC * const tied_magic = mg_find((SV *) av, PERL_MAGIC_tied);
557 SV * const * const negative_indices_glob = hv_fetch(
558 SvSTASH(SvRV(SvTIED_obj((SV *) (av), tied_magic))),
559 NEGATIVE_INDICES_VAR, sizeof(NEGATIVE_INDICES_VAR)-1, 0
561 if (negative_indices_glob && SvTRUE(GvSV(*negative_indices_glob)))
567 idx = key + av_len(av) + 1;
581 static void su_adelete(pTHX_ void *ud_) {
582 su_ud_adelete *ud = (su_ud_adelete *) ud_;
584 av_delete(ud->av, ud->idx, G_DISCARD);
585 SvREFCNT_dec(ud->av);
590 static void su_save_adelete(pTHX_ AV *av, I32 idx) {
591 #define su_save_adelete(A, K) su_save_adelete(aTHX_ (A), (K))
594 Newx(ud, 1, su_ud_adelete);
597 SvREFCNT_inc_simple_void(av);
599 SAVEDESTRUCTOR_X(su_adelete, ud);
602 #define SAVEADELETE(A, K) su_save_adelete((A), (K))
604 #endif /* SAVEADELETE */
606 static void su_save_aelem(pTHX_ AV *av, SV *key, SV *val) {
607 #define su_save_aelem(A, K, V) su_save_aelem(aTHX_ (A), (K), (V))
614 idx = su_av_key2idx(av, SvIV(key));
616 if (SvCANEXISTDELETE(av))
617 preeminent = av_exists(av, idx);
619 svp = av_fetch(av, idx, 1);
620 if (!svp || *svp == &PL_sv_undef) croak(PL_no_aelem, idx);
623 save_aelem(av, idx, svp);
625 SAVEADELETE(av, idx);
627 if (val) { /* local $x[$idx] = $val; */
628 SvSetMagicSV(*svp, val);
629 } else { /* local $x[$idx]; delete $x[$idx]; */
630 av_delete(av, idx, G_DISCARD);
634 /* ... Saving hash elements ................................................ */
636 static void su_save_helem(pTHX_ HV *hv, SV *keysv, SV *val) {
637 #define su_save_helem(H, K, V) su_save_helem(aTHX_ (H), (K), (V))
644 if (SvCANEXISTDELETE(hv) || mg_find((SV *) hv, PERL_MAGIC_env))
645 preeminent = hv_exists_ent(hv, keysv, 0);
647 he = hv_fetch_ent(hv, keysv, 1, 0);
648 svp = he ? &HeVAL(he) : NULL;
649 if (!svp || *svp == &PL_sv_undef) croak("Modification of non-creatable hash value attempted, subscript \"%s\"", SvPV_nolen_const(*svp));
651 if (HvNAME_get(hv) && isGV(*svp)) {
652 save_gp((GV *) *svp, 0);
657 save_helem(hv, keysv, svp);
660 const char * const key = SvPV_const(keysv, keylen);
661 SAVEDELETE(hv, savepvn(key, keylen),
662 SvUTF8(keysv) ? -(I32)keylen : (I32)keylen);
665 if (val) { /* local $x{$keysv} = $val; */
666 SvSetMagicSV(*svp, val);
667 } else { /* local $x{$keysv}; delete $x{$keysv}; */
668 (void)hv_delete_ent(hv, keysv, G_DISCARD, HeHASH(he));
672 /* ... Saving code slots from a glob ....................................... */
674 #if !XSH_HAS_PERL(5, 10, 0) && !defined(mro_method_changed_in)
675 # define mro_method_changed_in(G) PL_sub_generation++
683 static void su_restore_gvcv(pTHX_ void *ud_) {
684 su_save_gvcv_ud *ud = ud_;
687 GvCV_set(gv, ud->old_cv);
689 mro_method_changed_in(GvSTASH(gv));
694 static void su_save_gvcv(pTHX_ GV *gv) {
695 #define su_save_gvcv(G) su_save_gvcv(aTHX_ (G))
698 Newx(ud, 1, su_save_gvcv_ud);
700 ud->old_cv = GvCV(gv);
704 mro_method_changed_in(GvSTASH(gv));
706 SAVEDESTRUCTOR_X(su_restore_gvcv, ud);
709 /* --- Actions ------------------------------------------------------------- */
712 I32 orig_ix; /* original savestack_ix */
713 I32 offset; /* how much we bumped this savestack index */
721 su_ud_origin_elem *origin;
724 #define SU_UD_TYPE(U) (((su_ud_common *) (U))->type)
725 #define SU_UD_PRIVATE(U) (((su_ud_common *) (U))->private)
726 #define SU_UD_DEPTH(U) (((su_ud_common *) (U))->depth)
727 #define SU_UD_ORIGIN(U) (((su_ud_common *) (U))->origin)
729 #define SU_UD_TYPE_REAP 0
730 #define SU_UD_TYPE_LOCALIZE 1
731 #define SU_UD_TYPE_UID 2
733 #define SU_UD_FREE(U) STMT_START { \
734 if (SU_UD_ORIGIN(U)) Safefree(SU_UD_ORIGIN(U)); \
738 /* ... Reap ................................................................ */
740 #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))
747 #define SU_UD_REAP_CB(U) (((su_ud_reap *) (U))->cb)
749 static void su_call(pTHX_ SV *cb) {
752 PERL_CONTEXT saved_cx;
753 #endif /* SU_SAVE_LAST_CX */
757 XSH_D(xsh_debug_log("@@@ call scope_ix=%2d save_ix=%2d\n",
758 PL_scopestack_ix, PL_savestack_ix));
767 /* If the recently popped context isn't saved there, it will be overwritten by
768 * the sub scope from call_sv, although it's still needed in our caller. */
769 cxix = (cxstack_ix < cxstack_max) ? (cxstack_ix + 1) : Perl_cxinc(aTHX);
770 saved_cx = cxstack[cxix];
771 #endif /* SU_SAVE_LAST_CX */
776 cxstack[cxix] = saved_cx;
777 #endif /* SU_SAVE_LAST_CX */
789 /* ... Localize & localize array/hash element .............................. */
798 #define SU_UD_LOCALIZE_SV(U) (((su_ud_localize *) (U))->sv)
799 #define SU_UD_LOCALIZE_VAL(U) (((su_ud_localize *) (U))->val)
800 #define SU_UD_LOCALIZE_ELEM(U) (((su_ud_localize *) (U))->elem)
802 #define SU_UD_LOCALIZE_FREE(U) STMT_START { \
803 SvREFCNT_dec(SU_UD_LOCALIZE_ELEM(U)); \
804 SvREFCNT_dec(SU_UD_LOCALIZE_VAL(U)); \
805 SvREFCNT_dec(SU_UD_LOCALIZE_SV(U)); \
809 static I32 su_ud_localize_init(pTHX_ su_ud_localize *ud, SV *sv, SV *val, SV *elem) {
810 #define su_ud_localize_init(UD, S, V, E) su_ud_localize_init(aTHX_ (UD), (S), (V), (E))
815 SvREFCNT_inc_simple_void(sv);
817 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));
828 } else if (SvROK(sv)) {
829 croak("Invalid %s reference as the localization target",
830 sv_reftype(SvRV(sv), 0));
835 p = SvPV_const(sv, len);
836 for (s = p, l = len; l > 0 && isSPACE(*s); ++s, --l) { }
842 case '$': t = SVt_PV; break;
843 case '@': t = SVt_PVAV; break;
844 case '%': t = SVt_PVHV; break;
845 case '&': t = SVt_PVCV; break;
846 case '*': t = SVt_PVGV; break;
853 } else if (val) { /* t == SVt_NULL, type can't be inferred from the sigil */
854 if (SvROK(val) && !sv_isobject(val)) {
855 t = SvTYPE(SvRV(val));
868 size = elem ? SU_SAVE_AELEM_OR_ADELETE_SIZE
872 size = elem ? SU_SAVE_HELEM_OR_HDELETE_SIZE
876 size = SU_SAVE_GP_SIZE;
879 size = SU_SAVE_GVCV_SIZE;
882 size = SU_SAVE_SCALAR_SIZE;
886 SU_UD_PRIVATE(ud) = t;
891 ud->val = take_ref ? newRV_noinc(val) : val;
895 ud->elem = SvREFCNT_inc(elem);
900 static void su_localize(pTHX_ void *ud_) {
901 #define su_localize(U) su_localize(aTHX_ (U))
902 su_ud_localize *ud = (su_ud_localize *) ud_;
906 svtype t = SU_UD_PRIVATE(ud);
909 if (SvTYPE(sv) >= SVt_PVGV) {
912 /* new perl context implementation frees savestack *before* restoring
913 * PL_curcop. Temporarily restore it prematurely to make gv_fetch*
914 * looks up unqualified var names in the caller's package */
916 COP *old_cop = PL_curcop;
917 PL_curcop = CX_CUR()->blk_oldcop;
921 gv = gv_fetchsv(sv, GV_ADDMULTI, t);
925 const char *name = SvPV_const(sv, len);
926 gv = gv_fetchpvn_flags(name, len, GV_ADDMULTI, t);
931 CX_CUR()->blk_oldcop = old_cop;
938 xsh_debug_log("%p: === localize a %s\n", ud, sv_reftype(z, 0));
939 xsh_debug_log("%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
940 ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
944 /* Inspired from Alias.pm */
948 su_save_aelem(GvAV(gv), elem, val);
956 su_save_helem(GvHV(gv), elem, val);
963 save_gp(gv, 1); /* hide previous entry in symtab */
974 SvSetMagicSV((SV *) gv, val);
979 /* ... Unique context ID ................................................... */
981 /* We must pass the index because XSH_CXT.uid_storage might be reallocated
982 * between the UID fetch and the invalidation at the end of scope. */
989 static void su_uid_drop(pTHX_ void *ud_) {
993 XSH_CXT.uid_storage.map[ud->idx].flags &= ~SU_UID_ACTIVE;
1000 /* --- Pop a context back -------------------------------------------------- */
1003 # define SU_CX_TYPENAME(T) PL_block_type[(T)]
1005 # if XSH_HAS_PERL(5, 23, 8)
1006 static const char *su_block_type[] = {
1021 # elif XSH_HAS_PERL(5, 11, 0)
1022 static const char *su_block_type[] = {
1036 # elif XSH_HAS_PERL(5, 10, 0)
1037 static const char *su_block_type[] = {
1049 static const char *su_block_type[] = {
1059 # define SU_CX_TYPENAME(T) su_block_type[(T)]
1062 #define SU_CXNAME(C) SU_CX_TYPENAME(CxTYPE(C))
1066 /* for debugging. These indicate how many ENTERs each context type
1067 * does before the PUSHBLOCK */
1069 static const int su_cxt_enter_count[] = {
1070 # if XSH_HAS_PERL(5, 23, 8)
1071 0 /* context pushes no longer do ENTERs */
1072 # elif XSH_HAS_PERL(5, 11, 0)
1073 /* NULL WHEN BLOCK GIVEN LOOP_FOR LOOP_PLAIN LOOP_LAZYSV
1074 * LOOP_LAZYIV SUB FORMAT EVAL SUBST */
1075 0, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 0
1076 # elif XSH_HAS_PERL(5, 10, 0)
1077 /* NULL SUB EVAL LOOP SUBST BLOCK FORMAT WHEN GIVEN */
1078 0, 1, 1, 2, 0, 1, 1, 1, 1
1080 /* NULL SUB EVAL LOOP SUBST BLOCK FORMAT */
1085 #endif /* XSH_DEBUG */
1087 /* push at least 'size' slots worth of padding onto the savestack */
1089 static void su_ss_push_padding(pTHX_ void *ud, I32 size) {
1090 #define su_ss_push_padding(U, S) su_ss_push_padding(aTHX_ (U), (S))
1094 if (size < SU_SAVE_ALLOC_SIZE + 1) /* minimum possible SAVEt_ALLOC */
1095 size = SU_SAVE_ALLOC_SIZE + 1;
1097 XSH_D(xsh_debug_log(
1098 "%p: push %2d padding at save_ix=%d\n",
1099 ud, size, PL_savestack_ix));
1101 save_alloc((size - SU_SAVE_ALLOC_SIZE) * sizeof(*PL_savestack), 0);
1106 static void su_pop(pTHX_ void *ud);
1108 /* push an su_pop destructor onto the savestack with suitable padding.
1109 * first indicates that this is the first push of a destructor */
1111 static void su_ss_push_destructor(pTHX_ void *ud, I32 depth, bool first) {
1112 #define su_ss_push_destructor(U, D, F) su_ss_push_destructor(aTHX_ (U), (D), (F))
1113 su_ud_origin_elem *origin = SU_UD_ORIGIN(ud);
1115 assert(first || origin[depth+1].orig_ix == PL_savestack_ix);
1117 su_ss_push_padding(ud,
1118 (origin[depth].orig_ix + origin[depth].offset) - PL_savestack_ix);
1120 XSH_D(xsh_debug_log(
1121 "%p: push destructor at save_ix=%d depth=%d scope_ix=%d\n",
1122 ud, PL_savestack_ix, depth, PL_scopestack_ix));
1124 SAVEDESTRUCTOR_X(su_pop, ud);
1127 PL_savestack_ix <= origin[depth+1].orig_ix + origin[depth+1].offset);
1132 /* this is called during each leave_scope() via SAVEDESTRUCTOR_X */
1134 static void su_pop(pTHX_ void *ud) {
1135 #define su_pop(U) su_pop(aTHX_ (U))
1136 I32 depth, base, mark;
1137 su_ud_origin_elem *origin;
1139 depth = SU_UD_DEPTH(ud);
1140 origin = SU_UD_ORIGIN(ud);
1142 XSH_D(xsh_debug_log("%p: ### su_pop: depth=%d\n", ud, depth));
1145 mark = PL_savestack_ix;
1146 base = origin[depth].orig_ix;
1148 XSH_D(xsh_debug_log("%p: residual savestack frame is %d(+%d)..%d\n",
1149 ud, base, origin[depth].offset, mark));
1152 XSH_D(xsh_debug_log("%p: clear leftovers at %d..%d\n", ud, base, mark));
1155 assert(PL_savestack_ix == base);
1157 SU_UD_DEPTH(ud) = depth;
1160 su_ss_push_destructor(ud, depth-1, 0);
1162 I32 offset = origin[0].offset; /* grab value before origin is freed */
1163 switch (SU_UD_TYPE(ud)) {
1164 case SU_UD_TYPE_REAP: {
1166 xsh_debug_log("%p: === reap\n%p: depth=%d scope_ix=%d save_ix=%d\n",
1167 ud, ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix)
1169 SAVEDESTRUCTOR_X(su_call, SU_UD_REAP_CB(ud));
1173 case SU_UD_TYPE_LOCALIZE:
1175 SU_UD_LOCALIZE_FREE(ud);
1177 case SU_UD_TYPE_UID:
1178 SAVEDESTRUCTOR_X(su_uid_drop, ud);
1181 /* perl 5.23.8 onwards is very fussy about the return from leave_scope()
1182 * leaving PL_savestack_ix where it expects it to be */
1183 if (PL_savestack_ix < base + offset) {
1184 I32 gap = (base + offset) - PL_savestack_ix;
1185 assert(gap >= SU_SAVE_ALLOC_SIZE + 1);
1186 su_ss_push_padding(ud, gap);
1188 assert(PL_savestack_ix == base + offset);
1191 XSH_D(xsh_debug_log("%p: end pop: ss_ix=%d\n", ud, PL_savestack_ix));
1194 /* --- Initialize the stack and the action userdata ------------------------ */
1196 static void su_init(pTHX_ void *ud, I32 cxix, I32 size) {
1197 #define su_init(U, C, S) su_init(aTHX_ (U), (C), (S))
1198 su_ud_origin_elem *origin;
1200 I32 cur_cx_ix, cur_scope_ix;
1202 XSH_D(xsh_debug_log("%p: ### su_init(cxix=%d, size=%d)\n", ud, cxix, size));
1204 depth = PL_scopestack_ix - cxstack[cxix].blk_oldscopesp;
1206 depth += (cxstack_ix - cxix); /* each context frame holds 1 scope */
1208 XSH_D(xsh_debug_log(
1209 "%p: going down by depth=%d with scope_ix=%d save_ix=%d\n",
1210 ud, depth, PL_scopestack_ix, PL_savestack_ix));
1212 /* Artificially increase the position of each savestack frame boundary
1213 * to make space to squeeze in a 'size' sized entry (first one) or a
1214 * SU_SAVE_DESTRUCTOR_SIZE sized entry (higher ones). In addition, make
1215 * sure that each boundary is higher than the previous, so that *every*
1216 * scope exit triggers a call to leave_scope(). Each scope exit will call
1217 * the su_pop() destructor, which is responsible for: freeing any
1218 * savestack entries below the artificially raised floor; then pushing a
1219 * new destructor in that space. On the final pop, the "real" savestack
1220 * action is pushed rather than another destructor.
1222 * On older perls, savestack frame boundaries are specified by a range of
1223 * scopestack entries (one per ENTER). Each scope entry typically does
1224 * one or two ENTERs followed by a PUSHBLOCK. Thus the
1225 * cx->blku_oldscopesp field set by the PUSHBLOCK points to the next free
1226 * slot, which is one above the last of the ENTERs. In the debugging
1227 * output we indicate that by bracketing the ENTERs directly preceding
1228 * that context push with dashes, e.g.:
1230 * 13b98d8: ------------------
1231 * 13b98d8: ENTER origin[0] scope[3] savestack=3+3
1232 * 13b98d8: ENTER origin[1] scope[4] savestack=9+3
1233 * 13b98d8: cx=1 LOOP_LAZYIV
1234 * 13b98d8: ------------------
1236 * In addition to context stack pushes, other activities can push ENTERs
1237 * too, such as grep expr and XS sub calls.
1239 * For newer perls (SU_HAS_NEW_CXT), a context push no longer does any
1240 * ENTERs; instead the old savestack position is stored in the new
1241 * cx->blk_oldsaveix field; thus this field specifies an additional
1242 * savestack frame boundary point in addition to the scopestack entries,
1243 * and will also need adjusting.
1245 * We record the original and modified position of each boundary in the
1248 * The passed cxix argument represents the scope we wish to inject into;
1249 * we have to adjust all the savestack frame boundaries above (but not
1250 * including) that context.
1253 Newx(origin, depth, su_ud_origin_elem);
1256 cur_scope_ix = cxstack[cxix].blk_oldscopesp;
1259 XSH_D(xsh_debug_log("%p: cx=%-2d %-11s\n",
1260 ud, cur_cx_ix, SU_CXNAME(cxstack+cur_cx_ix)));
1264 for (i = 0; cur_scope_ix < PL_scopestack_ix; i++) {
1270 if (cur_cx_ix <= cxstack_ix
1271 && cur_scope_ix == cxstack[cur_cx_ix].blk_oldscopesp)
1272 ixp = &(cxstack[cur_cx_ix++].blk_oldsaveix);
1274 ixp = &PL_scopestack[cur_scope_ix++]; /* an ENTER pushed after cur context */
1279 if (cur_cx_ix <= cxstack_ix) {
1280 if (cur_scope_ix == cxstack[cur_cx_ix].blk_oldscopesp) {
1281 xsh_debug_log("%p: cx=%-2d %s\n%p: ------------------\n",
1282 ud, cur_cx_ix, SU_CXNAME(cxstack+cur_cx_ix), ud);
1285 else if (cur_scope_ix + su_cxt_enter_count[CxTYPE(cxstack+cur_cx_ix)]
1286 == cxstack[cur_cx_ix].blk_oldscopesp)
1287 xsh_debug_log("%p: ------------------\n", ud);
1291 ixp = &PL_scopestack[cur_scope_ix++];
1298 /* we have three constraints to satisfy:
1299 * 1) Each adjusted offset must be at least SU_SAVE_DESTRUCTOR_SIZE
1300 * above its unadjusted boundary, so that there is space to inject a
1301 * destructor into the outer scope.
1302 * 2) Each adjusted boundary must be at least SU_SAVE_DESTRUCTOR_SIZE
1303 * higher than the previous adjusted boundary, so that a new
1304 * destructor can be added below the Nth adjusted frame boundary,
1305 * but be within the (N-1)th adjusted frame and so be triggered on
1306 * the next scope exit;
1307 * 3) If the adjustment needs to be greater than SU_SAVE_DESTRUCTOR_SIZE,
1308 * then it should be greater by an amount of at least the minimum
1309 * pad side, so a destructor and padding can be pushed.
1312 offset = SU_SAVE_DESTRUCTOR_SIZE; /* rule 1 */
1313 pad = (origin[i-1].orig_ix + origin[i-1].offset) + offset
1315 if (pad > 0) { /* rule 2 */
1316 if (pad < SU_SAVE_ALLOC_SIZE + 1) /* rule 3 */
1317 pad = SU_SAVE_ALLOC_SIZE + 1;
1322 origin[i].offset = offset;
1323 origin[i].orig_ix = *ixp;
1328 if (ixp == &PL_scopestack[cur_scope_ix-1])
1330 "%p: ENTER origin[%d] scope[%d] savestack=%d+%d\n",
1331 ud, i, cur_scope_ix, origin[i].orig_ix, origin[i].offset);
1334 "%p: cx=%-2d %-11s origin[%d] scope[%d] savestack=%d+%d\n",
1335 ud, cur_cx_ix-1, SU_CXNAME(cxstack+cur_cx_ix-1),
1336 i, cur_scope_ix, origin[i].orig_ix, origin[i].offset);
1339 XSH_D(xsh_debug_log(
1340 "%p: ENTER origin[%d] scope[%d] savestack=%d+%d\n",
1341 ud, i, cur_scope_ix, origin[i].orig_ix, origin[i].offset));
1348 SU_UD_DEPTH(ud) = depth;
1349 SU_UD_ORIGIN(ud) = origin;
1351 su_ss_push_destructor(ud, depth-1, 1);
1354 /* --- Unwind stack -------------------------------------------------------- */
1356 static void su_unwind(pTHX_ void *ud_) {
1358 I32 cxix = XSH_CXT.unwind_storage.cxix;
1359 I32 items = XSH_CXT.unwind_storage.items;
1362 PERL_UNUSED_VAR(ud_);
1364 PL_stack_sp = XSH_CXT.unwind_storage.savesp;
1365 #if XSH_HAS_PERL(5, 19, 4)
1368 SV **sp = PL_stack_sp;
1369 for (i = -items + 1; i <= 0; ++i)
1371 sv_2mortal(SvREFCNT_inc(sp[i]));
1375 if (cxstack_ix > cxix)
1378 mark = PL_markstack[cxstack[cxix].blk_oldmarksp];
1379 PUSHMARK(PL_stack_sp - items);
1382 I32 gimme = GIMME_V;
1383 xsh_debug_log("%p: cx=%d gimme=%s items=%d sp=%d oldmark=%d mark=%d\n",
1385 gimme == G_VOID ? "void" : gimme == G_ARRAY ? "list" : "scalar",
1386 items, PL_stack_sp - PL_stack_base, *PL_markstack_ptr, mark);
1389 PL_op = (OP *) &(XSH_CXT.unwind_storage.return_op);
1390 PL_op = PL_op->op_ppaddr(aTHX);
1392 *PL_markstack_ptr = mark;
1394 XSH_CXT.unwind_storage.proxy_op.op_next = PL_op;
1395 PL_op = &(XSH_CXT.unwind_storage.proxy_op);
1398 /* --- Yield --------------------------------------------------------------- */
1400 #if XSH_HAS_PERL(5, 10, 0)
1401 # define SU_RETOP_SUB(C) ((C)->blk_sub.retop)
1402 # define SU_RETOP_EVAL(C) ((C)->blk_eval.retop)
1403 # define SU_RETOP_LOOP(C) ((C)->blk_loop.my_op->op_lastop->op_next)
1404 # define SU_RETOP_GIVEN(C) ((C)->blk_givwhen.leave_op->op_next)
1406 # define SU_RETOP_SUB(C) ((C)->blk_oldretsp > 0 ? PL_retstack[(C)->blk_oldretsp - 1] : NULL)
1407 # define SU_RETOP_EVAL(C) SU_RETOP_SUB(C)
1408 # define SU_RETOP_LOOP(C) ((C)->blk_loop.last_op->op_next)
1411 static void su_yield(pTHX_ void *ud_) {
1414 const char *which = ud_;
1415 I32 cxix = XSH_CXT.yield_storage.cxix;
1416 I32 items = XSH_CXT.yield_storage.items;
1417 opcode type = OP_NULL;
1421 cx = cxstack + cxix;
1422 switch (CxTYPE(cx)) {
1424 I32 i, cur = cxstack_ix, n = 1;
1426 /* Is this actually a given/when block? This may occur only when yield was
1427 * called with HERE (or nothing) as the context. */
1428 #if XSH_HAS_PERL(5, 10, 0)
1430 PERL_CONTEXT *prev = cx - 1;
1431 U8 prev_type = CxTYPE(prev);
1432 if ((prev_type == CXt_GIVEN || prev_type == CXt_WHEN)
1433 && (prev->blk_oldcop == cx->blk_oldcop)) {
1436 if (prev_type == CXt_GIVEN)
1445 /* Bare blocks (that appear as do { ... } blocks, map { ... } blocks or
1446 * constant folded blcoks) don't need to save the op to return to anywhere
1447 * since 'last' isn't supposed to work inside them. So we climb higher in
1448 * the context stack until we reach a context that has a return op (i.e. a
1449 * sub, an eval, a format or a real loop), recording how many blocks we
1450 * crossed. Then we follow the op_next chain until we get to the leave op
1451 * that closes the original block, which we are assured to reach since
1452 * everything is static (the blocks we have crossed cannot be evals or
1453 * subroutine calls). */
1454 for (i = cxix + 1; i <= cur; ++i) {
1455 PERL_CONTEXT *cx2 = cxstack + i;
1456 switch (CxTYPE(cx2)) {
1462 o = SU_RETOP_SUB(cx2);
1465 o = SU_RETOP_EVAL(cx2);
1467 #if XSH_HAS_PERL(5, 11, 0)
1468 # if XSH_HAS_PERL(5, 23, 8)
1474 case CXt_LOOP_PLAIN:
1475 case CXt_LOOP_LAZYSV:
1476 case CXt_LOOP_LAZYIV:
1480 o = SU_RETOP_LOOP(cx2);
1489 /* We may find other enter/leave blocks on our way to the matching leave.
1490 * Make sure the depth is incremented/decremented appropriately. */
1491 if (o->op_type == OP_ENTER) {
1493 } else if (o->op_type == OP_LEAVE) {
1507 next = SU_RETOP_SUB(cx);
1510 type = CxTRYBLOCK(cx) ? OP_LEAVETRY : OP_LEAVEEVAL;
1511 next = SU_RETOP_EVAL(cx);
1513 #if XSH_HAS_PERL(5, 11, 0)
1514 # if XSH_HAS_PERL(5, 23, 8)
1520 case CXt_LOOP_PLAIN:
1521 case CXt_LOOP_LAZYSV:
1522 case CXt_LOOP_LAZYIV:
1526 type = OP_LEAVELOOP;
1527 next = SU_RETOP_LOOP(cx);
1529 #if XSH_HAS_PERL(5, 10, 0)
1532 type = OP_LEAVEGIVEN;
1533 next = SU_RETOP_GIVEN(cx);
1537 #if XSH_HAS_PERL(5, 15, 1)
1538 type = OP_LEAVEWHEN;
1541 flags |= OPf_SPECIAL;
1547 croak("%s() can't target a substitution context", which);
1550 croak("%s() doesn't know how to leave a %s context",
1551 which, SU_CXNAME(cxstack + cxix));
1555 PL_stack_sp = XSH_CXT.yield_storage.savesp;
1556 #if XSH_HAS_PERL(5, 19, 4)
1559 SV **sp = PL_stack_sp;
1560 for (i = -items + 1; i <= 0; ++i)
1562 sv_2mortal(SvREFCNT_inc(sp[i]));
1566 if (cxstack_ix > cxix)
1569 /* Copy the arguments passed to yield() where the leave op expects to find
1572 Move(PL_stack_sp - items + 1, PL_stack_base + cx->blk_oldsp + 1, items, SV *);
1573 PL_stack_sp = PL_stack_base + cx->blk_oldsp + items;
1575 flags |= OP_GIMME_REVERSE(cx->blk_gimme);
1577 XSH_CXT.yield_storage.leave_op.op_type = type;
1578 XSH_CXT.yield_storage.leave_op.op_ppaddr = PL_ppaddr[type];
1579 XSH_CXT.yield_storage.leave_op.op_flags = flags;
1580 XSH_CXT.yield_storage.leave_op.op_next = next;
1582 PL_op = (OP *) &(XSH_CXT.yield_storage.leave_op);
1583 PL_op = PL_op->op_ppaddr(aTHX);
1585 XSH_CXT.yield_storage.proxy_op.op_next = PL_op;
1586 PL_op = &(XSH_CXT.yield_storage.proxy_op);
1589 /* --- Uplevel ------------------------------------------------------------- */
1591 #define SU_UPLEVEL_SAVE(f, t) STMT_START { sud->old_##f = PL_##f; PL_##f = (t); } STMT_END
1592 #define SU_UPLEVEL_RESTORE(f) STMT_START { PL_##f = sud->old_##f; } STMT_END
1594 static su_uplevel_ud *su_uplevel_storage_new(pTHX_ I32 cxix) {
1595 #define su_uplevel_storage_new(I) su_uplevel_storage_new(aTHX_ (I))
1600 sud = XSH_CXT.uplevel_storage.root;
1602 XSH_CXT.uplevel_storage.root = sud->next;
1603 XSH_CXT.uplevel_storage.count--;
1605 sud = su_uplevel_ud_new();
1608 sud->next = XSH_CXT.uplevel_storage.top;
1609 XSH_CXT.uplevel_storage.top = sud;
1611 depth = su_uid_depth(cxix);
1612 su_uid_storage_dup(&sud->tmp_uid_storage, &XSH_CXT.uid_storage, depth);
1613 sud->old_uid_storage = XSH_CXT.uid_storage;
1614 XSH_CXT.uid_storage = sud->tmp_uid_storage;
1619 #if XSH_HAS_PERL(5, 13, 7)
1621 static void su_uplevel_storage_delete(pTHX_ su_uplevel_ud *sud) {
1622 #define su_uplevel_storage_delete(S) su_uplevel_storage_delete(aTHX_ (S))
1625 sud->tmp_uid_storage = XSH_CXT.uid_storage;
1626 XSH_CXT.uid_storage = sud->old_uid_storage;
1630 map = sud->tmp_uid_storage.map;
1631 alloc = sud->tmp_uid_storage.alloc;
1632 for (i = 0; i < alloc; ++i)
1633 map[i].flags &= ~SU_UID_ACTIVE;
1635 XSH_CXT.uplevel_storage.top = sud->next;
1637 if (XSH_CXT.uplevel_storage.count >= SU_UPLEVEL_STORAGE_SIZE) {
1638 su_uplevel_ud_delete(sud);
1640 sud->next = XSH_CXT.uplevel_storage.root;
1641 XSH_CXT.uplevel_storage.root = sud;
1642 XSH_CXT.uplevel_storage.count++;
1648 static int su_uplevel_goto_static(const OP *o) {
1649 for (; o; o = OpSIBLING(o)) {
1650 /* goto ops are unops with kids. */
1651 if (!(o->op_flags & OPf_KIDS))
1654 switch (o->op_type) {
1657 /* Don't care about gotos inside eval, as they are forbidden at run time. */
1662 if (su_uplevel_goto_static(((const UNOP *) o)->op_first))
1671 #if !SU_HAS_NEW_CXT && SU_UPLEVEL_HIJACKS_RUNOPS
1673 static int su_uplevel_goto_runops(pTHX) {
1674 #define su_uplevel_goto_runops() su_uplevel_goto_runops(aTHX)
1680 if (op->op_type == OP_GOTO) {
1681 AV *argarray = NULL;
1684 for (cxix = cxstack_ix; cxix >= 0; --cxix) {
1685 const PERL_CONTEXT *cx = cxstack + cxix;
1687 switch (CxTYPE(cx)) {
1689 if (CxHASARGS(cx)) {
1690 argarray = cx->blk_sub.argarray;
1706 if (XSH_CXT.uplevel_storage.top->cxix == cxix) {
1707 AV *args = GvAV(PL_defgv);
1708 I32 items = AvFILLp(args);
1710 av_extend(argarray, items);
1711 Copy(AvARRAY(args), AvARRAY(argarray), items + 1, SV *);
1712 AvFILLp(argarray) = items;
1717 PL_op = op = op->op_ppaddr(aTHX);
1719 #if !XSH_HAS_PERL(5, 13, 0)
1729 #endif /* SU_UPLEVEL_HIJACKS_RUNOPS */
1731 #define su_at_underscore(C) PadARRAY(PadlistARRAY(CvPADLIST(C))[CvDEPTH(C)])[0]
1735 static void su_uplevel_restore_new(pTHX_ void *sus_) {
1736 su_uplevel_ud *sud = sus_;
1739 U8 *saved_cxtypes = sud->cxtypes;
1741 for (i = 0; i < sud->gap; i++) {
1742 PERL_CONTEXT *cx = cxstack + sud->cxix + i;
1743 XSH_D(xsh_debug_log("su_uplevel_restore: i=%d cxix=%d type %s => %s\n",
1744 i, cx-cxstack, SU_CX_TYPENAME(CxTYPE(cx)),
1745 SU_CX_TYPENAME(saved_cxtypes[i] & CXTYPEMASK)));
1746 cx->cx_type = saved_cxtypes[i];
1748 Safefree(saved_cxtypes);
1750 /* renamed is a copy of callback, but they share the same CvPADLIST.
1751 * At this point any calls to renamed should have exited so that its
1752 * depth is back to that of of callback. At this point its safe to free
1753 * renamed, then undo the extra ref count that was ensuring that callback
1756 assert(sud->renamed);
1757 assert(sud->callback);
1759 CvDEPTH(sud->callback)--;
1760 assert(CvDEPTH(sud->callback) == CvDEPTH(sud->renamed));
1761 if (!CvISXSUB(sud->renamed)) {
1762 CvDEPTH(sud->renamed) = 0;
1763 CvPADLIST(sud->renamed) = NULL;
1765 SvREFCNT_dec(sud->renamed);
1766 SvREFCNT_dec(sud->callback);
1768 SU_UPLEVEL_RESTORE(curcop);
1770 su_uplevel_storage_delete(sud);
1777 /* 5.23.7 and earlier */
1779 static void su_uplevel_restore_old(pTHX_ void *sus_) {
1780 su_uplevel_ud *sud = sus_;
1781 PERL_SI *cur = sud->old_curstackinfo;
1782 PERL_SI *si = sud->si;
1784 #if SU_UPLEVEL_HIJACKS_RUNOPS
1785 if (PL_runops == su_uplevel_goto_runops)
1786 PL_runops = sud->old_runops;
1789 if (sud->callback) {
1790 PERL_CONTEXT *cx = cxstack + sud->cxix;
1791 AV *argarray = MUTABLE_AV(su_at_underscore(sud->callback));
1793 /* We have to fix the pad entry for @_ in the original callback because it
1794 * may have been reified. */
1795 if (AvREAL(argarray)) {
1796 const I32 fill = AvFILLp(argarray);
1797 SvREFCNT_dec(argarray);
1799 AvREAL_off(argarray);
1800 AvREIFY_on(argarray);
1801 av_extend(argarray, fill);
1802 su_at_underscore(sud->callback) = MUTABLE_SV(argarray);
1804 CLEAR_ARGARRAY(argarray);
1807 /* If the old cv member is our renamed CV, it means that this place has been
1808 * reached without a goto() happening, and the old argarray member is
1809 * actually our fake argarray. Destroy it properly in that case. */
1810 if (cx->blk_sub.cv == sud->renamed) {
1811 SvREFCNT_dec(cx->blk_sub.argarray);
1812 cx->blk_sub.argarray = argarray;
1815 CvDEPTH(sud->callback)--;
1816 SvREFCNT_dec(sud->callback);
1819 /* Free the renamed CV. We must do it ourselves so that we can force the
1820 * depth to be 0, or perl would complain about it being "still in use".
1821 * But we *know* that it cannot be so. */
1823 if (!CvISXSUB(sud->renamed)) {
1824 CvDEPTH(sud->renamed) = 0;
1825 CvPADLIST(sud->renamed) = NULL;
1827 SvREFCNT_dec(sud->renamed);
1830 CATCH_SET(sud->old_catch);
1832 SU_UPLEVEL_RESTORE(op);
1834 /* stack_grow() wants PL_curstack so restore the old stack first */
1835 if (PL_curstackinfo == si) {
1836 PL_curstack = cur->si_stack;
1837 if (sud->old_mainstack)
1838 SU_UPLEVEL_RESTORE(mainstack);
1839 SU_UPLEVEL_RESTORE(curstackinfo);
1842 CV *target = sud->target;
1845 /* When we die, the depth of the target CV is not updated because of the
1846 * stack switcheroo. So we have to look at all the frames between the
1847 * uplevel call and the catch block to count how many call frames to the
1848 * target CV were skipped. */
1849 for (i = cur->si_cxix; i > sud->cxix; i--) {
1850 register const PERL_CONTEXT *cx = cxstack + i;
1852 if (CxTYPE(cx) == CXt_SUB) {
1853 if (cx->blk_sub.cv == target)
1858 /* If we died, the replacement stack was already unwinded to the first
1859 * eval frame, and all the contexts down there were popped. We don't have
1860 * to pop manually any context of the original stack, because they must
1861 * have been in the replacement stack as well (since the second was copied
1862 * from the first). Thus we only have to make sure the original stack index
1863 * points to the context just below the first eval scope under the target
1865 for (; i >= 0; i--) {
1866 register const PERL_CONTEXT *cx = cxstack + i;
1868 switch (CxTYPE(cx)) {
1870 if (cx->blk_sub.cv == target)
1882 CvDEPTH(target) = sud->target_depth - levels;
1883 PL_curstackinfo->si_cxix = i - 1;
1885 #if !XSH_HAS_PERL(5, 13, 1)
1886 /* Since $@ was maybe localized between the target frame and the uplevel
1887 * call, we forcefully flush the save stack to get rid of it and then
1888 * reset $@ to its proper value. Note that the the call to
1889 * su_uplevel_restore() must happen before the "reset $@" item of the save
1890 * stack is processed, as uplevel was called after the localization.
1891 * Andrew's changes to how $@ was handled, which were mainly integrated
1892 * between perl 5.13.0 and 5.13.1, fixed this. */
1893 if (ERRSV && SvTRUE(ERRSV)) {
1894 register const PERL_CONTEXT *cx = cxstack + i; /* This is the eval scope */
1895 SV *errsv = SvREFCNT_inc(ERRSV);
1896 PL_scopestack_ix = cx->blk_oldscopesp;
1897 leave_scope(PL_scopestack[PL_scopestack_ix]);
1898 sv_setsv(ERRSV, errsv);
1899 SvREFCNT_dec(errsv);
1905 SU_UPLEVEL_RESTORE(curcop);
1907 SvREFCNT_dec(sud->target);
1909 PL_stack_base = AvARRAY(cur->si_stack);
1910 PL_stack_sp = PL_stack_base + AvFILLp(cur->si_stack);
1911 PL_stack_max = PL_stack_base + AvMAX(cur->si_stack);
1913 /* When an exception is thrown from the uplevel'd subroutine,
1914 * su_uplevel_restore() may be called by the LEAVE in die_unwind() (renamed
1915 * die_where() in more recent perls), which has the sad habit of keeping a
1916 * pointer to the current context frame across this call. This means that we
1917 * can't free the temporary context stack we used for the uplevel call right
1918 * now, or that pointer upwards would point to garbage. */
1919 #if XSH_HAS_PERL(5, 13, 7)
1920 /* This issue has been fixed in perl with commit 8f89e5a9, which was made
1921 * public in perl 5.13.7. */
1922 su_uplevel_storage_delete(sud);
1924 /* Otherwise, we just enqueue it back in the global storage list. */
1928 sud->tmp_uid_storage = XSH_CXT.uid_storage;
1929 XSH_CXT.uid_storage = sud->old_uid_storage;
1931 XSH_CXT.uplevel_storage.top = sud->next;
1932 sud->next = XSH_CXT.uplevel_storage.root;
1933 XSH_CXT.uplevel_storage.root = sud;
1934 XSH_CXT.uplevel_storage.count++;
1943 static CV *su_cv_clone(pTHX_ CV *proto, GV *gv) {
1944 #define su_cv_clone(P, G) su_cv_clone(aTHX_ (P), (G))
1948 cv = MUTABLE_CV(newSV_type(SvTYPE(proto)));
1950 CvFLAGS(cv) = CvFLAGS(proto);
1952 CvFLAGS(cv) &= ~CVf_CVGV_RC;
1954 CvDEPTH(cv) = CvDEPTH(proto);
1956 CvFILE(cv) = CvISXSUB(proto) ? CvFILE(proto) : savepv(CvFILE(proto));
1958 CvFILE(cv) = CvFILE(proto);
1962 #if SU_RELEASE && XSH_HAS_PERL_EXACT(5, 21, 4)
1965 CvSTASH_set(cv, CvSTASH(proto));
1966 /* Commit 4c74a7df, publicized with perl 5.13.3, began to add backrefs to
1967 * stashes. CvSTASH_set() started to do it as well with commit c68d95645
1968 * (which was part of perl 5.13.7). */
1969 #if XSH_HAS_PERL(5, 13, 3) && !XSH_HAS_PERL(5, 13, 7)
1971 Perl_sv_add_backref(aTHX_ CvSTASH(proto), MUTABLE_SV(cv));
1974 if (CvISXSUB(proto)) {
1975 CvXSUB(cv) = CvXSUB(proto);
1976 CvXSUBANY(cv) = CvXSUBANY(proto);
1979 CvROOT(cv) = OpREFCNT_inc(CvROOT(proto));
1981 CvSTART(cv) = CvSTART(proto);
1982 CvPADLIST(cv) = CvPADLIST(proto);
1984 CvOUTSIDE(cv) = CvOUTSIDE(proto);
1985 #ifdef CVf_WEAKOUTSIDE
1986 if (!(CvFLAGS(proto) & CVf_WEAKOUTSIDE))
1988 SvREFCNT_inc_simple_void(CvOUTSIDE(cv));
1989 #ifdef CvOUTSIDE_SEQ
1990 CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(proto);
1994 sv_setpvn(MUTABLE_SV(cv), SvPVX_const(proto), SvCUR(proto));
2006 /* this one-shot runops "loop" is designed to be called just before
2007 * execution of the first op following an uplevel()'s entersub. It gets a
2008 * chance to fix up the args as seen by caller(), before immediately
2009 * falling through to the previous runops loop. Note that pp_entersub is
2010 * called directly by call_sv() rather than being called from a runops
2014 static int su_uplevel_runops_hook_entersub(pTHX) {
2017 su_uplevel_ud *sud = XSH_CXT.uplevel_storage.top;
2019 /* Create a new array containing a copy of the original sub's call args,
2020 * then stick it in PL_curpad[0] of the current running sub so that
2021 * thay will be seen by caller().
2024 if (sud->argarray) {
2028 av_extend(av, AvMAX(sud->argarray));
2029 AvFILLp(av) = AvFILLp(sud->argarray);
2030 Copy(AvARRAY(sud->argarray), AvARRAY(av), AvFILLp(av) + 1, SV *);
2032 /* should be referenced by PL_curpad[0] and *_ */
2033 assert(SvREFCNT(PL_curpad[0]) > 1);
2034 SvREFCNT_dec(PL_curpad[0]);
2036 PL_curpad[0] = (SV *) av;
2039 /* undo the temporary runops hook and fall through to a real runops loop. */
2040 assert(sud->old_runops != su_uplevel_runops_hook_entersub);
2041 PL_runops = sud->old_runops;
2048 static I32 su_uplevel_new(pTHX_ CV *callback, I32 cxix, I32 args) {
2049 #define su_uplevel_new(CB, CX, A) su_uplevel_new(aTHX_ (CB), (CX), (A))
2054 CV *base_cv = cxstack[cxix].blk_sub.cv;
2057 assert(CxTYPE(&cxstack[cxix]) == CXt_SUB);
2063 /* At this point SP points to the top arg.
2064 * Shuffle the args down by one, eliminating the CV slot */
2065 Move(SP - args + 1, SP - args, args, SV *);
2067 PUSHMARK(SP - args);
2070 sud = su_uplevel_storage_new(cxix);
2073 sud->callback = (CV *) SvREFCNT_inc_simple(callback);
2074 sud->renamed = NULL;
2075 sud->gap = cxstack_ix - cxix + 1;
2076 sud->argarray = NULL;
2078 Newx(saved_cxtypes, sud->gap, U8);
2079 sud->cxtypes = saved_cxtypes;
2081 SAVEDESTRUCTOR_X(su_uplevel_restore_new, sud);
2082 SU_UPLEVEL_SAVE(curcop, cxstack[cxix].blk_oldcop);
2084 /* temporarily change the type of any contexts to NULL, so they're
2085 * invisible to caller() etc. */
2086 for (i = 0; i < sud->gap; i++) {
2087 PERL_CONTEXT *cx = cxstack + cxix + i;
2088 saved_cxtypes[i] = cx->cx_type; /* save type and flags */
2089 XSH_D(xsh_debug_log("su_uplevel: i=%d cxix=%d type %-11s => %s\n",
2090 i, cx-cxstack, SU_CX_TYPENAME(CxTYPE(cx)), SU_CX_TYPENAME(CXt_NULL)));
2091 cx->cx_type = (CXt_NULL | CXp_SU_UPLEVEL_NULLED);
2094 /* create a copy of the callback with a doctored name (as seen by
2095 * caller). It shares the padlist with callback */
2096 sud->renamed = su_cv_clone(callback, CvGV(base_cv));
2097 sud->old_runops = PL_runops;
2099 if (!CvISXSUB(sud->renamed) && CxHASARGS(&cxstack[cxix])) {
2100 sud->argarray = (AV *) su_at_underscore(base_cv);
2101 assert(PL_runops != su_uplevel_runops_hook_entersub);
2102 /* set up a one-shot runops hook so that we can fake up the
2103 * args as seen by caller() on return from pp_entersub */
2104 PL_runops = su_uplevel_runops_hook_entersub;
2107 CvDEPTH(callback)++; /* match what CvDEPTH(sud->renamed) is about to become */
2109 ret = call_sv((SV *) sud->renamed, gimme);
2118 static I32 su_uplevel_old(pTHX_ CV *callback, I32 cxix, I32 args) {
2119 #define su_uplevel_old(CB, CX, A) su_uplevel_old(aTHX_ (CB), (CX), (A))
2121 const PERL_CONTEXT *cx = cxstack + cxix;
2123 PERL_SI *cur = PL_curstackinfo;
2129 I32 old_mark, new_mark;
2136 /* Make PL_stack_sp point just before the CV. */
2137 PL_stack_sp -= args + 1;
2138 old_mark = AvFILLp(PL_curstack) = PL_stack_sp - PL_stack_base;
2141 sud = su_uplevel_storage_new(cxix);
2145 sud->callback = NULL;
2146 sud->renamed = NULL;
2147 SAVEDESTRUCTOR_X(su_uplevel_restore_old, sud);
2151 si->si_type = cur->si_type;
2153 si->si_prev = cur->si_prev;
2155 si->si_markoff = cx->blk_oldmarksp;
2158 /* Allocate enough space for all the elements of the original stack up to the
2159 * target context, plus the forthcoming arguments. */
2160 new_mark = cx->blk_oldsp;
2161 av_extend(si->si_stack, new_mark + 1 + args + 1);
2162 Copy(AvARRAY(PL_curstack), AvARRAY(si->si_stack), new_mark + 1, SV *);
2163 AvFILLp(si->si_stack) = new_mark;
2164 SU_POISON(AvARRAY(si->si_stack) + new_mark + 1, args + 1, SV *);
2166 /* Specialized SWITCHSTACK() */
2167 PL_stack_base = AvARRAY(si->si_stack);
2168 old_stack_sp = PL_stack_sp;
2169 PL_stack_sp = PL_stack_base + AvFILLp(si->si_stack);
2170 PL_stack_max = PL_stack_base + AvMAX(si->si_stack);
2173 /* Copy the context stack up to the context just below the target. */
2174 si->si_cxix = (cxix < 0) ? -1 : (cxix - 1);
2175 if (si->si_cxmax < cxix) {
2176 /* The max size must be at least two so that GROW(max) = (max*3)/2 > max */
2177 si->si_cxmax = (cxix < 4) ? 4 : cxix;
2178 Renew(si->si_cxstack, si->si_cxmax + 1, PERL_CONTEXT);
2180 Copy(cur->si_cxstack, si->si_cxstack, cxix, PERL_CONTEXT);
2181 SU_POISON(si->si_cxstack + cxix, si->si_cxmax + 1 - cxix, PERL_CONTEXT);
2183 target = cx->blk_sub.cv;
2184 sud->target = (CV *) SvREFCNT_inc(target);
2185 sud->target_depth = CvDEPTH(target);
2187 /* blk_oldcop is essentially needed for caller() and stack traces. It has no
2188 * run-time implication, since PL_curcop will be overwritten as soon as we
2189 * enter a sub (a sub starts by a nextstate/dbstate). Hence it's safe to just
2190 * make it point to the blk_oldcop for the target frame, so that caller()
2191 * reports the right file name, line number and lexical hints. */
2192 SU_UPLEVEL_SAVE(curcop, cx->blk_oldcop);
2193 /* Don't reset PL_markstack_ptr, or we would overwrite the mark stack below
2194 * this point. Don't reset PL_curpm either, we want the most recent matches. */
2196 SU_UPLEVEL_SAVE(curstackinfo, si);
2197 /* If those two are equal, we need to fool POPSTACK_TO() */
2198 if (PL_mainstack == PL_curstack)
2199 SU_UPLEVEL_SAVE(mainstack, si->si_stack);
2201 sud->old_mainstack = NULL;
2202 PL_curstack = si->si_stack;
2204 renamed = su_cv_clone(callback, CvGV(target));
2205 sud->renamed = renamed;
2208 /* Both SP and old_stack_sp point just before the CV. */
2209 Copy(old_stack_sp + 2, SP + 1, args, SV *);
2211 PUSHs((SV *) renamed);
2214 Zero(&sub_op, 1, UNOP);
2215 sub_op.op_type = OP_ENTERSUB;
2216 sub_op.op_next = NULL;
2217 sub_op.op_flags = OP_GIMME_REVERSE(gimme) | OPf_STACKED;
2219 sub_op.op_flags |= OPpENTERSUB_DB;
2221 SU_UPLEVEL_SAVE(op, (OP *) &sub_op);
2223 #if SU_UPLEVEL_HIJACKS_RUNOPS
2224 sud->old_runops = PL_runops;
2227 sud->old_catch = CATCH_GET;
2230 if ((PL_op = PL_ppaddr[OP_ENTERSUB](aTHX))) {
2231 PERL_CONTEXT *sub_cx = cxstack + cxstack_ix;
2232 AV *argarray = cx->blk_sub.argarray;
2234 /* If pp_entersub() returns a non-null OP, it means that the callback is not
2237 sud->callback = MUTABLE_CV(SvREFCNT_inc(callback));
2238 CvDEPTH(callback)++;
2240 if (CxHASARGS(cx) && argarray) {
2241 /* The call to pp_entersub() has saved the current @_ (in XS terms,
2242 * GvAV(PL_defgv)) in the savearray member, and has created a new argarray
2243 * with what we put on the stack. But we want to fake up the same arguments
2244 * as the ones in use at the context we uplevel to, so we replace the
2245 * argarray with an unreal copy of the original @_. */
2249 av_extend(av, AvMAX(argarray));
2250 AvFILLp(av) = AvFILLp(argarray);
2251 Copy(AvARRAY(argarray), AvARRAY(av), AvFILLp(av) + 1, SV *);
2252 sub_cx->blk_sub.argarray = av;
2254 SvREFCNT_inc_simple_void(sub_cx->blk_sub.argarray);
2257 if (su_uplevel_goto_static(CvROOT(renamed))) {
2258 #if SU_UPLEVEL_HIJACKS_RUNOPS
2259 if (PL_runops != PL_runops_std) {
2260 if (PL_runops == PL_runops_dbg) {
2262 croak("uplevel() can't execute code that calls goto when debugging flags are set");
2263 } else if (PL_runops != su_uplevel_goto_runops)
2264 croak("uplevel() can't execute code that calls goto with a custom runloop");
2267 PL_runops = su_uplevel_goto_runops;
2268 #else /* SU_UPLEVEL_HIJACKS_RUNOPS */
2269 croak("uplevel() can't execute code that calls goto before perl 5.8");
2270 #endif /* !SU_UPLEVEL_HIJACKS_RUNOPS */
2278 ret = PL_stack_sp - (PL_stack_base + new_mark);
2280 AV *old_stack = sud->old_curstackinfo->si_stack;
2282 if (old_mark + ret > AvMAX(old_stack)) {
2283 /* Specialized EXTEND(old_sp, ret) */
2284 av_extend(old_stack, old_mark + ret + 1);
2285 old_stack_sp = AvARRAY(old_stack) + old_mark;
2288 Copy(PL_stack_sp - ret + 1, old_stack_sp + 1, ret, SV *);
2290 AvFILLp(old_stack) += ret;
2300 /* --- Unique context ID --------------------------------------------------- */
2302 static su_uid *su_uid_storage_fetch(pTHX_ UV depth) {
2303 #define su_uid_storage_fetch(D) su_uid_storage_fetch(aTHX_ (D))
2308 map = XSH_CXT.uid_storage.map;
2309 alloc = XSH_CXT.uid_storage.alloc;
2311 if (depth >= alloc) {
2314 Renew(map, depth + 1, su_uid);
2315 for (i = alloc; i <= depth; ++i) {
2320 XSH_CXT.uid_storage.map = map;
2321 XSH_CXT.uid_storage.alloc = depth + 1;
2324 if (depth >= XSH_CXT.uid_storage.used)
2325 XSH_CXT.uid_storage.used = depth + 1;
2330 static int su_uid_storage_check(pTHX_ UV depth, UV seq) {
2331 #define su_uid_storage_check(D, S) su_uid_storage_check(aTHX_ (D), (S))
2335 if (depth >= XSH_CXT.uid_storage.used)
2338 uid = XSH_CXT.uid_storage.map + depth;
2340 return (uid->seq == seq) && (uid->flags & SU_UID_ACTIVE);
2343 static SV *su_uid_get(pTHX_ I32 cxix) {
2344 #define su_uid_get(I) su_uid_get(aTHX_ (I))
2349 depth = su_uid_depth(cxix);
2350 uid = su_uid_storage_fetch(depth);
2352 if (!(uid->flags & SU_UID_ACTIVE)) {
2355 uid->seq = su_uid_seq_next(depth);
2356 uid->flags |= SU_UID_ACTIVE;
2358 Newx(ud, 1, su_ud_uid);
2359 SU_UD_TYPE(ud) = SU_UD_TYPE_UID;
2361 su_init(ud, cxix, SU_SAVE_DESTRUCTOR_SIZE);
2364 uid_sv = sv_newmortal();
2365 sv_setpvf(uid_sv, "%"UVuf"-%"UVuf, depth, uid->seq);
2372 #define su_grok_number(S, L, VP) grok_number((S), (L), (VP))
2374 #else /* grok_number */
2376 #define IS_NUMBER_IN_UV 0x1
2378 static int su_grok_number(pTHX_ const char *s, STRLEN len, UV *valuep) {
2379 #define su_grok_number(S, L, VP) su_grok_number(aTHX_ (S), (L), (VP))
2383 /* This crude check should be good enough for a fallback implementation.
2384 * Better be too strict than too lax. */
2385 for (i = 0; i < len; ++i) {
2390 tmpsv = sv_newmortal();
2391 sv_setpvn(tmpsv, s, len);
2392 *valuep = sv_2uv(tmpsv);
2394 return IS_NUMBER_IN_UV;
2397 #endif /* !grok_number */
2399 static int su_uid_validate(pTHX_ SV *uid) {
2400 #define su_uid_validate(U) su_uid_validate(aTHX_ (U))
2406 s = SvPV_const(uid, len);
2408 while (p < len && s[p] != '-')
2411 croak("UID contains only one part");
2413 type = su_grok_number(s, p, &depth);
2414 if (type != IS_NUMBER_IN_UV)
2415 croak("First UID part is not an unsigned integer");
2417 ++p; /* Skip '-'. As we used to have p < len, len - (p + 1) >= 0. */
2419 type = su_grok_number(s + p, len - p, &seq);
2420 if (type != IS_NUMBER_IN_UV)
2421 croak("Second UID part is not an unsigned integer");
2423 return su_uid_storage_check(depth, seq);
2426 /* --- Context operations -------------------------------------------------- */
2428 /* Remove sequences of BLOCKs having DB for stash, followed by a SUB context
2429 * for the debugger callback. */
2431 static I32 su_context_skip_db(pTHX_ I32 cxix) {
2432 #define su_context_skip_db(C) su_context_skip_db(aTHX_ (C))
2438 for (i = cxix; i > 0; --i) {
2439 PERL_CONTEXT *cx = cxstack + i;
2441 switch (CxTYPE(cx)) {
2442 #if XSH_HAS_PERL(5, 17, 1)
2443 case CXt_LOOP_PLAIN:
2446 if (cx->blk_oldcop && CopSTASH(cx->blk_oldcop) == GvSTASH(PL_DBgv))
2450 if (cx->blk_sub.cv == GvCV(PL_DBsub)) {
2467 /* convert a physical context stack index into the logical equivalent:
2468 * one that ignores all the context frames hidden by uplevel().
2469 * Perl-level functions use logical args (e.g. UP takes an optional logical
2470 * value and returns a logical value), while we use and store *real*
2471 * values internally.
2474 static I32 su_context_real2logical(pTHX_ I32 cxix) {
2475 # define su_context_real2logical(C) su_context_real2logical(aTHX_ (C))
2479 for (i = 0; i <= cxix; i++) {
2481 if (cx->cx_type == (CXt_NULL | CXp_SU_UPLEVEL_NULLED))
2485 XSH_D(xsh_debug_log("su_context_real2logical: %d => %d\n", cxix, cxix - gaps));
2490 /* convert a logical context stack index (one that ignores all the context
2491 * frames hidden by uplevel) into the physical equivalent
2494 static I32 su_context_logical2real(pTHX_ I32 cxix) {
2495 # define su_context_logical2real(C) su_context_logical2real(aTHX_ (C))
2499 for (i = 0; i <= cxstack_ix; i++) {
2500 PERL_CONTEXT *cx = cxstack + i;
2501 if (cx->cx_type != (CXt_NULL | CXp_SU_UPLEVEL_NULLED))
2507 XSH_D(xsh_debug_log("su_context_logical2real: %d => %d\n", cxix, i));
2516 # define su_context_real2logical(C) (C)
2517 # define su_context_logical2real(C) (C)
2520 static I32 su_context_normalize_up(pTHX_ I32 cxix) {
2521 #define su_context_normalize_up(C) su_context_normalize_up(aTHX_ (C))
2527 cx = cxstack + cxix;
2528 if (CxTYPE(cx) == CXt_BLOCK) {
2529 PERL_CONTEXT *prev = cx - 1;
2531 switch (CxTYPE(prev)) {
2532 #if XSH_HAS_PERL(5, 10, 0)
2536 #if XSH_HAS_PERL(5, 11, 0)
2537 /* That's the only subcategory that can cause an extra BLOCK context */
2538 case CXt_LOOP_PLAIN:
2542 if (cx->blk_oldcop == prev->blk_oldcop)
2546 if (cx->blk_oldcop && OpSIBLING(cx->blk_oldcop)
2547 && OpSIBLING(cx->blk_oldcop)->op_type == OP_SUBST)
2556 static I32 su_context_normalize_down(pTHX_ I32 cxix) {
2557 #define su_context_normalize_down(C) su_context_normalize_down(aTHX_ (C))
2560 if (cxix >= cxstack_ix)
2563 next = cxstack + cxix + 1;
2564 if (CxTYPE(next) == CXt_BLOCK) {
2565 PERL_CONTEXT *cx = next - 1;
2567 switch (CxTYPE(cx)) {
2568 #if XSH_HAS_PERL(5, 10, 0)
2572 #if XSH_HAS_PERL(5, 11, 0)
2573 /* That's the only subcategory that can cause an extra BLOCK context */
2574 case CXt_LOOP_PLAIN:
2578 if (cx->blk_oldcop == next->blk_oldcop)
2582 if (next->blk_oldcop && OpSIBLING(next->blk_oldcop)
2583 && OpSIBLING(next->blk_oldcop)->op_type == OP_SUBST)
2592 #define su_context_here() su_context_normalize_up(su_context_skip_db(cxstack_ix))
2594 static I32 su_context_gimme(pTHX_ I32 cxix) {
2595 #define su_context_gimme(C) su_context_gimme(aTHX_ (C))
2598 for (i = cxix; i >= 0; --i) {
2599 PERL_CONTEXT *cx = cxstack + i;
2601 switch (CxTYPE(cx)) {
2602 /* gimme is always G_ARRAY for loop contexts. */
2603 #if XSH_HAS_PERL(5, 11, 0)
2604 # if XSH_HAS_PERL(5, 23, 8)
2610 case CXt_LOOP_PLAIN:
2611 case CXt_LOOP_LAZYSV:
2612 case CXt_LOOP_LAZYIV:
2617 const COP *cop = cx->blk_oldcop;
2618 if (cop && OpSIBLING(cop)) {
2619 switch (OpSIBLING(cop)->op_flags & OPf_WANT) {
2622 case OPf_WANT_SCALAR:
2641 /* --- Module setup/teardown ----------------------------------------------- */
2643 static void xsh_user_global_setup(pTHX) {
2646 MUTEX_INIT(&su_uid_seq_counter_mutex);
2648 XSH_LOCK(&su_uid_seq_counter_mutex);
2649 su_uid_seq_counter.seqs = NULL;
2650 su_uid_seq_counter.size = 0;
2651 XSH_UNLOCK(&su_uid_seq_counter_mutex);
2653 stash = gv_stashpv(XSH_PACKAGE, 1);
2654 newCONSTSUB(stash, "TOP", newSViv(0));
2655 newCONSTSUB(stash, "SU_THREADSAFE", newSVuv(XSH_THREADSAFE));
2660 static void xsh_user_local_setup(pTHX_ xsh_user_cxt_t *cxt) {
2662 /* NewOp() calls calloc() which just zeroes the memory with memset(). */
2663 Zero(&(cxt->unwind_storage.return_op), 1, LISTOP);
2664 cxt->unwind_storage.return_op.op_type = OP_RETURN;
2665 cxt->unwind_storage.return_op.op_ppaddr = PL_ppaddr[OP_RETURN];
2667 Zero(&(cxt->unwind_storage.proxy_op), 1, OP);
2668 cxt->unwind_storage.proxy_op.op_type = OP_STUB;
2669 cxt->unwind_storage.proxy_op.op_ppaddr = NULL;
2671 Zero(&(cxt->yield_storage.leave_op), 1, UNOP);
2672 cxt->yield_storage.leave_op.op_type = OP_STUB;
2673 cxt->yield_storage.leave_op.op_ppaddr = NULL;
2675 Zero(&(cxt->yield_storage.proxy_op), 1, OP);
2676 cxt->yield_storage.proxy_op.op_type = OP_STUB;
2677 cxt->yield_storage.proxy_op.op_ppaddr = NULL;
2679 cxt->uplevel_storage.top = NULL;
2680 cxt->uplevel_storage.root = NULL;
2681 cxt->uplevel_storage.count = 0;
2683 cxt->uid_storage.map = NULL;
2684 cxt->uid_storage.used = 0;
2685 cxt->uid_storage.alloc = 0;
2690 static void xsh_user_local_teardown(pTHX_ xsh_user_cxt_t *cxt) {
2693 Safefree(cxt->uid_storage.map);
2695 cur = cxt->uplevel_storage.root;
2697 su_uplevel_ud *prev;
2701 su_uplevel_ud_delete(prev);
2708 static void xsh_user_global_teardown(pTHX) {
2709 XSH_LOCK(&su_uid_seq_counter_mutex);
2710 PerlMemShared_free(su_uid_seq_counter.seqs);
2711 su_uid_seq_counter.size = 0;
2712 XSH_UNLOCK(&su_uid_seq_counter_mutex);
2714 MUTEX_DESTROY(&su_uid_seq_counter_mutex);
2719 /* --- XS ------------------------------------------------------------------ */
2721 /* D is real; B is logical. Returns real. */
2723 #define SU_GET_CONTEXT(A, B, D) \
2732 else if (cxix > cxstack_ix) \
2734 cxix = su_context_logical2real(cxix); \
2741 #define SU_GET_LEVEL(A, B) \
2747 level = SvIV(lsv); \
2754 #if XSH_HAS_PERL(5, 10, 0)
2755 # define SU_INFO_COUNT 11
2757 # define SU_INFO_COUNT 10
2760 XS(XS_Scope__Upper_unwind) {
2769 PERL_UNUSED_VAR(cv); /* -W */
2770 PERL_UNUSED_VAR(ax); /* -Wall */
2772 SU_GET_CONTEXT(0, items - 1, cxstack_ix);
2774 PERL_CONTEXT *cx = cxstack + cxix;
2775 switch (CxTYPE(cx)) {
2777 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2781 XSH_CXT.unwind_storage.cxix = cxix;
2782 XSH_CXT.unwind_storage.items = items;
2783 XSH_CXT.unwind_storage.savesp = PL_stack_sp;
2785 XSH_CXT.unwind_storage.items--;
2786 XSH_CXT.unwind_storage.savesp--;
2788 /* pp_entersub will want to sanitize the stack after returning from there
2789 * Screw that, we're insane!
2790 * dXSARGS calls POPMARK, so we need to match PL_markstack_ptr[1] */
2791 if (GIMME_V == G_SCALAR)
2792 PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
2793 SAVEDESTRUCTOR_X(su_unwind, NULL);
2798 } while (--cxix >= 0);
2799 croak("Can't return outside a subroutine");
2802 static const char su_yield_name[] = "yield";
2804 XS(XS_Scope__Upper_yield) {
2813 PERL_UNUSED_VAR(cv); /* -W */
2814 PERL_UNUSED_VAR(ax); /* -Wall */
2816 SU_GET_CONTEXT(0, items - 1, su_context_here());
2817 XSH_CXT.yield_storage.cxix = cxix;
2818 XSH_CXT.yield_storage.items = items;
2819 XSH_CXT.yield_storage.savesp = PL_stack_sp;
2821 XSH_CXT.yield_storage.items--;
2822 XSH_CXT.yield_storage.savesp--;
2824 /* See XS_Scope__Upper_unwind */
2825 if (GIMME_V == G_SCALAR)
2826 PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
2827 SAVEDESTRUCTOR_X(su_yield, su_yield_name);
2831 static const char su_leave_name[] = "leave";
2833 XS(XS_Scope__Upper_leave) {
2841 PERL_UNUSED_VAR(cv); /* -W */
2842 PERL_UNUSED_VAR(ax); /* -Wall */
2844 XSH_CXT.yield_storage.cxix = su_context_here();
2845 XSH_CXT.yield_storage.items = items;
2846 XSH_CXT.yield_storage.savesp = PL_stack_sp;
2847 /* See XS_Scope__Upper_unwind */
2848 if (GIMME_V == G_SCALAR)
2849 PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
2851 SAVEDESTRUCTOR_X(su_yield, su_leave_name);
2856 MODULE = Scope::Upper PACKAGE = Scope::Upper
2863 newXSproto("Scope::Upper::unwind", XS_Scope__Upper_unwind, file, NULL);
2864 newXSproto("Scope::Upper::yield", XS_Scope__Upper_yield, file, NULL);
2865 newXSproto("Scope::Upper::leave", XS_Scope__Upper_leave, file, NULL);
2877 #endif /* XSH_THREADSAFE */
2885 cxix = su_context_real2logical(su_context_here());
2896 SU_GET_CONTEXT(0, 0, su_context_here());
2899 cxix = su_context_skip_db(cxix);
2900 cxix = su_context_normalize_up(cxix);
2901 cxix = su_context_real2logical(cxix);
2903 warn(su_stack_smash);
2915 SU_GET_CONTEXT(0, 0, cxstack_ix);
2917 for (; cxix >= 0; --cxix) {
2918 PERL_CONTEXT *cx = cxstack + cxix;
2919 switch (CxTYPE(cx)) {
2923 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2925 cxix = su_context_real2logical(cxix);
2930 warn(su_no_such_target, "subroutine");
2939 SU_GET_CONTEXT(0, 0, cxstack_ix);
2941 for (; cxix >= 0; --cxix) {
2942 PERL_CONTEXT *cx = cxstack + cxix;
2943 switch (CxTYPE(cx)) {
2947 cxix = su_context_real2logical(cxix);
2952 warn(su_no_such_target, "eval");
2962 cxix = su_context_here();
2963 while (--level >= 0) {
2965 warn(su_stack_smash);
2969 cxix = su_context_skip_db(cxix);
2970 cxix = su_context_normalize_up(cxix);
2971 cxix = su_context_real2logical(cxix);
2984 for (cxix = cxstack_ix; cxix > 0; --cxix) {
2985 PERL_CONTEXT *cx = cxstack + cxix;
2986 switch (CxTYPE(cx)) {
2988 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2999 warn(su_stack_smash);
3001 cxix = su_context_real2logical(cxix);
3011 SU_GET_CONTEXT(0, 0, cxstack_ix);
3014 PERL_CONTEXT *cx = cxstack + cxix--;
3015 switch (CxTYPE(cx)) {
3017 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
3021 I32 gimme = cx->blk_gimme;
3023 case G_VOID: XSRETURN_UNDEF; break;
3024 case G_SCALAR: XSRETURN_NO; break;
3025 case G_ARRAY: XSRETURN_YES; break;
3038 const PERL_CONTEXT *cx, *dbcx;
3041 SU_GET_CONTEXT(0, 0, su_context_skip_db(cxstack_ix));
3042 cxix = su_context_normalize_up(cxix);
3043 cx = cxstack + cxix;
3045 if (PL_DBsub && cxix && (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT)) {
3046 I32 i = su_context_skip_db(cxix - 1) + 1;
3047 if (i < cxix && CxTYPE(cxstack + i) == CXt_SUB)
3050 cop = cx->blk_oldcop;
3051 EXTEND(SP, SU_INFO_COUNT);
3054 HV *stash = CopSTASH(cop);
3056 PUSHs(su_newmortal_pvn(HvNAME(stash), HvNAMELEN(stash)));
3058 PUSHs(&PL_sv_undef);
3061 PUSHs(su_newmortal_pvn(OutCopFILE(cop), OutCopFILE_len(cop)));
3063 mPUSHi(CopLINE(cop));
3064 /* subroutine (3) and has_args (4) */
3065 switch (CxTYPE(cx)) {
3068 GV *cvgv = CvGV(dbcx->blk_sub.cv);
3069 if (cvgv && isGV(cvgv)) {
3070 SV *sv = sv_newmortal();
3071 gv_efullname3(sv, cvgv, NULL);
3074 PUSHs(su_newmortal_pvs("(unknown)"));
3083 PUSHs(su_newmortal_pvs("(eval)"));
3087 PUSHs(&PL_sv_undef);
3088 PUSHs(&PL_sv_undef);
3091 switch (su_context_gimme(cxix)) {
3098 default: /* G_VOID */
3099 PUSHs(&PL_sv_undef);
3102 /* eval text (6) and is_require (7) */
3103 switch (CxTYPE(cx)) {
3105 if (CxOLD_OP_TYPE(cx) == OP_ENTEREVAL) {
3107 #if XSH_HAS_PERL(5, 17, 4)
3108 PUSHs(newSVpvn_flags(SvPVX(cx->blk_eval.cur_text),
3109 SvCUR(cx->blk_eval.cur_text)-2,
3110 SvUTF8(cx->blk_eval.cur_text)|SVs_TEMP));
3112 PUSHs(cx->blk_eval.cur_text);
3116 } else if (cx->blk_eval.old_namesv) {
3118 PUSHs(sv_mortalcopy(cx->blk_eval.old_namesv));
3124 /* Anything else including eval BLOCK */
3125 PUSHs(&PL_sv_undef);
3126 PUSHs(&PL_sv_undef);
3130 mPUSHi(CopHINTS_get(cop));
3134 #if XSH_HAS_PERL(5, 9, 4)
3135 STRLEN *old_warnings = cop->cop_warnings;
3137 SV *old_warnings = cop->cop_warnings;
3139 if (old_warnings == pWARN_STD) {
3140 if (PL_dowarn & G_WARN_ON)
3141 goto context_info_warnings_on;
3143 #if XSH_HAS_PERL(5, 17, 4)
3144 mask = &PL_sv_undef;
3146 goto context_info_warnings_off;
3148 } else if (old_warnings == pWARN_NONE) {
3149 #if !XSH_HAS_PERL(5, 17, 4)
3150 context_info_warnings_off:
3152 mask = su_newmortal_pvn(WARN_NONEstring, WARNsize);
3153 } else if (old_warnings == pWARN_ALL) {
3155 context_info_warnings_on:
3156 #if XSH_HAS_PERL(5, 8, 7)
3157 bits = get_hv("warnings::Bits", 0);
3159 SV **bits_all = hv_fetchs(bits, "all", FALSE);
3161 mask = sv_mortalcopy(*bits_all);
3165 mask = su_newmortal_pvn(WARN_ALLstring, WARNsize);
3167 #if XSH_HAS_PERL(5, 9, 4)
3168 mask = su_newmortal_pvn((char *) (old_warnings + 1), old_warnings[0]);
3170 mask = sv_mortalcopy(old_warnings);
3175 #if XSH_HAS_PERL(5, 10, 0)
3176 /* hints hash (10) */
3178 COPHH *hints_hash = CopHINTHASH_get(cop);
3180 SV *rhv = sv_2mortal(newRV_noinc((SV *) cophh_2hv(hints_hash, 0)));
3183 PUSHs(&PL_sv_undef);
3187 XSRETURN(SU_INFO_COUNT);
3196 SU_GET_CONTEXT(1, 1, su_context_skip_db(cxstack_ix));
3197 cxix = su_context_normalize_down(cxix);
3198 Newx(ud, 1, su_ud_reap);
3199 SU_UD_TYPE(ud) = SU_UD_TYPE_REAP;
3200 ud->cb = (SvROK(hook) && SvTYPE(SvRV(hook)) >= SVt_PVCV)
3201 ? SvRV(hook) : hook;
3202 SvREFCNT_inc_simple_void(ud->cb);
3203 su_init(ud, cxix, SU_SAVE_DESTRUCTOR_SIZE);
3206 localize(SV *sv, SV *val, ...)
3213 SU_GET_CONTEXT(2, 2, su_context_skip_db(cxstack_ix));
3214 cxix = su_context_normalize_down(cxix);
3215 Newx(ud, 1, su_ud_localize);
3216 SU_UD_TYPE(ud) = SU_UD_TYPE_LOCALIZE;
3217 size = su_ud_localize_init(ud, sv, val, NULL);
3218 su_init(ud, cxix, size);
3221 localize_elem(SV *sv, SV *elem, SV *val, ...)
3228 if (SvTYPE(sv) >= SVt_PVGV)
3229 croak("Can't infer the element localization type from a glob and the value");
3230 SU_GET_CONTEXT(3, 3, su_context_skip_db(cxstack_ix));
3231 cxix = su_context_normalize_down(cxix);
3232 Newx(ud, 1, su_ud_localize);
3233 /* Initialize SU_UD_ORIGIN(ud) in case SU_UD_LOCALIZE_FREE(ud) needs it */
3234 SU_UD_ORIGIN(ud) = NULL;
3235 SU_UD_TYPE(ud) = SU_UD_TYPE_LOCALIZE;
3236 size = su_ud_localize_init(ud, sv, val, elem);
3237 if (SU_UD_PRIVATE(ud) != SVt_PVAV && SU_UD_PRIVATE(ud) != SVt_PVHV) {
3238 SU_UD_LOCALIZE_FREE(ud);
3239 croak("Can't localize an element of something that isn't an array or a hash");
3241 su_init(ud, cxix, size);
3244 localize_delete(SV *sv, SV *elem, ...)
3251 SU_GET_CONTEXT(2, 2, su_context_skip_db(cxstack_ix));
3252 cxix = su_context_normalize_down(cxix);
3253 Newx(ud, 1, su_ud_localize);
3254 SU_UD_TYPE(ud) = SU_UD_TYPE_LOCALIZE;
3255 size = su_ud_localize_init(ud, sv, NULL, elem);
3256 su_init(ud, cxix, size);
3259 uplevel(SV *code, ...)
3262 I32 cxix, ret, args = 0;
3266 if (SvTYPE(code) < SVt_PVCV)
3267 croak("First argument to uplevel must be a code reference");
3268 SU_GET_CONTEXT(1, items - 1, cxstack_ix);
3270 PERL_CONTEXT *cx = cxstack + cxix;
3271 switch (CxTYPE(cx)) {
3273 croak("Can't uplevel to an eval frame");
3275 croak("Can't uplevel to a format frame");
3277 if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
3283 /* su_uplevel() takes care of extending the stack if needed. */
3285 ret = su_uplevel_new((CV *) code, cxix, args);
3287 ret = su_uplevel_old((CV *) code, cxix, args);
3293 } while (--cxix >= 0);
3294 croak("Can't uplevel outside a subroutine");
3303 SU_GET_CONTEXT(0, 0, su_context_here());
3304 uid = su_uid_get(cxix);
3310 validate_uid(SV *uid)
3315 ret = su_uid_validate(uid) ? &PL_sv_yes : &PL_sv_no;