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