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