]> git.vpit.fr Git - perl/modules/Scope-Upper.git/blob - Upper.xs
fix uplevel() under 5.23.8+
[perl/modules/Scope-Upper.git] / Upper.xs
1 /* This file is part of the Scope::Upper Perl module.
2  * See http://search.cpan.org/dist/Scope-Upper/ */
3
4 #define PERL_NO_GET_CONTEXT
5 #include "EXTERN.h"
6 #include "perl.h"
7 #include "XSUB.h"
8
9 /* --- XS helpers ---------------------------------------------------------- */
10
11 #define XSH_PACKAGE "Scope::Upper"
12
13 #include "xsh/caps.h"
14 #include "xsh/util.h"
15 #include "xsh/debug.h"
16
17 /* --- Compatibility ------------------------------------------------------- */
18
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
22 #endif
23
24
25 #ifndef dVAR
26 # define dVAR dNOOP
27 #endif
28
29 #ifndef MUTABLE_SV
30 # define MUTABLE_SV(S) ((SV *) (S))
31 #endif
32
33 #ifndef MUTABLE_AV
34 # define MUTABLE_AV(A) ((AV *) (A))
35 #endif
36
37 #ifndef MUTABLE_CV
38 # define MUTABLE_CV(C) ((CV *) (C))
39 #endif
40
41 #ifndef PERL_UNUSED_VAR
42 # define PERL_UNUSED_VAR(V)
43 #endif
44
45 #ifndef Newx
46 # define Newx(v, n, c) New(0, v, n, c)
47 #endif
48
49 #ifdef DEBUGGING
50 # ifdef PoisonNew
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)
54 # endif
55 #endif
56 #ifndef SU_POISON
57 # define SU_POISON(D, N, T) NOOP
58 #endif
59
60 #ifndef newSV_type
61 static SV *su_newSV_type(pTHX_ svtype t) {
62  SV *sv = newSV(0);
63  SvUPGRADE(sv, t);
64  return sv;
65 }
66 # define newSV_type(T) su_newSV_type(aTHX_ (T))
67 #endif
68
69 #ifdef newSVpvn_flags
70 # define su_newmortal_pvn(S, L) newSVpvn_flags((S), (L), SVs_TEMP)
71 #else
72 # define su_newmortal_pvn(S, L) sv_2mortal(newSVpvn((S), (L)))
73 #endif
74 #define su_newmortal_pvs(S) su_newmortal_pvn((S), sizeof(S)-1)
75
76 #ifndef SvPV_const
77 # define SvPV_const(S, L) SvPV(S, L)
78 #endif
79
80 #ifndef SvPVX_const
81 # define SvPVX_const(S) SvPVX(S)
82 #endif
83
84 #ifndef SvPV_nolen_const
85 # define SvPV_nolen_const(S) SvPV_nolen(S)
86 #endif
87
88 #ifndef SvREFCNT_inc_simple_void
89 # define SvREFCNT_inc_simple_void(sv) ((void) SvREFCNT_inc(sv))
90 #endif
91
92 #ifndef mPUSHi
93 # define mPUSHi(I) PUSHs(sv_2mortal(newSViv(I)))
94 #endif
95
96 #ifndef GvCV_set
97 # define GvCV_set(G, C) (GvCV(G) = (C))
98 #endif
99
100 #ifndef CvGV_set
101 # define CvGV_set(C, G) (CvGV(C) = (G))
102 #endif
103
104 #ifndef CvSTASH_set
105 # define CvSTASH_set(C, S) (CvSTASH(C) = (S))
106 #endif
107
108 #ifndef CvISXSUB
109 # define CvISXSUB(C) CvXSUB(C)
110 #endif
111
112 #ifndef PadlistARRAY
113 # define PadlistARRAY(P) AvARRAY(P)
114 # define PadARRAY(P)     AvARRAY(P)
115 #endif
116
117 #ifndef CxHASARGS
118 # define CxHASARGS(C) ((C)->blk_sub.hasargs)
119 #endif
120
121 #ifndef CxGIMME
122 # ifdef G_WANT
123 #  define CxGIMME(C) ((C)->blk_gimme & G_WANT)
124 # else
125 #  define CxGIMME(C) ((C)->blk_gimme)
126 # endif
127 #endif
128
129 #ifndef CxOLD_OP_TYPE
130 # define CxOLD_OP_TYPE(C) (C)->blk_eval.old_op_type
131 #endif
132
133 #ifndef OutCopFILE
134 # define OutCopFILE(C) CopFILE(C)
135 #endif
136
137 #ifndef OutCopFILE_len
138 # define OutCopFILE_len(C) strlen(OutCopFILE(C))
139 #endif
140
141 #ifndef CopHINTS_get
142 # define CopHINTS_get(C) ((I32) (C)->op_private & HINT_PRIVATE_MASK)
143 #endif
144
145 #ifndef CopHINTHASH_get
146 # define CopHINTHASH_get(C) (C)->cop_hints_hash
147 #endif
148
149 #ifndef cophh_2hv
150 # define COPHH           struct refcounted_he
151 # define cophh_2hv(H, F) Perl_refcounted_he_chain_2hv(aTHX_ (H))
152 #endif
153
154 #ifndef HvNAME_get
155 # define HvNAME_get(H) HvNAME(H)
156 #endif
157
158 #ifndef HvNAMELEN
159 # define HvNAMELEN(H) strlen(HvNAME(H))
160 #endif
161
162 #ifndef gv_fetchpvn_flags
163 # define gv_fetchpvn_flags(A, B, C, D) gv_fetchpv((A), (C), (D))
164 #endif
165
166 #ifndef hv_fetchs
167 # define hv_fetchs(H, K, L) hv_fetch((H), (K), sizeof(K)-1, (L))
168 #endif
169
170 #ifndef OP_GIMME_REVERSE
171 static U8 su_op_gimme_reverse(U8 gimme) {
172  switch (gimme) {
173   case G_VOID:
174    return OPf_WANT_VOID;
175   case G_ARRAY:
176    return OPf_WANT_LIST;
177   default:
178    break;
179  }
180
181  return OPf_WANT_SCALAR;
182 }
183 #define OP_GIMME_REVERSE(G) su_op_gimme_reverse(G)
184 #endif
185
186 #ifndef OpSIBLING
187 # ifdef OP_SIBLING
188 #  define OpSIBLING(O) OP_SIBLING(O)
189 # else
190 #  define OpSIBLING(O) ((O)->op_sibling)
191 # endif
192 #endif
193
194 #ifndef PERL_MAGIC_tied
195 # define PERL_MAGIC_tied 'P'
196 #endif
197
198 #ifndef PERL_MAGIC_env
199 # define PERL_MAGIC_env 'E'
200 #endif
201
202 #ifndef NEGATIVE_INDICES_VAR
203 # define NEGATIVE_INDICES_VAR "NEGATIVE_INDICES"
204 #endif
205
206 /* CX_ARGARRAY(cx): the AV at pad[0] of the CV associated with CXt_SUB
207  * context cx */
208
209 #if XSH_HAS_PERL(5, 23, 8)
210 # define CX_ARGARRAY(cx) \
211     ((AV*)(AvARRAY(MUTABLE_AV(                     \
212         PadlistARRAY(CvPADLIST(cx->blk_sub.cv))[   \
213             CvDEPTH(cx->blk_sub.cv)]))[0]))
214 # define CX_ARGARRAY_set(cx,ary) \
215     (AvARRAY(MUTABLE_AV(                     \
216         PadlistARRAY(CvPADLIST(cx->blk_sub.cv))[   \
217             CvDEPTH(cx->blk_sub.cv)]))[0] = (SV*)(ary))
218 #else
219 # define CX_ARGARRAY(cx)         (cx->blk_sub.argarray)
220 # define CX_ARGARRAY_set(cx,ary) (cx->blk_sub.argarray = (ary))
221 #endif
222
223
224 /* --- Error messages ------------------------------------------------------ */
225
226 static const char su_stack_smash[]    = "Cannot target a scope outside of the current stack";
227 static const char su_no_such_target[] = "No targetable %s scope in the current stack";
228
229 /* --- Unique context ID global storage ------------------------------------ */
230
231 /* ... Sequence ID counter ................................................. */
232
233 typedef struct {
234  UV     *seqs;
235  STRLEN  size;
236 } su_uv_array;
237
238 static su_uv_array su_uid_seq_counter;
239
240 #ifdef USE_ITHREADS
241
242 static perl_mutex su_uid_seq_counter_mutex;
243
244 #endif /* USE_ITHREADS */
245
246 static UV su_uid_seq_next(pTHX_ UV depth) {
247 #define su_uid_seq_next(D) su_uid_seq_next(aTHX_ (D))
248  UV seq;
249  UV *seqs;
250
251  XSH_LOCK(&su_uid_seq_counter_mutex);
252
253  seqs = su_uid_seq_counter.seqs;
254
255  if (depth >= su_uid_seq_counter.size) {
256   UV i;
257
258   seqs = PerlMemShared_realloc(seqs, (depth + 1) * sizeof(UV));
259   for (i = su_uid_seq_counter.size; i <= depth; ++i)
260    seqs[i] = 0;
261
262   su_uid_seq_counter.seqs = seqs;
263   su_uid_seq_counter.size = depth + 1;
264  }
265
266  seq = ++seqs[depth];
267
268  XSH_UNLOCK(&su_uid_seq_counter_mutex);
269
270  return seq;
271 }
272
273 /* ... UID storage ......................................................... */
274
275 typedef struct {
276  UV  seq;
277  U32 flags;
278 } su_uid;
279
280 #define SU_UID_ACTIVE 1
281
282 static UV su_uid_depth(pTHX_ I32 cxix) {
283 #define su_uid_depth(I) su_uid_depth(aTHX_ (I))
284  const PERL_SI *si;
285  UV depth;
286
287  depth = cxix;
288  for (si = PL_curstackinfo->si_prev; si; si = si->si_prev)
289   depth += si->si_cxix + 1;
290
291  return depth;
292 }
293
294 typedef struct {
295  su_uid *map;
296  STRLEN  used;
297  STRLEN  alloc;
298 } su_uid_storage;
299
300 static void su_uid_storage_dup(pTHX_ su_uid_storage *new_cxt, const su_uid_storage *old_cxt, UV max_depth) {
301 #define su_uid_storage_dup(N, O, D) su_uid_storage_dup(aTHX_ (N), (O), (D))
302  su_uid *old_map = old_cxt->map;
303
304  if (old_map) {
305   su_uid *new_map  = new_cxt->map;
306   STRLEN  old_used = old_cxt->used;
307   STRLEN  new_used, new_alloc;
308   STRLEN  i;
309
310   new_used      = max_depth < old_used ? max_depth : old_used;
311   new_cxt->used = new_used;
312
313   if (new_used <= new_cxt->alloc) {
314    new_alloc      = new_cxt->alloc;
315   } else {
316    new_alloc      = new_used;
317    Renew(new_map, new_alloc, su_uid);
318    new_cxt->map   = new_map;
319    new_cxt->alloc = new_alloc;
320   }
321
322   for (i = 0; i < new_alloc; ++i) {
323    su_uid *new_uid = new_map + i;
324
325    if (i < new_used) { /* => i < max_depth && i < old_used */
326     su_uid *old_uid = old_map + i;
327
328     if (old_uid && (old_uid->flags & SU_UID_ACTIVE)) {
329      *new_uid = *old_uid;
330      continue;
331     }
332    }
333
334    new_uid->seq   = 0;
335    new_uid->flags = 0;
336   }
337  }
338
339  return;
340 }
341
342 /* --- unwind() global storage --------------------------------------------- */
343
344 typedef struct {
345  I32      cxix;
346  I32      items;
347  SV     **savesp;
348  LISTOP   return_op;
349  OP       proxy_op;
350 } su_unwind_storage;
351
352 /* --- yield() global storage ---------------------------------------------- */
353
354 typedef struct {
355  I32      cxix;
356  I32      items;
357  SV     **savesp;
358  UNOP     leave_op;
359  OP       proxy_op;
360 } su_yield_storage;
361
362 /* --- uplevel() data tokens and global storage ---------------------------- */
363
364 #define SU_UPLEVEL_HIJACKS_RUNOPS XSH_HAS_PERL(5, 8, 0)
365
366 typedef struct {
367  void          *next;
368
369  su_uid_storage tmp_uid_storage;
370  su_uid_storage old_uid_storage;
371
372  I32            cxix;
373
374  CV            *callback;
375  CV            *renamed;
376
377 #ifdef SU_HAS_NEW_CXT
378  U8            *cxtypes; /* array of saved context types */
379  I32           gap;      /* how many contexts have temporarily CXt_NULLed out */
380  AV*           argarray; /* the PL_curpad[0] of the uplevel sub */
381 #else
382  I32            target_depth;
383  CV            *target;
384  PERL_SI       *si;
385  PERL_SI       *old_curstackinfo;
386  AV            *old_mainstack;
387  OP            *old_op;
388  bool           old_catch;
389  bool           died;
390 #endif
391
392  COP           *old_curcop;
393
394 #if SU_UPLEVEL_HIJACKS_RUNOPS
395  runops_proc_t  old_runops;
396 #endif
397 } su_uplevel_ud;
398
399 #ifdef SU_HAS_NEW_CXT
400 /* used to flag a context stack entry whose type has been temporarily
401  * set to CXt_NULL. It relies on perl not using this value for real
402  * CXt_NULL entries.
403  */
404 # define CXp_SU_UPLEVEL_NULLED 0x20
405 #endif
406
407 static su_uplevel_ud *su_uplevel_ud_new(pTHX) {
408 #define su_uplevel_ud_new() su_uplevel_ud_new(aTHX)
409  su_uplevel_ud *sud;
410  PERL_SI       *si;
411
412  Newx(sud, 1, su_uplevel_ud);
413  sud->next = NULL;
414
415  sud->tmp_uid_storage.map   = NULL;
416  sud->tmp_uid_storage.used  = 0;
417  sud->tmp_uid_storage.alloc = 0;
418
419  #ifndef SU_HAS_NEW_CXT
420  Newx(si, 1, PERL_SI);
421  si->si_stack   = newAV();
422  AvREAL_off(si->si_stack);
423  si->si_cxstack = NULL;
424  si->si_cxmax   = -1;
425
426  sud->si = si;
427 #endif
428
429  return sud;
430 }
431
432 static void su_uplevel_ud_delete(pTHX_ su_uplevel_ud *sud) {
433 #define su_uplevel_ud_delete(S) su_uplevel_ud_delete(aTHX_ (S))
434
435 #ifndef SU_HAS_NEW_CXT
436  PERL_SI *si = sud->si;
437
438  Safefree(si->si_cxstack);
439  SvREFCNT_dec(si->si_stack);
440  Safefree(si);
441 #endif
442
443  Safefree(sud->tmp_uid_storage.map);
444
445  Safefree(sud);
446
447  return;
448 }
449
450 typedef struct {
451  su_uplevel_ud *top;
452  su_uplevel_ud *root;
453  I32            count;
454 } su_uplevel_storage;
455
456 #ifndef SU_UPLEVEL_STORAGE_SIZE
457 # define SU_UPLEVEL_STORAGE_SIZE 4
458 #endif
459
460 /* --- Global data --------------------------------------------------------- */
461
462 typedef struct {
463  su_unwind_storage   unwind_storage;
464  su_yield_storage    yield_storage;
465  su_uplevel_storage  uplevel_storage;
466  su_uid_storage      uid_storage;
467 } xsh_user_cxt_t;
468
469 #define XSH_THREADS_USER_CONTEXT            1
470 #define XSH_THREADS_USER_CLONE_NEEDS_DUP    0
471 #define XSH_THREADS_COMPILE_TIME_PROTECTION 0
472
473 #if XSH_THREADSAFE
474
475 static void xsh_user_clone(pTHX_ const xsh_user_cxt_t *old_cxt, xsh_user_cxt_t *new_cxt) {
476  new_cxt->uplevel_storage.top   = NULL;
477  new_cxt->uplevel_storage.root  = NULL;
478  new_cxt->uplevel_storage.count = 0;
479  new_cxt->uid_storage.map   = NULL;
480  new_cxt->uid_storage.used  = 0;
481  new_cxt->uid_storage.alloc = 0;
482
483  su_uid_storage_dup(&new_cxt->uid_storage, &old_cxt->uid_storage,
484                     old_cxt->uid_storage.used);
485
486  return;
487 }
488
489 #endif /* XSH_THREADSAFE */
490
491 #include "xsh/threads.h"
492
493 /* --- Stack manipulations ------------------------------------------------- */
494
495 /* how many slots on the save stack various save types take up */
496
497 #define SU_SAVE_DESTRUCTOR_SIZE 3 /* SAVEt_DESTRUCTOR_X */
498 #define SU_SAVE_SCALAR_SIZE     3 /* SAVEt_SV */
499 #define SU_SAVE_ARY_SIZE        3 /* SAVEt_AV */
500 #define SU_SAVE_AELEM_SIZE      4 /* SAVEt_AELEM */
501 #define SU_SAVE_HASH_SIZE       3 /* SAVEt_HV */
502 #define SU_SAVE_HELEM_SIZE      4 /* SAVEt_HELEM */
503 #define SU_SAVE_HDELETE_SIZE    4 /* SAVEt_DELETE */
504
505 #define SU_SAVE_GVCV_SIZE       SU_SAVE_DESTRUCTOR_SIZE
506
507 /* the overhead of save_alloc() but not including any elements,
508  * of which there must be at least 1 */
509 #if XSH_HAS_PERL(5, 14, 0)
510 # define SU_SAVE_ALLOC_SIZE      1 /* SAVEt_ALLOC */
511 #else
512 # define SU_SAVE_ALLOC_SIZE      2 /* SAVEt_ALLOC */
513 #endif
514
515 #ifdef SAVEADELETE
516 # define SU_SAVE_ADELETE_SIZE   3 /* SAVEt_ADELETE */
517 #else
518 # define SU_SAVE_ADELETE_SIZE   SU_SAVE_DESTRUCTOR_SIZE
519 #endif
520
521 /* (NB: it was 4 between 5.13.1 and 5.13.7) */
522 #if XSH_HAS_PERL(5, 8, 9)
523 # define SU_SAVE_GP_SIZE        3 /* SAVEt_GP */
524 # else
525 # define SU_SAVE_GP_SIZE        6 /* SAVEt_GP */
526 #endif
527
528 /* sometimes we don't know in advance whether we're saving or deleting
529  * an array/hash element. So include enough room for a variable-sized
530  * save_alloc() to pad it to a fixed size.
531  */
532
533 #if SU_SAVE_AELEM_SIZE < SU_SAVE_ADELETE_SIZE
534 # define SU_SAVE_AELEM_OR_ADELETE_SIZE \
535     (SU_SAVE_ADELETE_SIZE + SU_SAVE_ALLOC_SIZE + 1)
536 #elif SU_SAVE_AELEM_SIZE > SU_SAVE_ADELETE_SIZE
537 # define SU_SAVE_AELEM_OR_ADELETE_SIZE \
538     (SU_SAVE_AELEM_SIZE + SU_SAVE_ALLOC_SIZE + 1)
539 #else
540 # define SU_SAVE_AELEM_OR_ADELETE_SIZE SU_SAVE_AELEM_SIZE
541 #endif
542
543 #if SU_SAVE_HELEM_SIZE < SU_SAVE_HDELETE_SIZE
544 # define SU_SAVE_HELEM_OR_HDELETE_SIZE \
545     (SU_SAVE_HDELETE_SIZE + SU_SAVE_ALLOC_SIZE + 1)
546 #elif SU_SAVE_HELEM_SIZE > SU_SAVE_HDELETE_SIZE
547 # define SU_SAVE_HELEM_OR_HDELETE_SIZE \
548     (SU_SAVE_HELEM_SIZE + SU_SAVE_ALLOC_SIZE + 1)
549 #else
550 # define SU_SAVE_HELEM_OR_HDELETE_SIZE SU_SAVE_HELEM_SIZE
551 #endif
552
553
554 #ifndef SvCANEXISTDELETE
555 # define SvCANEXISTDELETE(sv) \
556   (!SvRMAGICAL(sv)            \
557    || ((mg = mg_find((SV *) sv, PERL_MAGIC_tied))            \
558        && (stash = SvSTASH(SvRV(SvTIED_obj((SV *) sv, mg)))) \
559        && gv_fetchmethod_autoload(stash, "EXISTS", TRUE)     \
560        && gv_fetchmethod_autoload(stash, "DELETE", TRUE)     \
561       )                       \
562    )
563 #endif
564
565 /* ... Saving array elements ............................................... */
566
567 static I32 su_av_key2idx(pTHX_ AV *av, I32 key) {
568 #define su_av_key2idx(A, K) su_av_key2idx(aTHX_ (A), (K))
569  I32 idx;
570
571  if (key >= 0)
572   return key;
573
574 /* Added by MJD in perl-5.8.1 with 6f12eb6d2a1dfaf441504d869b27d2e40ef4966a */
575 #if XSH_HAS_PERL(5, 8, 1)
576  if (SvRMAGICAL(av)) {
577   const MAGIC * const tied_magic = mg_find((SV *) av, PERL_MAGIC_tied);
578   if (tied_magic) {
579    SV * const * const negative_indices_glob = hv_fetch(
580     SvSTASH(SvRV(SvTIED_obj((SV *) (av), tied_magic))),
581     NEGATIVE_INDICES_VAR, sizeof(NEGATIVE_INDICES_VAR)-1, 0
582    );
583    if (negative_indices_glob && SvTRUE(GvSV(*negative_indices_glob)))
584     return key;
585   }
586  }
587 #endif
588
589  idx = key + av_len(av) + 1;
590  if (idx < 0)
591   return key;
592
593  return idx;
594 }
595
596 #ifndef SAVEADELETE
597
598 typedef struct {
599  AV *av;
600  I32 idx;
601 } su_ud_adelete;
602
603 static void su_adelete(pTHX_ void *ud_) {
604  su_ud_adelete *ud = (su_ud_adelete *) ud_;
605
606  av_delete(ud->av, ud->idx, G_DISCARD);
607  SvREFCNT_dec(ud->av);
608
609  Safefree(ud);
610 }
611
612 static void su_save_adelete(pTHX_ AV *av, I32 idx) {
613 #define su_save_adelete(A, K) su_save_adelete(aTHX_ (A), (K))
614  su_ud_adelete *ud;
615
616  Newx(ud, 1, su_ud_adelete);
617  ud->av  = av;
618  ud->idx = idx;
619  SvREFCNT_inc_simple_void(av);
620
621  SAVEDESTRUCTOR_X(su_adelete, ud);
622 }
623
624 #define SAVEADELETE(A, K) su_save_adelete((A), (K))
625
626 #endif /* SAVEADELETE */
627
628 static void su_save_aelem(pTHX_ AV *av, SV *key, SV *val) {
629 #define su_save_aelem(A, K, V) su_save_aelem(aTHX_ (A), (K), (V))
630  I32 idx;
631  I32 preeminent = 1;
632  SV **svp;
633  HV *stash;
634  MAGIC *mg;
635
636  idx = su_av_key2idx(av, SvIV(key));
637
638  if (SvCANEXISTDELETE(av))
639   preeminent = av_exists(av, idx);
640
641  svp = av_fetch(av, idx, 1);
642  if (!svp || *svp == &PL_sv_undef) croak(PL_no_aelem, idx);
643
644  if (preeminent)
645   save_aelem(av, idx, svp);
646  else
647   SAVEADELETE(av, idx);
648
649  if (val) { /* local $x[$idx] = $val; */
650   SvSetMagicSV(*svp, val);
651  } else {   /* local $x[$idx]; delete $x[$idx]; */
652   av_delete(av, idx, G_DISCARD);
653  }
654 }
655
656 /* ... Saving hash elements ................................................ */
657
658 static void su_save_helem(pTHX_ HV *hv, SV *keysv, SV *val) {
659 #define su_save_helem(H, K, V) su_save_helem(aTHX_ (H), (K), (V))
660  I32 preeminent = 1;
661  HE *he;
662  SV **svp;
663  HV *stash;
664  MAGIC *mg;
665
666  if (SvCANEXISTDELETE(hv) || mg_find((SV *) hv, PERL_MAGIC_env))
667   preeminent = hv_exists_ent(hv, keysv, 0);
668
669  he  = hv_fetch_ent(hv, keysv, 1, 0);
670  svp = he ? &HeVAL(he) : NULL;
671  if (!svp || *svp == &PL_sv_undef) croak("Modification of non-creatable hash value attempted, subscript \"%s\"", SvPV_nolen_const(*svp));
672
673  if (HvNAME_get(hv) && isGV(*svp)) {
674   save_gp((GV *) *svp, 0);
675   return;
676  }
677
678  if (preeminent)
679   save_helem(hv, keysv, svp);
680  else {
681   STRLEN keylen;
682   const char * const key = SvPV_const(keysv, keylen);
683   SAVEDELETE(hv, savepvn(key, keylen),
684                  SvUTF8(keysv) ? -(I32)keylen : (I32)keylen);
685  }
686
687  if (val) { /* local $x{$keysv} = $val; */
688   SvSetMagicSV(*svp, val);
689  } else {   /* local $x{$keysv}; delete $x{$keysv}; */
690   (void)hv_delete_ent(hv, keysv, G_DISCARD, HeHASH(he));
691  }
692 }
693
694 /* ... Saving code slots from a glob ....................................... */
695
696 #if !XSH_HAS_PERL(5, 10, 0) && !defined(mro_method_changed_in)
697 # define mro_method_changed_in(G) PL_sub_generation++
698 #endif
699
700 typedef struct {
701  GV *gv;
702  CV *old_cv;
703 } su_save_gvcv_ud;
704
705 static void su_restore_gvcv(pTHX_ void *ud_) {
706  su_save_gvcv_ud *ud = ud_;
707  GV              *gv = ud->gv;
708
709  GvCV_set(gv, ud->old_cv);
710  GvCVGEN(gv) = 0;
711  mro_method_changed_in(GvSTASH(gv));
712
713  Safefree(ud);
714 }
715
716 static void su_save_gvcv(pTHX_ GV *gv) {
717 #define su_save_gvcv(G) su_save_gvcv(aTHX_ (G))
718  su_save_gvcv_ud *ud;
719
720  Newx(ud, 1, su_save_gvcv_ud);
721  ud->gv     = gv;
722  ud->old_cv = GvCV(gv);
723
724  GvCV_set(gv, NULL);
725  GvCVGEN(gv) = 0;
726  mro_method_changed_in(GvSTASH(gv));
727
728  SAVEDESTRUCTOR_X(su_restore_gvcv, ud);
729 }
730
731 /* --- Actions ------------------------------------------------------------- */
732
733 typedef struct {
734  I32  orig_ix; /* original savestack_ix */
735  I32  offset;  /* how much we bumped this savestack index */
736 } su_ud_origin_elem;
737
738 typedef struct {
739  U8   type;
740  U8   private;
741  /* spare */
742  I32  depth;
743  su_ud_origin_elem *origin;
744 } su_ud_common;
745
746
747 #define SU_UD_TYPE(U)    (((su_ud_common *) (U))->type)
748 #define SU_UD_PRIVATE(U) (((su_ud_common *) (U))->private)
749 #define SU_UD_DEPTH(U)   (((su_ud_common *) (U))->depth)
750 #define SU_UD_ORIGIN(U)  (((su_ud_common *) (U))->origin)
751
752 #define SU_UD_TYPE_REAP     0
753 #define SU_UD_TYPE_LOCALIZE 1
754 #define SU_UD_TYPE_UID      2
755
756 #define SU_UD_FREE(U) STMT_START { \
757  if (SU_UD_ORIGIN(U)) Safefree(SU_UD_ORIGIN(U)); \
758  Safefree(U); \
759 } STMT_END
760
761 /* ... Reap ................................................................ */
762
763 #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))
764
765 typedef struct {
766  su_ud_common ci;
767  SV          *cb;
768 } su_ud_reap;
769
770 #define SU_UD_REAP_CB(U) (((su_ud_reap *) (U))->cb)
771
772 static void su_call(pTHX_ SV *cb) {
773 #if SU_SAVE_LAST_CX
774  I32 cxix;
775  PERL_CONTEXT saved_cx;
776 #endif /* SU_SAVE_LAST_CX */
777
778  dSP;
779
780  XSH_D(su_debug_log("@@@ call scope_ix=%2d save_ix=%2d\n",
781                           PL_scopestack_ix, PL_savestack_ix));
782
783  ENTER;
784  SAVETMPS;
785
786  PUSHMARK(SP);
787  PUTBACK;
788
789 #if SU_SAVE_LAST_CX
790  /* If the recently popped context isn't saved there, it will be overwritten by
791   * the sub scope from call_sv, although it's still needed in our caller. */
792  cxix     = (cxstack_ix < cxstack_max) ? (cxstack_ix + 1) : Perl_cxinc(aTHX);
793  saved_cx = cxstack[cxix];
794 #endif /* SU_SAVE_LAST_CX */
795
796  call_sv(cb, G_VOID);
797
798 #if SU_SAVE_LAST_CX
799  cxstack[cxix] = saved_cx;
800 #endif /* SU_SAVE_LAST_CX */
801
802  PUTBACK;
803
804  FREETMPS;
805  LEAVE;
806
807  SvREFCNT_dec(cb);
808
809  return;
810 }
811
812 /* ... Localize & localize array/hash element .............................. */
813
814 typedef struct {
815  su_ud_common ci;
816  SV          *sv;
817  SV          *val;
818  SV          *elem;
819 } su_ud_localize;
820
821 #define SU_UD_LOCALIZE_SV(U)   (((su_ud_localize *) (U))->sv)
822 #define SU_UD_LOCALIZE_VAL(U)  (((su_ud_localize *) (U))->val)
823 #define SU_UD_LOCALIZE_ELEM(U) (((su_ud_localize *) (U))->elem)
824
825 #define SU_UD_LOCALIZE_FREE(U) STMT_START { \
826  SvREFCNT_dec(SU_UD_LOCALIZE_ELEM(U)); \
827  SvREFCNT_dec(SU_UD_LOCALIZE_VAL(U)); \
828  SvREFCNT_dec(SU_UD_LOCALIZE_SV(U)); \
829  SU_UD_FREE(U); \
830 } STMT_END
831
832 static I32 su_ud_localize_init(pTHX_ su_ud_localize *ud, SV *sv, SV *val, SV *elem) {
833 #define su_ud_localize_init(UD, S, V, E) su_ud_localize_init(aTHX_ (UD), (S), (V), (E))
834  UV deref = 0;
835  svtype t = SVt_NULL;
836  I32 size;
837
838  SvREFCNT_inc_simple_void(sv);
839
840  if (SvTYPE(sv) >= SVt_PVGV) {
841   if (!val || !SvROK(val)) { /* local *x; or local *x = $val; */
842    t = SVt_PVGV;
843   } else {                   /* local *x = \$val; */
844    t = SvTYPE(SvRV(val));
845    deref = 1;
846   }
847  } else if (SvROK(sv)) {
848   croak("Invalid %s reference as the localization target",
849                  sv_reftype(SvRV(sv), 0));
850  } else {
851   STRLEN len, l;
852   const char *p = SvPV_const(sv, len), *s;
853   for (s = p, l = len; l > 0 && isSPACE(*s); ++s, --l) { }
854   if (!l) {
855    l = len;
856    s = p;
857   }
858   switch (*s) {
859    case '$': t = SVt_PV;   break;
860    case '@': t = SVt_PVAV; break;
861    case '%': t = SVt_PVHV; break;
862    case '&': t = SVt_PVCV; break;
863    case '*': t = SVt_PVGV; break;
864   }
865   if (t != SVt_NULL) {
866    ++s;
867    --l;
868   } else if (val) { /* t == SVt_NULL, type can't be inferred from the sigil */
869    if (SvROK(val) && !sv_isobject(val)) {
870     t = SvTYPE(SvRV(val));
871     deref = 1;
872    } else {
873     t = SvTYPE(val);
874    }
875   }
876   SvREFCNT_dec(sv);
877   sv = newSVpvn(s, l);
878  }
879
880  switch (t) {
881   case SVt_PVAV:
882    size  = elem ? SU_SAVE_AELEM_OR_ADELETE_SIZE
883                 : SU_SAVE_ARY_SIZE;
884    deref = 0;
885    break;
886   case SVt_PVHV:
887    size  = elem ? SU_SAVE_HELEM_OR_HDELETE_SIZE
888                 : SU_SAVE_HASH_SIZE;
889    deref = 0;
890    break;
891   case SVt_PVGV:
892    size  = SU_SAVE_GP_SIZE;
893    deref = 0;
894    break;
895   case SVt_PVCV:
896    size  = SU_SAVE_GVCV_SIZE;
897    deref = 0;
898    break;
899   default:
900    size = SU_SAVE_SCALAR_SIZE;
901    break;
902  }
903  /* When deref is set, val isn't NULL */
904
905  SU_UD_PRIVATE(ud) = t;
906
907  ud->sv   = sv;
908  ud->val  = val ? newSVsv(deref ? SvRV(val) : val) : NULL;
909  ud->elem = SvREFCNT_inc(elem);
910
911  return size;
912 }
913
914 static void su_localize(pTHX_ void *ud_) {
915 #define su_localize(U) su_localize(aTHX_ (U))
916  su_ud_localize *ud = (su_ud_localize *) ud_;
917  SV *sv   = ud->sv;
918  SV *val  = ud->val;
919  SV *elem = ud->elem;
920  svtype t = SU_UD_PRIVATE(ud);
921  GV *gv;
922
923  if (SvTYPE(sv) >= SVt_PVGV) {
924   gv = (GV *) sv;
925  } else {
926
927 /* new perl context implementation frees savestack *before* restoring
928  * PL_curcop. Temporarily restore it prematurely to make gv_fetch*
929  * looks up unqualified var names in the caller's package */
930 #ifdef SU_HAS_NEW_CXT
931   COP *old_cop = PL_curcop;
932   PL_curcop = CX_CUR()->blk_oldcop;
933 #endif
934
935 #ifdef gv_fetchsv
936   gv = gv_fetchsv(sv, GV_ADDMULTI, t);
937 #else
938   STRLEN len;
939   const char *name = SvPV_const(sv, len);
940   gv = gv_fetchpvn_flags(name, len, GV_ADDMULTI, t);
941 #endif
942 #ifdef SU_HAS_NEW_CXT
943   CX_CUR()->blk_oldcop = PL_curcop;
944 #endif
945  }
946
947  XSH_D({
948   SV *z = newSV(0);
949   SvUPGRADE(z, t);
950   su_debug_log("%p:     === localize a %s\n",ud, sv_reftype(z, 0));
951   su_debug_log("%p:         depth=%2d scope_ix=%2d save_ix=%2d\n",
952                 ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
953   SvREFCNT_dec(z);
954  });
955
956  /* Inspired from Alias.pm */
957  switch (t) {
958   case SVt_PVAV:
959    if (elem) {
960     su_save_aelem(GvAV(gv), elem, val);
961     return;
962    } else
963     save_ary(gv);
964    break;
965   case SVt_PVHV:
966    if (elem) {
967     su_save_helem(GvHV(gv), elem, val);
968     return;
969    } else
970     save_hash(gv);
971    break;
972   case SVt_PVGV:
973    save_gp(gv, 1); /* hide previous entry in symtab */
974    break;
975   case SVt_PVCV:
976    su_save_gvcv(gv);
977    break;
978   default:
979    gv = (GV *) save_scalar(gv);
980    break;
981  }
982
983  if (val)
984   SvSetMagicSV((SV *) gv, val);
985
986  return;
987 }
988
989 /* ... Unique context ID ................................................... */
990
991 /* We must pass the index because XSH_CXT.uid_storage might be reallocated
992  * between the UID fetch and the invalidation at the end of scope. */
993
994 typedef struct {
995  su_ud_common ci;
996  I32          idx;
997 } su_ud_uid;
998
999 static void su_uid_drop(pTHX_ void *ud_) {
1000  su_ud_uid *ud = ud_;
1001  dXSH_CXT;
1002
1003  XSH_CXT.uid_storage.map[ud->idx].flags &= ~SU_UID_ACTIVE;
1004
1005  SU_UD_FREE(ud);
1006
1007  return;
1008 }
1009
1010 /* --- Pop a context back -------------------------------------------------- */
1011
1012 #ifdef DEBUGGING
1013 # define SU_CX_TYPENAME(T) PL_block_type[(T)]
1014 #else
1015 # if XSH_HAS_PERL(5, 23, 8)
1016 static const char *su_block_type[] = {
1017  "NULL",
1018  "WHEN",
1019  "BLOCK",
1020  "GIVEN",
1021  "LOOP_ARY",
1022  "LOOP_LAZYSV",
1023  "LOOP_LAZYIV",
1024  "LOOP_LIST",
1025  "LOOP_PLAIN",
1026  "SUB",
1027  "FORMAT",
1028  "EVAL",
1029  "SUBST"
1030 };
1031 # elif XSH_HAS_PERL(5, 11, 0)
1032 static const char *su_block_type[] = {
1033  "NULL",
1034  "WHEN",
1035  "BLOCK",
1036  "GIVEN",
1037  "LOOP_FOR",
1038  "LOOP_PLAIN",
1039  "LOOP_LAZYSV",
1040  "LOOP_LAZYIV",
1041  "SUB",
1042  "FORMAT",
1043  "EVAL",
1044  "SUBST"
1045 };
1046 # elif XSH_HAS_PERL(5, 10, 0)
1047 static const char *su_block_type[] = {
1048  "NULL",
1049  "SUB",
1050  "EVAL",
1051  "LOOP",
1052  "SUBST",
1053  "BLOCK",
1054  "FORMAT"
1055  "WHEN",
1056  "GIVEN"
1057 };
1058 # else
1059 static const char *su_block_type[] = {
1060  "NULL",
1061  "SUB",
1062  "EVAL",
1063  "LOOP",
1064  "SUBST",
1065  "BLOCK",
1066  "FORMAT"
1067 };
1068 # endif
1069 # define SU_CX_TYPENAME(T) su_block_type[(T)]
1070 #endif
1071
1072 #define SU_CXNAME(C) SU_CX_TYPENAME(CxTYPE(C))
1073
1074 /* for debugging. These indicate how many ENTERs each context type
1075  * does before the PUSHBLOCK */
1076
1077 static const int su_cxt_enter_count[] = {
1078 # if XSH_HAS_PERL(5, 23, 8)
1079   0 /* context pushes no longer do ENTERs */
1080 # elif XSH_HAS_PERL(5, 11, 0)
1081  /* NULL WHEN BLOCK GIVEN LOOP_FOR LOOP_PLAIN LOOP_LAZYSV
1082   * LOOP_LAZYIV SUB FORMAT EVAL SUBST */
1083  0, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 0
1084 # elif XSH_HAS_PERL(5, 10, 0)
1085  /* NULL SUB EVAL LOOP SUBST BLOCK FORMAT WHEN GIVEN */
1086  0, 1, 1, 2, 0, 1, 1, 1, 1
1087 # else
1088  /* NULL SUB EVAL LOOP SUBST BLOCK FORMAT */
1089  0, 1, 1, 2, 0, 1, 1
1090 # endif
1091 };
1092
1093
1094
1095 /* push at least 'size' slots worth of padding onto the savestack */
1096
1097 static void su_ss_push_padding(pTHX_ void *ud, I32 size) {
1098  if (size <= 0)
1099   return;
1100  if (size < SU_SAVE_ALLOC_SIZE + 1) /* minimum possible SAVEt_ALLOC */
1101   size = SU_SAVE_ALLOC_SIZE + 1;
1102  XSH_D(su_debug_log(
1103         "%p:     push %2d padding at save_ix=%d\n",
1104          ud, size, PL_savestack_ix));
1105  save_alloc((size - SU_SAVE_ALLOC_SIZE)*sizeof(*PL_savestack), 0);
1106 }
1107
1108
1109 static void su_pop(pTHX_ void *ud);
1110
1111
1112
1113 /* push an su_pop destructor onto the savestack with suitable padding.
1114  * first indicates that this is the first push of a destructor */
1115
1116 static void su_ss_push_destructor(pTHX_ void *ud, I32 depth, bool first) {
1117  su_ud_origin_elem *origin = SU_UD_ORIGIN(ud);
1118  I32 pad;
1119
1120  assert(first || origin[depth+1].orig_ix == PL_savestack_ix);
1121  su_ss_push_padding(aTHX_ ud,
1122     (origin[depth].orig_ix + origin[depth].offset) - PL_savestack_ix);
1123  XSH_D(su_debug_log(
1124         "%p:     push destructor at save_ix=%d depth=%d scope_ix=%d\n",
1125          ud, PL_savestack_ix, depth, PL_scopestack_ix));
1126  SAVEDESTRUCTOR_X(su_pop, ud);
1127  assert(first ||
1128         PL_savestack_ix <= origin[depth+1].orig_ix +  origin[depth+1].offset);
1129 }
1130
1131
1132 /* this is called during each leave_scope() via SAVEDESTRUCTOR_X */
1133
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;
1138
1139  depth  = SU_UD_DEPTH(ud);
1140  origin = SU_UD_ORIGIN(ud);
1141
1142  XSH_D(su_debug_log( "%p: ### su_pop: depth=%d\n", ud, depth));
1143
1144  depth--;
1145  mark = PL_savestack_ix;
1146  base = origin[depth].orig_ix;
1147
1148  XSH_D(su_debug_log("%p:     residual savestack frame is %d(+%d)..%d\n",
1149                      ud, base, origin[depth].offset, mark));
1150
1151  if (base < mark) {
1152   XSH_D(su_debug_log("%p:     clear leftovers at %d..%d\n", ud, base, mark));
1153   leave_scope(base);
1154  }
1155  assert(PL_savestack_ix == base);
1156
1157  SU_UD_DEPTH(ud) = depth;
1158
1159  if (depth > 0) {
1160   su_ss_push_destructor(aTHX_ ud, depth-1, 0);
1161  } else {
1162   I32 offset = origin[0].offset; /* grab value before origin is freed */
1163   switch (SU_UD_TYPE(ud)) {
1164    case SU_UD_TYPE_REAP: {
1165     XSH_D(su_debug_log("%p:     === reap\n%p: depth=%d scope_ix=%d save_ix=%d\n",
1166                    ud, ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix));
1167     SAVEDESTRUCTOR_X(su_call, SU_UD_REAP_CB(ud));
1168     SU_UD_FREE(ud);
1169     break;
1170    }
1171    case SU_UD_TYPE_LOCALIZE:
1172     su_localize(ud);
1173     SU_UD_LOCALIZE_FREE(ud);
1174     break;
1175    case SU_UD_TYPE_UID:
1176     SAVEDESTRUCTOR_X(su_uid_drop, ud);
1177     break;
1178   }
1179   /* perl 5.23.8 onwards is very fussy about the return from leave_scope()
1180    * leaving PL_savestack_ix where it expects it to be */
1181   if (PL_savestack_ix < base + offset) {
1182    I32 gap = (base + offset) - PL_savestack_ix;
1183    assert(gap >= SU_SAVE_ALLOC_SIZE + 1);
1184    su_ss_push_padding(aTHX_ ud, gap);
1185   }
1186   assert(PL_savestack_ix == base + offset);
1187  }
1188
1189  XSH_D(su_debug_log("%p:     end pop: ss_ix=%d\n", ud, PL_savestack_ix));
1190 }
1191
1192
1193 /* --- Initialize the stack and the action userdata ------------------------ */
1194
1195 static void su_init(pTHX_ void *ud, I32 cxix, I32 size) {
1196 #define su_init(U, C, S) su_init(aTHX_ (U), (C), (S))
1197  I32 i, depth, base;
1198  su_ud_origin_elem *origin;
1199  I32 cur_cx_ix;
1200  I32 cur_scope_ix;
1201
1202  XSH_D(su_debug_log("%p: ### su_init(cxix=%d, size=%d)\n", ud, cxix, size));
1203
1204  depth = PL_scopestack_ix - cxstack[cxix].blk_oldscopesp;
1205 #ifdef SU_HAS_NEW_CXT
1206  depth += (cxstack_ix - cxix); /* each context frame holds 1 scope */
1207 #endif
1208  XSH_D(su_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));
1211
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.
1221   *
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.:
1229   *
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:     ------------------
1235   *
1236   * In addition to context stack pushes, other activities can push ENTERs
1237   * too, such as grep expr and XS sub calls.
1238   *
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.
1244   *
1245   * We record the original and modified position of each boundary in the
1246   * origin array.
1247   *
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. 
1251   */
1252
1253  Newx(origin, depth, su_ud_origin_elem);
1254
1255  cur_cx_ix  = cxix;
1256  cur_scope_ix = cxstack[cxix].blk_oldscopesp;
1257 #ifdef SU_HAS_NEW_CXT
1258  XSH_D(su_debug_log("%p:     cx=%-2d %-11s\n",
1259       ud, cur_cx_ix, SU_CXNAME(cxstack+cur_cx_ix)));
1260  cur_cx_ix++;
1261 #endif
1262
1263  for (i = 0; cur_scope_ix < PL_scopestack_ix; i++) {
1264   I32 *ixp;
1265   I32 offset;
1266
1267 #ifdef SU_HAS_NEW_CXT
1268
1269   if (   cur_cx_ix <= cxstack_ix
1270       && cur_scope_ix == cxstack[cur_cx_ix].blk_oldscopesp
1271   )
1272    ixp = &(cxstack[cur_cx_ix++].blk_oldsaveix);
1273   else
1274    ixp = &PL_scopestack[cur_scope_ix++]; /* an ENTER pushed after cur context */
1275
1276 #else
1277
1278   XSH_D({
1279    if (cur_cx_ix <= cxstack_ix) {
1280     if (cur_scope_ix == cxstack[cur_cx_ix].blk_oldscopesp) {
1281      su_debug_log(
1282        "%p:     cx=%-2d %s\n%p:     ------------------\n",
1283        ud, cur_cx_ix, SU_CXNAME(cxstack+cur_cx_ix), ud);
1284      cur_cx_ix++;
1285     }
1286     else if (cur_scope_ix + su_cxt_enter_count[CxTYPE(cxstack+cur_cx_ix)]
1287              == cxstack[cur_cx_ix].blk_oldscopesp)
1288      su_debug_log("%p:     ------------------\n", ud);
1289    }
1290   });
1291   ixp = &PL_scopestack[cur_scope_ix++];
1292
1293 #endif
1294
1295   if (i == 0)
1296    offset = size;
1297   else {
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.
1310     */
1311    I32 pad;
1312    offset = SU_SAVE_DESTRUCTOR_SIZE; /* rule 1 */
1313    pad = (origin[i-1].orig_ix + origin[i-1].offset) + offset - (*ixp + offset);
1314    if (pad > 0) { /* rule 2 */
1315     if (pad < SU_SAVE_ALLOC_SIZE + 1) /* rule 3 */
1316      pad = SU_SAVE_ALLOC_SIZE + 1;
1317     offset += pad;
1318    }
1319   }
1320
1321   origin[i].offset = offset;
1322   origin[i].orig_ix = *ixp;
1323   *ixp += offset;
1324
1325 #ifdef SU_HAS_NEW_CXT
1326   XSH_D({
1327    if (ixp == &PL_scopestack[cur_scope_ix-1])
1328     su_debug_log(
1329      "%p:           ENTER       origin[%d] scope[%d] savestack=%d+%d\n",
1330       ud, i, cur_scope_ix, origin[i].orig_ix, origin[i].offset);
1331    else
1332     su_debug_log(
1333      "%p:     cx=%-2d %-11s origin[%d] scope[%d] savestack=%d+%d\n",
1334       ud, cur_cx_ix-1, SU_CXNAME(cxstack+cur_cx_ix-1),
1335       i, cur_scope_ix, origin[i].orig_ix, origin[i].offset);
1336   });
1337 #else
1338   XSH_D(su_debug_log(
1339     "%p:                 ENTER origin[%d] scope[%d] savestack=%d+%d\n",
1340      ud, i, cur_scope_ix, origin[i].orig_ix, origin[i].offset));
1341 #endif
1342
1343  }
1344
1345  assert(i == depth);
1346
1347  SU_UD_DEPTH(ud)  = depth;
1348  SU_UD_ORIGIN(ud) = origin;
1349
1350  su_ss_push_destructor(aTHX_ ud, depth-1, 1);
1351 }
1352
1353
1354 /* --- Unwind stack -------------------------------------------------------- */
1355
1356 static void su_unwind(pTHX_ void *ud_) {
1357  dXSH_CXT;
1358  I32 cxix  = XSH_CXT.unwind_storage.cxix;
1359  I32 items = XSH_CXT.unwind_storage.items;
1360  I32 mark;
1361
1362  PERL_UNUSED_VAR(ud_);
1363
1364  PL_stack_sp = XSH_CXT.unwind_storage.savesp;
1365 #if XSH_HAS_PERL(5, 19, 4)
1366  {
1367   I32 i;
1368   SV **sp = PL_stack_sp;
1369   for (i = -items + 1; i <= 0; ++i)
1370    if (!SvTEMP(sp[i]))
1371     sv_2mortal(SvREFCNT_inc(sp[i]));
1372  }
1373 #endif
1374
1375  if (cxstack_ix > cxix)
1376   dounwind(cxix);
1377
1378  mark = PL_markstack[cxstack[cxix].blk_oldmarksp];
1379  PUSHMARK(PL_stack_sp - items);
1380
1381  XSH_D({
1382   I32 gimme = GIMME_V;
1383   su_debug_log("%p: cx=%d gimme=%s items=%d sp=%d oldmark=%d mark=%d\n",
1384                 &XSH_CXT, cxix,
1385                 gimme == G_VOID ? "void" : gimme == G_ARRAY ? "list" : "scalar",
1386                 items, PL_stack_sp - PL_stack_base, *PL_markstack_ptr, mark);
1387  });
1388
1389  PL_op = (OP *) &(XSH_CXT.unwind_storage.return_op);
1390  PL_op = PL_op->op_ppaddr(aTHX);
1391
1392  *PL_markstack_ptr = mark;
1393
1394  XSH_CXT.unwind_storage.proxy_op.op_next = PL_op;
1395  PL_op = &(XSH_CXT.unwind_storage.proxy_op);
1396 }
1397
1398 /* --- Yield --------------------------------------------------------------- */
1399
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)
1405 #else
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)
1409 #endif
1410
1411 static void su_yield(pTHX_ void *ud_) {
1412  dXSH_CXT;
1413  PERL_CONTEXT *cx;
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;
1418  U8      flags = 0;
1419  OP     *next;
1420
1421  PERL_UNUSED_VAR(ud_);
1422
1423  cx = cxstack + cxix;
1424  switch (CxTYPE(cx)) {
1425   case CXt_BLOCK: {
1426    I32 i, cur = cxstack_ix, n = 1;
1427    OP *o = NULL;
1428    /* Is this actually a given/when block? This may occur only when yield was
1429     * called with HERE (or nothing) as the context. */
1430 #if XSH_HAS_PERL(5, 10, 0)
1431    if (cxix > 0) {
1432     PERL_CONTEXT *prev = cx - 1;
1433     U8       prev_type = CxTYPE(prev);
1434     if ((prev_type == CXt_GIVEN || prev_type == CXt_WHEN)
1435         && (prev->blk_oldcop == cx->blk_oldcop)) {
1436      cxix--;
1437      cx = prev;
1438      if (prev_type == CXt_GIVEN)
1439       goto cxt_given;
1440      else
1441       goto cxt_when;
1442     }
1443    }
1444 #endif
1445    type  = OP_LEAVE;
1446    next  = NULL;
1447    /* Bare blocks (that appear as do { ... } blocks, map { ... } blocks or
1448     * constant folded blcoks) don't need to save the op to return to anywhere
1449     * since 'last' isn't supposed to work inside them. So we climb higher in
1450     * the context stack until we reach a context that has a return op (i.e. a
1451     * sub, an eval, a format or a real loop), recording how many blocks we
1452     * crossed. Then we follow the op_next chain until we get to the leave op
1453     * that closes the original block, which we are assured to reach since
1454     * everything is static (the blocks we have crossed cannot be evals or
1455     * subroutine calls). */
1456    for (i = cxix + 1; i <= cur; ++i) {
1457     PERL_CONTEXT *cx2 = cxstack + i;
1458     switch (CxTYPE(cx2)) {
1459      case CXt_BLOCK:
1460       ++n;
1461       break;
1462      case CXt_SUB:
1463      case CXt_FORMAT:
1464       o = SU_RETOP_SUB(cx2);
1465       break;
1466      case CXt_EVAL:
1467       o = SU_RETOP_EVAL(cx2);
1468       break;
1469 #if XSH_HAS_PERL(5, 11, 0)
1470 # if XSH_HAS_PERL(5, 23, 8)
1471      case CXt_LOOP_ARY:
1472      case CXt_LOOP_LIST:
1473 # else
1474      case CXt_LOOP_FOR:
1475 # endif
1476      case CXt_LOOP_PLAIN:
1477      case CXt_LOOP_LAZYSV:
1478      case CXt_LOOP_LAZYIV:
1479 #else
1480      case CXt_LOOP:
1481 #endif
1482       o = SU_RETOP_LOOP(cx2);
1483       break;
1484     }
1485     if (o)
1486      break;
1487    }
1488    if (!o)
1489     o = PL_op;
1490    while (n && o) {
1491     /* We may find other enter/leave blocks on our way to the matching leave.
1492      * Make sure the depth is incremented/decremented appropriately. */
1493     if (o->op_type == OP_ENTER) {
1494      ++n;
1495     } else if (o->op_type == OP_LEAVE) {
1496      --n;
1497      if (!n) {
1498       next = o->op_next;
1499       break;
1500      }
1501     }
1502     o = o->op_next;
1503    }
1504    break;
1505   }
1506   case CXt_SUB:
1507   case CXt_FORMAT:
1508    type = OP_LEAVESUB;
1509    next = SU_RETOP_SUB(cx);
1510    break;
1511   case CXt_EVAL:
1512    type = CxTRYBLOCK(cx) ? OP_LEAVETRY : OP_LEAVEEVAL;
1513    next = SU_RETOP_EVAL(cx);
1514    break;
1515 #if XSH_HAS_PERL(5, 11, 0)
1516 # if XSH_HAS_PERL(5, 23, 8)
1517   case CXt_LOOP_ARY:
1518   case CXt_LOOP_LIST:
1519 # else
1520   case CXt_LOOP_FOR:
1521 # endif
1522   case CXt_LOOP_PLAIN:
1523   case CXt_LOOP_LAZYSV:
1524   case CXt_LOOP_LAZYIV:
1525 #else
1526   case CXt_LOOP:
1527 #endif
1528    type = OP_LEAVELOOP;
1529    next = SU_RETOP_LOOP(cx);
1530    break;
1531 #if XSH_HAS_PERL(5, 10, 0)
1532   case CXt_GIVEN:
1533 cxt_given:
1534    type = OP_LEAVEGIVEN;
1535    next = SU_RETOP_GIVEN(cx);
1536    break;
1537   case CXt_WHEN:
1538 cxt_when:
1539 #if XSH_HAS_PERL(5, 15, 1)
1540    type   = OP_LEAVEWHEN;
1541 #else
1542    type   = OP_BREAK;
1543    flags |= OPf_SPECIAL;
1544 #endif
1545    next   = NULL;
1546    break;
1547 #endif
1548   case CXt_SUBST:
1549    croak("%s() can't target a substitution context", which);
1550    break;
1551   default:
1552    croak("%s() doesn't know how to leave a %s context",
1553           which,                         SU_CXNAME(cxstack + cxix));
1554    break;
1555  }
1556
1557  PL_stack_sp = XSH_CXT.yield_storage.savesp;
1558 #if XSH_HAS_PERL(5, 19, 4)
1559  {
1560   I32 i;
1561   SV **sp = PL_stack_sp;
1562   for (i = -items + 1; i <= 0; ++i)
1563    if (!SvTEMP(sp[i]))
1564     sv_2mortal(SvREFCNT_inc(sp[i]));
1565  }
1566 #endif
1567
1568  if (cxstack_ix > cxix)
1569   dounwind(cxix);
1570
1571  /* Copy the arguments passed to yield() where the leave op expects to find
1572   * them. */
1573  if (items)
1574   Move(PL_stack_sp - items + 1, PL_stack_base + cx->blk_oldsp + 1, items, SV *);
1575  PL_stack_sp = PL_stack_base + cx->blk_oldsp + items;
1576
1577  flags |= OP_GIMME_REVERSE(cx->blk_gimme);
1578
1579  XSH_CXT.yield_storage.leave_op.op_type   = type;
1580  XSH_CXT.yield_storage.leave_op.op_ppaddr = PL_ppaddr[type];
1581  XSH_CXT.yield_storage.leave_op.op_flags  = flags;
1582  XSH_CXT.yield_storage.leave_op.op_next   = next;
1583
1584  PL_op = (OP *) &(XSH_CXT.yield_storage.leave_op);
1585  PL_op = PL_op->op_ppaddr(aTHX);
1586
1587  XSH_CXT.yield_storage.proxy_op.op_next = PL_op;
1588  PL_op = &(XSH_CXT.yield_storage.proxy_op);
1589 }
1590
1591 /* --- Uplevel ------------------------------------------------------------- */
1592
1593 #define SU_UPLEVEL_SAVE(f, t) STMT_START { sud->old_##f = PL_##f; PL_##f = (t); } STMT_END
1594 #define SU_UPLEVEL_RESTORE(f) STMT_START { PL_##f = sud->old_##f; } STMT_END
1595
1596 static su_uplevel_ud *su_uplevel_storage_new(pTHX_ I32 cxix) {
1597 #define su_uplevel_storage_new(I) su_uplevel_storage_new(aTHX_ (I))
1598  su_uplevel_ud *sud;
1599  UV depth;
1600  dXSH_CXT;
1601
1602  sud = XSH_CXT.uplevel_storage.root;
1603  if (sud) {
1604   XSH_CXT.uplevel_storage.root = sud->next;
1605   XSH_CXT.uplevel_storage.count--;
1606  } else {
1607   sud = su_uplevel_ud_new();
1608  }
1609
1610  sud->next = XSH_CXT.uplevel_storage.top;
1611  XSH_CXT.uplevel_storage.top = sud;
1612
1613  depth = su_uid_depth(cxix);
1614  su_uid_storage_dup(&sud->tmp_uid_storage, &XSH_CXT.uid_storage, depth);
1615  sud->old_uid_storage = XSH_CXT.uid_storage;
1616  XSH_CXT.uid_storage  = sud->tmp_uid_storage;
1617
1618  return sud;
1619 }
1620
1621 #if XSH_HAS_PERL(5, 13, 7)
1622
1623 static void su_uplevel_storage_delete(pTHX_ su_uplevel_ud *sud) {
1624 #define su_uplevel_storage_delete(S) su_uplevel_storage_delete(aTHX_ (S))
1625  dXSH_CXT;
1626
1627  sud->tmp_uid_storage = XSH_CXT.uid_storage;
1628  XSH_CXT.uid_storage   = sud->old_uid_storage;
1629  {
1630   su_uid *map;
1631   STRLEN  i, alloc;
1632   map   = sud->tmp_uid_storage.map;
1633   alloc = sud->tmp_uid_storage.alloc;
1634   for (i = 0; i < alloc; ++i)
1635    map[i].flags &= ~SU_UID_ACTIVE;
1636  }
1637  XSH_CXT.uplevel_storage.top = sud->next;
1638
1639  if (XSH_CXT.uplevel_storage.count >= SU_UPLEVEL_STORAGE_SIZE) {
1640   su_uplevel_ud_delete(sud);
1641  } else {
1642   sud->next = XSH_CXT.uplevel_storage.root;
1643   XSH_CXT.uplevel_storage.root = sud;
1644   XSH_CXT.uplevel_storage.count++;
1645  }
1646 }
1647
1648 #endif
1649
1650 static int su_uplevel_goto_static(const OP *o) {
1651  for (; o; o = OpSIBLING(o)) {
1652   /* goto ops are unops with kids. */
1653   if (!(o->op_flags & OPf_KIDS))
1654    continue;
1655
1656   switch (o->op_type) {
1657    case OP_LEAVEEVAL:
1658    case OP_LEAVETRY:
1659     /* Don't care about gotos inside eval, as they are forbidden at run time. */
1660     break;
1661    case OP_GOTO:
1662     return 1;
1663    default:
1664     if (su_uplevel_goto_static(((const UNOP *) o)->op_first))
1665      return 1;
1666     break;
1667   }
1668  }
1669
1670  return 0;
1671 }
1672
1673 #if !defined(SU_HAS_NEW_CXT) && SU_UPLEVEL_HIJACKS_RUNOPS
1674
1675 static int su_uplevel_goto_runops(pTHX) {
1676 #define su_uplevel_goto_runops() su_uplevel_goto_runops(aTHX)
1677  register OP *op;
1678  dVAR;
1679
1680  op = PL_op;
1681  do {
1682   if (op->op_type == OP_GOTO) {
1683    AV  *argarray = NULL;
1684    I32  cxix;
1685
1686    for (cxix = cxstack_ix; cxix >= 0; --cxix) {
1687     const PERL_CONTEXT *cx = cxstack + cxix;
1688
1689     switch (CxTYPE(cx)) {
1690      case CXt_SUB:
1691       if (CxHASARGS(cx)) {
1692        argarray = CX_ARGARRAY(cx);
1693        goto done;
1694       }
1695       break;
1696      case CXt_EVAL:
1697      case CXt_FORMAT:
1698       goto done;
1699      default:
1700       break;
1701     }
1702    }
1703
1704 done:
1705    if (argarray) {
1706     dXSH_CXT;
1707
1708     if (XSH_CXT.uplevel_storage.top->cxix == cxix) {
1709      AV  *args  = GvAV(PL_defgv);
1710      I32  items = AvFILLp(args);
1711
1712      av_extend(argarray, items);
1713      Copy(AvARRAY(args), AvARRAY(argarray), items + 1, SV *);
1714      AvFILLp(argarray) = items;
1715     }
1716    }
1717   }
1718
1719   PL_op = op = op->op_ppaddr(aTHX);
1720
1721 #if !XSH_HAS_PERL(5, 13, 0)
1722   PERL_ASYNC_CHECK();
1723 #endif
1724  } while (op);
1725
1726  TAINT_NOT;
1727
1728  return 0;
1729 }
1730
1731 #endif /* SU_UPLEVEL_HIJACKS_RUNOPS */
1732
1733 #define su_at_underscore(C) PadARRAY(PadlistARRAY(CvPADLIST(C))[CvDEPTH(C)])[0]
1734
1735 #ifdef SU_HAS_NEW_CXT
1736
1737 static void su_uplevel_restore_new(pTHX_ void *sus_) {
1738  su_uplevel_ud *sud = sus_;
1739  PERL_CONTEXT *cx;
1740  I32 i;
1741  U8 *saved_cxtypes = sud->cxtypes;
1742
1743  for (i = 0; i < sud->gap; i++) {
1744   PERL_CONTEXT *cx = cxstack + sud->cxix + i;
1745    XSH_D(su_debug_log("su_uplevel_restore: i=%d cxix=%d type %s => %s\n",
1746         i, cx-cxstack, SU_CX_TYPENAME(CxTYPE(cx)),
1747         SU_CX_TYPENAME(saved_cxtypes[i] & CXTYPEMASK)));
1748    cx->cx_type = saved_cxtypes[i];
1749  }
1750  Safefree(saved_cxtypes);
1751
1752  /* renamed is a copy of callback, but they share the same CvPADLIST.
1753   * At this point any calls to renamed should have exited so that its
1754   * depth is back to that of of callback. At this point its safe to free
1755   * renamed, then undo the extra ref count that was ensuring that callback
1756   * remains alive
1757   */
1758  assert(sud->renamed);
1759  assert(sud->callback);
1760
1761  CvDEPTH(sud->callback)--;
1762  assert(CvDEPTH(sud->callback) == CvDEPTH(sud->renamed));
1763  if (!CvISXSUB(sud->renamed)) {
1764   CvDEPTH(sud->renamed)   = 0;
1765   CvPADLIST(sud->renamed) = NULL;
1766  }
1767  SvREFCNT_dec(sud->renamed);
1768  SvREFCNT_dec(sud->callback);
1769
1770  SU_UPLEVEL_RESTORE(curcop);
1771
1772  su_uplevel_storage_delete(sud);
1773
1774  return;
1775 }
1776
1777 #else
1778
1779 /* 5.23.7 and earlier */
1780
1781 static void su_uplevel_restore_old(pTHX_ void *sus_) {
1782  su_uplevel_ud *sud = sus_;
1783  PERL_SI *cur = sud->old_curstackinfo;
1784  PERL_SI *si  = sud->si;
1785
1786 #if SU_UPLEVEL_HIJACKS_RUNOPS
1787  if (PL_runops == su_uplevel_goto_runops)
1788   PL_runops = sud->old_runops;
1789 #endif
1790
1791  if (sud->callback) {
1792   PERL_CONTEXT *cx = cxstack + sud->cxix;
1793   AV     *argarray = MUTABLE_AV(su_at_underscore(sud->callback));
1794
1795   /* We have to fix the pad entry for @_ in the original callback because it
1796    * may have been reified. */
1797   if (AvREAL(argarray)) {
1798    const I32 fill = AvFILLp(argarray);
1799    SvREFCNT_dec(argarray);
1800    argarray = newAV();
1801    AvREAL_off(argarray);
1802    AvREIFY_on(argarray);
1803    av_extend(argarray, fill);
1804    su_at_underscore(sud->callback) = MUTABLE_SV(argarray);
1805   } else {
1806    CLEAR_ARGARRAY(argarray);
1807   }
1808
1809   /* If the old cv member is our renamed CV, it means that this place has been
1810    * reached without a goto() happening, and the old argarray member is
1811    * actually our fake argarray. Destroy it properly in that case. */
1812   if (cx->blk_sub.cv == sud->renamed) {
1813    SvREFCNT_dec(CX_ARGARRAY(cx));
1814    CX_ARGARRAY_set(cx, argarray);
1815   }
1816
1817   CvDEPTH(sud->callback)--;
1818   SvREFCNT_dec(sud->callback);
1819  }
1820
1821  /* Free the renamed CV. We must do it ourselves so that we can force the
1822   * depth to be 0, or perl would complain about it being "still in use".
1823   * But we *know* that it cannot be so. */
1824  if (sud->renamed) {
1825   if (!CvISXSUB(sud->renamed)) {
1826    CvDEPTH(sud->renamed)   = 0;
1827    CvPADLIST(sud->renamed) = NULL;
1828   }
1829   SvREFCNT_dec(sud->renamed);
1830  }
1831
1832  CATCH_SET(sud->old_catch);
1833
1834  SU_UPLEVEL_RESTORE(op);
1835
1836  /* stack_grow() wants PL_curstack so restore the old stack first */
1837  if (PL_curstackinfo == si) {
1838   PL_curstack = cur->si_stack;
1839   if (sud->old_mainstack)
1840    SU_UPLEVEL_RESTORE(mainstack);
1841   SU_UPLEVEL_RESTORE(curstackinfo);
1842
1843   if (sud->died) {
1844    CV *target = sud->target;
1845    I32 levels = 0, i;
1846
1847    /* When we die, the depth of the target CV is not updated because of the
1848     * stack switcheroo. So we have to look at all the frames between the
1849     * uplevel call and the catch block to count how many call frames to the
1850     * target CV were skipped. */
1851    for (i = cur->si_cxix; i > sud->cxix; i--) {
1852     register const PERL_CONTEXT *cx = cxstack + i;
1853
1854     if (CxTYPE(cx) == CXt_SUB) {
1855      if (cx->blk_sub.cv == target)
1856       ++levels;
1857     }
1858    }
1859
1860    /* If we died, the replacement stack was already unwinded to the first
1861     * eval frame, and all the contexts down there were popped. We don't have
1862     * to pop manually any context of the original stack, because they must
1863     * have been in the replacement stack as well (since the second was copied
1864     * from the first). Thus we only have to make sure the original stack index
1865     * points to the context just below the first eval scope under the target
1866     * frame. */
1867    for (; i >= 0; i--) {
1868     register const PERL_CONTEXT *cx = cxstack + i;
1869
1870     switch (CxTYPE(cx)) {
1871      case CXt_SUB:
1872       if (cx->blk_sub.cv == target)
1873        ++levels;
1874       break;
1875      case CXt_EVAL:
1876       goto found_it;
1877       break;
1878      default:
1879       break;
1880     }
1881    }
1882
1883 found_it:
1884    CvDEPTH(target) = sud->target_depth - levels;
1885    PL_curstackinfo->si_cxix = i - 1;
1886
1887 #if !XSH_HAS_PERL(5, 13, 1)
1888    /* Since $@ was maybe localized between the target frame and the uplevel
1889     * call, we forcefully flush the save stack to get rid of it and then
1890     * reset $@ to its proper value. Note that the the call to
1891     * su_uplevel_restore() must happen before the "reset $@" item of the save
1892     * stack is processed, as uplevel was called after the localization.
1893     * Andrew's changes to how $@ was handled, which were mainly integrated
1894     * between perl 5.13.0 and 5.13.1, fixed this. */
1895    if (ERRSV && SvTRUE(ERRSV)) {
1896     register const PERL_CONTEXT *cx = cxstack + i; /* This is the eval scope */
1897     SV *errsv = SvREFCNT_inc(ERRSV);
1898     PL_scopestack_ix = cx->blk_oldscopesp;
1899     leave_scope(PL_scopestack[PL_scopestack_ix]);
1900     sv_setsv(ERRSV, errsv);
1901     SvREFCNT_dec(errsv);
1902    }
1903 #endif
1904   }
1905  }
1906
1907  SU_UPLEVEL_RESTORE(curcop);
1908
1909  SvREFCNT_dec(sud->target);
1910
1911  PL_stack_base = AvARRAY(cur->si_stack);
1912  PL_stack_sp   = PL_stack_base + AvFILLp(cur->si_stack);
1913  PL_stack_max  = PL_stack_base + AvMAX(cur->si_stack);
1914
1915  /* When an exception is thrown from the uplevel'd subroutine,
1916   * su_uplevel_restore() may be called by the LEAVE in die_unwind() (renamed
1917   * die_where() in more recent perls), which has the sad habit of keeping a
1918   * pointer to the current context frame across this call. This means that we
1919   * can't free the temporary context stack we used for the uplevel call right
1920   * now, or that pointer upwards would point to garbage. */
1921 #if XSH_HAS_PERL(5, 13, 7)
1922  /* This issue has been fixed in perl with commit 8f89e5a9, which was made
1923   * public in perl 5.13.7. */
1924  su_uplevel_storage_delete(sud);
1925 #else
1926  /* Otherwise, we just enqueue it back in the global storage list. */
1927  {
1928   dXSH_CXT;
1929
1930   sud->tmp_uid_storage = XSH_CXT.uid_storage;
1931   XSH_CXT.uid_storage  = sud->old_uid_storage;
1932
1933   XSH_CXT.uplevel_storage.top  = sud->next;
1934   sud->next = XSH_CXT.uplevel_storage.root;
1935   XSH_CXT.uplevel_storage.root = sud;
1936   XSH_CXT.uplevel_storage.count++;
1937  }
1938 #endif
1939
1940  return;
1941 }
1942
1943 #endif
1944
1945 static CV *su_cv_clone(pTHX_ CV *proto, GV *gv) {
1946 #define su_cv_clone(P, G) su_cv_clone(aTHX_ (P), (G))
1947  dVAR;
1948  CV *cv;
1949
1950  cv = MUTABLE_CV(newSV_type(SvTYPE(proto)));
1951
1952  CvFLAGS(cv)  = CvFLAGS(proto);
1953 #ifdef CVf_CVGV_RC
1954  CvFLAGS(cv) &= ~CVf_CVGV_RC;
1955 #endif
1956  CvDEPTH(cv)  = CvDEPTH(proto);
1957 #ifdef USE_ITHREADS
1958  CvFILE(cv)   = CvISXSUB(proto) ? CvFILE(proto) : savepv(CvFILE(proto));
1959 #else
1960  CvFILE(cv)   = CvFILE(proto);
1961 #endif
1962
1963  CvGV_set(cv, gv);
1964 #if SU_RELEASE && XSH_HAS_PERL_EXACT(5, 21, 4)
1965  CvNAMED_off(cv);
1966 #endif
1967  CvSTASH_set(cv, CvSTASH(proto));
1968  /* Commit 4c74a7df, publicized with perl 5.13.3, began to add backrefs to
1969   * stashes. CvSTASH_set() started to do it as well with commit c68d95645
1970   * (which was part of perl 5.13.7). */
1971 #if XSH_HAS_PERL(5, 13, 3) && !XSH_HAS_PERL(5, 13, 7)
1972  if (CvSTASH(proto))
1973   Perl_sv_add_backref(aTHX_ CvSTASH(proto), MUTABLE_SV(cv));
1974 #endif
1975
1976  if (CvISXSUB(proto)) {
1977   CvXSUB(cv)       = CvXSUB(proto);
1978   CvXSUBANY(cv)    = CvXSUBANY(proto);
1979  } else {
1980   OP_REFCNT_LOCK;
1981   CvROOT(cv)       = OpREFCNT_inc(CvROOT(proto));
1982   OP_REFCNT_UNLOCK;
1983   CvSTART(cv)      = CvSTART(proto);
1984   CvPADLIST(cv)    = CvPADLIST(proto);
1985  }
1986  CvOUTSIDE(cv)     = CvOUTSIDE(proto);
1987 #ifdef CVf_WEAKOUTSIDE
1988  if (!(CvFLAGS(proto) & CVf_WEAKOUTSIDE))
1989 #endif
1990   SvREFCNT_inc_simple_void(CvOUTSIDE(cv));
1991 #ifdef CvOUTSIDE_SEQ
1992  CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(proto);
1993 #endif
1994
1995  if (SvPOK(proto))
1996   sv_setpvn(MUTABLE_SV(cv), SvPVX_const(proto), SvCUR(proto));
1997
1998 #ifdef CvCONST
1999  if (CvCONST(cv))
2000   CvCONST_off(cv);
2001 #endif
2002
2003  return cv;
2004 }
2005
2006
2007
2008 #ifdef SU_HAS_NEW_CXT
2009
2010 /* this one-shot runops "loop" is designed to be called just before
2011  * execution of the first op following an uplevel()'s entersub. It gets a
2012  * chance to fix up the args as seen by caller(), before immediately
2013  * falling through to the previous runops loop. Note that pp_entersub is
2014  * called directly by call_sv() rather than being called from a runops
2015  * loop.
2016  */
2017
2018 static int su_uplevel_runops_hook_entersub(pTHX) {
2019  OP *op = PL_op;
2020  dXSH_CXT;
2021  su_uplevel_ud *sud = XSH_CXT.uplevel_storage.top;
2022
2023  /* Create a new array containing a copy of the original sub's call args,
2024   * then stick it in PL_curpad[0] of the current running sub so that
2025   * thay will be seen by caller().
2026   */
2027  assert(sud);
2028  if (sud->argarray) {
2029   AV *av = newAV();
2030   AvREAL_off(av);
2031   AvREIFY_on(av);
2032   av_extend(av, AvMAX(sud->argarray));
2033   AvFILLp(av) = AvFILLp(sud->argarray);
2034   Copy(AvARRAY(sud->argarray), AvARRAY(av), AvFILLp(av) + 1, SV *);
2035
2036   /* should be referenced by PL_curpad[0] and *_ */
2037   assert(SvREFCNT(PL_curpad[0]) > 1);
2038   SvREFCNT_dec(PL_curpad[0]);
2039
2040   PL_curpad[0] = (SV*)av;
2041  }
2042
2043  /* undo the temporary runops hook and fall through to a real runops loop. */
2044  assert(sud->old_runops != su_uplevel_runops_hook_entersub);
2045  PL_runops = sud->old_runops;
2046  CALLRUNOPS(aTHX);
2047  return 0;
2048 }
2049
2050
2051
2052 static I32 su_uplevel_new(pTHX_ CV *callback, I32 cxix, I32 args) {
2053  su_uplevel_ud *sud;
2054  U8 *saved_cxtypes;
2055  I32 i, ret;
2056  I32  gimme;
2057  CV *base_cv = cxstack[cxix].blk_sub.cv;
2058  dSP;
2059
2060  assert(CxTYPE(&cxstack[cxix]) == CXt_SUB);
2061
2062  ENTER;
2063
2064  gimme = GIMME_V;
2065
2066  /* At this point SP points to the top arg.
2067   * Shuffle the args down by one, eliminating the CV slot */
2068  Move(SP - args + 1, SP - args, args, SV*);
2069  SP--;
2070  PUSHMARK(SP - args);
2071  PUTBACK;
2072
2073  sud = su_uplevel_storage_new(cxix);
2074
2075  sud->cxix     = cxix;
2076  sud->callback = (CV*)SvREFCNT_inc_simple(callback);
2077  sud->renamed  = NULL;
2078  sud->gap      = cxstack_ix - cxix + 1;
2079  sud->argarray = NULL;
2080
2081
2082  Newx(saved_cxtypes, sud->gap, U8);
2083  sud->cxtypes = saved_cxtypes;
2084
2085  SAVEDESTRUCTOR_X(su_uplevel_restore_new, sud);
2086  SU_UPLEVEL_SAVE(curcop, cxstack[cxix].blk_oldcop);
2087
2088 /* temporarily change the type of any contexts to NULL, so they're
2089  * invisible to caller() etc. */
2090  for (i = 0; i < sud->gap; i++) {
2091   PERL_CONTEXT *cx = cxstack + cxix + i;
2092   saved_cxtypes[i] = cx->cx_type; /* save type and flags */
2093   XSH_D(su_debug_log("su_uplevel: i=%d cxix=%d type %-11s => %s\n",
2094         i, cx-cxstack, SU_CX_TYPENAME(CxTYPE(cx)), SU_CX_TYPENAME(CXt_NULL)));
2095   cx->cx_type = (CXt_NULL | CXp_SU_UPLEVEL_NULLED);
2096  }
2097
2098  /* create a copy of the callback with a doctored name (as seen by
2099   * caller). It shares the padlist with callback */
2100  sud->renamed = su_cv_clone(callback, CvGV(base_cv));
2101  sud->old_runops = PL_runops;
2102
2103
2104  if (!CvISXSUB(sud->renamed) && CxHASARGS(&cxstack[cxix])) {
2105   sud->argarray = (AV*)su_at_underscore(base_cv);
2106   assert(PL_runops != su_uplevel_runops_hook_entersub);
2107   /* set up a one-shot runops hook so that we can fake up the
2108    * args as seen by caller() on return from pp_entersub */
2109   PL_runops = su_uplevel_runops_hook_entersub;
2110  }
2111
2112  CvDEPTH(callback)++; /* match what CvDEPTH(sud->renamed) is about to become */
2113
2114  ret = call_sv((SV*)sud->renamed, gimme);
2115
2116  LEAVE;
2117
2118  return ret;
2119 }
2120
2121 #else
2122
2123 static I32 su_uplevel_old(pTHX_ CV *callback, I32 cxix, I32 args) {
2124  su_uplevel_ud *sud;
2125  const PERL_CONTEXT *cx = cxstack + cxix;
2126  PERL_SI *si;
2127  PERL_SI *cur = PL_curstackinfo;
2128  SV **old_stack_sp;
2129  CV  *target;
2130  CV  *renamed;
2131  UNOP sub_op;
2132  I32  gimme;
2133  I32  old_mark, new_mark;
2134  I32  ret;
2135  dSP;
2136
2137  ENTER;
2138
2139  gimme = GIMME_V;
2140  /* Make PL_stack_sp point just before the CV. */
2141  PL_stack_sp -= args + 1;
2142  old_mark = AvFILLp(PL_curstack) = PL_stack_sp - PL_stack_base;
2143  SPAGAIN;
2144
2145  sud = su_uplevel_storage_new(cxix);
2146
2147  sud->cxix     = cxix;
2148  sud->died     = 1;
2149  sud->callback = NULL;
2150  sud->renamed  = NULL;
2151  SAVEDESTRUCTOR_X(su_uplevel_restore_old, sud);
2152
2153  si = sud->si;
2154
2155  si->si_type    = cur->si_type;
2156  si->si_next    = NULL;
2157  si->si_prev    = cur->si_prev;
2158 #ifdef DEBUGGING
2159  si->si_markoff = cx->blk_oldmarksp;
2160 #endif
2161
2162  /* Allocate enough space for all the elements of the original stack up to the
2163   * target context, plus the forthcoming arguments. */
2164  new_mark = cx->blk_oldsp;
2165  av_extend(si->si_stack, new_mark + 1 + args + 1);
2166  Copy(AvARRAY(PL_curstack), AvARRAY(si->si_stack), new_mark + 1, SV *);
2167  AvFILLp(si->si_stack) = new_mark;
2168  SU_POISON(AvARRAY(si->si_stack) + new_mark + 1, args + 1, SV *);
2169
2170  /* Specialized SWITCHSTACK() */
2171  PL_stack_base = AvARRAY(si->si_stack);
2172  old_stack_sp  = PL_stack_sp;
2173  PL_stack_sp   = PL_stack_base + AvFILLp(si->si_stack);
2174  PL_stack_max  = PL_stack_base + AvMAX(si->si_stack);
2175  SPAGAIN;
2176
2177  /* Copy the context stack up to the context just below the target. */
2178  si->si_cxix = (cxix < 0) ? -1 : (cxix - 1);
2179  if (si->si_cxmax < cxix) {
2180   /* The max size must be at least two so that GROW(max) = (max*3)/2 > max */
2181   si->si_cxmax = (cxix < 4) ? 4 : cxix;
2182   Renew(si->si_cxstack, si->si_cxmax + 1, PERL_CONTEXT);
2183  }
2184  Copy(cur->si_cxstack, si->si_cxstack, cxix, PERL_CONTEXT);
2185  SU_POISON(si->si_cxstack + cxix, si->si_cxmax + 1 - cxix, PERL_CONTEXT);
2186
2187  target            = cx->blk_sub.cv;
2188  sud->target       = (CV *) SvREFCNT_inc(target);
2189  sud->target_depth = CvDEPTH(target);
2190
2191  /* blk_oldcop is essentially needed for caller() and stack traces. It has no
2192   * run-time implication, since PL_curcop will be overwritten as soon as we
2193   * enter a sub (a sub starts by a nextstate/dbstate). Hence it's safe to just
2194   * make it point to the blk_oldcop for the target frame, so that caller()
2195   * reports the right file name, line number and lexical hints. */
2196  SU_UPLEVEL_SAVE(curcop, cx->blk_oldcop);
2197  /* Don't reset PL_markstack_ptr, or we would overwrite the mark stack below
2198   * this point. Don't reset PL_curpm either, we want the most recent matches. */
2199
2200  SU_UPLEVEL_SAVE(curstackinfo, si);
2201  /* If those two are equal, we need to fool POPSTACK_TO() */
2202  if (PL_mainstack == PL_curstack)
2203   SU_UPLEVEL_SAVE(mainstack, si->si_stack);
2204  else
2205   sud->old_mainstack = NULL;
2206  PL_curstack = si->si_stack;
2207
2208  renamed      = su_cv_clone(callback, CvGV(target));
2209  sud->renamed = renamed;
2210
2211  PUSHMARK(SP);
2212  /* Both SP and old_stack_sp point just before the CV. */
2213  Copy(old_stack_sp + 2, SP + 1, args, SV *);
2214  SP += args;
2215  PUSHs((SV *) renamed);
2216  PUTBACK;
2217
2218  Zero(&sub_op, 1, UNOP);
2219  sub_op.op_type  = OP_ENTERSUB;
2220  sub_op.op_next  = NULL;
2221  sub_op.op_flags = OP_GIMME_REVERSE(gimme) | OPf_STACKED;
2222  if (PL_DBsub)
2223   sub_op.op_flags |= OPpENTERSUB_DB;
2224
2225  SU_UPLEVEL_SAVE(op, (OP *) &sub_op);
2226
2227 #if SU_UPLEVEL_HIJACKS_RUNOPS
2228  sud->old_runops = PL_runops;
2229 #endif
2230
2231  sud->old_catch = CATCH_GET;
2232  CATCH_SET(TRUE);
2233
2234  if ((PL_op = PL_ppaddr[OP_ENTERSUB](aTHX))) {
2235   PERL_CONTEXT *sub_cx = cxstack + cxstack_ix;
2236   AV *argarray = CX_ARGARRAY(cx);
2237
2238   /* If pp_entersub() returns a non-null OP, it means that the callback is not
2239    * an XSUB. */
2240
2241   sud->callback = MUTABLE_CV(SvREFCNT_inc(callback));
2242   CvDEPTH(callback)++;
2243
2244   if (CxHASARGS(cx) && argarray) {
2245    /* The call to pp_entersub() has saved the current @_ (in XS terms,
2246     * GvAV(PL_defgv)) in the savearray member, and has created a new argarray
2247     * with what we put on the stack. But we want to fake up the same arguments
2248     * as the ones in use at the context we uplevel to, so we replace the
2249     * argarray with an unreal copy of the original @_. */
2250    AV *av = newAV();
2251    AvREAL_off(av);
2252    AvREIFY_on(av);
2253    av_extend(av, AvMAX(argarray));
2254    AvFILLp(av) = AvFILLp(argarray);
2255    Copy(AvARRAY(argarray), AvARRAY(av), AvFILLp(av) + 1, SV *);
2256    CX_ARGARRAY_set(sub_cx, av);
2257   } else {
2258    SvREFCNT_inc_simple_void(CX_ARGARRAY(sub_cx));
2259   }
2260
2261   if (su_uplevel_goto_static(CvROOT(renamed))) {
2262 #if SU_UPLEVEL_HIJACKS_RUNOPS
2263    if (PL_runops != PL_runops_std) {
2264     if (PL_runops == PL_runops_dbg) {
2265      if (PL_debug)
2266       croak("uplevel() can't execute code that calls goto when debugging flags are set");
2267     } else if (PL_runops != su_uplevel_goto_runops)
2268      croak("uplevel() can't execute code that calls goto with a custom runloop");
2269    }
2270
2271    PL_runops = su_uplevel_goto_runops;
2272 #else  /* SU_UPLEVEL_HIJACKS_RUNOPS */
2273    croak("uplevel() can't execute code that calls goto before perl 5.8");
2274 #endif /* !SU_UPLEVEL_HIJACKS_RUNOPS */
2275   }
2276
2277   CALLRUNOPS(aTHX);
2278  }
2279
2280  sud->died = 0;
2281
2282  ret = PL_stack_sp - (PL_stack_base + new_mark);
2283  if (ret > 0) {
2284   AV *old_stack = sud->old_curstackinfo->si_stack;
2285
2286   if (old_mark + ret > AvMAX(old_stack)) {
2287    /* Specialized EXTEND(old_sp, ret) */
2288    av_extend(old_stack, old_mark + ret + 1);
2289    old_stack_sp = AvARRAY(old_stack) + old_mark;
2290   }
2291
2292   Copy(PL_stack_sp - ret + 1, old_stack_sp + 1, ret, SV *);
2293   PL_stack_sp        += ret;
2294   AvFILLp(old_stack) += ret;
2295  }
2296
2297  LEAVE;
2298
2299  return ret;
2300 }
2301
2302 #endif
2303
2304 /* --- Unique context ID --------------------------------------------------- */
2305
2306 static su_uid *su_uid_storage_fetch(pTHX_ UV depth) {
2307 #define su_uid_storage_fetch(D) su_uid_storage_fetch(aTHX_ (D))
2308  su_uid *map;
2309  STRLEN  alloc;
2310  dXSH_CXT;
2311
2312  map   = XSH_CXT.uid_storage.map;
2313  alloc = XSH_CXT.uid_storage.alloc;
2314
2315  if (depth >= alloc) {
2316   STRLEN i;
2317
2318   Renew(map, depth + 1, su_uid);
2319   for (i = alloc; i <= depth; ++i) {
2320    map[i].seq   = 0;
2321    map[i].flags = 0;
2322   }
2323
2324   XSH_CXT.uid_storage.map   = map;
2325   XSH_CXT.uid_storage.alloc = depth + 1;
2326  }
2327
2328  if (depth >= XSH_CXT.uid_storage.used)
2329   XSH_CXT.uid_storage.used = depth + 1;
2330
2331  return map + depth;
2332 }
2333
2334 static int su_uid_storage_check(pTHX_ UV depth, UV seq) {
2335 #define su_uid_storage_check(D, S) su_uid_storage_check(aTHX_ (D), (S))
2336  su_uid *uid;
2337  dXSH_CXT;
2338
2339  if (depth >= XSH_CXT.uid_storage.used)
2340   return 0;
2341
2342  uid = XSH_CXT.uid_storage.map + depth;
2343
2344  return (uid->seq == seq) && (uid->flags & SU_UID_ACTIVE);
2345 }
2346
2347 static SV *su_uid_get(pTHX_ I32 cxix) {
2348 #define su_uid_get(I) su_uid_get(aTHX_ (I))
2349  su_uid *uid;
2350  SV     *uid_sv;
2351  UV      depth;
2352
2353  depth = su_uid_depth(cxix);
2354  uid   = su_uid_storage_fetch(depth);
2355
2356  if (!(uid->flags & SU_UID_ACTIVE)) {
2357   su_ud_uid *ud;
2358
2359   uid->seq    = su_uid_seq_next(depth);
2360   uid->flags |= SU_UID_ACTIVE;
2361
2362   Newx(ud, 1, su_ud_uid);
2363   SU_UD_TYPE(ud) = SU_UD_TYPE_UID;
2364   ud->idx        = depth;
2365   su_init(ud, cxix, SU_SAVE_DESTRUCTOR_SIZE);
2366  }
2367
2368  uid_sv = sv_newmortal();
2369  sv_setpvf(uid_sv, "%"UVuf"-%"UVuf, depth, uid->seq);
2370
2371  return uid_sv;
2372 }
2373
2374 #ifdef grok_number
2375
2376 #define su_grok_number(S, L, VP) grok_number((S), (L), (VP))
2377
2378 #else /* grok_number */
2379
2380 #define IS_NUMBER_IN_UV 0x1
2381
2382 static int su_grok_number(pTHX_ const char *s, STRLEN len, UV *valuep) {
2383 #define su_grok_number(S, L, VP) su_grok_number(aTHX_ (S), (L), (VP))
2384  STRLEN i;
2385  SV *tmpsv;
2386
2387  /* This crude check should be good enough for a fallback implementation.
2388   * Better be too strict than too lax. */
2389  for (i = 0; i < len; ++i) {
2390   if (!isDIGIT(s[i]))
2391    return 0;
2392  }
2393
2394  tmpsv = sv_newmortal();
2395  sv_setpvn(tmpsv, s, len);
2396  *valuep = sv_2uv(tmpsv);
2397
2398  return IS_NUMBER_IN_UV;
2399 }
2400
2401 #endif /* !grok_number */
2402
2403 static int su_uid_validate(pTHX_ SV *uid) {
2404 #define su_uid_validate(U) su_uid_validate(aTHX_ (U))
2405  const char *s;
2406  STRLEN len, p = 0;
2407  UV depth, seq;
2408  int type;
2409
2410  s = SvPV_const(uid, len);
2411
2412  while (p < len && s[p] != '-')
2413   ++p;
2414  if (p >= len)
2415   croak("UID contains only one part");
2416
2417  type = su_grok_number(s, p, &depth);
2418  if (type != IS_NUMBER_IN_UV)
2419   croak("First UID part is not an unsigned integer");
2420
2421  ++p; /* Skip '-'. As we used to have p < len, len - (p + 1) >= 0. */
2422
2423  type = su_grok_number(s + p, len - p, &seq);
2424  if (type != IS_NUMBER_IN_UV)
2425   croak("Second UID part is not an unsigned integer");
2426
2427  return su_uid_storage_check(depth, seq);
2428 }
2429
2430 /* --- Context operations -------------------------------------------------- */
2431
2432 /* Remove sequences of BLOCKs having DB for stash, followed by a SUB context
2433  * for the debugger callback. */
2434
2435 static I32 su_context_skip_db(pTHX_ I32 cxix) {
2436 #define su_context_skip_db(C) su_context_skip_db(aTHX_ (C))
2437  I32 i;
2438
2439  if (!PL_DBsub)
2440   return cxix;
2441
2442  for (i = cxix; i > 0; --i) {
2443   PERL_CONTEXT *cx = cxstack + i;
2444
2445   switch (CxTYPE(cx)) {
2446 #if XSH_HAS_PERL(5, 17, 1)
2447    case CXt_LOOP_PLAIN:
2448 #endif
2449    case CXt_BLOCK:
2450     if (cx->blk_oldcop && CopSTASH(cx->blk_oldcop) == GvSTASH(PL_DBgv))
2451      continue;
2452     break;
2453    case CXt_SUB:
2454     if (cx->blk_sub.cv == GvCV(PL_DBsub)) {
2455      cxix = i - 1;
2456      continue;
2457     }
2458     break;
2459    default:
2460     break;
2461   }
2462
2463   break;
2464  }
2465
2466  return cxix;
2467 }
2468
2469
2470 #ifdef SU_HAS_NEW_CXT
2471
2472 /* convert a physical context stack index into the logical equivalent:
2473  * one that ignores all the context frames hidden by uplevel().
2474  * Perl-level functions use logical args (e.g. UP takes an optional logical
2475  * value and returns a logical value), while we use and store *real*
2476  * values internally.
2477  */
2478
2479 static I32 su_context_real2logical(pTHX_ I32 cxix) {
2480 # define su_context_real2logical(C) su_context_real2logical(aTHX_ (C))
2481  PERL_CONTEXT *cx;
2482  I32 i, gaps = 0;
2483
2484  for (i = 0; i <= cxix; i++) {
2485   cx = cxstack + i;
2486   if (cx->cx_type == (CXt_NULL | CXp_SU_UPLEVEL_NULLED))
2487    gaps++;
2488  }
2489  XSH_D(su_debug_log("su_context_real2logical: %d => %d\n", cxix, cxix - gaps));
2490  return cxix - gaps;
2491 }
2492
2493 /* convert a logical context stack index (one that ignores all the context
2494  * frames hidden by uplevel) into the physical equivalent
2495  */
2496
2497 static I32 su_context_logical2real(pTHX_ I32 cxix) {
2498 # define su_context_logical2real(C) su_context_logical2real(aTHX_ (C))
2499  PERL_CONTEXT *cx;
2500  I32 i, seen = -1;
2501
2502  for (i = 0; i <= cxstack_ix; i++) {
2503   PERL_CONTEXT *cx = cxstack + i;
2504   if (cx->cx_type != (CXt_NULL | CXp_SU_UPLEVEL_NULLED))
2505    seen++;
2506   if (seen >= cxix)
2507    break;
2508  }
2509  XSH_D(su_debug_log("su_context_logical2real: %d => %d\n", cxix, i));
2510  if (i > cxstack_ix)
2511   i = cxstack_ix;
2512  return i;
2513 }
2514
2515 #else
2516 # define su_context_real2logical(C) (C)
2517 # define su_context_logical2real(C) (C)
2518 #endif
2519
2520
2521 static I32 su_context_normalize_up(pTHX_ I32 cxix) {
2522 #define su_context_normalize_up(C) su_context_normalize_up(aTHX_ (C))
2523  PERL_CONTEXT *cx;
2524
2525  if (cxix <= 0)
2526   return 0;
2527
2528  cx = cxstack + cxix;
2529  if (CxTYPE(cx) == CXt_BLOCK) {
2530   PERL_CONTEXT *prev = cx - 1;
2531
2532   switch (CxTYPE(prev)) {
2533 #if XSH_HAS_PERL(5, 10, 0)
2534    case CXt_GIVEN:
2535    case CXt_WHEN:
2536 #endif
2537 #if XSH_HAS_PERL(5, 11, 0)
2538    /* That's the only subcategory that can cause an extra BLOCK context */
2539    case CXt_LOOP_PLAIN:
2540 #else
2541    case CXt_LOOP:
2542 #endif
2543     if (cx->blk_oldcop == prev->blk_oldcop)
2544      return cxix - 1;
2545     break;
2546    case CXt_SUBST:
2547     if (cx->blk_oldcop && OpSIBLING(cx->blk_oldcop)
2548                        && OpSIBLING(cx->blk_oldcop)->op_type == OP_SUBST)
2549      return cxix - 1;
2550     break;
2551   }
2552  }
2553
2554  return cxix;
2555 }
2556
2557 static I32 su_context_normalize_down(pTHX_ I32 cxix) {
2558 #define su_context_normalize_down(C) su_context_normalize_down(aTHX_ (C))
2559  PERL_CONTEXT *next;
2560
2561  if (cxix >= cxstack_ix)
2562   return cxstack_ix;
2563
2564  next = cxstack + cxix + 1;
2565  if (CxTYPE(next) == CXt_BLOCK) {
2566   PERL_CONTEXT *cx = next - 1;
2567
2568   switch (CxTYPE(cx)) {
2569 #if XSH_HAS_PERL(5, 10, 0)
2570    case CXt_GIVEN:
2571    case CXt_WHEN:
2572 #endif
2573 #if XSH_HAS_PERL(5, 11, 0)
2574    /* That's the only subcategory that can cause an extra BLOCK context */
2575    case CXt_LOOP_PLAIN:
2576 #else
2577    case CXt_LOOP:
2578 #endif
2579     if (cx->blk_oldcop == next->blk_oldcop)
2580      return cxix + 1;
2581     break;
2582    case CXt_SUBST:
2583     if (next->blk_oldcop && OpSIBLING(next->blk_oldcop)
2584                          && OpSIBLING(next->blk_oldcop)->op_type == OP_SUBST)
2585      return cxix + 1;
2586     break;
2587   }
2588  }
2589
2590  return cxix;
2591 }
2592
2593 #define su_context_here() su_context_normalize_up(su_context_skip_db(cxstack_ix))
2594
2595 static I32 su_context_gimme(pTHX_ I32 cxix) {
2596 #define su_context_gimme(C) su_context_gimme(aTHX_ (C))
2597  I32 i;
2598
2599  for (i = cxix; i >= 0; --i) {
2600   PERL_CONTEXT *cx = cxstack + i;
2601
2602   switch (CxTYPE(cx)) {
2603    /* gimme is always G_ARRAY for loop contexts. */
2604 #if XSH_HAS_PERL(5, 11, 0)
2605 # if XSH_HAS_PERL(5, 23, 8)
2606    case CXt_LOOP_ARY:
2607    case CXt_LOOP_LIST:
2608 # else
2609    case CXt_LOOP_FOR:
2610 # endif
2611    case CXt_LOOP_PLAIN:
2612    case CXt_LOOP_LAZYSV:
2613    case CXt_LOOP_LAZYIV:
2614 #else
2615    case CXt_LOOP:
2616 #endif
2617    case CXt_SUBST: {
2618     const COP *cop = cx->blk_oldcop;
2619     if (cop && OpSIBLING(cop)) {
2620      switch (OpSIBLING(cop)->op_flags & OPf_WANT) {
2621       case OPf_WANT_VOID:
2622        return G_VOID;
2623       case OPf_WANT_SCALAR:
2624        return G_SCALAR;
2625       case OPf_WANT_LIST:
2626        return G_ARRAY;
2627       default:
2628        break;
2629      }
2630     }
2631     break;
2632    }
2633    default:
2634     return CxGIMME(cx);
2635     break;
2636   }
2637  }
2638
2639  return G_VOID;
2640 }
2641
2642 /* --- Module setup/teardown ----------------------------------------------- */
2643
2644 static void xsh_user_global_setup(pTHX) {
2645  HV *stash;
2646
2647  MUTEX_INIT(&su_uid_seq_counter_mutex);
2648
2649  XSH_LOCK(&su_uid_seq_counter_mutex);
2650  su_uid_seq_counter.seqs = NULL;
2651  su_uid_seq_counter.size = 0;
2652  XSH_UNLOCK(&su_uid_seq_counter_mutex);
2653
2654  stash = gv_stashpv(XSH_PACKAGE, 1);
2655  newCONSTSUB(stash, "TOP",           newSViv(0));
2656  newCONSTSUB(stash, "SU_THREADSAFE", newSVuv(XSH_THREADSAFE));
2657
2658  return;
2659 }
2660
2661 static void xsh_user_local_setup(pTHX_ xsh_user_cxt_t *cxt) {
2662
2663  /* NewOp() calls calloc() which just zeroes the memory with memset(). */
2664  Zero(&(cxt->unwind_storage.return_op), 1, LISTOP);
2665  cxt->unwind_storage.return_op.op_type   = OP_RETURN;
2666  cxt->unwind_storage.return_op.op_ppaddr = PL_ppaddr[OP_RETURN];
2667
2668  Zero(&(cxt->unwind_storage.proxy_op), 1, OP);
2669  cxt->unwind_storage.proxy_op.op_type   = OP_STUB;
2670  cxt->unwind_storage.proxy_op.op_ppaddr = NULL;
2671
2672  Zero(&(cxt->yield_storage.leave_op), 1, UNOP);
2673  cxt->yield_storage.leave_op.op_type   = OP_STUB;
2674  cxt->yield_storage.leave_op.op_ppaddr = NULL;
2675
2676  Zero(&(cxt->yield_storage.proxy_op), 1, OP);
2677  cxt->yield_storage.proxy_op.op_type   = OP_STUB;
2678  cxt->yield_storage.proxy_op.op_ppaddr = NULL;
2679
2680  cxt->uplevel_storage.top   = NULL;
2681  cxt->uplevel_storage.root  = NULL;
2682  cxt->uplevel_storage.count = 0;
2683
2684  cxt->uid_storage.map   = NULL;
2685  cxt->uid_storage.used  = 0;
2686  cxt->uid_storage.alloc = 0;
2687
2688  return;
2689 }
2690
2691 static void xsh_user_local_teardown(pTHX_ xsh_user_cxt_t *cxt) {
2692  su_uplevel_ud *cur;
2693
2694  Safefree(cxt->uid_storage.map);
2695
2696  cur = cxt->uplevel_storage.root;
2697  if (cur) {
2698   su_uplevel_ud *prev;
2699   do {
2700    prev = cur;
2701    cur  = prev->next;
2702    su_uplevel_ud_delete(prev);
2703   } while (cur);
2704  }
2705
2706  return;
2707 }
2708
2709 static void xsh_user_global_teardown(pTHX) {
2710  XSH_LOCK(&su_uid_seq_counter_mutex);
2711  PerlMemShared_free(su_uid_seq_counter.seqs);
2712  su_uid_seq_counter.size = 0;
2713  XSH_UNLOCK(&su_uid_seq_counter_mutex);
2714
2715  MUTEX_DESTROY(&su_uid_seq_counter_mutex);
2716
2717  return;
2718 }
2719
2720 /* --- XS ------------------------------------------------------------------ */
2721
2722 /* D is real; B is logical. Returns real. */
2723
2724 #define SU_GET_CONTEXT(A, B, D) \
2725  STMT_START {                   \
2726   if (items > A) {              \
2727    SV *csv = ST(B);             \
2728    if (!SvOK(csv))              \
2729     goto default_cx;            \
2730    cxix = SvIV(csv);            \
2731    if (cxix < 0)                \
2732     cxix = 0;                   \
2733    else if (cxix > cxstack_ix)  \
2734     goto default_cx;            \
2735    cxix = su_context_logical2real(cxix); \
2736   } else {                      \
2737 default_cx:                     \
2738    cxix = (D);                  \
2739   }                             \
2740  } STMT_END
2741
2742 #define SU_GET_LEVEL(A, B) \
2743  STMT_START {              \
2744   level = 0;               \
2745   if (items > 0) {         \
2746    SV *lsv = ST(B);        \
2747    if (SvOK(lsv)) {        \
2748     level = SvIV(lsv);     \
2749     if (level < 0)         \
2750      level = 0;            \
2751    }                       \
2752   }                        \
2753  } STMT_END
2754
2755 #if XSH_HAS_PERL(5, 10, 0)
2756 # define SU_INFO_COUNT 11
2757 #else
2758 # define SU_INFO_COUNT 10
2759 #endif
2760
2761 XS(XS_Scope__Upper_unwind) {
2762 #ifdef dVAR
2763  dVAR; dXSARGS;
2764 #else
2765  dXSARGS;
2766 #endif
2767  dXSH_CXT;
2768  I32 cxix;
2769
2770  PERL_UNUSED_VAR(cv); /* -W */
2771  PERL_UNUSED_VAR(ax); /* -Wall */
2772
2773  SU_GET_CONTEXT(0, items - 1, cxstack_ix);
2774  do {
2775   PERL_CONTEXT *cx = cxstack + cxix;
2776   switch (CxTYPE(cx)) {
2777    case CXt_SUB:
2778     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2779      continue;
2780    case CXt_EVAL:
2781    case CXt_FORMAT:
2782     XSH_CXT.unwind_storage.cxix   = cxix;
2783     XSH_CXT.unwind_storage.items  = items;
2784     XSH_CXT.unwind_storage.savesp = PL_stack_sp;
2785     if (items > 0) {
2786      XSH_CXT.unwind_storage.items--;
2787      XSH_CXT.unwind_storage.savesp--;
2788     }
2789     /* pp_entersub will want to sanitize the stack after returning from there
2790      * Screw that, we're insane!
2791      * dXSARGS calls POPMARK, so we need to match PL_markstack_ptr[1] */
2792     if (GIMME_V == G_SCALAR)
2793      PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
2794     SAVEDESTRUCTOR_X(su_unwind, NULL);
2795     return;
2796    default:
2797     break;
2798   }
2799  } while (--cxix >= 0);
2800  croak("Can't return outside a subroutine");
2801 }
2802
2803 static const char su_yield_name[] = "yield";
2804
2805 XS(XS_Scope__Upper_yield) {
2806 #ifdef dVAR
2807  dVAR; dXSARGS;
2808 #else
2809  dXSARGS;
2810 #endif
2811  dXSH_CXT;
2812  I32 cxix;
2813
2814  PERL_UNUSED_VAR(cv); /* -W */
2815  PERL_UNUSED_VAR(ax); /* -Wall */
2816
2817  SU_GET_CONTEXT(0, items - 1, su_context_here());
2818  XSH_CXT.yield_storage.cxix   = cxix;
2819  XSH_CXT.yield_storage.items  = items;
2820  XSH_CXT.yield_storage.savesp = PL_stack_sp;
2821  if (items > 0) {
2822   XSH_CXT.yield_storage.items--;
2823   XSH_CXT.yield_storage.savesp--;
2824  }
2825  /* See XS_Scope__Upper_unwind */
2826  if (GIMME_V == G_SCALAR)
2827   PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
2828  SAVEDESTRUCTOR_X(su_yield, su_yield_name);
2829  return;
2830 }
2831
2832 static const char su_leave_name[] = "leave";
2833
2834 XS(XS_Scope__Upper_leave) {
2835 #ifdef dVAR
2836  dVAR; dXSARGS;
2837 #else
2838  dXSARGS;
2839 #endif
2840  dXSH_CXT;
2841
2842  PERL_UNUSED_VAR(cv); /* -W */
2843  PERL_UNUSED_VAR(ax); /* -Wall */
2844
2845  XSH_CXT.yield_storage.cxix   = su_context_here();
2846  XSH_CXT.yield_storage.items  = items;
2847  XSH_CXT.yield_storage.savesp = PL_stack_sp;
2848  /* See XS_Scope__Upper_unwind */
2849  if (GIMME_V == G_SCALAR)
2850   PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
2851  SAVEDESTRUCTOR_X(su_yield, su_leave_name);
2852  return;
2853 }
2854
2855 MODULE = Scope::Upper            PACKAGE = Scope::Upper
2856
2857 PROTOTYPES: ENABLE
2858
2859 BOOT:
2860 {
2861  xsh_setup();
2862  newXSproto("Scope::Upper::unwind", XS_Scope__Upper_unwind, file, NULL);
2863  newXSproto("Scope::Upper::yield",  XS_Scope__Upper_yield,  file, NULL);
2864  newXSproto("Scope::Upper::leave",  XS_Scope__Upper_leave,  file, NULL);
2865 }
2866
2867 #if XSH_THREADSAFE
2868
2869 void
2870 CLONE(...)
2871 PROTOTYPE: DISABLE
2872 PPCODE:
2873  xsh_clone();
2874  XSRETURN(0);
2875
2876 #endif /* XSH_THREADSAFE */
2877
2878 void
2879 HERE()
2880 PROTOTYPE:
2881 PREINIT:
2882  I32 cxix;
2883 PPCODE:
2884  cxix = su_context_real2logical(su_context_here());
2885  EXTEND(SP, 1);
2886  mPUSHi(cxix);
2887  XSRETURN(1);
2888
2889 void
2890 UP(...)
2891 PROTOTYPE: ;$
2892 PREINIT:
2893  I32 cxix;
2894 PPCODE:
2895  SU_GET_CONTEXT(0, 0, su_context_here());
2896  if (cxix > 0) {
2897   --cxix;
2898   cxix = su_context_skip_db(cxix);
2899   cxix = su_context_normalize_up(cxix);
2900   cxix = su_context_real2logical(cxix);
2901  } else {
2902   warn(su_stack_smash);
2903  }
2904  EXTEND(SP, 1);
2905  mPUSHi(cxix);
2906  XSRETURN(1);
2907
2908 void
2909 SUB(...)
2910 PROTOTYPE: ;$
2911 PREINIT:
2912  I32 cxix;
2913 PPCODE:
2914  SU_GET_CONTEXT(0, 0, cxstack_ix);
2915  EXTEND(SP, 1);
2916  for (; cxix >= 0; --cxix) {
2917   PERL_CONTEXT *cx = cxstack + cxix;
2918   switch (CxTYPE(cx)) {
2919    default:
2920     continue;
2921    case CXt_SUB:
2922     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2923      continue;
2924     cxix = su_context_real2logical(cxix);
2925     mPUSHi(cxix);
2926     XSRETURN(1);
2927   }
2928  }
2929  warn(su_no_such_target, "subroutine");
2930  XSRETURN_UNDEF;
2931
2932 void
2933 EVAL(...)
2934 PROTOTYPE: ;$
2935 PREINIT:
2936  I32 cxix;
2937 PPCODE:
2938  SU_GET_CONTEXT(0, 0, cxstack_ix);
2939  EXTEND(SP, 1);
2940  for (; cxix >= 0; --cxix) {
2941   PERL_CONTEXT *cx = cxstack + cxix;
2942   switch (CxTYPE(cx)) {
2943    default:
2944     continue;
2945    case CXt_EVAL:
2946     cxix = su_context_real2logical(cxix);
2947     mPUSHi(cxix);
2948     XSRETURN(1);
2949   }
2950  }
2951  warn(su_no_such_target, "eval");
2952  XSRETURN_UNDEF;
2953
2954 void
2955 SCOPE(...)
2956 PROTOTYPE: ;$
2957 PREINIT:
2958  I32 cxix, level;
2959 PPCODE:
2960  SU_GET_LEVEL(0, 0);
2961  cxix = su_context_here();
2962  while (--level >= 0) {
2963   if (cxix <= 0) {
2964    warn(su_stack_smash);
2965    break;
2966   }
2967   --cxix;
2968   cxix = su_context_skip_db(cxix);
2969   cxix = su_context_normalize_up(cxix);
2970   cxix = su_context_real2logical(cxix);
2971  }
2972  EXTEND(SP, 1);
2973  mPUSHi(cxix);
2974  XSRETURN(1);
2975
2976 void
2977 CALLER(...)
2978 PROTOTYPE: ;$
2979 PREINIT:
2980  I32 cxix, level;
2981 PPCODE:
2982  SU_GET_LEVEL(0, 0);
2983  for (cxix = cxstack_ix; cxix > 0; --cxix) {
2984   PERL_CONTEXT *cx = cxstack + cxix;
2985   switch (CxTYPE(cx)) {
2986    case CXt_SUB:
2987     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2988      continue;
2989    case CXt_EVAL:
2990    case CXt_FORMAT:
2991     if (--level < 0)
2992      goto done;
2993     break;
2994   }
2995  }
2996 done:
2997  if (level >= 0)
2998   warn(su_stack_smash);
2999  EXTEND(SP, 1);
3000  cxix = su_context_real2logical(cxix);
3001  mPUSHi(cxix);
3002  XSRETURN(1);
3003
3004 void
3005 want_at(...)
3006 PROTOTYPE: ;$
3007 PREINIT:
3008  I32 cxix;
3009 PPCODE:
3010  SU_GET_CONTEXT(0, 0, cxstack_ix);
3011  EXTEND(SP, 1);
3012  while (cxix > 0) {
3013   PERL_CONTEXT *cx = cxstack + cxix--;
3014   switch (CxTYPE(cx)) {
3015    case CXt_SUB:
3016     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
3017      continue;
3018    case CXt_EVAL:
3019    case CXt_FORMAT: {
3020     I32 gimme = cx->blk_gimme;
3021     switch (gimme) {
3022      case G_VOID:   XSRETURN_UNDEF; break;
3023      case G_SCALAR: XSRETURN_NO;    break;
3024      case G_ARRAY:  XSRETURN_YES;   break;
3025     }
3026     break;
3027    }
3028   }
3029  }
3030  XSRETURN_UNDEF;
3031
3032 void
3033 context_info(...)
3034 PROTOTYPE: ;$
3035 PREINIT:
3036  I32 cxix;
3037  const PERL_CONTEXT *cx, *dbcx;
3038  COP *cop;
3039 PPCODE:
3040  SU_GET_CONTEXT(0, 0, su_context_skip_db(cxstack_ix));
3041  cxix = su_context_normalize_up(cxix);
3042  cx   = cxstack + cxix;
3043  dbcx = cx;
3044  if (PL_DBsub && cxix && (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT)) {
3045   I32 i = su_context_skip_db(cxix - 1) + 1;
3046   if (i < cxix && CxTYPE(cxstack + i) == CXt_SUB)
3047    cx = cxstack + i;
3048  }
3049  cop  = cx->blk_oldcop;
3050  EXTEND(SP, SU_INFO_COUNT);
3051  /* stash (0) */
3052  {
3053   HV *stash = CopSTASH(cop);
3054   if (stash)
3055    PUSHs(su_newmortal_pvn(HvNAME(stash), HvNAMELEN(stash)));
3056   else
3057    PUSHs(&PL_sv_undef);
3058  }
3059  /* file (1) */
3060  PUSHs(su_newmortal_pvn(OutCopFILE(cop), OutCopFILE_len(cop)));
3061  /* line (2) */
3062  mPUSHi(CopLINE(cop));
3063  /* subroutine (3) and has_args (4) */
3064  switch (CxTYPE(cx)) {
3065   case CXt_SUB:
3066   case CXt_FORMAT: {
3067    GV *cvgv = CvGV(dbcx->blk_sub.cv);
3068    if (cvgv && isGV(cvgv)) {
3069     SV *sv = sv_newmortal();
3070     gv_efullname3(sv, cvgv, NULL);
3071     PUSHs(sv);
3072    } else {
3073     PUSHs(su_newmortal_pvs("(unknown)"));
3074    }
3075    if (CxHASARGS(cx))
3076     PUSHs(&PL_sv_yes);
3077    else
3078     PUSHs(&PL_sv_no);
3079    break;
3080   }
3081   case CXt_EVAL:
3082    PUSHs(su_newmortal_pvs("(eval)"));
3083    mPUSHi(0);
3084    break;
3085   default:
3086    PUSHs(&PL_sv_undef);
3087    PUSHs(&PL_sv_undef);
3088  }
3089  /* gimme (5) */
3090  switch (su_context_gimme(cxix)) {
3091   case G_ARRAY:
3092    PUSHs(&PL_sv_yes);
3093    break;
3094   case G_SCALAR:
3095    PUSHs(&PL_sv_no);
3096    break;
3097   default: /* G_VOID */
3098    PUSHs(&PL_sv_undef);
3099    break;
3100  }
3101  /* eval text (6) and is_require (7) */
3102  switch (CxTYPE(cx)) {
3103   case CXt_EVAL:
3104    if (CxOLD_OP_TYPE(cx) == OP_ENTEREVAL) {
3105     /* eval STRING */
3106 #if XSH_HAS_PERL(5, 17, 4)
3107     PUSHs(newSVpvn_flags(SvPVX(cx->blk_eval.cur_text),
3108                          SvCUR(cx->blk_eval.cur_text)-2,
3109                          SvUTF8(cx->blk_eval.cur_text)|SVs_TEMP));
3110 #else
3111     PUSHs(cx->blk_eval.cur_text);
3112 #endif
3113     PUSHs(&PL_sv_no);
3114     break;
3115    } else if (cx->blk_eval.old_namesv) {
3116     /* require */
3117     PUSHs(sv_mortalcopy(cx->blk_eval.old_namesv));
3118     PUSHs(&PL_sv_yes);
3119     break;
3120    }
3121    /* FALLTHROUGH */
3122   default:
3123    /* Anything else including eval BLOCK */
3124    PUSHs(&PL_sv_undef);
3125    PUSHs(&PL_sv_undef);
3126    break;
3127  }
3128  /* hints (8) */
3129  mPUSHi(CopHINTS_get(cop));
3130  /* warnings (9) */
3131  {
3132   SV *mask = NULL;
3133 #if XSH_HAS_PERL(5, 9, 4)
3134   STRLEN *old_warnings = cop->cop_warnings;
3135 #else
3136   SV *old_warnings = cop->cop_warnings;
3137 #endif
3138   if (old_warnings == pWARN_STD) {
3139    if (PL_dowarn & G_WARN_ON)
3140     goto context_info_warnings_on;
3141    else
3142 #if XSH_HAS_PERL(5, 17, 4)
3143     mask = &PL_sv_undef;
3144 #else
3145     goto context_info_warnings_off;
3146 #endif
3147   } else if (old_warnings == pWARN_NONE) {
3148 #if !XSH_HAS_PERL(5, 17, 4)
3149 context_info_warnings_off:
3150 #endif
3151    mask = su_newmortal_pvn(WARN_NONEstring, WARNsize);
3152   } else if (old_warnings == pWARN_ALL) {
3153    HV *bits;
3154 context_info_warnings_on:
3155 #if XSH_HAS_PERL(5, 8, 7)
3156    bits = get_hv("warnings::Bits", 0);
3157    if (bits) {
3158     SV **bits_all = hv_fetchs(bits, "all", FALSE);
3159     if (bits_all)
3160      mask = sv_mortalcopy(*bits_all);
3161    }
3162 #endif
3163    if (!mask)
3164     mask = su_newmortal_pvn(WARN_ALLstring, WARNsize);
3165   } else {
3166 #if XSH_HAS_PERL(5, 9, 4)
3167    mask = su_newmortal_pvn((char *) (old_warnings + 1), old_warnings[0]);
3168 #else
3169    mask = sv_mortalcopy(old_warnings);
3170 #endif
3171   }
3172   PUSHs(mask);
3173  }
3174 #if XSH_HAS_PERL(5, 10, 0)
3175  /* hints hash (10) */
3176  {
3177   COPHH *hints_hash = CopHINTHASH_get(cop);
3178   if (hints_hash) {
3179    SV *rhv = sv_2mortal(newRV_noinc((SV *) cophh_2hv(hints_hash, 0)));
3180    PUSHs(rhv);
3181   } else {
3182    PUSHs(&PL_sv_undef);
3183   }
3184  }
3185 #endif
3186  XSRETURN(SU_INFO_COUNT);
3187
3188 void
3189 reap(SV *hook, ...)
3190 PROTOTYPE: &;$
3191 PREINIT:
3192  I32 cxix;
3193  su_ud_reap *ud;
3194 CODE:
3195  SU_GET_CONTEXT(1, 1, su_context_skip_db(cxstack_ix));
3196  cxix = su_context_normalize_down(cxix);
3197  Newx(ud, 1, su_ud_reap);
3198  SU_UD_TYPE(ud) = SU_UD_TYPE_REAP;
3199  ud->cb         = (SvROK(hook) && SvTYPE(SvRV(hook)) >= SVt_PVCV)
3200                   ? SvRV(hook) : hook;
3201  SvREFCNT_inc_simple_void(ud->cb);
3202  su_init(ud, cxix, SU_SAVE_DESTRUCTOR_SIZE);
3203
3204 void
3205 localize(SV *sv, SV *val, ...)
3206 PROTOTYPE: $$;$
3207 PREINIT:
3208  I32 cxix;
3209  I32 size;
3210  su_ud_localize *ud;
3211 CODE:
3212  SU_GET_CONTEXT(2, 2, su_context_skip_db(cxstack_ix));
3213  cxix = su_context_normalize_down(cxix);
3214  Newx(ud, 1, su_ud_localize);
3215  SU_UD_TYPE(ud) = SU_UD_TYPE_LOCALIZE;
3216  size = su_ud_localize_init(ud, sv, val, NULL);
3217  su_init(ud, cxix, size);
3218
3219 void
3220 localize_elem(SV *sv, SV *elem, SV *val, ...)
3221 PROTOTYPE: $$$;$
3222 PREINIT:
3223  I32 cxix;
3224  I32 size;
3225  su_ud_localize *ud;
3226 CODE:
3227  if (SvTYPE(sv) >= SVt_PVGV)
3228   croak("Can't infer the element localization type from a glob and the value");
3229  SU_GET_CONTEXT(3, 3, su_context_skip_db(cxstack_ix));
3230  cxix = su_context_normalize_down(cxix);
3231  Newx(ud, 1, su_ud_localize);
3232  /* Initialize SU_UD_ORIGIN(ud) in case SU_UD_LOCALIZE_FREE(ud) needs it */
3233  SU_UD_ORIGIN(ud) = NULL;
3234  SU_UD_TYPE(ud)   = SU_UD_TYPE_LOCALIZE;
3235  size = su_ud_localize_init(ud, sv, val, elem);
3236  if (SU_UD_PRIVATE(ud) != SVt_PVAV && SU_UD_PRIVATE(ud) != SVt_PVHV) {
3237   SU_UD_LOCALIZE_FREE(ud);
3238   croak("Can't localize an element of something that isn't an array or a hash");
3239  }
3240  su_init(ud, cxix, size);
3241
3242 void
3243 localize_delete(SV *sv, SV *elem, ...)
3244 PROTOTYPE: $$;$
3245 PREINIT:
3246  I32 cxix;
3247  I32 size;
3248  su_ud_localize *ud;
3249 CODE:
3250  SU_GET_CONTEXT(2, 2, su_context_skip_db(cxstack_ix));
3251  cxix = su_context_normalize_down(cxix);
3252  Newx(ud, 1, su_ud_localize);
3253  SU_UD_TYPE(ud) = SU_UD_TYPE_LOCALIZE;
3254  size = su_ud_localize_init(ud, sv, NULL, elem);
3255  su_init(ud, cxix, size);
3256
3257 void
3258 uplevel(SV *code, ...)
3259 PROTOTYPE: &@
3260 PREINIT:
3261  I32 cxix, ret, args = 0;
3262 PPCODE:
3263  if (SvROK(code))
3264   code = SvRV(code);
3265  if (SvTYPE(code) < SVt_PVCV)
3266   croak("First argument to uplevel must be a code reference");
3267  SU_GET_CONTEXT(1, items - 1, cxstack_ix);
3268  do {
3269   PERL_CONTEXT *cx = cxstack + cxix;
3270   switch (CxTYPE(cx)) {
3271    case CXt_EVAL:
3272     croak("Can't uplevel to an eval frame");
3273    case CXt_FORMAT:
3274     croak("Can't uplevel to a format frame");
3275    case CXt_SUB:
3276     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
3277      continue;
3278     if (items > 1) {
3279      PL_stack_sp--;
3280      args = items - 2;
3281     }
3282     /* su_uplevel() takes care of extending the stack if needed. */
3283 #ifdef SU_HAS_NEW_CXT
3284     ret = su_uplevel_new(aTHX_ (CV *) code, cxix, args);
3285 #else
3286     ret = su_uplevel_old(aTHX_ (CV *) code, cxix, args);
3287 #endif
3288     XSRETURN(ret);
3289    default:
3290     break;
3291   }
3292  } while (--cxix >= 0);
3293  croak("Can't uplevel outside a subroutine");
3294
3295 void
3296 uid(...)
3297 PROTOTYPE: ;$
3298 PREINIT:
3299  I32 cxix;
3300  SV *uid;
3301 PPCODE:
3302  SU_GET_CONTEXT(0, 0, su_context_here());
3303  uid = su_uid_get(cxix);
3304  EXTEND(SP, 1);
3305  PUSHs(uid);
3306  XSRETURN(1);
3307
3308 void
3309 validate_uid(SV *uid)
3310 PROTOTYPE: $
3311 PREINIT:
3312  SV *ret;
3313 PPCODE:
3314  ret = su_uid_validate(uid) ? &PL_sv_yes : &PL_sv_no;
3315  EXTEND(SP, 1);
3316  PUSHs(ret);
3317  XSRETURN(1);