3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4 * 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * Now far ahead the Road has gone,
13 * And I must follow, if I can,
14 * Pursuing it with eager feet,
15 * Until it joins some larger way
16 * Where many paths and errands meet.
17 * And whither then? I cannot say.
19 * [Bilbo on p.35 of _The Lord of the Rings_, I/i: "A Long-Expected Party"]
22 /* This file contains control-oriented pp ("push/pop") functions that
23 * execute the opcodes that make up a perl program. A typical pp function
24 * expects to find its arguments on the stack, and usually pushes its
25 * results onto the stack, hence the 'pp' terminology. Each OP structure
26 * contains a pointer to the relevant pp_foo() function.
28 * Control-oriented means things like pp_enteriter() and pp_next(), which
29 * alter the flow of control of the program.
34 #define PERL_IN_PP_CTL_C
38 #define dopopto_cursub() \
39 (PL_curstackinfo->si_cxsubix >= 0 \
40 ? PL_curstackinfo->si_cxsubix \
41 : dopoptosub_at(cxstack, cxstack_ix))
43 #define dopoptosub(plop) dopoptosub_at(cxstack, (plop))
49 const PERL_CONTEXT *cx;
52 if (PL_op->op_private & OPpOFFBYONE) {
53 if (!(cx = caller_cx(1,NULL))) RETPUSHUNDEF;
56 cxix = dopopto_cursub();
62 switch (cx->blk_gimme) {
81 PMOP *pm = cPMOPx(cLOGOP->op_other);
86 const regexp_engine *eng;
87 bool is_bare_re= FALSE;
89 if (PL_op->op_flags & OPf_STACKED) {
99 /* prevent recompiling under /o and ithreads. */
100 #if defined(USE_ITHREADS)
101 if (pm->op_pmflags & PMf_KEEP && PM_GETRE(pm)) {
108 assert (re != (REGEXP*) &PL_sv_undef);
109 eng = re ? RX_ENGINE(re) : current_re_engine();
111 new_re = (eng->op_comp
113 : &Perl_re_op_compile
114 )(aTHX_ args, nargs, pm->op_code_list, eng, re,
116 (pm->op_pmflags & RXf_PMf_FLAGCOPYMASK),
118 (PL_op->op_flags & OPf_SPECIAL ? PMf_USE_RE_EVAL : 0));
120 if (pm->op_pmflags & PMf_HAS_CV)
121 ReANY(new_re)->qr_anoncv
122 = (CV*) SvREFCNT_inc(PAD_SV(PL_op->op_targ));
126 /* The match's LHS's get-magic might need to access this op's regexp
127 (e.g. $' =~ /$re/ while foo; see bug 70764). So we must call
128 get-magic now before we replace the regexp. Hopefully this hack can
129 be replaced with the approach described at
130 http://www.nntp.perl.org/group/perl.perl5.porters/2007/03/msg122415.html
132 if (pm->op_type == OP_MATCH) {
134 const bool was_tainted = TAINT_get;
135 if (pm->op_flags & OPf_STACKED)
137 else if (pm->op_targ)
138 lhs = PAD_SV(pm->op_targ);
141 /* Restore the previous value of PL_tainted (which may have been
142 modified by get-magic), to avoid incorrectly setting the
143 RXf_TAINTED flag with RX_TAINT_on further down. */
144 TAINT_set(was_tainted);
145 #ifdef NO_TAINT_SUPPORT
146 PERL_UNUSED_VAR(was_tainted);
149 tmp = reg_temp_copy(NULL, new_re);
150 ReREFCNT_dec(new_re);
156 PM_SETRE(pm, new_re);
160 assert(TAINTING_get || !TAINT_get);
162 SvTAINTED_on((SV*)new_re);
166 /* handle the empty pattern */
167 if (!RX_PRELEN(PM_GETRE(pm)) && PL_curpm) {
168 if (PL_curpm == PL_reg_curpm) {
169 if (PL_curpm_under && PL_curpm_under == PL_reg_curpm) {
170 Perl_croak(aTHX_ "Infinite recursion via empty pattern");
175 #if !defined(USE_ITHREADS)
176 /* can't change the optree at runtime either */
177 /* PMf_KEEP is handled differently under threads to avoid these problems */
178 if (pm->op_pmflags & PMf_KEEP) {
179 cLOGOP->op_first->op_next = PL_op->op_next;
191 PERL_CONTEXT *cx = CX_CUR();
192 PMOP * const pm = cPMOPx(cLOGOP->op_other);
193 SV * const dstr = cx->sb_dstr;
196 char *orig = cx->sb_orig;
197 REGEXP * const rx = cx->sb_rx;
199 REGEXP *old = PM_GETRE(pm);
206 PM_SETRE(pm,ReREFCNT_inc(rx));
209 rxres_restore(&cx->sb_rxres, rx);
211 if (cx->sb_iters++) {
212 const SSize_t saviters = cx->sb_iters;
213 if (cx->sb_iters > cx->sb_maxiters)
214 DIE(aTHX_ "Substitution loop");
216 SvGETMAGIC(TOPs); /* possibly clear taint on $1 etc: #67962 */
218 /* See "how taint works": pp_subst() in pp_hot.c */
219 sv_catsv_nomg(dstr, POPs);
220 if (UNLIKELY(TAINT_get))
221 cx->sb_rxtainted |= SUBST_TAINT_REPL;
222 if (CxONCE(cx) || s < orig ||
223 !CALLREGEXEC(rx, s, cx->sb_strend, orig,
224 (s == m), cx->sb_targ, NULL,
225 (REXEC_IGNOREPOS|REXEC_NOT_FIRST|REXEC_FAIL_ON_UNDERFLOW)))
227 SV *targ = cx->sb_targ;
229 assert(cx->sb_strend >= s);
230 if(cx->sb_strend > s) {
231 if (DO_UTF8(dstr) && !SvUTF8(targ))
232 sv_catpvn_nomg_utf8_upgrade(dstr, s, cx->sb_strend - s, nsv);
234 sv_catpvn_nomg(dstr, s, cx->sb_strend - s);
236 if (RX_MATCH_TAINTED(rx)) /* run time pattern taint, eg locale */
237 cx->sb_rxtainted |= SUBST_TAINT_PAT;
239 if (pm->op_pmflags & PMf_NONDESTRUCT) {
241 /* From here on down we're using the copy, and leaving the
242 original untouched. */
246 SV_CHECK_THINKFIRST_COW_DROP(targ);
247 if (isGV(targ)) Perl_croak_no_modify();
249 SvPV_set(targ, SvPVX(dstr));
250 SvCUR_set(targ, SvCUR(dstr));
251 SvLEN_set(targ, SvLEN(dstr));
254 SvPV_set(dstr, NULL);
257 mPUSHi(saviters - 1);
259 (void)SvPOK_only_UTF8(targ);
262 /* update the taint state of various variables in
263 * preparation for final exit.
264 * See "how taint works": pp_subst() in pp_hot.c */
266 if ((cx->sb_rxtainted & SUBST_TAINT_PAT) ||
267 ((cx->sb_rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
268 == (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
270 (RX_MATCH_TAINTED_on(rx)); /* taint $1 et al */
272 if (!(cx->sb_rxtainted & SUBST_TAINT_BOOLRET)
273 && (cx->sb_rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_PAT))
275 SvTAINTED_on(TOPs); /* taint return value */
276 /* needed for mg_set below */
278 cBOOL(cx->sb_rxtainted &
279 (SUBST_TAINT_STR|SUBST_TAINT_PAT|SUBST_TAINT_REPL))
282 /* sv_magic(), when adding magic (e.g.taint magic), also
283 * recalculates any pos() magic, converting any byte offset
284 * to utf8 offset. Make sure pos() is reset before this
285 * happens rather than using the now invalid value (since
286 * we've just replaced targ's pvx buffer with the
287 * potentially shorter dstr buffer). Normally (i.e. in
288 * non-taint cases), pos() gets removed a few lines later
289 * with the SvSETMAGIC().
293 mg = mg_find_mglob(targ);
295 MgBYTEPOS_set(mg, targ, SvPVX(targ), -1);
301 /* PL_tainted must be correctly set for this mg_set */
310 RETURNOP(pm->op_next);
311 NOT_REACHED; /* NOTREACHED */
313 cx->sb_iters = saviters;
315 if (RX_MATCH_COPIED(rx) && RX_SUBBEG(rx) != orig) {
318 assert(!RX_SUBOFFSET(rx));
319 cx->sb_orig = orig = RX_SUBBEG(rx);
321 cx->sb_strend = s + (cx->sb_strend - m);
323 cx->sb_m = m = RX_OFFS(rx)[0].start + orig;
325 if (DO_UTF8(dstr) && !SvUTF8(cx->sb_targ))
326 sv_catpvn_nomg_utf8_upgrade(dstr, s, m - s, nsv);
328 sv_catpvn_nomg(dstr, s, m-s);
330 cx->sb_s = RX_OFFS(rx)[0].end + orig;
331 { /* Update the pos() information. */
333 = (pm->op_pmflags & PMf_NONDESTRUCT) ? cx->sb_dstr : cx->sb_targ;
336 /* the string being matched against may no longer be a string,
337 * e.g. $_=0; s/.../$_++/ge */
340 SvPV_force_nomg_nolen(sv);
342 if (!(mg = mg_find_mglob(sv))) {
343 mg = sv_magicext_mglob(sv);
345 MgBYTEPOS_set(mg, sv, SvPVX(sv), m - orig);
348 (void)ReREFCNT_inc(rx);
349 /* update the taint state of various variables in preparation
350 * for calling the code block.
351 * See "how taint works": pp_subst() in pp_hot.c */
353 if (RX_MATCH_TAINTED(rx)) /* run time pattern taint, eg locale */
354 cx->sb_rxtainted |= SUBST_TAINT_PAT;
356 if ((cx->sb_rxtainted & SUBST_TAINT_PAT) ||
357 ((cx->sb_rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
358 == (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
360 (RX_MATCH_TAINTED_on(rx)); /* taint $1 et al */
362 if (cx->sb_iters > 1 && (cx->sb_rxtainted &
363 (SUBST_TAINT_STR|SUBST_TAINT_PAT|SUBST_TAINT_REPL)))
364 SvTAINTED_on((pm->op_pmflags & PMf_NONDESTRUCT)
365 ? cx->sb_dstr : cx->sb_targ);
368 rxres_save(&cx->sb_rxres, rx);
370 RETURNOP(pm->op_pmstashstartu.op_pmreplstart);
374 Perl_rxres_save(pTHX_ void **rsp, REGEXP *rx)
379 PERL_ARGS_ASSERT_RXRES_SAVE;
382 if (!p || p[1] < RX_NPARENS(rx)) {
384 i = 7 + (RX_NPARENS(rx)+1) * 2;
386 i = 6 + (RX_NPARENS(rx)+1) * 2;
395 /* what (if anything) to free on croak */
396 *p++ = PTR2UV(RX_MATCH_COPIED(rx) ? RX_SUBBEG(rx) : NULL);
397 RX_MATCH_COPIED_off(rx);
398 *p++ = RX_NPARENS(rx);
401 *p++ = PTR2UV(RX_SAVED_COPY(rx));
402 RX_SAVED_COPY(rx) = NULL;
405 *p++ = PTR2UV(RX_SUBBEG(rx));
406 *p++ = (UV)RX_SUBLEN(rx);
407 *p++ = (UV)RX_SUBOFFSET(rx);
408 *p++ = (UV)RX_SUBCOFFSET(rx);
409 for (i = 0; i <= RX_NPARENS(rx); ++i) {
410 *p++ = (UV)RX_OFFS(rx)[i].start;
411 *p++ = (UV)RX_OFFS(rx)[i].end;
416 S_rxres_restore(pTHX_ void **rsp, REGEXP *rx)
421 PERL_ARGS_ASSERT_RXRES_RESTORE;
424 RX_MATCH_COPY_FREE(rx);
425 RX_MATCH_COPIED_set(rx, *p);
427 RX_NPARENS(rx) = *p++;
430 if (RX_SAVED_COPY(rx))
431 SvREFCNT_dec (RX_SAVED_COPY(rx));
432 RX_SAVED_COPY(rx) = INT2PTR(SV*,*p);
436 RX_SUBBEG(rx) = INT2PTR(char*,*p++);
437 RX_SUBLEN(rx) = (I32)(*p++);
438 RX_SUBOFFSET(rx) = (I32)*p++;
439 RX_SUBCOFFSET(rx) = (I32)*p++;
440 for (i = 0; i <= RX_NPARENS(rx); ++i) {
441 RX_OFFS(rx)[i].start = (I32)(*p++);
442 RX_OFFS(rx)[i].end = (I32)(*p++);
447 S_rxres_free(pTHX_ void **rsp)
449 UV * const p = (UV*)*rsp;
451 PERL_ARGS_ASSERT_RXRES_FREE;
455 void *tmp = INT2PTR(char*,*p);
458 U32 i = 9 + p[1] * 2;
460 U32 i = 8 + p[1] * 2;
465 SvREFCNT_dec (INT2PTR(SV*,p[2]));
468 PoisonFree(p, i, sizeof(UV));
477 #define FORM_NUM_BLANK (1<<30)
478 #define FORM_NUM_POINT (1<<29)
482 dSP; dMARK; dORIGMARK;
483 SV * const tmpForm = *++MARK;
484 SV *formsv; /* contains text of original format */
485 U32 *fpc; /* format ops program counter */
486 char *t; /* current append position in target string */
487 const char *f; /* current position in format string */
489 SV *sv = NULL; /* current item */
490 const char *item = NULL;/* string value of current item */
491 I32 itemsize = 0; /* length (chars) of item, possibly truncated */
492 I32 itembytes = 0; /* as itemsize, but length in bytes */
493 I32 fieldsize = 0; /* width of current field */
494 I32 lines = 0; /* number of lines that have been output */
495 bool chopspace = (strchr(PL_chopset, ' ') != NULL); /* does $: have space */
496 const char *chophere = NULL; /* where to chop current item */
497 STRLEN linemark = 0; /* pos of start of line in output */
499 bool gotsome = FALSE; /* seen at least one non-blank item on this line */
500 STRLEN len; /* length of current sv */
501 STRLEN linemax; /* estimate of output size in bytes */
502 bool item_is_utf8 = FALSE;
503 bool targ_is_utf8 = FALSE;
506 U8 *source; /* source of bytes to append */
507 STRLEN to_copy; /* how may bytes to append */
508 char trans; /* what chars to translate */
509 bool copied_form = FALSE; /* have we duplicated the form? */
511 mg = doparseform(tmpForm);
513 fpc = (U32*)mg->mg_ptr;
514 /* the actual string the format was compiled from.
515 * with overload etc, this may not match tmpForm */
519 SvPV_force(PL_formtarget, len);
520 if (SvTAINTED(tmpForm) || SvTAINTED(formsv))
521 SvTAINTED_on(PL_formtarget);
522 if (DO_UTF8(PL_formtarget))
524 /* this is an initial estimate of how much output buffer space
525 * to allocate. It may be exceeded later */
526 linemax = (SvCUR(formsv) * (IN_BYTES ? 1 : 3) + 1);
527 t = SvGROW(PL_formtarget, len + linemax + 1);
528 /* XXX from now onwards, SvCUR(PL_formtarget) is invalid */
530 f = SvPV_const(formsv, len);
534 const char *name = "???";
537 case FF_LITERAL: arg = fpc[1]; name = "LITERAL"; break;
538 case FF_BLANK: arg = fpc[1]; name = "BLANK"; break;
539 case FF_SKIP: arg = fpc[1]; name = "SKIP"; break;
540 case FF_FETCH: arg = fpc[1]; name = "FETCH"; break;
541 case FF_DECIMAL: arg = fpc[1]; name = "DECIMAL"; break;
543 case FF_CHECKNL: name = "CHECKNL"; break;
544 case FF_CHECKCHOP: name = "CHECKCHOP"; break;
545 case FF_SPACE: name = "SPACE"; break;
546 case FF_HALFSPACE: name = "HALFSPACE"; break;
547 case FF_ITEM: name = "ITEM"; break;
548 case FF_CHOP: name = "CHOP"; break;
549 case FF_LINEGLOB: name = "LINEGLOB"; break;
550 case FF_NEWLINE: name = "NEWLINE"; break;
551 case FF_MORE: name = "MORE"; break;
552 case FF_LINEMARK: name = "LINEMARK"; break;
553 case FF_END: name = "END"; break;
554 case FF_0DECIMAL: name = "0DECIMAL"; break;
555 case FF_LINESNGL: name = "LINESNGL"; break;
558 PerlIO_printf(Perl_debug_log, "%-16s%ld\n", name, (long) arg);
560 PerlIO_printf(Perl_debug_log, "%-16s\n", name);
563 case FF_LINEMARK: /* start (or end) of a line */
564 linemark = t - SvPVX(PL_formtarget);
569 case FF_LITERAL: /* append <arg> literal chars */
574 item_is_utf8 = (targ_is_utf8)
575 ? cBOOL(DO_UTF8(formsv))
576 : cBOOL(SvUTF8(formsv));
579 case FF_SKIP: /* skip <arg> chars in format */
583 case FF_FETCH: /* get next item and set field size to <arg> */
592 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "Not enough format arguments");
595 SvTAINTED_on(PL_formtarget);
598 case FF_CHECKNL: /* find max len of item (up to \n) that fits field */
600 const char *s = item = SvPV_const(sv, len);
601 const char *send = s + len;
604 item_is_utf8 = DO_UTF8(sv);
616 if (itemsize == fieldsize)
619 itembytes = s - item;
624 case FF_CHECKCHOP: /* like CHECKNL, but up to highest split point */
626 const char *s = item = SvPV_const(sv, len);
627 const char *send = s + len;
631 item_is_utf8 = DO_UTF8(sv);
633 /* look for a legal split position */
641 /* provisional split point */
645 /* we delay testing fieldsize until after we've
646 * processed the possible split char directly
647 * following the last field char; so if fieldsize=3
648 * and item="a b cdef", we consume "a b", not "a".
649 * Ditto further down.
651 if (size == fieldsize)
655 if (size == fieldsize)
657 if (strchr(PL_chopset, *s)) {
658 /* provisional split point */
659 /* for a non-space split char, we include
660 * the split char; hence the '+1' */
674 if (!chophere || s == send) {
678 itembytes = chophere - item;
683 case FF_SPACE: /* append padding space (diff of field, item size) */
684 arg = fieldsize - itemsize;
692 case FF_HALFSPACE: /* like FF_SPACE, but only append half as many */
693 arg = fieldsize - itemsize;
702 case FF_ITEM: /* append a text item, while blanking ctrl chars */
708 case FF_CHOP: /* (for ^*) chop the current item */
709 if (sv != &PL_sv_no) {
710 const char *s = chophere;
712 ((sv == tmpForm || SvSMAGICAL(sv))
713 || (SvGMAGICAL(tmpForm) && !sv_only_taint_gmagic(tmpForm))) ) {
714 /* sv and tmpForm are either the same SV, or magic might allow modification
715 of tmpForm when sv is modified, so copy */
716 SV *newformsv = sv_mortalcopy(formsv);
719 f = SvPV_nolen(newformsv) + (f - SvPV_nolen(formsv));
720 Newx(new_compiled, mg->mg_len / sizeof(U32), U32);
721 memcpy(new_compiled, mg->mg_ptr, mg->mg_len);
722 SAVEFREEPV(new_compiled);
723 fpc = new_compiled + (fpc - (U32*)mg->mg_ptr);
735 /* tied, overloaded or similar strangeness.
736 * Do it the hard way */
737 sv_setpvn(sv, s, len - (s-item));
743 case FF_LINESNGL: /* process ^* */
747 case FF_LINEGLOB: /* process @* */
749 const bool oneline = fpc[-1] == FF_LINESNGL;
750 const char *s = item = SvPV_const(sv, len);
751 const char *const send = s + len;
753 item_is_utf8 = DO_UTF8(sv);
764 to_copy = s - item - 1;
778 /* append to_copy bytes from source to PL_formstring.
779 * item_is_utf8 implies source is utf8.
780 * if trans, translate certain characters during the copy */
785 SvCUR_set(PL_formtarget,
786 t - SvPVX_const(PL_formtarget));
788 if (targ_is_utf8 && !item_is_utf8) {
789 source = tmp = bytes_to_utf8(source, &to_copy);
792 if (item_is_utf8 && !targ_is_utf8) {
794 /* Upgrade targ to UTF8, and then we reduce it to
795 a problem we have a simple solution for.
796 Don't need get magic. */
797 sv_utf8_upgrade_nomg(PL_formtarget);
799 /* re-calculate linemark */
800 s = (U8*)SvPVX(PL_formtarget);
801 /* the bytes we initially allocated to append the
802 * whole line may have been gobbled up during the
803 * upgrade, so allocate a whole new line's worth
807 s += UTF8_SAFE_SKIP(s,
808 (U8 *) SvEND(PL_formtarget));
809 linemark = s - (U8*)SvPVX(PL_formtarget);
811 /* Easy. They agree. */
812 assert (item_is_utf8 == targ_is_utf8);
815 /* @* and ^* are the only things that can exceed
816 * the linemax, so grow by the output size, plus
817 * a whole new form's worth in case of any further
819 grow = linemax + to_copy;
821 SvGROW(PL_formtarget, SvCUR(PL_formtarget) + grow + 1);
822 t = SvPVX(PL_formtarget) + SvCUR(PL_formtarget);
824 Copy(source, t, to_copy, char);
826 /* blank out ~ or control chars, depending on trans.
827 * works on bytes not chars, so relies on not
828 * matching utf8 continuation bytes */
830 U8 *send = s + to_copy;
833 if (trans == '~' ? (ch == '~') : isCNTRL(ch))
840 SvCUR_set(PL_formtarget, SvCUR(PL_formtarget) + to_copy);
846 case FF_0DECIMAL: /* like FF_DECIMAL but for 0### */
849 ((arg & FORM_NUM_POINT) ? "%#0*.*" NVff : "%0*.*" NVff);
852 case FF_DECIMAL: /* do @##, ^##, where <arg>=(precision|flags) */
855 ((arg & FORM_NUM_POINT) ? "%#*.*" NVff : "%*.*" NVff);
857 /* If the field is marked with ^ and the value is undefined,
859 if ((arg & FORM_NUM_BLANK) && !SvOK(sv)) {
867 /* overflow evidence */
868 if (num_overflow(value, fieldsize, arg)) {
874 /* Formats aren't yet marked for locales, so assume "yes". */
876 Size_t max = SvLEN(PL_formtarget) - (t - SvPVX(PL_formtarget));
878 DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
879 STORE_LC_NUMERIC_SET_TO_NEEDED();
880 arg &= ~(FORM_NUM_POINT|FORM_NUM_BLANK);
884 if (!quadmath_format_valid(fmt))
885 Perl_croak_nocontext("panic: quadmath invalid format \"%s\"", fmt);
886 len = quadmath_snprintf(t, max, fmt, (int) fieldsize, (int) arg, value);
888 Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", fmt);
891 /* we generate fmt ourselves so it is safe */
892 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
893 len = my_snprintf(t, max, fmt, (int) fieldsize, (int) arg, value);
894 GCC_DIAG_RESTORE_STMT;
896 PERL_MY_SNPRINTF_POST_GUARD(len, max);
897 RESTORE_LC_NUMERIC();
902 case FF_NEWLINE: /* delete trailing spaces, then append \n */
904 while (t-- > (SvPVX(PL_formtarget) + linemark) && *t == ' ') ;
909 case FF_BLANK: /* for arg==0: do '~'; for arg>0 : do '~~' */
912 if (arg) { /* repeat until fields exhausted? */
918 t = SvPVX(PL_formtarget) + linemark;
923 case FF_MORE: /* replace long end of string with '...' */
925 const char *s = chophere;
926 const char *send = item + len;
928 while (isSPACE(*s) && (s < send))
933 arg = fieldsize - itemsize;
940 if (strBEGINs(s1," ")) {
941 while (s1 > SvPVX_const(PL_formtarget) && isSPACE(s1[-1]))
951 case FF_END: /* tidy up, then return */
953 assert(t < SvPVX_const(PL_formtarget) + SvLEN(PL_formtarget));
955 SvCUR_set(PL_formtarget, t - SvPVX_const(PL_formtarget));
957 SvUTF8_on(PL_formtarget);
958 FmLINES(PL_formtarget) += lines;
960 if (fpc[-1] == FF_BLANK)
961 RETURNOP(cLISTOP->op_first);
968 /* also used for: pp_mapstart() */
974 if (PL_stack_base + TOPMARK == SP) {
976 if (GIMME_V == G_SCALAR)
978 RETURNOP(PL_op->op_next->op_next);
980 PL_stack_sp = PL_stack_base + TOPMARK + 1;
981 Perl_pp_pushmark(aTHX); /* push dst */
982 Perl_pp_pushmark(aTHX); /* push src */
983 ENTER_with_name("grep"); /* enter outer scope */
987 ENTER_with_name("grep_item"); /* enter inner scope */
990 src = PL_stack_base[TOPMARK];
992 src = PL_stack_base[TOPMARK] = sv_mortalcopy(src);
999 if (PL_op->op_type == OP_MAPSTART)
1000 Perl_pp_pushmark(aTHX); /* push top */
1001 return cLOGOPx(PL_op->op_next)->op_other;
1004 /* pp_grepwhile() lives in pp_hot.c */
1009 const U8 gimme = GIMME_V;
1010 I32 items = (SP - PL_stack_base) - TOPMARK; /* how many new items */
1016 /* first, move source pointer to the next item in the source list */
1017 ++PL_markstack_ptr[-1];
1019 /* if there are new items, push them into the destination list */
1020 if (items && gimme != G_VOID) {
1021 /* might need to make room back there first */
1022 if (items > PL_markstack_ptr[-1] - PL_markstack_ptr[-2]) {
1023 /* XXX this implementation is very pessimal because the stack
1024 * is repeatedly extended for every set of items. Is possible
1025 * to do this without any stack extension or copying at all
1026 * by maintaining a separate list over which the map iterates
1027 * (like foreach does). --gsar */
1029 /* everything in the stack after the destination list moves
1030 * towards the end the stack by the amount of room needed */
1031 shift = items - (PL_markstack_ptr[-1] - PL_markstack_ptr[-2]);
1033 /* items to shift up (accounting for the moved source pointer) */
1034 count = (SP - PL_stack_base) - (PL_markstack_ptr[-1] - 1);
1036 /* This optimization is by Ben Tilly and it does
1037 * things differently from what Sarathy (gsar)
1038 * is describing. The downside of this optimization is
1039 * that leaves "holes" (uninitialized and hopefully unused areas)
1040 * to the Perl stack, but on the other hand this
1041 * shouldn't be a problem. If Sarathy's idea gets
1042 * implemented, this optimization should become
1043 * irrelevant. --jhi */
1045 shift = count; /* Avoid shifting too often --Ben Tilly */
1049 dst = (SP += shift);
1050 PL_markstack_ptr[-1] += shift;
1051 *PL_markstack_ptr += shift;
1055 /* copy the new items down to the destination list */
1056 dst = PL_stack_base + (PL_markstack_ptr[-2] += items) - 1;
1057 if (gimme == G_LIST) {
1058 /* add returned items to the collection (making mortal copies
1059 * if necessary), then clear the current temps stack frame
1060 * *except* for those items. We do this splicing the items
1061 * into the start of the tmps frame (so some items may be on
1062 * the tmps stack twice), then moving PL_tmps_floor above
1063 * them, then freeing the frame. That way, the only tmps that
1064 * accumulate over iterations are the return values for map.
1065 * We have to do to this way so that everything gets correctly
1066 * freed if we die during the map.
1070 /* make space for the slice */
1071 EXTEND_MORTAL(items);
1072 tmpsbase = PL_tmps_floor + 1;
1073 Move(PL_tmps_stack + tmpsbase,
1074 PL_tmps_stack + tmpsbase + items,
1075 PL_tmps_ix - PL_tmps_floor,
1077 PL_tmps_ix += items;
1082 sv = sv_mortalcopy(sv);
1084 PL_tmps_stack[tmpsbase++] = SvREFCNT_inc_simple(sv);
1086 /* clear the stack frame except for the items */
1087 PL_tmps_floor += items;
1089 /* FREETMPS may have cleared the TEMP flag on some of the items */
1092 SvTEMP_on(PL_tmps_stack[--tmpsbase]);
1095 /* scalar context: we don't care about which values map returns
1096 * (we use undef here). And so we certainly don't want to do mortal
1097 * copies of meaningless values. */
1098 while (items-- > 0) {
1100 *dst-- = &PL_sv_undef;
1108 LEAVE_with_name("grep_item"); /* exit inner scope */
1111 if (PL_markstack_ptr[-1] > TOPMARK) {
1113 (void)POPMARK; /* pop top */
1114 LEAVE_with_name("grep"); /* exit outer scope */
1115 (void)POPMARK; /* pop src */
1116 items = --*PL_markstack_ptr - PL_markstack_ptr[-1];
1117 (void)POPMARK; /* pop dst */
1118 SP = PL_stack_base + POPMARK; /* pop original mark */
1119 if (gimme == G_SCALAR) {
1123 else if (gimme == G_LIST)
1130 ENTER_with_name("grep_item"); /* enter inner scope */
1133 /* set $_ to the new source item */
1134 src = PL_stack_base[PL_markstack_ptr[-1]];
1135 if (SvPADTMP(src)) {
1136 src = sv_mortalcopy(src);
1141 RETURNOP(cLOGOP->op_other);
1150 if (GIMME_V == G_LIST)
1153 if (SvTRUE_NN(targ))
1154 return cLOGOP->op_other;
1163 if (GIMME_V == G_LIST) {
1164 RETURNOP(cLOGOPx(cUNOP->op_first)->op_other);
1168 SV * const targ = PAD_SV(PL_op->op_targ);
1171 if (PL_op->op_private & OPpFLIP_LINENUM) {
1172 if (GvIO(PL_last_in_gv)) {
1173 flip = SvIV(sv) == (IV)IoLINES(GvIOp(PL_last_in_gv));
1176 GV * const gv = gv_fetchpvs(".", GV_ADD|GV_NOTQUAL, SVt_PV);
1178 flip = SvIV(sv) == SvIV(GvSV(gv));
1181 flip = SvTRUE_NN(sv);
1184 sv_setiv(PAD_SV(cUNOP->op_first->op_targ), 1);
1185 if (PL_op->op_flags & OPf_SPECIAL) {
1193 RETURNOP(cLOGOPx(cUNOP->op_first)->op_other);
1202 /* This code tries to decide if "$left .. $right" should use the
1203 magical string increment, or if the range is numeric. Initially,
1204 an exception was made for *any* string beginning with "0" (see
1205 [#18165], AMS 20021031), but now that is only applied when the
1206 string's length is also >1 - see the rules now documented in
1209 #define RANGE_IS_NUMERIC(left,right) ( \
1210 SvNIOKp(left) || (SvOK(left) && !SvPOKp(left)) || \
1211 SvNIOKp(right) || (SvOK(right) && !SvPOKp(right)) || \
1212 (((!SvOK(left) && SvOK(right)) || ((!SvOK(left) || \
1213 looks_like_number(left)) && SvPOKp(left) \
1214 && !(*SvPVX_const(left) == '0' && SvCUR(left)>1 ) )) \
1215 && (!SvOK(right) || looks_like_number(right))))
1221 if (GIMME_V == G_LIST) {
1227 if (RANGE_IS_NUMERIC(left,right)) {
1229 if ((SvOK(left) && !SvIOK(left) && SvNV_nomg(left) < IV_MIN) ||
1230 (SvOK(right) && (SvIOK(right)
1231 ? SvIsUV(right) && SvUV(right) > IV_MAX
1232 : SvNV_nomg(right) > (NV) IV_MAX)))
1233 DIE(aTHX_ "Range iterator outside integer range");
1234 i = SvIV_nomg(left);
1235 j = SvIV_nomg(right);
1237 /* Dance carefully around signed max. */
1238 bool overflow = (i <= 0 && j > SSize_t_MAX + i - 1);
1241 /* The wraparound of signed integers is undefined
1242 * behavior, but here we aim for count >=1, and
1243 * negative count is just wrong. */
1245 #if IVSIZE > Size_t_size
1252 Perl_croak(aTHX_ "Out of memory during list extend");
1259 SV * const sv = sv_2mortal(newSViv(i));
1261 if (n) /* avoid incrementing above IV_MAX */
1267 const char * const lpv = SvPV_nomg_const(left, llen);
1268 const char * const tmps = SvPV_nomg_const(right, len);
1270 SV *sv = newSVpvn_flags(lpv, llen, SvUTF8(left)|SVs_TEMP);
1271 if (DO_UTF8(right) && IN_UNI_8_BIT)
1272 len = sv_len_utf8_nomg(right);
1273 while (!SvNIOKp(sv) && SvCUR(sv) <= len) {
1275 if (strEQ(SvPVX_const(sv),tmps))
1277 sv = sv_2mortal(newSVsv(sv));
1284 SV * const targ = PAD_SV(cUNOP->op_first->op_targ);
1288 if (PL_op->op_private & OPpFLIP_LINENUM) {
1289 if (GvIO(PL_last_in_gv)) {
1290 flop = SvIV(sv) == (IV)IoLINES(GvIOp(PL_last_in_gv));
1293 GV * const gv = gv_fetchpvs(".", GV_ADD|GV_NOTQUAL, SVt_PV);
1294 if (gv && GvSV(gv)) flop = SvIV(sv) == SvIV(GvSV(gv));
1298 flop = SvTRUE_NN(sv);
1302 sv_setiv(PAD_SV(cUNOPx(cUNOP->op_first)->op_first->op_targ), 0);
1303 sv_catpvs(targ, "E0");
1313 static const char * const context_name[] = {
1315 NULL, /* CXt_WHEN never actually needs "block" */
1316 NULL, /* CXt_BLOCK never actually needs "block" */
1317 NULL, /* CXt_GIVEN never actually needs "block" */
1318 NULL, /* CXt_LOOP_PLAIN never actually needs "loop" */
1319 NULL, /* CXt_LOOP_LAZYIV never actually needs "loop" */
1320 NULL, /* CXt_LOOP_LAZYSV never actually needs "loop" */
1321 NULL, /* CXt_LOOP_LIST never actually needs "loop" */
1322 NULL, /* CXt_LOOP_ARY never actually needs "loop" */
1331 S_dopoptolabel(pTHX_ const char *label, STRLEN len, U32 flags)
1335 PERL_ARGS_ASSERT_DOPOPTOLABEL;
1337 for (i = cxstack_ix; i >= 0; i--) {
1338 const PERL_CONTEXT * const cx = &cxstack[i];
1339 switch (CxTYPE(cx)) {
1348 /* diag_listed_as: Exiting subroutine via %s */
1349 Perl_ck_warner(aTHX_ packWARN(WARN_EXITING), "Exiting %s via %s",
1350 context_name[CxTYPE(cx)], OP_NAME(PL_op));
1351 if (CxTYPE(cx) == CXt_NULL) /* sort BLOCK */
1354 case CXt_LOOP_PLAIN:
1355 case CXt_LOOP_LAZYIV:
1356 case CXt_LOOP_LAZYSV:
1360 STRLEN cx_label_len = 0;
1361 U32 cx_label_flags = 0;
1362 const char *cx_label = CxLABEL_len_flags(cx, &cx_label_len, &cx_label_flags);
1364 ( (cx_label_flags & SVf_UTF8) != (flags & SVf_UTF8) ) ?
1367 (const U8*)cx_label, cx_label_len,
1368 (const U8*)label, len) == 0)
1370 (const U8*)label, len,
1371 (const U8*)cx_label, cx_label_len) == 0)
1372 : (len == cx_label_len && ((cx_label == label)
1373 || memEQ(cx_label, label, len))) )) {
1374 DEBUG_l(Perl_deb(aTHX_ "(poptolabel(): skipping label at cx=%ld %s)\n",
1375 (long)i, cx_label));
1378 DEBUG_l( Perl_deb(aTHX_ "(poptolabel(): found label at cx=%ld %s)\n", (long)i, label));
1387 =for apidoc_section $callback
1388 =for apidoc dowantarray
1390 Implements the deprecated L<perlapi/C<GIMME>>.
1396 Perl_dowantarray(pTHX)
1398 const U8 gimme = block_gimme();
1399 return (gimme == G_VOID) ? G_SCALAR : gimme;
1402 /* note that this function has mostly been superseded by Perl_gimme_V */
1405 Perl_block_gimme(pTHX)
1407 const I32 cxix = dopopto_cursub();
1412 gimme = (cxstack[cxix].blk_gimme & G_WANT);
1414 Perl_croak(aTHX_ "panic: bad gimme: %d\n", gimme);
1419 =for apidoc is_lvalue_sub
1421 Returns non-zero if the sub calling this function is being called in an lvalue
1422 context. Returns 0 otherwise.
1428 Perl_is_lvalue_sub(pTHX)
1430 const I32 cxix = dopopto_cursub();
1431 assert(cxix >= 0); /* We should only be called from inside subs */
1433 if (CxLVAL(cxstack + cxix) && CvLVALUE(cxstack[cxix].blk_sub.cv))
1434 return CxLVAL(cxstack + cxix);
1439 /* only used by cx_pushsub() */
1441 Perl_was_lvalue_sub(pTHX)
1443 const I32 cxix = dopoptosub(cxstack_ix-1);
1444 assert(cxix >= 0); /* We should only be called from inside subs */
1446 if (CxLVAL(cxstack + cxix) && CvLVALUE(cxstack[cxix].blk_sub.cv))
1447 return CxLVAL(cxstack + cxix);
1453 S_dopoptosub_at(pTHX_ const PERL_CONTEXT *cxstk, I32 startingblock)
1457 PERL_ARGS_ASSERT_DOPOPTOSUB_AT;
1459 PERL_UNUSED_CONTEXT;
1462 for (i = startingblock; i >= 0; i--) {
1463 const PERL_CONTEXT * const cx = &cxstk[i];
1464 switch (CxTYPE(cx)) {
1468 /* in sub foo { /(?{...})/ }, foo ends up on the CX stack
1469 * twice; the first for the normal foo() call, and the second
1470 * for a faked up re-entry into the sub to execute the
1471 * code block. Hide this faked entry from the world. */
1472 if (cx->cx_type & CXp_SUB_RE_FAKE)
1474 DEBUG_l( Perl_deb(aTHX_ "(dopoptosub_at(): found sub at cx=%ld)\n", (long)i));
1480 DEBUG_l( Perl_deb(aTHX_ "(dopoptosub_at(): found sub at cx=%ld)\n", (long)i));
1484 DEBUG_l( Perl_deb(aTHX_ "(dopoptosub_at(): found sub at cx=%ld)\n", (long)i));
1492 S_dopoptoeval(pTHX_ I32 startingblock)
1495 for (i = startingblock; i >= 0; i--) {
1496 const PERL_CONTEXT *cx = &cxstack[i];
1497 switch (CxTYPE(cx)) {
1501 DEBUG_l( Perl_deb(aTHX_ "(dopoptoeval(): found eval at cx=%ld)\n", (long)i));
1509 S_dopoptoloop(pTHX_ I32 startingblock)
1512 for (i = startingblock; i >= 0; i--) {
1513 const PERL_CONTEXT * const cx = &cxstack[i];
1514 switch (CxTYPE(cx)) {
1523 /* diag_listed_as: Exiting subroutine via %s */
1524 Perl_ck_warner(aTHX_ packWARN(WARN_EXITING), "Exiting %s via %s",
1525 context_name[CxTYPE(cx)], OP_NAME(PL_op));
1526 if ((CxTYPE(cx)) == CXt_NULL) /* sort BLOCK */
1529 case CXt_LOOP_PLAIN:
1530 case CXt_LOOP_LAZYIV:
1531 case CXt_LOOP_LAZYSV:
1534 DEBUG_l( Perl_deb(aTHX_ "(dopoptoloop(): found loop at cx=%ld)\n", (long)i));
1541 /* find the next GIVEN or FOR (with implicit $_) loop context block */
1544 S_dopoptogivenfor(pTHX_ I32 startingblock)
1547 for (i = startingblock; i >= 0; i--) {
1548 const PERL_CONTEXT *cx = &cxstack[i];
1549 switch (CxTYPE(cx)) {
1553 DEBUG_l( Perl_deb(aTHX_ "(dopoptogivenfor(): found given at cx=%ld)\n", (long)i));
1555 case CXt_LOOP_PLAIN:
1556 assert(!(cx->cx_type & CXp_FOR_DEF));
1558 case CXt_LOOP_LAZYIV:
1559 case CXt_LOOP_LAZYSV:
1562 if (cx->cx_type & CXp_FOR_DEF) {
1563 DEBUG_l( Perl_deb(aTHX_ "(dopoptogivenfor(): found foreach at cx=%ld)\n", (long)i));
1572 S_dopoptowhen(pTHX_ I32 startingblock)
1575 for (i = startingblock; i >= 0; i--) {
1576 const PERL_CONTEXT *cx = &cxstack[i];
1577 switch (CxTYPE(cx)) {
1581 DEBUG_l( Perl_deb(aTHX_ "(dopoptowhen(): found when at cx=%ld)\n", (long)i));
1588 /* dounwind(): pop all contexts above (but not including) cxix.
1589 * Note that it clears the savestack frame associated with each popped
1590 * context entry, but doesn't free any temps.
1591 * It does a cx_popblock() of the last frame that it pops, and leaves
1592 * cxstack_ix equal to cxix.
1596 Perl_dounwind(pTHX_ I32 cxix)
1598 if (!PL_curstackinfo) /* can happen if die during thread cloning */
1601 while (cxstack_ix > cxix) {
1602 PERL_CONTEXT *cx = CX_CUR();
1604 CX_DEBUG(cx, "UNWIND");
1605 /* Note: we don't need to restore the base context info till the end. */
1609 switch (CxTYPE(cx)) {
1612 /* CXt_SUBST is not a block context type, so skip the
1613 * cx_popblock(cx) below */
1614 if (cxstack_ix == cxix + 1) {
1625 case CXt_LOOP_PLAIN:
1626 case CXt_LOOP_LAZYIV:
1627 case CXt_LOOP_LAZYSV:
1641 /* these two don't have a POPFOO() */
1647 if (cxstack_ix == cxix + 1) {
1656 Perl_qerror(pTHX_ SV *err)
1658 PERL_ARGS_ASSERT_QERROR;
1661 if (PL_in_eval & EVAL_KEEPERR) {
1662 Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "\t(in cleanup) %" SVf,
1666 sv_catsv(ERRSV, err);
1669 sv_catsv(PL_errors, err);
1671 Perl_warn(aTHX_ "%" SVf, SVfARG(err));
1673 ++PL_parser->error_count;
1678 /* pop a CXt_EVAL context and in addition, if it was a require then
1680 * 0: do nothing extra;
1681 * 1: undef $INC{$name}; croak "$name did not return a true value";
1682 * 2: delete $INC{$name}; croak "$errsv: Compilation failed in require"
1686 S_pop_eval_context_maybe_croak(pTHX_ PERL_CONTEXT *cx, SV *errsv, int action)
1688 SV *namesv = NULL; /* init to avoid dumb compiler warning */
1692 do_croak = action && (CxOLD_OP_TYPE(cx) == OP_REQUIRE);
1694 /* keep namesv alive after cx_popeval() */
1695 namesv = cx->blk_eval.old_namesv;
1696 cx->blk_eval.old_namesv = NULL;
1705 HV *inc_hv = GvHVn(PL_incgv);
1708 (void)hv_delete_ent(inc_hv, namesv, G_DISCARD, 0);
1709 fmt = "%" SVf " did not return a true value";
1713 (void)hv_store_ent(inc_hv, namesv, &PL_sv_undef, 0);
1714 fmt = "%" SVf "Compilation failed in require";
1716 errsv = newSVpvs_flags("Unknown error\n", SVs_TEMP);
1719 Perl_croak(aTHX_ fmt, SVfARG(errsv));
1724 /* die_unwind(): this is the final destination for the various croak()
1725 * functions. If we're in an eval, unwind the context and other stacks
1726 * back to the top-most CXt_EVAL and set $@ to msv; otherwise print msv
1727 * to STDERR and initiate an exit. Note that if the CXt_EVAL popped back
1728 * to is a require the exception will be rethrown, as requires don't
1729 * actually trap exceptions.
1733 Perl_die_unwind(pTHX_ SV *msv)
1736 U8 in_eval = PL_in_eval;
1737 PERL_ARGS_ASSERT_DIE_UNWIND;
1742 /* We need to keep this SV alive through all the stack unwinding
1743 * and FREETMPSing below, while ensuing that it doesn't leak
1744 * if we call out to something which then dies (e.g. sub STORE{die}
1745 * when unlocalising a tied var). So we do a dance with
1746 * mortalising and SAVEFREEing.
1748 if (PL_phase == PERL_PHASE_DESTRUCT) {
1749 exceptsv = sv_mortalcopy(exceptsv);
1751 exceptsv = sv_2mortal(SvREFCNT_inc_simple_NN(exceptsv));
1755 * Historically, perl used to set ERRSV ($@) early in the die
1756 * process and rely on it not getting clobbered during unwinding.
1757 * That sucked, because it was liable to get clobbered, so the
1758 * setting of ERRSV used to emit the exception from eval{} has
1759 * been moved to much later, after unwinding (see just before
1760 * JMPENV_JUMP below). However, some modules were relying on the
1761 * early setting, by examining $@ during unwinding to use it as
1762 * a flag indicating whether the current unwinding was caused by
1763 * an exception. It was never a reliable flag for that purpose,
1764 * being totally open to false positives even without actual
1765 * clobberage, but was useful enough for production code to
1766 * semantically rely on it.
1768 * We'd like to have a proper introspective interface that
1769 * explicitly describes the reason for whatever unwinding
1770 * operations are currently in progress, so that those modules
1771 * work reliably and $@ isn't further overloaded. But we don't
1772 * have one yet. In its absence, as a stopgap measure, ERRSV is
1773 * now *additionally* set here, before unwinding, to serve as the
1774 * (unreliable) flag that it used to.
1776 * This behaviour is temporary, and should be removed when a
1777 * proper way to detect exceptional unwinding has been developed.
1778 * As of 2010-12, the authors of modules relying on the hack
1779 * are aware of the issue, because the modules failed on
1780 * perls 5.13.{1..7} which had late setting of $@ without this
1781 * early-setting hack.
1783 if (!(in_eval & EVAL_KEEPERR)) {
1784 /* remove any read-only/magic from the SV, so we don't
1785 get infinite recursion when setting ERRSV */
1787 sv_setsv_flags(ERRSV, exceptsv,
1788 (SV_GMAGIC|SV_DO_COW_SVSETSV|SV_NOSTEAL));
1791 if (in_eval & EVAL_KEEPERR) {
1792 Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "\t(in cleanup) %" SVf,
1796 while ((cxix = dopoptoeval(cxstack_ix)) < 0
1797 && PL_curstackinfo->si_prev)
1807 JMPENV *restartjmpenv;
1810 if (cxix < cxstack_ix)
1814 assert(CxTYPE(cx) == CXt_EVAL);
1816 /* return false to the caller of eval */
1817 oldsp = PL_stack_base + cx->blk_oldsp;
1818 gimme = cx->blk_gimme;
1819 if (gimme == G_SCALAR)
1820 *++oldsp = &PL_sv_undef;
1821 PL_stack_sp = oldsp;
1823 restartjmpenv = cx->blk_eval.cur_top_env;
1824 restartop = cx->blk_eval.retop;
1826 /* We need a FREETMPS here to avoid late-called destructors
1827 * clobbering $@ *after* we set it below, e.g.
1828 * sub DESTROY { eval { die "X" } }
1829 * eval { my $x = bless []; die $x = 0, "Y" };
1831 * Here the clearing of the $x ref mortalises the anon array,
1832 * which needs to be freed *before* $& is set to "Y",
1833 * otherwise it gets overwritten with "X".
1835 * However, the FREETMPS will clobber exceptsv, so preserve it
1836 * on the savestack for now.
1838 SAVEFREESV(SvREFCNT_inc_simple_NN(exceptsv));
1840 /* now we're about to pop the savestack, so re-mortalise it */
1841 sv_2mortal(SvREFCNT_inc_simple_NN(exceptsv));
1843 /* Note that unlike pp_entereval, pp_require isn't supposed to
1844 * trap errors. So if we're a require, after we pop the
1845 * CXt_EVAL that pp_require pushed, rethrow the error with
1846 * croak(exceptsv). This is all handled by the call below when
1849 S_pop_eval_context_maybe_croak(aTHX_ cx, exceptsv, 2);
1851 if (!(in_eval & EVAL_KEEPERR)) {
1853 sv_setsv(ERRSV, exceptsv);
1855 PL_restartjmpenv = restartjmpenv;
1856 PL_restartop = restartop;
1858 NOT_REACHED; /* NOTREACHED */
1862 write_to_stderr(exceptsv);
1864 NOT_REACHED; /* NOTREACHED */
1870 if (SvTRUE_NN(left) != SvTRUE_NN(right))
1878 =for apidoc_section $CV
1880 =for apidoc caller_cx
1882 The XSUB-writer's equivalent of L<caller()|perlfunc/caller>. The
1883 returned C<PERL_CONTEXT> structure can be interrogated to find all the
1884 information returned to Perl by C<caller>. Note that XSUBs don't get a
1885 stack frame, so C<caller_cx(0, NULL)> will return information for the
1886 immediately-surrounding Perl code.
1888 This function skips over the automatic calls to C<&DB::sub> made on the
1889 behalf of the debugger. If the stack frame requested was a sub called by
1890 C<DB::sub>, the return value will be the frame for the call to
1891 C<DB::sub>, since that has the correct line number/etc. for the call
1892 site. If I<dbcxp> is non-C<NULL>, it will be set to a pointer to the
1893 frame for the sub call itself.
1898 const PERL_CONTEXT *
1899 Perl_caller_cx(pTHX_ I32 count, const PERL_CONTEXT **dbcxp)
1901 I32 cxix = dopopto_cursub();
1902 const PERL_CONTEXT *cx;
1903 const PERL_CONTEXT *ccstack = cxstack;
1904 const PERL_SI *top_si = PL_curstackinfo;
1907 /* we may be in a higher stacklevel, so dig down deeper */
1908 while (cxix < 0 && top_si->si_type != PERLSI_MAIN) {
1909 top_si = top_si->si_prev;
1910 ccstack = top_si->si_cxstack;
1911 cxix = dopoptosub_at(ccstack, top_si->si_cxix);
1915 /* caller() should not report the automatic calls to &DB::sub */
1916 if (PL_DBsub && GvCV(PL_DBsub) && cxix >= 0 &&
1917 ccstack[cxix].blk_sub.cv == GvCV(PL_DBsub))
1921 cxix = dopoptosub_at(ccstack, cxix - 1);
1924 cx = &ccstack[cxix];
1925 if (dbcxp) *dbcxp = cx;
1927 if (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT) {
1928 const I32 dbcxix = dopoptosub_at(ccstack, cxix - 1);
1929 /* We expect that ccstack[dbcxix] is CXt_SUB, anyway, the
1930 field below is defined for any cx. */
1931 /* caller() should not report the automatic calls to &DB::sub */
1932 if (PL_DBsub && GvCV(PL_DBsub) && dbcxix >= 0 && ccstack[dbcxix].blk_sub.cv == GvCV(PL_DBsub))
1933 cx = &ccstack[dbcxix];
1942 const PERL_CONTEXT *cx;
1943 const PERL_CONTEXT *dbcx;
1945 const HEK *stash_hek;
1947 bool has_arg = MAXARG && TOPs;
1956 cx = caller_cx(count + cBOOL(PL_op->op_private & OPpOFFBYONE), &dbcx);
1958 if (gimme != G_LIST) {
1965 CX_DEBUG(cx, "CALLER");
1966 assert(CopSTASH(cx->blk_oldcop));
1967 stash_hek = SvTYPE(CopSTASH(cx->blk_oldcop)) == SVt_PVHV
1968 ? HvNAME_HEK((HV*)CopSTASH(cx->blk_oldcop))
1970 if (gimme != G_LIST) {
1973 PUSHs(&PL_sv_undef);
1976 sv_sethek(TARG, stash_hek);
1985 PUSHs(&PL_sv_undef);
1988 sv_sethek(TARG, stash_hek);
1991 mPUSHs(newSVpv(OutCopFILE(cx->blk_oldcop), 0));
1992 lcop = closest_cop(cx->blk_oldcop, OpSIBLING(cx->blk_oldcop),
1993 cx->blk_sub.retop, TRUE);
1995 lcop = cx->blk_oldcop;
1996 mPUSHu(CopLINE(lcop));
1999 if (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT) {
2000 /* So is ccstack[dbcxix]. */
2001 if (CvHASGV(dbcx->blk_sub.cv)) {
2002 PUSHs(cv_name(dbcx->blk_sub.cv, 0, 0));
2003 PUSHs(boolSV(CxHASARGS(cx)));
2006 PUSHs(newSVpvs_flags("(unknown)", SVs_TEMP));
2007 PUSHs(boolSV(CxHASARGS(cx)));
2011 PUSHs(newSVpvs_flags("(eval)", SVs_TEMP));
2014 gimme = cx->blk_gimme;
2015 if (gimme == G_VOID)
2016 PUSHs(&PL_sv_undef);
2018 PUSHs(boolSV((gimme & G_WANT) == G_LIST));
2019 if (CxTYPE(cx) == CXt_EVAL) {
2021 if (CxOLD_OP_TYPE(cx) == OP_ENTEREVAL) {
2022 SV *cur_text = cx->blk_eval.cur_text;
2023 if (SvCUR(cur_text) >= 2) {
2024 PUSHs(newSVpvn_flags(SvPVX(cur_text), SvCUR(cur_text)-2,
2025 SvUTF8(cur_text)|SVs_TEMP));
2028 /* I think this is will always be "", but be sure */
2029 PUSHs(sv_2mortal(newSVsv(cur_text)));
2035 else if (cx->blk_eval.old_namesv) {
2036 mPUSHs(newSVsv(cx->blk_eval.old_namesv));
2039 /* eval BLOCK (try blocks have old_namesv == 0) */
2041 PUSHs(&PL_sv_undef);
2042 PUSHs(&PL_sv_undef);
2046 PUSHs(&PL_sv_undef);
2047 PUSHs(&PL_sv_undef);
2049 if (CxTYPE(cx) == CXt_SUB && CxHASARGS(cx)
2050 && CopSTASH_eq(PL_curcop, PL_debstash))
2052 /* slot 0 of the pad contains the original @_ */
2053 AV * const ary = MUTABLE_AV(AvARRAY(MUTABLE_AV(
2054 PadlistARRAY(CvPADLIST(cx->blk_sub.cv))[
2055 cx->blk_sub.olddepth+1]))[0]);
2056 const SSize_t off = AvARRAY(ary) - AvALLOC(ary);
2058 Perl_init_dbargs(aTHX);
2060 if (AvMAX(PL_dbargs) < AvFILLp(ary) + off)
2061 av_extend(PL_dbargs, AvFILLp(ary) + off);
2062 if (AvFILLp(ary) + 1 + off)
2063 Copy(AvALLOC(ary), AvARRAY(PL_dbargs), AvFILLp(ary) + 1 + off, SV*);
2064 AvFILLp(PL_dbargs) = AvFILLp(ary) + off;
2066 mPUSHi(CopHINTS_get(cx->blk_oldcop));
2069 STRLEN * const old_warnings = cx->blk_oldcop->cop_warnings ;
2071 if (old_warnings == pWARN_NONE)
2072 mask = newSVpvn(WARN_NONEstring, WARNsize) ;
2073 else if (old_warnings == pWARN_STD && (PL_dowarn & G_WARN_ON) == 0)
2074 mask = &PL_sv_undef ;
2075 else if (old_warnings == pWARN_ALL ||
2076 (old_warnings == pWARN_STD && PL_dowarn & G_WARN_ON)) {
2077 mask = newSVpvn(WARN_ALLstring, WARNsize) ;
2080 mask = newSVpvn((char *) (old_warnings + 1), old_warnings[0]);
2084 PUSHs(cx->blk_oldcop->cop_hints_hash ?
2085 sv_2mortal(newRV_noinc(MUTABLE_SV(cop_hints_2hv(cx->blk_oldcop, 0))))
2095 if (MAXARG < 1 || (!TOPs && !POPs)) {
2097 tmps = NULL, len = 0;
2100 tmps = SvPVx_const(POPs, len);
2101 sv_resetpvn(tmps, len, CopSTASH(PL_curcop));
2106 /* like pp_nextstate, but used instead when the debugger is active */
2110 PL_curcop = (COP*)PL_op;
2111 TAINT_NOT; /* Each statement is presumed innocent */
2112 PL_stack_sp = PL_stack_base + CX_CUR()->blk_oldsp;
2117 if (PL_op->op_flags & OPf_SPECIAL /* breakpoint */
2118 || PL_DBsingle_iv || PL_DBsignal_iv || PL_DBtrace_iv)
2122 const U8 gimme = G_LIST;
2123 GV * const gv = PL_DBgv;
2126 if (gv && isGV_with_GP(gv))
2129 if (!cv || (!CvROOT(cv) && !CvXSUB(cv)))
2130 DIE(aTHX_ "No DB::DB routine defined");
2132 if (CvDEPTH(cv) >= 1 && !(PL_debug & DEBUG_DB_RECURSE_FLAG))
2133 /* don't do recursive DB::DB call */
2143 (void)(*CvXSUB(cv))(aTHX_ cv);
2149 cx = cx_pushblock(CXt_SUB, gimme, SP, PL_savestack_ix);
2150 cx_pushsub(cx, cv, PL_op->op_next, 0);
2151 /* OP_DBSTATE's op_private holds hint bits rather than
2152 * the lvalue-ish flags seen in OP_ENTERSUB. So cancel
2153 * any CxLVAL() flags that have now been mis-calculated */
2160 if (CvDEPTH(cv) >= 2)
2161 pad_push(CvPADLIST(cv), CvDEPTH(cv));
2162 PAD_SET_CUR_NOSAVE(CvPADLIST(cv), CvDEPTH(cv));
2163 RETURNOP(CvSTART(cv));
2175 (void)cx_pushblock(CXt_BLOCK, gimme, PL_stack_sp, PL_savestack_ix);
2187 assert(CxTYPE(cx) == CXt_BLOCK);
2189 if (PL_op->op_flags & OPf_SPECIAL)
2190 /* fake block should preserve $1 et al; e.g. /(...)/ while ...; */
2191 cx->blk_oldpm = PL_curpm;
2193 oldsp = PL_stack_base + cx->blk_oldsp;
2194 gimme = cx->blk_gimme;
2196 if (gimme == G_VOID)
2197 PL_stack_sp = oldsp;
2199 leave_adjust_stacks(oldsp, oldsp, gimme,
2200 PL_op->op_private & OPpLVALUE ? 3 : 1);
2210 S_outside_integer(pTHX_ SV *sv)
2213 const NV nv = SvNV_nomg(sv);
2214 if (Perl_isinfnan(nv))
2216 #ifdef NV_PRESERVES_UV
2217 if (nv < (NV)IV_MIN || nv > (NV)IV_MAX)
2220 if (nv <= (NV)IV_MIN)
2223 ((nv > (NV)UV_MAX ||
2224 SvUV_nomg(sv) > (UV)IV_MAX)))
2235 const U8 gimme = GIMME_V;
2236 void *itervarp; /* GV or pad slot of the iteration variable */
2237 SV *itersave; /* the old var in the iterator var slot */
2240 if (PL_op->op_targ) { /* "my" variable */
2241 itervarp = &PAD_SVl(PL_op->op_targ);
2242 itersave = *(SV**)itervarp;
2244 if (PL_op->op_private & OPpLVAL_INTRO) { /* for my $x (...) */
2245 /* the SV currently in the pad slot is never live during
2246 * iteration (the slot is always aliased to one of the items)
2247 * so it's always stale */
2248 SvPADSTALE_on(itersave);
2250 SvREFCNT_inc_simple_void_NN(itersave);
2251 cxflags = CXp_FOR_PAD;
2254 SV * const sv = POPs;
2255 itervarp = (void *)sv;
2256 if (LIKELY(isGV(sv))) { /* symbol table variable */
2257 itersave = GvSV(sv);
2258 SvREFCNT_inc_simple_void(itersave);
2259 cxflags = CXp_FOR_GV;
2260 if (PL_op->op_private & OPpITER_DEF)
2261 cxflags |= CXp_FOR_DEF;
2263 else { /* LV ref: for \$foo (...) */
2264 assert(SvTYPE(sv) == SVt_PVMG);
2265 assert(SvMAGIC(sv));
2266 assert(SvMAGIC(sv)->mg_type == PERL_MAGIC_lvref);
2268 cxflags = CXp_FOR_LVREF;
2271 /* OPpITER_DEF (implicit $_) should only occur with a GV iter var */
2272 assert((cxflags & CXp_FOR_GV) || !(PL_op->op_private & OPpITER_DEF));
2274 /* Note that this context is initially set as CXt_NULL. Further on
2275 * down it's changed to one of the CXt_LOOP_*. Before it's changed,
2276 * there mustn't be anything in the blk_loop substruct that requires
2277 * freeing or undoing, in case we die in the meantime. And vice-versa.
2279 cx = cx_pushblock(cxflags, gimme, MARK, PL_savestack_ix);
2280 cx_pushloop_for(cx, itervarp, itersave);
2282 if (PL_op->op_flags & OPf_STACKED) {
2283 /* OPf_STACKED implies either a single array: for(@), with a
2284 * single AV on the stack, or a range: for (1..5), with 1 and 5 on
2286 SV *maybe_ary = POPs;
2287 if (SvTYPE(maybe_ary) != SVt_PVAV) {
2290 SV * const right = maybe_ary;
2291 if (UNLIKELY(cxflags & CXp_FOR_LVREF))
2292 DIE(aTHX_ "Assigned value is not a reference");
2295 if (RANGE_IS_NUMERIC(sv,right)) {
2296 cx->cx_type |= CXt_LOOP_LAZYIV;
2297 if (S_outside_integer(aTHX_ sv) ||
2298 S_outside_integer(aTHX_ right))
2299 DIE(aTHX_ "Range iterator outside integer range");
2300 cx->blk_loop.state_u.lazyiv.cur = SvIV_nomg(sv);
2301 cx->blk_loop.state_u.lazyiv.end = SvIV_nomg(right);
2304 cx->cx_type |= CXt_LOOP_LAZYSV;
2305 cx->blk_loop.state_u.lazysv.cur = newSVsv(sv);
2306 cx->blk_loop.state_u.lazysv.end = right;
2307 SvREFCNT_inc_simple_void_NN(right);
2308 (void) SvPV_force_nolen(cx->blk_loop.state_u.lazysv.cur);
2309 /* This will do the upgrade to SVt_PV, and warn if the value
2310 is uninitialised. */
2311 (void) SvPV_nolen_const(right);
2312 /* Doing this avoids a check every time in pp_iter in pp_hot.c
2313 to replace !SvOK() with a pointer to "". */
2315 SvREFCNT_dec(right);
2316 cx->blk_loop.state_u.lazysv.end = &PL_sv_no;
2320 else /* SvTYPE(maybe_ary) == SVt_PVAV */ {
2321 /* for (@array) {} */
2322 cx->cx_type |= CXt_LOOP_ARY;
2323 cx->blk_loop.state_u.ary.ary = MUTABLE_AV(maybe_ary);
2324 SvREFCNT_inc_simple_void_NN(maybe_ary);
2325 cx->blk_loop.state_u.ary.ix =
2326 (PL_op->op_private & OPpITER_REVERSED) ?
2327 AvFILL(cx->blk_loop.state_u.ary.ary) + 1 :
2330 /* EXTEND(SP, 1) not needed in this branch because we just did POPs */
2332 else { /* iterating over items on the stack */
2333 cx->cx_type |= CXt_LOOP_LIST;
2334 cx->blk_oldsp = SP - PL_stack_base;
2335 cx->blk_loop.state_u.stack.basesp = MARK - PL_stack_base;
2336 cx->blk_loop.state_u.stack.ix =
2337 (PL_op->op_private & OPpITER_REVERSED)
2339 : cx->blk_loop.state_u.stack.basesp;
2340 /* pre-extend stack so pp_iter doesn't have to check every time
2341 * it pushes yes/no */
2351 const U8 gimme = GIMME_V;
2353 cx = cx_pushblock(CXt_LOOP_PLAIN, gimme, PL_stack_sp, PL_savestack_ix);
2354 cx_pushloop_plain(cx);
2367 assert(CxTYPE_is_LOOP(cx));
2368 oldsp = PL_stack_base + cx->blk_oldsp;
2369 base = CxTYPE(cx) == CXt_LOOP_LIST
2370 ? PL_stack_base + cx->blk_loop.state_u.stack.basesp
2372 gimme = cx->blk_gimme;
2374 if (gimme == G_VOID)
2377 leave_adjust_stacks(oldsp, base, gimme,
2378 PL_op->op_private & OPpLVALUE ? 3 : 1);
2381 cx_poploop(cx); /* Stack values are safe: release loop vars ... */
2389 /* This duplicates most of pp_leavesub, but with additional code to handle
2390 * return args in lvalue context. It was forked from pp_leavesub to
2391 * avoid slowing down that function any further.
2393 * Any changes made to this function may need to be copied to pp_leavesub
2396 * also tail-called by pp_return
2407 assert(CxTYPE(cx) == CXt_SUB);
2409 if (CxMULTICALL(cx)) {
2410 /* entry zero of a stack is always PL_sv_undef, which
2411 * simplifies converting a '()' return into undef in scalar context */
2412 assert(PL_stack_sp > PL_stack_base || *PL_stack_base == &PL_sv_undef);
2416 gimme = cx->blk_gimme;
2417 oldsp = PL_stack_base + cx->blk_oldsp; /* last arg of previous frame */
2419 if (gimme == G_VOID)
2420 PL_stack_sp = oldsp;
2422 U8 lval = CxLVAL(cx);
2423 bool is_lval = (lval && !(lval & OPpENTERSUB_INARGS));
2424 const char *what = NULL;
2426 if (gimme == G_SCALAR) {
2428 /* check for bad return arg */
2429 if (oldsp < PL_stack_sp) {
2430 SV *sv = *PL_stack_sp;
2431 if ((SvPADTMP(sv) || SvREADONLY(sv))) {
2433 SvREADONLY(sv) ? (sv == &PL_sv_undef) ? "undef"
2434 : "a readonly value" : "a temporary";
2439 /* sub:lvalue{} will take us here. */
2444 "Can't return %s from lvalue subroutine", what);
2448 leave_adjust_stacks(oldsp, oldsp, gimme, is_lval ? 3 : 2);
2450 if (lval & OPpDEREF) {
2451 /* lval_sub()->{...} and similar */
2455 TOPs = vivify_ref(TOPs, CxLVAL(cx) & OPpDEREF);
2461 assert(gimme == G_LIST);
2462 assert (!(lval & OPpDEREF));
2465 /* scan for bad return args */
2467 for (p = PL_stack_sp; p > oldsp; p--) {
2469 /* the PL_sv_undef exception is to allow things like
2470 * this to work, where PL_sv_undef acts as 'skip'
2471 * placeholder on the LHS of list assigns:
2472 * sub foo :lvalue { undef }
2473 * ($a, undef, foo(), $b) = 1..4;
2475 if (sv != &PL_sv_undef && (SvPADTMP(sv) || SvREADONLY(sv)))
2477 /* Might be flattened array after $#array = */
2478 what = SvREADONLY(sv)
2479 ? "a readonly value" : "a temporary";
2485 leave_adjust_stacks(oldsp, oldsp, gimme, is_lval ? 3 : 2);
2490 cx_popsub(cx); /* Stack values are safe: release CV and @_ ... */
2492 retop = cx->blk_sub.retop;
2498 static const char *S_defer_blockname(PERL_CONTEXT *cx)
2500 return (cx->cx_type & CXp_FINALLY) ? "finally" : "defer";
2508 I32 cxix = dopopto_cursub();
2510 assert(cxstack_ix >= 0);
2511 if (cxix < cxstack_ix) {
2513 /* Check for defer { return; } */
2514 for(i = cxstack_ix; i > cxix; i--) {
2515 if(CxTYPE(&cxstack[i]) == CXt_DEFER)
2516 /* diag_listed_as: Can't "%s" out of a "defer" block */
2517 /* diag_listed_as: Can't "%s" out of a "finally" block */
2518 Perl_croak(aTHX_ "Can't \"%s\" out of a \"%s\" block",
2519 "return", S_defer_blockname(&cxstack[i]));
2522 if (!( PL_curstackinfo->si_type == PERLSI_SORT
2523 || ( PL_curstackinfo->si_type == PERLSI_MULTICALL
2524 && (cxstack[0].cx_type & CXp_SUB_RE_FAKE))
2527 DIE(aTHX_ "Can't return outside a subroutine");
2529 * a sort block, which is a CXt_NULL not a CXt_SUB;
2530 * or a /(?{...})/ block.
2531 * Handle specially. */
2532 assert(CxTYPE(&cxstack[0]) == CXt_NULL
2533 || ( CxTYPE(&cxstack[0]) == CXt_SUB
2534 && (cxstack[0].cx_type & CXp_SUB_RE_FAKE)));
2535 if (cxstack_ix > 0) {
2536 /* See comment below about context popping. Since we know
2537 * we're scalar and not lvalue, we can preserve the return
2538 * value in a simpler fashion than there. */
2540 assert(cxstack[0].blk_gimme == G_SCALAR);
2541 if ( (sp != PL_stack_base)
2542 && !(SvFLAGS(sv) & (SVs_TEMP|SVs_PADTMP))
2544 *SP = sv_mortalcopy(sv);
2547 /* caller responsible for popping cxstack[0] */
2551 /* There are contexts that need popping. Doing this may free the
2552 * return value(s), so preserve them first: e.g. popping the plain
2553 * loop here would free $x:
2554 * sub f { { my $x = 1; return $x } }
2555 * We may also need to shift the args down; for example,
2556 * for (1,2) { return 3,4 }
2557 * leaves 1,2,3,4 on the stack. Both these actions will be done by
2558 * leave_adjust_stacks(), along with freeing any temps. Note that
2559 * whoever we tail-call (e.g. pp_leaveeval) will also call
2560 * leave_adjust_stacks(); however, the second call is likely to
2561 * just see a bunch of SvTEMPs with a ref count of 1, and so just
2562 * pass them through, rather than copying them again. So this
2563 * isn't as inefficient as it sounds.
2565 cx = &cxstack[cxix];
2567 if (cx->blk_gimme != G_VOID)
2568 leave_adjust_stacks(MARK, PL_stack_base + cx->blk_oldsp,
2570 CxTYPE(cx) == CXt_SUB && CvLVALUE(cx->blk_sub.cv)
2574 cx = &cxstack[cxix]; /* CX stack may have been realloced */
2577 /* Like in the branch above, we need to handle any extra junk on
2578 * the stack. But because we're not also popping extra contexts, we
2579 * don't have to worry about prematurely freeing args. So we just
2580 * need to do the bare minimum to handle junk, and leave the main
2581 * arg processing in the function we tail call, e.g. pp_leavesub.
2582 * In list context we have to splice out the junk; in scalar
2583 * context we can leave as-is (pp_leavesub will later return the
2584 * top stack element). But for an empty arg list, e.g.
2585 * for (1,2) { return }
2586 * we need to set sp = oldsp so that pp_leavesub knows to push
2587 * &PL_sv_undef onto the stack.
2590 cx = &cxstack[cxix];
2591 oldsp = PL_stack_base + cx->blk_oldsp;
2592 if (oldsp != MARK) {
2593 SSize_t nargs = SP - MARK;
2595 if (cx->blk_gimme == G_LIST) {
2596 /* shift return args to base of call stack frame */
2597 Move(MARK + 1, oldsp + 1, nargs, SV*);
2598 PL_stack_sp = oldsp + nargs;
2602 PL_stack_sp = oldsp;
2606 /* fall through to a normal exit */
2607 switch (CxTYPE(cx)) {
2609 return CxEVALBLOCK(cx)
2610 ? Perl_pp_leavetry(aTHX)
2611 : Perl_pp_leaveeval(aTHX);
2613 return CvLVALUE(cx->blk_sub.cv)
2614 ? Perl_pp_leavesublv(aTHX)
2615 : Perl_pp_leavesub(aTHX);
2617 return Perl_pp_leavewrite(aTHX);
2619 DIE(aTHX_ "panic: return, type=%u", (unsigned) CxTYPE(cx));
2623 /* find the enclosing loop or labelled loop and dounwind() back to it. */
2625 static PERL_CONTEXT *
2629 if (PL_op->op_flags & OPf_SPECIAL) {
2630 cxix = dopoptoloop(cxstack_ix);
2632 /* diag_listed_as: Can't "last" outside a loop block */
2633 Perl_croak(aTHX_ "Can't \"%s\" outside a loop block",
2639 const char * const label =
2640 PL_op->op_flags & OPf_STACKED
2641 ? SvPV(TOPs,label_len)
2642 : (label_len = strlen(cPVOP->op_pv), cPVOP->op_pv);
2643 const U32 label_flags =
2644 PL_op->op_flags & OPf_STACKED
2646 : (cPVOP->op_private & OPpPV_IS_UTF8) ? SVf_UTF8 : 0;
2648 cxix = dopoptolabel(label, label_len, label_flags);
2650 /* diag_listed_as: Label not found for "last %s" */
2651 Perl_croak(aTHX_ "Label not found for \"%s %" SVf "\"",
2653 SVfARG(PL_op->op_flags & OPf_STACKED
2654 && !SvGMAGICAL(TOPp1s)
2656 : newSVpvn_flags(label,
2658 label_flags | SVs_TEMP)));
2660 if (cxix < cxstack_ix) {
2662 /* Check for defer { last ... } etc */
2663 for(i = cxstack_ix; i > cxix; i--) {
2664 if(CxTYPE(&cxstack[i]) == CXt_DEFER)
2665 /* diag_listed_as: Can't "%s" out of a "defer" block */
2666 /* diag_listed_as: Can't "%s" out of a "finally" block */
2667 Perl_croak(aTHX_ "Can't \"%s\" out of a \"%s\" block",
2668 OP_NAME(PL_op), S_defer_blockname(&cxstack[i]));
2672 return &cxstack[cxix];
2681 cx = S_unwind_loop(aTHX);
2683 assert(CxTYPE_is_LOOP(cx));
2684 PL_stack_sp = PL_stack_base
2685 + (CxTYPE(cx) == CXt_LOOP_LIST
2686 ? cx->blk_loop.state_u.stack.basesp
2692 /* Stack values are safe: */
2694 cx_poploop(cx); /* release loop vars ... */
2696 nextop = cx->blk_loop.my_op->op_lastop->op_next;
2706 /* if not a bare 'next' in the main scope, search for it */
2708 if (!((PL_op->op_flags & OPf_SPECIAL) && CxTYPE_is_LOOP(cx)))
2709 cx = S_unwind_loop(aTHX);
2712 PL_curcop = cx->blk_oldcop;
2714 return (cx)->blk_loop.my_op->op_nextop;
2719 PERL_CONTEXT *cx = S_unwind_loop(aTHX);
2720 OP* redo_op = cx->blk_loop.my_op->op_redoop;
2722 if (redo_op->op_type == OP_ENTER) {
2723 /* pop one less context to avoid $x being freed in while (my $x..) */
2726 assert(CxTYPE(cx) == CXt_BLOCK);
2727 redo_op = redo_op->op_next;
2733 PL_curcop = cx->blk_oldcop;
2738 #define UNENTERABLE (OP *)1
2739 #define GOTO_DEPTH 64
2742 S_dofindlabel(pTHX_ OP *o, const char *label, STRLEN len, U32 flags, OP **opstack, OP **oplimit)
2745 static const char* const too_deep = "Target of goto is too deeply nested";
2747 PERL_ARGS_ASSERT_DOFINDLABEL;
2750 Perl_croak(aTHX_ "%s", too_deep);
2751 if (o->op_type == OP_LEAVE ||
2752 o->op_type == OP_SCOPE ||
2753 o->op_type == OP_LEAVELOOP ||
2754 o->op_type == OP_LEAVESUB ||
2755 o->op_type == OP_LEAVETRY ||
2756 o->op_type == OP_LEAVEGIVEN)
2758 *ops++ = cUNOPo->op_first;
2760 else if (oplimit - opstack < GOTO_DEPTH) {
2761 if (o->op_flags & OPf_KIDS
2762 && cUNOPo->op_first->op_type == OP_PUSHMARK) {
2763 *ops++ = UNENTERABLE;
2765 else if (o->op_flags & OPf_KIDS && PL_opargs[o->op_type]
2766 && OP_CLASS(o) != OA_LOGOP
2767 && o->op_type != OP_LINESEQ
2768 && o->op_type != OP_SREFGEN
2769 && o->op_type != OP_ENTEREVAL
2770 && o->op_type != OP_GLOB
2771 && o->op_type != OP_RV2CV) {
2772 OP * const kid = cUNOPo->op_first;
2773 if (OP_GIMME(kid, 0) != G_SCALAR || OpHAS_SIBLING(kid))
2774 *ops++ = UNENTERABLE;
2778 Perl_croak(aTHX_ "%s", too_deep);
2780 if (o->op_flags & OPf_KIDS) {
2782 OP * const kid1 = cUNOPo->op_first;
2783 /* First try all the kids at this level, since that's likeliest. */
2784 for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
2785 if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
2786 STRLEN kid_label_len;
2787 U32 kid_label_flags;
2788 const char *kid_label = CopLABEL_len_flags(kCOP,
2789 &kid_label_len, &kid_label_flags);
2791 ( (kid_label_flags & SVf_UTF8) != (flags & SVf_UTF8) ) ?
2794 (const U8*)kid_label, kid_label_len,
2795 (const U8*)label, len) == 0)
2797 (const U8*)label, len,
2798 (const U8*)kid_label, kid_label_len) == 0)
2799 : ( len == kid_label_len && ((kid_label == label)
2800 || memEQ(kid_label, label, len)))))
2804 for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
2805 bool first_kid_of_binary = FALSE;
2806 if (kid == PL_lastgotoprobe)
2808 if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
2811 else if (ops[-1] != UNENTERABLE
2812 && (ops[-1]->op_type == OP_NEXTSTATE ||
2813 ops[-1]->op_type == OP_DBSTATE))
2818 if (kid == kid1 && ops != opstack && ops[-1] == UNENTERABLE) {
2819 first_kid_of_binary = TRUE;
2822 if ((o = dofindlabel(kid, label, len, flags, ops, oplimit))) {
2823 if (kid->op_type == OP_PUSHDEFER)
2824 Perl_croak(aTHX_ "Can't \"goto\" into a \"defer\" block");
2827 if (first_kid_of_binary)
2828 *ops++ = UNENTERABLE;
2837 S_check_op_type(pTHX_ OP * const o)
2839 /* Eventually we may want to stack the needed arguments
2840 * for each op. For now, we punt on the hard ones. */
2841 /* XXX This comment seems to me like wishful thinking. --sprout */
2842 if (o == UNENTERABLE)
2844 "Can't \"goto\" into a binary or list expression");
2845 if (o->op_type == OP_ENTERITER)
2847 "Can't \"goto\" into the middle of a foreach loop");
2848 if (o->op_type == OP_ENTERGIVEN)
2850 "Can't \"goto\" into a \"given\" block");
2853 /* also used for: pp_dump() */
2861 OP *enterops[GOTO_DEPTH];
2862 const char *label = NULL;
2863 STRLEN label_len = 0;
2864 U32 label_flags = 0;
2865 const bool do_dump = (PL_op->op_type == OP_DUMP);
2866 static const char* const must_have_label = "goto must have label";
2868 if (PL_op->op_flags & OPf_STACKED) {
2869 /* goto EXPR or goto &foo */
2871 SV * const sv = POPs;
2874 if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
2875 /* This egregious kludge implements goto &subroutine */
2878 CV *cv = MUTABLE_CV(SvRV(sv));
2879 AV *arg = GvAV(PL_defgv);
2882 while (!CvROOT(cv) && !CvXSUB(cv)) {
2883 const GV * const gv = CvGV(cv);
2887 /* autoloaded stub? */
2888 if (cv != GvCV(gv) && (cv = GvCV(gv)))
2890 autogv = gv_autoload_pvn(GvSTASH(gv), GvNAME(gv),
2892 GvNAMEUTF8(gv) ? SVf_UTF8 : 0);
2893 if (autogv && (cv = GvCV(autogv)))
2895 tmpstr = sv_newmortal();
2896 gv_efullname3(tmpstr, gv, NULL);
2897 DIE(aTHX_ "Goto undefined subroutine &%" SVf, SVfARG(tmpstr));
2899 DIE(aTHX_ "Goto undefined subroutine");
2902 cxix = dopopto_cursub();
2904 DIE(aTHX_ "Can't goto subroutine outside a subroutine");
2906 cx = &cxstack[cxix];
2907 /* ban goto in eval: see <20050521150056.GC20213@iabyn.com> */
2908 if (CxTYPE(cx) == CXt_EVAL) {
2910 /* diag_listed_as: Can't goto subroutine from an eval-%s */
2911 DIE(aTHX_ "Can't goto subroutine from an eval-string");
2913 /* diag_listed_as: Can't goto subroutine from an eval-%s */
2914 DIE(aTHX_ "Can't goto subroutine from an eval-block");
2916 else if (CxMULTICALL(cx))
2917 DIE(aTHX_ "Can't goto subroutine from a sort sub (or similar callback)");
2919 /* Check for defer { goto &...; } */
2920 for(ix = cxstack_ix; ix > cxix; ix--) {
2921 if(CxTYPE(&cxstack[ix]) == CXt_DEFER)
2922 /* diag_listed_as: Can't "%s" out of a "defer" block */
2923 Perl_croak(aTHX_ "Can't \"%s\" out of a \"%s\" block",
2924 "goto", S_defer_blockname(&cxstack[ix]));
2927 /* First do some returnish stuff. */
2929 SvREFCNT_inc_simple_void(cv); /* avoid premature free during unwind */
2931 if (cxix < cxstack_ix) {
2938 /* protect @_ during save stack unwind. */
2940 SvREFCNT_inc_NN(sv_2mortal(MUTABLE_SV(arg)));
2942 assert(PL_scopestack_ix == cx->blk_oldscopesp);
2945 if (CxTYPE(cx) == CXt_SUB && CxHASARGS(cx)) {
2946 /* this is part of cx_popsub_args() */
2947 AV* av = MUTABLE_AV(PAD_SVl(0));
2948 assert(AvARRAY(MUTABLE_AV(
2949 PadlistARRAY(CvPADLIST(cx->blk_sub.cv))[
2950 CvDEPTH(cx->blk_sub.cv)])) == PL_curpad);
2952 /* we are going to donate the current @_ from the old sub
2953 * to the new sub. This first part of the donation puts a
2954 * new empty AV in the pad[0] slot of the old sub,
2955 * unless pad[0] and @_ differ (e.g. if the old sub did
2956 * local *_ = []); in which case clear the old pad[0]
2957 * array in the usual way */
2958 if (av == arg || AvREAL(av))
2959 clear_defarray(av, av == arg);
2960 else CLEAR_ARGARRAY(av);
2963 /* don't restore PL_comppad here. It won't be needed if the
2964 * sub we're going to is non-XS, but restoring it early then
2965 * croaking (e.g. the "Goto undefined subroutine" below)
2966 * means the CX block gets processed again in dounwind,
2967 * but this time with the wrong PL_comppad */
2969 /* A destructor called during LEAVE_SCOPE could have undefined
2970 * our precious cv. See bug #99850. */
2971 if (!CvROOT(cv) && !CvXSUB(cv)) {
2972 const GV * const gv = CvGV(cv);
2974 SV * const tmpstr = sv_newmortal();
2975 gv_efullname3(tmpstr, gv, NULL);
2976 DIE(aTHX_ "Goto undefined subroutine &%" SVf,
2979 DIE(aTHX_ "Goto undefined subroutine");
2982 if (CxTYPE(cx) == CXt_SUB) {
2983 CvDEPTH(cx->blk_sub.cv) = cx->blk_sub.olddepth;
2984 /*on XS calls defer freeing the old CV as it could
2985 * prematurely set PL_op to NULL, which could cause
2986 * e..g XS subs using GIMME_V to SEGV */
2988 old_cv = cx->blk_sub.cv;
2990 SvREFCNT_dec_NN(cx->blk_sub.cv);
2993 /* Now do some callish stuff. */
2995 const SSize_t items = arg ? AvFILL(arg) + 1 : 0;
2996 const bool m = arg ? cBOOL(SvRMAGICAL(arg)) : 0;
3002 SAVEFREESV(cv); /* later, undo the 'avoid premature free' hack */
3004 SAVEFREESV(old_cv); /* ditto, deferred freeing of old CV */
3006 /* put GvAV(defgv) back onto stack */
3008 EXTEND(SP, items+1); /* @_ could have been extended. */
3013 bool r = cBOOL(AvREAL(arg));
3014 for (index=0; index<items; index++)
3018 SV ** const svp = av_fetch(arg, index, 0);
3019 sv = svp ? *svp : NULL;
3021 else sv = AvARRAY(arg)[index];
3023 ? r ? SvREFCNT_inc_NN(sv_2mortal(sv)) : sv
3024 : sv_2mortal(newSVavdefelem(arg, index, 1));
3028 if (CxTYPE(cx) == CXt_SUB && CxHASARGS(cx)) {
3029 /* Restore old @_ */
3030 CX_POP_SAVEARRAY(cx);
3033 retop = cx->blk_sub.retop;
3034 PL_comppad = cx->blk_sub.prevcomppad;
3035 PL_curpad = LIKELY(PL_comppad) ? AvARRAY(PL_comppad) : NULL;
3037 /* Make a temporary a copy of the current GOTO op on the C
3038 * stack, but with a modified gimme (we can't modify the
3039 * real GOTO op as that's not thread-safe). This allows XS
3040 * users of GIMME_V to get the correct calling context,
3041 * even though there is no longer a CXt_SUB frame to
3042 * provide that information.
3044 Copy(PL_op, &fake_goto_op, 1, UNOP);
3045 fake_goto_op.op_flags =
3046 (fake_goto_op.op_flags & ~OPf_WANT)
3047 | (cx->blk_gimme & G_WANT);
3048 PL_op = (OP*)&fake_goto_op;
3050 /* XS subs don't have a CXt_SUB, so pop it;
3051 * this is a cx_popblock(), less all the stuff we already did
3052 * for cx_topblock() earlier */
3053 PL_curcop = cx->blk_oldcop;
3054 /* this is cx_popsub, less all the stuff we already did */
3055 PL_curstackinfo->si_cxsubix = cx->blk_sub.old_cxsubix;
3059 /* Push a mark for the start of arglist */
3062 (void)(*CvXSUB(cv))(aTHX_ cv);
3067 PADLIST * const padlist = CvPADLIST(cv);
3069 SAVEFREESV(cv); /* later, undo the 'avoid premature free' hack */
3071 /* partial unrolled cx_pushsub(): */
3073 cx->blk_sub.cv = cv;
3074 cx->blk_sub.olddepth = CvDEPTH(cv);
3077 SvREFCNT_inc_simple_void_NN(cv);
3078 if (CvDEPTH(cv) > 1) {
3079 if (CvDEPTH(cv) == PERL_SUB_DEPTH_WARN && ckWARN(WARN_RECURSION))
3080 sub_crush_depth(cv);
3081 pad_push(padlist, CvDEPTH(cv));
3083 PL_curcop = cx->blk_oldcop;
3084 PAD_SET_CUR_NOSAVE(padlist, CvDEPTH(cv));
3087 /* second half of donating @_ from the old sub to the
3088 * new sub: abandon the original pad[0] AV in the
3089 * new sub, and replace it with the donated @_.
3090 * pad[0] takes ownership of the extra refcount
3091 * we gave arg earlier */
3093 SvREFCNT_dec(PAD_SVl(0));
3094 PAD_SVl(0) = (SV *)arg;
3095 SvREFCNT_inc_simple_void_NN(arg);
3098 /* GvAV(PL_defgv) might have been modified on scope
3099 exit, so point it at arg again. */
3100 if (arg != GvAV(PL_defgv)) {
3101 AV * const av = GvAV(PL_defgv);
3102 GvAV(PL_defgv) = (AV *)SvREFCNT_inc_simple(arg);
3107 if (PERLDB_SUB) { /* Checking curstash breaks DProf. */
3108 Perl_get_db_sub(aTHX_ NULL, cv);
3110 CV * const gotocv = get_cvs("DB::goto", 0);
3112 PUSHMARK( PL_stack_sp );
3113 call_sv(MUTABLE_SV(gotocv), G_SCALAR | G_NODEBUG);
3118 retop = CvSTART(cv);
3119 goto putback_return;
3124 label = SvPV_nomg_const(sv, label_len);
3125 label_flags = SvUTF8(sv);
3128 else if (!(PL_op->op_flags & OPf_SPECIAL)) {
3129 /* goto LABEL or dump LABEL */
3130 label = cPVOP->op_pv;
3131 label_flags = (cPVOP->op_private & OPpPV_IS_UTF8) ? SVf_UTF8 : 0;
3132 label_len = strlen(label);
3134 if (!(do_dump || label_len)) DIE(aTHX_ "%s", must_have_label);
3139 OP *gotoprobe = NULL;
3140 bool leaving_eval = FALSE;
3141 bool in_block = FALSE;
3142 bool pseudo_block = FALSE;
3143 PERL_CONTEXT *last_eval_cx = NULL;
3147 PL_lastgotoprobe = NULL;
3149 for (ix = cxstack_ix; ix >= 0; ix--) {
3151 switch (CxTYPE(cx)) {
3153 leaving_eval = TRUE;
3154 if (!CxEVALBLOCK(cx)) {
3155 gotoprobe = (last_eval_cx ?
3156 last_eval_cx->blk_eval.old_eval_root :
3161 /* else fall through */
3162 case CXt_LOOP_PLAIN:
3163 case CXt_LOOP_LAZYIV:
3164 case CXt_LOOP_LAZYSV:
3169 gotoprobe = OpSIBLING(cx->blk_oldcop);
3175 gotoprobe = OpSIBLING(cx->blk_oldcop);
3178 gotoprobe = PL_main_root;
3181 gotoprobe = CvROOT(cx->blk_sub.cv);
3182 pseudo_block = cBOOL(CxMULTICALL(cx));
3186 DIE(aTHX_ "Can't \"goto\" out of a pseudo block");
3188 /* diag_listed_as: Can't "%s" out of a "defer" block */
3189 DIE(aTHX_ "Can't \"%s\" out of a \"%s\" block", "goto", S_defer_blockname(cx));
3192 DIE(aTHX_ "panic: goto, type=%u, ix=%ld",
3193 CxTYPE(cx), (long) ix);
3194 gotoprobe = PL_main_root;
3200 retop = dofindlabel(gotoprobe, label, label_len, label_flags,
3201 enterops, enterops + GOTO_DEPTH);
3204 if ( (sibl1 = OpSIBLING(gotoprobe)) &&
3205 sibl1->op_type == OP_UNSTACK &&
3206 (sibl2 = OpSIBLING(sibl1)))
3208 retop = dofindlabel(sibl2,
3209 label, label_len, label_flags, enterops,
3210 enterops + GOTO_DEPTH);
3216 DIE(aTHX_ "Can't \"goto\" out of a pseudo block");
3217 PL_lastgotoprobe = gotoprobe;
3220 DIE(aTHX_ "Can't find label %" UTF8f,
3221 UTF8fARG(label_flags, label_len, label));
3223 /* if we're leaving an eval, check before we pop any frames
3224 that we're not going to punt, otherwise the error
3227 if (leaving_eval && *enterops && enterops[1]) {
3229 for (i = 1; enterops[i]; i++)
3230 S_check_op_type(aTHX_ enterops[i]);
3233 if (*enterops && enterops[1]) {
3234 I32 i = enterops[1] != UNENTERABLE
3235 && enterops[1]->op_type == OP_ENTER && in_block
3239 deprecate("\"goto\" to jump into a construct");
3242 /* pop unwanted frames */
3244 if (ix < cxstack_ix) {
3246 DIE(aTHX_ "panic: docatch: illegal ix=%ld", (long)ix);
3252 /* push wanted frames */
3254 if (*enterops && enterops[1]) {
3255 OP * const oldop = PL_op;
3256 ix = enterops[1] != UNENTERABLE
3257 && enterops[1]->op_type == OP_ENTER && in_block
3260 for (; enterops[ix]; ix++) {
3261 PL_op = enterops[ix];
3262 S_check_op_type(aTHX_ PL_op);
3263 DEBUG_l( Perl_deb(aTHX_ "pp_goto: Entering %s\n",
3265 PL_op->op_ppaddr(aTHX);
3273 if (!retop) retop = PL_main_start;
3275 PL_restartop = retop;
3276 PL_do_undump = TRUE;
3280 PL_restartop = 0; /* hmm, must be GNU unexec().. */
3281 PL_do_undump = FALSE;
3299 anum = 0; (void)POPs;
3305 && SvTRUE(cop_hints_fetch_pvs(PL_curcop, "vmsish_exit", 0)))
3308 VMSISH_HUSHED || (PL_curcop->op_private & OPpHUSH_VMSISH);
3311 PL_exit_flags |= PERL_EXIT_EXPECTED;
3313 PUSHs(&PL_sv_undef);
3320 S_save_lines(pTHX_ AV *array, SV *sv)
3322 const char *s = SvPVX_const(sv);
3323 const char * const send = SvPVX_const(sv) + SvCUR(sv);
3326 PERL_ARGS_ASSERT_SAVE_LINES;
3328 while (s && s < send) {
3330 SV * const tmpstr = newSV_type(SVt_PVMG);
3332 t = (const char *)memchr(s, '\n', send - s);
3338 sv_setpvn_fresh(tmpstr, s, t - s);
3339 av_store(array, line++, tmpstr);
3347 Interpose, for the current op and RUNOPS loop,
3349 - a new JMPENV stack catch frame, and
3350 - an inner RUNOPS loop to run all the remaining ops following the
3353 Then handle any exceptions raised while in that loop.
3354 For a caught eval at this level, re-enter the loop with the specified
3355 restart op (i.e. the op following the OP_LEAVETRY etc); otherwise re-throw
3358 docatch() is intended to be used like this:
3363 return docatch(Perl_pp_entertry);
3365 ... rest of function ...
3366 return PL_op->op_next;
3369 If a new catch frame isn't needed, the op behaves normally. Otherwise it
3370 calls docatch(), which recursively calls pp_entertry(), this time with
3371 CATCH_GET() false, so the rest of the body of the entertry is run. Then
3372 docatch() calls CALLRUNOPS() which executes all the ops following the
3373 entertry. When the loop finally finishes, control returns to docatch(),
3374 which pops the JMPENV and returns to the parent pp_entertry(), which
3375 itself immediately returns. Note that *all* subsequent ops are run within
3376 the inner RUNOPS loop, not just the body of the eval. For example, in
3378 sub TIEARRAY { eval {1}; my $x }
3381 at the point the 'my' is executed, the C stack will look something like:
3384 #9 perl_run() # JMPENV_PUSH level 1 here
3386 #7 Perl_runops_standard() # main RUNOPS loop
3389 #4 Perl_runops_standard() # unguarded RUNOPS loop: no new JMPENV
3390 #3 Perl_pp_entertry()
3391 #2 S_docatch() # JMPENV_PUSH level 2 here
3392 #1 Perl_runops_standard() # docatch()'s RUNOPs loop
3395 Basically, any section of the perl core which starts a RUNOPS loop may
3396 make a promise that it will catch any exceptions and restart the loop if
3397 necessary. If it's not prepared to do that (like call_sv() isn't), then
3398 it sets CATCH_GET() to true, so that any later eval-like code knows to
3399 set up a new handler and loop (via docatch()).
3401 See L<perlinterp/"Exception handing"> for further details.
3407 S_docatch(pTHX_ Perl_ppaddr_t firstpp)
3410 OP * const oldop = PL_op;
3418 case 0: /* normal flow-of-control return from JMPENV_PUSH */
3420 /* re-run the current op, this time executing the full body of the
3422 PL_op = firstpp(aTHX);
3429 case 3: /* an exception raised within an eval */
3430 if (PL_restartjmpenv == PL_top_env) {
3431 /* die caught by an inner eval - continue inner loop */
3435 PL_restartjmpenv = NULL;
3436 PL_op = PL_restartop;
3445 JMPENV_JUMP(ret); /* re-throw the exception */
3446 NOT_REACHED; /* NOTREACHED */
3455 =for apidoc find_runcv
3457 Locate the CV corresponding to the currently executing sub or eval.
3458 If C<db_seqp> is non_null, skip CVs that are in the DB package and populate
3459 C<*db_seqp> with the cop sequence number at the point that the DB:: code was
3460 entered. (This allows debuggers to eval in the scope of the breakpoint
3461 rather than in the scope of the debugger itself.)
3467 Perl_find_runcv(pTHX_ U32 *db_seqp)
3469 return Perl_find_runcv_where(aTHX_ 0, 0, db_seqp);
3472 /* If this becomes part of the API, it might need a better name. */
3474 Perl_find_runcv_where(pTHX_ U8 cond, IV arg, U32 *db_seqp)
3481 PL_curcop == &PL_compiling
3483 : PL_curcop->cop_seq;
3485 for (si = PL_curstackinfo; si; si = si->si_prev) {
3487 for (ix = si->si_cxix; ix >= 0; ix--) {
3488 const PERL_CONTEXT *cx = &(si->si_cxstack[ix]);
3490 if (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT) {
3491 cv = cx->blk_sub.cv;
3492 /* skip DB:: code */
3493 if (db_seqp && PL_debstash && CvSTASH(cv) == PL_debstash) {
3494 *db_seqp = cx->blk_oldcop->cop_seq;
3497 if (cx->cx_type & CXp_SUB_RE)
3500 else if (CxTYPE(cx) == CXt_EVAL && !CxEVALBLOCK(cx))
3501 cv = cx->blk_eval.cv;
3504 case FIND_RUNCV_padid_eq:
3506 || CvPADLIST(cv)->xpadl_id != (U32)arg)
3509 case FIND_RUNCV_level_eq:
3510 if (level++ != arg) continue;
3518 return cond == FIND_RUNCV_padid_eq ? NULL : PL_main_cv;
3522 /* Run yyparse() in a setjmp wrapper. Returns:
3523 * 0: yyparse() successful
3524 * 1: yyparse() failed
3528 S_try_yyparse(pTHX_ int gramtype)
3533 assert(CxTYPE(CX_CUR()) == CXt_EVAL);
3537 ret = yyparse(gramtype) ? 1 : 0;
3544 NOT_REACHED; /* NOTREACHED */
3551 /* Compile a require/do or an eval ''.
3553 * outside is the lexically enclosing CV (if any) that invoked us.
3554 * seq is the current COP scope value.
3555 * hh is the saved hints hash, if any.
3557 * Returns a bool indicating whether the compile was successful; if so,
3558 * PL_eval_start contains the first op of the compiled code; otherwise,
3561 * This function is called from two places: pp_require and pp_entereval.
3562 * These can be distinguished by whether PL_op is entereval.
3566 S_doeval_compile(pTHX_ U8 gimme, CV* outside, U32 seq, HV *hh)
3569 OP * const saveop = PL_op;
3570 bool clear_hints = saveop->op_type != OP_ENTEREVAL;
3571 COP * const oldcurcop = PL_curcop;
3572 bool in_require = (saveop->op_type == OP_REQUIRE);
3576 PL_in_eval = (in_require
3577 ? (EVAL_INREQUIRE | (PL_in_eval & EVAL_INEVAL))
3579 ((PL_op->op_private & OPpEVAL_RE_REPARSING)
3580 ? EVAL_RE_REPARSING : 0)));
3584 evalcv = MUTABLE_CV(newSV_type(SVt_PVCV));
3586 assert(CxTYPE(CX_CUR()) == CXt_EVAL);
3587 CX_CUR()->blk_eval.cv = evalcv;
3588 CX_CUR()->blk_gimme = gimme;
3590 CvOUTSIDE_SEQ(evalcv) = seq;
3591 CvOUTSIDE(evalcv) = MUTABLE_CV(SvREFCNT_inc_simple(outside));
3593 /* set up a scratch pad */
3595 CvPADLIST_set(evalcv, pad_new(padnew_SAVE));
3596 PL_op = NULL; /* avoid PL_op and PL_curpad referring to different CVs */
3599 SAVEMORTALIZESV(evalcv); /* must remain until end of current statement */
3601 /* make sure we compile in the right package */
3603 if (CopSTASH_ne(PL_curcop, PL_curstash)) {
3604 SAVEGENERICSV(PL_curstash);
3605 PL_curstash = (HV *)CopSTASH(PL_curcop);
3606 if (SvTYPE(PL_curstash) != SVt_PVHV) PL_curstash = NULL;
3608 SvREFCNT_inc_simple_void(PL_curstash);
3609 save_item(PL_curstname);
3610 sv_sethek(PL_curstname, HvNAME_HEK(PL_curstash));
3613 /* XXX:ajgo do we really need to alloc an AV for begin/checkunit */
3614 SAVESPTR(PL_beginav);
3615 PL_beginav = newAV();
3616 SAVEFREESV(PL_beginav);
3617 SAVESPTR(PL_unitcheckav);
3618 PL_unitcheckav = newAV();
3619 SAVEFREESV(PL_unitcheckav);
3622 ENTER_with_name("evalcomp");
3623 SAVESPTR(PL_compcv);
3626 /* try to compile it */
3628 PL_eval_root = NULL;
3629 PL_curcop = &PL_compiling;
3630 if ((saveop->op_type != OP_REQUIRE) && (saveop->op_flags & OPf_SPECIAL))
3631 PL_in_eval |= EVAL_KEEPERR;
3637 PL_hints = HINTS_DEFAULT;
3638 PL_prevailing_version = 0;
3639 hv_clear(GvHV(PL_hintgv));
3643 PL_hints = saveop->op_private & OPpEVAL_COPHH
3644 ? oldcurcop->cop_hints : (U32)saveop->op_targ;
3646 /* making 'use re eval' not be in scope when compiling the
3647 * qr/mabye_has_runtime_code_block/ ensures that we don't get
3648 * infinite recursion when S_has_runtime_code() gives a false
3649 * positive: the second time round, HINT_RE_EVAL isn't set so we
3650 * don't bother calling S_has_runtime_code() */
3651 if (PL_in_eval & EVAL_RE_REPARSING)
3652 PL_hints &= ~HINT_RE_EVAL;
3655 /* SAVEHINTS created a new HV in PL_hintgv, which we need to GC */
3656 SvREFCNT_dec(GvHV(PL_hintgv));
3657 GvHV(PL_hintgv) = hh;
3658 FETCHFEATUREBITSHH(hh);
3661 SAVECOMPILEWARNINGS();
3663 if (PL_dowarn & G_WARN_ALL_ON)
3664 PL_compiling.cop_warnings = pWARN_ALL ;
3665 else if (PL_dowarn & G_WARN_ALL_OFF)
3666 PL_compiling.cop_warnings = pWARN_NONE ;
3668 PL_compiling.cop_warnings = pWARN_STD ;
3671 PL_compiling.cop_warnings =
3672 DUP_WARNINGS(oldcurcop->cop_warnings);
3673 cophh_free(CopHINTHASH_get(&PL_compiling));
3674 if (Perl_cop_fetch_label(aTHX_ oldcurcop, NULL, NULL)) {
3675 /* The label, if present, is the first entry on the chain. So rather
3676 than writing a blank label in front of it (which involves an
3677 allocation), just use the next entry in the chain. */
3678 PL_compiling.cop_hints_hash
3679 = cophh_copy(oldcurcop->cop_hints_hash->refcounted_he_next);
3680 /* Check the assumption that this removed the label. */
3681 assert(Perl_cop_fetch_label(aTHX_ &PL_compiling, NULL, NULL) == NULL);
3684 PL_compiling.cop_hints_hash = cophh_copy(oldcurcop->cop_hints_hash);
3687 CALL_BLOCK_HOOKS(bhk_eval, saveop);
3689 /* note that yyparse() may raise an exception, e.g. C<BEGIN{die}>,
3690 * so honour CATCH_GET and trap it here if necessary */
3693 /* compile the code */
3694 yystatus = (!in_require && CATCH_GET) ? S_try_yyparse(aTHX_ GRAMPROG) : yyparse(GRAMPROG);
3696 if (yystatus || PL_parser->error_count || !PL_eval_root) {
3701 /* note that if yystatus == 3, then the require/eval died during
3702 * compilation, so the EVAL CX block has already been popped, and
3703 * various vars restored */
3704 if (yystatus != 3) {
3706 op_free(PL_eval_root);
3707 PL_eval_root = NULL;
3709 SP = PL_stack_base + POPMARK; /* pop original mark */
3711 assert(CxTYPE(cx) == CXt_EVAL);
3712 /* pop the CXt_EVAL, and if was a require, croak */
3713 S_pop_eval_context_maybe_croak(aTHX_ cx, ERRSV, 2);
3716 /* die_unwind() re-croaks when in require, having popped the
3717 * require EVAL context. So we should never catch a require
3719 assert(!in_require);
3722 if (!*(SvPV_nolen_const(errsv)))
3723 sv_setpvs(errsv, "Compilation error");
3725 if (gimme != G_LIST) PUSHs(&PL_sv_undef);
3730 /* Compilation successful. Now clean up */
3732 LEAVE_with_name("evalcomp");
3734 CopLINE_set(&PL_compiling, 0);
3735 SAVEFREEOP(PL_eval_root);
3736 cv_forget_slab(evalcv);
3738 DEBUG_x(dump_eval());
3740 /* Register with debugger: */
3741 if (PERLDB_INTER && saveop->op_type == OP_REQUIRE) {
3742 CV * const cv = get_cvs("DB::postponed", 0);
3746 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
3748 call_sv(MUTABLE_SV(cv), G_DISCARD);
3752 if (PL_unitcheckav) {
3753 OP *es = PL_eval_start;
3754 call_list(PL_scopestack_ix, PL_unitcheckav);
3758 CvDEPTH(evalcv) = 1;
3759 SP = PL_stack_base + POPMARK; /* pop original mark */
3760 PL_op = saveop; /* The caller may need it. */
3761 PL_parser->lex_state = LEX_NOTPARSING; /* $^S needs this. */
3767 /* Return NULL if the file doesn't exist or isn't a file;
3768 * else return PerlIO_openn().
3772 S_check_type_and_open(pTHX_ SV *name)
3777 const char *p = SvPV_const(name, len);
3780 PERL_ARGS_ASSERT_CHECK_TYPE_AND_OPEN;
3782 /* checking here captures a reasonable error message when
3783 * PERL_DISABLE_PMC is true, but when PMC checks are enabled, the
3784 * user gets a confusing message about looking for the .pmc file
3785 * rather than for the .pm file so do the check in S_doopen_pm when
3786 * PMC is on instead of here. S_doopen_pm calls this func.
3787 * This check prevents a \0 in @INC causing problems.
3789 #ifdef PERL_DISABLE_PMC
3790 if (!IS_SAFE_PATHNAME(p, len, "require"))
3794 /* on Win32 stat is expensive (it does an open() and close() twice and
3795 a couple other IO calls), the open will fail with a dir on its own with
3796 errno EACCES, so only do a stat to separate a dir from a real EACCES
3797 caused by user perms */
3799 st_rc = PerlLIO_stat(p, &st);
3805 if(S_ISBLK(st.st_mode)) {
3809 else if(S_ISDIR(st.st_mode)) {
3818 retio = PerlIO_openn(aTHX_ ":", PERL_SCRIPT_MODE, -1, 0, 0, NULL, 1, &name);
3820 /* EACCES stops the INC search early in pp_require to implement
3821 feature RT #113422 */
3822 if(!retio && errno == EACCES) { /* exists but probably a directory */
3824 st_rc = PerlLIO_stat(p, &st);
3826 if(S_ISDIR(st.st_mode))
3828 else if(S_ISBLK(st.st_mode))
3839 /* doopen_pm(): return the equivalent of PerlIO_openn() on the given name,
3840 * but first check for bad names (\0) and non-files.
3841 * Also if the filename ends in .pm and unless PERL_DISABLE_PMC,
3842 * try loading Foo.pmc first.
3844 #ifndef PERL_DISABLE_PMC
3846 S_doopen_pm(pTHX_ SV *name)
3849 const char *p = SvPV_const(name, namelen);
3851 PERL_ARGS_ASSERT_DOOPEN_PM;
3853 /* check the name before trying for the .pmc name to avoid the
3854 * warning referring to the .pmc which the user probably doesn't
3855 * know or care about
3857 if (!IS_SAFE_PATHNAME(p, namelen, "require"))
3860 if (memENDPs(p, namelen, ".pm")) {
3861 SV *const pmcsv = sv_newmortal();
3864 SvSetSV_nosteal(pmcsv,name);
3865 sv_catpvs(pmcsv, "c");
3867 pmcio = check_type_and_open(pmcsv);
3871 return check_type_and_open(name);
3874 # define doopen_pm(name) check_type_and_open(name)
3875 #endif /* !PERL_DISABLE_PMC */
3877 /* require doesn't search in @INC for absolute names, or when the name is
3878 explicitly relative the current directory: i.e. ./, ../ */
3879 PERL_STATIC_INLINE bool
3880 S_path_is_searchable(const char *name)
3882 PERL_ARGS_ASSERT_PATH_IS_SEARCHABLE;
3884 if (PERL_FILE_IS_ABSOLUTE(name)
3886 || (*name == '.' && ((name[1] == '/' ||
3887 (name[1] == '.' && name[2] == '/'))
3888 || (name[1] == '\\' ||
3889 ( name[1] == '.' && name[2] == '\\')))
3892 || (*name == '.' && (name[1] == '/' ||
3893 (name[1] == '.' && name[2] == '/')))
3904 /* implement 'require 5.010001' */
3907 S_require_version(pTHX_ SV *sv)
3911 sv = sv_2mortal(new_version(sv));
3912 if (!Perl_sv_derived_from_pvn(aTHX_ PL_patchlevel, STR_WITH_LEN("version"), 0))
3913 upg_version(PL_patchlevel, TRUE);
3914 if (cUNOP->op_first->op_type == OP_CONST && cUNOP->op_first->op_private & OPpCONST_NOVER) {
3915 if ( vcmp(sv,PL_patchlevel) <= 0 )
3916 DIE(aTHX_ "Perls since %" SVf " too modern--this is %" SVf ", stopped",
3917 SVfARG(sv_2mortal(vnormal(sv))),
3918 SVfARG(sv_2mortal(vnormal(PL_patchlevel)))
3922 if ( vcmp(sv,PL_patchlevel) > 0 ) {
3925 SV * const req = SvRV(sv);
3926 SV * const pv = *hv_fetchs(MUTABLE_HV(req), "original", FALSE);
3928 /* get the left hand term */
3929 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(req), "version", FALSE)));
3931 first = SvIV(*av_fetch(lav,0,0));
3932 if ( first > (int)PERL_REVISION /* probably 'use 6.0' */
3933 || hv_exists(MUTABLE_HV(req), "qv", 2 ) /* qv style */
3934 || av_count(lav) > 2 /* FP with > 3 digits */
3935 || strstr(SvPVX(pv),".0") /* FP with leading 0 */
3937 DIE(aTHX_ "Perl %" SVf " required--this is only "
3938 "%" SVf ", stopped",
3939 SVfARG(sv_2mortal(vnormal(req))),
3940 SVfARG(sv_2mortal(vnormal(PL_patchlevel)))
3943 else { /* probably 'use 5.10' or 'use 5.8' */
3947 if (av_count(lav) > 1)
3948 second = SvIV(*av_fetch(lav,1,0));
3950 second /= second >= 600 ? 100 : 10;
3951 hintsv = Perl_newSVpvf(aTHX_ "v%d.%d.0",
3952 (int)first, (int)second);
3953 upg_version(hintsv, TRUE);
3955 DIE(aTHX_ "Perl %" SVf " required (did you mean %" SVf "?)"
3956 "--this is only %" SVf ", stopped",
3957 SVfARG(sv_2mortal(vnormal(req))),
3958 SVfARG(sv_2mortal(vnormal(sv_2mortal(hintsv)))),
3959 SVfARG(sv_2mortal(vnormal(PL_patchlevel)))
3968 /* Handle C<require Foo::Bar>, C<require "Foo/Bar.pm"> and C<do "Foo.pm">.
3969 * The first form will have already been converted at compile time to
3970 * the second form */
3973 S_require_file(pTHX_ SV *sv)
3983 int vms_unixname = 0;
3986 /* tryname is the actual pathname (with @INC prefix) which was loaded.
3987 * It's stored as a value in %INC, and used for error messages */
3988 const char *tryname = NULL;
3989 SV *namesv = NULL; /* SV equivalent of tryname */
3990 const U8 gimme = GIMME_V;
3991 int filter_has_file = 0;
3992 PerlIO *tryrsfp = NULL;
3993 SV *filter_cache = NULL;
3994 SV *filter_state = NULL;
3995 SV *filter_sub = NULL;
3999 bool path_searchable;
4000 I32 old_savestack_ix;
4001 const bool op_is_require = PL_op->op_type == OP_REQUIRE;
4002 const char *const op_name = op_is_require ? "require" : "do";
4003 SV ** svp_cached = NULL;
4005 assert(op_is_require || PL_op->op_type == OP_DOFILE);
4008 DIE(aTHX_ "Missing or undefined argument to %s", op_name);
4009 name = SvPV_nomg_const(sv, len);
4010 if (!(name && len > 0 && *name))
4011 DIE(aTHX_ "Missing or undefined argument to %s", op_name);
4014 /* try to return earlier (save the SAFE_PATHNAME check) if INC already got the name */
4015 if (op_is_require) {
4016 /* can optimize to only perform one single lookup */
4017 svp_cached = hv_fetch(GvHVn(PL_incgv), (char*) name, len, 0);
4018 if ( svp_cached && (SvGETMAGIC(*svp_cached), SvOK(*svp_cached)) ) RETPUSHYES;
4022 if (!IS_SAFE_PATHNAME(name, len, op_name)) {
4023 if (!op_is_require) {
4027 DIE(aTHX_ "Can't locate %s: %s",
4028 pv_escape(newSVpvs_flags("",SVs_TEMP),name,len,len*2,
4029 NULL, SvUTF8(sv)?PERL_PV_ESCAPE_UNI:0),
4032 TAINT_PROPER(op_name);
4034 path_searchable = path_is_searchable(name);
4037 /* The key in the %ENV hash is in the syntax of file passed as the argument
4038 * usually this is in UNIX format, but sometimes in VMS format, which
4039 * can result in a module being pulled in more than once.
4040 * To prevent this, the key must be stored in UNIX format if the VMS
4041 * name can be translated to UNIX.
4045 tounixspec(name, SvPVX(sv_2mortal(newSVpv("", VMS_MAXRSS-1)))))
4047 unixlen = strlen(unixname);
4053 /* if not VMS or VMS name can not be translated to UNIX, pass it
4056 unixname = (char *) name;
4059 if (op_is_require) {
4060 /* reuse the previous hv_fetch result if possible */
4061 SV * const * const svp = svp_cached ? svp_cached : hv_fetch(GvHVn(PL_incgv), unixname, unixlen, 0);
4063 /* we already did a get magic if this was cached */
4069 DIE(aTHX_ "Attempt to reload %s aborted.\n"
4070 "Compilation failed in require", unixname);
4073 /*XXX OPf_KIDS should always be true? -dapm 4/2017 */
4074 if (PL_op->op_flags & OPf_KIDS) {
4075 SVOP * const kid = cSVOPx(cUNOP->op_first);
4077 if (kid->op_type == OP_CONST && (kid->op_private & OPpCONST_BARE)) {
4078 /* Make sure that a bareword module name (e.g. ::Foo::Bar)
4079 * doesn't map to a naughty pathname like /Foo/Bar.pm.
4080 * Note that the parser will normally detect such errors
4081 * at compile time before we reach here, but
4082 * Perl_load_module() can fake up an identical optree
4083 * without going near the parser, and being able to put
4084 * anything as the bareword. So we include a duplicate set
4085 * of checks here at runtime.
4087 const STRLEN package_len = len - 3;
4088 const char slashdot[2] = {'/', '.'};
4090 const char backslashdot[2] = {'\\', '.'};
4093 /* Disallow *purported* barewords that map to absolute
4094 filenames, filenames relative to the current or parent
4095 directory, or (*nix) hidden filenames. Also sanity check
4096 that the generated filename ends .pm */
4097 if (!path_searchable || len < 3 || name[0] == '.'
4098 || !memEQs(name + package_len, len - package_len, ".pm"))
4099 DIE(aTHX_ "Bareword in require maps to disallowed filename \"%" SVf "\"", sv);
4100 if (memchr(name, 0, package_len)) {
4101 /* diag_listed_as: Bareword in require contains "%s" */
4102 DIE(aTHX_ "Bareword in require contains \"\\0\"");
4104 if (ninstr(name, name + package_len, slashdot,
4105 slashdot + sizeof(slashdot))) {
4106 /* diag_listed_as: Bareword in require contains "%s" */
4107 DIE(aTHX_ "Bareword in require contains \"/.\"");
4110 if (ninstr(name, name + package_len, backslashdot,
4111 backslashdot + sizeof(backslashdot))) {
4112 /* diag_listed_as: Bareword in require contains "%s" */
4113 DIE(aTHX_ "Bareword in require contains \"\\.\"");
4120 PERL_DTRACE_PROBE_FILE_LOADING(unixname);
4122 /* Try to locate and open a file, possibly using @INC */
4124 /* with "/foo/bar.pm", "./foo.pm" and "../foo/bar.pm", try to load
4125 * the file directly rather than via @INC ... */
4126 if (!path_searchable) {
4127 /* At this point, name is SvPVX(sv) */
4129 tryrsfp = doopen_pm(sv);
4132 /* ... but if we fail, still search @INC for code references;
4133 * these are applied even on non-searchable paths (except
4134 * if we got EACESS).
4136 * For searchable paths, just search @INC normally
4138 if (!tryrsfp && !(errno == EACCES && !path_searchable)) {
4139 AV * const ar = GvAVn(PL_incgv);
4146 namesv = newSV_type(SVt_PV);
4147 for (i = 0; i <= AvFILL(ar); i++) {
4148 SV * const dirsv = *av_fetch(ar, i, TRUE);
4156 if (SvTYPE(SvRV(loader)) == SVt_PVAV
4157 && !SvOBJECT(SvRV(loader)))
4159 loader = *av_fetch(MUTABLE_AV(SvRV(loader)), 0, TRUE);
4163 Perl_sv_setpvf(aTHX_ namesv, "/loader/0x%" UVxf "/%s",
4164 PTR2UV(SvRV(dirsv)), name);
4165 tryname = SvPVX_const(namesv);
4168 if (SvPADTMP(nsv)) {
4169 nsv = sv_newmortal();
4170 SvSetSV_nosteal(nsv,sv);
4173 ENTER_with_name("call_INC");
4181 if (SvGMAGICAL(loader)) {
4182 SV *l = sv_newmortal();
4183 sv_setsv_nomg(l, loader);
4186 if (sv_isobject(loader))
4187 count = call_method("INC", G_LIST);
4189 count = call_sv(loader, G_LIST);
4199 if (SvROK(arg) && (SvTYPE(SvRV(arg)) <= SVt_PVLV)
4200 && !isGV_with_GP(SvRV(arg))) {
4201 filter_cache = SvRV(arg);
4208 if (SvROK(arg) && isGV_with_GP(SvRV(arg))) {
4212 if (isGV_with_GP(arg)) {
4213 IO * const io = GvIO((const GV *)arg);
4218 tryrsfp = IoIFP(io);
4219 if (IoOFP(io) && IoOFP(io) != IoIFP(io)) {
4220 PerlIO_close(IoOFP(io));
4231 if (SvROK(arg) && SvTYPE(SvRV(arg)) == SVt_PVCV) {
4233 SvREFCNT_inc_simple_void_NN(filter_sub);
4236 filter_state = SP[i];
4237 SvREFCNT_inc_simple_void(filter_state);
4241 if (!tryrsfp && (filter_cache || filter_sub)) {
4242 tryrsfp = PerlIO_open(BIT_BUCKET,
4248 /* FREETMPS may free our filter_cache */
4249 SvREFCNT_inc_simple_void(filter_cache);
4253 LEAVE_with_name("call_INC");
4255 /* Now re-mortalize it. */
4256 sv_2mortal(filter_cache);
4258 /* Adjust file name if the hook has set an %INC entry.
4259 This needs to happen after the FREETMPS above. */
4260 svp = hv_fetch(GvHVn(PL_incgv), name, len, 0);
4262 tryname = SvPV_nolen_const(*svp);
4269 filter_has_file = 0;
4270 filter_cache = NULL;
4272 SvREFCNT_dec_NN(filter_state);
4273 filter_state = NULL;
4276 SvREFCNT_dec_NN(filter_sub);
4280 else if (path_searchable) {
4281 /* match against a plain @INC element (non-searchable
4282 * paths are only matched against refs in @INC) */
4287 dir = SvPV_nomg_const(dirsv, dirlen);
4293 if (!IS_SAFE_SYSCALL(dir, dirlen, "@INC entry", op_name))
4297 tounixpath(dir, SvPVX(sv_2mortal(newSVpv("", VMS_MAXRSS-1)))))
4300 sv_setpv(namesv, unixdir);
4301 sv_catpv(namesv, unixname);
4303 /* The equivalent of
4304 Perl_sv_setpvf(aTHX_ namesv, "%s/%s", dir, name);
4305 but without the need to parse the format string, or
4306 call strlen on either pointer, and with the correct
4307 allocation up front. */
4309 char *tmp = SvGROW(namesv, dirlen + len + 2);
4311 memcpy(tmp, dir, dirlen);
4314 /* Avoid '<dir>//<file>' */
4315 if (!dirlen || *(tmp-1) != '/') {
4318 /* So SvCUR_set reports the correct length below */
4322 /* name came from an SV, so it will have a '\0' at the
4323 end that we can copy as part of this memcpy(). */
4324 memcpy(tmp, name, len + 1);
4326 SvCUR_set(namesv, dirlen + len + 1);
4330 TAINT_PROPER(op_name);
4331 tryname = SvPVX_const(namesv);
4332 tryrsfp = doopen_pm(namesv);
4334 if (tryname[0] == '.' && tryname[1] == '/') {
4336 while (*++tryname == '/') {}
4340 else if (errno == EMFILE || errno == EACCES) {
4341 /* no point in trying other paths if out of handles;
4342 * on the other hand, if we couldn't open one of the
4343 * files, then going on with the search could lead to
4344 * unexpected results; see perl #113422
4353 /* at this point we've ether opened a file (tryrsfp) or set errno */
4355 saved_errno = errno; /* sv_2mortal can realloc things */
4358 /* we failed; croak if require() or return undef if do() */
4359 if (op_is_require) {
4360 if(saved_errno == EMFILE || saved_errno == EACCES) {
4361 /* diag_listed_as: Can't locate %s */
4362 DIE(aTHX_ "Can't locate %s: %s: %s",
4363 name, tryname, Strerror(saved_errno));
4365 if (path_searchable) { /* did we lookup @INC? */
4366 AV * const ar = GvAVn(PL_incgv);
4368 SV *const msg = newSVpvs_flags("", SVs_TEMP);
4369 SV *const inc = newSVpvs_flags("", SVs_TEMP);
4370 for (i = 0; i <= AvFILL(ar); i++) {
4371 sv_catpvs(inc, " ");
4372 sv_catsv(inc, *av_fetch(ar, i, TRUE));
4374 if (memENDPs(name, len, ".pm")) {
4375 const char *e = name + len - (sizeof(".pm") - 1);
4377 bool utf8 = cBOOL(SvUTF8(sv));
4379 /* if the filename, when converted from "Foo/Bar.pm"
4380 * form back to Foo::Bar form, makes a valid
4381 * package name (i.e. parseable by C<require
4382 * Foo::Bar>), then emit a hint.
4384 * this loop is modelled after the one in
4388 if (utf8 && isIDFIRST_utf8_safe(c, e)) {
4390 while (c < e && isIDCONT_utf8_safe(
4391 (const U8*) c, (const U8*) e))
4394 else if (isWORDCHAR_A(*c)) {
4395 while (c < e && isWORDCHAR_A(*c))
4404 if (c == e && isIDFIRST_lazy_if_safe(name, e, utf8)) {
4405 sv_catpvs(msg, " (you may need to install the ");
4406 for (c = name; c < e; c++) {
4408 sv_catpvs(msg, "::");
4411 sv_catpvn(msg, c, 1);
4414 sv_catpvs(msg, " module)");
4417 else if (memENDs(name, len, ".h")) {
4418 sv_catpvs(msg, " (change .h to .ph maybe?) (did you run h2ph?)");
4420 else if (memENDs(name, len, ".ph")) {
4421 sv_catpvs(msg, " (did you run h2ph?)");
4424 /* diag_listed_as: Can't locate %s */
4426 "Can't locate %s in @INC%" SVf " (@INC contains:%" SVf ")",
4430 DIE(aTHX_ "Can't locate %s", name);
4433 #ifdef DEFAULT_INC_EXCLUDES_DOT
4437 /* the complication is to match the logic from doopen_pm() so
4438 * we don't treat do "sda1" as a previously successful "do".
4440 bool do_warn = namesv && ckWARN_d(WARN_DEPRECATED)
4441 && PerlLIO_stat(name, &st) == 0 && !S_ISDIR(st.st_mode) && !S_ISBLK(st.st_mode)
4442 && (io = PerlIO_openn(aTHX_ ":", PERL_SCRIPT_MODE, -1, 0, 0, NULL, 1, &sv)) != NULL;
4448 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),
4449 "do \"%s\" failed, '.' is no longer in @INC; "
4450 "did you mean do \"./%s\"?",
4459 SETERRNO(0, SS_NORMAL);
4461 /* Update %INC. Assume success here to prevent recursive requirement. */
4462 /* name is never assigned to again, so len is still strlen(name) */
4463 /* Check whether a hook in @INC has already filled %INC */
4465 (void)hv_store(GvHVn(PL_incgv),
4466 unixname, unixlen, newSVpv(tryname,0),0);
4468 SV** const svp = hv_fetch(GvHVn(PL_incgv), unixname, unixlen, 0);
4470 (void)hv_store(GvHVn(PL_incgv),
4471 unixname, unixlen, SvREFCNT_inc_simple(hook_sv), 0 );
4474 /* Now parse the file */
4476 old_savestack_ix = PL_savestack_ix;
4477 SAVECOPFILE_FREE(&PL_compiling);
4478 CopFILE_set(&PL_compiling, tryname);
4479 lex_start(NULL, tryrsfp, 0);
4481 if (filter_sub || filter_cache) {
4482 /* We can use the SvPV of the filter PVIO itself as our cache, rather
4483 than hanging another SV from it. In turn, filter_add() optionally
4484 takes the SV to use as the filter (or creates a new SV if passed
4485 NULL), so simply pass in whatever value filter_cache has. */
4486 SV * const fc = filter_cache ? newSV_type(SVt_NULL) : NULL;
4488 if (fc) sv_copypv(fc, filter_cache);
4489 datasv = filter_add(S_run_user_filter, fc);
4490 IoLINES(datasv) = filter_has_file;
4491 IoTOP_GV(datasv) = MUTABLE_GV(filter_state);
4492 IoBOTTOM_GV(datasv) = MUTABLE_GV(filter_sub);
4495 /* switch to eval mode */
4497 cx = cx_pushblock(CXt_EVAL, gimme, SP, old_savestack_ix);
4498 cx_pusheval(cx, PL_op->op_next, newSVpv(name, 0));
4500 SAVECOPLINE(&PL_compiling);
4501 CopLINE_set(&PL_compiling, 0);
4505 if (doeval_compile(gimme, NULL, PL_curcop->cop_seq, NULL))
4508 op = PL_op->op_next;
4510 PERL_DTRACE_PROBE_FILE_LOADED(unixname);
4516 /* also used for: pp_dofile() */
4520 /* If a suitable JMPENV catch frame isn't present, call docatch(),
4522 * - add such a frame, and
4523 * - start a new RUNOPS loop, which will (as the first op to run),
4524 * recursively call this pp function again.
4525 * The main body of this function is then executed by the inner call.
4528 return docatch(Perl_pp_require);
4535 return ((SvNIOKp(sv) || SvVOK(sv)) && PL_op->op_type != OP_DOFILE)
4536 ? S_require_version(aTHX_ sv)
4537 : S_require_file(aTHX_ sv);
4542 /* This is a op added to hold the hints hash for
4543 pp_entereval. The hash can be modified by the code
4544 being eval'ed, so we return a copy instead. */
4549 mXPUSHs(MUTABLE_SV(hv_copy_hints_hv(MUTABLE_HV(cSVOP_sv))));
4561 char tbuf[TYPE_DIGITS(long) + 12];
4569 I32 old_savestack_ix;
4571 /* If a suitable JMPENV catch frame isn't present, call docatch(),
4573 * - add such a frame, and
4574 * - start a new RUNOPS loop, which will (as the first op to run),
4575 * recursively call this pp function again.
4576 * The main body of this function is then executed by the inner call.
4579 return docatch(Perl_pp_entereval);
4582 was = PL_breakable_sub_gen;
4583 saved_delete = FALSE;
4587 bytes = PL_op->op_private & OPpEVAL_BYTES;
4589 if (PL_op->op_private & OPpEVAL_HAS_HH) {
4590 saved_hh = MUTABLE_HV(SvREFCNT_inc(POPs));
4592 else if (PL_hints & HINT_LOCALIZE_HH || (
4593 PL_op->op_private & OPpEVAL_COPHH
4594 && PL_curcop->cop_hints & HINT_LOCALIZE_HH
4596 saved_hh = cop_hints_2hv(PL_curcop, 0);
4597 hv_magic(saved_hh, NULL, PERL_MAGIC_hints);
4601 /* make sure we've got a plain PV (no overload etc) before testing
4602 * for taint. Making a copy here is probably overkill, but better
4603 * safe than sorry */
4605 const char * const p = SvPV_const(sv, len);
4607 sv = newSVpvn_flags(p, len, SVs_TEMP | SvUTF8(sv));
4608 lex_flags |= LEX_START_COPIED;
4610 if (bytes && SvUTF8(sv))
4611 SvPVbyte_force(sv, len);
4613 else if (bytes && SvUTF8(sv)) {
4614 /* Don't modify someone else's scalar */
4617 (void)sv_2mortal(sv);
4618 SvPVbyte_force(sv,len);
4619 lex_flags |= LEX_START_COPIED;
4622 TAINT_IF(SvTAINTED(sv));
4623 TAINT_PROPER("eval");
4625 old_savestack_ix = PL_savestack_ix;
4627 lex_start(sv, NULL, lex_flags | (PL_op->op_private & OPpEVAL_UNICODE
4628 ? LEX_IGNORE_UTF8_HINTS
4629 : bytes ? LEX_EVALBYTES : LEX_START_SAME_FILTER
4633 /* switch to eval mode */
4635 if (PERLDB_NAMEEVAL && CopLINE(PL_curcop)) {
4636 SV * const temp_sv = sv_newmortal();
4637 Perl_sv_setpvf(aTHX_ temp_sv, "_<(eval %lu)[%s:%" IVdf "]",
4638 (unsigned long)++PL_evalseq,
4639 CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
4640 tmpbuf = SvPVX(temp_sv);
4641 len = SvCUR(temp_sv);
4644 len = my_snprintf(tmpbuf, sizeof(tbuf), "_<(eval %lu)", (unsigned long)++PL_evalseq);
4645 SAVECOPFILE_FREE(&PL_compiling);
4646 CopFILE_set(&PL_compiling, tmpbuf+2);
4647 SAVECOPLINE(&PL_compiling);
4648 CopLINE_set(&PL_compiling, 1);
4649 /* special case: an eval '' executed within the DB package gets lexically
4650 * placed in the first non-DB CV rather than the current CV - this
4651 * allows the debugger to execute code, find lexicals etc, in the
4652 * scope of the code being debugged. Passing &seq gets find_runcv
4653 * to do the dirty work for us */
4654 runcv = find_runcv(&seq);
4657 cx = cx_pushblock((CXt_EVAL|CXp_REAL), gimme, SP, old_savestack_ix);
4658 cx_pusheval(cx, PL_op->op_next, NULL);
4660 /* prepare to compile string */
4662 if (PERLDB_LINE_OR_SAVESRC && PL_curstash != PL_debstash)
4663 save_lines(CopFILEAV(&PL_compiling), PL_parser->linestr);
4665 /* XXX For C<eval "...">s within BEGIN {} blocks, this ends up
4666 deleting the eval's FILEGV from the stash before gv_check() runs
4667 (i.e. before run-time proper). To work around the coredump that
4668 ensues, we always turn GvMULTI_on for any globals that were
4669 introduced within evals. See force_ident(). GSAR 96-10-12 */
4670 char *const safestr = savepvn(tmpbuf, len);
4671 SAVEDELETE(PL_defstash, safestr, len);
4672 saved_delete = TRUE;
4677 if (doeval_compile(gimme, runcv, seq, saved_hh)) {
4678 if (was != PL_breakable_sub_gen /* Some subs defined here. */
4679 ? PERLDB_LINE_OR_SAVESRC
4680 : PERLDB_SAVESRC_NOSUBS) {
4681 /* Retain the filegv we created. */
4682 } else if (!saved_delete) {
4683 char *const safestr = savepvn(tmpbuf, len);
4684 SAVEDELETE(PL_defstash, safestr, len);
4686 return PL_eval_start;
4688 /* We have already left the scope set up earlier thanks to the LEAVE
4689 in doeval_compile(). */
4690 if (was != PL_breakable_sub_gen /* Some subs defined here. */
4691 ? PERLDB_LINE_OR_SAVESRC
4692 : PERLDB_SAVESRC_INVALID) {
4693 /* Retain the filegv we created. */
4694 } else if (!saved_delete) {
4695 (void)hv_delete(PL_defstash, tmpbuf, len, G_DISCARD);
4697 return PL_op->op_next;
4702 /* also tail-called by pp_return */
4717 assert(CxTYPE(cx) == CXt_EVAL);
4719 oldsp = PL_stack_base + cx->blk_oldsp;
4720 gimme = cx->blk_gimme;
4722 /* did require return a false value? */
4723 failed = CxOLD_OP_TYPE(cx) == OP_REQUIRE
4724 && !(gimme == G_SCALAR
4725 ? SvTRUE_NN(*PL_stack_sp)
4726 : PL_stack_sp > oldsp);
4728 if (gimme == G_VOID) {
4729 PL_stack_sp = oldsp;
4730 /* free now to avoid late-called destructors clobbering $@ */
4734 leave_adjust_stacks(oldsp, oldsp, gimme, 0);
4736 /* the cx_popeval does a leavescope, which frees the optree associated
4737 * with eval, which if it frees the nextstate associated with
4738 * PL_curcop, sets PL_curcop to NULL. Which can mess up freeing a
4739 * regex when running under 'use re Debug' because it needs PL_curcop
4740 * to get the current hints. So restore it early.
4742 PL_curcop = cx->blk_oldcop;
4744 /* grab this value before cx_popeval restores the old PL_in_eval */
4745 keep = cBOOL(PL_in_eval & EVAL_KEEPERR);
4746 retop = cx->blk_eval.retop;
4747 evalcv = cx->blk_eval.cv;
4749 assert(CvDEPTH(evalcv) == 1);
4751 CvDEPTH(evalcv) = 0;
4753 /* pop the CXt_EVAL, and if a require failed, croak */
4754 S_pop_eval_context_maybe_croak(aTHX_ cx, NULL, failed);
4762 /* Ops that implement try/catch syntax
4763 * Note the asymmetry here:
4764 * pp_entertrycatch does two pushblocks
4765 * pp_leavetrycatch pops only the outer one; the inner one is popped by
4766 * pp_poptry or by stack-unwind of die within the try block
4769 PP(pp_entertrycatch)
4772 const U8 gimme = GIMME_V;
4774 /* If a suitable JMPENV catch frame isn't present, call docatch(),
4776 * - add such a frame, and
4777 * - start a new RUNOPS loop, which will (as the first op to run),
4778 * recursively call this pp function again.
4779 * The main body of this function is then executed by the inner call.
4782 return docatch(Perl_pp_entertrycatch);
4786 Perl_pp_enter(aTHX); /* performs cx_pushblock(CXt_BLOCK, ...) */
4788 save_scalar(PL_errgv);
4791 cx = cx_pushblock((CXt_EVAL|CXp_EVALBLOCK|CXp_TRY), gimme,
4792 PL_stack_sp, PL_savestack_ix);
4793 cx_pushtry(cx, cLOGOP->op_other);
4795 PL_in_eval = EVAL_INEVAL;
4800 PP(pp_leavetrycatch)
4802 /* leavetrycatch is leave */
4803 return Perl_pp_leave(aTHX);
4808 /* poptry is leavetry */
4809 return Perl_pp_leavetry(aTHX);
4816 save_clearsv(&(PAD_SVl(PL_op->op_targ)));
4817 sv_setsv(TARG, ERRSV);
4820 return cLOGOP->op_other;
4823 /* Common code for Perl_call_sv and Perl_fold_constants, put here to keep it
4824 close to the related Perl_create_eval_scope. */
4826 Perl_delete_eval_scope(pTHX)
4837 /* Common-ish code salvaged from Perl_call_sv and pp_entertry, because it was
4838 also needed by Perl_fold_constants. */
4840 Perl_create_eval_scope(pTHX_ OP *retop, U32 flags)
4843 const U8 gimme = GIMME_V;
4845 cx = cx_pushblock((CXt_EVAL|CXp_EVALBLOCK), gimme,
4846 PL_stack_sp, PL_savestack_ix);
4847 cx_pusheval(cx, retop, NULL);
4849 PL_in_eval = EVAL_INEVAL;
4850 if (flags & G_KEEPERR)
4851 PL_in_eval |= EVAL_KEEPERR;
4854 if (flags & G_FAKINGEVAL) {
4855 PL_eval_root = PL_op; /* Only needed so that goto works right. */
4861 OP *retop = cLOGOP->op_other->op_next;
4863 /* If a suitable JMPENV catch frame isn't present, call docatch(),
4865 * - add such a frame, and
4866 * - start a new RUNOPS loop, which will (as the first op to run),
4867 * recursively call this pp function again.
4868 * The main body of this function is then executed by the inner call.
4871 return docatch(Perl_pp_entertry);
4875 create_eval_scope(retop, 0);
4877 return PL_op->op_next;
4881 /* also tail-called by pp_return */
4893 assert(CxTYPE(cx) == CXt_EVAL);
4894 oldsp = PL_stack_base + cx->blk_oldsp;
4895 gimme = cx->blk_gimme;
4897 if (gimme == G_VOID) {
4898 PL_stack_sp = oldsp;
4899 /* free now to avoid late-called destructors clobbering $@ */
4903 leave_adjust_stacks(oldsp, oldsp, gimme, 1);
4907 retop = CxTRY(cx) ? PL_op->op_next : cx->blk_eval.retop;
4918 const U8 gimme = GIMME_V;
4922 assert(!PL_op->op_targ); /* used to be set for lexical $_ */
4923 GvSV(PL_defgv) = SvREFCNT_inc(newsv);
4925 cx = cx_pushblock(CXt_GIVEN, gimme, SP, PL_savestack_ix);
4926 cx_pushgiven(cx, origsv);
4936 PERL_UNUSED_CONTEXT;
4939 assert(CxTYPE(cx) == CXt_GIVEN);
4940 oldsp = PL_stack_base + cx->blk_oldsp;
4941 gimme = cx->blk_gimme;
4943 if (gimme == G_VOID)
4944 PL_stack_sp = oldsp;
4946 leave_adjust_stacks(oldsp, oldsp, gimme, 1);
4956 /* Helper routines used by pp_smartmatch */
4958 S_make_matcher(pTHX_ REGEXP *re)
4960 PMOP *matcher = cPMOPx(newPMOP(OP_MATCH, OPf_WANT_SCALAR | OPf_STACKED));
4962 PERL_ARGS_ASSERT_MAKE_MATCHER;
4964 PM_SETRE(matcher, ReREFCNT_inc(re));
4966 SAVEFREEOP((OP *) matcher);
4967 ENTER_with_name("matcher"); SAVETMPS;
4973 S_matcher_matches_sv(pTHX_ PMOP *matcher, SV *sv)
4978 PERL_ARGS_ASSERT_MATCHER_MATCHES_SV;
4980 PL_op = (OP *) matcher;
4983 (void) Perl_pp_match(aTHX);
4985 result = SvTRUEx(POPs);
4992 S_destroy_matcher(pTHX_ PMOP *matcher)
4994 PERL_ARGS_ASSERT_DESTROY_MATCHER;
4995 PERL_UNUSED_ARG(matcher);
4998 LEAVE_with_name("matcher");
5001 /* Do a smart match */
5004 DEBUG_M(Perl_deb(aTHX_ "Starting smart match resolution\n"));
5005 return do_smartmatch(NULL, NULL, 0);
5008 /* This version of do_smartmatch() implements the
5009 * table of smart matches that is found in perlsyn.
5012 S_do_smartmatch(pTHX_ HV *seen_this, HV *seen_other, const bool copied)
5016 bool object_on_left = FALSE;
5017 SV *e = TOPs; /* e is for 'expression' */
5018 SV *d = TOPm1s; /* d is for 'default', as in PL_defgv */
5020 /* Take care only to invoke mg_get() once for each argument.
5021 * Currently we do this by copying the SV if it's magical. */
5023 if (!copied && SvGMAGICAL(d))
5024 d = sv_mortalcopy(d);
5031 e = sv_mortalcopy(e);
5033 /* First of all, handle overload magic of the rightmost argument */
5036 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Object\n"));
5037 DEBUG_M(Perl_deb(aTHX_ " attempting overload\n"));
5039 tmpsv = amagic_call(d, e, smart_amg, AMGf_noleft);
5046 DEBUG_M(Perl_deb(aTHX_ " failed to run overload method; continuing...\n"));
5049 SP -= 2; /* Pop the values */
5054 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-undef\n"));
5061 if (SvROK(e) && SvOBJECT(SvRV(e)) && (SvTYPE(SvRV(e)) != SVt_REGEXP)) {
5062 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Object\n"));
5063 Perl_croak(aTHX_ "Smart matching a non-overloaded object breaks encapsulation");
5065 if (SvROK(d) && SvOBJECT(SvRV(d)) && (SvTYPE(SvRV(d)) != SVt_REGEXP))
5066 object_on_left = TRUE;
5069 if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_PVCV) {
5071 if (object_on_left) {
5072 goto sm_any_sub; /* Treat objects like scalars */
5074 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
5075 /* Test sub truth for each key */
5077 bool andedresults = TRUE;
5078 HV *hv = (HV*) SvRV(d);
5079 I32 numkeys = hv_iterinit(hv);
5080 DEBUG_M(Perl_deb(aTHX_ " applying rule Hash-CodeRef\n"));
5083 while ( (he = hv_iternext(hv)) ) {
5084 DEBUG_M(Perl_deb(aTHX_ " testing hash key...\n"));
5085 ENTER_with_name("smartmatch_hash_key_test");
5088 PUSHs(hv_iterkeysv(he));
5090 c = call_sv(e, G_SCALAR);
5093 andedresults = FALSE;
5095 andedresults = SvTRUEx(POPs) && andedresults;
5097 LEAVE_with_name("smartmatch_hash_key_test");
5104 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
5105 /* Test sub truth for each element */
5107 bool andedresults = TRUE;
5108 AV *av = (AV*) SvRV(d);
5109 const Size_t len = av_count(av);
5110 DEBUG_M(Perl_deb(aTHX_ " applying rule Array-CodeRef\n"));
5113 for (i = 0; i < len; ++i) {
5114 SV * const * const svp = av_fetch(av, i, FALSE);
5115 DEBUG_M(Perl_deb(aTHX_ " testing array element...\n"));
5116 ENTER_with_name("smartmatch_array_elem_test");
5122 c = call_sv(e, G_SCALAR);
5125 andedresults = FALSE;
5127 andedresults = SvTRUEx(POPs) && andedresults;
5129 LEAVE_with_name("smartmatch_array_elem_test");
5138 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-CodeRef\n"));
5139 ENTER_with_name("smartmatch_coderef");
5144 c = call_sv(e, G_SCALAR);
5148 else if (SvTEMP(TOPs))
5149 SvREFCNT_inc_void(TOPs);
5151 LEAVE_with_name("smartmatch_coderef");
5156 else if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_PVHV) {
5157 if (object_on_left) {
5158 goto sm_any_hash; /* Treat objects like scalars */
5160 else if (!SvOK(d)) {
5161 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Hash ($a undef)\n"));
5164 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
5165 /* Check that the key-sets are identical */
5167 HV *other_hv = MUTABLE_HV(SvRV(d));
5170 U32 this_key_count = 0,
5171 other_key_count = 0;
5172 HV *hv = MUTABLE_HV(SvRV(e));
5174 DEBUG_M(Perl_deb(aTHX_ " applying rule Hash-Hash\n"));
5175 /* Tied hashes don't know how many keys they have. */
5176 tied = cBOOL(SvTIED_mg((SV*)hv, PERL_MAGIC_tied));
5177 other_tied = cBOOL(SvTIED_mg((const SV *)other_hv, PERL_MAGIC_tied));
5181 HV * const temp = other_hv;
5187 else if(HvUSEDKEYS((const HV *) hv) != HvUSEDKEYS(other_hv))
5191 /* The hashes have the same number of keys, so it suffices
5192 to check that one is a subset of the other. */
5193 (void) hv_iterinit(hv);
5194 while ( (he = hv_iternext(hv)) ) {
5195 SV *key = hv_iterkeysv(he);
5197 DEBUG_M(Perl_deb(aTHX_ " comparing hash key...\n"));
5200 if(!hv_exists_ent(other_hv, key, 0)) {
5201 (void) hv_iterinit(hv); /* reset iterator */
5207 (void) hv_iterinit(other_hv);
5208 while ( hv_iternext(other_hv) )
5212 other_key_count = HvUSEDKEYS(other_hv);
5214 if (this_key_count != other_key_count)
5219 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
5220 AV * const other_av = MUTABLE_AV(SvRV(d));
5221 const Size_t other_len = av_count(other_av);
5223 HV *hv = MUTABLE_HV(SvRV(e));
5225 DEBUG_M(Perl_deb(aTHX_ " applying rule Array-Hash\n"));
5226 for (i = 0; i < other_len; ++i) {
5227 SV ** const svp = av_fetch(other_av, i, FALSE);
5228 DEBUG_M(Perl_deb(aTHX_ " checking for key existence...\n"));
5229 if (svp) { /* ??? When can this not happen? */
5230 if (hv_exists_ent(hv, *svp, 0))
5236 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_REGEXP) {
5237 DEBUG_M(Perl_deb(aTHX_ " applying rule Regex-Hash\n"));
5240 PMOP * const matcher = make_matcher((REGEXP*) SvRV(d));
5242 HV *hv = MUTABLE_HV(SvRV(e));
5244 (void) hv_iterinit(hv);
5245 while ( (he = hv_iternext(hv)) ) {
5246 DEBUG_M(Perl_deb(aTHX_ " testing key against pattern...\n"));
5248 if (matcher_matches_sv(matcher, hv_iterkeysv(he))) {
5250 (void) hv_iterinit(hv);
5251 destroy_matcher(matcher);
5256 destroy_matcher(matcher);
5262 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Hash\n"));
5263 if (hv_exists_ent(MUTABLE_HV(SvRV(e)), d, 0))
5270 else if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_PVAV) {
5271 if (object_on_left) {
5272 goto sm_any_array; /* Treat objects like scalars */
5274 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
5275 AV * const other_av = MUTABLE_AV(SvRV(e));
5276 const Size_t other_len = av_count(other_av);
5279 DEBUG_M(Perl_deb(aTHX_ " applying rule Hash-Array\n"));
5280 for (i = 0; i < other_len; ++i) {
5281 SV ** const svp = av_fetch(other_av, i, FALSE);
5283 DEBUG_M(Perl_deb(aTHX_ " testing for key existence...\n"));
5284 if (svp) { /* ??? When can this not happen? */
5285 if (hv_exists_ent(MUTABLE_HV(SvRV(d)), *svp, 0))
5291 if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
5292 AV *other_av = MUTABLE_AV(SvRV(d));
5293 DEBUG_M(Perl_deb(aTHX_ " applying rule Array-Array\n"));
5294 if (av_count(MUTABLE_AV(SvRV(e))) != av_count(other_av))
5298 const Size_t other_len = av_count(other_av);
5300 if (NULL == seen_this) {
5301 seen_this = (HV*)newSV_type_mortal(SVt_PVHV);
5303 if (NULL == seen_other) {
5304 seen_other = (HV*)newSV_type_mortal(SVt_PVHV);
5306 for(i = 0; i < other_len; ++i) {
5307 SV * const * const this_elem = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
5308 SV * const * const other_elem = av_fetch(other_av, i, FALSE);
5310 if (!this_elem || !other_elem) {
5311 if ((this_elem && SvOK(*this_elem))
5312 || (other_elem && SvOK(*other_elem)))
5315 else if (hv_exists_ent(seen_this,
5316 sv_2mortal(newSViv(PTR2IV(*this_elem))), 0) ||
5317 hv_exists_ent(seen_other,
5318 sv_2mortal(newSViv(PTR2IV(*other_elem))), 0))
5320 if (*this_elem != *other_elem)
5324 (void)hv_store_ent(seen_this,
5325 sv_2mortal(newSViv(PTR2IV(*this_elem))),
5327 (void)hv_store_ent(seen_other,
5328 sv_2mortal(newSViv(PTR2IV(*other_elem))),
5334 DEBUG_M(Perl_deb(aTHX_ " recursively comparing array element...\n"));
5335 (void) do_smartmatch(seen_this, seen_other, 0);
5337 DEBUG_M(Perl_deb(aTHX_ " recursion finished\n"));
5346 else if (SvROK(d) && SvTYPE(SvRV(d)) == SVt_REGEXP) {
5347 DEBUG_M(Perl_deb(aTHX_ " applying rule Regex-Array\n"));
5350 PMOP * const matcher = make_matcher((REGEXP*) SvRV(d));
5351 const Size_t this_len = av_count(MUTABLE_AV(SvRV(e)));
5354 for(i = 0; i < this_len; ++i) {
5355 SV * const * const svp = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
5356 DEBUG_M(Perl_deb(aTHX_ " testing element against pattern...\n"));
5358 if (svp && matcher_matches_sv(matcher, *svp)) {
5360 destroy_matcher(matcher);
5365 destroy_matcher(matcher);
5369 else if (!SvOK(d)) {
5370 /* undef ~~ array */
5371 const Size_t this_len = av_count(MUTABLE_AV(SvRV(e)));
5374 DEBUG_M(Perl_deb(aTHX_ " applying rule Undef-Array\n"));
5375 for (i = 0; i < this_len; ++i) {
5376 SV * const * const svp = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
5377 DEBUG_M(Perl_deb(aTHX_ " testing for undef element...\n"));
5378 if (!svp || !SvOK(*svp))
5387 const Size_t this_len = av_count(MUTABLE_AV(SvRV(e)));
5389 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Array\n"));
5390 for (i = 0; i < this_len; ++i) {
5391 SV * const * const svp = av_fetch(MUTABLE_AV(SvRV(e)), i, FALSE);
5398 /* infinite recursion isn't supposed to happen here */
5399 DEBUG_M(Perl_deb(aTHX_ " recursively testing array element...\n"));
5400 (void) do_smartmatch(NULL, NULL, 1);
5402 DEBUG_M(Perl_deb(aTHX_ " recursion finished\n"));
5411 else if (SvROK(e) && SvTYPE(SvRV(e)) == SVt_REGEXP) {
5412 if (!object_on_left && SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVHV) {
5413 SV *t = d; d = e; e = t;
5414 DEBUG_M(Perl_deb(aTHX_ " applying rule Hash-Regex\n"));
5417 else if (!object_on_left && SvROK(d) && SvTYPE(SvRV(d)) == SVt_PVAV) {
5418 SV *t = d; d = e; e = t;
5419 DEBUG_M(Perl_deb(aTHX_ " applying rule Array-Regex\n"));
5420 goto sm_regex_array;
5423 PMOP * const matcher = make_matcher((REGEXP*) SvRV(e));
5426 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Regex\n"));
5428 result = matcher_matches_sv(matcher, d);
5430 PUSHs(result ? &PL_sv_yes : &PL_sv_no);
5431 destroy_matcher(matcher);
5436 /* See if there is overload magic on left */
5437 else if (object_on_left && SvAMAGIC(d)) {
5439 DEBUG_M(Perl_deb(aTHX_ " applying rule Object-Any\n"));
5440 DEBUG_M(Perl_deb(aTHX_ " attempting overload\n"));
5443 tmpsv = amagic_call(d, e, smart_amg, AMGf_noright);
5451 DEBUG_M(Perl_deb(aTHX_ " failed to run overload method; falling back...\n"));
5454 else if (!SvOK(d)) {
5455 /* undef ~~ scalar ; we already know that the scalar is SvOK */
5456 DEBUG_M(Perl_deb(aTHX_ " applying rule undef-Any\n"));
5461 if (SvNIOK(e) || (SvPOK(e) && looks_like_number(e) && SvNIOK(d))) {
5462 DEBUG_M(if (SvNIOK(e))
5463 Perl_deb(aTHX_ " applying rule Any-Num\n");
5465 Perl_deb(aTHX_ " applying rule Num-numish\n");
5467 /* numeric comparison */
5470 if (CopHINTS_get(PL_curcop) & HINT_INTEGER)
5471 (void) Perl_pp_i_eq(aTHX);
5473 (void) Perl_pp_eq(aTHX);
5481 /* As a last resort, use string comparison */
5482 DEBUG_M(Perl_deb(aTHX_ " applying rule Any-Any\n"));
5485 return Perl_pp_seq(aTHX);
5492 const U8 gimme = GIMME_V;
5494 /* This is essentially an optimization: if the match
5495 fails, we don't want to push a context and then
5496 pop it again right away, so we skip straight
5497 to the op that follows the leavewhen.
5498 RETURNOP calls PUTBACK which restores the stack pointer after the POPs.
5500 if (!(PL_op->op_flags & OPf_SPECIAL) && !SvTRUEx(POPs)) {
5501 if (gimme == G_SCALAR)
5502 PUSHs(&PL_sv_undef);
5503 RETURNOP(cLOGOP->op_other->op_next);
5506 cx = cx_pushblock(CXt_WHEN, gimme, SP, PL_savestack_ix);
5520 assert(CxTYPE(cx) == CXt_WHEN);
5521 gimme = cx->blk_gimme;
5523 cxix = dopoptogivenfor(cxstack_ix);
5525 /* diag_listed_as: Can't "when" outside a topicalizer */
5526 DIE(aTHX_ "Can't \"%s\" outside a topicalizer",
5527 PL_op->op_flags & OPf_SPECIAL ? "default" : "when");
5529 oldsp = PL_stack_base + cx->blk_oldsp;
5530 if (gimme == G_VOID)
5531 PL_stack_sp = oldsp;
5533 leave_adjust_stacks(oldsp, oldsp, gimme, 1);
5535 /* pop the WHEN, BLOCK and anything else before the GIVEN/FOR */
5536 assert(cxix < cxstack_ix);
5539 cx = &cxstack[cxix];
5541 if (CxFOREACH(cx)) {
5542 /* emulate pp_next. Note that any stack(s) cleanup will be
5543 * done by the pp_unstack which op_nextop should point to */
5546 PL_curcop = cx->blk_oldcop;
5547 return cx->blk_loop.my_op->op_nextop;
5551 assert(cx->blk_givwhen.leave_op->op_type == OP_LEAVEGIVEN);
5552 return cx->blk_givwhen.leave_op;
5562 cxix = dopoptowhen(cxstack_ix);
5564 DIE(aTHX_ "Can't \"continue\" outside a when block");
5566 if (cxix < cxstack_ix)
5570 assert(CxTYPE(cx) == CXt_WHEN);
5571 PL_stack_sp = PL_stack_base + cx->blk_oldsp;
5575 nextop = cx->blk_givwhen.leave_op->op_next;
5586 cxix = dopoptogivenfor(cxstack_ix);
5588 DIE(aTHX_ "Can't \"break\" outside a given block");
5590 cx = &cxstack[cxix];
5592 DIE(aTHX_ "Can't \"break\" in a loop topicalizer");
5594 if (cxix < cxstack_ix)
5597 /* Restore the sp at the time we entered the given block */
5599 PL_stack_sp = PL_stack_base + cx->blk_oldsp;
5601 return cx->blk_givwhen.leave_op;
5605 _invoke_defer_block(pTHX_ U8 type, void *_arg)
5607 OP *start = (OP *)_arg;
5609 I32 was_cxstack_ix = cxstack_ix;
5612 cx_pushblock(type, G_VOID, PL_stack_sp, PL_savestack_ix);
5628 assert(CxTYPE(cx) == CXt_DEFER);
5630 PL_stack_sp = PL_stack_base + cx->blk_oldsp;
5637 assert(cxstack_ix == was_cxstack_ix);
5641 invoke_defer_block(pTHX_ void *_arg)
5643 _invoke_defer_block(aTHX_ CXt_DEFER, _arg);
5647 invoke_finally_block(pTHX_ void *_arg)
5649 _invoke_defer_block(aTHX_ CXt_DEFER|CXp_FINALLY, _arg);
5654 if(PL_op->op_private & OPpDEFER_FINALLY)
5655 SAVEDESTRUCTOR_X(invoke_finally_block, cLOGOP->op_other);
5657 SAVEDESTRUCTOR_X(invoke_defer_block, cLOGOP->op_other);
5663 S_doparseform(pTHX_ SV *sv)
5666 char *s = SvPV(sv, len);
5668 char *base = NULL; /* start of current field */
5669 I32 skipspaces = 0; /* number of contiguous spaces seen */
5670 bool noblank = FALSE; /* ~ or ~~ seen on this line */
5671 bool repeat = FALSE; /* ~~ seen on this line */
5672 bool postspace = FALSE; /* a text field may need right padding */
5675 U32 *linepc = NULL; /* position of last FF_LINEMARK */
5677 bool ischop; /* it's a ^ rather than a @ */
5678 bool unchopnum = FALSE; /* at least one @ (i.e. non-chop) num field seen */
5679 int maxops = 12; /* FF_LINEMARK + FF_END + 10 (\0 without preceding \n) */
5683 PERL_ARGS_ASSERT_DOPARSEFORM;
5686 Perl_croak(aTHX_ "Null picture in formline");
5688 if (SvTYPE(sv) >= SVt_PVMG) {
5689 /* This might, of course, still return NULL. */
5690 mg = mg_find(sv, PERL_MAGIC_fm);
5692 sv_upgrade(sv, SVt_PVMG);
5696 /* still the same as previously-compiled string? */
5697 SV *old = mg->mg_obj;
5698 if ( ! (cBOOL(SvUTF8(old)) ^ cBOOL(SvUTF8(sv)))
5699 && len == SvCUR(old)
5700 && strnEQ(SvPVX(old), s, len)
5702 DEBUG_f(PerlIO_printf(Perl_debug_log,"Re-using compiled format\n"));
5706 DEBUG_f(PerlIO_printf(Perl_debug_log, "Re-compiling format\n"));
5707 Safefree(mg->mg_ptr);
5713 DEBUG_f(PerlIO_printf(Perl_debug_log, "Compiling format\n"));
5714 mg = sv_magicext(sv, NULL, PERL_MAGIC_fm, &PL_vtbl_fm, NULL, 0);
5717 sv_copy = newSVpvn_utf8(s, len, SvUTF8(sv));
5718 s = SvPV(sv_copy, len); /* work on the copy, not the original */
5722 /* estimate the buffer size needed */
5723 for (base = s; s <= send; s++) {
5724 if (*s == '\n' || *s == '@' || *s == '^')
5730 Newx(fops, maxops, U32);
5735 *fpc++ = FF_LINEMARK;
5736 noblank = repeat = FALSE;
5754 case ' ': case '\t':
5770 *fpc++ = FF_LITERAL;
5778 *fpc++ = (U32)skipspaces;
5782 *fpc++ = FF_NEWLINE;
5786 arg = fpc - linepc + 1;
5793 *fpc++ = FF_LINEMARK;
5794 noblank = repeat = FALSE;
5803 ischop = s[-1] == '^';
5809 arg = (s - base) - 1;
5811 *fpc++ = FF_LITERAL;
5817 if (*s == '*') { /* @* or ^* */
5819 *fpc++ = 2; /* skip the @* or ^* */
5821 *fpc++ = FF_LINESNGL;
5824 *fpc++ = FF_LINEGLOB;
5826 else if (*s == '#' || (*s == '.' && s[1] == '#')) { /* @###, ^### */
5827 arg = ischop ? FORM_NUM_BLANK : 0;
5832 const char * const f = ++s;
5835 arg |= FORM_NUM_POINT + (s - f);
5837 *fpc++ = s - base; /* fieldsize for FETCH */
5838 *fpc++ = FF_DECIMAL;
5840 unchopnum |= ! ischop;
5842 else if (*s == '0' && s[1] == '#') { /* Zero padded decimals */
5843 arg = ischop ? FORM_NUM_BLANK : 0;
5845 s++; /* skip the '0' first */
5849 const char * const f = ++s;
5852 arg |= FORM_NUM_POINT + (s - f);
5854 *fpc++ = s - base; /* fieldsize for FETCH */
5855 *fpc++ = FF_0DECIMAL;
5857 unchopnum |= ! ischop;
5859 else { /* text field */
5861 bool ismore = FALSE;
5864 while (*++s == '>') ;
5865 prespace = FF_SPACE;
5867 else if (*s == '|') {
5868 while (*++s == '|') ;
5869 prespace = FF_HALFSPACE;
5874 while (*++s == '<') ;
5877 if (*s == '.' && s[1] == '.' && s[2] == '.') {
5881 *fpc++ = s - base; /* fieldsize for FETCH */
5883 *fpc++ = ischop ? FF_CHECKCHOP : FF_CHECKNL;
5886 *fpc++ = (U32)prespace; /* add SPACE or HALFSPACE */
5900 assert (fpc <= fops + maxops); /* ensure our buffer estimate was valid */
5903 mg->mg_ptr = (char *) fops;
5904 mg->mg_len = arg * sizeof(U32);
5905 mg->mg_obj = sv_copy;
5906 mg->mg_flags |= MGf_REFCOUNTED;
5908 if (unchopnum && repeat)
5909 Perl_die(aTHX_ "Repeated format line will never terminate (~~ and @#)");
5916 S_num_overflow(NV value, I32 fldsize, I32 frcsize)
5918 /* Can value be printed in fldsize chars, using %*.*f ? */
5922 int intsize = fldsize - (value < 0 ? 1 : 0);
5924 if (frcsize & FORM_NUM_POINT)
5926 frcsize &= ~(FORM_NUM_POINT|FORM_NUM_BLANK);
5929 while (intsize--) pwr *= 10.0;
5930 while (frcsize--) eps /= 10.0;
5933 if (value + eps >= pwr)
5936 if (value - eps <= -pwr)
5943 S_run_user_filter(pTHX_ int idx, SV *buf_sv, int maxlen)
5945 SV * const datasv = FILTER_DATA(idx);
5946 const int filter_has_file = IoLINES(datasv);
5947 SV * const filter_state = MUTABLE_SV(IoTOP_GV(datasv));
5948 SV * const filter_sub = MUTABLE_SV(IoBOTTOM_GV(datasv));
5953 char *prune_from = NULL;
5954 bool read_from_cache = FALSE;
5958 PERL_ARGS_ASSERT_RUN_USER_FILTER;
5960 assert(maxlen >= 0);
5963 /* I was having segfault trouble under Linux 2.2.5 after a
5964 parse error occurred. (Had to hack around it with a test
5965 for PL_parser->error_count == 0.) Solaris doesn't segfault --
5966 not sure where the trouble is yet. XXX */
5969 SV *const cache = datasv;
5972 const char *cache_p = SvPV(cache, cache_len);
5976 /* Running in block mode and we have some cached data already.
5978 if (cache_len >= umaxlen) {
5979 /* In fact, so much data we don't even need to call
5984 const char *const first_nl =
5985 (const char *)memchr(cache_p, '\n', cache_len);
5987 take = first_nl + 1 - cache_p;
5991 sv_catpvn(buf_sv, cache_p, take);
5992 sv_chop(cache, cache_p + take);
5993 /* Definitely not EOF */
5997 sv_catsv(buf_sv, cache);
5999 umaxlen -= cache_len;
6002 read_from_cache = TRUE;
6006 /* Filter API says that the filter appends to the contents of the buffer.
6007 Usually the buffer is "", so the details don't matter. But if it's not,
6008 then clearly what it contains is already filtered by this filter, so we
6009 don't want to pass it in a second time.
6010 I'm going to use a mortal in case the upstream filter croaks. */
6011 upstream = ((SvOK(buf_sv) && sv_len(buf_sv)) || SvGMAGICAL(buf_sv))
6012 ? newSV_type_mortal(SVt_PV) : buf_sv;
6013 SvUPGRADE(upstream, SVt_PV);
6015 if (filter_has_file) {
6016 status = FILTER_READ(idx+1, upstream, 0);
6019 if (filter_sub && status >= 0) {
6023 ENTER_with_name("call_filter_sub");
6028 DEFSV_set(upstream);
6032 PUSHs(filter_state);
6035 count = call_sv(filter_sub, G_SCALAR|G_EVAL);
6045 SV * const errsv = ERRSV;
6046 if (SvTRUE_NN(errsv))
6047 err = newSVsv(errsv);
6053 LEAVE_with_name("call_filter_sub");
6056 if (SvGMAGICAL(upstream)) {
6058 if (upstream == buf_sv) mg_free(buf_sv);
6060 if (SvIsCOW(upstream)) sv_force_normal(upstream);
6061 if(!err && SvOK(upstream)) {
6062 got_p = SvPV_nomg(upstream, got_len);
6064 if (got_len > umaxlen) {
6065 prune_from = got_p + umaxlen;
6068 char *const first_nl = (char *)memchr(got_p, '\n', got_len);
6069 if (first_nl && first_nl + 1 < got_p + got_len) {
6070 /* There's a second line here... */
6071 prune_from = first_nl + 1;
6075 if (!err && prune_from) {
6076 /* Oh. Too long. Stuff some in our cache. */
6077 STRLEN cached_len = got_p + got_len - prune_from;
6078 SV *const cache = datasv;
6081 /* Cache should be empty. */
6082 assert(!SvCUR(cache));
6085 sv_setpvn(cache, prune_from, cached_len);
6086 /* If you ask for block mode, you may well split UTF-8 characters.
6087 "If it breaks, you get to keep both parts"
6088 (Your code is broken if you don't put them back together again
6089 before something notices.) */
6090 if (SvUTF8(upstream)) {
6093 if (SvPOK(upstream)) SvCUR_set(upstream, got_len - cached_len);
6095 /* Cannot just use sv_setpvn, as that could free the buffer
6096 before we have a chance to assign it. */
6097 sv_usepvn(upstream, savepvn(got_p, got_len - cached_len),
6098 got_len - cached_len);
6100 /* Can't yet be EOF */
6105 /* If they are at EOF but buf_sv has something in it, then they may never
6106 have touched the SV upstream, so it may be undefined. If we naively
6107 concatenate it then we get a warning about use of uninitialised value.
6109 if (!err && upstream != buf_sv &&
6111 sv_catsv_nomg(buf_sv, upstream);
6113 else if (SvOK(upstream)) (void)SvPV_force_nolen(buf_sv);
6116 IoLINES(datasv) = 0;
6118 SvREFCNT_dec(filter_state);
6119 IoTOP_GV(datasv) = NULL;
6122 SvREFCNT_dec(filter_sub);
6123 IoBOTTOM_GV(datasv) = NULL;
6125 filter_del(S_run_user_filter);
6131 if (status == 0 && read_from_cache) {
6132 /* If we read some data from the cache (and by getting here it implies
6133 that we emptied the cache) then we aren't yet at EOF, and mustn't
6134 report that to our caller. */
6141 * ex: set ts=8 sts=4 sw=4 et: