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