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