3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4 * 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 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 * 'Mercy!' cried Gandalf. 'If the giving of information is to be the cure
13 * of your inquisitiveness, I shall spend all the rest of my days in answering
14 * you. What more do you want to know?'
15 * 'The names of all the stars, and of all living things, and the whole
16 * history of Middle-earth and Over-heaven and of the Sundering Seas,'
19 * [p.599 of _The Lord of the Rings_, III/xi: "The PalantÃr"]
23 =head1 GV Handling and Stashes
24 A GV is a structure which corresponds to to a Perl typeglob, ie *foo.
25 It is a structure that holds a pointer to a scalar, an array, a hash etc,
26 corresponding to $foo, @foo, %foo.
28 GVs are usually found as values in stashes (symbol table hashes) where
29 Perl stores its global variables.
31 A B<stash> is a hash that contains all variables that are defined
32 within a package. See L<perlguts/Stashes and Globs>
42 #include "overload.inc"
46 static const char S_autoload[] = "AUTOLOAD";
47 #define S_autolen (sizeof("AUTOLOAD")-1)
50 =for apidoc gv_add_by_type
52 Make sure there is a slot of type C<type> in the GV C<gv>.
58 Perl_gv_add_by_type(pTHX_ GV *gv, svtype type)
65 SvTYPE((const SV *)gv) != SVt_PVGV
66 && SvTYPE((const SV *)gv) != SVt_PVLV
70 if (type == SVt_PVIO) {
72 * if it walks like a dirhandle, then let's assume that
73 * this is a dirhandle.
75 what = OP_IS_DIRHOP(PL_op->op_type) ?
76 "dirhandle" : "filehandle";
77 } else if (type == SVt_PVHV) {
80 what = type == SVt_PVAV ? "array" : "scalar";
82 Perl_croak(aTHX_ "Bad symbol for %s", what);
85 if (type == SVt_PVHV) {
86 where = (SV **)&GvHV(gv);
87 } else if (type == SVt_PVAV) {
88 where = (SV **)&GvAV(gv);
89 } else if (type == SVt_PVIO) {
90 where = (SV **)&GvIOp(gv);
97 *where = newSV_type(type);
99 && memEQs(GvNAME(gv), GvNAMELEN(gv), "ISA"))
101 sv_magic(*where, (SV *)gv, PERL_MAGIC_isa, NULL, 0);
108 =for apidoc gv_fetchfile
109 =for apidoc_item gv_fetchfile_flags
111 These return the debugger glob for the file (compiled by Perl) whose name is
112 given by the C<name> parameter.
114 There are currently exactly two differences between these functions.
116 The C<name> parameter to C<gv_fetchfile> is a C string, meaning it is
117 C<NUL>-terminated; whereas the C<name> parameter to C<gv_fetchfile_flags> is a
118 Perl string, whose length (in bytes) is passed in via the C<namelen> parameter
119 This means the name may contain embedded C<NUL> characters.
120 C<namelen> doesn't exist in plain C<gv_fetchfile>).
122 The other difference is that C<gv_fetchfile_flags> has an extra C<flags>
123 parameter, which is currently completely ignored, but allows for possible
129 Perl_gv_fetchfile(pTHX_ const char *name)
131 PERL_ARGS_ASSERT_GV_FETCHFILE;
132 return gv_fetchfile_flags(name, strlen(name), 0);
136 Perl_gv_fetchfile_flags(pTHX_ const char *const name, const STRLEN namelen,
141 const STRLEN tmplen = namelen + 2;
144 PERL_ARGS_ASSERT_GV_FETCHFILE_FLAGS;
145 PERL_UNUSED_ARG(flags);
150 if (tmplen <= sizeof smallbuf)
153 Newx(tmpbuf, tmplen, char);
154 /* This is where the debugger's %{"::_<$filename"} hash is created */
157 memcpy(tmpbuf + 2, name, namelen);
158 GV **gvp = (GV**)hv_fetch(PL_defstash, tmpbuf, tmplen, (flags & GVF_NOADD) ? FALSE : TRUE);
162 gv_init(gv, PL_defstash, tmpbuf, tmplen, FALSE);
163 #ifdef PERL_DONT_CREATE_GVSV
164 GvSV(gv) = newSVpvn(name, namelen);
166 sv_setpvn(GvSV(gv), name, namelen);
169 if (PERLDB_LINE_OR_SAVESRC && !GvAV(gv))
170 hv_magic(GvHVn(gv), GvAVn(gv), PERL_MAGIC_dbfile);
175 if (tmpbuf != smallbuf)
181 =for apidoc gv_const_sv
183 If C<gv> is a typeglob whose subroutine entry is a constant sub eligible for
184 inlining, or C<gv> is a placeholder reference that would be promoted to such
185 a typeglob, then returns the value returned by the sub. Otherwise, returns
192 Perl_gv_const_sv(pTHX_ GV *gv)
194 PERL_ARGS_ASSERT_GV_CONST_SV;
197 if (SvTYPE(gv) == SVt_PVGV)
198 return cv_const_sv(GvCVu(gv));
199 return SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVAV && SvTYPE(SvRV(gv)) != SVt_PVCV ? SvRV(gv) : NULL;
203 Perl_newGP(pTHX_ GV *const gv)
210 PERL_ARGS_ASSERT_NEWGP;
212 gp->gp_egv = gv; /* allow compiler to reuse gv after this */
213 #ifndef PERL_DONT_CREATE_GVSV
214 gp->gp_sv = newSV_type(SVt_NULL);
217 /* PL_curcop may be null here. E.g.,
218 INIT { bless {} and exit }
219 frees INIT before looking up DESTROY (and creating *DESTROY)
222 char *tmp= CopFILE(PL_curcop);
223 gp->gp_line = CopLINE(PL_curcop); /* 0 otherwise Newxz */
227 len = CopFILE_LEN(PL_curcop);
237 PERL_HASH(hash, file, len);
238 gp->gp_file_hek = share_hek(file, len, hash);
244 /* Assign CvGV(cv) = gv, handling weak references.
245 * See also S_anonymise_cv_maybe */
248 Perl_cvgv_set(pTHX_ CV* cv, GV* gv)
250 GV * const oldgv = CvNAMED(cv) ? NULL : SvANY(cv)->xcv_gv_u.xcv_gv;
252 PERL_ARGS_ASSERT_CVGV_SET;
259 SvREFCNT_dec_NN(oldgv);
263 sv_del_backref(MUTABLE_SV(oldgv), MUTABLE_SV(cv));
266 else if ((hek = CvNAME_HEK(cv))) {
272 SvANY(cv)->xcv_gv_u.xcv_gv = gv;
273 assert(!CvCVGV_RC(cv));
278 if (isGV_with_GP(gv) && GvGP(gv) && (GvCV(gv) == cv || GvFORM(gv) == cv))
279 Perl_sv_add_backref(aTHX_ MUTABLE_SV(gv), MUTABLE_SV(cv));
282 SvREFCNT_inc_simple_void_NN(gv);
286 /* Convert CvSTASH + CvNAME_HEK into a GV. Conceptually, all subs have a
287 GV, but for efficiency that GV may not in fact exist. This function,
288 called by CvGV, reifies it. */
291 Perl_cvgv_from_hek(pTHX_ CV *cv)
295 PERL_ARGS_ASSERT_CVGV_FROM_HEK;
296 assert(SvTYPE(cv) == SVt_PVCV);
297 if (!CvSTASH(cv)) return NULL;
298 ASSUME(CvNAME_HEK(cv));
299 svp = hv_fetchhek(CvSTASH(cv), CvNAME_HEK(cv), 0);
300 gv = MUTABLE_GV(svp && *svp ? *svp : newSV_type(SVt_NULL));
302 gv_init_pvn(gv, CvSTASH(cv), HEK_KEY(CvNAME_HEK(cv)),
303 HEK_LEN(CvNAME_HEK(cv)),
304 SVf_UTF8 * cBOOL(HEK_UTF8(CvNAME_HEK(cv))));
305 if (!CvNAMED(cv)) { /* gv_init took care of it */
306 assert (SvANY(cv)->xcv_gv_u.xcv_gv == gv);
309 unshare_hek(CvNAME_HEK(cv));
311 SvANY(cv)->xcv_gv_u.xcv_gv = gv;
312 if (svp && *svp) SvREFCNT_inc_simple_void_NN(gv);
317 /* Assign CvSTASH(cv) = st, handling weak references. */
320 Perl_cvstash_set(pTHX_ CV *cv, HV *st)
322 HV *oldst = CvSTASH(cv);
323 PERL_ARGS_ASSERT_CVSTASH_SET;
327 sv_del_backref(MUTABLE_SV(oldst), MUTABLE_SV(cv));
328 SvANY(cv)->xcv_stash = st;
330 Perl_sv_add_backref(aTHX_ MUTABLE_SV(st), MUTABLE_SV(cv));
334 =for apidoc gv_init_pvn
336 Converts a scalar into a typeglob. This is an incoercible typeglob;
337 assigning a reference to it will assign to one of its slots, instead of
338 overwriting it as happens with typeglobs created by C<SvSetSV>. Converting
339 any scalar that is C<SvOK()> may produce unpredictable results and is reserved
340 for perl's internal use.
342 C<gv> is the scalar to be converted.
344 C<stash> is the parent stash/package, if any.
346 C<name> and C<len> give the name. The name must be unqualified;
347 that is, it must not include the package name. If C<gv> is a
348 stash element, it is the caller's responsibility to ensure that the name
349 passed to this function matches the name of the element. If it does not
350 match, perl's internal bookkeeping will get out of sync.
352 C<flags> can be set to C<SVf_UTF8> if C<name> is a UTF-8 string, or
353 the return value of SvUTF8(sv). It can also take the
354 C<GV_ADDMULTI> flag, which means to pretend that the GV has been
355 seen before (i.e., suppress "Used once" warnings).
357 =for apidoc Amnh||GV_ADDMULTI
361 The old form of C<gv_init_pvn()>. It does not work with UTF-8 strings, as it
362 has no flags parameter. If the C<multi> parameter is set, the
363 C<GV_ADDMULTI> flag will be passed to C<gv_init_pvn()>.
365 =for apidoc gv_init_pv
367 Same as C<gv_init_pvn()>, but takes a nul-terminated string for the name
368 instead of separate char * and length parameters.
370 =for apidoc gv_init_sv
372 Same as C<gv_init_pvn()>, but takes an SV * for the name instead of separate
373 char * and length parameters. C<flags> is currently unused.
379 Perl_gv_init_sv(pTHX_ GV *gv, HV *stash, SV* namesv, U32 flags)
383 PERL_ARGS_ASSERT_GV_INIT_SV;
384 namepv = SvPV(namesv, namelen);
387 gv_init_pvn(gv, stash, namepv, namelen, flags);
391 Perl_gv_init_pv(pTHX_ GV *gv, HV *stash, const char *name, U32 flags)
393 PERL_ARGS_ASSERT_GV_INIT_PV;
394 gv_init_pvn(gv, stash, name, strlen(name), flags);
397 /* Packages in the symbol table are "stashes" - hashes where the keys are symbol
398 names and the values are typeglobs. The value $foo::bar is actually found
399 by looking up the typeglob *foo::{bar} and then reading its SCALAR slot.
401 At least, that's what you see in Perl space if you use typeglob syntax.
402 Usually it's also what's actually stored in the stash, but for some cases
403 different values are stored (as a space optimisation) and converted to full
404 typeglobs "on demand" - if a typeglob syntax is used to read a value. It's
405 the job of this function, Perl_gv_init_pvn(), to undo any trickery and
406 replace the SV stored in the stash with the regular PVGV structure that it is
407 a shorthand for. This has to be done "in-place" by upgrading the actual SV
408 that is already stored in the stash to a PVGV.
410 As the public documentation above says:
411 Converting any scalar that is C<SvOK()> may produce unpredictable
412 results and is reserved for perl's internal use.
414 Values that can be stored:
416 * plain scalar - a subroutine declaration
417 The scalar's string value is the subroutine prototype; the integer -1 is
418 "no prototype". ie shorthand for sub foo ($$); or sub bar;
419 * reference to a scalar - a constant. ie shorthand for sub PI() { 4; }
420 * reference to a sub - a subroutine (avoids allocating a PVGV)
422 The earliest optimisation was subroutine declarations, implemented in 1998
423 by commit 8472ac73d6d80294:
424 "Sub declaration cost reduced from ~500 to ~100 bytes"
426 This space optimisation needs to be invisible to regular Perl code. For this
432 When the first line is compiled, the optimisation is used, and $::{foo} is
433 assigned the scalar '$$'. No PVGV or PVCV is created.
435 When the second line encountered, the typeglob lookup on foo needs to
436 "upgrade" the symbol table entry to a PVGV, and then create a PVCV in the
437 {CODE} slot with the prototype $$ and no body. The typeglob is then available
438 so that [] can be assigned to the {ARRAY} slot. For the code above the
439 upgrade happens at compile time, the assignment at runtime.
441 Analogous code unwinds the other optimisations.
444 Perl_gv_init_pvn(pTHX_ GV *gv, HV *stash, const char *name, STRLEN len, U32 flags)
446 const U32 old_type = SvTYPE(gv);
447 const bool doproto = old_type > SVt_NULL;
448 char * const proto = (doproto && SvPOK(gv))
449 ? ((void)(SvIsCOW(gv) && (sv_force_normal((SV *)gv), 0)), SvPVX(gv))
451 const STRLEN protolen = proto ? SvCUR(gv) : 0;
452 const U32 proto_utf8 = proto ? SvUTF8(gv) : 0;
453 SV *const has_constant = doproto && SvROK(gv) ? SvRV(gv) : NULL;
454 const U32 exported_constant = has_constant ? SvPCS_IMPORTED(gv) : 0;
455 const bool really_sub =
456 has_constant && SvTYPE(has_constant) == SVt_PVCV;
457 COP * const old = PL_curcop;
459 PERL_ARGS_ASSERT_GV_INIT_PVN;
460 assert (!(proto && has_constant));
463 /* The constant has to be a scalar, array or subroutine. */
464 switch (SvTYPE(has_constant)) {
468 Perl_croak(aTHX_ "Cannot convert a reference to %s to typeglob",
469 sv_reftype(has_constant, 0));
470 NOT_REACHED; /* NOTREACHED */
480 if (old_type < SVt_PVGV) {
481 if (old_type >= SVt_PV)
483 sv_upgrade(MUTABLE_SV(gv), SVt_PVGV);
487 /* For this case, we are "stealing" the buffer from the SvPV and
488 re-attaching to an SV below with the call to sv_usepvn_flags().
489 Hence we don't free it. */
493 /* There is no valid prototype. (SvPOK() must be true for a valid
494 prototype.) Hence we free the memory. */
495 Safefree(SvPVX_mutable(gv));
503 if (really_sub && !CvISXSUB(has_constant) && CvSTART(has_constant)
504 && ( CvSTART(has_constant)->op_type == OP_NEXTSTATE
505 || CvSTART(has_constant)->op_type == OP_DBSTATE))
506 PL_curcop = (COP *)CvSTART(has_constant);
507 GvGP_set(gv, Perl_newGP(aTHX_ gv));
511 Perl_sv_add_backref(aTHX_ MUTABLE_SV(stash), MUTABLE_SV(gv));
512 gv_name_set(gv, name, len, GV_ADD | ( flags & SVf_UTF8 ? SVf_UTF8 : 0 ));
513 if (flags & GV_ADDMULTI || doproto) /* doproto means it */
514 GvMULTI_on(gv); /* _was_ mentioned */
516 /* Not actually a constant. Just a regular sub. */
517 CV * const cv = (CV *)has_constant;
519 if (CvNAMED(cv) && CvSTASH(cv) == stash && (
520 CvNAME_HEK(cv) == GvNAME_HEK(gv)
521 || ( HEK_LEN(CvNAME_HEK(cv)) == HEK_LEN(GvNAME_HEK(gv))
522 && HEK_FLAGS(CvNAME_HEK(cv)) != HEK_FLAGS(GvNAME_HEK(gv))
523 && HEK_UTF8(CvNAME_HEK(cv)) == HEK_UTF8(GvNAME_HEK(gv))
524 && memEQ(HEK_KEY(CvNAME_HEK(cv)), GvNAME(gv), GvNAMELEN(gv))
532 /* newCONSTSUB takes ownership of the reference from us. */
533 cv = newCONSTSUB_flags(stash, name, len, flags, has_constant);
534 /* In case op.c:S_process_special_blocks stole it: */
536 GvCV_set(gv, (CV *)SvREFCNT_inc_simple_NN(cv));
537 assert(GvCV(gv) == cv); /* newCONSTSUB should have set this */
538 /* If this reference was a copy of another, then the subroutine
539 must have been "imported", by a Perl space assignment to a GV
540 from a reference to CV. */
541 if (exported_constant)
542 GvIMPORTED_CV_on(gv);
543 CvSTASH_set(cv, PL_curstash); /* XXX Why is this needed? */
548 sv_usepvn_flags(MUTABLE_SV(cv), proto, protolen,
549 SV_HAS_TRAILING_NUL);
550 if ( proto_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
556 S_gv_init_svtype(pTHX_ GV *gv, const svtype sv_type)
558 PERL_ARGS_ASSERT_GV_INIT_SVTYPE;
570 #ifdef PERL_DONT_CREATE_GVSV
578 /* Work round what appears to be a bug in Sun C++ 5.8 2005/10/13
579 If we just cast GvSVn(gv) to void, it ignores evaluating it for
586 static void core_xsub(pTHX_ CV* cv);
589 S_maybe_add_coresub(pTHX_ HV * const stash, GV *gv,
590 const char * const name, const STRLEN len)
592 const int code = keyword(name, len, 1);
593 static const char file[] = __FILE__;
594 CV *cv, *oldcompcv = NULL;
596 bool ampable = TRUE; /* &{}-able */
597 COP *oldcurcop = NULL;
598 yy_parser *oldparser = NULL;
599 I32 oldsavestack_ix = 0;
604 if (!code) return NULL; /* Not a keyword */
605 switch (code < 0 ? -code : code) {
606 /* no support for \&CORE::infix;
607 no support for funcs that do not parse like funcs */
608 case KEY___DATA__: case KEY___END__: case KEY_and: case KEY_AUTOLOAD:
609 case KEY_BEGIN : case KEY_CHECK : case KEY_catch : case KEY_cmp:
610 case KEY_default : case KEY_defer : case KEY_DESTROY:
611 case KEY_do : case KEY_dump : case KEY_else : case KEY_elsif :
612 case KEY_END : case KEY_eq : case KEY_eval : case KEY_finally:
613 case KEY_for : case KEY_foreach: case KEY_format: case KEY_ge :
614 case KEY_given : case KEY_goto : case KEY_grep : case KEY_gt :
615 case KEY_if : case KEY_isa : case KEY_INIT : case KEY_last :
616 case KEY_le : case KEY_local : case KEY_lt : case KEY_m :
617 case KEY_map : case KEY_my:
618 case KEY_ne : case KEY_next : case KEY_no: case KEY_or: case KEY_our:
619 case KEY_package: case KEY_print: case KEY_printf:
620 case KEY_q : case KEY_qq : case KEY_qr : case KEY_qw :
621 case KEY_qx : case KEY_redo : case KEY_require: case KEY_return:
622 case KEY_s : case KEY_say : case KEY_sort :
623 case KEY_state: case KEY_sub :
624 case KEY_tr : case KEY_try : case KEY_UNITCHECK: case KEY_unless:
625 case KEY_until: case KEY_use : case KEY_when : case KEY_while :
626 case KEY_x : case KEY_xor : case KEY_y :
629 case KEY_chomp: case KEY_chop: case KEY_defined: case KEY_delete:
630 case KEY_eof : case KEY_exec: case KEY_exists :
635 case KEY_truncate: case KEY_unlink:
639 gv = (GV *)newSV_type(SVt_NULL);
640 gv_init(gv, stash, name, len, TRUE);
645 oldcurcop = PL_curcop;
646 oldparser = PL_parser;
647 lex_start(NULL, NULL, 0);
648 oldcompcv = PL_compcv;
649 PL_compcv = NULL; /* Prevent start_subparse from setting
651 oldsavestack_ix = start_subparse(FALSE,0);
655 /* Avoid calling newXS, as it calls us, and things start to
657 cv = MUTABLE_CV(newSV_type(SVt_PVCV));
661 CvXSUB(cv) = core_xsub;
664 CvGV_set(cv, gv); /* This stops new ATTRSUB from setting CvFILE
666 /* XSUBs can't be perl lang/perl5db.pl debugged
667 if (PERLDB_LINE_OR_SAVESRC)
668 (void)gv_fetchfile(file); */
669 CvFILE(cv) = (char *)file;
670 /* XXX This is inefficient, as doing things this order causes
671 a prototype check in newATTRSUB. But we have to do
672 it this order as we need an op number before calling
674 (void)core_prototype((SV *)cv, name, code, &opnum);
676 (void)hv_store(stash,name,len,(SV *)gv,0);
682 /* newATTRSUB will free the CV and return NULL if we're still
683 compiling after a syntax error */
684 if ((cv = newATTRSUB_x(
685 oldsavestack_ix, (OP *)gv,
690 : newSVpvn(name,len),
695 assert(GvCV(gv) == orig_cv);
696 if (opnum != OP_VEC && opnum != OP_SUBSTR && opnum != OP_POS
697 && opnum != OP_UNDEF && opnum != OP_KEYS)
698 CvLVALUE_off(cv); /* Now *that* was a neat trick. */
701 PL_parser = oldparser;
702 PL_curcop = oldcurcop;
703 PL_compcv = oldcompcv;
706 SV *opnumsv = newSViv(
707 (opnum == OP_ENTEREVAL && len == 9 && memEQ(name, "evalbytes", 9)) ?
708 (OP_ENTEREVAL | (1<<16))
709 : opnum ? opnum : (((I32)name[2]) << 16));
710 cv_set_call_checker_flags(cv, Perl_ck_entersub_args_core, opnumsv, 0);
711 SvREFCNT_dec_NN(opnumsv);
718 =for apidoc gv_fetchmeth
719 =for apidoc_item gv_fetchmeth_pv
720 =for apidoc_item gv_fetchmeth_pvn
721 =for apidoc_item gv_fetchmeth_sv
723 These each look for a glob with name C<name>, containing a defined subroutine,
724 returning the GV of that glob if found, or C<NULL> if not.
726 C<stash> is always searched (first), unless it is C<NULL>.
728 If C<stash> is NULL, or was searched but nothing was found in it, and the
729 C<GV_SUPER> bit is set in C<flags>, stashes accessible via C<@ISA> are searched
730 next. Searching is conducted according to L<C<MRO> order|perlmroapi>.
732 Finally, if no matches were found so far, and the C<GV_NOUNIVERSAL> flag in
733 C<flags> is not set, C<UNIVERSAL::> is searched.
735 The argument C<level> should be either 0 or -1. If -1, the function will
736 return without any side effects or caching. If 0, the function makes sure
737 there is a glob named C<name> in C<stash>, creating one if necessary.
738 The subroutine slot in the glob will be set to any subroutine found in the
739 C<stash> and C<SUPER::> search, hence caching any C<SUPER::> result. Note that
740 subroutines found in C<UNIVERSAL::> are not cached.
742 The GV returned from these may be a method cache entry, which is not visible to
743 Perl code. So when calling C<call_sv>, you should not use the GV directly;
744 instead, you should use the method's CV, which can be obtained from the GV with
747 The only other significant value for C<flags> is C<SVf_UTF8>, indicating that
748 C<name> is to be treated as being encoded in UTF-8.
750 Plain C<gv_fetchmeth> lacks a C<flags> parameter, hence always searches in
751 C<stash>, then C<UNIVERSAL::>, and C<name> is never UTF-8. Otherwise it is
752 exactly like C<gv_fetchmeth_pvn>.
754 The other forms do have a C<flags> parameter, and differ only in how the glob
757 In C<gv_fetchmeth_pv>, C<name> is a C language NUL-terminated string.
759 In C<gv_fetchmeth_pvn>, C<name> points to the first byte of the name, and an
760 additional parameter, C<len>, specifies its length in bytes. Hence, the name
761 may contain embedded-NUL characters.
763 In C<gv_fetchmeth_sv>, C<*name> is an SV, and the name is the PV extracted from
764 that, using L</C<SvPV>>. If the SV is marked as being in UTF-8, the extracted
767 =for apidoc Amnh||GV_SUPER
773 Perl_gv_fetchmeth_sv(pTHX_ HV *stash, SV *namesv, I32 level, U32 flags)
777 PERL_ARGS_ASSERT_GV_FETCHMETH_SV;
778 if (LIKELY(SvPOK_nog(namesv))) /* common case */
779 return gv_fetchmeth_internal(stash, namesv, NULL, 0, level,
780 flags | SvUTF8(namesv));
781 namepv = SvPV(namesv, namelen);
782 if (SvUTF8(namesv)) flags |= SVf_UTF8;
783 return gv_fetchmeth_pvn(stash, namepv, namelen, level, flags);
788 Perl_gv_fetchmeth_pv(pTHX_ HV *stash, const char *name, I32 level, U32 flags)
790 PERL_ARGS_ASSERT_GV_FETCHMETH_PV;
791 return gv_fetchmeth_internal(stash, NULL, name, strlen(name), level, flags);
794 /* NOTE: No support for tied ISA */
796 PERL_STATIC_INLINE GV*
797 S_gv_fetchmeth_internal(pTHX_ HV* stash, SV* meth, const char* name, STRLEN len, I32 level, U32 flags)
804 HV* cstash, *cachestash;
805 GV* candidate = NULL;
810 I32 create = (level >= 0) ? HV_FETCH_LVALUE : 0;
813 U32 is_utf8 = flags & SVf_UTF8;
815 /* UNIVERSAL methods should be callable without a stash */
817 create = 0; /* probably appropriate */
818 if(!(stash = gv_stashpvs("UNIVERSAL", 0)))
824 hvname = HvNAME_get(stash);
825 hvnamelen = HvNAMELEN_get(stash);
827 Perl_croak(aTHX_ "Can't use anonymous symbol table for method lookup");
830 assert(name || meth);
832 DEBUG_o( Perl_deb(aTHX_ "Looking for %smethod %s in package %s\n",
833 flags & GV_SUPER ? "SUPER " : "",
834 name ? name : SvPV_nolen(meth), hvname) );
836 topgen_cmp = HvMROMETA(stash)->cache_gen + PL_sub_generation;
838 if (flags & GV_SUPER) {
839 if (!HvAUX(stash)->xhv_mro_meta->super)
840 HvAUX(stash)->xhv_mro_meta->super = newHV();
841 cachestash = HvAUX(stash)->xhv_mro_meta->super;
843 else cachestash = stash;
845 /* check locally for a real method or a cache entry */
847 cachestash, meth, name, len, is_utf8 ? HVhek_UTF8 : 0, create, NULL, 0
849 if (he) gvp = (GV**)&HeVAL(he);
856 if (SvTYPE(topgv) != SVt_PVGV)
859 name = SvPV_nomg(meth, len);
860 gv_init_pvn(topgv, stash, name, len, GV_ADDMULTI|is_utf8);
862 if ((cand_cv = GvCV(topgv))) {
863 /* If genuine method or valid cache entry, use it */
864 if (!GvCVGEN(topgv) || GvCVGEN(topgv) == topgen_cmp) {
868 /* stale cache entry, junk it and move on */
869 SvREFCNT_dec_NN(cand_cv);
870 GvCV_set(topgv, NULL);
875 else if (GvCVGEN(topgv) == topgen_cmp) {
876 /* cache indicates no such method definitively */
879 else if (stash == cachestash
880 && len > 1 /* shortest is uc */
881 && memEQs(hvname, HvNAMELEN_get(stash), "CORE")
882 && S_maybe_add_coresub(aTHX_ NULL,topgv,name,len))
886 linear_av = mro_get_linear_isa(stash); /* has ourselves at the top of the list */
887 linear_svp = AvARRAY(linear_av) + 1; /* skip over self */
888 items = AvFILLp(linear_av); /* no +1, to skip over self */
890 linear_sv = *linear_svp++;
892 cstash = gv_stashsv(linear_sv, 0);
895 if ( ckWARN(WARN_SYNTAX)) {
896 if( /* these are loaded from Perl_Gv_AMupdate() one way or another */
897 ( len && name[0] == '(' ) /* overload.pm related, in particular "()" */
898 || ( memEQs( name, len, "DESTROY") )
900 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
901 "Can't locate package %" SVf " for @%" HEKf "::ISA",
903 HEKfARG(HvNAME_HEK(stash)));
905 } else if( memEQs( name, len, "AUTOLOAD") ) {
906 /* gobble this warning */
908 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
909 "While trying to resolve method call %.*s->%.*s()"
910 " can not locate package %" SVf_QUOTEDPREFIX " yet it is mentioned in @%.*s::ISA"
911 " (perhaps you forgot to load %" SVf_QUOTEDPREFIX "?)",
912 (int) hvnamelen, hvname,
915 (int) hvnamelen, hvname,
924 gvp = (GV**)hv_common(
925 cstash, meth, name, len, is_utf8 ? HVhek_UTF8 : 0, HV_FETCH_JUST_SV, NULL, 0
928 if (len > 1 && HvNAMELEN_get(cstash) == 4) {
929 const char *hvname = HvNAME(cstash); assert(hvname);
930 if (strBEGINs(hvname, "CORE")
932 S_maybe_add_coresub(aTHX_ cstash,NULL,name,len)
938 else candidate = *gvp;
941 if (SvTYPE(candidate) != SVt_PVGV)
942 gv_init_pvn(candidate, cstash, name, len, GV_ADDMULTI|is_utf8);
943 if (SvTYPE(candidate) == SVt_PVGV && (cand_cv = GvCV(candidate)) && !GvCVGEN(candidate)) {
945 * Found real method, cache method in topgv if:
946 * 1. topgv has no synonyms (else inheritance crosses wires)
947 * 2. method isn't a stub (else AUTOLOAD fails spectacularly)
949 if (topgv && (GvREFCNT(topgv) == 1) && (CvROOT(cand_cv) || CvXSUB(cand_cv))) {
950 CV *old_cv = GvCV(topgv);
951 SvREFCNT_dec(old_cv);
952 SvREFCNT_inc_simple_void_NN(cand_cv);
953 GvCV_set(topgv, cand_cv);
954 GvCVGEN(topgv) = topgen_cmp;
960 /* Check UNIVERSAL without caching */
961 if((level == 0 || level == -1) && !(flags & GV_NOUNIVERSAL)) {
962 candidate = gv_fetchmeth_internal(NULL, meth, name, len, 1,
965 cand_cv = GvCV(candidate);
966 if (topgv && (GvREFCNT(topgv) == 1) && (CvROOT(cand_cv) || CvXSUB(cand_cv))) {
967 CV *old_cv = GvCV(topgv);
968 SvREFCNT_dec(old_cv);
969 SvREFCNT_inc_simple_void_NN(cand_cv);
970 GvCV_set(topgv, cand_cv);
971 GvCVGEN(topgv) = topgen_cmp;
977 if (topgv && GvREFCNT(topgv) == 1 && !(flags & GV_NOUNIVERSAL)) {
978 /* cache the fact that the method is not defined */
979 GvCVGEN(topgv) = topgen_cmp;
986 Perl_gv_fetchmeth_pvn(pTHX_ HV *stash, const char *name, STRLEN len, I32 level, U32 flags)
988 PERL_ARGS_ASSERT_GV_FETCHMETH_PVN;
989 return gv_fetchmeth_internal(stash, NULL, name, len, level, flags);
993 =for apidoc gv_fetchmeth_autoload
995 This is the old form of L</gv_fetchmeth_pvn_autoload>, which has no flags
998 =for apidoc gv_fetchmeth_sv_autoload
1000 Exactly like L</gv_fetchmeth_pvn_autoload>, but takes the name string in the form
1001 of an SV instead of a string/length pair.
1007 Perl_gv_fetchmeth_sv_autoload(pTHX_ HV *stash, SV *namesv, I32 level, U32 flags)
1011 PERL_ARGS_ASSERT_GV_FETCHMETH_SV_AUTOLOAD;
1012 namepv = SvPV(namesv, namelen);
1015 return gv_fetchmeth_pvn_autoload(stash, namepv, namelen, level, flags);
1019 =for apidoc gv_fetchmeth_pv_autoload
1021 Exactly like L</gv_fetchmeth_pvn_autoload>, but takes a nul-terminated string
1022 instead of a string/length pair.
1028 Perl_gv_fetchmeth_pv_autoload(pTHX_ HV *stash, const char *name, I32 level, U32 flags)
1030 PERL_ARGS_ASSERT_GV_FETCHMETH_PV_AUTOLOAD;
1031 return gv_fetchmeth_pvn_autoload(stash, name, strlen(name), level, flags);
1035 =for apidoc gv_fetchmeth_pvn_autoload
1037 Same as C<gv_fetchmeth_pvn()>, but looks for autoloaded subroutines too.
1038 Returns a glob for the subroutine.
1040 For an autoloaded subroutine without a GV, will create a GV even
1041 if C<level < 0>. For an autoloaded subroutine without a stub, C<GvCV()>
1042 of the result may be zero.
1044 Currently, the only significant value for C<flags> is C<SVf_UTF8>.
1050 Perl_gv_fetchmeth_pvn_autoload(pTHX_ HV *stash, const char *name, STRLEN len, I32 level, U32 flags)
1052 GV *gv = gv_fetchmeth_pvn(stash, name, len, level, flags);
1054 PERL_ARGS_ASSERT_GV_FETCHMETH_PVN_AUTOLOAD;
1061 return NULL; /* UNIVERSAL::AUTOLOAD could cause trouble */
1062 if (len == S_autolen && memEQ(name, S_autoload, S_autolen))
1064 if (!(gv = gv_fetchmeth_pvn(stash, S_autoload, S_autolen, FALSE, flags)))
1067 if (!(CvROOT(cv) || CvXSUB(cv)))
1069 /* Have an autoload */
1070 if (level < 0) /* Cannot do without a stub */
1071 gv_fetchmeth_pvn(stash, name, len, 0, flags);
1072 gvp = (GV**)hv_fetch(stash, name,
1073 (flags & SVf_UTF8) ? -(I32)len : (I32)len, (level >= 0));
1082 =for apidoc gv_fetchmethod_autoload
1084 Returns the glob which contains the subroutine to call to invoke the method
1085 on the C<stash>. In fact in the presence of autoloading this may be the
1086 glob for "AUTOLOAD". In this case the corresponding variable C<$AUTOLOAD> is
1089 The third parameter of C<gv_fetchmethod_autoload> determines whether
1090 AUTOLOAD lookup is performed if the given method is not present: non-zero
1091 means yes, look for AUTOLOAD; zero means no, don't look for AUTOLOAD.
1092 Calling C<gv_fetchmethod> is equivalent to calling C<gv_fetchmethod_autoload>
1093 with a non-zero C<autoload> parameter.
1095 These functions grant C<"SUPER"> token
1096 as a prefix of the method name. Note
1097 that if you want to keep the returned glob for a long time, you need to
1098 check for it being "AUTOLOAD", since at the later time the call may load a
1099 different subroutine due to C<$AUTOLOAD> changing its value. Use the glob
1100 created as a side effect to do this.
1102 These functions have the same side-effects as C<gv_fetchmeth> with
1103 C<level==0>. The warning against passing the GV returned by
1104 C<gv_fetchmeth> to C<call_sv> applies equally to these functions.
1110 Perl_gv_fetchmethod_autoload(pTHX_ HV *stash, const char *name, I32 autoload)
1112 PERL_ARGS_ASSERT_GV_FETCHMETHOD_AUTOLOAD;
1114 return gv_fetchmethod_flags(stash, name, autoload ? GV_AUTOLOAD : 0);
1118 Perl_gv_fetchmethod_sv_flags(pTHX_ HV *stash, SV *namesv, U32 flags)
1122 PERL_ARGS_ASSERT_GV_FETCHMETHOD_SV_FLAGS;
1123 namepv = SvPV(namesv, namelen);
1126 return gv_fetchmethod_pvn_flags(stash, namepv, namelen, flags);
1130 Perl_gv_fetchmethod_pv_flags(pTHX_ HV *stash, const char *name, U32 flags)
1132 PERL_ARGS_ASSERT_GV_FETCHMETHOD_PV_FLAGS;
1133 return gv_fetchmethod_pvn_flags(stash, name, strlen(name), flags);
1137 Perl_gv_fetchmethod_pvn_flags(pTHX_ HV *stash, const char *name, const STRLEN len, U32 flags)
1139 const char * const origname = name;
1140 const char * const name_end = name + len;
1141 const char *last_separator = NULL;
1144 SV *const error_report = MUTABLE_SV(stash);
1145 const U32 autoload = flags & GV_AUTOLOAD;
1146 const U32 do_croak = flags & GV_CROAK;
1147 const U32 is_utf8 = flags & SVf_UTF8;
1149 PERL_ARGS_ASSERT_GV_FETCHMETHOD_PVN_FLAGS;
1151 if (SvTYPE(stash) < SVt_PVHV)
1154 /* The only way stash can become NULL later on is if last_separator is set,
1155 which in turn means that there is no need for a SVt_PVHV case
1156 the error reporting code. */
1160 /* check if the method name is fully qualified or
1161 * not, and separate the package name from the actual
1164 * leaves last_separator pointing to the beginning of the
1165 * last package separator (either ' or ::) or 0
1166 * if none was found.
1168 * leaves name pointing at the beginning of the
1171 const char *name_cursor = name;
1172 const char * const name_em1 = name_end - 1; /* name_end minus 1 */
1173 for (name_cursor = name; name_cursor < name_end ; name_cursor++) {
1174 if (*name_cursor == '\'') {
1175 last_separator = name_cursor;
1176 name = name_cursor + 1;
1178 else if (name_cursor < name_em1 && *name_cursor == ':' && name_cursor[1] == ':') {
1179 last_separator = name_cursor++;
1180 name = name_cursor + 1;
1185 /* did we find a separator? */
1186 if (last_separator) {
1187 STRLEN sep_len= last_separator - origname;
1188 if ( memEQs(origname, sep_len, "SUPER")) {
1189 /* ->SUPER::method should really be looked up in original stash */
1190 stash = CopSTASH(PL_curcop);
1192 DEBUG_o( Perl_deb(aTHX_ "Treating %s as %s::%s\n",
1193 origname, HvENAME_get(stash), name) );
1195 else if ( sep_len >= 7 &&
1196 strBEGINs(last_separator - 7, "::SUPER")) {
1197 /* don't autovivify if ->NoSuchStash::SUPER::method */
1198 stash = gv_stashpvn(origname, sep_len - 7, is_utf8);
1199 if (stash) flags |= GV_SUPER;
1202 /* don't autovivify if ->NoSuchStash::method */
1203 stash = gv_stashpvn(origname, sep_len, is_utf8);
1208 gv = gv_fetchmeth_pvn(stash, name, name_end - name, 0, flags);
1210 /* This is the special case that exempts Foo->import and
1211 Foo->unimport from being an error even if there's no
1212 import/unimport subroutine */
1213 if (strEQ(name,"import") || strEQ(name,"unimport")) {
1214 gv = (GV*)sv_2mortal((SV*)newCONSTSUB_flags(NULL,
1216 } else if (autoload)
1217 gv = gv_autoload_pvn(
1218 ostash, name, name_end - name, GV_AUTOLOAD_ISMETHOD|flags
1220 if (!gv && do_croak) {
1221 /* Right now this is exclusively for the benefit of S_method_common
1224 /* If we can't find an IO::File method, it might be a call on
1225 * a filehandle. If IO:File has not been loaded, try to
1226 * require it first instead of croaking */
1227 const char *stash_name = HvNAME_get(stash);
1228 if (stash_name && memEQs(stash_name, HvNAMELEN_get(stash), "IO::File")
1229 && !Perl_hv_common(aTHX_ GvHVn(PL_incgv), NULL,
1230 STR_WITH_LEN("IO/File.pm"), 0,
1231 HV_FETCH_ISEXISTS, NULL, 0)
1233 require_pv("IO/File.pm");
1234 gv = gv_fetchmeth_pvn(stash, name, name_end - name, 0, flags);
1239 "Can't locate object method %" UTF8f_QUOTEDPREFIX ""
1240 " via package %" HEKf_QUOTEDPREFIX,
1241 UTF8fARG(is_utf8, name_end - name, name),
1242 HEKfARG(HvNAME_HEK(stash)));
1247 if (last_separator) {
1248 packnamesv = newSVpvn_flags(origname, last_separator - origname,
1249 SVs_TEMP | is_utf8);
1251 packnamesv = error_report;
1255 "Can't locate object method %" UTF8f_QUOTEDPREFIX ""
1256 " via package %" SVf_QUOTEDPREFIX ""
1257 " (perhaps you forgot to load %" SVf_QUOTEDPREFIX "?)",
1258 UTF8fARG(is_utf8, name_end - name, name),
1259 SVfARG(packnamesv), SVfARG(packnamesv));
1263 else if (autoload) {
1264 CV* const cv = GvCV(gv);
1265 if (!CvROOT(cv) && !CvXSUB(cv)) {
1269 if (CvANON(cv) || CvLEXICAL(cv))
1273 if (GvCV(stubgv) != cv) /* orphaned import */
1276 autogv = gv_autoload_pvn(GvSTASH(stubgv),
1277 GvNAME(stubgv), GvNAMELEN(stubgv),
1278 GV_AUTOLOAD_ISMETHOD
1279 | (GvNAMEUTF8(stubgv) ? SVf_UTF8 : 0));
1290 =for apidoc gv_autoload_pv
1291 =for apidoc_item gv_autoload_pvn
1292 =for apidoc_item gv_autoload_sv
1294 These each search for an C<AUTOLOAD> method, returning NULL if not found, or
1295 else returning a pointer to its GV, while setting the package
1296 L<C<$AUTOLOAD>|perlobj/AUTOLOAD> variable to C<name> (fully qualified). Also,
1297 if found and the GV's CV is an XSUB, the CV's PV will be set to C<name>, and
1298 its stash will be set to the stash of the GV.
1300 Searching is done in L<C<MRO> order|perlmroapi>, as specified in
1301 L</C<gv_fetchmeth>>, beginning with C<stash> if it isn't NULL.
1303 The forms differ only in how C<name> is specified.
1305 In C<gv_autoload_pv>, C<namepv> is a C language NUL-terminated string.
1307 In C<gv_autoload_pvn>, C<name> points to the first byte of the name, and an
1308 additional parameter, C<len>, specifies its length in bytes. Hence, C<*name>
1309 may contain embedded-NUL characters.
1311 In C<gv_autoload_sv>, C<*namesv> is an SV, and the name is the PV extracted
1312 from that using L</C<SvPV>>. If the SV is marked as being in UTF-8, the
1313 extracted PV will also be.
1319 Perl_gv_autoload_sv(pTHX_ HV *stash, SV* namesv, U32 flags)
1323 PERL_ARGS_ASSERT_GV_AUTOLOAD_SV;
1324 namepv = SvPV(namesv, namelen);
1327 return gv_autoload_pvn(stash, namepv, namelen, flags);
1331 Perl_gv_autoload_pv(pTHX_ HV *stash, const char *namepv, U32 flags)
1333 PERL_ARGS_ASSERT_GV_AUTOLOAD_PV;
1334 return gv_autoload_pvn(stash, namepv, strlen(namepv), flags);
1338 Perl_gv_autoload_pvn(pTHX_ HV *stash, const char *name, STRLEN len, U32 flags)
1345 SV *packname = NULL;
1346 U32 is_utf8 = flags & SVf_UTF8 ? SVf_UTF8 : 0;
1348 PERL_ARGS_ASSERT_GV_AUTOLOAD_PVN;
1350 if (len == S_autolen && memEQ(name, S_autoload, S_autolen))
1353 if (SvTYPE(stash) < SVt_PVHV) {
1354 STRLEN packname_len = 0;
1355 const char * const packname_ptr = SvPV_const(MUTABLE_SV(stash), packname_len);
1356 packname = newSVpvn_flags(packname_ptr, packname_len,
1357 SVs_TEMP | SvUTF8(stash));
1361 packname = newSVhek_mortal(HvNAME_HEK(stash));
1362 if (flags & GV_SUPER) sv_catpvs(packname, "::SUPER");
1364 if (!(gv = gv_fetchmeth_pvn(stash, S_autoload, S_autolen, FALSE,
1365 is_utf8 | (flags & GV_SUPER))))
1369 if (!(CvROOT(cv) || CvXSUB(cv)))
1373 * Inheriting AUTOLOAD for non-methods no longer works
1376 !(flags & GV_AUTOLOAD_ISMETHOD)
1377 && (GvCVGEN(gv) || GvSTASH(gv) != stash)
1379 Perl_croak(aTHX_ "Use of inherited AUTOLOAD for non-method %" SVf
1380 "::%" UTF8f "() is no longer allowed",
1382 UTF8fARG(is_utf8, len, name));
1385 /* Instead of forcing the XSUB to do another lookup for $AUTOLOAD
1386 * and split that value on the last '::', pass along the same data
1387 * via the SvPVX field in the CV, and the stash in CvSTASH.
1389 * Due to an unfortunate accident of history, the SvPVX field
1390 * serves two purposes. It is also used for the subroutine's
1391 * prototype. Since SvPVX has been documented as returning the sub
1392 * name for a long time, but not as returning the prototype, we have to
1393 * preserve the SvPVX AUTOLOAD behaviour and put the prototype
1396 * We put the prototype in the same allocated buffer, but after
1397 * the sub name. The SvPOK flag indicates the presence of a proto-
1398 * type. The CvAUTOLOAD flag indicates the presence of a sub name.
1399 * If both flags are on, then SvLEN is used to indicate the end of
1400 * the prototype (artificially lower than what is actually allo-
1401 * cated), at the risk of having to reallocate a few bytes unneces-
1402 * sarily--but that should happen very rarely, if ever.
1404 * We use SvUTF8 for both prototypes and sub names, so if one is
1405 * UTF8, the other must be upgraded.
1407 CvSTASH_set(cv, stash);
1408 if (SvPOK(cv)) { /* Ouch! */
1409 SV * const tmpsv = newSVpvn_flags(name, len, is_utf8);
1411 const char *proto = CvPROTO(cv);
1414 sv_utf8_upgrade_flags_grow(tmpsv, 0, CvPROTOLEN(cv) + 2);
1415 ulen = SvCUR(tmpsv);
1416 SvCUR_set(tmpsv, SvCUR(tmpsv) + 1); /* include null in string */
1418 tmpsv, proto, CvPROTOLEN(cv), SV_CATBYTES*!SvUTF8(cv)
1420 SvTEMP_on(tmpsv); /* Allow theft */
1421 sv_setsv_nomg((SV *)cv, tmpsv);
1423 SvREFCNT_dec_NN(tmpsv);
1424 SvLEN_set(cv, SvCUR(cv) + 1);
1425 SvCUR_set(cv, ulen);
1428 sv_setpvn((SV *)cv, name, len);
1432 else SvUTF8_off(cv);
1438 * Given &FOO::AUTOLOAD, set $FOO::AUTOLOAD to desired function name.
1439 * The subroutine's original name may not be "AUTOLOAD", so we don't
1440 * use that, but for lack of anything better we will use the sub's
1441 * original package to look up $AUTOLOAD.
1443 varstash = CvNAMED(cv) ? CvSTASH(cv) : GvSTASH(CvGV(cv));
1444 vargv = *(GV**)hv_fetch(varstash, S_autoload, S_autolen, TRUE);
1448 gv_init_pvn(vargv, varstash, S_autoload, S_autolen, 0);
1449 #ifdef PERL_DONT_CREATE_GVSV
1450 GvSV(vargv) = newSV_type(SVt_NULL);
1454 varsv = GvSVn(vargv);
1455 SvTAINTED_off(varsv); /* previous $AUTOLOAD taint is obsolete */
1456 /* XXX: this process is not careful to avoid extra magic gets and sets; tied $AUTOLOAD will get noise */
1457 sv_setsv(varsv, packname);
1458 sv_catpvs(varsv, "::");
1459 /* Ensure SvSETMAGIC() is called if necessary. In particular, to clear
1460 tainting if $FOO::AUTOLOAD was previously tainted, but is not now. */
1463 SV_SMAGIC|(is_utf8 ? SV_CATUTF8 : SV_CATBYTES)
1471 /* require_tie_mod() internal routine for requiring a module
1472 * that implements the logic of automatic ties like %! and %-
1473 * It loads the module and then calls the _tie_it subroutine
1474 * with the passed gv as an argument.
1476 * The "gv" parameter should be the glob.
1477 * "varname" holds the 1-char name of the var, used for error messages.
1478 * "namesv" holds the module name. Its refcount will be decremented.
1479 * "flags": if flag & 1 then save the scalar before loading.
1480 * For the protection of $! to work (it is set by this routine)
1481 * the sv slot must already be magicalized.
1484 S_require_tie_mod(pTHX_ GV *gv, const char varname, const char * name,
1485 STRLEN len, const U32 flags)
1487 const SV * const target = varname == '[' ? GvSV(gv) : (SV *)GvHV(gv);
1489 PERL_ARGS_ASSERT_REQUIRE_TIE_MOD;
1491 /* If it is not tied */
1492 if (!target || !SvRMAGICAL(target)
1494 varname == '[' ? PERL_MAGIC_tiedscalar : PERL_MAGIC_tied))
1500 PUSHSTACKi(PERLSI_MAGIC);
1503 #define GET_HV_FETCH_TIE_FUNC \
1504 ( (gvp = (GV **)hv_fetchs(stash, "_tie_it", 0)) \
1506 && ( (isGV(*gvp) && GvCV(*gvp)) \
1507 || (SvROK(*gvp) && SvTYPE(SvRV(*gvp)) == SVt_PVCV) ) \
1510 /* Load the module if it is not loaded. */
1511 if (!(stash = gv_stashpvn(name, len, 0))
1512 || ! GET_HV_FETCH_TIE_FUNC)
1514 SV * const module = newSVpvn(name, len);
1515 const char type = varname == '[' ? '$' : '%';
1518 Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT, module, NULL);
1519 assert(sp == PL_stack_sp);
1520 stash = gv_stashpvn(name, len, 0);
1522 Perl_croak(aTHX_ "panic: Can't use %c%c because %s is not available",
1523 type, varname, name);
1524 else if (! GET_HV_FETCH_TIE_FUNC)
1525 Perl_croak(aTHX_ "panic: Can't use %c%c because %s does not define _tie_it",
1526 type, varname, name);
1528 /* Now call the tie function. It should be in *gvp. */
1529 assert(gvp); assert(*gvp);
1533 call_sv((SV *)*gvp, G_VOID|G_DISCARD);
1539 /* add a require_tie_mod_s - the _s suffix is similar to pvs type suffixes,
1540 * IOW it means we do STR_WITH_LEN() ourselves and the user should pass in
1541 * a true string WITHOUT a len.
1543 #define require_tie_mod_s(gv, varname, name, flags) \
1544 S_require_tie_mod(aTHX_ gv, varname, STR_WITH_LEN(name), flags)
1547 =for apidoc gv_stashpv
1549 Returns a pointer to the stash for a specified package. Uses C<strlen> to
1550 determine the length of C<name>, then calls C<gv_stashpvn()>.
1556 Perl_gv_stashpv(pTHX_ const char *name, I32 create)
1558 PERL_ARGS_ASSERT_GV_STASHPV;
1559 return gv_stashpvn(name, strlen(name), create);
1563 =for apidoc gv_stashpvn
1565 Returns a pointer to the stash for a specified package. The C<namelen>
1566 parameter indicates the length of the C<name>, in bytes. C<flags> is passed
1567 to C<gv_fetchpvn_flags()>, so if set to C<GV_ADD> then the package will be
1568 created if it does not already exist. If the package does not exist and
1569 C<flags> is 0 (or any other setting that does not create packages) then C<NULL>
1572 Flags may be one of:
1574 GV_ADD Create and initialize the package if doesn't
1576 GV_NOADD_NOINIT Don't create the package,
1577 GV_ADDMG GV_ADD iff the GV is magical
1578 GV_NOINIT GV_ADD, but don't initialize
1579 GV_NOEXPAND Don't expand SvOK() entries to PVGV
1580 SVf_UTF8 The name is in UTF-8
1582 The most important of which are probably C<GV_ADD> and C<SVf_UTF8>.
1584 Note, use of C<gv_stashsv> instead of C<gv_stashpvn> where possible is strongly
1585 recommended for performance reasons.
1587 =for apidoc Amnh||GV_ADD
1588 =for apidoc Amnh||GV_NOADD_NOINIT
1589 =for apidoc Amnh||GV_NOINIT
1590 =for apidoc Amnh||GV_NOEXPAND
1591 =for apidoc Amnh||GV_ADDMG
1592 =for apidoc Amnh||SVf_UTF8
1598 gv_stashpvn_internal
1600 Perform the internal bits of gv_stashsvpvn_cached. You could think of this
1601 as being one half of the logic. Not to be called except from gv_stashsvpvn_cached().
1605 PERL_STATIC_INLINE HV*
1606 S_gv_stashpvn_internal(pTHX_ const char *name, U32 namelen, I32 flags)
1612 U32 tmplen = namelen + 2;
1614 PERL_ARGS_ASSERT_GV_STASHPVN_INTERNAL;
1616 if (tmplen <= sizeof smallbuf)
1619 Newx(tmpbuf, tmplen, char);
1620 Copy(name, tmpbuf, namelen, char);
1621 tmpbuf[namelen] = ':';
1622 tmpbuf[namelen+1] = ':';
1623 tmpgv = gv_fetchpvn_flags(tmpbuf, tmplen, flags, SVt_PVHV);
1624 if (tmpbuf != smallbuf)
1626 if (!tmpgv || !isGV_with_GP(tmpgv))
1628 stash = GvHV(tmpgv);
1629 if (!(flags & ~GV_NOADD_MASK) && !stash) return NULL;
1631 if (!HvHasNAME(stash)) {
1632 hv_name_set(stash, name, namelen, flags & SVf_UTF8 ? SVf_UTF8 : 0 );
1634 /* FIXME: This is a repeat of logic in gv_fetchpvn_flags */
1635 /* If the containing stash has multiple effective
1636 names, see that this one gets them, too. */
1637 if (HvAUX(GvSTASH(tmpgv))->xhv_name_count)
1638 mro_package_moved(stash, NULL, tmpgv, 1);
1644 =for apidoc gv_stashsvpvn_cached
1646 Returns a pointer to the stash for a specified package, possibly
1647 cached. Implements both L<perlapi/C<gv_stashpvn>> and
1648 L<perlapi/C<gv_stashsv>>.
1650 Requires one of either C<namesv> or C<namepv> to be non-null.
1652 If the flag C<GV_CACHE_ONLY> is set, return the stash only if found in the
1653 cache; see L<perlapi/C<gv_stashpvn>> for details on the other C<flags>.
1655 Note it is strongly preferred for C<namesv> to be non-null, for performance
1658 =for apidoc Emnh||GV_CACHE_ONLY
1663 #define PERL_ARGS_ASSERT_GV_STASHSVPVN_CACHED \
1664 assert(namesv || name)
1667 Perl_gv_stashsvpvn_cached(pTHX_ SV *namesv, const char *name, U32 namelen, I32 flags)
1672 PERL_ARGS_ASSERT_GV_STASHSVPVN_CACHED;
1674 he = (HE *)hv_common(
1675 PL_stashcache, namesv, name, namelen,
1676 (flags & SVf_UTF8) ? HVhek_UTF8 : 0, 0, NULL, 0
1683 hv = INT2PTR(HV*, SvIVX(sv));
1684 assert(SvTYPE(hv) == SVt_PVHV);
1687 else if (flags & GV_CACHE_ONLY) return NULL;
1690 if (SvOK(namesv)) { /* prevent double uninit warning */
1692 name = SvPV_const(namesv, len);
1694 flags |= SvUTF8(namesv);
1696 name = ""; namelen = 0;
1699 stash = gv_stashpvn_internal(name, namelen, flags);
1701 if (stash && namelen) {
1702 SV* const ref = newSViv(PTR2IV(stash));
1703 (void)hv_store(PL_stashcache, name,
1704 (flags & SVf_UTF8) ? -(I32)namelen : (I32)namelen, ref, 0);
1711 Perl_gv_stashpvn(pTHX_ const char *name, U32 namelen, I32 flags)
1713 PERL_ARGS_ASSERT_GV_STASHPVN;
1714 return gv_stashsvpvn_cached(NULL, name, namelen, flags);
1718 =for apidoc gv_stashsv
1720 Returns a pointer to the stash for a specified package. See
1723 Note this interface is strongly preferred over C<gv_stashpvn> for performance
1730 Perl_gv_stashsv(pTHX_ SV *sv, I32 flags)
1732 PERL_ARGS_ASSERT_GV_STASHSV;
1733 return gv_stashsvpvn_cached(sv, NULL, 0, flags);
1736 Perl_gv_fetchpv(pTHX_ const char *nambeg, I32 flags, const svtype sv_type) {
1737 PERL_ARGS_ASSERT_GV_FETCHPV;
1738 return gv_fetchpvn_flags(nambeg, strlen(nambeg), flags, sv_type);
1742 Perl_gv_fetchsv(pTHX_ SV *name, I32 flags, const svtype sv_type) {
1744 const char * const nambeg =
1745 SvPV_flags_const(name, len, flags & GV_NO_SVGMAGIC ? 0 : SV_GMAGIC);
1746 PERL_ARGS_ASSERT_GV_FETCHSV;
1747 return gv_fetchpvn_flags(nambeg, len, flags | SvUTF8(name), sv_type);
1750 PERL_STATIC_INLINE void
1751 S_gv_magicalize_isa(pTHX_ GV *gv)
1755 PERL_ARGS_ASSERT_GV_MAGICALIZE_ISA;
1759 sv_magic(MUTABLE_SV(av), MUTABLE_SV(gv), PERL_MAGIC_isa,
1763 /* This function grabs name and tries to split a stash and glob
1764 * from its contents. TODO better description, comments
1766 * If the function returns TRUE and 'name == name_end', then
1767 * 'gv' can be directly returned to the caller of gv_fetchpvn_flags
1769 PERL_STATIC_INLINE bool
1770 S_parse_gv_stash_name(pTHX_ HV **stash, GV **gv, const char **name,
1771 STRLEN *len, const char *nambeg, STRLEN full_len,
1772 const U32 is_utf8, const I32 add)
1774 char *tmpfullbuf = NULL; /* only malloc one big chunk of memory when the smallbuff is not large enough */
1775 const char *name_cursor;
1776 const char *const name_end = nambeg + full_len;
1777 const char *const name_em1 = name_end - 1;
1778 char smallbuf[64]; /* small buffer to avoid a malloc when possible */
1780 PERL_ARGS_ASSERT_PARSE_GV_STASH_NAME;
1784 && isIDFIRST_lazy_if_safe(*name + 1, name_end, is_utf8))
1786 /* accidental stringify on a GV? */
1790 for (name_cursor = *name; name_cursor < name_end; name_cursor++) {
1791 if (name_cursor < name_em1 &&
1792 ((*name_cursor == ':' && name_cursor[1] == ':')
1793 || *name_cursor == '\''))
1796 *stash = PL_defstash;
1797 if (!*stash || !SvREFCNT(*stash)) /* symbol table under destruction */
1800 *len = name_cursor - *name;
1801 if (name_cursor > nambeg) { /* Skip for initial :: or ' */
1804 if (*name_cursor == ':') {
1808 else { /* using ' for package separator */
1809 /* use our pre-allocated buffer when possible to save a malloc */
1811 if ( *len+2 <= sizeof smallbuf)
1814 /* only malloc once if needed */
1815 if (tmpfullbuf == NULL) /* only malloc&free once, a little more than needed */
1816 Newx(tmpfullbuf, full_len+2, char);
1817 tmpbuf = tmpfullbuf;
1819 Copy(*name, tmpbuf, *len, char);
1820 tmpbuf[(*len)++] = ':';
1821 tmpbuf[(*len)++] = ':';
1824 gvp = (GV**)hv_fetch(*stash, key, is_utf8 ? -((I32)*len) : (I32)*len, add);
1825 *gv = gvp ? *gvp : NULL;
1826 if (!*gv || *gv == (const GV *)&PL_sv_undef) {
1829 /* here we know that *gv && *gv != &PL_sv_undef */
1830 if (SvTYPE(*gv) != SVt_PVGV)
1831 gv_init_pvn(*gv, *stash, key, *len, (add & GV_ADDMULTI)|is_utf8);
1835 if (!(*stash = GvHV(*gv))) {
1836 *stash = GvHV(*gv) = newHV();
1837 if (!HvHasNAME(*stash)) {
1838 if (GvSTASH(*gv) == PL_defstash && *len == 6
1839 && strBEGINs(*name, "CORE"))
1840 hv_name_sets(*stash, "CORE", 0);
1843 *stash, nambeg, name_cursor-nambeg, is_utf8
1845 /* If the containing stash has multiple effective
1846 names, see that this one gets them, too. */
1847 if (HvAUX(GvSTASH(*gv))->xhv_name_count)
1848 mro_package_moved(*stash, NULL, *gv, 1);
1851 else if (!HvHasNAME(*stash))
1852 hv_name_set(*stash, nambeg, name_cursor - nambeg, is_utf8);
1855 if (*name_cursor == ':')
1857 *name = name_cursor+1;
1858 if (*name == name_end) {
1860 *gv = MUTABLE_GV(*hv_fetchs(PL_defstash, "main::", TRUE));
1861 if (SvTYPE(*gv) != SVt_PVGV) {
1862 gv_init_pvn(*gv, PL_defstash, "main::", 6,
1865 MUTABLE_HV(SvREFCNT_inc_simple(PL_defstash));
1872 *len = name_cursor - *name;
1874 Safefree(tmpfullbuf); /* free our tmpfullbuf if it was used */
1877 Safefree(tmpfullbuf); /* free our tmpfullbuf if it was used */
1882 /* Checks if an unqualified name is in the main stash */
1883 PERL_STATIC_INLINE bool
1884 S_gv_is_in_main(pTHX_ const char *name, STRLEN len, const U32 is_utf8)
1886 PERL_ARGS_ASSERT_GV_IS_IN_MAIN;
1888 /* If it's an alphanumeric variable */
1889 if ( len && isIDFIRST_lazy_if_safe(name, name + len, is_utf8) ) {
1890 /* Some "normal" variables are always in main::,
1891 * like INC or STDOUT.
1899 if ((name[0] == 'I' && name[1] == 'N' && name[2] == 'C')
1900 || (name[0] == 'E' && name[1] == 'N' && name[2] == 'V')
1901 || (name[0] == 'S' && name[1] == 'I' && name[2] == 'G'))
1905 if (name[0] == 'A' && name[1] == 'R' && name[2] == 'G'
1910 if (name[0] == 'S' && name[1] == 'T' && name[2] == 'D'
1911 && name[3] == 'I' && name[4] == 'N')
1915 if ((name[0] == 'S' && name[1] == 'T' && name[2] == 'D')
1916 &&((name[3] == 'O' && name[4] == 'U' && name[5] == 'T')
1917 ||(name[3] == 'E' && name[4] == 'R' && name[5] == 'R')))
1921 if (name[0] == 'A' && name[1] == 'R' && name[2] == 'G'
1922 && name[3] == 'V' && name[4] == 'O' && name[5] == 'U'
1928 /* *{""}, or a special variable like $@ */
1936 /* This function is called if parse_gv_stash_name() failed to
1937 * find a stash, or if GV_NOTQUAL or an empty name was passed
1938 * to gv_fetchpvn_flags.
1940 * It returns FALSE if the default stash can't be found nor created,
1941 * which might happen during global destruction.
1943 PERL_STATIC_INLINE bool
1944 S_find_default_stash(pTHX_ HV **stash, const char *name, STRLEN len,
1945 const U32 is_utf8, const I32 add,
1946 const svtype sv_type)
1948 PERL_ARGS_ASSERT_FIND_DEFAULT_STASH;
1950 /* No stash in name, so see how we can default */
1952 if ( gv_is_in_main(name, len, is_utf8) ) {
1953 *stash = PL_defstash;
1956 if (IN_PERL_COMPILETIME) {
1957 *stash = PL_curstash;
1958 if (add && (PL_hints & HINT_STRICT_VARS) &&
1959 sv_type != SVt_PVCV &&
1960 sv_type != SVt_PVGV &&
1961 sv_type != SVt_PVFM &&
1962 sv_type != SVt_PVIO &&
1963 !(len == 1 && sv_type == SVt_PV &&
1964 (*name == 'a' || *name == 'b')) )
1966 GV**gvp = (GV**)hv_fetch(*stash,name,is_utf8 ? -(I32)len : (I32)len,0);
1967 if (!gvp || *gvp == (const GV *)&PL_sv_undef ||
1968 SvTYPE(*gvp) != SVt_PVGV)
1972 else if ((sv_type == SVt_PV && !GvIMPORTED_SV(*gvp)) ||
1973 (sv_type == SVt_PVAV && !GvIMPORTED_AV(*gvp)) ||
1974 (sv_type == SVt_PVHV && !GvIMPORTED_HV(*gvp)) )
1976 /* diag_listed_as: Variable "%s" is not imported%s */
1978 aTHX_ packWARN(WARN_MISC),
1979 "Variable \"%c%" UTF8f "\" is not imported",
1980 sv_type == SVt_PVAV ? '@' :
1981 sv_type == SVt_PVHV ? '%' : '$',
1982 UTF8fARG(is_utf8, len, name));
1985 aTHX_ packWARN(WARN_MISC),
1986 "\t(Did you mean &%" UTF8f " instead?)\n",
1987 UTF8fARG(is_utf8, len, name)
1994 /* Use the current op's stash */
1995 *stash = CopSTASH(PL_curcop);
2000 if (add && !PL_in_clean_all) {
2002 qerror(Perl_mess(aTHX_
2003 "Global symbol \"%s%" UTF8f
2004 "\" requires explicit package name (did you forget to "
2005 "declare \"my %s%" UTF8f "\"?)",
2006 (sv_type == SVt_PV ? "$"
2007 : sv_type == SVt_PVAV ? "@"
2008 : sv_type == SVt_PVHV ? "%"
2009 : ""), UTF8fARG(is_utf8, len, name),
2010 (sv_type == SVt_PV ? "$"
2011 : sv_type == SVt_PVAV ? "@"
2012 : sv_type == SVt_PVHV ? "%"
2013 : ""), UTF8fARG(is_utf8, len, name)));
2014 /* To maintain the output of errors after the strict exception
2015 * above, and to keep compat with older releases, rather than
2016 * placing the variables in the pad, we place
2017 * them in the <none>:: stash.
2019 gv = gv_fetchpvs("<none>::", GV_ADDMULTI, SVt_PVHV);
2021 /* symbol table under destruction */
2030 if (!SvREFCNT(*stash)) /* symbol table under destruction */
2036 /* gv_magicalize only turns on the SVf_READONLY flag, not SVf_PROTECT. So
2037 redefine SvREADONLY_on for that purpose. We don’t use it later on in
2039 #undef SvREADONLY_on
2040 #define SvREADONLY_on(sv) (SvFLAGS(sv) |= SVf_READONLY)
2042 /* gv_magicalize() is called by gv_fetchpvn_flags when creating
2044 * Note that it does not insert the GV into the stash prior to
2045 * magicalization, which some variables require need in order
2046 * to work (like %+, %-, %!), so callers must take care of
2049 * It returns true if the gv did turn out to be magical one; i.e.,
2050 * if gv_magicalize actually did something.
2052 PERL_STATIC_INLINE bool
2053 S_gv_magicalize(pTHX_ GV *gv, HV *stash, const char *name, STRLEN len,
2054 const svtype sv_type)
2058 PERL_ARGS_ASSERT_GV_MAGICALIZE;
2060 if (stash != PL_defstash) { /* not the main stash */
2061 /* We only have to check for a few names here: a, b, EXPORT, ISA
2062 and VERSION. All the others apply only to the main stash or to
2063 CORE (which is checked right after this). */
2068 len >= 6 && name[1] == 'X' &&
2069 (memEQs(name, len, "EXPORT")
2070 ||memEQs(name, len, "EXPORT_OK")
2071 ||memEQs(name, len, "EXPORT_FAIL")
2072 ||memEQs(name, len, "EXPORT_TAGS"))
2077 if (memEQs(name, len, "ISA"))
2078 gv_magicalize_isa(gv);
2081 if (memEQs(name, len, "VERSION"))
2085 if (stash == PL_debstash && memEQs(name, len, "args")) {
2086 GvMULTI_on(gv_AVadd(gv));
2091 if (len == 1 && sv_type == SVt_PV)
2100 if (len > 1 /* shortest is uc */ && HvNAMELEN_get(stash) == 4) {
2101 /* Avoid null warning: */
2102 const char * const stashname = HvNAME(stash); assert(stashname);
2103 if (strBEGINs(stashname, "CORE"))
2104 S_maybe_add_coresub(aTHX_ 0, gv, name, len);
2111 /* Nothing else to do.
2112 The compiler will probably turn the switch statement into a
2113 branch table. Make sure we avoid even that small overhead for
2114 the common case of lower case variable names. (On EBCDIC
2115 platforms, we can't just do:
2116 if (NATIVE_TO_ASCII(*name) > NATIVE_TO_ASCII('V') ) {
2117 because cases like '\027' in the switch statement below are
2118 C1 (non-ASCII) controls on those platforms, so the remapping
2119 would make them larger than 'V')
2126 if (memEQs(name, len, "ARGV")) {
2127 IoFLAGS(GvIOn(gv)) |= IOf_ARGV|IOf_START;
2129 else if (memEQs(name, len, "ARGVOUT")) {
2135 len >= 6 && name[1] == 'X' &&
2136 (memEQs(name, len, "EXPORT")
2137 ||memEQs(name, len, "EXPORT_OK")
2138 ||memEQs(name, len, "EXPORT_FAIL")
2139 ||memEQs(name, len, "EXPORT_TAGS"))
2144 if (memEQs(name, len, "ISA")) {
2145 gv_magicalize_isa(gv);
2149 if (memEQs(name, len, "SIG")) {
2152 if (!PL_psig_name) {
2153 Newxz(PL_psig_name, 2 * SIG_SIZE, SV*);
2154 Newxz(PL_psig_pend, SIG_SIZE, int);
2155 PL_psig_ptr = PL_psig_name + SIG_SIZE;
2157 /* I think that the only way to get here is to re-use an
2158 embedded perl interpreter, where the previous
2159 use didn't clean up fully because
2160 PL_perl_destruct_level was 0. I'm not sure that we
2161 "support" that, in that I suspect in that scenario
2162 there are sufficient other garbage values left in the
2163 interpreter structure that something else will crash
2164 before we get here. I suspect that this is one of
2165 those "doctor, it hurts when I do this" bugs. */
2166 Zero(PL_psig_name, 2 * SIG_SIZE, SV*);
2167 Zero(PL_psig_pend, SIG_SIZE, int);
2171 hv_magic(hv, NULL, PERL_MAGIC_sig);
2172 for (i = 1; i < SIG_SIZE; i++) {
2173 SV * const * const init = hv_fetch(hv, PL_sig_name[i], strlen(PL_sig_name[i]), 1);
2175 sv_setsv(*init, &PL_sv_undef);
2180 if (memEQs(name, len, "VERSION"))
2183 case '\003': /* $^CHILD_ERROR_NATIVE */
2184 if (memEQs(name, len, "\003HILD_ERROR_NATIVE"))
2186 /* @{^CAPTURE} %{^CAPTURE} */
2187 if (memEQs(name, len, "\003APTURE")) {
2188 AV* const av = GvAVn(gv);
2189 const Size_t n = *name;
2191 sv_magic(MUTABLE_SV(av), (SV*)n, PERL_MAGIC_regdata, NULL, 0);
2194 require_tie_mod_s(gv, '+', "Tie::Hash::NamedCapture",0);
2196 } else /* %{^CAPTURE_ALL} */
2197 if (memEQs(name, len, "\003APTURE_ALL")) {
2198 require_tie_mod_s(gv, '-', "Tie::Hash::NamedCapture",0);
2201 case '\005': /* $^ENCODING */
2202 if (memEQs(name, len, "\005NCODING"))
2205 case '\007': /* $^GLOBAL_PHASE */
2206 if (memEQs(name, len, "\007LOBAL_PHASE"))
2209 case '\014': /* $^LAST_FH */
2210 if (memEQs(name, len, "\014AST_FH"))
2213 case '\015': /* $^MATCH */
2214 if (memEQs(name, len, "\015ATCH")) {
2215 paren = RX_BUFF_IDX_CARET_FULLMATCH;
2219 case '\017': /* $^OPEN */
2220 if (memEQs(name, len, "\017PEN"))
2223 case '\020': /* $^PREMATCH $^POSTMATCH */
2224 if (memEQs(name, len, "\020REMATCH")) {
2225 paren = RX_BUFF_IDX_CARET_PREMATCH;
2228 if (memEQs(name, len, "\020OSTMATCH")) {
2229 paren = RX_BUFF_IDX_CARET_POSTMATCH;
2234 if (memEQs(name, len, "\023AFE_LOCALES"))
2237 case '\024': /* ${^TAINT} */
2238 if (memEQs(name, len, "\024AINT"))
2241 case '\025': /* ${^UNICODE}, ${^UTF8LOCALE} */
2242 if (memEQs(name, len, "\025NICODE"))
2244 if (memEQs(name, len, "\025TF8LOCALE"))
2246 if (memEQs(name, len, "\025TF8CACHE"))
2249 case '\027': /* $^WARNING_BITS */
2250 if (memEQs(name, len, "\027ARNING_BITS"))
2253 else if (memEQs(name, len, "\027IN32_SLOPPY_STAT"))
2267 /* Ensures that we have an all-digit variable, ${"1foo"} fails
2270 if (!grok_atoUV(name, &uv, NULL) || uv > I32_MAX)
2272 /* XXX why are we using a SSize_t? */
2273 paren = (SSize_t)(I32)uv;
2279 /* Names of length 1. (Or 0. But name is NUL terminated, so that will
2280 be case '\0' in this switch statement (ie a default case) */
2283 paren = RX_BUFF_IDX_FULLMATCH;
2286 paren = RX_BUFF_IDX_PREMATCH;
2289 paren = RX_BUFF_IDX_POSTMATCH;
2291 #ifdef PERL_SAWAMPERSAND
2293 sv_type == SVt_PVAV ||
2294 sv_type == SVt_PVHV ||
2295 sv_type == SVt_PVCV ||
2296 sv_type == SVt_PVFM ||
2298 )) { PL_sawampersand |=
2302 ? SAWAMPERSAND_MIDDLE
2303 : SAWAMPERSAND_RIGHT;
2316 paren = *name - '0';
2319 /* Flag the capture variables with a NULL mg_ptr
2320 Use mg_len for the array index to lookup. */
2321 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, NULL, paren);
2325 sv_setpv(GvSVn(gv),PL_chopset);
2329 #ifdef COMPLEX_STATUS
2330 SvUPGRADE(GvSVn(gv), SVt_PVLV);
2336 /* If %! has been used, automatically load Errno.pm. */
2338 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, name, len);
2340 /* magicalization must be done before require_tie_mod_s is called */
2341 if (sv_type == SVt_PVHV || sv_type == SVt_PVGV)
2342 require_tie_mod_s(gv, '!', "Errno", 1);
2345 case '-': /* $-, %-, @- */
2346 case '+': /* $+, %+, @+ */
2347 GvMULTI_on(gv); /* no used once warnings here */
2349 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, name, len);
2351 SvREADONLY_on(GvSVn(gv));
2354 if (sv_type == SVt_PVHV || sv_type == SVt_PVGV)
2355 require_tie_mod_s(gv, *name, "Tie::Hash::NamedCapture",0);
2358 AV* const av = GvAVn(gv);
2359 const Size_t n = *name;
2361 sv_magic(MUTABLE_SV(av), (SV*)n, PERL_MAGIC_regdata, NULL, 0);
2367 if (sv_type == SVt_PV)
2368 /* diag_listed_as: $* is no longer supported as of Perl 5.30 */
2369 Perl_croak(aTHX_ "$%c is no longer supported as of Perl 5.30", *name);
2371 case '\010': /* $^H */
2373 HV *const hv = GvHVn(gv);
2374 hv_magic(hv, NULL, PERL_MAGIC_hints);
2377 case '\023': /* $^S */
2379 SvREADONLY_on(GvSVn(gv));
2396 case '\001': /* $^A */
2397 case '\003': /* $^C */
2398 case '\004': /* $^D */
2399 case '\005': /* $^E */
2400 case '\006': /* $^F */
2401 case '\011': /* $^I, NOT \t in EBCDIC */
2402 case '\016': /* $^N */
2403 case '\017': /* $^O */
2404 case '\020': /* $^P */
2405 case '\024': /* $^T */
2406 case '\027': /* $^W */
2408 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, name, len);
2411 case '\014': /* $^L */
2412 sv_setpvs(GvSVn(gv),"\f");
2415 sv_setpvs(GvSVn(gv),"\034");
2419 SV * const sv = GvSV(gv);
2420 if (!sv_derived_from(PL_patchlevel, "version"))
2421 upg_version(PL_patchlevel, TRUE);
2422 GvSV(gv) = vnumify(PL_patchlevel);
2423 SvREADONLY_on(GvSV(gv));
2427 case '\026': /* $^V */
2429 SV * const sv = GvSV(gv);
2430 GvSV(gv) = new_version(PL_patchlevel);
2431 SvREADONLY_on(GvSV(gv));
2437 if (sv_type == SVt_PV)
2443 /* Return true if we actually did something. */
2444 return GvAV(gv) || GvHV(gv) || GvIO(gv) || GvCV(gv)
2446 SvOK(GvSV(gv)) || SvMAGICAL(GvSV(gv))
2451 /* If we do ever start using this later on in the file, we need to make
2452 sure we don’t accidentally use the wrong definition. */
2453 #undef SvREADONLY_on
2455 /* This function is called when the stash already holds the GV of the magic
2456 * variable we're looking for, but we need to check that it has the correct
2457 * kind of magic. For example, if someone first uses $! and then %!, the
2458 * latter would end up here, and we add the Errno tie to the HASH slot of
2461 PERL_STATIC_INLINE void
2462 S_maybe_multimagic_gv(pTHX_ GV *gv, const char *name, const svtype sv_type)
2464 PERL_ARGS_ASSERT_MAYBE_MULTIMAGIC_GV;
2466 if (sv_type == SVt_PVHV || sv_type == SVt_PVGV) {
2468 require_tie_mod_s(gv, '!', "Errno", 1);
2469 else if (*name == '-' || *name == '+')
2470 require_tie_mod_s(gv, *name, "Tie::Hash::NamedCapture", 0);
2471 } else if (sv_type == SVt_PV) {
2472 if (*name == '*' || *name == '#') {
2473 /* diag_listed_as: $* is no longer supported as of Perl 5.30 */
2474 Perl_croak(aTHX_ "$%c is no longer supported as of Perl 5.30", *name);
2477 if (sv_type==SVt_PV || sv_type==SVt_PVGV) {
2479 #ifdef PERL_SAWAMPERSAND
2481 PL_sawampersand |= SAWAMPERSAND_LEFT;
2485 PL_sawampersand |= SAWAMPERSAND_MIDDLE;
2489 PL_sawampersand |= SAWAMPERSAND_RIGHT;
2498 =for apidoc gv_fetchpv
2499 =for apidoc_item |GV *|gv_fetchpvn|const char * nambeg|STRLEN full_len|I32 flags|const svtype sv_type
2500 =for apidoc_item ||gv_fetchpvn_flags
2501 =for apidoc_item |GV *|gv_fetchpvs|"name"|I32 flags|const svtype sv_type
2502 =for apidoc_item ||gv_fetchsv
2503 =for apidoc_item |GV *|gv_fetchsv_nomg|SV *name|I32 flags|const svtype sv_type
2505 These all return the GV of type C<sv_type> whose name is given by the inputs,
2506 or NULL if no GV of that name and type could be found. See L<perlguts/Stashes
2509 The only differences are how the input name is specified, and if 'get' magic is
2510 normally used in getting that name.
2512 Don't be fooled by the fact that only one form has C<flags> in its name. They
2513 all have a C<flags> parameter in fact, and all the flag bits have the same
2516 If any of the flags C<GV_ADD>, C<GV_ADDMG>, C<GV_ADDWARN>, C<GV_ADDMULTI>, or
2517 C<GV_NOINIT> is set, a GV is created if none already exists for the input name
2518 and type. However, C<GV_ADDMG> will only do the creation for magical GV's.
2519 For all of these flags except C<GV_NOINIT>, C<L</gv_init_pvn>> is called after
2520 the addition. C<GV_ADDWARN> is used when the caller expects that adding won't
2521 be necessary because the symbol should already exist; but if not, add it
2522 anyway, with a warning that it was unexpectedly absent. The C<GV_ADDMULTI>
2523 flag means to pretend that the GV has been seen before (I<i.e.>, suppress "Used
2526 The flag C<GV_NOADD_NOINIT> causes C<L</gv_init_pvn>> not be to called if the
2527 GV existed but isn't PVGV.
2529 If the C<SVf_UTF8> bit is set, the name is treated as being encoded in UTF-8;
2530 otherwise the name won't be considered to be UTF-8 in the C<pv>-named forms,
2531 and the UTF-8ness of the underlying SVs will be used in the C<sv> forms.
2533 If the flag C<GV_NOTQUAL> is set, the caller warrants that the input name is a
2534 plain symbol name, not qualified with a package, otherwise the name is checked
2535 for being a qualified one.
2537 In C<gv_fetchpv>, C<nambeg> is a C string, NUL-terminated with no intermediate
2540 In C<gv_fetchpvs>, C<name> is a literal C string, hence is enclosed in
2543 C<gv_fetchpvn> and C<gv_fetchpvn_flags> are identical. In these, <nambeg> is
2544 a Perl string whose byte length is given by C<full_len>, and may contain
2547 In C<gv_fetchsv> and C<gv_fetchsv_nomg>, the name is extracted from the PV of
2548 the input C<name> SV. The only difference between these two forms is that
2549 'get' magic is normally done on C<name> in C<gv_fetchsv>, and always skipped
2550 with C<gv_fetchsv_nomg>. Including C<GV_NO_SVGMAGIC> in the C<flags> parameter
2551 to C<gv_fetchsv> makes it behave identically to C<gv_fetchsv_nomg>.
2553 =for apidoc Amnh||GV_ADD
2554 =for apidoc Amnh||GV_ADDMG
2555 =for apidoc Amnh||GV_ADDMULTI
2556 =for apidoc Amnh||GV_ADDWARN
2557 =for apidoc Amnh||GV_NOINIT
2558 =for apidoc Amnh||GV_NOADD_NOINIT
2559 =for apidoc Amnh||GV_NOTQUAL
2560 =for apidoc Amnh||GV_NO_SVGMAGIC
2561 =for apidoc Amnh||SVf_UTF8
2567 Perl_gv_fetchpvn_flags(pTHX_ const char *nambeg, STRLEN full_len, I32 flags,
2568 const svtype sv_type)
2570 const char *name = nambeg;
2575 const I32 no_init = flags & (GV_NOADD_NOINIT | GV_NOINIT);
2576 const I32 no_expand = flags & GV_NOEXPAND;
2577 const I32 add = flags & ~GV_NOADD_MASK;
2578 const U32 is_utf8 = flags & SVf_UTF8;
2579 bool addmg = cBOOL(flags & GV_ADDMG);
2580 const char *const name_end = nambeg + full_len;
2583 PERL_ARGS_ASSERT_GV_FETCHPVN_FLAGS;
2585 /* If we have GV_NOTQUAL, the caller promised that
2586 * there is no stash, so we can skip the check.
2587 * Similarly if full_len is 0, since then we're
2588 * dealing with something like *{""} or ""->foo()
2590 if ((flags & GV_NOTQUAL) || !full_len) {
2593 else if (parse_gv_stash_name(&stash, &gv, &name, &len, nambeg, full_len, is_utf8, add)) {
2594 if (name == name_end) return gv;
2600 if (!stash && !find_default_stash(&stash, name, len, is_utf8, add, sv_type)) {
2604 /* By this point we should have a stash and a name */
2605 gvp = (GV**)hv_fetch(stash,name,is_utf8 ? -(I32)len : (I32)len,add);
2606 if (!gvp || *gvp == (const GV *)&PL_sv_undef) {
2607 if (addmg) gv = (GV *)newSV_type(SVt_NULL); /* tentatively */
2610 else gv = *gvp, addmg = 0;
2611 /* From this point on, addmg means gv has not been inserted in the
2614 if (SvTYPE(gv) == SVt_PVGV) {
2615 /* The GV already exists, so return it, but check if we need to do
2616 * anything else with it before that.
2619 /* This is the heuristic that handles if a variable triggers the
2620 * 'used only once' warning. If there's already a GV in the stash
2621 * with this name, then we assume that the variable has been used
2622 * before and turn its MULTI flag on.
2623 * It's a heuristic because it can easily be "tricked", like with
2624 * BEGIN { $a = 1; $::{foo} = *a }; () = $foo
2625 * not warning about $main::foo being used just once
2628 gv_init_svtype(gv, sv_type);
2629 /* You reach this path once the typeglob has already been created,
2630 either by the same or a different sigil. If this path didn't
2631 exist, then (say) referencing $! first, and %! second would
2632 mean that %! was not handled correctly. */
2633 if (len == 1 && stash == PL_defstash) {
2634 maybe_multimagic_gv(gv, name, sv_type);
2636 else if (sv_type == SVt_PVAV
2637 && memEQs(name, len, "ISA")
2638 && (!GvAV(gv) || !SvSMAGICAL(GvAV(gv))))
2639 gv_magicalize_isa(gv);
2642 } else if (no_init) {
2646 /* If GV_NOEXPAND is true and what we got off the stash is a ref,
2647 * don't expand it to a glob. This is an optimization so that things
2648 * copying constants over, like Exporter, don't have to be rewritten
2649 * to take into account that you can store more than just globs in
2652 else if (no_expand && SvROK(gv)) {
2657 /* Adding a new symbol.
2658 Unless of course there was already something non-GV here, in which case
2659 we want to behave as if there was always a GV here, containing some sort
2661 Otherwise we run the risk of creating things like GvIO, which can cause
2662 subtle bugs. eg the one that tripped up SQL::Translator */
2664 faking_it = SvOK(gv);
2666 if (add & GV_ADDWARN)
2667 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2668 "Had to create %" UTF8f " unexpectedly",
2669 UTF8fARG(is_utf8, name_end-nambeg, nambeg));
2670 gv_init_pvn(gv, stash, name, len, (add & GV_ADDMULTI)|is_utf8);
2673 && isIDFIRST_lazy_if_safe(name, name + full_len, is_utf8)
2674 && !ckWARN(WARN_ONCE) )
2679 /* set up magic where warranted */
2680 if ( gv_magicalize(gv, stash, name, len, sv_type) ) {
2683 /* gv_magicalize magicalised this gv, so we want it
2684 * stored in the symtab.
2685 * Effectively the caller is asking, ‘Does this gv exist?’
2686 * And we respond, ‘Er, *now* it does!’
2688 (void)hv_store(stash,name,len,(SV *)gv,0);
2692 /* The temporary GV created above */
2693 SvREFCNT_dec_NN(gv);
2697 if (gv) gv_init_svtype(gv, faking_it ? SVt_PVCV : sv_type);
2702 =for apidoc gv_efullname3
2703 =for apidoc_item gv_efullname4
2704 =for apidoc_item gv_fullname3
2705 =for apidoc_item gv_fullname4
2707 Place the full package name of C<gv> into C<sv>. The C<gv_e*> forms return
2708 instead the effective package name (see L</HvENAME>).
2710 If C<prefix> is non-NULL, it is considered to be a C language NUL-terminated
2711 string, and the stored name will be prefaced with it.
2713 The other difference between the functions is that the C<*4> forms have an
2714 extra parameter, C<keepmain>. If C<true> an initial C<main::> in the name is
2715 kept; if C<false> it is stripped. With the C<*3> forms, it is always kept.
2721 Perl_gv_fullname4(pTHX_ SV *sv, const GV *gv, const char *prefix, bool keepmain)
2724 const HV * const hv = GvSTASH(gv);
2726 PERL_ARGS_ASSERT_GV_FULLNAME4;
2728 sv_setpv(sv, prefix ? prefix : "");
2730 if (hv && (name = HvNAME(hv))) {
2731 const STRLEN len = HvNAMELEN(hv);
2732 if (keepmain || ! memBEGINs(name, len, "main")) {
2733 sv_catpvn_flags(sv,name,len,HvNAMEUTF8(hv)?SV_CATUTF8:SV_CATBYTES);
2737 else sv_catpvs(sv,"__ANON__::");
2738 sv_catsv(sv,newSVhek_mortal(GvNAME_HEK(gv)));
2742 Perl_gv_efullname4(pTHX_ SV *sv, const GV *gv, const char *prefix, bool keepmain)
2744 const GV * const egv = GvEGVx(gv);
2746 PERL_ARGS_ASSERT_GV_EFULLNAME4;
2748 gv_fullname4(sv, egv ? egv : gv, prefix, keepmain);
2752 /* recursively scan a stash and any nested stashes looking for entries
2753 * that need the "only used once" warning raised
2757 Perl_gv_check(pTHX_ HV *stash)
2761 PERL_ARGS_ASSERT_GV_CHECK;
2763 if (!HvHasAUX(stash))
2766 assert(HvARRAY(stash));
2768 /* mark stash is being scanned, to avoid recursing */
2769 HvAUX(stash)->xhv_aux_flags |= HvAUXf_SCAN_STASH;
2770 for (i = 0; i <= (I32) HvMAX(stash); i++) {
2772 for (entry = HvARRAY(stash)[i]; entry; entry = HeNEXT(entry)) {
2775 STRLEN keylen = HeKLEN(entry);
2776 const char * const key = HeKEY(entry);
2778 if (keylen >= 2 && key[keylen-2] == ':' && key[keylen-1] == ':' &&
2779 (gv = MUTABLE_GV(HeVAL(entry))) && isGV(gv) && (hv = GvHV(gv)))
2781 if (hv != PL_defstash && hv != stash
2783 && (HvAUX(hv)->xhv_aux_flags & HvAUXf_SCAN_STASH))
2785 gv_check(hv); /* nested package */
2787 else if ( HeKLEN(entry) != 0
2788 && *HeKEY(entry) != '_'
2789 && isIDFIRST_lazy_if_safe(HeKEY(entry),
2790 HeKEY(entry) + HeKLEN(entry),
2794 gv = MUTABLE_GV(HeVAL(entry));
2795 if (SvTYPE(gv) != SVt_PVGV || GvMULTI(gv))
2798 assert(PL_curcop == &PL_compiling);
2799 CopLINE_set(PL_curcop, GvLINE(gv));
2801 SAVECOPFILE_FREE(PL_curcop);
2802 CopFILE_set(PL_curcop, (char *)file); /* set for warning */
2804 CopFILEGV(PL_curcop)
2805 = gv_fetchfile_flags(file, HEK_LEN(GvFILE_HEK(gv)), 0);
2807 Perl_warner(aTHX_ packWARN(WARN_ONCE),
2808 "Name \"%" HEKf "::%" HEKf
2809 "\" used only once: possible typo",
2810 HEKfARG(HvNAME_HEK(stash)),
2811 HEKfARG(GvNAME_HEK(gv)));
2815 HvAUX(stash)->xhv_aux_flags &= ~HvAUXf_SCAN_STASH;
2819 =for apidoc newGVgen
2820 =for apidoc_item newGVgen_flags
2822 Create a new, guaranteed to be unique, GV in the package given by the
2823 NUL-terminated C language string C<pack>, and return a pointer to it.
2825 For C<newGVgen> or if C<flags> in C<newGVgen_flags> is 0, C<pack> is to be
2826 considered to be encoded in Latin-1. The only other legal C<flags> value is
2827 C<SVf_UTF8>, which indicates C<pack> is to be considered to be encoded in
2834 Perl_newGVgen_flags(pTHX_ const char *pack, U32 flags)
2836 PERL_ARGS_ASSERT_NEWGVGEN_FLAGS;
2837 assert(!(flags & ~SVf_UTF8));
2839 return gv_fetchpv(Perl_form(aTHX_ "%" UTF8f "::_GEN_%ld",
2840 UTF8fARG(flags, strlen(pack), pack),
2845 /* hopefully this is only called on local symbol table entries */
2848 Perl_gp_ref(pTHX_ GP *gp)
2855 /* If the GP they asked for a reference to contains
2856 a method cache entry, clear it first, so that we
2857 don't infect them with our cached entry */
2858 SvREFCNT_dec_NN(gp->gp_cv);
2867 Perl_gp_free(pTHX_ GV *gv)
2871 bool in_global_destruction = PL_phase == PERL_PHASE_DESTRUCT;
2873 if (!gv || !isGV_with_GP(gv) || !(gp = GvGP(gv)))
2875 if (gp->gp_refcnt == 0) {
2876 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2877 "Attempt to free unreferenced glob pointers"
2878 pTHX__FORMAT pTHX__VALUE);
2881 if (gp->gp_refcnt > 1) {
2883 if (gp->gp_egv == gv)
2891 /* Copy and null out all the glob slots, so destructors do not see
2893 HEK * const file_hek = gp->gp_file_hek;
2894 SV * sv = gp->gp_sv;
2895 AV * av = gp->gp_av;
2896 HV * hv = gp->gp_hv;
2897 IO * io = gp->gp_io;
2898 CV * cv = gp->gp_cv;
2899 CV * form = gp->gp_form;
2903 gp->gp_file_hek = NULL;
2912 unshare_hek(file_hek);
2914 /* Storing the SV on the temps stack (instead of freeing it immediately)
2915 is an admitted bodge that attempt to compensate for the lack of
2916 reference counting on the stack. The motivation is that typeglob syntax
2917 is extremely short hence programs such as '$a += (*a = 2)' are often
2918 found randomly by researchers running fuzzers. Previously these
2919 programs would trigger errors, that the researchers would
2920 (legitimately) report, and then we would spend time figuring out that
2921 the cause was "stack not reference counted" and so not a dangerous
2922 security hole. This consumed a lot of researcher time, our time, and
2923 prevents "interesting" security holes being uncovered.
2925 Typeglob assignment is rarely used in performance critical production
2926 code, so we aren't causing much slowdown by doing extra work here.
2928 In turn, the need to check for SvOBJECT (and references to objects) is
2929 because we have regression tests that rely on timely destruction that
2930 happens *within this while loop* to demonstrate behaviour, and
2931 potentially there is also *working* code in the wild that relies on
2934 And we need to avoid doing this in global destruction else we can end
2935 up with "Attempt to free temp prematurely ... Unbalanced string table
2938 Hence the whole thing is a heuristic intended to mitigate against
2939 simple problems likely found by fuzzers but never written by humans,
2940 whilst leaving working code unchanged. */
2943 if (SvREFCNT(sv) > 1 || SvOBJECT(sv) || UNLIKELY(in_global_destruction)) {
2944 SvREFCNT_dec_NN(sv);
2946 } else if (SvROK(sv) && (referent = SvRV(sv))
2947 && (SvREFCNT(referent) > 1 || SvOBJECT(referent))) {
2948 SvREFCNT_dec_NN(sv);
2955 if (SvREFCNT(av) > 1 || SvOBJECT(av) || UNLIKELY(in_global_destruction)) {
2956 SvREFCNT_dec_NN(av);
2962 /* FIXME - another reference loop GV -> symtab -> GV ?
2963 Somehow gp->gp_hv can end up pointing at freed garbage. */
2964 if (hv && SvTYPE(hv) == SVt_PVHV) {
2965 const HEK *hvname_hek = HvNAME_HEK(hv);
2966 if (PL_stashcache && hvname_hek) {
2967 DEBUG_o(Perl_deb(aTHX_
2968 "gp_free clearing PL_stashcache for '%" HEKf "'\n",
2969 HEKfARG(hvname_hek)));
2970 (void)hv_deletehek(PL_stashcache, hvname_hek, G_DISCARD);
2972 if (SvREFCNT(hv) > 1 || SvOBJECT(hv) || UNLIKELY(in_global_destruction)) {
2973 SvREFCNT_dec_NN(hv);
2979 if (io && SvREFCNT(io) == 1 && IoIFP(io)
2980 && (IoTYPE(io) == IoTYPE_WRONLY ||
2981 IoTYPE(io) == IoTYPE_RDWR ||
2982 IoTYPE(io) == IoTYPE_APPEND)
2983 && ckWARN_d(WARN_IO)
2984 && IoIFP(io) != PerlIO_stdin()
2985 && IoIFP(io) != PerlIO_stdout()
2986 && IoIFP(io) != PerlIO_stderr()
2987 && !(IoFLAGS(io) & IOf_FAKE_DIRP))
2988 io_close(io, gv, FALSE, TRUE);
2990 if (SvREFCNT(io) > 1 || SvOBJECT(io) || UNLIKELY(in_global_destruction)) {
2991 SvREFCNT_dec_NN(io);
2998 if (SvREFCNT(cv) > 1 || SvOBJECT(cv) || UNLIKELY(in_global_destruction)) {
2999 SvREFCNT_dec_NN(cv);
3006 if (SvREFCNT(form) > 1 || SvOBJECT(form) || UNLIKELY(in_global_destruction)) {
3007 SvREFCNT_dec_NN(form);
3015 /* We don't strictly need to defer all this to the end, but it's
3016 easiest to do so. The subtle problems we have are
3017 1) any of the actions triggered by the various SvREFCNT_dec()s in
3018 any of the intermediate blocks can cause more items to be added
3019 to the temps stack. So we can't "cache" its state locally
3020 2) We'd have to re-check the "extend by 1?" for each time.
3021 Whereas if we don't NULL out the values that we want to put onto
3022 the save stack until here, we can do it in one go, with one
3025 SSize_t max_ix = PL_tmps_ix + need;
3027 if (max_ix >= PL_tmps_max) {
3028 tmps_grow_p(max_ix);
3032 PL_tmps_stack[++PL_tmps_ix] = sv;
3035 PL_tmps_stack[++PL_tmps_ix] = (SV *) av;
3038 PL_tmps_stack[++PL_tmps_ix] = (SV *) hv;
3041 PL_tmps_stack[++PL_tmps_ix] = (SV *) io;
3044 PL_tmps_stack[++PL_tmps_ix] = (SV *) cv;
3047 PL_tmps_stack[++PL_tmps_ix] = (SV *) form;
3051 /* Possibly reallocated by a destructor */
3054 if (!gp->gp_file_hek
3060 && !gp->gp_form) break;
3062 if (--attempts == 0) {
3064 "panic: gp_free failed to free glob pointer - "
3065 "something is repeatedly re-creating entries"
3070 /* Possibly incremented by a destructor doing glob assignment */
3071 if (gp->gp_refcnt > 1) goto borrowed;
3077 Perl_magic_freeovrld(pTHX_ SV *sv, MAGIC *mg)
3079 AMT * const amtp = (AMT*)mg->mg_ptr;
3080 PERL_UNUSED_ARG(sv);
3082 PERL_ARGS_ASSERT_MAGIC_FREEOVRLD;
3084 if (amtp && AMT_AMAGIC(amtp)) {
3086 for (i = 1; i < NofAMmeth; i++) {
3087 CV * const cv = amtp->table[i];
3089 SvREFCNT_dec_NN(MUTABLE_SV(cv));
3090 amtp->table[i] = NULL;
3098 =for apidoc Gv_AMupdate
3100 Recalculates overload magic in the package given by C<stash>.
3106 =item 1 on success and there is some overload
3108 =item 0 if there is no overload
3110 =item -1 if some error occurred and it couldn't croak (because C<destructing>
3119 Perl_Gv_AMupdate(pTHX_ HV *stash, bool destructing)
3121 MAGIC* const mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
3123 const struct mro_meta* stash_meta = HvMROMETA(stash);
3126 PERL_ARGS_ASSERT_GV_AMUPDATE;
3128 newgen = PL_sub_generation + stash_meta->pkg_gen + stash_meta->cache_gen;
3130 const AMT * const amtp = (AMT*)mg->mg_ptr;
3131 if (amtp->was_ok_sub == newgen) {
3132 return AMT_AMAGIC(amtp) ? 1 : 0;
3134 sv_unmagic(MUTABLE_SV(stash), PERL_MAGIC_overload_table);
3137 DEBUG_o( Perl_deb(aTHX_ "Recalculating overload magic in package %s\n",HvNAME_get(stash)) );
3140 amt.was_ok_sub = newgen;
3141 amt.fallback = AMGfallNO;
3147 bool deref_seen = 0;
3150 /* Work with "fallback" key, which we assume to be first in PL_AMG_names */
3152 /* Try to find via inheritance. */
3153 GV *gv = gv_fetchmeth_pvn(stash, PL_AMG_names[0], 2, -1, 0);
3154 SV * const sv = gv ? GvSV(gv) : NULL;
3159 if (!gv_fetchmeth_pvn(stash, "((", 2, -1, 0))
3162 #ifdef PERL_DONT_CREATE_GVSV
3164 NOOP; /* Equivalent to !SvTRUE and !SvOK */
3167 else if (SvTRUE(sv))
3168 /* don't need to set overloading here because fallback => 1
3169 * is the default setting for classes without overloading */
3170 amt.fallback=AMGfallYES;
3171 else if (SvOK(sv)) {
3172 amt.fallback=AMGfallNEVER;
3179 assert(HvHasAUX(stash));
3180 /* initially assume the worst */
3181 HvAUX(stash)->xhv_aux_flags &= ~HvAUXf_NO_DEREF;
3183 for (i = 1; i < NofAMmeth; i++) {
3184 const char * const cooky = PL_AMG_names[i];
3185 /* Human-readable form, for debugging: */
3186 const char * const cp = AMG_id2name(i);
3187 const STRLEN l = PL_AMG_namelens[i];
3189 DEBUG_o( Perl_deb(aTHX_ "Checking overloading of \"%s\" in package \"%.256s\"\n",
3190 cp, HvNAME_get(stash)) );
3191 /* don't fill the cache while looking up!
3192 Creation of inheritance stubs in intermediate packages may
3193 conflict with the logic of runtime method substitution.
3194 Indeed, for inheritance A -> B -> C, if C overloads "+0",
3195 then we could have created stubs for "(+0" in A and C too.
3196 But if B overloads "bool", we may want to use it for
3197 numifying instead of C's "+0". */
3198 gv = Perl_gv_fetchmeth_pvn(aTHX_ stash, cooky, l, -1, 0);
3200 if (gv && (cv = GvCV(gv)) && CvHASGV(cv)) {
3201 const HEK * const gvhek = CvGvNAME_HEK(cv);
3202 const HEK * const stashek =
3203 HvNAME_HEK(CvNAMED(cv) ? CvSTASH(cv) : GvSTASH(CvGV(cv)));
3204 if (memEQs(HEK_KEY(gvhek), HEK_LEN(gvhek), "nil")
3206 && memEQs(HEK_KEY(stashek), HEK_LEN(stashek), "overload")) {
3207 /* This is a hack to support autoloading..., while
3208 knowing *which* methods were declared as overloaded. */
3209 /* GvSV contains the name of the method. */
3211 SV *gvsv = GvSV(gv);
3213 DEBUG_o( Perl_deb(aTHX_ "Resolving method \"%" SVf256\
3214 "\" for overloaded \"%s\" in package \"%.256s\"\n",
3215 (void*)GvSV(gv), cp, HvNAME(stash)) );
3216 if (!gvsv || !SvPOK(gvsv)
3217 || !(ngv = gv_fetchmethod_sv_flags(stash, gvsv, 0)))
3219 /* Can be an import stub (created by "can"). */
3224 const SV * const name = (gvsv && SvPOK(gvsv))
3226 : newSVpvs_flags("???", SVs_TEMP);
3227 /* diag_listed_as: Can't resolve method "%s" overloading "%s" in package "%s" */
3228 Perl_croak(aTHX_ "%s method \"%" SVf256
3229 "\" overloading \"%s\" "\
3230 "in package \"%" HEKf256 "\"",
3231 (GvCVGEN(gv) ? "Stub found while resolving"
3239 cv = GvCV(gv = ngv);
3241 DEBUG_o( Perl_deb(aTHX_ "Overloading \"%s\" in package \"%.256s\" via \"%.256s::%.256s\"\n",
3242 cp, HvNAME_get(stash), HvNAME_get(GvSTASH(CvGV(cv))),
3243 GvNAME(CvGV(cv))) );
3245 } else if (gv) { /* Autoloaded... */
3246 cv = MUTABLE_CV(gv);
3249 amt.table[i]=MUTABLE_CV(SvREFCNT_inc_simple(cv));
3265 /* none of @{} etc overloaded; we can do $obj->[N] quicker.
3266 * NB - aux var invalid here, HvARRAY() could have been
3267 * reallocated since it was assigned to */
3268 HvAUX(stash)->xhv_aux_flags |= HvAUXf_NO_DEREF;
3271 AMT_AMAGIC_on(&amt);
3272 sv_magic(MUTABLE_SV(stash), 0, PERL_MAGIC_overload_table,
3273 (char*)&amt, sizeof(AMT));
3277 /* Here we have no table: */
3279 AMT_AMAGIC_off(&amt);
3280 sv_magic(MUTABLE_SV(stash), 0, PERL_MAGIC_overload_table,
3281 (char*)&amt, sizeof(AMTS));
3286 =for apidoc gv_handler
3288 Implements C<StashHANDLER>, which you should use instead
3294 Perl_gv_handler(pTHX_ HV *stash, I32 id)
3299 struct mro_meta* stash_meta;
3301 if (!stash || !HvHasNAME(stash))
3304 stash_meta = HvMROMETA(stash);
3305 newgen = PL_sub_generation + stash_meta->pkg_gen + stash_meta->cache_gen;
3307 mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
3310 if (Gv_AMupdate(stash, 0) == -1)
3312 mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
3315 amtp = (AMT*)mg->mg_ptr;
3316 if ( amtp->was_ok_sub != newgen )
3318 if (AMT_AMAGIC(amtp)) {
3319 CV * const ret = amtp->table[id];
3320 if (ret && isGV(ret)) { /* Autoloading stab */
3321 /* Passing it through may have resulted in a warning
3322 "Inherited AUTOLOAD for a non-method deprecated", since
3323 our caller is going through a function call, not a method call.
3324 So return the CV for AUTOLOAD, setting $AUTOLOAD. */
3325 GV * const gv = gv_fetchmethod(stash, PL_AMG_names[id]);
3337 /* Implement tryAMAGICun_MG macro.
3338 Do get magic, then see if the stack arg is overloaded and if so call it.
3340 AMGf_numeric apply sv_2num to the stack arg.
3344 Perl_try_amagic_un(pTHX_ int method, int flags) {
3347 SV* const arg = TOPs;
3351 if (SvAMAGIC(arg) && (tmpsv = amagic_call(arg, &PL_sv_undef, method,
3352 AMGf_noright | AMGf_unary
3353 | (flags & AMGf_numarg))))
3355 /* where the op is of the form:
3356 * $lex = $x op $y (where the assign is optimised away)
3357 * then assign the returned value to targ and return that;
3358 * otherwise return the value directly
3360 if ( (PL_opargs[PL_op->op_type] & OA_TARGLEX)
3361 && (PL_op->op_private & OPpTARGET_MY))
3364 sv_setsv(TARG, tmpsv);
3374 if ((flags & AMGf_numeric) && SvROK(arg))
3381 =for apidoc amagic_applies
3383 Check C<sv> to see if the overloaded (active magic) operation C<method>
3384 applies to it. If the sv is not SvROK or it is not an object then returns
3385 false, otherwise checks if the object is blessed into a class supporting
3386 overloaded operations, and returns true if a call to amagic_call() with
3387 this SV and the given method would trigger an amagic operation, including
3388 via the overload fallback rules or via nomethod. Thus a call like:
3390 amagic_applies(sv, string_amg, AMG_unary)
3392 would return true for an object with overloading set up in any of the
3395 use overload q("") => sub { ... };
3396 use overload q(0+) => sub { ... }, fallback => 1;
3398 and could be used to tell if a given object would stringify to something
3399 other than the normal default ref stringification.
3401 Note that the fact that this function returns TRUE does not mean you
3402 can succesfully perform the operation with amagic_call(), for instance
3403 any overloaded method might throw a fatal exception, however if this
3404 function returns FALSE you can be confident that it will NOT perform
3405 the given overload operation.
3407 C<method> is an integer enum, one of the values found in F<overload.h>,
3408 for instance C<string_amg>.
3410 C<flags> should be set to AMG_unary for unary operations.
3415 Perl_amagic_applies(pTHX_ SV *sv, int method, int flags)
3417 PERL_ARGS_ASSERT_AMAGIC_APPLIES;
3418 PERL_UNUSED_VAR(flags);
3420 assert(method >= 0 && method < NofAMmeth);
3425 HV *stash = SvSTASH(SvRV(sv));
3429 MAGIC *mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
3435 if (AMT_AMAGIC((AMT *)mg->mg_ptr)) {
3436 amtp = (AMT *)mg->mg_ptr;
3445 /* Note this logic should be kept in sync with amagic_call() */
3446 if (amtp->fallback > AMGfallNEVER && flags & AMGf_unary) {
3447 CV *cv; /* This makes it easier to kee ... */
3448 int off,off1; /* ... in sync with amagic_call() */
3450 /* look for substituted methods */
3451 /* In all the covered cases we should be called with assign==0. */
3454 if ((cv = cvp[off=add_ass_amg]) || ((cv = cvp[off = add_amg])))
3458 if((cv = cvp[off = subtr_ass_amg]) || ((cv = cvp[off = subtr_amg])))
3462 if ((cv = cvp[off=numer_amg]) || (cv = cvp[off=string_amg]))
3466 if((cv = cvp[off=string_amg]) || (cv = cvp[off=bool__amg]))
3470 if((cv = cvp[off=numer_amg]) || (cv = cvp[off=bool__amg]))
3474 if((cv = cvp[off=bool__amg])
3475 || (cv = cvp[off=numer_amg])
3476 || (cv = cvp[off=string_amg]))
3480 if((cvp[off1=lt_amg] || cvp[off1=ncmp_amg])
3481 && ((cv = cvp[off=neg_amg]) || (cv = cvp[off=subtr_amg])))
3485 if ((cv = cvp[off=subtr_amg]))
3489 } else if (((cvp && amtp->fallback > AMGfallNEVER))
3490 && !(flags & AMGf_unary)) {
3491 /* We look for substitution for
3492 * comparison operations and
3494 if (method==concat_amg || method==concat_ass_amg
3495 || method==repeat_amg || method==repeat_ass_amg) {
3496 return FALSE; /* Delegate operation to string conversion */
3520 if (cvp[nomethod_amg])
3527 /* Implement tryAMAGICbin_MG macro.
3528 Do get magic, then see if the two stack args are overloaded and if so
3531 AMGf_assign op may be called as mutator (eg +=)
3532 AMGf_numeric apply sv_2num to the stack arg.
3536 Perl_try_amagic_bin(pTHX_ int method, int flags) {
3538 SV* const left = TOPm1s;
3539 SV* const right = TOPs;
3545 if (SvAMAGIC(left) || SvAMAGIC(right)) {
3547 /* STACKED implies mutator variant, e.g. $x += 1 */
3548 bool mutator = (flags & AMGf_assign) && (PL_op->op_flags & OPf_STACKED);
3550 tmpsv = amagic_call(left, right, method,
3551 (mutator ? AMGf_assign: 0)
3552 | (flags & AMGf_numarg));
3555 /* where the op is one of the two forms:
3557 * $lex = $x op $y (where the assign is optimised away)
3558 * then assign the returned value to targ and return that;
3559 * otherwise return the value directly
3562 || ( (PL_opargs[PL_op->op_type] & OA_TARGLEX)
3563 && (PL_op->op_private & OPpTARGET_MY)))
3566 TARG = mutator ? *SP : PAD_SV(PL_op->op_targ);
3567 sv_setsv(TARG, tmpsv);
3578 if(left==right && SvGMAGICAL(left)) {
3579 SV * const left = sv_newmortal();
3581 /* Print the uninitialized warning now, so it includes the vari-
3584 if (ckWARN(WARN_UNINITIALIZED)) report_uninit(right);
3585 sv_setbool(left, FALSE);
3587 else sv_setsv_flags(left, right, 0);
3590 if (flags & AMGf_numeric) {
3592 *(sp-1) = sv_2num(TOPm1s);
3594 *sp = sv_2num(right);
3600 =for apidoc amagic_deref_call
3602 Perform C<method> overloading dereferencing on C<ref>, returning the
3603 dereferenced result. C<method> must be one of the dereference operations given
3606 If overloading is inactive on C<ref>, returns C<ref> itself.
3612 Perl_amagic_deref_call(pTHX_ SV *ref, int method) {
3616 PERL_ARGS_ASSERT_AMAGIC_DEREF_CALL;
3620 /* return quickly if none of the deref ops are overloaded */
3621 stash = SvSTASH(SvRV(ref));
3622 assert(HvHasAUX(stash));
3623 if (HvAUX(stash)->xhv_aux_flags & HvAUXf_NO_DEREF)
3626 while ((tmpsv = amagic_call(ref, &PL_sv_undef, method,
3627 AMGf_noright | AMGf_unary))) {
3629 Perl_croak(aTHX_ "Overloaded dereference did not return a reference");
3630 if (tmpsv == ref || SvRV(tmpsv) == SvRV(ref)) {
3631 /* Bail out if it returns us the same reference. */
3638 return tmpsv ? tmpsv : ref;
3642 Perl_amagic_is_enabled(pTHX_ int method)
3644 SV *lex_mask = cop_hints_fetch_pvs(PL_curcop, "overloading", 0);
3646 assert(PL_curcop->cop_hints & HINT_NO_AMAGIC);
3648 if ( !lex_mask || !SvOK(lex_mask) )
3649 /* overloading lexically disabled */
3651 else if ( lex_mask && SvPOK(lex_mask) ) {
3652 /* we have an entry in the hints hash, check if method has been
3653 * masked by overloading.pm */
3655 const int offset = method / 8;
3656 const int bit = method % 8;
3657 char *pv = SvPV(lex_mask, len);
3659 /* Bit set, so this overloading operator is disabled */
3660 if ( (STRLEN)offset < len && pv[offset] & ( 1 << bit ) )
3667 =for apidoc amagic_call
3669 Perform the overloaded (active magic) operation given by C<method>.
3670 C<method> is one of the values found in F<overload.h>.
3672 C<flags> affects how the operation is performed, as follows:
3676 =item C<AMGf_noleft>
3678 C<left> is not to be used in this operation.
3680 =item C<AMGf_noright>
3682 C<right> is not to be used in this operation.
3686 The operation is done only on just one operand.
3688 =item C<AMGf_assign>
3690 The operation changes one of the operands, e.g., $x += 1
3698 Perl_amagic_call(pTHX_ SV *left, SV *right, int method, int flags)
3702 CV **cvp=NULL, **ocvp=NULL;
3703 AMT *amtp=NULL, *oamtp=NULL;
3704 int off = 0, off1, lr = 0, notfound = 0;
3705 int postpr = 0, force_cpy = 0;
3706 int assign = AMGf_assign & flags;
3707 const int assignshift = assign ? 1 : 0;
3708 int use_default_op = 0;
3709 int force_scalar = 0;
3715 PERL_ARGS_ASSERT_AMAGIC_CALL;
3717 if ( PL_curcop->cop_hints & HINT_NO_AMAGIC ) {
3718 if (!amagic_is_enabled(method)) return NULL;
3721 if (!(AMGf_noleft & flags) && SvAMAGIC(left)
3722 && (stash = SvSTASH(SvRV(left))) && Gv_AMG(stash)
3723 && (mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table))
3724 && (ocvp = cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
3725 ? (oamtp = amtp = (AMT*)mg->mg_ptr)->table
3727 && ((cv = cvp[off=method+assignshift])
3728 || (assign && amtp->fallback > AMGfallNEVER && /* fallback to
3734 cv = cvp[off=method]))))
3736 lr = -1; /* Call method for left argument */
3738 /* Note this logic should be kept in sync with amagic_applies() */
3739 if (cvp && amtp->fallback > AMGfallNEVER && flags & AMGf_unary) {
3742 /* look for substituted methods */
3743 /* In all the covered cases we should be called with assign==0. */
3747 if ((cv = cvp[off=add_ass_amg])
3748 || ((cv = cvp[off = add_amg])
3749 && (force_cpy = 0, (postpr = 1)))) {
3750 right = &PL_sv_yes; lr = -1; assign = 1;
3755 if ((cv = cvp[off = subtr_ass_amg])
3756 || ((cv = cvp[off = subtr_amg])
3757 && (force_cpy = 0, (postpr=1)))) {
3758 right = &PL_sv_yes; lr = -1; assign = 1;
3762 (void)((cv = cvp[off=numer_amg]) || (cv = cvp[off=string_amg]));
3765 (void)((cv = cvp[off=string_amg]) || (cv = cvp[off=bool__amg]));
3768 (void)((cv = cvp[off=numer_amg]) || (cv = cvp[off=bool__amg]));
3771 (void)((cv = cvp[off=bool__amg])
3772 || (cv = cvp[off=numer_amg])
3773 || (cv = cvp[off=string_amg]));
3780 * SV* ref causes confusion with the interpreter variable of
3783 SV* const tmpRef=SvRV(left);
3784 if (!SvROK(tmpRef) && SvTYPE(tmpRef) <= SVt_PVMG) {
3786 * Just to be extra cautious. Maybe in some
3787 * additional cases sv_setsv is safe, too.
3789 SV* const newref = newSVsv(tmpRef);
3790 SvOBJECT_on(newref);
3791 /* No need to do SvAMAGIC_on here, as SvAMAGIC macros
3792 delegate to the stash. */
3793 SvSTASH_set(newref, MUTABLE_HV(SvREFCNT_inc(SvSTASH(tmpRef))));
3799 if ((cvp[off1=lt_amg] || cvp[off1=ncmp_amg])
3800 && ((cv = cvp[off=neg_amg]) || (cv = cvp[off=subtr_amg]))) {
3801 SV* const nullsv=&PL_sv_zero;
3803 SV* const lessp = amagic_call(left,nullsv,
3804 lt_amg,AMGf_noright);
3805 logic = SvTRUE_NN(lessp);
3807 SV* const lessp = amagic_call(left,nullsv,
3808 ncmp_amg,AMGf_noright);
3809 logic = (SvNV(lessp) < 0);
3812 if (off==subtr_amg) {
3823 if ((cv = cvp[off=subtr_amg])) {
3830 case iter_amg: /* XXXX Eventually should do to_gv. */
3831 case ftest_amg: /* XXXX Eventually should do to_gv. */
3834 return NULL; /* Delegate operation to standard mechanisms. */
3842 return left; /* Delegate operation to standard mechanisms. */
3847 if (!cv) goto not_found;
3848 } else if (!(AMGf_noright & flags) && SvAMAGIC(right)
3849 && (stash = SvSTASH(SvRV(right))) && Gv_AMG(stash)
3850 && (mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table))
3851 && (cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
3852 ? (amtp = (AMT*)mg->mg_ptr)->table
3854 && (cv = cvp[off=method])) { /* Method for right
3857 } else if (((cvp && amtp->fallback > AMGfallNEVER)
3858 || (ocvp && oamtp->fallback > AMGfallNEVER))
3859 && !(flags & AMGf_unary)) {
3860 /* We look for substitution for
3861 * comparison operations and
3863 if (method==concat_amg || method==concat_ass_amg
3864 || method==repeat_amg || method==repeat_ass_amg) {
3865 return NULL; /* Delegate operation to string conversion */
3887 if (ocvp && (oamtp->fallback > AMGfallNEVER)) {
3891 if (!cv && (cvp && amtp->fallback > AMGfallNEVER)) {
3901 not_found: /* No method found, either report or croak */
3909 return left; /* Delegate operation to standard mechanisms. */
3911 if (ocvp && (cv=ocvp[nomethod_amg])) { /* Call report method */
3912 notfound = 1; lr = -1;
3913 } else if (cvp && (cv=cvp[nomethod_amg])) {
3914 notfound = 1; lr = 1;
3915 } else if ((use_default_op =
3916 (!ocvp || oamtp->fallback >= AMGfallYES)
3917 && (!cvp || amtp->fallback >= AMGfallYES))
3919 /* Skip generating the "no method found" message. */
3923 if (off==-1) off=method;
3924 msg = sv_2mortal(Perl_newSVpvf(aTHX_
3925 "Operation \"%s\": no method found,%sargument %s%" SVf "%s%" SVf,
3926 AMG_id2name(method + assignshift),
3927 (flags & AMGf_unary ? " " : "\n\tleft "),
3929 "in overloaded package ":
3930 "has no overloaded magic",
3932 SVfARG(newSVhek_mortal(HvNAME_HEK(SvSTASH(SvRV(left))))):
3935 ",\n\tright argument in overloaded package ":
3938 : ",\n\tright argument has no overloaded magic"),
3940 SVfARG(newSVhek_mortal(HvNAME_HEK(SvSTASH(SvRV(right))))):
3941 SVfARG(&PL_sv_no)));
3942 if (use_default_op) {
3943 DEBUG_o( Perl_deb(aTHX_ "%" SVf, SVfARG(msg)) );
3945 Perl_croak(aTHX_ "%" SVf, SVfARG(msg));
3949 force_cpy = force_cpy || assign;
3954 /* in these cases, we're calling '+' or '-' as a fallback for a ++ or --
3955 * operation. we need this to return a value, so that it can be assigned
3956 * later on, in the postpr block (case inc_amg/dec_amg), even if the
3957 * increment or decrement was itself called in void context */
3963 if (off == subtr_amg)
3966 /* in these cases, we're calling an assignment variant of an operator
3967 * (+= rather than +, for instance). regardless of whether it's a
3968 * fallback or not, it always has to return a value, which will be
3969 * assigned to the proper variable later */
3989 /* the copy constructor always needs to return a value */
3993 /* because of the way these are implemented (they don't perform the
3994 * dereferencing themselves, they return a reference that perl then
3995 * dereferences later), they always have to be in scalar context */
4003 /* these don't have an op of their own; they're triggered by their parent
4004 * op, so the context there isn't meaningful ('$a and foo()' in void
4005 * context still needs to pass scalar context on to $a's bool overload) */
4015 DEBUG_o(Perl_deb(aTHX_
4016 "Overloaded operator \"%s\"%s%s%s:\n\tmethod%s found%s in package %" SVf "%s\n",
4018 method+assignshift==off? "" :
4020 method+assignshift==off? "" :
4021 AMG_id2name(method+assignshift),
4022 method+assignshift==off? "" : "\")",
4023 flags & AMGf_unary? "" :
4024 lr==1 ? " for right argument": " for left argument",
4025 flags & AMGf_unary? " for argument" : "",
4026 stash ? SVfARG(newSVhek_mortal(HvNAME_HEK(stash))) : SVfARG(newSVpvs_flags("null", SVs_TEMP)),
4027 fl? ",\n\tassignment variant used": "") );
4030 /* Since we use shallow copy during assignment, we need
4031 * to duplicate the contents, probably calling user-supplied
4032 * version of copy operator
4034 /* We need to copy in following cases:
4035 * a) Assignment form was called.
4036 * assignshift==1, assign==T, method + 1 == off
4037 * b) Increment or decrement, called directly.
4038 * assignshift==0, assign==0, method + 0 == off
4039 * c) Increment or decrement, translated to assignment add/subtr.
4040 * assignshift==0, assign==T,
4042 * d) Increment or decrement, translated to nomethod.
4043 * assignshift==0, assign==0,
4045 * e) Assignment form translated to nomethod.
4046 * assignshift==1, assign==T, method + 1 != off
4049 /* off is method, method+assignshift, or a result of opcode substitution.
4050 * In the latter case assignshift==0, so only notfound case is important.
4052 if ( (lr == -1) && ( ( (method + assignshift == off)
4053 && (assign || (method == inc_amg) || (method == dec_amg)))
4056 /* newSVsv does not behave as advertised, so we copy missing
4057 * information by hand */
4058 SV *tmpRef = SvRV(left);
4060 if (SvREFCNT(tmpRef) > 1 && (rv_copy = AMG_CALLunary(left,copy_amg))) {
4061 SvRV_set(left, rv_copy);
4063 SvREFCNT_dec_NN(tmpRef);
4071 const bool oldcatch = CATCH_GET;
4073 /* for multiconcat, we may call overload several times,
4074 * with the context of individual concats being scalar,
4075 * regardless of the overall context of the multiconcat op
4077 U8 gimme = (force_scalar || PL_op->op_type == OP_MULTICONCAT)
4078 ? G_SCALAR : GIMME_V;
4081 Zero(&myop, 1, BINOP);
4082 myop.op_last = (OP *) &myop;
4083 myop.op_next = NULL;
4084 myop.op_flags = OPf_STACKED;
4088 myop.op_flags |= OPf_WANT_VOID;
4091 if (flags & AMGf_want_list) {
4092 myop.op_flags |= OPf_WANT_LIST;
4097 myop.op_flags |= OPf_WANT_SCALAR;
4101 PUSHSTACKi(PERLSI_OVERLOAD);
4104 PL_op = (OP *) &myop;
4105 if (PERLDB_SUB && PL_curstash != PL_debstash)
4106 PL_op->op_private |= OPpENTERSUB_DB;
4107 Perl_pp_pushmark(aTHX);
4109 EXTEND(SP, notfound + 5);
4110 PUSHs(lr>0? right: left);
4111 PUSHs(lr>0? left: right);
4112 PUSHs( lr > 0 ? &PL_sv_yes : ( assign ? &PL_sv_undef : &PL_sv_no ));
4114 PUSHs(newSVpvn_flags(AMG_id2name(method + assignshift),
4115 AMG_id2namelen(method + assignshift), SVs_TEMP));
4117 else if (flags & AMGf_numarg)
4118 PUSHs(&PL_sv_undef);
4119 if (flags & AMGf_numarg)
4121 PUSHs(MUTABLE_SV(cv));
4125 if ((PL_op = PL_ppaddr[OP_ENTERSUB](aTHX)))
4129 nret = SP - (PL_stack_base + oldmark);
4133 /* returning NULL has another meaning, and we check the context
4134 * at the call site too, so this can be differentiated from the
4137 SP = PL_stack_base + oldmark;
4140 if (flags & AMGf_want_list) {
4141 res = newSV_type_mortal(SVt_PVAV);
4142 av_extend((AV *)res, nret);
4144 av_store((AV *)res, nret, POPs);
4155 CATCH_SET(oldcatch);
4162 ans=SvIV(res)<=0; break;
4165 ans=SvIV(res)<0; break;
4168 ans=SvIV(res)>=0; break;
4171 ans=SvIV(res)>0; break;
4174 ans=SvIV(res)==0; break;
4177 ans=SvIV(res)!=0; break;
4180 SvSetSV(left,res); return left;
4182 ans=!SvTRUE_NN(res); break;
4187 } else if (method==copy_amg) {
4189 Perl_croak(aTHX_ "Copy method did not return a reference");
4191 return SvREFCNT_inc(SvRV(res));
4199 =for apidoc gv_name_set
4201 Set the name for GV C<gv> to C<name> which is C<len> bytes long. Thus it may
4202 contain embedded NUL characters.
4204 If C<flags> contains C<SVf_UTF8>, the name is treated as being encoded in
4205 UTF-8; otherwise not.
4211 Perl_gv_name_set(pTHX_ GV *gv, const char *name, U32 len, U32 flags)
4215 PERL_ARGS_ASSERT_GV_NAME_SET;
4218 Perl_croak(aTHX_ "panic: gv name too long (%" UVuf ")", (UV) len);
4220 if (!(flags & GV_ADD) && GvNAME_HEK(gv)) {
4221 unshare_hek(GvNAME_HEK(gv));
4224 PERL_HASH(hash, name, len);
4225 GvNAME_HEK(gv) = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
4229 =for apidoc gv_try_downgrade
4231 If the typeglob C<gv> can be expressed more succinctly, by having
4232 something other than a real GV in its place in the stash, replace it
4233 with the optimised form. Basic requirements for this are that C<gv>
4234 is a real typeglob, is sufficiently ordinary, and is only referenced
4235 from its package. This function is meant to be used when a GV has been
4236 looked up in part to see what was there, causing upgrading, but based
4237 on what was found it turns out that the real GV isn't required after all.
4239 If C<gv> is a completely empty typeglob, it is deleted from the stash.
4241 If C<gv> is a typeglob containing only a sufficiently-ordinary constant
4242 sub, the typeglob is replaced with a scalar-reference placeholder that
4243 more compactly represents the same thing.
4249 Perl_gv_try_downgrade(pTHX_ GV *gv)
4255 PERL_ARGS_ASSERT_GV_TRY_DOWNGRADE;
4257 /* XXX Why and where does this leave dangling pointers during global
4259 if (PL_phase == PERL_PHASE_DESTRUCT) return;
4261 if (!(SvREFCNT(gv) == 1 && SvTYPE(gv) == SVt_PVGV && !SvFAKE(gv) &&
4262 !SvOBJECT(gv) && !SvREADONLY(gv) &&
4263 isGV_with_GP(gv) && GvGP(gv) &&
4264 !GvINTRO(gv) && GvREFCNT(gv) == 1 &&
4265 !GvSV(gv) && !GvAV(gv) && !GvHV(gv) && !GvIOp(gv) && !GvFORM(gv) &&
4266 GvEGVx(gv) == gv && (stash = GvSTASH(gv))))
4268 if (gv == PL_statgv || gv == PL_last_in_gv || gv == PL_stderrgv)
4270 if (SvMAGICAL(gv)) {
4272 /* only backref magic is allowed */
4273 if (SvGMAGICAL(gv) || SvSMAGICAL(gv))
4275 for (mg = SvMAGIC(gv); mg; mg = mg->mg_moremagic) {
4276 if (mg->mg_type != PERL_MAGIC_backref)
4282 HEK *gvnhek = GvNAME_HEK(gv);
4283 (void)hv_deletehek(stash, gvnhek, G_DISCARD);
4284 } else if (GvMULTI(gv) && cv && SvREFCNT(cv) == 1 &&
4285 !SvOBJECT(cv) && !SvMAGICAL(cv) && !SvREADONLY(cv) &&
4286 CvSTASH(cv) == stash && !CvNAMED(cv) && CvGV(cv) == gv &&
4287 CvCONST(cv) && !CvNOWARN_AMBIGUOUS(cv) && !CvLVALUE(cv) && !CvUNIQUE(cv) &&
4288 !CvNODEBUG(cv) && !CvCLONE(cv) && !CvCLONED(cv) && !CvANON(cv) &&
4289 (namehek = GvNAME_HEK(gv)) &&
4290 (gvp = hv_fetchhek(stash, namehek, 0)) &&
4292 SV *value = SvREFCNT_inc(CvXSUBANY(cv).any_ptr);
4293 const bool imported = cBOOL(GvIMPORTED_CV(gv));
4297 SvFLAGS(gv) = SVt_IV|SVf_ROK|SVprv_PCS_IMPORTED * imported;
4299 /* See also: 'SET_SVANY_FOR_BODYLESS_IV' in sv.c */
4300 SvANY(gv) = (XPVGV*)((char*)&(gv->sv_u.svu_iv) -
4301 STRUCT_OFFSET(XPVIV, xiv_iv));
4302 SvRV_set(gv, value);
4307 Perl_gv_override(pTHX_ const char * const name, const STRLEN len)
4309 GV *gv = gv_fetchpvn(name, len, GV_NOTQUAL, SVt_PVCV);
4311 PERL_ARGS_ASSERT_GV_OVERRIDE;
4312 if (gv && GvCVu(gv) && GvIMPORTED_CV(gv)) return gv;
4313 gvp = (GV**)hv_fetch(PL_globalstash, name, len, FALSE);
4314 gv = gvp ? *gvp : NULL;
4315 if (gv && !isGV(gv)) {
4316 if (!SvPCS_IMPORTED(gv)) return NULL;
4317 gv_init(gv, PL_globalstash, name, len, 0);
4320 return gv && GvCVu(gv) && GvIMPORTED_CV(gv) ? gv : NULL;
4326 core_xsub(pTHX_ CV* cv)
4329 "&CORE::%s cannot be called directly", GvNAME(CvGV(cv))
4334 * ex: set ts=8 sts=4 sw=4 et: