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