Not all the world's a VAX, er ASCII, so don't make assumptions.
[p5sagit/p5-mst-13.2.git] / gv.c
1 /*    gv.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4  *    2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
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  *
9  */
10
11 /*
12  *   'Mercy!' cried Gandalf.  'If the giving of information is to be the cure
13  * of your inquisitiveness, I shall spend all the rest of my days answering
14  * you.  What more do you want to know?'
15  *   'The names of all the stars, and of all living things, and the whole
16  * history of Middle-earth and Over-heaven and of the Sundering Seas,'
17  * laughed Pippin.
18  */
19
20 /*
21 =head1 GV Functions
22
23 A GV is a structure which corresponds to to a Perl typeglob, ie *foo.
24 It is a structure that holds a pointer to a scalar, an array, a hash etc,
25 corresponding to $foo, @foo, %foo.
26
27 GVs are usually found as values in stashes (symbol table hashes) where
28 Perl stores its global variables.
29
30 =cut
31 */
32
33 #include "EXTERN.h"
34 #define PERL_IN_GV_C
35 #include "perl.h"
36
37 GV *
38 Perl_gv_AVadd(pTHX_ register GV *gv)
39 {
40     if (!gv || SvTYPE((SV*)gv) != SVt_PVGV)
41         Perl_croak(aTHX_ "Bad symbol for array");
42     if (!GvAV(gv))
43         GvAV(gv) = newAV();
44     return gv;
45 }
46
47 GV *
48 Perl_gv_HVadd(pTHX_ register GV *gv)
49 {
50     if (!gv || SvTYPE((SV*)gv) != SVt_PVGV)
51         Perl_croak(aTHX_ "Bad symbol for hash");
52     if (!GvHV(gv))
53         GvHV(gv) = newHV();
54     return gv;
55 }
56
57 GV *
58 Perl_gv_IOadd(pTHX_ register GV *gv)
59 {
60     if (!gv || SvTYPE((SV*)gv) != SVt_PVGV)
61         Perl_croak(aTHX_ "Bad symbol for filehandle");
62     if (!GvIOp(gv)) {
63 #ifdef GV_UNIQUE_CHECK
64         if (GvUNIQUE(gv)) {
65             Perl_croak(aTHX_ "Bad symbol for filehandle (GV is unique)");
66         }
67 #endif
68         GvIOp(gv) = newIO();
69     }
70     return gv;
71 }
72
73 GV *
74 Perl_gv_fetchfile(pTHX_ const char *name)
75 {
76     char smallbuf[256];
77     char *tmpbuf;
78     STRLEN tmplen;
79     GV *gv;
80
81     if (!PL_defstash)
82         return Nullgv;
83
84     tmplen = strlen(name) + 2;
85     if (tmplen < sizeof smallbuf)
86         tmpbuf = smallbuf;
87     else
88         New(603, tmpbuf, tmplen + 1, char);
89     /* This is where the debugger's %{"::_<$filename"} hash is created */
90     tmpbuf[0] = '_';
91     tmpbuf[1] = '<';
92     strcpy(tmpbuf + 2, name);
93     gv = *(GV**)hv_fetch(PL_defstash, tmpbuf, tmplen, TRUE);
94     if (!isGV(gv)) {
95         gv_init(gv, PL_defstash, tmpbuf, tmplen, FALSE);
96         sv_setpv(GvSV(gv), name);
97         if (PERLDB_LINE)
98             hv_magic(GvHVn(gv_AVadd(gv)), Nullgv, PERL_MAGIC_dbfile);
99     }
100     if (tmpbuf != smallbuf)
101         Safefree(tmpbuf);
102     return gv;
103 }
104
105 void
106 Perl_gv_init(pTHX_ GV *gv, HV *stash, const char *name, STRLEN len, int multi)
107 {
108     register GP *gp;
109     bool doproto = SvTYPE(gv) > SVt_NULL;
110     char *proto = (doproto && SvPOK(gv)) ? SvPVX(gv) : NULL;
111
112     sv_upgrade((SV*)gv, SVt_PVGV);
113     if (SvLEN(gv)) {
114         if (proto) {
115             SvPVX(gv) = NULL;
116             SvLEN(gv) = 0;
117             SvPOK_off(gv);
118         } else
119             Safefree(SvPVX(gv));
120     }
121     Newz(602, gp, 1, GP);
122     GvGP(gv) = gp_ref(gp);
123     GvSV(gv) = NEWSV(72,0);
124     GvLINE(gv) = CopLINE(PL_curcop);
125     GvFILE(gv) = CopFILE(PL_curcop) ? CopFILE(PL_curcop) : "";
126     GvCVGEN(gv) = 0;
127     GvEGV(gv) = gv;
128     sv_magic((SV*)gv, (SV*)gv, PERL_MAGIC_glob, Nullch, 0);
129     GvSTASH(gv) = (HV*)SvREFCNT_inc(stash);
130     GvNAME(gv) = savepvn(name, len);
131     GvNAMELEN(gv) = len;
132     if (multi || doproto)              /* doproto means it _was_ mentioned */
133         GvMULTI_on(gv);
134     if (doproto) {                      /* Replicate part of newSUB here. */
135         SvIOK_off(gv);
136         ENTER;
137         /* XXX unsafe for threads if eval_owner isn't held */
138         start_subparse(0,0);            /* Create CV in compcv. */
139         GvCV(gv) = PL_compcv;
140         LEAVE;
141
142         PL_sub_generation++;
143         CvGV(GvCV(gv)) = gv;
144         CvFILE_set_from_cop(GvCV(gv), PL_curcop);
145         CvSTASH(GvCV(gv)) = PL_curstash;
146         if (proto) {
147             sv_setpv((SV*)GvCV(gv), proto);
148             Safefree(proto);
149         }
150     }
151 }
152
153 STATIC void
154 S_gv_init_sv(pTHX_ GV *gv, I32 sv_type)
155 {
156     switch (sv_type) {
157     case SVt_PVIO:
158         (void)GvIOn(gv);
159         break;
160     case SVt_PVAV:
161         (void)GvAVn(gv);
162         break;
163     case SVt_PVHV:
164         (void)GvHVn(gv);
165         break;
166     }
167 }
168
169 /*
170 =for apidoc gv_fetchmeth
171
172 Returns the glob with the given C<name> and a defined subroutine or
173 C<NULL>.  The glob lives in the given C<stash>, or in the stashes
174 accessible via @ISA and UNIVERSAL::.
175
176 The argument C<level> should be either 0 or -1.  If C<level==0>, as a
177 side-effect creates a glob with the given C<name> in the given C<stash>
178 which in the case of success contains an alias for the subroutine, and sets
179 up caching info for this glob.  Similarly for all the searched stashes.
180
181 This function grants C<"SUPER"> token as a postfix of the stash name. The
182 GV returned from C<gv_fetchmeth> may be a method cache entry, which is not
183 visible to Perl code.  So when calling C<call_sv>, you should not use
184 the GV directly; instead, you should use the method's CV, which can be
185 obtained from the GV with the C<GvCV> macro.
186
187 =cut
188 */
189
190 GV *
191 Perl_gv_fetchmeth(pTHX_ HV *stash, const char *name, STRLEN len, I32 level)
192 {
193     AV* av;
194     GV* topgv;
195     GV* gv;
196     GV** gvp;
197     CV* cv;
198
199     /* UNIVERSAL methods should be callable without a stash */
200     if (!stash) {
201         level = -1;  /* probably appropriate */
202         if(!(stash = gv_stashpvn("UNIVERSAL", 9, FALSE)))
203             return 0;
204     }
205
206     if (!HvNAME(stash))
207       Perl_croak(aTHX_
208                  "Can't use anonymous symbol table for method lookup");
209
210     if ((level > 100) || (level < -100))
211         Perl_croak(aTHX_ "Recursive inheritance detected while looking for method '%s' in package '%s'",
212               name, HvNAME(stash));
213
214     DEBUG_o( Perl_deb(aTHX_ "Looking for method %s in package %s\n",name,HvNAME(stash)) );
215
216     gvp = (GV**)hv_fetch(stash, name, len, (level >= 0));
217     if (!gvp)
218         topgv = Nullgv;
219     else {
220         topgv = *gvp;
221         if (SvTYPE(topgv) != SVt_PVGV)
222             gv_init(topgv, stash, name, len, TRUE);
223         if ((cv = GvCV(topgv))) {
224             /* If genuine method or valid cache entry, use it */
225             if (!GvCVGEN(topgv) || GvCVGEN(topgv) == PL_sub_generation)
226                 return topgv;
227             /* Stale cached entry: junk it */
228             SvREFCNT_dec(cv);
229             GvCV(topgv) = cv = Nullcv;
230             GvCVGEN(topgv) = 0;
231         }
232         else if (GvCVGEN(topgv) == PL_sub_generation)
233             return 0;  /* cache indicates sub doesn't exist */
234     }
235
236     gvp = (GV**)hv_fetch(stash, "ISA", 3, FALSE);
237     av = (gvp && (gv = *gvp) && gv != (GV*)&PL_sv_undef) ? GvAV(gv) : Nullav;
238
239     /* create and re-create @.*::SUPER::ISA on demand */
240     if (!av || !SvMAGIC(av)) {
241         char* packname = HvNAME(stash);
242         STRLEN packlen = strlen(packname);
243
244         if (packlen >= 7 && strEQ(packname + packlen - 7, "::SUPER")) {
245             HV* basestash;
246
247             packlen -= 7;
248             basestash = gv_stashpvn(packname, packlen, TRUE);
249             gvp = (GV**)hv_fetch(basestash, "ISA", 3, FALSE);
250             if (gvp && (gv = *gvp) != (GV*)&PL_sv_undef && (av = GvAV(gv))) {
251                 gvp = (GV**)hv_fetch(stash, "ISA", 3, TRUE);
252                 if (!gvp || !(gv = *gvp))
253                     Perl_croak(aTHX_ "Cannot create %s::ISA", HvNAME(stash));
254                 if (SvTYPE(gv) != SVt_PVGV)
255                     gv_init(gv, stash, "ISA", 3, TRUE);
256                 SvREFCNT_dec(GvAV(gv));
257                 GvAV(gv) = (AV*)SvREFCNT_inc(av);
258             }
259         }
260     }
261
262     if (av) {
263         SV** svp = AvARRAY(av);
264         /* NOTE: No support for tied ISA */
265         I32 items = AvFILLp(av) + 1;
266         while (items--) {
267             SV* sv = *svp++;
268             HV* basestash = gv_stashsv(sv, FALSE);
269             if (!basestash) {
270                 if (ckWARN(WARN_MISC))
271                     Perl_warner(aTHX_ packWARN(WARN_MISC), "Can't locate package %"SVf" for @%s::ISA",
272                         sv, HvNAME(stash));
273                 continue;
274             }
275             gv = gv_fetchmeth(basestash, name, len,
276                               (level >= 0) ? level + 1 : level - 1);
277             if (gv)
278                 goto gotcha;
279         }
280     }
281
282     /* if at top level, try UNIVERSAL */
283
284     if (level == 0 || level == -1) {
285         HV* lastchance;
286
287         if ((lastchance = gv_stashpvn("UNIVERSAL", 9, FALSE))) {
288             if ((gv = gv_fetchmeth(lastchance, name, len,
289                                   (level >= 0) ? level + 1 : level - 1)))
290             {
291           gotcha:
292                 /*
293                  * Cache method in topgv if:
294                  *  1. topgv has no synonyms (else inheritance crosses wires)
295                  *  2. method isn't a stub (else AUTOLOAD fails spectacularly)
296                  */
297                 if (topgv &&
298                     GvREFCNT(topgv) == 1 &&
299                     (cv = GvCV(gv)) &&
300                     (CvROOT(cv) || CvXSUB(cv)))
301                 {
302                     if ((cv = GvCV(topgv)))
303                         SvREFCNT_dec(cv);
304                     GvCV(topgv) = (CV*)SvREFCNT_inc(GvCV(gv));
305                     GvCVGEN(topgv) = PL_sub_generation;
306                 }
307                 return gv;
308             }
309             else if (topgv && GvREFCNT(topgv) == 1) {
310                 /* cache the fact that the method is not defined */
311                 GvCVGEN(topgv) = PL_sub_generation;
312             }
313         }
314     }
315
316     return 0;
317 }
318
319 /*
320 =for apidoc gv_fetchmeth_autoload
321
322 Same as gv_fetchmeth(), but looks for autoloaded subroutines too.
323 Returns a glob for the subroutine.
324
325 For an autoloaded subroutine without a GV, will create a GV even
326 if C<level < 0>.  For an autoloaded subroutine without a stub, GvCV()
327 of the result may be zero.
328
329 =cut
330 */
331
332 GV *
333 Perl_gv_fetchmeth_autoload(pTHX_ HV *stash, const char *name, STRLEN len, I32 level)
334 {
335     GV *gv = gv_fetchmeth(stash, name, len, level);
336
337     if (!gv) {
338         char autoload[] = "AUTOLOAD";
339         STRLEN autolen = sizeof(autoload)-1;
340         CV *cv;
341         GV **gvp;
342
343         if (!stash)
344             return Nullgv;      /* UNIVERSAL::AUTOLOAD could cause trouble */
345         if (len == autolen && strnEQ(name, autoload, autolen))
346             return Nullgv;
347         if (!(gv = gv_fetchmeth(stash, autoload, autolen, FALSE)))
348             return Nullgv;
349         cv = GvCV(gv);
350         if (!(CvROOT(cv) || CvXSUB(cv)))
351             return Nullgv;
352         /* Have an autoload */
353         if (level < 0)  /* Cannot do without a stub */
354             gv_fetchmeth(stash, name, len, 0);
355         gvp = (GV**)hv_fetch(stash, name, len, (level >= 0));
356         if (!gvp)
357             return Nullgv;
358         return *gvp;
359     }
360     return gv;
361 }
362
363 /*
364 =for apidoc gv_fetchmethod
365
366 See L<gv_fetchmethod_autoload>.
367
368 =cut
369 */
370
371 GV *
372 Perl_gv_fetchmethod(pTHX_ HV *stash, const char *name)
373 {
374     return gv_fetchmethod_autoload(stash, name, TRUE);
375 }
376
377 /*
378 =for apidoc gv_fetchmethod_autoload
379
380 Returns the glob which contains the subroutine to call to invoke the method
381 on the C<stash>.  In fact in the presence of autoloading this may be the
382 glob for "AUTOLOAD".  In this case the corresponding variable $AUTOLOAD is
383 already setup.
384
385 The third parameter of C<gv_fetchmethod_autoload> determines whether
386 AUTOLOAD lookup is performed if the given method is not present: non-zero
387 means yes, look for AUTOLOAD; zero means no, don't look for AUTOLOAD.
388 Calling C<gv_fetchmethod> is equivalent to calling C<gv_fetchmethod_autoload>
389 with a non-zero C<autoload> parameter.
390
391 These functions grant C<"SUPER"> token as a prefix of the method name. Note
392 that if you want to keep the returned glob for a long time, you need to
393 check for it being "AUTOLOAD", since at the later time the call may load a
394 different subroutine due to $AUTOLOAD changing its value. Use the glob
395 created via a side effect to do this.
396
397 These functions have the same side-effects and as C<gv_fetchmeth> with
398 C<level==0>.  C<name> should be writable if contains C<':'> or C<'
399 ''>. The warning against passing the GV returned by C<gv_fetchmeth> to
400 C<call_sv> apply equally to these functions.
401
402 =cut
403 */
404
405 GV *
406 Perl_gv_fetchmethod_autoload(pTHX_ HV *stash, const char *name, I32 autoload)
407 {
408     register const char *nend;
409     const char *nsplit = 0;
410     GV* gv;
411     HV* ostash = stash;
412
413     if (stash && SvTYPE(stash) < SVt_PVHV)
414         stash = Nullhv;
415
416     for (nend = name; *nend; nend++) {
417         if (*nend == '\'')
418             nsplit = nend;
419         else if (*nend == ':' && *(nend + 1) == ':')
420             nsplit = ++nend;
421     }
422     if (nsplit) {
423         const char *origname = name;
424         name = nsplit + 1;
425         if (*nsplit == ':')
426             --nsplit;
427         if ((nsplit - origname) == 5 && strnEQ(origname, "SUPER", 5)) {
428             /* ->SUPER::method should really be looked up in original stash */
429             SV *tmpstr = sv_2mortal(Perl_newSVpvf(aTHX_ "%s::SUPER",
430                                                   CopSTASHPV(PL_curcop)));
431             /* __PACKAGE__::SUPER stash should be autovivified */
432             stash = gv_stashpvn(SvPVX(tmpstr), SvCUR(tmpstr), TRUE);
433             DEBUG_o( Perl_deb(aTHX_ "Treating %s as %s::%s\n",
434                          origname, HvNAME(stash), name) );
435         }
436         else {
437             /* don't autovifify if ->NoSuchStash::method */
438             stash = gv_stashpvn(origname, nsplit - origname, FALSE);
439
440             /* however, explicit calls to Pkg::SUPER::method may
441                happen, and may require autovivification to work */
442             if (!stash && (nsplit - origname) >= 7 &&
443                 strnEQ(nsplit - 7, "::SUPER", 7) &&
444                 gv_stashpvn(origname, nsplit - origname - 7, FALSE))
445               stash = gv_stashpvn(origname, nsplit - origname, TRUE);
446         }
447         ostash = stash;
448     }
449
450     gv = gv_fetchmeth(stash, name, nend - name, 0);
451     if (!gv) {
452         if (strEQ(name,"import") || strEQ(name,"unimport"))
453             gv = (GV*)&PL_sv_yes;
454         else if (autoload)
455             gv = gv_autoload4(ostash, name, nend - name, TRUE);
456     }
457     else if (autoload) {
458         CV* cv = GvCV(gv);
459         if (!CvROOT(cv) && !CvXSUB(cv)) {
460             GV* stubgv;
461             GV* autogv;
462
463             if (CvANON(cv))
464                 stubgv = gv;
465             else {
466                 stubgv = CvGV(cv);
467                 if (GvCV(stubgv) != cv)         /* orphaned import */
468                     stubgv = gv;
469             }
470             autogv = gv_autoload4(GvSTASH(stubgv),
471                                   GvNAME(stubgv), GvNAMELEN(stubgv), TRUE);
472             if (autogv)
473                 gv = autogv;
474         }
475     }
476
477     return gv;
478 }
479
480 GV*
481 Perl_gv_autoload4(pTHX_ HV *stash, const char *name, STRLEN len, I32 method)
482 {
483     char autoload[] = "AUTOLOAD";
484     STRLEN autolen = sizeof(autoload)-1;
485     GV* gv;
486     CV* cv;
487     HV* varstash;
488     GV* vargv;
489     SV* varsv;
490     char *packname = "";
491
492     if (len == autolen && strnEQ(name, autoload, autolen))
493         return Nullgv;
494     if (stash) {
495         if (SvTYPE(stash) < SVt_PVHV) {
496             packname = SvPV_nolen((SV*)stash);
497             stash = Nullhv;
498         }
499         else {
500             packname = HvNAME(stash);
501         }
502     }
503     if (!(gv = gv_fetchmeth(stash, autoload, autolen, FALSE)))
504         return Nullgv;
505     cv = GvCV(gv);
506
507     if (!(CvROOT(cv) || CvXSUB(cv)))
508         return Nullgv;
509
510     /*
511      * Inheriting AUTOLOAD for non-methods works ... for now.
512      */
513     if (ckWARN2(WARN_DEPRECATED, WARN_SYNTAX) && !method &&
514         (GvCVGEN(gv) || GvSTASH(gv) != stash))
515         Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED, WARN_SYNTAX),
516           "Use of inherited AUTOLOAD for non-method %s::%.*s() is deprecated",
517              packname, (int)len, name);
518
519     if (CvXSUB(cv)) {
520         /* rather than lookup/init $AUTOLOAD here
521          * only to have the XSUB do another lookup for $AUTOLOAD
522          * and split that value on the last '::',
523          * pass along the same data via some unused fields in the CV
524          */
525         CvSTASH(cv) = stash;
526         SvPVX(cv) = (char *)name; /* cast to lose constness warning */
527         SvCUR(cv) = len;
528         return gv;
529     }
530
531     /*
532      * Given &FOO::AUTOLOAD, set $FOO::AUTOLOAD to desired function name.
533      * The subroutine's original name may not be "AUTOLOAD", so we don't
534      * use that, but for lack of anything better we will use the sub's
535      * original package to look up $AUTOLOAD.
536      */
537     varstash = GvSTASH(CvGV(cv));
538     vargv = *(GV**)hv_fetch(varstash, autoload, autolen, TRUE);
539     ENTER;
540
541     if (!isGV(vargv))
542         gv_init(vargv, varstash, autoload, autolen, FALSE);
543     LEAVE;
544     varsv = GvSV(vargv);
545     sv_setpv(varsv, packname);
546     sv_catpvn(varsv, "::", 2);
547     sv_catpvn(varsv, name, len);
548     SvTAINTED_off(varsv);
549     return gv;
550 }
551
552 /* The "gv" parameter should be the glob known to Perl code as *!
553  * The scalar must already have been magicalized.
554  */
555 STATIC void
556 S_require_errno(pTHX_ GV *gv)
557 {
558     HV* stash = gv_stashpvn("Errno",5,FALSE);
559
560     if (!stash || !(gv_fetchmethod(stash, "TIEHASH"))) { 
561         dSP;
562         PUTBACK;
563         ENTER;
564         save_scalar(gv); /* keep the value of $! */
565         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
566                          newSVpvn("Errno",5), Nullsv);
567         LEAVE;
568         SPAGAIN;
569         stash = gv_stashpvn("Errno",5,FALSE);
570         if (!stash || !(gv_fetchmethod(stash, "TIEHASH")))
571             Perl_croak(aTHX_ "Can't use %%! because Errno.pm is not available");
572     }
573 }
574
575 /*
576 =for apidoc gv_stashpv
577
578 Returns a pointer to the stash for a specified package.  C<name> should
579 be a valid UTF-8 string and must be null-terminated.  If C<create> is set
580 then the package will be created if it does not already exist.  If C<create>
581 is not set and the package does not exist then NULL is returned.
582
583 =cut
584 */
585
586 HV*
587 Perl_gv_stashpv(pTHX_ const char *name, I32 create)
588 {
589     return gv_stashpvn(name, strlen(name), create);
590 }
591
592 /*
593 =for apidoc gv_stashpvn
594
595 Returns a pointer to the stash for a specified package.  C<name> should
596 be a valid UTF-8 string.  The C<namelen> parameter indicates the length of
597 the C<name>, in bytes.  If C<create> is set then the package will be
598 created if it does not already exist.  If C<create> is not set and the
599 package does not exist then NULL is returned.
600
601 =cut
602 */
603
604 HV*
605 Perl_gv_stashpvn(pTHX_ const char *name, U32 namelen, I32 create)
606 {
607     char smallbuf[256];
608     char *tmpbuf;
609     HV *stash;
610     GV *tmpgv;
611
612     if (namelen + 3 < sizeof smallbuf)
613         tmpbuf = smallbuf;
614     else
615         New(606, tmpbuf, namelen + 3, char);
616     Copy(name,tmpbuf,namelen,char);
617     tmpbuf[namelen++] = ':';
618     tmpbuf[namelen++] = ':';
619     tmpbuf[namelen] = '\0';
620     tmpgv = gv_fetchpv(tmpbuf, create, SVt_PVHV);
621     if (tmpbuf != smallbuf)
622         Safefree(tmpbuf);
623     if (!tmpgv)
624         return 0;
625     if (!GvHV(tmpgv))
626         GvHV(tmpgv) = newHV();
627     stash = GvHV(tmpgv);
628     if (!HvNAME(stash))
629         HvNAME(stash) = savepv(name);
630     return stash;
631 }
632
633 /*
634 =for apidoc gv_stashsv
635
636 Returns a pointer to the stash for a specified package, which must be a
637 valid UTF-8 string.  See C<gv_stashpv>.
638
639 =cut
640 */
641
642 HV*
643 Perl_gv_stashsv(pTHX_ SV *sv, I32 create)
644 {
645     register char *ptr;
646     STRLEN len;
647     ptr = SvPV(sv,len);
648     return gv_stashpvn(ptr, len, create);
649 }
650
651
652 GV *
653 Perl_gv_fetchpv(pTHX_ const char *nambeg, I32 add, I32 sv_type)
654 {
655     register const char *name = nambeg;
656     register GV *gv = 0;
657     GV**gvp;
658     I32 len;
659     register const char *namend;
660     HV *stash = 0;
661
662     if (*name == '*' && isALPHA(name[1])) /* accidental stringify on a GV? */
663         name++;
664
665     for (namend = name; *namend; namend++) {
666         if ((*namend == ':' && namend[1] == ':')
667             || (*namend == '\'' && namend[1]))
668         {
669             if (!stash)
670                 stash = PL_defstash;
671             if (!stash || !SvREFCNT(stash)) /* symbol table under destruction */
672                 return Nullgv;
673
674             len = namend - name;
675             if (len > 0) {
676                 char smallbuf[256];
677                 char *tmpbuf;
678
679                 if (len + 3 < sizeof (smallbuf))
680                     tmpbuf = smallbuf;
681                 else
682                     New(601, tmpbuf, len+3, char);
683                 Copy(name, tmpbuf, len, char);
684                 tmpbuf[len++] = ':';
685                 tmpbuf[len++] = ':';
686                 tmpbuf[len] = '\0';
687                 gvp = (GV**)hv_fetch(stash,tmpbuf,len,add);
688                 gv = gvp ? *gvp : Nullgv;
689                 if (gv && gv != (GV*)&PL_sv_undef) {
690                     if (SvTYPE(gv) != SVt_PVGV)
691                         gv_init(gv, stash, tmpbuf, len, (add & GV_ADDMULTI));
692                     else
693                         GvMULTI_on(gv);
694                 }
695                 if (tmpbuf != smallbuf)
696                     Safefree(tmpbuf);
697                 if (!gv || gv == (GV*)&PL_sv_undef)
698                     return Nullgv;
699
700                 if (!(stash = GvHV(gv)))
701                     stash = GvHV(gv) = newHV();
702
703                 if (!HvNAME(stash))
704                     HvNAME(stash) = savepvn(nambeg, namend - nambeg);
705             }
706
707             if (*namend == ':')
708                 namend++;
709             namend++;
710             name = namend;
711             if (!*name)
712                 return gv ? gv : (GV*)*hv_fetch(PL_defstash, "main::", 6, TRUE);
713         }
714     }
715     len = namend - name;
716
717     /* No stash in name, so see how we can default */
718
719     if (!stash) {
720         if (isIDFIRST_lazy(name)) {
721             bool global = FALSE;
722
723             /* name is always \0 terminated, and initial \0 wouldn't return
724                true from isIDFIRST_lazy, so we know that name[1] is defined  */
725             switch (name[1]) {
726             case '\0':
727                 if (*name == '_')
728                     global = TRUE;
729                 break;
730             case 'N':
731                 if (strEQ(name, "INC") || strEQ(name, "ENV"))
732                     global = TRUE;
733                 break;
734             case 'I':
735                 if (strEQ(name, "SIG"))
736                     global = TRUE;
737                 break;
738             case 'T':
739                 if (strEQ(name, "STDIN") || strEQ(name, "STDOUT") ||
740                     strEQ(name, "STDERR"))
741                     global = TRUE;
742                 break;
743             case 'R':
744                 if (strEQ(name, "ARGV") || strEQ(name, "ARGVOUT"))
745                     global = TRUE;
746                 break;
747             }
748
749             if (global)
750                 stash = PL_defstash;
751             else if (IN_PERL_COMPILETIME) {
752                 stash = PL_curstash;
753                 if (add && (PL_hints & HINT_STRICT_VARS) &&
754                     sv_type != SVt_PVCV &&
755                     sv_type != SVt_PVGV &&
756                     sv_type != SVt_PVFM &&
757                     sv_type != SVt_PVIO &&
758                     !(len == 1 && sv_type == SVt_PV &&
759                       (*name == 'a' || *name == 'b')) )
760                 {
761                     gvp = (GV**)hv_fetch(stash,name,len,0);
762                     if (!gvp ||
763                         *gvp == (GV*)&PL_sv_undef ||
764                         SvTYPE(*gvp) != SVt_PVGV)
765                     {
766                         stash = 0;
767                     }
768                     else if ((sv_type == SVt_PV   && !GvIMPORTED_SV(*gvp)) ||
769                              (sv_type == SVt_PVAV && !GvIMPORTED_AV(*gvp)) ||
770                              (sv_type == SVt_PVHV && !GvIMPORTED_HV(*gvp)) )
771                     {
772                         Perl_warn(aTHX_ "Variable \"%c%s\" is not imported",
773                             sv_type == SVt_PVAV ? '@' :
774                             sv_type == SVt_PVHV ? '%' : '$',
775                             name);
776                         if (GvCVu(*gvp))
777                             Perl_warn(aTHX_ "\t(Did you mean &%s instead?)\n", name);
778                         stash = 0;
779                     }
780                 }
781             }
782             else
783                 stash = CopSTASH(PL_curcop);
784         }
785         else
786             stash = PL_defstash;
787     }
788
789     /* By this point we should have a stash and a name */
790
791     if (!stash) {
792         if (add) {
793             register SV *err = Perl_mess(aTHX_
794                  "Global symbol \"%s%s\" requires explicit package name",
795                  (sv_type == SVt_PV ? "$"
796                   : sv_type == SVt_PVAV ? "@"
797                   : sv_type == SVt_PVHV ? "%"
798                   : ""), name);
799             if (USE_UTF8_IN_NAMES)
800                 SvUTF8_on(err);
801             qerror(err);
802             stash = GvHV(gv_fetchpv("<none>::", GV_ADDMULTI, SVt_PVHV));
803         }
804         else
805             return Nullgv;
806     }
807
808     if (!SvREFCNT(stash))       /* symbol table under destruction */
809         return Nullgv;
810
811     gvp = (GV**)hv_fetch(stash,name,len,add);
812     if (!gvp || *gvp == (GV*)&PL_sv_undef)
813         return Nullgv;
814     gv = *gvp;
815     if (SvTYPE(gv) == SVt_PVGV) {
816         if (add) {
817             GvMULTI_on(gv);
818             gv_init_sv(gv, sv_type);
819             if (*name=='!' && sv_type == SVt_PVHV && len==1)
820                 require_errno(gv);
821         }
822         return gv;
823     } else if (add & GV_NOINIT) {
824         return gv;
825     }
826
827     /* Adding a new symbol */
828
829     if (add & GV_ADDWARN && ckWARN_d(WARN_INTERNAL))
830         Perl_warner(aTHX_ packWARN(WARN_INTERNAL), "Had to create %s unexpectedly", nambeg);
831     gv_init(gv, stash, name, len, add & GV_ADDMULTI);
832     gv_init_sv(gv, sv_type);
833
834     if (isALPHA(name[0]) && ! (isLEXWARN_on ? ckWARN(WARN_ONCE) 
835                                             : (PL_dowarn & G_WARN_ON ) ) )
836         GvMULTI_on(gv) ;
837
838     /* set up magic where warranted */
839     if (len > 1) {
840 #ifndef EBCDIC
841         if (*name > 'V' ) {
842             /* Nothing else to do.
843                The compiler will probably turn the switch statement into a
844                branch table. Make sure we avoid even that small overhead for
845                the common case of lower case variable names.  */
846         } else
847 #endif
848         {
849             const char *name2 = name + 1;
850             switch (*name) {
851             case 'A':
852                 if (strEQ(name2, "RGV")) {
853                     IoFLAGS(GvIOn(gv)) |= IOf_ARGV|IOf_START;
854                 }
855                 break;
856             case 'E':
857                 if (strnEQ(name2, "XPORT", 5))
858                     GvMULTI_on(gv);
859                 break;
860             case 'I':
861                 if (strEQ(name2, "SA")) {
862                     AV* av = GvAVn(gv);
863                     GvMULTI_on(gv);
864                     sv_magic((SV*)av, (SV*)gv, PERL_MAGIC_isa, Nullch, 0);
865                     /* NOTE: No support for tied ISA */
866                     if ((add & GV_ADDMULTI) && strEQ(nambeg,"AnyDBM_File::ISA")
867                         && AvFILLp(av) == -1)
868                         {
869                             char *pname;
870                             av_push(av, newSVpvn(pname = "NDBM_File",9));
871                             gv_stashpvn(pname, 9, TRUE);
872                             av_push(av, newSVpvn(pname = "DB_File",7));
873                             gv_stashpvn(pname, 7, TRUE);
874                             av_push(av, newSVpvn(pname = "GDBM_File",9));
875                             gv_stashpvn(pname, 9, TRUE);
876                             av_push(av, newSVpvn(pname = "SDBM_File",9));
877                             gv_stashpvn(pname, 9, TRUE);
878                             av_push(av, newSVpvn(pname = "ODBM_File",9));
879                             gv_stashpvn(pname, 9, TRUE);
880                         }
881                 }
882                 break;
883             case 'O':
884                 if (strEQ(name2, "VERLOAD")) {
885                     HV* hv = GvHVn(gv);
886                     GvMULTI_on(gv);
887                     hv_magic(hv, Nullgv, PERL_MAGIC_overload);
888                 }
889                 break;
890             case 'S':
891                 if (strEQ(name2, "IG")) {
892                     HV *hv;
893                     I32 i;
894                     if (!PL_psig_ptr) {
895                         Newz(73, PL_psig_ptr,  SIG_SIZE, SV*);
896                         Newz(73, PL_psig_name, SIG_SIZE, SV*);
897                         Newz(73, PL_psig_pend, SIG_SIZE, int);
898                     }
899                     GvMULTI_on(gv);
900                     hv = GvHVn(gv);
901                     hv_magic(hv, Nullgv, PERL_MAGIC_sig);
902                     for (i = 1; i < SIG_SIZE; i++) {
903                         SV ** init;
904                         init = hv_fetch(hv, PL_sig_name[i], strlen(PL_sig_name[i]), 1);
905                         if (init)
906                             sv_setsv(*init, &PL_sv_undef);
907                         PL_psig_ptr[i] = 0;
908                         PL_psig_name[i] = 0;
909                         PL_psig_pend[i] = 0;
910                     }
911                 }
912                 break;
913             case 'V':
914                 if (strEQ(name2, "ERSION"))
915                     GvMULTI_on(gv);
916                 break;
917             case '\005':        /* $^ENCODING */
918                 if (strEQ(name2, "NCODING"))
919                     goto magicalize;
920                 break;
921             case '\017':        /* $^OPEN */
922                 if (strEQ(name2, "PEN"))
923                     goto magicalize;
924                 break;
925             case '\024':        /* ${^TAINT} */
926                 if (strEQ(name2, "AINT"))
927                     goto ro_magicalize;
928                 break;
929             case '\025':        /* $^UNICODE */
930                 if (strEQ(name2, "NICODE")) 
931                     goto ro_magicalize;
932                 break;
933             case '\027':        /* $^WARNING_BITS */
934                 if (strEQ(name2, "ARNING_BITS"))
935                     goto magicalize;
936                 break;
937             case '1':
938             case '2':
939             case '3':
940             case '4':
941             case '5':
942             case '6':
943             case '7':
944             case '8':
945             case '9':
946             {
947                 /* ensures variable is only digits */
948                 /* ${"1foo"} fails this test (and is thus writeable) */
949                 /* added by japhy, but borrowed from is_gv_magical */
950                 const char *end = name + len;
951                 while (--end > name) {
952                     if (!isDIGIT(*end)) return gv;
953                 }
954                 goto ro_magicalize;
955             }
956             }
957         }
958     } else {
959         /* Names of length 1.  (Or 0. But name is NUL terminated, so that will
960            be case '\0' in this switch statement (ie a default case)  */
961         switch (*name) {
962         case '&':
963         case '`':
964         case '\'':
965             if (
966                 sv_type == SVt_PVAV ||
967                 sv_type == SVt_PVHV ||
968                 sv_type == SVt_PVCV ||
969                 sv_type == SVt_PVFM ||
970                 sv_type == SVt_PVIO
971                 ) { break; }
972             PL_sawampersand = TRUE;
973             goto ro_magicalize;
974
975         case ':':
976             sv_setpv(GvSV(gv),PL_chopset);
977             goto magicalize;
978
979         case '?':
980 #ifdef COMPLEX_STATUS
981             (void)SvUPGRADE(GvSV(gv), SVt_PVLV);
982 #endif
983             goto magicalize;
984
985         case '!':
986
987             /* If %! has been used, automatically load Errno.pm.
988                The require will itself set errno, so in order to
989                preserve its value we have to set up the magic
990                now (rather than going to magicalize)
991             */
992
993             sv_magic(GvSV(gv), (SV*)gv, PERL_MAGIC_sv, name, len);
994
995             if (sv_type == SVt_PVHV)
996                 require_errno(gv);
997
998             break;
999         case '-':
1000         {
1001             AV* av = GvAVn(gv);
1002             sv_magic((SV*)av, Nullsv, PERL_MAGIC_regdata, Nullch, 0);
1003             SvREADONLY_on(av);
1004             goto magicalize;
1005         }
1006         case '*':
1007             if (sv_type == SVt_PV && ckWARN2(WARN_DEPRECATED, WARN_SYNTAX))
1008                 Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED, WARN_SYNTAX),
1009                             "$* is no longer supported");
1010             break;
1011         case '#':
1012             if (sv_type == SVt_PV && ckWARN2(WARN_DEPRECATED, WARN_SYNTAX))
1013                 Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED, WARN_SYNTAX),
1014                             "Use of $# is deprecated");
1015             goto magicalize;
1016         case '|':
1017             sv_setiv(GvSV(gv), (IV)(IoFLAGS(GvIOp(PL_defoutgv)) & IOf_FLUSH) != 0);
1018             goto magicalize;
1019
1020         case '+':
1021         {
1022             AV* av = GvAVn(gv);
1023             sv_magic((SV*)av, (SV*)av, PERL_MAGIC_regdata, Nullch, 0);
1024             SvREADONLY_on(av);
1025             /* FALL THROUGH */
1026         }
1027         case '\023':    /* $^S */
1028         case '1':
1029         case '2':
1030         case '3':
1031         case '4':
1032         case '5':
1033         case '6':
1034         case '7':
1035         case '8':
1036         case '9':
1037         ro_magicalize:
1038             SvREADONLY_on(GvSV(gv));
1039             /* FALL THROUGH */
1040         case '[':
1041         case '^':
1042         case '~':
1043         case '=':
1044         case '%':
1045         case '.':
1046         case '(':
1047         case ')':
1048         case '<':
1049         case '>':
1050         case ',':
1051         case '\\':
1052         case '/':
1053         case '\001':    /* $^A */
1054         case '\003':    /* $^C */
1055         case '\004':    /* $^D */
1056         case '\005':    /* $^E */
1057         case '\006':    /* $^F */
1058         case '\010':    /* $^H */
1059         case '\011':    /* $^I, NOT \t in EBCDIC */
1060         case '\016':    /* $^N */
1061         case '\017':    /* $^O */
1062         case '\020':    /* $^P */
1063         case '\024':    /* $^T */
1064         case '\027':    /* $^W */
1065         magicalize:
1066             sv_magic(GvSV(gv), (SV*)gv, PERL_MAGIC_sv, name, len);
1067             break;
1068
1069         case '\014':    /* $^L */
1070             sv_setpv(GvSV(gv),"\f");
1071             PL_formfeed = GvSV(gv);
1072             break;
1073         case ';':
1074             sv_setpv(GvSV(gv),"\034");
1075             break;
1076         case ']':
1077         {
1078             SV *sv = GvSV(gv);
1079             if (!sv_derived_from(PL_patchlevel, "version"))
1080                 (void *)upg_version(PL_patchlevel);
1081             GvSV(gv) = vnumify(PL_patchlevel);
1082             SvREADONLY_on(GvSV(gv));
1083             SvREFCNT_dec(sv);
1084         }
1085         break;
1086         case '\026':    /* $^V */
1087         {
1088             SV *sv = GvSV(gv);
1089             GvSV(gv) = new_version(PL_patchlevel);
1090             SvREADONLY_on(GvSV(gv));
1091             SvREFCNT_dec(sv);
1092         }
1093         break;
1094         }
1095     }
1096     return gv;
1097 }
1098
1099 void
1100 Perl_gv_fullname4(pTHX_ SV *sv, GV *gv, const char *prefix, bool keepmain)
1101 {
1102     char *name;
1103     HV *hv = GvSTASH(gv);
1104     if (!hv) {
1105         SvOK_off(sv);
1106         return;
1107     }
1108     sv_setpv(sv, prefix ? prefix : "");
1109     
1110     name = HvNAME(hv);
1111     if (!name)
1112         name = "__ANON__";
1113         
1114     if (keepmain || strNE(name, "main")) {
1115         sv_catpv(sv,name);
1116         sv_catpvn(sv,"::", 2);
1117     }
1118     sv_catpvn(sv,GvNAME(gv),GvNAMELEN(gv));
1119 }
1120
1121 void
1122 Perl_gv_fullname3(pTHX_ SV *sv, GV *gv, const char *prefix)
1123 {
1124     gv_fullname4(sv, gv, prefix, TRUE);
1125 }
1126
1127 void
1128 Perl_gv_efullname4(pTHX_ SV *sv, GV *gv, const char *prefix, bool keepmain)
1129 {
1130     GV *egv = GvEGV(gv);
1131     if (!egv)
1132         egv = gv;
1133     gv_fullname4(sv, egv, prefix, keepmain);
1134 }
1135
1136 void
1137 Perl_gv_efullname3(pTHX_ SV *sv, GV *gv, const char *prefix)
1138 {
1139     gv_efullname4(sv, gv, prefix, TRUE);
1140 }
1141
1142 /* XXX compatibility with versions <= 5.003. */
1143 void
1144 Perl_gv_fullname(pTHX_ SV *sv, GV *gv)
1145 {
1146     gv_fullname3(sv, gv, sv == (SV*)gv ? "*" : "");
1147 }
1148
1149 /* XXX compatibility with versions <= 5.003. */
1150 void
1151 Perl_gv_efullname(pTHX_ SV *sv, GV *gv)
1152 {
1153     gv_efullname3(sv, gv, sv == (SV*)gv ? "*" : "");
1154 }
1155
1156 IO *
1157 Perl_newIO(pTHX)
1158 {
1159     IO *io;
1160     GV *iogv;
1161
1162     io = (IO*)NEWSV(0,0);
1163     sv_upgrade((SV *)io,SVt_PVIO);
1164     SvREFCNT(io) = 1;
1165     SvOBJECT_on(io);
1166     /* Clear the stashcache because a new IO could overrule a 
1167        package name */
1168     hv_clear(PL_stashcache);
1169     iogv = gv_fetchpv("FileHandle::", FALSE, SVt_PVHV);
1170     /* unless exists($main::{FileHandle}) and defined(%main::FileHandle::) */
1171     if (!(iogv && GvHV(iogv) && HvARRAY(GvHV(iogv))))
1172       iogv = gv_fetchpv("IO::Handle::", TRUE, SVt_PVHV);
1173     SvSTASH(io) = (HV*)SvREFCNT_inc(GvHV(iogv));
1174     return io;
1175 }
1176
1177 void
1178 Perl_gv_check(pTHX_ HV *stash)
1179 {
1180     register HE *entry;
1181     register I32 i;
1182     register GV *gv;
1183     HV *hv;
1184
1185     if (!HvARRAY(stash))
1186         return;
1187     for (i = 0; i <= (I32) HvMAX(stash); i++) {
1188         for (entry = HvARRAY(stash)[i]; entry; entry = HeNEXT(entry)) {
1189             if (HeKEY(entry)[HeKLEN(entry)-1] == ':' &&
1190                 (gv = (GV*)HeVAL(entry)) && isGV(gv) && (hv = GvHV(gv)))
1191             {
1192                 if (hv != PL_defstash && hv != stash)
1193                      gv_check(hv);              /* nested package */
1194             }
1195             else if (isALPHA(*HeKEY(entry))) {
1196                 char *file;
1197                 gv = (GV*)HeVAL(entry);
1198                 if (SvTYPE(gv) != SVt_PVGV || GvMULTI(gv))
1199                     continue;
1200                 file = GvFILE(gv);
1201                 /* performance hack: if filename is absolute and it's a standard
1202                  * module, don't bother warning */
1203                 if (file
1204                     && PERL_FILE_IS_ABSOLUTE(file)
1205 #ifdef MACOS_TRADITIONAL
1206                     && (instr(file, ":lib:")
1207 #else
1208                     && (instr(file, "/lib/")
1209 #endif
1210                     || instr(file, ".pm")))
1211                 {
1212                     continue;
1213                 }
1214                 CopLINE_set(PL_curcop, GvLINE(gv));
1215 #ifdef USE_ITHREADS
1216                 CopFILE(PL_curcop) = file;      /* set for warning */
1217 #else
1218                 CopFILEGV(PL_curcop) = gv_fetchfile(file);
1219 #endif
1220                 Perl_warner(aTHX_ packWARN(WARN_ONCE),
1221                         "Name \"%s::%s\" used only once: possible typo",
1222                         HvNAME(stash), GvNAME(gv));
1223             }
1224         }
1225     }
1226 }
1227
1228 GV *
1229 Perl_newGVgen(pTHX_ char *pack)
1230 {
1231     return gv_fetchpv(Perl_form(aTHX_ "%s::_GEN_%ld", pack, (long)PL_gensym++),
1232                       TRUE, SVt_PVGV);
1233 }
1234
1235 /* hopefully this is only called on local symbol table entries */
1236
1237 GP*
1238 Perl_gp_ref(pTHX_ GP *gp)
1239 {
1240     if (!gp)
1241         return (GP*)NULL;
1242     gp->gp_refcnt++;
1243     if (gp->gp_cv) {
1244         if (gp->gp_cvgen) {
1245             /* multi-named GPs cannot be used for method cache */
1246             SvREFCNT_dec(gp->gp_cv);
1247             gp->gp_cv = Nullcv;
1248             gp->gp_cvgen = 0;
1249         }
1250         else {
1251             /* Adding a new name to a subroutine invalidates method cache */
1252             PL_sub_generation++;
1253         }
1254     }
1255     return gp;
1256 }
1257
1258 void
1259 Perl_gp_free(pTHX_ GV *gv)
1260 {
1261     GP* gp;
1262
1263     if (!gv || !(gp = GvGP(gv)))
1264         return;
1265     if (gp->gp_refcnt == 0) {
1266         if (ckWARN_d(WARN_INTERNAL))
1267             Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
1268                         "Attempt to free unreferenced glob pointers"
1269                         pTHX__FORMAT pTHX__VALUE);
1270         return;
1271     }
1272     if (gp->gp_cv) {
1273         /* Deleting the name of a subroutine invalidates method cache */
1274         PL_sub_generation++;
1275     }
1276     if (--gp->gp_refcnt > 0) {
1277         if (gp->gp_egv == gv)
1278             gp->gp_egv = 0;
1279         return;
1280     }
1281
1282     if (gp->gp_sv) SvREFCNT_dec(gp->gp_sv);
1283     if (gp->gp_av) SvREFCNT_dec(gp->gp_av);
1284     if (gp->gp_hv) {
1285          if (PL_stashcache && HvNAME(gp->gp_hv))
1286               hv_delete(PL_stashcache,
1287                         HvNAME(gp->gp_hv), strlen(HvNAME(gp->gp_hv)),
1288                         G_DISCARD);
1289          SvREFCNT_dec(gp->gp_hv);
1290     }
1291     if (gp->gp_io)   SvREFCNT_dec(gp->gp_io);
1292     if (gp->gp_cv)   SvREFCNT_dec(gp->gp_cv);
1293     if (gp->gp_form) SvREFCNT_dec(gp->gp_form);
1294
1295     Safefree(gp);
1296     GvGP(gv) = 0;
1297 }
1298
1299 int
1300 Perl_magic_freeovrld(pTHX_ SV *sv, MAGIC *mg)
1301 {
1302     AMT *amtp = (AMT*)mg->mg_ptr;
1303     if (amtp && AMT_AMAGIC(amtp)) {
1304         int i;
1305         for (i = 1; i < NofAMmeth; i++) {
1306             CV *cv = amtp->table[i];
1307             if (cv != Nullcv) {
1308                 SvREFCNT_dec((SV *) cv);
1309                 amtp->table[i] = Nullcv;
1310             }
1311         }
1312     }
1313  return 0;
1314 }
1315
1316 /* Updates and caches the CV's */
1317
1318 bool
1319 Perl_Gv_AMupdate(pTHX_ HV *stash)
1320 {
1321   GV* gv;
1322   CV* cv;
1323   MAGIC* mg=mg_find((SV*)stash, PERL_MAGIC_overload_table);
1324   AMT *amtp = (mg) ? (AMT*)mg->mg_ptr: (AMT *) NULL;
1325   AMT amt;
1326
1327   if (mg && amtp->was_ok_am == PL_amagic_generation
1328       && amtp->was_ok_sub == PL_sub_generation)
1329       return (bool)AMT_OVERLOADED(amtp);
1330   sv_unmagic((SV*)stash, PERL_MAGIC_overload_table);
1331
1332   DEBUG_o( Perl_deb(aTHX_ "Recalcing overload magic in package %s\n",HvNAME(stash)) );
1333
1334   Zero(&amt,1,AMT);
1335   amt.was_ok_am = PL_amagic_generation;
1336   amt.was_ok_sub = PL_sub_generation;
1337   amt.fallback = AMGfallNO;
1338   amt.flags = 0;
1339
1340   {
1341     int filled = 0, have_ovl = 0;
1342     int i, lim = 1;
1343     SV* sv = NULL;
1344
1345     /* Work with "fallback" key, which we assume to be first in PL_AMG_names */
1346
1347     /* Try to find via inheritance. */
1348     gv = gv_fetchmeth(stash, PL_AMG_names[0], 2, -1);
1349     if (gv)
1350         sv = GvSV(gv);
1351
1352     if (!gv)
1353         lim = DESTROY_amg;              /* Skip overloading entries. */
1354     else if (SvTRUE(sv))
1355         amt.fallback=AMGfallYES;
1356     else if (SvOK(sv))
1357         amt.fallback=AMGfallNEVER;
1358
1359     for (i = 1; i < lim; i++)
1360         amt.table[i] = Nullcv;
1361     for (; i < NofAMmeth; i++) {
1362         char *cooky = (char*)PL_AMG_names[i];
1363         /* Human-readable form, for debugging: */
1364         char *cp = (i >= DESTROY_amg ? cooky : AMG_id2name(i));
1365         STRLEN l = strlen(cooky);
1366
1367         DEBUG_o( Perl_deb(aTHX_ "Checking overloading of `%s' in package `%.256s'\n",
1368                      cp, HvNAME(stash)) );
1369         /* don't fill the cache while looking up!
1370            Creation of inheritance stubs in intermediate packages may
1371            conflict with the logic of runtime method substitution.
1372            Indeed, for inheritance A -> B -> C, if C overloads "+0",
1373            then we could have created stubs for "(+0" in A and C too.
1374            But if B overloads "bool", we may want to use it for
1375            numifying instead of C's "+0". */
1376         if (i >= DESTROY_amg)
1377             gv = Perl_gv_fetchmeth_autoload(aTHX_ stash, cooky, l, 0);
1378         else                            /* Autoload taken care of below */
1379             gv = Perl_gv_fetchmeth(aTHX_ stash, cooky, l, -1);
1380         cv = 0;
1381         if (gv && (cv = GvCV(gv))) {
1382             if (GvNAMELEN(CvGV(cv)) == 3 && strEQ(GvNAME(CvGV(cv)), "nil")
1383                 && strEQ(HvNAME(GvSTASH(CvGV(cv))), "overload")) {
1384                 /* This is a hack to support autoloading..., while
1385                    knowing *which* methods were declared as overloaded. */
1386                 /* GvSV contains the name of the method. */
1387                 GV *ngv = Nullgv;
1388                 
1389                 DEBUG_o( Perl_deb(aTHX_ "Resolving method `%"SVf256\
1390                         "' for overloaded `%s' in package `%.256s'\n",
1391                              GvSV(gv), cp, HvNAME(stash)) );
1392                 if (!SvPOK(GvSV(gv))
1393                     || !(ngv = gv_fetchmethod_autoload(stash, SvPVX(GvSV(gv)),
1394                                                        FALSE)))
1395                 {
1396                     /* Can be an import stub (created by `can'). */
1397                     SV *gvsv = GvSV(gv);
1398                     const char *name = SvPOK(gvsv) ?  SvPVX(gvsv) : "???";
1399                     Perl_croak(aTHX_ "%s method `%.256s' overloading `%s' "\
1400                                 "in package `%.256s'",
1401                                (GvCVGEN(gv) ? "Stub found while resolving"
1402                                 : "Can't resolve"),
1403                                name, cp, HvNAME(stash));
1404                 }
1405                 cv = GvCV(gv = ngv);
1406             }
1407             DEBUG_o( Perl_deb(aTHX_ "Overloading `%s' in package `%.256s' via `%.256s::%.256s' \n",
1408                          cp, HvNAME(stash), HvNAME(GvSTASH(CvGV(cv))),
1409                          GvNAME(CvGV(cv))) );
1410             filled = 1;
1411             if (i < DESTROY_amg)
1412                 have_ovl = 1;
1413         } else if (gv) {                /* Autoloaded... */
1414             cv = (CV*)gv;
1415             filled = 1;
1416         }
1417         amt.table[i]=(CV*)SvREFCNT_inc(cv);
1418     }
1419     if (filled) {
1420       AMT_AMAGIC_on(&amt);
1421       if (have_ovl)
1422           AMT_OVERLOADED_on(&amt);
1423       sv_magic((SV*)stash, 0, PERL_MAGIC_overload_table,
1424                                                 (char*)&amt, sizeof(AMT));
1425       return have_ovl;
1426     }
1427   }
1428   /* Here we have no table: */
1429   /* no_table: */
1430   AMT_AMAGIC_off(&amt);
1431   sv_magic((SV*)stash, 0, PERL_MAGIC_overload_table,
1432                                                 (char*)&amt, sizeof(AMTS));
1433   return FALSE;
1434 }
1435
1436
1437 CV*
1438 Perl_gv_handler(pTHX_ HV *stash, I32 id)
1439 {
1440     MAGIC *mg;
1441     AMT *amtp;
1442     CV *ret;
1443
1444     if (!stash || !HvNAME(stash))
1445         return Nullcv;
1446     mg = mg_find((SV*)stash, PERL_MAGIC_overload_table);
1447     if (!mg) {
1448       do_update:
1449         Gv_AMupdate(stash);
1450         mg = mg_find((SV*)stash, PERL_MAGIC_overload_table);
1451     }
1452     amtp = (AMT*)mg->mg_ptr;
1453     if ( amtp->was_ok_am != PL_amagic_generation
1454          || amtp->was_ok_sub != PL_sub_generation )
1455         goto do_update;
1456     if (AMT_AMAGIC(amtp)) {
1457         ret = amtp->table[id];
1458         if (ret && isGV(ret)) {         /* Autoloading stab */
1459             /* Passing it through may have resulted in a warning
1460                "Inherited AUTOLOAD for a non-method deprecated", since
1461                our caller is going through a function call, not a method call.
1462                So return the CV for AUTOLOAD, setting $AUTOLOAD. */
1463             GV *gv = gv_fetchmethod(stash, (char*)PL_AMG_names[id]);
1464
1465             if (gv && GvCV(gv))
1466                 return GvCV(gv);
1467         }
1468         return ret;
1469     }
1470     
1471     return Nullcv;
1472 }
1473
1474
1475 SV*
1476 Perl_amagic_call(pTHX_ SV *left, SV *right, int method, int flags)
1477 {
1478   MAGIC *mg;
1479   CV *cv=NULL;
1480   CV **cvp=NULL, **ocvp=NULL;
1481   AMT *amtp=NULL, *oamtp=NULL;
1482   int off=0, off1, lr=0, assign=AMGf_assign & flags, notfound=0;
1483   int postpr = 0, force_cpy = 0, assignshift = assign ? 1 : 0;
1484 #ifdef DEBUGGING
1485   int fl=0;
1486 #endif
1487   HV* stash=NULL;
1488   if (!(AMGf_noleft & flags) && SvAMAGIC(left)
1489       && (stash = SvSTASH(SvRV(left)))
1490       && (mg = mg_find((SV*)stash, PERL_MAGIC_overload_table))
1491       && (ocvp = cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
1492                         ? (oamtp = amtp = (AMT*)mg->mg_ptr)->table
1493                         : (CV **) NULL))
1494       && ((cv = cvp[off=method+assignshift])
1495           || (assign && amtp->fallback > AMGfallNEVER && /* fallback to
1496                                                           * usual method */
1497                   (
1498 #ifdef DEBUGGING
1499                    fl = 1,
1500 #endif 
1501                    cv = cvp[off=method])))) {
1502     lr = -1;                    /* Call method for left argument */
1503   } else {
1504     if (cvp && amtp->fallback > AMGfallNEVER && flags & AMGf_unary) {
1505       int logic;
1506
1507       /* look for substituted methods */
1508       /* In all the covered cases we should be called with assign==0. */
1509          switch (method) {
1510          case inc_amg:
1511            force_cpy = 1;
1512            if ((cv = cvp[off=add_ass_amg])
1513                || ((cv = cvp[off = add_amg]) && (force_cpy = 0, postpr = 1))) {
1514              right = &PL_sv_yes; lr = -1; assign = 1;
1515            }
1516            break;
1517          case dec_amg:
1518            force_cpy = 1;
1519            if ((cv = cvp[off = subtr_ass_amg])
1520                || ((cv = cvp[off = subtr_amg]) && (force_cpy = 0, postpr=1))) {
1521              right = &PL_sv_yes; lr = -1; assign = 1;
1522            }
1523            break;
1524          case bool__amg:
1525            (void)((cv = cvp[off=numer_amg]) || (cv = cvp[off=string_amg]));
1526            break;
1527          case numer_amg:
1528            (void)((cv = cvp[off=string_amg]) || (cv = cvp[off=bool__amg]));
1529            break;
1530          case string_amg:
1531            (void)((cv = cvp[off=numer_amg]) || (cv = cvp[off=bool__amg]));
1532            break;
1533  case not_amg:
1534    (void)((cv = cvp[off=bool__amg])
1535           || (cv = cvp[off=numer_amg])
1536           || (cv = cvp[off=string_amg]));
1537    postpr = 1;
1538    break;
1539          case copy_amg:
1540            {
1541              /*
1542                   * SV* ref causes confusion with the interpreter variable of
1543                   * the same name
1544                   */
1545              SV* tmpRef=SvRV(left);
1546              if (!SvROK(tmpRef) && SvTYPE(tmpRef) <= SVt_PVMG) {
1547                 /*
1548                  * Just to be extra cautious.  Maybe in some
1549                  * additional cases sv_setsv is safe, too.
1550                  */
1551                 SV* newref = newSVsv(tmpRef);
1552                 SvOBJECT_on(newref);
1553                 SvSTASH(newref) = (HV*)SvREFCNT_inc(SvSTASH(tmpRef));
1554                 return newref;
1555              }
1556            }
1557            break;
1558          case abs_amg:
1559            if ((cvp[off1=lt_amg] || cvp[off1=ncmp_amg])
1560                && ((cv = cvp[off=neg_amg]) || (cv = cvp[off=subtr_amg]))) {
1561              SV* nullsv=sv_2mortal(newSViv(0));
1562              if (off1==lt_amg) {
1563                SV* lessp = amagic_call(left,nullsv,
1564                                        lt_amg,AMGf_noright);
1565                logic = SvTRUE(lessp);
1566              } else {
1567                SV* lessp = amagic_call(left,nullsv,
1568                                        ncmp_amg,AMGf_noright);
1569                logic = (SvNV(lessp) < 0);
1570              }
1571              if (logic) {
1572                if (off==subtr_amg) {
1573                  right = left;
1574                  left = nullsv;
1575                  lr = 1;
1576                }
1577              } else {
1578                return left;
1579              }
1580            }
1581            break;
1582          case neg_amg:
1583            if ((cv = cvp[off=subtr_amg])) {
1584              right = left;
1585              left = sv_2mortal(newSViv(0));
1586              lr = 1;
1587            }
1588            break;
1589          case int_amg:
1590          case iter_amg:                 /* XXXX Eventually should do to_gv. */
1591              /* FAIL safe */
1592              return NULL;       /* Delegate operation to standard mechanisms. */
1593              break;
1594          case to_sv_amg:
1595          case to_av_amg:
1596          case to_hv_amg:
1597          case to_gv_amg:
1598          case to_cv_amg:
1599              /* FAIL safe */
1600              return left;       /* Delegate operation to standard mechanisms. */
1601              break;
1602          default:
1603            goto not_found;
1604          }
1605          if (!cv) goto not_found;
1606     } else if (!(AMGf_noright & flags) && SvAMAGIC(right)
1607                && (stash = SvSTASH(SvRV(right)))
1608                && (mg = mg_find((SV*)stash, PERL_MAGIC_overload_table))
1609                && (cvp = (AMT_AMAGIC((AMT*)mg->mg_ptr)
1610                           ? (amtp = (AMT*)mg->mg_ptr)->table
1611                           : (CV **) NULL))
1612                && (cv = cvp[off=method])) { /* Method for right
1613                                              * argument found */
1614       lr=1;
1615     } else if (((ocvp && oamtp->fallback > AMGfallNEVER
1616                  && (cvp=ocvp) && (lr = -1))
1617                 || (cvp && amtp->fallback > AMGfallNEVER && (lr=1)))
1618                && !(flags & AMGf_unary)) {
1619                                 /* We look for substitution for
1620                                  * comparison operations and
1621                                  * concatenation */
1622       if (method==concat_amg || method==concat_ass_amg
1623           || method==repeat_amg || method==repeat_ass_amg) {
1624         return NULL;            /* Delegate operation to string conversion */
1625       }
1626       off = -1;
1627       switch (method) {
1628          case lt_amg:
1629          case le_amg:
1630          case gt_amg:
1631          case ge_amg:
1632          case eq_amg:
1633          case ne_amg:
1634            postpr = 1; off=ncmp_amg; break;
1635          case slt_amg:
1636          case sle_amg:
1637          case sgt_amg:
1638          case sge_amg:
1639          case seq_amg:
1640          case sne_amg:
1641            postpr = 1; off=scmp_amg; break;
1642          }
1643       if (off != -1) cv = cvp[off];
1644       if (!cv) {
1645         goto not_found;
1646       }
1647     } else {
1648     not_found:                  /* No method found, either report or croak */
1649       switch (method) {
1650          case to_sv_amg:
1651          case to_av_amg:
1652          case to_hv_amg:
1653          case to_gv_amg:
1654          case to_cv_amg:
1655              /* FAIL safe */
1656              return left;       /* Delegate operation to standard mechanisms. */
1657              break;
1658       }
1659       if (ocvp && (cv=ocvp[nomethod_amg])) { /* Call report method */
1660         notfound = 1; lr = -1;
1661       } else if (cvp && (cv=cvp[nomethod_amg])) {
1662         notfound = 1; lr = 1;
1663       } else {
1664         SV *msg;
1665         if (off==-1) off=method;
1666         msg = sv_2mortal(Perl_newSVpvf(aTHX_
1667                       "Operation `%s': no method found,%sargument %s%s%s%s",
1668                       AMG_id2name(method + assignshift),
1669                       (flags & AMGf_unary ? " " : "\n\tleft "),
1670                       SvAMAGIC(left)?
1671                         "in overloaded package ":
1672                         "has no overloaded magic",
1673                       SvAMAGIC(left)?
1674                         HvNAME(SvSTASH(SvRV(left))):
1675                         "",
1676                       SvAMAGIC(right)?
1677                         ",\n\tright argument in overloaded package ":
1678                         (flags & AMGf_unary
1679                          ? ""
1680                          : ",\n\tright argument has no overloaded magic"),
1681                       SvAMAGIC(right)?
1682                         HvNAME(SvSTASH(SvRV(right))):
1683                         ""));
1684         if (amtp && amtp->fallback >= AMGfallYES) {
1685           DEBUG_o( Perl_deb(aTHX_ "%s", SvPVX(msg)) );
1686         } else {
1687           Perl_croak(aTHX_ "%"SVf, msg);
1688         }
1689         return NULL;
1690       }
1691       force_cpy = force_cpy || assign;
1692     }
1693   }
1694 #ifdef DEBUGGING
1695   if (!notfound) {
1696     DEBUG_o(Perl_deb(aTHX_
1697                      "Overloaded operator `%s'%s%s%s:\n\tmethod%s found%s in package %s%s\n",
1698                      AMG_id2name(off),
1699                      method+assignshift==off? "" :
1700                      " (initially `",
1701                      method+assignshift==off? "" :
1702                      AMG_id2name(method+assignshift),
1703                      method+assignshift==off? "" : "')",
1704                      flags & AMGf_unary? "" :
1705                      lr==1 ? " for right argument": " for left argument",
1706                      flags & AMGf_unary? " for argument" : "",
1707                      stash ? HvNAME(stash) : "null",
1708                      fl? ",\n\tassignment variant used": "") );
1709   }
1710 #endif
1711     /* Since we use shallow copy during assignment, we need
1712      * to dublicate the contents, probably calling user-supplied
1713      * version of copy operator
1714      */
1715     /* We need to copy in following cases:
1716      * a) Assignment form was called.
1717      *          assignshift==1,  assign==T, method + 1 == off
1718      * b) Increment or decrement, called directly.
1719      *          assignshift==0,  assign==0, method + 0 == off
1720      * c) Increment or decrement, translated to assignment add/subtr.
1721      *          assignshift==0,  assign==T,
1722      *          force_cpy == T
1723      * d) Increment or decrement, translated to nomethod.
1724      *          assignshift==0,  assign==0,
1725      *          force_cpy == T
1726      * e) Assignment form translated to nomethod.
1727      *          assignshift==1,  assign==T, method + 1 != off
1728      *          force_cpy == T
1729      */
1730     /*  off is method, method+assignshift, or a result of opcode substitution.
1731      *  In the latter case assignshift==0, so only notfound case is important.
1732      */
1733   if (( (method + assignshift == off)
1734         && (assign || (method == inc_amg) || (method == dec_amg)))
1735       || force_cpy)
1736     RvDEEPCP(left);
1737   {
1738     dSP;
1739     BINOP myop;
1740     SV* res;
1741     bool oldcatch = CATCH_GET;
1742
1743     CATCH_SET(TRUE);
1744     Zero(&myop, 1, BINOP);
1745     myop.op_last = (OP *) &myop;
1746     myop.op_next = Nullop;
1747     myop.op_flags = OPf_WANT_SCALAR | OPf_STACKED;
1748
1749     PUSHSTACKi(PERLSI_OVERLOAD);
1750     ENTER;
1751     SAVEOP();
1752     PL_op = (OP *) &myop;
1753     if (PERLDB_SUB && PL_curstash != PL_debstash)
1754         PL_op->op_private |= OPpENTERSUB_DB;
1755     PUTBACK;
1756     pp_pushmark();
1757
1758     EXTEND(SP, notfound + 5);
1759     PUSHs(lr>0? right: left);
1760     PUSHs(lr>0? left: right);
1761     PUSHs( lr > 0 ? &PL_sv_yes : ( assign ? &PL_sv_undef : &PL_sv_no ));
1762     if (notfound) {
1763       PUSHs( sv_2mortal(newSVpv(AMG_id2name(method + assignshift),0)));
1764     }
1765     PUSHs((SV*)cv);
1766     PUTBACK;
1767
1768     if ((PL_op = Perl_pp_entersub(aTHX)))
1769       CALLRUNOPS(aTHX);
1770     LEAVE;
1771     SPAGAIN;
1772
1773     res=POPs;
1774     PUTBACK;
1775     POPSTACK;
1776     CATCH_SET(oldcatch);
1777
1778     if (postpr) {
1779       int ans=0;
1780       switch (method) {
1781       case le_amg:
1782       case sle_amg:
1783         ans=SvIV(res)<=0; break;
1784       case lt_amg:
1785       case slt_amg:
1786         ans=SvIV(res)<0; break;
1787       case ge_amg:
1788       case sge_amg:
1789         ans=SvIV(res)>=0; break;
1790       case gt_amg:
1791       case sgt_amg:
1792         ans=SvIV(res)>0; break;
1793       case eq_amg:
1794       case seq_amg:
1795         ans=SvIV(res)==0; break;
1796       case ne_amg:
1797       case sne_amg:
1798         ans=SvIV(res)!=0; break;
1799       case inc_amg:
1800       case dec_amg:
1801         SvSetSV(left,res); return left;
1802       case not_amg:
1803         ans=!SvTRUE(res); break;
1804       }
1805       return boolSV(ans);
1806     } else if (method==copy_amg) {
1807       if (!SvROK(res)) {
1808         Perl_croak(aTHX_ "Copy method did not return a reference");
1809       }
1810       return SvREFCNT_inc(SvRV(res));
1811     } else {
1812       return res;
1813     }
1814   }
1815 }
1816
1817 /*
1818 =for apidoc is_gv_magical
1819
1820 Returns C<TRUE> if given the name of a magical GV.
1821
1822 Currently only useful internally when determining if a GV should be
1823 created even in rvalue contexts.
1824
1825 C<flags> is not used at present but available for future extension to
1826 allow selecting particular classes of magical variable.
1827
1828 Currently assumes that C<name> is NUL terminated (as well as len being valid).
1829 This assumption is met by all callers within the perl core, which all pass
1830 pointers returned by SvPV.
1831
1832 =cut
1833 */
1834 bool
1835 Perl_is_gv_magical(pTHX_ char *name, STRLEN len, U32 flags)
1836 {
1837     if (len > 1) {
1838         const char *name1 = name + 1;
1839         switch (*name) {
1840         case 'I':
1841             if (len == 3 && name1[1] == 'S' && name[2] == 'A')
1842                 goto yes;
1843             break;
1844         case 'O':
1845             if (len == 8 && strEQ(name1, "VERLOAD"))
1846                 goto yes;
1847             break;
1848         case 'S':
1849             if (len == 3 && name[1] == 'I' && name[2] == 'G')
1850                 goto yes;
1851             break;
1852             /* Using ${^...} variables is likely to be sufficiently rare that
1853                it seems sensible to avoid the space hit of also checking the
1854                length.  */
1855         case '\017':   /* ${^OPEN} */
1856             if (strEQ(name1, "PEN"))
1857                 goto yes;
1858             break;
1859         case '\024':   /* ${^TAINT} */
1860             if (strEQ(name1, "AINT"))
1861                 goto yes;
1862             break;
1863         case '\025':    /* ${^UNICODE} */
1864             if (strEQ(name1, "NICODE"))
1865                 goto yes;
1866             break;
1867         case '\027':   /* ${^WARNING_BITS} */
1868             if (strEQ(name1, "ARNING_BITS"))
1869                 goto yes;
1870             break;
1871         case '1':
1872         case '2':
1873         case '3':
1874         case '4':
1875         case '5':
1876         case '6':
1877         case '7':
1878         case '8':
1879         case '9':
1880         {
1881             char *end = name + len;
1882             while (--end > name) {
1883                 if (!isDIGIT(*end))
1884                     return FALSE;
1885             }
1886             goto yes;
1887         }
1888         }
1889     } else {
1890         /* Because we're already assuming that name is NUL terminated
1891            below, we can treat an empty name as "\0"  */
1892         switch (*name) {
1893         case '&':
1894         case '`':
1895         case '\'':
1896         case ':':
1897         case '?':
1898         case '!':
1899         case '-':
1900         case '#':
1901         case '[':
1902         case '^':
1903         case '~':
1904         case '=':
1905         case '%':
1906         case '.':
1907         case '(':
1908         case ')':
1909         case '<':
1910         case '>':
1911         case ',':
1912         case '\\':
1913         case '/':
1914         case '|':
1915         case '+':
1916         case ';':
1917         case ']':
1918         case '\001':   /* $^A */
1919         case '\003':   /* $^C */
1920         case '\004':   /* $^D */
1921         case '\005':   /* $^E */
1922         case '\006':   /* $^F */
1923         case '\010':   /* $^H */
1924         case '\011':   /* $^I, NOT \t in EBCDIC */
1925         case '\014':   /* $^L */
1926         case '\016':   /* $^N */
1927         case '\017':   /* $^O */
1928         case '\020':   /* $^P */
1929         case '\023':   /* $^S */
1930         case '\024':   /* $^T */
1931         case '\026':   /* $^V */
1932         case '\027':   /* $^W */
1933         case '1':
1934         case '2':
1935         case '3':
1936         case '4':
1937         case '5':
1938         case '6':
1939         case '7':
1940         case '8':
1941         case '9':
1942         yes:
1943             return TRUE;
1944         default:
1945             break;
1946         }
1947     }
1948     return FALSE;
1949 }