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