ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/staticperl/perl/sv.c
Revision: 1.1
Committed: Thu Jun 30 14:26:42 2005 UTC (21 years, 3 months ago) by root
Content type: text/plain
Branch: MAIN
CVS Tags: PERL-5-8-7, HEAD
Branch point for: PERL
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 /* sv.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     * "I wonder what the Entish is for 'yes' and 'no'," he thought.
10     *
11     *
12     * This file contains the code that creates, manipulates and destroys
13     * scalar values (SVs). The other types (AV, HV, GV, etc.) reuse the
14     * structure of an SV, so their creation and destruction is handled
15     * here; higher-level functions are in av.c, hv.c, and so on. Opcode
16     * level functions (eg. substr, split, join) for each of the types are
17     * in the pp*.c files.
18     */
19    
20     #include "EXTERN.h"
21     #define PERL_IN_SV_C
22     #include "perl.h"
23     #include "regcomp.h"
24    
25     #define FCALL *f
26    
27     #ifdef __Lynx__
28     /* Missing proto on LynxOS */
29     char *gconvert(double, int, int, char *);
30     #endif
31    
32     #ifdef PERL_UTF8_CACHE_ASSERT
33     /* The cache element 0 is the Unicode offset;
34     * the cache element 1 is the byte offset of the element 0;
35     * the cache element 2 is the Unicode length of the substring;
36     * the cache element 3 is the byte length of the substring;
37     * The checking of the substring side would be good
38     * but substr() has enough code paths to make my head spin;
39     * if adding more checks watch out for the following tests:
40     * t/op/index.t t/op/length.t t/op/pat.t t/op/substr.t
41     * lib/utf8.t lib/Unicode/Collate/t/index.t
42     * --jhi
43     */
44     #define ASSERT_UTF8_CACHE(cache) \
45     STMT_START { if (cache) { assert((cache)[0] <= (cache)[1]); } } STMT_END
46     #else
47     #define ASSERT_UTF8_CACHE(cache) NOOP
48     #endif
49    
50     /* ============================================================================
51    
52     =head1 Allocation and deallocation of SVs.
53    
54     An SV (or AV, HV, etc.) is allocated in two parts: the head (struct sv,
55     av, hv...) contains type and reference count information, as well as a
56     pointer to the body (struct xrv, xpv, xpviv...), which contains fields
57     specific to each type.
58    
59     Normally, this allocation is done using arenas, which by default are
60     approximately 4K chunks of memory parcelled up into N heads or bodies. The
61     first slot in each arena is reserved, and is used to hold a link to the next
62     arena. In the case of heads, the unused first slot also contains some flags
63     and a note of the number of slots. Snaked through each arena chain is a
64     linked list of free items; when this becomes empty, an extra arena is
65     allocated and divided up into N items which are threaded into the free list.
66    
67     The following global variables are associated with arenas:
68    
69     PL_sv_arenaroot pointer to list of SV arenas
70     PL_sv_root pointer to list of free SV structures
71    
72     PL_foo_arenaroot pointer to list of foo arenas,
73     PL_foo_root pointer to list of free foo bodies
74     ... for foo in xiv, xnv, xrv, xpv etc.
75    
76     Note that some of the larger and more rarely used body types (eg xpvio)
77     are not allocated using arenas, but are instead just malloc()/free()ed as
78     required. Also, if PURIFY is defined, arenas are abandoned altogether,
79     with all items individually malloc()ed. In addition, a few SV heads are
80     not allocated from an arena, but are instead directly created as static
81     or auto variables, eg PL_sv_undef. The size of arenas can be changed from
82     the default by setting PERL_ARENA_SIZE appropriately at compile time.
83    
84     The SV arena serves the secondary purpose of allowing still-live SVs
85     to be located and destroyed during final cleanup.
86    
87     At the lowest level, the macros new_SV() and del_SV() grab and free
88     an SV head. (If debugging with -DD, del_SV() calls the function S_del_sv()
89     to return the SV to the free list with error checking.) new_SV() calls
90     more_sv() / sv_add_arena() to add an extra arena if the free list is empty.
91     SVs in the free list have their SvTYPE field set to all ones.
92    
93     Similarly, there are macros new_XIV()/del_XIV(), new_XNV()/del_XNV() etc
94     that allocate and return individual body types. Normally these are mapped
95     to the arena-manipulating functions new_xiv()/del_xiv() etc, but may be
96     instead mapped directly to malloc()/free() if PURIFY is defined. The
97     new/del functions remove from, or add to, the appropriate PL_foo_root
98     list, and call more_xiv() etc to add a new arena if the list is empty.
99    
100     At the time of very final cleanup, sv_free_arenas() is called from
101     perl_destruct() to physically free all the arenas allocated since the
102     start of the interpreter. Note that this also clears PL_he_arenaroot,
103     which is otherwise dealt with in hv.c.
104    
105     Manipulation of any of the PL_*root pointers is protected by enclosing
106     LOCK_SV_MUTEX; ... UNLOCK_SV_MUTEX calls which should Do the Right Thing
107     if threads are enabled.
108    
109     The function visit() scans the SV arenas list, and calls a specified
110     function for each SV it finds which is still live - ie which has an SvTYPE
111     other than all 1's, and a non-zero SvREFCNT. visit() is used by the
112     following functions (specified as [function that calls visit()] / [function
113     called by visit() for each SV]):
114    
115     sv_report_used() / do_report_used()
116     dump all remaining SVs (debugging aid)
117    
118     sv_clean_objs() / do_clean_objs(),do_clean_named_objs()
119     Attempt to free all objects pointed to by RVs,
120     and, unless DISABLE_DESTRUCTOR_KLUDGE is defined,
121     try to do the same for all objects indirectly
122     referenced by typeglobs too. Called once from
123     perl_destruct(), prior to calling sv_clean_all()
124     below.
125    
126     sv_clean_all() / do_clean_all()
127     SvREFCNT_dec(sv) each remaining SV, possibly
128     triggering an sv_free(). It also sets the
129     SVf_BREAK flag on the SV to indicate that the
130     refcnt has been artificially lowered, and thus
131     stopping sv_free() from giving spurious warnings
132     about SVs which unexpectedly have a refcnt
133     of zero. called repeatedly from perl_destruct()
134     until there are no SVs left.
135    
136     =head2 Summary
137    
138     Private API to rest of sv.c
139    
140     new_SV(), del_SV(),
141    
142     new_XIV(), del_XIV(),
143     new_XNV(), del_XNV(),
144     etc
145    
146     Public API:
147    
148     sv_report_used(), sv_clean_objs(), sv_clean_all(), sv_free_arenas()
149    
150    
151     =cut
152    
153     ============================================================================ */
154    
155    
156    
157     /*
158     * "A time to plant, and a time to uproot what was planted..."
159     */
160    
161     #define plant_SV(p) \
162     STMT_START { \
163     SvANY(p) = (void *)PL_sv_root; \
164     SvFLAGS(p) = SVTYPEMASK; \
165     PL_sv_root = (p); \
166     --PL_sv_count; \
167     } STMT_END
168    
169     /* sv_mutex must be held while calling uproot_SV() */
170     #define uproot_SV(p) \
171     STMT_START { \
172     (p) = PL_sv_root; \
173     PL_sv_root = (SV*)SvANY(p); \
174     ++PL_sv_count; \
175     } STMT_END
176    
177    
178     /* new_SV(): return a new, empty SV head */
179    
180     #ifdef DEBUG_LEAKING_SCALARS
181     /* provide a real function for a debugger to play with */
182     STATIC SV*
183     S_new_SV(pTHX)
184     {
185     SV* sv;
186    
187     LOCK_SV_MUTEX;
188     if (PL_sv_root)
189     uproot_SV(sv);
190     else
191     sv = more_sv();
192     UNLOCK_SV_MUTEX;
193     SvANY(sv) = 0;
194     SvREFCNT(sv) = 1;
195     SvFLAGS(sv) = 0;
196     return sv;
197     }
198     # define new_SV(p) (p)=S_new_SV(aTHX)
199    
200     #else
201     # define new_SV(p) \
202     STMT_START { \
203     LOCK_SV_MUTEX; \
204     if (PL_sv_root) \
205     uproot_SV(p); \
206     else \
207     (p) = more_sv(); \
208     UNLOCK_SV_MUTEX; \
209     SvANY(p) = 0; \
210     SvREFCNT(p) = 1; \
211     SvFLAGS(p) = 0; \
212     } STMT_END
213     #endif
214    
215    
216     /* del_SV(): return an empty SV head to the free list */
217    
218     #ifdef DEBUGGING
219    
220     #define del_SV(p) \
221     STMT_START { \
222     LOCK_SV_MUTEX; \
223     if (DEBUG_D_TEST) \
224     del_sv(p); \
225     else \
226     plant_SV(p); \
227     UNLOCK_SV_MUTEX; \
228     } STMT_END
229    
230     STATIC void
231     S_del_sv(pTHX_ SV *p)
232     {
233     if (DEBUG_D_TEST) {
234     SV* sva;
235     SV* sv;
236     SV* svend;
237     int ok = 0;
238     for (sva = PL_sv_arenaroot; sva; sva = (SV *) SvANY(sva)) {
239     sv = sva + 1;
240     svend = &sva[SvREFCNT(sva)];
241     if (p >= sv && p < svend)
242     ok = 1;
243     }
244     if (!ok) {
245     if (ckWARN_d(WARN_INTERNAL))
246     Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
247     "Attempt to free non-arena SV: 0x%"UVxf
248     pTHX__FORMAT, PTR2UV(p) pTHX__VALUE);
249     return;
250     }
251     }
252     plant_SV(p);
253     }
254    
255     #else /* ! DEBUGGING */
256    
257     #define del_SV(p) plant_SV(p)
258    
259     #endif /* DEBUGGING */
260    
261    
262     /*
263     =head1 SV Manipulation Functions
264    
265     =for apidoc sv_add_arena
266    
267     Given a chunk of memory, link it to the head of the list of arenas,
268     and split it into a list of free SVs.
269    
270     =cut
271     */
272    
273     void
274     Perl_sv_add_arena(pTHX_ char *ptr, U32 size, U32 flags)
275     {
276     SV* sva = (SV*)ptr;
277     register SV* sv;
278     register SV* svend;
279    
280     /* The first SV in an arena isn't an SV. */
281     SvANY(sva) = (void *) PL_sv_arenaroot; /* ptr to next arena */
282     SvREFCNT(sva) = size / sizeof(SV); /* number of SV slots */
283     SvFLAGS(sva) = flags; /* FAKE if not to be freed */
284    
285     PL_sv_arenaroot = sva;
286     PL_sv_root = sva + 1;
287    
288     svend = &sva[SvREFCNT(sva) - 1];
289     sv = sva + 1;
290     while (sv < svend) {
291     SvANY(sv) = (void *)(SV*)(sv + 1);
292     SvREFCNT(sv) = 0;
293     SvFLAGS(sv) = SVTYPEMASK;
294     sv++;
295     }
296     SvANY(sv) = 0;
297     SvFLAGS(sv) = SVTYPEMASK;
298     }
299    
300     /* make some more SVs by adding another arena */
301    
302     /* sv_mutex must be held while calling more_sv() */
303     STATIC SV*
304     S_more_sv(pTHX)
305     {
306     register SV* sv;
307    
308     if (PL_nice_chunk) {
309     sv_add_arena(PL_nice_chunk, PL_nice_chunk_size, 0);
310     PL_nice_chunk = Nullch;
311     PL_nice_chunk_size = 0;
312     }
313     else {
314     char *chunk; /* must use New here to match call to Safefree() */
315     New(704,chunk,PERL_ARENA_SIZE,char); /* in sv_free_arenas() */
316     sv_add_arena(chunk, PERL_ARENA_SIZE, 0);
317     }
318     uproot_SV(sv);
319     return sv;
320     }
321    
322     /* visit(): call the named function for each non-free SV in the arenas
323     * whose flags field matches the flags/mask args. */
324    
325     STATIC I32
326     S_visit(pTHX_ SVFUNC_t f, U32 flags, U32 mask)
327     {
328     SV* sva;
329     SV* sv;
330     register SV* svend;
331     I32 visited = 0;
332    
333     for (sva = PL_sv_arenaroot; sva; sva = (SV*)SvANY(sva)) {
334     svend = &sva[SvREFCNT(sva)];
335     for (sv = sva + 1; sv < svend; ++sv) {
336     if (SvTYPE(sv) != SVTYPEMASK
337     && (sv->sv_flags & mask) == flags
338     && SvREFCNT(sv))
339     {
340     (FCALL)(aTHX_ sv);
341     ++visited;
342     }
343     }
344     }
345     return visited;
346     }
347    
348     #ifdef DEBUGGING
349    
350     /* called by sv_report_used() for each live SV */
351    
352     static void
353     do_report_used(pTHX_ SV *sv)
354     {
355     if (SvTYPE(sv) != SVTYPEMASK) {
356     PerlIO_printf(Perl_debug_log, "****\n");
357     sv_dump(sv);
358     }
359     }
360     #endif
361    
362     /*
363     =for apidoc sv_report_used
364    
365     Dump the contents of all SVs not yet freed. (Debugging aid).
366    
367     =cut
368     */
369    
370     void
371     Perl_sv_report_used(pTHX)
372     {
373     #ifdef DEBUGGING
374     visit(do_report_used, 0, 0);
375     #endif
376     }
377    
378     /* called by sv_clean_objs() for each live SV */
379    
380     static void
381     do_clean_objs(pTHX_ SV *sv)
382     {
383     SV* rv;
384    
385     if (SvROK(sv) && SvOBJECT(rv = SvRV(sv))) {
386     DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning object ref:\n "), sv_dump(sv)));
387     if (SvWEAKREF(sv)) {
388     sv_del_backref(sv);
389     SvWEAKREF_off(sv);
390     SvRV(sv) = 0;
391     } else {
392     SvROK_off(sv);
393     SvRV(sv) = 0;
394     SvREFCNT_dec(rv);
395     }
396     }
397    
398     /* XXX Might want to check arrays, etc. */
399     }
400    
401     /* called by sv_clean_objs() for each live SV */
402    
403     #ifndef DISABLE_DESTRUCTOR_KLUDGE
404     static void
405     do_clean_named_objs(pTHX_ SV *sv)
406     {
407     if (SvTYPE(sv) == SVt_PVGV && GvGP(sv)) {
408     if ( SvOBJECT(GvSV(sv)) ||
409     (GvAV(sv) && SvOBJECT(GvAV(sv))) ||
410     (GvHV(sv) && SvOBJECT(GvHV(sv))) ||
411     (GvIO(sv) && SvOBJECT(GvIO(sv))) ||
412     (GvCV(sv) && SvOBJECT(GvCV(sv))) )
413     {
414     DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning named glob object:\n "), sv_dump(sv)));
415     SvFLAGS(sv) |= SVf_BREAK;
416     SvREFCNT_dec(sv);
417     }
418     }
419     }
420     #endif
421    
422     /*
423     =for apidoc sv_clean_objs
424    
425     Attempt to destroy all objects not yet freed
426    
427     =cut
428     */
429    
430     void
431     Perl_sv_clean_objs(pTHX)
432     {
433     PL_in_clean_objs = TRUE;
434     visit(do_clean_objs, SVf_ROK, SVf_ROK);
435     #ifndef DISABLE_DESTRUCTOR_KLUDGE
436     /* some barnacles may yet remain, clinging to typeglobs */
437     visit(do_clean_named_objs, SVt_PVGV, SVTYPEMASK);
438     #endif
439     PL_in_clean_objs = FALSE;
440     }
441    
442     /* called by sv_clean_all() for each live SV */
443    
444     static void
445     do_clean_all(pTHX_ SV *sv)
446     {
447     DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning loops: SV at 0x%"UVxf"\n", PTR2UV(sv)) ));
448     SvFLAGS(sv) |= SVf_BREAK;
449     SvREFCNT_dec(sv);
450     }
451    
452     /*
453     =for apidoc sv_clean_all
454    
455     Decrement the refcnt of each remaining SV, possibly triggering a
456     cleanup. This function may have to be called multiple times to free
457     SVs which are in complex self-referential hierarchies.
458    
459     =cut
460     */
461    
462     I32
463     Perl_sv_clean_all(pTHX)
464     {
465     I32 cleaned;
466     PL_in_clean_all = TRUE;
467     cleaned = visit(do_clean_all, 0,0);
468     PL_in_clean_all = FALSE;
469     return cleaned;
470     }
471    
472     /*
473     =for apidoc sv_free_arenas
474    
475     Deallocate the memory used by all arenas. Note that all the individual SV
476     heads and bodies within the arenas must already have been freed.
477    
478     =cut
479     */
480    
481     void
482     Perl_sv_free_arenas(pTHX)
483     {
484     SV* sva;
485     SV* svanext;
486     XPV *arena, *arenanext;
487    
488     /* Free arenas here, but be careful about fake ones. (We assume
489     contiguity of the fake ones with the corresponding real ones.) */
490    
491     for (sva = PL_sv_arenaroot; sva; sva = svanext) {
492     svanext = (SV*) SvANY(sva);
493     while (svanext && SvFAKE(svanext))
494     svanext = (SV*) SvANY(svanext);
495    
496     if (!SvFAKE(sva))
497     Safefree((void *)sva);
498     }
499    
500     for (arena = PL_xiv_arenaroot; arena; arena = arenanext) {
501     arenanext = (XPV*)arena->xpv_pv;
502     Safefree(arena);
503     }
504     PL_xiv_arenaroot = 0;
505     PL_xiv_root = 0;
506    
507     for (arena = PL_xnv_arenaroot; arena; arena = arenanext) {
508     arenanext = (XPV*)arena->xpv_pv;
509     Safefree(arena);
510     }
511     PL_xnv_arenaroot = 0;
512     PL_xnv_root = 0;
513    
514     for (arena = PL_xrv_arenaroot; arena; arena = arenanext) {
515     arenanext = (XPV*)arena->xpv_pv;
516     Safefree(arena);
517     }
518     PL_xrv_arenaroot = 0;
519     PL_xrv_root = 0;
520    
521     for (arena = PL_xpv_arenaroot; arena; arena = arenanext) {
522     arenanext = (XPV*)arena->xpv_pv;
523     Safefree(arena);
524     }
525     PL_xpv_arenaroot = 0;
526     PL_xpv_root = 0;
527    
528     for (arena = (XPV*)PL_xpviv_arenaroot; arena; arena = arenanext) {
529     arenanext = (XPV*)arena->xpv_pv;
530     Safefree(arena);
531     }
532     PL_xpviv_arenaroot = 0;
533     PL_xpviv_root = 0;
534    
535     for (arena = (XPV*)PL_xpvnv_arenaroot; arena; arena = arenanext) {
536     arenanext = (XPV*)arena->xpv_pv;
537     Safefree(arena);
538     }
539     PL_xpvnv_arenaroot = 0;
540     PL_xpvnv_root = 0;
541    
542     for (arena = (XPV*)PL_xpvcv_arenaroot; arena; arena = arenanext) {
543     arenanext = (XPV*)arena->xpv_pv;
544     Safefree(arena);
545     }
546     PL_xpvcv_arenaroot = 0;
547     PL_xpvcv_root = 0;
548    
549     for (arena = (XPV*)PL_xpvav_arenaroot; arena; arena = arenanext) {
550     arenanext = (XPV*)arena->xpv_pv;
551     Safefree(arena);
552     }
553     PL_xpvav_arenaroot = 0;
554     PL_xpvav_root = 0;
555    
556     for (arena = (XPV*)PL_xpvhv_arenaroot; arena; arena = arenanext) {
557     arenanext = (XPV*)arena->xpv_pv;
558     Safefree(arena);
559     }
560     PL_xpvhv_arenaroot = 0;
561     PL_xpvhv_root = 0;
562    
563     for (arena = (XPV*)PL_xpvmg_arenaroot; arena; arena = arenanext) {
564     arenanext = (XPV*)arena->xpv_pv;
565     Safefree(arena);
566     }
567     PL_xpvmg_arenaroot = 0;
568     PL_xpvmg_root = 0;
569    
570     for (arena = (XPV*)PL_xpvlv_arenaroot; arena; arena = arenanext) {
571     arenanext = (XPV*)arena->xpv_pv;
572     Safefree(arena);
573     }
574     PL_xpvlv_arenaroot = 0;
575     PL_xpvlv_root = 0;
576    
577     for (arena = (XPV*)PL_xpvbm_arenaroot; arena; arena = arenanext) {
578     arenanext = (XPV*)arena->xpv_pv;
579     Safefree(arena);
580     }
581     PL_xpvbm_arenaroot = 0;
582     PL_xpvbm_root = 0;
583    
584     for (arena = (XPV*)PL_he_arenaroot; arena; arena = arenanext) {
585     arenanext = (XPV*)arena->xpv_pv;
586     Safefree(arena);
587     }
588     PL_he_arenaroot = 0;
589     PL_he_root = 0;
590    
591     #if defined(USE_ITHREADS)
592     for (arena = (XPV*)PL_pte_arenaroot; arena; arena = arenanext) {
593     arenanext = (XPV*)arena->xpv_pv;
594     Safefree(arena);
595     }
596     PL_pte_arenaroot = 0;
597     PL_pte_root = 0;
598     #endif
599    
600     if (PL_nice_chunk)
601     Safefree(PL_nice_chunk);
602     PL_nice_chunk = Nullch;
603     PL_nice_chunk_size = 0;
604     PL_sv_arenaroot = 0;
605     PL_sv_root = 0;
606     }
607    
608     /*
609     =for apidoc report_uninit
610    
611     Print appropriate "Use of uninitialized variable" warning
612    
613     =cut
614     */
615    
616     void
617     Perl_report_uninit(pTHX)
618     {
619     if (PL_op)
620     Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
621     " in ", OP_DESC(PL_op));
622     else
623     Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit, "", "");
624     }
625    
626     /* grab a new IV body from the free list, allocating more if necessary */
627    
628     STATIC XPVIV*
629     S_new_xiv(pTHX)
630     {
631     IV* xiv;
632     LOCK_SV_MUTEX;
633     if (!PL_xiv_root)
634     more_xiv();
635     xiv = PL_xiv_root;
636     /*
637     * See comment in more_xiv() -- RAM.
638     */
639     PL_xiv_root = *(IV**)xiv;
640     UNLOCK_SV_MUTEX;
641     return (XPVIV*)((char*)xiv - STRUCT_OFFSET(XPVIV, xiv_iv));
642     }
643    
644     /* return an IV body to the free list */
645    
646     STATIC void
647     S_del_xiv(pTHX_ XPVIV *p)
648     {
649     IV* xiv = (IV*)((char*)(p) + STRUCT_OFFSET(XPVIV, xiv_iv));
650     LOCK_SV_MUTEX;
651     *(IV**)xiv = PL_xiv_root;
652     PL_xiv_root = xiv;
653     UNLOCK_SV_MUTEX;
654     }
655    
656     /* allocate another arena's worth of IV bodies */
657    
658     STATIC void
659     S_more_xiv(pTHX)
660     {
661     register IV* xiv;
662     register IV* xivend;
663     XPV* ptr;
664     New(705, ptr, PERL_ARENA_SIZE/sizeof(XPV), XPV);
665     ptr->xpv_pv = (char*)PL_xiv_arenaroot; /* linked list of xiv arenas */
666     PL_xiv_arenaroot = ptr; /* to keep Purify happy */
667    
668     xiv = (IV*) ptr;
669     xivend = &xiv[PERL_ARENA_SIZE / sizeof(IV) - 1];
670     xiv += (sizeof(XPV) - 1) / sizeof(IV) + 1; /* fudge by size of XPV */
671     PL_xiv_root = xiv;
672     while (xiv < xivend) {
673     *(IV**)xiv = (IV *)(xiv + 1);
674     xiv++;
675     }
676     *(IV**)xiv = 0;
677     }
678    
679     /* grab a new NV body from the free list, allocating more if necessary */
680    
681     STATIC XPVNV*
682     S_new_xnv(pTHX)
683     {
684     NV* xnv;
685     LOCK_SV_MUTEX;
686     if (!PL_xnv_root)
687     more_xnv();
688     xnv = PL_xnv_root;
689     PL_xnv_root = *(NV**)xnv;
690     UNLOCK_SV_MUTEX;
691     return (XPVNV*)((char*)xnv - STRUCT_OFFSET(XPVNV, xnv_nv));
692     }
693    
694     /* return an NV body to the free list */
695    
696     STATIC void
697     S_del_xnv(pTHX_ XPVNV *p)
698     {
699     NV* xnv = (NV*)((char*)(p) + STRUCT_OFFSET(XPVNV, xnv_nv));
700     LOCK_SV_MUTEX;
701     *(NV**)xnv = PL_xnv_root;
702     PL_xnv_root = xnv;
703     UNLOCK_SV_MUTEX;
704     }
705    
706     /* allocate another arena's worth of NV bodies */
707    
708     STATIC void
709     S_more_xnv(pTHX)
710     {
711     register NV* xnv;
712     register NV* xnvend;
713     XPV *ptr;
714     New(711, ptr, PERL_ARENA_SIZE/sizeof(XPV), XPV);
715     ptr->xpv_pv = (char*)PL_xnv_arenaroot;
716     PL_xnv_arenaroot = ptr;
717    
718     xnv = (NV*) ptr;
719     xnvend = &xnv[PERL_ARENA_SIZE / sizeof(NV) - 1];
720     xnv += (sizeof(XPVIV) - 1) / sizeof(NV) + 1; /* fudge by sizeof XPVIV */
721     PL_xnv_root = xnv;
722     while (xnv < xnvend) {
723     *(NV**)xnv = (NV*)(xnv + 1);
724     xnv++;
725     }
726     *(NV**)xnv = 0;
727     }
728    
729     /* grab a new struct xrv from the free list, allocating more if necessary */
730    
731     STATIC XRV*
732     S_new_xrv(pTHX)
733     {
734     XRV* xrv;
735     LOCK_SV_MUTEX;
736     if (!PL_xrv_root)
737     more_xrv();
738     xrv = PL_xrv_root;
739     PL_xrv_root = (XRV*)xrv->xrv_rv;
740     UNLOCK_SV_MUTEX;
741     return xrv;
742     }
743    
744     /* return a struct xrv to the free list */
745    
746     STATIC void
747     S_del_xrv(pTHX_ XRV *p)
748     {
749     LOCK_SV_MUTEX;
750     p->xrv_rv = (SV*)PL_xrv_root;
751     PL_xrv_root = p;
752     UNLOCK_SV_MUTEX;
753     }
754    
755     /* allocate another arena's worth of struct xrv */
756    
757     STATIC void
758     S_more_xrv(pTHX)
759     {
760     register XRV* xrv;
761     register XRV* xrvend;
762     XPV *ptr;
763     New(712, ptr, PERL_ARENA_SIZE/sizeof(XPV), XPV);
764     ptr->xpv_pv = (char*)PL_xrv_arenaroot;
765     PL_xrv_arenaroot = ptr;
766    
767     xrv = (XRV*) ptr;
768     xrvend = &xrv[PERL_ARENA_SIZE / sizeof(XRV) - 1];
769     xrv += (sizeof(XPV) - 1) / sizeof(XRV) + 1;
770     PL_xrv_root = xrv;
771     while (xrv < xrvend) {
772     xrv->xrv_rv = (SV*)(xrv + 1);
773     xrv++;
774     }
775     xrv->xrv_rv = 0;
776     }
777    
778     /* grab a new struct xpv from the free list, allocating more if necessary */
779    
780     STATIC XPV*
781     S_new_xpv(pTHX)
782     {
783     XPV* xpv;
784     LOCK_SV_MUTEX;
785     if (!PL_xpv_root)
786     more_xpv();
787     xpv = PL_xpv_root;
788     PL_xpv_root = (XPV*)xpv->xpv_pv;
789     UNLOCK_SV_MUTEX;
790     return xpv;
791     }
792    
793     /* return a struct xpv to the free list */
794    
795     STATIC void
796     S_del_xpv(pTHX_ XPV *p)
797     {
798     LOCK_SV_MUTEX;
799     p->xpv_pv = (char*)PL_xpv_root;
800     PL_xpv_root = p;
801     UNLOCK_SV_MUTEX;
802     }
803    
804     /* allocate another arena's worth of struct xpv */
805    
806     STATIC void
807     S_more_xpv(pTHX)
808     {
809     register XPV* xpv;
810     register XPV* xpvend;
811     New(713, xpv, PERL_ARENA_SIZE/sizeof(XPV), XPV);
812     xpv->xpv_pv = (char*)PL_xpv_arenaroot;
813     PL_xpv_arenaroot = xpv;
814    
815     xpvend = &xpv[PERL_ARENA_SIZE / sizeof(XPV) - 1];
816     PL_xpv_root = ++xpv;
817     while (xpv < xpvend) {
818     xpv->xpv_pv = (char*)(xpv + 1);
819     xpv++;
820     }
821     xpv->xpv_pv = 0;
822     }
823    
824     /* grab a new struct xpviv from the free list, allocating more if necessary */
825    
826     STATIC XPVIV*
827     S_new_xpviv(pTHX)
828     {
829     XPVIV* xpviv;
830     LOCK_SV_MUTEX;
831     if (!PL_xpviv_root)
832     more_xpviv();
833     xpviv = PL_xpviv_root;
834     PL_xpviv_root = (XPVIV*)xpviv->xpv_pv;
835     UNLOCK_SV_MUTEX;
836     return xpviv;
837     }
838    
839     /* return a struct xpviv to the free list */
840    
841     STATIC void
842     S_del_xpviv(pTHX_ XPVIV *p)
843     {
844     LOCK_SV_MUTEX;
845     p->xpv_pv = (char*)PL_xpviv_root;
846     PL_xpviv_root = p;
847     UNLOCK_SV_MUTEX;
848     }
849    
850     /* allocate another arena's worth of struct xpviv */
851    
852     STATIC void
853     S_more_xpviv(pTHX)
854     {
855     register XPVIV* xpviv;
856     register XPVIV* xpvivend;
857     New(714, xpviv, PERL_ARENA_SIZE/sizeof(XPVIV), XPVIV);
858     xpviv->xpv_pv = (char*)PL_xpviv_arenaroot;
859     PL_xpviv_arenaroot = xpviv;
860    
861     xpvivend = &xpviv[PERL_ARENA_SIZE / sizeof(XPVIV) - 1];
862     PL_xpviv_root = ++xpviv;
863     while (xpviv < xpvivend) {
864     xpviv->xpv_pv = (char*)(xpviv + 1);
865     xpviv++;
866     }
867     xpviv->xpv_pv = 0;
868     }
869    
870     /* grab a new struct xpvnv from the free list, allocating more if necessary */
871    
872     STATIC XPVNV*
873     S_new_xpvnv(pTHX)
874     {
875     XPVNV* xpvnv;
876     LOCK_SV_MUTEX;
877     if (!PL_xpvnv_root)
878     more_xpvnv();
879     xpvnv = PL_xpvnv_root;
880     PL_xpvnv_root = (XPVNV*)xpvnv->xpv_pv;
881     UNLOCK_SV_MUTEX;
882     return xpvnv;
883     }
884    
885     /* return a struct xpvnv to the free list */
886    
887     STATIC void
888     S_del_xpvnv(pTHX_ XPVNV *p)
889     {
890     LOCK_SV_MUTEX;
891     p->xpv_pv = (char*)PL_xpvnv_root;
892     PL_xpvnv_root = p;
893     UNLOCK_SV_MUTEX;
894     }
895    
896     /* allocate another arena's worth of struct xpvnv */
897    
898     STATIC void
899     S_more_xpvnv(pTHX)
900     {
901     register XPVNV* xpvnv;
902     register XPVNV* xpvnvend;
903     New(715, xpvnv, PERL_ARENA_SIZE/sizeof(XPVNV), XPVNV);
904     xpvnv->xpv_pv = (char*)PL_xpvnv_arenaroot;
905     PL_xpvnv_arenaroot = xpvnv;
906    
907     xpvnvend = &xpvnv[PERL_ARENA_SIZE / sizeof(XPVNV) - 1];
908     PL_xpvnv_root = ++xpvnv;
909     while (xpvnv < xpvnvend) {
910     xpvnv->xpv_pv = (char*)(xpvnv + 1);
911     xpvnv++;
912     }
913     xpvnv->xpv_pv = 0;
914     }
915    
916     /* grab a new struct xpvcv from the free list, allocating more if necessary */
917    
918     STATIC XPVCV*
919     S_new_xpvcv(pTHX)
920     {
921     XPVCV* xpvcv;
922     LOCK_SV_MUTEX;
923     if (!PL_xpvcv_root)
924     more_xpvcv();
925     xpvcv = PL_xpvcv_root;
926     PL_xpvcv_root = (XPVCV*)xpvcv->xpv_pv;
927     UNLOCK_SV_MUTEX;
928     return xpvcv;
929     }
930    
931     /* return a struct xpvcv to the free list */
932    
933     STATIC void
934     S_del_xpvcv(pTHX_ XPVCV *p)
935     {
936     LOCK_SV_MUTEX;
937     p->xpv_pv = (char*)PL_xpvcv_root;
938     PL_xpvcv_root = p;
939     UNLOCK_SV_MUTEX;
940     }
941    
942     /* allocate another arena's worth of struct xpvcv */
943    
944     STATIC void
945     S_more_xpvcv(pTHX)
946     {
947     register XPVCV* xpvcv;
948     register XPVCV* xpvcvend;
949     New(716, xpvcv, PERL_ARENA_SIZE/sizeof(XPVCV), XPVCV);
950     xpvcv->xpv_pv = (char*)PL_xpvcv_arenaroot;
951     PL_xpvcv_arenaroot = xpvcv;
952    
953     xpvcvend = &xpvcv[PERL_ARENA_SIZE / sizeof(XPVCV) - 1];
954     PL_xpvcv_root = ++xpvcv;
955     while (xpvcv < xpvcvend) {
956     xpvcv->xpv_pv = (char*)(xpvcv + 1);
957     xpvcv++;
958     }
959     xpvcv->xpv_pv = 0;
960     }
961    
962     /* grab a new struct xpvav from the free list, allocating more if necessary */
963    
964     STATIC XPVAV*
965     S_new_xpvav(pTHX)
966     {
967     XPVAV* xpvav;
968     LOCK_SV_MUTEX;
969     if (!PL_xpvav_root)
970     more_xpvav();
971     xpvav = PL_xpvav_root;
972     PL_xpvav_root = (XPVAV*)xpvav->xav_array;
973     UNLOCK_SV_MUTEX;
974     return xpvav;
975     }
976    
977     /* return a struct xpvav to the free list */
978    
979     STATIC void
980     S_del_xpvav(pTHX_ XPVAV *p)
981     {
982     LOCK_SV_MUTEX;
983     p->xav_array = (char*)PL_xpvav_root;
984     PL_xpvav_root = p;
985     UNLOCK_SV_MUTEX;
986     }
987    
988     /* allocate another arena's worth of struct xpvav */
989    
990     STATIC void
991     S_more_xpvav(pTHX)
992     {
993     register XPVAV* xpvav;
994     register XPVAV* xpvavend;
995     New(717, xpvav, PERL_ARENA_SIZE/sizeof(XPVAV), XPVAV);
996     xpvav->xav_array = (char*)PL_xpvav_arenaroot;
997     PL_xpvav_arenaroot = xpvav;
998    
999     xpvavend = &xpvav[PERL_ARENA_SIZE / sizeof(XPVAV) - 1];
1000     PL_xpvav_root = ++xpvav;
1001     while (xpvav < xpvavend) {
1002     xpvav->xav_array = (char*)(xpvav + 1);
1003     xpvav++;
1004     }
1005     xpvav->xav_array = 0;
1006     }
1007    
1008     /* grab a new struct xpvhv from the free list, allocating more if necessary */
1009    
1010     STATIC XPVHV*
1011     S_new_xpvhv(pTHX)
1012     {
1013     XPVHV* xpvhv;
1014     LOCK_SV_MUTEX;
1015     if (!PL_xpvhv_root)
1016     more_xpvhv();
1017     xpvhv = PL_xpvhv_root;
1018     PL_xpvhv_root = (XPVHV*)xpvhv->xhv_array;
1019     UNLOCK_SV_MUTEX;
1020     return xpvhv;
1021     }
1022    
1023     /* return a struct xpvhv to the free list */
1024    
1025     STATIC void
1026     S_del_xpvhv(pTHX_ XPVHV *p)
1027     {
1028     LOCK_SV_MUTEX;
1029     p->xhv_array = (char*)PL_xpvhv_root;
1030     PL_xpvhv_root = p;
1031     UNLOCK_SV_MUTEX;
1032     }
1033    
1034     /* allocate another arena's worth of struct xpvhv */
1035    
1036     STATIC void
1037     S_more_xpvhv(pTHX)
1038     {
1039     register XPVHV* xpvhv;
1040     register XPVHV* xpvhvend;
1041     New(718, xpvhv, PERL_ARENA_SIZE/sizeof(XPVHV), XPVHV);
1042     xpvhv->xhv_array = (char*)PL_xpvhv_arenaroot;
1043     PL_xpvhv_arenaroot = xpvhv;
1044    
1045     xpvhvend = &xpvhv[PERL_ARENA_SIZE / sizeof(XPVHV) - 1];
1046     PL_xpvhv_root = ++xpvhv;
1047     while (xpvhv < xpvhvend) {
1048     xpvhv->xhv_array = (char*)(xpvhv + 1);
1049     xpvhv++;
1050     }
1051     xpvhv->xhv_array = 0;
1052     }
1053    
1054     /* grab a new struct xpvmg from the free list, allocating more if necessary */
1055    
1056     STATIC XPVMG*
1057     S_new_xpvmg(pTHX)
1058     {
1059     XPVMG* xpvmg;
1060     LOCK_SV_MUTEX;
1061     if (!PL_xpvmg_root)
1062     more_xpvmg();
1063     xpvmg = PL_xpvmg_root;
1064     PL_xpvmg_root = (XPVMG*)xpvmg->xpv_pv;
1065     UNLOCK_SV_MUTEX;
1066     return xpvmg;
1067     }
1068    
1069     /* return a struct xpvmg to the free list */
1070    
1071     STATIC void
1072     S_del_xpvmg(pTHX_ XPVMG *p)
1073     {
1074     LOCK_SV_MUTEX;
1075     p->xpv_pv = (char*)PL_xpvmg_root;
1076     PL_xpvmg_root = p;
1077     UNLOCK_SV_MUTEX;
1078     }
1079    
1080     /* allocate another arena's worth of struct xpvmg */
1081    
1082     STATIC void
1083     S_more_xpvmg(pTHX)
1084     {
1085     register XPVMG* xpvmg;
1086     register XPVMG* xpvmgend;
1087     New(719, xpvmg, PERL_ARENA_SIZE/sizeof(XPVMG), XPVMG);
1088     xpvmg->xpv_pv = (char*)PL_xpvmg_arenaroot;
1089     PL_xpvmg_arenaroot = xpvmg;
1090    
1091     xpvmgend = &xpvmg[PERL_ARENA_SIZE / sizeof(XPVMG) - 1];
1092     PL_xpvmg_root = ++xpvmg;
1093     while (xpvmg < xpvmgend) {
1094     xpvmg->xpv_pv = (char*)(xpvmg + 1);
1095     xpvmg++;
1096     }
1097     xpvmg->xpv_pv = 0;
1098     }
1099    
1100     /* grab a new struct xpvlv from the free list, allocating more if necessary */
1101    
1102     STATIC XPVLV*
1103     S_new_xpvlv(pTHX)
1104     {
1105     XPVLV* xpvlv;
1106     LOCK_SV_MUTEX;
1107     if (!PL_xpvlv_root)
1108     more_xpvlv();
1109     xpvlv = PL_xpvlv_root;
1110     PL_xpvlv_root = (XPVLV*)xpvlv->xpv_pv;
1111     UNLOCK_SV_MUTEX;
1112     return xpvlv;
1113     }
1114    
1115     /* return a struct xpvlv to the free list */
1116    
1117     STATIC void
1118     S_del_xpvlv(pTHX_ XPVLV *p)
1119     {
1120     LOCK_SV_MUTEX;
1121     p->xpv_pv = (char*)PL_xpvlv_root;
1122     PL_xpvlv_root = p;
1123     UNLOCK_SV_MUTEX;
1124     }
1125    
1126     /* allocate another arena's worth of struct xpvlv */
1127    
1128     STATIC void
1129     S_more_xpvlv(pTHX)
1130     {
1131     register XPVLV* xpvlv;
1132     register XPVLV* xpvlvend;
1133     New(720, xpvlv, PERL_ARENA_SIZE/sizeof(XPVLV), XPVLV);
1134     xpvlv->xpv_pv = (char*)PL_xpvlv_arenaroot;
1135     PL_xpvlv_arenaroot = xpvlv;
1136    
1137     xpvlvend = &xpvlv[PERL_ARENA_SIZE / sizeof(XPVLV) - 1];
1138     PL_xpvlv_root = ++xpvlv;
1139     while (xpvlv < xpvlvend) {
1140     xpvlv->xpv_pv = (char*)(xpvlv + 1);
1141     xpvlv++;
1142     }
1143     xpvlv->xpv_pv = 0;
1144     }
1145    
1146     /* grab a new struct xpvbm from the free list, allocating more if necessary */
1147    
1148     STATIC XPVBM*
1149     S_new_xpvbm(pTHX)
1150     {
1151     XPVBM* xpvbm;
1152     LOCK_SV_MUTEX;
1153     if (!PL_xpvbm_root)
1154     more_xpvbm();
1155     xpvbm = PL_xpvbm_root;
1156     PL_xpvbm_root = (XPVBM*)xpvbm->xpv_pv;
1157     UNLOCK_SV_MUTEX;
1158     return xpvbm;
1159     }
1160    
1161     /* return a struct xpvbm to the free list */
1162    
1163     STATIC void
1164     S_del_xpvbm(pTHX_ XPVBM *p)
1165     {
1166     LOCK_SV_MUTEX;
1167     p->xpv_pv = (char*)PL_xpvbm_root;
1168     PL_xpvbm_root = p;
1169     UNLOCK_SV_MUTEX;
1170     }
1171    
1172     /* allocate another arena's worth of struct xpvbm */
1173    
1174     STATIC void
1175     S_more_xpvbm(pTHX)
1176     {
1177     register XPVBM* xpvbm;
1178     register XPVBM* xpvbmend;
1179     New(721, xpvbm, PERL_ARENA_SIZE/sizeof(XPVBM), XPVBM);
1180     xpvbm->xpv_pv = (char*)PL_xpvbm_arenaroot;
1181     PL_xpvbm_arenaroot = xpvbm;
1182    
1183     xpvbmend = &xpvbm[PERL_ARENA_SIZE / sizeof(XPVBM) - 1];
1184     PL_xpvbm_root = ++xpvbm;
1185     while (xpvbm < xpvbmend) {
1186     xpvbm->xpv_pv = (char*)(xpvbm + 1);
1187     xpvbm++;
1188     }
1189     xpvbm->xpv_pv = 0;
1190     }
1191    
1192     #define my_safemalloc(s) (void*)safemalloc(s)
1193     #define my_safefree(p) safefree((char*)p)
1194    
1195     #ifdef PURIFY
1196    
1197     #define new_XIV() my_safemalloc(sizeof(XPVIV))
1198     #define del_XIV(p) my_safefree(p)
1199    
1200     #define new_XNV() my_safemalloc(sizeof(XPVNV))
1201     #define del_XNV(p) my_safefree(p)
1202    
1203     #define new_XRV() my_safemalloc(sizeof(XRV))
1204     #define del_XRV(p) my_safefree(p)
1205    
1206     #define new_XPV() my_safemalloc(sizeof(XPV))
1207     #define del_XPV(p) my_safefree(p)
1208    
1209     #define new_XPVIV() my_safemalloc(sizeof(XPVIV))
1210     #define del_XPVIV(p) my_safefree(p)
1211    
1212     #define new_XPVNV() my_safemalloc(sizeof(XPVNV))
1213     #define del_XPVNV(p) my_safefree(p)
1214    
1215     #define new_XPVCV() my_safemalloc(sizeof(XPVCV))
1216     #define del_XPVCV(p) my_safefree(p)
1217    
1218     #define new_XPVAV() my_safemalloc(sizeof(XPVAV))
1219     #define del_XPVAV(p) my_safefree(p)
1220    
1221     #define new_XPVHV() my_safemalloc(sizeof(XPVHV))
1222     #define del_XPVHV(p) my_safefree(p)
1223    
1224     #define new_XPVMG() my_safemalloc(sizeof(XPVMG))
1225     #define del_XPVMG(p) my_safefree(p)
1226    
1227     #define new_XPVLV() my_safemalloc(sizeof(XPVLV))
1228     #define del_XPVLV(p) my_safefree(p)
1229    
1230     #define new_XPVBM() my_safemalloc(sizeof(XPVBM))
1231     #define del_XPVBM(p) my_safefree(p)
1232    
1233     #else /* !PURIFY */
1234    
1235     #define new_XIV() (void*)new_xiv()
1236     #define del_XIV(p) del_xiv((XPVIV*) p)
1237    
1238     #define new_XNV() (void*)new_xnv()
1239     #define del_XNV(p) del_xnv((XPVNV*) p)
1240    
1241     #define new_XRV() (void*)new_xrv()
1242     #define del_XRV(p) del_xrv((XRV*) p)
1243    
1244     #define new_XPV() (void*)new_xpv()
1245     #define del_XPV(p) del_xpv((XPV *)p)
1246    
1247     #define new_XPVIV() (void*)new_xpviv()
1248     #define del_XPVIV(p) del_xpviv((XPVIV *)p)
1249    
1250     #define new_XPVNV() (void*)new_xpvnv()
1251     #define del_XPVNV(p) del_xpvnv((XPVNV *)p)
1252    
1253     #define new_XPVCV() (void*)new_xpvcv()
1254     #define del_XPVCV(p) del_xpvcv((XPVCV *)p)
1255    
1256     #define new_XPVAV() (void*)new_xpvav()
1257     #define del_XPVAV(p) del_xpvav((XPVAV *)p)
1258    
1259     #define new_XPVHV() (void*)new_xpvhv()
1260     #define del_XPVHV(p) del_xpvhv((XPVHV *)p)
1261    
1262     #define new_XPVMG() (void*)new_xpvmg()
1263     #define del_XPVMG(p) del_xpvmg((XPVMG *)p)
1264    
1265     #define new_XPVLV() (void*)new_xpvlv()
1266     #define del_XPVLV(p) del_xpvlv((XPVLV *)p)
1267    
1268     #define new_XPVBM() (void*)new_xpvbm()
1269     #define del_XPVBM(p) del_xpvbm((XPVBM *)p)
1270    
1271     #endif /* PURIFY */
1272    
1273     #define new_XPVGV() my_safemalloc(sizeof(XPVGV))
1274     #define del_XPVGV(p) my_safefree(p)
1275    
1276     #define new_XPVFM() my_safemalloc(sizeof(XPVFM))
1277     #define del_XPVFM(p) my_safefree(p)
1278    
1279     #define new_XPVIO() my_safemalloc(sizeof(XPVIO))
1280     #define del_XPVIO(p) my_safefree(p)
1281    
1282     /*
1283     =for apidoc sv_upgrade
1284    
1285     Upgrade an SV to a more complex form. Generally adds a new body type to the
1286     SV, then copies across as much information as possible from the old body.
1287     You generally want to use the C<SvUPGRADE> macro wrapper. See also C<svtype>.
1288    
1289     =cut
1290     */
1291    
1292     bool
1293     Perl_sv_upgrade(pTHX_ register SV *sv, U32 mt)
1294     {
1295    
1296     char* pv;
1297     U32 cur;
1298     U32 len;
1299     IV iv;
1300     NV nv;
1301     MAGIC* magic;
1302     HV* stash;
1303    
1304     if (mt != SVt_PV && SvREADONLY(sv) && SvFAKE(sv)) {
1305     sv_force_normal(sv);
1306     }
1307    
1308     if (SvTYPE(sv) == mt)
1309     return TRUE;
1310    
1311     if (mt < SVt_PVIV)
1312     (void)SvOOK_off(sv);
1313    
1314     pv = NULL;
1315     cur = 0;
1316     len = 0;
1317     iv = 0;
1318     nv = 0.0;
1319     magic = NULL;
1320     stash = Nullhv;
1321    
1322     switch (SvTYPE(sv)) {
1323     case SVt_NULL:
1324     break;
1325     case SVt_IV:
1326     iv = SvIVX(sv);
1327     del_XIV(SvANY(sv));
1328     if (mt == SVt_NV)
1329     mt = SVt_PVNV;
1330     else if (mt < SVt_PVIV)
1331     mt = SVt_PVIV;
1332     break;
1333     case SVt_NV:
1334     nv = SvNVX(sv);
1335     del_XNV(SvANY(sv));
1336     if (mt < SVt_PVNV)
1337     mt = SVt_PVNV;
1338     break;
1339     case SVt_RV:
1340     pv = (char*)SvRV(sv);
1341     del_XRV(SvANY(sv));
1342     break;
1343     case SVt_PV:
1344     pv = SvPVX(sv);
1345     cur = SvCUR(sv);
1346     len = SvLEN(sv);
1347     del_XPV(SvANY(sv));
1348     if (mt <= SVt_IV)
1349     mt = SVt_PVIV;
1350     else if (mt == SVt_NV)
1351     mt = SVt_PVNV;
1352     break;
1353     case SVt_PVIV:
1354     pv = SvPVX(sv);
1355     cur = SvCUR(sv);
1356     len = SvLEN(sv);
1357     iv = SvIVX(sv);
1358     del_XPVIV(SvANY(sv));
1359     break;
1360     case SVt_PVNV:
1361     pv = SvPVX(sv);
1362     cur = SvCUR(sv);
1363     len = SvLEN(sv);
1364     iv = SvIVX(sv);
1365     nv = SvNVX(sv);
1366     del_XPVNV(SvANY(sv));
1367     break;
1368     case SVt_PVMG:
1369     pv = SvPVX(sv);
1370     cur = SvCUR(sv);
1371     len = SvLEN(sv);
1372     iv = SvIVX(sv);
1373     nv = SvNVX(sv);
1374     magic = SvMAGIC(sv);
1375     stash = SvSTASH(sv);
1376     del_XPVMG(SvANY(sv));
1377     break;
1378     default:
1379     Perl_croak(aTHX_ "Can't upgrade that kind of scalar");
1380     }
1381    
1382     switch (mt) {
1383     case SVt_NULL:
1384     Perl_croak(aTHX_ "Can't upgrade to undef");
1385     case SVt_IV:
1386     SvANY(sv) = new_XIV();
1387     SvIVX(sv) = iv;
1388     break;
1389     case SVt_NV:
1390     SvANY(sv) = new_XNV();
1391     SvNVX(sv) = nv;
1392     break;
1393     case SVt_RV:
1394     SvANY(sv) = new_XRV();
1395     SvRV(sv) = (SV*)pv;
1396     break;
1397     case SVt_PV:
1398     SvANY(sv) = new_XPV();
1399     SvPVX(sv) = pv;
1400     SvCUR(sv) = cur;
1401     SvLEN(sv) = len;
1402     break;
1403     case SVt_PVIV:
1404     SvANY(sv) = new_XPVIV();
1405     SvPVX(sv) = pv;
1406     SvCUR(sv) = cur;
1407     SvLEN(sv) = len;
1408     SvIVX(sv) = iv;
1409     if (SvNIOK(sv))
1410     (void)SvIOK_on(sv);
1411     SvNOK_off(sv);
1412     break;
1413     case SVt_PVNV:
1414     SvANY(sv) = new_XPVNV();
1415     SvPVX(sv) = pv;
1416     SvCUR(sv) = cur;
1417     SvLEN(sv) = len;
1418     SvIVX(sv) = iv;
1419     SvNVX(sv) = nv;
1420     break;
1421     case SVt_PVMG:
1422     SvANY(sv) = new_XPVMG();
1423     SvPVX(sv) = pv;
1424     SvCUR(sv) = cur;
1425     SvLEN(sv) = len;
1426     SvIVX(sv) = iv;
1427     SvNVX(sv) = nv;
1428     SvMAGIC(sv) = magic;
1429     SvSTASH(sv) = stash;
1430     break;
1431     case SVt_PVLV:
1432     SvANY(sv) = new_XPVLV();
1433     SvPVX(sv) = pv;
1434     SvCUR(sv) = cur;
1435     SvLEN(sv) = len;
1436     SvIVX(sv) = iv;
1437     SvNVX(sv) = nv;
1438     SvMAGIC(sv) = magic;
1439     SvSTASH(sv) = stash;
1440     LvTARGOFF(sv) = 0;
1441     LvTARGLEN(sv) = 0;
1442     LvTARG(sv) = 0;
1443     LvTYPE(sv) = 0;
1444     break;
1445     case SVt_PVAV:
1446     SvANY(sv) = new_XPVAV();
1447     if (pv)
1448     Safefree(pv);
1449     SvPVX(sv) = 0;
1450     AvMAX(sv) = -1;
1451     AvFILLp(sv) = -1;
1452     SvIVX(sv) = 0;
1453     SvNVX(sv) = 0.0;
1454     SvMAGIC(sv) = magic;
1455     SvSTASH(sv) = stash;
1456     AvALLOC(sv) = 0;
1457     AvARYLEN(sv) = 0;
1458     AvFLAGS(sv) = AVf_REAL;
1459     break;
1460     case SVt_PVHV:
1461     SvANY(sv) = new_XPVHV();
1462     if (pv)
1463     Safefree(pv);
1464     SvPVX(sv) = 0;
1465     HvFILL(sv) = 0;
1466     HvMAX(sv) = 0;
1467     HvTOTALKEYS(sv) = 0;
1468     HvPLACEHOLDERS(sv) = 0;
1469     SvMAGIC(sv) = magic;
1470     SvSTASH(sv) = stash;
1471     HvRITER(sv) = 0;
1472     HvEITER(sv) = 0;
1473     HvPMROOT(sv) = 0;
1474     HvNAME(sv) = 0;
1475     break;
1476     case SVt_PVCV:
1477     SvANY(sv) = new_XPVCV();
1478     Zero(SvANY(sv), 1, XPVCV);
1479     SvPVX(sv) = pv;
1480     SvCUR(sv) = cur;
1481     SvLEN(sv) = len;
1482     SvIVX(sv) = iv;
1483     SvNVX(sv) = nv;
1484     SvMAGIC(sv) = magic;
1485     SvSTASH(sv) = stash;
1486     break;
1487     case SVt_PVGV:
1488     SvANY(sv) = new_XPVGV();
1489     SvPVX(sv) = pv;
1490     SvCUR(sv) = cur;
1491     SvLEN(sv) = len;
1492     SvIVX(sv) = iv;
1493     SvNVX(sv) = nv;
1494     SvMAGIC(sv) = magic;
1495     SvSTASH(sv) = stash;
1496     GvGP(sv) = 0;
1497     GvNAME(sv) = 0;
1498     GvNAMELEN(sv) = 0;
1499     GvSTASH(sv) = 0;
1500     GvFLAGS(sv) = 0;
1501     break;
1502     case SVt_PVBM:
1503     SvANY(sv) = new_XPVBM();
1504     SvPVX(sv) = pv;
1505     SvCUR(sv) = cur;
1506     SvLEN(sv) = len;
1507     SvIVX(sv) = iv;
1508     SvNVX(sv) = nv;
1509     SvMAGIC(sv) = magic;
1510     SvSTASH(sv) = stash;
1511     BmRARE(sv) = 0;
1512     BmUSEFUL(sv) = 0;
1513     BmPREVIOUS(sv) = 0;
1514     break;
1515     case SVt_PVFM:
1516     SvANY(sv) = new_XPVFM();
1517     Zero(SvANY(sv), 1, XPVFM);
1518     SvPVX(sv) = pv;
1519     SvCUR(sv) = cur;
1520     SvLEN(sv) = len;
1521     SvIVX(sv) = iv;
1522     SvNVX(sv) = nv;
1523     SvMAGIC(sv) = magic;
1524     SvSTASH(sv) = stash;
1525     break;
1526     case SVt_PVIO:
1527     SvANY(sv) = new_XPVIO();
1528     Zero(SvANY(sv), 1, XPVIO);
1529     SvPVX(sv) = pv;
1530     SvCUR(sv) = cur;
1531     SvLEN(sv) = len;
1532     SvIVX(sv) = iv;
1533     SvNVX(sv) = nv;
1534     SvMAGIC(sv) = magic;
1535     SvSTASH(sv) = stash;
1536     IoPAGE_LEN(sv) = 60;
1537     break;
1538     }
1539     SvFLAGS(sv) &= ~SVTYPEMASK;
1540     SvFLAGS(sv) |= mt;
1541     return TRUE;
1542     }
1543    
1544     /*
1545     =for apidoc sv_backoff
1546    
1547     Remove any string offset. You should normally use the C<SvOOK_off> macro
1548     wrapper instead.
1549    
1550     =cut
1551     */
1552    
1553     int
1554     Perl_sv_backoff(pTHX_ register SV *sv)
1555     {
1556     assert(SvOOK(sv));
1557     if (SvIVX(sv)) {
1558     char *s = SvPVX(sv);
1559     SvLEN(sv) += SvIVX(sv);
1560     SvPVX(sv) -= SvIVX(sv);
1561     SvIV_set(sv, 0);
1562     Move(s, SvPVX(sv), SvCUR(sv)+1, char);
1563     }
1564     SvFLAGS(sv) &= ~SVf_OOK;
1565     return 0;
1566     }
1567    
1568     /*
1569     =for apidoc sv_grow
1570    
1571     Expands the character buffer in the SV. If necessary, uses C<sv_unref> and
1572     upgrades the SV to C<SVt_PV>. Returns a pointer to the character buffer.
1573     Use the C<SvGROW> wrapper instead.
1574    
1575     =cut
1576     */
1577    
1578     char *
1579     Perl_sv_grow(pTHX_ register SV *sv, register STRLEN newlen)
1580     {
1581     register char *s;
1582    
1583    
1584    
1585     #ifdef HAS_64K_LIMIT
1586     if (newlen >= 0x10000) {
1587     PerlIO_printf(Perl_debug_log,
1588     "Allocation too large: %"UVxf"\n", (UV)newlen);
1589     my_exit(1);
1590     }
1591     #endif /* HAS_64K_LIMIT */
1592     if (SvROK(sv))
1593     sv_unref(sv);
1594     if (SvTYPE(sv) < SVt_PV) {
1595     sv_upgrade(sv, SVt_PV);
1596     s = SvPVX(sv);
1597     }
1598     else if (SvOOK(sv)) { /* pv is offset? */
1599     sv_backoff(sv);
1600     s = SvPVX(sv);
1601     if (newlen > SvLEN(sv))
1602     newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1603     #ifdef HAS_64K_LIMIT
1604     if (newlen >= 0x10000)
1605     newlen = 0xFFFF;
1606     #endif
1607     }
1608     else
1609     s = SvPVX(sv);
1610    
1611     if (newlen > SvLEN(sv)) { /* need more room? */
1612     if (SvLEN(sv) && s) {
1613     #ifdef MYMALLOC
1614     STRLEN l = malloced_size((void*)SvPVX(sv));
1615     if (newlen <= l) {
1616     SvLEN_set(sv, l);
1617     return s;
1618     } else
1619     #endif
1620     Renew(s,newlen,char);
1621     }
1622     else {
1623     /* sv_force_normal_flags() must not try to unshare the new
1624     PVX we allocate below. AMS 20010713 */
1625     if (SvREADONLY(sv) && SvFAKE(sv)) {
1626     SvFAKE_off(sv);
1627     SvREADONLY_off(sv);
1628     }
1629     New(703, s, newlen, char);
1630     if (SvPVX(sv) && SvCUR(sv)) {
1631     Move(SvPVX(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1632     }
1633     }
1634     SvPV_set(sv, s);
1635     SvLEN_set(sv, newlen);
1636     }
1637     return s;
1638     }
1639    
1640     /*
1641     =for apidoc sv_setiv
1642    
1643     Copies an integer into the given SV, upgrading first if necessary.
1644     Does not handle 'set' magic. See also C<sv_setiv_mg>.
1645    
1646     =cut
1647     */
1648    
1649     void
1650     Perl_sv_setiv(pTHX_ register SV *sv, IV i)
1651     {
1652     SV_CHECK_THINKFIRST(sv);
1653     switch (SvTYPE(sv)) {
1654     case SVt_NULL:
1655     sv_upgrade(sv, SVt_IV);
1656     break;
1657     case SVt_NV:
1658     sv_upgrade(sv, SVt_PVNV);
1659     break;
1660     case SVt_RV:
1661     case SVt_PV:
1662     sv_upgrade(sv, SVt_PVIV);
1663     break;
1664    
1665     case SVt_PVGV:
1666     case SVt_PVAV:
1667     case SVt_PVHV:
1668     case SVt_PVCV:
1669     case SVt_PVFM:
1670     case SVt_PVIO:
1671     Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1672     OP_DESC(PL_op));
1673     }
1674     (void)SvIOK_only(sv); /* validate number */
1675     SvIVX(sv) = i;
1676     SvTAINT(sv);
1677     }
1678    
1679     /*
1680     =for apidoc sv_setiv_mg
1681    
1682     Like C<sv_setiv>, but also handles 'set' magic.
1683    
1684     =cut
1685     */
1686    
1687     void
1688     Perl_sv_setiv_mg(pTHX_ register SV *sv, IV i)
1689     {
1690     sv_setiv(sv,i);
1691     SvSETMAGIC(sv);
1692     }
1693    
1694     /*
1695     =for apidoc sv_setuv
1696    
1697     Copies an unsigned integer into the given SV, upgrading first if necessary.
1698     Does not handle 'set' magic. See also C<sv_setuv_mg>.
1699    
1700     =cut
1701     */
1702    
1703     void
1704     Perl_sv_setuv(pTHX_ register SV *sv, UV u)
1705     {
1706     /* With these two if statements:
1707     u=1.49 s=0.52 cu=72.49 cs=10.64 scripts=270 tests=20865
1708    
1709     without
1710     u=1.35 s=0.47 cu=73.45 cs=11.43 scripts=270 tests=20865
1711    
1712     If you wish to remove them, please benchmark to see what the effect is
1713     */
1714     if (u <= (UV)IV_MAX) {
1715     sv_setiv(sv, (IV)u);
1716     return;
1717     }
1718     sv_setiv(sv, 0);
1719     SvIsUV_on(sv);
1720     SvUVX(sv) = u;
1721     }
1722    
1723     /*
1724     =for apidoc sv_setuv_mg
1725    
1726     Like C<sv_setuv>, but also handles 'set' magic.
1727    
1728     =cut
1729     */
1730    
1731     void
1732     Perl_sv_setuv_mg(pTHX_ register SV *sv, UV u)
1733     {
1734     /* With these two if statements:
1735     u=1.49 s=0.52 cu=72.49 cs=10.64 scripts=270 tests=20865
1736    
1737     without
1738     u=1.35 s=0.47 cu=73.45 cs=11.43 scripts=270 tests=20865
1739    
1740     If you wish to remove them, please benchmark to see what the effect is
1741     */
1742     if (u <= (UV)IV_MAX) {
1743     sv_setiv(sv, (IV)u);
1744     } else {
1745     sv_setiv(sv, 0);
1746     SvIsUV_on(sv);
1747     sv_setuv(sv,u);
1748     }
1749     SvSETMAGIC(sv);
1750     }
1751    
1752     /*
1753     =for apidoc sv_setnv
1754    
1755     Copies a double into the given SV, upgrading first if necessary.
1756     Does not handle 'set' magic. See also C<sv_setnv_mg>.
1757    
1758     =cut
1759     */
1760    
1761     void
1762     Perl_sv_setnv(pTHX_ register SV *sv, NV num)
1763     {
1764     SV_CHECK_THINKFIRST(sv);
1765     switch (SvTYPE(sv)) {
1766     case SVt_NULL:
1767     case SVt_IV:
1768     sv_upgrade(sv, SVt_NV);
1769     break;
1770     case SVt_RV:
1771     case SVt_PV:
1772     case SVt_PVIV:
1773     sv_upgrade(sv, SVt_PVNV);
1774     break;
1775    
1776     case SVt_PVGV:
1777     case SVt_PVAV:
1778     case SVt_PVHV:
1779     case SVt_PVCV:
1780     case SVt_PVFM:
1781     case SVt_PVIO:
1782     Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
1783     OP_NAME(PL_op));
1784     }
1785     SvNVX(sv) = num;
1786     (void)SvNOK_only(sv); /* validate number */
1787     SvTAINT(sv);
1788     }
1789    
1790     /*
1791     =for apidoc sv_setnv_mg
1792    
1793     Like C<sv_setnv>, but also handles 'set' magic.
1794    
1795     =cut
1796     */
1797    
1798     void
1799     Perl_sv_setnv_mg(pTHX_ register SV *sv, NV num)
1800     {
1801     sv_setnv(sv,num);
1802     SvSETMAGIC(sv);
1803     }
1804    
1805     /* Print an "isn't numeric" warning, using a cleaned-up,
1806     * printable version of the offending string
1807     */
1808    
1809     STATIC void
1810     S_not_a_number(pTHX_ SV *sv)
1811     {
1812     SV *dsv;
1813     char tmpbuf[64];
1814     char *pv;
1815    
1816     if (DO_UTF8(sv)) {
1817     dsv = sv_2mortal(newSVpv("", 0));
1818     pv = sv_uni_display(dsv, sv, 10, 0);
1819     } else {
1820     char *d = tmpbuf;
1821     char *limit = tmpbuf + sizeof(tmpbuf) - 8;
1822     /* each *s can expand to 4 chars + "...\0",
1823     i.e. need room for 8 chars */
1824    
1825     char *s, *end;
1826     for (s = SvPVX(sv), end = s + SvCUR(sv); s < end && d < limit; s++) {
1827     int ch = *s & 0xFF;
1828     if (ch & 128 && !isPRINT_LC(ch)) {
1829     *d++ = 'M';
1830     *d++ = '-';
1831     ch &= 127;
1832     }
1833     if (ch == '\n') {
1834     *d++ = '\\';
1835     *d++ = 'n';
1836     }
1837     else if (ch == '\r') {
1838     *d++ = '\\';
1839     *d++ = 'r';
1840     }
1841     else if (ch == '\f') {
1842     *d++ = '\\';
1843     *d++ = 'f';
1844     }
1845     else if (ch == '\\') {
1846     *d++ = '\\';
1847     *d++ = '\\';
1848     }
1849     else if (ch == '\0') {
1850     *d++ = '\\';
1851     *d++ = '0';
1852     }
1853     else if (isPRINT_LC(ch))
1854     *d++ = ch;
1855     else {
1856     *d++ = '^';
1857     *d++ = toCTRL(ch);
1858     }
1859     }
1860     if (s < end) {
1861     *d++ = '.';
1862     *d++ = '.';
1863     *d++ = '.';
1864     }
1865     *d = '\0';
1866     pv = tmpbuf;
1867     }
1868    
1869     if (PL_op)
1870     Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1871     "Argument \"%s\" isn't numeric in %s", pv,
1872     OP_DESC(PL_op));
1873     else
1874     Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1875     "Argument \"%s\" isn't numeric", pv);
1876     }
1877    
1878     /*
1879     =for apidoc looks_like_number
1880    
1881     Test if the content of an SV looks like a number (or is a number).
1882     C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1883     non-numeric warning), even if your atof() doesn't grok them.
1884    
1885     =cut
1886     */
1887    
1888     I32
1889     Perl_looks_like_number(pTHX_ SV *sv)
1890     {
1891     register char *sbegin;
1892     STRLEN len;
1893    
1894     if (SvPOK(sv)) {
1895     sbegin = SvPVX(sv);
1896     len = SvCUR(sv);
1897     }
1898     else if (SvPOKp(sv))
1899     sbegin = SvPV(sv, len);
1900     else
1901     return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
1902     return grok_number(sbegin, len, NULL);
1903     }
1904    
1905     /* Actually, ISO C leaves conversion of UV to IV undefined, but
1906     until proven guilty, assume that things are not that bad... */
1907    
1908     /*
1909     NV_PRESERVES_UV:
1910    
1911     As 64 bit platforms often have an NV that doesn't preserve all bits of
1912     an IV (an assumption perl has been based on to date) it becomes necessary
1913     to remove the assumption that the NV always carries enough precision to
1914     recreate the IV whenever needed, and that the NV is the canonical form.
1915     Instead, IV/UV and NV need to be given equal rights. So as to not lose
1916     precision as a side effect of conversion (which would lead to insanity
1917     and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1918     1) to distinguish between IV/UV/NV slots that have cached a valid
1919     conversion where precision was lost and IV/UV/NV slots that have a
1920     valid conversion which has lost no precision
1921     2) to ensure that if a numeric conversion to one form is requested that
1922     would lose precision, the precise conversion (or differently
1923     imprecise conversion) is also performed and cached, to prevent
1924     requests for different numeric formats on the same SV causing
1925     lossy conversion chains. (lossless conversion chains are perfectly
1926     acceptable (still))
1927    
1928    
1929     flags are used:
1930     SvIOKp is true if the IV slot contains a valid value
1931     SvIOK is true only if the IV value is accurate (UV if SvIOK_UV true)
1932     SvNOKp is true if the NV slot contains a valid value
1933     SvNOK is true only if the NV value is accurate
1934    
1935     so
1936     while converting from PV to NV, check to see if converting that NV to an
1937     IV(or UV) would lose accuracy over a direct conversion from PV to
1938     IV(or UV). If it would, cache both conversions, return NV, but mark
1939     SV as IOK NOKp (ie not NOK).
1940    
1941     While converting from PV to IV, check to see if converting that IV to an
1942     NV would lose accuracy over a direct conversion from PV to NV. If it
1943     would, cache both conversions, flag similarly.
1944    
1945     Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1946     correctly because if IV & NV were set NV *always* overruled.
1947     Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1948     changes - now IV and NV together means that the two are interchangeable:
1949     SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
1950    
1951     The benefit of this is that operations such as pp_add know that if
1952     SvIOK is true for both left and right operands, then integer addition
1953     can be used instead of floating point (for cases where the result won't
1954     overflow). Before, floating point was always used, which could lead to
1955     loss of precision compared with integer addition.
1956    
1957     * making IV and NV equal status should make maths accurate on 64 bit
1958     platforms
1959     * may speed up maths somewhat if pp_add and friends start to use
1960     integers when possible instead of fp. (Hopefully the overhead in
1961     looking for SvIOK and checking for overflow will not outweigh the
1962     fp to integer speedup)
1963     * will slow down integer operations (callers of SvIV) on "inaccurate"
1964     values, as the change from SvIOK to SvIOKp will cause a call into
1965     sv_2iv each time rather than a macro access direct to the IV slot
1966     * should speed up number->string conversion on integers as IV is
1967     favoured when IV and NV are equally accurate
1968    
1969     ####################################################################
1970     You had better be using SvIOK_notUV if you want an IV for arithmetic:
1971     SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
1972     On the other hand, SvUOK is true iff UV.
1973     ####################################################################
1974    
1975     Your mileage will vary depending your CPU's relative fp to integer
1976     performance ratio.
1977     */
1978    
1979     #ifndef NV_PRESERVES_UV
1980     # define IS_NUMBER_UNDERFLOW_IV 1
1981     # define IS_NUMBER_UNDERFLOW_UV 2
1982     # define IS_NUMBER_IV_AND_UV 2
1983     # define IS_NUMBER_OVERFLOW_IV 4
1984     # define IS_NUMBER_OVERFLOW_UV 5
1985    
1986     /* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
1987    
1988     /* For sv_2nv these three cases are "SvNOK and don't bother casting" */
1989     STATIC int
1990     S_sv_2iuv_non_preserve(pTHX_ register SV *sv, I32 numtype)
1991     {
1992     DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_2iuv_non '%s', IV=0x%"UVxf" NV=%"NVgf" inttype=%"UVXf"\n", SvPVX(sv), SvIVX(sv), SvNVX(sv), (UV)numtype));
1993     if (SvNVX(sv) < (NV)IV_MIN) {
1994     (void)SvIOKp_on(sv);
1995     (void)SvNOK_on(sv);
1996     SvIVX(sv) = IV_MIN;
1997     return IS_NUMBER_UNDERFLOW_IV;
1998     }
1999     if (SvNVX(sv) > (NV)UV_MAX) {
2000     (void)SvIOKp_on(sv);
2001     (void)SvNOK_on(sv);
2002     SvIsUV_on(sv);
2003     SvUVX(sv) = UV_MAX;
2004     return IS_NUMBER_OVERFLOW_UV;
2005     }
2006     (void)SvIOKp_on(sv);
2007     (void)SvNOK_on(sv);
2008     /* Can't use strtol etc to convert this string. (See truth table in
2009     sv_2iv */
2010     if (SvNVX(sv) <= (UV)IV_MAX) {
2011     SvIVX(sv) = I_V(SvNVX(sv));
2012     if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2013     SvIOK_on(sv); /* Integer is precise. NOK, IOK */
2014     } else {
2015     /* Integer is imprecise. NOK, IOKp */
2016     }
2017     return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
2018     }
2019     SvIsUV_on(sv);
2020     SvUVX(sv) = U_V(SvNVX(sv));
2021     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2022     if (SvUVX(sv) == UV_MAX) {
2023     /* As we know that NVs don't preserve UVs, UV_MAX cannot
2024     possibly be preserved by NV. Hence, it must be overflow.
2025     NOK, IOKp */
2026     return IS_NUMBER_OVERFLOW_UV;
2027     }
2028     SvIOK_on(sv); /* Integer is precise. NOK, UOK */
2029     } else {
2030     /* Integer is imprecise. NOK, IOKp */
2031     }
2032     return IS_NUMBER_OVERFLOW_IV;
2033     }
2034     #endif /* !NV_PRESERVES_UV*/
2035    
2036     /*
2037     =for apidoc sv_2iv
2038    
2039     Return the integer value of an SV, doing any necessary string conversion,
2040     magic etc. Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2041    
2042     =cut
2043     */
2044    
2045     IV
2046     Perl_sv_2iv(pTHX_ register SV *sv)
2047     {
2048     if (!sv)
2049     return 0;
2050     if (SvGMAGICAL(sv)) {
2051     mg_get(sv);
2052     if (SvIOKp(sv))
2053     return SvIVX(sv);
2054     if (SvNOKp(sv)) {
2055     return I_V(SvNVX(sv));
2056     }
2057     if (SvPOKp(sv) && SvLEN(sv))
2058     return asIV(sv);
2059     if (!SvROK(sv)) {
2060     if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2061     if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2062     report_uninit();
2063     }
2064     return 0;
2065     }
2066     }
2067     if (SvTHINKFIRST(sv)) {
2068     if (SvROK(sv)) {
2069     SV* tmpstr;
2070     if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,numer)) &&
2071     (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv))))
2072     return SvIV(tmpstr);
2073     return PTR2IV(SvRV(sv));
2074     }
2075     if (SvREADONLY(sv) && SvFAKE(sv)) {
2076     sv_force_normal(sv);
2077     }
2078     if (SvREADONLY(sv) && !SvOK(sv)) {
2079     if (ckWARN(WARN_UNINITIALIZED))
2080     report_uninit();
2081     return 0;
2082     }
2083     }
2084     if (SvIOKp(sv)) {
2085     if (SvIsUV(sv)) {
2086     return (IV)(SvUVX(sv));
2087     }
2088     else {
2089     return SvIVX(sv);
2090     }
2091     }
2092     if (SvNOKp(sv)) {
2093     /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
2094     * without also getting a cached IV/UV from it at the same time
2095     * (ie PV->NV conversion should detect loss of accuracy and cache
2096     * IV or UV at same time to avoid this. NWC */
2097    
2098     if (SvTYPE(sv) == SVt_NV)
2099     sv_upgrade(sv, SVt_PVNV);
2100    
2101     (void)SvIOKp_on(sv); /* Must do this first, to clear any SvOOK */
2102     /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
2103     certainly cast into the IV range at IV_MAX, whereas the correct
2104     answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
2105     cases go to UV */
2106     if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2107     SvIVX(sv) = I_V(SvNVX(sv));
2108     if (SvNVX(sv) == (NV) SvIVX(sv)
2109     #ifndef NV_PRESERVES_UV
2110     && (((UV)1 << NV_PRESERVES_UV_BITS) >
2111     (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2112     /* Don't flag it as "accurately an integer" if the number
2113     came from a (by definition imprecise) NV operation, and
2114     we're outside the range of NV integer precision */
2115     #endif
2116     ) {
2117     SvIOK_on(sv); /* Can this go wrong with rounding? NWC */
2118     DEBUG_c(PerlIO_printf(Perl_debug_log,
2119     "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
2120     PTR2UV(sv),
2121     SvNVX(sv),
2122     SvIVX(sv)));
2123    
2124     } else {
2125     /* IV not precise. No need to convert from PV, as NV
2126     conversion would already have cached IV if it detected
2127     that PV->IV would be better than PV->NV->IV
2128     flags already correct - don't set public IOK. */
2129     DEBUG_c(PerlIO_printf(Perl_debug_log,
2130     "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
2131     PTR2UV(sv),
2132     SvNVX(sv),
2133     SvIVX(sv)));
2134     }
2135     /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2136     but the cast (NV)IV_MIN rounds to a the value less (more
2137     negative) than IV_MIN which happens to be equal to SvNVX ??
2138     Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2139     NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2140     (NV)UVX == NVX are both true, but the values differ. :-(
2141     Hopefully for 2s complement IV_MIN is something like
2142     0x8000000000000000 which will be exact. NWC */
2143     }
2144     else {
2145     SvUVX(sv) = U_V(SvNVX(sv));
2146     if (
2147     (SvNVX(sv) == (NV) SvUVX(sv))
2148     #ifndef NV_PRESERVES_UV
2149     /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2150     /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2151     && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2152     /* Don't flag it as "accurately an integer" if the number
2153     came from a (by definition imprecise) NV operation, and
2154     we're outside the range of NV integer precision */
2155     #endif
2156     )
2157     SvIOK_on(sv);
2158     SvIsUV_on(sv);
2159     ret_iv_max:
2160     DEBUG_c(PerlIO_printf(Perl_debug_log,
2161     "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
2162     PTR2UV(sv),
2163     SvUVX(sv),
2164     SvUVX(sv)));
2165     return (IV)SvUVX(sv);
2166     }
2167     }
2168     else if (SvPOKp(sv) && SvLEN(sv)) {
2169     UV value;
2170     int numtype = grok_number(SvPVX(sv), SvCUR(sv), &value);
2171     /* We want to avoid a possible problem when we cache an IV which
2172     may be later translated to an NV, and the resulting NV is not
2173     the same as the direct translation of the initial string
2174     (eg 123.456 can shortcut to the IV 123 with atol(), but we must
2175     be careful to ensure that the value with the .456 is around if the
2176     NV value is requested in the future).
2177    
2178     This means that if we cache such an IV, we need to cache the
2179     NV as well. Moreover, we trade speed for space, and do not
2180     cache the NV if we are sure it's not needed.
2181     */
2182    
2183     /* SVt_PVNV is one higher than SVt_PVIV, hence this order */
2184     if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2185     == IS_NUMBER_IN_UV) {
2186     /* It's definitely an integer, only upgrade to PVIV */
2187     if (SvTYPE(sv) < SVt_PVIV)
2188     sv_upgrade(sv, SVt_PVIV);
2189     (void)SvIOK_on(sv);
2190     } else if (SvTYPE(sv) < SVt_PVNV)
2191     sv_upgrade(sv, SVt_PVNV);
2192    
2193     /* If NV preserves UV then we only use the UV value if we know that
2194     we aren't going to call atof() below. If NVs don't preserve UVs
2195     then the value returned may have more precision than atof() will
2196     return, even though value isn't perfectly accurate. */
2197     if ((numtype & (IS_NUMBER_IN_UV
2198     #ifdef NV_PRESERVES_UV
2199     | IS_NUMBER_NOT_INT
2200     #endif
2201     )) == IS_NUMBER_IN_UV) {
2202     /* This won't turn off the public IOK flag if it was set above */
2203     (void)SvIOKp_on(sv);
2204    
2205     if (!(numtype & IS_NUMBER_NEG)) {
2206     /* positive */;
2207     if (value <= (UV)IV_MAX) {
2208     SvIVX(sv) = (IV)value;
2209     } else {
2210     SvUVX(sv) = value;
2211     SvIsUV_on(sv);
2212     }
2213     } else {
2214     /* 2s complement assumption */
2215     if (value <= (UV)IV_MIN) {
2216     SvIVX(sv) = -(IV)value;
2217     } else {
2218     /* Too negative for an IV. This is a double upgrade, but
2219     I'm assuming it will be rare. */
2220     if (SvTYPE(sv) < SVt_PVNV)
2221     sv_upgrade(sv, SVt_PVNV);
2222     SvNOK_on(sv);
2223     SvIOK_off(sv);
2224     SvIOKp_on(sv);
2225     SvNVX(sv) = -(NV)value;
2226     SvIVX(sv) = IV_MIN;
2227     }
2228     }
2229     }
2230     /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2231     will be in the previous block to set the IV slot, and the next
2232     block to set the NV slot. So no else here. */
2233    
2234     if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2235     != IS_NUMBER_IN_UV) {
2236     /* It wasn't an (integer that doesn't overflow the UV). */
2237     SvNVX(sv) = Atof(SvPVX(sv));
2238    
2239     if (! numtype && ckWARN(WARN_NUMERIC))
2240     not_a_number(sv);
2241    
2242     #if defined(USE_LONG_DOUBLE)
2243     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" PERL_PRIgldbl ")\n",
2244     PTR2UV(sv), SvNVX(sv)));
2245     #else
2246     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"NVgf")\n",
2247     PTR2UV(sv), SvNVX(sv)));
2248     #endif
2249    
2250    
2251     #ifdef NV_PRESERVES_UV
2252     (void)SvIOKp_on(sv);
2253     (void)SvNOK_on(sv);
2254     if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2255     SvIVX(sv) = I_V(SvNVX(sv));
2256     if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2257     SvIOK_on(sv);
2258     } else {
2259     /* Integer is imprecise. NOK, IOKp */
2260     }
2261     /* UV will not work better than IV */
2262     } else {
2263     if (SvNVX(sv) > (NV)UV_MAX) {
2264     SvIsUV_on(sv);
2265     /* Integer is inaccurate. NOK, IOKp, is UV */
2266     SvUVX(sv) = UV_MAX;
2267     SvIsUV_on(sv);
2268     } else {
2269     SvUVX(sv) = U_V(SvNVX(sv));
2270     /* 0xFFFFFFFFFFFFFFFF not an issue in here */
2271     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2272     SvIOK_on(sv);
2273     SvIsUV_on(sv);
2274     } else {
2275     /* Integer is imprecise. NOK, IOKp, is UV */
2276     SvIsUV_on(sv);
2277     }
2278     }
2279     goto ret_iv_max;
2280     }
2281     #else /* NV_PRESERVES_UV */
2282     if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2283     == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2284     /* The IV slot will have been set from value returned by
2285     grok_number above. The NV slot has just been set using
2286     Atof. */
2287     SvNOK_on(sv);
2288     assert (SvIOKp(sv));
2289     } else {
2290     if (((UV)1 << NV_PRESERVES_UV_BITS) >
2291     U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2292     /* Small enough to preserve all bits. */
2293     (void)SvIOKp_on(sv);
2294     SvNOK_on(sv);
2295     SvIVX(sv) = I_V(SvNVX(sv));
2296     if ((NV)(SvIVX(sv)) == SvNVX(sv))
2297     SvIOK_on(sv);
2298     /* Assumption: first non-preserved integer is < IV_MAX,
2299     this NV is in the preserved range, therefore: */
2300     if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2301     < (UV)IV_MAX)) {
2302     Perl_croak(aTHX_ "sv_2iv assumed (U_V(fabs((double)SvNVX(sv))) < (UV)IV_MAX) but SvNVX(sv)=%"NVgf" U_V is 0x%"UVxf", IV_MAX is 0x%"UVxf"\n", SvNVX(sv), U_V(SvNVX(sv)), (UV)IV_MAX);
2303     }
2304     } else {
2305     /* IN_UV NOT_INT
2306     0 0 already failed to read UV.
2307     0 1 already failed to read UV.
2308     1 0 you won't get here in this case. IV/UV
2309     slot set, public IOK, Atof() unneeded.
2310     1 1 already read UV.
2311     so there's no point in sv_2iuv_non_preserve() attempting
2312     to use atol, strtol, strtoul etc. */
2313     if (sv_2iuv_non_preserve (sv, numtype)
2314     >= IS_NUMBER_OVERFLOW_IV)
2315     goto ret_iv_max;
2316     }
2317     }
2318     #endif /* NV_PRESERVES_UV */
2319     }
2320     } else {
2321     if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP))
2322     report_uninit();
2323     if (SvTYPE(sv) < SVt_IV)
2324     /* Typically the caller expects that sv_any is not NULL now. */
2325     sv_upgrade(sv, SVt_IV);
2326     return 0;
2327     }
2328     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2329     PTR2UV(sv),SvIVX(sv)));
2330     return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
2331     }
2332    
2333     /*
2334     =for apidoc sv_2uv
2335    
2336     Return the unsigned integer value of an SV, doing any necessary string
2337     conversion, magic etc. Normally used via the C<SvUV(sv)> and C<SvUVx(sv)>
2338     macros.
2339    
2340     =cut
2341     */
2342    
2343     UV
2344     Perl_sv_2uv(pTHX_ register SV *sv)
2345     {
2346     if (!sv)
2347     return 0;
2348     if (SvGMAGICAL(sv)) {
2349     mg_get(sv);
2350     if (SvIOKp(sv))
2351     return SvUVX(sv);
2352     if (SvNOKp(sv))
2353     return U_V(SvNVX(sv));
2354     if (SvPOKp(sv) && SvLEN(sv))
2355     return asUV(sv);
2356     if (!SvROK(sv)) {
2357     if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2358     if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2359     report_uninit();
2360     }
2361     return 0;
2362     }
2363     }
2364     if (SvTHINKFIRST(sv)) {
2365     if (SvROK(sv)) {
2366     SV* tmpstr;
2367     if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,numer)) &&
2368     (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv))))
2369     return SvUV(tmpstr);
2370     return PTR2UV(SvRV(sv));
2371     }
2372     if (SvREADONLY(sv) && SvFAKE(sv)) {
2373     sv_force_normal(sv);
2374     }
2375     if (SvREADONLY(sv) && !SvOK(sv)) {
2376     if (ckWARN(WARN_UNINITIALIZED))
2377     report_uninit();
2378     return 0;
2379     }
2380     }
2381     if (SvIOKp(sv)) {
2382     if (SvIsUV(sv)) {
2383     return SvUVX(sv);
2384     }
2385     else {
2386     return (UV)SvIVX(sv);
2387     }
2388     }
2389     if (SvNOKp(sv)) {
2390     /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
2391     * without also getting a cached IV/UV from it at the same time
2392     * (ie PV->NV conversion should detect loss of accuracy and cache
2393     * IV or UV at same time to avoid this. */
2394     /* IV-over-UV optimisation - choose to cache IV if possible */
2395    
2396     if (SvTYPE(sv) == SVt_NV)
2397     sv_upgrade(sv, SVt_PVNV);
2398    
2399     (void)SvIOKp_on(sv); /* Must do this first, to clear any SvOOK */
2400     if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2401     SvIVX(sv) = I_V(SvNVX(sv));
2402     if (SvNVX(sv) == (NV) SvIVX(sv)
2403     #ifndef NV_PRESERVES_UV
2404     && (((UV)1 << NV_PRESERVES_UV_BITS) >
2405     (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2406     /* Don't flag it as "accurately an integer" if the number
2407     came from a (by definition imprecise) NV operation, and
2408     we're outside the range of NV integer precision */
2409     #endif
2410     ) {
2411     SvIOK_on(sv); /* Can this go wrong with rounding? NWC */
2412     DEBUG_c(PerlIO_printf(Perl_debug_log,
2413     "0x%"UVxf" uv(%"NVgf" => %"IVdf") (precise)\n",
2414     PTR2UV(sv),
2415     SvNVX(sv),
2416     SvIVX(sv)));
2417    
2418     } else {
2419     /* IV not precise. No need to convert from PV, as NV
2420     conversion would already have cached IV if it detected
2421     that PV->IV would be better than PV->NV->IV
2422     flags already correct - don't set public IOK. */
2423     DEBUG_c(PerlIO_printf(Perl_debug_log,
2424     "0x%"UVxf" uv(%"NVgf" => %"IVdf") (imprecise)\n",
2425     PTR2UV(sv),
2426     SvNVX(sv),
2427     SvIVX(sv)));
2428     }
2429     /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2430     but the cast (NV)IV_MIN rounds to a the value less (more
2431     negative) than IV_MIN which happens to be equal to SvNVX ??
2432     Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2433     NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2434     (NV)UVX == NVX are both true, but the values differ. :-(
2435     Hopefully for 2s complement IV_MIN is something like
2436     0x8000000000000000 which will be exact. NWC */
2437     }
2438     else {
2439     SvUVX(sv) = U_V(SvNVX(sv));
2440     if (
2441     (SvNVX(sv) == (NV) SvUVX(sv))
2442     #ifndef NV_PRESERVES_UV
2443     /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2444     /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2445     && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2446     /* Don't flag it as "accurately an integer" if the number
2447     came from a (by definition imprecise) NV operation, and
2448     we're outside the range of NV integer precision */
2449     #endif
2450     )
2451     SvIOK_on(sv);
2452     SvIsUV_on(sv);
2453     DEBUG_c(PerlIO_printf(Perl_debug_log,
2454     "0x%"UVxf" 2uv(%"UVuf" => %"IVdf") (as unsigned)\n",
2455     PTR2UV(sv),
2456     SvUVX(sv),
2457     SvUVX(sv)));
2458     }
2459     }
2460     else if (SvPOKp(sv) && SvLEN(sv)) {
2461     UV value;
2462     int numtype = grok_number(SvPVX(sv), SvCUR(sv), &value);
2463    
2464     /* We want to avoid a possible problem when we cache a UV which
2465     may be later translated to an NV, and the resulting NV is not
2466     the translation of the initial data.
2467    
2468     This means that if we cache such a UV, we need to cache the
2469     NV as well. Moreover, we trade speed for space, and do not
2470     cache the NV if not needed.
2471     */
2472    
2473     /* SVt_PVNV is one higher than SVt_PVIV, hence this order */
2474     if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2475     == IS_NUMBER_IN_UV) {
2476     /* It's definitely an integer, only upgrade to PVIV */
2477     if (SvTYPE(sv) < SVt_PVIV)
2478     sv_upgrade(sv, SVt_PVIV);
2479     (void)SvIOK_on(sv);
2480     } else if (SvTYPE(sv) < SVt_PVNV)
2481     sv_upgrade(sv, SVt_PVNV);
2482    
2483     /* If NV preserves UV then we only use the UV value if we know that
2484     we aren't going to call atof() below. If NVs don't preserve UVs
2485     then the value returned may have more precision than atof() will
2486     return, even though it isn't accurate. */
2487     if ((numtype & (IS_NUMBER_IN_UV
2488     #ifdef NV_PRESERVES_UV
2489     | IS_NUMBER_NOT_INT
2490     #endif
2491     )) == IS_NUMBER_IN_UV) {
2492     /* This won't turn off the public IOK flag if it was set above */
2493     (void)SvIOKp_on(sv);
2494    
2495     if (!(numtype & IS_NUMBER_NEG)) {
2496     /* positive */;
2497     if (value <= (UV)IV_MAX) {
2498     SvIVX(sv) = (IV)value;
2499     } else {
2500     /* it didn't overflow, and it was positive. */
2501     SvUVX(sv) = value;
2502     SvIsUV_on(sv);
2503     }
2504     } else {
2505     /* 2s complement assumption */
2506     if (value <= (UV)IV_MIN) {
2507     SvIVX(sv) = -(IV)value;
2508     } else {
2509     /* Too negative for an IV. This is a double upgrade, but
2510     I'm assuming it will be rare. */
2511     if (SvTYPE(sv) < SVt_PVNV)
2512     sv_upgrade(sv, SVt_PVNV);
2513     SvNOK_on(sv);
2514     SvIOK_off(sv);
2515     SvIOKp_on(sv);
2516     SvNVX(sv) = -(NV)value;
2517     SvIVX(sv) = IV_MIN;
2518     }
2519     }
2520     }
2521    
2522     if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2523     != IS_NUMBER_IN_UV) {
2524     /* It wasn't an integer, or it overflowed the UV. */
2525     SvNVX(sv) = Atof(SvPVX(sv));
2526    
2527     if (! numtype && ckWARN(WARN_NUMERIC))
2528     not_a_number(sv);
2529    
2530     #if defined(USE_LONG_DOUBLE)
2531     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%" PERL_PRIgldbl ")\n",
2532     PTR2UV(sv), SvNVX(sv)));
2533     #else
2534     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"NVgf")\n",
2535     PTR2UV(sv), SvNVX(sv)));
2536     #endif
2537    
2538     #ifdef NV_PRESERVES_UV
2539     (void)SvIOKp_on(sv);
2540     (void)SvNOK_on(sv);
2541     if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2542     SvIVX(sv) = I_V(SvNVX(sv));
2543     if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2544     SvIOK_on(sv);
2545     } else {
2546     /* Integer is imprecise. NOK, IOKp */
2547     }
2548     /* UV will not work better than IV */
2549     } else {
2550     if (SvNVX(sv) > (NV)UV_MAX) {
2551     SvIsUV_on(sv);
2552     /* Integer is inaccurate. NOK, IOKp, is UV */
2553     SvUVX(sv) = UV_MAX;
2554     SvIsUV_on(sv);
2555     } else {
2556     SvUVX(sv) = U_V(SvNVX(sv));
2557     /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2558     NV preservse UV so can do correct comparison. */
2559     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2560     SvIOK_on(sv);
2561     SvIsUV_on(sv);
2562     } else {
2563     /* Integer is imprecise. NOK, IOKp, is UV */
2564     SvIsUV_on(sv);
2565     }
2566     }
2567     }
2568     #else /* NV_PRESERVES_UV */
2569     if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2570     == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2571     /* The UV slot will have been set from value returned by
2572     grok_number above. The NV slot has just been set using
2573     Atof. */
2574     SvNOK_on(sv);
2575     assert (SvIOKp(sv));
2576     } else {
2577     if (((UV)1 << NV_PRESERVES_UV_BITS) >
2578     U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2579     /* Small enough to preserve all bits. */
2580     (void)SvIOKp_on(sv);
2581     SvNOK_on(sv);
2582     SvIVX(sv) = I_V(SvNVX(sv));
2583     if ((NV)(SvIVX(sv)) == SvNVX(sv))
2584     SvIOK_on(sv);
2585     /* Assumption: first non-preserved integer is < IV_MAX,
2586     this NV is in the preserved range, therefore: */
2587     if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2588     < (UV)IV_MAX)) {
2589     Perl_croak(aTHX_ "sv_2uv assumed (U_V(fabs((double)SvNVX(sv))) < (UV)IV_MAX) but SvNVX(sv)=%"NVgf" U_V is 0x%"UVxf", IV_MAX is 0x%"UVxf"\n", SvNVX(sv), U_V(SvNVX(sv)), (UV)IV_MAX);
2590     }
2591     } else
2592     sv_2iuv_non_preserve (sv, numtype);
2593     }
2594     #endif /* NV_PRESERVES_UV */
2595     }
2596     }
2597     else {
2598     if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2599     if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2600     report_uninit();
2601     }
2602     if (SvTYPE(sv) < SVt_IV)
2603     /* Typically the caller expects that sv_any is not NULL now. */
2604     sv_upgrade(sv, SVt_IV);
2605     return 0;
2606     }
2607    
2608     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2609     PTR2UV(sv),SvUVX(sv)));
2610     return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
2611     }
2612    
2613     /*
2614     =for apidoc sv_2nv
2615    
2616     Return the num value of an SV, doing any necessary string or integer
2617     conversion, magic etc. Normally used via the C<SvNV(sv)> and C<SvNVx(sv)>
2618     macros.
2619    
2620     =cut
2621     */
2622    
2623     NV
2624     Perl_sv_2nv(pTHX_ register SV *sv)
2625     {
2626     if (!sv)
2627     return 0.0;
2628     if (SvGMAGICAL(sv)) {
2629     mg_get(sv);
2630     if (SvNOKp(sv))
2631     return SvNVX(sv);
2632     if (SvPOKp(sv) && SvLEN(sv)) {
2633     if (ckWARN(WARN_NUMERIC) && !SvIOKp(sv) &&
2634     !grok_number(SvPVX(sv), SvCUR(sv), NULL))
2635     not_a_number(sv);
2636     return Atof(SvPVX(sv));
2637     }
2638     if (SvIOKp(sv)) {
2639     if (SvIsUV(sv))
2640     return (NV)SvUVX(sv);
2641     else
2642     return (NV)SvIVX(sv);
2643     }
2644     if (!SvROK(sv)) {
2645     if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2646     if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2647     report_uninit();
2648     }
2649     return 0;
2650     }
2651     }
2652     if (SvTHINKFIRST(sv)) {
2653     if (SvROK(sv)) {
2654     SV* tmpstr;
2655     if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,numer)) &&
2656     (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv))))
2657     return SvNV(tmpstr);
2658     return PTR2NV(SvRV(sv));
2659     }
2660     if (SvREADONLY(sv) && SvFAKE(sv)) {
2661     sv_force_normal(sv);
2662     }
2663     if (SvREADONLY(sv) && !SvOK(sv)) {
2664     if (ckWARN(WARN_UNINITIALIZED))
2665     report_uninit();
2666     return 0.0;
2667     }
2668     }
2669     if (SvTYPE(sv) < SVt_NV) {
2670     if (SvTYPE(sv) == SVt_IV)
2671     sv_upgrade(sv, SVt_PVNV);
2672     else
2673     sv_upgrade(sv, SVt_NV);
2674     #ifdef USE_LONG_DOUBLE
2675     DEBUG_c({
2676     STORE_NUMERIC_LOCAL_SET_STANDARD();
2677     PerlIO_printf(Perl_debug_log,
2678     "0x%"UVxf" num(%" PERL_PRIgldbl ")\n",
2679     PTR2UV(sv), SvNVX(sv));
2680     RESTORE_NUMERIC_LOCAL();
2681     });
2682     #else
2683     DEBUG_c({
2684     STORE_NUMERIC_LOCAL_SET_STANDARD();
2685     PerlIO_printf(Perl_debug_log, "0x%"UVxf" num(%"NVgf")\n",
2686     PTR2UV(sv), SvNVX(sv));
2687     RESTORE_NUMERIC_LOCAL();
2688     });
2689     #endif
2690     }
2691     else if (SvTYPE(sv) < SVt_PVNV)
2692     sv_upgrade(sv, SVt_PVNV);
2693     if (SvNOKp(sv)) {
2694     return SvNVX(sv);
2695     }
2696     if (SvIOKp(sv)) {
2697     SvNVX(sv) = SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv);
2698     #ifdef NV_PRESERVES_UV
2699     SvNOK_on(sv);
2700     #else
2701     /* Only set the public NV OK flag if this NV preserves the IV */
2702     /* Check it's not 0xFFFFFFFFFFFFFFFF */
2703     if (SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
2704     : (SvIVX(sv) == I_V(SvNVX(sv))))
2705     SvNOK_on(sv);
2706     else
2707     SvNOKp_on(sv);
2708     #endif
2709     }
2710     else if (SvPOKp(sv) && SvLEN(sv)) {
2711     UV value;
2712     int numtype = grok_number(SvPVX(sv), SvCUR(sv), &value);
2713     if (ckWARN(WARN_NUMERIC) && !SvIOKp(sv) && !numtype)
2714     not_a_number(sv);
2715     #ifdef NV_PRESERVES_UV
2716     if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2717     == IS_NUMBER_IN_UV) {
2718     /* It's definitely an integer */
2719     SvNVX(sv) = (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value;
2720     } else
2721     SvNVX(sv) = Atof(SvPVX(sv));
2722     SvNOK_on(sv);
2723     #else
2724     SvNVX(sv) = Atof(SvPVX(sv));
2725     /* Only set the public NV OK flag if this NV preserves the value in
2726     the PV at least as well as an IV/UV would.
2727     Not sure how to do this 100% reliably. */
2728     /* if that shift count is out of range then Configure's test is
2729     wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2730     UV_BITS */
2731     if (((UV)1 << NV_PRESERVES_UV_BITS) >
2732     U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2733     SvNOK_on(sv); /* Definitely small enough to preserve all bits */
2734     } else if (!(numtype & IS_NUMBER_IN_UV)) {
2735     /* Can't use strtol etc to convert this string, so don't try.
2736     sv_2iv and sv_2uv will use the NV to convert, not the PV. */
2737     SvNOK_on(sv);
2738     } else {
2739     /* value has been set. It may not be precise. */
2740     if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2741     /* 2s complement assumption for (UV)IV_MIN */
2742     SvNOK_on(sv); /* Integer is too negative. */
2743     } else {
2744     SvNOKp_on(sv);
2745     SvIOKp_on(sv);
2746    
2747     if (numtype & IS_NUMBER_NEG) {
2748     SvIVX(sv) = -(IV)value;
2749     } else if (value <= (UV)IV_MAX) {
2750     SvIVX(sv) = (IV)value;
2751     } else {
2752     SvUVX(sv) = value;
2753     SvIsUV_on(sv);
2754     }
2755    
2756     if (numtype & IS_NUMBER_NOT_INT) {
2757     /* I believe that even if the original PV had decimals,
2758     they are lost beyond the limit of the FP precision.
2759     However, neither is canonical, so both only get p
2760     flags. NWC, 2000/11/25 */
2761     /* Both already have p flags, so do nothing */
2762     } else {
2763     NV nv = SvNVX(sv);
2764     if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2765     if (SvIVX(sv) == I_V(nv)) {
2766     SvNOK_on(sv);
2767     SvIOK_on(sv);
2768     } else {
2769     SvIOK_on(sv);
2770     /* It had no "." so it must be integer. */
2771     }
2772     } else {
2773     /* between IV_MAX and NV(UV_MAX).
2774     Could be slightly > UV_MAX */
2775    
2776     if (numtype & IS_NUMBER_NOT_INT) {
2777     /* UV and NV both imprecise. */
2778     } else {
2779     UV nv_as_uv = U_V(nv);
2780    
2781     if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2782     SvNOK_on(sv);
2783     SvIOK_on(sv);
2784     } else {
2785     SvIOK_on(sv);
2786     }
2787     }
2788     }
2789     }
2790     }
2791     }
2792     #endif /* NV_PRESERVES_UV */
2793     }
2794     else {
2795     if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP))
2796     report_uninit();
2797     if (SvTYPE(sv) < SVt_NV)
2798     /* Typically the caller expects that sv_any is not NULL now. */
2799     /* XXX Ilya implies that this is a bug in callers that assume this
2800     and ideally should be fixed. */
2801     sv_upgrade(sv, SVt_NV);
2802     return 0.0;
2803     }
2804     #if defined(USE_LONG_DOUBLE)
2805     DEBUG_c({
2806     STORE_NUMERIC_LOCAL_SET_STANDARD();
2807     PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" PERL_PRIgldbl ")\n",
2808     PTR2UV(sv), SvNVX(sv));
2809     RESTORE_NUMERIC_LOCAL();
2810     });
2811     #else
2812     DEBUG_c({
2813     STORE_NUMERIC_LOCAL_SET_STANDARD();
2814     PerlIO_printf(Perl_debug_log, "0x%"UVxf" 1nv(%"NVgf")\n",
2815     PTR2UV(sv), SvNVX(sv));
2816     RESTORE_NUMERIC_LOCAL();
2817     });
2818     #endif
2819     return SvNVX(sv);
2820     }
2821    
2822     /* asIV(): extract an integer from the string value of an SV.
2823     * Caller must validate PVX */
2824    
2825     STATIC IV
2826     S_asIV(pTHX_ SV *sv)
2827     {
2828     UV value;
2829     int numtype = grok_number(SvPVX(sv), SvCUR(sv), &value);
2830    
2831     if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2832     == IS_NUMBER_IN_UV) {
2833     /* It's definitely an integer */
2834     if (numtype & IS_NUMBER_NEG) {
2835     if (value < (UV)IV_MIN)
2836     return -(IV)value;
2837     } else {
2838     if (value < (UV)IV_MAX)
2839     return (IV)value;
2840     }
2841     }
2842     if (!numtype) {
2843     if (ckWARN(WARN_NUMERIC))
2844     not_a_number(sv);
2845     }
2846     return I_V(Atof(SvPVX(sv)));
2847     }
2848    
2849     /* asUV(): extract an unsigned integer from the string value of an SV
2850     * Caller must validate PVX */
2851    
2852     STATIC UV
2853     S_asUV(pTHX_ SV *sv)
2854     {
2855     UV value;
2856     int numtype = grok_number(SvPVX(sv), SvCUR(sv), &value);
2857    
2858     if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2859     == IS_NUMBER_IN_UV) {
2860     /* It's definitely an integer */
2861     if (!(numtype & IS_NUMBER_NEG))
2862     return value;
2863     }
2864     if (!numtype) {
2865     if (ckWARN(WARN_NUMERIC))
2866     not_a_number(sv);
2867     }
2868     return U_V(Atof(SvPVX(sv)));
2869     }
2870    
2871     /*
2872     =for apidoc sv_2pv_nolen
2873    
2874     Like C<sv_2pv()>, but doesn't return the length too. You should usually
2875     use the macro wrapper C<SvPV_nolen(sv)> instead.
2876     =cut
2877     */
2878    
2879     char *
2880     Perl_sv_2pv_nolen(pTHX_ register SV *sv)
2881     {
2882     STRLEN n_a;
2883     return sv_2pv(sv, &n_a);
2884     }
2885    
2886     /* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2887     * UV as a string towards the end of buf, and return pointers to start and
2888     * end of it.
2889     *
2890     * We assume that buf is at least TYPE_CHARS(UV) long.
2891     */
2892    
2893     static char *
2894     uiv_2buf(char *buf, IV iv, UV uv, int is_uv, char **peob)
2895     {
2896     char *ptr = buf + TYPE_CHARS(UV);
2897     char *ebuf = ptr;
2898     int sign;
2899    
2900     if (is_uv)
2901     sign = 0;
2902     else if (iv >= 0) {
2903     uv = iv;
2904     sign = 0;
2905     } else {
2906     uv = -iv;
2907     sign = 1;
2908     }
2909     do {
2910     *--ptr = '0' + (char)(uv % 10);
2911     } while (uv /= 10);
2912     if (sign)
2913     *--ptr = '-';
2914     *peob = ebuf;
2915     return ptr;
2916     }
2917    
2918     /* sv_2pv() is now a macro using Perl_sv_2pv_flags();
2919     * this function provided for binary compatibility only
2920     */
2921    
2922     char *
2923     Perl_sv_2pv(pTHX_ register SV *sv, STRLEN *lp)
2924     {
2925     return sv_2pv_flags(sv, lp, SV_GMAGIC);
2926     }
2927    
2928     /*
2929     =for apidoc sv_2pv_flags
2930    
2931     Returns a pointer to the string value of an SV, and sets *lp to its length.
2932     If flags includes SV_GMAGIC, does an mg_get() first. Coerces sv to a string
2933     if necessary.
2934     Normally invoked via the C<SvPV_flags> macro. C<sv_2pv()> and C<sv_2pv_nomg>
2935     usually end up here too.
2936    
2937     =cut
2938     */
2939    
2940     char *
2941     Perl_sv_2pv_flags(pTHX_ register SV *sv, STRLEN *lp, I32 flags)
2942     {
2943     register char *s;
2944     int olderrno;
2945     SV *tsv, *origsv;
2946     char tbuf[64]; /* Must fit sprintf/Gconvert of longest IV/NV */
2947     char *tmpbuf = tbuf;
2948    
2949     if (!sv) {
2950     *lp = 0;
2951     return "";
2952     }
2953     if (SvGMAGICAL(sv)) {
2954     if (flags & SV_GMAGIC)
2955     mg_get(sv);
2956     if (SvPOKp(sv)) {
2957     *lp = SvCUR(sv);
2958     return SvPVX(sv);
2959     }
2960     if (SvIOKp(sv)) {
2961     if (SvIsUV(sv))
2962     (void)sprintf(tmpbuf,"%"UVuf, (UV)SvUVX(sv));
2963     else
2964     (void)sprintf(tmpbuf,"%"IVdf, (IV)SvIVX(sv));
2965     tsv = Nullsv;
2966     goto tokensave;
2967     }
2968     if (SvNOKp(sv)) {
2969     Gconvert(SvNVX(sv), NV_DIG, 0, tmpbuf);
2970     tsv = Nullsv;
2971     goto tokensave;
2972     }
2973     if (!SvROK(sv)) {
2974     if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2975     if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2976     report_uninit();
2977     }
2978     *lp = 0;
2979     return "";
2980     }
2981     }
2982     if (SvTHINKFIRST(sv)) {
2983     if (SvROK(sv)) {
2984     SV* tmpstr;
2985     if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,string)) &&
2986     (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2987     char *pv = SvPV(tmpstr, *lp);
2988     if (SvUTF8(tmpstr))
2989     SvUTF8_on(sv);
2990     else
2991     SvUTF8_off(sv);
2992     return pv;
2993     }
2994     origsv = sv;
2995     sv = (SV*)SvRV(sv);
2996     if (!sv)
2997     s = "NULLREF";
2998     else {
2999     MAGIC *mg;
3000    
3001     switch (SvTYPE(sv)) {
3002     case SVt_PVMG:
3003     if ( ((SvFLAGS(sv) &
3004     (SVs_OBJECT|SVf_OK|SVs_GMG|SVs_SMG|SVs_RMG))
3005     == (SVs_OBJECT|SVs_SMG))
3006     && (mg = mg_find(sv, PERL_MAGIC_qr))) {
3007     regexp *re = (regexp *)mg->mg_obj;
3008    
3009     if (!mg->mg_ptr) {
3010     char *fptr = "msix";
3011     char reflags[6];
3012     char ch;
3013     int left = 0;
3014     int right = 4;
3015     char need_newline = 0;
3016     U16 reganch = (U16)((re->reganch & PMf_COMPILETIME) >> 12);
3017    
3018     while((ch = *fptr++)) {
3019     if(reganch & 1) {
3020     reflags[left++] = ch;
3021     }
3022     else {
3023     reflags[right--] = ch;
3024     }
3025     reganch >>= 1;
3026     }
3027     if(left != 4) {
3028     reflags[left] = '-';
3029     left = 5;
3030     }
3031    
3032     mg->mg_len = re->prelen + 4 + left;
3033     /*
3034     * If /x was used, we have to worry about a regex
3035     * ending with a comment later being embedded
3036     * within another regex. If so, we don't want this
3037     * regex's "commentization" to leak out to the
3038     * right part of the enclosing regex, we must cap
3039     * it with a newline.
3040     *
3041     * So, if /x was used, we scan backwards from the
3042     * end of the regex. If we find a '#' before we
3043     * find a newline, we need to add a newline
3044     * ourself. If we find a '\n' first (or if we
3045     * don't find '#' or '\n'), we don't need to add
3046     * anything. -jfriedl
3047     */
3048     if (PMf_EXTENDED & re->reganch)
3049     {
3050     char *endptr = re->precomp + re->prelen;
3051     while (endptr >= re->precomp)
3052     {
3053     char c = *(endptr--);
3054     if (c == '\n')
3055     break; /* don't need another */
3056     if (c == '#') {
3057     /* we end while in a comment, so we
3058     need a newline */
3059     mg->mg_len++; /* save space for it */
3060     need_newline = 1; /* note to add it */
3061     break;
3062     }
3063     }
3064     }
3065    
3066     New(616, mg->mg_ptr, mg->mg_len + 1 + left, char);
3067     Copy("(?", mg->mg_ptr, 2, char);
3068     Copy(reflags, mg->mg_ptr+2, left, char);
3069     Copy(":", mg->mg_ptr+left+2, 1, char);
3070     Copy(re->precomp, mg->mg_ptr+3+left, re->prelen, char);
3071     if (need_newline)
3072     mg->mg_ptr[mg->mg_len - 2] = '\n';
3073     mg->mg_ptr[mg->mg_len - 1] = ')';
3074     mg->mg_ptr[mg->mg_len] = 0;
3075     }
3076     PL_reginterp_cnt += re->program[0].next_off;
3077    
3078     if (re->reganch & ROPT_UTF8)
3079     SvUTF8_on(origsv);
3080     else
3081     SvUTF8_off(origsv);
3082     *lp = mg->mg_len;
3083     return mg->mg_ptr;
3084     }
3085     /* Fall through */
3086     case SVt_NULL:
3087     case SVt_IV:
3088     case SVt_NV:
3089     case SVt_RV:
3090     case SVt_PV:
3091     case SVt_PVIV:
3092     case SVt_PVNV:
3093     case SVt_PVBM: if (SvROK(sv))
3094     s = "REF";
3095     else
3096     s = "SCALAR"; break;
3097     case SVt_PVLV: s = SvROK(sv) ? "REF"
3098     /* tied lvalues should appear to be
3099     * scalars for backwards compatitbility */
3100     : (LvTYPE(sv) == 't' || LvTYPE(sv) == 'T')
3101     ? "SCALAR" : "LVALUE"; break;
3102     case SVt_PVAV: s = "ARRAY"; break;
3103     case SVt_PVHV: s = "HASH"; break;
3104     case SVt_PVCV: s = "CODE"; break;
3105     case SVt_PVGV: s = "GLOB"; break;
3106     case SVt_PVFM: s = "FORMAT"; break;
3107     case SVt_PVIO: s = "IO"; break;
3108     default: s = "UNKNOWN"; break;
3109     }
3110     tsv = NEWSV(0,0);
3111     if (SvOBJECT(sv)) {
3112     const char *name = HvNAME(SvSTASH(sv));
3113     Perl_sv_setpvf(aTHX_ tsv, "%s=%s(0x%"UVxf")",
3114     name ? name : "__ANON__" , s, PTR2UV(sv));
3115     }
3116     else
3117     Perl_sv_setpvf(aTHX_ tsv, "%s(0x%"UVxf")", s, PTR2UV(sv));
3118     goto tokensaveref;
3119     }
3120     *lp = strlen(s);
3121     return s;
3122     }
3123     if (SvREADONLY(sv) && !SvOK(sv)) {
3124     if (ckWARN(WARN_UNINITIALIZED))
3125     report_uninit();
3126     *lp = 0;
3127     return "";
3128     }
3129     }
3130     if (SvIOK(sv) || ((SvIOKp(sv) && !SvNOKp(sv)))) {
3131     /* I'm assuming that if both IV and NV are equally valid then
3132     converting the IV is going to be more efficient */
3133     U32 isIOK = SvIOK(sv);
3134     U32 isUIOK = SvIsUV(sv);
3135     char buf[TYPE_CHARS(UV)];
3136     char *ebuf, *ptr;
3137    
3138     if (SvTYPE(sv) < SVt_PVIV)
3139     sv_upgrade(sv, SVt_PVIV);
3140     if (isUIOK)
3141     ptr = uiv_2buf(buf, 0, SvUVX(sv), 1, &ebuf);
3142     else
3143     ptr = uiv_2buf(buf, SvIVX(sv), 0, 0, &ebuf);
3144     SvGROW(sv, (STRLEN)(ebuf - ptr + 1)); /* inlined from sv_setpvn */
3145     Move(ptr,SvPVX(sv),ebuf - ptr,char);
3146     SvCUR_set(sv, ebuf - ptr);
3147     s = SvEND(sv);
3148     *s = '\0';
3149     if (isIOK)
3150     SvIOK_on(sv);
3151     else
3152     SvIOKp_on(sv);
3153     if (isUIOK)
3154     SvIsUV_on(sv);
3155     }
3156     else if (SvNOKp(sv)) {
3157     if (SvTYPE(sv) < SVt_PVNV)
3158     sv_upgrade(sv, SVt_PVNV);
3159     /* The +20 is pure guesswork. Configure test needed. --jhi */
3160     SvGROW(sv, NV_DIG + 20);
3161     s = SvPVX(sv);
3162     olderrno = errno; /* some Xenix systems wipe out errno here */
3163     #ifdef apollo
3164     if (SvNVX(sv) == 0.0)
3165     (void)strcpy(s,"0");
3166     else
3167     #endif /*apollo*/
3168     {
3169     Gconvert(SvNVX(sv), NV_DIG, 0, s);
3170     }
3171     errno = olderrno;
3172     #ifdef FIXNEGATIVEZERO
3173     if (*s == '-' && s[1] == '0' && !s[2])
3174     strcpy(s,"0");
3175     #endif
3176     while (*s) s++;
3177     #ifdef hcx
3178     if (s[-1] == '.')
3179     *--s = '\0';
3180     #endif
3181     }
3182     else {
3183     if (ckWARN(WARN_UNINITIALIZED)
3184     && !PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP))
3185     report_uninit();
3186     *lp = 0;
3187     if (SvTYPE(sv) < SVt_PV)
3188     /* Typically the caller expects that sv_any is not NULL now. */
3189     sv_upgrade(sv, SVt_PV);
3190     return "";
3191     }
3192     *lp = s - SvPVX(sv);
3193     SvCUR_set(sv, *lp);
3194     SvPOK_on(sv);
3195     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
3196     PTR2UV(sv),SvPVX(sv)));
3197     return SvPVX(sv);
3198    
3199     tokensave:
3200     if (SvROK(sv)) { /* XXX Skip this when sv_pvn_force calls */
3201     /* Sneaky stuff here */
3202    
3203     tokensaveref:
3204     if (!tsv)
3205     tsv = newSVpv(tmpbuf, 0);
3206     sv_2mortal(tsv);
3207     *lp = SvCUR(tsv);
3208     return SvPVX(tsv);
3209     }
3210     else {
3211     STRLEN len;
3212     char *t;
3213    
3214     if (tsv) {
3215     sv_2mortal(tsv);
3216     t = SvPVX(tsv);
3217     len = SvCUR(tsv);
3218     }
3219     else {
3220     t = tmpbuf;
3221     len = strlen(tmpbuf);
3222     }
3223     #ifdef FIXNEGATIVEZERO
3224     if (len == 2 && t[0] == '-' && t[1] == '0') {
3225     t = "0";
3226     len = 1;
3227     }
3228     #endif
3229     (void)SvUPGRADE(sv, SVt_PV);
3230     *lp = len;
3231     s = SvGROW(sv, len + 1);
3232     SvCUR_set(sv, len);
3233     SvPOKp_on(sv);
3234     return strcpy(s, t);
3235     }
3236     }
3237    
3238     /*
3239     =for apidoc sv_copypv
3240    
3241     Copies a stringified representation of the source SV into the
3242     destination SV. Automatically performs any necessary mg_get and
3243     coercion of numeric values into strings. Guaranteed to preserve
3244     UTF-8 flag even from overloaded objects. Similar in nature to
3245     sv_2pv[_flags] but operates directly on an SV instead of just the
3246     string. Mostly uses sv_2pv_flags to do its work, except when that
3247     would lose the UTF-8'ness of the PV.
3248    
3249     =cut
3250     */
3251    
3252     void
3253     Perl_sv_copypv(pTHX_ SV *dsv, register SV *ssv)
3254     {
3255     STRLEN len;
3256     char *s;
3257     s = SvPV(ssv,len);
3258     sv_setpvn(dsv,s,len);
3259     if (SvUTF8(ssv))
3260     SvUTF8_on(dsv);
3261     else
3262     SvUTF8_off(dsv);
3263     }
3264    
3265     /*
3266     =for apidoc sv_2pvbyte_nolen
3267    
3268     Return a pointer to the byte-encoded representation of the SV.
3269     May cause the SV to be downgraded from UTF-8 as a side-effect.
3270    
3271     Usually accessed via the C<SvPVbyte_nolen> macro.
3272    
3273     =cut
3274     */
3275    
3276     char *
3277     Perl_sv_2pvbyte_nolen(pTHX_ register SV *sv)
3278     {
3279     STRLEN n_a;
3280     return sv_2pvbyte(sv, &n_a);
3281     }
3282    
3283     /*
3284     =for apidoc sv_2pvbyte
3285    
3286     Return a pointer to the byte-encoded representation of the SV, and set *lp
3287     to its length. May cause the SV to be downgraded from UTF-8 as a
3288     side-effect.
3289    
3290     Usually accessed via the C<SvPVbyte> macro.
3291    
3292     =cut
3293     */
3294    
3295     char *
3296     Perl_sv_2pvbyte(pTHX_ register SV *sv, STRLEN *lp)
3297     {
3298     sv_utf8_downgrade(sv,0);
3299     return SvPV(sv,*lp);
3300     }
3301    
3302     /*
3303     =for apidoc sv_2pvutf8_nolen
3304    
3305     Return a pointer to the UTF-8-encoded representation of the SV.
3306     May cause the SV to be upgraded to UTF-8 as a side-effect.
3307    
3308     Usually accessed via the C<SvPVutf8_nolen> macro.
3309    
3310     =cut
3311     */
3312    
3313     char *
3314     Perl_sv_2pvutf8_nolen(pTHX_ register SV *sv)
3315     {
3316     STRLEN n_a;
3317     return sv_2pvutf8(sv, &n_a);
3318     }
3319    
3320     /*
3321     =for apidoc sv_2pvutf8
3322    
3323     Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
3324     to its length. May cause the SV to be upgraded to UTF-8 as a side-effect.
3325    
3326     Usually accessed via the C<SvPVutf8> macro.
3327    
3328     =cut
3329     */
3330    
3331     char *
3332     Perl_sv_2pvutf8(pTHX_ register SV *sv, STRLEN *lp)
3333     {
3334     sv_utf8_upgrade(sv);
3335     return SvPV(sv,*lp);
3336     }
3337    
3338     /*
3339     =for apidoc sv_2bool
3340    
3341     This function is only called on magical items, and is only used by
3342     sv_true() or its macro equivalent.
3343    
3344     =cut
3345     */
3346    
3347     bool
3348     Perl_sv_2bool(pTHX_ register SV *sv)
3349     {
3350     if (SvGMAGICAL(sv))
3351     mg_get(sv);
3352    
3353     if (!SvOK(sv))
3354     return 0;
3355     if (SvROK(sv)) {
3356     SV* tmpsv;
3357     if (SvAMAGIC(sv) && (tmpsv=AMG_CALLun(sv,bool_)) &&
3358     (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
3359     return (bool)SvTRUE(tmpsv);
3360     return SvRV(sv) != 0;
3361     }
3362     if (SvPOKp(sv)) {
3363     register XPV* Xpvtmp;
3364     if ((Xpvtmp = (XPV*)SvANY(sv)) &&
3365     (*Xpvtmp->xpv_pv > '0' ||
3366     Xpvtmp->xpv_cur > 1 ||
3367     (Xpvtmp->xpv_cur && *Xpvtmp->xpv_pv != '0')))
3368     return 1;
3369     else
3370     return 0;
3371     }
3372     else {
3373     if (SvIOKp(sv))
3374     return SvIVX(sv) != 0;
3375     else {
3376     if (SvNOKp(sv))
3377     return SvNVX(sv) != 0.0;
3378     else
3379     return FALSE;
3380     }
3381     }
3382     }
3383    
3384     /* sv_utf8_upgrade() is now a macro using sv_utf8_upgrade_flags();
3385     * this function provided for binary compatibility only
3386     */
3387    
3388    
3389     STRLEN
3390     Perl_sv_utf8_upgrade(pTHX_ register SV *sv)
3391     {
3392     return sv_utf8_upgrade_flags(sv, SV_GMAGIC);
3393     }
3394    
3395     /*
3396     =for apidoc sv_utf8_upgrade
3397    
3398     Converts the PV of an SV to its UTF-8-encoded form.
3399     Forces the SV to string form if it is not already.
3400     Always sets the SvUTF8 flag to avoid future validity checks even
3401     if all the bytes have hibit clear.
3402    
3403     This is not as a general purpose byte encoding to Unicode interface:
3404     use the Encode extension for that.
3405    
3406     =for apidoc sv_utf8_upgrade_flags
3407    
3408     Converts the PV of an SV to its UTF-8-encoded form.
3409     Forces the SV to string form if it is not already.
3410     Always sets the SvUTF8 flag to avoid future validity checks even
3411     if all the bytes have hibit clear. If C<flags> has C<SV_GMAGIC> bit set,
3412     will C<mg_get> on C<sv> if appropriate, else not. C<sv_utf8_upgrade> and
3413     C<sv_utf8_upgrade_nomg> are implemented in terms of this function.
3414    
3415     This is not as a general purpose byte encoding to Unicode interface:
3416     use the Encode extension for that.
3417    
3418     =cut
3419     */
3420    
3421     STRLEN
3422     Perl_sv_utf8_upgrade_flags(pTHX_ register SV *sv, I32 flags)
3423     {
3424     U8 *s, *t, *e;
3425     int hibit = 0;
3426    
3427     if (sv == &PL_sv_undef)
3428     return 0;
3429     if (!SvPOK(sv)) {
3430     STRLEN len = 0;
3431     if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
3432     (void) sv_2pv_flags(sv,&len, flags);
3433     if (SvUTF8(sv))
3434     return len;
3435     } else {
3436     (void) SvPV_force(sv,len);
3437     }
3438     }
3439    
3440     if (SvUTF8(sv)) {
3441     return SvCUR(sv);
3442     }
3443    
3444     if (SvREADONLY(sv) && SvFAKE(sv)) {
3445     sv_force_normal(sv);
3446     }
3447    
3448     if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING))
3449     sv_recode_to_utf8(sv, PL_encoding);
3450     else { /* Assume Latin-1/EBCDIC */
3451     /* This function could be much more efficient if we
3452     * had a FLAG in SVs to signal if there are any hibit
3453     * chars in the PV. Given that there isn't such a flag
3454     * make the loop as fast as possible. */
3455     s = (U8 *) SvPVX(sv);
3456     e = (U8 *) SvEND(sv);
3457     t = s;
3458     while (t < e) {
3459     U8 ch = *t++;
3460     if ((hibit = !NATIVE_IS_INVARIANT(ch)))
3461     break;
3462     }
3463     if (hibit) {
3464     STRLEN len;
3465     (void)SvOOK_off(sv);
3466     s = (U8*)SvPVX(sv);
3467     len = SvCUR(sv) + 1; /* Plus the \0 */
3468     SvPVX(sv) = (char*)bytes_to_utf8((U8*)s, &len);
3469     SvCUR(sv) = len - 1;
3470     if (SvLEN(sv) != 0)
3471     Safefree(s); /* No longer using what was there before. */
3472     SvLEN(sv) = len; /* No longer know the real size. */
3473     }
3474     /* Mark as UTF-8 even if no hibit - saves scanning loop */
3475     SvUTF8_on(sv);
3476     }
3477     return SvCUR(sv);
3478     }
3479    
3480     /*
3481     =for apidoc sv_utf8_downgrade
3482    
3483     Attempts to convert the PV of an SV from characters to bytes.
3484     If the PV contains a character beyond byte, this conversion will fail;
3485     in this case, either returns false or, if C<fail_ok> is not
3486     true, croaks.
3487    
3488     This is not as a general purpose Unicode to byte encoding interface:
3489     use the Encode extension for that.
3490    
3491     =cut
3492     */
3493    
3494     bool
3495     Perl_sv_utf8_downgrade(pTHX_ register SV* sv, bool fail_ok)
3496     {
3497     if (SvPOKp(sv) && SvUTF8(sv)) {
3498     if (SvCUR(sv)) {
3499     U8 *s;
3500     STRLEN len;
3501    
3502     if (SvREADONLY(sv) && SvFAKE(sv))
3503     sv_force_normal(sv);
3504     s = (U8 *) SvPV(sv, len);
3505     if (!utf8_to_bytes(s, &len)) {
3506     if (fail_ok)
3507     return FALSE;
3508     else {
3509     if (PL_op)
3510     Perl_croak(aTHX_ "Wide character in %s",
3511     OP_DESC(PL_op));
3512     else
3513     Perl_croak(aTHX_ "Wide character");
3514     }
3515     }
3516     SvCUR(sv) = len;
3517     }
3518     }
3519     SvUTF8_off(sv);
3520     return TRUE;
3521     }
3522    
3523     /*
3524     =for apidoc sv_utf8_encode
3525    
3526     Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3527     flag off so that it looks like octets again.
3528    
3529     =cut
3530     */
3531    
3532     void
3533     Perl_sv_utf8_encode(pTHX_ register SV *sv)
3534     {
3535     (void) sv_utf8_upgrade(sv);
3536     if (SvIsCOW(sv)) {
3537     sv_force_normal_flags(sv, 0);
3538     }
3539     if (SvREADONLY(sv)) {
3540     Perl_croak(aTHX_ PL_no_modify);
3541     }
3542     SvUTF8_off(sv);
3543     }
3544    
3545     /*
3546     =for apidoc sv_utf8_decode
3547    
3548     If the PV of the SV is an octet sequence in UTF-8
3549     and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3550     so that it looks like a character. If the PV contains only single-byte
3551     characters, the C<SvUTF8> flag stays being off.
3552     Scans PV for validity and returns false if the PV is invalid UTF-8.
3553    
3554     =cut
3555     */
3556    
3557     bool
3558     Perl_sv_utf8_decode(pTHX_ register SV *sv)
3559     {
3560     if (SvPOKp(sv)) {
3561     U8 *c;
3562     U8 *e;
3563    
3564     /* The octets may have got themselves encoded - get them back as
3565     * bytes
3566     */
3567     if (!sv_utf8_downgrade(sv, TRUE))
3568     return FALSE;
3569    
3570     /* it is actually just a matter of turning the utf8 flag on, but
3571     * we want to make sure everything inside is valid utf8 first.
3572     */
3573     c = (U8 *) SvPVX(sv);
3574     if (!is_utf8_string(c, SvCUR(sv)+1))
3575     return FALSE;
3576     e = (U8 *) SvEND(sv);
3577     while (c < e) {
3578     U8 ch = *c++;
3579     if (!UTF8_IS_INVARIANT(ch)) {
3580     SvUTF8_on(sv);
3581     break;
3582     }
3583     }
3584     }
3585     return TRUE;
3586     }
3587    
3588     /* sv_setsv() is now a macro using Perl_sv_setsv_flags();
3589     * this function provided for binary compatibility only
3590     */
3591    
3592     void
3593     Perl_sv_setsv(pTHX_ SV *dstr, register SV *sstr)
3594     {
3595     sv_setsv_flags(dstr, sstr, SV_GMAGIC);
3596     }
3597    
3598     /*
3599     =for apidoc sv_setsv
3600    
3601     Copies the contents of the source SV C<ssv> into the destination SV
3602     C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3603     function if the source SV needs to be reused. Does not handle 'set' magic.
3604     Loosely speaking, it performs a copy-by-value, obliterating any previous
3605     content of the destination.
3606    
3607     You probably want to use one of the assortment of wrappers, such as
3608     C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3609     C<SvSetMagicSV_nosteal>.
3610    
3611     =for apidoc sv_setsv_flags
3612    
3613     Copies the contents of the source SV C<ssv> into the destination SV
3614     C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3615     function if the source SV needs to be reused. Does not handle 'set' magic.
3616     Loosely speaking, it performs a copy-by-value, obliterating any previous
3617     content of the destination.
3618     If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
3619     C<ssv> if appropriate, else not. If the C<flags> parameter has the
3620     C<NOSTEAL> bit set then the buffers of temps will not be stolen. <sv_setsv>
3621     and C<sv_setsv_nomg> are implemented in terms of this function.
3622    
3623     You probably want to use one of the assortment of wrappers, such as
3624     C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3625     C<SvSetMagicSV_nosteal>.
3626    
3627     This is the primary function for copying scalars, and most other
3628     copy-ish functions and macros use this underneath.
3629    
3630     =cut
3631     */
3632    
3633     void
3634     Perl_sv_setsv_flags(pTHX_ SV *dstr, register SV *sstr, I32 flags)
3635     {
3636     register U32 sflags;
3637     register int dtype;
3638     register int stype;
3639    
3640     if (sstr == dstr)
3641     return;
3642     SV_CHECK_THINKFIRST(dstr);
3643     if (!sstr)
3644     sstr = &PL_sv_undef;
3645     stype = SvTYPE(sstr);
3646     dtype = SvTYPE(dstr);
3647    
3648     SvAMAGIC_off(dstr);
3649     if ( SvVOK(dstr) )
3650     {
3651     /* need to nuke the magic */
3652     mg_free(dstr);
3653     SvRMAGICAL_off(dstr);
3654     }
3655    
3656     /* There's a lot of redundancy below but we're going for speed here */
3657    
3658     switch (stype) {
3659     case SVt_NULL:
3660     undef_sstr:
3661     if (dtype != SVt_PVGV) {
3662     (void)SvOK_off(dstr);
3663     return;
3664     }
3665     break;
3666     case SVt_IV:
3667     if (SvIOK(sstr)) {
3668     switch (dtype) {
3669     case SVt_NULL:
3670     sv_upgrade(dstr, SVt_IV);
3671     break;
3672     case SVt_NV:
3673     sv_upgrade(dstr, SVt_PVNV);
3674     break;
3675     case SVt_RV:
3676     case SVt_PV:
3677     sv_upgrade(dstr, SVt_PVIV);
3678     break;
3679     }
3680     (void)SvIOK_only(dstr);
3681     SvIVX(dstr) = SvIVX(sstr);
3682     if (SvIsUV(sstr))
3683     SvIsUV_on(dstr);
3684     if (SvTAINTED(sstr))
3685     SvTAINT(dstr);
3686     return;
3687     }
3688     goto undef_sstr;
3689    
3690     case SVt_NV:
3691     if (SvNOK(sstr)) {
3692     switch (dtype) {
3693     case SVt_NULL:
3694     case SVt_IV:
3695     sv_upgrade(dstr, SVt_NV);
3696     break;
3697     case SVt_RV:
3698     case SVt_PV:
3699     case SVt_PVIV:
3700     sv_upgrade(dstr, SVt_PVNV);
3701     break;
3702     }
3703     SvNVX(dstr) = SvNVX(sstr);
3704     (void)SvNOK_only(dstr);
3705     if (SvTAINTED(sstr))
3706     SvTAINT(dstr);
3707     return;
3708     }
3709     goto undef_sstr;
3710    
3711     case SVt_RV:
3712     if (dtype < SVt_RV)
3713     sv_upgrade(dstr, SVt_RV);
3714     else if (dtype == SVt_PVGV &&
3715     SvROK(sstr) && SvTYPE(SvRV(sstr)) == SVt_PVGV) {
3716     sstr = SvRV(sstr);
3717     if (sstr == dstr) {
3718     if (GvIMPORTED(dstr) != GVf_IMPORTED
3719     && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3720     {
3721     GvIMPORTED_on(dstr);
3722     }
3723     GvMULTI_on(dstr);
3724     return;
3725     }
3726     goto glob_assign;
3727     }
3728     break;
3729     case SVt_PV:
3730     case SVt_PVFM:
3731     if (dtype < SVt_PV)
3732     sv_upgrade(dstr, SVt_PV);
3733     break;
3734     case SVt_PVIV:
3735     if (dtype < SVt_PVIV)
3736     sv_upgrade(dstr, SVt_PVIV);
3737     break;
3738     case SVt_PVNV:
3739     if (dtype < SVt_PVNV)
3740     sv_upgrade(dstr, SVt_PVNV);
3741     break;
3742     case SVt_PVAV:
3743     case SVt_PVHV:
3744     case SVt_PVCV:
3745     case SVt_PVIO:
3746     if (PL_op)
3747     Perl_croak(aTHX_ "Bizarre copy of %s in %s", sv_reftype(sstr, 0),
3748     OP_NAME(PL_op));
3749     else
3750     Perl_croak(aTHX_ "Bizarre copy of %s", sv_reftype(sstr, 0));
3751     break;
3752    
3753     case SVt_PVGV:
3754     if (dtype <= SVt_PVGV) {
3755     glob_assign:
3756     if (dtype != SVt_PVGV) {
3757     char *name = GvNAME(sstr);
3758     STRLEN len = GvNAMELEN(sstr);
3759     sv_upgrade(dstr, SVt_PVGV);
3760     sv_magic(dstr, dstr, PERL_MAGIC_glob, Nullch, 0);
3761     GvSTASH(dstr) = (HV*)SvREFCNT_inc(GvSTASH(sstr));
3762     GvNAME(dstr) = savepvn(name, len);
3763     GvNAMELEN(dstr) = len;
3764     SvFAKE_on(dstr); /* can coerce to non-glob */
3765     }
3766     /* ahem, death to those who redefine active sort subs */
3767     else if (PL_curstackinfo->si_type == PERLSI_SORT
3768     && GvCV(dstr) && PL_sortcop == CvSTART(GvCV(dstr)))
3769     Perl_croak(aTHX_ "Can't redefine active sort subroutine %s",
3770     GvNAME(dstr));
3771    
3772     #ifdef GV_UNIQUE_CHECK
3773     if (GvUNIQUE((GV*)dstr)) {
3774     Perl_croak(aTHX_ PL_no_modify);
3775     }
3776     #endif
3777    
3778     (void)SvOK_off(dstr);
3779     GvINTRO_off(dstr); /* one-shot flag */
3780     gp_free((GV*)dstr);
3781     GvGP(dstr) = gp_ref(GvGP(sstr));
3782     if (SvTAINTED(sstr))
3783     SvTAINT(dstr);
3784     if (GvIMPORTED(dstr) != GVf_IMPORTED
3785     && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3786     {
3787     GvIMPORTED_on(dstr);
3788     }
3789     GvMULTI_on(dstr);
3790     return;
3791     }
3792     /* FALL THROUGH */
3793    
3794     default:
3795     if (SvGMAGICAL(sstr) && (flags & SV_GMAGIC)) {
3796     mg_get(sstr);
3797     if ((int)SvTYPE(sstr) != stype) {
3798     stype = SvTYPE(sstr);
3799     if (stype == SVt_PVGV && dtype <= SVt_PVGV)
3800     goto glob_assign;
3801     }
3802     }
3803     if (stype == SVt_PVLV)
3804     (void)SvUPGRADE(dstr, SVt_PVNV);
3805     else
3806     (void)SvUPGRADE(dstr, (U32)stype);
3807     }
3808    
3809     sflags = SvFLAGS(sstr);
3810    
3811     if (sflags & SVf_ROK) {
3812     if (dtype >= SVt_PV) {
3813     if (dtype == SVt_PVGV) {
3814     SV *sref = SvREFCNT_inc(SvRV(sstr));
3815     SV *dref = 0;
3816     int intro = GvINTRO(dstr);
3817    
3818     #ifdef GV_UNIQUE_CHECK
3819     if (GvUNIQUE((GV*)dstr)) {
3820     Perl_croak(aTHX_ PL_no_modify);
3821     }
3822     #endif
3823    
3824     if (intro) {
3825     GvINTRO_off(dstr); /* one-shot flag */
3826     GvLINE(dstr) = CopLINE(PL_curcop);
3827     GvEGV(dstr) = (GV*)dstr;
3828     }
3829     GvMULTI_on(dstr);
3830     switch (SvTYPE(sref)) {
3831     case SVt_PVAV:
3832     if (intro)
3833     SAVEGENERICSV(GvAV(dstr));
3834     else
3835     dref = (SV*)GvAV(dstr);
3836     GvAV(dstr) = (AV*)sref;
3837     if (!GvIMPORTED_AV(dstr)
3838     && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3839     {
3840     GvIMPORTED_AV_on(dstr);
3841     }
3842     break;
3843     case SVt_PVHV:
3844     if (intro)
3845     SAVEGENERICSV(GvHV(dstr));
3846     else
3847     dref = (SV*)GvHV(dstr);
3848     GvHV(dstr) = (HV*)sref;
3849     if (!GvIMPORTED_HV(dstr)
3850     && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3851     {
3852     GvIMPORTED_HV_on(dstr);
3853     }
3854     break;
3855     case SVt_PVCV:
3856     if (intro) {
3857     if (GvCVGEN(dstr) && GvCV(dstr) != (CV*)sref) {
3858     SvREFCNT_dec(GvCV(dstr));
3859     GvCV(dstr) = Nullcv;
3860     GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3861     PL_sub_generation++;
3862     }
3863     SAVEGENERICSV(GvCV(dstr));
3864     }
3865     else
3866     dref = (SV*)GvCV(dstr);
3867     if (GvCV(dstr) != (CV*)sref) {
3868     CV* cv = GvCV(dstr);
3869     if (cv) {
3870     if (!GvCVGEN((GV*)dstr) &&
3871     (CvROOT(cv) || CvXSUB(cv)))
3872     {
3873     /* ahem, death to those who redefine
3874     * active sort subs */
3875     if (PL_curstackinfo->si_type == PERLSI_SORT &&
3876     PL_sortcop == CvSTART(cv))
3877     Perl_croak(aTHX_
3878     "Can't redefine active sort subroutine %s",
3879     GvENAME((GV*)dstr));
3880     /* Redefining a sub - warning is mandatory if
3881     it was a const and its value changed. */
3882     if (ckWARN(WARN_REDEFINE)
3883     || (CvCONST(cv)
3884     && (!CvCONST((CV*)sref)
3885     || sv_cmp(cv_const_sv(cv),
3886     cv_const_sv((CV*)sref)))))
3887     {
3888     Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
3889     CvCONST(cv)
3890     ? "Constant subroutine %s::%s redefined"
3891     : "Subroutine %s::%s redefined",
3892     HvNAME(GvSTASH((GV*)dstr)),
3893     GvENAME((GV*)dstr));
3894     }
3895     }
3896     if (!intro)
3897     cv_ckproto(cv, (GV*)dstr,
3898     SvPOK(sref) ? SvPVX(sref) : Nullch);
3899     }
3900     GvCV(dstr) = (CV*)sref;
3901     GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3902     GvASSUMECV_on(dstr);
3903     PL_sub_generation++;
3904     }
3905     if (!GvIMPORTED_CV(dstr)
3906     && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3907     {
3908     GvIMPORTED_CV_on(dstr);
3909     }
3910     break;
3911     case SVt_PVIO:
3912     if (intro)
3913     SAVEGENERICSV(GvIOp(dstr));
3914     else
3915     dref = (SV*)GvIOp(dstr);
3916     GvIOp(dstr) = (IO*)sref;
3917     break;
3918     case SVt_PVFM:
3919     if (intro)
3920     SAVEGENERICSV(GvFORM(dstr));
3921     else
3922     dref = (SV*)GvFORM(dstr);
3923     GvFORM(dstr) = (CV*)sref;
3924     break;
3925     default:
3926     if (intro)
3927     SAVEGENERICSV(GvSV(dstr));
3928     else
3929     dref = (SV*)GvSV(dstr);
3930     GvSV(dstr) = sref;
3931     if (!GvIMPORTED_SV(dstr)
3932     && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3933     {
3934     GvIMPORTED_SV_on(dstr);
3935     }
3936     break;
3937     }
3938     if (dref)
3939     SvREFCNT_dec(dref);
3940     if (SvTAINTED(sstr))
3941     SvTAINT(dstr);
3942     return;
3943     }
3944     if (SvPVX(dstr)) {
3945     (void)SvOOK_off(dstr); /* backoff */
3946     if (SvLEN(dstr))
3947     Safefree(SvPVX(dstr));
3948     SvLEN(dstr)=SvCUR(dstr)=0;
3949     }
3950     }
3951     (void)SvOK_off(dstr);
3952     SvRV(dstr) = SvREFCNT_inc(SvRV(sstr));
3953     SvROK_on(dstr);
3954     if (sflags & SVp_NOK) {
3955     SvNOKp_on(dstr);
3956     /* Only set the public OK flag if the source has public OK. */
3957     if (sflags & SVf_NOK)
3958     SvFLAGS(dstr) |= SVf_NOK;
3959     SvNVX(dstr) = SvNVX(sstr);
3960     }
3961     if (sflags & SVp_IOK) {
3962     (void)SvIOKp_on(dstr);
3963     if (sflags & SVf_IOK)
3964     SvFLAGS(dstr) |= SVf_IOK;
3965     if (sflags & SVf_IVisUV)
3966     SvIsUV_on(dstr);
3967     SvIVX(dstr) = SvIVX(sstr);
3968     }
3969     if (SvAMAGIC(sstr)) {
3970     SvAMAGIC_on(dstr);
3971     }
3972     }
3973     else if (sflags & SVp_POK) {
3974    
3975     /*
3976     * Check to see if we can just swipe the string. If so, it's a
3977     * possible small lose on short strings, but a big win on long ones.
3978     * It might even be a win on short strings if SvPVX(dstr)
3979     * has to be allocated and SvPVX(sstr) has to be freed.
3980     */
3981    
3982     if (SvTEMP(sstr) && /* slated for free anyway? */
3983     SvREFCNT(sstr) == 1 && /* and no other references to it? */
3984     (!(flags & SV_NOSTEAL)) && /* and we're allowed to steal temps */
3985     !(sflags & SVf_OOK) && /* and not involved in OOK hack? */
3986     SvLEN(sstr) && /* and really is a string */
3987     /* and won't be needed again, potentially */
3988     !(PL_op && PL_op->op_type == OP_AASSIGN))
3989     {
3990     if (SvPVX(dstr)) { /* we know that dtype >= SVt_PV */
3991     if (SvOOK(dstr)) {
3992     SvFLAGS(dstr) &= ~SVf_OOK;
3993     Safefree(SvPVX(dstr) - SvIVX(dstr));
3994     }
3995     else if (SvLEN(dstr))
3996     Safefree(SvPVX(dstr));
3997     }
3998     (void)SvPOK_only(dstr);
3999     SvPV_set(dstr, SvPVX(sstr));
4000     SvLEN_set(dstr, SvLEN(sstr));
4001     SvCUR_set(dstr, SvCUR(sstr));
4002    
4003     SvTEMP_off(dstr);
4004     (void)SvOK_off(sstr); /* NOTE: nukes most SvFLAGS on sstr */
4005     SvPV_set(sstr, Nullch);
4006     SvLEN_set(sstr, 0);
4007     SvCUR_set(sstr, 0);
4008     SvTEMP_off(sstr);
4009     }
4010     else { /* have to copy actual string */
4011     STRLEN len = SvCUR(sstr);
4012     SvGROW(dstr, len + 1); /* inlined from sv_setpvn */
4013     Move(SvPVX(sstr),SvPVX(dstr),len,char);
4014     SvCUR_set(dstr, len);
4015     *SvEND(dstr) = '\0';
4016     (void)SvPOK_only(dstr);
4017     }
4018     if (sflags & SVf_UTF8)
4019     SvUTF8_on(dstr);
4020     /*SUPPRESS 560*/
4021     if (sflags & SVp_NOK) {
4022     SvNOKp_on(dstr);
4023     if (sflags & SVf_NOK)
4024     SvFLAGS(dstr) |= SVf_NOK;
4025     SvNVX(dstr) = SvNVX(sstr);
4026     }
4027     if (sflags & SVp_IOK) {
4028     (void)SvIOKp_on(dstr);
4029     if (sflags & SVf_IOK)
4030     SvFLAGS(dstr) |= SVf_IOK;
4031     if (sflags & SVf_IVisUV)
4032     SvIsUV_on(dstr);
4033     SvIVX(dstr) = SvIVX(sstr);
4034     }
4035     if ( SvVOK(sstr) ) {
4036     MAGIC *smg = mg_find(sstr,PERL_MAGIC_vstring);
4037     sv_magic(dstr, NULL, PERL_MAGIC_vstring,
4038     smg->mg_ptr, smg->mg_len);
4039     SvRMAGICAL_on(dstr);
4040     }
4041     }
4042     else if (sflags & SVp_IOK) {
4043     if (sflags & SVf_IOK)
4044     (void)SvIOK_only(dstr);
4045     else {
4046     (void)SvOK_off(dstr);
4047     (void)SvIOKp_on(dstr);
4048     }
4049     /* XXXX Do we want to set IsUV for IV(ROK)? Be extra safe... */
4050     if (sflags & SVf_IVisUV)
4051     SvIsUV_on(dstr);
4052     SvIVX(dstr) = SvIVX(sstr);
4053     if (sflags & SVp_NOK) {
4054     if (sflags & SVf_NOK)
4055     (void)SvNOK_on(dstr);
4056     else
4057     (void)SvNOKp_on(dstr);
4058     SvNVX(dstr) = SvNVX(sstr);
4059     }
4060     }
4061     else if (sflags & SVp_NOK) {
4062     if (sflags & SVf_NOK)
4063     (void)SvNOK_only(dstr);
4064     else {
4065     (void)SvOK_off(dstr);
4066     SvNOKp_on(dstr);
4067     }
4068     SvNVX(dstr) = SvNVX(sstr);
4069     }
4070     else {
4071     if (dtype == SVt_PVGV) {
4072     if (ckWARN(WARN_MISC))
4073     Perl_warner(aTHX_ packWARN(WARN_MISC), "Undefined value assigned to typeglob");
4074     }
4075     else
4076     (void)SvOK_off(dstr);
4077     }
4078     if (SvTAINTED(sstr))
4079     SvTAINT(dstr);
4080     }
4081    
4082     /*
4083     =for apidoc sv_setsv_mg
4084    
4085     Like C<sv_setsv>, but also handles 'set' magic.
4086    
4087     =cut
4088     */
4089    
4090     void
4091     Perl_sv_setsv_mg(pTHX_ SV *dstr, register SV *sstr)
4092     {
4093     sv_setsv(dstr,sstr);
4094     SvSETMAGIC(dstr);
4095     }
4096    
4097     /*
4098     =for apidoc sv_setpvn
4099    
4100     Copies a string into an SV. The C<len> parameter indicates the number of
4101     bytes to be copied. If the C<ptr> argument is NULL the SV will become
4102     undefined. Does not handle 'set' magic. See C<sv_setpvn_mg>.
4103    
4104     =cut
4105     */
4106    
4107     void
4108     Perl_sv_setpvn(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
4109     {
4110     register char *dptr;
4111    
4112     SV_CHECK_THINKFIRST(sv);
4113     if (!ptr) {
4114     (void)SvOK_off(sv);
4115     return;
4116     }
4117     else {
4118     /* len is STRLEN which is unsigned, need to copy to signed */
4119     IV iv = len;
4120     if (iv < 0)
4121     Perl_croak(aTHX_ "panic: sv_setpvn called with negative strlen");
4122     }
4123     (void)SvUPGRADE(sv, SVt_PV);
4124    
4125     SvGROW(sv, len + 1);
4126     dptr = SvPVX(sv);
4127     Move(ptr,dptr,len,char);
4128     dptr[len] = '\0';
4129     SvCUR_set(sv, len);
4130     (void)SvPOK_only_UTF8(sv); /* validate pointer */
4131     SvTAINT(sv);
4132     }
4133    
4134     /*
4135     =for apidoc sv_setpvn_mg
4136    
4137     Like C<sv_setpvn>, but also handles 'set' magic.
4138    
4139     =cut
4140     */
4141    
4142     void
4143     Perl_sv_setpvn_mg(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
4144     {
4145     sv_setpvn(sv,ptr,len);
4146     SvSETMAGIC(sv);
4147     }
4148    
4149     /*
4150     =for apidoc sv_setpv
4151    
4152     Copies a string into an SV. The string must be null-terminated. Does not
4153     handle 'set' magic. See C<sv_setpv_mg>.
4154    
4155     =cut
4156     */
4157    
4158     void
4159     Perl_sv_setpv(pTHX_ register SV *sv, register const char *ptr)
4160     {
4161     register STRLEN len;
4162    
4163     SV_CHECK_THINKFIRST(sv);
4164     if (!ptr) {
4165     (void)SvOK_off(sv);
4166     return;
4167     }
4168     len = strlen(ptr);
4169     (void)SvUPGRADE(sv, SVt_PV);
4170    
4171     SvGROW(sv, len + 1);
4172     Move(ptr,SvPVX(sv),len+1,char);
4173     SvCUR_set(sv, len);
4174     (void)SvPOK_only_UTF8(sv); /* validate pointer */
4175     SvTAINT(sv);
4176     }
4177    
4178     /*
4179     =for apidoc sv_setpv_mg
4180    
4181     Like C<sv_setpv>, but also handles 'set' magic.
4182    
4183     =cut
4184     */
4185    
4186     void
4187     Perl_sv_setpv_mg(pTHX_ register SV *sv, register const char *ptr)
4188     {
4189     sv_setpv(sv,ptr);
4190     SvSETMAGIC(sv);
4191     }
4192    
4193     /*
4194     =for apidoc sv_usepvn
4195    
4196     Tells an SV to use C<ptr> to find its string value. Normally the string is
4197     stored inside the SV but sv_usepvn allows the SV to use an outside string.
4198     The C<ptr> should point to memory that was allocated by C<malloc>. The
4199     string length, C<len>, must be supplied. This function will realloc the
4200     memory pointed to by C<ptr>, so that pointer should not be freed or used by
4201     the programmer after giving it to sv_usepvn. Does not handle 'set' magic.
4202     See C<sv_usepvn_mg>.
4203    
4204     =cut
4205     */
4206    
4207     void
4208     Perl_sv_usepvn(pTHX_ register SV *sv, register char *ptr, register STRLEN len)
4209     {
4210     SV_CHECK_THINKFIRST(sv);
4211     (void)SvUPGRADE(sv, SVt_PV);
4212     if (!ptr) {
4213     (void)SvOK_off(sv);
4214     return;
4215     }
4216     (void)SvOOK_off(sv);
4217     if (SvPVX(sv) && SvLEN(sv))
4218     Safefree(SvPVX(sv));
4219     Renew(ptr, len+1, char);
4220     SvPVX(sv) = ptr;
4221     SvCUR_set(sv, len);
4222     SvLEN_set(sv, len+1);
4223     *SvEND(sv) = '\0';
4224     (void)SvPOK_only_UTF8(sv); /* validate pointer */
4225     SvTAINT(sv);
4226     }
4227    
4228     /*
4229     =for apidoc sv_usepvn_mg
4230    
4231     Like C<sv_usepvn>, but also handles 'set' magic.
4232    
4233     =cut
4234     */
4235    
4236     void
4237     Perl_sv_usepvn_mg(pTHX_ register SV *sv, register char *ptr, register STRLEN len)
4238     {
4239     sv_usepvn(sv,ptr,len);
4240     SvSETMAGIC(sv);
4241     }
4242    
4243     /*
4244     =for apidoc sv_force_normal_flags
4245    
4246     Undo various types of fakery on an SV: if the PV is a shared string, make
4247     a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
4248     an xpvmg. The C<flags> parameter gets passed to C<sv_unref_flags()>
4249     when unrefing. C<sv_force_normal> calls this function with flags set to 0.
4250    
4251     =cut
4252     */
4253    
4254     void
4255     Perl_sv_force_normal_flags(pTHX_ register SV *sv, U32 flags)
4256     {
4257     if (SvREADONLY(sv)) {
4258     if (SvFAKE(sv)) {
4259     char *pvx = SvPVX(sv);
4260     STRLEN len = SvCUR(sv);
4261     U32 hash = SvUVX(sv);
4262     SvFAKE_off(sv);
4263     SvREADONLY_off(sv);
4264     SvGROW(sv, len + 1);
4265     Move(pvx,SvPVX(sv),len,char);
4266     *SvEND(sv) = '\0';
4267     unsharepvn(pvx, SvUTF8(sv) ? -(I32)len : len, hash);
4268     }
4269     else if (IN_PERL_RUNTIME)
4270     Perl_croak(aTHX_ PL_no_modify);
4271     }
4272     if (SvROK(sv))
4273     sv_unref_flags(sv, flags);
4274     else if (SvFAKE(sv) && SvTYPE(sv) == SVt_PVGV)
4275     sv_unglob(sv);
4276     }
4277    
4278     /*
4279     =for apidoc sv_force_normal
4280    
4281     Undo various types of fakery on an SV: if the PV is a shared string, make
4282     a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
4283     an xpvmg. See also C<sv_force_normal_flags>.
4284    
4285     =cut
4286     */
4287    
4288     void
4289     Perl_sv_force_normal(pTHX_ register SV *sv)
4290     {
4291     sv_force_normal_flags(sv, 0);
4292     }
4293    
4294     /*
4295     =for apidoc sv_chop
4296    
4297     Efficient removal of characters from the beginning of the string buffer.
4298     SvPOK(sv) must be true and the C<ptr> must be a pointer to somewhere inside
4299     the string buffer. The C<ptr> becomes the first character of the adjusted
4300     string. Uses the "OOK hack".
4301     Beware: after this function returns, C<ptr> and SvPVX(sv) may no longer
4302     refer to the same chunk of data.
4303    
4304     =cut
4305     */
4306    
4307     void
4308     Perl_sv_chop(pTHX_ register SV *sv, register char *ptr)
4309     {
4310     register STRLEN delta;
4311     if (!ptr || !SvPOKp(sv))
4312     return;
4313     delta = ptr - SvPVX(sv);
4314     SV_CHECK_THINKFIRST(sv);
4315     if (SvTYPE(sv) < SVt_PVIV)
4316     sv_upgrade(sv,SVt_PVIV);
4317    
4318     if (!SvOOK(sv)) {
4319     if (!SvLEN(sv)) { /* make copy of shared string */
4320     char *pvx = SvPVX(sv);
4321     STRLEN len = SvCUR(sv);
4322     SvGROW(sv, len + 1);
4323     Move(pvx,SvPVX(sv),len,char);
4324     *SvEND(sv) = '\0';
4325     }
4326     SvIVX(sv) = 0;
4327     /* Same SvOOK_on but SvOOK_on does a SvIOK_off
4328     and we do that anyway inside the SvNIOK_off
4329     */
4330     SvFLAGS(sv) |= SVf_OOK;
4331     }
4332     SvNIOK_off(sv);
4333     SvLEN(sv) -= delta;
4334     SvCUR(sv) -= delta;
4335     SvPVX(sv) += delta;
4336     SvIVX(sv) += delta;
4337     }
4338    
4339     /* sv_catpvn() is now a macro using Perl_sv_catpvn_flags();
4340     * this function provided for binary compatibility only
4341     */
4342    
4343     void
4344     Perl_sv_catpvn(pTHX_ SV *dsv, const char* sstr, STRLEN slen)
4345     {
4346     sv_catpvn_flags(dsv, sstr, slen, SV_GMAGIC);
4347     }
4348    
4349     /*
4350     =for apidoc sv_catpvn
4351    
4352     Concatenates the string onto the end of the string which is in the SV. The
4353     C<len> indicates number of bytes to copy. If the SV has the UTF-8
4354     status set, then the bytes appended should be valid UTF-8.
4355     Handles 'get' magic, but not 'set' magic. See C<sv_catpvn_mg>.
4356    
4357     =for apidoc sv_catpvn_flags
4358    
4359     Concatenates the string onto the end of the string which is in the SV. The
4360     C<len> indicates number of bytes to copy. If the SV has the UTF-8
4361     status set, then the bytes appended should be valid UTF-8.
4362     If C<flags> has C<SV_GMAGIC> bit set, will C<mg_get> on C<dsv> if
4363     appropriate, else not. C<sv_catpvn> and C<sv_catpvn_nomg> are implemented
4364     in terms of this function.
4365    
4366     =cut
4367     */
4368    
4369     void
4370     Perl_sv_catpvn_flags(pTHX_ register SV *dsv, register const char *sstr, register STRLEN slen, I32 flags)
4371     {
4372     STRLEN dlen;
4373     char *dstr;
4374    
4375     dstr = SvPV_force_flags(dsv, dlen, flags);
4376     SvGROW(dsv, dlen + slen + 1);
4377     if (sstr == dstr)
4378     sstr = SvPVX(dsv);
4379     Move(sstr, SvPVX(dsv) + dlen, slen, char);
4380     SvCUR(dsv) += slen;
4381     *SvEND(dsv) = '\0';
4382     (void)SvPOK_only_UTF8(dsv); /* validate pointer */
4383     SvTAINT(dsv);
4384     }
4385    
4386     /*
4387     =for apidoc sv_catpvn_mg
4388    
4389     Like C<sv_catpvn>, but also handles 'set' magic.
4390    
4391     =cut
4392     */
4393    
4394     void
4395     Perl_sv_catpvn_mg(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
4396     {
4397     sv_catpvn(sv,ptr,len);
4398     SvSETMAGIC(sv);
4399     }
4400    
4401     /* sv_catsv() is now a macro using Perl_sv_catsv_flags();
4402     * this function provided for binary compatibility only
4403     */
4404    
4405     void
4406     Perl_sv_catsv(pTHX_ SV *dstr, register SV *sstr)
4407     {
4408     sv_catsv_flags(dstr, sstr, SV_GMAGIC);
4409     }
4410    
4411     /*
4412     =for apidoc sv_catsv
4413    
4414     Concatenates the string from SV C<ssv> onto the end of the string in
4415     SV C<dsv>. Modifies C<dsv> but not C<ssv>. Handles 'get' magic, but
4416     not 'set' magic. See C<sv_catsv_mg>.
4417    
4418     =for apidoc sv_catsv_flags
4419    
4420     Concatenates the string from SV C<ssv> onto the end of the string in
4421     SV C<dsv>. Modifies C<dsv> but not C<ssv>. If C<flags> has C<SV_GMAGIC>
4422     bit set, will C<mg_get> on the SVs if appropriate, else not. C<sv_catsv>
4423     and C<sv_catsv_nomg> are implemented in terms of this function.
4424    
4425     =cut */
4426    
4427     void
4428     Perl_sv_catsv_flags(pTHX_ SV *dsv, register SV *ssv, I32 flags)
4429     {
4430     char *spv;
4431     STRLEN slen;
4432     if (!ssv)
4433     return;
4434     if ((spv = SvPV(ssv, slen))) {
4435     /* sutf8 and dutf8 were type bool, but under USE_ITHREADS,
4436     gcc version 2.95.2 20000220 (Debian GNU/Linux) for
4437     Linux xxx 2.2.17 on sparc64 with gcc -O2, we erroneously
4438     get dutf8 = 0x20000000, (i.e. SVf_UTF8) even though
4439     dsv->sv_flags doesn't have that bit set.
4440     Andy Dougherty 12 Oct 2001
4441     */
4442     I32 sutf8 = DO_UTF8(ssv);
4443     I32 dutf8;
4444    
4445     if (SvGMAGICAL(dsv) && (flags & SV_GMAGIC))
4446     mg_get(dsv);
4447     dutf8 = DO_UTF8(dsv);
4448    
4449     if (dutf8 != sutf8) {
4450     if (dutf8) {
4451     /* Not modifying source SV, so taking a temporary copy. */
4452     SV* csv = sv_2mortal(newSVpvn(spv, slen));
4453    
4454     sv_utf8_upgrade(csv);
4455     spv = SvPV(csv, slen);
4456     }
4457     else
4458     sv_utf8_upgrade_nomg(dsv);
4459     }
4460     sv_catpvn_nomg(dsv, spv, slen);
4461     }
4462     }
4463    
4464     /*
4465     =for apidoc sv_catsv_mg
4466    
4467     Like C<sv_catsv>, but also handles 'set' magic.
4468    
4469     =cut
4470     */
4471    
4472     void
4473     Perl_sv_catsv_mg(pTHX_ SV *dsv, register SV *ssv)
4474     {
4475     sv_catsv(dsv,ssv);
4476     SvSETMAGIC(dsv);
4477     }
4478    
4479     /*
4480     =for apidoc sv_catpv
4481    
4482     Concatenates the string onto the end of the string which is in the SV.
4483     If the SV has the UTF-8 status set, then the bytes appended should be
4484     valid UTF-8. Handles 'get' magic, but not 'set' magic. See C<sv_catpv_mg>.
4485    
4486     =cut */
4487    
4488     void
4489     Perl_sv_catpv(pTHX_ register SV *sv, register const char *ptr)
4490     {
4491     register STRLEN len;
4492     STRLEN tlen;
4493     char *junk;
4494    
4495     if (!ptr)
4496     return;
4497     junk = SvPV_force(sv, tlen);
4498     len = strlen(ptr);
4499     SvGROW(sv, tlen + len + 1);
4500     if (ptr == junk)
4501     ptr = SvPVX(sv);
4502     Move(ptr,SvPVX(sv)+tlen,len+1,char);
4503     SvCUR(sv) += len;
4504     (void)SvPOK_only_UTF8(sv); /* validate pointer */
4505     SvTAINT(sv);
4506     }
4507    
4508     /*
4509     =for apidoc sv_catpv_mg
4510    
4511     Like C<sv_catpv>, but also handles 'set' magic.
4512    
4513     =cut
4514     */
4515    
4516     void
4517     Perl_sv_catpv_mg(pTHX_ register SV *sv, register const char *ptr)
4518     {
4519     sv_catpv(sv,ptr);
4520     SvSETMAGIC(sv);
4521     }
4522    
4523     /*
4524     =for apidoc newSV
4525    
4526     Create a new null SV, or if len > 0, create a new empty SVt_PV type SV
4527     with an initial PV allocation of len+1. Normally accessed via the C<NEWSV>
4528     macro.
4529    
4530     =cut
4531     */
4532    
4533     SV *
4534     Perl_newSV(pTHX_ STRLEN len)
4535     {
4536     register SV *sv;
4537    
4538     new_SV(sv);
4539     if (len) {
4540     sv_upgrade(sv, SVt_PV);
4541     SvGROW(sv, len + 1);
4542     }
4543     return sv;
4544     }
4545     /*
4546     =for apidoc sv_magicext
4547    
4548     Adds magic to an SV, upgrading it if necessary. Applies the
4549     supplied vtable and returns a pointer to the magic added.
4550    
4551     Note that C<sv_magicext> will allow things that C<sv_magic> will not.
4552     In particular, you can add magic to SvREADONLY SVs, and add more than
4553     one instance of the same 'how'.
4554    
4555     If C<namlen> is greater than zero then a C<savepvn> I<copy> of C<name> is
4556     stored, if C<namlen> is zero then C<name> is stored as-is and - as another
4557     special case - if C<(name && namlen == HEf_SVKEY)> then C<name> is assumed
4558     to contain an C<SV*> and is stored as-is with its REFCNT incremented.
4559    
4560     (This is now used as a subroutine by C<sv_magic>.)
4561    
4562     =cut
4563     */
4564     MAGIC *
4565     Perl_sv_magicext(pTHX_ SV* sv, SV* obj, int how, MGVTBL *vtable,
4566     const char* name, I32 namlen)
4567     {
4568     MAGIC* mg;
4569    
4570     if (SvTYPE(sv) < SVt_PVMG) {
4571     (void)SvUPGRADE(sv, SVt_PVMG);
4572     }
4573     Newz(702,mg, 1, MAGIC);
4574     mg->mg_moremagic = SvMAGIC(sv);
4575     SvMAGIC(sv) = mg;
4576    
4577     /* Sometimes a magic contains a reference loop, where the sv and
4578     object refer to each other. To prevent a reference loop that
4579     would prevent such objects being freed, we look for such loops
4580     and if we find one we avoid incrementing the object refcount.
4581    
4582     Note we cannot do this to avoid self-tie loops as intervening RV must
4583     have its REFCNT incremented to keep it in existence.
4584    
4585     */
4586     if (!obj || obj == sv ||
4587     how == PERL_MAGIC_arylen ||
4588     how == PERL_MAGIC_qr ||
4589     (SvTYPE(obj) == SVt_PVGV &&
4590     (GvSV(obj) == sv || GvHV(obj) == (HV*)sv || GvAV(obj) == (AV*)sv ||
4591     GvCV(obj) == (CV*)sv || GvIOp(obj) == (IO*)sv ||
4592     GvFORM(obj) == (CV*)sv)))
4593     {
4594     mg->mg_obj = obj;
4595     }
4596     else {
4597     mg->mg_obj = SvREFCNT_inc(obj);
4598     mg->mg_flags |= MGf_REFCOUNTED;
4599     }
4600    
4601     /* Normal self-ties simply pass a null object, and instead of
4602     using mg_obj directly, use the SvTIED_obj macro to produce a
4603     new RV as needed. For glob "self-ties", we are tieing the PVIO
4604     with an RV obj pointing to the glob containing the PVIO. In
4605     this case, to avoid a reference loop, we need to weaken the
4606     reference.
4607     */
4608    
4609     if (how == PERL_MAGIC_tiedscalar && SvTYPE(sv) == SVt_PVIO &&
4610     obj && SvROK(obj) && GvIO(SvRV(obj)) == (IO*)sv)
4611     {
4612     sv_rvweaken(obj);
4613     }
4614    
4615     mg->mg_type = how;
4616     mg->mg_len = namlen;
4617     if (name) {
4618     if (namlen > 0)
4619     mg->mg_ptr = savepvn(name, namlen);
4620     else if (namlen == HEf_SVKEY)
4621     mg->mg_ptr = (char*)SvREFCNT_inc((SV*)name);
4622     else
4623     mg->mg_ptr = (char *) name;
4624     }
4625     mg->mg_virtual = vtable;
4626    
4627     mg_magical(sv);
4628     if (SvGMAGICAL(sv))
4629     SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK|SVf_POK);
4630     return mg;
4631     }
4632    
4633     /*
4634     =for apidoc sv_magic
4635    
4636     Adds magic to an SV. First upgrades C<sv> to type C<SVt_PVMG> if necessary,
4637     then adds a new magic item of type C<how> to the head of the magic list.
4638    
4639     See C<sv_magicext> (which C<sv_magic> now calls) for a description of the
4640     handling of the C<name> and C<namlen> arguments.
4641    
4642     You need to use C<sv_magicext> to add magic to SvREADONLY SVs and also
4643     to add more than one instance of the same 'how'.
4644    
4645     =cut
4646     */
4647    
4648     void
4649     Perl_sv_magic(pTHX_ register SV *sv, SV *obj, int how, const char *name, I32 namlen)
4650     {
4651     MAGIC* mg;
4652     MGVTBL *vtable = 0;
4653    
4654     if (SvREADONLY(sv)) {
4655     if (IN_PERL_RUNTIME
4656     && how != PERL_MAGIC_regex_global
4657     && how != PERL_MAGIC_bm
4658     && how != PERL_MAGIC_fm
4659     && how != PERL_MAGIC_sv
4660     && how != PERL_MAGIC_backref
4661     )
4662     {
4663     Perl_croak(aTHX_ PL_no_modify);
4664     }
4665     }
4666     if (SvMAGICAL(sv) || (how == PERL_MAGIC_taint && SvTYPE(sv) >= SVt_PVMG)) {
4667     if (SvMAGIC(sv) && (mg = mg_find(sv, how))) {
4668     /* sv_magic() refuses to add a magic of the same 'how' as an
4669     existing one
4670     */
4671     if (how == PERL_MAGIC_taint)
4672     mg->mg_len |= 1;
4673     return;
4674     }
4675     }
4676    
4677     switch (how) {
4678     case PERL_MAGIC_sv:
4679     vtable = &PL_vtbl_sv;
4680     break;
4681     case PERL_MAGIC_overload:
4682     vtable = &PL_vtbl_amagic;
4683     break;
4684     case PERL_MAGIC_overload_elem:
4685     vtable = &PL_vtbl_amagicelem;
4686     break;
4687     case PERL_MAGIC_overload_table:
4688     vtable = &PL_vtbl_ovrld;
4689     break;
4690     case PERL_MAGIC_bm:
4691     vtable = &PL_vtbl_bm;
4692     break;
4693     case PERL_MAGIC_regdata:
4694     vtable = &PL_vtbl_regdata;
4695     break;
4696     case PERL_MAGIC_regdatum:
4697     vtable = &PL_vtbl_regdatum;
4698     break;
4699     case PERL_MAGIC_env:
4700     vtable = &PL_vtbl_env;
4701     break;
4702     case PERL_MAGIC_fm:
4703     vtable = &PL_vtbl_fm;
4704     break;
4705     case PERL_MAGIC_envelem:
4706     vtable = &PL_vtbl_envelem;
4707     break;
4708     case PERL_MAGIC_regex_global:
4709     vtable = &PL_vtbl_mglob;
4710     break;
4711     case PERL_MAGIC_isa:
4712     vtable = &PL_vtbl_isa;
4713     break;
4714     case PERL_MAGIC_isaelem:
4715     vtable = &PL_vtbl_isaelem;
4716     break;
4717     case PERL_MAGIC_nkeys:
4718     vtable = &PL_vtbl_nkeys;
4719     break;
4720     case PERL_MAGIC_dbfile:
4721     vtable = 0;
4722     break;
4723     case PERL_MAGIC_dbline:
4724     vtable = &PL_vtbl_dbline;
4725     break;
4726     #ifdef USE_5005THREADS
4727     case PERL_MAGIC_mutex:
4728     vtable = &PL_vtbl_mutex;
4729     break;
4730     #endif /* USE_5005THREADS */
4731     #ifdef USE_LOCALE_COLLATE
4732     case PERL_MAGIC_collxfrm:
4733     vtable = &PL_vtbl_collxfrm;
4734     break;
4735     #endif /* USE_LOCALE_COLLATE */
4736     case PERL_MAGIC_tied:
4737     vtable = &PL_vtbl_pack;
4738     break;
4739     case PERL_MAGIC_tiedelem:
4740     case PERL_MAGIC_tiedscalar:
4741     vtable = &PL_vtbl_packelem;
4742     break;
4743     case PERL_MAGIC_qr:
4744     vtable = &PL_vtbl_regexp;
4745     break;
4746     case PERL_MAGIC_sig:
4747     vtable = &PL_vtbl_sig;
4748     break;
4749     case PERL_MAGIC_sigelem:
4750     vtable = &PL_vtbl_sigelem;
4751     break;
4752     case PERL_MAGIC_taint:
4753     vtable = &PL_vtbl_taint;
4754     break;
4755     case PERL_MAGIC_uvar:
4756     vtable = &PL_vtbl_uvar;
4757     break;
4758     case PERL_MAGIC_vec:
4759     vtable = &PL_vtbl_vec;
4760     break;
4761     case PERL_MAGIC_vstring:
4762     vtable = 0;
4763     break;
4764     case PERL_MAGIC_utf8:
4765     vtable = &PL_vtbl_utf8;
4766     break;
4767     case PERL_MAGIC_substr:
4768     vtable = &PL_vtbl_substr;
4769     break;
4770     case PERL_MAGIC_defelem:
4771     vtable = &PL_vtbl_defelem;
4772     break;
4773     case PERL_MAGIC_glob:
4774     vtable = &PL_vtbl_glob;
4775     break;
4776     case PERL_MAGIC_arylen:
4777     vtable = &PL_vtbl_arylen;
4778     break;
4779     case PERL_MAGIC_pos:
4780     vtable = &PL_vtbl_pos;
4781     break;
4782     case PERL_MAGIC_backref:
4783     vtable = &PL_vtbl_backref;
4784     break;
4785     case PERL_MAGIC_ext:
4786     /* Reserved for use by extensions not perl internals. */
4787     /* Useful for attaching extension internal data to perl vars. */
4788     /* Note that multiple extensions may clash if magical scalars */
4789     /* etc holding private data from one are passed to another. */
4790     break;
4791     default:
4792     Perl_croak(aTHX_ "Don't know how to handle magic of type \\%o", how);
4793     }
4794    
4795     /* Rest of work is done else where */
4796     mg = sv_magicext(sv,obj,how,vtable,name,namlen);
4797    
4798     switch (how) {
4799     case PERL_MAGIC_taint:
4800     mg->mg_len = 1;
4801     break;
4802     case PERL_MAGIC_ext:
4803     case PERL_MAGIC_dbfile:
4804     SvRMAGICAL_on(sv);
4805     break;
4806     }
4807     }
4808    
4809     /*
4810     =for apidoc sv_unmagic
4811    
4812     Removes all magic of type C<type> from an SV.
4813    
4814     =cut
4815     */
4816    
4817     int
4818     Perl_sv_unmagic(pTHX_ SV *sv, int type)
4819     {
4820     MAGIC* mg;
4821     MAGIC** mgp;
4822     if (SvTYPE(sv) < SVt_PVMG || !SvMAGIC(sv))
4823     return 0;
4824     mgp = &SvMAGIC(sv);
4825     for (mg = *mgp; mg; mg = *mgp) {
4826     if (mg->mg_type == type) {
4827     MGVTBL* vtbl = mg->mg_virtual;
4828     *mgp = mg->mg_moremagic;
4829     if (vtbl && vtbl->svt_free)
4830     CALL_FPTR(vtbl->svt_free)(aTHX_ sv, mg);
4831     if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) {
4832     if (mg->mg_len > 0)
4833     Safefree(mg->mg_ptr);
4834     else if (mg->mg_len == HEf_SVKEY)
4835     SvREFCNT_dec((SV*)mg->mg_ptr);
4836     else if (mg->mg_type == PERL_MAGIC_utf8 && mg->mg_ptr)
4837     Safefree(mg->mg_ptr);
4838     }
4839     if (mg->mg_flags & MGf_REFCOUNTED)
4840     SvREFCNT_dec(mg->mg_obj);
4841     Safefree(mg);
4842     }
4843     else
4844     mgp = &mg->mg_moremagic;
4845     }
4846     if (!SvMAGIC(sv)) {
4847     SvMAGICAL_off(sv);
4848     SvFLAGS(sv) |= (SvFLAGS(sv) & (SVp_NOK|SVp_POK)) >> PRIVSHIFT;
4849     }
4850    
4851     return 0;
4852     }
4853    
4854     /*
4855     =for apidoc sv_rvweaken
4856    
4857     Weaken a reference: set the C<SvWEAKREF> flag on this RV; give the
4858     referred-to SV C<PERL_MAGIC_backref> magic if it hasn't already; and
4859     push a back-reference to this RV onto the array of backreferences
4860     associated with that magic.
4861    
4862     =cut
4863     */
4864    
4865     SV *
4866     Perl_sv_rvweaken(pTHX_ SV *sv)
4867     {
4868     SV *tsv;
4869     if (!SvOK(sv)) /* let undefs pass */
4870     return sv;
4871     if (!SvROK(sv))
4872     Perl_croak(aTHX_ "Can't weaken a nonreference");
4873     else if (SvWEAKREF(sv)) {
4874     if (ckWARN(WARN_MISC))
4875     Perl_warner(aTHX_ packWARN(WARN_MISC), "Reference is already weak");
4876     return sv;
4877     }
4878     tsv = SvRV(sv);
4879     sv_add_backref(tsv, sv);
4880     SvWEAKREF_on(sv);
4881     SvREFCNT_dec(tsv);
4882     return sv;
4883     }
4884    
4885     /* Give tsv backref magic if it hasn't already got it, then push a
4886     * back-reference to sv onto the array associated with the backref magic.
4887     */
4888    
4889     STATIC void
4890     S_sv_add_backref(pTHX_ SV *tsv, SV *sv)
4891     {
4892     AV *av;
4893     MAGIC *mg;
4894     if (SvMAGICAL(tsv) && (mg = mg_find(tsv, PERL_MAGIC_backref)))
4895     av = (AV*)mg->mg_obj;
4896     else {
4897     av = newAV();
4898     sv_magic(tsv, (SV*)av, PERL_MAGIC_backref, NULL, 0);
4899     /* av now has a refcnt of 2, which avoids it getting freed
4900     * before us during global cleanup. The extra ref is removed
4901     * by magic_killbackrefs() when tsv is being freed */
4902     }
4903     if (AvFILLp(av) >= AvMAX(av)) {
4904     I32 i;
4905     SV **svp = AvARRAY(av);
4906     for (i = AvFILLp(av); i >= 0; i--)
4907     if (!svp[i]) {
4908     svp[i] = sv; /* reuse the slot */
4909     return;
4910     }
4911     av_extend(av, AvFILLp(av)+1);
4912     }
4913     AvARRAY(av)[++AvFILLp(av)] = sv; /* av_push() */
4914     }
4915    
4916     /* delete a back-reference to ourselves from the backref magic associated
4917     * with the SV we point to.
4918     */
4919    
4920     STATIC void
4921     S_sv_del_backref(pTHX_ SV *sv)
4922     {
4923     AV *av;
4924     SV **svp;
4925     I32 i;
4926     SV *tsv = SvRV(sv);
4927     MAGIC *mg = NULL;
4928     if (!SvMAGICAL(tsv) || !(mg = mg_find(tsv, PERL_MAGIC_backref)))
4929     Perl_croak(aTHX_ "panic: del_backref");
4930     av = (AV *)mg->mg_obj;
4931     svp = AvARRAY(av);
4932     for (i = AvFILLp(av); i >= 0; i--)
4933     if (svp[i] == sv) svp[i] = Nullsv;
4934     }
4935    
4936     /*
4937     =for apidoc sv_insert
4938    
4939     Inserts a string at the specified offset/length within the SV. Similar to
4940     the Perl substr() function.
4941    
4942     =cut
4943     */
4944    
4945     void
4946     Perl_sv_insert(pTHX_ SV *bigstr, STRLEN offset, STRLEN len, char *little, STRLEN littlelen)
4947     {
4948     register char *big;
4949     register char *mid;
4950     register char *midend;
4951     register char *bigend;
4952     register I32 i;
4953     STRLEN curlen;
4954    
4955    
4956     if (!bigstr)
4957     Perl_croak(aTHX_ "Can't modify non-existent substring");
4958     SvPV_force(bigstr, curlen);
4959     (void)SvPOK_only_UTF8(bigstr);
4960     if (offset + len > curlen) {
4961     SvGROW(bigstr, offset+len+1);
4962     Zero(SvPVX(bigstr)+curlen, offset+len-curlen, char);
4963     SvCUR_set(bigstr, offset+len);
4964     }
4965    
4966     SvTAINT(bigstr);
4967     i = littlelen - len;
4968     if (i > 0) { /* string might grow */
4969     big = SvGROW(bigstr, SvCUR(bigstr) + i + 1);
4970     mid = big + offset + len;
4971     midend = bigend = big + SvCUR(bigstr);
4972     bigend += i;
4973     *bigend = '\0';
4974     while (midend > mid) /* shove everything down */
4975     *--bigend = *--midend;
4976     Move(little,big+offset,littlelen,char);
4977     SvCUR(bigstr) += i;
4978     SvSETMAGIC(bigstr);
4979     return;
4980     }
4981     else if (i == 0) {
4982     Move(little,SvPVX(bigstr)+offset,len,char);
4983     SvSETMAGIC(bigstr);
4984     return;
4985     }
4986    
4987     big = SvPVX(bigstr);
4988     mid = big + offset;
4989     midend = mid + len;
4990     bigend = big + SvCUR(bigstr);
4991    
4992     if (midend > bigend)
4993     Perl_croak(aTHX_ "panic: sv_insert");
4994    
4995     if (mid - big > bigend - midend) { /* faster to shorten from end */
4996     if (littlelen) {
4997     Move(little, mid, littlelen,char);
4998     mid += littlelen;
4999     }
5000     i = bigend - midend;
5001     if (i > 0) {
5002     Move(midend, mid, i,char);
5003     mid += i;
5004     }
5005     *mid = '\0';
5006     SvCUR_set(bigstr, mid - big);
5007     }
5008     /*SUPPRESS 560*/
5009     else if ((i = mid - big)) { /* faster from front */
5010     midend -= littlelen;
5011     mid = midend;
5012     sv_chop(bigstr,midend-i);
5013     big += i;
5014     while (i--)
5015     *--midend = *--big;
5016     if (littlelen)
5017     Move(little, mid, littlelen,char);
5018     }
5019     else if (littlelen) {
5020     midend -= littlelen;
5021     sv_chop(bigstr,midend);
5022     Move(little,midend,littlelen,char);
5023     }
5024     else {
5025     sv_chop(bigstr,midend);
5026     }
5027     SvSETMAGIC(bigstr);
5028     }
5029    
5030     /*
5031     =for apidoc sv_replace
5032    
5033     Make the first argument a copy of the second, then delete the original.
5034     The target SV physically takes over ownership of the body of the source SV
5035     and inherits its flags; however, the target keeps any magic it owns,
5036     and any magic in the source is discarded.
5037     Note that this is a rather specialist SV copying operation; most of the
5038     time you'll want to use C<sv_setsv> or one of its many macro front-ends.
5039    
5040     =cut
5041     */
5042    
5043     void
5044     Perl_sv_replace(pTHX_ register SV *sv, register SV *nsv)
5045     {
5046     U32 refcnt = SvREFCNT(sv);
5047     SV_CHECK_THINKFIRST(sv);
5048     if (SvREFCNT(nsv) != 1 && ckWARN_d(WARN_INTERNAL))
5049     Perl_warner(aTHX_ packWARN(WARN_INTERNAL), "Reference miscount in sv_replace()");
5050     if (SvMAGICAL(sv)) {
5051     if (SvMAGICAL(nsv))
5052     mg_free(nsv);
5053     else
5054     sv_upgrade(nsv, SVt_PVMG);
5055     SvMAGIC(nsv) = SvMAGIC(sv);
5056     SvFLAGS(nsv) |= SvMAGICAL(sv);
5057     SvMAGICAL_off(sv);
5058     SvMAGIC(sv) = 0;
5059     }
5060     SvREFCNT(sv) = 0;
5061     sv_clear(sv);
5062     assert(!SvREFCNT(sv));
5063     StructCopy(nsv,sv,SV);
5064     SvREFCNT(sv) = refcnt;
5065     SvFLAGS(nsv) |= SVTYPEMASK; /* Mark as freed */
5066     SvREFCNT(nsv) = 0;
5067     del_SV(nsv);
5068     }
5069    
5070     /*
5071     =for apidoc sv_clear
5072    
5073     Clear an SV: call any destructors, free up any memory used by the body,
5074     and free the body itself. The SV's head is I<not> freed, although
5075     its type is set to all 1's so that it won't inadvertently be assumed
5076     to be live during global destruction etc.
5077     This function should only be called when REFCNT is zero. Most of the time
5078     you'll want to call C<sv_free()> (or its macro wrapper C<SvREFCNT_dec>)
5079     instead.
5080    
5081     =cut
5082     */
5083    
5084     void
5085     Perl_sv_clear(pTHX_ register SV *sv)
5086     {
5087     HV* stash;
5088     assert(sv);
5089     assert(SvREFCNT(sv) == 0);
5090    
5091     if (SvOBJECT(sv)) {
5092     if (PL_defstash) { /* Still have a symbol table? */
5093     dSP;
5094     CV* destructor;
5095    
5096    
5097    
5098     do {
5099     stash = SvSTASH(sv);
5100     destructor = StashHANDLER(stash,DESTROY);
5101     if (destructor) {
5102     SV* tmpref = newRV(sv);
5103     SvREADONLY_on(tmpref); /* DESTROY() could be naughty */
5104     ENTER;
5105     PUSHSTACKi(PERLSI_DESTROY);
5106     EXTEND(SP, 2);
5107     PUSHMARK(SP);
5108     PUSHs(tmpref);
5109     PUTBACK;
5110     call_sv((SV*)destructor, G_DISCARD|G_EVAL|G_KEEPERR|G_VOID);
5111    
5112    
5113     POPSTACK;
5114     SPAGAIN;
5115     LEAVE;
5116     if(SvREFCNT(tmpref) < 2) {
5117     /* tmpref is not kept alive! */
5118     SvREFCNT(sv)--;
5119     SvRV(tmpref) = 0;
5120     SvROK_off(tmpref);
5121     }
5122     SvREFCNT_dec(tmpref);
5123     }
5124     } while (SvOBJECT(sv) && SvSTASH(sv) != stash);
5125    
5126    
5127     if (SvREFCNT(sv)) {
5128     if (PL_in_clean_objs)
5129     Perl_croak(aTHX_ "DESTROY created new reference to dead object '%s'",
5130     HvNAME(stash));
5131     /* DESTROY gave object new lease on life */
5132     return;
5133     }
5134     }
5135    
5136     if (SvOBJECT(sv)) {
5137     SvREFCNT_dec(SvSTASH(sv)); /* possibly of changed persuasion */
5138     SvOBJECT_off(sv); /* Curse the object. */
5139     if (SvTYPE(sv) != SVt_PVIO)
5140     --PL_sv_objcount; /* XXX Might want something more general */
5141     }
5142     }
5143     if (SvTYPE(sv) >= SVt_PVMG) {
5144     if (SvMAGIC(sv))
5145     mg_free(sv);
5146     if (SvFLAGS(sv) & SVpad_TYPED)
5147     SvREFCNT_dec(SvSTASH(sv));
5148     }
5149     stash = NULL;
5150     switch (SvTYPE(sv)) {
5151     case SVt_PVIO:
5152     if (IoIFP(sv) &&
5153     IoIFP(sv) != PerlIO_stdin() &&
5154     IoIFP(sv) != PerlIO_stdout() &&
5155     IoIFP(sv) != PerlIO_stderr())
5156     {
5157     io_close((IO*)sv, FALSE);
5158     }
5159     if (IoDIRP(sv) && !(IoFLAGS(sv) & IOf_FAKE_DIRP))
5160     PerlDir_close(IoDIRP(sv));
5161     IoDIRP(sv) = (DIR*)NULL;
5162     Safefree(IoTOP_NAME(sv));
5163     Safefree(IoFMT_NAME(sv));
5164     Safefree(IoBOTTOM_NAME(sv));
5165     /* FALL THROUGH */
5166     case SVt_PVBM:
5167     goto freescalar;
5168     case SVt_PVCV:
5169     case SVt_PVFM:
5170     cv_undef((CV*)sv);
5171     goto freescalar;
5172     case SVt_PVHV:
5173     hv_undef((HV*)sv);
5174     break;
5175     case SVt_PVAV:
5176     av_undef((AV*)sv);
5177     break;
5178     case SVt_PVLV:
5179     if (LvTYPE(sv) == 'T') { /* for tie: return HE to pool */
5180     SvREFCNT_dec(HeKEY_sv((HE*)LvTARG(sv)));
5181     HeNEXT((HE*)LvTARG(sv)) = PL_hv_fetch_ent_mh;
5182     PL_hv_fetch_ent_mh = (HE*)LvTARG(sv);
5183     }
5184     else if (LvTYPE(sv) != 't') /* unless tie: unrefcnted fake SV** */
5185     SvREFCNT_dec(LvTARG(sv));
5186     goto freescalar;
5187     case SVt_PVGV:
5188     gp_free((GV*)sv);
5189     Safefree(GvNAME(sv));
5190     /* cannot decrease stash refcount yet, as we might recursively delete
5191     ourselves when the refcnt drops to zero. Delay SvREFCNT_dec
5192     of stash until current sv is completely gone.
5193     -- JohnPC, 27 Mar 1998 */
5194     stash = GvSTASH(sv);
5195     /* FALL THROUGH */
5196     case SVt_PVMG:
5197     case SVt_PVNV:
5198     case SVt_PVIV:
5199     freescalar:
5200     SvOOK_off(sv);
5201     /* FALL THROUGH */
5202     case SVt_PV:
5203     case SVt_RV:
5204     if (SvROK(sv)) {
5205     if (SvWEAKREF(sv))
5206     sv_del_backref(sv);
5207     else
5208     SvREFCNT_dec(SvRV(sv));
5209     }
5210     else if (SvPVX(sv) && SvLEN(sv))
5211     Safefree(SvPVX(sv));
5212     else if (SvPVX(sv) && SvREADONLY(sv) && SvFAKE(sv)) {
5213     unsharepvn(SvPVX(sv),
5214     SvUTF8(sv) ? -(I32)SvCUR(sv) : SvCUR(sv),
5215     SvUVX(sv));
5216     SvFAKE_off(sv);
5217     }
5218     break;
5219     /*
5220     case SVt_NV:
5221     case SVt_IV:
5222     case SVt_NULL:
5223     break;
5224     */
5225     }
5226    
5227     switch (SvTYPE(sv)) {
5228     case SVt_NULL:
5229     break;
5230     case SVt_IV:
5231     del_XIV(SvANY(sv));
5232     break;
5233     case SVt_NV:
5234     del_XNV(SvANY(sv));
5235     break;
5236     case SVt_RV:
5237     del_XRV(SvANY(sv));
5238     break;
5239     case SVt_PV:
5240     del_XPV(SvANY(sv));
5241     break;
5242     case SVt_PVIV:
5243     del_XPVIV(SvANY(sv));
5244     break;
5245     case SVt_PVNV:
5246     del_XPVNV(SvANY(sv));
5247     break;
5248     case SVt_PVMG:
5249     del_XPVMG(SvANY(sv));
5250     break;
5251     case SVt_PVLV:
5252     del_XPVLV(SvANY(sv));
5253     break;
5254     case SVt_PVAV:
5255     del_XPVAV(SvANY(sv));
5256     break;
5257     case SVt_PVHV:
5258     del_XPVHV(SvANY(sv));
5259     break;
5260     case SVt_PVCV:
5261     del_XPVCV(SvANY(sv));
5262     break;
5263     case SVt_PVGV:
5264     del_XPVGV(SvANY(sv));
5265     /* code duplication for increased performance. */
5266     SvFLAGS(sv) &= SVf_BREAK;
5267     SvFLAGS(sv) |= SVTYPEMASK;
5268     /* decrease refcount of the stash that owns this GV, if any */
5269     if (stash)
5270     SvREFCNT_dec(stash);
5271     return; /* not break, SvFLAGS reset already happened */
5272     case SVt_PVBM:
5273     del_XPVBM(SvANY(sv));
5274     break;
5275     case SVt_PVFM:
5276     del_XPVFM(SvANY(sv));
5277     break;
5278     case SVt_PVIO:
5279     del_XPVIO(SvANY(sv));
5280     break;
5281     }
5282     SvFLAGS(sv) &= SVf_BREAK;
5283     SvFLAGS(sv) |= SVTYPEMASK;
5284     }
5285    
5286     /*
5287     =for apidoc sv_newref
5288    
5289     Increment an SV's reference count. Use the C<SvREFCNT_inc()> wrapper
5290     instead.
5291    
5292     =cut
5293     */
5294    
5295     SV *
5296     Perl_sv_newref(pTHX_ SV *sv)
5297     {
5298     if (sv)
5299     ATOMIC_INC(SvREFCNT(sv));
5300     return sv;
5301     }
5302    
5303     /*
5304     =for apidoc sv_free
5305    
5306     Decrement an SV's reference count, and if it drops to zero, call
5307     C<sv_clear> to invoke destructors and free up any memory used by
5308     the body; finally, deallocate the SV's head itself.
5309     Normally called via a wrapper macro C<SvREFCNT_dec>.
5310    
5311     =cut
5312     */
5313    
5314     void
5315     Perl_sv_free(pTHX_ SV *sv)
5316     {
5317     int refcount_is_zero;
5318    
5319     if (!sv)
5320     return;
5321     if (SvREFCNT(sv) == 0) {
5322     if (SvFLAGS(sv) & SVf_BREAK)
5323     /* this SV's refcnt has been artificially decremented to
5324     * trigger cleanup */
5325     return;
5326     if (PL_in_clean_all) /* All is fair */
5327     return;
5328     if (SvREADONLY(sv) && SvIMMORTAL(sv)) {
5329     /* make sure SvREFCNT(sv)==0 happens very seldom */
5330     SvREFCNT(sv) = (~(U32)0)/2;
5331     return;
5332     }
5333     if (ckWARN_d(WARN_INTERNAL))
5334     Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
5335     "Attempt to free unreferenced scalar: SV 0x%"UVxf
5336     pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
5337     return;
5338     }
5339     ATOMIC_DEC_AND_TEST(refcount_is_zero, SvREFCNT(sv));
5340     if (!refcount_is_zero)
5341     return;
5342     #ifdef DEBUGGING
5343     if (SvTEMP(sv)) {
5344     if (ckWARN_d(WARN_DEBUGGING))
5345     Perl_warner(aTHX_ packWARN(WARN_DEBUGGING),
5346     "Attempt to free temp prematurely: SV 0x%"UVxf
5347     pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
5348     return;
5349     }
5350     #endif
5351     if (SvREADONLY(sv) && SvIMMORTAL(sv)) {
5352     /* make sure SvREFCNT(sv)==0 happens very seldom */
5353     SvREFCNT(sv) = (~(U32)0)/2;
5354     return;
5355     }
5356     sv_clear(sv);
5357     if (! SvREFCNT(sv))
5358     del_SV(sv);
5359     }
5360    
5361     /*
5362     =for apidoc sv_len
5363    
5364     Returns the length of the string in the SV. Handles magic and type
5365     coercion. See also C<SvCUR>, which gives raw access to the xpv_cur slot.
5366    
5367     =cut
5368     */
5369    
5370     STRLEN
5371     Perl_sv_len(pTHX_ register SV *sv)
5372     {
5373     STRLEN len;
5374    
5375     if (!sv)
5376     return 0;
5377    
5378     if (SvGMAGICAL(sv))
5379     len = mg_length(sv);
5380     else
5381     (void)SvPV(sv, len);
5382     return len;
5383     }
5384    
5385     /*
5386     =for apidoc sv_len_utf8
5387    
5388     Returns the number of characters in the string in an SV, counting wide
5389     UTF-8 bytes as a single character. Handles magic and type coercion.
5390    
5391     =cut
5392     */
5393    
5394     /*
5395     * The length is cached in PERL_UTF8_magic, in the mg_len field. Also the
5396     * mg_ptr is used, by sv_pos_u2b(), see the comments of S_utf8_mg_pos_init().
5397     * (Note that the mg_len is not the length of the mg_ptr field.)
5398     *
5399     */
5400    
5401     STRLEN
5402     Perl_sv_len_utf8(pTHX_ register SV *sv)
5403     {
5404     if (!sv)
5405     return 0;
5406    
5407     if (SvGMAGICAL(sv))
5408     return mg_length(sv);
5409     else
5410     {
5411     STRLEN len, ulen;
5412     U8 *s = (U8*)SvPV(sv, len);
5413     MAGIC *mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : 0;
5414    
5415     if (mg && mg->mg_len != -1 && (mg->mg_len > 0 || len == 0)) {
5416     ulen = mg->mg_len;
5417     #ifdef PERL_UTF8_CACHE_ASSERT
5418     assert(ulen == Perl_utf8_length(aTHX_ s, s + len));
5419     #endif
5420     }
5421     else {
5422     ulen = Perl_utf8_length(aTHX_ s, s + len);
5423     if (!mg && !SvREADONLY(sv)) {
5424     sv_magic(sv, 0, PERL_MAGIC_utf8, 0, 0);
5425     mg = mg_find(sv, PERL_MAGIC_utf8);
5426     assert(mg);
5427     }
5428     if (mg)
5429     mg->mg_len = ulen;
5430     }
5431     return ulen;
5432     }
5433     }
5434    
5435     /* S_utf8_mg_pos_init() is used to initialize the mg_ptr field of
5436     * a PERL_UTF8_magic. The mg_ptr is used to store the mapping
5437     * between UTF-8 and byte offsets. There are two (substr offset and substr
5438     * length, the i offset, PERL_MAGIC_UTF8_CACHESIZE) times two (UTF-8 offset
5439     * and byte offset) cache positions.
5440     *
5441     * The mg_len field is used by sv_len_utf8(), see its comments.
5442     * Note that the mg_len is not the length of the mg_ptr field.
5443     *
5444     */
5445     STATIC bool
5446     S_utf8_mg_pos_init(pTHX_ SV *sv, MAGIC **mgp, STRLEN **cachep, I32 i, I32 *offsetp, U8 *s, U8 *start)
5447     {
5448     bool found = FALSE;
5449    
5450     if (SvMAGICAL(sv) && !SvREADONLY(sv)) {
5451     if (!*mgp)
5452     *mgp = sv_magicext(sv, 0, PERL_MAGIC_utf8, &PL_vtbl_utf8, 0, 0);
5453     assert(*mgp);
5454    
5455     if ((*mgp)->mg_ptr)
5456     *cachep = (STRLEN *) (*mgp)->mg_ptr;
5457     else {
5458     Newz(0, *cachep, PERL_MAGIC_UTF8_CACHESIZE * 2, STRLEN);
5459     (*mgp)->mg_ptr = (char *) *cachep;
5460     }
5461     assert(*cachep);
5462    
5463     (*cachep)[i] = *offsetp;
5464     (*cachep)[i+1] = s - start;
5465     found = TRUE;
5466     }
5467    
5468     return found;
5469     }
5470    
5471     /*
5472     * S_utf8_mg_pos() is used to query and update mg_ptr field of
5473     * a PERL_UTF8_magic. The mg_ptr is used to store the mapping
5474     * between UTF-8 and byte offsets. See also the comments of
5475     * S_utf8_mg_pos_init().
5476     *
5477     */
5478     STATIC bool
5479     S_utf8_mg_pos(pTHX_ SV *sv, MAGIC **mgp, STRLEN **cachep, I32 i, I32 *offsetp, I32 uoff, U8 **sp, U8 *start, U8 *send)
5480     {
5481     bool found = FALSE;
5482    
5483     if (SvMAGICAL(sv) && !SvREADONLY(sv)) {
5484     if (!*mgp)
5485     *mgp = mg_find(sv, PERL_MAGIC_utf8);
5486     if (*mgp && (*mgp)->mg_ptr) {
5487     *cachep = (STRLEN *) (*mgp)->mg_ptr;
5488     ASSERT_UTF8_CACHE(*cachep);
5489     if ((*cachep)[i] == (STRLEN)uoff) /* An exact match. */
5490     found = TRUE;
5491     else { /* We will skip to the right spot. */
5492     STRLEN forw = 0;
5493     STRLEN backw = 0;
5494     U8* p = NULL;
5495    
5496     /* The assumption is that going backward is half
5497     * the speed of going forward (that's where the
5498     * 2 * backw in the below comes from). (The real
5499     * figure of course depends on the UTF-8 data.) */
5500    
5501     if ((*cachep)[i] > (STRLEN)uoff) {
5502     forw = uoff;
5503     backw = (*cachep)[i] - (STRLEN)uoff;
5504    
5505     if (forw < 2 * backw)
5506     p = start;
5507     else
5508     p = start + (*cachep)[i+1];
5509     }
5510     /* Try this only for the substr offset (i == 0),
5511     * not for the substr length (i == 2). */
5512     else if (i == 0) { /* (*cachep)[i] < uoff */
5513     STRLEN ulen = sv_len_utf8(sv);
5514    
5515     if ((STRLEN)uoff < ulen) {
5516     forw = (STRLEN)uoff - (*cachep)[i];
5517     backw = ulen - (STRLEN)uoff;
5518    
5519     if (forw < 2 * backw)
5520     p = start + (*cachep)[i+1];
5521     else
5522     p = send;
5523     }
5524    
5525     /* If the string is not long enough for uoff,
5526     * we could extend it, but not at this low a level. */
5527     }
5528    
5529     if (p) {
5530     if (forw < 2 * backw) {
5531     while (forw--)
5532     p += UTF8SKIP(p);
5533     }
5534     else {
5535     while (backw--) {
5536     p--;
5537     while (UTF8_IS_CONTINUATION(*p))
5538     p--;
5539     }
5540     }
5541    
5542     /* Update the cache. */
5543     (*cachep)[i] = (STRLEN)uoff;
5544     (*cachep)[i+1] = p - start;
5545    
5546     /* Drop the stale "length" cache */
5547     if (i == 0) {
5548     (*cachep)[2] = 0;
5549     (*cachep)[3] = 0;
5550     }
5551    
5552     found = TRUE;
5553     }
5554     }
5555     if (found) { /* Setup the return values. */
5556     *offsetp = (*cachep)[i+1];
5557     *sp = start + *offsetp;
5558     if (*sp >= send) {
5559     *sp = send;
5560     *offsetp = send - start;
5561     }
5562     else if (*sp < start) {
5563     *sp = start;
5564     *offsetp = 0;
5565     }
5566     }
5567     }
5568     #ifdef PERL_UTF8_CACHE_ASSERT
5569     if (found) {
5570     U8 *s = start;
5571     I32 n = uoff;
5572    
5573     while (n-- && s < send)
5574     s += UTF8SKIP(s);
5575    
5576     if (i == 0) {
5577     assert(*offsetp == s - start);
5578     assert((*cachep)[0] == (STRLEN)uoff);
5579     assert((*cachep)[1] == *offsetp);
5580     }
5581     ASSERT_UTF8_CACHE(*cachep);
5582     }
5583     #endif
5584     }
5585    
5586     return found;
5587     }
5588    
5589     /*
5590     =for apidoc sv_pos_u2b
5591    
5592     Converts the value pointed to by offsetp from a count of UTF-8 chars from
5593     the start of the string, to a count of the equivalent number of bytes; if
5594     lenp is non-zero, it does the same to lenp, but this time starting from
5595     the offset, rather than from the start of the string. Handles magic and
5596     type coercion.
5597    
5598     =cut
5599     */
5600    
5601     /*
5602     * sv_pos_u2b() uses, like sv_pos_b2u(), the mg_ptr of the potential
5603     * PERL_UTF8_magic of the sv to store the mapping between UTF-8 and
5604     * byte offsets. See also the comments of S_utf8_mg_pos().
5605     *
5606     */
5607    
5608     void
5609     Perl_sv_pos_u2b(pTHX_ register SV *sv, I32* offsetp, I32* lenp)
5610     {
5611     U8 *start;
5612     U8 *s;
5613     STRLEN len;
5614     STRLEN *cache = 0;
5615     STRLEN boffset = 0;
5616    
5617     if (!sv)
5618     return;
5619    
5620     start = s = (U8*)SvPV(sv, len);
5621     if (len) {
5622     I32 uoffset = *offsetp;
5623     U8 *send = s + len;
5624     MAGIC *mg = 0;
5625     bool found = FALSE;
5626    
5627     if (utf8_mg_pos(sv, &mg, &cache, 0, offsetp, *offsetp, &s, start, send))
5628     found = TRUE;
5629     if (!found && uoffset > 0) {
5630     while (s < send && uoffset--)
5631     s += UTF8SKIP(s);
5632     if (s >= send)
5633     s = send;
5634     if (utf8_mg_pos_init(sv, &mg, &cache, 0, offsetp, s, start))
5635     boffset = cache[1];
5636     *offsetp = s - start;
5637     }
5638     if (lenp) {
5639     found = FALSE;
5640     start = s;
5641     if (utf8_mg_pos(sv, &mg, &cache, 2, lenp, *lenp, &s, start, send)) {
5642     *lenp -= boffset;
5643     found = TRUE;
5644     }
5645     if (!found && *lenp > 0) {
5646     I32 ulen = *lenp;
5647     if (ulen > 0)
5648     while (s < send && ulen--)
5649     s += UTF8SKIP(s);
5650     if (s >= send)
5651     s = send;
5652     utf8_mg_pos_init(sv, &mg, &cache, 2, lenp, s, start);
5653     }
5654     *lenp = s - start;
5655     }
5656     ASSERT_UTF8_CACHE(cache);
5657     }
5658     else {
5659     *offsetp = 0;
5660     if (lenp)
5661     *lenp = 0;
5662     }
5663    
5664     return;
5665     }
5666    
5667     /*
5668     =for apidoc sv_pos_b2u
5669    
5670     Converts the value pointed to by offsetp from a count of bytes from the
5671     start of the string, to a count of the equivalent number of UTF-8 chars.
5672     Handles magic and type coercion.
5673    
5674     =cut
5675     */
5676    
5677     /*
5678     * sv_pos_b2u() uses, like sv_pos_u2b(), the mg_ptr of the potential
5679     * PERL_UTF8_magic of the sv to store the mapping between UTF-8 and
5680     * byte offsets. See also the comments of S_utf8_mg_pos().
5681     *
5682     */
5683    
5684     void
5685     Perl_sv_pos_b2u(pTHX_ register SV* sv, I32* offsetp)
5686     {
5687     U8* s;
5688     STRLEN len;
5689    
5690     if (!sv)
5691     return;
5692    
5693     s = (U8*)SvPV(sv, len);
5694     if ((I32)len < *offsetp)
5695     Perl_croak(aTHX_ "panic: sv_pos_b2u: bad byte offset");
5696     else {
5697     U8* send = s + *offsetp;
5698     MAGIC* mg = NULL;
5699     STRLEN *cache = NULL;
5700    
5701     len = 0;
5702    
5703     if (SvMAGICAL(sv) && !SvREADONLY(sv)) {
5704     mg = mg_find(sv, PERL_MAGIC_utf8);
5705     if (mg && mg->mg_ptr) {
5706     cache = (STRLEN *) mg->mg_ptr;
5707     if (cache[1] == (STRLEN)*offsetp) {
5708     /* An exact match. */
5709     *offsetp = cache[0];
5710    
5711     return;
5712     }
5713     else if (cache[1] < (STRLEN)*offsetp) {
5714     /* We already know part of the way. */
5715     len = cache[0];
5716     s += cache[1];
5717     /* Let the below loop do the rest. */
5718     }
5719     else { /* cache[1] > *offsetp */
5720     /* We already know all of the way, now we may
5721     * be able to walk back. The same assumption
5722     * is made as in S_utf8_mg_pos(), namely that
5723     * walking backward is twice slower than
5724     * walking forward. */
5725     STRLEN forw = *offsetp;
5726     STRLEN backw = cache[1] - *offsetp;
5727    
5728     if (!(forw < 2 * backw)) {
5729     U8 *p = s + cache[1];
5730     STRLEN ubackw = 0;
5731    
5732     cache[1] -= backw;
5733    
5734     while (backw--) {
5735     p--;
5736     while (UTF8_IS_CONTINUATION(*p)) {
5737     p--;
5738     backw--;
5739     }
5740     ubackw++;
5741     }
5742    
5743     cache[0] -= ubackw;
5744     *offsetp = cache[0];
5745    
5746     /* Drop the stale "length" cache */
5747     cache[2] = 0;
5748     cache[3] = 0;
5749    
5750     return;
5751     }
5752     }
5753     }
5754     ASSERT_UTF8_CACHE(cache);
5755     }
5756    
5757     while (s < send) {
5758     STRLEN n = 1;
5759    
5760     /* Call utf8n_to_uvchr() to validate the sequence
5761     * (unless a simple non-UTF character) */
5762     if (!UTF8_IS_INVARIANT(*s))
5763     utf8n_to_uvchr(s, UTF8SKIP(s), &n, 0);
5764     if (n > 0) {
5765     s += n;
5766     len++;
5767     }
5768     else
5769     break;
5770     }
5771    
5772     if (!SvREADONLY(sv)) {
5773     if (!mg) {
5774     sv_magic(sv, 0, PERL_MAGIC_utf8, 0, 0);
5775     mg = mg_find(sv, PERL_MAGIC_utf8);
5776     }
5777     assert(mg);
5778    
5779     if (!mg->mg_ptr) {
5780     Newz(0, cache, PERL_MAGIC_UTF8_CACHESIZE * 2, STRLEN);
5781     mg->mg_ptr = (char *) cache;
5782     }
5783     assert(cache);
5784    
5785     cache[0] = len;
5786     cache[1] = *offsetp;
5787     /* Drop the stale "length" cache */
5788     cache[2] = 0;
5789     cache[3] = 0;
5790     }
5791    
5792     *offsetp = len;
5793     }
5794    
5795     return;
5796     }
5797    
5798     /*
5799     =for apidoc sv_eq
5800    
5801     Returns a boolean indicating whether the strings in the two SVs are
5802     identical. Is UTF-8 and 'use bytes' aware, handles get magic, and will
5803     coerce its args to strings if necessary.
5804    
5805     =cut
5806     */
5807    
5808     I32
5809     Perl_sv_eq(pTHX_ register SV *sv1, register SV *sv2)
5810     {
5811     char *pv1;
5812     STRLEN cur1;
5813     char *pv2;
5814     STRLEN cur2;
5815     I32 eq = 0;
5816     char *tpv = Nullch;
5817     SV* svrecode = Nullsv;
5818    
5819     if (!sv1) {
5820     pv1 = "";
5821     cur1 = 0;
5822     }
5823     else
5824     pv1 = SvPV(sv1, cur1);
5825    
5826     if (!sv2){
5827     pv2 = "";
5828     cur2 = 0;
5829     }
5830     else
5831     pv2 = SvPV(sv2, cur2);
5832    
5833     if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
5834     /* Differing utf8ness.
5835     * Do not UTF8size the comparands as a side-effect. */
5836     if (PL_encoding) {
5837     if (SvUTF8(sv1)) {
5838     svrecode = newSVpvn(pv2, cur2);
5839     sv_recode_to_utf8(svrecode, PL_encoding);
5840     pv2 = SvPV(svrecode, cur2);
5841     }
5842     else {
5843     svrecode = newSVpvn(pv1, cur1);
5844     sv_recode_to_utf8(svrecode, PL_encoding);
5845     pv1 = SvPV(svrecode, cur1);
5846     }
5847     /* Now both are in UTF-8. */
5848     if (cur1 != cur2) {
5849     SvREFCNT_dec(svrecode);
5850     return FALSE;
5851     }
5852     }
5853     else {
5854     bool is_utf8 = TRUE;
5855    
5856     if (SvUTF8(sv1)) {
5857     /* sv1 is the UTF-8 one,
5858     * if is equal it must be downgrade-able */
5859     char *pv = (char*)bytes_from_utf8((U8*)pv1,
5860     &cur1, &is_utf8);
5861     if (pv != pv1)
5862     pv1 = tpv = pv;
5863     }
5864     else {
5865     /* sv2 is the UTF-8 one,
5866     * if is equal it must be downgrade-able */
5867     char *pv = (char *)bytes_from_utf8((U8*)pv2,
5868     &cur2, &is_utf8);
5869     if (pv != pv2)
5870     pv2 = tpv = pv;
5871     }
5872     if (is_utf8) {
5873     /* Downgrade not possible - cannot be eq */
5874     return FALSE;
5875     }
5876     }
5877     }
5878    
5879     if (cur1 == cur2)
5880     eq = memEQ(pv1, pv2, cur1);
5881    
5882     if (svrecode)
5883     SvREFCNT_dec(svrecode);
5884    
5885     if (tpv)
5886     Safefree(tpv);
5887    
5888     return eq;
5889     }
5890    
5891     /*
5892     =for apidoc sv_cmp
5893    
5894     Compares the strings in two SVs. Returns -1, 0, or 1 indicating whether the
5895     string in C<sv1> is less than, equal to, or greater than the string in
5896     C<sv2>. Is UTF-8 and 'use bytes' aware, handles get magic, and will
5897     coerce its args to strings if necessary. See also C<sv_cmp_locale>.
5898    
5899     =cut
5900     */
5901    
5902     I32
5903     Perl_sv_cmp(pTHX_ register SV *sv1, register SV *sv2)
5904     {
5905     STRLEN cur1, cur2;
5906     char *pv1, *pv2, *tpv = Nullch;
5907     I32 cmp;
5908     SV *svrecode = Nullsv;
5909    
5910     if (!sv1) {
5911     pv1 = "";
5912     cur1 = 0;
5913     }
5914     else
5915     pv1 = SvPV(sv1, cur1);
5916    
5917     if (!sv2) {
5918     pv2 = "";
5919     cur2 = 0;
5920     }
5921     else
5922     pv2 = SvPV(sv2, cur2);
5923    
5924     if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
5925     /* Differing utf8ness.
5926     * Do not UTF8size the comparands as a side-effect. */
5927     if (SvUTF8(sv1)) {
5928     if (PL_encoding) {
5929     svrecode = newSVpvn(pv2, cur2);
5930     sv_recode_to_utf8(svrecode, PL_encoding);
5931     pv2 = SvPV(svrecode, cur2);
5932     }
5933     else {
5934     pv2 = tpv = (char*)bytes_to_utf8((U8*)pv2, &cur2);
5935     }
5936     }
5937     else {
5938     if (PL_encoding) {
5939     svrecode = newSVpvn(pv1, cur1);
5940     sv_recode_to_utf8(svrecode, PL_encoding);
5941     pv1 = SvPV(svrecode, cur1);
5942     }
5943     else {
5944     pv1 = tpv = (char*)bytes_to_utf8((U8*)pv1, &cur1);
5945     }
5946     }
5947     }
5948    
5949     if (!cur1) {
5950     cmp = cur2 ? -1 : 0;
5951     } else if (!cur2) {
5952     cmp = 1;
5953     } else {
5954     I32 retval = memcmp((void*)pv1, (void*)pv2, cur1 < cur2 ? cur1 : cur2);
5955    
5956     if (retval) {
5957     cmp = retval < 0 ? -1 : 1;
5958     } else if (cur1 == cur2) {
5959     cmp = 0;
5960     } else {
5961     cmp = cur1 < cur2 ? -1 : 1;
5962     }
5963     }
5964    
5965     if (svrecode)
5966     SvREFCNT_dec(svrecode);
5967    
5968     if (tpv)
5969     Safefree(tpv);
5970    
5971     return cmp;
5972     }
5973    
5974     /*
5975     =for apidoc sv_cmp_locale
5976    
5977     Compares the strings in two SVs in a locale-aware manner. Is UTF-8 and
5978     'use bytes' aware, handles get magic, and will coerce its args to strings
5979     if necessary. See also C<sv_cmp_locale>. See also C<sv_cmp>.
5980    
5981     =cut
5982     */
5983    
5984     I32
5985     Perl_sv_cmp_locale(pTHX_ register SV *sv1, register SV *sv2)
5986     {
5987     #ifdef USE_LOCALE_COLLATE
5988    
5989     char *pv1, *pv2;
5990     STRLEN len1, len2;
5991     I32 retval;
5992    
5993     if (PL_collation_standard)
5994     goto raw_compare;
5995    
5996     len1 = 0;
5997     pv1 = sv1 ? sv_collxfrm(sv1, &len1) : (char *) NULL;
5998     len2 = 0;
5999     pv2 = sv2 ? sv_collxfrm(sv2, &len2) : (char *) NULL;
6000    
6001     if (!pv1 || !len1) {
6002     if (pv2 && len2)
6003     return -1;
6004     else
6005     goto raw_compare;
6006     }
6007     else {
6008     if (!pv2 || !len2)
6009     return 1;
6010     }
6011    
6012     retval = memcmp((void*)pv1, (void*)pv2, len1 < len2 ? len1 : len2);
6013    
6014     if (retval)
6015     return retval < 0 ? -1 : 1;
6016    
6017     /*
6018     * When the result of collation is equality, that doesn't mean
6019     * that there are no differences -- some locales exclude some
6020     * characters from consideration. So to avoid false equalities,
6021     * we use the raw string as a tiebreaker.
6022     */
6023    
6024     raw_compare:
6025     /* FALL THROUGH */
6026    
6027     #endif /* USE_LOCALE_COLLATE */
6028    
6029     return sv_cmp(sv1, sv2);
6030     }
6031    
6032    
6033     #ifdef USE_LOCALE_COLLATE
6034    
6035     /*
6036     =for apidoc sv_collxfrm
6037    
6038     Add Collate Transform magic to an SV if it doesn't already have it.
6039    
6040     Any scalar variable may carry PERL_MAGIC_collxfrm magic that contains the
6041     scalar data of the variable, but transformed to such a format that a normal
6042     memory comparison can be used to compare the data according to the locale
6043     settings.
6044    
6045     =cut
6046     */
6047    
6048     char *
6049     Perl_sv_collxfrm(pTHX_ SV *sv, STRLEN *nxp)
6050     {
6051     MAGIC *mg;
6052    
6053     mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_collxfrm) : (MAGIC *) NULL;
6054     if (!mg || !mg->mg_ptr || *(U32*)mg->mg_ptr != PL_collation_ix) {
6055     char *s, *xf;
6056     STRLEN len, xlen;
6057    
6058     if (mg)
6059     Safefree(mg->mg_ptr);
6060     s = SvPV(sv, len);
6061     if ((xf = mem_collxfrm(s, len, &xlen))) {
6062     if (SvREADONLY(sv)) {
6063     SAVEFREEPV(xf);
6064     *nxp = xlen;
6065     return xf + sizeof(PL_collation_ix);
6066     }
6067     if (! mg) {
6068     sv_magic(sv, 0, PERL_MAGIC_collxfrm, 0, 0);
6069     mg = mg_find(sv, PERL_MAGIC_collxfrm);
6070     assert(mg);
6071     }
6072     mg->mg_ptr = xf;
6073     mg->mg_len = xlen;
6074     }
6075     else {
6076     if (mg) {
6077     mg->mg_ptr = NULL;
6078     mg->mg_len = -1;
6079     }
6080     }
6081     }
6082     if (mg && mg->mg_ptr) {
6083     *nxp = mg->mg_len;
6084     return mg->mg_ptr + sizeof(PL_collation_ix);
6085     }
6086     else {
6087     *nxp = 0;
6088     return NULL;
6089     }
6090     }
6091    
6092     #endif /* USE_LOCALE_COLLATE */
6093    
6094     /*
6095     =for apidoc sv_gets
6096    
6097     Get a line from the filehandle and store it into the SV, optionally
6098     appending to the currently-stored string.
6099    
6100     =cut
6101     */
6102    
6103     char *
6104     Perl_sv_gets(pTHX_ register SV *sv, register PerlIO *fp, I32 append)
6105     {
6106     char *rsptr;
6107     STRLEN rslen;
6108     register STDCHAR rslast;
6109     register STDCHAR *bp;
6110     register I32 cnt;
6111     I32 i = 0;
6112     I32 rspara = 0;
6113     I32 recsize;
6114    
6115     if (SvTHINKFIRST(sv))
6116     sv_force_normal_flags(sv, append ? 0 : SV_COW_DROP_PV);
6117     /* XXX. If you make this PVIV, then copy on write can copy scalars read
6118     from <>.
6119     However, perlbench says it's slower, because the existing swipe code
6120     is faster than copy on write.
6121     Swings and roundabouts. */
6122     (void)SvUPGRADE(sv, SVt_PV);
6123    
6124     SvSCREAM_off(sv);
6125    
6126     if (append) {
6127     if (PerlIO_isutf8(fp)) {
6128     if (!SvUTF8(sv)) {
6129     sv_utf8_upgrade_nomg(sv);
6130     sv_pos_u2b(sv,&append,0);
6131     }
6132     } else if (SvUTF8(sv)) {
6133     SV *tsv = NEWSV(0,0);
6134     sv_gets(tsv, fp, 0);
6135     sv_utf8_upgrade_nomg(tsv);
6136     SvCUR_set(sv,append);
6137     sv_catsv(sv,tsv);
6138     sv_free(tsv);
6139     goto return_string_or_null;
6140     }
6141     }
6142    
6143     SvPOK_only(sv);
6144     if (PerlIO_isutf8(fp))
6145     SvUTF8_on(sv);
6146    
6147     if (IN_PERL_COMPILETIME) {
6148     /* we always read code in line mode */
6149     rsptr = "\n";
6150     rslen = 1;
6151     }
6152     else if (RsSNARF(PL_rs)) {
6153     /* If it is a regular disk file use size from stat() as estimate
6154     of amount we are going to read - may result in malloc-ing
6155     more memory than we realy need if layers bellow reduce
6156     size we read (e.g. CRLF or a gzip layer)
6157     */
6158     Stat_t st;
6159     if (!PerlLIO_fstat(PerlIO_fileno(fp), &st) && S_ISREG(st.st_mode)) {
6160     Off_t offset = PerlIO_tell(fp);
6161     if (offset != (Off_t) -1 && st.st_size + append > offset) {
6162     (void) SvGROW(sv, (STRLEN)((st.st_size - offset) + append + 1));
6163     }
6164     }
6165     rsptr = NULL;
6166     rslen = 0;
6167     }
6168     else if (RsRECORD(PL_rs)) {
6169     I32 bytesread;
6170     char *buffer;
6171    
6172     /* Grab the size of the record we're getting */
6173     recsize = SvIV(SvRV(PL_rs));
6174     buffer = SvGROW(sv, (STRLEN)(recsize + append + 1)) + append;
6175     /* Go yank in */
6176     #ifdef VMS
6177     /* VMS wants read instead of fread, because fread doesn't respect */
6178     /* RMS record boundaries. This is not necessarily a good thing to be */
6179     /* doing, but we've got no other real choice - except avoid stdio
6180     as implementation - perhaps write a :vms layer ?
6181     */
6182     bytesread = PerlLIO_read(PerlIO_fileno(fp), buffer, recsize);
6183     #else
6184     bytesread = PerlIO_read(fp, buffer, recsize);
6185     #endif
6186     if (bytesread < 0)
6187     bytesread = 0;
6188     SvCUR_set(sv, bytesread += append);
6189     buffer[bytesread] = '\0';
6190     goto return_string_or_null;
6191     }
6192     else if (RsPARA(PL_rs)) {
6193     rsptr = "\n\n";
6194     rslen = 2;
6195     rspara = 1;
6196     }
6197     else {
6198     /* Get $/ i.e. PL_rs into same encoding as stream wants */
6199     if (PerlIO_isutf8(fp)) {
6200     rsptr = SvPVutf8(PL_rs, rslen);
6201     }
6202     else {
6203     if (SvUTF8(PL_rs)) {
6204     if (!sv_utf8_downgrade(PL_rs, TRUE)) {
6205     Perl_croak(aTHX_ "Wide character in $/");
6206     }
6207     }
6208     rsptr = SvPV(PL_rs, rslen);
6209     }
6210     }
6211    
6212     rslast = rslen ? rsptr[rslen - 1] : '\0';
6213    
6214     if (rspara) { /* have to do this both before and after */
6215     do { /* to make sure file boundaries work right */
6216     if (PerlIO_eof(fp))
6217     return 0;
6218     i = PerlIO_getc(fp);
6219     if (i != '\n') {
6220     if (i == -1)
6221     return 0;
6222     PerlIO_ungetc(fp,i);
6223     break;
6224     }
6225     } while (i != EOF);
6226     }
6227    
6228     /* See if we know enough about I/O mechanism to cheat it ! */
6229    
6230     /* This used to be #ifdef test - it is made run-time test for ease
6231     of abstracting out stdio interface. One call should be cheap
6232     enough here - and may even be a macro allowing compile
6233     time optimization.
6234     */
6235    
6236     if (PerlIO_fast_gets(fp)) {
6237    
6238     /*
6239     * We're going to steal some values from the stdio struct
6240     * and put EVERYTHING in the innermost loop into registers.
6241     */
6242     register STDCHAR *ptr;
6243     STRLEN bpx;
6244     I32 shortbuffered;
6245    
6246     #if defined(VMS) && defined(PERLIO_IS_STDIO)
6247     /* An ungetc()d char is handled separately from the regular
6248     * buffer, so we getc() it back out and stuff it in the buffer.
6249     */
6250     i = PerlIO_getc(fp);
6251     if (i == EOF) return 0;
6252     *(--((*fp)->_ptr)) = (unsigned char) i;
6253     (*fp)->_cnt++;
6254     #endif
6255    
6256     /* Here is some breathtakingly efficient cheating */
6257    
6258     cnt = PerlIO_get_cnt(fp); /* get count into register */
6259     /* make sure we have the room */
6260     if ((I32)(SvLEN(sv) - append) <= cnt + 1) {
6261     /* Not room for all of it
6262     if we are looking for a separator and room for some
6263     */
6264     if (rslen && cnt > 80 && (I32)SvLEN(sv) > append) {
6265     /* just process what we have room for */
6266     shortbuffered = cnt - SvLEN(sv) + append + 1;
6267     cnt -= shortbuffered;
6268     }
6269     else {
6270     shortbuffered = 0;
6271     /* remember that cnt can be negative */
6272     SvGROW(sv, (STRLEN)(append + (cnt <= 0 ? 2 : (cnt + 1))));
6273     }
6274     }
6275     else
6276     shortbuffered = 0;
6277     bp = (STDCHAR*)SvPVX(sv) + append; /* move these two too to registers */
6278     ptr = (STDCHAR*)PerlIO_get_ptr(fp);
6279     DEBUG_P(PerlIO_printf(Perl_debug_log,
6280     "Screamer: entering, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
6281     DEBUG_P(PerlIO_printf(Perl_debug_log,
6282     "Screamer: entering: PerlIO * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
6283     PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
6284     PTR2UV(PerlIO_has_base(fp) ? PerlIO_get_base(fp) : 0)));
6285     for (;;) {
6286     screamer:
6287     if (cnt > 0) {
6288     if (rslen) {
6289     while (cnt > 0) { /* this | eat */
6290     cnt--;
6291     if ((*bp++ = *ptr++) == rslast) /* really | dust */
6292     goto thats_all_folks; /* screams | sed :-) */
6293     }
6294     }
6295     else {
6296     Copy(ptr, bp, cnt, char); /* this | eat */
6297     bp += cnt; /* screams | dust */
6298     ptr += cnt; /* louder | sed :-) */
6299     cnt = 0;
6300     }
6301     }
6302    
6303     if (shortbuffered) { /* oh well, must extend */
6304     cnt = shortbuffered;
6305     shortbuffered = 0;
6306     bpx = bp - (STDCHAR*)SvPVX(sv); /* box up before relocation */
6307     SvCUR_set(sv, bpx);
6308     SvGROW(sv, SvLEN(sv) + append + cnt + 2);
6309     bp = (STDCHAR*)SvPVX(sv) + bpx; /* unbox after relocation */
6310     continue;
6311     }
6312    
6313     DEBUG_P(PerlIO_printf(Perl_debug_log,
6314     "Screamer: going to getc, ptr=%"UVuf", cnt=%ld\n",
6315     PTR2UV(ptr),(long)cnt));
6316     PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt); /* deregisterize cnt and ptr */
6317     #if 0
6318     DEBUG_P(PerlIO_printf(Perl_debug_log,
6319     "Screamer: pre: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
6320     PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
6321     PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
6322     #endif
6323     /* This used to call 'filbuf' in stdio form, but as that behaves like
6324     getc when cnt <= 0 we use PerlIO_getc here to avoid introducing
6325     another abstraction. */
6326     i = PerlIO_getc(fp); /* get more characters */
6327     #if 0
6328     DEBUG_P(PerlIO_printf(Perl_debug_log,
6329     "Screamer: post: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
6330     PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
6331     PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
6332     #endif
6333     cnt = PerlIO_get_cnt(fp);
6334     ptr = (STDCHAR*)PerlIO_get_ptr(fp); /* reregisterize cnt and ptr */
6335     DEBUG_P(PerlIO_printf(Perl_debug_log,
6336     "Screamer: after getc, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
6337    
6338     if (i == EOF) /* all done for ever? */
6339     goto thats_really_all_folks;
6340    
6341     bpx = bp - (STDCHAR*)SvPVX(sv); /* box up before relocation */
6342     SvCUR_set(sv, bpx);
6343     SvGROW(sv, bpx + cnt + 2);
6344     bp = (STDCHAR*)SvPVX(sv) + bpx; /* unbox after relocation */
6345    
6346     *bp++ = (STDCHAR)i; /* store character from PerlIO_getc */
6347    
6348     if (rslen && (STDCHAR)i == rslast) /* all done for now? */
6349     goto thats_all_folks;
6350     }
6351    
6352     thats_all_folks:
6353     if ((rslen > 1 && (STRLEN)(bp - (STDCHAR*)SvPVX(sv)) < rslen) ||
6354     memNE((char*)bp - rslen, rsptr, rslen))
6355     goto screamer; /* go back to the fray */
6356     thats_really_all_folks:
6357     if (shortbuffered)
6358     cnt += shortbuffered;
6359     DEBUG_P(PerlIO_printf(Perl_debug_log,
6360     "Screamer: quitting, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
6361     PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt); /* put these back or we're in trouble */
6362     DEBUG_P(PerlIO_printf(Perl_debug_log,
6363     "Screamer: end: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
6364     PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
6365     PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
6366     *bp = '\0';
6367     SvCUR_set(sv, bp - (STDCHAR*)SvPVX(sv)); /* set length */
6368     DEBUG_P(PerlIO_printf(Perl_debug_log,
6369     "Screamer: done, len=%ld, string=|%.*s|\n",
6370     (long)SvCUR(sv),(int)SvCUR(sv),SvPVX(sv)));
6371     }
6372     else
6373     {
6374     /*The big, slow, and stupid way. */
6375    
6376     /* Any stack-challenged places. */
6377     #if defined(EPOC)
6378     /* EPOC: need to work around SDK features. *
6379     * On WINS: MS VC5 generates calls to _chkstk, *
6380     * if a "large" stack frame is allocated. *
6381     * gcc on MARM does not generate calls like these. */
6382     # define USEHEAPINSTEADOFSTACK
6383     #endif
6384    
6385     #ifdef USEHEAPINSTEADOFSTACK
6386     STDCHAR *buf = 0;
6387     New(0, buf, 8192, STDCHAR);
6388     assert(buf);
6389     #else
6390     STDCHAR buf[8192];
6391     #endif
6392    
6393     screamer2:
6394     if (rslen) {
6395     register STDCHAR *bpe = buf + sizeof(buf);
6396     bp = buf;
6397     while ((i = PerlIO_getc(fp)) != EOF && (*bp++ = (STDCHAR)i) != rslast && bp < bpe)
6398     ; /* keep reading */
6399     cnt = bp - buf;
6400     }
6401     else {
6402     cnt = PerlIO_read(fp,(char*)buf, sizeof(buf));
6403     /* Accomodate broken VAXC compiler, which applies U8 cast to
6404     * both args of ?: operator, causing EOF to change into 255
6405     */
6406     if (cnt > 0)
6407     i = (U8)buf[cnt - 1];
6408     else
6409     i = EOF;
6410     }
6411    
6412     if (cnt < 0)
6413     cnt = 0; /* we do need to re-set the sv even when cnt <= 0 */
6414     if (append)
6415     sv_catpvn(sv, (char *) buf, cnt);
6416     else
6417     sv_setpvn(sv, (char *) buf, cnt);
6418    
6419     if (i != EOF && /* joy */
6420     (!rslen ||
6421     SvCUR(sv) < rslen ||
6422     memNE(SvPVX(sv) + SvCUR(sv) - rslen, rsptr, rslen)))
6423     {
6424     append = -1;
6425     /*
6426     * If we're reading from a TTY and we get a short read,
6427     * indicating that the user hit his EOF character, we need
6428     * to notice it now, because if we try to read from the TTY
6429     * again, the EOF condition will disappear.
6430     *
6431     * The comparison of cnt to sizeof(buf) is an optimization
6432     * that prevents unnecessary calls to feof().
6433     *
6434     * - jik 9/25/96
6435     */
6436     if (!(cnt < sizeof(buf) && PerlIO_eof(fp)))
6437     goto screamer2;
6438     }
6439    
6440     #ifdef USEHEAPINSTEADOFSTACK
6441     Safefree(buf);
6442     #endif
6443     }
6444    
6445     if (rspara) { /* have to do this both before and after */
6446     while (i != EOF) { /* to make sure file boundaries work right */
6447     i = PerlIO_getc(fp);
6448     if (i != '\n') {
6449     PerlIO_ungetc(fp,i);
6450     break;
6451     }
6452     }
6453     }
6454    
6455     return_string_or_null:
6456     return (SvCUR(sv) - append) ? SvPVX(sv) : Nullch;
6457     }
6458    
6459     /*
6460     =for apidoc sv_inc
6461    
6462     Auto-increment of the value in the SV, doing string to numeric conversion
6463     if necessary. Handles 'get' magic.
6464    
6465     =cut
6466     */
6467    
6468     void
6469     Perl_sv_inc(pTHX_ register SV *sv)
6470     {
6471     register char *d;
6472     int flags;
6473    
6474     if (!sv)
6475     return;
6476     if (SvGMAGICAL(sv))
6477     mg_get(sv);
6478     if (SvTHINKFIRST(sv)) {
6479     if (SvREADONLY(sv) && SvFAKE(sv))
6480     sv_force_normal(sv);
6481     if (SvREADONLY(sv)) {
6482     if (IN_PERL_RUNTIME)
6483     Perl_croak(aTHX_ PL_no_modify);
6484     }
6485     if (SvROK(sv)) {
6486     IV i;
6487     if (SvAMAGIC(sv) && AMG_CALLun(sv,inc))
6488     return;
6489     i = PTR2IV(SvRV(sv));
6490     sv_unref(sv);
6491     sv_setiv(sv, i);
6492     }
6493     }
6494     flags = SvFLAGS(sv);
6495     if ((flags & (SVp_NOK|SVp_IOK)) == SVp_NOK) {
6496     /* It's (privately or publicly) a float, but not tested as an
6497     integer, so test it to see. */
6498     (void) SvIV(sv);
6499     flags = SvFLAGS(sv);
6500     }
6501     if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
6502     /* It's publicly an integer, or privately an integer-not-float */
6503     #ifdef PERL_PRESERVE_IVUV
6504     oops_its_int:
6505     #endif
6506     if (SvIsUV(sv)) {
6507     if (SvUVX(sv) == UV_MAX)
6508     sv_setnv(sv, UV_MAX_P1);
6509     else
6510     (void)SvIOK_only_UV(sv);
6511     ++SvUVX(sv);
6512     } else {
6513     if (SvIVX(sv) == IV_MAX)
6514     sv_setuv(sv, (UV)IV_MAX + 1);
6515     else {
6516     (void)SvIOK_only(sv);
6517     ++SvIVX(sv);
6518     }
6519     }
6520     return;
6521     }
6522     if (flags & SVp_NOK) {
6523     (void)SvNOK_only(sv);
6524     SvNVX(sv) += 1.0;
6525     return;
6526     }
6527    
6528     if (!(flags & SVp_POK) || !*SvPVX(sv)) {
6529     if ((flags & SVTYPEMASK) < SVt_PVIV)
6530     sv_upgrade(sv, SVt_IV);
6531     (void)SvIOK_only(sv);
6532     SvIVX(sv) = 1;
6533     return;
6534     }
6535     d = SvPVX(sv);
6536     while (isALPHA(*d)) d++;
6537     while (isDIGIT(*d)) d++;
6538     if (*d) {
6539     #ifdef PERL_PRESERVE_IVUV
6540     /* Got to punt this as an integer if needs be, but we don't issue
6541     warnings. Probably ought to make the sv_iv_please() that does
6542     the conversion if possible, and silently. */
6543     int numtype = grok_number(SvPVX(sv), SvCUR(sv), NULL);
6544     if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
6545     /* Need to try really hard to see if it's an integer.
6546     9.22337203685478e+18 is an integer.
6547     but "9.22337203685478e+18" + 0 is UV=9223372036854779904
6548     so $a="9.22337203685478e+18"; $a+0; $a++
6549     needs to be the same as $a="9.22337203685478e+18"; $a++
6550     or we go insane. */
6551    
6552     (void) sv_2iv(sv);
6553     if (SvIOK(sv))
6554     goto oops_its_int;
6555    
6556     /* sv_2iv *should* have made this an NV */
6557     if (flags & SVp_NOK) {
6558     (void)SvNOK_only(sv);
6559     SvNVX(sv) += 1.0;
6560     return;
6561     }
6562     /* I don't think we can get here. Maybe I should assert this
6563     And if we do get here I suspect that sv_setnv will croak. NWC
6564     Fall through. */
6565     #if defined(USE_LONG_DOUBLE)
6566     DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_inc punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"PERL_PRIgldbl"\n",
6567     SvPVX(sv), SvIVX(sv), SvNVX(sv)));
6568     #else
6569     DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_inc punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
6570     SvPVX(sv), SvIVX(sv), SvNVX(sv)));
6571     #endif
6572     }
6573     #endif /* PERL_PRESERVE_IVUV */
6574     sv_setnv(sv,Atof(SvPVX(sv)) + 1.0);
6575     return;
6576     }
6577     d--;
6578     while (d >= SvPVX(sv)) {
6579     if (isDIGIT(*d)) {
6580     if (++*d <= '9')
6581     return;
6582     *(d--) = '0';
6583     }
6584     else {
6585     #ifdef EBCDIC
6586     /* MKS: The original code here died if letters weren't consecutive.
6587     * at least it didn't have to worry about non-C locales. The
6588     * new code assumes that ('z'-'a')==('Z'-'A'), letters are
6589     * arranged in order (although not consecutively) and that only
6590     * [A-Za-z] are accepted by isALPHA in the C locale.
6591     */
6592     if (*d != 'z' && *d != 'Z') {
6593     do { ++*d; } while (!isALPHA(*d));
6594     return;
6595     }
6596     *(d--) -= 'z' - 'a';
6597     #else
6598     ++*d;
6599     if (isALPHA(*d))
6600     return;
6601     *(d--) -= 'z' - 'a' + 1;
6602     #endif
6603     }
6604     }
6605     /* oh,oh, the number grew */
6606     SvGROW(sv, SvCUR(sv) + 2);
6607     SvCUR(sv)++;
6608     for (d = SvPVX(sv) + SvCUR(sv); d > SvPVX(sv); d--)
6609     *d = d[-1];
6610     if (isDIGIT(d[1]))
6611     *d = '1';
6612     else
6613     *d = d[1];
6614     }
6615    
6616     /*
6617     =for apidoc sv_dec
6618    
6619     Auto-decrement of the value in the SV, doing string to numeric conversion
6620     if necessary. Handles 'get' magic.
6621    
6622     =cut
6623     */
6624    
6625     void
6626     Perl_sv_dec(pTHX_ register SV *sv)
6627     {
6628     int flags;
6629    
6630     if (!sv)
6631     return;
6632     if (SvGMAGICAL(sv))
6633     mg_get(sv);
6634     if (SvTHINKFIRST(sv)) {
6635     if (SvREADONLY(sv) && SvFAKE(sv))
6636     sv_force_normal(sv);
6637     if (SvREADONLY(sv)) {
6638     if (IN_PERL_RUNTIME)
6639     Perl_croak(aTHX_ PL_no_modify);
6640     }
6641     if (SvROK(sv)) {
6642     IV i;
6643     if (SvAMAGIC(sv) && AMG_CALLun(sv,dec))
6644     return;
6645     i = PTR2IV(SvRV(sv));
6646     sv_unref(sv);
6647     sv_setiv(sv, i);
6648     }
6649     }
6650     /* Unlike sv_inc we don't have to worry about string-never-numbers
6651     and keeping them magic. But we mustn't warn on punting */
6652     flags = SvFLAGS(sv);
6653     if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
6654     /* It's publicly an integer, or privately an integer-not-float */
6655     #ifdef PERL_PRESERVE_IVUV
6656     oops_its_int:
6657     #endif
6658     if (SvIsUV(sv)) {
6659     if (SvUVX(sv) == 0) {
6660     (void)SvIOK_only(sv);
6661     SvIVX(sv) = -1;
6662     }
6663     else {
6664     (void)SvIOK_only_UV(sv);
6665     --SvUVX(sv);
6666     }
6667     } else {
6668     if (SvIVX(sv) == IV_MIN)
6669     sv_setnv(sv, (NV)IV_MIN - 1.0);
6670     else {
6671     (void)SvIOK_only(sv);
6672     --SvIVX(sv);
6673     }
6674     }
6675     return;
6676     }
6677     if (flags & SVp_NOK) {
6678     SvNVX(sv) -= 1.0;
6679     (void)SvNOK_only(sv);
6680     return;
6681     }
6682     if (!(flags & SVp_POK)) {
6683     if ((flags & SVTYPEMASK) < SVt_PVNV)
6684     sv_upgrade(sv, SVt_NV);
6685     SvNVX(sv) = -1.0;
6686     (void)SvNOK_only(sv);
6687     return;
6688     }
6689     #ifdef PERL_PRESERVE_IVUV
6690     {
6691     int numtype = grok_number(SvPVX(sv), SvCUR(sv), NULL);
6692     if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
6693     /* Need to try really hard to see if it's an integer.
6694     9.22337203685478e+18 is an integer.
6695     but "9.22337203685478e+18" + 0 is UV=9223372036854779904
6696     so $a="9.22337203685478e+18"; $a+0; $a--
6697     needs to be the same as $a="9.22337203685478e+18"; $a--
6698     or we go insane. */
6699    
6700     (void) sv_2iv(sv);
6701     if (SvIOK(sv))
6702     goto oops_its_int;
6703    
6704     /* sv_2iv *should* have made this an NV */
6705     if (flags & SVp_NOK) {
6706     (void)SvNOK_only(sv);
6707     SvNVX(sv) -= 1.0;
6708     return;
6709     }
6710     /* I don't think we can get here. Maybe I should assert this
6711     And if we do get here I suspect that sv_setnv will croak. NWC
6712     Fall through. */
6713     #if defined(USE_LONG_DOUBLE)
6714     DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_dec punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"PERL_PRIgldbl"\n",
6715     SvPVX(sv), SvIVX(sv), SvNVX(sv)));
6716     #else
6717     DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_dec punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
6718     SvPVX(sv), SvIVX(sv), SvNVX(sv)));
6719     #endif
6720     }
6721     }
6722     #endif /* PERL_PRESERVE_IVUV */
6723     sv_setnv(sv,Atof(SvPVX(sv)) - 1.0); /* punt */
6724     }
6725    
6726     /*
6727     =for apidoc sv_mortalcopy
6728    
6729     Creates a new SV which is a copy of the original SV (using C<sv_setsv>).
6730     The new SV is marked as mortal. It will be destroyed "soon", either by an
6731     explicit call to FREETMPS, or by an implicit call at places such as
6732     statement boundaries. See also C<sv_newmortal> and C<sv_2mortal>.
6733    
6734     =cut
6735     */
6736    
6737     /* Make a string that will exist for the duration of the expression
6738     * evaluation. Actually, it may have to last longer than that, but
6739     * hopefully we won't free it until it has been assigned to a
6740     * permanent location. */
6741    
6742     SV *
6743     Perl_sv_mortalcopy(pTHX_ SV *oldstr)
6744     {
6745     register SV *sv;
6746    
6747     new_SV(sv);
6748     sv_setsv(sv,oldstr);
6749     EXTEND_MORTAL(1);
6750     PL_tmps_stack[++PL_tmps_ix] = sv;
6751     SvTEMP_on(sv);
6752     return sv;
6753     }
6754    
6755     /*
6756     =for apidoc sv_newmortal
6757    
6758     Creates a new null SV which is mortal. The reference count of the SV is
6759     set to 1. It will be destroyed "soon", either by an explicit call to
6760     FREETMPS, or by an implicit call at places such as statement boundaries.
6761     See also C<sv_mortalcopy> and C<sv_2mortal>.
6762    
6763     =cut
6764     */
6765    
6766     SV *
6767     Perl_sv_newmortal(pTHX)
6768     {
6769     register SV *sv;
6770    
6771     new_SV(sv);
6772     SvFLAGS(sv) = SVs_TEMP;
6773     EXTEND_MORTAL(1);
6774     PL_tmps_stack[++PL_tmps_ix] = sv;
6775     return sv;
6776     }
6777    
6778     /*
6779     =for apidoc sv_2mortal
6780    
6781     Marks an existing SV as mortal. The SV will be destroyed "soon", either
6782     by an explicit call to FREETMPS, or by an implicit call at places such as
6783     statement boundaries. SvTEMP() is turned on which means that the SV's
6784     string buffer can be "stolen" if this SV is copied. See also C<sv_newmortal>
6785     and C<sv_mortalcopy>.
6786    
6787     =cut
6788     */
6789    
6790     SV *
6791     Perl_sv_2mortal(pTHX_ register SV *sv)
6792     {
6793     if (!sv)
6794     return sv;
6795     if (SvREADONLY(sv) && SvIMMORTAL(sv))
6796     return sv;
6797     EXTEND_MORTAL(1);
6798     PL_tmps_stack[++PL_tmps_ix] = sv;
6799     SvTEMP_on(sv);
6800     return sv;
6801     }
6802    
6803     /*
6804     =for apidoc newSVpv
6805    
6806     Creates a new SV and copies a string into it. The reference count for the
6807     SV is set to 1. If C<len> is zero, Perl will compute the length using
6808     strlen(). For efficiency, consider using C<newSVpvn> instead.
6809    
6810     =cut
6811     */
6812    
6813     SV *
6814     Perl_newSVpv(pTHX_ const char *s, STRLEN len)
6815     {
6816     register SV *sv;
6817    
6818     new_SV(sv);
6819     if (!len)
6820     len = strlen(s);
6821     sv_setpvn(sv,s,len);
6822     return sv;
6823     }
6824    
6825     /*
6826     =for apidoc newSVpvn
6827    
6828     Creates a new SV and copies a string into it. The reference count for the
6829     SV is set to 1. Note that if C<len> is zero, Perl will create a zero length
6830     string. You are responsible for ensuring that the source string is at least
6831     C<len> bytes long. If the C<s> argument is NULL the new SV will be undefined.
6832    
6833     =cut
6834     */
6835    
6836     SV *
6837     Perl_newSVpvn(pTHX_ const char *s, STRLEN len)
6838     {
6839     register SV *sv;
6840    
6841     new_SV(sv);
6842     sv_setpvn(sv,s,len);
6843     return sv;
6844     }
6845    
6846     /*
6847     =for apidoc newSVpvn_share
6848    
6849     Creates a new SV with its SvPVX pointing to a shared string in the string
6850     table. If the string does not already exist in the table, it is created
6851     first. Turns on READONLY and FAKE. The string's hash is stored in the UV
6852     slot of the SV; if the C<hash> parameter is non-zero, that value is used;
6853     otherwise the hash is computed. The idea here is that as the string table
6854     is used for shared hash keys these strings will have SvPVX == HeKEY and
6855     hash lookup will avoid string compare.
6856    
6857     =cut
6858     */
6859    
6860     SV *
6861     Perl_newSVpvn_share(pTHX_ const char *src, I32 len, U32 hash)
6862     {
6863     register SV *sv;
6864     bool is_utf8 = FALSE;
6865     if (len < 0) {
6866     STRLEN tmplen = -len;
6867     is_utf8 = TRUE;
6868     /* See the note in hv.c:hv_fetch() --jhi */
6869     src = (char*)bytes_from_utf8((U8*)src, &tmplen, &is_utf8);
6870     len = tmplen;
6871     }
6872     if (!hash)
6873     PERL_HASH(hash, src, len);
6874     new_SV(sv);
6875     sv_upgrade(sv, SVt_PVIV);
6876     SvPVX(sv) = sharepvn(src, is_utf8?-len:len, hash);
6877     SvCUR(sv) = len;
6878     SvUVX(sv) = hash;
6879     SvLEN(sv) = 0;
6880     SvREADONLY_on(sv);
6881     SvFAKE_on(sv);
6882     SvPOK_on(sv);
6883     if (is_utf8)
6884     SvUTF8_on(sv);
6885     return sv;
6886     }
6887    
6888    
6889     #if defined(PERL_IMPLICIT_CONTEXT)
6890    
6891     /* pTHX_ magic can't cope with varargs, so this is a no-context
6892     * version of the main function, (which may itself be aliased to us).
6893     * Don't access this version directly.
6894     */
6895    
6896     SV *
6897     Perl_newSVpvf_nocontext(const char* pat, ...)
6898     {
6899     dTHX;
6900     register SV *sv;
6901     va_list args;
6902     va_start(args, pat);
6903     sv = vnewSVpvf(pat, &args);
6904     va_end(args);
6905     return sv;
6906     }
6907     #endif
6908    
6909     /*
6910     =for apidoc newSVpvf
6911    
6912     Creates a new SV and initializes it with the string formatted like
6913     C<sprintf>.
6914    
6915     =cut
6916     */
6917    
6918     SV *
6919     Perl_newSVpvf(pTHX_ const char* pat, ...)
6920     {
6921     register SV *sv;
6922     va_list args;
6923     va_start(args, pat);
6924     sv = vnewSVpvf(pat, &args);
6925     va_end(args);
6926     return sv;
6927     }
6928    
6929     /* backend for newSVpvf() and newSVpvf_nocontext() */
6930    
6931     SV *
6932     Perl_vnewSVpvf(pTHX_ const char* pat, va_list* args)
6933     {
6934     register SV *sv;
6935     new_SV(sv);
6936     sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
6937     return sv;
6938     }
6939    
6940     /*
6941     =for apidoc newSVnv
6942    
6943     Creates a new SV and copies a floating point value into it.
6944     The reference count for the SV is set to 1.
6945    
6946     =cut
6947     */
6948    
6949     SV *
6950     Perl_newSVnv(pTHX_ NV n)
6951     {
6952     register SV *sv;
6953    
6954     new_SV(sv);
6955     sv_setnv(sv,n);
6956     return sv;
6957     }
6958    
6959     /*
6960     =for apidoc newSViv
6961    
6962     Creates a new SV and copies an integer into it. The reference count for the
6963     SV is set to 1.
6964    
6965     =cut
6966     */
6967    
6968     SV *
6969     Perl_newSViv(pTHX_ IV i)
6970     {
6971     register SV *sv;
6972    
6973     new_SV(sv);
6974     sv_setiv(sv,i);
6975     return sv;
6976     }
6977    
6978     /*
6979     =for apidoc newSVuv
6980    
6981     Creates a new SV and copies an unsigned integer into it.
6982     The reference count for the SV is set to 1.
6983    
6984     =cut
6985     */
6986    
6987     SV *
6988     Perl_newSVuv(pTHX_ UV u)
6989     {
6990     register SV *sv;
6991    
6992     new_SV(sv);
6993     sv_setuv(sv,u);
6994     return sv;
6995     }
6996    
6997     /*
6998     =for apidoc newRV_noinc
6999    
7000     Creates an RV wrapper for an SV. The reference count for the original
7001     SV is B<not> incremented.
7002    
7003     =cut
7004     */
7005    
7006     SV *
7007     Perl_newRV_noinc(pTHX_ SV *tmpRef)
7008     {
7009     register SV *sv;
7010    
7011     new_SV(sv);
7012     sv_upgrade(sv, SVt_RV);
7013     SvTEMP_off(tmpRef);
7014     SvRV(sv) = tmpRef;
7015     SvROK_on(sv);
7016     return sv;
7017     }
7018    
7019     /* newRV_inc is the official function name to use now.
7020     * newRV_inc is in fact #defined to newRV in sv.h
7021     */
7022    
7023     SV *
7024     Perl_newRV(pTHX_ SV *tmpRef)
7025     {
7026     return newRV_noinc(SvREFCNT_inc(tmpRef));
7027     }
7028    
7029     /*
7030     =for apidoc newSVsv
7031    
7032     Creates a new SV which is an exact duplicate of the original SV.
7033     (Uses C<sv_setsv>).
7034    
7035     =cut
7036     */
7037    
7038     SV *
7039     Perl_newSVsv(pTHX_ register SV *old)
7040     {
7041     register SV *sv;
7042    
7043     if (!old)
7044     return Nullsv;
7045     if (SvTYPE(old) == SVTYPEMASK) {
7046     if (ckWARN_d(WARN_INTERNAL))
7047     Perl_warner(aTHX_ packWARN(WARN_INTERNAL), "semi-panic: attempt to dup freed string");
7048     return Nullsv;
7049     }
7050     new_SV(sv);
7051     /* SV_GMAGIC is the default for sv_setv()
7052     SV_NOSTEAL prevents TEMP buffers being, well, stolen, and saves games
7053     with SvTEMP_off and SvTEMP_on round a call to sv_setsv. */
7054     sv_setsv_flags(sv, old, SV_GMAGIC | SV_NOSTEAL);
7055     return sv;
7056     }
7057    
7058     /*
7059     =for apidoc sv_reset
7060    
7061     Underlying implementation for the C<reset> Perl function.
7062     Note that the perl-level function is vaguely deprecated.
7063    
7064     =cut
7065     */
7066    
7067     void
7068     Perl_sv_reset(pTHX_ register char *s, HV *stash)
7069     {
7070     register HE *entry;
7071     register GV *gv;
7072     register SV *sv;
7073     register I32 i;
7074     register PMOP *pm;
7075     register I32 max;
7076     char todo[PERL_UCHAR_MAX+1];
7077    
7078     if (!stash)
7079     return;
7080    
7081     if (!*s) { /* reset ?? searches */
7082     for (pm = HvPMROOT(stash); pm; pm = pm->op_pmnext) {
7083     pm->op_pmdynflags &= ~PMdf_USED;
7084     }
7085     return;
7086     }
7087    
7088     /* reset variables */
7089    
7090     if (!HvARRAY(stash))
7091     return;
7092    
7093     Zero(todo, 256, char);
7094     while (*s) {
7095     i = (unsigned char)*s;
7096     if (s[1] == '-') {
7097     s += 2;
7098     }
7099     max = (unsigned char)*s++;
7100     for ( ; i <= max; i++) {
7101     todo[i] = 1;
7102     }
7103     for (i = 0; i <= (I32) HvMAX(stash); i++) {
7104     for (entry = HvARRAY(stash)[i];
7105     entry;
7106     entry = HeNEXT(entry))
7107     {
7108     if (!todo[(U8)*HeKEY(entry)])
7109     continue;
7110     gv = (GV*)HeVAL(entry);
7111     sv = GvSV(gv);
7112     if (SvTHINKFIRST(sv)) {
7113     if (!SvREADONLY(sv) && SvROK(sv))
7114     sv_unref(sv);
7115     continue;
7116     }
7117     SvOK_off(sv);
7118     if (SvTYPE(sv) >= SVt_PV) {
7119     SvCUR_set(sv, 0);
7120     if (SvPVX(sv) != Nullch)
7121     *SvPVX(sv) = '\0';
7122     SvTAINT(sv);
7123     }
7124     if (GvAV(gv)) {
7125     av_clear(GvAV(gv));
7126     }
7127     if (GvHV(gv) && !HvNAME(GvHV(gv))) {
7128     hv_clear(GvHV(gv));
7129     #ifndef PERL_MICRO
7130     #ifdef USE_ENVIRON_ARRAY
7131     if (gv == PL_envgv
7132     # ifdef USE_ITHREADS
7133     && PL_curinterp == aTHX
7134     # endif
7135     )
7136     {
7137     environ[0] = Nullch;
7138     }
7139     #endif
7140     #endif /* !PERL_MICRO */
7141     }
7142     }
7143     }
7144     }
7145     }
7146    
7147     /*
7148     =for apidoc sv_2io
7149    
7150     Using various gambits, try to get an IO from an SV: the IO slot if its a
7151     GV; or the recursive result if we're an RV; or the IO slot of the symbol
7152     named after the PV if we're a string.
7153    
7154     =cut
7155     */
7156    
7157     IO*
7158     Perl_sv_2io(pTHX_ SV *sv)
7159     {
7160     IO* io;
7161     GV* gv;
7162     STRLEN n_a;
7163    
7164     switch (SvTYPE(sv)) {
7165     case SVt_PVIO:
7166     io = (IO*)sv;
7167     break;
7168     case SVt_PVGV:
7169     gv = (GV*)sv;
7170     io = GvIO(gv);
7171     if (!io)
7172     Perl_croak(aTHX_ "Bad filehandle: %s", GvNAME(gv));
7173     break;
7174     default:
7175     if (!SvOK(sv))
7176     Perl_croak(aTHX_ PL_no_usym, "filehandle");
7177     if (SvROK(sv))
7178     return sv_2io(SvRV(sv));
7179     gv = gv_fetchpv(SvPV(sv,n_a), FALSE, SVt_PVIO);
7180     if (gv)
7181     io = GvIO(gv);
7182     else
7183     io = 0;
7184     if (!io)
7185     Perl_croak(aTHX_ "Bad filehandle: %"SVf, sv);
7186     break;
7187     }
7188     return io;
7189     }
7190    
7191     /*
7192     =for apidoc sv_2cv
7193    
7194     Using various gambits, try to get a CV from an SV; in addition, try if
7195     possible to set C<*st> and C<*gvp> to the stash and GV associated with it.
7196    
7197     =cut
7198     */
7199    
7200     CV *
7201     Perl_sv_2cv(pTHX_ SV *sv, HV **st, GV **gvp, I32 lref)
7202     {
7203     GV *gv = Nullgv;
7204     CV *cv = Nullcv;
7205     STRLEN n_a;
7206    
7207     if (!sv)
7208     return *gvp = Nullgv, Nullcv;
7209     switch (SvTYPE(sv)) {
7210     case SVt_PVCV:
7211     *st = CvSTASH(sv);
7212     *gvp = Nullgv;
7213     return (CV*)sv;
7214     case SVt_PVHV:
7215     case SVt_PVAV:
7216     *gvp = Nullgv;
7217     return Nullcv;
7218     case SVt_PVGV:
7219     gv = (GV*)sv;
7220     *gvp = gv;
7221     *st = GvESTASH(gv);
7222     goto fix_gv;
7223    
7224     default:
7225     if (SvGMAGICAL(sv))
7226     mg_get(sv);
7227     if (SvROK(sv)) {
7228     SV **sp = &sv; /* Used in tryAMAGICunDEREF macro. */
7229     tryAMAGICunDEREF(to_cv);
7230    
7231     sv = SvRV(sv);
7232     if (SvTYPE(sv) == SVt_PVCV) {
7233     cv = (CV*)sv;
7234     *gvp = Nullgv;
7235     *st = CvSTASH(cv);
7236     return cv;
7237     }
7238     else if(isGV(sv))
7239     gv = (GV*)sv;
7240     else
7241     Perl_croak(aTHX_ "Not a subroutine reference");
7242     }
7243     else if (isGV(sv))
7244     gv = (GV*)sv;
7245     else
7246     gv = gv_fetchpv(SvPV(sv, n_a), lref, SVt_PVCV);
7247     *gvp = gv;
7248     if (!gv)
7249     return Nullcv;
7250     *st = GvESTASH(gv);
7251     fix_gv:
7252     if (lref && !GvCVu(gv)) {
7253     SV *tmpsv;
7254     ENTER;
7255     tmpsv = NEWSV(704,0);
7256     gv_efullname3(tmpsv, gv, Nullch);
7257     /* XXX this is probably not what they think they're getting.
7258     * It has the same effect as "sub name;", i.e. just a forward
7259     * declaration! */
7260     newSUB(start_subparse(FALSE, 0),
7261     newSVOP(OP_CONST, 0, tmpsv),
7262     Nullop,
7263     Nullop);
7264     LEAVE;
7265     if (!GvCVu(gv))
7266     Perl_croak(aTHX_ "Unable to create sub named \"%"SVf"\"",
7267     sv);
7268     }
7269     return GvCVu(gv);
7270     }
7271     }
7272    
7273     /*
7274     =for apidoc sv_true
7275    
7276     Returns true if the SV has a true value by Perl's rules.
7277     Use the C<SvTRUE> macro instead, which may call C<sv_true()> or may
7278     instead use an in-line version.
7279    
7280     =cut
7281     */
7282    
7283     I32
7284     Perl_sv_true(pTHX_ register SV *sv)
7285     {
7286     if (!sv)
7287     return 0;
7288     if (SvPOK(sv)) {
7289     register XPV* tXpv;
7290     if ((tXpv = (XPV*)SvANY(sv)) &&
7291     (tXpv->xpv_cur > 1 ||
7292     (tXpv->xpv_cur && *tXpv->xpv_pv != '0')))
7293     return 1;
7294     else
7295     return 0;
7296     }
7297     else {
7298     if (SvIOK(sv))
7299     return SvIVX(sv) != 0;
7300     else {
7301     if (SvNOK(sv))
7302     return SvNVX(sv) != 0.0;
7303     else
7304     return sv_2bool(sv);
7305     }
7306     }
7307     }
7308    
7309     /*
7310     =for apidoc sv_iv
7311    
7312     A private implementation of the C<SvIVx> macro for compilers which can't
7313     cope with complex macro expressions. Always use the macro instead.
7314    
7315     =cut
7316     */
7317    
7318     IV
7319     Perl_sv_iv(pTHX_ register SV *sv)
7320     {
7321     if (SvIOK(sv)) {
7322     if (SvIsUV(sv))
7323     return (IV)SvUVX(sv);
7324     return SvIVX(sv);
7325     }
7326     return sv_2iv(sv);
7327     }
7328    
7329     /*
7330     =for apidoc sv_uv
7331    
7332     A private implementation of the C<SvUVx> macro for compilers which can't
7333     cope with complex macro expressions. Always use the macro instead.
7334    
7335     =cut
7336     */
7337    
7338     UV
7339     Perl_sv_uv(pTHX_ register SV *sv)
7340     {
7341     if (SvIOK(sv)) {
7342     if (SvIsUV(sv))
7343     return SvUVX(sv);
7344     return (UV)SvIVX(sv);
7345     }
7346     return sv_2uv(sv);
7347     }
7348    
7349     /*
7350     =for apidoc sv_nv
7351    
7352     A private implementation of the C<SvNVx> macro for compilers which can't
7353     cope with complex macro expressions. Always use the macro instead.
7354    
7355     =cut
7356     */
7357    
7358     NV
7359     Perl_sv_nv(pTHX_ register SV *sv)
7360     {
7361     if (SvNOK(sv))
7362     return SvNVX(sv);
7363     return sv_2nv(sv);
7364     }
7365    
7366     /* sv_pv() is now a macro using SvPV_nolen();
7367     * this function provided for binary compatibility only
7368     */
7369    
7370     char *
7371     Perl_sv_pv(pTHX_ SV *sv)
7372     {
7373     STRLEN n_a;
7374    
7375     if (SvPOK(sv))
7376     return SvPVX(sv);
7377    
7378     return sv_2pv(sv, &n_a);
7379     }
7380    
7381     /*
7382     =for apidoc sv_pv
7383    
7384     Use the C<SvPV_nolen> macro instead
7385    
7386     =for apidoc sv_pvn
7387    
7388     A private implementation of the C<SvPV> macro for compilers which can't
7389     cope with complex macro expressions. Always use the macro instead.
7390    
7391     =cut
7392     */
7393    
7394     char *
7395     Perl_sv_pvn(pTHX_ SV *sv, STRLEN *lp)
7396     {
7397     if (SvPOK(sv)) {
7398     *lp = SvCUR(sv);
7399     return SvPVX(sv);
7400     }
7401     return sv_2pv(sv, lp);
7402     }
7403    
7404    
7405     char *
7406     Perl_sv_pvn_nomg(pTHX_ register SV *sv, STRLEN *lp)
7407     {
7408     if (SvPOK(sv)) {
7409     *lp = SvCUR(sv);
7410     return SvPVX(sv);
7411     }
7412     return sv_2pv_flags(sv, lp, 0);
7413     }
7414    
7415     /* sv_pvn_force() is now a macro using Perl_sv_pvn_force_flags();
7416     * this function provided for binary compatibility only
7417     */
7418    
7419     char *
7420     Perl_sv_pvn_force(pTHX_ SV *sv, STRLEN *lp)
7421     {
7422     return sv_pvn_force_flags(sv, lp, SV_GMAGIC);
7423     }
7424    
7425     /*
7426     =for apidoc sv_pvn_force
7427    
7428     Get a sensible string out of the SV somehow.
7429     A private implementation of the C<SvPV_force> macro for compilers which
7430     can't cope with complex macro expressions. Always use the macro instead.
7431    
7432     =for apidoc sv_pvn_force_flags
7433    
7434     Get a sensible string out of the SV somehow.
7435     If C<flags> has C<SV_GMAGIC> bit set, will C<mg_get> on C<sv> if
7436     appropriate, else not. C<sv_pvn_force> and C<sv_pvn_force_nomg> are
7437     implemented in terms of this function.
7438     You normally want to use the various wrapper macros instead: see
7439     C<SvPV_force> and C<SvPV_force_nomg>
7440    
7441     =cut
7442     */
7443    
7444     char *
7445     Perl_sv_pvn_force_flags(pTHX_ SV *sv, STRLEN *lp, I32 flags)
7446     {
7447     char *s = NULL;
7448    
7449     if (SvTHINKFIRST(sv) && !SvROK(sv))
7450     sv_force_normal(sv);
7451    
7452     if (SvPOK(sv)) {
7453     *lp = SvCUR(sv);
7454     }
7455     else {
7456     if (SvTYPE(sv) > SVt_PVLV && SvTYPE(sv) != SVt_PVFM) {
7457     Perl_croak(aTHX_ "Can't coerce %s to string in %s", sv_reftype(sv,0),
7458     OP_NAME(PL_op));
7459     }
7460     else
7461     s = sv_2pv_flags(sv, lp, flags);
7462     if (s != SvPVX(sv)) { /* Almost, but not quite, sv_setpvn() */
7463     STRLEN len = *lp;
7464    
7465     if (SvROK(sv))
7466     sv_unref(sv);
7467     (void)SvUPGRADE(sv, SVt_PV); /* Never FALSE */
7468     SvGROW(sv, len + 1);
7469     Move(s,SvPVX(sv),len,char);
7470     SvCUR_set(sv, len);
7471     *SvEND(sv) = '\0';
7472     }
7473     if (!SvPOK(sv)) {
7474     SvPOK_on(sv); /* validate pointer */
7475     SvTAINT(sv);
7476     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
7477     PTR2UV(sv),SvPVX(sv)));
7478     }
7479     }
7480     return SvPVX(sv);
7481     }
7482    
7483     /* sv_pvbyte () is now a macro using Perl_sv_2pv_flags();
7484     * this function provided for binary compatibility only
7485     */
7486    
7487     char *
7488     Perl_sv_pvbyte(pTHX_ SV *sv)
7489     {
7490     sv_utf8_downgrade(sv,0);
7491     return sv_pv(sv);
7492     }
7493    
7494     /*
7495     =for apidoc sv_pvbyte
7496    
7497     Use C<SvPVbyte_nolen> instead.
7498    
7499     =for apidoc sv_pvbyten
7500    
7501     A private implementation of the C<SvPVbyte> macro for compilers
7502     which can't cope with complex macro expressions. Always use the macro
7503     instead.
7504    
7505     =cut
7506     */
7507    
7508     char *
7509     Perl_sv_pvbyten(pTHX_ SV *sv, STRLEN *lp)
7510     {
7511     sv_utf8_downgrade(sv,0);
7512     return sv_pvn(sv,lp);
7513     }
7514    
7515     /*
7516     =for apidoc sv_pvbyten_force
7517    
7518     A private implementation of the C<SvPVbytex_force> macro for compilers
7519     which can't cope with complex macro expressions. Always use the macro
7520     instead.
7521    
7522     =cut
7523     */
7524    
7525     char *
7526     Perl_sv_pvbyten_force(pTHX_ SV *sv, STRLEN *lp)
7527     {
7528     sv_pvn_force(sv,lp);
7529     sv_utf8_downgrade(sv,0);
7530     *lp = SvCUR(sv);
7531     return SvPVX(sv);
7532     }
7533    
7534     /* sv_pvutf8 () is now a macro using Perl_sv_2pv_flags();
7535     * this function provided for binary compatibility only
7536     */
7537    
7538     char *
7539     Perl_sv_pvutf8(pTHX_ SV *sv)
7540     {
7541     sv_utf8_upgrade(sv);
7542     return sv_pv(sv);
7543     }
7544    
7545     /*
7546     =for apidoc sv_pvutf8
7547    
7548     Use the C<SvPVutf8_nolen> macro instead
7549    
7550     =for apidoc sv_pvutf8n
7551    
7552     A private implementation of the C<SvPVutf8> macro for compilers
7553     which can't cope with complex macro expressions. Always use the macro
7554     instead.
7555    
7556     =cut
7557     */
7558    
7559     char *
7560     Perl_sv_pvutf8n(pTHX_ SV *sv, STRLEN *lp)
7561     {
7562     sv_utf8_upgrade(sv);
7563     return sv_pvn(sv,lp);
7564     }
7565    
7566     /*
7567     =for apidoc sv_pvutf8n_force
7568    
7569     A private implementation of the C<SvPVutf8_force> macro for compilers
7570     which can't cope with complex macro expressions. Always use the macro
7571     instead.
7572    
7573     =cut
7574     */
7575    
7576     char *
7577     Perl_sv_pvutf8n_force(pTHX_ SV *sv, STRLEN *lp)
7578     {
7579     sv_pvn_force(sv,lp);
7580     sv_utf8_upgrade(sv);
7581     *lp = SvCUR(sv);
7582     return SvPVX(sv);
7583     }
7584    
7585     /*
7586     =for apidoc sv_reftype
7587    
7588     Returns a string describing what the SV is a reference to.
7589    
7590     =cut
7591     */
7592    
7593     char *
7594     Perl_sv_reftype(pTHX_ SV *sv, int ob)
7595     {
7596     if (ob && SvOBJECT(sv)) {
7597     char *name = HvNAME(SvSTASH(sv));
7598     return name ? name : "__ANON__";
7599     }
7600     else {
7601     switch (SvTYPE(sv)) {
7602     case SVt_NULL:
7603     case SVt_IV:
7604     case SVt_NV:
7605     case SVt_RV:
7606     case SVt_PV:
7607     case SVt_PVIV:
7608     case SVt_PVNV:
7609     case SVt_PVMG:
7610     case SVt_PVBM:
7611     if (SvROK(sv))
7612     return "REF";
7613     else
7614     return "SCALAR";
7615    
7616     case SVt_PVLV: return SvROK(sv) ? "REF"
7617     /* tied lvalues should appear to be
7618     * scalars for backwards compatitbility */
7619     : (LvTYPE(sv) == 't' || LvTYPE(sv) == 'T')
7620     ? "SCALAR" : "LVALUE";
7621     case SVt_PVAV: return "ARRAY";
7622     case SVt_PVHV: return "HASH";
7623     case SVt_PVCV: return "CODE";
7624     case SVt_PVGV: return "GLOB";
7625     case SVt_PVFM: return "FORMAT";
7626     case SVt_PVIO: return "IO";
7627     default: return "UNKNOWN";
7628     }
7629     }
7630     }
7631    
7632     /*
7633     =for apidoc sv_isobject
7634    
7635     Returns a boolean indicating whether the SV is an RV pointing to a blessed
7636     object. If the SV is not an RV, or if the object is not blessed, then this
7637     will return false.
7638    
7639     =cut
7640     */
7641    
7642     int
7643     Perl_sv_isobject(pTHX_ SV *sv)
7644     {
7645     if (!sv)
7646     return 0;
7647     if (SvGMAGICAL(sv))
7648     mg_get(sv);
7649     if (!SvROK(sv))
7650     return 0;
7651     sv = (SV*)SvRV(sv);
7652     if (!SvOBJECT(sv))
7653     return 0;
7654     return 1;
7655     }
7656    
7657     /*
7658     =for apidoc sv_isa
7659    
7660     Returns a boolean indicating whether the SV is blessed into the specified
7661     class. This does not check for subtypes; use C<sv_derived_from> to verify
7662     an inheritance relationship.
7663    
7664     =cut
7665     */
7666    
7667     int
7668     Perl_sv_isa(pTHX_ SV *sv, const char *name)
7669     {
7670     if (!sv)
7671     return 0;
7672     if (SvGMAGICAL(sv))
7673     mg_get(sv);
7674     if (!SvROK(sv))
7675     return 0;
7676     sv = (SV*)SvRV(sv);
7677     if (!SvOBJECT(sv))
7678     return 0;
7679     if (!HvNAME(SvSTASH(sv)))
7680     return 0;
7681    
7682     return strEQ(HvNAME(SvSTASH(sv)), name);
7683     }
7684    
7685     /*
7686     =for apidoc newSVrv
7687    
7688     Creates a new SV for the RV, C<rv>, to point to. If C<rv> is not an RV then
7689     it will be upgraded to one. If C<classname> is non-null then the new SV will
7690     be blessed in the specified package. The new SV is returned and its
7691     reference count is 1.
7692    
7693     =cut
7694     */
7695    
7696     SV*
7697     Perl_newSVrv(pTHX_ SV *rv, const char *classname)
7698     {
7699     SV *sv;
7700    
7701     new_SV(sv);
7702    
7703     SV_CHECK_THINKFIRST(rv);
7704     SvAMAGIC_off(rv);
7705    
7706     if (SvTYPE(rv) >= SVt_PVMG) {
7707     U32 refcnt = SvREFCNT(rv);
7708     SvREFCNT(rv) = 0;
7709     sv_clear(rv);
7710     SvFLAGS(rv) = 0;
7711     SvREFCNT(rv) = refcnt;
7712     }
7713    
7714     if (SvTYPE(rv) < SVt_RV)
7715     sv_upgrade(rv, SVt_RV);
7716     else if (SvTYPE(rv) > SVt_RV) {
7717     SvOOK_off(rv);
7718     if (SvPVX(rv) && SvLEN(rv))
7719     Safefree(SvPVX(rv));
7720     SvCUR_set(rv, 0);
7721     SvLEN_set(rv, 0);
7722     }
7723    
7724     SvOK_off(rv);
7725     SvRV(rv) = sv;
7726     SvROK_on(rv);
7727    
7728     if (classname) {
7729     HV* stash = gv_stashpv(classname, TRUE);
7730     (void)sv_bless(rv, stash);
7731     }
7732     return sv;
7733     }
7734    
7735     /*
7736     =for apidoc sv_setref_pv
7737    
7738     Copies a pointer into a new SV, optionally blessing the SV. The C<rv>
7739     argument will be upgraded to an RV. That RV will be modified to point to
7740     the new SV. If the C<pv> argument is NULL then C<PL_sv_undef> will be placed
7741     into the SV. The C<classname> argument indicates the package for the
7742     blessing. Set C<classname> to C<Nullch> to avoid the blessing. The new SV
7743     will have a reference count of 1, and the RV will be returned.
7744    
7745     Do not use with other Perl types such as HV, AV, SV, CV, because those
7746     objects will become corrupted by the pointer copy process.
7747    
7748     Note that C<sv_setref_pvn> copies the string while this copies the pointer.
7749    
7750     =cut
7751     */
7752    
7753     SV*
7754     Perl_sv_setref_pv(pTHX_ SV *rv, const char *classname, void *pv)
7755     {
7756     if (!pv) {
7757     sv_setsv(rv, &PL_sv_undef);
7758     SvSETMAGIC(rv);
7759     }
7760     else
7761     sv_setiv(newSVrv(rv,classname), PTR2IV(pv));
7762     return rv;
7763     }
7764    
7765     /*
7766     =for apidoc sv_setref_iv
7767    
7768     Copies an integer into a new SV, optionally blessing the SV. The C<rv>
7769     argument will be upgraded to an RV. That RV will be modified to point to
7770     the new SV. The C<classname> argument indicates the package for the
7771     blessing. Set C<classname> to C<Nullch> to avoid the blessing. The new SV
7772     will have a reference count of 1, and the RV will be returned.
7773    
7774     =cut
7775     */
7776    
7777     SV*
7778     Perl_sv_setref_iv(pTHX_ SV *rv, const char *classname, IV iv)
7779     {
7780     sv_setiv(newSVrv(rv,classname), iv);
7781     return rv;
7782     }
7783    
7784     /*
7785     =for apidoc sv_setref_uv
7786    
7787     Copies an unsigned integer into a new SV, optionally blessing the SV. The C<rv>
7788     argument will be upgraded to an RV. That RV will be modified to point to
7789     the new SV. The C<classname> argument indicates the package for the
7790     blessing. Set C<classname> to C<Nullch> to avoid the blessing. The new SV
7791     will have a reference count of 1, and the RV will be returned.
7792    
7793     =cut
7794     */
7795    
7796     SV*
7797     Perl_sv_setref_uv(pTHX_ SV *rv, const char *classname, UV uv)
7798     {
7799     sv_setuv(newSVrv(rv,classname), uv);
7800     return rv;
7801     }
7802    
7803     /*
7804     =for apidoc sv_setref_nv
7805    
7806     Copies a double into a new SV, optionally blessing the SV. The C<rv>
7807     argument will be upgraded to an RV. That RV will be modified to point to
7808     the new SV. The C<classname> argument indicates the package for the
7809     blessing. Set C<classname> to C<Nullch> to avoid the blessing. The new SV
7810     will have a reference count of 1, and the RV will be returned.
7811    
7812     =cut
7813     */
7814    
7815     SV*
7816     Perl_sv_setref_nv(pTHX_ SV *rv, const char *classname, NV nv)
7817     {
7818     sv_setnv(newSVrv(rv,classname), nv);
7819     return rv;
7820     }
7821    
7822     /*
7823     =for apidoc sv_setref_pvn
7824    
7825     Copies a string into a new SV, optionally blessing the SV. The length of the
7826     string must be specified with C<n>. The C<rv> argument will be upgraded to
7827     an RV. That RV will be modified to point to the new SV. The C<classname>
7828     argument indicates the package for the blessing. Set C<classname> to
7829     C<Nullch> to avoid the blessing. The new SV will have a reference count
7830     of 1, and the RV will be returned.
7831    
7832     Note that C<sv_setref_pv> copies the pointer while this copies the string.
7833    
7834     =cut
7835     */
7836    
7837     SV*
7838     Perl_sv_setref_pvn(pTHX_ SV *rv, const char *classname, char *pv, STRLEN n)
7839     {
7840     sv_setpvn(newSVrv(rv,classname), pv, n);
7841     return rv;
7842     }
7843    
7844     /*
7845     =for apidoc sv_bless
7846    
7847     Blesses an SV into a specified package. The SV must be an RV. The package
7848     must be designated by its stash (see C<gv_stashpv()>). The reference count
7849     of the SV is unaffected.
7850    
7851     =cut
7852     */
7853    
7854     SV*
7855     Perl_sv_bless(pTHX_ SV *sv, HV *stash)
7856     {
7857     SV *tmpRef;
7858     if (!SvROK(sv))
7859     Perl_croak(aTHX_ "Can't bless non-reference value");
7860     tmpRef = SvRV(sv);
7861     if (SvFLAGS(tmpRef) & (SVs_OBJECT|SVf_READONLY)) {
7862     if (SvREADONLY(tmpRef))
7863     Perl_croak(aTHX_ PL_no_modify);
7864     if (SvOBJECT(tmpRef)) {
7865     if (SvTYPE(tmpRef) != SVt_PVIO)
7866     --PL_sv_objcount;
7867     SvREFCNT_dec(SvSTASH(tmpRef));
7868     }
7869     }
7870     SvOBJECT_on(tmpRef);
7871     if (SvTYPE(tmpRef) != SVt_PVIO)
7872     ++PL_sv_objcount;
7873     (void)SvUPGRADE(tmpRef, SVt_PVMG);
7874     SvSTASH(tmpRef) = (HV*)SvREFCNT_inc(stash);
7875    
7876     if (Gv_AMG(stash))
7877     SvAMAGIC_on(sv);
7878     else
7879     SvAMAGIC_off(sv);
7880    
7881     if(SvSMAGICAL(tmpRef))
7882     if(mg_find(tmpRef, PERL_MAGIC_ext) || mg_find(tmpRef, PERL_MAGIC_uvar))
7883     mg_set(tmpRef);
7884    
7885    
7886    
7887     return sv;
7888     }
7889    
7890     /* Downgrades a PVGV to a PVMG.
7891     */
7892    
7893     STATIC void
7894     S_sv_unglob(pTHX_ SV *sv)
7895     {
7896     void *xpvmg;
7897    
7898     assert(SvTYPE(sv) == SVt_PVGV);
7899     SvFAKE_off(sv);
7900     if (GvGP(sv))
7901     gp_free((GV*)sv);
7902     if (GvSTASH(sv)) {
7903     SvREFCNT_dec(GvSTASH(sv));
7904     GvSTASH(sv) = Nullhv;
7905     }
7906     sv_unmagic(sv, PERL_MAGIC_glob);
7907     Safefree(GvNAME(sv));
7908     GvMULTI_off(sv);
7909    
7910     /* need to keep SvANY(sv) in the right arena */
7911     xpvmg = new_XPVMG();
7912     StructCopy(SvANY(sv), xpvmg, XPVMG);
7913     del_XPVGV(SvANY(sv));
7914     SvANY(sv) = xpvmg;
7915    
7916     SvFLAGS(sv) &= ~SVTYPEMASK;
7917     SvFLAGS(sv) |= SVt_PVMG;
7918     }
7919    
7920     /*
7921     =for apidoc sv_unref_flags
7922    
7923     Unsets the RV status of the SV, and decrements the reference count of
7924     whatever was being referenced by the RV. This can almost be thought of
7925     as a reversal of C<newSVrv>. The C<cflags> argument can contain
7926     C<SV_IMMEDIATE_UNREF> to force the reference count to be decremented
7927     (otherwise the decrementing is conditional on the reference count being
7928     different from one or the reference being a readonly SV).
7929     See C<SvROK_off>.
7930    
7931     =cut
7932     */
7933    
7934     void
7935     Perl_sv_unref_flags(pTHX_ SV *sv, U32 flags)
7936     {
7937     SV* rv = SvRV(sv);
7938    
7939     if (SvWEAKREF(sv)) {
7940     sv_del_backref(sv);
7941     SvWEAKREF_off(sv);
7942     SvRV(sv) = 0;
7943     return;
7944     }
7945     SvRV(sv) = 0;
7946     SvROK_off(sv);
7947     /* You can't have a || SvREADONLY(rv) here, as $a = $$a, where $a was
7948     assigned to as BEGIN {$a = \"Foo"} will fail. */
7949     if (SvREFCNT(rv) != 1 || (flags & SV_IMMEDIATE_UNREF))
7950     SvREFCNT_dec(rv);
7951     else /* XXX Hack, but hard to make $a=$a->[1] work otherwise */
7952     sv_2mortal(rv); /* Schedule for freeing later */
7953     }
7954    
7955     /*
7956     =for apidoc sv_unref
7957    
7958     Unsets the RV status of the SV, and decrements the reference count of
7959     whatever was being referenced by the RV. This can almost be thought of
7960     as a reversal of C<newSVrv>. This is C<sv_unref_flags> with the C<flag>
7961     being zero. See C<SvROK_off>.
7962    
7963     =cut
7964     */
7965    
7966     void
7967     Perl_sv_unref(pTHX_ SV *sv)
7968     {
7969     sv_unref_flags(sv, 0);
7970     }
7971    
7972     /*
7973     =for apidoc sv_taint
7974    
7975     Taint an SV. Use C<SvTAINTED_on> instead.
7976     =cut
7977     */
7978    
7979     void
7980     Perl_sv_taint(pTHX_ SV *sv)
7981     {
7982     sv_magic((sv), Nullsv, PERL_MAGIC_taint, Nullch, 0);
7983     }
7984    
7985     /*
7986     =for apidoc sv_untaint
7987    
7988     Untaint an SV. Use C<SvTAINTED_off> instead.
7989     =cut
7990     */
7991    
7992     void
7993     Perl_sv_untaint(pTHX_ SV *sv)
7994     {
7995     if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
7996     MAGIC *mg = mg_find(sv, PERL_MAGIC_taint);
7997     if (mg)
7998     mg->mg_len &= ~1;
7999     }
8000     }
8001    
8002     /*
8003     =for apidoc sv_tainted
8004    
8005     Test an SV for taintedness. Use C<SvTAINTED> instead.
8006     =cut
8007     */
8008    
8009     bool
8010     Perl_sv_tainted(pTHX_ SV *sv)
8011     {
8012     if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
8013     MAGIC *mg = mg_find(sv, PERL_MAGIC_taint);
8014     if (mg && ((mg->mg_len & 1) || ((mg->mg_len & 2) && mg->mg_obj == sv)))
8015     return TRUE;
8016     }
8017     return FALSE;
8018     }
8019    
8020     /*
8021     =for apidoc sv_setpviv
8022    
8023     Copies an integer into the given SV, also updating its string value.
8024     Does not handle 'set' magic. See C<sv_setpviv_mg>.
8025    
8026     =cut
8027     */
8028    
8029     void
8030     Perl_sv_setpviv(pTHX_ SV *sv, IV iv)
8031     {
8032     char buf[TYPE_CHARS(UV)];
8033     char *ebuf;
8034     char *ptr = uiv_2buf(buf, iv, 0, 0, &ebuf);
8035    
8036     sv_setpvn(sv, ptr, ebuf - ptr);
8037     }
8038    
8039     /*
8040     =for apidoc sv_setpviv_mg
8041    
8042     Like C<sv_setpviv>, but also handles 'set' magic.
8043    
8044     =cut
8045     */
8046    
8047     void
8048     Perl_sv_setpviv_mg(pTHX_ SV *sv, IV iv)
8049     {
8050     char buf[TYPE_CHARS(UV)];
8051     char *ebuf;
8052     char *ptr = uiv_2buf(buf, iv, 0, 0, &ebuf);
8053    
8054     sv_setpvn(sv, ptr, ebuf - ptr);
8055     SvSETMAGIC(sv);
8056     }
8057    
8058     #if defined(PERL_IMPLICIT_CONTEXT)
8059    
8060     /* pTHX_ magic can't cope with varargs, so this is a no-context
8061     * version of the main function, (which may itself be aliased to us).
8062     * Don't access this version directly.
8063     */
8064    
8065     void
8066     Perl_sv_setpvf_nocontext(SV *sv, const char* pat, ...)
8067     {
8068     dTHX;
8069     va_list args;
8070     va_start(args, pat);
8071     sv_vsetpvf(sv, pat, &args);
8072     va_end(args);
8073     }
8074    
8075     /* pTHX_ magic can't cope with varargs, so this is a no-context
8076     * version of the main function, (which may itself be aliased to us).
8077     * Don't access this version directly.
8078     */
8079    
8080     void
8081     Perl_sv_setpvf_mg_nocontext(SV *sv, const char* pat, ...)
8082     {
8083     dTHX;
8084     va_list args;
8085     va_start(args, pat);
8086     sv_vsetpvf_mg(sv, pat, &args);
8087     va_end(args);
8088     }
8089     #endif
8090    
8091     /*
8092     =for apidoc sv_setpvf
8093    
8094     Works like C<sv_catpvf> but copies the text into the SV instead of
8095     appending it. Does not handle 'set' magic. See C<sv_setpvf_mg>.
8096    
8097     =cut
8098     */
8099    
8100     void
8101     Perl_sv_setpvf(pTHX_ SV *sv, const char* pat, ...)
8102     {
8103     va_list args;
8104     va_start(args, pat);
8105     sv_vsetpvf(sv, pat, &args);
8106     va_end(args);
8107     }
8108    
8109     /*
8110     =for apidoc sv_vsetpvf
8111    
8112     Works like C<sv_vcatpvf> but copies the text into the SV instead of
8113     appending it. Does not handle 'set' magic. See C<sv_vsetpvf_mg>.
8114    
8115     Usually used via its frontend C<sv_setpvf>.
8116    
8117     =cut
8118     */
8119    
8120     void
8121     Perl_sv_vsetpvf(pTHX_ SV *sv, const char* pat, va_list* args)
8122     {
8123     sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
8124     }
8125    
8126     /*
8127     =for apidoc sv_setpvf_mg
8128    
8129     Like C<sv_setpvf>, but also handles 'set' magic.
8130    
8131     =cut
8132     */
8133    
8134     void
8135     Perl_sv_setpvf_mg(pTHX_ SV *sv, const char* pat, ...)
8136     {
8137     va_list args;
8138     va_start(args, pat);
8139     sv_vsetpvf_mg(sv, pat, &args);
8140     va_end(args);
8141     }
8142    
8143     /*
8144     =for apidoc sv_vsetpvf_mg
8145    
8146     Like C<sv_vsetpvf>, but also handles 'set' magic.
8147    
8148     Usually used via its frontend C<sv_setpvf_mg>.
8149    
8150     =cut
8151     */
8152    
8153     void
8154     Perl_sv_vsetpvf_mg(pTHX_ SV *sv, const char* pat, va_list* args)
8155     {
8156     sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
8157     SvSETMAGIC(sv);
8158     }
8159    
8160     #if defined(PERL_IMPLICIT_CONTEXT)
8161    
8162     /* pTHX_ magic can't cope with varargs, so this is a no-context
8163     * version of the main function, (which may itself be aliased to us).
8164     * Don't access this version directly.
8165     */
8166    
8167     void
8168     Perl_sv_catpvf_nocontext(SV *sv, const char* pat, ...)
8169     {
8170     dTHX;
8171     va_list args;
8172     va_start(args, pat);
8173     sv_vcatpvf(sv, pat, &args);
8174     va_end(args);
8175     }
8176    
8177     /* pTHX_ magic can't cope with varargs, so this is a no-context
8178     * version of the main function, (which may itself be aliased to us).
8179     * Don't access this version directly.
8180     */
8181    
8182     void
8183     Perl_sv_catpvf_mg_nocontext(SV *sv, const char* pat, ...)
8184     {
8185     dTHX;
8186     va_list args;
8187     va_start(args, pat);
8188     sv_vcatpvf_mg(sv, pat, &args);
8189     va_end(args);
8190     }
8191     #endif
8192    
8193     /*
8194     =for apidoc sv_catpvf
8195    
8196     Processes its arguments like C<sprintf> and appends the formatted
8197     output to an SV. If the appended data contains "wide" characters
8198     (including, but not limited to, SVs with a UTF-8 PV formatted with %s,
8199     and characters >255 formatted with %c), the original SV might get
8200     upgraded to UTF-8. Handles 'get' magic, but not 'set' magic. See
8201     C<sv_catpvf_mg>. If the original SV was UTF-8, the pattern should be
8202     valid UTF-8; if the original SV was bytes, the pattern should be too.
8203    
8204     =cut */
8205    
8206     void
8207     Perl_sv_catpvf(pTHX_ SV *sv, const char* pat, ...)
8208     {
8209     va_list args;
8210     va_start(args, pat);
8211     sv_vcatpvf(sv, pat, &args);
8212     va_end(args);
8213     }
8214    
8215     /*
8216     =for apidoc sv_vcatpvf
8217    
8218     Processes its arguments like C<vsprintf> and appends the formatted output
8219     to an SV. Does not handle 'set' magic. See C<sv_vcatpvf_mg>.
8220    
8221     Usually used via its frontend C<sv_catpvf>.
8222    
8223     =cut
8224     */
8225    
8226     void
8227     Perl_sv_vcatpvf(pTHX_ SV *sv, const char* pat, va_list* args)
8228     {
8229     sv_vcatpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
8230     }
8231    
8232     /*
8233     =for apidoc sv_catpvf_mg
8234    
8235     Like C<sv_catpvf>, but also handles 'set' magic.
8236    
8237     =cut
8238     */
8239    
8240     void
8241     Perl_sv_catpvf_mg(pTHX_ SV *sv, const char* pat, ...)
8242     {
8243     va_list args;
8244     va_start(args, pat);
8245     sv_vcatpvf_mg(sv, pat, &args);
8246     va_end(args);
8247     }
8248    
8249     /*
8250     =for apidoc sv_vcatpvf_mg
8251    
8252     Like C<sv_vcatpvf>, but also handles 'set' magic.
8253    
8254     Usually used via its frontend C<sv_catpvf_mg>.
8255    
8256     =cut
8257     */
8258    
8259     void
8260     Perl_sv_vcatpvf_mg(pTHX_ SV *sv, const char* pat, va_list* args)
8261     {
8262     sv_vcatpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
8263     SvSETMAGIC(sv);
8264     }
8265    
8266     /*
8267     =for apidoc sv_vsetpvfn
8268    
8269     Works like C<sv_vcatpvfn> but copies the text into the SV instead of
8270     appending it.
8271    
8272     Usually used via one of its frontends C<sv_vsetpvf> and C<sv_vsetpvf_mg>.
8273    
8274     =cut
8275     */
8276    
8277     void
8278     Perl_sv_vsetpvfn(pTHX_ SV *sv, const char *pat, STRLEN patlen, va_list *args, SV **svargs, I32 svmax, bool *maybe_tainted)
8279     {
8280     sv_setpvn(sv, "", 0);
8281     sv_vcatpvfn(sv, pat, patlen, args, svargs, svmax, maybe_tainted);
8282     }
8283    
8284     /* private function for use in sv_vcatpvfn via the EXPECT_NUMBER macro */
8285    
8286     STATIC I32
8287     S_expect_number(pTHX_ char** pattern)
8288     {
8289     I32 var = 0;
8290     switch (**pattern) {
8291     case '1': case '2': case '3':
8292     case '4': case '5': case '6':
8293     case '7': case '8': case '9':
8294     while (isDIGIT(**pattern))
8295     var = var * 10 + (*(*pattern)++ - '0');
8296     }
8297     return var;
8298     }
8299     #define EXPECT_NUMBER(pattern, var) (var = S_expect_number(aTHX_ &pattern))
8300    
8301     static char *
8302     F0convert(NV nv, char *endbuf, STRLEN *len)
8303     {
8304     int neg = nv < 0;
8305     UV uv;
8306     char *p = endbuf;
8307    
8308     if (neg)
8309     nv = -nv;
8310     if (nv < UV_MAX) {
8311     nv += 0.5;
8312     uv = (UV)nv;
8313     if (uv & 1 && uv == nv)
8314     uv--; /* Round to even */
8315     do {
8316     unsigned dig = uv % 10;
8317     *--p = '0' + dig;
8318     } while (uv /= 10);
8319     if (neg)
8320     *--p = '-';
8321     *len = endbuf - p;
8322     return p;
8323     }
8324     return Nullch;
8325     }
8326    
8327    
8328     /*
8329     =for apidoc sv_vcatpvfn
8330    
8331     Processes its arguments like C<vsprintf> and appends the formatted output
8332     to an SV. Uses an array of SVs if the C style variable argument list is
8333     missing (NULL). When running with taint checks enabled, indicates via
8334     C<maybe_tainted> if results are untrustworthy (often due to the use of
8335     locales).
8336    
8337     Usually used via one of its frontends C<sv_vcatpvf> and C<sv_vcatpvf_mg>.
8338    
8339     =cut
8340     */
8341    
8342     void
8343     Perl_sv_vcatpvfn(pTHX_ SV *sv, const char *pat, STRLEN patlen, va_list *args, SV **svargs, I32 svmax, bool *maybe_tainted)
8344     {
8345     char *p;
8346     char *q;
8347     char *patend;
8348     STRLEN origlen;
8349     I32 svix = 0;
8350     static char nullstr[] = "(null)";
8351     SV *argsv = Nullsv;
8352     bool has_utf8; /* has the result utf8? */
8353     bool pat_utf8; /* the pattern is in utf8? */
8354     SV *nsv = Nullsv;
8355     /* Times 4: a decimal digit takes more than 3 binary digits.
8356     * NV_DIG: mantissa takes than many decimal digits.
8357     * Plus 32: Playing safe. */
8358     char ebuf[IV_DIG * 4 + NV_DIG + 32];
8359     /* large enough for "%#.#f" --chip */
8360     /* what about long double NVs? --jhi */
8361    
8362     has_utf8 = pat_utf8 = DO_UTF8(sv);
8363    
8364     /* no matter what, this is a string now */
8365     (void)SvPV_force(sv, origlen);
8366    
8367     /* special-case "", "%s", and "%_" */
8368     if (patlen == 0)
8369     return;
8370     if (patlen == 2 && pat[0] == '%') {
8371     switch (pat[1]) {
8372     case 's':
8373     if (args) {
8374     char *s = va_arg(*args, char*);
8375     sv_catpv(sv, s ? s : nullstr);
8376     }
8377     else if (svix < svmax) {
8378     sv_catsv(sv, *svargs);
8379     if (DO_UTF8(*svargs))
8380     SvUTF8_on(sv);
8381     }
8382     return;
8383     case '_':
8384     if (args) {
8385     argsv = va_arg(*args, SV*);
8386     sv_catsv(sv, argsv);
8387     if (DO_UTF8(argsv))
8388     SvUTF8_on(sv);
8389     return;
8390     }
8391     /* See comment on '_' below */
8392     break;
8393     }
8394     }
8395    
8396     #ifndef USE_LONG_DOUBLE
8397     /* special-case "%.<number>[gf]" */
8398     if ( patlen <= 5 && pat[0] == '%' && pat[1] == '.'
8399     && (pat[patlen-1] == 'g' || pat[patlen-1] == 'f') ) {
8400     unsigned digits = 0;
8401     const char *pp;
8402    
8403     pp = pat + 2;
8404     while (*pp >= '0' && *pp <= '9')
8405     digits = 10 * digits + (*pp++ - '0');
8406     if (pp - pat == (int)patlen - 1) {
8407     NV nv;
8408    
8409     if (args)
8410     nv = (NV)va_arg(*args, double);
8411     else if (svix < svmax)
8412     nv = SvNV(*svargs);
8413     else
8414     return;
8415     if (*pp == 'g') {
8416     /* Add check for digits != 0 because it seems that some
8417     gconverts are buggy in this case, and we don't yet have
8418     a Configure test for this. */
8419     if (digits && digits < sizeof(ebuf) - NV_DIG - 10) {
8420     /* 0, point, slack */
8421     Gconvert(nv, (int)digits, 0, ebuf);
8422     sv_catpv(sv, ebuf);
8423     if (*ebuf) /* May return an empty string for digits==0 */
8424     return;
8425     }
8426     } else if (!digits) {
8427     STRLEN l;
8428    
8429     if ((p = F0convert(nv, ebuf + sizeof ebuf, &l))) {
8430     sv_catpvn(sv, p, l);
8431     return;
8432     }
8433     }
8434     }
8435     }
8436     #endif /* !USE_LONG_DOUBLE */
8437    
8438     if (!args && svix < svmax && DO_UTF8(*svargs))
8439     has_utf8 = TRUE;
8440    
8441     patend = (char*)pat + patlen;
8442     for (p = (char*)pat; p < patend; p = q) {
8443     bool alt = FALSE;
8444     bool left = FALSE;
8445     bool vectorize = FALSE;
8446     bool vectorarg = FALSE;
8447     bool vec_utf8 = FALSE;
8448     char fill = ' ';
8449     char plus = 0;
8450     char intsize = 0;
8451     STRLEN width = 0;
8452     STRLEN zeros = 0;
8453     bool has_precis = FALSE;
8454     STRLEN precis = 0;
8455     I32 osvix = svix;
8456     bool is_utf8 = FALSE; /* is this item utf8? */
8457     #ifdef HAS_LDBL_SPRINTF_BUG
8458     /* This is to try to fix a bug with irix/nonstop-ux/powerux and
8459     with sfio - Allen <allens@cpan.org> */
8460     bool fix_ldbl_sprintf_bug = FALSE;
8461     #endif
8462    
8463     char esignbuf[4];
8464     U8 utf8buf[UTF8_MAXBYTES+1];
8465     STRLEN esignlen = 0;
8466    
8467     char *eptr = Nullch;
8468     STRLEN elen = 0;
8469     SV *vecsv = Nullsv;
8470     U8 *vecstr = Null(U8*);
8471     STRLEN veclen = 0;
8472     char c = 0;
8473     int i;
8474     unsigned base = 0;
8475     IV iv = 0;
8476     UV uv = 0;
8477     /* we need a long double target in case HAS_LONG_DOUBLE but
8478     not USE_LONG_DOUBLE
8479     */
8480     #if defined(HAS_LONG_DOUBLE) && LONG_DOUBLESIZE > DOUBLESIZE
8481     long double nv;
8482     #else
8483     NV nv;
8484     #endif
8485     STRLEN have;
8486     STRLEN need;
8487     STRLEN gap;
8488     char *dotstr = ".";
8489     STRLEN dotstrlen = 1;
8490     I32 efix = 0; /* explicit format parameter index */
8491     I32 ewix = 0; /* explicit width index */
8492     I32 epix = 0; /* explicit precision index */
8493     I32 evix = 0; /* explicit vector index */
8494     bool asterisk = FALSE;
8495    
8496     /* echo everything up to the next format specification */
8497     for (q = p; q < patend && *q != '%'; ++q) ;
8498     if (q > p) {
8499     if (has_utf8 && !pat_utf8)
8500     sv_catpvn_utf8_upgrade(sv, p, q - p, nsv);
8501     else
8502     sv_catpvn(sv, p, q - p);
8503     p = q;
8504     }
8505     if (q++ >= patend)
8506     break;
8507    
8508     /*
8509     We allow format specification elements in this order:
8510     \d+\$ explicit format parameter index
8511     [-+ 0#]+ flags
8512     v|\*(\d+\$)?v vector with optional (optionally specified) arg
8513     0 flag (as above): repeated to allow "v02"
8514     \d+|\*(\d+\$)? width using optional (optionally specified) arg
8515     \.(\d*|\*(\d+\$)?) precision using optional (optionally specified) arg
8516     [hlqLV] size
8517     [%bcdefginopsux_DFOUX] format (mandatory)
8518     */
8519     if (EXPECT_NUMBER(q, width)) {
8520     if (*q == '$') {
8521     ++q;
8522     efix = width;
8523     } else {
8524     goto gotwidth;
8525     }
8526     }
8527    
8528     /* FLAGS */
8529    
8530     while (*q) {
8531     switch (*q) {
8532     case ' ':
8533     case '+':
8534     plus = *q++;
8535     continue;
8536    
8537     case '-':
8538     left = TRUE;
8539     q++;
8540     continue;
8541    
8542     case '0':
8543     fill = *q++;
8544     continue;
8545    
8546     case '#':
8547     alt = TRUE;
8548     q++;
8549     continue;
8550    
8551     default:
8552     break;
8553     }
8554     break;
8555     }
8556    
8557     tryasterisk:
8558     if (*q == '*') {
8559     q++;
8560     if (EXPECT_NUMBER(q, ewix))
8561     if (*q++ != '$')
8562     goto unknown;
8563     asterisk = TRUE;
8564     }
8565     if (*q == 'v') {
8566     q++;
8567     if (vectorize)
8568     goto unknown;
8569     if ((vectorarg = asterisk)) {
8570     evix = ewix;
8571     ewix = 0;
8572     asterisk = FALSE;
8573     }
8574     vectorize = TRUE;
8575     goto tryasterisk;
8576     }
8577    
8578     if (!asterisk)
8579     if( *q == '0' )
8580     fill = *q++;
8581     EXPECT_NUMBER(q, width);
8582    
8583     #ifdef CHECK_FORMAT
8584     if ((*q == 'p') && left) {
8585     vectorize = (width == 1);
8586     }
8587     #endif
8588     if (vectorize) {
8589     if (vectorarg) {
8590     if (args)
8591     vecsv = va_arg(*args, SV*);
8592     else
8593     vecsv = (evix ? evix <= svmax : svix < svmax) ?
8594     svargs[evix ? evix-1 : svix++] : &PL_sv_undef;
8595     dotstr = SvPVx(vecsv, dotstrlen);
8596     if (DO_UTF8(vecsv))
8597     is_utf8 = TRUE;
8598     }
8599     if (args) {
8600     vecsv = va_arg(*args, SV*);
8601     vecstr = (U8*)SvPVx(vecsv,veclen);
8602     vec_utf8 = DO_UTF8(vecsv);
8603     }
8604     else if (efix ? efix <= svmax : svix < svmax) {
8605     vecsv = svargs[efix ? efix-1 : svix++];
8606     vecstr = (U8*)SvPVx(vecsv,veclen);
8607     vec_utf8 = DO_UTF8(vecsv);
8608     }
8609     else {
8610     vecstr = (U8*)"";
8611     veclen = 0;
8612     }
8613     }
8614    
8615     if (asterisk) {
8616     if (args)
8617     i = va_arg(*args, int);
8618     else
8619     i = (ewix ? ewix <= svmax : svix < svmax) ?
8620     SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
8621     left |= (i < 0);
8622     width = (i < 0) ? -i : i;
8623     }
8624     gotwidth:
8625    
8626     /* PRECISION */
8627    
8628     if (*q == '.') {
8629     q++;
8630     if (*q == '*') {
8631     q++;
8632     if (EXPECT_NUMBER(q, epix) && *q++ != '$')
8633     goto unknown;
8634     /* XXX: todo, support specified precision parameter */
8635     if (epix)
8636     goto unknown;
8637     if (args)
8638     i = va_arg(*args, int);
8639     else
8640     i = (ewix ? ewix <= svmax : svix < svmax)
8641     ? SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
8642     precis = (i < 0) ? 0 : i;
8643     }
8644     else {
8645     precis = 0;
8646     while (isDIGIT(*q))
8647     precis = precis * 10 + (*q++ - '0');
8648     }
8649     has_precis = TRUE;
8650     }
8651    
8652     /* SIZE */
8653    
8654     switch (*q) {
8655     #ifdef WIN32
8656     case 'I': /* Ix, I32x, and I64x */
8657     # ifdef WIN64
8658     if (q[1] == '6' && q[2] == '4') {
8659     q += 3;
8660     intsize = 'q';
8661     break;
8662     }
8663     # endif
8664     if (q[1] == '3' && q[2] == '2') {
8665     q += 3;
8666     break;
8667     }
8668     # ifdef WIN64
8669     intsize = 'q';
8670     # endif
8671     q++;
8672     break;
8673     #endif
8674     #if defined(HAS_QUAD) || defined(HAS_LONG_DOUBLE)
8675     case 'L': /* Ld */
8676     /* FALL THROUGH */
8677     #ifdef HAS_QUAD
8678     case 'q': /* qd */
8679     #endif
8680     intsize = 'q';
8681     q++;
8682     break;
8683     #endif
8684     case 'l':
8685     #if defined(HAS_QUAD) || defined(HAS_LONG_DOUBLE)
8686     if (*(q + 1) == 'l') { /* lld, llf */
8687     intsize = 'q';
8688     q += 2;
8689     break;
8690     }
8691     #endif
8692     /* FALL THROUGH */
8693     case 'h':
8694     /* FALL THROUGH */
8695     case 'V':
8696     intsize = *q++;
8697     break;
8698     }
8699    
8700     /* CONVERSION */
8701    
8702     if (*q == '%') {
8703     eptr = q++;
8704     elen = 1;
8705     goto string;
8706     }
8707    
8708     if (vectorize)
8709     argsv = vecsv;
8710     else if (!args)
8711     argsv = (efix ? efix <= svmax : svix < svmax) ?
8712     svargs[efix ? efix-1 : svix++] : &PL_sv_undef;
8713    
8714     switch (c = *q++) {
8715    
8716     /* STRINGS */
8717    
8718     case 'c':
8719     uv = (args && !vectorize) ? va_arg(*args, int) : SvIVx(argsv);
8720     if ((uv > 255 ||
8721     (!UNI_IS_INVARIANT(uv) && SvUTF8(sv)))
8722     && !IN_BYTES) {
8723     eptr = (char*)utf8buf;
8724     elen = uvchr_to_utf8((U8*)eptr, uv) - utf8buf;
8725     is_utf8 = TRUE;
8726     }
8727     else {
8728     c = (char)uv;
8729     eptr = &c;
8730     elen = 1;
8731     }
8732     goto string;
8733    
8734     case 's':
8735     if (args && !vectorize) {
8736     eptr = va_arg(*args, char*);
8737     if (eptr)
8738     #ifdef MACOS_TRADITIONAL
8739     /* On MacOS, %#s format is used for Pascal strings */
8740     if (alt)
8741     elen = *eptr++;
8742     else
8743     #endif
8744     elen = strlen(eptr);
8745     else {
8746     eptr = nullstr;
8747     elen = sizeof nullstr - 1;
8748     }
8749     }
8750     else {
8751     eptr = SvPVx(argsv, elen);
8752     if (DO_UTF8(argsv)) {
8753     if (has_precis && precis < elen) {
8754     I32 p = precis;
8755     sv_pos_u2b(argsv, &p, 0); /* sticks at end */
8756     precis = p;
8757     }
8758     if (width) { /* fudge width (can't fudge elen) */
8759     width += elen - sv_len_utf8(argsv);
8760     }
8761     is_utf8 = TRUE;
8762     }
8763     }
8764     goto string;
8765    
8766     case '_':
8767     #ifdef CHECK_FORMAT
8768     format_sv:
8769     #endif
8770     /*
8771     * The "%_" hack might have to be changed someday,
8772     * if ISO or ANSI decide to use '_' for something.
8773     * So we keep it hidden from users' code.
8774     */
8775     if (!args || vectorize)
8776     goto unknown;
8777     argsv = va_arg(*args, SV*);
8778     eptr = SvPVx(argsv, elen);
8779     if (DO_UTF8(argsv))
8780     is_utf8 = TRUE;
8781    
8782     string:
8783     vectorize = FALSE;
8784     if (has_precis && elen > precis)
8785     elen = precis;
8786     break;
8787    
8788     /* INTEGERS */
8789    
8790     case 'p':
8791     #ifdef CHECK_FORMAT
8792     if (left) {
8793     left = FALSE;
8794     if (!width)
8795     goto format_sv; /* %-p -> %_ */
8796     if (vectorize) {
8797     width = 0;
8798     goto format_vd; /* %-1p -> %vd */
8799     }
8800     precis = width;
8801     has_precis = TRUE;
8802     width = 0;
8803     goto format_sv; /* %-Np -> %.N_ */
8804     }
8805     #endif
8806     if (alt || vectorize)
8807     goto unknown;
8808     uv = PTR2UV(args ? va_arg(*args, void*) : argsv);
8809     base = 16;
8810     goto integer;
8811    
8812     case 'D':
8813     #ifdef IV_IS_QUAD
8814     intsize = 'q';
8815     #else
8816     intsize = 'l';
8817     #endif
8818     /* FALL THROUGH */
8819     case 'd':
8820     case 'i':
8821     #ifdef CHECK_FORMAT
8822     format_vd:
8823     #endif
8824     if (vectorize) {
8825     STRLEN ulen;
8826     if (!veclen)
8827     continue;
8828     if (vec_utf8)
8829     uv = utf8n_to_uvchr(vecstr, veclen, &ulen,
8830     UTF8_ALLOW_ANYUV);
8831     else {
8832     uv = *vecstr;
8833     ulen = 1;
8834     }
8835     vecstr += ulen;
8836     veclen -= ulen;
8837     if (plus)
8838     esignbuf[esignlen++] = plus;
8839     }
8840     else if (args) {
8841     switch (intsize) {
8842     case 'h': iv = (short)va_arg(*args, int); break;
8843     case 'l': iv = va_arg(*args, long); break;
8844     case 'V': iv = va_arg(*args, IV); break;
8845     default: iv = va_arg(*args, int); break;
8846     #ifdef HAS_QUAD
8847     case 'q': iv = va_arg(*args, Quad_t); break;
8848     #endif
8849     }
8850     }
8851     else {
8852     IV tiv = SvIVx(argsv); /* work around GCC bug #13488 */
8853     switch (intsize) {
8854     case 'h': iv = (short)tiv; break;
8855     case 'l': iv = (long)tiv; break;
8856     case 'V':
8857     default: iv = tiv; break;
8858     #ifdef HAS_QUAD
8859     case 'q': iv = (Quad_t)tiv; break;
8860     #endif
8861     }
8862     }
8863     if ( !vectorize ) /* we already set uv above */
8864     {
8865     if (iv >= 0) {
8866     uv = iv;
8867     if (plus)
8868     esignbuf[esignlen++] = plus;
8869     }
8870     else {
8871     uv = -iv;
8872     esignbuf[esignlen++] = '-';
8873     }
8874     }
8875     base = 10;
8876     goto integer;
8877    
8878     case 'U':
8879     #ifdef IV_IS_QUAD
8880     intsize = 'q';
8881     #else
8882     intsize = 'l';
8883     #endif
8884     /* FALL THROUGH */
8885     case 'u':
8886     base = 10;
8887     goto uns_integer;
8888    
8889     case 'b':
8890     base = 2;
8891     goto uns_integer;
8892    
8893     case 'O':
8894     #ifdef IV_IS_QUAD
8895     intsize = 'q';
8896     #else
8897     intsize = 'l';
8898     #endif
8899     /* FALL THROUGH */
8900     case 'o':
8901     base = 8;
8902     goto uns_integer;
8903    
8904     case 'X':
8905     case 'x':
8906     base = 16;
8907    
8908     uns_integer:
8909     if (vectorize) {
8910     STRLEN ulen;
8911     vector:
8912     if (!veclen)
8913     continue;
8914     if (vec_utf8)
8915     uv = utf8n_to_uvchr(vecstr, veclen, &ulen,
8916     UTF8_ALLOW_ANYUV);
8917     else {
8918     uv = *vecstr;
8919     ulen = 1;
8920     }
8921     vecstr += ulen;
8922     veclen -= ulen;
8923     }
8924     else if (args) {
8925     switch (intsize) {
8926     case 'h': uv = (unsigned short)va_arg(*args, unsigned); break;
8927     case 'l': uv = va_arg(*args, unsigned long); break;
8928     case 'V': uv = va_arg(*args, UV); break;
8929     default: uv = va_arg(*args, unsigned); break;
8930     #ifdef HAS_QUAD
8931     case 'q': uv = va_arg(*args, Uquad_t); break;
8932     #endif
8933     }
8934     }
8935     else {
8936     UV tuv = SvUVx(argsv); /* work around GCC bug #13488 */
8937     switch (intsize) {
8938     case 'h': uv = (unsigned short)tuv; break;
8939     case 'l': uv = (unsigned long)tuv; break;
8940     case 'V':
8941     default: uv = tuv; break;
8942     #ifdef HAS_QUAD
8943     case 'q': uv = (Uquad_t)tuv; break;
8944     #endif
8945     }
8946     }
8947    
8948     integer:
8949     eptr = ebuf + sizeof ebuf;
8950     switch (base) {
8951     unsigned dig;
8952     case 16:
8953     if (!uv)
8954     alt = FALSE;
8955     p = (char*)((c == 'X')
8956     ? "0123456789ABCDEF" : "0123456789abcdef");
8957     do {
8958     dig = uv & 15;
8959     *--eptr = p[dig];
8960     } while (uv >>= 4);
8961     if (alt) {
8962     esignbuf[esignlen++] = '0';
8963     esignbuf[esignlen++] = c; /* 'x' or 'X' */
8964     }
8965     break;
8966     case 8:
8967     do {
8968     dig = uv & 7;
8969     *--eptr = '0' + dig;
8970     } while (uv >>= 3);
8971     if (alt && *eptr != '0')
8972     *--eptr = '0';
8973     break;
8974     case 2:
8975     do {
8976     dig = uv & 1;
8977     *--eptr = '0' + dig;
8978     } while (uv >>= 1);
8979     if (alt) {
8980     esignbuf[esignlen++] = '0';
8981     esignbuf[esignlen++] = 'b';
8982     }
8983     break;
8984     default: /* it had better be ten or less */
8985     #if defined(PERL_Y2KWARN)
8986     if (ckWARN(WARN_Y2K)) {
8987     STRLEN n;
8988     char *s = SvPV(sv,n);
8989     if (n >= 2 && s[n-2] == '1' && s[n-1] == '9'
8990     && (n == 2 || !isDIGIT(s[n-3])))
8991     {
8992     Perl_warner(aTHX_ packWARN(WARN_Y2K),
8993     "Possible Y2K bug: %%%c %s",
8994     c, "format string following '19'");
8995     }
8996     }
8997     #endif
8998     do {
8999     dig = uv % base;
9000     *--eptr = '0' + dig;
9001     } while (uv /= base);
9002     break;
9003     }
9004     elen = (ebuf + sizeof ebuf) - eptr;
9005     if (has_precis) {
9006     if (precis > elen)
9007     zeros = precis - elen;
9008     else if (precis == 0 && elen == 1 && *eptr == '0')
9009     elen = 0;
9010     }
9011     break;
9012    
9013     /* FLOATING POINT */
9014    
9015     case 'F':
9016     c = 'f'; /* maybe %F isn't supported here */
9017     /* FALL THROUGH */
9018     case 'e': case 'E':
9019     case 'f':
9020     case 'g': case 'G':
9021    
9022     /* This is evil, but floating point is even more evil */
9023    
9024     /* for SV-style calling, we can only get NV
9025     for C-style calling, we assume %f is double;
9026     for simplicity we allow any of %Lf, %llf, %qf for long double
9027     */
9028     switch (intsize) {
9029     case 'V':
9030     #if defined(USE_LONG_DOUBLE)
9031     intsize = 'q';
9032     #endif
9033     break;
9034     /* [perl #20339] - we should accept and ignore %lf rather than die */
9035     case 'l':
9036     /* FALL THROUGH */
9037     default:
9038     #if defined(USE_LONG_DOUBLE)
9039     intsize = args ? 0 : 'q';
9040     #endif
9041     break;
9042     case 'q':
9043     #if defined(HAS_LONG_DOUBLE)
9044     break;
9045     #else
9046     /* FALL THROUGH */
9047     #endif
9048     case 'h':
9049     goto unknown;
9050     }
9051    
9052     /* now we need (long double) if intsize == 'q', else (double) */
9053     nv = (args && !vectorize) ?
9054     #if LONG_DOUBLESIZE > DOUBLESIZE
9055     intsize == 'q' ?
9056     va_arg(*args, long double) :
9057     va_arg(*args, double)
9058     #else
9059     va_arg(*args, double)
9060     #endif
9061     : SvNVx(argsv);
9062    
9063     need = 0;
9064     vectorize = FALSE;
9065     if (c != 'e' && c != 'E') {
9066     i = PERL_INT_MIN;
9067     /* FIXME: if HAS_LONG_DOUBLE but not USE_LONG_DOUBLE this
9068     will cast our (long double) to (double) */
9069     (void)Perl_frexp(nv, &i);
9070     if (i == PERL_INT_MIN)
9071     Perl_die(aTHX_ "panic: frexp");
9072     if (i > 0)
9073     need = BIT_DIGITS(i);
9074     }
9075     need += has_precis ? precis : 6; /* known default */
9076    
9077     if (need < width)
9078     need = width;
9079    
9080     #ifdef HAS_LDBL_SPRINTF_BUG
9081     /* This is to try to fix a bug with irix/nonstop-ux/powerux and
9082     with sfio - Allen <allens@cpan.org> */
9083    
9084     # ifdef DBL_MAX
9085     # define MY_DBL_MAX DBL_MAX
9086     # else /* XXX guessing! HUGE_VAL may be defined as infinity, so not using */
9087     # if DOUBLESIZE >= 8
9088     # define MY_DBL_MAX 1.7976931348623157E+308L
9089     # else
9090     # define MY_DBL_MAX 3.40282347E+38L
9091     # endif
9092     # endif
9093    
9094     # ifdef HAS_LDBL_SPRINTF_BUG_LESS1 /* only between -1L & 1L - Allen */
9095     # define MY_DBL_MAX_BUG 1L
9096     # else
9097     # define MY_DBL_MAX_BUG MY_DBL_MAX
9098     # endif
9099    
9100     # ifdef DBL_MIN
9101     # define MY_DBL_MIN DBL_MIN
9102     # else /* XXX guessing! -Allen */
9103     # if DOUBLESIZE >= 8
9104     # define MY_DBL_MIN 2.2250738585072014E-308L
9105     # else
9106     # define MY_DBL_MIN 1.17549435E-38L
9107     # endif
9108     # endif
9109    
9110     if ((intsize == 'q') && (c == 'f') &&
9111     ((nv < MY_DBL_MAX_BUG) && (nv > -MY_DBL_MAX_BUG)) &&
9112     (need < DBL_DIG)) {
9113     /* it's going to be short enough that
9114     * long double precision is not needed */
9115    
9116     if ((nv <= 0L) && (nv >= -0L))
9117     fix_ldbl_sprintf_bug = TRUE; /* 0 is 0 - easiest */
9118     else {
9119     /* would use Perl_fp_class as a double-check but not
9120     * functional on IRIX - see perl.h comments */
9121    
9122     if ((nv >= MY_DBL_MIN) || (nv <= -MY_DBL_MIN)) {
9123     /* It's within the range that a double can represent */
9124     #if defined(DBL_MAX) && !defined(DBL_MIN)
9125     if ((nv >= ((long double)1/DBL_MAX)) ||
9126     (nv <= (-(long double)1/DBL_MAX)))
9127     #endif
9128     fix_ldbl_sprintf_bug = TRUE;
9129     }
9130     }
9131     if (fix_ldbl_sprintf_bug == TRUE) {
9132     double temp;
9133    
9134     intsize = 0;
9135     temp = (double)nv;
9136     nv = (NV)temp;
9137     }
9138     }
9139    
9140     # undef MY_DBL_MAX
9141     # undef MY_DBL_MAX_BUG
9142     # undef MY_DBL_MIN
9143    
9144     #endif /* HAS_LDBL_SPRINTF_BUG */
9145    
9146     need += 20; /* fudge factor */
9147     if (PL_efloatsize < need) {
9148     Safefree(PL_efloatbuf);
9149     PL_efloatsize = need + 20; /* more fudge */
9150     New(906, PL_efloatbuf, PL_efloatsize, char);
9151     PL_efloatbuf[0] = '\0';
9152     }
9153    
9154     if ( !(width || left || plus || alt) && fill != '0'
9155     && has_precis && intsize != 'q' ) { /* Shortcuts */
9156     /* See earlier comment about buggy Gconvert when digits,
9157     aka precis is 0 */
9158     if ( c == 'g' && precis) {
9159     Gconvert((NV)nv, (int)precis, 0, PL_efloatbuf);
9160     if (*PL_efloatbuf) /* May return an empty string for digits==0 */
9161     goto float_converted;
9162     } else if ( c == 'f' && !precis) {
9163     if ((eptr = F0convert(nv, ebuf + sizeof ebuf, &elen)))
9164     break;
9165     }
9166     }
9167     eptr = ebuf + sizeof ebuf;
9168     *--eptr = '\0';
9169     *--eptr = c;
9170     /* FIXME: what to do if HAS_LONG_DOUBLE but not PERL_PRIfldbl? */
9171     #if defined(HAS_LONG_DOUBLE) && defined(PERL_PRIfldbl)
9172     if (intsize == 'q') {
9173     /* Copy the one or more characters in a long double
9174     * format before the 'base' ([efgEFG]) character to
9175     * the format string. */
9176     static char const prifldbl[] = PERL_PRIfldbl;
9177     char const *p = prifldbl + sizeof(prifldbl) - 3;
9178     while (p >= prifldbl) { *--eptr = *p--; }
9179     }
9180     #endif
9181     if (has_precis) {
9182     base = precis;
9183     do { *--eptr = '0' + (base % 10); } while (base /= 10);
9184     *--eptr = '.';
9185     }
9186     if (width) {
9187     base = width;
9188     do { *--eptr = '0' + (base % 10); } while (base /= 10);
9189     }
9190     if (fill == '0')
9191     *--eptr = fill;
9192     if (left)
9193     *--eptr = '-';
9194     if (plus)
9195     *--eptr = plus;
9196     if (alt)
9197     *--eptr = '#';
9198     *--eptr = '%';
9199    
9200     /* No taint. Otherwise we are in the strange situation
9201     * where printf() taints but print($float) doesn't.
9202     * --jhi */
9203     #if defined(HAS_LONG_DOUBLE)
9204     if (intsize == 'q')
9205     (void)sprintf(PL_efloatbuf, eptr, nv);
9206     else
9207     (void)sprintf(PL_efloatbuf, eptr, (double)nv);
9208     #else
9209     (void)sprintf(PL_efloatbuf, eptr, nv);
9210     #endif
9211     float_converted:
9212     eptr = PL_efloatbuf;
9213     elen = strlen(PL_efloatbuf);
9214     break;
9215    
9216     /* SPECIAL */
9217    
9218     case 'n':
9219     i = SvCUR(sv) - origlen;
9220     if (args && !vectorize) {
9221     switch (intsize) {
9222     case 'h': *(va_arg(*args, short*)) = i; break;
9223     default: *(va_arg(*args, int*)) = i; break;
9224     case 'l': *(va_arg(*args, long*)) = i; break;
9225     case 'V': *(va_arg(*args, IV*)) = i; break;
9226     #ifdef HAS_QUAD
9227     case 'q': *(va_arg(*args, Quad_t*)) = i; break;
9228     #endif
9229     }
9230     }
9231     else
9232     sv_setuv_mg(argsv, (UV)i);
9233     vectorize = FALSE;
9234     continue; /* not "break" */
9235    
9236     /* UNKNOWN */
9237    
9238     default:
9239     unknown:
9240     if (!args && ckWARN(WARN_PRINTF) &&
9241     (PL_op->op_type == OP_PRTF || PL_op->op_type == OP_SPRINTF)) {
9242     SV *msg = sv_newmortal();
9243     Perl_sv_setpvf(aTHX_ msg, "Invalid conversion in %sprintf: ",
9244     (PL_op->op_type == OP_PRTF) ? "" : "s");
9245     if (c) {
9246     if (isPRINT(c))
9247     Perl_sv_catpvf(aTHX_ msg,
9248     "\"%%%c\"", c & 0xFF);
9249     else
9250     Perl_sv_catpvf(aTHX_ msg,
9251     "\"%%\\%03"UVof"\"",
9252     (UV)c & 0xFF);
9253     } else
9254     sv_catpv(msg, "end of string");
9255     Perl_warner(aTHX_ packWARN(WARN_PRINTF), "%"SVf, msg); /* yes, this is reentrant */
9256     }
9257    
9258     /* output mangled stuff ... */
9259     if (c == '\0')
9260     --q;
9261     eptr = p;
9262     elen = q - p;
9263    
9264     /* ... right here, because formatting flags should not apply */
9265     SvGROW(sv, SvCUR(sv) + elen + 1);
9266     p = SvEND(sv);
9267     Copy(eptr, p, elen, char);
9268     p += elen;
9269     *p = '\0';
9270     SvCUR(sv) = p - SvPVX(sv);
9271     svix = osvix;
9272     continue; /* not "break" */
9273     }
9274    
9275     /* calculate width before utf8_upgrade changes it */
9276     have = esignlen + zeros + elen;
9277    
9278     if (is_utf8 != has_utf8) {
9279     if (is_utf8) {
9280     if (SvCUR(sv))
9281     sv_utf8_upgrade(sv);
9282     }
9283     else {
9284     SV *nsv = sv_2mortal(newSVpvn(eptr, elen));
9285     sv_utf8_upgrade(nsv);
9286     eptr = SvPVX(nsv);
9287     elen = SvCUR(nsv);
9288     }
9289     SvGROW(sv, SvCUR(sv) + elen + 1);
9290     p = SvEND(sv);
9291     *p = '\0';
9292     }
9293     /* Use memchr() instead of strchr(), as eptr is not guaranteed */
9294     /* to point to a null-terminated string. */
9295     if (left && ckWARN(WARN_PRINTF) && memchr(eptr, '\n', elen) &&
9296     (PL_op->op_type == OP_PRTF || PL_op->op_type == OP_SPRINTF))
9297     Perl_warner(aTHX_ packWARN(WARN_PRINTF),
9298     "Newline in left-justified string for %sprintf",
9299     (PL_op->op_type == OP_PRTF) ? "" : "s");
9300    
9301     need = (have > width ? have : width);
9302     gap = need - have;
9303    
9304     SvGROW(sv, SvCUR(sv) + need + dotstrlen + 1);
9305     p = SvEND(sv);
9306     if (esignlen && fill == '0') {
9307     for (i = 0; i < (int)esignlen; i++)
9308     *p++ = esignbuf[i];
9309     }
9310     if (gap && !left) {
9311     memset(p, fill, gap);
9312     p += gap;
9313     }
9314     if (esignlen && fill != '0') {
9315     for (i = 0; i < (int)esignlen; i++)
9316     *p++ = esignbuf[i];
9317     }
9318     if (zeros) {
9319     for (i = zeros; i; i--)
9320     *p++ = '0';
9321     }
9322     if (elen) {
9323     Copy(eptr, p, elen, char);
9324     p += elen;
9325     }
9326     if (gap && left) {
9327     memset(p, ' ', gap);
9328     p += gap;
9329     }
9330     if (vectorize) {
9331     if (veclen) {
9332     Copy(dotstr, p, dotstrlen, char);
9333     p += dotstrlen;
9334     }
9335     else
9336     vectorize = FALSE; /* done iterating over vecstr */
9337     }
9338     if (is_utf8)
9339     has_utf8 = TRUE;
9340     if (has_utf8)
9341     SvUTF8_on(sv);
9342     *p = '\0';
9343     SvCUR(sv) = p - SvPVX(sv);
9344     if (vectorize) {
9345     esignlen = 0;
9346     goto vector;
9347     }
9348     }
9349     }
9350    
9351     /* =========================================================================
9352    
9353     =head1 Cloning an interpreter
9354    
9355     All the macros and functions in this section are for the private use of
9356     the main function, perl_clone().
9357    
9358     The foo_dup() functions make an exact copy of an existing foo thinngy.
9359     During the course of a cloning, a hash table is used to map old addresses
9360     to new addresses. The table is created and manipulated with the
9361     ptr_table_* functions.
9362    
9363     =cut
9364    
9365     ============================================================================*/
9366    
9367    
9368     #if defined(USE_ITHREADS)
9369    
9370     #if defined(USE_5005THREADS)
9371     # include "error: USE_5005THREADS and USE_ITHREADS are incompatible"
9372     #endif
9373    
9374     #ifndef GpREFCNT_inc
9375     # define GpREFCNT_inc(gp) ((gp) ? (++(gp)->gp_refcnt, (gp)) : (GP*)NULL)
9376     #endif
9377    
9378    
9379     #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
9380     #define av_dup(s,t) (AV*)sv_dup((SV*)s,t)
9381     #define av_dup_inc(s,t) (AV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9382     #define hv_dup(s,t) (HV*)sv_dup((SV*)s,t)
9383     #define hv_dup_inc(s,t) (HV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9384     #define cv_dup(s,t) (CV*)sv_dup((SV*)s,t)
9385     #define cv_dup_inc(s,t) (CV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9386     #define io_dup(s,t) (IO*)sv_dup((SV*)s,t)
9387     #define io_dup_inc(s,t) (IO*)SvREFCNT_inc(sv_dup((SV*)s,t))
9388     #define gv_dup(s,t) (GV*)sv_dup((SV*)s,t)
9389     #define gv_dup_inc(s,t) (GV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9390     #define SAVEPV(p) (p ? savepv(p) : Nullch)
9391     #define SAVEPVN(p,n) (p ? savepvn(p,n) : Nullch)
9392    
9393    
9394     /* Duplicate a regexp. Required reading: pregcomp() and pregfree() in
9395     regcomp.c. AMS 20010712 */
9396    
9397     REGEXP *
9398     Perl_re_dup(pTHX_ REGEXP *r, CLONE_PARAMS *param)
9399     {
9400     REGEXP *ret;
9401     int i, len, npar;
9402     struct reg_substr_datum *s;
9403    
9404     if (!r)
9405     return (REGEXP *)NULL;
9406    
9407     if ((ret = (REGEXP *)ptr_table_fetch(PL_ptr_table, r)))
9408     return ret;
9409    
9410     len = r->offsets[0];
9411     npar = r->nparens+1;
9412    
9413     Newc(0, ret, sizeof(regexp) + (len+1)*sizeof(regnode), char, regexp);
9414     Copy(r->program, ret->program, len+1, regnode);
9415    
9416     New(0, ret->startp, npar, I32);
9417     Copy(r->startp, ret->startp, npar, I32);
9418     New(0, ret->endp, npar, I32);
9419     Copy(r->startp, ret->startp, npar, I32);
9420    
9421     New(0, ret->substrs, 1, struct reg_substr_data);
9422     for (s = ret->substrs->data, i = 0; i < 3; i++, s++) {
9423     s->min_offset = r->substrs->data[i].min_offset;
9424     s->max_offset = r->substrs->data[i].max_offset;
9425     s->substr = sv_dup_inc(r->substrs->data[i].substr, param);
9426     s->utf8_substr = sv_dup_inc(r->substrs->data[i].utf8_substr, param);
9427     }
9428    
9429     ret->regstclass = NULL;
9430     if (r->data) {
9431     struct reg_data *d;
9432     int count = r->data->count;
9433    
9434     Newc(0, d, sizeof(struct reg_data) + count*sizeof(void *),
9435     char, struct reg_data);
9436     New(0, d->what, count, U8);
9437    
9438     d->count = count;
9439     for (i = 0; i < count; i++) {
9440     d->what[i] = r->data->what[i];
9441     switch (d->what[i]) {
9442     case 's':
9443     d->data[i] = sv_dup_inc((SV *)r->data->data[i], param);
9444     break;
9445     case 'p':
9446     d->data[i] = av_dup_inc((AV *)r->data->data[i], param);
9447     break;
9448     case 'f':
9449     /* This is cheating. */
9450     New(0, d->data[i], 1, struct regnode_charclass_class);
9451     StructCopy(r->data->data[i], d->data[i],
9452     struct regnode_charclass_class);
9453     ret->regstclass = (regnode*)d->data[i];
9454     break;
9455     case 'o':
9456     /* Compiled op trees are readonly, and can thus be
9457     shared without duplication. */
9458     OP_REFCNT_LOCK;
9459     d->data[i] = (void*)OpREFCNT_inc((OP*)r->data->data[i]);
9460     OP_REFCNT_UNLOCK;
9461     break;
9462     case 'n':
9463     d->data[i] = r->data->data[i];
9464     break;
9465     }
9466     }
9467    
9468     ret->data = d;
9469     }
9470     else
9471     ret->data = NULL;
9472    
9473     New(0, ret->offsets, 2*len+1, U32);
9474     Copy(r->offsets, ret->offsets, 2*len+1, U32);
9475    
9476     ret->precomp = SAVEPVN(r->precomp, r->prelen);
9477     ret->refcnt = r->refcnt;
9478     ret->minlen = r->minlen;
9479     ret->prelen = r->prelen;
9480     ret->nparens = r->nparens;
9481     ret->lastparen = r->lastparen;
9482     ret->lastcloseparen = r->lastcloseparen;
9483     ret->reganch = r->reganch;
9484    
9485     ret->sublen = r->sublen;
9486    
9487     if (RX_MATCH_COPIED(ret))
9488     ret->subbeg = SAVEPVN(r->subbeg, r->sublen);
9489     else
9490     ret->subbeg = Nullch;
9491    
9492     ptr_table_store(PL_ptr_table, r, ret);
9493     return ret;
9494     }
9495    
9496     /* duplicate a file handle */
9497    
9498     PerlIO *
9499     Perl_fp_dup(pTHX_ PerlIO *fp, char type, CLONE_PARAMS *param)
9500     {
9501     PerlIO *ret;
9502     if (!fp)
9503     return (PerlIO*)NULL;
9504    
9505     /* look for it in the table first */
9506     ret = (PerlIO*)ptr_table_fetch(PL_ptr_table, fp);
9507     if (ret)
9508     return ret;
9509    
9510     /* create anew and remember what it is */
9511     ret = PerlIO_fdupopen(aTHX_ fp, param, PERLIO_DUP_CLONE);
9512     ptr_table_store(PL_ptr_table, fp, ret);
9513     return ret;
9514     }
9515    
9516     /* duplicate a directory handle */
9517    
9518     DIR *
9519     Perl_dirp_dup(pTHX_ DIR *dp)
9520     {
9521     if (!dp)
9522     return (DIR*)NULL;
9523     /* XXX TODO */
9524     return dp;
9525     }
9526    
9527     /* duplicate a typeglob */
9528    
9529     GP *
9530     Perl_gp_dup(pTHX_ GP *gp, CLONE_PARAMS* param)
9531     {
9532     GP *ret;
9533     if (!gp)
9534     return (GP*)NULL;
9535     /* look for it in the table first */
9536     ret = (GP*)ptr_table_fetch(PL_ptr_table, gp);
9537     if (ret)
9538     return ret;
9539    
9540     /* create anew and remember what it is */
9541     Newz(0, ret, 1, GP);
9542     ptr_table_store(PL_ptr_table, gp, ret);
9543    
9544     /* clone */
9545     ret->gp_refcnt = 0; /* must be before any other dups! */
9546     ret->gp_sv = sv_dup_inc(gp->gp_sv, param);
9547     ret->gp_io = io_dup_inc(gp->gp_io, param);
9548     ret->gp_form = cv_dup_inc(gp->gp_form, param);
9549     ret->gp_av = av_dup_inc(gp->gp_av, param);
9550     ret->gp_hv = hv_dup_inc(gp->gp_hv, param);
9551     ret->gp_egv = gv_dup(gp->gp_egv, param);/* GvEGV is not refcounted */
9552     ret->gp_cv = cv_dup_inc(gp->gp_cv, param);
9553     ret->gp_cvgen = gp->gp_cvgen;
9554     ret->gp_flags = gp->gp_flags;
9555     ret->gp_line = gp->gp_line;
9556     ret->gp_file = gp->gp_file; /* points to COP.cop_file */
9557     return ret;
9558     }
9559    
9560     /* duplicate a chain of magic */
9561    
9562     MAGIC *
9563     Perl_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS* param)
9564     {
9565     MAGIC *mgprev = (MAGIC*)NULL;
9566     MAGIC *mgret;
9567     if (!mg)
9568     return (MAGIC*)NULL;
9569     /* look for it in the table first */
9570     mgret = (MAGIC*)ptr_table_fetch(PL_ptr_table, mg);
9571     if (mgret)
9572     return mgret;
9573    
9574     for (; mg; mg = mg->mg_moremagic) {
9575     MAGIC *nmg;
9576     Newz(0, nmg, 1, MAGIC);
9577     if (mgprev)
9578     mgprev->mg_moremagic = nmg;
9579     else
9580     mgret = nmg;
9581     nmg->mg_virtual = mg->mg_virtual; /* XXX copy dynamic vtable? */
9582     nmg->mg_private = mg->mg_private;
9583     nmg->mg_type = mg->mg_type;
9584     nmg->mg_flags = mg->mg_flags;
9585     if (mg->mg_type == PERL_MAGIC_qr) {
9586     nmg->mg_obj = (SV*)re_dup((REGEXP*)mg->mg_obj, param);
9587     }
9588     else if(mg->mg_type == PERL_MAGIC_backref) {
9589     AV *av = (AV*) mg->mg_obj;
9590     SV **svp;
9591     I32 i;
9592     SvREFCNT_inc(nmg->mg_obj = (SV*)newAV());
9593     svp = AvARRAY(av);
9594     for (i = AvFILLp(av); i >= 0; i--) {
9595     if (!svp[i]) continue;
9596     av_push((AV*)nmg->mg_obj,sv_dup(svp[i],param));
9597     }
9598     }
9599     else {
9600     nmg->mg_obj = (mg->mg_flags & MGf_REFCOUNTED)
9601     ? sv_dup_inc(mg->mg_obj, param)
9602     : sv_dup(mg->mg_obj, param);
9603     }
9604     nmg->mg_len = mg->mg_len;
9605     nmg->mg_ptr = mg->mg_ptr; /* XXX random ptr? */
9606     if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) {
9607     if (mg->mg_len > 0) {
9608     nmg->mg_ptr = SAVEPVN(mg->mg_ptr, mg->mg_len);
9609     if (mg->mg_type == PERL_MAGIC_overload_table &&
9610     AMT_AMAGIC((AMT*)mg->mg_ptr))
9611     {
9612     AMT *amtp = (AMT*)mg->mg_ptr;
9613     AMT *namtp = (AMT*)nmg->mg_ptr;
9614     I32 i;
9615     for (i = 1; i < NofAMmeth; i++) {
9616     namtp->table[i] = cv_dup_inc(amtp->table[i], param);
9617     }
9618     }
9619     }
9620     else if (mg->mg_len == HEf_SVKEY)
9621     nmg->mg_ptr = (char*)sv_dup_inc((SV*)mg->mg_ptr, param);
9622     }
9623     if ((mg->mg_flags & MGf_DUP) && mg->mg_virtual && mg->mg_virtual->svt_dup) {
9624     CALL_FPTR(nmg->mg_virtual->svt_dup)(aTHX_ nmg, param);
9625     }
9626     mgprev = nmg;
9627     }
9628     return mgret;
9629     }
9630    
9631     /* create a new pointer-mapping table */
9632    
9633     PTR_TBL_t *
9634     Perl_ptr_table_new(pTHX)
9635     {
9636     PTR_TBL_t *tbl;
9637     Newz(0, tbl, 1, PTR_TBL_t);
9638     tbl->tbl_max = 511;
9639     tbl->tbl_items = 0;
9640     Newz(0, tbl->tbl_ary, tbl->tbl_max + 1, PTR_TBL_ENT_t*);
9641     return tbl;
9642     }
9643    
9644     #if (PTRSIZE == 8)
9645     # define PTR_TABLE_HASH(ptr) (PTR2UV(ptr) >> 3)
9646     #else
9647     # define PTR_TABLE_HASH(ptr) (PTR2UV(ptr) >> 2)
9648     #endif
9649    
9650    
9651    
9652     STATIC void
9653     S_more_pte(pTHX)
9654     {
9655     register struct ptr_tbl_ent* pte;
9656     register struct ptr_tbl_ent* pteend;
9657     XPV *ptr;
9658     New(54, ptr, PERL_ARENA_SIZE/sizeof(XPV), XPV);
9659     ptr->xpv_pv = (char*)PL_pte_arenaroot;
9660     PL_pte_arenaroot = ptr;
9661    
9662     pte = (struct ptr_tbl_ent*)ptr;
9663     pteend = &pte[PERL_ARENA_SIZE / sizeof(struct ptr_tbl_ent) - 1];
9664     PL_pte_root = ++pte;
9665     while (pte < pteend) {
9666     pte->next = pte + 1;
9667     pte++;
9668     }
9669     pte->next = 0;
9670     }
9671    
9672     STATIC struct ptr_tbl_ent*
9673     S_new_pte(pTHX)
9674     {
9675     struct ptr_tbl_ent* pte;
9676     if (!PL_pte_root)
9677     S_more_pte(aTHX);
9678     pte = PL_pte_root;
9679     PL_pte_root = pte->next;
9680     return pte;
9681     }
9682    
9683     STATIC void
9684     S_del_pte(pTHX_ struct ptr_tbl_ent*p)
9685     {
9686     p->next = PL_pte_root;
9687     PL_pte_root = p;
9688     }
9689    
9690     /* map an existing pointer using a table */
9691    
9692     void *
9693     Perl_ptr_table_fetch(pTHX_ PTR_TBL_t *tbl, void *sv)
9694     {
9695     PTR_TBL_ENT_t *tblent;
9696     UV hash = PTR_TABLE_HASH(sv);
9697     assert(tbl);
9698     tblent = tbl->tbl_ary[hash & tbl->tbl_max];
9699     for (; tblent; tblent = tblent->next) {
9700     if (tblent->oldval == sv)
9701     return tblent->newval;
9702     }
9703     return (void*)NULL;
9704     }
9705    
9706     /* add a new entry to a pointer-mapping table */
9707    
9708     void
9709     Perl_ptr_table_store(pTHX_ PTR_TBL_t *tbl, void *oldv, void *newv)
9710     {
9711     PTR_TBL_ENT_t *tblent, **otblent;
9712     /* XXX this may be pessimal on platforms where pointers aren't good
9713     * hash values e.g. if they grow faster in the most significant
9714     * bits */
9715     UV hash = PTR_TABLE_HASH(oldv);
9716     bool empty = 1;
9717    
9718     assert(tbl);
9719     otblent = &tbl->tbl_ary[hash & tbl->tbl_max];
9720     for (tblent = *otblent; tblent; empty=0, tblent = tblent->next) {
9721     if (tblent->oldval == oldv) {
9722     tblent->newval = newv;
9723     return;
9724     }
9725     }
9726     tblent = S_new_pte(aTHX);
9727     tblent->oldval = oldv;
9728     tblent->newval = newv;
9729     tblent->next = *otblent;
9730     *otblent = tblent;
9731     tbl->tbl_items++;
9732     if (!empty && tbl->tbl_items > tbl->tbl_max)
9733     ptr_table_split(tbl);
9734     }
9735    
9736     /* double the hash bucket size of an existing ptr table */
9737    
9738     void
9739     Perl_ptr_table_split(pTHX_ PTR_TBL_t *tbl)
9740     {
9741     PTR_TBL_ENT_t **ary = tbl->tbl_ary;
9742     UV oldsize = tbl->tbl_max + 1;
9743     UV newsize = oldsize * 2;
9744     UV i;
9745    
9746     Renew(ary, newsize, PTR_TBL_ENT_t*);
9747     Zero(&ary[oldsize], newsize-oldsize, PTR_TBL_ENT_t*);
9748     tbl->tbl_max = --newsize;
9749     tbl->tbl_ary = ary;
9750     for (i=0; i < oldsize; i++, ary++) {
9751     PTR_TBL_ENT_t **curentp, **entp, *ent;
9752     if (!*ary)
9753     continue;
9754     curentp = ary + oldsize;
9755     for (entp = ary, ent = *ary; ent; ent = *entp) {
9756     if ((newsize & PTR_TABLE_HASH(ent->oldval)) != i) {
9757     *entp = ent->next;
9758     ent->next = *curentp;
9759     *curentp = ent;
9760     continue;
9761     }
9762     else
9763     entp = &ent->next;
9764     }
9765     }
9766     }
9767    
9768     /* remove all the entries from a ptr table */
9769    
9770     void
9771     Perl_ptr_table_clear(pTHX_ PTR_TBL_t *tbl)
9772     {
9773     register PTR_TBL_ENT_t **array;
9774     register PTR_TBL_ENT_t *entry;
9775     register PTR_TBL_ENT_t *oentry = Null(PTR_TBL_ENT_t*);
9776     UV riter = 0;
9777     UV max;
9778    
9779     if (!tbl || !tbl->tbl_items) {
9780     return;
9781     }
9782    
9783     array = tbl->tbl_ary;
9784     entry = array[0];
9785     max = tbl->tbl_max;
9786    
9787     for (;;) {
9788     if (entry) {
9789     oentry = entry;
9790     entry = entry->next;
9791     S_del_pte(aTHX_ oentry);
9792     }
9793     if (!entry) {
9794     if (++riter > max) {
9795     break;
9796     }
9797     entry = array[riter];
9798     }
9799     }
9800    
9801     tbl->tbl_items = 0;
9802     }
9803    
9804     /* clear and free a ptr table */
9805    
9806     void
9807     Perl_ptr_table_free(pTHX_ PTR_TBL_t *tbl)
9808     {
9809     if (!tbl) {
9810     return;
9811     }
9812     ptr_table_clear(tbl);
9813     Safefree(tbl->tbl_ary);
9814     Safefree(tbl);
9815     }
9816    
9817     #ifdef DEBUGGING
9818     char *PL_watch_pvx;
9819     #endif
9820    
9821     /* attempt to make everything in the typeglob readonly */
9822    
9823     STATIC SV *
9824     S_gv_share(pTHX_ SV *sstr, CLONE_PARAMS *param)
9825     {
9826     GV *gv = (GV*)sstr;
9827     SV *sv = &param->proto_perl->Isv_no; /* just need SvREADONLY-ness */
9828    
9829     if (GvIO(gv) || GvFORM(gv)) {
9830     GvUNIQUE_off(gv); /* GvIOs cannot be shared. nor can GvFORMs */
9831     }
9832     else if (!GvCV(gv)) {
9833     GvCV(gv) = (CV*)sv;
9834     }
9835     else {
9836     /* CvPADLISTs cannot be shared */
9837     if (!SvREADONLY(GvCV(gv)) && !CvXSUB(GvCV(gv))) {
9838     GvUNIQUE_off(gv);
9839     }
9840     }
9841    
9842     if (!GvUNIQUE(gv)) {
9843     #if 0
9844     PerlIO_printf(Perl_debug_log, "gv_share: unable to share %s::%s\n",
9845     HvNAME(GvSTASH(gv)), GvNAME(gv));
9846     #endif
9847     return Nullsv;
9848     }
9849    
9850     /*
9851     * write attempts will die with
9852     * "Modification of a read-only value attempted"
9853     */
9854     if (!GvSV(gv)) {
9855     GvSV(gv) = sv;
9856     }
9857     else {
9858     SvREADONLY_on(GvSV(gv));
9859     }
9860    
9861     if (!GvAV(gv)) {
9862     GvAV(gv) = (AV*)sv;
9863     }
9864     else {
9865     SvREADONLY_on(GvAV(gv));
9866     }
9867    
9868     if (!GvHV(gv)) {
9869     GvHV(gv) = (HV*)sv;
9870     }
9871     else {
9872     SvREADONLY_on(GvHV(gv));
9873     }
9874    
9875     return sstr; /* he_dup() will SvREFCNT_inc() */
9876     }
9877    
9878     /* duplicate an SV of any type (including AV, HV etc) */
9879    
9880     void
9881     Perl_rvpv_dup(pTHX_ SV *dstr, SV *sstr, CLONE_PARAMS* param)
9882     {
9883     if (SvROK(sstr)) {
9884     SvRV(dstr) = SvWEAKREF(sstr)
9885     ? sv_dup(SvRV(sstr), param)
9886     : sv_dup_inc(SvRV(sstr), param);
9887     }
9888     else if (SvPVX(sstr)) {
9889     /* Has something there */
9890     if (SvLEN(sstr)) {
9891     /* Normal PV - clone whole allocated space */
9892     SvPVX(dstr) = SAVEPVN(SvPVX(sstr), SvLEN(sstr)-1);
9893     }
9894     else {
9895     /* Special case - not normally malloced for some reason */
9896     if (SvREADONLY(sstr) && SvFAKE(sstr)) {
9897     /* A "shared" PV - clone it as unshared string */
9898     if(SvPADTMP(sstr)) {
9899     /* However, some of them live in the pad
9900     and they should not have these flags
9901     turned off */
9902    
9903     SvPVX(dstr) = sharepvn(SvPVX(sstr), SvCUR(sstr),
9904     SvUVX(sstr));
9905     SvUVX(dstr) = SvUVX(sstr);
9906     } else {
9907    
9908     SvPVX(dstr) = SAVEPVN(SvPVX(sstr), SvCUR(sstr));
9909     SvFAKE_off(dstr);
9910     SvREADONLY_off(dstr);
9911     }
9912     }
9913     else {
9914     /* Some other special case - random pointer */
9915     SvPVX(dstr) = SvPVX(sstr);
9916     }
9917     }
9918     }
9919     else {
9920     /* Copy the Null */
9921     SvPVX(dstr) = SvPVX(sstr);
9922     }
9923     }
9924    
9925     SV *
9926     Perl_sv_dup(pTHX_ SV *sstr, CLONE_PARAMS* param)
9927     {
9928     SV *dstr;
9929    
9930     if (!sstr || SvTYPE(sstr) == SVTYPEMASK)
9931     return Nullsv;
9932     /* look for it in the table first */
9933     dstr = (SV*)ptr_table_fetch(PL_ptr_table, sstr);
9934     if (dstr)
9935     return dstr;
9936    
9937     if(param->flags & CLONEf_JOIN_IN) {
9938     /** We are joining here so we don't want do clone
9939     something that is bad **/
9940    
9941     if(SvTYPE(sstr) == SVt_PVHV &&
9942     HvNAME(sstr)) {
9943     /** don't clone stashes if they already exist **/
9944     HV* old_stash = gv_stashpv(HvNAME(sstr),0);
9945     return (SV*) old_stash;
9946     }
9947     }
9948    
9949     /* create anew and remember what it is */
9950     new_SV(dstr);
9951     ptr_table_store(PL_ptr_table, sstr, dstr);
9952    
9953     /* clone */
9954     SvFLAGS(dstr) = SvFLAGS(sstr);
9955     SvFLAGS(dstr) &= ~SVf_OOK; /* don't propagate OOK hack */
9956     SvREFCNT(dstr) = 0; /* must be before any other dups! */
9957    
9958     #ifdef DEBUGGING
9959     if (SvANY(sstr) && PL_watch_pvx && SvPVX(sstr) == PL_watch_pvx)
9960     PerlIO_printf(Perl_debug_log, "watch at %p hit, found string \"%s\"\n",
9961     PL_watch_pvx, SvPVX(sstr));
9962     #endif
9963    
9964     /* don't clone objects whose class has asked us not to */
9965     if (SvOBJECT(sstr) && ! (SvFLAGS(SvSTASH(sstr)) & SVphv_CLONEABLE)) {
9966     SvFLAGS(dstr) &= ~SVTYPEMASK;
9967     SvOBJECT_off(dstr);
9968     return dstr;
9969     }
9970    
9971     switch (SvTYPE(sstr)) {
9972     case SVt_NULL:
9973     SvANY(dstr) = NULL;
9974     break;
9975     case SVt_IV:
9976     SvANY(dstr) = new_XIV();
9977     SvIVX(dstr) = SvIVX(sstr);
9978     break;
9979     case SVt_NV:
9980     SvANY(dstr) = new_XNV();
9981     SvNVX(dstr) = SvNVX(sstr);
9982     break;
9983     case SVt_RV:
9984     SvANY(dstr) = new_XRV();
9985     Perl_rvpv_dup(aTHX_ dstr, sstr, param);
9986     break;
9987     case SVt_PV:
9988     SvANY(dstr) = new_XPV();
9989     SvCUR(dstr) = SvCUR(sstr);
9990     SvLEN(dstr) = SvLEN(sstr);
9991     Perl_rvpv_dup(aTHX_ dstr, sstr, param);
9992     break;
9993     case SVt_PVIV:
9994     SvANY(dstr) = new_XPVIV();
9995     SvCUR(dstr) = SvCUR(sstr);
9996     SvLEN(dstr) = SvLEN(sstr);
9997     SvIVX(dstr) = SvIVX(sstr);
9998     Perl_rvpv_dup(aTHX_ dstr, sstr, param);
9999     break;
10000     case SVt_PVNV:
10001     SvANY(dstr) = new_XPVNV();
10002     SvCUR(dstr) = SvCUR(sstr);
10003     SvLEN(dstr) = SvLEN(sstr);
10004     SvIVX(dstr) = SvIVX(sstr);
10005     SvNVX(dstr) = SvNVX(sstr);
10006     Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10007     break;
10008     case SVt_PVMG:
10009     SvANY(dstr) = new_XPVMG();
10010     SvCUR(dstr) = SvCUR(sstr);
10011     SvLEN(dstr) = SvLEN(sstr);
10012     SvIVX(dstr) = SvIVX(sstr);
10013     SvNVX(dstr) = SvNVX(sstr);
10014     SvMAGIC(dstr) = mg_dup(SvMAGIC(sstr), param);
10015     SvSTASH(dstr) = hv_dup_inc(SvSTASH(sstr), param);
10016     Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10017     break;
10018     case SVt_PVBM:
10019     SvANY(dstr) = new_XPVBM();
10020     SvCUR(dstr) = SvCUR(sstr);
10021     SvLEN(dstr) = SvLEN(sstr);
10022     SvIVX(dstr) = SvIVX(sstr);
10023     SvNVX(dstr) = SvNVX(sstr);
10024     SvMAGIC(dstr) = mg_dup(SvMAGIC(sstr), param);
10025     SvSTASH(dstr) = hv_dup_inc(SvSTASH(sstr), param);
10026     Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10027     BmRARE(dstr) = BmRARE(sstr);
10028     BmUSEFUL(dstr) = BmUSEFUL(sstr);
10029     BmPREVIOUS(dstr)= BmPREVIOUS(sstr);
10030     break;
10031     case SVt_PVLV:
10032     SvANY(dstr) = new_XPVLV();
10033     SvCUR(dstr) = SvCUR(sstr);
10034     SvLEN(dstr) = SvLEN(sstr);
10035     SvIVX(dstr) = SvIVX(sstr);
10036     SvNVX(dstr) = SvNVX(sstr);
10037     SvMAGIC(dstr) = mg_dup(SvMAGIC(sstr), param);
10038     SvSTASH(dstr) = hv_dup_inc(SvSTASH(sstr), param);
10039     Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10040     LvTARGOFF(dstr) = LvTARGOFF(sstr); /* XXX sometimes holds PMOP* when DEBUGGING */
10041     LvTARGLEN(dstr) = LvTARGLEN(sstr);
10042     if (LvTYPE(sstr) == 't') /* for tie: unrefcnted fake (SV**) */
10043     LvTARG(dstr) = dstr;
10044     else if (LvTYPE(sstr) == 'T') /* for tie: fake HE */
10045     LvTARG(dstr) = (SV*)he_dup((HE*)LvTARG(sstr), 0, param);
10046     else
10047     LvTARG(dstr) = sv_dup_inc(LvTARG(sstr), param);
10048     LvTYPE(dstr) = LvTYPE(sstr);
10049     break;
10050     case SVt_PVGV:
10051     if (GvUNIQUE((GV*)sstr)) {
10052     SV *share;
10053     if ((share = gv_share(sstr, param))) {
10054     del_SV(dstr);
10055     dstr = share;
10056     ptr_table_store(PL_ptr_table, sstr, dstr);
10057     #if 0
10058     PerlIO_printf(Perl_debug_log, "sv_dup: sharing %s::%s\n",
10059     HvNAME(GvSTASH(share)), GvNAME(share));
10060     #endif
10061     break;
10062     }
10063     }
10064     SvANY(dstr) = new_XPVGV();
10065     SvCUR(dstr) = SvCUR(sstr);
10066     SvLEN(dstr) = SvLEN(sstr);
10067     SvIVX(dstr) = SvIVX(sstr);
10068     SvNVX(dstr) = SvNVX(sstr);
10069     SvMAGIC(dstr) = mg_dup(SvMAGIC(sstr), param);
10070     SvSTASH(dstr) = hv_dup_inc(SvSTASH(sstr), param);
10071     Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10072     GvNAMELEN(dstr) = GvNAMELEN(sstr);
10073     GvNAME(dstr) = SAVEPVN(GvNAME(sstr), GvNAMELEN(sstr));
10074     GvSTASH(dstr) = hv_dup_inc(GvSTASH(sstr), param);
10075     GvFLAGS(dstr) = GvFLAGS(sstr);
10076     GvGP(dstr) = gp_dup(GvGP(sstr), param);
10077     (void)GpREFCNT_inc(GvGP(dstr));
10078     break;
10079     case SVt_PVIO:
10080     SvANY(dstr) = new_XPVIO();
10081     SvCUR(dstr) = SvCUR(sstr);
10082     SvLEN(dstr) = SvLEN(sstr);
10083     SvIVX(dstr) = SvIVX(sstr);
10084     SvNVX(dstr) = SvNVX(sstr);
10085     SvMAGIC(dstr) = mg_dup(SvMAGIC(sstr), param);
10086     SvSTASH(dstr) = hv_dup_inc(SvSTASH(sstr), param);
10087     Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10088     IoIFP(dstr) = fp_dup(IoIFP(sstr), IoTYPE(sstr), param);
10089     if (IoOFP(sstr) == IoIFP(sstr))
10090     IoOFP(dstr) = IoIFP(dstr);
10091     else
10092     IoOFP(dstr) = fp_dup(IoOFP(sstr), IoTYPE(sstr), param);
10093     /* PL_rsfp_filters entries have fake IoDIRP() */
10094     if (IoDIRP(sstr) && !(IoFLAGS(sstr) & IOf_FAKE_DIRP))
10095     IoDIRP(dstr) = dirp_dup(IoDIRP(sstr));
10096     else
10097     IoDIRP(dstr) = IoDIRP(sstr);
10098     IoLINES(dstr) = IoLINES(sstr);
10099     IoPAGE(dstr) = IoPAGE(sstr);
10100     IoPAGE_LEN(dstr) = IoPAGE_LEN(sstr);
10101     IoLINES_LEFT(dstr) = IoLINES_LEFT(sstr);
10102     if(IoFLAGS(sstr) & IOf_FAKE_DIRP) {
10103     /* I have no idea why fake dirp (rsfps)
10104     should be treaded differently but otherwise
10105     we end up with leaks -- sky*/
10106     IoTOP_GV(dstr) = gv_dup_inc(IoTOP_GV(sstr), param);
10107     IoFMT_GV(dstr) = gv_dup_inc(IoFMT_GV(sstr), param);
10108     IoBOTTOM_GV(dstr) = gv_dup_inc(IoBOTTOM_GV(sstr), param);
10109     } else {
10110     IoTOP_GV(dstr) = gv_dup(IoTOP_GV(sstr), param);
10111     IoFMT_GV(dstr) = gv_dup(IoFMT_GV(sstr), param);
10112     IoBOTTOM_GV(dstr) = gv_dup(IoBOTTOM_GV(sstr), param);
10113     }
10114     IoTOP_NAME(dstr) = SAVEPV(IoTOP_NAME(sstr));
10115     IoFMT_NAME(dstr) = SAVEPV(IoFMT_NAME(sstr));
10116     IoBOTTOM_NAME(dstr) = SAVEPV(IoBOTTOM_NAME(sstr));
10117     IoSUBPROCESS(dstr) = IoSUBPROCESS(sstr);
10118     IoTYPE(dstr) = IoTYPE(sstr);
10119     IoFLAGS(dstr) = IoFLAGS(sstr);
10120     break;
10121     case SVt_PVAV:
10122     SvANY(dstr) = new_XPVAV();
10123     SvCUR(dstr) = SvCUR(sstr);
10124     SvLEN(dstr) = SvLEN(sstr);
10125     SvIVX(dstr) = SvIVX(sstr);
10126     SvNVX(dstr) = SvNVX(sstr);
10127     SvMAGIC(dstr) = mg_dup(SvMAGIC(sstr), param);
10128     SvSTASH(dstr) = hv_dup_inc(SvSTASH(sstr), param);
10129     AvARYLEN((AV*)dstr) = sv_dup_inc(AvARYLEN((AV*)sstr), param);
10130     AvFLAGS((AV*)dstr) = AvFLAGS((AV*)sstr);
10131     if (AvARRAY((AV*)sstr)) {
10132     SV **dst_ary, **src_ary;
10133     SSize_t items = AvFILLp((AV*)sstr) + 1;
10134    
10135     src_ary = AvARRAY((AV*)sstr);
10136     Newz(0, dst_ary, AvMAX((AV*)sstr)+1, SV*);
10137     ptr_table_store(PL_ptr_table, src_ary, dst_ary);
10138     SvPVX(dstr) = (char*)dst_ary;
10139     AvALLOC((AV*)dstr) = dst_ary;
10140     if (AvREAL((AV*)sstr)) {
10141     while (items-- > 0)
10142     *dst_ary++ = sv_dup_inc(*src_ary++, param);
10143     }
10144     else {
10145     while (items-- > 0)
10146     *dst_ary++ = sv_dup(*src_ary++, param);
10147     }
10148     items = AvMAX((AV*)sstr) - AvFILLp((AV*)sstr);
10149     while (items-- > 0) {
10150     *dst_ary++ = &PL_sv_undef;
10151     }
10152     }
10153     else {
10154     SvPVX(dstr) = Nullch;
10155     AvALLOC((AV*)dstr) = (SV**)NULL;
10156     }
10157     break;
10158     case SVt_PVHV:
10159     SvANY(dstr) = new_XPVHV();
10160     SvCUR(dstr) = SvCUR(sstr);
10161     SvLEN(dstr) = SvLEN(sstr);
10162     SvIVX(dstr) = SvIVX(sstr);
10163     SvNVX(dstr) = SvNVX(sstr);
10164     SvMAGIC(dstr) = mg_dup(SvMAGIC(sstr), param);
10165     SvSTASH(dstr) = hv_dup_inc(SvSTASH(sstr), param);
10166     HvRITER((HV*)dstr) = HvRITER((HV*)sstr);
10167     if (HvARRAY((HV*)sstr)) {
10168     STRLEN i = 0;
10169     XPVHV *dxhv = (XPVHV*)SvANY(dstr);
10170     XPVHV *sxhv = (XPVHV*)SvANY(sstr);
10171     Newz(0, dxhv->xhv_array,
10172     PERL_HV_ARRAY_ALLOC_BYTES(dxhv->xhv_max+1), char);
10173     while (i <= sxhv->xhv_max) {
10174     ((HE**)dxhv->xhv_array)[i] = he_dup(((HE**)sxhv->xhv_array)[i],
10175     (bool)!!HvSHAREKEYS(sstr),
10176     param);
10177     ++i;
10178     }
10179     dxhv->xhv_eiter = he_dup(sxhv->xhv_eiter,
10180     (bool)!!HvSHAREKEYS(sstr), param);
10181     }
10182     else {
10183     SvPVX(dstr) = Nullch;
10184     HvEITER((HV*)dstr) = (HE*)NULL;
10185     }
10186     HvPMROOT((HV*)dstr) = HvPMROOT((HV*)sstr); /* XXX */
10187     HvNAME((HV*)dstr) = SAVEPV(HvNAME((HV*)sstr));
10188     /* Record stashes for possible cloning in Perl_clone(). */
10189     if(HvNAME((HV*)dstr))
10190     av_push(param->stashes, dstr);
10191     break;
10192     case SVt_PVFM:
10193     SvANY(dstr) = new_XPVFM();
10194     FmLINES(dstr) = FmLINES(sstr);
10195     goto dup_pvcv;
10196     /* NOTREACHED */
10197     case SVt_PVCV:
10198     SvANY(dstr) = new_XPVCV();
10199     dup_pvcv:
10200     SvCUR(dstr) = SvCUR(sstr);
10201     SvLEN(dstr) = SvLEN(sstr);
10202     SvIVX(dstr) = SvIVX(sstr);
10203     SvNVX(dstr) = SvNVX(sstr);
10204     SvMAGIC(dstr) = mg_dup(SvMAGIC(sstr), param);
10205     SvSTASH(dstr) = hv_dup_inc(SvSTASH(sstr), param);
10206     Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10207     CvSTASH(dstr) = hv_dup(CvSTASH(sstr), param); /* NOTE: not refcounted */
10208     CvSTART(dstr) = CvSTART(sstr);
10209     OP_REFCNT_LOCK;
10210     CvROOT(dstr) = OpREFCNT_inc(CvROOT(sstr));
10211     OP_REFCNT_UNLOCK;
10212     CvXSUB(dstr) = CvXSUB(sstr);
10213     CvXSUBANY(dstr) = CvXSUBANY(sstr);
10214     if (CvCONST(sstr)) {
10215     CvXSUBANY(dstr).any_ptr = GvUNIQUE(CvGV(sstr)) ?
10216     SvREFCNT_inc(CvXSUBANY(sstr).any_ptr) :
10217     sv_dup_inc(CvXSUBANY(sstr).any_ptr, param);
10218     }
10219     /* don't dup if copying back - CvGV isn't refcounted, so the
10220     * duped GV may never be freed. A bit of a hack! DAPM */
10221     CvGV(dstr) = (param->flags & CLONEf_JOIN_IN) ?
10222     Nullgv : gv_dup(CvGV(sstr), param) ;
10223     if (param->flags & CLONEf_COPY_STACKS) {
10224     CvDEPTH(dstr) = CvDEPTH(sstr);
10225     } else {
10226     CvDEPTH(dstr) = 0;
10227     }
10228     PAD_DUP(CvPADLIST(dstr), CvPADLIST(sstr), param);
10229     CvOUTSIDE_SEQ(dstr) = CvOUTSIDE_SEQ(sstr);
10230     CvOUTSIDE(dstr) =
10231     CvWEAKOUTSIDE(sstr)
10232     ? cv_dup( CvOUTSIDE(sstr), param)
10233     : cv_dup_inc(CvOUTSIDE(sstr), param);
10234     CvFLAGS(dstr) = CvFLAGS(sstr);
10235     CvFILE(dstr) = CvXSUB(sstr) ? CvFILE(sstr) : SAVEPV(CvFILE(sstr));
10236     break;
10237     default:
10238     Perl_croak(aTHX_ "Bizarre SvTYPE [%" IVdf "]", (IV)SvTYPE(sstr));
10239     break;
10240     }
10241    
10242     if (SvOBJECT(dstr) && SvTYPE(dstr) != SVt_PVIO)
10243     ++PL_sv_objcount;
10244    
10245     return dstr;
10246     }
10247    
10248     /* duplicate a context */
10249    
10250     PERL_CONTEXT *
10251     Perl_cx_dup(pTHX_ PERL_CONTEXT *cxs, I32 ix, I32 max, CLONE_PARAMS* param)
10252     {
10253     PERL_CONTEXT *ncxs;
10254    
10255     if (!cxs)
10256     return (PERL_CONTEXT*)NULL;
10257    
10258     /* look for it in the table first */
10259     ncxs = (PERL_CONTEXT*)ptr_table_fetch(PL_ptr_table, cxs);
10260     if (ncxs)
10261     return ncxs;
10262    
10263     /* create anew and remember what it is */
10264     Newz(56, ncxs, max + 1, PERL_CONTEXT);
10265     ptr_table_store(PL_ptr_table, cxs, ncxs);
10266    
10267     while (ix >= 0) {
10268     PERL_CONTEXT *cx = &cxs[ix];
10269     PERL_CONTEXT *ncx = &ncxs[ix];
10270     ncx->cx_type = cx->cx_type;
10271     if (CxTYPE(cx) == CXt_SUBST) {
10272     Perl_croak(aTHX_ "Cloning substitution context is unimplemented");
10273     }
10274     else {
10275     ncx->blk_oldsp = cx->blk_oldsp;
10276     ncx->blk_oldcop = cx->blk_oldcop;
10277     ncx->blk_oldretsp = cx->blk_oldretsp;
10278     ncx->blk_oldmarksp = cx->blk_oldmarksp;
10279     ncx->blk_oldscopesp = cx->blk_oldscopesp;
10280     ncx->blk_oldpm = cx->blk_oldpm;
10281     ncx->blk_gimme = cx->blk_gimme;
10282     switch (CxTYPE(cx)) {
10283     case CXt_SUB:
10284     ncx->blk_sub.cv = (cx->blk_sub.olddepth == 0
10285     ? cv_dup_inc(cx->blk_sub.cv, param)
10286     : cv_dup(cx->blk_sub.cv,param));
10287     ncx->blk_sub.argarray = (cx->blk_sub.hasargs
10288     ? av_dup_inc(cx->blk_sub.argarray, param)
10289     : Nullav);
10290     ncx->blk_sub.savearray = av_dup_inc(cx->blk_sub.savearray, param);
10291     ncx->blk_sub.olddepth = cx->blk_sub.olddepth;
10292     ncx->blk_sub.hasargs = cx->blk_sub.hasargs;
10293     ncx->blk_sub.lval = cx->blk_sub.lval;
10294     break;
10295     case CXt_EVAL:
10296     ncx->blk_eval.old_in_eval = cx->blk_eval.old_in_eval;
10297     ncx->blk_eval.old_op_type = cx->blk_eval.old_op_type;
10298     ncx->blk_eval.old_namesv = sv_dup_inc(cx->blk_eval.old_namesv, param);
10299     ncx->blk_eval.old_eval_root = cx->blk_eval.old_eval_root;
10300     ncx->blk_eval.cur_text = sv_dup(cx->blk_eval.cur_text, param);
10301     break;
10302     case CXt_LOOP:
10303     ncx->blk_loop.label = cx->blk_loop.label;
10304     ncx->blk_loop.resetsp = cx->blk_loop.resetsp;
10305     ncx->blk_loop.redo_op = cx->blk_loop.redo_op;
10306     ncx->blk_loop.next_op = cx->blk_loop.next_op;
10307     ncx->blk_loop.last_op = cx->blk_loop.last_op;
10308     ncx->blk_loop.iterdata = (CxPADLOOP(cx)
10309     ? cx->blk_loop.iterdata
10310     : gv_dup((GV*)cx->blk_loop.iterdata, param));
10311     ncx->blk_loop.oldcomppad
10312     = (PAD*)ptr_table_fetch(PL_ptr_table,
10313     cx->blk_loop.oldcomppad);
10314     ncx->blk_loop.itersave = sv_dup_inc(cx->blk_loop.itersave, param);
10315     ncx->blk_loop.iterlval = sv_dup_inc(cx->blk_loop.iterlval, param);
10316     ncx->blk_loop.iterary = av_dup_inc(cx->blk_loop.iterary, param);
10317     ncx->blk_loop.iterix = cx->blk_loop.iterix;
10318     ncx->blk_loop.itermax = cx->blk_loop.itermax;
10319     break;
10320     case CXt_FORMAT:
10321     ncx->blk_sub.cv = cv_dup(cx->blk_sub.cv, param);
10322     ncx->blk_sub.gv = gv_dup(cx->blk_sub.gv, param);
10323     ncx->blk_sub.dfoutgv = gv_dup_inc(cx->blk_sub.dfoutgv, param);
10324     ncx->blk_sub.hasargs = cx->blk_sub.hasargs;
10325     break;
10326     case CXt_BLOCK:
10327     case CXt_NULL:
10328     break;
10329     }
10330     }
10331     --ix;
10332     }
10333     return ncxs;
10334     }
10335    
10336     /* duplicate a stack info structure */
10337    
10338     PERL_SI *
10339     Perl_si_dup(pTHX_ PERL_SI *si, CLONE_PARAMS* param)
10340     {
10341     PERL_SI *nsi;
10342    
10343     if (!si)
10344     return (PERL_SI*)NULL;
10345    
10346     /* look for it in the table first */
10347     nsi = (PERL_SI*)ptr_table_fetch(PL_ptr_table, si);
10348     if (nsi)
10349     return nsi;
10350    
10351     /* create anew and remember what it is */
10352     Newz(56, nsi, 1, PERL_SI);
10353     ptr_table_store(PL_ptr_table, si, nsi);
10354    
10355     nsi->si_stack = av_dup_inc(si->si_stack, param);
10356     nsi->si_cxix = si->si_cxix;
10357     nsi->si_cxmax = si->si_cxmax;
10358     nsi->si_cxstack = cx_dup(si->si_cxstack, si->si_cxix, si->si_cxmax, param);
10359     nsi->si_type = si->si_type;
10360     nsi->si_prev = si_dup(si->si_prev, param);
10361     nsi->si_next = si_dup(si->si_next, param);
10362     nsi->si_markoff = si->si_markoff;
10363    
10364     return nsi;
10365     }
10366    
10367     #define POPINT(ss,ix) ((ss)[--(ix)].any_i32)
10368     #define TOPINT(ss,ix) ((ss)[ix].any_i32)
10369     #define POPLONG(ss,ix) ((ss)[--(ix)].any_long)
10370     #define TOPLONG(ss,ix) ((ss)[ix].any_long)
10371     #define POPIV(ss,ix) ((ss)[--(ix)].any_iv)
10372     #define TOPIV(ss,ix) ((ss)[ix].any_iv)
10373     #define POPBOOL(ss,ix) ((ss)[--(ix)].any_bool)
10374     #define TOPBOOL(ss,ix) ((ss)[ix].any_bool)
10375     #define POPPTR(ss,ix) ((ss)[--(ix)].any_ptr)
10376     #define TOPPTR(ss,ix) ((ss)[ix].any_ptr)
10377     #define POPDPTR(ss,ix) ((ss)[--(ix)].any_dptr)
10378     #define TOPDPTR(ss,ix) ((ss)[ix].any_dptr)
10379     #define POPDXPTR(ss,ix) ((ss)[--(ix)].any_dxptr)
10380     #define TOPDXPTR(ss,ix) ((ss)[ix].any_dxptr)
10381    
10382     /* XXXXX todo */
10383     #define pv_dup_inc(p) SAVEPV(p)
10384     #define pv_dup(p) SAVEPV(p)
10385     #define svp_dup_inc(p,pp) any_dup(p,pp)
10386    
10387     /* map any object to the new equivent - either something in the
10388     * ptr table, or something in the interpreter structure
10389     */
10390    
10391     void *
10392     Perl_any_dup(pTHX_ void *v, PerlInterpreter *proto_perl)
10393     {
10394     void *ret;
10395    
10396     if (!v)
10397     return (void*)NULL;
10398    
10399     /* look for it in the table first */
10400     ret = ptr_table_fetch(PL_ptr_table, v);
10401     if (ret)
10402     return ret;
10403    
10404     /* see if it is part of the interpreter structure */
10405     if (v >= (void*)proto_perl && v < (void*)(proto_perl+1))
10406     ret = (void*)(((char*)aTHX) + (((char*)v) - (char*)proto_perl));
10407     else {
10408     ret = v;
10409     }
10410    
10411     return ret;
10412     }
10413    
10414     /* duplicate the save stack */
10415    
10416     ANY *
10417     Perl_ss_dup(pTHX_ PerlInterpreter *proto_perl, CLONE_PARAMS* param)
10418     {
10419     ANY *ss = proto_perl->Tsavestack;
10420     I32 ix = proto_perl->Tsavestack_ix;
10421     I32 max = proto_perl->Tsavestack_max;
10422     ANY *nss;
10423     SV *sv;
10424     GV *gv;
10425     AV *av;
10426     HV *hv;
10427     void* ptr;
10428     int intval;
10429     long longval;
10430     GP *gp;
10431     IV iv;
10432     I32 i;
10433     char *c = NULL;
10434     void (*dptr) (void*);
10435     void (*dxptr) (pTHX_ void*);
10436     OP *o;
10437    
10438     Newz(54, nss, max, ANY);
10439    
10440     while (ix > 0) {
10441     i = POPINT(ss,ix);
10442     TOPINT(nss,ix) = i;
10443     switch (i) {
10444     case SAVEt_ITEM: /* normal string */
10445     sv = (SV*)POPPTR(ss,ix);
10446     TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10447     sv = (SV*)POPPTR(ss,ix);
10448     TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10449     break;
10450     case SAVEt_SV: /* scalar reference */
10451     sv = (SV*)POPPTR(ss,ix);
10452     TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10453     gv = (GV*)POPPTR(ss,ix);
10454     TOPPTR(nss,ix) = gv_dup_inc(gv, param);
10455     break;
10456     case SAVEt_GENERIC_PVREF: /* generic char* */
10457     c = (char*)POPPTR(ss,ix);
10458     TOPPTR(nss,ix) = pv_dup(c);
10459     ptr = POPPTR(ss,ix);
10460     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10461     break;
10462     case SAVEt_SHARED_PVREF: /* char* in shared space */
10463     c = (char*)POPPTR(ss,ix);
10464     TOPPTR(nss,ix) = savesharedpv(c);
10465     ptr = POPPTR(ss,ix);
10466     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10467     break;
10468     case SAVEt_GENERIC_SVREF: /* generic sv */
10469     case SAVEt_SVREF: /* scalar reference */
10470     sv = (SV*)POPPTR(ss,ix);
10471     TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10472     ptr = POPPTR(ss,ix);
10473     TOPPTR(nss,ix) = svp_dup_inc((SV**)ptr, proto_perl);/* XXXXX */
10474     break;
10475     case SAVEt_AV: /* array reference */
10476     av = (AV*)POPPTR(ss,ix);
10477     TOPPTR(nss,ix) = av_dup_inc(av, param);
10478     gv = (GV*)POPPTR(ss,ix);
10479     TOPPTR(nss,ix) = gv_dup(gv, param);
10480     break;
10481     case SAVEt_HV: /* hash reference */
10482     hv = (HV*)POPPTR(ss,ix);
10483     TOPPTR(nss,ix) = hv_dup_inc(hv, param);
10484     gv = (GV*)POPPTR(ss,ix);
10485     TOPPTR(nss,ix) = gv_dup(gv, param);
10486     break;
10487     case SAVEt_INT: /* int reference */
10488     ptr = POPPTR(ss,ix);
10489     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10490     intval = (int)POPINT(ss,ix);
10491     TOPINT(nss,ix) = intval;
10492     break;
10493     case SAVEt_LONG: /* long reference */
10494     ptr = POPPTR(ss,ix);
10495     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10496     longval = (long)POPLONG(ss,ix);
10497     TOPLONG(nss,ix) = longval;
10498     break;
10499     case SAVEt_I32: /* I32 reference */
10500     case SAVEt_I16: /* I16 reference */
10501     case SAVEt_I8: /* I8 reference */
10502     ptr = POPPTR(ss,ix);
10503     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10504     i = POPINT(ss,ix);
10505     TOPINT(nss,ix) = i;
10506     break;
10507     case SAVEt_IV: /* IV reference */
10508     ptr = POPPTR(ss,ix);
10509     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10510     iv = POPIV(ss,ix);
10511     TOPIV(nss,ix) = iv;
10512     break;
10513     case SAVEt_SPTR: /* SV* reference */
10514     ptr = POPPTR(ss,ix);
10515     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10516     sv = (SV*)POPPTR(ss,ix);
10517     TOPPTR(nss,ix) = sv_dup(sv, param);
10518     break;
10519     case SAVEt_VPTR: /* random* reference */
10520     ptr = POPPTR(ss,ix);
10521     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10522     ptr = POPPTR(ss,ix);
10523     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10524     break;
10525     case SAVEt_PPTR: /* char* reference */
10526     ptr = POPPTR(ss,ix);
10527     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10528     c = (char*)POPPTR(ss,ix);
10529     TOPPTR(nss,ix) = pv_dup(c);
10530     break;
10531     case SAVEt_HPTR: /* HV* reference */
10532     ptr = POPPTR(ss,ix);
10533     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10534     hv = (HV*)POPPTR(ss,ix);
10535     TOPPTR(nss,ix) = hv_dup(hv, param);
10536     break;
10537     case SAVEt_APTR: /* AV* reference */
10538     ptr = POPPTR(ss,ix);
10539     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10540     av = (AV*)POPPTR(ss,ix);
10541     TOPPTR(nss,ix) = av_dup(av, param);
10542     break;
10543     case SAVEt_NSTAB:
10544     gv = (GV*)POPPTR(ss,ix);
10545     TOPPTR(nss,ix) = gv_dup(gv, param);
10546     break;
10547     case SAVEt_GP: /* scalar reference */
10548     gp = (GP*)POPPTR(ss,ix);
10549     TOPPTR(nss,ix) = gp = gp_dup(gp, param);
10550     (void)GpREFCNT_inc(gp);
10551     gv = (GV*)POPPTR(ss,ix);
10552     TOPPTR(nss,ix) = gv_dup_inc(gv, param);
10553     c = (char*)POPPTR(ss,ix);
10554     TOPPTR(nss,ix) = pv_dup(c);
10555     iv = POPIV(ss,ix);
10556     TOPIV(nss,ix) = iv;
10557     iv = POPIV(ss,ix);
10558     TOPIV(nss,ix) = iv;
10559     break;
10560     case SAVEt_FREESV:
10561     case SAVEt_MORTALIZESV:
10562     sv = (SV*)POPPTR(ss,ix);
10563     TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10564     break;
10565     case SAVEt_FREEOP:
10566     ptr = POPPTR(ss,ix);
10567     if (ptr && (((OP*)ptr)->op_private & OPpREFCOUNTED)) {
10568     /* these are assumed to be refcounted properly */
10569     switch (((OP*)ptr)->op_type) {
10570     case OP_LEAVESUB:
10571     case OP_LEAVESUBLV:
10572     case OP_LEAVEEVAL:
10573     case OP_LEAVE:
10574     case OP_SCOPE:
10575     case OP_LEAVEWRITE:
10576     TOPPTR(nss,ix) = ptr;
10577     o = (OP*)ptr;
10578     OpREFCNT_inc(o);
10579     break;
10580     default:
10581     TOPPTR(nss,ix) = Nullop;
10582     break;
10583     }
10584     }
10585     else
10586     TOPPTR(nss,ix) = Nullop;
10587     break;
10588     case SAVEt_FREEPV:
10589     c = (char*)POPPTR(ss,ix);
10590     TOPPTR(nss,ix) = pv_dup_inc(c);
10591     break;
10592     case SAVEt_CLEARSV:
10593     longval = POPLONG(ss,ix);
10594     TOPLONG(nss,ix) = longval;
10595     break;
10596     case SAVEt_DELETE:
10597     hv = (HV*)POPPTR(ss,ix);
10598     TOPPTR(nss,ix) = hv_dup_inc(hv, param);
10599     c = (char*)POPPTR(ss,ix);
10600     TOPPTR(nss,ix) = pv_dup_inc(c);
10601     i = POPINT(ss,ix);
10602     TOPINT(nss,ix) = i;
10603     break;
10604     case SAVEt_DESTRUCTOR:
10605     ptr = POPPTR(ss,ix);
10606     TOPPTR(nss,ix) = any_dup(ptr, proto_perl); /* XXX quite arbitrary */
10607     dptr = POPDPTR(ss,ix);
10608     TOPDPTR(nss,ix) = (void (*)(void*))any_dup((void *)dptr, proto_perl);
10609     break;
10610     case SAVEt_DESTRUCTOR_X:
10611     ptr = POPPTR(ss,ix);
10612     TOPPTR(nss,ix) = any_dup(ptr, proto_perl); /* XXX quite arbitrary */
10613     dxptr = POPDXPTR(ss,ix);
10614     TOPDXPTR(nss,ix) = (void (*)(pTHX_ void*))any_dup((void *)dxptr, proto_perl);
10615     break;
10616     case SAVEt_REGCONTEXT:
10617     case SAVEt_ALLOC:
10618     i = POPINT(ss,ix);
10619     TOPINT(nss,ix) = i;
10620     ix -= i;
10621     break;
10622     case SAVEt_STACK_POS: /* Position on Perl stack */
10623     i = POPINT(ss,ix);
10624     TOPINT(nss,ix) = i;
10625     break;
10626     case SAVEt_AELEM: /* array element */
10627     sv = (SV*)POPPTR(ss,ix);
10628     TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10629     i = POPINT(ss,ix);
10630     TOPINT(nss,ix) = i;
10631     av = (AV*)POPPTR(ss,ix);
10632     TOPPTR(nss,ix) = av_dup_inc(av, param);
10633     break;
10634     case SAVEt_HELEM: /* hash element */
10635     sv = (SV*)POPPTR(ss,ix);
10636     TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10637     sv = (SV*)POPPTR(ss,ix);
10638     TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10639     hv = (HV*)POPPTR(ss,ix);
10640     TOPPTR(nss,ix) = hv_dup_inc(hv, param);
10641     break;
10642     case SAVEt_OP:
10643     ptr = POPPTR(ss,ix);
10644     TOPPTR(nss,ix) = ptr;
10645     break;
10646     case SAVEt_HINTS:
10647     i = POPINT(ss,ix);
10648     TOPINT(nss,ix) = i;
10649     break;
10650     case SAVEt_COMPPAD:
10651     av = (AV*)POPPTR(ss,ix);
10652     TOPPTR(nss,ix) = av_dup(av, param);
10653     break;
10654     case SAVEt_PADSV:
10655     longval = (long)POPLONG(ss,ix);
10656     TOPLONG(nss,ix) = longval;
10657     ptr = POPPTR(ss,ix);
10658     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10659     sv = (SV*)POPPTR(ss,ix);
10660     TOPPTR(nss,ix) = sv_dup(sv, param);
10661     break;
10662     case SAVEt_BOOL:
10663     ptr = POPPTR(ss,ix);
10664     TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10665     longval = (long)POPBOOL(ss,ix);
10666     TOPBOOL(nss,ix) = (bool)longval;
10667     break;
10668     default:
10669     Perl_croak(aTHX_ "panic: ss_dup inconsistency");
10670     }
10671     }
10672    
10673     return nss;
10674     }
10675    
10676    
10677     /* if sv is a stash, call $class->CLONE_SKIP(), and set the SVphv_CLONEABLE
10678     * flag to the result. This is done for each stash before cloning starts,
10679     * so we know which stashes want their objects cloned */
10680    
10681     static void
10682     do_mark_cloneable_stash(pTHX_ SV *sv)
10683     {
10684     if (HvNAME((HV*)sv)) {
10685     GV* cloner = gv_fetchmethod_autoload((HV*)sv, "CLONE_SKIP", 0);
10686     SvFLAGS(sv) |= SVphv_CLONEABLE; /* clone objects by default */
10687     if (cloner && GvCV(cloner)) {
10688     dSP;
10689     UV status;
10690    
10691     ENTER;
10692     SAVETMPS;
10693     PUSHMARK(SP);
10694     XPUSHs(sv_2mortal(newSVpv(HvNAME((HV*)sv), 0)));
10695     PUTBACK;
10696     call_sv((SV*)GvCV(cloner), G_SCALAR);
10697     SPAGAIN;
10698     status = POPu;
10699     PUTBACK;
10700     FREETMPS;
10701     LEAVE;
10702     if (status)
10703     SvFLAGS(sv) &= ~SVphv_CLONEABLE;
10704     }
10705     }
10706     }
10707    
10708    
10709    
10710     /*
10711     =for apidoc perl_clone
10712    
10713     Create and return a new interpreter by cloning the current one.
10714    
10715     perl_clone takes these flags as parameters:
10716    
10717     CLONEf_COPY_STACKS - is used to, well, copy the stacks also,
10718     without it we only clone the data and zero the stacks,
10719     with it we copy the stacks and the new perl interpreter is
10720     ready to run at the exact same point as the previous one.
10721     The pseudo-fork code uses COPY_STACKS while the
10722     threads->new doesn't.
10723    
10724     CLONEf_KEEP_PTR_TABLE
10725     perl_clone keeps a ptr_table with the pointer of the old
10726     variable as a key and the new variable as a value,
10727     this allows it to check if something has been cloned and not
10728     clone it again but rather just use the value and increase the
10729     refcount. If KEEP_PTR_TABLE is not set then perl_clone will kill
10730     the ptr_table using the function
10731     C<ptr_table_free(PL_ptr_table); PL_ptr_table = NULL;>,
10732     reason to keep it around is if you want to dup some of your own
10733     variable who are outside the graph perl scans, example of this
10734     code is in threads.xs create
10735    
10736     CLONEf_CLONE_HOST
10737     This is a win32 thing, it is ignored on unix, it tells perls
10738     win32host code (which is c++) to clone itself, this is needed on
10739     win32 if you want to run two threads at the same time,
10740     if you just want to do some stuff in a separate perl interpreter
10741     and then throw it away and return to the original one,
10742     you don't need to do anything.
10743    
10744     =cut
10745     */
10746    
10747     /* XXX the above needs expanding by someone who actually understands it ! */
10748     EXTERN_C PerlInterpreter *
10749     perl_clone_host(PerlInterpreter* proto_perl, UV flags);
10750    
10751     PerlInterpreter *
10752     perl_clone(PerlInterpreter *proto_perl, UV flags)
10753     {
10754     #ifdef PERL_IMPLICIT_SYS
10755    
10756     /* perlhost.h so we need to call into it
10757     to clone the host, CPerlHost should have a c interface, sky */
10758    
10759     if (flags & CLONEf_CLONE_HOST) {
10760     return perl_clone_host(proto_perl,flags);
10761     }
10762     return perl_clone_using(proto_perl, flags,
10763     proto_perl->IMem,
10764     proto_perl->IMemShared,
10765     proto_perl->IMemParse,
10766     proto_perl->IEnv,
10767     proto_perl->IStdIO,
10768     proto_perl->ILIO,
10769     proto_perl->IDir,
10770     proto_perl->ISock,
10771     proto_perl->IProc);
10772     }
10773    
10774     PerlInterpreter *
10775     perl_clone_using(PerlInterpreter *proto_perl, UV flags,
10776     struct IPerlMem* ipM, struct IPerlMem* ipMS,
10777     struct IPerlMem* ipMP, struct IPerlEnv* ipE,
10778     struct IPerlStdIO* ipStd, struct IPerlLIO* ipLIO,
10779     struct IPerlDir* ipD, struct IPerlSock* ipS,
10780     struct IPerlProc* ipP)
10781     {
10782     /* XXX many of the string copies here can be optimized if they're
10783     * constants; they need to be allocated as common memory and just
10784     * their pointers copied. */
10785    
10786     IV i;
10787     CLONE_PARAMS clone_params;
10788     CLONE_PARAMS* param = &clone_params;
10789    
10790     PerlInterpreter *my_perl = (PerlInterpreter*)(*ipM->pMalloc)(ipM, sizeof(PerlInterpreter));
10791     /* for each stash, determine whether its objects should be cloned */
10792     S_visit(proto_perl, do_mark_cloneable_stash, SVt_PVHV, SVTYPEMASK);
10793     PERL_SET_THX(my_perl);
10794    
10795     # ifdef DEBUGGING
10796     Poison(my_perl, 1, PerlInterpreter);
10797     PL_markstack = 0;
10798     PL_scopestack = 0;
10799     PL_savestack = 0;
10800     PL_savestack_ix = 0;
10801     PL_savestack_max = -1;
10802     PL_retstack = 0;
10803     PL_sig_pending = 0;
10804     Zero(&PL_debug_pad, 1, struct perl_debug_pad);
10805     # else /* !DEBUGGING */
10806     Zero(my_perl, 1, PerlInterpreter);
10807     # endif /* DEBUGGING */
10808    
10809     /* host pointers */
10810     PL_Mem = ipM;
10811     PL_MemShared = ipMS;
10812     PL_MemParse = ipMP;
10813     PL_Env = ipE;
10814     PL_StdIO = ipStd;
10815     PL_LIO = ipLIO;
10816     PL_Dir = ipD;
10817     PL_Sock = ipS;
10818     PL_Proc = ipP;
10819     #else /* !PERL_IMPLICIT_SYS */
10820     IV i;
10821     CLONE_PARAMS clone_params;
10822     CLONE_PARAMS* param = &clone_params;
10823     PerlInterpreter *my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
10824     /* for each stash, determine whether its objects should be cloned */
10825     S_visit(proto_perl, do_mark_cloneable_stash, SVt_PVHV, SVTYPEMASK);
10826     PERL_SET_THX(my_perl);
10827    
10828     # ifdef DEBUGGING
10829     Poison(my_perl, 1, PerlInterpreter);
10830     PL_markstack = 0;
10831     PL_scopestack = 0;
10832     PL_savestack = 0;
10833     PL_savestack_ix = 0;
10834     PL_savestack_max = -1;
10835     PL_retstack = 0;
10836     PL_sig_pending = 0;
10837     Zero(&PL_debug_pad, 1, struct perl_debug_pad);
10838     # else /* !DEBUGGING */
10839     Zero(my_perl, 1, PerlInterpreter);
10840     # endif /* DEBUGGING */
10841     #endif /* PERL_IMPLICIT_SYS */
10842     param->flags = flags;
10843     param->proto_perl = proto_perl;
10844    
10845     /* arena roots */
10846     PL_xiv_arenaroot = NULL;
10847     PL_xiv_root = NULL;
10848     PL_xnv_arenaroot = NULL;
10849     PL_xnv_root = NULL;
10850     PL_xrv_arenaroot = NULL;
10851     PL_xrv_root = NULL;
10852     PL_xpv_arenaroot = NULL;
10853     PL_xpv_root = NULL;
10854     PL_xpviv_arenaroot = NULL;
10855     PL_xpviv_root = NULL;
10856     PL_xpvnv_arenaroot = NULL;
10857     PL_xpvnv_root = NULL;
10858     PL_xpvcv_arenaroot = NULL;
10859     PL_xpvcv_root = NULL;
10860     PL_xpvav_arenaroot = NULL;
10861     PL_xpvav_root = NULL;
10862     PL_xpvhv_arenaroot = NULL;
10863     PL_xpvhv_root = NULL;
10864     PL_xpvmg_arenaroot = NULL;
10865     PL_xpvmg_root = NULL;
10866     PL_xpvlv_arenaroot = NULL;
10867     PL_xpvlv_root = NULL;
10868     PL_xpvbm_arenaroot = NULL;
10869     PL_xpvbm_root = NULL;
10870     PL_he_arenaroot = NULL;
10871     PL_he_root = NULL;
10872     #if defined(USE_ITHREADS)
10873     PL_pte_arenaroot = NULL;
10874     PL_pte_root = NULL;
10875     #endif
10876     PL_nice_chunk = NULL;
10877     PL_nice_chunk_size = 0;
10878     PL_sv_count = 0;
10879     PL_sv_objcount = 0;
10880     PL_sv_root = Nullsv;
10881     PL_sv_arenaroot = Nullsv;
10882    
10883     PL_debug = proto_perl->Idebug;
10884    
10885     #ifdef USE_REENTRANT_API
10886     /* XXX: things like -Dm will segfault here in perlio, but doing
10887     * PERL_SET_CONTEXT(proto_perl);
10888     * breaks too many other things
10889     */
10890     Perl_reentrant_init(aTHX);
10891     #endif
10892    
10893     /* create SV map for pointer relocation */
10894     PL_ptr_table = ptr_table_new();
10895    
10896     /* initialize these special pointers as early as possible */
10897     SvANY(&PL_sv_undef) = NULL;
10898     SvREFCNT(&PL_sv_undef) = (~(U32)0)/2;
10899     SvFLAGS(&PL_sv_undef) = SVf_READONLY|SVt_NULL;
10900     ptr_table_store(PL_ptr_table, &proto_perl->Isv_undef, &PL_sv_undef);
10901    
10902     SvANY(&PL_sv_no) = new_XPVNV();
10903     SvREFCNT(&PL_sv_no) = (~(U32)0)/2;
10904     SvFLAGS(&PL_sv_no) = SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
10905     |SVp_POK|SVf_POK|SVf_READONLY|SVt_PVNV;
10906     SvPVX(&PL_sv_no) = SAVEPVN(PL_No, 0);
10907     SvCUR(&PL_sv_no) = 0;
10908     SvLEN(&PL_sv_no) = 1;
10909     SvIVX(&PL_sv_no) = 0;
10910     SvNVX(&PL_sv_no) = 0;
10911     ptr_table_store(PL_ptr_table, &proto_perl->Isv_no, &PL_sv_no);
10912    
10913     SvANY(&PL_sv_yes) = new_XPVNV();
10914     SvREFCNT(&PL_sv_yes) = (~(U32)0)/2;
10915     SvFLAGS(&PL_sv_yes) = SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
10916     |SVp_POK|SVf_POK|SVf_READONLY|SVt_PVNV;
10917     SvPVX(&PL_sv_yes) = SAVEPVN(PL_Yes, 1);
10918     SvCUR(&PL_sv_yes) = 1;
10919     SvLEN(&PL_sv_yes) = 2;
10920     SvIVX(&PL_sv_yes) = 1;
10921     SvNVX(&PL_sv_yes) = 1;
10922     ptr_table_store(PL_ptr_table, &proto_perl->Isv_yes, &PL_sv_yes);
10923    
10924     /* create (a non-shared!) shared string table */
10925     PL_strtab = newHV();
10926     HvSHAREKEYS_off(PL_strtab);
10927     hv_ksplit(PL_strtab, 512);
10928     ptr_table_store(PL_ptr_table, proto_perl->Istrtab, PL_strtab);
10929    
10930     PL_compiling = proto_perl->Icompiling;
10931    
10932     /* These two PVs will be free'd special way so must set them same way op.c does */
10933     PL_compiling.cop_stashpv = savesharedpv(PL_compiling.cop_stashpv);
10934     ptr_table_store(PL_ptr_table, proto_perl->Icompiling.cop_stashpv, PL_compiling.cop_stashpv);
10935    
10936     PL_compiling.cop_file = savesharedpv(PL_compiling.cop_file);
10937     ptr_table_store(PL_ptr_table, proto_perl->Icompiling.cop_file, PL_compiling.cop_file);
10938    
10939     ptr_table_store(PL_ptr_table, &proto_perl->Icompiling, &PL_compiling);
10940     if (!specialWARN(PL_compiling.cop_warnings))
10941     PL_compiling.cop_warnings = sv_dup_inc(PL_compiling.cop_warnings, param);
10942     if (!specialCopIO(PL_compiling.cop_io))
10943     PL_compiling.cop_io = sv_dup_inc(PL_compiling.cop_io, param);
10944     PL_curcop = (COP*)any_dup(proto_perl->Tcurcop, proto_perl);
10945    
10946     /* pseudo environmental stuff */
10947     PL_origargc = proto_perl->Iorigargc;
10948     PL_origargv = proto_perl->Iorigargv;
10949    
10950     param->stashes = newAV(); /* Setup array of objects to call clone on */
10951    
10952     #ifdef PERLIO_LAYERS
10953     /* Clone PerlIO tables as soon as we can handle general xx_dup() */
10954     PerlIO_clone(aTHX_ proto_perl, param);
10955     #endif
10956    
10957     PL_envgv = gv_dup(proto_perl->Ienvgv, param);
10958     PL_incgv = gv_dup(proto_perl->Iincgv, param);
10959     PL_hintgv = gv_dup(proto_perl->Ihintgv, param);
10960     PL_origfilename = SAVEPV(proto_perl->Iorigfilename);
10961     PL_diehook = sv_dup_inc(proto_perl->Idiehook, param);
10962     PL_warnhook = sv_dup_inc(proto_perl->Iwarnhook, param);
10963    
10964     /* switches */
10965     PL_minus_c = proto_perl->Iminus_c;
10966     PL_patchlevel = sv_dup_inc(proto_perl->Ipatchlevel, param);
10967     PL_localpatches = proto_perl->Ilocalpatches;
10968     PL_splitstr = proto_perl->Isplitstr;
10969     PL_preprocess = proto_perl->Ipreprocess;
10970     PL_minus_n = proto_perl->Iminus_n;
10971     PL_minus_p = proto_perl->Iminus_p;
10972     PL_minus_l = proto_perl->Iminus_l;
10973     PL_minus_a = proto_perl->Iminus_a;
10974     PL_minus_F = proto_perl->Iminus_F;
10975     PL_doswitches = proto_perl->Idoswitches;
10976     PL_dowarn = proto_perl->Idowarn;
10977     PL_doextract = proto_perl->Idoextract;
10978     PL_sawampersand = proto_perl->Isawampersand;
10979     PL_unsafe = proto_perl->Iunsafe;
10980     PL_inplace = SAVEPV(proto_perl->Iinplace);
10981     PL_e_script = sv_dup_inc(proto_perl->Ie_script, param);
10982     PL_perldb = proto_perl->Iperldb;
10983     PL_perl_destruct_level = proto_perl->Iperl_destruct_level;
10984     PL_exit_flags = proto_perl->Iexit_flags;
10985    
10986     /* magical thingies */
10987     /* XXX time(&PL_basetime) when asked for? */
10988     PL_basetime = proto_perl->Ibasetime;
10989     PL_formfeed = sv_dup(proto_perl->Iformfeed, param);
10990    
10991     PL_maxsysfd = proto_perl->Imaxsysfd;
10992     PL_multiline = proto_perl->Imultiline;
10993     PL_statusvalue = proto_perl->Istatusvalue;
10994     #ifdef VMS
10995     PL_statusvalue_vms = proto_perl->Istatusvalue_vms;
10996     #endif
10997     PL_encoding = sv_dup(proto_perl->Iencoding, param);
10998    
10999     sv_setpvn(PERL_DEBUG_PAD(0), "", 0); /* For regex debugging. */
11000     sv_setpvn(PERL_DEBUG_PAD(1), "", 0); /* ext/re needs these */
11001     sv_setpvn(PERL_DEBUG_PAD(2), "", 0); /* even without DEBUGGING. */
11002    
11003     /* Clone the regex array */
11004     PL_regex_padav = newAV();
11005     {
11006     I32 len = av_len((AV*)proto_perl->Iregex_padav);
11007     SV** regexen = AvARRAY((AV*)proto_perl->Iregex_padav);
11008     av_push(PL_regex_padav,
11009     sv_dup_inc(regexen[0],param));
11010     for(i = 1; i <= len; i++) {
11011     if(SvREPADTMP(regexen[i])) {
11012     av_push(PL_regex_padav, sv_dup_inc(regexen[i], param));
11013     } else {
11014     av_push(PL_regex_padav,
11015     SvREFCNT_inc(
11016     newSViv(PTR2IV(re_dup(INT2PTR(REGEXP *,
11017     SvIVX(regexen[i])), param)))
11018     ));
11019     }
11020     }
11021     }
11022     PL_regex_pad = AvARRAY(PL_regex_padav);
11023    
11024     /* shortcuts to various I/O objects */
11025     PL_stdingv = gv_dup(proto_perl->Istdingv, param);
11026     PL_stderrgv = gv_dup(proto_perl->Istderrgv, param);
11027     PL_defgv = gv_dup(proto_perl->Idefgv, param);
11028     PL_argvgv = gv_dup(proto_perl->Iargvgv, param);
11029     PL_argvoutgv = gv_dup(proto_perl->Iargvoutgv, param);
11030     PL_argvout_stack = av_dup_inc(proto_perl->Iargvout_stack, param);
11031    
11032     /* shortcuts to regexp stuff */
11033     PL_replgv = gv_dup(proto_perl->Ireplgv, param);
11034    
11035     /* shortcuts to misc objects */
11036     PL_errgv = gv_dup(proto_perl->Ierrgv, param);
11037    
11038     /* shortcuts to debugging objects */
11039     PL_DBgv = gv_dup(proto_perl->IDBgv, param);
11040     PL_DBline = gv_dup(proto_perl->IDBline, param);
11041     PL_DBsub = gv_dup(proto_perl->IDBsub, param);
11042     PL_DBsingle = sv_dup(proto_perl->IDBsingle, param);
11043     PL_DBtrace = sv_dup(proto_perl->IDBtrace, param);
11044     PL_DBsignal = sv_dup(proto_perl->IDBsignal, param);
11045     PL_lineary = av_dup(proto_perl->Ilineary, param);
11046     PL_dbargs = av_dup(proto_perl->Idbargs, param);
11047    
11048     /* symbol tables */
11049     PL_defstash = hv_dup_inc(proto_perl->Tdefstash, param);
11050     PL_curstash = hv_dup(proto_perl->Tcurstash, param);
11051     PL_nullstash = hv_dup(proto_perl->Inullstash, param);
11052     PL_debstash = hv_dup(proto_perl->Idebstash, param);
11053     PL_globalstash = hv_dup(proto_perl->Iglobalstash, param);
11054     PL_curstname = sv_dup_inc(proto_perl->Icurstname, param);
11055    
11056     PL_beginav = av_dup_inc(proto_perl->Ibeginav, param);
11057     PL_beginav_save = av_dup_inc(proto_perl->Ibeginav_save, param);
11058     PL_checkav_save = av_dup_inc(proto_perl->Icheckav_save, param);
11059     PL_endav = av_dup_inc(proto_perl->Iendav, param);
11060     PL_checkav = av_dup_inc(proto_perl->Icheckav, param);
11061     PL_initav = av_dup_inc(proto_perl->Iinitav, param);
11062    
11063     PL_sub_generation = proto_perl->Isub_generation;
11064    
11065     /* funky return mechanisms */
11066     PL_forkprocess = proto_perl->Iforkprocess;
11067    
11068     /* subprocess state */
11069     PL_fdpid = av_dup_inc(proto_perl->Ifdpid, param);
11070    
11071     /* internal state */
11072     PL_tainting = proto_perl->Itainting;
11073     PL_taint_warn = proto_perl->Itaint_warn;
11074     PL_maxo = proto_perl->Imaxo;
11075     if (proto_perl->Iop_mask)
11076     PL_op_mask = SAVEPVN(proto_perl->Iop_mask, PL_maxo);
11077     else
11078     PL_op_mask = Nullch;
11079    
11080     /* current interpreter roots */
11081     PL_main_cv = cv_dup_inc(proto_perl->Imain_cv, param);
11082     PL_main_root = OpREFCNT_inc(proto_perl->Imain_root);
11083     PL_main_start = proto_perl->Imain_start;
11084     PL_eval_root = proto_perl->Ieval_root;
11085     PL_eval_start = proto_perl->Ieval_start;
11086    
11087     /* runtime control stuff */
11088     PL_curcopdb = (COP*)any_dup(proto_perl->Icurcopdb, proto_perl);
11089     PL_copline = proto_perl->Icopline;
11090    
11091     PL_filemode = proto_perl->Ifilemode;
11092     PL_lastfd = proto_perl->Ilastfd;
11093     PL_oldname = proto_perl->Ioldname; /* XXX not quite right */
11094     PL_Argv = NULL;
11095     PL_Cmd = Nullch;
11096     PL_gensym = proto_perl->Igensym;
11097     PL_preambled = proto_perl->Ipreambled;
11098     PL_preambleav = av_dup_inc(proto_perl->Ipreambleav, param);
11099     PL_laststatval = proto_perl->Ilaststatval;
11100     PL_laststype = proto_perl->Ilaststype;
11101     PL_mess_sv = Nullsv;
11102    
11103     PL_ors_sv = sv_dup_inc(proto_perl->Iors_sv, param);
11104     PL_ofmt = SAVEPV(proto_perl->Iofmt);
11105    
11106     /* interpreter atexit processing */
11107     PL_exitlistlen = proto_perl->Iexitlistlen;
11108     if (PL_exitlistlen) {
11109     New(0, PL_exitlist, PL_exitlistlen, PerlExitListEntry);
11110     Copy(proto_perl->Iexitlist, PL_exitlist, PL_exitlistlen, PerlExitListEntry);
11111     }
11112     else
11113     PL_exitlist = (PerlExitListEntry*)NULL;
11114     PL_modglobal = hv_dup_inc(proto_perl->Imodglobal, param);
11115     PL_custom_op_names = hv_dup_inc(proto_perl->Icustom_op_names,param);
11116     PL_custom_op_descs = hv_dup_inc(proto_perl->Icustom_op_descs,param);
11117    
11118     PL_profiledata = NULL;
11119     PL_rsfp = fp_dup(proto_perl->Irsfp, '<', param);
11120     /* PL_rsfp_filters entries have fake IoDIRP() */
11121     PL_rsfp_filters = av_dup_inc(proto_perl->Irsfp_filters, param);
11122    
11123     PL_compcv = cv_dup(proto_perl->Icompcv, param);
11124    
11125     PAD_CLONE_VARS(proto_perl, param);
11126    
11127     #ifdef HAVE_INTERP_INTERN
11128     sys_intern_dup(&proto_perl->Isys_intern, &PL_sys_intern);
11129     #endif
11130    
11131     /* more statics moved here */
11132     PL_generation = proto_perl->Igeneration;
11133     PL_DBcv = cv_dup(proto_perl->IDBcv, param);
11134    
11135     PL_in_clean_objs = proto_perl->Iin_clean_objs;
11136     PL_in_clean_all = proto_perl->Iin_clean_all;
11137    
11138     PL_uid = proto_perl->Iuid;
11139     PL_euid = proto_perl->Ieuid;
11140     PL_gid = proto_perl->Igid;
11141     PL_egid = proto_perl->Iegid;
11142     PL_nomemok = proto_perl->Inomemok;
11143     PL_an = proto_perl->Ian;
11144     PL_op_seqmax = proto_perl->Iop_seqmax;
11145     PL_evalseq = proto_perl->Ievalseq;
11146     PL_origenviron = proto_perl->Iorigenviron; /* XXX not quite right */
11147     PL_origalen = proto_perl->Iorigalen;
11148     PL_pidstatus = newHV(); /* XXX flag for cloning? */
11149     PL_osname = SAVEPV(proto_perl->Iosname);
11150     PL_sh_path_compat = proto_perl->Ish_path_compat; /* XXX never deallocated */
11151     PL_sighandlerp = proto_perl->Isighandlerp;
11152    
11153    
11154     PL_runops = proto_perl->Irunops;
11155    
11156     Copy(proto_perl->Itokenbuf, PL_tokenbuf, 256, char);
11157    
11158     #ifdef CSH
11159     PL_cshlen = proto_perl->Icshlen;
11160     PL_cshname = proto_perl->Icshname; /* XXX never deallocated */
11161     #endif
11162    
11163     PL_lex_state = proto_perl->Ilex_state;
11164     PL_lex_defer = proto_perl->Ilex_defer;
11165     PL_lex_expect = proto_perl->Ilex_expect;
11166     PL_lex_formbrack = proto_perl->Ilex_formbrack;
11167     PL_lex_dojoin = proto_perl->Ilex_dojoin;
11168     PL_lex_starts = proto_perl->Ilex_starts;
11169     PL_lex_stuff = sv_dup_inc(proto_perl->Ilex_stuff, param);
11170     PL_lex_repl = sv_dup_inc(proto_perl->Ilex_repl, param);
11171     PL_lex_op = proto_perl->Ilex_op;
11172     PL_lex_inpat = proto_perl->Ilex_inpat;
11173     PL_lex_inwhat = proto_perl->Ilex_inwhat;
11174     PL_lex_brackets = proto_perl->Ilex_brackets;
11175     i = (PL_lex_brackets < 120 ? 120 : PL_lex_brackets);
11176     PL_lex_brackstack = SAVEPVN(proto_perl->Ilex_brackstack,i);
11177     PL_lex_casemods = proto_perl->Ilex_casemods;
11178     i = (PL_lex_casemods < 12 ? 12 : PL_lex_casemods);
11179     PL_lex_casestack = SAVEPVN(proto_perl->Ilex_casestack,i);
11180    
11181     Copy(proto_perl->Inextval, PL_nextval, 5, YYSTYPE);
11182     Copy(proto_perl->Inexttype, PL_nexttype, 5, I32);
11183     PL_nexttoke = proto_perl->Inexttoke;
11184    
11185     /* XXX This is probably masking the deeper issue of why
11186     * SvANY(proto_perl->Ilinestr) can be NULL at this point. For test case:
11187     * http://archive.develooper.com/perl5-porters%40perl.org/msg83298.html
11188     * (A little debugging with a watchpoint on it may help.)
11189     */
11190     if (SvANY(proto_perl->Ilinestr)) {
11191     PL_linestr = sv_dup_inc(proto_perl->Ilinestr, param);
11192     i = proto_perl->Ibufptr - SvPVX(proto_perl->Ilinestr);
11193     PL_bufptr = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11194     i = proto_perl->Ioldbufptr - SvPVX(proto_perl->Ilinestr);
11195     PL_oldbufptr = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11196     i = proto_perl->Ioldoldbufptr - SvPVX(proto_perl->Ilinestr);
11197     PL_oldoldbufptr = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11198     i = proto_perl->Ilinestart - SvPVX(proto_perl->Ilinestr);
11199     PL_linestart = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11200     }
11201     else {
11202     PL_linestr = NEWSV(65,79);
11203     sv_upgrade(PL_linestr,SVt_PVIV);
11204     sv_setpvn(PL_linestr,"",0);
11205     PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart = SvPVX(PL_linestr);
11206     }
11207     PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
11208     PL_pending_ident = proto_perl->Ipending_ident;
11209     PL_sublex_info = proto_perl->Isublex_info; /* XXX not quite right */
11210    
11211     PL_expect = proto_perl->Iexpect;
11212    
11213     PL_multi_start = proto_perl->Imulti_start;
11214     PL_multi_end = proto_perl->Imulti_end;
11215     PL_multi_open = proto_perl->Imulti_open;
11216     PL_multi_close = proto_perl->Imulti_close;
11217    
11218     PL_error_count = proto_perl->Ierror_count;
11219     PL_subline = proto_perl->Isubline;
11220     PL_subname = sv_dup_inc(proto_perl->Isubname, param);
11221    
11222     /* XXX See comment on SvANY(proto_perl->Ilinestr) above */
11223     if (SvANY(proto_perl->Ilinestr)) {
11224     i = proto_perl->Ilast_uni - SvPVX(proto_perl->Ilinestr);
11225     PL_last_uni = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11226     i = proto_perl->Ilast_lop - SvPVX(proto_perl->Ilinestr);
11227     PL_last_lop = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11228     PL_last_lop_op = proto_perl->Ilast_lop_op;
11229     }
11230     else {
11231     PL_last_uni = SvPVX(PL_linestr);
11232     PL_last_lop = SvPVX(PL_linestr);
11233     PL_last_lop_op = 0;
11234     }
11235     PL_in_my = proto_perl->Iin_my;
11236     PL_in_my_stash = hv_dup(proto_perl->Iin_my_stash, param);
11237     #ifdef FCRYPT
11238     PL_cryptseen = proto_perl->Icryptseen;
11239     #endif
11240    
11241     PL_hints = proto_perl->Ihints;
11242    
11243     PL_amagic_generation = proto_perl->Iamagic_generation;
11244    
11245     #ifdef USE_LOCALE_COLLATE
11246     PL_collation_ix = proto_perl->Icollation_ix;
11247     PL_collation_name = SAVEPV(proto_perl->Icollation_name);
11248     PL_collation_standard = proto_perl->Icollation_standard;
11249     PL_collxfrm_base = proto_perl->Icollxfrm_base;
11250     PL_collxfrm_mult = proto_perl->Icollxfrm_mult;
11251     #endif /* USE_LOCALE_COLLATE */
11252    
11253     #ifdef USE_LOCALE_NUMERIC
11254     PL_numeric_name = SAVEPV(proto_perl->Inumeric_name);
11255     PL_numeric_standard = proto_perl->Inumeric_standard;
11256     PL_numeric_local = proto_perl->Inumeric_local;
11257     PL_numeric_radix_sv = sv_dup_inc(proto_perl->Inumeric_radix_sv, param);
11258     #endif /* !USE_LOCALE_NUMERIC */
11259    
11260     /* utf8 character classes */
11261     PL_utf8_alnum = sv_dup_inc(proto_perl->Iutf8_alnum, param);
11262     PL_utf8_alnumc = sv_dup_inc(proto_perl->Iutf8_alnumc, param);
11263     PL_utf8_ascii = sv_dup_inc(proto_perl->Iutf8_ascii, param);
11264     PL_utf8_alpha = sv_dup_inc(proto_perl->Iutf8_alpha, param);
11265     PL_utf8_space = sv_dup_inc(proto_perl->Iutf8_space, param);
11266     PL_utf8_cntrl = sv_dup_inc(proto_perl->Iutf8_cntrl, param);
11267     PL_utf8_graph = sv_dup_inc(proto_perl->Iutf8_graph, param);
11268     PL_utf8_digit = sv_dup_inc(proto_perl->Iutf8_digit, param);
11269     PL_utf8_upper = sv_dup_inc(proto_perl->Iutf8_upper, param);
11270     PL_utf8_lower = sv_dup_inc(proto_perl->Iutf8_lower, param);
11271     PL_utf8_print = sv_dup_inc(proto_perl->Iutf8_print, param);
11272     PL_utf8_punct = sv_dup_inc(proto_perl->Iutf8_punct, param);
11273     PL_utf8_xdigit = sv_dup_inc(proto_perl->Iutf8_xdigit, param);
11274     PL_utf8_mark = sv_dup_inc(proto_perl->Iutf8_mark, param);
11275     PL_utf8_toupper = sv_dup_inc(proto_perl->Iutf8_toupper, param);
11276     PL_utf8_totitle = sv_dup_inc(proto_perl->Iutf8_totitle, param);
11277     PL_utf8_tolower = sv_dup_inc(proto_perl->Iutf8_tolower, param);
11278     PL_utf8_tofold = sv_dup_inc(proto_perl->Iutf8_tofold, param);
11279     PL_utf8_idstart = sv_dup_inc(proto_perl->Iutf8_idstart, param);
11280     PL_utf8_idcont = sv_dup_inc(proto_perl->Iutf8_idcont, param);
11281    
11282     /* Did the locale setup indicate UTF-8? */
11283     PL_utf8locale = proto_perl->Iutf8locale;
11284     /* Unicode features (see perlrun/-C) */
11285     PL_unicode = proto_perl->Iunicode;
11286    
11287     /* Pre-5.8 signals control */
11288     PL_signals = proto_perl->Isignals;
11289    
11290     /* times() ticks per second */
11291     PL_clocktick = proto_perl->Iclocktick;
11292    
11293     /* Recursion stopper for PerlIO_find_layer */
11294     PL_in_load_module = proto_perl->Iin_load_module;
11295    
11296     /* sort() routine */
11297     PL_sort_RealCmp = proto_perl->Isort_RealCmp;
11298    
11299     /* Not really needed/useful since the reenrant_retint is "volatile",
11300     * but do it for consistency's sake. */
11301     PL_reentrant_retint = proto_perl->Ireentrant_retint;
11302    
11303     /* Hooks to shared SVs and locks. */
11304     PL_sharehook = proto_perl->Isharehook;
11305     PL_lockhook = proto_perl->Ilockhook;
11306     PL_unlockhook = proto_perl->Iunlockhook;
11307     PL_threadhook = proto_perl->Ithreadhook;
11308    
11309     PL_runops_std = proto_perl->Irunops_std;
11310     PL_runops_dbg = proto_perl->Irunops_dbg;
11311    
11312     #ifdef THREADS_HAVE_PIDS
11313     PL_ppid = proto_perl->Ippid;
11314     #endif
11315    
11316     /* swatch cache */
11317     PL_last_swash_hv = Nullhv; /* reinits on demand */
11318     PL_last_swash_klen = 0;
11319     PL_last_swash_key[0]= '\0';
11320     PL_last_swash_tmps = (U8*)NULL;
11321     PL_last_swash_slen = 0;
11322    
11323     /* perly.c globals */
11324     PL_yydebug = proto_perl->Iyydebug;
11325     PL_yynerrs = proto_perl->Iyynerrs;
11326     PL_yyerrflag = proto_perl->Iyyerrflag;
11327     PL_yychar = proto_perl->Iyychar;
11328     PL_yyval = proto_perl->Iyyval;
11329     PL_yylval = proto_perl->Iyylval;
11330    
11331     PL_glob_index = proto_perl->Iglob_index;
11332     PL_srand_called = proto_perl->Isrand_called;
11333     PL_hash_seed = proto_perl->Ihash_seed;
11334     PL_rehash_seed = proto_perl->Irehash_seed;
11335     PL_uudmap['M'] = 0; /* reinits on demand */
11336     PL_bitcount = Nullch; /* reinits on demand */
11337    
11338     if (proto_perl->Ipsig_pend) {
11339     Newz(0, PL_psig_pend, SIG_SIZE, int);
11340     }
11341     else {
11342     PL_psig_pend = (int*)NULL;
11343     }
11344    
11345     if (proto_perl->Ipsig_ptr) {
11346     Newz(0, PL_psig_ptr, SIG_SIZE, SV*);
11347     Newz(0, PL_psig_name, SIG_SIZE, SV*);
11348     for (i = 1; i < SIG_SIZE; i++) {
11349     PL_psig_ptr[i] = sv_dup_inc(proto_perl->Ipsig_ptr[i], param);
11350     PL_psig_name[i] = sv_dup_inc(proto_perl->Ipsig_name[i], param);
11351     }
11352     }
11353     else {
11354     PL_psig_ptr = (SV**)NULL;
11355     PL_psig_name = (SV**)NULL;
11356     }
11357    
11358     /* thrdvar.h stuff */
11359    
11360     if (flags & CLONEf_COPY_STACKS) {
11361     /* next allocation will be PL_tmps_stack[PL_tmps_ix+1] */
11362     PL_tmps_ix = proto_perl->Ttmps_ix;
11363     PL_tmps_max = proto_perl->Ttmps_max;
11364     PL_tmps_floor = proto_perl->Ttmps_floor;
11365     Newz(50, PL_tmps_stack, PL_tmps_max, SV*);
11366     i = 0;
11367     while (i <= PL_tmps_ix) {
11368     PL_tmps_stack[i] = sv_dup_inc(proto_perl->Ttmps_stack[i], param);
11369     ++i;
11370     }
11371    
11372     /* next PUSHMARK() sets *(PL_markstack_ptr+1) */
11373     i = proto_perl->Tmarkstack_max - proto_perl->Tmarkstack;
11374     Newz(54, PL_markstack, i, I32);
11375     PL_markstack_max = PL_markstack + (proto_perl->Tmarkstack_max
11376     - proto_perl->Tmarkstack);
11377     PL_markstack_ptr = PL_markstack + (proto_perl->Tmarkstack_ptr
11378     - proto_perl->Tmarkstack);
11379     Copy(proto_perl->Tmarkstack, PL_markstack,
11380     PL_markstack_ptr - PL_markstack + 1, I32);
11381    
11382     /* next push_scope()/ENTER sets PL_scopestack[PL_scopestack_ix]
11383     * NOTE: unlike the others! */
11384     PL_scopestack_ix = proto_perl->Tscopestack_ix;
11385     PL_scopestack_max = proto_perl->Tscopestack_max;
11386     Newz(54, PL_scopestack, PL_scopestack_max, I32);
11387     Copy(proto_perl->Tscopestack, PL_scopestack, PL_scopestack_ix, I32);
11388    
11389     /* next push_return() sets PL_retstack[PL_retstack_ix]
11390     * NOTE: unlike the others! */
11391     PL_retstack_ix = proto_perl->Tretstack_ix;
11392     PL_retstack_max = proto_perl->Tretstack_max;
11393     Newz(54, PL_retstack, PL_retstack_max, OP*);
11394     Copy(proto_perl->Tretstack, PL_retstack, PL_retstack_ix, OP*);
11395    
11396     /* NOTE: si_dup() looks at PL_markstack */
11397     PL_curstackinfo = si_dup(proto_perl->Tcurstackinfo, param);
11398    
11399     /* PL_curstack = PL_curstackinfo->si_stack; */
11400     PL_curstack = av_dup(proto_perl->Tcurstack, param);
11401     PL_mainstack = av_dup(proto_perl->Tmainstack, param);
11402    
11403     /* next PUSHs() etc. set *(PL_stack_sp+1) */
11404     PL_stack_base = AvARRAY(PL_curstack);
11405     PL_stack_sp = PL_stack_base + (proto_perl->Tstack_sp
11406     - proto_perl->Tstack_base);
11407     PL_stack_max = PL_stack_base + AvMAX(PL_curstack);
11408    
11409     /* next SSPUSHFOO() sets PL_savestack[PL_savestack_ix]
11410     * NOTE: unlike the others! */
11411     PL_savestack_ix = proto_perl->Tsavestack_ix;
11412     PL_savestack_max = proto_perl->Tsavestack_max;
11413     /*Newz(54, PL_savestack, PL_savestack_max, ANY);*/
11414     PL_savestack = ss_dup(proto_perl, param);
11415     }
11416     else {
11417     init_stacks();
11418     ENTER; /* perl_destruct() wants to LEAVE; */
11419     }
11420    
11421     PL_start_env = proto_perl->Tstart_env; /* XXXXXX */
11422     PL_top_env = &PL_start_env;
11423    
11424     PL_op = proto_perl->Top;
11425    
11426     PL_Sv = Nullsv;
11427     PL_Xpv = (XPV*)NULL;
11428     PL_na = proto_perl->Tna;
11429    
11430     PL_statbuf = proto_perl->Tstatbuf;
11431     PL_statcache = proto_perl->Tstatcache;
11432     PL_statgv = gv_dup(proto_perl->Tstatgv, param);
11433     PL_statname = sv_dup_inc(proto_perl->Tstatname, param);
11434     #ifdef HAS_TIMES
11435     PL_timesbuf = proto_perl->Ttimesbuf;
11436     #endif
11437    
11438     PL_tainted = proto_perl->Ttainted;
11439     PL_curpm = proto_perl->Tcurpm; /* XXX No PMOP ref count */
11440     PL_rs = sv_dup_inc(proto_perl->Trs, param);
11441     PL_last_in_gv = gv_dup(proto_perl->Tlast_in_gv, param);
11442     PL_ofs_sv = sv_dup_inc(proto_perl->Tofs_sv, param);
11443     PL_defoutgv = gv_dup_inc(proto_perl->Tdefoutgv, param);
11444     PL_chopset = proto_perl->Tchopset; /* XXX never deallocated */
11445     PL_toptarget = sv_dup_inc(proto_perl->Ttoptarget, param);
11446     PL_bodytarget = sv_dup_inc(proto_perl->Tbodytarget, param);
11447     PL_formtarget = sv_dup(proto_perl->Tformtarget, param);
11448    
11449     PL_restartop = proto_perl->Trestartop;
11450     PL_in_eval = proto_perl->Tin_eval;
11451     PL_delaymagic = proto_perl->Tdelaymagic;
11452     PL_dirty = proto_perl->Tdirty;
11453     PL_localizing = proto_perl->Tlocalizing;
11454    
11455     #ifdef PERL_FLEXIBLE_EXCEPTIONS
11456     PL_protect = proto_perl->Tprotect;
11457     #endif
11458     PL_errors = sv_dup_inc(proto_perl->Terrors, param);
11459     PL_hv_fetch_ent_mh = Nullhe;
11460     PL_modcount = proto_perl->Tmodcount;
11461     PL_lastgotoprobe = Nullop;
11462     PL_dumpindent = proto_perl->Tdumpindent;
11463    
11464     PL_sortcop = (OP*)any_dup(proto_perl->Tsortcop, proto_perl);
11465     PL_sortstash = hv_dup(proto_perl->Tsortstash, param);
11466     PL_firstgv = gv_dup(proto_perl->Tfirstgv, param);
11467     PL_secondgv = gv_dup(proto_perl->Tsecondgv, param);
11468     PL_sortcxix = proto_perl->Tsortcxix;
11469     PL_efloatbuf = Nullch; /* reinits on demand */
11470     PL_efloatsize = 0; /* reinits on demand */
11471    
11472     /* regex stuff */
11473    
11474     PL_screamfirst = NULL;
11475     PL_screamnext = NULL;
11476     PL_maxscream = -1; /* reinits on demand */
11477     PL_lastscream = Nullsv;
11478    
11479     PL_watchaddr = NULL;
11480     PL_watchok = Nullch;
11481    
11482     PL_regdummy = proto_perl->Tregdummy;
11483     PL_regcomp_parse = Nullch;
11484     PL_regxend = Nullch;
11485     PL_regcode = (regnode*)NULL;
11486     PL_regnaughty = 0;
11487     PL_regsawback = 0;
11488     PL_regprecomp = Nullch;
11489     PL_regnpar = 0;
11490     PL_regsize = 0;
11491     PL_regflags = 0;
11492     PL_regseen = 0;
11493     PL_seen_zerolen = 0;
11494     PL_seen_evals = 0;
11495     PL_regcomp_rx = (regexp*)NULL;
11496     PL_extralen = 0;
11497     PL_colorset = 0; /* reinits PL_colors[] */
11498     /*PL_colors[6] = {0,0,0,0,0,0};*/
11499     PL_reg_whilem_seen = 0;
11500     PL_reginput = Nullch;
11501     PL_regbol = Nullch;
11502     PL_regeol = Nullch;
11503     PL_regstartp = (I32*)NULL;
11504     PL_regendp = (I32*)NULL;
11505     PL_reglastparen = (U32*)NULL;
11506     PL_reglastcloseparen = (U32*)NULL;
11507     PL_regtill = Nullch;
11508     PL_reg_start_tmp = (char**)NULL;
11509     PL_reg_start_tmpl = 0;
11510     PL_regdata = (struct reg_data*)NULL;
11511     PL_bostr = Nullch;
11512     PL_reg_flags = 0;
11513     PL_reg_eval_set = 0;
11514     PL_regnarrate = 0;
11515     PL_regprogram = (regnode*)NULL;
11516     PL_regindent = 0;
11517     PL_regcc = (CURCUR*)NULL;
11518     PL_reg_call_cc = (struct re_cc_state*)NULL;
11519     PL_reg_re = (regexp*)NULL;
11520     PL_reg_ganch = Nullch;
11521     PL_reg_sv = Nullsv;
11522     PL_reg_match_utf8 = FALSE;
11523     PL_reg_magic = (MAGIC*)NULL;
11524     PL_reg_oldpos = 0;
11525     PL_reg_oldcurpm = (PMOP*)NULL;
11526     PL_reg_curpm = (PMOP*)NULL;
11527     PL_reg_oldsaved = Nullch;
11528     PL_reg_oldsavedlen = 0;
11529     PL_reg_maxiter = 0;
11530     PL_reg_leftiter = 0;
11531     PL_reg_poscache = Nullch;
11532     PL_reg_poscache_size= 0;
11533    
11534     /* RE engine - function pointers */
11535     PL_regcompp = proto_perl->Tregcompp;
11536     PL_regexecp = proto_perl->Tregexecp;
11537     PL_regint_start = proto_perl->Tregint_start;
11538     PL_regint_string = proto_perl->Tregint_string;
11539     PL_regfree = proto_perl->Tregfree;
11540    
11541     PL_reginterp_cnt = 0;
11542     PL_reg_starttry = 0;
11543    
11544     /* Pluggable optimizer */
11545     PL_peepp = proto_perl->Tpeepp;
11546    
11547     PL_stashcache = newHV();
11548    
11549     if (!(flags & CLONEf_KEEP_PTR_TABLE)) {
11550     ptr_table_free(PL_ptr_table);
11551     PL_ptr_table = NULL;
11552     }
11553    
11554     /* Call the ->CLONE method, if it exists, for each of the stashes
11555     identified by sv_dup() above.
11556     */
11557     while(av_len(param->stashes) != -1) {
11558     HV* stash = (HV*) av_shift(param->stashes);
11559     GV* cloner = gv_fetchmethod_autoload(stash, "CLONE", 0);
11560     if (cloner && GvCV(cloner)) {
11561     dSP;
11562     ENTER;
11563     SAVETMPS;
11564     PUSHMARK(SP);
11565     XPUSHs(sv_2mortal(newSVpv(HvNAME(stash), 0)));
11566     PUTBACK;
11567     call_sv((SV*)GvCV(cloner), G_DISCARD);
11568     FREETMPS;
11569     LEAVE;
11570     }
11571     }
11572    
11573     SvREFCNT_dec(param->stashes);
11574    
11575     return my_perl;
11576     }
11577    
11578     #endif /* USE_ITHREADS */
11579    
11580     /*
11581     =head1 Unicode Support
11582    
11583     =for apidoc sv_recode_to_utf8
11584    
11585     The encoding is assumed to be an Encode object, on entry the PV
11586     of the sv is assumed to be octets in that encoding, and the sv
11587     will be converted into Unicode (and UTF-8).
11588    
11589     If the sv already is UTF-8 (or if it is not POK), or if the encoding
11590     is not a reference, nothing is done to the sv. If the encoding is not
11591     an C<Encode::XS> Encoding object, bad things will happen.
11592     (See F<lib/encoding.pm> and L<Encode>).
11593    
11594     The PV of the sv is returned.
11595    
11596     =cut */
11597    
11598     char *
11599     Perl_sv_recode_to_utf8(pTHX_ SV *sv, SV *encoding)
11600     {
11601     if (SvPOK(sv) && !SvUTF8(sv) && !IN_BYTES && SvROK(encoding)) {
11602     SV *uni;
11603     STRLEN len;
11604     char *s;
11605     dSP;
11606     ENTER;
11607     SAVETMPS;
11608     save_re_context();
11609     PUSHMARK(sp);
11610     EXTEND(SP, 3);
11611     XPUSHs(encoding);
11612     XPUSHs(sv);
11613     /*
11614     NI-S 2002/07/09
11615     Passing sv_yes is wrong - it needs to be or'ed set of constants
11616     for Encode::XS, while UTf-8 decode (currently) assumes a true value means
11617     remove converted chars from source.
11618    
11619     Both will default the value - let them.
11620    
11621     XPUSHs(&PL_sv_yes);
11622     */
11623     PUTBACK;
11624     call_method("decode", G_SCALAR);
11625     SPAGAIN;
11626     uni = POPs;
11627     PUTBACK;
11628     s = SvPV(uni, len);
11629     if (s != SvPVX(sv)) {
11630     SvGROW(sv, len + 1);
11631     Move(s, SvPVX(sv), len, char);
11632     SvCUR_set(sv, len);
11633     SvPVX(sv)[len] = 0;
11634     }
11635     FREETMPS;
11636     LEAVE;
11637     SvUTF8_on(sv);
11638     return SvPVX(sv);
11639     }
11640     return SvPOKp(sv) ? SvPVX(sv) : NULL;
11641     }
11642    
11643     /*
11644     =for apidoc sv_cat_decode
11645    
11646     The encoding is assumed to be an Encode object, the PV of the ssv is
11647     assumed to be octets in that encoding and decoding the input starts
11648     from the position which (PV + *offset) pointed to. The dsv will be
11649     concatenated the decoded UTF-8 string from ssv. Decoding will terminate
11650     when the string tstr appears in decoding output or the input ends on
11651     the PV of the ssv. The value which the offset points will be modified
11652     to the last input position on the ssv.
11653    
11654     Returns TRUE if the terminator was found, else returns FALSE.
11655    
11656     =cut */
11657    
11658     bool
11659     Perl_sv_cat_decode(pTHX_ SV *dsv, SV *encoding,
11660     SV *ssv, int *offset, char *tstr, int tlen)
11661     {
11662     bool ret = FALSE;
11663     if (SvPOK(ssv) && SvPOK(dsv) && SvROK(encoding) && offset) {
11664     SV *offsv;
11665     dSP;
11666     ENTER;
11667     SAVETMPS;
11668     save_re_context();
11669     PUSHMARK(sp);
11670     EXTEND(SP, 6);
11671     XPUSHs(encoding);
11672     XPUSHs(dsv);
11673     XPUSHs(ssv);
11674     XPUSHs(offsv = sv_2mortal(newSViv(*offset)));
11675     XPUSHs(sv_2mortal(newSVpvn(tstr, tlen)));
11676     PUTBACK;
11677     call_method("cat_decode", G_SCALAR);
11678     SPAGAIN;
11679     ret = SvTRUE(TOPs);
11680     *offset = SvIV(offsv);
11681     PUTBACK;
11682     FREETMPS;
11683     LEAVE;
11684     }
11685     else
11686     Perl_croak(aTHX_ "Invalid argument to sv_cat_decode");
11687     return ret;
11688     }
11689    
11690     /*
11691     * Local variables:
11692     * c-indentation-style: bsd
11693     * c-basic-offset: 4
11694     * indent-tabs-mode: t
11695     * End:
11696     *
11697     * vim: shiftwidth=4:
11698     */