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