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
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.
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.
19 * [Bilbo on p.35 of _The Lord of the Rings_, I/i: "A Long-Expected Party"]
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.
28 * Control-oriented means things like pp_enteriter() and pp_next(), which
29 * alter the flow of control of the program.
34 #define PERL_IN_PP_CTL_C
38 #define RUN_PP_CATCHABLY(thispp) \
39 STMT_START { if (CATCH_GET) return docatch(thispp); } STMT_END
41 #define dopopto_cursub() \
42 (PL_curstackinfo->si_cxsubix >= 0 \
43 ? PL_curstackinfo->si_cxsubix \
44 : dopoptosub_at(cxstack, cxstack_ix))
46 #define dopoptosub(plop) dopoptosub_at(cxstack, (plop))
52 const PERL_CONTEXT *cx;
55 if (PL_op->op_private & OPpOFFBYONE) {
56 if (!(cx = caller_cx(1,NULL))) RETPUSHUNDEF;
59 cxix = dopopto_cursub();
65 switch (cx->blk_gimme) {
84 PMOP *pm = (PMOP*)cLOGOP->op_other;
89 const regexp_engine *eng;
90 bool is_bare_re= FALSE;
92 if (PL_op->op_flags & OPf_STACKED) {
102 /* prevent recompiling under /o and ithreads. */
103 #if defined(USE_ITHREADS)
104 if (pm->op_pmflags & PMf_KEEP && PM_GETRE(pm)) {
111 assert (re != (REGEXP*) &PL_sv_undef);
112 eng = re ? RX_ENGINE(re) : current_re_engine();
114 new_re = (eng->op_comp
116 : &Perl_re_op_compile
117 )(aTHX_ args, nargs, pm->op_code_list, eng, re,
119 (pm->op_pmflags & RXf_PMf_FLAGCOPYMASK),
121 (PL_op->op_flags & OPf_SPECIAL ? PMf_USE_RE_EVAL : 0));
123 if (pm->op_pmflags & PMf_HAS_CV)
124 ReANY(new_re)->qr_anoncv
125 = (CV*) SvREFCNT_inc(PAD_SV(PL_op->op_targ));
129 /* The match's LHS's get-magic might need to access this op's regexp
130 (e.g. $' =~ /$re/ while foo; see bug 70764). So we must call
131 get-magic now before we replace the regexp. Hopefully this hack can
132 be replaced with the approach described at
133 http://www.nntp.perl.org/group/perl.perl5.porters/2007/03/msg122415.html
135 if (pm->op_type == OP_MATCH) {
137 const bool was_tainted = TAINT_get;
138 if (pm->op_flags & OPf_STACKED)
140 else if (pm->op_targ)
141 lhs = PAD_SV(pm->op_targ);
144 /* Restore the previous value of PL_tainted (which may have been
145 modified by get-magic), to avoid incorrectly setting the
146 RXf_TAINTED flag with RX_TAINT_on further down. */
147 TAINT_set(was_tainted);
148 #ifdef NO_TAINT_SUPPORT
149 PERL_UNUSED_VAR(was_tainted);
152 tmp = reg_temp_copy(NULL, new_re);
153 ReREFCNT_dec(new_re);
159 PM_SETRE(pm, new_re);
163 assert(TAINTING_get || !TAINT_get);
165 SvTAINTED_on((SV*)new_re);
169 /* handle the empty pattern */
170 if (!RX_PRELEN(PM_GETRE(pm)) && PL_curpm) {
171 if (PL_curpm == PL_reg_curpm) {
172 if (PL_curpm_under && PL_curpm_under == PL_reg_curpm) {
173 Perl_croak(aTHX_ "Infinite recursion via empty pattern");
178 #if !defined(USE_ITHREADS)
179 /* can't change the optree at runtime either */
180 /* PMf_KEEP is handled differently under threads to avoid these problems */
181 if (pm->op_pmflags & PMf_KEEP) {
182 cLOGOP->op_first->op_next = PL_op->op_next;
194 PERL_CONTEXT *cx = CX_CUR();
195 PMOP * const pm = (PMOP*) cLOGOP->op_other;
196 SV * const dstr = cx->sb_dstr;
199 char *orig = cx->sb_orig;
200 REGEXP * const rx = cx->sb_rx;
202 REGEXP *old = PM_GETRE(pm);
209 PM_SETRE(pm,ReREFCNT_inc(rx));
212 rxres_restore(&cx->sb_rxres, rx);
214 if (cx->sb_iters++) {
215 const SSize_t saviters = cx->sb_iters;
216 if (cx->sb_iters > cx->sb_maxiters)
217 DIE(aTHX_ "Substitution loop");
219 SvGETMAGIC(TOPs); /* possibly clear taint on $1 etc: #67962 */
221 /* See "how taint works" above pp_subst() */
222 sv_catsv_nomg(dstr, POPs);
223 if (UNLIKELY(TAINT_get))
224 cx->sb_rxtainted |= SUBST_TAINT_REPL;
225 if (CxONCE(cx) || s < orig ||
226 !CALLREGEXEC(rx, s, cx->sb_strend, orig,
227 (s == m), cx->sb_targ, NULL,
228 (REXEC_IGNOREPOS|REXEC_NOT_FIRST|REXEC_FAIL_ON_UNDERFLOW)))
230 SV *targ = cx->sb_targ;
232 assert(cx->sb_strend >= s);
233 if(cx->sb_strend > s) {
234 if (DO_UTF8(dstr) && !SvUTF8(targ))
235 sv_catpvn_nomg_utf8_upgrade(dstr, s, cx->sb_strend - s, nsv);
237 sv_catpvn_nomg(dstr, s, cx->sb_strend - s);
239 if (RX_MATCH_TAINTED(rx)) /* run time pattern taint, eg locale */
240 cx->sb_rxtainted |= SUBST_TAINT_PAT;
242 if (pm->op_pmflags & PMf_NONDESTRUCT) {
244 /* From here on down we're using the copy, and leaving the
245 original untouched. */
249 SV_CHECK_THINKFIRST_COW_DROP(targ);
250 if (isGV(targ)) Perl_croak_no_modify();
252 SvPV_set(targ, SvPVX(dstr));
253 SvCUR_set(targ, SvCUR(dstr));
254 SvLEN_set(targ, SvLEN(dstr));
257 SvPV_set(dstr, NULL);
260 mPUSHi(saviters - 1);
262 (void)SvPOK_only_UTF8(targ);
265 /* update the taint state of various various variables in
266 * preparation for final exit.
267 * See "how taint works" above pp_subst() */
269 if ((cx->sb_rxtainted & SUBST_TAINT_PAT) ||
270 ((cx->sb_rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
271 == (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
273 (RX_MATCH_TAINTED_on(rx)); /* taint $1 et al */
275 if (!(cx->sb_rxtainted & SUBST_TAINT_BOOLRET)
276 && (cx->sb_rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_PAT))
278 SvTAINTED_on(TOPs); /* taint return value */
279 /* needed for mg_set below */
281 cBOOL(cx->sb_rxtainted &
282 (SUBST_TAINT_STR|SUBST_TAINT_PAT|SUBST_TAINT_REPL))
285 /* sv_magic(), when adding magic (e.g.taint magic), also
286 * recalculates any pos() magic, converting any byte offset
287 * to utf8 offset. Make sure pos() is reset before this
288 * happens rather than using the now invalid value (since
289 * we've just replaced targ's pvx buffer with the
290 * potentially shorter dstr buffer). Normally (i.e. in
291 * non-taint cases), pos() gets removed a few lines later
292 * with the SvSETMAGIC().
296 mg = mg_find_mglob(targ);
298 MgBYTEPOS_set(mg, targ, SvPVX(targ), -1);
304 /* PL_tainted must be correctly set for this mg_set */
313 RETURNOP(pm->op_next);
314 NOT_REACHED; /* NOTREACHED */
316 cx->sb_iters = saviters;
318 if (RX_MATCH_COPIED(rx) && RX_SUBBEG(rx) != orig) {
321 assert(!RX_SUBOFFSET(rx));
322 cx->sb_orig = orig = RX_SUBBEG(rx);
324 cx->sb_strend = s + (cx->sb_strend - m);
326 cx->sb_m = m = RX_OFFS(rx)[0].start + orig;
328 if (DO_UTF8(dstr) && !SvUTF8(cx->sb_targ))
329 sv_catpvn_nomg_utf8_upgrade(dstr, s, m - s, nsv);
331 sv_catpvn_nomg(dstr, s, m-s);
333 cx->sb_s = RX_OFFS(rx)[0].end + orig;
334 { /* Update the pos() information. */
336 = (pm->op_pmflags & PMf_NONDESTRUCT) ? cx->sb_dstr : cx->sb_targ;
339 /* the string being matched against may no longer be a string,
340 * e.g. $_=0; s/.../$_++/ge */
343 SvPV_force_nomg_nolen(sv);
345 if (!(mg = mg_find_mglob(sv))) {
346 mg = sv_magicext_mglob(sv);
348 MgBYTEPOS_set(mg, sv, SvPVX(sv), m - orig);
351 (void)ReREFCNT_inc(rx);
352 /* update the taint state of various various variables in preparation
353 * for calling the code block.
354 * See "how taint works" above pp_subst() */
356 if (RX_MATCH_TAINTED(rx)) /* run time pattern taint, eg locale */
357 cx->sb_rxtainted |= SUBST_TAINT_PAT;
359 if ((cx->sb_rxtainted & SUBST_TAINT_PAT) ||
360 ((cx->sb_rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
361 == (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
363 (RX_MATCH_TAINTED_on(rx)); /* taint $1 et al */
365 if (cx->sb_iters > 1 && (cx->sb_rxtainted &
366 (SUBST_TAINT_STR|SUBST_TAINT_PAT|SUBST_TAINT_REPL)))
367 SvTAINTED_on((pm->op_pmflags & PMf_NONDESTRUCT)
368 ? cx->sb_dstr : cx->sb_targ);
371 rxres_save(&cx->sb_rxres, rx);
373 RETURNOP(pm->op_pmstashstartu.op_pmreplstart);
377 Perl_rxres_save(pTHX_ void **rsp, REGEXP *rx)
382 PERL_ARGS_ASSERT_RXRES_SAVE;
385 if (!p || p[1] < RX_NPARENS(rx)) {
387 i = 7 + (RX_NPARENS(rx)+1) * 2;
389 i = 6 + (RX_NPARENS(rx)+1) * 2;
398 /* what (if anything) to free on croak */
399 *p++ = PTR2UV(RX_MATCH_COPIED(rx) ? RX_SUBBEG(rx) : NULL);
400 RX_MATCH_COPIED_off(rx);
401 *p++ = RX_NPARENS(rx);
404 *p++ = PTR2UV(RX_SAVED_COPY(rx));
405 RX_SAVED_COPY(rx) = NULL;
408 *p++ = PTR2UV(RX_SUBBEG(rx));
409 *p++ = (UV)RX_SUBLEN(rx);
410 *p++ = (UV)RX_SUBOFFSET(rx);
411 *p++ = (UV)RX_SUBCOFFSET(rx);
412 for (i = 0; i <= RX_NPARENS(rx); ++i) {
413 *p++ = (UV)RX_OFFS(rx)[i].start;
414 *p++ = (UV)RX_OFFS(rx)[i].end;
419 S_rxres_restore(pTHX_ void **rsp, REGEXP *rx)
424 PERL_ARGS_ASSERT_RXRES_RESTORE;
427 RX_MATCH_COPY_FREE(rx);
428 RX_MATCH_COPIED_set(rx, *p);
430 RX_NPARENS(rx) = *p++;
433 if (RX_SAVED_COPY(rx))
434 SvREFCNT_dec (RX_SAVED_COPY(rx));
435 RX_SAVED_COPY(rx) = INT2PTR(SV*,*p);
439 RX_SUBBEG(rx) = INT2PTR(char*,*p++);
440 RX_SUBLEN(rx) = (I32)(*p++);
441 RX_SUBOFFSET(rx) = (I32)*p++;
442 RX_SUBCOFFSET(rx) = (I32)*p++;
443 for (i = 0; i <= RX_NPARENS(rx); ++i) {
444 RX_OFFS(rx)[i].start = (I32)(*p++);
445 RX_OFFS(rx)[i].end = (I32)(*p++);
450 S_rxres_free(pTHX_ void **rsp)
452 UV * const p = (UV*)*rsp;
454 PERL_ARGS_ASSERT_RXRES_FREE;
458 void *tmp = INT2PTR(char*,*p);
461 U32 i = 9 + p[1] * 2;
463 U32 i = 8 + p[1] * 2;
468 SvREFCNT_dec (INT2PTR(SV*,p[2]));
471 PoisonFree(p, i, sizeof(UV));
480 #define FORM_NUM_BLANK (1<<30)
481 #define FORM_NUM_POINT (1<<29)
485 dSP; dMARK; dORIGMARK;
486 SV * const tmpForm = *++MARK;
487 SV *formsv; /* contains text of original format */
488 U32 *fpc; /* format ops program counter */
489 char *t; /* current append position in target string */
490 const char *f; /* current position in format string */
492 SV *sv = NULL; /* current item */
493 const char *item = NULL;/* string value of current item */
494 I32 itemsize = 0; /* length (chars) of item, possibly truncated */
495 I32 itembytes = 0; /* as itemsize, but length in bytes */
496 I32 fieldsize = 0; /* width of current field */
497 I32 lines = 0; /* number of lines that have been output */
498 bool chopspace = (strchr(PL_chopset, ' ') != NULL); /* does $: have space */
499 const char *chophere = NULL; /* where to chop current item */
500 STRLEN linemark = 0; /* pos of start of line in output */
502 bool gotsome = FALSE; /* seen at least one non-blank item on this line */
503 STRLEN len; /* length of current sv */
504 STRLEN linemax; /* estimate of output size in bytes */
505 bool item_is_utf8 = FALSE;
506 bool targ_is_utf8 = FALSE;
509 U8 *source; /* source of bytes to append */
510 STRLEN to_copy; /* how may bytes to append */
511 char trans; /* what chars to translate */
512 bool copied_form = FALSE; /* have we duplicated the form? */
514 mg = doparseform(tmpForm);
516 fpc = (U32*)mg->mg_ptr;
517 /* the actual string the format was compiled from.
518 * with overload etc, this may not match tmpForm */
522 SvPV_force(PL_formtarget, len);
523 if (SvTAINTED(tmpForm) || SvTAINTED(formsv))
524 SvTAINTED_on(PL_formtarget);
525 if (DO_UTF8(PL_formtarget))
527 /* this is an initial estimate of how much output buffer space
528 * to allocate. It may be exceeded later */
529 linemax = (SvCUR(formsv) * (IN_BYTES ? 1 : 3) + 1);
530 t = SvGROW(PL_formtarget, len + linemax + 1);
531 /* XXX from now onwards, SvCUR(PL_formtarget) is invalid */
533 f = SvPV_const(formsv, len);
537 const char *name = "???";
540 case FF_LITERAL: arg = fpc[1]; name = "LITERAL"; break;
541 case FF_BLANK: arg = fpc[1]; name = "BLANK"; break;
542 case FF_SKIP: arg = fpc[1]; name = "SKIP"; break;
543 case FF_FETCH: arg = fpc[1]; name = "FETCH"; break;
544 case FF_DECIMAL: arg = fpc[1]; name = "DECIMAL"; break;
546 case FF_CHECKNL: name = "CHECKNL"; break;
547 case FF_CHECKCHOP: name = "CHECKCHOP"; break;
548 case FF_SPACE: name = "SPACE"; break;
549 case FF_HALFSPACE: name = "HALFSPACE"; break;
550 case FF_ITEM: name = "ITEM"; break;
551 case FF_CHOP: name = "CHOP"; break;
552 case FF_LINEGLOB: name = "LINEGLOB"; break;
553 case FF_NEWLINE: name = "NEWLINE"; break;
554 case FF_MORE: name = "MORE"; break;
555 case FF_LINEMARK: name = "LINEMARK"; break;
556 case FF_END: name = "END"; break;
557 case FF_0DECIMAL: name = "0DECIMAL"; break;
558 case FF_LINESNGL: name = "LINESNGL"; break;
561 PerlIO_printf(Perl_debug_log, "%-16s%ld\n", name, (long) arg);
563 PerlIO_printf(Perl_debug_log, "%-16s\n", name);
566 case FF_LINEMARK: /* start (or end) of a line */
567 linemark = t - SvPVX(PL_formtarget);
572 case FF_LITERAL: /* append <arg> literal chars */
577 item_is_utf8 = targ_is_utf8 ? !!DO_UTF8(formsv) : !!SvUTF8(formsv);
580 case FF_SKIP: /* skip <arg> chars in format */
584 case FF_FETCH: /* get next item and set field size to <arg> */
593 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "Not enough format arguments");
596 SvTAINTED_on(PL_formtarget);
599 case FF_CHECKNL: /* find max len of item (up to \n) that fits field */
601 const char *s = item = SvPV_const(sv, len);
602 const char *send = s + len;
605 item_is_utf8 = DO_UTF8(sv);
617 if (itemsize == fieldsize)
620 itembytes = s - item;
625 case FF_CHECKCHOP: /* like CHECKNL, but up to highest split point */
627 const char *s = item = SvPV_const(sv, len);
628 const char *send = s + len;
632 item_is_utf8 = DO_UTF8(sv);
634 /* look for a legal split position */
642 /* provisional split point */
646 /* we delay testing fieldsize until after we've
647 * processed the possible split char directly
648 * following the last field char; so if fieldsize=3
649 * and item="a b cdef", we consume "a b", not "a".
650 * Ditto further down.
652 if (size == fieldsize)
656 if (strchr(PL_chopset, *s)) {
657 /* provisional split point */
658 /* for a non-space split char, we include
659 * the split char; hence the '+1' */
663 if (size == fieldsize)
675 if (!chophere || s == send) {
679 itembytes = chophere - item;
684 case FF_SPACE: /* append padding space (diff of field, item size) */
685 arg = fieldsize - itemsize;
693 case FF_HALFSPACE: /* like FF_SPACE, but only append half as many */
694 arg = fieldsize - itemsize;
703 case FF_ITEM: /* append a text item, while blanking ctrl chars */
709 case FF_CHOP: /* (for ^*) chop the current item */
710 if (sv != &PL_sv_no) {
711 const char *s = chophere;
713 ((sv == tmpForm || SvSMAGICAL(sv))
714 || (SvGMAGICAL(tmpForm) && !sv_only_taint_gmagic(tmpForm))) ) {
715 /* sv and tmpForm are either the same SV, or magic might allow modification
716 of tmpForm when sv is modified, so copy */
717 SV *newformsv = sv_mortalcopy(formsv);
720 f = SvPV_nolen(newformsv) + (f - SvPV_nolen(formsv));
721 Newx(new_compiled, mg->mg_len / sizeof(U32), U32);
722 memcpy(new_compiled, mg->mg_ptr, mg->mg_len);
723 SAVEFREEPV(new_compiled);
724 fpc = new_compiled + (fpc - (U32*)mg->mg_ptr);
736 /* tied, overloaded or similar strangeness.
737 * Do it the hard way */
738 sv_setpvn(sv, s, len - (s-item));
744 case FF_LINESNGL: /* process ^* */
748 case FF_LINEGLOB: /* process @* */
750 const bool oneline = fpc[-1] == FF_LINESNGL;
751 const char *s = item = SvPV_const(sv, len);
752 const char *const send = s + len;
754 item_is_utf8 = DO_UTF8(sv);
765 to_copy = s - item - 1;
779 /* append to_copy bytes from source to PL_formstring.
780 * item_is_utf8 implies source is utf8.
781 * if trans, translate certain characters during the copy */
786 SvCUR_set(PL_formtarget,
787 t - SvPVX_const(PL_formtarget));
789 if (targ_is_utf8 && !item_is_utf8) {
790 source = tmp = bytes_to_utf8(source, &to_copy);
793 if (item_is_utf8 && !targ_is_utf8) {
795 /* Upgrade targ to UTF8, and then we reduce it to
796 a problem we have a simple solution for.
797 Don't need get magic. */
798 sv_utf8_upgrade_nomg(PL_formtarget);
800 /* re-calculate linemark */
801 s = (U8*)SvPVX(PL_formtarget);
802 /* the bytes we initially allocated to append the
803 * whole line may have been gobbled up during the
804 * upgrade, so allocate a whole new line's worth
808 s += UTF8_SAFE_SKIP(s,
809 (U8 *) SvEND(PL_formtarget));
810 linemark = s - (U8*)SvPVX(PL_formtarget);
812 /* Easy. They agree. */
813 assert (item_is_utf8 == targ_is_utf8);
816 /* @* and ^* are the only things that can exceed
817 * the linemax, so grow by the output size, plus
818 * a whole new form's worth in case of any further
820 grow = linemax + to_copy;
822 SvGROW(PL_formtarget, SvCUR(PL_formtarget) + grow + 1);
823 t = SvPVX(PL_formtarget) + SvCUR(PL_formtarget);
825 Copy(source, t, to_copy, char);
827 /* blank out ~ or control chars, depending on trans.
828 * works on bytes not chars, so relies on not
829 * matching utf8 continuation bytes */
831 U8 *send = s + to_copy;
834 if (trans == '~' ? (ch == '~') : isCNTRL(ch))
841 SvCUR_set(PL_formtarget, SvCUR(PL_formtarget) + to_copy);
847 case FF_0DECIMAL: /* like FF_DECIMAL but for 0### */
850 ((arg & FORM_NUM_POINT) ? "%#0*.*" NVff : "%0*.*" NVff);
853 case FF_DECIMAL: /* do @##, ^##, where <arg>=(precision|flags) */
856 ((arg & FORM_NUM_POINT) ? "%#*.*" NVff : "%*.*" NVff);
858 /* If the field is marked with ^ and the value is undefined,
860 if ((arg & FORM_NUM_BLANK) && !SvOK(sv)) {
868 /* overflow evidence */
869 if (num_overflow(value, fieldsize, arg)) {
875 /* Formats aren't yet marked for locales, so assume "yes". */
877 Size_t max = SvLEN(PL_formtarget) - (t - SvPVX(PL_formtarget));
879 DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
880 STORE_LC_NUMERIC_SET_TO_NEEDED();
881 arg &= ~(FORM_NUM_POINT|FORM_NUM_BLANK);
884 const char* qfmt = quadmath_format_single(fmt);
887 Perl_croak_nocontext("panic: quadmath invalid format \"%s\"", fmt);
888 len = quadmath_snprintf(t, max, qfmt, (int) fieldsize, (int) arg, value);
890 Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", qfmt);
895 /* we generate fmt ourselves so it is safe */
896 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
897 len = my_snprintf(t, max, fmt, (int) fieldsize, (int) arg, value);
898 GCC_DIAG_RESTORE_STMT;
900 PERL_MY_SNPRINTF_POST_GUARD(len, max);
901 RESTORE_LC_NUMERIC();
906 case FF_NEWLINE: /* delete trailing spaces, then append \n */
908 while (t-- > (SvPVX(PL_formtarget) + linemark) && *t == ' ') ;
913 case FF_BLANK: /* for arg==0: do '~'; for arg>0 : do '~~' */
916 if (arg) { /* repeat until fields exhausted? */
922 t = SvPVX(PL_formtarget) + linemark;
927 case FF_MORE: /* replace long end of string with '...' */
929 const char *s = chophere;
930 const char *send = item + len;
932 while (isSPACE(*s) && (s < send))
937 arg = fieldsize - itemsize;
944 if (strBEGINs(s1," ")) {
945 while (s1 > SvPVX_const(PL_formtarget) && isSPACE(s1[-1]))
955 case FF_END: /* tidy up, then return */
957 assert(t < SvPVX_const(PL_formtarget) + SvLEN(PL_formtarget));
959 SvCUR_set(PL_formtarget, t - SvPVX_const(PL_formtarget));
961 SvUTF8_on(PL_formtarget);
962 FmLINES(PL_formtarget) += lines;
964 if (fpc[-1] == FF_BLANK)
965 RETURNOP(cLISTOP->op_first);
972 /* also used for: pp_mapstart() */
978 if (PL_stack_base + TOPMARK == SP) {
980 if (GIMME_V == G_SCALAR)
982 RETURNOP(PL_op->op_next->op_next);
984 PL_stack_sp = PL_stack_base + TOPMARK + 1;
985 Perl_pp_pushmark(aTHX); /* push dst */
986 Perl_pp_pushmark(aTHX); /* push src */
987 ENTER_with_name("grep"); /* enter outer scope */
991 ENTER_with_name("grep_item"); /* enter inner scope */
994 src = PL_stack_base[TOPMARK];
996 src = PL_stack_base[TOPMARK] = sv_mortalcopy(src);
1003 if (PL_op->op_type == OP_MAPSTART)
1004 Perl_pp_pushmark(aTHX); /* push top */
1005 return ((LOGOP*)PL_op->op_next)->op_other;
1011 const U8 gimme = GIMME_V;
1012 I32 items = (SP - PL_stack_base) - TOPMARK; /* how many new items */
1018 /* first, move source pointer to the next item in the source list */
1019 ++PL_markstack_ptr[-1];
1021 /* if there are new items, push them into the destination list */
1022 if (items && gimme != G_VOID) {
1023 /* might need to make room back there first */
1024 if (items > PL_markstack_ptr[-1] - PL_markstack_ptr[-2]) {
1025 /* XXX this implementation is very pessimal because the stack
1026 * is repeatedly extended for every set of items. Is possible
1027 * to do this without any stack extension or copying at all
1028 * by maintaining a separate list over which the map iterates
1029 * (like foreach does). --gsar */
1031 /* everything in the stack after the destination list moves
1032 * towards the end the stack by the amount of room needed */
1033 shift = items - (PL_markstack_ptr[-1] - PL_markstack_ptr[-2]);
1035 /* items to shift up (accounting for the moved source pointer) */
1036 count = (SP - PL_stack_base) - (PL_markstack_ptr[-1] - 1);
1038 /* This optimization is by Ben Tilly and it does
1039 * things differently from what Sarathy (gsar)
1040 * is describing. The downside of this optimization is
1041 * that leaves "holes" (uninitialized and hopefully unused areas)
1042 * to the Perl stack, but on the other hand this
1043 * shouldn't be a problem. If Sarathy's idea gets
1044 * implemented, this optimization should become
1045 * irrelevant. --jhi */
1047 shift = count; /* Avoid shifting too often --Ben Tilly */
1051 dst = (SP += shift);
1052 PL_markstack_ptr[-1] += shift;
1053 *PL_markstack_ptr += shift;
1057 /* copy the new items down to the destination list */
1058 dst = PL_stack_base + (PL_markstack_ptr[-2] += items) - 1;
1059 if (gimme == G_ARRAY) {
1060 /* add returned items to the collection (making mortal copies
1061 * if necessary), then clear the current temps stack frame
1062 * *except* for those items. We do this splicing the items
1063 * into the start of the tmps frame (so some items may be on
1064 * the tmps stack twice), then moving PL_tmps_floor above
1065 * them, then freeing the frame. That way, the only tmps that
1066 * accumulate over iterations are the return values for map.
1067 * We have to do to this way so that everything gets correctly
1068 * freed if we die during the map.
1072 /* make space for the slice */
1073 EXTEND_MORTAL(items);
1074 tmpsbase = PL_tmps_floor + 1;
1075 Move(PL_tmps_stack + tmpsbase,
1076 PL_tmps_stack + tmpsbase + items,
1077 PL_tmps_ix - PL_tmps_floor,
1079 PL_tmps_ix += items;
1084 sv = sv_mortalcopy(sv);
1086 PL_tmps_stack[tmpsbase++] = SvREFCNT_inc_simple(sv);
1088 /* clear the stack frame except for the items */
1089 PL_tmps_floor += items;
1091 /* FREETMPS may have cleared the TEMP flag on some of the items */
1094 SvTEMP_on(PL_tmps_stack[--tmpsbase]);
1097 /* scalar context: we don't care about which values map returns
1098 * (we use undef here). And so we certainly don't want to do mortal
1099 * copies of meaningless values. */
1100 while (items-- > 0) {
1102 *dst-- = &PL_sv_undef;
1110 LEAVE_with_name("grep_item"); /* exit inner scope */
1113 if (PL_markstack_ptr[-1] > TOPMARK) {
1115 (void)POPMARK; /* pop top */
1116 LEAVE_with_name("grep"); /* exit outer scope */
1117 (void)POPMARK; /* pop src */
1118 items = --*PL_markstack_ptr - PL_markstack_ptr[-1];
1119 (void)POPMARK; /* pop dst */
1120 SP = PL_stack_base + POPMARK; /* pop original mark */
1121 if (gimme == G_SCALAR) {
1125 else if (gimme == G_ARRAY)
1132 ENTER_with_name("grep_item"); /* enter inner scope */
1135 /* set $_ to the new source item */
1136 src = PL_stack_base[PL_markstack_ptr[-1]];
1137 if (SvPADTMP(src)) {
1138 src = sv_mortalcopy(src);
1143 RETURNOP(cLOGOP->op_other);
1152 if (GIMME_V == G_ARRAY)
1155 if (SvTRUE_NN(targ))
1156 return cLOGOP->op_other;
1165 if (GIMME_V == G_ARRAY) {
1166 RETURNOP(((LOGOP*)cUNOP->op_first)->op_other);
1170 SV * const targ = PAD_SV(PL_op->op_targ);
1173 if (PL_op->op_private & OPpFLIP_LINENUM) {
1174 if (GvIO(PL_last_in_gv)) {
1175 flip = SvIV(sv) == (IV)IoLINES(GvIOp(PL_last_in_gv));
1178 GV * const gv = gv_fetchpvs(".", GV_ADD|GV_NOTQUAL, SVt_PV);
1180 flip = SvIV(sv) == SvIV(GvSV(gv));
1183 flip = SvTRUE_NN(sv);
1186 sv_setiv(PAD_SV(cUNOP->op_first->op_targ), 1);
1187 if (PL_op->op_flags & OPf_SPECIAL) {
1195 RETURNOP(((LOGOP*)cUNOP->op_first)->op_other);
1204 /* This code tries to decide if "$left .. $right" should use the
1205 magical string increment, or if the range is numeric. Initially,
1206 an exception was made for *any* string beginning with "0" (see
1207 [#18165], AMS 20021031), but now that is only applied when the
1208 string's length is also >1 - see the rules now documented in
1211 #define RANGE_IS_NUMERIC(left,right) ( \
1212 SvNIOKp(left) || (SvOK(left) && !SvPOKp(left)) || \
1213 SvNIOKp(right) || (SvOK(right) && !SvPOKp(right)) || \
1214 (((!SvOK(left) && SvOK(right)) || ((!SvOK(left) || \
1215 looks_like_number(left)) && SvPOKp(left) \
1216 && !(*SvPVX_const(left) == '0' && SvCUR(left)>1 ) )) \
1217 && (!SvOK(right) || looks_like_number(right))))
1223 if (GIMME_V == G_ARRAY) {
1229 if (RANGE_IS_NUMERIC(left,right)) {
1231 if ((SvOK(left) && !SvIOK(left) && SvNV_nomg(left) < IV_MIN) ||
1232 (SvOK(right) && (SvIOK(right)
1233 ? SvIsUV(right) && SvUV(right) > IV_MAX
1234 : SvNV_nomg(right) > IV_MAX)))
1235 DIE(aTHX_ "Range iterator outside integer range");
1236 i = SvIV_nomg(left);
1237 j = SvIV_nomg(right);
1239 /* Dance carefully around signed max. */
1240 bool overflow = (i <= 0 && j > SSize_t_MAX + i - 1);
1243 /* The wraparound of signed integers is undefined
1244 * behavior, but here we aim for count >=1, and
1245 * negative count is just wrong. */
1247 #if IVSIZE > Size_t_size
1254 Perl_croak(aTHX_ "Out of memory during list extend");
1261 SV * const sv = sv_2mortal(newSViv(i));
1263 if (n) /* avoid incrementing above IV_MAX */
1269 const char * const lpv = SvPV_nomg_const(left, llen);
1270 const char * const tmps = SvPV_nomg_const(right, len);
1272 SV *sv = newSVpvn_flags(lpv, llen, SvUTF8(left)|SVs_TEMP);
1273 if (DO_UTF8(right) && IN_UNI_8_BIT)
1274 len = sv_len_utf8_nomg(right);
1275 while (!SvNIOKp(sv) && SvCUR(sv) <= len) {
1277 if (strEQ(SvPVX_const(sv),tmps))
1279 sv = sv_2mortal(newSVsv(sv));
1286 SV * const targ = PAD_SV(cUNOP->op_first->op_targ);
1290 if (PL_op->op_private & OPpFLIP_LINENUM) {
1291 if (GvIO(PL_last_in_gv)) {
1292 flop = SvIV(sv) == (IV)IoLINES(GvIOp(PL_last_in_gv));
1295 GV * const gv = gv_fetchpvs(".", GV_ADD|GV_NOTQUAL, SVt_PV);
1296 if (gv && GvSV(gv)) flop = SvIV(sv) == SvIV(GvSV(gv));
1300 flop = SvTRUE_NN(sv);
1304 sv_setiv(PAD_SV(((UNOP*)cUNOP->op_first)->op_first->op_targ), 0);
1305 sv_catpvs(targ, "E0");
1315 static const char * const context_name[] = {
1317 NULL, /* CXt_WHEN never actually needs "block" */
1318 NULL, /* CXt_BLOCK never actually needs "block" */
1319 NULL, /* CXt_GIVEN never actually needs "block" */
1320 NULL, /* CXt_LOOP_PLAIN never actually needs "loop" */
1321 NULL, /* CXt_LOOP_LAZYIV never actually needs "loop" */
1322 NULL, /* CXt_LOOP_LAZYSV never actually needs "loop" */
1323 NULL, /* CXt_LOOP_LIST never actually needs "loop" */
1324 NULL, /* CXt_LOOP_ARY never actually needs "loop" */
1332 S_dopoptolabel(pTHX_ const char *label, STRLEN len, U32 flags)
1336 PERL_ARGS_ASSERT_DOPOPTOLABEL;
1338 for (i = cxstack_ix; i >= 0; i--) {
1339 const PERL_CONTEXT * const cx = &cxstack[i];
1340 switch (CxTYPE(cx)) {
1346 /* diag_listed_as: Exiting subroutine via %s */
1347 Perl_ck_warner(aTHX_ packWARN(WARN_EXITING), "Exiting %s via %s",
1348 context_name[CxTYPE(cx)], OP_NAME(PL_op));
1349 if (CxTYPE(cx) == CXt_NULL) /* sort BLOCK */
1352 case CXt_LOOP_PLAIN:
1353 case CXt_LOOP_LAZYIV:
1354 case CXt_LOOP_LAZYSV:
1358 STRLEN cx_label_len = 0;
1359 U32 cx_label_flags = 0;
1360 const char *cx_label = CxLABEL_len_flags(cx, &cx_label_len, &cx_label_flags);
1362 ( (cx_label_flags & SVf_UTF8) != (flags & SVf_UTF8) ) ?
1365 (const U8*)cx_label, cx_label_len,
1366 (const U8*)label, len) == 0)
1368 (const U8*)label, len,
1369 (const U8*)cx_label, cx_label_len) == 0)
1370 : (len == cx_label_len && ((cx_label == label)
1371 || memEQ(cx_label, label, len))) )) {
1372 DEBUG_l(Perl_deb(aTHX_ "(poptolabel(): skipping label at cx=%ld %s)\n",
1373 (long)i, cx_label));
1376 DEBUG_l( Perl_deb(aTHX_ "(poptolabel(): found label at cx=%ld %s)\n", (long)i, label));
1387 Perl_dowantarray(pTHX)
1389 const U8 gimme = block_gimme();
1390 return (gimme == G_VOID) ? G_SCALAR : gimme;
1393 /* note that this function has mostly been superseded by Perl_gimme_V */
1396 Perl_block_gimme(pTHX)
1398 const I32 cxix = dopopto_cursub();
1403 gimme = (cxstack[cxix].blk_gimme & G_WANT);
1405 Perl_croak(aTHX_ "panic: bad gimme: %d\n", gimme);
1411 Perl_is_lvalue_sub(pTHX)
1413 const I32 cxix = dopopto_cursub();
1414 assert(cxix >= 0); /* We should only be called from inside subs */
1416 if (CxLVAL(cxstack + cxix) && CvLVALUE(cxstack[cxix].blk_sub.cv))
1417 return CxLVAL(cxstack + cxix);
1422 /* only used by cx_pushsub() */
1424 Perl_was_lvalue_sub(pTHX)
1426 const I32 cxix = dopoptosub(cxstack_ix-1);
1427 assert(cxix >= 0); /* We should only be called from inside subs */
1429 if (CxLVAL(cxstack + cxix) && CvLVALUE(cxstack[cxix].blk_sub.cv))
1430 return CxLVAL(cxstack + cxix);
1436 S_dopoptosub_at(pTHX_ const PERL_CONTEXT *cxstk, I32 startingblock)
1440 PERL_ARGS_ASSERT_DOPOPTOSUB_AT;
1442 PERL_UNUSED_CONTEXT;
1445 for (i = startingblock; i >= 0; i--) {
1446 const PERL_CONTEXT * const cx = &cxstk[i];
1447 switch (CxTYPE(cx)) {
1451 /* in sub foo { /(?{...})/ }, foo ends up on the CX stack
1452 * twice; the first for the normal foo() call, and the second
1453 * for a faked up re-entry into the sub to execute the
1454 * code block. Hide this faked entry from the world. */
1455 if (cx->cx_type & CXp_SUB_RE_FAKE)
1460 DEBUG_l( Perl_deb(aTHX_ "(dopoptosub_at(): found sub at cx=%ld)\n", (long)i));
1468 S_dopoptoeval(pTHX_ I32 startingblock)
1471 for (i = startingblock; i >= 0; i--) {
1472 const PERL_CONTEXT *cx = &cxstack[i];
1473 switch (CxTYPE(cx)) {
1477 DEBUG_l( Perl_deb(aTHX_ "(dopoptoeval(): found eval at cx=%ld)\n", (long)i));
1485 S_dopoptoloop(pTHX_ I32 startingblock)
1488 for (i = startingblock; i >= 0; i--) {
1489 const PERL_CONTEXT * const cx = &cxstack[i];
1490 switch (CxTYPE(cx)) {
1496 /* diag_listed_as: Exiting subroutine via %s */
1497 Perl_ck_warner(aTHX_ packWARN(WARN_EXITING), "Exiting %s via %s",
1498 context_name[CxTYPE(cx)], OP_NAME(PL_op));
1499 if ((CxTYPE(cx)) == CXt_NULL) /* sort BLOCK */
1502 case CXt_LOOP_PLAIN:
1503 case CXt_LOOP_LAZYIV:
1504 case CXt_LOOP_LAZYSV:
1507 DEBUG_l( Perl_deb(aTHX_ "(dopoptoloop(): found loop at cx=%ld)\n", (long)i));
1514 /* find the next GIVEN or FOR (with implicit $_) loop context block */
1517 S_dopoptogivenfor(pTHX_ I32 startingblock)
1520 for (i = startingblock; i >= 0; i--) {
1521 const PERL_CONTEXT *cx = &cxstack[i];
1522 switch (CxTYPE(cx)) {
1526 DEBUG_l( Perl_deb(aTHX_ "(dopoptogivenfor(): found given at cx=%ld)\n", (long)i));
1528 case CXt_LOOP_PLAIN:
1529 assert(!(cx->cx_type & CXp_FOR_DEF));
1531 case CXt_LOOP_LAZYIV:
1532 case CXt_LOOP_LAZYSV:
1535 if (cx->cx_type & CXp_FOR_DEF) {
1536 DEBUG_l( Perl_deb(aTHX_ "(dopoptogivenfor(): found foreach at cx=%ld)\n", (long)i));
1545 S_dopoptowhen(pTHX_ I32 startingblock)
1548 for (i = startingblock; i >= 0; i--) {
1549 const PERL_CONTEXT *cx = &cxstack[i];
1550 switch (CxTYPE(cx)) {
1554 DEBUG_l( Perl_deb(aTHX_ "(dopoptowhen(): found when at cx=%ld)\n", (long)i));
1561 /* dounwind(): pop all contexts above (but not including) cxix.
1562 * Note that it clears the savestack frame associated with each popped
1563 * context entry, but doesn't free any temps.
1564 * It does a cx_popblock() of the last frame that it pops, and leaves
1565 * cxstack_ix equal to cxix.
1569 Perl_dounwind(pTHX_ I32 cxix)
1571 if (!PL_curstackinfo) /* can happen if die during thread cloning */
1574 while (cxstack_ix > cxix) {
1575 PERL_CONTEXT *cx = CX_CUR();
1577 CX_DEBUG(cx, "UNWIND");
1578 /* Note: we don't need to restore the base context info till the end. */
1582 switch (CxTYPE(cx)) {
1585 /* CXt_SUBST is not a block context type, so skip the
1586 * cx_popblock(cx) below */
1587 if (cxstack_ix == cxix + 1) {
1598 case CXt_LOOP_PLAIN:
1599 case CXt_LOOP_LAZYIV:
1600 case CXt_LOOP_LAZYSV:
1613 /* these two don't have a POPFOO() */
1619 if (cxstack_ix == cxix + 1) {
1628 Perl_qerror(pTHX_ SV *err)
1630 PERL_ARGS_ASSERT_QERROR;
1633 if (PL_in_eval & EVAL_KEEPERR) {
1634 Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "\t(in cleanup) %" SVf,
1638 sv_catsv(ERRSV, err);
1641 sv_catsv(PL_errors, err);
1643 Perl_warn(aTHX_ "%" SVf, SVfARG(err));
1645 ++PL_parser->error_count;
1650 /* pop a CXt_EVAL context and in addition, if it was a require then
1652 * 0: do nothing extra;
1653 * 1: undef $INC{$name}; croak "$name did not return a true value";
1654 * 2: delete $INC{$name}; croak "$errsv: Compilation failed in require"
1658 S_pop_eval_context_maybe_croak(pTHX_ PERL_CONTEXT *cx, SV *errsv, int action)
1660 SV *namesv = NULL; /* init to avoid dumb compiler warning */
1664 do_croak = action && (CxOLD_OP_TYPE(cx) == OP_REQUIRE);
1666 /* keep namesv alive after cx_popeval() */
1667 namesv = cx->blk_eval.old_namesv;
1668 cx->blk_eval.old_namesv = NULL;
1677 HV *inc_hv = GvHVn(PL_incgv);
1678 I32 klen = SvUTF8(namesv) ? -(I32)SvCUR(namesv) : (I32)SvCUR(namesv);
1679 const char *key = SvPVX_const(namesv);
1682 (void)hv_delete(inc_hv, key, klen, G_DISCARD);
1683 fmt = "%" SVf " did not return a true value";
1687 (void)hv_store(inc_hv, key, klen, &PL_sv_undef, 0);
1688 fmt = "%" SVf "Compilation failed in require";
1690 errsv = newSVpvs_flags("Unknown error\n", SVs_TEMP);
1693 Perl_croak(aTHX_ fmt, SVfARG(errsv));
1698 /* die_unwind(): this is the final destination for the various croak()
1699 * functions. If we're in an eval, unwind the context and other stacks
1700 * back to the top-most CXt_EVAL and set $@ to msv; otherwise print msv
1701 * to STDERR and initiate an exit. Note that if the CXt_EVAL popped back
1702 * to is a require the exception will be rethrown, as requires don't
1703 * actually trap exceptions.
1707 Perl_die_unwind(pTHX_ SV *msv)
1710 U8 in_eval = PL_in_eval;
1711 PERL_ARGS_ASSERT_DIE_UNWIND;
1716 /* We need to keep this SV alive through all the stack unwinding
1717 * and FREETMPSing below, while ensuing that it doesn't leak
1718 * if we call out to something which then dies (e.g. sub STORE{die}
1719 * when unlocalising a tied var). So we do a dance with
1720 * mortalising and SAVEFREEing.
1722 sv_2mortal(SvREFCNT_inc_simple_NN(exceptsv));
1725 * Historically, perl used to set ERRSV ($@) early in the die
1726 * process and rely on it not getting clobbered during unwinding.
1727 * That sucked, because it was liable to get clobbered, so the
1728 * setting of ERRSV used to emit the exception from eval{} has
1729 * been moved to much later, after unwinding (see just before
1730 * JMPENV_JUMP below). However, some modules were relying on the
1731 * early setting, by examining $@ during unwinding to use it as
1732 * a flag indicating whether the current unwinding was caused by
1733 * an exception. It was never a reliable flag for that purpose,
1734 * being totally open to false positives even without actual
1735 * clobberage, but was useful enough for production code to
1736 * semantically rely on it.
1738 * We'd like to have a proper introspective interface that
1739 * explicitly describes the reason for whatever unwinding
1740 * operations are currently in progress, so that those modules
1741 * work reliably and $@ isn't further overloaded. But we don't
1742 * have one yet. In its absence, as a stopgap measure, ERRSV is
1743 * now *additionally* set here, before unwinding, to serve as the
1744 * (unreliable) flag that it used to.
1746 * This behaviour is temporary, and should be removed when a
1747 * proper way to detect exceptional unwinding has been developed.
1748 * As of 2010-12, the authors of modules relying on the hack
1749 * are aware of the issue, because the modules failed on
1750 * perls 5.13.{1..7} which had late setting of $@ without this
1751 * early-setting hack.
1753 if (!(in_eval & EVAL_KEEPERR)) {
1754 /* remove any read-only/magic from the SV, so we don't
1755 get infinite recursion when setting ERRSV */
1757 sv_setsv_flags(ERRSV, exceptsv,
1758 (SV_GMAGIC|SV_DO_COW_SVSETSV|SV_NOSTEAL));
1761 if (in_eval & EVAL_KEEPERR) {
1762 Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "\t(in cleanup) %" SVf,
1766 while ((cxix = dopoptoeval(cxstack_ix)) < 0
1767 && PL_curstackinfo->si_prev)
1777 JMPENV *restartjmpenv;
1780 if (cxix < cxstack_ix)
1784 assert(CxTYPE(cx) == CXt_EVAL);
1786 /* return false to the caller of eval */
1787 oldsp = PL_stack_base + cx->blk_oldsp;
1788 gimme = cx->blk_gimme;
1789 if (gimme == G_SCALAR)
1790 *++oldsp = &PL_sv_undef;
1791 PL_stack_sp = oldsp;
1793 restartjmpenv = cx->blk_eval.cur_top_env;
1794 restartop = cx->blk_eval.retop;
1796 /* We need a FREETMPS here to avoid late-called destructors
1797 * clobbering $@ *after* we set it below, e.g.
1798 * sub DESTROY { eval { die "X" } }
1799 * eval { my $x = bless []; die $x = 0, "Y" };
1801 * Here the clearing of the $x ref mortalises the anon array,
1802 * which needs to be freed *before* $& is set to "Y",
1803 * otherwise it gets overwritten with "X".
1805 * However, the FREETMPS will clobber exceptsv, so preserve it
1806 * on the savestack for now.
1808 SAVEFREESV(SvREFCNT_inc_simple_NN(exceptsv));
1810 /* now we're about to pop the savestack, so re-mortalise it */
1811 sv_2mortal(SvREFCNT_inc_simple_NN(exceptsv));
1813 /* Note that unlike pp_entereval, pp_require isn't supposed to
1814 * trap errors. So if we're a require, after we pop the
1815 * CXt_EVAL that pp_require pushed, rethrow the error with
1816 * croak(exceptsv). This is all handled by the call below when
1819 S_pop_eval_context_maybe_croak(aTHX_ cx, exceptsv, 2);
1821 if (!(in_eval & EVAL_KEEPERR)) {
1823 sv_setsv(ERRSV, exceptsv);
1825 PL_restartjmpenv = restartjmpenv;
1826 PL_restartop = restartop;
1828 NOT_REACHED; /* NOTREACHED */
1832 write_to_stderr(exceptsv);
1834 NOT_REACHED; /* NOTREACHED */
1840 if (SvTRUE_NN(left) != SvTRUE_NN(right))
1848 =head1 CV Manipulation Functions
1850 =for apidoc caller_cx
1852 The XSUB-writer's equivalent of L<caller()|perlfunc/caller>. The
1853 returned C<PERL_CONTEXT> structure can be interrogated to find all the
1854 information returned to Perl by C<caller>. Note that XSUBs don't get a
1855 stack frame, so C<caller_cx(0, NULL)> will return information for the
1856 immediately-surrounding Perl code.
1858 This function skips over the automatic calls to C<&DB::sub> made on the
1859 behalf of the debugger. If the stack frame requested was a sub called by
1860 C<DB::sub>, the return value will be the frame for the call to
1861 C<DB::sub>, since that has the correct line number/etc. for the call
1862 site. If I<dbcxp> is non-C<NULL>, it will be set to a pointer to the
1863 frame for the sub call itself.
1868 const PERL_CONTEXT *
1869 Perl_caller_cx(pTHX_ I32 count, const PERL_CONTEXT **dbcxp)
1871 I32 cxix = dopopto_cursub();
1872 const PERL_CONTEXT *cx;
1873 const PERL_CONTEXT *ccstack = cxstack;
1874 const PERL_SI *top_si = PL_curstackinfo;
1877 /* we may be in a higher stacklevel, so dig down deeper */
1878 while (cxix < 0 && top_si->si_type != PERLSI_MAIN) {
1879 top_si = top_si->si_prev;
1880 ccstack = top_si->si_cxstack;
1881 cxix = dopoptosub_at(ccstack, top_si->si_cxix);
1885 /* caller() should not report the automatic calls to &DB::sub */
1886 if (PL_DBsub && GvCV(PL_DBsub) && cxix >= 0 &&
1887 ccstack[cxix].blk_sub.cv == GvCV(PL_DBsub))
1891 cxix = dopoptosub_at(ccstack, cxix - 1);
1894 cx = &ccstack[cxix];
1895 if (dbcxp) *dbcxp = cx;
1897 if (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT) {
1898 const I32 dbcxix = dopoptosub_at(ccstack, cxix - 1);
1899 /* We expect that ccstack[dbcxix] is CXt_SUB, anyway, the
1900 field below is defined for any cx. */
1901 /* caller() should not report the automatic calls to &DB::sub */
1902 if (PL_DBsub && GvCV(PL_DBsub) && dbcxix >= 0 && ccstack[dbcxix].blk_sub.cv == GvCV(PL_DBsub))
1903 cx = &ccstack[dbcxix];
1912 const PERL_CONTEXT *cx;
1913 const PERL_CONTEXT *dbcx;
1915 const HEK *stash_hek;
1917 bool has_arg = MAXARG && TOPs;
1926 cx = caller_cx(count + !!(PL_op->op_private & OPpOFFBYONE), &dbcx);
1928 if (gimme != G_ARRAY) {
1935 CX_DEBUG(cx, "CALLER");
1936 assert(CopSTASH(cx->blk_oldcop));
1937 stash_hek = SvTYPE(CopSTASH(cx->blk_oldcop)) == SVt_PVHV
1938 ? HvNAME_HEK((HV*)CopSTASH(cx->blk_oldcop))
1940 if (gimme != G_ARRAY) {
1943 PUSHs(&PL_sv_undef);
1946 sv_sethek(TARG, stash_hek);
1955 PUSHs(&PL_sv_undef);
1958 sv_sethek(TARG, stash_hek);
1961 mPUSHs(newSVpv(OutCopFILE(cx->blk_oldcop), 0));
1962 lcop = closest_cop(cx->blk_oldcop, OpSIBLING(cx->blk_oldcop),
1963 cx->blk_sub.retop, TRUE);
1965 lcop = cx->blk_oldcop;
1966 mPUSHu(CopLINE(lcop));
1969 if (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT) {
1970 /* So is ccstack[dbcxix]. */
1971 if (CvHASGV(dbcx->blk_sub.cv)) {
1972 PUSHs(cv_name(dbcx->blk_sub.cv, 0, 0));
1973 PUSHs(boolSV(CxHASARGS(cx)));
1976 PUSHs(newSVpvs_flags("(unknown)", SVs_TEMP));
1977 PUSHs(boolSV(CxHASARGS(cx)));
1981 PUSHs(newSVpvs_flags("(eval)", SVs_TEMP));
1984 gimme = cx->blk_gimme;
1985 if (gimme == G_VOID)
1986 PUSHs(&PL_sv_undef);
1988 PUSHs(boolSV((gimme & G_WANT) == G_ARRAY));
1989 if (CxTYPE(cx) == CXt_EVAL) {
1991 if (CxOLD_OP_TYPE(cx) == OP_ENTEREVAL) {
1992 SV *cur_text = cx->blk_eval.cur_text;
1993 if (SvCUR(cur_text) >= 2) {
1994 PUSHs(newSVpvn_flags(SvPVX(cur_text), SvCUR(cur_text)-2,
1995 SvUTF8(cur_text)|SVs_TEMP));
1998 /* I think this is will always be "", but be sure */
1999 PUSHs(sv_2mortal(newSVsv(cur_text)));
2005 else if (cx->blk_eval.old_namesv) {
2006 mPUSHs(newSVsv(cx->blk_eval.old_namesv));
2009 /* eval BLOCK (try blocks have old_namesv == 0) */
2011 PUSHs(&PL_sv_undef);
2012 PUSHs(&PL_sv_undef);
2016 PUSHs(&PL_sv_undef);
2017 PUSHs(&PL_sv_undef);
2019 if (CxTYPE(cx) == CXt_SUB && CxHASARGS(cx)
2020 && CopSTASH_eq(PL_curcop, PL_debstash))
2022 /* slot 0 of the pad contains the original @_ */
2023 AV * const ary = MUTABLE_AV(AvARRAY(MUTABLE_AV(
2024 PadlistARRAY(CvPADLIST(cx->blk_sub.cv))[
2025 cx->blk_sub.olddepth+1]))[0]);
2026 const SSize_t off = AvARRAY(ary) - AvALLOC(ary);
2028 Perl_init_dbargs(aTHX);
2030 if (AvMAX(PL_dbargs) < AvFILLp(ary) + off)
2031 av_extend(PL_dbargs, AvFILLp(ary) + off);
2032 if (AvFILLp(ary) + 1 + off)
2033 Copy(AvALLOC(ary), AvARRAY(PL_dbargs), AvFILLp(ary) + 1 + off, SV*);
2034 AvFILLp(PL_dbargs) = AvFILLp(ary) + off;
2036 mPUSHi(CopHINTS_get(cx->blk_oldcop));
2039 STRLEN * const old_warnings = cx->blk_oldcop->cop_warnings ;
2041 if (old_warnings == pWARN_NONE)
2042 mask = newSVpvn(WARN_NONEstring, WARNsize) ;
2043 else if (old_warnings == pWARN_STD && (PL_dowarn & G_WARN_ON) == 0)
2044 mask = &PL_sv_undef ;
2045 else if (old_warnings == pWARN_ALL ||
2046 (old_warnings == pWARN_STD && PL_dowarn & G_WARN_ON)) {
2047 mask = newSVpvn(WARN_ALLstring, WARNsize) ;
2050 mask = newSVpvn((char *) (old_warnings + 1), old_warnings[0]);
2054 PUSHs(cx->blk_oldcop->cop_hints_hash ?
2055 sv_2mortal(newRV_noinc(MUTABLE_SV(cop_hints_2hv(cx->blk_oldcop, 0))))
2065 if (MAXARG < 1 || (!TOPs && !POPs)) {
2067 tmps = NULL, len = 0;
2070 tmps = SvPVx_const(POPs, len);
2071 sv_resetpvn(tmps, len, CopSTASH(PL_curcop));
2076 /* like pp_nextstate, but used instead when the debugger is active */
2080 PL_curcop = (COP*)PL_op;
2081 TAINT_NOT; /* Each statement is presumed innocent */
2082 PL_stack_sp = PL_stack_base + CX_CUR()->blk_oldsp;
2087 if (PL_op->op_flags & OPf_SPECIAL /* breakpoint */
2088 || PL_DBsingle_iv || PL_DBsignal_iv || PL_DBtrace_iv)
2092 const U8 gimme = G_ARRAY;
2093 GV * const gv = PL_DBgv;
2096 if (gv && isGV_with_GP(gv))
2099 if (!cv || (!CvROOT(cv) && !CvXSUB(cv)))
2100 DIE(aTHX_ "No DB::DB routine defined");
2102 if (CvDEPTH(cv) >= 1 && !(PL_debug & DEBUG_DB_RECURSE_FLAG))
2103 /* don't do recursive DB::DB call */
2113 (void)(*CvXSUB(cv))(aTHX_ cv);
2119 cx = cx_pushblock(CXt_SUB, gimme, SP, PL_savestack_ix);
2120 cx_pushsub(cx, cv, PL_op->op_next, 0);
2121 /* OP_DBSTATE's op_private holds hint bits rather than
2122 * the lvalue-ish flags seen in OP_ENTERSUB. So cancel
2123 * any CxLVAL() flags that have now been mis-calculated */
2130 if (CvDEPTH(cv) >= 2)
2131 pad_push(CvPADLIST(cv), CvDEPTH(cv));
2132 PAD_SET_CUR_NOSAVE(CvPADLIST(cv), CvDEPTH(cv));
2133 RETURNOP(CvSTART(cv));
2145 (void)cx_pushblock(CXt_BLOCK, gimme, PL_stack_sp, PL_savestack_ix);
2157 assert(CxTYPE(cx) == CXt_BLOCK);
2159 if (PL_op->op_flags & OPf_SPECIAL)
2160 /* fake block should preserve $1 et al; e.g. /(...)/ while ...; */
2161 cx->blk_oldpm = PL_curpm;
2163 oldsp = PL_stack_base + cx->blk_oldsp;
2164 gimme = cx->blk_gimme;
2166 if (gimme == G_VOID)
2167 PL_stack_sp = oldsp;
2169 leave_adjust_stacks(oldsp, oldsp, gimme,
2170 PL_op->op_private & OPpLVALUE ? 3 : 1);
2180 S_outside_integer(pTHX_ SV *sv)
2183 const NV nv = SvNV_nomg(sv);
2184 if (Perl_isinfnan(nv))
2186 #ifdef NV_PRESERVES_UV
2187 if (nv < (NV)IV_MIN || nv > (NV)IV_MAX)
2190 if (nv <= (NV)IV_MIN)
2193 ((nv > (NV)UV_MAX ||
2194 SvUV_nomg(sv) > (UV)IV_MAX)))
2205 const U8 gimme = GIMME_V;
2206 void *itervarp; /* GV or pad slot of the iteration variable */
2207 SV *itersave; /* the old var in the iterator var slot */
2210 if (PL_op->op_targ) { /* "my" variable */
2211 itervarp = &PAD_SVl(PL_op->op_targ);
2212 itersave = *(SV**)itervarp;
2214 if (PL_op->op_private & OPpLVAL_INTRO) { /* for my $x (...) */
2215 /* the SV currently in the pad slot is never live during
2216 * iteration (the slot is always aliased to one of the items)
2217 * so it's always stale */
2218 SvPADSTALE_on(itersave);
2220 SvREFCNT_inc_simple_void_NN(itersave);
2221 cxflags = CXp_FOR_PAD;
2224 SV * const sv = POPs;
2225 itervarp = (void *)sv;
2226 if (LIKELY(isGV(sv))) { /* symbol table variable */
2227 itersave = GvSV(sv);
2228 SvREFCNT_inc_simple_void(itersave);
2229 cxflags = CXp_FOR_GV;
2230 if (PL_op->op_private & OPpITER_DEF)
2231 cxflags |= CXp_FOR_DEF;
2233 else { /* LV ref: for \$foo (...) */
2234 assert(SvTYPE(sv) == SVt_PVMG);
2235 assert(SvMAGIC(sv));
2236 assert(SvMAGIC(sv)->mg_type == PERL_MAGIC_lvref);
2238 cxflags = CXp_FOR_LVREF;
2241 /* OPpITER_DEF (implicit $_) should only occur with a GV iter var */
2242 assert((cxflags & CXp_FOR_GV) || !(PL_op->op_private & OPpITER_DEF));
2244 /* Note that this context is initially set as CXt_NULL. Further on
2245 * down it's changed to one of the CXt_LOOP_*. Before it's changed,
2246 * there mustn't be anything in the blk_loop substruct that requires
2247 * freeing or undoing, in case we die in the meantime. And vice-versa.
2249 cx = cx_pushblock(cxflags, gimme, MARK, PL_savestack_ix);
2250 cx_pushloop_for(cx, itervarp, itersave);
2252 if (PL_op->op_flags & OPf_STACKED) {
2253 /* OPf_STACKED implies either a single array: for(@), with a
2254 * single AV on the stack, or a range: for (1..5), with 1 and 5 on
2256 SV *maybe_ary = POPs;
2257 if (SvTYPE(maybe_ary) != SVt_PVAV) {
2260 SV * const right = maybe_ary;
2261 if (UNLIKELY(cxflags & CXp_FOR_LVREF))
2262 DIE(aTHX_ "Assigned value is not a reference");
2265 if (RANGE_IS_NUMERIC(sv,right)) {
2266 cx->cx_type |= CXt_LOOP_LAZYIV;
2267 if (S_outside_integer(aTHX_ sv) ||
2268 S_outside_integer(aTHX_ right))
2269 DIE(aTHX_ "Range iterator outside integer range");
2270 cx->blk_loop.state_u.lazyiv.cur = SvIV_nomg(sv);
2271 cx->blk_loop.state_u.lazyiv.end = SvIV_nomg(right);
2274 cx->cx_type |= CXt_LOOP_LAZYSV;
2275 cx->blk_loop.state_u.lazysv.cur = newSVsv(sv);
2276 cx->blk_loop.state_u.lazysv.end = right;
2277 SvREFCNT_inc_simple_void_NN(right);
2278 (void) SvPV_force_nolen(cx->blk_loop.state_u.lazysv.cur);
2279 /* This will do the upgrade to SVt_PV, and warn if the value
2280 is uninitialised. */
2281 (void) SvPV_nolen_const(right);
2282 /* Doing this avoids a check every time in pp_iter in pp_hot.c
2283 to replace !SvOK() with a pointer to "". */
2285 SvREFCNT_dec(right);
2286 cx->blk_loop.state_u.lazysv.end = &PL_sv_no;
2290 else /* SvTYPE(maybe_ary) == SVt_PVAV */ {
2291 /* for (@array) {} */
2292 cx->cx_type |= CXt_LOOP_ARY;
2293 cx->blk_loop.state_u.ary.ary = MUTABLE_AV(maybe_ary);
2294 SvREFCNT_inc_simple_void_NN(maybe_ary);
2295 cx->blk_loop.state_u.ary.ix =
2296 (PL_op->op_private & OPpITER_REVERSED) ?
2297 AvFILL(cx->blk_loop.state_u.ary.ary) + 1 :
2300 /* EXTEND(SP, 1) not needed in this branch because we just did POPs */
2302 else { /* iterating over items on the stack */
2303 cx->cx_type |= CXt_LOOP_LIST;
2304 cx->blk_oldsp = SP - PL_stack_base;
2305 cx->blk_loop.state_u.stack.basesp = MARK - PL_stack_base;
2306 cx->blk_loop.state_u.stack.ix =
2307 (PL_op->op_private & OPpITER_REVERSED)
2309 : cx->blk_loop.state_u.stack.basesp;
2310 /* pre-extend stack so pp_iter doesn't have to check every time
2311 * it pushes yes/no */
2321 const U8 gimme = GIMME_V;
2323 cx = cx_pushblock(CXt_LOOP_PLAIN, gimme, PL_stack_sp, PL_savestack_ix);
2324 cx_pushloop_plain(cx);
2337 assert(CxTYPE_is_LOOP(cx));
2338 oldsp = PL_stack_base + cx->blk_oldsp;
2339 base = CxTYPE(cx) == CXt_LOOP_LIST
2340 ? PL_stack_base + cx->blk_loop.state_u.stack.basesp
2342 gimme = cx->blk_gimme;
2344 if (gimme == G_VOID)
2347 leave_adjust_stacks(oldsp, base, gimme,
2348 PL_op->op_private & OPpLVALUE ? 3 : 1);
2351 cx_poploop(cx); /* Stack values are safe: release loop vars ... */
2359 /* This duplicates most of pp_leavesub, but with additional code to handle
2360 * return args in lvalue context. It was forked from pp_leavesub to
2361 * avoid slowing down that function any further.
2363 * Any changes made to this function may need to be copied to pp_leavesub
2366 * also tail-called by pp_return
2377 assert(CxTYPE(cx) == CXt_SUB);
2379 if (CxMULTICALL(cx)) {
2380 /* entry zero of a stack is always PL_sv_undef, which
2381 * simplifies converting a '()' return into undef in scalar context */
2382 assert(PL_stack_sp > PL_stack_base || *PL_stack_base == &PL_sv_undef);
2386 gimme = cx->blk_gimme;
2387 oldsp = PL_stack_base + cx->blk_oldsp; /* last arg of previous frame */
2389 if (gimme == G_VOID)
2390 PL_stack_sp = oldsp;
2392 U8 lval = CxLVAL(cx);
2393 bool is_lval = (lval && !(lval & OPpENTERSUB_INARGS));
2394 const char *what = NULL;
2396 if (gimme == G_SCALAR) {
2398 /* check for bad return arg */
2399 if (oldsp < PL_stack_sp) {
2400 SV *sv = *PL_stack_sp;
2401 if ((SvPADTMP(sv) || SvREADONLY(sv))) {
2403 SvREADONLY(sv) ? (sv == &PL_sv_undef) ? "undef"
2404 : "a readonly value" : "a temporary";
2409 /* sub:lvalue{} will take us here. */
2414 "Can't return %s from lvalue subroutine", what);
2418 leave_adjust_stacks(oldsp, oldsp, gimme, is_lval ? 3 : 2);
2420 if (lval & OPpDEREF) {
2421 /* lval_sub()->{...} and similar */
2425 TOPs = vivify_ref(TOPs, CxLVAL(cx) & OPpDEREF);
2431 assert(gimme == G_ARRAY);
2432 assert (!(lval & OPpDEREF));
2435 /* scan for bad return args */
2437 for (p = PL_stack_sp; p > oldsp; p--) {
2439 /* the PL_sv_undef exception is to allow things like
2440 * this to work, where PL_sv_undef acts as 'skip'
2441 * placeholder on the LHS of list assigns:
2442 * sub foo :lvalue { undef }
2443 * ($a, undef, foo(), $b) = 1..4;
2445 if (sv != &PL_sv_undef && (SvPADTMP(sv) || SvREADONLY(sv)))
2447 /* Might be flattened array after $#array = */
2448 what = SvREADONLY(sv)
2449 ? "a readonly value" : "a temporary";
2455 leave_adjust_stacks(oldsp, oldsp, gimme, is_lval ? 3 : 2);
2460 cx_popsub(cx); /* Stack values are safe: release CV and @_ ... */
2462 retop = cx->blk_sub.retop;
2473 const I32 cxix = dopopto_cursub();
2475 assert(cxstack_ix >= 0);
2476 if (cxix < cxstack_ix) {
2478 if (!( PL_curstackinfo->si_type == PERLSI_SORT
2479 || ( PL_curstackinfo->si_type == PERLSI_MULTICALL
2480 && (cxstack[0].cx_type & CXp_SUB_RE_FAKE))
2483 DIE(aTHX_ "Can't return outside a subroutine");
2485 * a sort block, which is a CXt_NULL not a CXt_SUB;
2486 * or a /(?{...})/ block.
2487 * Handle specially. */
2488 assert(CxTYPE(&cxstack[0]) == CXt_NULL
2489 || ( CxTYPE(&cxstack[0]) == CXt_SUB
2490 && (cxstack[0].cx_type & CXp_SUB_RE_FAKE)));
2491 if (cxstack_ix > 0) {
2492 /* See comment below about context popping. Since we know
2493 * we're scalar and not lvalue, we can preserve the return
2494 * value in a simpler fashion than there. */
2496 assert(cxstack[0].blk_gimme == G_SCALAR);
2497 if ( (sp != PL_stack_base)
2498 && !(SvFLAGS(sv) & (SVs_TEMP|SVs_PADTMP))
2500 *SP = sv_mortalcopy(sv);
2503 /* caller responsible for popping cxstack[0] */
2507 /* There are contexts that need popping. Doing this may free the
2508 * return value(s), so preserve them first: e.g. popping the plain
2509 * loop here would free $x:
2510 * sub f { { my $x = 1; return $x } }
2511 * We may also need to shift the args down; for example,
2512 * for (1,2) { return 3,4 }
2513 * leaves 1,2,3,4 on the stack. Both these actions will be done by
2514 * leave_adjust_stacks(), along with freeing any temps. Note that
2515 * whoever we tail-call (e.g. pp_leaveeval) will also call
2516 * leave_adjust_stacks(); however, the second call is likely to
2517 * just see a bunch of SvTEMPs with a ref count of 1, and so just
2518 * pass them through, rather than copying them again. So this
2519 * isn't as inefficient as it sounds.
2521 cx = &cxstack[cxix];
2523 if (cx->blk_gimme != G_VOID)
2524 leave_adjust_stacks(MARK, PL_stack_base + cx->blk_oldsp,
2526 CxTYPE(cx) == CXt_SUB && CvLVALUE(cx->blk_sub.cv)
2530 cx = &cxstack[cxix]; /* CX stack may have been realloced */
2533 /* Like in the branch above, we need to handle any extra junk on
2534 * the stack. But because we're not also popping extra contexts, we
2535 * don't have to worry about prematurely freeing args. So we just
2536 * need to do the bare minimum to handle junk, and leave the main
2537 * arg processing in the function we tail call, e.g. pp_leavesub.
2538 * In list context we have to splice out the junk; in scalar
2539 * context we can leave as-is (pp_leavesub will later return the
2540 * top stack element). But for an empty arg list, e.g.
2541 * for (1,2) { return }
2542 * we need to set sp = oldsp so that pp_leavesub knows to push
2543 * &PL_sv_undef onto the stack.
2546 cx = &cxstack[cxix];
2547 oldsp = PL_stack_base + cx->blk_oldsp;
2548 if (oldsp != MARK) {
2549 SSize_t nargs = SP - MARK;
2551 if (cx->blk_gimme == G_ARRAY) {
2552 /* shift return args to base of call stack frame */
2553 Move(MARK + 1, oldsp + 1, nargs, SV*);
2554 PL_stack_sp = oldsp + nargs;
2558 PL_stack_sp = oldsp;
2562 /* fall through to a normal exit */
2563 switch (CxTYPE(cx)) {
2565 return CxTRYBLOCK(cx)
2566 ? Perl_pp_leavetry(aTHX)
2567 : Perl_pp_leaveeval(aTHX);
2569 return CvLVALUE(cx->blk_sub.cv)
2570 ? Perl_pp_leavesublv(aTHX)
2571 : Perl_pp_leavesub(aTHX);
2573 return Perl_pp_leavewrite(aTHX);
2575 DIE(aTHX_ "panic: return, type=%u", (unsigned) CxTYPE(cx));
2579 /* find the enclosing loop or labelled loop and dounwind() back to it. */
2581 static PERL_CONTEXT *
2585 if (PL_op->op_flags & OPf_SPECIAL) {
2586 cxix = dopoptoloop(cxstack_ix);
2588 /* diag_listed_as: Can't "last" outside a loop block */
2589 Perl_croak(aTHX_ "Can't \"%s\" outside a loop block",
2595 const char * const label =
2596 PL_op->op_flags & OPf_STACKED
2597 ? SvPV(TOPs,label_len)
2598 : (label_len = strlen(cPVOP->op_pv), cPVOP->op_pv);
2599 const U32 label_flags =
2600 PL_op->op_flags & OPf_STACKED
2602 : (cPVOP->op_private & OPpPV_IS_UTF8) ? SVf_UTF8 : 0;
2604 cxix = dopoptolabel(label, label_len, label_flags);
2606 /* diag_listed_as: Label not found for "last %s" */
2607 Perl_croak(aTHX_ "Label not found for \"%s %" SVf "\"",
2609 SVfARG(PL_op->op_flags & OPf_STACKED
2610 && !SvGMAGICAL(TOPp1s)
2612 : newSVpvn_flags(label,
2614 label_flags | SVs_TEMP)));
2616 if (cxix < cxstack_ix)
2618 return &cxstack[cxix];
2627 cx = S_unwind_loop(aTHX);
2629 assert(CxTYPE_is_LOOP(cx));
2630 PL_stack_sp = PL_stack_base
2631 + (CxTYPE(cx) == CXt_LOOP_LIST
2632 ? cx->blk_loop.state_u.stack.basesp
2638 /* Stack values are safe: */
2640 cx_poploop(cx); /* release loop vars ... */
2642 nextop = cx->blk_loop.my_op->op_lastop->op_next;
2652 /* if not a bare 'next' in the main scope, search for it */
2654 if (!((PL_op->op_flags & OPf_SPECIAL) && CxTYPE_is_LOOP(cx)))
2655 cx = S_unwind_loop(aTHX);
2658 PL_curcop = cx->blk_oldcop;
2660 return (cx)->blk_loop.my_op->op_nextop;
2665 PERL_CONTEXT *cx = S_unwind_loop(aTHX);
2666 OP* redo_op = cx->blk_loop.my_op->op_redoop;
2668 if (redo_op->op_type == OP_ENTER) {
2669 /* pop one less context to avoid $x being freed in while (my $x..) */
2672 assert(CxTYPE(cx) == CXt_BLOCK);
2673 redo_op = redo_op->op_next;
2679 PL_curcop = cx->blk_oldcop;
2684 #define UNENTERABLE (OP *)1
2685 #define GOTO_DEPTH 64
2688 S_dofindlabel(pTHX_ OP *o, const char *label, STRLEN len, U32 flags, OP **opstack, OP **oplimit)
2691 static const char* const too_deep = "Target of goto is too deeply nested";
2693 PERL_ARGS_ASSERT_DOFINDLABEL;
2696 Perl_croak(aTHX_ "%s", too_deep);
2697 if (o->op_type == OP_LEAVE ||
2698 o->op_type == OP_SCOPE ||
2699 o->op_type == OP_LEAVELOOP ||
2700 o->op_type == OP_LEAVESUB ||
2701 o->op_type == OP_LEAVETRY ||
2702 o->op_type == OP_LEAVEGIVEN)
2704 *ops++ = cUNOPo->op_first;
2706 else if (oplimit - opstack < GOTO_DEPTH) {
2707 if (o->op_flags & OPf_KIDS
2708 && cUNOPo->op_first->op_type == OP_PUSHMARK) {
2709 *ops++ = UNENTERABLE;
2711 else if (o->op_flags & OPf_KIDS && PL_opargs[o->op_type]
2712 && OP_CLASS(o) != OA_LOGOP
2713 && o->op_type != OP_LINESEQ
2714 && o->op_type != OP_SREFGEN
2715 && o->op_type != OP_ENTEREVAL
2716 && o->op_type != OP_GLOB
2717 && o->op_type != OP_RV2CV) {
2718 OP * const kid = cUNOPo->op_first;
2719 if (OP_GIMME(kid, 0) != G_SCALAR || OpHAS_SIBLING(kid))
2720 *ops++ = UNENTERABLE;
2724 Perl_croak(aTHX_ "%s", too_deep);
2726 if (o->op_flags & OPf_KIDS) {
2728 OP * const kid1 = cUNOPo->op_first;
2729 /* First try all the kids at this level, since that's likeliest. */
2730 for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
2731 if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
2732 STRLEN kid_label_len;
2733 U32 kid_label_flags;
2734 const char *kid_label = CopLABEL_len_flags(kCOP,
2735 &kid_label_len, &kid_label_flags);
2737 ( (kid_label_flags & SVf_UTF8) != (flags & SVf_UTF8) ) ?
2740 (const U8*)kid_label, kid_label_len,
2741 (const U8*)label, len) == 0)
2743 (const U8*)label, len,
2744 (const U8*)kid_label, kid_label_len) == 0)
2745 : ( len == kid_label_len && ((kid_label == label)
2746 || memEQ(kid_label, label, len)))))
2750 for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
2751 bool first_kid_of_binary = FALSE;
2752 if (kid == PL_lastgotoprobe)
2754 if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
2757 else if (ops[-1] != UNENTERABLE
2758 && (ops[-1]->op_type == OP_NEXTSTATE ||
2759 ops[-1]->op_type == OP_DBSTATE))
2764 if (kid == kid1 && ops != opstack && ops[-1] == UNENTERABLE) {
2765 first_kid_of_binary = TRUE;
2768 if ((o = dofindlabel(kid, label, len, flags, ops, oplimit)))
2770 if (first_kid_of_binary)
2771 *ops++ = UNENTERABLE;
2780 S_check_op_type(pTHX_ OP * const o)
2782 /* Eventually we may want to stack the needed arguments
2783 * for each op. For now, we punt on the hard ones. */
2784 /* XXX This comment seems to me like wishful thinking. --sprout */
2785 if (o == UNENTERABLE)
2787 "Can't \"goto\" into a binary or list expression");
2788 if (o->op_type == OP_ENTERITER)
2790 "Can't \"goto\" into the middle of a foreach loop");
2791 if (o->op_type == OP_ENTERGIVEN)
2793 "Can't \"goto\" into a \"given\" block");
2796 /* also used for: pp_dump() */
2804 OP *enterops[GOTO_DEPTH];
2805 const char *label = NULL;
2806 STRLEN label_len = 0;
2807 U32 label_flags = 0;
2808 const bool do_dump = (PL_op->op_type == OP_DUMP);
2809 static const char* const must_have_label = "goto must have label";
2811 if (PL_op->op_flags & OPf_STACKED) {
2812 /* goto EXPR or goto &foo */
2814 SV * const sv = POPs;
2817 if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
2818 /* This egregious kludge implements goto &subroutine */
2821 CV *cv = MUTABLE_CV(SvRV(sv));
2822 AV *arg = GvAV(PL_defgv);
2824 while (!CvROOT(cv) && !CvXSUB(cv)) {
2825 const GV * const gv = CvGV(cv);
2829 /* autoloaded stub? */
2830 if (cv != GvCV(gv) && (cv = GvCV(gv)))
2832 autogv = gv_autoload_pvn(GvSTASH(gv), GvNAME(gv),
2834 GvNAMEUTF8(gv) ? SVf_UTF8 : 0);
2835 if (autogv && (cv = GvCV(autogv)))
2837 tmpstr = sv_newmortal();
2838 gv_efullname3(tmpstr, gv, NULL);
2839 DIE(aTHX_ "Goto undefined subroutine &%" SVf, SVfARG(tmpstr));
2841 DIE(aTHX_ "Goto undefined subroutine");
2844 cxix = dopopto_cursub();
2846 DIE(aTHX_ "Can't goto subroutine outside a subroutine");
2848 cx = &cxstack[cxix];
2849 /* ban goto in eval: see <20050521150056.GC20213@iabyn.com> */
2850 if (CxTYPE(cx) == CXt_EVAL) {
2852 /* diag_listed_as: Can't goto subroutine from an eval-%s */
2853 DIE(aTHX_ "Can't goto subroutine from an eval-string");
2855 /* diag_listed_as: Can't goto subroutine from an eval-%s */
2856 DIE(aTHX_ "Can't goto subroutine from an eval-block");
2858 else if (CxMULTICALL(cx))
2859 DIE(aTHX_ "Can't goto subroutine from a sort sub (or similar callback)");
2861 /* First do some returnish stuff. */
2863 SvREFCNT_inc_simple_void(cv); /* avoid premature free during unwind */
2865 if (cxix < cxstack_ix) {
2872 /* protect @_ during save stack unwind. */
2874 SvREFCNT_inc_NN(sv_2mortal(MUTABLE_SV(arg)));
2876 assert(PL_scopestack_ix == cx->blk_oldscopesp);
2879 if (CxTYPE(cx) == CXt_SUB && CxHASARGS(cx)) {
2880 /* this is part of cx_popsub_args() */
2881 AV* av = MUTABLE_AV(PAD_SVl(0));
2882 assert(AvARRAY(MUTABLE_AV(
2883 PadlistARRAY(CvPADLIST(cx->blk_sub.cv))[
2884 CvDEPTH(cx->blk_sub.cv)])) == PL_curpad);
2886 /* we are going to donate the current @_ from the old sub
2887 * to the new sub. This first part of the donation puts a
2888 * new empty AV in the pad[0] slot of the old sub,
2889 * unless pad[0] and @_ differ (e.g. if the old sub did
2890 * local *_ = []); in which case clear the old pad[0]
2891 * array in the usual way */
2892 if (av == arg || AvREAL(av))
2893 clear_defarray(av, av == arg);
2894 else CLEAR_ARGARRAY(av);
2897 /* don't restore PL_comppad here. It won't be needed if the
2898 * sub we're going to is non-XS, but restoring it early then
2899 * croaking (e.g. the "Goto undefined subroutine" below)
2900 * means the CX block gets processed again in dounwind,
2901 * but this time with the wrong PL_comppad */
2903 /* A destructor called during LEAVE_SCOPE could have undefined
2904 * our precious cv. See bug #99850. */
2905 if (!CvROOT(cv) && !CvXSUB(cv)) {
2906 const GV * const gv = CvGV(cv);
2908 SV * const tmpstr = sv_newmortal();
2909 gv_efullname3(tmpstr, gv, NULL);
2910 DIE(aTHX_ "Goto undefined subroutine &%" SVf,
2913 DIE(aTHX_ "Goto undefined subroutine");
2916 if (CxTYPE(cx) == CXt_SUB) {
2917 CvDEPTH(cx->blk_sub.cv) = cx->blk_sub.olddepth;
2918 SvREFCNT_dec_NN(cx->blk_sub.cv);
2921 /* Now do some callish stuff. */
2923 const SSize_t items = arg ? AvFILL(arg) + 1 : 0;
2924 const bool m = arg ? cBOOL(SvRMAGICAL(arg)) : 0;
2929 SAVEFREESV(cv); /* later, undo the 'avoid premature free' hack */
2931 /* put GvAV(defgv) back onto stack */
2933 EXTEND(SP, items+1); /* @_ could have been extended. */
2938 bool r = cBOOL(AvREAL(arg));
2939 for (index=0; index<items; index++)
2943 SV ** const svp = av_fetch(arg, index, 0);
2944 sv = svp ? *svp : NULL;
2946 else sv = AvARRAY(arg)[index];
2948 ? r ? SvREFCNT_inc_NN(sv_2mortal(sv)) : sv
2949 : sv_2mortal(newSVavdefelem(arg, index, 1));
2953 if (CxTYPE(cx) == CXt_SUB && CxHASARGS(cx)) {
2954 /* Restore old @_ */
2955 CX_POP_SAVEARRAY(cx);
2958 retop = cx->blk_sub.retop;
2959 PL_comppad = cx->blk_sub.prevcomppad;
2960 PL_curpad = LIKELY(PL_comppad) ? AvARRAY(PL_comppad) : NULL;
2962 /* XS subs don't have a CXt_SUB, so pop it;
2963 * this is a cx_popblock(), less all the stuff we already did
2964 * for cx_topblock() earlier */
2965 PL_curcop = cx->blk_oldcop;
2966 /* this is cx_popsub, less all the stuff we already did */
2967 PL_curstackinfo->si_cxsubix = cx->blk_sub.old_cxsubix;
2971 /* Push a mark for the start of arglist */
2974 (void)(*CvXSUB(cv))(aTHX_ cv);
2979 PADLIST * const padlist = CvPADLIST(cv);
2981 SAVEFREESV(cv); /* later, undo the 'avoid premature free' hack */
2983 /* partial unrolled cx_pushsub(): */
2985 cx->blk_sub.cv = cv;
2986 cx->blk_sub.olddepth = CvDEPTH(cv);
2989 SvREFCNT_inc_simple_void_NN(cv);
2990 if (CvDEPTH(cv) > 1) {
2991 if (CvDEPTH(cv) == PERL_SUB_DEPTH_WARN && ckWARN(WARN_RECURSION))
2992 sub_crush_depth(cv);
2993 pad_push(padlist, CvDEPTH(cv));
2995 PL_curcop = cx->blk_oldcop;
2996 PAD_SET_CUR_NOSAVE(padlist, CvDEPTH(cv));
2999 /* second half of donating @_ from the old sub to the
3000 * new sub: abandon the original pad[0] AV in the
3001 * new sub, and replace it with the donated @_.
3002 * pad[0] takes ownership of the extra refcount
3003 * we gave arg earlier */
3005 SvREFCNT_dec(PAD_SVl(0));
3006 PAD_SVl(0) = (SV *)arg;
3007 SvREFCNT_inc_simple_void_NN(arg);
3010 /* GvAV(PL_defgv) might have been modified on scope
3011 exit, so point it at arg again. */
3012 if (arg != GvAV(PL_defgv)) {
3013 AV * const av = GvAV(PL_defgv);
3014 GvAV(PL_defgv) = (AV *)SvREFCNT_inc_simple(arg);
3019 if (PERLDB_SUB) { /* Checking curstash breaks DProf. */
3020 Perl_get_db_sub(aTHX_ NULL, cv);
3022 CV * const gotocv = get_cvs("DB::goto", 0);
3024 PUSHMARK( PL_stack_sp );
3025 call_sv(MUTABLE_SV(gotocv), G_SCALAR | G_NODEBUG);
3030 retop = CvSTART(cv);
3031 goto putback_return;
3036 label = SvPV_nomg_const(sv, label_len);
3037 label_flags = SvUTF8(sv);
3040 else if (!(PL_op->op_flags & OPf_SPECIAL)) {
3041 /* goto LABEL or dump LABEL */
3042 label = cPVOP->op_pv;
3043 label_flags = (cPVOP->op_private & OPpPV_IS_UTF8) ? SVf_UTF8 : 0;
3044 label_len = strlen(label);
3046 if (!(do_dump || label_len)) DIE(aTHX_ "%s", must_have_label);
3051 OP *gotoprobe = NULL;
3052 bool leaving_eval = FALSE;
3053 bool in_block = FALSE;
3054 bool pseudo_block = FALSE;
3055 PERL_CONTEXT *last_eval_cx = NULL;
3059 PL_lastgotoprobe = NULL;
3061 for (ix = cxstack_ix; ix >= 0; ix--) {
3063 switch (CxTYPE(cx)) {
3065 leaving_eval = TRUE;
3066 if (!CxTRYBLOCK(cx)) {
3067 gotoprobe = (last_eval_cx ?
3068 last_eval_cx->blk_eval.old_eval_root :
3073 /* else fall through */
3074 case CXt_LOOP_PLAIN:
3075 case CXt_LOOP_LAZYIV:
3076 case CXt_LOOP_LAZYSV:
3081 gotoprobe = OpSIBLING(cx->blk_oldcop);
3087 gotoprobe = OpSIBLING(cx->blk_oldcop);
3090 gotoprobe = PL_main_root;
3093 gotoprobe = CvROOT(cx->blk_sub.cv);
3094 pseudo_block = cBOOL(CxMULTICALL(cx));
3098 DIE(aTHX_ "Can't \"goto\" out of a pseudo block");
3101 DIE(aTHX_ "panic: goto, type=%u, ix=%ld",
3102 CxTYPE(cx), (long) ix);
3103 gotoprobe = PL_main_root;
3109 retop = dofindlabel(gotoprobe, label, label_len, label_flags,
3110 enterops, enterops + GOTO_DEPTH);
3113 if ( (sibl1 = OpSIBLING(gotoprobe)) &&
3114 sibl1->op_type == OP_UNSTACK &&
3115 (sibl2 = OpSIBLING(sibl1)))
3117 retop = dofindlabel(sibl2,
3118 label, label_len, label_flags, enterops,
3119 enterops + GOTO_DEPTH);
3125 DIE(aTHX_ "Can't \"goto\" out of a pseudo block");
3126 PL_lastgotoprobe = gotoprobe;
3129 DIE(aTHX_ "Can't find label %" UTF8f,
3130 UTF8fARG(label_flags, label_len, label));
3132 /* if we're leaving an eval, check before we pop any frames
3133 that we're not going to punt, otherwise the error
3136 if (leaving_eval && *enterops && enterops[1]) {
3138 for (i = 1; enterops[i]; i++)
3139 S_check_op_type(aTHX_ enterops[i]);
3142 if (*enterops && enterops[1]) {
3143 I32 i = enterops[1] != UNENTERABLE
3144 && enterops[1]->op_type == OP_ENTER && in_block
3148 deprecate("\"goto\" to jump into a construct");
3151 /* pop unwanted frames */
3153 if (ix < cxstack_ix) {
3155 DIE(aTHX_ "panic: docatch: illegal ix=%ld", (long)ix);
3161 /* push wanted frames */
3163 if (*enterops && enterops[1]) {
3164 OP * const oldop = PL_op;
3165 ix = enterops[1] != UNENTERABLE
3166 && enterops[1]->op_type == OP_ENTER && in_block
3169 for (; enterops[ix]; ix++) {
3170 PL_op = enterops[ix];
3171 S_check_op_type(aTHX_ PL_op);
3172 DEBUG_l( Perl_deb(aTHX_ "pp_goto: Entering %s\n",
3174 PL_op->op_ppaddr(aTHX);
3182 if (!retop) retop = PL_main_start;
3184 PL_restartop = retop;
3185 PL_do_undump = TRUE;
3189 PL_restartop = 0; /* hmm, must be GNU unexec().. */
3190 PL_do_undump = FALSE;
3208 anum = 0; (void)POPs;
3214 && SvTRUE(cop_hints_fetch_pvs(PL_curcop, "vmsish_exit", 0)))
3217 VMSISH_HUSHED || (PL_curcop->op_private & OPpHUSH_VMSISH);
3220 PL_exit_flags |= PERL_EXIT_EXPECTED;
3222 PUSHs(&PL_sv_undef);
3229 S_save_lines(pTHX_ AV *array, SV *sv)
3231 const char *s = SvPVX_const(sv);
3232 const char * const send = SvPVX_const(sv) + SvCUR(sv);
3235 PERL_ARGS_ASSERT_SAVE_LINES;
3237 while (s && s < send) {
3239 SV * const tmpstr = newSV_type(SVt_PVMG);
3241 t = (const char *)memchr(s, '\n', send - s);
3247 sv_setpvn(tmpstr, s, t - s);
3248 av_store(array, line++, tmpstr);
3256 Check for the cases 0 or 3 of cur_env.je_ret, only used inside an eval context.
3258 0 is used as continue inside eval,
3260 3 is used for a die caught by an inner eval - continue inner loop
3262 See F<cop.h>: je_mustcatch, when set at any runlevel to TRUE, means eval ops must
3263 establish a local jmpenv to handle exception traps.
3268 S_docatch(pTHX_ Perl_ppaddr_t firstpp)
3271 OP * const oldop = PL_op;
3274 assert(CATCH_GET == TRUE);
3279 PL_op = firstpp(aTHX);
3284 /* die caught by an inner eval - continue inner loop */
3285 if (PL_restartop && PL_restartjmpenv == PL_top_env) {
3286 PL_restartjmpenv = NULL;
3287 PL_op = PL_restartop;
3296 NOT_REACHED; /* NOTREACHED */
3305 =for apidoc find_runcv
3307 Locate the CV corresponding to the currently executing sub or eval.
3308 If C<db_seqp> is non_null, skip CVs that are in the DB package and populate
3309 C<*db_seqp> with the cop sequence number at the point that the DB:: code was
3310 entered. (This allows debuggers to eval in the scope of the breakpoint
3311 rather than in the scope of the debugger itself.)
3317 Perl_find_runcv(pTHX_ U32 *db_seqp)
3319 return Perl_find_runcv_where(aTHX_ 0, 0, db_seqp);
3322 /* If this becomes part of the API, it might need a better name. */
3324 Perl_find_runcv_where(pTHX_ U8 cond, IV arg, U32 *db_seqp)
3331 PL_curcop == &PL_compiling
3333 : PL_curcop->cop_seq;
3335 for (si = PL_curstackinfo; si; si = si->si_prev) {
3337 for (ix = si->si_cxix; ix >= 0; ix--) {
3338 const PERL_CONTEXT *cx = &(si->si_cxstack[ix]);
3340 if (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT) {
3341 cv = cx->blk_sub.cv;
3342 /* skip DB:: code */
3343 if (db_seqp && PL_debstash && CvSTASH(cv) == PL_debstash) {
3344 *db_seqp = cx->blk_oldcop->cop_seq;
3347 if (cx->cx_type & CXp_SUB_RE)
3350 else if (CxTYPE(cx) == CXt_EVAL && !CxTRYBLOCK(cx))
3351 cv = cx->blk_eval.cv;
3354 case FIND_RUNCV_padid_eq:
3356 || CvPADLIST(cv)->xpadl_id != (U32)arg)
3359 case FIND_RUNCV_level_eq:
3360 if (level++ != arg) continue;
3368 return cond == FIND_RUNCV_padid_eq ? NULL : PL_main_cv;
3372 /* Run yyparse() in a setjmp wrapper. Returns:
3373 * 0: yyparse() successful
3374 * 1: yyparse() failed
3378 S_try_yyparse(pTHX_ int gramtype)
3383 assert(CxTYPE(CX_CUR()) == CXt_EVAL);
3387 ret = yyparse(gramtype) ? 1 : 0;
3394 NOT_REACHED; /* NOTREACHED */
3401 /* Compile a require/do or an eval ''.
3403 * outside is the lexically enclosing CV (if any) that invoked us.
3404 * seq is the current COP scope value.
3405 * hh is the saved hints hash, if any.
3407 * Returns a bool indicating whether the compile was successful; if so,
3408 * PL_eval_start contains the first op of the compiled code; otherwise,
3411 * This function is called from two places: pp_require and pp_entereval.
3412 * These can be distinguished by whether PL_op is entereval.
3416 S_doeval_compile(pTHX_ U8 gimme, CV* outside, U32 seq, HV *hh)
3419 OP * const saveop = PL_op;
3420 bool clear_hints = saveop->op_type != OP_ENTEREVAL;
3421 COP * const oldcurcop = PL_curcop;
3422 bool in_require = (saveop->op_type == OP_REQUIRE);
3426 PL_in_eval = (in_require
3427 ? (EVAL_INREQUIRE | (PL_in_eval & EVAL_INEVAL))
3429 ((PL_op->op_private & OPpEVAL_RE_REPARSING)
3430 ? EVAL_RE_REPARSING : 0)));
3434 evalcv = MUTABLE_CV(newSV_type(SVt_PVCV));
3436 assert(CxTYPE(CX_CUR()) == CXt_EVAL);
3437 CX_CUR()->blk_eval.cv = evalcv;
3438 CX_CUR()->blk_gimme = gimme;
3440 CvOUTSIDE_SEQ(evalcv) = seq;
3441 CvOUTSIDE(evalcv) = MUTABLE_CV(SvREFCNT_inc_simple(outside));
3443 /* set up a scratch pad */
3445 CvPADLIST_set(evalcv, pad_new(padnew_SAVE));
3446 PL_op = NULL; /* avoid PL_op and PL_curpad referring to different CVs */
3449 SAVEMORTALIZESV(evalcv); /* must remain until end of current statement */
3451 /* make sure we compile in the right package */
3453 if (CopSTASH_ne(PL_curcop, PL_curstash)) {
3454 SAVEGENERICSV(PL_curstash);
3455 PL_curstash = (HV *)CopSTASH(PL_curcop);
3456 if (SvTYPE(PL_curstash) != SVt_PVHV) PL_curstash = NULL;
3458 SvREFCNT_inc_simple_void(PL_curstash);
3459 save_item(PL_curstname);
3460 sv_sethek(PL_curstname, HvNAME_HEK(PL_curstash));
3463 /* XXX:ajgo do we really need to alloc an AV for begin/checkunit */
3464 SAVESPTR(PL_beginav);
3465 PL_beginav = newAV();
3466 SAVEFREESV(PL_beginav);
3467 SAVESPTR(PL_unitcheckav);
3468 PL_unitcheckav = newAV();
3469 SAVEFREESV(PL_unitcheckav);
3472 ENTER_with_name("evalcomp");
3473 SAVESPTR(PL_compcv);
3476 /* try to compile it */
3478 PL_eval_root = NULL;
3479 PL_curcop = &PL_compiling;
3480 if ((saveop->op_type != OP_REQUIRE) && (saveop->op_flags & OPf_SPECIAL))
3481 PL_in_eval |= EVAL_KEEPERR;
3488 hv_clear(GvHV(PL_hintgv));
3492 PL_hints = saveop->op_private & OPpEVAL_COPHH
3493 ? oldcurcop->cop_hints : (U32)saveop->op_targ;
3495 /* making 'use re eval' not be in scope when compiling the
3496 * qr/mabye_has_runtime_code_block/ ensures that we don't get
3497 * infinite recursion when S_has_runtime_code() gives a false
3498 * positive: the second time round, HINT_RE_EVAL isn't set so we
3499 * don't bother calling S_has_runtime_code() */
3500 if (PL_in_eval & EVAL_RE_REPARSING)
3501 PL_hints &= ~HINT_RE_EVAL;
3504 /* SAVEHINTS created a new HV in PL_hintgv, which we need to GC */
3505 SvREFCNT_dec(GvHV(PL_hintgv));
3506 GvHV(PL_hintgv) = hh;
3507 FETCHFEATUREBITSHH(hh);
3510 SAVECOMPILEWARNINGS();
3512 if (PL_dowarn & G_WARN_ALL_ON)
3513 PL_compiling.cop_warnings = pWARN_ALL ;
3514 else if (PL_dowarn & G_WARN_ALL_OFF)
3515 PL_compiling.cop_warnings = pWARN_NONE ;
3517 PL_compiling.cop_warnings = pWARN_STD ;
3520 PL_compiling.cop_warnings =
3521 DUP_WARNINGS(oldcurcop->cop_warnings);
3522 cophh_free(CopHINTHASH_get(&PL_compiling));
3523 if (Perl_cop_fetch_label(aTHX_ oldcurcop, NULL, NULL)) {
3524 /* The label, if present, is the first entry on the chain. So rather
3525 than writing a blank label in front of it (which involves an
3526 allocation), just use the next entry in the chain. */
3527 PL_compiling.cop_hints_hash
3528 = cophh_copy(oldcurcop->cop_hints_hash->refcounted_he_next);
3529 /* Check the assumption that this removed the label. */
3530 assert(Perl_cop_fetch_label(aTHX_ &PL_compiling, NULL, NULL) == NULL);
3533 PL_compiling.cop_hints_hash = cophh_copy(oldcurcop->cop_hints_hash);
3536 CALL_BLOCK_HOOKS(bhk_eval, saveop);
3538 /* note that yyparse() may raise an exception, e.g. C<BEGIN{die}>,
3539 * so honour CATCH_GET and trap it here if necessary */
3542 /* compile the code */
3543 yystatus = (!in_require && CATCH_GET) ? S_try_yyparse(aTHX_ GRAMPROG) : yyparse(GRAMPROG);
3545 if (yystatus || PL_parser->error_count || !PL_eval_root) {
3550 /* note that if yystatus == 3, then the require/eval died during
3551 * compilation, so the EVAL CX block has already been popped, and
3552 * various vars restored */
3553 if (yystatus != 3) {
3555 op_free(PL_eval_root);
3556 PL_eval_root = NULL;
3558 SP = PL_stack_base + POPMARK; /* pop original mark */
3560 assert(CxTYPE(cx) == CXt_EVAL);
3561 /* pop the CXt_EVAL, and if was a require, croak */
3562 S_pop_eval_context_maybe_croak(aTHX_ cx, ERRSV, 2);
3565 /* die_unwind() re-croaks when in require, having popped the
3566 * require EVAL context. So we should never catch a require
3568 assert(!in_require);
3571 if (!*(SvPV_nolen_const(errsv)))
3572 sv_setpvs(errsv, "Compilation error");
3574 if (gimme != G_ARRAY) PUSHs(&PL_sv_undef);
3579 /* Compilation successful. Now clean up */
3581 LEAVE_with_name("evalcomp");
3583 CopLINE_set(&PL_compiling, 0);
3584 SAVEFREEOP(PL_eval_root);
3585 cv_forget_slab(evalcv);
3587 DEBUG_x(dump_eval());
3589 /* Register with debugger: */
3590 if (PERLDB_INTER && saveop->op_type == OP_REQUIRE) {
3591 CV * const cv = get_cvs("DB::postponed", 0);
3595 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
3597 call_sv(MUTABLE_SV(cv), G_DISCARD);
3601 if (PL_unitcheckav) {
3602 OP *es = PL_eval_start;
3603 call_list(PL_scopestack_ix, PL_unitcheckav);
3607 CvDEPTH(evalcv) = 1;
3608 SP = PL_stack_base + POPMARK; /* pop original mark */
3609 PL_op = saveop; /* The caller may need it. */
3610 PL_parser->lex_state = LEX_NOTPARSING; /* $^S needs this. */
3616 /* Return NULL if the file doesn't exist or isn't a file;
3617 * else return PerlIO_openn().
3621 S_check_type_and_open(pTHX_ SV *name)
3626 const char *p = SvPV_const(name, len);
3629 PERL_ARGS_ASSERT_CHECK_TYPE_AND_OPEN;
3631 /* checking here captures a reasonable error message when
3632 * PERL_DISABLE_PMC is true, but when PMC checks are enabled, the
3633 * user gets a confusing message about looking for the .pmc file
3634 * rather than for the .pm file so do the check in S_doopen_pm when
3635 * PMC is on instead of here. S_doopen_pm calls this func.
3636 * This check prevents a \0 in @INC causing problems.
3638 #ifdef PERL_DISABLE_PMC
3639 if (!IS_SAFE_PATHNAME(p, len, "require"))
3643 /* on Win32 stat is expensive (it does an open() and close() twice and
3644 a couple other IO calls), the open will fail with a dir on its own with
3645 errno EACCES, so only do a stat to separate a dir from a real EACCES
3646 caused by user perms */
3648 st_rc = PerlLIO_stat(p, &st);
3654 if(S_ISBLK(st.st_mode)) {
3658 else if(S_ISDIR(st.st_mode)) {
3667 retio = PerlIO_openn(aTHX_ ":", PERL_SCRIPT_MODE, -1, 0, 0, NULL, 1, &name);
3669 /* EACCES stops the INC search early in pp_require to implement
3670 feature RT #113422 */
3671 if(!retio && errno == EACCES) { /* exists but probably a directory */
3673 st_rc = PerlLIO_stat(p, &st);
3675 if(S_ISDIR(st.st_mode))
3677 else if(S_ISBLK(st.st_mode))
3688 /* doopen_pm(): return the equivalent of PerlIO_openn() on the given name,
3689 * but first check for bad names (\0) and non-files.
3690 * Also if the filename ends in .pm and unless PERL_DISABLE_PMC,
3691 * try loading Foo.pmc first.
3693 #ifndef PERL_DISABLE_PMC
3695 S_doopen_pm(pTHX_ SV *name)
3698 const char *p = SvPV_const(name, namelen);
3700 PERL_ARGS_ASSERT_DOOPEN_PM;
3702 /* check the name before trying for the .pmc name to avoid the
3703 * warning referring to the .pmc which the user probably doesn't
3704 * know or care about
3706 if (!IS_SAFE_PATHNAME(p, namelen, "require"))
3709 if (memENDPs(p, namelen, ".pm")) {
3710 SV *const pmcsv = sv_newmortal();
3713 SvSetSV_nosteal(pmcsv,name);
3714 sv_catpvs(pmcsv, "c");
3716 pmcio = check_type_and_open(pmcsv);
3720 return check_type_and_open(name);
3723 # define doopen_pm(name) check_type_and_open(name)
3724 #endif /* !PERL_DISABLE_PMC */
3726 /* require doesn't search in @INC for absolute names, or when the name is
3727 explicitly relative the current directory: i.e. ./, ../ */
3728 PERL_STATIC_INLINE bool
3729 S_path_is_searchable(const char *name)
3731 PERL_ARGS_ASSERT_PATH_IS_SEARCHABLE;
3733 if (PERL_FILE_IS_ABSOLUTE(name)
3735 || (*name == '.' && ((name[1] == '/' ||
3736 (name[1] == '.' && name[2] == '/'))
3737 || (name[1] == '\\' ||
3738 ( name[1] == '.' && name[2] == '\\')))
3741 || (*name == '.' && (name[1] == '/' ||
3742 (name[1] == '.' && name[2] == '/')))
3753 /* implement 'require 5.010001' */
3756 S_require_version(pTHX_ SV *sv)
3760 sv = sv_2mortal(new_version(sv));
3761 if (!Perl_sv_derived_from_pvn(aTHX_ PL_patchlevel, STR_WITH_LEN("version"), 0))
3762 upg_version(PL_patchlevel, TRUE);
3763 if (cUNOP->op_first->op_type == OP_CONST && cUNOP->op_first->op_private & OPpCONST_NOVER) {
3764 if ( vcmp(sv,PL_patchlevel) <= 0 )
3765 DIE(aTHX_ "Perls since %" SVf " too modern--this is %" SVf ", stopped",
3766 SVfARG(sv_2mortal(vnormal(sv))),
3767 SVfARG(sv_2mortal(vnormal(PL_patchlevel)))
3771 if ( vcmp(sv,PL_patchlevel) > 0 ) {
3774 SV * const req = SvRV(sv);
3775 SV * const pv = *hv_fetchs(MUTABLE_HV(req), "original", FALSE);
3777 /* get the left hand term */
3778 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(req), "version", FALSE)));
3780 first = SvIV(*av_fetch(lav,0,0));
3781 if ( first > (int)PERL_REVISION /* probably 'use 6.0' */
3782 || hv_exists(MUTABLE_HV(req), "qv", 2 ) /* qv style */
3783 || av_tindex(lav) > 1 /* FP with > 3 digits */
3784 || strstr(SvPVX(pv),".0") /* FP with leading 0 */
3786 DIE(aTHX_ "Perl %" SVf " required--this is only "
3787 "%" SVf ", stopped",
3788 SVfARG(sv_2mortal(vnormal(req))),
3789 SVfARG(sv_2mortal(vnormal(PL_patchlevel)))
3792 else { /* probably 'use 5.10' or 'use 5.8' */
3796 if (av_tindex(lav)>=1)
3797 second = SvIV(*av_fetch(lav,1,0));
3799 second /= second >= 600 ? 100 : 10;
3800 hintsv = Perl_newSVpvf(aTHX_ "v%d.%d.0",
3801 (int)first, (int)second);
3802 upg_version(hintsv, TRUE);
3804 DIE(aTHX_ "Perl %" SVf " required (did you mean %" SVf "?)"
3805 "--this is only %" SVf ", stopped",
3806 SVfARG(sv_2mortal(vnormal(req))),
3807 SVfARG(sv_2mortal(vnormal(sv_2mortal(hintsv)))),
3808 SVfARG(sv_2mortal(vnormal(PL_patchlevel)))
3817 /* Handle C<require Foo::Bar>, C<require "Foo/Bar.pm"> and C<do "Foo.pm">.
3818 * The first form will have already been converted at compile time to
3819 * the second form */
3822 S_require_file(pTHX_ SV *sv)
3832 int vms_unixname = 0;
3835 /* tryname is the actual pathname (with @INC prefix) which was loaded.
3836 * It's stored as a value in %INC, and used for error messages */
3837 const char *tryname = NULL;
3838 SV *namesv = NULL; /* SV equivalent of tryname */
3839 const U8 gimme = GIMME_V;
3840 int filter_has_file = 0;
3841 PerlIO *tryrsfp = NULL;
3842 SV *filter_cache = NULL;
3843 SV *filter_state = NULL;
3844 SV *filter_sub = NULL;
3848 bool path_searchable;
3849 I32 old_savestack_ix;
3850 const bool op_is_require = PL_op->op_type == OP_REQUIRE;
3851 const char *const op_name = op_is_require ? "require" : "do";
3852 SV ** svp_cached = NULL;
3854 assert(op_is_require || PL_op->op_type == OP_DOFILE);
3857 DIE(aTHX_ "Missing or undefined argument to %s", op_name);
3858 name = SvPV_nomg_const(sv, len);
3859 if (!(name && len > 0 && *name))
3860 DIE(aTHX_ "Missing or undefined argument to %s", op_name);
3863 /* try to return earlier (save the SAFE_PATHNAME check) if INC already got the name */
3864 if (op_is_require) {
3865 /* can optimize to only perform one single lookup */
3866 svp_cached = hv_fetch(GvHVn(PL_incgv), (char*) name, len, 0);
3867 if ( svp_cached && *svp_cached != &PL_sv_undef ) RETPUSHYES;
3871 if (!IS_SAFE_PATHNAME(name, len, op_name)) {
3872 if (!op_is_require) {
3876 DIE(aTHX_ "Can't locate %s: %s",
3877 pv_escape(newSVpvs_flags("",SVs_TEMP),name,len,len*2,
3878 NULL, SvUTF8(sv)?PERL_PV_ESCAPE_UNI:0),
3881 TAINT_PROPER(op_name);
3883 path_searchable = path_is_searchable(name);
3886 /* The key in the %ENV hash is in the syntax of file passed as the argument
3887 * usually this is in UNIX format, but sometimes in VMS format, which
3888 * can result in a module being pulled in more than once.
3889 * To prevent this, the key must be stored in UNIX format if the VMS
3890 * name can be translated to UNIX.
3894 tounixspec(name, SvPVX(sv_2mortal(newSVpv("", VMS_MAXRSS-1)))))
3896 unixlen = strlen(unixname);
3902 /* if not VMS or VMS name can not be translated to UNIX, pass it
3905 unixname = (char *) name;
3908 if (op_is_require) {
3909 /* reuse the previous hv_fetch result if possible */
3910 SV * const * const svp = svp_cached ? svp_cached : hv_fetch(GvHVn(PL_incgv), unixname, unixlen, 0);
3912 if (*svp != &PL_sv_undef)
3915 DIE(aTHX_ "Attempt to reload %s aborted.\n"
3916 "Compilation failed in require", unixname);
3919 /*XXX OPf_KIDS should always be true? -dapm 4/2017 */
3920 if (PL_op->op_flags & OPf_KIDS) {
3921 SVOP * const kid = (SVOP*)cUNOP->op_first;
3923 if (kid->op_type == OP_CONST && (kid->op_private & OPpCONST_BARE)) {
3924 /* Make sure that a bareword module name (e.g. ::Foo::Bar)
3925 * doesn't map to a naughty pathname like /Foo/Bar.pm.
3926 * Note that the parser will normally detect such errors
3927 * at compile time before we reach here, but
3928 * Perl_load_module() can fake up an identical optree
3929 * without going near the parser, and being able to put
3930 * anything as the bareword. So we include a duplicate set
3931 * of checks here at runtime.
3933 const STRLEN package_len = len - 3;
3934 const char slashdot[2] = {'/', '.'};
3936 const char backslashdot[2] = {'\\', '.'};
3939 /* Disallow *purported* barewords that map to absolute
3940 filenames, filenames relative to the current or parent
3941 directory, or (*nix) hidden filenames. Also sanity check
3942 that the generated filename ends .pm */
3943 if (!path_searchable || len < 3 || name[0] == '.'
3944 || !memEQs(name + package_len, len - package_len, ".pm"))
3945 DIE(aTHX_ "Bareword in require maps to disallowed filename \"%" SVf "\"", sv);
3946 if (memchr(name, 0, package_len)) {
3947 /* diag_listed_as: Bareword in require contains "%s" */
3948 DIE(aTHX_ "Bareword in require contains \"\\0\"");
3950 if (ninstr(name, name + package_len, slashdot,
3951 slashdot + sizeof(slashdot))) {
3952 /* diag_listed_as: Bareword in require contains "%s" */
3953 DIE(aTHX_ "Bareword in require contains \"/.\"");
3956 if (ninstr(name, name + package_len, backslashdot,
3957 backslashdot + sizeof(backslashdot))) {
3958 /* diag_listed_as: Bareword in require contains "%s" */
3959 DIE(aTHX_ "Bareword in require contains \"\\.\"");
3966 PERL_DTRACE_PROBE_FILE_LOADING(unixname);
3968 /* Try to locate and open a file, possibly using @INC */
3970 /* with "/foo/bar.pm", "./foo.pm" and "../foo/bar.pm", try to load
3971 * the file directly rather than via @INC ... */
3972 if (!path_searchable) {
3973 /* At this point, name is SvPVX(sv) */
3975 tryrsfp = doopen_pm(sv);
3978 /* ... but if we fail, still search @INC for code references;
3979 * these are applied even on on-searchable paths (except
3980 * if we got EACESS).
3982 * For searchable paths, just search @INC normally
3984 if (!tryrsfp && !(errno == EACCES && !path_searchable)) {
3985 AV * const ar = GvAVn(PL_incgv);
3992 namesv = newSV_type(SVt_PV);
3993 for (i = 0; i <= AvFILL(ar); i++) {
3994 SV * const dirsv = *av_fetch(ar, i, TRUE);
4002 if (SvTYPE(SvRV(loader)) == SVt_PVAV
4003 && !SvOBJECT(SvRV(loader)))
4005 loader = *av_fetch(MUTABLE_AV(SvRV(loader)), 0, TRUE);
4009 Perl_sv_setpvf(aTHX_ namesv, "/loader/0x%" UVxf "/%s",
4010 PTR2UV(SvRV(dirsv)), name);
4011 tryname = SvPVX_const(namesv);
4014 if (SvPADTMP(nsv)) {
4015 nsv = sv_newmortal();
4016 SvSetSV_nosteal(nsv,sv);
4019 ENTER_with_name("call_INC");
4027 if (SvGMAGICAL(loader)) {
4028 SV *l = sv_newmortal();
4029 sv_setsv_nomg(l, loader);
4032 if (sv_isobject(loader))
4033 count = call_method("INC", G_ARRAY);
4035 count = call_sv(loader, G_ARRAY);
4045 if (SvROK(arg) && (SvTYPE(SvRV(arg)) <= SVt_PVLV)
4046 && !isGV_with_GP(SvRV(arg))) {
4047 filter_cache = SvRV(arg);
4054 if (SvROK(arg) && isGV_with_GP(SvRV(arg))) {
4058 if (isGV_with_GP(arg)) {
4059 IO * const io = GvIO((const GV *)arg);
4064 tryrsfp = IoIFP(io);
4065 if (IoOFP(io) && IoOFP(io) != IoIFP(io)) {
4066 PerlIO_close(IoOFP(io));
4077 if (SvROK(arg) && SvTYPE(SvRV(arg)) == SVt_PVCV) {
4079 SvREFCNT_inc_simple_void_NN(filter_sub);
4082 filter_state = SP[i];
4083 SvREFCNT_inc_simple_void(filter_state);
4087 if (!tryrsfp && (filter_cache || filter_sub)) {
4088 tryrsfp = PerlIO_open(BIT_BUCKET,
4094 /* FREETMPS may free our filter_cache */
4095 SvREFCNT_inc_simple_void(filter_cache);
4099 LEAVE_with_name("call_INC");
4101 /* Now re-mortalize it. */
4102 sv_2mortal(filter_cache);
4104 /* Adjust file name if the hook has set an %INC entry.
4105 This needs to happen after the FREETMPS above. */
4106 svp = hv_fetch(GvHVn(PL_incgv), name, len, 0);
4108 tryname = SvPV_nolen_const(*svp);
4115 filter_has_file = 0;
4116 filter_cache = NULL;
4118 SvREFCNT_dec_NN(filter_state);
4119 filter_state = NULL;
4122 SvREFCNT_dec_NN(filter_sub);
4126 else if (path_searchable) {
4127 /* match against a plain @INC element (non-searchable
4128 * paths are only matched against refs in @INC) */
4133 dir = SvPV_nomg_const(dirsv, dirlen);
4139 if (!IS_SAFE_SYSCALL(dir, dirlen, "@INC entry", op_name))
4143 tounixpath(dir, SvPVX(sv_2mortal(newSVpv("", VMS_MAXRSS-1)))))
4146 sv_setpv(namesv, unixdir);
4147 sv_catpv(namesv, unixname);
4148 #elif defined(__SYMBIAN32__)
4149 if (PL_origfilename[0] &&
4150 PL_origfilename[1] == ':' &&
4151 !(dir[0] && dir[1] == ':'))
4152 Perl_sv_setpvf(aTHX_ namesv,
4157 Perl_sv_setpvf(aTHX_ namesv,
4161 /* The equivalent of
4162 Perl_sv_setpvf(aTHX_ namesv, "%s/%s", dir, name);
4163 but without the need to parse the format string, or
4164 call strlen on either pointer, and with the correct
4165 allocation up front. */
4167 char *tmp = SvGROW(namesv, dirlen + len + 2);
4169 memcpy(tmp, dir, dirlen);
4172 /* Avoid '<dir>//<file>' */
4173 if (!dirlen || *(tmp-1) != '/') {
4176 /* So SvCUR_set reports the correct length below */
4180 /* name came from an SV, so it will have a '\0' at the
4181 end that we can copy as part of this memcpy(). */
4182 memcpy(tmp, name, len + 1);
4184 SvCUR_set(namesv, dirlen + len + 1);
4188 TAINT_PROPER(op_name);
4189 tryname = SvPVX_const(namesv);
4190 tryrsfp = doopen_pm(namesv);
4192 if (tryname[0] == '.' && tryname[1] == '/') {
4194 while (*++tryname == '/') {}
4198 else if (errno == EMFILE || errno == EACCES) {
4199 /* no point in trying other paths if out of handles;
4200 * on the other hand, if we couldn't open one of the
4201 * files, then going on with the search could lead to
4202 * unexpected results; see perl #113422
4211 /* at this point we've ether opened a file (tryrsfp) or set errno */
4213 saved_errno = errno; /* sv_2mortal can realloc things */
4216 /* we failed; croak if require() or return undef if do() */
4217 if (op_is_require) {
4218 if(saved_errno == EMFILE || saved_errno == EACCES) {
4219 /* diag_listed_as: Can't locate %s */
4220 DIE(aTHX_ "Can't locate %s: %s: %s",
4221 name, tryname, Strerror(saved_errno));
4223 if (path_searchable) { /* did we lookup @INC? */
4224 AV * const ar = GvAVn(PL_incgv);
4226 SV *const msg = newSVpvs_flags("", SVs_TEMP);
4227 SV *const inc = newSVpvs_flags("", SVs_TEMP);
4228 for (i = 0; i <= AvFILL(ar); i++) {
4229 sv_catpvs(inc, " ");
4230 sv_catsv(inc, *av_fetch(ar, i, TRUE));
4232 if (memENDPs(name, len, ".pm")) {
4233 const char *e = name + len - (sizeof(".pm") - 1);
4235 bool utf8 = cBOOL(SvUTF8(sv));
4237 /* if the filename, when converted from "Foo/Bar.pm"
4238 * form back to Foo::Bar form, makes a valid
4239 * package name (i.e. parseable by C<require
4240 * Foo::Bar>), then emit a hint.
4242 * this loop is modelled after the one in
4246 if (utf8 && isIDFIRST_utf8_safe(c, e)) {
4248 while (c < e && isIDCONT_utf8_safe(
4249 (const U8*) c, (const U8*) e))
4252 else if (isWORDCHAR_A(*c)) {
4253 while (c < e && isWORDCHAR_A(*c))
4262 if (c == e && isIDFIRST_lazy_if_safe(name, e, utf8)) {
4263 sv_catpvs(msg, " (you may need to install the ");
4264 for (c = name; c < e; c++) {
4266 sv_catpvs(msg, "::");
4269 sv_catpvn(msg, c, 1);
4272 sv_catpvs(msg, " module)");
4275 else if (memENDs(name, len, ".h")) {
4276 sv_catpvs(msg, " (change .h to .ph maybe?) (did you run h2ph?)");
4278 else if (memENDs(name, len, ".ph")) {
4279 sv_catpvs(msg, " (did you run h2ph?)");
4282 /* diag_listed_as: Can't locate %s */
4284 "Can't locate %s in @INC%" SVf " (@INC contains:%" SVf ")",
4288 DIE(aTHX_ "Can't locate %s", name);
4291 #ifdef DEFAULT_INC_EXCLUDES_DOT
4295 /* the complication is to match the logic from doopen_pm() so
4296 * we don't treat do "sda1" as a previously successful "do".
4298 bool do_warn = namesv && ckWARN_d(WARN_DEPRECATED)
4299 && PerlLIO_stat(name, &st) == 0 && !S_ISDIR(st.st_mode) && !S_ISBLK(st.st_mode)
4300 && (io = PerlIO_openn(aTHX_ ":", PERL_SCRIPT_MODE, -1, 0, 0, NULL, 1, &sv)) != NULL;
4306 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),
4307 "do \"%s\" failed, '.' is no longer in @INC; "
4308 "did you mean do \"./%s\"?",
4317 SETERRNO(0, SS_NORMAL);
4319 /* Update %INC. Assume success here to prevent recursive requirement. */
4320 /* name is never assigned to again, so len is still strlen(name) */
4321 /* Check whether a hook in @INC has already filled %INC */
4323 (void)hv_store(GvHVn(PL_incgv),
4324 unixname, unixlen, newSVpv(tryname,0),0);
4326 SV** const svp = hv_fetch(GvHVn(PL_incgv), unixname, unixlen, 0);
4328 (void)hv_store(GvHVn(PL_incgv),
4329 unixname, unixlen, SvREFCNT_inc_simple(hook_sv), 0 );
4332 /* Now parse the file */
4334 old_savestack_ix = PL_savestack_ix;
4335 SAVECOPFILE_FREE(&PL_compiling);
4336 CopFILE_set(&PL_compiling, tryname);
4337 lex_start(NULL, tryrsfp, 0);
4339 if (filter_sub || filter_cache) {
4340 /* We can use the SvPV of the filter PVIO itself as our cache, rather
4341 than hanging another SV from it. In turn, filter_add() optionally
4342 takes the SV to use as the filter (or creates a new SV if passed
4343 NULL), so simply pass in whatever value filter_cache has. */
4344 SV * const fc = filter_cache ? newSV(0) : NULL;
4346 if (fc) sv_copypv(fc, filter_cache);
4347 datasv = filter_add(S_run_user_filter, fc);
4348 IoLINES(datasv) = filter_has_file;
4349 IoTOP_GV(datasv) = MUTABLE_GV(filter_state);
4350 IoBOTTOM_GV(datasv) = MUTABLE_GV(filter_sub);
4353 /* switch to eval mode */
4355 cx = cx_pushblock(CXt_EVAL, gimme, SP, old_savestack_ix);
4356 cx_pusheval(cx, PL_op->op_next, newSVpv(name, 0));
4358 SAVECOPLINE(&PL_compiling);
4359 CopLINE_set(&PL_compiling, 0);
4363 if (doeval_compile(gimme, NULL, PL_curcop->cop_seq, NULL))
4366 op = PL_op->op_next;
4368 PERL_DTRACE_PROBE_FILE_LOADED(unixname);
4374 /* also used for: pp_dofile() */
4378 RUN_PP_CATCHABLY(Perl_pp_require);
4385 return ((SvNIOKp(sv) || SvVOK(sv)) && PL_op->op_type != OP_DOFILE)
4386 ? S_require_version(aTHX_ sv)
4387 : S_require_file(aTHX_ sv);
4392 /* This is a op added to hold the hints hash for
4393 pp_entereval. The hash can be modified by the code
4394 being eval'ed, so we return a copy instead. */
4399 mXPUSHs(MUTABLE_SV(hv_copy_hints_hv(MUTABLE_HV(cSVOP_sv))));
4411 char tbuf[TYPE_DIGITS(long) + 12];
4419 I32 old_savestack_ix;
4421 RUN_PP_CATCHABLY(Perl_pp_entereval);
4424 was = PL_breakable_sub_gen;
4425 saved_delete = FALSE;
4429 bytes = PL_op->op_private & OPpEVAL_BYTES;
4431 if (PL_op->op_private & OPpEVAL_HAS_HH) {
4432 saved_hh = MUTABLE_HV(SvREFCNT_inc(POPs));
4434 else if (PL_hints & HINT_LOCALIZE_HH || (
4435 PL_op->op_private & OPpEVAL_COPHH
4436 && PL_curcop->cop_hints & HINT_LOCALIZE_HH
4438 saved_hh = cop_hints_2hv(PL_curcop, 0);
4439 hv_magic(saved_hh, NULL, PERL_MAGIC_hints);
4443 /* make sure we've got a plain PV (no overload etc) before testing
4444 * for taint. Making a copy here is probably overkill, but better
4445 * safe than sorry */
4447 const char * const p = SvPV_const(sv, len);
4449 sv = newSVpvn_flags(p, len, SVs_TEMP | SvUTF8(sv));
4450 lex_flags |= LEX_START_COPIED;
4452 if (bytes && SvUTF8(sv))
4453 SvPVbyte_force(sv, len);
4455 else if (bytes && SvUTF8(sv)) {
4456 /* Don't modify someone else's scalar */
4459 (void)sv_2mortal(sv);
4460 SvPVbyte_force(sv,len);
4461 lex_flags |= LEX_START_COPIED;
4464 TAINT_IF(SvTAINTED(sv));
4465 TAINT_PROPER("eval");
4467 old_savestack_ix = PL_savestack_ix;
4469 lex_start(sv, NULL, lex_flags | (PL_op->op_private & OPpEVAL_UNICODE
4470 ? LEX_IGNORE_UTF8_HINTS
4471 : bytes ? LEX_EVALBYTES : LEX_START_SAME_FILTER
4475 /* switch to eval mode */
4477 if (PERLDB_NAMEEVAL && CopLINE(PL_curcop)) {
4478 SV * const temp_sv = sv_newmortal();
4479 Perl_sv_setpvf(aTHX_ temp_sv, "_<(eval %lu)[%s:%" IVdf "]",
4480 (unsigned long)++PL_evalseq,
4481 CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
4482 tmpbuf = SvPVX(temp_sv);
4483 len = SvCUR(temp_sv);
4486 len = my_snprintf(tmpbuf, sizeof(tbuf), "_<(eval %lu)", (unsigned long)++PL_evalseq);
4487 SAVECOPFILE_FREE(&PL_compiling);
4488 CopFILE_set(&PL_compiling, tmpbuf+2);
4489 SAVECOPLINE(&PL_compiling);
4490 CopLINE_set(&PL_compiling, 1);
4491 /* special case: an eval '' executed within the DB package gets lexically
4492 * placed in the first non-DB CV rather than the current CV - this
4493 * allows the debugger to execute code, find lexicals etc, in the
4494 * scope of the code being debugged. Passing &seq gets find_runcv
4495 * to do the dirty work for us */
4496 runcv = find_runcv(&seq);
4499 cx = cx_pushblock((CXt_EVAL|CXp_REAL), gimme, SP, old_savestack_ix);
4500 cx_pusheval(cx, PL_op->op_next, NULL);
4502 /* prepare to compile string */
4504 if (PERLDB_LINE_OR_SAVESRC && PL_curstash != PL_debstash)
4505 save_lines(CopFILEAV(&PL_compiling), PL_parser->linestr);
4507 /* XXX For C<eval "...">s within BEGIN {} blocks, this ends up
4508 deleting the eval's FILEGV from the stash before gv_check() runs
4509 (i.e. before run-time proper). To work around the coredump that
4510 ensues, we always turn GvMULTI_on for any globals that were
4511 introduced within evals. See force_ident(). GSAR 96-10-12 */
4512 char *const safestr = savepvn(tmpbuf, len);
4513 SAVEDELETE(PL_defstash, safestr, len);
4514 saved_delete = TRUE;
4519 if (doeval_compile(gimme, runcv, seq, saved_hh)) {
4520 if (was != PL_breakable_sub_gen /* Some subs defined here. */
4521 ? PERLDB_LINE_OR_SAVESRC
4522 : PERLDB_SAVESRC_NOSUBS) {
4523 /* Retain the filegv we created. */
4524 } else if (!saved_delete) {
4525 char *const safestr = savepvn(tmpbuf, len);
4526 SAVEDELETE(PL_defstash, safestr, len);
4528 return PL_eval_start;
4530 /* We have already left the scope set up earlier thanks to the LEAVE
4531 in doeval_compile(). */
4532 if (was != PL_breakable_sub_gen /* Some subs defined here. */
4533 ? PERLDB_LINE_OR_SAVESRC
4534 : PERLDB_SAVESRC_INVALID) {
4535 /* Retain the filegv we created. */
4536 } else if (!saved_delete) {
4537 (void)hv_delete(PL_defstash, tmpbuf, len, G_DISCARD);
4539 return PL_op->op_next;
4544 /* also tail-called by pp_return */
4559 assert(CxTYPE(cx) == CXt_EVAL);
4561 oldsp = PL_stack_base + cx->blk_oldsp;
4562 gimme = cx->blk_gimme;
4564 /* did require return a false value? */
4565 failed = CxOLD_OP_TYPE(cx) == OP_REQUIRE
4566 && !(gimme == G_SCALAR
4567 ? SvTRUE_NN(*PL_stack_sp)
4568 : PL_stack_sp > oldsp);
4570 if (gimme == G_VOID) {
4571 PL_stack_sp = oldsp;
4572 /* free now to avoid late-called destructors clobbering $@ */
4576 leave_adjust_stacks(oldsp, oldsp, gimme, 0);
4578 /* the cx_popeval does a leavescope, which frees the optree associated
4579 * with eval, which if it frees the nextstate associated with
4580 * PL_curcop, sets PL_curcop to NULL. Which can mess up freeing a
4581 * regex when running under 'use re Debug' because it needs PL_curcop
4582 * to get the current hints. So restore it early.
4584 PL_curcop = cx->blk_oldcop;
4586 /* grab this value before cx_popeval restores the old PL_in_eval */
4587 keep = cBOOL(PL_in_eval & EVAL_KEEPERR);
4588 retop = cx->blk_eval.retop;
4589 evalcv = cx->blk_eval.cv;
4591 assert(CvDEPTH(evalcv) == 1);
4593 CvDEPTH(evalcv) = 0;
4595 /* pop the CXt_EVAL, and if a require failed, croak */
4596 S_pop_eval_context_maybe_croak(aTHX_ cx, NULL, failed);
4604 /* Common code for Perl_call_sv and Perl_fold_constants, put here to keep it
4605 close to the related Perl_create_eval_scope. */
4607 Perl_delete_eval_scope(pTHX)
4618 /* Common-ish code salvaged from Perl_call_sv and pp_entertry, because it was
4619 also needed by Perl_fold_constants. */
4621 Perl_create_eval_scope(pTHX_ OP *retop, U32 flags)
4624 const U8 gimme = GIMME_V;
4626 cx = cx_pushblock((CXt_EVAL|CXp_TRYBLOCK), gimme,
4627 PL_stack_sp, PL_savestack_ix);
4628 cx_pusheval(cx, retop, NULL);
4630 PL_in_eval = EVAL_INEVAL;
4631 if (flags & G_KEEPERR)
4632 PL_in_eval |= EVAL_KEEPERR;
4635 if (flags & G_FAKINGEVAL) {
4636 PL_eval_root = PL_op; /* Only needed so that goto works right. */
4642 RUN_PP_CATCHABLY(Perl_pp_entertry);
4645 create_eval_scope(cLOGOP->op_other->op_next, 0);
4646 return PL_op->op_next;
4650 /* also tail-called by pp_return */
4662 assert(CxTYPE(cx) == CXt_EVAL);
4663 oldsp = PL_stack_base + cx->blk_oldsp;
4664 gimme = cx->blk_gimme;
4666 if (gimme == G_VOID) {
4667 PL_stack_sp = oldsp;
4668 /* free now to avoid late-called destructors clobbering $@ */
4672 leave_adjust_stacks(oldsp, oldsp, gimme, 1);
4676 retop = cx->blk_eval.retop;
4687 const U8 gimme = GIMME_V;
4691 assert(!PL_op->op_targ); /* used to be set for lexical $_ */
4692 GvSV(PL_defgv) = SvREFCNT_inc(newsv);
4694 cx = cx_pushblock(CXt_GIVEN, gimme, SP, PL_savestack_ix);
4695 cx_pushgiven(cx, origsv);
4705 PERL_UNUSED_CONTEXT;
4708 assert(CxTYPE(cx) == CXt_GIVEN);
4709 oldsp = PL_stack_base + cx->blk_oldsp;
4710 gimme = cx->blk_gimme;
4712 if (gimme == G_VOID)
4713 PL_stack_sp = oldsp;
4715 leave_adjust_stacks(oldsp, oldsp, gimme, 1);
4725 /* Helper routines used by pp_smartmatch */
4727 S_make_matcher(pTHX_ REGEXP *re)
4729 PMOP *matcher = (PMOP *) newPMOP(OP_MATCH, OPf_WANT_SCALAR | OPf_STACKED);
4731 PERL_ARGS_ASSERT_MAKE_MATCHER;
4733 PM_SETRE(matcher, ReREFCNT_inc(re));
4735 SAVEFREEOP((OP *) matcher);
4736 ENTER_with_name("matcher"); SAVETMPS;
4742 S_matcher_matches_sv(pTHX_ PMOP *matcher, SV *sv)
4747 PERL_ARGS_ASSERT_MATCHER_MATCHES_SV;
4749 PL_op = (OP *) matcher;
4752 (void) Perl_pp_match(aTHX);
4754 result = SvTRUEx(POPs);
4761 S_destroy_matcher(pTHX_ PMOP *matcher)
4763 PERL_ARGS_ASSERT_DESTROY_MATCHER;
4764 PERL_UNUSED_ARG(matcher);
4767 LEAVE_with_name("matcher");
4770 /* Do a smart match */
4773 DEBUG_M(Perl_deb(aTHX_ "Starting smart match resolution\n"));
4774 return do_smartmatch(NULL, NULL, 0);
4777 /* This version of do_smartmatch() implements the
4778 * table of smart matches that is found in perlsyn.
4781 S_do_smartmatch(pTHX_ HV *seen_this, HV *seen_other, const bool copied)
4785 bool object_on_left = FALSE;
4786 SV *e = TOPs; /* e is for 'expression' */
4787 SV *d = TOPm1s; /* d is for 'default', as in PL_defgv */
4789 /* Take care only to invoke mg_get() once for each argument.
4790 * Currently we do this by copying the SV if it's magical. */
4792 if (!copied && SvGMAGICAL(d))
4793 d = sv_mortalcopy(d);
4800 e = sv_mortalcopy(e);
4802 /* First of all, handle overload magic of the rightmost argument */
4805 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Object\n"));
4806 DEBUG_M(Perl_deb(aTHX_ " attempting overload\n"));
4808 tmpsv = amagic_call(d, e, smart_amg, AMGf_noleft);
4815 DEBUG_M(Perl_deb(aTHX_ " failed to run overload method; continuing...\n"));
4818 SP -= 2; /* Pop the values */
4823 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-undef\n"));
4830 if (SvROK(e) && SvOBJECT(SvRV(e)) && (SvTYPE(SvRV(e)) != SVt_REGEXP)) {
4831 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Object\n"));
4832 Perl_croak(aTHX_ "Smart matching a non-overloaded object breaks encapsulation");
4834 if (SvROK(d) && SvOBJECT(SvRV(d)) && (SvTYPE(SvRV(d)) != SVt_REGEXP))
4835 object_on_left = TRUE;
4838 if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_PVCV) {
4840 if (object_on_left) {
4841 goto sm_any_sub; /* Treat objects like scalars */
4843 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
4844 /* Test sub truth for each key */
4846 bool andedresults = TRUE;
4847 HV *hv = (HV*) SvRV(d);
4848 I32 numkeys = hv_iterinit(hv);
4849 DEBUG_M(Perl_deb(aTHX_ " applying rule Hash-CodeRef\n"));
4852 while ( (he = hv_iternext(hv)) ) {
4853 DEBUG_M(Perl_deb(aTHX_ " testing hash key...\n"));
4854 ENTER_with_name("smartmatch_hash_key_test");
4857 PUSHs(hv_iterkeysv(he));
4859 c = call_sv(e, G_SCALAR);
4862 andedresults = FALSE;
4864 andedresults = SvTRUEx(POPs) && andedresults;
4866 LEAVE_with_name("smartmatch_hash_key_test");
4873 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
4874 /* Test sub truth for each element */
4876 bool andedresults = TRUE;
4877 AV *av = (AV*) SvRV(d);
4878 const I32 len = av_tindex(av);
4879 DEBUG_M(Perl_deb(aTHX_ " applying rule Array-CodeRef\n"));
4882 for (i = 0; i <= len; ++i) {
4883 SV * const * const svp = av_fetch(av, i, FALSE);
4884 DEBUG_M(Perl_deb(aTHX_ " testing array element...\n"));
4885 ENTER_with_name("smartmatch_array_elem_test");
4891 c = call_sv(e, G_SCALAR);
4894 andedresults = FALSE;
4896 andedresults = SvTRUEx(POPs) && andedresults;
4898 LEAVE_with_name("smartmatch_array_elem_test");
4907 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-CodeRef\n"));
4908 ENTER_with_name("smartmatch_coderef");
4913 c = call_sv(e, G_SCALAR);
4917 else if (SvTEMP(TOPs))
4918 SvREFCNT_inc_void(TOPs);
4920 LEAVE_with_name("smartmatch_coderef");
4925 else if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_PVHV) {
4926 if (object_on_left) {
4927 goto sm_any_hash; /* Treat objects like scalars */
4929 else if (!SvOK(d)) {
4930 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Hash ($a undef)\n"));
4933 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
4934 /* Check that the key-sets are identical */
4936 HV *other_hv = MUTABLE_HV(SvRV(d));
4939 U32 this_key_count = 0,
4940 other_key_count = 0;
4941 HV *hv = MUTABLE_HV(SvRV(e));
4943 DEBUG_M(Perl_deb(aTHX_ " applying rule Hash-Hash\n"));
4944 /* Tied hashes don't know how many keys they have. */
4945 tied = cBOOL(SvTIED_mg((SV*)hv, PERL_MAGIC_tied));
4946 other_tied = cBOOL(SvTIED_mg((const SV *)other_hv, PERL_MAGIC_tied));
4950 HV * const temp = other_hv;
4956 else if(HvUSEDKEYS((const HV *) hv) != HvUSEDKEYS(other_hv))
4960 /* The hashes have the same number of keys, so it suffices
4961 to check that one is a subset of the other. */
4962 (void) hv_iterinit(hv);
4963 while ( (he = hv_iternext(hv)) ) {
4964 SV *key = hv_iterkeysv(he);
4966 DEBUG_M(Perl_deb(aTHX_ " comparing hash key...\n"));
4969 if(!hv_exists_ent(other_hv, key, 0)) {
4970 (void) hv_iterinit(hv); /* reset iterator */
4976 (void) hv_iterinit(other_hv);
4977 while ( hv_iternext(other_hv) )
4981 other_key_count = HvUSEDKEYS(other_hv);
4983 if (this_key_count != other_key_count)
4988 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
4989 AV * const other_av = MUTABLE_AV(SvRV(d));
4990 const SSize_t other_len = av_tindex(other_av) + 1;
4992 HV *hv = MUTABLE_HV(SvRV(e));
4994 DEBUG_M(Perl_deb(aTHX_ " applying rule Array-Hash\n"));
4995 for (i = 0; i < other_len; ++i) {
4996 SV ** const svp = av_fetch(other_av, i, FALSE);
4997 DEBUG_M(Perl_deb(aTHX_ " checking for key existence...\n"));
4998 if (svp) { /* ??? When can this not happen? */
4999 if (hv_exists_ent(hv, *svp, 0))
5005 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_REGEXP) {
5006 DEBUG_M(Perl_deb(aTHX_ " applying rule Regex-Hash\n"));
5009 PMOP * const matcher = make_matcher((REGEXP*) SvRV(d));
5011 HV *hv = MUTABLE_HV(SvRV(e));
5013 (void) hv_iterinit(hv);
5014 while ( (he = hv_iternext(hv)) ) {
5015 DEBUG_M(Perl_deb(aTHX_ " testing key against pattern...\n"));
5017 if (matcher_matches_sv(matcher, hv_iterkeysv(he))) {
5019 (void) hv_iterinit(hv);
5020 destroy_matcher(matcher);
5025 destroy_matcher(matcher);
5031 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Hash\n"));
5032 if (hv_exists_ent(MUTABLE_HV(SvRV(e)), d, 0))
5039 else if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_PVAV) {
5040 if (object_on_left) {
5041 goto sm_any_array; /* Treat objects like scalars */
5043 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
5044 AV * const other_av = MUTABLE_AV(SvRV(e));
5045 const SSize_t other_len = av_tindex(other_av) + 1;
5048 DEBUG_M(Perl_deb(aTHX_ " applying rule Hash-Array\n"));
5049 for (i = 0; i < other_len; ++i) {
5050 SV ** const svp = av_fetch(other_av, i, FALSE);
5052 DEBUG_M(Perl_deb(aTHX_ " testing for key existence...\n"));
5053 if (svp) { /* ??? When can this not happen? */
5054 if (hv_exists_ent(MUTABLE_HV(SvRV(d)), *svp, 0))
5060 if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
5061 AV *other_av = MUTABLE_AV(SvRV(d));
5062 DEBUG_M(Perl_deb(aTHX_ " applying rule Array-Array\n"));
5063 if (av_tindex(MUTABLE_AV(SvRV(e))) != av_tindex(other_av))
5067 const SSize_t other_len = av_tindex(other_av);
5069 if (NULL == seen_this) {
5070 seen_this = newHV();
5071 (void) sv_2mortal(MUTABLE_SV(seen_this));
5073 if (NULL == seen_other) {
5074 seen_other = newHV();
5075 (void) sv_2mortal(MUTABLE_SV(seen_other));
5077 for(i = 0; i <= other_len; ++i) {
5078 SV * const * const this_elem = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
5079 SV * const * const other_elem = av_fetch(other_av, i, FALSE);
5081 if (!this_elem || !other_elem) {
5082 if ((this_elem && SvOK(*this_elem))
5083 || (other_elem && SvOK(*other_elem)))
5086 else if (hv_exists_ent(seen_this,
5087 sv_2mortal(newSViv(PTR2IV(*this_elem))), 0) ||
5088 hv_exists_ent(seen_other,
5089 sv_2mortal(newSViv(PTR2IV(*other_elem))), 0))
5091 if (*this_elem != *other_elem)
5095 (void)hv_store_ent(seen_this,
5096 sv_2mortal(newSViv(PTR2IV(*this_elem))),
5098 (void)hv_store_ent(seen_other,
5099 sv_2mortal(newSViv(PTR2IV(*other_elem))),
5105 DEBUG_M(Perl_deb(aTHX_ " recursively comparing array element...\n"));
5106 (void) do_smartmatch(seen_this, seen_other, 0);
5108 DEBUG_M(Perl_deb(aTHX_ " recursion finished\n"));
5117 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_REGEXP) {
5118 DEBUG_M(Perl_deb(aTHX_ " applying rule Regex-Array\n"));
5121 PMOP * const matcher = make_matcher((REGEXP*) SvRV(d));
5122 const SSize_t this_len = av_tindex(MUTABLE_AV(SvRV(e)));
5125 for(i = 0; i <= this_len; ++i) {
5126 SV * const * const svp = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
5127 DEBUG_M(Perl_deb(aTHX_ " testing element against pattern...\n"));
5129 if (svp && matcher_matches_sv(matcher, *svp)) {
5131 destroy_matcher(matcher);
5136 destroy_matcher(matcher);
5140 else if (!SvOK(d)) {
5141 /* undef ~~ array */
5142 const SSize_t this_len = av_tindex(MUTABLE_AV(SvRV(e)));
5145 DEBUG_M(Perl_deb(aTHX_ " applying rule Undef-Array\n"));
5146 for (i = 0; i <= this_len; ++i) {
5147 SV * const * const svp = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
5148 DEBUG_M(Perl_deb(aTHX_ " testing for undef element...\n"));
5149 if (!svp || !SvOK(*svp))
5158 const SSize_t this_len = av_tindex(MUTABLE_AV(SvRV(e)));
5160 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Array\n"));
5161 for (i = 0; i <= this_len; ++i) {
5162 SV * const * const svp = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
5169 /* infinite recursion isn't supposed to happen here */
5170 DEBUG_M(Perl_deb(aTHX_ " recursively testing array element...\n"));
5171 (void) do_smartmatch(NULL, NULL, 1);
5173 DEBUG_M(Perl_deb(aTHX_ " recursion finished\n"));
5182 else if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_REGEXP) {
5183 if (!object_on_left && SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
5184 SV *t = d; d = e; e = t;
5185 DEBUG_M(Perl_deb(aTHX_ " applying rule Hash-Regex\n"));
5188 else if (!object_on_left && SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
5189 SV *t = d; d = e; e = t;
5190 DEBUG_M(Perl_deb(aTHX_ " applying rule Array-Regex\n"));
5191 goto sm_regex_array;
5194 PMOP * const matcher = make_matcher((REGEXP*) SvRV(e));
5197 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Regex\n"));
5199 result = matcher_matches_sv(matcher, d);
5201 PUSHs(result ? &PL_sv_yes : &PL_sv_no);
5202 destroy_matcher(matcher);
5207 /* See if there is overload magic on left */
5208 else if (object_on_left && SvAMAGIC(d)) {
5210 DEBUG_M(Perl_deb(aTHX_ " applying rule Object-Any\n"));
5211 DEBUG_M(Perl_deb(aTHX_ " attempting overload\n"));
5214 tmpsv = amagic_call(d, e, smart_amg, AMGf_noright);
5222 DEBUG_M(Perl_deb(aTHX_ " failed to run overload method; falling back...\n"));
5225 else if (!SvOK(d)) {
5226 /* undef ~~ scalar ; we already know that the scalar is SvOK */
5227 DEBUG_M(Perl_deb(aTHX_ " applying rule undef-Any\n"));
5232 if (SvNIOK(e) || (SvPOK(e) && looks_like_number(e) && SvNIOK(d))) {
5233 DEBUG_M(if (SvNIOK(e))
5234 Perl_deb(aTHX_ " applying rule Any-Num\n");
5236 Perl_deb(aTHX_ " applying rule Num-numish\n");
5238 /* numeric comparison */
5241 if (CopHINTS_get(PL_curcop) & HINT_INTEGER)
5242 (void) Perl_pp_i_eq(aTHX);
5244 (void) Perl_pp_eq(aTHX);
5252 /* As a last resort, use string comparison */
5253 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Any\n"));
5256 return Perl_pp_seq(aTHX);
5263 const U8 gimme = GIMME_V;
5265 /* This is essentially an optimization: if the match
5266 fails, we don't want to push a context and then
5267 pop it again right away, so we skip straight
5268 to the op that follows the leavewhen.
5269 RETURNOP calls PUTBACK which restores the stack pointer after the POPs.
5271 if (!(PL_op->op_flags & OPf_SPECIAL) && !SvTRUEx(POPs)) {
5272 if (gimme == G_SCALAR)
5273 PUSHs(&PL_sv_undef);
5274 RETURNOP(cLOGOP->op_other->op_next);
5277 cx = cx_pushblock(CXt_WHEN, gimme, SP, PL_savestack_ix);
5291 assert(CxTYPE(cx) == CXt_WHEN);
5292 gimme = cx->blk_gimme;
5294 cxix = dopoptogivenfor(cxstack_ix);
5296 /* diag_listed_as: Can't "when" outside a topicalizer */
5297 DIE(aTHX_ "Can't \"%s\" outside a topicalizer",
5298 PL_op->op_flags & OPf_SPECIAL ? "default" : "when");
5300 oldsp = PL_stack_base + cx->blk_oldsp;
5301 if (gimme == G_VOID)
5302 PL_stack_sp = oldsp;
5304 leave_adjust_stacks(oldsp, oldsp, gimme, 1);
5306 /* pop the WHEN, BLOCK and anything else before the GIVEN/FOR */
5307 assert(cxix < cxstack_ix);
5310 cx = &cxstack[cxix];
5312 if (CxFOREACH(cx)) {
5313 /* emulate pp_next. Note that any stack(s) cleanup will be
5314 * done by the pp_unstack which op_nextop should point to */
5317 PL_curcop = cx->blk_oldcop;
5318 return cx->blk_loop.my_op->op_nextop;
5322 assert(cx->blk_givwhen.leave_op->op_type == OP_LEAVEGIVEN);
5323 return cx->blk_givwhen.leave_op;
5333 cxix = dopoptowhen(cxstack_ix);
5335 DIE(aTHX_ "Can't \"continue\" outside a when block");
5337 if (cxix < cxstack_ix)
5341 assert(CxTYPE(cx) == CXt_WHEN);
5342 PL_stack_sp = PL_stack_base + cx->blk_oldsp;
5346 nextop = cx->blk_givwhen.leave_op->op_next;
5357 cxix = dopoptogivenfor(cxstack_ix);
5359 DIE(aTHX_ "Can't \"break\" outside a given block");
5361 cx = &cxstack[cxix];
5363 DIE(aTHX_ "Can't \"break\" in a loop topicalizer");
5365 if (cxix < cxstack_ix)
5368 /* Restore the sp at the time we entered the given block */
5370 PL_stack_sp = PL_stack_base + cx->blk_oldsp;
5372 return cx->blk_givwhen.leave_op;
5376 S_doparseform(pTHX_ SV *sv)
5379 char *s = SvPV(sv, len);
5381 char *base = NULL; /* start of current field */
5382 I32 skipspaces = 0; /* number of contiguous spaces seen */
5383 bool noblank = FALSE; /* ~ or ~~ seen on this line */
5384 bool repeat = FALSE; /* ~~ seen on this line */
5385 bool postspace = FALSE; /* a text field may need right padding */
5388 U32 *linepc = NULL; /* position of last FF_LINEMARK */
5390 bool ischop; /* it's a ^ rather than a @ */
5391 bool unchopnum = FALSE; /* at least one @ (i.e. non-chop) num field seen */
5392 int maxops = 12; /* FF_LINEMARK + FF_END + 10 (\0 without preceding \n) */
5396 PERL_ARGS_ASSERT_DOPARSEFORM;
5399 Perl_croak(aTHX_ "Null picture in formline");
5401 if (SvTYPE(sv) >= SVt_PVMG) {
5402 /* This might, of course, still return NULL. */
5403 mg = mg_find(sv, PERL_MAGIC_fm);
5405 sv_upgrade(sv, SVt_PVMG);
5409 /* still the same as previously-compiled string? */
5410 SV *old = mg->mg_obj;
5411 if ( !(!!SvUTF8(old) ^ !!SvUTF8(sv))
5412 && len == SvCUR(old)
5413 && strnEQ(SvPVX(old), s, len)
5415 DEBUG_f(PerlIO_printf(Perl_debug_log,"Re-using compiled format\n"));
5419 DEBUG_f(PerlIO_printf(Perl_debug_log, "Re-compiling format\n"));
5420 Safefree(mg->mg_ptr);
5426 DEBUG_f(PerlIO_printf(Perl_debug_log, "Compiling format\n"));
5427 mg = sv_magicext(sv, NULL, PERL_MAGIC_fm, &PL_vtbl_fm, NULL, 0);
5430 sv_copy = newSVpvn_utf8(s, len, SvUTF8(sv));
5431 s = SvPV(sv_copy, len); /* work on the copy, not the original */
5435 /* estimate the buffer size needed */
5436 for (base = s; s <= send; s++) {
5437 if (*s == '\n' || *s == '@' || *s == '^')
5443 Newx(fops, maxops, U32);
5448 *fpc++ = FF_LINEMARK;
5449 noblank = repeat = FALSE;
5467 case ' ': case '\t':
5483 *fpc++ = FF_LITERAL;
5491 *fpc++ = (U32)skipspaces;
5495 *fpc++ = FF_NEWLINE;
5499 arg = fpc - linepc + 1;
5506 *fpc++ = FF_LINEMARK;
5507 noblank = repeat = FALSE;
5516 ischop = s[-1] == '^';
5522 arg = (s - base) - 1;
5524 *fpc++ = FF_LITERAL;
5530 if (*s == '*') { /* @* or ^* */
5532 *fpc++ = 2; /* skip the @* or ^* */
5534 *fpc++ = FF_LINESNGL;
5537 *fpc++ = FF_LINEGLOB;
5539 else if (*s == '#' || (*s == '.' && s[1] == '#')) { /* @###, ^### */
5540 arg = ischop ? FORM_NUM_BLANK : 0;
5545 const char * const f = ++s;
5548 arg |= FORM_NUM_POINT + (s - f);
5550 *fpc++ = s - base; /* fieldsize for FETCH */
5551 *fpc++ = FF_DECIMAL;
5553 unchopnum |= ! ischop;
5555 else if (*s == '0' && s[1] == '#') { /* Zero padded decimals */
5556 arg = ischop ? FORM_NUM_BLANK : 0;
5558 s++; /* skip the '0' first */
5562 const char * const f = ++s;
5565 arg |= FORM_NUM_POINT + (s - f);
5567 *fpc++ = s - base; /* fieldsize for FETCH */
5568 *fpc++ = FF_0DECIMAL;
5570 unchopnum |= ! ischop;
5572 else { /* text field */
5574 bool ismore = FALSE;
5577 while (*++s == '>') ;
5578 prespace = FF_SPACE;
5580 else if (*s == '|') {
5581 while (*++s == '|') ;
5582 prespace = FF_HALFSPACE;
5587 while (*++s == '<') ;
5590 if (*s == '.' && s[1] == '.' && s[2] == '.') {
5594 *fpc++ = s - base; /* fieldsize for FETCH */
5596 *fpc++ = ischop ? FF_CHECKCHOP : FF_CHECKNL;
5599 *fpc++ = (U32)prespace; /* add SPACE or HALFSPACE */
5613 assert (fpc <= fops + maxops); /* ensure our buffer estimate was valid */
5616 mg->mg_ptr = (char *) fops;
5617 mg->mg_len = arg * sizeof(U32);
5618 mg->mg_obj = sv_copy;
5619 mg->mg_flags |= MGf_REFCOUNTED;
5621 if (unchopnum && repeat)
5622 Perl_die(aTHX_ "Repeated format line will never terminate (~~ and @#)");
5629 S_num_overflow(NV value, I32 fldsize, I32 frcsize)
5631 /* Can value be printed in fldsize chars, using %*.*f ? */
5635 int intsize = fldsize - (value < 0 ? 1 : 0);
5637 if (frcsize & FORM_NUM_POINT)
5639 frcsize &= ~(FORM_NUM_POINT|FORM_NUM_BLANK);
5642 while (intsize--) pwr *= 10.0;
5643 while (frcsize--) eps /= 10.0;
5646 if (value + eps >= pwr)
5649 if (value - eps <= -pwr)
5656 S_run_user_filter(pTHX_ int idx, SV *buf_sv, int maxlen)
5658 SV * const datasv = FILTER_DATA(idx);
5659 const int filter_has_file = IoLINES(datasv);
5660 SV * const filter_state = MUTABLE_SV(IoTOP_GV(datasv));
5661 SV * const filter_sub = MUTABLE_SV(IoBOTTOM_GV(datasv));
5666 char *prune_from = NULL;
5667 bool read_from_cache = FALSE;
5671 PERL_ARGS_ASSERT_RUN_USER_FILTER;
5673 assert(maxlen >= 0);
5676 /* I was having segfault trouble under Linux 2.2.5 after a
5677 parse error occurred. (Had to hack around it with a test
5678 for PL_parser->error_count == 0.) Solaris doesn't segfault --
5679 not sure where the trouble is yet. XXX */
5682 SV *const cache = datasv;
5685 const char *cache_p = SvPV(cache, cache_len);
5689 /* Running in block mode and we have some cached data already.
5691 if (cache_len >= umaxlen) {
5692 /* In fact, so much data we don't even need to call
5697 const char *const first_nl =
5698 (const char *)memchr(cache_p, '\n', cache_len);
5700 take = first_nl + 1 - cache_p;
5704 sv_catpvn(buf_sv, cache_p, take);
5705 sv_chop(cache, cache_p + take);
5706 /* Definitely not EOF */
5710 sv_catsv(buf_sv, cache);
5712 umaxlen -= cache_len;
5715 read_from_cache = TRUE;
5719 /* Filter API says that the filter appends to the contents of the buffer.
5720 Usually the buffer is "", so the details don't matter. But if it's not,
5721 then clearly what it contains is already filtered by this filter, so we
5722 don't want to pass it in a second time.
5723 I'm going to use a mortal in case the upstream filter croaks. */
5724 upstream = ((SvOK(buf_sv) && sv_len(buf_sv)) || SvGMAGICAL(buf_sv))
5725 ? sv_newmortal() : buf_sv;
5726 SvUPGRADE(upstream, SVt_PV);
5728 if (filter_has_file) {
5729 status = FILTER_READ(idx+1, upstream, 0);
5732 if (filter_sub && status >= 0) {
5736 ENTER_with_name("call_filter_sub");
5741 DEFSV_set(upstream);
5745 PUSHs(filter_state);
5748 count = call_sv(filter_sub, G_SCALAR|G_EVAL);
5758 SV * const errsv = ERRSV;
5759 if (SvTRUE_NN(errsv))
5760 err = newSVsv(errsv);
5766 LEAVE_with_name("call_filter_sub");
5769 if (SvGMAGICAL(upstream)) {
5771 if (upstream == buf_sv) mg_free(buf_sv);
5773 if (SvIsCOW(upstream)) sv_force_normal(upstream);
5774 if(!err && SvOK(upstream)) {
5775 got_p = SvPV_nomg(upstream, got_len);
5777 if (got_len > umaxlen) {
5778 prune_from = got_p + umaxlen;
5781 char *const first_nl = (char *)memchr(got_p, '\n', got_len);
5782 if (first_nl && first_nl + 1 < got_p + got_len) {
5783 /* There's a second line here... */
5784 prune_from = first_nl + 1;
5788 if (!err && prune_from) {
5789 /* Oh. Too long. Stuff some in our cache. */
5790 STRLEN cached_len = got_p + got_len - prune_from;
5791 SV *const cache = datasv;
5794 /* Cache should be empty. */
5795 assert(!SvCUR(cache));
5798 sv_setpvn(cache, prune_from, cached_len);
5799 /* If you ask for block mode, you may well split UTF-8 characters.
5800 "If it breaks, you get to keep both parts"
5801 (Your code is broken if you don't put them back together again
5802 before something notices.) */
5803 if (SvUTF8(upstream)) {
5806 if (SvPOK(upstream)) SvCUR_set(upstream, got_len - cached_len);
5808 /* Cannot just use sv_setpvn, as that could free the buffer
5809 before we have a chance to assign it. */
5810 sv_usepvn(upstream, savepvn(got_p, got_len - cached_len),
5811 got_len - cached_len);
5813 /* Can't yet be EOF */
5818 /* If they are at EOF but buf_sv has something in it, then they may never
5819 have touched the SV upstream, so it may be undefined. If we naively
5820 concatenate it then we get a warning about use of uninitialised value.
5822 if (!err && upstream != buf_sv &&
5824 sv_catsv_nomg(buf_sv, upstream);
5826 else if (SvOK(upstream)) (void)SvPV_force_nolen(buf_sv);
5829 IoLINES(datasv) = 0;
5831 SvREFCNT_dec(filter_state);
5832 IoTOP_GV(datasv) = NULL;
5835 SvREFCNT_dec(filter_sub);
5836 IoBOTTOM_GV(datasv) = NULL;
5838 filter_del(S_run_user_filter);
5844 if (status == 0 && read_from_cache) {
5845 /* If we read some data from the cache (and by getting here it implies
5846 that we emptied the cache) then we aren't yet at EOF, and mustn't
5847 report that to our caller. */
5854 * ex: set ts=8 sts=4 sw=4 et: