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