]> git.vpit.fr Git - perl/modules/Scope-Upper.git/blob - Upper.xs
Always define SU_HAS_NEW_CXT
[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
904 /* new perl context implementation frees savestack *before* restoring
905  * PL_curcop. Temporarily restore it prematurely to make gv_fetch*
906  * looks up unqualified var names in the caller's package */
907 #if SU_HAS_NEW_CXT
908   COP *old_cop = PL_curcop;
909   PL_curcop = CX_CUR()->blk_oldcop;
910 #endif
911
912 #ifdef gv_fetchsv
913   gv = gv_fetchsv(sv, GV_ADDMULTI, t);
914 #else
915   STRLEN len;
916   const char *name = SvPV_const(sv, len);
917   gv = gv_fetchpvn_flags(name, len, GV_ADDMULTI, t);
918 #endif
919 #if SU_HAS_NEW_CXT
920   CX_CUR()->blk_oldcop = PL_curcop;
921 #endif
922  }
923
924  XSH_D({
925   SV *z = newSV(0);
926   SvUPGRADE(z, t);
927   su_debug_log("%p:     === localize a %s\n",ud, sv_reftype(z, 0));
928   su_debug_log("%p:         depth=%2d scope_ix=%2d save_ix=%2d\n",
929                 ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
930   SvREFCNT_dec(z);
931  });
932
933  /* Inspired from Alias.pm */
934  switch (t) {
935   case SVt_PVAV:
936    if (elem) {
937     su_save_aelem(GvAV(gv), elem, val);
938     return;
939    } else
940     save_ary(gv);
941    break;
942   case SVt_PVHV:
943    if (elem) {
944     su_save_helem(GvHV(gv), elem, val);
945     return;
946    } else
947     save_hash(gv);
948    break;
949   case SVt_PVGV:
950    save_gp(gv, 1); /* hide previous entry in symtab */
951    break;
952   case SVt_PVCV:
953    su_save_gvcv(gv);
954    break;
955   default:
956    gv = (GV *) save_scalar(gv);
957    break;
958  }
959
960  if (val)
961   SvSetMagicSV((SV *) gv, val);
962
963  return;
964 }
965
966 /* ... Unique context ID ................................................... */
967
968 /* We must pass the index because XSH_CXT.uid_storage might be reallocated
969  * between the UID fetch and the invalidation at the end of scope. */
970
971 typedef struct {
972  su_ud_common ci;
973  I32          idx;
974 } su_ud_uid;
975
976 static void su_uid_drop(pTHX_ void *ud_) {
977  su_ud_uid *ud = ud_;
978  dXSH_CXT;
979
980  XSH_CXT.uid_storage.map[ud->idx].flags &= ~SU_UID_ACTIVE;
981
982  SU_UD_FREE(ud);
983
984  return;
985 }
986
987 /* --- Pop a context back -------------------------------------------------- */
988
989 #ifdef DEBUGGING
990 # define SU_CX_TYPENAME(T) PL_block_type[(T)]
991 #else
992 # if XSH_HAS_PERL(5, 23, 8)
993 static const char *su_block_type[] = {
994  "NULL",
995  "WHEN",
996  "BLOCK",
997  "GIVEN",
998  "LOOP_ARY",
999  "LOOP_LAZYSV",
1000  "LOOP_LAZYIV",
1001  "LOOP_LIST",
1002  "LOOP_PLAIN",
1003  "SUB",
1004  "FORMAT",
1005  "EVAL",
1006  "SUBST"
1007 };
1008 # elif XSH_HAS_PERL(5, 11, 0)
1009 static const char *su_block_type[] = {
1010  "NULL",
1011  "WHEN",
1012  "BLOCK",
1013  "GIVEN",
1014  "LOOP_FOR",
1015  "LOOP_PLAIN",
1016  "LOOP_LAZYSV",
1017  "LOOP_LAZYIV",
1018  "SUB",
1019  "FORMAT",
1020  "EVAL",
1021  "SUBST"
1022 };
1023 # elif XSH_HAS_PERL(5, 10, 0)
1024 static const char *su_block_type[] = {
1025  "NULL",
1026  "SUB",
1027  "EVAL",
1028  "LOOP",
1029  "SUBST",
1030  "BLOCK",
1031  "FORMAT"
1032  "WHEN",
1033  "GIVEN"
1034 };
1035 # else
1036 static const char *su_block_type[] = {
1037  "NULL",
1038  "SUB",
1039  "EVAL",
1040  "LOOP",
1041  "SUBST",
1042  "BLOCK",
1043  "FORMAT"
1044 };
1045 # endif
1046 # define SU_CX_TYPENAME(T) su_block_type[(T)]
1047 #endif
1048
1049 #define SU_CXNAME(C) SU_CX_TYPENAME(CxTYPE(C))
1050
1051 /* for debugging. These indicate how many ENTERs each context type
1052  * does before the PUSHBLOCK */
1053
1054 static const int su_cxt_enter_count[] = {
1055 # if XSH_HAS_PERL(5, 23, 8)
1056   0 /* context pushes no longer do ENTERs */
1057 # elif XSH_HAS_PERL(5, 11, 0)
1058  /* NULL WHEN BLOCK GIVEN LOOP_FOR LOOP_PLAIN LOOP_LAZYSV
1059   * LOOP_LAZYIV SUB FORMAT EVAL SUBST */
1060  0, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 0
1061 # elif XSH_HAS_PERL(5, 10, 0)
1062  /* NULL SUB EVAL LOOP SUBST BLOCK FORMAT WHEN GIVEN */
1063  0, 1, 1, 2, 0, 1, 1, 1, 1
1064 # else
1065  /* NULL SUB EVAL LOOP SUBST BLOCK FORMAT */
1066  0, 1, 1, 2, 0, 1, 1
1067 # endif
1068 };
1069
1070 /* push at least 'size' slots worth of padding onto the savestack */
1071
1072 static void su_ss_push_padding(pTHX_ void *ud, I32 size) {
1073  if (size <= 0)
1074   return;
1075  if (size < SU_SAVE_ALLOC_SIZE + 1) /* minimum possible SAVEt_ALLOC */
1076   size = SU_SAVE_ALLOC_SIZE + 1;
1077  XSH_D(su_debug_log(
1078         "%p:     push %2d padding at save_ix=%d\n",
1079          ud, size, PL_savestack_ix));
1080  save_alloc((size - SU_SAVE_ALLOC_SIZE)*sizeof(*PL_savestack), 0);
1081 }
1082
1083 static void su_pop(pTHX_ void *ud);
1084
1085 /* push an su_pop destructor onto the savestack with suitable padding.
1086  * first indicates that this is the first push of a destructor */
1087
1088 static void su_ss_push_destructor(pTHX_ void *ud, I32 depth, bool first) {
1089  su_ud_origin_elem *origin = SU_UD_ORIGIN(ud);
1090  I32 pad;
1091
1092  assert(first || origin[depth+1].orig_ix == PL_savestack_ix);
1093  su_ss_push_padding(aTHX_ ud,
1094     (origin[depth].orig_ix + origin[depth].offset) - PL_savestack_ix);
1095  XSH_D(su_debug_log(
1096         "%p:     push destructor at save_ix=%d depth=%d scope_ix=%d\n",
1097          ud, PL_savestack_ix, depth, PL_scopestack_ix));
1098  SAVEDESTRUCTOR_X(su_pop, ud);
1099  assert(first ||
1100         PL_savestack_ix <= origin[depth+1].orig_ix +  origin[depth+1].offset);
1101 }
1102
1103 /* this is called during each leave_scope() via SAVEDESTRUCTOR_X */
1104
1105 static void su_pop(pTHX_ void *ud) {
1106 #define su_pop(U) su_pop(aTHX_ (U))
1107  I32 depth, base, mark;
1108  su_ud_origin_elem *origin;
1109
1110  depth  = SU_UD_DEPTH(ud);
1111  origin = SU_UD_ORIGIN(ud);
1112
1113  XSH_D(su_debug_log( "%p: ### su_pop: depth=%d\n", ud, depth));
1114
1115  depth--;
1116  mark = PL_savestack_ix;
1117  base = origin[depth].orig_ix;
1118
1119  XSH_D(su_debug_log("%p:     residual savestack frame is %d(+%d)..%d\n",
1120                      ud, base, origin[depth].offset, mark));
1121
1122  if (base < mark) {
1123   XSH_D(su_debug_log("%p:     clear leftovers at %d..%d\n", ud, base, mark));
1124   leave_scope(base);
1125  }
1126  assert(PL_savestack_ix == base);
1127
1128  SU_UD_DEPTH(ud) = depth;
1129
1130  if (depth > 0) {
1131   su_ss_push_destructor(aTHX_ ud, depth-1, 0);
1132  } else {
1133   I32 offset = origin[0].offset; /* grab value before origin is freed */
1134   switch (SU_UD_TYPE(ud)) {
1135    case SU_UD_TYPE_REAP: {
1136     XSH_D(su_debug_log("%p:     === reap\n%p: depth=%d scope_ix=%d save_ix=%d\n",
1137                    ud, ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix));
1138     SAVEDESTRUCTOR_X(su_call, SU_UD_REAP_CB(ud));
1139     SU_UD_FREE(ud);
1140     break;
1141    }
1142    case SU_UD_TYPE_LOCALIZE:
1143     su_localize(ud);
1144     SU_UD_LOCALIZE_FREE(ud);
1145     break;
1146    case SU_UD_TYPE_UID:
1147     SAVEDESTRUCTOR_X(su_uid_drop, ud);
1148     break;
1149   }
1150   /* perl 5.23.8 onwards is very fussy about the return from leave_scope()
1151    * leaving PL_savestack_ix where it expects it to be */
1152   if (PL_savestack_ix < base + offset) {
1153    I32 gap = (base + offset) - PL_savestack_ix;
1154    assert(gap >= SU_SAVE_ALLOC_SIZE + 1);
1155    su_ss_push_padding(aTHX_ ud, gap);
1156   }
1157   assert(PL_savestack_ix == base + offset);
1158  }
1159
1160  XSH_D(su_debug_log("%p:     end pop: ss_ix=%d\n", ud, PL_savestack_ix));
1161 }
1162
1163 /* --- Initialize the stack and the action userdata ------------------------ */
1164
1165 static void su_init(pTHX_ void *ud, I32 cxix, I32 size) {
1166 #define su_init(U, C, S) su_init(aTHX_ (U), (C), (S))
1167  I32 i, depth, base;
1168  su_ud_origin_elem *origin;
1169  I32 cur_cx_ix;
1170  I32 cur_scope_ix;
1171
1172  XSH_D(su_debug_log("%p: ### su_init(cxix=%d, size=%d)\n", ud, cxix, size));
1173
1174  depth = PL_scopestack_ix - cxstack[cxix].blk_oldscopesp;
1175 #if SU_HAS_NEW_CXT
1176  depth += (cxstack_ix - cxix); /* each context frame holds 1 scope */
1177 #endif
1178  XSH_D(su_debug_log(
1179    "%p:     going down by depth=%d with scope_ix=%d save_ix=%d\n",
1180     ud, depth, PL_scopestack_ix, PL_savestack_ix));
1181
1182  /* Artificially increase the position of each savestack frame boundary
1183   * to make space to squeeze in a 'size' sized entry (first one) or a
1184   * SU_SAVE_DESTRUCTOR_SIZE sized entry (higher ones). In addition, make
1185   * sure that each boundary is higher than the previous, so that *every*
1186   * scope exit triggers a call to leave_scope(). Each scope exit will call
1187   * the su_pop() destructor, which is responsible for: freeing any
1188   * savestack entries below the artificially raised floor; then pushing a
1189   * new destructor in that space. On the final pop, the "real" savestack
1190   * action is pushed rather than another destructor.
1191   *
1192   * On older perls, savestack frame boundaries are specified by a range of
1193   * scopestack entries (one per ENTER). Each scope entry typically does
1194   * one or two ENTERs followed by a PUSHBLOCK. Thus the
1195   * cx->blku_oldscopesp field set by the PUSHBLOCK points to the next free
1196   * slot, which is one above the last of the ENTERs. In the debugging
1197   * output we indicate that by bracketing the ENTERs directly preceding
1198   * that context push with dashes, e.g.:
1199   *
1200   *   13b98d8:     ------------------
1201   *   13b98d8:                 ENTER origin[0] scope[3] savestack=3+3
1202   *   13b98d8:                 ENTER origin[1] scope[4] savestack=9+3
1203   *   13b98d8:     cx=1  LOOP_LAZYIV
1204   *   13b98d8:     ------------------
1205   *
1206   * In addition to context stack pushes, other activities can push ENTERs
1207   * too, such as grep expr and XS sub calls.
1208   *
1209   * For newer perls (SU_HAS_NEW_CXT), a context push no longer does any
1210   * ENTERs; instead the old savestack position is stored in the new
1211   * cx->blk_oldsaveix field; thus this field specifies an additional
1212   * savestack frame boundary point in addition to the scopestack entries,
1213   * and will also need adjusting.
1214   *
1215   * We record the original and modified position of each boundary in the
1216   * origin array.
1217   *
1218   * The passed cxix argument represents the scope we wish to inject into;
1219   * we have to adjust all the savestack frame boundaries above (but not
1220   * including) that context.
1221   */
1222
1223  Newx(origin, depth, su_ud_origin_elem);
1224
1225  cur_cx_ix  = cxix;
1226  cur_scope_ix = cxstack[cxix].blk_oldscopesp;
1227 #if SU_HAS_NEW_CXT
1228  XSH_D(su_debug_log("%p:     cx=%-2d %-11s\n",
1229       ud, cur_cx_ix, SU_CXNAME(cxstack+cur_cx_ix)));
1230  cur_cx_ix++;
1231 #endif
1232
1233  for (i = 0; cur_scope_ix < PL_scopestack_ix; i++) {
1234   I32 *ixp;
1235   I32 offset;
1236
1237 #if SU_HAS_NEW_CXT
1238
1239   if (   cur_cx_ix <= cxstack_ix
1240       && cur_scope_ix == cxstack[cur_cx_ix].blk_oldscopesp
1241   )
1242    ixp = &(cxstack[cur_cx_ix++].blk_oldsaveix);
1243   else
1244    ixp = &PL_scopestack[cur_scope_ix++]; /* an ENTER pushed after cur context */
1245
1246 #else
1247
1248   XSH_D({
1249    if (cur_cx_ix <= cxstack_ix) {
1250     if (cur_scope_ix == cxstack[cur_cx_ix].blk_oldscopesp) {
1251      su_debug_log(
1252        "%p:     cx=%-2d %s\n%p:     ------------------\n",
1253        ud, cur_cx_ix, SU_CXNAME(cxstack+cur_cx_ix), ud);
1254      cur_cx_ix++;
1255     }
1256     else if (cur_scope_ix + su_cxt_enter_count[CxTYPE(cxstack+cur_cx_ix)]
1257              == cxstack[cur_cx_ix].blk_oldscopesp)
1258      su_debug_log("%p:     ------------------\n", ud);
1259    }
1260   });
1261   ixp = &PL_scopestack[cur_scope_ix++];
1262
1263 #endif
1264
1265   if (i == 0)
1266    offset = size;
1267   else {
1268    /* we have three constraints to satisfy:
1269     * 1) Each adjusted offset must be at least SU_SAVE_DESTRUCTOR_SIZE
1270     *    above its unadjusted boundary, so that there is space to inject a
1271     *    destructor into the outer scope.
1272     * 2) Each adjusted boundary must be at least SU_SAVE_DESTRUCTOR_SIZE
1273     *    higher than the previous adjusted boundary, so that a new
1274     *    destructor can be added below the Nth adjusted frame boundary,
1275     *    but be within the (N-1)th adjusted frame and so be triggered on
1276     *    the next scope exit;
1277     * 3) If the adjustment needs to be greater than SU_SAVE_DESTRUCTOR_SIZE,
1278     *    then it should be greater by an amount of at least the minimum
1279     *    pad side, so a destructor and padding can be pushed.
1280     */
1281    I32 pad;
1282    offset = SU_SAVE_DESTRUCTOR_SIZE; /* rule 1 */
1283    pad = (origin[i-1].orig_ix + origin[i-1].offset) + offset - (*ixp + offset);
1284    if (pad > 0) { /* rule 2 */
1285     if (pad < SU_SAVE_ALLOC_SIZE + 1) /* rule 3 */
1286      pad = SU_SAVE_ALLOC_SIZE + 1;
1287     offset += pad;
1288    }
1289   }
1290
1291   origin[i].offset = offset;
1292   origin[i].orig_ix = *ixp;
1293   *ixp += offset;
1294
1295 #if SU_HAS_NEW_CXT
1296   XSH_D({
1297    if (ixp == &PL_scopestack[cur_scope_ix-1])
1298     su_debug_log(
1299      "%p:           ENTER       origin[%d] scope[%d] savestack=%d+%d\n",
1300       ud, i, cur_scope_ix, origin[i].orig_ix, origin[i].offset);
1301    else
1302     su_debug_log(
1303      "%p:     cx=%-2d %-11s origin[%d] scope[%d] savestack=%d+%d\n",
1304       ud, cur_cx_ix-1, SU_CXNAME(cxstack+cur_cx_ix-1),
1305       i, cur_scope_ix, origin[i].orig_ix, origin[i].offset);
1306   });
1307 #else
1308   XSH_D(su_debug_log(
1309     "%p:                 ENTER origin[%d] scope[%d] savestack=%d+%d\n",
1310      ud, i, cur_scope_ix, origin[i].orig_ix, origin[i].offset));
1311 #endif
1312
1313  }
1314
1315  assert(i == depth);
1316
1317  SU_UD_DEPTH(ud)  = depth;
1318  SU_UD_ORIGIN(ud) = origin;
1319
1320  su_ss_push_destructor(aTHX_ ud, depth-1, 1);
1321 }
1322
1323 /* --- Unwind stack -------------------------------------------------------- */
1324
1325 static void su_unwind(pTHX_ void *ud_) {
1326  dXSH_CXT;
1327  I32 cxix  = XSH_CXT.unwind_storage.cxix;
1328  I32 items = XSH_CXT.unwind_storage.items;
1329  I32 mark;
1330
1331  PERL_UNUSED_VAR(ud_);
1332
1333  PL_stack_sp = XSH_CXT.unwind_storage.savesp;
1334 #if XSH_HAS_PERL(5, 19, 4)
1335  {
1336   I32 i;
1337   SV **sp = PL_stack_sp;
1338   for (i = -items + 1; i <= 0; ++i)
1339    if (!SvTEMP(sp[i]))
1340     sv_2mortal(SvREFCNT_inc(sp[i]));
1341  }
1342 #endif
1343
1344  if (cxstack_ix > cxix)
1345   dounwind(cxix);
1346
1347  mark = PL_markstack[cxstack[cxix].blk_oldmarksp];
1348  PUSHMARK(PL_stack_sp - items);
1349
1350  XSH_D({
1351   I32 gimme = GIMME_V;
1352   su_debug_log("%p: cx=%d gimme=%s items=%d sp=%d oldmark=%d mark=%d\n",
1353                 &XSH_CXT, cxix,
1354                 gimme == G_VOID ? "void" : gimme == G_ARRAY ? "list" : "scalar",
1355                 items, PL_stack_sp - PL_stack_base, *PL_markstack_ptr, mark);
1356  });
1357
1358  PL_op = (OP *) &(XSH_CXT.unwind_storage.return_op);
1359  PL_op = PL_op->op_ppaddr(aTHX);
1360
1361  *PL_markstack_ptr = mark;
1362
1363  XSH_CXT.unwind_storage.proxy_op.op_next = PL_op;
1364  PL_op = &(XSH_CXT.unwind_storage.proxy_op);
1365 }
1366
1367 /* --- Yield --------------------------------------------------------------- */
1368
1369 #if XSH_HAS_PERL(5, 10, 0)
1370 # define SU_RETOP_SUB(C)   ((C)->blk_sub.retop)
1371 # define SU_RETOP_EVAL(C)  ((C)->blk_eval.retop)
1372 # define SU_RETOP_LOOP(C)  ((C)->blk_loop.my_op->op_lastop->op_next)
1373 # define SU_RETOP_GIVEN(C) ((C)->blk_givwhen.leave_op->op_next)
1374 #else
1375 # define SU_RETOP_SUB(C)  ((C)->blk_oldretsp > 0 ? PL_retstack[(C)->blk_oldretsp - 1] : NULL)
1376 # define SU_RETOP_EVAL(C) SU_RETOP_SUB(C)
1377 # define SU_RETOP_LOOP(C) ((C)->blk_loop.last_op->op_next)
1378 #endif
1379
1380 static void su_yield(pTHX_ void *ud_) {
1381  dXSH_CXT;
1382  PERL_CONTEXT *cx;
1383  const char   *which = ud_;
1384  I32 cxix      = XSH_CXT.yield_storage.cxix;
1385  I32 items     = XSH_CXT.yield_storage.items;
1386  opcode  type  = OP_NULL;
1387  U8      flags = 0;
1388  OP     *next;
1389
1390  PERL_UNUSED_VAR(ud_);
1391
1392  cx = cxstack + cxix;
1393  switch (CxTYPE(cx)) {
1394   case CXt_BLOCK: {
1395    I32 i, cur = cxstack_ix, n = 1;
1396    OP *o = NULL;
1397    /* Is this actually a given/when block? This may occur only when yield was
1398     * called with HERE (or nothing) as the context. */
1399 #if XSH_HAS_PERL(5, 10, 0)
1400    if (cxix > 0) {
1401     PERL_CONTEXT *prev = cx - 1;
1402     U8       prev_type = CxTYPE(prev);
1403     if ((prev_type == CXt_GIVEN || prev_type == CXt_WHEN)
1404         && (prev->blk_oldcop == cx->blk_oldcop)) {
1405      cxix--;
1406      cx = prev;
1407      if (prev_type == CXt_GIVEN)
1408       goto cxt_given;
1409      else
1410       goto cxt_when;
1411     }
1412    }
1413 #endif
1414    type  = OP_LEAVE;
1415    next  = NULL;
1416    /* Bare blocks (that appear as do { ... } blocks, map { ... } blocks or
1417     * constant folded blcoks) don't need to save the op to return to anywhere
1418     * since 'last' isn't supposed to work inside them. So we climb higher in
1419     * the context stack until we reach a context that has a return op (i.e. a
1420     * sub, an eval, a format or a real loop), recording how many blocks we
1421     * crossed. Then we follow the op_next chain until we get to the leave op
1422     * that closes the original block, which we are assured to reach since
1423     * everything is static (the blocks we have crossed cannot be evals or
1424     * subroutine calls). */
1425    for (i = cxix + 1; i <= cur; ++i) {
1426     PERL_CONTEXT *cx2 = cxstack + i;
1427     switch (CxTYPE(cx2)) {
1428      case CXt_BLOCK:
1429       ++n;
1430       break;
1431      case CXt_SUB:
1432      case CXt_FORMAT:
1433       o = SU_RETOP_SUB(cx2);
1434       break;
1435      case CXt_EVAL:
1436       o = SU_RETOP_EVAL(cx2);
1437       break;
1438 #if XSH_HAS_PERL(5, 11, 0)
1439 # if XSH_HAS_PERL(5, 23, 8)
1440      case CXt_LOOP_ARY:
1441      case CXt_LOOP_LIST:
1442 # else
1443      case CXt_LOOP_FOR:
1444 # endif
1445      case CXt_LOOP_PLAIN:
1446      case CXt_LOOP_LAZYSV:
1447      case CXt_LOOP_LAZYIV:
1448 #else
1449      case CXt_LOOP:
1450 #endif
1451       o = SU_RETOP_LOOP(cx2);
1452       break;
1453     }
1454     if (o)
1455      break;
1456    }
1457    if (!o)
1458     o = PL_op;
1459    while (n && o) {
1460     /* We may find other enter/leave blocks on our way to the matching leave.
1461      * Make sure the depth is incremented/decremented appropriately. */
1462     if (o->op_type == OP_ENTER) {
1463      ++n;
1464     } else if (o->op_type == OP_LEAVE) {
1465      --n;
1466      if (!n) {
1467       next = o->op_next;
1468       break;
1469      }
1470     }
1471     o = o->op_next;
1472    }
1473    break;
1474   }
1475   case CXt_SUB:
1476   case CXt_FORMAT:
1477    type = OP_LEAVESUB;
1478    next = SU_RETOP_SUB(cx);
1479    break;
1480   case CXt_EVAL:
1481    type = CxTRYBLOCK(cx) ? OP_LEAVETRY : OP_LEAVEEVAL;
1482    next = SU_RETOP_EVAL(cx);
1483    break;
1484 #if XSH_HAS_PERL(5, 11, 0)
1485 # if XSH_HAS_PERL(5, 23, 8)
1486   case CXt_LOOP_ARY:
1487   case CXt_LOOP_LIST:
1488 # else
1489   case CXt_LOOP_FOR:
1490 # endif
1491   case CXt_LOOP_PLAIN:
1492   case CXt_LOOP_LAZYSV:
1493   case CXt_LOOP_LAZYIV:
1494 #else
1495   case CXt_LOOP:
1496 #endif
1497    type = OP_LEAVELOOP;
1498    next = SU_RETOP_LOOP(cx);
1499    break;
1500 #if XSH_HAS_PERL(5, 10, 0)
1501   case CXt_GIVEN:
1502 cxt_given:
1503    type = OP_LEAVEGIVEN;
1504    next = SU_RETOP_GIVEN(cx);
1505    break;
1506   case CXt_WHEN:
1507 cxt_when:
1508 #if XSH_HAS_PERL(5, 15, 1)
1509    type   = OP_LEAVEWHEN;
1510 #else
1511    type   = OP_BREAK;
1512    flags |= OPf_SPECIAL;
1513 #endif
1514    next   = NULL;
1515    break;
1516 #endif
1517   case CXt_SUBST:
1518    croak("%s() can't target a substitution context", which);
1519    break;
1520   default:
1521    croak("%s() doesn't know how to leave a %s context",
1522           which,                         SU_CXNAME(cxstack + cxix));
1523    break;
1524  }
1525
1526  PL_stack_sp = XSH_CXT.yield_storage.savesp;
1527 #if XSH_HAS_PERL(5, 19, 4)
1528  {
1529   I32 i;
1530   SV **sp = PL_stack_sp;
1531   for (i = -items + 1; i <= 0; ++i)
1532    if (!SvTEMP(sp[i]))
1533     sv_2mortal(SvREFCNT_inc(sp[i]));
1534  }
1535 #endif
1536
1537  if (cxstack_ix > cxix)
1538   dounwind(cxix);
1539
1540  /* Copy the arguments passed to yield() where the leave op expects to find
1541   * them. */
1542  if (items)
1543   Move(PL_stack_sp - items + 1, PL_stack_base + cx->blk_oldsp + 1, items, SV *);
1544  PL_stack_sp = PL_stack_base + cx->blk_oldsp + items;
1545
1546  flags |= OP_GIMME_REVERSE(cx->blk_gimme);
1547
1548  XSH_CXT.yield_storage.leave_op.op_type   = type;
1549  XSH_CXT.yield_storage.leave_op.op_ppaddr = PL_ppaddr[type];
1550  XSH_CXT.yield_storage.leave_op.op_flags  = flags;
1551  XSH_CXT.yield_storage.leave_op.op_next   = next;
1552
1553  PL_op = (OP *) &(XSH_CXT.yield_storage.leave_op);
1554  PL_op = PL_op->op_ppaddr(aTHX);
1555
1556  XSH_CXT.yield_storage.proxy_op.op_next = PL_op;
1557  PL_op = &(XSH_CXT.yield_storage.proxy_op);
1558 }
1559
1560 /* --- Uplevel ------------------------------------------------------------- */
1561
1562 #define SU_UPLEVEL_SAVE(f, t) STMT_START { sud->old_##f = PL_##f; PL_##f = (t); } STMT_END
1563 #define SU_UPLEVEL_RESTORE(f) STMT_START { PL_##f = sud->old_##f; } STMT_END
1564
1565 static su_uplevel_ud *su_uplevel_storage_new(pTHX_ I32 cxix) {
1566 #define su_uplevel_storage_new(I) su_uplevel_storage_new(aTHX_ (I))
1567  su_uplevel_ud *sud;
1568  UV depth;
1569  dXSH_CXT;
1570
1571  sud = XSH_CXT.uplevel_storage.root;
1572  if (sud) {
1573   XSH_CXT.uplevel_storage.root = sud->next;
1574   XSH_CXT.uplevel_storage.count--;
1575  } else {
1576   sud = su_uplevel_ud_new();
1577  }
1578
1579  sud->next = XSH_CXT.uplevel_storage.top;
1580  XSH_CXT.uplevel_storage.top = sud;
1581
1582  depth = su_uid_depth(cxix);
1583  su_uid_storage_dup(&sud->tmp_uid_storage, &XSH_CXT.uid_storage, depth);
1584  sud->old_uid_storage = XSH_CXT.uid_storage;
1585  XSH_CXT.uid_storage  = sud->tmp_uid_storage;
1586
1587  return sud;
1588 }
1589
1590 #if XSH_HAS_PERL(5, 13, 7)
1591
1592 static void su_uplevel_storage_delete(pTHX_ su_uplevel_ud *sud) {
1593 #define su_uplevel_storage_delete(S) su_uplevel_storage_delete(aTHX_ (S))
1594  dXSH_CXT;
1595
1596  sud->tmp_uid_storage = XSH_CXT.uid_storage;
1597  XSH_CXT.uid_storage   = sud->old_uid_storage;
1598  {
1599   su_uid *map;
1600   STRLEN  i, alloc;
1601   map   = sud->tmp_uid_storage.map;
1602   alloc = sud->tmp_uid_storage.alloc;
1603   for (i = 0; i < alloc; ++i)
1604    map[i].flags &= ~SU_UID_ACTIVE;
1605  }
1606  XSH_CXT.uplevel_storage.top = sud->next;
1607
1608  if (XSH_CXT.uplevel_storage.count >= SU_UPLEVEL_STORAGE_SIZE) {
1609   su_uplevel_ud_delete(sud);
1610  } else {
1611   sud->next = XSH_CXT.uplevel_storage.root;
1612   XSH_CXT.uplevel_storage.root = sud;
1613   XSH_CXT.uplevel_storage.count++;
1614  }
1615 }
1616
1617 #endif
1618
1619 static int su_uplevel_goto_static(const OP *o) {
1620  for (; o; o = OpSIBLING(o)) {
1621   /* goto ops are unops with kids. */
1622   if (!(o->op_flags & OPf_KIDS))
1623    continue;
1624
1625   switch (o->op_type) {
1626    case OP_LEAVEEVAL:
1627    case OP_LEAVETRY:
1628     /* Don't care about gotos inside eval, as they are forbidden at run time. */
1629     break;
1630    case OP_GOTO:
1631     return 1;
1632    default:
1633     if (su_uplevel_goto_static(((const UNOP *) o)->op_first))
1634      return 1;
1635     break;
1636   }
1637  }
1638
1639  return 0;
1640 }
1641
1642 #if !SU_HAS_NEW_CXT && SU_UPLEVEL_HIJACKS_RUNOPS
1643
1644 static int su_uplevel_goto_runops(pTHX) {
1645 #define su_uplevel_goto_runops() su_uplevel_goto_runops(aTHX)
1646  register OP *op;
1647  dVAR;
1648
1649  op = PL_op;
1650  do {
1651   if (op->op_type == OP_GOTO) {
1652    AV  *argarray = NULL;
1653    I32  cxix;
1654
1655    for (cxix = cxstack_ix; cxix >= 0; --cxix) {
1656     const PERL_CONTEXT *cx = cxstack + cxix;
1657
1658     switch (CxTYPE(cx)) {
1659      case CXt_SUB:
1660       if (CxHASARGS(cx)) {
1661        argarray = cx->blk_sub.argarray;
1662        goto done;
1663       }
1664       break;
1665      case CXt_EVAL:
1666      case CXt_FORMAT:
1667       goto done;
1668      default:
1669       break;
1670     }
1671    }
1672
1673 done:
1674    if (argarray) {
1675     dXSH_CXT;
1676
1677     if (XSH_CXT.uplevel_storage.top->cxix == cxix) {
1678      AV  *args  = GvAV(PL_defgv);
1679      I32  items = AvFILLp(args);
1680
1681      av_extend(argarray, items);
1682      Copy(AvARRAY(args), AvARRAY(argarray), items + 1, SV *);
1683      AvFILLp(argarray) = items;
1684     }
1685    }
1686   }
1687
1688   PL_op = op = op->op_ppaddr(aTHX);
1689
1690 #if !XSH_HAS_PERL(5, 13, 0)
1691   PERL_ASYNC_CHECK();
1692 #endif
1693  } while (op);
1694
1695  TAINT_NOT;
1696
1697  return 0;
1698 }
1699
1700 #endif /* SU_UPLEVEL_HIJACKS_RUNOPS */
1701
1702 #define su_at_underscore(C) PadARRAY(PadlistARRAY(CvPADLIST(C))[CvDEPTH(C)])[0]
1703
1704 #if SU_HAS_NEW_CXT
1705
1706 static void su_uplevel_restore_new(pTHX_ void *sus_) {
1707  su_uplevel_ud *sud = sus_;
1708  PERL_CONTEXT *cx;
1709  I32 i;
1710  U8 *saved_cxtypes = sud->cxtypes;
1711
1712  for (i = 0; i < sud->gap; i++) {
1713   PERL_CONTEXT *cx = cxstack + sud->cxix + i;
1714    XSH_D(su_debug_log("su_uplevel_restore: i=%d cxix=%d type %s => %s\n",
1715         i, cx-cxstack, SU_CX_TYPENAME(CxTYPE(cx)),
1716         SU_CX_TYPENAME(saved_cxtypes[i] & CXTYPEMASK)));
1717    cx->cx_type = saved_cxtypes[i];
1718  }
1719  Safefree(saved_cxtypes);
1720
1721  /* renamed is a copy of callback, but they share the same CvPADLIST.
1722   * At this point any calls to renamed should have exited so that its
1723   * depth is back to that of of callback. At this point its safe to free
1724   * renamed, then undo the extra ref count that was ensuring that callback
1725   * remains alive
1726   */
1727  assert(sud->renamed);
1728  assert(sud->callback);
1729
1730  CvDEPTH(sud->callback)--;
1731  assert(CvDEPTH(sud->callback) == CvDEPTH(sud->renamed));
1732  if (!CvISXSUB(sud->renamed)) {
1733   CvDEPTH(sud->renamed)   = 0;
1734   CvPADLIST(sud->renamed) = NULL;
1735  }
1736  SvREFCNT_dec(sud->renamed);
1737  SvREFCNT_dec(sud->callback);
1738
1739  SU_UPLEVEL_RESTORE(curcop);
1740
1741  su_uplevel_storage_delete(sud);
1742
1743  return;
1744 }
1745
1746 #else
1747
1748 /* 5.23.7 and earlier */
1749
1750 static void su_uplevel_restore_old(pTHX_ void *sus_) {
1751  su_uplevel_ud *sud = sus_;
1752  PERL_SI *cur = sud->old_curstackinfo;
1753  PERL_SI *si  = sud->si;
1754
1755 #if SU_UPLEVEL_HIJACKS_RUNOPS
1756  if (PL_runops == su_uplevel_goto_runops)
1757   PL_runops = sud->old_runops;
1758 #endif
1759
1760  if (sud->callback) {
1761   PERL_CONTEXT *cx = cxstack + sud->cxix;
1762   AV     *argarray = MUTABLE_AV(su_at_underscore(sud->callback));
1763
1764   /* We have to fix the pad entry for @_ in the original callback because it
1765    * may have been reified. */
1766   if (AvREAL(argarray)) {
1767    const I32 fill = AvFILLp(argarray);
1768    SvREFCNT_dec(argarray);
1769    argarray = newAV();
1770    AvREAL_off(argarray);
1771    AvREIFY_on(argarray);
1772    av_extend(argarray, fill);
1773    su_at_underscore(sud->callback) = MUTABLE_SV(argarray);
1774   } else {
1775    CLEAR_ARGARRAY(argarray);
1776   }
1777
1778   /* If the old cv member is our renamed CV, it means that this place has been
1779    * reached without a goto() happening, and the old argarray member is
1780    * actually our fake argarray. Destroy it properly in that case. */
1781   if (cx->blk_sub.cv == sud->renamed) {
1782    SvREFCNT_dec(cx->blk_sub.argarray);
1783    cx->blk_sub.argarray = argarray;
1784   }
1785
1786   CvDEPTH(sud->callback)--;
1787   SvREFCNT_dec(sud->callback);
1788  }
1789
1790  /* Free the renamed CV. We must do it ourselves so that we can force the
1791   * depth to be 0, or perl would complain about it being "still in use".
1792   * But we *know* that it cannot be so. */
1793  if (sud->renamed) {
1794   if (!CvISXSUB(sud->renamed)) {
1795    CvDEPTH(sud->renamed)   = 0;
1796    CvPADLIST(sud->renamed) = NULL;
1797   }
1798   SvREFCNT_dec(sud->renamed);
1799  }
1800
1801  CATCH_SET(sud->old_catch);
1802
1803  SU_UPLEVEL_RESTORE(op);
1804
1805  /* stack_grow() wants PL_curstack so restore the old stack first */
1806  if (PL_curstackinfo == si) {
1807   PL_curstack = cur->si_stack;
1808   if (sud->old_mainstack)
1809    SU_UPLEVEL_RESTORE(mainstack);
1810   SU_UPLEVEL_RESTORE(curstackinfo);
1811
1812   if (sud->died) {
1813    CV *target = sud->target;
1814    I32 levels = 0, i;
1815
1816    /* When we die, the depth of the target CV is not updated because of the
1817     * stack switcheroo. So we have to look at all the frames between the
1818     * uplevel call and the catch block to count how many call frames to the
1819     * target CV were skipped. */
1820    for (i = cur->si_cxix; i > sud->cxix; i--) {
1821     register const PERL_CONTEXT *cx = cxstack + i;
1822
1823     if (CxTYPE(cx) == CXt_SUB) {
1824      if (cx->blk_sub.cv == target)
1825       ++levels;
1826     }
1827    }
1828
1829    /* If we died, the replacement stack was already unwinded to the first
1830     * eval frame, and all the contexts down there were popped. We don't have
1831     * to pop manually any context of the original stack, because they must
1832     * have been in the replacement stack as well (since the second was copied
1833     * from the first). Thus we only have to make sure the original stack index
1834     * points to the context just below the first eval scope under the target
1835     * frame. */
1836    for (; i >= 0; i--) {
1837     register const PERL_CONTEXT *cx = cxstack + i;
1838
1839     switch (CxTYPE(cx)) {
1840      case CXt_SUB:
1841       if (cx->blk_sub.cv == target)
1842        ++levels;
1843       break;
1844      case CXt_EVAL:
1845       goto found_it;
1846       break;
1847      default:
1848       break;
1849     }
1850    }
1851
1852 found_it:
1853    CvDEPTH(target) = sud->target_depth - levels;
1854    PL_curstackinfo->si_cxix = i - 1;
1855
1856 #if !XSH_HAS_PERL(5, 13, 1)
1857    /* Since $@ was maybe localized between the target frame and the uplevel
1858     * call, we forcefully flush the save stack to get rid of it and then
1859     * reset $@ to its proper value. Note that the the call to
1860     * su_uplevel_restore() must happen before the "reset $@" item of the save
1861     * stack is processed, as uplevel was called after the localization.
1862     * Andrew's changes to how $@ was handled, which were mainly integrated
1863     * between perl 5.13.0 and 5.13.1, fixed this. */
1864    if (ERRSV && SvTRUE(ERRSV)) {
1865     register const PERL_CONTEXT *cx = cxstack + i; /* This is the eval scope */
1866     SV *errsv = SvREFCNT_inc(ERRSV);
1867     PL_scopestack_ix = cx->blk_oldscopesp;
1868     leave_scope(PL_scopestack[PL_scopestack_ix]);
1869     sv_setsv(ERRSV, errsv);
1870     SvREFCNT_dec(errsv);
1871    }
1872 #endif
1873   }
1874  }
1875
1876  SU_UPLEVEL_RESTORE(curcop);
1877
1878  SvREFCNT_dec(sud->target);
1879
1880  PL_stack_base = AvARRAY(cur->si_stack);
1881  PL_stack_sp   = PL_stack_base + AvFILLp(cur->si_stack);
1882  PL_stack_max  = PL_stack_base + AvMAX(cur->si_stack);
1883
1884  /* When an exception is thrown from the uplevel'd subroutine,
1885   * su_uplevel_restore() may be called by the LEAVE in die_unwind() (renamed
1886   * die_where() in more recent perls), which has the sad habit of keeping a
1887   * pointer to the current context frame across this call. This means that we
1888   * can't free the temporary context stack we used for the uplevel call right
1889   * now, or that pointer upwards would point to garbage. */
1890 #if XSH_HAS_PERL(5, 13, 7)
1891  /* This issue has been fixed in perl with commit 8f89e5a9, which was made
1892   * public in perl 5.13.7. */
1893  su_uplevel_storage_delete(sud);
1894 #else
1895  /* Otherwise, we just enqueue it back in the global storage list. */
1896  {
1897   dXSH_CXT;
1898
1899   sud->tmp_uid_storage = XSH_CXT.uid_storage;
1900   XSH_CXT.uid_storage  = sud->old_uid_storage;
1901
1902   XSH_CXT.uplevel_storage.top  = sud->next;
1903   sud->next = XSH_CXT.uplevel_storage.root;
1904   XSH_CXT.uplevel_storage.root = sud;
1905   XSH_CXT.uplevel_storage.count++;
1906  }
1907 #endif
1908
1909  return;
1910 }
1911
1912 #endif
1913
1914 static CV *su_cv_clone(pTHX_ CV *proto, GV *gv) {
1915 #define su_cv_clone(P, G) su_cv_clone(aTHX_ (P), (G))
1916  dVAR;
1917  CV *cv;
1918
1919  cv = MUTABLE_CV(newSV_type(SvTYPE(proto)));
1920
1921  CvFLAGS(cv)  = CvFLAGS(proto);
1922 #ifdef CVf_CVGV_RC
1923  CvFLAGS(cv) &= ~CVf_CVGV_RC;
1924 #endif
1925  CvDEPTH(cv)  = CvDEPTH(proto);
1926 #ifdef USE_ITHREADS
1927  CvFILE(cv)   = CvISXSUB(proto) ? CvFILE(proto) : savepv(CvFILE(proto));
1928 #else
1929  CvFILE(cv)   = CvFILE(proto);
1930 #endif
1931
1932  CvGV_set(cv, gv);
1933 #if SU_RELEASE && XSH_HAS_PERL_EXACT(5, 21, 4)
1934  CvNAMED_off(cv);
1935 #endif
1936  CvSTASH_set(cv, CvSTASH(proto));
1937  /* Commit 4c74a7df, publicized with perl 5.13.3, began to add backrefs to
1938   * stashes. CvSTASH_set() started to do it as well with commit c68d95645
1939   * (which was part of perl 5.13.7). */
1940 #if XSH_HAS_PERL(5, 13, 3) && !XSH_HAS_PERL(5, 13, 7)
1941  if (CvSTASH(proto))
1942   Perl_sv_add_backref(aTHX_ CvSTASH(proto), MUTABLE_SV(cv));
1943 #endif
1944
1945  if (CvISXSUB(proto)) {
1946   CvXSUB(cv)       = CvXSUB(proto);
1947   CvXSUBANY(cv)    = CvXSUBANY(proto);
1948  } else {
1949   OP_REFCNT_LOCK;
1950   CvROOT(cv)       = OpREFCNT_inc(CvROOT(proto));
1951   OP_REFCNT_UNLOCK;
1952   CvSTART(cv)      = CvSTART(proto);
1953   CvPADLIST(cv)    = CvPADLIST(proto);
1954  }
1955  CvOUTSIDE(cv)     = CvOUTSIDE(proto);
1956 #ifdef CVf_WEAKOUTSIDE
1957  if (!(CvFLAGS(proto) & CVf_WEAKOUTSIDE))
1958 #endif
1959   SvREFCNT_inc_simple_void(CvOUTSIDE(cv));
1960 #ifdef CvOUTSIDE_SEQ
1961  CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(proto);
1962 #endif
1963
1964  if (SvPOK(proto))
1965   sv_setpvn(MUTABLE_SV(cv), SvPVX_const(proto), SvCUR(proto));
1966
1967 #ifdef CvCONST
1968  if (CvCONST(cv))
1969   CvCONST_off(cv);
1970 #endif
1971
1972  return cv;
1973 }
1974
1975 #if SU_HAS_NEW_CXT
1976
1977 /* this one-shot runops "loop" is designed to be called just before
1978  * execution of the first op following an uplevel()'s entersub. It gets a
1979  * chance to fix up the args as seen by caller(), before immediately
1980  * falling through to the previous runops loop. Note that pp_entersub is
1981  * called directly by call_sv() rather than being called from a runops
1982  * loop.
1983  */
1984
1985 static int su_uplevel_runops_hook_entersub(pTHX) {
1986  OP *op = PL_op;
1987  dXSH_CXT;
1988  su_uplevel_ud *sud = XSH_CXT.uplevel_storage.top;
1989
1990  /* Create a new array containing a copy of the original sub's call args,
1991   * then stick it in PL_curpad[0] of the current running sub so that
1992   * thay will be seen by caller().
1993   */
1994  assert(sud);
1995  if (sud->argarray) {
1996   AV *av = newAV();
1997   AvREAL_off(av);
1998   AvREIFY_on(av);
1999   av_extend(av, AvMAX(sud->argarray));
2000   AvFILLp(av) = AvFILLp(sud->argarray);
2001   Copy(AvARRAY(sud->argarray), AvARRAY(av), AvFILLp(av) + 1, SV *);
2002
2003   /* should be referenced by PL_curpad[0] and *_ */
2004   assert(SvREFCNT(PL_curpad[0]) > 1);
2005   SvREFCNT_dec(PL_curpad[0]);
2006
2007   PL_curpad[0] = (SV*)av;
2008  }
2009
2010  /* undo the temporary runops hook and fall through to a real runops loop. */
2011  assert(sud->old_runops != su_uplevel_runops_hook_entersub);
2012  PL_runops = sud->old_runops;
2013  CALLRUNOPS(aTHX);
2014  return 0;
2015 }
2016
2017 static I32 su_uplevel_new(pTHX_ CV *callback, I32 cxix, I32 args) {
2018  su_uplevel_ud *sud;
2019  U8 *saved_cxtypes;
2020  I32 i, ret;
2021  I32  gimme;
2022  CV *base_cv = cxstack[cxix].blk_sub.cv;
2023  dSP;
2024
2025  assert(CxTYPE(&cxstack[cxix]) == CXt_SUB);
2026
2027  ENTER;
2028
2029  gimme = GIMME_V;
2030
2031  /* At this point SP points to the top arg.
2032   * Shuffle the args down by one, eliminating the CV slot */
2033  Move(SP - args + 1, SP - args, args, SV*);
2034  SP--;
2035  PUSHMARK(SP - args);
2036  PUTBACK;
2037
2038  sud = su_uplevel_storage_new(cxix);
2039
2040  sud->cxix     = cxix;
2041  sud->callback = (CV*)SvREFCNT_inc_simple(callback);
2042  sud->renamed  = NULL;
2043  sud->gap      = cxstack_ix - cxix + 1;
2044  sud->argarray = NULL;
2045
2046  Newx(saved_cxtypes, sud->gap, U8);
2047  sud->cxtypes = saved_cxtypes;
2048
2049  SAVEDESTRUCTOR_X(su_uplevel_restore_new, sud);
2050  SU_UPLEVEL_SAVE(curcop, cxstack[cxix].blk_oldcop);
2051
2052 /* temporarily change the type of any contexts to NULL, so they're
2053  * invisible to caller() etc. */
2054  for (i = 0; i < sud->gap; i++) {
2055   PERL_CONTEXT *cx = cxstack + cxix + i;
2056   saved_cxtypes[i] = cx->cx_type; /* save type and flags */
2057   XSH_D(su_debug_log("su_uplevel: i=%d cxix=%d type %-11s => %s\n",
2058         i, cx-cxstack, SU_CX_TYPENAME(CxTYPE(cx)), SU_CX_TYPENAME(CXt_NULL)));
2059   cx->cx_type = (CXt_NULL | CXp_SU_UPLEVEL_NULLED);
2060  }
2061
2062  /* create a copy of the callback with a doctored name (as seen by
2063   * caller). It shares the padlist with callback */
2064  sud->renamed = su_cv_clone(callback, CvGV(base_cv));
2065  sud->old_runops = PL_runops;
2066
2067  if (!CvISXSUB(sud->renamed) && CxHASARGS(&cxstack[cxix])) {
2068   sud->argarray = (AV*)su_at_underscore(base_cv);
2069   assert(PL_runops != su_uplevel_runops_hook_entersub);
2070   /* set up a one-shot runops hook so that we can fake up the
2071    * args as seen by caller() on return from pp_entersub */
2072   PL_runops = su_uplevel_runops_hook_entersub;
2073  }
2074
2075  CvDEPTH(callback)++; /* match what CvDEPTH(sud->renamed) is about to become */
2076
2077  ret = call_sv((SV*)sud->renamed, gimme);
2078
2079  LEAVE;
2080
2081  return ret;
2082 }
2083
2084 #else
2085
2086 static I32 su_uplevel_old(pTHX_ CV *callback, I32 cxix, I32 args) {
2087  su_uplevel_ud *sud;
2088  const PERL_CONTEXT *cx = cxstack + cxix;
2089  PERL_SI *si;
2090  PERL_SI *cur = PL_curstackinfo;
2091  SV **old_stack_sp;
2092  CV  *target;
2093  CV  *renamed;
2094  UNOP sub_op;
2095  I32  gimme;
2096  I32  old_mark, new_mark;
2097  I32  ret;
2098  dSP;
2099
2100  ENTER;
2101
2102  gimme = GIMME_V;
2103  /* Make PL_stack_sp point just before the CV. */
2104  PL_stack_sp -= args + 1;
2105  old_mark = AvFILLp(PL_curstack) = PL_stack_sp - PL_stack_base;
2106  SPAGAIN;
2107
2108  sud = su_uplevel_storage_new(cxix);
2109
2110  sud->cxix     = cxix;
2111  sud->died     = 1;
2112  sud->callback = NULL;
2113  sud->renamed  = NULL;
2114  SAVEDESTRUCTOR_X(su_uplevel_restore_old, sud);
2115
2116  si = sud->si;
2117
2118  si->si_type    = cur->si_type;
2119  si->si_next    = NULL;
2120  si->si_prev    = cur->si_prev;
2121 #ifdef DEBUGGING
2122  si->si_markoff = cx->blk_oldmarksp;
2123 #endif
2124
2125  /* Allocate enough space for all the elements of the original stack up to the
2126   * target context, plus the forthcoming arguments. */
2127  new_mark = cx->blk_oldsp;
2128  av_extend(si->si_stack, new_mark + 1 + args + 1);
2129  Copy(AvARRAY(PL_curstack), AvARRAY(si->si_stack), new_mark + 1, SV *);
2130  AvFILLp(si->si_stack) = new_mark;
2131  SU_POISON(AvARRAY(si->si_stack) + new_mark + 1, args + 1, SV *);
2132
2133  /* Specialized SWITCHSTACK() */
2134  PL_stack_base = AvARRAY(si->si_stack);
2135  old_stack_sp  = PL_stack_sp;
2136  PL_stack_sp   = PL_stack_base + AvFILLp(si->si_stack);
2137  PL_stack_max  = PL_stack_base + AvMAX(si->si_stack);
2138  SPAGAIN;
2139
2140  /* Copy the context stack up to the context just below the target. */
2141  si->si_cxix = (cxix < 0) ? -1 : (cxix - 1);
2142  if (si->si_cxmax < cxix) {
2143   /* The max size must be at least two so that GROW(max) = (max*3)/2 > max */
2144   si->si_cxmax = (cxix < 4) ? 4 : cxix;
2145   Renew(si->si_cxstack, si->si_cxmax + 1, PERL_CONTEXT);
2146  }
2147  Copy(cur->si_cxstack, si->si_cxstack, cxix, PERL_CONTEXT);
2148  SU_POISON(si->si_cxstack + cxix, si->si_cxmax + 1 - cxix, PERL_CONTEXT);
2149
2150  target            = cx->blk_sub.cv;
2151  sud->target       = (CV *) SvREFCNT_inc(target);
2152  sud->target_depth = CvDEPTH(target);
2153
2154  /* blk_oldcop is essentially needed for caller() and stack traces. It has no
2155   * run-time implication, since PL_curcop will be overwritten as soon as we
2156   * enter a sub (a sub starts by a nextstate/dbstate). Hence it's safe to just
2157   * make it point to the blk_oldcop for the target frame, so that caller()
2158   * reports the right file name, line number and lexical hints. */
2159  SU_UPLEVEL_SAVE(curcop, cx->blk_oldcop);
2160  /* Don't reset PL_markstack_ptr, or we would overwrite the mark stack below
2161   * this point. Don't reset PL_curpm either, we want the most recent matches. */
2162
2163  SU_UPLEVEL_SAVE(curstackinfo, si);
2164  /* If those two are equal, we need to fool POPSTACK_TO() */
2165  if (PL_mainstack == PL_curstack)
2166   SU_UPLEVEL_SAVE(mainstack, si->si_stack);
2167  else
2168   sud->old_mainstack = NULL;
2169  PL_curstack = si->si_stack;
2170
2171  renamed      = su_cv_clone(callback, CvGV(target));
2172  sud->renamed = renamed;
2173
2174  PUSHMARK(SP);
2175  /* Both SP and old_stack_sp point just before the CV. */
2176  Copy(old_stack_sp + 2, SP + 1, args, SV *);
2177  SP += args;
2178  PUSHs((SV *) renamed);
2179  PUTBACK;
2180
2181  Zero(&sub_op, 1, UNOP);
2182  sub_op.op_type  = OP_ENTERSUB;
2183  sub_op.op_next  = NULL;
2184  sub_op.op_flags = OP_GIMME_REVERSE(gimme) | OPf_STACKED;
2185  if (PL_DBsub)
2186   sub_op.op_flags |= OPpENTERSUB_DB;
2187
2188  SU_UPLEVEL_SAVE(op, (OP *) &sub_op);
2189
2190 #if SU_UPLEVEL_HIJACKS_RUNOPS
2191  sud->old_runops = PL_runops;
2192 #endif
2193
2194  sud->old_catch = CATCH_GET;
2195  CATCH_SET(TRUE);
2196
2197  if ((PL_op = PL_ppaddr[OP_ENTERSUB](aTHX))) {
2198   PERL_CONTEXT *sub_cx = cxstack + cxstack_ix;
2199   AV *argarray = cx->blk_sub.argarray;
2200
2201   /* If pp_entersub() returns a non-null OP, it means that the callback is not
2202    * an XSUB. */
2203
2204   sud->callback = MUTABLE_CV(SvREFCNT_inc(callback));
2205   CvDEPTH(callback)++;
2206
2207   if (CxHASARGS(cx) && argarray) {
2208    /* The call to pp_entersub() has saved the current @_ (in XS terms,
2209     * GvAV(PL_defgv)) in the savearray member, and has created a new argarray
2210     * with what we put on the stack. But we want to fake up the same arguments
2211     * as the ones in use at the context we uplevel to, so we replace the
2212     * argarray with an unreal copy of the original @_. */
2213    AV *av = newAV();
2214    AvREAL_off(av);
2215    AvREIFY_on(av);
2216    av_extend(av, AvMAX(argarray));
2217    AvFILLp(av) = AvFILLp(argarray);
2218    Copy(AvARRAY(argarray), AvARRAY(av), AvFILLp(av) + 1, SV *);
2219    sub_cx->blk_sub.argarray = av;
2220   } else {
2221    SvREFCNT_inc_simple_void(sub_cx->blk_sub.argarray);
2222   }
2223
2224   if (su_uplevel_goto_static(CvROOT(renamed))) {
2225 #if SU_UPLEVEL_HIJACKS_RUNOPS
2226    if (PL_runops != PL_runops_std) {
2227     if (PL_runops == PL_runops_dbg) {
2228      if (PL_debug)
2229       croak("uplevel() can't execute code that calls goto when debugging flags are set");
2230     } else if (PL_runops != su_uplevel_goto_runops)
2231      croak("uplevel() can't execute code that calls goto with a custom runloop");
2232    }
2233
2234    PL_runops = su_uplevel_goto_runops;
2235 #else  /* SU_UPLEVEL_HIJACKS_RUNOPS */
2236    croak("uplevel() can't execute code that calls goto before perl 5.8");
2237 #endif /* !SU_UPLEVEL_HIJACKS_RUNOPS */
2238   }
2239
2240   CALLRUNOPS(aTHX);
2241  }
2242
2243  sud->died = 0;
2244
2245  ret = PL_stack_sp - (PL_stack_base + new_mark);
2246  if (ret > 0) {
2247   AV *old_stack = sud->old_curstackinfo->si_stack;
2248
2249   if (old_mark + ret > AvMAX(old_stack)) {
2250    /* Specialized EXTEND(old_sp, ret) */
2251    av_extend(old_stack, old_mark + ret + 1);
2252    old_stack_sp = AvARRAY(old_stack) + old_mark;
2253   }
2254
2255   Copy(PL_stack_sp - ret + 1, old_stack_sp + 1, ret, SV *);
2256   PL_stack_sp        += ret;
2257   AvFILLp(old_stack) += ret;
2258  }
2259
2260  LEAVE;
2261
2262  return ret;
2263 }
2264
2265 #endif
2266
2267 /* --- Unique context ID --------------------------------------------------- */
2268
2269 static su_uid *su_uid_storage_fetch(pTHX_ UV depth) {
2270 #define su_uid_storage_fetch(D) su_uid_storage_fetch(aTHX_ (D))
2271  su_uid *map;
2272  STRLEN  alloc;
2273  dXSH_CXT;
2274
2275  map   = XSH_CXT.uid_storage.map;
2276  alloc = XSH_CXT.uid_storage.alloc;
2277
2278  if (depth >= alloc) {
2279   STRLEN i;
2280
2281   Renew(map, depth + 1, su_uid);
2282   for (i = alloc; i <= depth; ++i) {
2283    map[i].seq   = 0;
2284    map[i].flags = 0;
2285   }
2286
2287   XSH_CXT.uid_storage.map   = map;
2288   XSH_CXT.uid_storage.alloc = depth + 1;
2289  }
2290
2291  if (depth >= XSH_CXT.uid_storage.used)
2292   XSH_CXT.uid_storage.used = depth + 1;
2293
2294  return map + depth;
2295 }
2296
2297 static int su_uid_storage_check(pTHX_ UV depth, UV seq) {
2298 #define su_uid_storage_check(D, S) su_uid_storage_check(aTHX_ (D), (S))
2299  su_uid *uid;
2300  dXSH_CXT;
2301
2302  if (depth >= XSH_CXT.uid_storage.used)
2303   return 0;
2304
2305  uid = XSH_CXT.uid_storage.map + depth;
2306
2307  return (uid->seq == seq) && (uid->flags & SU_UID_ACTIVE);
2308 }
2309
2310 static SV *su_uid_get(pTHX_ I32 cxix) {
2311 #define su_uid_get(I) su_uid_get(aTHX_ (I))
2312  su_uid *uid;
2313  SV     *uid_sv;
2314  UV      depth;
2315
2316  depth = su_uid_depth(cxix);
2317  uid   = su_uid_storage_fetch(depth);
2318
2319  if (!(uid->flags & SU_UID_ACTIVE)) {
2320   su_ud_uid *ud;
2321
2322   uid->seq    = su_uid_seq_next(depth);
2323   uid->flags |= SU_UID_ACTIVE;
2324
2325   Newx(ud, 1, su_ud_uid);
2326   SU_UD_TYPE(ud) = SU_UD_TYPE_UID;
2327   ud->idx        = depth;
2328   su_init(ud, cxix, SU_SAVE_DESTRUCTOR_SIZE);
2329  }
2330
2331  uid_sv = sv_newmortal();
2332  sv_setpvf(uid_sv, "%"UVuf"-%"UVuf, depth, uid->seq);
2333
2334  return uid_sv;
2335 }
2336
2337 #ifdef grok_number
2338
2339 #define su_grok_number(S, L, VP) grok_number((S), (L), (VP))
2340
2341 #else /* grok_number */
2342
2343 #define IS_NUMBER_IN_UV 0x1
2344
2345 static int su_grok_number(pTHX_ const char *s, STRLEN len, UV *valuep) {
2346 #define su_grok_number(S, L, VP) su_grok_number(aTHX_ (S), (L), (VP))
2347  STRLEN i;
2348  SV *tmpsv;
2349
2350  /* This crude check should be good enough for a fallback implementation.
2351   * Better be too strict than too lax. */
2352  for (i = 0; i < len; ++i) {
2353   if (!isDIGIT(s[i]))
2354    return 0;
2355  }
2356
2357  tmpsv = sv_newmortal();
2358  sv_setpvn(tmpsv, s, len);
2359  *valuep = sv_2uv(tmpsv);
2360
2361  return IS_NUMBER_IN_UV;
2362 }
2363
2364 #endif /* !grok_number */
2365
2366 static int su_uid_validate(pTHX_ SV *uid) {
2367 #define su_uid_validate(U) su_uid_validate(aTHX_ (U))
2368  const char *s;
2369  STRLEN len, p = 0;
2370  UV depth, seq;
2371  int type;
2372
2373  s = SvPV_const(uid, len);
2374
2375  while (p < len && s[p] != '-')
2376   ++p;
2377  if (p >= len)
2378   croak("UID contains only one part");
2379
2380  type = su_grok_number(s, p, &depth);
2381  if (type != IS_NUMBER_IN_UV)
2382   croak("First UID part is not an unsigned integer");
2383
2384  ++p; /* Skip '-'. As we used to have p < len, len - (p + 1) >= 0. */
2385
2386  type = su_grok_number(s + p, len - p, &seq);
2387  if (type != IS_NUMBER_IN_UV)
2388   croak("Second UID part is not an unsigned integer");
2389
2390  return su_uid_storage_check(depth, seq);
2391 }
2392
2393 /* --- Context operations -------------------------------------------------- */
2394
2395 /* Remove sequences of BLOCKs having DB for stash, followed by a SUB context
2396  * for the debugger callback. */
2397
2398 static I32 su_context_skip_db(pTHX_ I32 cxix) {
2399 #define su_context_skip_db(C) su_context_skip_db(aTHX_ (C))
2400  I32 i;
2401
2402  if (!PL_DBsub)
2403   return cxix;
2404
2405  for (i = cxix; i > 0; --i) {
2406   PERL_CONTEXT *cx = cxstack + i;
2407
2408   switch (CxTYPE(cx)) {
2409 #if XSH_HAS_PERL(5, 17, 1)
2410    case CXt_LOOP_PLAIN:
2411 #endif
2412    case CXt_BLOCK:
2413     if (cx->blk_oldcop && CopSTASH(cx->blk_oldcop) == GvSTASH(PL_DBgv))
2414      continue;
2415     break;
2416    case CXt_SUB:
2417     if (cx->blk_sub.cv == GvCV(PL_DBsub)) {
2418      cxix = i - 1;
2419      continue;
2420     }
2421     break;
2422    default:
2423     break;
2424   }
2425
2426   break;
2427  }
2428
2429  return cxix;
2430 }
2431
2432 #if SU_HAS_NEW_CXT
2433
2434 /* convert a physical context stack index into the logical equivalent:
2435  * one that ignores all the context frames hidden by uplevel().
2436  * Perl-level functions use logical args (e.g. UP takes an optional logical
2437  * value and returns a logical value), while we use and store *real*
2438  * values internally.
2439  */
2440
2441 static I32 su_context_real2logical(pTHX_ I32 cxix) {
2442 # define su_context_real2logical(C) su_context_real2logical(aTHX_ (C))
2443  PERL_CONTEXT *cx;
2444  I32 i, gaps = 0;
2445
2446  for (i = 0; i <= cxix; i++) {
2447   cx = cxstack + i;
2448   if (cx->cx_type == (CXt_NULL | CXp_SU_UPLEVEL_NULLED))
2449    gaps++;
2450  }
2451  XSH_D(su_debug_log("su_context_real2logical: %d => %d\n", cxix, cxix - gaps));
2452  return cxix - gaps;
2453 }
2454
2455 /* convert a logical context stack index (one that ignores all the context
2456  * frames hidden by uplevel) into the physical equivalent
2457  */
2458
2459 static I32 su_context_logical2real(pTHX_ I32 cxix) {
2460 # define su_context_logical2real(C) su_context_logical2real(aTHX_ (C))
2461  PERL_CONTEXT *cx;
2462  I32 i, seen = -1;
2463
2464  for (i = 0; i <= cxstack_ix; i++) {
2465   PERL_CONTEXT *cx = cxstack + i;
2466   if (cx->cx_type != (CXt_NULL | CXp_SU_UPLEVEL_NULLED))
2467    seen++;
2468   if (seen >= cxix)
2469    break;
2470  }
2471  XSH_D(su_debug_log("su_context_logical2real: %d => %d\n", cxix, i));
2472  if (i > cxstack_ix)
2473   i = cxstack_ix;
2474  return i;
2475 }
2476
2477 #else
2478 # define su_context_real2logical(C) (C)
2479 # define su_context_logical2real(C) (C)
2480 #endif
2481
2482 static I32 su_context_normalize_up(pTHX_ I32 cxix) {
2483 #define su_context_normalize_up(C) su_context_normalize_up(aTHX_ (C))
2484  PERL_CONTEXT *cx;
2485
2486  if (cxix <= 0)
2487   return 0;
2488
2489  cx = cxstack + cxix;
2490  if (CxTYPE(cx) == CXt_BLOCK) {
2491   PERL_CONTEXT *prev = cx - 1;
2492
2493   switch (CxTYPE(prev)) {
2494 #if XSH_HAS_PERL(5, 10, 0)
2495    case CXt_GIVEN:
2496    case CXt_WHEN:
2497 #endif
2498 #if XSH_HAS_PERL(5, 11, 0)
2499    /* That's the only subcategory that can cause an extra BLOCK context */
2500    case CXt_LOOP_PLAIN:
2501 #else
2502    case CXt_LOOP:
2503 #endif
2504     if (cx->blk_oldcop == prev->blk_oldcop)
2505      return cxix - 1;
2506     break;
2507    case CXt_SUBST:
2508     if (cx->blk_oldcop && OpSIBLING(cx->blk_oldcop)
2509                        && OpSIBLING(cx->blk_oldcop)->op_type == OP_SUBST)
2510      return cxix - 1;
2511     break;
2512   }
2513  }
2514
2515  return cxix;
2516 }
2517
2518 static I32 su_context_normalize_down(pTHX_ I32 cxix) {
2519 #define su_context_normalize_down(C) su_context_normalize_down(aTHX_ (C))
2520  PERL_CONTEXT *next;
2521
2522  if (cxix >= cxstack_ix)
2523   return cxstack_ix;
2524
2525  next = cxstack + cxix + 1;
2526  if (CxTYPE(next) == CXt_BLOCK) {
2527   PERL_CONTEXT *cx = next - 1;
2528
2529   switch (CxTYPE(cx)) {
2530 #if XSH_HAS_PERL(5, 10, 0)
2531    case CXt_GIVEN:
2532    case CXt_WHEN:
2533 #endif
2534 #if XSH_HAS_PERL(5, 11, 0)
2535    /* That's the only subcategory that can cause an extra BLOCK context */
2536    case CXt_LOOP_PLAIN:
2537 #else
2538    case CXt_LOOP:
2539 #endif
2540     if (cx->blk_oldcop == next->blk_oldcop)
2541      return cxix + 1;
2542     break;
2543    case CXt_SUBST:
2544     if (next->blk_oldcop && OpSIBLING(next->blk_oldcop)
2545                          && OpSIBLING(next->blk_oldcop)->op_type == OP_SUBST)
2546      return cxix + 1;
2547     break;
2548   }
2549  }
2550
2551  return cxix;
2552 }
2553
2554 #define su_context_here() su_context_normalize_up(su_context_skip_db(cxstack_ix))
2555
2556 static I32 su_context_gimme(pTHX_ I32 cxix) {
2557 #define su_context_gimme(C) su_context_gimme(aTHX_ (C))
2558  I32 i;
2559
2560  for (i = cxix; i >= 0; --i) {
2561   PERL_CONTEXT *cx = cxstack + i;
2562
2563   switch (CxTYPE(cx)) {
2564    /* gimme is always G_ARRAY for loop contexts. */
2565 #if XSH_HAS_PERL(5, 11, 0)
2566 # if XSH_HAS_PERL(5, 23, 8)
2567    case CXt_LOOP_ARY:
2568    case CXt_LOOP_LIST:
2569 # else
2570    case CXt_LOOP_FOR:
2571 # endif
2572    case CXt_LOOP_PLAIN:
2573    case CXt_LOOP_LAZYSV:
2574    case CXt_LOOP_LAZYIV:
2575 #else
2576    case CXt_LOOP:
2577 #endif
2578    case CXt_SUBST: {
2579     const COP *cop = cx->blk_oldcop;
2580     if (cop && OpSIBLING(cop)) {
2581      switch (OpSIBLING(cop)->op_flags & OPf_WANT) {
2582       case OPf_WANT_VOID:
2583        return G_VOID;
2584       case OPf_WANT_SCALAR:
2585        return G_SCALAR;
2586       case OPf_WANT_LIST:
2587        return G_ARRAY;
2588       default:
2589        break;
2590      }
2591     }
2592     break;
2593    }
2594    default:
2595     return CxGIMME(cx);
2596     break;
2597   }
2598  }
2599
2600  return G_VOID;
2601 }
2602
2603 /* --- Module setup/teardown ----------------------------------------------- */
2604
2605 static void xsh_user_global_setup(pTHX) {
2606  HV *stash;
2607
2608  MUTEX_INIT(&su_uid_seq_counter_mutex);
2609
2610  XSH_LOCK(&su_uid_seq_counter_mutex);
2611  su_uid_seq_counter.seqs = NULL;
2612  su_uid_seq_counter.size = 0;
2613  XSH_UNLOCK(&su_uid_seq_counter_mutex);
2614
2615  stash = gv_stashpv(XSH_PACKAGE, 1);
2616  newCONSTSUB(stash, "TOP",           newSViv(0));
2617  newCONSTSUB(stash, "SU_THREADSAFE", newSVuv(XSH_THREADSAFE));
2618
2619  return;
2620 }
2621
2622 static void xsh_user_local_setup(pTHX_ xsh_user_cxt_t *cxt) {
2623
2624  /* NewOp() calls calloc() which just zeroes the memory with memset(). */
2625  Zero(&(cxt->unwind_storage.return_op), 1, LISTOP);
2626  cxt->unwind_storage.return_op.op_type   = OP_RETURN;
2627  cxt->unwind_storage.return_op.op_ppaddr = PL_ppaddr[OP_RETURN];
2628
2629  Zero(&(cxt->unwind_storage.proxy_op), 1, OP);
2630  cxt->unwind_storage.proxy_op.op_type   = OP_STUB;
2631  cxt->unwind_storage.proxy_op.op_ppaddr = NULL;
2632
2633  Zero(&(cxt->yield_storage.leave_op), 1, UNOP);
2634  cxt->yield_storage.leave_op.op_type   = OP_STUB;
2635  cxt->yield_storage.leave_op.op_ppaddr = NULL;
2636
2637  Zero(&(cxt->yield_storage.proxy_op), 1, OP);
2638  cxt->yield_storage.proxy_op.op_type   = OP_STUB;
2639  cxt->yield_storage.proxy_op.op_ppaddr = NULL;
2640
2641  cxt->uplevel_storage.top   = NULL;
2642  cxt->uplevel_storage.root  = NULL;
2643  cxt->uplevel_storage.count = 0;
2644
2645  cxt->uid_storage.map   = NULL;
2646  cxt->uid_storage.used  = 0;
2647  cxt->uid_storage.alloc = 0;
2648
2649  return;
2650 }
2651
2652 static void xsh_user_local_teardown(pTHX_ xsh_user_cxt_t *cxt) {
2653  su_uplevel_ud *cur;
2654
2655  Safefree(cxt->uid_storage.map);
2656
2657  cur = cxt->uplevel_storage.root;
2658  if (cur) {
2659   su_uplevel_ud *prev;
2660   do {
2661    prev = cur;
2662    cur  = prev->next;
2663    su_uplevel_ud_delete(prev);
2664   } while (cur);
2665  }
2666
2667  return;
2668 }
2669
2670 static void xsh_user_global_teardown(pTHX) {
2671  XSH_LOCK(&su_uid_seq_counter_mutex);
2672  PerlMemShared_free(su_uid_seq_counter.seqs);
2673  su_uid_seq_counter.size = 0;
2674  XSH_UNLOCK(&su_uid_seq_counter_mutex);
2675
2676  MUTEX_DESTROY(&su_uid_seq_counter_mutex);
2677
2678  return;
2679 }
2680
2681 /* --- XS ------------------------------------------------------------------ */
2682
2683 /* D is real; B is logical. Returns real. */
2684
2685 #define SU_GET_CONTEXT(A, B, D) \
2686  STMT_START {                   \
2687   if (items > A) {              \
2688    SV *csv = ST(B);             \
2689    if (!SvOK(csv))              \
2690     goto default_cx;            \
2691    cxix = SvIV(csv);            \
2692    if (cxix < 0)                \
2693     cxix = 0;                   \
2694    else if (cxix > cxstack_ix)  \
2695     goto default_cx;            \
2696    cxix = su_context_logical2real(cxix); \
2697   } else {                      \
2698 default_cx:                     \
2699    cxix = (D);                  \
2700   }                             \
2701  } STMT_END
2702
2703 #define SU_GET_LEVEL(A, B) \
2704  STMT_START {              \
2705   level = 0;               \
2706   if (items > 0) {         \
2707    SV *lsv = ST(B);        \
2708    if (SvOK(lsv)) {        \
2709     level = SvIV(lsv);     \
2710     if (level < 0)         \
2711      level = 0;            \
2712    }                       \
2713   }                        \
2714  } STMT_END
2715
2716 #if XSH_HAS_PERL(5, 10, 0)
2717 # define SU_INFO_COUNT 11
2718 #else
2719 # define SU_INFO_COUNT 10
2720 #endif
2721
2722 XS(XS_Scope__Upper_unwind) {
2723 #ifdef dVAR
2724  dVAR; dXSARGS;
2725 #else
2726  dXSARGS;
2727 #endif
2728  dXSH_CXT;
2729  I32 cxix;
2730
2731  PERL_UNUSED_VAR(cv); /* -W */
2732  PERL_UNUSED_VAR(ax); /* -Wall */
2733
2734  SU_GET_CONTEXT(0, items - 1, cxstack_ix);
2735  do {
2736   PERL_CONTEXT *cx = cxstack + cxix;
2737   switch (CxTYPE(cx)) {
2738    case CXt_SUB:
2739     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2740      continue;
2741    case CXt_EVAL:
2742    case CXt_FORMAT:
2743     XSH_CXT.unwind_storage.cxix   = cxix;
2744     XSH_CXT.unwind_storage.items  = items;
2745     XSH_CXT.unwind_storage.savesp = PL_stack_sp;
2746     if (items > 0) {
2747      XSH_CXT.unwind_storage.items--;
2748      XSH_CXT.unwind_storage.savesp--;
2749     }
2750     /* pp_entersub will want to sanitize the stack after returning from there
2751      * Screw that, we're insane!
2752      * dXSARGS calls POPMARK, so we need to match PL_markstack_ptr[1] */
2753     if (GIMME_V == G_SCALAR)
2754      PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
2755     SAVEDESTRUCTOR_X(su_unwind, NULL);
2756     return;
2757    default:
2758     break;
2759   }
2760  } while (--cxix >= 0);
2761  croak("Can't return outside a subroutine");
2762 }
2763
2764 static const char su_yield_name[] = "yield";
2765
2766 XS(XS_Scope__Upper_yield) {
2767 #ifdef dVAR
2768  dVAR; dXSARGS;
2769 #else
2770  dXSARGS;
2771 #endif
2772  dXSH_CXT;
2773  I32 cxix;
2774
2775  PERL_UNUSED_VAR(cv); /* -W */
2776  PERL_UNUSED_VAR(ax); /* -Wall */
2777
2778  SU_GET_CONTEXT(0, items - 1, su_context_here());
2779  XSH_CXT.yield_storage.cxix   = cxix;
2780  XSH_CXT.yield_storage.items  = items;
2781  XSH_CXT.yield_storage.savesp = PL_stack_sp;
2782  if (items > 0) {
2783   XSH_CXT.yield_storage.items--;
2784   XSH_CXT.yield_storage.savesp--;
2785  }
2786  /* See XS_Scope__Upper_unwind */
2787  if (GIMME_V == G_SCALAR)
2788   PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
2789  SAVEDESTRUCTOR_X(su_yield, su_yield_name);
2790  return;
2791 }
2792
2793 static const char su_leave_name[] = "leave";
2794
2795 XS(XS_Scope__Upper_leave) {
2796 #ifdef dVAR
2797  dVAR; dXSARGS;
2798 #else
2799  dXSARGS;
2800 #endif
2801  dXSH_CXT;
2802
2803  PERL_UNUSED_VAR(cv); /* -W */
2804  PERL_UNUSED_VAR(ax); /* -Wall */
2805
2806  XSH_CXT.yield_storage.cxix   = su_context_here();
2807  XSH_CXT.yield_storage.items  = items;
2808  XSH_CXT.yield_storage.savesp = PL_stack_sp;
2809  /* See XS_Scope__Upper_unwind */
2810  if (GIMME_V == G_SCALAR)
2811   PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
2812  SAVEDESTRUCTOR_X(su_yield, su_leave_name);
2813  return;
2814 }
2815
2816 MODULE = Scope::Upper            PACKAGE = Scope::Upper
2817
2818 PROTOTYPES: ENABLE
2819
2820 BOOT:
2821 {
2822  xsh_setup();
2823  newXSproto("Scope::Upper::unwind", XS_Scope__Upper_unwind, file, NULL);
2824  newXSproto("Scope::Upper::yield",  XS_Scope__Upper_yield,  file, NULL);
2825  newXSproto("Scope::Upper::leave",  XS_Scope__Upper_leave,  file, NULL);
2826 }
2827
2828 #if XSH_THREADSAFE
2829
2830 void
2831 CLONE(...)
2832 PROTOTYPE: DISABLE
2833 PPCODE:
2834  xsh_clone();
2835  XSRETURN(0);
2836
2837 #endif /* XSH_THREADSAFE */
2838
2839 void
2840 HERE()
2841 PROTOTYPE:
2842 PREINIT:
2843  I32 cxix;
2844 PPCODE:
2845  cxix = su_context_real2logical(su_context_here());
2846  EXTEND(SP, 1);
2847  mPUSHi(cxix);
2848  XSRETURN(1);
2849
2850 void
2851 UP(...)
2852 PROTOTYPE: ;$
2853 PREINIT:
2854  I32 cxix;
2855 PPCODE:
2856  SU_GET_CONTEXT(0, 0, su_context_here());
2857  if (cxix > 0) {
2858   --cxix;
2859   cxix = su_context_skip_db(cxix);
2860   cxix = su_context_normalize_up(cxix);
2861   cxix = su_context_real2logical(cxix);
2862  } else {
2863   warn(su_stack_smash);
2864  }
2865  EXTEND(SP, 1);
2866  mPUSHi(cxix);
2867  XSRETURN(1);
2868
2869 void
2870 SUB(...)
2871 PROTOTYPE: ;$
2872 PREINIT:
2873  I32 cxix;
2874 PPCODE:
2875  SU_GET_CONTEXT(0, 0, cxstack_ix);
2876  EXTEND(SP, 1);
2877  for (; cxix >= 0; --cxix) {
2878   PERL_CONTEXT *cx = cxstack + cxix;
2879   switch (CxTYPE(cx)) {
2880    default:
2881     continue;
2882    case CXt_SUB:
2883     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2884      continue;
2885     cxix = su_context_real2logical(cxix);
2886     mPUSHi(cxix);
2887     XSRETURN(1);
2888   }
2889  }
2890  warn(su_no_such_target, "subroutine");
2891  XSRETURN_UNDEF;
2892
2893 void
2894 EVAL(...)
2895 PROTOTYPE: ;$
2896 PREINIT:
2897  I32 cxix;
2898 PPCODE:
2899  SU_GET_CONTEXT(0, 0, cxstack_ix);
2900  EXTEND(SP, 1);
2901  for (; cxix >= 0; --cxix) {
2902   PERL_CONTEXT *cx = cxstack + cxix;
2903   switch (CxTYPE(cx)) {
2904    default:
2905     continue;
2906    case CXt_EVAL:
2907     cxix = su_context_real2logical(cxix);
2908     mPUSHi(cxix);
2909     XSRETURN(1);
2910   }
2911  }
2912  warn(su_no_such_target, "eval");
2913  XSRETURN_UNDEF;
2914
2915 void
2916 SCOPE(...)
2917 PROTOTYPE: ;$
2918 PREINIT:
2919  I32 cxix, level;
2920 PPCODE:
2921  SU_GET_LEVEL(0, 0);
2922  cxix = su_context_here();
2923  while (--level >= 0) {
2924   if (cxix <= 0) {
2925    warn(su_stack_smash);
2926    break;
2927   }
2928   --cxix;
2929   cxix = su_context_skip_db(cxix);
2930   cxix = su_context_normalize_up(cxix);
2931   cxix = su_context_real2logical(cxix);
2932  }
2933  EXTEND(SP, 1);
2934  mPUSHi(cxix);
2935  XSRETURN(1);
2936
2937 void
2938 CALLER(...)
2939 PROTOTYPE: ;$
2940 PREINIT:
2941  I32 cxix, level;
2942 PPCODE:
2943  SU_GET_LEVEL(0, 0);
2944  for (cxix = cxstack_ix; cxix > 0; --cxix) {
2945   PERL_CONTEXT *cx = cxstack + cxix;
2946   switch (CxTYPE(cx)) {
2947    case CXt_SUB:
2948     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2949      continue;
2950    case CXt_EVAL:
2951    case CXt_FORMAT:
2952     if (--level < 0)
2953      goto done;
2954     break;
2955   }
2956  }
2957 done:
2958  if (level >= 0)
2959   warn(su_stack_smash);
2960  EXTEND(SP, 1);
2961  cxix = su_context_real2logical(cxix);
2962  mPUSHi(cxix);
2963  XSRETURN(1);
2964
2965 void
2966 want_at(...)
2967 PROTOTYPE: ;$
2968 PREINIT:
2969  I32 cxix;
2970 PPCODE:
2971  SU_GET_CONTEXT(0, 0, cxstack_ix);
2972  EXTEND(SP, 1);
2973  while (cxix > 0) {
2974   PERL_CONTEXT *cx = cxstack + cxix--;
2975   switch (CxTYPE(cx)) {
2976    case CXt_SUB:
2977     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2978      continue;
2979    case CXt_EVAL:
2980    case CXt_FORMAT: {
2981     I32 gimme = cx->blk_gimme;
2982     switch (gimme) {
2983      case G_VOID:   XSRETURN_UNDEF; break;
2984      case G_SCALAR: XSRETURN_NO;    break;
2985      case G_ARRAY:  XSRETURN_YES;   break;
2986     }
2987     break;
2988    }
2989   }
2990  }
2991  XSRETURN_UNDEF;
2992
2993 void
2994 context_info(...)
2995 PROTOTYPE: ;$
2996 PREINIT:
2997  I32 cxix;
2998  const PERL_CONTEXT *cx, *dbcx;
2999  COP *cop;
3000 PPCODE:
3001  SU_GET_CONTEXT(0, 0, su_context_skip_db(cxstack_ix));
3002  cxix = su_context_normalize_up(cxix);
3003  cx   = cxstack + cxix;
3004  dbcx = cx;
3005  if (PL_DBsub && cxix && (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT)) {
3006   I32 i = su_context_skip_db(cxix - 1) + 1;
3007   if (i < cxix && CxTYPE(cxstack + i) == CXt_SUB)
3008    cx = cxstack + i;
3009  }
3010  cop  = cx->blk_oldcop;
3011  EXTEND(SP, SU_INFO_COUNT);
3012  /* stash (0) */
3013  {
3014   HV *stash = CopSTASH(cop);
3015   if (stash)
3016    PUSHs(su_newmortal_pvn(HvNAME(stash), HvNAMELEN(stash)));
3017   else
3018    PUSHs(&PL_sv_undef);
3019  }
3020  /* file (1) */
3021  PUSHs(su_newmortal_pvn(OutCopFILE(cop), OutCopFILE_len(cop)));
3022  /* line (2) */
3023  mPUSHi(CopLINE(cop));
3024  /* subroutine (3) and has_args (4) */
3025  switch (CxTYPE(cx)) {
3026   case CXt_SUB:
3027   case CXt_FORMAT: {
3028    GV *cvgv = CvGV(dbcx->blk_sub.cv);
3029    if (cvgv && isGV(cvgv)) {
3030     SV *sv = sv_newmortal();
3031     gv_efullname3(sv, cvgv, NULL);
3032     PUSHs(sv);
3033    } else {
3034     PUSHs(su_newmortal_pvs("(unknown)"));
3035    }
3036    if (CxHASARGS(cx))
3037     PUSHs(&PL_sv_yes);
3038    else
3039     PUSHs(&PL_sv_no);
3040    break;
3041   }
3042   case CXt_EVAL:
3043    PUSHs(su_newmortal_pvs("(eval)"));
3044    mPUSHi(0);
3045    break;
3046   default:
3047    PUSHs(&PL_sv_undef);
3048    PUSHs(&PL_sv_undef);
3049  }
3050  /* gimme (5) */
3051  switch (su_context_gimme(cxix)) {
3052   case G_ARRAY:
3053    PUSHs(&PL_sv_yes);
3054    break;
3055   case G_SCALAR:
3056    PUSHs(&PL_sv_no);
3057    break;
3058   default: /* G_VOID */
3059    PUSHs(&PL_sv_undef);
3060    break;
3061  }
3062  /* eval text (6) and is_require (7) */
3063  switch (CxTYPE(cx)) {
3064   case CXt_EVAL:
3065    if (CxOLD_OP_TYPE(cx) == OP_ENTEREVAL) {
3066     /* eval STRING */
3067 #if XSH_HAS_PERL(5, 17, 4)
3068     PUSHs(newSVpvn_flags(SvPVX(cx->blk_eval.cur_text),
3069                          SvCUR(cx->blk_eval.cur_text)-2,
3070                          SvUTF8(cx->blk_eval.cur_text)|SVs_TEMP));
3071 #else
3072     PUSHs(cx->blk_eval.cur_text);
3073 #endif
3074     PUSHs(&PL_sv_no);
3075     break;
3076    } else if (cx->blk_eval.old_namesv) {
3077     /* require */
3078     PUSHs(sv_mortalcopy(cx->blk_eval.old_namesv));
3079     PUSHs(&PL_sv_yes);
3080     break;
3081    }
3082    /* FALLTHROUGH */
3083   default:
3084    /* Anything else including eval BLOCK */
3085    PUSHs(&PL_sv_undef);
3086    PUSHs(&PL_sv_undef);
3087    break;
3088  }
3089  /* hints (8) */
3090  mPUSHi(CopHINTS_get(cop));
3091  /* warnings (9) */
3092  {
3093   SV *mask = NULL;
3094 #if XSH_HAS_PERL(5, 9, 4)
3095   STRLEN *old_warnings = cop->cop_warnings;
3096 #else
3097   SV *old_warnings = cop->cop_warnings;
3098 #endif
3099   if (old_warnings == pWARN_STD) {
3100    if (PL_dowarn & G_WARN_ON)
3101     goto context_info_warnings_on;
3102    else
3103 #if XSH_HAS_PERL(5, 17, 4)
3104     mask = &PL_sv_undef;
3105 #else
3106     goto context_info_warnings_off;
3107 #endif
3108   } else if (old_warnings == pWARN_NONE) {
3109 #if !XSH_HAS_PERL(5, 17, 4)
3110 context_info_warnings_off:
3111 #endif
3112    mask = su_newmortal_pvn(WARN_NONEstring, WARNsize);
3113   } else if (old_warnings == pWARN_ALL) {
3114    HV *bits;
3115 context_info_warnings_on:
3116 #if XSH_HAS_PERL(5, 8, 7)
3117    bits = get_hv("warnings::Bits", 0);
3118    if (bits) {
3119     SV **bits_all = hv_fetchs(bits, "all", FALSE);
3120     if (bits_all)
3121      mask = sv_mortalcopy(*bits_all);
3122    }
3123 #endif
3124    if (!mask)
3125     mask = su_newmortal_pvn(WARN_ALLstring, WARNsize);
3126   } else {
3127 #if XSH_HAS_PERL(5, 9, 4)
3128    mask = su_newmortal_pvn((char *) (old_warnings + 1), old_warnings[0]);
3129 #else
3130    mask = sv_mortalcopy(old_warnings);
3131 #endif
3132   }
3133   PUSHs(mask);
3134  }
3135 #if XSH_HAS_PERL(5, 10, 0)
3136  /* hints hash (10) */
3137  {
3138   COPHH *hints_hash = CopHINTHASH_get(cop);
3139   if (hints_hash) {
3140    SV *rhv = sv_2mortal(newRV_noinc((SV *) cophh_2hv(hints_hash, 0)));
3141    PUSHs(rhv);
3142   } else {
3143    PUSHs(&PL_sv_undef);
3144   }
3145  }
3146 #endif
3147  XSRETURN(SU_INFO_COUNT);
3148
3149 void
3150 reap(SV *hook, ...)
3151 PROTOTYPE: &;$
3152 PREINIT:
3153  I32 cxix;
3154  su_ud_reap *ud;
3155 CODE:
3156  SU_GET_CONTEXT(1, 1, su_context_skip_db(cxstack_ix));
3157  cxix = su_context_normalize_down(cxix);
3158  Newx(ud, 1, su_ud_reap);
3159  SU_UD_TYPE(ud) = SU_UD_TYPE_REAP;
3160  ud->cb         = (SvROK(hook) && SvTYPE(SvRV(hook)) >= SVt_PVCV)
3161                   ? SvRV(hook) : hook;
3162  SvREFCNT_inc_simple_void(ud->cb);
3163  su_init(ud, cxix, SU_SAVE_DESTRUCTOR_SIZE);
3164
3165 void
3166 localize(SV *sv, SV *val, ...)
3167 PROTOTYPE: $$;$
3168 PREINIT:
3169  I32 cxix;
3170  I32 size;
3171  su_ud_localize *ud;
3172 CODE:
3173  SU_GET_CONTEXT(2, 2, su_context_skip_db(cxstack_ix));
3174  cxix = su_context_normalize_down(cxix);
3175  Newx(ud, 1, su_ud_localize);
3176  SU_UD_TYPE(ud) = SU_UD_TYPE_LOCALIZE;
3177  size = su_ud_localize_init(ud, sv, val, NULL);
3178  su_init(ud, cxix, size);
3179
3180 void
3181 localize_elem(SV *sv, SV *elem, SV *val, ...)
3182 PROTOTYPE: $$$;$
3183 PREINIT:
3184  I32 cxix;
3185  I32 size;
3186  su_ud_localize *ud;
3187 CODE:
3188  if (SvTYPE(sv) >= SVt_PVGV)
3189   croak("Can't infer the element localization type from a glob and the value");
3190  SU_GET_CONTEXT(3, 3, su_context_skip_db(cxstack_ix));
3191  cxix = su_context_normalize_down(cxix);
3192  Newx(ud, 1, su_ud_localize);
3193  /* Initialize SU_UD_ORIGIN(ud) in case SU_UD_LOCALIZE_FREE(ud) needs it */
3194  SU_UD_ORIGIN(ud) = NULL;
3195  SU_UD_TYPE(ud)   = SU_UD_TYPE_LOCALIZE;
3196  size = su_ud_localize_init(ud, sv, val, elem);
3197  if (SU_UD_PRIVATE(ud) != SVt_PVAV && SU_UD_PRIVATE(ud) != SVt_PVHV) {
3198   SU_UD_LOCALIZE_FREE(ud);
3199   croak("Can't localize an element of something that isn't an array or a hash");
3200  }
3201  su_init(ud, cxix, size);
3202
3203 void
3204 localize_delete(SV *sv, SV *elem, ...)
3205 PROTOTYPE: $$;$
3206 PREINIT:
3207  I32 cxix;
3208  I32 size;
3209  su_ud_localize *ud;
3210 CODE:
3211  SU_GET_CONTEXT(2, 2, su_context_skip_db(cxstack_ix));
3212  cxix = su_context_normalize_down(cxix);
3213  Newx(ud, 1, su_ud_localize);
3214  SU_UD_TYPE(ud) = SU_UD_TYPE_LOCALIZE;
3215  size = su_ud_localize_init(ud, sv, NULL, elem);
3216  su_init(ud, cxix, size);
3217
3218 void
3219 uplevel(SV *code, ...)
3220 PROTOTYPE: &@
3221 PREINIT:
3222  I32 cxix, ret, args = 0;
3223 PPCODE:
3224  if (SvROK(code))
3225   code = SvRV(code);
3226  if (SvTYPE(code) < SVt_PVCV)
3227   croak("First argument to uplevel must be a code reference");
3228  SU_GET_CONTEXT(1, items - 1, cxstack_ix);
3229  do {
3230   PERL_CONTEXT *cx = cxstack + cxix;
3231   switch (CxTYPE(cx)) {
3232    case CXt_EVAL:
3233     croak("Can't uplevel to an eval frame");
3234    case CXt_FORMAT:
3235     croak("Can't uplevel to a format frame");
3236    case CXt_SUB:
3237     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
3238      continue;
3239     if (items > 1) {
3240      PL_stack_sp--;
3241      args = items - 2;
3242     }
3243     /* su_uplevel() takes care of extending the stack if needed. */
3244 #if SU_HAS_NEW_CXT
3245     ret = su_uplevel_new(aTHX_ (CV *) code, cxix, args);
3246 #else
3247     ret = su_uplevel_old(aTHX_ (CV *) code, cxix, args);
3248 #endif
3249     XSRETURN(ret);
3250    default:
3251     break;
3252   }
3253  } while (--cxix >= 0);
3254  croak("Can't uplevel outside a subroutine");
3255
3256 void
3257 uid(...)
3258 PROTOTYPE: ;$
3259 PREINIT:
3260  I32 cxix;
3261  SV *uid;
3262 PPCODE:
3263  SU_GET_CONTEXT(0, 0, su_context_here());
3264  uid = su_uid_get(cxix);
3265  EXTEND(SP, 1);
3266  PUSHs(uid);
3267  XSRETURN(1);
3268
3269 void
3270 validate_uid(SV *uid)
3271 PROTOTYPE: $
3272 PREINIT:
3273  SV *ret;
3274 PPCODE:
3275  ret = su_uid_validate(uid) ? &PL_sv_yes : &PL_sv_no;
3276  EXTEND(SP, 1);
3277  PUSHs(ret);
3278  XSRETURN(1);