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"]
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.
39 #include "overload.inc"
43 static const char S_autoload[] = "AUTOLOAD";
44 #define S_autolen (sizeof("AUTOLOAD")-1)
47 Perl_gv_add_by_type(pTHX_ GV *gv, svtype type)
54 SvTYPE((const SV *)gv) != SVt_PVGV
55 && SvTYPE((const SV *)gv) != SVt_PVLV
59 if (type == SVt_PVIO) {
61 * if it walks like a dirhandle, then let's assume that
62 * this is a dirhandle.
64 what = OP_IS_DIRHOP(PL_op->op_type) ?
65 "dirhandle" : "filehandle";
66 } else if (type == SVt_PVHV) {
69 what = type == SVt_PVAV ? "array" : "scalar";
71 /* diag_listed_as: Bad symbol for filehandle */
72 Perl_croak(aTHX_ "Bad symbol for %s", what);
75 if (type == SVt_PVHV) {
76 where = (SV **)&GvHV(gv);
77 } else if (type == SVt_PVAV) {
78 where = (SV **)&GvAV(gv);
79 } else if (type == SVt_PVIO) {
80 where = (SV **)&GvIOp(gv);
87 *where = newSV_type(type);
89 && memEQs(GvNAME(gv), GvNAMELEN(gv), "ISA"))
90 sv_magic(*where, (SV *)gv, PERL_MAGIC_isa, NULL, 0);
96 =for apidoc gv_fetchfile
97 =for apidoc_item gv_fetchfile_flags
99 These return the debugger glob for the file (compiled by Perl) whose name is
100 given by the C<name> parameter.
102 There are currently exactly two differences between these functions.
104 The C<name> parameter to C<gv_fetchfile> is a C string, meaning it is
105 C<NUL>-terminated; whereas the C<name> parameter to C<gv_fetchfile_flags> is a
106 Perl string, whose length (in bytes) is passed in via the C<namelen> parameter
107 This means the name may contain embedded C<NUL> characters.
108 C<namelen> doesn't exist in plain C<gv_fetchfile>).
110 The other difference is that C<gv_fetchfile_flags> has an extra C<flags>
111 parameter, which is currently completely ignored, but allows for possible
117 Perl_gv_fetchfile(pTHX_ const char *name)
119 PERL_ARGS_ASSERT_GV_FETCHFILE;
120 return gv_fetchfile_flags(name, strlen(name), 0);
124 Perl_gv_fetchfile_flags(pTHX_ const char *const name, const STRLEN namelen,
129 const STRLEN tmplen = namelen + 2;
132 PERL_ARGS_ASSERT_GV_FETCHFILE_FLAGS;
133 PERL_UNUSED_ARG(flags);
138 if (tmplen <= sizeof smallbuf)
141 Newx(tmpbuf, tmplen, char);
142 /* This is where the debugger's %{"::_<$filename"} hash is created */
145 memcpy(tmpbuf + 2, name, namelen);
146 GV **gvp = (GV**)hv_fetch(PL_defstash, tmpbuf, tmplen, (flags & GVF_NOADD) ? FALSE : TRUE);
150 gv_init(gv, PL_defstash, tmpbuf, tmplen, FALSE);
151 #ifdef PERL_DONT_CREATE_GVSV
152 GvSV(gv) = newSVpvn(name, namelen);
154 sv_setpvn(GvSV(gv), name, namelen);
157 if (PERLDB_LINE_OR_SAVESRC && !GvAV(gv))
158 hv_magic(GvHVn(gv), GvAVn(gv), PERL_MAGIC_dbfile);
163 if (tmpbuf != smallbuf)
169 =for apidoc gv_const_sv
171 If C<gv> is a typeglob whose subroutine entry is a constant sub eligible for
172 inlining, or C<gv> is a placeholder reference that would be promoted to such
173 a typeglob, then returns the value returned by the sub. Otherwise, returns
180 Perl_gv_const_sv(pTHX_ GV *gv)
182 PERL_ARGS_ASSERT_GV_CONST_SV;
185 if (SvTYPE(gv) == SVt_PVGV)
186 return cv_const_sv(GvCVu(gv));
187 return SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVAV && SvTYPE(SvRV(gv)) != SVt_PVCV ? SvRV(gv) : NULL;
191 Perl_newGP(pTHX_ GV *const gv)
201 PERL_ARGS_ASSERT_NEWGP;
203 gp->gp_egv = gv; /* allow compiler to reuse gv after this */
204 #ifndef PERL_DONT_CREATE_GVSV
205 gp->gp_sv = newSV(0);
208 /* PL_curcop may be null here. E.g.,
209 INIT { bless {} and exit }
210 frees INIT before looking up DESTROY (and creating *DESTROY)
213 gp->gp_line = CopLINE(PL_curcop); /* 0 otherwise Newxz */
215 if (CopFILE(PL_curcop)) {
216 file = CopFILE(PL_curcop);
220 filegv = CopFILEGV(PL_curcop);
222 file = GvNAME(filegv)+2;
223 len = GvNAMELEN(filegv)-2;
234 PERL_HASH(hash, file, len);
235 gp->gp_file_hek = share_hek(file, len, hash);
241 /* Assign CvGV(cv) = gv, handling weak references.
242 * See also S_anonymise_cv_maybe */
245 Perl_cvgv_set(pTHX_ CV* cv, GV* gv)
247 GV * const oldgv = CvNAMED(cv) ? NULL : SvANY(cv)->xcv_gv_u.xcv_gv;
249 PERL_ARGS_ASSERT_CVGV_SET;
256 SvREFCNT_dec_NN(oldgv);
260 sv_del_backref(MUTABLE_SV(oldgv), MUTABLE_SV(cv));
263 else if ((hek = CvNAME_HEK(cv))) {
269 SvANY(cv)->xcv_gv_u.xcv_gv = gv;
270 assert(!CvCVGV_RC(cv));
275 if (isGV_with_GP(gv) && GvGP(gv) && (GvCV(gv) == cv || GvFORM(gv) == cv))
276 Perl_sv_add_backref(aTHX_ MUTABLE_SV(gv), MUTABLE_SV(cv));
279 SvREFCNT_inc_simple_void_NN(gv);
283 /* Convert CvSTASH + CvNAME_HEK into a GV. Conceptually, all subs have a
284 GV, but for efficiency that GV may not in fact exist. This function,
285 called by CvGV, reifies it. */
288 Perl_cvgv_from_hek(pTHX_ CV *cv)
292 PERL_ARGS_ASSERT_CVGV_FROM_HEK;
293 assert(SvTYPE(cv) == SVt_PVCV);
294 if (!CvSTASH(cv)) return NULL;
295 ASSUME(CvNAME_HEK(cv));
296 svp = hv_fetchhek(CvSTASH(cv), CvNAME_HEK(cv), 0);
297 gv = MUTABLE_GV(svp && *svp ? *svp : newSV(0));
299 gv_init_pvn(gv, CvSTASH(cv), HEK_KEY(CvNAME_HEK(cv)),
300 HEK_LEN(CvNAME_HEK(cv)),
301 SVf_UTF8 * !!HEK_UTF8(CvNAME_HEK(cv)));
302 if (!CvNAMED(cv)) { /* gv_init took care of it */
303 assert (SvANY(cv)->xcv_gv_u.xcv_gv == gv);
306 unshare_hek(CvNAME_HEK(cv));
308 SvANY(cv)->xcv_gv_u.xcv_gv = gv;
309 if (svp && *svp) SvREFCNT_inc_simple_void_NN(gv);
314 /* Assign CvSTASH(cv) = st, handling weak references. */
317 Perl_cvstash_set(pTHX_ CV *cv, HV *st)
319 HV *oldst = CvSTASH(cv);
320 PERL_ARGS_ASSERT_CVSTASH_SET;
324 sv_del_backref(MUTABLE_SV(oldst), MUTABLE_SV(cv));
325 SvANY(cv)->xcv_stash = st;
327 Perl_sv_add_backref(aTHX_ MUTABLE_SV(st), MUTABLE_SV(cv));
331 =for apidoc gv_init_pvn
333 Converts a scalar into a typeglob. This is an incoercible typeglob;
334 assigning a reference to it will assign to one of its slots, instead of
335 overwriting it as happens with typeglobs created by C<SvSetSV>. Converting
336 any scalar that is C<SvOK()> may produce unpredictable results and is reserved
337 for perl's internal use.
339 C<gv> is the scalar to be converted.
341 C<stash> is the parent stash/package, if any.
343 C<name> and C<len> give the name. The name must be unqualified;
344 that is, it must not include the package name. If C<gv> is a
345 stash element, it is the caller's responsibility to ensure that the name
346 passed to this function matches the name of the element. If it does not
347 match, perl's internal bookkeeping will get out of sync.
349 C<flags> can be set to C<SVf_UTF8> if C<name> is a UTF-8 string, or
350 the return value of SvUTF8(sv). It can also take the
351 C<GV_ADDMULTI> flag, which means to pretend that the GV has been
352 seen before (i.e., suppress "Used once" warnings).
354 =for apidoc Amnh||GV_ADDMULTI
358 The old form of C<gv_init_pvn()>. It does not work with UTF-8 strings, as it
359 has no flags parameter. If the C<multi> parameter is set, the
360 C<GV_ADDMULTI> flag will be passed to C<gv_init_pvn()>.
362 =for apidoc gv_init_pv
364 Same as C<gv_init_pvn()>, but takes a nul-terminated string for the name
365 instead of separate char * and length parameters.
367 =for apidoc gv_init_sv
369 Same as C<gv_init_pvn()>, but takes an SV * for the name instead of separate
370 char * and length parameters. C<flags> is currently unused.
376 Perl_gv_init_sv(pTHX_ GV *gv, HV *stash, SV* namesv, U32 flags)
380 PERL_ARGS_ASSERT_GV_INIT_SV;
381 namepv = SvPV(namesv, namelen);
384 gv_init_pvn(gv, stash, namepv, namelen, flags);
388 Perl_gv_init_pv(pTHX_ GV *gv, HV *stash, const char *name, U32 flags)
390 PERL_ARGS_ASSERT_GV_INIT_PV;
391 gv_init_pvn(gv, stash, name, strlen(name), flags);
395 Perl_gv_init_pvn(pTHX_ GV *gv, HV *stash, const char *name, STRLEN len, U32 flags)
397 const U32 old_type = SvTYPE(gv);
398 const bool doproto = old_type > SVt_NULL;
399 char * const proto = (doproto && SvPOK(gv))
400 ? ((void)(SvIsCOW(gv) && (sv_force_normal((SV *)gv), 0)), SvPVX(gv))
402 const STRLEN protolen = proto ? SvCUR(gv) : 0;
403 const U32 proto_utf8 = proto ? SvUTF8(gv) : 0;
404 SV *const has_constant = doproto && SvROK(gv) ? SvRV(gv) : NULL;
405 const U32 exported_constant = has_constant ? SvPCS_IMPORTED(gv) : 0;
406 const bool really_sub =
407 has_constant && SvTYPE(has_constant) == SVt_PVCV;
408 COP * const old = PL_curcop;
410 PERL_ARGS_ASSERT_GV_INIT_PVN;
411 assert (!(proto && has_constant));
414 /* The constant has to be a scalar, array or subroutine. */
415 switch (SvTYPE(has_constant)) {
419 Perl_croak(aTHX_ "Cannot convert a reference to %s to typeglob",
420 sv_reftype(has_constant, 0));
421 NOT_REACHED; /* NOTREACHED */
431 if (old_type < SVt_PVGV) {
432 if (old_type >= SVt_PV)
434 sv_upgrade(MUTABLE_SV(gv), SVt_PVGV);
442 Safefree(SvPVX_mutable(gv));
447 if (really_sub && !CvISXSUB(has_constant) && CvSTART(has_constant)
448 && ( CvSTART(has_constant)->op_type == OP_NEXTSTATE
449 || CvSTART(has_constant)->op_type == OP_DBSTATE))
450 PL_curcop = (COP *)CvSTART(has_constant);
451 GvGP_set(gv, Perl_newGP(aTHX_ gv));
455 Perl_sv_add_backref(aTHX_ MUTABLE_SV(stash), MUTABLE_SV(gv));
456 gv_name_set(gv, name, len, GV_ADD | ( flags & SVf_UTF8 ? SVf_UTF8 : 0 ));
457 if (flags & GV_ADDMULTI || doproto) /* doproto means it */
458 GvMULTI_on(gv); /* _was_ mentioned */
460 /* Not actually a constant. Just a regular sub. */
461 CV * const cv = (CV *)has_constant;
463 if (CvNAMED(cv) && CvSTASH(cv) == stash && (
464 CvNAME_HEK(cv) == GvNAME_HEK(gv)
465 || ( HEK_LEN(CvNAME_HEK(cv)) == HEK_LEN(GvNAME_HEK(gv))
466 && HEK_FLAGS(CvNAME_HEK(cv)) != HEK_FLAGS(GvNAME_HEK(gv))
467 && HEK_UTF8(CvNAME_HEK(cv)) == HEK_UTF8(GvNAME_HEK(gv))
468 && memEQ(HEK_KEY(CvNAME_HEK(cv)), GvNAME(gv), GvNAMELEN(gv))
476 /* newCONSTSUB takes ownership of the reference from us. */
477 cv = newCONSTSUB_flags(stash, name, len, flags, has_constant);
478 /* In case op.c:S_process_special_blocks stole it: */
480 GvCV_set(gv, (CV *)SvREFCNT_inc_simple_NN(cv));
481 assert(GvCV(gv) == cv); /* newCONSTSUB should have set this */
482 /* If this reference was a copy of another, then the subroutine
483 must have been "imported", by a Perl space assignment to a GV
484 from a reference to CV. */
485 if (exported_constant)
486 GvIMPORTED_CV_on(gv);
487 CvSTASH_set(cv, PL_curstash); /* XXX Why is this needed? */
492 sv_usepvn_flags(MUTABLE_SV(cv), proto, protolen,
493 SV_HAS_TRAILING_NUL);
494 if ( proto_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
500 S_gv_init_svtype(pTHX_ GV *gv, const svtype sv_type)
502 PERL_ARGS_ASSERT_GV_INIT_SVTYPE;
514 #ifdef PERL_DONT_CREATE_GVSV
522 /* Work round what appears to be a bug in Sun C++ 5.8 2005/10/13
523 If we just cast GvSVn(gv) to void, it ignores evaluating it for
530 static void core_xsub(pTHX_ CV* cv);
533 S_maybe_add_coresub(pTHX_ HV * const stash, GV *gv,
534 const char * const name, const STRLEN len)
536 const int code = keyword(name, len, 1);
537 static const char file[] = __FILE__;
538 CV *cv, *oldcompcv = NULL;
540 bool ampable = TRUE; /* &{}-able */
541 COP *oldcurcop = NULL;
542 yy_parser *oldparser = NULL;
543 I32 oldsavestack_ix = 0;
548 if (!code) return NULL; /* Not a keyword */
549 switch (code < 0 ? -code : code) {
550 /* no support for \&CORE::infix;
551 no support for funcs that do not parse like funcs */
552 case KEY___DATA__: case KEY___END__: case KEY_and: case KEY_AUTOLOAD:
553 case KEY_BEGIN : case KEY_CHECK : case KEY_catch : case KEY_cmp:
554 case KEY_default : case KEY_defer : case KEY_DESTROY:
555 case KEY_do : case KEY_dump : case KEY_else : case KEY_elsif :
556 case KEY_END : case KEY_eq : case KEY_eval : case KEY_finally:
557 case KEY_for : case KEY_foreach: case KEY_format: case KEY_ge :
558 case KEY_given : case KEY_goto : case KEY_grep : case KEY_gt :
559 case KEY_if : case KEY_isa : case KEY_INIT : case KEY_last :
560 case KEY_le : case KEY_local : case KEY_lt : case KEY_m :
561 case KEY_map : case KEY_my:
562 case KEY_ne : case KEY_next : case KEY_no: case KEY_or: case KEY_our:
563 case KEY_package: case KEY_print: case KEY_printf:
564 case KEY_q : case KEY_qq : case KEY_qr : case KEY_qw :
565 case KEY_qx : case KEY_redo : case KEY_require: case KEY_return:
566 case KEY_s : case KEY_say : case KEY_sort :
567 case KEY_state: case KEY_sub :
568 case KEY_tr : case KEY_try : case KEY_UNITCHECK: case KEY_unless:
569 case KEY_until: case KEY_use : case KEY_when : case KEY_while :
570 case KEY_x : case KEY_xor : case KEY_y :
573 case KEY_chomp: case KEY_chop: case KEY_defined: case KEY_delete:
574 case KEY_eof : case KEY_exec: case KEY_exists :
579 case KEY_truncate: case KEY_unlink:
584 gv_init(gv, stash, name, len, TRUE);
589 oldcurcop = PL_curcop;
590 oldparser = PL_parser;
591 lex_start(NULL, NULL, 0);
592 oldcompcv = PL_compcv;
593 PL_compcv = NULL; /* Prevent start_subparse from setting
595 oldsavestack_ix = start_subparse(FALSE,0);
599 /* Avoid calling newXS, as it calls us, and things start to
601 cv = MUTABLE_CV(newSV_type(SVt_PVCV));
605 CvXSUB(cv) = core_xsub;
608 CvGV_set(cv, gv); /* This stops new ATTRSUB from setting CvFILE
610 /* XSUBs can't be perl lang/perl5db.pl debugged
611 if (PERLDB_LINE_OR_SAVESRC)
612 (void)gv_fetchfile(file); */
613 CvFILE(cv) = (char *)file;
614 /* XXX This is inefficient, as doing things this order causes
615 a prototype check in newATTRSUB. But we have to do
616 it this order as we need an op number before calling
618 (void)core_prototype((SV *)cv, name, code, &opnum);
620 (void)hv_store(stash,name,len,(SV *)gv,0);
626 /* newATTRSUB will free the CV and return NULL if we're still
627 compiling after a syntax error */
628 if ((cv = newATTRSUB_x(
629 oldsavestack_ix, (OP *)gv,
634 : newSVpvn(name,len),
639 assert(GvCV(gv) == orig_cv);
640 if (opnum != OP_VEC && opnum != OP_SUBSTR && opnum != OP_POS
641 && opnum != OP_UNDEF && opnum != OP_KEYS)
642 CvLVALUE_off(cv); /* Now *that* was a neat trick. */
645 PL_parser = oldparser;
646 PL_curcop = oldcurcop;
647 PL_compcv = oldcompcv;
650 SV *opnumsv = newSViv(
651 (opnum == OP_ENTEREVAL && len == 9 && memEQ(name, "evalbytes", 9)) ?
652 (OP_ENTEREVAL | (1<<16))
653 : opnum ? opnum : (((I32)name[2]) << 16));
654 cv_set_call_checker_flags(cv, Perl_ck_entersub_args_core, opnumsv, 0);
655 SvREFCNT_dec_NN(opnumsv);
662 =for apidoc gv_fetchmeth
664 Like L</gv_fetchmeth_pvn>, but lacks a flags parameter.
666 =for apidoc gv_fetchmeth_sv
668 Exactly like L</gv_fetchmeth_pvn>, but takes the name string in the form
669 of an SV instead of a string/length pair.
675 Perl_gv_fetchmeth_sv(pTHX_ HV *stash, SV *namesv, I32 level, U32 flags)
679 PERL_ARGS_ASSERT_GV_FETCHMETH_SV;
680 if (LIKELY(SvPOK_nog(namesv))) /* common case */
681 return gv_fetchmeth_internal(stash, namesv, NULL, 0, level,
682 flags | SvUTF8(namesv));
683 namepv = SvPV(namesv, namelen);
684 if (SvUTF8(namesv)) flags |= SVf_UTF8;
685 return gv_fetchmeth_pvn(stash, namepv, namelen, level, flags);
689 =for apidoc gv_fetchmeth_pv
691 Exactly like L</gv_fetchmeth_pvn>, but takes a nul-terminated string
692 instead of a string/length pair.
698 Perl_gv_fetchmeth_pv(pTHX_ HV *stash, const char *name, I32 level, U32 flags)
700 PERL_ARGS_ASSERT_GV_FETCHMETH_PV;
701 return gv_fetchmeth_internal(stash, NULL, name, strlen(name), level, flags);
705 =for apidoc gv_fetchmeth_pvn
707 Returns the glob with the given C<name> and a defined subroutine or
708 C<NULL>. The glob lives in the given C<stash>, or in the stashes
709 accessible via C<@ISA> and C<UNIVERSAL::>.
711 The argument C<level> should be either 0 or -1. If C<level==0>, as a
712 side-effect creates a glob with the given C<name> in the given C<stash>
713 which in the case of success contains an alias for the subroutine, and sets
714 up caching info for this glob.
716 The only significant values for C<flags> are C<GV_SUPER>, C<GV_NOUNIVERSAL>, and
719 C<GV_SUPER> indicates that we want to look up the method in the superclasses
722 C<GV_NOUNIVERSAL> indicates that we do not want to look up the method in
723 the stash accessible by C<UNIVERSAL::>.
726 GV returned from C<gv_fetchmeth> may be a method cache entry, which is not
727 visible to Perl code. So when calling C<call_sv>, you should not use
728 the GV directly; instead, you should use the method's CV, which can be
729 obtained from the GV with the C<GvCV> macro.
731 =for apidoc Amnh||GV_SUPER
736 /* NOTE: No support for tied ISA */
738 PERL_STATIC_INLINE GV*
739 S_gv_fetchmeth_internal(pTHX_ HV* stash, SV* meth, const char* name, STRLEN len, I32 level, U32 flags)
746 HV* cstash, *cachestash;
747 GV* candidate = NULL;
752 I32 create = (level >= 0) ? HV_FETCH_LVALUE : 0;
755 U32 is_utf8 = flags & SVf_UTF8;
757 /* UNIVERSAL methods should be callable without a stash */
759 create = 0; /* probably appropriate */
760 if(!(stash = gv_stashpvs("UNIVERSAL", 0)))
766 hvname = HvNAME_get(stash);
767 hvnamelen = HvNAMELEN_get(stash);
769 Perl_croak(aTHX_ "Can't use anonymous symbol table for method lookup");
772 assert(name || meth);
774 DEBUG_o( Perl_deb(aTHX_ "Looking for %smethod %s in package %s\n",
775 flags & GV_SUPER ? "SUPER " : "",
776 name ? name : SvPV_nolen(meth), hvname) );
778 topgen_cmp = HvMROMETA(stash)->cache_gen + PL_sub_generation;
780 if (flags & GV_SUPER) {
781 if (!HvAUX(stash)->xhv_mro_meta->super)
782 HvAUX(stash)->xhv_mro_meta->super = newHV();
783 cachestash = HvAUX(stash)->xhv_mro_meta->super;
785 else cachestash = stash;
787 /* check locally for a real method or a cache entry */
789 cachestash, meth, name, len, is_utf8 ? HVhek_UTF8 : 0, create, NULL, 0
791 if (he) gvp = (GV**)&HeVAL(he);
798 if (SvTYPE(topgv) != SVt_PVGV)
801 name = SvPV_nomg(meth, len);
802 gv_init_pvn(topgv, stash, name, len, GV_ADDMULTI|is_utf8);
804 if ((cand_cv = GvCV(topgv))) {
805 /* If genuine method or valid cache entry, use it */
806 if (!GvCVGEN(topgv) || GvCVGEN(topgv) == topgen_cmp) {
810 /* stale cache entry, junk it and move on */
811 SvREFCNT_dec_NN(cand_cv);
812 GvCV_set(topgv, NULL);
817 else if (GvCVGEN(topgv) == topgen_cmp) {
818 /* cache indicates no such method definitively */
821 else if (stash == cachestash
822 && len > 1 /* shortest is uc */
823 && memEQs(hvname, HvNAMELEN_get(stash), "CORE")
824 && S_maybe_add_coresub(aTHX_ NULL,topgv,name,len))
828 linear_av = mro_get_linear_isa(stash); /* has ourselves at the top of the list */
829 linear_svp = AvARRAY(linear_av) + 1; /* skip over self */
830 items = AvFILLp(linear_av); /* no +1, to skip over self */
832 linear_sv = *linear_svp++;
834 cstash = gv_stashsv(linear_sv, 0);
837 if ( ckWARN(WARN_SYNTAX)) {
838 if( /* these are loaded from Perl_Gv_AMupdate() one way or another */
839 ( len && name[0] == '(' ) /* overload.pm related, in particular "()" */
840 || ( memEQs( name, len, "DESTROY") )
842 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
843 "Can't locate package %" SVf " for @%" HEKf "::ISA",
845 HEKfARG(HvNAME_HEK(stash)));
847 } else if( memEQs( name, len, "AUTOLOAD") ) {
848 /* gobble this warning */
850 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
851 "While trying to resolve method call %.*s->%.*s()"
852 " can not locate package \"%" SVf "\" yet it is mentioned in @%.*s::ISA"
853 " (perhaps you forgot to load \"%" SVf "\"?)",
854 (int) hvnamelen, hvname,
857 (int) hvnamelen, hvname,
866 gvp = (GV**)hv_common(
867 cstash, meth, name, len, is_utf8 ? HVhek_UTF8 : 0, HV_FETCH_JUST_SV, NULL, 0
870 if (len > 1 && HvNAMELEN_get(cstash) == 4) {
871 const char *hvname = HvNAME(cstash); assert(hvname);
872 if (strBEGINs(hvname, "CORE")
874 S_maybe_add_coresub(aTHX_ cstash,NULL,name,len)
880 else candidate = *gvp;
883 if (SvTYPE(candidate) != SVt_PVGV)
884 gv_init_pvn(candidate, cstash, name, len, GV_ADDMULTI|is_utf8);
885 if (SvTYPE(candidate) == SVt_PVGV && (cand_cv = GvCV(candidate)) && !GvCVGEN(candidate)) {
887 * Found real method, cache method in topgv if:
888 * 1. topgv has no synonyms (else inheritance crosses wires)
889 * 2. method isn't a stub (else AUTOLOAD fails spectacularly)
891 if (topgv && (GvREFCNT(topgv) == 1) && (CvROOT(cand_cv) || CvXSUB(cand_cv))) {
892 CV *old_cv = GvCV(topgv);
893 SvREFCNT_dec(old_cv);
894 SvREFCNT_inc_simple_void_NN(cand_cv);
895 GvCV_set(topgv, cand_cv);
896 GvCVGEN(topgv) = topgen_cmp;
902 /* Check UNIVERSAL without caching */
903 if((level == 0 || level == -1) && !(flags & GV_NOUNIVERSAL)) {
904 candidate = gv_fetchmeth_internal(NULL, meth, name, len, 1,
907 cand_cv = GvCV(candidate);
908 if (topgv && (GvREFCNT(topgv) == 1) && (CvROOT(cand_cv) || CvXSUB(cand_cv))) {
909 CV *old_cv = GvCV(topgv);
910 SvREFCNT_dec(old_cv);
911 SvREFCNT_inc_simple_void_NN(cand_cv);
912 GvCV_set(topgv, cand_cv);
913 GvCVGEN(topgv) = topgen_cmp;
919 if (topgv && GvREFCNT(topgv) == 1) {
920 /* cache the fact that the method is not defined */
921 GvCVGEN(topgv) = topgen_cmp;
928 Perl_gv_fetchmeth_pvn(pTHX_ HV *stash, const char *name, STRLEN len, I32 level, U32 flags)
930 PERL_ARGS_ASSERT_GV_FETCHMETH_PVN;
931 return gv_fetchmeth_internal(stash, NULL, name, len, level, flags);
935 =for apidoc gv_fetchmeth_autoload
937 This is the old form of L</gv_fetchmeth_pvn_autoload>, which has no flags
940 =for apidoc gv_fetchmeth_sv_autoload
942 Exactly like L</gv_fetchmeth_pvn_autoload>, but takes the name string in the form
943 of an SV instead of a string/length pair.
949 Perl_gv_fetchmeth_sv_autoload(pTHX_ HV *stash, SV *namesv, I32 level, U32 flags)
953 PERL_ARGS_ASSERT_GV_FETCHMETH_SV_AUTOLOAD;
954 namepv = SvPV(namesv, namelen);
957 return gv_fetchmeth_pvn_autoload(stash, namepv, namelen, level, flags);
961 =for apidoc gv_fetchmeth_pv_autoload
963 Exactly like L</gv_fetchmeth_pvn_autoload>, but takes a nul-terminated string
964 instead of a string/length pair.
970 Perl_gv_fetchmeth_pv_autoload(pTHX_ HV *stash, const char *name, I32 level, U32 flags)
972 PERL_ARGS_ASSERT_GV_FETCHMETH_PV_AUTOLOAD;
973 return gv_fetchmeth_pvn_autoload(stash, name, strlen(name), level, flags);
977 =for apidoc gv_fetchmeth_pvn_autoload
979 Same as C<gv_fetchmeth_pvn()>, but looks for autoloaded subroutines too.
980 Returns a glob for the subroutine.
982 For an autoloaded subroutine without a GV, will create a GV even
983 if C<level < 0>. For an autoloaded subroutine without a stub, C<GvCV()>
984 of the result may be zero.
986 Currently, the only significant value for C<flags> is C<SVf_UTF8>.
992 Perl_gv_fetchmeth_pvn_autoload(pTHX_ HV *stash, const char *name, STRLEN len, I32 level, U32 flags)
994 GV *gv = gv_fetchmeth_pvn(stash, name, len, level, flags);
996 PERL_ARGS_ASSERT_GV_FETCHMETH_PVN_AUTOLOAD;
1003 return NULL; /* UNIVERSAL::AUTOLOAD could cause trouble */
1004 if (len == S_autolen && memEQ(name, S_autoload, S_autolen))
1006 if (!(gv = gv_fetchmeth_pvn(stash, S_autoload, S_autolen, FALSE, flags)))
1009 if (!(CvROOT(cv) || CvXSUB(cv)))
1011 /* Have an autoload */
1012 if (level < 0) /* Cannot do without a stub */
1013 gv_fetchmeth_pvn(stash, name, len, 0, flags);
1014 gvp = (GV**)hv_fetch(stash, name,
1015 (flags & SVf_UTF8) ? -(I32)len : (I32)len, (level >= 0));
1024 =for apidoc gv_fetchmethod_autoload
1026 Returns the glob which contains the subroutine to call to invoke the method
1027 on the C<stash>. In fact in the presence of autoloading this may be the
1028 glob for "AUTOLOAD". In this case the corresponding variable C<$AUTOLOAD> is
1031 The third parameter of C<gv_fetchmethod_autoload> determines whether
1032 AUTOLOAD lookup is performed if the given method is not present: non-zero
1033 means yes, look for AUTOLOAD; zero means no, don't look for AUTOLOAD.
1034 Calling C<gv_fetchmethod> is equivalent to calling C<gv_fetchmethod_autoload>
1035 with a non-zero C<autoload> parameter.
1037 These functions grant C<"SUPER"> token
1038 as a prefix of the method name. Note
1039 that if you want to keep the returned glob for a long time, you need to
1040 check for it being "AUTOLOAD", since at the later time the call may load a
1041 different subroutine due to C<$AUTOLOAD> changing its value. Use the glob
1042 created as a side effect to do this.
1044 These functions have the same side-effects as C<gv_fetchmeth> with
1045 C<level==0>. The warning against passing the GV returned by
1046 C<gv_fetchmeth> to C<call_sv> applies equally to these functions.
1052 Perl_gv_fetchmethod_autoload(pTHX_ HV *stash, const char *name, I32 autoload)
1054 PERL_ARGS_ASSERT_GV_FETCHMETHOD_AUTOLOAD;
1056 return gv_fetchmethod_flags(stash, name, autoload ? GV_AUTOLOAD : 0);
1060 Perl_gv_fetchmethod_sv_flags(pTHX_ HV *stash, SV *namesv, U32 flags)
1064 PERL_ARGS_ASSERT_GV_FETCHMETHOD_SV_FLAGS;
1065 namepv = SvPV(namesv, namelen);
1068 return gv_fetchmethod_pvn_flags(stash, namepv, namelen, flags);
1072 Perl_gv_fetchmethod_pv_flags(pTHX_ HV *stash, const char *name, U32 flags)
1074 PERL_ARGS_ASSERT_GV_FETCHMETHOD_PV_FLAGS;
1075 return gv_fetchmethod_pvn_flags(stash, name, strlen(name), flags);
1079 Perl_gv_fetchmethod_pvn_flags(pTHX_ HV *stash, const char *name, const STRLEN len, U32 flags)
1081 const char * const origname = name;
1082 const char * const name_end = name + len;
1083 const char *last_separator = NULL;
1086 SV *const error_report = MUTABLE_SV(stash);
1087 const U32 autoload = flags & GV_AUTOLOAD;
1088 const U32 do_croak = flags & GV_CROAK;
1089 const U32 is_utf8 = flags & SVf_UTF8;
1091 PERL_ARGS_ASSERT_GV_FETCHMETHOD_PVN_FLAGS;
1093 if (SvTYPE(stash) < SVt_PVHV)
1096 /* The only way stash can become NULL later on is if last_separator is set,
1097 which in turn means that there is no need for a SVt_PVHV case
1098 the error reporting code. */
1102 /* check if the method name is fully qualified or
1103 * not, and separate the package name from the actual
1106 * leaves last_separator pointing to the beginning of the
1107 * last package separator (either ' or ::) or 0
1108 * if none was found.
1110 * leaves name pointing at the beginning of the
1113 const char *name_cursor = name;
1114 const char * const name_em1 = name_end - 1; /* name_end minus 1 */
1115 for (name_cursor = name; name_cursor < name_end ; name_cursor++) {
1116 if (*name_cursor == '\'') {
1117 last_separator = name_cursor;
1118 name = name_cursor + 1;
1120 else if (name_cursor < name_em1 && *name_cursor == ':' && name_cursor[1] == ':') {
1121 last_separator = name_cursor++;
1122 name = name_cursor + 1;
1127 /* did we find a separator? */
1128 if (last_separator) {
1129 STRLEN sep_len= last_separator - origname;
1130 if ( memEQs(origname, sep_len, "SUPER")) {
1131 /* ->SUPER::method should really be looked up in original stash */
1132 stash = CopSTASH(PL_curcop);
1134 DEBUG_o( Perl_deb(aTHX_ "Treating %s as %s::%s\n",
1135 origname, HvENAME_get(stash), name) );
1137 else if ( sep_len >= 7 &&
1138 strBEGINs(last_separator - 7, "::SUPER")) {
1139 /* don't autovifify if ->NoSuchStash::SUPER::method */
1140 stash = gv_stashpvn(origname, sep_len - 7, is_utf8);
1141 if (stash) flags |= GV_SUPER;
1144 /* don't autovifify if ->NoSuchStash::method */
1145 stash = gv_stashpvn(origname, sep_len, is_utf8);
1150 gv = gv_fetchmeth_pvn(stash, name, name_end - name, 0, flags);
1152 /* This is the special case that exempts Foo->import and
1153 Foo->unimport from being an error even if there's no
1154 import/unimport subroutine */
1155 if (strEQ(name,"import") || strEQ(name,"unimport")) {
1156 gv = (GV*)sv_2mortal((SV*)newCONSTSUB_flags(NULL,
1158 } else if (autoload)
1159 gv = gv_autoload_pvn(
1160 ostash, name, name_end - name, GV_AUTOLOAD_ISMETHOD|flags
1162 if (!gv && do_croak) {
1163 /* Right now this is exclusively for the benefit of S_method_common
1166 /* If we can't find an IO::File method, it might be a call on
1167 * a filehandle. If IO:File has not been loaded, try to
1168 * require it first instead of croaking */
1169 const char *stash_name = HvNAME_get(stash);
1170 if (stash_name && memEQs(stash_name, HvNAMELEN_get(stash), "IO::File")
1171 && !Perl_hv_common(aTHX_ GvHVn(PL_incgv), NULL,
1172 STR_WITH_LEN("IO/File.pm"), 0,
1173 HV_FETCH_ISEXISTS, NULL, 0)
1175 require_pv("IO/File.pm");
1176 gv = gv_fetchmeth_pvn(stash, name, name_end - name, 0, flags);
1181 "Can't locate object method \"%" UTF8f
1182 "\" via package \"%" HEKf "\"",
1183 UTF8fARG(is_utf8, name_end - name, name),
1184 HEKfARG(HvNAME_HEK(stash)));
1189 if (last_separator) {
1190 packnamesv = newSVpvn_flags(origname, last_separator - origname,
1191 SVs_TEMP | is_utf8);
1193 packnamesv = error_report;
1197 "Can't locate object method \"%" UTF8f
1198 "\" via package \"%" SVf "\""
1199 " (perhaps you forgot to load \"%" SVf "\"?)",
1200 UTF8fARG(is_utf8, name_end - name, name),
1201 SVfARG(packnamesv), SVfARG(packnamesv));
1205 else if (autoload) {
1206 CV* const cv = GvCV(gv);
1207 if (!CvROOT(cv) && !CvXSUB(cv)) {
1211 if (CvANON(cv) || CvLEXICAL(cv))
1215 if (GvCV(stubgv) != cv) /* orphaned import */
1218 autogv = gv_autoload_pvn(GvSTASH(stubgv),
1219 GvNAME(stubgv), GvNAMELEN(stubgv),
1220 GV_AUTOLOAD_ISMETHOD
1221 | (GvNAMEUTF8(stubgv) ? SVf_UTF8 : 0));
1231 Perl_gv_autoload_sv(pTHX_ HV *stash, SV* namesv, U32 flags)
1235 PERL_ARGS_ASSERT_GV_AUTOLOAD_SV;
1236 namepv = SvPV(namesv, namelen);
1239 return gv_autoload_pvn(stash, namepv, namelen, flags);
1243 Perl_gv_autoload_pv(pTHX_ HV *stash, const char *namepv, U32 flags)
1245 PERL_ARGS_ASSERT_GV_AUTOLOAD_PV;
1246 return gv_autoload_pvn(stash, namepv, strlen(namepv), flags);
1250 Perl_gv_autoload_pvn(pTHX_ HV *stash, const char *name, STRLEN len, U32 flags)
1257 SV *packname = NULL;
1258 U32 is_utf8 = flags & SVf_UTF8 ? SVf_UTF8 : 0;
1260 PERL_ARGS_ASSERT_GV_AUTOLOAD_PVN;
1262 if (len == S_autolen && memEQ(name, S_autoload, S_autolen))
1265 if (SvTYPE(stash) < SVt_PVHV) {
1266 STRLEN packname_len = 0;
1267 const char * const packname_ptr = SvPV_const(MUTABLE_SV(stash), packname_len);
1268 packname = newSVpvn_flags(packname_ptr, packname_len,
1269 SVs_TEMP | SvUTF8(stash));
1273 packname = sv_2mortal(newSVhek(HvNAME_HEK(stash)));
1274 if (flags & GV_SUPER) sv_catpvs(packname, "::SUPER");
1276 if (!(gv = gv_fetchmeth_pvn(stash, S_autoload, S_autolen, FALSE,
1277 is_utf8 | (flags & GV_SUPER))))
1281 if (!(CvROOT(cv) || CvXSUB(cv)))
1285 * Inheriting AUTOLOAD for non-methods no longer works
1288 !(flags & GV_AUTOLOAD_ISMETHOD)
1289 && (GvCVGEN(gv) || GvSTASH(gv) != stash)
1291 Perl_croak(aTHX_ "Use of inherited AUTOLOAD for non-method %" SVf
1292 "::%" UTF8f "() is no longer allowed",
1294 UTF8fARG(is_utf8, len, name));
1297 /* Instead of forcing the XSUB do another lookup for $AUTOLOAD
1298 * and split that value on the last '::', pass along the same data
1299 * via the SvPVX field in the CV, and the stash in CvSTASH.
1301 * Due to an unfortunate accident of history, the SvPVX field
1302 * serves two purposes. It is also used for the subroutine's pro-
1303 * type. Since SvPVX has been documented as returning the sub name
1304 * for a long time, but not as returning the prototype, we have
1305 * to preserve the SvPVX AUTOLOAD behaviour and put the prototype
1308 * We put the prototype in the same allocated buffer, but after
1309 * the sub name. The SvPOK flag indicates the presence of a proto-
1310 * type. The CvAUTOLOAD flag indicates the presence of a sub name.
1311 * If both flags are on, then SvLEN is used to indicate the end of
1312 * the prototype (artificially lower than what is actually allo-
1313 * cated), at the risk of having to reallocate a few bytes unneces-
1314 * sarily--but that should happen very rarely, if ever.
1316 * We use SvUTF8 for both prototypes and sub names, so if one is
1317 * UTF8, the other must be upgraded.
1319 CvSTASH_set(cv, stash);
1320 if (SvPOK(cv)) { /* Ouch! */
1321 SV * const tmpsv = newSVpvn_flags(name, len, is_utf8);
1323 const char *proto = CvPROTO(cv);
1326 sv_utf8_upgrade_flags_grow(tmpsv, 0, CvPROTOLEN(cv) + 2);
1327 ulen = SvCUR(tmpsv);
1328 SvCUR_set(tmpsv, SvCUR(tmpsv) + 1); /* include null in string */
1330 tmpsv, proto, CvPROTOLEN(cv), SV_CATBYTES*!SvUTF8(cv)
1332 SvTEMP_on(tmpsv); /* Allow theft */
1333 sv_setsv_nomg((SV *)cv, tmpsv);
1335 SvREFCNT_dec_NN(tmpsv);
1336 SvLEN_set(cv, SvCUR(cv) + 1);
1337 SvCUR_set(cv, ulen);
1340 sv_setpvn((SV *)cv, name, len);
1344 else SvUTF8_off(cv);
1350 * Given &FOO::AUTOLOAD, set $FOO::AUTOLOAD to desired function name.
1351 * The subroutine's original name may not be "AUTOLOAD", so we don't
1352 * use that, but for lack of anything better we will use the sub's
1353 * original package to look up $AUTOLOAD.
1355 varstash = CvNAMED(cv) ? CvSTASH(cv) : GvSTASH(CvGV(cv));
1356 vargv = *(GV**)hv_fetch(varstash, S_autoload, S_autolen, TRUE);
1360 gv_init_pvn(vargv, varstash, S_autoload, S_autolen, 0);
1361 #ifdef PERL_DONT_CREATE_GVSV
1362 GvSV(vargv) = newSV(0);
1366 varsv = GvSVn(vargv);
1367 SvTAINTED_off(varsv); /* previous $AUTOLOAD taint is obsolete */
1368 /* XXX: this process is not careful to avoid extra magic gets and sets; tied $AUTOLOAD will get noise */
1369 sv_setsv(varsv, packname);
1370 sv_catpvs(varsv, "::");
1371 /* Ensure SvSETMAGIC() is called if necessary. In particular, to clear
1372 tainting if $FOO::AUTOLOAD was previously tainted, but is not now. */
1375 SV_SMAGIC|(is_utf8 ? SV_CATUTF8 : SV_CATBYTES)
1383 /* require_tie_mod() internal routine for requiring a module
1384 * that implements the logic of automatic ties like %! and %-
1385 * It loads the module and then calls the _tie_it subroutine
1386 * with the passed gv as an argument.
1388 * The "gv" parameter should be the glob.
1389 * "varname" holds the 1-char name of the var, used for error messages.
1390 * "namesv" holds the module name. Its refcount will be decremented.
1391 * "flags": if flag & 1 then save the scalar before loading.
1392 * For the protection of $! to work (it is set by this routine)
1393 * the sv slot must already be magicalized.
1396 S_require_tie_mod(pTHX_ GV *gv, const char varname, const char * name,
1397 STRLEN len, const U32 flags)
1399 const SV * const target = varname == '[' ? GvSV(gv) : (SV *)GvHV(gv);
1401 PERL_ARGS_ASSERT_REQUIRE_TIE_MOD;
1403 /* If it is not tied */
1404 if (!target || !SvRMAGICAL(target)
1406 varname == '[' ? PERL_MAGIC_tiedscalar : PERL_MAGIC_tied))
1412 PUSHSTACKi(PERLSI_MAGIC);
1415 #define GET_HV_FETCH_TIE_FUNC \
1416 ( (gvp = (GV **)hv_fetchs(stash, "_tie_it", 0)) \
1418 && ( (isGV(*gvp) && GvCV(*gvp)) \
1419 || (SvROK(*gvp) && SvTYPE(SvRV(*gvp)) == SVt_PVCV) ) \
1422 /* Load the module if it is not loaded. */
1423 if (!(stash = gv_stashpvn(name, len, 0))
1424 || ! GET_HV_FETCH_TIE_FUNC)
1426 SV * const module = newSVpvn(name, len);
1427 const char type = varname == '[' ? '$' : '%';
1430 Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT, module, NULL);
1431 assert(sp == PL_stack_sp);
1432 stash = gv_stashpvn(name, len, 0);
1434 Perl_croak(aTHX_ "panic: Can't use %c%c because %s is not available",
1435 type, varname, name);
1436 else if (! GET_HV_FETCH_TIE_FUNC)
1437 Perl_croak(aTHX_ "panic: Can't use %c%c because %s does not define _tie_it",
1438 type, varname, name);
1440 /* Now call the tie function. It should be in *gvp. */
1441 assert(gvp); assert(*gvp);
1445 call_sv((SV *)*gvp, G_VOID|G_DISCARD);
1451 /* add a require_tie_mod_s - the _s suffix is similar to pvs type suffixes,
1452 * IOW it means we do STR_WITH_LEN() ourselves and the user should pass in
1453 * a true string WITHOUT a len.
1455 #define require_tie_mod_s(gv, varname, name, flags) \
1456 S_require_tie_mod(aTHX_ gv, varname, STR_WITH_LEN(name), flags)
1459 =for apidoc gv_stashpv
1461 Returns a pointer to the stash for a specified package. Uses C<strlen> to
1462 determine the length of C<name>, then calls C<gv_stashpvn()>.
1468 Perl_gv_stashpv(pTHX_ const char *name, I32 create)
1470 PERL_ARGS_ASSERT_GV_STASHPV;
1471 return gv_stashpvn(name, strlen(name), create);
1475 =for apidoc gv_stashpvn
1477 Returns a pointer to the stash for a specified package. The C<namelen>
1478 parameter indicates the length of the C<name>, in bytes. C<flags> is passed
1479 to C<gv_fetchpvn_flags()>, so if set to C<GV_ADD> then the package will be
1480 created if it does not already exist. If the package does not exist and
1481 C<flags> is 0 (or any other setting that does not create packages) then C<NULL>
1484 Flags may be one of:
1486 GV_ADD Create and initialize the package if doesn't
1488 GV_NOADD_NOINIT Don't create the package,
1489 GV_ADDMG GV_ADD iff the GV is magical
1490 GV_NOINIT GV_ADD, but don't initialize
1491 GV_NOEXPAND Don't expand SvOK() entries to PVGV
1492 SVf_UTF8 The name is in UTF-8
1494 The most important of which are probably C<GV_ADD> and C<SVf_UTF8>.
1496 Note, use of C<gv_stashsv> instead of C<gv_stashpvn> where possible is strongly
1497 recommended for performance reasons.
1499 =for apidoc Amnh||GV_ADD
1500 =for apidoc Amnh||GV_NOADD_NOINIT
1501 =for apidoc Amnh||GV_NOINIT
1502 =for apidoc Amnh||GV_NOEXPAND
1503 =for apidoc Amnh||GV_ADDMG
1504 =for apidoc Amnh||SVf_UTF8
1510 gv_stashpvn_internal
1512 Perform the internal bits of gv_stashsvpvn_cached. You could think of this
1513 as being one half of the logic. Not to be called except from gv_stashsvpvn_cached().
1517 PERL_STATIC_INLINE HV*
1518 S_gv_stashpvn_internal(pTHX_ const char *name, U32 namelen, I32 flags)
1524 U32 tmplen = namelen + 2;
1526 PERL_ARGS_ASSERT_GV_STASHPVN_INTERNAL;
1528 if (tmplen <= sizeof smallbuf)
1531 Newx(tmpbuf, tmplen, char);
1532 Copy(name, tmpbuf, namelen, char);
1533 tmpbuf[namelen] = ':';
1534 tmpbuf[namelen+1] = ':';
1535 tmpgv = gv_fetchpvn_flags(tmpbuf, tmplen, flags, SVt_PVHV);
1536 if (tmpbuf != smallbuf)
1538 if (!tmpgv || !isGV_with_GP(tmpgv))
1540 stash = GvHV(tmpgv);
1541 if (!(flags & ~GV_NOADD_MASK) && !stash) return NULL;
1543 if (!HvNAME_get(stash)) {
1544 hv_name_set(stash, name, namelen, flags & SVf_UTF8 ? SVf_UTF8 : 0 );
1546 /* FIXME: This is a repeat of logic in gv_fetchpvn_flags */
1547 /* If the containing stash has multiple effective
1548 names, see that this one gets them, too. */
1549 if (HvAUX(GvSTASH(tmpgv))->xhv_name_count)
1550 mro_package_moved(stash, NULL, tmpgv, 1);
1556 =for apidoc gv_stashsvpvn_cached
1558 Returns a pointer to the stash for a specified package, possibly
1559 cached. Implements both L<perlapi/C<gv_stashpvn>> and
1560 L<perlapi/C<gv_stashsv>>.
1562 Requires one of either C<namesv> or C<namepv> to be non-null.
1564 If the flag C<GV_CACHE_ONLY> is set, return the stash only if found in the
1565 cache; see L<perlapi/C<gv_stashpvn>> for details on the other C<flags>.
1567 Note it is strongly preferred for C<namesv> to be non-null, for performance
1570 =for apidoc Emnh||GV_CACHE_ONLY
1575 #define PERL_ARGS_ASSERT_GV_STASHSVPVN_CACHED \
1576 assert(namesv || name)
1579 Perl_gv_stashsvpvn_cached(pTHX_ SV *namesv, const char *name, U32 namelen, I32 flags)
1584 PERL_ARGS_ASSERT_GV_STASHSVPVN_CACHED;
1586 he = (HE *)hv_common(
1587 PL_stashcache, namesv, name, namelen,
1588 (flags & SVf_UTF8) ? HVhek_UTF8 : 0, 0, NULL, 0
1595 hv = INT2PTR(HV*, SvIVX(sv));
1596 assert(SvTYPE(hv) == SVt_PVHV);
1599 else if (flags & GV_CACHE_ONLY) return NULL;
1602 if (SvOK(namesv)) { /* prevent double uninit warning */
1604 name = SvPV_const(namesv, len);
1606 flags |= SvUTF8(namesv);
1608 name = ""; namelen = 0;
1611 stash = gv_stashpvn_internal(name, namelen, flags);
1613 if (stash && namelen) {
1614 SV* const ref = newSViv(PTR2IV(stash));
1615 (void)hv_store(PL_stashcache, name,
1616 (flags & SVf_UTF8) ? -(I32)namelen : (I32)namelen, ref, 0);
1623 Perl_gv_stashpvn(pTHX_ const char *name, U32 namelen, I32 flags)
1625 PERL_ARGS_ASSERT_GV_STASHPVN;
1626 return gv_stashsvpvn_cached(NULL, name, namelen, flags);
1630 =for apidoc gv_stashsv
1632 Returns a pointer to the stash for a specified package. See
1635 Note this interface is strongly preferred over C<gv_stashpvn> for performance
1642 Perl_gv_stashsv(pTHX_ SV *sv, I32 flags)
1644 PERL_ARGS_ASSERT_GV_STASHSV;
1645 return gv_stashsvpvn_cached(sv, NULL, 0, flags);
1648 Perl_gv_fetchpv(pTHX_ const char *nambeg, I32 flags, const svtype sv_type) {
1649 PERL_ARGS_ASSERT_GV_FETCHPV;
1650 return gv_fetchpvn_flags(nambeg, strlen(nambeg), flags, sv_type);
1654 Perl_gv_fetchsv(pTHX_ SV *name, I32 flags, const svtype sv_type) {
1656 const char * const nambeg =
1657 SvPV_flags_const(name, len, flags & GV_NO_SVGMAGIC ? 0 : SV_GMAGIC);
1658 PERL_ARGS_ASSERT_GV_FETCHSV;
1659 return gv_fetchpvn_flags(nambeg, len, flags | SvUTF8(name), sv_type);
1662 PERL_STATIC_INLINE void
1663 S_gv_magicalize_isa(pTHX_ GV *gv)
1667 PERL_ARGS_ASSERT_GV_MAGICALIZE_ISA;
1671 sv_magic(MUTABLE_SV(av), MUTABLE_SV(gv), PERL_MAGIC_isa,
1675 /* This function grabs name and tries to split a stash and glob
1676 * from its contents. TODO better description, comments
1678 * If the function returns TRUE and 'name == name_end', then
1679 * 'gv' can be directly returned to the caller of gv_fetchpvn_flags
1681 PERL_STATIC_INLINE bool
1682 S_parse_gv_stash_name(pTHX_ HV **stash, GV **gv, const char **name,
1683 STRLEN *len, const char *nambeg, STRLEN full_len,
1684 const U32 is_utf8, const I32 add)
1686 char *tmpfullbuf = NULL; /* only malloc one big chunk of memory when the smallbuff is not large enough */
1687 const char *name_cursor;
1688 const char *const name_end = nambeg + full_len;
1689 const char *const name_em1 = name_end - 1;
1690 char smallbuf[64]; /* small buffer to avoid a malloc when possible */
1692 PERL_ARGS_ASSERT_PARSE_GV_STASH_NAME;
1696 && isIDFIRST_lazy_if_safe(*name + 1, name_end, is_utf8))
1698 /* accidental stringify on a GV? */
1702 for (name_cursor = *name; name_cursor < name_end; name_cursor++) {
1703 if (name_cursor < name_em1 &&
1704 ((*name_cursor == ':' && name_cursor[1] == ':')
1705 || *name_cursor == '\''))
1708 *stash = PL_defstash;
1709 if (!*stash || !SvREFCNT(*stash)) /* symbol table under destruction */
1712 *len = name_cursor - *name;
1713 if (name_cursor > nambeg) { /* Skip for initial :: or ' */
1716 if (*name_cursor == ':') {
1720 else { /* using ' for package separator */
1721 /* use our pre-allocated buffer when possible to save a malloc */
1723 if ( *len+2 <= sizeof smallbuf)
1726 /* only malloc once if needed */
1727 if (tmpfullbuf == NULL) /* only malloc&free once, a little more than needed */
1728 Newx(tmpfullbuf, full_len+2, char);
1729 tmpbuf = tmpfullbuf;
1731 Copy(*name, tmpbuf, *len, char);
1732 tmpbuf[(*len)++] = ':';
1733 tmpbuf[(*len)++] = ':';
1736 gvp = (GV**)hv_fetch(*stash, key, is_utf8 ? -((I32)*len) : (I32)*len, add);
1737 *gv = gvp ? *gvp : NULL;
1738 if (!*gv || *gv == (const GV *)&PL_sv_undef) {
1741 /* here we know that *gv && *gv != &PL_sv_undef */
1742 if (SvTYPE(*gv) != SVt_PVGV)
1743 gv_init_pvn(*gv, *stash, key, *len, (add & GV_ADDMULTI)|is_utf8);
1747 if (!(*stash = GvHV(*gv))) {
1748 *stash = GvHV(*gv) = newHV();
1749 if (!HvNAME_get(*stash)) {
1750 if (GvSTASH(*gv) == PL_defstash && *len == 6
1751 && strBEGINs(*name, "CORE"))
1752 hv_name_sets(*stash, "CORE", 0);
1755 *stash, nambeg, name_cursor-nambeg, is_utf8
1757 /* If the containing stash has multiple effective
1758 names, see that this one gets them, too. */
1759 if (HvAUX(GvSTASH(*gv))->xhv_name_count)
1760 mro_package_moved(*stash, NULL, *gv, 1);
1763 else if (!HvNAME_get(*stash))
1764 hv_name_set(*stash, nambeg, name_cursor - nambeg, is_utf8);
1767 if (*name_cursor == ':')
1769 *name = name_cursor+1;
1770 if (*name == name_end) {
1772 *gv = MUTABLE_GV(*hv_fetchs(PL_defstash, "main::", TRUE));
1773 if (SvTYPE(*gv) != SVt_PVGV) {
1774 gv_init_pvn(*gv, PL_defstash, "main::", 6,
1777 MUTABLE_HV(SvREFCNT_inc_simple(PL_defstash));
1784 *len = name_cursor - *name;
1786 Safefree(tmpfullbuf); /* free our tmpfullbuf if it was used */
1789 Safefree(tmpfullbuf); /* free our tmpfullbuf if it was used */
1794 /* Checks if an unqualified name is in the main stash */
1795 PERL_STATIC_INLINE bool
1796 S_gv_is_in_main(pTHX_ const char *name, STRLEN len, const U32 is_utf8)
1798 PERL_ARGS_ASSERT_GV_IS_IN_MAIN;
1800 /* If it's an alphanumeric variable */
1801 if ( len && isIDFIRST_lazy_if_safe(name, name + len, is_utf8) ) {
1802 /* Some "normal" variables are always in main::,
1803 * like INC or STDOUT.
1811 if ((name[0] == 'I' && name[1] == 'N' && name[2] == 'C')
1812 || (name[0] == 'E' && name[1] == 'N' && name[2] == 'V')
1813 || (name[0] == 'S' && name[1] == 'I' && name[2] == 'G'))
1817 if (name[0] == 'A' && name[1] == 'R' && name[2] == 'G'
1822 if (name[0] == 'S' && name[1] == 'T' && name[2] == 'D'
1823 && name[3] == 'I' && name[4] == 'N')
1827 if ((name[0] == 'S' && name[1] == 'T' && name[2] == 'D')
1828 &&((name[3] == 'O' && name[4] == 'U' && name[5] == 'T')
1829 ||(name[3] == 'E' && name[4] == 'R' && name[5] == 'R')))
1833 if (name[0] == 'A' && name[1] == 'R' && name[2] == 'G'
1834 && name[3] == 'V' && name[4] == 'O' && name[5] == 'U'
1840 /* *{""}, or a special variable like $@ */
1848 /* This function is called if parse_gv_stash_name() failed to
1849 * find a stash, or if GV_NOTQUAL or an empty name was passed
1850 * to gv_fetchpvn_flags.
1852 * It returns FALSE if the default stash can't be found nor created,
1853 * which might happen during global destruction.
1855 PERL_STATIC_INLINE bool
1856 S_find_default_stash(pTHX_ HV **stash, const char *name, STRLEN len,
1857 const U32 is_utf8, const I32 add,
1858 const svtype sv_type)
1860 PERL_ARGS_ASSERT_FIND_DEFAULT_STASH;
1862 /* No stash in name, so see how we can default */
1864 if ( gv_is_in_main(name, len, is_utf8) ) {
1865 *stash = PL_defstash;
1868 if (IN_PERL_COMPILETIME) {
1869 *stash = PL_curstash;
1870 if (add && (PL_hints & HINT_STRICT_VARS) &&
1871 sv_type != SVt_PVCV &&
1872 sv_type != SVt_PVGV &&
1873 sv_type != SVt_PVFM &&
1874 sv_type != SVt_PVIO &&
1875 !(len == 1 && sv_type == SVt_PV &&
1876 (*name == 'a' || *name == 'b')) )
1878 GV**gvp = (GV**)hv_fetch(*stash,name,is_utf8 ? -(I32)len : (I32)len,0);
1879 if (!gvp || *gvp == (const GV *)&PL_sv_undef ||
1880 SvTYPE(*gvp) != SVt_PVGV)
1884 else if ((sv_type == SVt_PV && !GvIMPORTED_SV(*gvp)) ||
1885 (sv_type == SVt_PVAV && !GvIMPORTED_AV(*gvp)) ||
1886 (sv_type == SVt_PVHV && !GvIMPORTED_HV(*gvp)) )
1888 /* diag_listed_as: Variable "%s" is not imported%s */
1890 aTHX_ packWARN(WARN_MISC),
1891 "Variable \"%c%" UTF8f "\" is not imported",
1892 sv_type == SVt_PVAV ? '@' :
1893 sv_type == SVt_PVHV ? '%' : '$',
1894 UTF8fARG(is_utf8, len, name));
1897 aTHX_ packWARN(WARN_MISC),
1898 "\t(Did you mean &%" UTF8f " instead?)\n",
1899 UTF8fARG(is_utf8, len, name)
1906 /* Use the current op's stash */
1907 *stash = CopSTASH(PL_curcop);
1912 if (add && !PL_in_clean_all) {
1914 qerror(Perl_mess(aTHX_
1915 "Global symbol \"%s%" UTF8f
1916 "\" requires explicit package name (did you forget to "
1917 "declare \"my %s%" UTF8f "\"?)",
1918 (sv_type == SVt_PV ? "$"
1919 : sv_type == SVt_PVAV ? "@"
1920 : sv_type == SVt_PVHV ? "%"
1921 : ""), UTF8fARG(is_utf8, len, name),
1922 (sv_type == SVt_PV ? "$"
1923 : sv_type == SVt_PVAV ? "@"
1924 : sv_type == SVt_PVHV ? "%"
1925 : ""), UTF8fARG(is_utf8, len, name)));
1926 /* To maintain the output of errors after the strict exception
1927 * above, and to keep compat with older releases, rather than
1928 * placing the variables in the pad, we place
1929 * them in the <none>:: stash.
1931 gv = gv_fetchpvs("<none>::", GV_ADDMULTI, SVt_PVHV);
1933 /* symbol table under destruction */
1942 if (!SvREFCNT(*stash)) /* symbol table under destruction */
1948 /* gv_magicalize only turns on the SVf_READONLY flag, not SVf_PROTECT. So
1949 redefine SvREADONLY_on for that purpose. We don’t use it later on in
1951 #undef SvREADONLY_on
1952 #define SvREADONLY_on(sv) (SvFLAGS(sv) |= SVf_READONLY)
1954 /* gv_magicalize() is called by gv_fetchpvn_flags when creating
1956 * Note that it does not insert the GV into the stash prior to
1957 * magicalization, which some variables require need in order
1958 * to work (like %+, %-, %!), so callers must take care of
1961 * It returns true if the gv did turn out to be magical one; i.e.,
1962 * if gv_magicalize actually did something.
1964 PERL_STATIC_INLINE bool
1965 S_gv_magicalize(pTHX_ GV *gv, HV *stash, const char *name, STRLEN len,
1966 const svtype sv_type)
1970 PERL_ARGS_ASSERT_GV_MAGICALIZE;
1972 if (stash != PL_defstash) { /* not the main stash */
1973 /* We only have to check for a few names here: a, b, EXPORT, ISA
1974 and VERSION. All the others apply only to the main stash or to
1975 CORE (which is checked right after this). */
1980 len >= 6 && name[1] == 'X' &&
1981 (memEQs(name, len, "EXPORT")
1982 ||memEQs(name, len, "EXPORT_OK")
1983 ||memEQs(name, len, "EXPORT_FAIL")
1984 ||memEQs(name, len, "EXPORT_TAGS"))
1989 if (memEQs(name, len, "ISA"))
1990 gv_magicalize_isa(gv);
1993 if (memEQs(name, len, "VERSION"))
1997 if (stash == PL_debstash && memEQs(name, len, "args")) {
1998 GvMULTI_on(gv_AVadd(gv));
2003 if (len == 1 && sv_type == SVt_PV)
2012 if (len > 1 /* shortest is uc */ && HvNAMELEN_get(stash) == 4) {
2013 /* Avoid null warning: */
2014 const char * const stashname = HvNAME(stash); assert(stashname);
2015 if (strBEGINs(stashname, "CORE"))
2016 S_maybe_add_coresub(aTHX_ 0, gv, name, len);
2023 /* Nothing else to do.
2024 The compiler will probably turn the switch statement into a
2025 branch table. Make sure we avoid even that small overhead for
2026 the common case of lower case variable names. (On EBCDIC
2027 platforms, we can't just do:
2028 if (NATIVE_TO_ASCII(*name) > NATIVE_TO_ASCII('V') ) {
2029 because cases like '\027' in the switch statement below are
2030 C1 (non-ASCII) controls on those platforms, so the remapping
2031 would make them larger than 'V')
2038 if (memEQs(name, len, "ARGV")) {
2039 IoFLAGS(GvIOn(gv)) |= IOf_ARGV|IOf_START;
2041 else if (memEQs(name, len, "ARGVOUT")) {
2047 len >= 6 && name[1] == 'X' &&
2048 (memEQs(name, len, "EXPORT")
2049 ||memEQs(name, len, "EXPORT_OK")
2050 ||memEQs(name, len, "EXPORT_FAIL")
2051 ||memEQs(name, len, "EXPORT_TAGS"))
2056 if (memEQs(name, len, "ISA")) {
2057 gv_magicalize_isa(gv);
2061 if (memEQs(name, len, "SIG")) {
2064 if (!PL_psig_name) {
2065 Newxz(PL_psig_name, 2 * SIG_SIZE, SV*);
2066 Newxz(PL_psig_pend, SIG_SIZE, int);
2067 PL_psig_ptr = PL_psig_name + SIG_SIZE;
2069 /* I think that the only way to get here is to re-use an
2070 embedded perl interpreter, where the previous
2071 use didn't clean up fully because
2072 PL_perl_destruct_level was 0. I'm not sure that we
2073 "support" that, in that I suspect in that scenario
2074 there are sufficient other garbage values left in the
2075 interpreter structure that something else will crash
2076 before we get here. I suspect that this is one of
2077 those "doctor, it hurts when I do this" bugs. */
2078 Zero(PL_psig_name, 2 * SIG_SIZE, SV*);
2079 Zero(PL_psig_pend, SIG_SIZE, int);
2083 hv_magic(hv, NULL, PERL_MAGIC_sig);
2084 for (i = 1; i < SIG_SIZE; i++) {
2085 SV * const * const init = hv_fetch(hv, PL_sig_name[i], strlen(PL_sig_name[i]), 1);
2087 sv_setsv(*init, &PL_sv_undef);
2092 if (memEQs(name, len, "VERSION"))
2095 case '\003': /* $^CHILD_ERROR_NATIVE */
2096 if (memEQs(name, len, "\003HILD_ERROR_NATIVE"))
2098 /* @{^CAPTURE} %{^CAPTURE} */
2099 if (memEQs(name, len, "\003APTURE")) {
2100 AV* const av = GvAVn(gv);
2101 const Size_t n = *name;
2103 sv_magic(MUTABLE_SV(av), (SV*)n, PERL_MAGIC_regdata, NULL, 0);
2106 require_tie_mod_s(gv, '+', "Tie::Hash::NamedCapture",0);
2108 } else /* %{^CAPTURE_ALL} */
2109 if (memEQs(name, len, "\003APTURE_ALL")) {
2110 require_tie_mod_s(gv, '-', "Tie::Hash::NamedCapture",0);
2113 case '\005': /* $^ENCODING */
2114 if (memEQs(name, len, "\005NCODING"))
2117 case '\007': /* $^GLOBAL_PHASE */
2118 if (memEQs(name, len, "\007LOBAL_PHASE"))
2121 case '\014': /* $^LAST_FH */
2122 if (memEQs(name, len, "\014AST_FH"))
2125 case '\015': /* $^MATCH */
2126 if (memEQs(name, len, "\015ATCH")) {
2127 paren = RX_BUFF_IDX_CARET_FULLMATCH;
2131 case '\017': /* $^OPEN */
2132 if (memEQs(name, len, "\017PEN"))
2135 case '\020': /* $^PREMATCH $^POSTMATCH */
2136 if (memEQs(name, len, "\020REMATCH")) {
2137 paren = RX_BUFF_IDX_CARET_PREMATCH;
2140 if (memEQs(name, len, "\020OSTMATCH")) {
2141 paren = RX_BUFF_IDX_CARET_POSTMATCH;
2146 if (memEQs(name, len, "\023AFE_LOCALES"))
2149 case '\024': /* ${^TAINT} */
2150 if (memEQs(name, len, "\024AINT"))
2153 case '\025': /* ${^UNICODE}, ${^UTF8LOCALE} */
2154 if (memEQs(name, len, "\025NICODE"))
2156 if (memEQs(name, len, "\025TF8LOCALE"))
2158 if (memEQs(name, len, "\025TF8CACHE"))
2161 case '\027': /* $^WARNING_BITS */
2162 if (memEQs(name, len, "\027ARNING_BITS"))
2165 else if (memEQs(name, len, "\027IN32_SLOPPY_STAT"))
2179 /* Ensures that we have an all-digit variable, ${"1foo"} fails
2182 if (!grok_atoUV(name, &uv, NULL) || uv > I32_MAX)
2184 /* XXX why are we using a SSize_t? */
2185 paren = (SSize_t)(I32)uv;
2191 /* Names of length 1. (Or 0. But name is NUL terminated, so that will
2192 be case '\0' in this switch statement (ie a default case) */
2195 paren = RX_BUFF_IDX_FULLMATCH;
2198 paren = RX_BUFF_IDX_PREMATCH;
2201 paren = RX_BUFF_IDX_POSTMATCH;
2203 #ifdef PERL_SAWAMPERSAND
2205 sv_type == SVt_PVAV ||
2206 sv_type == SVt_PVHV ||
2207 sv_type == SVt_PVCV ||
2208 sv_type == SVt_PVFM ||
2210 )) { PL_sawampersand |=
2214 ? SAWAMPERSAND_MIDDLE
2215 : SAWAMPERSAND_RIGHT;
2228 paren = *name - '0';
2231 /* Flag the capture variables with a NULL mg_ptr
2232 Use mg_len for the array index to lookup. */
2233 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, NULL, paren);
2237 sv_setpv(GvSVn(gv),PL_chopset);
2241 #ifdef COMPLEX_STATUS
2242 SvUPGRADE(GvSVn(gv), SVt_PVLV);
2248 /* If %! has been used, automatically load Errno.pm. */
2250 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, name, len);
2252 /* magicalization must be done before require_tie_mod_s is called */
2253 if (sv_type == SVt_PVHV || sv_type == SVt_PVGV)
2254 require_tie_mod_s(gv, '!', "Errno", 1);
2257 case '-': /* $-, %-, @- */
2258 case '+': /* $+, %+, @+ */
2259 GvMULTI_on(gv); /* no used once warnings here */
2261 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, name, len);
2263 SvREADONLY_on(GvSVn(gv));
2266 if (sv_type == SVt_PVHV || sv_type == SVt_PVGV)
2267 require_tie_mod_s(gv, *name, "Tie::Hash::NamedCapture",0);
2270 AV* const av = GvAVn(gv);
2271 const Size_t n = *name;
2273 sv_magic(MUTABLE_SV(av), (SV*)n, PERL_MAGIC_regdata, NULL, 0);
2279 if (sv_type == SVt_PV)
2280 /* diag_listed_as: $* is no longer supported as of Perl 5.30 */
2281 Perl_croak(aTHX_ "$%c is no longer supported as of Perl 5.30", *name);
2283 case '\010': /* $^H */
2285 HV *const hv = GvHVn(gv);
2286 hv_magic(hv, NULL, PERL_MAGIC_hints);
2289 case '\023': /* $^S */
2291 SvREADONLY_on(GvSVn(gv));
2308 case '\001': /* $^A */
2309 case '\003': /* $^C */
2310 case '\004': /* $^D */
2311 case '\005': /* $^E */
2312 case '\006': /* $^F */
2313 case '\011': /* $^I, NOT \t in EBCDIC */
2314 case '\016': /* $^N */
2315 case '\017': /* $^O */
2316 case '\020': /* $^P */
2317 case '\024': /* $^T */
2318 case '\027': /* $^W */
2320 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, name, len);
2323 case '\014': /* $^L */
2324 sv_setpvs(GvSVn(gv),"\f");
2327 sv_setpvs(GvSVn(gv),"\034");
2331 SV * const sv = GvSV(gv);
2332 if (!sv_derived_from(PL_patchlevel, "version"))
2333 upg_version(PL_patchlevel, TRUE);
2334 GvSV(gv) = vnumify(PL_patchlevel);
2335 SvREADONLY_on(GvSV(gv));
2339 case '\026': /* $^V */
2341 SV * const sv = GvSV(gv);
2342 GvSV(gv) = new_version(PL_patchlevel);
2343 SvREADONLY_on(GvSV(gv));
2349 if (sv_type == SVt_PV)
2355 /* Return true if we actually did something. */
2356 return GvAV(gv) || GvHV(gv) || GvIO(gv) || GvCV(gv)
2358 SvOK(GvSV(gv)) || SvMAGICAL(GvSV(gv))
2363 /* If we do ever start using this later on in the file, we need to make
2364 sure we don’t accidentally use the wrong definition. */
2365 #undef SvREADONLY_on
2367 /* This function is called when the stash already holds the GV of the magic
2368 * variable we're looking for, but we need to check that it has the correct
2369 * kind of magic. For example, if someone first uses $! and then %!, the
2370 * latter would end up here, and we add the Errno tie to the HASH slot of
2373 PERL_STATIC_INLINE void
2374 S_maybe_multimagic_gv(pTHX_ GV *gv, const char *name, const svtype sv_type)
2376 PERL_ARGS_ASSERT_MAYBE_MULTIMAGIC_GV;
2378 if (sv_type == SVt_PVHV || sv_type == SVt_PVGV) {
2380 require_tie_mod_s(gv, '!', "Errno", 1);
2381 else if (*name == '-' || *name == '+')
2382 require_tie_mod_s(gv, *name, "Tie::Hash::NamedCapture", 0);
2383 } else if (sv_type == SVt_PV) {
2384 if (*name == '*' || *name == '#') {
2385 /* diag_listed_as: $* is no longer supported as of Perl 5.30 */
2386 Perl_croak(aTHX_ "$%c is no longer supported as of Perl 5.30", *name);
2389 if (sv_type==SVt_PV || sv_type==SVt_PVGV) {
2391 #ifdef PERL_SAWAMPERSAND
2393 PL_sawampersand |= SAWAMPERSAND_LEFT;
2397 PL_sawampersand |= SAWAMPERSAND_MIDDLE;
2401 PL_sawampersand |= SAWAMPERSAND_RIGHT;
2410 =for apidoc gv_fetchpv
2411 =for apidoc_item |GV *|gv_fetchpvn|const char * nambeg|STRLEN full_len|I32 flags|const svtype sv_type
2412 =for apidoc_item ||gv_fetchpvn_flags
2413 =for apidoc_item |GV *|gv_fetchpvs|"name"|I32 flags|const svtype sv_type
2414 =for apidoc_item ||gv_fetchsv
2415 =for apidoc_item |GV *|gv_fetchsv_nomg|SV *name|I32 flags|const svtype sv_type
2417 These all return the GV of type C<sv_type> whose name is given by the inputs,
2418 or NULL if no GV of that name and type could be found. See L<perlguts/Stashes
2421 The only differences are how the input name is specified, and if 'get' magic is
2422 normally used in getting that name.
2424 Don't be fooled by the fact that only one form has C<flags> in its name. They
2425 all have a C<flags> parameter in fact, and all the flag bits have the same
2428 If any of the flags C<GV_ADD>, C<GV_ADDMG>, C<GV_ADDWARN>, C<GV_ADDMULTI>, or
2429 C<GV_NOINIT> is set, a GV is created if none already exists for the input name
2430 and type. However, C<GV_ADDMG> will only do the creation for magical GV's.
2431 For all of these flags except C<GV_NOINIT>, C<L</gv_init_pvn>> is called after
2432 the addition. C<GV_ADDWARN> is used when the caller expects that adding won't
2433 be necessary because the symbol should already exist; but if not, add it
2434 anyway, with a warning that it was unexpectedly absent. The C<GV_ADDMULTI>
2435 flag means to pretend that the GV has been seen before (I<i.e.>, suppress "Used
2438 The flag C<GV_NOADD_NOINIT> causes C<L</gv_init_pvn>> not be to called if the
2439 GV existed but isn't PVGV.
2441 If the C<SVf_UTF8> bit is set, the name is treated as being encoded in UTF-8;
2442 otherwise the name won't be considered to be UTF-8 in the C<pv>-named forms,
2443 and the UTF-8ness of the underlying SVs will be used in the C<sv> forms.
2445 If the flag C<GV_NOTQUAL> is set, the caller warrants that the input name is a
2446 plain symbol name, not qualified with a package, otherwise the name is checked
2447 for being a qualified one.
2449 In C<gv_fetchpv>, C<nambeg> is a C string, NUL-terminated with no intermediate
2452 In C<gv_fetchpvs>, C<name> is a literal C string, hence is enclosed in
2455 C<gv_fetchpvn> and C<gv_fetchpvn_flags> are identical. In these, <nambeg> is
2456 a Perl string whose byte length is given by C<full_len>, and may contain
2459 In C<gv_fetchsv> and C<gv_fetchsv_nomg>, the name is extracted from the PV of
2460 the input C<name> SV. The only difference between these two forms is that
2461 'get' magic is normally done on C<name> in C<gv_fetchsv>, and always skipped
2462 with C<gv_fetchsv_nomg>. Including C<GV_NO_SVGMAGIC> in the C<flags> parameter
2463 to C<gv_fetchsv> makes it behave identically to C<gv_fetchsv_nomg>.
2465 =for apidoc Amnh||GV_ADD
2466 =for apidoc Amnh||GV_ADDMG
2467 =for apidoc Amnh||GV_ADDMULTI
2468 =for apidoc Amnh||GV_ADDWARN
2469 =for apidoc Amnh||GV_NOADD_NOINIT
2470 =for apidoc Amnh||GV_NOINIT
2471 =for apidoc Amnh||GV_NOTQUAL
2472 =for apidoc Amnh||GV_NO_SVGMAGIC
2473 =for apidoc Amnh||SVf_UTF8
2479 Perl_gv_fetchpvn_flags(pTHX_ const char *nambeg, STRLEN full_len, I32 flags,
2480 const svtype sv_type)
2482 const char *name = nambeg;
2487 const I32 no_init = flags & (GV_NOADD_NOINIT | GV_NOINIT);
2488 const I32 no_expand = flags & GV_NOEXPAND;
2489 const I32 add = flags & ~GV_NOADD_MASK;
2490 const U32 is_utf8 = flags & SVf_UTF8;
2491 bool addmg = cBOOL(flags & GV_ADDMG);
2492 const char *const name_end = nambeg + full_len;
2495 PERL_ARGS_ASSERT_GV_FETCHPVN_FLAGS;
2497 /* If we have GV_NOTQUAL, the caller promised that
2498 * there is no stash, so we can skip the check.
2499 * Similarly if full_len is 0, since then we're
2500 * dealing with something like *{""} or ""->foo()
2502 if ((flags & GV_NOTQUAL) || !full_len) {
2505 else if (parse_gv_stash_name(&stash, &gv, &name, &len, nambeg, full_len, is_utf8, add)) {
2506 if (name == name_end) return gv;
2512 if (!stash && !find_default_stash(&stash, name, len, is_utf8, add, sv_type)) {
2516 /* By this point we should have a stash and a name */
2517 gvp = (GV**)hv_fetch(stash,name,is_utf8 ? -(I32)len : (I32)len,add);
2518 if (!gvp || *gvp == (const GV *)&PL_sv_undef) {
2519 if (addmg) gv = (GV *)newSV(0); /* tentatively */
2522 else gv = *gvp, addmg = 0;
2523 /* From this point on, addmg means gv has not been inserted in the
2526 if (SvTYPE(gv) == SVt_PVGV) {
2527 /* The GV already exists, so return it, but check if we need to do
2528 * anything else with it before that.
2531 /* This is the heuristic that handles if a variable triggers the
2532 * 'used only once' warning. If there's already a GV in the stash
2533 * with this name, then we assume that the variable has been used
2534 * before and turn its MULTI flag on.
2535 * It's a heuristic because it can easily be "tricked", like with
2536 * BEGIN { $a = 1; $::{foo} = *a }; () = $foo
2537 * not warning about $main::foo being used just once
2540 gv_init_svtype(gv, sv_type);
2541 /* You reach this path once the typeglob has already been created,
2542 either by the same or a different sigil. If this path didn't
2543 exist, then (say) referencing $! first, and %! second would
2544 mean that %! was not handled correctly. */
2545 if (len == 1 && stash == PL_defstash) {
2546 maybe_multimagic_gv(gv, name, sv_type);
2548 else if (sv_type == SVt_PVAV
2549 && memEQs(name, len, "ISA")
2550 && (!GvAV(gv) || !SvSMAGICAL(GvAV(gv))))
2551 gv_magicalize_isa(gv);
2554 } else if (no_init) {
2558 /* If GV_NOEXPAND is true and what we got off the stash is a ref,
2559 * don't expand it to a glob. This is an optimization so that things
2560 * copying constants over, like Exporter, don't have to be rewritten
2561 * to take into account that you can store more than just globs in
2564 else if (no_expand && SvROK(gv)) {
2569 /* Adding a new symbol.
2570 Unless of course there was already something non-GV here, in which case
2571 we want to behave as if there was always a GV here, containing some sort
2573 Otherwise we run the risk of creating things like GvIO, which can cause
2574 subtle bugs. eg the one that tripped up SQL::Translator */
2576 faking_it = SvOK(gv);
2578 if (add & GV_ADDWARN)
2579 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2580 "Had to create %" UTF8f " unexpectedly",
2581 UTF8fARG(is_utf8, name_end-nambeg, nambeg));
2582 gv_init_pvn(gv, stash, name, len, (add & GV_ADDMULTI)|is_utf8);
2585 && isIDFIRST_lazy_if_safe(name, name + full_len, is_utf8)
2586 && !ckWARN(WARN_ONCE) )
2591 /* set up magic where warranted */
2592 if ( gv_magicalize(gv, stash, name, len, sv_type) ) {
2595 /* gv_magicalize magicalised this gv, so we want it
2596 * stored in the symtab.
2597 * Effectively the caller is asking, ‘Does this gv exist?’
2598 * And we respond, ‘Er, *now* it does!’
2600 (void)hv_store(stash,name,len,(SV *)gv,0);
2604 /* The temporary GV created above */
2605 SvREFCNT_dec_NN(gv);
2609 if (gv) gv_init_svtype(gv, faking_it ? SVt_PVCV : sv_type);
2614 Perl_gv_fullname4(pTHX_ SV *sv, const GV *gv, const char *prefix, bool keepmain)
2617 const HV * const hv = GvSTASH(gv);
2619 PERL_ARGS_ASSERT_GV_FULLNAME4;
2621 sv_setpv(sv, prefix ? prefix : "");
2623 if (hv && (name = HvNAME(hv))) {
2624 const STRLEN len = HvNAMELEN(hv);
2625 if (keepmain || ! memBEGINs(name, len, "main")) {
2626 sv_catpvn_flags(sv,name,len,HvNAMEUTF8(hv)?SV_CATUTF8:SV_CATBYTES);
2630 else sv_catpvs(sv,"__ANON__::");
2631 sv_catsv(sv,sv_2mortal(newSVhek(GvNAME_HEK(gv))));
2635 Perl_gv_efullname4(pTHX_ SV *sv, const GV *gv, const char *prefix, bool keepmain)
2637 const GV * const egv = GvEGVx(gv);
2639 PERL_ARGS_ASSERT_GV_EFULLNAME4;
2641 gv_fullname4(sv, egv ? egv : gv, prefix, keepmain);
2645 /* recursively scan a stash and any nested stashes looking for entries
2646 * that need the "only used once" warning raised
2650 Perl_gv_check(pTHX_ HV *stash)
2654 PERL_ARGS_ASSERT_GV_CHECK;
2659 assert(HvARRAY(stash));
2661 /* mark stash is being scanned, to avoid recursing */
2662 HvAUX(stash)->xhv_aux_flags |= HvAUXf_SCAN_STASH;
2663 for (i = 0; i <= (I32) HvMAX(stash); i++) {
2665 for (entry = HvARRAY(stash)[i]; entry; entry = HeNEXT(entry)) {
2668 STRLEN keylen = HeKLEN(entry);
2669 const char * const key = HeKEY(entry);
2671 if (keylen >= 2 && key[keylen-2] == ':' && key[keylen-1] == ':' &&
2672 (gv = MUTABLE_GV(HeVAL(entry))) && isGV(gv) && (hv = GvHV(gv)))
2674 if (hv != PL_defstash && hv != stash
2676 && (HvAUX(hv)->xhv_aux_flags & HvAUXf_SCAN_STASH))
2678 gv_check(hv); /* nested package */
2680 else if ( HeKLEN(entry) != 0
2681 && *HeKEY(entry) != '_'
2682 && isIDFIRST_lazy_if_safe(HeKEY(entry),
2683 HeKEY(entry) + HeKLEN(entry),
2687 gv = MUTABLE_GV(HeVAL(entry));
2688 if (SvTYPE(gv) != SVt_PVGV || GvMULTI(gv))
2691 CopLINE_set(PL_curcop, GvLINE(gv));
2693 CopFILE(PL_curcop) = (char *)file; /* set for warning */
2695 CopFILEGV(PL_curcop)
2696 = gv_fetchfile_flags(file, HEK_LEN(GvFILE_HEK(gv)), 0);
2698 Perl_warner(aTHX_ packWARN(WARN_ONCE),
2699 "Name \"%" HEKf "::%" HEKf
2700 "\" used only once: possible typo",
2701 HEKfARG(HvNAME_HEK(stash)),
2702 HEKfARG(GvNAME_HEK(gv)));
2706 HvAUX(stash)->xhv_aux_flags &= ~HvAUXf_SCAN_STASH;
2710 Perl_newGVgen_flags(pTHX_ const char *pack, U32 flags)
2712 PERL_ARGS_ASSERT_NEWGVGEN_FLAGS;
2713 assert(!(flags & ~SVf_UTF8));
2715 return gv_fetchpv(Perl_form(aTHX_ "%" UTF8f "::_GEN_%ld",
2716 UTF8fARG(flags, strlen(pack), pack),
2721 /* hopefully this is only called on local symbol table entries */
2724 Perl_gp_ref(pTHX_ GP *gp)
2731 /* If the GP they asked for a reference to contains
2732 a method cache entry, clear it first, so that we
2733 don't infect them with our cached entry */
2734 SvREFCNT_dec_NN(gp->gp_cv);
2743 Perl_gp_free(pTHX_ GV *gv)
2747 bool in_global_destruction = PL_phase == PERL_PHASE_DESTRUCT;
2749 if (!gv || !isGV_with_GP(gv) || !(gp = GvGP(gv)))
2751 if (gp->gp_refcnt == 0) {
2752 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2753 "Attempt to free unreferenced glob pointers"
2754 pTHX__FORMAT pTHX__VALUE);
2757 if (gp->gp_refcnt > 1) {
2759 if (gp->gp_egv == gv)
2767 /* Copy and null out all the glob slots, so destructors do not see
2769 HEK * const file_hek = gp->gp_file_hek;
2770 SV * sv = gp->gp_sv;
2771 AV * av = gp->gp_av;
2772 HV * hv = gp->gp_hv;
2773 IO * io = gp->gp_io;
2774 CV * cv = gp->gp_cv;
2775 CV * form = gp->gp_form;
2779 gp->gp_file_hek = NULL;
2788 unshare_hek(file_hek);
2790 /* Storing the SV on the temps stack (instead of freeing it immediately)
2791 is an admitted bodge that attempt to compensate for the lack of
2792 reference counting on the stack. The motivation is that typeglob syntax
2793 is extremely short hence programs such as '$a += (*a = 2)' are often
2794 found randomly by researchers running fuzzers. Previously these
2795 programs would trigger errors, that the researchers would
2796 (legitimately) report, and then we would spend time figuring out that
2797 the cause was "stack not reference counted" and so not a dangerous
2798 security hole. This consumed a lot of researcher time, our time, and
2799 prevents "interesting" security holes being uncovered.
2801 Typeglob assignment is rarely used in performance critical production
2802 code, so we aren't causing much slowdown by doing extra work here.
2804 In turn, the need to check for SvOBJECT (and references to objects) is
2805 because we have regression tests that rely on timely destruction that
2806 happens *within this while loop* to demonstrate behaviour, and
2807 potentially there is also *working* code in the wild that relies on
2810 And we need to avoid doing this in global destruction else we can end
2811 up with "Attempt to free temp prematurely ... Unbalanced string table
2814 Hence the whole thing is a heuristic intended to mitigate against
2815 simple problems likely found by fuzzers but never written by humans,
2816 whilst leaving working code unchanged. */
2819 if (SvREFCNT(sv) > 1 || SvOBJECT(sv) || UNLIKELY(in_global_destruction)) {
2820 SvREFCNT_dec_NN(sv);
2822 } else if (SvROK(sv) && (referant = SvRV(sv))
2823 && (SvREFCNT(referant) > 1 || SvOBJECT(referant))) {
2824 SvREFCNT_dec_NN(sv);
2831 if (SvREFCNT(av) > 1 || SvOBJECT(av) || UNLIKELY(in_global_destruction)) {
2832 SvREFCNT_dec_NN(av);
2838 /* FIXME - another reference loop GV -> symtab -> GV ?
2839 Somehow gp->gp_hv can end up pointing at freed garbage. */
2840 if (hv && SvTYPE(hv) == SVt_PVHV) {
2841 const HEK *hvname_hek = HvNAME_HEK(hv);
2842 if (PL_stashcache && hvname_hek) {
2843 DEBUG_o(Perl_deb(aTHX_
2844 "gp_free clearing PL_stashcache for '%" HEKf "'\n",
2845 HEKfARG(hvname_hek)));
2846 (void)hv_deletehek(PL_stashcache, hvname_hek, G_DISCARD);
2848 if (SvREFCNT(hv) > 1 || SvOBJECT(hv) || UNLIKELY(in_global_destruction)) {
2849 SvREFCNT_dec_NN(hv);
2855 if (io && SvREFCNT(io) == 1 && IoIFP(io)
2856 && (IoTYPE(io) == IoTYPE_WRONLY ||
2857 IoTYPE(io) == IoTYPE_RDWR ||
2858 IoTYPE(io) == IoTYPE_APPEND)
2859 && ckWARN_d(WARN_IO)
2860 && IoIFP(io) != PerlIO_stdin()
2861 && IoIFP(io) != PerlIO_stdout()
2862 && IoIFP(io) != PerlIO_stderr()
2863 && !(IoFLAGS(io) & IOf_FAKE_DIRP))
2864 io_close(io, gv, FALSE, TRUE);
2866 if (SvREFCNT(io) > 1 || SvOBJECT(io) || UNLIKELY(in_global_destruction)) {
2867 SvREFCNT_dec_NN(io);
2874 if (SvREFCNT(cv) > 1 || SvOBJECT(cv) || UNLIKELY(in_global_destruction)) {
2875 SvREFCNT_dec_NN(cv);
2882 if (SvREFCNT(form) > 1 || SvOBJECT(form) || UNLIKELY(in_global_destruction)) {
2883 SvREFCNT_dec_NN(form);
2891 /* We don't strictly need to defer all this to the end, but it's
2892 easiest to do so. The subtle problems we have are
2893 1) any of the actions triggered by the various SvREFCNT_dec()s in
2894 any of the intermediate blocks can cause more items to be added
2895 to the temps stack. So we can't "cache" its state locally
2896 2) We'd have to re-check the "extend by 1?" for each time.
2897 Whereas if we don't NULL out the values that we want to put onto
2898 the save stack until here, we can do it in one go, with one
2901 SSize_t max_ix = PL_tmps_ix + need;
2903 if (max_ix >= PL_tmps_max) {
2904 tmps_grow_p(max_ix);
2908 PL_tmps_stack[++PL_tmps_ix] = sv;
2911 PL_tmps_stack[++PL_tmps_ix] = (SV *) av;
2914 PL_tmps_stack[++PL_tmps_ix] = (SV *) hv;
2917 PL_tmps_stack[++PL_tmps_ix] = (SV *) io;
2920 PL_tmps_stack[++PL_tmps_ix] = (SV *) cv;
2923 PL_tmps_stack[++PL_tmps_ix] = (SV *) form;
2927 /* Possibly reallocated by a destructor */
2930 if (!gp->gp_file_hek
2936 && !gp->gp_form) break;
2938 if (--attempts == 0) {
2940 "panic: gp_free failed to free glob pointer - "
2941 "something is repeatedly re-creating entries"
2946 /* Possibly incremented by a destructor doing glob assignment */
2947 if (gp->gp_refcnt > 1) goto borrowed;
2953 Perl_magic_freeovrld(pTHX_ SV *sv, MAGIC *mg)
2955 AMT * const amtp = (AMT*)mg->mg_ptr;
2956 PERL_UNUSED_ARG(sv);
2958 PERL_ARGS_ASSERT_MAGIC_FREEOVRLD;
2960 if (amtp && AMT_AMAGIC(amtp)) {
2962 for (i = 1; i < NofAMmeth; i++) {
2963 CV * const cv = amtp->table[i];
2965 SvREFCNT_dec_NN(MUTABLE_SV(cv));
2966 amtp->table[i] = NULL;
2973 /* Updates and caches the CV's */
2975 * 1 on success and there is some overload
2976 * 0 if there is no overload
2977 * -1 if some error occurred and it couldn't croak
2981 Perl_Gv_AMupdate(pTHX_ HV *stash, bool destructing)
2983 MAGIC* const mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
2985 const struct mro_meta* stash_meta = HvMROMETA(stash);
2988 PERL_ARGS_ASSERT_GV_AMUPDATE;
2990 newgen = PL_sub_generation + stash_meta->pkg_gen + stash_meta->cache_gen;
2992 const AMT * const amtp = (AMT*)mg->mg_ptr;
2993 if (amtp->was_ok_sub == newgen) {
2994 return AMT_AMAGIC(amtp) ? 1 : 0;
2996 sv_unmagic(MUTABLE_SV(stash), PERL_MAGIC_overload_table);
2999 DEBUG_o( Perl_deb(aTHX_ "Recalcing overload magic in package %s\n",HvNAME_get(stash)) );
3002 amt.was_ok_sub = newgen;
3003 amt.fallback = AMGfallNO;
3009 bool deref_seen = 0;
3012 /* Work with "fallback" key, which we assume to be first in PL_AMG_names */
3014 /* Try to find via inheritance. */
3015 GV *gv = gv_fetchmeth_pvn(stash, PL_AMG_names[0], 2, -1, 0);
3016 SV * const sv = gv ? GvSV(gv) : NULL;
3021 if (!gv_fetchmeth_pvn(stash, "((", 2, -1, 0))
3024 #ifdef PERL_DONT_CREATE_GVSV
3026 NOOP; /* Equivalent to !SvTRUE and !SvOK */
3029 else if (SvTRUE(sv))
3030 /* don't need to set overloading here because fallback => 1
3031 * is the default setting for classes without overloading */
3032 amt.fallback=AMGfallYES;
3033 else if (SvOK(sv)) {
3034 amt.fallback=AMGfallNEVER;
3041 assert(SvOOK(stash));
3042 /* initially assume the worst */
3043 HvAUX(stash)->xhv_aux_flags &= ~HvAUXf_NO_DEREF;
3045 for (i = 1; i < NofAMmeth; i++) {
3046 const char * const cooky = PL_AMG_names[i];
3047 /* Human-readable form, for debugging: */
3048 const char * const cp = AMG_id2name(i);
3049 const STRLEN l = PL_AMG_namelens[i];
3051 DEBUG_o( Perl_deb(aTHX_ "Checking overloading of \"%s\" in package \"%.256s\"\n",
3052 cp, HvNAME_get(stash)) );
3053 /* don't fill the cache while looking up!
3054 Creation of inheritance stubs in intermediate packages may
3055 conflict with the logic of runtime method substitution.
3056 Indeed, for inheritance A -> B -> C, if C overloads "+0",
3057 then we could have created stubs for "(+0" in A and C too.
3058 But if B overloads "bool", we may want to use it for
3059 numifying instead of C's "+0". */
3060 gv = Perl_gv_fetchmeth_pvn(aTHX_ stash, cooky, l, -1, 0);
3062 if (gv && (cv = GvCV(gv)) && CvHASGV(cv)) {
3063 const HEK * const gvhek = CvGvNAME_HEK(cv);
3064 const HEK * const stashek =
3065 HvNAME_HEK(CvNAMED(cv) ? CvSTASH(cv) : GvSTASH(CvGV(cv)));
3066 if (memEQs(HEK_KEY(gvhek), HEK_LEN(gvhek), "nil")
3068 && memEQs(HEK_KEY(stashek), HEK_LEN(stashek), "overload")) {
3069 /* This is a hack to support autoloading..., while
3070 knowing *which* methods were declared as overloaded. */
3071 /* GvSV contains the name of the method. */
3073 SV *gvsv = GvSV(gv);
3075 DEBUG_o( Perl_deb(aTHX_ "Resolving method \"%" SVf256\
3076 "\" for overloaded \"%s\" in package \"%.256s\"\n",
3077 (void*)GvSV(gv), cp, HvNAME(stash)) );
3078 if (!gvsv || !SvPOK(gvsv)
3079 || !(ngv = gv_fetchmethod_sv_flags(stash, gvsv, 0)))
3081 /* Can be an import stub (created by "can"). */
3086 const SV * const name = (gvsv && SvPOK(gvsv))
3088 : newSVpvs_flags("???", SVs_TEMP);
3089 /* diag_listed_as: Can't resolve method "%s" overloading "%s" in package "%s" */
3090 Perl_croak(aTHX_ "%s method \"%" SVf256
3091 "\" overloading \"%s\" "\
3092 "in package \"%" HEKf256 "\"",
3093 (GvCVGEN(gv) ? "Stub found while resolving"
3101 cv = GvCV(gv = ngv);
3103 DEBUG_o( Perl_deb(aTHX_ "Overloading \"%s\" in package \"%.256s\" via \"%.256s::%.256s\"\n",
3104 cp, HvNAME_get(stash), HvNAME_get(GvSTASH(CvGV(cv))),
3105 GvNAME(CvGV(cv))) );
3107 } else if (gv) { /* Autoloaded... */
3108 cv = MUTABLE_CV(gv);
3111 amt.table[i]=MUTABLE_CV(SvREFCNT_inc_simple(cv));
3127 /* none of @{} etc overloaded; we can do $obj->[N] quicker.
3128 * NB - aux var invalid here, HvARRAY() could have been
3129 * reallocated since it was assigned to */
3130 HvAUX(stash)->xhv_aux_flags |= HvAUXf_NO_DEREF;
3133 AMT_AMAGIC_on(&amt);
3134 sv_magic(MUTABLE_SV(stash), 0, PERL_MAGIC_overload_table,
3135 (char*)&amt, sizeof(AMT));
3139 /* Here we have no table: */
3141 AMT_AMAGIC_off(&amt);
3142 sv_magic(MUTABLE_SV(stash), 0, PERL_MAGIC_overload_table,
3143 (char*)&amt, sizeof(AMTS));
3149 Perl_gv_handler(pTHX_ HV *stash, I32 id)
3154 struct mro_meta* stash_meta;
3156 if (!stash || !HvNAME_get(stash))
3159 stash_meta = HvMROMETA(stash);
3160 newgen = PL_sub_generation + stash_meta->pkg_gen + stash_meta->cache_gen;
3162 mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
3165 if (Gv_AMupdate(stash, 0) == -1)
3167 mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
3170 amtp = (AMT*)mg->mg_ptr;
3171 if ( amtp->was_ok_sub != newgen )
3173 if (AMT_AMAGIC(amtp)) {
3174 CV * const ret = amtp->table[id];
3175 if (ret && isGV(ret)) { /* Autoloading stab */
3176 /* Passing it through may have resulted in a warning
3177 "Inherited AUTOLOAD for a non-method deprecated", since
3178 our caller is going through a function call, not a method call.
3179 So return the CV for AUTOLOAD, setting $AUTOLOAD. */
3180 GV * const gv = gv_fetchmethod(stash, PL_AMG_names[id]);
3192 /* Implement tryAMAGICun_MG macro.
3193 Do get magic, then see if the stack arg is overloaded and if so call it.
3195 AMGf_numeric apply sv_2num to the stack arg.
3199 Perl_try_amagic_un(pTHX_ int method, int flags) {
3202 SV* const arg = TOPs;
3206 if (SvAMAGIC(arg) && (tmpsv = amagic_call(arg, &PL_sv_undef, method,
3207 AMGf_noright | AMGf_unary
3208 | (flags & AMGf_numarg))))
3210 /* where the op is of the form:
3211 * $lex = $x op $y (where the assign is optimised away)
3212 * then assign the returned value to targ and return that;
3213 * otherwise return the value directly
3215 if ( (PL_opargs[PL_op->op_type] & OA_TARGLEX)
3216 && (PL_op->op_private & OPpTARGET_MY))
3219 sv_setsv(TARG, tmpsv);
3229 if ((flags & AMGf_numeric) && SvROK(arg))
3235 /* Implement tryAMAGICbin_MG macro.
3236 Do get magic, then see if the two stack args are overloaded and if so
3239 AMGf_assign op may be called as mutator (eg +=)
3240 AMGf_numeric apply sv_2num to the stack arg.
3244 Perl_try_amagic_bin(pTHX_ int method, int flags) {
3246 SV* const left = TOPm1s;
3247 SV* const right = TOPs;
3253 if (SvAMAGIC(left) || SvAMAGIC(right)) {
3255 /* STACKED implies mutator variant, e.g. $x += 1 */
3256 bool mutator = (flags & AMGf_assign) && (PL_op->op_flags & OPf_STACKED);
3258 tmpsv = amagic_call(left, right, method,
3259 (mutator ? AMGf_assign: 0)
3260 | (flags & AMGf_numarg));
3263 /* where the op is one of the two forms:
3265 * $lex = $x op $y (where the assign is optimised away)
3266 * then assign the returned value to targ and return that;
3267 * otherwise return the value directly
3270 || ( (PL_opargs[PL_op->op_type] & OA_TARGLEX)
3271 && (PL_op->op_private & OPpTARGET_MY)))
3274 TARG = mutator ? *SP : PAD_SV(PL_op->op_targ);
3275 sv_setsv(TARG, tmpsv);
3286 if(left==right && SvGMAGICAL(left)) {
3287 SV * const left = sv_newmortal();
3289 /* Print the uninitialized warning now, so it includes the vari-
3292 if (ckWARN(WARN_UNINITIALIZED)) report_uninit(right);
3293 sv_setbool(left, FALSE);
3295 else sv_setsv_flags(left, right, 0);
3298 if (flags & AMGf_numeric) {
3300 *(sp-1) = sv_2num(TOPm1s);
3302 *sp = sv_2num(right);
3308 Perl_amagic_deref_call(pTHX_ SV *ref, int method) {
3312 PERL_ARGS_ASSERT_AMAGIC_DEREF_CALL;
3316 /* return quickly if none of the deref ops are overloaded */
3317 stash = SvSTASH(SvRV(ref));
3318 assert(SvOOK(stash));
3319 if (HvAUX(stash)->xhv_aux_flags & HvAUXf_NO_DEREF)
3322 while ((tmpsv = amagic_call(ref, &PL_sv_undef, method,
3323 AMGf_noright | AMGf_unary))) {
3325 Perl_croak(aTHX_ "Overloaded dereference did not return a reference");
3326 if (tmpsv == ref || SvRV(tmpsv) == SvRV(ref)) {
3327 /* Bail out if it returns us the same reference. */
3334 return tmpsv ? tmpsv : ref;
3338 Perl_amagic_is_enabled(pTHX_ int method)
3340 SV *lex_mask = cop_hints_fetch_pvs(PL_curcop, "overloading", 0);
3342 assert(PL_curcop->cop_hints & HINT_NO_AMAGIC);
3344 if ( !lex_mask || !SvOK(lex_mask) )
3345 /* overloading lexically disabled */
3347 else if ( lex_mask && SvPOK(lex_mask) ) {
3348 /* we have an entry in the hints hash, check if method has been
3349 * masked by overloading.pm */
3351 const int offset = method / 8;
3352 const int bit = method % 8;
3353 char *pv = SvPV(lex_mask, len);
3355 /* Bit set, so this overloading operator is disabled */
3356 if ( (STRLEN)offset < len && pv[offset] & ( 1 << bit ) )
3363 Perl_amagic_call(pTHX_ SV *left, SV *right, int method, int flags)
3367 CV **cvp=NULL, **ocvp=NULL;
3368 AMT *amtp=NULL, *oamtp=NULL;
3369 int off = 0, off1, lr = 0, notfound = 0;
3370 int postpr = 0, force_cpy = 0;
3371 int assign = AMGf_assign & flags;
3372 const int assignshift = assign ? 1 : 0;
3373 int use_default_op = 0;
3374 int force_scalar = 0;
3380 PERL_ARGS_ASSERT_AMAGIC_CALL;
3382 if ( PL_curcop->cop_hints & HINT_NO_AMAGIC ) {
3383 if (!amagic_is_enabled(method)) return NULL;
3386 if (!(AMGf_noleft & flags) && SvAMAGIC(left)
3387 && (stash = SvSTASH(SvRV(left))) && Gv_AMG(stash)
3388 && (mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table))
3389 && (ocvp = cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
3390 ? (oamtp = amtp = (AMT*)mg->mg_ptr)->table
3392 && ((cv = cvp[off=method+assignshift])
3393 || (assign && amtp->fallback > AMGfallNEVER && /* fallback to
3399 cv = cvp[off=method])))) {
3400 lr = -1; /* Call method for left argument */
3402 if (cvp && amtp->fallback > AMGfallNEVER && flags & AMGf_unary) {
3405 /* look for substituted methods */
3406 /* In all the covered cases we should be called with assign==0. */
3410 if ((cv = cvp[off=add_ass_amg])
3411 || ((cv = cvp[off = add_amg])
3412 && (force_cpy = 0, (postpr = 1)))) {
3413 right = &PL_sv_yes; lr = -1; assign = 1;
3418 if ((cv = cvp[off = subtr_ass_amg])
3419 || ((cv = cvp[off = subtr_amg])
3420 && (force_cpy = 0, (postpr=1)))) {
3421 right = &PL_sv_yes; lr = -1; assign = 1;
3425 (void)((cv = cvp[off=numer_amg]) || (cv = cvp[off=string_amg]));
3428 (void)((cv = cvp[off=string_amg]) || (cv = cvp[off=bool__amg]));
3431 (void)((cv = cvp[off=numer_amg]) || (cv = cvp[off=bool__amg]));
3434 (void)((cv = cvp[off=bool__amg])
3435 || (cv = cvp[off=numer_amg])
3436 || (cv = cvp[off=string_amg]));
3443 * SV* ref causes confusion with the interpreter variable of
3446 SV* const tmpRef=SvRV(left);
3447 if (!SvROK(tmpRef) && SvTYPE(tmpRef) <= SVt_PVMG) {
3449 * Just to be extra cautious. Maybe in some
3450 * additional cases sv_setsv is safe, too.
3452 SV* const newref = newSVsv(tmpRef);
3453 SvOBJECT_on(newref);
3454 /* No need to do SvAMAGIC_on here, as SvAMAGIC macros
3455 delegate to the stash. */
3456 SvSTASH_set(newref, MUTABLE_HV(SvREFCNT_inc(SvSTASH(tmpRef))));
3462 if ((cvp[off1=lt_amg] || cvp[off1=ncmp_amg])
3463 && ((cv = cvp[off=neg_amg]) || (cv = cvp[off=subtr_amg]))) {
3464 SV* const nullsv=&PL_sv_zero;
3466 SV* const lessp = amagic_call(left,nullsv,
3467 lt_amg,AMGf_noright);
3468 logic = SvTRUE_NN(lessp);
3470 SV* const lessp = amagic_call(left,nullsv,
3471 ncmp_amg,AMGf_noright);
3472 logic = (SvNV(lessp) < 0);
3475 if (off==subtr_amg) {
3486 if ((cv = cvp[off=subtr_amg])) {
3493 case iter_amg: /* XXXX Eventually should do to_gv. */
3494 case ftest_amg: /* XXXX Eventually should do to_gv. */
3497 return NULL; /* Delegate operation to standard mechanisms. */
3505 return left; /* Delegate operation to standard mechanisms. */
3510 if (!cv) goto not_found;
3511 } else if (!(AMGf_noright & flags) && SvAMAGIC(right)
3512 && (stash = SvSTASH(SvRV(right))) && Gv_AMG(stash)
3513 && (mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table))
3514 && (cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
3515 ? (amtp = (AMT*)mg->mg_ptr)->table
3517 && (cv = cvp[off=method])) { /* Method for right
3520 } else if (((cvp && amtp->fallback > AMGfallNEVER)
3521 || (ocvp && oamtp->fallback > AMGfallNEVER))
3522 && !(flags & AMGf_unary)) {
3523 /* We look for substitution for
3524 * comparison operations and
3526 if (method==concat_amg || method==concat_ass_amg
3527 || method==repeat_amg || method==repeat_ass_amg) {
3528 return NULL; /* Delegate operation to string conversion */
3550 if (ocvp && (oamtp->fallback > AMGfallNEVER)) {
3554 if (!cv && (cvp && amtp->fallback > AMGfallNEVER)) {
3564 not_found: /* No method found, either report or croak */
3572 return left; /* Delegate operation to standard mechanisms. */
3574 if (ocvp && (cv=ocvp[nomethod_amg])) { /* Call report method */
3575 notfound = 1; lr = -1;
3576 } else if (cvp && (cv=cvp[nomethod_amg])) {
3577 notfound = 1; lr = 1;
3578 } else if ((use_default_op =
3579 (!ocvp || oamtp->fallback >= AMGfallYES)
3580 && (!cvp || amtp->fallback >= AMGfallYES))
3582 /* Skip generating the "no method found" message. */
3586 if (off==-1) off=method;
3587 msg = sv_2mortal(Perl_newSVpvf(aTHX_
3588 "Operation \"%s\": no method found,%sargument %s%" SVf "%s%" SVf,
3589 AMG_id2name(method + assignshift),
3590 (flags & AMGf_unary ? " " : "\n\tleft "),
3592 "in overloaded package ":
3593 "has no overloaded magic",
3595 SVfARG(sv_2mortal(newSVhek(HvNAME_HEK(SvSTASH(SvRV(left)))))):
3598 ",\n\tright argument in overloaded package ":
3601 : ",\n\tright argument has no overloaded magic"),
3603 SVfARG(sv_2mortal(newSVhek(HvNAME_HEK(SvSTASH(SvRV(right)))))):
3604 SVfARG(&PL_sv_no)));
3605 if (use_default_op) {
3606 DEBUG_o( Perl_deb(aTHX_ "%" SVf, SVfARG(msg)) );
3608 Perl_croak(aTHX_ "%" SVf, SVfARG(msg));
3612 force_cpy = force_cpy || assign;
3617 /* in these cases, we're calling '+' or '-' as a fallback for a ++ or --
3618 * operation. we need this to return a value, so that it can be assigned
3619 * later on, in the postpr block (case inc_amg/dec_amg), even if the
3620 * increment or decrement was itself called in void context */
3626 if (off == subtr_amg)
3629 /* in these cases, we're calling an assignment variant of an operator
3630 * (+= rather than +, for instance). regardless of whether it's a
3631 * fallback or not, it always has to return a value, which will be
3632 * assigned to the proper variable later */
3652 /* the copy constructor always needs to return a value */
3656 /* because of the way these are implemented (they don't perform the
3657 * dereferencing themselves, they return a reference that perl then
3658 * dereferences later), they always have to be in scalar context */
3666 /* these don't have an op of their own; they're triggered by their parent
3667 * op, so the context there isn't meaningful ('$a and foo()' in void
3668 * context still needs to pass scalar context on to $a's bool overload) */
3678 DEBUG_o(Perl_deb(aTHX_
3679 "Overloaded operator \"%s\"%s%s%s:\n\tmethod%s found%s in package %" SVf "%s\n",
3681 method+assignshift==off? "" :
3683 method+assignshift==off? "" :
3684 AMG_id2name(method+assignshift),
3685 method+assignshift==off? "" : "\")",
3686 flags & AMGf_unary? "" :
3687 lr==1 ? " for right argument": " for left argument",
3688 flags & AMGf_unary? " for argument" : "",
3689 stash ? SVfARG(sv_2mortal(newSVhek(HvNAME_HEK(stash)))) : SVfARG(newSVpvs_flags("null", SVs_TEMP)),
3690 fl? ",\n\tassignment variant used": "") );
3693 /* Since we use shallow copy during assignment, we need
3694 * to dublicate the contents, probably calling user-supplied
3695 * version of copy operator
3697 /* We need to copy in following cases:
3698 * a) Assignment form was called.
3699 * assignshift==1, assign==T, method + 1 == off
3700 * b) Increment or decrement, called directly.
3701 * assignshift==0, assign==0, method + 0 == off
3702 * c) Increment or decrement, translated to assignment add/subtr.
3703 * assignshift==0, assign==T,
3705 * d) Increment or decrement, translated to nomethod.
3706 * assignshift==0, assign==0,
3708 * e) Assignment form translated to nomethod.
3709 * assignshift==1, assign==T, method + 1 != off
3712 /* off is method, method+assignshift, or a result of opcode substitution.
3713 * In the latter case assignshift==0, so only notfound case is important.
3715 if ( (lr == -1) && ( ( (method + assignshift == off)
3716 && (assign || (method == inc_amg) || (method == dec_amg)))
3719 /* newSVsv does not behave as advertised, so we copy missing
3720 * information by hand */
3721 SV *tmpRef = SvRV(left);
3723 if (SvREFCNT(tmpRef) > 1 && (rv_copy = AMG_CALLunary(left,copy_amg))) {
3724 SvRV_set(left, rv_copy);
3726 SvREFCNT_dec_NN(tmpRef);
3734 const bool oldcatch = CATCH_GET;
3736 /* for multiconcat, we may call overload several times,
3737 * with the context of individual concats being scalar,
3738 * regardless of the overall context of the multiconcat op
3740 U8 gimme = (force_scalar || PL_op->op_type == OP_MULTICONCAT)
3741 ? G_SCALAR : GIMME_V;
3744 Zero(&myop, 1, BINOP);
3745 myop.op_last = (OP *) &myop;
3746 myop.op_next = NULL;
3747 myop.op_flags = OPf_STACKED;
3751 myop.op_flags |= OPf_WANT_VOID;
3754 if (flags & AMGf_want_list) {
3755 myop.op_flags |= OPf_WANT_LIST;
3760 myop.op_flags |= OPf_WANT_SCALAR;
3764 PUSHSTACKi(PERLSI_OVERLOAD);
3767 PL_op = (OP *) &myop;
3768 if (PERLDB_SUB && PL_curstash != PL_debstash)
3769 PL_op->op_private |= OPpENTERSUB_DB;
3770 Perl_pp_pushmark(aTHX);
3772 EXTEND(SP, notfound + 5);
3773 PUSHs(lr>0? right: left);
3774 PUSHs(lr>0? left: right);
3775 PUSHs( lr > 0 ? &PL_sv_yes : ( assign ? &PL_sv_undef : &PL_sv_no ));
3777 PUSHs(newSVpvn_flags(AMG_id2name(method + assignshift),
3778 AMG_id2namelen(method + assignshift), SVs_TEMP));
3780 else if (flags & AMGf_numarg)
3781 PUSHs(&PL_sv_undef);
3782 if (flags & AMGf_numarg)
3784 PUSHs(MUTABLE_SV(cv));
3788 if ((PL_op = PL_ppaddr[OP_ENTERSUB](aTHX)))
3792 nret = SP - (PL_stack_base + oldmark);
3796 /* returning NULL has another meaning, and we check the context
3797 * at the call site too, so this can be differentiated from the
3800 SP = PL_stack_base + oldmark;
3803 if (flags & AMGf_want_list) {
3804 res = sv_2mortal((SV *)newAV());
3805 av_extend((AV *)res, nret);
3807 av_store((AV *)res, nret, POPs);
3818 CATCH_SET(oldcatch);
3825 ans=SvIV(res)<=0; break;
3828 ans=SvIV(res)<0; break;
3831 ans=SvIV(res)>=0; break;
3834 ans=SvIV(res)>0; break;
3837 ans=SvIV(res)==0; break;
3840 ans=SvIV(res)!=0; break;
3843 SvSetSV(left,res); return left;
3845 ans=!SvTRUE_NN(res); break;
3850 } else if (method==copy_amg) {
3852 Perl_croak(aTHX_ "Copy method did not return a reference");
3854 return SvREFCNT_inc(SvRV(res));
3862 Perl_gv_name_set(pTHX_ GV *gv, const char *name, U32 len, U32 flags)
3866 PERL_ARGS_ASSERT_GV_NAME_SET;
3869 Perl_croak(aTHX_ "panic: gv name too long (%" UVuf ")", (UV) len);
3871 if (!(flags & GV_ADD) && GvNAME_HEK(gv)) {
3872 unshare_hek(GvNAME_HEK(gv));
3875 PERL_HASH(hash, name, len);
3876 GvNAME_HEK(gv) = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
3880 =for apidoc gv_try_downgrade
3882 If the typeglob C<gv> can be expressed more succinctly, by having
3883 something other than a real GV in its place in the stash, replace it
3884 with the optimised form. Basic requirements for this are that C<gv>
3885 is a real typeglob, is sufficiently ordinary, and is only referenced
3886 from its package. This function is meant to be used when a GV has been
3887 looked up in part to see what was there, causing upgrading, but based
3888 on what was found it turns out that the real GV isn't required after all.
3890 If C<gv> is a completely empty typeglob, it is deleted from the stash.
3892 If C<gv> is a typeglob containing only a sufficiently-ordinary constant
3893 sub, the typeglob is replaced with a scalar-reference placeholder that
3894 more compactly represents the same thing.
3900 Perl_gv_try_downgrade(pTHX_ GV *gv)
3906 PERL_ARGS_ASSERT_GV_TRY_DOWNGRADE;
3908 /* XXX Why and where does this leave dangling pointers during global
3910 if (PL_phase == PERL_PHASE_DESTRUCT) return;
3912 if (!(SvREFCNT(gv) == 1 && SvTYPE(gv) == SVt_PVGV && !SvFAKE(gv) &&
3913 !SvOBJECT(gv) && !SvREADONLY(gv) &&
3914 isGV_with_GP(gv) && GvGP(gv) &&
3915 !GvINTRO(gv) && GvREFCNT(gv) == 1 &&
3916 !GvSV(gv) && !GvAV(gv) && !GvHV(gv) && !GvIOp(gv) && !GvFORM(gv) &&
3917 GvEGVx(gv) == gv && (stash = GvSTASH(gv))))
3919 if (gv == PL_statgv || gv == PL_last_in_gv || gv == PL_stderrgv)
3921 if (SvMAGICAL(gv)) {
3923 /* only backref magic is allowed */
3924 if (SvGMAGICAL(gv) || SvSMAGICAL(gv))
3926 for (mg = SvMAGIC(gv); mg; mg = mg->mg_moremagic) {
3927 if (mg->mg_type != PERL_MAGIC_backref)
3933 HEK *gvnhek = GvNAME_HEK(gv);
3934 (void)hv_deletehek(stash, gvnhek, G_DISCARD);
3935 } else if (GvMULTI(gv) && cv && SvREFCNT(cv) == 1 &&
3936 !SvOBJECT(cv) && !SvMAGICAL(cv) && !SvREADONLY(cv) &&
3937 CvSTASH(cv) == stash && !CvNAMED(cv) && CvGV(cv) == gv &&
3938 CvCONST(cv) && !CvMETHOD(cv) && !CvLVALUE(cv) && !CvUNIQUE(cv) &&
3939 !CvNODEBUG(cv) && !CvCLONE(cv) && !CvCLONED(cv) && !CvANON(cv) &&
3940 (namehek = GvNAME_HEK(gv)) &&
3941 (gvp = hv_fetchhek(stash, namehek, 0)) &&
3943 SV *value = SvREFCNT_inc(CvXSUBANY(cv).any_ptr);
3944 const bool imported = !!GvIMPORTED_CV(gv);
3948 SvFLAGS(gv) = SVt_IV|SVf_ROK|SVprv_PCS_IMPORTED * imported;
3950 /* See also: 'SET_SVANY_FOR_BODYLESS_IV' in sv.c */
3951 SvANY(gv) = (XPVGV*)((char*)&(gv->sv_u.svu_iv) -
3952 STRUCT_OFFSET(XPVIV, xiv_iv));
3953 SvRV_set(gv, value);
3958 Perl_gv_override(pTHX_ const char * const name, const STRLEN len)
3960 GV *gv = gv_fetchpvn(name, len, GV_NOTQUAL, SVt_PVCV);
3962 PERL_ARGS_ASSERT_GV_OVERRIDE;
3963 if (gv && GvCVu(gv) && GvIMPORTED_CV(gv)) return gv;
3964 gvp = (GV**)hv_fetch(PL_globalstash, name, len, FALSE);
3965 gv = gvp ? *gvp : NULL;
3966 if (gv && !isGV(gv)) {
3967 if (!SvPCS_IMPORTED(gv)) return NULL;
3968 gv_init(gv, PL_globalstash, name, len, 0);
3971 return gv && GvCVu(gv) && GvIMPORTED_CV(gv) ? gv : NULL;
3977 core_xsub(pTHX_ CV* cv)
3980 "&CORE::%s cannot be called directly", GvNAME(CvGV(cv))
3985 * ex: set ts=8 sts=4 sw=4 et: