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