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