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