3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4 * 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * 'Mercy!' cried Gandalf. 'If the giving of information is to be the cure
13 * of your inquisitiveness, I shall spend all the rest of my days in answering
14 * you. What more do you want to know?'
15 * 'The names of all the stars, and of all living things, and the whole
16 * history of Middle-earth and Over-heaven and of the Sundering Seas,'
19 * [p.599 of _The Lord of the Rings_, III/xi: "The PalantÃr"]
23 =head1 GV Handling and Stashes
24 A GV is a structure which corresponds to a Perl typeglob, ie *foo.
25 It is a structure that holds a pointer to a scalar, an array, a hash etc,
26 corresponding to $foo, @foo, %foo.
28 GVs are usually found as values in stashes (symbol table hashes) where
29 Perl stores its global variables.
31 A B<stash> is a hash that contains all variables that are defined
32 within a package. See L<perlguts/Stashes and Globs>
42 #include "overload.inc"
46 static const char S_autoload[] = "AUTOLOAD";
47 #define S_autolen (sizeof("AUTOLOAD")-1)
50 =for apidoc gv_add_by_type
52 Make sure there is a slot of type C<type> in the GV C<gv>.
58 Perl_gv_add_by_type(pTHX_ GV *gv, svtype type)
65 SvTYPE((const SV *)gv) != SVt_PVGV
66 && SvTYPE((const SV *)gv) != SVt_PVLV
70 if (type == SVt_PVIO) {
72 * if it walks like a dirhandle, then let's assume that
73 * this is a dirhandle.
75 what = OP_IS_DIRHOP(PL_op->op_type) ?
76 "dirhandle" : "filehandle";
77 } else if (type == SVt_PVHV) {
80 what = type == SVt_PVAV ? "array" : "scalar";
82 Perl_croak(aTHX_ "Bad symbol for %s", what);
85 if (type == SVt_PVHV) {
86 where = (SV **)&GvHV(gv);
87 } else if (type == SVt_PVAV) {
88 where = (SV **)&GvAV(gv);
89 } else if (type == SVt_PVIO) {
90 where = (SV **)&GvIOp(gv);
97 *where = newSV_type(type);
99 && memEQs(GvNAME(gv), GvNAMELEN(gv), "ISA"))
101 sv_magic(*where, (SV *)gv, PERL_MAGIC_isa, NULL, 0);
108 =for apidoc gv_fetchfile
109 =for apidoc_item gv_fetchfile_flags
111 These return the debugger glob for the file (compiled by Perl) whose name is
112 given by the C<name> parameter.
114 There are currently exactly two differences between these functions.
116 The C<name> parameter to C<gv_fetchfile> is a C string, meaning it is
117 C<NUL>-terminated; whereas the C<name> parameter to C<gv_fetchfile_flags> is a
118 Perl string, whose length (in bytes) is passed in via the C<namelen> parameter
119 This means the name may contain embedded C<NUL> characters.
120 C<namelen> doesn't exist in plain C<gv_fetchfile>).
122 The other difference is that C<gv_fetchfile_flags> has an extra C<flags>
123 parameter, which is currently completely ignored, but allows for possible
129 Perl_gv_fetchfile(pTHX_ const char *name)
131 PERL_ARGS_ASSERT_GV_FETCHFILE;
132 return gv_fetchfile_flags(name, strlen(name), 0);
136 Perl_gv_fetchfile_flags(pTHX_ const char *const name, const STRLEN namelen,
141 const STRLEN tmplen = namelen + 2;
144 PERL_ARGS_ASSERT_GV_FETCHFILE_FLAGS;
145 PERL_UNUSED_ARG(flags);
150 if (tmplen <= sizeof smallbuf)
153 Newx(tmpbuf, tmplen, char);
154 /* This is where the debugger's %{"::_<$filename"} hash is created */
157 memcpy(tmpbuf + 2, name, namelen);
158 GV **gvp = (GV**)hv_fetch(PL_defstash, tmpbuf, tmplen, (flags & GVF_NOADD) ? FALSE : TRUE);
162 gv_init(gv, PL_defstash, tmpbuf, tmplen, FALSE);
163 #ifdef PERL_DONT_CREATE_GVSV
164 GvSV(gv) = newSVpvn(name, namelen);
166 sv_setpvn(GvSV(gv), name, namelen);
169 if (PERLDB_LINE_OR_SAVESRC && !GvAV(gv))
170 hv_magic(GvHVn(gv), GvAVn(gv), PERL_MAGIC_dbfile);
175 if (tmpbuf != smallbuf)
181 =for apidoc gv_const_sv
183 If C<gv> is a typeglob whose subroutine entry is a constant sub eligible for
184 inlining, or C<gv> is a placeholder reference that would be promoted to such
185 a typeglob, then returns the value returned by the sub. Otherwise, returns
192 Perl_gv_const_sv(pTHX_ GV *gv)
194 PERL_ARGS_ASSERT_GV_CONST_SV;
197 if (SvTYPE(gv) == SVt_PVGV)
198 return cv_const_sv(GvCVu(gv));
199 return SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVAV && SvTYPE(SvRV(gv)) != SVt_PVCV ? SvRV(gv) : NULL;
203 Perl_newGP(pTHX_ GV *const gv)
210 PERL_ARGS_ASSERT_NEWGP;
212 gp->gp_egv = gv; /* allow compiler to reuse gv after this */
213 #ifndef PERL_DONT_CREATE_GVSV
214 gp->gp_sv = newSV_type(SVt_NULL);
217 /* PL_curcop may be null here. E.g.,
218 INIT { bless {} and exit }
219 frees INIT before looking up DESTROY (and creating *DESTROY)
222 char *tmp= CopFILE(PL_curcop);
223 gp->gp_line = CopLINE(PL_curcop); /* 0 otherwise Newxz */
227 len = CopFILE_LEN(PL_curcop);
237 PERL_HASH(hash, file, len);
238 gp->gp_file_hek = share_hek(file, len, hash);
244 /* Assign CvGV(cv) = gv, handling weak references.
245 * See also S_anonymise_cv_maybe */
248 Perl_cvgv_set(pTHX_ CV* cv, GV* gv)
250 GV * const oldgv = CvNAMED(cv) ? NULL : SvANY(cv)->xcv_gv_u.xcv_gv;
252 PERL_ARGS_ASSERT_CVGV_SET;
259 SvREFCNT_dec_NN(oldgv);
263 sv_del_backref(MUTABLE_SV(oldgv), MUTABLE_SV(cv));
266 else if ((hek = CvNAME_HEK(cv))) {
272 SvANY(cv)->xcv_gv_u.xcv_gv = gv;
273 assert(!CvCVGV_RC(cv));
278 if (isGV_with_GP(gv) && GvGP(gv) && (GvCV(gv) == cv || GvFORM(gv) == cv))
279 Perl_sv_add_backref(aTHX_ MUTABLE_SV(gv), MUTABLE_SV(cv));
282 SvREFCNT_inc_simple_void_NN(gv);
286 /* Convert CvSTASH + CvNAME_HEK into a GV. Conceptually, all subs have a
287 GV, but for efficiency that GV may not in fact exist. This function,
288 called by CvGV, reifies it. */
291 Perl_cvgv_from_hek(pTHX_ CV *cv)
295 PERL_ARGS_ASSERT_CVGV_FROM_HEK;
296 assert(SvTYPE(cv) == SVt_PVCV);
297 if (!CvSTASH(cv)) return NULL;
298 ASSUME(CvNAME_HEK(cv));
299 svp = hv_fetchhek(CvSTASH(cv), CvNAME_HEK(cv), 0);
300 gv = MUTABLE_GV(svp && *svp ? *svp : newSV_type(SVt_NULL));
302 gv_init_pvn(gv, CvSTASH(cv), HEK_KEY(CvNAME_HEK(cv)),
303 HEK_LEN(CvNAME_HEK(cv)),
304 SVf_UTF8 * cBOOL(HEK_UTF8(CvNAME_HEK(cv))));
305 if (!CvNAMED(cv)) { /* gv_init took care of it */
306 assert (SvANY(cv)->xcv_gv_u.xcv_gv == gv);
309 unshare_hek(CvNAME_HEK(cv));
311 SvANY(cv)->xcv_gv_u.xcv_gv = gv;
312 if (svp && *svp) SvREFCNT_inc_simple_void_NN(gv);
317 /* Assign CvSTASH(cv) = st, handling weak references. */
320 Perl_cvstash_set(pTHX_ CV *cv, HV *st)
322 HV *oldst = CvSTASH(cv);
323 PERL_ARGS_ASSERT_CVSTASH_SET;
327 sv_del_backref(MUTABLE_SV(oldst), MUTABLE_SV(cv));
328 SvANY(cv)->xcv_stash = st;
330 Perl_sv_add_backref(aTHX_ MUTABLE_SV(st), MUTABLE_SV(cv));
334 =for apidoc gv_init_pvn
336 Converts a scalar into a typeglob. This is an incoercible typeglob;
337 assigning a reference to it will assign to one of its slots, instead of
338 overwriting it as happens with typeglobs created by C<SvSetSV>. Converting
339 any scalar that is C<SvOK()> may produce unpredictable results and is reserved
340 for perl's internal use.
342 C<gv> is the scalar to be converted.
344 C<stash> is the parent stash/package, if any.
346 C<name> and C<len> give the name. The name must be unqualified;
347 that is, it must not include the package name. If C<gv> is a
348 stash element, it is the caller's responsibility to ensure that the name
349 passed to this function matches the name of the element. If it does not
350 match, perl's internal bookkeeping will get out of sync.
352 C<flags> can be set to C<SVf_UTF8> if C<name> is a UTF-8 string, or
353 the return value of SvUTF8(sv). It can also take the
354 C<GV_ADDMULTI> flag, which means to pretend that the GV has been
355 seen before (i.e., suppress "Used once" warnings).
357 =for apidoc Amnh||GV_ADDMULTI
361 The old form of C<gv_init_pvn()>. It does not work with UTF-8 strings, as it
362 has no flags parameter. If the C<multi> parameter is set, the
363 C<GV_ADDMULTI> flag will be passed to C<gv_init_pvn()>.
365 =for apidoc gv_init_pv
367 Same as C<gv_init_pvn()>, but takes a nul-terminated string for the name
368 instead of separate char * and length parameters.
370 =for apidoc gv_init_sv
372 Same as C<gv_init_pvn()>, but takes an SV * for the name instead of separate
373 char * and length parameters. C<flags> is currently unused.
379 Perl_gv_init_sv(pTHX_ GV *gv, HV *stash, SV* namesv, U32 flags)
383 PERL_ARGS_ASSERT_GV_INIT_SV;
384 namepv = SvPV(namesv, namelen);
387 gv_init_pvn(gv, stash, namepv, namelen, flags);
391 Perl_gv_init_pv(pTHX_ GV *gv, HV *stash, const char *name, U32 flags)
393 PERL_ARGS_ASSERT_GV_INIT_PV;
394 gv_init_pvn(gv, stash, name, strlen(name), flags);
397 /* Packages in the symbol table are "stashes" - hashes where the keys are symbol
398 names and the values are typeglobs. The value $foo::bar is actually found
399 by looking up the typeglob *foo::{bar} and then reading its SCALAR slot.
401 At least, that's what you see in Perl space if you use typeglob syntax.
402 Usually it's also what's actually stored in the stash, but for some cases
403 different values are stored (as a space optimisation) and converted to full
404 typeglobs "on demand" - if a typeglob syntax is used to read a value. It's
405 the job of this function, Perl_gv_init_pvn(), to undo any trickery and
406 replace the SV stored in the stash with the regular PVGV structure that it is
407 a shorthand for. This has to be done "in-place" by upgrading the actual SV
408 that is already stored in the stash to a PVGV.
410 As the public documentation above says:
411 Converting any scalar that is C<SvOK()> may produce unpredictable
412 results and is reserved for perl's internal use.
414 Values that can be stored:
416 * plain scalar - a subroutine declaration
417 The scalar's string value is the subroutine prototype; the integer -1 is
418 "no prototype". ie shorthand for sub foo ($$); or sub bar;
419 * reference to a scalar - a constant. ie shorthand for sub PI() { 4; }
420 * reference to a sub - a subroutine (avoids allocating a PVGV)
422 The earliest optimisation was subroutine declarations, implemented in 1998
423 by commit 8472ac73d6d80294:
424 "Sub declaration cost reduced from ~500 to ~100 bytes"
426 This space optimisation needs to be invisible to regular Perl code. For this
432 When the first line is compiled, the optimisation is used, and $::{foo} is
433 assigned the scalar '$$'. No PVGV or PVCV is created.
435 When the second line encountered, the typeglob lookup on foo needs to
436 "upgrade" the symbol table entry to a PVGV, and then create a PVCV in the
437 {CODE} slot with the prototype $$ and no body. The typeglob is then available
438 so that [] can be assigned to the {ARRAY} slot. For the code above the
439 upgrade happens at compile time, the assignment at runtime.
441 Analogous code unwinds the other optimisations.
444 Perl_gv_init_pvn(pTHX_ GV *gv, HV *stash, const char *name, STRLEN len, U32 flags)
446 const U32 old_type = SvTYPE(gv);
447 const bool doproto = old_type > SVt_NULL;
448 char * const proto = (doproto && SvPOK(gv))
449 ? ((void)(SvIsCOW(gv) && (sv_force_normal((SV *)gv), 0)), SvPVX(gv))
451 const STRLEN protolen = proto ? SvCUR(gv) : 0;
452 const U32 proto_utf8 = proto ? SvUTF8(gv) : 0;
453 SV *const has_constant = doproto && SvROK(gv) ? SvRV(gv) : NULL;
454 const U32 exported_constant = has_constant ? SvPCS_IMPORTED(gv) : 0;
455 const bool really_sub =
456 has_constant && SvTYPE(has_constant) == SVt_PVCV;
457 COP * const old = PL_curcop;
459 PERL_ARGS_ASSERT_GV_INIT_PVN;
460 assert (!(proto && has_constant));
463 /* The constant has to be a scalar, array or subroutine. */
464 switch (SvTYPE(has_constant)) {
468 Perl_croak(aTHX_ "Cannot convert a reference to %s to typeglob",
469 sv_reftype(has_constant, 0));
470 NOT_REACHED; /* NOTREACHED */
480 if (old_type < SVt_PVGV) {
481 if (old_type >= SVt_PV)
483 sv_upgrade(MUTABLE_SV(gv), SVt_PVGV);
487 /* For this case, we are "stealing" the buffer from the SvPV and
488 re-attaching to an SV below with the call to sv_usepvn_flags().
489 Hence we don't free it. */
493 /* There is no valid prototype. (SvPOK() must be true for a valid
494 prototype.) Hence we free the memory. */
495 Safefree(SvPVX_mutable(gv));
503 if (really_sub && !CvISXSUB(has_constant) && CvSTART(has_constant)
504 && ( CvSTART(has_constant)->op_type == OP_NEXTSTATE
505 || CvSTART(has_constant)->op_type == OP_DBSTATE))
506 PL_curcop = (COP *)CvSTART(has_constant);
507 GvGP_set(gv, Perl_newGP(aTHX_ gv));
511 Perl_sv_add_backref(aTHX_ MUTABLE_SV(stash), MUTABLE_SV(gv));
512 gv_name_set(gv, name, len, GV_ADD | ( flags & SVf_UTF8 ? SVf_UTF8 : 0 ));
513 if (flags & GV_ADDMULTI || doproto) /* doproto means it */
514 GvMULTI_on(gv); /* _was_ mentioned */
516 /* Not actually a constant. Just a regular sub. */
517 CV * const cv = (CV *)has_constant;
519 if (CvNAMED(cv) && CvSTASH(cv) == stash && (
520 CvNAME_HEK(cv) == GvNAME_HEK(gv)
521 || ( HEK_LEN(CvNAME_HEK(cv)) == HEK_LEN(GvNAME_HEK(gv))
522 && HEK_FLAGS(CvNAME_HEK(cv)) != HEK_FLAGS(GvNAME_HEK(gv))
523 && HEK_UTF8(CvNAME_HEK(cv)) == HEK_UTF8(GvNAME_HEK(gv))
524 && memEQ(HEK_KEY(CvNAME_HEK(cv)), GvNAME(gv), GvNAMELEN(gv))
532 /* newCONSTSUB takes ownership of the reference from us. */
533 cv = newCONSTSUB_flags(stash, name, len, flags, has_constant);
534 /* In case op.c:S_process_special_blocks stole it: */
536 GvCV_set(gv, (CV *)SvREFCNT_inc_simple_NN(cv));
537 assert(GvCV(gv) == cv); /* newCONSTSUB should have set this */
538 /* If this reference was a copy of another, then the subroutine
539 must have been "imported", by a Perl space assignment to a GV
540 from a reference to CV. */
541 if (exported_constant)
542 GvIMPORTED_CV_on(gv);
543 CvSTASH_set(cv, PL_curstash); /* XXX Why is this needed? */
548 sv_usepvn_flags(MUTABLE_SV(cv), proto, protolen,
549 SV_HAS_TRAILING_NUL);
550 if ( proto_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
556 S_gv_init_svtype(pTHX_ GV *gv, const svtype sv_type)
558 PERL_ARGS_ASSERT_GV_INIT_SVTYPE;
570 #ifdef PERL_DONT_CREATE_GVSV
578 /* Work round what appears to be a bug in Sun C++ 5.8 2005/10/13
579 If we just cast GvSVn(gv) to void, it ignores evaluating it for
586 static void core_xsub(pTHX_ CV* cv);
589 S_maybe_add_coresub(pTHX_ HV * const stash, GV *gv,
590 const char * const name, const STRLEN len)
592 const int code = keyword(name, len, 1);
593 static const char file[] = __FILE__;
594 CV *cv, *oldcompcv = NULL;
596 bool ampable = TRUE; /* &{}-able */
597 COP *oldcurcop = NULL;
598 yy_parser *oldparser = NULL;
599 I32 oldsavestack_ix = 0;
604 if (!code) return NULL; /* Not a keyword */
605 switch (code < 0 ? -code : code) {
606 /* no support for \&CORE::infix;
607 no support for funcs that do not parse like funcs */
608 case KEY___DATA__: case KEY___END__ :
609 case KEY_ADJUST : case KEY_AUTOLOAD: case KEY_BEGIN : case KEY_CHECK :
610 case KEY_DESTROY : case KEY_END : case KEY_INIT : case KEY_UNITCHECK:
611 case KEY_and : case KEY_catch : case KEY_class :
612 case KEY_cmp : case KEY_default: case KEY_defer :
613 case KEY_do : case KEY_dump : case KEY_else : case KEY_elsif :
614 case KEY_eq : case KEY_eval : case KEY_field :
616 case KEY_for : case KEY_foreach: case KEY_format: case KEY_ge :
617 case KEY_given : case KEY_goto : case KEY_grep : case KEY_gt :
618 case KEY_if : case KEY_isa :
620 case KEY_le : case KEY_local : case KEY_lt : case KEY_m :
621 case KEY_map : case KEY_method : case KEY_my :
622 case KEY_ne : case KEY_next : case KEY_no: case KEY_or: case KEY_our:
623 case KEY_package: case KEY_print: case KEY_printf:
624 case KEY_q : case KEY_qq : case KEY_qr : case KEY_qw :
625 case KEY_qx : case KEY_redo : case KEY_require: case KEY_return:
626 case KEY_s : case KEY_say : case KEY_sort :
627 case KEY_state: case KEY_sub :
628 case KEY_tr : case KEY_try :
630 case KEY_until: case KEY_use : case KEY_when : case KEY_while :
631 case KEY_x : case KEY_xor : case KEY_y :
634 case KEY_chomp: case KEY_chop: case KEY_defined: case KEY_delete:
635 case KEY_eof : case KEY_exec: case KEY_exists :
640 case KEY_truncate: case KEY_unlink:
644 gv = (GV *)newSV_type(SVt_NULL);
645 gv_init(gv, stash, name, len, TRUE);
650 oldcurcop = PL_curcop;
651 oldparser = PL_parser;
652 lex_start(NULL, NULL, 0);
653 oldcompcv = PL_compcv;
654 PL_compcv = NULL; /* Prevent start_subparse from setting
656 oldsavestack_ix = start_subparse(FALSE,0);
660 /* Avoid calling newXS, as it calls us, and things start to
662 cv = MUTABLE_CV(newSV_type(SVt_PVCV));
666 CvXSUB(cv) = core_xsub;
669 CvGV_set(cv, gv); /* This stops new ATTRSUB from setting CvFILE
671 /* XSUBs can't be perl lang/perl5db.pl debugged
672 if (PERLDB_LINE_OR_SAVESRC)
673 (void)gv_fetchfile(file); */
674 CvFILE(cv) = (char *)file;
675 /* XXX This is inefficient, as doing things this order causes
676 a prototype check in newATTRSUB. But we have to do
677 it this order as we need an op number before calling
679 (void)core_prototype((SV *)cv, name, code, &opnum);
681 (void)hv_store(stash,name,len,(SV *)gv,0);
687 /* newATTRSUB will free the CV and return NULL if we're still
688 compiling after a syntax error */
689 if ((cv = newATTRSUB_x(
690 oldsavestack_ix, (OP *)gv,
695 : newSVpvn(name,len),
700 assert(GvCV(gv) == orig_cv);
701 if (opnum != OP_VEC && opnum != OP_SUBSTR && opnum != OP_POS
702 && opnum != OP_UNDEF && opnum != OP_KEYS)
703 CvLVALUE_off(cv); /* Now *that* was a neat trick. */
706 PL_parser = oldparser;
707 PL_curcop = oldcurcop;
708 PL_compcv = oldcompcv;
711 SV *opnumsv = newSViv(
712 (opnum == OP_ENTEREVAL && len == 9 && memEQ(name, "evalbytes", 9)) ?
713 (OP_ENTEREVAL | (1<<16))
714 : opnum ? opnum : (((I32)name[2]) << 16));
715 cv_set_call_checker_flags(cv, Perl_ck_entersub_args_core, opnumsv, 0);
716 SvREFCNT_dec_NN(opnumsv);
723 =for apidoc gv_fetchmeth
724 =for apidoc_item gv_fetchmeth_pv
725 =for apidoc_item gv_fetchmeth_pvn
726 =for apidoc_item gv_fetchmeth_sv
728 These each look for a glob with name C<name>, containing a defined subroutine,
729 returning the GV of that glob if found, or C<NULL> if not.
731 C<stash> is always searched (first), unless it is C<NULL>.
733 If C<stash> is NULL, or was searched but nothing was found in it, and the
734 C<GV_SUPER> bit is set in C<flags>, stashes accessible via C<@ISA> are searched
735 next. Searching is conducted according to L<C<MRO> order|perlmroapi>.
737 Finally, if no matches were found so far, and the C<GV_NOUNIVERSAL> flag in
738 C<flags> is not set, C<UNIVERSAL::> is searched.
740 The argument C<level> should be either 0 or -1. If -1, the function will
741 return without any side effects or caching. If 0, the function makes sure
742 there is a glob named C<name> in C<stash>, creating one if necessary.
743 The subroutine slot in the glob will be set to any subroutine found in the
744 C<stash> and C<SUPER::> search, hence caching any C<SUPER::> result. Note that
745 subroutines found in C<UNIVERSAL::> are not cached.
747 The GV returned from these may be a method cache entry, which is not visible to
748 Perl code. So when calling C<call_sv>, you should not use the GV directly;
749 instead, you should use the method's CV, which can be obtained from the GV with
752 The only other significant value for C<flags> is C<SVf_UTF8>, indicating that
753 C<name> is to be treated as being encoded in UTF-8.
755 Plain C<gv_fetchmeth> lacks a C<flags> parameter, hence always searches in
756 C<stash>, then C<UNIVERSAL::>, and C<name> is never UTF-8. Otherwise it is
757 exactly like C<gv_fetchmeth_pvn>.
759 The other forms do have a C<flags> parameter, and differ only in how the glob
762 In C<gv_fetchmeth_pv>, C<name> is a C language NUL-terminated string.
764 In C<gv_fetchmeth_pvn>, C<name> points to the first byte of the name, and an
765 additional parameter, C<len>, specifies its length in bytes. Hence, the name
766 may contain embedded-NUL characters.
768 In C<gv_fetchmeth_sv>, C<*name> is an SV, and the name is the PV extracted from
769 that, using L</C<SvPV>>. If the SV is marked as being in UTF-8, the extracted
772 =for apidoc Amnh||GV_SUPER
778 Perl_gv_fetchmeth_sv(pTHX_ HV *stash, SV *namesv, I32 level, U32 flags)
782 PERL_ARGS_ASSERT_GV_FETCHMETH_SV;
783 if (LIKELY(SvPOK_nog(namesv))) /* common case */
784 return gv_fetchmeth_internal(stash, namesv, NULL, 0, level,
785 flags | SvUTF8(namesv));
786 namepv = SvPV(namesv, namelen);
787 if (SvUTF8(namesv)) flags |= SVf_UTF8;
788 return gv_fetchmeth_pvn(stash, namepv, namelen, level, flags);
793 Perl_gv_fetchmeth_pv(pTHX_ HV *stash, const char *name, I32 level, U32 flags)
795 PERL_ARGS_ASSERT_GV_FETCHMETH_PV;
796 return gv_fetchmeth_internal(stash, NULL, name, strlen(name), level, flags);
799 /* NOTE: No support for tied ISA */
801 PERL_STATIC_INLINE GV*
802 S_gv_fetchmeth_internal(pTHX_ HV* stash, SV* meth, const char* name, STRLEN len, I32 level, U32 flags)
809 HV* cstash, *cachestash;
810 GV* candidate = NULL;
815 I32 create = (level >= 0) ? HV_FETCH_LVALUE : 0;
818 U32 is_utf8 = flags & SVf_UTF8;
820 /* UNIVERSAL methods should be callable without a stash */
822 create = 0; /* probably appropriate */
823 if(!(stash = gv_stashpvs("UNIVERSAL", 0)))
829 hvname = HvNAME_get(stash);
830 hvnamelen = HvNAMELEN_get(stash);
832 Perl_croak(aTHX_ "Can't use anonymous symbol table for method lookup");
835 assert(name || meth);
837 DEBUG_o( Perl_deb(aTHX_ "Looking for %smethod %s in package %s\n",
838 flags & GV_SUPER ? "SUPER " : "",
839 name ? name : SvPV_nolen(meth), hvname) );
841 topgen_cmp = HvMROMETA(stash)->cache_gen + PL_sub_generation;
843 if (flags & GV_SUPER) {
844 if (!HvAUX(stash)->xhv_mro_meta->super)
845 HvAUX(stash)->xhv_mro_meta->super = newHV();
846 cachestash = HvAUX(stash)->xhv_mro_meta->super;
848 else cachestash = stash;
850 /* check locally for a real method or a cache entry */
852 cachestash, meth, name, len, is_utf8 ? HVhek_UTF8 : 0, create, NULL, 0
854 if (he) gvp = (GV**)&HeVAL(he);
861 if (SvTYPE(topgv) != SVt_PVGV)
864 name = SvPV_nomg(meth, len);
865 gv_init_pvn(topgv, stash, name, len, GV_ADDMULTI|is_utf8);
867 if ((cand_cv = GvCV(topgv))) {
868 /* If genuine method or valid cache entry, use it */
869 if (!GvCVGEN(topgv) || GvCVGEN(topgv) == topgen_cmp) {
873 /* stale cache entry, junk it and move on */
874 SvREFCNT_dec_NN(cand_cv);
875 GvCV_set(topgv, NULL);
880 else if (GvCVGEN(topgv) == topgen_cmp) {
881 /* cache indicates no such method definitively */
884 else if (stash == cachestash
885 && len > 1 /* shortest is uc */
886 && memEQs(hvname, HvNAMELEN_get(stash), "CORE")
887 && S_maybe_add_coresub(aTHX_ NULL,topgv,name,len))
891 linear_av = mro_get_linear_isa(stash); /* has ourselves at the top of the list */
892 linear_svp = AvARRAY(linear_av) + 1; /* skip over self */
893 items = AvFILLp(linear_av); /* no +1, to skip over self */
895 linear_sv = *linear_svp++;
897 cstash = gv_stashsv(linear_sv, 0);
900 if ( ckWARN(WARN_SYNTAX)) {
901 if( /* these are loaded from Perl_Gv_AMupdate() one way or another */
902 ( len && name[0] == '(' ) /* overload.pm related, in particular "()" */
903 || ( memEQs( name, len, "DESTROY") )
905 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
906 "Can't locate package %" SVf " for @%" HEKf "::ISA",
908 HEKfARG(HvNAME_HEK(stash)));
910 } else if( memEQs( name, len, "AUTOLOAD") ) {
911 /* gobble this warning */
913 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
914 "While trying to resolve method call %.*s->%.*s()"
915 " can not locate package %" SVf_QUOTEDPREFIX " yet it is mentioned in @%.*s::ISA"
916 " (perhaps you forgot to load %" SVf_QUOTEDPREFIX "?)",
917 (int) hvnamelen, hvname,
920 (int) hvnamelen, hvname,
929 gvp = (GV**)hv_common(
930 cstash, meth, name, len, is_utf8 ? HVhek_UTF8 : 0, HV_FETCH_JUST_SV, NULL, 0
933 if (len > 1 && HvNAMELEN_get(cstash) == 4) {
934 const char *hvname = HvNAME(cstash); assert(hvname);
935 if (strBEGINs(hvname, "CORE")
937 S_maybe_add_coresub(aTHX_ cstash,NULL,name,len)
943 else candidate = *gvp;
946 if (SvTYPE(candidate) != SVt_PVGV)
947 gv_init_pvn(candidate, cstash, name, len, GV_ADDMULTI|is_utf8);
948 if (SvTYPE(candidate) == SVt_PVGV && (cand_cv = GvCV(candidate)) && !GvCVGEN(candidate)) {
950 * Found real method, cache method in topgv if:
951 * 1. topgv has no synonyms (else inheritance crosses wires)
952 * 2. method isn't a stub (else AUTOLOAD fails spectacularly)
954 if (topgv && (GvREFCNT(topgv) == 1) && (CvROOT(cand_cv) || CvXSUB(cand_cv))) {
955 CV *old_cv = GvCV(topgv);
956 SvREFCNT_dec(old_cv);
957 SvREFCNT_inc_simple_void_NN(cand_cv);
958 GvCV_set(topgv, cand_cv);
959 GvCVGEN(topgv) = topgen_cmp;
965 /* Check UNIVERSAL without caching */
966 if((level == 0 || level == -1) && !(flags & GV_NOUNIVERSAL)) {
967 candidate = gv_fetchmeth_internal(NULL, meth, name, len, 1,
970 cand_cv = GvCV(candidate);
971 if (topgv && (GvREFCNT(topgv) == 1) && (CvROOT(cand_cv) || CvXSUB(cand_cv))) {
972 CV *old_cv = GvCV(topgv);
973 SvREFCNT_dec(old_cv);
974 SvREFCNT_inc_simple_void_NN(cand_cv);
975 GvCV_set(topgv, cand_cv);
976 GvCVGEN(topgv) = topgen_cmp;
982 if (topgv && GvREFCNT(topgv) == 1 && !(flags & GV_NOUNIVERSAL)) {
983 /* cache the fact that the method is not defined */
984 GvCVGEN(topgv) = topgen_cmp;
991 Perl_gv_fetchmeth_pvn(pTHX_ HV *stash, const char *name, STRLEN len, I32 level, U32 flags)
993 PERL_ARGS_ASSERT_GV_FETCHMETH_PVN;
994 return gv_fetchmeth_internal(stash, NULL, name, len, level, flags);
998 =for apidoc gv_fetchmeth_autoload
1000 This is the old form of L</gv_fetchmeth_pvn_autoload>, which has no flags
1003 =for apidoc gv_fetchmeth_sv_autoload
1005 Exactly like L</gv_fetchmeth_pvn_autoload>, but takes the name string in the form
1006 of an SV instead of a string/length pair.
1012 Perl_gv_fetchmeth_sv_autoload(pTHX_ HV *stash, SV *namesv, I32 level, U32 flags)
1016 PERL_ARGS_ASSERT_GV_FETCHMETH_SV_AUTOLOAD;
1017 namepv = SvPV(namesv, namelen);
1020 return gv_fetchmeth_pvn_autoload(stash, namepv, namelen, level, flags);
1024 =for apidoc gv_fetchmeth_pv_autoload
1026 Exactly like L</gv_fetchmeth_pvn_autoload>, but takes a nul-terminated string
1027 instead of a string/length pair.
1033 Perl_gv_fetchmeth_pv_autoload(pTHX_ HV *stash, const char *name, I32 level, U32 flags)
1035 PERL_ARGS_ASSERT_GV_FETCHMETH_PV_AUTOLOAD;
1036 return gv_fetchmeth_pvn_autoload(stash, name, strlen(name), level, flags);
1040 =for apidoc gv_fetchmeth_pvn_autoload
1042 Same as C<gv_fetchmeth_pvn()>, but looks for autoloaded subroutines too.
1043 Returns a glob for the subroutine.
1045 For an autoloaded subroutine without a GV, will create a GV even
1046 if C<level < 0>. For an autoloaded subroutine without a stub, C<GvCV()>
1047 of the result may be zero.
1049 Currently, the only significant value for C<flags> is C<SVf_UTF8>.
1055 Perl_gv_fetchmeth_pvn_autoload(pTHX_ HV *stash, const char *name, STRLEN len, I32 level, U32 flags)
1057 GV *gv = gv_fetchmeth_pvn(stash, name, len, level, flags);
1059 PERL_ARGS_ASSERT_GV_FETCHMETH_PVN_AUTOLOAD;
1066 return NULL; /* UNIVERSAL::AUTOLOAD could cause trouble */
1067 if (len == S_autolen && memEQ(name, S_autoload, S_autolen))
1069 if (!(gv = gv_fetchmeth_pvn(stash, S_autoload, S_autolen, FALSE, flags)))
1072 if (!(CvROOT(cv) || CvXSUB(cv)))
1074 /* Have an autoload */
1075 if (level < 0) /* Cannot do without a stub */
1076 gv_fetchmeth_pvn(stash, name, len, 0, flags);
1077 gvp = (GV**)hv_fetch(stash, name,
1078 (flags & SVf_UTF8) ? -(I32)len : (I32)len, (level >= 0));
1087 =for apidoc gv_fetchmethod_autoload
1089 Returns the glob which contains the subroutine to call to invoke the method
1090 on the C<stash>. In fact in the presence of autoloading this may be the
1091 glob for "AUTOLOAD". In this case the corresponding variable C<$AUTOLOAD> is
1094 The third parameter of C<gv_fetchmethod_autoload> determines whether
1095 AUTOLOAD lookup is performed if the given method is not present: non-zero
1096 means yes, look for AUTOLOAD; zero means no, don't look for AUTOLOAD.
1097 Calling C<gv_fetchmethod> is equivalent to calling C<gv_fetchmethod_autoload>
1098 with a non-zero C<autoload> parameter.
1100 These functions grant C<"SUPER"> token
1101 as a prefix of the method name. Note
1102 that if you want to keep the returned glob for a long time, you need to
1103 check for it being "AUTOLOAD", since at the later time the call may load a
1104 different subroutine due to C<$AUTOLOAD> changing its value. Use the glob
1105 created as a side effect to do this.
1107 These functions have the same side-effects as C<gv_fetchmeth> with
1108 C<level==0>. The warning against passing the GV returned by
1109 C<gv_fetchmeth> to C<call_sv> applies equally to these functions.
1115 Perl_gv_fetchmethod_autoload(pTHX_ HV *stash, const char *name, I32 autoload)
1117 PERL_ARGS_ASSERT_GV_FETCHMETHOD_AUTOLOAD;
1119 return gv_fetchmethod_flags(stash, name, autoload ? GV_AUTOLOAD : 0);
1123 Perl_gv_fetchmethod_sv_flags(pTHX_ HV *stash, SV *namesv, U32 flags)
1127 PERL_ARGS_ASSERT_GV_FETCHMETHOD_SV_FLAGS;
1128 namepv = SvPV(namesv, namelen);
1131 return gv_fetchmethod_pvn_flags(stash, namepv, namelen, flags);
1135 Perl_gv_fetchmethod_pv_flags(pTHX_ HV *stash, const char *name, U32 flags)
1137 PERL_ARGS_ASSERT_GV_FETCHMETHOD_PV_FLAGS;
1138 return gv_fetchmethod_pvn_flags(stash, name, strlen(name), flags);
1142 Perl_gv_fetchmethod_pvn_flags(pTHX_ HV *stash, const char *name, const STRLEN len, U32 flags)
1144 const char * const origname = name;
1145 const char * const name_end = name + len;
1146 const char *last_separator = NULL;
1149 SV *const error_report = MUTABLE_SV(stash);
1150 const U32 autoload = flags & GV_AUTOLOAD;
1151 const U32 do_croak = flags & GV_CROAK;
1152 const U32 is_utf8 = flags & SVf_UTF8;
1154 PERL_ARGS_ASSERT_GV_FETCHMETHOD_PVN_FLAGS;
1156 if (SvTYPE(stash) < SVt_PVHV)
1159 /* The only way stash can become NULL later on is if last_separator is set,
1160 which in turn means that there is no need for a SVt_PVHV case
1161 the error reporting code. */
1165 /* check if the method name is fully qualified or
1166 * not, and separate the package name from the actual
1169 * leaves last_separator pointing to the beginning of the
1170 * last package separator (either ' or ::) or 0
1171 * if none was found.
1173 * leaves name pointing at the beginning of the
1176 const char *name_cursor = name;
1177 const char * const name_em1 = name_end - 1; /* name_end minus 1 */
1178 for (name_cursor = name; name_cursor < name_end ; name_cursor++) {
1179 if (*name_cursor == '\'') {
1180 last_separator = name_cursor;
1181 name = name_cursor + 1;
1183 else if (name_cursor < name_em1 && *name_cursor == ':' && name_cursor[1] == ':') {
1184 last_separator = name_cursor++;
1185 name = name_cursor + 1;
1190 /* did we find a separator? */
1191 if (last_separator) {
1192 STRLEN sep_len= last_separator - origname;
1193 if ( memEQs(origname, sep_len, "SUPER")) {
1194 /* ->SUPER::method should really be looked up in original stash */
1195 stash = CopSTASH(PL_curcop);
1197 DEBUG_o( Perl_deb(aTHX_ "Treating %s as %s::%s\n",
1198 origname, HvENAME_get(stash), name) );
1200 else if ( sep_len >= 7 &&
1201 strBEGINs(last_separator - 7, "::SUPER")) {
1202 /* don't autovivify if ->NoSuchStash::SUPER::method */
1203 stash = gv_stashpvn(origname, sep_len - 7, is_utf8);
1204 if (stash) flags |= GV_SUPER;
1207 /* don't autovivify if ->NoSuchStash::method */
1208 stash = gv_stashpvn(origname, sep_len, is_utf8);
1213 gv = gv_fetchmeth_pvn(stash, name, name_end - name, 0, flags);
1216 gv = gv_autoload_pvn(
1217 ostash, name, name_end - name, GV_AUTOLOAD_ISMETHOD|flags
1219 if (!gv && do_croak) {
1220 /* Right now this is exclusively for the benefit of S_method_common
1223 /* If we can't find an IO::File method, it might be a call on
1224 * a filehandle. If IO:File has not been loaded, try to
1225 * require it first instead of croaking */
1226 const char *stash_name = HvNAME_get(stash);
1227 if (stash_name && memEQs(stash_name, HvNAMELEN_get(stash), "IO::File")
1228 && !Perl_hv_common(aTHX_ GvHVn(PL_incgv), NULL,
1229 STR_WITH_LEN("IO/File.pm"), 0,
1230 HV_FETCH_ISEXISTS, NULL, 0)
1232 require_pv("IO/File.pm");
1233 gv = gv_fetchmeth_pvn(stash, name, name_end - name, 0, flags);
1238 "Can't locate object method %" UTF8f_QUOTEDPREFIX ""
1239 " via package %" HEKf_QUOTEDPREFIX,
1240 UTF8fARG(is_utf8, name_end - name, name),
1241 HEKfARG(HvNAME_HEK(stash)));
1246 if (last_separator) {
1247 packnamesv = newSVpvn_flags(origname, last_separator - origname,
1248 SVs_TEMP | is_utf8);
1250 packnamesv = error_report;
1254 "Can't locate object method %" UTF8f_QUOTEDPREFIX ""
1255 " via package %" SVf_QUOTEDPREFIX ""
1256 " (perhaps you forgot to load %" SVf_QUOTEDPREFIX "?)",
1257 UTF8fARG(is_utf8, name_end - name, name),
1258 SVfARG(packnamesv), SVfARG(packnamesv));
1262 else if (autoload) {
1263 CV* const cv = GvCV(gv);
1264 if (!CvROOT(cv) && !CvXSUB(cv)) {
1268 if (CvANON(cv) || CvLEXICAL(cv))
1272 if (GvCV(stubgv) != cv) /* orphaned import */
1275 autogv = gv_autoload_pvn(GvSTASH(stubgv),
1276 GvNAME(stubgv), GvNAMELEN(stubgv),
1277 GV_AUTOLOAD_ISMETHOD
1278 | (GvNAMEUTF8(stubgv) ? SVf_UTF8 : 0));
1289 =for apidoc gv_autoload_pv
1290 =for apidoc_item gv_autoload_pvn
1291 =for apidoc_item gv_autoload_sv
1293 These each search for an C<AUTOLOAD> method, returning NULL if not found, or
1294 else returning a pointer to its GV, while setting the package
1295 L<C<$AUTOLOAD>|perlobj/AUTOLOAD> variable to C<name> (fully qualified). Also,
1296 if found and the GV's CV is an XSUB, the CV's PV will be set to C<name>, and
1297 its stash will be set to the stash of the GV.
1299 Searching is done in L<C<MRO> order|perlmroapi>, as specified in
1300 L</C<gv_fetchmeth>>, beginning with C<stash> if it isn't NULL.
1302 The forms differ only in how C<name> is specified.
1304 In C<gv_autoload_pv>, C<namepv> is a C language NUL-terminated string.
1306 In C<gv_autoload_pvn>, C<name> points to the first byte of the name, and an
1307 additional parameter, C<len>, specifies its length in bytes. Hence, C<*name>
1308 may contain embedded-NUL characters.
1310 In C<gv_autoload_sv>, C<*namesv> is an SV, and the name is the PV extracted
1311 from that using L</C<SvPV>>. If the SV is marked as being in UTF-8, the
1312 extracted PV will also be.
1318 Perl_gv_autoload_sv(pTHX_ HV *stash, SV* namesv, U32 flags)
1322 PERL_ARGS_ASSERT_GV_AUTOLOAD_SV;
1323 namepv = SvPV(namesv, namelen);
1326 return gv_autoload_pvn(stash, namepv, namelen, flags);
1330 Perl_gv_autoload_pv(pTHX_ HV *stash, const char *namepv, U32 flags)
1332 PERL_ARGS_ASSERT_GV_AUTOLOAD_PV;
1333 return gv_autoload_pvn(stash, namepv, strlen(namepv), flags);
1337 Perl_gv_autoload_pvn(pTHX_ HV *stash, const char *name, STRLEN len, U32 flags)
1344 SV *packname = NULL;
1345 U32 is_utf8 = flags & SVf_UTF8 ? SVf_UTF8 : 0;
1347 PERL_ARGS_ASSERT_GV_AUTOLOAD_PVN;
1349 if (len == S_autolen && memEQ(name, S_autoload, S_autolen))
1352 if (SvTYPE(stash) < SVt_PVHV) {
1353 STRLEN packname_len = 0;
1354 const char * const packname_ptr = SvPV_const(MUTABLE_SV(stash), packname_len);
1355 packname = newSVpvn_flags(packname_ptr, packname_len,
1356 SVs_TEMP | SvUTF8(stash));
1360 packname = newSVhek_mortal(HvNAME_HEK(stash));
1361 if (flags & GV_SUPER) sv_catpvs(packname, "::SUPER");
1363 if (!(gv = gv_fetchmeth_pvn(stash, S_autoload, S_autolen, FALSE,
1364 is_utf8 | (flags & GV_SUPER))))
1368 if (!(CvROOT(cv) || CvXSUB(cv)))
1372 * Inheriting AUTOLOAD for non-methods no longer works
1375 !(flags & GV_AUTOLOAD_ISMETHOD)
1376 && (GvCVGEN(gv) || GvSTASH(gv) != stash)
1378 Perl_croak(aTHX_ "Use of inherited AUTOLOAD for non-method %" SVf
1379 "::%" UTF8f "() is no longer allowed",
1381 UTF8fARG(is_utf8, len, name));
1384 /* Instead of forcing the XSUB to do another lookup for $AUTOLOAD
1385 * and split that value on the last '::', pass along the same data
1386 * via the SvPVX field in the CV, and the stash in CvSTASH.
1388 * Due to an unfortunate accident of history, the SvPVX field
1389 * serves two purposes. It is also used for the subroutine's
1390 * prototype. Since SvPVX has been documented as returning the sub
1391 * name for a long time, but not as returning the prototype, we have to
1392 * preserve the SvPVX AUTOLOAD behaviour and put the prototype
1395 * We put the prototype in the same allocated buffer, but after
1396 * the sub name. The SvPOK flag indicates the presence of a proto-
1397 * type. The CvAUTOLOAD flag indicates the presence of a sub name.
1398 * If both flags are on, then SvLEN is used to indicate the end of
1399 * the prototype (artificially lower than what is actually allo-
1400 * cated), at the risk of having to reallocate a few bytes unneces-
1401 * sarily--but that should happen very rarely, if ever.
1403 * We use SvUTF8 for both prototypes and sub names, so if one is
1404 * UTF8, the other must be upgraded.
1406 CvSTASH_set(cv, stash);
1407 if (SvPOK(cv)) { /* Ouch! */
1408 SV * const tmpsv = newSVpvn_flags(name, len, is_utf8);
1410 const char *proto = CvPROTO(cv);
1413 sv_utf8_upgrade_flags_grow(tmpsv, 0, CvPROTOLEN(cv) + 2);
1414 ulen = SvCUR(tmpsv);
1415 SvCUR_set(tmpsv, SvCUR(tmpsv) + 1); /* include null in string */
1417 tmpsv, proto, CvPROTOLEN(cv), SV_CATBYTES*!SvUTF8(cv)
1419 SvTEMP_on(tmpsv); /* Allow theft */
1420 sv_setsv_nomg((SV *)cv, tmpsv);
1422 SvREFCNT_dec_NN(tmpsv);
1423 SvLEN_set(cv, SvCUR(cv) + 1);
1424 SvCUR_set(cv, ulen);
1427 sv_setpvn((SV *)cv, name, len);
1431 else SvUTF8_off(cv);
1437 * Given &FOO::AUTOLOAD, set $FOO::AUTOLOAD to desired function name.
1438 * The subroutine's original name may not be "AUTOLOAD", so we don't
1439 * use that, but for lack of anything better we will use the sub's
1440 * original package to look up $AUTOLOAD.
1442 varstash = CvNAMED(cv) ? CvSTASH(cv) : GvSTASH(CvGV(cv));
1443 vargv = *(GV**)hv_fetch(varstash, S_autoload, S_autolen, TRUE);
1447 gv_init_pvn(vargv, varstash, S_autoload, S_autolen, 0);
1448 #ifdef PERL_DONT_CREATE_GVSV
1449 GvSV(vargv) = newSV_type(SVt_NULL);
1453 varsv = GvSVn(vargv);
1454 SvTAINTED_off(varsv); /* previous $AUTOLOAD taint is obsolete */
1455 /* XXX: this process is not careful to avoid extra magic gets and sets; tied $AUTOLOAD will get noise */
1456 sv_setsv(varsv, packname);
1457 sv_catpvs(varsv, "::");
1458 /* Ensure SvSETMAGIC() is called if necessary. In particular, to clear
1459 tainting if $FOO::AUTOLOAD was previously tainted, but is not now. */
1462 SV_SMAGIC|(is_utf8 ? SV_CATUTF8 : SV_CATBYTES)
1470 /* require_tie_mod() internal routine for requiring a module
1471 * that implements the logic of automatic ties like %! and %-
1472 * It loads the module and then calls the _tie_it subroutine
1473 * with the passed gv as an argument.
1475 * The "gv" parameter should be the glob.
1476 * "varname" holds the 1-char name of the var, used for error messages.
1477 * "namesv" holds the module name. Its refcount will be decremented.
1478 * "flags": if flag & 1 then save the scalar before loading.
1479 * For the protection of $! to work (it is set by this routine)
1480 * the sv slot must already be magicalized.
1483 S_require_tie_mod(pTHX_ GV *gv, const char varname, const char * name,
1484 STRLEN len, const U32 flags)
1486 const SV * const target = varname == '[' ? GvSV(gv) : (SV *)GvHV(gv);
1488 PERL_ARGS_ASSERT_REQUIRE_TIE_MOD;
1490 /* If it is not tied */
1491 if (!target || !SvRMAGICAL(target)
1493 varname == '[' ? PERL_MAGIC_tiedscalar : PERL_MAGIC_tied))
1499 PUSHSTACKi(PERLSI_MAGIC);
1502 #define GET_HV_FETCH_TIE_FUNC \
1503 ( (gvp = (GV **)hv_fetchs(stash, "_tie_it", 0)) \
1505 && ( (isGV(*gvp) && GvCV(*gvp)) \
1506 || (SvROK(*gvp) && SvTYPE(SvRV(*gvp)) == SVt_PVCV) ) \
1509 /* Load the module if it is not loaded. */
1510 if (!(stash = gv_stashpvn(name, len, 0))
1511 || ! GET_HV_FETCH_TIE_FUNC)
1513 SV * const module = newSVpvn(name, len);
1514 const char type = varname == '[' ? '$' : '%';
1517 Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT, module, NULL);
1518 assert(sp == PL_stack_sp);
1519 stash = gv_stashpvn(name, len, 0);
1521 Perl_croak(aTHX_ "panic: Can't use %c%c because %s is not available",
1522 type, varname, name);
1523 else if (! GET_HV_FETCH_TIE_FUNC)
1524 Perl_croak(aTHX_ "panic: Can't use %c%c because %s does not define _tie_it",
1525 type, varname, name);
1527 /* Now call the tie function. It should be in *gvp. */
1528 assert(gvp); assert(*gvp);
1532 call_sv((SV *)*gvp, G_VOID|G_DISCARD);
1538 /* add a require_tie_mod_s - the _s suffix is similar to pvs type suffixes,
1539 * IOW it means we do STR_WITH_LEN() ourselves and the user should pass in
1540 * a true string WITHOUT a len.
1542 #define require_tie_mod_s(gv, varname, name, flags) \
1543 S_require_tie_mod(aTHX_ gv, varname, STR_WITH_LEN(name), flags)
1546 =for apidoc gv_stashpv
1548 Returns a pointer to the stash for a specified package. Uses C<strlen> to
1549 determine the length of C<name>, then calls C<gv_stashpvn()>.
1555 Perl_gv_stashpv(pTHX_ const char *name, I32 create)
1557 PERL_ARGS_ASSERT_GV_STASHPV;
1558 return gv_stashpvn(name, strlen(name), create);
1562 =for apidoc gv_stashpvn
1564 Returns a pointer to the stash for a specified package. The C<namelen>
1565 parameter indicates the length of the C<name>, in bytes. C<flags> is passed
1566 to C<gv_fetchpvn_flags()>, so if set to C<GV_ADD> then the package will be
1567 created if it does not already exist. If the package does not exist and
1568 C<flags> is 0 (or any other setting that does not create packages) then C<NULL>
1571 Flags may be one of:
1573 GV_ADD Create and initialize the package if doesn't
1575 GV_NOADD_NOINIT Don't create the package,
1576 GV_ADDMG GV_ADD iff the GV is magical
1577 GV_NOINIT GV_ADD, but don't initialize
1578 GV_NOEXPAND Don't expand SvOK() entries to PVGV
1579 SVf_UTF8 The name is in UTF-8
1581 The most important of which are probably C<GV_ADD> and C<SVf_UTF8>.
1583 Note, use of C<gv_stashsv> instead of C<gv_stashpvn> where possible is strongly
1584 recommended for performance reasons.
1586 =for apidoc Amnh||GV_ADD
1587 =for apidoc Amnh||GV_NOADD_NOINIT
1588 =for apidoc Amnh||GV_NOINIT
1589 =for apidoc Amnh||GV_NOEXPAND
1590 =for apidoc Amnh||GV_ADDMG
1591 =for apidoc Amnh||SVf_UTF8
1597 gv_stashpvn_internal
1599 Perform the internal bits of gv_stashsvpvn_cached. You could think of this
1600 as being one half of the logic. Not to be called except from gv_stashsvpvn_cached().
1604 PERL_STATIC_INLINE HV*
1605 S_gv_stashpvn_internal(pTHX_ const char *name, U32 namelen, I32 flags)
1611 U32 tmplen = namelen + 2;
1613 PERL_ARGS_ASSERT_GV_STASHPVN_INTERNAL;
1615 if (tmplen <= sizeof smallbuf)
1618 Newx(tmpbuf, tmplen, char);
1619 Copy(name, tmpbuf, namelen, char);
1620 tmpbuf[namelen] = ':';
1621 tmpbuf[namelen+1] = ':';
1622 tmpgv = gv_fetchpvn_flags(tmpbuf, tmplen, flags, SVt_PVHV);
1623 if (tmpbuf != smallbuf)
1625 if (!tmpgv || !isGV_with_GP(tmpgv))
1627 stash = GvHV(tmpgv);
1628 if (!(flags & ~GV_NOADD_MASK) && !stash) return NULL;
1630 if (!HvHasNAME(stash)) {
1631 hv_name_set(stash, name, namelen, flags & SVf_UTF8 ? SVf_UTF8 : 0 );
1633 /* FIXME: This is a repeat of logic in gv_fetchpvn_flags */
1634 /* If the containing stash has multiple effective
1635 names, see that this one gets them, too. */
1636 if (HvAUX(GvSTASH(tmpgv))->xhv_name_count)
1637 mro_package_moved(stash, NULL, tmpgv, 1);
1643 =for apidoc gv_stashsvpvn_cached
1645 Returns a pointer to the stash for a specified package, possibly
1646 cached. Implements both L<perlapi/C<gv_stashpvn>> and
1647 L<perlapi/C<gv_stashsv>>.
1649 Requires one of either C<namesv> or C<namepv> to be non-null.
1651 If the flag C<GV_CACHE_ONLY> is set, return the stash only if found in the
1652 cache; see L<perlapi/C<gv_stashpvn>> for details on the other C<flags>.
1654 Note it is strongly preferred for C<namesv> to be non-null, for performance
1657 =for apidoc Emnh||GV_CACHE_ONLY
1662 #define PERL_ARGS_ASSERT_GV_STASHSVPVN_CACHED \
1663 assert(namesv || name)
1666 Perl_gv_stashsvpvn_cached(pTHX_ SV *namesv, const char *name, U32 namelen, I32 flags)
1671 PERL_ARGS_ASSERT_GV_STASHSVPVN_CACHED;
1673 he = (HE *)hv_common(
1674 PL_stashcache, namesv, name, namelen,
1675 (flags & SVf_UTF8) ? HVhek_UTF8 : 0, 0, NULL, 0
1682 hv = INT2PTR(HV*, SvIVX(sv));
1683 assert(SvTYPE(hv) == SVt_PVHV);
1686 else if (flags & GV_CACHE_ONLY) return NULL;
1689 if (SvOK(namesv)) { /* prevent double uninit warning */
1691 name = SvPV_const(namesv, len);
1693 flags |= SvUTF8(namesv);
1695 name = ""; namelen = 0;
1698 stash = gv_stashpvn_internal(name, namelen, flags);
1700 if (stash && namelen) {
1701 SV* const ref = newSViv(PTR2IV(stash));
1702 (void)hv_store(PL_stashcache, name,
1703 (flags & SVf_UTF8) ? -(I32)namelen : (I32)namelen, ref, 0);
1710 Perl_gv_stashpvn(pTHX_ const char *name, U32 namelen, I32 flags)
1712 PERL_ARGS_ASSERT_GV_STASHPVN;
1713 return gv_stashsvpvn_cached(NULL, name, namelen, flags);
1717 =for apidoc gv_stashsv
1719 Returns a pointer to the stash for a specified package. See
1722 Note this interface is strongly preferred over C<gv_stashpvn> for performance
1729 Perl_gv_stashsv(pTHX_ SV *sv, I32 flags)
1731 PERL_ARGS_ASSERT_GV_STASHSV;
1732 return gv_stashsvpvn_cached(sv, NULL, 0, flags);
1735 Perl_gv_fetchpv(pTHX_ const char *nambeg, I32 flags, const svtype sv_type) {
1736 PERL_ARGS_ASSERT_GV_FETCHPV;
1737 return gv_fetchpvn_flags(nambeg, strlen(nambeg), flags, sv_type);
1741 Perl_gv_fetchsv(pTHX_ SV *name, I32 flags, const svtype sv_type) {
1743 const char * const nambeg =
1744 SvPV_flags_const(name, len, flags & GV_NO_SVGMAGIC ? 0 : SV_GMAGIC);
1745 PERL_ARGS_ASSERT_GV_FETCHSV;
1746 return gv_fetchpvn_flags(nambeg, len, flags | SvUTF8(name), sv_type);
1749 PERL_STATIC_INLINE void
1750 S_gv_magicalize_isa(pTHX_ GV *gv)
1754 PERL_ARGS_ASSERT_GV_MAGICALIZE_ISA;
1758 sv_magic(MUTABLE_SV(av), MUTABLE_SV(gv), PERL_MAGIC_isa,
1761 if(HvSTASH_IS_CLASS(GvSTASH(gv))) {
1762 /* Don't permit modification of @ISA outside of the class management
1763 * code. This is temporarily undone by class.c when fiddling with the
1764 * array, so it knows it can be done safely.
1766 SvREADONLY_on((SV *)av);
1770 /* This function grabs name and tries to split a stash and glob
1771 * from its contents. TODO better description, comments
1773 * If the function returns TRUE and 'name == name_end', then
1774 * 'gv' can be directly returned to the caller of gv_fetchpvn_flags
1776 PERL_STATIC_INLINE bool
1777 S_parse_gv_stash_name(pTHX_ HV **stash, GV **gv, const char **name,
1778 STRLEN *len, const char *nambeg, STRLEN full_len,
1779 const U32 is_utf8, const I32 add)
1781 char *tmpfullbuf = NULL; /* only malloc one big chunk of memory when the smallbuff is not large enough */
1782 const char *name_cursor;
1783 const char *const name_end = nambeg + full_len;
1784 const char *const name_em1 = name_end - 1;
1785 char smallbuf[64]; /* small buffer to avoid a malloc when possible */
1787 PERL_ARGS_ASSERT_PARSE_GV_STASH_NAME;
1791 && isIDFIRST_lazy_if_safe(*name + 1, name_end, is_utf8))
1793 /* accidental stringify on a GV? */
1797 for (name_cursor = *name; name_cursor < name_end; name_cursor++) {
1798 if (name_cursor < name_em1 &&
1799 ((*name_cursor == ':' && name_cursor[1] == ':')
1800 || *name_cursor == '\''))
1803 *stash = PL_defstash;
1804 if (!*stash || !SvREFCNT(*stash)) /* symbol table under destruction */
1807 *len = name_cursor - *name;
1808 if (name_cursor > nambeg) { /* Skip for initial :: or ' */
1811 if (*name_cursor == ':') {
1815 else { /* using ' for package separator */
1816 /* use our pre-allocated buffer when possible to save a malloc */
1818 if ( *len+2 <= sizeof smallbuf)
1821 /* only malloc once if needed */
1822 if (tmpfullbuf == NULL) /* only malloc&free once, a little more than needed */
1823 Newx(tmpfullbuf, full_len+2, char);
1824 tmpbuf = tmpfullbuf;
1826 Copy(*name, tmpbuf, *len, char);
1827 tmpbuf[(*len)++] = ':';
1828 tmpbuf[(*len)++] = ':';
1831 gvp = (GV**)hv_fetch(*stash, key, is_utf8 ? -((I32)*len) : (I32)*len, add);
1832 *gv = gvp ? *gvp : NULL;
1833 if (!*gv || *gv == (const GV *)&PL_sv_undef) {
1836 /* here we know that *gv && *gv != &PL_sv_undef */
1837 if (SvTYPE(*gv) != SVt_PVGV)
1838 gv_init_pvn(*gv, *stash, key, *len, (add & GV_ADDMULTI)|is_utf8);
1842 if (!(*stash = GvHV(*gv))) {
1843 *stash = GvHV(*gv) = newHV();
1844 if (!HvHasNAME(*stash)) {
1845 if (GvSTASH(*gv) == PL_defstash && *len == 6
1846 && strBEGINs(*name, "CORE"))
1847 hv_name_sets(*stash, "CORE", 0);
1850 *stash, nambeg, name_cursor-nambeg, is_utf8
1852 /* If the containing stash has multiple effective
1853 names, see that this one gets them, too. */
1854 if (HvAUX(GvSTASH(*gv))->xhv_name_count)
1855 mro_package_moved(*stash, NULL, *gv, 1);
1858 else if (!HvHasNAME(*stash))
1859 hv_name_set(*stash, nambeg, name_cursor - nambeg, is_utf8);
1862 if (*name_cursor == ':')
1864 *name = name_cursor+1;
1865 if (*name == name_end) {
1867 *gv = MUTABLE_GV(*hv_fetchs(PL_defstash, "main::", TRUE));
1868 if (SvTYPE(*gv) != SVt_PVGV) {
1869 gv_init_pvn(*gv, PL_defstash, "main::", 6,
1872 MUTABLE_HV(SvREFCNT_inc_simple(PL_defstash));
1879 *len = name_cursor - *name;
1881 Safefree(tmpfullbuf); /* free our tmpfullbuf if it was used */
1884 Safefree(tmpfullbuf); /* free our tmpfullbuf if it was used */
1889 /* Checks if an unqualified name is in the main stash */
1890 PERL_STATIC_INLINE bool
1891 S_gv_is_in_main(pTHX_ const char *name, STRLEN len, const U32 is_utf8)
1893 PERL_ARGS_ASSERT_GV_IS_IN_MAIN;
1895 /* If it's an alphanumeric variable */
1896 if ( len && isIDFIRST_lazy_if_safe(name, name + len, is_utf8) ) {
1897 /* Some "normal" variables are always in main::,
1898 * like INC or STDOUT.
1906 if ((name[0] == 'I' && name[1] == 'N' && name[2] == 'C')
1907 || (name[0] == 'E' && name[1] == 'N' && name[2] == 'V')
1908 || (name[0] == 'S' && name[1] == 'I' && name[2] == 'G'))
1912 if (name[0] == 'A' && name[1] == 'R' && name[2] == 'G'
1917 if (name[0] == 'S' && name[1] == 'T' && name[2] == 'D'
1918 && name[3] == 'I' && name[4] == 'N')
1922 if ((name[0] == 'S' && name[1] == 'T' && name[2] == 'D')
1923 &&((name[3] == 'O' && name[4] == 'U' && name[5] == 'T')
1924 ||(name[3] == 'E' && name[4] == 'R' && name[5] == 'R')))
1928 if (name[0] == 'A' && name[1] == 'R' && name[2] == 'G'
1929 && name[3] == 'V' && name[4] == 'O' && name[5] == 'U'
1935 /* *{""}, or a special variable like $@ */
1943 /* This function is called if parse_gv_stash_name() failed to
1944 * find a stash, or if GV_NOTQUAL or an empty name was passed
1945 * to gv_fetchpvn_flags.
1947 * It returns FALSE if the default stash can't be found nor created,
1948 * which might happen during global destruction.
1950 PERL_STATIC_INLINE bool
1951 S_find_default_stash(pTHX_ HV **stash, const char *name, STRLEN len,
1952 const U32 is_utf8, const I32 add,
1953 const svtype sv_type)
1955 PERL_ARGS_ASSERT_FIND_DEFAULT_STASH;
1957 /* No stash in name, so see how we can default */
1959 if ( gv_is_in_main(name, len, is_utf8) ) {
1960 *stash = PL_defstash;
1963 if (IN_PERL_COMPILETIME) {
1964 *stash = PL_curstash;
1965 if (add && (PL_hints & HINT_STRICT_VARS) &&
1966 sv_type != SVt_PVCV &&
1967 sv_type != SVt_PVGV &&
1968 sv_type != SVt_PVFM &&
1969 sv_type != SVt_PVIO &&
1970 !(len == 1 && sv_type == SVt_PV &&
1971 (*name == 'a' || *name == 'b')) )
1973 GV**gvp = (GV**)hv_fetch(*stash,name,is_utf8 ? -(I32)len : (I32)len,0);
1974 if (!gvp || *gvp == (const GV *)&PL_sv_undef ||
1975 SvTYPE(*gvp) != SVt_PVGV)
1979 else if ((sv_type == SVt_PV && !GvIMPORTED_SV(*gvp)) ||
1980 (sv_type == SVt_PVAV && !GvIMPORTED_AV(*gvp)) ||
1981 (sv_type == SVt_PVHV && !GvIMPORTED_HV(*gvp)) )
1983 /* diag_listed_as: Variable "%s" is not imported%s */
1985 aTHX_ packWARN(WARN_MISC),
1986 "Variable \"%c%" UTF8f "\" is not imported",
1987 sv_type == SVt_PVAV ? '@' :
1988 sv_type == SVt_PVHV ? '%' : '$',
1989 UTF8fARG(is_utf8, len, name));
1992 aTHX_ packWARN(WARN_MISC),
1993 "\t(Did you mean &%" UTF8f " instead?)\n",
1994 UTF8fARG(is_utf8, len, name)
2001 /* Use the current op's stash */
2002 *stash = CopSTASH(PL_curcop);
2007 if (add && !PL_in_clean_all) {
2009 qerror(Perl_mess(aTHX_
2010 "Global symbol \"%s%" UTF8f
2011 "\" requires explicit package name (did you forget to "
2012 "declare \"my %s%" UTF8f "\"?)",
2013 (sv_type == SVt_PV ? "$"
2014 : sv_type == SVt_PVAV ? "@"
2015 : sv_type == SVt_PVHV ? "%"
2016 : ""), UTF8fARG(is_utf8, len, name),
2017 (sv_type == SVt_PV ? "$"
2018 : sv_type == SVt_PVAV ? "@"
2019 : sv_type == SVt_PVHV ? "%"
2020 : ""), UTF8fARG(is_utf8, len, name)));
2021 /* To maintain the output of errors after the strict exception
2022 * above, and to keep compat with older releases, rather than
2023 * placing the variables in the pad, we place
2024 * them in the <none>:: stash.
2026 gv = gv_fetchpvs("<none>::", GV_ADDMULTI, SVt_PVHV);
2028 /* symbol table under destruction */
2037 if (!SvREFCNT(*stash)) /* symbol table under destruction */
2043 /* gv_magicalize only turns on the SVf_READONLY flag, not SVf_PROTECT. So
2044 redefine SvREADONLY_on for that purpose. We don’t use it later on in
2046 #undef SvREADONLY_on
2047 #define SvREADONLY_on(sv) (SvFLAGS(sv) |= SVf_READONLY)
2049 /* gv_magicalize() is called by gv_fetchpvn_flags when creating
2051 * Note that it does not insert the GV into the stash prior to
2052 * magicalization, which some variables require need in order
2053 * to work (like %+, %-, %!), so callers must take care of
2056 * It returns true if the gv did turn out to be magical one; i.e.,
2057 * if gv_magicalize actually did something.
2059 PERL_STATIC_INLINE bool
2060 S_gv_magicalize(pTHX_ GV *gv, HV *stash, const char *name, STRLEN len,
2061 const svtype sv_type)
2065 PERL_ARGS_ASSERT_GV_MAGICALIZE;
2067 if (stash != PL_defstash) { /* not the main stash */
2068 /* We only have to check for a few names here: a, b, EXPORT, ISA
2069 and VERSION. All the others apply only to the main stash or to
2070 CORE (which is checked right after this). */
2075 len >= 6 && name[1] == 'X' &&
2076 (memEQs(name, len, "EXPORT")
2077 ||memEQs(name, len, "EXPORT_OK")
2078 ||memEQs(name, len, "EXPORT_FAIL")
2079 ||memEQs(name, len, "EXPORT_TAGS"))
2084 if (memEQs(name, len, "ISA"))
2085 gv_magicalize_isa(gv);
2088 if (memEQs(name, len, "VERSION"))
2092 if (stash == PL_debstash && memEQs(name, len, "args")) {
2093 GvMULTI_on(gv_AVadd(gv));
2098 if (len == 1 && sv_type == SVt_PV)
2107 if (len > 1 /* shortest is uc */ && HvNAMELEN_get(stash) == 4) {
2108 /* Avoid null warning: */
2109 const char * const stashname = HvNAME(stash); assert(stashname);
2110 if (strBEGINs(stashname, "CORE"))
2111 S_maybe_add_coresub(aTHX_ 0, gv, name, len);
2118 /* Nothing else to do.
2119 The compiler will probably turn the switch statement into a
2120 branch table. Make sure we avoid even that small overhead for
2121 the common case of lower case variable names. (On EBCDIC
2122 platforms, we can't just do:
2123 if (NATIVE_TO_ASCII(*name) > NATIVE_TO_ASCII('V') ) {
2124 because cases like '\027' in the switch statement below are
2125 C1 (non-ASCII) controls on those platforms, so the remapping
2126 would make them larger than 'V')
2133 if (memEQs(name, len, "ARGV")) {
2134 IoFLAGS(GvIOn(gv)) |= IOf_ARGV|IOf_START;
2136 else if (memEQs(name, len, "ARGVOUT")) {
2142 len >= 6 && name[1] == 'X' &&
2143 (memEQs(name, len, "EXPORT")
2144 ||memEQs(name, len, "EXPORT_OK")
2145 ||memEQs(name, len, "EXPORT_FAIL")
2146 ||memEQs(name, len, "EXPORT_TAGS"))
2151 if (memEQs(name, len, "ISA")) {
2152 gv_magicalize_isa(gv);
2156 if (memEQs(name, len, "SIG")) {
2159 if (!PL_psig_name) {
2160 Newxz(PL_psig_name, 2 * SIG_SIZE, SV*);
2161 Newxz(PL_psig_pend, SIG_SIZE, int);
2162 PL_psig_ptr = PL_psig_name + SIG_SIZE;
2164 /* I think that the only way to get here is to re-use an
2165 embedded perl interpreter, where the previous
2166 use didn't clean up fully because
2167 PL_perl_destruct_level was 0. I'm not sure that we
2168 "support" that, in that I suspect in that scenario
2169 there are sufficient other garbage values left in the
2170 interpreter structure that something else will crash
2171 before we get here. I suspect that this is one of
2172 those "doctor, it hurts when I do this" bugs. */
2173 Zero(PL_psig_name, 2 * SIG_SIZE, SV*);
2174 Zero(PL_psig_pend, SIG_SIZE, int);
2178 hv_magic(hv, NULL, PERL_MAGIC_sig);
2179 for (i = 1; i < SIG_SIZE; i++) {
2180 SV * const * const init = hv_fetch(hv, PL_sig_name[i], strlen(PL_sig_name[i]), 1);
2182 sv_setsv(*init, &PL_sv_undef);
2187 if (memEQs(name, len, "VERSION"))
2190 case '\003': /* $^CHILD_ERROR_NATIVE */
2191 if (memEQs(name, len, "\003HILD_ERROR_NATIVE"))
2193 /* @{^CAPTURE} %{^CAPTURE} */
2194 if (memEQs(name, len, "\003APTURE")) {
2195 AV* const av = GvAVn(gv);
2196 const Size_t n = *name;
2198 sv_magic(MUTABLE_SV(av), (SV*)n, PERL_MAGIC_regdata, NULL, 0);
2201 require_tie_mod_s(gv, '+', "Tie::Hash::NamedCapture",0);
2203 } else /* %{^CAPTURE_ALL} */
2204 if (memEQs(name, len, "\003APTURE_ALL")) {
2205 require_tie_mod_s(gv, '-', "Tie::Hash::NamedCapture",0);
2208 case '\005': /* ${^ENCODING} */
2209 if (memEQs(name, len, "\005NCODING"))
2212 case '\007': /* ${^GLOBAL_PHASE} */
2213 if (memEQs(name, len, "\007LOBAL_PHASE"))
2216 case '\010': /* %{^HOOK} */
2217 if (memEQs(name, len, "\010OOK")) {
2220 hv_magic(hv, NULL, PERL_MAGIC_hook);
2224 if ( memEQs(name, len, "\014AST_FH") || /* ${^LAST_FH} */
2225 memEQs(name, len, "\014AST_SUCCESSFUL_PATTERN")) /* ${^LAST_SUCCESSFUL_PATTERN} */
2228 case '\015': /* ${^MATCH} */
2229 if (memEQs(name, len, "\015ATCH")) {
2230 paren = RX_BUFF_IDX_CARET_FULLMATCH;
2234 case '\017': /* ${^OPEN} */
2235 if (memEQs(name, len, "\017PEN"))
2238 case '\020': /* ${^PREMATCH} ${^POSTMATCH} */
2239 if (memEQs(name, len, "\020REMATCH")) {
2240 paren = RX_BUFF_IDX_CARET_PREMATCH;
2243 if (memEQs(name, len, "\020OSTMATCH")) {
2244 paren = RX_BUFF_IDX_CARET_POSTMATCH;
2249 if (memEQs(name, len, "\023AFE_LOCALES"))
2252 case '\024': /* ${^TAINT} */
2253 if (memEQs(name, len, "\024AINT"))
2256 case '\025': /* ${^UNICODE}, ${^UTF8LOCALE} */
2257 if (memEQs(name, len, "\025NICODE"))
2259 if (memEQs(name, len, "\025TF8LOCALE"))
2261 if (memEQs(name, len, "\025TF8CACHE"))
2264 case '\027': /* $^WARNING_BITS */
2265 if (memEQs(name, len, "\027ARNING_BITS"))
2268 else if (memEQs(name, len, "\027IN32_SLOPPY_STAT"))
2282 /* Ensures that we have an all-digit variable, ${"1foo"} fails
2285 if (!grok_atoUV(name, &uv, NULL) || uv > I32_MAX)
2287 /* XXX why are we using a SSize_t? */
2288 paren = (SSize_t)(I32)uv;
2294 /* Names of length 1. (Or 0. But name is NUL terminated, so that will
2295 be case '\0' in this switch statement (ie a default case) */
2298 paren = RX_BUFF_IDX_FULLMATCH;
2301 paren = RX_BUFF_IDX_PREMATCH;
2304 paren = RX_BUFF_IDX_POSTMATCH;
2306 #ifdef PERL_SAWAMPERSAND
2308 sv_type == SVt_PVAV ||
2309 sv_type == SVt_PVHV ||
2310 sv_type == SVt_PVCV ||
2311 sv_type == SVt_PVFM ||
2313 )) { PL_sawampersand |=
2317 ? SAWAMPERSAND_MIDDLE
2318 : SAWAMPERSAND_RIGHT;
2331 paren = *name - '0';
2334 /* Flag the capture variables with a NULL mg_ptr
2335 Use mg_len for the array index to lookup. */
2336 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, NULL, paren);
2340 sv_setpv(GvSVn(gv),PL_chopset);
2344 #ifdef COMPLEX_STATUS
2345 SvUPGRADE(GvSVn(gv), SVt_PVLV);
2351 /* If %! has been used, automatically load Errno.pm. */
2353 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, name, len);
2355 /* magicalization must be done before require_tie_mod_s is called */
2356 if (sv_type == SVt_PVHV || sv_type == SVt_PVGV)
2357 require_tie_mod_s(gv, '!', "Errno", 1);
2360 case '-': /* $-, %-, @- */
2361 case '+': /* $+, %+, @+ */
2362 GvMULTI_on(gv); /* no used once warnings here */
2364 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, name, len);
2366 SvREADONLY_on(GvSVn(gv));
2369 if (sv_type == SVt_PVHV || sv_type == SVt_PVGV)
2370 require_tie_mod_s(gv, *name, "Tie::Hash::NamedCapture",0);
2373 AV* const av = GvAVn(gv);
2374 const Size_t n = *name;
2376 sv_magic(MUTABLE_SV(av), (SV*)n, PERL_MAGIC_regdata, NULL, 0);
2382 if (sv_type == SVt_PV)
2383 /* diag_listed_as: $* is no longer supported as of Perl 5.30 */
2384 Perl_croak(aTHX_ "$%c is no longer supported as of Perl 5.30", *name);
2386 case '\010': /* $^H */
2388 HV *const hv = GvHVn(gv);
2389 hv_magic(hv, NULL, PERL_MAGIC_hints);
2392 case '\023': /* $^S */
2394 SvREADONLY_on(GvSVn(gv));
2411 case '\001': /* $^A */
2412 case '\003': /* $^C */
2413 case '\004': /* $^D */
2414 case '\005': /* $^E */
2415 case '\006': /* $^F */
2416 case '\011': /* $^I, NOT \t in EBCDIC */
2417 case '\016': /* $^N */
2418 case '\017': /* $^O */
2419 case '\020': /* $^P */
2420 case '\024': /* $^T */
2421 case '\027': /* $^W */
2423 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, name, len);
2426 case '\014': /* $^L */
2427 sv_setpvs(GvSVn(gv),"\f");
2430 sv_setpvs(GvSVn(gv),"\034");
2434 SV * const sv = GvSV(gv);
2435 if (!sv_derived_from(PL_patchlevel, "version"))
2436 upg_version(PL_patchlevel, TRUE);
2437 GvSV(gv) = vnumify(PL_patchlevel);
2438 SvREADONLY_on(GvSV(gv));
2442 case '\026': /* $^V */
2444 SV * const sv = GvSV(gv);
2445 GvSV(gv) = new_version(PL_patchlevel);
2446 SvREADONLY_on(GvSV(gv));
2452 if (sv_type == SVt_PV)
2458 /* Return true if we actually did something. */
2459 return GvAV(gv) || GvHV(gv) || GvIO(gv) || GvCV(gv)
2461 SvOK(GvSV(gv)) || SvMAGICAL(GvSV(gv))
2466 /* If we do ever start using this later on in the file, we need to make
2467 sure we don’t accidentally use the wrong definition. */
2468 #undef SvREADONLY_on
2470 /* This function is called when the stash already holds the GV of the magic
2471 * variable we're looking for, but we need to check that it has the correct
2472 * kind of magic. For example, if someone first uses $! and then %!, the
2473 * latter would end up here, and we add the Errno tie to the HASH slot of
2476 PERL_STATIC_INLINE void
2477 S_maybe_multimagic_gv(pTHX_ GV *gv, const char *name, const svtype sv_type)
2479 PERL_ARGS_ASSERT_MAYBE_MULTIMAGIC_GV;
2481 if (sv_type == SVt_PVHV || sv_type == SVt_PVGV) {
2483 require_tie_mod_s(gv, '!', "Errno", 1);
2484 else if (*name == '-' || *name == '+')
2485 require_tie_mod_s(gv, *name, "Tie::Hash::NamedCapture", 0);
2486 } else if (sv_type == SVt_PV) {
2487 if (*name == '*' || *name == '#') {
2488 /* diag_listed_as: $* is no longer supported as of Perl 5.30 */
2489 Perl_croak(aTHX_ "$%c is no longer supported as of Perl 5.30", *name);
2492 if (sv_type==SVt_PV || sv_type==SVt_PVGV) {
2494 #ifdef PERL_SAWAMPERSAND
2496 PL_sawampersand |= SAWAMPERSAND_LEFT;
2500 PL_sawampersand |= SAWAMPERSAND_MIDDLE;
2504 PL_sawampersand |= SAWAMPERSAND_RIGHT;
2513 =for apidoc gv_fetchpv
2514 =for apidoc_item |GV *|gv_fetchpvn|const char * nambeg|STRLEN full_len|I32 flags|const svtype sv_type
2515 =for apidoc_item ||gv_fetchpvn_flags
2516 =for apidoc_item |GV *|gv_fetchpvs|"name"|I32 flags|const svtype sv_type
2517 =for apidoc_item ||gv_fetchsv
2518 =for apidoc_item |GV *|gv_fetchsv_nomg|SV *name|I32 flags|const svtype sv_type
2520 These all return the GV of type C<sv_type> whose name is given by the inputs,
2521 or NULL if no GV of that name and type could be found. See L<perlguts/Stashes
2524 The only differences are how the input name is specified, and if 'get' magic is
2525 normally used in getting that name.
2527 Don't be fooled by the fact that only one form has C<flags> in its name. They
2528 all have a C<flags> parameter in fact, and all the flag bits have the same
2531 If any of the flags C<GV_ADD>, C<GV_ADDMG>, C<GV_ADDWARN>, C<GV_ADDMULTI>, or
2532 C<GV_NOINIT> is set, a GV is created if none already exists for the input name
2533 and type. However, C<GV_ADDMG> will only do the creation for magical GV's.
2534 For all of these flags except C<GV_NOINIT>, C<L</gv_init_pvn>> is called after
2535 the addition. C<GV_ADDWARN> is used when the caller expects that adding won't
2536 be necessary because the symbol should already exist; but if not, add it
2537 anyway, with a warning that it was unexpectedly absent. The C<GV_ADDMULTI>
2538 flag means to pretend that the GV has been seen before (I<i.e.>, suppress "Used
2541 The flag C<GV_NOADD_NOINIT> causes C<L</gv_init_pvn>> not be to called if the
2542 GV existed but isn't PVGV.
2544 If the C<SVf_UTF8> bit is set, the name is treated as being encoded in UTF-8;
2545 otherwise the name won't be considered to be UTF-8 in the C<pv>-named forms,
2546 and the UTF-8ness of the underlying SVs will be used in the C<sv> forms.
2548 If the flag C<GV_NOTQUAL> is set, the caller warrants that the input name is a
2549 plain symbol name, not qualified with a package, otherwise the name is checked
2550 for being a qualified one.
2552 In C<gv_fetchpv>, C<nambeg> is a C string, NUL-terminated with no intermediate
2555 In C<gv_fetchpvs>, C<name> is a literal C string, hence is enclosed in
2558 C<gv_fetchpvn> and C<gv_fetchpvn_flags> are identical. In these, <nambeg> is
2559 a Perl string whose byte length is given by C<full_len>, and may contain
2562 In C<gv_fetchsv> and C<gv_fetchsv_nomg>, the name is extracted from the PV of
2563 the input C<name> SV. The only difference between these two forms is that
2564 'get' magic is normally done on C<name> in C<gv_fetchsv>, and always skipped
2565 with C<gv_fetchsv_nomg>. Including C<GV_NO_SVGMAGIC> in the C<flags> parameter
2566 to C<gv_fetchsv> makes it behave identically to C<gv_fetchsv_nomg>.
2568 =for apidoc Amnh||GV_ADD
2569 =for apidoc Amnh||GV_ADDMG
2570 =for apidoc Amnh||GV_ADDMULTI
2571 =for apidoc Amnh||GV_ADDWARN
2572 =for apidoc Amnh||GV_NOINIT
2573 =for apidoc Amnh||GV_NOADD_NOINIT
2574 =for apidoc Amnh||GV_NOTQUAL
2575 =for apidoc Amnh||GV_NO_SVGMAGIC
2576 =for apidoc Amnh||SVf_UTF8
2582 Perl_gv_fetchpvn_flags(pTHX_ const char *nambeg, STRLEN full_len, I32 flags,
2583 const svtype sv_type)
2585 const char *name = nambeg;
2590 const I32 no_init = flags & (GV_NOADD_NOINIT | GV_NOINIT);
2591 const I32 no_expand = flags & GV_NOEXPAND;
2592 const I32 add = flags & ~GV_NOADD_MASK;
2593 const U32 is_utf8 = flags & SVf_UTF8;
2594 bool addmg = cBOOL(flags & GV_ADDMG);
2595 const char *const name_end = nambeg + full_len;
2598 PERL_ARGS_ASSERT_GV_FETCHPVN_FLAGS;
2600 /* If we have GV_NOTQUAL, the caller promised that
2601 * there is no stash, so we can skip the check.
2602 * Similarly if full_len is 0, since then we're
2603 * dealing with something like *{""} or ""->foo()
2605 if ((flags & GV_NOTQUAL) || !full_len) {
2608 else if (parse_gv_stash_name(&stash, &gv, &name, &len, nambeg, full_len, is_utf8, add)) {
2609 if (name == name_end) return gv;
2615 if (!stash && !find_default_stash(&stash, name, len, is_utf8, add, sv_type)) {
2619 /* By this point we should have a stash and a name */
2620 gvp = (GV**)hv_fetch(stash,name,is_utf8 ? -(I32)len : (I32)len,add);
2621 if (!gvp || *gvp == (const GV *)&PL_sv_undef) {
2622 if (addmg) gv = (GV *)newSV_type(SVt_NULL); /* tentatively */
2625 else gv = *gvp, addmg = 0;
2626 /* From this point on, addmg means gv has not been inserted in the
2629 if (SvTYPE(gv) == SVt_PVGV) {
2630 /* The GV already exists, so return it, but check if we need to do
2631 * anything else with it before that.
2634 /* This is the heuristic that handles if a variable triggers the
2635 * 'used only once' warning. If there's already a GV in the stash
2636 * with this name, then we assume that the variable has been used
2637 * before and turn its MULTI flag on.
2638 * It's a heuristic because it can easily be "tricked", like with
2639 * BEGIN { $a = 1; $::{foo} = *a }; () = $foo
2640 * not warning about $main::foo being used just once
2643 gv_init_svtype(gv, sv_type);
2644 /* You reach this path once the typeglob has already been created,
2645 either by the same or a different sigil. If this path didn't
2646 exist, then (say) referencing $! first, and %! second would
2647 mean that %! was not handled correctly. */
2648 if (len == 1 && stash == PL_defstash) {
2649 maybe_multimagic_gv(gv, name, sv_type);
2651 else if (sv_type == SVt_PVAV
2652 && memEQs(name, len, "ISA")
2653 && (!GvAV(gv) || !SvSMAGICAL(GvAV(gv))))
2654 gv_magicalize_isa(gv);
2657 } else if (no_init) {
2661 /* If GV_NOEXPAND is true and what we got off the stash is a ref,
2662 * don't expand it to a glob. This is an optimization so that things
2663 * copying constants over, like Exporter, don't have to be rewritten
2664 * to take into account that you can store more than just globs in
2667 else if (no_expand && SvROK(gv)) {
2672 /* Adding a new symbol.
2673 Unless of course there was already something non-GV here, in which case
2674 we want to behave as if there was always a GV here, containing some sort
2676 Otherwise we run the risk of creating things like GvIO, which can cause
2677 subtle bugs. eg the one that tripped up SQL::Translator */
2679 faking_it = SvOK(gv);
2681 if (add & GV_ADDWARN)
2682 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2683 "Had to create %" UTF8f " unexpectedly",
2684 UTF8fARG(is_utf8, name_end-nambeg, nambeg));
2685 gv_init_pvn(gv, stash, name, len, (add & GV_ADDMULTI)|is_utf8);
2688 && isIDFIRST_lazy_if_safe(name, name + full_len, is_utf8)
2689 && !ckWARN(WARN_ONCE) )
2694 /* set up magic where warranted */
2695 if ( gv_magicalize(gv, stash, name, len, sv_type) ) {
2698 /* gv_magicalize magicalised this gv, so we want it
2699 * stored in the symtab.
2700 * Effectively the caller is asking, ‘Does this gv exist?’
2701 * And we respond, ‘Er, *now* it does!’
2703 (void)hv_store(stash,name,len,(SV *)gv,0);
2707 /* The temporary GV created above */
2708 SvREFCNT_dec_NN(gv);
2712 if (gv) gv_init_svtype(gv, faking_it ? SVt_PVCV : sv_type);
2717 =for apidoc gv_efullname3
2718 =for apidoc_item gv_efullname4
2719 =for apidoc_item gv_fullname3
2720 =for apidoc_item gv_fullname4
2722 Place the full package name of C<gv> into C<sv>. The C<gv_e*> forms return
2723 instead the effective package name (see L</HvENAME>).
2725 If C<prefix> is non-NULL, it is considered to be a C language NUL-terminated
2726 string, and the stored name will be prefaced with it.
2728 The other difference between the functions is that the C<*4> forms have an
2729 extra parameter, C<keepmain>. If C<true> an initial C<main::> in the name is
2730 kept; if C<false> it is stripped. With the C<*3> forms, it is always kept.
2736 Perl_gv_fullname4(pTHX_ SV *sv, const GV *gv, const char *prefix, bool keepmain)
2739 const HV * const hv = GvSTASH(gv);
2741 PERL_ARGS_ASSERT_GV_FULLNAME4;
2743 sv_setpv(sv, prefix ? prefix : "");
2745 if (hv && (name = HvNAME(hv))) {
2746 const STRLEN len = HvNAMELEN(hv);
2747 if (keepmain || ! memBEGINs(name, len, "main")) {
2748 sv_catpvn_flags(sv,name,len,HvNAMEUTF8(hv)?SV_CATUTF8:SV_CATBYTES);
2752 else sv_catpvs(sv,"__ANON__::");
2753 sv_catsv(sv,newSVhek_mortal(GvNAME_HEK(gv)));
2757 Perl_gv_efullname4(pTHX_ SV *sv, const GV *gv, const char *prefix, bool keepmain)
2759 const GV * const egv = GvEGVx(gv);
2761 PERL_ARGS_ASSERT_GV_EFULLNAME4;
2763 gv_fullname4(sv, egv ? egv : gv, prefix, keepmain);
2767 /* recursively scan a stash and any nested stashes looking for entries
2768 * that need the "only used once" warning raised
2772 Perl_gv_check(pTHX_ HV *stash)
2776 PERL_ARGS_ASSERT_GV_CHECK;
2778 if (!HvHasAUX(stash))
2781 assert(HvARRAY(stash));
2783 /* mark stash is being scanned, to avoid recursing */
2784 HvAUX(stash)->xhv_aux_flags |= HvAUXf_SCAN_STASH;
2785 for (i = 0; i <= (I32) HvMAX(stash); i++) {
2787 for (entry = HvARRAY(stash)[i]; entry; entry = HeNEXT(entry)) {
2790 STRLEN keylen = HeKLEN(entry);
2791 const char * const key = HeKEY(entry);
2793 if (keylen >= 2 && key[keylen-2] == ':' && key[keylen-1] == ':' &&
2794 (gv = MUTABLE_GV(HeVAL(entry))) && isGV(gv) && (hv = GvHV(gv)))
2796 if (hv != PL_defstash && hv != stash
2798 && (HvAUX(hv)->xhv_aux_flags & HvAUXf_SCAN_STASH))
2800 gv_check(hv); /* nested package */
2802 else if ( HeKLEN(entry) != 0
2803 && *HeKEY(entry) != '_'
2804 && isIDFIRST_lazy_if_safe(HeKEY(entry),
2805 HeKEY(entry) + HeKLEN(entry),
2809 gv = MUTABLE_GV(HeVAL(entry));
2810 if (SvTYPE(gv) != SVt_PVGV || GvMULTI(gv))
2813 assert(PL_curcop == &PL_compiling);
2814 CopLINE_set(PL_curcop, GvLINE(gv));
2816 SAVECOPFILE_FREE(PL_curcop);
2817 CopFILE_set(PL_curcop, (char *)file); /* set for warning */
2819 CopFILEGV(PL_curcop)
2820 = gv_fetchfile_flags(file, HEK_LEN(GvFILE_HEK(gv)), 0);
2822 Perl_warner(aTHX_ packWARN(WARN_ONCE),
2823 "Name \"%" HEKf "::%" HEKf
2824 "\" used only once: possible typo",
2825 HEKfARG(HvNAME_HEK(stash)),
2826 HEKfARG(GvNAME_HEK(gv)));
2830 HvAUX(stash)->xhv_aux_flags &= ~HvAUXf_SCAN_STASH;
2834 =for apidoc newGVgen
2835 =for apidoc_item newGVgen_flags
2837 Create a new, guaranteed to be unique, GV in the package given by the
2838 NUL-terminated C language string C<pack>, and return a pointer to it.
2840 For C<newGVgen> or if C<flags> in C<newGVgen_flags> is 0, C<pack> is to be
2841 considered to be encoded in Latin-1. The only other legal C<flags> value is
2842 C<SVf_UTF8>, which indicates C<pack> is to be considered to be encoded in
2849 Perl_newGVgen_flags(pTHX_ const char *pack, U32 flags)
2851 PERL_ARGS_ASSERT_NEWGVGEN_FLAGS;
2852 assert(!(flags & ~SVf_UTF8));
2854 return gv_fetchpv(Perl_form(aTHX_ "%" UTF8f "::_GEN_%ld",
2855 UTF8fARG(flags, strlen(pack), pack),
2860 /* hopefully this is only called on local symbol table entries */
2863 Perl_gp_ref(pTHX_ GP *gp)
2870 /* If the GP they asked for a reference to contains
2871 a method cache entry, clear it first, so that we
2872 don't infect them with our cached entry */
2873 SvREFCNT_dec_NN(gp->gp_cv);
2882 Perl_gp_free(pTHX_ GV *gv)
2886 bool in_global_destruction = PL_phase == PERL_PHASE_DESTRUCT;
2888 if (!gv || !isGV_with_GP(gv) || !(gp = GvGP(gv)))
2890 if (gp->gp_refcnt == 0) {
2891 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2892 "Attempt to free unreferenced glob pointers"
2893 pTHX__FORMAT pTHX__VALUE);
2896 if (gp->gp_refcnt > 1) {
2898 if (gp->gp_egv == gv)
2906 /* Copy and null out all the glob slots, so destructors do not see
2908 HEK * const file_hek = gp->gp_file_hek;
2909 SV * sv = gp->gp_sv;
2910 AV * av = gp->gp_av;
2911 HV * hv = gp->gp_hv;
2912 IO * io = gp->gp_io;
2913 CV * cv = gp->gp_cv;
2914 CV * form = gp->gp_form;
2918 gp->gp_file_hek = NULL;
2927 unshare_hek(file_hek);
2929 /* Storing the SV on the temps stack (instead of freeing it immediately)
2930 is an admitted bodge that attempt to compensate for the lack of
2931 reference counting on the stack. The motivation is that typeglob syntax
2932 is extremely short hence programs such as '$a += (*a = 2)' are often
2933 found randomly by researchers running fuzzers. Previously these
2934 programs would trigger errors, that the researchers would
2935 (legitimately) report, and then we would spend time figuring out that
2936 the cause was "stack not reference counted" and so not a dangerous
2937 security hole. This consumed a lot of researcher time, our time, and
2938 prevents "interesting" security holes being uncovered.
2940 Typeglob assignment is rarely used in performance critical production
2941 code, so we aren't causing much slowdown by doing extra work here.
2943 In turn, the need to check for SvOBJECT (and references to objects) is
2944 because we have regression tests that rely on timely destruction that
2945 happens *within this while loop* to demonstrate behaviour, and
2946 potentially there is also *working* code in the wild that relies on
2949 And we need to avoid doing this in global destruction else we can end
2950 up with "Attempt to free temp prematurely ... Unbalanced string table
2953 Hence the whole thing is a heuristic intended to mitigate against
2954 simple problems likely found by fuzzers but never written by humans,
2955 whilst leaving working code unchanged. */
2958 if (SvREFCNT(sv) > 1 || SvOBJECT(sv) || UNLIKELY(in_global_destruction)) {
2959 SvREFCNT_dec_NN(sv);
2961 } else if (SvROK(sv) && (referent = SvRV(sv))
2962 && (SvREFCNT(referent) > 1 || SvOBJECT(referent))) {
2963 SvREFCNT_dec_NN(sv);
2970 if (SvREFCNT(av) > 1 || SvOBJECT(av) || UNLIKELY(in_global_destruction)) {
2971 SvREFCNT_dec_NN(av);
2977 /* FIXME - another reference loop GV -> symtab -> GV ?
2978 Somehow gp->gp_hv can end up pointing at freed garbage. */
2979 if (hv && SvTYPE(hv) == SVt_PVHV) {
2980 const HEK *hvname_hek = HvNAME_HEK(hv);
2981 if (PL_stashcache && hvname_hek) {
2982 DEBUG_o(Perl_deb(aTHX_
2983 "gp_free clearing PL_stashcache for '%" HEKf "'\n",
2984 HEKfARG(hvname_hek)));
2985 (void)hv_deletehek(PL_stashcache, hvname_hek, G_DISCARD);
2987 if (SvREFCNT(hv) > 1 || SvOBJECT(hv) || UNLIKELY(in_global_destruction)) {
2988 SvREFCNT_dec_NN(hv);
2994 if (io && SvREFCNT(io) == 1 && IoIFP(io)
2995 && (IoTYPE(io) == IoTYPE_WRONLY ||
2996 IoTYPE(io) == IoTYPE_RDWR ||
2997 IoTYPE(io) == IoTYPE_APPEND)
2998 && ckWARN_d(WARN_IO)
2999 && IoIFP(io) != PerlIO_stdin()
3000 && IoIFP(io) != PerlIO_stdout()
3001 && IoIFP(io) != PerlIO_stderr()
3002 && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3003 io_close(io, gv, FALSE, TRUE);
3005 if (SvREFCNT(io) > 1 || SvOBJECT(io) || UNLIKELY(in_global_destruction)) {
3006 SvREFCNT_dec_NN(io);
3013 if (SvREFCNT(cv) > 1 || SvOBJECT(cv) || UNLIKELY(in_global_destruction)) {
3014 SvREFCNT_dec_NN(cv);
3021 if (SvREFCNT(form) > 1 || SvOBJECT(form) || UNLIKELY(in_global_destruction)) {
3022 SvREFCNT_dec_NN(form);
3030 /* We don't strictly need to defer all this to the end, but it's
3031 easiest to do so. The subtle problems we have are
3032 1) any of the actions triggered by the various SvREFCNT_dec()s in
3033 any of the intermediate blocks can cause more items to be added
3034 to the temps stack. So we can't "cache" its state locally
3035 2) We'd have to re-check the "extend by 1?" for each time.
3036 Whereas if we don't NULL out the values that we want to put onto
3037 the save stack until here, we can do it in one go, with one
3040 SSize_t max_ix = PL_tmps_ix + need;
3042 if (max_ix >= PL_tmps_max) {
3043 tmps_grow_p(max_ix);
3047 PL_tmps_stack[++PL_tmps_ix] = sv;
3050 PL_tmps_stack[++PL_tmps_ix] = (SV *) av;
3053 PL_tmps_stack[++PL_tmps_ix] = (SV *) hv;
3056 PL_tmps_stack[++PL_tmps_ix] = (SV *) io;
3059 PL_tmps_stack[++PL_tmps_ix] = (SV *) cv;
3062 PL_tmps_stack[++PL_tmps_ix] = (SV *) form;
3066 /* Possibly reallocated by a destructor */
3069 if (!gp->gp_file_hek
3075 && !gp->gp_form) break;
3077 if (--attempts == 0) {
3079 "panic: gp_free failed to free glob pointer - "
3080 "something is repeatedly re-creating entries"
3085 /* Possibly incremented by a destructor doing glob assignment */
3086 if (gp->gp_refcnt > 1) goto borrowed;
3092 Perl_magic_freeovrld(pTHX_ SV *sv, MAGIC *mg)
3094 AMT * const amtp = (AMT*)mg->mg_ptr;
3095 PERL_UNUSED_ARG(sv);
3097 PERL_ARGS_ASSERT_MAGIC_FREEOVRLD;
3099 if (amtp && AMT_AMAGIC(amtp)) {
3101 for (i = 1; i < NofAMmeth; i++) {
3102 CV * const cv = amtp->table[i];
3104 SvREFCNT_dec_NN(MUTABLE_SV(cv));
3105 amtp->table[i] = NULL;
3113 =for apidoc Gv_AMupdate
3115 Recalculates overload magic in the package given by C<stash>.
3121 =item 1 on success and there is some overload
3123 =item 0 if there is no overload
3125 =item -1 if some error occurred and it couldn't croak (because C<destructing>
3134 Perl_Gv_AMupdate(pTHX_ HV *stash, bool destructing)
3136 MAGIC* const mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
3138 const struct mro_meta* stash_meta = HvMROMETA(stash);
3141 PERL_ARGS_ASSERT_GV_AMUPDATE;
3143 newgen = PL_sub_generation + stash_meta->pkg_gen + stash_meta->cache_gen;
3145 const AMT * const amtp = (AMT*)mg->mg_ptr;
3146 if (amtp->was_ok_sub == newgen) {
3147 return AMT_AMAGIC(amtp) ? 1 : 0;
3149 sv_unmagic(MUTABLE_SV(stash), PERL_MAGIC_overload_table);
3152 DEBUG_o( Perl_deb(aTHX_ "Recalculating overload magic in package %s\n",HvNAME_get(stash)) );
3155 amt.was_ok_sub = newgen;
3156 amt.fallback = AMGfallNO;
3162 bool deref_seen = 0;
3165 /* Work with "fallback" key, which we assume to be first in PL_AMG_names */
3167 /* Try to find via inheritance. */
3168 GV *gv = gv_fetchmeth_pvn(stash, PL_AMG_names[0], 2, -1, 0);
3169 SV * const sv = gv ? GvSV(gv) : NULL;
3174 if (!gv_fetchmeth_pvn(stash, "((", 2, -1, 0))
3177 #ifdef PERL_DONT_CREATE_GVSV
3179 NOOP; /* Equivalent to !SvTRUE and !SvOK */
3182 else if (SvTRUE(sv))
3183 /* don't need to set overloading here because fallback => 1
3184 * is the default setting for classes without overloading */
3185 amt.fallback=AMGfallYES;
3186 else if (SvOK(sv)) {
3187 amt.fallback=AMGfallNEVER;
3194 assert(HvHasAUX(stash));
3195 /* initially assume the worst */
3196 HvAUX(stash)->xhv_aux_flags &= ~HvAUXf_NO_DEREF;
3198 for (i = 1; i < NofAMmeth; i++) {
3199 const char * const cooky = PL_AMG_names[i];
3200 /* Human-readable form, for debugging: */
3201 const char * const cp = AMG_id2name(i);
3202 const STRLEN l = PL_AMG_namelens[i];
3204 DEBUG_o( Perl_deb(aTHX_ "Checking overloading of \"%s\" in package \"%.256s\"\n",
3205 cp, HvNAME_get(stash)) );
3206 /* don't fill the cache while looking up!
3207 Creation of inheritance stubs in intermediate packages may
3208 conflict with the logic of runtime method substitution.
3209 Indeed, for inheritance A -> B -> C, if C overloads "+0",
3210 then we could have created stubs for "(+0" in A and C too.
3211 But if B overloads "bool", we may want to use it for
3212 numifying instead of C's "+0". */
3213 gv = Perl_gv_fetchmeth_pvn(aTHX_ stash, cooky, l, -1, 0);
3215 if (gv && (cv = GvCV(gv)) && CvHASGV(cv)) {
3216 const HEK * const gvhek = CvGvNAME_HEK(cv);
3217 const HEK * const stashek =
3218 HvNAME_HEK(CvNAMED(cv) ? CvSTASH(cv) : GvSTASH(CvGV(cv)));
3219 if (memEQs(HEK_KEY(gvhek), HEK_LEN(gvhek), "nil")
3221 && memEQs(HEK_KEY(stashek), HEK_LEN(stashek), "overload")) {
3222 /* This is a hack to support autoloading..., while
3223 knowing *which* methods were declared as overloaded. */
3224 /* GvSV contains the name of the method. */
3226 SV *gvsv = GvSV(gv);
3228 DEBUG_o( Perl_deb(aTHX_ "Resolving method \"%" SVf256\
3229 "\" for overloaded \"%s\" in package \"%.256s\"\n",
3230 (void*)GvSV(gv), cp, HvNAME(stash)) );
3231 if (!gvsv || !SvPOK(gvsv)
3232 || !(ngv = gv_fetchmethod_sv_flags(stash, gvsv, 0)))
3234 /* Can be an import stub (created by "can"). */
3239 const SV * const name = (gvsv && SvPOK(gvsv))
3241 : newSVpvs_flags("???", SVs_TEMP);
3242 /* diag_listed_as: Can't resolve method "%s" overloading "%s" in package "%s" */
3243 Perl_croak(aTHX_ "%s method \"%" SVf256
3244 "\" overloading \"%s\" "\
3245 "in package \"%" HEKf256 "\"",
3246 (GvCVGEN(gv) ? "Stub found while resolving"
3254 cv = GvCV(gv = ngv);
3256 DEBUG_o( Perl_deb(aTHX_ "Overloading \"%s\" in package \"%.256s\" via \"%.256s::%.256s\"\n",
3257 cp, HvNAME_get(stash), HvNAME_get(GvSTASH(CvGV(cv))),
3258 GvNAME(CvGV(cv))) );
3260 } else if (gv) { /* Autoloaded... */
3261 cv = MUTABLE_CV(gv);
3264 amt.table[i]=MUTABLE_CV(SvREFCNT_inc_simple(cv));
3280 /* none of @{} etc overloaded; we can do $obj->[N] quicker.
3281 * NB - aux var invalid here, HvARRAY() could have been
3282 * reallocated since it was assigned to */
3283 HvAUX(stash)->xhv_aux_flags |= HvAUXf_NO_DEREF;
3286 AMT_AMAGIC_on(&amt);
3287 sv_magic(MUTABLE_SV(stash), 0, PERL_MAGIC_overload_table,
3288 (char*)&amt, sizeof(AMT));
3292 /* Here we have no table: */
3294 AMT_AMAGIC_off(&amt);
3295 sv_magic(MUTABLE_SV(stash), 0, PERL_MAGIC_overload_table,
3296 (char*)&amt, sizeof(AMTS));
3301 =for apidoc gv_handler
3303 Implements C<StashHANDLER>, which you should use instead
3309 Perl_gv_handler(pTHX_ HV *stash, I32 id)
3314 struct mro_meta* stash_meta;
3316 if (!stash || !HvHasNAME(stash))
3319 stash_meta = HvMROMETA(stash);
3320 newgen = PL_sub_generation + stash_meta->pkg_gen + stash_meta->cache_gen;
3322 mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
3325 if (Gv_AMupdate(stash, 0) == -1)
3327 mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
3330 amtp = (AMT*)mg->mg_ptr;
3331 if ( amtp->was_ok_sub != newgen )
3333 if (AMT_AMAGIC(amtp)) {
3334 CV * const ret = amtp->table[id];
3335 if (ret && isGV(ret)) { /* Autoloading stab */
3336 /* Passing it through may have resulted in a warning
3337 "Inherited AUTOLOAD for a non-method deprecated", since
3338 our caller is going through a function call, not a method call.
3339 So return the CV for AUTOLOAD, setting $AUTOLOAD. */
3340 GV * const gv = gv_fetchmethod(stash, PL_AMG_names[id]);
3352 /* Implement tryAMAGICun_MG macro.
3353 Do get magic, then see if the stack arg is overloaded and if so call it.
3355 AMGf_numeric apply sv_2num to the stack arg.
3359 Perl_try_amagic_un(pTHX_ int method, int flags)
3362 SV* const arg = PL_stack_sp[0];
3363 bool is_rc = rpp_stack_is_rc();
3367 if (SvAMAGIC(arg) && (tmpsv = amagic_call(arg, &PL_sv_undef, method,
3368 AMGf_noright | AMGf_unary
3369 | (flags & AMGf_numarg))))
3371 /* where the op is of the form:
3372 * $lex = $x op $y (where the assign is optimised away)
3373 * then assign the returned value to targ and return that;
3374 * otherwise return the value directly
3377 if ( (PL_opargs[PL_op->op_type] & OA_TARGLEX)
3378 && (PL_op->op_private & OPpTARGET_MY))
3380 targ = PAD_SV(PL_op->op_targ);
3381 sv_setsv(targ, tmpsv);
3385 *PL_stack_sp = targ;
3387 SvREFCNT_inc_NN(targ);
3388 SvREFCNT_dec_NN(arg);
3395 if ((flags & AMGf_numeric) && SvROK(arg)) {
3396 PL_stack_sp[0] = tmpsv = sv_2num(arg);
3398 SvREFCNT_inc_NN(tmpsv);
3399 SvREFCNT_dec_NN(arg);
3408 =for apidoc amagic_applies
3410 Check C<sv> to see if the overloaded (active magic) operation C<method>
3411 applies to it. If the sv is not SvROK or it is not an object then returns
3412 false, otherwise checks if the object is blessed into a class supporting
3413 overloaded operations, and returns true if a call to amagic_call() with
3414 this SV and the given method would trigger an amagic operation, including
3415 via the overload fallback rules or via nomethod. Thus a call like:
3417 amagic_applies(sv, string_amg, AMG_unary)
3419 would return true for an object with overloading set up in any of the
3422 use overload q("") => sub { ... };
3423 use overload q(0+) => sub { ... }, fallback => 1;
3425 and could be used to tell if a given object would stringify to something
3426 other than the normal default ref stringification.
3428 Note that the fact that this function returns TRUE does not mean you
3429 can succesfully perform the operation with amagic_call(), for instance
3430 any overloaded method might throw a fatal exception, however if this
3431 function returns FALSE you can be confident that it will NOT perform
3432 the given overload operation.
3434 C<method> is an integer enum, one of the values found in F<overload.h>,
3435 for instance C<string_amg>.
3437 C<flags> should be set to AMG_unary for unary operations.
3442 Perl_amagic_applies(pTHX_ SV *sv, int method, int flags)
3444 PERL_ARGS_ASSERT_AMAGIC_APPLIES;
3445 PERL_UNUSED_VAR(flags);
3447 assert(method >= 0 && method < NofAMmeth);
3452 HV *stash = SvSTASH(SvRV(sv));
3456 MAGIC *mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
3462 if (AMT_AMAGIC((AMT *)mg->mg_ptr)) {
3463 amtp = (AMT *)mg->mg_ptr;
3472 /* Note this logic should be kept in sync with amagic_call() */
3473 if (amtp->fallback > AMGfallNEVER && flags & AMGf_unary) {
3474 CV *cv; /* This makes it easier to kee ... */
3475 int off,off1; /* ... in sync with amagic_call() */
3477 /* look for substituted methods */
3478 /* In all the covered cases we should be called with assign==0. */
3481 if ((cv = cvp[off=add_ass_amg]) || ((cv = cvp[off = add_amg])))
3485 if((cv = cvp[off = subtr_ass_amg]) || ((cv = cvp[off = subtr_amg])))
3489 if ((cv = cvp[off=numer_amg]) || (cv = cvp[off=string_amg]))
3493 if((cv = cvp[off=string_amg]) || (cv = cvp[off=bool__amg]))
3497 if((cv = cvp[off=numer_amg]) || (cv = cvp[off=bool__amg]))
3501 if((cv = cvp[off=bool__amg])
3502 || (cv = cvp[off=numer_amg])
3503 || (cv = cvp[off=string_amg]))
3507 if((cvp[off1=lt_amg] || cvp[off1=ncmp_amg])
3508 && ((cv = cvp[off=neg_amg]) || (cv = cvp[off=subtr_amg])))
3512 if ((cv = cvp[off=subtr_amg]))
3516 } else if (((cvp && amtp->fallback > AMGfallNEVER))
3517 && !(flags & AMGf_unary)) {
3518 /* We look for substitution for
3519 * comparison operations and
3521 if (method==concat_amg || method==concat_ass_amg
3522 || method==repeat_amg || method==repeat_ass_amg) {
3523 return FALSE; /* Delegate operation to string conversion */
3547 if (cvp[nomethod_amg])
3554 /* Implement tryAMAGICbin_MG macro.
3555 Do get magic, then see if the two stack args are overloaded and if so
3558 AMGf_assign op may be called as mutator (eg +=)
3559 AMGf_numeric apply sv_2num to the stack arg.
3563 Perl_try_amagic_bin(pTHX_ int method, int flags)
3565 SV* left = PL_stack_sp[-1];
3566 SV* right = PL_stack_sp[0];
3567 bool is_rc = rpp_stack_is_rc();
3573 if (SvAMAGIC(left) || SvAMAGIC(right)) {
3575 /* STACKED implies mutator variant, e.g. $x += 1 */
3576 bool mutator = (flags & AMGf_assign) && (PL_op->op_flags & OPf_STACKED);
3578 tmpsv = amagic_call(left, right, method,
3579 (mutator ? AMGf_assign: 0)
3580 | (flags & AMGf_numarg));
3584 SvREFCNT_dec_NN(right);
3585 /* where the op is one of the two forms:
3587 * $lex = $x op $y (where the assign is optimised away)
3588 * then assign the returned value to targ and return that;
3589 * otherwise return the value directly
3593 || ( (PL_opargs[PL_op->op_type] & OA_TARGLEX)
3594 && (PL_op->op_private & OPpTARGET_MY)))
3596 targ = mutator ? left : PAD_SV(PL_op->op_targ);
3597 sv_setsv(targ, tmpsv);
3601 *PL_stack_sp = targ;
3603 SvREFCNT_inc_NN(targ);
3604 SvREFCNT_dec_NN(left);
3612 /* if the same magic value appears on both sides, replace the LH one
3613 * with a copy and call get magic on the RH one, so that magic gets
3614 * called twice with possibly two different returned values */
3615 if (left == right && SvGMAGICAL(left)) {
3616 SV * const tmpsv = is_rc ? newSV_type(SVt_NULL) : sv_newmortal();
3617 /* Print the uninitialized warning now, so it includes the vari-
3620 if (ckWARN(WARN_UNINITIALIZED))
3621 report_uninit(right);
3622 sv_setbool(tmpsv, FALSE);
3625 sv_setsv_flags(tmpsv, right, 0);
3627 SvREFCNT_dec_NN(left);
3628 left = PL_stack_sp[-1] = tmpsv;
3632 if (flags & AMGf_numeric) {
3635 PL_stack_sp[-1] = tmpsv = sv_2num(left);
3637 SvREFCNT_inc_NN(tmpsv);
3638 SvREFCNT_dec_NN(left);
3642 PL_stack_sp[0] = tmpsv = sv_2num(right);
3644 SvREFCNT_inc_NN(tmpsv);
3645 SvREFCNT_dec_NN(right);
3655 =for apidoc amagic_deref_call
3657 Perform C<method> overloading dereferencing on C<ref>, returning the
3658 dereferenced result. C<method> must be one of the dereference operations given
3661 If overloading is inactive on C<ref>, returns C<ref> itself.
3667 Perl_amagic_deref_call(pTHX_ SV *ref, int method) {
3671 PERL_ARGS_ASSERT_AMAGIC_DEREF_CALL;
3675 /* return quickly if none of the deref ops are overloaded */
3676 stash = SvSTASH(SvRV(ref));
3677 assert(HvHasAUX(stash));
3678 if (HvAUX(stash)->xhv_aux_flags & HvAUXf_NO_DEREF)
3681 while ((tmpsv = amagic_call(ref, &PL_sv_undef, method,
3682 AMGf_noright | AMGf_unary))) {
3684 Perl_croak(aTHX_ "Overloaded dereference did not return a reference");
3685 if (tmpsv == ref || SvRV(tmpsv) == SvRV(ref)) {
3686 /* Bail out if it returns us the same reference. */
3693 return tmpsv ? tmpsv : ref;
3697 Perl_amagic_is_enabled(pTHX_ int method)
3699 SV *lex_mask = cop_hints_fetch_pvs(PL_curcop, "overloading", 0);
3701 assert(PL_curcop->cop_hints & HINT_NO_AMAGIC);
3703 if ( !lex_mask || !SvOK(lex_mask) )
3704 /* overloading lexically disabled */
3706 else if ( lex_mask && SvPOK(lex_mask) ) {
3707 /* we have an entry in the hints hash, check if method has been
3708 * masked by overloading.pm */
3710 const int offset = method / 8;
3711 const int bit = method % 8;
3712 char *pv = SvPV(lex_mask, len);
3714 /* Bit set, so this overloading operator is disabled */
3715 if ( (STRLEN)offset < len && pv[offset] & ( 1 << bit ) )
3722 =for apidoc amagic_call
3724 Perform the overloaded (active magic) operation given by C<method>.
3725 C<method> is one of the values found in F<overload.h>.
3727 C<flags> affects how the operation is performed, as follows:
3731 =item C<AMGf_noleft>
3733 C<left> is not to be used in this operation.
3735 =item C<AMGf_noright>
3737 C<right> is not to be used in this operation.
3741 The operation is done only on just one operand.
3743 =item C<AMGf_assign>
3745 The operation changes one of the operands, e.g., $x += 1
3753 Perl_amagic_call(pTHX_ SV *left, SV *right, int method, int flags)
3757 CV **cvp=NULL, **ocvp=NULL;
3758 AMT *amtp=NULL, *oamtp=NULL;
3759 int off = 0, off1, lr = 0, notfound = 0;
3760 int postpr = 0, force_cpy = 0;
3761 int assign = AMGf_assign & flags;
3762 const int assignshift = assign ? 1 : 0;
3763 int use_default_op = 0;
3764 int force_scalar = 0;
3770 PERL_ARGS_ASSERT_AMAGIC_CALL;
3772 if ( PL_curcop->cop_hints & HINT_NO_AMAGIC ) {
3773 if (!amagic_is_enabled(method)) return NULL;
3776 if (!(AMGf_noleft & flags) && SvAMAGIC(left)
3777 && (stash = SvSTASH(SvRV(left))) && Gv_AMG(stash)
3778 && (mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table))
3779 && (ocvp = cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
3780 ? (oamtp = amtp = (AMT*)mg->mg_ptr)->table
3782 && ((cv = cvp[off=method+assignshift])
3783 || (assign && amtp->fallback > AMGfallNEVER && /* fallback to
3789 cv = cvp[off=method]))))
3791 lr = -1; /* Call method for left argument */
3793 /* Note this logic should be kept in sync with amagic_applies() */
3794 if (cvp && amtp->fallback > AMGfallNEVER && flags & AMGf_unary) {
3797 /* look for substituted methods */
3798 /* In all the covered cases we should be called with assign==0. */
3802 if ((cv = cvp[off=add_ass_amg])
3803 || ((cv = cvp[off = add_amg])
3804 && (force_cpy = 0, (postpr = 1)))) {
3805 right = &PL_sv_yes; lr = -1; assign = 1;
3810 if ((cv = cvp[off = subtr_ass_amg])
3811 || ((cv = cvp[off = subtr_amg])
3812 && (force_cpy = 0, (postpr=1)))) {
3813 right = &PL_sv_yes; lr = -1; assign = 1;
3817 (void)((cv = cvp[off=numer_amg]) || (cv = cvp[off=string_amg]));
3820 (void)((cv = cvp[off=string_amg]) || (cv = cvp[off=bool__amg]));
3823 (void)((cv = cvp[off=numer_amg]) || (cv = cvp[off=bool__amg]));
3826 (void)((cv = cvp[off=bool__amg])
3827 || (cv = cvp[off=numer_amg])
3828 || (cv = cvp[off=string_amg]));
3835 * SV* ref causes confusion with the interpreter variable of
3838 SV* const tmpRef=SvRV(left);
3839 if (!SvROK(tmpRef) && SvTYPE(tmpRef) <= SVt_PVMG) {
3841 * Just to be extra cautious. Maybe in some
3842 * additional cases sv_setsv is safe, too.
3844 SV* const newref = newSVsv(tmpRef);
3845 SvOBJECT_on(newref);
3846 /* No need to do SvAMAGIC_on here, as SvAMAGIC macros
3847 delegate to the stash. */
3848 SvSTASH_set(newref, MUTABLE_HV(SvREFCNT_inc(SvSTASH(tmpRef))));
3854 if ((cvp[off1=lt_amg] || cvp[off1=ncmp_amg])
3855 && ((cv = cvp[off=neg_amg]) || (cv = cvp[off=subtr_amg]))) {
3856 SV* const nullsv=&PL_sv_zero;
3858 SV* const lessp = amagic_call(left,nullsv,
3859 lt_amg,AMGf_noright);
3860 logic = SvTRUE_NN(lessp);
3862 SV* const lessp = amagic_call(left,nullsv,
3863 ncmp_amg,AMGf_noright);
3864 logic = (SvNV(lessp) < 0);
3867 if (off==subtr_amg) {
3878 if ((cv = cvp[off=subtr_amg])) {
3885 case iter_amg: /* XXXX Eventually should do to_gv. */
3886 case ftest_amg: /* XXXX Eventually should do to_gv. */
3889 return NULL; /* Delegate operation to standard mechanisms. */
3897 return left; /* Delegate operation to standard mechanisms. */
3902 if (!cv) goto not_found;
3903 } else if (!(AMGf_noright & flags) && SvAMAGIC(right)
3904 && (stash = SvSTASH(SvRV(right))) && Gv_AMG(stash)
3905 && (mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table))
3906 && (cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
3907 ? (amtp = (AMT*)mg->mg_ptr)->table
3909 && (cv = cvp[off=method])) { /* Method for right
3912 } else if (((cvp && amtp->fallback > AMGfallNEVER)
3913 || (ocvp && oamtp->fallback > AMGfallNEVER))
3914 && !(flags & AMGf_unary)) {
3915 /* We look for substitution for
3916 * comparison operations and
3918 if (method==concat_amg || method==concat_ass_amg
3919 || method==repeat_amg || method==repeat_ass_amg) {
3920 return NULL; /* Delegate operation to string conversion */
3942 if (ocvp && (oamtp->fallback > AMGfallNEVER)) {
3946 if (!cv && (cvp && amtp->fallback > AMGfallNEVER)) {
3956 not_found: /* No method found, either report or croak */
3964 return left; /* Delegate operation to standard mechanisms. */
3966 if (ocvp && (cv=ocvp[nomethod_amg])) { /* Call report method */
3967 notfound = 1; lr = -1;
3968 } else if (cvp && (cv=cvp[nomethod_amg])) {
3969 notfound = 1; lr = 1;
3970 } else if ((use_default_op =
3971 (!ocvp || oamtp->fallback >= AMGfallYES)
3972 && (!cvp || amtp->fallback >= AMGfallYES))
3974 /* Skip generating the "no method found" message. */
3978 if (off==-1) off=method;
3979 msg = sv_2mortal(Perl_newSVpvf(aTHX_
3980 "Operation \"%s\": no method found,%sargument %s%" SVf "%s%" SVf,
3981 AMG_id2name(method + assignshift),
3982 (flags & AMGf_unary ? " " : "\n\tleft "),
3984 "in overloaded package ":
3985 "has no overloaded magic",
3987 SVfARG(newSVhek_mortal(HvNAME_HEK(SvSTASH(SvRV(left))))):
3990 ",\n\tright argument in overloaded package ":
3993 : ",\n\tright argument has no overloaded magic"),
3995 SVfARG(newSVhek_mortal(HvNAME_HEK(SvSTASH(SvRV(right))))):
3996 SVfARG(&PL_sv_no)));
3997 if (use_default_op) {
3998 DEBUG_o( Perl_deb(aTHX_ "%" SVf, SVfARG(msg)) );
4000 Perl_croak(aTHX_ "%" SVf, SVfARG(msg));
4004 force_cpy = force_cpy || assign;
4009 /* in these cases, we're calling '+' or '-' as a fallback for a ++ or --
4010 * operation. we need this to return a value, so that it can be assigned
4011 * later on, in the postpr block (case inc_amg/dec_amg), even if the
4012 * increment or decrement was itself called in void context */
4018 if (off == subtr_amg)
4021 /* in these cases, we're calling an assignment variant of an operator
4022 * (+= rather than +, for instance). regardless of whether it's a
4023 * fallback or not, it always has to return a value, which will be
4024 * assigned to the proper variable later */
4044 /* the copy constructor always needs to return a value */
4048 /* because of the way these are implemented (they don't perform the
4049 * dereferencing themselves, they return a reference that perl then
4050 * dereferences later), they always have to be in scalar context */
4058 /* these don't have an op of their own; they're triggered by their parent
4059 * op, so the context there isn't meaningful ('$a and foo()' in void
4060 * context still needs to pass scalar context on to $a's bool overload) */
4070 DEBUG_o(Perl_deb(aTHX_
4071 "Overloaded operator \"%s\"%s%s%s:\n\tmethod%s found%s in package %" SVf "%s\n",
4073 method+assignshift==off? "" :
4075 method+assignshift==off? "" :
4076 AMG_id2name(method+assignshift),
4077 method+assignshift==off? "" : "\")",
4078 flags & AMGf_unary? "" :
4079 lr==1 ? " for right argument": " for left argument",
4080 flags & AMGf_unary? " for argument" : "",
4081 stash ? SVfARG(newSVhek_mortal(HvNAME_HEK(stash))) : SVfARG(newSVpvs_flags("null", SVs_TEMP)),
4082 fl? ",\n\tassignment variant used": "") );
4085 /* Since we use shallow copy during assignment, we need
4086 * to duplicate the contents, probably calling user-supplied
4087 * version of copy operator
4089 /* We need to copy in following cases:
4090 * a) Assignment form was called.
4091 * assignshift==1, assign==T, method + 1 == off
4092 * b) Increment or decrement, called directly.
4093 * assignshift==0, assign==0, method + 0 == off
4094 * c) Increment or decrement, translated to assignment add/subtr.
4095 * assignshift==0, assign==T,
4097 * d) Increment or decrement, translated to nomethod.
4098 * assignshift==0, assign==0,
4100 * e) Assignment form translated to nomethod.
4101 * assignshift==1, assign==T, method + 1 != off
4104 /* off is method, method+assignshift, or a result of opcode substitution.
4105 * In the latter case assignshift==0, so only notfound case is important.
4107 if ( (lr == -1) && ( ( (method + assignshift == off)
4108 && (assign || (method == inc_amg) || (method == dec_amg)))
4111 /* newSVsv does not behave as advertised, so we copy missing
4112 * information by hand */
4113 SV *tmpRef = SvRV(left);
4115 if (SvREFCNT(tmpRef) > 1 && (rv_copy = AMG_CALLunary(left,copy_amg))) {
4116 SvRV_set(left, rv_copy);
4118 SvREFCNT_dec_NN(tmpRef);
4126 const bool oldcatch = CATCH_GET;
4128 /* for multiconcat, we may call overload several times,
4129 * with the context of individual concats being scalar,
4130 * regardless of the overall context of the multiconcat op
4132 U8 gimme = (force_scalar || PL_op->op_type == OP_MULTICONCAT)
4133 ? G_SCALAR : GIMME_V;
4136 Zero(&myop, 1, UNOP);
4137 myop.op_flags = OPf_STACKED;
4138 myop.op_ppaddr = PL_ppaddr[OP_ENTERSUB];
4139 myop.op_type = OP_ENTERSUB;
4144 myop.op_flags |= OPf_WANT_VOID;
4147 if (flags & AMGf_want_list) {
4148 myop.op_flags |= OPf_WANT_LIST;
4153 myop.op_flags |= OPf_WANT_SCALAR;
4157 PUSHSTACKi(PERLSI_OVERLOAD);
4160 PL_op = (OP *) &myop;
4161 if (PERLDB_SUB && PL_curstash != PL_debstash)
4162 PL_op->op_private |= OPpENTERSUB_DB;
4163 Perl_pp_pushmark(aTHX);
4165 EXTEND(SP, notfound + 5);
4166 PUSHs(lr>0? right: left);
4167 PUSHs(lr>0? left: right);
4168 PUSHs( lr > 0 ? &PL_sv_yes : ( assign ? &PL_sv_undef : &PL_sv_no ));
4170 PUSHs(newSVpvn_flags(AMG_id2name(method + assignshift),
4171 AMG_id2namelen(method + assignshift), SVs_TEMP));
4173 else if (flags & AMGf_numarg)
4174 PUSHs(&PL_sv_undef);
4175 if (flags & AMGf_numarg)
4177 PUSHs(MUTABLE_SV(cv));
4183 nret = SP - (PL_stack_base + oldmark);
4187 /* returning NULL has another meaning, and we check the context
4188 * at the call site too, so this can be differentiated from the
4191 SP = PL_stack_base + oldmark;
4194 if (flags & AMGf_want_list) {
4195 res = newSV_type_mortal(SVt_PVAV);
4196 av_extend((AV *)res, nret);
4198 av_store((AV *)res, nret, POPs);
4209 CATCH_SET(oldcatch);
4216 ans=SvIV(res)<=0; break;
4219 ans=SvIV(res)<0; break;
4222 ans=SvIV(res)>=0; break;
4225 ans=SvIV(res)>0; break;
4228 ans=SvIV(res)==0; break;
4231 ans=SvIV(res)!=0; break;
4234 SvSetSV(left,res); return left;
4236 ans=!SvTRUE_NN(res); break;
4241 } else if (method==copy_amg) {
4243 Perl_croak(aTHX_ "Copy method did not return a reference");
4245 return SvREFCNT_inc(SvRV(res));
4253 =for apidoc gv_name_set
4255 Set the name for GV C<gv> to C<name> which is C<len> bytes long. Thus it may
4256 contain embedded NUL characters.
4258 If C<flags> contains C<SVf_UTF8>, the name is treated as being encoded in
4259 UTF-8; otherwise not.
4265 Perl_gv_name_set(pTHX_ GV *gv, const char *name, U32 len, U32 flags)
4269 PERL_ARGS_ASSERT_GV_NAME_SET;
4272 Perl_croak(aTHX_ "panic: gv name too long (%" UVuf ")", (UV) len);
4274 if (!(flags & GV_ADD) && GvNAME_HEK(gv)) {
4275 unshare_hek(GvNAME_HEK(gv));
4278 PERL_HASH(hash, name, len);
4279 GvNAME_HEK(gv) = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
4283 =for apidoc gv_try_downgrade
4285 If the typeglob C<gv> can be expressed more succinctly, by having
4286 something other than a real GV in its place in the stash, replace it
4287 with the optimised form. Basic requirements for this are that C<gv>
4288 is a real typeglob, is sufficiently ordinary, and is only referenced
4289 from its package. This function is meant to be used when a GV has been
4290 looked up in part to see what was there, causing upgrading, but based
4291 on what was found it turns out that the real GV isn't required after all.
4293 If C<gv> is a completely empty typeglob, it is deleted from the stash.
4295 If C<gv> is a typeglob containing only a sufficiently-ordinary constant
4296 sub, the typeglob is replaced with a scalar-reference placeholder that
4297 more compactly represents the same thing.
4303 Perl_gv_try_downgrade(pTHX_ GV *gv)
4309 PERL_ARGS_ASSERT_GV_TRY_DOWNGRADE;
4311 /* XXX Why and where does this leave dangling pointers during global
4313 if (PL_phase == PERL_PHASE_DESTRUCT) return;
4315 if (!(SvREFCNT(gv) == 1 && SvTYPE(gv) == SVt_PVGV && !SvFAKE(gv) &&
4316 !SvOBJECT(gv) && !SvREADONLY(gv) &&
4317 isGV_with_GP(gv) && GvGP(gv) &&
4318 !GvINTRO(gv) && GvREFCNT(gv) == 1 &&
4319 !GvSV(gv) && !GvAV(gv) && !GvHV(gv) && !GvIOp(gv) && !GvFORM(gv) &&
4320 GvEGVx(gv) == gv && (stash = GvSTASH(gv))))
4322 if (gv == PL_statgv || gv == PL_last_in_gv || gv == PL_stderrgv)
4324 if (SvMAGICAL(gv)) {
4326 /* only backref magic is allowed */
4327 if (SvGMAGICAL(gv) || SvSMAGICAL(gv))
4329 for (mg = SvMAGIC(gv); mg; mg = mg->mg_moremagic) {
4330 if (mg->mg_type != PERL_MAGIC_backref)
4336 HEK *gvnhek = GvNAME_HEK(gv);
4337 (void)hv_deletehek(stash, gvnhek, G_DISCARD);
4338 } else if (GvMULTI(gv) && cv && SvREFCNT(cv) == 1 &&
4339 !SvOBJECT(cv) && !SvMAGICAL(cv) && !SvREADONLY(cv) &&
4340 CvSTASH(cv) == stash && !CvNAMED(cv) && CvGV(cv) == gv &&
4341 CvCONST(cv) && !CvNOWARN_AMBIGUOUS(cv) && !CvLVALUE(cv) && !CvUNIQUE(cv) &&
4342 !CvNODEBUG(cv) && !CvCLONE(cv) && !CvCLONED(cv) && !CvANON(cv) &&
4343 (namehek = GvNAME_HEK(gv)) &&
4344 (gvp = hv_fetchhek(stash, namehek, 0)) &&
4346 SV *value = SvREFCNT_inc(CvXSUBANY(cv).any_ptr);
4347 const bool imported = cBOOL(GvIMPORTED_CV(gv));
4351 SvFLAGS(gv) = SVt_IV|SVf_ROK|SVprv_PCS_IMPORTED * imported;
4353 /* See also: 'SET_SVANY_FOR_BODYLESS_IV' in sv.c */
4354 SvANY(gv) = (XPVGV*)((char*)&(gv->sv_u.svu_iv) -
4355 STRUCT_OFFSET(XPVIV, xiv_iv));
4356 SvRV_set(gv, value);
4361 Perl_gv_override(pTHX_ const char * const name, const STRLEN len)
4363 GV *gv = gv_fetchpvn(name, len, GV_NOTQUAL, SVt_PVCV);
4365 PERL_ARGS_ASSERT_GV_OVERRIDE;
4366 if (gv && GvCVu(gv) && GvIMPORTED_CV(gv)) return gv;
4367 gvp = (GV**)hv_fetch(PL_globalstash, name, len, FALSE);
4368 gv = gvp ? *gvp : NULL;
4369 if (gv && !isGV(gv)) {
4370 if (!SvPCS_IMPORTED(gv)) return NULL;
4371 gv_init(gv, PL_globalstash, name, len, 0);
4374 return gv && GvCVu(gv) && GvIMPORTED_CV(gv) ? gv : NULL;
4380 core_xsub(pTHX_ CV* cv)
4383 "&CORE::%s cannot be called directly", GvNAME(CvGV(cv))
4388 * ex: set ts=8 sts=4 sw=4 et: