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