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