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