This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
new perldelta
[perl5.git] / pp_ctl.c
1 /*    pp_ctl.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  *      Now far ahead the Road has gone,
13  *          And I must follow, if I can,
14  *      Pursuing it with eager feet,
15  *          Until it joins some larger way
16  *      Where many paths and errands meet.
17  *          And whither then?  I cannot say.
18  *
19  *     [Bilbo on p.35 of _The Lord of the Rings_, I/i: "A Long-Expected Party"]
20  */
21
22 /* This file contains control-oriented pp ("push/pop") functions that
23  * execute the opcodes that make up a perl program. A typical pp function
24  * expects to find its arguments on the stack, and usually pushes its
25  * results onto the stack, hence the 'pp' terminology. Each OP structure
26  * contains a pointer to the relevant pp_foo() function.
27  *
28  * Control-oriented means things like pp_enteriter() and pp_next(), which
29  * alter the flow of control of the program.
30  */
31
32
33 #include "EXTERN.h"
34 #define PERL_IN_PP_CTL_C
35 #include "perl.h"
36 #include "feature.h"
37
38 #define dopopto_cursub() \
39     (PL_curstackinfo->si_cxsubix >= 0        \
40         ? PL_curstackinfo->si_cxsubix        \
41         : dopoptosub_at(cxstack, cxstack_ix))
42
43 #define dopoptosub(plop)        dopoptosub_at(cxstack, (plop))
44
45 PP(pp_wantarray)
46 {
47     I32 cxix;
48     const PERL_CONTEXT *cx;
49     SV *sv;
50
51     if (PL_op->op_private & OPpOFFBYONE) {
52         if (!(cx = caller_cx(1,NULL))) {
53             sv = &PL_sv_undef;
54             goto ret;
55         }
56     }
57     else {
58       cxix = dopopto_cursub();
59       if (cxix < 0) {
60         sv = &PL_sv_undef;
61         goto ret;
62       }
63       cx = &cxstack[cxix];
64     }
65
66     switch (cx->blk_gimme) {
67     case G_LIST:
68         sv = &PL_sv_yes;
69         break;
70     case G_SCALAR:
71         sv = &PL_sv_no;
72         break;
73     default:
74         sv = &PL_sv_undef;
75         break;
76     }
77
78   ret:
79     rpp_xpush_IMM(sv);
80     return NORMAL;
81 }
82
83 PP(pp_regcreset)
84 {
85     TAINT_NOT;
86     return NORMAL;
87 }
88
89 PP(pp_regcomp)
90 {
91     PMOP *pm = cPMOPx(cLOGOP->op_other);
92     SV **args;
93     int nargs;
94     REGEXP *re = NULL;
95     REGEXP *new_re;
96     const regexp_engine *eng;
97     bool is_bare_re= FALSE;
98
99     if (PL_op->op_flags & OPf_STACKED) {
100         dMARK;
101         nargs = PL_stack_sp - MARK;
102         args  = ++MARK;
103     }
104     else {
105         nargs = 1;
106         args  = PL_stack_sp;
107     }
108
109     /* prevent recompiling under /o and ithreads. */
110 #if defined(USE_ITHREADS)
111     if (pm->op_pmflags & PMf_KEEP && PM_GETRE(pm))
112         goto finish;
113 #endif
114
115     re = PM_GETRE(pm);
116     assert (re != (REGEXP*) &PL_sv_undef);
117     eng = re ? RX_ENGINE(re) : current_re_engine();
118
119     new_re = (eng->op_comp
120                     ? eng->op_comp
121                     : &Perl_re_op_compile
122             )(aTHX_ args, nargs, pm->op_code_list, eng, re,
123                 &is_bare_re,
124                 (pm->op_pmflags & RXf_PMf_FLAGCOPYMASK),
125                 pm->op_pmflags |
126                     (PL_op->op_flags & OPf_SPECIAL ? PMf_USE_RE_EVAL : 0));
127
128     if (pm->op_pmflags & PMf_HAS_CV)
129         ReANY(new_re)->qr_anoncv
130                         = (CV*) SvREFCNT_inc(PAD_SV(PL_op->op_targ));
131
132     if (is_bare_re) {
133         REGEXP *tmp;
134         /* The match's LHS's get-magic might need to access this op's regexp
135            (e.g. $' =~ /$re/ while foo; see bug 70764).  So we must call
136            get-magic now before we replace the regexp. Hopefully this hack can
137            be replaced with the approach described at
138            https://www.nntp.perl.org/group/perl.perl5.porters/2007/03/msg122415.html
139            some day. */
140         if (pm->op_type == OP_MATCH) {
141             SV *lhs;
142             const bool was_tainted = TAINT_get;
143             if (pm->op_flags & OPf_STACKED)
144                 lhs = args[-1];
145             else if (pm->op_targ)
146                 lhs = PAD_SV(pm->op_targ);
147             else lhs = DEFSV;
148             SvGETMAGIC(lhs);
149             /* Restore the previous value of PL_tainted (which may have been
150                modified by get-magic), to avoid incorrectly setting the
151                RXf_TAINTED flag with RX_TAINT_on further down. */
152             TAINT_set(was_tainted);
153 #ifdef NO_TAINT_SUPPORT
154             PERL_UNUSED_VAR(was_tainted);
155 #endif
156         }
157         tmp = reg_temp_copy(NULL, new_re);
158         ReREFCNT_dec(new_re);
159         new_re = tmp;
160     }
161
162     if (re != new_re) {
163         ReREFCNT_dec(re);
164         PM_SETRE(pm, new_re);
165     }
166
167
168     assert(TAINTING_get || !TAINT_get);
169     if (TAINT_get) {
170         SvTAINTED_on((SV*)new_re);
171         RX_TAINT_on(new_re);
172     }
173
174     /* handle the empty pattern */
175     if (!RX_PRELEN(PM_GETRE(pm)) && PL_curpm) {
176         if (PL_curpm == PL_reg_curpm) {
177             if (PL_curpm_under && PL_curpm_under == PL_reg_curpm) {
178                 Perl_croak(aTHX_ "Infinite recursion via empty pattern");
179             }
180         }
181     }
182
183 #if !defined(USE_ITHREADS)
184     /* can't change the optree at runtime either */
185     /* PMf_KEEP is handled differently under threads to avoid these problems */
186     if (pm->op_pmflags & PMf_KEEP) {
187         cLOGOP->op_first->op_next = PL_op->op_next;
188     }
189 #endif
190
191 #if defined(USE_ITHREADS)
192   finish:
193 #endif
194     rpp_popfree_to_NN(args - 1);
195     return NORMAL;
196 }
197
198
199 /* s/.../expr/e is executed in order as if written as
200  *
201  * pp_subst();
202  * while (pp_substcont()) {
203  *     expr;
204  * }
205  *
206  * Only on the second and later calls to pp_substcont() is there a scalar
207  * on the stack holding the value of expr.
208  *
209  * Note that pp_subst() leaves its original 0-2 args on the stack to
210  * avoid them being prematurely freed. It is pp_substcont()'s
211  * responsibility to pop them after the last iteration.
212  */
213
214 PP(pp_substcont)
215 {
216     PERL_CONTEXT *cx = CX_CUR();
217     PMOP * const pm = cPMOPx(cLOGOP->op_other);
218     SV * const dstr = cx->sb_dstr;
219     char *s = cx->sb_s;
220     char *m = cx->sb_m;
221     char *orig = cx->sb_orig;
222     REGEXP * const rx = cx->sb_rx;
223     SV *nsv = NULL;
224     REGEXP *old = PM_GETRE(pm);
225
226     PERL_ASYNC_CHECK();
227
228     if(old != rx) {
229         if(old)
230             ReREFCNT_dec(old);
231         PM_SETRE(pm,ReREFCNT_inc(rx));
232     }
233
234     rxres_restore(&cx->sb_rxres, rx);
235
236     if (cx->sb_iters++) {
237         /* second+ time round. Result is on stack */
238         const SSize_t saviters = cx->sb_iters;
239         if (cx->sb_iters > cx->sb_maxiters)
240             DIE(aTHX_ "Substitution loop");
241
242         SvGETMAGIC(*PL_stack_sp); /* possibly clear taint on $1 etc: #67962 */
243
244         /* See "how taint works": pp_subst() in pp_hot.c */
245         sv_catsv_nomg(dstr, *PL_stack_sp);
246         rpp_popfree_1_NN();
247         if (UNLIKELY(TAINT_get))
248             cx->sb_rxtainted |= SUBST_TAINT_REPL;
249         if (CxONCE(cx) || s < orig ||
250                 !CALLREGEXEC(rx, s, cx->sb_strend, orig,
251                              (s == m), cx->sb_targ, NULL,
252                     (REXEC_IGNOREPOS|REXEC_NOT_FIRST|REXEC_FAIL_ON_UNDERFLOW)))
253         {
254             /* no more iterations. Push return value etc */
255             SV *targ = cx->sb_targ;
256             SV *retval;
257
258             assert(cx->sb_strend >= s);
259             if(cx->sb_strend > s) {
260                  if (DO_UTF8(dstr) && !SvUTF8(targ))
261                       sv_catpvn_nomg_utf8_upgrade(dstr, s, cx->sb_strend - s, nsv);
262                  else
263                       sv_catpvn_nomg(dstr, s, cx->sb_strend - s);
264             }
265             if (RX_MATCH_TAINTED(rx)) /* run time pattern taint, eg locale */
266                 cx->sb_rxtainted |= SUBST_TAINT_PAT;
267
268             if (pm->op_pmflags & PMf_NONDESTRUCT) {
269                 retval = dstr;
270                 /* From here on down we're using the copy, and leaving the
271                    original untouched.  */
272                 targ = dstr;
273             }
274             else {
275                 SV_CHECK_THINKFIRST_COW_DROP(targ);
276                 if (isGV(targ)) Perl_croak_no_modify();
277                 SvPV_free(targ);
278                 SvPV_set(targ, SvPVX(dstr));
279                 SvCUR_set(targ, SvCUR(dstr));
280                 SvLEN_set(targ, SvLEN(dstr));
281                 if (DO_UTF8(dstr))
282                     SvUTF8_on(targ);
283                 SvPV_set(dstr, NULL);
284
285                 PL_tainted = 0;
286                 retval = sv_newmortal();
287                 sv_setiv(retval, saviters - 1);
288
289                 (void)SvPOK_only_UTF8(targ);
290             }
291
292             /* pop the original args (if any) to pp_subst(),
293              * then push the result */
294             if (pm->op_pmflags & PMf_CONST)
295                 rpp_popfree_1_NN(); /* pop replacement string */
296             if (pm->op_flags & OPf_STACKED)
297                 rpp_replace_1_1_NN(retval); /* pop LHS of =~ */
298             else
299                 rpp_push_1(retval);
300
301             /* update the taint state of various variables in
302              * preparation for final exit.
303              * See "how taint works": pp_subst() in pp_hot.c */
304             if (TAINTING_get) {
305                 if ((cx->sb_rxtainted & SUBST_TAINT_PAT) ||
306                     ((cx->sb_rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
307                                     == (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
308                 )
309                     (RX_MATCH_TAINTED_on(rx)); /* taint $1 et al */
310
311                 if (!(cx->sb_rxtainted & SUBST_TAINT_BOOLRET)
312                     && (cx->sb_rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_PAT))
313                 )
314                     SvTAINTED_on(retval);  /* taint return value */
315                 /* needed for mg_set below */
316                 TAINT_set(
317                     cBOOL(cx->sb_rxtainted &
318                           (SUBST_TAINT_STR|SUBST_TAINT_PAT|SUBST_TAINT_REPL))
319                 );
320
321                 /* sv_magic(), when adding magic (e.g.taint magic), also
322                  * recalculates any pos() magic, converting any byte offset
323                  * to utf8 offset. Make sure pos() is reset before this
324                  * happens rather than using the now invalid value (since
325                  * we've just replaced targ's pvx buffer with the
326                  * potentially shorter dstr buffer). Normally (i.e. in
327                  * non-taint cases), pos() gets removed a few lines later
328                  * with the SvSETMAGIC().
329                  */
330                 {
331                     MAGIC *mg;
332                     mg = mg_find_mglob(targ);
333                     if (mg) {
334                         MgBYTEPOS_set(mg, targ, SvPVX(targ), -1);
335                     }
336                 }
337
338                 SvTAINT(TARG);
339             }
340             /* PL_tainted must be correctly set for this mg_set */
341             SvSETMAGIC(TARG);
342             TAINT_NOT;
343
344             CX_LEAVE_SCOPE(cx);
345             CX_POPSUBST(cx);
346             CX_POP(cx);
347
348             PERL_ASYNC_CHECK();
349             return pm->op_next;
350             NOT_REACHED; /* NOTREACHED */
351         }
352         cx->sb_iters = saviters;
353     }
354
355     /* First iteration. The substitution expression hasn;'t been executed
356      * this time */
357
358     if (RX_MATCH_COPIED(rx) && RX_SUBBEG(rx) != orig) {
359         m = s;
360         s = orig;
361         assert(!RX_SUBOFFSET(rx));
362         cx->sb_orig = orig = RX_SUBBEG(rx);
363         s = orig + (m - s);
364         cx->sb_strend = s + (cx->sb_strend - m);
365     }
366     cx->sb_m = m = RX_OFFS_START(rx,0) + orig;
367     if (m > s) {
368         if (DO_UTF8(dstr) && !SvUTF8(cx->sb_targ))
369             sv_catpvn_nomg_utf8_upgrade(dstr, s, m - s, nsv);
370         else
371             sv_catpvn_nomg(dstr, s, m-s);
372     }
373     cx->sb_s = RX_OFFS_END(rx,0) + orig;
374     { /* Update the pos() information. */
375         SV * const sv
376             = (pm->op_pmflags & PMf_NONDESTRUCT) ? cx->sb_dstr : cx->sb_targ;
377         MAGIC *mg;
378
379         /* the string being matched against may no longer be a string,
380          * e.g. $_=0; s/.../$_++/ge */
381
382         if (!SvPOK(sv))
383             SvPV_force_nomg_nolen(sv);
384
385         if (!(mg = mg_find_mglob(sv))) {
386             mg = sv_magicext_mglob(sv);
387         }
388         MgBYTEPOS_set(mg, sv, SvPVX(sv), m - orig);
389     }
390     if (old != rx)
391         (void)ReREFCNT_inc(rx);
392     /* update the taint state of various variables in preparation
393      * for calling the code block.
394      * See "how taint works": pp_subst() in pp_hot.c */
395     if (TAINTING_get) {
396         if (RX_MATCH_TAINTED(rx)) /* run time pattern taint, eg locale */
397             cx->sb_rxtainted |= SUBST_TAINT_PAT;
398
399         if ((cx->sb_rxtainted & SUBST_TAINT_PAT) ||
400             ((cx->sb_rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
401                             == (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
402         )
403             (RX_MATCH_TAINTED_on(rx)); /* taint $1 et al */
404
405         if (cx->sb_iters > 1 && (cx->sb_rxtainted & 
406                         (SUBST_TAINT_STR|SUBST_TAINT_PAT|SUBST_TAINT_REPL)))
407             SvTAINTED_on((pm->op_pmflags & PMf_NONDESTRUCT)
408                          ? cx->sb_dstr : cx->sb_targ);
409         TAINT_NOT;
410     }
411     rxres_save(&cx->sb_rxres, rx);
412     PL_curpm = pm;
413     return pm->op_pmstashstartu.op_pmreplstart;
414 }
415
416
417 void
418 Perl_rxres_save(pTHX_ void **rsp, REGEXP *rx)
419 {
420     UV *p = (UV*)*rsp;
421     U32 i;
422
423     PERL_ARGS_ASSERT_RXRES_SAVE;
424     PERL_UNUSED_CONTEXT;
425
426     /* deal with regexp_paren_pair items */
427     if (!p || p[1] < RX_NPARENS(rx)) {
428 #ifdef PERL_ANY_COW
429         i = 7 + (RX_NPARENS(rx)+1) * 2;
430 #else
431         i = 6 + (RX_NPARENS(rx)+1) * 2;
432 #endif
433         if (!p)
434             Newx(p, i, UV);
435         else
436             Renew(p, i, UV);
437         *rsp = (void*)p;
438     }
439
440     /* what (if anything) to free on croak */
441     *p++ = PTR2UV(RX_MATCH_COPIED(rx) ? RX_SUBBEG(rx) : NULL);
442     RX_MATCH_COPIED_off(rx);
443     *p++ = RX_NPARENS(rx);
444
445 #ifdef PERL_ANY_COW
446     *p++ = PTR2UV(RX_SAVED_COPY(rx));
447     RX_SAVED_COPY(rx) = NULL;
448 #endif
449
450     *p++ = PTR2UV(RX_SUBBEG(rx));
451     *p++ = (UV)RX_SUBLEN(rx);
452     *p++ = (UV)RX_SUBOFFSET(rx);
453     *p++ = (UV)RX_SUBCOFFSET(rx);
454     for (i = 0; i <= RX_NPARENS(rx); ++i) {
455         *p++ = (UV)RX_OFFSp(rx)[i].start;
456         *p++ = (UV)RX_OFFSp(rx)[i].end;
457     }
458 }
459
460 static void
461 S_rxres_restore(pTHX_ void **rsp, REGEXP *rx)
462 {
463     UV *p = (UV*)*rsp;
464     U32 i;
465
466     PERL_ARGS_ASSERT_RXRES_RESTORE;
467     PERL_UNUSED_CONTEXT;
468
469     RX_MATCH_COPY_FREE(rx);
470     RX_MATCH_COPIED_set(rx, *p);
471     *p++ = 0;
472     RX_NPARENS(rx) = *p++;
473
474 #ifdef PERL_ANY_COW
475     if (RX_SAVED_COPY(rx))
476         SvREFCNT_dec (RX_SAVED_COPY(rx));
477     RX_SAVED_COPY(rx) = INT2PTR(SV*,*p);
478     *p++ = 0;
479 #endif
480
481     RX_SUBBEG(rx) = INT2PTR(char*,*p++);
482     RX_SUBLEN(rx) = (SSize_t)(*p++);
483     RX_SUBOFFSET(rx) = (Size_t)*p++;
484     RX_SUBCOFFSET(rx) = (SSize_t)*p++;
485     for (i = 0; i <= RX_NPARENS(rx); ++i) {
486         RX_OFFSp(rx)[i].start = (SSize_t)(*p++);
487         RX_OFFSp(rx)[i].end = (SSize_t)(*p++);
488     }
489 }
490
491 static void
492 S_rxres_free(pTHX_ void **rsp)
493 {
494     UV * const p = (UV*)*rsp;
495
496     PERL_ARGS_ASSERT_RXRES_FREE;
497     PERL_UNUSED_CONTEXT;
498
499     if (p) {
500         void *tmp = INT2PTR(char*,*p);
501 #ifdef PERL_POISON
502 #ifdef PERL_ANY_COW
503         U32 i = 9 + p[1] * 2;
504 #else
505         U32 i = 8 + p[1] * 2;
506 #endif
507 #endif
508
509 #ifdef PERL_ANY_COW
510         SvREFCNT_dec (INT2PTR(SV*,p[2]));
511 #endif
512 #ifdef PERL_POISON
513         PoisonFree(p, i, sizeof(UV));
514 #endif
515
516         Safefree(tmp);
517         Safefree(p);
518         *rsp = NULL;
519     }
520 }
521
522 #define FORM_NUM_BLANK (1<<30)
523 #define FORM_NUM_POINT (1<<29)
524
525 PP_wrapped(pp_formline, 0, 1)
526 {
527     dSP; dMARK; dORIGMARK;
528     SV * const tmpForm = *++MARK;
529     SV *formsv;             /* contains text of original format */
530     U32 *fpc;       /* format ops program counter */
531     char *t;        /* current append position in target string */
532     const char *f;          /* current position in format string */
533     I32 arg;
534     SV *sv = NULL; /* current item */
535     const char *item = NULL;/* string value of current item */
536     I32 itemsize  = 0;      /* length (chars) of item, possibly truncated */
537     I32 itembytes = 0;      /* as itemsize, but length in bytes */
538     I32 fieldsize = 0;      /* width of current field */
539     I32 lines = 0;          /* number of lines that have been output */
540     bool chopspace = (strchr(PL_chopset, ' ') != NULL); /* does $: have space */
541     const char *chophere = NULL; /* where to chop current item */
542     STRLEN linemark = 0;    /* pos of start of line in output */
543     NV value;
544     bool gotsome = FALSE;   /* seen at least one non-blank item on this line */
545     STRLEN len;             /* length of current sv */
546     STRLEN linemax;         /* estimate of output size in bytes */
547     bool item_is_utf8 = FALSE;
548     bool targ_is_utf8 = FALSE;
549     const char *fmt;
550     MAGIC *mg = NULL;
551     U8 *source;             /* source of bytes to append */
552     STRLEN to_copy;         /* how may bytes to append */
553     char trans;             /* what chars to translate */
554     bool copied_form = FALSE; /* have we duplicated the form? */
555
556     mg = doparseform(tmpForm);
557
558     fpc = (U32*)mg->mg_ptr;
559     /* the actual string the format was compiled from.
560      * with overload etc, this may not match tmpForm */
561     formsv = mg->mg_obj;
562
563
564     SvPV_force(PL_formtarget, len);
565     if (SvTAINTED(tmpForm) || SvTAINTED(formsv))
566         SvTAINTED_on(PL_formtarget);
567     if (DO_UTF8(PL_formtarget))
568         targ_is_utf8 = TRUE;
569     /* this is an initial estimate of how much output buffer space
570      * to allocate. It may be exceeded later */
571     linemax = (SvCUR(formsv) * (IN_BYTES ? 1 : 3) + 1);
572     t = SvGROW(PL_formtarget, len + linemax + 1);
573     /* XXX from now onwards, SvCUR(PL_formtarget) is invalid */
574     t += len;
575     f = SvPV_const(formsv, len);
576
577     for (;;) {
578         DEBUG_f( {
579             const char *name = "???";
580             arg = -1;
581             switch (*fpc) {
582             case FF_LITERAL:    arg = fpc[1]; name = "LITERAL"; break;
583             case FF_BLANK:      arg = fpc[1]; name = "BLANK";   break;
584             case FF_SKIP:       arg = fpc[1]; name = "SKIP";    break;
585             case FF_FETCH:      arg = fpc[1]; name = "FETCH";   break;
586             case FF_DECIMAL:    arg = fpc[1]; name = "DECIMAL"; break;
587
588             case FF_CHECKNL:    name = "CHECKNL";       break;
589             case FF_CHECKCHOP:  name = "CHECKCHOP";     break;
590             case FF_SPACE:      name = "SPACE";         break;
591             case FF_HALFSPACE:  name = "HALFSPACE";     break;
592             case FF_ITEM:       name = "ITEM";          break;
593             case FF_CHOP:       name = "CHOP";          break;
594             case FF_LINEGLOB:   name = "LINEGLOB";      break;
595             case FF_NEWLINE:    name = "NEWLINE";       break;
596             case FF_MORE:       name = "MORE";          break;
597             case FF_LINEMARK:   name = "LINEMARK";      break;
598             case FF_END:        name = "END";           break;
599             case FF_0DECIMAL:   name = "0DECIMAL";      break;
600             case FF_LINESNGL:   name = "LINESNGL";      break;
601             }
602             if (arg >= 0)
603                 PerlIO_printf(Perl_debug_log, "%-16s%ld\n", name, (long) arg);
604             else
605                 PerlIO_printf(Perl_debug_log, "%-16s\n", name);
606         } );
607         switch (*fpc++) {
608         case FF_LINEMARK: /* start (or end) of a line */
609             linemark = t - SvPVX(PL_formtarget);
610             lines++;
611             gotsome = FALSE;
612             break;
613
614         case FF_LITERAL: /* append <arg> literal chars */
615             to_copy = *fpc++;
616             source = (U8 *)f;
617             f += to_copy;
618             trans = '~';
619             item_is_utf8 = (targ_is_utf8)
620                            ? cBOOL(DO_UTF8(formsv))
621                            : cBOOL(SvUTF8(formsv));
622             goto append;
623
624         case FF_SKIP: /* skip <arg> chars in format */
625             f += *fpc++;
626             break;
627
628         case FF_FETCH: /* get next item and set field size to <arg> */
629             arg = *fpc++;
630             f += arg;
631             fieldsize = arg;
632
633             if (MARK < SP)
634                 sv = *++MARK;
635             else {
636                 sv = &PL_sv_no;
637                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "Not enough format arguments");
638             }
639             if (SvTAINTED(sv))
640                 SvTAINTED_on(PL_formtarget);
641             break;
642
643         case FF_CHECKNL: /* find max len of item (up to \n) that fits field */
644             {
645                 const char *s = item = SvPV_const(sv, len);
646                 const char *send = s + len;
647
648                 itemsize = 0;
649                 item_is_utf8 = DO_UTF8(sv);
650                 while (s < send) {
651                     if (!isCNTRL(*s))
652                         gotsome = TRUE;
653                     else if (*s == '\n')
654                         break;
655
656                     if (item_is_utf8)
657                         s += UTF8SKIP(s);
658                     else
659                         s++;
660                     itemsize++;
661                     if (itemsize == fieldsize)
662                         break;
663                 }
664                 itembytes = s - item;
665                 chophere = s;
666                 break;
667             }
668
669         case FF_CHECKCHOP: /* like CHECKNL, but up to highest split point */
670             {
671                 const char *s = item = SvPV_const(sv, len);
672                 const char *send = s + len;
673                 I32 size = 0;
674
675                 chophere = NULL;
676                 item_is_utf8 = DO_UTF8(sv);
677                 while (s < send) {
678                     /* look for a legal split position */
679                     if (isSPACE(*s)) {
680                         if (*s == '\r') {
681                             chophere = s;
682                             itemsize = size;
683                             break;
684                         }
685                         if (chopspace) {
686                             /* provisional split point */
687                             chophere = s;
688                             itemsize = size;
689                         }
690                         /* we delay testing fieldsize until after we've
691                          * processed the possible split char directly
692                          * following the last field char; so if fieldsize=3
693                          * and item="a b cdef", we consume "a b", not "a".
694                          * Ditto further down.
695                          */
696                         if (size == fieldsize)
697                             break;
698                     }
699                     else {
700                         if (size == fieldsize)
701                             break;
702                         if (strchr(PL_chopset, *s)) {
703                             /* provisional split point */
704                             /* for a non-space split char, we include
705                              * the split char; hence the '+1' */
706                             chophere = s + 1;
707                             itemsize = size + 1;
708                         }
709                         if (!isCNTRL(*s))
710                             gotsome = TRUE;
711                     }
712
713                     if (item_is_utf8)
714                         s += UTF8SKIP(s);
715                     else
716                         s++;
717                     size++;
718                 }
719                 if (!chophere || s == send) {
720                     chophere = s;
721                     itemsize = size;
722                 }
723                 itembytes = chophere - item;
724
725                 break;
726             }
727
728         case FF_SPACE: /* append padding space (diff of field, item size) */
729             arg = fieldsize - itemsize;
730             if (arg) {
731                 fieldsize -= arg;
732                 while (arg-- > 0)
733                     *t++ = ' ';
734             }
735             break;
736
737         case FF_HALFSPACE: /* like FF_SPACE, but only append half as many */
738             arg = fieldsize - itemsize;
739             if (arg) {
740                 arg /= 2;
741                 fieldsize -= arg;
742                 while (arg-- > 0)
743                     *t++ = ' ';
744             }
745             break;
746
747         case FF_ITEM: /* append a text item, while blanking ctrl chars */
748             to_copy = itembytes;
749             source = (U8 *)item;
750             trans = 1;
751             goto append;
752
753         case FF_CHOP: /* (for ^*) chop the current item */
754             if (sv != &PL_sv_no) {
755                 const char *s = chophere;
756                 if (!copied_form &&
757                     ((sv == tmpForm || SvSMAGICAL(sv))
758                      || (SvGMAGICAL(tmpForm) && !sv_only_taint_gmagic(tmpForm))) ) {
759                     /* sv and tmpForm are either the same SV, or magic might allow modification
760                        of tmpForm when sv is modified, so copy */
761                     SV *newformsv = sv_mortalcopy(formsv);
762                     U32 *new_compiled;
763
764                     f = SvPV_nolen(newformsv) + (f - SvPV_nolen(formsv));
765                     Newx(new_compiled, mg->mg_len / sizeof(U32), U32);
766                     memcpy(new_compiled, mg->mg_ptr, mg->mg_len);
767                     SAVEFREEPV(new_compiled);
768                     fpc = new_compiled + (fpc - (U32*)mg->mg_ptr);
769                     formsv = newformsv;
770
771                     copied_form = TRUE;
772                 }
773                 if (chopspace) {
774                     while (isSPACE(*s))
775                         s++;
776                 }
777                 if (SvPOKp(sv))
778                     sv_chop(sv,s);
779                 else
780                     /* tied, overloaded or similar strangeness.
781                      * Do it the hard way */
782                     sv_setpvn(sv, s, len - (s-item));
783                 SvSETMAGIC(sv);
784                 break;
785             }
786             /* FALLTHROUGH */
787
788         case FF_LINESNGL: /* process ^*  */
789             chopspace = 0;
790             /* FALLTHROUGH */
791
792         case FF_LINEGLOB: /* process @*  */
793             {
794                 const bool oneline = fpc[-1] == FF_LINESNGL;
795                 const char *s = item = SvPV_const(sv, len);
796                 const char *const send = s + len;
797
798                 item_is_utf8 = DO_UTF8(sv);
799                 chophere = s + len;
800                 if (!len)
801                     break;
802                 trans = 0;
803                 gotsome = TRUE;
804                 source = (U8 *) s;
805                 to_copy = len;
806                 while (s < send) {
807                     if (*s++ == '\n') {
808                         if (oneline) {
809                             to_copy = s - item - 1;
810                             chophere = s;
811                             break;
812                         } else {
813                             if (s == send) {
814                                 to_copy--;
815                             } else
816                                 lines++;
817                         }
818                     }
819                 }
820             }
821
822         append:
823             /* append to_copy bytes from source to PL_formstring.
824              * item_is_utf8 implies source is utf8.
825              * if trans, translate certain characters during the copy */
826             {
827                 U8 *tmp = NULL;
828                 STRLEN grow = 0;
829
830                 SvCUR_set(PL_formtarget,
831                           t - SvPVX_const(PL_formtarget));
832
833                 if (targ_is_utf8 && !item_is_utf8) {
834                     source = tmp = bytes_to_utf8(source, &to_copy);
835                     grow = to_copy;
836                 } else {
837                     if (item_is_utf8 && !targ_is_utf8) {
838                         U8 *s;
839                         /* Upgrade targ to UTF8, and then we reduce it to
840                            a problem we have a simple solution for.
841                            Don't need get magic.  */
842                         sv_utf8_upgrade_nomg(PL_formtarget);
843                         targ_is_utf8 = TRUE;
844                         /* re-calculate linemark */
845                         s = (U8*)SvPVX(PL_formtarget);
846                         /* the bytes we initially allocated to append the
847                          * whole line may have been gobbled up during the
848                          * upgrade, so allocate a whole new line's worth
849                          * for safety */
850                         grow = linemax;
851                         while (linemark--)
852                             s += UTF8_SAFE_SKIP(s,
853                                             (U8 *) SvEND(PL_formtarget));
854                         linemark = s - (U8*)SvPVX(PL_formtarget);
855                     }
856                     /* Easy. They agree.  */
857                     assert (item_is_utf8 == targ_is_utf8);
858                 }
859                 if (!trans)
860                     /* @* and ^* are the only things that can exceed
861                      * the linemax, so grow by the output size, plus
862                      * a whole new form's worth in case of any further
863                      * output */
864                     grow = linemax + to_copy;
865                 if (grow)
866                     SvGROW(PL_formtarget, SvCUR(PL_formtarget) + grow + 1);
867                 t = SvPVX(PL_formtarget) + SvCUR(PL_formtarget);
868
869                 Copy(source, t, to_copy, char);
870                 if (trans) {
871                     /* blank out ~ or control chars, depending on trans.
872                      * works on bytes not chars, so relies on not
873                      * matching utf8 continuation bytes */
874                     U8 *s = (U8*)t;
875                     U8 *send = s + to_copy;
876                     while (s < send) {
877                         const int ch = *s;
878                         if (trans == '~' ? (ch == '~') : isCNTRL(ch))
879                             *s = ' ';
880                         s++;
881                     }
882                 }
883
884                 t += to_copy;
885                 SvCUR_set(PL_formtarget, SvCUR(PL_formtarget) + to_copy);
886                 if (tmp)
887                     Safefree(tmp);
888                 break;
889             }
890
891         case FF_0DECIMAL: /* like FF_DECIMAL but for 0### */
892             arg = *fpc++;
893             fmt = (const char *)
894                 ((arg & FORM_NUM_POINT) ? "%#0*.*" NVff : "%0*.*" NVff);
895             goto ff_dec;
896
897         case FF_DECIMAL: /* do @##, ^##, where <arg>=(precision|flags) */
898             arg = *fpc++;
899             fmt = (const char *)
900                 ((arg & FORM_NUM_POINT) ? "%#*.*" NVff : "%*.*" NVff);
901         ff_dec:
902             /* If the field is marked with ^ and the value is undefined,
903                blank it out. */
904             if ((arg & FORM_NUM_BLANK) && !SvOK(sv)) {
905                 arg = fieldsize;
906                 while (arg--)
907                     *t++ = ' ';
908                 break;
909             }
910             gotsome = TRUE;
911             value = SvNV(sv);
912             /* overflow evidence */
913             if (num_overflow(value, fieldsize, arg)) {
914                 arg = fieldsize;
915                 while (arg--)
916                     *t++ = '#';
917                 break;
918             }
919             /* Formats aren't yet marked for locales, so assume "yes". */
920             {
921                 Size_t max = SvLEN(PL_formtarget) - (t - SvPVX(PL_formtarget));
922                 int len;
923                 arg &= ~(FORM_NUM_POINT|FORM_NUM_BLANK);
924 #ifdef USE_QUADMATH
925                 {
926                     int len;
927                     if (!quadmath_format_valid(fmt))
928                         Perl_croak_nocontext("panic: quadmath invalid format \"%s\"", fmt);
929                     WITH_LC_NUMERIC_SET_TO_NEEDED(
930                         len = quadmath_snprintf(t, max, fmt, (int) fieldsize,
931                                                (int) arg, value);
932                     );
933                     if (len == -1)
934                         Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", fmt);
935                 }
936 #else
937                 /* we generate fmt ourselves so it is safe */
938                 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
939                 len = my_snprintf(t, max, fmt, (int) fieldsize, (int) arg, value);
940                 GCC_DIAG_RESTORE_STMT;
941 #endif
942                 PERL_MY_SNPRINTF_POST_GUARD(len, max);
943             }
944             t += fieldsize;
945             break;
946
947         case FF_NEWLINE: /* delete trailing spaces, then append \n */
948             f++;
949             while (t-- > (SvPVX(PL_formtarget) + linemark) && *t == ' ') ;
950             t++;
951             *t++ = '\n';
952             break;
953
954         case FF_BLANK: /* for arg==0: do '~'; for arg>0 : do '~~' */
955             arg = *fpc++;
956             if (gotsome) {
957                 if (arg) {              /* repeat until fields exhausted? */
958                     fpc--;
959                     goto end;
960                 }
961             }
962             else {
963                 t = SvPVX(PL_formtarget) + linemark;
964                 lines--;
965             }
966             break;
967
968         case FF_MORE: /* replace long end of string with '...' */
969             {
970                 const char *s = chophere;
971                 const char *send = item + len;
972                 if (chopspace) {
973                     while (isSPACE(*s) && (s < send))
974                         s++;
975                 }
976                 if (s < send) {
977                     char *s1;
978                     arg = fieldsize - itemsize;
979                     if (arg) {
980                         fieldsize -= arg;
981                         while (arg-- > 0)
982                             *t++ = ' ';
983                     }
984                     s1 = t - 3;
985                     if (strBEGINs(s1,"   ")) {
986                         while (s1 > SvPVX_const(PL_formtarget) && isSPACE(s1[-1]))
987                             s1--;
988                     }
989                     *s1++ = '.';
990                     *s1++ = '.';
991                     *s1++ = '.';
992                 }
993                 break;
994             }
995
996         case FF_END: /* tidy up, then return */
997         end:
998             assert(t < SvPVX_const(PL_formtarget) + SvLEN(PL_formtarget));
999             *t = '\0';
1000             SvCUR_set(PL_formtarget, t - SvPVX_const(PL_formtarget));
1001             if (targ_is_utf8)
1002                 SvUTF8_on(PL_formtarget);
1003             FmLINES(PL_formtarget) += lines;
1004             SP = ORIGMARK;
1005             if (fpc[-1] == FF_BLANK)
1006                 RETURNOP(cLISTOP->op_first);
1007             else
1008                 RETPUSHYES;
1009         }
1010     }
1011 }
1012
1013 /* also used for: pp_mapstart() */
1014 PP(pp_grepstart)
1015 {
1016     /* See the code comments at the start of pp_grepwhile() and
1017      * pp_mapwhile() for an explanation of how the stack is used
1018      * during a grep or map.
1019      */
1020     SV *src;
1021     SV **svp;
1022
1023     if (PL_stack_base + TOPMARK == PL_stack_sp) {
1024         (void)POPMARK;
1025         if (GIMME_V == G_SCALAR) {
1026             rpp_extend(1);
1027             *++PL_stack_sp = &PL_sv_zero;
1028         }
1029         return PL_op->op_next->op_next;
1030     }
1031     svp = PL_stack_base + TOPMARK + 1;
1032     PUSHMARK(svp);                              /* push dst */
1033     PUSHMARK(svp);                              /* push src */
1034     ENTER_with_name("grep");                                    /* enter outer scope */
1035
1036     SAVETMPS;
1037     SAVE_DEFSV;
1038     ENTER_with_name("grep_item");                                       /* enter inner scope */
1039     SAVEVPTR(PL_curpm);
1040
1041     src = PL_stack_base[TOPMARK];
1042     if (SvPADTMP(src)) {
1043         SV *newsrc = sv_mortalcopy(src);
1044         PL_tmps_floor++;
1045         PL_stack_base[TOPMARK] = newsrc;
1046 #ifdef PERL_RC_STACK
1047         SvREFCNT_inc_simple_void_NN(newsrc);
1048         SvREFCNT_dec(src);
1049 #endif
1050         src = newsrc;
1051     }
1052     SvTEMP_off(src);
1053     DEFSV_set(src);
1054
1055     if (PL_op->op_type == OP_MAPSTART)
1056         PUSHMARK(PL_stack_sp);                  /* push top */
1057     return cLOGOPx(PL_op->op_next)->op_other;
1058 }
1059
1060 /* pp_grepwhile() lives in pp_hot.c */
1061
1062 PP(pp_mapwhile)
1063 {
1064     /* Understanding the stack during a map.
1065      *
1066      * 'map expr, args' is implemented in the form of
1067      *
1068      *     grepstart; // which handles map too
1069      *     do {
1070      *          expr;
1071      *          mapwhile;
1072      *     } while (args);
1073      *
1074      * The stack examples below are in the form of 'perl -Ds' output,
1075      * where any stack element indexed by PL_markstack_ptr[i] has a star
1076      * just to the right of it.  In addition, the corresponding i value
1077      * is displayed under the indexed stack element.
1078      *
1079      * On entry to mapwhile, the stack looks like this:
1080      *
1081      *      =>   *  A1..An  X1  *  X2..Xn  C  *  R1..Rn  *  E1..En
1082      *      [-3]           [-2]          [-1]        [0]
1083      *
1084      * where:
1085      *   A1..An   Accumulated results from all previous iterations of expr
1086      *   X1..Xn   Random garbage
1087      *   C        The current (just processed) arg, still aliased to $_.
1088      *   R1..Rn   The args remaining to be processed.
1089      *   E1..En   the (list) result of the just-executed map expression.
1090      *
1091      * Note that it is easiest to think of stack marks [-1] and [-2] as both
1092      * being one too high, and so it would make more sense to have had the
1093      * marks like this:
1094      *
1095      *      =>   *  A1..An  *  X1..Xn  *  C  R1..Rn  *  E1..En
1096      *      [-3]       [-2]       [-1]           [0]
1097      *
1098      * where the stack is divided neatly into 4 groups:
1099      *   - accumulated results
1100      *   - discards and/or holes proactively created for later result storage
1101      *   - being, or yet to be, processed,
1102      *   - results of last expr
1103      * But off-by-one is the way it is currently, and it works as long as
1104      * we keep it consistent and bear it in mind.
1105      *
1106      * pp_mapwhile() does the following:
1107      *
1108      * - If there isn't enough space in the X1..Xn zone to insert the
1109      *   expression results, grow the stack and shift up everything above C.
1110      * - move E1..En to just above An
1111      * - at the same time, manipulate the tmps stack so that temporaries
1112      *   from executing expr can be freed without prematurely freeing
1113      *   E1..En.
1114      * - if on last iteration, pop all the marks, reset the stack pointer
1115      *   and update the return args based on caller context.
1116      * - else alias $_ to the next arg.
1117      *
1118      */
1119
1120     const U8 gimme = GIMME_V;
1121     SSize_t items = (PL_stack_sp - PL_stack_base) - TOPMARK; /* how many new items */
1122     SSize_t count;
1123     SSize_t shift;
1124     SV** src;
1125     SV** dst;
1126
1127 #ifdef PERL_RC_STACK
1128     /* for ref-counted stack, we need to account for the currently-aliased
1129      * stack element, as it might (or might not) get over-written when
1130      * copying values from the expr to the end of the accumulated results
1131      * section of the list. By RC--ing and zeroing out the stack entry, we
1132      * ensure consistent handling.
1133      */
1134     dst = PL_stack_base + PL_markstack_ptr[-1];
1135     SvREFCNT_dec_NN(*dst);
1136     *dst = NULL;
1137 #endif
1138
1139     /* first, move source pointer to the next item in the source list */
1140     ++PL_markstack_ptr[-1];
1141
1142     /* if there are new items, push them into the destination list */
1143     if (items && gimme != G_VOID) {
1144         /* might need to make room back there first */
1145         if (items > PL_markstack_ptr[-1] - PL_markstack_ptr[-2]) {
1146             /* XXX this implementation is very pessimal because the stack
1147              * is repeatedly extended for every set of items.  Is possible
1148              * to do this without any stack extension or copying at all
1149              * by maintaining a separate list over which the map iterates
1150              * (like foreach does). --gsar */
1151
1152             /* everything in the stack after the destination list moves
1153              * towards the end the stack by the amount of room needed */
1154             shift = items - (PL_markstack_ptr[-1] - PL_markstack_ptr[-2]);
1155
1156             /* items to shift up (accounting for the moved source pointer) */
1157             count = (PL_stack_sp - PL_stack_base) - (PL_markstack_ptr[-1] - 1);
1158
1159             /* This optimization is by Ben Tilly and it does
1160              * things differently from what Sarathy (gsar)
1161              * is describing.  The downside of this optimization is
1162              * that leaves "holes" (uninitialized and hopefully unused areas)
1163              * to the Perl stack, but on the other hand this
1164              * shouldn't be a problem.  If Sarathy's idea gets
1165              * implemented, this optimization should become
1166              * irrelevant.  --jhi */
1167             if (shift < count)
1168                 shift = count; /* Avoid shifting too often --Ben Tilly */
1169
1170             rpp_extend(shift);
1171             src = PL_stack_sp;
1172             PL_stack_sp += shift;
1173             dst = PL_stack_sp;
1174             PL_markstack_ptr[-1] += shift;
1175             *PL_markstack_ptr += shift;
1176             while (count--)
1177                 *dst-- = *src--;
1178 #ifdef PERL_RC_STACK
1179             /* zero out the hole just created, so that on a
1180              * reference-counted stack, so that the just-shifted SVs
1181              * aren't counted twice.
1182              */
1183             Zero(src+1, (dst-src), SV*);
1184 #endif
1185         }
1186         /* copy the new items down to the destination list */
1187         PL_markstack_ptr[-2] += items;
1188         dst = PL_stack_base + PL_markstack_ptr[-2] - 1;
1189         if (gimme == G_LIST) {
1190             /* add returned items to the collection (making mortal copies
1191              * if necessary), then clear the current temps stack frame
1192              * *except* for those items. We do this splicing the items
1193              * into the start of the tmps frame (so some items may be on
1194              * the tmps stack twice), then moving PL_tmps_floor above
1195              * them, then freeing the frame. That way, the only tmps that
1196              * accumulate over iterations are the return values for map.
1197              * We have to do to this way so that everything gets correctly
1198              * freed if we die during the map.
1199              */
1200             SSize_t tmpsbase;
1201             SSize_t i = items;
1202             /* make space for the slice */
1203             EXTEND_MORTAL(items);
1204             tmpsbase = PL_tmps_floor + 1;
1205             Move(PL_tmps_stack + tmpsbase,
1206                  PL_tmps_stack + tmpsbase + items,
1207                  PL_tmps_ix - PL_tmps_floor,
1208                  SV*);
1209             PL_tmps_ix += items;
1210
1211             while (i-- > 0) {
1212 #ifdef PERL_RC_STACK
1213                 SV *sv = *PL_stack_sp;
1214                 assert(!*dst); /* not overwriting ptrs to refcnted SVs */
1215                 if (!SvTEMP(sv)) {
1216                     sv = sv_mortalcopy(sv);
1217                     /* NB - don't really need the mortalising above.
1218                      * A simple copy would suffice */
1219                     *dst-- = sv;
1220                     SvREFCNT_inc_simple_void_NN(sv);
1221                     rpp_popfree_1_NN();
1222                 }
1223                 else {
1224                     *dst-- = sv;
1225                     PL_stack_sp--;
1226                 }
1227
1228 #else
1229                 SV *sv = *PL_stack_sp--;
1230                 if (!SvTEMP(sv))
1231                     sv = sv_mortalcopy(sv);
1232                 *dst-- = sv;
1233 #endif
1234                 PL_tmps_stack[tmpsbase++] = SvREFCNT_inc_simple(sv);
1235             }
1236             /* clear the stack frame except for the items */
1237             PL_tmps_floor += items;
1238             FREETMPS;
1239             /* FREETMPS may have cleared the TEMP flag on some of the items */
1240             i = items;
1241             while (i-- > 0)
1242                 SvTEMP_on(PL_tmps_stack[--tmpsbase]);
1243         }
1244         else {
1245             /* scalar context: we don't care about which values map returns
1246              * (we use undef here). And so we certainly don't want to do mortal
1247              * copies of meaningless values. */
1248             *(dst - items + 1) = &PL_sv_undef;
1249             rpp_popfree_to(PL_stack_sp - items);
1250             FREETMPS;
1251         }
1252     }
1253     else {
1254         if (items) {
1255             assert(gimme == G_VOID);
1256             rpp_popfree_to(PL_stack_sp - items);
1257         }
1258         FREETMPS;
1259     }
1260     LEAVE_with_name("grep_item");                                       /* exit inner scope */
1261
1262     /* All done yet? */
1263     if (PL_markstack_ptr[-1] > TOPMARK) {
1264
1265         (void)POPMARK;                          /* pop top */
1266         LEAVE_with_name("grep");                                        /* exit outer scope */
1267         (void)POPMARK;                          /* pop src */
1268         items = --*PL_markstack_ptr - PL_markstack_ptr[-1];
1269         (void)POPMARK;                          /* pop dst */
1270         SV **svp = PL_stack_base + POPMARK; /* pop original mark */
1271         if (gimme == G_LIST)
1272             svp += items;
1273         rpp_popfree_to(svp);
1274         if (gimme == G_SCALAR) {
1275             dTARGET;
1276             TARGi(items, 1);
1277             /* XXX is the extend necessary? */
1278             rpp_xpush_1(targ);
1279         }
1280         return NORMAL;
1281     }
1282     else {
1283         SV *src;
1284
1285         ENTER_with_name("grep_item");                                   /* enter inner scope */
1286         SAVEVPTR(PL_curpm);
1287
1288         /* set $_ to the new source item */
1289         src = PL_stack_base[PL_markstack_ptr[-1]];
1290         if (SvPADTMP(src)) {
1291             SV *newsrc = sv_mortalcopy(src);
1292             PL_stack_base[PL_markstack_ptr[-1]] = newsrc;
1293 #ifdef PERL_RC_STACK
1294             SvREFCNT_inc_simple_void_NN(newsrc);
1295             SvREFCNT_dec(src);
1296 #endif
1297             src = newsrc;
1298         }
1299         if (SvPADTMP(src)) {
1300             src = sv_mortalcopy(src);
1301         }
1302         SvTEMP_off(src);
1303         DEFSV_set(src);
1304
1305         return cLOGOP->op_other;
1306     }
1307 }
1308
1309 /* Range stuff. */
1310
1311 PP(pp_range)
1312 {
1313     dTARG;
1314     if (GIMME_V == G_LIST)
1315         return NORMAL;
1316     GETTARGET;
1317     if (SvTRUE_NN(targ))
1318         return cLOGOP->op_other;
1319     else
1320         return NORMAL;
1321 }
1322
1323
1324 PP_wrapped(pp_flip,((GIMME_V == G_LIST) ? 0 : 1), 0)
1325 {
1326     dSP;
1327
1328     if (GIMME_V == G_LIST) {
1329         RETURNOP(cLOGOPx(cUNOP->op_first)->op_other);
1330     }
1331     else {
1332         dTOPss;
1333         SV * const targ = PAD_SV(PL_op->op_targ);
1334         int flip = 0;
1335
1336         if (PL_op->op_private & OPpFLIP_LINENUM) {
1337             if (GvIO(PL_last_in_gv)) {
1338                 flip = SvIV(sv) == (IV)IoLINES(GvIOp(PL_last_in_gv));
1339             }
1340             else {
1341                 GV * const gv = gv_fetchpvs(".", GV_ADD|GV_NOTQUAL, SVt_PV);
1342                 if (gv && GvSV(gv))
1343                     flip = SvIV(sv) == SvIV(GvSV(gv));
1344             }
1345         } else {
1346             flip = SvTRUE_NN(sv);
1347         }
1348         if (flip) {
1349             sv_setiv(PAD_SV(cUNOP->op_first->op_targ), 1);
1350             if (PL_op->op_flags & OPf_SPECIAL) {
1351                 sv_setiv(targ, 1);
1352                 SETs(targ);
1353                 RETURN;
1354             }
1355             else {
1356                 sv_setiv(targ, 0);
1357                 SP--;
1358                 RETURNOP(cLOGOPx(cUNOP->op_first)->op_other);
1359             }
1360         }
1361         SvPVCLEAR(TARG);
1362         SETs(targ);
1363         RETURN;
1364     }
1365 }
1366
1367
1368 /* This code tries to decide if "$left .. $right" should use the
1369    magical string increment, or if the range is numeric. Initially,
1370    an exception was made for *any* string beginning with "0" (see
1371    [#18165], AMS 20021031), but now that is only applied when the
1372    string's length is also >1 - see the rules now documented in
1373    perlop [#133695] */
1374
1375 #define RANGE_IS_NUMERIC(left,right) ( \
1376         SvNIOKp(left)  || (SvOK(left)  && !SvPOKp(left))  || \
1377         SvNIOKp(right) || (SvOK(right) && !SvPOKp(right)) || \
1378         (((!SvOK(left) && SvOK(right)) || ((!SvOK(left) || \
1379           looks_like_number(left)) && SvPOKp(left) \
1380           && !(*SvPVX_const(left) == '0' && SvCUR(left)>1 ) )) \
1381          && (!SvOK(right) || looks_like_number(right))))
1382
1383
1384 PP_wrapped(pp_flop, (GIMME_V == G_LIST) ? 2 : 1, 0)
1385 {
1386     dSP;
1387
1388     if (GIMME_V == G_LIST) {
1389         dPOPPOPssrl;
1390
1391         SvGETMAGIC(left);
1392         SvGETMAGIC(right);
1393
1394         if (RANGE_IS_NUMERIC(left,right)) {
1395             IV i, j, n;
1396             if ((SvOK(left) && !SvIOK(left) && SvNV_nomg(left) < IV_MIN) ||
1397                 (SvOK(right) && (SvIOK(right)
1398                                  ? SvIsUV(right) && SvUV(right) > IV_MAX
1399                                  : SvNV_nomg(right) > (NV) IV_MAX)))
1400                 DIE(aTHX_ "Range iterator outside integer range");
1401             i = SvIV_nomg(left);
1402             j = SvIV_nomg(right);
1403             if (j >= i) {
1404                 /* Dance carefully around signed max. */
1405                 bool overflow = (i <= 0 && j > SSize_t_MAX + i - 1);
1406                 if (!overflow) {
1407                     n = j - i + 1;
1408                     /* The wraparound of signed integers is undefined
1409                      * behavior, but here we aim for count >=1, and
1410                      * negative count is just wrong. */
1411                     if (n < 1
1412 #if IVSIZE > Size_t_size
1413                         || n > SSize_t_MAX
1414 #endif
1415                         )
1416                         overflow = TRUE;
1417                 }
1418                 if (overflow)
1419                     Perl_croak(aTHX_ "Out of memory during list extend");
1420                 EXTEND_MORTAL(n);
1421                 EXTEND(SP, n);
1422             }
1423             else
1424                 n = 0;
1425             while (n--) {
1426                 SV * const sv = sv_2mortal(newSViv(i));
1427                 PUSHs(sv);
1428                 if (n) /* avoid incrementing above IV_MAX */
1429                     i++;
1430             }
1431         }
1432         else {
1433             STRLEN len, llen;
1434             const char * const lpv = SvPV_nomg_const(left, llen);
1435             const char * const tmps = SvPV_nomg_const(right, len);
1436
1437             SV *sv = newSVpvn_flags(lpv, llen, SvUTF8(left)|SVs_TEMP);
1438             if (DO_UTF8(right) && IN_UNI_8_BIT)
1439                 len = sv_len_utf8_nomg(right);
1440             while (!SvNIOKp(sv) && SvCUR(sv) <= len) {
1441                 XPUSHs(sv);
1442                 if (strEQ(SvPVX_const(sv),tmps))
1443                     break;
1444                 sv = sv_2mortal(newSVsv(sv));
1445                 sv_inc(sv);
1446             }
1447         }
1448     }
1449     else {
1450         dTOPss;
1451         SV * const targ = PAD_SV(cUNOP->op_first->op_targ);
1452         int flop = 0;
1453         sv_inc(targ);
1454
1455         if (PL_op->op_private & OPpFLIP_LINENUM) {
1456             if (GvIO(PL_last_in_gv)) {
1457                 flop = SvIV(sv) == (IV)IoLINES(GvIOp(PL_last_in_gv));
1458             }
1459             else {
1460                 GV * const gv = gv_fetchpvs(".", GV_ADD|GV_NOTQUAL, SVt_PV);
1461                 if (gv && GvSV(gv)) flop = SvIV(sv) == SvIV(GvSV(gv));
1462             }
1463         }
1464         else {
1465             flop = SvTRUE_NN(sv);
1466         }
1467
1468         if (flop) {
1469             sv_setiv(PAD_SV(cUNOPx(cUNOP->op_first)->op_first->op_targ), 0);
1470             sv_catpvs(targ, "E0");
1471         }
1472         SETs(targ);
1473     }
1474
1475     RETURN;
1476 }
1477
1478
1479 /* Control. */
1480
1481 static const char * const context_name[] = {
1482     "pseudo-block",
1483     NULL, /* CXt_WHEN never actually needs "block" */
1484     NULL, /* CXt_BLOCK never actually needs "block" */
1485     NULL, /* CXt_GIVEN never actually needs "block" */
1486     NULL, /* CXt_LOOP_PLAIN never actually needs "loop" */
1487     NULL, /* CXt_LOOP_LAZYIV never actually needs "loop" */
1488     NULL, /* CXt_LOOP_LAZYSV never actually needs "loop" */
1489     NULL, /* CXt_LOOP_LIST never actually needs "loop" */
1490     NULL, /* CXt_LOOP_ARY never actually needs "loop" */
1491     "subroutine",
1492     "format",
1493     "eval",
1494     "substitution",
1495     "defer block",
1496 };
1497
1498 STATIC I32
1499 S_dopoptolabel(pTHX_ const char *label, STRLEN len, U32 flags)
1500 {
1501     I32 i;
1502
1503     PERL_ARGS_ASSERT_DOPOPTOLABEL;
1504
1505     for (i = cxstack_ix; i >= 0; i--) {
1506         const PERL_CONTEXT * const cx = &cxstack[i];
1507         switch (CxTYPE(cx)) {
1508         case CXt_EVAL:
1509             if(CxTRY(cx))
1510                 continue;
1511             /* FALLTHROUGH */
1512         case CXt_SUBST:
1513         case CXt_SUB:
1514         case CXt_FORMAT:
1515         case CXt_NULL:
1516             /* diag_listed_as: Exiting subroutine via %s */
1517             Perl_ck_warner(aTHX_ packWARN(WARN_EXITING), "Exiting %s via %s",
1518                            context_name[CxTYPE(cx)], OP_NAME(PL_op));
1519             if (CxTYPE(cx) == CXt_NULL) /* sort BLOCK */
1520                 return -1;
1521             break;
1522         case CXt_LOOP_PLAIN:
1523         case CXt_LOOP_LAZYIV:
1524         case CXt_LOOP_LAZYSV:
1525         case CXt_LOOP_LIST:
1526         case CXt_LOOP_ARY:
1527           {
1528             STRLEN cx_label_len = 0;
1529             U32 cx_label_flags = 0;
1530             const char *cx_label = CxLABEL_len_flags(cx, &cx_label_len, &cx_label_flags);
1531             if (!cx_label || !(
1532                     ( (cx_label_flags & SVf_UTF8) != (flags & SVf_UTF8) ) ?
1533                         (flags & SVf_UTF8)
1534                             ? (bytes_cmp_utf8(
1535                                         (const U8*)cx_label, cx_label_len,
1536                                         (const U8*)label, len) == 0)
1537                             : (bytes_cmp_utf8(
1538                                         (const U8*)label, len,
1539                                         (const U8*)cx_label, cx_label_len) == 0)
1540                     : (len == cx_label_len && ((cx_label == label)
1541                                     || memEQ(cx_label, label, len))) )) {
1542                 DEBUG_l(Perl_deb(aTHX_ "(poptolabel(): skipping label at cx=%ld %s)\n",
1543                         (long)i, cx_label));
1544                 continue;
1545             }
1546             DEBUG_l( Perl_deb(aTHX_ "(poptolabel(): found label at cx=%ld %s)\n", (long)i, label));
1547             return i;
1548           }
1549         }
1550     }
1551     return i;
1552 }
1553
1554 /*
1555 =for apidoc_section $callback
1556 =for apidoc dowantarray
1557
1558 Implements the deprecated L<perlapi/C<GIMME>>.
1559
1560 =cut
1561 */
1562
1563 U8
1564 Perl_dowantarray(pTHX)
1565 {
1566     const U8 gimme = block_gimme();
1567     return (gimme == G_VOID) ? G_SCALAR : gimme;
1568 }
1569
1570 /* note that this function has mostly been superseded by Perl_gimme_V */
1571
1572 U8
1573 Perl_block_gimme(pTHX)
1574 {
1575     const I32 cxix = dopopto_cursub();
1576     U8 gimme;
1577     if (cxix < 0)
1578         return G_VOID;
1579
1580     gimme = (cxstack[cxix].blk_gimme & G_WANT);
1581     if (!gimme)
1582         Perl_croak(aTHX_ "panic: bad gimme: %d\n", gimme);
1583     return gimme;
1584 }
1585
1586 /*
1587 =for apidoc is_lvalue_sub
1588
1589 Returns non-zero if the sub calling this function is being called in an lvalue
1590 context.  Returns 0 otherwise.
1591
1592 =cut
1593 */
1594
1595 I32
1596 Perl_is_lvalue_sub(pTHX)
1597 {
1598     const I32 cxix = dopopto_cursub();
1599     assert(cxix >= 0);  /* We should only be called from inside subs */
1600
1601     if (CxLVAL(cxstack + cxix) && CvLVALUE(cxstack[cxix].blk_sub.cv))
1602         return CxLVAL(cxstack + cxix);
1603     else
1604         return 0;
1605 }
1606
1607 /* only used by cx_pushsub() */
1608 I32
1609 Perl_was_lvalue_sub(pTHX)
1610 {
1611     const I32 cxix = dopoptosub(cxstack_ix-1);
1612     assert(cxix >= 0);  /* We should only be called from inside subs */
1613
1614     if (CxLVAL(cxstack + cxix) && CvLVALUE(cxstack[cxix].blk_sub.cv))
1615         return CxLVAL(cxstack + cxix);
1616     else
1617         return 0;
1618 }
1619
1620 STATIC I32
1621 S_dopoptosub_at(pTHX_ const PERL_CONTEXT *cxstk, I32 startingblock)
1622 {
1623     I32 i;
1624
1625     PERL_ARGS_ASSERT_DOPOPTOSUB_AT;
1626 #ifndef DEBUGGING
1627     PERL_UNUSED_CONTEXT;
1628 #endif
1629
1630     for (i = startingblock; i >= 0; i--) {
1631         const PERL_CONTEXT * const cx = &cxstk[i];
1632         switch (CxTYPE(cx)) {
1633         default:
1634             continue;
1635         case CXt_SUB:
1636             /* in sub foo { /(?{...})/ }, foo ends up on the CX stack
1637              * twice; the first for the normal foo() call, and the second
1638              * for a faked up re-entry into the sub to execute the
1639              * code block. Hide this faked entry from the world. */
1640             if (cx->cx_type & CXp_SUB_RE_FAKE)
1641                 continue;
1642             DEBUG_l( Perl_deb(aTHX_ "(dopoptosub_at(): found sub at cx=%ld)\n", (long)i));
1643             return i;
1644
1645         case CXt_EVAL:
1646             if (CxTRY(cx))
1647                 continue;
1648             DEBUG_l( Perl_deb(aTHX_ "(dopoptosub_at(): found sub at cx=%ld)\n", (long)i));
1649             return i;
1650
1651         case CXt_FORMAT:
1652             DEBUG_l( Perl_deb(aTHX_ "(dopoptosub_at(): found sub at cx=%ld)\n", (long)i));
1653             return i;
1654         }
1655     }
1656     return i;
1657 }
1658
1659 STATIC I32
1660 S_dopoptoeval(pTHX_ I32 startingblock)
1661 {
1662     I32 i;
1663     for (i = startingblock; i >= 0; i--) {
1664         const PERL_CONTEXT *cx = &cxstack[i];
1665         switch (CxTYPE(cx)) {
1666         default:
1667             continue;
1668         case CXt_EVAL:
1669             DEBUG_l( Perl_deb(aTHX_ "(dopoptoeval(): found eval at cx=%ld)\n", (long)i));
1670             return i;
1671         }
1672     }
1673     return i;
1674 }
1675
1676 STATIC I32
1677 S_dopoptoloop(pTHX_ I32 startingblock)
1678 {
1679     I32 i;
1680     for (i = startingblock; i >= 0; i--) {
1681         const PERL_CONTEXT * const cx = &cxstack[i];
1682         switch (CxTYPE(cx)) {
1683         case CXt_EVAL:
1684             if(CxTRY(cx))
1685                 continue;
1686             /* FALLTHROUGH */
1687         case CXt_SUBST:
1688         case CXt_SUB:
1689         case CXt_FORMAT:
1690         case CXt_NULL:
1691             /* diag_listed_as: Exiting subroutine via %s */
1692             Perl_ck_warner(aTHX_ packWARN(WARN_EXITING), "Exiting %s via %s",
1693                            context_name[CxTYPE(cx)], OP_NAME(PL_op));
1694             if ((CxTYPE(cx)) == CXt_NULL) /* sort BLOCK */
1695                 return -1;
1696             break;
1697         case CXt_LOOP_PLAIN:
1698         case CXt_LOOP_LAZYIV:
1699         case CXt_LOOP_LAZYSV:
1700         case CXt_LOOP_LIST:
1701         case CXt_LOOP_ARY:
1702             DEBUG_l( Perl_deb(aTHX_ "(dopoptoloop(): found loop at cx=%ld)\n", (long)i));
1703             return i;
1704         }
1705     }
1706     return i;
1707 }
1708
1709 /* find the next GIVEN or FOR (with implicit $_) loop context block */
1710
1711 STATIC I32
1712 S_dopoptogivenfor(pTHX_ I32 startingblock)
1713 {
1714     I32 i;
1715     for (i = startingblock; i >= 0; i--) {
1716         const PERL_CONTEXT *cx = &cxstack[i];
1717         switch (CxTYPE(cx)) {
1718         default:
1719             continue;
1720         case CXt_GIVEN:
1721             DEBUG_l( Perl_deb(aTHX_ "(dopoptogivenfor(): found given at cx=%ld)\n", (long)i));
1722             return i;
1723         case CXt_LOOP_PLAIN:
1724             assert(!(cx->cx_type & CXp_FOR_DEF));
1725             break;
1726         case CXt_LOOP_LAZYIV:
1727         case CXt_LOOP_LAZYSV:
1728         case CXt_LOOP_LIST:
1729         case CXt_LOOP_ARY:
1730             if (cx->cx_type & CXp_FOR_DEF) {
1731                 DEBUG_l( Perl_deb(aTHX_ "(dopoptogivenfor(): found foreach at cx=%ld)\n", (long)i));
1732                 return i;
1733             }
1734         }
1735     }
1736     return i;
1737 }
1738
1739 STATIC I32
1740 S_dopoptowhen(pTHX_ I32 startingblock)
1741 {
1742     I32 i;
1743     for (i = startingblock; i >= 0; i--) {
1744         const PERL_CONTEXT *cx = &cxstack[i];
1745         switch (CxTYPE(cx)) {
1746         default:
1747             continue;
1748         case CXt_WHEN:
1749             DEBUG_l( Perl_deb(aTHX_ "(dopoptowhen(): found when at cx=%ld)\n", (long)i));
1750             return i;
1751         }
1752     }
1753     return i;
1754 }
1755
1756 /* dounwind(): pop all contexts above (but not including) cxix.
1757  * Note that it clears the savestack frame associated with each popped
1758  * context entry, but doesn't free any temps.
1759  * It does a cx_popblock() of the last frame that it pops, and leaves
1760  * cxstack_ix equal to cxix.
1761  */
1762
1763 void
1764 Perl_dounwind(pTHX_ I32 cxix)
1765 {
1766     if (!PL_curstackinfo) /* can happen if die during thread cloning */
1767         return;
1768
1769     while (cxstack_ix > cxix) {
1770         PERL_CONTEXT *cx = CX_CUR();
1771
1772         CX_DEBUG(cx, "UNWIND");
1773         /* Note: we don't need to restore the base context info till the end. */
1774
1775         CX_LEAVE_SCOPE(cx);
1776
1777         switch (CxTYPE(cx)) {
1778         case CXt_SUBST:
1779             CX_POPSUBST(cx);
1780             /* CXt_SUBST is not a block context type, so skip the
1781              * cx_popblock(cx) below */
1782             if (cxstack_ix == cxix + 1) {
1783                 cxstack_ix--;
1784                 return;
1785             }
1786             break;
1787         case CXt_SUB:
1788             cx_popsub(cx);
1789             break;
1790         case CXt_EVAL:
1791             cx_popeval(cx);
1792             break;
1793         case CXt_LOOP_PLAIN:
1794         case CXt_LOOP_LAZYIV:
1795         case CXt_LOOP_LAZYSV:
1796         case CXt_LOOP_LIST:
1797         case CXt_LOOP_ARY:
1798             cx_poploop(cx);
1799             break;
1800         case CXt_WHEN:
1801             cx_popwhen(cx);
1802             break;
1803         case CXt_GIVEN:
1804             cx_popgiven(cx);
1805             break;
1806         case CXt_BLOCK:
1807         case CXt_NULL:
1808         case CXt_DEFER:
1809             /* these two don't have a POPFOO() */
1810             break;
1811         case CXt_FORMAT:
1812             cx_popformat(cx);
1813             break;
1814         }
1815         if (cxstack_ix == cxix + 1) {
1816             cx_popblock(cx);
1817         }
1818         cxstack_ix--;
1819     }
1820
1821 }
1822
1823
1824 /* Like rpp_popfree_to(), but takes an offset rather than a pointer,
1825  * and frees everything above ix appropriately, *regardless* of the
1826  * refcountedness of the stack. If necessary it removes any split stack.
1827  * Intended for use during exit() and die() and similar.
1828 */
1829 void
1830 Perl_rpp_obliterate_stack_to(pTHX_ I32 ix)
1831 {
1832 #ifdef PERL_RC_STACK
1833     I32 nonrc_base = PL_curstackinfo->si_stack_nonrc_base;
1834     assert(ix >= 0);
1835     assert(ix <= PL_stack_sp - PL_stack_base);
1836     assert(nonrc_base <= PL_stack_sp - PL_stack_base + 1);
1837
1838     if (nonrc_base && nonrc_base > ix) {
1839         /* abandon any non-refcounted stuff */
1840         PL_stack_sp = PL_stack_base + nonrc_base - 1;
1841         /* and mark the stack as fully refcounted again */
1842         PL_curstackinfo->si_stack_nonrc_base = 0;
1843     }
1844
1845     if (rpp_stack_is_rc())
1846         rpp_popfree_to(PL_stack_base + ix);
1847     else
1848         PL_stack_sp = PL_stack_base + ix;
1849 #else
1850     PL_stack_sp = PL_stack_base + ix;
1851 #endif
1852
1853 }
1854
1855
1856 void
1857 Perl_qerror(pTHX_ SV *err)
1858 {
1859     PERL_ARGS_ASSERT_QERROR;
1860     if (err!=NULL) {
1861         if (PL_in_eval) {
1862             if (PL_in_eval & EVAL_KEEPERR) {
1863                     Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "\t(in cleanup) %" SVf,
1864                                                         SVfARG(err));
1865             }
1866             else {
1867                 sv_catsv(ERRSV, err);
1868             }
1869         }
1870         else if (PL_errors)
1871             sv_catsv(PL_errors, err);
1872         else
1873             Perl_warn(aTHX_ "%" SVf, SVfARG(err));
1874
1875         if (PL_parser) {
1876             ++PL_parser->error_count;
1877         }
1878     }
1879
1880     if ( PL_parser && (err == NULL ||
1881          PL_parser->error_count >= PERL_STOP_PARSING_AFTER_N_ERRORS)
1882     ) {
1883         const char * const name = OutCopFILE(PL_curcop);
1884         SV * errsv = NULL;
1885         U8 raw_error_count = PERL_PARSE_ERROR_COUNT(PL_parser->error_count);
1886
1887         if (PL_in_eval) {
1888             errsv = ERRSV;
1889         }
1890
1891         if (err == NULL) {
1892             abort_execution(errsv, name);
1893         }
1894         else
1895         if (raw_error_count >= PERL_STOP_PARSING_AFTER_N_ERRORS) {
1896             if (errsv) {
1897                 Perl_croak(aTHX_ "%" SVf "%s has too many errors.\n",
1898                     SVfARG(errsv), name);
1899             } else {
1900                 Perl_croak(aTHX_ "%s has too many errors.\n", name);
1901             }
1902         }
1903     }
1904 }
1905
1906
1907 /* pop a CXt_EVAL context and in addition, if it was a require then
1908  * based on action:
1909  *     0: do nothing extra;
1910  *     1: undef  $INC{$name}; croak "$name did not return a true value";
1911  *     2: delete $INC{$name}; croak "$errsv: Compilation failed in require"
1912  */
1913
1914 static void
1915 S_pop_eval_context_maybe_croak(pTHX_ PERL_CONTEXT *cx, SV *errsv, int action)
1916 {
1917     SV  *namesv = NULL; /* init to avoid dumb compiler warning */
1918     bool do_croak;
1919
1920     CX_LEAVE_SCOPE(cx);
1921     do_croak = action && (CxOLD_OP_TYPE(cx) == OP_REQUIRE);
1922     if (do_croak) {
1923         /* keep namesv alive after cx_popeval() */
1924         namesv = cx->blk_eval.old_namesv;
1925         cx->blk_eval.old_namesv = NULL;
1926         sv_2mortal(namesv);
1927     }
1928     cx_popeval(cx);
1929     cx_popblock(cx);
1930     CX_POP(cx);
1931
1932     if (do_croak) {
1933         const char *fmt;
1934         HV *inc_hv = GvHVn(PL_incgv);
1935
1936         if (action == 1) {
1937             (void)hv_delete_ent(inc_hv, namesv, G_DISCARD, 0);
1938             fmt = "%" SVf " did not return a true value";
1939             errsv = namesv;
1940         }
1941         else {
1942             (void)hv_store_ent(inc_hv, namesv, &PL_sv_undef, 0);
1943             fmt = "%" SVf "Compilation failed in require";
1944             if (!errsv)
1945                 errsv = newSVpvs_flags("Unknown error\n", SVs_TEMP);
1946         }
1947
1948         Perl_croak(aTHX_ fmt, SVfARG(errsv));
1949     }
1950 }
1951
1952
1953 /* die_unwind(): this is the final destination for the various croak()
1954  * functions. If we're in an eval, unwind the context and other stacks
1955  * back to the top-most CXt_EVAL and set $@ to msv; otherwise print msv
1956  * to STDERR and initiate an exit. Note that if the CXt_EVAL popped back
1957  * to is a require the exception will be rethrown, as requires don't
1958  * actually trap exceptions.
1959  */
1960
1961 void
1962 Perl_die_unwind(pTHX_ SV *msv)
1963 {
1964     SV *exceptsv = msv;
1965     U8 in_eval = PL_in_eval;
1966     PERL_ARGS_ASSERT_DIE_UNWIND;
1967
1968     if (in_eval) {
1969         I32 cxix;
1970
1971         /* We need to keep this SV alive through all the stack unwinding
1972          * and FREETMPSing below, while ensuing that it doesn't leak
1973          * if we call out to something which then dies (e.g. sub STORE{die}
1974          * when unlocalising a tied var). So we do a dance with
1975          * mortalising and SAVEFREEing.
1976          */
1977         if (PL_phase == PERL_PHASE_DESTRUCT) {
1978             exceptsv = sv_mortalcopy(exceptsv);
1979         } else {
1980             exceptsv = sv_2mortal(SvREFCNT_inc_simple_NN(exceptsv));
1981         }
1982
1983         /*
1984          * Historically, perl used to set ERRSV ($@) early in the die
1985          * process and rely on it not getting clobbered during unwinding.
1986          * That sucked, because it was liable to get clobbered, so the
1987          * setting of ERRSV used to emit the exception from eval{} has
1988          * been moved to much later, after unwinding (see just before
1989          * JMPENV_JUMP below).  However, some modules were relying on the
1990          * early setting, by examining $@ during unwinding to use it as
1991          * a flag indicating whether the current unwinding was caused by
1992          * an exception.  It was never a reliable flag for that purpose,
1993          * being totally open to false positives even without actual
1994          * clobberage, but was useful enough for production code to
1995          * semantically rely on it.
1996          *
1997          * We'd like to have a proper introspective interface that
1998          * explicitly describes the reason for whatever unwinding
1999          * operations are currently in progress, so that those modules
2000          * work reliably and $@ isn't further overloaded.  But we don't
2001          * have one yet.  In its absence, as a stopgap measure, ERRSV is
2002          * now *additionally* set here, before unwinding, to serve as the
2003          * (unreliable) flag that it used to.
2004          *
2005          * This behaviour is temporary, and should be removed when a
2006          * proper way to detect exceptional unwinding has been developed.
2007          * As of 2010-12, the authors of modules relying on the hack
2008          * are aware of the issue, because the modules failed on
2009          * perls 5.13.{1..7} which had late setting of $@ without this
2010          * early-setting hack.
2011          */
2012         if (!(in_eval & EVAL_KEEPERR)) {
2013             /* remove any read-only/magic from the SV, so we don't
2014                get infinite recursion when setting ERRSV */
2015             SANE_ERRSV();
2016             sv_setsv_flags(ERRSV, exceptsv,
2017                         (SV_GMAGIC|SV_DO_COW_SVSETSV|SV_NOSTEAL));
2018         }
2019
2020         if (in_eval & EVAL_KEEPERR) {
2021             Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "\t(in cleanup) %" SVf,
2022                            SVfARG(exceptsv));
2023         }
2024
2025         while ((cxix = dopoptoeval(cxstack_ix)) < 0
2026                && PL_curstackinfo->si_prev)
2027         {
2028             dounwind(-1);
2029             rpp_obliterate_stack_to(0);
2030             POPSTACK;
2031         }
2032
2033         if (cxix >= 0) {
2034             PERL_CONTEXT *cx;
2035             U8 gimme;
2036             JMPENV *restartjmpenv;
2037             OP *restartop;
2038
2039             if (cxix < cxstack_ix)
2040                 dounwind(cxix);
2041
2042             cx = CX_CUR();
2043             assert(CxTYPE(cx) == CXt_EVAL);
2044
2045             rpp_obliterate_stack_to(cx->blk_oldsp);
2046
2047             /* return false to the caller of eval */
2048             gimme = cx->blk_gimme;
2049             if (gimme == G_SCALAR)
2050                 rpp_xpush_IMM(&PL_sv_undef);
2051
2052             restartjmpenv = cx->blk_eval.cur_top_env;
2053             restartop     = cx->blk_eval.retop;
2054
2055             /* We need a FREETMPS here to avoid late-called destructors
2056              * clobbering $@ *after* we set it below, e.g.
2057              *    sub DESTROY { eval { die "X" } }
2058              *    eval { my $x = bless []; die $x = 0, "Y" };
2059              *    is($@, "Y")
2060              * Here the clearing of the $x ref mortalises the anon array,
2061              * which needs to be freed *before* $& is set to "Y",
2062              * otherwise it gets overwritten with "X".
2063              *
2064              * However, the FREETMPS will clobber exceptsv, so preserve it
2065              * on the savestack for now.
2066              */
2067             SAVEFREESV(SvREFCNT_inc_simple_NN(exceptsv));
2068             FREETMPS;
2069             /* now we're about to pop the savestack, so re-mortalise it */
2070             sv_2mortal(SvREFCNT_inc_simple_NN(exceptsv));
2071
2072             /* Note that unlike pp_entereval, pp_require isn't supposed to
2073              * trap errors. So if we're a require, after we pop the
2074              * CXt_EVAL that pp_require pushed, rethrow the error with
2075              * croak(exceptsv). This is all handled by the call below when
2076              * action == 2.
2077              */
2078             S_pop_eval_context_maybe_croak(aTHX_ cx, exceptsv, 2);
2079
2080             if (!(in_eval & EVAL_KEEPERR)) {
2081                 SANE_ERRSV();
2082                 sv_setsv(ERRSV, exceptsv);
2083             }
2084             PL_restartjmpenv = restartjmpenv;
2085             PL_restartop = restartop;
2086             JMPENV_JUMP(3);
2087             NOT_REACHED; /* NOTREACHED */
2088         }
2089     }
2090
2091     write_to_stderr(exceptsv);
2092     my_failure_exit();
2093     NOT_REACHED; /* NOTREACHED */
2094 }
2095
2096
2097 PP(pp_xor)
2098 {
2099     SV *left  = PL_stack_sp[0];
2100     SV *right = PL_stack_sp[-1];
2101     rpp_replace_2_IMM_NN(SvTRUE_NN(left) != SvTRUE_NN(right)
2102                     ? &PL_sv_yes
2103                     : &PL_sv_no);
2104     return NORMAL;
2105 }
2106
2107
2108 /*
2109
2110 =for apidoc_section $CV
2111
2112 =for apidoc caller_cx
2113
2114 The XSUB-writer's equivalent of L<caller()|perlfunc/caller>.  The
2115 returned C<PERL_CONTEXT> structure can be interrogated to find all the
2116 information returned to Perl by C<caller>.  Note that XSUBs don't get a
2117 stack frame, so C<caller_cx(0, NULL)> will return information for the
2118 immediately-surrounding Perl code.
2119
2120 This function skips over the automatic calls to C<&DB::sub> made on the
2121 behalf of the debugger.  If the stack frame requested was a sub called by
2122 C<DB::sub>, the return value will be the frame for the call to
2123 C<DB::sub>, since that has the correct line number/etc. for the call
2124 site.  If I<dbcxp> is non-C<NULL>, it will be set to a pointer to the
2125 frame for the sub call itself.
2126
2127 =cut
2128 */
2129
2130 const PERL_CONTEXT *
2131 Perl_caller_cx(pTHX_ I32 count, const PERL_CONTEXT **dbcxp)
2132 {
2133     I32 cxix = dopopto_cursub();
2134     const PERL_CONTEXT *cx;
2135     const PERL_CONTEXT *ccstack = cxstack;
2136     const PERL_SI *top_si = PL_curstackinfo;
2137
2138     for (;;) {
2139         /* we may be in a higher stacklevel, so dig down deeper */
2140         while (cxix < 0 && top_si->si_type != PERLSI_MAIN) {
2141             top_si = top_si->si_prev;
2142             ccstack = top_si->si_cxstack;
2143             cxix = dopoptosub_at(ccstack, top_si->si_cxix);
2144         }
2145         if (cxix < 0)
2146             return NULL;
2147         /* caller() should not report the automatic calls to &DB::sub */
2148         if (PL_DBsub && GvCV(PL_DBsub) && cxix >= 0 &&
2149                 ccstack[cxix].blk_sub.cv == GvCV(PL_DBsub))
2150             count++;
2151         if (!count--)
2152             break;
2153         cxix = dopoptosub_at(ccstack, cxix - 1);
2154     }
2155
2156     cx = &ccstack[cxix];
2157     if (dbcxp) *dbcxp = cx;
2158
2159     if (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT) {
2160         const I32 dbcxix = dopoptosub_at(ccstack, cxix - 1);
2161         /* We expect that ccstack[dbcxix] is CXt_SUB, anyway, the
2162            field below is defined for any cx. */
2163         /* caller() should not report the automatic calls to &DB::sub */
2164         if (PL_DBsub && GvCV(PL_DBsub) && dbcxix >= 0 && ccstack[dbcxix].blk_sub.cv == GvCV(PL_DBsub))
2165             cx = &ccstack[dbcxix];
2166     }
2167
2168     return cx;
2169 }
2170
2171 PP_wrapped(pp_caller, MAXARG, 0)
2172 {
2173     dSP;
2174     const PERL_CONTEXT *cx;
2175     const PERL_CONTEXT *dbcx;
2176     U8 gimme = GIMME_V;
2177     const HEK *stash_hek;
2178     I32 count = 0;
2179     bool has_arg = MAXARG && TOPs;
2180     const COP *lcop;
2181
2182     if (MAXARG) {
2183       if (has_arg)
2184         count = POPi;
2185       else (void)POPs;
2186     }
2187
2188     cx = caller_cx(count + cBOOL(PL_op->op_private & OPpOFFBYONE), &dbcx);
2189     if (!cx) {
2190         if (gimme != G_LIST) {
2191             EXTEND(SP, 1);
2192             RETPUSHUNDEF;
2193         }
2194         RETURN;
2195     }
2196
2197     /* populate @DB::args ? */
2198     if (CxTYPE(cx) == CXt_SUB && CxHASARGS(cx)
2199         && CopSTASH_eq(PL_curcop, PL_debstash))
2200     {
2201         /* slot 0 of the pad contains the original @_ */
2202         AV * const ary = MUTABLE_AV(AvARRAY(MUTABLE_AV(
2203                             PadlistARRAY(CvPADLIST(cx->blk_sub.cv))[
2204                                 cx->blk_sub.olddepth+1]))[0]);
2205         const SSize_t off = AvARRAY(ary) - AvALLOC(ary);
2206
2207         Perl_init_dbargs(aTHX);
2208
2209         if (AvMAX(PL_dbargs) < AvFILLp(ary) + off)
2210             av_extend(PL_dbargs, AvFILLp(ary) + off);
2211
2212         /* Alias elements of @_ to @DB::args */
2213         for (SSize_t i = AvFILLp(ary) + off; i >= 0; i--) {
2214             SV* sv = AvALLOC(ary)[i];
2215             /* for a shifted @_, the elements between AvALLOC and AvARRAY
2216              * point to old SVs which may have been freed or even
2217              * reallocated in the meantime. In the interests of
2218              * reconstructing the original @_ before any shifting, use
2219              * those old values, even at the risk of them being wrong.
2220              * But if the ref count is 0, then don't use it because
2221              * further assigning that value anywhere will panic.
2222              * Of course there's nothing to stop a RC != 0 SV being
2223              * subsequently freed, but hopefully people quickly copy the
2224              * contents of @DB::args before doing anything else.
2225              */
2226             if (sv && (SvREFCNT(sv) == 0 || SvIS_FREED(sv)))
2227                 sv = NULL;
2228             AvARRAY(PL_dbargs)[i] = sv;
2229         }
2230         AvFILLp(PL_dbargs) = AvFILLp(ary) + off;
2231     }
2232
2233     CX_DEBUG(cx, "CALLER");
2234     assert(CopSTASH(cx->blk_oldcop));
2235     stash_hek = SvTYPE(CopSTASH(cx->blk_oldcop)) == SVt_PVHV
2236       ? HvNAME_HEK((HV*)CopSTASH(cx->blk_oldcop))
2237       : NULL;
2238     if (gimme != G_LIST) {
2239         EXTEND(SP, 1);
2240         if (!stash_hek)
2241             PUSHs(&PL_sv_undef);
2242         else {
2243             dTARGET;
2244             sv_sethek(TARG, stash_hek);
2245             PUSHs(TARG);
2246         }
2247         RETURN;
2248     }
2249
2250     EXTEND(SP, 11);
2251
2252     if (!stash_hek)
2253         PUSHs(&PL_sv_undef);
2254     else {
2255         dTARGET;
2256         sv_sethek(TARG, stash_hek);
2257         PUSHTARG;
2258     }
2259     mPUSHs(newSVpv(OutCopFILE(cx->blk_oldcop), 0));
2260     lcop = closest_cop(cx->blk_oldcop, OpSIBLING(cx->blk_oldcop),
2261                        cx->blk_sub.retop, TRUE);
2262     if (!lcop)
2263         lcop = cx->blk_oldcop;
2264     mPUSHu(CopLINE(lcop));
2265     if (!has_arg)
2266         RETURN;
2267     if (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT) {
2268         /* So is ccstack[dbcxix]. */
2269         if (CvHASGV(dbcx->blk_sub.cv)) {
2270             PUSHs(cv_name(dbcx->blk_sub.cv, 0, 0));
2271             PUSHs(boolSV(CxHASARGS(cx)));
2272         }
2273         else {
2274             PUSHs(newSVpvs_flags("(unknown)", SVs_TEMP));
2275             PUSHs(boolSV(CxHASARGS(cx)));
2276         }
2277     }
2278     else {
2279         PUSHs(newSVpvs_flags("(eval)", SVs_TEMP));
2280         PUSHs(&PL_sv_zero);
2281     }
2282     gimme = cx->blk_gimme;
2283     if (gimme == G_VOID)
2284         PUSHs(&PL_sv_undef);
2285     else
2286         PUSHs(boolSV((gimme & G_WANT) == G_LIST));
2287     if (CxTYPE(cx) == CXt_EVAL) {
2288         /* eval STRING */
2289         if (CxOLD_OP_TYPE(cx) == OP_ENTEREVAL) {
2290             SV *cur_text = cx->blk_eval.cur_text;
2291             if (SvCUR(cur_text) >= 2) {
2292                 PUSHs(newSVpvn_flags(SvPVX(cur_text), SvCUR(cur_text)-2,
2293                                      SvUTF8(cur_text)|SVs_TEMP));
2294             }
2295             else {
2296                 /* I think this is will always be "", but be sure */
2297                 PUSHs(sv_2mortal(newSVsv(cur_text)));
2298             }
2299
2300             PUSHs(&PL_sv_no);
2301         }
2302         /* require */
2303         else if (cx->blk_eval.old_namesv) {
2304             mPUSHs(newSVsv(cx->blk_eval.old_namesv));
2305             PUSHs(&PL_sv_yes);
2306         }
2307         /* eval BLOCK (try blocks have old_namesv == 0) */
2308         else {
2309             PUSHs(&PL_sv_undef);
2310             PUSHs(&PL_sv_undef);
2311         }
2312     }
2313     else {
2314         PUSHs(&PL_sv_undef);
2315         PUSHs(&PL_sv_undef);
2316     }
2317
2318     mPUSHi(CopHINTS_get(cx->blk_oldcop));
2319     {
2320         SV * mask ;
2321         char *old_warnings = cx->blk_oldcop->cop_warnings;
2322
2323         if  (old_warnings == pWARN_NONE)
2324             mask = newSVpvn(WARN_NONEstring, WARNsize) ;
2325         else if (old_warnings == pWARN_STD && (PL_dowarn & G_WARN_ON) == 0)
2326             mask = &PL_sv_undef ;
2327         else if (old_warnings == pWARN_ALL ||
2328                   (old_warnings == pWARN_STD && PL_dowarn & G_WARN_ON)) {
2329             mask = newSVpvn(WARN_ALLstring, WARNsize) ;
2330         }
2331         else
2332             mask = newSVpvn(old_warnings, RCPV_LEN(old_warnings));
2333         mPUSHs(mask);
2334     }
2335
2336     PUSHs(cx->blk_oldcop->cop_hints_hash ?
2337           sv_2mortal(newRV_noinc(MUTABLE_SV(cop_hints_2hv(cx->blk_oldcop, 0))))
2338           : &PL_sv_undef);
2339     RETURN;
2340 }
2341
2342
2343 PP_wrapped(pp_reset, MAXARG, 0)
2344 {
2345     dSP;
2346     const char * tmps;
2347     STRLEN len = 0;
2348     if (MAXARG < 1 || (!TOPs && !POPs)) {
2349         EXTEND(SP, 1);
2350         tmps = NULL, len = 0;
2351     }
2352     else
2353         tmps = SvPVx_const(POPs, len);
2354     sv_resetpvn(tmps, len, CopSTASH(PL_curcop));
2355     PUSHs(&PL_sv_yes);
2356     RETURN;
2357 }
2358
2359 /* like pp_nextstate, but used instead when the debugger is active */
2360
2361 PP(pp_dbstate)
2362 {
2363     PL_curcop = (COP*)PL_op;
2364     TAINT_NOT;          /* Each statement is presumed innocent */
2365     rpp_popfree_to_NN(PL_stack_base + CX_CUR()->blk_oldsp);
2366     FREETMPS;
2367
2368     PERL_ASYNC_CHECK();
2369
2370     if (PL_op->op_flags & OPf_SPECIAL /* breakpoint */
2371             || PL_DBsingle_iv || PL_DBsignal_iv || PL_DBtrace_iv)
2372     {
2373         PERL_CONTEXT *cx;
2374         const U8 gimme = G_LIST;
2375         GV * const gv = PL_DBgv;
2376         CV * cv = NULL;
2377
2378         if (gv && isGV_with_GP(gv))
2379             cv = GvCV(gv);
2380
2381         if (!cv || (!CvROOT(cv) && !CvXSUB(cv)))
2382             DIE(aTHX_ "No DB::DB routine defined");
2383
2384         if (CvDEPTH(cv) >= 1 && !(PL_debug & DEBUG_DB_RECURSE_FLAG))
2385             /* don't do recursive DB::DB call */
2386             return NORMAL;
2387
2388         if (CvISXSUB(cv)) {
2389             ENTER;
2390             SAVEI32(PL_debug);
2391             PL_debug = 0;
2392             /* I suspect that saving the stack position is no longer
2393              * required. It was added in 5.001 by:
2394              * 
2395              *     NETaa13155: &DB::DB left trash on the stack.
2396              *     From: Thomas Koenig
2397              *     Files patched: lib/perl5db.pl pp_ctl.c
2398              *      The call by pp_dbstate() to &DB::DB left trash on the
2399              *      stack.  It now calls DB in list context, and DB returns
2400              *      ().
2401              *
2402              * but the details of what bug it fixed are long lost to
2403              * history.  SAVESTACK_POS() doesn't work well with stacks
2404              * which may be split into partly reference-counted and partly
2405              * not halves, so skip it and hope it doesn't cause any
2406              * problems.
2407              */
2408 #ifndef PERL_RC_STACK
2409             SAVESTACK_POS();
2410 #endif
2411             SAVETMPS;
2412             PUSHMARK(PL_stack_sp);
2413             rpp_invoke_xs(cv);
2414             FREETMPS;
2415             LEAVE;
2416             return NORMAL;
2417         }
2418         else {
2419 #ifdef PERL_RC_STACK
2420             assert(!PL_curstackinfo->si_stack_nonrc_base);
2421 #endif
2422             cx = cx_pushblock(CXt_SUB, gimme, PL_stack_sp, PL_savestack_ix);
2423             cx_pushsub(cx, cv, PL_op->op_next, 0);
2424             /* OP_DBSTATE's op_private holds hint bits rather than
2425              * the lvalue-ish flags seen in OP_ENTERSUB. So cancel
2426              * any CxLVAL() flags that have now been mis-calculated */
2427             cx->blk_u16 = 0;
2428
2429             SAVEI32(PL_debug);
2430             PL_debug = 0;
2431             /* see comment above about SAVESTACK_POS */
2432 #ifndef PERL_RC_STACK
2433             SAVESTACK_POS();
2434 #endif
2435             CvDEPTH(cv)++;
2436             if (CvDEPTH(cv) >= 2)
2437                 pad_push(CvPADLIST(cv), CvDEPTH(cv));
2438             PAD_SET_CUR_NOSAVE(CvPADLIST(cv), CvDEPTH(cv));
2439             return CvSTART(cv);
2440         }
2441     }
2442     else
2443         return NORMAL;
2444 }
2445
2446
2447 PP(pp_enter)
2448 {
2449     U8 gimme = GIMME_V;
2450
2451     (void)cx_pushblock(CXt_BLOCK, gimme, PL_stack_sp, PL_savestack_ix);
2452     return NORMAL;
2453 }
2454
2455
2456 PP(pp_leave)
2457 {
2458     PERL_CONTEXT *cx;
2459     SV **oldsp;
2460     U8 gimme;
2461
2462     cx = CX_CUR();
2463     assert(CxTYPE(cx) == CXt_BLOCK);
2464
2465     if (PL_op->op_flags & OPf_SPECIAL)
2466         /* fake block should preserve $1 et al; e.g.  /(...)/ while ...; */
2467         cx->blk_oldpm = PL_curpm;
2468
2469     oldsp = PL_stack_base + cx->blk_oldsp;
2470     gimme = cx->blk_gimme;
2471
2472     if (gimme == G_VOID)
2473         rpp_popfree_to_NN(oldsp);
2474     else
2475         leave_adjust_stacks(oldsp, oldsp, gimme,
2476                                 PL_op->op_private & OPpLVALUE ? 3 : 1);
2477
2478     CX_LEAVE_SCOPE(cx);
2479     cx_popblock(cx);
2480     CX_POP(cx);
2481
2482     return NORMAL;
2483 }
2484
2485 static bool
2486 S_outside_integer(pTHX_ SV *sv)
2487 {
2488   if (SvOK(sv)) {
2489     const NV nv = SvNV_nomg(sv);
2490     if (Perl_isinfnan(nv))
2491       return TRUE;
2492 #ifdef NV_PRESERVES_UV
2493     if (nv < (NV)IV_MIN || nv > (NV)IV_MAX)
2494       return TRUE;
2495 #else
2496     if (nv <= (NV)IV_MIN)
2497       return TRUE;
2498     if ((nv > 0) &&
2499         ((nv > (NV)UV_MAX ||
2500           SvUV_nomg(sv) > (UV)IV_MAX)))
2501       return TRUE;
2502 #endif
2503   }
2504   return FALSE;
2505 }
2506
2507 PP(pp_enteriter)
2508 {
2509     dMARK;
2510     PERL_CONTEXT *cx;
2511     const U8 gimme = GIMME_V;
2512     void *itervarp; /* GV or pad slot of the iteration variable */
2513     SV   *itersave; /* the old var in the iterator var slot */
2514     U8 cxflags = 0;
2515
2516     if (PL_op->op_targ) {                        /* "my" variable */
2517         itervarp = &PAD_SVl(PL_op->op_targ);
2518         itersave = *(SV**)itervarp;
2519         assert(itersave);
2520         if (PL_op->op_private & OPpLVAL_INTRO) {        /* for my $x (...) */
2521             /* the SV currently in the pad slot is never live during
2522              * iteration (the slot is always aliased to one of the items)
2523              * so it's always stale */
2524             SvPADSTALE_on(itersave);
2525         }
2526         SvREFCNT_inc_simple_void_NN(itersave);
2527         cxflags = CXp_FOR_PAD;
2528     }
2529     else {
2530         SV * const sv = *PL_stack_sp;
2531         itervarp = (void *)sv;
2532         if (LIKELY(isGV(sv))) {         /* symbol table variable */
2533             itersave = GvSV(sv);
2534             SvREFCNT_inc_simple_void(itersave);
2535             cxflags = CXp_FOR_GV;
2536             if (PL_op->op_private & OPpITER_DEF)
2537                 cxflags |= CXp_FOR_DEF;
2538         }
2539         else {                          /* LV ref: for \$foo (...) */
2540             assert(SvTYPE(sv) == SVt_PVMG);
2541             assert(SvMAGIC(sv));
2542             assert(SvMAGIC(sv)->mg_type == PERL_MAGIC_lvref);
2543             itersave = NULL;
2544             cxflags = CXp_FOR_LVREF;
2545         }
2546         /* we transfer ownership of 1 ref count of itervarp from the stack
2547          * to the CX entry, so no SvREFCNT_dec() needed */
2548         (void)rpp_pop_1_norc();
2549     }
2550     /* OPpITER_DEF (implicit $_) should only occur with a GV iter var */
2551     assert((cxflags & CXp_FOR_GV) || !(PL_op->op_private & OPpITER_DEF));
2552
2553     /* Note that this context is initially set as CXt_NULL. Further on
2554      * down it's changed to one of the CXt_LOOP_*. Before it's changed,
2555      * there mustn't be anything in the blk_loop substruct that requires
2556      * freeing or undoing, in case we die in the meantime. And vice-versa.
2557      */
2558     cx = cx_pushblock(cxflags, gimme, MARK, PL_savestack_ix);
2559     cx_pushloop_for(cx, itervarp, itersave);
2560
2561     if (PL_op->op_flags & OPf_STACKED) {
2562         /* OPf_STACKED implies either a single array: for(@), with a
2563          * single AV on the stack, or a range: for (1..5), with 1 and 5 on
2564          * the stack */
2565         SV *maybe_ary = *PL_stack_sp;
2566         if (SvTYPE(maybe_ary) != SVt_PVAV) {
2567             /* range */
2568             SV* sv = PL_stack_sp[-1];
2569             SV * const right = maybe_ary;
2570             if (UNLIKELY(cxflags & CXp_FOR_LVREF))
2571                 DIE(aTHX_ "Assigned value is not a reference");
2572             SvGETMAGIC(sv);
2573             SvGETMAGIC(right);
2574             if (RANGE_IS_NUMERIC(sv,right)) {
2575                 cx->cx_type |= CXt_LOOP_LAZYIV;
2576                 if (S_outside_integer(aTHX_ sv) ||
2577                     S_outside_integer(aTHX_ right))
2578                     DIE(aTHX_ "Range iterator outside integer range");
2579                 cx->blk_loop.state_u.lazyiv.cur = SvIV_nomg(sv);
2580                 cx->blk_loop.state_u.lazyiv.end = SvIV_nomg(right);
2581                 rpp_popfree_2_NN();
2582             }
2583             else {
2584                 cx->cx_type |= CXt_LOOP_LAZYSV;
2585                 cx->blk_loop.state_u.lazysv.cur = newSVsv(sv);
2586                 cx->blk_loop.state_u.lazysv.end = right;
2587
2588                 /* we transfer ownership of 1 ref count of right from the
2589                  * stack to the CX .end entry, so no SvREFCNT_dec() needed */
2590                 (void)rpp_pop_1_norc();
2591
2592                 rpp_popfree_1_NN(); /* free the (now copied) start SV */
2593                 (void) SvPV_force_nolen(cx->blk_loop.state_u.lazysv.cur);
2594                 /* This will do the upgrade to SVt_PV, and warn if the value
2595                    is uninitialised.  */
2596                 (void) SvPV_nolen_const(right);
2597                 /* Doing this avoids a check every time in pp_iter in pp_hot.c
2598                    to replace !SvOK() with a pointer to "".  */
2599                 if (!SvOK(right)) {
2600                     SvREFCNT_dec(right);
2601                     cx->blk_loop.state_u.lazysv.end = &PL_sv_no;
2602                 }
2603             }
2604         }
2605         else /* SvTYPE(maybe_ary) == SVt_PVAV */ {
2606             /* for (@array) {} */
2607             cx->cx_type |= CXt_LOOP_ARY;
2608             cx->blk_loop.state_u.ary.ary = MUTABLE_AV(maybe_ary);
2609             /* we transfer ownership of 1 ref count of the av from the
2610              * stack to the CX .ary entry, so no SvREFCNT_dec() needed */
2611             (void)rpp_pop_1_norc();
2612             cx->blk_loop.state_u.ary.ix =
2613                 (PL_op->op_private & OPpITER_REVERSED) ?
2614                 AvFILL(cx->blk_loop.state_u.ary.ary) + 1 :
2615                 -1;
2616         }
2617         /* rpp_extend(1) not needed in this branch
2618          * because we just popped 1 item */
2619     }
2620     else { /* iterating over items on the stack */
2621         cx->cx_type |= CXt_LOOP_LIST;
2622         cx->blk_oldsp = PL_stack_sp - PL_stack_base;
2623         cx->blk_loop.state_u.stack.basesp = MARK - PL_stack_base;
2624         cx->blk_loop.state_u.stack.ix =
2625             (PL_op->op_private & OPpITER_REVERSED)
2626                 ? cx->blk_oldsp + 1
2627                 : cx->blk_loop.state_u.stack.basesp;
2628         /* pre-extend stack so pp_iter doesn't have to check every time
2629          * it pushes yes/no */
2630         rpp_extend(1);
2631     }
2632
2633     return NORMAL;
2634 }
2635
2636 PP(pp_enterloop)
2637 {
2638     PERL_CONTEXT *cx;
2639     const U8 gimme = GIMME_V;
2640
2641     cx = cx_pushblock(CXt_LOOP_PLAIN, gimme, PL_stack_sp, PL_savestack_ix);
2642     cx_pushloop_plain(cx);
2643     return NORMAL;
2644 }
2645
2646
2647 PP(pp_leaveloop)
2648 {
2649     PERL_CONTEXT *cx;
2650     U8 gimme;
2651     SV **base;
2652     SV **oldsp;
2653
2654     cx = CX_CUR();
2655     assert(CxTYPE_is_LOOP(cx));
2656     oldsp = PL_stack_base + cx->blk_oldsp;
2657     base = CxTYPE(cx) == CXt_LOOP_LIST
2658                 ? PL_stack_base + cx->blk_loop.state_u.stack.basesp
2659                 : oldsp;
2660     gimme = cx->blk_gimme;
2661
2662     if (gimme == G_VOID)
2663         rpp_popfree_to_NN(base);
2664     else
2665         leave_adjust_stacks(oldsp, base, gimme,
2666                                 PL_op->op_private & OPpLVALUE ? 3 : 1);
2667
2668     CX_LEAVE_SCOPE(cx);
2669     cx_poploop(cx);     /* Stack values are safe: release loop vars ... */
2670     cx_popblock(cx);
2671     CX_POP(cx);
2672
2673     return NORMAL;
2674 }
2675
2676
2677 /* This duplicates most of pp_leavesub, but with additional code to handle
2678  * return args in lvalue context. It was forked from pp_leavesub to
2679  * avoid slowing down that function any further.
2680  *
2681  * Any changes made to this function may need to be copied to pp_leavesub
2682  * and vice-versa.
2683  *
2684  * also tail-called by pp_return
2685  */
2686
2687 PP(pp_leavesublv)
2688 {
2689     U8 gimme;
2690     PERL_CONTEXT *cx;
2691     SV **oldsp;
2692     OP *retop;
2693
2694     cx = CX_CUR();
2695     assert(CxTYPE(cx) == CXt_SUB);
2696
2697     if (CxMULTICALL(cx)) {
2698         /* entry zero of a stack is always PL_sv_undef, which
2699          * simplifies converting a '()' return into undef in scalar context */
2700         assert(PL_stack_sp > PL_stack_base || *PL_stack_base == &PL_sv_undef);
2701         return 0;
2702     }
2703
2704     gimme = cx->blk_gimme;
2705     oldsp = PL_stack_base + cx->blk_oldsp; /* last arg of previous frame */
2706
2707     if (gimme == G_VOID)
2708         rpp_popfree_to_NN(oldsp);
2709     else {
2710         U8   lval    = CxLVAL(cx);
2711         bool is_lval = (lval && !(lval & OPpENTERSUB_INARGS));
2712         const char *what = NULL;
2713
2714         if (gimme == G_SCALAR) {
2715             if (is_lval) {
2716                 /* check for bad return arg */
2717                 if (oldsp < PL_stack_sp) {
2718                     SV *sv = *PL_stack_sp;
2719                     if ((SvPADTMP(sv) || SvREADONLY(sv))) {
2720                         what =
2721                             SvREADONLY(sv) ? (sv == &PL_sv_undef) ? "undef"
2722                             : "a readonly value" : "a temporary";
2723                     }
2724                     else goto ok;
2725                 }
2726                 else {
2727                     /* sub:lvalue{} will take us here. */
2728                     what = "undef";
2729                 }
2730               croak:
2731                 Perl_croak(aTHX_
2732                           "Can't return %s from lvalue subroutine", what);
2733             }
2734
2735           ok:
2736             leave_adjust_stacks(oldsp, oldsp, gimme, is_lval ? 3 : 2);
2737
2738             if (lval & OPpDEREF) {
2739                 /* lval_sub()->{...} and similar */
2740                 SvGETMAGIC(*PL_stack_sp);
2741                 if (!SvOK(*PL_stack_sp)) {
2742                     SV *sv = vivify_ref(*PL_stack_sp, CxLVAL(cx) & OPpDEREF);
2743                     rpp_replace_1_1_NN(sv);
2744                 }
2745             }
2746         }
2747         else {
2748             assert(gimme == G_LIST);
2749             assert (!(lval & OPpDEREF));
2750
2751             if (is_lval) {
2752                 /* scan for bad return args */
2753                 SV **p;
2754                 for (p = PL_stack_sp; p > oldsp; p--) {
2755                     SV *sv = *p;
2756                     /* the PL_sv_undef exception is to allow things like
2757                      * this to work, where PL_sv_undef acts as 'skip'
2758                      * placeholder on the LHS of list assigns:
2759                      *    sub foo :lvalue { undef }
2760                      *    ($a, undef, foo(), $b) = 1..4;
2761                      */
2762                     if (sv != &PL_sv_undef && (SvPADTMP(sv) || SvREADONLY(sv)))
2763                     {
2764                         /* Might be flattened array after $#array =  */
2765                         what = SvREADONLY(sv)
2766                                 ? "a readonly value" : "a temporary";
2767                         goto croak;
2768                     }
2769                 }
2770             }
2771
2772             leave_adjust_stacks(oldsp, oldsp, gimme, is_lval ? 3 : 2);
2773         }
2774     }
2775
2776     CX_LEAVE_SCOPE(cx);
2777     cx_popsub(cx);      /* Stack values are safe: release CV and @_ ... */
2778     cx_popblock(cx);
2779     retop =  cx->blk_sub.retop;
2780     CX_POP(cx);
2781
2782     return retop;
2783 }
2784
2785 static const char *S_defer_blockname(PERL_CONTEXT *cx)
2786 {
2787     return (cx->cx_type & CXp_FINALLY) ? "finally" : "defer";
2788 }
2789
2790
2791 PP(pp_return)
2792 {
2793     dMARK;
2794     PERL_CONTEXT *cx;
2795     I32 cxix = dopopto_cursub();
2796
2797     assert(cxstack_ix >= 0);
2798     if (cxix < cxstack_ix) {
2799         I32 i;
2800         /* Check for  defer { return; } */
2801         for(i = cxstack_ix; i > cxix; i--) {
2802             if(CxTYPE(&cxstack[i]) == CXt_DEFER)
2803                 /* diag_listed_as: Can't "%s" out of a "defer" block */
2804                 /* diag_listed_as: Can't "%s" out of a "finally" block */
2805                 Perl_croak(aTHX_ "Can't \"%s\" out of a \"%s\" block",
2806                         "return", S_defer_blockname(&cxstack[i]));
2807         }
2808         if (cxix < 0) {
2809             if (!(       PL_curstackinfo->si_type == PERLSI_SORT
2810                   || (   PL_curstackinfo->si_type == PERLSI_MULTICALL
2811                       && (cxstack[0].cx_type & CXp_SUB_RE_FAKE))
2812                  )
2813             )
2814                 DIE(aTHX_ "Can't return outside a subroutine");
2815             /* We must be in:
2816              *  a sort block, which is a CXt_NULL not a CXt_SUB;
2817              *  or a /(?{...})/ block.
2818              * Handle specially. */
2819             assert(CxTYPE(&cxstack[0]) == CXt_NULL
2820                     || (   CxTYPE(&cxstack[0]) == CXt_SUB
2821                         && (cxstack[0].cx_type & CXp_SUB_RE_FAKE)));
2822             if (cxstack_ix > 0) {
2823                 /* See comment below about context popping. Since we know
2824                  * we're scalar and not lvalue, we can preserve the return
2825                  * value in a simpler fashion than there. */
2826                 SV *sv = *PL_stack_sp;
2827                 assert(cxstack[0].blk_gimme == G_SCALAR);
2828                 if (   (PL_stack_sp != PL_stack_base)
2829                     && !(SvFLAGS(sv) & (SVs_TEMP|SVs_PADTMP))
2830                 )
2831 #ifdef PERL_RC_STACK
2832                     rpp_replace_at_norc(PL_stack_sp, newSVsv(sv));
2833 #else
2834                     *PL_stack_sp = sv_mortalcopy(sv);
2835 #endif
2836                 dounwind(0);
2837             }
2838             /* caller responsible for popping cxstack[0] */
2839             return 0;
2840         }
2841
2842         /* There are contexts that need popping. Doing this may free the
2843          * return value(s), so preserve them first: e.g. popping the plain
2844          * loop here would free $x:
2845          *     sub f {  { my $x = 1; return $x } }
2846          * We may also need to shift the args down; for example,
2847          *    for (1,2) { return 3,4 }
2848          * leaves 1,2,3,4 on the stack. Both these actions will be done by
2849          * leave_adjust_stacks(), along with freeing any temps. Note that
2850          * whoever we tail-call (e.g. pp_leaveeval) will also call
2851          * leave_adjust_stacks(); however, the second call is likely to
2852          * just see a bunch of SvTEMPs with a ref count of 1, and so just
2853          * pass them through, rather than copying them again. So this
2854          * isn't as inefficient as it sounds.
2855          */
2856         cx = &cxstack[cxix];
2857         if (cx->blk_gimme != G_VOID)
2858             leave_adjust_stacks(MARK, PL_stack_base + cx->blk_oldsp,
2859                     cx->blk_gimme,
2860                     CxTYPE(cx) == CXt_SUB && CvLVALUE(cx->blk_sub.cv)
2861                         ? 3 : 0);
2862         dounwind(cxix);
2863         cx = &cxstack[cxix]; /* CX stack may have been realloced */
2864     }
2865     else {
2866         /* Like in the branch above, we need to handle any extra junk on
2867          * the stack. But because we're not also popping extra contexts, we
2868          * don't have to worry about prematurely freeing args. So we just
2869          * need to do the bare minimum to handle junk, and leave the main
2870          * arg processing in the function we tail call, e.g. pp_leavesub.
2871          * In list context we have to splice out the junk; in scalar
2872          * context we can leave as-is (pp_leavesub will later return the
2873          * top stack element). But for an  empty arg list, e.g.
2874          *    for (1,2) { return }
2875          * we need to set PL_stack_sp = oldsp so that pp_leavesub knows to
2876          * push &PL_sv_undef onto the stack.
2877          */
2878         SV **oldsp;
2879         cx = &cxstack[cxix];
2880         oldsp = PL_stack_base + cx->blk_oldsp;
2881         if (oldsp != MARK) {
2882             SSize_t nargs = PL_stack_sp - MARK;
2883             if (nargs) {
2884                 if (cx->blk_gimme == G_LIST) {
2885                     /* shift return args to base of call stack frame */
2886 #ifdef PERL_RC_STACK
2887                     /* free the items on the stack that will get
2888                      * overwritten */
2889                     SV **p;
2890                     for (p = MARK; p > oldsp; p--) {
2891                         SV *sv = *p;
2892                         *p = NULL;
2893                         SvREFCNT_dec(sv);
2894                     }
2895 #endif
2896                     Move(MARK + 1, oldsp + 1, nargs, SV*);
2897                     PL_stack_sp  = oldsp + nargs;
2898                 }
2899             }
2900             else
2901                 rpp_popfree_to_NN(oldsp);
2902         }
2903     }
2904
2905     /* fall through to a normal exit */
2906     switch (CxTYPE(cx)) {
2907     case CXt_EVAL:
2908         return CxEVALBLOCK(cx)
2909             ? Perl_pp_leavetry(aTHX)
2910             : Perl_pp_leaveeval(aTHX);
2911     case CXt_SUB:
2912         return CvLVALUE(cx->blk_sub.cv)
2913             ? Perl_pp_leavesublv(aTHX)
2914             : Perl_pp_leavesub(aTHX);
2915     case CXt_FORMAT:
2916         return Perl_pp_leavewrite(aTHX);
2917     default:
2918         DIE(aTHX_ "panic: return, type=%u", (unsigned) CxTYPE(cx));
2919     }
2920 }
2921
2922 /* find the enclosing loop or labelled loop and dounwind() back to it. */
2923
2924 static PERL_CONTEXT *
2925 S_unwind_loop(pTHX)
2926 {
2927     I32 cxix;
2928     if (PL_op->op_flags & OPf_SPECIAL) {
2929         cxix = dopoptoloop(cxstack_ix);
2930         if (cxix < 0)
2931             /* diag_listed_as: Can't "last" outside a loop block */
2932             Perl_croak(aTHX_ "Can't \"%s\" outside a loop block",
2933                 OP_NAME(PL_op));
2934     }
2935     else {
2936         STRLEN label_len;
2937         const char * label;
2938         U32 label_flags;
2939         SV *sv;
2940
2941         if (PL_op->op_flags & OPf_STACKED) {
2942             sv          = *PL_stack_sp;
2943             label       = SvPV(sv, label_len);
2944             label_flags = SvUTF8(sv);
2945         }
2946         else {
2947             sv          = NULL; /* not needed, but shuts up compiler warn */
2948             label       = cPVOP->op_pv;
2949             label_len   = strlen(label);
2950             label_flags = (cPVOP->op_private & OPpPV_IS_UTF8) ? SVf_UTF8 : 0;
2951         }
2952
2953         cxix = dopoptolabel(label, label_len, label_flags);
2954         if (cxix < 0)
2955             /* diag_listed_as: Label not found for "last %s" */
2956             Perl_croak(aTHX_ "Label not found for \"%s %" SVf "\"",
2957                                        OP_NAME(PL_op),
2958                                        SVfARG(PL_op->op_flags & OPf_STACKED
2959                                               && !SvGMAGICAL(sv)
2960                                               ? sv
2961                                               : newSVpvn_flags(label,
2962                                                     label_len,
2963                                                     label_flags | SVs_TEMP)));
2964         if (PL_op->op_flags & OPf_STACKED)
2965             rpp_popfree_1_NN();
2966     }
2967
2968     if (cxix < cxstack_ix) {
2969         I32 i;
2970         /* Check for  defer { last ... } etc */
2971         for(i = cxstack_ix; i > cxix; i--) {
2972             if(CxTYPE(&cxstack[i]) == CXt_DEFER)
2973                 /* diag_listed_as: Can't "%s" out of a "defer" block */
2974                 /* diag_listed_as: Can't "%s" out of a "finally" block */
2975                 Perl_croak(aTHX_ "Can't \"%s\" out of a \"%s\" block",
2976                         OP_NAME(PL_op), S_defer_blockname(&cxstack[i]));
2977         }
2978         dounwind(cxix);
2979     }
2980     return &cxstack[cxix];
2981 }
2982
2983
2984 PP(pp_last)
2985 {
2986     PERL_CONTEXT *cx;
2987     OP* nextop;
2988
2989     cx = S_unwind_loop(aTHX);
2990
2991     assert(CxTYPE_is_LOOP(cx));
2992     rpp_popfree_to_NN(PL_stack_base
2993                 + (CxTYPE(cx) == CXt_LOOP_LIST
2994                     ?  cx->blk_loop.state_u.stack.basesp
2995                     : cx->blk_oldsp
2996                 ));
2997
2998     TAINT_NOT;
2999
3000     /* Stack values are safe: */
3001     CX_LEAVE_SCOPE(cx);
3002     cx_poploop(cx);     /* release loop vars ... */
3003     cx_popblock(cx);
3004     nextop = cx->blk_loop.my_op->op_lastop->op_next;
3005     CX_POP(cx);
3006
3007     return nextop;
3008 }
3009
3010 PP(pp_next)
3011 {
3012     PERL_CONTEXT *cx;
3013
3014     /* if not a bare 'next' in the main scope, search for it */
3015     cx = CX_CUR();
3016     if (!((PL_op->op_flags & OPf_SPECIAL) && CxTYPE_is_LOOP(cx)))
3017         cx = S_unwind_loop(aTHX);
3018
3019     cx_topblock(cx);
3020     PL_curcop = cx->blk_oldcop;
3021     PERL_ASYNC_CHECK();
3022     return (cx)->blk_loop.my_op->op_nextop;
3023 }
3024
3025 PP(pp_redo)
3026 {
3027     PERL_CONTEXT *cx = S_unwind_loop(aTHX);
3028     OP* redo_op = cx->blk_loop.my_op->op_redoop;
3029
3030     if (redo_op->op_type == OP_ENTER) {
3031         /* pop one less context to avoid $x being freed in while (my $x..) */
3032         cxstack_ix++;
3033         cx = CX_CUR();
3034         assert(CxTYPE(cx) == CXt_BLOCK);
3035         redo_op = redo_op->op_next;
3036     }
3037
3038     FREETMPS;
3039     CX_LEAVE_SCOPE(cx);
3040     cx_topblock(cx);
3041     PL_curcop = cx->blk_oldcop;
3042     PERL_ASYNC_CHECK();
3043     return redo_op;
3044 }
3045
3046 #define UNENTERABLE (OP *)1
3047 #define GOTO_DEPTH 64
3048
3049 STATIC OP *
3050 S_dofindlabel(pTHX_ OP *o, const char *label, STRLEN len, U32 flags, OP **opstack, OP **oplimit)
3051 {
3052     OP **ops = opstack;
3053     static const char* const too_deep = "Target of goto is too deeply nested";
3054
3055     PERL_ARGS_ASSERT_DOFINDLABEL;
3056
3057     if (ops >= oplimit)
3058         Perl_croak(aTHX_ "%s", too_deep);
3059     if (o->op_type == OP_LEAVE ||
3060         o->op_type == OP_SCOPE ||
3061         o->op_type == OP_LEAVELOOP ||
3062         o->op_type == OP_LEAVESUB ||
3063         o->op_type == OP_LEAVETRY ||
3064         o->op_type == OP_LEAVEGIVEN)
3065     {
3066         *ops++ = cUNOPo->op_first;
3067     }
3068     else if (oplimit - opstack < GOTO_DEPTH) {
3069       if (o->op_flags & OPf_KIDS
3070           && cUNOPo->op_first->op_type == OP_PUSHMARK) {
3071         *ops++ = UNENTERABLE;
3072       }
3073       else if (o->op_flags & OPf_KIDS && PL_opargs[o->op_type]
3074           && OP_CLASS(o) != OA_LOGOP
3075           && o->op_type != OP_LINESEQ
3076           && o->op_type != OP_SREFGEN
3077           && o->op_type != OP_ENTEREVAL
3078           && o->op_type != OP_GLOB
3079           && o->op_type != OP_RV2CV) {
3080         OP * const kid = cUNOPo->op_first;
3081         if (OP_GIMME(kid, 0) != G_SCALAR || OpHAS_SIBLING(kid))
3082             *ops++ = UNENTERABLE;
3083       }
3084     }
3085     if (ops >= oplimit)
3086         Perl_croak(aTHX_ "%s", too_deep);
3087     *ops = 0;
3088     if (o->op_flags & OPf_KIDS) {
3089         OP *kid;
3090         OP * const kid1 = cUNOPo->op_first;
3091         /* First try all the kids at this level, since that's likeliest. */
3092         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
3093             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
3094                 STRLEN kid_label_len;
3095                 U32 kid_label_flags;
3096                 const char *kid_label = CopLABEL_len_flags(kCOP,
3097                                                     &kid_label_len, &kid_label_flags);
3098                 if (kid_label && (
3099                     ( (kid_label_flags & SVf_UTF8) != (flags & SVf_UTF8) ) ?
3100                         (flags & SVf_UTF8)
3101                             ? (bytes_cmp_utf8(
3102                                         (const U8*)kid_label, kid_label_len,
3103                                         (const U8*)label, len) == 0)
3104                             : (bytes_cmp_utf8(
3105                                         (const U8*)label, len,
3106                                         (const U8*)kid_label, kid_label_len) == 0)
3107                     : ( len == kid_label_len && ((kid_label == label)
3108                                     || memEQ(kid_label, label, len)))))
3109                     return kid;
3110             }
3111         }
3112         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
3113             bool first_kid_of_binary = FALSE;
3114             if (kid == PL_lastgotoprobe)
3115                 continue;
3116             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
3117                 if (ops == opstack)
3118                     *ops++ = kid;
3119                 else if (ops[-1] != UNENTERABLE
3120                       && (ops[-1]->op_type == OP_NEXTSTATE ||
3121                           ops[-1]->op_type == OP_DBSTATE))
3122                     ops[-1] = kid;
3123                 else
3124                     *ops++ = kid;
3125             }
3126             if (kid == kid1 && ops != opstack && ops[-1] == UNENTERABLE) {
3127                 first_kid_of_binary = TRUE;
3128                 ops--;
3129             }
3130             if ((o = dofindlabel(kid, label, len, flags, ops, oplimit))) {
3131                 if (kid->op_type == OP_PUSHDEFER)
3132                     Perl_croak(aTHX_ "Can't \"goto\" into a \"defer\" block");
3133                 return o;
3134             }
3135             if (first_kid_of_binary)
3136                 *ops++ = UNENTERABLE;
3137         }
3138     }
3139     *ops = 0;
3140     return 0;
3141 }
3142
3143
3144 static void
3145 S_check_op_type(pTHX_ OP * const o)
3146 {
3147     /* Eventually we may want to stack the needed arguments
3148      * for each op.  For now, we punt on the hard ones. */
3149     /* XXX This comment seems to me like wishful thinking.  --sprout */
3150     if (o == UNENTERABLE)
3151         Perl_croak(aTHX_
3152                   "Can't \"goto\" into a binary or list expression");
3153     if (o->op_type == OP_ENTERITER)
3154         Perl_croak(aTHX_
3155                   "Can't \"goto\" into the middle of a foreach loop");
3156     if (o->op_type == OP_ENTERGIVEN)
3157         Perl_croak(aTHX_
3158                   "Can't \"goto\" into a \"given\" block");
3159 }
3160
3161 /* also used for: pp_dump() */
3162
3163 PP(pp_goto)
3164 {
3165     OP *retop = NULL;
3166     I32 ix;
3167     PERL_CONTEXT *cx;
3168     OP *enterops[GOTO_DEPTH];
3169     const char *label = NULL;
3170     STRLEN label_len = 0;
3171     U32 label_flags = 0;
3172     const bool do_dump = (PL_op->op_type == OP_DUMP);
3173     static const char* const must_have_label = "goto must have label";
3174
3175     if (PL_op->op_flags & OPf_STACKED) {
3176         /* goto EXPR  or  goto &foo */
3177
3178         SV * const sv = *PL_stack_sp;
3179         SvGETMAGIC(sv);
3180
3181         if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
3182             /* This egregious kludge implements goto &subroutine */
3183             I32 cxix;
3184             PERL_CONTEXT *cx;
3185             CV *cv = MUTABLE_CV(SvRV(sv));
3186             AV *arg = GvAV(PL_defgv);
3187             CV *old_cv = NULL;
3188
3189             while (!CvROOT(cv) && !CvXSUB(cv)) {
3190                 const GV * const gv = CvGV(cv);
3191                 if (gv) {
3192                     GV *autogv;
3193                     SV *tmpstr;
3194                     /* autoloaded stub? */
3195                     if (cv != GvCV(gv) && (cv = GvCV(gv)))
3196                         continue;
3197                     autogv = gv_autoload_pvn(GvSTASH(gv), GvNAME(gv),
3198                                           GvNAMELEN(gv),
3199                                           GvNAMEUTF8(gv) ? SVf_UTF8 : 0);
3200                     if (autogv && (cv = GvCV(autogv)))
3201                         continue;
3202                     tmpstr = sv_newmortal();
3203                     gv_efullname3(tmpstr, gv, NULL);
3204                     DIE(aTHX_ "Goto undefined subroutine &%" SVf, SVfARG(tmpstr));
3205                 }
3206                 DIE(aTHX_ "Goto undefined subroutine");
3207             }
3208
3209             cxix = dopopto_cursub();
3210             if (cxix < 0) {
3211                 DIE(aTHX_ "Can't goto subroutine outside a subroutine");
3212             }
3213             cx  = &cxstack[cxix];
3214             /* ban goto in eval: see <20050521150056.GC20213@iabyn.com> */
3215             if (CxTYPE(cx) == CXt_EVAL) {
3216                 if (CxREALEVAL(cx))
3217                 /* diag_listed_as: Can't goto subroutine from an eval-%s */
3218                     DIE(aTHX_ "Can't goto subroutine from an eval-string");
3219                 else
3220                 /* diag_listed_as: Can't goto subroutine from an eval-%s */
3221                     DIE(aTHX_ "Can't goto subroutine from an eval-block");
3222             }
3223             else if (CxMULTICALL(cx))
3224                 DIE(aTHX_ "Can't goto subroutine from a sort sub (or similar callback)");
3225
3226             /* Check for  defer { goto &...; } */
3227             for(ix = cxstack_ix; ix > cxix; ix--) {
3228                 if(CxTYPE(&cxstack[ix]) == CXt_DEFER)
3229                     /* diag_listed_as: Can't "%s" out of a "defer" block */
3230                     Perl_croak(aTHX_ "Can't \"%s\" out of a \"%s\" block",
3231                             "goto", S_defer_blockname(&cxstack[ix]));
3232             }
3233
3234             /* First do some returnish stuff. */
3235
3236             SvREFCNT_inc_simple_void(cv); /* avoid premature free during unwind */
3237             rpp_popfree_1_NN(); /* safe to free original sv now */
3238
3239             FREETMPS;
3240             if (cxix < cxstack_ix) {
3241                 dounwind(cxix);
3242             }
3243             cx = CX_CUR();
3244             cx_topblock(cx);
3245
3246             /* protect @_ during save stack unwind. */
3247             if (arg)
3248                 SvREFCNT_inc_NN(sv_2mortal(MUTABLE_SV(arg)));
3249
3250             assert(PL_scopestack_ix == cx->blk_oldscopesp);
3251             CX_LEAVE_SCOPE(cx);
3252
3253             if (CxTYPE(cx) == CXt_SUB && CxHASARGS(cx)) {
3254                 /* this is part of cx_popsub_args() */
3255                 AV* av = MUTABLE_AV(PAD_SVl(0));
3256                 assert(AvARRAY(MUTABLE_AV(
3257                     PadlistARRAY(CvPADLIST(cx->blk_sub.cv))[
3258                             CvDEPTH(cx->blk_sub.cv)])) == PL_curpad);
3259
3260                 /* we are going to donate the current @_ from the old sub
3261                  * to the new sub. This first part of the donation puts a
3262                  * new empty AV in the pad[0] slot of the old sub,
3263                  * unless pad[0] and @_ differ (e.g. if the old sub did
3264                  * local *_ = []); in which case clear the old pad[0]
3265                  * array in the usual way */
3266
3267                 if (av != arg && !SvMAGICAL(av) && SvREFCNT(av) == 1
3268 #ifndef PERL_RC_STACK
3269                     && !AvREAL(av)
3270 #endif
3271                 )
3272                     clear_defarray_simple(av);
3273                 else
3274                     clear_defarray(av, av == arg);
3275             }
3276
3277             /* don't restore PL_comppad here. It won't be needed if the
3278              * sub we're going to is non-XS, but restoring it early then
3279              * croaking (e.g. the "Goto undefined subroutine" below)
3280              * means the CX block gets processed again in dounwind,
3281              * but this time with the wrong PL_comppad */
3282
3283             /* A destructor called during LEAVE_SCOPE could have undefined
3284              * our precious cv.  See bug #99850. */
3285             if (!CvROOT(cv) && !CvXSUB(cv)) {
3286                 const GV * const gv = CvGV(cv);
3287                 if (gv) {
3288                     SV * const tmpstr = sv_newmortal();
3289                     gv_efullname3(tmpstr, gv, NULL);
3290                     DIE(aTHX_ "Goto undefined subroutine &%" SVf,
3291                                SVfARG(tmpstr));
3292                 }
3293                 DIE(aTHX_ "Goto undefined subroutine");
3294             }
3295
3296             if (CxTYPE(cx) == CXt_SUB) {
3297                 CvDEPTH(cx->blk_sub.cv) = cx->blk_sub.olddepth;
3298                 /*on XS calls defer freeing the old CV as it could
3299                  * prematurely set PL_op to NULL, which could cause
3300                  * e..g XS subs using GIMME_V to SEGV */
3301                 if (CvISXSUB(cv))
3302                     old_cv = cx->blk_sub.cv;
3303                 else
3304                     SvREFCNT_dec_NN(cx->blk_sub.cv);
3305             }
3306
3307             /* Now do some callish stuff. */
3308             if (CvISXSUB(cv)) {
3309                 const SSize_t items = arg ? AvFILL(arg) + 1 : 0;
3310                 const bool m = arg ? cBOOL(SvRMAGICAL(arg)) : 0;
3311                 SV** mark;
3312                 UNOP fake_goto_op;
3313
3314                 ENTER;
3315                 SAVETMPS;
3316                 SAVEFREESV(cv); /* later, undo the 'avoid premature free' hack */
3317                 if (old_cv)
3318                     SAVEFREESV(old_cv); /* ditto, deferred freeing of old CV */
3319
3320                 /* put GvAV(defgv) back onto stack */
3321                 if (items)
3322                     rpp_extend(items + 1); /* @_ could have been extended. */
3323                 mark = PL_stack_sp;
3324                 if (items) {
3325                     SSize_t index;
3326 #ifdef PERL_RC_STACK
3327                     assert(AvREAL(arg));
3328 #else
3329                     bool r = cBOOL(AvREAL(arg));
3330 #endif
3331                     for (index=0; index<items; index++)
3332                     {
3333                         SV *sv;
3334                         if (m) {
3335                             SV ** const svp = av_fetch(arg, index, 0);
3336                             sv = svp ? *svp : NULL;
3337                         }
3338                         else sv = AvARRAY(arg)[index];
3339
3340 #ifdef PERL_RC_STACK
3341                         rpp_push_1(
3342                             sv
3343                             ? sv
3344                             : newSVavdefelem(arg, index, 1)
3345                         );
3346 #else
3347                         rpp_push_1(
3348                             sv
3349                             ? (r ? SvREFCNT_inc_NN(sv_2mortal(sv)) : sv)
3350                             : sv_2mortal(newSVavdefelem(arg, index, 1))
3351                         );
3352 #endif
3353                     }
3354                 }
3355
3356                 if (CxTYPE(cx) == CXt_SUB && CxHASARGS(cx)) {
3357                     /* Restore old @_ */
3358                     CX_POP_SAVEARRAY(cx);
3359                 }
3360
3361                 retop = cx->blk_sub.retop;
3362                 PL_comppad = cx->blk_sub.prevcomppad;
3363                 PL_curpad = LIKELY(PL_comppad) ? AvARRAY(PL_comppad) : NULL;
3364
3365                 /* Make a temporary a copy of the current GOTO op on the C
3366                  * stack, but with a modified gimme (we can't modify the
3367                  * real GOTO op as that's not thread-safe). This allows XS
3368                  * users of GIMME_V to get the correct calling context,
3369                  * even though there is no longer a CXt_SUB frame to
3370                  * provide that information.
3371                  */
3372                 Copy(PL_op, &fake_goto_op, 1, UNOP);
3373                 fake_goto_op.op_flags =
3374                                   (fake_goto_op.op_flags & ~OPf_WANT)
3375                                 | (cx->blk_gimme & G_WANT);
3376                 PL_op = (OP*)&fake_goto_op;
3377
3378                 /* XS subs don't have a CXt_SUB, so pop it;
3379                  * this is a cx_popblock(), less all the stuff we already did
3380                  * for cx_topblock() earlier */
3381                 PL_curcop = cx->blk_oldcop;
3382                 /* this is cx_popsub, less all the stuff we already did */
3383                 PL_curstackinfo->si_cxsubix = cx->blk_sub.old_cxsubix;
3384
3385                 CX_POP(cx);
3386
3387                 /* Push a mark for the start of arglist */
3388                 PUSHMARK(mark);
3389                 rpp_invoke_xs(cv);
3390                 LEAVE;
3391                 goto finish;
3392             }
3393             else {
3394                 PADLIST * const padlist = CvPADLIST(cv);
3395
3396                 SAVEFREESV(cv); /* later, undo the 'avoid premature free' hack */
3397
3398                 /* partial unrolled cx_pushsub(): */
3399
3400                 cx->blk_sub.cv = cv;
3401                 cx->blk_sub.olddepth = CvDEPTH(cv);
3402
3403                 CvDEPTH(cv)++;
3404                 SvREFCNT_inc_simple_void_NN(cv);
3405                 if (CvDEPTH(cv) > 1) {
3406                     if (CvDEPTH(cv) == PERL_SUB_DEPTH_WARN && ckWARN(WARN_RECURSION))
3407                         sub_crush_depth(cv);
3408                     pad_push(padlist, CvDEPTH(cv));
3409                 }
3410                 PL_curcop = cx->blk_oldcop;
3411                 PAD_SET_CUR_NOSAVE(padlist, CvDEPTH(cv));
3412
3413                 if (CxHASARGS(cx))
3414                 {
3415                     /* second half of donating @_ from the old sub to the
3416                      * new sub: abandon the original pad[0] AV in the
3417                      * new sub, and replace it with the donated @_.
3418                      * pad[0] takes ownership of the extra refcount
3419                      * we gave arg earlier */
3420                     if (arg) {
3421                         SvREFCNT_dec(PAD_SVl(0));
3422                         PAD_SVl(0) = (SV *)arg;
3423                         SvREFCNT_inc_simple_void_NN(arg);
3424                     }
3425
3426                     /* GvAV(PL_defgv) might have been modified on scope
3427                        exit, so point it at arg again. */
3428                     if (arg != GvAV(PL_defgv)) {
3429                         AV * const av = GvAV(PL_defgv);
3430                         GvAV(PL_defgv) = (AV *)SvREFCNT_inc_simple(arg);
3431                         SvREFCNT_dec(av);
3432                     }
3433                 }
3434
3435                 if (PERLDB_SUB) {       /* Checking curstash breaks DProf. */
3436                     Perl_get_db_sub(aTHX_ NULL, cv);
3437                     if (PERLDB_GOTO) {
3438                         CV * const gotocv = get_cvs("DB::goto", 0);
3439                         if (gotocv) {
3440                             PUSHMARK( PL_stack_sp );
3441                             call_sv(MUTABLE_SV(gotocv), G_SCALAR | G_NODEBUG);
3442                             PL_stack_sp--;
3443                         }
3444                     }
3445                 }
3446                 retop = CvSTART(cv);
3447                 goto finish;
3448             }
3449         }
3450         else {
3451             /* goto EXPR */
3452             /* avoid premature free of label before popping it off stack */
3453             SvREFCNT_inc_NN(sv);
3454             sv_2mortal(sv);
3455             rpp_popfree_1_NN();
3456             label       = SvPV_nomg_const(sv, label_len);
3457             label_flags = SvUTF8(sv);
3458         }
3459     }
3460     else if (!(PL_op->op_flags & OPf_SPECIAL)) {
3461         /* goto LABEL  or  dump LABEL */
3462         label       = cPVOP->op_pv;
3463         label_flags = (cPVOP->op_private & OPpPV_IS_UTF8) ? SVf_UTF8 : 0;
3464         label_len   = strlen(label);
3465     }
3466     if (!(do_dump || label_len)) DIE(aTHX_ "%s", must_have_label);
3467
3468     PERL_ASYNC_CHECK();
3469
3470     if (label_len) {
3471         OP *gotoprobe = NULL;
3472         bool leaving_eval = FALSE;
3473         bool in_block = FALSE;
3474         bool pseudo_block = FALSE;
3475         PERL_CONTEXT *last_eval_cx = NULL;
3476
3477         /* find label */
3478
3479         PL_lastgotoprobe = NULL;
3480         *enterops = 0;
3481         for (ix = cxstack_ix; ix >= 0; ix--) {
3482             cx = &cxstack[ix];
3483             switch (CxTYPE(cx)) {
3484             case CXt_EVAL:
3485                 leaving_eval = TRUE;
3486                 if (!CxEVALBLOCK(cx)) {
3487                     gotoprobe = (last_eval_cx ?
3488                                 last_eval_cx->blk_eval.old_eval_root :
3489                                 PL_eval_root);
3490                     last_eval_cx = cx;
3491                     break;
3492                 }
3493                 /* else fall through */
3494             case CXt_LOOP_PLAIN:
3495             case CXt_LOOP_LAZYIV:
3496             case CXt_LOOP_LAZYSV:
3497             case CXt_LOOP_LIST:
3498             case CXt_LOOP_ARY:
3499             case CXt_GIVEN:
3500             case CXt_WHEN:
3501                 gotoprobe = OpSIBLING(cx->blk_oldcop);
3502                 break;
3503             case CXt_SUBST:
3504                 continue;
3505             case CXt_BLOCK:
3506                 if (ix) {
3507                     gotoprobe = OpSIBLING(cx->blk_oldcop);
3508                     in_block = TRUE;
3509                 } else
3510                     gotoprobe = PL_main_root;
3511                 break;
3512             case CXt_SUB:
3513                 gotoprobe = CvROOT(cx->blk_sub.cv);
3514                 pseudo_block = cBOOL(CxMULTICALL(cx));
3515                 break;
3516             case CXt_FORMAT:
3517             case CXt_NULL:
3518                 DIE(aTHX_ "Can't \"goto\" out of a pseudo block");
3519             case CXt_DEFER:
3520                 /* diag_listed_as: Can't "%s" out of a "defer" block */
3521                 DIE(aTHX_ "Can't \"%s\" out of a \"%s\" block", "goto", S_defer_blockname(cx));
3522             default:
3523                 if (ix)
3524                     DIE(aTHX_ "panic: goto, type=%u, ix=%ld",
3525                         CxTYPE(cx), (long) ix);
3526                 gotoprobe = PL_main_root;
3527                 break;
3528             }
3529             if (gotoprobe) {
3530                 OP *sibl1, *sibl2;
3531
3532                 retop = dofindlabel(gotoprobe, label, label_len, label_flags,
3533                                     enterops, enterops + GOTO_DEPTH);
3534                 if (retop)
3535                     break;
3536                 if ( (sibl1 = OpSIBLING(gotoprobe)) &&
3537                      sibl1->op_type == OP_UNSTACK &&
3538                      (sibl2 = OpSIBLING(sibl1)))
3539                 {
3540                     retop = dofindlabel(sibl2,
3541                                         label, label_len, label_flags, enterops,
3542                                         enterops + GOTO_DEPTH);
3543                     if (retop)
3544                         break;
3545                 }
3546             }
3547             if (pseudo_block)
3548                 DIE(aTHX_ "Can't \"goto\" out of a pseudo block");
3549             PL_lastgotoprobe = gotoprobe;
3550         }
3551         if (!retop)
3552             DIE(aTHX_ "Can't find label %" UTF8f,
3553                        UTF8fARG(label_flags, label_len, label));
3554
3555         /* if we're leaving an eval, check before we pop any frames
3556            that we're not going to punt, otherwise the error
3557            won't be caught */
3558
3559         if (leaving_eval && *enterops && enterops[1]) {
3560             I32 i;
3561             for (i = 1; enterops[i]; i++)
3562                 S_check_op_type(aTHX_ enterops[i]);
3563         }
3564
3565         if (*enterops && enterops[1]) {
3566             I32 i = enterops[1] != UNENTERABLE
3567                  && enterops[1]->op_type == OP_ENTER && in_block
3568                     ? 2
3569                     : 1;
3570             if (enterops[i])
3571                 deprecate_fatal_in(WARN_DEPRECATED__GOTO_CONSTRUCT,
3572                         "5.42",
3573                         "Use of \"goto\" to jump into a construct");
3574         }
3575
3576         /* pop unwanted frames */
3577
3578         if (ix < cxstack_ix) {
3579             if (ix < 0)
3580                 DIE(aTHX_ "panic: docatch: illegal ix=%ld", (long)ix);
3581             dounwind(ix);
3582             cx = CX_CUR();
3583             cx_topblock(cx);
3584         }
3585
3586         /* push wanted frames */
3587
3588         if (*enterops && enterops[1]) {
3589             OP * const oldop = PL_op;
3590             ix = enterops[1] != UNENTERABLE
3591               && enterops[1]->op_type == OP_ENTER && in_block
3592                    ? 2
3593                    : 1;
3594             for (; enterops[ix]; ix++) {
3595                 PL_op = enterops[ix];
3596                 S_check_op_type(aTHX_ PL_op);
3597                 DEBUG_l( Perl_deb(aTHX_ "pp_goto: Entering %s\n",
3598                                          OP_NAME(PL_op)));
3599                 PL_op->op_ppaddr(aTHX);
3600             }
3601             PL_op = oldop;
3602         }
3603     }
3604
3605     if (do_dump) {
3606 #ifdef VMS
3607         if (!retop) retop = PL_main_start;
3608 #endif
3609         PL_restartop = retop;
3610         PL_do_undump = TRUE;
3611
3612         my_unexec();
3613
3614         PL_restartop = 0;               /* hmm, must be GNU unexec().. */
3615         PL_do_undump = FALSE;
3616     }
3617
3618   finish:
3619     PERL_ASYNC_CHECK();
3620     return retop;
3621 }
3622
3623 PP_wrapped(pp_exit, 1, 0)
3624 {
3625     dSP;
3626     I32 anum;
3627
3628     if (MAXARG < 1)
3629         anum = 0;
3630     else if (!TOPs) {
3631         anum = 0; (void)POPs;
3632     }
3633     else {
3634         anum = SvIVx(POPs);
3635 #ifdef VMS
3636         if (anum == 1
3637          && SvTRUE(cop_hints_fetch_pvs(PL_curcop, "vmsish_exit", 0)))
3638             anum = 0;
3639         VMSISH_HUSHED  =
3640             VMSISH_HUSHED || (PL_curcop->op_private & OPpHUSH_VMSISH);
3641 #endif
3642     }
3643     PL_exit_flags |= PERL_EXIT_EXPECTED;
3644     my_exit(anum);
3645     PUSHs(&PL_sv_undef);
3646     RETURN;
3647 }
3648
3649 /* Eval. */
3650
3651 STATIC void
3652 S_save_lines(pTHX_ AV *array, SV *sv)
3653 {
3654     const char *s = SvPVX_const(sv);
3655     const char * const send = SvPVX_const(sv) + SvCUR(sv);
3656     I32 line = 1;
3657
3658     PERL_ARGS_ASSERT_SAVE_LINES;
3659
3660     while (s && s < send) {
3661         const char *t;
3662         SV * const tmpstr = newSV_type(SVt_PVMG);
3663
3664         t = (const char *)memchr(s, '\n', send - s);
3665         if (t)
3666             t++;
3667         else
3668             t = send;
3669
3670         sv_setpvn_fresh(tmpstr, s, t - s);
3671         av_store(array, line++, tmpstr);
3672         s = t;
3673     }
3674 }
3675
3676 /*
3677 =for apidoc docatch
3678
3679 Interpose, for the current op and RUNOPS loop,
3680
3681     - a new JMPENV stack catch frame, and
3682     - an inner RUNOPS loop to run all the remaining ops following the
3683       current PL_op.
3684
3685 Then handle any exceptions raised while in that loop.
3686 For a caught eval at this level, re-enter the loop with the specified
3687 restart op (i.e. the op following the OP_LEAVETRY etc); otherwise re-throw
3688 the exception.
3689
3690 docatch() is intended to be used like this:
3691
3692     PP(pp_entertry)
3693     {
3694         if (CATCH_GET)
3695             return docatch(Perl_pp_entertry);
3696
3697         ... rest of function ...
3698         return PL_op->op_next;
3699     }
3700
3701 If a new catch frame isn't needed, the op behaves normally. Otherwise it
3702 calls docatch(), which recursively calls pp_entertry(), this time with
3703 CATCH_GET() false, so the rest of the body of the entertry is run. Then
3704 docatch() calls CALLRUNOPS() which executes all the ops following the
3705 entertry. When the loop finally finishes, control returns to docatch(),
3706 which pops the JMPENV and returns to the parent pp_entertry(), which
3707 itself immediately returns. Note that *all* subsequent ops are run within
3708 the inner RUNOPS loop, not just the body of the eval. For example, in
3709
3710     sub TIEARRAY { eval {1}; my $x }
3711     tie @a, "main";
3712
3713 at the point the 'my' is executed, the C stack will look something like:
3714
3715     #10 main()
3716     #9  perl_run()              # JMPENV_PUSH level 1 here
3717     #8  S_run_body()
3718     #7  Perl_runops_standard()  # main RUNOPS loop
3719     #6  Perl_pp_tie()
3720     #5  Perl_call_sv()
3721     #4  Perl_runops_standard()  # unguarded RUNOPS loop: no new JMPENV
3722     #3  Perl_pp_entertry()
3723     #2  S_docatch()             # JMPENV_PUSH level 2 here
3724     #1  Perl_runops_standard()  # docatch()'s RUNOPs loop
3725     #0  Perl_pp_padsv()
3726
3727 Basically, any section of the perl core which starts a RUNOPS loop may
3728 make a promise that it will catch any exceptions and restart the loop if
3729 necessary. If it's not prepared to do that (like call_sv() isn't), then
3730 it sets CATCH_GET() to true, so that any later eval-like code knows to
3731 set up a new handler and loop (via docatch()).
3732
3733 See L<perlinterp/"Exception handing"> for further details.
3734
3735 =cut
3736 */
3737
3738 STATIC OP *
3739 S_docatch(pTHX_ Perl_ppaddr_t firstpp)
3740 {
3741     int ret;
3742     OP * const oldop = PL_op;
3743     dJMPENV;
3744
3745     assert(CATCH_GET);
3746     JMPENV_PUSH(ret);
3747     assert(!CATCH_GET);
3748
3749     switch (ret) {
3750     case 0: /* normal flow-of-control return from JMPENV_PUSH */
3751
3752         /* re-run the current op, this time executing the full body of the
3753          * pp function */
3754         PL_op = firstpp(aTHX);
3755  redo_body:
3756         if (PL_op) {
3757             CALLRUNOPS(aTHX);
3758         }
3759         break;
3760
3761     case 3: /* an exception raised within an eval */
3762         if (PL_restartjmpenv == PL_top_env) {
3763             /* die caught by an inner eval - continue inner loop */
3764
3765             if (!PL_restartop)
3766                 break;
3767             PL_restartjmpenv = NULL;
3768             PL_op = PL_restartop;
3769             PL_restartop = 0;
3770             goto redo_body;
3771         }
3772         /* FALLTHROUGH */
3773
3774     default:
3775         JMPENV_POP;
3776         PL_op = oldop;
3777         JMPENV_JUMP(ret); /* re-throw the exception */
3778         NOT_REACHED; /* NOTREACHED */
3779     }
3780     JMPENV_POP;
3781     PL_op = oldop;
3782     return NULL;
3783 }
3784
3785
3786 /*
3787 =for apidoc find_runcv
3788
3789 Locate the CV corresponding to the currently executing sub or eval.
3790 If C<db_seqp> is non_null, skip CVs that are in the DB package and populate
3791 C<*db_seqp> with the cop sequence number at the point that the DB:: code was
3792 entered.  (This allows debuggers to eval in the scope of the breakpoint
3793 rather than in the scope of the debugger itself.)
3794
3795 =cut
3796 */
3797
3798 CV*
3799 Perl_find_runcv(pTHX_ U32 *db_seqp)
3800 {
3801     return Perl_find_runcv_where(aTHX_ 0, 0, db_seqp);
3802 }
3803
3804 /* If this becomes part of the API, it might need a better name. */
3805 CV *
3806 Perl_find_runcv_where(pTHX_ U8 cond, IV arg, U32 *db_seqp)
3807 {
3808     PERL_SI      *si;
3809     int          level = 0;
3810
3811     if (db_seqp)
3812         *db_seqp =
3813             PL_curcop == &PL_compiling
3814                 ? PL_cop_seqmax
3815                 : PL_curcop->cop_seq;
3816
3817     for (si = PL_curstackinfo; si; si = si->si_prev) {
3818         I32 ix;
3819         for (ix = si->si_cxix; ix >= 0; ix--) {
3820             const PERL_CONTEXT *cx = &(si->si_cxstack[ix]);
3821             CV *cv = NULL;
3822             if (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT) {
3823                 cv = cx->blk_sub.cv;
3824                 /* skip DB:: code */
3825                 if (db_seqp && PL_debstash && CvSTASH(cv) == PL_debstash) {
3826                     *db_seqp = cx->blk_oldcop->cop_seq;
3827                     continue;
3828                 }
3829                 if (cx->cx_type & CXp_SUB_RE)
3830                     continue;
3831             }
3832             else if (CxTYPE(cx) == CXt_EVAL && !CxEVALBLOCK(cx))
3833                 cv = cx->blk_eval.cv;
3834             if (cv) {
3835                 switch (cond) {
3836                 case FIND_RUNCV_padid_eq:
3837                     if (!CvPADLIST(cv)
3838                      || CvPADLIST(cv)->xpadl_id != (U32)arg)
3839                         continue;
3840                     return cv;
3841                 case FIND_RUNCV_level_eq:
3842                     if (level++ != arg) continue;
3843                     /* FALLTHROUGH */
3844                 default:
3845                     return cv;
3846                 }
3847             }
3848         }
3849     }
3850     return cond == FIND_RUNCV_padid_eq ? NULL : PL_main_cv;
3851 }
3852
3853
3854 /* S_try_yyparse():
3855  *
3856  * Run yyparse() in a setjmp wrapper. Returns:
3857  *   0: yyparse() successful
3858  *   1: yyparse() failed
3859  *   3: yyparse() died
3860  *
3861  * This is used to trap Perl_croak() calls that are executed
3862  * during the compilation process and before the code has been
3863  * completely compiled. It is expected to be called from
3864  * doeval_compile() only. The parameter 'caller_op' is
3865  * only used in DEBUGGING to validate the logic is working
3866  * correctly.
3867  *
3868  * See also try_run_unitcheck().
3869  *
3870  */
3871 STATIC int
3872 S_try_yyparse(pTHX_ int gramtype, OP *caller_op)
3873 {
3874     /* if we die during compilation PL_restartop and PL_restartjmpenv
3875      * will be set by Perl_die_unwind(). We need to restore their values
3876      * if that happens as they are intended for the case where the code
3877      * compiles and dies during execution, not where it dies during
3878      * compilation. PL_restartop and caller_op->op_next should be the
3879      * same anyway, and when compilation fails then caller_op->op_next is
3880      * used as the next op after the compile.
3881      */
3882     JMPENV *restartjmpenv = PL_restartjmpenv;
3883     OP *restartop = PL_restartop;
3884     dJMPENV;
3885     int ret;
3886     PERL_UNUSED_ARG(caller_op); /* only used in debugging builds */
3887
3888     assert(CxTYPE(CX_CUR()) == CXt_EVAL);
3889     JMPENV_PUSH(ret);
3890     switch (ret) {
3891     case 0:
3892         ret = yyparse(gramtype) ? 1 : 0;
3893         break;
3894     case 3:
3895         /* yyparse() died and we trapped the error. We need to restore
3896          * the old PL_restartjmpenv and PL_restartop values. */
3897         assert(PL_restartop == caller_op->op_next); /* we expect these to match */
3898         PL_restartjmpenv = restartjmpenv;
3899         PL_restartop = restartop;
3900         break;
3901     default:
3902         JMPENV_POP;
3903         JMPENV_JUMP(ret);
3904         NOT_REACHED; /* NOTREACHED */
3905     }
3906     JMPENV_POP;
3907     return ret;
3908 }
3909
3910 /* S_try_run_unitcheck()
3911  *
3912  * Run PL_unitcheckav in a setjmp wrapper via call_list.
3913  * Returns:
3914  *   0: unitcheck blocks ran without error
3915  *   3: a unitcheck block died
3916  *
3917  * This is used to trap Perl_croak() calls that are executed
3918  * during UNITCHECK blocks executed after the compilation
3919  * process has completed but before the code itself has been
3920  * executed via the normal run loops. It is expected to be called
3921  * from doeval_compile() only. The parameter 'caller_op' is
3922  * only used in DEBUGGING to validate the logic is working
3923  * correctly.
3924  *
3925  * See also try_yyparse().
3926  */
3927 STATIC int
3928 S_try_run_unitcheck(pTHX_ OP* caller_op)
3929 {
3930     /* if we die during compilation PL_restartop and PL_restartjmpenv
3931      * will be set by Perl_die_unwind(). We need to restore their values
3932      * if that happens as they are intended for the case where the code
3933      * compiles and dies during execution, not where it dies during
3934      * compilation. UNITCHECK runs after compilation completes, and
3935      * if it dies we will execute the PL_restartop anyway via the
3936      * failed compilation code path. PL_restartop and caller_op->op_next
3937      * should be the same anyway, and when compilation fails then
3938      * caller_op->op_next is  used as the next op after the compile.
3939      */
3940     JMPENV *restartjmpenv = PL_restartjmpenv;
3941     OP *restartop = PL_restartop;
3942     dJMPENV;
3943     int ret;
3944     PERL_UNUSED_ARG(caller_op); /* only used in debugging builds */
3945
3946     assert(CxTYPE(CX_CUR()) == CXt_EVAL);
3947     JMPENV_PUSH(ret);
3948     switch (ret) {
3949     case 0:
3950         call_list(PL_scopestack_ix, PL_unitcheckav);
3951         break;
3952     case 3:
3953         /* call_list died */
3954         /* call_list() died and we trapped the error. We should restore
3955          * the old PL_restartjmpenv and PL_restartop values, as they are
3956          * used only in the case where the code was actually run.
3957          * The assert validates that we will still execute the PL_restartop.
3958          */
3959         assert(PL_restartop == caller_op->op_next); /* we expect these to match */
3960         PL_restartjmpenv = restartjmpenv;
3961         PL_restartop = restartop;
3962         break;
3963     default:
3964         JMPENV_POP;
3965         JMPENV_JUMP(ret);
3966         NOT_REACHED; /* NOTREACHED */
3967     }
3968     JMPENV_POP;
3969     return ret;
3970 }
3971
3972 /* Compile a require/do or an eval ''.
3973  *
3974  * outside is the lexically enclosing CV (if any) that invoked us.
3975  * seq     is the current COP scope value.
3976  * hh      is the saved hints hash, if any.
3977  *
3978  * Returns a bool indicating whether the compile was successful; if so,
3979  * PL_eval_start contains the first op of the compiled code; otherwise,
3980  * pushes undef.
3981  *
3982  * This function is called from two places: pp_require and pp_entereval.
3983  * These can be distinguished by whether PL_op is entereval.
3984  */
3985
3986 STATIC bool
3987 S_doeval_compile(pTHX_ U8 gimme, CV* outside, U32 seq, HV *hh)
3988 {
3989     OP * const saveop = PL_op;
3990     bool clear_hints = saveop->op_type != OP_ENTEREVAL;
3991     COP * const oldcurcop = PL_curcop;
3992     bool in_require = (saveop->op_type == OP_REQUIRE);
3993     int yystatus;
3994     CV *evalcv;
3995
3996     PL_in_eval = (in_require
3997                   ? (EVAL_INREQUIRE | (PL_in_eval & EVAL_INEVAL))
3998                   : (EVAL_INEVAL |
3999                         ((PL_op->op_private & OPpEVAL_RE_REPARSING)
4000                             ? EVAL_RE_REPARSING : 0)));
4001
4002     PUSHMARK(PL_stack_sp);
4003
4004     evalcv = MUTABLE_CV(newSV_type(SVt_PVCV));
4005     CvEVAL_on(evalcv);
4006     assert(CxTYPE(CX_CUR()) == CXt_EVAL);
4007     CX_CUR()->blk_eval.cv = evalcv;
4008     CX_CUR()->blk_gimme = gimme;
4009
4010     CvOUTSIDE_SEQ(evalcv) = seq;
4011     CvOUTSIDE(evalcv) = MUTABLE_CV(SvREFCNT_inc_simple(outside));
4012
4013     /* set up a scratch pad */
4014
4015     CvPADLIST_set(evalcv, pad_new(padnew_SAVE));
4016     PL_op = NULL; /* avoid PL_op and PL_curpad referring to different CVs */
4017
4018
4019     SAVEMORTALIZESV(evalcv);    /* must remain until end of current statement */
4020
4021     /* make sure we compile in the right package */
4022
4023     if (CopSTASH_ne(PL_curcop, PL_curstash)) {
4024         SAVEGENERICSV(PL_curstash);
4025         PL_curstash = (HV *)CopSTASH(PL_curcop);
4026         if (SvTYPE(PL_curstash) != SVt_PVHV) PL_curstash = NULL;
4027         else {
4028             SvREFCNT_inc_simple_void(PL_curstash);
4029             save_item(PL_curstname);
4030             sv_sethek(PL_curstname, HvNAME_HEK(PL_curstash));
4031         }
4032     }
4033     /* XXX:ajgo do we really need to alloc an AV for begin/checkunit */
4034     SAVESPTR(PL_beginav);
4035     PL_beginav = newAV();
4036     SAVEFREESV(PL_beginav);
4037     SAVESPTR(PL_unitcheckav);
4038     PL_unitcheckav = newAV();
4039     SAVEFREESV(PL_unitcheckav);
4040
4041
4042     ENTER_with_name("evalcomp");
4043     SAVESPTR(PL_compcv);
4044     PL_compcv = evalcv;
4045
4046     /* try to compile it */
4047
4048     PL_eval_root = NULL;
4049     PL_curcop = &PL_compiling;
4050     if ((saveop->op_type != OP_REQUIRE) && (saveop->op_flags & OPf_SPECIAL))
4051         PL_in_eval |= EVAL_KEEPERR;
4052     else
4053         CLEAR_ERRSV();
4054
4055     SAVEHINTS();
4056     if (clear_hints) {
4057         PL_hints = HINTS_DEFAULT;
4058         PL_prevailing_version = 0;
4059         hv_clear(GvHV(PL_hintgv));
4060         CLEARFEATUREBITS();
4061     }
4062     else {
4063         PL_hints = saveop->op_private & OPpEVAL_COPHH
4064                      ? oldcurcop->cop_hints : (U32)saveop->op_targ;
4065
4066         /* making 'use re eval' not be in scope when compiling the
4067          * qr/mabye_has_runtime_code_block/ ensures that we don't get
4068          * infinite recursion when S_has_runtime_code() gives a false
4069          * positive: the second time round, HINT_RE_EVAL isn't set so we
4070          * don't bother calling S_has_runtime_code() */
4071         if (PL_in_eval & EVAL_RE_REPARSING)
4072             PL_hints &= ~HINT_RE_EVAL;
4073
4074         if (hh) {
4075             /* SAVEHINTS created a new HV in PL_hintgv, which we need to GC */
4076             SvREFCNT_dec(GvHV(PL_hintgv));
4077             GvHV(PL_hintgv) = hh;
4078             FETCHFEATUREBITSHH(hh);
4079         }
4080     }
4081     SAVECOMPILEWARNINGS();
4082     if (clear_hints) {
4083         if (PL_dowarn & G_WARN_ALL_ON)
4084             PL_compiling.cop_warnings = pWARN_ALL ;
4085         else if (PL_dowarn & G_WARN_ALL_OFF)
4086             PL_compiling.cop_warnings = pWARN_NONE ;
4087         else
4088             PL_compiling.cop_warnings = pWARN_STD ;
4089     }
4090     else {
4091         PL_compiling.cop_warnings =
4092             DUP_WARNINGS(oldcurcop->cop_warnings);
4093         cophh_free(CopHINTHASH_get(&PL_compiling));
4094         if (Perl_cop_fetch_label(aTHX_ oldcurcop, NULL, NULL)) {
4095             /* The label, if present, is the first entry on the chain. So rather
4096                than writing a blank label in front of it (which involves an
4097                allocation), just use the next entry in the chain.  */
4098             PL_compiling.cop_hints_hash
4099                 = cophh_copy(oldcurcop->cop_hints_hash->refcounted_he_next);
4100             /* Check the assumption that this removed the label.  */
4101             assert(Perl_cop_fetch_label(aTHX_ &PL_compiling, NULL, NULL) == NULL);
4102         }
4103         else
4104             PL_compiling.cop_hints_hash = cophh_copy(oldcurcop->cop_hints_hash);
4105     }
4106
4107     CALL_BLOCK_HOOKS(bhk_eval, saveop);
4108
4109     /* we should never be CATCH_GET true here, as our immediate callers should
4110      * always handle that case. */
4111     assert(!CATCH_GET);
4112     /* compile the code */
4113
4114
4115     yystatus = (!in_require)
4116                ? S_try_yyparse(aTHX_ GRAMPROG, saveop)
4117                : yyparse(GRAMPROG);
4118
4119     if (yystatus || PL_parser->error_count || !PL_eval_root) {
4120         PERL_CONTEXT *cx;
4121         SV *errsv;
4122
4123         PL_op = saveop;
4124         if (yystatus != 3) {
4125             /* note that if yystatus == 3, then the require/eval died during
4126              * compilation, so the EVAL CX block has already been popped, and
4127              * various vars restored. This block applies similar steps after
4128              * the other "failed to compile" cases in yyparse, eg, where
4129              * yystatus=1, "failed, but did not die". */
4130
4131             if (!in_require)
4132                 invoke_exception_hook(ERRSV,FALSE);
4133
4134             op_free(PL_eval_root);
4135             PL_eval_root = NULL;
4136
4137             rpp_popfree_to(PL_stack_base + POPMARK); /* pop original mark */
4138             cx = CX_CUR();
4139             assert(CxTYPE(cx) == CXt_EVAL);
4140             /* If we are in an eval we need to make sure that $SIG{__DIE__}
4141              * handler is invoked so we simulate that part of the
4142              * Perl_die_unwind() process. In a require we will croak
4143              * so it will happen there. */
4144             /* pop the CXt_EVAL, and if was a require, croak */
4145             S_pop_eval_context_maybe_croak(aTHX_ cx, ERRSV, 2);
4146
4147         }
4148
4149         /* die_unwind() re-croaks when in require, having popped the
4150          * require EVAL context. So we should never catch a require
4151          * exception here */
4152         assert(!in_require);
4153
4154         errsv = ERRSV;
4155         if (!*(SvPV_nolen_const(errsv)))
4156             sv_setpvs(errsv, "Compilation error");
4157
4158         if (gimme == G_SCALAR) {
4159             if (yystatus == 3) {
4160                 /* die_unwind already pushed undef in scalar context */
4161                 assert(*PL_stack_sp == &PL_sv_undef);
4162             }
4163             else {
4164                 rpp_xpush_1(&PL_sv_undef);
4165             }
4166         }
4167         return FALSE;
4168     }
4169
4170     /* Compilation successful. Now clean up */
4171
4172     LEAVE_with_name("evalcomp");
4173
4174     CopLINE_set(&PL_compiling, 0);
4175     SAVEFREEOP(PL_eval_root);
4176     cv_forget_slab(evalcv);
4177
4178     DEBUG_x(dump_eval());
4179
4180     /* Register with debugger: */
4181     if (PERLDB_INTER && saveop->op_type == OP_REQUIRE) {
4182         CV * const cv = get_cvs("DB::postponed", 0);
4183         if (cv) {
4184             PUSHMARK(PL_stack_sp);
4185             rpp_xpush_1(MUTABLE_SV(CopFILEGV(&PL_compiling)));
4186             call_sv(MUTABLE_SV(cv), G_DISCARD);
4187         }
4188     }
4189
4190     if (PL_unitcheckav && av_count(PL_unitcheckav)>0) {
4191         OP *es = PL_eval_start;
4192         /* TODO: are we sure we shouldn't do S_try_run_unitcheck()
4193         * when `in_require` is true? */
4194         if (in_require) {
4195             call_list(PL_scopestack_ix, PL_unitcheckav);
4196         }
4197         else if (S_try_run_unitcheck(aTHX_ saveop)) {
4198             /* there was an error! */
4199
4200             /* Restore PL_OP */
4201             PL_op = saveop;
4202
4203             SV *errsv = ERRSV;
4204             if (!*(SvPV_nolen_const(errsv))) {
4205                 /* This happens when using:
4206                  * eval qq# UNITCHECK { die "\x00"; } #;
4207                  */
4208                 sv_setpvs(errsv, "Unit check error");
4209             }
4210
4211             if (gimme != G_LIST)
4212                 rpp_xpush_1(&PL_sv_undef);
4213             return FALSE;
4214         }
4215         PL_eval_start = es;
4216     }
4217
4218     CvDEPTH(evalcv) = 1;
4219     rpp_popfree_to_NN(PL_stack_base + POPMARK); /* pop original mark */
4220     PL_op = saveop;                     /* The caller may need it. */
4221     PL_parser->lex_state = LEX_NOTPARSING;      /* $^S needs this. */
4222
4223     return TRUE;
4224 }
4225
4226
4227 /* Return NULL if the file doesn't exist or isn't a file;
4228  * else return PerlIO_openn().
4229  */
4230
4231 STATIC PerlIO *
4232 S_check_type_and_open(pTHX_ SV *name)
4233 {
4234     Stat_t st;
4235     STRLEN len;
4236     PerlIO * retio;
4237     const char *p = SvPV_const(name, len);
4238     int st_rc;
4239
4240     PERL_ARGS_ASSERT_CHECK_TYPE_AND_OPEN;
4241
4242     /* checking here captures a reasonable error message when
4243      * PERL_DISABLE_PMC is true, but when PMC checks are enabled, the
4244      * user gets a confusing message about looking for the .pmc file
4245      * rather than for the .pm file so do the check in S_doopen_pm when
4246      * PMC is on instead of here. S_doopen_pm calls this func.
4247      * This check prevents a \0 in @INC causing problems.
4248      */
4249 #ifdef PERL_DISABLE_PMC
4250     if (!IS_SAFE_PATHNAME(p, len, "require"))
4251         return NULL;
4252 #endif
4253
4254     /* on Win32 stat is expensive (it does an open() and close() twice and
4255        a couple other IO calls), the open will fail with a dir on its own with
4256        errno EACCES, so only do a stat to separate a dir from a real EACCES
4257        caused by user perms */
4258 #ifndef WIN32
4259     st_rc = PerlLIO_stat(p, &st);
4260
4261     if (st_rc < 0)
4262         return NULL;
4263     else {
4264         int eno;
4265         if(S_ISBLK(st.st_mode)) {
4266             eno = EINVAL;
4267             goto not_file;
4268         }
4269         else if(S_ISDIR(st.st_mode)) {
4270             eno = EISDIR;
4271             not_file:
4272             errno = eno;
4273             return NULL;
4274         }
4275     }
4276 #endif
4277
4278     retio = PerlIO_openn(aTHX_ ":", PERL_SCRIPT_MODE, -1, 0, 0, NULL, 1, &name);
4279 #ifdef WIN32
4280     /* EACCES stops the INC search early in pp_require to implement
4281        feature RT #113422 */
4282     if(!retio && errno == EACCES) { /* exists but probably a directory */
4283         int eno;
4284         st_rc = PerlLIO_stat(p, &st);
4285         if (st_rc >= 0) {
4286             if(S_ISDIR(st.st_mode))
4287                 eno = EISDIR;
4288             else if(S_ISBLK(st.st_mode))
4289                 eno = EINVAL;
4290             else
4291                 eno = EACCES;
4292             errno = eno;
4293         }
4294     }
4295 #endif
4296     return retio;
4297 }
4298
4299 /* doopen_pm(): return the equivalent of PerlIO_openn() on the given name,
4300  * but first check for bad names (\0) and non-files.
4301  * Also if the filename ends in .pm and unless PERL_DISABLE_PMC,
4302  * try loading Foo.pmc first.
4303  */
4304 #ifndef PERL_DISABLE_PMC
4305 STATIC PerlIO *
4306 S_doopen_pm(pTHX_ SV *name)
4307 {
4308     STRLEN namelen;
4309     const char *p = SvPV_const(name, namelen);
4310
4311     PERL_ARGS_ASSERT_DOOPEN_PM;
4312
4313     /* check the name before trying for the .pmc name to avoid the
4314      * warning referring to the .pmc which the user probably doesn't
4315      * know or care about
4316      */
4317     if (!IS_SAFE_PATHNAME(p, namelen, "require"))
4318         return NULL;
4319
4320     if (memENDPs(p, namelen, ".pm")) {
4321         SV *const pmcsv = sv_newmortal();
4322         PerlIO * pmcio;
4323
4324         SvSetSV_nosteal(pmcsv,name);
4325         sv_catpvs(pmcsv, "c");
4326
4327         pmcio = check_type_and_open(pmcsv);
4328         if (pmcio)
4329             return pmcio;
4330     }
4331     return check_type_and_open(name);
4332 }
4333 #else
4334 #  define doopen_pm(name) check_type_and_open(name)
4335 #endif /* !PERL_DISABLE_PMC */
4336
4337 /* require doesn't search in @INC for absolute names, or when the name is
4338    explicitly relative the current directory: i.e. ./, ../ */
4339 PERL_STATIC_INLINE bool
4340 S_path_is_searchable(const char *name)
4341 {
4342     PERL_ARGS_ASSERT_PATH_IS_SEARCHABLE;
4343
4344     if (PERL_FILE_IS_ABSOLUTE(name)
4345 #ifdef WIN32
4346         || (*name == '.' && ((name[1] == '/' ||
4347                              (name[1] == '.' && name[2] == '/'))
4348                          || (name[1] == '\\' ||
4349                              ( name[1] == '.' && name[2] == '\\')))
4350             )
4351 #else
4352         || (*name == '.' && (name[1] == '/' ||
4353                              (name[1] == '.' && name[2] == '/')))
4354 #endif
4355          )
4356     {
4357         return FALSE;
4358     }
4359     else
4360         return TRUE;
4361 }
4362
4363
4364 /* implement 'require 5.010001' */
4365
4366 static OP *
4367 S_require_version(pTHX_ SV *sv)
4368 {
4369     sv = sv_2mortal(new_version(sv));
4370     rpp_popfree_1_NN();
4371
4372     if (!Perl_sv_derived_from_pvn(aTHX_ PL_patchlevel, STR_WITH_LEN("version"), 0))
4373         upg_version(PL_patchlevel, TRUE);
4374     if (cUNOP->op_first->op_type == OP_CONST && cUNOP->op_first->op_private & OPpCONST_NOVER) {
4375         if ( vcmp(sv,PL_patchlevel) <= 0 )
4376             DIE(aTHX_ "Perls since %" SVf " too modern--this is %" SVf ", stopped",
4377                 SVfARG(sv_2mortal(vnormal(sv))),
4378                 SVfARG(sv_2mortal(vnormal(PL_patchlevel)))
4379             );
4380     }
4381     else {
4382         if ( vcmp(sv,PL_patchlevel) > 0 ) {
4383             I32 first = 0;
4384             AV *lav;
4385             SV * const req = SvRV(sv);
4386             SV * const pv = *hv_fetchs(MUTABLE_HV(req), "original", FALSE);
4387
4388             /* get the left hand term */
4389             lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(req), "version", FALSE)));
4390
4391             first  = SvIV(*av_fetch(lav,0,0));
4392             if (   first > (int)PERL_REVISION    /* probably 'use 6.0' */
4393                 || hv_exists(MUTABLE_HV(req), "qv", 2 ) /* qv style */
4394                 || av_count(lav) > 2             /* FP with > 3 digits */
4395                 || strstr(SvPVX(pv),".0")        /* FP with leading 0 */
4396                ) {
4397                 DIE(aTHX_ "Perl %" SVf " required--this is only "
4398                     "%" SVf ", stopped",
4399                     SVfARG(sv_2mortal(vnormal(req))),
4400                     SVfARG(sv_2mortal(vnormal(PL_patchlevel)))
4401                 );
4402             }
4403             else { /* probably 'use 5.10' or 'use 5.8' */
4404                 SV *hintsv;
4405                 I32 second = 0;
4406
4407                 if (av_count(lav) > 1)
4408                     second = SvIV(*av_fetch(lav,1,0));
4409
4410                 second /= second >= 600  ? 100 : 10;
4411                 hintsv = Perl_newSVpvf(aTHX_ "v%d.%d.0",
4412                                        (int)first, (int)second);
4413                 upg_version(hintsv, TRUE);
4414
4415                 DIE(aTHX_ "Perl %" SVf " required (did you mean %" SVf "?)"
4416                     "--this is only %" SVf ", stopped",
4417                     SVfARG(sv_2mortal(vnormal(req))),
4418                     SVfARG(sv_2mortal(vnormal(sv_2mortal(hintsv)))),
4419                     SVfARG(sv_2mortal(vnormal(PL_patchlevel)))
4420                 );
4421             }
4422         }
4423     }
4424
4425     rpp_push_IMM(&PL_sv_yes);
4426     return NORMAL;
4427 }
4428
4429
4430 /* Handle C<require Foo::Bar>, C<require "Foo/Bar.pm"> and C<do "Foo.pm">.
4431  * The first form will have already been converted at compile time to
4432  * the second form.
4433  * sv is still on the stack at this point. */
4434
4435 static OP *
4436 S_require_file(pTHX_ SV *sv)
4437 {
4438     PERL_CONTEXT *cx;
4439     const char *name;
4440     STRLEN len;
4441     char * unixname;
4442     STRLEN unixlen;
4443 #ifdef VMS
4444     int vms_unixname = 0;
4445     char *unixdir;
4446 #endif
4447     /* tryname is the actual pathname (with @INC prefix) which was loaded.
4448      * It's stored as a value in %INC, and used for error messages */
4449     const char *tryname = NULL;
4450     SV *namesv = NULL; /* SV equivalent of tryname */
4451     const U8 gimme = GIMME_V;
4452     int filter_has_file = 0;
4453     PerlIO *tryrsfp = NULL;
4454     SV *filter_cache = NULL;
4455     SV *filter_state = NULL;
4456     SV *filter_sub = NULL;
4457     SV *hook_sv = NULL;
4458     OP *op;
4459     int saved_errno;
4460     bool path_searchable;
4461     I32 old_savestack_ix;
4462     const bool op_is_require = PL_op->op_type == OP_REQUIRE;
4463     const char *const op_name = op_is_require ? "require" : "do";
4464     SV ** svp_cached = NULL;
4465
4466     assert(op_is_require || PL_op->op_type == OP_DOFILE);
4467
4468     if (!SvOK(sv))
4469         DIE(aTHX_ "Missing or undefined argument to %s", op_name);
4470     name = SvPV_nomg_const(sv, len);
4471     if (!(name && len > 0 && *name))
4472         DIE(aTHX_ "Missing or undefined argument to %s", op_name);
4473
4474     if (
4475         PL_hook__require__before
4476         && SvROK(PL_hook__require__before)
4477         && SvTYPE(SvRV(PL_hook__require__before)) == SVt_PVCV
4478     ) {
4479         SV* name_sv = sv_mortalcopy(sv);
4480         SV *post_hook__require__before_sv = NULL;
4481
4482         ENTER_with_name("call_PRE_REQUIRE");
4483         SAVETMPS;
4484         PUSHMARK(PL_stack_sp);
4485         rpp_xpush_1(name_sv); /* always use the object for method calls */
4486         call_sv(PL_hook__require__before, G_SCALAR);
4487         SV *rsv = *PL_stack_sp;
4488         if (SvOK(rsv) && SvROK(rsv) && SvTYPE(SvRV(rsv)) == SVt_PVCV) {
4489             /* the RC++ preserves it across the popping and/or FREETMPS
4490              * below */
4491             post_hook__require__before_sv = SvREFCNT_inc_simple_NN(rsv);
4492             rpp_popfree_1_NN();
4493         }
4494         if (!sv_streq(name_sv,sv)) {
4495             /* they modified the name argument, so do some sleight of hand */
4496             name = SvPV_nomg_const(name_sv, len);
4497             if (!(name && len > 0 && *name))
4498                 DIE(aTHX_ "Missing or undefined argument to %s via %%{^HOOK}{require__before}",
4499                         op_name);
4500             sv = name_sv;
4501         }
4502         FREETMPS;
4503         LEAVE_with_name("call_PRE_REQUIRE");
4504         if (post_hook__require__before_sv) {
4505             SV *nsv = newSVsv(sv);
4506             MORTALDESTRUCTOR_SV(post_hook__require__before_sv, nsv);
4507             SvREFCNT_dec_NN(nsv);
4508             SvREFCNT_dec_NN(post_hook__require__before_sv);
4509         }
4510     }
4511     if (
4512         PL_hook__require__after
4513         && SvROK(PL_hook__require__after)
4514         && SvTYPE(SvRV(PL_hook__require__after)) == SVt_PVCV
4515     ) {
4516         SV *nsv = newSVsv(sv);
4517         MORTALDESTRUCTOR_SV(PL_hook__require__after, nsv);
4518         SvREFCNT_dec_NN(nsv);
4519     }
4520
4521 #ifndef VMS
4522         /* try to return earlier (save the SAFE_PATHNAME check) if INC already got the name */
4523         if (op_is_require) {
4524                 /* can optimize to only perform one single lookup */
4525                 svp_cached = hv_fetch(GvHVn(PL_incgv), (char*) name, len, 0);
4526                 if (svp_cached &&
4527                     (SvGETMAGIC(*svp_cached), SvOK(*svp_cached)))
4528                 {
4529                     rpp_replace_1_IMM_NN(&PL_sv_yes);
4530                     return NORMAL;
4531                 }
4532         }
4533 #endif
4534
4535     if (!IS_SAFE_PATHNAME(name, len, op_name)) {
4536         if (!op_is_require) {
4537             CLEAR_ERRSV();
4538             rpp_replace_1_IMM_NN(&PL_sv_undef);
4539             return NORMAL;
4540         }
4541         DIE(aTHX_ "Can't locate %s:   %s",
4542             pv_escape(newSVpvs_flags("",SVs_TEMP),name,len,len*2,
4543                       NULL, SvUTF8(sv)?PERL_PV_ESCAPE_UNI:0),
4544             Strerror(ENOENT));
4545     }
4546     TAINT_PROPER(op_name);
4547
4548     path_searchable = path_is_searchable(name);
4549
4550 #ifdef VMS
4551     /* The key in the %ENV hash is in the syntax of file passed as the argument
4552      * usually this is in UNIX format, but sometimes in VMS format, which
4553      * can result in a module being pulled in more than once.
4554      * To prevent this, the key must be stored in UNIX format if the VMS
4555      * name can be translated to UNIX.
4556      */
4557     
4558     if ((unixname =
4559           tounixspec(name, SvPVX(sv_2mortal(newSVpv("", VMS_MAXRSS-1)))))
4560          != NULL) {
4561         unixlen = strlen(unixname);
4562         vms_unixname = 1;
4563     }
4564     else
4565 #endif
4566     {
4567         /* if not VMS or VMS name can not be translated to UNIX, pass it
4568          * through.
4569          */
4570         unixname = (char *) name;
4571         unixlen = len;
4572     }
4573     if (op_is_require) {
4574         /* reuse the previous hv_fetch result if possible */
4575         SV * const * const svp = svp_cached ? svp_cached : hv_fetch(GvHVn(PL_incgv), unixname, unixlen, 0);
4576         if ( svp ) {
4577             /* we already did a get magic if this was cached */
4578             if (!svp_cached)
4579                 SvGETMAGIC(*svp);
4580             if (SvOK(*svp)) {
4581                 rpp_replace_1_IMM_NN(&PL_sv_yes);
4582                 return NORMAL;
4583             }
4584             else
4585                 DIE(aTHX_ "Attempt to reload %s aborted.\n"
4586                             "Compilation failed in require", unixname);
4587         }
4588
4589         /*XXX OPf_KIDS should always be true? -dapm 4/2017 */
4590         if (PL_op->op_flags & OPf_KIDS) {
4591             SVOP * const kid = cSVOPx(cUNOP->op_first);
4592
4593             if (kid->op_type == OP_CONST && (kid->op_private & OPpCONST_BARE)) {
4594                 /* Make sure that a bareword module name (e.g. ::Foo::Bar)
4595                  * doesn't map to a naughty pathname like /Foo/Bar.pm.
4596                  * Note that the parser will normally detect such errors
4597                  * at compile time before we reach here, but
4598                  * Perl_load_module() can fake up an identical optree
4599                  * without going near the parser, and being able to put
4600                  * anything as the bareword. So we include a duplicate set
4601                  * of checks here at runtime.
4602                  */
4603                 const STRLEN package_len = len - 3;
4604                 const char slashdot[2] = {'/', '.'};
4605 #ifdef DOSISH
4606                 const char backslashdot[2] = {'\\', '.'};
4607 #endif
4608
4609                 /* Disallow *purported* barewords that map to absolute
4610                    filenames, filenames relative to the current or parent
4611                    directory, or (*nix) hidden filenames.  Also sanity check
4612                    that the generated filename ends .pm  */
4613                 if (!path_searchable || len < 3 || name[0] == '.'
4614                     || !memEQs(name + package_len, len - package_len, ".pm"))
4615                     DIE(aTHX_ "Bareword in require maps to disallowed filename \"%" SVf "\"", sv);
4616                 if (memchr(name, 0, package_len)) {
4617                     /* diag_listed_as: Bareword in require contains "%s" */
4618                     DIE(aTHX_ "Bareword in require contains \"\\0\"");
4619                 }
4620                 if (ninstr(name, name + package_len, slashdot,
4621                            slashdot + sizeof(slashdot))) {
4622                     /* diag_listed_as: Bareword in require contains "%s" */
4623                     DIE(aTHX_ "Bareword in require contains \"/.\"");
4624                 }
4625 #ifdef DOSISH
4626                 if (ninstr(name, name + package_len, backslashdot,
4627                            backslashdot + sizeof(backslashdot))) {
4628                     /* diag_listed_as: Bareword in require contains "%s" */
4629                     DIE(aTHX_ "Bareword in require contains \"\\.\"");
4630                 }
4631 #endif
4632             }
4633         }
4634     }
4635
4636     PERL_DTRACE_PROBE_FILE_LOADING(unixname);
4637
4638     /* Try to locate and open a file, possibly using @INC  */
4639
4640     /* with "/foo/bar.pm", "./foo.pm" and "../foo/bar.pm", try to load
4641      * the file directly rather than via @INC ... */
4642     if (!path_searchable) {
4643         /* At this point, name is SvPVX(sv)  */
4644         tryname = name;
4645         tryrsfp = doopen_pm(sv);
4646     }
4647
4648     /* ... but if we fail, still search @INC for code references;
4649      * these are applied even on non-searchable paths (except
4650      * if we got EACESS).
4651      *
4652      * For searchable paths, just search @INC normally
4653      */
4654     AV *inc_checked = (AV*)sv_2mortal((SV*)newAV());
4655     if (!tryrsfp && !(errno == EACCES && !path_searchable)) {
4656         SSize_t inc_idx;
4657 #ifdef VMS
4658         if (vms_unixname)
4659 #endif
4660         {
4661             AV *incdir_av = (AV*)sv_2mortal((SV*)newAV());
4662             SV *nsv = sv; /* non const copy we can change if necessary */
4663             namesv = newSV_type(SVt_PV);
4664             AV *inc_ar = GvAVn(PL_incgv);
4665             SSize_t incdir_continue_inc_idx = -1;
4666
4667             for (
4668                 inc_idx = 0;
4669                 (AvFILL(incdir_av)>=0 /* we have INCDIR items pending */
4670                     || inc_idx <= AvFILL(inc_ar));  /* @INC entries remain */
4671                 inc_idx++
4672             ) {
4673                 SV *dirsv;
4674
4675                 /* do we have any pending INCDIR items? */
4676                 if (AvFILL(incdir_av)>=0) {
4677                     /* yep, shift it out */
4678                     dirsv = av_shift(incdir_av);
4679                     if (AvFILL(incdir_av)<0) {
4680                         /* incdir is now empty, continue from where
4681                          * we left off after we process this entry  */
4682                         inc_idx = incdir_continue_inc_idx;
4683                     }
4684                 } else {
4685                     dirsv = *av_fetch(inc_ar, inc_idx, TRUE);
4686                 }
4687
4688                 if (SvGMAGICAL(dirsv)) {
4689                     SvGETMAGIC(dirsv);
4690                     dirsv = newSVsv_nomg(dirsv);
4691                 } else {
4692                     /* on the other hand, since we aren't copying we do need
4693                      * to increment */
4694                     SvREFCNT_inc(dirsv);
4695                 }
4696                 if (!SvOK(dirsv))
4697                     continue;
4698
4699                 av_push(inc_checked, dirsv);
4700
4701                 if (SvROK(dirsv)) {
4702                     int count;
4703                     SV **svp;
4704                     SV *loader = dirsv;
4705                     UV diruv = PTR2UV(SvRV(dirsv));
4706
4707                     if (SvTYPE(SvRV(loader)) == SVt_PVAV
4708                         && !SvOBJECT(SvRV(loader)))
4709                     {
4710                         loader = *av_fetch(MUTABLE_AV(SvRV(loader)), 0, TRUE);
4711                         if (SvGMAGICAL(loader)) {
4712                             SvGETMAGIC(loader);
4713                             SV *l = sv_newmortal();
4714                             sv_setsv_nomg(l, loader);
4715                             loader = l;
4716                         }
4717                     }
4718
4719                     if (SvPADTMP(nsv)) {
4720                         nsv = sv_newmortal();
4721                         SvSetSV_nosteal(nsv,sv);
4722                     }
4723
4724                     const char *method = NULL;
4725                     bool is_incdir = FALSE;
4726                     SV * inc_idx_sv = save_scalar(PL_incgv);
4727                     sv_setiv(inc_idx_sv,inc_idx);
4728                     if (sv_isobject(loader)) {
4729                         /* if it is an object and it has an INC method, then
4730                          * call the method.
4731                          */
4732                         HV *pkg = SvSTASH(SvRV(loader));
4733                         GV * gv = gv_fetchmethod_pvn_flags(pkg, "INC", 3, GV_AUTOLOAD);
4734                         if (gv && isGV(gv)) {
4735                             method = "INC";
4736                         } else {
4737                             /* no point to autoload here, it would have been found above */
4738                             gv = gv_fetchmethod_pvn_flags(pkg, "INCDIR", 6, 0);
4739                             if (gv && isGV(gv)) {
4740                                 method = "INCDIR";
4741                                 is_incdir = TRUE;
4742                             }
4743                         }
4744                         /* But if we have no method, check if this is a
4745                          * coderef, if it is then we treat it as an
4746                          * unblessed coderef would be treated: we
4747                          * execute it. If it is some other and it is in
4748                          * an array ref wrapper, then really we don't
4749                          * know what to do with it, (why use the
4750                          * wrapper?) and we throw an exception to help
4751                          * debug. If it is not in a wrapper assume it
4752                          * has an overload and treat it as a string.
4753                          * Maybe in the future we can detect if it does
4754                          * have overloading and throw an error if not.
4755                          */
4756                         if (!method) {
4757                             if (SvTYPE(SvRV(loader)) != SVt_PVCV) {
4758                                 if (amagic_applies(loader,string_amg,AMGf_unary))
4759                                     goto treat_as_string;
4760                                 else {
4761                                     croak("Can't locate object method \"INC\", nor"
4762                                           " \"INCDIR\" nor string overload via"
4763                                           " package %" HvNAMEf_QUOTEDPREFIX " %s"
4764                                           " in @INC", pkg,
4765                                           dirsv == loader
4766                                           ? "in object hook"
4767                                           : "in object in ARRAY hook"
4768                                     );
4769                                 }
4770                             }
4771                         }
4772                     }
4773
4774                     Perl_sv_setpvf(aTHX_ namesv, "/loader/0x%" UVxf "/%s",
4775                                    diruv, name);
4776                     tryname = SvPVX_const(namesv);
4777                     tryrsfp = NULL;
4778
4779                     ENTER_with_name("call_INC_hook");
4780                     SAVETMPS;
4781                     PUSHMARK(PL_stack_sp);
4782                     /* add the args array for method calls */
4783                     bool add_dirsv = (method && (loader != dirsv));
4784                     rpp_extend(2 + add_dirsv);
4785                     rpp_push_2(
4786                         /* always use the object for method calls */
4787                         method ? loader : dirsv,
4788                         nsv
4789                     );
4790                     if (add_dirsv)
4791                         rpp_push_1(dirsv);
4792                     if (method) {
4793                         count = call_method(method, G_LIST|G_EVAL);
4794                     } else {
4795                         count = call_sv(loader, G_LIST|G_EVAL);
4796                     }
4797
4798                     if (count > 0) {
4799                         int i = 0;
4800                         SV *arg;
4801                         SV **base = PL_stack_sp - count + 1;
4802
4803                         if (is_incdir) {
4804                             /* push the stringified returned items into the
4805                              * incdir_av array for processing immediately
4806                              * afterwards. we deliberately stringify or copy
4807                              * "special" arguments, so that overload logic for
4808                              * instance applies, but so that the end result is
4809                              * stable. We speficially do *not* support returning
4810                              * coderefs from an INCDIR call. */
4811                             while (count-->0) {
4812                                 arg = base[i++];
4813                                 SvGETMAGIC(arg);
4814                                 if (!SvOK(arg))
4815                                     continue;
4816                                 if (SvROK(arg)) {
4817                                     STRLEN l;
4818                                     char *pv = SvPV(arg,l);
4819                                     arg = newSVpvn(pv,l);
4820                                 }
4821                                 else if (SvGMAGICAL(arg)) {
4822                                     arg = newSVsv_nomg(arg);
4823                                 }
4824                                 else {
4825                                     SvREFCNT_inc(arg);
4826                                 }
4827                                 av_push(incdir_av, arg);
4828                             }
4829                             /* We copy $INC into incdir_continue_inc_idx
4830                              * so that when we finish processing the items
4831                              * we just inserted into incdir_av we can continue
4832                              * as though we had just finished executing the INCDIR
4833                              * hook. We honour $INC here just like we would for
4834                              * an INC hook, the hook might have rewritten @INC
4835                              * at the same time as returning something to us.
4836                              */
4837                             inc_idx_sv = GvSVn(PL_incgv);
4838                             incdir_continue_inc_idx = SvOK(inc_idx_sv)
4839                                                       ? SvIV(inc_idx_sv) : -1;
4840
4841                             goto done_hook;
4842                         }
4843
4844                         arg = base[i++];
4845
4846                         if (SvROK(arg) && (SvTYPE(SvRV(arg)) <= SVt_PVLV)
4847                             && !isGV_with_GP(SvRV(arg))) {
4848                             filter_cache = SvRV(arg);
4849
4850                             if (i < count) {
4851                                 arg = base[i++];
4852                             }
4853                         }
4854
4855                         if (SvROK(arg) && isGV_with_GP(SvRV(arg))) {
4856                             arg = SvRV(arg);
4857                         }
4858
4859                         if (isGV_with_GP(arg)) {
4860                             IO * const io = GvIO((const GV *)arg);
4861
4862                             ++filter_has_file;
4863
4864                             if (io) {
4865                                 tryrsfp = IoIFP(io);
4866                                 if (IoOFP(io) && IoOFP(io) != IoIFP(io)) {
4867                                     PerlIO_close(IoOFP(io));
4868                                 }
4869                                 IoIFP(io) = NULL;
4870                                 IoOFP(io) = NULL;
4871                             }
4872
4873                             if (i < count) {
4874                                 arg = base[i++];
4875                             }
4876                         }
4877
4878                         if (SvROK(arg) && SvTYPE(SvRV(arg)) == SVt_PVCV) {
4879                             filter_sub = arg;
4880                             SvREFCNT_inc_simple_void_NN(filter_sub);
4881
4882                             if (i < count) {
4883                                 filter_state = base[i];
4884                                 SvREFCNT_inc_simple_void(filter_state);
4885                             }
4886                         }
4887
4888                         if (!tryrsfp && (filter_cache || filter_sub)) {
4889                             tryrsfp = PerlIO_open(BIT_BUCKET,
4890                                                   PERL_SCRIPT_MODE);
4891                         }
4892                       done_hook:
4893                         rpp_popfree_to_NN(base - 1);
4894                     } else {
4895                         SV *errsv= ERRSV;
4896                         if (SvTRUE(errsv) && !SvROK(errsv)) {
4897                             STRLEN l;
4898                             char *pv= SvPV(errsv,l);
4899                             /* Heuristic to tell if this error message
4900                              * includes the standard line number info:
4901                              * check if the line ends in digit dot newline.
4902                              * If it does then we add some extra info so
4903                              * its obvious this is coming from a hook.
4904                              * If it is a user generated error we try to
4905                              * leave it alone. l>12 is to ensure the
4906                              * other checks are in string, but also
4907                              * accounts for "at ... line 1.\n" to a
4908                              * certain extent. Really we should check
4909                              * further, but this is good enough for back
4910                              * compat I think.
4911                              */
4912                             if (l>=12 && pv[l-1] == '\n' && pv[l-2] == '.' && isDIGIT(pv[l-3]))
4913                                 sv_catpvf(errsv, "%s %s hook died--halting @INC search",
4914                                           method ? method : "INC",
4915                                           method ? "method" : "sub");
4916                             croak_sv(errsv);
4917                         }
4918                     }
4919
4920                     /* FREETMPS may free our filter_cache */
4921                     SvREFCNT_inc_simple_void(filter_cache);
4922
4923                     /*
4924                      Let the hook override which @INC entry we visit
4925                      next by setting $INC to a different value than it
4926                      was before we called the hook. If they have
4927                      completely rewritten the array they might want us
4928                      to start traversing from the beginning, which is
4929                      represented by -1. We use undef as an equivalent of
4930                      -1. This can't be used as a way to call a hook
4931                      twice, as we still dedupe.
4932                      We have to do this before we LEAVE, as we localized
4933                      $INC before we called the hook.
4934                     */
4935                     inc_idx_sv = GvSVn(PL_incgv);
4936                     inc_idx = SvOK(inc_idx_sv) ? SvIV(inc_idx_sv) : -1;
4937
4938                     FREETMPS;
4939                     LEAVE_with_name("call_INC_hook");
4940
4941                     /*
4942                      It is possible that @INC has been replaced and that inc_ar
4943                      now points at a freed AV. So we have to refresh it from
4944                      the GV to be sure.
4945                     */
4946                     inc_ar = GvAVn(PL_incgv);
4947
4948                     /* Now re-mortalize it. */
4949                     sv_2mortal(filter_cache);
4950
4951                     /* Adjust file name if the hook has set an %INC entry.
4952                        This needs to happen after the FREETMPS above.  */
4953                     svp = hv_fetch(GvHVn(PL_incgv), name, len, 0);
4954                     /* we have to make sure that the value is not undef
4955                      * or the empty string, if it is then we should not
4956                      * set tryname to it as this will break error messages.
4957                      *
4958                      * This might happen if an @INC hook evals the module
4959                      * which was required in the first place and which
4960                      * triggered the @INC hook, and that eval dies.
4961                      * See https://github.com/Perl/perl5/issues/20535
4962                      */
4963                     if (svp && SvOK(*svp)) {
4964                         STRLEN len;
4965                         const char *tmp_pv = SvPV_const(*svp,len);
4966                         /* we also guard against the deliberate empty string.
4967                          * We do not guard against '0', if people want to set their
4968                          * file name to 0 that is up to them. */
4969                         if (len)
4970                             tryname = tmp_pv;
4971                     }
4972
4973                     if (tryrsfp) {
4974                         hook_sv = dirsv;
4975                         break;
4976                     }
4977
4978                     filter_has_file = 0;
4979                     filter_cache = NULL;
4980                     if (filter_state) {
4981                         SvREFCNT_dec_NN(filter_state);
4982                         filter_state = NULL;
4983                     }
4984                     if (filter_sub) {
4985                         SvREFCNT_dec_NN(filter_sub);
4986                         filter_sub = NULL;
4987                     }
4988                 }
4989                 else
4990                     treat_as_string:
4991                     if (path_searchable) {
4992                     /* match against a plain @INC element (non-searchable
4993                      * paths are only matched against refs in @INC) */
4994                     const char *dir;
4995                     STRLEN dirlen;
4996                     if (SvOK(dirsv)) {
4997                         dir = SvPV_nomg_const(dirsv, dirlen);
4998                     } else {
4999                         dir = "";
5000                         dirlen = 0;
5001                     }
5002
5003                     if (!IS_SAFE_SYSCALL(dir, dirlen, "@INC entry", op_name))
5004                         continue;
5005 #ifdef VMS
5006                     if ((unixdir =
5007                           tounixpath(dir, SvPVX(sv_2mortal(newSVpv("", VMS_MAXRSS-1)))))
5008                          == NULL)
5009                         continue;
5010                     sv_setpv(namesv, unixdir);
5011                     sv_catpv(namesv, unixname);
5012 #else
5013                     /* The equivalent of                    
5014                        Perl_sv_setpvf(aTHX_ namesv, "%s/%s", dir, name);
5015                        but without the need to parse the format string, or
5016                        call strlen on either pointer, and with the correct
5017                        allocation up front.  */
5018                     {
5019                         char *tmp = SvGROW(namesv, dirlen + len + 2);
5020
5021                         memcpy(tmp, dir, dirlen);
5022                         tmp +=dirlen;
5023
5024                         /* Avoid '<dir>//<file>' */
5025                         if (!dirlen || *(tmp-1) != '/') {
5026                             *tmp++ = '/';
5027                         } else {
5028                             /* So SvCUR_set reports the correct length below */
5029                             dirlen--;
5030                         }
5031
5032                         /* name came from an SV, so it will have a '\0' at the
5033                            end that we can copy as part of this memcpy().  */
5034                         memcpy(tmp, name, len + 1);
5035
5036                         SvCUR_set(namesv, dirlen + len + 1);
5037                         SvPOK_on(namesv);
5038                     }
5039 #endif
5040                     TAINT_PROPER(op_name);
5041                     tryname = SvPVX_const(namesv);
5042                     tryrsfp = doopen_pm(namesv);
5043                     if (tryrsfp) {
5044                         if (tryname[0] == '.' && tryname[1] == '/') {
5045                             ++tryname;
5046                             while (*++tryname == '/') {}
5047                         }
5048                         break;
5049                     }
5050                     else if (errno == EMFILE || errno == EACCES) {
5051                         /* no point in trying other paths if out of handles;
5052                          * on the other hand, if we couldn't open one of the
5053                          * files, then going on with the search could lead to
5054                          * unexpected results; see perl #113422
5055                          */
5056                         break;
5057                     }
5058                 }
5059             }
5060         }
5061     }
5062
5063     /* at this point we've ether opened a file (tryrsfp) or set errno */
5064
5065     saved_errno = errno; /* sv_2mortal can realloc things */
5066     sv_2mortal(namesv);
5067     if (!tryrsfp) {
5068         /* we failed; croak if require() or return undef if do() */
5069         if (op_is_require) {
5070             if(saved_errno == EMFILE || saved_errno == EACCES) {
5071                 /* diag_listed_as: Can't locate %s */
5072                 DIE(aTHX_ "Can't locate %s:   %s: %s",
5073                     name, tryname, Strerror(saved_errno));
5074             } else {
5075                 if (path_searchable) {          /* did we lookup @INC? */
5076                     SSize_t i;
5077                     SV *const msg = newSVpvs_flags("", SVs_TEMP);
5078                     SV *const inc = newSVpvs_flags("", SVs_TEMP);
5079                     for (i = 0; i <= AvFILL(inc_checked); i++) {
5080                         SV **svp= av_fetch(inc_checked, i, TRUE);
5081                         if (!svp || !*svp) continue;
5082                         sv_catpvs(inc, " ");
5083                         sv_catsv(inc, *svp);
5084                     }
5085                     if (memENDPs(name, len, ".pm")) {
5086                         const char *e = name + len - (sizeof(".pm") - 1);
5087                         const char *c;
5088                         bool utf8 = cBOOL(SvUTF8(sv));
5089
5090                         /* if the filename, when converted from "Foo/Bar.pm"
5091                          * form back to Foo::Bar form, makes a valid
5092                          * package name (i.e. parseable by C<require
5093                          * Foo::Bar>), then emit a hint.
5094                          *
5095                          * this loop is modelled after the one in
5096                          S_parse_ident */
5097                         c = name;
5098                         while (c < e) {
5099                             if (utf8 && isIDFIRST_utf8_safe(c, e)) {
5100                                 c += UTF8SKIP(c);
5101                                 while (c < e && isIDCONT_utf8_safe(
5102                                             (const U8*) c, (const U8*) e))
5103                                     c += UTF8SKIP(c);
5104                             }
5105                             else if (isWORDCHAR_A(*c)) {
5106                                 while (c < e && isWORDCHAR_A(*c))
5107                                     c++;
5108                             }
5109                             else if (*c == '/')
5110                                 c++;
5111                             else
5112                                 break;
5113                         }
5114
5115                         if (c == e && isIDFIRST_lazy_if_safe(name, e, utf8)) {
5116                             sv_catpvs(msg, " (you may need to install the ");
5117                             for (c = name; c < e; c++) {
5118                                 if (*c == '/') {
5119                                     sv_catpvs(msg, "::");
5120                                 }
5121                                 else {
5122                                     sv_catpvn(msg, c, 1);
5123                                 }
5124                             }
5125                             sv_catpvs(msg, " module)");
5126                         }
5127                     }
5128                     else if (memENDs(name, len, ".h")) {
5129                         sv_catpvs(msg, " (change .h to .ph maybe?) (did you run h2ph?)");
5130                     }
5131                     else if (memENDs(name, len, ".ph")) {
5132                         sv_catpvs(msg, " (did you run h2ph?)");
5133                     }
5134
5135                     /* diag_listed_as: Can't locate %s */
5136                     DIE(aTHX_
5137                         "Can't locate %s in @INC%" SVf " (@INC entries checked:%" SVf ")",
5138                         name, msg, inc);
5139                 }
5140             }
5141             DIE(aTHX_ "Can't locate %s", name);
5142         }
5143         else {
5144 #ifdef DEFAULT_INC_EXCLUDES_DOT
5145             Stat_t st;
5146             PerlIO *io = NULL;
5147             dSAVE_ERRNO;
5148             /* the complication is to match the logic from doopen_pm() so
5149              * we don't treat do "sda1" as a previously successful "do".
5150             */
5151             bool do_warn = namesv && ckWARN_d(WARN_DEPRECATED__DOT_IN_INC)
5152                 && PerlLIO_stat(name, &st) == 0 && !S_ISDIR(st.st_mode) && !S_ISBLK(st.st_mode)
5153                 && (io = PerlIO_openn(aTHX_ ":", PERL_SCRIPT_MODE, -1, 0, 0, NULL, 1, &sv)) != NULL;
5154             if (io)
5155                 PerlIO_close(io);
5156
5157             RESTORE_ERRNO;
5158             if (do_warn) {
5159                 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED__DOT_IN_INC),
5160                 "do \"%s\" failed, '.' is no longer in @INC; "
5161                 "did you mean do \"./%s\"?",
5162                 name, name);
5163             }
5164 #endif
5165             CLEAR_ERRSV();
5166             rpp_replace_1_IMM_NN(&PL_sv_undef);
5167             return NORMAL;
5168         }
5169     }
5170     else
5171         SETERRNO(0, SS_NORMAL);
5172
5173     rpp_popfree_1_NN(); /* finished with sv now */
5174
5175     /* Update %INC. Assume success here to prevent recursive requirement. */
5176     /* name is never assigned to again, so len is still strlen(name)  */
5177     /* Check whether a hook in @INC has already filled %INC */
5178     if (!hook_sv) {
5179         (void)hv_store(GvHVn(PL_incgv),
5180                        unixname, unixlen, newSVpv(tryname,0),0);
5181     } else {
5182         /* store the hook in the sv, note we have to *copy* hook_sv,
5183          * we don't want modifications to it to change @INC - see GH #20577
5184          */
5185         SV** const svp = hv_fetch(GvHVn(PL_incgv), unixname, unixlen, 0);
5186         if (!svp)
5187             (void)hv_store(GvHVn(PL_incgv),
5188                            unixname, unixlen, newSVsv(hook_sv), 0 );
5189     }
5190
5191     /* Now parse the file */
5192
5193     old_savestack_ix = PL_savestack_ix;
5194     SAVECOPFILE_FREE(&PL_compiling);
5195     CopFILE_set(&PL_compiling, tryname);
5196     lex_start(NULL, tryrsfp, 0);
5197
5198     if (filter_sub || filter_cache) {
5199         /* We can use the SvPV of the filter PVIO itself as our cache, rather
5200            than hanging another SV from it. In turn, filter_add() optionally
5201            takes the SV to use as the filter (or creates a new SV if passed
5202            NULL), so simply pass in whatever value filter_cache has.  */
5203         SV * const fc = filter_cache ? newSV_type(SVt_NULL) : NULL;
5204         SV *datasv;
5205         if (fc) sv_copypv(fc, filter_cache);
5206         datasv = filter_add(S_run_user_filter, fc);
5207         IoLINES(datasv) = filter_has_file;
5208         IoTOP_GV(datasv) = MUTABLE_GV(filter_state);
5209         IoBOTTOM_GV(datasv) = MUTABLE_GV(filter_sub);
5210     }
5211
5212     /* switch to eval mode */
5213     assert(!CATCH_GET);
5214     cx = cx_pushblock(CXt_EVAL, gimme, PL_stack_sp, old_savestack_ix);
5215     cx_pusheval(cx, PL_op->op_next, newSVpv(name, 0));
5216
5217     SAVECOPLINE(&PL_compiling);
5218     CopLINE_set(&PL_compiling, 0);
5219
5220     if (doeval_compile(gimme, NULL, PL_curcop->cop_seq, NULL))
5221         op = PL_eval_start;
5222     else
5223         op = PL_op->op_next;
5224
5225     PERL_DTRACE_PROBE_FILE_LOADED(unixname);
5226
5227     return op;
5228 }
5229
5230
5231 /* also used for: pp_dofile() */
5232
5233 PP(pp_require)
5234 {
5235     /* If a suitable JMPENV catch frame isn't present, call docatch(),
5236      * which will:
5237      *   - add such a frame, and
5238      *   - start a new RUNOPS loop, which will (as the first op to run),
5239      *     recursively call this pp function again.
5240      * The main body of this function is then executed by the inner call.
5241      */
5242     if (CATCH_GET)
5243         return docatch(Perl_pp_require);
5244
5245     {
5246         SV *sv = *PL_stack_sp;
5247         SvGETMAGIC(sv);
5248         /* these tail-called subs are responsible for popping sv off the
5249          * stack */
5250         return ((SvNIOKp(sv) || SvVOK(sv)) && PL_op->op_type != OP_DOFILE)
5251             ? S_require_version(aTHX_ sv)
5252             : S_require_file(aTHX_ sv);
5253     }
5254 }
5255
5256
5257 /* This is a op added to hold the hints hash for
5258    pp_entereval. The hash can be modified by the code
5259    being eval'ed, so we return a copy instead. */
5260
5261 PP(pp_hintseval)
5262 {
5263     rpp_extend(1);
5264     rpp_push_1_norc(MUTABLE_SV(hv_copy_hints_hv(MUTABLE_HV(cSVOP_sv))));
5265     return NORMAL;
5266 }
5267
5268
5269 PP(pp_entereval)
5270 {
5271     PERL_CONTEXT *cx;
5272     SV *sv;
5273     U8 gimme;
5274     U32 was;
5275     char tbuf[TYPE_DIGITS(long) + 12];
5276     bool saved_delete;
5277     char *tmpbuf;
5278     STRLEN len;
5279     CV* runcv;
5280     U32 seq, lex_flags;
5281     HV *saved_hh;
5282     bool bytes;
5283     I32 old_savestack_ix;
5284
5285     /* If a suitable JMPENV catch frame isn't present, call docatch(),
5286      * which will:
5287      *   - add such a frame, and
5288      *   - start a new RUNOPS loop, which will (as the first op to run),
5289      *     recursively call this pp function again.
5290      * The main body of this function is then executed by the inner call.
5291      */
5292     if (CATCH_GET)
5293         return docatch(Perl_pp_entereval);
5294
5295     assert(!CATCH_GET);
5296
5297     gimme = GIMME_V;
5298     was = PL_breakable_sub_gen;
5299     saved_delete = FALSE;
5300     tmpbuf = tbuf;
5301     lex_flags = 0;
5302     saved_hh = NULL;
5303     bytes = PL_op->op_private & OPpEVAL_BYTES;
5304
5305     if (PL_op->op_private & OPpEVAL_HAS_HH) {
5306         saved_hh = MUTABLE_HV(rpp_pop_1_norc());
5307     }
5308     else if (PL_hints & HINT_LOCALIZE_HH || (
5309                 PL_op->op_private & OPpEVAL_COPHH
5310              && PL_curcop->cop_hints & HINT_LOCALIZE_HH
5311             )) {
5312         saved_hh = cop_hints_2hv(PL_curcop, 0);
5313         hv_magic(saved_hh, NULL, PERL_MAGIC_hints);
5314     }
5315     sv = *PL_stack_sp;
5316     if (!SvPOK(sv)) {
5317         /* make sure we've got a plain PV (no overload etc) before testing
5318          * for taint. Making a copy here is probably overkill, but better
5319          * safe than sorry */
5320         STRLEN len;
5321         const char * const p = SvPV_const(sv, len);
5322
5323         sv = newSVpvn_flags(p, len, SVs_TEMP | SvUTF8(sv));
5324         lex_flags |= LEX_START_COPIED;
5325
5326         if (bytes && SvUTF8(sv))
5327             SvPVbyte_force(sv, len);
5328     }
5329     else if (bytes && SvUTF8(sv)) {
5330         /* Don't modify someone else's scalar */
5331         STRLEN len;
5332         sv = newSVsv(sv);
5333         (void)sv_2mortal(sv);
5334         SvPVbyte_force(sv,len);
5335         lex_flags |= LEX_START_COPIED;
5336     }
5337
5338     TAINT_IF(SvTAINTED(sv));
5339     TAINT_PROPER("eval");
5340
5341     old_savestack_ix = PL_savestack_ix;
5342
5343     lex_start(sv, NULL, lex_flags | (PL_op->op_private & OPpEVAL_UNICODE
5344                            ? LEX_IGNORE_UTF8_HINTS
5345                            : bytes ? LEX_EVALBYTES : LEX_START_SAME_FILTER
5346                         )
5347              );
5348
5349     rpp_popfree_1_NN(); /* can free sv now */
5350
5351     /* switch to eval mode */
5352
5353     if (PERLDB_NAMEEVAL && CopLINE(PL_curcop)) {
5354         SV * const temp_sv = sv_newmortal();
5355         Perl_sv_setpvf(aTHX_ temp_sv, "_<(eval %lu)[%s:%" LINE_Tf "]",
5356                        (unsigned long)++PL_evalseq,
5357                        CopFILE(PL_curcop), CopLINE(PL_curcop));
5358         tmpbuf = SvPVX(temp_sv);
5359         len = SvCUR(temp_sv);
5360     }
5361     else
5362         len = my_snprintf(tmpbuf, sizeof(tbuf), "_<(eval %lu)", (unsigned long)++PL_evalseq);
5363     SAVECOPFILE_FREE(&PL_compiling);
5364     CopFILE_set(&PL_compiling, tmpbuf+2);
5365     SAVECOPLINE(&PL_compiling);
5366     CopLINE_set(&PL_compiling, 1);
5367     /* special case: an eval '' executed within the DB package gets lexically
5368      * placed in the first non-DB CV rather than the current CV - this
5369      * allows the debugger to execute code, find lexicals etc, in the
5370      * scope of the code being debugged. Passing &seq gets find_runcv
5371      * to do the dirty work for us */
5372     runcv = find_runcv(&seq);
5373
5374     assert(!CATCH_GET);
5375     cx = cx_pushblock((CXt_EVAL|CXp_REAL),
5376                         gimme, PL_stack_sp, old_savestack_ix);
5377     cx_pusheval(cx, PL_op->op_next, NULL);
5378
5379     /* prepare to compile string */
5380
5381     if (PERLDB_LINE_OR_SAVESRC && PL_curstash != PL_debstash)
5382         save_lines(CopFILEAV(&PL_compiling), PL_parser->linestr);
5383     else {
5384         /* XXX For C<eval "...">s within BEGIN {} blocks, this ends up
5385            deleting the eval's FILEGV from the stash before gv_check() runs
5386            (i.e. before run-time proper). To work around the coredump that
5387            ensues, we always turn GvMULTI_on for any globals that were
5388            introduced within evals. See force_ident(). GSAR 96-10-12 */
5389         char *const safestr = savepvn(tmpbuf, len);
5390         SAVEDELETE(PL_defstash, safestr, len);
5391         saved_delete = TRUE;
5392     }
5393     
5394     if (doeval_compile(gimme, runcv, seq, saved_hh)) {
5395         if (was != PL_breakable_sub_gen /* Some subs defined here. */
5396             ?  PERLDB_LINE_OR_SAVESRC
5397             :  PERLDB_SAVESRC_NOSUBS) {
5398             /* Retain the filegv we created.  */
5399         } else if (!saved_delete) {
5400             char *const safestr = savepvn(tmpbuf, len);
5401             SAVEDELETE(PL_defstash, safestr, len);
5402         }
5403         return PL_eval_start;
5404     } else {
5405         /* We have already left the scope set up earlier thanks to the LEAVE
5406            in doeval_compile().  */
5407         if (was != PL_breakable_sub_gen /* Some subs defined here. */
5408             ?  PERLDB_LINE_OR_SAVESRC
5409             :  PERLDB_SAVESRC_INVALID) {
5410             /* Retain the filegv we created.  */
5411         } else if (!saved_delete) {
5412             (void)hv_delete(PL_defstash, tmpbuf, len, G_DISCARD);
5413         }
5414         if (PL_op->op_private & OPpEVAL_EVALSV)
5415             /* signal compiletime failure to our eval_sv() caller */
5416             *++PL_stack_sp = NULL;
5417         return PL_op->op_next;
5418     }
5419 }
5420
5421
5422 /* also tail-called by pp_return */
5423
5424 PP(pp_leaveeval)
5425 {
5426     SV **oldsp;
5427     U8 gimme;
5428     PERL_CONTEXT *cx;
5429     OP *retop;
5430     int failed;
5431     bool override_return = FALSE; /* is feature 'module_true' in effect? */
5432     CV *evalcv;
5433     bool keep;
5434
5435     PERL_ASYNC_CHECK();
5436
5437     cx = CX_CUR();
5438     assert(CxTYPE(cx) == CXt_EVAL);
5439
5440     oldsp = PL_stack_base + cx->blk_oldsp;
5441     gimme = cx->blk_gimme;
5442
5443     bool is_require= CxOLD_OP_TYPE(cx) == OP_REQUIRE;
5444     if (is_require) {
5445         /* We are in an require. Check if use feature 'module_true' is enabled,
5446          * and if so later on correct any returns from the require. */
5447
5448         /* we might be called for an OP_LEAVEEVAL or OP_RETURN opcode
5449          * and the parse tree will look different for either case.
5450          * so find the right op to check later */
5451         if (OP_TYPE_IS_OR_WAS(PL_op, OP_RETURN)) {
5452             if (PL_op->op_flags & OPf_SPECIAL)
5453                 override_return = true;
5454         }
5455         else if ((PL_op->op_flags & OPf_KIDS) && OP_TYPE_IS_OR_WAS(PL_op, OP_LEAVEEVAL)){
5456             COP *old_pl_curcop = PL_curcop;
5457             OP *check = cUNOPx(PL_op)->op_first;
5458
5459             /* ok, we found something to check, we need to scan through
5460              * it and find the last OP_NEXTSTATE it contains and then read the
5461              * feature state out of the COP data it contains.
5462              */
5463             if (check) {
5464                 if (!OP_TYPE_IS(check,OP_STUB)) {
5465                     const OP *kid = cLISTOPx(check)->op_first;
5466                     const OP *last_state = NULL;
5467
5468                     for (; kid; kid = OpSIBLING(kid)) {
5469                         if (
5470                                OP_TYPE_IS_OR_WAS(kid, OP_NEXTSTATE)
5471                             || OP_TYPE_IS_OR_WAS(kid, OP_DBSTATE)
5472                         ){
5473                             last_state = kid;
5474                         }
5475                     }
5476                     if (last_state) {
5477                         PL_curcop = cCOPx(last_state);
5478                         if (FEATURE_MODULE_TRUE_IS_ENABLED) {
5479                             override_return = TRUE;
5480                         }
5481                     } else {
5482                         NOT_REACHED; /* NOTREACHED */
5483                     }
5484                 }
5485             } else {
5486                 NOT_REACHED; /* NOTREACHED */
5487             }
5488             PL_curcop = old_pl_curcop;
5489         }
5490     }
5491
5492     /* we might override this later if 'module_true' is enabled */
5493     failed =    is_require
5494              && !(gimme == G_SCALAR
5495                     ? SvTRUE_NN(*PL_stack_sp)
5496                     : PL_stack_sp > oldsp);
5497
5498     if (gimme == G_VOID) {
5499         rpp_popfree_to(oldsp);
5500         /* free now to avoid late-called destructors clobbering $@ */
5501         FREETMPS;
5502     }
5503     else
5504         leave_adjust_stacks(oldsp, oldsp, gimme, 0);
5505
5506     /* the cx_popeval does a leavescope, which frees the optree associated
5507      * with eval, which if it frees the nextstate associated with
5508      * PL_curcop, sets PL_curcop to NULL. Which can mess up freeing a
5509      * regex when running under 'use re Debug' because it needs PL_curcop
5510      * to get the current hints. So restore it early.
5511      */
5512     PL_curcop = cx->blk_oldcop;
5513
5514     /* grab this value before cx_popeval restores the old PL_in_eval */
5515     keep = cBOOL(PL_in_eval & EVAL_KEEPERR);
5516     retop = cx->blk_eval.retop;
5517     evalcv = cx->blk_eval.cv;
5518 #ifdef DEBUGGING
5519     assert(CvDEPTH(evalcv) == 1);
5520 #endif
5521     CvDEPTH(evalcv) = 0;
5522
5523     if (override_return) {
5524         /* make sure that we use a standard return when feature 'module_load'
5525          * is enabled. Returns from require are problematic (consider what happens
5526          * when it is called twice) */
5527         if (gimme == G_SCALAR)
5528             rpp_replace_1_IMM_NN(&PL_sv_yes);
5529         assert(gimme == G_VOID || gimme == G_SCALAR);
5530         failed = 0;
5531     }
5532
5533     /* pop the CXt_EVAL, and if a require failed, croak */
5534     S_pop_eval_context_maybe_croak(aTHX_ cx, NULL, failed);
5535
5536     if (!keep)
5537         CLEAR_ERRSV();
5538
5539     return retop;
5540 }
5541
5542 /* Ops that implement try/catch syntax
5543  * Note the asymmetry here:
5544  *   pp_entertrycatch does two pushblocks
5545  *   pp_leavetrycatch pops only the outer one; the inner one is popped by
5546  *     pp_poptry or by stack-unwind of die within the try block
5547  */
5548
5549 PP(pp_entertrycatch)
5550 {
5551     PERL_CONTEXT *cx;
5552     const U8 gimme = GIMME_V;
5553
5554     /* If a suitable JMPENV catch frame isn't present, call docatch(),
5555      * which will:
5556      *   - add such a frame, and
5557      *   - start a new RUNOPS loop, which will (as the first op to run),
5558      *     recursively call this pp function again.
5559      * The main body of this function is then executed by the inner call.
5560      */
5561     if (CATCH_GET)
5562         return docatch(Perl_pp_entertrycatch);
5563
5564     assert(!CATCH_GET);
5565
5566     Perl_pp_enter(aTHX); /* performs cx_pushblock(CXt_BLOCK, ...) */
5567
5568     save_scalar(PL_errgv);
5569     CLEAR_ERRSV();
5570
5571     cx = cx_pushblock((CXt_EVAL|CXp_EVALBLOCK|CXp_TRY), gimme,
5572             PL_stack_sp, PL_savestack_ix);
5573     cx_pushtry(cx, cLOGOP->op_other);
5574
5575     PL_in_eval = EVAL_INEVAL;
5576
5577     return NORMAL;
5578 }
5579
5580 PP(pp_leavetrycatch)
5581 {
5582     /* leavetrycatch is leave */
5583     return Perl_pp_leave(aTHX);
5584 }
5585
5586 PP(pp_poptry)
5587 {
5588     /* poptry is leavetry */
5589     return Perl_pp_leavetry(aTHX);
5590 }
5591
5592 PP(pp_catch)
5593 {
5594     dTARGET;
5595
5596     save_clearsv(&(PAD_SVl(PL_op->op_targ)));
5597     sv_setsv(TARG, ERRSV);
5598     CLEAR_ERRSV();
5599
5600     return cLOGOP->op_other;
5601 }
5602
5603 /* Common code for Perl_call_sv and Perl_fold_constants, put here to keep it
5604    close to the related Perl_create_eval_scope.  */
5605 void
5606 Perl_delete_eval_scope(pTHX)
5607 {
5608     PERL_CONTEXT *cx;
5609         
5610     cx = CX_CUR();
5611     CX_LEAVE_SCOPE(cx);
5612     cx_popeval(cx);
5613     cx_popblock(cx);
5614     CX_POP(cx);
5615 }
5616
5617 /* Common-ish code salvaged from Perl_call_sv and pp_entertry, because it was
5618    also needed by Perl_fold_constants.  */
5619 void
5620 Perl_create_eval_scope(pTHX_ OP *retop, SV **sp, U32 flags)
5621 {
5622     PERL_CONTEXT *cx;
5623     const U8 gimme = GIMME_V;
5624
5625     PERL_ARGS_ASSERT_CREATE_EVAL_SCOPE;
5626         
5627     cx = cx_pushblock((CXt_EVAL|CXp_EVALBLOCK), gimme,
5628                     sp, PL_savestack_ix);
5629     cx_pusheval(cx, retop, NULL);
5630
5631     PL_in_eval = EVAL_INEVAL;
5632     if (flags & G_KEEPERR)
5633         PL_in_eval |= EVAL_KEEPERR;
5634     else
5635         CLEAR_ERRSV();
5636     if (flags & G_FAKINGEVAL) {
5637         PL_eval_root = PL_op; /* Only needed so that goto works right. */
5638     }
5639 }
5640     
5641 PP(pp_entertry)
5642 {
5643     OP *retop = cLOGOP->op_other->op_next;
5644
5645     /* If a suitable JMPENV catch frame isn't present, call docatch(),
5646      * which will:
5647      *   - add such a frame, and
5648      *   - start a new RUNOPS loop, which will (as the first op to run),
5649      *     recursively call this pp function again.
5650      * The main body of this function is then executed by the inner call.
5651      */
5652     if (CATCH_GET)
5653         return docatch(Perl_pp_entertry);
5654
5655     assert(!CATCH_GET);
5656
5657     create_eval_scope(retop, PL_stack_sp, 0);
5658
5659     return PL_op->op_next;
5660 }
5661
5662
5663 /* also tail-called by pp_return */
5664
5665 PP(pp_leavetry)
5666 {
5667     SV **oldsp;
5668     U8 gimme;
5669     PERL_CONTEXT *cx;
5670     OP *retop;
5671
5672     PERL_ASYNC_CHECK();
5673
5674     cx = CX_CUR();
5675     assert(CxTYPE(cx) == CXt_EVAL);
5676     oldsp = PL_stack_base + cx->blk_oldsp;
5677     gimme = cx->blk_gimme;
5678
5679     if (gimme == G_VOID) {
5680         rpp_popfree_to_NN(oldsp);
5681         /* free now to avoid late-called destructors clobbering $@ */
5682         FREETMPS;
5683     }
5684     else
5685         leave_adjust_stacks(oldsp, oldsp, gimme, 1);
5686     CX_LEAVE_SCOPE(cx);
5687     cx_popeval(cx);
5688     cx_popblock(cx);
5689     retop = CxTRY(cx) ? PL_op->op_next : cx->blk_eval.retop;
5690     CX_POP(cx);
5691
5692     CLEAR_ERRSV();
5693     return retop;
5694 }
5695
5696 PP(pp_entergiven)
5697 {
5698     PERL_CONTEXT *cx;
5699     const U8 gimme = GIMME_V;
5700     SV *origsv = DEFSV;
5701     
5702     assert(!PL_op->op_targ); /* used to be set for lexical $_ */
5703     GvSV(PL_defgv) = rpp_pop_1_norc();
5704
5705     cx = cx_pushblock(CXt_GIVEN, gimme, PL_stack_sp, PL_savestack_ix);
5706     cx_pushgiven(cx, origsv);
5707
5708     return NORMAL;
5709 }
5710
5711 PP(pp_leavegiven)
5712 {
5713     PERL_CONTEXT *cx;
5714     U8 gimme;
5715     SV **oldsp;
5716     PERL_UNUSED_CONTEXT;
5717
5718     cx = CX_CUR();
5719     assert(CxTYPE(cx) == CXt_GIVEN);
5720     oldsp = PL_stack_base + cx->blk_oldsp;
5721     gimme = cx->blk_gimme;
5722
5723     if (gimme == G_VOID)
5724         rpp_popfree_to_NN(oldsp);
5725     else
5726         leave_adjust_stacks(oldsp, oldsp, gimme, 1);
5727
5728     CX_LEAVE_SCOPE(cx);
5729     cx_popgiven(cx);
5730     cx_popblock(cx);
5731     CX_POP(cx);
5732
5733     return NORMAL;
5734 }
5735
5736 /* Helper routines used by pp_smartmatch */
5737 STATIC PMOP *
5738 S_make_matcher(pTHX_ REGEXP *re)
5739 {
5740     PMOP *matcher = cPMOPx(newPMOP(OP_MATCH, OPf_WANT_SCALAR | OPf_STACKED));
5741
5742     PERL_ARGS_ASSERT_MAKE_MATCHER;
5743
5744     PM_SETRE(matcher, ReREFCNT_inc(re));
5745
5746     SAVEFREEOP((OP *) matcher);
5747     ENTER_with_name("matcher"); SAVETMPS;
5748     SAVEOP();
5749     return matcher;
5750 }
5751
5752 STATIC bool
5753 S_matcher_matches_sv(pTHX_ PMOP *matcher, SV *sv)
5754 {
5755     bool result;
5756
5757     PERL_ARGS_ASSERT_MATCHER_MATCHES_SV;
5758     
5759     PL_op = (OP *) matcher;
5760     rpp_xpush_1(sv);
5761     (void) Perl_pp_match(aTHX);
5762     result = SvTRUEx(*PL_stack_sp);
5763     rpp_popfree_1_NN();
5764     return result;
5765 }
5766
5767 STATIC void
5768 S_destroy_matcher(pTHX_ PMOP *matcher)
5769 {
5770     PERL_ARGS_ASSERT_DESTROY_MATCHER;
5771     PERL_UNUSED_ARG(matcher);
5772
5773     FREETMPS;
5774     LEAVE_with_name("matcher");
5775 }
5776
5777
5778 /* Do a smart match */
5779 PP(pp_smartmatch)
5780 {
5781     DEBUG_M(Perl_deb(aTHX_ "Starting smart match resolution\n"));
5782     return do_smartmatch(NULL, NULL, 0);
5783 }
5784
5785
5786 /* This version of do_smartmatch() implements the
5787  * table of smart matches that is found in perlsyn.
5788  */
5789 STATIC OP *
5790 S_do_smartmatch(pTHX_ HV *seen_this, HV *seen_other, const bool copied)
5791 {
5792     bool object_on_left = FALSE;
5793     SV *e = PL_stack_sp[0];  /* e is for 'expression' */
5794     SV *d = PL_stack_sp[-1]; /* d is for 'default', as in PL_defgv */
5795
5796     /* Take care only to invoke mg_get() once for each argument.
5797      * Currently we do this by copying the SV if it's magical. */
5798     if (d) {
5799         if (!copied && SvGMAGICAL(d))
5800             d = sv_mortalcopy(d);
5801     }
5802     else
5803         d = &PL_sv_undef;
5804
5805     assert(e);
5806     if (SvGMAGICAL(e))
5807         e = sv_mortalcopy(e);
5808
5809     /* First of all, handle overload magic of the rightmost argument */
5810     if (SvAMAGIC(e)) {
5811         SV * tmpsv;
5812         DEBUG_M(Perl_deb(aTHX_ "    applying rule Any-Object\n"));
5813         DEBUG_M(Perl_deb(aTHX_ "        attempting overload\n"));
5814
5815         tmpsv = amagic_call(d, e, smart_amg, AMGf_noleft);
5816         if (tmpsv) {
5817             rpp_replace_2_1_NN(tmpsv);
5818             return NORMAL;
5819         }
5820         DEBUG_M(Perl_deb(aTHX_ "        failed to run overload method; continuing...\n"));
5821     }
5822
5823     /* ~~ undef */
5824     if (!SvOK(e)) {
5825         DEBUG_M(Perl_deb(aTHX_ "    applying rule Any-undef\n"));
5826         if (SvOK(d))
5827             goto ret_no;
5828         else
5829             goto ret_yes;
5830     }
5831
5832     if (SvROK(e) && SvOBJECT(SvRV(e)) && (SvTYPE(SvRV(e)) != SVt_REGEXP)) {
5833         DEBUG_M(Perl_deb(aTHX_ "    applying rule Any-Object\n"));
5834         Perl_croak(aTHX_ "Smart matching a non-overloaded object breaks encapsulation");
5835     }
5836     if (SvROK(d) && SvOBJECT(SvRV(d)) && (SvTYPE(SvRV(d)) != SVt_REGEXP))
5837         object_on_left = TRUE;
5838
5839     /* ~~ sub */
5840     if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_PVCV) {
5841         if (object_on_left) {
5842             goto sm_any_sub; /* Treat objects like scalars */
5843         }
5844         else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
5845             /* Test sub truth for each key */
5846             HE *he;
5847             bool andedresults = TRUE;
5848             HV *hv = (HV*) SvRV(d);
5849             I32 numkeys = hv_iterinit(hv);
5850             DEBUG_M(Perl_deb(aTHX_ "    applying rule Hash-CodeRef\n"));
5851             if (numkeys == 0)
5852                 goto ret_yes;
5853             while ( (he = hv_iternext(hv)) ) {
5854                 DEBUG_M(Perl_deb(aTHX_ "        testing hash key...\n"));
5855                 ENTER_with_name("smartmatch_hash_key_test");
5856                 SAVETMPS;
5857                 PUSHMARK(PL_stack_sp);
5858                 rpp_xpush_1(hv_iterkeysv(he));
5859                 (void)call_sv(e, G_SCALAR);
5860                 andedresults = SvTRUEx(PL_stack_sp[0]) && andedresults;
5861                 rpp_popfree_1_NN();
5862                 FREETMPS;
5863                 LEAVE_with_name("smartmatch_hash_key_test");
5864             }
5865             if (andedresults)
5866                 goto ret_yes;
5867             else
5868                 goto ret_no;
5869         }
5870         else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
5871             /* Test sub truth for each element */
5872             Size_t i;
5873             bool andedresults = TRUE;
5874             AV *av = (AV*) SvRV(d);
5875             const Size_t len = av_count(av);
5876             DEBUG_M(Perl_deb(aTHX_ "    applying rule Array-CodeRef\n"));
5877             if (len == 0)
5878                 goto ret_yes;
5879             for (i = 0; i < len; ++i) {
5880                 SV * const * const svp = av_fetch(av, i, FALSE);
5881                 DEBUG_M(Perl_deb(aTHX_ "        testing array element...\n"));
5882                 ENTER_with_name("smartmatch_array_elem_test");
5883                 SAVETMPS;
5884                 PUSHMARK(PL_stack_sp);
5885                 if (svp)
5886                     rpp_xpush_1(*svp);
5887                 (void)call_sv(e, G_SCALAR);
5888                 andedresults = SvTRUEx(PL_stack_sp[0]) && andedresults;
5889                 rpp_popfree_1_NN();
5890                 FREETMPS;
5891                 LEAVE_with_name("smartmatch_array_elem_test");
5892             }
5893             if (andedresults)
5894                 goto ret_yes;
5895             else
5896                 goto ret_no;
5897         }
5898         else {
5899           sm_any_sub:
5900             DEBUG_M(Perl_deb(aTHX_ "    applying rule Any-CodeRef\n"));
5901             ENTER_with_name("smartmatch_coderef");
5902             PUSHMARK(PL_stack_sp);
5903             rpp_xpush_1(d);
5904             (void)call_sv(e, G_SCALAR);
5905             LEAVE_with_name("smartmatch_coderef");
5906             SV *retsv = *PL_stack_sp--;
5907             rpp_replace_2_1(retsv);
5908 #ifdef PERL_RC_STACK
5909             SvREFCNT_dec(retsv);
5910 #endif
5911             return NORMAL;
5912         }
5913     }
5914     /* ~~ %hash */
5915     else if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_PVHV) {
5916         if (object_on_left) {
5917             goto sm_any_hash; /* Treat objects like scalars */
5918         }
5919         else if (!SvOK(d)) {
5920             DEBUG_M(Perl_deb(aTHX_ "    applying rule Any-Hash ($a undef)\n"));
5921             goto ret_no;
5922         }
5923         else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
5924             /* Check that the key-sets are identical */
5925             HE *he;
5926             HV *other_hv = MUTABLE_HV(SvRV(d));
5927             bool tied;
5928             bool other_tied;
5929             U32 this_key_count  = 0,
5930                 other_key_count = 0;
5931             HV *hv = MUTABLE_HV(SvRV(e));
5932
5933             DEBUG_M(Perl_deb(aTHX_ "    applying rule Hash-Hash\n"));
5934             /* Tied hashes don't know how many keys they have. */
5935             tied = cBOOL(SvTIED_mg((SV*)hv, PERL_MAGIC_tied));
5936             other_tied = cBOOL(SvTIED_mg((const SV *)other_hv, PERL_MAGIC_tied));
5937             if (!tied ) {
5938                 if(other_tied) {
5939                     /* swap HV sides */
5940                     HV * const temp = other_hv;
5941                     other_hv = hv;
5942                     hv = temp;
5943                     tied = TRUE;
5944                     other_tied = FALSE;
5945                 }
5946                 else if(HvUSEDKEYS((const HV *) hv) != HvUSEDKEYS(other_hv))
5947                     goto ret_no;
5948             }
5949
5950             /* The hashes have the same number of keys, so it suffices
5951                to check that one is a subset of the other. */
5952             (void) hv_iterinit(hv);
5953             while ( (he = hv_iternext(hv)) ) {
5954                 SV *key = hv_iterkeysv(he);
5955
5956                 DEBUG_M(Perl_deb(aTHX_ "        comparing hash key...\n"));
5957                 ++ this_key_count;
5958                 
5959                 if(!hv_exists_ent(other_hv, key, 0)) {
5960                     (void) hv_iterinit(hv);     /* reset iterator */
5961                     goto ret_no;
5962                 }
5963             }
5964             
5965             if (other_tied) {
5966                 (void) hv_iterinit(other_hv);
5967                 while ( hv_iternext(other_hv) )
5968                     ++other_key_count;
5969             }
5970             else
5971                 other_key_count = HvUSEDKEYS(other_hv);
5972             
5973             if (this_key_count != other_key_count)
5974                 goto ret_no;
5975             else
5976                 goto ret_yes;
5977         }
5978         else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
5979             AV * const other_av = MUTABLE_AV(SvRV(d));
5980             const Size_t other_len = av_count(other_av);
5981             Size_t i;
5982             HV *hv = MUTABLE_HV(SvRV(e));
5983
5984             DEBUG_M(Perl_deb(aTHX_ "    applying rule Array-Hash\n"));
5985             for (i = 0; i < other_len; ++i) {
5986                 SV ** const svp = av_fetch(other_av, i, FALSE);
5987                 DEBUG_M(Perl_deb(aTHX_ "        checking for key existence...\n"));
5988                 if (svp) {      /* ??? When can this not happen? */
5989                     if (hv_exists_ent(hv, *svp, 0))
5990                         goto ret_yes;
5991                 }
5992             }
5993             goto ret_no;
5994         }
5995         else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_REGEXP) {
5996             DEBUG_M(Perl_deb(aTHX_ "    applying rule Regex-Hash\n"));
5997           sm_regex_hash:
5998             {
5999                 PMOP * const matcher = make_matcher((REGEXP*) SvRV(d));
6000                 HE *he;
6001                 HV *hv = MUTABLE_HV(SvRV(e));
6002
6003                 (void) hv_iterinit(hv);
6004                 while ( (he = hv_iternext(hv)) ) {
6005                     DEBUG_M(Perl_deb(aTHX_ "        testing key against pattern...\n"));
6006                     if (matcher_matches_sv(matcher, hv_iterkeysv(he))) {
6007                         (void) hv_iterinit(hv);
6008                         destroy_matcher(matcher);
6009                         goto ret_yes;
6010                     }
6011                 }
6012                 destroy_matcher(matcher);
6013                 goto ret_no;
6014             }
6015         }
6016         else {
6017           sm_any_hash:
6018             DEBUG_M(Perl_deb(aTHX_ "    applying rule Any-Hash\n"));
6019             if (hv_exists_ent(MUTABLE_HV(SvRV(e)), d, 0))
6020                 goto ret_yes;
6021             else
6022                 goto ret_no;
6023         }
6024     }
6025     /* ~~ @array */
6026     else if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_PVAV) {
6027         if (object_on_left) {
6028             goto sm_any_array; /* Treat objects like scalars */
6029         }
6030         else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
6031             AV * const other_av = MUTABLE_AV(SvRV(e));
6032             const Size_t other_len = av_count(other_av);
6033             Size_t i;
6034
6035             DEBUG_M(Perl_deb(aTHX_ "    applying rule Hash-Array\n"));
6036             for (i = 0; i < other_len; ++i) {
6037                 SV ** const svp = av_fetch(other_av, i, FALSE);
6038
6039                 DEBUG_M(Perl_deb(aTHX_ "        testing for key existence...\n"));
6040                 if (svp) {      /* ??? When can this not happen? */
6041                     if (hv_exists_ent(MUTABLE_HV(SvRV(d)), *svp, 0))
6042                         goto ret_yes;
6043                 }
6044             }
6045             goto ret_no;
6046         }
6047         if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
6048             AV *other_av = MUTABLE_AV(SvRV(d));
6049             DEBUG_M(Perl_deb(aTHX_ "    applying rule Array-Array\n"));
6050             if (av_count(MUTABLE_AV(SvRV(e))) != av_count(other_av))
6051                 goto ret_no;
6052             else {
6053                 Size_t i;
6054                 const Size_t other_len = av_count(other_av);
6055
6056                 if (NULL == seen_this) {
6057                     seen_this = (HV*)newSV_type_mortal(SVt_PVHV);
6058                 }
6059                 if (NULL == seen_other) {
6060                     seen_other = (HV*)newSV_type_mortal(SVt_PVHV);
6061                 }
6062                 for(i = 0; i < other_len; ++i) {
6063                     SV * const * const this_elem = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
6064                     SV * const * const other_elem = av_fetch(other_av, i, FALSE);
6065
6066                     if (!this_elem || !other_elem) {
6067                         if ((this_elem && SvOK(*this_elem))
6068                                 || (other_elem && SvOK(*other_elem)))
6069                             goto ret_no;
6070                     }
6071                     else if (hv_exists_ent(seen_this,
6072                                 sv_2mortal(newSViv(PTR2IV(*this_elem))), 0) ||
6073                             hv_exists_ent(seen_other,
6074                                 sv_2mortal(newSViv(PTR2IV(*other_elem))), 0))
6075                     {
6076                         if (*this_elem != *other_elem)
6077                             goto ret_no;
6078                     }
6079                     else {
6080                         (void)hv_store_ent(seen_this,
6081                                 sv_2mortal(newSViv(PTR2IV(*this_elem))),
6082                                 &PL_sv_undef, 0);
6083                         (void)hv_store_ent(seen_other,
6084                                 sv_2mortal(newSViv(PTR2IV(*other_elem))),
6085                                 &PL_sv_undef, 0);
6086                         rpp_xpush_2(*other_elem, *this_elem);
6087                         DEBUG_M(Perl_deb(aTHX_ "        recursively comparing array element...\n"));
6088                         (void) do_smartmatch(seen_this, seen_other, 0);
6089                         DEBUG_M(Perl_deb(aTHX_ "        recursion finished\n"));
6090                         
6091                          bool ok = SvTRUEx(PL_stack_sp[0]);
6092                          rpp_popfree_1_NN();
6093                         if (!ok)
6094                             goto ret_no;
6095                     }
6096                 }
6097                 goto ret_yes;
6098             }
6099         }
6100         else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_REGEXP) {
6101             DEBUG_M(Perl_deb(aTHX_ "    applying rule Regex-Array\n"));
6102           sm_regex_array:
6103             {
6104                 PMOP * const matcher = make_matcher((REGEXP*) SvRV(d));
6105                 const Size_t this_len = av_count(MUTABLE_AV(SvRV(e)));
6106                 Size_t i;
6107
6108                 for(i = 0; i < this_len; ++i) {
6109                     SV * const * const svp = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
6110                     DEBUG_M(Perl_deb(aTHX_ "        testing element against pattern...\n"));
6111                     if (svp && matcher_matches_sv(matcher, *svp)) {
6112                         destroy_matcher(matcher);
6113                         goto ret_yes;
6114                     }
6115                 }
6116                 destroy_matcher(matcher);
6117                 goto ret_no;
6118             }
6119         }
6120         else if (!SvOK(d)) {
6121             /* undef ~~ array */
6122             const Size_t this_len = av_count(MUTABLE_AV(SvRV(e)));
6123             Size_t i;
6124
6125             DEBUG_M(Perl_deb(aTHX_ "    applying rule Undef-Array\n"));
6126             for (i = 0; i < this_len; ++i) {
6127                 SV * const * const svp = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
6128                 DEBUG_M(Perl_deb(aTHX_ "        testing for undef element...\n"));
6129                 if (!svp || !SvOK(*svp))
6130                     goto ret_yes;
6131             }
6132             goto ret_no;
6133         }
6134         else {
6135           sm_any_array:
6136             {
6137                 Size_t i;
6138                 const Size_t this_len = av_count(MUTABLE_AV(SvRV(e)));
6139
6140                 DEBUG_M(Perl_deb(aTHX_ "    applying rule Any-Array\n"));
6141                 for (i = 0; i < this_len; ++i) {
6142                     SV * const * const svp = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
6143                     if (!svp)
6144                         continue;
6145
6146                     rpp_xpush_2(d, *svp);
6147                     /* infinite recursion isn't supposed to happen here */
6148                     DEBUG_M(Perl_deb(aTHX_ "        recursively testing array element...\n"));
6149                     (void) do_smartmatch(NULL, NULL, 1);
6150                     DEBUG_M(Perl_deb(aTHX_ "        recursion finished\n"));
6151                     bool ok = SvTRUEx(PL_stack_sp[0]);
6152                     rpp_popfree_1_NN();
6153                     if (ok)
6154                         goto ret_yes;
6155                 }
6156                 goto ret_no;
6157             }
6158         }
6159     }
6160     /* ~~ qr// */
6161     else if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_REGEXP) {
6162         if (!object_on_left && SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
6163             SV *t = d; d = e; e = t;
6164             DEBUG_M(Perl_deb(aTHX_ "    applying rule Hash-Regex\n"));
6165             goto sm_regex_hash;
6166         }
6167         else if (!object_on_left && SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
6168             SV *t = d; d = e; e = t;
6169             DEBUG_M(Perl_deb(aTHX_ "    applying rule Array-Regex\n"));
6170             goto sm_regex_array;
6171         }
6172         else {
6173             PMOP * const matcher = make_matcher((REGEXP*) SvRV(e));
6174             bool result;
6175
6176             DEBUG_M(Perl_deb(aTHX_ "    applying rule Any-Regex\n"));
6177             result = matcher_matches_sv(matcher, d);
6178             destroy_matcher(matcher);
6179             if (result)
6180                 goto ret_yes;
6181             else
6182                 goto ret_no;
6183         }
6184     }
6185     /* ~~ scalar */
6186     /* See if there is overload magic on left */
6187     else if (object_on_left && SvAMAGIC(d)) {
6188         SV *tmpsv;
6189         DEBUG_M(Perl_deb(aTHX_ "    applying rule Object-Any\n"));
6190         DEBUG_M(Perl_deb(aTHX_ "        attempting overload\n"));
6191         tmpsv = amagic_call(d, e, smart_amg, AMGf_noright);
6192         if (tmpsv) {
6193             rpp_replace_2_1_NN(tmpsv);
6194             return NORMAL;
6195         }
6196
6197         DEBUG_M(Perl_deb(aTHX_ "        failed to run overload method; falling back...\n"));
6198         goto sm_any_scalar;
6199     }
6200     else if (!SvOK(d)) {
6201         /* undef ~~ scalar ; we already know that the scalar is SvOK */
6202         DEBUG_M(Perl_deb(aTHX_ "    applying rule undef-Any\n"));
6203         goto ret_no;
6204     }
6205     else
6206   sm_any_scalar:
6207     if (SvNIOK(e) || (SvPOK(e) && looks_like_number(e) && SvNIOK(d))) {
6208         DEBUG_M(if (SvNIOK(e))
6209                     Perl_deb(aTHX_ "    applying rule Any-Num\n");
6210                 else
6211                     Perl_deb(aTHX_ "    applying rule Num-numish\n");
6212         );
6213         /* numeric comparison */
6214         rpp_xpush_2(d, e);
6215         if (CopHINTS_get(PL_curcop) & HINT_INTEGER)
6216             (void) Perl_pp_i_eq(aTHX);
6217         else
6218             (void) Perl_pp_eq(aTHX);
6219         bool ok = SvTRUEx(PL_stack_sp[0]);
6220         rpp_popfree_1_NN();
6221         if (ok)
6222             goto ret_yes;
6223         else
6224             goto ret_no;
6225     }
6226     
6227     /* As a last resort, use string comparison */
6228     DEBUG_M(Perl_deb(aTHX_ "    applying rule Any-Any\n"));
6229     rpp_xpush_2(d, e);
6230     Perl_pp_seq(aTHX);
6231     {
6232         bool ok = SvTRUEx(PL_stack_sp[0]);
6233         rpp_popfree_1_NN();
6234         if (ok)
6235             goto ret_yes;
6236         else
6237             goto ret_no;
6238     }
6239
6240   ret_no:
6241     rpp_replace_2_IMM_NN(&PL_sv_no);
6242     return NORMAL;
6243
6244   ret_yes:
6245     rpp_replace_2_IMM_NN(&PL_sv_yes);
6246     return NORMAL;
6247 }
6248
6249
6250 PP(pp_enterwhen)
6251 {
6252     PERL_CONTEXT *cx;
6253     const U8 gimme = GIMME_V;
6254
6255     /* This is essentially an optimization: if the match
6256        fails, we don't want to push a context and then
6257        pop it again right away, so we skip straight
6258        to the op that follows the leavewhen.
6259     */
6260     if (!(PL_op->op_flags & OPf_SPECIAL)) { /* SPECIAL implies no condition */
6261         bool tr = SvTRUEx(*PL_stack_sp);
6262         rpp_popfree_1_NN();
6263         if (!tr) {
6264             if (gimme == G_SCALAR)
6265                 rpp_push_IMM(&PL_sv_undef);
6266             return cLOGOP->op_other->op_next;
6267         }
6268     }
6269
6270     cx = cx_pushblock(CXt_WHEN, gimme, PL_stack_sp, PL_savestack_ix);
6271     cx_pushwhen(cx);
6272
6273     return NORMAL;
6274 }
6275
6276 PP(pp_leavewhen)
6277 {
6278     I32 cxix;
6279     PERL_CONTEXT *cx;
6280     U8 gimme;
6281     SV **oldsp;
6282
6283     cx = CX_CUR();
6284     assert(CxTYPE(cx) == CXt_WHEN);
6285     gimme = cx->blk_gimme;
6286
6287     cxix = dopoptogivenfor(cxstack_ix);
6288     if (cxix < 0)
6289         /* diag_listed_as: Can't "when" outside a topicalizer */
6290         DIE(aTHX_ "Can't \"%s\" outside a topicalizer",
6291                    PL_op->op_flags & OPf_SPECIAL ? "default" : "when");
6292
6293     oldsp = PL_stack_base + cx->blk_oldsp;
6294     if (gimme == G_VOID)
6295         rpp_popfree_to_NN(oldsp);
6296     else
6297         leave_adjust_stacks(oldsp, oldsp, gimme, 1);
6298
6299     /* pop the WHEN, BLOCK and anything else before the GIVEN/FOR */
6300     assert(cxix < cxstack_ix);
6301     dounwind(cxix);
6302
6303     cx = &cxstack[cxix];
6304
6305     if (CxFOREACH(cx)) {
6306         /* emulate pp_next. Note that any stack(s) cleanup will be
6307          * done by the pp_unstack which op_nextop should point to */
6308         cx = CX_CUR();
6309         cx_topblock(cx);
6310         PL_curcop = cx->blk_oldcop;
6311         return cx->blk_loop.my_op->op_nextop;
6312     }
6313     else {
6314         PERL_ASYNC_CHECK();
6315         assert(cx->blk_givwhen.leave_op->op_type == OP_LEAVEGIVEN);
6316         return cx->blk_givwhen.leave_op;
6317     }
6318 }
6319
6320 PP(pp_continue)
6321 {
6322     I32 cxix;
6323     PERL_CONTEXT *cx;
6324     OP *nextop;
6325     
6326     cxix = dopoptowhen(cxstack_ix); 
6327     if (cxix < 0)   
6328         DIE(aTHX_ "Can't \"continue\" outside a when block");
6329
6330     if (cxix < cxstack_ix)
6331         dounwind(cxix);
6332     
6333     cx = CX_CUR();
6334     assert(CxTYPE(cx) == CXt_WHEN);
6335     rpp_popfree_to_NN(PL_stack_base + cx->blk_oldsp);
6336     CX_LEAVE_SCOPE(cx);
6337     cx_popwhen(cx);
6338     cx_popblock(cx);
6339     nextop = cx->blk_givwhen.leave_op->op_next;
6340     CX_POP(cx);
6341
6342     return nextop;
6343 }
6344
6345 PP(pp_break)
6346 {
6347     I32 cxix;
6348     PERL_CONTEXT *cx;
6349
6350     cxix = dopoptogivenfor(cxstack_ix);
6351     if (cxix < 0)
6352         DIE(aTHX_ "Can't \"break\" outside a given block");
6353
6354     cx = &cxstack[cxix];
6355     if (CxFOREACH(cx))
6356         DIE(aTHX_ "Can't \"break\" in a loop topicalizer");
6357
6358     if (cxix < cxstack_ix)
6359         dounwind(cxix);
6360
6361     /* Restore the sp at the time we entered the given block */
6362     cx = CX_CUR();
6363     rpp_popfree_to_NN(PL_stack_base + cx->blk_oldsp);
6364
6365     return cx->blk_givwhen.leave_op;
6366 }
6367
6368 static void
6369 _invoke_defer_block(pTHX_ U8 type, void *_arg)
6370 {
6371     OP *start = (OP *)_arg;
6372 #ifdef DEBUGGING
6373     I32 was_cxstack_ix = cxstack_ix;
6374 #endif
6375
6376     cx_pushblock(type, G_VOID, PL_stack_sp, PL_savestack_ix);
6377     ENTER;
6378     SAVETMPS;
6379
6380     SAVEOP();
6381     PL_op = start;
6382
6383     CALLRUNOPS(aTHX);
6384
6385     FREETMPS;
6386     LEAVE;
6387
6388     {
6389         PERL_CONTEXT *cx;
6390
6391         cx = CX_CUR();
6392         assert(CxTYPE(cx) == CXt_DEFER);
6393
6394         /* since we're called during a scope cleanup (including after
6395          * a croak), theere's no guarantee thr stack is currently
6396          * ref-counted */
6397 #ifdef PERL_RC_STACK
6398         if (rpp_stack_is_rc())
6399             rpp_popfree_to_NN(PL_stack_base + cx->blk_oldsp);
6400         else
6401 #endif
6402             PL_stack_sp = PL_stack_base + cx->blk_oldsp;
6403
6404
6405         CX_LEAVE_SCOPE(cx);
6406         cx_popblock(cx);
6407         CX_POP(cx);
6408     }
6409
6410     assert(cxstack_ix == was_cxstack_ix);
6411 }
6412
6413 static void
6414 invoke_defer_block(pTHX_ void *_arg)
6415 {
6416     _invoke_defer_block(aTHX_ CXt_DEFER, _arg);
6417 }
6418
6419 static void
6420 invoke_finally_block(pTHX_ void *_arg)
6421 {
6422     _invoke_defer_block(aTHX_ CXt_DEFER|CXp_FINALLY, _arg);
6423 }
6424
6425 PP(pp_pushdefer)
6426 {
6427     if(PL_op->op_private & OPpDEFER_FINALLY)
6428         SAVEDESTRUCTOR_X(invoke_finally_block, cLOGOP->op_other);
6429     else
6430         SAVEDESTRUCTOR_X(invoke_defer_block, cLOGOP->op_other);
6431
6432     return NORMAL;
6433 }
6434
6435 static MAGIC *
6436 S_doparseform(pTHX_ SV *sv)
6437 {
6438     STRLEN len;
6439     char *s = SvPV(sv, len);
6440     char *send;
6441     char *base = NULL; /* start of current field */
6442     I32 skipspaces = 0; /* number of contiguous spaces seen */
6443     bool noblank   = FALSE; /* ~ or ~~ seen on this line */
6444     bool repeat    = FALSE; /* ~~ seen on this line */
6445     bool postspace = FALSE; /* a text field may need right padding */
6446     U32 *fops;
6447     U32 *fpc;
6448     U32 *linepc = NULL;     /* position of last FF_LINEMARK */
6449     I32 arg;
6450     bool ischop;            /* it's a ^ rather than a @ */
6451     bool unchopnum = FALSE; /* at least one @ (i.e. non-chop) num field seen */
6452     int maxops = 12; /* FF_LINEMARK + FF_END + 10 (\0 without preceding \n) */
6453     MAGIC *mg = NULL;
6454     SV *sv_copy;
6455
6456     PERL_ARGS_ASSERT_DOPARSEFORM;
6457
6458     if (len == 0)
6459         Perl_croak(aTHX_ "Null picture in formline");
6460
6461     if (SvTYPE(sv) >= SVt_PVMG) {
6462         /* This might, of course, still return NULL.  */
6463         mg = mg_find(sv, PERL_MAGIC_fm);
6464     } else {
6465         sv_upgrade(sv, SVt_PVMG);
6466     }
6467
6468     if (mg) {
6469         /* still the same as previously-compiled string? */
6470         SV *old = mg->mg_obj;
6471         if ( ! (cBOOL(SvUTF8(old)) ^ cBOOL(SvUTF8(sv)))
6472             && len == SvCUR(old)
6473             && strnEQ(SvPVX(old), s, len)
6474         ) {
6475             DEBUG_f(PerlIO_printf(Perl_debug_log,"Re-using compiled format\n"));
6476             return mg;
6477         }
6478
6479         DEBUG_f(PerlIO_printf(Perl_debug_log, "Re-compiling format\n"));
6480         Safefree(mg->mg_ptr);
6481         mg->mg_ptr = NULL;
6482         SvREFCNT_dec(old);
6483         mg->mg_obj = NULL;
6484     }
6485     else {
6486         DEBUG_f(PerlIO_printf(Perl_debug_log, "Compiling format\n"));
6487         mg = sv_magicext(sv, NULL, PERL_MAGIC_fm, &PL_vtbl_fm, NULL, 0);
6488     }
6489
6490     sv_copy = newSVpvn_utf8(s, len, SvUTF8(sv));
6491     s = SvPV(sv_copy, len); /* work on the copy, not the original */
6492     send = s + len;
6493
6494
6495     /* estimate the buffer size needed */
6496     for (base = s; s <= send; s++) {
6497         if (*s == '\n' || *s == '@' || *s == '^')
6498             maxops += 10;
6499     }
6500     s = base;
6501     base = NULL;
6502
6503     Newx(fops, maxops, U32);
6504     fpc = fops;
6505
6506     if (s < send) {
6507         linepc = fpc;
6508         *fpc++ = FF_LINEMARK;
6509         noblank = repeat = FALSE;
6510         base = s;
6511     }
6512
6513     while (s <= send) {
6514         switch (*s++) {
6515         default:
6516             skipspaces = 0;
6517             continue;
6518
6519         case '~':
6520             if (*s == '~') {
6521                 repeat = TRUE;
6522                 skipspaces++;
6523                 s++;
6524             }
6525             noblank = TRUE;
6526             /* FALLTHROUGH */
6527         case ' ': case '\t':
6528             skipspaces++;
6529             continue;
6530         case 0:
6531             if (s < send) {
6532                 skipspaces = 0;
6533                 continue;
6534             }
6535             /* FALLTHROUGH */
6536         case '\n':
6537             arg = s - base;
6538             skipspaces++;
6539             arg -= skipspaces;
6540             if (arg) {
6541                 if (postspace)
6542                     *fpc++ = FF_SPACE;
6543                 *fpc++ = FF_LITERAL;
6544                 *fpc++ = (U32)arg;
6545             }
6546             postspace = FALSE;
6547             if (s <= send)
6548                 skipspaces--;
6549             if (skipspaces) {
6550                 *fpc++ = FF_SKIP;
6551                 *fpc++ = (U32)skipspaces;
6552             }
6553             skipspaces = 0;
6554             if (s <= send)
6555                 *fpc++ = FF_NEWLINE;
6556             if (noblank) {
6557                 *fpc++ = FF_BLANK;
6558                 if (repeat)
6559                     arg = fpc - linepc + 1;
6560                 else
6561                     arg = 0;
6562                 *fpc++ = (U32)arg;
6563             }
6564             if (s < send) {
6565                 linepc = fpc;
6566                 *fpc++ = FF_LINEMARK;
6567                 noblank = repeat = FALSE;
6568                 base = s;
6569             }
6570             else
6571                 s++;
6572             continue;
6573
6574         case '@':
6575         case '^':
6576             ischop = s[-1] == '^';
6577
6578             if (postspace) {
6579                 *fpc++ = FF_SPACE;
6580                 postspace = FALSE;
6581             }
6582             arg = (s - base) - 1;
6583             if (arg) {
6584                 *fpc++ = FF_LITERAL;
6585                 *fpc++ = (U32)arg;
6586             }
6587
6588             base = s - 1;
6589             *fpc++ = FF_FETCH;
6590             if (*s == '*') { /*  @* or ^*  */
6591                 s++;
6592                 *fpc++ = 2;  /* skip the @* or ^* */
6593                 if (ischop) {
6594                     *fpc++ = FF_LINESNGL;
6595                     *fpc++ = FF_CHOP;
6596                 } else
6597                     *fpc++ = FF_LINEGLOB;
6598             }
6599             else if (*s == '#' || (*s == '.' && s[1] == '#')) { /* @###, ^### */
6600                 arg = ischop ? FORM_NUM_BLANK : 0;
6601                 base = s - 1;
6602                 while (*s == '#')
6603                     s++;
6604                 if (*s == '.') {
6605                     const char * const f = ++s;
6606                     while (*s == '#')
6607                         s++;
6608                     arg |= FORM_NUM_POINT + (s - f);
6609                 }
6610                 *fpc++ = s - base;              /* fieldsize for FETCH */
6611                 *fpc++ = FF_DECIMAL;
6612                 *fpc++ = (U32)arg;
6613                 unchopnum |= ! ischop;
6614             }
6615             else if (*s == '0' && s[1] == '#') {  /* Zero padded decimals */
6616                 arg = ischop ? FORM_NUM_BLANK : 0;
6617                 base = s - 1;
6618                 s++;                                /* skip the '0' first */
6619                 while (*s == '#')
6620                     s++;
6621                 if (*s == '.') {
6622                     const char * const f = ++s;
6623                     while (*s == '#')
6624                         s++;
6625                     arg |= FORM_NUM_POINT + (s - f);
6626                 }
6627                 *fpc++ = s - base;                /* fieldsize for FETCH */
6628                 *fpc++ = FF_0DECIMAL;
6629                 *fpc++ = (U32)arg;
6630                 unchopnum |= ! ischop;
6631             }
6632             else {                              /* text field */
6633                 I32 prespace = 0;
6634                 bool ismore = FALSE;
6635
6636                 if (*s == '>') {
6637                     while (*++s == '>') ;
6638                     prespace = FF_SPACE;
6639                 }
6640                 else if (*s == '|') {
6641                     while (*++s == '|') ;
6642                     prespace = FF_HALFSPACE;
6643                     postspace = TRUE;
6644                 }
6645                 else {
6646                     if (*s == '<')
6647                         while (*++s == '<') ;
6648                     postspace = TRUE;
6649                 }
6650                 if (*s == '.' && s[1] == '.' && s[2] == '.') {
6651                     s += 3;
6652                     ismore = TRUE;
6653                 }
6654                 *fpc++ = s - base;              /* fieldsize for FETCH */
6655
6656                 *fpc++ = ischop ? FF_CHECKCHOP : FF_CHECKNL;
6657
6658                 if (prespace)
6659                     *fpc++ = (U32)prespace; /* add SPACE or HALFSPACE */
6660                 *fpc++ = FF_ITEM;
6661                 if (ismore)
6662                     *fpc++ = FF_MORE;
6663                 if (ischop)
6664                     *fpc++ = FF_CHOP;
6665             }
6666             base = s;
6667             skipspaces = 0;
6668             continue;
6669         }
6670     }
6671     *fpc++ = FF_END;
6672
6673     assert (fpc <= fops + maxops); /* ensure our buffer estimate was valid */
6674     arg = fpc - fops;
6675
6676     mg->mg_ptr = (char *) fops;
6677     mg->mg_len = arg * sizeof(U32);
6678     mg->mg_obj = sv_copy;
6679     mg->mg_flags |= MGf_REFCOUNTED;
6680
6681     if (unchopnum && repeat)
6682         Perl_die(aTHX_ "Repeated format line will never terminate (~~ and @#)");
6683
6684     return mg;
6685 }
6686
6687
6688 STATIC bool
6689 S_num_overflow(NV value, I32 fldsize, I32 frcsize)
6690 {
6691     /* Can value be printed in fldsize chars, using %*.*f ? */
6692     NV pwr = 1;
6693     NV eps = 0.5;
6694     bool res = FALSE;
6695     int intsize = fldsize - (value < 0 ? 1 : 0);
6696
6697     if (frcsize & FORM_NUM_POINT)
6698         intsize--;
6699     frcsize &= ~(FORM_NUM_POINT|FORM_NUM_BLANK);
6700     intsize -= frcsize;
6701
6702     while (intsize--) pwr *= 10.0;
6703     while (frcsize--) eps /= 10.0;
6704
6705     if( value >= 0 ){
6706         if (value + eps >= pwr)
6707             res = TRUE;
6708     } else {
6709         if (value - eps <= -pwr)
6710             res = TRUE;
6711     }
6712     return res;
6713 }
6714
6715 static I32
6716 S_run_user_filter(pTHX_ int idx, SV *buf_sv, int maxlen)
6717 {
6718     SV * const datasv = FILTER_DATA(idx);
6719     const int filter_has_file = IoLINES(datasv);
6720     SV * const filter_state = MUTABLE_SV(IoTOP_GV(datasv));
6721     SV * const filter_sub = MUTABLE_SV(IoBOTTOM_GV(datasv));
6722     int status = 0;
6723     SV *upstream;
6724     STRLEN got_len;
6725     char *got_p = NULL;
6726     char *prune_from = NULL;
6727     bool read_from_cache = FALSE;
6728     STRLEN umaxlen;
6729     SV *err = NULL;
6730
6731     PERL_ARGS_ASSERT_RUN_USER_FILTER;
6732
6733     assert(maxlen >= 0);
6734     umaxlen = maxlen;
6735
6736     /* I was having segfault trouble under Linux 2.2.5 after a
6737        parse error occurred.  (Had to hack around it with a test
6738        for PL_parser->error_count == 0.)  Solaris doesn't segfault --
6739        not sure where the trouble is yet.  XXX */
6740
6741     {
6742         SV *const cache = datasv;
6743         if (SvOK(cache)) {
6744             STRLEN cache_len;
6745             const char *cache_p = SvPV(cache, cache_len);
6746             STRLEN take = 0;
6747
6748             if (umaxlen) {
6749                 /* Running in block mode and we have some cached data already.
6750                  */
6751                 if (cache_len >= umaxlen) {
6752                     /* In fact, so much data we don't even need to call
6753                        filter_read.  */
6754                     take = umaxlen;
6755                 }
6756             } else {
6757                 const char *const first_nl =
6758                     (const char *)memchr(cache_p, '\n', cache_len);
6759                 if (first_nl) {
6760                     take = first_nl + 1 - cache_p;
6761                 }
6762             }
6763             if (take) {
6764                 sv_catpvn(buf_sv, cache_p, take);
6765                 sv_chop(cache, cache_p + take);
6766                 /* Definitely not EOF  */
6767                 return 1;
6768             }
6769
6770             sv_catsv(buf_sv, cache);
6771             if (umaxlen) {
6772                 umaxlen -= cache_len;
6773             }
6774             SvOK_off(cache);
6775             read_from_cache = TRUE;
6776         }
6777     }
6778
6779     /* Filter API says that the filter appends to the contents of the buffer.
6780        Usually the buffer is "", so the details don't matter. But if it's not,
6781        then clearly what it contains is already filtered by this filter, so we
6782        don't want to pass it in a second time.
6783        I'm going to use a mortal in case the upstream filter croaks.  */
6784     upstream = ((SvOK(buf_sv) && sv_len(buf_sv)) || SvGMAGICAL(buf_sv))
6785         ? newSV_type_mortal(SVt_PV) : buf_sv;
6786     SvUPGRADE(upstream, SVt_PV);
6787         
6788     if (filter_has_file) {
6789         status = FILTER_READ(idx+1, upstream, 0);
6790     }
6791
6792     if (filter_sub && status >= 0) {
6793         dSP;
6794         int count;
6795
6796         ENTER_with_name("call_filter_sub");
6797         SAVE_DEFSV;
6798         SAVETMPS;
6799         EXTEND(SP, 2);
6800
6801         DEFSV_set(upstream);
6802         PUSHMARK(SP);
6803         PUSHs(&PL_sv_zero);
6804         if (filter_state) {
6805             PUSHs(filter_state);
6806         }
6807         PUTBACK;
6808         count = call_sv(filter_sub, G_SCALAR|G_EVAL);
6809         SPAGAIN;
6810
6811         if (count > 0) {
6812             SV *out = POPs;
6813             SvGETMAGIC(out);
6814             if (SvOK(out)) {
6815                 status = SvIV(out);
6816             }
6817             else {
6818                 SV * const errsv = ERRSV;
6819                 if (SvTRUE_NN(errsv))
6820                     err = newSVsv(errsv);
6821             }
6822         }
6823
6824         PUTBACK;
6825         FREETMPS;
6826         LEAVE_with_name("call_filter_sub");
6827     }
6828
6829     if (SvGMAGICAL(upstream)) {
6830         mg_get(upstream);
6831         if (upstream == buf_sv) mg_free(buf_sv);
6832     }
6833     if (SvIsCOW(upstream)) sv_force_normal(upstream);
6834     if(!err && SvOK(upstream)) {
6835         got_p = SvPV_nomg(upstream, got_len);
6836         if (umaxlen) {
6837             if (got_len > umaxlen) {
6838                 prune_from = got_p + umaxlen;
6839             }
6840         } else {
6841             char *const first_nl = (char *)memchr(got_p, '\n', got_len);
6842             if (first_nl && first_nl + 1 < got_p + got_len) {
6843                 /* There's a second line here... */
6844                 prune_from = first_nl + 1;
6845             }
6846         }
6847     }
6848     if (!err && prune_from) {
6849         /* Oh. Too long. Stuff some in our cache.  */
6850         STRLEN cached_len = got_p + got_len - prune_from;
6851         SV *const cache = datasv;
6852
6853         if (SvOK(cache)) {
6854             /* Cache should be empty.  */
6855             assert(!SvCUR(cache));
6856         }
6857
6858         sv_setpvn(cache, prune_from, cached_len);
6859         /* If you ask for block mode, you may well split UTF-8 characters.
6860            "If it breaks, you get to keep both parts"
6861            (Your code is broken if you  don't put them back together again
6862            before something notices.) */
6863         if (SvUTF8(upstream)) {
6864             SvUTF8_on(cache);
6865         }
6866         if (SvPOK(upstream)) SvCUR_set(upstream, got_len - cached_len);
6867         else
6868             /* Cannot just use sv_setpvn, as that could free the buffer
6869                before we have a chance to assign it. */
6870             sv_usepvn(upstream, savepvn(got_p, got_len - cached_len),
6871                       got_len - cached_len);
6872         *prune_from = 0;
6873         /* Can't yet be EOF  */
6874         if (status == 0)
6875             status = 1;
6876     }
6877
6878     /* If they are at EOF but buf_sv has something in it, then they may never
6879        have touched the SV upstream, so it may be undefined.  If we naively
6880        concatenate it then we get a warning about use of uninitialised value.
6881     */
6882     if (!err && upstream != buf_sv &&
6883         SvOK(upstream)) {
6884         sv_catsv_nomg(buf_sv, upstream);
6885     }
6886     else if (SvOK(upstream)) (void)SvPV_force_nolen(buf_sv);
6887
6888     if (status <= 0) {
6889         IoLINES(datasv) = 0;
6890         if (filter_state) {
6891             SvREFCNT_dec(filter_state);
6892             IoTOP_GV(datasv) = NULL;
6893         }
6894         if (filter_sub) {
6895             SvREFCNT_dec(filter_sub);
6896             IoBOTTOM_GV(datasv) = NULL;
6897         }
6898         filter_del(S_run_user_filter);
6899     }
6900
6901     if (err)
6902         croak_sv(err);
6903
6904     if (status == 0 && read_from_cache) {
6905         /* If we read some data from the cache (and by getting here it implies
6906            that we emptied the cache) then we aren't yet at EOF, and mustn't
6907            report that to our caller.  */
6908         return 1;
6909     }
6910     return status;
6911 }
6912
6913 /*
6914  * ex: set ts=8 sts=4 sw=4 et:
6915  */