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
37 #define RUN_PP_CATCHABLY(thispp) \
38 STMT_START { if (CATCH_GET) return docatch(thispp); } STMT_END
40 #define dopoptosub(plop) dopoptosub_at(cxstack, (plop))
46 const PERL_CONTEXT *cx;
49 if (PL_op->op_private & OPpOFFBYONE) {
50 if (!(cx = caller_cx(1,NULL))) RETPUSHUNDEF;
53 cxix = dopoptosub(cxstack_ix);
59 switch (cx->blk_gimme) {
78 PMOP *pm = (PMOP*)cLOGOP->op_other;
83 const regexp_engine *eng;
84 bool is_bare_re= FALSE;
86 if (PL_op->op_flags & OPf_STACKED) {
96 /* prevent recompiling under /o and ithreads. */
97 #if defined(USE_ITHREADS)
98 if (pm->op_pmflags & PMf_KEEP && PM_GETRE(pm)) {
105 assert (re != (REGEXP*) &PL_sv_undef);
106 eng = re ? RX_ENGINE(re) : current_re_engine();
108 new_re = (eng->op_comp
110 : &Perl_re_op_compile
111 )(aTHX_ args, nargs, pm->op_code_list, eng, re,
113 (pm->op_pmflags & RXf_PMf_FLAGCOPYMASK),
115 (PL_op->op_flags & OPf_SPECIAL ? PMf_USE_RE_EVAL : 0));
117 if (pm->op_pmflags & PMf_HAS_CV)
118 ReANY(new_re)->qr_anoncv
119 = (CV*) SvREFCNT_inc(PAD_SV(PL_op->op_targ));
123 /* The match's LHS's get-magic might need to access this op's regexp
124 (e.g. $' =~ /$re/ while foo; see bug 70764). So we must call
125 get-magic now before we replace the regexp. Hopefully this hack can
126 be replaced with the approach described at
127 http://www.nntp.perl.org/group/perl.perl5.porters/2007/03/msg122415.html
129 if (pm->op_type == OP_MATCH) {
131 const bool was_tainted = TAINT_get;
132 if (pm->op_flags & OPf_STACKED)
134 else if (pm->op_targ)
135 lhs = PAD_SV(pm->op_targ);
138 /* Restore the previous value of PL_tainted (which may have been
139 modified by get-magic), to avoid incorrectly setting the
140 RXf_TAINTED flag with RX_TAINT_on further down. */
141 TAINT_set(was_tainted);
142 #ifdef NO_TAINT_SUPPORT
143 PERL_UNUSED_VAR(was_tainted);
146 tmp = reg_temp_copy(NULL, new_re);
147 ReREFCNT_dec(new_re);
153 PM_SETRE(pm, new_re);
157 assert(TAINTING_get || !TAINT_get);
159 SvTAINTED_on((SV*)new_re);
163 /* handle the empty pattern */
164 if (!RX_PRELEN(PM_GETRE(pm)) && PL_curpm) {
165 if (PL_curpm == PL_reg_curpm) {
166 if (PL_curpm_under && PL_curpm_under == PL_reg_curpm) {
167 Perl_croak(aTHX_ "Infinite recursion via empty pattern");
172 #if !defined(USE_ITHREADS)
173 /* can't change the optree at runtime either */
174 /* PMf_KEEP is handled differently under threads to avoid these problems */
175 if (pm->op_pmflags & PMf_KEEP) {
176 cLOGOP->op_first->op_next = PL_op->op_next;
188 PERL_CONTEXT *cx = CX_CUR();
189 PMOP * const pm = (PMOP*) cLOGOP->op_other;
190 SV * const dstr = cx->sb_dstr;
193 char *orig = cx->sb_orig;
194 REGEXP * const rx = cx->sb_rx;
196 REGEXP *old = PM_GETRE(pm);
203 PM_SETRE(pm,ReREFCNT_inc(rx));
206 rxres_restore(&cx->sb_rxres, rx);
208 if (cx->sb_iters++) {
209 const SSize_t saviters = cx->sb_iters;
210 if (cx->sb_iters > cx->sb_maxiters)
211 DIE(aTHX_ "Substitution loop");
213 SvGETMAGIC(TOPs); /* possibly clear taint on $1 etc: #67962 */
215 /* See "how taint works" above pp_subst() */
216 sv_catsv_nomg(dstr, POPs);
217 if (UNLIKELY(TAINT_get))
218 cx->sb_rxtainted |= SUBST_TAINT_REPL;
219 if (CxONCE(cx) || s < orig ||
220 !CALLREGEXEC(rx, s, cx->sb_strend, orig,
221 (s == m), cx->sb_targ, NULL,
222 (REXEC_IGNOREPOS|REXEC_NOT_FIRST|REXEC_FAIL_ON_UNDERFLOW)))
224 SV *targ = cx->sb_targ;
226 assert(cx->sb_strend >= s);
227 if(cx->sb_strend > s) {
228 if (DO_UTF8(dstr) && !SvUTF8(targ))
229 sv_catpvn_nomg_utf8_upgrade(dstr, s, cx->sb_strend - s, nsv);
231 sv_catpvn_nomg(dstr, s, cx->sb_strend - s);
233 if (RX_MATCH_TAINTED(rx)) /* run time pattern taint, eg locale */
234 cx->sb_rxtainted |= SUBST_TAINT_PAT;
236 if (pm->op_pmflags & PMf_NONDESTRUCT) {
238 /* From here on down we're using the copy, and leaving the
239 original untouched. */
243 SV_CHECK_THINKFIRST_COW_DROP(targ);
244 if (isGV(targ)) Perl_croak_no_modify();
246 SvPV_set(targ, SvPVX(dstr));
247 SvCUR_set(targ, SvCUR(dstr));
248 SvLEN_set(targ, SvLEN(dstr));
251 SvPV_set(dstr, NULL);
254 mPUSHi(saviters - 1);
256 (void)SvPOK_only_UTF8(targ);
259 /* update the taint state of various various variables in
260 * preparation for final exit.
261 * See "how taint works" above pp_subst() */
263 if ((cx->sb_rxtainted & SUBST_TAINT_PAT) ||
264 ((cx->sb_rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
265 == (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
267 (RX_MATCH_TAINTED_on(rx)); /* taint $1 et al */
269 if (!(cx->sb_rxtainted & SUBST_TAINT_BOOLRET)
270 && (cx->sb_rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_PAT))
272 SvTAINTED_on(TOPs); /* taint return value */
273 /* needed for mg_set below */
275 cBOOL(cx->sb_rxtainted &
276 (SUBST_TAINT_STR|SUBST_TAINT_PAT|SUBST_TAINT_REPL))
280 /* PL_tainted must be correctly set for this mg_set */
289 RETURNOP(pm->op_next);
290 NOT_REACHED; /* NOTREACHED */
292 cx->sb_iters = saviters;
294 if (RX_MATCH_COPIED(rx) && RX_SUBBEG(rx) != orig) {
297 assert(!RX_SUBOFFSET(rx));
298 cx->sb_orig = orig = RX_SUBBEG(rx);
300 cx->sb_strend = s + (cx->sb_strend - m);
302 cx->sb_m = m = RX_OFFS(rx)[0].start + orig;
304 if (DO_UTF8(dstr) && !SvUTF8(cx->sb_targ))
305 sv_catpvn_nomg_utf8_upgrade(dstr, s, m - s, nsv);
307 sv_catpvn_nomg(dstr, s, m-s);
309 cx->sb_s = RX_OFFS(rx)[0].end + orig;
310 { /* Update the pos() information. */
312 = (pm->op_pmflags & PMf_NONDESTRUCT) ? cx->sb_dstr : cx->sb_targ;
315 /* the string being matched against may no longer be a string,
316 * e.g. $_=0; s/.../$_++/ge */
319 SvPV_force_nomg_nolen(sv);
321 if (!(mg = mg_find_mglob(sv))) {
322 mg = sv_magicext_mglob(sv);
324 MgBYTEPOS_set(mg, sv, SvPVX(sv), m - orig);
327 (void)ReREFCNT_inc(rx);
328 /* update the taint state of various various variables in preparation
329 * for calling the code block.
330 * See "how taint works" above pp_subst() */
332 if (RX_MATCH_TAINTED(rx)) /* run time pattern taint, eg locale */
333 cx->sb_rxtainted |= SUBST_TAINT_PAT;
335 if ((cx->sb_rxtainted & SUBST_TAINT_PAT) ||
336 ((cx->sb_rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
337 == (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
339 (RX_MATCH_TAINTED_on(rx)); /* taint $1 et al */
341 if (cx->sb_iters > 1 && (cx->sb_rxtainted &
342 (SUBST_TAINT_STR|SUBST_TAINT_PAT|SUBST_TAINT_REPL)))
343 SvTAINTED_on((pm->op_pmflags & PMf_NONDESTRUCT)
344 ? cx->sb_dstr : cx->sb_targ);
347 rxres_save(&cx->sb_rxres, rx);
349 RETURNOP(pm->op_pmstashstartu.op_pmreplstart);
353 Perl_rxres_save(pTHX_ void **rsp, REGEXP *rx)
358 PERL_ARGS_ASSERT_RXRES_SAVE;
361 if (!p || p[1] < RX_NPARENS(rx)) {
363 i = 7 + (RX_NPARENS(rx)+1) * 2;
365 i = 6 + (RX_NPARENS(rx)+1) * 2;
374 /* what (if anything) to free on croak */
375 *p++ = PTR2UV(RX_MATCH_COPIED(rx) ? RX_SUBBEG(rx) : NULL);
376 RX_MATCH_COPIED_off(rx);
377 *p++ = RX_NPARENS(rx);
380 *p++ = PTR2UV(RX_SAVED_COPY(rx));
381 RX_SAVED_COPY(rx) = NULL;
384 *p++ = PTR2UV(RX_SUBBEG(rx));
385 *p++ = (UV)RX_SUBLEN(rx);
386 *p++ = (UV)RX_SUBOFFSET(rx);
387 *p++ = (UV)RX_SUBCOFFSET(rx);
388 for (i = 0; i <= RX_NPARENS(rx); ++i) {
389 *p++ = (UV)RX_OFFS(rx)[i].start;
390 *p++ = (UV)RX_OFFS(rx)[i].end;
395 S_rxres_restore(pTHX_ void **rsp, REGEXP *rx)
400 PERL_ARGS_ASSERT_RXRES_RESTORE;
403 RX_MATCH_COPY_FREE(rx);
404 RX_MATCH_COPIED_set(rx, *p);
406 RX_NPARENS(rx) = *p++;
409 if (RX_SAVED_COPY(rx))
410 SvREFCNT_dec (RX_SAVED_COPY(rx));
411 RX_SAVED_COPY(rx) = INT2PTR(SV*,*p);
415 RX_SUBBEG(rx) = INT2PTR(char*,*p++);
416 RX_SUBLEN(rx) = (I32)(*p++);
417 RX_SUBOFFSET(rx) = (I32)*p++;
418 RX_SUBCOFFSET(rx) = (I32)*p++;
419 for (i = 0; i <= RX_NPARENS(rx); ++i) {
420 RX_OFFS(rx)[i].start = (I32)(*p++);
421 RX_OFFS(rx)[i].end = (I32)(*p++);
426 S_rxres_free(pTHX_ void **rsp)
428 UV * const p = (UV*)*rsp;
430 PERL_ARGS_ASSERT_RXRES_FREE;
434 void *tmp = INT2PTR(char*,*p);
437 U32 i = 9 + p[1] * 2;
439 U32 i = 8 + p[1] * 2;
444 SvREFCNT_dec (INT2PTR(SV*,p[2]));
447 PoisonFree(p, i, sizeof(UV));
456 #define FORM_NUM_BLANK (1<<30)
457 #define FORM_NUM_POINT (1<<29)
461 dSP; dMARK; dORIGMARK;
462 SV * const tmpForm = *++MARK;
463 SV *formsv; /* contains text of original format */
464 U32 *fpc; /* format ops program counter */
465 char *t; /* current append position in target string */
466 const char *f; /* current position in format string */
468 SV *sv = NULL; /* current item */
469 const char *item = NULL;/* string value of current item */
470 I32 itemsize = 0; /* length (chars) of item, possibly truncated */
471 I32 itembytes = 0; /* as itemsize, but length in bytes */
472 I32 fieldsize = 0; /* width of current field */
473 I32 lines = 0; /* number of lines that have been output */
474 bool chopspace = (strchr(PL_chopset, ' ') != NULL); /* does $: have space */
475 const char *chophere = NULL; /* where to chop current item */
476 STRLEN linemark = 0; /* pos of start of line in output */
478 bool gotsome = FALSE; /* seen at least one non-blank item on this line */
479 STRLEN len; /* length of current sv */
480 STRLEN linemax; /* estimate of output size in bytes */
481 bool item_is_utf8 = FALSE;
482 bool targ_is_utf8 = FALSE;
485 U8 *source; /* source of bytes to append */
486 STRLEN to_copy; /* how may bytes to append */
487 char trans; /* what chars to translate */
488 bool copied_form = FALSE; /* have we duplicated the form? */
490 mg = doparseform(tmpForm);
492 fpc = (U32*)mg->mg_ptr;
493 /* the actual string the format was compiled from.
494 * with overload etc, this may not match tmpForm */
498 SvPV_force(PL_formtarget, len);
499 if (SvTAINTED(tmpForm) || SvTAINTED(formsv))
500 SvTAINTED_on(PL_formtarget);
501 if (DO_UTF8(PL_formtarget))
503 /* this is an initial estimate of how much output buffer space
504 * to allocate. It may be exceeded later */
505 linemax = (SvCUR(formsv) * (IN_BYTES ? 1 : 3) + 1);
506 t = SvGROW(PL_formtarget, len + linemax + 1);
507 /* XXX from now onwards, SvCUR(PL_formtarget) is invalid */
509 f = SvPV_const(formsv, len);
513 const char *name = "???";
516 case FF_LITERAL: arg = fpc[1]; name = "LITERAL"; break;
517 case FF_BLANK: arg = fpc[1]; name = "BLANK"; break;
518 case FF_SKIP: arg = fpc[1]; name = "SKIP"; break;
519 case FF_FETCH: arg = fpc[1]; name = "FETCH"; break;
520 case FF_DECIMAL: arg = fpc[1]; name = "DECIMAL"; break;
522 case FF_CHECKNL: name = "CHECKNL"; break;
523 case FF_CHECKCHOP: name = "CHECKCHOP"; break;
524 case FF_SPACE: name = "SPACE"; break;
525 case FF_HALFSPACE: name = "HALFSPACE"; break;
526 case FF_ITEM: name = "ITEM"; break;
527 case FF_CHOP: name = "CHOP"; break;
528 case FF_LINEGLOB: name = "LINEGLOB"; break;
529 case FF_NEWLINE: name = "NEWLINE"; break;
530 case FF_MORE: name = "MORE"; break;
531 case FF_LINEMARK: name = "LINEMARK"; break;
532 case FF_END: name = "END"; break;
533 case FF_0DECIMAL: name = "0DECIMAL"; break;
534 case FF_LINESNGL: name = "LINESNGL"; break;
537 PerlIO_printf(Perl_debug_log, "%-16s%ld\n", name, (long) arg);
539 PerlIO_printf(Perl_debug_log, "%-16s\n", name);
542 case FF_LINEMARK: /* start (or end) of a line */
543 linemark = t - SvPVX(PL_formtarget);
548 case FF_LITERAL: /* append <arg> literal chars */
553 item_is_utf8 = targ_is_utf8 ? !!DO_UTF8(formsv) : !!SvUTF8(formsv);
556 case FF_SKIP: /* skip <arg> chars in format */
560 case FF_FETCH: /* get next item and set field size to <arg> */
569 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "Not enough format arguments");
572 SvTAINTED_on(PL_formtarget);
575 case FF_CHECKNL: /* find max len of item (up to \n) that fits field */
577 const char *s = item = SvPV_const(sv, len);
578 const char *send = s + len;
581 item_is_utf8 = DO_UTF8(sv);
593 if (itemsize == fieldsize)
596 itembytes = s - item;
601 case FF_CHECKCHOP: /* like CHECKNL, but up to highest split point */
603 const char *s = item = SvPV_const(sv, len);
604 const char *send = s + len;
608 item_is_utf8 = DO_UTF8(sv);
610 /* look for a legal split position */
618 /* provisional split point */
622 /* we delay testing fieldsize until after we've
623 * processed the possible split char directly
624 * following the last field char; so if fieldsize=3
625 * and item="a b cdef", we consume "a b", not "a".
626 * Ditto further down.
628 if (size == fieldsize)
632 if (strchr(PL_chopset, *s)) {
633 /* provisional split point */
634 /* for a non-space split char, we include
635 * the split char; hence the '+1' */
639 if (size == fieldsize)
651 if (!chophere || s == send) {
655 itembytes = chophere - item;
660 case FF_SPACE: /* append padding space (diff of field, item size) */
661 arg = fieldsize - itemsize;
669 case FF_HALFSPACE: /* like FF_SPACE, but only append half as many */
670 arg = fieldsize - itemsize;
679 case FF_ITEM: /* append a text item, while blanking ctrl chars */
685 case FF_CHOP: /* (for ^*) chop the current item */
686 if (sv != &PL_sv_no) {
687 const char *s = chophere;
689 ((sv == tmpForm || SvSMAGICAL(sv))
690 || (SvGMAGICAL(tmpForm) && !sv_only_taint_gmagic(tmpForm))) ) {
691 /* sv and tmpForm are either the same SV, or magic might allow modification
692 of tmpForm when sv is modified, so copy */
693 SV *newformsv = sv_mortalcopy(formsv);
696 f = SvPV_nolen(newformsv) + (f - SvPV_nolen(formsv));
697 Newx(new_compiled, mg->mg_len / sizeof(U32), U32);
698 memcpy(new_compiled, mg->mg_ptr, mg->mg_len);
699 SAVEFREEPV(new_compiled);
700 fpc = new_compiled + (fpc - (U32*)mg->mg_ptr);
712 /* tied, overloaded or similar strangeness.
713 * Do it the hard way */
714 sv_setpvn(sv, s, len - (s-item));
720 case FF_LINESNGL: /* process ^* */
724 case FF_LINEGLOB: /* process @* */
726 const bool oneline = fpc[-1] == FF_LINESNGL;
727 const char *s = item = SvPV_const(sv, len);
728 const char *const send = s + len;
730 item_is_utf8 = DO_UTF8(sv);
741 to_copy = s - item - 1;
755 /* append to_copy bytes from source to PL_formstring.
756 * item_is_utf8 implies source is utf8.
757 * if trans, translate certain characters during the copy */
762 SvCUR_set(PL_formtarget,
763 t - SvPVX_const(PL_formtarget));
765 if (targ_is_utf8 && !item_is_utf8) {
766 source = tmp = bytes_to_utf8(source, &to_copy);
769 if (item_is_utf8 && !targ_is_utf8) {
771 /* Upgrade targ to UTF8, and then we reduce it to
772 a problem we have a simple solution for.
773 Don't need get magic. */
774 sv_utf8_upgrade_nomg(PL_formtarget);
776 /* re-calculate linemark */
777 s = (U8*)SvPVX(PL_formtarget);
778 /* the bytes we initially allocated to append the
779 * whole line may have been gobbled up during the
780 * upgrade, so allocate a whole new line's worth
784 s += UTF8_SAFE_SKIP(s,
785 (U8 *) SvEND(PL_formtarget));
786 linemark = s - (U8*)SvPVX(PL_formtarget);
788 /* Easy. They agree. */
789 assert (item_is_utf8 == targ_is_utf8);
792 /* @* and ^* are the only things that can exceed
793 * the linemax, so grow by the output size, plus
794 * a whole new form's worth in case of any further
796 grow = linemax + to_copy;
798 SvGROW(PL_formtarget, SvCUR(PL_formtarget) + grow + 1);
799 t = SvPVX(PL_formtarget) + SvCUR(PL_formtarget);
801 Copy(source, t, to_copy, char);
803 /* blank out ~ or control chars, depending on trans.
804 * works on bytes not chars, so relies on not
805 * matching utf8 continuation bytes */
807 U8 *send = s + to_copy;
810 if (trans == '~' ? (ch == '~') : isCNTRL(ch))
817 SvCUR_set(PL_formtarget, SvCUR(PL_formtarget) + to_copy);
823 case FF_0DECIMAL: /* like FF_DECIMAL but for 0### */
826 ((arg & FORM_NUM_POINT) ? "%#0*.*" NVff : "%0*.*" NVff);
829 case FF_DECIMAL: /* do @##, ^##, where <arg>=(precision|flags) */
832 ((arg & FORM_NUM_POINT) ? "%#*.*" NVff : "%*.*" NVff);
834 /* If the field is marked with ^ and the value is undefined,
836 if ((arg & FORM_NUM_BLANK) && !SvOK(sv)) {
844 /* overflow evidence */
845 if (num_overflow(value, fieldsize, arg)) {
851 /* Formats aren't yet marked for locales, so assume "yes". */
853 Size_t max = SvLEN(PL_formtarget) - (t - SvPVX(PL_formtarget));
855 DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
856 STORE_LC_NUMERIC_SET_TO_NEEDED();
857 arg &= ~(FORM_NUM_POINT|FORM_NUM_BLANK);
860 const char* qfmt = quadmath_format_single(fmt);
863 Perl_croak_nocontext("panic: quadmath invalid format \"%s\"", fmt);
864 len = quadmath_snprintf(t, max, qfmt, (int) fieldsize, (int) arg, value);
866 Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", qfmt);
871 /* we generate fmt ourselves so it is safe */
872 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
873 len = my_snprintf(t, max, fmt, (int) fieldsize, (int) arg, value);
874 GCC_DIAG_RESTORE_STMT;
876 PERL_MY_SNPRINTF_POST_GUARD(len, max);
877 RESTORE_LC_NUMERIC();
882 case FF_NEWLINE: /* delete trailing spaces, then append \n */
884 while (t-- > (SvPVX(PL_formtarget) + linemark) && *t == ' ') ;
889 case FF_BLANK: /* for arg==0: do '~'; for arg>0 : do '~~' */
892 if (arg) { /* repeat until fields exhausted? */
898 t = SvPVX(PL_formtarget) + linemark;
903 case FF_MORE: /* replace long end of string with '...' */
905 const char *s = chophere;
906 const char *send = item + len;
908 while (isSPACE(*s) && (s < send))
913 arg = fieldsize - itemsize;
920 if (strBEGINs(s1," ")) {
921 while (s1 > SvPVX_const(PL_formtarget) && isSPACE(s1[-1]))
931 case FF_END: /* tidy up, then return */
933 assert(t < SvPVX_const(PL_formtarget) + SvLEN(PL_formtarget));
935 SvCUR_set(PL_formtarget, t - SvPVX_const(PL_formtarget));
937 SvUTF8_on(PL_formtarget);
938 FmLINES(PL_formtarget) += lines;
940 if (fpc[-1] == FF_BLANK)
941 RETURNOP(cLISTOP->op_first);
948 /* also used for: pp_mapstart() */
954 if (PL_stack_base + TOPMARK == SP) {
956 if (GIMME_V == G_SCALAR)
958 RETURNOP(PL_op->op_next->op_next);
960 PL_stack_sp = PL_stack_base + TOPMARK + 1;
961 Perl_pp_pushmark(aTHX); /* push dst */
962 Perl_pp_pushmark(aTHX); /* push src */
963 ENTER_with_name("grep"); /* enter outer scope */
967 ENTER_with_name("grep_item"); /* enter inner scope */
970 src = PL_stack_base[TOPMARK];
972 src = PL_stack_base[TOPMARK] = sv_mortalcopy(src);
979 if (PL_op->op_type == OP_MAPSTART)
980 Perl_pp_pushmark(aTHX); /* push top */
981 return ((LOGOP*)PL_op->op_next)->op_other;
987 const U8 gimme = GIMME_V;
988 I32 items = (SP - PL_stack_base) - TOPMARK; /* how many new items */
994 /* first, move source pointer to the next item in the source list */
995 ++PL_markstack_ptr[-1];
997 /* if there are new items, push them into the destination list */
998 if (items && gimme != G_VOID) {
999 /* might need to make room back there first */
1000 if (items > PL_markstack_ptr[-1] - PL_markstack_ptr[-2]) {
1001 /* XXX this implementation is very pessimal because the stack
1002 * is repeatedly extended for every set of items. Is possible
1003 * to do this without any stack extension or copying at all
1004 * by maintaining a separate list over which the map iterates
1005 * (like foreach does). --gsar */
1007 /* everything in the stack after the destination list moves
1008 * towards the end the stack by the amount of room needed */
1009 shift = items - (PL_markstack_ptr[-1] - PL_markstack_ptr[-2]);
1011 /* items to shift up (accounting for the moved source pointer) */
1012 count = (SP - PL_stack_base) - (PL_markstack_ptr[-1] - 1);
1014 /* This optimization is by Ben Tilly and it does
1015 * things differently from what Sarathy (gsar)
1016 * is describing. The downside of this optimization is
1017 * that leaves "holes" (uninitialized and hopefully unused areas)
1018 * to the Perl stack, but on the other hand this
1019 * shouldn't be a problem. If Sarathy's idea gets
1020 * implemented, this optimization should become
1021 * irrelevant. --jhi */
1023 shift = count; /* Avoid shifting too often --Ben Tilly */
1027 dst = (SP += shift);
1028 PL_markstack_ptr[-1] += shift;
1029 *PL_markstack_ptr += shift;
1033 /* copy the new items down to the destination list */
1034 dst = PL_stack_base + (PL_markstack_ptr[-2] += items) - 1;
1035 if (gimme == G_ARRAY) {
1036 /* add returned items to the collection (making mortal copies
1037 * if necessary), then clear the current temps stack frame
1038 * *except* for those items. We do this splicing the items
1039 * into the start of the tmps frame (so some items may be on
1040 * the tmps stack twice), then moving PL_tmps_floor above
1041 * them, then freeing the frame. That way, the only tmps that
1042 * accumulate over iterations are the return values for map.
1043 * We have to do to this way so that everything gets correctly
1044 * freed if we die during the map.
1048 /* make space for the slice */
1049 EXTEND_MORTAL(items);
1050 tmpsbase = PL_tmps_floor + 1;
1051 Move(PL_tmps_stack + tmpsbase,
1052 PL_tmps_stack + tmpsbase + items,
1053 PL_tmps_ix - PL_tmps_floor,
1055 PL_tmps_ix += items;
1060 sv = sv_mortalcopy(sv);
1062 PL_tmps_stack[tmpsbase++] = SvREFCNT_inc_simple(sv);
1064 /* clear the stack frame except for the items */
1065 PL_tmps_floor += items;
1067 /* FREETMPS may have cleared the TEMP flag on some of the items */
1070 SvTEMP_on(PL_tmps_stack[--tmpsbase]);
1073 /* scalar context: we don't care about which values map returns
1074 * (we use undef here). And so we certainly don't want to do mortal
1075 * copies of meaningless values. */
1076 while (items-- > 0) {
1078 *dst-- = &PL_sv_undef;
1086 LEAVE_with_name("grep_item"); /* exit inner scope */
1089 if (PL_markstack_ptr[-1] > TOPMARK) {
1091 (void)POPMARK; /* pop top */
1092 LEAVE_with_name("grep"); /* exit outer scope */
1093 (void)POPMARK; /* pop src */
1094 items = --*PL_markstack_ptr - PL_markstack_ptr[-1];
1095 (void)POPMARK; /* pop dst */
1096 SP = PL_stack_base + POPMARK; /* pop original mark */
1097 if (gimme == G_SCALAR) {
1101 else if (gimme == G_ARRAY)
1108 ENTER_with_name("grep_item"); /* enter inner scope */
1111 /* set $_ to the new source item */
1112 src = PL_stack_base[PL_markstack_ptr[-1]];
1113 if (SvPADTMP(src)) {
1114 src = sv_mortalcopy(src);
1119 RETURNOP(cLOGOP->op_other);
1128 if (GIMME_V == G_ARRAY)
1131 if (SvTRUE_NN(targ))
1132 return cLOGOP->op_other;
1141 if (GIMME_V == G_ARRAY) {
1142 RETURNOP(((LOGOP*)cUNOP->op_first)->op_other);
1146 SV * const targ = PAD_SV(PL_op->op_targ);
1149 if (PL_op->op_private & OPpFLIP_LINENUM) {
1150 if (GvIO(PL_last_in_gv)) {
1151 flip = SvIV(sv) == (IV)IoLINES(GvIOp(PL_last_in_gv));
1154 GV * const gv = gv_fetchpvs(".", GV_ADD|GV_NOTQUAL, SVt_PV);
1156 flip = SvIV(sv) == SvIV(GvSV(gv));
1159 flip = SvTRUE_NN(sv);
1162 sv_setiv(PAD_SV(cUNOP->op_first->op_targ), 1);
1163 if (PL_op->op_flags & OPf_SPECIAL) {
1171 RETURNOP(((LOGOP*)cUNOP->op_first)->op_other);
1180 /* This code tries to decide if "$left .. $right" should use the
1181 magical string increment, or if the range is numeric. Initially,
1182 an exception was made for *any* string beginning with "0" (see
1183 [#18165], AMS 20021031), but now that is only applied when the
1184 string's length is also >1 - see the rules now documented in
1187 #define RANGE_IS_NUMERIC(left,right) ( \
1188 SvNIOKp(left) || (SvOK(left) && !SvPOKp(left)) || \
1189 SvNIOKp(right) || (SvOK(right) && !SvPOKp(right)) || \
1190 (((!SvOK(left) && SvOK(right)) || ((!SvOK(left) || \
1191 looks_like_number(left)) && SvPOKp(left) \
1192 && !(*SvPVX_const(left) == '0' && SvCUR(left)>1 ) )) \
1193 && (!SvOK(right) || looks_like_number(right))))
1199 if (GIMME_V == G_ARRAY) {
1205 if (RANGE_IS_NUMERIC(left,right)) {
1207 if ((SvOK(left) && !SvIOK(left) && SvNV_nomg(left) < IV_MIN) ||
1208 (SvOK(right) && (SvIOK(right)
1209 ? SvIsUV(right) && SvUV(right) > IV_MAX
1210 : SvNV_nomg(right) > IV_MAX)))
1211 DIE(aTHX_ "Range iterator outside integer range");
1212 i = SvIV_nomg(left);
1213 j = SvIV_nomg(right);
1215 /* Dance carefully around signed max. */
1216 bool overflow = (i <= 0 && j > SSize_t_MAX + i - 1);
1219 /* The wraparound of signed integers is undefined
1220 * behavior, but here we aim for count >=1, and
1221 * negative count is just wrong. */
1223 #if IVSIZE > Size_t_size
1230 Perl_croak(aTHX_ "Out of memory during list extend");
1237 SV * const sv = sv_2mortal(newSViv(i));
1239 if (n) /* avoid incrementing above IV_MAX */
1245 const char * const lpv = SvPV_nomg_const(left, llen);
1246 const char * const tmps = SvPV_nomg_const(right, len);
1248 SV *sv = newSVpvn_flags(lpv, llen, SvUTF8(left)|SVs_TEMP);
1249 if (DO_UTF8(right) && IN_UNI_8_BIT)
1250 len = sv_len_utf8_nomg(right);
1251 while (!SvNIOKp(sv) && SvCUR(sv) <= len) {
1253 if (strEQ(SvPVX_const(sv),tmps))
1255 sv = sv_2mortal(newSVsv(sv));
1262 SV * const targ = PAD_SV(cUNOP->op_first->op_targ);
1266 if (PL_op->op_private & OPpFLIP_LINENUM) {
1267 if (GvIO(PL_last_in_gv)) {
1268 flop = SvIV(sv) == (IV)IoLINES(GvIOp(PL_last_in_gv));
1271 GV * const gv = gv_fetchpvs(".", GV_ADD|GV_NOTQUAL, SVt_PV);
1272 if (gv && GvSV(gv)) flop = SvIV(sv) == SvIV(GvSV(gv));
1276 flop = SvTRUE_NN(sv);
1280 sv_setiv(PAD_SV(((UNOP*)cUNOP->op_first)->op_first->op_targ), 0);
1281 sv_catpvs(targ, "E0");
1291 static const char * const context_name[] = {
1293 NULL, /* CXt_WHEN never actually needs "block" */
1294 NULL, /* CXt_BLOCK never actually needs "block" */
1295 NULL, /* CXt_GIVEN never actually needs "block" */
1296 NULL, /* CXt_LOOP_PLAIN never actually needs "loop" */
1297 NULL, /* CXt_LOOP_LAZYIV never actually needs "loop" */
1298 NULL, /* CXt_LOOP_LAZYSV never actually needs "loop" */
1299 NULL, /* CXt_LOOP_LIST never actually needs "loop" */
1300 NULL, /* CXt_LOOP_ARY never actually needs "loop" */
1308 S_dopoptolabel(pTHX_ const char *label, STRLEN len, U32 flags)
1312 PERL_ARGS_ASSERT_DOPOPTOLABEL;
1314 for (i = cxstack_ix; i >= 0; i--) {
1315 const PERL_CONTEXT * const cx = &cxstack[i];
1316 switch (CxTYPE(cx)) {
1322 /* diag_listed_as: Exiting subroutine via %s */
1323 Perl_ck_warner(aTHX_ packWARN(WARN_EXITING), "Exiting %s via %s",
1324 context_name[CxTYPE(cx)], OP_NAME(PL_op));
1325 if (CxTYPE(cx) == CXt_NULL) /* sort BLOCK */
1328 case CXt_LOOP_PLAIN:
1329 case CXt_LOOP_LAZYIV:
1330 case CXt_LOOP_LAZYSV:
1334 STRLEN cx_label_len = 0;
1335 U32 cx_label_flags = 0;
1336 const char *cx_label = CxLABEL_len_flags(cx, &cx_label_len, &cx_label_flags);
1338 ( (cx_label_flags & SVf_UTF8) != (flags & SVf_UTF8) ) ?
1341 (const U8*)cx_label, cx_label_len,
1342 (const U8*)label, len) == 0)
1344 (const U8*)label, len,
1345 (const U8*)cx_label, cx_label_len) == 0)
1346 : (len == cx_label_len && ((cx_label == label)
1347 || memEQ(cx_label, label, len))) )) {
1348 DEBUG_l(Perl_deb(aTHX_ "(poptolabel(): skipping label at cx=%ld %s)\n",
1349 (long)i, cx_label));
1352 DEBUG_l( Perl_deb(aTHX_ "(poptolabel(): found label at cx=%ld %s)\n", (long)i, label));
1363 Perl_dowantarray(pTHX)
1365 const U8 gimme = block_gimme();
1366 return (gimme == G_VOID) ? G_SCALAR : gimme;
1370 Perl_block_gimme(pTHX)
1372 const I32 cxix = dopoptosub(cxstack_ix);
1377 gimme = (cxstack[cxix].blk_gimme & G_WANT);
1379 Perl_croak(aTHX_ "panic: bad gimme: %d\n", gimme);
1385 Perl_is_lvalue_sub(pTHX)
1387 const I32 cxix = dopoptosub(cxstack_ix);
1388 assert(cxix >= 0); /* We should only be called from inside subs */
1390 if (CxLVAL(cxstack + cxix) && CvLVALUE(cxstack[cxix].blk_sub.cv))
1391 return CxLVAL(cxstack + cxix);
1396 /* only used by cx_pushsub() */
1398 Perl_was_lvalue_sub(pTHX)
1400 const I32 cxix = dopoptosub(cxstack_ix-1);
1401 assert(cxix >= 0); /* We should only be called from inside subs */
1403 if (CxLVAL(cxstack + cxix) && CvLVALUE(cxstack[cxix].blk_sub.cv))
1404 return CxLVAL(cxstack + cxix);
1410 S_dopoptosub_at(pTHX_ const PERL_CONTEXT *cxstk, I32 startingblock)
1414 PERL_ARGS_ASSERT_DOPOPTOSUB_AT;
1416 PERL_UNUSED_CONTEXT;
1419 for (i = startingblock; i >= 0; i--) {
1420 const PERL_CONTEXT * const cx = &cxstk[i];
1421 switch (CxTYPE(cx)) {
1425 /* in sub foo { /(?{...})/ }, foo ends up on the CX stack
1426 * twice; the first for the normal foo() call, and the second
1427 * for a faked up re-entry into the sub to execute the
1428 * code block. Hide this faked entry from the world. */
1429 if (cx->cx_type & CXp_SUB_RE_FAKE)
1434 DEBUG_l( Perl_deb(aTHX_ "(dopoptosub_at(): found sub at cx=%ld)\n", (long)i));
1442 S_dopoptoeval(pTHX_ I32 startingblock)
1445 for (i = startingblock; i >= 0; i--) {
1446 const PERL_CONTEXT *cx = &cxstack[i];
1447 switch (CxTYPE(cx)) {
1451 DEBUG_l( Perl_deb(aTHX_ "(dopoptoeval(): found eval at cx=%ld)\n", (long)i));
1459 S_dopoptoloop(pTHX_ I32 startingblock)
1462 for (i = startingblock; i >= 0; i--) {
1463 const PERL_CONTEXT * const cx = &cxstack[i];
1464 switch (CxTYPE(cx)) {
1470 /* diag_listed_as: Exiting subroutine via %s */
1471 Perl_ck_warner(aTHX_ packWARN(WARN_EXITING), "Exiting %s via %s",
1472 context_name[CxTYPE(cx)], OP_NAME(PL_op));
1473 if ((CxTYPE(cx)) == CXt_NULL) /* sort BLOCK */
1476 case CXt_LOOP_PLAIN:
1477 case CXt_LOOP_LAZYIV:
1478 case CXt_LOOP_LAZYSV:
1481 DEBUG_l( Perl_deb(aTHX_ "(dopoptoloop(): found loop at cx=%ld)\n", (long)i));
1488 /* find the next GIVEN or FOR (with implicit $_) loop context block */
1491 S_dopoptogivenfor(pTHX_ I32 startingblock)
1494 for (i = startingblock; i >= 0; i--) {
1495 const PERL_CONTEXT *cx = &cxstack[i];
1496 switch (CxTYPE(cx)) {
1500 DEBUG_l( Perl_deb(aTHX_ "(dopoptogivenfor(): found given at cx=%ld)\n", (long)i));
1502 case CXt_LOOP_PLAIN:
1503 assert(!(cx->cx_type & CXp_FOR_DEF));
1505 case CXt_LOOP_LAZYIV:
1506 case CXt_LOOP_LAZYSV:
1509 if (cx->cx_type & CXp_FOR_DEF) {
1510 DEBUG_l( Perl_deb(aTHX_ "(dopoptogivenfor(): found foreach at cx=%ld)\n", (long)i));
1519 S_dopoptowhen(pTHX_ I32 startingblock)
1522 for (i = startingblock; i >= 0; i--) {
1523 const PERL_CONTEXT *cx = &cxstack[i];
1524 switch (CxTYPE(cx)) {
1528 DEBUG_l( Perl_deb(aTHX_ "(dopoptowhen(): found when at cx=%ld)\n", (long)i));
1535 /* dounwind(): pop all contexts above (but not including) cxix.
1536 * Note that it clears the savestack frame associated with each popped
1537 * context entry, but doesn't free any temps.
1538 * It does a cx_popblock() of the last frame that it pops, and leaves
1539 * cxstack_ix equal to cxix.
1543 Perl_dounwind(pTHX_ I32 cxix)
1545 if (!PL_curstackinfo) /* can happen if die during thread cloning */
1548 while (cxstack_ix > cxix) {
1549 PERL_CONTEXT *cx = CX_CUR();
1551 CX_DEBUG(cx, "UNWIND");
1552 /* Note: we don't need to restore the base context info till the end. */
1556 switch (CxTYPE(cx)) {
1559 /* CXt_SUBST is not a block context type, so skip the
1560 * cx_popblock(cx) below */
1561 if (cxstack_ix == cxix + 1) {
1572 case CXt_LOOP_PLAIN:
1573 case CXt_LOOP_LAZYIV:
1574 case CXt_LOOP_LAZYSV:
1587 /* these two don't have a POPFOO() */
1593 if (cxstack_ix == cxix + 1) {
1602 Perl_qerror(pTHX_ SV *err)
1604 PERL_ARGS_ASSERT_QERROR;
1607 if (PL_in_eval & EVAL_KEEPERR) {
1608 Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "\t(in cleanup) %" SVf,
1612 sv_catsv(ERRSV, err);
1615 sv_catsv(PL_errors, err);
1617 Perl_warn(aTHX_ "%" SVf, SVfARG(err));
1619 ++PL_parser->error_count;
1624 /* pop a CXt_EVAL context and in addition, if it was a require then
1626 * 0: do nothing extra;
1627 * 1: undef $INC{$name}; croak "$name did not return a true value";
1628 * 2: delete $INC{$name}; croak "$errsv: Compilation failed in require"
1632 S_pop_eval_context_maybe_croak(pTHX_ PERL_CONTEXT *cx, SV *errsv, int action)
1634 SV *namesv = NULL; /* init to avoid dumb compiler warning */
1638 do_croak = action && (CxOLD_OP_TYPE(cx) == OP_REQUIRE);
1640 /* keep namesv alive after cx_popeval() */
1641 namesv = cx->blk_eval.old_namesv;
1642 cx->blk_eval.old_namesv = NULL;
1651 HV *inc_hv = GvHVn(PL_incgv);
1652 I32 klen = SvUTF8(namesv) ? -(I32)SvCUR(namesv) : (I32)SvCUR(namesv);
1653 const char *key = SvPVX_const(namesv);
1656 (void)hv_delete(inc_hv, key, klen, G_DISCARD);
1657 fmt = "%" SVf " did not return a true value";
1661 (void)hv_store(inc_hv, key, klen, &PL_sv_undef, 0);
1662 fmt = "%" SVf "Compilation failed in require";
1664 errsv = newSVpvs_flags("Unknown error\n", SVs_TEMP);
1667 Perl_croak(aTHX_ fmt, SVfARG(errsv));
1672 /* die_unwind(): this is the final destination for the various croak()
1673 * functions. If we're in an eval, unwind the context and other stacks
1674 * back to the top-most CXt_EVAL and set $@ to msv; otherwise print msv
1675 * to STDERR and initiate an exit. Note that if the CXt_EVAL popped back
1676 * to is a require the exception will be rethrown, as requires don't
1677 * actually trap exceptions.
1681 Perl_die_unwind(pTHX_ SV *msv)
1684 U8 in_eval = PL_in_eval;
1685 PERL_ARGS_ASSERT_DIE_UNWIND;
1690 /* We need to keep this SV alive through all the stack unwinding
1691 * and FREETMPSing below, while ensuing that it doesn't leak
1692 * if we call out to something which then dies (e.g. sub STORE{die}
1693 * when unlocalising a tied var). So we do a dance with
1694 * mortalising and SAVEFREEing.
1696 sv_2mortal(SvREFCNT_inc_simple_NN(exceptsv));
1699 * Historically, perl used to set ERRSV ($@) early in the die
1700 * process and rely on it not getting clobbered during unwinding.
1701 * That sucked, because it was liable to get clobbered, so the
1702 * setting of ERRSV used to emit the exception from eval{} has
1703 * been moved to much later, after unwinding (see just before
1704 * JMPENV_JUMP below). However, some modules were relying on the
1705 * early setting, by examining $@ during unwinding to use it as
1706 * a flag indicating whether the current unwinding was caused by
1707 * an exception. It was never a reliable flag for that purpose,
1708 * being totally open to false positives even without actual
1709 * clobberage, but was useful enough for production code to
1710 * semantically rely on it.
1712 * We'd like to have a proper introspective interface that
1713 * explicitly describes the reason for whatever unwinding
1714 * operations are currently in progress, so that those modules
1715 * work reliably and $@ isn't further overloaded. But we don't
1716 * have one yet. In its absence, as a stopgap measure, ERRSV is
1717 * now *additionally* set here, before unwinding, to serve as the
1718 * (unreliable) flag that it used to.
1720 * This behaviour is temporary, and should be removed when a
1721 * proper way to detect exceptional unwinding has been developed.
1722 * As of 2010-12, the authors of modules relying on the hack
1723 * are aware of the issue, because the modules failed on
1724 * perls 5.13.{1..7} which had late setting of $@ without this
1725 * early-setting hack.
1727 if (!(in_eval & EVAL_KEEPERR)) {
1728 /* remove any read-only/magic from the SV, so we don't
1729 get infinite recursion when setting ERRSV */
1731 sv_setsv_flags(ERRSV, exceptsv,
1732 (SV_GMAGIC|SV_DO_COW_SVSETSV|SV_NOSTEAL));
1735 if (in_eval & EVAL_KEEPERR) {
1736 Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "\t(in cleanup) %" SVf,
1740 while ((cxix = dopoptoeval(cxstack_ix)) < 0
1741 && PL_curstackinfo->si_prev)
1751 JMPENV *restartjmpenv;
1754 if (cxix < cxstack_ix)
1758 assert(CxTYPE(cx) == CXt_EVAL);
1760 /* return false to the caller of eval */
1761 oldsp = PL_stack_base + cx->blk_oldsp;
1762 gimme = cx->blk_gimme;
1763 if (gimme == G_SCALAR)
1764 *++oldsp = &PL_sv_undef;
1765 PL_stack_sp = oldsp;
1767 restartjmpenv = cx->blk_eval.cur_top_env;
1768 restartop = cx->blk_eval.retop;
1770 /* We need a FREETMPS here to avoid late-called destructors
1771 * clobbering $@ *after* we set it below, e.g.
1772 * sub DESTROY { eval { die "X" } }
1773 * eval { my $x = bless []; die $x = 0, "Y" };
1775 * Here the clearing of the $x ref mortalises the anon array,
1776 * which needs to be freed *before* $& is set to "Y",
1777 * otherwise it gets overwritten with "X".
1779 * However, the FREETMPS will clobber exceptsv, so preserve it
1780 * on the savestack for now.
1782 SAVEFREESV(SvREFCNT_inc_simple_NN(exceptsv));
1784 /* now we're about to pop the savestack, so re-mortalise it */
1785 sv_2mortal(SvREFCNT_inc_simple_NN(exceptsv));
1787 /* Note that unlike pp_entereval, pp_require isn't supposed to
1788 * trap errors. So if we're a require, after we pop the
1789 * CXt_EVAL that pp_require pushed, rethrow the error with
1790 * croak(exceptsv). This is all handled by the call below when
1793 S_pop_eval_context_maybe_croak(aTHX_ cx, exceptsv, 2);
1795 if (!(in_eval & EVAL_KEEPERR)) {
1797 sv_setsv(ERRSV, exceptsv);
1799 PL_restartjmpenv = restartjmpenv;
1800 PL_restartop = restartop;
1802 NOT_REACHED; /* NOTREACHED */
1806 write_to_stderr(exceptsv);
1808 NOT_REACHED; /* NOTREACHED */
1814 if (SvTRUE_NN(left) != SvTRUE_NN(right))
1822 =head1 CV Manipulation Functions
1824 =for apidoc caller_cx
1826 The XSUB-writer's equivalent of L<caller()|perlfunc/caller>. The
1827 returned C<PERL_CONTEXT> structure can be interrogated to find all the
1828 information returned to Perl by C<caller>. Note that XSUBs don't get a
1829 stack frame, so C<caller_cx(0, NULL)> will return information for the
1830 immediately-surrounding Perl code.
1832 This function skips over the automatic calls to C<&DB::sub> made on the
1833 behalf of the debugger. If the stack frame requested was a sub called by
1834 C<DB::sub>, the return value will be the frame for the call to
1835 C<DB::sub>, since that has the correct line number/etc. for the call
1836 site. If I<dbcxp> is non-C<NULL>, it will be set to a pointer to the
1837 frame for the sub call itself.
1842 const PERL_CONTEXT *
1843 Perl_caller_cx(pTHX_ I32 count, const PERL_CONTEXT **dbcxp)
1845 I32 cxix = dopoptosub(cxstack_ix);
1846 const PERL_CONTEXT *cx;
1847 const PERL_CONTEXT *ccstack = cxstack;
1848 const PERL_SI *top_si = PL_curstackinfo;
1851 /* we may be in a higher stacklevel, so dig down deeper */
1852 while (cxix < 0 && top_si->si_type != PERLSI_MAIN) {
1853 top_si = top_si->si_prev;
1854 ccstack = top_si->si_cxstack;
1855 cxix = dopoptosub_at(ccstack, top_si->si_cxix);
1859 /* caller() should not report the automatic calls to &DB::sub */
1860 if (PL_DBsub && GvCV(PL_DBsub) && cxix >= 0 &&
1861 ccstack[cxix].blk_sub.cv == GvCV(PL_DBsub))
1865 cxix = dopoptosub_at(ccstack, cxix - 1);
1868 cx = &ccstack[cxix];
1869 if (dbcxp) *dbcxp = cx;
1871 if (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT) {
1872 const I32 dbcxix = dopoptosub_at(ccstack, cxix - 1);
1873 /* We expect that ccstack[dbcxix] is CXt_SUB, anyway, the
1874 field below is defined for any cx. */
1875 /* caller() should not report the automatic calls to &DB::sub */
1876 if (PL_DBsub && GvCV(PL_DBsub) && dbcxix >= 0 && ccstack[dbcxix].blk_sub.cv == GvCV(PL_DBsub))
1877 cx = &ccstack[dbcxix];
1886 const PERL_CONTEXT *cx;
1887 const PERL_CONTEXT *dbcx;
1889 const HEK *stash_hek;
1891 bool has_arg = MAXARG && TOPs;
1900 cx = caller_cx(count + !!(PL_op->op_private & OPpOFFBYONE), &dbcx);
1902 if (gimme != G_ARRAY) {
1909 CX_DEBUG(cx, "CALLER");
1910 assert(CopSTASH(cx->blk_oldcop));
1911 stash_hek = SvTYPE(CopSTASH(cx->blk_oldcop)) == SVt_PVHV
1912 ? HvNAME_HEK((HV*)CopSTASH(cx->blk_oldcop))
1914 if (gimme != G_ARRAY) {
1917 PUSHs(&PL_sv_undef);
1920 sv_sethek(TARG, stash_hek);
1929 PUSHs(&PL_sv_undef);
1932 sv_sethek(TARG, stash_hek);
1935 mPUSHs(newSVpv(OutCopFILE(cx->blk_oldcop), 0));
1936 lcop = closest_cop(cx->blk_oldcop, OpSIBLING(cx->blk_oldcop),
1937 cx->blk_sub.retop, TRUE);
1939 lcop = cx->blk_oldcop;
1940 mPUSHu(CopLINE(lcop));
1943 if (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT) {
1944 /* So is ccstack[dbcxix]. */
1945 if (CvHASGV(dbcx->blk_sub.cv)) {
1946 PUSHs(cv_name(dbcx->blk_sub.cv, 0, 0));
1947 PUSHs(boolSV(CxHASARGS(cx)));
1950 PUSHs(newSVpvs_flags("(unknown)", SVs_TEMP));
1951 PUSHs(boolSV(CxHASARGS(cx)));
1955 PUSHs(newSVpvs_flags("(eval)", SVs_TEMP));
1958 gimme = cx->blk_gimme;
1959 if (gimme == G_VOID)
1960 PUSHs(&PL_sv_undef);
1962 PUSHs(boolSV((gimme & G_WANT) == G_ARRAY));
1963 if (CxTYPE(cx) == CXt_EVAL) {
1965 if (CxOLD_OP_TYPE(cx) == OP_ENTEREVAL) {
1966 SV *cur_text = cx->blk_eval.cur_text;
1967 if (SvCUR(cur_text) >= 2) {
1968 PUSHs(newSVpvn_flags(SvPVX(cur_text), SvCUR(cur_text)-2,
1969 SvUTF8(cur_text)|SVs_TEMP));
1972 /* I think this is will always be "", but be sure */
1973 PUSHs(sv_2mortal(newSVsv(cur_text)));
1979 else if (cx->blk_eval.old_namesv) {
1980 mPUSHs(newSVsv(cx->blk_eval.old_namesv));
1983 /* eval BLOCK (try blocks have old_namesv == 0) */
1985 PUSHs(&PL_sv_undef);
1986 PUSHs(&PL_sv_undef);
1990 PUSHs(&PL_sv_undef);
1991 PUSHs(&PL_sv_undef);
1993 if (CxTYPE(cx) == CXt_SUB && CxHASARGS(cx)
1994 && CopSTASH_eq(PL_curcop, PL_debstash))
1996 /* slot 0 of the pad contains the original @_ */
1997 AV * const ary = MUTABLE_AV(AvARRAY(MUTABLE_AV(
1998 PadlistARRAY(CvPADLIST(cx->blk_sub.cv))[
1999 cx->blk_sub.olddepth+1]))[0]);
2000 const SSize_t off = AvARRAY(ary) - AvALLOC(ary);
2002 Perl_init_dbargs(aTHX);
2004 if (AvMAX(PL_dbargs) < AvFILLp(ary) + off)
2005 av_extend(PL_dbargs, AvFILLp(ary) + off);
2006 if (AvFILLp(ary) + 1 + off)
2007 Copy(AvALLOC(ary), AvARRAY(PL_dbargs), AvFILLp(ary) + 1 + off, SV*);
2008 AvFILLp(PL_dbargs) = AvFILLp(ary) + off;
2010 mPUSHi(CopHINTS_get(cx->blk_oldcop));
2013 STRLEN * const old_warnings = cx->blk_oldcop->cop_warnings ;
2015 if (old_warnings == pWARN_NONE)
2016 mask = newSVpvn(WARN_NONEstring, WARNsize) ;
2017 else if (old_warnings == pWARN_STD && (PL_dowarn & G_WARN_ON) == 0)
2018 mask = &PL_sv_undef ;
2019 else if (old_warnings == pWARN_ALL ||
2020 (old_warnings == pWARN_STD && PL_dowarn & G_WARN_ON)) {
2021 mask = newSVpvn(WARN_ALLstring, WARNsize) ;
2024 mask = newSVpvn((char *) (old_warnings + 1), old_warnings[0]);
2028 PUSHs(cx->blk_oldcop->cop_hints_hash ?
2029 sv_2mortal(newRV_noinc(MUTABLE_SV(cop_hints_2hv(cx->blk_oldcop, 0))))
2039 if (MAXARG < 1 || (!TOPs && !POPs)) {
2041 tmps = NULL, len = 0;
2044 tmps = SvPVx_const(POPs, len);
2045 sv_resetpvn(tmps, len, CopSTASH(PL_curcop));
2050 /* like pp_nextstate, but used instead when the debugger is active */
2054 PL_curcop = (COP*)PL_op;
2055 TAINT_NOT; /* Each statement is presumed innocent */
2056 PL_stack_sp = PL_stack_base + CX_CUR()->blk_oldsp;
2061 if (PL_op->op_flags & OPf_SPECIAL /* breakpoint */
2062 || PL_DBsingle_iv || PL_DBsignal_iv || PL_DBtrace_iv)
2066 const U8 gimme = G_ARRAY;
2067 GV * const gv = PL_DBgv;
2070 if (gv && isGV_with_GP(gv))
2073 if (!cv || (!CvROOT(cv) && !CvXSUB(cv)))
2074 DIE(aTHX_ "No DB::DB routine defined");
2076 if (CvDEPTH(cv) >= 1 && !(PL_debug & DEBUG_DB_RECURSE_FLAG))
2077 /* don't do recursive DB::DB call */
2087 (void)(*CvXSUB(cv))(aTHX_ cv);
2093 cx = cx_pushblock(CXt_SUB, gimme, SP, PL_savestack_ix);
2094 cx_pushsub(cx, cv, PL_op->op_next, 0);
2095 /* OP_DBSTATE's op_private holds hint bits rather than
2096 * the lvalue-ish flags seen in OP_ENTERSUB. So cancel
2097 * any CxLVAL() flags that have now been mis-calculated */
2104 if (CvDEPTH(cv) >= 2)
2105 pad_push(CvPADLIST(cv), CvDEPTH(cv));
2106 PAD_SET_CUR_NOSAVE(CvPADLIST(cv), CvDEPTH(cv));
2107 RETURNOP(CvSTART(cv));
2119 (void)cx_pushblock(CXt_BLOCK, gimme, PL_stack_sp, PL_savestack_ix);
2131 assert(CxTYPE(cx) == CXt_BLOCK);
2133 if (PL_op->op_flags & OPf_SPECIAL)
2134 /* fake block should preserve $1 et al; e.g. /(...)/ while ...; */
2135 cx->blk_oldpm = PL_curpm;
2137 oldsp = PL_stack_base + cx->blk_oldsp;
2138 gimme = cx->blk_gimme;
2140 if (gimme == G_VOID)
2141 PL_stack_sp = oldsp;
2143 leave_adjust_stacks(oldsp, oldsp, gimme,
2144 PL_op->op_private & OPpLVALUE ? 3 : 1);
2154 S_outside_integer(pTHX_ SV *sv)
2157 const NV nv = SvNV_nomg(sv);
2158 if (Perl_isinfnan(nv))
2160 #ifdef NV_PRESERVES_UV
2161 if (nv < (NV)IV_MIN || nv > (NV)IV_MAX)
2164 if (nv <= (NV)IV_MIN)
2167 ((nv > (NV)UV_MAX ||
2168 SvUV_nomg(sv) > (UV)IV_MAX)))
2179 const U8 gimme = GIMME_V;
2180 void *itervarp; /* GV or pad slot of the iteration variable */
2181 SV *itersave; /* the old var in the iterator var slot */
2184 if (PL_op->op_targ) { /* "my" variable */
2185 itervarp = &PAD_SVl(PL_op->op_targ);
2186 itersave = *(SV**)itervarp;
2188 if (PL_op->op_private & OPpLVAL_INTRO) { /* for my $x (...) */
2189 /* the SV currently in the pad slot is never live during
2190 * iteration (the slot is always aliased to one of the items)
2191 * so it's always stale */
2192 SvPADSTALE_on(itersave);
2194 SvREFCNT_inc_simple_void_NN(itersave);
2195 cxflags = CXp_FOR_PAD;
2198 SV * const sv = POPs;
2199 itervarp = (void *)sv;
2200 if (LIKELY(isGV(sv))) { /* symbol table variable */
2201 itersave = GvSV(sv);
2202 SvREFCNT_inc_simple_void(itersave);
2203 cxflags = CXp_FOR_GV;
2204 if (PL_op->op_private & OPpITER_DEF)
2205 cxflags |= CXp_FOR_DEF;
2207 else { /* LV ref: for \$foo (...) */
2208 assert(SvTYPE(sv) == SVt_PVMG);
2209 assert(SvMAGIC(sv));
2210 assert(SvMAGIC(sv)->mg_type == PERL_MAGIC_lvref);
2212 cxflags = CXp_FOR_LVREF;
2215 /* OPpITER_DEF (implicit $_) should only occur with a GV iter var */
2216 assert((cxflags & CXp_FOR_GV) || !(PL_op->op_private & OPpITER_DEF));
2218 /* Note that this context is initially set as CXt_NULL. Further on
2219 * down it's changed to one of the CXt_LOOP_*. Before it's changed,
2220 * there mustn't be anything in the blk_loop substruct that requires
2221 * freeing or undoing, in case we die in the meantime. And vice-versa.
2223 cx = cx_pushblock(cxflags, gimme, MARK, PL_savestack_ix);
2224 cx_pushloop_for(cx, itervarp, itersave);
2226 if (PL_op->op_flags & OPf_STACKED) {
2227 /* OPf_STACKED implies either a single array: for(@), with a
2228 * single AV on the stack, or a range: for (1..5), with 1 and 5 on
2230 SV *maybe_ary = POPs;
2231 if (SvTYPE(maybe_ary) != SVt_PVAV) {
2234 SV * const right = maybe_ary;
2235 if (UNLIKELY(cxflags & CXp_FOR_LVREF))
2236 DIE(aTHX_ "Assigned value is not a reference");
2239 if (RANGE_IS_NUMERIC(sv,right)) {
2240 cx->cx_type |= CXt_LOOP_LAZYIV;
2241 if (S_outside_integer(aTHX_ sv) ||
2242 S_outside_integer(aTHX_ right))
2243 DIE(aTHX_ "Range iterator outside integer range");
2244 cx->blk_loop.state_u.lazyiv.cur = SvIV_nomg(sv);
2245 cx->blk_loop.state_u.lazyiv.end = SvIV_nomg(right);
2248 cx->cx_type |= CXt_LOOP_LAZYSV;
2249 cx->blk_loop.state_u.lazysv.cur = newSVsv(sv);
2250 cx->blk_loop.state_u.lazysv.end = right;
2251 SvREFCNT_inc_simple_void_NN(right);
2252 (void) SvPV_force_nolen(cx->blk_loop.state_u.lazysv.cur);
2253 /* This will do the upgrade to SVt_PV, and warn if the value
2254 is uninitialised. */
2255 (void) SvPV_nolen_const(right);
2256 /* Doing this avoids a check every time in pp_iter in pp_hot.c
2257 to replace !SvOK() with a pointer to "". */
2259 SvREFCNT_dec(right);
2260 cx->blk_loop.state_u.lazysv.end = &PL_sv_no;
2264 else /* SvTYPE(maybe_ary) == SVt_PVAV */ {
2265 /* for (@array) {} */
2266 cx->cx_type |= CXt_LOOP_ARY;
2267 cx->blk_loop.state_u.ary.ary = MUTABLE_AV(maybe_ary);
2268 SvREFCNT_inc_simple_void_NN(maybe_ary);
2269 cx->blk_loop.state_u.ary.ix =
2270 (PL_op->op_private & OPpITER_REVERSED) ?
2271 AvFILL(cx->blk_loop.state_u.ary.ary) + 1 :
2274 /* EXTEND(SP, 1) not needed in this branch because we just did POPs */
2276 else { /* iterating over items on the stack */
2277 cx->cx_type |= CXt_LOOP_LIST;
2278 cx->blk_oldsp = SP - PL_stack_base;
2279 cx->blk_loop.state_u.stack.basesp = MARK - PL_stack_base;
2280 cx->blk_loop.state_u.stack.ix =
2281 (PL_op->op_private & OPpITER_REVERSED)
2283 : cx->blk_loop.state_u.stack.basesp;
2284 /* pre-extend stack so pp_iter doesn't have to check every time
2285 * it pushes yes/no */
2295 const U8 gimme = GIMME_V;
2297 cx = cx_pushblock(CXt_LOOP_PLAIN, gimme, PL_stack_sp, PL_savestack_ix);
2298 cx_pushloop_plain(cx);
2311 assert(CxTYPE_is_LOOP(cx));
2312 oldsp = PL_stack_base + cx->blk_oldsp;
2313 base = CxTYPE(cx) == CXt_LOOP_LIST
2314 ? PL_stack_base + cx->blk_loop.state_u.stack.basesp
2316 gimme = cx->blk_gimme;
2318 if (gimme == G_VOID)
2321 leave_adjust_stacks(oldsp, base, gimme,
2322 PL_op->op_private & OPpLVALUE ? 3 : 1);
2325 cx_poploop(cx); /* Stack values are safe: release loop vars ... */
2333 /* This duplicates most of pp_leavesub, but with additional code to handle
2334 * return args in lvalue context. It was forked from pp_leavesub to
2335 * avoid slowing down that function any further.
2337 * Any changes made to this function may need to be copied to pp_leavesub
2340 * also tail-called by pp_return
2351 assert(CxTYPE(cx) == CXt_SUB);
2353 if (CxMULTICALL(cx)) {
2354 /* entry zero of a stack is always PL_sv_undef, which
2355 * simplifies converting a '()' return into undef in scalar context */
2356 assert(PL_stack_sp > PL_stack_base || *PL_stack_base == &PL_sv_undef);
2360 gimme = cx->blk_gimme;
2361 oldsp = PL_stack_base + cx->blk_oldsp; /* last arg of previous frame */
2363 if (gimme == G_VOID)
2364 PL_stack_sp = oldsp;
2366 U8 lval = CxLVAL(cx);
2367 bool is_lval = (lval && !(lval & OPpENTERSUB_INARGS));
2368 const char *what = NULL;
2370 if (gimme == G_SCALAR) {
2372 /* check for bad return arg */
2373 if (oldsp < PL_stack_sp) {
2374 SV *sv = *PL_stack_sp;
2375 if ((SvPADTMP(sv) || SvREADONLY(sv))) {
2377 SvREADONLY(sv) ? (sv == &PL_sv_undef) ? "undef"
2378 : "a readonly value" : "a temporary";
2383 /* sub:lvalue{} will take us here. */
2388 "Can't return %s from lvalue subroutine", what);
2392 leave_adjust_stacks(oldsp, oldsp, gimme, is_lval ? 3 : 2);
2394 if (lval & OPpDEREF) {
2395 /* lval_sub()->{...} and similar */
2399 TOPs = vivify_ref(TOPs, CxLVAL(cx) & OPpDEREF);
2405 assert(gimme == G_ARRAY);
2406 assert (!(lval & OPpDEREF));
2409 /* scan for bad return args */
2411 for (p = PL_stack_sp; p > oldsp; p--) {
2413 /* the PL_sv_undef exception is to allow things like
2414 * this to work, where PL_sv_undef acts as 'skip'
2415 * placeholder on the LHS of list assigns:
2416 * sub foo :lvalue { undef }
2417 * ($a, undef, foo(), $b) = 1..4;
2419 if (sv != &PL_sv_undef && (SvPADTMP(sv) || SvREADONLY(sv)))
2421 /* Might be flattened array after $#array = */
2422 what = SvREADONLY(sv)
2423 ? "a readonly value" : "a temporary";
2429 leave_adjust_stacks(oldsp, oldsp, gimme, is_lval ? 3 : 2);
2434 cx_popsub(cx); /* Stack values are safe: release CV and @_ ... */
2436 retop = cx->blk_sub.retop;
2447 const I32 cxix = dopoptosub(cxstack_ix);
2449 assert(cxstack_ix >= 0);
2450 if (cxix < cxstack_ix) {
2452 if (!( PL_curstackinfo->si_type == PERLSI_SORT
2453 || ( PL_curstackinfo->si_type == PERLSI_MULTICALL
2454 && (cxstack[0].cx_type & CXp_SUB_RE_FAKE))
2457 DIE(aTHX_ "Can't return outside a subroutine");
2459 * a sort block, which is a CXt_NULL not a CXt_SUB;
2460 * or a /(?{...})/ block.
2461 * Handle specially. */
2462 assert(CxTYPE(&cxstack[0]) == CXt_NULL
2463 || ( CxTYPE(&cxstack[0]) == CXt_SUB
2464 && (cxstack[0].cx_type & CXp_SUB_RE_FAKE)));
2465 if (cxstack_ix > 0) {
2466 /* See comment below about context popping. Since we know
2467 * we're scalar and not lvalue, we can preserve the return
2468 * value in a simpler fashion than there. */
2470 assert(cxstack[0].blk_gimme == G_SCALAR);
2471 if ( (sp != PL_stack_base)
2472 && !(SvFLAGS(sv) & (SVs_TEMP|SVs_PADTMP))
2474 *SP = sv_mortalcopy(sv);
2477 /* caller responsible for popping cxstack[0] */
2481 /* There are contexts that need popping. Doing this may free the
2482 * return value(s), so preserve them first: e.g. popping the plain
2483 * loop here would free $x:
2484 * sub f { { my $x = 1; return $x } }
2485 * We may also need to shift the args down; for example,
2486 * for (1,2) { return 3,4 }
2487 * leaves 1,2,3,4 on the stack. Both these actions will be done by
2488 * leave_adjust_stacks(), along with freeing any temps. Note that
2489 * whoever we tail-call (e.g. pp_leaveeval) will also call
2490 * leave_adjust_stacks(); however, the second call is likely to
2491 * just see a bunch of SvTEMPs with a ref count of 1, and so just
2492 * pass them through, rather than copying them again. So this
2493 * isn't as inefficient as it sounds.
2495 cx = &cxstack[cxix];
2497 if (cx->blk_gimme != G_VOID)
2498 leave_adjust_stacks(MARK, PL_stack_base + cx->blk_oldsp,
2500 CxTYPE(cx) == CXt_SUB && CvLVALUE(cx->blk_sub.cv)
2504 cx = &cxstack[cxix]; /* CX stack may have been realloced */
2507 /* Like in the branch above, we need to handle any extra junk on
2508 * the stack. But because we're not also popping extra contexts, we
2509 * don't have to worry about prematurely freeing args. So we just
2510 * need to do the bare minimum to handle junk, and leave the main
2511 * arg processing in the function we tail call, e.g. pp_leavesub.
2512 * In list context we have to splice out the junk; in scalar
2513 * context we can leave as-is (pp_leavesub will later return the
2514 * top stack element). But for an empty arg list, e.g.
2515 * for (1,2) { return }
2516 * we need to set sp = oldsp so that pp_leavesub knows to push
2517 * &PL_sv_undef onto the stack.
2520 cx = &cxstack[cxix];
2521 oldsp = PL_stack_base + cx->blk_oldsp;
2522 if (oldsp != MARK) {
2523 SSize_t nargs = SP - MARK;
2525 if (cx->blk_gimme == G_ARRAY) {
2526 /* shift return args to base of call stack frame */
2527 Move(MARK + 1, oldsp + 1, nargs, SV*);
2528 PL_stack_sp = oldsp + nargs;
2532 PL_stack_sp = oldsp;
2536 /* fall through to a normal exit */
2537 switch (CxTYPE(cx)) {
2539 return CxTRYBLOCK(cx)
2540 ? Perl_pp_leavetry(aTHX)
2541 : Perl_pp_leaveeval(aTHX);
2543 return CvLVALUE(cx->blk_sub.cv)
2544 ? Perl_pp_leavesublv(aTHX)
2545 : Perl_pp_leavesub(aTHX);
2547 return Perl_pp_leavewrite(aTHX);
2549 DIE(aTHX_ "panic: return, type=%u", (unsigned) CxTYPE(cx));
2553 /* find the enclosing loop or labelled loop and dounwind() back to it. */
2555 static PERL_CONTEXT *
2559 if (PL_op->op_flags & OPf_SPECIAL) {
2560 cxix = dopoptoloop(cxstack_ix);
2562 /* diag_listed_as: Can't "last" outside a loop block */
2563 Perl_croak(aTHX_ "Can't \"%s\" outside a loop block",
2569 const char * const label =
2570 PL_op->op_flags & OPf_STACKED
2571 ? SvPV(TOPs,label_len)
2572 : (label_len = strlen(cPVOP->op_pv), cPVOP->op_pv);
2573 const U32 label_flags =
2574 PL_op->op_flags & OPf_STACKED
2576 : (cPVOP->op_private & OPpPV_IS_UTF8) ? SVf_UTF8 : 0;
2578 cxix = dopoptolabel(label, label_len, label_flags);
2580 /* diag_listed_as: Label not found for "last %s" */
2581 Perl_croak(aTHX_ "Label not found for \"%s %" SVf "\"",
2583 SVfARG(PL_op->op_flags & OPf_STACKED
2584 && !SvGMAGICAL(TOPp1s)
2586 : newSVpvn_flags(label,
2588 label_flags | SVs_TEMP)));
2590 if (cxix < cxstack_ix)
2592 return &cxstack[cxix];
2601 cx = S_unwind_loop(aTHX);
2603 assert(CxTYPE_is_LOOP(cx));
2604 PL_stack_sp = PL_stack_base
2605 + (CxTYPE(cx) == CXt_LOOP_LIST
2606 ? cx->blk_loop.state_u.stack.basesp
2612 /* Stack values are safe: */
2614 cx_poploop(cx); /* release loop vars ... */
2616 nextop = cx->blk_loop.my_op->op_lastop->op_next;
2626 /* if not a bare 'next' in the main scope, search for it */
2628 if (!((PL_op->op_flags & OPf_SPECIAL) && CxTYPE_is_LOOP(cx)))
2629 cx = S_unwind_loop(aTHX);
2632 PL_curcop = cx->blk_oldcop;
2634 return (cx)->blk_loop.my_op->op_nextop;
2639 PERL_CONTEXT *cx = S_unwind_loop(aTHX);
2640 OP* redo_op = cx->blk_loop.my_op->op_redoop;
2642 if (redo_op->op_type == OP_ENTER) {
2643 /* pop one less context to avoid $x being freed in while (my $x..) */
2646 assert(CxTYPE(cx) == CXt_BLOCK);
2647 redo_op = redo_op->op_next;
2653 PL_curcop = cx->blk_oldcop;
2658 #define UNENTERABLE (OP *)1
2659 #define GOTO_DEPTH 64
2662 S_dofindlabel(pTHX_ OP *o, const char *label, STRLEN len, U32 flags, OP **opstack, OP **oplimit)
2665 static const char* const too_deep = "Target of goto is too deeply nested";
2667 PERL_ARGS_ASSERT_DOFINDLABEL;
2670 Perl_croak(aTHX_ "%s", too_deep);
2671 if (o->op_type == OP_LEAVE ||
2672 o->op_type == OP_SCOPE ||
2673 o->op_type == OP_LEAVELOOP ||
2674 o->op_type == OP_LEAVESUB ||
2675 o->op_type == OP_LEAVETRY ||
2676 o->op_type == OP_LEAVEGIVEN)
2678 *ops++ = cUNOPo->op_first;
2680 else if (oplimit - opstack < GOTO_DEPTH) {
2681 if (o->op_flags & OPf_KIDS
2682 && cUNOPo->op_first->op_type == OP_PUSHMARK) {
2683 *ops++ = UNENTERABLE;
2685 else if (o->op_flags & OPf_KIDS && PL_opargs[o->op_type]
2686 && OP_CLASS(o) != OA_LOGOP
2687 && o->op_type != OP_LINESEQ
2688 && o->op_type != OP_SREFGEN
2689 && o->op_type != OP_ENTEREVAL
2690 && o->op_type != OP_GLOB
2691 && o->op_type != OP_RV2CV) {
2692 OP * const kid = cUNOPo->op_first;
2693 if (OP_GIMME(kid, 0) != G_SCALAR || OpHAS_SIBLING(kid))
2694 *ops++ = UNENTERABLE;
2698 Perl_croak(aTHX_ "%s", too_deep);
2700 if (o->op_flags & OPf_KIDS) {
2702 OP * const kid1 = cUNOPo->op_first;
2703 /* First try all the kids at this level, since that's likeliest. */
2704 for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
2705 if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
2706 STRLEN kid_label_len;
2707 U32 kid_label_flags;
2708 const char *kid_label = CopLABEL_len_flags(kCOP,
2709 &kid_label_len, &kid_label_flags);
2711 ( (kid_label_flags & SVf_UTF8) != (flags & SVf_UTF8) ) ?
2714 (const U8*)kid_label, kid_label_len,
2715 (const U8*)label, len) == 0)
2717 (const U8*)label, len,
2718 (const U8*)kid_label, kid_label_len) == 0)
2719 : ( len == kid_label_len && ((kid_label == label)
2720 || memEQ(kid_label, label, len)))))
2724 for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
2725 bool first_kid_of_binary = FALSE;
2726 if (kid == PL_lastgotoprobe)
2728 if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
2731 else if (ops[-1] != UNENTERABLE
2732 && (ops[-1]->op_type == OP_NEXTSTATE ||
2733 ops[-1]->op_type == OP_DBSTATE))
2738 if (kid == kid1 && ops != opstack && ops[-1] == UNENTERABLE) {
2739 first_kid_of_binary = TRUE;
2742 if ((o = dofindlabel(kid, label, len, flags, ops, oplimit)))
2744 if (first_kid_of_binary)
2745 *ops++ = UNENTERABLE;
2754 S_check_op_type(pTHX_ OP * const o)
2756 /* Eventually we may want to stack the needed arguments
2757 * for each op. For now, we punt on the hard ones. */
2758 /* XXX This comment seems to me like wishful thinking. --sprout */
2759 if (o == UNENTERABLE)
2761 "Can't \"goto\" into a binary or list expression");
2762 if (o->op_type == OP_ENTERITER)
2764 "Can't \"goto\" into the middle of a foreach loop");
2765 if (o->op_type == OP_ENTERGIVEN)
2767 "Can't \"goto\" into a \"given\" block");
2770 /* also used for: pp_dump() */
2778 OP *enterops[GOTO_DEPTH];
2779 const char *label = NULL;
2780 STRLEN label_len = 0;
2781 U32 label_flags = 0;
2782 const bool do_dump = (PL_op->op_type == OP_DUMP);
2783 static const char* const must_have_label = "goto must have label";
2785 if (PL_op->op_flags & OPf_STACKED) {
2786 /* goto EXPR or goto &foo */
2788 SV * const sv = POPs;
2791 if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
2792 /* This egregious kludge implements goto &subroutine */
2795 CV *cv = MUTABLE_CV(SvRV(sv));
2796 AV *arg = GvAV(PL_defgv);
2798 while (!CvROOT(cv) && !CvXSUB(cv)) {
2799 const GV * const gv = CvGV(cv);
2803 /* autoloaded stub? */
2804 if (cv != GvCV(gv) && (cv = GvCV(gv)))
2806 autogv = gv_autoload_pvn(GvSTASH(gv), GvNAME(gv),
2808 GvNAMEUTF8(gv) ? SVf_UTF8 : 0);
2809 if (autogv && (cv = GvCV(autogv)))
2811 tmpstr = sv_newmortal();
2812 gv_efullname3(tmpstr, gv, NULL);
2813 DIE(aTHX_ "Goto undefined subroutine &%" SVf, SVfARG(tmpstr));
2815 DIE(aTHX_ "Goto undefined subroutine");
2818 cxix = dopoptosub(cxstack_ix);
2820 DIE(aTHX_ "Can't goto subroutine outside a subroutine");
2822 cx = &cxstack[cxix];
2823 /* ban goto in eval: see <20050521150056.GC20213@iabyn.com> */
2824 if (CxTYPE(cx) == CXt_EVAL) {
2826 /* diag_listed_as: Can't goto subroutine from an eval-%s */
2827 DIE(aTHX_ "Can't goto subroutine from an eval-string");
2829 /* diag_listed_as: Can't goto subroutine from an eval-%s */
2830 DIE(aTHX_ "Can't goto subroutine from an eval-block");
2832 else if (CxMULTICALL(cx))
2833 DIE(aTHX_ "Can't goto subroutine from a sort sub (or similar callback)");
2835 /* First do some returnish stuff. */
2837 SvREFCNT_inc_simple_void(cv); /* avoid premature free during unwind */
2839 if (cxix < cxstack_ix) {
2846 /* protect @_ during save stack unwind. */
2848 SvREFCNT_inc_NN(sv_2mortal(MUTABLE_SV(arg)));
2850 assert(PL_scopestack_ix == cx->blk_oldscopesp);
2853 if (CxTYPE(cx) == CXt_SUB && CxHASARGS(cx)) {
2854 /* this is part of cx_popsub_args() */
2855 AV* av = MUTABLE_AV(PAD_SVl(0));
2856 assert(AvARRAY(MUTABLE_AV(
2857 PadlistARRAY(CvPADLIST(cx->blk_sub.cv))[
2858 CvDEPTH(cx->blk_sub.cv)])) == PL_curpad);
2860 /* we are going to donate the current @_ from the old sub
2861 * to the new sub. This first part of the donation puts a
2862 * new empty AV in the pad[0] slot of the old sub,
2863 * unless pad[0] and @_ differ (e.g. if the old sub did
2864 * local *_ = []); in which case clear the old pad[0]
2865 * array in the usual way */
2866 if (av == arg || AvREAL(av))
2867 clear_defarray(av, av == arg);
2868 else CLEAR_ARGARRAY(av);
2871 /* don't restore PL_comppad here. It won't be needed if the
2872 * sub we're going to is non-XS, but restoring it early then
2873 * croaking (e.g. the "Goto undefined subroutine" below)
2874 * means the CX block gets processed again in dounwind,
2875 * but this time with the wrong PL_comppad */
2877 /* A destructor called during LEAVE_SCOPE could have undefined
2878 * our precious cv. See bug #99850. */
2879 if (!CvROOT(cv) && !CvXSUB(cv)) {
2880 const GV * const gv = CvGV(cv);
2882 SV * const tmpstr = sv_newmortal();
2883 gv_efullname3(tmpstr, gv, NULL);
2884 DIE(aTHX_ "Goto undefined subroutine &%" SVf,
2887 DIE(aTHX_ "Goto undefined subroutine");
2890 if (CxTYPE(cx) == CXt_SUB) {
2891 CvDEPTH(cx->blk_sub.cv) = cx->blk_sub.olddepth;
2892 SvREFCNT_dec_NN(cx->blk_sub.cv);
2895 /* Now do some callish stuff. */
2897 const SSize_t items = arg ? AvFILL(arg) + 1 : 0;
2898 const bool m = arg ? cBOOL(SvRMAGICAL(arg)) : 0;
2903 SAVEFREESV(cv); /* later, undo the 'avoid premature free' hack */
2905 /* put GvAV(defgv) back onto stack */
2907 EXTEND(SP, items+1); /* @_ could have been extended. */
2912 bool r = cBOOL(AvREAL(arg));
2913 for (index=0; index<items; index++)
2917 SV ** const svp = av_fetch(arg, index, 0);
2918 sv = svp ? *svp : NULL;
2920 else sv = AvARRAY(arg)[index];
2922 ? r ? SvREFCNT_inc_NN(sv_2mortal(sv)) : sv
2923 : sv_2mortal(newSVavdefelem(arg, index, 1));
2927 if (CxTYPE(cx) == CXt_SUB && CxHASARGS(cx)) {
2928 /* Restore old @_ */
2929 CX_POP_SAVEARRAY(cx);
2932 retop = cx->blk_sub.retop;
2933 PL_comppad = cx->blk_sub.prevcomppad;
2934 PL_curpad = LIKELY(PL_comppad) ? AvARRAY(PL_comppad) : NULL;
2936 /* XS subs don't have a CXt_SUB, so pop it;
2937 * this is a cx_popblock(), less all the stuff we already did
2938 * for cx_topblock() earlier */
2939 PL_curcop = cx->blk_oldcop;
2942 /* Push a mark for the start of arglist */
2945 (void)(*CvXSUB(cv))(aTHX_ cv);
2950 PADLIST * const padlist = CvPADLIST(cv);
2952 SAVEFREESV(cv); /* later, undo the 'avoid premature free' hack */
2954 /* partial unrolled cx_pushsub(): */
2956 cx->blk_sub.cv = cv;
2957 cx->blk_sub.olddepth = CvDEPTH(cv);
2960 SvREFCNT_inc_simple_void_NN(cv);
2961 if (CvDEPTH(cv) > 1) {
2962 if (CvDEPTH(cv) == PERL_SUB_DEPTH_WARN && ckWARN(WARN_RECURSION))
2963 sub_crush_depth(cv);
2964 pad_push(padlist, CvDEPTH(cv));
2966 PL_curcop = cx->blk_oldcop;
2967 PAD_SET_CUR_NOSAVE(padlist, CvDEPTH(cv));
2970 /* second half of donating @_ from the old sub to the
2971 * new sub: abandon the original pad[0] AV in the
2972 * new sub, and replace it with the donated @_.
2973 * pad[0] takes ownership of the extra refcount
2974 * we gave arg earlier */
2976 SvREFCNT_dec(PAD_SVl(0));
2977 PAD_SVl(0) = (SV *)arg;
2978 SvREFCNT_inc_simple_void_NN(arg);
2981 /* GvAV(PL_defgv) might have been modified on scope
2982 exit, so point it at arg again. */
2983 if (arg != GvAV(PL_defgv)) {
2984 AV * const av = GvAV(PL_defgv);
2985 GvAV(PL_defgv) = (AV *)SvREFCNT_inc_simple(arg);
2990 if (PERLDB_SUB) { /* Checking curstash breaks DProf. */
2991 Perl_get_db_sub(aTHX_ NULL, cv);
2993 CV * const gotocv = get_cvs("DB::goto", 0);
2995 PUSHMARK( PL_stack_sp );
2996 call_sv(MUTABLE_SV(gotocv), G_SCALAR | G_NODEBUG);
3001 retop = CvSTART(cv);
3002 goto putback_return;
3007 label = SvPV_nomg_const(sv, label_len);
3008 label_flags = SvUTF8(sv);
3011 else if (!(PL_op->op_flags & OPf_SPECIAL)) {
3012 /* goto LABEL or dump LABEL */
3013 label = cPVOP->op_pv;
3014 label_flags = (cPVOP->op_private & OPpPV_IS_UTF8) ? SVf_UTF8 : 0;
3015 label_len = strlen(label);
3017 if (!(do_dump || label_len)) DIE(aTHX_ "%s", must_have_label);
3022 OP *gotoprobe = NULL;
3023 bool leaving_eval = FALSE;
3024 bool in_block = FALSE;
3025 bool pseudo_block = FALSE;
3026 PERL_CONTEXT *last_eval_cx = NULL;
3030 PL_lastgotoprobe = NULL;
3032 for (ix = cxstack_ix; ix >= 0; ix--) {
3034 switch (CxTYPE(cx)) {
3036 leaving_eval = TRUE;
3037 if (!CxTRYBLOCK(cx)) {
3038 gotoprobe = (last_eval_cx ?
3039 last_eval_cx->blk_eval.old_eval_root :
3044 /* else fall through */
3045 case CXt_LOOP_PLAIN:
3046 case CXt_LOOP_LAZYIV:
3047 case CXt_LOOP_LAZYSV:
3052 gotoprobe = OpSIBLING(cx->blk_oldcop);
3058 gotoprobe = OpSIBLING(cx->blk_oldcop);
3061 gotoprobe = PL_main_root;
3064 gotoprobe = CvROOT(cx->blk_sub.cv);
3065 pseudo_block = cBOOL(CxMULTICALL(cx));
3069 DIE(aTHX_ "Can't \"goto\" out of a pseudo block");
3072 DIE(aTHX_ "panic: goto, type=%u, ix=%ld",
3073 CxTYPE(cx), (long) ix);
3074 gotoprobe = PL_main_root;
3080 retop = dofindlabel(gotoprobe, label, label_len, label_flags,
3081 enterops, enterops + GOTO_DEPTH);
3084 if ( (sibl1 = OpSIBLING(gotoprobe)) &&
3085 sibl1->op_type == OP_UNSTACK &&
3086 (sibl2 = OpSIBLING(sibl1)))
3088 retop = dofindlabel(sibl2,
3089 label, label_len, label_flags, enterops,
3090 enterops + GOTO_DEPTH);
3096 DIE(aTHX_ "Can't \"goto\" out of a pseudo block");
3097 PL_lastgotoprobe = gotoprobe;
3100 DIE(aTHX_ "Can't find label %" UTF8f,
3101 UTF8fARG(label_flags, label_len, label));
3103 /* if we're leaving an eval, check before we pop any frames
3104 that we're not going to punt, otherwise the error
3107 if (leaving_eval && *enterops && enterops[1]) {
3109 for (i = 1; enterops[i]; i++)
3110 S_check_op_type(aTHX_ enterops[i]);
3113 if (*enterops && enterops[1]) {
3114 I32 i = enterops[1] != UNENTERABLE
3115 && enterops[1]->op_type == OP_ENTER && in_block
3119 deprecate("\"goto\" to jump into a construct");
3122 /* pop unwanted frames */
3124 if (ix < cxstack_ix) {
3126 DIE(aTHX_ "panic: docatch: illegal ix=%ld", (long)ix);
3132 /* push wanted frames */
3134 if (*enterops && enterops[1]) {
3135 OP * const oldop = PL_op;
3136 ix = enterops[1] != UNENTERABLE
3137 && enterops[1]->op_type == OP_ENTER && in_block
3140 for (; enterops[ix]; ix++) {
3141 PL_op = enterops[ix];
3142 S_check_op_type(aTHX_ PL_op);
3143 DEBUG_l( Perl_deb(aTHX_ "pp_goto: Entering %s\n",
3145 PL_op->op_ppaddr(aTHX);
3153 if (!retop) retop = PL_main_start;
3155 PL_restartop = retop;
3156 PL_do_undump = TRUE;
3160 PL_restartop = 0; /* hmm, must be GNU unexec().. */
3161 PL_do_undump = FALSE;
3179 anum = 0; (void)POPs;
3185 && SvTRUE(cop_hints_fetch_pvs(PL_curcop, "vmsish_exit", 0)))
3188 VMSISH_HUSHED || (PL_curcop->op_private & OPpHUSH_VMSISH);
3191 PL_exit_flags |= PERL_EXIT_EXPECTED;
3193 PUSHs(&PL_sv_undef);
3200 S_save_lines(pTHX_ AV *array, SV *sv)
3202 const char *s = SvPVX_const(sv);
3203 const char * const send = SvPVX_const(sv) + SvCUR(sv);
3206 PERL_ARGS_ASSERT_SAVE_LINES;
3208 while (s && s < send) {
3210 SV * const tmpstr = newSV_type(SVt_PVMG);
3212 t = (const char *)memchr(s, '\n', send - s);
3218 sv_setpvn(tmpstr, s, t - s);
3219 av_store(array, line++, tmpstr);
3227 Check for the cases 0 or 3 of cur_env.je_ret, only used inside an eval context.
3229 0 is used as continue inside eval,
3231 3 is used for a die caught by an inner eval - continue inner loop
3233 See F<cop.h>: je_mustcatch, when set at any runlevel to TRUE, means eval ops must
3234 establish a local jmpenv to handle exception traps.
3239 S_docatch(pTHX_ Perl_ppaddr_t firstpp)
3242 OP * const oldop = PL_op;
3245 assert(CATCH_GET == TRUE);
3250 PL_op = firstpp(aTHX);
3255 /* die caught by an inner eval - continue inner loop */
3256 if (PL_restartop && PL_restartjmpenv == PL_top_env) {
3257 PL_restartjmpenv = NULL;
3258 PL_op = PL_restartop;
3267 NOT_REACHED; /* NOTREACHED */
3276 =for apidoc find_runcv
3278 Locate the CV corresponding to the currently executing sub or eval.
3279 If C<db_seqp> is non_null, skip CVs that are in the DB package and populate
3280 C<*db_seqp> with the cop sequence number at the point that the DB:: code was
3281 entered. (This allows debuggers to eval in the scope of the breakpoint
3282 rather than in the scope of the debugger itself.)
3288 Perl_find_runcv(pTHX_ U32 *db_seqp)
3290 return Perl_find_runcv_where(aTHX_ 0, 0, db_seqp);
3293 /* If this becomes part of the API, it might need a better name. */
3295 Perl_find_runcv_where(pTHX_ U8 cond, IV arg, U32 *db_seqp)
3302 PL_curcop == &PL_compiling
3304 : PL_curcop->cop_seq;
3306 for (si = PL_curstackinfo; si; si = si->si_prev) {
3308 for (ix = si->si_cxix; ix >= 0; ix--) {
3309 const PERL_CONTEXT *cx = &(si->si_cxstack[ix]);
3311 if (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT) {
3312 cv = cx->blk_sub.cv;
3313 /* skip DB:: code */
3314 if (db_seqp && PL_debstash && CvSTASH(cv) == PL_debstash) {
3315 *db_seqp = cx->blk_oldcop->cop_seq;
3318 if (cx->cx_type & CXp_SUB_RE)
3321 else if (CxTYPE(cx) == CXt_EVAL && !CxTRYBLOCK(cx))
3322 cv = cx->blk_eval.cv;
3325 case FIND_RUNCV_padid_eq:
3327 || CvPADLIST(cv)->xpadl_id != (U32)arg)
3330 case FIND_RUNCV_level_eq:
3331 if (level++ != arg) continue;
3339 return cond == FIND_RUNCV_padid_eq ? NULL : PL_main_cv;
3343 /* Run yyparse() in a setjmp wrapper. Returns:
3344 * 0: yyparse() successful
3345 * 1: yyparse() failed
3349 S_try_yyparse(pTHX_ int gramtype)
3354 assert(CxTYPE(CX_CUR()) == CXt_EVAL);
3358 ret = yyparse(gramtype) ? 1 : 0;
3365 NOT_REACHED; /* NOTREACHED */
3372 /* Compile a require/do or an eval ''.
3374 * outside is the lexically enclosing CV (if any) that invoked us.
3375 * seq is the current COP scope value.
3376 * hh is the saved hints hash, if any.
3378 * Returns a bool indicating whether the compile was successful; if so,
3379 * PL_eval_start contains the first op of the compiled code; otherwise,
3382 * This function is called from two places: pp_require and pp_entereval.
3383 * These can be distinguished by whether PL_op is entereval.
3387 S_doeval_compile(pTHX_ U8 gimme, CV* outside, U32 seq, HV *hh)
3390 OP * const saveop = PL_op;
3391 bool clear_hints = saveop->op_type != OP_ENTEREVAL;
3392 COP * const oldcurcop = PL_curcop;
3393 bool in_require = (saveop->op_type == OP_REQUIRE);
3397 PL_in_eval = (in_require
3398 ? (EVAL_INREQUIRE | (PL_in_eval & EVAL_INEVAL))
3400 ((PL_op->op_private & OPpEVAL_RE_REPARSING)
3401 ? EVAL_RE_REPARSING : 0)));
3405 evalcv = MUTABLE_CV(newSV_type(SVt_PVCV));
3407 assert(CxTYPE(CX_CUR()) == CXt_EVAL);
3408 CX_CUR()->blk_eval.cv = evalcv;
3409 CX_CUR()->blk_gimme = gimme;
3411 CvOUTSIDE_SEQ(evalcv) = seq;
3412 CvOUTSIDE(evalcv) = MUTABLE_CV(SvREFCNT_inc_simple(outside));
3414 /* set up a scratch pad */
3416 CvPADLIST_set(evalcv, pad_new(padnew_SAVE));
3417 PL_op = NULL; /* avoid PL_op and PL_curpad referring to different CVs */
3420 SAVEMORTALIZESV(evalcv); /* must remain until end of current statement */
3422 /* make sure we compile in the right package */
3424 if (CopSTASH_ne(PL_curcop, PL_curstash)) {
3425 SAVEGENERICSV(PL_curstash);
3426 PL_curstash = (HV *)CopSTASH(PL_curcop);
3427 if (SvTYPE(PL_curstash) != SVt_PVHV) PL_curstash = NULL;
3429 SvREFCNT_inc_simple_void(PL_curstash);
3430 save_item(PL_curstname);
3431 sv_sethek(PL_curstname, HvNAME_HEK(PL_curstash));
3434 /* XXX:ajgo do we really need to alloc an AV for begin/checkunit */
3435 SAVESPTR(PL_beginav);
3436 PL_beginav = newAV();
3437 SAVEFREESV(PL_beginav);
3438 SAVESPTR(PL_unitcheckav);
3439 PL_unitcheckav = newAV();
3440 SAVEFREESV(PL_unitcheckav);
3443 ENTER_with_name("evalcomp");
3444 SAVESPTR(PL_compcv);
3447 /* try to compile it */
3449 PL_eval_root = NULL;
3450 PL_curcop = &PL_compiling;
3451 if ((saveop->op_type != OP_REQUIRE) && (saveop->op_flags & OPf_SPECIAL))
3452 PL_in_eval |= EVAL_KEEPERR;
3459 hv_clear(GvHV(PL_hintgv));
3462 PL_hints = saveop->op_private & OPpEVAL_COPHH
3463 ? oldcurcop->cop_hints : (U32)saveop->op_targ;
3465 /* making 'use re eval' not be in scope when compiling the
3466 * qr/mabye_has_runtime_code_block/ ensures that we don't get
3467 * infinite recursion when S_has_runtime_code() gives a false
3468 * positive: the second time round, HINT_RE_EVAL isn't set so we
3469 * don't bother calling S_has_runtime_code() */
3470 if (PL_in_eval & EVAL_RE_REPARSING)
3471 PL_hints &= ~HINT_RE_EVAL;
3474 /* SAVEHINTS created a new HV in PL_hintgv, which we need to GC */
3475 SvREFCNT_dec(GvHV(PL_hintgv));
3476 GvHV(PL_hintgv) = hh;
3479 SAVECOMPILEWARNINGS();
3481 if (PL_dowarn & G_WARN_ALL_ON)
3482 PL_compiling.cop_warnings = pWARN_ALL ;
3483 else if (PL_dowarn & G_WARN_ALL_OFF)
3484 PL_compiling.cop_warnings = pWARN_NONE ;
3486 PL_compiling.cop_warnings = pWARN_STD ;
3489 PL_compiling.cop_warnings =
3490 DUP_WARNINGS(oldcurcop->cop_warnings);
3491 cophh_free(CopHINTHASH_get(&PL_compiling));
3492 if (Perl_cop_fetch_label(aTHX_ oldcurcop, NULL, NULL)) {
3493 /* The label, if present, is the first entry on the chain. So rather
3494 than writing a blank label in front of it (which involves an
3495 allocation), just use the next entry in the chain. */
3496 PL_compiling.cop_hints_hash
3497 = cophh_copy(oldcurcop->cop_hints_hash->refcounted_he_next);
3498 /* Check the assumption that this removed the label. */
3499 assert(Perl_cop_fetch_label(aTHX_ &PL_compiling, NULL, NULL) == NULL);
3502 PL_compiling.cop_hints_hash = cophh_copy(oldcurcop->cop_hints_hash);
3505 CALL_BLOCK_HOOKS(bhk_eval, saveop);
3507 /* note that yyparse() may raise an exception, e.g. C<BEGIN{die}>,
3508 * so honour CATCH_GET and trap it here if necessary */
3511 /* compile the code */
3512 yystatus = (!in_require && CATCH_GET) ? S_try_yyparse(aTHX_ GRAMPROG) : yyparse(GRAMPROG);
3514 if (yystatus || PL_parser->error_count || !PL_eval_root) {
3519 /* note that if yystatus == 3, then the require/eval died during
3520 * compilation, so the EVAL CX block has already been popped, and
3521 * various vars restored */
3522 if (yystatus != 3) {
3524 op_free(PL_eval_root);
3525 PL_eval_root = NULL;
3527 SP = PL_stack_base + POPMARK; /* pop original mark */
3529 assert(CxTYPE(cx) == CXt_EVAL);
3530 /* pop the CXt_EVAL, and if was a require, croak */
3531 S_pop_eval_context_maybe_croak(aTHX_ cx, ERRSV, 2);
3534 /* die_unwind() re-croaks when in require, having popped the
3535 * require EVAL context. So we should never catch a require
3537 assert(!in_require);
3540 if (!*(SvPV_nolen_const(errsv)))
3541 sv_setpvs(errsv, "Compilation error");
3543 if (gimme != G_ARRAY) PUSHs(&PL_sv_undef);
3548 /* Compilation successful. Now clean up */
3550 LEAVE_with_name("evalcomp");
3552 CopLINE_set(&PL_compiling, 0);
3553 SAVEFREEOP(PL_eval_root);
3554 cv_forget_slab(evalcv);
3556 DEBUG_x(dump_eval());
3558 /* Register with debugger: */
3559 if (PERLDB_INTER && saveop->op_type == OP_REQUIRE) {
3560 CV * const cv = get_cvs("DB::postponed", 0);
3564 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
3566 call_sv(MUTABLE_SV(cv), G_DISCARD);
3570 if (PL_unitcheckav) {
3571 OP *es = PL_eval_start;
3572 call_list(PL_scopestack_ix, PL_unitcheckav);
3576 CvDEPTH(evalcv) = 1;
3577 SP = PL_stack_base + POPMARK; /* pop original mark */
3578 PL_op = saveop; /* The caller may need it. */
3579 PL_parser->lex_state = LEX_NOTPARSING; /* $^S needs this. */
3585 /* Return NULL if the file doesn't exist or isn't a file;
3586 * else return PerlIO_openn().
3590 S_check_type_and_open(pTHX_ SV *name)
3595 const char *p = SvPV_const(name, len);
3598 PERL_ARGS_ASSERT_CHECK_TYPE_AND_OPEN;
3600 /* checking here captures a reasonable error message when
3601 * PERL_DISABLE_PMC is true, but when PMC checks are enabled, the
3602 * user gets a confusing message about looking for the .pmc file
3603 * rather than for the .pm file so do the check in S_doopen_pm when
3604 * PMC is on instead of here. S_doopen_pm calls this func.
3605 * This check prevents a \0 in @INC causing problems.
3607 #ifdef PERL_DISABLE_PMC
3608 if (!IS_SAFE_PATHNAME(p, len, "require"))
3612 /* on Win32 stat is expensive (it does an open() and close() twice and
3613 a couple other IO calls), the open will fail with a dir on its own with
3614 errno EACCES, so only do a stat to separate a dir from a real EACCES
3615 caused by user perms */
3617 st_rc = PerlLIO_stat(p, &st);
3623 if(S_ISBLK(st.st_mode)) {
3627 else if(S_ISDIR(st.st_mode)) {
3636 retio = PerlIO_openn(aTHX_ ":", PERL_SCRIPT_MODE, -1, 0, 0, NULL, 1, &name);
3638 /* EACCES stops the INC search early in pp_require to implement
3639 feature RT #113422 */
3640 if(!retio && errno == EACCES) { /* exists but probably a directory */
3642 st_rc = PerlLIO_stat(p, &st);
3644 if(S_ISDIR(st.st_mode))
3646 else if(S_ISBLK(st.st_mode))
3657 /* doopen_pm(): return the equivalent of PerlIO_openn() on the given name,
3658 * but first check for bad names (\0) and non-files.
3659 * Also if the filename ends in .pm and unless PERL_DISABLE_PMC,
3660 * try loading Foo.pmc first.
3662 #ifndef PERL_DISABLE_PMC
3664 S_doopen_pm(pTHX_ SV *name)
3667 const char *p = SvPV_const(name, namelen);
3669 PERL_ARGS_ASSERT_DOOPEN_PM;
3671 /* check the name before trying for the .pmc name to avoid the
3672 * warning referring to the .pmc which the user probably doesn't
3673 * know or care about
3675 if (!IS_SAFE_PATHNAME(p, namelen, "require"))
3678 if (memENDPs(p, namelen, ".pm")) {
3679 SV *const pmcsv = sv_newmortal();
3682 SvSetSV_nosteal(pmcsv,name);
3683 sv_catpvs(pmcsv, "c");
3685 pmcio = check_type_and_open(pmcsv);
3689 return check_type_and_open(name);
3692 # define doopen_pm(name) check_type_and_open(name)
3693 #endif /* !PERL_DISABLE_PMC */
3695 /* require doesn't search in @INC for absolute names, or when the name is
3696 explicitly relative the current directory: i.e. ./, ../ */
3697 PERL_STATIC_INLINE bool
3698 S_path_is_searchable(const char *name)
3700 PERL_ARGS_ASSERT_PATH_IS_SEARCHABLE;
3702 if (PERL_FILE_IS_ABSOLUTE(name)
3704 || (*name == '.' && ((name[1] == '/' ||
3705 (name[1] == '.' && name[2] == '/'))
3706 || (name[1] == '\\' ||
3707 ( name[1] == '.' && name[2] == '\\')))
3710 || (*name == '.' && (name[1] == '/' ||
3711 (name[1] == '.' && name[2] == '/')))
3722 /* implement 'require 5.010001' */
3725 S_require_version(pTHX_ SV *sv)
3729 sv = sv_2mortal(new_version(sv));
3730 if (!Perl_sv_derived_from_pvn(aTHX_ PL_patchlevel, STR_WITH_LEN("version"), 0))
3731 upg_version(PL_patchlevel, TRUE);
3732 if (cUNOP->op_first->op_type == OP_CONST && cUNOP->op_first->op_private & OPpCONST_NOVER) {
3733 if ( vcmp(sv,PL_patchlevel) <= 0 )
3734 DIE(aTHX_ "Perls since %" SVf " too modern--this is %" SVf ", stopped",
3735 SVfARG(sv_2mortal(vnormal(sv))),
3736 SVfARG(sv_2mortal(vnormal(PL_patchlevel)))
3740 if ( vcmp(sv,PL_patchlevel) > 0 ) {
3743 SV * const req = SvRV(sv);
3744 SV * const pv = *hv_fetchs(MUTABLE_HV(req), "original", FALSE);
3746 /* get the left hand term */
3747 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(req), "version", FALSE)));
3749 first = SvIV(*av_fetch(lav,0,0));
3750 if ( first > (int)PERL_REVISION /* probably 'use 6.0' */
3751 || hv_exists(MUTABLE_HV(req), "qv", 2 ) /* qv style */
3752 || av_tindex(lav) > 1 /* FP with > 3 digits */
3753 || strstr(SvPVX(pv),".0") /* FP with leading 0 */
3755 DIE(aTHX_ "Perl %" SVf " required--this is only "
3756 "%" SVf ", stopped",
3757 SVfARG(sv_2mortal(vnormal(req))),
3758 SVfARG(sv_2mortal(vnormal(PL_patchlevel)))
3761 else { /* probably 'use 5.10' or 'use 5.8' */
3765 if (av_tindex(lav)>=1)
3766 second = SvIV(*av_fetch(lav,1,0));
3768 second /= second >= 600 ? 100 : 10;
3769 hintsv = Perl_newSVpvf(aTHX_ "v%d.%d.0",
3770 (int)first, (int)second);
3771 upg_version(hintsv, TRUE);
3773 DIE(aTHX_ "Perl %" SVf " required (did you mean %" SVf "?)"
3774 "--this is only %" SVf ", stopped",
3775 SVfARG(sv_2mortal(vnormal(req))),
3776 SVfARG(sv_2mortal(vnormal(sv_2mortal(hintsv)))),
3777 SVfARG(sv_2mortal(vnormal(PL_patchlevel)))
3786 /* Handle C<require Foo::Bar>, C<require "Foo/Bar.pm"> and C<do "Foo.pm">.
3787 * The first form will have already been converted at compile time to
3788 * the second form */
3791 S_require_file(pTHX_ SV *sv)
3801 int vms_unixname = 0;
3804 /* tryname is the actual pathname (with @INC prefix) which was loaded.
3805 * It's stored as a value in %INC, and used for error messages */
3806 const char *tryname = NULL;
3807 SV *namesv = NULL; /* SV equivalent of tryname */
3808 const U8 gimme = GIMME_V;
3809 int filter_has_file = 0;
3810 PerlIO *tryrsfp = NULL;
3811 SV *filter_cache = NULL;
3812 SV *filter_state = NULL;
3813 SV *filter_sub = NULL;
3817 bool path_searchable;
3818 I32 old_savestack_ix;
3819 const bool op_is_require = PL_op->op_type == OP_REQUIRE;
3820 const char *const op_name = op_is_require ? "require" : "do";
3821 SV ** svp_cached = NULL;
3823 assert(op_is_require || PL_op->op_type == OP_DOFILE);
3826 DIE(aTHX_ "Missing or undefined argument to %s", op_name);
3827 name = SvPV_nomg_const(sv, len);
3828 if (!(name && len > 0 && *name))
3829 DIE(aTHX_ "Missing or undefined argument to %s", op_name);
3832 /* try to return earlier (save the SAFE_PATHNAME check) if INC already got the name */
3833 if (op_is_require) {
3834 /* can optimize to only perform one single lookup */
3835 svp_cached = hv_fetch(GvHVn(PL_incgv), (char*) name, len, 0);
3836 if ( svp_cached && *svp_cached != &PL_sv_undef ) RETPUSHYES;
3840 if (!IS_SAFE_PATHNAME(name, len, op_name)) {
3841 if (!op_is_require) {
3845 DIE(aTHX_ "Can't locate %s: %s",
3846 pv_escape(newSVpvs_flags("",SVs_TEMP),name,len,len*2,
3847 NULL, SvUTF8(sv)?PERL_PV_ESCAPE_UNI:0),
3850 TAINT_PROPER(op_name);
3852 path_searchable = path_is_searchable(name);
3855 /* The key in the %ENV hash is in the syntax of file passed as the argument
3856 * usually this is in UNIX format, but sometimes in VMS format, which
3857 * can result in a module being pulled in more than once.
3858 * To prevent this, the key must be stored in UNIX format if the VMS
3859 * name can be translated to UNIX.
3863 tounixspec(name, SvPVX(sv_2mortal(newSVpv("", VMS_MAXRSS-1)))))
3865 unixlen = strlen(unixname);
3871 /* if not VMS or VMS name can not be translated to UNIX, pass it
3874 unixname = (char *) name;
3877 if (op_is_require) {
3878 /* reuse the previous hv_fetch result if possible */
3879 SV * const * const svp = svp_cached ? svp_cached : hv_fetch(GvHVn(PL_incgv), unixname, unixlen, 0);
3881 if (*svp != &PL_sv_undef)
3884 DIE(aTHX_ "Attempt to reload %s aborted.\n"
3885 "Compilation failed in require", unixname);
3888 /*XXX OPf_KIDS should always be true? -dapm 4/2017 */
3889 if (PL_op->op_flags & OPf_KIDS) {
3890 SVOP * const kid = (SVOP*)cUNOP->op_first;
3892 if (kid->op_type == OP_CONST && (kid->op_private & OPpCONST_BARE)) {
3893 /* Make sure that a bareword module name (e.g. ::Foo::Bar)
3894 * doesn't map to a naughty pathname like /Foo/Bar.pm.
3895 * Note that the parser will normally detect such errors
3896 * at compile time before we reach here, but
3897 * Perl_load_module() can fake up an identical optree
3898 * without going near the parser, and being able to put
3899 * anything as the bareword. So we include a duplicate set
3900 * of checks here at runtime.
3902 const STRLEN package_len = len - 3;
3903 const char slashdot[2] = {'/', '.'};
3905 const char backslashdot[2] = {'\\', '.'};
3908 /* Disallow *purported* barewords that map to absolute
3909 filenames, filenames relative to the current or parent
3910 directory, or (*nix) hidden filenames. Also sanity check
3911 that the generated filename ends .pm */
3912 if (!path_searchable || len < 3 || name[0] == '.'
3913 || !memEQs(name + package_len, len - package_len, ".pm"))
3914 DIE(aTHX_ "Bareword in require maps to disallowed filename \"%" SVf "\"", sv);
3915 if (memchr(name, 0, package_len)) {
3916 /* diag_listed_as: Bareword in require contains "%s" */
3917 DIE(aTHX_ "Bareword in require contains \"\\0\"");
3919 if (ninstr(name, name + package_len, slashdot,
3920 slashdot + sizeof(slashdot))) {
3921 /* diag_listed_as: Bareword in require contains "%s" */
3922 DIE(aTHX_ "Bareword in require contains \"/.\"");
3925 if (ninstr(name, name + package_len, backslashdot,
3926 backslashdot + sizeof(backslashdot))) {
3927 /* diag_listed_as: Bareword in require contains "%s" */
3928 DIE(aTHX_ "Bareword in require contains \"\\.\"");
3935 PERL_DTRACE_PROBE_FILE_LOADING(unixname);
3937 /* Try to locate and open a file, possibly using @INC */
3939 /* with "/foo/bar.pm", "./foo.pm" and "../foo/bar.pm", try to load
3940 * the file directly rather than via @INC ... */
3941 if (!path_searchable) {
3942 /* At this point, name is SvPVX(sv) */
3944 tryrsfp = doopen_pm(sv);
3947 /* ... but if we fail, still search @INC for code references;
3948 * these are applied even on on-searchable paths (except
3949 * if we got EACESS).
3951 * For searchable paths, just search @INC normally
3953 if (!tryrsfp && !(errno == EACCES && !path_searchable)) {
3954 AV * const ar = GvAVn(PL_incgv);
3961 namesv = newSV_type(SVt_PV);
3962 for (i = 0; i <= AvFILL(ar); i++) {
3963 SV * const dirsv = *av_fetch(ar, i, TRUE);
3971 if (SvTYPE(SvRV(loader)) == SVt_PVAV
3972 && !SvOBJECT(SvRV(loader)))
3974 loader = *av_fetch(MUTABLE_AV(SvRV(loader)), 0, TRUE);
3978 Perl_sv_setpvf(aTHX_ namesv, "/loader/0x%" UVxf "/%s",
3979 PTR2UV(SvRV(dirsv)), name);
3980 tryname = SvPVX_const(namesv);
3983 if (SvPADTMP(nsv)) {
3984 nsv = sv_newmortal();
3985 SvSetSV_nosteal(nsv,sv);
3988 ENTER_with_name("call_INC");
3996 if (SvGMAGICAL(loader)) {
3997 SV *l = sv_newmortal();
3998 sv_setsv_nomg(l, loader);
4001 if (sv_isobject(loader))
4002 count = call_method("INC", G_ARRAY);
4004 count = call_sv(loader, G_ARRAY);
4014 if (SvROK(arg) && (SvTYPE(SvRV(arg)) <= SVt_PVLV)
4015 && !isGV_with_GP(SvRV(arg))) {
4016 filter_cache = SvRV(arg);
4023 if (SvROK(arg) && isGV_with_GP(SvRV(arg))) {
4027 if (isGV_with_GP(arg)) {
4028 IO * const io = GvIO((const GV *)arg);
4033 tryrsfp = IoIFP(io);
4034 if (IoOFP(io) && IoOFP(io) != IoIFP(io)) {
4035 PerlIO_close(IoOFP(io));
4046 if (SvROK(arg) && SvTYPE(SvRV(arg)) == SVt_PVCV) {
4048 SvREFCNT_inc_simple_void_NN(filter_sub);
4051 filter_state = SP[i];
4052 SvREFCNT_inc_simple_void(filter_state);
4056 if (!tryrsfp && (filter_cache || filter_sub)) {
4057 tryrsfp = PerlIO_open(BIT_BUCKET,
4063 /* FREETMPS may free our filter_cache */
4064 SvREFCNT_inc_simple_void(filter_cache);
4068 LEAVE_with_name("call_INC");
4070 /* Now re-mortalize it. */
4071 sv_2mortal(filter_cache);
4073 /* Adjust file name if the hook has set an %INC entry.
4074 This needs to happen after the FREETMPS above. */
4075 svp = hv_fetch(GvHVn(PL_incgv), name, len, 0);
4077 tryname = SvPV_nolen_const(*svp);
4084 filter_has_file = 0;
4085 filter_cache = NULL;
4087 SvREFCNT_dec_NN(filter_state);
4088 filter_state = NULL;
4091 SvREFCNT_dec_NN(filter_sub);
4095 else if (path_searchable) {
4096 /* match against a plain @INC element (non-searchable
4097 * paths are only matched against refs in @INC) */
4102 dir = SvPV_nomg_const(dirsv, dirlen);
4108 if (!IS_SAFE_SYSCALL(dir, dirlen, "@INC entry", op_name))
4112 tounixpath(dir, SvPVX(sv_2mortal(newSVpv("", VMS_MAXRSS-1)))))
4115 sv_setpv(namesv, unixdir);
4116 sv_catpv(namesv, unixname);
4117 #elif defined(__SYMBIAN32__)
4118 if (PL_origfilename[0] &&
4119 PL_origfilename[1] == ':' &&
4120 !(dir[0] && dir[1] == ':'))
4121 Perl_sv_setpvf(aTHX_ namesv,
4126 Perl_sv_setpvf(aTHX_ namesv,
4130 /* The equivalent of
4131 Perl_sv_setpvf(aTHX_ namesv, "%s/%s", dir, name);
4132 but without the need to parse the format string, or
4133 call strlen on either pointer, and with the correct
4134 allocation up front. */
4136 char *tmp = SvGROW(namesv, dirlen + len + 2);
4138 memcpy(tmp, dir, dirlen);
4141 /* Avoid '<dir>//<file>' */
4142 if (!dirlen || *(tmp-1) != '/') {
4145 /* So SvCUR_set reports the correct length below */
4149 /* name came from an SV, so it will have a '\0' at the
4150 end that we can copy as part of this memcpy(). */
4151 memcpy(tmp, name, len + 1);
4153 SvCUR_set(namesv, dirlen + len + 1);
4157 TAINT_PROPER(op_name);
4158 tryname = SvPVX_const(namesv);
4159 tryrsfp = doopen_pm(namesv);
4161 if (tryname[0] == '.' && tryname[1] == '/') {
4163 while (*++tryname == '/') {}
4167 else if (errno == EMFILE || errno == EACCES) {
4168 /* no point in trying other paths if out of handles;
4169 * on the other hand, if we couldn't open one of the
4170 * files, then going on with the search could lead to
4171 * unexpected results; see perl #113422
4180 /* at this point we've ether opened a file (tryrsfp) or set errno */
4182 saved_errno = errno; /* sv_2mortal can realloc things */
4185 /* we failed; croak if require() or return undef if do() */
4186 if (op_is_require) {
4187 if(saved_errno == EMFILE || saved_errno == EACCES) {
4188 /* diag_listed_as: Can't locate %s */
4189 DIE(aTHX_ "Can't locate %s: %s: %s",
4190 name, tryname, Strerror(saved_errno));
4192 if (path_searchable) { /* did we lookup @INC? */
4193 AV * const ar = GvAVn(PL_incgv);
4195 SV *const msg = newSVpvs_flags("", SVs_TEMP);
4196 SV *const inc = newSVpvs_flags("", SVs_TEMP);
4197 for (i = 0; i <= AvFILL(ar); i++) {
4198 sv_catpvs(inc, " ");
4199 sv_catsv(inc, *av_fetch(ar, i, TRUE));
4201 if (memENDPs(name, len, ".pm")) {
4202 const char *e = name + len - (sizeof(".pm") - 1);
4204 bool utf8 = cBOOL(SvUTF8(sv));
4206 /* if the filename, when converted from "Foo/Bar.pm"
4207 * form back to Foo::Bar form, makes a valid
4208 * package name (i.e. parseable by C<require
4209 * Foo::Bar>), then emit a hint.
4211 * this loop is modelled after the one in
4215 if (utf8 && isIDFIRST_utf8_safe(c, e)) {
4217 while (c < e && isIDCONT_utf8_safe(
4218 (const U8*) c, (const U8*) e))
4221 else if (isWORDCHAR_A(*c)) {
4222 while (c < e && isWORDCHAR_A(*c))
4231 if (c == e && isIDFIRST_lazy_if_safe(name, e, utf8)) {
4232 sv_catpvs(msg, " (you may need to install the ");
4233 for (c = name; c < e; c++) {
4235 sv_catpvs(msg, "::");
4238 sv_catpvn(msg, c, 1);
4241 sv_catpvs(msg, " module)");
4244 else if (memENDs(name, len, ".h")) {
4245 sv_catpvs(msg, " (change .h to .ph maybe?) (did you run h2ph?)");
4247 else if (memENDs(name, len, ".ph")) {
4248 sv_catpvs(msg, " (did you run h2ph?)");
4251 /* diag_listed_as: Can't locate %s */
4253 "Can't locate %s in @INC%" SVf " (@INC contains:%" SVf ")",
4257 DIE(aTHX_ "Can't locate %s", name);
4260 #ifdef DEFAULT_INC_EXCLUDES_DOT
4264 /* the complication is to match the logic from doopen_pm() so
4265 * we don't treat do "sda1" as a previously successful "do".
4267 bool do_warn = namesv && ckWARN_d(WARN_DEPRECATED)
4268 && PerlLIO_stat(name, &st) == 0 && !S_ISDIR(st.st_mode) && !S_ISBLK(st.st_mode)
4269 && (io = PerlIO_openn(aTHX_ ":", PERL_SCRIPT_MODE, -1, 0, 0, NULL, 1, &sv)) != NULL;
4275 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),
4276 "do \"%s\" failed, '.' is no longer in @INC; "
4277 "did you mean do \"./%s\"?",
4286 SETERRNO(0, SS_NORMAL);
4288 /* Update %INC. Assume success here to prevent recursive requirement. */
4289 /* name is never assigned to again, so len is still strlen(name) */
4290 /* Check whether a hook in @INC has already filled %INC */
4292 (void)hv_store(GvHVn(PL_incgv),
4293 unixname, unixlen, newSVpv(tryname,0),0);
4295 SV** const svp = hv_fetch(GvHVn(PL_incgv), unixname, unixlen, 0);
4297 (void)hv_store(GvHVn(PL_incgv),
4298 unixname, unixlen, SvREFCNT_inc_simple(hook_sv), 0 );
4301 /* Now parse the file */
4303 old_savestack_ix = PL_savestack_ix;
4304 SAVECOPFILE_FREE(&PL_compiling);
4305 CopFILE_set(&PL_compiling, tryname);
4306 lex_start(NULL, tryrsfp, 0);
4308 if (filter_sub || filter_cache) {
4309 /* We can use the SvPV of the filter PVIO itself as our cache, rather
4310 than hanging another SV from it. In turn, filter_add() optionally
4311 takes the SV to use as the filter (or creates a new SV if passed
4312 NULL), so simply pass in whatever value filter_cache has. */
4313 SV * const fc = filter_cache ? newSV(0) : NULL;
4315 if (fc) sv_copypv(fc, filter_cache);
4316 datasv = filter_add(S_run_user_filter, fc);
4317 IoLINES(datasv) = filter_has_file;
4318 IoTOP_GV(datasv) = MUTABLE_GV(filter_state);
4319 IoBOTTOM_GV(datasv) = MUTABLE_GV(filter_sub);
4322 /* switch to eval mode */
4324 cx = cx_pushblock(CXt_EVAL, gimme, SP, old_savestack_ix);
4325 cx_pusheval(cx, PL_op->op_next, newSVpv(name, 0));
4327 SAVECOPLINE(&PL_compiling);
4328 CopLINE_set(&PL_compiling, 0);
4332 if (doeval_compile(gimme, NULL, PL_curcop->cop_seq, NULL))
4335 op = PL_op->op_next;
4337 PERL_DTRACE_PROBE_FILE_LOADED(unixname);
4343 /* also used for: pp_dofile() */
4347 RUN_PP_CATCHABLY(Perl_pp_require);
4354 return ((SvNIOKp(sv) || SvVOK(sv)) && PL_op->op_type != OP_DOFILE)
4355 ? S_require_version(aTHX_ sv)
4356 : S_require_file(aTHX_ sv);
4361 /* This is a op added to hold the hints hash for
4362 pp_entereval. The hash can be modified by the code
4363 being eval'ed, so we return a copy instead. */
4368 mXPUSHs(MUTABLE_SV(hv_copy_hints_hv(MUTABLE_HV(cSVOP_sv))));
4380 char tbuf[TYPE_DIGITS(long) + 12];
4388 I32 old_savestack_ix;
4390 RUN_PP_CATCHABLY(Perl_pp_entereval);
4393 was = PL_breakable_sub_gen;
4394 saved_delete = FALSE;
4398 bytes = PL_op->op_private & OPpEVAL_BYTES;
4400 if (PL_op->op_private & OPpEVAL_HAS_HH) {
4401 saved_hh = MUTABLE_HV(SvREFCNT_inc(POPs));
4403 else if (PL_hints & HINT_LOCALIZE_HH || (
4404 PL_op->op_private & OPpEVAL_COPHH
4405 && PL_curcop->cop_hints & HINT_LOCALIZE_HH
4407 saved_hh = cop_hints_2hv(PL_curcop, 0);
4408 hv_magic(saved_hh, NULL, PERL_MAGIC_hints);
4412 /* make sure we've got a plain PV (no overload etc) before testing
4413 * for taint. Making a copy here is probably overkill, but better
4414 * safe than sorry */
4416 const char * const p = SvPV_const(sv, len);
4418 sv = newSVpvn_flags(p, len, SVs_TEMP | SvUTF8(sv));
4419 lex_flags |= LEX_START_COPIED;
4421 if (bytes && SvUTF8(sv))
4422 SvPVbyte_force(sv, len);
4424 else if (bytes && SvUTF8(sv)) {
4425 /* Don't modify someone else's scalar */
4428 (void)sv_2mortal(sv);
4429 SvPVbyte_force(sv,len);
4430 lex_flags |= LEX_START_COPIED;
4433 TAINT_IF(SvTAINTED(sv));
4434 TAINT_PROPER("eval");
4436 old_savestack_ix = PL_savestack_ix;
4438 lex_start(sv, NULL, lex_flags | (PL_op->op_private & OPpEVAL_UNICODE
4439 ? LEX_IGNORE_UTF8_HINTS
4440 : bytes ? LEX_EVALBYTES : LEX_START_SAME_FILTER
4444 /* switch to eval mode */
4446 if (PERLDB_NAMEEVAL && CopLINE(PL_curcop)) {
4447 SV * const temp_sv = sv_newmortal();
4448 Perl_sv_setpvf(aTHX_ temp_sv, "_<(eval %lu)[%s:%" IVdf "]",
4449 (unsigned long)++PL_evalseq,
4450 CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
4451 tmpbuf = SvPVX(temp_sv);
4452 len = SvCUR(temp_sv);
4455 len = my_snprintf(tmpbuf, sizeof(tbuf), "_<(eval %lu)", (unsigned long)++PL_evalseq);
4456 SAVECOPFILE_FREE(&PL_compiling);
4457 CopFILE_set(&PL_compiling, tmpbuf+2);
4458 SAVECOPLINE(&PL_compiling);
4459 CopLINE_set(&PL_compiling, 1);
4460 /* special case: an eval '' executed within the DB package gets lexically
4461 * placed in the first non-DB CV rather than the current CV - this
4462 * allows the debugger to execute code, find lexicals etc, in the
4463 * scope of the code being debugged. Passing &seq gets find_runcv
4464 * to do the dirty work for us */
4465 runcv = find_runcv(&seq);
4468 cx = cx_pushblock((CXt_EVAL|CXp_REAL), gimme, SP, old_savestack_ix);
4469 cx_pusheval(cx, PL_op->op_next, NULL);
4471 /* prepare to compile string */
4473 if (PERLDB_LINE_OR_SAVESRC && PL_curstash != PL_debstash)
4474 save_lines(CopFILEAV(&PL_compiling), PL_parser->linestr);
4476 /* XXX For C<eval "...">s within BEGIN {} blocks, this ends up
4477 deleting the eval's FILEGV from the stash before gv_check() runs
4478 (i.e. before run-time proper). To work around the coredump that
4479 ensues, we always turn GvMULTI_on for any globals that were
4480 introduced within evals. See force_ident(). GSAR 96-10-12 */
4481 char *const safestr = savepvn(tmpbuf, len);
4482 SAVEDELETE(PL_defstash, safestr, len);
4483 saved_delete = TRUE;
4488 if (doeval_compile(gimme, runcv, seq, saved_hh)) {
4489 if (was != PL_breakable_sub_gen /* Some subs defined here. */
4490 ? PERLDB_LINE_OR_SAVESRC
4491 : PERLDB_SAVESRC_NOSUBS) {
4492 /* Retain the filegv we created. */
4493 } else if (!saved_delete) {
4494 char *const safestr = savepvn(tmpbuf, len);
4495 SAVEDELETE(PL_defstash, safestr, len);
4497 return PL_eval_start;
4499 /* We have already left the scope set up earlier thanks to the LEAVE
4500 in doeval_compile(). */
4501 if (was != PL_breakable_sub_gen /* Some subs defined here. */
4502 ? PERLDB_LINE_OR_SAVESRC
4503 : PERLDB_SAVESRC_INVALID) {
4504 /* Retain the filegv we created. */
4505 } else if (!saved_delete) {
4506 (void)hv_delete(PL_defstash, tmpbuf, len, G_DISCARD);
4508 return PL_op->op_next;
4513 /* also tail-called by pp_return */
4528 assert(CxTYPE(cx) == CXt_EVAL);
4530 oldsp = PL_stack_base + cx->blk_oldsp;
4531 gimme = cx->blk_gimme;
4533 /* did require return a false value? */
4534 failed = CxOLD_OP_TYPE(cx) == OP_REQUIRE
4535 && !(gimme == G_SCALAR
4536 ? SvTRUE_NN(*PL_stack_sp)
4537 : PL_stack_sp > oldsp);
4539 if (gimme == G_VOID) {
4540 PL_stack_sp = oldsp;
4541 /* free now to avoid late-called destructors clobbering $@ */
4545 leave_adjust_stacks(oldsp, oldsp, gimme, 0);
4547 /* the cx_popeval does a leavescope, which frees the optree associated
4548 * with eval, which if it frees the nextstate associated with
4549 * PL_curcop, sets PL_curcop to NULL. Which can mess up freeing a
4550 * regex when running under 'use re Debug' because it needs PL_curcop
4551 * to get the current hints. So restore it early.
4553 PL_curcop = cx->blk_oldcop;
4555 /* grab this value before cx_popeval restores the old PL_in_eval */
4556 keep = cBOOL(PL_in_eval & EVAL_KEEPERR);
4557 retop = cx->blk_eval.retop;
4558 evalcv = cx->blk_eval.cv;
4560 assert(CvDEPTH(evalcv) == 1);
4562 CvDEPTH(evalcv) = 0;
4564 /* pop the CXt_EVAL, and if a require failed, croak */
4565 S_pop_eval_context_maybe_croak(aTHX_ cx, NULL, failed);
4573 /* Common code for Perl_call_sv and Perl_fold_constants, put here to keep it
4574 close to the related Perl_create_eval_scope. */
4576 Perl_delete_eval_scope(pTHX)
4587 /* Common-ish code salvaged from Perl_call_sv and pp_entertry, because it was
4588 also needed by Perl_fold_constants. */
4590 Perl_create_eval_scope(pTHX_ OP *retop, U32 flags)
4593 const U8 gimme = GIMME_V;
4595 cx = cx_pushblock((CXt_EVAL|CXp_TRYBLOCK), gimme,
4596 PL_stack_sp, PL_savestack_ix);
4597 cx_pusheval(cx, retop, NULL);
4599 PL_in_eval = EVAL_INEVAL;
4600 if (flags & G_KEEPERR)
4601 PL_in_eval |= EVAL_KEEPERR;
4604 if (flags & G_FAKINGEVAL) {
4605 PL_eval_root = PL_op; /* Only needed so that goto works right. */
4611 RUN_PP_CATCHABLY(Perl_pp_entertry);
4614 create_eval_scope(cLOGOP->op_other->op_next, 0);
4615 return PL_op->op_next;
4619 /* also tail-called by pp_return */
4631 assert(CxTYPE(cx) == CXt_EVAL);
4632 oldsp = PL_stack_base + cx->blk_oldsp;
4633 gimme = cx->blk_gimme;
4635 if (gimme == G_VOID) {
4636 PL_stack_sp = oldsp;
4637 /* free now to avoid late-called destructors clobbering $@ */
4641 leave_adjust_stacks(oldsp, oldsp, gimme, 1);
4645 retop = cx->blk_eval.retop;
4656 const U8 gimme = GIMME_V;
4660 assert(!PL_op->op_targ); /* used to be set for lexical $_ */
4661 GvSV(PL_defgv) = SvREFCNT_inc(newsv);
4663 cx = cx_pushblock(CXt_GIVEN, gimme, SP, PL_savestack_ix);
4664 cx_pushgiven(cx, origsv);
4674 PERL_UNUSED_CONTEXT;
4677 assert(CxTYPE(cx) == CXt_GIVEN);
4678 oldsp = PL_stack_base + cx->blk_oldsp;
4679 gimme = cx->blk_gimme;
4681 if (gimme == G_VOID)
4682 PL_stack_sp = oldsp;
4684 leave_adjust_stacks(oldsp, oldsp, gimme, 1);
4694 /* Helper routines used by pp_smartmatch */
4696 S_make_matcher(pTHX_ REGEXP *re)
4698 PMOP *matcher = (PMOP *) newPMOP(OP_MATCH, OPf_WANT_SCALAR | OPf_STACKED);
4700 PERL_ARGS_ASSERT_MAKE_MATCHER;
4702 PM_SETRE(matcher, ReREFCNT_inc(re));
4704 SAVEFREEOP((OP *) matcher);
4705 ENTER_with_name("matcher"); SAVETMPS;
4711 S_matcher_matches_sv(pTHX_ PMOP *matcher, SV *sv)
4716 PERL_ARGS_ASSERT_MATCHER_MATCHES_SV;
4718 PL_op = (OP *) matcher;
4721 (void) Perl_pp_match(aTHX);
4723 result = SvTRUEx(POPs);
4730 S_destroy_matcher(pTHX_ PMOP *matcher)
4732 PERL_ARGS_ASSERT_DESTROY_MATCHER;
4733 PERL_UNUSED_ARG(matcher);
4736 LEAVE_with_name("matcher");
4739 /* Do a smart match */
4742 DEBUG_M(Perl_deb(aTHX_ "Starting smart match resolution\n"));
4743 return do_smartmatch(NULL, NULL, 0);
4746 /* This version of do_smartmatch() implements the
4747 * table of smart matches that is found in perlsyn.
4750 S_do_smartmatch(pTHX_ HV *seen_this, HV *seen_other, const bool copied)
4754 bool object_on_left = FALSE;
4755 SV *e = TOPs; /* e is for 'expression' */
4756 SV *d = TOPm1s; /* d is for 'default', as in PL_defgv */
4758 /* Take care only to invoke mg_get() once for each argument.
4759 * Currently we do this by copying the SV if it's magical. */
4761 if (!copied && SvGMAGICAL(d))
4762 d = sv_mortalcopy(d);
4769 e = sv_mortalcopy(e);
4771 /* First of all, handle overload magic of the rightmost argument */
4774 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Object\n"));
4775 DEBUG_M(Perl_deb(aTHX_ " attempting overload\n"));
4777 tmpsv = amagic_call(d, e, smart_amg, AMGf_noleft);
4784 DEBUG_M(Perl_deb(aTHX_ " failed to run overload method; continuing...\n"));
4787 SP -= 2; /* Pop the values */
4792 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-undef\n"));
4799 if (SvROK(e) && SvOBJECT(SvRV(e)) && (SvTYPE(SvRV(e)) != SVt_REGEXP)) {
4800 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Object\n"));
4801 Perl_croak(aTHX_ "Smart matching a non-overloaded object breaks encapsulation");
4803 if (SvROK(d) && SvOBJECT(SvRV(d)) && (SvTYPE(SvRV(d)) != SVt_REGEXP))
4804 object_on_left = TRUE;
4807 if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_PVCV) {
4809 if (object_on_left) {
4810 goto sm_any_sub; /* Treat objects like scalars */
4812 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
4813 /* Test sub truth for each key */
4815 bool andedresults = TRUE;
4816 HV *hv = (HV*) SvRV(d);
4817 I32 numkeys = hv_iterinit(hv);
4818 DEBUG_M(Perl_deb(aTHX_ " applying rule Hash-CodeRef\n"));
4821 while ( (he = hv_iternext(hv)) ) {
4822 DEBUG_M(Perl_deb(aTHX_ " testing hash key...\n"));
4823 ENTER_with_name("smartmatch_hash_key_test");
4826 PUSHs(hv_iterkeysv(he));
4828 c = call_sv(e, G_SCALAR);
4831 andedresults = FALSE;
4833 andedresults = SvTRUEx(POPs) && andedresults;
4835 LEAVE_with_name("smartmatch_hash_key_test");
4842 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
4843 /* Test sub truth for each element */
4845 bool andedresults = TRUE;
4846 AV *av = (AV*) SvRV(d);
4847 const I32 len = av_tindex(av);
4848 DEBUG_M(Perl_deb(aTHX_ " applying rule Array-CodeRef\n"));
4851 for (i = 0; i <= len; ++i) {
4852 SV * const * const svp = av_fetch(av, i, FALSE);
4853 DEBUG_M(Perl_deb(aTHX_ " testing array element...\n"));
4854 ENTER_with_name("smartmatch_array_elem_test");
4860 c = call_sv(e, G_SCALAR);
4863 andedresults = FALSE;
4865 andedresults = SvTRUEx(POPs) && andedresults;
4867 LEAVE_with_name("smartmatch_array_elem_test");
4876 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-CodeRef\n"));
4877 ENTER_with_name("smartmatch_coderef");
4882 c = call_sv(e, G_SCALAR);
4886 else if (SvTEMP(TOPs))
4887 SvREFCNT_inc_void(TOPs);
4889 LEAVE_with_name("smartmatch_coderef");
4894 else if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_PVHV) {
4895 if (object_on_left) {
4896 goto sm_any_hash; /* Treat objects like scalars */
4898 else if (!SvOK(d)) {
4899 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Hash ($a undef)\n"));
4902 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
4903 /* Check that the key-sets are identical */
4905 HV *other_hv = MUTABLE_HV(SvRV(d));
4908 U32 this_key_count = 0,
4909 other_key_count = 0;
4910 HV *hv = MUTABLE_HV(SvRV(e));
4912 DEBUG_M(Perl_deb(aTHX_ " applying rule Hash-Hash\n"));
4913 /* Tied hashes don't know how many keys they have. */
4914 tied = cBOOL(SvTIED_mg((SV*)hv, PERL_MAGIC_tied));
4915 other_tied = cBOOL(SvTIED_mg((const SV *)other_hv, PERL_MAGIC_tied));
4919 HV * const temp = other_hv;
4925 else if(HvUSEDKEYS((const HV *) hv) != HvUSEDKEYS(other_hv))
4929 /* The hashes have the same number of keys, so it suffices
4930 to check that one is a subset of the other. */
4931 (void) hv_iterinit(hv);
4932 while ( (he = hv_iternext(hv)) ) {
4933 SV *key = hv_iterkeysv(he);
4935 DEBUG_M(Perl_deb(aTHX_ " comparing hash key...\n"));
4938 if(!hv_exists_ent(other_hv, key, 0)) {
4939 (void) hv_iterinit(hv); /* reset iterator */
4945 (void) hv_iterinit(other_hv);
4946 while ( hv_iternext(other_hv) )
4950 other_key_count = HvUSEDKEYS(other_hv);
4952 if (this_key_count != other_key_count)
4957 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
4958 AV * const other_av = MUTABLE_AV(SvRV(d));
4959 const SSize_t other_len = av_tindex(other_av) + 1;
4961 HV *hv = MUTABLE_HV(SvRV(e));
4963 DEBUG_M(Perl_deb(aTHX_ " applying rule Array-Hash\n"));
4964 for (i = 0; i < other_len; ++i) {
4965 SV ** const svp = av_fetch(other_av, i, FALSE);
4966 DEBUG_M(Perl_deb(aTHX_ " checking for key existence...\n"));
4967 if (svp) { /* ??? When can this not happen? */
4968 if (hv_exists_ent(hv, *svp, 0))
4974 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_REGEXP) {
4975 DEBUG_M(Perl_deb(aTHX_ " applying rule Regex-Hash\n"));
4978 PMOP * const matcher = make_matcher((REGEXP*) SvRV(d));
4980 HV *hv = MUTABLE_HV(SvRV(e));
4982 (void) hv_iterinit(hv);
4983 while ( (he = hv_iternext(hv)) ) {
4984 DEBUG_M(Perl_deb(aTHX_ " testing key against pattern...\n"));
4986 if (matcher_matches_sv(matcher, hv_iterkeysv(he))) {
4988 (void) hv_iterinit(hv);
4989 destroy_matcher(matcher);
4994 destroy_matcher(matcher);
5000 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Hash\n"));
5001 if (hv_exists_ent(MUTABLE_HV(SvRV(e)), d, 0))
5008 else if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_PVAV) {
5009 if (object_on_left) {
5010 goto sm_any_array; /* Treat objects like scalars */
5012 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
5013 AV * const other_av = MUTABLE_AV(SvRV(e));
5014 const SSize_t other_len = av_tindex(other_av) + 1;
5017 DEBUG_M(Perl_deb(aTHX_ " applying rule Hash-Array\n"));
5018 for (i = 0; i < other_len; ++i) {
5019 SV ** const svp = av_fetch(other_av, i, FALSE);
5021 DEBUG_M(Perl_deb(aTHX_ " testing for key existence...\n"));
5022 if (svp) { /* ??? When can this not happen? */
5023 if (hv_exists_ent(MUTABLE_HV(SvRV(d)), *svp, 0))
5029 if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
5030 AV *other_av = MUTABLE_AV(SvRV(d));
5031 DEBUG_M(Perl_deb(aTHX_ " applying rule Array-Array\n"));
5032 if (av_tindex(MUTABLE_AV(SvRV(e))) != av_tindex(other_av))
5036 const SSize_t other_len = av_tindex(other_av);
5038 if (NULL == seen_this) {
5039 seen_this = newHV();
5040 (void) sv_2mortal(MUTABLE_SV(seen_this));
5042 if (NULL == seen_other) {
5043 seen_other = newHV();
5044 (void) sv_2mortal(MUTABLE_SV(seen_other));
5046 for(i = 0; i <= other_len; ++i) {
5047 SV * const * const this_elem = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
5048 SV * const * const other_elem = av_fetch(other_av, i, FALSE);
5050 if (!this_elem || !other_elem) {
5051 if ((this_elem && SvOK(*this_elem))
5052 || (other_elem && SvOK(*other_elem)))
5055 else if (hv_exists_ent(seen_this,
5056 sv_2mortal(newSViv(PTR2IV(*this_elem))), 0) ||
5057 hv_exists_ent(seen_other,
5058 sv_2mortal(newSViv(PTR2IV(*other_elem))), 0))
5060 if (*this_elem != *other_elem)
5064 (void)hv_store_ent(seen_this,
5065 sv_2mortal(newSViv(PTR2IV(*this_elem))),
5067 (void)hv_store_ent(seen_other,
5068 sv_2mortal(newSViv(PTR2IV(*other_elem))),
5074 DEBUG_M(Perl_deb(aTHX_ " recursively comparing array element...\n"));
5075 (void) do_smartmatch(seen_this, seen_other, 0);
5077 DEBUG_M(Perl_deb(aTHX_ " recursion finished\n"));
5086 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_REGEXP) {
5087 DEBUG_M(Perl_deb(aTHX_ " applying rule Regex-Array\n"));
5090 PMOP * const matcher = make_matcher((REGEXP*) SvRV(d));
5091 const SSize_t this_len = av_tindex(MUTABLE_AV(SvRV(e)));
5094 for(i = 0; i <= this_len; ++i) {
5095 SV * const * const svp = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
5096 DEBUG_M(Perl_deb(aTHX_ " testing element against pattern...\n"));
5098 if (svp && matcher_matches_sv(matcher, *svp)) {
5100 destroy_matcher(matcher);
5105 destroy_matcher(matcher);
5109 else if (!SvOK(d)) {
5110 /* undef ~~ array */
5111 const SSize_t this_len = av_tindex(MUTABLE_AV(SvRV(e)));
5114 DEBUG_M(Perl_deb(aTHX_ " applying rule Undef-Array\n"));
5115 for (i = 0; i <= this_len; ++i) {
5116 SV * const * const svp = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
5117 DEBUG_M(Perl_deb(aTHX_ " testing for undef element...\n"));
5118 if (!svp || !SvOK(*svp))
5127 const SSize_t this_len = av_tindex(MUTABLE_AV(SvRV(e)));
5129 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Array\n"));
5130 for (i = 0; i <= this_len; ++i) {
5131 SV * const * const svp = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
5138 /* infinite recursion isn't supposed to happen here */
5139 DEBUG_M(Perl_deb(aTHX_ " recursively testing array element...\n"));
5140 (void) do_smartmatch(NULL, NULL, 1);
5142 DEBUG_M(Perl_deb(aTHX_ " recursion finished\n"));
5151 else if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_REGEXP) {
5152 if (!object_on_left && SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
5153 SV *t = d; d = e; e = t;
5154 DEBUG_M(Perl_deb(aTHX_ " applying rule Hash-Regex\n"));
5157 else if (!object_on_left && SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
5158 SV *t = d; d = e; e = t;
5159 DEBUG_M(Perl_deb(aTHX_ " applying rule Array-Regex\n"));
5160 goto sm_regex_array;
5163 PMOP * const matcher = make_matcher((REGEXP*) SvRV(e));
5166 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Regex\n"));
5168 result = matcher_matches_sv(matcher, d);
5170 PUSHs(result ? &PL_sv_yes : &PL_sv_no);
5171 destroy_matcher(matcher);
5176 /* See if there is overload magic on left */
5177 else if (object_on_left && SvAMAGIC(d)) {
5179 DEBUG_M(Perl_deb(aTHX_ " applying rule Object-Any\n"));
5180 DEBUG_M(Perl_deb(aTHX_ " attempting overload\n"));
5183 tmpsv = amagic_call(d, e, smart_amg, AMGf_noright);
5191 DEBUG_M(Perl_deb(aTHX_ " failed to run overload method; falling back...\n"));
5194 else if (!SvOK(d)) {
5195 /* undef ~~ scalar ; we already know that the scalar is SvOK */
5196 DEBUG_M(Perl_deb(aTHX_ " applying rule undef-Any\n"));
5201 if (SvNIOK(e) || (SvPOK(e) && looks_like_number(e) && SvNIOK(d))) {
5202 DEBUG_M(if (SvNIOK(e))
5203 Perl_deb(aTHX_ " applying rule Any-Num\n");
5205 Perl_deb(aTHX_ " applying rule Num-numish\n");
5207 /* numeric comparison */
5210 if (CopHINTS_get(PL_curcop) & HINT_INTEGER)
5211 (void) Perl_pp_i_eq(aTHX);
5213 (void) Perl_pp_eq(aTHX);
5221 /* As a last resort, use string comparison */
5222 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Any\n"));
5225 return Perl_pp_seq(aTHX);
5232 const U8 gimme = GIMME_V;
5234 /* This is essentially an optimization: if the match
5235 fails, we don't want to push a context and then
5236 pop it again right away, so we skip straight
5237 to the op that follows the leavewhen.
5238 RETURNOP calls PUTBACK which restores the stack pointer after the POPs.
5240 if (!(PL_op->op_flags & OPf_SPECIAL) && !SvTRUEx(POPs)) {
5241 if (gimme == G_SCALAR)
5242 PUSHs(&PL_sv_undef);
5243 RETURNOP(cLOGOP->op_other->op_next);
5246 cx = cx_pushblock(CXt_WHEN, gimme, SP, PL_savestack_ix);
5260 assert(CxTYPE(cx) == CXt_WHEN);
5261 gimme = cx->blk_gimme;
5263 cxix = dopoptogivenfor(cxstack_ix);
5265 /* diag_listed_as: Can't "when" outside a topicalizer */
5266 DIE(aTHX_ "Can't \"%s\" outside a topicalizer",
5267 PL_op->op_flags & OPf_SPECIAL ? "default" : "when");
5269 oldsp = PL_stack_base + cx->blk_oldsp;
5270 if (gimme == G_VOID)
5271 PL_stack_sp = oldsp;
5273 leave_adjust_stacks(oldsp, oldsp, gimme, 1);
5275 /* pop the WHEN, BLOCK and anything else before the GIVEN/FOR */
5276 assert(cxix < cxstack_ix);
5279 cx = &cxstack[cxix];
5281 if (CxFOREACH(cx)) {
5282 /* emulate pp_next. Note that any stack(s) cleanup will be
5283 * done by the pp_unstack which op_nextop should point to */
5286 PL_curcop = cx->blk_oldcop;
5287 return cx->blk_loop.my_op->op_nextop;
5291 assert(cx->blk_givwhen.leave_op->op_type == OP_LEAVEGIVEN);
5292 return cx->blk_givwhen.leave_op;
5302 cxix = dopoptowhen(cxstack_ix);
5304 DIE(aTHX_ "Can't \"continue\" outside a when block");
5306 if (cxix < cxstack_ix)
5310 assert(CxTYPE(cx) == CXt_WHEN);
5311 PL_stack_sp = PL_stack_base + cx->blk_oldsp;
5315 nextop = cx->blk_givwhen.leave_op->op_next;
5326 cxix = dopoptogivenfor(cxstack_ix);
5328 DIE(aTHX_ "Can't \"break\" outside a given block");
5330 cx = &cxstack[cxix];
5332 DIE(aTHX_ "Can't \"break\" in a loop topicalizer");
5334 if (cxix < cxstack_ix)
5337 /* Restore the sp at the time we entered the given block */
5339 PL_stack_sp = PL_stack_base + cx->blk_oldsp;
5341 return cx->blk_givwhen.leave_op;
5345 S_doparseform(pTHX_ SV *sv)
5348 char *s = SvPV(sv, len);
5350 char *base = NULL; /* start of current field */
5351 I32 skipspaces = 0; /* number of contiguous spaces seen */
5352 bool noblank = FALSE; /* ~ or ~~ seen on this line */
5353 bool repeat = FALSE; /* ~~ seen on this line */
5354 bool postspace = FALSE; /* a text field may need right padding */
5357 U32 *linepc = NULL; /* position of last FF_LINEMARK */
5359 bool ischop; /* it's a ^ rather than a @ */
5360 bool unchopnum = FALSE; /* at least one @ (i.e. non-chop) num field seen */
5361 int maxops = 12; /* FF_LINEMARK + FF_END + 10 (\0 without preceding \n) */
5365 PERL_ARGS_ASSERT_DOPARSEFORM;
5368 Perl_croak(aTHX_ "Null picture in formline");
5370 if (SvTYPE(sv) >= SVt_PVMG) {
5371 /* This might, of course, still return NULL. */
5372 mg = mg_find(sv, PERL_MAGIC_fm);
5374 sv_upgrade(sv, SVt_PVMG);
5378 /* still the same as previously-compiled string? */
5379 SV *old = mg->mg_obj;
5380 if ( !(!!SvUTF8(old) ^ !!SvUTF8(sv))
5381 && len == SvCUR(old)
5382 && strnEQ(SvPVX(old), s, len)
5384 DEBUG_f(PerlIO_printf(Perl_debug_log,"Re-using compiled format\n"));
5388 DEBUG_f(PerlIO_printf(Perl_debug_log, "Re-compiling format\n"));
5389 Safefree(mg->mg_ptr);
5395 DEBUG_f(PerlIO_printf(Perl_debug_log, "Compiling format\n"));
5396 mg = sv_magicext(sv, NULL, PERL_MAGIC_fm, &PL_vtbl_fm, NULL, 0);
5399 sv_copy = newSVpvn_utf8(s, len, SvUTF8(sv));
5400 s = SvPV(sv_copy, len); /* work on the copy, not the original */
5404 /* estimate the buffer size needed */
5405 for (base = s; s <= send; s++) {
5406 if (*s == '\n' || *s == '@' || *s == '^')
5412 Newx(fops, maxops, U32);
5417 *fpc++ = FF_LINEMARK;
5418 noblank = repeat = FALSE;
5436 case ' ': case '\t':
5452 *fpc++ = FF_LITERAL;
5460 *fpc++ = (U32)skipspaces;
5464 *fpc++ = FF_NEWLINE;
5468 arg = fpc - linepc + 1;
5475 *fpc++ = FF_LINEMARK;
5476 noblank = repeat = FALSE;
5485 ischop = s[-1] == '^';
5491 arg = (s - base) - 1;
5493 *fpc++ = FF_LITERAL;
5499 if (*s == '*') { /* @* or ^* */
5501 *fpc++ = 2; /* skip the @* or ^* */
5503 *fpc++ = FF_LINESNGL;
5506 *fpc++ = FF_LINEGLOB;
5508 else if (*s == '#' || (*s == '.' && s[1] == '#')) { /* @###, ^### */
5509 arg = ischop ? FORM_NUM_BLANK : 0;
5514 const char * const f = ++s;
5517 arg |= FORM_NUM_POINT + (s - f);
5519 *fpc++ = s - base; /* fieldsize for FETCH */
5520 *fpc++ = FF_DECIMAL;
5522 unchopnum |= ! ischop;
5524 else if (*s == '0' && s[1] == '#') { /* Zero padded decimals */
5525 arg = ischop ? FORM_NUM_BLANK : 0;
5527 s++; /* skip the '0' first */
5531 const char * const f = ++s;
5534 arg |= FORM_NUM_POINT + (s - f);
5536 *fpc++ = s - base; /* fieldsize for FETCH */
5537 *fpc++ = FF_0DECIMAL;
5539 unchopnum |= ! ischop;
5541 else { /* text field */
5543 bool ismore = FALSE;
5546 while (*++s == '>') ;
5547 prespace = FF_SPACE;
5549 else if (*s == '|') {
5550 while (*++s == '|') ;
5551 prespace = FF_HALFSPACE;
5556 while (*++s == '<') ;
5559 if (*s == '.' && s[1] == '.' && s[2] == '.') {
5563 *fpc++ = s - base; /* fieldsize for FETCH */
5565 *fpc++ = ischop ? FF_CHECKCHOP : FF_CHECKNL;
5568 *fpc++ = (U32)prespace; /* add SPACE or HALFSPACE */
5582 assert (fpc <= fops + maxops); /* ensure our buffer estimate was valid */
5585 mg->mg_ptr = (char *) fops;
5586 mg->mg_len = arg * sizeof(U32);
5587 mg->mg_obj = sv_copy;
5588 mg->mg_flags |= MGf_REFCOUNTED;
5590 if (unchopnum && repeat)
5591 Perl_die(aTHX_ "Repeated format line will never terminate (~~ and @#)");
5598 S_num_overflow(NV value, I32 fldsize, I32 frcsize)
5600 /* Can value be printed in fldsize chars, using %*.*f ? */
5604 int intsize = fldsize - (value < 0 ? 1 : 0);
5606 if (frcsize & FORM_NUM_POINT)
5608 frcsize &= ~(FORM_NUM_POINT|FORM_NUM_BLANK);
5611 while (intsize--) pwr *= 10.0;
5612 while (frcsize--) eps /= 10.0;
5615 if (value + eps >= pwr)
5618 if (value - eps <= -pwr)
5625 S_run_user_filter(pTHX_ int idx, SV *buf_sv, int maxlen)
5627 SV * const datasv = FILTER_DATA(idx);
5628 const int filter_has_file = IoLINES(datasv);
5629 SV * const filter_state = MUTABLE_SV(IoTOP_GV(datasv));
5630 SV * const filter_sub = MUTABLE_SV(IoBOTTOM_GV(datasv));
5635 char *prune_from = NULL;
5636 bool read_from_cache = FALSE;
5640 PERL_ARGS_ASSERT_RUN_USER_FILTER;
5642 assert(maxlen >= 0);
5645 /* I was having segfault trouble under Linux 2.2.5 after a
5646 parse error occurred. (Had to hack around it with a test
5647 for PL_parser->error_count == 0.) Solaris doesn't segfault --
5648 not sure where the trouble is yet. XXX */
5651 SV *const cache = datasv;
5654 const char *cache_p = SvPV(cache, cache_len);
5658 /* Running in block mode and we have some cached data already.
5660 if (cache_len >= umaxlen) {
5661 /* In fact, so much data we don't even need to call
5666 const char *const first_nl =
5667 (const char *)memchr(cache_p, '\n', cache_len);
5669 take = first_nl + 1 - cache_p;
5673 sv_catpvn(buf_sv, cache_p, take);
5674 sv_chop(cache, cache_p + take);
5675 /* Definitely not EOF */
5679 sv_catsv(buf_sv, cache);
5681 umaxlen -= cache_len;
5684 read_from_cache = TRUE;
5688 /* Filter API says that the filter appends to the contents of the buffer.
5689 Usually the buffer is "", so the details don't matter. But if it's not,
5690 then clearly what it contains is already filtered by this filter, so we
5691 don't want to pass it in a second time.
5692 I'm going to use a mortal in case the upstream filter croaks. */
5693 upstream = ((SvOK(buf_sv) && sv_len(buf_sv)) || SvGMAGICAL(buf_sv))
5694 ? sv_newmortal() : buf_sv;
5695 SvUPGRADE(upstream, SVt_PV);
5697 if (filter_has_file) {
5698 status = FILTER_READ(idx+1, upstream, 0);
5701 if (filter_sub && status >= 0) {
5705 ENTER_with_name("call_filter_sub");
5710 DEFSV_set(upstream);
5714 PUSHs(filter_state);
5717 count = call_sv(filter_sub, G_SCALAR|G_EVAL);
5727 SV * const errsv = ERRSV;
5728 if (SvTRUE_NN(errsv))
5729 err = newSVsv(errsv);
5735 LEAVE_with_name("call_filter_sub");
5738 if (SvGMAGICAL(upstream)) {
5740 if (upstream == buf_sv) mg_free(buf_sv);
5742 if (SvIsCOW(upstream)) sv_force_normal(upstream);
5743 if(!err && SvOK(upstream)) {
5744 got_p = SvPV_nomg(upstream, got_len);
5746 if (got_len > umaxlen) {
5747 prune_from = got_p + umaxlen;
5750 char *const first_nl = (char *)memchr(got_p, '\n', got_len);
5751 if (first_nl && first_nl + 1 < got_p + got_len) {
5752 /* There's a second line here... */
5753 prune_from = first_nl + 1;
5757 if (!err && prune_from) {
5758 /* Oh. Too long. Stuff some in our cache. */
5759 STRLEN cached_len = got_p + got_len - prune_from;
5760 SV *const cache = datasv;
5763 /* Cache should be empty. */
5764 assert(!SvCUR(cache));
5767 sv_setpvn(cache, prune_from, cached_len);
5768 /* If you ask for block mode, you may well split UTF-8 characters.
5769 "If it breaks, you get to keep both parts"
5770 (Your code is broken if you don't put them back together again
5771 before something notices.) */
5772 if (SvUTF8(upstream)) {
5775 if (SvPOK(upstream)) SvCUR_set(upstream, got_len - cached_len);
5777 /* Cannot just use sv_setpvn, as that could free the buffer
5778 before we have a chance to assign it. */
5779 sv_usepvn(upstream, savepvn(got_p, got_len - cached_len),
5780 got_len - cached_len);
5782 /* Can't yet be EOF */
5787 /* If they are at EOF but buf_sv has something in it, then they may never
5788 have touched the SV upstream, so it may be undefined. If we naively
5789 concatenate it then we get a warning about use of uninitialised value.
5791 if (!err && upstream != buf_sv &&
5793 sv_catsv_nomg(buf_sv, upstream);
5795 else if (SvOK(upstream)) (void)SvPV_force_nolen(buf_sv);
5798 IoLINES(datasv) = 0;
5800 SvREFCNT_dec(filter_state);
5801 IoTOP_GV(datasv) = NULL;
5804 SvREFCNT_dec(filter_sub);
5805 IoBOTTOM_GV(datasv) = NULL;
5807 filter_del(S_run_user_filter);
5813 if (status == 0 && read_from_cache) {
5814 /* If we read some data from the cache (and by getting here it implies
5815 that we emptied the cache) then we aren't yet at EOF, and mustn't
5816 report that to our caller. */
5823 * ex: set ts=8 sts=4 sw=4 et: