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