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