This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Initial attack at basic 'class' feature
[perl5.git] / gv.c
CommitLineData
a0d0e21e 1/* gv.c
79072805 2 *
1129b882 3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
67fbe0e1 4 * 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 by Larry Wall and others
79072805
LW
5 *
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
8 *
a0d0e21e
LW
9 */
10
11/*
12 * 'Mercy!' cried Gandalf. 'If the giving of information is to be the cure
4ac71550 13 * of your inquisitiveness, I shall spend all the rest of my days in answering
a0d0e21e
LW
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,'
17 * laughed Pippin.
4ac71550 18 *
cdad3b53 19 * [p.599 of _The Lord of the Rings_, III/xi: "The Palantír"]
79072805
LW
20 */
21
ccfc67b7 22/*
f3d866f2 23=head1 GV Handling and Stashes
166f8a29
DM
24A GV is a structure which corresponds to to a Perl typeglob, ie *foo.
25It is a structure that holds a pointer to a scalar, an array, a hash etc,
26corresponding to $foo, @foo, %foo.
27
28GVs are usually found as values in stashes (symbol table hashes) where
29Perl stores its global variables.
30
f3d866f2
KW
31A B<stash> is a hash that contains all variables that are defined
32within a package. See L<perlguts/Stashes and Globs>
33
fa2b244a
KW
34=for apidoc Ayh||GV
35
166f8a29 36=cut
ccfc67b7
JH
37*/
38
79072805 39#include "EXTERN.h"
864dbfa3 40#define PERL_IN_GV_C
79072805 41#include "perl.h"
6ffcffbd 42#include "overload.inc"
4aaa4757 43#include "keywords.h"
2846acbf 44#include "feature.h"
79072805 45
f54cb97a 46static const char S_autoload[] = "AUTOLOAD";
3c81f0b3 47#define S_autolen (sizeof("AUTOLOAD")-1)
5c7983e5 48
c8a452ed
KW
49/*
50=for apidoc gv_add_by_type
51
52Make sure there is a slot of type C<type> in the GV C<gv>.
53
54=cut
55*/
56
13c59d41
MH
57GV *
58Perl_gv_add_by_type(pTHX_ GV *gv, svtype type)
c69033f2 59{
d5713896 60 SV **where;
7918f24d 61
13c59d41
MH
62 if (
63 !gv
64 || (
65 SvTYPE((const SV *)gv) != SVt_PVGV
13be902c 66 && SvTYPE((const SV *)gv) != SVt_PVLV
13c59d41 67 )
13be902c 68 ) {
1604cfb0
MS
69 const char *what;
70 if (type == SVt_PVIO) {
71 /*
72 * if it walks like a dirhandle, then let's assume that
73 * this is a dirhandle.
74 */
75 what = OP_IS_DIRHOP(PL_op->op_type) ?
76 "dirhandle" : "filehandle";
77 } else if (type == SVt_PVHV) {
78 what = "hash";
79 } else {
80 what = type == SVt_PVAV ? "array" : "scalar";
81 }
1604cfb0 82 Perl_croak(aTHX_ "Bad symbol for %s", what);
bb85b28a 83 }
d5713896 84
13c59d41 85 if (type == SVt_PVHV) {
1604cfb0 86 where = (SV **)&GvHV(gv);
13c59d41 87 } else if (type == SVt_PVAV) {
1604cfb0 88 where = (SV **)&GvAV(gv);
13c59d41 89 } else if (type == SVt_PVIO) {
1604cfb0 90 where = (SV **)&GvIOp(gv);
13c59d41 91 } else {
1604cfb0 92 where = &GvSV(gv);
13c59d41 93 }
7918f24d 94
13c59d41
MH
95 if (!*where)
96 {
1604cfb0 97 *where = newSV_type(type);
76d5f637
KW
98 if ( type == SVt_PVAV
99 && memEQs(GvNAME(gv), GvNAMELEN(gv), "ISA"))
100 {
1604cfb0 101 sv_magic(*where, (SV *)gv, PERL_MAGIC_isa, NULL, 0);
76d5f637 102 }
e17aed30 103 }
13c59d41 104 return gv;
79072805
LW
105}
106
b1decff3
KW
107/*
108=for apidoc gv_fetchfile
109=for apidoc_item gv_fetchfile_flags
110
111These return the debugger glob for the file (compiled by Perl) whose name is
112given by the C<name> parameter.
113
114There are currently exactly two differences between these functions.
115
116The C<name> parameter to C<gv_fetchfile> is a C string, meaning it is
117C<NUL>-terminated; whereas the C<name> parameter to C<gv_fetchfile_flags> is a
118Perl string, whose length (in bytes) is passed in via the C<namelen> parameter
119This means the name may contain embedded C<NUL> characters.
120C<namelen> doesn't exist in plain C<gv_fetchfile>).
121
122The other difference is that C<gv_fetchfile_flags> has an extra C<flags>
123parameter, which is currently completely ignored, but allows for possible
124future extensions.
125
126=cut
127*/
79072805 128GV *
864dbfa3 129Perl_gv_fetchfile(pTHX_ const char *name)
79072805 130{
7918f24d 131 PERL_ARGS_ASSERT_GV_FETCHFILE;
d9095cec
NC
132 return gv_fetchfile_flags(name, strlen(name), 0);
133}
134
135GV *
136Perl_gv_fetchfile_flags(pTHX_ const char *const name, const STRLEN namelen,
1604cfb0 137 const U32 flags)
d9095cec 138{
4116122e 139 char smallbuf[128];
53d95988 140 char *tmpbuf;
d9095cec 141 const STRLEN tmplen = namelen + 2;
79072805
LW
142 GV *gv;
143
7918f24d 144 PERL_ARGS_ASSERT_GV_FETCHFILE_FLAGS;
d9095cec
NC
145 PERL_UNUSED_ARG(flags);
146
1d7c1841 147 if (!PL_defstash)
1604cfb0 148 return NULL;
1d7c1841 149
d9095cec 150 if (tmplen <= sizeof smallbuf)
1604cfb0 151 tmpbuf = smallbuf;
53d95988 152 else
1604cfb0 153 Newx(tmpbuf, tmplen, char);
0ac0412a 154 /* This is where the debugger's %{"::_<$filename"} hash is created */
53d95988
CS
155 tmpbuf[0] = '_';
156 tmpbuf[1] = '<';
d9095cec 157 memcpy(tmpbuf + 2, name, namelen);
9c913148
TC
158 GV **gvp = (GV**)hv_fetch(PL_defstash, tmpbuf, tmplen, (flags & GVF_NOADD) ? FALSE : TRUE);
159 if (gvp) {
160 gv = *gvp;
161 if (!isGV(gv)) {
162 gv_init(gv, PL_defstash, tmpbuf, tmplen, FALSE);
c69033f2 163#ifdef PERL_DONT_CREATE_GVSV
9c913148 164 GvSV(gv) = newSVpvn(name, namelen);
c69033f2 165#else
9c913148 166 sv_setpvn(GvSV(gv), name, namelen);
c69033f2 167#endif
9c913148
TC
168 }
169 if (PERLDB_LINE_OR_SAVESRC && !GvAV(gv))
1604cfb0 170 hv_magic(GvHVn(gv), GvAVn(gv), PERL_MAGIC_dbfile);
9c913148
TC
171 }
172 else {
173 gv = NULL;
174 }
53d95988 175 if (tmpbuf != smallbuf)
1604cfb0 176 Safefree(tmpbuf);
79072805
LW
177 return gv;
178}
179
62d55b22
NC
180/*
181=for apidoc gv_const_sv
182
183If C<gv> is a typeglob whose subroutine entry is a constant sub eligible for
184inlining, or C<gv> is a placeholder reference that would be promoted to such
185a typeglob, then returns the value returned by the sub. Otherwise, returns
796b6530 186C<NULL>.
62d55b22
NC
187
188=cut
189*/
190
191SV *
192Perl_gv_const_sv(pTHX_ GV *gv)
193{
7918f24d 194 PERL_ARGS_ASSERT_GV_CONST_SV;
23491f1d 195 PERL_UNUSED_CONTEXT;
7918f24d 196
62d55b22 197 if (SvTYPE(gv) == SVt_PVGV)
1604cfb0 198 return cv_const_sv(GvCVu(gv));
16a6e5a4 199 return SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVAV && SvTYPE(SvRV(gv)) != SVt_PVCV ? SvRV(gv) : NULL;
62d55b22
NC
200}
201
12816592
NC
202GP *
203Perl_newGP(pTHX_ GV *const gv)
204{
205 GP *gp;
19bad673 206 U32 hash;
19bad673
NC
207 const char *file;
208 STRLEN len;
209
7918f24d 210 PERL_ARGS_ASSERT_NEWGP;
2639089b
DD
211 Newxz(gp, 1, GP);
212 gp->gp_egv = gv; /* allow compiler to reuse gv after this */
213#ifndef PERL_DONT_CREATE_GVSV
8fcb2425 214 gp->gp_sv = newSV_type(SVt_NULL);
2639089b 215#endif
7918f24d 216
c947bc1d 217 /* PL_curcop may be null here. E.g.,
1604cfb0 218 INIT { bless {} and exit }
c947bc1d
FC
219 frees INIT before looking up DESTROY (and creating *DESTROY)
220 */
2639089b 221 if (PL_curcop) {
6760f691 222 char *tmp= CopFILE(PL_curcop);
1604cfb0 223 gp->gp_line = CopLINE(PL_curcop); /* 0 otherwise Newxz */
6760f691
YO
224
225 if (tmp) {
226 file = tmp;
227 len = CopFILE_LEN(PL_curcop);
1604cfb0 228 }
1604cfb0 229 else goto no_file;
cb0d3385
FC
230 }
231 else {
1604cfb0
MS
232 no_file:
233 file = "";
234 len = 0;
19bad673 235 }
f4890806
NC
236
237 PERL_HASH(hash, file, len);
f4890806 238 gp->gp_file_hek = share_hek(file, len, hash);
12816592
NC
239 gp->gp_refcnt = 1;
240
241 return gp;
242}
243
803f2748
DM
244/* Assign CvGV(cv) = gv, handling weak references.
245 * See also S_anonymise_cv_maybe */
246
247void
248Perl_cvgv_set(pTHX_ CV* cv, GV* gv)
249{
ae77754a 250 GV * const oldgv = CvNAMED(cv) ? NULL : SvANY(cv)->xcv_gv_u.xcv_gv;
b290562e 251 HEK *hek;
803f2748
DM
252 PERL_ARGS_ASSERT_CVGV_SET;
253
254 if (oldgv == gv)
1604cfb0 255 return;
803f2748
DM
256
257 if (oldgv) {
1604cfb0
MS
258 if (CvCVGV_RC(cv)) {
259 SvREFCNT_dec_NN(oldgv);
260 CvCVGV_RC_off(cv);
261 }
262 else {
263 sv_del_backref(MUTABLE_SV(oldgv), MUTABLE_SV(cv));
264 }
803f2748 265 }
db5cc3ee 266 else if ((hek = CvNAME_HEK(cv))) {
1604cfb0
MS
267 unshare_hek(hek);
268 CvLEXICAL_off(cv);
db5cc3ee 269 }
803f2748 270
5988f306 271 CvNAMED_off(cv);
b290562e 272 SvANY(cv)->xcv_gv_u.xcv_gv = gv;
c794ca97 273 assert(!CvCVGV_RC(cv));
803f2748
DM
274
275 if (!gv)
1604cfb0 276 return;
803f2748 277
c794ca97 278 if (isGV_with_GP(gv) && GvGP(gv) && (GvCV(gv) == cv || GvFORM(gv) == cv))
1604cfb0 279 Perl_sv_add_backref(aTHX_ MUTABLE_SV(gv), MUTABLE_SV(cv));
c794ca97 280 else {
1604cfb0
MS
281 CvCVGV_RC_on(cv);
282 SvREFCNT_inc_simple_void_NN(gv);
803f2748 283 }
803f2748
DM
284}
285
ae77754a
FC
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. */
289
290GV *
291Perl_cvgv_from_hek(pTHX_ CV *cv)
292{
293 GV *gv;
2eaf799e 294 SV **svp;
ae77754a
FC
295 PERL_ARGS_ASSERT_CVGV_FROM_HEK;
296 assert(SvTYPE(cv) == SVt_PVCV);
297 if (!CvSTASH(cv)) return NULL;
298 ASSUME(CvNAME_HEK(cv));
2eaf799e 299 svp = hv_fetchhek(CvSTASH(cv), CvNAME_HEK(cv), 0);
8fcb2425 300 gv = MUTABLE_GV(svp && *svp ? *svp : newSV_type(SVt_NULL));
2eaf799e 301 if (!isGV(gv))
1604cfb0
MS
302 gv_init_pvn(gv, CvSTASH(cv), HEK_KEY(CvNAME_HEK(cv)),
303 HEK_LEN(CvNAME_HEK(cv)),
82943faa 304 SVf_UTF8 * cBOOL(HEK_UTF8(CvNAME_HEK(cv))));
2eaf799e 305 if (!CvNAMED(cv)) { /* gv_init took care of it */
1604cfb0
MS
306 assert (SvANY(cv)->xcv_gv_u.xcv_gv == gv);
307 return gv;
2eaf799e 308 }
ae77754a
FC
309 unshare_hek(CvNAME_HEK(cv));
310 CvNAMED_off(cv);
311 SvANY(cv)->xcv_gv_u.xcv_gv = gv;
2eaf799e 312 if (svp && *svp) SvREFCNT_inc_simple_void_NN(gv);
ae77754a
FC
313 CvCVGV_RC_on(cv);
314 return gv;
315}
316
c68d9564
Z
317/* Assign CvSTASH(cv) = st, handling weak references. */
318
319void
320Perl_cvstash_set(pTHX_ CV *cv, HV *st)
321{
322 HV *oldst = CvSTASH(cv);
323 PERL_ARGS_ASSERT_CVSTASH_SET;
324 if (oldst == st)
1604cfb0 325 return;
c68d9564 326 if (oldst)
1604cfb0 327 sv_del_backref(MUTABLE_SV(oldst), MUTABLE_SV(cv));
c68d9564
Z
328 SvANY(cv)->xcv_stash = st;
329 if (st)
1604cfb0 330 Perl_sv_add_backref(aTHX_ MUTABLE_SV(st), MUTABLE_SV(cv));
c68d9564 331}
803f2748 332
e1104062
FC
333/*
334=for apidoc gv_init_pvn
335
336Converts a scalar into a typeglob. This is an incoercible typeglob;
337assigning a reference to it will assign to one of its slots, instead of
796b6530
KW
338overwriting it as happens with typeglobs created by C<SvSetSV>. Converting
339any scalar that is C<SvOK()> may produce unpredictable results and is reserved
e1104062
FC
340for perl's internal use.
341
342C<gv> is the scalar to be converted.
343
344C<stash> is the parent stash/package, if any.
345
04ec7e59
FC
346C<name> and C<len> give the name. The name must be unqualified;
347that is, it must not include the package name. If C<gv> is a
e1104062
FC
348stash element, it is the caller's responsibility to ensure that the name
349passed to this function matches the name of the element. If it does not
350match, perl's internal bookkeeping will get out of sync.
351
4a4088c4 352C<flags> can be set to C<SVf_UTF8> if C<name> is a UTF-8 string, or
04ec7e59 353the return value of SvUTF8(sv). It can also take the
796b6530 354C<GV_ADDMULTI> flag, which means to pretend that the GV has been
e1104062
FC
355seen before (i.e., suppress "Used once" warnings).
356
5af38e47
KW
357=for apidoc Amnh||GV_ADDMULTI
358
e1104062
FC
359=for apidoc gv_init
360
4a4088c4 361The old form of C<gv_init_pvn()>. It does not work with UTF-8 strings, as it
04ec7e59 362has no flags parameter. If the C<multi> parameter is set, the
796b6530 363C<GV_ADDMULTI> flag will be passed to C<gv_init_pvn()>.
e1104062
FC
364
365=for apidoc gv_init_pv
366
796b6530 367Same as C<gv_init_pvn()>, but takes a nul-terminated string for the name
e1104062
FC
368instead of separate char * and length parameters.
369
370=for apidoc gv_init_sv
371
796b6530 372Same as C<gv_init_pvn()>, but takes an SV * for the name instead of separate
e1104062
FC
373char * and length parameters. C<flags> is currently unused.
374
375=cut
376*/
377
463ee0b2 378void
04ec7e59 379Perl_gv_init_sv(pTHX_ GV *gv, HV *stash, SV* namesv, U32 flags)
e6066781
BF
380{
381 char *namepv;
382 STRLEN namelen;
383 PERL_ARGS_ASSERT_GV_INIT_SV;
384 namepv = SvPV(namesv, namelen);
385 if (SvUTF8(namesv))
386 flags |= SVf_UTF8;
04ec7e59 387 gv_init_pvn(gv, stash, namepv, namelen, flags);
e6066781
BF
388}
389
390void
04ec7e59 391Perl_gv_init_pv(pTHX_ GV *gv, HV *stash, const char *name, U32 flags)
e6066781
BF
392{
393 PERL_ARGS_ASSERT_GV_INIT_PV;
04ec7e59 394 gv_init_pvn(gv, stash, name, strlen(name), flags);
e6066781
BF
395}
396
d538caf6
NC
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.
400
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.
409
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.
413
414 Values that can be stored:
415
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)
421
422 The earliest optimisation was subroutine declarations, implemented in 1998
423 by commit 8472ac73d6d80294:
424 "Sub declaration cost reduced from ~500 to ~100 bytes"
425
426 This space optimisation needs to be invisible to regular Perl code. For this
427 code:
428
429 sub foo ($$);
430 *foo = [];
431
432 When the first line is compiled, the optimisation is used, and $::{foo} is
433 assigned the scalar '$$'. No PVGV or PVCV is created.
434
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.
440
441 Analogous code unwinds the other optimisations.
442*/
e6066781 443void
04ec7e59 444Perl_gv_init_pvn(pTHX_ GV *gv, HV *stash, const char *name, STRLEN len, U32 flags)
463ee0b2 445{
3b6733bf
NC
446 const U32 old_type = SvTYPE(gv);
447 const bool doproto = old_type > SVt_NULL;
f9509170 448 char * const proto = (doproto && SvPOK(gv))
1604cfb0
MS
449 ? ((void)(SvIsCOW(gv) && (sv_force_normal((SV *)gv), 0)), SvPVX(gv))
450 : NULL;
49a54bbe 451 const STRLEN protolen = proto ? SvCUR(gv) : 0;
e0260a5b 452 const U32 proto_utf8 = proto ? SvUTF8(gv) : 0;
756cb477 453 SV *const has_constant = doproto && SvROK(gv) ? SvRV(gv) : NULL;
1ccdb730 454 const U32 exported_constant = has_constant ? SvPCS_IMPORTED(gv) : 0;
6881372e 455 const bool really_sub =
1604cfb0 456 has_constant && SvTYPE(has_constant) == SVt_PVCV;
6881372e 457 COP * const old = PL_curcop;
756cb477 458
e6066781 459 PERL_ARGS_ASSERT_GV_INIT_PVN;
756cb477
NC
460 assert (!(proto && has_constant));
461
462 if (has_constant) {
1604cfb0
MS
463 /* The constant has to be a scalar, array or subroutine. */
464 switch (SvTYPE(has_constant)) {
465 case SVt_PVHV:
466 case SVt_PVFM:
467 case SVt_PVIO:
5c1f4d79 468 Perl_croak(aTHX_ "Cannot convert a reference to %s to typeglob",
1604cfb0 469 sv_reftype(has_constant, 0));
c9a0dcdc 470 NOT_REACHED; /* NOTREACHED */
4bbde2f7 471 break;
81d52ecd 472
1604cfb0
MS
473 default: NOOP;
474 }
475 SvRV_set(gv, NULL);
476 SvROK_off(gv);
756cb477 477 }
463ee0b2 478
3b6733bf
NC
479
480 if (old_type < SVt_PVGV) {
1604cfb0
MS
481 if (old_type >= SVt_PV)
482 SvCUR_set(gv, 0);
483 sv_upgrade(MUTABLE_SV(gv), SVt_PVGV);
3b6733bf 484 }
55d729e4 485 if (SvLEN(gv)) {
1604cfb0 486 if (proto) {
d538caf6
NC
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. */
1604cfb0 490 SvPV_set(gv, NULL);
d538caf6
NC
491 }
492 else {
493 /* There is no valid prototype. (SvPOK() must be true for a valid
494 prototype.) Hence we free the memory. */
1604cfb0 495 Safefree(SvPVX_mutable(gv));
d538caf6
NC
496 }
497 SvLEN_set(gv, 0);
498 SvPOK_off(gv);
55d729e4 499 }
2e5b91de
NC
500 SvIOK_off(gv);
501 isGV_with_GP_on(gv);
12816592 502
6881372e
FC
503 if (really_sub && !CvISXSUB(has_constant) && CvSTART(has_constant)
504 && ( CvSTART(has_constant)->op_type == OP_NEXTSTATE
1604cfb0
MS
505 || CvSTART(has_constant)->op_type == OP_DBSTATE))
506 PL_curcop = (COP *)CvSTART(has_constant);
c43ae56f 507 GvGP_set(gv, Perl_newGP(aTHX_ gv));
6881372e 508 PL_curcop = old;
e15faf7d
NC
509 GvSTASH(gv) = stash;
510 if (stash)
1604cfb0 511 Perl_sv_add_backref(aTHX_ MUTABLE_SV(stash), MUTABLE_SV(gv));
04f3bf56 512 gv_name_set(gv, name, len, GV_ADD | ( flags & SVf_UTF8 ? SVf_UTF8 : 0 ));
04ec7e59 513 if (flags & GV_ADDMULTI || doproto) /* doproto means it */
1604cfb0 514 GvMULTI_on(gv); /* _was_ mentioned */
6881372e 515 if (really_sub) {
1604cfb0
MS
516 /* Not actually a constant. Just a regular sub. */
517 CV * const cv = (CV *)has_constant;
518 GvCV_set(gv,cv);
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))
525 )
526 ))
527 CvGV_set(cv,gv);
2eaf799e
FC
528 }
529 else if (doproto) {
1604cfb0
MS
530 CV *cv;
531 if (has_constant) {
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: */
535 if (!GvCV(gv))
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? */
544 } else {
545 cv = newSTUB(gv,1);
546 }
547 if (proto) {
548 sv_usepvn_flags(MUTABLE_SV(cv), proto, protolen,
549 SV_HAS_TRAILING_NUL);
e0260a5b 550 if ( proto_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
1604cfb0 551 }
55d729e4 552 }
463ee0b2
LW
553}
554
76e3520e 555STATIC void
e6066781 556S_gv_init_svtype(pTHX_ GV *gv, const svtype sv_type)
a0d0e21e 557{
13c59d41
MH
558 PERL_ARGS_ASSERT_GV_INIT_SVTYPE;
559
560 switch (sv_type) {
561 case SVt_PVIO:
1604cfb0
MS
562 (void)GvIOn(gv);
563 break;
13c59d41 564 case SVt_PVAV:
1604cfb0
MS
565 (void)GvAVn(gv);
566 break;
13c59d41 567 case SVt_PVHV:
1604cfb0
MS
568 (void)GvHVn(gv);
569 break;
c69033f2 570#ifdef PERL_DONT_CREATE_GVSV
13c59d41
MH
571 case SVt_NULL:
572 case SVt_PVCV:
573 case SVt_PVFM:
574 case SVt_PVGV:
1604cfb0 575 break;
13c59d41 576 default:
1604cfb0
MS
577 if(GvSVn(gv)) {
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
580 its side effect */
581 }
c69033f2 582#endif
a0d0e21e
LW
583 }
584}
585
0f8d4b5e
FC
586static void core_xsub(pTHX_ CV* cv);
587
588static GV *
589S_maybe_add_coresub(pTHX_ HV * const stash, GV *gv,
87566176 590 const char * const name, const STRLEN len)
0f8d4b5e
FC
591{
592 const int code = keyword(name, len, 1);
593 static const char file[] = __FILE__;
97021f77 594 CV *cv, *oldcompcv = NULL;
0f8d4b5e 595 int opnum = 0;
0f8d4b5e 596 bool ampable = TRUE; /* &{}-able */
97021f77
FC
597 COP *oldcurcop = NULL;
598 yy_parser *oldparser = NULL;
599 I32 oldsavestack_ix = 0;
0f8d4b5e
FC
600
601 assert(gv || stash);
602 assert(name);
0f8d4b5e 603
88b892d8
FC
604 if (!code) return NULL; /* Not a keyword */
605 switch (code < 0 ? -code : code) {
0f8d4b5e 606 /* no support for \&CORE::infix;
d885f758 607 no support for funcs that do not parse like funcs */
99b497aa
PE
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 :
88b892d8 613 case KEY_do : case KEY_dump : case KEY_else : case KEY_elsif :
99b497aa
PE
614 case KEY_eq : case KEY_eval : case KEY_field :
615 case KEY_finally:
88b892d8 616 case KEY_for : case KEY_foreach: case KEY_format: case KEY_ge :
813e85a0 617 case KEY_given : case KEY_goto : case KEY_grep : case KEY_gt :
99b497aa
PE
618 case KEY_if : case KEY_isa :
619 case KEY_last :
813e85a0 620 case KEY_le : case KEY_local : case KEY_lt : case KEY_m :
99b497aa 621 case KEY_map : case KEY_method : case KEY_my :
88b892d8 622 case KEY_ne : case KEY_next : case KEY_no: case KEY_or: case KEY_our:
1efec5ed 623 case KEY_package: case KEY_print: case KEY_printf:
919ad5f7 624 case KEY_q : case KEY_qq : case KEY_qr : case KEY_qw :
88b892d8 625 case KEY_qx : case KEY_redo : case KEY_require: case KEY_return:
d33bb3da 626 case KEY_s : case KEY_say : case KEY_sort :
d80ed303 627 case KEY_state: case KEY_sub :
99b497aa
PE
628 case KEY_tr : case KEY_try :
629 case KEY_unless:
7896dde7 630 case KEY_until: case KEY_use : case KEY_when : case KEY_while :
88b892d8 631 case KEY_x : case KEY_xor : case KEY_y :
1604cfb0 632 return NULL;
0f8d4b5e 633 case KEY_chdir:
eb31eb35 634 case KEY_chomp: case KEY_chop: case KEY_defined: case KEY_delete:
73665bc4 635 case KEY_eof : case KEY_exec: case KEY_exists :
0f8d4b5e 636 case KEY_lstat:
bea284c8 637 case KEY_split:
0f8d4b5e
FC
638 case KEY_stat:
639 case KEY_system:
640 case KEY_truncate: case KEY_unlink:
1604cfb0 641 ampable = FALSE;
0f8d4b5e
FC
642 }
643 if (!gv) {
8fcb2425 644 gv = (GV *)newSV_type(SVt_NULL);
1604cfb0 645 gv_init(gv, stash, name, len, TRUE);
0f8d4b5e 646 }
7e68c38b 647 GvMULTI_on(gv);
0f8d4b5e 648 if (ampable) {
1604cfb0
MS
649 ENTER;
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
655 CvOUTSIDE. */
656 oldsavestack_ix = start_subparse(FALSE,0);
657 cv = PL_compcv;
0f8d4b5e
FC
658 }
659 else {
1604cfb0
MS
660 /* Avoid calling newXS, as it calls us, and things start to
661 get hairy. */
662 cv = MUTABLE_CV(newSV_type(SVt_PVCV));
663 GvCV_set(gv,cv);
664 GvCVGEN(gv) = 0;
665 CvISXSUB_on(cv);
666 CvXSUB(cv) = core_xsub;
667 PoisonPADLIST(cv);
0f8d4b5e
FC
668 }
669 CvGV_set(cv, gv); /* This stops new ATTRSUB from setting CvFILE
670 from PL_curcop. */
9b669ea1
DD
671 /* XSUBs can't be perl lang/perl5db.pl debugged
672 if (PERLDB_LINE_OR_SAVESRC)
673 (void)gv_fetchfile(file); */
0f8d4b5e
FC
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
678 new ATTRSUB. */
679 (void)core_prototype((SV *)cv, name, code, &opnum);
87566176 680 if (stash)
1604cfb0 681 (void)hv_store(stash,name,len,(SV *)gv,0);
0f8d4b5e 682 if (ampable) {
4428fb0e
TC
683#ifdef DEBUGGING
684 CV *orig_cv = cv;
685#endif
1604cfb0 686 CvLVALUE_on(cv);
4428fb0e
TC
687 /* newATTRSUB will free the CV and return NULL if we're still
688 compiling after a syntax error */
1604cfb0
MS
689 if ((cv = newATTRSUB_x(
690 oldsavestack_ix, (OP *)gv,
691 NULL,NULL,
692 coresub_op(
693 opnum
694 ? newSVuv((UV)opnum)
695 : newSVpvn(name,len),
696 code, opnum
697 ),
698 TRUE
4428fb0e
TC
699 )) != NULL) {
700 assert(GvCV(gv) == orig_cv);
701 if (opnum != OP_VEC && opnum != OP_SUBSTR && opnum != OP_POS
cd642408 702 && opnum != OP_UNDEF && opnum != OP_KEYS)
4428fb0e
TC
703 CvLVALUE_off(cv); /* Now *that* was a neat trick. */
704 }
1604cfb0
MS
705 LEAVE;
706 PL_parser = oldparser;
707 PL_curcop = oldcurcop;
708 PL_compcv = oldcompcv;
0f8d4b5e 709 }
4428fb0e 710 if (cv) {
1604cfb0
MS
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));
a83b92fa 715 cv_set_call_checker_flags(cv, Perl_ck_entersub_args_core, opnumsv, 0);
1604cfb0 716 SvREFCNT_dec_NN(opnumsv);
4428fb0e
TC
717 }
718
0f8d4b5e
FC
719 return gv;
720}
721
954c1994 722/*
a1f822c2
KW
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
6c53d59b 727
a1f822c2
KW
728These each look for a glob with name C<name>, containing a defined subroutine,
729returning the GV of that glob if found, or C<NULL> if not.
6c53d59b 730
a1f822c2 731C<stash> is always searched (first), unless it is C<NULL>.
e6919483 732
a1f822c2
KW
733If C<stash> is NULL, or was searched but nothing was found in it, and the
734C<GV_SUPER> bit is set in C<flags>, stashes accessible via C<@ISA> are searched
735next. Searching is conducted according to L<C<MRO> order|perlmroapi>.
736
737Finally, if no matches were found so far, and the C<GV_NOUNIVERSAL> flag in
738C<flags> is not set, C<UNIVERSAL::> is searched.
739
740The argument C<level> should be either 0 or -1. If -1, the function will
741return without any side effects or caching. If 0, the function makes sure
742there is a glob named C<name> in C<stash>, creating one if necessary.
743The subroutine slot in the glob will be set to any subroutine found in the
744C<stash> and C<SUPER::> search, hence caching any C<SUPER::> result. Note that
745subroutines found in C<UNIVERSAL::> are not cached.
746
747The GV returned from these may be a method cache entry, which is not visible to
748Perl code. So when calling C<call_sv>, you should not use the GV directly;
749instead, you should use the method's CV, which can be obtained from the GV with
750the C<GvCV> macro.
751
752The only other significant value for C<flags> is C<SVf_UTF8>, indicating that
753C<name> is to be treated as being encoded in UTF-8.
754
755Plain C<gv_fetchmeth> lacks a C<flags> parameter, hence always searches in
756C<stash>, then C<UNIVERSAL::>, and C<name> is never UTF-8. Otherwise it is
757exactly like C<gv_fetchmeth_pvn>.
758
759The other forms do have a C<flags> parameter, and differ only in how the glob
760name is specified.
761
762In C<gv_fetchmeth_pv>, C<name> is a C language NUL-terminated string.
763
764In C<gv_fetchmeth_pvn>, C<name> points to the first byte of the name, and an
765additional parameter, C<len>, specifies its length in bytes. Hence, the name
766may contain embedded-NUL characters.
767
768In C<gv_fetchmeth_sv>, C<*name> is an SV, and the name is the PV extracted from
769that, using L</C<SvPV>>. If the SV is marked as being in UTF-8, the extracted
770PV will also be.
771
772=for apidoc Amnh||GV_SUPER
e6919483
BF
773
774=cut
775*/
776
777GV *
778Perl_gv_fetchmeth_sv(pTHX_ HV *stash, SV *namesv, I32 level, U32 flags)
779{
c290e187 780 char *namepv;
781 STRLEN namelen;
782 PERL_ARGS_ASSERT_GV_FETCHMETH_SV;
783 if (LIKELY(SvPOK_nog(namesv))) /* common case */
14062320
FC
784 return gv_fetchmeth_internal(stash, namesv, NULL, 0, level,
785 flags | SvUTF8(namesv));
c290e187 786 namepv = SvPV(namesv, namelen);
787 if (SvUTF8(namesv)) flags |= SVf_UTF8;
788 return gv_fetchmeth_pvn(stash, namepv, namelen, level, flags);
e6919483
BF
789}
790
e6919483
BF
791
792GV *
793Perl_gv_fetchmeth_pv(pTHX_ HV *stash, const char *name, I32 level, U32 flags)
794{
795 PERL_ARGS_ASSERT_GV_FETCHMETH_PV;
c6afe666 796 return gv_fetchmeth_internal(stash, NULL, name, strlen(name), level, flags);
e6919483
BF
797}
798
e1a479c5
BB
799/* NOTE: No support for tied ISA */
800
c6afe666 801PERL_STATIC_INLINE GV*
802S_gv_fetchmeth_internal(pTHX_ HV* stash, SV* meth, const char* name, STRLEN len, I32 level, U32 flags)
79072805 803{
463ee0b2 804 GV** gvp;
c6afe666 805 HE* he;
e1a479c5
BB
806 AV* linear_av;
807 SV** linear_svp;
808 SV* linear_sv;
aae43805 809 HV* cstash, *cachestash;
e1a479c5
BB
810 GV* candidate = NULL;
811 CV* cand_cv = NULL;
e1a479c5 812 GV* topgv = NULL;
bfcb3514 813 const char *hvname;
448aac91 814 STRLEN hvnamelen;
c6afe666 815 I32 create = (level >= 0) ? HV_FETCH_LVALUE : 0;
e1a479c5 816 I32 items;
e1a479c5 817 U32 topgen_cmp;
04f3bf56 818 U32 is_utf8 = flags & SVf_UTF8;
a0d0e21e 819
af09ea45
IK
820 /* UNIVERSAL methods should be callable without a stash */
821 if (!stash) {
1604cfb0
MS
822 create = 0; /* probably appropriate */
823 if(!(stash = gv_stashpvs("UNIVERSAL", 0)))
824 return 0;
af09ea45
IK
825 }
826
e1a479c5
BB
827 assert(stash);
828
bfcb3514 829 hvname = HvNAME_get(stash);
448aac91 830 hvnamelen = HvNAMELEN_get(stash);
bfcb3514 831 if (!hvname)
e1a479c5 832 Perl_croak(aTHX_ "Can't use anonymous symbol table for method lookup");
e27ad1f2 833
e1a479c5 834 assert(hvname);
55df6700 835 assert(name || meth);
463ee0b2 836
aae43805 837 DEBUG_o( Perl_deb(aTHX_ "Looking for %smethod %s in package %s\n",
1604cfb0
MS
838 flags & GV_SUPER ? "SUPER " : "",
839 name ? name : SvPV_nolen(meth), hvname) );
44a8e56a 840
dd69841b 841 topgen_cmp = HvMROMETA(stash)->cache_gen + PL_sub_generation;
e1a479c5 842
aae43805 843 if (flags & GV_SUPER) {
1604cfb0
MS
844 if (!HvAUX(stash)->xhv_mro_meta->super)
845 HvAUX(stash)->xhv_mro_meta->super = newHV();
846 cachestash = HvAUX(stash)->xhv_mro_meta->super;
aae43805
FC
847 }
848 else cachestash = stash;
849
e1a479c5 850 /* check locally for a real method or a cache entry */
c6afe666 851 he = (HE*)hv_common(
1cde3371 852 cachestash, meth, name, len, is_utf8 ? HVhek_UTF8 : 0, create, NULL, 0
c6afe666 853 );
854 if (he) gvp = (GV**)&HeVAL(he);
855 else gvp = NULL;
856
e1a479c5
BB
857 if(gvp) {
858 topgv = *gvp;
0f8d4b5e 859 have_gv:
e1a479c5
BB
860 assert(topgv);
861 if (SvTYPE(topgv) != SVt_PVGV)
55df6700
FC
862 {
863 if (!name)
864 name = SvPV_nomg(meth, len);
04ec7e59 865 gv_init_pvn(topgv, stash, name, len, GV_ADDMULTI|is_utf8);
55df6700 866 }
e1a479c5
BB
867 if ((cand_cv = GvCV(topgv))) {
868 /* If genuine method or valid cache entry, use it */
869 if (!GvCVGEN(topgv) || GvCVGEN(topgv) == topgen_cmp) {
870 return topgv;
871 }
872 else {
873 /* stale cache entry, junk it and move on */
1604cfb0
MS
874 SvREFCNT_dec_NN(cand_cv);
875 GvCV_set(topgv, NULL);
876 cand_cv = NULL;
877 GvCVGEN(topgv) = 0;
e1a479c5
BB
878 }
879 }
880 else if (GvCVGEN(topgv) == topgen_cmp) {
881 /* cache indicates no such method definitively */
882 return 0;
883 }
1604cfb0
MS
884 else if (stash == cachestash
885 && len > 1 /* shortest is uc */
b59bf0b2 886 && memEQs(hvname, HvNAMELEN_get(stash), "CORE")
87566176 887 && S_maybe_add_coresub(aTHX_ NULL,topgv,name,len))
1604cfb0 888 goto have_gv;
463ee0b2 889 }
79072805 890
aae43805 891 linear_av = mro_get_linear_isa(stash); /* has ourselves at the top of the list */
e1a479c5
BB
892 linear_svp = AvARRAY(linear_av) + 1; /* skip over self */
893 items = AvFILLp(linear_av); /* no +1, to skip over self */
894 while (items--) {
895 linear_sv = *linear_svp++;
896 assert(linear_sv);
897 cstash = gv_stashsv(linear_sv, 0);
898
dd69841b 899 if (!cstash) {
448aac91
MM
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") )
904 ) {
905 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
906 "Can't locate package %" SVf " for @%" HEKf "::ISA",
907 SVfARG(linear_sv),
908 HEKfARG(HvNAME_HEK(stash)));
909
910 } else if( memEQs( name, len, "AUTOLOAD") ) {
911 /* gobble this warning */
912 } else {
913 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
914 "While trying to resolve method call %.*s->%.*s()"
39629dcf
YO
915 " can not locate package %" SVf_QUOTEDPREFIX " yet it is mentioned in @%.*s::ISA"
916 " (perhaps you forgot to load %" SVf_QUOTEDPREFIX "?)",
29a3370f
N
917 (int) hvnamelen, hvname,
918 (int) len, name,
448aac91 919 SVfARG(linear_sv),
29a3370f 920 (int) hvnamelen, hvname,
448aac91
MM
921 SVfARG(linear_sv));
922 }
923 }
e1a479c5
BB
924 continue;
925 }
9607fc9c 926
e1a479c5
BB
927 assert(cstash);
928
202cd98a
SA
929 gvp = (GV**)hv_common(
930 cstash, meth, name, len, is_utf8 ? HVhek_UTF8 : 0, HV_FETCH_JUST_SV, NULL, 0
931 );
0f8d4b5e
FC
932 if (!gvp) {
933 if (len > 1 && HvNAMELEN_get(cstash) == 4) {
934 const char *hvname = HvNAME(cstash); assert(hvname);
c8b388b0 935 if (strBEGINs(hvname, "CORE")
0f8d4b5e 936 && (candidate =
87566176 937 S_maybe_add_coresub(aTHX_ cstash,NULL,name,len)
0f8d4b5e
FC
938 ))
939 goto have_candidate;
940 }
941 continue;
942 }
943 else candidate = *gvp;
944 have_candidate:
e1a479c5 945 assert(candidate);
04f3bf56 946 if (SvTYPE(candidate) != SVt_PVGV)
04ec7e59 947 gv_init_pvn(candidate, cstash, name, len, GV_ADDMULTI|is_utf8);
e1a479c5
BB
948 if (SvTYPE(candidate) == SVt_PVGV && (cand_cv = GvCV(candidate)) && !GvCVGEN(candidate)) {
949 /*
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)
953 */
954 if (topgv && (GvREFCNT(topgv) == 1) && (CvROOT(cand_cv) || CvXSUB(cand_cv))) {
9bfbb681
VP
955 CV *old_cv = GvCV(topgv);
956 SvREFCNT_dec(old_cv);
e1a479c5 957 SvREFCNT_inc_simple_void_NN(cand_cv);
c43ae56f 958 GvCV_set(topgv, cand_cv);
e1a479c5
BB
959 GvCVGEN(topgv) = topgen_cmp;
960 }
1604cfb0 961 return candidate;
e1a479c5
BB
962 }
963 }
9607fc9c 964
e1a479c5 965 /* Check UNIVERSAL without caching */
5f65868c 966 if((level == 0 || level == -1) && !(flags & GV_NOUNIVERSAL)) {
55df6700
FC
967 candidate = gv_fetchmeth_internal(NULL, meth, name, len, 1,
968 flags &~GV_SUPER);
e1a479c5
BB
969 if(candidate) {
970 cand_cv = GvCV(candidate);
971 if (topgv && (GvREFCNT(topgv) == 1) && (CvROOT(cand_cv) || CvXSUB(cand_cv))) {
9bfbb681
VP
972 CV *old_cv = GvCV(topgv);
973 SvREFCNT_dec(old_cv);
e1a479c5 974 SvREFCNT_inc_simple_void_NN(cand_cv);
c43ae56f 975 GvCV_set(topgv, cand_cv);
e1a479c5
BB
976 GvCVGEN(topgv) = topgen_cmp;
977 }
978 return candidate;
979 }
980 }
981
64d11743 982 if (topgv && GvREFCNT(topgv) == 1 && !(flags & GV_NOUNIVERSAL)) {
e1a479c5
BB
983 /* cache the fact that the method is not defined */
984 GvCVGEN(topgv) = topgen_cmp;
a0d0e21e
LW
985 }
986
79072805
LW
987 return 0;
988}
989
c6afe666 990GV *
991Perl_gv_fetchmeth_pvn(pTHX_ HV *stash, const char *name, STRLEN len, I32 level, U32 flags)
992{
993 PERL_ARGS_ASSERT_GV_FETCHMETH_PVN;
994 return gv_fetchmeth_internal(stash, NULL, name, len, level, flags);
995}
996
954c1994 997/*
460e5730
FC
998=for apidoc gv_fetchmeth_autoload
999
1000This is the old form of L</gv_fetchmeth_pvn_autoload>, which has no flags
1001parameter.
1002
d21989ed 1003=for apidoc gv_fetchmeth_sv_autoload
611c1e95 1004
d21989ed
BF
1005Exactly like L</gv_fetchmeth_pvn_autoload>, but takes the name string in the form
1006of an SV instead of a string/length pair.
1007
1008=cut
1009*/
1010
1011GV *
1012Perl_gv_fetchmeth_sv_autoload(pTHX_ HV *stash, SV *namesv, I32 level, U32 flags)
1013{
1014 char *namepv;
1015 STRLEN namelen;
1016 PERL_ARGS_ASSERT_GV_FETCHMETH_SV_AUTOLOAD;
1017 namepv = SvPV(namesv, namelen);
1018 if (SvUTF8(namesv))
1019 flags |= SVf_UTF8;
1020 return gv_fetchmeth_pvn_autoload(stash, namepv, namelen, level, flags);
1021}
1022
1023/*
1024=for apidoc gv_fetchmeth_pv_autoload
1025
1026Exactly like L</gv_fetchmeth_pvn_autoload>, but takes a nul-terminated string
1027instead of a string/length pair.
1028
1029=cut
1030*/
1031
1032GV *
1033Perl_gv_fetchmeth_pv_autoload(pTHX_ HV *stash, const char *name, I32 level, U32 flags)
1034{
1035 PERL_ARGS_ASSERT_GV_FETCHMETH_PV_AUTOLOAD;
1036 return gv_fetchmeth_pvn_autoload(stash, name, strlen(name), level, flags);
1037}
1038
1039/*
1040=for apidoc gv_fetchmeth_pvn_autoload
1041
796b6530 1042Same as C<gv_fetchmeth_pvn()>, but looks for autoloaded subroutines too.
611c1e95
IZ
1043Returns a glob for the subroutine.
1044
1045For an autoloaded subroutine without a GV, will create a GV even
796b6530 1046if C<level < 0>. For an autoloaded subroutine without a stub, C<GvCV()>
611c1e95
IZ
1047of the result may be zero.
1048
796b6530 1049Currently, the only significant value for C<flags> is C<SVf_UTF8>.
d21989ed 1050
611c1e95
IZ
1051=cut
1052*/
1053
1054GV *
d21989ed 1055Perl_gv_fetchmeth_pvn_autoload(pTHX_ HV *stash, const char *name, STRLEN len, I32 level, U32 flags)
611c1e95 1056{
499321d3 1057 GV *gv = gv_fetchmeth_pvn(stash, name, len, level, flags);
611c1e95 1058
d21989ed 1059 PERL_ARGS_ASSERT_GV_FETCHMETH_PVN_AUTOLOAD;
7918f24d 1060
611c1e95 1061 if (!gv) {
1604cfb0
MS
1062 CV *cv;
1063 GV **gvp;
1064
1065 if (!stash)
1066 return NULL; /* UNIVERSAL::AUTOLOAD could cause trouble */
1067 if (len == S_autolen && memEQ(name, S_autoload, S_autolen))
1068 return NULL;
1069 if (!(gv = gv_fetchmeth_pvn(stash, S_autoload, S_autolen, FALSE, flags)))
1070 return NULL;
1071 cv = GvCV(gv);
1072 if (!(CvROOT(cv) || CvXSUB(cv)))
1073 return NULL;
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,
c60dbbc3 1078 (flags & SVf_UTF8) ? -(I32)len : (I32)len, (level >= 0));
1604cfb0
MS
1079 if (!gvp)
1080 return NULL;
1081 return *gvp;
611c1e95
IZ
1082 }
1083 return gv;
1084}
1085
1086/*
954c1994
GS
1087=for apidoc gv_fetchmethod_autoload
1088
1089Returns the glob which contains the subroutine to call to invoke the method
1090on the C<stash>. In fact in the presence of autoloading this may be the
796b6530 1091glob for "AUTOLOAD". In this case the corresponding variable C<$AUTOLOAD> is
b267980d 1092already setup.
954c1994
GS
1093
1094The third parameter of C<gv_fetchmethod_autoload> determines whether
1095AUTOLOAD lookup is performed if the given method is not present: non-zero
b267980d 1096means yes, look for AUTOLOAD; zero means no, don't look for AUTOLOAD.
954c1994 1097Calling C<gv_fetchmethod> is equivalent to calling C<gv_fetchmethod_autoload>
b267980d 1098with a non-zero C<autoload> parameter.
954c1994 1099
cec2d7b1
FC
1100These functions grant C<"SUPER"> token
1101as a prefix of the method name. Note
954c1994
GS
1102that if you want to keep the returned glob for a long time, you need to
1103check for it being "AUTOLOAD", since at the later time the call may load a
796b6530 1104different subroutine due to C<$AUTOLOAD> changing its value. Use the glob
cec2d7b1 1105created as a side effect to do this.
954c1994 1106
cec2d7b1
FC
1107These functions have the same side-effects as C<gv_fetchmeth> with
1108C<level==0>. The warning against passing the GV returned by
1109C<gv_fetchmeth> to C<call_sv> applies equally to these functions.
954c1994
GS
1110
1111=cut
1112*/
1113
dc848c6f 1114GV *
864dbfa3 1115Perl_gv_fetchmethod_autoload(pTHX_ HV *stash, const char *name, I32 autoload)
dc848c6f 1116{
547bb267
NC
1117 PERL_ARGS_ASSERT_GV_FETCHMETHOD_AUTOLOAD;
1118
256d1bb2
NC
1119 return gv_fetchmethod_flags(stash, name, autoload ? GV_AUTOLOAD : 0);
1120}
1121
44130a26
BF
1122GV *
1123Perl_gv_fetchmethod_sv_flags(pTHX_ HV *stash, SV *namesv, U32 flags)
1124{
1125 char *namepv;
1126 STRLEN namelen;
1127 PERL_ARGS_ASSERT_GV_FETCHMETHOD_SV_FLAGS;
1128 namepv = SvPV(namesv, namelen);
1129 if (SvUTF8(namesv))
1130 flags |= SVf_UTF8;
1131 return gv_fetchmethod_pvn_flags(stash, namepv, namelen, flags);
1132}
1133
1134GV *
1135Perl_gv_fetchmethod_pv_flags(pTHX_ HV *stash, const char *name, U32 flags)
1136{
1137 PERL_ARGS_ASSERT_GV_FETCHMETHOD_PV_FLAGS;
1138 return gv_fetchmethod_pvn_flags(stash, name, strlen(name), flags);
1139}
1140
256d1bb2 1141GV *
44130a26 1142Perl_gv_fetchmethod_pvn_flags(pTHX_ HV *stash, const char *name, const STRLEN len, U32 flags)
256d1bb2 1143{
65308f87
YO
1144 const char * const origname = name;
1145 const char * const name_end = name + len;
e2cace1e 1146 const char *last_separator = NULL;
a0d0e21e 1147 GV* gv;
0dae17bd 1148 HV* ostash = stash;
ad64d0ec 1149 SV *const error_report = MUTABLE_SV(stash);
256d1bb2
NC
1150 const U32 autoload = flags & GV_AUTOLOAD;
1151 const U32 do_croak = flags & GV_CROAK;
14d1dfbd 1152 const U32 is_utf8 = flags & SVf_UTF8;
0dae17bd 1153
44130a26 1154 PERL_ARGS_ASSERT_GV_FETCHMETHOD_PVN_FLAGS;
7918f24d 1155
eff494dd 1156 if (SvTYPE(stash) < SVt_PVHV)
1604cfb0 1157 stash = NULL;
c9bf4021 1158 else {
1604cfb0
MS
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. */
c9bf4021 1162 }
b267980d 1163
cfb73676
YO
1164 {
1165 /* check if the method name is fully qualified or
1166 * not, and separate the package name from the actual
1167 * method name.
1168 *
1169 * leaves last_separator pointing to the beginning of the
1170 * last package separator (either ' or ::) or 0
1171 * if none was found.
1172 *
1173 * leaves name pointing at the beginning of the
1174 * method name.
1175 */
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;
1182 }
1183 else if (name_cursor < name_em1 && *name_cursor == ':' && name_cursor[1] == ':') {
1184 last_separator = name_cursor++;
1185 name = name_cursor + 1;
1186 }
1187 }
a0d0e21e 1188 }
cfb73676
YO
1189
1190 /* did we find a separator? */
e2cace1e 1191 if (last_separator) {
9b7f107c
YO
1192 STRLEN sep_len= last_separator - origname;
1193 if ( memEQs(origname, sep_len, "SUPER")) {
1604cfb0
MS
1194 /* ->SUPER::method should really be looked up in original stash */
1195 stash = CopSTASH(PL_curcop);
1196 flags |= GV_SUPER;
1197 DEBUG_o( Perl_deb(aTHX_ "Treating %s as %s::%s\n",
1198 origname, HvENAME_get(stash), name) );
1199 }
47324b4e 1200 else if ( sep_len >= 7 &&
1604cfb0 1201 strBEGINs(last_separator - 7, "::SUPER")) {
0c6362ad 1202 /* don't autovivify if ->NoSuchStash::SUPER::method */
9b7f107c 1203 stash = gv_stashpvn(origname, sep_len - 7, is_utf8);
1604cfb0
MS
1204 if (stash) flags |= GV_SUPER;
1205 }
1206 else {
0c6362ad 1207 /* don't autovivify if ->NoSuchStash::method */
9b7f107c 1208 stash = gv_stashpvn(origname, sep_len, is_utf8);
1604cfb0
MS
1209 }
1210 ostash = stash;
4633a7c4
LW
1211 }
1212
65308f87 1213 gv = gv_fetchmeth_pvn(stash, name, name_end - name, 0, flags);
a0d0e21e 1214 if (!gv) {
1604cfb0
MS
1215 /* This is the special case that exempts Foo->import and
1216 Foo->unimport from being an error even if there's no
1217 import/unimport subroutine */
1218 if (strEQ(name,"import") || strEQ(name,"unimport")) {
1219 gv = (GV*)sv_2mortal((SV*)newCONSTSUB_flags(NULL,
1220 NULL, 0, 0, NULL));
1221 } else if (autoload)
1222 gv = gv_autoload_pvn(
1223 ostash, name, name_end - name, GV_AUTOLOAD_ISMETHOD|flags
1224 );
1225 if (!gv && do_croak) {
1226 /* Right now this is exclusively for the benefit of S_method_common
1227 in pp_hot.c */
1228 if (stash) {
1229 /* If we can't find an IO::File method, it might be a call on
1230 * a filehandle. If IO:File has not been loaded, try to
1231 * require it first instead of croaking */
1232 const char *stash_name = HvNAME_get(stash);
1233 if (stash_name && memEQs(stash_name, HvNAMELEN_get(stash), "IO::File")
1234 && !Perl_hv_common(aTHX_ GvHVn(PL_incgv), NULL,
1235 STR_WITH_LEN("IO/File.pm"), 0,
1236 HV_FETCH_ISEXISTS, NULL, 0)
1237 ) {
1238 require_pv("IO/File.pm");
1239 gv = gv_fetchmeth_pvn(stash, name, name_end - name, 0, flags);
1240 if (gv)
1241 return gv;
1242 }
1243 Perl_croak(aTHX_
33ef5d2c
YO
1244 "Can't locate object method %" UTF8f_QUOTEDPREFIX ""
1245 " via package %" HEKf_QUOTEDPREFIX,
1604cfb0 1246 UTF8fARG(is_utf8, name_end - name, name),
d0c0e7dd 1247 HEKfARG(HvNAME_HEK(stash)));
1604cfb0
MS
1248 }
1249 else {
ecad31f0 1250 SV* packnamesv;
256d1bb2 1251
1604cfb0
MS
1252 if (last_separator) {
1253 packnamesv = newSVpvn_flags(origname, last_separator - origname,
ecad31f0 1254 SVs_TEMP | is_utf8);
1604cfb0
MS
1255 } else {
1256 packnamesv = error_report;
1257 }
1258
1259 Perl_croak(aTHX_
33ef5d2c
YO
1260 "Can't locate object method %" UTF8f_QUOTEDPREFIX ""
1261 " via package %" SVf_QUOTEDPREFIX ""
1262 " (perhaps you forgot to load %" SVf_QUOTEDPREFIX "?)",
1604cfb0 1263 UTF8fARG(is_utf8, name_end - name, name),
ecad31f0 1264 SVfARG(packnamesv), SVfARG(packnamesv));
1604cfb0
MS
1265 }
1266 }
463ee0b2 1267 }
dc848c6f 1268 else if (autoload) {
1604cfb0
MS
1269 CV* const cv = GvCV(gv);
1270 if (!CvROOT(cv) && !CvXSUB(cv)) {
1271 GV* stubgv;
1272 GV* autogv;
1273
1274 if (CvANON(cv) || CvLEXICAL(cv))
1275 stubgv = gv;
1276 else {
1277 stubgv = CvGV(cv);
1278 if (GvCV(stubgv) != cv) /* orphaned import */
1279 stubgv = gv;
1280 }
c8416c26
BF
1281 autogv = gv_autoload_pvn(GvSTASH(stubgv),
1282 GvNAME(stubgv), GvNAMELEN(stubgv),
1283 GV_AUTOLOAD_ISMETHOD
1284 | (GvNAMEUTF8(stubgv) ? SVf_UTF8 : 0));
1604cfb0
MS
1285 if (autogv)
1286 gv = autogv;
1287 }
dc848c6f 1288 }
44a8e56a 1289
1290 return gv;
1291}
1292
df91ed1f
KW
1293
1294/*
1295=for apidoc gv_autoload_pv
1296=for apidoc_item gv_autoload_pvn
1297=for apidoc_item gv_autoload_sv
1298
1299These each search for an C<AUTOLOAD> method, returning NULL if not found, or
1300else returning a pointer to its GV, while setting the package
1301L<C<$AUTOLOAD>|perlobj/AUTOLOAD> variable to C<name> (fully qualified). Also,
1302if found and the GV's CV is an XSUB, the CV's PV will be set to C<name>, and
1303its stash will be set to the stash of the GV.
1304
1305Searching is done in L<C<MRO> order|perlmroapi>, as specified in
1306L</C<gv_fetchmeth>>, beginning with C<stash> if it isn't NULL.
1307
1308The forms differ only in how C<name> is specified.
1309
1310In C<gv_autoload_pv>, C<namepv> is a C language NUL-terminated string.
1311
1312In C<gv_autoload_pvn>, C<name> points to the first byte of the name, and an
1313additional parameter, C<len>, specifies its length in bytes. Hence, C<*name>
1314may contain embedded-NUL characters.
1315
1316In C<gv_autoload_sv>, C<*namesv> is an SV, and the name is the PV extracted
1317from that using L</C<SvPV>>. If the SV is marked as being in UTF-8, the
1318extracted PV will also be.
1319
1320=cut
1321*/
1322
44a8e56a 1323GV*
0eeb01b9 1324Perl_gv_autoload_sv(pTHX_ HV *stash, SV* namesv, U32 flags)
5fba3c91
BF
1325{
1326 char *namepv;
1327 STRLEN namelen;
0fe84f7c 1328 PERL_ARGS_ASSERT_GV_AUTOLOAD_SV;
5fba3c91
BF
1329 namepv = SvPV(namesv, namelen);
1330 if (SvUTF8(namesv))
1331 flags |= SVf_UTF8;
0eeb01b9 1332 return gv_autoload_pvn(stash, namepv, namelen, flags);
5fba3c91
BF
1333}
1334
1335GV*
0eeb01b9 1336Perl_gv_autoload_pv(pTHX_ HV *stash, const char *namepv, U32 flags)
5fba3c91 1337{
0fe84f7c 1338 PERL_ARGS_ASSERT_GV_AUTOLOAD_PV;
0eeb01b9 1339 return gv_autoload_pvn(stash, namepv, strlen(namepv), flags);
5fba3c91
BF
1340}
1341
1342GV*
0eeb01b9 1343Perl_gv_autoload_pvn(pTHX_ HV *stash, const char *name, STRLEN len, U32 flags)
44a8e56a 1344{
44a8e56a 1345 GV* gv;
1346 CV* cv;
1347 HV* varstash;
1348 GV* vargv;
1349 SV* varsv;
c8416c26
BF
1350 SV *packname = NULL;
1351 U32 is_utf8 = flags & SVf_UTF8 ? SVf_UTF8 : 0;
44a8e56a 1352
0fe84f7c 1353 PERL_ARGS_ASSERT_GV_AUTOLOAD_PVN;
7918f24d 1354
7edbdc6b 1355 if (len == S_autolen && memEQ(name, S_autoload, S_autolen))
1604cfb0 1356 return NULL;
0dae17bd 1357 if (stash) {
1604cfb0 1358 if (SvTYPE(stash) < SVt_PVHV) {
c8416c26
BF
1359 STRLEN packname_len = 0;
1360 const char * const packname_ptr = SvPV_const(MUTABLE_SV(stash), packname_len);
1361 packname = newSVpvn_flags(packname_ptr, packname_len,
1362 SVs_TEMP | SvUTF8(stash));
1604cfb0
MS
1363 stash = NULL;
1364 }
1365 else
518db96a 1366 packname = newSVhek_mortal(HvNAME_HEK(stash));
1604cfb0 1367 if (flags & GV_SUPER) sv_catpvs(packname, "::SUPER");
0dae17bd 1368 }
257dc59d 1369 if (!(gv = gv_fetchmeth_pvn(stash, S_autoload, S_autolen, FALSE,
1604cfb0
MS
1370 is_utf8 | (flags & GV_SUPER))))
1371 return NULL;
dc848c6f 1372 cv = GvCV(gv);
1373
adb5a9ae 1374 if (!(CvROOT(cv) || CvXSUB(cv)))
1604cfb0 1375 return NULL;
ed850460 1376
dc848c6f 1377 /*
64278e8c 1378 * Inheriting AUTOLOAD for non-methods no longer works
dc848c6f 1379 */
0eeb01b9
FC
1380 if (
1381 !(flags & GV_AUTOLOAD_ISMETHOD)
1382 && (GvCVGEN(gv) || GvSTASH(gv) != stash)
041457d9 1383 )
64278e8c
A
1384 Perl_croak(aTHX_ "Use of inherited AUTOLOAD for non-method %" SVf
1385 "::%" UTF8f "() is no longer allowed",
1604cfb0 1386 SVfARG(packname),
b17a0679 1387 UTF8fARG(is_utf8, len, name));
44a8e56a 1388
aed2304a 1389 if (CvISXSUB(cv)) {
51254cb2 1390 /* Instead of forcing the XSUB to do another lookup for $AUTOLOAD
bb619f37
FC
1391 * and split that value on the last '::', pass along the same data
1392 * via the SvPVX field in the CV, and the stash in CvSTASH.
8fa6a409
FC
1393 *
1394 * Due to an unfortunate accident of history, the SvPVX field
51254cb2
KW
1395 * serves two purposes. It is also used for the subroutine's
1396 * prototype. Since SvPVX has been documented as returning the sub
1397 * name for a long time, but not as returning the prototype, we have to
1398 * preserve the SvPVX AUTOLOAD behaviour and put the prototype
8fa6a409
FC
1399 * elsewhere.
1400 *
1401 * We put the prototype in the same allocated buffer, but after
1402 * the sub name. The SvPOK flag indicates the presence of a proto-
1403 * type. The CvAUTOLOAD flag indicates the presence of a sub name.
1404 * If both flags are on, then SvLEN is used to indicate the end of
1405 * the prototype (artificially lower than what is actually allo-
1406 * cated), at the risk of having to reallocate a few bytes unneces-
1407 * sarily--but that should happen very rarely, if ever.
1408 *
1409 * We use SvUTF8 for both prototypes and sub names, so if one is
1410 * UTF8, the other must be upgraded.
adb5a9ae 1411 */
1604cfb0
MS
1412 CvSTASH_set(cv, stash);
1413 if (SvPOK(cv)) { /* Ouch! */
1414 SV * const tmpsv = newSVpvn_flags(name, len, is_utf8);
1415 STRLEN ulen;
1416 const char *proto = CvPROTO(cv);
1417 assert(proto);
1418 if (SvUTF8(cv))
1419 sv_utf8_upgrade_flags_grow(tmpsv, 0, CvPROTOLEN(cv) + 2);
1420 ulen = SvCUR(tmpsv);
1421 SvCUR_set(tmpsv, SvCUR(tmpsv) + 1); /* include null in string */
1422 sv_catpvn_flags(
1423 tmpsv, proto, CvPROTOLEN(cv), SV_CATBYTES*!SvUTF8(cv)
1424 );
1425 SvTEMP_on(tmpsv); /* Allow theft */
1426 sv_setsv_nomg((SV *)cv, tmpsv);
1427 SvTEMP_off(tmpsv);
1428 SvREFCNT_dec_NN(tmpsv);
1429 SvLEN_set(cv, SvCUR(cv) + 1);
1430 SvCUR_set(cv, ulen);
1431 }
1432 else {
1433 sv_setpvn((SV *)cv, name, len);
1434 SvPOK_off(cv);
1435 if (is_utf8)
c8416c26 1436 SvUTF8_on(cv);
1604cfb0
MS
1437 else SvUTF8_off(cv);
1438 }
1439 CvAUTOLOAD_on(cv);
adb5a9ae 1440 }
adb5a9ae 1441
44a8e56a 1442 /*
1443 * Given &FOO::AUTOLOAD, set $FOO::AUTOLOAD to desired function name.
1444 * The subroutine's original name may not be "AUTOLOAD", so we don't
1445 * use that, but for lack of anything better we will use the sub's
1446 * original package to look up $AUTOLOAD.
1447 */
18691622 1448 varstash = CvNAMED(cv) ? CvSTASH(cv) : GvSTASH(CvGV(cv));
5c7983e5 1449 vargv = *(GV**)hv_fetch(varstash, S_autoload, S_autolen, TRUE);
3d35f11b
GS
1450 ENTER;
1451
c69033f2 1452 if (!isGV(vargv)) {
1604cfb0 1453 gv_init_pvn(vargv, varstash, S_autoload, S_autolen, 0);
c69033f2 1454#ifdef PERL_DONT_CREATE_GVSV
8fcb2425 1455 GvSV(vargv) = newSV_type(SVt_NULL);
c69033f2
NC
1456#endif
1457 }
3d35f11b 1458 LEAVE;
e203899d 1459 varsv = GvSVn(vargv);
4bac9ae4
CS
1460 SvTAINTED_off(varsv); /* previous $AUTOLOAD taint is obsolete */
1461 /* XXX: this process is not careful to avoid extra magic gets and sets; tied $AUTOLOAD will get noise */
c8416c26 1462 sv_setsv(varsv, packname);
396482e1 1463 sv_catpvs(varsv, "::");
d40bf27b
NC
1464 /* Ensure SvSETMAGIC() is called if necessary. In particular, to clear
1465 tainting if $FOO::AUTOLOAD was previously tainted, but is not now. */
61a9130e 1466 sv_catpvn_flags(
1604cfb0
MS
1467 varsv, name, len,
1468 SV_SMAGIC|(is_utf8 ? SV_CATUTF8 : SV_CATBYTES)
61a9130e 1469 );
c8416c26
BF
1470 if (is_utf8)
1471 SvUTF8_on(varsv);
a0d0e21e
LW
1472 return gv;
1473}
1474
44a2ac75
YO
1475
1476/* require_tie_mod() internal routine for requiring a module
486ec47a 1477 * that implements the logic of automatic ties like %! and %-
e94ea821
FC
1478 * It loads the module and then calls the _tie_it subroutine
1479 * with the passed gv as an argument.
44a2ac75
YO
1480 *
1481 * The "gv" parameter should be the glob.
ee33cc1a 1482 * "varname" holds the 1-char name of the var, used for error messages.
45cbc99a 1483 * "namesv" holds the module name. Its refcount will be decremented.
45cbc99a 1484 * "flags": if flag & 1 then save the scalar before loading.
44a2ac75
YO
1485 * For the protection of $! to work (it is set by this routine)
1486 * the sv slot must already be magicalized.
d2c93421 1487 */
e94ea821 1488STATIC void
ee33cc1a 1489S_require_tie_mod(pTHX_ GV *gv, const char varname, const char * name,
a1683482 1490 STRLEN len, const U32 flags)
d2c93421 1491{
e94ea821 1492 const SV * const target = varname == '[' ? GvSV(gv) : (SV *)GvHV(gv);
45cbc99a 1493
7918f24d
NC
1494 PERL_ARGS_ASSERT_REQUIRE_TIE_MOD;
1495
e94ea821
FC
1496 /* If it is not tied */
1497 if (!target || !SvRMAGICAL(target)
1498 || !mg_find(target,
1499 varname == '[' ? PERL_MAGIC_tiedscalar : PERL_MAGIC_tied))
1500 {
1501 HV *stash;
1502 GV **gvp;
1503 dSP;
1504
655f5b26 1505 PUSHSTACKi(PERLSI_MAGIC);
e94ea821 1506 ENTER;
e94ea821 1507
6881372e
FC
1508#define GET_HV_FETCH_TIE_FUNC \
1509 ( (gvp = (GV **)hv_fetchs(stash, "_tie_it", 0)) \
1510 && *gvp \
1511 && ( (isGV(*gvp) && GvCV(*gvp)) \
1512 || (SvROK(*gvp) && SvTYPE(SvRV(*gvp)) == SVt_PVCV) ) \
1513 )
e94ea821
FC
1514
1515 /* Load the module if it is not loaded. */
360cebfd 1516 if (!(stash = gv_stashpvn(name, len, 0))
6881372e 1517 || ! GET_HV_FETCH_TIE_FUNC)
e94ea821 1518 {
1604cfb0
MS
1519 SV * const module = newSVpvn(name, len);
1520 const char type = varname == '[' ? '$' : '%';
1521 if ( flags & 1 )
1522 save_scalar(gv);
1523 Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT, module, NULL);
1524 assert(sp == PL_stack_sp);
1525 stash = gv_stashpvn(name, len, 0);
1526 if (!stash)
1527 Perl_croak(aTHX_ "panic: Can't use %c%c because %s is not available",
1528 type, varname, name);
1529 else if (! GET_HV_FETCH_TIE_FUNC)
1530 Perl_croak(aTHX_ "panic: Can't use %c%c because %s does not define _tie_it",
1531 type, varname, name);
e94ea821
FC
1532 }
1533 /* Now call the tie function. It should be in *gvp. */
6881372e 1534 assert(gvp); assert(*gvp);
e94ea821
FC
1535 PUSHMARK(SP);
1536 XPUSHs((SV *)gv);
1537 PUTBACK;
1538 call_sv((SV *)*gvp, G_VOID|G_DISCARD);
1539 LEAVE;
655f5b26 1540 POPSTACK;
d2c93421
RH
1541 }
1542}
1543
7c719134
YO
1544/* add a require_tie_mod_s - the _s suffix is similar to pvs type suffixes,
1545 * IOW it means we do STR_WITH_LEN() ourselves and the user should pass in
1546 * a true string WITHOUT a len.
1547 */
1548#define require_tie_mod_s(gv, varname, name, flags) \
1549 S_require_tie_mod(aTHX_ gv, varname, STR_WITH_LEN(name), flags)
1550
954c1994
GS
1551/*
1552=for apidoc gv_stashpv
1553
da51bb9b 1554Returns a pointer to the stash for a specified package. Uses C<strlen> to
75c442e4 1555determine the length of C<name>, then calls C<gv_stashpvn()>.
954c1994
GS
1556
1557=cut
1558*/
1559
a0d0e21e 1560HV*
864dbfa3 1561Perl_gv_stashpv(pTHX_ const char *name, I32 create)
a0d0e21e 1562{
7918f24d 1563 PERL_ARGS_ASSERT_GV_STASHPV;
dc437b57 1564 return gv_stashpvn(name, strlen(name), create);
1565}
1566
bc96cb06
SH
1567/*
1568=for apidoc gv_stashpvn
1569
da51bb9b
NC
1570Returns a pointer to the stash for a specified package. The C<namelen>
1571parameter indicates the length of the C<name>, in bytes. C<flags> is passed
1572to C<gv_fetchpvn_flags()>, so if set to C<GV_ADD> then the package will be
1573created if it does not already exist. If the package does not exist and
796b6530 1574C<flags> is 0 (or any other setting that does not create packages) then C<NULL>
da51bb9b
NC
1575is returned.
1576
566a4718
YO
1577Flags may be one of:
1578
52e47e22
KW
1579 GV_ADD Create and initialize the package if doesn't
1580 already exist
1581 GV_NOADD_NOINIT Don't create the package,
1582 GV_ADDMG GV_ADD iff the GV is magical
1583 GV_NOINIT GV_ADD, but don't initialize
1584 GV_NOEXPAND Don't expand SvOK() entries to PVGV
1585 SVf_UTF8 The name is in UTF-8
566a4718 1586
796b6530 1587The most important of which are probably C<GV_ADD> and C<SVf_UTF8>.
bc96cb06 1588
808724c8 1589Note, use of C<gv_stashsv> instead of C<gv_stashpvn> where possible is strongly
1590recommended for performance reasons.
1591
4f8d487a 1592=for apidoc Amnh||GV_ADD
5af38e47
KW
1593=for apidoc Amnh||GV_NOADD_NOINIT
1594=for apidoc Amnh||GV_NOINIT
1595=for apidoc Amnh||GV_NOEXPAND
1596=for apidoc Amnh||GV_ADDMG
1597=for apidoc Amnh||SVf_UTF8
4f8d487a 1598
bc96cb06
SH
1599=cut
1600*/
1601
0eadbdad
YO
1602/*
1603gv_stashpvn_internal
1604
1605Perform the internal bits of gv_stashsvpvn_cached. You could think of this
1606as being one half of the logic. Not to be called except from gv_stashsvpvn_cached().
1607
1608*/
1609
4e7ebec5 1610PERL_STATIC_INLINE HV*
0eadbdad 1611S_gv_stashpvn_internal(pTHX_ const char *name, U32 namelen, I32 flags)
dc437b57 1612{
0cea0058 1613 char smallbuf[128];
46fc3d4c 1614 char *tmpbuf;
a0d0e21e
LW
1615 HV *stash;
1616 GV *tmpgv;
add0ecde 1617 U32 tmplen = namelen + 2;
dc437b57 1618
0eadbdad 1619 PERL_ARGS_ASSERT_GV_STASHPVN_INTERNAL;
7918f24d 1620
add0ecde 1621 if (tmplen <= sizeof smallbuf)
1604cfb0 1622 tmpbuf = smallbuf;
46fc3d4c 1623 else
1604cfb0 1624 Newx(tmpbuf, tmplen, char);
add0ecde
VP
1625 Copy(name, tmpbuf, namelen, char);
1626 tmpbuf[namelen] = ':';
1627 tmpbuf[namelen+1] = ':';
1628 tmpgv = gv_fetchpvn_flags(tmpbuf, tmplen, flags, SVt_PVHV);
46fc3d4c 1629 if (tmpbuf != smallbuf)
1604cfb0 1630 Safefree(tmpbuf);
d2fcb1d6 1631 if (!tmpgv || !isGV_with_GP(tmpgv))
1604cfb0 1632 return NULL;
a0d0e21e 1633 stash = GvHV(tmpgv);
1f656fcf 1634 if (!(flags & ~GV_NOADD_MASK) && !stash) return NULL;
9efb5c72 1635 assert(stash);
2e4090b8 1636 if (!HvHasNAME(stash)) {
1604cfb0 1637 hv_name_set(stash, name, namelen, flags & SVf_UTF8 ? SVf_UTF8 : 0 );
9c913148 1638
1604cfb0
MS
1639 /* FIXME: This is a repeat of logic in gv_fetchpvn_flags */
1640 /* If the containing stash has multiple effective
1641 names, see that this one gets them, too. */
1642 if (HvAUX(GvSTASH(tmpgv))->xhv_name_count)
1643 mro_package_moved(stash, NULL, tmpgv, 1);
1f656fcf 1644 }
a0d0e21e 1645 return stash;
463ee0b2
LW
1646}
1647
808724c8 1648/*
85bf2e91 1649=for apidoc gv_stashsvpvn_cached
808724c8 1650
1651Returns a pointer to the stash for a specified package, possibly
85bf2e91
KW
1652cached. Implements both L<perlapi/C<gv_stashpvn>> and
1653L<perlapi/C<gv_stashsv>>.
808724c8 1654
b8c7ef84 1655Requires one of either C<namesv> or C<namepv> to be non-null.
808724c8 1656
85bf2e91
KW
1657If the flag C<GV_CACHE_ONLY> is set, return the stash only if found in the
1658cache; see L<perlapi/C<gv_stashpvn>> for details on the other C<flags>.
808724c8 1659
85bf2e91
KW
1660Note it is strongly preferred for C<namesv> to be non-null, for performance
1661reasons.
808724c8 1662
85bf2e91
KW
1663=for apidoc Emnh||GV_CACHE_ONLY
1664
1665=cut
808724c8 1666*/
1667
1668#define PERL_ARGS_ASSERT_GV_STASHSVPVN_CACHED \
1669 assert(namesv || name)
1670
c4b6b96d
SA
1671HV*
1672Perl_gv_stashsvpvn_cached(pTHX_ SV *namesv, const char *name, U32 namelen, I32 flags)
4e7ebec5 1673{
1674 HV* stash;
808724c8 1675 HE* he;
1676
1677 PERL_ARGS_ASSERT_GV_STASHSVPVN_CACHED;
1678
1679 he = (HE *)hv_common(
1680 PL_stashcache, namesv, name, namelen,
4e7ebec5 1681 (flags & SVf_UTF8) ? HVhek_UTF8 : 0, 0, NULL, 0
1682 );
808724c8 1683
78e4f28f
DM
1684 if (he) {
1685 SV *sv = HeVAL(he);
1686 HV *hv;
1687 assert(SvIOK(sv));
1688 hv = INT2PTR(HV*, SvIVX(sv));
1689 assert(SvTYPE(hv) == SVt_PVHV);
1690 return hv;
1691 }
d283e876 1692 else if (flags & GV_CACHE_ONLY) return NULL;
4e7ebec5 1693
808724c8 1694 if (namesv) {
1695 if (SvOK(namesv)) { /* prevent double uninit warning */
1696 STRLEN len;
1697 name = SvPV_const(namesv, len);
1698 namelen = len;
1699 flags |= SvUTF8(namesv);
1700 } else {
1701 name = ""; namelen = 0;
1702 }
1703 }
0eadbdad
YO
1704 stash = gv_stashpvn_internal(name, namelen, flags);
1705
4e7ebec5 1706 if (stash && namelen) {
1707 SV* const ref = newSViv(PTR2IV(stash));
0eadbdad 1708 (void)hv_store(PL_stashcache, name,
4e7ebec5 1709 (flags & SVf_UTF8) ? -(I32)namelen : (I32)namelen, ref, 0);
1710 }
808724c8 1711
4e7ebec5 1712 return stash;
1713}
1714
808724c8 1715HV*
1716Perl_gv_stashpvn(pTHX_ const char *name, U32 namelen, I32 flags)
1717{
1718 PERL_ARGS_ASSERT_GV_STASHPVN;
1719 return gv_stashsvpvn_cached(NULL, name, namelen, flags);
1720}
1721
954c1994
GS
1722/*
1723=for apidoc gv_stashsv
1724
fbe13c60
KW
1725Returns a pointer to the stash for a specified package. See
1726C<L</gv_stashpvn>>.
954c1994 1727
fbe13c60
KW
1728Note this interface is strongly preferred over C<gv_stashpvn> for performance
1729reasons.
808724c8 1730
954c1994
GS
1731=cut
1732*/
1733
a0d0e21e 1734HV*
da51bb9b 1735Perl_gv_stashsv(pTHX_ SV *sv, I32 flags)
a0d0e21e 1736{
7918f24d 1737 PERL_ARGS_ASSERT_GV_STASHSV;
808724c8 1738 return gv_stashsvpvn_cached(sv, NULL, 0, flags);
a0d0e21e 1739}
463ee0b2 1740GV *
3752a9fe 1741Perl_gv_fetchpv(pTHX_ const char *nambeg, I32 flags, const svtype sv_type) {
7918f24d 1742 PERL_ARGS_ASSERT_GV_FETCHPV;
3752a9fe 1743 return gv_fetchpvn_flags(nambeg, strlen(nambeg), flags, sv_type);
7a5fd60d
NC
1744}
1745
1746GV *
fe9845cc 1747Perl_gv_fetchsv(pTHX_ SV *name, I32 flags, const svtype sv_type) {
7a5fd60d 1748 STRLEN len;
77cb3b01
FC
1749 const char * const nambeg =
1750 SvPV_flags_const(name, len, flags & GV_NO_SVGMAGIC ? 0 : SV_GMAGIC);
7918f24d 1751 PERL_ARGS_ASSERT_GV_FETCHSV;
7a5fd60d
NC
1752 return gv_fetchpvn_flags(nambeg, len, flags | SvUTF8(name), sv_type);
1753}
1754
90aeefb4 1755PERL_STATIC_INLINE void
290a1700 1756S_gv_magicalize_isa(pTHX_ GV *gv)
ad7cce9f
FR
1757{
1758 AV* av;
1759
1760 PERL_ARGS_ASSERT_GV_MAGICALIZE_ISA;
1761
1762 av = GvAVn(gv);
1763 GvMULTI_on(gv);
1764 sv_magic(MUTABLE_SV(av), MUTABLE_SV(gv), PERL_MAGIC_isa,
1604cfb0 1765 NULL, 0);
ad7cce9f
FR
1766}
1767
90aeefb4
BF
1768/* This function grabs name and tries to split a stash and glob
1769 * from its contents. TODO better description, comments
9c913148 1770 *
90aeefb4
BF
1771 * If the function returns TRUE and 'name == name_end', then
1772 * 'gv' can be directly returned to the caller of gv_fetchpvn_flags
1773 */
1774PERL_STATIC_INLINE bool
1775S_parse_gv_stash_name(pTHX_ HV **stash, GV **gv, const char **name,
1776 STRLEN *len, const char *nambeg, STRLEN full_len,
1777 const U32 is_utf8, const I32 add)
1778{
8c573bee 1779 char *tmpfullbuf = NULL; /* only malloc one big chunk of memory when the smallbuff is not large enough */
90aeefb4
BF
1780 const char *name_cursor;
1781 const char *const name_end = nambeg + full_len;
1782 const char *const name_em1 = name_end - 1;
8c573bee 1783 char smallbuf[64]; /* small buffer to avoid a malloc when possible */
90aeefb4
BF
1784
1785 PERL_ARGS_ASSERT_PARSE_GV_STASH_NAME;
9c913148 1786
7a207065
KW
1787 if ( full_len > 2
1788 && **name == '*'
1789 && isIDFIRST_lazy_if_safe(*name + 1, name_end, is_utf8))
1790 {
90aeefb4
BF
1791 /* accidental stringify on a GV? */
1792 (*name)++;
1793 }
1794
1795 for (name_cursor = *name; name_cursor < name_end; name_cursor++) {
1796 if (name_cursor < name_em1 &&
1797 ((*name_cursor == ':' && name_cursor[1] == ':')
1798 || *name_cursor == '\''))
1799 {
1800 if (!*stash)
1801 *stash = PL_defstash;
1802 if (!*stash || !SvREFCNT(*stash)) /* symbol table under destruction */
657ed7c1 1803 goto notok;
90aeefb4
BF
1804
1805 *len = name_cursor - *name;
1806 if (name_cursor > nambeg) { /* Skip for initial :: or ' */
1807 const char *key;
1808 GV**gvp;
1809 if (*name_cursor == ':') {
1810 key = *name;
1811 *len += 2;
1812 }
f8ac814f 1813 else { /* using ' for package separator */
8c573bee
N
1814 /* use our pre-allocated buffer when possible to save a malloc */
1815 char *tmpbuf;
1816 if ( *len+2 <= sizeof smallbuf)
1817 tmpbuf = smallbuf;
1818 else {
1819 /* only malloc once if needed */
1820 if (tmpfullbuf == NULL) /* only malloc&free once, a little more than needed */
1821 Newx(tmpfullbuf, full_len+2, char);
1822 tmpbuf = tmpfullbuf;
1823 }
90aeefb4
BF
1824 Copy(*name, tmpbuf, *len, char);
1825 tmpbuf[(*len)++] = ':';
1826 tmpbuf[(*len)++] = ':';
1827 key = tmpbuf;
1828 }
c161da64 1829 gvp = (GV**)hv_fetch(*stash, key, is_utf8 ? -((I32)*len) : (I32)*len, add);
90aeefb4 1830 *gv = gvp ? *gvp : NULL;
f8ac814f 1831 if (!*gv || *gv == (const GV *)&PL_sv_undef) {
657ed7c1 1832 goto notok;
f8ac814f
N
1833 }
1834 /* here we know that *gv && *gv != &PL_sv_undef */
1835 if (SvTYPE(*gv) != SVt_PVGV)
1836 gv_init_pvn(*gv, *stash, key, *len, (add & GV_ADDMULTI)|is_utf8);
1837 else
1838 GvMULTI_on(*gv);
90aeefb4
BF
1839
1840 if (!(*stash = GvHV(*gv))) {
1841 *stash = GvHV(*gv) = newHV();
2e4090b8 1842 if (!HvHasNAME(*stash)) {
90aeefb4 1843 if (GvSTASH(*gv) == PL_defstash && *len == 6
c8b388b0 1844 && strBEGINs(*name, "CORE"))
4c4f3c46 1845 hv_name_sets(*stash, "CORE", 0);
90aeefb4
BF
1846 else
1847 hv_name_set(
1848 *stash, nambeg, name_cursor-nambeg, is_utf8
1849 );
1850 /* If the containing stash has multiple effective
1851 names, see that this one gets them, too. */
1852 if (HvAUX(GvSTASH(*gv))->xhv_name_count)
1853 mro_package_moved(*stash, NULL, *gv, 1);
1854 }
1855 }
2e4090b8 1856 else if (!HvHasNAME(*stash))
90aeefb4
BF
1857 hv_name_set(*stash, nambeg, name_cursor - nambeg, is_utf8);
1858 }
1859
1860 if (*name_cursor == ':')
1861 name_cursor++;
1862 *name = name_cursor+1;
1863 if (*name == name_end) {
120921ac 1864 if (!*gv) {
1604cfb0
MS
1865 *gv = MUTABLE_GV(*hv_fetchs(PL_defstash, "main::", TRUE));
1866 if (SvTYPE(*gv) != SVt_PVGV) {
1867 gv_init_pvn(*gv, PL_defstash, "main::", 6,
1868 GV_ADDMULTI);
1869 GvHV(*gv) =
1870 MUTABLE_HV(SvREFCNT_inc_simple(PL_defstash));
1871 }
1872 }
657ed7c1 1873 goto ok;
90aeefb4
BF
1874 }
1875 }
1876 }
1877 *len = name_cursor - *name;
657ed7c1
DM
1878 ok:
1879 Safefree(tmpfullbuf); /* free our tmpfullbuf if it was used */
90aeefb4 1880 return TRUE;
657ed7c1
DM
1881 notok:
1882 Safefree(tmpfullbuf); /* free our tmpfullbuf if it was used */
1883 return FALSE;
90aeefb4
BF
1884}
1885
657ed7c1 1886
536d1a88 1887/* Checks if an unqualified name is in the main stash */
90aeefb4 1888PERL_STATIC_INLINE bool
536d1a88 1889S_gv_is_in_main(pTHX_ const char *name, STRLEN len, const U32 is_utf8)
90aeefb4 1890{
536d1a88 1891 PERL_ARGS_ASSERT_GV_IS_IN_MAIN;
9c913148 1892
90aeefb4 1893 /* If it's an alphanumeric variable */
7a207065 1894 if ( len && isIDFIRST_lazy_if_safe(name, name + len, is_utf8) ) {
90aeefb4
BF
1895 /* Some "normal" variables are always in main::,
1896 * like INC or STDOUT.
1897 */
1898 switch (len) {
1899 case 1:
1900 if (*name == '_')
536d1a88 1901 return TRUE;
90aeefb4
BF
1902 break;
1903 case 3:
1904 if ((name[0] == 'I' && name[1] == 'N' && name[2] == 'C')
1905 || (name[0] == 'E' && name[1] == 'N' && name[2] == 'V')
1906 || (name[0] == 'S' && name[1] == 'I' && name[2] == 'G'))
536d1a88 1907 return TRUE;
90aeefb4
BF
1908 break;
1909 case 4:
1910 if (name[0] == 'A' && name[1] == 'R' && name[2] == 'G'
1911 && name[3] == 'V')
536d1a88 1912 return TRUE;
90aeefb4
BF
1913 break;
1914 case 5:
1915 if (name[0] == 'S' && name[1] == 'T' && name[2] == 'D'
1916 && name[3] == 'I' && name[4] == 'N')
536d1a88 1917 return TRUE;
90aeefb4
BF
1918 break;
1919 case 6:
1920 if ((name[0] == 'S' && name[1] == 'T' && name[2] == 'D')
1921 &&((name[3] == 'O' && name[4] == 'U' && name[5] == 'T')
1922 ||(name[3] == 'E' && name[4] == 'R' && name[5] == 'R')))
536d1a88 1923 return TRUE;
90aeefb4
BF
1924 break;
1925 case 7:
1926 if (name[0] == 'A' && name[1] == 'R' && name[2] == 'G'
1927 && name[3] == 'V' && name[4] == 'O' && name[5] == 'U'
1928 && name[6] == 'T')
536d1a88 1929 return TRUE;
90aeefb4
BF
1930 break;
1931 }
536d1a88
BF
1932 }
1933 /* *{""}, or a special variable like $@ */
1934 else
1935 return TRUE;
9c913148 1936
536d1a88
BF
1937 return FALSE;
1938}
1939
1940
1941/* This function is called if parse_gv_stash_name() failed to
1942 * find a stash, or if GV_NOTQUAL or an empty name was passed
1943 * to gv_fetchpvn_flags.
9c913148 1944 *
536d1a88
BF
1945 * It returns FALSE if the default stash can't be found nor created,
1946 * which might happen during global destruction.
1947 */
1948PERL_STATIC_INLINE bool
1949S_find_default_stash(pTHX_ HV **stash, const char *name, STRLEN len,
1950 const U32 is_utf8, const I32 add,
1951 const svtype sv_type)
1952{
1953 PERL_ARGS_ASSERT_FIND_DEFAULT_STASH;
9c913148 1954
536d1a88 1955 /* No stash in name, so see how we can default */
90aeefb4 1956
536d1a88
BF
1957 if ( gv_is_in_main(name, len, is_utf8) ) {
1958 *stash = PL_defstash;
1959 }
1960 else {
1961 if (IN_PERL_COMPILETIME) {
90aeefb4
BF
1962 *stash = PL_curstash;
1963 if (add && (PL_hints & HINT_STRICT_VARS) &&
1964 sv_type != SVt_PVCV &&
1965 sv_type != SVt_PVGV &&
1966 sv_type != SVt_PVFM &&
1967 sv_type != SVt_PVIO &&
1968 !(len == 1 && sv_type == SVt_PV &&
1969 (*name == 'a' || *name == 'b')) )
1970 {
c161da64 1971 GV**gvp = (GV**)hv_fetch(*stash,name,is_utf8 ? -(I32)len : (I32)len,0);
90aeefb4
BF
1972 if (!gvp || *gvp == (const GV *)&PL_sv_undef ||
1973 SvTYPE(*gvp) != SVt_PVGV)
1974 {
1975 *stash = NULL;
1976 }
1977 else if ((sv_type == SVt_PV && !GvIMPORTED_SV(*gvp)) ||
1978 (sv_type == SVt_PVAV && !GvIMPORTED_AV(*gvp)) ||
1979 (sv_type == SVt_PVHV && !GvIMPORTED_HV(*gvp)) )
1980 {
1981 /* diag_listed_as: Variable "%s" is not imported%s */
1982 Perl_ck_warner_d(
1983 aTHX_ packWARN(WARN_MISC),
147e3846 1984 "Variable \"%c%" UTF8f "\" is not imported",
90aeefb4
BF
1985 sv_type == SVt_PVAV ? '@' :
1986 sv_type == SVt_PVHV ? '%' : '$',
1987 UTF8fARG(is_utf8, len, name));
1988 if (GvCVu(*gvp))
1989 Perl_ck_warner_d(
1990 aTHX_ packWARN(WARN_MISC),
147e3846 1991 "\t(Did you mean &%" UTF8f " instead?)\n",
90aeefb4
BF
1992 UTF8fARG(is_utf8, len, name)
1993 );
1994 *stash = NULL;
1995 }
1996 }
1997 }
1998 else {
1999 /* Use the current op's stash */
2000 *stash = CopSTASH(PL_curcop);
2001 }
2002 }
90aeefb4
BF
2003
2004 if (!*stash) {
2005 if (add && !PL_in_clean_all) {
10860bf4
FC
2006 GV *gv;
2007 qerror(Perl_mess(aTHX_
147e3846 2008 "Global symbol \"%s%" UTF8f
d8c6310a 2009 "\" requires explicit package name (did you forget to "
147e3846 2010 "declare \"my %s%" UTF8f "\"?)",
d8c6310a
FC
2011 (sv_type == SVt_PV ? "$"
2012 : sv_type == SVt_PVAV ? "@"
2013 : sv_type == SVt_PVHV ? "%"
2014 : ""), UTF8fARG(is_utf8, len, name),
90aeefb4
BF
2015 (sv_type == SVt_PV ? "$"
2016 : sv_type == SVt_PVAV ? "@"
2017 : sv_type == SVt_PVHV ? "%"
10860bf4 2018 : ""), UTF8fARG(is_utf8, len, name)));
cd164bf8
BF
2019 /* To maintain the output of errors after the strict exception
2020 * above, and to keep compat with older releases, rather than
2021 * placing the variables in the pad, we place
2022 * them in the <none>:: stash.
2023 */
90aeefb4
BF
2024 gv = gv_fetchpvs("<none>::", GV_ADDMULTI, SVt_PVHV);
2025 if (!gv) {
2026 /* symbol table under destruction */
2027 return FALSE;
2028 }
2029 *stash = GvHV(gv);
2030 }
2031 else
2032 return FALSE;
2033 }
2034
2035 if (!SvREFCNT(*stash)) /* symbol table under destruction */
2036 return FALSE;
2037
2038 return TRUE;
2039}
2040
8c995aba
FC
2041/* gv_magicalize only turns on the SVf_READONLY flag, not SVf_PROTECT. So
2042 redefine SvREADONLY_on for that purpose. We don’t use it later on in
2043 this file. */
2044#undef SvREADONLY_on
2045#define SvREADONLY_on(sv) (SvFLAGS(sv) |= SVf_READONLY)
2046
930867a8
BF
2047/* gv_magicalize() is called by gv_fetchpvn_flags when creating
2048 * a new GV.
2049 * Note that it does not insert the GV into the stash prior to
2050 * magicalization, which some variables require need in order
c22e17d0 2051 * to work (like %+, %-, %!), so callers must take care of
1321bbe3 2052 * that.
9c913148 2053 *
1321bbe3
FC
2054 * It returns true if the gv did turn out to be magical one; i.e.,
2055 * if gv_magicalize actually did something.
930867a8
BF
2056 */
2057PERL_STATIC_INLINE bool
2058S_gv_magicalize(pTHX_ GV *gv, HV *stash, const char *name, STRLEN len,
1321bbe3 2059 const svtype sv_type)
79072805 2060{
960b831f 2061 SSize_t paren;
79072805 2062
930867a8 2063 PERL_ARGS_ASSERT_GV_MAGICALIZE;
9c913148 2064
44428a46 2065 if (stash != PL_defstash) { /* not the main stash */
1604cfb0
MS
2066 /* We only have to check for a few names here: a, b, EXPORT, ISA
2067 and VERSION. All the others apply only to the main stash or to
2068 CORE (which is checked right after this). */
2069 if (len) {
2070 switch (*name) {
2071 case 'E':
3092ee0c
YO
2072 if (
2073 len >= 6 && name[1] == 'X' &&
2074 (memEQs(name, len, "EXPORT")
eafd371c
YO
2075 ||memEQs(name, len, "EXPORT_OK")
2076 ||memEQs(name, len, "EXPORT_FAIL")
3092ee0c 2077 ||memEQs(name, len, "EXPORT_TAGS"))
eafd371c 2078 )
1604cfb0
MS
2079 GvMULTI_on(gv);
2080 break;
2081 case 'I':
eafd371c 2082 if (memEQs(name, len, "ISA"))
1604cfb0
MS
2083 gv_magicalize_isa(gv);
2084 break;
2085 case 'V':
eafd371c 2086 if (memEQs(name, len, "VERSION"))
1604cfb0
MS
2087 GvMULTI_on(gv);
2088 break;
2089 case 'a':
eafd371c 2090 if (stash == PL_debstash && memEQs(name, len, "args")) {
1604cfb0
MS
2091 GvMULTI_on(gv_AVadd(gv));
2092 break;
eafd371c
YO
2093 }
2094 /* FALLTHROUGH */
1604cfb0
MS
2095 case 'b':
2096 if (len == 1 && sv_type == SVt_PV)
2097 GvMULTI_on(gv);
2098 /* FALLTHROUGH */
2099 default:
2100 goto try_core;
2101 }
2102 goto ret;
2103 }
4aaa4757 2104 try_core:
1604cfb0
MS
2105 if (len > 1 /* shortest is uc */ && HvNAMELEN_get(stash) == 4) {
2106 /* Avoid null warning: */
2107 const char * const stashname = HvNAME(stash); assert(stashname);
2108 if (strBEGINs(stashname, "CORE"))
2109 S_maybe_add_coresub(aTHX_ 0, gv, name, len);
2110 }
44428a46
FC
2111 }
2112 else if (len > 1) {
2113#ifndef EBCDIC
1604cfb0
MS
2114 if (*name > 'V' ) {
2115 NOOP;
2116 /* Nothing else to do.
2117 The compiler will probably turn the switch statement into a
2118 branch table. Make sure we avoid even that small overhead for
2ae25f5c
KW
2119 the common case of lower case variable names. (On EBCDIC
2120 platforms, we can't just do:
2121 if (NATIVE_TO_ASCII(*name) > NATIVE_TO_ASCII('V') ) {
2122 because cases like '\027' in the switch statement below are
2123 C1 (non-ASCII) controls on those platforms, so the remapping
2124 would make them larger than 'V')
2125 */
1604cfb0 2126 } else
44428a46 2127#endif
1604cfb0
MS
2128 {
2129 switch (*name) {
2130 case 'A':
eafd371c 2131 if (memEQs(name, len, "ARGV")) {
1604cfb0
MS
2132 IoFLAGS(GvIOn(gv)) |= IOf_ARGV|IOf_START;
2133 }
eafd371c 2134 else if (memEQs(name, len, "ARGVOUT")) {
1604cfb0
MS
2135 GvMULTI_on(gv);
2136 }
2137 break;
2138 case 'E':
3092ee0c
YO
2139 if (
2140 len >= 6 && name[1] == 'X' &&
2141 (memEQs(name, len, "EXPORT")
055ae706
YO
2142 ||memEQs(name, len, "EXPORT_OK")
2143 ||memEQs(name, len, "EXPORT_FAIL")
3092ee0c 2144 ||memEQs(name, len, "EXPORT_TAGS"))
055ae706 2145 )
1604cfb0
MS
2146 GvMULTI_on(gv);
2147 break;
2148 case 'I':
eafd371c 2149 if (memEQs(name, len, "ISA")) {
1604cfb0
MS
2150 gv_magicalize_isa(gv);
2151 }
2152 break;
2153 case 'S':
eafd371c 2154 if (memEQs(name, len, "SIG")) {
1604cfb0
MS
2155 HV *hv;
2156 I32 i;
2157 if (!PL_psig_name) {
2158 Newxz(PL_psig_name, 2 * SIG_SIZE, SV*);
2159 Newxz(PL_psig_pend, SIG_SIZE, int);
2160 PL_psig_ptr = PL_psig_name + SIG_SIZE;
2161 } else {
2162 /* I think that the only way to get here is to re-use an
2163 embedded perl interpreter, where the previous
2164 use didn't clean up fully because
2165 PL_perl_destruct_level was 0. I'm not sure that we
2166 "support" that, in that I suspect in that scenario
2167 there are sufficient other garbage values left in the
2168 interpreter structure that something else will crash
2169 before we get here. I suspect that this is one of
2170 those "doctor, it hurts when I do this" bugs. */
2171 Zero(PL_psig_name, 2 * SIG_SIZE, SV*);
2172 Zero(PL_psig_pend, SIG_SIZE, int);
2173 }
2174 GvMULTI_on(gv);
2175 hv = GvHVn(gv);
2176 hv_magic(hv, NULL, PERL_MAGIC_sig);
2177 for (i = 1; i < SIG_SIZE; i++) {
2178 SV * const * const init = hv_fetch(hv, PL_sig_name[i], strlen(PL_sig_name[i]), 1);
2179 if (init)
2180 sv_setsv(*init, &PL_sv_undef);
2181 }
2182 }
2183 break;
2184 case 'V':
eafd371c 2185 if (memEQs(name, len, "VERSION"))
1604cfb0
MS
2186 GvMULTI_on(gv);
2187 break;
e5218da5 2188 case '\003': /* $^CHILD_ERROR_NATIVE */
eafd371c 2189 if (memEQs(name, len, "\003HILD_ERROR_NATIVE"))
1604cfb0 2190 goto magicalize;
27deb0cf
YO
2191 /* @{^CAPTURE} %{^CAPTURE} */
2192 if (memEQs(name, len, "\003APTURE")) {
2193 AV* const av = GvAVn(gv);
fa531f32 2194 const Size_t n = *name;
27deb0cf 2195
fa531f32 2196 sv_magic(MUTABLE_SV(av), (SV*)n, PERL_MAGIC_regdata, NULL, 0);
27deb0cf
YO
2197 SvREADONLY_on(av);
2198
d8422270 2199 require_tie_mod_s(gv, '+', "Tie::Hash::NamedCapture",0);
27deb0cf
YO
2200
2201 } else /* %{^CAPTURE_ALL} */
2202 if (memEQs(name, len, "\003APTURE_ALL")) {
d8422270 2203 require_tie_mod_s(gv, '-', "Tie::Hash::NamedCapture",0);
27deb0cf 2204 }
1604cfb0
MS
2205 break;
2206 case '\005': /* $^ENCODING */
eafd371c 2207 if (memEQs(name, len, "\005NCODING"))
1604cfb0
MS
2208 goto magicalize;
2209 break;
2210 case '\007': /* $^GLOBAL_PHASE */
eafd371c 2211 if (memEQs(name, len, "\007LOBAL_PHASE"))
1604cfb0
MS
2212 goto ro_magicalize;
2213 break;
2214 case '\014': /* $^LAST_FH */
eafd371c 2215 if (memEQs(name, len, "\014AST_FH"))
1604cfb0
MS
2216 goto ro_magicalize;
2217 break;
cde0cee5 2218 case '\015': /* $^MATCH */
eafd371c 2219 if (memEQs(name, len, "\015ATCH")) {
960b831f
NC
2220 paren = RX_BUFF_IDX_CARET_FULLMATCH;
2221 goto storeparen;
2222 }
66230c86 2223 break;
1604cfb0 2224 case '\017': /* $^OPEN */
eafd371c 2225 if (memEQs(name, len, "\017PEN"))
1604cfb0
MS
2226 goto magicalize;
2227 break;
2228 case '\020': /* $^PREMATCH $^POSTMATCH */
eafd371c 2229 if (memEQs(name, len, "\020REMATCH")) {
960b831f
NC
2230 paren = RX_BUFF_IDX_CARET_PREMATCH;
2231 goto storeparen;
2232 }
eafd371c 2233 if (memEQs(name, len, "\020OSTMATCH")) {
960b831f
NC
2234 paren = RX_BUFF_IDX_CARET_POSTMATCH;
2235 goto storeparen;
2236 }
1604cfb0 2237 break;
f512d242
KW
2238 case '\023':
2239 if (memEQs(name, len, "\023AFE_LOCALES"))
1604cfb0
MS
2240 goto ro_magicalize;
2241 break;
2242 case '\024': /* ${^TAINT} */
eafd371c 2243 if (memEQs(name, len, "\024AINT"))
1604cfb0
MS
2244 goto ro_magicalize;
2245 break;
2246 case '\025': /* ${^UNICODE}, ${^UTF8LOCALE} */
eafd371c 2247 if (memEQs(name, len, "\025NICODE"))
1604cfb0 2248 goto ro_magicalize;
eafd371c 2249 if (memEQs(name, len, "\025TF8LOCALE"))
1604cfb0 2250 goto ro_magicalize;
eafd371c 2251 if (memEQs(name, len, "\025TF8CACHE"))
1604cfb0
MS
2252 goto magicalize;
2253 break;
2254 case '\027': /* $^WARNING_BITS */
eafd371c 2255 if (memEQs(name, len, "\027ARNING_BITS"))
1604cfb0 2256 goto magicalize;
8ca2a5d6 2257#ifdef WIN32
eafd371c 2258 else if (memEQs(name, len, "\027IN32_SLOPPY_STAT"))
1604cfb0 2259 goto magicalize;
8ca2a5d6 2260#endif
1604cfb0
MS
2261 break;
2262 case '1':
2263 case '2':
2264 case '3':
2265 case '4':
2266 case '5':
2267 case '6':
2268 case '7':
2269 case '8':
2270 case '9':
2271 {
2272 /* Ensures that we have an all-digit variable, ${"1foo"} fails
2273 this test */
22ff3130
HS
2274 UV uv;
2275 if (!grok_atoUV(name, &uv, NULL) || uv > I32_MAX)
1321bbe3 2276 goto ret;
22ff3130
HS
2277 /* XXX why are we using a SSize_t? */
2278 paren = (SSize_t)(I32)uv;
960b831f 2279 goto storeparen;
1604cfb0
MS
2280 }
2281 }
2282 }
392db708 2283 } else {
1604cfb0
MS
2284 /* Names of length 1. (Or 0. But name is NUL terminated, so that will
2285 be case '\0' in this switch statement (ie a default case) */
2286 switch (*name) {
2287 case '&': /* $& */
960b831f
NC
2288 paren = RX_BUFF_IDX_FULLMATCH;
2289 goto sawampersand;
1604cfb0 2290 case '`': /* $` */
960b831f
NC
2291 paren = RX_BUFF_IDX_PREMATCH;
2292 goto sawampersand;
1604cfb0 2293 case '\'': /* $' */
960b831f
NC
2294 paren = RX_BUFF_IDX_POSTMATCH;
2295 sawampersand:
1a904fc8 2296#ifdef PERL_SAWAMPERSAND
1604cfb0
MS
2297 if (!(
2298 sv_type == SVt_PVAV ||
2299 sv_type == SVt_PVHV ||
2300 sv_type == SVt_PVCV ||
2301 sv_type == SVt_PVFM ||
2302 sv_type == SVt_PVIO
2303 )) { PL_sawampersand |=
d3b97530
DM
2304 (*name == '`')
2305 ? SAWAMPERSAND_LEFT
2306 : (*name == '&')
2307 ? SAWAMPERSAND_MIDDLE
2308 : SAWAMPERSAND_RIGHT;
2309 }
1a904fc8 2310#endif
960b831f 2311 goto storeparen;
e91d8259
NC
2312 case '1': /* $1 */
2313 case '2': /* $2 */
2314 case '3': /* $3 */
2315 case '4': /* $4 */
2316 case '5': /* $5 */
2317 case '6': /* $6 */
2318 case '7': /* $7 */
2319 case '8': /* $8 */
2320 case '9': /* $9 */
960b831f
NC
2321 paren = *name - '0';
2322
2323 storeparen:
e91d8259
NC
2324 /* Flag the capture variables with a NULL mg_ptr
2325 Use mg_len for the array index to lookup. */
960b831f 2326 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, NULL, paren);
e91d8259 2327 break;
cc4c2da6 2328
1604cfb0
MS
2329 case ':': /* $: */
2330 sv_setpv(GvSVn(gv),PL_chopset);
2331 goto magicalize;
cc4c2da6 2332
1604cfb0 2333 case '?': /* $? */
ff0cee69 2334#ifdef COMPLEX_STATUS
1604cfb0 2335 SvUPGRADE(GvSVn(gv), SVt_PVLV);
ff0cee69 2336#endif
1604cfb0 2337 goto magicalize;
ff0cee69 2338
1604cfb0
MS
2339 case '!': /* $! */
2340 GvMULTI_on(gv);
2341 /* If %! has been used, automatically load Errno.pm. */
d2c93421 2342
1604cfb0 2343 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, name, len);
d2c93421 2344
7c719134 2345 /* magicalization must be done before require_tie_mod_s is called */
1604cfb0 2346 if (sv_type == SVt_PVHV || sv_type == SVt_PVGV)
7c719134 2347 require_tie_mod_s(gv, '!', "Errno", 1);
d2c93421 2348
1604cfb0
MS
2349 break;
2350 case '-': /* $-, %-, @- */
2351 case '+': /* $+, %+, @+ */
27deb0cf
YO
2352 GvMULTI_on(gv); /* no used once warnings here */
2353 { /* $- $+ */
2354 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, name, len);
2355 if (*name == '+')
2356 SvREADONLY_on(GvSVn(gv));
2357 }
2358 { /* %- %+ */
2359 if (sv_type == SVt_PVHV || sv_type == SVt_PVGV)
2360 require_tie_mod_s(gv, *name, "Tie::Hash::NamedCapture",0);
2361 }
2362 { /* @- @+ */
2363 AV* const av = GvAVn(gv);
fa531f32 2364 const Size_t n = *name;
67261566 2365
fa531f32 2366 sv_magic(MUTABLE_SV(av), (SV*)n, PERL_MAGIC_regdata, NULL, 0);
27deb0cf
YO
2367 SvREADONLY_on(av);
2368 }
80305961 2369 break;
1604cfb0
MS
2370 case '*': /* $* */
2371 case '#': /* $# */
dcb414ac
JK
2372 if (sv_type == SVt_PV)
2373 /* diag_listed_as: $* is no longer supported as of Perl 5.30 */
2374 Perl_croak(aTHX_ "$%c is no longer supported as of Perl 5.30", *name);
2375 break;
1604cfb0
MS
2376 case '\010': /* $^H */
2377 {
2378 HV *const hv = GvHVn(gv);
2379 hv_magic(hv, NULL, PERL_MAGIC_hints);
2380 }
2381 goto magicalize;
2382 case '\023': /* $^S */
2383 ro_magicalize:
2384 SvREADONLY_on(GvSVn(gv));
2385 /* FALLTHROUGH */
2386 case '0': /* $0 */
2387 case '^': /* $^ */
2388 case '~': /* $~ */
2389 case '=': /* $= */
2390 case '%': /* $% */
2391 case '.': /* $. */
2392 case '(': /* $( */
2393 case ')': /* $) */
2394 case '<': /* $< */
2395 case '>': /* $> */
2396 case '\\': /* $\ */
2397 case '/': /* $/ */
2398 case '|': /* $| */
2399 case '$': /* $$ */
2400 case '[': /* $[ */
2401 case '\001': /* $^A */
2402 case '\003': /* $^C */
2403 case '\004': /* $^D */
2404 case '\005': /* $^E */
2405 case '\006': /* $^F */
2406 case '\011': /* $^I, NOT \t in EBCDIC */
2407 case '\016': /* $^N */
2408 case '\017': /* $^O */
2409 case '\020': /* $^P */
2410 case '\024': /* $^T */
2411 case '\027': /* $^W */
2412 magicalize:
2413 sv_magic(GvSVn(gv), MUTABLE_SV(gv), PERL_MAGIC_sv, name, len);
2414 break;
2415
2416 case '\014': /* $^L */
2417 sv_setpvs(GvSVn(gv),"\f");
2418 break;
2419 case ';': /* $; */
2420 sv_setpvs(GvSVn(gv),"\034");
2421 break;
2422 case ']': /* $] */
2423 {
2424 SV * const sv = GvSV(gv);
2425 if (!sv_derived_from(PL_patchlevel, "version"))
2426 upg_version(PL_patchlevel, TRUE);
2427 GvSV(gv) = vnumify(PL_patchlevel);
2428 SvREADONLY_on(GvSV(gv));
2429 SvREFCNT_dec(sv);
2430 }
2431 break;
2432 case '\026': /* $^V */
2433 {
2434 SV * const sv = GvSV(gv);
2435 GvSV(gv) = new_version(PL_patchlevel);
2436 SvREADONLY_on(GvSV(gv));
2437 SvREFCNT_dec(sv);
2438 }
2439 break;
2440 case 'a':
2441 case 'b':
2442 if (sv_type == SVt_PV)
2443 GvMULTI_on(gv);
2444 }
79072805 2445 }
930867a8 2446
1321bbe3
FC
2447 ret:
2448 /* Return true if we actually did something. */
2449 return GvAV(gv) || GvHV(gv) || GvIO(gv) || GvCV(gv)
2450 || ( GvSV(gv) && (
2451 SvOK(GvSV(gv)) || SvMAGICAL(GvSV(gv))
2452 )
2453 );
71c35c05
BF
2454}
2455
8c995aba
FC
2456/* If we do ever start using this later on in the file, we need to make
2457 sure we don’t accidentally use the wrong definition. */
2458#undef SvREADONLY_on
2459
070dc475
BF
2460/* This function is called when the stash already holds the GV of the magic
2461 * variable we're looking for, but we need to check that it has the correct
2462 * kind of magic. For example, if someone first uses $! and then %!, the
2463 * latter would end up here, and we add the Errno tie to the HASH slot of
2464 * the *! glob.
2465 */
2466PERL_STATIC_INLINE void
2467S_maybe_multimagic_gv(pTHX_ GV *gv, const char *name, const svtype sv_type)
2468{
2469 PERL_ARGS_ASSERT_MAYBE_MULTIMAGIC_GV;
2470
2471 if (sv_type == SVt_PVHV || sv_type == SVt_PVGV) {
2472 if (*name == '!')
7c719134 2473 require_tie_mod_s(gv, '!', "Errno", 1);
070dc475 2474 else if (*name == '-' || *name == '+')
7c719134 2475 require_tie_mod_s(gv, *name, "Tie::Hash::NamedCapture", 0);
a678626e
A
2476 } else if (sv_type == SVt_PV) {
2477 if (*name == '*' || *name == '#') {
dcb414ac
JK
2478 /* diag_listed_as: $* is no longer supported as of Perl 5.30 */
2479 Perl_croak(aTHX_ "$%c is no longer supported as of Perl 5.30", *name);
a678626e 2480 }
070dc475
BF
2481 }
2482 if (sv_type==SVt_PV || sv_type==SVt_PVGV) {
2483 switch (*name) {
070dc475
BF
2484#ifdef PERL_SAWAMPERSAND
2485 case '`':
2486 PL_sawampersand |= SAWAMPERSAND_LEFT;
2487 (void)GvSVn(gv);
2488 break;
2489 case '&':
2490 PL_sawampersand |= SAWAMPERSAND_MIDDLE;
2491 (void)GvSVn(gv);
2492 break;
2493 case '\'':
2494 PL_sawampersand |= SAWAMPERSAND_RIGHT;
2495 (void)GvSVn(gv);
2496 break;
2497#endif
2498 }
2499 }
2500}
2501
84ca0d82
KW
2502/*
2503=for apidoc gv_fetchpv
2504=for apidoc_item |GV *|gv_fetchpvn|const char * nambeg|STRLEN full_len|I32 flags|const svtype sv_type
2505=for apidoc_item ||gv_fetchpvn_flags
2506=for apidoc_item |GV *|gv_fetchpvs|"name"|I32 flags|const svtype sv_type
2507=for apidoc_item ||gv_fetchsv
2508=for apidoc_item |GV *|gv_fetchsv_nomg|SV *name|I32 flags|const svtype sv_type
2509
2510These all return the GV of type C<sv_type> whose name is given by the inputs,
2511or NULL if no GV of that name and type could be found. See L<perlguts/Stashes
2512and Globs>.
2513
2514The only differences are how the input name is specified, and if 'get' magic is
2515normally used in getting that name.
2516
2517Don't be fooled by the fact that only one form has C<flags> in its name. They
2518all have a C<flags> parameter in fact, and all the flag bits have the same
2519meanings for all
2520
2521If any of the flags C<GV_ADD>, C<GV_ADDMG>, C<GV_ADDWARN>, C<GV_ADDMULTI>, or
2522C<GV_NOINIT> is set, a GV is created if none already exists for the input name
2523and type. However, C<GV_ADDMG> will only do the creation for magical GV's.
2524For all of these flags except C<GV_NOINIT>, C<L</gv_init_pvn>> is called after
2525the addition. C<GV_ADDWARN> is used when the caller expects that adding won't
2526be necessary because the symbol should already exist; but if not, add it
2527anyway, with a warning that it was unexpectedly absent. The C<GV_ADDMULTI>
2528flag means to pretend that the GV has been seen before (I<i.e.>, suppress "Used
2529once" warnings).
2530
2531The flag C<GV_NOADD_NOINIT> causes C<L</gv_init_pvn>> not be to called if the
2532GV existed but isn't PVGV.
2533
2534If the C<SVf_UTF8> bit is set, the name is treated as being encoded in UTF-8;
2535otherwise the name won't be considered to be UTF-8 in the C<pv>-named forms,
2536and the UTF-8ness of the underlying SVs will be used in the C<sv> forms.
2537
2538If the flag C<GV_NOTQUAL> is set, the caller warrants that the input name is a
2539plain symbol name, not qualified with a package, otherwise the name is checked
2540for being a qualified one.
2541
2542In C<gv_fetchpv>, C<nambeg> is a C string, NUL-terminated with no intermediate
2543NULs.
2544
2545In C<gv_fetchpvs>, C<name> is a literal C string, hence is enclosed in
2546double quotes.
2547
2548C<gv_fetchpvn> and C<gv_fetchpvn_flags> are identical. In these, <nambeg> is
2549a Perl string whose byte length is given by C<full_len>, and may contain
2550embedded NULs.
2551
2552In C<gv_fetchsv> and C<gv_fetchsv_nomg>, the name is extracted from the PV of
2553the input C<name> SV. The only difference between these two forms is that
2554'get' magic is normally done on C<name> in C<gv_fetchsv>, and always skipped
2555with C<gv_fetchsv_nomg>. Including C<GV_NO_SVGMAGIC> in the C<flags> parameter
2556to C<gv_fetchsv> makes it behave identically to C<gv_fetchsv_nomg>.
2557
2558=for apidoc Amnh||GV_ADD
2559=for apidoc Amnh||GV_ADDMG
2560=for apidoc Amnh||GV_ADDMULTI
2561=for apidoc Amnh||GV_ADDWARN
84ca0d82 2562=for apidoc Amnh||GV_NOINIT
1607e393 2563=for apidoc Amnh||GV_NOADD_NOINIT
84ca0d82
KW
2564=for apidoc Amnh||GV_NOTQUAL
2565=for apidoc Amnh||GV_NO_SVGMAGIC
2566=for apidoc Amnh||SVf_UTF8
2567
2568=cut
2569*/
2570
71c35c05
BF
2571GV *
2572Perl_gv_fetchpvn_flags(pTHX_ const char *nambeg, STRLEN full_len, I32 flags,
1604cfb0 2573 const svtype sv_type)
71c35c05 2574{
71c35c05
BF
2575 const char *name = nambeg;
2576 GV *gv = NULL;
2577 GV**gvp;
2578 STRLEN len;
2579 HV *stash = NULL;
2580 const I32 no_init = flags & (GV_NOADD_NOINIT | GV_NOINIT);
2581 const I32 no_expand = flags & GV_NOEXPAND;
2582 const I32 add = flags & ~GV_NOADD_MASK;
2583 const U32 is_utf8 = flags & SVf_UTF8;
930867a8 2584 bool addmg = cBOOL(flags & GV_ADDMG);
71c35c05
BF
2585 const char *const name_end = nambeg + full_len;
2586 U32 faking_it;
2587
2588 PERL_ARGS_ASSERT_GV_FETCHPVN_FLAGS;
2589
2590 /* If we have GV_NOTQUAL, the caller promised that
2591 * there is no stash, so we can skip the check.
2592 * Similarly if full_len is 0, since then we're
2593 * dealing with something like *{""} or ""->foo()
2594 */
2595 if ((flags & GV_NOTQUAL) || !full_len) {
2596 len = full_len;
2597 }
2598 else if (parse_gv_stash_name(&stash, &gv, &name, &len, nambeg, full_len, is_utf8, add)) {
2599 if (name == name_end) return gv;
2600 }
2601 else {
2602 return NULL;
2603 }
2604
2605 if (!stash && !find_default_stash(&stash, name, len, is_utf8, add, sv_type)) {
2606 return NULL;
2607 }
9c913148 2608
71c35c05 2609 /* By this point we should have a stash and a name */
c161da64 2610 gvp = (GV**)hv_fetch(stash,name,is_utf8 ? -(I32)len : (I32)len,add);
71c35c05 2611 if (!gvp || *gvp == (const GV *)&PL_sv_undef) {
8fcb2425 2612 if (addmg) gv = (GV *)newSV_type(SVt_NULL); /* tentatively */
1604cfb0 2613 else return NULL;
71c35c05
BF
2614 }
2615 else gv = *gvp, addmg = 0;
2616 /* From this point on, addmg means gv has not been inserted in the
2617 symtab yet. */
2618
2619 if (SvTYPE(gv) == SVt_PVGV) {
c002ae9a
BF
2620 /* The GV already exists, so return it, but check if we need to do
2621 * anything else with it before that.
2622 */
1604cfb0 2623 if (add) {
c002ae9a
BF
2624 /* This is the heuristic that handles if a variable triggers the
2625 * 'used only once' warning. If there's already a GV in the stash
2626 * with this name, then we assume that the variable has been used
2627 * before and turn its MULTI flag on.
2628 * It's a heuristic because it can easily be "tricked", like with
2629 * BEGIN { $a = 1; $::{foo} = *a }; () = $foo
2630 * not warning about $main::foo being used just once
2631 */
1604cfb0
MS
2632 GvMULTI_on(gv);
2633 gv_init_svtype(gv, sv_type);
71c35c05
BF
2634 /* You reach this path once the typeglob has already been created,
2635 either by the same or a different sigil. If this path didn't
2636 exist, then (say) referencing $! first, and %! second would
2637 mean that %! was not handled correctly. */
1604cfb0 2638 if (len == 1 && stash == PL_defstash) {
070dc475 2639 maybe_multimagic_gv(gv, name, sv_type);
1604cfb0 2640 }
b59bf0b2 2641 else if (sv_type == SVt_PVAV
1604cfb0
MS
2642 && memEQs(name, len, "ISA")
2643 && (!GvAV(gv) || !SvSMAGICAL(GvAV(gv))))
2644 gv_magicalize_isa(gv);
2645 }
2646 return gv;
71c35c05 2647 } else if (no_init) {
1604cfb0
MS
2648 assert(!addmg);
2649 return gv;
c002ae9a
BF
2650 }
2651 /* If GV_NOEXPAND is true and what we got off the stash is a ref,
2652 * don't expand it to a glob. This is an optimization so that things
2653 * copying constants over, like Exporter, don't have to be rewritten
2654 * to take into account that you can store more than just globs in
2655 * stashes.
2656 */
2657 else if (no_expand && SvROK(gv)) {
1604cfb0
MS
2658 assert(!addmg);
2659 return gv;
71c35c05
BF
2660 }
2661
2662 /* Adding a new symbol.
2663 Unless of course there was already something non-GV here, in which case
2664 we want to behave as if there was always a GV here, containing some sort
2665 of subroutine.
2666 Otherwise we run the risk of creating things like GvIO, which can cause
2667 subtle bugs. eg the one that tripped up SQL::Translator */
2668
2669 faking_it = SvOK(gv);
2670
2671 if (add & GV_ADDWARN)
1604cfb0
MS
2672 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2673 "Had to create %" UTF8f " unexpectedly",
2674 UTF8fARG(is_utf8, name_end-nambeg, nambeg));
71c35c05
BF
2675 gv_init_pvn(gv, stash, name, len, (add & GV_ADDMULTI)|is_utf8);
2676
7a207065
KW
2677 if ( full_len != 0
2678 && isIDFIRST_lazy_if_safe(name, name + full_len, is_utf8)
2679 && !ckWARN(WARN_ONCE) )
2680 {
71c35c05 2681 GvMULTI_on(gv) ;
7a207065 2682 }
71c35c05
BF
2683
2684 /* set up magic where warranted */
1321bbe3 2685 if ( gv_magicalize(gv, stash, name, len, sv_type) ) {
930867a8 2686 /* See 23496c6 */
1321bbe3
FC
2687 if (addmg) {
2688 /* gv_magicalize magicalised this gv, so we want it
930867a8 2689 * stored in the symtab.
9c913148 2690 * Effectively the caller is asking, ‘Does this gv exist?’
1321bbe3 2691 * And we respond, ‘Er, *now* it does!’
930867a8
BF
2692 */
2693 (void)hv_store(stash,name,len,(SV *)gv,0);
1321bbe3
FC
2694 }
2695 }
2696 else if (addmg) {
2697 /* The temporary GV created above */
930867a8
BF
2698 SvREFCNT_dec_NN(gv);
2699 gv = NULL;
930867a8 2700 }
9c913148 2701
e6066781 2702 if (gv) gv_init_svtype(gv, faking_it ? SVt_PVCV : sv_type);
93a17b20 2703 return gv;
79072805
LW
2704}
2705
a5dd70c5 2706/*
1607e393 2707=for apidoc gv_efullname3
a5dd70c5 2708=for apidoc_item gv_efullname4
1607e393
KW
2709=for apidoc_item gv_fullname3
2710=for apidoc_item gv_fullname4
a5dd70c5
KW
2711
2712Place the full package name of C<gv> into C<sv>. The C<gv_e*> forms return
2713instead the effective package name (see L</HvENAME>).
2714
2715If C<prefix> is non-NULL, it is considered to be a C language NUL-terminated
2716string, and the stored name will be prefaced with it.
2717
2718The other difference between the functions is that the C<*4> forms have an
2719extra parameter, C<keepmain>. If C<true> an initial C<main::> in the name is
2720kept; if C<false> it is stripped. With the C<*3> forms, it is always kept.
2721
2722=cut
2723*/
2724
79072805 2725void
35a4481c 2726Perl_gv_fullname4(pTHX_ SV *sv, const GV *gv, const char *prefix, bool keepmain)
43693395 2727{
ed60a868 2728 const char *name;
35a4481c 2729 const HV * const hv = GvSTASH(gv);
7918f24d
NC
2730
2731 PERL_ARGS_ASSERT_GV_FULLNAME4;
2732
666ea192 2733 sv_setpv(sv, prefix ? prefix : "");
a0288114 2734
52a6327b 2735 if (hv && (name = HvNAME(hv))) {
ed60a868 2736 const STRLEN len = HvNAMELEN(hv);
61e2287f 2737 if (keepmain || ! memBEGINs(name, len, "main")) {
1604cfb0
MS
2738 sv_catpvn_flags(sv,name,len,HvNAMEUTF8(hv)?SV_CATUTF8:SV_CATBYTES);
2739 sv_catpvs(sv,"::");
ed60a868 2740 }
43693395 2741 }
ed60a868 2742 else sv_catpvs(sv,"__ANON__::");
518db96a 2743 sv_catsv(sv,newSVhek_mortal(GvNAME_HEK(gv)));
43693395
GS
2744}
2745
2746void
35a4481c 2747Perl_gv_efullname4(pTHX_ SV *sv, const GV *gv, const char *prefix, bool keepmain)
43693395 2748{
099be4f1 2749 const GV * const egv = GvEGVx(gv);
7918f24d
NC
2750
2751 PERL_ARGS_ASSERT_GV_EFULLNAME4;
2752
46c461b5 2753 gv_fullname4(sv, egv ? egv : gv, prefix, keepmain);
43693395
GS
2754}
2755
39a65960
DM
2756
2757/* recursively scan a stash and any nested stashes looking for entries
2758 * that need the "only used once" warning raised
2759 */
2760
79072805 2761void
51da40ed 2762Perl_gv_check(pTHX_ HV *stash)
79072805 2763{
eb578fdb 2764 I32 i;
463ee0b2 2765
7918f24d
NC
2766 PERL_ARGS_ASSERT_GV_CHECK;
2767
53083cad 2768 if (!HvHasAUX(stash))
1604cfb0 2769 return;
90754377 2770
9e5cda6b 2771 assert(HvARRAY(stash));
90754377 2772
0cdaae3e
NC
2773 /* mark stash is being scanned, to avoid recursing */
2774 HvAUX(stash)->xhv_aux_flags |= HvAUXf_SCAN_STASH;
a0d0e21e 2775 for (i = 0; i <= (I32) HvMAX(stash); i++) {
e1ec3a88 2776 const HE *entry;
1604cfb0 2777 for (entry = HvARRAY(stash)[i]; entry; entry = HeNEXT(entry)) {
eb578fdb 2778 GV *gv;
b7787f18 2779 HV *hv;
1604cfb0 2780 STRLEN keylen = HeKLEN(entry);
e7acdfe9
DM
2781 const char * const key = HeKEY(entry);
2782
1604cfb0
MS
2783 if (keylen >= 2 && key[keylen-2] == ':' && key[keylen-1] == ':' &&
2784 (gv = MUTABLE_GV(HeVAL(entry))) && isGV(gv) && (hv = GvHV(gv)))
2785 {
2786 if (hv != PL_defstash && hv != stash
53083cad 2787 && !(HvHasAUX(hv)
90754377
DM
2788 && (HvAUX(hv)->xhv_aux_flags & HvAUXf_SCAN_STASH))
2789 )
1604cfb0
MS
2790 gv_check(hv); /* nested package */
2791 }
7a207065
KW
2792 else if ( HeKLEN(entry) != 0
2793 && *HeKEY(entry) != '_'
2794 && isIDFIRST_lazy_if_safe(HeKEY(entry),
2795 HeKEY(entry) + HeKLEN(entry),
2796 HeUTF8(entry)) )
2797 {
e1ec3a88 2798 const char *file;
1604cfb0
MS
2799 gv = MUTABLE_GV(HeVAL(entry));
2800 if (SvTYPE(gv) != SVt_PVGV || GvMULTI(gv))
2801 continue;
2802 file = GvFILE(gv);
6760f691 2803 assert(PL_curcop == &PL_compiling);
1604cfb0 2804 CopLINE_set(PL_curcop, GvLINE(gv));
1dc74fdb 2805#ifdef USE_ITHREADS
6760f691
YO
2806 SAVECOPFILE_FREE(PL_curcop);
2807 CopFILE_set(PL_curcop, (char *)file); /* set for warning */
1dc74fdb 2808#else
1604cfb0
MS
2809 CopFILEGV(PL_curcop)
2810 = gv_fetchfile_flags(file, HEK_LEN(GvFILE_HEK(gv)), 0);
1dc74fdb 2811#endif
1604cfb0
MS
2812 Perl_warner(aTHX_ packWARN(WARN_ONCE),
2813 "Name \"%" HEKf "::%" HEKf
2814 "\" used only once: possible typo",
d0c0e7dd
FC
2815 HEKfARG(HvNAME_HEK(stash)),
2816 HEKfARG(GvNAME_HEK(gv)));
1604cfb0
MS
2817 }
2818 }
79072805 2819 }
0cdaae3e 2820 HvAUX(stash)->xhv_aux_flags &= ~HvAUXf_SCAN_STASH;
79072805
LW
2821}
2822
875e4924
KW
2823/*
2824=for apidoc newGVgen
2825=for apidoc_item newGVgen_flags
2826
2827Create a new, guaranteed to be unique, GV in the package given by the
2828NUL-terminated C language string C<pack>, and return a pointer to it.
2829
2830For C<newGVgen> or if C<flags> in C<newGVgen_flags> is 0, C<pack> is to be
2831considered to be encoded in Latin-1. The only other legal C<flags> value is
2832C<SVf_UTF8>, which indicates C<pack> is to be considered to be encoded in
2833UTF-8.
2834
2835=cut
2836*/
2837
79072805 2838GV *
9cc50d5b 2839Perl_newGVgen_flags(pTHX_ const char *pack, U32 flags)
79072805 2840{
9cc50d5b 2841 PERL_ARGS_ASSERT_NEWGVGEN_FLAGS;
b17a0679 2842 assert(!(flags & ~SVf_UTF8));
7918f24d 2843
147e3846 2844 return gv_fetchpv(Perl_form(aTHX_ "%" UTF8f "::_GEN_%ld",
b17a0679 2845 UTF8fARG(flags, strlen(pack), pack),
9cc50d5b
BF
2846 (long)PL_gensym++),
2847 GV_ADD, SVt_PVGV);
79072805
LW
2848}
2849
2850/* hopefully this is only called on local symbol table entries */
2851
2852GP*
864dbfa3 2853Perl_gp_ref(pTHX_ GP *gp)
79072805 2854{
1d7c1841 2855 if (!gp)
1604cfb0 2856 return NULL;
79072805 2857 gp->gp_refcnt++;
44a8e56a 2858 if (gp->gp_cv) {
1604cfb0
MS
2859 if (gp->gp_cvgen) {
2860 /* If the GP they asked for a reference to contains
e1a479c5
BB
2861 a method cache entry, clear it first, so that we
2862 don't infect them with our cached entry */
1604cfb0
MS
2863 SvREFCNT_dec_NN(gp->gp_cv);
2864 gp->gp_cv = NULL;
2865 gp->gp_cvgen = 0;
2866 }
44a8e56a 2867 }
79072805 2868 return gp;
79072805
LW
2869}
2870
2871void
864dbfa3 2872Perl_gp_free(pTHX_ GV *gv)
79072805 2873{
79072805 2874 GP* gp;
b0d55c99 2875 int attempts = 100;
2c205b54 2876 bool in_global_destruction = PL_phase == PERL_PHASE_DESTRUCT;
79072805 2877
f7877b28 2878 if (!gv || !isGV_with_GP(gv) || !(gp = GvGP(gv)))
1604cfb0 2879 return;
f248d071 2880 if (gp->gp_refcnt == 0) {
1604cfb0
MS
2881 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2882 "Attempt to free unreferenced glob pointers"
2883 pTHX__FORMAT pTHX__VALUE);
79072805
LW
2884 return;
2885 }
4571f4a7 2886 if (gp->gp_refcnt > 1) {
bc81b34d 2887 borrowed:
1604cfb0
MS
2888 if (gp->gp_egv == gv)
2889 gp->gp_egv = 0;
2890 gp->gp_refcnt--;
2891 GvGP_set(gv, NULL);
79072805 2892 return;
748a9306 2893 }
79072805 2894
b0d55c99
FC
2895 while (1) {
2896 /* Copy and null out all the glob slots, so destructors do not see
2897 freed SVs. */
2898 HEK * const file_hek = gp->gp_file_hek;
2c205b54
NC
2899 SV * sv = gp->gp_sv;
2900 AV * av = gp->gp_av;
2901 HV * hv = gp->gp_hv;
2902 IO * io = gp->gp_io;
2903 CV * cv = gp->gp_cv;
2904 CV * form = gp->gp_form;
2905
2906 int need = 0;
b0d55c99
FC
2907
2908 gp->gp_file_hek = NULL;
2909 gp->gp_sv = NULL;
2910 gp->gp_av = NULL;
2911 gp->gp_hv = NULL;
2912 gp->gp_io = NULL;
2913 gp->gp_cv = NULL;
2914 gp->gp_form = NULL;
2915
2916 if (file_hek)
1604cfb0 2917 unshare_hek(file_hek);
b0d55c99 2918
2c205b54
NC
2919 /* Storing the SV on the temps stack (instead of freeing it immediately)
2920 is an admitted bodge that attempt to compensate for the lack of
2921 reference counting on the stack. The motivation is that typeglob syntax
2922 is extremely short hence programs such as '$a += (*a = 2)' are often
2923 found randomly by researchers running fuzzers. Previously these
2924 programs would trigger errors, that the researchers would
2925 (legitimately) report, and then we would spend time figuring out that
2926 the cause was "stack not reference counted" and so not a dangerous
2927 security hole. This consumed a lot of researcher time, our time, and
2928 prevents "interesting" security holes being uncovered.
2929
2930 Typeglob assignment is rarely used in performance critical production
2931 code, so we aren't causing much slowdown by doing extra work here.
2932
2933 In turn, the need to check for SvOBJECT (and references to objects) is
2934 because we have regression tests that rely on timely destruction that
2935 happens *within this while loop* to demonstrate behaviour, and
2936 potentially there is also *working* code in the wild that relies on
2937 such behaviour.
2938
2939 And we need to avoid doing this in global destruction else we can end
2940 up with "Attempt to free temp prematurely ... Unbalanced string table
2941 refcount".
2942
2943 Hence the whole thing is a heuristic intended to mitigate against
2944 simple problems likely found by fuzzers but never written by humans,
2945 whilst leaving working code unchanged. */
2946 if (sv) {
0c6362ad 2947 SV *referent;
2c205b54
NC
2948 if (SvREFCNT(sv) > 1 || SvOBJECT(sv) || UNLIKELY(in_global_destruction)) {
2949 SvREFCNT_dec_NN(sv);
2950 sv = NULL;
0c6362ad
JK
2951 } else if (SvROK(sv) && (referent = SvRV(sv))
2952 && (SvREFCNT(referent) > 1 || SvOBJECT(referent))) {
2c205b54
NC
2953 SvREFCNT_dec_NN(sv);
2954 sv = NULL;
2955 } else {
2956 ++need;
2957 }
2958 }
2959 if (av) {
2960 if (SvREFCNT(av) > 1 || SvOBJECT(av) || UNLIKELY(in_global_destruction)) {
2961 SvREFCNT_dec_NN(av);
2962 av = NULL;
2963 } else {
2964 ++need;
2965 }
2966 }
b0d55c99
FC
2967 /* FIXME - another reference loop GV -> symtab -> GV ?
2968 Somehow gp->gp_hv can end up pointing at freed garbage. */
2969 if (hv && SvTYPE(hv) == SVt_PVHV) {
c2242065 2970 const HEK *hvname_hek = HvNAME_HEK(hv);
923ed580
FC
2971 if (PL_stashcache && hvname_hek) {
2972 DEBUG_o(Perl_deb(aTHX_
147e3846 2973 "gp_free clearing PL_stashcache for '%" HEKf "'\n",
923ed580 2974 HEKfARG(hvname_hek)));
0ca9877d 2975 (void)hv_deletehek(PL_stashcache, hvname_hek, G_DISCARD);
923ed580 2976 }
2c205b54
NC
2977 if (SvREFCNT(hv) > 1 || SvOBJECT(hv) || UNLIKELY(in_global_destruction)) {
2978 SvREFCNT_dec_NN(hv);
2979 hv = NULL;
2980 } else {
2981 ++need;
2982 }
b0d55c99 2983 }
96d7c888 2984 if (io && SvREFCNT(io) == 1 && IoIFP(io)
1604cfb0
MS
2985 && (IoTYPE(io) == IoTYPE_WRONLY ||
2986 IoTYPE(io) == IoTYPE_RDWR ||
2987 IoTYPE(io) == IoTYPE_APPEND)
2988 && ckWARN_d(WARN_IO)
2989 && IoIFP(io) != PerlIO_stdin()
2990 && IoIFP(io) != PerlIO_stdout()
2991 && IoIFP(io) != PerlIO_stderr()
2992 && !(IoFLAGS(io) & IOf_FAKE_DIRP))
2993 io_close(io, gv, FALSE, TRUE);
2c205b54
NC
2994 if (io) {
2995 if (SvREFCNT(io) > 1 || SvOBJECT(io) || UNLIKELY(in_global_destruction)) {
2996 SvREFCNT_dec_NN(io);
2997 io = NULL;
2998 } else {
2999 ++need;
3000 }
3001 }
3002 if (cv) {
3003 if (SvREFCNT(cv) > 1 || SvOBJECT(cv) || UNLIKELY(in_global_destruction)) {
3004 SvREFCNT_dec_NN(cv);
3005 cv = NULL;
3006 } else {
3007 ++need;
3008 }
3009 }
3010 if (form) {
3011 if (SvREFCNT(form) > 1 || SvOBJECT(form) || UNLIKELY(in_global_destruction)) {
3012 SvREFCNT_dec_NN(form);
3013 form = NULL;
3014 } else {
3015 ++need;
3016 }
3017 }
3018
3019 if (need) {
3020 /* We don't strictly need to defer all this to the end, but it's
3021 easiest to do so. The subtle problems we have are
3022 1) any of the actions triggered by the various SvREFCNT_dec()s in
3023 any of the intermediate blocks can cause more items to be added
3024 to the temps stack. So we can't "cache" its state locally
3025 2) We'd have to re-check the "extend by 1?" for each time.
3026 Whereas if we don't NULL out the values that we want to put onto
3027 the save stack until here, we can do it in one go, with one
3028 one size check. */
3029
3030 SSize_t max_ix = PL_tmps_ix + need;
3031
3032 if (max_ix >= PL_tmps_max) {
3033 tmps_grow_p(max_ix);
3034 }
3035
3036 if (sv) {
3037 PL_tmps_stack[++PL_tmps_ix] = sv;
3038 }
3039 if (av) {
3040 PL_tmps_stack[++PL_tmps_ix] = (SV *) av;
3041 }
3042 if (hv) {
3043 PL_tmps_stack[++PL_tmps_ix] = (SV *) hv;
3044 }
3045 if (io) {
3046 PL_tmps_stack[++PL_tmps_ix] = (SV *) io;
3047 }
3048 if (cv) {
3049 PL_tmps_stack[++PL_tmps_ix] = (SV *) cv;
3050 }
3051 if (form) {
3052 PL_tmps_stack[++PL_tmps_ix] = (SV *) form;
3053 }
3054 }
b0d55c99 3055
bc81b34d
FC
3056 /* Possibly reallocated by a destructor */
3057 gp = GvGP(gv);
3058
b0d55c99
FC
3059 if (!gp->gp_file_hek
3060 && !gp->gp_sv
3061 && !gp->gp_av
3062 && !gp->gp_hv
3063 && !gp->gp_io
3064 && !gp->gp_cv
3065 && !gp->gp_form) break;
3066
3067 if (--attempts == 0) {
1604cfb0
MS
3068 Perl_die(aTHX_
3069 "panic: gp_free failed to free glob pointer - "
3070 "something is repeatedly re-creating entries"
3071 );
b0d55c99 3072 }
13207a71 3073 }
748a9306 3074
bc81b34d
FC
3075 /* Possibly incremented by a destructor doing glob assignment */
3076 if (gp->gp_refcnt > 1) goto borrowed;
79072805 3077 Safefree(gp);
c43ae56f 3078 GvGP_set(gv, NULL);
79072805
LW
3079}
3080
d460ef45
NIS
3081int
3082Perl_magic_freeovrld(pTHX_ SV *sv, MAGIC *mg)
3083{
53c1dcc0
AL
3084 AMT * const amtp = (AMT*)mg->mg_ptr;
3085 PERL_UNUSED_ARG(sv);
dd374669 3086
7918f24d
NC
3087 PERL_ARGS_ASSERT_MAGIC_FREEOVRLD;
3088
d460ef45 3089 if (amtp && AMT_AMAGIC(amtp)) {
1604cfb0
MS
3090 int i;
3091 for (i = 1; i < NofAMmeth; i++) {
3092 CV * const cv = amtp->table[i];
3093 if (cv) {
3094 SvREFCNT_dec_NN(MUTABLE_SV(cv));
3095 amtp->table[i] = NULL;
3096 }
3097 }
d460ef45
NIS
3098 }
3099 return 0;
3100}
3101
30062c3a
KW
3102/*
3103=for apidoc Gv_AMupdate
3104
3105Recalculates overload magic in the package given by C<stash>.
3106
3107Returns:
3108
3109=over
3110
3111=item 1 on success and there is some overload
3112
3113=item 0 if there is no overload
3114
3115=item -1 if some error occurred and it couldn't croak (because C<destructing>
3116is true).
3117
3118=back
3119
3120=cut
3121*/
a0d0e21e 3122
c3a9a790 3123int
242f8760 3124Perl_Gv_AMupdate(pTHX_ HV *stash, bool destructing)
a0d0e21e 3125{
ad64d0ec 3126 MAGIC* const mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
a6006777 3127 AMT amt;
9b439311 3128 const struct mro_meta* stash_meta = HvMROMETA(stash);
e1a479c5 3129 U32 newgen;
a0d0e21e 3130
7918f24d
NC
3131 PERL_ARGS_ASSERT_GV_AMUPDATE;
3132
9b439311 3133 newgen = PL_sub_generation + stash_meta->pkg_gen + stash_meta->cache_gen;
14899595
NC
3134 if (mg) {
3135 const AMT * const amtp = (AMT*)mg->mg_ptr;
66978156 3136 if (amtp->was_ok_sub == newgen) {
1604cfb0 3137 return AMT_AMAGIC(amtp) ? 1 : 0;
14899595 3138 }
ad64d0ec 3139 sv_unmagic(MUTABLE_SV(stash), PERL_MAGIC_overload_table);
14899595 3140 }
a0d0e21e 3141
0c6362ad 3142 DEBUG_o( Perl_deb(aTHX_ "Recalculating overload magic in package %s\n",HvNAME_get(stash)) );
a0d0e21e 3143
d460ef45 3144 Zero(&amt,1,AMT);
e1a479c5 3145 amt.was_ok_sub = newgen;
a6006777 3146 amt.fallback = AMGfallNO;
3147 amt.flags = 0;
3148
a6006777 3149 {
8c34e50d
FC
3150 int filled = 0;
3151 int i;
3d147ac2
DM
3152 bool deref_seen = 0;
3153
a6006777 3154
3866ea3b 3155 /* Work with "fallback" key, which we assume to be first in PL_AMG_names */
a6006777 3156
89ffc314 3157 /* Try to find via inheritance. */
e6919483 3158 GV *gv = gv_fetchmeth_pvn(stash, PL_AMG_names[0], 2, -1, 0);
3866ea3b 3159 SV * const sv = gv ? GvSV(gv) : NULL;
53c1dcc0 3160 CV* cv;
89ffc314
IZ
3161
3162 if (!gv)
3866ea3b
FC
3163 {
3164 if (!gv_fetchmeth_pvn(stash, "((", 2, -1, 0))
1604cfb0 3165 goto no_table;
3866ea3b
FC
3166 }
3167#ifdef PERL_DONT_CREATE_GVSV
3168 else if (!sv) {
1604cfb0 3169 NOOP; /* Equivalent to !SvTRUE and !SvOK */
3866ea3b
FC
3170 }
3171#endif
79c9643d
JL
3172 else if (SvTRUE(sv))
3173 /* don't need to set overloading here because fallback => 1
3174 * is the default setting for classes without overloading */
1604cfb0 3175 amt.fallback=AMGfallYES;
79c9643d 3176 else if (SvOK(sv)) {
1604cfb0 3177 amt.fallback=AMGfallNEVER;
386a5489 3178 filled = 1;
386a5489 3179 }
79c9643d 3180 else {
386a5489 3181 filled = 1;
386a5489 3182 }
a6006777 3183
53083cad 3184 assert(HvHasAUX(stash));
3d147ac2 3185 /* initially assume the worst */
339441ef 3186 HvAUX(stash)->xhv_aux_flags &= ~HvAUXf_NO_DEREF;
3d147ac2 3187
8c34e50d 3188 for (i = 1; i < NofAMmeth; i++) {
1604cfb0
MS
3189 const char * const cooky = PL_AMG_names[i];
3190 /* Human-readable form, for debugging: */
3191 const char * const cp = AMG_id2name(i);
3192 const STRLEN l = PL_AMG_namelens[i];
3193
3194 DEBUG_o( Perl_deb(aTHX_ "Checking overloading of \"%s\" in package \"%.256s\"\n",
3195 cp, HvNAME_get(stash)) );
3196 /* don't fill the cache while looking up!
3197 Creation of inheritance stubs in intermediate packages may
3198 conflict with the logic of runtime method substitution.
3199 Indeed, for inheritance A -> B -> C, if C overloads "+0",
3200 then we could have created stubs for "(+0" in A and C too.
3201 But if B overloads "bool", we may want to use it for
3202 numifying instead of C's "+0". */
3203 gv = Perl_gv_fetchmeth_pvn(aTHX_ stash, cooky, l, -1, 0);
46fc3d4c 3204 cv = 0;
c3ad4e54 3205 if (gv && (cv = GvCV(gv)) && CvHASGV(cv)) {
79656330 3206 const HEK * const gvhek = CvGvNAME_HEK(cv);
c3ad4e54
FC
3207 const HEK * const stashek =
3208 HvNAME_HEK(CvNAMED(cv) ? CvSTASH(cv) : GvSTASH(CvGV(cv)));
b59bf0b2
KW
3209 if (memEQs(HEK_KEY(gvhek), HEK_LEN(gvhek), "nil")
3210 && stashek
3211 && memEQs(HEK_KEY(stashek), HEK_LEN(stashek), "overload")) {
1604cfb0
MS
3212 /* This is a hack to support autoloading..., while
3213 knowing *which* methods were declared as overloaded. */
3214 /* GvSV contains the name of the method. */
3215 GV *ngv = NULL;
3216 SV *gvsv = GvSV(gv);
3217
3218 DEBUG_o( Perl_deb(aTHX_ "Resolving method \"%" SVf256\
3219 "\" for overloaded \"%s\" in package \"%.256s\"\n",
3220 (void*)GvSV(gv), cp, HvNAME(stash)) );
3221 if (!gvsv || !SvPOK(gvsv)
3222 || !(ngv = gv_fetchmethod_sv_flags(stash, gvsv, 0)))
3223 {
3224 /* Can be an import stub (created by "can"). */
3225 if (destructing) {
3226 return -1;
3227 }
3228 else {
3229 const SV * const name = (gvsv && SvPOK(gvsv))
d66cca07
BF
3230 ? gvsv
3231 : newSVpvs_flags("???", SVs_TEMP);
1604cfb0
MS
3232 /* diag_listed_as: Can't resolve method "%s" overloading "%s" in package "%s" */
3233 Perl_croak(aTHX_ "%s method \"%" SVf256
3234 "\" overloading \"%s\" "\
3235 "in package \"%" HEKf256 "\"",
3236 (GvCVGEN(gv) ? "Stub found while resolving"
3237 : "Can't resolve"),
3238 SVfARG(name), cp,
d0c0e7dd 3239 HEKfARG(
1604cfb0
MS
3240 HvNAME_HEK(stash)
3241 ));
3242 }
3243 }
3244 cv = GvCV(gv = ngv);
3245 }
3246 DEBUG_o( Perl_deb(aTHX_ "Overloading \"%s\" in package \"%.256s\" via \"%.256s::%.256s\"\n",
3247 cp, HvNAME_get(stash), HvNAME_get(GvSTASH(CvGV(cv))),
3248 GvNAME(CvGV(cv))) );
3249 filled = 1;
3250 } else if (gv) { /* Autoloaded... */
3251 cv = MUTABLE_CV(gv);
3252 filled = 1;
3253 }
3254 amt.table[i]=MUTABLE_CV(SvREFCNT_inc_simple(cv));
3d147ac2
DM
3255
3256 if (gv) {
3257 switch (i) {
3258 case to_sv_amg:
3259 case to_av_amg:
3260 case to_hv_amg:
3261 case to_gv_amg:
3262 case to_cv_amg:
3263 case nomethod_amg:
3264 deref_seen = 1;
3265 break;
3266 }
3267 }
a0d0e21e 3268 }
3d147ac2 3269 if (!deref_seen)
45479970
DM
3270 /* none of @{} etc overloaded; we can do $obj->[N] quicker.
3271 * NB - aux var invalid here, HvARRAY() could have been
3272 * reallocated since it was assigned to */
3273 HvAUX(stash)->xhv_aux_flags |= HvAUXf_NO_DEREF;
3d147ac2 3274
a0d0e21e 3275 if (filled) {
a6006777 3276 AMT_AMAGIC_on(&amt);
ad64d0ec 3277 sv_magic(MUTABLE_SV(stash), 0, PERL_MAGIC_overload_table,
1604cfb0 3278 (char*)&amt, sizeof(AMT));
8c34e50d 3279 return TRUE;
a0d0e21e
LW
3280 }
3281 }
a6006777 3282 /* Here we have no table: */
8c34e50d 3283 no_table:
a6006777 3284 AMT_AMAGIC_off(&amt);
ad64d0ec 3285 sv_magic(MUTABLE_SV(stash), 0, PERL_MAGIC_overload_table,
1604cfb0 3286 (char*)&amt, sizeof(AMTS));
c3a9a790 3287 return 0;
a0d0e21e
LW
3288}
3289
7f3d1102
KW
3290/*
3291=for apidoc gv_handler
3292
3293Implements C<StashHANDLER>, which you should use instead
3294
3295=cut
3296*/
32251b26
IZ
3297
3298CV*
3299Perl_gv_handler(pTHX_ HV *stash, I32 id)
3300{
3f8f4626 3301 MAGIC *mg;
32251b26 3302 AMT *amtp;
e1a479c5 3303 U32 newgen;
9b439311 3304 struct mro_meta* stash_meta;
32251b26 3305
2e4090b8 3306 if (!stash || !HvHasNAME(stash))
601f1833 3307 return NULL;
e1a479c5 3308
9b439311
BB
3309 stash_meta = HvMROMETA(stash);
3310 newgen = PL_sub_generation + stash_meta->pkg_gen + stash_meta->cache_gen;
e1a479c5 3311
ad64d0ec 3312 mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
32251b26
IZ
3313 if (!mg) {
3314 do_update:
1604cfb0
MS
3315 if (Gv_AMupdate(stash, 0) == -1)
3316 return NULL;
3317 mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
32251b26 3318 }
a9fd4e40 3319 assert(mg);
32251b26 3320 amtp = (AMT*)mg->mg_ptr;
66978156 3321 if ( amtp->was_ok_sub != newgen )
1604cfb0 3322 goto do_update;
3ad83ce7 3323 if (AMT_AMAGIC(amtp)) {
1604cfb0
MS
3324 CV * const ret = amtp->table[id];
3325 if (ret && isGV(ret)) { /* Autoloading stab */
3326 /* Passing it through may have resulted in a warning
3327 "Inherited AUTOLOAD for a non-method deprecated", since
3328 our caller is going through a function call, not a method call.
3329 So return the CV for AUTOLOAD, setting $AUTOLOAD. */
3330 GV * const gv = gv_fetchmethod(stash, PL_AMG_names[id]);
3331
3332 if (gv && GvCV(gv))
3333 return GvCV(gv);
3334 }
3335 return ret;
3ad83ce7 3336 }
a0288114 3337
601f1833 3338 return NULL;
32251b26
IZ
3339}
3340
3341
6f1401dc
DM
3342/* Implement tryAMAGICun_MG macro.
3343 Do get magic, then see if the stack arg is overloaded and if so call it.
3344 Flags:
1604cfb0 3345 AMGf_numeric apply sv_2num to the stack arg.
6f1401dc
DM
3346*/
3347
3348bool
3349Perl_try_amagic_un(pTHX_ int method, int flags) {
6f1401dc
DM
3350 dSP;
3351 SV* tmpsv;
3352 SV* const arg = TOPs;
3353
3354 SvGETMAGIC(arg);
3355
9f8bf298 3356 if (SvAMAGIC(arg) && (tmpsv = amagic_call(arg, &PL_sv_undef, method,
1604cfb0
MS
3357 AMGf_noright | AMGf_unary
3358 | (flags & AMGf_numarg))))
636ac8fc 3359 {
13874762
DM
3360 /* where the op is of the form:
3361 * $lex = $x op $y (where the assign is optimised away)
3362 * then assign the returned value to targ and return that;
3363 * otherwise return the value directly
3364 */
3365 if ( (PL_opargs[PL_op->op_type] & OA_TARGLEX)
3366 && (PL_op->op_private & OPpTARGET_MY))
3367 {
3368 dTARGET;
3369 sv_setsv(TARG, tmpsv);
3370 SETTARG;
3371 }
3372 else
3373 SETs(tmpsv);
3374
1604cfb0
MS
3375 PUTBACK;
3376 return TRUE;
6f1401dc
DM
3377 }
3378
3379 if ((flags & AMGf_numeric) && SvROK(arg))
1604cfb0 3380 *sp = sv_2num(arg);
6f1401dc
DM
3381 return FALSE;
3382}
3383
3384
bab261c9 3385/*
8da47909 3386=for apidoc amagic_applies
bab261c9 3387
8da47909
YO
3388Check C<sv> to see if the overloaded (active magic) operation C<method>
3389applies to it. If the sv is not SvROK or it is not an object then returns
3390false, otherwise checks if the object is blessed into a class supporting
3391overloaded operations, and returns true if a call to amagic_call() with
3392this SV and the given method would trigger an amagic operation, including
3393via the overload fallback rules or via nomethod. Thus a call like:
bab261c9 3394
8da47909
YO
3395 amagic_applies(sv, string_amg, AMG_unary)
3396
3397would return true for an object with overloading set up in any of the
3398following ways:
3399
3400 use overload q("") => sub { ... };
3401 use overload q(0+) => sub { ... }, fallback => 1;
3402
3403and could be used to tell if a given object would stringify to something
3404other than the normal default ref stringification.
bab261c9 3405
8da47909
YO
3406Note that the fact that this function returns TRUE does not mean you
3407can succesfully perform the operation with amagic_call(), for instance
3408any overloaded method might throw a fatal exception, however if this
3409function returns FALSE you can be confident that it will NOT perform
3410the given overload operation.
3411
3412C<method> is an integer enum, one of the values found in F<overload.h>,
3413for instance C<string_amg>.
3414
3415C<flags> should be set to AMG_unary for unary operations.
bab261c9
EH
3416
3417=cut
3418*/
8da47909
YO
3419bool
3420Perl_amagic_applies(pTHX_ SV *sv, int method, int flags)
bab261c9 3421{
8da47909 3422 PERL_ARGS_ASSERT_AMAGIC_APPLIES;
bab261c9
EH
3423 PERL_UNUSED_VAR(flags);
3424
3425 assert(method >= 0 && method < NofAMmeth);
3426
3427 if (!SvAMAGIC(sv))
8da47909 3428 return FALSE;
bab261c9
EH
3429
3430 HV *stash = SvSTASH(SvRV(sv));
3431 if (!Gv_AMG(stash))
8da47909 3432 return FALSE;
bab261c9
EH
3433
3434 MAGIC *mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table);
3435 if (!mg)
8da47909 3436 return FALSE;
bab261c9
EH
3437
3438 CV **cvp = NULL;
8da47909
YO
3439 AMT *amtp = NULL;
3440 if (AMT_AMAGIC((AMT *)mg->mg_ptr)) {
3441 amtp = (AMT *)mg->mg_ptr;
3442 cvp = amtp->table;
3443 }
bab261c9 3444 if (!cvp)
8da47909
YO
3445 return FALSE;
3446
3447 if (cvp[method])
3448 return TRUE;
3449
3450 /* Note this logic should be kept in sync with amagic_call() */
3451 if (amtp->fallback > AMGfallNEVER && flags & AMGf_unary) {
3452 CV *cv; /* This makes it easier to kee ... */
3453 int off,off1; /* ... in sync with amagic_call() */
bab261c9 3454
8da47909
YO
3455 /* look for substituted methods */
3456 /* In all the covered cases we should be called with assign==0. */
3457 switch (method) {
3458 case inc_amg:
3459 if ((cv = cvp[off=add_ass_amg]) || ((cv = cvp[off = add_amg])))
3460 return TRUE;
3461 break;
3462 case dec_amg:
3463 if((cv = cvp[off = subtr_ass_amg]) || ((cv = cvp[off = subtr_amg])))
3464 return TRUE;
3465 break;
3466 case bool__amg:
3467 if ((cv = cvp[off=numer_amg]) || (cv = cvp[off=string_amg]))
3468 return TRUE;
3469 break;
3470 case numer_amg:
3471 if((cv = cvp[off=string_amg]) || (cv = cvp[off=bool__amg]))
3472 return TRUE;
3473 break;
3474 case string_amg:
3475 if((cv = cvp[off=numer_amg]) || (cv = cvp[off=bool__amg]))
3476 return TRUE;
3477 break;
3478 case not_amg:
3479 if((cv = cvp[off=bool__amg])
3480 || (cv = cvp[off=numer_amg])
3481 || (cv = cvp[off=string_amg]))
3482 return TRUE;
3483 break;
3484 case abs_amg:
3485 if((cvp[off1=lt_amg] || cvp[off1=ncmp_amg])
3486 && ((cv = cvp[off=neg_amg]) || (cv = cvp[off=subtr_amg])))
3487 return TRUE;
3488 break;
3489 case neg_amg:
3490 if ((cv = cvp[off=subtr_amg]))
3491 return TRUE;
3492 break;
3493 }
3494 } else if (((cvp && amtp->fallback > AMGfallNEVER))
3495 && !(flags & AMGf_unary)) {
3496 /* We look for substitution for
3497 * comparison operations and
3498 * concatenation */
3499 if (method==concat_amg || method==concat_ass_amg
3500 || method==repeat_amg || method==repeat_ass_amg) {
3501 return FALSE; /* Delegate operation to string conversion */
3502 }
3503 switch (method) {
3504 case lt_amg:
3505 case le_amg:
3506 case gt_amg:
3507 case ge_amg:
3508 case eq_amg:
3509 case ne_amg:
3510 if (cvp[ncmp_amg])
3511 return TRUE;
3512 break;
3513 case slt_amg:
3514 case sle_amg:
3515 case sgt_amg:
3516 case sge_amg:
3517 case seq_amg:
3518 case sne_amg:
3519 if (cvp[scmp_amg])
3520 return TRUE;
3521 break;
3522 }
3523 }
3524
3525 if (cvp[nomethod_amg])
3526 return TRUE;
3527
3528 return FALSE;
bab261c9
EH
3529}
3530
3531
6f1401dc
DM
3532/* Implement tryAMAGICbin_MG macro.
3533 Do get magic, then see if the two stack args are overloaded and if so
3534 call it.
3535 Flags:
1604cfb0
MS
3536 AMGf_assign op may be called as mutator (eg +=)
3537 AMGf_numeric apply sv_2num to the stack arg.
6f1401dc
DM
3538*/
3539
3540bool
3541Perl_try_amagic_bin(pTHX_ int method, int flags) {
6f1401dc
DM
3542 dSP;
3543 SV* const left = TOPm1s;
3544 SV* const right = TOPs;
3545
3546 SvGETMAGIC(left);
3547 if (left != right)
1604cfb0 3548 SvGETMAGIC(right);
6f1401dc
DM
3549
3550 if (SvAMAGIC(left) || SvAMAGIC(right)) {
1604cfb0 3551 SV * tmpsv;
72876cce
DM
3552 /* STACKED implies mutator variant, e.g. $x += 1 */
3553 bool mutator = (flags & AMGf_assign) && (PL_op->op_flags & OPf_STACKED);
3554
1604cfb0
MS
3555 tmpsv = amagic_call(left, right, method,
3556 (mutator ? AMGf_assign: 0)
3557 | (flags & AMGf_numarg));
3558 if (tmpsv) {
13874762
DM
3559 (void)POPs;
3560 /* where the op is one of the two forms:
3561 * $x op= $y
3562 * $lex = $x op $y (where the assign is optimised away)
3563 * then assign the returned value to targ and return that;
3564 * otherwise return the value directly
3565 */
3566 if ( mutator
3567 || ( (PL_opargs[PL_op->op_type] & OA_TARGLEX)
3568 && (PL_op->op_private & OPpTARGET_MY)))
3569 {
3570 dTARG;
3571 TARG = mutator ? *SP : PAD_SV(PL_op->op_targ);
3572 sv_setsv(TARG, tmpsv);
3573 SETTARG;
3574 }
3575 else
3576 SETs(tmpsv);
3577
1604cfb0
MS
3578 PUTBACK;
3579 return TRUE;
3580 }
6f1401dc 3581 }
13874762 3582
75ea7a12 3583 if(left==right && SvGMAGICAL(left)) {
1604cfb0
MS
3584 SV * const left = sv_newmortal();
3585 *(sp-1) = left;
3586 /* Print the uninitialized warning now, so it includes the vari-
3587 able name. */
3588 if (!SvOK(right)) {
3589 if (ckWARN(WARN_UNINITIALIZED)) report_uninit(right);
1d0d673f 3590 sv_setbool(left, FALSE);
1604cfb0
MS
3591 }
3592 else sv_setsv_flags(left, right, 0);
3593 SvGETMAGIC(right);
75ea7a12 3594 }
6f1401dc 3595 if (flags & AMGf_numeric) {
1604cfb0
MS
3596 if (SvROK(TOPm1s))
3597 *(sp-1) = sv_2num(TOPm1s);
3598 if (SvROK(right))
3599 *sp = sv_2num(right);
6f1401dc
DM
3600 }
3601 return FALSE;
3602}
3603
0797ed67
KW
3604/*
3605=for apidoc amagic_deref_call
3606
3607Perform C<method> overloading dereferencing on C<ref>, returning the
3608dereferenced result. C<method> must be one of the dereference operations given
3609in F<overload.h>.
3610
3611If overloading is inactive on C<ref>, returns C<ref> itself.
3612
3613=cut
3614*/
3615
25a9ffce
NC
3616SV *
3617Perl_amagic_deref_call(pTHX_ SV *ref, int method) {
3618 SV *tmpsv = NULL;
3d147ac2 3619 HV *stash;
25a9ffce
NC
3620
3621 PERL_ARGS_ASSERT_AMAGIC_DEREF_CALL;
3622
3d147ac2
DM
3623 if (!SvAMAGIC(ref))
3624 return ref;
3625 /* return quickly if none of the deref ops are overloaded */
3626 stash = SvSTASH(SvRV(ref));
53083cad 3627 assert(HvHasAUX(stash));
3d147ac2
DM
3628 if (HvAUX(stash)->xhv_aux_flags & HvAUXf_NO_DEREF)
3629 return ref;
3630
3631 while ((tmpsv = amagic_call(ref, &PL_sv_undef, method,
9c913148 3632 AMGf_noright | AMGf_unary))) {
1604cfb0
MS
3633 if (!SvROK(tmpsv))
3634 Perl_croak(aTHX_ "Overloaded dereference did not return a reference");
3635 if (tmpsv == ref || SvRV(tmpsv) == SvRV(ref)) {
3636 /* Bail out if it returns us the same reference. */
3637 return tmpsv;
3638 }
3639 ref = tmpsv;
3d147ac2
DM
3640 if (!SvAMAGIC(ref))
3641 break;
25a9ffce
NC
3642 }
3643 return tmpsv ? tmpsv : ref;
3644}
6f1401dc 3645
8d569291
FC
3646bool
3647Perl_amagic_is_enabled(pTHX_ int method)
3648{
3649 SV *lex_mask = cop_hints_fetch_pvs(PL_curcop, "overloading", 0);
3650
3651 assert(PL_curcop->cop_hints & HINT_NO_AMAGIC);
3652
3653 if ( !lex_mask || !SvOK(lex_mask) )
1604cfb0
MS
3654 /* overloading lexically disabled */
3655 return FALSE;
8d569291 3656 else if ( lex_mask && SvPOK(lex_mask) ) {
1604cfb0
MS
3657 /* we have an entry in the hints hash, check if method has been
3658 * masked by overloading.pm */
3659 STRLEN len;
3660 const int offset = method / 8;
3661 const int bit = method % 8;
3662 char *pv = SvPV(lex_mask, len);
3663
3664 /* Bit set, so this overloading operator is disabled */
3665 if ( (STRLEN)offset < len && pv[offset] & ( 1 << bit ) )
3666 return FALSE;
8d569291
FC
3667 }
3668 return TRUE;
3669}
3670
0797ed67 3671/*
d487610d 3672=for apidoc amagic_call
0797ed67
KW
3673
3674Perform the overloaded (active magic) operation given by C<method>.
3675C<method> is one of the values found in F<overload.h>.
3676
3677C<flags> affects how the operation is performed, as follows:
3678
3679=over
3680
3681=item C<AMGf_noleft>
3682
3683C<left> is not to be used in this operation.
3684
3685=item C<AMGf_noright>
3686
3687C<right> is not to be used in this operation.
3688
3689=item C<AMGf_unary>
3690
3691The operation is done only on just one operand.
3692
3693=item C<AMGf_assign>
3694
3695The operation changes one of the operands, e.g., $x += 1
3696
3697=back
3698
3699=cut
3700*/
3701
a0d0e21e 3702SV*
864dbfa3 3703Perl_amagic_call(pTHX_ SV *left, SV *right, int method, int flags)
a0d0e21e 3704{
b267980d 3705 MAGIC *mg;
9c5ffd7c 3706 CV *cv=NULL;
a0d0e21e 3707 CV **cvp=NULL, **ocvp=NULL;
9c5ffd7c 3708 AMT *amtp=NULL, *oamtp=NULL;
b464bac0
AL
3709 int off = 0, off1, lr = 0, notfound = 0;
3710 int postpr = 0, force_cpy = 0;
3711 int assign = AMGf_assign & flags;
3712 const int assignshift = assign ? 1 : 0;
bf5522a1 3713 int use_default_op = 0;
67288365 3714 int force_scalar = 0;
497b47a8
JH
3715#ifdef DEBUGGING
3716 int fl=0;
497b47a8 3717#endif
25716404 3718 HV* stash=NULL;
7918f24d
NC
3719
3720 PERL_ARGS_ASSERT_AMAGIC_CALL;
3721
e46c382e 3722 if ( PL_curcop->cop_hints & HINT_NO_AMAGIC ) {
8d569291 3723 if (!amagic_is_enabled(method)) return NULL;
e46c382e
YK
3724 }
3725
a0d0e21e 3726 if (!(AMGf_noleft & flags) && SvAMAGIC(left)
0a2c84ab 3727 && (stash = SvSTASH(SvRV(left))) && Gv_AMG(stash)
ad64d0ec 3728 && (mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table))
b267980d 3729 && (ocvp = cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
1604cfb0
MS
3730 ? (oamtp = amtp = (AMT*)mg->mg_ptr)->table
3731 : NULL))
b267980d 3732 && ((cv = cvp[off=method+assignshift])
1604cfb0
MS
3733 || (assign && amtp->fallback > AMGfallNEVER && /* fallback to
3734 * usual method */
3735 (
497b47a8 3736#ifdef DEBUGGING
1604cfb0 3737 fl = 1,
a0288114 3738#endif
51254cb2
KW
3739 cv = cvp[off=method]))))
3740 {
a0d0e21e
LW
3741 lr = -1; /* Call method for left argument */
3742 } else {
8da47909 3743 /* Note this logic should be kept in sync with amagic_applies() */
a0d0e21e
LW
3744 if (cvp && amtp->fallback > AMGfallNEVER && flags & AMGf_unary) {
3745 int logic;
3746
3747 /* look for substituted methods */
ee239bfe 3748 /* In all the covered cases we should be called with assign==0. */
1604cfb0
MS
3749 switch (method) {
3750 case inc_amg:
3751 force_cpy = 1;
3752 if ((cv = cvp[off=add_ass_amg])
2eb3aaaa
JK
3753 || ((cv = cvp[off = add_amg])
3754 && (force_cpy = 0, (postpr = 1)))) {
1604cfb0
MS
3755 right = &PL_sv_yes; lr = -1; assign = 1;
3756 }
3757 break;
3758 case dec_amg:
3759 force_cpy = 1;
3760 if ((cv = cvp[off = subtr_ass_amg])
2eb3aaaa
JK
3761 || ((cv = cvp[off = subtr_amg])
3762 && (force_cpy = 0, (postpr=1)))) {
1604cfb0
MS
3763 right = &PL_sv_yes; lr = -1; assign = 1;
3764 }
3765 break;
3766 case bool__amg:
3767 (void)((cv = cvp[off=numer_amg]) || (cv = cvp[off=string_amg]));
3768 break;
3769 case numer_amg:
3770 (void)((cv = cvp[off=string_amg]) || (cv = cvp[off=bool__amg]));
3771 break;
3772 case string_amg:
3773 (void)((cv = cvp[off=numer_amg]) || (cv = cvp[off=bool__amg]));
3774 break;
b7787f18
AL
3775 case not_amg:
3776 (void)((cv = cvp[off=bool__amg])
3777 || (cv = cvp[off=numer_amg])
3778 || (cv = cvp[off=string_amg]));
2ab54efd
MB
3779 if (cv)
3780 postpr = 1;
b7787f18 3781 break;
1604cfb0
MS
3782 case copy_amg:
3783 {
3784 /*
3785 * SV* ref causes confusion with the interpreter variable of
3786 * the same name
3787 */
3788 SV* const tmpRef=SvRV(left);
3789 if (!SvROK(tmpRef) && SvTYPE(tmpRef) <= SVt_PVMG) {
3790 /*
3791 * Just to be extra cautious. Maybe in some
3792 * additional cases sv_setsv is safe, too.
3793 */
3794 SV* const newref = newSVsv(tmpRef);
3795 SvOBJECT_on(newref);
3796 /* No need to do SvAMAGIC_on here, as SvAMAGIC macros
3797 delegate to the stash. */
3798 SvSTASH_set(newref, MUTABLE_HV(SvREFCNT_inc(SvSTASH(tmpRef))));
3799 return newref;
3800 }
3801 }
3802 break;
3803 case abs_amg:
3804 if ((cvp[off1=lt_amg] || cvp[off1=ncmp_amg])
3805 && ((cv = cvp[off=neg_amg]) || (cv = cvp[off=subtr_amg]))) {
3806 SV* const nullsv=&PL_sv_zero;
3807 if (off1==lt_amg) {
3808 SV* const lessp = amagic_call(left,nullsv,
3809 lt_amg,AMGf_noright);
3810 logic = SvTRUE_NN(lessp);
3811 } else {
3812 SV* const lessp = amagic_call(left,nullsv,
3813 ncmp_amg,AMGf_noright);
3814 logic = (SvNV(lessp) < 0);
3815 }
3816 if (logic) {
3817 if (off==subtr_amg) {
3818 right = left;
3819 left = nullsv;
3820 lr = 1;
3821 }
3822 } else {
3823 return left;
3824 }
3825 }
3826 break;
3827 case neg_amg:
3828 if ((cv = cvp[off=subtr_amg])) {
3829 right = left;
3830 left = &PL_sv_zero;
3831 lr = 1;
3832 }
3833 break;
3834 case int_amg:
3835 case iter_amg: /* XXXX Eventually should do to_gv. */
3836 case ftest_amg: /* XXXX Eventually should do to_gv. */
3837 case regexp_amg:
3838 /* FAIL safe */
3839 return NULL; /* Delegate operation to standard mechanisms. */
3840
3841 case to_sv_amg:
3842 case to_av_amg:
3843 case to_hv_amg:
3844 case to_gv_amg:
3845 case to_cv_amg:
3846 /* FAIL safe */
3847 return left; /* Delegate operation to standard mechanisms. */
3848
3849 default:
3850 goto not_found;
3851 }
3852 if (!cv) goto not_found;
a0d0e21e 3853 } else if (!(AMGf_noright & flags) && SvAMAGIC(right)
1604cfb0
MS
3854 && (stash = SvSTASH(SvRV(right))) && Gv_AMG(stash)
3855 && (mg = mg_find((const SV *)stash, PERL_MAGIC_overload_table))
3856 && (cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
3857 ? (amtp = (AMT*)mg->mg_ptr)->table
3858 : NULL))
3859 && (cv = cvp[off=method])) { /* Method for right
3860 * argument found */
69815d08 3861 lr=1;
bf5522a1
MB
3862 } else if (((cvp && amtp->fallback > AMGfallNEVER)
3863 || (ocvp && oamtp->fallback > AMGfallNEVER))
1604cfb0
MS
3864 && !(flags & AMGf_unary)) {
3865 /* We look for substitution for
3866 * comparison operations and
3867 * concatenation */
a0d0e21e 3868 if (method==concat_amg || method==concat_ass_amg
1604cfb0
MS
3869 || method==repeat_amg || method==repeat_ass_amg) {
3870 return NULL; /* Delegate operation to string conversion */
a0d0e21e
LW
3871 }
3872 off = -1;
3873 switch (method) {
1604cfb0
MS
3874 case lt_amg:
3875 case le_amg:
3876 case gt_amg:
3877 case ge_amg:
3878 case eq_amg:
3879 case ne_amg:
2ab54efd
MB
3880 off = ncmp_amg;
3881 break;
1604cfb0
MS
3882 case slt_amg:
3883 case sle_amg:
3884 case sgt_amg:
3885 case sge_amg:
3886 case seq_amg:
3887 case sne_amg:
2ab54efd
MB
3888 off = scmp_amg;
3889 break;
1604cfb0 3890 }
bf5522a1
MB
3891 if (off != -1) {
3892 if (ocvp && (oamtp->fallback > AMGfallNEVER)) {
3893 cv = ocvp[off];
3894 lr = -1;
3895 }
3896 if (!cv && (cvp && amtp->fallback > AMGfallNEVER)) {
3897 cv = cvp[off];
3898 lr = 1;
3899 }
3900 }
3901 if (cv)
2ab54efd
MB
3902 postpr = 1;
3903 else
3904 goto not_found;
a0d0e21e 3905 } else {
a6006777 3906 not_found: /* No method found, either report or croak */
b267980d 3907 switch (method) {
1604cfb0
MS
3908 case to_sv_amg:
3909 case to_av_amg:
3910 case to_hv_amg:
3911 case to_gv_amg:
3912 case to_cv_amg:
3913 /* FAIL safe */
3914 return left; /* Delegate operation to standard mechanisms. */
b267980d 3915 }
a0d0e21e 3916 if (ocvp && (cv=ocvp[nomethod_amg])) { /* Call report method */
1604cfb0 3917 notfound = 1; lr = -1;
a0d0e21e 3918 } else if (cvp && (cv=cvp[nomethod_amg])) {
1604cfb0 3919 notfound = 1; lr = 1;
bf5522a1
MB
3920 } else if ((use_default_op =
3921 (!ocvp || oamtp->fallback >= AMGfallYES)
3922 && (!cvp || amtp->fallback >= AMGfallYES))
3923 && !DEBUG_o_TEST) {
1604cfb0
MS
3924 /* Skip generating the "no method found" message. */
3925 return NULL;
a0d0e21e 3926 } else {
1604cfb0
MS
3927 SV *msg;
3928 if (off==-1) off=method;
3929 msg = sv_2mortal(Perl_newSVpvf(aTHX_
3930 "Operation \"%s\": no method found,%sargument %s%" SVf "%s%" SVf,
3931 AMG_id2name(method + assignshift),
3932 (flags & AMGf_unary ? " " : "\n\tleft "),
3933 SvAMAGIC(left)?
3934 "in overloaded package ":
3935 "has no overloaded magic",
3936 SvAMAGIC(left)?
518db96a 3937 SVfARG(newSVhek_mortal(HvNAME_HEK(SvSTASH(SvRV(left))))):
1604cfb0
MS
3938 SVfARG(&PL_sv_no),
3939 SvAMAGIC(right)?
3940 ",\n\tright argument in overloaded package ":
3941 (flags & AMGf_unary
3942 ? ""
3943 : ",\n\tright argument has no overloaded magic"),
3944 SvAMAGIC(right)?
518db96a 3945 SVfARG(newSVhek_mortal(HvNAME_HEK(SvSTASH(SvRV(right))))):
1604cfb0 3946 SVfARG(&PL_sv_no)));
bf5522a1 3947 if (use_default_op) {
1604cfb0
MS
3948 DEBUG_o( Perl_deb(aTHX_ "%" SVf, SVfARG(msg)) );
3949 } else {
3950 Perl_croak(aTHX_ "%" SVf, SVfARG(msg));
3951 }
3952 return NULL;
a0d0e21e 3953 }
ee239bfe 3954 force_cpy = force_cpy || assign;
a0d0e21e
LW
3955 }
3956 }
67288365
JL
3957
3958 switch (method) {
3959 /* in these cases, we're calling '+' or '-' as a fallback for a ++ or --
3960 * operation. we need this to return a value, so that it can be assigned
3961 * later on, in the postpr block (case inc_amg/dec_amg), even if the
3962 * increment or decrement was itself called in void context */
3963 case inc_amg:
3964 if (off == add_amg)
3965 force_scalar = 1;
3966 break;
3967 case dec_amg:
3968 if (off == subtr_amg)
3969 force_scalar = 1;
3970 break;
3971 /* in these cases, we're calling an assignment variant of an operator
3972 * (+= rather than +, for instance). regardless of whether it's a
3973 * fallback or not, it always has to return a value, which will be
3974 * assigned to the proper variable later */
3975 case add_amg:
3976 case subtr_amg:
3977 case mult_amg:
3978 case div_amg:
3979 case modulo_amg:
3980 case pow_amg:
3981 case lshift_amg:
3982 case rshift_amg:
3983 case repeat_amg:
3984 case concat_amg:
3985 case band_amg:
3986 case bor_amg:
3987 case bxor_amg:
6d06ecce
FC
3988 case sband_amg:
3989 case sbor_amg:
3990 case sbxor_amg:
67288365
JL
3991 if (assign)
3992 force_scalar = 1;
3993 break;
3994 /* the copy constructor always needs to return a value */
3995 case copy_amg:
3996 force_scalar = 1;
3997 break;
3998 /* because of the way these are implemented (they don't perform the
3999 * dereferencing themselves, they return a reference that perl then
4000 * dereferences later), they always have to be in scalar context */
4001 case to_sv_amg:
4002 case to_av_amg:
4003 case to_hv_amg:
4004 case to_gv_amg:
4005 case to_cv_amg:
4006 force_scalar = 1;
4007 break;
4008 /* these don't have an op of their own; they're triggered by their parent
4009 * op, so the context there isn't meaningful ('$a and foo()' in void
4010 * context still needs to pass scalar context on to $a's bool overload) */
4011 case bool__amg:
4012 case numer_amg:
4013 case string_amg:
4014 force_scalar = 1;
4015 break;
4016 }
4017
497b47a8 4018#ifdef DEBUGGING
a0d0e21e 4019 if (!notfound) {
497b47a8 4020 DEBUG_o(Perl_deb(aTHX_
1604cfb0
MS
4021 "Overloaded operator \"%s\"%s%s%s:\n\tmethod%s found%s in package %" SVf "%s\n",
4022 AMG_id2name(off),
4023 method+assignshift==off? "" :
4024 " (initially \"",
4025 method+assignshift==off? "" :
4026 AMG_id2name(method+assignshift),
4027 method+assignshift==off? "" : "\")",
4028 flags & AMGf_unary? "" :
4029 lr==1 ? " for right argument": " for left argument",
4030 flags & AMGf_unary? " for argument" : "",
518db96a 4031 stash ? SVfARG(newSVhek_mortal(HvNAME_HEK(stash))) : SVfARG(newSVpvs_flags("null", SVs_TEMP)),
1604cfb0 4032 fl? ",\n\tassignment variant used": "") );
ee239bfe 4033 }
497b47a8 4034#endif
748a9306 4035 /* Since we use shallow copy during assignment, we need
0c6362ad 4036 * to duplicate the contents, probably calling user-supplied
748a9306
LW
4037 * version of copy operator
4038 */
ee239bfe
IZ
4039 /* We need to copy in following cases:
4040 * a) Assignment form was called.
4041 * assignshift==1, assign==T, method + 1 == off
4042 * b) Increment or decrement, called directly.
4043 * assignshift==0, assign==0, method + 0 == off
4044 * c) Increment or decrement, translated to assignment add/subtr.
b267980d 4045 * assignshift==0, assign==T,
ee239bfe
IZ
4046 * force_cpy == T
4047 * d) Increment or decrement, translated to nomethod.
b267980d 4048 * assignshift==0, assign==0,
ee239bfe
IZ
4049 * force_cpy == T
4050 * e) Assignment form translated to nomethod.
4051 * assignshift==1, assign==T, method + 1 != off
4052 * force_cpy == T
4053 */
4054 /* off is method, method+assignshift, or a result of opcode substitution.
4055 * In the latter case assignshift==0, so only notfound case is important.
4056 */
73512201 4057 if ( (lr == -1) && ( ( (method + assignshift == off)
1604cfb0 4058 && (assign || (method == inc_amg) || (method == dec_amg)))
73512201 4059 || force_cpy) )
6f1401dc 4060 {
1b38c28e
NC
4061 /* newSVsv does not behave as advertised, so we copy missing
4062 * information by hand */
4063 SV *tmpRef = SvRV(left);
4064 SV *rv_copy;
31d632c3 4065 if (SvREFCNT(tmpRef) > 1 && (rv_copy = AMG_CALLunary(left,copy_amg))) {
1604cfb0
MS
4066 SvRV_set(left, rv_copy);
4067 SvSETMAGIC(left);
9c913148 4068 SvREFCNT_dec_NN(tmpRef);
1b38c28e 4069 }
6f1401dc
DM
4070 }
4071
a0d0e21e
LW
4072 {
4073 dSP;
4074 BINOP myop;
4075 SV* res;
b7787f18 4076 const bool oldcatch = CATCH_GET;
67288365 4077 I32 oldmark, nret;
e839e6ed
DM
4078 /* for multiconcat, we may call overload several times,
4079 * with the context of individual concats being scalar,
4080 * regardless of the overall context of the multiconcat op
4081 */
4082 U8 gimme = (force_scalar || PL_op->op_type == OP_MULTICONCAT)
4083 ? G_SCALAR : GIMME_V;
a0d0e21e 4084
54310121 4085 CATCH_SET(TRUE);
a0d0e21e
LW
4086 Zero(&myop, 1, BINOP);
4087 myop.op_last = (OP *) &myop;
b37c2d43 4088 myop.op_next = NULL;
67288365
JL
4089 myop.op_flags = OPf_STACKED;
4090
4091 switch (gimme) {
4092 case G_VOID:
4093 myop.op_flags |= OPf_WANT_VOID;
4094 break;
eb7e169e 4095 case G_LIST:
67288365
JL
4096 if (flags & AMGf_want_list) {
4097 myop.op_flags |= OPf_WANT_LIST;
4098 break;
4099 }
4100 /* FALLTHROUGH */
4101 default:
4102 myop.op_flags |= OPf_WANT_SCALAR;
4103 break;
4104 }
a0d0e21e 4105
e788e7d3 4106 PUSHSTACKi(PERLSI_OVERLOAD);
a0d0e21e 4107 ENTER;
462e5cf6 4108 SAVEOP();
533c011a 4109 PL_op = (OP *) &myop;
3280af22 4110 if (PERLDB_SUB && PL_curstash != PL_debstash)
1604cfb0 4111 PL_op->op_private |= OPpENTERSUB_DB;
897d3989 4112 Perl_pp_pushmark(aTHX);
a0d0e21e 4113
924508f0 4114 EXTEND(SP, notfound + 5);
a0d0e21e
LW
4115 PUSHs(lr>0? right: left);
4116 PUSHs(lr>0? left: right);
3280af22 4117 PUSHs( lr > 0 ? &PL_sv_yes : ( assign ? &PL_sv_undef : &PL_sv_no ));
a0d0e21e 4118 if (notfound) {
59cd0e26 4119 PUSHs(newSVpvn_flags(AMG_id2name(method + assignshift),
1604cfb0 4120 AMG_id2namelen(method + assignshift), SVs_TEMP));
a0d0e21e 4121 }
636ac8fc
FC
4122 else if (flags & AMGf_numarg)
4123 PUSHs(&PL_sv_undef);
4124 if (flags & AMGf_numarg)
4125 PUSHs(&PL_sv_yes);
ad64d0ec 4126 PUSHs(MUTABLE_SV(cv));
a0d0e21e 4127 PUTBACK;
67288365 4128 oldmark = TOPMARK;
a0d0e21e 4129
139d0ce6 4130 if ((PL_op = PL_ppaddr[OP_ENTERSUB](aTHX)))
cea2e8a9 4131 CALLRUNOPS(aTHX);
a0d0e21e
LW
4132 LEAVE;
4133 SPAGAIN;
67288365
JL
4134 nret = SP - (PL_stack_base + oldmark);
4135
4136 switch (gimme) {
4137 case G_VOID:
4138 /* returning NULL has another meaning, and we check the context
4139 * at the call site too, so this can be differentiated from the
4140 * scalar case */
4141 res = &PL_sv_undef;
4142 SP = PL_stack_base + oldmark;
4143 break;
eb7e169e 4144 case G_LIST:
67288365 4145 if (flags & AMGf_want_list) {
7ea8b04b 4146 res = newSV_type_mortal(SVt_PVAV);
67288365
JL
4147 av_extend((AV *)res, nret);
4148 while (nret--)
4149 av_store((AV *)res, nret, POPs);
4150 break;
4151 }
4152 /* FALLTHROUGH */
67288365
JL
4153 default:
4154 res = POPs;
4155 break;
4156 }
a0d0e21e 4157
ebafeae7 4158 PUTBACK;
d3acc0f7 4159 POPSTACK;
54310121 4160 CATCH_SET(oldcatch);
a0d0e21e 4161
a0d0e21e 4162 if (postpr) {
b7787f18 4163 int ans;
a0d0e21e
LW
4164 switch (method) {
4165 case le_amg:
4166 case sle_amg:
1604cfb0 4167 ans=SvIV(res)<=0; break;
a0d0e21e
LW
4168 case lt_amg:
4169 case slt_amg:
1604cfb0 4170 ans=SvIV(res)<0; break;
a0d0e21e
LW
4171 case ge_amg:
4172 case sge_amg:
1604cfb0 4173 ans=SvIV(res)>=0; break;
a0d0e21e
LW
4174 case gt_amg:
4175 case sgt_amg:
1604cfb0 4176 ans=SvIV(res)>0; break;
a0d0e21e
LW
4177 case eq_amg:
4178 case seq_amg:
1604cfb0 4179 ans=SvIV(res)==0; break;
a0d0e21e
LW
4180 case ne_amg:
4181 case sne_amg:
1604cfb0 4182 ans=SvIV(res)!=0; break;
a0d0e21e
LW
4183 case inc_amg:
4184 case dec_amg:
1604cfb0 4185 SvSetSV(left,res); return left;
dc437b57 4186 case not_amg:
1604cfb0 4187 ans=!SvTRUE_NN(res); break;
b7787f18
AL
4188 default:
4189 ans=0; break;
a0d0e21e 4190 }
54310121 4191 return boolSV(ans);
748a9306
LW
4192 } else if (method==copy_amg) {
4193 if (!SvROK(res)) {
1604cfb0 4194 Perl_croak(aTHX_ "Copy method did not return a reference");
748a9306
LW
4195 }
4196 return SvREFCNT_inc(SvRV(res));
a0d0e21e
LW
4197 } else {
4198 return res;
4199 }
4200 }
4201}
c9d5ac95 4202
629fbf9b
KW
4203/*
4204=for apidoc gv_name_set
4205
4206Set the name for GV C<gv> to C<name> which is C<len> bytes long. Thus it may
4207contain embedded NUL characters.
4208
4209If C<flags> contains C<SVf_UTF8>, the name is treated as being encoded in
4210UTF-8; otherwise not.
4211
4212=cut
4213*/
4214
f5c1e807
NC
4215void
4216Perl_gv_name_set(pTHX_ GV *gv, const char *name, U32 len, U32 flags)
4217{
acda4c6a 4218 U32 hash;
f5c1e807 4219
7918f24d 4220 PERL_ARGS_ASSERT_GV_NAME_SET;
f5c1e807 4221
acda4c6a 4222 if (len > I32_MAX)
1604cfb0 4223 Perl_croak(aTHX_ "panic: gv name too long (%" UVuf ")", (UV) len);
acda4c6a 4224
ae8cc45f 4225 if (!(flags & GV_ADD) && GvNAME_HEK(gv)) {
1604cfb0 4226 unshare_hek(GvNAME_HEK(gv));
ae8cc45f
NC
4227 }
4228
acda4c6a 4229 PERL_HASH(hash, name, len);
c60dbbc3 4230 GvNAME_HEK(gv) = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
f5c1e807
NC
4231}
4232
66610fdd 4233/*
f7461760
Z
4234=for apidoc gv_try_downgrade
4235
2867cdbc
Z
4236If the typeglob C<gv> can be expressed more succinctly, by having
4237something other than a real GV in its place in the stash, replace it
4238with the optimised form. Basic requirements for this are that C<gv>
4239is a real typeglob, is sufficiently ordinary, and is only referenced
4240from its package. This function is meant to be used when a GV has been
4241looked up in part to see what was there, causing upgrading, but based
4242on what was found it turns out that the real GV isn't required after all.
4243
4244If C<gv> is a completely empty typeglob, it is deleted from the stash.
4245
4246If C<gv> is a typeglob containing only a sufficiently-ordinary constant
4247sub, the typeglob is replaced with a scalar-reference placeholder that
4248more compactly represents the same thing.
f7461760
Z
4249
4250=cut
4251*/
4252
4253void
4254Perl_gv_try_downgrade(pTHX_ GV *gv)
4255{
4256 HV *stash;
4257 CV *cv;
4258 HEK *namehek;
4259 SV **gvp;
4260 PERL_ARGS_ASSERT_GV_TRY_DOWNGRADE;
95f56751
FC
4261
4262 /* XXX Why and where does this leave dangling pointers during global
4263 destruction? */
627364f1 4264 if (PL_phase == PERL_PHASE_DESTRUCT) return;
95f56751 4265
2867cdbc 4266 if (!(SvREFCNT(gv) == 1 && SvTYPE(gv) == SVt_PVGV && !SvFAKE(gv) &&
1604cfb0
MS
4267 !SvOBJECT(gv) && !SvREADONLY(gv) &&
4268 isGV_with_GP(gv) && GvGP(gv) &&
4269 !GvINTRO(gv) && GvREFCNT(gv) == 1 &&
4270 !GvSV(gv) && !GvAV(gv) && !GvHV(gv) && !GvIOp(gv) && !GvFORM(gv) &&
4271 GvEGVx(gv) == gv && (stash = GvSTASH(gv))))
4272 return;
2be08ad1 4273 if (gv == PL_statgv || gv == PL_last_in_gv || gv == PL_stderrgv)
1604cfb0 4274 return;
803f2748
DM
4275 if (SvMAGICAL(gv)) {
4276 MAGIC *mg;
1604cfb0
MS
4277 /* only backref magic is allowed */
4278 if (SvGMAGICAL(gv) || SvSMAGICAL(gv))
4279 return;
803f2748
DM
4280 for (mg = SvMAGIC(gv); mg; mg = mg->mg_moremagic) {
4281 if (mg->mg_type != PERL_MAGIC_backref)
4282 return;
1604cfb0 4283 }
803f2748 4284 }
2867cdbc
Z
4285 cv = GvCV(gv);
4286 if (!cv) {
1604cfb0
MS
4287 HEK *gvnhek = GvNAME_HEK(gv);
4288 (void)hv_deletehek(stash, gvnhek, G_DISCARD);
8941bf97 4289 } else if (GvMULTI(gv) && cv && SvREFCNT(cv) == 1 &&
1604cfb0
MS
4290 !SvOBJECT(cv) && !SvMAGICAL(cv) && !SvREADONLY(cv) &&
4291 CvSTASH(cv) == stash && !CvNAMED(cv) && CvGV(cv) == gv &&
ec11e338 4292 CvCONST(cv) && !CvNOWARN_AMBIGUOUS(cv) && !CvLVALUE(cv) && !CvUNIQUE(cv) &&
1604cfb0
MS
4293 !CvNODEBUG(cv) && !CvCLONE(cv) && !CvCLONED(cv) && !CvANON(cv) &&
4294 (namehek = GvNAME_HEK(gv)) &&
4295 (gvp = hv_fetchhek(stash, namehek, 0)) &&
4296 *gvp == (SV*)gv) {
4297 SV *value = SvREFCNT_inc(CvXSUBANY(cv).any_ptr);
82943faa 4298 const bool imported = cBOOL(GvIMPORTED_CV(gv));
1604cfb0
MS
4299 SvREFCNT(gv) = 0;
4300 sv_clear((SV*)gv);
4301 SvREFCNT(gv) = 1;
4302 SvFLAGS(gv) = SVt_IV|SVf_ROK|SVprv_PCS_IMPORTED * imported;
dc6369ef
EH
4303
4304 /* See also: 'SET_SVANY_FOR_BODYLESS_IV' in sv.c */
1604cfb0
MS
4305 SvANY(gv) = (XPVGV*)((char*)&(gv->sv_u.svu_iv) -
4306 STRUCT_OFFSET(XPVIV, xiv_iv));
4307 SvRV_set(gv, value);
f7461760
Z
4308 }
4309}
4310
9e3fb20c
FC
4311GV *
4312Perl_gv_override(pTHX_ const char * const name, const STRLEN len)
4313{
4314 GV *gv = gv_fetchpvn(name, len, GV_NOTQUAL, SVt_PVCV);
4315 GV * const *gvp;
4316 PERL_ARGS_ASSERT_GV_OVERRIDE;
4317 if (gv && GvCVu(gv) && GvIMPORTED_CV(gv)) return gv;
4318 gvp = (GV**)hv_fetch(PL_globalstash, name, len, FALSE);
4319 gv = gvp ? *gvp : NULL;
4320 if (gv && !isGV(gv)) {
1604cfb0
MS
4321 if (!SvPCS_IMPORTED(gv)) return NULL;
4322 gv_init(gv, PL_globalstash, name, len, 0);
4323 return gv;
9e3fb20c
FC
4324 }
4325 return gv && GvCVu(gv) && GvIMPORTED_CV(gv) ? gv : NULL;
4326}
4327
4aaa4757
FC
4328#include "XSUB.h"
4329
4330static void
4331core_xsub(pTHX_ CV* cv)
4332{
4333 Perl_croak(aTHX_
4334 "&CORE::%s cannot be called directly", GvNAME(CvGV(cv))
4335 );
4336}
4337
f7461760 4338/*
14d04a33 4339 * ex: set ts=8 sts=4 sw=4 et:
37442d52 4340 */