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