3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4 * 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * Then he heard Merry change the note, and up went the Horn-cry of Buckland,
15 * Awake! Awake! Fear, Fire, Foes! Awake!
18 * [p.1007 of _The Lord of the Rings_, VI/viii: "The Scouring of the Shire"]
21 /* This file contains 'hot' pp ("push/pop") functions that
22 * execute the opcodes that make up a perl program. A typical pp function
23 * expects to find its arguments on the stack, and usually pushes its
24 * results onto the stack, hence the 'pp' terminology. Each OP structure
25 * contains a pointer to the relevant pp_foo() function.
27 * By 'hot', we mean common ops whose execution speed is critical.
28 * By gathering them together into a single file, we encourage
29 * CPU cache hits on hot code. Also it could be taken as a warning not to
30 * change any code in this file unless you're sure it won't affect
35 #define PERL_IN_PP_HOT_C
49 PL_curcop = (COP*)PL_op;
50 TAINT_NOT; /* Each statement is presumed innocent */
51 PL_stack_sp = PL_stack_base + CX_CUR()->blk_oldsp;
61 if (UNLIKELY(PL_op->op_private & OPpLVAL_INTRO))
62 PUSHs(save_scalar(cGVOP_gv));
64 PUSHs(GvSVn(cGVOP_gv));
69 /* also used for: pp_lineseq() pp_regcmaybe() pp_scalar() pp_scope() */
76 /* This is sometimes called directly by pp_coreargs, pp_grepstart and
80 PUSHMARK(PL_stack_sp);
91 /* no PUTBACK, SETs doesn't inc/dec SP */
98 XPUSHs(MUTABLE_SV(cGVOP_gv));
103 /* also used for: pp_andassign() */
109 /* SP is not used to remove a variable that is saved across the
110 sv_2bool_flags call in SvTRUE_NN, if a RISC/CISC or low/high machine
111 register or load/store vs direct mem ops macro is introduced, this
112 should be a define block between direct PL_stack_sp and dSP operations,
113 presently, using PL_stack_sp is bias towards CISC cpus */
114 SV * const sv = *PL_stack_sp;
118 if (PL_op->op_type == OP_AND)
120 return cLOGOP->op_other;
128 /* sassign keeps its args in the optree traditionally backwards.
129 So we pop them differently.
131 SV *left = POPs; SV *right = TOPs;
133 if (PL_op->op_private & OPpASSIGN_BACKWARDS) { /* {or,and,dor}assign */
134 SV * const temp = left;
135 left = right; right = temp;
137 assert(TAINTING_get || !TAINT_get);
138 if (UNLIKELY(TAINT_get) && !SvTAINTED(right))
140 if (UNLIKELY(PL_op->op_private & OPpASSIGN_CV_TO_GV)) {
142 SV * const cv = SvRV(right);
143 const U32 cv_type = SvTYPE(cv);
144 const bool is_gv = isGV_with_GP(left);
145 const bool got_coderef = cv_type == SVt_PVCV || cv_type == SVt_PVFM;
151 /* Can do the optimisation if left (LVALUE) is not a typeglob,
152 right (RVALUE) is a reference to something, and we're in void
154 if (!got_coderef && !is_gv && GIMME_V == G_VOID) {
155 /* Is the target symbol table currently empty? */
156 GV * const gv = gv_fetchsv_nomg(left, GV_NOINIT, SVt_PVGV);
157 if (SvTYPE(gv) != SVt_PVGV && !SvOK(gv)) {
158 /* Good. Create a new proxy constant subroutine in the target.
159 The gv becomes a(nother) reference to the constant. */
160 SV *const value = SvRV(cv);
162 SvUPGRADE(MUTABLE_SV(gv), SVt_IV);
163 SvPCS_IMPORTED_on(gv);
165 SvREFCNT_inc_simple_void(value);
171 /* Need to fix things up. */
173 /* Need to fix GV. */
174 left = MUTABLE_SV(gv_fetchsv_nomg(left,GV_ADD, SVt_PVGV));
178 /* We've been returned a constant rather than a full subroutine,
179 but they expect a subroutine reference to apply. */
181 ENTER_with_name("sassign_coderef");
182 SvREFCNT_inc_void(SvRV(cv));
183 /* newCONSTSUB takes a reference count on the passed in SV
184 from us. We set the name to NULL, otherwise we get into
185 all sorts of fun as the reference to our new sub is
186 donated to the GV that we're about to assign to.
188 SvRV_set(right, MUTABLE_SV(newCONSTSUB(GvSTASH(left), NULL,
191 LEAVE_with_name("sassign_coderef");
193 /* What can happen for the corner case *{"BONK"} = \&{"BONK"};
195 First: ops for \&{"BONK"}; return us the constant in the
197 Second: ops for *{"BONK"} cause that symbol table entry
198 (and our reference to it) to be upgraded from RV
200 Thirdly: We get here. cv is actually PVGV now, and its
201 GvCV() is actually the subroutine we're looking for
203 So change the reference so that it points to the subroutine
204 of that typeglob, as that's what they were after all along.
206 GV *const upgraded = MUTABLE_GV(cv);
207 CV *const source = GvCV(upgraded);
210 assert(CvFLAGS(source) & CVf_CONST);
212 SvREFCNT_inc_simple_void_NN(source);
213 SvREFCNT_dec_NN(upgraded);
214 SvRV_set(right, MUTABLE_SV(source));
220 UNLIKELY(SvTEMP(left)) && !SvSMAGICAL(left) && SvREFCNT(left) == 1 &&
221 (!isGV_with_GP(left) || SvFAKE(left)) && ckWARN(WARN_MISC)
224 packWARN(WARN_MISC), "Useless assignment to a temporary"
226 SvSetMagicSV(left, right);
238 RETURNOP(SvTRUE_NN(sv) ? cLOGOP->op_other : cLOGOP->op_next);
245 TAINT_NOT; /* Each statement is presumed innocent */
247 PL_stack_sp = PL_stack_base + cx->blk_oldsp;
249 if (!(PL_op->op_flags & OPf_SPECIAL)) {
250 assert(CxTYPE(cx) == CXt_BLOCK || CxTYPE_is_LOOP(cx));
257 /* The main body of pp_concat, not including the magic/overload and
259 * It does targ = left . right.
260 * Moved into a separate function so that pp_multiconcat() can use it
264 PERL_STATIC_INLINE void
265 S_do_concat(pTHX_ SV *left, SV *right, SV *targ, U8 targmy)
269 const char *rpv = NULL;
271 bool rcopied = FALSE;
273 if (TARG == right && right != left) { /* $r = $l.$r */
274 rpv = SvPV_nomg_const(right, rlen);
275 rbyte = !DO_UTF8(right);
276 right = newSVpvn_flags(rpv, rlen, SVs_TEMP);
277 rpv = SvPV_const(right, rlen); /* no point setting UTF-8 here */
281 if (TARG != left) { /* not $l .= $r */
283 const char* const lpv = SvPV_nomg_const(left, llen);
284 lbyte = !DO_UTF8(left);
285 sv_setpvn(TARG, lpv, llen);
291 else { /* $l .= $r and left == TARG */
293 if ((left == right /* $l .= $l */
294 || targmy) /* $l = $l . $r */
295 && ckWARN(WARN_UNINITIALIZED)
301 SvPV_force_nomg_nolen(left);
303 lbyte = !DO_UTF8(left);
309 rpv = SvPV_nomg_const(right, rlen);
310 rbyte = !DO_UTF8(right);
312 if (lbyte != rbyte) {
314 sv_utf8_upgrade_nomg(TARG);
317 right = newSVpvn_flags(rpv, rlen, SVs_TEMP);
318 sv_utf8_upgrade_nomg(right);
319 rpv = SvPV_nomg_const(right, rlen);
322 sv_catpvn_nomg(TARG, rpv, rlen);
329 dSP; dATARGET; tryAMAGICbin_MG(concat_amg, AMGf_assign);
332 S_do_concat(aTHX_ left, right, targ, PL_op->op_private & OPpTARGET_MY);
341 Concatenate one or more args, possibly interleaved with constant string
342 segments. The result may be assigned to, or appended to, a variable or
345 Several op_flags and/or op_private bits indicate what the target is, and
346 whether it's appended to. Valid permutations are:
348 - (PADTMP) = (A.B.C....)
349 OPpTARGET_MY $lex = (A.B.C....)
350 OPpTARGET_MY,OPpLVAL_INTRO my $lex = (A.B.C....)
351 OPpTARGET_MY,OPpMULTICONCAT_APPEND $lex .= (A.B.C....)
352 OPf_STACKED expr = (A.B.C....)
353 OPf_STACKED,OPpMULTICONCAT_APPEND expr .= (A.B.C....)
355 Other combinations like (A.B).(C.D) are not optimised into a multiconcat
356 op, as it's too hard to get the correct ordering of ties, overload etc.
360 OPpMULTICONCAT_FAKE: not a real concat, instead an optimised
361 sprintf "...%s...". Don't call '.'
362 overloading: only use '""' overloading.
364 OPpMULTICONCAT_STRINGIFY: the RHS was of the form
365 "...$a...$b..." rather than
366 "..." . $a . "..." . $b . "..."
368 An OP_MULTICONCAT is of type UNOP_AUX. The fixed slots of the aux array are
369 defined with PERL_MULTICONCAT_IX_FOO constants, where:
372 FOO index description
373 -------- ----- ----------------------------------
374 NARGS 0 number of arguments
375 PLAIN_PV 1 non-utf8 constant string
376 PLAIN_LEN 2 non-utf8 constant string length
377 UTF8_PV 3 utf8 constant string
378 UTF8_LEN 4 utf8 constant string length
379 LENGTHS 5 first of nargs+1 const segment lengths
381 The idea is that a general string concatenation will have a fixed (known
382 at compile time) number of variable args, interspersed with constant
383 strings, e.g. "a=$a b=$b\n"
385 All the constant string segments "a=", " b=" and "\n" are stored as a
386 single string "a= b=\n", pointed to from the PLAIN_PV/UTF8_PV slot, along
387 with a series of segment lengths: e.g. 2,3,1. In the case where the
388 constant string is plain but has a different utf8 representation, both
389 variants are stored, and two sets of (nargs+1) segments lengths are stored
390 in the slots beginning at PERL_MULTICONCAT_IX_LENGTHS.
392 A segment length of -1 indicates that there is no constant string at that
393 point; this distinguishes between e.g. ($a . $b) and ($a . "" . $b), which
394 have differing overloading behaviour.
401 SV *targ; /* The SV to be assigned or appended to */
402 char *targ_pv; /* where within SvPVX(targ) we're writing to */
403 STRLEN targ_len; /* SvCUR(targ) */
404 SV **toparg; /* the highest arg position on the stack */
405 UNOP_AUX_item *aux; /* PL_op->op_aux buffer */
406 UNOP_AUX_item *const_lens; /* the segment length array part of aux */
407 const char *const_pv; /* the current segment of the const string buf */
408 SSize_t nargs; /* how many args were expected */
409 SSize_t stack_adj; /* how much to adjust SP on return */
410 STRLEN grow; /* final size of destination string (targ) */
411 UV targ_count; /* how many times targ has appeared on the RHS */
412 bool is_append; /* OPpMULTICONCAT_APPEND flag is set */
413 bool slow_concat; /* args too complex for quick concat */
414 U32 dst_utf8; /* the result will be utf8 (indicate this with
415 SVf_UTF8 in a U32, rather than using bool,
416 for ease of testing and setting) */
417 /* for each arg, holds the result of an SvPV() call */
418 struct multiconcat_svpv {
422 *targ_chain, /* chain of slots where targ has appeared on RHS */
423 *svpv_p, /* ptr for looping through svpv_buf */
424 *svpv_base, /* first slot (may be greater than svpv_buf), */
425 *svpv_end, /* and slot after highest result so far, of: */
426 svpv_buf[PERL_MULTICONCAT_MAXARG]; /* buf for storing SvPV() results */
428 aux = cUNOP_AUXx(PL_op)->op_aux;
429 stack_adj = nargs = aux[PERL_MULTICONCAT_IX_NARGS].ssize;
430 is_append = cBOOL(PL_op->op_private & OPpMULTICONCAT_APPEND);
432 /* get targ from the stack or pad */
434 if (PL_op->op_flags & OPf_STACKED) {
436 /* for 'expr .= ...', expr is the bottom item on the stack */
441 /* for 'expr = ...', expr is the top item on the stack */
445 SV **svp = &(PAD_SVl(PL_op->op_targ));
447 if (PL_op->op_private & OPpLVAL_INTRO) {
448 assert(PL_op->op_private & OPpTARGET_MY);
452 /* $lex .= "const" doesn't cause anything to be pushed */
458 grow = 1; /* allow for '\0' at minimum */
463 /* only utf8 variants of the const strings? */
464 dst_utf8 = aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv ? 0 : SVf_UTF8;
467 /* --------------------------------------------------------------
470 * stringify (i.e. SvPV()) every arg and store the resultant pv/len/utf8
471 * triplets in svpv_buf[]. Also increment 'grow' by the args' lengths.
473 * utf8 is indicated by storing a negative length.
475 * Where an arg is actually targ, the stringification is deferred:
476 * the length is set to 0, and the slot is added to targ_chain.
478 * If a magic, overloaded, or otherwise weird arg is found, which
479 * might have side effects when stringified, the loop is abandoned and
480 * we goto a code block where a more basic 'emulate calling
481 * pp_cpncat() on each arg in turn' is done.
484 for (; SP <= toparg; SP++, svpv_end++) {
489 assert(svpv_end - svpv_buf < PERL_MULTICONCAT_MAXARG);
493 /* this if/else chain is arranged so that common/simple cases
494 * take few conditionals */
496 if (LIKELY((SvFLAGS(sv) & (SVs_GMG|SVf_ROK|SVf_POK)) == SVf_POK)) {
497 /* common case: sv is a simple non-magical PV */
499 /* targ appears on RHS.
500 * Delay storing PV pointer; instead, add slot to targ_chain
501 * so it can be populated later, after targ has been grown and
502 * we know its final SvPVX() address.
505 svpv_end->len = 0; /* zerojng here means we can skip
506 updating later if targ_len == 0 */
507 svpv_end->pv = (char*)targ_chain;
508 targ_chain = svpv_end;
514 svpv_end->pv = SvPVX(sv);
516 else if (UNLIKELY(SvFLAGS(sv) & (SVs_GMG|SVf_ROK)))
517 /* may have side effects: tie, overload etc.
518 * Abandon 'stringify everything first' and handle
519 * args in strict order. Note that already-stringified args
520 * will be reprocessed, which is safe because the each first
521 * stringification would have been idempotent.
524 else if (SvNIOK(sv)) {
527 /* stringify general valid scalar */
528 svpv_end->pv = sv_2pv_flags(sv, &len, 0);
530 else if (!SvOK(sv)) {
531 if (ckWARN(WARN_UNINITIALIZED))
532 /* an undef value in the presence of warnings may trigger
535 svpv_end->pv = (char*)"";
539 goto do_magical; /* something weird */
541 utf8 = (SvFLAGS(sv) & SVf_UTF8);
543 ASSUME(len < SSize_t_MAX);
544 svpv_end->len = utf8 ? -(SSize_t)len : (SSize_t)len;
548 /* --------------------------------------------------------------
553 * if targ appears on the RHS or is appended to, force stringify it;
554 * otherwise set it to "". Then set targ_len.
558 /* abandon quick route if using targ might have side effects */
559 if (UNLIKELY(SvFLAGS(targ) & (SVs_GMG|SVf_ROK)))
565 SvPV_force_nomg_nolen(targ);
566 targ_utf8 = SvFLAGS(targ) & SVf_UTF8;
567 if (UNLIKELY(dst_utf8 & ~targ_utf8)) {
568 if (LIKELY(!IN_BYTES))
569 sv_utf8_upgrade_nomg(targ);
572 dst_utf8 |= targ_utf8;
574 targ_len = SvCUR(targ);
575 grow += targ_len * (targ_count + is_append);
578 else if (ckWARN(WARN_UNINITIALIZED))
579 /* warning might have side effects */
581 /* the undef targ will be silently SvPVCLEAR()ed below */
583 else if (UNLIKELY(SvTYPE(targ) >= SVt_REGEXP)) {
584 /* Assigning to some weird LHS type. Don't force the LHS to be an
585 * empty string; instead, do things 'long hand' by using the
586 * overload code path, which concats to a TEMP sv and does
587 * sv_catsv() calls rather than COPY()s. This ensures that even
588 * bizarre code like this doesn't break or crash:
590 * (which makes the 'F' typeglob an alias to the
591 * '*main::F*main::F' typeglob).
596 /* targ was found on RHS.
597 * Force stringify it, using the same code as the append branch
598 * above, except that we don't need the magic/overload/undef
599 * checks as these will already have been done in the phase 1
604 /* unrolled SvPVCLEAR() - mostly: no need to grow or set SvCUR() to 0;
605 * those will be done later. */
606 SV_CHECK_THINKFIRST_COW_DROP(targ);
607 SvUPGRADE(targ, SVt_PV);
608 SvFLAGS(targ) &= ~(SVf_OK|SVf_IVisUV|SVf_UTF8);
609 SvFLAGS(targ) |= (SVf_POK|SVp_POK|dst_utf8);
613 /* --------------------------------------------------------------
616 * UTF-8 tweaks and grow targ:
618 * Now that we know the length and utf8-ness of both the targ and
619 * args, grow targ to the size needed to accumulate all the args, based
620 * on whether targ appears on the RHS, whether we're appending, and
621 * whether any non-utf8 args expand in size if converted to utf8.
623 * For the latter, if dst_utf8 we scan non-utf8 args looking for
624 * variant chars, and adjust the svpv->len value of those args to the
625 * utf8 size and negate it to flag them. At the same time we un-negate
626 * the lens of any utf8 args since after this phase we no longer care
627 * whether an arg is utf8 or not.
629 * Finally, initialise const_lens and const_pv based on utf8ness.
630 * Note that there are 3 permutations:
632 * * If the constant string is invariant whether utf8 or not (e.g. "abc"),
633 * then aux[PERL_MULTICONCAT_IX_PLAIN_PV/LEN] are the same as
634 * aux[PERL_MULTICONCAT_IX_UTF8_PV/LEN] and there is one set of
637 * * If the string is fully utf8, e.g. "\x{100}", then
638 * aux[PERL_MULTICONCAT_IX_PLAIN_PV/LEN] == (NULL,0) and there is
639 * one set of segment lengths.
641 * * If the string has different plain and utf8 representations
642 * (e.g. "\x80"), then then aux[PERL_MULTICONCAT_IX_PLAIN_PV/LEN]]
643 * holds the plain rep, while aux[PERL_MULTICONCAT_IX_UTF8_PV/LEN]
644 * holds the utf8 rep, and there are 2 sets of segment lengths,
645 * with the utf8 set following after the plain set.
647 * On entry to this section the (pv,len) pairs in svpv_buf have the
648 * following meanings:
649 * (pv, len) a plain string
650 * (pv, -len) a utf8 string
651 * (NULL, 0) left-most targ \ linked together R-to-L
652 * (next, 0) other targ / in targ_chain
655 /* turn off utf8 handling if 'use bytes' is in scope */
656 if (UNLIKELY(dst_utf8 && IN_BYTES)) {
659 /* undo all the negative lengths which flag utf8-ness */
660 for (svpv_p = svpv_buf; svpv_p < svpv_end; svpv_p++) {
661 SSize_t len = svpv_p->len;
667 /* grow += total of lengths of constant string segments */
670 len = aux[dst_utf8 ? PERL_MULTICONCAT_IX_UTF8_LEN
671 : PERL_MULTICONCAT_IX_PLAIN_LEN].ssize;
672 slow_concat = cBOOL(len);
676 const_lens = aux + PERL_MULTICONCAT_IX_LENGTHS;
679 const_pv = aux[PERL_MULTICONCAT_IX_UTF8_PV].pv;
680 if ( aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv
681 && const_pv != aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv)
682 /* separate sets of lengths for plain and utf8 */
683 const_lens += nargs + 1;
685 /* If the result is utf8 but some of the args aren't,
686 * calculate how much extra growth is needed for all the chars
687 * which will expand to two utf8 bytes.
688 * Also, if the growth is non-zero, negate the length to indicate
689 * that this this is a variant string. Conversely, un-negate the
690 * length on utf8 args (which was only needed to flag non-utf8
691 * args in this loop */
692 for (svpv_p = svpv_buf; svpv_p < svpv_end; svpv_p++) {
701 extra = variant_under_utf8_count((U8 *) svpv_p->pv,
702 (U8 *) svpv_p->pv + len);
703 if (UNLIKELY(extra)) {
705 /* -ve len indicates special handling */
706 svpv_p->len = -(len + extra);
712 const_pv = aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv;
714 /* unrolled SvGROW(), except don't check for SVf_IsCOW, which should
715 * already have been dropped */
716 assert(!SvIsCOW(targ));
717 targ_pv = (SvLEN(targ) < (grow) ? sv_grow(targ,grow) : SvPVX(targ));
720 /* --------------------------------------------------------------
723 * Now that targ has been grown, we know the final address of the targ
724 * PVX, if needed. Preserve / move targ contents if appending or if
725 * targ appears on RHS.
727 * Also update svpv_buf slots in targ_chain.
729 * Don't bother with any of this if the target length is zero:
730 * targ_len is set to zero unless we're appending or targ appears on
731 * RHS. And even if it is, we can optimise by skipping this chunk of
732 * code for zero targ_len. In the latter case, we don't need to update
733 * the slots in targ_chain with the (zero length) target string, since
734 * we set the len in such slots to 0 earlier, and since the Copy() is
735 * skipped on zero length, it doesn't matter what svpv_p->pv contains.
737 * On entry to this section the (pv,len) pairs in svpv_buf have the
738 * following meanings:
739 * (pv, len) a pure-plain or utf8 string
740 * (pv, -(len+extra)) a plain string which will expand by 'extra'
741 * bytes when converted to utf8
742 * (NULL, 0) left-most targ \ linked together R-to-L
743 * (next, 0) other targ / in targ_chain
745 * On exit, the targ contents will have been moved to the
746 * earliest place they are needed (e.g. $x = "abc$x" will shift them
747 * 3 bytes, while $x .= ... will leave them at the beginning);
748 * and dst_pv will point to the location within SvPVX(targ) where the
749 * next arg should be copied.
752 svpv_base = svpv_buf;
755 struct multiconcat_svpv *tc_stop;
756 char *targ_buf = targ_pv; /* ptr to original targ string */
758 assert(is_append || targ_count);
765 /* The targ appears on RHS, e.g. '$t = $a . $t . $t'.
766 * Move the current contents of targ to the first
767 * position where it's needed, and use that as the src buffer
768 * for any further uses (such as the second RHS $t above).
769 * In calculating the first position, we need to sum the
770 * lengths of all consts and args before that.
773 UNOP_AUX_item *lens = const_lens;
774 /* length of first const string segment */
775 STRLEN offset = lens->ssize > 0 ? lens->ssize : 0;
783 break; /* the first targ argument */
784 /* add lengths of the next arg and const string segment */
786 if (len < 0) /* variant args have this */
788 offset += (STRLEN)len;
789 len = (++lens)->ssize;
790 offset += (len >= 0) ? (STRLEN)len : 0;
792 /* all args and consts so far are empty; update
793 * the start position for the concat later */
798 assert(svpv_p < svpv_end);
803 Move(targ_pv, targ_buf, targ_len, char);
804 /* a negative length implies don't Copy(), but do increment */
805 svpv_p->len = -((SSize_t)targ_len);
809 /* skip the first targ copy */
815 /* Don't populate the first targ slot in the loop below; it's
816 * either not used because we advanced svpv_base beyond it, or
817 * we already stored the special -targ_len value in it
822 /* populate slots in svpv_buf representing targ on RHS */
823 while (targ_chain != tc_stop) {
824 struct multiconcat_svpv *p = targ_chain;
825 targ_chain = (struct multiconcat_svpv *)(p->pv);
827 p->len = (SSize_t)targ_len;
832 /* --------------------------------------------------------------
835 * Append all the args in svpv_buf, plus the const strings, to targ.
837 * On entry to this section the (pv,len) pairs in svpv_buf have the
838 * following meanings:
839 * (pv, len) a pure-plain or utf8 string (which may be targ)
840 * (pv, -(len+extra)) a plain string which will expand by 'extra'
841 * bytes when converted to utf8
842 * (0, -len) left-most targ, whose content has already
843 * been copied. Just advance targ_pv by len.
846 /* If there are no constant strings and no special case args
847 * (svpv_p->len < 0), use a simpler, more efficient concat loop
850 for (svpv_p = svpv_base; svpv_p < svpv_end; svpv_p++) {
851 SSize_t len = svpv_p->len;
854 Copy(svpv_p->pv, targ_pv, len, char);
857 const_lens += (svpv_end - svpv_base + 1);
860 /* Note that we iterate the loop nargs+1 times: to append nargs
861 * arguments and nargs+1 constant strings. For example, "-$a-$b-"
863 svpv_p = svpv_base - 1;
866 SSize_t len = (const_lens++)->ssize;
868 /* append next const string segment */
870 Copy(const_pv, targ_pv, len, char);
875 if (++svpv_p == svpv_end)
878 /* append next arg */
881 if (LIKELY(len > 0)) {
882 Copy(svpv_p->pv, targ_pv, len, char);
885 else if (UNLIKELY(len < 0)) {
886 /* negative length indicates two special cases */
887 const char *p = svpv_p->pv;
890 /* copy plain-but-variant pv to a utf8 targ */
891 char * end_pv = targ_pv + len;
893 while (targ_pv < end_pv) {
895 append_utf8_from_native_byte(c, (U8**)&targ_pv);
899 /* arg is already-copied targ */
907 SvCUR_set(targ, targ_pv - SvPVX(targ));
908 assert(grow >= SvCUR(targ) + 1);
909 assert(SvLEN(targ) >= SvCUR(targ) + 1);
911 /* --------------------------------------------------------------
922 /* --------------------------------------------------------------
925 * We only get here if any of the args (or targ too in the case of
926 * append) have something which might cause side effects, such
927 * as magic, overload, or an undef value in the presence of warnings.
928 * In that case, any earlier attempt to stringify the args will have
929 * been abandoned, and we come here instead.
931 * Here, we concat each arg in turn the old-fashioned way: essentially
932 * emulating pp_concat() in a loop. This means that all the weird edge
933 * cases will be handled correctly, if not necessarily speedily.
935 * Note that some args may already have been stringified - those are
936 * processed again, which is safe, since only args without side-effects
937 * were stringified earlier.
949 const char *cpv = aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv;
950 UNOP_AUX_item *lens = aux + PERL_MULTICONCAT_IX_LENGTHS;
951 Size_t arg_count = 0; /* how many args have been processed */
954 cpv = aux[PERL_MULTICONCAT_IX_UTF8_PV].pv;
958 svp = toparg - nargs + 1;
962 * plus possible nargs+1 consts,
963 * plus, if appending, a final targ in an extra last iteration
967 for (i = 0; i <= n; i++) {
970 /* if necessary, stringify the final RHS result in
971 * something like $targ .= "$a$b$c" - simulating
975 && (PL_op->op_private &OPpMULTICONCAT_STRINGIFY)
977 /* extra conditions for backwards compatibility:
978 * probably incorrect, but keep the existing behaviour
979 * for now. The rules are:
980 * $x = "$ov" single arg: stringify;
981 * $x = "$ov$y" multiple args: don't stringify,
982 * $lex = "$ov$y$z" except TARGMY with at least 2 concats
987 && (PL_op->op_private & OPpTARGET_MY)
988 && !(PL_op->op_private & OPpLVAL_INTRO)
993 SV *tmp = sv_newmortal();
994 sv_copypv(tmp, left);
999 /* do one extra iteration to handle $targ in $targ .= ... */
1000 if (i == n && !is_append)
1003 /* get the next arg SV or regen the next const SV */
1004 len = lens[i >> 1].ssize;
1006 /* handle the final targ .= (....) */
1011 right = svp[(i >> 1)];
1013 continue; /* no const in this position */
1015 right = newSVpvn_flags(cpv, len, (utf8 | SVs_TEMP));
1021 if (arg_count <= 1) {
1023 continue; /* need at least two SVs to concat together */
1026 if (arg_count == 2 && i < n) {
1027 /* for the first concat, create a mortal acting like the
1028 * padtmp from OP_CONST. In later iterations this will
1030 nexttarg = sv_newmortal();
1038 /* Handle possible overloading.
1039 * This is basically an unrolled
1040 * tryAMAGICbin_MG(concat_amg, AMGf_assign);
1042 * Perl_try_amagic_bin()
1043 * call, but using left and right rather than SP[-1], SP[0],
1044 * and not relying on OPf_STACKED implying .=
1047 if ((SvFLAGS(left)|SvFLAGS(right)) & (SVf_ROK|SVs_GMG)) {
1052 if ((SvAMAGIC(left) || SvAMAGIC(right))
1053 /* sprintf doesn't do concat overloading,
1054 * but allow for $x .= sprintf(...)
1056 && ( !(PL_op->op_private & OPpMULTICONCAT_FAKE)
1060 SV * const tmpsv = amagic_call(left, right, concat_amg,
1061 (nextappend ? AMGf_assign: 0));
1063 /* NB: tryAMAGICbin_MG() includes an OPpTARGET_MY test
1064 * here, which isn't needed as any implicit
1065 * assign done under OPpTARGET_MY is done after
1068 sv_setsv(left, tmpsv);
1077 /* if both args are the same magical value, make one a copy */
1078 if (left == right && SvGMAGICAL(left)) {
1079 left = sv_newmortal();
1080 /* Print the uninitialized warning now, so it includes the
1083 if (ckWARN(WARN_UNINITIALIZED))
1084 report_uninit(right);
1085 sv_setsv_flags(left, &PL_sv_no, 0);
1088 sv_setsv_flags(left, right, 0);
1093 /* nexttarg = left . right */
1094 S_do_concat(aTHX_ left, right, nexttarg, 0);
1098 SP = toparg - stack_adj + 1;
1100 /* Return the result of all RHS concats, unless this op includes
1101 * an assign ($lex = x.y.z or expr = x.y.z), in which case copy
1102 * to target (which will be $lex or expr).
1103 * If we are appending, targ will already have been appended to in
1106 && ( (PL_op->op_flags & OPf_STACKED)
1107 || (PL_op->op_private & OPpTARGET_MY))
1109 sv_setsv(targ, left);
1120 /* push the elements of av onto the stack.
1121 * Returns PL_op->op_next to allow tail-call optimisation of its callers */
1124 S_pushav(pTHX_ AV* const av)
1127 const SSize_t maxarg = AvFILL(av) + 1;
1129 if (UNLIKELY(SvRMAGICAL(av))) {
1131 for (i=0; i < (PADOFFSET)maxarg; i++) {
1132 SV ** const svp = av_fetch(av, i, FALSE);
1133 SP[i+1] = LIKELY(svp)
1135 : UNLIKELY(PL_op->op_flags & OPf_MOD)
1142 for (i=0; i < (PADOFFSET)maxarg; i++) {
1143 SV *sv = AvARRAY(av)[i];
1144 SP[i+1] = LIKELY(sv)
1146 : UNLIKELY(PL_op->op_flags & OPf_MOD)
1157 /* ($lex1,@lex2,...) or my ($lex1,@lex2,...) */
1162 PADOFFSET base = PL_op->op_targ;
1163 int count = (int)(PL_op->op_private) & OPpPADRANGE_COUNTMASK;
1164 if (PL_op->op_flags & OPf_SPECIAL) {
1165 /* fake the RHS of my ($x,$y,..) = @_ */
1167 (void)S_pushav(aTHX_ GvAVn(PL_defgv));
1171 /* note, this is only skipped for compile-time-known void cxt */
1172 if ((PL_op->op_flags & OPf_WANT) != OPf_WANT_VOID) {
1177 for (i = 0; i <count; i++)
1178 *++SP = PAD_SV(base+i);
1180 if (PL_op->op_private & OPpLVAL_INTRO) {
1181 SV **svp = &(PAD_SVl(base));
1182 const UV payload = (UV)(
1183 (base << (OPpPADRANGE_COUNTSHIFT + SAVE_TIGHT_SHIFT))
1184 | (count << SAVE_TIGHT_SHIFT)
1185 | SAVEt_CLEARPADRANGE);
1188 STATIC_ASSERT_STMT(OPpPADRANGE_COUNTMASK + 1 == (1 << OPpPADRANGE_COUNTSHIFT));
1189 assert((payload >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
1197 for (i = 0; i <count; i++)
1198 SvPADSTALE_off(*svp++); /* mark lexical as active */
1209 OP * const op = PL_op;
1210 /* access PL_curpad once */
1211 SV ** const padentry = &(PAD_SVl(op->op_targ));
1216 PUTBACK; /* no pop/push after this, TOPs ok */
1218 if (op->op_flags & OPf_MOD) {
1219 if (op->op_private & OPpLVAL_INTRO)
1220 if (!(op->op_private & OPpPAD_STATE))
1221 save_clearsv(padentry);
1222 if (op->op_private & OPpDEREF) {
1223 /* TOPs is equivalent to TARG here. Using TOPs (SP) rather
1224 than TARG reduces the scope of TARG, so it does not
1225 span the call to save_clearsv, resulting in smaller
1227 TOPs = vivify_ref(TOPs, op->op_private & OPpDEREF);
1237 /* pp_coreargs pushes a NULL to indicate no args passed to
1238 * CORE::readline() */
1241 tryAMAGICunTARGETlist(iter_amg, 0);
1242 PL_last_in_gv = MUTABLE_GV(*PL_stack_sp--);
1244 else PL_last_in_gv = PL_argvgv, PL_stack_sp--;
1245 if (!isGV_with_GP(PL_last_in_gv)) {
1246 if (SvROK(PL_last_in_gv) && isGV_with_GP(SvRV(PL_last_in_gv)))
1247 PL_last_in_gv = MUTABLE_GV(SvRV(PL_last_in_gv));
1250 XPUSHs(MUTABLE_SV(PL_last_in_gv));
1252 Perl_pp_rv2gv(aTHX);
1253 PL_last_in_gv = MUTABLE_GV(*PL_stack_sp--);
1254 assert((SV*)PL_last_in_gv == &PL_sv_undef || isGV_with_GP(PL_last_in_gv));
1257 return do_readline();
1265 tryAMAGICbin_MG(eq_amg, AMGf_numeric);
1269 (SvIOK_notUV(left) && SvIOK_notUV(right))
1270 ? (SvIVX(left) == SvIVX(right))
1271 : ( do_ncmp(left, right) == 0)
1277 /* also used for: pp_i_preinc() */
1281 SV *sv = *PL_stack_sp;
1283 if (LIKELY(((sv->sv_flags &
1284 (SVf_THINKFIRST|SVs_GMG|SVf_IVisUV|
1285 SVf_IOK|SVf_NOK|SVf_POK|SVp_NOK|SVp_POK|SVf_ROK))
1287 && SvIVX(sv) != IV_MAX)
1289 SvIV_set(sv, SvIVX(sv) + 1);
1291 else /* Do all the PERL_PRESERVE_IVUV and hard cases in sv_inc */
1298 /* also used for: pp_i_predec() */
1302 SV *sv = *PL_stack_sp;
1304 if (LIKELY(((sv->sv_flags &
1305 (SVf_THINKFIRST|SVs_GMG|SVf_IVisUV|
1306 SVf_IOK|SVf_NOK|SVf_POK|SVp_NOK|SVp_POK|SVf_ROK))
1308 && SvIVX(sv) != IV_MIN)
1310 SvIV_set(sv, SvIVX(sv) - 1);
1312 else /* Do all the PERL_PRESERVE_IVUV and hard cases in sv_dec */
1319 /* also used for: pp_orassign() */
1330 if (PL_op->op_type == OP_OR)
1332 RETURNOP(cLOGOP->op_other);
1337 /* also used for: pp_dor() pp_dorassign() */
1344 const int op_type = PL_op->op_type;
1345 const bool is_dor = (op_type == OP_DOR || op_type == OP_DORASSIGN);
1350 if (UNLIKELY(!sv || !SvANY(sv))) {
1351 if (op_type == OP_DOR)
1353 RETURNOP(cLOGOP->op_other);
1359 if (UNLIKELY(!sv || !SvANY(sv)))
1364 switch (SvTYPE(sv)) {
1366 if (AvMAX(sv) >= 0 || SvGMAGICAL(sv) || (SvRMAGICAL(sv) && mg_find(sv, PERL_MAGIC_tied)))
1370 if (HvARRAY(sv) || SvGMAGICAL(sv) || (SvRMAGICAL(sv) && mg_find(sv, PERL_MAGIC_tied)))
1374 if (CvROOT(sv) || CvXSUB(sv))
1387 if(op_type == OP_DOR)
1389 RETURNOP(cLOGOP->op_other);
1391 /* assuming OP_DEFINED */
1401 dSP; dATARGET; bool useleft; SV *svl, *svr;
1403 tryAMAGICbin_MG(add_amg, AMGf_assign|AMGf_numeric);
1407 #ifdef PERL_PRESERVE_IVUV
1409 /* special-case some simple common cases */
1410 if (!((svl->sv_flags|svr->sv_flags) & (SVf_IVisUV|SVs_GMG))) {
1412 U32 flags = (svl->sv_flags & svr->sv_flags);
1413 if (flags & SVf_IOK) {
1414 /* both args are simple IVs */
1419 topl = ((UV)il) >> (UVSIZE * 8 - 2);
1420 topr = ((UV)ir) >> (UVSIZE * 8 - 2);
1422 /* if both are in a range that can't under/overflow, do a
1423 * simple integer add: if the top of both numbers
1424 * are 00 or 11, then it's safe */
1425 if (!( ((topl+1) | (topr+1)) & 2)) {
1427 TARGi(il + ir, 0); /* args not GMG, so can't be tainted */
1433 else if (flags & SVf_NOK) {
1434 /* both args are NVs */
1438 if (lossless_NV_to_IV(nl, &il) && lossless_NV_to_IV(nr, &ir)) {
1439 /* nothing was lost by converting to IVs */
1443 TARGn(nl + nr, 0); /* args not GMG, so can't be tainted */
1451 useleft = USE_LEFT(svl);
1452 /* We must see if we can perform the addition with integers if possible,
1453 as the integer code detects overflow while the NV code doesn't.
1454 If either argument hasn't had a numeric conversion yet attempt to get
1455 the IV. It's important to do this now, rather than just assuming that
1456 it's not IOK as a PV of "9223372036854775806" may not take well to NV
1457 addition, and an SV which is NOK, NV=6.0 ought to be coerced to
1458 integer in case the second argument is IV=9223372036854775806
1459 We can (now) rely on sv_2iv to do the right thing, only setting the
1460 public IOK flag if the value in the NV (or PV) slot is truly integer.
1462 A side effect is that this also aggressively prefers integer maths over
1463 fp maths for integer values.
1465 How to detect overflow?
1467 C 99 section 6.2.6.1 says
1469 The range of nonnegative values of a signed integer type is a subrange
1470 of the corresponding unsigned integer type, and the representation of
1471 the same value in each type is the same. A computation involving
1472 unsigned operands can never overflow, because a result that cannot be
1473 represented by the resulting unsigned integer type is reduced modulo
1474 the number that is one greater than the largest value that can be
1475 represented by the resulting type.
1479 which I read as "unsigned ints wrap."
1481 signed integer overflow seems to be classed as "exception condition"
1483 If an exceptional condition occurs during the evaluation of an
1484 expression (that is, if the result is not mathematically defined or not
1485 in the range of representable values for its type), the behavior is
1488 (6.5, the 5th paragraph)
1490 I had assumed that on 2s complement machines signed arithmetic would
1491 wrap, hence coded pp_add and pp_subtract on the assumption that
1492 everything perl builds on would be happy. After much wailing and
1493 gnashing of teeth it would seem that irix64 knows its ANSI spec well,
1494 knows that it doesn't need to, and doesn't. Bah. Anyway, the all-
1495 unsigned code below is actually shorter than the old code. :-)
1498 if (SvIV_please_nomg(svr)) {
1499 /* Unless the left argument is integer in range we are going to have to
1500 use NV maths. Hence only attempt to coerce the right argument if
1501 we know the left is integer. */
1508 a_valid = auvok = 1;
1509 /* left operand is undef, treat as zero. + 0 is identity,
1510 Could SETi or SETu right now, but space optimise by not adding
1511 lots of code to speed up what is probably a rarish case. */
1513 /* Left operand is defined, so is it IV? */
1514 if (SvIV_please_nomg(svl)) {
1515 if ((auvok = SvUOK(svl)))
1518 const IV aiv = SvIVX(svl);
1521 auvok = 1; /* Now acting as a sign flag. */
1523 /* Using 0- here and later to silence bogus warning
1525 auv = (UV) (0 - (UV) aiv);
1532 bool result_good = 0;
1535 bool buvok = SvUOK(svr);
1540 const IV biv = SvIVX(svr);
1545 buv = (UV) (0 - (UV) biv);
1547 /* ?uvok if value is >= 0. basically, flagged as UV if it's +ve,
1548 else "IV" now, independent of how it came in.
1549 if a, b represents positive, A, B negative, a maps to -A etc
1554 all UV maths. negate result if A negative.
1555 add if signs same, subtract if signs differ. */
1557 if (auvok ^ buvok) {
1561 /* Must get smaller */
1566 if (result <= buv) {
1567 /* result really should be -(auv-buv). as its negation
1568 of true value, need to swap our result flag */
1585 if (result <= (UV)IV_MIN)
1586 SETi(result == (UV)IV_MIN
1587 ? IV_MIN : -(IV)result);
1589 /* result valid, but out of range for IV. */
1590 SETn( -(NV)result );
1594 } /* Overflow, drop through to NVs. */
1599 useleft = USE_LEFT(svl);
1603 NV value = SvNV_nomg(svr);
1606 /* left operand is undef, treat as zero. + 0.0 is identity. */
1610 SETn( value + SvNV_nomg(svl) );
1616 /* also used for: pp_aelemfast_lex() */
1621 AV * const av = PL_op->op_type == OP_AELEMFAST_LEX
1622 ? MUTABLE_AV(PAD_SV(PL_op->op_targ)) : GvAVn(cGVOP_gv);
1623 const U32 lval = PL_op->op_flags & OPf_MOD;
1624 const I8 key = (I8)PL_op->op_private;
1628 assert(SvTYPE(av) == SVt_PVAV);
1632 /* inlined av_fetch() for simple cases ... */
1633 if (!SvRMAGICAL(av) && key >= 0 && key <= AvFILLp(av)) {
1634 sv = AvARRAY(av)[key];
1641 /* ... else do it the hard way */
1642 svp = av_fetch(av, key, lval);
1643 sv = (svp ? *svp : &PL_sv_undef);
1645 if (UNLIKELY(!svp && lval))
1646 DIE(aTHX_ PL_no_aelem, (int)key);
1648 if (!lval && SvRMAGICAL(av) && SvGMAGICAL(sv)) /* see note in pp_helem() */
1656 dSP; dMARK; dTARGET;
1658 do_join(TARG, *MARK, MARK, SP);
1664 /* Oversized hot code. */
1666 /* also used for: pp_say() */
1670 dSP; dMARK; dORIGMARK;
1674 = (PL_op->op_flags & OPf_STACKED) ? MUTABLE_GV(*++MARK) : PL_defoutgv;
1678 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1681 if (MARK == ORIGMARK) {
1682 /* If using default handle then we need to make space to
1683 * pass object as 1st arg, so move other args up ...
1687 Move(MARK, MARK + 1, (SP - MARK) + 1, SV*);
1690 return Perl_tied_method(aTHX_ SV_CONST(PRINT), mark - 1, MUTABLE_SV(io),
1692 (G_SCALAR | TIED_METHOD_ARGUMENTS_ON_STACK
1693 | (PL_op->op_type == OP_SAY
1694 ? TIED_METHOD_SAY : 0)), sp - mark);
1697 if ( gv && GvEGVx(gv) && (io = GvIO(GvEGV(gv)))
1698 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1701 SETERRNO(EBADF,RMS_IFI);
1704 else if (!(fp = IoOFP(io))) {
1706 report_wrongway_fh(gv, '<');
1709 SETERRNO(EBADF,IoIFP(io)?RMS_FAC:RMS_IFI);
1713 SV * const ofs = GvSV(PL_ofsgv); /* $, */
1715 if (ofs && (SvGMAGICAL(ofs) || SvOK(ofs))) {
1716 while (MARK <= SP) {
1717 if (!do_print(*MARK, fp))
1721 /* don't use 'ofs' here - it may be invalidated by magic callbacks */
1722 if (!do_print(GvSV(PL_ofsgv), fp)) {
1730 while (MARK <= SP) {
1731 if (!do_print(*MARK, fp))
1739 if (PL_op->op_type == OP_SAY) {
1740 if (PerlIO_write(fp, "\n", 1) == 0 || PerlIO_error(fp))
1743 else if (PL_ors_sv && SvOK(PL_ors_sv))
1744 if (!do_print(PL_ors_sv, fp)) /* $\ */
1747 if (IoFLAGS(io) & IOf_FLUSH)
1748 if (PerlIO_flush(fp) == EOF)
1758 XPUSHs(&PL_sv_undef);
1763 /* do the common parts of pp_padhv() and pp_rv2hv()
1764 * It assumes the caller has done EXTEND(SP, 1) or equivalent.
1765 * 'is_keys' indicates the OPpPADHV_ISKEYS/OPpRV2HV_ISKEYS flag is set.
1766 * 'has_targ' indicates that the op has a target - this should
1767 * be a compile-time constant so that the code can constant-folded as
1771 PERL_STATIC_INLINE OP*
1772 S_padhv_rv2hv_common(pTHX_ HV *hv, U8 gimme, bool is_keys, bool has_targ)
1781 assert(PL_op->op_type == OP_PADHV || PL_op->op_type == OP_RV2HV);
1783 if (gimme == G_ARRAY) {
1789 /* 'keys %h' masquerading as '%h': reset iterator */
1790 (void)hv_iterinit(hv);
1792 if (gimme == G_VOID)
1795 is_bool = ( PL_op->op_private & OPpTRUEBOOL
1796 || ( PL_op->op_private & OPpMAYBE_TRUEBOOL
1797 && block_gimme() == G_VOID));
1798 is_tied = SvRMAGICAL(hv) && (mg = mg_find(MUTABLE_SV(hv), PERL_MAGIC_tied));
1800 if (UNLIKELY(is_tied)) {
1801 if (is_keys && !is_bool) {
1803 while (hv_iternext(hv))
1808 sv = magic_scalarpack(hv, mg);
1815 sv = i ? &PL_sv_yes : &PL_sv_zero;
1827 /* parent op should be an unused OP_KEYS whose targ we can
1832 assert(!OpHAS_SIBLING(PL_op));
1833 k = PL_op->op_sibparent;
1834 assert(k->op_type == OP_KEYS);
1835 TARG = PAD_SV(k->op_targ);
1848 /* This is also called directly by pp_lvavref. */
1853 assert(SvTYPE(TARG) == SVt_PVAV);
1854 if (UNLIKELY( PL_op->op_private & OPpLVAL_INTRO ))
1855 if (LIKELY( !(PL_op->op_private & OPpPAD_STATE) ))
1856 SAVECLEARSV(PAD_SVl(PL_op->op_targ));
1859 if (PL_op->op_flags & OPf_REF) {
1863 else if (PL_op->op_private & OPpMAYBE_LVSUB) {
1864 const I32 flags = is_lvalue_sub();
1865 if (flags && !(flags & OPpENTERSUB_INARGS)) {
1866 if (GIMME_V == G_SCALAR)
1867 /* diag_listed_as: Can't return %s to lvalue scalar context */
1868 Perl_croak(aTHX_ "Can't return array to lvalue scalar context");
1875 if (gimme == G_ARRAY)
1876 return S_pushav(aTHX_ (AV*)TARG);
1878 if (gimme == G_SCALAR) {
1879 const SSize_t maxarg = AvFILL(MUTABLE_AV(TARG)) + 1;
1882 else if (PL_op->op_private & OPpTRUEBOOL)
1896 assert(SvTYPE(TARG) == SVt_PVHV);
1897 if (UNLIKELY( PL_op->op_private & OPpLVAL_INTRO ))
1898 if (LIKELY( !(PL_op->op_private & OPpPAD_STATE) ))
1899 SAVECLEARSV(PAD_SVl(PL_op->op_targ));
1903 if (PL_op->op_flags & OPf_REF) {
1907 else if (PL_op->op_private & OPpMAYBE_LVSUB) {
1908 const I32 flags = is_lvalue_sub();
1909 if (flags && !(flags & OPpENTERSUB_INARGS)) {
1910 if (GIMME_V == G_SCALAR)
1911 /* diag_listed_as: Can't return %s to lvalue scalar context */
1912 Perl_croak(aTHX_ "Can't return hash to lvalue scalar context");
1920 return S_padhv_rv2hv_common(aTHX_ (HV*)TARG, gimme,
1921 cBOOL(PL_op->op_private & OPpPADHV_ISKEYS),
1926 /* also used for: pp_rv2hv() */
1927 /* also called directly by pp_lvavref */
1932 const U8 gimme = GIMME_V;
1933 static const char an_array[] = "an ARRAY";
1934 static const char a_hash[] = "a HASH";
1935 const bool is_pp_rv2av = PL_op->op_type == OP_RV2AV
1936 || PL_op->op_type == OP_LVAVREF;
1937 const svtype type = is_pp_rv2av ? SVt_PVAV : SVt_PVHV;
1941 if (UNLIKELY(SvAMAGIC(sv))) {
1942 sv = amagic_deref_call(sv, is_pp_rv2av ? to_av_amg : to_hv_amg);
1945 if (UNLIKELY(SvTYPE(sv) != type))
1946 /* diag_listed_as: Not an ARRAY reference */
1947 DIE(aTHX_ "Not %s reference", is_pp_rv2av ? an_array : a_hash);
1948 else if (UNLIKELY(PL_op->op_flags & OPf_MOD
1949 && PL_op->op_private & OPpLVAL_INTRO))
1950 Perl_croak(aTHX_ "%s", PL_no_localize_ref);
1952 else if (UNLIKELY(SvTYPE(sv) != type)) {
1955 if (!isGV_with_GP(sv)) {
1956 gv = Perl_softref2xv(aTHX_ sv, is_pp_rv2av ? an_array : a_hash,
1962 gv = MUTABLE_GV(sv);
1964 sv = is_pp_rv2av ? MUTABLE_SV(GvAVn(gv)) : MUTABLE_SV(GvHVn(gv));
1965 if (PL_op->op_private & OPpLVAL_INTRO)
1966 sv = is_pp_rv2av ? MUTABLE_SV(save_ary(gv)) : MUTABLE_SV(save_hash(gv));
1968 if (PL_op->op_flags & OPf_REF) {
1972 else if (UNLIKELY(PL_op->op_private & OPpMAYBE_LVSUB)) {
1973 const I32 flags = is_lvalue_sub();
1974 if (flags && !(flags & OPpENTERSUB_INARGS)) {
1975 if (gimme != G_ARRAY)
1976 goto croak_cant_return;
1983 AV *const av = MUTABLE_AV(sv);
1985 if (gimme == G_ARRAY) {
1988 return S_pushav(aTHX_ av);
1991 if (gimme == G_SCALAR) {
1992 const SSize_t maxarg = AvFILL(av) + 1;
1993 if (PL_op->op_private & OPpTRUEBOOL)
1994 SETs(maxarg ? &PL_sv_yes : &PL_sv_zero);
2003 return S_padhv_rv2hv_common(aTHX_ (HV*)sv, gimme,
2004 cBOOL(PL_op->op_private & OPpRV2HV_ISKEYS),
2010 Perl_croak(aTHX_ "Can't return %s to lvalue scalar context",
2011 is_pp_rv2av ? "array" : "hash");
2016 S_do_oddball(pTHX_ SV **oddkey, SV **firstkey)
2018 PERL_ARGS_ASSERT_DO_ODDBALL;
2021 if (ckWARN(WARN_MISC)) {
2023 if (oddkey == firstkey &&
2025 (SvTYPE(SvRV(*oddkey)) == SVt_PVAV ||
2026 SvTYPE(SvRV(*oddkey)) == SVt_PVHV))
2028 err = "Reference found where even-sized list expected";
2031 err = "Odd number of elements in hash assignment";
2032 Perl_warner(aTHX_ packWARN(WARN_MISC), "%s", err);
2039 /* Do a mark and sweep with the SVf_BREAK flag to detect elements which
2040 * are common to both the LHS and RHS of an aassign, and replace them
2041 * with copies. All these copies are made before the actual list assign is
2044 * For example in ($a,$b) = ($b,$a), assigning the value of the first RHS
2045 * element ($b) to the first LH element ($a), modifies $a; when the
2046 * second assignment is done, the second RH element now has the wrong
2047 * value. So we initially replace the RHS with ($b, mortalcopy($a)).
2048 * Note that we don't need to make a mortal copy of $b.
2050 * The algorithm below works by, for every RHS element, mark the
2051 * corresponding LHS target element with SVf_BREAK. Then if the RHS
2052 * element is found with SVf_BREAK set, it means it would have been
2053 * modified, so make a copy.
2054 * Note that by scanning both LHS and RHS in lockstep, we avoid
2055 * unnecessary copies (like $b above) compared with a naive
2056 * "mark all LHS; copy all marked RHS; unmark all LHS".
2058 * If the LHS element is a 'my' declaration' and has a refcount of 1, then
2059 * it can't be common and can be skipped.
2061 * On DEBUGGING builds it takes an extra boolean, fake. If true, it means
2062 * that we thought we didn't need to call S_aassign_copy_common(), but we
2063 * have anyway for sanity checking. If we find we need to copy, then panic.
2066 PERL_STATIC_INLINE void
2067 S_aassign_copy_common(pTHX_ SV **firstlelem, SV **lastlelem,
2068 SV **firstrelem, SV **lastrelem
2077 SSize_t lcount = lastlelem - firstlelem + 1;
2078 bool marked = FALSE; /* have we marked any LHS with SVf_BREAK ? */
2079 bool const do_rc1 = cBOOL(PL_op->op_private & OPpASSIGN_COMMON_RC1);
2080 bool copy_all = FALSE;
2082 assert(!PL_in_clean_all); /* SVf_BREAK not already in use */
2083 assert(firstlelem < lastlelem); /* at least 2 LH elements */
2084 assert(firstrelem < lastrelem); /* at least 2 RH elements */
2088 /* we never have to copy the first RH element; it can't be corrupted
2089 * by assigning something to the corresponding first LH element.
2090 * So this scan does in a loop: mark LHS[N]; test RHS[N+1]
2092 relem = firstrelem + 1;
2094 for (; relem <= lastrelem; relem++) {
2097 /* mark next LH element */
2099 if (--lcount >= 0) {
2102 if (UNLIKELY(!svl)) {/* skip AV alias marker */
2103 assert (lelem <= lastlelem);
2109 if (SvSMAGICAL(svl)) {
2112 if (SvTYPE(svl) == SVt_PVAV || SvTYPE(svl) == SVt_PVHV) {
2115 /* this LH element will consume all further args;
2116 * no need to mark any further LH elements (if any).
2117 * But we still need to scan any remaining RHS elements;
2118 * set lcount negative to distinguish from lcount == 0,
2119 * so the loop condition continues being true
2122 lelem--; /* no need to unmark this element */
2124 else if (!(do_rc1 && SvREFCNT(svl) == 1) && !SvIMMORTAL(svl)) {
2125 SvFLAGS(svl) |= SVf_BREAK;
2129 /* don't check RH element if no SVf_BREAK flags set yet */
2136 /* see if corresponding RH element needs copying */
2142 if (UNLIKELY(SvFLAGS(svr) & (SVf_BREAK|SVs_GMG) || copy_all)) {
2143 U32 brk = (SvFLAGS(svr) & SVf_BREAK);
2147 /* op_dump(PL_op); */
2149 "panic: aassign skipped needed copy of common RH elem %"
2150 UVuf, (UV)(relem - firstrelem));
2154 TAINT_NOT; /* Each item is independent */
2156 /* Dear TODO test in t/op/sort.t, I love you.
2157 (It's relying on a panic, not a "semi-panic" from newSVsv()
2158 and then an assertion failure below.) */
2159 if (UNLIKELY(SvIS_FREED(svr))) {
2160 Perl_croak(aTHX_ "panic: attempt to copy freed scalar %p",
2163 /* avoid break flag while copying; otherwise COW etc
2165 SvFLAGS(svr) &= ~SVf_BREAK;
2166 /* Not newSVsv(), as it does not allow copy-on-write,
2167 resulting in wasteful copies.
2168 Also, we use SV_NOSTEAL in case the SV is used more than
2169 once, e.g. (...) = (f())[0,0]
2170 Where the same SV appears twice on the RHS without a ref
2171 count bump. (Although I suspect that the SV won't be
2172 stealable here anyway - DAPM).
2174 *relem = sv_mortalcopy_flags(svr,
2175 SV_GMAGIC|SV_DO_COW_SVSETSV|SV_NOSTEAL);
2176 /* ... but restore afterwards in case it's needed again,
2177 * e.g. ($a,$b,$c) = (1,$a,$a)
2179 SvFLAGS(svr) |= brk;
2191 while (lelem > firstlelem) {
2192 SV * const svl = *(--lelem);
2194 SvFLAGS(svl) &= ~SVf_BREAK;
2203 SV **lastlelem = PL_stack_sp;
2204 SV **lastrelem = PL_stack_base + POPMARK;
2205 SV **firstrelem = PL_stack_base + POPMARK + 1;
2206 SV **firstlelem = lastrelem + 1;
2211 /* PL_delaymagic is restored by JUMPENV_POP on dieing, so we
2212 * only need to save locally, not on the save stack */
2213 U16 old_delaymagic = PL_delaymagic;
2218 PL_delaymagic = DM_DELAY; /* catch simultaneous items */
2220 /* If there's a common identifier on both sides we have to take
2221 * special care that assigning the identifier on the left doesn't
2222 * clobber a value on the right that's used later in the list.
2225 /* at least 2 LH and RH elements, or commonality isn't an issue */
2226 if (firstlelem < lastlelem && firstrelem < lastrelem) {
2227 for (relem = firstrelem+1; relem <= lastrelem; relem++) {
2228 if (SvGMAGICAL(*relem))
2231 for (lelem = firstlelem; lelem <= lastlelem; lelem++) {
2232 if (*lelem && SvSMAGICAL(*lelem))
2235 if ( PL_op->op_private & (OPpASSIGN_COMMON_SCALAR|OPpASSIGN_COMMON_RC1) ) {
2236 if (PL_op->op_private & OPpASSIGN_COMMON_RC1) {
2237 /* skip the scan if all scalars have a ref count of 1 */
2238 for (lelem = firstlelem; lelem <= lastlelem; lelem++) {
2240 if (!sv || SvREFCNT(sv) == 1)
2242 if (SvTYPE(sv) != SVt_PVAV && SvTYPE(sv) != SVt_PVAV)
2249 S_aassign_copy_common(aTHX_
2250 firstlelem, lastlelem, firstrelem, lastrelem
2260 /* on debugging builds, do the scan even if we've concluded we
2261 * don't need to, then panic if we find commonality. Note that the
2262 * scanner assumes at least 2 elements */
2263 if (firstlelem < lastlelem && firstrelem < lastrelem) {
2274 if (relem > lastrelem)
2277 /* first lelem loop while there are still relems */
2278 while (LIKELY(lelem <= lastlelem)) {
2282 TAINT_NOT; /* Each item stands on its own, taintwise. */
2284 assert(relem <= lastrelem);
2285 if (UNLIKELY(!lsv)) {
2288 ASSUME(SvTYPE(lsv) == SVt_PVAV);
2291 switch (SvTYPE(lsv)) {
2296 SSize_t nelems = lastrelem - relem + 1;
2297 AV *ary = MUTABLE_AV(lsv);
2299 /* Assigning to an aggregate is tricky. First there is the
2300 * issue of commonality, e.g. @a = ($a[0]). Since the
2301 * stack isn't refcounted, clearing @a prior to storing
2302 * elements will free $a[0]. Similarly with
2303 * sub FETCH { $status[$_[1]] } @status = @tied[0,1];
2305 * The way to avoid these issues is to make the copy of each
2306 * SV (and we normally store a *copy* in the array) *before*
2307 * clearing the array. But this has a problem in that
2308 * if the code croaks during copying, the not-yet-stored copies
2309 * could leak. One way to avoid this is to make all the copies
2310 * mortal, but that's quite expensive.
2312 * The current solution to these issues is to use a chunk
2313 * of the tmps stack as a temporary refcounted-stack. SVs
2314 * will be put on there during processing to avoid leaks,
2315 * but will be removed again before the end of this block,
2316 * so free_tmps() is never normally called. Also, the
2317 * sv_refcnt of the SVs doesn't have to be manipulated, since
2318 * the ownership of 1 reference count is transferred directly
2319 * from the tmps stack to the AV when the SV is stored.
2321 * We disarm slots in the temps stack by storing PL_sv_undef
2322 * there: it doesn't matter if that SV's refcount is
2323 * repeatedly decremented during a croak. But usually this is
2324 * only an interim measure. By the end of this code block
2325 * we try where possible to not leave any PL_sv_undef's on the
2326 * tmps stack e.g. by shuffling newer entries down.
2328 * There is one case where we don't copy: non-magical
2329 * SvTEMP(sv)'s with a ref count of 1. The only owner of these
2330 * is on the tmps stack, so its safe to directly steal the SV
2331 * rather than copying. This is common in things like function
2332 * returns, map etc, which all return a list of such SVs.
2334 * Note however something like @a = (f())[0,0], where there is
2335 * a danger of the same SV being shared: this avoided because
2336 * when the SV is stored as $a[0], its ref count gets bumped,
2337 * so the RC==1 test fails and the second element is copied
2340 * We also use one slot in the tmps stack to hold an extra
2341 * ref to the array, to ensure it doesn't get prematurely
2342 * freed. Again, this is removed before the end of this block.
2344 * Note that OPpASSIGN_COMMON_AGG is used to flag a possible
2345 * @a = ($a[0]) case, but the current implementation uses the
2346 * same algorithm regardless, so ignores that flag. (It *is*
2347 * used in the hash branch below, however).
2350 /* Reserve slots for ary, plus the elems we're about to copy,
2351 * then protect ary and temporarily void the remaining slots
2352 * with &PL_sv_undef */
2353 EXTEND_MORTAL(nelems + 1);
2354 PL_tmps_stack[++PL_tmps_ix] = SvREFCNT_inc_simple_NN(ary);
2355 tmps_base = PL_tmps_ix + 1;
2356 for (i = 0; i < nelems; i++)
2357 PL_tmps_stack[tmps_base + i] = &PL_sv_undef;
2358 PL_tmps_ix += nelems;
2360 /* Make a copy of each RHS elem and save on the tmps_stack
2361 * (or pass through where we can optimise away the copy) */
2363 if (UNLIKELY(alias)) {
2364 U32 lval = (gimme == G_ARRAY)
2365 ? (PL_op->op_flags & OPf_MOD || LVRET) : 0;
2366 for (svp = relem; svp <= lastrelem; svp++) {
2371 DIE(aTHX_ "Assigned value is not a reference");
2372 if (SvTYPE(SvRV(rsv)) > SVt_PVLV)
2373 /* diag_listed_as: Assigned value is not %s reference */
2375 "Assigned value is not a SCALAR reference");
2377 *svp = rsv = sv_mortalcopy(rsv);
2378 /* XXX else check for weak refs? */
2379 rsv = SvREFCNT_inc_NN(SvRV(rsv));
2380 assert(tmps_base <= PL_tmps_max);
2381 PL_tmps_stack[tmps_base++] = rsv;
2385 for (svp = relem; svp <= lastrelem; svp++) {
2388 if (SvTEMP(rsv) && !SvGMAGICAL(rsv) && SvREFCNT(rsv) == 1) {
2389 /* can skip the copy */
2390 SvREFCNT_inc_simple_void_NN(rsv);
2395 /* do get before newSV, in case it dies and leaks */
2398 /* see comment in S_aassign_copy_common about
2400 sv_setsv_flags(nsv, rsv,
2401 (SV_DO_COW_SVSETSV|SV_NOSTEAL));
2405 assert(tmps_base <= PL_tmps_max);
2406 PL_tmps_stack[tmps_base++] = rsv;
2410 if (SvRMAGICAL(ary) || AvFILLp(ary) >= 0) /* may be non-empty */
2413 /* store in the array, the SVs that are in the tmps stack */
2415 tmps_base -= nelems;
2417 if (SvMAGICAL(ary) || SvREADONLY(ary) || !AvREAL(ary)) {
2418 /* for arrays we can't cheat with, use the official API */
2419 av_extend(ary, nelems - 1);
2420 for (i = 0; i < nelems; i++) {
2421 SV **svp = &(PL_tmps_stack[tmps_base + i]);
2423 /* A tied store won't take ownership of rsv, so keep
2424 * the 1 refcnt on the tmps stack; otherwise disarm
2425 * the tmps stack entry */
2426 if (av_store(ary, i, rsv))
2427 *svp = &PL_sv_undef;
2428 /* av_store() may have added set magic to rsv */;
2431 /* disarm ary refcount: see comments below about leak */
2432 PL_tmps_stack[tmps_base - 1] = &PL_sv_undef;
2435 /* directly access/set the guts of the AV */
2436 SSize_t fill = nelems - 1;
2437 if (fill > AvMAX(ary))
2438 av_extend_guts(ary, fill, &AvMAX(ary), &AvALLOC(ary),
2440 AvFILLp(ary) = fill;
2441 Copy(&(PL_tmps_stack[tmps_base]), AvARRAY(ary), nelems, SV*);
2442 /* Quietly remove all the SVs from the tmps stack slots,
2443 * since ary has now taken ownership of the refcnt.
2444 * Also remove ary: which will now leak if we die before
2445 * the SvREFCNT_dec_NN(ary) below */
2446 if (UNLIKELY(PL_tmps_ix >= tmps_base + nelems))
2447 Move(&PL_tmps_stack[tmps_base + nelems],
2448 &PL_tmps_stack[tmps_base - 1],
2449 PL_tmps_ix - (tmps_base + nelems) + 1,
2451 PL_tmps_ix -= (nelems + 1);
2454 if (UNLIKELY(PL_delaymagic & DM_ARRAY_ISA))
2455 /* its assumed @ISA set magic can't die and leak ary */
2456 SvSETMAGIC(MUTABLE_SV(ary));
2457 SvREFCNT_dec_NN(ary);
2459 relem = lastrelem + 1;
2463 case SVt_PVHV: { /* normal hash */
2469 SSize_t nelems = lastrelem - relem + 1;
2470 HV *hash = MUTABLE_HV(lsv);
2472 if (UNLIKELY(nelems & 1)) {
2473 do_oddball(lastrelem, relem);
2474 /* we have firstlelem to reuse, it's not needed any more */
2475 *++lastrelem = &PL_sv_undef;
2479 /* See the SVt_PVAV branch above for a long description of
2480 * how the following all works. The main difference for hashes
2481 * is that we treat keys and values separately (and have
2482 * separate loops for them): as for arrays, values are always
2483 * copied (except for the SvTEMP optimisation), since they
2484 * need to be stored in the hash; while keys are only
2485 * processed where they might get prematurely freed or
2488 /* tmps stack slots:
2489 * * reserve a slot for the hash keepalive;
2490 * * reserve slots for the hash values we're about to copy;
2491 * * preallocate for the keys we'll possibly copy or refcount bump
2493 * then protect hash and temporarily void the remaining
2494 * value slots with &PL_sv_undef */
2495 EXTEND_MORTAL(nelems + 1);
2497 /* convert to number of key/value pairs */
2500 PL_tmps_stack[++PL_tmps_ix] = SvREFCNT_inc_simple_NN(hash);
2501 tmps_base = PL_tmps_ix + 1;
2502 for (i = 0; i < nelems; i++)
2503 PL_tmps_stack[tmps_base + i] = &PL_sv_undef;
2504 PL_tmps_ix += nelems;
2506 /* Make a copy of each RHS hash value and save on the tmps_stack
2507 * (or pass through where we can optimise away the copy) */
2509 for (svp = relem + 1; svp <= lastrelem; svp += 2) {
2512 if (SvTEMP(rsv) && !SvGMAGICAL(rsv) && SvREFCNT(rsv) == 1) {
2513 /* can skip the copy */
2514 SvREFCNT_inc_simple_void_NN(rsv);
2519 /* do get before newSV, in case it dies and leaks */
2522 /* see comment in S_aassign_copy_common about
2524 sv_setsv_flags(nsv, rsv,
2525 (SV_DO_COW_SVSETSV|SV_NOSTEAL));
2529 assert(tmps_base <= PL_tmps_max);
2530 PL_tmps_stack[tmps_base++] = rsv;
2532 tmps_base -= nelems;
2535 /* possibly protect keys */
2537 if (UNLIKELY(gimme == G_ARRAY)) {
2539 * @a = ((%h = ($$r, 1)), $r = "x");
2540 * $_++ for %h = (1,2,3,4);
2542 EXTEND_MORTAL(nelems);
2543 for (svp = relem; svp <= lastrelem; svp += 2)
2544 *svp = sv_mortalcopy_flags(*svp,
2545 SV_GMAGIC|SV_DO_COW_SVSETSV|SV_NOSTEAL);
2547 else if (PL_op->op_private & OPpASSIGN_COMMON_AGG) {
2548 /* for possible commonality, e.g.
2550 * avoid premature freeing RHS keys by mortalising
2552 * For a magic element, make a copy so that its magic is
2553 * called *before* the hash is emptied (which may affect
2554 * a tied value for example).
2555 * In theory we should check for magic keys in all
2556 * cases, not just under OPpASSIGN_COMMON_AGG, but in
2557 * practice, !OPpASSIGN_COMMON_AGG implies only
2558 * constants or padtmps on the RHS.
2560 EXTEND_MORTAL(nelems);
2561 for (svp = relem; svp <= lastrelem; svp += 2) {
2563 if (UNLIKELY(SvGMAGICAL(rsv))) {
2565 *svp = sv_mortalcopy_flags(*svp,
2566 SV_GMAGIC|SV_DO_COW_SVSETSV|SV_NOSTEAL);
2567 /* allow other branch to continue pushing
2568 * onto tmps stack without checking each time */
2569 n = (lastrelem - relem) >> 1;
2573 PL_tmps_stack[++PL_tmps_ix] =
2574 SvREFCNT_inc_simple_NN(rsv);
2578 if (SvRMAGICAL(hash) || HvUSEDKEYS(hash))
2581 /* now assign the keys and values to the hash */
2585 if (UNLIKELY(gimme == G_ARRAY)) {
2586 /* @a = (%h = (...)) etc */
2588 SV **topelem = relem;
2590 for (i = 0, svp = relem; svp <= lastrelem; i++, svp++) {
2593 /* remove duplicates from list we return */
2594 if (!hv_exists_ent(hash, key, 0)) {
2595 /* copy key back: possibly to an earlier
2596 * stack location if we encountered dups earlier,
2597 * The values will be updated later
2602 /* A tied store won't take ownership of val, so keep
2603 * the 1 refcnt on the tmps stack; otherwise disarm
2604 * the tmps stack entry */
2605 if (hv_store_ent(hash, key, val, 0))
2606 PL_tmps_stack[tmps_base + i] = &PL_sv_undef;
2609 /* hv_store_ent() may have added set magic to val */;
2612 if (topelem < svp) {
2613 /* at this point we have removed the duplicate key/value
2614 * pairs from the stack, but the remaining values may be
2615 * wrong; i.e. with (a 1 a 2 b 3) on the stack we've removed
2616 * the (a 2), but the stack now probably contains
2617 * (a <freed> b 3), because { hv_save(a,1); hv_save(a,2) }
2618 * obliterates the earlier key. So refresh all values. */
2619 lastrelem = topelem - 1;
2620 while (relem < lastrelem) {
2622 he = hv_fetch_ent(hash, *relem++, 0, 0);
2623 *relem++ = (he ? HeVAL(he) : &PL_sv_undef);
2629 for (i = 0, svp = relem; svp <= lastrelem; i++, svp++) {
2632 if (hv_store_ent(hash, key, val, 0))
2633 PL_tmps_stack[tmps_base + i] = &PL_sv_undef;
2636 /* hv_store_ent() may have added set magic to val */;
2642 /* there are still some 'live' recounts on the tmps stack
2643 * - usually caused by storing into a tied hash. So let
2644 * free_tmps() do the proper but slow job later.
2645 * Just disarm hash refcount: see comments below about leak
2647 PL_tmps_stack[tmps_base - 1] = &PL_sv_undef;
2650 /* Quietly remove all the SVs from the tmps stack slots,
2651 * since hash has now taken ownership of the refcnt.
2652 * Also remove hash: which will now leak if we die before
2653 * the SvREFCNT_dec_NN(hash) below */
2654 if (UNLIKELY(PL_tmps_ix >= tmps_base + nelems))
2655 Move(&PL_tmps_stack[tmps_base + nelems],
2656 &PL_tmps_stack[tmps_base - 1],
2657 PL_tmps_ix - (tmps_base + nelems) + 1,
2659 PL_tmps_ix -= (nelems + 1);
2662 SvREFCNT_dec_NN(hash);
2664 relem = lastrelem + 1;
2669 if (!SvIMMORTAL(lsv)) {
2673 SvTEMP(lsv) && !SvSMAGICAL(lsv) && SvREFCNT(lsv) == 1 &&
2674 (!isGV_with_GP(lsv) || SvFAKE(lsv)) && ckWARN(WARN_MISC)
2677 packWARN(WARN_MISC),
2678 "Useless assignment to a temporary"
2681 /* avoid freeing $$lsv if it might be needed for further
2682 * elements, e.g. ($ref, $foo) = (1, $$ref) */
2684 && ( ((ref = SvRV(lsv)), SvREFCNT(ref)) == 1)
2685 && lelem <= lastlelem
2688 SvREFCNT_inc_simple_void_NN(ref);
2689 /* an unrolled sv_2mortal */
2691 if (UNLIKELY(ix >= PL_tmps_max))
2692 /* speculatively grow enough to cover other
2694 (void)tmps_grow_p(ix + (lastlelem - lelem));
2695 PL_tmps_stack[ix] = ref;
2698 sv_setsv(lsv, *relem);
2702 if (++relem > lastrelem)
2711 /* simplified lelem loop for when there are no relems left */
2712 while (LIKELY(lelem <= lastlelem)) {
2715 TAINT_NOT; /* Each item stands on its own, taintwise. */
2717 if (UNLIKELY(!lsv)) {
2719 ASSUME(SvTYPE(lsv) == SVt_PVAV);
2722 switch (SvTYPE(lsv)) {
2724 if (SvRMAGICAL(lsv) || AvFILLp((SV*)lsv) >= 0) {
2726 if (UNLIKELY(PL_delaymagic & DM_ARRAY_ISA))
2732 if (SvRMAGICAL(lsv) || HvUSEDKEYS((HV*)lsv))
2737 if (!SvIMMORTAL(lsv)) {
2746 TAINT_NOT; /* result of list assign isn't tainted */
2748 if (UNLIKELY(PL_delaymagic & ~DM_DELAY)) {
2749 /* Will be used to set PL_tainting below */
2750 Uid_t tmp_uid = PerlProc_getuid();
2751 Uid_t tmp_euid = PerlProc_geteuid();
2752 Gid_t tmp_gid = PerlProc_getgid();
2753 Gid_t tmp_egid = PerlProc_getegid();
2755 /* XXX $> et al currently silently ignore failures */
2756 if (PL_delaymagic & DM_UID) {
2757 #ifdef HAS_SETRESUID
2759 setresuid((PL_delaymagic & DM_RUID) ? PL_delaymagic_uid : (Uid_t)-1,
2760 (PL_delaymagic & DM_EUID) ? PL_delaymagic_euid : (Uid_t)-1,
2762 #elif defined(HAS_SETREUID)
2764 setreuid((PL_delaymagic & DM_RUID) ? PL_delaymagic_uid : (Uid_t)-1,
2765 (PL_delaymagic & DM_EUID) ? PL_delaymagic_euid : (Uid_t)-1));
2768 if ((PL_delaymagic & DM_UID) == DM_RUID) {
2769 PERL_UNUSED_RESULT(setruid(PL_delaymagic_uid));
2770 PL_delaymagic &= ~DM_RUID;
2772 # endif /* HAS_SETRUID */
2774 if ((PL_delaymagic & DM_UID) == DM_EUID) {
2775 PERL_UNUSED_RESULT(seteuid(PL_delaymagic_euid));
2776 PL_delaymagic &= ~DM_EUID;
2778 # endif /* HAS_SETEUID */
2779 if (PL_delaymagic & DM_UID) {
2780 if (PL_delaymagic_uid != PL_delaymagic_euid)
2781 DIE(aTHX_ "No setreuid available");
2782 PERL_UNUSED_RESULT(PerlProc_setuid(PL_delaymagic_uid));
2784 #endif /* HAS_SETRESUID */
2786 tmp_uid = PerlProc_getuid();
2787 tmp_euid = PerlProc_geteuid();
2789 /* XXX $> et al currently silently ignore failures */
2790 if (PL_delaymagic & DM_GID) {
2791 #ifdef HAS_SETRESGID
2793 setresgid((PL_delaymagic & DM_RGID) ? PL_delaymagic_gid : (Gid_t)-1,
2794 (PL_delaymagic & DM_EGID) ? PL_delaymagic_egid : (Gid_t)-1,
2796 #elif defined(HAS_SETREGID)
2798 setregid((PL_delaymagic & DM_RGID) ? PL_delaymagic_gid : (Gid_t)-1,
2799 (PL_delaymagic & DM_EGID) ? PL_delaymagic_egid : (Gid_t)-1));
2802 if ((PL_delaymagic & DM_GID) == DM_RGID) {
2803 PERL_UNUSED_RESULT(setrgid(PL_delaymagic_gid));
2804 PL_delaymagic &= ~DM_RGID;
2806 # endif /* HAS_SETRGID */
2808 if ((PL_delaymagic & DM_GID) == DM_EGID) {
2809 PERL_UNUSED_RESULT(setegid(PL_delaymagic_egid));
2810 PL_delaymagic &= ~DM_EGID;
2812 # endif /* HAS_SETEGID */
2813 if (PL_delaymagic & DM_GID) {
2814 if (PL_delaymagic_gid != PL_delaymagic_egid)
2815 DIE(aTHX_ "No setregid available");
2816 PERL_UNUSED_RESULT(PerlProc_setgid(PL_delaymagic_gid));
2818 #endif /* HAS_SETRESGID */
2820 tmp_gid = PerlProc_getgid();
2821 tmp_egid = PerlProc_getegid();
2823 TAINTING_set( TAINTING_get | (tmp_uid && (tmp_euid != tmp_uid || tmp_egid != tmp_gid)) );
2824 #ifdef NO_TAINT_SUPPORT
2825 PERL_UNUSED_VAR(tmp_uid);
2826 PERL_UNUSED_VAR(tmp_euid);
2827 PERL_UNUSED_VAR(tmp_gid);
2828 PERL_UNUSED_VAR(tmp_egid);
2831 PL_delaymagic = old_delaymagic;
2833 if (gimme == G_VOID)
2834 SP = firstrelem - 1;
2835 else if (gimme == G_SCALAR) {
2838 if (PL_op->op_private & OPpASSIGN_TRUEBOOL)
2839 SETs((firstlelem - firstrelem) ? &PL_sv_yes : &PL_sv_zero);
2842 SETi(firstlelem - firstrelem);
2854 PMOP * const pm = cPMOP;
2855 REGEXP * rx = PM_GETRE(pm);
2856 regexp *prog = ReANY(rx);
2857 SV * const pkg = RXp_ENGINE(prog)->qr_package(aTHX_ (rx));
2858 SV * const rv = sv_newmortal();
2862 SvUPGRADE(rv, SVt_IV);
2863 /* For a subroutine describing itself as "This is a hacky workaround" I'm
2864 loathe to use it here, but it seems to be the right fix. Or close.
2865 The key part appears to be that it's essential for pp_qr to return a new
2866 object (SV), which implies that there needs to be an effective way to
2867 generate a new SV from the existing SV that is pre-compiled in the
2869 SvRV_set(rv, MUTABLE_SV(reg_temp_copy(NULL, rx)));
2872 cvp = &( ReANY((REGEXP *)SvRV(rv))->qr_anoncv);
2873 if (UNLIKELY((cv = *cvp) && CvCLONE(*cvp))) {
2874 *cvp = cv_clone(cv);
2875 SvREFCNT_dec_NN(cv);
2879 HV *const stash = gv_stashsv(pkg, GV_ADD);
2880 SvREFCNT_dec_NN(pkg);
2881 (void)sv_bless(rv, stash);
2884 if (UNLIKELY(RXp_ISTAINTED(prog))) {
2886 SvTAINTED_on(SvRV(rv));
2899 SSize_t curpos = 0; /* initial pos() or current $+[0] */
2902 const char *truebase; /* Start of string */
2903 REGEXP *rx = PM_GETRE(pm);
2904 regexp *prog = ReANY(rx);
2906 const U8 gimme = GIMME_V;
2908 const I32 oldsave = PL_savestack_ix;
2909 I32 had_zerolen = 0;
2912 if (PL_op->op_flags & OPf_STACKED)
2923 PUTBACK; /* EVAL blocks need stack_sp. */
2924 /* Skip get-magic if this is a qr// clone, because regcomp has
2926 truebase = prog->mother_re
2927 ? SvPV_nomg_const(TARG, len)
2928 : SvPV_const(TARG, len);
2930 DIE(aTHX_ "panic: pp_match");
2931 strend = truebase + len;
2932 rxtainted = (RXp_ISTAINTED(prog) ||
2933 (TAINT_get && (pm->op_pmflags & PMf_RETAINT)));
2936 /* We need to know this in case we fail out early - pos() must be reset */
2937 global = dynpm->op_pmflags & PMf_GLOBAL;
2939 /* PMdf_USED is set after a ?? matches once */
2942 SvREADONLY(PL_regex_pad[pm->op_pmoffset])
2944 pm->op_pmflags & PMf_USED
2947 DEBUG_r(PerlIO_printf(Perl_debug_log, "?? already matched once"));
2951 /* handle the empty pattern */
2952 if (!RX_PRELEN(rx) && PL_curpm && !prog->mother_re) {
2953 if (PL_curpm == PL_reg_curpm) {
2954 if (PL_curpm_under) {
2955 if (PL_curpm_under == PL_reg_curpm) {
2956 Perl_croak(aTHX_ "Infinite recursion via empty pattern");
2958 pm = PL_curpm_under;
2968 if (RXp_MINLEN(prog) >= 0 && (STRLEN)RXp_MINLEN(prog) > len) {
2969 DEBUG_r(PerlIO_printf(Perl_debug_log, "String shorter than min possible regex match (%"
2970 UVuf " < %" IVdf ")\n",
2971 (UV)len, (IV)RXp_MINLEN(prog)));
2975 /* get pos() if //g */
2977 mg = mg_find_mglob(TARG);
2978 if (mg && mg->mg_len >= 0) {
2979 curpos = MgBYTEPOS(mg, TARG, truebase, len);
2980 /* last time pos() was set, it was zero-length match */
2981 if (mg->mg_flags & MGf_MINMATCH)
2986 #ifdef PERL_SAWAMPERSAND
2987 if ( RXp_NPARENS(prog)
2989 || (RXp_EXTFLAGS(prog) & (RXf_EVAL_SEEN|RXf_PMf_KEEPCOPY))
2990 || (dynpm->op_pmflags & PMf_KEEPCOPY)
2994 r_flags |= (REXEC_COPY_STR|REXEC_COPY_SKIP_PRE);
2995 /* in @a =~ /(.)/g, we iterate multiple times, but copy the buffer
2996 * only on the first iteration. Therefore we need to copy $' as well
2997 * as $&, to make the rest of the string available for captures in
2998 * subsequent iterations */
2999 if (! (global && gimme == G_ARRAY))
3000 r_flags |= REXEC_COPY_SKIP_POST;
3002 #ifdef PERL_SAWAMPERSAND
3003 if (dynpm->op_pmflags & PMf_KEEPCOPY)
3004 /* handle KEEPCOPY in pmop but not rx, eg $r=qr/a/; /$r/p */
3005 r_flags &= ~(REXEC_COPY_SKIP_PRE|REXEC_COPY_SKIP_POST);
3012 s = truebase + curpos;
3014 if (!CALLREGEXEC(rx, (char*)s, (char *)strend, (char*)truebase,
3015 had_zerolen, TARG, NULL, r_flags))
3019 if (dynpm->op_pmflags & PMf_ONCE)
3021 SvREADONLY_on(PL_regex_pad[dynpm->op_pmoffset]);
3023 dynpm->op_pmflags |= PMf_USED;
3027 RXp_MATCH_TAINTED_on(prog);
3028 TAINT_IF(RXp_MATCH_TAINTED(prog));
3032 if (global && (gimme != G_ARRAY || (dynpm->op_pmflags & PMf_CONTINUE))) {
3034 mg = sv_magicext_mglob(TARG);
3035 MgBYTEPOS_set(mg, TARG, truebase, RXp_OFFS(prog)[0].end);
3036 if (RXp_ZERO_LEN(prog))
3037 mg->mg_flags |= MGf_MINMATCH;
3039 mg->mg_flags &= ~MGf_MINMATCH;
3042 if ((!RXp_NPARENS(prog) && !global) || gimme != G_ARRAY) {
3043 LEAVE_SCOPE(oldsave);
3047 /* push captures on stack */
3050 const I32 nparens = RXp_NPARENS(prog);
3051 I32 i = (global && !nparens) ? 1 : 0;
3053 SPAGAIN; /* EVAL blocks could move the stack. */
3054 EXTEND(SP, nparens + i);
3055 EXTEND_MORTAL(nparens + i);
3056 for (i = !i; i <= nparens; i++) {
3057 PUSHs(sv_newmortal());
3058 if (LIKELY((RXp_OFFS(prog)[i].start != -1)
3059 && RXp_OFFS(prog)[i].end != -1 ))
3061 const I32 len = RXp_OFFS(prog)[i].end - RXp_OFFS(prog)[i].start;
3062 const char * const s = RXp_OFFS(prog)[i].start + truebase;
3063 if (UNLIKELY( RXp_OFFS(prog)[i].end < 0
3064 || RXp_OFFS(prog)[i].start < 0
3066 || len > strend - s)
3068 DIE(aTHX_ "panic: pp_match start/end pointers, i=%ld, "
3069 "start=%ld, end=%ld, s=%p, strend=%p, len=%" UVuf,
3070 (long) i, (long) RXp_OFFS(prog)[i].start,
3071 (long)RXp_OFFS(prog)[i].end, s, strend, (UV) len);
3072 sv_setpvn(*SP, s, len);
3073 if (DO_UTF8(TARG) && is_utf8_string((U8*)s, len))
3078 curpos = (UV)RXp_OFFS(prog)[0].end;
3079 had_zerolen = RXp_ZERO_LEN(prog);
3080 PUTBACK; /* EVAL blocks may use stack */
3081 r_flags |= REXEC_IGNOREPOS | REXEC_NOT_FIRST;
3084 LEAVE_SCOPE(oldsave);
3087 NOT_REACHED; /* NOTREACHED */
3090 if (global && !(dynpm->op_pmflags & PMf_CONTINUE)) {
3092 mg = mg_find_mglob(TARG);
3096 LEAVE_SCOPE(oldsave);
3097 if (gimme == G_ARRAY)
3103 Perl_do_readline(pTHX)
3105 dSP; dTARGETSTACKED;
3110 IO * const io = GvIO(PL_last_in_gv);
3111 const I32 type = PL_op->op_type;
3112 const U8 gimme = GIMME_V;
3115 const MAGIC *const mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar);
3117 Perl_tied_method(aTHX_ SV_CONST(READLINE), SP, MUTABLE_SV(io), mg, gimme, 0);
3118 if (gimme == G_SCALAR) {
3120 SvSetSV_nosteal(TARG, TOPs);
3130 if (IoFLAGS(io) & IOf_ARGV) {
3131 if (IoFLAGS(io) & IOf_START) {
3133 if (av_tindex(GvAVn(PL_last_in_gv)) < 0) {
3134 IoFLAGS(io) &= ~IOf_START;
3135 do_open6(PL_last_in_gv, "-", 1, NULL, NULL, 0);
3136 SvTAINTED_off(GvSVn(PL_last_in_gv)); /* previous tainting irrelevant */
3137 sv_setpvs(GvSVn(PL_last_in_gv), "-");
3138 SvSETMAGIC(GvSV(PL_last_in_gv));
3143 fp = nextargv(PL_last_in_gv, PL_op->op_flags & OPf_SPECIAL);
3144 if (!fp) { /* Note: fp != IoIFP(io) */
3145 (void)do_close(PL_last_in_gv, FALSE); /* now it does*/
3148 else if (type == OP_GLOB)
3149 fp = Perl_start_glob(aTHX_ POPs, io);
3151 else if (type == OP_GLOB)
3153 else if (IoTYPE(io) == IoTYPE_WRONLY) {
3154 report_wrongway_fh(PL_last_in_gv, '>');
3158 if ((!io || !(IoFLAGS(io) & IOf_START))
3159 && ckWARN(WARN_CLOSED)
3162 report_evil_fh(PL_last_in_gv);
3164 if (gimme == G_SCALAR) {
3165 /* undef TARG, and push that undefined value */
3166 if (type != OP_RCATLINE) {
3174 if (gimme == G_SCALAR) {
3176 if (type == OP_RCATLINE && SvGMAGICAL(sv))
3179 if (type == OP_RCATLINE)
3180 SvPV_force_nomg_nolen(sv);
3184 else if (isGV_with_GP(sv)) {
3185 SvPV_force_nomg_nolen(sv);
3187 SvUPGRADE(sv, SVt_PV);
3188 tmplen = SvLEN(sv); /* remember if already alloced */
3189 if (!tmplen && !SvREADONLY(sv) && !SvIsCOW(sv)) {
3190 /* try short-buffering it. Please update t/op/readline.t
3191 * if you change the growth length.
3196 if (type == OP_RCATLINE && SvOK(sv)) {
3198 SvPV_force_nomg_nolen(sv);
3204 sv = sv_2mortal(newSV(80));
3208 /* This should not be marked tainted if the fp is marked clean */
3209 #define MAYBE_TAINT_LINE(io, sv) \
3210 if (!(IoFLAGS(io) & IOf_UNTAINT)) { \
3215 /* delay EOF state for a snarfed empty file */
3216 #define SNARF_EOF(gimme,rs,io,sv) \
3217 (gimme != G_SCALAR || SvCUR(sv) \
3218 || (IoFLAGS(io) & IOf_NOLINE) || !RsSNARF(rs))
3222 if (!sv_gets(sv, fp, offset)
3224 || SNARF_EOF(gimme, PL_rs, io, sv)
3225 || PerlIO_error(fp)))
3227 PerlIO_clearerr(fp);
3228 if (IoFLAGS(io) & IOf_ARGV) {
3229 fp = nextargv(PL_last_in_gv, PL_op->op_flags & OPf_SPECIAL);
3232 (void)do_close(PL_last_in_gv, FALSE);
3234 else if (type == OP_GLOB) {
3235 if (!do_close(PL_last_in_gv, FALSE)) {
3236 Perl_ck_warner(aTHX_ packWARN(WARN_GLOB),
3237 "glob failed (child exited with status %d%s)",
3238 (int)(STATUS_CURRENT >> 8),
3239 (STATUS_CURRENT & 0x80) ? ", core dumped" : "");
3242 if (gimme == G_SCALAR) {
3243 if (type != OP_RCATLINE) {
3244 SV_CHECK_THINKFIRST_COW_DROP(TARG);
3250 MAYBE_TAINT_LINE(io, sv);
3253 MAYBE_TAINT_LINE(io, sv);
3255 IoFLAGS(io) |= IOf_NOLINE;
3259 if (type == OP_GLOB) {
3263 if (SvCUR(sv) > 0 && SvCUR(PL_rs) > 0) {
3264 char * const tmps = SvEND(sv) - 1;
3265 if (*tmps == *SvPVX_const(PL_rs)) {
3267 SvCUR_set(sv, SvCUR(sv) - 1);
3270 for (t1 = SvPVX_const(sv); *t1; t1++)
3272 if (strchr("*%?", *t1))
3274 if (strchr("$&*(){}[]'\";\\|?<>~`", *t1))
3277 if (*t1 && PerlLIO_lstat(SvPVX_const(sv), &statbuf) < 0) {
3278 (void)POPs; /* Unmatched wildcard? Chuck it... */
3281 } else if (SvUTF8(sv)) { /* OP_READLINE, OP_RCATLINE */
3282 if (ckWARN(WARN_UTF8)) {
3283 const U8 * const s = (const U8*)SvPVX_const(sv) + offset;
3284 const STRLEN len = SvCUR(sv) - offset;
3287 if (!is_utf8_string_loc(s, len, &f))
3288 /* Emulate :encoding(utf8) warning in the same case. */
3289 Perl_warner(aTHX_ packWARN(WARN_UTF8),
3290 "utf8 \"\\x%02X\" does not map to Unicode",
3291 f < (U8*)SvEND(sv) ? *f : 0);
3294 if (gimme == G_ARRAY) {
3295 if (SvLEN(sv) - SvCUR(sv) > 20) {
3296 SvPV_shrink_to_cur(sv);
3298 sv = sv_2mortal(newSV(80));
3301 else if (gimme == G_SCALAR && !tmplen && SvLEN(sv) - SvCUR(sv) > 80) {
3302 /* try to reclaim a bit of scalar space (only on 1st alloc) */
3303 const STRLEN new_len
3304 = SvCUR(sv) < 60 ? 80 : SvCUR(sv)+40; /* allow some slop */
3305 SvPV_renew(sv, new_len);
3316 SV * const keysv = POPs;
3317 HV * const hv = MUTABLE_HV(POPs);
3318 const U32 lval = PL_op->op_flags & OPf_MOD || LVRET;
3319 const U32 defer = PL_op->op_private & OPpLVAL_DEFER;
3321 const bool localizing = PL_op->op_private & OPpLVAL_INTRO;
3322 bool preeminent = TRUE;
3324 if (SvTYPE(hv) != SVt_PVHV)
3331 /* If we can determine whether the element exist,
3332 * Try to preserve the existenceness of a tied hash
3333 * element by using EXISTS and DELETE if possible.
3334 * Fallback to FETCH and STORE otherwise. */
3335 if (SvCANEXISTDELETE(hv))
3336 preeminent = hv_exists_ent(hv, keysv, 0);
3339 he = hv_fetch_ent(hv, keysv, lval && !defer, 0);
3340 svp = he ? &HeVAL(he) : NULL;
3342 if (!svp || !*svp || *svp == &PL_sv_undef) {
3346 DIE(aTHX_ PL_no_helem_sv, SVfARG(keysv));
3348 lv = sv_newmortal();
3349 sv_upgrade(lv, SVt_PVLV);
3351 sv_magic(lv, key2 = newSVsv(keysv), PERL_MAGIC_defelem, NULL, 0);
3352 SvREFCNT_dec_NN(key2); /* sv_magic() increments refcount */
3353 LvTARG(lv) = SvREFCNT_inc_simple_NN(hv);
3359 if (HvNAME_get(hv) && isGV_or_RVCV(*svp))
3360 save_gp(MUTABLE_GV(*svp), !(PL_op->op_flags & OPf_SPECIAL));
3361 else if (preeminent)
3362 save_helem_flags(hv, keysv, svp,
3363 (PL_op->op_flags & OPf_SPECIAL) ? 0 : SAVEf_SETMAGIC);
3365 SAVEHDELETE(hv, keysv);
3367 else if (PL_op->op_private & OPpDEREF) {
3368 PUSHs(vivify_ref(*svp, PL_op->op_private & OPpDEREF));
3372 sv = (svp && *svp ? *svp : &PL_sv_undef);
3373 /* Originally this did a conditional C<sv = sv_mortalcopy(sv)>; this
3374 * was to make C<local $tied{foo} = $tied{foo}> possible.
3375 * However, it seems no longer to be needed for that purpose, and
3376 * introduced a new bug: stuff like C<while ($hash{taintedval} =~ /.../g>
3377 * would loop endlessly since the pos magic is getting set on the
3378 * mortal copy and lost. However, the copy has the effect of
3379 * triggering the get magic, and losing it altogether made things like
3380 * c<$tied{foo};> in void context no longer do get magic, which some
3381 * code relied on. Also, delayed triggering of magic on @+ and friends
3382 * meant the original regex may be out of scope by now. So as a
3383 * compromise, do the get magic here. (The MGf_GSKIP flag will stop it
3384 * being called too many times). */
3385 if (!lval && SvRMAGICAL(hv) && SvGMAGICAL(sv))
3392 /* a stripped-down version of Perl_softref2xv() for use by
3393 * pp_multideref(), which doesn't use PL_op->op_flags */
3396 S_softref2xv_lite(pTHX_ SV *const sv, const char *const what,
3399 if (PL_op->op_private & HINT_STRICT_REFS) {
3401 Perl_die(aTHX_ PL_no_symref_sv, sv,
3402 (SvPOKp(sv) && SvCUR(sv)>32 ? "..." : ""), what);
3404 Perl_die(aTHX_ PL_no_usym, what);
3407 Perl_die(aTHX_ PL_no_usym, what);
3408 return gv_fetchsv_nomg(sv, GV_ADD, type);
3412 /* Handle one or more aggregate derefs and array/hash indexings, e.g.
3413 * $h->{foo} or $a[0]{$key}[$i] or f()->[1]
3415 * op_aux points to an array of unions of UV / IV / SV* / PADOFFSET.
3416 * Each of these either contains a set of actions, or an argument, such as
3417 * an IV to use as an array index, or a lexical var to retrieve.
3418 * Several actions re stored per UV; we keep shifting new actions off the
3419 * one UV, and only reload when it becomes zero.
3424 SV *sv = NULL; /* init to avoid spurious 'may be used uninitialized' */
3425 UNOP_AUX_item *items = cUNOP_AUXx(PL_op)->op_aux;
3426 UV actions = items->uv;
3429 /* this tells find_uninit_var() where we're up to */
3430 PL_multideref_pc = items;
3433 /* there are three main classes of action; the first retrieve
3434 * the initial AV or HV from a variable or the stack; the second
3435 * does the equivalent of an unrolled (/DREFAV, rv2av, aelem),
3436 * the third an unrolled (/DREFHV, rv2hv, helem).
3438 switch (actions & MDEREF_ACTION_MASK) {
3441 actions = (++items)->uv;
3444 case MDEREF_AV_padav_aelem: /* $lex[...] */
3445 sv = PAD_SVl((++items)->pad_offset);
3448 case MDEREF_AV_gvav_aelem: /* $pkg[...] */
3449 sv = UNOP_AUX_item_sv(++items);
3450 assert(isGV_with_GP(sv));
3451 sv = (SV*)GvAVn((GV*)sv);
3454 case MDEREF_AV_pop_rv2av_aelem: /* expr->[...] */
3459 goto do_AV_rv2av_aelem;
3462 case MDEREF_AV_gvsv_vivify_rv2av_aelem: /* $pkg->[...] */
3463 sv = UNOP_AUX_item_sv(++items);
3464 assert(isGV_with_GP(sv));
3465 sv = GvSVn((GV*)sv);
3466 goto do_AV_vivify_rv2av_aelem;
3468 case MDEREF_AV_padsv_vivify_rv2av_aelem: /* $lex->[...] */
3469 sv = PAD_SVl((++items)->pad_offset);
3472 do_AV_vivify_rv2av_aelem:
3473 case MDEREF_AV_vivify_rv2av_aelem: /* vivify, ->[...] */
3474 /* this is the OPpDEREF action normally found at the end of
3475 * ops like aelem, helem, rv2sv */
3476 sv = vivify_ref(sv, OPpDEREF_AV);
3480 /* this is basically a copy of pp_rv2av when it just has the
3483 if (LIKELY(SvROK(sv))) {
3484 if (UNLIKELY(SvAMAGIC(sv))) {
3485 sv = amagic_deref_call(sv, to_av_amg);
3488 if (UNLIKELY(SvTYPE(sv) != SVt_PVAV))
3489 DIE(aTHX_ "Not an ARRAY reference");
3491 else if (SvTYPE(sv) != SVt_PVAV) {
3492 if (!isGV_with_GP(sv))
3493 sv = (SV*)S_softref2xv_lite(aTHX_ sv, "an ARRAY", SVt_PVAV);
3494 sv = MUTABLE_SV(GvAVn((GV*)sv));
3500 /* retrieve the key; this may be either a lexical or package
3501 * var (whose index/ptr is stored as an item) or a signed
3502 * integer constant stored as an item.
3505 IV elem = 0; /* to shut up stupid compiler warnings */
3508 assert(SvTYPE(sv) == SVt_PVAV);
3510 switch (actions & MDEREF_INDEX_MASK) {
3511 case MDEREF_INDEX_none:
3513 case MDEREF_INDEX_const:
3514 elem = (++items)->iv;
3516 case MDEREF_INDEX_padsv:
3517 elemsv = PAD_SVl((++items)->pad_offset);
3519 case MDEREF_INDEX_gvsv:
3520 elemsv = UNOP_AUX_item_sv(++items);
3521 assert(isGV_with_GP(elemsv));
3522 elemsv = GvSVn((GV*)elemsv);
3524 if (UNLIKELY(SvROK(elemsv) && !SvGAMAGIC(elemsv)
3525 && ckWARN(WARN_MISC)))
3526 Perl_warner(aTHX_ packWARN(WARN_MISC),
3527 "Use of reference \"%" SVf "\" as array index",
3529 /* the only time that S_find_uninit_var() needs this
3530 * is to determine which index value triggered the
3531 * undef warning. So just update it here. Note that
3532 * since we don't save and restore this var (e.g. for
3533 * tie or overload execution), its value will be
3534 * meaningless apart from just here */
3535 PL_multideref_pc = items;
3536 elem = SvIV(elemsv);
3541 /* this is basically a copy of pp_aelem with OPpDEREF skipped */
3543 if (!(actions & MDEREF_FLAG_last)) {
3544 SV** svp = av_fetch((AV*)sv, elem, 1);
3545 if (!svp || ! (sv=*svp))
3546 DIE(aTHX_ PL_no_aelem, elem);
3550 if (PL_op->op_private &
3551 (OPpMULTIDEREF_EXISTS|OPpMULTIDEREF_DELETE))
3553 if (PL_op->op_private & OPpMULTIDEREF_EXISTS) {
3554 sv = av_exists((AV*)sv, elem) ? &PL_sv_yes : &PL_sv_no;
3557 I32 discard = (GIMME_V == G_VOID) ? G_DISCARD : 0;
3558 sv = av_delete((AV*)sv, elem, discard);
3566 const U32 lval = PL_op->op_flags & OPf_MOD || LVRET;
3567 const U32 defer = PL_op->op_private & OPpLVAL_DEFER;
3568 const bool localizing = PL_op->op_private & OPpLVAL_INTRO;
3569 bool preeminent = TRUE;
3570 AV *const av = (AV*)sv;
3573 if (UNLIKELY(localizing)) {
3577 /* If we can determine whether the element exist,
3578 * Try to preserve the existenceness of a tied array
3579 * element by using EXISTS and DELETE if possible.
3580 * Fallback to FETCH and STORE otherwise. */
3581 if (SvCANEXISTDELETE(av))
3582 preeminent = av_exists(av, elem);
3585 svp = av_fetch(av, elem, lval && !defer);
3588 if (!svp || !(sv = *svp)) {
3591 DIE(aTHX_ PL_no_aelem, elem);
3592 len = av_tindex(av);
3593 /* Resolve a negative index that falls within
3594 * the array. Leave it negative it if falls
3595 * outside the array. */
3596 if (elem < 0 && len + elem >= 0)
3598 if (elem >= 0 && elem <= len)
3599 /* Falls within the array. */
3600 sv = av_nonelem(av,elem);
3602 /* Falls outside the array. If it is neg-
3603 ative, magic_setdefelem will use the
3604 index for error reporting. */
3605 sv = sv_2mortal(newSVavdefelem(av,elem,1));
3608 if (UNLIKELY(localizing)) {
3610 save_aelem(av, elem, svp);
3611 sv = *svp; /* may have changed */
3614 SAVEADELETE(av, elem);
3619 sv = (svp ? *svp : &PL_sv_undef);
3620 /* see note in pp_helem() */
3621 if (SvRMAGICAL(av) && SvGMAGICAL(sv))
3638 case MDEREF_HV_padhv_helem: /* $lex{...} */
3639 sv = PAD_SVl((++items)->pad_offset);
3642 case MDEREF_HV_gvhv_helem: /* $pkg{...} */
3643 sv = UNOP_AUX_item_sv(++items);
3644 assert(isGV_with_GP(sv));
3645 sv = (SV*)GvHVn((GV*)sv);
3648 case MDEREF_HV_pop_rv2hv_helem: /* expr->{...} */
3653 goto do_HV_rv2hv_helem;
3656 case MDEREF_HV_gvsv_vivify_rv2hv_helem: /* $pkg->{...} */
3657 sv = UNOP_AUX_item_sv(++items);
3658 assert(isGV_with_GP(sv));
3659 sv = GvSVn((GV*)sv);
3660 goto do_HV_vivify_rv2hv_helem;
3662 case MDEREF_HV_padsv_vivify_rv2hv_helem: /* $lex->{...} */
3663 sv = PAD_SVl((++items)->pad_offset);
3666 do_HV_vivify_rv2hv_helem:
3667 case MDEREF_HV_vivify_rv2hv_helem: /* vivify, ->{...} */
3668 /* this is the OPpDEREF action normally found at the end of
3669 * ops like aelem, helem, rv2sv */
3670 sv = vivify_ref(sv, OPpDEREF_HV);
3674 /* this is basically a copy of pp_rv2hv when it just has the
3675 * sKR/1 flags (and pp_rv2hv is aliased to pp_rv2av) */
3678 if (LIKELY(SvROK(sv))) {
3679 if (UNLIKELY(SvAMAGIC(sv))) {
3680 sv = amagic_deref_call(sv, to_hv_amg);
3683 if (UNLIKELY(SvTYPE(sv) != SVt_PVHV))
3684 DIE(aTHX_ "Not a HASH reference");
3686 else if (SvTYPE(sv) != SVt_PVHV) {
3687 if (!isGV_with_GP(sv))
3688 sv = (SV*)S_softref2xv_lite(aTHX_ sv, "a HASH", SVt_PVHV);
3689 sv = MUTABLE_SV(GvHVn((GV*)sv));
3695 /* retrieve the key; this may be either a lexical / package
3696 * var or a string constant, whose index/ptr is stored as an
3699 SV *keysv = NULL; /* to shut up stupid compiler warnings */
3701 assert(SvTYPE(sv) == SVt_PVHV);
3703 switch (actions & MDEREF_INDEX_MASK) {
3704 case MDEREF_INDEX_none:
3707 case MDEREF_INDEX_const:
3708 keysv = UNOP_AUX_item_sv(++items);
3711 case MDEREF_INDEX_padsv:
3712 keysv = PAD_SVl((++items)->pad_offset);
3715 case MDEREF_INDEX_gvsv:
3716 keysv = UNOP_AUX_item_sv(++items);
3717 keysv = GvSVn((GV*)keysv);
3721 /* see comment above about setting this var */
3722 PL_multideref_pc = items;
3725 /* ensure that candidate CONSTs have been HEKified */
3726 assert( ((actions & MDEREF_INDEX_MASK) != MDEREF_INDEX_const)
3727 || SvTYPE(keysv) >= SVt_PVMG
3730 || SvIsCOW_shared_hash(keysv));
3732 /* this is basically a copy of pp_helem with OPpDEREF skipped */
3734 if (!(actions & MDEREF_FLAG_last)) {
3735 HE *he = hv_fetch_ent((HV*)sv, keysv, 1, 0);
3736 if (!he || !(sv=HeVAL(he)) || sv == &PL_sv_undef)
3737 DIE(aTHX_ PL_no_helem_sv, SVfARG(keysv));
3741 if (PL_op->op_private &
3742 (OPpMULTIDEREF_EXISTS|OPpMULTIDEREF_DELETE))
3744 if (PL_op->op_private & OPpMULTIDEREF_EXISTS) {
3745 sv = hv_exists_ent((HV*)sv, keysv, 0)
3746 ? &PL_sv_yes : &PL_sv_no;
3749 I32 discard = (GIMME_V == G_VOID) ? G_DISCARD : 0;
3750 sv = hv_delete_ent((HV*)sv, keysv, discard, 0);
3758 const U32 lval = PL_op->op_flags & OPf_MOD || LVRET;
3759 const U32 defer = PL_op->op_private & OPpLVAL_DEFER;
3760 const bool localizing = PL_op->op_private & OPpLVAL_INTRO;
3761 bool preeminent = TRUE;
3763 HV * const hv = (HV*)sv;
3766 if (UNLIKELY(localizing)) {
3770 /* If we can determine whether the element exist,
3771 * Try to preserve the existenceness of a tied hash
3772 * element by using EXISTS and DELETE if possible.
3773 * Fallback to FETCH and STORE otherwise. */
3774 if (SvCANEXISTDELETE(hv))
3775 preeminent = hv_exists_ent(hv, keysv, 0);
3778 he = hv_fetch_ent(hv, keysv, lval && !defer, 0);
3779 svp = he ? &HeVAL(he) : NULL;
3783 if (!svp || !(sv = *svp) || sv == &PL_sv_undef) {
3787 DIE(aTHX_ PL_no_helem_sv, SVfARG(keysv));
3788 lv = sv_newmortal();
3789 sv_upgrade(lv, SVt_PVLV);
3791 sv_magic(lv, key2 = newSVsv(keysv),
3792 PERL_MAGIC_defelem, NULL, 0);
3793 /* sv_magic() increments refcount */
3794 SvREFCNT_dec_NN(key2);
3795 LvTARG(lv) = SvREFCNT_inc_simple_NN(hv);
3801 if (HvNAME_get(hv) && isGV_or_RVCV(sv))
3802 save_gp(MUTABLE_GV(sv),
3803 !(PL_op->op_flags & OPf_SPECIAL));
3804 else if (preeminent) {
3805 save_helem_flags(hv, keysv, svp,
3806 (PL_op->op_flags & OPf_SPECIAL)
3807 ? 0 : SAVEf_SETMAGIC);
3808 sv = *svp; /* may have changed */
3811 SAVEHDELETE(hv, keysv);
3816 sv = (svp && *svp ? *svp : &PL_sv_undef);
3817 /* see note in pp_helem() */
3818 if (SvRMAGICAL(hv) && SvGMAGICAL(sv))
3827 actions >>= MDEREF_SHIFT;
3845 itersvp = CxITERVAR(cx);
3848 switch (CxTYPE(cx)) {
3850 case CXt_LOOP_LAZYSV: /* string increment */
3852 SV* cur = cx->blk_loop.state_u.lazysv.cur;
3853 SV *end = cx->blk_loop.state_u.lazysv.end;
3854 /* If the maximum is !SvOK(), pp_enteriter substitutes PL_sv_no.
3855 It has SvPVX of "" and SvCUR of 0, which is what we want. */
3857 const char *max = SvPV_const(end, maxlen);
3858 if (DO_UTF8(end) && IN_UNI_8_BIT)
3859 maxlen = sv_len_utf8_nomg(end);
3860 if (UNLIKELY(SvNIOK(cur) || SvCUR(cur) > maxlen))
3864 /* NB: on the first iteration, oldsv will have a ref count of at
3865 * least 2 (one extra from blk_loop.itersave), so the GV or pad
3866 * slot will get localised; on subsequent iterations the RC==1
3867 * optimisation may kick in and the SV will be reused. */
3868 if (oldsv && LIKELY(SvREFCNT(oldsv) == 1 && !SvMAGICAL(oldsv))) {
3869 /* safe to reuse old SV */
3870 sv_setsv(oldsv, cur);
3874 /* we need a fresh SV every time so that loop body sees a
3875 * completely new SV for closures/references to work as
3877 *itersvp = newSVsv(cur);
3878 SvREFCNT_dec(oldsv);
3880 if (strEQ(SvPVX_const(cur), max))
3881 sv_setiv(cur, 0); /* terminate next time */
3887 case CXt_LOOP_LAZYIV: /* integer increment */
3889 IV cur = cx->blk_loop.state_u.lazyiv.cur;
3890 if (UNLIKELY(cur > cx->blk_loop.state_u.lazyiv.end))
3894 /* see NB comment above */
3895 if (oldsv && LIKELY(SvREFCNT(oldsv) == 1 && !SvMAGICAL(oldsv))) {
3896 /* safe to reuse old SV */
3898 if ( (SvFLAGS(oldsv) & (SVTYPEMASK|SVf_THINKFIRST|SVf_IVisUV))
3901 /* Cheap SvIOK_only().
3902 * Assert that flags which SvIOK_only() would test or
3903 * clear can't be set, because we're SVt_IV */
3904 assert(!(SvFLAGS(oldsv) &
3905 (SVf_OOK|SVf_UTF8|(SVf_OK & ~(SVf_IOK|SVp_IOK)))));
3906 SvFLAGS(oldsv) |= (SVf_IOK|SVp_IOK);
3907 /* SvIV_set() where sv_any points to head */
3908 oldsv->sv_u.svu_iv = cur;
3912 sv_setiv(oldsv, cur);
3916 /* we need a fresh SV every time so that loop body sees a
3917 * completely new SV for closures/references to work as they
3919 *itersvp = newSViv(cur);
3920 SvREFCNT_dec(oldsv);
3923 if (UNLIKELY(cur == IV_MAX)) {
3924 /* Handle end of range at IV_MAX */
3925 cx->blk_loop.state_u.lazyiv.end = IV_MIN;
3927 ++cx->blk_loop.state_u.lazyiv.cur;
3931 case CXt_LOOP_LIST: /* for (1,2,3) */
3933 assert(OPpITER_REVERSED == 2); /* so inc becomes -1 or 1 */
3934 inc = (IV)1 - (IV)(PL_op->op_private & OPpITER_REVERSED);
3935 ix = (cx->blk_loop.state_u.stack.ix += inc);
3936 if (UNLIKELY(inc > 0
3937 ? ix > cx->blk_oldsp
3938 : ix <= cx->blk_loop.state_u.stack.basesp)
3942 sv = PL_stack_base[ix];
3944 goto loop_ary_common;
3946 case CXt_LOOP_ARY: /* for (@ary) */
3948 av = cx->blk_loop.state_u.ary.ary;
3949 inc = (IV)1 - (IV)(PL_op->op_private & OPpITER_REVERSED);
3950 ix = (cx->blk_loop.state_u.ary.ix += inc);
3951 if (UNLIKELY(inc > 0
3957 if (UNLIKELY(SvRMAGICAL(av))) {
3958 SV * const * const svp = av_fetch(av, ix, FALSE);
3959 sv = svp ? *svp : NULL;
3962 sv = AvARRAY(av)[ix];
3967 if (UNLIKELY(cx->cx_type & CXp_FOR_LVREF)) {
3968 SvSetMagicSV(*itersvp, sv);
3973 if (UNLIKELY(SvIS_FREED(sv))) {
3975 Perl_croak(aTHX_ "Use of freed value in iteration");
3982 SvREFCNT_inc_simple_void_NN(sv);
3986 sv = newSVavdefelem(av, ix, 0);
3993 SvREFCNT_dec(oldsv);
3997 DIE(aTHX_ "panic: pp_iter, type=%u", CxTYPE(cx));
4000 /* Try to bypass pushing &PL_sv_yes and calling pp_and(); instead
4001 * jump straight to the AND op's op_other */
4002 assert(PL_op->op_next->op_type == OP_AND);
4003 if (PL_op->op_next->op_ppaddr == Perl_pp_and) {
4004 return cLOGOPx(PL_op->op_next)->op_other;
4007 /* An XS module has replaced the op_ppaddr, so fall back to the slow,
4009 /* pp_enteriter should have pre-extended the stack */
4010 EXTEND_SKIP(PL_stack_sp, 1);
4011 *++PL_stack_sp = &PL_sv_yes;
4012 return PL_op->op_next;
4016 /* Try to bypass pushing &PL_sv_no and calling pp_and(); instead
4017 * jump straight to the AND op's op_next */
4018 assert(PL_op->op_next->op_type == OP_AND);
4019 /* pp_enteriter should have pre-extended the stack */
4020 EXTEND_SKIP(PL_stack_sp, 1);
4021 /* we only need this for the rare case where the OP_AND isn't
4022 * in void context, e.g. $x = do { for (..) {...} };
4023 * (or for when an XS module has replaced the op_ppaddr)
4024 * but it's cheaper to just push it rather than testing first
4026 *++PL_stack_sp = &PL_sv_no;
4027 if (PL_op->op_next->op_ppaddr == Perl_pp_and) {
4028 return PL_op->op_next->op_next;
4031 /* An XS module has replaced the op_ppaddr, so fall back to the slow,
4033 return PL_op->op_next;
4039 A description of how taint works in pattern matching and substitution.
4041 This is all conditional on NO_TAINT_SUPPORT not being defined. Under
4042 NO_TAINT_SUPPORT, taint-related operations should become no-ops.
4044 While the pattern is being assembled/concatenated and then compiled,
4045 PL_tainted will get set (via TAINT_set) if any component of the pattern
4046 is tainted, e.g. /.*$tainted/. At the end of pattern compilation,
4047 the RXf_TAINTED flag is set on the pattern if PL_tainted is set (via
4048 TAINT_get). It will also be set if any component of the pattern matches
4049 based on locale-dependent behavior.
4051 When the pattern is copied, e.g. $r = qr/..../, the SV holding the ref to
4052 the pattern is marked as tainted. This means that subsequent usage, such
4053 as /x$r/, will set PL_tainted using TAINT_set, and thus RXf_TAINTED,
4054 on the new pattern too.
4056 RXf_TAINTED_SEEN is used post-execution by the get magic code
4057 of $1 et al to indicate whether the returned value should be tainted.
4058 It is the responsibility of the caller of the pattern (i.e. pp_match,
4059 pp_subst etc) to set this flag for any other circumstances where $1 needs
4062 The taint behaviour of pp_subst (and pp_substcont) is quite complex.
4064 There are three possible sources of taint
4066 * the pattern (both compile- and run-time, RXf_TAINTED / RXf_TAINTED_SEEN)
4067 * the replacement string (or expression under /e)
4069 There are four destinations of taint and they are affected by the sources
4070 according to the rules below:
4072 * the return value (not including /r):
4073 tainted by the source string and pattern, but only for the
4074 number-of-iterations case; boolean returns aren't tainted;
4075 * the modified string (or modified copy under /r):
4076 tainted by the source string, pattern, and replacement strings;
4078 tainted by the pattern, and under 'use re "taint"', by the source
4080 * PL_taint - i.e. whether subsequent code (e.g. in a /e block) is tainted:
4081 should always be unset before executing subsequent code.
4083 The overall action of pp_subst is:
4085 * at the start, set bits in rxtainted indicating the taint status of
4086 the various sources.
4088 * After each pattern execution, update the SUBST_TAINT_PAT bit in
4089 rxtainted if RXf_TAINTED_SEEN has been set, to indicate that the
4090 pattern has subsequently become tainted via locale ops.
4092 * If control is being passed to pp_substcont to execute a /e block,
4093 save rxtainted in the CXt_SUBST block, for future use by
4096 * Whenever control is being returned to perl code (either by falling
4097 off the "end" of pp_subst/pp_substcont, or by entering a /e block),
4098 use the flag bits in rxtainted to make all the appropriate types of
4099 destination taint visible; e.g. set RXf_TAINTED_SEEN so that $1
4100 et al will appear tainted.
4102 pp_match is just a simpler version of the above.
4118 U8 rxtainted = 0; /* holds various SUBST_TAINT_* flag bits.
4119 See "how taint works" above */
4122 REGEXP *rx = PM_GETRE(pm);
4123 regexp *prog = ReANY(rx);
4125 int force_on_match = 0;
4126 const I32 oldsave = PL_savestack_ix;
4128 bool doutf8 = FALSE; /* whether replacement is in utf8 */
4133 /* known replacement string? */
4134 SV *dstr = (pm->op_pmflags & PMf_CONST) ? POPs : NULL;
4138 if (PL_op->op_flags & OPf_STACKED)
4149 SvGETMAGIC(TARG); /* must come before cow check */
4151 /* note that a string might get converted to COW during matching */
4152 was_cow = cBOOL(SvIsCOW(TARG));
4154 if (!(rpm->op_pmflags & PMf_NONDESTRUCT)) {
4155 #ifndef PERL_ANY_COW
4157 sv_force_normal_flags(TARG,0);
4159 if ((SvREADONLY(TARG)
4160 || ( ((SvTYPE(TARG) == SVt_PVGV && isGV_with_GP(TARG))
4161 || SvTYPE(TARG) > SVt_PVLV)
4162 && !(SvTYPE(TARG) == SVt_PVGV && SvFAKE(TARG)))))
4163 Perl_croak_no_modify();
4167 orig = SvPV_nomg(TARG, len);
4168 /* note we don't (yet) force the var into being a string; if we fail
4169 * to match, we leave as-is; on successful match however, we *will*
4170 * coerce into a string, then repeat the match */
4171 if (!SvPOKp(TARG) || SvTYPE(TARG) == SVt_PVGV || SvVOK(TARG))
4174 /* only replace once? */
4175 once = !(rpm->op_pmflags & PMf_GLOBAL);
4177 /* See "how taint works" above */
4180 (SvTAINTED(TARG) ? SUBST_TAINT_STR : 0)
4181 | (RXp_ISTAINTED(prog) ? SUBST_TAINT_PAT : 0)
4182 | ((pm->op_pmflags & PMf_RETAINT) ? SUBST_TAINT_RETAINT : 0)
4183 | (( (once && !(rpm->op_pmflags & PMf_NONDESTRUCT))
4184 || (PL_op->op_private & OPpTRUEBOOL)) ? SUBST_TAINT_BOOLRET : 0));
4190 DIE(aTHX_ "panic: pp_subst, pm=%p, orig=%p", pm, orig);
4192 strend = orig + len;
4193 slen = DO_UTF8(TARG) ? utf8_length((U8*)orig, (U8*)strend) : len;
4194 maxiters = 2 * slen + 10; /* We can match twice at each
4195 position, once with zero-length,
4196 second time with non-zero. */
4198 /* handle the empty pattern */
4199 if (!RX_PRELEN(rx) && PL_curpm && !prog->mother_re) {
4200 if (PL_curpm == PL_reg_curpm) {
4201 if (PL_curpm_under) {
4202 if (PL_curpm_under == PL_reg_curpm) {
4203 Perl_croak(aTHX_ "Infinite recursion via empty pattern");
4205 pm = PL_curpm_under;
4215 #ifdef PERL_SAWAMPERSAND
4216 r_flags = ( RXp_NPARENS(prog)
4218 || (RXp_EXTFLAGS(prog) & (RXf_EVAL_SEEN|RXf_PMf_KEEPCOPY))
4219 || (rpm->op_pmflags & PMf_KEEPCOPY)
4224 r_flags = REXEC_COPY_STR;
4227 if (!CALLREGEXEC(rx, orig, strend, orig, 0, TARG, NULL, r_flags))
4230 PUSHs(rpm->op_pmflags & PMf_NONDESTRUCT ? TARG : &PL_sv_no);
4231 LEAVE_SCOPE(oldsave);
4236 /* known replacement string? */
4238 /* replacement needing upgrading? */
4239 if (DO_UTF8(TARG) && !doutf8) {
4240 nsv = sv_newmortal();
4242 sv_utf8_upgrade(nsv);
4243 c = SvPV_const(nsv, clen);
4247 c = SvPV_const(dstr, clen);
4248 doutf8 = DO_UTF8(dstr);
4251 if (UNLIKELY(TAINT_get))
4252 rxtainted |= SUBST_TAINT_REPL;
4259 /* can do inplace substitution? */
4264 && (I32)clen <= RXp_MINLENRET(prog)
4266 || !(r_flags & REXEC_COPY_STR)
4267 || (!SvGMAGICAL(dstr) && !(RXp_EXTFLAGS(prog) & RXf_EVAL_SEEN))
4269 && !(RXp_EXTFLAGS(prog) & RXf_NO_INPLACE_SUBST)
4270 && (!doutf8 || SvUTF8(TARG))
4271 && !(rpm->op_pmflags & PMf_NONDESTRUCT))
4275 /* string might have got converted to COW since we set was_cow */
4276 if (SvIsCOW(TARG)) {
4277 if (!force_on_match)
4279 assert(SvVOK(TARG));
4282 if (force_on_match) {
4283 /* redo the first match, this time with the orig var
4284 * forced into being a string */
4286 orig = SvPV_force_nomg(TARG, len);
4292 if (RXp_MATCH_TAINTED(prog)) /* run time pattern taint, eg locale */
4293 rxtainted |= SUBST_TAINT_PAT;
4294 m = orig + RXp_OFFS(prog)[0].start;
4295 d = orig + RXp_OFFS(prog)[0].end;
4297 if (m - s > strend - d) { /* faster to shorten from end */
4300 Copy(c, m, clen, char);
4305 Move(d, m, i, char);
4309 SvCUR_set(TARG, m - s);
4311 else { /* faster from front */
4315 Move(s, d - i, i, char);
4318 Copy(c, d, clen, char);
4325 d = s = RXp_OFFS(prog)[0].start + orig;
4328 if (UNLIKELY(iters++ > maxiters))
4329 DIE(aTHX_ "Substitution loop");
4330 /* run time pattern taint, eg locale */
4331 if (UNLIKELY(RXp_MATCH_TAINTED(prog)))
4332 rxtainted |= SUBST_TAINT_PAT;
4333 m = RXp_OFFS(prog)[0].start + orig;
4336 Move(s, d, i, char);
4340 Copy(c, d, clen, char);
4343 s = RXp_OFFS(prog)[0].end + orig;
4344 } while (CALLREGEXEC(rx, s, strend, orig,
4345 s == m, /* don't match same null twice */
4347 REXEC_NOT_FIRST|REXEC_IGNOREPOS|REXEC_FAIL_ON_UNDERFLOW));
4350 SvCUR_set(TARG, d - SvPVX_const(TARG) + i);
4351 Move(s, d, i+1, char); /* include the NUL */
4355 if (PL_op->op_private & OPpTRUEBOOL)
4365 if (force_on_match) {
4366 /* redo the first match, this time with the orig var
4367 * forced into being a string */
4369 if (rpm->op_pmflags & PMf_NONDESTRUCT) {
4370 /* I feel that it should be possible to avoid this mortal copy
4371 given that the code below copies into a new destination.
4372 However, I suspect it isn't worth the complexity of
4373 unravelling the C<goto force_it> for the small number of
4374 cases where it would be viable to drop into the copy code. */
4375 TARG = sv_2mortal(newSVsv(TARG));
4377 orig = SvPV_force_nomg(TARG, len);
4383 if (RXp_MATCH_TAINTED(prog)) /* run time pattern taint, eg locale */
4384 rxtainted |= SUBST_TAINT_PAT;
4386 s = RXp_OFFS(prog)[0].start + orig;
4387 dstr = newSVpvn_flags(orig, s-orig,
4388 SVs_TEMP | (DO_UTF8(TARG) ? SVf_UTF8 : 0));
4393 /* note that a whole bunch of local vars are saved here for
4394 * use by pp_substcont: here's a list of them in case you're
4395 * searching for places in this sub that uses a particular var:
4396 * iters maxiters r_flags oldsave rxtainted orig dstr targ
4397 * s m strend rx once */
4399 RETURNOP(cPMOP->op_pmreplrootu.op_pmreplroot);
4403 if (UNLIKELY(iters++ > maxiters))
4404 DIE(aTHX_ "Substitution loop");
4405 if (UNLIKELY(RXp_MATCH_TAINTED(prog)))
4406 rxtainted |= SUBST_TAINT_PAT;
4407 if (RXp_MATCH_COPIED(prog) && RXp_SUBBEG(prog) != orig) {
4409 char *old_orig = orig;
4410 assert(RXp_SUBOFFSET(prog) == 0);
4412 orig = RXp_SUBBEG(prog);
4413 s = orig + (old_s - old_orig);
4414 strend = s + (strend - old_s);
4416 m = RXp_OFFS(prog)[0].start + orig;
4417 sv_catpvn_nomg_maybeutf8(dstr, s, m - s, DO_UTF8(TARG));
4418 s = RXp_OFFS(prog)[0].end + orig;
4420 /* replacement already stringified */
4422 sv_catpvn_nomg_maybeutf8(dstr, c, clen, doutf8);
4426 sv_catsv(dstr, repl);
4430 } while (CALLREGEXEC(rx, s, strend, orig,
4431 s == m, /* Yields minend of 0 or 1 */
4433 REXEC_NOT_FIRST|REXEC_IGNOREPOS|REXEC_FAIL_ON_UNDERFLOW));
4434 assert(strend >= s);
4435 sv_catpvn_nomg_maybeutf8(dstr, s, strend - s, DO_UTF8(TARG));
4437 if (rpm->op_pmflags & PMf_NONDESTRUCT) {
4438 /* From here on down we're using the copy, and leaving the original
4445 /* The match may make the string COW. If so, brilliant, because
4446 that's just saved us one malloc, copy and free - the regexp has
4447 donated the old buffer, and we malloc an entirely new one, rather
4448 than the regexp malloc()ing a buffer and copying our original,
4449 only for us to throw it away here during the substitution. */
4450 if (SvIsCOW(TARG)) {
4451 sv_force_normal_flags(TARG, SV_COW_DROP_PV);
4457 SvPV_set(TARG, SvPVX(dstr));
4458 SvCUR_set(TARG, SvCUR(dstr));
4459 SvLEN_set(TARG, SvLEN(dstr));
4460 SvFLAGS(TARG) |= SvUTF8(dstr);
4461 SvPV_set(dstr, NULL);
4464 if (PL_op->op_private & OPpTRUEBOOL)
4471 if (!(rpm->op_pmflags & PMf_NONDESTRUCT)) {
4472 (void)SvPOK_only_UTF8(TARG);
4475 /* See "how taint works" above */
4477 if ((rxtainted & SUBST_TAINT_PAT) ||
4478 ((rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_RETAINT)) ==
4479 (SUBST_TAINT_STR|SUBST_TAINT_RETAINT))
4481 (RXp_MATCH_TAINTED_on(prog)); /* taint $1 et al */
4483 if (!(rxtainted & SUBST_TAINT_BOOLRET)
4484 && (rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_PAT))
4486 SvTAINTED_on(TOPs); /* taint return value */
4488 SvTAINTED_off(TOPs); /* may have got tainted earlier */
4490 /* needed for mg_set below */
4492 cBOOL(rxtainted & (SUBST_TAINT_STR|SUBST_TAINT_PAT|SUBST_TAINT_REPL))
4496 SvSETMAGIC(TARG); /* PL_tainted must be correctly set for this mg_set */
4498 LEAVE_SCOPE(oldsave);
4508 PL_stack_base[PL_markstack_ptr[-1]++] = PL_stack_base[*PL_markstack_ptr];
4509 ++*PL_markstack_ptr;
4511 LEAVE_with_name("grep_item"); /* exit inner scope */
4514 if (UNLIKELY(PL_stack_base + *PL_markstack_ptr > SP)) {
4516 const U8 gimme = GIMME_V;
4518 LEAVE_with_name("grep"); /* exit outer scope */
4519 (void)POPMARK; /* pop src */
4520 items = --*PL_markstack_ptr - PL_markstack_ptr[-1];
4521 (void)POPMARK; /* pop dst */
4522 SP = PL_stack_base + POPMARK; /* pop original mark */
4523 if (gimme == G_SCALAR) {
4524 if (PL_op->op_private & OPpTRUEBOOL)
4525 PUSHs(items ? &PL_sv_yes : &PL_sv_zero);
4531 else if (gimme == G_ARRAY)
4538 ENTER_with_name("grep_item"); /* enter inner scope */
4541 src = PL_stack_base[TOPMARK];
4542 if (SvPADTMP(src)) {
4543 src = PL_stack_base[TOPMARK] = sv_mortalcopy(src);
4549 RETURNOP(cLOGOP->op_other);
4553 /* leave_adjust_stacks():
4555 * Process a scope's return args (in the range from_sp+1 .. PL_stack_sp),
4556 * positioning them at to_sp+1 onwards, and do the equivalent of a
4557 * FREEMPS and TAINT_NOT.
4559 * Not intended to be called in void context.
4561 * When leaving a sub, eval, do{} or other scope, the things that need
4562 * doing to process the return args are:
4563 * * in scalar context, only return the last arg (or PL_sv_undef if none);
4564 * * for the types of return that return copies of their args (such
4565 * as rvalue sub return), make a mortal copy of every return arg,
4566 * except where we can optimise the copy away without it being
4567 * semantically visible;
4568 * * make sure that the arg isn't prematurely freed; in the case of an
4569 * arg not copied, this may involve mortalising it. For example, in
4570 * C<sub f { my $x = ...; $x }>, $x would be freed when we do
4571 * CX_LEAVE_SCOPE(cx) unless it's protected or copied.
4573 * What condition to use when deciding whether to pass the arg through
4574 * or make a copy, is determined by the 'pass' arg; its valid values are:
4575 * 0: rvalue sub/eval exit
4576 * 1: other rvalue scope exit
4577 * 2: :lvalue sub exit in rvalue context
4578 * 3: :lvalue sub exit in lvalue context and other lvalue scope exits
4580 * There is a big issue with doing a FREETMPS. We would like to free any
4581 * temps created by the last statement which the sub executed, rather than
4582 * leaving them for the caller. In a situation where a sub call isn't
4583 * soon followed by a nextstate (e.g. nested recursive calls, a la
4584 * fibonacci()), temps can accumulate, causing memory and performance
4587 * On the other hand, we don't want to free any TEMPs which are keeping
4588 * alive any return args that we skipped copying; nor do we wish to undo
4589 * any mortalising done here.
4591 * The solution is to split the temps stack frame into two, with a cut
4592 * point delineating the two halves. We arrange that by the end of this
4593 * function, all the temps stack frame entries we wish to keep are in the
4594 * range PL_tmps_floor+1.. tmps_base-1, while the ones to free now are in
4595 * the range tmps_base .. PL_tmps_ix. During the course of this
4596 * function, tmps_base starts off as PL_tmps_floor+1, then increases
4597 * whenever we find or create a temp that we know should be kept. In
4598 * general the stuff above tmps_base is undecided until we reach the end,
4599 * and we may need a sort stage for that.
4601 * To determine whether a TEMP is keeping a return arg alive, every
4602 * arg that is kept rather than copied and which has the SvTEMP flag
4603 * set, has the flag temporarily unset, to mark it. At the end we scan
4604 * the temps stack frame above the cut for entries without SvTEMP and
4605 * keep them, while turning SvTEMP on again. Note that if we die before
4606 * the SvTEMPs flags are set again, its safe: at worst, subsequent use of
4607 * those SVs may be slightly less efficient.
4609 * In practice various optimisations for some common cases mean we can
4610 * avoid most of the scanning and swapping about with the temps stack.
4614 Perl_leave_adjust_stacks(pTHX_ SV **from_sp, SV **to_sp, U8 gimme, int pass)
4618 SSize_t tmps_base; /* lowest index into tmps stack that needs freeing now */
4621 PERL_ARGS_ASSERT_LEAVE_ADJUST_STACKS;
4625 if (gimme == G_ARRAY) {
4626 nargs = SP - from_sp;
4630 assert(gimme == G_SCALAR);
4631 if (UNLIKELY(from_sp >= SP)) {
4632 /* no return args */
4633 assert(from_sp == SP);
4635 *++SP = &PL_sv_undef;
4645 /* common code for G_SCALAR and G_ARRAY */
4647 tmps_base = PL_tmps_floor + 1;
4651 /* pointer version of tmps_base. Not safe across temp stack
4655 EXTEND_MORTAL(nargs); /* one big extend for worst-case scenario */
4656 tmps_basep = PL_tmps_stack + tmps_base;
4658 /* process each return arg */
4661 SV *sv = *from_sp++;
4663 assert(PL_tmps_ix + nargs < PL_tmps_max);
4665 /* PADTMPs with container set magic shouldn't appear in the
4666 * wild. This assert is more important for pp_leavesublv(),
4667 * but by testing for it here, we're more likely to catch
4668 * bad cases (what with :lvalue subs not being widely
4669 * deployed). The two issues are that for something like
4670 * sub :lvalue { $tied{foo} }
4672 * sub :lvalue { substr($foo,1,2) }
4673 * pp_leavesublv() will croak if the sub returns a PADTMP,
4674 * and currently functions like pp_substr() return a mortal
4675 * rather than using their PADTMP when returning a PVLV.
4676 * This is because the PVLV will hold a ref to $foo,
4677 * so $foo would get delayed in being freed while
4678 * the PADTMP SV remained in the PAD.
4679 * So if this assert fails it means either:
4680 * 1) there is pp code similar to pp_substr that is
4681 * returning a PADTMP instead of a mortal, and probably
4683 * 2) pp_leavesublv is making unwarranted assumptions
4684 * about always croaking on a PADTMP
4686 if (SvPADTMP(sv) && SvSMAGICAL(sv)) {
4688 for (mg = SvMAGIC(sv); mg; mg = mg->mg_moremagic) {
4689 assert(PERL_MAGIC_TYPE_IS_VALUE_MAGIC(mg->mg_type));
4695 pass == 0 ? (SvTEMP(sv) && !SvMAGICAL(sv) && SvREFCNT(sv) == 1)
4696 : pass == 1 ? ((SvTEMP(sv) || SvPADTMP(sv)) && !SvMAGICAL(sv) && SvREFCNT(sv) == 1)
4697 : pass == 2 ? (!SvPADTMP(sv))
4700 /* pass through: skip copy for logic or optimisation
4701 * reasons; instead mortalise it, except that ... */
4705 /* ... since this SV is an SvTEMP , we don't need to
4706 * re-mortalise it; instead we just need to ensure
4707 * that its existing entry in the temps stack frame
4708 * ends up below the cut and so avoids being freed
4709 * this time round. We mark it as needing to be kept
4710 * by temporarily unsetting SvTEMP; then at the end,
4711 * we shuffle any !SvTEMP entries on the tmps stack
4712 * back below the cut.
4713 * However, there's a significant chance that there's
4714 * a 1:1 correspondence between the first few (or all)
4715 * elements in the return args stack frame and those
4716 * in the temps stack frame; e,g.:
4717 * sub f { ....; map {...} .... },
4718 * or if we're exiting multiple scopes and one of the
4719 * inner scopes has already made mortal copies of each
4722 * If so, this arg sv will correspond to the next item
4723 * on the tmps stack above the cut, and so can be kept
4724 * merely by moving the cut boundary up one, rather
4725 * than messing with SvTEMP. If all args are 1:1 then
4726 * we can avoid the sorting stage below completely.
4728 * If there are no items above the cut on the tmps
4729 * stack, then the SvTEMP must comne from an item
4730 * below the cut, so there's nothing to do.
4732 if (tmps_basep <= &PL_tmps_stack[PL_tmps_ix]) {
4733 if (sv == *tmps_basep)
4739 else if (!SvPADTMP(sv)) {
4740 /* mortalise arg to avoid it being freed during save
4741 * stack unwinding. Pad tmps don't need mortalising as
4742 * they're never freed. This is the equivalent of
4743 * sv_2mortal(SvREFCNT_inc(sv)), except that:
4744 * * it assumes that the temps stack has already been
4746 * * it puts the new item at the cut rather than at
4747 * ++PL_tmps_ix, moving the previous occupant there
4750 if (!SvIMMORTAL(sv)) {
4751 SvREFCNT_inc_simple_void_NN(sv);
4753 /* Note that if there's nothing above the cut,
4754 * this copies the garbage one slot above
4755 * PL_tmps_ix onto itself. This is harmless (the
4756 * stack's already been extended), but might in
4757 * theory trigger warnings from tools like ASan
4759 PL_tmps_stack[++PL_tmps_ix] = *tmps_basep;
4765 /* Make a mortal copy of the SV.
4766 * The following code is the equivalent of sv_mortalcopy()
4768 * * it assumes the temps stack has already been extended;
4769 * * it optimises the copying for some simple SV types;
4770 * * it puts the new item at the cut rather than at
4771 * ++PL_tmps_ix, moving the previous occupant there
4774 SV *newsv = newSV(0);
4776 PL_tmps_stack[++PL_tmps_ix] = *tmps_basep;
4777 /* put it on the tmps stack early so it gets freed if we die */
4778 *tmps_basep++ = newsv;
4781 if (SvTYPE(sv) <= SVt_IV) {
4782 /* arg must be one of undef, IV/UV, or RV: skip
4783 * sv_setsv_flags() and do the copy directly */
4785 U32 srcflags = SvFLAGS(sv);
4787 assert(!SvGMAGICAL(sv));
4788 if (srcflags & (SVf_IOK|SVf_ROK)) {
4789 SET_SVANY_FOR_BODYLESS_IV(newsv);
4791 if (srcflags & SVf_ROK) {
4792 newsv->sv_u.svu_rv = SvREFCNT_inc(SvRV(sv));
4793 /* SV type plus flags */
4794 dstflags = (SVt_IV|SVf_ROK|SVs_TEMP);
4797 /* both src and dst are <= SVt_IV, so sv_any
4798 * points to the head; so access the heads
4799 * directly rather than going via sv_any.
4801 assert( &(sv->sv_u.svu_iv)
4802 == &(((XPVIV*) SvANY(sv))->xiv_iv));
4803 assert( &(newsv->sv_u.svu_iv)
4804 == &(((XPVIV*) SvANY(newsv))->xiv_iv));
4805 newsv->sv_u.svu_iv = sv->sv_u.svu_iv;
4806 /* SV type plus flags */
4807 dstflags = (SVt_IV|SVf_IOK|SVp_IOK|SVs_TEMP
4808 |(srcflags & SVf_IVisUV));
4812 assert(!(srcflags & SVf_OK));
4813 dstflags = (SVt_NULL|SVs_TEMP); /* SV type plus flags */
4815 SvFLAGS(newsv) = dstflags;
4819 /* do the full sv_setsv() */
4823 old_base = tmps_basep - PL_tmps_stack;
4825 sv_setsv_flags(newsv, sv, SV_DO_COW_SVSETSV);
4826 /* the mg_get or sv_setsv might have created new temps
4827 * or realloced the tmps stack; regrow and reload */
4828 EXTEND_MORTAL(nargs);
4829 tmps_basep = PL_tmps_stack + old_base;
4830 TAINT_NOT; /* Each item is independent */
4836 /* If there are any temps left above the cut, we need to sort
4837 * them into those to keep and those to free. The only ones to
4838 * keep are those for which we've temporarily unset SvTEMP.
4839 * Work inwards from the two ends at tmps_basep .. PL_tmps_ix,
4840 * swapping pairs as necessary. Stop when we meet in the middle.
4843 SV **top = PL_tmps_stack + PL_tmps_ix;
4844 while (tmps_basep <= top) {
4857 tmps_base = tmps_basep - PL_tmps_stack;
4860 PL_stack_sp = to_sp;
4862 /* unrolled FREETMPS() but using tmps_base-1 rather than PL_tmps_floor */
4863 while (PL_tmps_ix >= tmps_base) {
4864 SV* const sv = PL_tmps_stack[PL_tmps_ix--];
4866 PoisonWith(PL_tmps_stack + PL_tmps_ix + 1, 1, SV *, 0xAB);
4870 SvREFCNT_dec_NN(sv); /* note, can modify tmps_ix!!! */
4876 /* also tail-called by pp_return */
4886 assert(CxTYPE(cx) == CXt_SUB);
4888 if (CxMULTICALL(cx)) {
4889 /* entry zero of a stack is always PL_sv_undef, which
4890 * simplifies converting a '()' return into undef in scalar context */
4891 assert(PL_stack_sp > PL_stack_base || *PL_stack_base == &PL_sv_undef);
4895 gimme = cx->blk_gimme;
4896 oldsp = PL_stack_base + cx->blk_oldsp; /* last arg of previous frame */
4898 if (gimme == G_VOID)
4899 PL_stack_sp = oldsp;
4901 leave_adjust_stacks(oldsp, oldsp, gimme, 0);
4904 cx_popsub(cx); /* Stack values are safe: release CV and @_ ... */
4906 retop = cx->blk_sub.retop;
4913 /* clear (if possible) or abandon the current @_. If 'abandon' is true,
4914 * forces an abandon */
4917 Perl_clear_defarray(pTHX_ AV* av, bool abandon)
4919 const SSize_t fill = AvFILLp(av);
4921 PERL_ARGS_ASSERT_CLEAR_DEFARRAY;
4923 if (LIKELY(!abandon && SvREFCNT(av) == 1 && !SvMAGICAL(av))) {
4928 AV *newav = newAV();
4929 av_extend(newav, fill);
4930 AvREIFY_only(newav);
4931 PAD_SVl(0) = MUTABLE_SV(newav);
4932 SvREFCNT_dec_NN(av);
4943 I32 old_savestack_ix;
4948 /* Locate the CV to call:
4949 * - most common case: RV->CV: f(), $ref->():
4950 * note that if a sub is compiled before its caller is compiled,
4951 * the stash entry will be a ref to a CV, rather than being a GV.
4952 * - second most common case: CV: $ref->method()
4955 /* a non-magic-RV -> CV ? */
4956 if (LIKELY( (SvFLAGS(sv) & (SVf_ROK|SVs_GMG)) == SVf_ROK)) {
4957 cv = MUTABLE_CV(SvRV(sv));
4958 if (UNLIKELY(SvOBJECT(cv))) /* might be overloaded */
4962 cv = MUTABLE_CV(sv);
4965 if (UNLIKELY(SvTYPE(cv) != SVt_PVCV)) {
4966 /* handle all the weird cases */
4967 switch (SvTYPE(sv)) {
4969 if (!isGV_with_GP(sv))
4973 cv = GvCVu((const GV *)sv);
4974 if (UNLIKELY(!cv)) {
4976 cv = sv_2cv(sv, &stash, &gv, 0);
4978 old_savestack_ix = PL_savestack_ix;
4989 if (UNLIKELY(SvAMAGIC(sv))) {
4990 sv = amagic_deref_call(sv, to_cv_amg);
4991 /* Don't SPAGAIN here. */
4997 if (UNLIKELY(!SvOK(sv)))
4998 DIE(aTHX_ PL_no_usym, "a subroutine");
5000 sym = SvPV_nomg_const(sv, len);
5001 if (PL_op->op_private & HINT_STRICT_REFS)
5002 DIE(aTHX_ "Can't use string (\"%" SVf32 "\"%s) as a subroutine ref while \"strict refs\" in use", sv, len>32 ? "..." : "");
5003 cv = get_cvn_flags(sym, len, GV_ADD|SvUTF8(sv));
5006 cv = MUTABLE_CV(SvRV(sv));
5007 if (LIKELY(SvTYPE(cv) == SVt_PVCV))
5013 DIE(aTHX_ "Not a CODE reference");
5017 /* At this point we want to save PL_savestack_ix, either by doing a
5018 * cx_pushsub(), or for XS, doing an ENTER. But we don't yet know the final
5019 * CV we will be using (so we don't know whether its XS, so we can't
5020 * cx_pushsub() or ENTER yet), and determining cv may itself push stuff on
5021 * the save stack. So remember where we are currently on the save
5022 * stack, and later update the CX or scopestack entry accordingly. */
5023 old_savestack_ix = PL_savestack_ix;
5025 /* these two fields are in a union. If they ever become separate,
5026 * we have to test for both of them being null below */
5028 assert((void*)&CvROOT(cv) == (void*)&CvXSUB(cv));
5029 while (UNLIKELY(!CvROOT(cv))) {
5033 /* anonymous or undef'd function leaves us no recourse */
5034 if (CvLEXICAL(cv) && CvHASGV(cv))
5035 DIE(aTHX_ "Undefined subroutine &%" SVf " called",
5036 SVfARG(cv_name(cv, NULL, 0)));
5037 if (CvANON(cv) || !CvHASGV(cv)) {
5038 DIE(aTHX_ "Undefined subroutine called");
5041 /* autoloaded stub? */
5042 if (cv != GvCV(gv = CvGV(cv))) {
5045 /* should call AUTOLOAD now? */
5048 autogv = gv_autoload_pvn(GvSTASH(gv), GvNAME(gv), GvNAMELEN(gv),
5049 (GvNAMEUTF8(gv) ? SVf_UTF8 : 0)
5050 |(PL_op->op_flags & OPf_REF
5051 ? GV_AUTOLOAD_ISMETHOD
5053 cv = autogv ? GvCV(autogv) : NULL;
5056 sub_name = sv_newmortal();
5057 gv_efullname3(sub_name, gv, NULL);
5058 DIE(aTHX_ "Undefined subroutine &%" SVf " called", SVfARG(sub_name));
5062 /* unrolled "CvCLONE(cv) && ! CvCLONED(cv)" */
5063 if (UNLIKELY((CvFLAGS(cv) & (CVf_CLONE|CVf_CLONED)) == CVf_CLONE))
5064 DIE(aTHX_ "Closure prototype called");
5066 if (UNLIKELY((PL_op->op_private & OPpENTERSUB_DB) && GvCV(PL_DBsub)
5069 Perl_get_db_sub(aTHX_ &sv, cv);
5071 PL_curcopdb = PL_curcop;
5073 /* check for lsub that handles lvalue subroutines */
5074 cv = GvCV(gv_fetchpvs("DB::lsub", GV_ADDMULTI, SVt_PVCV));
5075 /* if lsub not found then fall back to DB::sub */
5076 if (!cv) cv = GvCV(PL_DBsub);
5078 cv = GvCV(PL_DBsub);
5081 if (!cv || (!CvXSUB(cv) && !CvSTART(cv)))
5082 DIE(aTHX_ "No DB::sub routine defined");
5085 if (!(CvISXSUB(cv))) {
5086 /* This path taken at least 75% of the time */
5093 /* keep PADTMP args alive throughout the call (we need to do this
5094 * because @_ isn't refcounted). Note that we create the mortals
5095 * in the caller's tmps frame, so they won't be freed until after
5096 * we return from the sub.
5105 *svp = sv = sv_mortalcopy(sv);
5111 cx = cx_pushblock(CXt_SUB, gimme, MARK, old_savestack_ix);
5112 hasargs = cBOOL(PL_op->op_flags & OPf_STACKED);
5113 cx_pushsub(cx, cv, PL_op->op_next, hasargs);
5115 padlist = CvPADLIST(cv);
5116 if (UNLIKELY((depth = ++CvDEPTH(cv)) >= 2))
5117 pad_push(padlist, depth);
5118 PAD_SET_CUR_NOSAVE(padlist, depth);
5119 if (LIKELY(hasargs)) {
5120 AV *const av = MUTABLE_AV(PAD_SVl(0));
5124 defavp = &GvAV(PL_defgv);
5125 cx->blk_sub.savearray = *defavp;
5126 *defavp = MUTABLE_AV(SvREFCNT_inc_simple_NN(av));
5128 /* it's the responsibility of whoever leaves a sub to ensure
5129 * that a clean, empty AV is left in pad[0]. This is normally
5130 * done by cx_popsub() */
5131 assert(!AvREAL(av) && AvFILLp(av) == -1);
5134 if (UNLIKELY(items - 1 > AvMAX(av))) {
5135 SV **ary = AvALLOC(av);
5136 Renew(ary, items, SV*);
5137 AvMAX(av) = items - 1;
5143 Copy(MARK+1,AvARRAY(av),items,SV*);
5144 AvFILLp(av) = items - 1;
5146 if (UNLIKELY((cx->blk_u16 & OPpENTERSUB_LVAL_MASK) == OPpLVAL_INTRO &&
5148 DIE(aTHX_ "Can't modify non-lvalue subroutine call of &%" SVf,
5149 SVfARG(cv_name(cv, NULL, 0)));
5150 /* warning must come *after* we fully set up the context
5151 * stuff so that __WARN__ handlers can safely dounwind()
5154 if (UNLIKELY(depth == PERL_SUB_DEPTH_WARN
5155 && ckWARN(WARN_RECURSION)
5156 && !(PERLDB_SUB && cv == GvCV(PL_DBsub))))
5157 sub_crush_depth(cv);
5158 RETURNOP(CvSTART(cv));
5161 SSize_t markix = TOPMARK;
5165 /* pretend we did the ENTER earlier */
5166 PL_scopestack[PL_scopestack_ix - 1] = old_savestack_ix;
5171 if (UNLIKELY(((PL_op->op_private
5172 & CX_PUSHSUB_GET_LVALUE_MASK(Perl_is_lvalue_sub)
5173 ) & OPpENTERSUB_LVAL_MASK) == OPpLVAL_INTRO &&
5175 DIE(aTHX_ "Can't modify non-lvalue subroutine call of &%" SVf,
5176 SVfARG(cv_name(cv, NULL, 0)));
5178 if (UNLIKELY(!(PL_op->op_flags & OPf_STACKED) && GvAV(PL_defgv))) {
5179 /* Need to copy @_ to stack. Alternative may be to
5180 * switch stack to @_, and copy return values
5181 * back. This would allow popping @_ in XSUB, e.g.. XXXX */
5182 AV * const av = GvAV(PL_defgv);
5183 const SSize_t items = AvFILL(av) + 1;
5187 const bool m = cBOOL(SvRMAGICAL(av));
5188 /* Mark is at the end of the stack. */
5190 for (; i < items; ++i)
5194 SV ** const svp = av_fetch(av, i, 0);
5195 sv = svp ? *svp : NULL;
5197 else sv = AvARRAY(av)[i];
5198 if (sv) SP[i+1] = sv;
5200 SP[i+1] = av_nonelem(av, i);
5208 SV **mark = PL_stack_base + markix;
5209 SSize_t items = SP - mark;
5212 if (*mark && SvPADTMP(*mark)) {
5213 *mark = sv_mortalcopy(*mark);
5217 /* We assume first XSUB in &DB::sub is the called one. */
5218 if (UNLIKELY(PL_curcopdb)) {
5219 SAVEVPTR(PL_curcop);
5220 PL_curcop = PL_curcopdb;
5223 /* Do we need to open block here? XXXX */
5225 /* calculate gimme here as PL_op might get changed and then not
5226 * restored until the LEAVE further down */
5227 is_scalar = (GIMME_V == G_SCALAR);
5229 /* CvXSUB(cv) must not be NULL because newXS() refuses NULL xsub address */
5231 CvXSUB(cv)(aTHX_ cv);
5233 #if defined DEBUGGING && !defined DEBUGGING_RE_ONLY
5234 /* This duplicates the check done in runops_debug(), but provides more
5235 * information in the common case of the fault being with an XSUB.
5237 * It should also catch an XSUB pushing more than it extends
5238 * in scalar context.
5240 if (PL_curstackinfo->si_stack_hwm < PL_stack_sp - PL_stack_base)
5241 Perl_croak_nocontext(
5242 "panic: XSUB %s::%s (%s) failed to extend arg stack: "
5243 "base=%p, sp=%p, hwm=%p\n",
5244 HvNAME(GvSTASH(CvGV(cv))), GvNAME(CvGV(cv)), CvFILE(cv),
5245 PL_stack_base, PL_stack_sp,
5246 PL_stack_base + PL_curstackinfo->si_stack_hwm);
5248 /* Enforce some sanity in scalar context. */
5250 SV **svp = PL_stack_base + markix + 1;
5251 if (svp != PL_stack_sp) {
5252 *svp = svp > PL_stack_sp ? &PL_sv_undef : *PL_stack_sp;
5262 Perl_sub_crush_depth(pTHX_ CV *cv)
5264 PERL_ARGS_ASSERT_SUB_CRUSH_DEPTH;
5267 Perl_warner(aTHX_ packWARN(WARN_RECURSION), "Deep recursion on anonymous subroutine");
5269 Perl_warner(aTHX_ packWARN(WARN_RECURSION), "Deep recursion on subroutine \"%" SVf "\"",
5270 SVfARG(cv_name(cv,NULL,0)));
5276 /* like croak, but report in context of caller */
5279 Perl_croak_caller(const char *pat, ...)
5283 const PERL_CONTEXT *cx = caller_cx(0, NULL);
5285 /* make error appear at call site */
5287 PL_curcop = cx->blk_oldcop;
5289 va_start(args, pat);
5291 NOT_REACHED; /* NOTREACHED */
5300 SV* const elemsv = POPs;
5301 IV elem = SvIV(elemsv);
5302 AV *const av = MUTABLE_AV(POPs);
5303 const U32 lval = PL_op->op_flags & OPf_MOD || LVRET;
5304 const U32 defer = PL_op->op_private & OPpLVAL_DEFER;
5305 const bool localizing = PL_op->op_private & OPpLVAL_INTRO;
5306 bool preeminent = TRUE;
5309 if (UNLIKELY(SvROK(elemsv) && !SvGAMAGIC(elemsv) && ckWARN(WARN_MISC)))
5310 Perl_warner(aTHX_ packWARN(WARN_MISC),
5311 "Use of reference \"%" SVf "\" as array index",
5313 if (UNLIKELY(SvTYPE(av) != SVt_PVAV))
5316 if (UNLIKELY(localizing)) {
5320 /* If we can determine whether the element exist,
5321 * Try to preserve the existenceness of a tied array
5322 * element by using EXISTS and DELETE if possible.
5323 * Fallback to FETCH and STORE otherwise. */
5324 if (SvCANEXISTDELETE(av))
5325 preeminent = av_exists(av, elem);
5328 svp = av_fetch(av, elem, lval && !defer);
5330 #ifdef PERL_MALLOC_WRAP
5331 if (SvUOK(elemsv)) {
5332 const UV uv = SvUV(elemsv);
5333 elem = uv > IV_MAX ? IV_MAX : uv;
5335 else if (SvNOK(elemsv))
5336 elem = (IV)SvNV(elemsv);
5338 MEM_WRAP_CHECK_s(elem,SV*,"Out of memory during array extend");
5341 if (!svp || !*svp) {
5344 DIE(aTHX_ PL_no_aelem, elem);
5345 len = av_tindex(av);
5346 /* Resolve a negative index that falls within the array. Leave
5347 it negative it if falls outside the array. */
5348 if (elem < 0 && len + elem >= 0)
5350 if (elem >= 0 && elem <= len)
5351 /* Falls within the array. */
5352 PUSHs(av_nonelem(av,elem));
5354 /* Falls outside the array. If it is negative,
5355 magic_setdefelem will use the index for error reporting.
5357 mPUSHs(newSVavdefelem(av, elem, 1));
5360 if (UNLIKELY(localizing)) {
5362 save_aelem(av, elem, svp);
5364 SAVEADELETE(av, elem);
5366 else if (PL_op->op_private & OPpDEREF) {
5367 PUSHs(vivify_ref(*svp, PL_op->op_private & OPpDEREF));
5371 sv = (svp ? *svp : &PL_sv_undef);
5372 if (!lval && SvRMAGICAL(av) && SvGMAGICAL(sv)) /* see note in pp_helem() */
5379 Perl_vivify_ref(pTHX_ SV *sv, U32 to_what)
5381 PERL_ARGS_ASSERT_VIVIFY_REF;
5386 Perl_croak_no_modify();
5387 prepare_SV_for_RV(sv);
5390 SvRV_set(sv, newSV(0));
5393 SvRV_set(sv, MUTABLE_SV(newAV()));
5396 SvRV_set(sv, MUTABLE_SV(newHV()));
5403 if (SvGMAGICAL(sv)) {
5404 /* copy the sv without magic to prevent magic from being
5406 SV* msv = sv_newmortal();
5407 sv_setsv_nomg(msv, sv);
5413 PERL_STATIC_INLINE HV *
5414 S_opmethod_stash(pTHX_ SV* meth)
5419 SV* const sv = PL_stack_base + TOPMARK == PL_stack_sp
5420 ? (Perl_croak(aTHX_ "Can't call method \"%" SVf "\" without a "
5421 "package or object reference", SVfARG(meth)),
5423 : *(PL_stack_base + TOPMARK + 1);
5425 PERL_ARGS_ASSERT_OPMETHOD_STASH;
5429 Perl_croak(aTHX_ "Can't call method \"%" SVf "\" on an undefined value",
5432 if (UNLIKELY(SvGMAGICAL(sv))) mg_get(sv);
5433 else if (SvIsCOW_shared_hash(sv)) { /* MyClass->meth() */
5434 stash = gv_stashsv(sv, GV_CACHE_ONLY);
5435 if (stash) return stash;
5439 ob = MUTABLE_SV(SvRV(sv));
5440 else if (!SvOK(sv)) goto undefined;
5441 else if (isGV_with_GP(sv)) {
5443 Perl_croak(aTHX_ "Can't call method \"%" SVf "\" "
5444 "without a package or object reference",
5447 if (SvTYPE(ob) == SVt_PVLV && LvTYPE(ob) == 'y') {
5448 assert(!LvTARGLEN(ob));
5452 *(PL_stack_base + TOPMARK + 1) = sv_2mortal(newRV(ob));
5455 /* this isn't a reference */
5458 const char * const packname = SvPV_nomg_const(sv, packlen);
5459 const U32 packname_utf8 = SvUTF8(sv);
5460 stash = gv_stashpvn(packname, packlen, packname_utf8 | GV_CACHE_ONLY);
5461 if (stash) return stash;
5463 if (!(iogv = gv_fetchpvn_flags(
5464 packname, packlen, packname_utf8, SVt_PVIO
5466 !(ob=MUTABLE_SV(GvIO(iogv))))
5468 /* this isn't the name of a filehandle either */
5471 Perl_croak(aTHX_ "Can't call method \"%" SVf "\" "
5472 "without a package or object reference",
5475 /* assume it's a package name */
5476 stash = gv_stashpvn(packname, packlen, packname_utf8);
5477 if (stash) return stash;
5478 else return MUTABLE_HV(sv);
5480 /* it _is_ a filehandle name -- replace with a reference */
5481 *(PL_stack_base + TOPMARK + 1) = sv_2mortal(newRV(MUTABLE_SV(iogv)));
5484 /* if we got here, ob should be an object or a glob */
5485 if (!ob || !(SvOBJECT(ob)
5486 || (isGV_with_GP(ob)
5487 && (ob = MUTABLE_SV(GvIO((const GV *)ob)))
5490 Perl_croak(aTHX_ "Can't call method \"%" SVf "\" on unblessed reference",
5491 SVfARG((SvPOK(meth) && SvPVX(meth) == PL_isa_DOES)
5492 ? newSVpvs_flags("DOES", SVs_TEMP)
5504 SV* const meth = TOPs;
5507 SV* const rmeth = SvRV(meth);
5508 if (SvTYPE(rmeth) == SVt_PVCV) {
5514 stash = opmethod_stash(meth);
5516 gv = gv_fetchmethod_sv_flags(stash, meth, GV_AUTOLOAD|GV_CROAK);
5519 SETs(isGV(gv) ? MUTABLE_SV(GvCV(gv)) : MUTABLE_SV(gv));
5523 #define METHOD_CHECK_CACHE(stash,cache,meth) \
5524 const HE* const he = hv_fetch_ent(cache, meth, 0, 0); \
5526 gv = MUTABLE_GV(HeVAL(he)); \
5527 if (isGV(gv) && GvCV(gv) && (!GvCVGEN(gv) || GvCVGEN(gv) \
5528 == (PL_sub_generation + HvMROMETA(stash)->cache_gen))) \
5530 XPUSHs(MUTABLE_SV(GvCV(gv))); \
5539 SV* const meth = cMETHOPx_meth(PL_op);
5540 HV* const stash = opmethod_stash(meth);
5542 if (LIKELY(SvTYPE(stash) == SVt_PVHV)) {
5543 METHOD_CHECK_CACHE(stash, stash, meth);
5546 gv = gv_fetchmethod_sv_flags(stash, meth, GV_AUTOLOAD|GV_CROAK);
5549 XPUSHs(isGV(gv) ? MUTABLE_SV(GvCV(gv)) : MUTABLE_SV(gv));
5558 SV* const meth = cMETHOPx_meth(PL_op);
5559 HV* const stash = CopSTASH(PL_curcop);
5560 /* Actually, SUPER doesn't need real object's (or class') stash at all,
5561 * as it uses CopSTASH. However, we must ensure that object(class) is
5562 * correct (this check is done by S_opmethod_stash) */
5563 opmethod_stash(meth);
5565 if ((cache = HvMROMETA(stash)->super)) {
5566 METHOD_CHECK_CACHE(stash, cache, meth);
5569 gv = gv_fetchmethod_sv_flags(stash, meth, GV_AUTOLOAD|GV_CROAK|GV_SUPER);
5572 XPUSHs(isGV(gv) ? MUTABLE_SV(GvCV(gv)) : MUTABLE_SV(gv));
5580 SV* const meth = cMETHOPx_meth(PL_op);
5581 HV* stash = gv_stashsv(cMETHOPx_rclass(PL_op), 0);
5582 opmethod_stash(meth); /* not used but needed for error checks */
5584 if (stash) { METHOD_CHECK_CACHE(stash, stash, meth); }
5585 else stash = MUTABLE_HV(cMETHOPx_rclass(PL_op));
5587 gv = gv_fetchmethod_sv_flags(stash, meth, GV_AUTOLOAD|GV_CROAK);
5590 XPUSHs(isGV(gv) ? MUTABLE_SV(GvCV(gv)) : MUTABLE_SV(gv));
5594 PP(pp_method_redir_super)
5599 SV* const meth = cMETHOPx_meth(PL_op);
5600 HV* stash = gv_stashsv(cMETHOPx_rclass(PL_op), 0);
5601 opmethod_stash(meth); /* not used but needed for error checks */
5603 if (UNLIKELY(!stash)) stash = MUTABLE_HV(cMETHOPx_rclass(PL_op));
5604 else if ((cache = HvMROMETA(stash)->super)) {
5605 METHOD_CHECK_CACHE(stash, cache, meth);
5608 gv = gv_fetchmethod_sv_flags(stash, meth, GV_AUTOLOAD|GV_CROAK|GV_SUPER);
5611 XPUSHs(isGV(gv) ? MUTABLE_SV(GvCV(gv)) : MUTABLE_SV(gv));
5616 * ex: set ts=8 sts=4 sw=4 et: