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