FPTR2DPTR/DPTR2FPTR
[p5sagit/p5-mst-13.2.git] / pad.c
1 /*    pad.c
2  *
3  *    Copyright (C) 2002, 2003, 2004, 2005 by Larry Wall and others
4  *
5  *    You may distribute under the terms of either the GNU General Public
6  *    License or the Artistic License, as specified in the README file.
7  *
8  *  "Anyway: there was this Mr Frodo left an orphan and stranded, as you
9  *  might say, among those queer Bucklanders, being brought up anyhow in
10  *  Brandy Hall. A regular warren, by all accounts. Old Master Gorbadoc
11  *  never had fewer than a couple of hundred relations in the place. Mr
12  *  Bilbo never did a kinder deed than when he brought the lad back to
13  *  live among decent folk." --the Gaffer
14  */
15
16 /* XXX DAPM
17  * As of Sept 2002, this file is new and may be in a state of flux for
18  * a while. I've marked things I intent to come back and look at further
19  * with an 'XXX DAPM' comment.
20  */
21
22 /*
23 =head1 Pad Data Structures
24
25 This file contains the functions that create and manipulate scratchpads,
26 which are array-of-array data structures attached to a CV (ie a sub)
27 and which store lexical variables and opcode temporary and per-thread
28 values.
29
30 =for apidoc m|AV *|CvPADLIST|CV *cv
31 CV's can have CvPADLIST(cv) set to point to an AV.
32
33 For these purposes "forms" are a kind-of CV, eval""s are too (except they're
34 not callable at will and are always thrown away after the eval"" is done
35 executing). Require'd files are simply evals without any outer lexical
36 scope.
37
38 XSUBs don't have CvPADLIST set - dXSTARG fetches values from PL_curpad,
39 but that is really the callers pad (a slot of which is allocated by
40 every entersub).
41
42 The CvPADLIST AV has does not have AvREAL set, so REFCNT of component items
43 is managed "manual" (mostly in pad.c) rather than normal av.c rules.
44 The items in the AV are not SVs as for a normal AV, but other AVs:
45
46 0'th Entry of the CvPADLIST is an AV which represents the "names" or rather
47 the "static type information" for lexicals.
48
49 The CvDEPTH'th entry of CvPADLIST AV is an AV which is the stack frame at that
50 depth of recursion into the CV.
51 The 0'th slot of a frame AV is an AV which is @_.
52 other entries are storage for variables and op targets.
53
54 During compilation:
55 C<PL_comppad_name> is set to the names AV.
56 C<PL_comppad> is set to the frame AV for the frame CvDEPTH == 1.
57 C<PL_curpad> is set to the body of the frame AV (i.e. AvARRAY(PL_comppad)).
58
59 During execution, C<PL_comppad> and C<PL_curpad> refer to the live
60 frame of the currently executing sub.
61
62 Iterating over the names AV iterates over all possible pad
63 items. Pad slots that are SVs_PADTMP (targets/GVs/constants) end up having
64 &PL_sv_undef "names" (see pad_alloc()).
65
66 Only my/our variable (SVs_PADMY/SVs_PADOUR) slots get valid names.
67 The rest are op targets/GVs/constants which are statically allocated
68 or resolved at compile time.  These don't have names by which they
69 can be looked up from Perl code at run time through eval"" like
70 my/our variables can be.  Since they can't be looked up by "name"
71 but only by their index allocated at compile time (which is usually
72 in PL_op->op_targ), wasting a name SV for them doesn't make sense.
73
74 The SVs in the names AV have their PV being the name of the variable.
75 NV+1..IV inclusive is a range of cop_seq numbers for which the name is
76 valid.  For typed lexicals name SV is SVt_PVMG and SvSTASH points at the
77 type.  For C<our> lexicals, the type is SVt_PVGV, and GvSTASH points at the
78 stash of the associated global (so that duplicate C<our> delarations in the
79 same package can be detected).  SvCUR is sometimes hijacked to
80 store the generation number during compilation.
81
82 If SvFAKE is set on the name SV, then that slot in the frame AV is
83 a REFCNT'ed reference to a lexical from "outside". In this case,
84 the name SV does not use NVX and IVX to store a cop_seq range, since it is
85 in scope throughout. Instead IVX stores some flags containing info about
86 the real lexical (is it declared in an anon, and is it capable of being
87 instantiated multiple times?), and for fake ANONs, NVX contains the index
88 within the parent's pad where the lexical's value is stored, to make
89 cloning quicker.
90
91 If the 'name' is '&' the corresponding entry in frame AV
92 is a CV representing a possible closure.
93 (SvFAKE and name of '&' is not a meaningful combination currently but could
94 become so if C<my sub foo {}> is implemented.)
95
96 Note that formats are treated as anon subs, and are cloned each time
97 write is called (if necessary).
98
99 The flag SVf_PADSTALE is cleared on lexicals each time the my() is executed,
100 and set on scope exit. This allows the 'Variable $x is not available' warning
101 to be generated in evals, such as 
102
103     { my $x = 1; sub f { eval '$x'} } f();
104
105 =cut
106 */
107
108
109 #include "EXTERN.h"
110 #define PERL_IN_PAD_C
111 #include "perl.h"
112
113
114 #define PAD_MAX 999999999
115
116
117
118 /*
119 =for apidoc pad_new
120
121 Create a new compiling padlist, saving and updating the various global
122 vars at the same time as creating the pad itself. The following flags
123 can be OR'ed together:
124
125     padnew_CLONE        this pad is for a cloned CV
126     padnew_SAVE         save old globals
127     padnew_SAVESUB      also save extra stuff for start of sub
128
129 =cut
130 */
131
132 PADLIST *
133 Perl_pad_new(pTHX_ int flags)
134 {
135     AV *padlist, *padname, *pad;
136
137     ASSERT_CURPAD_LEGAL("pad_new");
138
139     /* XXX DAPM really need a new SAVEt_PAD which restores all or most
140      * vars (based on flags) rather than storing vals + addresses for
141      * each individually. Also see pad_block_start.
142      * XXX DAPM Try to see whether all these conditionals are required
143      */
144
145     /* save existing state, ... */
146
147     if (flags & padnew_SAVE) {
148         SAVECOMPPAD();
149         SAVESPTR(PL_comppad_name);
150         if (! (flags & padnew_CLONE)) {
151             SAVEI32(PL_padix);
152             SAVEI32(PL_comppad_name_fill);
153             SAVEI32(PL_min_intro_pending);
154             SAVEI32(PL_max_intro_pending);
155             SAVEI32(PL_cv_has_eval);
156             if (flags & padnew_SAVESUB) {
157                 SAVEI32(PL_pad_reset_pending);
158             }
159         }
160     }
161     /* XXX DAPM interestingly, PL_comppad_name_floor never seems to be
162      * saved - check at some pt that this is okay */
163
164     /* ... create new pad ... */
165
166     padlist     = newAV();
167     padname     = newAV();
168     pad         = newAV();
169
170     if (flags & padnew_CLONE) {
171         /* XXX DAPM  I dont know why cv_clone needs it
172          * doing differently yet - perhaps this separate branch can be
173          * dispensed with eventually ???
174          */
175
176         AV * const a0 = newAV();                        /* will be @_ */
177         av_extend(a0, 0);
178         av_store(pad, 0, (SV*)a0);
179         AvREIFY_only(a0);
180     }
181     else {
182         av_store(pad, 0, Nullsv);
183     }
184
185     AvREAL_off(padlist);
186     av_store(padlist, 0, (SV*)padname);
187     av_store(padlist, 1, (SV*)pad);
188
189     /* ... then update state variables */
190
191     PL_comppad_name     = (AV*)(*av_fetch(padlist, 0, FALSE));
192     PL_comppad          = (AV*)(*av_fetch(padlist, 1, FALSE));
193     PL_curpad           = AvARRAY(PL_comppad);
194
195     if (! (flags & padnew_CLONE)) {
196         PL_comppad_name_fill = 0;
197         PL_min_intro_pending = 0;
198         PL_padix             = 0;
199         PL_cv_has_eval       = 0;
200     }
201
202     DEBUG_X(PerlIO_printf(Perl_debug_log,
203           "Pad 0x%"UVxf"[0x%"UVxf"] new:       compcv=0x%"UVxf
204               " name=0x%"UVxf" flags=0x%"UVxf"\n",
205           PTR2UV(PL_comppad), PTR2UV(PL_curpad), PTR2UV(PL_compcv),
206               PTR2UV(padname), (UV)flags
207         )
208     );
209
210     return (PADLIST*)padlist;
211 }
212
213 /*
214 =for apidoc pad_undef
215
216 Free the padlist associated with a CV.
217 If parts of it happen to be current, we null the relevant
218 PL_*pad* global vars so that we don't have any dangling references left.
219 We also repoint the CvOUTSIDE of any about-to-be-orphaned
220 inner subs to the outer of this cv.
221
222 (This function should really be called pad_free, but the name was already
223 taken)
224
225 =cut
226 */
227
228 void
229 Perl_pad_undef(pTHX_ CV* cv)
230 {
231     I32 ix;
232     const PADLIST *padlist = CvPADLIST(cv);
233
234     if (!padlist)
235         return;
236     if (!SvREFCNT(CvPADLIST(cv))) /* may be during global destruction */
237         return;
238
239     DEBUG_X(PerlIO_printf(Perl_debug_log,
240           "Pad undef: cv=0x%"UVxf" padlist=0x%"UVxf"\n",
241             PTR2UV(cv), PTR2UV(padlist))
242     );
243
244     /* detach any '&' anon children in the pad; if afterwards they
245      * are still live, fix up their CvOUTSIDEs to point to our outside,
246      * bypassing us. */
247     /* XXX DAPM for efficiency, we should only do this if we know we have
248      * children, or integrate this loop with general cleanup */
249
250     if (!PL_dirty) { /* don't bother during global destruction */
251         CV * const outercv = CvOUTSIDE(cv);
252         const U32 seq = CvOUTSIDE_SEQ(cv);
253         AV *  const comppad_name = (AV*)AvARRAY(padlist)[0];
254         SV ** const namepad = AvARRAY(comppad_name);
255         AV *  const comppad = (AV*)AvARRAY(padlist)[1];
256         SV ** const curpad = AvARRAY(comppad);
257         for (ix = AvFILLp(comppad_name); ix > 0; ix--) {
258             SV * const namesv = namepad[ix];
259             if (namesv && namesv != &PL_sv_undef
260                 && *SvPVX_const(namesv) == '&')
261             {
262                 CV * const innercv = (CV*)curpad[ix];
263                 U32 inner_rc = SvREFCNT(innercv);
264                 assert(inner_rc);
265                 namepad[ix] = Nullsv;
266                 SvREFCNT_dec(namesv);
267
268                 if (SvREFCNT(comppad) < 2) { /* allow for /(?{ sub{} })/  */
269                     curpad[ix] = Nullsv;
270                     SvREFCNT_dec(innercv);
271                     inner_rc--;
272                 }
273                 if (inner_rc /* in use, not just a prototype */
274                     && CvOUTSIDE(innercv) == cv)
275                 {
276                     assert(CvWEAKOUTSIDE(innercv));
277                     /* don't relink to grandfather if he's being freed */
278                     if (outercv && SvREFCNT(outercv)) {
279                         CvWEAKOUTSIDE_off(innercv);
280                         CvOUTSIDE(innercv) = outercv;
281                         CvOUTSIDE_SEQ(innercv) = seq;
282                         (void)SvREFCNT_inc(outercv);
283                     }
284                     else {
285                         CvOUTSIDE(innercv) = Nullcv;
286                     }
287
288                 }
289
290             }
291         }
292     }
293
294     ix = AvFILLp(padlist);
295     while (ix >= 0) {
296         SV* const sv = AvARRAY(padlist)[ix--];
297         if (!sv)
298             continue;
299         if (sv == (SV*)PL_comppad_name)
300             PL_comppad_name = Nullav;
301         else if (sv == (SV*)PL_comppad) {
302             PL_comppad = Null(PAD*);
303             PL_curpad = Null(SV**);
304         }
305         SvREFCNT_dec(sv);
306     }
307     SvREFCNT_dec((SV*)CvPADLIST(cv));
308     CvPADLIST(cv) = Null(PADLIST*);
309 }
310
311
312
313
314 /*
315 =for apidoc pad_add_name
316
317 Create a new name and associated PADMY SV in the current pad; return the
318 offset.
319 If C<typestash> is valid, the name is for a typed lexical; set the
320 name's stash to that value.
321 If C<ourstash> is valid, it's an our lexical, set the name's
322 GvSTASH to that value
323
324 If fake, it means we're cloning an existing entry
325
326 =cut
327 */
328
329 PADOFFSET
330 Perl_pad_add_name(pTHX_ const char *name, HV* typestash, HV* ourstash, bool fake)
331 {
332     const PADOFFSET offset = pad_alloc(OP_PADSV, SVs_PADMY);
333     SV* const namesv = NEWSV(1102, 0);
334
335     ASSERT_CURPAD_ACTIVE("pad_add_name");
336
337
338     sv_upgrade(namesv, ourstash ? SVt_PVGV : typestash ? SVt_PVMG : SVt_PVNV);
339     sv_setpv(namesv, name);
340
341     if (typestash) {
342         SvFLAGS(namesv) |= SVpad_TYPED;
343         SvSTASH_set(namesv, (HV*)SvREFCNT_inc((SV*) typestash));
344     }
345     if (ourstash) {
346         SvFLAGS(namesv) |= SVpad_OUR;
347         GvSTASH(namesv) = (HV*)SvREFCNT_inc((SV*) ourstash);
348     }
349
350     av_store(PL_comppad_name, offset, namesv);
351     if (fake) {
352         SvFAKE_on(namesv);
353         DEBUG_Xv(PerlIO_printf(Perl_debug_log,
354             "Pad addname: %ld \"%s\" FAKE\n", (long)offset, name));
355     }
356     else {
357         /* not yet introduced */
358         SvNV_set(namesv, (NV)PAD_MAX);  /* min */
359         SvIV_set(namesv, 0);            /* max */
360
361         if (!PL_min_intro_pending)
362             PL_min_intro_pending = offset;
363         PL_max_intro_pending = offset;
364         /* if it's not a simple scalar, replace with an AV or HV */
365         /* XXX DAPM since slot has been allocated, replace
366          * av_store with PL_curpad[offset] ? */
367         if (*name == '@')
368             av_store(PL_comppad, offset, (SV*)newAV());
369         else if (*name == '%')
370             av_store(PL_comppad, offset, (SV*)newHV());
371         SvPADMY_on(PL_curpad[offset]);
372         DEBUG_Xv(PerlIO_printf(Perl_debug_log,
373             "Pad addname: %ld \"%s\" new lex=0x%"UVxf"\n",
374             (long)offset, name, PTR2UV(PL_curpad[offset])));
375     }
376
377     return offset;
378 }
379
380
381
382
383 /*
384 =for apidoc pad_alloc
385
386 Allocate a new my or tmp pad entry. For a my, simply push a null SV onto
387 the end of PL_comppad, but for a tmp, scan the pad from PL_padix upwards
388 for a slot which has no name and and no active value.
389
390 =cut
391 */
392
393 /* XXX DAPM integrate alloc(), add_name() and add_anon(),
394  * or at least rationalise ??? */
395
396
397 PADOFFSET
398 Perl_pad_alloc(pTHX_ I32 optype, U32 tmptype)
399 {
400     SV *sv;
401     I32 retval;
402
403     ASSERT_CURPAD_ACTIVE("pad_alloc");
404
405     if (AvARRAY(PL_comppad) != PL_curpad)
406         Perl_croak(aTHX_ "panic: pad_alloc");
407     if (PL_pad_reset_pending)
408         pad_reset();
409     if (tmptype & SVs_PADMY) {
410         sv = *av_fetch(PL_comppad, AvFILLp(PL_comppad) + 1, TRUE);
411         retval = AvFILLp(PL_comppad);
412     }
413     else {
414         SV ** const names = AvARRAY(PL_comppad_name);
415         const SSize_t names_fill = AvFILLp(PL_comppad_name);
416         for (;;) {
417             /*
418              * "foreach" index vars temporarily become aliases to non-"my"
419              * values.  Thus we must skip, not just pad values that are
420              * marked as current pad values, but also those with names.
421              */
422             /* HVDS why copy to sv here? we don't seem to use it */
423             if (++PL_padix <= names_fill &&
424                    (sv = names[PL_padix]) && sv != &PL_sv_undef)
425                 continue;
426             sv = *av_fetch(PL_comppad, PL_padix, TRUE);
427             if (!(SvFLAGS(sv) & (SVs_PADTMP | SVs_PADMY)) &&
428                 !IS_PADGV(sv) && !IS_PADCONST(sv))
429                 break;
430         }
431         retval = PL_padix;
432     }
433     SvFLAGS(sv) |= tmptype;
434     PL_curpad = AvARRAY(PL_comppad);
435
436     DEBUG_X(PerlIO_printf(Perl_debug_log,
437           "Pad 0x%"UVxf"[0x%"UVxf"] alloc:   %ld for %s\n",
438           PTR2UV(PL_comppad), PTR2UV(PL_curpad), (long) retval,
439           PL_op_name[optype]));
440 #ifdef DEBUG_LEAKING_SCALARS
441     sv->sv_debug_optype = optype;
442     sv->sv_debug_inpad = 1;
443 #endif
444     return (PADOFFSET)retval;
445 }
446
447 /*
448 =for apidoc pad_add_anon
449
450 Add an anon code entry to the current compiling pad
451
452 =cut
453 */
454
455 PADOFFSET
456 Perl_pad_add_anon(pTHX_ SV* sv, OPCODE op_type)
457 {
458     PADOFFSET ix;
459     SV* name;
460
461     name = NEWSV(1106, 0);
462     sv_upgrade(name, SVt_PVNV);
463     sv_setpvn(name, "&", 1);
464     SvIV_set(name, -1);
465     SvNV_set(name, 1);
466     ix = pad_alloc(op_type, SVs_PADMY);
467     av_store(PL_comppad_name, ix, name);
468     /* XXX DAPM use PL_curpad[] ? */
469     av_store(PL_comppad, ix, sv);
470     SvPADMY_on(sv);
471
472     /* to avoid ref loops, we never have parent + child referencing each
473      * other simultaneously */
474     if (CvOUTSIDE((CV*)sv)) {
475         assert(!CvWEAKOUTSIDE((CV*)sv));
476         CvWEAKOUTSIDE_on((CV*)sv);
477         SvREFCNT_dec(CvOUTSIDE((CV*)sv));
478     }
479     return ix;
480 }
481
482
483
484 /*
485 =for apidoc pad_check_dup
486
487 Check for duplicate declarations: report any of:
488      * a my in the current scope with the same name;
489      * an our (anywhere in the pad) with the same name and the same stash
490        as C<ourstash>
491 C<is_our> indicates that the name to check is an 'our' declaration
492
493 =cut
494 */
495
496 /* XXX DAPM integrate this into pad_add_name ??? */
497
498 void
499 Perl_pad_check_dup(pTHX_ const char *name, bool is_our, const HV *ourstash)
500 {
501     SV          **svp;
502     PADOFFSET   top, off;
503
504     ASSERT_CURPAD_ACTIVE("pad_check_dup");
505     if (!ckWARN(WARN_MISC) || AvFILLp(PL_comppad_name) < 0)
506         return; /* nothing to check */
507
508     svp = AvARRAY(PL_comppad_name);
509     top = AvFILLp(PL_comppad_name);
510     /* check the current scope */
511     /* XXX DAPM - why the (I32) cast - shouldn't we ensure they're the same
512      * type ? */
513     for (off = top; (I32)off > PL_comppad_name_floor; off--) {
514         SV * const sv = svp[off];
515         if (sv
516             && sv != &PL_sv_undef
517             && !SvFAKE(sv)
518             && (SvIVX(sv) == PAD_MAX || SvIVX(sv) == 0)
519             && (!is_our
520                 || ((SvFLAGS(sv) & SVpad_OUR) && GvSTASH(sv) == ourstash))
521             && strEQ(name, SvPVX_const(sv)))
522         {
523             Perl_warner(aTHX_ packWARN(WARN_MISC),
524                 "\"%s\" variable %s masks earlier declaration in same %s",
525                 (is_our ? "our" : "my"),
526                 name,
527                 (SvIVX(sv) == PAD_MAX ? "scope" : "statement"));
528             --off;
529             break;
530         }
531     }
532     /* check the rest of the pad */
533     if (is_our) {
534         do {
535             SV * const sv = svp[off];
536             if (sv
537                 && sv != &PL_sv_undef
538                 && !SvFAKE(sv)
539                 && (SvIVX(sv) == PAD_MAX || SvIVX(sv) == 0)
540                 && ((SvFLAGS(sv) & SVpad_OUR) && GvSTASH(sv) == ourstash)
541                 && strEQ(name, SvPVX_const(sv)))
542             {
543                 Perl_warner(aTHX_ packWARN(WARN_MISC),
544                     "\"our\" variable %s redeclared", name);
545                 Perl_warner(aTHX_ packWARN(WARN_MISC),
546                     "\t(Did you mean \"local\" instead of \"our\"?)\n");
547                 break;
548             }
549         } while ( off-- > 0 );
550     }
551 }
552
553
554 /*
555 =for apidoc pad_findmy
556
557 Given a lexical name, try to find its offset, first in the current pad,
558 or failing that, in the pads of any lexically enclosing subs (including
559 the complications introduced by eval). If the name is found in an outer pad,
560 then a fake entry is added to the current pad.
561 Returns the offset in the current pad, or NOT_IN_PAD on failure.
562
563 =cut
564 */
565
566 PADOFFSET
567 Perl_pad_findmy(pTHX_ const char *name)
568 {
569     SV *out_sv;
570     int out_flags;
571     I32 offset;
572     const AV *nameav;
573     SV **name_svp;
574
575     offset =  pad_findlex(name, PL_compcv, PL_cop_seqmax, 1,
576                 Null(SV**), &out_sv, &out_flags);
577     if (offset != NOT_IN_PAD) 
578         return offset;
579
580     /* look for an our that's being introduced; this allows
581      *    our $foo = 0 unless defined $foo;
582      * to not give a warning. (Yes, this is a hack) */
583
584     nameav = (AV*)AvARRAY(CvPADLIST(PL_compcv))[0];
585     name_svp = AvARRAY(nameav);
586     for (offset = AvFILLp(nameav); offset > 0; offset--) {
587         const SV *namesv = name_svp[offset];
588         if (namesv && namesv != &PL_sv_undef
589             && !SvFAKE(namesv)
590             && (SvFLAGS(namesv) & SVpad_OUR)
591             && strEQ(SvPVX_const(namesv), name)
592             && U_32(SvNVX(namesv)) == PAD_MAX /* min */
593         )
594             return offset;
595     }
596     return NOT_IN_PAD;
597 }
598
599 /*
600  * Returns the offset of a lexical $_, if there is one, at run time.
601  * Used by the UNDERBAR XS macro.
602  */
603
604 PADOFFSET
605 Perl_find_rundefsvoffset(pTHX)
606 {
607     SV *out_sv;
608     int out_flags;
609     return pad_findlex("$_", find_runcv(NULL), PL_curcop->cop_seq, 1,
610             Null(SV**), &out_sv, &out_flags);
611 }
612
613 /*
614 =for apidoc pad_findlex
615
616 Find a named lexical anywhere in a chain of nested pads. Add fake entries
617 in the inner pads if it's found in an outer one.
618
619 Returns the offset in the bottom pad of the lex or the fake lex.
620 cv is the CV in which to start the search, and seq is the current cop_seq
621 to match against. If warn is true, print appropriate warnings.  The out_*
622 vars return values, and so are pointers to where the returned values
623 should be stored. out_capture, if non-null, requests that the innermost
624 instance of the lexical is captured; out_name_sv is set to the innermost
625 matched namesv or fake namesv; out_flags returns the flags normally
626 associated with the IVX field of a fake namesv.
627
628 Note that pad_findlex() is recursive; it recurses up the chain of CVs,
629 then comes back down, adding fake entries as it goes. It has to be this way
630 because fake namesvs in anon protoypes have to store in NVX the index into
631 the parent pad.
632
633 =cut
634 */
635
636 /* Flags set in the SvIVX field of FAKE namesvs */
637
638 #define PAD_FAKELEX_ANON   1 /* the lex is declared in an ANON, or ... */
639 #define PAD_FAKELEX_MULTI  2 /* the lex can be instantiated multiple times */
640
641 /* the CV has finished being compiled. This is not a sufficient test for
642  * all CVs (eg XSUBs), but suffices for the CVs found in a lexical chain */
643 #define CvCOMPILED(cv)  CvROOT(cv)
644
645 /* the CV does late binding of its lexicals */
646 #define CvLATE(cv) (CvANON(cv) || SvTYPE(cv) == SVt_PVFM)
647
648
649 STATIC PADOFFSET
650 S_pad_findlex(pTHX_ const char *name, const CV* cv, U32 seq, int warn,
651         SV** out_capture, SV** out_name_sv, int *out_flags)
652 {
653     I32 offset, new_offset;
654     SV *new_capture;
655     SV **new_capturep;
656     const AV *padlist = CvPADLIST(cv);
657
658     *out_flags = 0;
659
660     DEBUG_Xv(PerlIO_printf(Perl_debug_log,
661         "Pad findlex cv=0x%"UVxf" searching \"%s\" seq=%d%s\n",
662         PTR2UV(cv), name, (int)seq, out_capture ? " capturing" : "" ));
663
664     /* first, search this pad */
665
666     if (padlist) { /* not an undef CV */
667         I32 fake_offset = 0;
668         const AV *nameav = (AV*)AvARRAY(padlist)[0];
669         SV **name_svp = AvARRAY(nameav);
670
671         for (offset = AvFILLp(nameav); offset > 0; offset--) {
672             const SV *namesv = name_svp[offset];
673             if (namesv && namesv != &PL_sv_undef
674                     && strEQ(SvPVX_const(namesv), name))
675             {
676                 if (SvFAKE(namesv))
677                     fake_offset = offset; /* in case we don't find a real one */
678                 else if (  seq >  U_32(SvNVX(namesv))   /* min */
679                         && seq <= (U32)SvIVX(namesv))   /* max */
680                     break;
681             }
682         }
683
684         if (offset > 0 || fake_offset > 0 ) { /* a match! */
685             if (offset > 0) { /* not fake */
686                 fake_offset = 0;
687                 *out_name_sv = name_svp[offset]; /* return the namesv */
688
689                 /* set PAD_FAKELEX_MULTI if this lex can have multiple
690                  * instances. For now, we just test !CvUNIQUE(cv), but
691                  * ideally, we should detect my's declared within loops
692                  * etc - this would allow a wider range of 'not stayed
693                  * shared' warnings. We also treated alreadly-compiled
694                  * lexes as not multi as viewed from evals. */
695
696                 *out_flags = CvANON(cv) ?
697                         PAD_FAKELEX_ANON :
698                             (!CvUNIQUE(cv) && ! CvCOMPILED(cv))
699                                 ? PAD_FAKELEX_MULTI : 0;
700
701                 DEBUG_Xv(PerlIO_printf(Perl_debug_log,
702                     "Pad findlex cv=0x%"UVxf" matched: offset=%ld (%ld,%ld)\n",
703                     PTR2UV(cv), (long)offset, (long)U_32(SvNVX(*out_name_sv)),
704                     (long)SvIVX(*out_name_sv)));
705             }
706             else { /* fake match */
707                 offset = fake_offset;
708                 *out_name_sv = name_svp[offset]; /* return the namesv */
709                 *out_flags = SvIVX(*out_name_sv);
710                 DEBUG_Xv(PerlIO_printf(Perl_debug_log,
711                     "Pad findlex cv=0x%"UVxf" matched: offset=%ld flags=0x%lx index=%lu\n",
712                     PTR2UV(cv), (long)offset, (unsigned long)*out_flags,
713                         (unsigned long)SvNVX(*out_name_sv) 
714                 ));
715             }
716
717             /* return the lex? */
718
719             if (out_capture) {
720
721                 /* our ? */
722                 if ((SvFLAGS(*out_name_sv) & SVpad_OUR)) {
723                     *out_capture = Nullsv;
724                     return offset;
725                 }
726
727                 /* trying to capture from an anon prototype? */
728                 if (CvCOMPILED(cv)
729                         ? CvANON(cv) && CvCLONE(cv) && !CvCLONED(cv)
730                         : *out_flags & PAD_FAKELEX_ANON)
731                 {
732                     if (warn && ckWARN(WARN_CLOSURE))
733                         Perl_warner(aTHX_ packWARN(WARN_CLOSURE),
734                             "Variable \"%s\" is not available", name);
735                     *out_capture = Nullsv;
736                 }
737
738                 /* real value */
739                 else {
740                     int newwarn = warn;
741                     if (!CvCOMPILED(cv) && (*out_flags & PAD_FAKELEX_MULTI)
742                          && warn && ckWARN(WARN_CLOSURE)) {
743                         newwarn = 0;
744                         Perl_warner(aTHX_ packWARN(WARN_CLOSURE),
745                             "Variable \"%s\" will not stay shared", name);
746                     }
747
748                     if (fake_offset && CvANON(cv)
749                             && CvCLONE(cv) &&!CvCLONED(cv))
750                     {
751                         SV *n;
752                         /* not yet caught - look further up */
753                         DEBUG_Xv(PerlIO_printf(Perl_debug_log,
754                             "Pad findlex cv=0x%"UVxf" chasing lex in outer pad\n",
755                             PTR2UV(cv)));
756                         n = *out_name_sv;
757                         pad_findlex(name, CvOUTSIDE(cv), CvOUTSIDE_SEQ(cv),
758                             newwarn, out_capture, out_name_sv, out_flags);
759                         *out_name_sv = n;
760                         return offset;
761                     }
762
763                     *out_capture = AvARRAY((AV*)AvARRAY(padlist)[
764                                     CvDEPTH(cv) ? CvDEPTH(cv) : 1])[offset];
765                     DEBUG_Xv(PerlIO_printf(Perl_debug_log,
766                         "Pad findlex cv=0x%"UVxf" found lex=0x%"UVxf"\n",
767                         PTR2UV(cv), PTR2UV(*out_capture)));
768
769                     if (SvPADSTALE(*out_capture)) {
770                         if (ckWARN(WARN_CLOSURE))
771                             Perl_warner(aTHX_ packWARN(WARN_CLOSURE),
772                                 "Variable \"%s\" is not available", name);
773                         *out_capture = Nullsv;
774                     }
775                 }
776                 if (!*out_capture) {
777                     if (*name == '@')
778                         *out_capture = sv_2mortal((SV*)newAV());
779                     else if (*name == '%')
780                         *out_capture = sv_2mortal((SV*)newHV());
781                     else
782                         *out_capture = sv_newmortal();
783                 }
784             }
785
786             return offset;
787         }
788     }
789
790     /* it's not in this pad - try above */
791
792     if (!CvOUTSIDE(cv))
793         return NOT_IN_PAD;
794     
795     /* out_capture non-null means caller wants us to capture lex; in
796      * addition we capture ourselves unless it's an ANON/format */
797     new_capturep = out_capture ? out_capture :
798                 CvLATE(cv) ? Null(SV**) : &new_capture;
799
800     offset = pad_findlex(name, CvOUTSIDE(cv), CvOUTSIDE_SEQ(cv), 1,
801                 new_capturep, out_name_sv, out_flags);
802     if (offset == NOT_IN_PAD)
803         return NOT_IN_PAD;
804     
805     /* found in an outer CV. Add appropriate fake entry to this pad */
806
807     /* don't add new fake entries (via eval) to CVs that we have already
808      * finished compiling, or to undef CVs */
809     if (CvCOMPILED(cv) || !padlist)
810         return 0; /* this dummy (and invalid) value isnt used by the caller */
811
812     {
813         SV *new_namesv;
814         AV *  const ocomppad_name = PL_comppad_name;
815         PAD * const ocomppad = PL_comppad;
816         PL_comppad_name = (AV*)AvARRAY(padlist)[0];
817         PL_comppad = (AV*)AvARRAY(padlist)[1];
818         PL_curpad = AvARRAY(PL_comppad);
819
820         new_offset = pad_add_name(
821             SvPVX_const(*out_name_sv),
822             (SvFLAGS(*out_name_sv) & SVpad_TYPED)
823                     ? SvSTASH(*out_name_sv) : Nullhv,
824             (SvFLAGS(*out_name_sv) & SVpad_OUR)
825                     ? GvSTASH(*out_name_sv) : Nullhv,
826             1  /* fake */
827         );
828
829         new_namesv = AvARRAY(PL_comppad_name)[new_offset];
830         SvIV_set(new_namesv, *out_flags);
831
832         SvNV_set(new_namesv, (NV)0);
833         if (SvFLAGS(new_namesv) & SVpad_OUR) {
834            /* do nothing */
835         }
836         else if (CvLATE(cv)) {
837             /* delayed creation - just note the offset within parent pad */
838             SvNV_set(new_namesv, (NV)offset);
839             CvCLONE_on(cv);
840         }
841         else {
842             /* immediate creation - capture outer value right now */
843             av_store(PL_comppad, new_offset, SvREFCNT_inc(*new_capturep));
844             DEBUG_Xv(PerlIO_printf(Perl_debug_log,
845                 "Pad findlex cv=0x%"UVxf" saved captured sv 0x%"UVxf" at offset %ld\n",
846                 PTR2UV(cv), PTR2UV(*new_capturep), (long)new_offset));
847         }
848         *out_name_sv = new_namesv;
849         *out_flags = SvIVX(new_namesv);
850
851         PL_comppad_name = ocomppad_name;
852         PL_comppad = ocomppad;
853         PL_curpad = ocomppad ? AvARRAY(ocomppad) : Null(SV **);
854     }
855     return new_offset;
856 }
857
858                 
859 /*
860 =for apidoc pad_sv
861
862 Get the value at offset po in the current pad.
863 Use macro PAD_SV instead of calling this function directly.
864
865 =cut
866 */
867
868
869 SV *
870 Perl_pad_sv(pTHX_ PADOFFSET po)
871 {
872     ASSERT_CURPAD_ACTIVE("pad_sv");
873
874     if (!po)
875         Perl_croak(aTHX_ "panic: pad_sv po");
876     DEBUG_X(PerlIO_printf(Perl_debug_log,
877         "Pad 0x%"UVxf"[0x%"UVxf"] sv:      %ld sv=0x%"UVxf"\n",
878         PTR2UV(PL_comppad), PTR2UV(PL_curpad), (long)po, PTR2UV(PL_curpad[po]))
879     );
880     return PL_curpad[po];
881 }
882
883
884 /*
885 =for apidoc pad_setsv
886
887 Set the entry at offset po in the current pad to sv.
888 Use the macro PAD_SETSV() rather than calling this function directly.
889
890 =cut
891 */
892
893 #ifdef DEBUGGING
894 void
895 Perl_pad_setsv(pTHX_ PADOFFSET po, SV* sv)
896 {
897     ASSERT_CURPAD_ACTIVE("pad_setsv");
898
899     DEBUG_X(PerlIO_printf(Perl_debug_log,
900         "Pad 0x%"UVxf"[0x%"UVxf"] setsv:   %ld sv=0x%"UVxf"\n",
901         PTR2UV(PL_comppad), PTR2UV(PL_curpad), (long)po, PTR2UV(sv))
902     );
903     PL_curpad[po] = sv;
904 }
905 #endif
906
907
908
909 /*
910 =for apidoc pad_block_start
911
912 Update the pad compilation state variables on entry to a new block
913
914 =cut
915 */
916
917 /* XXX DAPM perhaps:
918  *      - integrate this in general state-saving routine ???
919  *      - combine with the state-saving going on in pad_new ???
920  *      - introduce a new SAVE type that does all this in one go ?
921  */
922
923 void
924 Perl_pad_block_start(pTHX_ int full)
925 {
926     ASSERT_CURPAD_ACTIVE("pad_block_start");
927     SAVEI32(PL_comppad_name_floor);
928     PL_comppad_name_floor = AvFILLp(PL_comppad_name);
929     if (full)
930         PL_comppad_name_fill = PL_comppad_name_floor;
931     if (PL_comppad_name_floor < 0)
932         PL_comppad_name_floor = 0;
933     SAVEI32(PL_min_intro_pending);
934     SAVEI32(PL_max_intro_pending);
935     PL_min_intro_pending = 0;
936     SAVEI32(PL_comppad_name_fill);
937     SAVEI32(PL_padix_floor);
938     PL_padix_floor = PL_padix;
939     PL_pad_reset_pending = FALSE;
940 }
941
942
943 /*
944 =for apidoc intro_my
945
946 "Introduce" my variables to visible status.
947
948 =cut
949 */
950
951 U32
952 Perl_intro_my(pTHX)
953 {
954     SV **svp;
955     I32 i;
956
957     ASSERT_CURPAD_ACTIVE("intro_my");
958     if (! PL_min_intro_pending)
959         return PL_cop_seqmax;
960
961     svp = AvARRAY(PL_comppad_name);
962     for (i = PL_min_intro_pending; i <= PL_max_intro_pending; i++) {
963         SV * const sv = svp[i];
964
965         if (sv && sv != &PL_sv_undef && !SvFAKE(sv) && !SvIVX(sv)) {
966             SvIV_set(sv, PAD_MAX);      /* Don't know scope end yet. */
967             SvNV_set(sv, (NV)PL_cop_seqmax);
968             DEBUG_Xv(PerlIO_printf(Perl_debug_log,
969                 "Pad intromy: %ld \"%s\", (%ld,%ld)\n",
970                 (long)i, SvPVX_const(sv),
971                 (long)U_32(SvNVX(sv)), (long)SvIVX(sv))
972             );
973         }
974     }
975     PL_min_intro_pending = 0;
976     PL_comppad_name_fill = PL_max_intro_pending; /* Needn't search higher */
977     DEBUG_Xv(PerlIO_printf(Perl_debug_log,
978                 "Pad intromy: seq -> %ld\n", (long)(PL_cop_seqmax+1)));
979
980     return PL_cop_seqmax++;
981 }
982
983 /*
984 =for apidoc pad_leavemy
985
986 Cleanup at end of scope during compilation: set the max seq number for
987 lexicals in this scope and warn of any lexicals that never got introduced.
988
989 =cut
990 */
991
992 void
993 Perl_pad_leavemy(pTHX)
994 {
995     I32 off;
996     SV ** const svp = AvARRAY(PL_comppad_name);
997
998     PL_pad_reset_pending = FALSE;
999
1000     ASSERT_CURPAD_ACTIVE("pad_leavemy");
1001     if (PL_min_intro_pending && PL_comppad_name_fill < PL_min_intro_pending) {
1002         for (off = PL_max_intro_pending; off >= PL_min_intro_pending; off--) {
1003             const SV * const sv = svp[off];
1004             if (sv && sv != &PL_sv_undef
1005                     && !SvFAKE(sv) && ckWARN_d(WARN_INTERNAL))
1006                 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
1007                                         "%"SVf" never introduced", sv);
1008         }
1009     }
1010     /* "Deintroduce" my variables that are leaving with this scope. */
1011     for (off = AvFILLp(PL_comppad_name); off > PL_comppad_name_fill; off--) {
1012         const SV * const sv = svp[off];
1013         if (sv && sv != &PL_sv_undef && !SvFAKE(sv) && SvIVX(sv) == PAD_MAX) {
1014             SvIV_set(sv, PL_cop_seqmax);
1015             DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1016                 "Pad leavemy: %ld \"%s\", (%ld,%ld)\n",
1017                 (long)off, SvPVX_const(sv),
1018                 (long)U_32(SvNVX(sv)), (long)SvIVX(sv))
1019             );
1020         }
1021     }
1022     PL_cop_seqmax++;
1023     DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1024             "Pad leavemy: seq = %ld\n", (long)PL_cop_seqmax));
1025 }
1026
1027
1028 /*
1029 =for apidoc pad_swipe
1030
1031 Abandon the tmp in the current pad at offset po and replace with a
1032 new one.
1033
1034 =cut
1035 */
1036
1037 void
1038 Perl_pad_swipe(pTHX_ PADOFFSET po, bool refadjust)
1039 {
1040     ASSERT_CURPAD_LEGAL("pad_swipe");
1041     if (!PL_curpad)
1042         return;
1043     if (AvARRAY(PL_comppad) != PL_curpad)
1044         Perl_croak(aTHX_ "panic: pad_swipe curpad");
1045     if (!po)
1046         Perl_croak(aTHX_ "panic: pad_swipe po");
1047
1048     DEBUG_X(PerlIO_printf(Perl_debug_log,
1049                 "Pad 0x%"UVxf"[0x%"UVxf"] swipe:   %ld\n",
1050                 PTR2UV(PL_comppad), PTR2UV(PL_curpad), (long)po));
1051
1052     if (PL_curpad[po])
1053         SvPADTMP_off(PL_curpad[po]);
1054     if (refadjust)
1055         SvREFCNT_dec(PL_curpad[po]);
1056
1057     PL_curpad[po] = NEWSV(1107,0);
1058     SvPADTMP_on(PL_curpad[po]);
1059     if ((I32)po < PL_padix)
1060         PL_padix = po - 1;
1061 }
1062
1063
1064 /*
1065 =for apidoc pad_reset
1066
1067 Mark all the current temporaries for reuse
1068
1069 =cut
1070 */
1071
1072 /* XXX pad_reset() is currently disabled because it results in serious bugs.
1073  * It causes pad temp TARGs to be shared between OPs. Since TARGs are pushed
1074  * on the stack by OPs that use them, there are several ways to get an alias
1075  * to  a shared TARG.  Such an alias will change randomly and unpredictably.
1076  * We avoid doing this until we can think of a Better Way.
1077  * GSAR 97-10-29 */
1078 void
1079 Perl_pad_reset(pTHX)
1080 {
1081 #ifdef USE_BROKEN_PAD_RESET
1082     if (AvARRAY(PL_comppad) != PL_curpad)
1083         Perl_croak(aTHX_ "panic: pad_reset curpad");
1084
1085     DEBUG_X(PerlIO_printf(Perl_debug_log,
1086             "Pad 0x%"UVxf"[0x%"UVxf"] reset:     padix %ld -> %ld",
1087             PTR2UV(PL_comppad), PTR2UV(PL_curpad),
1088                 (long)PL_padix, (long)PL_padix_floor
1089             )
1090     );
1091
1092     if (!PL_tainting) { /* Can't mix tainted and non-tainted temporaries. */
1093         register I32 po;
1094         for (po = AvMAX(PL_comppad); po > PL_padix_floor; po--) {
1095             if (PL_curpad[po] && !SvIMMORTAL(PL_curpad[po]))
1096                 SvPADTMP_off(PL_curpad[po]);
1097         }
1098         PL_padix = PL_padix_floor;
1099     }
1100 #endif
1101     PL_pad_reset_pending = FALSE;
1102 }
1103
1104
1105 /*
1106 =for apidoc pad_tidy
1107
1108 Tidy up a pad after we've finished compiling it:
1109     * remove most stuff from the pads of anonsub prototypes;
1110     * give it a @_;
1111     * mark tmps as such.
1112
1113 =cut
1114 */
1115
1116 /* XXX DAPM surely most of this stuff should be done properly
1117  * at the right time beforehand, rather than going around afterwards
1118  * cleaning up our mistakes ???
1119  */
1120
1121 void
1122 Perl_pad_tidy(pTHX_ padtidy_type type)
1123 {
1124     dVAR;
1125
1126     ASSERT_CURPAD_ACTIVE("pad_tidy");
1127
1128     /* If this CV has had any 'eval-capable' ops planted in it
1129      * (ie it contains eval '...', //ee, /$var/ or /(?{..})/), Then any
1130      * anon prototypes in the chain of CVs should be marked as cloneable,
1131      * so that for example the eval's CV in C<< sub { eval '$x' } >> gets
1132      * the right CvOUTSIDE.
1133      * If running with -d, *any* sub may potentially have an eval
1134      * excuted within it.
1135      */
1136
1137     if (PL_cv_has_eval || PL_perldb) {
1138         const CV *cv;
1139         for (cv = PL_compcv ;cv; cv = CvOUTSIDE(cv)) {
1140             if (cv != PL_compcv && CvCOMPILED(cv))
1141                 break; /* no need to mark already-compiled code */
1142             if (CvANON(cv)) {
1143                 DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1144                     "Pad clone on cv=0x%"UVxf"\n", PTR2UV(cv)));
1145                 CvCLONE_on(cv);
1146             }
1147         }
1148     }
1149
1150     /* extend curpad to match namepad */
1151     if (AvFILLp(PL_comppad_name) < AvFILLp(PL_comppad))
1152         av_store(PL_comppad_name, AvFILLp(PL_comppad), Nullsv);
1153
1154     if (type == padtidy_SUBCLONE) {
1155         SV ** const namep = AvARRAY(PL_comppad_name);
1156         PADOFFSET ix;
1157
1158         for (ix = AvFILLp(PL_comppad); ix > 0; ix--) {
1159             SV *namesv;
1160
1161             if (SvIMMORTAL(PL_curpad[ix]) || IS_PADGV(PL_curpad[ix]) || IS_PADCONST(PL_curpad[ix]))
1162                 continue;
1163             /*
1164              * The only things that a clonable function needs in its
1165              * pad are anonymous subs.
1166              * The rest are created anew during cloning.
1167              */
1168             if (!((namesv = namep[ix]) != Nullsv &&
1169                   namesv != &PL_sv_undef &&
1170                    *SvPVX_const(namesv) == '&'))
1171             {
1172                 SvREFCNT_dec(PL_curpad[ix]);
1173                 PL_curpad[ix] = Nullsv;
1174             }
1175         }
1176     }
1177     else if (type == padtidy_SUB) {
1178         /* XXX DAPM this same bit of code keeps appearing !!! Rationalise? */
1179         AV * const av = newAV();                        /* Will be @_ */
1180         av_extend(av, 0);
1181         av_store(PL_comppad, 0, (SV*)av);
1182         AvREIFY_only(av);
1183     }
1184
1185     /* XXX DAPM rationalise these two similar branches */
1186
1187     if (type == padtidy_SUB) {
1188         PADOFFSET ix;
1189         for (ix = AvFILLp(PL_comppad); ix > 0; ix--) {
1190             if (SvIMMORTAL(PL_curpad[ix]) || IS_PADGV(PL_curpad[ix]) || IS_PADCONST(PL_curpad[ix]))
1191                 continue;
1192             if (!SvPADMY(PL_curpad[ix]))
1193                 SvPADTMP_on(PL_curpad[ix]);
1194         }
1195     }
1196     else if (type == padtidy_FORMAT) {
1197         PADOFFSET ix;
1198         for (ix = AvFILLp(PL_comppad); ix > 0; ix--) {
1199             if (!SvPADMY(PL_curpad[ix]) && !SvIMMORTAL(PL_curpad[ix]))
1200                 SvPADTMP_on(PL_curpad[ix]);
1201         }
1202     }
1203     PL_curpad = AvARRAY(PL_comppad);
1204 }
1205
1206
1207 /*
1208 =for apidoc pad_free
1209
1210 Free the SV at offet po in the current pad.
1211
1212 =cut
1213 */
1214
1215 /* XXX DAPM integrate with pad_swipe ???? */
1216 void
1217 Perl_pad_free(pTHX_ PADOFFSET po)
1218 {
1219     ASSERT_CURPAD_LEGAL("pad_free");
1220     if (!PL_curpad)
1221         return;
1222     if (AvARRAY(PL_comppad) != PL_curpad)
1223         Perl_croak(aTHX_ "panic: pad_free curpad");
1224     if (!po)
1225         Perl_croak(aTHX_ "panic: pad_free po");
1226
1227     DEBUG_X(PerlIO_printf(Perl_debug_log,
1228             "Pad 0x%"UVxf"[0x%"UVxf"] free:    %ld\n",
1229             PTR2UV(PL_comppad), PTR2UV(PL_curpad), (long)po)
1230     );
1231
1232     if (PL_curpad[po] && PL_curpad[po] != &PL_sv_undef) {
1233         SvPADTMP_off(PL_curpad[po]);
1234 #ifdef USE_ITHREADS
1235         /* SV could be a shared hash key (eg bugid #19022) */
1236         if (
1237 #ifdef PERL_OLD_COPY_ON_WRITE
1238             !SvIsCOW(PL_curpad[po])
1239 #else
1240             !SvFAKE(PL_curpad[po])
1241 #endif
1242             )
1243             SvREADONLY_off(PL_curpad[po]);      /* could be a freed constant */
1244 #endif
1245     }
1246     if ((I32)po < PL_padix)
1247         PL_padix = po - 1;
1248 }
1249
1250
1251
1252 /*
1253 =for apidoc do_dump_pad
1254
1255 Dump the contents of a padlist
1256
1257 =cut
1258 */
1259
1260 void
1261 Perl_do_dump_pad(pTHX_ I32 level, PerlIO *file, PADLIST *padlist, int full)
1262 {
1263     const AV *pad_name;
1264     const AV *pad;
1265     SV **pname;
1266     SV **ppad;
1267     I32 ix;
1268
1269     if (!padlist) {
1270         return;
1271     }
1272     pad_name = (AV*)*av_fetch((AV*)padlist, 0, FALSE);
1273     pad = (AV*)*av_fetch((AV*)padlist, 1, FALSE);
1274     pname = AvARRAY(pad_name);
1275     ppad = AvARRAY(pad);
1276     Perl_dump_indent(aTHX_ level, file,
1277             "PADNAME = 0x%"UVxf"(0x%"UVxf") PAD = 0x%"UVxf"(0x%"UVxf")\n",
1278             PTR2UV(pad_name), PTR2UV(pname), PTR2UV(pad), PTR2UV(ppad)
1279     );
1280
1281     for (ix = 1; ix <= AvFILLp(pad_name); ix++) {
1282         const SV *namesv = pname[ix];
1283         if (namesv && namesv == &PL_sv_undef) {
1284             namesv = Nullsv;
1285         }
1286         if (namesv) {
1287             if (SvFAKE(namesv))
1288                 Perl_dump_indent(aTHX_ level+1, file,
1289                     "%2d. 0x%"UVxf"<%lu> FAKE \"%s\" flags=0x%lx index=%lu\n",
1290                     (int) ix,
1291                     PTR2UV(ppad[ix]),
1292                     (unsigned long) (ppad[ix] ? SvREFCNT(ppad[ix]) : 0),
1293                     SvPVX_const(namesv),
1294                     (unsigned long)SvIVX(namesv),
1295                     (unsigned long)SvNVX(namesv)
1296
1297                 );
1298             else
1299                 Perl_dump_indent(aTHX_ level+1, file,
1300                     "%2d. 0x%"UVxf"<%lu> (%ld,%ld) \"%s\"\n",
1301                     (int) ix,
1302                     PTR2UV(ppad[ix]),
1303                     (unsigned long) (ppad[ix] ? SvREFCNT(ppad[ix]) : 0),
1304                     (long)U_32(SvNVX(namesv)),
1305                     (long)SvIVX(namesv),
1306                     SvPVX_const(namesv)
1307                 );
1308         }
1309         else if (full) {
1310             Perl_dump_indent(aTHX_ level+1, file,
1311                 "%2d. 0x%"UVxf"<%lu>\n",
1312                 (int) ix,
1313                 PTR2UV(ppad[ix]),
1314                 (unsigned long) (ppad[ix] ? SvREFCNT(ppad[ix]) : 0)
1315             );
1316         }
1317     }
1318 }
1319
1320
1321
1322 /*
1323 =for apidoc cv_dump
1324
1325 dump the contents of a CV
1326
1327 =cut
1328 */
1329
1330 #ifdef DEBUGGING
1331 STATIC void
1332 S_cv_dump(pTHX_ const CV *cv, const char *title)
1333 {
1334     const CV * const outside = CvOUTSIDE(cv);
1335     AV* const padlist = CvPADLIST(cv);
1336
1337     PerlIO_printf(Perl_debug_log,
1338                   "  %s: CV=0x%"UVxf" (%s), OUTSIDE=0x%"UVxf" (%s)\n",
1339                   title,
1340                   PTR2UV(cv),
1341                   (CvANON(cv) ? "ANON"
1342                    : (SvTYPE(cv) == SVt_PVFM) ? "FORMAT"
1343                    : (cv == PL_main_cv) ? "MAIN"
1344                    : CvUNIQUE(cv) ? "UNIQUE"
1345                    : CvGV(cv) ? GvNAME(CvGV(cv)) : "UNDEFINED"),
1346                   PTR2UV(outside),
1347                   (!outside ? "null"
1348                    : CvANON(outside) ? "ANON"
1349                    : (outside == PL_main_cv) ? "MAIN"
1350                    : CvUNIQUE(outside) ? "UNIQUE"
1351                    : CvGV(outside) ? GvNAME(CvGV(outside)) : "UNDEFINED"));
1352
1353     PerlIO_printf(Perl_debug_log,
1354                     "    PADLIST = 0x%"UVxf"\n", PTR2UV(padlist));
1355     do_dump_pad(1, Perl_debug_log, padlist, 1);
1356 }
1357 #endif /* DEBUGGING */
1358
1359
1360
1361
1362
1363 /*
1364 =for apidoc cv_clone
1365
1366 Clone a CV: make a new CV which points to the same code etc, but which
1367 has a newly-created pad built by copying the prototype pad and capturing
1368 any outer lexicals.
1369
1370 =cut
1371 */
1372
1373 CV *
1374 Perl_cv_clone(pTHX_ CV *proto)
1375 {
1376     dVAR;
1377     I32 ix;
1378     AV* const protopadlist = CvPADLIST(proto);
1379     const AV* const protopad_name = (AV*)*av_fetch(protopadlist, 0, FALSE);
1380     const AV* const protopad = (AV*)*av_fetch(protopadlist, 1, FALSE);
1381     SV** const pname = AvARRAY(protopad_name);
1382     SV** const ppad = AvARRAY(protopad);
1383     const I32 fname = AvFILLp(protopad_name);
1384     const I32 fpad = AvFILLp(protopad);
1385     CV* cv;
1386     SV** outpad;
1387     CV* outside;
1388     long depth;
1389
1390     assert(!CvUNIQUE(proto));
1391
1392     /* Since cloneable anon subs can be nested, CvOUTSIDE may point
1393      * to a prototype; we instead want the cloned parent who called us.
1394      * Note that in general for formats, CvOUTSIDE != find_runcv */
1395
1396     outside = CvOUTSIDE(proto);
1397     if (outside && CvCLONE(outside) && ! CvCLONED(outside))
1398         outside = find_runcv(NULL);
1399     depth = CvDEPTH(outside);
1400     assert(depth || SvTYPE(proto) == SVt_PVFM);
1401     if (!depth)
1402         depth = 1;
1403     assert(CvPADLIST(outside));
1404
1405     ENTER;
1406     SAVESPTR(PL_compcv);
1407
1408     cv = PL_compcv = (CV*)NEWSV(1104, 0);
1409     sv_upgrade((SV *)cv, SvTYPE(proto));
1410     CvFLAGS(cv) = CvFLAGS(proto) & ~(CVf_CLONE|CVf_WEAKOUTSIDE);
1411     CvCLONED_on(cv);
1412
1413 #ifdef USE_ITHREADS
1414     CvFILE(cv)          = CvXSUB(proto) ? CvFILE(proto)
1415                                         : savepv(CvFILE(proto));
1416 #else
1417     CvFILE(cv)          = CvFILE(proto);
1418 #endif
1419     CvGV(cv)            = CvGV(proto);
1420     CvSTASH(cv)         = CvSTASH(proto);
1421     OP_REFCNT_LOCK;
1422     CvROOT(cv)          = OpREFCNT_inc(CvROOT(proto));
1423     OP_REFCNT_UNLOCK;
1424     CvSTART(cv)         = CvSTART(proto);
1425     CvOUTSIDE(cv)       = (CV*)SvREFCNT_inc(outside);
1426     CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(proto);
1427
1428     if (SvPOK(proto))
1429         sv_setpvn((SV*)cv, SvPVX_const(proto), SvCUR(proto));
1430
1431     CvPADLIST(cv) = pad_new(padnew_CLONE|padnew_SAVE);
1432
1433     av_fill(PL_comppad, fpad);
1434     for (ix = fname; ix >= 0; ix--)
1435         av_store(PL_comppad_name, ix, SvREFCNT_inc(pname[ix]));
1436
1437     PL_curpad = AvARRAY(PL_comppad);
1438
1439     outpad = AvARRAY(AvARRAY(CvPADLIST(outside))[depth]);
1440
1441     for (ix = fpad; ix > 0; ix--) {
1442         SV* const namesv = (ix <= fname) ? pname[ix] : Nullsv;
1443         SV *sv = Nullsv;
1444         if (namesv && namesv != &PL_sv_undef) { /* lexical */
1445             if (SvFAKE(namesv)) {   /* lexical from outside? */
1446                 sv = outpad[(I32)SvNVX(namesv)];
1447                 assert(sv);
1448                 /* formats may have an inactive parent */
1449                 if (SvTYPE(proto) == SVt_PVFM && SvPADSTALE(sv)) {
1450                     if (ckWARN(WARN_CLOSURE))
1451                         Perl_warner(aTHX_ packWARN(WARN_CLOSURE),
1452                             "Variable \"%s\" is not available", SvPVX_const(namesv));
1453                     sv = Nullsv;
1454                 }
1455                 else {
1456                     assert(!SvPADSTALE(sv));
1457                     sv = SvREFCNT_inc(sv);
1458                 }
1459             }
1460             if (!sv) {
1461                 const char sigil = SvPVX_const(namesv)[0];
1462                 if (sigil == '&')
1463                     sv = SvREFCNT_inc(ppad[ix]);
1464                 else if (sigil == '@')
1465                     sv = (SV*)newAV();
1466                 else if (sigil == '%')
1467                     sv = (SV*)newHV();
1468                 else
1469                     sv = NEWSV(0, 0);
1470                 SvPADMY_on(sv);
1471             }
1472         }
1473         else if (IS_PADGV(ppad[ix]) || IS_PADCONST(ppad[ix])) {
1474             sv = SvREFCNT_inc(ppad[ix]);
1475         }
1476         else {
1477             sv = NEWSV(0, 0);
1478             SvPADTMP_on(sv);
1479         }
1480         PL_curpad[ix] = sv;
1481     }
1482
1483     DEBUG_Xv(
1484         PerlIO_printf(Perl_debug_log, "\nPad CV clone\n");
1485         cv_dump(outside, "Outside");
1486         cv_dump(proto,   "Proto");
1487         cv_dump(cv,      "To");
1488     );
1489
1490     LEAVE;
1491
1492     if (CvCONST(cv)) {
1493         /* Constant sub () { $x } closing over $x - see lib/constant.pm:
1494          * The prototype was marked as a candiate for const-ization,
1495          * so try to grab the current const value, and if successful,
1496          * turn into a const sub:
1497          */
1498         SV* const_sv = op_const_sv(CvSTART(cv), cv);
1499         if (const_sv) {
1500             SvREFCNT_dec(cv);
1501             cv = newCONSTSUB(CvSTASH(proto), 0, const_sv);
1502         }
1503         else {
1504             CvCONST_off(cv);
1505         }
1506     }
1507
1508     return cv;
1509 }
1510
1511
1512 /*
1513 =for apidoc pad_fixup_inner_anons
1514
1515 For any anon CVs in the pad, change CvOUTSIDE of that CV from
1516 old_cv to new_cv if necessary. Needed when a newly-compiled CV has to be
1517 moved to a pre-existing CV struct.
1518
1519 =cut
1520 */
1521
1522 void
1523 Perl_pad_fixup_inner_anons(pTHX_ PADLIST *padlist, CV *old_cv, CV *new_cv)
1524 {
1525     I32 ix;
1526     AV * const comppad_name = (AV*)AvARRAY(padlist)[0];
1527     AV * const comppad = (AV*)AvARRAY(padlist)[1];
1528     SV ** const namepad = AvARRAY(comppad_name);
1529     SV ** const curpad = AvARRAY(comppad);
1530     for (ix = AvFILLp(comppad_name); ix > 0; ix--) {
1531         const SV *namesv = namepad[ix];
1532         if (namesv && namesv != &PL_sv_undef
1533             && *SvPVX_const(namesv) == '&')
1534         {
1535             CV *innercv = (CV*)curpad[ix];
1536             assert(CvWEAKOUTSIDE(innercv));
1537             assert(CvOUTSIDE(innercv) == old_cv);
1538             CvOUTSIDE(innercv) = new_cv;
1539         }
1540     }
1541 }
1542
1543
1544 /*
1545 =for apidoc pad_push
1546
1547 Push a new pad frame onto the padlist, unless there's already a pad at
1548 this depth, in which case don't bother creating a new one.  Then give
1549 the new pad an @_ in slot zero.
1550
1551 =cut
1552 */
1553
1554 void
1555 Perl_pad_push(pTHX_ PADLIST *padlist, int depth)
1556 {
1557     if (depth <= AvFILLp(padlist))
1558         return;
1559
1560     {
1561         SV** svp = AvARRAY(padlist);
1562         AV *newpad = newAV();
1563         SV **oldpad = AvARRAY(svp[depth-1]);
1564         I32 ix = AvFILLp((AV*)svp[1]);
1565         const I32 names_fill = AvFILLp((AV*)svp[0]);
1566         SV** names = AvARRAY(svp[0]);
1567         AV *av;
1568
1569         for ( ;ix > 0; ix--) {
1570             if (names_fill >= ix && names[ix] != &PL_sv_undef) {
1571                 const char sigil = SvPVX_const(names[ix])[0];
1572                 if ((SvFLAGS(names[ix]) & SVf_FAKE) || sigil == '&') {
1573                     /* outer lexical or anon code */
1574                     av_store(newpad, ix, SvREFCNT_inc(oldpad[ix]));
1575                 }
1576                 else {          /* our own lexical */
1577                     SV *sv; 
1578                     if (sigil == '@')
1579                         sv = (SV*)newAV();
1580                     else if (sigil == '%')
1581                         sv = (SV*)newHV();
1582                     else
1583                         sv = NEWSV(0, 0);
1584                     av_store(newpad, ix, sv);
1585                     SvPADMY_on(sv);
1586                 }
1587             }
1588             else if (IS_PADGV(oldpad[ix]) || IS_PADCONST(oldpad[ix])) {
1589                 av_store(newpad, ix, SvREFCNT_inc(oldpad[ix]));
1590             }
1591             else {
1592                 /* save temporaries on recursion? */
1593                 SV *sv = NEWSV(0, 0);
1594                 av_store(newpad, ix, sv);
1595                 SvPADTMP_on(sv);
1596             }
1597         }
1598         av = newAV();
1599         av_extend(av, 0);
1600         av_store(newpad, 0, (SV*)av);
1601         AvREIFY_only(av);
1602
1603         av_store(padlist, depth, (SV*)newpad);
1604         AvFILLp(padlist) = depth;
1605     }
1606 }
1607
1608
1609 HV *
1610 Perl_pad_compname_type(pTHX_ const PADOFFSET po)
1611 {
1612     SV** const av = av_fetch(PL_comppad_name, po, FALSE);
1613     if ( SvFLAGS(*av) & SVpad_TYPED ) {
1614         return SvSTASH(*av);
1615     }
1616     return Nullhv;
1617 }
1618
1619 /*
1620  * Local variables:
1621  * c-indentation-style: bsd
1622  * c-basic-offset: 4
1623  * indent-tabs-mode: t
1624  * End:
1625  *
1626  * ex: set ts=8 sts=4 sw=4 noet:
1627  */