]> git.vpit.fr Git - perl/modules/Scope-Upper.git/blob - Upper.xs
Fix build with the new PADLIST API from 5.17.4
[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 #define __PACKAGE__ "Scope::Upper"
10
11 #ifndef SU_DEBUG
12 # define SU_DEBUG 0
13 #endif
14
15 /* --- Compatibility ------------------------------------------------------- */
16
17 #ifndef NOOP
18 # define NOOP
19 #endif
20
21 #ifndef dNOOP
22 # define dNOOP
23 #endif
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 STMT_START
46 # define STMT_START do
47 #endif
48
49 #ifndef STMT_END
50 # define STMT_END while (0)
51 #endif
52
53 #if SU_DEBUG
54 # define SU_D(X) STMT_START X STMT_END
55 #else
56 # define SU_D(X)
57 #endif
58
59 #ifndef Newx
60 # define Newx(v, n, c) New(0, v, n, c)
61 #endif
62
63 #ifdef DEBUGGING
64 # ifdef PoisonNew
65 #  define SU_POISON(D, N, T) PoisonNew((D), (N), T)
66 # elif defined(Poison)
67 #  define SU_POISON(D, N, T) Poison((D), (N), T)
68 # endif
69 #endif
70 #ifndef SU_POISON
71 # define SU_POISON(D, N, T) NOOP
72 #endif
73
74 #ifndef newSV_type
75 STATIC SV *su_newSV_type(pTHX_ svtype t) {
76  SV *sv = newSV(0);
77  SvUPGRADE(sv, t);
78  return sv;
79 }
80 # define newSV_type(T) su_newSV_type(aTHX_ (T))
81 #endif
82
83 #ifndef SvPV_const
84 # define SvPV_const(S, L) SvPV(S, L)
85 #endif
86
87 #ifndef SvPVX_const
88 # define SvPVX_const(S) SvPVX(S)
89 #endif
90
91 #ifndef SvPV_nolen_const
92 # define SvPV_nolen_const(S) SvPV_nolen(S)
93 #endif
94
95 #ifndef SvREFCNT_inc_simple_void
96 # define SvREFCNT_inc_simple_void(sv) ((void) SvREFCNT_inc(sv))
97 #endif
98
99 #ifndef mPUSHi
100 # define mPUSHi(I) PUSHs(sv_2mortal(newSViv(I)))
101 #endif
102
103 #ifndef GvCV_set
104 # define GvCV_set(G, C) (GvCV(G) = (C))
105 #endif
106
107 #ifndef CvGV_set
108 # define CvGV_set(C, G) (CvGV(C) = (G))
109 #endif
110
111 #ifndef CvSTASH_set
112 # define CvSTASH_set(C, S) (CvSTASH(C) = (S))
113 #endif
114
115 #ifndef CvISXSUB
116 # define CvISXSUB(C) CvXSUB(C)
117 #endif
118
119 #ifndef PADLIST_ARRAY
120 # define PADLIST_ARRAY(P) AvARRAY(P)
121 #endif
122
123 #ifndef CxHASARGS
124 # define CxHASARGS(C) ((C)->blk_sub.hasargs)
125 #endif
126
127 #ifndef HvNAME_get
128 # define HvNAME_get(H) HvNAME(H)
129 #endif
130
131 #ifndef gv_fetchpvn_flags
132 # define gv_fetchpvn_flags(A, B, C, D) gv_fetchpv((A), (C), (D))
133 #endif
134
135 #ifndef PERL_MAGIC_tied
136 # define PERL_MAGIC_tied 'P'
137 #endif
138
139 #ifndef PERL_MAGIC_env
140 # define PERL_MAGIC_env 'E'
141 #endif
142
143 #ifndef NEGATIVE_INDICES_VAR
144 # define NEGATIVE_INDICES_VAR "NEGATIVE_INDICES"
145 #endif
146
147 #define SU_HAS_PERL(R, V, S) (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S))))))
148 #define SU_HAS_PERL_EXACT(R, V, S) ((PERL_REVISION == (R)) && (PERL_VERSION == (V)) && (PERL_SUBVERSION == (S)))
149
150 /* --- Threads and multiplicity -------------------------------------------- */
151
152 #ifndef SU_MULTIPLICITY
153 # if defined(MULTIPLICITY) || defined(PERL_IMPLICIT_CONTEXT)
154 #  define SU_MULTIPLICITY 1
155 # else
156 #  define SU_MULTIPLICITY 0
157 # endif
158 #endif
159 #if SU_MULTIPLICITY && !defined(tTHX)
160 # define tTHX PerlInterpreter*
161 #endif
162
163 #if SU_MULTIPLICITY && defined(USE_ITHREADS) && defined(dMY_CXT) && defined(MY_CXT) && defined(START_MY_CXT) && defined(MY_CXT_INIT) && (defined(MY_CXT_CLONE) || defined(dMY_CXT_SV))
164 # define SU_THREADSAFE 1
165 # ifndef MY_CXT_CLONE
166 #  define MY_CXT_CLONE \
167     dMY_CXT_SV;                                                      \
168     my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1)); \
169     Copy(INT2PTR(my_cxt_t*, SvUV(my_cxt_sv)), my_cxtp, 1, my_cxt_t); \
170     sv_setuv(my_cxt_sv, PTR2UV(my_cxtp))
171 # endif
172 #else
173 # define SU_THREADSAFE 0
174 # undef  dMY_CXT
175 # define dMY_CXT      dNOOP
176 # undef  MY_CXT
177 # define MY_CXT       su_globaldata
178 # undef  START_MY_CXT
179 # define START_MY_CXT STATIC my_cxt_t MY_CXT;
180 # undef  MY_CXT_INIT
181 # define MY_CXT_INIT  NOOP
182 # undef  MY_CXT_CLONE
183 # define MY_CXT_CLONE NOOP
184 #endif
185
186 /* --- Unique context ID global storage ------------------------------------ */
187
188 /* ... Sequence ID counter ................................................. */
189
190 typedef struct {
191  UV     *seqs;
192  STRLEN  size;
193 } su_uv_array;
194
195 STATIC su_uv_array su_uid_seq_counter;
196
197 #ifdef USE_ITHREADS
198
199 STATIC perl_mutex su_uid_seq_counter_mutex;
200
201 #define SU_LOCK(M)   MUTEX_LOCK(M)
202 #define SU_UNLOCK(M) MUTEX_UNLOCK(M)
203
204 #else /* USE_ITHREADS */
205
206 #define SU_LOCK(M)
207 #define SU_UNLOCK(M)
208
209 #endif /* !USE_ITHREADS */
210
211 STATIC UV su_uid_seq_next(pTHX_ UV depth) {
212 #define su_uid_seq_next(D) su_uid_seq_next(aTHX_ (D))
213  UV seq;
214  UV *seqs;
215
216  SU_LOCK(&su_uid_seq_counter_mutex);
217
218  seqs = su_uid_seq_counter.seqs;
219
220  if (depth >= su_uid_seq_counter.size) {
221   UV i;
222
223   seqs = PerlMemShared_realloc(seqs, (depth + 1) * sizeof(UV));
224   for (i = su_uid_seq_counter.size; i <= depth; ++i)
225    seqs[i] = 0;
226
227   su_uid_seq_counter.seqs = seqs;
228   su_uid_seq_counter.size = depth + 1;
229  }
230
231  seq = ++seqs[depth];
232
233  SU_UNLOCK(&su_uid_seq_counter_mutex);
234
235  return seq;
236 }
237
238 /* ... UID storage ......................................................... */
239
240 typedef struct {
241  UV  seq;
242  U32 flags;
243 } su_uid;
244
245 #define SU_UID_ACTIVE 1
246
247 STATIC UV su_uid_depth(pTHX_ I32 cxix) {
248 #define su_uid_depth(I) su_uid_depth(aTHX_ (I))
249  const PERL_SI *si;
250  UV depth;
251
252  depth = cxix;
253  for (si = PL_curstackinfo->si_prev; si; si = si->si_prev)
254   depth += si->si_cxix + 1;
255
256  return depth;
257 }
258
259 typedef struct {
260  su_uid **map;
261  STRLEN   used;
262  STRLEN   alloc;
263 } su_uid_storage;
264
265 STATIC void su_uid_storage_dup(pTHX_ su_uid_storage *new_cxt, const su_uid_storage *old_cxt, UV max_depth) {
266 #define su_uid_storage_dup(N, O, D) su_uid_storage_dup(aTHX_ (N), (O), (D))
267  su_uid **old_map = old_cxt->map;
268
269  if (old_map) {
270   su_uid **new_map = new_cxt->map;
271   STRLEN old_used  = old_cxt->used;
272   STRLEN old_alloc = old_cxt->alloc;
273   STRLEN new_used, new_alloc;
274   STRLEN i;
275
276   new_used = max_depth < old_used ? max_depth : old_used;
277   new_cxt->used = new_used;
278
279   if (new_used <= new_cxt->alloc)
280    new_alloc = new_cxt->alloc;
281   else {
282    new_alloc = new_used;
283    Renew(new_map, new_alloc, su_uid *);
284    for (i = new_cxt->alloc; i < new_alloc; ++i)
285     new_map[i] = NULL;
286    new_cxt->map   = new_map;
287    new_cxt->alloc = new_alloc;
288   }
289
290   for (i = 0; i < new_alloc; ++i) {
291    su_uid *new_uid = new_map[i];
292
293    if (i < new_used) { /* => i < max_depth && i < old_used */
294     su_uid *old_uid = old_map[i];
295
296     if (old_uid && (old_uid->flags & SU_UID_ACTIVE)) {
297      if (!new_uid) {
298       Newx(new_uid, 1, su_uid);
299       new_map[i] = new_uid;
300      }
301      *new_uid = *old_uid;
302      continue;
303     }
304    }
305
306    if (new_uid)
307     new_uid->flags &= ~SU_UID_ACTIVE;
308   }
309  }
310
311  return;
312 }
313
314 /* --- unwind() global storage --------------------------------------------- */
315
316 typedef struct {
317  I32      cxix;
318  I32      items;
319  SV     **savesp;
320  LISTOP   return_op;
321  OP       proxy_op;
322 } su_unwind_storage;
323
324 /* --- uplevel() data tokens and global storage ---------------------------- */
325
326 #define SU_UPLEVEL_HIJACKS_RUNOPS SU_HAS_PERL(5, 8, 0)
327
328 typedef struct {
329  void          *next;
330
331  su_uid_storage tmp_uid_storage;
332  su_uid_storage old_uid_storage;
333
334  I32            cxix;
335
336  I32            target_depth;
337  CV            *target;
338
339  CV            *callback;
340  CV            *renamed;
341
342  PERL_SI       *si;
343  PERL_SI       *old_curstackinfo;
344  AV            *old_mainstack;
345
346  COP           *old_curcop;
347
348  OP            *old_op;
349 #if SU_UPLEVEL_HIJACKS_RUNOPS
350  runops_proc_t  old_runops;
351 #endif
352  bool           old_catch;
353
354  bool           died;
355 } su_uplevel_ud;
356
357 STATIC su_uplevel_ud *su_uplevel_ud_new(pTHX) {
358 #define su_uplevel_ud_new() su_uplevel_ud_new(aTHX)
359  su_uplevel_ud *sud;
360  PERL_SI       *si;
361
362  Newx(sud, 1, su_uplevel_ud);
363  sud->next = NULL;
364
365  sud->tmp_uid_storage.map   = NULL;
366  sud->tmp_uid_storage.used  = 0;
367  sud->tmp_uid_storage.alloc = 0;
368
369  Newx(si, 1, PERL_SI);
370  si->si_stack   = newAV();
371  AvREAL_off(si->si_stack);
372  si->si_cxstack = NULL;
373  si->si_cxmax   = 0;
374
375  sud->si = si;
376
377  return sud;
378 }
379
380 STATIC void su_uplevel_ud_delete(pTHX_ su_uplevel_ud *sud) {
381 #define su_uplevel_ud_delete(S) su_uplevel_ud_delete(aTHX_ (S))
382  PERL_SI *si = sud->si;
383
384  Safefree(si->si_cxstack);
385  SvREFCNT_dec(si->si_stack);
386  Safefree(si);
387
388  if (sud->tmp_uid_storage.map) {
389   su_uid **map   = sud->tmp_uid_storage.map;
390   STRLEN   alloc = sud->tmp_uid_storage.alloc;
391   STRLEN   i;
392
393   for (i = 0; i < alloc; ++i)
394    Safefree(map[i]);
395
396   Safefree(map);
397  }
398
399  Safefree(sud);
400
401  return;
402 }
403
404 typedef struct {
405  su_uplevel_ud *top;
406  su_uplevel_ud *root;
407  I32            count;
408 } su_uplevel_storage;
409
410 #ifndef SU_UPLEVEL_STORAGE_SIZE
411 # define SU_UPLEVEL_STORAGE_SIZE 4
412 #endif
413
414 /* --- Global data --------------------------------------------------------- */
415
416 #define MY_CXT_KEY __PACKAGE__ "::_guts" XS_VERSION
417
418 typedef struct {
419  char               *stack_placeholder;
420  su_unwind_storage   unwind_storage;
421  su_uplevel_storage  uplevel_storage;
422  su_uid_storage      uid_storage;
423 } my_cxt_t;
424
425 START_MY_CXT
426
427 /* --- Stack manipulations ------------------------------------------------- */
428
429 #define SU_SAVE_PLACEHOLDER() save_pptr(&MY_CXT.stack_placeholder)
430
431 #define SU_SAVE_DESTRUCTOR_SIZE  3
432 #define SU_SAVE_PLACEHOLDER_SIZE 3
433
434 #define SU_SAVE_SCALAR_SIZE 3
435
436 #define SU_SAVE_ARY_SIZE      3
437 #define SU_SAVE_AELEM_SIZE    4
438 #ifdef SAVEADELETE
439 # define SU_SAVE_ADELETE_SIZE 3
440 #else
441 # define SU_SAVE_ADELETE_SIZE SU_SAVE_DESTRUCTOR_SIZE
442 #endif
443 #if SU_SAVE_AELEM_SIZE < SU_SAVE_ADELETE_SIZE
444 # define SU_SAVE_AELEM_OR_ADELETE_SIZE SU_SAVE_ADELETE_SIZE
445 #else
446 # define SU_SAVE_AELEM_OR_ADELETE_SIZE SU_SAVE_AELEM_SIZE
447 #endif
448
449 #define SU_SAVE_HASH_SIZE    3
450 #define SU_SAVE_HELEM_SIZE   4
451 #define SU_SAVE_HDELETE_SIZE 4
452 #if SU_SAVE_HELEM_SIZE < SU_SAVE_HDELETE_SIZE
453 # define SU_SAVE_HELEM_OR_HDELETE_SIZE SU_SAVE_HDELETE_SIZE
454 #else
455 # define SU_SAVE_HELEM_OR_HDELETE_SIZE SU_SAVE_HELEM_SIZE
456 #endif
457
458 #define SU_SAVE_GVCV_SIZE SU_SAVE_DESTRUCTOR_SIZE
459
460 #if !SU_HAS_PERL(5, 8, 9)
461 # define SU_SAVE_GP_SIZE 6
462 #elif !SU_HAS_PERL(5, 13, 0) || (SU_RELEASE && SU_HAS_PERL_EXACT(5, 13, 0))
463 # define SU_SAVE_GP_SIZE 3
464 #elif !SU_HAS_PERL(5, 13, 8)
465 # define SU_SAVE_GP_SIZE 4
466 #else
467 # define SU_SAVE_GP_SIZE 3
468 #endif
469
470 #ifndef SvCANEXISTDELETE
471 # define SvCANEXISTDELETE(sv) \
472   (!SvRMAGICAL(sv)            \
473    || ((mg = mg_find((SV *) sv, PERL_MAGIC_tied))            \
474        && (stash = SvSTASH(SvRV(SvTIED_obj((SV *) sv, mg)))) \
475        && gv_fetchmethod_autoload(stash, "EXISTS", TRUE)     \
476        && gv_fetchmethod_autoload(stash, "DELETE", TRUE)     \
477       )                       \
478    )
479 #endif
480
481 /* ... Saving array elements ............................................... */
482
483 STATIC I32 su_av_key2idx(pTHX_ AV *av, I32 key) {
484 #define su_av_key2idx(A, K) su_av_key2idx(aTHX_ (A), (K))
485  I32 idx;
486
487  if (key >= 0)
488   return key;
489
490 /* Added by MJD in perl-5.8.1 with 6f12eb6d2a1dfaf441504d869b27d2e40ef4966a */
491 #if SU_HAS_PERL(5, 8, 1)
492  if (SvRMAGICAL(av)) {
493   const MAGIC * const tied_magic = mg_find((SV *) av, PERL_MAGIC_tied);
494   if (tied_magic) {
495    SV * const * const negative_indices_glob =
496                     hv_fetch(SvSTASH(SvRV(SvTIED_obj((SV *) (av), tied_magic))),
497                              NEGATIVE_INDICES_VAR, 16, 0);
498    if (negative_indices_glob && SvTRUE(GvSV(*negative_indices_glob)))
499     return key;
500   }
501  }
502 #endif
503
504  idx = key + av_len(av) + 1;
505  if (idx < 0)
506   return key;
507
508  return idx;
509 }
510
511 #ifndef SAVEADELETE
512
513 typedef struct {
514  AV *av;
515  I32 idx;
516 } su_ud_adelete;
517
518 STATIC void su_adelete(pTHX_ void *ud_) {
519  su_ud_adelete *ud = (su_ud_adelete *) ud_;
520
521  av_delete(ud->av, ud->idx, G_DISCARD);
522  SvREFCNT_dec(ud->av);
523
524  Safefree(ud);
525 }
526
527 STATIC void su_save_adelete(pTHX_ AV *av, I32 idx) {
528 #define su_save_adelete(A, K) su_save_adelete(aTHX_ (A), (K))
529  su_ud_adelete *ud;
530
531  Newx(ud, 1, su_ud_adelete);
532  ud->av  = av;
533  ud->idx = idx;
534  SvREFCNT_inc_simple_void(av);
535
536  SAVEDESTRUCTOR_X(su_adelete, ud);
537 }
538
539 #define SAVEADELETE(A, K) su_save_adelete((A), (K))
540
541 #endif /* SAVEADELETE */
542
543 STATIC void su_save_aelem(pTHX_ AV *av, SV *key, SV *val) {
544 #define su_save_aelem(A, K, V) su_save_aelem(aTHX_ (A), (K), (V))
545  I32 idx;
546  I32 preeminent = 1;
547  SV **svp;
548  HV *stash;
549  MAGIC *mg;
550
551  idx = su_av_key2idx(av, SvIV(key));
552
553  if (SvCANEXISTDELETE(av))
554   preeminent = av_exists(av, idx);
555
556  svp = av_fetch(av, idx, 1);
557  if (!svp || *svp == &PL_sv_undef) croak(PL_no_aelem, idx);
558
559  if (preeminent)
560   save_aelem(av, idx, svp);
561  else
562   SAVEADELETE(av, idx);
563
564  if (val) { /* local $x[$idx] = $val; */
565   SvSetMagicSV(*svp, val);
566  } else {   /* local $x[$idx]; delete $x[$idx]; */
567   av_delete(av, idx, G_DISCARD);
568  }
569 }
570
571 /* ... Saving hash elements ................................................ */
572
573 STATIC void su_save_helem(pTHX_ HV *hv, SV *keysv, SV *val) {
574 #define su_save_helem(H, K, V) su_save_helem(aTHX_ (H), (K), (V))
575  I32 preeminent = 1;
576  HE *he;
577  SV **svp;
578  HV *stash;
579  MAGIC *mg;
580
581  if (SvCANEXISTDELETE(hv) || mg_find((SV *) hv, PERL_MAGIC_env))
582   preeminent = hv_exists_ent(hv, keysv, 0);
583
584  he  = hv_fetch_ent(hv, keysv, 1, 0);
585  svp = he ? &HeVAL(he) : NULL;
586  if (!svp || *svp == &PL_sv_undef) croak("Modification of non-creatable hash value attempted, subscript \"%s\"", SvPV_nolen_const(*svp));
587
588  if (HvNAME_get(hv) && isGV(*svp)) {
589   save_gp((GV *) *svp, 0);
590   return;
591  }
592
593  if (preeminent)
594   save_helem(hv, keysv, svp);
595  else {
596   STRLEN keylen;
597   const char * const key = SvPV_const(keysv, keylen);
598   SAVEDELETE(hv, savepvn(key, keylen),
599                  SvUTF8(keysv) ? -(I32)keylen : (I32)keylen);
600  }
601
602  if (val) { /* local $x{$keysv} = $val; */
603   SvSetMagicSV(*svp, val);
604  } else {   /* local $x{$keysv}; delete $x{$keysv}; */
605   (void)hv_delete_ent(hv, keysv, G_DISCARD, HeHASH(he));
606  }
607 }
608
609 /* ... Saving code slots from a glob ....................................... */
610
611 #if !SU_HAS_PERL(5, 10, 0) && !defined(mro_method_changed_in)
612 # define mro_method_changed_in(G) PL_sub_generation++
613 #endif
614
615 typedef struct {
616  GV *gv;
617  CV *old_cv;
618 } su_save_gvcv_ud;
619
620 STATIC void su_restore_gvcv(pTHX_ void *ud_) {
621  su_save_gvcv_ud *ud = ud_;
622  GV              *gv = ud->gv;
623
624  GvCV_set(gv, ud->old_cv);
625  GvCVGEN(gv) = 0;
626  mro_method_changed_in(GvSTASH(gv));
627
628  Safefree(ud);
629 }
630
631 STATIC void su_save_gvcv(pTHX_ GV *gv) {
632 #define su_save_gvcv(G) su_save_gvcv(aTHX_ (G))
633  su_save_gvcv_ud *ud;
634
635  Newx(ud, 1, su_save_gvcv_ud);
636  ud->gv     = gv;
637  ud->old_cv = GvCV(gv);
638
639  GvCV_set(gv, NULL);
640  GvCVGEN(gv) = 0;
641  mro_method_changed_in(GvSTASH(gv));
642
643  SAVEDESTRUCTOR_X(su_restore_gvcv, ud);
644 }
645
646 /* --- Actions ------------------------------------------------------------- */
647
648 typedef struct {
649  I32 depth;
650  I32 pad;
651  I32 *origin;
652  void (*handler)(pTHX_ void *);
653 } su_ud_common;
654
655 #define SU_UD_DEPTH(U)   (((su_ud_common *) (U))->depth)
656 #define SU_UD_PAD(U)     (((su_ud_common *) (U))->pad)
657 #define SU_UD_ORIGIN(U)  (((su_ud_common *) (U))->origin)
658 #define SU_UD_HANDLER(U) (((su_ud_common *) (U))->handler)
659
660 #define SU_UD_FREE(U) STMT_START { \
661  if (SU_UD_ORIGIN(U)) Safefree(SU_UD_ORIGIN(U)); \
662  Safefree(U); \
663 } STMT_END
664
665 /* ... Reap ................................................................ */
666
667 #define SU_SAVE_LAST_CX (!SU_HAS_PERL(5, 8, 4) || (SU_HAS_PERL(5, 9, 5) && !SU_HAS_PERL(5, 14, 0)) || SU_HAS_PERL(5, 15, 0))
668
669 typedef struct {
670  su_ud_common ci;
671  SV *cb;
672 } su_ud_reap;
673
674 STATIC void su_call(pTHX_ void *ud_) {
675  su_ud_reap *ud = (su_ud_reap *) ud_;
676 #if SU_SAVE_LAST_CX
677  I32 cxix;
678  PERL_CONTEXT saved_cx;
679 #endif /* SU_SAVE_LAST_CX */
680
681  dSP;
682
683  SU_D({
684   PerlIO_printf(Perl_debug_log,
685                 "%p: @@@ call\n%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
686                  ud, ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
687  });
688
689  ENTER;
690  SAVETMPS;
691
692  PUSHMARK(SP);
693  PUTBACK;
694
695 #if SU_SAVE_LAST_CX
696  /* If the recently popped context isn't saved there, it will be overwritten by
697   * the sub scope from call_sv, although it's still needed in our caller. */
698  cxix     = (cxstack_ix < cxstack_max) ? (cxstack_ix + 1) : Perl_cxinc(aTHX);
699  saved_cx = cxstack[cxix];
700 #endif /* SU_SAVE_LAST_CX */
701
702  call_sv(ud->cb, G_VOID);
703
704 #if SU_SAVE_LAST_CX
705  cxstack[cxix] = saved_cx;
706 #endif /* SU_SAVE_LAST_CX */
707
708  PUTBACK;
709
710  FREETMPS;
711  LEAVE;
712
713  SvREFCNT_dec(ud->cb);
714  SU_UD_FREE(ud);
715 }
716
717 STATIC void su_reap(pTHX_ void *ud) {
718 #define su_reap(U) su_reap(aTHX_ (U))
719  SU_D({
720   PerlIO_printf(Perl_debug_log,
721                 "%p: === reap\n%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
722                  ud, ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
723  });
724
725  SAVEDESTRUCTOR_X(su_call, ud);
726 }
727
728 /* ... Localize & localize array/hash element .............................. */
729
730 typedef struct {
731  su_ud_common ci;
732  SV    *sv;
733  SV    *val;
734  SV    *elem;
735  svtype type;
736 } su_ud_localize;
737
738 #define SU_UD_LOCALIZE_FREE(U) STMT_START { \
739  SvREFCNT_dec((U)->elem); \
740  SvREFCNT_dec((U)->val);  \
741  SvREFCNT_dec((U)->sv);   \
742  SU_UD_FREE(U);           \
743 } STMT_END
744
745 STATIC I32 su_ud_localize_init(pTHX_ su_ud_localize *ud, SV *sv, SV *val, SV *elem) {
746 #define su_ud_localize_init(UD, S, V, E) su_ud_localize_init(aTHX_ (UD), (S), (V), (E))
747  UV deref = 0;
748  svtype t = SVt_NULL;
749  I32 size;
750
751  SvREFCNT_inc_simple_void(sv);
752
753  if (SvTYPE(sv) >= SVt_PVGV) {
754   if (!val || !SvROK(val)) { /* local *x; or local *x = $val; */
755    t = SVt_PVGV;
756   } else {                   /* local *x = \$val; */
757    t = SvTYPE(SvRV(val));
758    deref = 1;
759   }
760  } else if (SvROK(sv)) {
761   croak("Invalid %s reference as the localization target",
762                  sv_reftype(SvRV(sv), 0));
763  } else {
764   STRLEN len, l;
765   const char *p = SvPV_const(sv, len), *s;
766   for (s = p, l = len; l > 0 && isSPACE(*s); ++s, --l) { }
767   if (!l) {
768    l = len;
769    s = p;
770   }
771   switch (*s) {
772    case '$': t = SVt_PV;   break;
773    case '@': t = SVt_PVAV; break;
774    case '%': t = SVt_PVHV; break;
775    case '&': t = SVt_PVCV; break;
776    case '*': t = SVt_PVGV; break;
777   }
778   if (t != SVt_NULL) {
779    ++s;
780    --l;
781   } else if (val) { /* t == SVt_NULL, type can't be inferred from the sigil */
782    if (SvROK(val) && !sv_isobject(val)) {
783     t = SvTYPE(SvRV(val));
784     deref = 1;
785    } else {
786     t = SvTYPE(val);
787    }
788   }
789   SvREFCNT_dec(sv);
790   sv = newSVpvn(s, l);
791  }
792
793  switch (t) {
794   case SVt_PVAV:
795    size  = elem ? SU_SAVE_AELEM_OR_ADELETE_SIZE
796                 : SU_SAVE_ARY_SIZE;
797    deref = 0;
798    break;
799   case SVt_PVHV:
800    size  = elem ? SU_SAVE_HELEM_OR_HDELETE_SIZE
801                 : SU_SAVE_HASH_SIZE;
802    deref = 0;
803    break;
804   case SVt_PVGV:
805    size  = SU_SAVE_GP_SIZE;
806    deref = 0;
807    break;
808   case SVt_PVCV:
809    size  = SU_SAVE_GVCV_SIZE;
810    deref = 0;
811    break;
812   default:
813    size = SU_SAVE_SCALAR_SIZE;
814    break;
815  }
816  /* When deref is set, val isn't NULL */
817
818  ud->sv   = sv;
819  ud->val  = val ? newSVsv(deref ? SvRV(val) : val) : NULL;
820  ud->elem = SvREFCNT_inc(elem);
821  ud->type = t;
822
823  return size;
824 }
825
826 STATIC void su_localize(pTHX_ void *ud_) {
827 #define su_localize(U) su_localize(aTHX_ (U))
828  su_ud_localize *ud = (su_ud_localize *) ud_;
829  SV *sv   = ud->sv;
830  SV *val  = ud->val;
831  SV *elem = ud->elem;
832  svtype t = ud->type;
833  GV *gv;
834
835  if (SvTYPE(sv) >= SVt_PVGV) {
836   gv = (GV *) sv;
837  } else {
838 #ifdef gv_fetchsv
839   gv = gv_fetchsv(sv, GV_ADDMULTI, t);
840 #else
841   STRLEN len;
842   const char *name = SvPV_const(sv, len);
843   gv = gv_fetchpvn_flags(name, len, GV_ADDMULTI, t);
844 #endif
845  }
846
847  SU_D({
848   SV *z = newSV(0);
849   SvUPGRADE(z, t);
850   PerlIO_printf(Perl_debug_log, "%p: === localize a %s\n",ud, sv_reftype(z, 0));
851   PerlIO_printf(Perl_debug_log,
852                 "%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
853                  ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
854   SvREFCNT_dec(z);
855  });
856
857  /* Inspired from Alias.pm */
858  switch (t) {
859   case SVt_PVAV:
860    if (elem) {
861     su_save_aelem(GvAV(gv), elem, val);
862     goto done;
863    } else
864     save_ary(gv);
865    break;
866   case SVt_PVHV:
867    if (elem) {
868     su_save_helem(GvHV(gv), elem, val);
869     goto done;
870    } else
871     save_hash(gv);
872    break;
873   case SVt_PVGV:
874    save_gp(gv, 1); /* hide previous entry in symtab */
875    break;
876   case SVt_PVCV:
877    su_save_gvcv(gv);
878    break;
879   default:
880    gv = (GV *) save_scalar(gv);
881    break;
882  }
883
884  if (val)
885   SvSetMagicSV((SV *) gv, val);
886
887 done:
888  SU_UD_LOCALIZE_FREE(ud);
889 }
890
891 /* --- Pop a context back -------------------------------------------------- */
892
893 #if SU_DEBUG
894 # ifdef DEBUGGING
895 #  define SU_CXNAME PL_block_type[CxTYPE(&cxstack[cxstack_ix])]
896 # else
897 #  define SU_CXNAME "XXX"
898 # endif
899 #endif
900
901 STATIC void su_pop(pTHX_ void *ud) {
902 #define su_pop(U) su_pop(aTHX_ (U))
903  I32 depth, base, mark, *origin;
904  depth = SU_UD_DEPTH(ud);
905
906  SU_D(
907   PerlIO_printf(Perl_debug_log,
908    "%p: --- pop a %s\n"
909    "%p: leave scope     at depth=%2d scope_ix=%2d cur_top=%2d cur_base=%2d\n",
910     ud, SU_CXNAME,
911     ud, depth, PL_scopestack_ix,PL_savestack_ix,PL_scopestack[PL_scopestack_ix])
912  );
913
914  origin = SU_UD_ORIGIN(ud);
915  mark   = origin[depth];
916  base   = origin[depth - 1];
917
918  SU_D(PerlIO_printf(Perl_debug_log,
919                     "%p: original scope was %*c top=%2d     base=%2d\n",
920                      ud,                24, ' ',    mark,        base));
921
922  if (base < mark) {
923   SU_D(PerlIO_printf(Perl_debug_log, "%p: clear leftovers\n", ud));
924   PL_savestack_ix = mark;
925   leave_scope(base);
926  }
927  PL_savestack_ix = base;
928
929  SU_UD_DEPTH(ud) = --depth;
930
931  if (depth > 0) {
932   I32 pad;
933
934   if ((pad = SU_UD_PAD(ud))) {
935    dMY_CXT;
936    do {
937     SU_D(PerlIO_printf(Perl_debug_log,
938           "%p: push a pad slot at depth=%2d scope_ix=%2d save_ix=%2d\n",
939            ud,                       depth, PL_scopestack_ix, PL_savestack_ix));
940     SU_SAVE_PLACEHOLDER();
941    } while (--pad);
942   }
943
944   SU_D(PerlIO_printf(Perl_debug_log,
945           "%p: push destructor at depth=%2d scope_ix=%2d save_ix=%2d\n",
946            ud,                       depth, PL_scopestack_ix, PL_savestack_ix));
947   SAVEDESTRUCTOR_X(su_pop, ud);
948  } else {
949   SU_UD_HANDLER(ud)(aTHX_ ud);
950  }
951
952  SU_D(PerlIO_printf(Perl_debug_log,
953                     "%p: --- end pop: cur_top=%2d == cur_base=%2d\n",
954                      ud, PL_savestack_ix, PL_scopestack[PL_scopestack_ix]));
955 }
956
957 /* --- Initialize the stack and the action userdata ------------------------ */
958
959 STATIC I32 su_init(pTHX_ void *ud, I32 cxix, I32 size) {
960 #define su_init(U, C, S) su_init(aTHX_ (U), (C), (S))
961  I32 i, depth = 1, pad, offset, *origin;
962
963  SU_D(PerlIO_printf(Perl_debug_log, "%p: ### init for cx %d\n", ud, cxix));
964
965  if (size <= SU_SAVE_DESTRUCTOR_SIZE)
966   pad = 0;
967  else {
968   I32 extra = size - SU_SAVE_DESTRUCTOR_SIZE;
969   pad = extra / SU_SAVE_PLACEHOLDER_SIZE;
970   if (extra % SU_SAVE_PLACEHOLDER_SIZE)
971    ++pad;
972  }
973  offset = SU_SAVE_DESTRUCTOR_SIZE + SU_SAVE_PLACEHOLDER_SIZE * pad;
974
975  SU_D(PerlIO_printf(Perl_debug_log, "%p: size=%d pad=%d offset=%d\n",
976                                      ud,    size,   pad,   offset));
977
978  for (i = cxstack_ix; i > cxix; --i) {
979   PERL_CONTEXT *cx = cxstack + i;
980   switch (CxTYPE(cx)) {
981 #if SU_HAS_PERL(5, 10, 0)
982    case CXt_BLOCK:
983     SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is block\n", ud, i));
984     /* Given and when blocks are actually followed by a simple block, so skip
985      * it if needed. */
986     if (cxix > 0) { /* Implies i > 0 */
987      PERL_CONTEXT *next = cx - 1;
988      if (CxTYPE(next) == CXt_GIVEN || CxTYPE(next) == CXt_WHEN)
989       --cxix;
990     }
991     depth++;
992     break;
993 #endif
994 #if SU_HAS_PERL(5, 11, 0)
995    case CXt_LOOP_FOR:
996    case CXt_LOOP_PLAIN:
997    case CXt_LOOP_LAZYSV:
998    case CXt_LOOP_LAZYIV:
999 #else
1000    case CXt_LOOP:
1001 #endif
1002     SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is loop\n", ud, i));
1003     depth += 2;
1004     break;
1005    default:
1006     SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is other\n", ud, i));
1007     depth++;
1008     break;
1009   }
1010  }
1011  SU_D(PerlIO_printf(Perl_debug_log, "%p: going down to depth %d\n", ud, depth));
1012
1013  Newx(origin, depth + 1, I32);
1014  origin[0] = PL_scopestack[PL_scopestack_ix - depth];
1015  PL_scopestack[PL_scopestack_ix - depth] += size;
1016  for (i = depth - 1; i >= 1; --i) {
1017   I32 j = PL_scopestack_ix - i;
1018   origin[depth - i] = PL_scopestack[j];
1019   PL_scopestack[j] += offset;
1020  }
1021  origin[depth] = PL_savestack_ix;
1022
1023  SU_UD_ORIGIN(ud) = origin;
1024  SU_UD_DEPTH(ud)  = depth;
1025  SU_UD_PAD(ud)    = pad;
1026
1027  /* Make sure the first destructor fires by pushing enough fake slots on the
1028   * stack. */
1029  if (PL_savestack_ix + SU_SAVE_DESTRUCTOR_SIZE
1030                                        <= PL_scopestack[PL_scopestack_ix - 1]) {
1031   dMY_CXT;
1032   do {
1033    SU_D(PerlIO_printf(Perl_debug_log,
1034                   "%p: push a fake slot      at scope_ix=%2d  save_ix=%2d\n",
1035                    ud,                      PL_scopestack_ix, PL_savestack_ix));
1036    SU_SAVE_PLACEHOLDER();
1037   } while (PL_savestack_ix + SU_SAVE_DESTRUCTOR_SIZE
1038                                         <= PL_scopestack[PL_scopestack_ix - 1]);
1039  }
1040  SU_D(PerlIO_printf(Perl_debug_log,
1041                   "%p: push first destructor at scope_ix=%2d  save_ix=%2d\n",
1042                    ud,                      PL_scopestack_ix, PL_savestack_ix));
1043  SAVEDESTRUCTOR_X(su_pop, ud);
1044
1045  SU_D({
1046   for (i = 0; i <= depth; ++i) {
1047    I32 j = PL_scopestack_ix  - i;
1048    PerlIO_printf(Perl_debug_log,
1049                  "%p: depth=%2d scope_ix=%2d saved_floor=%2d new_floor=%2d\n",
1050                   ud,        i, j, origin[depth - i],
1051                                    i == 0 ? PL_savestack_ix : PL_scopestack[j]);
1052   }
1053  });
1054
1055  return depth;
1056 }
1057
1058 /* --- Unwind stack -------------------------------------------------------- */
1059
1060 STATIC void su_unwind(pTHX_ void *ud_) {
1061  dMY_CXT;
1062  I32 cxix    = MY_CXT.unwind_storage.cxix;
1063  I32 items   = MY_CXT.unwind_storage.items - 1;
1064  SV **savesp = MY_CXT.unwind_storage.savesp;
1065  I32 mark;
1066
1067  PERL_UNUSED_VAR(ud_);
1068
1069  if (savesp)
1070   PL_stack_sp = savesp;
1071
1072  if (cxstack_ix > cxix)
1073   dounwind(cxix);
1074
1075  /* Hide the level */
1076  if (items >= 0)
1077   PL_stack_sp--;
1078
1079  mark = PL_markstack[cxstack[cxix].blk_oldmarksp];
1080  *PL_markstack_ptr = PL_stack_sp - PL_stack_base - items;
1081
1082  SU_D({
1083   I32 gimme = GIMME_V;
1084   PerlIO_printf(Perl_debug_log,
1085                 "%p: cx=%d gimme=%s items=%d sp=%d oldmark=%d mark=%d\n",
1086                 &MY_CXT, cxix,
1087                 gimme == G_VOID ? "void" : gimme == G_ARRAY ? "list" : "scalar",
1088                 items, PL_stack_sp - PL_stack_base, *PL_markstack_ptr, mark);
1089  });
1090
1091  PL_op = (OP *) &(MY_CXT.unwind_storage.return_op);
1092  PL_op = PL_op->op_ppaddr(aTHX);
1093
1094  *PL_markstack_ptr = mark;
1095
1096  MY_CXT.unwind_storage.proxy_op.op_next = PL_op;
1097  PL_op = &(MY_CXT.unwind_storage.proxy_op);
1098 }
1099
1100 /* --- Uplevel ------------------------------------------------------------- */
1101
1102 #ifndef OP_GIMME_REVERSE
1103 STATIC U8 su_op_gimme_reverse(U8 gimme) {
1104  switch (gimme) {
1105   case G_VOID:
1106    return OPf_WANT_VOID;
1107   case G_ARRAY:
1108    return OPf_WANT_LIST;
1109   default:
1110    break;
1111  }
1112
1113  return OPf_WANT_SCALAR;
1114 }
1115 #define OP_GIMME_REVERSE(G) su_op_gimme_reverse(G)
1116 #endif
1117
1118 #define SU_UPLEVEL_SAVE(f, t) STMT_START { sud->old_##f = PL_##f; PL_##f = (t); } STMT_END
1119 #define SU_UPLEVEL_RESTORE(f) STMT_START { PL_##f = sud->old_##f; } STMT_END
1120
1121 STATIC su_uplevel_ud *su_uplevel_storage_new(pTHX_ I32 cxix) {
1122 #define su_uplevel_storage_new(I) su_uplevel_storage_new(aTHX_ (I))
1123  su_uplevel_ud *sud;
1124  UV depth;
1125  dMY_CXT;
1126
1127  sud = MY_CXT.uplevel_storage.root;
1128  if (sud) {
1129   MY_CXT.uplevel_storage.root = sud->next;
1130   MY_CXT.uplevel_storage.count--;
1131  } else {
1132   sud = su_uplevel_ud_new();
1133  }
1134
1135  sud->next = MY_CXT.uplevel_storage.top;
1136  MY_CXT.uplevel_storage.top = sud;
1137
1138  depth = su_uid_depth(cxix);
1139  su_uid_storage_dup(&sud->tmp_uid_storage, &MY_CXT.uid_storage, depth);
1140  sud->old_uid_storage = MY_CXT.uid_storage;
1141  MY_CXT.uid_storage   = sud->tmp_uid_storage;
1142
1143  return sud;
1144 }
1145
1146 STATIC void su_uplevel_storage_delete(pTHX_ su_uplevel_ud *sud) {
1147 #define su_uplevel_storage_delete(S) su_uplevel_storage_delete(aTHX_ (S))
1148  dMY_CXT;
1149
1150  sud->tmp_uid_storage = MY_CXT.uid_storage;
1151  MY_CXT.uid_storage   = sud->old_uid_storage;
1152  {
1153   su_uid **map;
1154   UV  i, alloc;
1155   map   = sud->tmp_uid_storage.map;
1156   alloc = sud->tmp_uid_storage.alloc;
1157   for (i = 0; i < alloc; ++i) {
1158    if (map[i])
1159     map[i]->flags &= SU_UID_ACTIVE;
1160   }
1161  }
1162  MY_CXT.uplevel_storage.top = sud->next;
1163
1164  if (MY_CXT.uplevel_storage.count >= SU_UPLEVEL_STORAGE_SIZE) {
1165   su_uplevel_ud_delete(sud);
1166  } else {
1167   sud->next = MY_CXT.uplevel_storage.root;
1168   MY_CXT.uplevel_storage.root = sud;
1169   MY_CXT.uplevel_storage.count++;
1170  }
1171 }
1172
1173 STATIC int su_uplevel_goto_static(const OP *o) {
1174  for (; o; o = o->op_sibling) {
1175   /* goto ops are unops with kids. */
1176   if (!(o->op_flags & OPf_KIDS))
1177    continue;
1178
1179   switch (o->op_type) {
1180    case OP_LEAVEEVAL:
1181    case OP_LEAVETRY:
1182     /* Don't care about gotos inside eval, as they are forbidden at run time. */
1183     break;
1184    case OP_GOTO:
1185     return 1;
1186    default:
1187     if (su_uplevel_goto_static(cUNOPo->op_first))
1188      return 1;
1189     break;
1190   }
1191  }
1192
1193  return 0;
1194 }
1195
1196 #if SU_UPLEVEL_HIJACKS_RUNOPS
1197
1198 STATIC int su_uplevel_goto_runops(pTHX) {
1199 #define su_uplevel_goto_runops() su_uplevel_goto_runops(aTHX)
1200  register OP *op;
1201  dVAR;
1202
1203  op = PL_op;
1204  do {
1205   if (op->op_type == OP_GOTO) {
1206    AV  *argarray = NULL;
1207    I32  cxix;
1208
1209    for (cxix = cxstack_ix; cxix >= 0; --cxix) {
1210     const PERL_CONTEXT *cx = cxstack + cxix;
1211
1212     switch (CxTYPE(cx)) {
1213      case CXt_SUB:
1214       if (CxHASARGS(cx)) {
1215        argarray = cx->blk_sub.argarray;
1216        goto done;
1217       }
1218       break;
1219      case CXt_EVAL:
1220      case CXt_FORMAT:
1221       goto done;
1222      default:
1223       break;
1224     }
1225    }
1226
1227 done:
1228    if (argarray) {
1229     dMY_CXT;
1230
1231     if (MY_CXT.uplevel_storage.top->cxix == cxix) {
1232      AV  *args  = GvAV(PL_defgv);
1233      I32  items = AvFILLp(args);
1234
1235      av_extend(argarray, items);
1236      Copy(AvARRAY(args), AvARRAY(argarray), items + 1, SV *);
1237      AvFILLp(argarray) = items;
1238     }
1239    }
1240   }
1241
1242   PL_op = op = op->op_ppaddr(aTHX);
1243
1244 #if !SU_HAS_PERL(5, 13, 0)
1245   PERL_ASYNC_CHECK();
1246 #endif
1247  } while (op);
1248
1249  TAINT_NOT;
1250
1251  return 0;
1252 }
1253
1254 #endif /* SU_UPLEVEL_HIJACKS_RUNOPS */
1255
1256 #define su_at_underscore(C) AvARRAY(PADLIST_ARRAY(CvPADLIST(C))[CvDEPTH(C)])[0]
1257
1258 STATIC void su_uplevel_restore(pTHX_ void *sus_) {
1259  su_uplevel_ud *sud = sus_;
1260  PERL_SI *cur = sud->old_curstackinfo;
1261  PERL_SI *si  = sud->si;
1262
1263 #if SU_UPLEVEL_HIJACKS_RUNOPS
1264  if (PL_runops == su_uplevel_goto_runops)
1265   PL_runops = sud->old_runops;
1266 #endif
1267
1268  if (sud->callback) {
1269   PERL_CONTEXT *cx = cxstack + sud->cxix;
1270   AV     *argarray = MUTABLE_AV(su_at_underscore(sud->callback));
1271
1272   /* We have to fix the pad entry for @_ in the original callback because it
1273    * may have been reified. */
1274   if (AvREAL(argarray)) {
1275    const I32 fill = AvFILLp(argarray);
1276    SvREFCNT_dec(argarray);
1277    argarray = newAV();
1278    AvREAL_off(argarray);
1279    AvREIFY_on(argarray);
1280    av_extend(argarray, fill);
1281    su_at_underscore(sud->callback) = MUTABLE_SV(argarray);
1282   } else {
1283    CLEAR_ARGARRAY(argarray);
1284   }
1285
1286   /* If the old cv member is our renamed CV, it means that this place has been
1287    * reached without a goto() happening, and the old argarray member is
1288    * actually our fake argarray. Destroy it properly in that case. */
1289   if (cx->blk_sub.cv == sud->renamed) {
1290    SvREFCNT_dec(cx->blk_sub.argarray);
1291    cx->blk_sub.argarray = argarray;
1292   }
1293
1294   CvDEPTH(sud->callback)--;
1295   SvREFCNT_dec(sud->callback);
1296  }
1297
1298  /* Free the renamed CV. We must do it ourselves so that we can force the
1299   * depth to be 0, or perl would complain about it being "still in use".
1300   * But we *know* that it cannot be so. */
1301  if (sud->renamed) {
1302   CvDEPTH(sud->renamed)   = 0;
1303   CvPADLIST(sud->renamed) = NULL;
1304   SvREFCNT_dec(sud->renamed);
1305  }
1306
1307  CATCH_SET(sud->old_catch);
1308
1309  SU_UPLEVEL_RESTORE(op);
1310
1311  /* stack_grow() wants PL_curstack so restore the old stack first */
1312  if (PL_curstackinfo == si) {
1313   PL_curstack = cur->si_stack;
1314   if (sud->old_mainstack)
1315    SU_UPLEVEL_RESTORE(mainstack);
1316   SU_UPLEVEL_RESTORE(curstackinfo);
1317
1318   if (sud->died) {
1319    CV *target = sud->target;
1320    I32 levels = 0, i;
1321
1322    /* When we die, the depth of the target CV is not updated because of the
1323     * stack switcheroo. So we have to look at all the frames between the
1324     * uplevel call and the catch block to count how many call frames to the
1325     * target CV were skipped. */
1326    for (i = cur->si_cxix; i > sud->cxix; i--) {
1327     register const PERL_CONTEXT *cx = cxstack + i;
1328
1329     if (CxTYPE(cx) == CXt_SUB) {
1330      if (cx->blk_sub.cv == target)
1331       ++levels;
1332     }
1333    }
1334
1335    /* If we died, the replacement stack was already unwinded to the first
1336     * eval frame, and all the contexts down there were popped. We don't have
1337     * to pop manually any context of the original stack, because they must
1338     * have been in the replacement stack as well (since the second was copied
1339     * from the first). Thus we only have to make sure the original stack index
1340     * points to the context just below the first eval scope under the target
1341     * frame. */
1342    for (; i >= 0; i--) {
1343     register const PERL_CONTEXT *cx = cxstack + i;
1344
1345     switch (CxTYPE(cx)) {
1346      case CXt_SUB:
1347       if (cx->blk_sub.cv == target)
1348        ++levels;
1349       break;
1350      case CXt_EVAL:
1351       goto found_it;
1352       break;
1353      default:
1354       break;
1355     }
1356    }
1357
1358 found_it:
1359    CvDEPTH(target) = sud->target_depth - levels;
1360    PL_curstackinfo->si_cxix = i - 1;
1361
1362 #if !SU_HAS_PERL(5, 13, 1)
1363    /* Since $@ was maybe localized between the target frame and the uplevel
1364     * call, we forcefully flush the save stack to get rid of it and then
1365     * reset $@ to its proper value. Note that the the call to
1366     * su_uplevel_restore() must happen before the "reset $@" item of the save
1367     * stack is processed, as uplevel was called after the localization.
1368     * Andrew's changes to how $@ was handled, which were mainly integrated
1369     * between perl 5.13.0 and 5.13.1, fixed this. */
1370    if (ERRSV && SvTRUE(ERRSV)) {
1371     register const PERL_CONTEXT *cx = cxstack + i; /* This is the eval scope */
1372     SV *errsv = SvREFCNT_inc(ERRSV);
1373     PL_scopestack_ix = cx->blk_oldscopesp;
1374     leave_scope(PL_scopestack[PL_scopestack_ix]);
1375     sv_setsv(ERRSV, errsv);
1376     SvREFCNT_dec(errsv);
1377    }
1378 #endif
1379   }
1380  }
1381
1382  SU_UPLEVEL_RESTORE(curcop);
1383
1384  SvREFCNT_dec(sud->target);
1385
1386  PL_stack_base = AvARRAY(cur->si_stack);
1387  PL_stack_sp   = PL_stack_base + AvFILLp(cur->si_stack);
1388  PL_stack_max  = PL_stack_base + AvMAX(cur->si_stack);
1389
1390  /* When an exception is thrown from the uplevel'd subroutine,
1391   * su_uplevel_restore() may be called by the LEAVE in die_unwind() (renamed
1392   * die_where() in more recent perls), which has the sad habit of keeping a
1393   * pointer to the current context frame across this call. This means that we
1394   * can't free the temporary context stack we used for the uplevel call right
1395   * now, or that pointer upwards would point to garbage. */
1396 #if SU_HAS_PERL(5, 13, 7)
1397  /* This issue has been fixed in perl with commit 8f89e5a9, which was made
1398   * public in perl 5.13.7. */
1399  su_uplevel_storage_delete(sud);
1400 #else
1401  /* Otherwise, we just enqueue it back in the global storage list. */
1402  {
1403   dMY_CXT;
1404
1405   sud->tmp_uid_storage = MY_CXT.uid_storage;
1406   MY_CXT.uid_storage   = sud->old_uid_storage;
1407
1408   MY_CXT.uplevel_storage.top  = sud->next;
1409   sud->next = MY_CXT.uplevel_storage.root;
1410   MY_CXT.uplevel_storage.root = sud;
1411   MY_CXT.uplevel_storage.count++;
1412  }
1413 #endif
1414
1415  return;
1416 }
1417
1418 STATIC CV *su_cv_clone(pTHX_ CV *proto, GV *gv) {
1419 #define su_cv_clone(P, G) su_cv_clone(aTHX_ (P), (G))
1420  dVAR;
1421  CV *cv;
1422
1423  cv = MUTABLE_CV(newSV_type(SvTYPE(proto)));
1424
1425  CvFLAGS(cv)  = CvFLAGS(proto);
1426 #ifdef CVf_CVGV_RC
1427  CvFLAGS(cv) &= ~CVf_CVGV_RC;
1428 #endif
1429  CvDEPTH(cv)  = CvDEPTH(proto);
1430 #ifdef USE_ITHREADS
1431  CvFILE(cv)   = CvISXSUB(proto) ? CvFILE(proto) : savepv(CvFILE(proto));
1432 #else
1433  CvFILE(cv)   = CvFILE(proto);
1434 #endif
1435
1436  CvGV_set(cv, gv);
1437  CvSTASH_set(cv, CvSTASH(proto));
1438  /* Commit 4c74a7df, publicized with perl 5.13.3, began to add backrefs to
1439   * stashes. CvSTASH_set() started to do it as well with commit c68d95645
1440   * (which was part of perl 5.13.7). */
1441 #if SU_HAS_PERL(5, 13, 3) && !SU_HAS_PERL(5, 13, 7)
1442  if (CvSTASH(proto))
1443   Perl_sv_add_backref(aTHX_ CvSTASH(proto), MUTABLE_SV(cv));
1444 #endif
1445
1446  if (CvISXSUB(proto)) {
1447   CvXSUB(cv)       = CvXSUB(proto);
1448   CvXSUBANY(cv)    = CvXSUBANY(proto);
1449  } else {
1450   OP_REFCNT_LOCK;
1451   CvROOT(cv)       = OpREFCNT_inc(CvROOT(proto));
1452   OP_REFCNT_UNLOCK;
1453   CvSTART(cv)      = CvSTART(proto);
1454  }
1455  CvOUTSIDE(cv)     = CvOUTSIDE(proto);
1456 #ifdef CVf_WEAKOUTSIDE
1457  if (!(CvFLAGS(proto) & CVf_WEAKOUTSIDE))
1458 #endif
1459   SvREFCNT_inc_simple_void(CvOUTSIDE(cv));
1460  CvPADLIST(cv)     = CvPADLIST(proto);
1461 #ifdef CvOUTSIDE_SEQ
1462  CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(proto);
1463 #endif
1464
1465  if (SvPOK(proto))
1466   sv_setpvn(MUTABLE_SV(cv), SvPVX_const(proto), SvCUR(proto));
1467
1468 #ifdef CvCONST
1469  if (CvCONST(cv))
1470   CvCONST_off(cv);
1471 #endif
1472
1473  return cv;
1474 }
1475
1476 STATIC I32 su_uplevel(pTHX_ CV *callback, I32 cxix, I32 args) {
1477 #define su_uplevel(C, I, A) su_uplevel(aTHX_ (C), (I), (A))
1478  su_uplevel_ud *sud;
1479  const PERL_CONTEXT *cx = cxstack + cxix;
1480  PERL_SI *si;
1481  PERL_SI *cur = PL_curstackinfo;
1482  SV **old_stack_sp;
1483  CV  *target;
1484  CV  *renamed;
1485  UNOP sub_op;
1486  I32  gimme;
1487  I32  old_mark, new_mark;
1488  I32  ret;
1489  dSP;
1490
1491  ENTER;
1492
1493  gimme = GIMME_V;
1494  /* Make PL_stack_sp point just before the CV. */
1495  PL_stack_sp -= args + 1;
1496  old_mark = AvFILLp(PL_curstack) = PL_stack_sp - PL_stack_base;
1497  SPAGAIN;
1498
1499  sud = su_uplevel_storage_new(cxix);
1500
1501  sud->cxix     = cxix;
1502  sud->died     = 1;
1503  sud->callback = NULL;
1504  sud->renamed  = NULL;
1505  SAVEDESTRUCTOR_X(su_uplevel_restore, sud);
1506
1507  si = sud->si;
1508
1509  si->si_type    = cur->si_type;
1510  si->si_next    = NULL;
1511  si->si_prev    = cur->si_prev;
1512 #ifdef DEBUGGING
1513  si->si_markoff = cx->blk_oldmarksp;
1514 #endif
1515
1516  /* Allocate enough space for all the elements of the original stack up to the
1517   * target context, plus the forthcoming arguments. */
1518  new_mark = cx->blk_oldsp;
1519  av_extend(si->si_stack, new_mark + 1 + args + 1);
1520  Copy(PL_curstack, AvARRAY(si->si_stack), new_mark + 1, SV *);
1521  AvFILLp(si->si_stack) = new_mark;
1522  SU_POISON(AvARRAY(si->si_stack) + new_mark + 1, args + 1, SV *);
1523
1524  /* Specialized SWITCHSTACK() */
1525  PL_stack_base = AvARRAY(si->si_stack);
1526  old_stack_sp  = PL_stack_sp;
1527  PL_stack_sp   = PL_stack_base + AvFILLp(si->si_stack);
1528  PL_stack_max  = PL_stack_base + AvMAX(si->si_stack);
1529  SPAGAIN;
1530
1531  /* Copy the context stack up to the context just below the target. */
1532  si->si_cxix = (cxix < 0) ? -1 : (cxix - 1);
1533  if (si->si_cxmax < cxix) {
1534   /* The max size must be at least two so that GROW(max) = (max*3)/2 > max */
1535   si->si_cxmax = (cxix < 4) ? 4 : cxix;
1536   Renew(si->si_cxstack, si->si_cxmax + 1, PERL_CONTEXT);
1537  }
1538  Copy(cur->si_cxstack, si->si_cxstack, cxix, PERL_CONTEXT);
1539  SU_POISON(si->si_cxstack + cxix, si->si_cxmax + 1 - cxix, PERL_CONTEXT);
1540
1541  target            = cx->blk_sub.cv;
1542  sud->target       = (CV *) SvREFCNT_inc(target);
1543  sud->target_depth = CvDEPTH(target);
1544
1545  /* blk_oldcop is essentially needed for caller() and stack traces. It has no
1546   * run-time implication, since PL_curcop will be overwritten as soon as we
1547   * enter a sub (a sub starts by a nextstate/dbstate). Hence it's safe to just
1548   * make it point to the blk_oldcop for the target frame, so that caller()
1549   * reports the right file name, line number and lexical hints. */
1550  SU_UPLEVEL_SAVE(curcop, cx->blk_oldcop);
1551  /* Don't reset PL_markstack_ptr, or we would overwrite the mark stack below
1552   * this point. Don't reset PL_curpm either, we want the most recent matches. */
1553
1554  SU_UPLEVEL_SAVE(curstackinfo, si);
1555  /* If those two are equal, we need to fool POPSTACK_TO() */
1556  if (PL_mainstack == PL_curstack)
1557   SU_UPLEVEL_SAVE(mainstack, si->si_stack);
1558  else
1559   sud->old_mainstack = NULL;
1560  PL_curstack = si->si_stack;
1561
1562  renamed      = su_cv_clone(callback, CvGV(target));
1563  sud->renamed = renamed;
1564
1565  PUSHMARK(SP);
1566  /* Both SP and old_stack_sp point just before the CV. */
1567  Copy(old_stack_sp + 2, SP + 1, args, SV *);
1568  SP += args;
1569  PUSHs((SV *) renamed);
1570  PUTBACK;
1571
1572  Zero(&sub_op, 1, UNOP);
1573  sub_op.op_type  = OP_ENTERSUB;
1574  sub_op.op_next  = NULL;
1575  sub_op.op_flags = OP_GIMME_REVERSE(gimme) | OPf_STACKED;
1576  if (PL_DBsub)
1577   sub_op.op_flags |= OPpENTERSUB_DB;
1578
1579  SU_UPLEVEL_SAVE(op, (OP *) &sub_op);
1580
1581 #if SU_UPLEVEL_HIJACKS_RUNOPS
1582  sud->old_runops = PL_runops;
1583 #endif
1584
1585  sud->old_catch = CATCH_GET;
1586  CATCH_SET(TRUE);
1587
1588  if ((PL_op = PL_ppaddr[OP_ENTERSUB](aTHX))) {
1589   PERL_CONTEXT *sub_cx = cxstack + cxstack_ix;
1590
1591   /* If pp_entersub() returns a non-null OP, it means that the callback is not
1592    * an XSUB. */
1593
1594   sud->callback = MUTABLE_CV(SvREFCNT_inc(callback));
1595   CvDEPTH(callback)++;
1596
1597   if (CxHASARGS(cx) && cx->blk_sub.argarray) {
1598    /* The call to pp_entersub() has saved the current @_ (in XS terms,
1599     * GvAV(PL_defgv)) in the savearray member, and has created a new argarray
1600     * with what we put on the stack. But we want to fake up the same arguments
1601     * as the ones in use at the context we uplevel to, so we replace the
1602     * argarray with an unreal copy of the original @_. */
1603    AV *av = newAV();
1604    AvREAL_off(av);
1605    AvREIFY_on(av);
1606    av_extend(av, AvMAX(cx->blk_sub.argarray));
1607    AvFILLp(av) = AvFILLp(cx->blk_sub.argarray);
1608    Copy(AvARRAY(cx->blk_sub.argarray), AvARRAY(av), AvFILLp(av) + 1, SV *);
1609    sub_cx->blk_sub.argarray = av;
1610   } else {
1611    SvREFCNT_inc_simple_void(sub_cx->blk_sub.argarray);
1612   }
1613
1614   if (su_uplevel_goto_static(CvROOT(renamed))) {
1615 #if SU_UPLEVEL_HIJACKS_RUNOPS
1616    if (PL_runops != PL_runops_std) {
1617     if (PL_runops == PL_runops_dbg) {
1618      if (PL_debug)
1619       croak("uplevel() can't execute code that calls goto when debugging flags are set");
1620     } else if (PL_runops != su_uplevel_goto_runops)
1621      croak("uplevel() can't execute code that calls goto with a custom runloop");
1622    }
1623
1624    PL_runops = su_uplevel_goto_runops;
1625 #else  /* SU_UPLEVEL_HIJACKS_RUNOPS */
1626    croak("uplevel() can't execute code that calls goto before perl 5.8");
1627 #endif /* !SU_UPLEVEL_HIJACKS_RUNOPS */
1628   }
1629
1630   CALLRUNOPS(aTHX);
1631  }
1632
1633  sud->died = 0;
1634
1635  ret = PL_stack_sp - (PL_stack_base + new_mark);
1636  if (ret > 0) {
1637   AV *old_stack = sud->old_curstackinfo->si_stack;
1638
1639   if (old_mark + ret > AvMAX(old_stack)) {
1640    /* Specialized EXTEND(old_sp, ret) */
1641    av_extend(old_stack, old_mark + ret + 1);
1642    old_stack_sp = AvARRAY(old_stack) + old_mark;
1643   }
1644
1645   Copy(PL_stack_sp - ret + 1, old_stack_sp + 1, ret, SV *);
1646   PL_stack_sp        += ret;
1647   AvFILLp(old_stack) += ret;
1648  }
1649
1650  LEAVE;
1651
1652  return ret;
1653 }
1654
1655 /* --- Unique context ID --------------------------------------------------- */
1656
1657 STATIC su_uid *su_uid_storage_fetch(pTHX_ UV depth) {
1658 #define su_uid_storage_fetch(D) su_uid_storage_fetch(aTHX_ (D))
1659  su_uid **map, *uid;
1660  STRLEN alloc;
1661  dMY_CXT;
1662
1663  map   = MY_CXT.uid_storage.map;
1664  alloc = MY_CXT.uid_storage.alloc;
1665
1666  if (depth >= alloc) {
1667   STRLEN i;
1668
1669   Renew(map, depth + 1, su_uid *);
1670   for (i = alloc; i <= depth; ++i)
1671    map[i] = NULL;
1672
1673   MY_CXT.uid_storage.map   = map;
1674   MY_CXT.uid_storage.alloc = depth + 1;
1675  }
1676
1677  uid = map[depth];
1678
1679  if (!uid) {
1680   Newx(uid, 1, su_uid);
1681   uid->seq   = 0;
1682   uid->flags = 0;
1683   map[depth] = uid;
1684  }
1685
1686  if (depth >= MY_CXT.uid_storage.used)
1687   MY_CXT.uid_storage.used = depth + 1;
1688
1689  return uid;
1690 }
1691
1692 STATIC int su_uid_storage_check(pTHX_ UV depth, UV seq) {
1693 #define su_uid_storage_check(D, S) su_uid_storage_check(aTHX_ (D), (S))
1694  su_uid *uid;
1695  dMY_CXT;
1696
1697  if (depth >= MY_CXT.uid_storage.used)
1698   return 0;
1699
1700  uid = MY_CXT.uid_storage.map[depth];
1701
1702  return uid && (uid->seq == seq) && (uid->flags & SU_UID_ACTIVE);
1703 }
1704
1705 STATIC void su_uid_drop(pTHX_ void *ud_) {
1706  su_uid *uid = ud_;
1707
1708  uid->flags &= ~SU_UID_ACTIVE;
1709 }
1710
1711 STATIC void su_uid_bump(pTHX_ void *ud_) {
1712  su_ud_reap *ud  = ud_;
1713
1714  SAVEDESTRUCTOR_X(su_uid_drop, ud->cb);
1715 }
1716
1717 STATIC SV *su_uid_get(pTHX_ I32 cxix) {
1718 #define su_uid_get(I) su_uid_get(aTHX_ (I))
1719  su_uid *uid;
1720  SV *uid_sv;
1721  UV depth;
1722
1723  depth = su_uid_depth(cxix);
1724  uid   = su_uid_storage_fetch(depth);
1725
1726  if (!(uid->flags & SU_UID_ACTIVE)) {
1727   su_ud_reap *ud;
1728
1729   uid->seq = su_uid_seq_next(depth);
1730   uid->flags |= SU_UID_ACTIVE;
1731
1732   Newx(ud, 1, su_ud_reap);
1733   SU_UD_ORIGIN(ud)  = NULL;
1734   SU_UD_HANDLER(ud) = su_uid_bump;
1735   ud->cb = (SV *) uid;
1736   su_init(ud, cxix, SU_SAVE_DESTRUCTOR_SIZE);
1737  }
1738
1739  uid_sv = sv_newmortal();
1740  sv_setpvf(uid_sv, "%"UVuf"-%"UVuf, depth, uid->seq);
1741  return uid_sv;
1742 }
1743
1744 #ifdef grok_number
1745
1746 #define su_grok_number(S, L, VP) grok_number((S), (L), (VP))
1747
1748 #else /* grok_number */
1749
1750 #define IS_NUMBER_IN_UV 0x1
1751
1752 STATIC int su_grok_number(pTHX_ const char *s, STRLEN len, UV *valuep) {
1753 #define su_grok_number(S, L, VP) su_grok_number(aTHX_ (S), (L), (VP))
1754  STRLEN i;
1755  SV *tmpsv;
1756
1757  /* This crude check should be good enough for a fallback implementation.
1758   * Better be too strict than too lax. */
1759  for (i = 0; i < len; ++i) {
1760   if (!isDIGIT(s[i]))
1761    return 0;
1762  }
1763
1764  tmpsv = sv_newmortal();
1765  sv_setpvn(tmpsv, s, len);
1766  *valuep = sv_2uv(tmpsv);
1767
1768  return IS_NUMBER_IN_UV;
1769 }
1770
1771 #endif /* !grok_number */
1772
1773 STATIC int su_uid_validate(pTHX_ SV *uid) {
1774 #define su_uid_validate(U) su_uid_validate(aTHX_ (U))
1775  const char *s;
1776  STRLEN len, p = 0;
1777  UV depth, seq;
1778  int type;
1779
1780  s = SvPV_const(uid, len);
1781
1782  while (p < len && s[p] != '-')
1783   ++p;
1784  if (p >= len)
1785   croak("UID contains only one part");
1786
1787  type = su_grok_number(s, p, &depth);
1788  if (type != IS_NUMBER_IN_UV)
1789   croak("First UID part is not an unsigned integer");
1790
1791  ++p; /* Skip '-'. As we used to have p < len, len - (p + 1) >= 0. */
1792
1793  type = su_grok_number(s + p, len - p, &seq);
1794  if (type != IS_NUMBER_IN_UV)
1795   croak("Second UID part is not an unsigned integer");
1796
1797  return su_uid_storage_check(depth, seq);
1798 }
1799
1800 /* --- Interpreter setup/teardown ------------------------------------------ */
1801
1802 STATIC void su_teardown(pTHX_ void *param) {
1803  su_uplevel_ud *cur;
1804  su_uid **map;
1805  dMY_CXT;
1806
1807  map = MY_CXT.uid_storage.map;
1808  if (map) {
1809   STRLEN i;
1810   for (i = 0; i < MY_CXT.uid_storage.used; ++i)
1811    Safefree(map[i]);
1812   Safefree(map);
1813  }
1814
1815  cur = MY_CXT.uplevel_storage.root;
1816  if (cur) {
1817   su_uplevel_ud *prev;
1818   do {
1819    prev = cur;
1820    cur  = prev->next;
1821    su_uplevel_ud_delete(prev);
1822   } while (cur);
1823  }
1824
1825  return;
1826 }
1827
1828 STATIC void su_setup(pTHX) {
1829 #define su_setup() su_setup(aTHX)
1830  MY_CXT_INIT;
1831
1832  MY_CXT.stack_placeholder = NULL;
1833
1834  /* NewOp() calls calloc() which just zeroes the memory with memset(). */
1835  Zero(&(MY_CXT.unwind_storage.return_op), 1, LISTOP);
1836  MY_CXT.unwind_storage.return_op.op_type   = OP_RETURN;
1837  MY_CXT.unwind_storage.return_op.op_ppaddr = PL_ppaddr[OP_RETURN];
1838
1839  Zero(&(MY_CXT.unwind_storage.proxy_op), 1, OP);
1840  MY_CXT.unwind_storage.proxy_op.op_type   = OP_STUB;
1841  MY_CXT.unwind_storage.proxy_op.op_ppaddr = NULL;
1842
1843  MY_CXT.uplevel_storage.top   = NULL;
1844  MY_CXT.uplevel_storage.root  = NULL;
1845  MY_CXT.uplevel_storage.count = 0;
1846
1847  MY_CXT.uid_storage.map   = NULL;
1848  MY_CXT.uid_storage.used  = 0;
1849  MY_CXT.uid_storage.alloc = 0;
1850
1851  call_atexit(su_teardown, NULL);
1852
1853  return;
1854 }
1855
1856 /* --- XS ------------------------------------------------------------------ */
1857
1858 #if SU_HAS_PERL(5, 8, 9)
1859 # define SU_SKIP_DB_MAX 2
1860 #else
1861 # define SU_SKIP_DB_MAX 3
1862 #endif
1863
1864 /* Skip context sequences of 1 to SU_SKIP_DB_MAX (included) block contexts
1865  * followed by a DB sub */
1866
1867 #define SU_SKIP_DB(C) \
1868  STMT_START {         \
1869   I32 skipped = 0;    \
1870   PERL_CONTEXT *base = cxstack;      \
1871   PERL_CONTEXT *cx   = base + (C);   \
1872   while (cx >= base && (C) > skipped && CxTYPE(cx) == CXt_BLOCK) \
1873    --cx, ++skipped;                  \
1874   if (cx >= base && (C) > skipped) { \
1875    switch (CxTYPE(cx)) {  \
1876     case CXt_SUB:         \
1877      if (skipped <= SU_SKIP_DB_MAX && cx->blk_sub.cv == GvCV(PL_DBsub)) \
1878       (C) -= skipped + 1; \
1879       break;              \
1880     default:              \
1881      break;               \
1882    }                      \
1883   }                       \
1884  } STMT_END
1885
1886 #define SU_GET_CONTEXT(A, B)   \
1887  STMT_START {                  \
1888   if (items > A) {             \
1889    SV *csv = ST(B);            \
1890    if (!SvOK(csv))             \
1891     goto default_cx;           \
1892    cxix = SvIV(csv);           \
1893    if (cxix < 0)               \
1894     cxix = 0;                  \
1895    else if (cxix > cxstack_ix) \
1896     cxix = cxstack_ix;         \
1897   } else {                     \
1898 default_cx:                    \
1899    cxix = cxstack_ix;          \
1900    if (PL_DBsub)               \
1901     SU_SKIP_DB(cxix);          \
1902   }                            \
1903  } STMT_END
1904
1905 #define SU_GET_LEVEL(A, B) \
1906  STMT_START {              \
1907   level = 0;               \
1908   if (items > 0) {         \
1909    SV *lsv = ST(B);        \
1910    if (SvOK(lsv)) {        \
1911     level = SvIV(lsv);     \
1912     if (level < 0)         \
1913      level = 0;            \
1914    }                       \
1915   }                        \
1916  } STMT_END
1917
1918 XS(XS_Scope__Upper_unwind); /* prototype to pass -Wmissing-prototypes */
1919
1920 XS(XS_Scope__Upper_unwind) {
1921 #ifdef dVAR
1922  dVAR; dXSARGS;
1923 #else
1924  dXSARGS;
1925 #endif
1926  dMY_CXT;
1927  I32 cxix;
1928
1929  PERL_UNUSED_VAR(cv); /* -W */
1930  PERL_UNUSED_VAR(ax); /* -Wall */
1931
1932  SU_GET_CONTEXT(0, items - 1);
1933  do {
1934   PERL_CONTEXT *cx = cxstack + cxix;
1935   switch (CxTYPE(cx)) {
1936    case CXt_SUB:
1937     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
1938      continue;
1939    case CXt_EVAL:
1940    case CXt_FORMAT:
1941     MY_CXT.unwind_storage.cxix  = cxix;
1942     MY_CXT.unwind_storage.items = items;
1943     /* pp_entersub will want to sanitize the stack after returning from there
1944      * Screw that, we're insane */
1945     if (GIMME_V == G_SCALAR) {
1946      MY_CXT.unwind_storage.savesp = PL_stack_sp;
1947      /* dXSARGS calls POPMARK, so we need to match PL_markstack_ptr[1] */
1948      PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
1949     } else {
1950      MY_CXT.unwind_storage.savesp = NULL;
1951     }
1952     SAVEDESTRUCTOR_X(su_unwind, NULL);
1953     return;
1954    default:
1955     break;
1956   }
1957  } while (--cxix >= 0);
1958  croak("Can't return outside a subroutine");
1959 }
1960
1961 MODULE = Scope::Upper            PACKAGE = Scope::Upper
1962
1963 PROTOTYPES: ENABLE
1964
1965 BOOT:
1966 {
1967  HV *stash;
1968
1969  MUTEX_INIT(&su_uid_seq_counter_mutex);
1970
1971  su_uid_seq_counter.seqs = NULL;
1972  su_uid_seq_counter.size = 0;
1973
1974  stash = gv_stashpv(__PACKAGE__, 1);
1975  newCONSTSUB(stash, "TOP",           newSViv(0));
1976  newCONSTSUB(stash, "SU_THREADSAFE", newSVuv(SU_THREADSAFE));
1977
1978  newXSproto("Scope::Upper::unwind", XS_Scope__Upper_unwind, file, NULL);
1979
1980  su_setup();
1981 }
1982
1983 #if SU_THREADSAFE
1984
1985 void
1986 CLONE(...)
1987 PROTOTYPE: DISABLE
1988 PREINIT:
1989  su_uid_storage new_cxt;
1990 PPCODE:
1991  {
1992   dMY_CXT;
1993   new_cxt.map   = NULL;
1994   new_cxt.used  = 0;
1995   new_cxt.alloc = 0;
1996   su_uid_storage_dup(&new_cxt, &MY_CXT.uid_storage, MY_CXT.uid_storage.used);
1997  }
1998  {
1999   MY_CXT_CLONE;
2000   MY_CXT.uplevel_storage.top   = NULL;
2001   MY_CXT.uplevel_storage.root  = NULL;
2002   MY_CXT.uplevel_storage.count = 0;
2003   MY_CXT.uid_storage           = new_cxt;
2004  }
2005  XSRETURN(0);
2006
2007 #endif /* SU_THREADSAFE */
2008
2009 void
2010 HERE()
2011 PROTOTYPE:
2012 PREINIT:
2013  I32 cxix = cxstack_ix;
2014 PPCODE:
2015  if (PL_DBsub)
2016   SU_SKIP_DB(cxix);
2017  EXTEND(SP, 1);
2018  mPUSHi(cxix);
2019  XSRETURN(1);
2020
2021 void
2022 UP(...)
2023 PROTOTYPE: ;$
2024 PREINIT:
2025  I32 cxix;
2026 PPCODE:
2027  SU_GET_CONTEXT(0, 0);
2028  if (--cxix < 0)
2029   cxix = 0;
2030  if (PL_DBsub)
2031   SU_SKIP_DB(cxix);
2032  EXTEND(SP, 1);
2033  mPUSHi(cxix);
2034  XSRETURN(1);
2035
2036 void
2037 SUB(...)
2038 PROTOTYPE: ;$
2039 PREINIT:
2040  I32 cxix;
2041 PPCODE:
2042  SU_GET_CONTEXT(0, 0);
2043  EXTEND(SP, 1);
2044  for (; cxix >= 0; --cxix) {
2045   PERL_CONTEXT *cx = cxstack + cxix;
2046   switch (CxTYPE(cx)) {
2047    default:
2048     continue;
2049    case CXt_SUB:
2050     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2051      continue;
2052     mPUSHi(cxix);
2053     XSRETURN(1);
2054   }
2055  }
2056  XSRETURN_UNDEF;
2057
2058 void
2059 EVAL(...)
2060 PROTOTYPE: ;$
2061 PREINIT:
2062  I32 cxix;
2063 PPCODE:
2064  SU_GET_CONTEXT(0, 0);
2065  EXTEND(SP, 1);
2066  for (; cxix >= 0; --cxix) {
2067   PERL_CONTEXT *cx = cxstack + cxix;
2068   switch (CxTYPE(cx)) {
2069    default:
2070     continue;
2071    case CXt_EVAL:
2072     mPUSHi(cxix);
2073     XSRETURN(1);
2074   }
2075  }
2076  XSRETURN_UNDEF;
2077
2078 void
2079 SCOPE(...)
2080 PROTOTYPE: ;$
2081 PREINIT:
2082  I32 cxix, level;
2083 PPCODE:
2084  SU_GET_LEVEL(0, 0);
2085  cxix = cxstack_ix;
2086  if (PL_DBsub) {
2087   SU_SKIP_DB(cxix);
2088   while (cxix > 0) {
2089    if (--level < 0)
2090     break;
2091    --cxix;
2092    SU_SKIP_DB(cxix);
2093   }
2094  } else {
2095   cxix -= level;
2096   if (cxix < 0)
2097    cxix = 0;
2098  }
2099  EXTEND(SP, 1);
2100  mPUSHi(cxix);
2101  XSRETURN(1);
2102
2103 void
2104 CALLER(...)
2105 PROTOTYPE: ;$
2106 PREINIT:
2107  I32 cxix, level;
2108 PPCODE:
2109  SU_GET_LEVEL(0, 0);
2110  for (cxix = cxstack_ix; cxix > 0; --cxix) {
2111   PERL_CONTEXT *cx = cxstack + cxix;
2112   switch (CxTYPE(cx)) {
2113    case CXt_SUB:
2114     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2115      continue;
2116    case CXt_EVAL:
2117    case CXt_FORMAT:
2118     if (--level < 0)
2119      goto done;
2120     break;
2121   }
2122  }
2123 done:
2124  EXTEND(SP, 1);
2125  mPUSHi(cxix);
2126  XSRETURN(1);
2127
2128 void
2129 want_at(...)
2130 PROTOTYPE: ;$
2131 PREINIT:
2132  I32 cxix;
2133 PPCODE:
2134  SU_GET_CONTEXT(0, 0);
2135  EXTEND(SP, 1);
2136  while (cxix > 0) {
2137   PERL_CONTEXT *cx = cxstack + cxix--;
2138   switch (CxTYPE(cx)) {
2139    case CXt_SUB:
2140    case CXt_EVAL:
2141    case CXt_FORMAT: {
2142     I32 gimme = cx->blk_gimme;
2143     switch (gimme) {
2144      case G_VOID:   XSRETURN_UNDEF; break;
2145      case G_SCALAR: XSRETURN_NO;    break;
2146      case G_ARRAY:  XSRETURN_YES;   break;
2147     }
2148     break;
2149    }
2150   }
2151  }
2152  XSRETURN_UNDEF;
2153
2154 void
2155 reap(SV *hook, ...)
2156 PROTOTYPE: &;$
2157 PREINIT:
2158  I32 cxix;
2159  su_ud_reap *ud;
2160 CODE:
2161  SU_GET_CONTEXT(1, 1);
2162  Newx(ud, 1, su_ud_reap);
2163  SU_UD_ORIGIN(ud)  = NULL;
2164  SU_UD_HANDLER(ud) = su_reap;
2165  ud->cb = newSVsv(hook);
2166  su_init(ud, cxix, SU_SAVE_DESTRUCTOR_SIZE);
2167
2168 void
2169 localize(SV *sv, SV *val, ...)
2170 PROTOTYPE: $$;$
2171 PREINIT:
2172  I32 cxix;
2173  I32 size;
2174  su_ud_localize *ud;
2175 CODE:
2176  SU_GET_CONTEXT(2, 2);
2177  Newx(ud, 1, su_ud_localize);
2178  SU_UD_ORIGIN(ud)  = NULL;
2179  SU_UD_HANDLER(ud) = su_localize;
2180  size = su_ud_localize_init(ud, sv, val, NULL);
2181  su_init(ud, cxix, size);
2182
2183 void
2184 localize_elem(SV *sv, SV *elem, SV *val, ...)
2185 PROTOTYPE: $$$;$
2186 PREINIT:
2187  I32 cxix;
2188  I32 size;
2189  su_ud_localize *ud;
2190 CODE:
2191  if (SvTYPE(sv) >= SVt_PVGV)
2192   croak("Can't infer the element localization type from a glob and the value");
2193  SU_GET_CONTEXT(3, 3);
2194  Newx(ud, 1, su_ud_localize);
2195  SU_UD_ORIGIN(ud)  = NULL;
2196  SU_UD_HANDLER(ud) = su_localize;
2197  size = su_ud_localize_init(ud, sv, val, elem);
2198  if (ud->type != SVt_PVAV && ud->type != SVt_PVHV) {
2199   SU_UD_LOCALIZE_FREE(ud);
2200   croak("Can't localize an element of something that isn't an array or a hash");
2201  }
2202  su_init(ud, cxix, size);
2203
2204 void
2205 localize_delete(SV *sv, SV *elem, ...)
2206 PROTOTYPE: $$;$
2207 PREINIT:
2208  I32 cxix;
2209  I32 size;
2210  su_ud_localize *ud;
2211 CODE:
2212  SU_GET_CONTEXT(2, 2);
2213  Newx(ud, 1, su_ud_localize);
2214  SU_UD_ORIGIN(ud)  = NULL;
2215  SU_UD_HANDLER(ud) = su_localize;
2216  size = su_ud_localize_init(ud, sv, NULL, elem);
2217  su_init(ud, cxix, size);
2218
2219 void
2220 uplevel(SV *code, ...)
2221 PROTOTYPE: &@
2222 PREINIT:
2223  I32 cxix, ret, args = 0;
2224 PPCODE:
2225  if (SvROK(code))
2226   code = SvRV(code);
2227  if (SvTYPE(code) < SVt_PVCV)
2228   croak("First argument to uplevel must be a code reference");
2229  SU_GET_CONTEXT(1, items - 1);
2230  do {
2231   PERL_CONTEXT *cx = cxstack + cxix;
2232   switch (CxTYPE(cx)) {
2233    case CXt_EVAL:
2234     croak("Can't uplevel to an eval frame");
2235    case CXt_FORMAT:
2236     croak("Can't uplevel to a format frame");
2237    case CXt_SUB:
2238     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
2239      continue;
2240     if (items > 1) {
2241      PL_stack_sp--;
2242      args = items - 2;
2243     }
2244     /* su_uplevel() takes care of extending the stack if needed. */
2245     ret = su_uplevel((CV *) code, cxix, args);
2246     XSRETURN(ret);
2247    default:
2248     break;
2249   }
2250  } while (--cxix >= 0);
2251  croak("Can't uplevel outside a subroutine");
2252
2253 void
2254 uid(...)
2255 PROTOTYPE: ;$
2256 PREINIT:
2257  I32 cxix;
2258  SV *uid;
2259 PPCODE:
2260  SU_GET_CONTEXT(0, 0);
2261  uid = su_uid_get(cxix);
2262  EXTEND(SP, 1);
2263  PUSHs(uid);
2264  XSRETURN(1);
2265
2266 void
2267 validate_uid(SV *uid)
2268 PROTOTYPE: $
2269 PREINIT:
2270  SV *ret;
2271 PPCODE:
2272  ret = su_uid_validate(uid) ? &PL_sv_yes : &PL_sv_no;
2273  EXTEND(SP, 1);
2274  PUSHs(ret);
2275  XSRETURN(1);