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