In sv.c, _all_ {new,del}_X* macros can be *_body_allocated.
[p5sagit/p5-mst-13.2.git] / sv.c
1 /*    sv.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 by Larry Wall
5  *    and others
6  *
7  *    You may distribute under the terms of either the GNU General Public
8  *    License or the Artistic License, as specified in the README file.
9  *
10  */
11
12 /*
13  * 'I wonder what the Entish is for "yes" and "no",' he thought.
14  *                                                      --Pippin
15  *
16  *     [p.480 of _The Lord of the Rings_, III/iv: "Treebeard"]
17  */
18
19 /*
20  *
21  *
22  * This file contains the code that creates, manipulates and destroys
23  * scalar values (SVs). The other types (AV, HV, GV, etc.) reuse the
24  * structure of an SV, so their creation and destruction is handled
25  * here; higher-level functions are in av.c, hv.c, and so on. Opcode
26  * level functions (eg. substr, split, join) for each of the types are
27  * in the pp*.c files.
28  */
29
30 #include "EXTERN.h"
31 #define PERL_IN_SV_C
32 #include "perl.h"
33 #include "regcomp.h"
34
35 #define FCALL *f
36
37 #ifdef __Lynx__
38 /* Missing proto on LynxOS */
39   char *gconvert(double, int, int,  char *);
40 #endif
41
42 #ifdef PERL_UTF8_CACHE_ASSERT
43 /* if adding more checks watch out for the following tests:
44  *   t/op/index.t t/op/length.t t/op/pat.t t/op/substr.t
45  *   lib/utf8.t lib/Unicode/Collate/t/index.t
46  * --jhi
47  */
48 #   define ASSERT_UTF8_CACHE(cache) \
49     STMT_START { if (cache) { assert((cache)[0] <= (cache)[1]); \
50                               assert((cache)[2] <= (cache)[3]); \
51                               assert((cache)[3] <= (cache)[1]);} \
52                               } STMT_END
53 #else
54 #   define ASSERT_UTF8_CACHE(cache) NOOP
55 #endif
56
57 #ifdef PERL_OLD_COPY_ON_WRITE
58 #define SV_COW_NEXT_SV(sv)      INT2PTR(SV *,SvUVX(sv))
59 #define SV_COW_NEXT_SV_SET(current,next)        SvUV_set(current, PTR2UV(next))
60 /* This is a pessimistic view. Scalar must be purely a read-write PV to copy-
61    on-write.  */
62 #endif
63
64 /* ============================================================================
65
66 =head1 Allocation and deallocation of SVs.
67
68 An SV (or AV, HV, etc.) is allocated in two parts: the head (struct
69 sv, av, hv...) contains type and reference count information, and for
70 many types, a pointer to the body (struct xrv, xpv, xpviv...), which
71 contains fields specific to each type.  Some types store all they need
72 in the head, so don't have a body.
73
74 In all but the most memory-paranoid configuations (ex: PURIFY), heads
75 and bodies are allocated out of arenas, which by default are
76 approximately 4K chunks of memory parcelled up into N heads or bodies.
77 Sv-bodies are allocated by their sv-type, guaranteeing size
78 consistency needed to allocate safely from arrays.
79
80 For SV-heads, the first slot in each arena is reserved, and holds a
81 link to the next arena, some flags, and a note of the number of slots.
82 Snaked through each arena chain is a linked list of free items; when
83 this becomes empty, an extra arena is allocated and divided up into N
84 items which are threaded into the free list.
85
86 SV-bodies are similar, but they use arena-sets by default, which
87 separate the link and info from the arena itself, and reclaim the 1st
88 slot in the arena.  SV-bodies are further described later.
89
90 The following global variables are associated with arenas:
91
92     PL_sv_arenaroot     pointer to list of SV arenas
93     PL_sv_root          pointer to list of free SV structures
94
95     PL_body_arenas      head of linked-list of body arenas
96     PL_body_roots[]     array of pointers to list of free bodies of svtype
97                         arrays are indexed by the svtype needed
98
99 A few special SV heads are not allocated from an arena, but are
100 instead directly created in the interpreter structure, eg PL_sv_undef.
101 The size of arenas can be changed from the default by setting
102 PERL_ARENA_SIZE appropriately at compile time.
103
104 The SV arena serves the secondary purpose of allowing still-live SVs
105 to be located and destroyed during final cleanup.
106
107 At the lowest level, the macros new_SV() and del_SV() grab and free
108 an SV head.  (If debugging with -DD, del_SV() calls the function S_del_sv()
109 to return the SV to the free list with error checking.) new_SV() calls
110 more_sv() / sv_add_arena() to add an extra arena if the free list is empty.
111 SVs in the free list have their SvTYPE field set to all ones.
112
113 At the time of very final cleanup, sv_free_arenas() is called from
114 perl_destruct() to physically free all the arenas allocated since the
115 start of the interpreter.
116
117 The function visit() scans the SV arenas list, and calls a specified
118 function for each SV it finds which is still live - ie which has an SvTYPE
119 other than all 1's, and a non-zero SvREFCNT. visit() is used by the
120 following functions (specified as [function that calls visit()] / [function
121 called by visit() for each SV]):
122
123     sv_report_used() / do_report_used()
124                         dump all remaining SVs (debugging aid)
125
126     sv_clean_objs() / do_clean_objs(),do_clean_named_objs()
127                         Attempt to free all objects pointed to by RVs,
128                         and, unless DISABLE_DESTRUCTOR_KLUDGE is defined,
129                         try to do the same for all objects indirectly
130                         referenced by typeglobs too.  Called once from
131                         perl_destruct(), prior to calling sv_clean_all()
132                         below.
133
134     sv_clean_all() / do_clean_all()
135                         SvREFCNT_dec(sv) each remaining SV, possibly
136                         triggering an sv_free(). It also sets the
137                         SVf_BREAK flag on the SV to indicate that the
138                         refcnt has been artificially lowered, and thus
139                         stopping sv_free() from giving spurious warnings
140                         about SVs which unexpectedly have a refcnt
141                         of zero.  called repeatedly from perl_destruct()
142                         until there are no SVs left.
143
144 =head2 Arena allocator API Summary
145
146 Private API to rest of sv.c
147
148     new_SV(),  del_SV(),
149
150     new_XIV(), del_XIV(),
151     new_XNV(), del_XNV(),
152     etc
153
154 Public API:
155
156     sv_report_used(), sv_clean_objs(), sv_clean_all(), sv_free_arenas()
157
158 =cut
159
160  * ========================================================================= */
161
162 /*
163  * "A time to plant, and a time to uproot what was planted..."
164  */
165
166 void
167 Perl_offer_nice_chunk(pTHX_ void *const chunk, const U32 chunk_size)
168 {
169     dVAR;
170     void *new_chunk;
171     U32 new_chunk_size;
172
173     PERL_ARGS_ASSERT_OFFER_NICE_CHUNK;
174
175     new_chunk = (void *)(chunk);
176     new_chunk_size = (chunk_size);
177     if (new_chunk_size > PL_nice_chunk_size) {
178         Safefree(PL_nice_chunk);
179         PL_nice_chunk = (char *) new_chunk;
180         PL_nice_chunk_size = new_chunk_size;
181     } else {
182         Safefree(chunk);
183     }
184 }
185
186 #ifdef PERL_MEM_LOG
187 #  define MEM_LOG_NEW_SV(sv, file, line, func)  \
188             Perl_mem_log_new_sv(sv, file, line, func)
189 #  define MEM_LOG_DEL_SV(sv, file, line, func)  \
190             Perl_mem_log_del_sv(sv, file, line, func)
191 #else
192 #  define MEM_LOG_NEW_SV(sv, file, line, func)  NOOP
193 #  define MEM_LOG_DEL_SV(sv, file, line, func)  NOOP
194 #endif
195
196 #ifdef DEBUG_LEAKING_SCALARS
197 #  define FREE_SV_DEBUG_FILE(sv) Safefree((sv)->sv_debug_file)
198 #  define DEBUG_SV_SERIAL(sv)                                               \
199     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) del_SV\n",    \
200             PTR2UV(sv), (long)(sv)->sv_debug_serial))
201 #else
202 #  define FREE_SV_DEBUG_FILE(sv)
203 #  define DEBUG_SV_SERIAL(sv)   NOOP
204 #endif
205
206 #ifdef PERL_POISON
207 #  define SvARENA_CHAIN(sv)     ((sv)->sv_u.svu_rv)
208 #  define SvARENA_CHAIN_SET(sv,val)     (sv)->sv_u.svu_rv = MUTABLE_SV((val))
209 /* Whilst I'd love to do this, it seems that things like to check on
210    unreferenced scalars
211 #  define POSION_SV_HEAD(sv)    PoisonNew(sv, 1, struct STRUCT_SV)
212 */
213 #  define POSION_SV_HEAD(sv)    PoisonNew(&SvANY(sv), 1, void *), \
214                                 PoisonNew(&SvREFCNT(sv), 1, U32)
215 #else
216 #  define SvARENA_CHAIN(sv)     SvANY(sv)
217 #  define SvARENA_CHAIN_SET(sv,val)     SvANY(sv) = (void *)(val)
218 #  define POSION_SV_HEAD(sv)
219 #endif
220
221 /* Mark an SV head as unused, and add to free list.
222  *
223  * If SVf_BREAK is set, skip adding it to the free list, as this SV had
224  * its refcount artificially decremented during global destruction, so
225  * there may be dangling pointers to it. The last thing we want in that
226  * case is for it to be reused. */
227
228 #define plant_SV(p) \
229     STMT_START {                                        \
230         const U32 old_flags = SvFLAGS(p);                       \
231         MEM_LOG_DEL_SV(p, __FILE__, __LINE__, FUNCTION__);  \
232         DEBUG_SV_SERIAL(p);                             \
233         FREE_SV_DEBUG_FILE(p);                          \
234         POSION_SV_HEAD(p);                              \
235         SvFLAGS(p) = SVTYPEMASK;                        \
236         if (!(old_flags & SVf_BREAK)) {         \
237             SvARENA_CHAIN_SET(p, PL_sv_root);   \
238             PL_sv_root = (p);                           \
239         }                                               \
240         --PL_sv_count;                                  \
241     } STMT_END
242
243 #define uproot_SV(p) \
244     STMT_START {                                        \
245         (p) = PL_sv_root;                               \
246         PL_sv_root = MUTABLE_SV(SvARENA_CHAIN(p));              \
247         ++PL_sv_count;                                  \
248     } STMT_END
249
250
251 /* make some more SVs by adding another arena */
252
253 STATIC SV*
254 S_more_sv(pTHX)
255 {
256     dVAR;
257     SV* sv;
258
259     if (PL_nice_chunk) {
260         sv_add_arena(PL_nice_chunk, PL_nice_chunk_size, 0);
261         PL_nice_chunk = NULL;
262         PL_nice_chunk_size = 0;
263     }
264     else {
265         char *chunk;                /* must use New here to match call to */
266         Newx(chunk,PERL_ARENA_SIZE,char);  /* Safefree() in sv_free_arenas() */
267         sv_add_arena(chunk, PERL_ARENA_SIZE, 0);
268     }
269     uproot_SV(sv);
270     return sv;
271 }
272
273 /* new_SV(): return a new, empty SV head */
274
275 #ifdef DEBUG_LEAKING_SCALARS
276 /* provide a real function for a debugger to play with */
277 STATIC SV*
278 S_new_SV(pTHX_ const char *file, int line, const char *func)
279 {
280     SV* sv;
281
282     if (PL_sv_root)
283         uproot_SV(sv);
284     else
285         sv = S_more_sv(aTHX);
286     SvANY(sv) = 0;
287     SvREFCNT(sv) = 1;
288     SvFLAGS(sv) = 0;
289     sv->sv_debug_optype = PL_op ? PL_op->op_type : 0;
290     sv->sv_debug_line = (U16) (PL_parser && PL_parser->copline != NOLINE
291                 ? PL_parser->copline
292                 :  PL_curcop
293                     ? CopLINE(PL_curcop)
294                     : 0
295             );
296     sv->sv_debug_inpad = 0;
297     sv->sv_debug_cloned = 0;
298     sv->sv_debug_file = PL_curcop ? savepv(CopFILE(PL_curcop)): NULL;
299
300     sv->sv_debug_serial = PL_sv_serial++;
301
302     MEM_LOG_NEW_SV(sv, file, line, func);
303     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) new_SV (from %s:%d [%s])\n",
304             PTR2UV(sv), (long)sv->sv_debug_serial, file, line, func));
305
306     return sv;
307 }
308 #  define new_SV(p) (p)=S_new_SV(aTHX_ __FILE__, __LINE__, FUNCTION__)
309
310 #else
311 #  define new_SV(p) \
312     STMT_START {                                        \
313         if (PL_sv_root)                                 \
314             uproot_SV(p);                               \
315         else                                            \
316             (p) = S_more_sv(aTHX);                      \
317         SvANY(p) = 0;                                   \
318         SvREFCNT(p) = 1;                                \
319         SvFLAGS(p) = 0;                                 \
320         MEM_LOG_NEW_SV(p, __FILE__, __LINE__, FUNCTION__);  \
321     } STMT_END
322 #endif
323
324
325 /* del_SV(): return an empty SV head to the free list */
326
327 #ifdef DEBUGGING
328
329 #define del_SV(p) \
330     STMT_START {                                        \
331         if (DEBUG_D_TEST)                               \
332             del_sv(p);                                  \
333         else                                            \
334             plant_SV(p);                                \
335     } STMT_END
336
337 STATIC void
338 S_del_sv(pTHX_ SV *p)
339 {
340     dVAR;
341
342     PERL_ARGS_ASSERT_DEL_SV;
343
344     if (DEBUG_D_TEST) {
345         SV* sva;
346         bool ok = 0;
347         for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
348             const SV * const sv = sva + 1;
349             const SV * const svend = &sva[SvREFCNT(sva)];
350             if (p >= sv && p < svend) {
351                 ok = 1;
352                 break;
353             }
354         }
355         if (!ok) {
356             Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
357                              "Attempt to free non-arena SV: 0x%"UVxf
358                              pTHX__FORMAT, PTR2UV(p) pTHX__VALUE);
359             return;
360         }
361     }
362     plant_SV(p);
363 }
364
365 #else /* ! DEBUGGING */
366
367 #define del_SV(p)   plant_SV(p)
368
369 #endif /* DEBUGGING */
370
371
372 /*
373 =head1 SV Manipulation Functions
374
375 =for apidoc sv_add_arena
376
377 Given a chunk of memory, link it to the head of the list of arenas,
378 and split it into a list of free SVs.
379
380 =cut
381 */
382
383 static void
384 S_sv_add_arena(pTHX_ char *const ptr, const U32 size, const U32 flags)
385 {
386     dVAR;
387     SV *const sva = MUTABLE_SV(ptr);
388     register SV* sv;
389     register SV* svend;
390
391     PERL_ARGS_ASSERT_SV_ADD_ARENA;
392
393     /* The first SV in an arena isn't an SV. */
394     SvANY(sva) = (void *) PL_sv_arenaroot;              /* ptr to next arena */
395     SvREFCNT(sva) = size / sizeof(SV);          /* number of SV slots */
396     SvFLAGS(sva) = flags;                       /* FAKE if not to be freed */
397
398     PL_sv_arenaroot = sva;
399     PL_sv_root = sva + 1;
400
401     svend = &sva[SvREFCNT(sva) - 1];
402     sv = sva + 1;
403     while (sv < svend) {
404         SvARENA_CHAIN_SET(sv, (sv + 1));
405 #ifdef DEBUGGING
406         SvREFCNT(sv) = 0;
407 #endif
408         /* Must always set typemask because it's always checked in on cleanup
409            when the arenas are walked looking for objects.  */
410         SvFLAGS(sv) = SVTYPEMASK;
411         sv++;
412     }
413     SvARENA_CHAIN_SET(sv, 0);
414 #ifdef DEBUGGING
415     SvREFCNT(sv) = 0;
416 #endif
417     SvFLAGS(sv) = SVTYPEMASK;
418 }
419
420 /* visit(): call the named function for each non-free SV in the arenas
421  * whose flags field matches the flags/mask args. */
422
423 STATIC I32
424 S_visit(pTHX_ SVFUNC_t f, const U32 flags, const U32 mask)
425 {
426     dVAR;
427     SV* sva;
428     I32 visited = 0;
429
430     PERL_ARGS_ASSERT_VISIT;
431
432     for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
433         register const SV * const svend = &sva[SvREFCNT(sva)];
434         register SV* sv;
435         for (sv = sva + 1; sv < svend; ++sv) {
436             if (SvTYPE(sv) != SVTYPEMASK
437                     && (sv->sv_flags & mask) == flags
438                     && SvREFCNT(sv))
439             {
440                 (FCALL)(aTHX_ sv);
441                 ++visited;
442             }
443         }
444     }
445     return visited;
446 }
447
448 #ifdef DEBUGGING
449
450 /* called by sv_report_used() for each live SV */
451
452 static void
453 do_report_used(pTHX_ SV *const sv)
454 {
455     if (SvTYPE(sv) != SVTYPEMASK) {
456         PerlIO_printf(Perl_debug_log, "****\n");
457         sv_dump(sv);
458     }
459 }
460 #endif
461
462 /*
463 =for apidoc sv_report_used
464
465 Dump the contents of all SVs not yet freed. (Debugging aid).
466
467 =cut
468 */
469
470 void
471 Perl_sv_report_used(pTHX)
472 {
473 #ifdef DEBUGGING
474     visit(do_report_used, 0, 0);
475 #else
476     PERL_UNUSED_CONTEXT;
477 #endif
478 }
479
480 /* called by sv_clean_objs() for each live SV */
481
482 static void
483 do_clean_objs(pTHX_ SV *const ref)
484 {
485     dVAR;
486     assert (SvROK(ref));
487     {
488         SV * const target = SvRV(ref);
489         if (SvOBJECT(target)) {
490             DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning object ref:\n "), sv_dump(ref)));
491             if (SvWEAKREF(ref)) {
492                 sv_del_backref(target, ref);
493                 SvWEAKREF_off(ref);
494                 SvRV_set(ref, NULL);
495             } else {
496                 SvROK_off(ref);
497                 SvRV_set(ref, NULL);
498                 SvREFCNT_dec(target);
499             }
500         }
501     }
502
503     /* XXX Might want to check arrays, etc. */
504 }
505
506 /* called by sv_clean_objs() for each live SV */
507
508 #ifndef DISABLE_DESTRUCTOR_KLUDGE
509 static void
510 do_clean_named_objs(pTHX_ SV *const sv)
511 {
512     dVAR;
513     assert(SvTYPE(sv) == SVt_PVGV);
514     assert(isGV_with_GP(sv));
515     if (GvGP(sv)) {
516         if ((
517 #ifdef PERL_DONT_CREATE_GVSV
518              GvSV(sv) &&
519 #endif
520              SvOBJECT(GvSV(sv))) ||
521              (GvAV(sv) && SvOBJECT(GvAV(sv))) ||
522              (GvHV(sv) && SvOBJECT(GvHV(sv))) ||
523              /* In certain rare cases GvIOp(sv) can be NULL, which would make SvOBJECT(GvIO(sv)) dereference NULL. */
524              (GvIO(sv) ? (SvFLAGS(GvIOp(sv)) & SVs_OBJECT) : 0) ||
525              (GvCV(sv) && SvOBJECT(GvCV(sv))) )
526         {
527             DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning named glob object:\n "), sv_dump(sv)));
528             SvFLAGS(sv) |= SVf_BREAK;
529             SvREFCNT_dec(sv);
530         }
531     }
532 }
533 #endif
534
535 /*
536 =for apidoc sv_clean_objs
537
538 Attempt to destroy all objects not yet freed
539
540 =cut
541 */
542
543 void
544 Perl_sv_clean_objs(pTHX)
545 {
546     dVAR;
547     PL_in_clean_objs = TRUE;
548     visit(do_clean_objs, SVf_ROK, SVf_ROK);
549 #ifndef DISABLE_DESTRUCTOR_KLUDGE
550     /* some barnacles may yet remain, clinging to typeglobs */
551     visit(do_clean_named_objs, SVt_PVGV|SVpgv_GP, SVTYPEMASK|SVp_POK|SVpgv_GP);
552 #endif
553     PL_in_clean_objs = FALSE;
554 }
555
556 /* called by sv_clean_all() for each live SV */
557
558 static void
559 do_clean_all(pTHX_ SV *const sv)
560 {
561     dVAR;
562     if (sv == (const SV *) PL_fdpid || sv == (const SV *)PL_strtab) {
563         /* don't clean pid table and strtab */
564         return;
565     }
566     DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning loops: SV at 0x%"UVxf"\n", PTR2UV(sv)) ));
567     SvFLAGS(sv) |= SVf_BREAK;
568     SvREFCNT_dec(sv);
569 }
570
571 /*
572 =for apidoc sv_clean_all
573
574 Decrement the refcnt of each remaining SV, possibly triggering a
575 cleanup. This function may have to be called multiple times to free
576 SVs which are in complex self-referential hierarchies.
577
578 =cut
579 */
580
581 I32
582 Perl_sv_clean_all(pTHX)
583 {
584     dVAR;
585     I32 cleaned;
586     PL_in_clean_all = TRUE;
587     cleaned = visit(do_clean_all, 0,0);
588     PL_in_clean_all = FALSE;
589     return cleaned;
590 }
591
592 /*
593   ARENASETS: a meta-arena implementation which separates arena-info
594   into struct arena_set, which contains an array of struct
595   arena_descs, each holding info for a single arena.  By separating
596   the meta-info from the arena, we recover the 1st slot, formerly
597   borrowed for list management.  The arena_set is about the size of an
598   arena, avoiding the needless malloc overhead of a naive linked-list.
599
600   The cost is 1 arena-set malloc per ~320 arena-mallocs, + the unused
601   memory in the last arena-set (1/2 on average).  In trade, we get
602   back the 1st slot in each arena (ie 1.7% of a CV-arena, less for
603   smaller types).  The recovery of the wasted space allows use of
604   small arenas for large, rare body types, by changing array* fields
605   in body_details_by_type[] below.
606 */
607 struct arena_desc {
608     char       *arena;          /* the raw storage, allocated aligned */
609     size_t      size;           /* its size ~4k typ */
610     svtype      utype;          /* bodytype stored in arena */
611 };
612
613 struct arena_set;
614
615 /* Get the maximum number of elements in set[] such that struct arena_set
616    will fit within PERL_ARENA_SIZE, which is probably just under 4K, and
617    therefore likely to be 1 aligned memory page.  */
618
619 #define ARENAS_PER_SET  ((PERL_ARENA_SIZE - sizeof(struct arena_set*) \
620                           - 2 * sizeof(int)) / sizeof (struct arena_desc))
621
622 struct arena_set {
623     struct arena_set* next;
624     unsigned int   set_size;    /* ie ARENAS_PER_SET */
625     unsigned int   curr;        /* index of next available arena-desc */
626     struct arena_desc set[ARENAS_PER_SET];
627 };
628
629 /*
630 =for apidoc sv_free_arenas
631
632 Deallocate the memory used by all arenas. Note that all the individual SV
633 heads and bodies within the arenas must already have been freed.
634
635 =cut
636 */
637 void
638 Perl_sv_free_arenas(pTHX)
639 {
640     dVAR;
641     SV* sva;
642     SV* svanext;
643     unsigned int i;
644
645     /* Free arenas here, but be careful about fake ones.  (We assume
646        contiguity of the fake ones with the corresponding real ones.) */
647
648     for (sva = PL_sv_arenaroot; sva; sva = svanext) {
649         svanext = MUTABLE_SV(SvANY(sva));
650         while (svanext && SvFAKE(svanext))
651             svanext = MUTABLE_SV(SvANY(svanext));
652
653         if (!SvFAKE(sva))
654             Safefree(sva);
655     }
656
657     {
658         struct arena_set *aroot = (struct arena_set*) PL_body_arenas;
659
660         while (aroot) {
661             struct arena_set *current = aroot;
662             i = aroot->curr;
663             while (i--) {
664                 assert(aroot->set[i].arena);
665                 Safefree(aroot->set[i].arena);
666             }
667             aroot = aroot->next;
668             Safefree(current);
669         }
670     }
671     PL_body_arenas = 0;
672
673     i = PERL_ARENA_ROOTS_SIZE;
674     while (i--)
675         PL_body_roots[i] = 0;
676
677     Safefree(PL_nice_chunk);
678     PL_nice_chunk = NULL;
679     PL_nice_chunk_size = 0;
680     PL_sv_arenaroot = 0;
681     PL_sv_root = 0;
682 }
683
684 /*
685   Here are mid-level routines that manage the allocation of bodies out
686   of the various arenas.  There are 5 kinds of arenas:
687
688   1. SV-head arenas, which are discussed and handled above
689   2. regular body arenas
690   3. arenas for reduced-size bodies
691   4. Hash-Entry arenas
692
693   Arena types 2 & 3 are chained by body-type off an array of
694   arena-root pointers, which is indexed by svtype.  Some of the
695   larger/less used body types are malloced singly, since a large
696   unused block of them is wasteful.  Also, several svtypes dont have
697   bodies; the data fits into the sv-head itself.  The arena-root
698   pointer thus has a few unused root-pointers (which may be hijacked
699   later for arena types 4,5)
700
701   3 differs from 2 as an optimization; some body types have several
702   unused fields in the front of the structure (which are kept in-place
703   for consistency).  These bodies can be allocated in smaller chunks,
704   because the leading fields arent accessed.  Pointers to such bodies
705   are decremented to point at the unused 'ghost' memory, knowing that
706   the pointers are used with offsets to the real memory.
707
708   HE, HEK arenas are managed separately, with separate code, but may
709   be merge-able later..
710 */
711
712 /* get_arena(size): this creates custom-sized arenas
713    TBD: export properly for hv.c: S_more_he().
714 */
715 void*
716 Perl_get_arena(pTHX_ const size_t arena_size, const svtype bodytype)
717 {
718     dVAR;
719     struct arena_desc* adesc;
720     struct arena_set *aroot = (struct arena_set*) PL_body_arenas;
721     unsigned int curr;
722
723     /* shouldnt need this
724     if (!arena_size)    arena_size = PERL_ARENA_SIZE;
725     */
726
727     /* may need new arena-set to hold new arena */
728     if (!aroot || aroot->curr >= aroot->set_size) {
729         struct arena_set *newroot;
730         Newxz(newroot, 1, struct arena_set);
731         newroot->set_size = ARENAS_PER_SET;
732         newroot->next = aroot;
733         aroot = newroot;
734         PL_body_arenas = (void *) newroot;
735         DEBUG_m(PerlIO_printf(Perl_debug_log, "new arenaset %p\n", (void*)aroot));
736     }
737
738     /* ok, now have arena-set with at least 1 empty/available arena-desc */
739     curr = aroot->curr++;
740     adesc = &(aroot->set[curr]);
741     assert(!adesc->arena);
742     
743     Newx(adesc->arena, arena_size, char);
744     adesc->size = arena_size;
745     adesc->utype = bodytype;
746     DEBUG_m(PerlIO_printf(Perl_debug_log, "arena %d added: %p size %"UVuf"\n", 
747                           curr, (void*)adesc->arena, (UV)arena_size));
748
749     return adesc->arena;
750 }
751
752
753 /* return a thing to the free list */
754
755 #define del_body(thing, root)                   \
756     STMT_START {                                \
757         void ** const thing_copy = (void **)thing;\
758         *thing_copy = *root;                    \
759         *root = (void*)thing_copy;              \
760     } STMT_END
761
762 /* 
763
764 =head1 SV-Body Allocation
765
766 Allocation of SV-bodies is similar to SV-heads, differing as follows;
767 the allocation mechanism is used for many body types, so is somewhat
768 more complicated, it uses arena-sets, and has no need for still-live
769 SV detection.
770
771 At the outermost level, (new|del)_X*V macros return bodies of the
772 appropriate type.  These macros call either (new|del)_body_type or
773 (new|del)_body_allocated macro pairs, depending on specifics of the
774 type.  Most body types use the former pair, the latter pair is used to
775 allocate body types with "ghost fields".
776
777 "ghost fields" are fields that are unused in certain types, and
778 consequently don't need to actually exist.  They are declared because
779 they're part of a "base type", which allows use of functions as
780 methods.  The simplest examples are AVs and HVs, 2 aggregate types
781 which don't use the fields which support SCALAR semantics.
782
783 For these types, the arenas are carved up into appropriately sized
784 chunks, we thus avoid wasted memory for those unaccessed members.
785 When bodies are allocated, we adjust the pointer back in memory by the
786 size of the part not allocated, so it's as if we allocated the full
787 structure.  (But things will all go boom if you write to the part that
788 is "not there", because you'll be overwriting the last members of the
789 preceding structure in memory.)
790
791 We calculate the correction using the STRUCT_OFFSET macro on the first
792 member present. If the allocated structure is smaller (no initial NV
793 actually allocated) then the net effect is to subtract the size of the NV
794 from the pointer, to return a new pointer as if an initial NV were actually
795 allocated. (We were using structures named *_allocated for this, but
796 this turned out to be a subtle bug, because a structure without an NV
797 could have a lower alignment constraint, but the compiler is allowed to
798 optimised accesses based on the alignment constraint of the actual pointer
799 to the full structure, for example, using a single 64 bit load instruction
800 because it "knows" that two adjacent 32 bit members will be 8-byte aligned.)
801
802 This is the same trick as was used for NV and IV bodies. Ironically it
803 doesn't need to be used for NV bodies any more, because NV is now at
804 the start of the structure. IV bodies don't need it either, because
805 they are no longer allocated.
806
807 In turn, the new_body_* allocators call S_new_body(), which invokes
808 new_body_inline macro, which takes a lock, and takes a body off the
809 linked list at PL_body_roots[sv_type], calling S_more_bodies() if
810 necessary to refresh an empty list.  Then the lock is released, and
811 the body is returned.
812
813 S_more_bodies calls get_arena(), and carves it up into an array of N
814 bodies, which it strings into a linked list.  It looks up arena-size
815 and body-size from the body_details table described below, thus
816 supporting the multiple body-types.
817
818 If PURIFY is defined, or PERL_ARENA_SIZE=0, arenas are not used, and
819 the (new|del)_X*V macros are mapped directly to malloc/free.
820
821 */
822
823 /* 
824
825 For each sv-type, struct body_details bodies_by_type[] carries
826 parameters which control these aspects of SV handling:
827
828 Arena_size determines whether arenas are used for this body type, and if
829 so, how big they are.  PURIFY or PERL_ARENA_SIZE=0 set this field to
830 zero, forcing individual mallocs and frees.
831
832 Body_size determines how big a body is, and therefore how many fit into
833 each arena.  Offset carries the body-pointer adjustment needed for
834 "ghost fields", and is used in *_allocated macros.
835
836 But its main purpose is to parameterize info needed in
837 Perl_sv_upgrade().  The info here dramatically simplifies the function
838 vs the implementation in 5.8.8, making it table-driven.  All fields
839 are used for this, except for arena_size.
840
841 For the sv-types that have no bodies, arenas are not used, so those
842 PL_body_roots[sv_type] are unused, and can be overloaded.  In
843 something of a special case, SVt_NULL is borrowed for HE arenas;
844 PL_body_roots[HE_SVSLOT=SVt_NULL] is filled by S_more_he, but the
845 bodies_by_type[SVt_NULL] slot is not used, as the table is not
846 available in hv.c.
847
848 */
849
850 struct body_details {
851     U8 body_size;       /* Size to allocate  */
852     U8 copy;            /* Size of structure to copy (may be shorter)  */
853     U8 offset;
854     unsigned int type : 4;          /* We have space for a sanity check.  */
855     unsigned int cant_upgrade : 1;  /* Cannot upgrade this type */
856     unsigned int zero_nv : 1;       /* zero the NV when upgrading from this */
857     unsigned int arena : 1;         /* Allocated from an arena */
858     size_t arena_size;              /* Size of arena to allocate */
859 };
860
861 #define HADNV FALSE
862 #define NONV TRUE
863
864
865 #ifdef PURIFY
866 /* With -DPURFIY we allocate everything directly, and don't use arenas.
867    This seems a rather elegant way to simplify some of the code below.  */
868 #define HASARENA FALSE
869 #else
870 #define HASARENA TRUE
871 #endif
872 #define NOARENA FALSE
873
874 /* Size the arenas to exactly fit a given number of bodies.  A count
875    of 0 fits the max number bodies into a PERL_ARENA_SIZE.block,
876    simplifying the default.  If count > 0, the arena is sized to fit
877    only that many bodies, allowing arenas to be used for large, rare
878    bodies (XPVFM, XPVIO) without undue waste.  The arena size is
879    limited by PERL_ARENA_SIZE, so we can safely oversize the
880    declarations.
881  */
882 #define FIT_ARENA0(body_size)                           \
883     ((size_t)(PERL_ARENA_SIZE / body_size) * body_size)
884 #define FIT_ARENAn(count,body_size)                     \
885     ( count * body_size <= PERL_ARENA_SIZE)             \
886     ? count * body_size                                 \
887     : FIT_ARENA0 (body_size)
888 #define FIT_ARENA(count,body_size)                      \
889     count                                               \
890     ? FIT_ARENAn (count, body_size)                     \
891     : FIT_ARENA0 (body_size)
892
893 /* Calculate the length to copy. Specifically work out the length less any
894    final padding the compiler needed to add.  See the comment in sv_upgrade
895    for why copying the padding proved to be a bug.  */
896
897 #define copy_length(type, last_member) \
898         STRUCT_OFFSET(type, last_member) \
899         + sizeof (((type*)SvANY((const SV *)0))->last_member)
900
901 static const struct body_details bodies_by_type[] = {
902     { sizeof(HE), 0, 0, SVt_NULL,
903       FALSE, NONV, NOARENA, FIT_ARENA(0, sizeof(HE)) },
904
905     /* The bind placeholder pretends to be an RV for now.
906        Also it's marked as "can't upgrade" to stop anyone using it before it's
907        implemented.  */
908     { 0, 0, 0, SVt_BIND, TRUE, NONV, NOARENA, 0 },
909
910     /* IVs are in the head, so the allocation size is 0.  */
911     { 0,
912       sizeof(IV), /* This is used to copy out the IV body.  */
913       STRUCT_OFFSET(XPVIV, xiv_iv), SVt_IV, FALSE, NONV,
914       NOARENA /* IVS don't need an arena  */, 0
915     },
916
917     /* 8 bytes on most ILP32 with IEEE doubles */
918     { sizeof(NV), sizeof(NV), 0, SVt_NV, FALSE, HADNV, HASARENA,
919       FIT_ARENA(0, sizeof(NV)) },
920
921     /* 8 bytes on most ILP32 with IEEE doubles */
922     { sizeof(XPV) - STRUCT_OFFSET(XPV, xpv_cur),
923       copy_length(XPV, xpv_len) - STRUCT_OFFSET(XPV, xpv_cur),
924       + STRUCT_OFFSET(XPV, xpv_cur),
925       SVt_PV, FALSE, NONV, HASARENA,
926       FIT_ARENA(0, sizeof(XPV) - STRUCT_OFFSET(XPV, xpv_cur)) },
927
928     /* 12 */
929     { sizeof(XPVIV) - STRUCT_OFFSET(XPV, xpv_cur),
930       copy_length(XPVIV, xiv_u) - STRUCT_OFFSET(XPV, xpv_cur),
931       + STRUCT_OFFSET(XPVIV, xpv_cur),
932       SVt_PVIV, FALSE, NONV, HASARENA,
933       FIT_ARENA(0, sizeof(XPV) - STRUCT_OFFSET(XPV, xpv_cur)) },
934
935     /* 20 */
936     { sizeof(XPVNV), copy_length(XPVNV, xiv_u), 0, SVt_PVNV, FALSE, HADNV,
937       HASARENA, FIT_ARENA(0, sizeof(XPVNV)) },
938
939     /* 28 */
940     { sizeof(XPVMG), copy_length(XPVMG, xmg_stash), 0, SVt_PVMG, FALSE, HADNV,
941       HASARENA, FIT_ARENA(0, sizeof(XPVMG)) },
942
943     /* something big */
944     { sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur),
945       sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur),
946       + STRUCT_OFFSET(regexp, xpv_cur),
947       SVt_REGEXP, FALSE, NONV, HASARENA,
948       FIT_ARENA(0, sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur))
949     },
950
951     /* 48 */
952     { sizeof(XPVGV), sizeof(XPVGV), 0, SVt_PVGV, TRUE, HADNV,
953       HASARENA, FIT_ARENA(0, sizeof(XPVGV)) },
954     
955     /* 64 */
956     { sizeof(XPVLV), sizeof(XPVLV), 0, SVt_PVLV, TRUE, HADNV,
957       HASARENA, FIT_ARENA(0, sizeof(XPVLV)) },
958
959     { sizeof(XPVAV) - STRUCT_OFFSET(XPVAV, xav_fill),
960       copy_length(XPVAV, xmg_stash) - STRUCT_OFFSET(XPVAV, xav_fill),
961       + STRUCT_OFFSET(XPVAV, xav_fill),
962       SVt_PVAV, TRUE, NONV, HASARENA,
963       FIT_ARENA(0, sizeof(XPVAV) - STRUCT_OFFSET(XPVAV, xav_fill)) },
964
965     { sizeof(XPVHV) - STRUCT_OFFSET(XPVHV, xhv_fill),
966       copy_length(XPVHV, xmg_stash) - STRUCT_OFFSET(XPVHV, xhv_fill),
967       + STRUCT_OFFSET(XPVHV, xhv_fill),
968       SVt_PVHV, TRUE, NONV, HASARENA,
969       FIT_ARENA(0, sizeof(XPVHV) - STRUCT_OFFSET(XPVHV, xhv_fill)) },
970
971     /* 56 */
972     { sizeof(XPVCV) - STRUCT_OFFSET(XPVCV, xpv_cur),
973       sizeof(XPVCV) - STRUCT_OFFSET(XPVCV, xpv_cur),
974       + STRUCT_OFFSET(XPVCV, xpv_cur),
975       SVt_PVCV, TRUE, NONV, HASARENA,
976       FIT_ARENA(0, sizeof(XPVCV) - STRUCT_OFFSET(XPVCV, xpv_cur)) },
977
978     { sizeof(XPVFM) - STRUCT_OFFSET(XPVFM, xpv_cur),
979       sizeof(XPVFM) - STRUCT_OFFSET(XPVFM, xpv_cur),
980       + STRUCT_OFFSET(XPVFM, xpv_cur),
981       SVt_PVFM, TRUE, NONV, NOARENA,
982       FIT_ARENA(20, sizeof(XPVFM) - STRUCT_OFFSET(XPVFM, xpv_cur)) },
983
984     /* XPVIO is 84 bytes, fits 48x */
985     { sizeof(XPVIO) - STRUCT_OFFSET(XPVIO, xpv_cur),
986       sizeof(XPVIO) - STRUCT_OFFSET(XPVIO, xpv_cur),
987       + STRUCT_OFFSET(XPVIO, xpv_cur),
988       SVt_PVIO, TRUE, NONV, HASARENA,
989       FIT_ARENA(24, sizeof(XPVIO) - STRUCT_OFFSET(XPVIO, xpv_cur)) },
990 };
991
992 #define new_body_allocated(sv_type)             \
993     (void *)((char *)S_new_body(aTHX_ sv_type)  \
994              - bodies_by_type[sv_type].offset)
995
996 #define del_body_allocated(p, sv_type)          \
997     del_body(p + bodies_by_type[sv_type].offset, &PL_body_roots[sv_type])
998
999
1000 #define my_safemalloc(s)        (void*)safemalloc(s)
1001 #define my_safecalloc(s)        (void*)safecalloc(s, 1)
1002 #define my_safefree(p)  safefree((char*)p)
1003
1004 #ifdef PURIFY
1005
1006 #define new_XNV()       my_safemalloc(sizeof(XPVNV))
1007 #define del_XNV(p)      my_safefree(p)
1008
1009 #define new_XPVNV()     my_safemalloc(sizeof(XPVNV))
1010 #define del_XPVNV(p)    my_safefree(p)
1011
1012 #define new_XPVAV()     my_safemalloc(sizeof(XPVAV))
1013 #define del_XPVAV(p)    my_safefree(p)
1014
1015 #define new_XPVHV()     my_safemalloc(sizeof(XPVHV))
1016 #define del_XPVHV(p)    my_safefree(p)
1017
1018 #define new_XPVMG()     my_safemalloc(sizeof(XPVMG))
1019 #define del_XPVMG(p)    my_safefree(p)
1020
1021 #define new_XPVGV()     my_safemalloc(sizeof(XPVGV))
1022 #define del_XPVGV(p)    my_safefree(p)
1023
1024 #else /* !PURIFY */
1025
1026 #define new_XNV()       new_body_allocated(SVt_NV)
1027 #define del_XNV(p)      del_body_allocated(p, SVt_NV)
1028
1029 #define new_XPVNV()     new_body_allocated(SVt_PVNV)
1030 #define del_XPVNV(p)    del_body_allocated(p, SVt_PVNV)
1031
1032 #define new_XPVAV()     new_body_allocated(SVt_PVAV)
1033 #define del_XPVAV(p)    del_body_allocated(p, SVt_PVAV)
1034
1035 #define new_XPVHV()     new_body_allocated(SVt_PVHV)
1036 #define del_XPVHV(p)    del_body_allocated(p, SVt_PVHV)
1037
1038 #define new_XPVMG()     new_body_allocated(SVt_PVMG)
1039 #define del_XPVMG(p)    del_body_allocated(p, SVt_PVMG)
1040
1041 #define new_XPVGV()     new_body_allocated(SVt_PVGV)
1042 #define del_XPVGV(p)    del_body_allocated(p, SVt_PVGV)
1043
1044 #endif /* PURIFY */
1045
1046 /* no arena for you! */
1047
1048 #define new_NOARENA(details) \
1049         my_safemalloc((details)->body_size + (details)->offset)
1050 #define new_NOARENAZ(details) \
1051         my_safecalloc((details)->body_size + (details)->offset)
1052
1053 STATIC void *
1054 S_more_bodies (pTHX_ const svtype sv_type)
1055 {
1056     dVAR;
1057     void ** const root = &PL_body_roots[sv_type];
1058     const struct body_details * const bdp = &bodies_by_type[sv_type];
1059     const size_t body_size = bdp->body_size;
1060     char *start;
1061     const char *end;
1062     const size_t arena_size = Perl_malloc_good_size(bdp->arena_size);
1063 #if defined(DEBUGGING) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
1064     static bool done_sanity_check;
1065
1066     /* PERL_GLOBAL_STRUCT_PRIVATE cannot coexist with global
1067      * variables like done_sanity_check. */
1068     if (!done_sanity_check) {
1069         unsigned int i = SVt_LAST;
1070
1071         done_sanity_check = TRUE;
1072
1073         while (i--)
1074             assert (bodies_by_type[i].type == i);
1075     }
1076 #endif
1077
1078     assert(bdp->arena_size);
1079
1080     start = (char*) Perl_get_arena(aTHX_ arena_size, sv_type);
1081
1082     end = start + arena_size - 2 * body_size;
1083
1084     /* computed count doesnt reflect the 1st slot reservation */
1085 #if defined(MYMALLOC) || defined(HAS_MALLOC_GOOD_SIZE)
1086     DEBUG_m(PerlIO_printf(Perl_debug_log,
1087                           "arena %p end %p arena-size %d (from %d) type %d "
1088                           "size %d ct %d\n",
1089                           (void*)start, (void*)end, (int)arena_size,
1090                           (int)bdp->arena_size, sv_type, (int)body_size,
1091                           (int)arena_size / (int)body_size));
1092 #else
1093     DEBUG_m(PerlIO_printf(Perl_debug_log,
1094                           "arena %p end %p arena-size %d type %d size %d ct %d\n",
1095                           (void*)start, (void*)end,
1096                           (int)bdp->arena_size, sv_type, (int)body_size,
1097                           (int)bdp->arena_size / (int)body_size));
1098 #endif
1099     *root = (void *)start;
1100
1101     while (start <= end) {
1102         char * const next = start + body_size;
1103         *(void**) start = (void *)next;
1104         start = next;
1105     }
1106     *(void **)start = 0;
1107
1108     return *root;
1109 }
1110
1111 /* grab a new thing from the free list, allocating more if necessary.
1112    The inline version is used for speed in hot routines, and the
1113    function using it serves the rest (unless PURIFY).
1114 */
1115 #define new_body_inline(xpv, sv_type) \
1116     STMT_START { \
1117         void ** const r3wt = &PL_body_roots[sv_type]; \
1118         xpv = (PTR_TBL_ENT_t*) (*((void **)(r3wt))      \
1119           ? *((void **)(r3wt)) : more_bodies(sv_type)); \
1120         *(r3wt) = *(void**)(xpv); \
1121     } STMT_END
1122
1123 #ifndef PURIFY
1124
1125 STATIC void *
1126 S_new_body(pTHX_ const svtype sv_type)
1127 {
1128     dVAR;
1129     void *xpv;
1130     new_body_inline(xpv, sv_type);
1131     return xpv;
1132 }
1133
1134 #endif
1135
1136 static const struct body_details fake_rv =
1137     { 0, 0, 0, SVt_IV, FALSE, NONV, NOARENA, 0 };
1138
1139 /*
1140 =for apidoc sv_upgrade
1141
1142 Upgrade an SV to a more complex form.  Generally adds a new body type to the
1143 SV, then copies across as much information as possible from the old body.
1144 You generally want to use the C<SvUPGRADE> macro wrapper. See also C<svtype>.
1145
1146 =cut
1147 */
1148
1149 void
1150 Perl_sv_upgrade(pTHX_ register SV *const sv, svtype new_type)
1151 {
1152     dVAR;
1153     void*       old_body;
1154     void*       new_body;
1155     const svtype old_type = SvTYPE(sv);
1156     const struct body_details *new_type_details;
1157     const struct body_details *old_type_details
1158         = bodies_by_type + old_type;
1159     SV *referant = NULL;
1160
1161     PERL_ARGS_ASSERT_SV_UPGRADE;
1162
1163     if (old_type == new_type)
1164         return;
1165
1166     /* This clause was purposefully added ahead of the early return above to
1167        the shared string hackery for (sort {$a <=> $b} keys %hash), with the
1168        inference by Nick I-S that it would fix other troublesome cases. See
1169        changes 7162, 7163 (f130fd4589cf5fbb24149cd4db4137c8326f49c1 and parent)
1170
1171        Given that shared hash key scalars are no longer PVIV, but PV, there is
1172        no longer need to unshare so as to free up the IVX slot for its proper
1173        purpose. So it's safe to move the early return earlier.  */
1174
1175     if (new_type != SVt_PV && SvIsCOW(sv)) {
1176         sv_force_normal_flags(sv, 0);
1177     }
1178
1179     old_body = SvANY(sv);
1180
1181     /* Copying structures onto other structures that have been neatly zeroed
1182        has a subtle gotcha. Consider XPVMG
1183
1184        +------+------+------+------+------+-------+-------+
1185        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |
1186        +------+------+------+------+------+-------+-------+
1187        0      4      8     12     16     20      24      28
1188
1189        where NVs are aligned to 8 bytes, so that sizeof that structure is
1190        actually 32 bytes long, with 4 bytes of padding at the end:
1191
1192        +------+------+------+------+------+-------+-------+------+
1193        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH | ???  |
1194        +------+------+------+------+------+-------+-------+------+
1195        0      4      8     12     16     20      24      28     32
1196
1197        so what happens if you allocate memory for this structure:
1198
1199        +------+------+------+------+------+-------+-------+------+------+...
1200        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |  GP  | NAME |
1201        +------+------+------+------+------+-------+-------+------+------+...
1202        0      4      8     12     16     20      24      28     32     36
1203
1204        zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
1205        expect, because you copy the area marked ??? onto GP. Now, ??? may have
1206        started out as zero once, but it's quite possible that it isn't. So now,
1207        rather than a nicely zeroed GP, you have it pointing somewhere random.
1208        Bugs ensue.
1209
1210        (In fact, GP ends up pointing at a previous GP structure, because the
1211        principle cause of the padding in XPVMG getting garbage is a copy of
1212        sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob. Right now
1213        this happens to be moot because XPVGV has been re-ordered, with GP
1214        no longer after STASH)
1215
1216        So we are careful and work out the size of used parts of all the
1217        structures.  */
1218
1219     switch (old_type) {
1220     case SVt_NULL:
1221         break;
1222     case SVt_IV:
1223         if (SvROK(sv)) {
1224             referant = SvRV(sv);
1225             old_type_details = &fake_rv;
1226             if (new_type == SVt_NV)
1227                 new_type = SVt_PVNV;
1228         } else {
1229             if (new_type < SVt_PVIV) {
1230                 new_type = (new_type == SVt_NV)
1231                     ? SVt_PVNV : SVt_PVIV;
1232             }
1233         }
1234         break;
1235     case SVt_NV:
1236         if (new_type < SVt_PVNV) {
1237             new_type = SVt_PVNV;
1238         }
1239         break;
1240     case SVt_PV:
1241         assert(new_type > SVt_PV);
1242         assert(SVt_IV < SVt_PV);
1243         assert(SVt_NV < SVt_PV);
1244         break;
1245     case SVt_PVIV:
1246         break;
1247     case SVt_PVNV:
1248         break;
1249     case SVt_PVMG:
1250         /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1251            there's no way that it can be safely upgraded, because perl.c
1252            expects to Safefree(SvANY(PL_mess_sv))  */
1253         assert(sv != PL_mess_sv);
1254         /* This flag bit is used to mean other things in other scalar types.
1255            Given that it only has meaning inside the pad, it shouldn't be set
1256            on anything that can get upgraded.  */
1257         assert(!SvPAD_TYPED(sv));
1258         break;
1259     default:
1260         if (old_type_details->cant_upgrade)
1261             Perl_croak(aTHX_ "Can't upgrade %s (%" UVuf ") to %" UVuf,
1262                        sv_reftype(sv, 0), (UV) old_type, (UV) new_type);
1263     }
1264
1265     if (old_type > new_type)
1266         Perl_croak(aTHX_ "sv_upgrade from type %d down to type %d",
1267                 (int)old_type, (int)new_type);
1268
1269     new_type_details = bodies_by_type + new_type;
1270
1271     SvFLAGS(sv) &= ~SVTYPEMASK;
1272     SvFLAGS(sv) |= new_type;
1273
1274     /* This can't happen, as SVt_NULL is <= all values of new_type, so one of
1275        the return statements above will have triggered.  */
1276     assert (new_type != SVt_NULL);
1277     switch (new_type) {
1278     case SVt_IV:
1279         assert(old_type == SVt_NULL);
1280         SvANY(sv) = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
1281         SvIV_set(sv, 0);
1282         return;
1283     case SVt_NV:
1284         assert(old_type == SVt_NULL);
1285         SvANY(sv) = new_XNV();
1286         SvNV_set(sv, 0);
1287         return;
1288     case SVt_PVHV:
1289     case SVt_PVAV:
1290         assert(new_type_details->body_size);
1291
1292 #ifndef PURIFY  
1293         assert(new_type_details->arena);
1294         assert(new_type_details->arena_size);
1295         /* This points to the start of the allocated area.  */
1296         new_body_inline(new_body, new_type);
1297         Zero(new_body, new_type_details->body_size, char);
1298         new_body = ((char *)new_body) - new_type_details->offset;
1299 #else
1300         /* We always allocated the full length item with PURIFY. To do this
1301            we fake things so that arena is false for all 16 types..  */
1302         new_body = new_NOARENAZ(new_type_details);
1303 #endif
1304         SvANY(sv) = new_body;
1305         if (new_type == SVt_PVAV) {
1306             AvMAX(sv)   = -1;
1307             AvFILLp(sv) = -1;
1308             AvREAL_only(sv);
1309             if (old_type_details->body_size) {
1310                 AvALLOC(sv) = 0;
1311             } else {
1312                 /* It will have been zeroed when the new body was allocated.
1313                    Lets not write to it, in case it confuses a write-back
1314                    cache.  */
1315             }
1316         } else {
1317             assert(!SvOK(sv));
1318             SvOK_off(sv);
1319 #ifndef NODEFAULT_SHAREKEYS
1320             HvSHAREKEYS_on(sv);         /* key-sharing on by default */
1321 #endif
1322             HvMAX(sv) = 7; /* (start with 8 buckets) */
1323             if (old_type_details->body_size) {
1324                 HvFILL(sv) = 0;
1325             } else {
1326                 /* It will have been zeroed when the new body was allocated.
1327                    Lets not write to it, in case it confuses a write-back
1328                    cache.  */
1329             }
1330         }
1331
1332         /* SVt_NULL isn't the only thing upgraded to AV or HV.
1333            The target created by newSVrv also is, and it can have magic.
1334            However, it never has SvPVX set.
1335         */
1336         if (old_type == SVt_IV) {
1337             assert(!SvROK(sv));
1338         } else if (old_type >= SVt_PV) {
1339             assert(SvPVX_const(sv) == 0);
1340         }
1341
1342         if (old_type >= SVt_PVMG) {
1343             SvMAGIC_set(sv, ((XPVMG*)old_body)->xmg_u.xmg_magic);
1344             SvSTASH_set(sv, ((XPVMG*)old_body)->xmg_stash);
1345         } else {
1346             sv->sv_u.svu_array = NULL; /* or svu_hash  */
1347         }
1348         break;
1349
1350
1351     case SVt_REGEXP:
1352         /* This ensures that SvTHINKFIRST(sv) is true, and hence that
1353            sv_force_normal_flags(sv) is called.  */
1354         SvFAKE_on(sv);
1355     case SVt_PVIV:
1356         /* XXX Is this still needed?  Was it ever needed?   Surely as there is
1357            no route from NV to PVIV, NOK can never be true  */
1358         assert(!SvNOKp(sv));
1359         assert(!SvNOK(sv));
1360     case SVt_PVIO:
1361     case SVt_PVFM:
1362     case SVt_PVGV:
1363     case SVt_PVCV:
1364     case SVt_PVLV:
1365     case SVt_PVMG:
1366     case SVt_PVNV:
1367     case SVt_PV:
1368
1369         assert(new_type_details->body_size);
1370         /* We always allocated the full length item with PURIFY. To do this
1371            we fake things so that arena is false for all 16 types..  */
1372         if(new_type_details->arena) {
1373             /* This points to the start of the allocated area.  */
1374             new_body_inline(new_body, new_type);
1375             Zero(new_body, new_type_details->body_size, char);
1376             new_body = ((char *)new_body) - new_type_details->offset;
1377         } else {
1378             new_body = new_NOARENAZ(new_type_details);
1379         }
1380         SvANY(sv) = new_body;
1381
1382         if (old_type_details->copy) {
1383             /* There is now the potential for an upgrade from something without
1384                an offset (PVNV or PVMG) to something with one (PVCV, PVFM)  */
1385             int offset = old_type_details->offset;
1386             int length = old_type_details->copy;
1387
1388             if (new_type_details->offset > old_type_details->offset) {
1389                 const int difference
1390                     = new_type_details->offset - old_type_details->offset;
1391                 offset += difference;
1392                 length -= difference;
1393             }
1394             assert (length >= 0);
1395                 
1396             Copy((char *)old_body + offset, (char *)new_body + offset, length,
1397                  char);
1398         }
1399
1400 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1401         /* If NV 0.0 is stores as all bits 0 then Zero() already creates a
1402          * correct 0.0 for us.  Otherwise, if the old body didn't have an
1403          * NV slot, but the new one does, then we need to initialise the
1404          * freshly created NV slot with whatever the correct bit pattern is
1405          * for 0.0  */
1406         if (old_type_details->zero_nv && !new_type_details->zero_nv
1407             && !isGV_with_GP(sv))
1408             SvNV_set(sv, 0);
1409 #endif
1410
1411         if (new_type == SVt_PVIO) {
1412             IO * const io = MUTABLE_IO(sv);
1413             GV *iogv = gv_fetchpvs("IO::File::", GV_ADD, SVt_PVHV);
1414
1415             SvOBJECT_on(io);
1416             /* Clear the stashcache because a new IO could overrule a package
1417                name */
1418             hv_clear(PL_stashcache);
1419
1420             SvSTASH_set(io, MUTABLE_HV(SvREFCNT_inc(GvHV(iogv))));
1421             IoPAGE_LEN(sv) = 60;
1422         }
1423         if (old_type < SVt_PV) {
1424             /* referant will be NULL unless the old type was SVt_IV emulating
1425                SVt_RV */
1426             sv->sv_u.svu_rv = referant;
1427         }
1428         break;
1429     default:
1430         Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu",
1431                    (unsigned long)new_type);
1432     }
1433
1434     if (old_type > SVt_IV) {
1435 #ifdef PURIFY
1436         my_safefree(old_body);
1437 #else
1438         /* Note that there is an assumption that all bodies of types that
1439            can be upgraded came from arenas. Only the more complex non-
1440            upgradable types are allowed to be directly malloc()ed.  */
1441         assert(old_type_details->arena);
1442         del_body((void*)((char*)old_body + old_type_details->offset),
1443                  &PL_body_roots[old_type]);
1444 #endif
1445     }
1446 }
1447
1448 /*
1449 =for apidoc sv_backoff
1450
1451 Remove any string offset. You should normally use the C<SvOOK_off> macro
1452 wrapper instead.
1453
1454 =cut
1455 */
1456
1457 int
1458 Perl_sv_backoff(pTHX_ register SV *const sv)
1459 {
1460     STRLEN delta;
1461     const char * const s = SvPVX_const(sv);
1462
1463     PERL_ARGS_ASSERT_SV_BACKOFF;
1464     PERL_UNUSED_CONTEXT;
1465
1466     assert(SvOOK(sv));
1467     assert(SvTYPE(sv) != SVt_PVHV);
1468     assert(SvTYPE(sv) != SVt_PVAV);
1469
1470     SvOOK_offset(sv, delta);
1471     
1472     SvLEN_set(sv, SvLEN(sv) + delta);
1473     SvPV_set(sv, SvPVX(sv) - delta);
1474     Move(s, SvPVX(sv), SvCUR(sv)+1, char);
1475     SvFLAGS(sv) &= ~SVf_OOK;
1476     return 0;
1477 }
1478
1479 /*
1480 =for apidoc sv_grow
1481
1482 Expands the character buffer in the SV.  If necessary, uses C<sv_unref> and
1483 upgrades the SV to C<SVt_PV>.  Returns a pointer to the character buffer.
1484 Use the C<SvGROW> wrapper instead.
1485
1486 =cut
1487 */
1488
1489 char *
1490 Perl_sv_grow(pTHX_ register SV *const sv, register STRLEN newlen)
1491 {
1492     register char *s;
1493
1494     PERL_ARGS_ASSERT_SV_GROW;
1495
1496     if (PL_madskills && newlen >= 0x100000) {
1497         PerlIO_printf(Perl_debug_log,
1498                       "Allocation too large: %"UVxf"\n", (UV)newlen);
1499     }
1500 #ifdef HAS_64K_LIMIT
1501     if (newlen >= 0x10000) {
1502         PerlIO_printf(Perl_debug_log,
1503                       "Allocation too large: %"UVxf"\n", (UV)newlen);
1504         my_exit(1);
1505     }
1506 #endif /* HAS_64K_LIMIT */
1507     if (SvROK(sv))
1508         sv_unref(sv);
1509     if (SvTYPE(sv) < SVt_PV) {
1510         sv_upgrade(sv, SVt_PV);
1511         s = SvPVX_mutable(sv);
1512     }
1513     else if (SvOOK(sv)) {       /* pv is offset? */
1514         sv_backoff(sv);
1515         s = SvPVX_mutable(sv);
1516         if (newlen > SvLEN(sv))
1517             newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1518 #ifdef HAS_64K_LIMIT
1519         if (newlen >= 0x10000)
1520             newlen = 0xFFFF;
1521 #endif
1522     }
1523     else
1524         s = SvPVX_mutable(sv);
1525
1526     if (newlen > SvLEN(sv)) {           /* need more room? */
1527 #ifndef Perl_safesysmalloc_size
1528         newlen = PERL_STRLEN_ROUNDUP(newlen);
1529 #endif
1530         if (SvLEN(sv) && s) {
1531             s = (char*)saferealloc(s, newlen);
1532         }
1533         else {
1534             s = (char*)safemalloc(newlen);
1535             if (SvPVX_const(sv) && SvCUR(sv)) {
1536                 Move(SvPVX_const(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1537             }
1538         }
1539         SvPV_set(sv, s);
1540 #ifdef Perl_safesysmalloc_size
1541         /* Do this here, do it once, do it right, and then we will never get
1542            called back into sv_grow() unless there really is some growing
1543            needed.  */
1544         SvLEN_set(sv, Perl_safesysmalloc_size(s));
1545 #else
1546         SvLEN_set(sv, newlen);
1547 #endif
1548     }
1549     return s;
1550 }
1551
1552 /*
1553 =for apidoc sv_setiv
1554
1555 Copies an integer into the given SV, upgrading first if necessary.
1556 Does not handle 'set' magic.  See also C<sv_setiv_mg>.
1557
1558 =cut
1559 */
1560
1561 void
1562 Perl_sv_setiv(pTHX_ register SV *const sv, const IV i)
1563 {
1564     dVAR;
1565
1566     PERL_ARGS_ASSERT_SV_SETIV;
1567
1568     SV_CHECK_THINKFIRST_COW_DROP(sv);
1569     switch (SvTYPE(sv)) {
1570     case SVt_NULL:
1571     case SVt_NV:
1572         sv_upgrade(sv, SVt_IV);
1573         break;
1574     case SVt_PV:
1575         sv_upgrade(sv, SVt_PVIV);
1576         break;
1577
1578     case SVt_PVGV:
1579         if (!isGV_with_GP(sv))
1580             break;
1581     case SVt_PVAV:
1582     case SVt_PVHV:
1583     case SVt_PVCV:
1584     case SVt_PVFM:
1585     case SVt_PVIO:
1586         Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1587                    OP_DESC(PL_op));
1588     default: NOOP;
1589     }
1590     (void)SvIOK_only(sv);                       /* validate number */
1591     SvIV_set(sv, i);
1592     SvTAINT(sv);
1593 }
1594
1595 /*
1596 =for apidoc sv_setiv_mg
1597
1598 Like C<sv_setiv>, but also handles 'set' magic.
1599
1600 =cut
1601 */
1602
1603 void
1604 Perl_sv_setiv_mg(pTHX_ register SV *const sv, const IV i)
1605 {
1606     PERL_ARGS_ASSERT_SV_SETIV_MG;
1607
1608     sv_setiv(sv,i);
1609     SvSETMAGIC(sv);
1610 }
1611
1612 /*
1613 =for apidoc sv_setuv
1614
1615 Copies an unsigned integer into the given SV, upgrading first if necessary.
1616 Does not handle 'set' magic.  See also C<sv_setuv_mg>.
1617
1618 =cut
1619 */
1620
1621 void
1622 Perl_sv_setuv(pTHX_ register SV *const sv, const UV u)
1623 {
1624     PERL_ARGS_ASSERT_SV_SETUV;
1625
1626     /* With these two if statements:
1627        u=1.49  s=0.52  cu=72.49  cs=10.64  scripts=270  tests=20865
1628
1629        without
1630        u=1.35  s=0.47  cu=73.45  cs=11.43  scripts=270  tests=20865
1631
1632        If you wish to remove them, please benchmark to see what the effect is
1633     */
1634     if (u <= (UV)IV_MAX) {
1635        sv_setiv(sv, (IV)u);
1636        return;
1637     }
1638     sv_setiv(sv, 0);
1639     SvIsUV_on(sv);
1640     SvUV_set(sv, u);
1641 }
1642
1643 /*
1644 =for apidoc sv_setuv_mg
1645
1646 Like C<sv_setuv>, but also handles 'set' magic.
1647
1648 =cut
1649 */
1650
1651 void
1652 Perl_sv_setuv_mg(pTHX_ register SV *const sv, const UV u)
1653 {
1654     PERL_ARGS_ASSERT_SV_SETUV_MG;
1655
1656     sv_setuv(sv,u);
1657     SvSETMAGIC(sv);
1658 }
1659
1660 /*
1661 =for apidoc sv_setnv
1662
1663 Copies a double into the given SV, upgrading first if necessary.
1664 Does not handle 'set' magic.  See also C<sv_setnv_mg>.
1665
1666 =cut
1667 */
1668
1669 void
1670 Perl_sv_setnv(pTHX_ register SV *const sv, const NV num)
1671 {
1672     dVAR;
1673
1674     PERL_ARGS_ASSERT_SV_SETNV;
1675
1676     SV_CHECK_THINKFIRST_COW_DROP(sv);
1677     switch (SvTYPE(sv)) {
1678     case SVt_NULL:
1679     case SVt_IV:
1680         sv_upgrade(sv, SVt_NV);
1681         break;
1682     case SVt_PV:
1683     case SVt_PVIV:
1684         sv_upgrade(sv, SVt_PVNV);
1685         break;
1686
1687     case SVt_PVGV:
1688         if (!isGV_with_GP(sv))
1689             break;
1690     case SVt_PVAV:
1691     case SVt_PVHV:
1692     case SVt_PVCV:
1693     case SVt_PVFM:
1694     case SVt_PVIO:
1695         Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
1696                    OP_DESC(PL_op));
1697     default: NOOP;
1698     }
1699     SvNV_set(sv, num);
1700     (void)SvNOK_only(sv);                       /* validate number */
1701     SvTAINT(sv);
1702 }
1703
1704 /*
1705 =for apidoc sv_setnv_mg
1706
1707 Like C<sv_setnv>, but also handles 'set' magic.
1708
1709 =cut
1710 */
1711
1712 void
1713 Perl_sv_setnv_mg(pTHX_ register SV *const sv, const NV num)
1714 {
1715     PERL_ARGS_ASSERT_SV_SETNV_MG;
1716
1717     sv_setnv(sv,num);
1718     SvSETMAGIC(sv);
1719 }
1720
1721 /* Print an "isn't numeric" warning, using a cleaned-up,
1722  * printable version of the offending string
1723  */
1724
1725 STATIC void
1726 S_not_a_number(pTHX_ SV *const sv)
1727 {
1728      dVAR;
1729      SV *dsv;
1730      char tmpbuf[64];
1731      const char *pv;
1732
1733      PERL_ARGS_ASSERT_NOT_A_NUMBER;
1734
1735      if (DO_UTF8(sv)) {
1736           dsv = newSVpvs_flags("", SVs_TEMP);
1737           pv = sv_uni_display(dsv, sv, 10, 0);
1738      } else {
1739           char *d = tmpbuf;
1740           const char * const limit = tmpbuf + sizeof(tmpbuf) - 8;
1741           /* each *s can expand to 4 chars + "...\0",
1742              i.e. need room for 8 chars */
1743         
1744           const char *s = SvPVX_const(sv);
1745           const char * const end = s + SvCUR(sv);
1746           for ( ; s < end && d < limit; s++ ) {
1747                int ch = *s & 0xFF;
1748                if (ch & 128 && !isPRINT_LC(ch)) {
1749                     *d++ = 'M';
1750                     *d++ = '-';
1751                     ch &= 127;
1752                }
1753                if (ch == '\n') {
1754                     *d++ = '\\';
1755                     *d++ = 'n';
1756                }
1757                else if (ch == '\r') {
1758                     *d++ = '\\';
1759                     *d++ = 'r';
1760                }
1761                else if (ch == '\f') {
1762                     *d++ = '\\';
1763                     *d++ = 'f';
1764                }
1765                else if (ch == '\\') {
1766                     *d++ = '\\';
1767                     *d++ = '\\';
1768                }
1769                else if (ch == '\0') {
1770                     *d++ = '\\';
1771                     *d++ = '0';
1772                }
1773                else if (isPRINT_LC(ch))
1774                     *d++ = ch;
1775                else {
1776                     *d++ = '^';
1777                     *d++ = toCTRL(ch);
1778                }
1779           }
1780           if (s < end) {
1781                *d++ = '.';
1782                *d++ = '.';
1783                *d++ = '.';
1784           }
1785           *d = '\0';
1786           pv = tmpbuf;
1787     }
1788
1789     if (PL_op)
1790         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1791                     "Argument \"%s\" isn't numeric in %s", pv,
1792                     OP_DESC(PL_op));
1793     else
1794         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1795                     "Argument \"%s\" isn't numeric", pv);
1796 }
1797
1798 /*
1799 =for apidoc looks_like_number
1800
1801 Test if the content of an SV looks like a number (or is a number).
1802 C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1803 non-numeric warning), even if your atof() doesn't grok them.
1804
1805 =cut
1806 */
1807
1808 I32
1809 Perl_looks_like_number(pTHX_ SV *const sv)
1810 {
1811     register const char *sbegin;
1812     STRLEN len;
1813
1814     PERL_ARGS_ASSERT_LOOKS_LIKE_NUMBER;
1815
1816     if (SvPOK(sv)) {
1817         sbegin = SvPVX_const(sv);
1818         len = SvCUR(sv);
1819     }
1820     else if (SvPOKp(sv))
1821         sbegin = SvPV_const(sv, len);
1822     else
1823         return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
1824     return grok_number(sbegin, len, NULL);
1825 }
1826
1827 STATIC bool
1828 S_glob_2number(pTHX_ GV * const gv)
1829 {
1830     const U32 wasfake = SvFLAGS(gv) & SVf_FAKE;
1831     SV *const buffer = sv_newmortal();
1832
1833     PERL_ARGS_ASSERT_GLOB_2NUMBER;
1834
1835     /* FAKE globs can get coerced, so need to turn this off temporarily if it
1836        is on.  */
1837     SvFAKE_off(gv);
1838     gv_efullname3(buffer, gv, "*");
1839     SvFLAGS(gv) |= wasfake;
1840
1841     /* We know that all GVs stringify to something that is not-a-number,
1842         so no need to test that.  */
1843     if (ckWARN(WARN_NUMERIC))
1844         not_a_number(buffer);
1845     /* We just want something true to return, so that S_sv_2iuv_common
1846         can tail call us and return true.  */
1847     return TRUE;
1848 }
1849
1850 /* Actually, ISO C leaves conversion of UV to IV undefined, but
1851    until proven guilty, assume that things are not that bad... */
1852
1853 /*
1854    NV_PRESERVES_UV:
1855
1856    As 64 bit platforms often have an NV that doesn't preserve all bits of
1857    an IV (an assumption perl has been based on to date) it becomes necessary
1858    to remove the assumption that the NV always carries enough precision to
1859    recreate the IV whenever needed, and that the NV is the canonical form.
1860    Instead, IV/UV and NV need to be given equal rights. So as to not lose
1861    precision as a side effect of conversion (which would lead to insanity
1862    and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1863    1) to distinguish between IV/UV/NV slots that have cached a valid
1864       conversion where precision was lost and IV/UV/NV slots that have a
1865       valid conversion which has lost no precision
1866    2) to ensure that if a numeric conversion to one form is requested that
1867       would lose precision, the precise conversion (or differently
1868       imprecise conversion) is also performed and cached, to prevent
1869       requests for different numeric formats on the same SV causing
1870       lossy conversion chains. (lossless conversion chains are perfectly
1871       acceptable (still))
1872
1873
1874    flags are used:
1875    SvIOKp is true if the IV slot contains a valid value
1876    SvIOK  is true only if the IV value is accurate (UV if SvIOK_UV true)
1877    SvNOKp is true if the NV slot contains a valid value
1878    SvNOK  is true only if the NV value is accurate
1879
1880    so
1881    while converting from PV to NV, check to see if converting that NV to an
1882    IV(or UV) would lose accuracy over a direct conversion from PV to
1883    IV(or UV). If it would, cache both conversions, return NV, but mark
1884    SV as IOK NOKp (ie not NOK).
1885
1886    While converting from PV to IV, check to see if converting that IV to an
1887    NV would lose accuracy over a direct conversion from PV to NV. If it
1888    would, cache both conversions, flag similarly.
1889
1890    Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1891    correctly because if IV & NV were set NV *always* overruled.
1892    Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1893    changes - now IV and NV together means that the two are interchangeable:
1894    SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
1895
1896    The benefit of this is that operations such as pp_add know that if
1897    SvIOK is true for both left and right operands, then integer addition
1898    can be used instead of floating point (for cases where the result won't
1899    overflow). Before, floating point was always used, which could lead to
1900    loss of precision compared with integer addition.
1901
1902    * making IV and NV equal status should make maths accurate on 64 bit
1903      platforms
1904    * may speed up maths somewhat if pp_add and friends start to use
1905      integers when possible instead of fp. (Hopefully the overhead in
1906      looking for SvIOK and checking for overflow will not outweigh the
1907      fp to integer speedup)
1908    * will slow down integer operations (callers of SvIV) on "inaccurate"
1909      values, as the change from SvIOK to SvIOKp will cause a call into
1910      sv_2iv each time rather than a macro access direct to the IV slot
1911    * should speed up number->string conversion on integers as IV is
1912      favoured when IV and NV are equally accurate
1913
1914    ####################################################################
1915    You had better be using SvIOK_notUV if you want an IV for arithmetic:
1916    SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
1917    On the other hand, SvUOK is true iff UV.
1918    ####################################################################
1919
1920    Your mileage will vary depending your CPU's relative fp to integer
1921    performance ratio.
1922 */
1923
1924 #ifndef NV_PRESERVES_UV
1925 #  define IS_NUMBER_UNDERFLOW_IV 1
1926 #  define IS_NUMBER_UNDERFLOW_UV 2
1927 #  define IS_NUMBER_IV_AND_UV    2
1928 #  define IS_NUMBER_OVERFLOW_IV  4
1929 #  define IS_NUMBER_OVERFLOW_UV  5
1930
1931 /* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
1932
1933 /* For sv_2nv these three cases are "SvNOK and don't bother casting"  */
1934 STATIC int
1935 S_sv_2iuv_non_preserve(pTHX_ register SV *const sv
1936 #  ifdef DEBUGGING
1937                        , I32 numtype
1938 #  endif
1939                        )
1940 {
1941     dVAR;
1942
1943     PERL_ARGS_ASSERT_SV_2IUV_NON_PRESERVE;
1944
1945     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));
1946     if (SvNVX(sv) < (NV)IV_MIN) {
1947         (void)SvIOKp_on(sv);
1948         (void)SvNOK_on(sv);
1949         SvIV_set(sv, IV_MIN);
1950         return IS_NUMBER_UNDERFLOW_IV;
1951     }
1952     if (SvNVX(sv) > (NV)UV_MAX) {
1953         (void)SvIOKp_on(sv);
1954         (void)SvNOK_on(sv);
1955         SvIsUV_on(sv);
1956         SvUV_set(sv, UV_MAX);
1957         return IS_NUMBER_OVERFLOW_UV;
1958     }
1959     (void)SvIOKp_on(sv);
1960     (void)SvNOK_on(sv);
1961     /* Can't use strtol etc to convert this string.  (See truth table in
1962        sv_2iv  */
1963     if (SvNVX(sv) <= (UV)IV_MAX) {
1964         SvIV_set(sv, I_V(SvNVX(sv)));
1965         if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
1966             SvIOK_on(sv); /* Integer is precise. NOK, IOK */
1967         } else {
1968             /* Integer is imprecise. NOK, IOKp */
1969         }
1970         return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
1971     }
1972     SvIsUV_on(sv);
1973     SvUV_set(sv, U_V(SvNVX(sv)));
1974     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
1975         if (SvUVX(sv) == UV_MAX) {
1976             /* As we know that NVs don't preserve UVs, UV_MAX cannot
1977                possibly be preserved by NV. Hence, it must be overflow.
1978                NOK, IOKp */
1979             return IS_NUMBER_OVERFLOW_UV;
1980         }
1981         SvIOK_on(sv); /* Integer is precise. NOK, UOK */
1982     } else {
1983         /* Integer is imprecise. NOK, IOKp */
1984     }
1985     return IS_NUMBER_OVERFLOW_IV;
1986 }
1987 #endif /* !NV_PRESERVES_UV*/
1988
1989 STATIC bool
1990 S_sv_2iuv_common(pTHX_ SV *const sv)
1991 {
1992     dVAR;
1993
1994     PERL_ARGS_ASSERT_SV_2IUV_COMMON;
1995
1996     if (SvNOKp(sv)) {
1997         /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
1998          * without also getting a cached IV/UV from it at the same time
1999          * (ie PV->NV conversion should detect loss of accuracy and cache
2000          * IV or UV at same time to avoid this. */
2001         /* IV-over-UV optimisation - choose to cache IV if possible */
2002
2003         if (SvTYPE(sv) == SVt_NV)
2004             sv_upgrade(sv, SVt_PVNV);
2005
2006         (void)SvIOKp_on(sv);    /* Must do this first, to clear any SvOOK */
2007         /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
2008            certainly cast into the IV range at IV_MAX, whereas the correct
2009            answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
2010            cases go to UV */
2011 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
2012         if (Perl_isnan(SvNVX(sv))) {
2013             SvUV_set(sv, 0);
2014             SvIsUV_on(sv);
2015             return FALSE;
2016         }
2017 #endif
2018         if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2019             SvIV_set(sv, I_V(SvNVX(sv)));
2020             if (SvNVX(sv) == (NV) SvIVX(sv)
2021 #ifndef NV_PRESERVES_UV
2022                 && (((UV)1 << NV_PRESERVES_UV_BITS) >
2023                     (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2024                 /* Don't flag it as "accurately an integer" if the number
2025                    came from a (by definition imprecise) NV operation, and
2026                    we're outside the range of NV integer precision */
2027 #endif
2028                 ) {
2029                 if (SvNOK(sv))
2030                     SvIOK_on(sv);  /* Can this go wrong with rounding? NWC */
2031                 else {
2032                     /* scalar has trailing garbage, eg "42a" */
2033                 }
2034                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2035                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
2036                                       PTR2UV(sv),
2037                                       SvNVX(sv),
2038                                       SvIVX(sv)));
2039
2040             } else {
2041                 /* IV not precise.  No need to convert from PV, as NV
2042                    conversion would already have cached IV if it detected
2043                    that PV->IV would be better than PV->NV->IV
2044                    flags already correct - don't set public IOK.  */
2045                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2046                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
2047                                       PTR2UV(sv),
2048                                       SvNVX(sv),
2049                                       SvIVX(sv)));
2050             }
2051             /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2052                but the cast (NV)IV_MIN rounds to a the value less (more
2053                negative) than IV_MIN which happens to be equal to SvNVX ??
2054                Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2055                NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2056                (NV)UVX == NVX are both true, but the values differ. :-(
2057                Hopefully for 2s complement IV_MIN is something like
2058                0x8000000000000000 which will be exact. NWC */
2059         }
2060         else {
2061             SvUV_set(sv, U_V(SvNVX(sv)));
2062             if (
2063                 (SvNVX(sv) == (NV) SvUVX(sv))
2064 #ifndef  NV_PRESERVES_UV
2065                 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2066                 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2067                 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2068                 /* Don't flag it as "accurately an integer" if the number
2069                    came from a (by definition imprecise) NV operation, and
2070                    we're outside the range of NV integer precision */
2071 #endif
2072                 && SvNOK(sv)
2073                 )
2074                 SvIOK_on(sv);
2075             SvIsUV_on(sv);
2076             DEBUG_c(PerlIO_printf(Perl_debug_log,
2077                                   "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
2078                                   PTR2UV(sv),
2079                                   SvUVX(sv),
2080                                   SvUVX(sv)));
2081         }
2082     }
2083     else if (SvPOKp(sv) && SvLEN(sv)) {
2084         UV value;
2085         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2086         /* We want to avoid a possible problem when we cache an IV/ a UV which
2087            may be later translated to an NV, and the resulting NV is not
2088            the same as the direct translation of the initial string
2089            (eg 123.456 can shortcut to the IV 123 with atol(), but we must
2090            be careful to ensure that the value with the .456 is around if the
2091            NV value is requested in the future).
2092         
2093            This means that if we cache such an IV/a UV, we need to cache the
2094            NV as well.  Moreover, we trade speed for space, and do not
2095            cache the NV if we are sure it's not needed.
2096          */
2097
2098         /* SVt_PVNV is one higher than SVt_PVIV, hence this order  */
2099         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2100              == IS_NUMBER_IN_UV) {
2101             /* It's definitely an integer, only upgrade to PVIV */
2102             if (SvTYPE(sv) < SVt_PVIV)
2103                 sv_upgrade(sv, SVt_PVIV);
2104             (void)SvIOK_on(sv);
2105         } else if (SvTYPE(sv) < SVt_PVNV)
2106             sv_upgrade(sv, SVt_PVNV);
2107
2108         /* If NVs preserve UVs then we only use the UV value if we know that
2109            we aren't going to call atof() below. If NVs don't preserve UVs
2110            then the value returned may have more precision than atof() will
2111            return, even though value isn't perfectly accurate.  */
2112         if ((numtype & (IS_NUMBER_IN_UV
2113 #ifdef NV_PRESERVES_UV
2114                         | IS_NUMBER_NOT_INT
2115 #endif
2116             )) == IS_NUMBER_IN_UV) {
2117             /* This won't turn off the public IOK flag if it was set above  */
2118             (void)SvIOKp_on(sv);
2119
2120             if (!(numtype & IS_NUMBER_NEG)) {
2121                 /* positive */;
2122                 if (value <= (UV)IV_MAX) {
2123                     SvIV_set(sv, (IV)value);
2124                 } else {
2125                     /* it didn't overflow, and it was positive. */
2126                     SvUV_set(sv, value);
2127                     SvIsUV_on(sv);
2128                 }
2129             } else {
2130                 /* 2s complement assumption  */
2131                 if (value <= (UV)IV_MIN) {
2132                     SvIV_set(sv, -(IV)value);
2133                 } else {
2134                     /* Too negative for an IV.  This is a double upgrade, but
2135                        I'm assuming it will be rare.  */
2136                     if (SvTYPE(sv) < SVt_PVNV)
2137                         sv_upgrade(sv, SVt_PVNV);
2138                     SvNOK_on(sv);
2139                     SvIOK_off(sv);
2140                     SvIOKp_on(sv);
2141                     SvNV_set(sv, -(NV)value);
2142                     SvIV_set(sv, IV_MIN);
2143                 }
2144             }
2145         }
2146         /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2147            will be in the previous block to set the IV slot, and the next
2148            block to set the NV slot.  So no else here.  */
2149         
2150         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2151             != IS_NUMBER_IN_UV) {
2152             /* It wasn't an (integer that doesn't overflow the UV). */
2153             SvNV_set(sv, Atof(SvPVX_const(sv)));
2154
2155             if (! numtype && ckWARN(WARN_NUMERIC))
2156                 not_a_number(sv);
2157
2158 #if defined(USE_LONG_DOUBLE)
2159             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" PERL_PRIgldbl ")\n",
2160                                   PTR2UV(sv), SvNVX(sv)));
2161 #else
2162             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"NVgf")\n",
2163                                   PTR2UV(sv), SvNVX(sv)));
2164 #endif
2165
2166 #ifdef NV_PRESERVES_UV
2167             (void)SvIOKp_on(sv);
2168             (void)SvNOK_on(sv);
2169             if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2170                 SvIV_set(sv, I_V(SvNVX(sv)));
2171                 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2172                     SvIOK_on(sv);
2173                 } else {
2174                     NOOP;  /* Integer is imprecise. NOK, IOKp */
2175                 }
2176                 /* UV will not work better than IV */
2177             } else {
2178                 if (SvNVX(sv) > (NV)UV_MAX) {
2179                     SvIsUV_on(sv);
2180                     /* Integer is inaccurate. NOK, IOKp, is UV */
2181                     SvUV_set(sv, UV_MAX);
2182                 } else {
2183                     SvUV_set(sv, U_V(SvNVX(sv)));
2184                     /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2185                        NV preservse UV so can do correct comparison.  */
2186                     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2187                         SvIOK_on(sv);
2188                     } else {
2189                         NOOP;   /* Integer is imprecise. NOK, IOKp, is UV */
2190                     }
2191                 }
2192                 SvIsUV_on(sv);
2193             }
2194 #else /* NV_PRESERVES_UV */
2195             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2196                 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2197                 /* The IV/UV slot will have been set from value returned by
2198                    grok_number above.  The NV slot has just been set using
2199                    Atof.  */
2200                 SvNOK_on(sv);
2201                 assert (SvIOKp(sv));
2202             } else {
2203                 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2204                     U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2205                     /* Small enough to preserve all bits. */
2206                     (void)SvIOKp_on(sv);
2207                     SvNOK_on(sv);
2208                     SvIV_set(sv, I_V(SvNVX(sv)));
2209                     if ((NV)(SvIVX(sv)) == SvNVX(sv))
2210                         SvIOK_on(sv);
2211                     /* Assumption: first non-preserved integer is < IV_MAX,
2212                        this NV is in the preserved range, therefore: */
2213                     if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2214                           < (UV)IV_MAX)) {
2215                         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);
2216                     }
2217                 } else {
2218                     /* IN_UV NOT_INT
2219                          0      0       already failed to read UV.
2220                          0      1       already failed to read UV.
2221                          1      0       you won't get here in this case. IV/UV
2222                                         slot set, public IOK, Atof() unneeded.
2223                          1      1       already read UV.
2224                        so there's no point in sv_2iuv_non_preserve() attempting
2225                        to use atol, strtol, strtoul etc.  */
2226 #  ifdef DEBUGGING
2227                     sv_2iuv_non_preserve (sv, numtype);
2228 #  else
2229                     sv_2iuv_non_preserve (sv);
2230 #  endif
2231                 }
2232             }
2233 #endif /* NV_PRESERVES_UV */
2234         /* It might be more code efficient to go through the entire logic above
2235            and conditionally set with SvIOKp_on() rather than SvIOK(), but it
2236            gets complex and potentially buggy, so more programmer efficient
2237            to do it this way, by turning off the public flags:  */
2238         if (!numtype)
2239             SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2240         }
2241     }
2242     else  {
2243         if (isGV_with_GP(sv))
2244             return glob_2number(MUTABLE_GV(sv));
2245
2246         if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2247             if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2248                 report_uninit(sv);
2249         }
2250         if (SvTYPE(sv) < SVt_IV)
2251             /* Typically the caller expects that sv_any is not NULL now.  */
2252             sv_upgrade(sv, SVt_IV);
2253         /* Return 0 from the caller.  */
2254         return TRUE;
2255     }
2256     return FALSE;
2257 }
2258
2259 /*
2260 =for apidoc sv_2iv_flags
2261
2262 Return the integer value of an SV, doing any necessary string
2263 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2264 Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2265
2266 =cut
2267 */
2268
2269 IV
2270 Perl_sv_2iv_flags(pTHX_ register SV *const sv, const I32 flags)
2271 {
2272     dVAR;
2273     if (!sv)
2274         return 0;
2275     if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2276         /* FBMs use the same flag bit as SVf_IVisUV, so must let them
2277            cache IVs just in case. In practice it seems that they never
2278            actually anywhere accessible by user Perl code, let alone get used
2279            in anything other than a string context.  */
2280         if (flags & SV_GMAGIC)
2281             mg_get(sv);
2282         if (SvIOKp(sv))
2283             return SvIVX(sv);
2284         if (SvNOKp(sv)) {
2285             return I_V(SvNVX(sv));
2286         }
2287         if (SvPOKp(sv) && SvLEN(sv)) {
2288             UV value;
2289             const int numtype
2290                 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2291
2292             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2293                 == IS_NUMBER_IN_UV) {
2294                 /* It's definitely an integer */
2295                 if (numtype & IS_NUMBER_NEG) {
2296                     if (value < (UV)IV_MIN)
2297                         return -(IV)value;
2298                 } else {
2299                     if (value < (UV)IV_MAX)
2300                         return (IV)value;
2301                 }
2302             }
2303             if (!numtype) {
2304                 if (ckWARN(WARN_NUMERIC))
2305                     not_a_number(sv);
2306             }
2307             return I_V(Atof(SvPVX_const(sv)));
2308         }
2309         if (SvROK(sv)) {
2310             goto return_rok;
2311         }
2312         assert(SvTYPE(sv) >= SVt_PVMG);
2313         /* This falls through to the report_uninit inside S_sv_2iuv_common.  */
2314     } else if (SvTHINKFIRST(sv)) {
2315         if (SvROK(sv)) {
2316         return_rok:
2317             if (SvAMAGIC(sv)) {
2318                 SV * tmpstr;
2319                 if (flags & SV_SKIP_OVERLOAD)
2320                     return 0;
2321                 tmpstr=AMG_CALLun(sv,numer);
2322                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2323                     return SvIV(tmpstr);
2324                 }
2325             }
2326             return PTR2IV(SvRV(sv));
2327         }
2328         if (SvIsCOW(sv)) {
2329             sv_force_normal_flags(sv, 0);
2330         }
2331         if (SvREADONLY(sv) && !SvOK(sv)) {
2332             if (ckWARN(WARN_UNINITIALIZED))
2333                 report_uninit(sv);
2334             return 0;
2335         }
2336     }
2337     if (!SvIOKp(sv)) {
2338         if (S_sv_2iuv_common(aTHX_ sv))
2339             return 0;
2340     }
2341     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2342         PTR2UV(sv),SvIVX(sv)));
2343     return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
2344 }
2345
2346 /*
2347 =for apidoc sv_2uv_flags
2348
2349 Return the unsigned integer value of an SV, doing any necessary string
2350 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2351 Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
2352
2353 =cut
2354 */
2355
2356 UV
2357 Perl_sv_2uv_flags(pTHX_ register SV *const sv, const I32 flags)
2358 {
2359     dVAR;
2360     if (!sv)
2361         return 0;
2362     if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2363         /* FBMs use the same flag bit as SVf_IVisUV, so must let them
2364            cache IVs just in case.  */
2365         if (flags & SV_GMAGIC)
2366             mg_get(sv);
2367         if (SvIOKp(sv))
2368             return SvUVX(sv);
2369         if (SvNOKp(sv))
2370             return U_V(SvNVX(sv));
2371         if (SvPOKp(sv) && SvLEN(sv)) {
2372             UV value;
2373             const int numtype
2374                 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2375
2376             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2377                 == IS_NUMBER_IN_UV) {
2378                 /* It's definitely an integer */
2379                 if (!(numtype & IS_NUMBER_NEG))
2380                     return value;
2381             }
2382             if (!numtype) {
2383                 if (ckWARN(WARN_NUMERIC))
2384                     not_a_number(sv);
2385             }
2386             return U_V(Atof(SvPVX_const(sv)));
2387         }
2388         if (SvROK(sv)) {
2389             goto return_rok;
2390         }
2391         assert(SvTYPE(sv) >= SVt_PVMG);
2392         /* This falls through to the report_uninit inside S_sv_2iuv_common.  */
2393     } else if (SvTHINKFIRST(sv)) {
2394         if (SvROK(sv)) {
2395         return_rok:
2396             if (SvAMAGIC(sv)) {
2397                 SV *tmpstr;
2398                 if (flags & SV_SKIP_OVERLOAD)
2399                     return 0;
2400                 tmpstr = AMG_CALLun(sv,numer);
2401                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2402                     return SvUV(tmpstr);
2403                 }
2404             }
2405             return PTR2UV(SvRV(sv));
2406         }
2407         if (SvIsCOW(sv)) {
2408             sv_force_normal_flags(sv, 0);
2409         }
2410         if (SvREADONLY(sv) && !SvOK(sv)) {
2411             if (ckWARN(WARN_UNINITIALIZED))
2412                 report_uninit(sv);
2413             return 0;
2414         }
2415     }
2416     if (!SvIOKp(sv)) {
2417         if (S_sv_2iuv_common(aTHX_ sv))
2418             return 0;
2419     }
2420
2421     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2422                           PTR2UV(sv),SvUVX(sv)));
2423     return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
2424 }
2425
2426 /*
2427 =for apidoc sv_2nv
2428
2429 Return the num value of an SV, doing any necessary string or integer
2430 conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2431 Normally used via the C<SvNV(sv)> and C<SvNVx(sv)> macros.
2432
2433 =cut
2434 */
2435
2436 NV
2437 Perl_sv_2nv_flags(pTHX_ register SV *const sv, const I32 flags)
2438 {
2439     dVAR;
2440     if (!sv)
2441         return 0.0;
2442     if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2443         /* FBMs use the same flag bit as SVf_IVisUV, so must let them
2444            cache IVs just in case.  */
2445         if (flags & SV_GMAGIC)
2446             mg_get(sv);
2447         if (SvNOKp(sv))
2448             return SvNVX(sv);
2449         if ((SvPOKp(sv) && SvLEN(sv)) && !SvIOKp(sv)) {
2450             if (!SvIOKp(sv) && ckWARN(WARN_NUMERIC) &&
2451                 !grok_number(SvPVX_const(sv), SvCUR(sv), NULL))
2452                 not_a_number(sv);
2453             return Atof(SvPVX_const(sv));
2454         }
2455         if (SvIOKp(sv)) {
2456             if (SvIsUV(sv))
2457                 return (NV)SvUVX(sv);
2458             else
2459                 return (NV)SvIVX(sv);
2460         }
2461         if (SvROK(sv)) {
2462             goto return_rok;
2463         }
2464         assert(SvTYPE(sv) >= SVt_PVMG);
2465         /* This falls through to the report_uninit near the end of the
2466            function. */
2467     } else if (SvTHINKFIRST(sv)) {
2468         if (SvROK(sv)) {
2469         return_rok:
2470             if (SvAMAGIC(sv)) {
2471                 SV *tmpstr;
2472                 if (flags & SV_SKIP_OVERLOAD)
2473                     return 0;
2474                 tmpstr = AMG_CALLun(sv,numer);
2475                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2476                     return SvNV(tmpstr);
2477                 }
2478             }
2479             return PTR2NV(SvRV(sv));
2480         }
2481         if (SvIsCOW(sv)) {
2482             sv_force_normal_flags(sv, 0);
2483         }
2484         if (SvREADONLY(sv) && !SvOK(sv)) {
2485             if (ckWARN(WARN_UNINITIALIZED))
2486                 report_uninit(sv);
2487             return 0.0;
2488         }
2489     }
2490     if (SvTYPE(sv) < SVt_NV) {
2491         /* The logic to use SVt_PVNV if necessary is in sv_upgrade.  */
2492         sv_upgrade(sv, SVt_NV);
2493 #ifdef USE_LONG_DOUBLE
2494         DEBUG_c({
2495             STORE_NUMERIC_LOCAL_SET_STANDARD();
2496             PerlIO_printf(Perl_debug_log,
2497                           "0x%"UVxf" num(%" PERL_PRIgldbl ")\n",
2498                           PTR2UV(sv), SvNVX(sv));
2499             RESTORE_NUMERIC_LOCAL();
2500         });
2501 #else
2502         DEBUG_c({
2503             STORE_NUMERIC_LOCAL_SET_STANDARD();
2504             PerlIO_printf(Perl_debug_log, "0x%"UVxf" num(%"NVgf")\n",
2505                           PTR2UV(sv), SvNVX(sv));
2506             RESTORE_NUMERIC_LOCAL();
2507         });
2508 #endif
2509     }
2510     else if (SvTYPE(sv) < SVt_PVNV)
2511         sv_upgrade(sv, SVt_PVNV);
2512     if (SvNOKp(sv)) {
2513         return SvNVX(sv);
2514     }
2515     if (SvIOKp(sv)) {
2516         SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
2517 #ifdef NV_PRESERVES_UV
2518         if (SvIOK(sv))
2519             SvNOK_on(sv);
2520         else
2521             SvNOKp_on(sv);
2522 #else
2523         /* Only set the public NV OK flag if this NV preserves the IV  */
2524         /* Check it's not 0xFFFFFFFFFFFFFFFF */
2525         if (SvIOK(sv) &&
2526             SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
2527                        : (SvIVX(sv) == I_V(SvNVX(sv))))
2528             SvNOK_on(sv);
2529         else
2530             SvNOKp_on(sv);
2531 #endif
2532     }
2533     else if (SvPOKp(sv) && SvLEN(sv)) {
2534         UV value;
2535         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2536         if (!SvIOKp(sv) && !numtype && ckWARN(WARN_NUMERIC))
2537             not_a_number(sv);
2538 #ifdef NV_PRESERVES_UV
2539         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2540             == IS_NUMBER_IN_UV) {
2541             /* It's definitely an integer */
2542             SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
2543         } else
2544             SvNV_set(sv, Atof(SvPVX_const(sv)));
2545         if (numtype)
2546             SvNOK_on(sv);
2547         else
2548             SvNOKp_on(sv);
2549 #else
2550         SvNV_set(sv, Atof(SvPVX_const(sv)));
2551         /* Only set the public NV OK flag if this NV preserves the value in
2552            the PV at least as well as an IV/UV would.
2553            Not sure how to do this 100% reliably. */
2554         /* if that shift count is out of range then Configure's test is
2555            wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2556            UV_BITS */
2557         if (((UV)1 << NV_PRESERVES_UV_BITS) >
2558             U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2559             SvNOK_on(sv); /* Definitely small enough to preserve all bits */
2560         } else if (!(numtype & IS_NUMBER_IN_UV)) {
2561             /* Can't use strtol etc to convert this string, so don't try.
2562                sv_2iv and sv_2uv will use the NV to convert, not the PV.  */
2563             SvNOK_on(sv);
2564         } else {
2565             /* value has been set.  It may not be precise.  */
2566             if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2567                 /* 2s complement assumption for (UV)IV_MIN  */
2568                 SvNOK_on(sv); /* Integer is too negative.  */
2569             } else {
2570                 SvNOKp_on(sv);
2571                 SvIOKp_on(sv);
2572
2573                 if (numtype & IS_NUMBER_NEG) {
2574                     SvIV_set(sv, -(IV)value);
2575                 } else if (value <= (UV)IV_MAX) {
2576                     SvIV_set(sv, (IV)value);
2577                 } else {
2578                     SvUV_set(sv, value);
2579                     SvIsUV_on(sv);
2580                 }
2581
2582                 if (numtype & IS_NUMBER_NOT_INT) {
2583                     /* I believe that even if the original PV had decimals,
2584                        they are lost beyond the limit of the FP precision.
2585                        However, neither is canonical, so both only get p
2586                        flags.  NWC, 2000/11/25 */
2587                     /* Both already have p flags, so do nothing */
2588                 } else {
2589                     const NV nv = SvNVX(sv);
2590                     if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2591                         if (SvIVX(sv) == I_V(nv)) {
2592                             SvNOK_on(sv);
2593                         } else {
2594                             /* It had no "." so it must be integer.  */
2595                         }
2596                         SvIOK_on(sv);
2597                     } else {
2598                         /* between IV_MAX and NV(UV_MAX).
2599                            Could be slightly > UV_MAX */
2600
2601                         if (numtype & IS_NUMBER_NOT_INT) {
2602                             /* UV and NV both imprecise.  */
2603                         } else {
2604                             const UV nv_as_uv = U_V(nv);
2605
2606                             if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2607                                 SvNOK_on(sv);
2608                             }
2609                             SvIOK_on(sv);
2610                         }
2611                     }
2612                 }
2613             }
2614         }
2615         /* It might be more code efficient to go through the entire logic above
2616            and conditionally set with SvNOKp_on() rather than SvNOK(), but it
2617            gets complex and potentially buggy, so more programmer efficient
2618            to do it this way, by turning off the public flags:  */
2619         if (!numtype)
2620             SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2621 #endif /* NV_PRESERVES_UV */
2622     }
2623     else  {
2624         if (isGV_with_GP(sv)) {
2625             glob_2number(MUTABLE_GV(sv));
2626             return 0.0;
2627         }
2628
2629         if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
2630             report_uninit(sv);
2631         assert (SvTYPE(sv) >= SVt_NV);
2632         /* Typically the caller expects that sv_any is not NULL now.  */
2633         /* XXX Ilya implies that this is a bug in callers that assume this
2634            and ideally should be fixed.  */
2635         return 0.0;
2636     }
2637 #if defined(USE_LONG_DOUBLE)
2638     DEBUG_c({
2639         STORE_NUMERIC_LOCAL_SET_STANDARD();
2640         PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" PERL_PRIgldbl ")\n",
2641                       PTR2UV(sv), SvNVX(sv));
2642         RESTORE_NUMERIC_LOCAL();
2643     });
2644 #else
2645     DEBUG_c({
2646         STORE_NUMERIC_LOCAL_SET_STANDARD();
2647         PerlIO_printf(Perl_debug_log, "0x%"UVxf" 1nv(%"NVgf")\n",
2648                       PTR2UV(sv), SvNVX(sv));
2649         RESTORE_NUMERIC_LOCAL();
2650     });
2651 #endif
2652     return SvNVX(sv);
2653 }
2654
2655 /*
2656 =for apidoc sv_2num
2657
2658 Return an SV with the numeric value of the source SV, doing any necessary
2659 reference or overload conversion.  You must use the C<SvNUM(sv)> macro to
2660 access this function.
2661
2662 =cut
2663 */
2664
2665 SV *
2666 Perl_sv_2num(pTHX_ register SV *const sv)
2667 {
2668     PERL_ARGS_ASSERT_SV_2NUM;
2669
2670     if (!SvROK(sv))
2671         return sv;
2672     if (SvAMAGIC(sv)) {
2673         SV * const tmpsv = AMG_CALLun(sv,numer);
2674         if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
2675             return sv_2num(tmpsv);
2676     }
2677     return sv_2mortal(newSVuv(PTR2UV(SvRV(sv))));
2678 }
2679
2680 /* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2681  * UV as a string towards the end of buf, and return pointers to start and
2682  * end of it.
2683  *
2684  * We assume that buf is at least TYPE_CHARS(UV) long.
2685  */
2686
2687 static char *
2688 S_uiv_2buf(char *const buf, const IV iv, UV uv, const int is_uv, char **const peob)
2689 {
2690     char *ptr = buf + TYPE_CHARS(UV);
2691     char * const ebuf = ptr;
2692     int sign;
2693
2694     PERL_ARGS_ASSERT_UIV_2BUF;
2695
2696     if (is_uv)
2697         sign = 0;
2698     else if (iv >= 0) {
2699         uv = iv;
2700         sign = 0;
2701     } else {
2702         uv = -iv;
2703         sign = 1;
2704     }
2705     do {
2706         *--ptr = '0' + (char)(uv % 10);
2707     } while (uv /= 10);
2708     if (sign)
2709         *--ptr = '-';
2710     *peob = ebuf;
2711     return ptr;
2712 }
2713
2714 /*
2715 =for apidoc sv_2pv_flags
2716
2717 Returns a pointer to the string value of an SV, and sets *lp to its length.
2718 If flags includes SV_GMAGIC, does an mg_get() first. Coerces sv to a string
2719 if necessary.
2720 Normally invoked via the C<SvPV_flags> macro. C<sv_2pv()> and C<sv_2pv_nomg>
2721 usually end up here too.
2722
2723 =cut
2724 */
2725
2726 char *
2727 Perl_sv_2pv_flags(pTHX_ register SV *const sv, STRLEN *const lp, const I32 flags)
2728 {
2729     dVAR;
2730     register char *s;
2731
2732     if (!sv) {
2733         if (lp)
2734             *lp = 0;
2735         return (char *)"";
2736     }
2737     if (SvGMAGICAL(sv)) {
2738         if (flags & SV_GMAGIC)
2739             mg_get(sv);
2740         if (SvPOKp(sv)) {
2741             if (lp)
2742                 *lp = SvCUR(sv);
2743             if (flags & SV_MUTABLE_RETURN)
2744                 return SvPVX_mutable(sv);
2745             if (flags & SV_CONST_RETURN)
2746                 return (char *)SvPVX_const(sv);
2747             return SvPVX(sv);
2748         }
2749         if (SvIOKp(sv) || SvNOKp(sv)) {
2750             char tbuf[64];  /* Must fit sprintf/Gconvert of longest IV/NV */
2751             STRLEN len;
2752
2753             if (SvIOKp(sv)) {
2754                 len = SvIsUV(sv)
2755                     ? my_snprintf(tbuf, sizeof(tbuf), "%"UVuf, (UV)SvUVX(sv))
2756                     : my_snprintf(tbuf, sizeof(tbuf), "%"IVdf, (IV)SvIVX(sv));
2757             } else {
2758                 Gconvert(SvNVX(sv), NV_DIG, 0, tbuf);
2759                 len = strlen(tbuf);
2760             }
2761             assert(!SvROK(sv));
2762             {
2763                 dVAR;
2764
2765 #ifdef FIXNEGATIVEZERO
2766                 if (len == 2 && tbuf[0] == '-' && tbuf[1] == '0') {
2767                     tbuf[0] = '0';
2768                     tbuf[1] = 0;
2769                     len = 1;
2770                 }
2771 #endif
2772                 SvUPGRADE(sv, SVt_PV);
2773                 if (lp)
2774                     *lp = len;
2775                 s = SvGROW_mutable(sv, len + 1);
2776                 SvCUR_set(sv, len);
2777                 SvPOKp_on(sv);
2778                 return (char*)memcpy(s, tbuf, len + 1);
2779             }
2780         }
2781         if (SvROK(sv)) {
2782             goto return_rok;
2783         }
2784         assert(SvTYPE(sv) >= SVt_PVMG);
2785         /* This falls through to the report_uninit near the end of the
2786            function. */
2787     } else if (SvTHINKFIRST(sv)) {
2788         if (SvROK(sv)) {
2789         return_rok:
2790             if (SvAMAGIC(sv)) {
2791                 SV *tmpstr;
2792                 if (flags & SV_SKIP_OVERLOAD)
2793                     return NULL;
2794                 tmpstr = AMG_CALLun(sv,string);
2795                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2796                     /* Unwrap this:  */
2797                     /* char *pv = lp ? SvPV(tmpstr, *lp) : SvPV_nolen(tmpstr);
2798                      */
2799
2800                     char *pv;
2801                     if ((SvFLAGS(tmpstr) & (SVf_POK)) == SVf_POK) {
2802                         if (flags & SV_CONST_RETURN) {
2803                             pv = (char *) SvPVX_const(tmpstr);
2804                         } else {
2805                             pv = (flags & SV_MUTABLE_RETURN)
2806                                 ? SvPVX_mutable(tmpstr) : SvPVX(tmpstr);
2807                         }
2808                         if (lp)
2809                             *lp = SvCUR(tmpstr);
2810                     } else {
2811                         pv = sv_2pv_flags(tmpstr, lp, flags);
2812                     }
2813                     if (SvUTF8(tmpstr))
2814                         SvUTF8_on(sv);
2815                     else
2816                         SvUTF8_off(sv);
2817                     return pv;
2818                 }
2819             }
2820             {
2821                 STRLEN len;
2822                 char *retval;
2823                 char *buffer;
2824                 SV *const referent = SvRV(sv);
2825
2826                 if (!referent) {
2827                     len = 7;
2828                     retval = buffer = savepvn("NULLREF", len);
2829                 } else if (SvTYPE(referent) == SVt_REGEXP) {
2830                     REGEXP * const re = (REGEXP *)MUTABLE_PTR(referent);
2831                     I32 seen_evals = 0;
2832
2833                     assert(re);
2834                         
2835                     /* If the regex is UTF-8 we want the containing scalar to
2836                        have an UTF-8 flag too */
2837                     if (RX_UTF8(re))
2838                         SvUTF8_on(sv);
2839                     else
2840                         SvUTF8_off(sv); 
2841
2842                     if ((seen_evals = RX_SEEN_EVALS(re)))
2843                         PL_reginterp_cnt += seen_evals;
2844
2845                     if (lp)
2846                         *lp = RX_WRAPLEN(re);
2847  
2848                     return RX_WRAPPED(re);
2849                 } else {
2850                     const char *const typestr = sv_reftype(referent, 0);
2851                     const STRLEN typelen = strlen(typestr);
2852                     UV addr = PTR2UV(referent);
2853                     const char *stashname = NULL;
2854                     STRLEN stashnamelen = 0; /* hush, gcc */
2855                     const char *buffer_end;
2856
2857                     if (SvOBJECT(referent)) {
2858                         const HEK *const name = HvNAME_HEK(SvSTASH(referent));
2859
2860                         if (name) {
2861                             stashname = HEK_KEY(name);
2862                             stashnamelen = HEK_LEN(name);
2863
2864                             if (HEK_UTF8(name)) {
2865                                 SvUTF8_on(sv);
2866                             } else {
2867                                 SvUTF8_off(sv);
2868                             }
2869                         } else {
2870                             stashname = "__ANON__";
2871                             stashnamelen = 8;
2872                         }
2873                         len = stashnamelen + 1 /* = */ + typelen + 3 /* (0x */
2874                             + 2 * sizeof(UV) + 2 /* )\0 */;
2875                     } else {
2876                         len = typelen + 3 /* (0x */
2877                             + 2 * sizeof(UV) + 2 /* )\0 */;
2878                     }
2879
2880                     Newx(buffer, len, char);
2881                     buffer_end = retval = buffer + len;
2882
2883                     /* Working backwards  */
2884                     *--retval = '\0';
2885                     *--retval = ')';
2886                     do {
2887                         *--retval = PL_hexdigit[addr & 15];
2888                     } while (addr >>= 4);
2889                     *--retval = 'x';
2890                     *--retval = '0';
2891                     *--retval = '(';
2892
2893                     retval -= typelen;
2894                     memcpy(retval, typestr, typelen);
2895
2896                     if (stashname) {
2897                         *--retval = '=';
2898                         retval -= stashnamelen;
2899                         memcpy(retval, stashname, stashnamelen);
2900                     }
2901                     /* retval may not neccesarily have reached the start of the
2902                        buffer here.  */
2903                     assert (retval >= buffer);
2904
2905                     len = buffer_end - retval - 1; /* -1 for that \0  */
2906                 }
2907                 if (lp)
2908                     *lp = len;
2909                 SAVEFREEPV(buffer);
2910                 return retval;
2911             }
2912         }
2913         if (SvREADONLY(sv) && !SvOK(sv)) {
2914             if (lp)
2915                 *lp = 0;
2916             if (flags & SV_UNDEF_RETURNS_NULL)
2917                 return NULL;
2918             if (ckWARN(WARN_UNINITIALIZED))
2919                 report_uninit(sv);
2920             return (char *)"";
2921         }
2922     }
2923     if (SvIOK(sv) || ((SvIOKp(sv) && !SvNOKp(sv)))) {
2924         /* I'm assuming that if both IV and NV are equally valid then
2925            converting the IV is going to be more efficient */
2926         const U32 isUIOK = SvIsUV(sv);
2927         char buf[TYPE_CHARS(UV)];
2928         char *ebuf, *ptr;
2929         STRLEN len;
2930
2931         if (SvTYPE(sv) < SVt_PVIV)
2932             sv_upgrade(sv, SVt_PVIV);
2933         ptr = uiv_2buf(buf, SvIVX(sv), SvUVX(sv), isUIOK, &ebuf);
2934         len = ebuf - ptr;
2935         /* inlined from sv_setpvn */
2936         s = SvGROW_mutable(sv, len + 1);
2937         Move(ptr, s, len, char);
2938         s += len;
2939         *s = '\0';
2940     }
2941     else if (SvNOKp(sv)) {
2942         dSAVE_ERRNO;
2943         if (SvTYPE(sv) < SVt_PVNV)
2944             sv_upgrade(sv, SVt_PVNV);
2945         /* The +20 is pure guesswork.  Configure test needed. --jhi */
2946         s = SvGROW_mutable(sv, NV_DIG + 20);
2947         /* some Xenix systems wipe out errno here */
2948 #ifdef apollo
2949         if (SvNVX(sv) == 0.0)
2950             my_strlcpy(s, "0", SvLEN(sv));
2951         else
2952 #endif /*apollo*/
2953         {
2954             Gconvert(SvNVX(sv), NV_DIG, 0, s);
2955         }
2956         RESTORE_ERRNO;
2957 #ifdef FIXNEGATIVEZERO
2958         if (*s == '-' && s[1] == '0' && !s[2]) {
2959             s[0] = '0';
2960             s[1] = 0;
2961         }
2962 #endif
2963         while (*s) s++;
2964 #ifdef hcx
2965         if (s[-1] == '.')
2966             *--s = '\0';
2967 #endif
2968     }
2969     else {
2970         if (isGV_with_GP(sv)) {
2971             GV *const gv = MUTABLE_GV(sv);
2972             const U32 wasfake = SvFLAGS(gv) & SVf_FAKE;
2973             SV *const buffer = sv_newmortal();
2974
2975             /* FAKE globs can get coerced, so need to turn this off temporarily
2976                if it is on.  */
2977             SvFAKE_off(gv);
2978             gv_efullname3(buffer, gv, "*");
2979             SvFLAGS(gv) |= wasfake;
2980
2981             if (SvPOK(buffer)) {
2982                 if (lp) {
2983                     *lp = SvCUR(buffer);
2984                 }
2985                 return SvPVX(buffer);
2986             }
2987             else {
2988                 if (lp)
2989                     *lp = 0;
2990                 return (char *)"";
2991             }
2992         }
2993
2994         if (lp)
2995             *lp = 0;
2996         if (flags & SV_UNDEF_RETURNS_NULL)
2997             return NULL;
2998         if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
2999             report_uninit(sv);
3000         if (SvTYPE(sv) < SVt_PV)
3001             /* Typically the caller expects that sv_any is not NULL now.  */
3002             sv_upgrade(sv, SVt_PV);
3003         return (char *)"";
3004     }
3005     {
3006         const STRLEN len = s - SvPVX_const(sv);
3007         if (lp) 
3008             *lp = len;
3009         SvCUR_set(sv, len);
3010     }
3011     SvPOK_on(sv);
3012     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
3013                           PTR2UV(sv),SvPVX_const(sv)));
3014     if (flags & SV_CONST_RETURN)
3015         return (char *)SvPVX_const(sv);
3016     if (flags & SV_MUTABLE_RETURN)
3017         return SvPVX_mutable(sv);
3018     return SvPVX(sv);
3019 }
3020
3021 /*
3022 =for apidoc sv_copypv
3023
3024 Copies a stringified representation of the source SV into the
3025 destination SV.  Automatically performs any necessary mg_get and
3026 coercion of numeric values into strings.  Guaranteed to preserve
3027 UTF8 flag even from overloaded objects.  Similar in nature to
3028 sv_2pv[_flags] but operates directly on an SV instead of just the
3029 string.  Mostly uses sv_2pv_flags to do its work, except when that
3030 would lose the UTF-8'ness of the PV.
3031
3032 =cut
3033 */
3034
3035 void
3036 Perl_sv_copypv(pTHX_ SV *const dsv, register SV *const ssv)
3037 {
3038     STRLEN len;
3039     const char * const s = SvPV_const(ssv,len);
3040
3041     PERL_ARGS_ASSERT_SV_COPYPV;
3042
3043     sv_setpvn(dsv,s,len);
3044     if (SvUTF8(ssv))
3045         SvUTF8_on(dsv);
3046     else
3047         SvUTF8_off(dsv);
3048 }
3049
3050 /*
3051 =for apidoc sv_2pvbyte
3052
3053 Return a pointer to the byte-encoded representation of the SV, and set *lp
3054 to its length.  May cause the SV to be downgraded from UTF-8 as a
3055 side-effect.
3056
3057 Usually accessed via the C<SvPVbyte> macro.
3058
3059 =cut
3060 */
3061
3062 char *
3063 Perl_sv_2pvbyte(pTHX_ register SV *const sv, STRLEN *const lp)
3064 {
3065     PERL_ARGS_ASSERT_SV_2PVBYTE;
3066
3067     sv_utf8_downgrade(sv,0);
3068     return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
3069 }
3070
3071 /*
3072 =for apidoc sv_2pvutf8
3073
3074 Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
3075 to its length.  May cause the SV to be upgraded to UTF-8 as a side-effect.
3076
3077 Usually accessed via the C<SvPVutf8> macro.
3078
3079 =cut
3080 */
3081
3082 char *
3083 Perl_sv_2pvutf8(pTHX_ register SV *const sv, STRLEN *const lp)
3084 {
3085     PERL_ARGS_ASSERT_SV_2PVUTF8;
3086
3087     sv_utf8_upgrade(sv);
3088     return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
3089 }
3090
3091
3092 /*
3093 =for apidoc sv_2bool
3094
3095 This function is only called on magical items, and is only used by
3096 sv_true() or its macro equivalent.
3097
3098 =cut
3099 */
3100
3101 bool
3102 Perl_sv_2bool(pTHX_ register SV *const sv)
3103 {
3104     dVAR;
3105
3106     PERL_ARGS_ASSERT_SV_2BOOL;
3107
3108     SvGETMAGIC(sv);
3109
3110     if (!SvOK(sv))
3111         return 0;
3112     if (SvROK(sv)) {
3113         if (SvAMAGIC(sv)) {
3114             SV * const tmpsv = AMG_CALLun(sv,bool_);
3115             if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
3116                 return cBOOL(SvTRUE(tmpsv));
3117         }
3118         return SvRV(sv) != 0;
3119     }
3120     if (SvPOKp(sv)) {
3121         register XPV* const Xpvtmp = (XPV*)SvANY(sv);
3122         if (Xpvtmp &&
3123                 (*sv->sv_u.svu_pv > '0' ||
3124                 Xpvtmp->xpv_cur > 1 ||
3125                 (Xpvtmp->xpv_cur && *sv->sv_u.svu_pv != '0')))
3126             return 1;
3127         else
3128             return 0;
3129     }
3130     else {
3131         if (SvIOKp(sv))
3132             return SvIVX(sv) != 0;
3133         else {
3134             if (SvNOKp(sv))
3135                 return SvNVX(sv) != 0.0;
3136             else {
3137                 if (isGV_with_GP(sv))
3138                     return TRUE;
3139                 else
3140                     return FALSE;
3141             }
3142         }
3143     }
3144 }
3145
3146 /*
3147 =for apidoc sv_utf8_upgrade
3148
3149 Converts the PV of an SV to its UTF-8-encoded form.
3150 Forces the SV to string form if it is not already.
3151 Will C<mg_get> on C<sv> if appropriate.
3152 Always sets the SvUTF8 flag to avoid future validity checks even
3153 if the whole string is the same in UTF-8 as not.
3154 Returns the number of bytes in the converted string
3155
3156 This is not as a general purpose byte encoding to Unicode interface:
3157 use the Encode extension for that.
3158
3159 =for apidoc sv_utf8_upgrade_nomg
3160
3161 Like sv_utf8_upgrade, but doesn't do magic on C<sv>
3162
3163 =for apidoc sv_utf8_upgrade_flags
3164
3165 Converts the PV of an SV to its UTF-8-encoded form.
3166 Forces the SV to string form if it is not already.
3167 Always sets the SvUTF8 flag to avoid future validity checks even
3168 if all the bytes are invariant in UTF-8. If C<flags> has C<SV_GMAGIC> bit set,
3169 will C<mg_get> on C<sv> if appropriate, else not.
3170 Returns the number of bytes in the converted string
3171 C<sv_utf8_upgrade> and
3172 C<sv_utf8_upgrade_nomg> are implemented in terms of this function.
3173
3174 This is not as a general purpose byte encoding to Unicode interface:
3175 use the Encode extension for that.
3176
3177 =cut
3178
3179 The grow version is currently not externally documented.  It adds a parameter,
3180 extra, which is the number of unused bytes the string of 'sv' is guaranteed to
3181 have free after it upon return.  This allows the caller to reserve extra space
3182 that it intends to fill, to avoid extra grows.
3183
3184 Also externally undocumented for the moment is the flag SV_FORCE_UTF8_UPGRADE,
3185 which can be used to tell this function to not first check to see if there are
3186 any characters that are different in UTF-8 (variant characters) which would
3187 force it to allocate a new string to sv, but to assume there are.  Typically
3188 this flag is used by a routine that has already parsed the string to find that
3189 there are such characters, and passes this information on so that the work
3190 doesn't have to be repeated.
3191
3192 (One might think that the calling routine could pass in the position of the
3193 first such variant, so it wouldn't have to be found again.  But that is not the
3194 case, because typically when the caller is likely to use this flag, it won't be
3195 calling this routine unless it finds something that won't fit into a byte.
3196 Otherwise it tries to not upgrade and just use bytes.  But some things that
3197 do fit into a byte are variants in utf8, and the caller may not have been
3198 keeping track of these.)
3199
3200 If the routine itself changes the string, it adds a trailing NUL.  Such a NUL
3201 isn't guaranteed due to having other routines do the work in some input cases,
3202 or if the input is already flagged as being in utf8.
3203
3204 The speed of this could perhaps be improved for many cases if someone wanted to
3205 write a fast function that counts the number of variant characters in a string,
3206 especially if it could return the position of the first one.
3207
3208 */
3209
3210 STRLEN
3211 Perl_sv_utf8_upgrade_flags_grow(pTHX_ register SV *const sv, const I32 flags, STRLEN extra)
3212 {
3213     dVAR;
3214
3215     PERL_ARGS_ASSERT_SV_UTF8_UPGRADE_FLAGS_GROW;
3216
3217     if (sv == &PL_sv_undef)
3218         return 0;
3219     if (!SvPOK(sv)) {
3220         STRLEN len = 0;
3221         if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
3222             (void) sv_2pv_flags(sv,&len, flags);
3223             if (SvUTF8(sv)) {
3224                 if (extra) SvGROW(sv, SvCUR(sv) + extra);
3225                 return len;
3226             }
3227         } else {
3228             (void) SvPV_force(sv,len);
3229         }
3230     }
3231
3232     if (SvUTF8(sv)) {
3233         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3234         return SvCUR(sv);
3235     }
3236
3237     if (SvIsCOW(sv)) {
3238         sv_force_normal_flags(sv, 0);
3239     }
3240
3241     if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING)) {
3242         sv_recode_to_utf8(sv, PL_encoding);
3243         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3244         return SvCUR(sv);
3245     }
3246
3247     if (SvCUR(sv) == 0) {
3248         if (extra) SvGROW(sv, extra);
3249     } else { /* Assume Latin-1/EBCDIC */
3250         /* This function could be much more efficient if we
3251          * had a FLAG in SVs to signal if there are any variant
3252          * chars in the PV.  Given that there isn't such a flag
3253          * make the loop as fast as possible (although there are certainly ways
3254          * to speed this up, eg. through vectorization) */
3255         U8 * s = (U8 *) SvPVX_const(sv);
3256         U8 * e = (U8 *) SvEND(sv);
3257         U8 *t = s;
3258         STRLEN two_byte_count = 0;
3259         
3260         if (flags & SV_FORCE_UTF8_UPGRADE) goto must_be_utf8;
3261
3262         /* See if really will need to convert to utf8.  We mustn't rely on our
3263          * incoming SV being well formed and having a trailing '\0', as certain
3264          * code in pp_formline can send us partially built SVs. */
3265
3266         while (t < e) {
3267             const U8 ch = *t++;
3268             if (NATIVE_IS_INVARIANT(ch)) continue;
3269
3270             t--;    /* t already incremented; re-point to first variant */
3271             two_byte_count = 1;
3272             goto must_be_utf8;
3273         }
3274
3275         /* utf8 conversion not needed because all are invariants.  Mark as
3276          * UTF-8 even if no variant - saves scanning loop */
3277         SvUTF8_on(sv);
3278         return SvCUR(sv);
3279
3280 must_be_utf8:
3281
3282         /* Here, the string should be converted to utf8, either because of an
3283          * input flag (two_byte_count = 0), or because a character that
3284          * requires 2 bytes was found (two_byte_count = 1).  t points either to
3285          * the beginning of the string (if we didn't examine anything), or to
3286          * the first variant.  In either case, everything from s to t - 1 will
3287          * occupy only 1 byte each on output.
3288          *
3289          * There are two main ways to convert.  One is to create a new string
3290          * and go through the input starting from the beginning, appending each
3291          * converted value onto the new string as we go along.  It's probably
3292          * best to allocate enough space in the string for the worst possible
3293          * case rather than possibly running out of space and having to
3294          * reallocate and then copy what we've done so far.  Since everything
3295          * from s to t - 1 is invariant, the destination can be initialized
3296          * with these using a fast memory copy
3297          *
3298          * The other way is to figure out exactly how big the string should be
3299          * by parsing the entire input.  Then you don't have to make it big
3300          * enough to handle the worst possible case, and more importantly, if
3301          * the string you already have is large enough, you don't have to
3302          * allocate a new string, you can copy the last character in the input
3303          * string to the final position(s) that will be occupied by the
3304          * converted string and go backwards, stopping at t, since everything
3305          * before that is invariant.
3306          *
3307          * There are advantages and disadvantages to each method.
3308          *
3309          * In the first method, we can allocate a new string, do the memory
3310          * copy from the s to t - 1, and then proceed through the rest of the
3311          * string byte-by-byte.
3312          *
3313          * In the second method, we proceed through the rest of the input
3314          * string just calculating how big the converted string will be.  Then
3315          * there are two cases:
3316          *  1)  if the string has enough extra space to handle the converted
3317          *      value.  We go backwards through the string, converting until we
3318          *      get to the position we are at now, and then stop.  If this
3319          *      position is far enough along in the string, this method is
3320          *      faster than the other method.  If the memory copy were the same
3321          *      speed as the byte-by-byte loop, that position would be about
3322          *      half-way, as at the half-way mark, parsing to the end and back
3323          *      is one complete string's parse, the same amount as starting
3324          *      over and going all the way through.  Actually, it would be
3325          *      somewhat less than half-way, as it's faster to just count bytes
3326          *      than to also copy, and we don't have the overhead of allocating
3327          *      a new string, changing the scalar to use it, and freeing the
3328          *      existing one.  But if the memory copy is fast, the break-even
3329          *      point is somewhere after half way.  The counting loop could be
3330          *      sped up by vectorization, etc, to move the break-even point
3331          *      further towards the beginning.
3332          *  2)  if the string doesn't have enough space to handle the converted
3333          *      value.  A new string will have to be allocated, and one might
3334          *      as well, given that, start from the beginning doing the first
3335          *      method.  We've spent extra time parsing the string and in
3336          *      exchange all we've gotten is that we know precisely how big to
3337          *      make the new one.  Perl is more optimized for time than space,
3338          *      so this case is a loser.
3339          * So what I've decided to do is not use the 2nd method unless it is
3340          * guaranteed that a new string won't have to be allocated, assuming
3341          * the worst case.  I also decided not to put any more conditions on it
3342          * than this, for now.  It seems likely that, since the worst case is
3343          * twice as big as the unknown portion of the string (plus 1), we won't
3344          * be guaranteed enough space, causing us to go to the first method,
3345          * unless the string is short, or the first variant character is near
3346          * the end of it.  In either of these cases, it seems best to use the
3347          * 2nd method.  The only circumstance I can think of where this would
3348          * be really slower is if the string had once had much more data in it
3349          * than it does now, but there is still a substantial amount in it  */
3350
3351         {
3352             STRLEN invariant_head = t - s;
3353             STRLEN size = invariant_head + (e - t) * 2 + 1 + extra;
3354             if (SvLEN(sv) < size) {
3355
3356                 /* Here, have decided to allocate a new string */
3357
3358                 U8 *dst;
3359                 U8 *d;
3360
3361                 Newx(dst, size, U8);
3362
3363                 /* If no known invariants at the beginning of the input string,
3364                  * set so starts from there.  Otherwise, can use memory copy to
3365                  * get up to where we are now, and then start from here */
3366
3367                 if (invariant_head <= 0) {
3368                     d = dst;
3369                 } else {
3370                     Copy(s, dst, invariant_head, char);
3371                     d = dst + invariant_head;
3372                 }
3373
3374                 while (t < e) {
3375                     const UV uv = NATIVE8_TO_UNI(*t++);
3376                     if (UNI_IS_INVARIANT(uv))
3377                         *d++ = (U8)UNI_TO_NATIVE(uv);
3378                     else {
3379                         *d++ = (U8)UTF8_EIGHT_BIT_HI(uv);
3380                         *d++ = (U8)UTF8_EIGHT_BIT_LO(uv);
3381                     }
3382                 }
3383                 *d = '\0';
3384                 SvPV_free(sv); /* No longer using pre-existing string */
3385                 SvPV_set(sv, (char*)dst);
3386                 SvCUR_set(sv, d - dst);
3387                 SvLEN_set(sv, size);
3388             } else {
3389
3390                 /* Here, have decided to get the exact size of the string.
3391                  * Currently this happens only when we know that there is
3392                  * guaranteed enough space to fit the converted string, so
3393                  * don't have to worry about growing.  If two_byte_count is 0,
3394                  * then t points to the first byte of the string which hasn't
3395                  * been examined yet.  Otherwise two_byte_count is 1, and t
3396                  * points to the first byte in the string that will expand to
3397                  * two.  Depending on this, start examining at t or 1 after t.
3398                  * */
3399
3400                 U8 *d = t + two_byte_count;
3401
3402
3403                 /* Count up the remaining bytes that expand to two */
3404
3405                 while (d < e) {
3406                     const U8 chr = *d++;
3407                     if (! NATIVE_IS_INVARIANT(chr)) two_byte_count++;
3408                 }
3409
3410                 /* The string will expand by just the number of bytes that
3411                  * occupy two positions.  But we are one afterwards because of
3412                  * the increment just above.  This is the place to put the
3413                  * trailing NUL, and to set the length before we decrement */
3414
3415                 d += two_byte_count;
3416                 SvCUR_set(sv, d - s);
3417                 *d-- = '\0';
3418
3419
3420                 /* Having decremented d, it points to the position to put the
3421                  * very last byte of the expanded string.  Go backwards through
3422                  * the string, copying and expanding as we go, stopping when we
3423                  * get to the part that is invariant the rest of the way down */
3424
3425                 e--;
3426                 while (e >= t) {
3427                     const U8 ch = NATIVE8_TO_UNI(*e--);
3428                     if (UNI_IS_INVARIANT(ch)) {
3429                         *d-- = UNI_TO_NATIVE(ch);
3430                     } else {
3431                         *d-- = (U8)UTF8_EIGHT_BIT_LO(ch);
3432                         *d-- = (U8)UTF8_EIGHT_BIT_HI(ch);
3433                     }
3434                 }
3435             }
3436         }
3437     }
3438
3439     /* Mark as UTF-8 even if no variant - saves scanning loop */
3440     SvUTF8_on(sv);
3441     return SvCUR(sv);
3442 }
3443
3444 /*
3445 =for apidoc sv_utf8_downgrade
3446
3447 Attempts to convert the PV of an SV from characters to bytes.
3448 If the PV contains a character that cannot fit
3449 in a byte, this conversion will fail;
3450 in this case, either returns false or, if C<fail_ok> is not
3451 true, croaks.
3452
3453 This is not as a general purpose Unicode to byte encoding interface:
3454 use the Encode extension for that.
3455
3456 =cut
3457 */
3458
3459 bool
3460 Perl_sv_utf8_downgrade(pTHX_ register SV *const sv, const bool fail_ok)
3461 {
3462     dVAR;
3463
3464     PERL_ARGS_ASSERT_SV_UTF8_DOWNGRADE;
3465
3466     if (SvPOKp(sv) && SvUTF8(sv)) {
3467         if (SvCUR(sv)) {
3468             U8 *s;
3469             STRLEN len;
3470
3471             if (SvIsCOW(sv)) {
3472                 sv_force_normal_flags(sv, 0);
3473             }
3474             s = (U8 *) SvPV(sv, len);
3475             if (!utf8_to_bytes(s, &len)) {
3476                 if (fail_ok)
3477                     return FALSE;
3478                 else {
3479                     if (PL_op)
3480                         Perl_croak(aTHX_ "Wide character in %s",
3481                                    OP_DESC(PL_op));
3482                     else
3483                         Perl_croak(aTHX_ "Wide character");
3484                 }
3485             }
3486             SvCUR_set(sv, len);
3487         }
3488     }
3489     SvUTF8_off(sv);
3490     return TRUE;
3491 }
3492
3493 /*
3494 =for apidoc sv_utf8_encode
3495
3496 Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3497 flag off so that it looks like octets again.
3498
3499 =cut
3500 */
3501
3502 void
3503 Perl_sv_utf8_encode(pTHX_ register SV *const sv)
3504 {
3505     PERL_ARGS_ASSERT_SV_UTF8_ENCODE;
3506
3507     if (SvIsCOW(sv)) {
3508         sv_force_normal_flags(sv, 0);
3509     }
3510     if (SvREADONLY(sv)) {
3511         Perl_croak(aTHX_ "%s", PL_no_modify);
3512     }
3513     (void) sv_utf8_upgrade(sv);
3514     SvUTF8_off(sv);
3515 }
3516
3517 /*
3518 =for apidoc sv_utf8_decode
3519
3520 If the PV of the SV is an octet sequence in UTF-8
3521 and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3522 so that it looks like a character. If the PV contains only single-byte
3523 characters, the C<SvUTF8> flag stays being off.
3524 Scans PV for validity and returns false if the PV is invalid UTF-8.
3525
3526 =cut
3527 */
3528
3529 bool
3530 Perl_sv_utf8_decode(pTHX_ register SV *const sv)
3531 {
3532     PERL_ARGS_ASSERT_SV_UTF8_DECODE;
3533
3534     if (SvPOKp(sv)) {
3535         const U8 *c;
3536         const U8 *e;
3537
3538         /* The octets may have got themselves encoded - get them back as
3539          * bytes
3540          */
3541         if (!sv_utf8_downgrade(sv, TRUE))
3542             return FALSE;
3543
3544         /* it is actually just a matter of turning the utf8 flag on, but
3545          * we want to make sure everything inside is valid utf8 first.
3546          */
3547         c = (const U8 *) SvPVX_const(sv);
3548         if (!is_utf8_string(c, SvCUR(sv)+1))
3549             return FALSE;
3550         e = (const U8 *) SvEND(sv);
3551         while (c < e) {
3552             const U8 ch = *c++;
3553             if (!UTF8_IS_INVARIANT(ch)) {
3554                 SvUTF8_on(sv);
3555                 break;
3556             }
3557         }
3558     }
3559     return TRUE;
3560 }
3561
3562 /*
3563 =for apidoc sv_setsv
3564
3565 Copies the contents of the source SV C<ssv> into the destination SV
3566 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3567 function if the source SV needs to be reused. Does not handle 'set' magic.
3568 Loosely speaking, it performs a copy-by-value, obliterating any previous
3569 content of the destination.
3570
3571 You probably want to use one of the assortment of wrappers, such as
3572 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3573 C<SvSetMagicSV_nosteal>.
3574
3575 =for apidoc sv_setsv_flags
3576
3577 Copies the contents of the source SV C<ssv> into the destination SV
3578 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3579 function if the source SV needs to be reused. Does not handle 'set' magic.
3580 Loosely speaking, it performs a copy-by-value, obliterating any previous
3581 content of the destination.
3582 If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
3583 C<ssv> if appropriate, else not. If the C<flags> parameter has the
3584 C<NOSTEAL> bit set then the buffers of temps will not be stolen. <sv_setsv>
3585 and C<sv_setsv_nomg> are implemented in terms of this function.
3586
3587 You probably want to use one of the assortment of wrappers, such as
3588 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3589 C<SvSetMagicSV_nosteal>.
3590
3591 This is the primary function for copying scalars, and most other
3592 copy-ish functions and macros use this underneath.
3593
3594 =cut
3595 */
3596
3597 static void
3598 S_glob_assign_glob(pTHX_ SV *const dstr, SV *const sstr, const int dtype)
3599 {
3600     I32 mro_changes = 0; /* 1 = method, 2 = isa */
3601
3602     PERL_ARGS_ASSERT_GLOB_ASSIGN_GLOB;
3603
3604     if (dtype != SVt_PVGV) {
3605         const char * const name = GvNAME(sstr);
3606         const STRLEN len = GvNAMELEN(sstr);
3607         {
3608             if (dtype >= SVt_PV) {
3609                 SvPV_free(dstr);
3610                 SvPV_set(dstr, 0);
3611                 SvLEN_set(dstr, 0);
3612                 SvCUR_set(dstr, 0);
3613             }
3614             SvUPGRADE(dstr, SVt_PVGV);
3615             (void)SvOK_off(dstr);
3616             /* FIXME - why are we doing this, then turning it off and on again
3617                below?  */
3618             isGV_with_GP_on(dstr);
3619         }
3620         GvSTASH(dstr) = GvSTASH(sstr);
3621         if (GvSTASH(dstr))
3622             Perl_sv_add_backref(aTHX_ MUTABLE_SV(GvSTASH(dstr)), dstr);
3623         gv_name_set(MUTABLE_GV(dstr), name, len, GV_ADD);
3624         SvFAKE_on(dstr);        /* can coerce to non-glob */
3625     }
3626
3627     if(GvGP(MUTABLE_GV(sstr))) {
3628         /* If source has method cache entry, clear it */
3629         if(GvCVGEN(sstr)) {
3630             SvREFCNT_dec(GvCV(sstr));
3631             GvCV(sstr) = NULL;
3632             GvCVGEN(sstr) = 0;
3633         }
3634         /* If source has a real method, then a method is
3635            going to change */
3636         else if(GvCV((const GV *)sstr)) {
3637             mro_changes = 1;
3638         }
3639     }
3640
3641     /* If dest already had a real method, that's a change as well */
3642     if(!mro_changes && GvGP(MUTABLE_GV(dstr)) && GvCVu((const GV *)dstr)) {
3643         mro_changes = 1;
3644     }
3645
3646     if(strEQ(GvNAME((const GV *)dstr),"ISA"))
3647         mro_changes = 2;
3648
3649     gp_free(MUTABLE_GV(dstr));
3650     isGV_with_GP_off(dstr);
3651     (void)SvOK_off(dstr);
3652     isGV_with_GP_on(dstr);
3653     GvINTRO_off(dstr);          /* one-shot flag */
3654     GvGP(dstr) = gp_ref(GvGP(sstr));
3655     if (SvTAINTED(sstr))
3656         SvTAINT(dstr);
3657     if (GvIMPORTED(dstr) != GVf_IMPORTED
3658         && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3659         {
3660             GvIMPORTED_on(dstr);
3661         }
3662     GvMULTI_on(dstr);
3663     if(mro_changes == 2) mro_isa_changed_in(GvSTASH(dstr));
3664     else if(mro_changes) mro_method_changed_in(GvSTASH(dstr));
3665     return;
3666 }
3667
3668 static void
3669 S_glob_assign_ref(pTHX_ SV *const dstr, SV *const sstr)
3670 {
3671     SV * const sref = SvREFCNT_inc(SvRV(sstr));
3672     SV *dref = NULL;
3673     const int intro = GvINTRO(dstr);
3674     SV **location;
3675     U8 import_flag = 0;
3676     const U32 stype = SvTYPE(sref);
3677
3678     PERL_ARGS_ASSERT_GLOB_ASSIGN_REF;
3679
3680     if (intro) {
3681         GvINTRO_off(dstr);      /* one-shot flag */
3682         GvLINE(dstr) = CopLINE(PL_curcop);
3683         GvEGV(dstr) = MUTABLE_GV(dstr);
3684     }
3685     GvMULTI_on(dstr);
3686     switch (stype) {
3687     case SVt_PVCV:
3688         location = (SV **) &GvCV(dstr);
3689         import_flag = GVf_IMPORTED_CV;
3690         goto common;
3691     case SVt_PVHV:
3692         location = (SV **) &GvHV(dstr);
3693         import_flag = GVf_IMPORTED_HV;
3694         goto common;
3695     case SVt_PVAV:
3696         location = (SV **) &GvAV(dstr);
3697         import_flag = GVf_IMPORTED_AV;
3698         goto common;
3699     case SVt_PVIO:
3700         location = (SV **) &GvIOp(dstr);
3701         goto common;
3702     case SVt_PVFM:
3703         location = (SV **) &GvFORM(dstr);
3704         goto common;
3705     default:
3706         location = &GvSV(dstr);
3707         import_flag = GVf_IMPORTED_SV;
3708     common:
3709         if (intro) {
3710             if (stype == SVt_PVCV) {
3711                 /*if (GvCVGEN(dstr) && (GvCV(dstr) != (const CV *)sref || GvCVGEN(dstr))) {*/
3712                 if (GvCVGEN(dstr)) {
3713                     SvREFCNT_dec(GvCV(dstr));
3714                     GvCV(dstr) = NULL;
3715                     GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3716                 }
3717             }
3718             SAVEGENERICSV(*location);
3719         }
3720         else
3721             dref = *location;
3722         if (stype == SVt_PVCV && (*location != sref || GvCVGEN(dstr))) {
3723             CV* const cv = MUTABLE_CV(*location);
3724             if (cv) {
3725                 if (!GvCVGEN((const GV *)dstr) &&
3726                     (CvROOT(cv) || CvXSUB(cv)))
3727                     {
3728                         /* Redefining a sub - warning is mandatory if
3729                            it was a const and its value changed. */
3730                         if (CvCONST(cv) && CvCONST((const CV *)sref)
3731                             && cv_const_sv(cv)
3732                             == cv_const_sv((const CV *)sref)) {
3733                             NOOP;
3734                             /* They are 2 constant subroutines generated from
3735                                the same constant. This probably means that
3736                                they are really the "same" proxy subroutine
3737                                instantiated in 2 places. Most likely this is
3738                                when a constant is exported twice.  Don't warn.
3739                             */
3740                         }
3741                         else if (ckWARN(WARN_REDEFINE)
3742                                  || (CvCONST(cv)
3743                                      && (!CvCONST((const CV *)sref)
3744                                          || sv_cmp(cv_const_sv(cv),
3745                                                    cv_const_sv((const CV *)
3746                                                                sref))))) {
3747                             Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
3748                                         (const char *)
3749                                         (CvCONST(cv)
3750                                          ? "Constant subroutine %s::%s redefined"
3751                                          : "Subroutine %s::%s redefined"),
3752                                         HvNAME_get(GvSTASH((const GV *)dstr)),
3753                                         GvENAME(MUTABLE_GV(dstr)));
3754                         }
3755                     }
3756                 if (!intro)
3757                     cv_ckproto_len(cv, (const GV *)dstr,
3758                                    SvPOK(sref) ? SvPVX_const(sref) : NULL,
3759                                    SvPOK(sref) ? SvCUR(sref) : 0);
3760             }
3761             GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3762             GvASSUMECV_on(dstr);
3763             if(GvSTASH(dstr)) mro_method_changed_in(GvSTASH(dstr)); /* sub foo { 1 } sub bar { 2 } *bar = \&foo */
3764         }
3765         *location = sref;
3766         if (import_flag && !(GvFLAGS(dstr) & import_flag)
3767             && CopSTASH_ne(PL_curcop, GvSTASH(dstr))) {
3768             GvFLAGS(dstr) |= import_flag;
3769         }
3770         if (stype == SVt_PVAV && strEQ(GvNAME((GV*)dstr), "ISA")) {
3771             sv_magic(sref, dstr, PERL_MAGIC_isa, NULL, 0);
3772             mro_isa_changed_in(GvSTASH(dstr));
3773         }
3774         break;
3775     }
3776     SvREFCNT_dec(dref);
3777     if (SvTAINTED(sstr))
3778         SvTAINT(dstr);
3779     return;
3780 }
3781
3782 void
3783 Perl_sv_setsv_flags(pTHX_ SV *dstr, register SV* sstr, const I32 flags)
3784 {
3785     dVAR;
3786     register U32 sflags;
3787     register int dtype;
3788     register svtype stype;
3789
3790     PERL_ARGS_ASSERT_SV_SETSV_FLAGS;
3791
3792     if (sstr == dstr)
3793         return;
3794
3795     if (SvIS_FREED(dstr)) {
3796         Perl_croak(aTHX_ "panic: attempt to copy value %" SVf
3797                    " to a freed scalar %p", SVfARG(sstr), (void *)dstr);
3798     }
3799     SV_CHECK_THINKFIRST_COW_DROP(dstr);
3800     if (!sstr)
3801         sstr = &PL_sv_undef;
3802     if (SvIS_FREED(sstr)) {
3803         Perl_croak(aTHX_ "panic: attempt to copy freed scalar %p to %p",
3804                    (void*)sstr, (void*)dstr);
3805     }
3806     stype = SvTYPE(sstr);
3807     dtype = SvTYPE(dstr);
3808
3809     (void)SvAMAGIC_off(dstr);
3810     if ( SvVOK(dstr) )
3811     {
3812         /* need to nuke the magic */
3813         mg_free(dstr);
3814     }
3815
3816     /* There's a lot of redundancy below but we're going for speed here */
3817
3818     switch (stype) {
3819     case SVt_NULL:
3820       undef_sstr:
3821         if (dtype != SVt_PVGV) {
3822             (void)SvOK_off(dstr);
3823             return;
3824         }
3825         break;
3826     case SVt_IV:
3827         if (SvIOK(sstr)) {
3828             switch (dtype) {
3829             case SVt_NULL:
3830                 sv_upgrade(dstr, SVt_IV);
3831                 break;
3832             case SVt_NV:
3833             case SVt_PV:
3834                 sv_upgrade(dstr, SVt_PVIV);
3835                 break;
3836             case SVt_PVGV:
3837                 goto end_of_first_switch;
3838             }
3839             (void)SvIOK_only(dstr);
3840             SvIV_set(dstr,  SvIVX(sstr));
3841             if (SvIsUV(sstr))
3842                 SvIsUV_on(dstr);
3843             /* SvTAINTED can only be true if the SV has taint magic, which in
3844                turn means that the SV type is PVMG (or greater). This is the
3845                case statement for SVt_IV, so this cannot be true (whatever gcov
3846                may say).  */
3847             assert(!SvTAINTED(sstr));
3848             return;
3849         }
3850         if (!SvROK(sstr))
3851             goto undef_sstr;
3852         if (dtype < SVt_PV && dtype != SVt_IV)
3853             sv_upgrade(dstr, SVt_IV);
3854         break;
3855
3856     case SVt_NV:
3857         if (SvNOK(sstr)) {
3858             switch (dtype) {
3859             case SVt_NULL:
3860             case SVt_IV:
3861                 sv_upgrade(dstr, SVt_NV);
3862                 break;
3863             case SVt_PV:
3864             case SVt_PVIV:
3865                 sv_upgrade(dstr, SVt_PVNV);
3866                 break;
3867             case SVt_PVGV:
3868                 goto end_of_first_switch;
3869             }
3870             SvNV_set(dstr, SvNVX(sstr));
3871             (void)SvNOK_only(dstr);
3872             /* SvTAINTED can only be true if the SV has taint magic, which in
3873                turn means that the SV type is PVMG (or greater). This is the
3874                case statement for SVt_NV, so this cannot be true (whatever gcov
3875                may say).  */
3876             assert(!SvTAINTED(sstr));
3877             return;
3878         }
3879         goto undef_sstr;
3880
3881     case SVt_PVFM:
3882 #ifdef PERL_OLD_COPY_ON_WRITE
3883         if ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS) {
3884             if (dtype < SVt_PVIV)
3885                 sv_upgrade(dstr, SVt_PVIV);
3886             break;
3887         }
3888         /* Fall through */
3889 #endif
3890     case SVt_PV:
3891         if (dtype < SVt_PV)
3892             sv_upgrade(dstr, SVt_PV);
3893         break;
3894     case SVt_PVIV:
3895         if (dtype < SVt_PVIV)
3896             sv_upgrade(dstr, SVt_PVIV);
3897         break;
3898     case SVt_PVNV:
3899         if (dtype < SVt_PVNV)
3900             sv_upgrade(dstr, SVt_PVNV);
3901         break;
3902     default:
3903         {
3904         const char * const type = sv_reftype(sstr,0);
3905         if (PL_op)
3906             Perl_croak(aTHX_ "Bizarre copy of %s in %s", type, OP_DESC(PL_op));
3907         else
3908             Perl_croak(aTHX_ "Bizarre copy of %s", type);
3909         }
3910         break;
3911
3912     case SVt_REGEXP:
3913         if (dtype < SVt_REGEXP)
3914             sv_upgrade(dstr, SVt_REGEXP);
3915         break;
3916
3917         /* case SVt_BIND: */
3918     case SVt_PVLV:
3919     case SVt_PVGV:
3920         if (isGV_with_GP(sstr) && dtype <= SVt_PVGV) {
3921             glob_assign_glob(dstr, sstr, dtype);
3922             return;
3923         }
3924         /* SvVALID means that this PVGV is playing at being an FBM.  */
3925         /*FALLTHROUGH*/
3926
3927     case SVt_PVMG:
3928         if (SvGMAGICAL(sstr) && (flags & SV_GMAGIC)) {
3929             mg_get(sstr);
3930             if (SvTYPE(sstr) != stype) {
3931                 stype = SvTYPE(sstr);
3932                 if (isGV_with_GP(sstr) && stype == SVt_PVGV && dtype <= SVt_PVGV) {
3933                     glob_assign_glob(dstr, sstr, dtype);
3934                     return;
3935                 }
3936             }
3937         }
3938         if (stype == SVt_PVLV)
3939             SvUPGRADE(dstr, SVt_PVNV);
3940         else
3941             SvUPGRADE(dstr, (svtype)stype);
3942     }
3943  end_of_first_switch:
3944
3945     /* dstr may have been upgraded.  */
3946     dtype = SvTYPE(dstr);
3947     sflags = SvFLAGS(sstr);
3948
3949     if (dtype == SVt_PVCV || dtype == SVt_PVFM) {
3950         /* Assigning to a subroutine sets the prototype.  */
3951         if (SvOK(sstr)) {
3952             STRLEN len;
3953             const char *const ptr = SvPV_const(sstr, len);
3954
3955             SvGROW(dstr, len + 1);
3956             Copy(ptr, SvPVX(dstr), len + 1, char);
3957             SvCUR_set(dstr, len);
3958             SvPOK_only(dstr);
3959             SvFLAGS(dstr) |= sflags & SVf_UTF8;
3960         } else {
3961             SvOK_off(dstr);
3962         }
3963     } else if (dtype == SVt_PVAV || dtype == SVt_PVHV) {
3964         const char * const type = sv_reftype(dstr,0);
3965         if (PL_op)
3966             Perl_croak(aTHX_ "Cannot copy to %s in %s", type, OP_DESC(PL_op));
3967         else
3968             Perl_croak(aTHX_ "Cannot copy to %s", type);
3969     } else if (sflags & SVf_ROK) {
3970         if (isGV_with_GP(dstr) && dtype == SVt_PVGV
3971             && SvTYPE(SvRV(sstr)) == SVt_PVGV && isGV_with_GP(SvRV(sstr))) {
3972             sstr = SvRV(sstr);
3973             if (sstr == dstr) {
3974                 if (GvIMPORTED(dstr) != GVf_IMPORTED
3975                     && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3976                 {
3977                     GvIMPORTED_on(dstr);
3978                 }
3979                 GvMULTI_on(dstr);
3980                 return;
3981             }
3982             glob_assign_glob(dstr, sstr, dtype);
3983             return;
3984         }
3985
3986         if (dtype >= SVt_PV) {
3987             if (dtype == SVt_PVGV && isGV_with_GP(dstr)) {
3988                 glob_assign_ref(dstr, sstr);
3989                 return;
3990             }
3991             if (SvPVX_const(dstr)) {
3992                 SvPV_free(dstr);
3993                 SvLEN_set(dstr, 0);
3994                 SvCUR_set(dstr, 0);
3995             }
3996         }
3997         (void)SvOK_off(dstr);
3998         SvRV_set(dstr, SvREFCNT_inc(SvRV(sstr)));
3999         SvFLAGS(dstr) |= sflags & SVf_ROK;
4000         assert(!(sflags & SVp_NOK));
4001         assert(!(sflags & SVp_IOK));
4002         assert(!(sflags & SVf_NOK));
4003         assert(!(sflags & SVf_IOK));
4004     }
4005     else if (dtype == SVt_PVGV && isGV_with_GP(dstr)) {
4006         if (!(sflags & SVf_OK)) {
4007             Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4008                            "Undefined value assigned to typeglob");
4009         }
4010         else {
4011             GV *gv = gv_fetchsv(sstr, GV_ADD, SVt_PVGV);
4012             if (dstr != (const SV *)gv) {
4013                 if (GvGP(dstr))
4014                     gp_free(MUTABLE_GV(dstr));
4015                 GvGP(dstr) = gp_ref(GvGP(gv));
4016             }
4017         }
4018     }
4019     else if (dtype == SVt_REGEXP && stype == SVt_REGEXP) {
4020         reg_temp_copy((REGEXP*)dstr, (REGEXP*)sstr);
4021     }
4022     else if (sflags & SVp_POK) {
4023         bool isSwipe = 0;
4024
4025         /*
4026          * Check to see if we can just swipe the string.  If so, it's a
4027          * possible small lose on short strings, but a big win on long ones.
4028          * It might even be a win on short strings if SvPVX_const(dstr)
4029          * has to be allocated and SvPVX_const(sstr) has to be freed.
4030          * Likewise if we can set up COW rather than doing an actual copy, we
4031          * drop to the else clause, as the swipe code and the COW setup code
4032          * have much in common.
4033          */
4034
4035         /* Whichever path we take through the next code, we want this true,
4036            and doing it now facilitates the COW check.  */
4037         (void)SvPOK_only(dstr);
4038
4039         if (
4040             /* If we're already COW then this clause is not true, and if COW
4041                is allowed then we drop down to the else and make dest COW 
4042                with us.  If caller hasn't said that we're allowed to COW
4043                shared hash keys then we don't do the COW setup, even if the
4044                source scalar is a shared hash key scalar.  */
4045             (((flags & SV_COW_SHARED_HASH_KEYS)
4046                ? (sflags & (SVf_FAKE|SVf_READONLY)) != (SVf_FAKE|SVf_READONLY)
4047                : 1 /* If making a COW copy is forbidden then the behaviour we
4048                        desire is as if the source SV isn't actually already
4049                        COW, even if it is.  So we act as if the source flags
4050                        are not COW, rather than actually testing them.  */
4051               )
4052 #ifndef PERL_OLD_COPY_ON_WRITE
4053              /* The change that added SV_COW_SHARED_HASH_KEYS makes the logic
4054                 when PERL_OLD_COPY_ON_WRITE is defined a little wrong.
4055                 Conceptually PERL_OLD_COPY_ON_WRITE being defined should
4056                 override SV_COW_SHARED_HASH_KEYS, because it means "always COW"
4057                 but in turn, it's somewhat dead code, never expected to go
4058                 live, but more kept as a placeholder on how to do it better
4059                 in a newer implementation.  */
4060              /* If we are COW and dstr is a suitable target then we drop down
4061                 into the else and make dest a COW of us.  */
4062              || (SvFLAGS(dstr) & CAN_COW_MASK) != CAN_COW_FLAGS
4063 #endif
4064              )
4065             &&
4066             !(isSwipe =
4067                  (sflags & SVs_TEMP) &&   /* slated for free anyway? */
4068                  !(sflags & SVf_OOK) &&   /* and not involved in OOK hack? */
4069                  (!(flags & SV_NOSTEAL)) &&
4070                                         /* and we're allowed to steal temps */
4071                  SvREFCNT(sstr) == 1 &&   /* and no other references to it? */
4072                  SvLEN(sstr))             /* and really is a string */
4073 #ifdef PERL_OLD_COPY_ON_WRITE
4074             && ((flags & SV_COW_SHARED_HASH_KEYS)
4075                 ? (!((sflags & CAN_COW_MASK) == CAN_COW_FLAGS
4076                      && (SvFLAGS(dstr) & CAN_COW_MASK) == CAN_COW_FLAGS
4077                      && SvTYPE(sstr) >= SVt_PVIV && SvTYPE(sstr) != SVt_PVFM))
4078                 : 1)
4079 #endif
4080             ) {
4081             /* Failed the swipe test, and it's not a shared hash key either.
4082                Have to copy the string.  */
4083             STRLEN len = SvCUR(sstr);
4084             SvGROW(dstr, len + 1);      /* inlined from sv_setpvn */
4085             Move(SvPVX_const(sstr),SvPVX(dstr),len,char);
4086             SvCUR_set(dstr, len);
4087             *SvEND(dstr) = '\0';
4088         } else {
4089             /* If PERL_OLD_COPY_ON_WRITE is not defined, then isSwipe will always
4090                be true in here.  */
4091             /* Either it's a shared hash key, or it's suitable for
4092                copy-on-write or we can swipe the string.  */
4093             if (DEBUG_C_TEST) {
4094                 PerlIO_printf(Perl_debug_log, "Copy on write: sstr --> dstr\n");
4095                 sv_dump(sstr);
4096                 sv_dump(dstr);
4097             }
4098 #ifdef PERL_OLD_COPY_ON_WRITE
4099             if (!isSwipe) {
4100                 if ((sflags & (SVf_FAKE | SVf_READONLY))
4101                     != (SVf_FAKE | SVf_READONLY)) {
4102                     SvREADONLY_on(sstr);
4103                     SvFAKE_on(sstr);
4104                     /* Make the source SV into a loop of 1.
4105                        (about to become 2) */
4106                     SV_COW_NEXT_SV_SET(sstr, sstr);
4107                 }
4108             }
4109 #endif
4110             /* Initial code is common.  */
4111             if (SvPVX_const(dstr)) {    /* we know that dtype >= SVt_PV */
4112                 SvPV_free(dstr);
4113             }
4114
4115             if (!isSwipe) {
4116                 /* making another shared SV.  */
4117                 STRLEN cur = SvCUR(sstr);
4118                 STRLEN len = SvLEN(sstr);
4119 #ifdef PERL_OLD_COPY_ON_WRITE
4120                 if (len) {
4121                     assert (SvTYPE(dstr) >= SVt_PVIV);
4122                     /* SvIsCOW_normal */
4123                     /* splice us in between source and next-after-source.  */
4124                     SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4125                     SV_COW_NEXT_SV_SET(sstr, dstr);
4126                     SvPV_set(dstr, SvPVX_mutable(sstr));
4127                 } else
4128 #endif
4129                 {
4130                     /* SvIsCOW_shared_hash */
4131                     DEBUG_C(PerlIO_printf(Perl_debug_log,
4132                                           "Copy on write: Sharing hash\n"));
4133
4134                     assert (SvTYPE(dstr) >= SVt_PV);
4135                     SvPV_set(dstr,
4136                              HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)))));
4137                 }
4138                 SvLEN_set(dstr, len);
4139                 SvCUR_set(dstr, cur);
4140                 SvREADONLY_on(dstr);
4141                 SvFAKE_on(dstr);
4142             }
4143             else
4144                 {       /* Passes the swipe test.  */
4145                 SvPV_set(dstr, SvPVX_mutable(sstr));
4146                 SvLEN_set(dstr, SvLEN(sstr));
4147                 SvCUR_set(dstr, SvCUR(sstr));
4148
4149                 SvTEMP_off(dstr);
4150                 (void)SvOK_off(sstr);   /* NOTE: nukes most SvFLAGS on sstr */
4151                 SvPV_set(sstr, NULL);
4152                 SvLEN_set(sstr, 0);
4153                 SvCUR_set(sstr, 0);
4154                 SvTEMP_off(sstr);
4155             }
4156         }
4157         if (sflags & SVp_NOK) {
4158             SvNV_set(dstr, SvNVX(sstr));
4159         }
4160         if (sflags & SVp_IOK) {
4161             SvIV_set(dstr, SvIVX(sstr));
4162             /* Must do this otherwise some other overloaded use of 0x80000000
4163                gets confused. I guess SVpbm_VALID */
4164             if (sflags & SVf_IVisUV)
4165                 SvIsUV_on(dstr);
4166         }
4167         SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_NOK|SVp_NOK|SVf_UTF8);
4168         {
4169             const MAGIC * const smg = SvVSTRING_mg(sstr);
4170             if (smg) {
4171                 sv_magic(dstr, NULL, PERL_MAGIC_vstring,
4172                          smg->mg_ptr, smg->mg_len);
4173                 SvRMAGICAL_on(dstr);
4174             }
4175         }
4176     }
4177     else if (sflags & (SVp_IOK|SVp_NOK)) {
4178         (void)SvOK_off(dstr);
4179         SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_IVisUV|SVf_NOK|SVp_NOK);
4180         if (sflags & SVp_IOK) {
4181             /* XXXX Do we want to set IsUV for IV(ROK)?  Be extra safe... */
4182             SvIV_set(dstr, SvIVX(sstr));
4183         }
4184         if (sflags & SVp_NOK) {
4185             SvNV_set(dstr, SvNVX(sstr));
4186         }
4187     }
4188     else {
4189         if (isGV_with_GP(sstr)) {
4190             /* This stringification rule for globs is spread in 3 places.
4191                This feels bad. FIXME.  */
4192             const U32 wasfake = sflags & SVf_FAKE;
4193
4194             /* FAKE globs can get coerced, so need to turn this off
4195                temporarily if it is on.  */
4196             SvFAKE_off(sstr);
4197             gv_efullname3(dstr, MUTABLE_GV(sstr), "*");
4198             SvFLAGS(sstr) |= wasfake;
4199         }
4200         else
4201             (void)SvOK_off(dstr);
4202     }
4203     if (SvTAINTED(sstr))
4204         SvTAINT(dstr);
4205 }
4206
4207 /*
4208 =for apidoc sv_setsv_mg
4209
4210 Like C<sv_setsv>, but also handles 'set' magic.
4211
4212 =cut
4213 */
4214
4215 void
4216 Perl_sv_setsv_mg(pTHX_ SV *const dstr, register SV *const sstr)
4217 {
4218     PERL_ARGS_ASSERT_SV_SETSV_MG;
4219
4220     sv_setsv(dstr,sstr);
4221     SvSETMAGIC(dstr);
4222 }
4223
4224 #ifdef PERL_OLD_COPY_ON_WRITE
4225 SV *
4226 Perl_sv_setsv_cow(pTHX_ SV *dstr, SV *sstr)
4227 {
4228     STRLEN cur = SvCUR(sstr);
4229     STRLEN len = SvLEN(sstr);
4230     register char *new_pv;
4231
4232     PERL_ARGS_ASSERT_SV_SETSV_COW;
4233
4234     if (DEBUG_C_TEST) {
4235         PerlIO_printf(Perl_debug_log, "Fast copy on write: %p -> %p\n",
4236                       (void*)sstr, (void*)dstr);
4237         sv_dump(sstr);
4238         if (dstr)
4239                     sv_dump(dstr);
4240     }
4241
4242     if (dstr) {
4243         if (SvTHINKFIRST(dstr))
4244             sv_force_normal_flags(dstr, SV_COW_DROP_PV);
4245         else if (SvPVX_const(dstr))
4246             Safefree(SvPVX_const(dstr));
4247     }
4248     else
4249         new_SV(dstr);
4250     SvUPGRADE(dstr, SVt_PVIV);
4251
4252     assert (SvPOK(sstr));
4253     assert (SvPOKp(sstr));
4254     assert (!SvIOK(sstr));
4255     assert (!SvIOKp(sstr));
4256     assert (!SvNOK(sstr));
4257     assert (!SvNOKp(sstr));
4258
4259     if (SvIsCOW(sstr)) {
4260
4261         if (SvLEN(sstr) == 0) {
4262             /* source is a COW shared hash key.  */
4263             DEBUG_C(PerlIO_printf(Perl_debug_log,
4264                                   "Fast copy on write: Sharing hash\n"));
4265             new_pv = HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr))));
4266             goto common_exit;
4267         }
4268         SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4269     } else {
4270         assert ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS);
4271         SvUPGRADE(sstr, SVt_PVIV);
4272         SvREADONLY_on(sstr);
4273         SvFAKE_on(sstr);
4274         DEBUG_C(PerlIO_printf(Perl_debug_log,
4275                               "Fast copy on write: Converting sstr to COW\n"));
4276         SV_COW_NEXT_SV_SET(dstr, sstr);
4277     }
4278     SV_COW_NEXT_SV_SET(sstr, dstr);
4279     new_pv = SvPVX_mutable(sstr);
4280
4281   common_exit:
4282     SvPV_set(dstr, new_pv);
4283     SvFLAGS(dstr) = (SVt_PVIV|SVf_POK|SVp_POK|SVf_FAKE|SVf_READONLY);
4284     if (SvUTF8(sstr))
4285         SvUTF8_on(dstr);
4286     SvLEN_set(dstr, len);
4287     SvCUR_set(dstr, cur);
4288     if (DEBUG_C_TEST) {
4289         sv_dump(dstr);
4290     }
4291     return dstr;
4292 }
4293 #endif
4294
4295 /*
4296 =for apidoc sv_setpvn
4297
4298 Copies a string into an SV.  The C<len> parameter indicates the number of
4299 bytes to be copied.  If the C<ptr> argument is NULL the SV will become
4300 undefined.  Does not handle 'set' magic.  See C<sv_setpvn_mg>.
4301
4302 =cut
4303 */
4304
4305 void
4306 Perl_sv_setpvn(pTHX_ register SV *const sv, register const char *const ptr, register const STRLEN len)
4307 {
4308     dVAR;
4309     register char *dptr;
4310
4311     PERL_ARGS_ASSERT_SV_SETPVN;
4312
4313     SV_CHECK_THINKFIRST_COW_DROP(sv);
4314     if (!ptr) {
4315         (void)SvOK_off(sv);
4316         return;
4317     }
4318     else {
4319         /* len is STRLEN which is unsigned, need to copy to signed */
4320         const IV iv = len;
4321         if (iv < 0)
4322             Perl_croak(aTHX_ "panic: sv_setpvn called with negative strlen");
4323     }
4324     SvUPGRADE(sv, SVt_PV);
4325
4326     dptr = SvGROW(sv, len + 1);
4327     Move(ptr,dptr,len,char);
4328     dptr[len] = '\0';
4329     SvCUR_set(sv, len);
4330     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4331     SvTAINT(sv);
4332 }
4333
4334 /*
4335 =for apidoc sv_setpvn_mg
4336
4337 Like C<sv_setpvn>, but also handles 'set' magic.
4338
4339 =cut
4340 */
4341
4342 void
4343 Perl_sv_setpvn_mg(pTHX_ register SV *const sv, register const char *const ptr, register const STRLEN len)
4344 {
4345     PERL_ARGS_ASSERT_SV_SETPVN_MG;
4346
4347     sv_setpvn(sv,ptr,len);
4348     SvSETMAGIC(sv);
4349 }
4350
4351 /*
4352 =for apidoc sv_setpv
4353
4354 Copies a string into an SV.  The string must be null-terminated.  Does not
4355 handle 'set' magic.  See C<sv_setpv_mg>.
4356
4357 =cut
4358 */
4359
4360 void
4361 Perl_sv_setpv(pTHX_ register SV *const sv, register const char *const ptr)
4362 {
4363     dVAR;
4364     register STRLEN len;
4365
4366     PERL_ARGS_ASSERT_SV_SETPV;
4367
4368     SV_CHECK_THINKFIRST_COW_DROP(sv);
4369     if (!ptr) {
4370         (void)SvOK_off(sv);
4371         return;
4372     }
4373     len = strlen(ptr);
4374     SvUPGRADE(sv, SVt_PV);
4375
4376     SvGROW(sv, len + 1);
4377     Move(ptr,SvPVX(sv),len+1,char);
4378     SvCUR_set(sv, len);
4379     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4380     SvTAINT(sv);
4381 }
4382
4383 /*
4384 =for apidoc sv_setpv_mg
4385
4386 Like C<sv_setpv>, but also handles 'set' magic.
4387
4388 =cut
4389 */
4390
4391 void
4392 Perl_sv_setpv_mg(pTHX_ register SV *const sv, register const char *const ptr)
4393 {
4394     PERL_ARGS_ASSERT_SV_SETPV_MG;
4395
4396     sv_setpv(sv,ptr);
4397     SvSETMAGIC(sv);
4398 }
4399
4400 /*
4401 =for apidoc sv_usepvn_flags
4402
4403 Tells an SV to use C<ptr> to find its string value.  Normally the
4404 string is stored inside the SV but sv_usepvn allows the SV to use an
4405 outside string.  The C<ptr> should point to memory that was allocated
4406 by C<malloc>.  The string length, C<len>, must be supplied.  By default
4407 this function will realloc (i.e. move) the memory pointed to by C<ptr>,
4408 so that pointer should not be freed or used by the programmer after
4409 giving it to sv_usepvn, and neither should any pointers from "behind"
4410 that pointer (e.g. ptr + 1) be used.
4411
4412 If C<flags> & SV_SMAGIC is true, will call SvSETMAGIC. If C<flags> &
4413 SV_HAS_TRAILING_NUL is true, then C<ptr[len]> must be NUL, and the realloc
4414 will be skipped. (i.e. the buffer is actually at least 1 byte longer than
4415 C<len>, and already meets the requirements for storing in C<SvPVX>)
4416
4417 =cut
4418 */
4419
4420 void
4421 Perl_sv_usepvn_flags(pTHX_ SV *const sv, char *ptr, const STRLEN len, const U32 flags)
4422 {
4423     dVAR;
4424     STRLEN allocate;
4425
4426     PERL_ARGS_ASSERT_SV_USEPVN_FLAGS;
4427
4428     SV_CHECK_THINKFIRST_COW_DROP(sv);
4429     SvUPGRADE(sv, SVt_PV);
4430     if (!ptr) {
4431         (void)SvOK_off(sv);
4432         if (flags & SV_SMAGIC)
4433             SvSETMAGIC(sv);
4434         return;
4435     }
4436     if (SvPVX_const(sv))
4437         SvPV_free(sv);
4438
4439 #ifdef DEBUGGING
4440     if (flags & SV_HAS_TRAILING_NUL)
4441         assert(ptr[len] == '\0');
4442 #endif
4443
4444     allocate = (flags & SV_HAS_TRAILING_NUL)
4445         ? len + 1 :
4446 #ifdef Perl_safesysmalloc_size
4447         len + 1;
4448 #else 
4449         PERL_STRLEN_ROUNDUP(len + 1);
4450 #endif
4451     if (flags & SV_HAS_TRAILING_NUL) {
4452         /* It's long enough - do nothing.
4453            Specfically Perl_newCONSTSUB is relying on this.  */
4454     } else {
4455 #ifdef DEBUGGING
4456         /* Force a move to shake out bugs in callers.  */
4457         char *new_ptr = (char*)safemalloc(allocate);
4458         Copy(ptr, new_ptr, len, char);
4459         PoisonFree(ptr,len,char);
4460         Safefree(ptr);
4461         ptr = new_ptr;
4462 #else
4463         ptr = (char*) saferealloc (ptr, allocate);
4464 #endif
4465     }
4466 #ifdef Perl_safesysmalloc_size
4467     SvLEN_set(sv, Perl_safesysmalloc_size(ptr));
4468 #else
4469     SvLEN_set(sv, allocate);
4470 #endif
4471     SvCUR_set(sv, len);
4472     SvPV_set(sv, ptr);
4473     if (!(flags & SV_HAS_TRAILING_NUL)) {
4474         ptr[len] = '\0';
4475     }
4476     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4477     SvTAINT(sv);
4478     if (flags & SV_SMAGIC)
4479         SvSETMAGIC(sv);
4480 }
4481
4482 #ifdef PERL_OLD_COPY_ON_WRITE
4483 /* Need to do this *after* making the SV normal, as we need the buffer
4484    pointer to remain valid until after we've copied it.  If we let go too early,
4485    another thread could invalidate it by unsharing last of the same hash key
4486    (which it can do by means other than releasing copy-on-write Svs)
4487    or by changing the other copy-on-write SVs in the loop.  */
4488 STATIC void
4489 S_sv_release_COW(pTHX_ register SV *sv, const char *pvx, SV *after)
4490 {
4491     PERL_ARGS_ASSERT_SV_RELEASE_COW;
4492
4493     { /* this SV was SvIsCOW_normal(sv) */
4494          /* we need to find the SV pointing to us.  */
4495         SV *current = SV_COW_NEXT_SV(after);
4496
4497         if (current == sv) {
4498             /* The SV we point to points back to us (there were only two of us
4499                in the loop.)
4500                Hence other SV is no longer copy on write either.  */
4501             SvFAKE_off(after);
4502             SvREADONLY_off(after);
4503         } else {
4504             /* We need to follow the pointers around the loop.  */
4505             SV *next;
4506             while ((next = SV_COW_NEXT_SV(current)) != sv) {
4507                 assert (next);
4508                 current = next;
4509                  /* don't loop forever if the structure is bust, and we have
4510                     a pointer into a closed loop.  */
4511                 assert (current != after);
4512                 assert (SvPVX_const(current) == pvx);
4513             }
4514             /* Make the SV before us point to the SV after us.  */
4515             SV_COW_NEXT_SV_SET(current, after);
4516         }
4517     }
4518 }
4519 #endif
4520 /*
4521 =for apidoc sv_force_normal_flags
4522
4523 Undo various types of fakery on an SV: if the PV is a shared string, make
4524 a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
4525 an xpvmg; if we're a copy-on-write scalar, this is the on-write time when
4526 we do the copy, and is also used locally. If C<SV_COW_DROP_PV> is set
4527 then a copy-on-write scalar drops its PV buffer (if any) and becomes
4528 SvPOK_off rather than making a copy. (Used where this scalar is about to be
4529 set to some other value.) In addition, the C<flags> parameter gets passed to
4530 C<sv_unref_flags()> when unrefing. C<sv_force_normal> calls this function
4531 with flags set to 0.
4532
4533 =cut
4534 */
4535
4536 void
4537 Perl_sv_force_normal_flags(pTHX_ register SV *const sv, const U32 flags)
4538 {
4539     dVAR;
4540
4541     PERL_ARGS_ASSERT_SV_FORCE_NORMAL_FLAGS;
4542
4543 #ifdef PERL_OLD_COPY_ON_WRITE
4544     if (SvREADONLY(sv)) {
4545         if (SvFAKE(sv)) {
4546             const char * const pvx = SvPVX_const(sv);
4547             const STRLEN len = SvLEN(sv);
4548             const STRLEN cur = SvCUR(sv);
4549             /* next COW sv in the loop.  If len is 0 then this is a shared-hash
4550                key scalar, so we mustn't attempt to call SV_COW_NEXT_SV(), as
4551                we'll fail an assertion.  */
4552             SV * const next = len ? SV_COW_NEXT_SV(sv) : 0;
4553
4554             if (DEBUG_C_TEST) {
4555                 PerlIO_printf(Perl_debug_log,
4556                               "Copy on write: Force normal %ld\n",
4557                               (long) flags);
4558                 sv_dump(sv);
4559             }
4560             SvFAKE_off(sv);
4561             SvREADONLY_off(sv);
4562             /* This SV doesn't own the buffer, so need to Newx() a new one:  */
4563             SvPV_set(sv, NULL);
4564             SvLEN_set(sv, 0);
4565             if (flags & SV_COW_DROP_PV) {
4566                 /* OK, so we don't need to copy our buffer.  */
4567                 SvPOK_off(sv);
4568             } else {
4569                 SvGROW(sv, cur + 1);
4570                 Move(pvx,SvPVX(sv),cur,char);
4571                 SvCUR_set(sv, cur);
4572                 *SvEND(sv) = '\0';
4573             }
4574             if (len) {
4575                 sv_release_COW(sv, pvx, next);
4576             } else {
4577                 unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4578             }
4579             if (DEBUG_C_TEST) {
4580                 sv_dump(sv);
4581             }
4582         }
4583         else if (IN_PERL_RUNTIME)
4584             Perl_croak(aTHX_ "%s", PL_no_modify);
4585     }
4586 #else
4587     if (SvREADONLY(sv)) {
4588         if (SvFAKE(sv)) {
4589             const char * const pvx = SvPVX_const(sv);
4590             const STRLEN len = SvCUR(sv);
4591             SvFAKE_off(sv);
4592             SvREADONLY_off(sv);
4593             SvPV_set(sv, NULL);
4594             SvLEN_set(sv, 0);
4595             SvGROW(sv, len + 1);
4596             Move(pvx,SvPVX(sv),len,char);
4597             *SvEND(sv) = '\0';
4598             unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4599         }
4600         else if (IN_PERL_RUNTIME)
4601             Perl_croak(aTHX_ "%s", PL_no_modify);
4602     }
4603 #endif
4604     if (SvROK(sv))
4605         sv_unref_flags(sv, flags);
4606     else if (SvFAKE(sv) && SvTYPE(sv) == SVt_PVGV)
4607         sv_unglob(sv);
4608     else if (SvFAKE(sv) && SvTYPE(sv) == SVt_REGEXP) {
4609         /* Need to downgrade the REGEXP to a simple(r) scalar. This is analagous
4610            to sv_unglob. We only need it here, so inline it.  */
4611         const svtype new_type = SvMAGIC(sv) || SvSTASH(sv) ? SVt_PVMG : SVt_PV;
4612         SV *const temp = newSV_type(new_type);
4613         void *const temp_p = SvANY(sv);
4614
4615         if (new_type == SVt_PVMG) {
4616             SvMAGIC_set(temp, SvMAGIC(sv));
4617             SvMAGIC_set(sv, NULL);
4618             SvSTASH_set(temp, SvSTASH(sv));
4619             SvSTASH_set(sv, NULL);
4620         }
4621         SvCUR_set(temp, SvCUR(sv));
4622         /* Remember that SvPVX is in the head, not the body. */
4623         if (SvLEN(temp)) {
4624             SvLEN_set(temp, SvLEN(sv));
4625             /* This signals "buffer is owned by someone else" in sv_clear,
4626                which is the least effort way to stop it freeing the buffer.
4627             */
4628             SvLEN_set(sv, SvLEN(sv)+1);
4629         } else {
4630             /* Their buffer is already owned by someone else. */
4631             SvPVX(sv) = savepvn(SvPVX(sv), SvCUR(sv));
4632             SvLEN_set(temp, SvCUR(sv)+1);
4633         }
4634
4635         /* Now swap the rest of the bodies. */
4636
4637         SvFLAGS(sv) &= ~(SVf_FAKE|SVTYPEMASK);
4638         SvFLAGS(sv) |= new_type;
4639         SvANY(sv) = SvANY(temp);
4640
4641         SvFLAGS(temp) &= ~(SVTYPEMASK);
4642         SvFLAGS(temp) |= SVt_REGEXP|SVf_FAKE;
4643         SvANY(temp) = temp_p;
4644
4645         SvREFCNT_dec(temp);
4646     }
4647 }
4648
4649 /*
4650 =for apidoc sv_chop
4651
4652 Efficient removal of characters from the beginning of the string buffer.
4653 SvPOK(sv) must be true and the C<ptr> must be a pointer to somewhere inside
4654 the string buffer.  The C<ptr> becomes the first character of the adjusted
4655 string. Uses the "OOK hack".
4656 Beware: after this function returns, C<ptr> and SvPVX_const(sv) may no longer
4657 refer to the same chunk of data.
4658
4659 =cut
4660 */
4661
4662 void
4663 Perl_sv_chop(pTHX_ register SV *const sv, register const char *const ptr)
4664 {
4665     STRLEN delta;
4666     STRLEN old_delta;
4667     U8 *p;
4668 #ifdef DEBUGGING
4669     const U8 *real_start;
4670 #endif
4671     STRLEN max_delta;
4672
4673     PERL_ARGS_ASSERT_SV_CHOP;
4674
4675     if (!ptr || !SvPOKp(sv))
4676         return;
4677     delta = ptr - SvPVX_const(sv);
4678     if (!delta) {
4679         /* Nothing to do.  */
4680         return;
4681     }
4682     /* SvPVX(sv) may move in SV_CHECK_THINKFIRST(sv), but after this line,
4683        nothing uses the value of ptr any more.  */
4684     max_delta = SvLEN(sv) ? SvLEN(sv) : SvCUR(sv);
4685     if (ptr <= SvPVX_const(sv))
4686         Perl_croak(aTHX_ "panic: sv_chop ptr=%p, start=%p, end=%p",
4687                    ptr, SvPVX_const(sv), SvPVX_const(sv) + max_delta);
4688     SV_CHECK_THINKFIRST(sv);
4689     if (delta > max_delta)
4690         Perl_croak(aTHX_ "panic: sv_chop ptr=%p (was %p), start=%p, end=%p",
4691                    SvPVX_const(sv) + delta, ptr, SvPVX_const(sv),
4692                    SvPVX_const(sv) + max_delta);
4693
4694     if (!SvOOK(sv)) {
4695         if (!SvLEN(sv)) { /* make copy of shared string */
4696             const char *pvx = SvPVX_const(sv);
4697             const STRLEN len = SvCUR(sv);
4698             SvGROW(sv, len + 1);
4699             Move(pvx,SvPVX(sv),len,char);
4700             *SvEND(sv) = '\0';
4701         }
4702         SvFLAGS(sv) |= SVf_OOK;
4703         old_delta = 0;
4704     } else {
4705         SvOOK_offset(sv, old_delta);
4706     }
4707     SvLEN_set(sv, SvLEN(sv) - delta);
4708     SvCUR_set(sv, SvCUR(sv) - delta);
4709     SvPV_set(sv, SvPVX(sv) + delta);
4710
4711     p = (U8 *)SvPVX_const(sv);
4712
4713     delta += old_delta;
4714
4715 #ifdef DEBUGGING
4716     real_start = p - delta;
4717 #endif
4718
4719     assert(delta);
4720     if (delta < 0x100) {
4721         *--p = (U8) delta;
4722     } else {
4723         *--p = 0;
4724         p -= sizeof(STRLEN);
4725         Copy((U8*)&delta, p, sizeof(STRLEN), U8);
4726     }
4727
4728 #ifdef DEBUGGING
4729     /* Fill the preceding buffer with sentinals to verify that no-one is
4730        using it.  */
4731     while (p > real_start) {
4732         --p;
4733         *p = (U8)PTR2UV(p);
4734     }
4735 #endif
4736 }
4737
4738 /*
4739 =for apidoc sv_catpvn
4740
4741 Concatenates the string onto the end of the string which is in the SV.  The
4742 C<len> indicates number of bytes to copy.  If the SV has the UTF-8
4743 status set, then the bytes appended should be valid UTF-8.
4744 Handles 'get' magic, but not 'set' magic.  See C<sv_catpvn_mg>.
4745
4746 =for apidoc sv_catpvn_flags
4747
4748 Concatenates the string onto the end of the string which is in the SV.  The
4749 C<len> indicates number of bytes to copy.  If the SV has the UTF-8
4750 status set, then the bytes appended should be valid UTF-8.
4751 If C<flags> has C<SV_GMAGIC> bit set, will C<mg_get> on C<dsv> if
4752 appropriate, else not. C<sv_catpvn> and C<sv_catpvn_nomg> are implemented
4753 in terms of this function.
4754
4755 =cut
4756 */
4757
4758 void
4759 Perl_sv_catpvn_flags(pTHX_ register SV *const dsv, register const char *sstr, register const STRLEN slen, const I32 flags)
4760 {
4761     dVAR;
4762     STRLEN dlen;
4763     const char * const dstr = SvPV_force_flags(dsv, dlen, flags);
4764
4765     PERL_ARGS_ASSERT_SV_CATPVN_FLAGS;
4766
4767     SvGROW(dsv, dlen + slen + 1);
4768     if (sstr == dstr)
4769         sstr = SvPVX_const(dsv);
4770     Move(sstr, SvPVX(dsv) + dlen, slen, char);
4771     SvCUR_set(dsv, SvCUR(dsv) + slen);
4772     *SvEND(dsv) = '\0';
4773     (void)SvPOK_only_UTF8(dsv);         /* validate pointer */
4774     SvTAINT(dsv);
4775     if (flags & SV_SMAGIC)
4776         SvSETMAGIC(dsv);
4777 }
4778
4779 /*
4780 =for apidoc sv_catsv
4781
4782 Concatenates the string from SV C<ssv> onto the end of the string in
4783 SV C<dsv>.  Modifies C<dsv> but not C<ssv>.  Handles 'get' magic, but
4784 not 'set' magic.  See C<sv_catsv_mg>.
4785
4786 =for apidoc sv_catsv_flags
4787
4788 Concatenates the string from SV C<ssv> onto the end of the string in
4789 SV C<dsv>.  Modifies C<dsv> but not C<ssv>.  If C<flags> has C<SV_GMAGIC>
4790 bit set, will C<mg_get> on the SVs if appropriate, else not. C<sv_catsv>
4791 and C<sv_catsv_nomg> are implemented in terms of this function.
4792
4793 =cut */
4794
4795 void
4796 Perl_sv_catsv_flags(pTHX_ SV *const dsv, register SV *const ssv, const I32 flags)
4797 {
4798     dVAR;
4799  
4800     PERL_ARGS_ASSERT_SV_CATSV_FLAGS;
4801
4802    if (ssv) {
4803         STRLEN slen;
4804         const char *spv = SvPV_const(ssv, slen);
4805         if (spv) {
4806             /*  sutf8 and dutf8 were type bool, but under USE_ITHREADS,
4807                 gcc version 2.95.2 20000220 (Debian GNU/Linux) for
4808                 Linux xxx 2.2.17 on sparc64 with gcc -O2, we erroneously
4809                 get dutf8 = 0x20000000, (i.e.  SVf_UTF8) even though
4810                 dsv->sv_flags doesn't have that bit set.
4811                 Andy Dougherty  12 Oct 2001
4812             */
4813             const I32 sutf8 = DO_UTF8(ssv);
4814             I32 dutf8;
4815
4816             if (SvGMAGICAL(dsv) && (flags & SV_GMAGIC))
4817                 mg_get(dsv);
4818             dutf8 = DO_UTF8(dsv);
4819
4820             if (dutf8 != sutf8) {
4821                 if (dutf8) {
4822                     /* Not modifying source SV, so taking a temporary copy. */
4823                     SV* const csv = newSVpvn_flags(spv, slen, SVs_TEMP);
4824
4825                     sv_utf8_upgrade(csv);
4826                     spv = SvPV_const(csv, slen);
4827                 }
4828                 else
4829                     /* Leave enough space for the cat that's about to happen */
4830                     sv_utf8_upgrade_flags_grow(dsv, 0, slen);
4831             }
4832             sv_catpvn_nomg(dsv, spv, slen);
4833         }
4834     }
4835     if (flags & SV_SMAGIC)
4836         SvSETMAGIC(dsv);
4837 }
4838
4839 /*
4840 =for apidoc sv_catpv
4841
4842 Concatenates the string onto the end of the string which is in the SV.
4843 If the SV has the UTF-8 status set, then the bytes appended should be
4844 valid UTF-8.  Handles 'get' magic, but not 'set' magic.  See C<sv_catpv_mg>.
4845
4846 =cut */
4847
4848 void
4849 Perl_sv_catpv(pTHX_ register SV *const sv, register const char *ptr)
4850 {
4851     dVAR;
4852     register STRLEN len;
4853     STRLEN tlen;
4854     char *junk;
4855
4856     PERL_ARGS_ASSERT_SV_CATPV;
4857
4858     if (!ptr)
4859         return;
4860     junk = SvPV_force(sv, tlen);
4861     len = strlen(ptr);
4862     SvGROW(sv, tlen + len + 1);
4863     if (ptr == junk)
4864         ptr = SvPVX_const(sv);
4865     Move(ptr,SvPVX(sv)+tlen,len+1,char);
4866     SvCUR_set(sv, SvCUR(sv) + len);
4867     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4868     SvTAINT(sv);
4869 }
4870
4871 /*
4872 =for apidoc sv_catpv_mg
4873
4874 Like C<sv_catpv>, but also handles 'set' magic.
4875
4876 =cut
4877 */
4878
4879 void
4880 Perl_sv_catpv_mg(pTHX_ register SV *const sv, register const char *const ptr)
4881 {
4882     PERL_ARGS_ASSERT_SV_CATPV_MG;
4883
4884     sv_catpv(sv,ptr);
4885     SvSETMAGIC(sv);
4886 }
4887
4888 /*
4889 =for apidoc newSV
4890
4891 Creates a new SV.  A non-zero C<len> parameter indicates the number of
4892 bytes of preallocated string space the SV should have.  An extra byte for a
4893 trailing NUL is also reserved.  (SvPOK is not set for the SV even if string
4894 space is allocated.)  The reference count for the new SV is set to 1.
4895
4896 In 5.9.3, newSV() replaces the older NEWSV() API, and drops the first
4897 parameter, I<x>, a debug aid which allowed callers to identify themselves.
4898 This aid has been superseded by a new build option, PERL_MEM_LOG (see
4899 L<perlhack/PERL_MEM_LOG>).  The older API is still there for use in XS
4900 modules supporting older perls.
4901
4902 =cut
4903 */
4904
4905 SV *
4906 Perl_newSV(pTHX_ const STRLEN len)
4907 {
4908     dVAR;
4909     register SV *sv;
4910
4911     new_SV(sv);
4912     if (len) {
4913         sv_upgrade(sv, SVt_PV);
4914         SvGROW(sv, len + 1);
4915     }
4916     return sv;
4917 }
4918 /*
4919 =for apidoc sv_magicext
4920
4921 Adds magic to an SV, upgrading it if necessary. Applies the
4922 supplied vtable and returns a pointer to the magic added.
4923
4924 Note that C<sv_magicext> will allow things that C<sv_magic> will not.
4925 In particular, you can add magic to SvREADONLY SVs, and add more than
4926 one instance of the same 'how'.
4927
4928 If C<namlen> is greater than zero then a C<savepvn> I<copy> of C<name> is
4929 stored, if C<namlen> is zero then C<name> is stored as-is and - as another
4930 special case - if C<(name && namlen == HEf_SVKEY)> then C<name> is assumed
4931 to contain an C<SV*> and is stored as-is with its REFCNT incremented.
4932
4933 (This is now used as a subroutine by C<sv_magic>.)
4934
4935 =cut
4936 */
4937 MAGIC * 
4938 Perl_sv_magicext(pTHX_ SV *const sv, SV *const obj, const int how, 
4939                 const MGVTBL *const vtable, const char *const name, const I32 namlen)
4940 {
4941     dVAR;
4942     MAGIC* mg;
4943
4944     PERL_ARGS_ASSERT_SV_MAGICEXT;
4945
4946     SvUPGRADE(sv, SVt_PVMG);
4947     Newxz(mg, 1, MAGIC);
4948     mg->mg_moremagic = SvMAGIC(sv);
4949     SvMAGIC_set(sv, mg);
4950
4951     /* Sometimes a magic contains a reference loop, where the sv and
4952        object refer to each other.  To prevent a reference loop that
4953        would prevent such objects being freed, we look for such loops
4954        and if we find one we avoid incrementing the object refcount.
4955
4956        Note we cannot do this to avoid self-tie loops as intervening RV must
4957        have its REFCNT incremented to keep it in existence.
4958
4959     */
4960     if (!obj || obj == sv ||
4961         how == PERL_MAGIC_arylen ||
4962         how == PERL_MAGIC_symtab ||
4963         (SvTYPE(obj) == SVt_PVGV &&
4964             (GvSV(obj) == sv || GvHV(obj) == (const HV *)sv
4965              || GvAV(obj) == (const AV *)sv || GvCV(obj) == (const CV *)sv
4966              || GvIOp(obj) == (const IO *)sv || GvFORM(obj) == (const CV *)sv)))
4967     {
4968         mg->mg_obj = obj;
4969     }
4970     else {
4971         mg->mg_obj = SvREFCNT_inc_simple(obj);
4972         mg->mg_flags |= MGf_REFCOUNTED;
4973     }
4974
4975     /* Normal self-ties simply pass a null object, and instead of
4976        using mg_obj directly, use the SvTIED_obj macro to produce a
4977        new RV as needed.  For glob "self-ties", we are tieing the PVIO
4978        with an RV obj pointing to the glob containing the PVIO.  In
4979        this case, to avoid a reference loop, we need to weaken the
4980        reference.
4981     */
4982
4983     if (how == PERL_MAGIC_tiedscalar && SvTYPE(sv) == SVt_PVIO &&
4984         obj && SvROK(obj) && GvIO(SvRV(obj)) == (const IO *)sv)
4985     {
4986       sv_rvweaken(obj);
4987     }
4988
4989     mg->mg_type = how;
4990     mg->mg_len = namlen;
4991     if (name) {
4992         if (namlen > 0)
4993             mg->mg_ptr = savepvn(name, namlen);
4994         else if (namlen == HEf_SVKEY) {
4995             /* Yes, this is casting away const. This is only for the case of
4996                HEf_SVKEY. I think we need to document this abberation of the
4997                constness of the API, rather than making name non-const, as
4998                that change propagating outwards a long way.  */
4999             mg->mg_ptr = (char*)SvREFCNT_inc_simple_NN((SV *)name);
5000         } else
5001             mg->mg_ptr = (char *) name;
5002     }
5003     mg->mg_virtual = (MGVTBL *) vtable;
5004
5005     mg_magical(sv);
5006     if (SvGMAGICAL(sv))
5007         SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK|SVf_POK);
5008     return mg;
5009 }
5010
5011 /*
5012 =for apidoc sv_magic
5013
5014 Adds magic to an SV. First upgrades C<sv> to type C<SVt_PVMG> if necessary,
5015 then adds a new magic item of type C<how> to the head of the magic list.
5016
5017 See C<sv_magicext> (which C<sv_magic> now calls) for a description of the
5018 handling of the C<name> and C<namlen> arguments.
5019
5020 You need to use C<sv_magicext> to add magic to SvREADONLY SVs and also
5021 to add more than one instance of the same 'how'.
5022
5023 =cut
5024 */
5025
5026 void
5027 Perl_sv_magic(pTHX_ register SV *const sv, SV *const obj, const int how, 
5028              const char *const name, const I32 namlen)
5029 {
5030     dVAR;
5031     const MGVTBL *vtable;
5032     MAGIC* mg;
5033
5034     PERL_ARGS_ASSERT_SV_MAGIC;
5035
5036 #ifdef PERL_OLD_COPY_ON_WRITE
5037     if (SvIsCOW(sv))
5038         sv_force_normal_flags(sv, 0);
5039 #endif
5040     if (SvREADONLY(sv)) {
5041         if (
5042             /* its okay to attach magic to shared strings; the subsequent
5043              * upgrade to PVMG will unshare the string */
5044             !(SvFAKE(sv) && SvTYPE(sv) < SVt_PVMG)
5045
5046             && IN_PERL_RUNTIME
5047             && how != PERL_MAGIC_regex_global
5048             && how != PERL_MAGIC_bm
5049             && how != PERL_MAGIC_fm
5050             && how != PERL_MAGIC_sv
5051             && how != PERL_MAGIC_backref
5052            )
5053         {
5054             Perl_croak(aTHX_ "%s", PL_no_modify);
5055         }
5056     }
5057     if (SvMAGICAL(sv) || (how == PERL_MAGIC_taint && SvTYPE(sv) >= SVt_PVMG)) {
5058         if (SvMAGIC(sv) && (mg = mg_find(sv, how))) {
5059             /* sv_magic() refuses to add a magic of the same 'how' as an
5060                existing one
5061              */
5062             if (how == PERL_MAGIC_taint) {
5063                 mg->mg_len |= 1;
5064                 /* Any scalar which already had taint magic on which someone
5065                    (erroneously?) did SvIOK_on() or similar will now be
5066                    incorrectly sporting public "OK" flags.  */
5067                 SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK|SVf_POK);
5068             }
5069             return;
5070         }
5071     }
5072
5073     switch (how) {
5074     case PERL_MAGIC_sv:
5075         vtable = &PL_vtbl_sv;
5076         break;
5077     case PERL_MAGIC_overload:
5078         vtable = &PL_vtbl_amagic;
5079         break;
5080     case PERL_MAGIC_overload_elem:
5081         vtable = &PL_vtbl_amagicelem;
5082         break;
5083     case PERL_MAGIC_overload_table:
5084         vtable = &PL_vtbl_ovrld;
5085         break;
5086     case PERL_MAGIC_bm:
5087         vtable = &PL_vtbl_bm;
5088         break;
5089     case PERL_MAGIC_regdata:
5090         vtable = &PL_vtbl_regdata;
5091         break;
5092     case PERL_MAGIC_regdatum:
5093         vtable = &PL_vtbl_regdatum;
5094         break;
5095     case PERL_MAGIC_env:
5096         vtable = &PL_vtbl_env;
5097         break;
5098     case PERL_MAGIC_fm:
5099         vtable = &PL_vtbl_fm;
5100         break;
5101     case PERL_MAGIC_envelem:
5102         vtable = &PL_vtbl_envelem;
5103         break;
5104     case PERL_MAGIC_regex_global:
5105         vtable = &PL_vtbl_mglob;
5106         break;
5107     case PERL_MAGIC_isa:
5108         vtable = &PL_vtbl_isa;
5109         break;
5110     case PERL_MAGIC_isaelem:
5111         vtable = &PL_vtbl_isaelem;
5112         break;
5113     case PERL_MAGIC_nkeys:
5114         vtable = &PL_vtbl_nkeys;
5115         break;
5116     case PERL_MAGIC_dbfile:
5117         vtable = NULL;
5118         break;
5119     case PERL_MAGIC_dbline:
5120         vtable = &PL_vtbl_dbline;
5121         break;
5122 #ifdef USE_LOCALE_COLLATE
5123     case PERL_MAGIC_collxfrm:
5124         vtable = &PL_vtbl_collxfrm;
5125         break;
5126 #endif /* USE_LOCALE_COLLATE */
5127     case PERL_MAGIC_tied:
5128         vtable = &PL_vtbl_pack;
5129         break;
5130     case PERL_MAGIC_tiedelem:
5131     case PERL_MAGIC_tiedscalar:
5132         vtable = &PL_vtbl_packelem;
5133         break;
5134     case PERL_MAGIC_qr:
5135         vtable = &PL_vtbl_regexp;
5136         break;
5137     case PERL_MAGIC_sig:
5138         vtable = &PL_vtbl_sig;
5139         break;
5140     case PERL_MAGIC_sigelem:
5141         vtable = &PL_vtbl_sigelem;
5142         break;
5143     case PERL_MAGIC_taint:
5144         vtable = &PL_vtbl_taint;
5145         break;
5146     case PERL_MAGIC_uvar:
5147         vtable = &PL_vtbl_uvar;
5148         break;
5149     case PERL_MAGIC_vec:
5150         vtable = &PL_vtbl_vec;
5151         break;
5152     case PERL_MAGIC_arylen_p:
5153     case PERL_MAGIC_rhash:
5154     case PERL_MAGIC_symtab:
5155     case PERL_MAGIC_vstring:
5156         vtable = NULL;
5157         break;
5158     case PERL_MAGIC_utf8:
5159         vtable = &PL_vtbl_utf8;
5160         break;
5161     case PERL_MAGIC_substr:
5162         vtable = &PL_vtbl_substr;
5163         break;
5164     case PERL_MAGIC_defelem:
5165         vtable = &PL_vtbl_defelem;
5166         break;
5167     case PERL_MAGIC_arylen:
5168         vtable = &PL_vtbl_arylen;
5169         break;
5170     case PERL_MAGIC_pos:
5171         vtable = &PL_vtbl_pos;
5172         break;
5173     case PERL_MAGIC_backref:
5174         vtable = &PL_vtbl_backref;
5175         break;
5176     case PERL_MAGIC_hintselem:
5177         vtable = &PL_vtbl_hintselem;
5178         break;
5179     case PERL_MAGIC_hints:
5180         vtable = &PL_vtbl_hints;
5181         break;
5182     case PERL_MAGIC_ext:
5183         /* Reserved for use by extensions not perl internals.           */
5184         /* Useful for attaching extension internal data to perl vars.   */
5185         /* Note that multiple extensions may clash if magical scalars   */
5186         /* etc holding private data from one are passed to another.     */
5187         vtable = NULL;
5188         break;
5189     default:
5190         Perl_croak(aTHX_ "Don't know how to handle magic of type \\%o", how);
5191     }
5192
5193     /* Rest of work is done else where */
5194     mg = sv_magicext(sv,obj,how,vtable,name,namlen);
5195
5196     switch (how) {
5197     case PERL_MAGIC_taint:
5198         mg->mg_len = 1;
5199         break;
5200     case PERL_MAGIC_ext:
5201     case PERL_MAGIC_dbfile:
5202         SvRMAGICAL_on(sv);
5203         break;
5204     }
5205 }
5206
5207 /*
5208 =for apidoc sv_unmagic
5209
5210 Removes all magic of type C<type> from an SV.
5211
5212 =cut
5213 */
5214
5215 int
5216 Perl_sv_unmagic(pTHX_ SV *const sv, const int type)
5217 {
5218     MAGIC* mg;
5219     MAGIC** mgp;
5220
5221     PERL_ARGS_ASSERT_SV_UNMAGIC;
5222
5223     if (SvTYPE(sv) < SVt_PVMG || !SvMAGIC(sv))
5224         return 0;
5225     mgp = &(((XPVMG*) SvANY(sv))->xmg_u.xmg_magic);
5226     for (mg = *mgp; mg; mg = *mgp) {
5227         if (mg->mg_type == type) {
5228             const MGVTBL* const vtbl = mg->mg_virtual;
5229             *mgp = mg->mg_moremagic;
5230             if (vtbl && vtbl->svt_free)
5231                 CALL_FPTR(vtbl->svt_free)(aTHX_ sv, mg);
5232             if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) {
5233                 if (mg->mg_len > 0)
5234                     Safefree(mg->mg_ptr);
5235                 else if (mg->mg_len == HEf_SVKEY)
5236                     SvREFCNT_dec(MUTABLE_SV(mg->mg_ptr));
5237                 else if (mg->mg_type == PERL_MAGIC_utf8)
5238                     Safefree(mg->mg_ptr);
5239             }
5240             if (mg->mg_flags & MGf_REFCOUNTED)
5241                 SvREFCNT_dec(mg->mg_obj);
5242             Safefree(mg);
5243         }
5244         else
5245             mgp = &mg->mg_moremagic;
5246     }
5247     if (SvMAGIC(sv)) {
5248         if (SvMAGICAL(sv))      /* if we're under save_magic, wait for restore_magic; */
5249             mg_magical(sv);     /*    else fix the flags now */
5250     }
5251     else {
5252         SvMAGICAL_off(sv);
5253         SvFLAGS(sv) |= (SvFLAGS(sv) & (SVp_IOK|SVp_NOK|SVp_POK)) >> PRIVSHIFT;
5254     }
5255     return 0;
5256 }
5257
5258 /*
5259 =for apidoc sv_rvweaken
5260
5261 Weaken a reference: set the C<SvWEAKREF> flag on this RV; give the
5262 referred-to SV C<PERL_MAGIC_backref> magic if it hasn't already; and
5263 push a back-reference to this RV onto the array of backreferences
5264 associated with that magic. If the RV is magical, set magic will be
5265 called after the RV is cleared.
5266
5267 =cut
5268 */
5269
5270 SV *
5271 Perl_sv_rvweaken(pTHX_ SV *const sv)
5272 {
5273     SV *tsv;
5274
5275     PERL_ARGS_ASSERT_SV_RVWEAKEN;
5276
5277     if (!SvOK(sv))  /* let undefs pass */
5278         return sv;
5279     if (!SvROK(sv))
5280         Perl_croak(aTHX_ "Can't weaken a nonreference");
5281     else if (SvWEAKREF(sv)) {
5282         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Reference is already weak");
5283         return sv;
5284     }
5285     tsv = SvRV(sv);
5286     Perl_sv_add_backref(aTHX_ tsv, sv);
5287     SvWEAKREF_on(sv);
5288     SvREFCNT_dec(tsv);
5289     return sv;
5290 }
5291
5292 /* Give tsv backref magic if it hasn't already got it, then push a
5293  * back-reference to sv onto the array associated with the backref magic.
5294  */
5295
5296 /* A discussion about the backreferences array and its refcount:
5297  *
5298  * The AV holding the backreferences is pointed to either as the mg_obj of
5299  * PERL_MAGIC_backref, or in the specific case of a HV that has the hv_aux
5300  * structure, from the xhv_backreferences field. (A HV without hv_aux will
5301  * have the standard magic instead.) The array is created with a refcount
5302  * of 2. This means that if during global destruction the array gets
5303  * picked on first to have its refcount decremented by the random zapper,
5304  * it won't actually be freed, meaning it's still theere for when its
5305  * parent gets freed.
5306  * When the parent SV is freed, in the case of magic, the magic is freed,
5307  * Perl_magic_killbackrefs is called which decrements one refcount, then
5308  * mg_obj is freed which kills the second count.
5309  * In the vase of a HV being freed, one ref is removed by
5310  * Perl_hv_kill_backrefs, the other by Perl_sv_kill_backrefs, which it
5311  * calls.
5312  */
5313
5314 void
5315 Perl_sv_add_backref(pTHX_ SV *const tsv, SV *const sv)
5316 {
5317     dVAR;
5318     AV *av;
5319
5320     PERL_ARGS_ASSERT_SV_ADD_BACKREF;
5321
5322     if (SvTYPE(tsv) == SVt_PVHV) {
5323         AV **const avp = Perl_hv_backreferences_p(aTHX_ MUTABLE_HV(tsv));
5324
5325         av = *avp;
5326         if (!av) {
5327             /* There is no AV in the offical place - try a fixup.  */
5328             MAGIC *const mg = mg_find(tsv, PERL_MAGIC_backref);
5329
5330             if (mg) {
5331                 /* Aha. They've got it stowed in magic.  Bring it back.  */
5332                 av = MUTABLE_AV(mg->mg_obj);
5333                 /* Stop mg_free decreasing the refernce count.  */
5334                 mg->mg_obj = NULL;
5335                 /* Stop mg_free even calling the destructor, given that
5336                    there's no AV to free up.  */
5337                 mg->mg_virtual = 0;
5338                 sv_unmagic(tsv, PERL_MAGIC_backref);
5339             } else {
5340                 av = newAV();
5341                 AvREAL_off(av);
5342                 SvREFCNT_inc_simple_void(av); /* see discussion above */
5343             }
5344             *avp = av;
5345         }
5346     } else {
5347         const MAGIC *const mg
5348             = SvMAGICAL(tsv) ? mg_find(tsv, PERL_MAGIC_backref) : NULL;
5349         if (mg)
5350             av = MUTABLE_AV(mg->mg_obj);
5351         else {
5352             av = newAV();
5353             AvREAL_off(av);
5354             sv_magic(tsv, MUTABLE_SV(av), PERL_MAGIC_backref, NULL, 0);
5355             /* av now has a refcnt of 2; see discussion above */
5356         }
5357     }
5358     if (AvFILLp(av) >= AvMAX(av)) {
5359         av_extend(av, AvFILLp(av)+1);
5360     }
5361     AvARRAY(av)[++AvFILLp(av)] = sv; /* av_push() */
5362 }
5363
5364 /* delete a back-reference to ourselves from the backref magic associated
5365  * with the SV we point to.
5366  */
5367
5368 STATIC void
5369 S_sv_del_backref(pTHX_ SV *const tsv, SV *const sv)
5370 {
5371     dVAR;
5372     AV *av = NULL;
5373     SV **svp;
5374     I32 i;
5375
5376     PERL_ARGS_ASSERT_SV_DEL_BACKREF;
5377
5378     if (SvTYPE(tsv) == SVt_PVHV && SvOOK(tsv)) {
5379         av = *Perl_hv_backreferences_p(aTHX_ MUTABLE_HV(tsv));
5380         /* We mustn't attempt to "fix up" the hash here by moving the
5381            backreference array back to the hv_aux structure, as that is stored
5382            in the main HvARRAY(), and hfreentries assumes that no-one
5383            reallocates HvARRAY() while it is running.  */
5384     }
5385     if (!av) {
5386         const MAGIC *const mg
5387             = SvMAGICAL(tsv) ? mg_find(tsv, PERL_MAGIC_backref) : NULL;
5388         if (mg)
5389             av = MUTABLE_AV(mg->mg_obj);
5390     }
5391
5392     if (!av)
5393         Perl_croak(aTHX_ "panic: del_backref");
5394
5395     assert(!SvIS_FREED(av));
5396
5397     svp = AvARRAY(av);
5398     /* We shouldn't be in here more than once, but for paranoia reasons lets
5399        not assume this.  */
5400     for (i = AvFILLp(av); i >= 0; i--) {
5401         if (svp[i] == sv) {
5402             const SSize_t fill = AvFILLp(av);
5403             if (i != fill) {
5404                 /* We weren't the last entry.
5405                    An unordered list has this property that you can take the
5406                    last element off the end to fill the hole, and it's still
5407                    an unordered list :-)
5408                 */
5409                 svp[i] = svp[fill];
5410             }
5411             svp[fill] = NULL;
5412             AvFILLp(av) = fill - 1;
5413         }
5414     }
5415 }
5416
5417 int
5418 Perl_sv_kill_backrefs(pTHX_ SV *const sv, AV *const av)
5419 {
5420     SV **svp = AvARRAY(av);
5421
5422     PERL_ARGS_ASSERT_SV_KILL_BACKREFS;
5423     PERL_UNUSED_ARG(sv);
5424
5425     assert(!svp || !SvIS_FREED(av));
5426     if (svp) {
5427         SV *const *const last = svp + AvFILLp(av);
5428
5429         while (svp <= last) {
5430             if (*svp) {
5431                 SV *const referrer = *svp;
5432                 if (SvWEAKREF(referrer)) {
5433                     /* XXX Should we check that it hasn't changed? */
5434                     SvRV_set(referrer, 0);
5435                     SvOK_off(referrer);
5436                     SvWEAKREF_off(referrer);
5437                     SvSETMAGIC(referrer);
5438                 } else if (SvTYPE(referrer) == SVt_PVGV ||
5439                            SvTYPE(referrer) == SVt_PVLV) {
5440                     /* You lookin' at me?  */
5441                     assert(GvSTASH(referrer));
5442                     assert(GvSTASH(referrer) == (const HV *)sv);
5443                     GvSTASH(referrer) = 0;
5444                 } else {
5445                     Perl_croak(aTHX_
5446                                "panic: magic_killbackrefs (flags=%"UVxf")",
5447                                (UV)SvFLAGS(referrer));
5448                 }
5449
5450                 *svp = NULL;
5451             }
5452             svp++;
5453         }
5454     }
5455     SvREFCNT_dec(av); /* remove extra count added by sv_add_backref() */
5456     return 0;
5457 }
5458
5459 /*
5460 =for apidoc sv_insert
5461
5462 Inserts a string at the specified offset/length within the SV. Similar to
5463 the Perl substr() function. Handles get magic.
5464
5465 =for apidoc sv_insert_flags
5466
5467 Same as C<sv_insert>, but the extra C<flags> are passed the C<SvPV_force_flags> that applies to C<bigstr>.
5468
5469 =cut
5470 */
5471
5472 void
5473 Perl_sv_insert_flags(pTHX_ SV *const bigstr, const STRLEN offset, const STRLEN len, const char *const little, const STRLEN littlelen, const U32 flags)
5474 {
5475     dVAR;
5476     register char *big;
5477     register char *mid;
5478     register char *midend;
5479     register char *bigend;
5480     register I32 i;
5481     STRLEN curlen;
5482
5483     PERL_ARGS_ASSERT_SV_INSERT_FLAGS;
5484
5485     if (!bigstr)
5486         Perl_croak(aTHX_ "Can't modify non-existent substring");
5487     SvPV_force_flags(bigstr, curlen, flags);
5488     (void)SvPOK_only_UTF8(bigstr);
5489     if (offset + len > curlen) {
5490         SvGROW(bigstr, offset+len+1);
5491         Zero(SvPVX(bigstr)+curlen, offset+len-curlen, char);
5492         SvCUR_set(bigstr, offset+len);
5493     }
5494
5495     SvTAINT(bigstr);
5496     i = littlelen - len;
5497     if (i > 0) {                        /* string might grow */
5498         big = SvGROW(bigstr, SvCUR(bigstr) + i + 1);
5499         mid = big + offset + len;
5500         midend = bigend = big + SvCUR(bigstr);
5501         bigend += i;
5502         *bigend = '\0';
5503         while (midend > mid)            /* shove everything down */
5504             *--bigend = *--midend;
5505         Move(little,big+offset,littlelen,char);
5506         SvCUR_set(bigstr, SvCUR(bigstr) + i);
5507         SvSETMAGIC(bigstr);
5508         return;
5509     }
5510     else if (i == 0) {
5511         Move(little,SvPVX(bigstr)+offset,len,char);
5512         SvSETMAGIC(bigstr);
5513         return;
5514     }
5515
5516     big = SvPVX(bigstr);
5517     mid = big + offset;
5518     midend = mid + len;
5519     bigend = big + SvCUR(bigstr);
5520
5521     if (midend > bigend)
5522         Perl_croak(aTHX_ "panic: sv_insert");
5523
5524     if (mid - big > bigend - midend) {  /* faster to shorten from end */
5525         if (littlelen) {
5526             Move(little, mid, littlelen,char);
5527             mid += littlelen;
5528         }
5529         i = bigend - midend;
5530         if (i > 0) {
5531             Move(midend, mid, i,char);
5532             mid += i;
5533         }
5534         *mid = '\0';
5535         SvCUR_set(bigstr, mid - big);
5536     }
5537     else if ((i = mid - big)) { /* faster from front */
5538         midend -= littlelen;
5539         mid = midend;
5540         Move(big, midend - i, i, char);
5541         sv_chop(bigstr,midend-i);
5542         if (littlelen)
5543             Move(little, mid, littlelen,char);
5544     }
5545     else if (littlelen) {
5546         midend -= littlelen;
5547         sv_chop(bigstr,midend);
5548         Move(little,midend,littlelen,char);
5549     }
5550     else {
5551         sv_chop(bigstr,midend);
5552     }
5553     SvSETMAGIC(bigstr);
5554 }
5555
5556 /*
5557 =for apidoc sv_replace
5558
5559 Make the first argument a copy of the second, then delete the original.
5560 The target SV physically takes over ownership of the body of the source SV
5561 and inherits its flags; however, the target keeps any magic it owns,
5562 and any magic in the source is discarded.
5563 Note that this is a rather specialist SV copying operation; most of the
5564 time you'll want to use C<sv_setsv> or one of its many macro front-ends.
5565
5566 =cut
5567 */
5568
5569 void
5570 Perl_sv_replace(pTHX_ register SV *const sv, register SV *const nsv)
5571 {
5572     dVAR;
5573     const U32 refcnt = SvREFCNT(sv);
5574
5575     PERL_ARGS_ASSERT_SV_REPLACE;
5576
5577     SV_CHECK_THINKFIRST_COW_DROP(sv);
5578     if (SvREFCNT(nsv) != 1) {
5579         Perl_croak(aTHX_ "panic: reference miscount on nsv in sv_replace()"
5580                    " (%" UVuf " != 1)", (UV) SvREFCNT(nsv));
5581     }
5582     if (SvMAGICAL(sv)) {
5583         if (SvMAGICAL(nsv))
5584             mg_free(nsv);
5585         else
5586             sv_upgrade(nsv, SVt_PVMG);
5587         SvMAGIC_set(nsv, SvMAGIC(sv));
5588         SvFLAGS(nsv) |= SvMAGICAL(sv);
5589         SvMAGICAL_off(sv);
5590         SvMAGIC_set(sv, NULL);
5591     }
5592     SvREFCNT(sv) = 0;
5593     sv_clear(sv);
5594     assert(!SvREFCNT(sv));
5595 #ifdef DEBUG_LEAKING_SCALARS
5596     sv->sv_flags  = nsv->sv_flags;
5597     sv->sv_any    = nsv->sv_any;
5598     sv->sv_refcnt = nsv->sv_refcnt;
5599     sv->sv_u      = nsv->sv_u;
5600 #else
5601     StructCopy(nsv,sv,SV);
5602 #endif
5603     if(SvTYPE(sv) == SVt_IV) {
5604         SvANY(sv)
5605             = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
5606     }
5607         
5608
5609 #ifdef PERL_OLD_COPY_ON_WRITE
5610     if (SvIsCOW_normal(nsv)) {
5611         /* We need to follow the pointers around the loop to make the
5612            previous SV point to sv, rather than nsv.  */
5613         SV *next;
5614         SV *current = nsv;
5615         while ((next = SV_COW_NEXT_SV(current)) != nsv) {
5616             assert(next);
5617             current = next;
5618             assert(SvPVX_const(current) == SvPVX_const(nsv));
5619         }
5620         /* Make the SV before us point to the SV after us.  */
5621         if (DEBUG_C_TEST) {
5622             PerlIO_printf(Perl_debug_log, "previous is\n");
5623             sv_dump(current);
5624             PerlIO_printf(Perl_debug_log,
5625                           "move it from 0x%"UVxf" to 0x%"UVxf"\n",
5626                           (UV) SV_COW_NEXT_SV(current), (UV) sv);
5627         }
5628         SV_COW_NEXT_SV_SET(current, sv);
5629     }
5630 #endif
5631     SvREFCNT(sv) = refcnt;
5632     SvFLAGS(nsv) |= SVTYPEMASK;         /* Mark as freed */
5633     SvREFCNT(nsv) = 0;
5634     del_SV(nsv);
5635 }
5636
5637 /*
5638 =for apidoc sv_clear
5639
5640 Clear an SV: call any destructors, free up any memory used by the body,
5641 and free the body itself. The SV's head is I<not> freed, although
5642 its type is set to all 1's so that it won't inadvertently be assumed
5643 to be live during global destruction etc.
5644 This function should only be called when REFCNT is zero. Most of the time
5645 you'll want to call C<sv_free()> (or its macro wrapper C<SvREFCNT_dec>)
5646 instead.
5647
5648 =cut
5649 */
5650
5651 void
5652 Perl_sv_clear(pTHX_ register SV *const sv)
5653 {
5654     dVAR;
5655     const U32 type = SvTYPE(sv);
5656     const struct body_details *const sv_type_details
5657         = bodies_by_type + type;
5658     HV *stash;
5659
5660     PERL_ARGS_ASSERT_SV_CLEAR;
5661     assert(SvREFCNT(sv) == 0);
5662     assert(SvTYPE(sv) != SVTYPEMASK);
5663
5664     if (type <= SVt_IV) {
5665         /* See the comment in sv.h about the collusion between this early
5666            return and the overloading of the NULL slots in the size table.  */
5667         if (SvROK(sv))
5668             goto free_rv;
5669         SvFLAGS(sv) &= SVf_BREAK;
5670         SvFLAGS(sv) |= SVTYPEMASK;
5671         return;
5672     }
5673
5674     if (SvOBJECT(sv)) {
5675         if (PL_defstash &&      /* Still have a symbol table? */
5676             SvDESTROYABLE(sv))
5677         {
5678             dSP;
5679             HV* stash;
5680             do {        
5681                 CV* destructor;
5682                 stash = SvSTASH(sv);
5683                 destructor = StashHANDLER(stash,DESTROY);
5684                 if (destructor
5685                         /* A constant subroutine can have no side effects, so
5686                            don't bother calling it.  */
5687                         && !CvCONST(destructor)
5688                         /* Don't bother calling an empty destructor */
5689                         && (CvISXSUB(destructor)
5690                         || (CvSTART(destructor)
5691                             && (CvSTART(destructor)->op_next->op_type != OP_LEAVESUB))))
5692                 {
5693                     SV* const tmpref = newRV(sv);
5694                     SvREADONLY_on(tmpref);   /* DESTROY() could be naughty */
5695                     ENTER;
5696                     PUSHSTACKi(PERLSI_DESTROY);
5697                     EXTEND(SP, 2);
5698                     PUSHMARK(SP);
5699                     PUSHs(tmpref);
5700                     PUTBACK;
5701                     call_sv(MUTABLE_SV(destructor), G_DISCARD|G_EVAL|G_KEEPERR|G_VOID);
5702                 
5703                 
5704                     POPSTACK;
5705                     SPAGAIN;
5706                     LEAVE;
5707                     if(SvREFCNT(tmpref) < 2) {
5708                         /* tmpref is not kept alive! */
5709                         SvREFCNT(sv)--;
5710                         SvRV_set(tmpref, NULL);
5711                         SvROK_off(tmpref);
5712                     }
5713                     SvREFCNT_dec(tmpref);
5714                 }
5715             } while (SvOBJECT(sv) && SvSTASH(sv) != stash);
5716
5717
5718             if (SvREFCNT(sv)) {
5719                 if (PL_in_clean_objs)
5720                     Perl_croak(aTHX_ "DESTROY created new reference to dead object '%s'",
5721                           HvNAME_get(stash));
5722                 /* DESTROY gave object new lease on life */
5723                 return;
5724             }
5725         }
5726
5727         if (SvOBJECT(sv)) {
5728             SvREFCNT_dec(SvSTASH(sv));  /* possibly of changed persuasion */
5729             SvOBJECT_off(sv);   /* Curse the object. */
5730             if (type != SVt_PVIO)
5731                 --PL_sv_objcount;       /* XXX Might want something more general */
5732         }
5733     }
5734     if (type >= SVt_PVMG) {
5735         if (type == SVt_PVMG && SvPAD_OUR(sv)) {
5736             SvREFCNT_dec(SvOURSTASH(sv));
5737         } else if (SvMAGIC(sv))
5738             mg_free(sv);
5739         if (type == SVt_PVMG && SvPAD_TYPED(sv))
5740             SvREFCNT_dec(SvSTASH(sv));
5741     }
5742     switch (type) {
5743         /* case SVt_BIND: */
5744     case SVt_PVIO:
5745         if (IoIFP(sv) &&
5746             IoIFP(sv) != PerlIO_stdin() &&
5747             IoIFP(sv) != PerlIO_stdout() &&
5748             IoIFP(sv) != PerlIO_stderr())
5749         {
5750             io_close(MUTABLE_IO(sv), FALSE);
5751         }
5752         if (IoDIRP(sv) && !(IoFLAGS(sv) & IOf_FAKE_DIRP))
5753             PerlDir_close(IoDIRP(sv));
5754         IoDIRP(sv) = (DIR*)NULL;
5755         Safefree(IoTOP_NAME(sv));
5756         Safefree(IoFMT_NAME(sv));
5757         Safefree(IoBOTTOM_NAME(sv));
5758         goto freescalar;
5759     case SVt_REGEXP:
5760         /* FIXME for plugins */
5761         pregfree2((REGEXP*) sv);
5762         goto freescalar;
5763     case SVt_PVCV:
5764     case SVt_PVFM:
5765         cv_undef(MUTABLE_CV(sv));
5766         goto freescalar;
5767     case SVt_PVHV:
5768         if (PL_last_swash_hv == (const HV *)sv) {
5769             PL_last_swash_hv = NULL;
5770         }
5771         Perl_hv_kill_backrefs(aTHX_ MUTABLE_HV(sv));
5772         hv_undef(MUTABLE_HV(sv));
5773         break;
5774     case SVt_PVAV:
5775         if (PL_comppad == MUTABLE_AV(sv)) {
5776             PL_comppad = NULL;
5777             PL_curpad = NULL;
5778         }
5779         av_undef(MUTABLE_AV(sv));
5780         break;
5781     case SVt_PVLV:
5782         if (LvTYPE(sv) == 'T') { /* for tie: return HE to pool */
5783             SvREFCNT_dec(HeKEY_sv((HE*)LvTARG(sv)));
5784             HeNEXT((HE*)LvTARG(sv)) = PL_hv_fetch_ent_mh;
5785             PL_hv_fetch_ent_mh = (HE*)LvTARG(sv);
5786         }
5787         else if (LvTYPE(sv) != 't') /* unless tie: unrefcnted fake SV**  */
5788             SvREFCNT_dec(LvTARG(sv));
5789     case SVt_PVGV:
5790         if (isGV_with_GP(sv)) {
5791             if(GvCVu((const GV *)sv) && (stash = GvSTASH(MUTABLE_GV(sv)))
5792                && HvNAME_get(stash))
5793                 mro_method_changed_in(stash);
5794             gp_free(MUTABLE_GV(sv));
5795             if (GvNAME_HEK(sv))
5796                 unshare_hek(GvNAME_HEK(sv));
5797             /* If we're in a stash, we don't own a reference to it. However it does
5798                have a back reference to us, which needs to be cleared.  */
5799             if (!SvVALID(sv) && (stash = GvSTASH(sv)))
5800                     sv_del_backref(MUTABLE_SV(stash), sv);
5801         }
5802         /* FIXME. There are probably more unreferenced pointers to SVs in the
5803            interpreter struct that we should check and tidy in a similar
5804            fashion to this:  */
5805         if ((const GV *)sv == PL_last_in_gv)
5806             PL_last_in_gv = NULL;
5807     case SVt_PVMG:
5808     case SVt_PVNV:
5809     case SVt_PVIV:
5810     case SVt_PV:
5811       freescalar:
5812         /* Don't bother with SvOOK_off(sv); as we're only going to free it.  */
5813         if (SvOOK(sv)) {
5814             STRLEN offset;
5815             SvOOK_offset(sv, offset);
5816             SvPV_set(sv, SvPVX_mutable(sv) - offset);
5817             /* Don't even bother with turning off the OOK flag.  */
5818         }
5819         if (SvROK(sv)) {
5820         free_rv:
5821             {
5822                 SV * const target = SvRV(sv);
5823                 if (SvWEAKREF(sv))
5824                     sv_del_backref(target, sv);
5825                 else
5826                     SvREFCNT_dec(target);
5827             }
5828         }
5829 #ifdef PERL_OLD_COPY_ON_WRITE
5830         else if (SvPVX_const(sv)) {
5831             if (SvIsCOW(sv)) {
5832                 if (DEBUG_C_TEST) {
5833                     PerlIO_printf(Perl_debug_log, "Copy on write: clear\n");
5834                     sv_dump(sv);
5835                 }
5836                 if (SvLEN(sv)) {
5837                     sv_release_COW(sv, SvPVX_const(sv), SV_COW_NEXT_SV(sv));
5838                 } else {
5839                     unshare_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sv)));
5840                 }
5841
5842                 SvFAKE_off(sv);
5843             } else if (SvLEN(sv)) {
5844                 Safefree(SvPVX_const(sv));
5845             }
5846         }
5847 #else
5848         else if (SvPVX_const(sv) && SvLEN(sv))
5849             Safefree(SvPVX_mutable(sv));
5850         else if (SvPVX_const(sv) && SvREADONLY(sv) && SvFAKE(sv)) {
5851             unshare_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sv)));
5852             SvFAKE_off(sv);
5853         }
5854 #endif
5855         break;
5856     case SVt_NV:
5857         break;
5858     }
5859
5860     SvFLAGS(sv) &= SVf_BREAK;
5861     SvFLAGS(sv) |= SVTYPEMASK;
5862
5863     if (sv_type_details->arena) {
5864         del_body(((char *)SvANY(sv) + sv_type_details->offset),
5865                  &PL_body_roots[type]);
5866     }
5867     else if (sv_type_details->body_size) {
5868         my_safefree(SvANY(sv));
5869     }
5870 }
5871
5872 /*
5873 =for apidoc sv_newref
5874
5875 Increment an SV's reference count. Use the C<SvREFCNT_inc()> wrapper
5876 instead.
5877
5878 =cut
5879 */
5880
5881 SV *
5882 Perl_sv_newref(pTHX_ SV *const sv)
5883 {
5884     PERL_UNUSED_CONTEXT;
5885     if (sv)
5886         (SvREFCNT(sv))++;
5887     return sv;
5888 }
5889
5890 /*
5891 =for apidoc sv_free
5892
5893 Decrement an SV's reference count, and if it drops to zero, call
5894 C<sv_clear> to invoke destructors and free up any memory used by
5895 the body; finally, deallocate the SV's head itself.
5896 Normally called via a wrapper macro C<SvREFCNT_dec>.
5897
5898 =cut
5899 */
5900
5901 void
5902 Perl_sv_free(pTHX_ SV *const sv)
5903 {
5904     dVAR;
5905     if (!sv)
5906         return;
5907     if (SvREFCNT(sv) == 0) {
5908         if (SvFLAGS(sv) & SVf_BREAK)
5909             /* this SV's refcnt has been artificially decremented to
5910              * trigger cleanup */
5911             return;
5912         if (PL_in_clean_all) /* All is fair */
5913             return;
5914         if (SvREADONLY(sv) && SvIMMORTAL(sv)) {
5915             /* make sure SvREFCNT(sv)==0 happens very seldom */
5916             SvREFCNT(sv) = (~(U32)0)/2;
5917             return;
5918         }
5919         if (ckWARN_d(WARN_INTERNAL)) {
5920 #ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
5921             Perl_dump_sv_child(aTHX_ sv);
5922 #else
5923   #ifdef DEBUG_LEAKING_SCALARS
5924             sv_dump(sv);
5925   #endif
5926 #ifdef DEBUG_LEAKING_SCALARS_ABORT
5927             if (PL_warnhook == PERL_WARNHOOK_FATAL
5928                 || ckDEAD(packWARN(WARN_INTERNAL))) {
5929                 /* Don't let Perl_warner cause us to escape our fate:  */
5930                 abort();
5931             }
5932 #endif
5933             /* This may not return:  */
5934             Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
5935                         "Attempt to free unreferenced scalar: SV 0x%"UVxf
5936                         pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
5937 #endif
5938         }
5939 #ifdef DEBUG_LEAKING_SCALARS_ABORT
5940         abort();
5941 #endif
5942         return;
5943     }
5944     if (--(SvREFCNT(sv)) > 0)
5945         return;
5946     Perl_sv_free2(aTHX_ sv);
5947 }
5948
5949 void
5950 Perl_sv_free2(pTHX_ SV *const sv)
5951 {
5952     dVAR;
5953
5954     PERL_ARGS_ASSERT_SV_FREE2;
5955
5956 #ifdef DEBUGGING
5957     if (SvTEMP(sv)) {
5958         Perl_ck_warner_d(aTHX_ packWARN(WARN_DEBUGGING),
5959                          "Attempt to free temp prematurely: SV 0x%"UVxf
5960                          pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
5961         return;
5962     }
5963 #endif
5964     if (SvREADONLY(sv) && SvIMMORTAL(sv)) {
5965         /* make sure SvREFCNT(sv)==0 happens very seldom */
5966         SvREFCNT(sv) = (~(U32)0)/2;
5967         return;
5968     }
5969     sv_clear(sv);
5970     if (! SvREFCNT(sv))
5971         del_SV(sv);
5972 }
5973
5974 /*
5975 =for apidoc sv_len
5976
5977 Returns the length of the string in the SV. Handles magic and type
5978 coercion.  See also C<SvCUR>, which gives raw access to the xpv_cur slot.
5979
5980 =cut
5981 */
5982
5983 STRLEN
5984 Perl_sv_len(pTHX_ register SV *const sv)
5985 {
5986     STRLEN len;
5987
5988     if (!sv)
5989         return 0;
5990
5991     if (SvGMAGICAL(sv))
5992         len = mg_length(sv);
5993     else
5994         (void)SvPV_const(sv, len);
5995     return len;
5996 }
5997
5998 /*
5999 =for apidoc sv_len_utf8
6000
6001 Returns the number of characters in the string in an SV, counting wide
6002 UTF-8 bytes as a single character. Handles magic and type coercion.
6003
6004 =cut
6005 */
6006
6007 /*
6008  * The length is cached in PERL_MAGIC_utf8, in the mg_len field.  Also the
6009  * mg_ptr is used, by sv_pos_u2b() and sv_pos_b2u() - see the comments below.
6010  * (Note that the mg_len is not the length of the mg_ptr field.
6011  * This allows the cache to store the character length of the string without
6012  * needing to malloc() extra storage to attach to the mg_ptr.)
6013  *
6014  */
6015
6016 STRLEN
6017 Perl_sv_len_utf8(pTHX_ register SV *const sv)
6018 {
6019     if (!sv)
6020         return 0;
6021
6022     if (SvGMAGICAL(sv))
6023         return mg_length(sv);
6024     else
6025     {
6026         STRLEN len;
6027         const U8 *s = (U8*)SvPV_const(sv, len);
6028
6029         if (PL_utf8cache) {
6030             STRLEN ulen;
6031             MAGIC *mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
6032
6033             if (mg && mg->mg_len != -1) {
6034                 ulen = mg->mg_len;
6035                 if (PL_utf8cache < 0) {
6036                     const STRLEN real = Perl_utf8_length(aTHX_ s, s + len);
6037                     if (real != ulen) {
6038                         /* Need to turn the assertions off otherwise we may
6039                            recurse infinitely while printing error messages.
6040                         */
6041                         SAVEI8(PL_utf8cache);
6042                         PL_utf8cache = 0;
6043                         Perl_croak(aTHX_ "panic: sv_len_utf8 cache %"UVuf
6044                                    " real %"UVuf" for %"SVf,
6045                                    (UV) ulen, (UV) real, SVfARG(sv));
6046                     }
6047                 }
6048             }
6049             else {
6050                 ulen = Perl_utf8_length(aTHX_ s, s + len);
6051                 if (!SvREADONLY(sv)) {
6052                     if (!mg && (SvTYPE(sv) < SVt_PVMG ||
6053                                 !(mg = mg_find(sv, PERL_MAGIC_utf8)))) {
6054                         mg = sv_magicext(sv, 0, PERL_MAGIC_utf8,
6055                                          &PL_vtbl_utf8, 0, 0);
6056                     }
6057                     assert(mg);
6058                     mg->mg_len = ulen;
6059                     /* For now, treat "overflowed" as "still unknown".
6060                        See RT #72924.  */
6061                     if (ulen != (STRLEN) mg->mg_len)
6062                         mg->mg_len = -1;
6063                 }
6064             }
6065             return ulen;
6066         }
6067         return Perl_utf8_length(aTHX_ s, s + len);
6068     }
6069 }
6070
6071 /* Walk forwards to find the byte corresponding to the passed in UTF-8
6072    offset.  */
6073 static STRLEN
6074 S_sv_pos_u2b_forwards(const U8 *const start, const U8 *const send,
6075                       STRLEN uoffset)
6076 {
6077     const U8 *s = start;
6078
6079     PERL_ARGS_ASSERT_SV_POS_U2B_FORWARDS;
6080
6081     while (s < send && uoffset--)
6082         s += UTF8SKIP(s);
6083     if (s > send) {
6084         /* This is the existing behaviour. Possibly it should be a croak, as
6085            it's actually a bounds error  */
6086         s = send;
6087     }
6088     return s - start;
6089 }
6090
6091 /* Given the length of the string in both bytes and UTF-8 characters, decide
6092    whether to walk forwards or backwards to find the byte corresponding to
6093    the passed in UTF-8 offset.  */
6094 static STRLEN
6095 S_sv_pos_u2b_midway(const U8 *const start, const U8 *send,
6096                       const STRLEN uoffset, const STRLEN uend)
6097 {
6098     STRLEN backw = uend - uoffset;
6099
6100     PERL_ARGS_ASSERT_SV_POS_U2B_MIDWAY;
6101
6102     if (uoffset < 2 * backw) {
6103         /* The assumption is that going forwards is twice the speed of going
6104            forward (that's where the 2 * backw comes from).
6105            (The real figure of course depends on the UTF-8 data.)  */
6106         return sv_pos_u2b_forwards(start, send, uoffset);
6107     }
6108
6109     while (backw--) {
6110         send--;
6111         while (UTF8_IS_CONTINUATION(*send))
6112             send--;
6113     }
6114     return send - start;
6115 }
6116
6117 /* For the string representation of the given scalar, find the byte
6118    corresponding to the passed in UTF-8 offset.  uoffset0 and boffset0
6119    give another position in the string, *before* the sought offset, which
6120    (which is always true, as 0, 0 is a valid pair of positions), which should
6121    help reduce the amount of linear searching.
6122    If *mgp is non-NULL, it should point to the UTF-8 cache magic, which
6123    will be used to reduce the amount of linear searching. The cache will be
6124    created if necessary, and the found value offered to it for update.  */
6125 static STRLEN
6126 S_sv_pos_u2b_cached(pTHX_ SV *const sv, MAGIC **const mgp, const U8 *const start,
6127                     const U8 *const send, const STRLEN uoffset,
6128                     STRLEN uoffset0, STRLEN boffset0)
6129 {
6130     STRLEN boffset = 0; /* Actually always set, but let's keep gcc happy.  */
6131     bool found = FALSE;
6132
6133     PERL_ARGS_ASSERT_SV_POS_U2B_CACHED;
6134
6135     assert (uoffset >= uoffset0);
6136
6137     if (!SvREADONLY(sv)
6138         && PL_utf8cache
6139         && (*mgp || (SvTYPE(sv) >= SVt_PVMG &&
6140                      (*mgp = mg_find(sv, PERL_MAGIC_utf8))))) {
6141         if ((*mgp)->mg_ptr) {
6142             STRLEN *cache = (STRLEN *) (*mgp)->mg_ptr;
6143             if (cache[0] == uoffset) {
6144                 /* An exact match. */
6145                 return cache[1];
6146             }
6147             if (cache[2] == uoffset) {
6148                 /* An exact match. */
6149                 return cache[3];
6150             }
6151
6152             if (cache[0] < uoffset) {
6153                 /* The cache already knows part of the way.   */
6154                 if (cache[0] > uoffset0) {
6155                     /* The cache knows more than the passed in pair  */
6156                     uoffset0 = cache[0];
6157                     boffset0 = cache[1];
6158                 }
6159                 if ((*mgp)->mg_len != -1) {
6160                     /* And we know the end too.  */
6161                     boffset = boffset0
6162                         + sv_pos_u2b_midway(start + boffset0, send,
6163                                               uoffset - uoffset0,
6164                                               (*mgp)->mg_len - uoffset0);
6165                 } else {
6166                     boffset = boffset0
6167                         + sv_pos_u2b_forwards(start + boffset0,
6168                                                 send, uoffset - uoffset0);
6169                 }
6170             }
6171             else if (cache[2] < uoffset) {
6172                 /* We're between the two cache entries.  */
6173                 if (cache[2] > uoffset0) {
6174                     /* and the cache knows more than the passed in pair  */
6175                     uoffset0 = cache[2];
6176                     boffset0 = cache[3];
6177                 }
6178
6179                 boffset = boffset0
6180                     + sv_pos_u2b_midway(start + boffset0,
6181                                           start + cache[1],
6182                                           uoffset - uoffset0,
6183                                           cache[0] - uoffset0);
6184             } else {
6185                 boffset = boffset0
6186                     + sv_pos_u2b_midway(start + boffset0,
6187                                           start + cache[3],
6188                                           uoffset - uoffset0,
6189                                           cache[2] - uoffset0);
6190             }
6191             found = TRUE;
6192         }
6193         else if ((*mgp)->mg_len != -1) {
6194             /* If we can take advantage of a passed in offset, do so.  */
6195             /* In fact, offset0 is either 0, or less than offset, so don't
6196                need to worry about the other possibility.  */
6197             boffset = boffset0
6198                 + sv_pos_u2b_midway(start + boffset0, send,
6199                                       uoffset - uoffset0,
6200                                       (*mgp)->mg_len - uoffset0);
6201             found = TRUE;
6202         }
6203     }
6204
6205     if (!found || PL_utf8cache < 0) {
6206         const STRLEN real_boffset
6207             = boffset0 + sv_pos_u2b_forwards(start + boffset0,
6208                                                send, uoffset - uoffset0);
6209
6210         if (found && PL_utf8cache < 0) {
6211             if (real_boffset != boffset) {
6212                 /* Need to turn the assertions off otherwise we may recurse
6213                    infinitely while printing error messages.  */
6214                 SAVEI8(PL_utf8cache);
6215                 PL_utf8cache = 0;
6216                 Perl_croak(aTHX_ "panic: sv_pos_u2b_cache cache %"UVuf
6217                            " real %"UVuf" for %"SVf,
6218                            (UV) boffset, (UV) real_boffset, SVfARG(sv));
6219             }
6220         }
6221         boffset = real_boffset;
6222     }
6223
6224     if (PL_utf8cache)
6225         utf8_mg_pos_cache_update(sv, mgp, boffset, uoffset, send - start);
6226     return boffset;
6227 }
6228
6229
6230 /*
6231 =for apidoc sv_pos_u2b_flags
6232
6233 Converts the value pointed to by offsetp from a count of UTF-8 chars from
6234 the start of the string, to a count of the equivalent number of bytes; if
6235 lenp is non-zero, it does the same to lenp, but this time starting from
6236 the offset, rather than from the start of the string. Handles type coercion.
6237 I<flags> is passed to C<SvPV_flags>, and usually should be
6238 C<SV_GMAGIC|SV_CONST_RETURN> to handle magic.
6239
6240 =cut
6241 */
6242
6243 /*
6244  * sv_pos_u2b_flags() uses, like sv_pos_b2u(), the mg_ptr of the potential
6245  * PERL_MAGIC_utf8 of the sv to store the mapping between UTF-8 and
6246  * byte offsets.  See also the comments of S_utf8_mg_pos_cache_update().
6247  *
6248  */
6249
6250 STRLEN
6251 Perl_sv_pos_u2b_flags(pTHX_ SV *const sv, STRLEN uoffset, STRLEN *const lenp,
6252                       U32 flags)
6253 {
6254     const U8 *start;
6255     STRLEN len;
6256     STRLEN boffset;
6257
6258     PERL_ARGS_ASSERT_SV_POS_U2B_FLAGS;
6259
6260     start = (U8*)SvPV_flags(sv, len, flags);
6261     if (len) {
6262         const U8 * const send = start + len;
6263         MAGIC *mg = NULL;
6264         boffset = sv_pos_u2b_cached(sv, &mg, start, send, uoffset, 0, 0);
6265
6266         if (lenp) {
6267             /* Convert the relative offset to absolute.  */
6268             const STRLEN uoffset2 = uoffset + *lenp;
6269             const STRLEN boffset2
6270                 = sv_pos_u2b_cached(sv, &mg, start, send, uoffset2,
6271                                       uoffset, boffset) - boffset;
6272
6273             *lenp = boffset2;
6274         }
6275     } else {
6276         if (lenp)
6277             *lenp = 0;
6278         boffset = 0;
6279     }
6280
6281     return boffset;
6282 }
6283
6284 /*
6285 =for apidoc sv_pos_u2b
6286
6287 Converts the value pointed to by offsetp from a count of UTF-8 chars from
6288 the start of the string, to a count of the equivalent number of bytes; if
6289 lenp is non-zero, it does the same to lenp, but this time starting from
6290 the offset, rather than from the start of the string. Handles magic and
6291 type coercion.
6292
6293 Use C<sv_pos_u2b_flags> in preference, which correctly handles strings longer
6294 than 2Gb.
6295
6296 =cut
6297 */
6298
6299 /*
6300  * sv_pos_u2b() uses, like sv_pos_b2u(), the mg_ptr of the potential
6301  * PERL_MAGIC_utf8 of the sv to store the mapping between UTF-8 and
6302  * byte offsets.  See also the comments of S_utf8_mg_pos_cache_update().
6303  *
6304  */
6305
6306 /* This function is subject to size and sign problems */
6307
6308 void
6309 Perl_sv_pos_u2b(pTHX_ register SV *const sv, I32 *const offsetp, I32 *const lenp)
6310 {
6311     PERL_ARGS_ASSERT_SV_POS_U2B;
6312
6313     if (lenp) {
6314         STRLEN ulen = (STRLEN)*lenp;
6315         *offsetp = (I32)sv_pos_u2b_flags(sv, (STRLEN)*offsetp, &ulen,
6316                                          SV_GMAGIC|SV_CONST_RETURN);
6317         *lenp = (I32)ulen;
6318     } else {
6319         *offsetp = (I32)sv_pos_u2b_flags(sv, (STRLEN)*offsetp, NULL,
6320                                          SV_GMAGIC|SV_CONST_RETURN);
6321     }
6322 }
6323
6324 /* Create and update the UTF8 magic offset cache, with the proffered utf8/
6325    byte length pairing. The (byte) length of the total SV is passed in too,
6326    as blen, because for some (more esoteric) SVs, the call to SvPV_const()
6327    may not have updated SvCUR, so we can't rely on reading it directly.
6328
6329    The proffered utf8/byte length pairing isn't used if the cache already has
6330    two pairs, and swapping either for the proffered pair would increase the
6331    RMS of the intervals between known byte offsets.
6332
6333    The cache itself consists of 4 STRLEN values
6334    0: larger UTF-8 offset
6335    1: corresponding byte offset
6336    2: smaller UTF-8 offset
6337    3: corresponding byte offset
6338
6339    Unused cache pairs have the value 0, 0.
6340    Keeping the cache "backwards" means that the invariant of
6341    cache[0] >= cache[2] is maintained even with empty slots, which means that
6342    the code that uses it doesn't need to worry if only 1 entry has actually
6343    been set to non-zero.  It also makes the "position beyond the end of the
6344    cache" logic much simpler, as the first slot is always the one to start
6345    from.   
6346 */
6347 static void
6348 S_utf8_mg_pos_cache_update(pTHX_ SV *const sv, MAGIC **const mgp, const STRLEN byte,
6349                            const STRLEN utf8, const STRLEN blen)
6350 {
6351     STRLEN *cache;
6352
6353     PERL_ARGS_ASSERT_UTF8_MG_POS_CACHE_UPDATE;
6354
6355     if (SvREADONLY(sv))
6356         return;
6357
6358     if (!*mgp && (SvTYPE(sv) < SVt_PVMG ||
6359                   !(*mgp = mg_find(sv, PERL_MAGIC_utf8)))) {
6360         *mgp = sv_magicext(sv, 0, PERL_MAGIC_utf8, (MGVTBL*)&PL_vtbl_utf8, 0,
6361                            0);
6362         (*mgp)->mg_len = -1;
6363     }
6364     assert(*mgp);
6365
6366     if (!(cache = (STRLEN *)(*mgp)->mg_ptr)) {
6367         Newxz(cache, PERL_MAGIC_UTF8_CACHESIZE * 2, STRLEN);
6368         (*mgp)->mg_ptr = (char *) cache;
6369     }
6370     assert(cache);
6371
6372     if (PL_utf8cache < 0 && SvPOKp(sv)) {
6373         /* SvPOKp() because it's possible that sv has string overloading, and
6374            therefore is a reference, hence SvPVX() is actually a pointer.
6375            This cures the (very real) symptoms of RT 69422, but I'm not actually
6376            sure whether we should even be caching the results of UTF-8
6377            operations on overloading, given that nothing stops overloading
6378            returning a different value every time it's called.  */
6379         const U8 *start = (const U8 *) SvPVX_const(sv);
6380         const STRLEN realutf8 = utf8_length(start, start + byte);
6381
6382         if (realutf8 != utf8) {
6383             /* Need to turn the assertions off otherwise we may recurse
6384                infinitely while printing error messages.  */
6385             SAVEI8(PL_utf8cache);
6386             PL_utf8cache = 0;
6387             Perl_croak(aTHX_ "panic: utf8_mg_pos_cache_update cache %"UVuf
6388                        " real %"UVuf" for %"SVf, (UV) utf8, (UV) realutf8, SVfARG(sv));
6389         }
6390     }
6391
6392     /* Cache is held with the later position first, to simplify the code
6393        that deals with unbounded ends.  */
6394        
6395     ASSERT_UTF8_CACHE(cache);
6396     if (cache[1] == 0) {
6397         /* Cache is totally empty  */
6398         cache[0] = utf8;
6399         cache[1] = byte;
6400     } else if (cache[3] == 0) {
6401         if (byte > cache[1]) {
6402             /* New one is larger, so goes first.  */
6403             cache[2] = cache[0];
6404             cache[3] = cache[1];
6405             cache[0] = utf8;
6406             cache[1] = byte;
6407         } else {
6408             cache[2] = utf8;
6409             cache[3] = byte;
6410         }
6411     } else {
6412 #define THREEWAY_SQUARE(a,b,c,d) \
6413             ((float)((d) - (c))) * ((float)((d) - (c))) \
6414             + ((float)((c) - (b))) * ((float)((c) - (b))) \
6415                + ((float)((b) - (a))) * ((float)((b) - (a)))
6416
6417         /* Cache has 2 slots in use, and we know three potential pairs.
6418            Keep the two that give the lowest RMS distance. Do the
6419            calcualation in bytes simply because we always know the byte
6420            length.  squareroot has the same ordering as the positive value,
6421            so don't bother with the actual square root.  */
6422         const float existing = THREEWAY_SQUARE(0, cache[3], cache[1], blen);
6423         if (byte > cache[1]) {
6424             /* New position is after the existing pair of pairs.  */
6425             const float keep_earlier
6426                 = THREEWAY_SQUARE(0, cache[3], byte, blen);
6427             const float keep_later
6428                 = THREEWAY_SQUARE(0, cache[1], byte, blen);
6429
6430             if (keep_later < keep_earlier) {
6431                 if (keep_later < existing) {
6432                     cache[2] = cache[0];
6433                     cache[3] = cache[1];
6434                     cache[0] = utf8;
6435                     cache[1] = byte;
6436                 }
6437             }
6438             else {
6439                 if (keep_earlier < existing) {
6440                     cache[0] = utf8;
6441                     cache[1] = byte;
6442                 }
6443             }
6444         }
6445         else if (byte > cache[3]) {
6446             /* New position is between the existing pair of pairs.  */
6447             const float keep_earlier
6448                 = THREEWAY_SQUARE(0, cache[3], byte, blen);
6449             const float keep_later
6450                 = THREEWAY_SQUARE(0, byte, cache[1], blen);
6451
6452             if (keep_later < keep_earlier) {
6453                 if (keep_later < existing) {
6454                     cache[2] = utf8;
6455                     cache[3] = byte;
6456                 }
6457             }
6458             else {
6459                 if (keep_earlier < existing) {
6460                     cache[0] = utf8;
6461                     cache[1] = byte;
6462                 }
6463             }
6464         }
6465         else {
6466             /* New position is before the existing pair of pairs.  */
6467             const float keep_earlier
6468                 = THREEWAY_SQUARE(0, byte, cache[3], blen);
6469             const float keep_later
6470                 = THREEWAY_SQUARE(0, byte, cache[1], blen);
6471
6472             if (keep_later < keep_earlier) {
6473                 if (keep_later < existing) {
6474                     cache[2] = utf8;
6475                     cache[3] = byte;
6476                 }
6477             }
6478             else {
6479                 if (keep_earlier < existing) {
6480                     cache[0] = cache[2];
6481                     cache[1] = cache[3];
6482                     cache[2] = utf8;
6483                     cache[3] = byte;
6484                 }
6485             }
6486         }
6487     }
6488     ASSERT_UTF8_CACHE(cache);
6489 }
6490
6491 /* We already know all of the way, now we may be able to walk back.  The same
6492    assumption is made as in S_sv_pos_u2b_midway(), namely that walking
6493    backward is half the speed of walking forward. */
6494 static STRLEN
6495 S_sv_pos_b2u_midway(pTHX_ const U8 *const s, const U8 *const target,
6496                     const U8 *end, STRLEN endu)
6497 {
6498     const STRLEN forw = target - s;
6499     STRLEN backw = end - target;
6500
6501     PERL_ARGS_ASSERT_SV_POS_B2U_MIDWAY;
6502
6503     if (forw < 2 * backw) {
6504         return utf8_length(s, target);
6505     }
6506
6507     while (end > target) {
6508         end--;
6509         while (UTF8_IS_CONTINUATION(*end)) {
6510             end--;
6511         }
6512         endu--;
6513     }
6514     return endu;
6515 }
6516
6517 /*
6518 =for apidoc sv_pos_b2u
6519
6520 Converts the value pointed to by offsetp from a count of bytes from the
6521 start of the string, to a count of the equivalent number of UTF-8 chars.
6522 Handles magic and type coercion.
6523
6524 =cut
6525 */
6526
6527 /*
6528  * sv_pos_b2u() uses, like sv_pos_u2b(), the mg_ptr of the potential
6529  * PERL_MAGIC_utf8 of the sv to store the mapping between UTF-8 and
6530  * byte offsets.
6531  *
6532  */
6533 void
6534 Perl_sv_pos_b2u(pTHX_ register SV *const sv, I32 *const offsetp)
6535 {
6536     const U8* s;
6537     const STRLEN byte = *offsetp;
6538     STRLEN len = 0; /* Actually always set, but let's keep gcc happy.  */
6539     STRLEN blen;
6540     MAGIC* mg = NULL;
6541     const U8* send;
6542     bool found = FALSE;
6543
6544     PERL_ARGS_ASSERT_SV_POS_B2U;
6545
6546     if (!sv)
6547         return;
6548
6549     s = (const U8*)SvPV_const(sv, blen);
6550
6551     if (blen < byte)
6552         Perl_croak(aTHX_ "panic: sv_pos_b2u: bad byte offset");
6553
6554     send = s + byte;
6555
6556     if (!SvREADONLY(sv)
6557         && PL_utf8cache
6558         && SvTYPE(sv) >= SVt_PVMG
6559         && (mg = mg_find(sv, PERL_MAGIC_utf8)))
6560     {
6561         if (mg->mg_ptr) {
6562             STRLEN * const cache = (STRLEN *) mg->mg_ptr;
6563             if (cache[1] == byte) {
6564                 /* An exact match. */
6565                 *offsetp = cache[0];
6566                 return;
6567             }
6568             if (cache[3] == byte) {
6569                 /* An exact match. */
6570                 *offsetp = cache[2];
6571                 return;
6572             }
6573
6574             if (cache[1] < byte) {
6575                 /* We already know part of the way. */
6576                 if (mg->mg_len != -1) {
6577                     /* Actually, we know the end too.  */
6578                     len = cache[0]
6579                         + S_sv_pos_b2u_midway(aTHX_ s + cache[1], send,
6580                                               s + blen, mg->mg_len - cache[0]);
6581                 } else {
6582                     len = cache[0] + utf8_length(s + cache[1], send);
6583                 }
6584             }
6585             else if (cache[3] < byte) {
6586                 /* We're between the two cached pairs, so we do the calculation
6587                    offset by the byte/utf-8 positions for the earlier pair,
6588                    then add the utf-8 characters from the string start to
6589                    there.  */
6590                 len = S_sv_pos_b2u_midway(aTHX_ s + cache[3], send,
6591                                           s + cache[1], cache[0] - cache[2])
6592                     + cache[2];
6593
6594             }
6595             else { /* cache[3] > byte */
6596                 len = S_sv_pos_b2u_midway(aTHX_ s, send, s + cache[3],
6597                                           cache[2]);
6598
6599             }
6600             ASSERT_UTF8_CACHE(cache);
6601             found = TRUE;
6602         } else if (mg->mg_len != -1) {
6603             len = S_sv_pos_b2u_midway(aTHX_ s, send, s + blen, mg->mg_len);
6604             found = TRUE;
6605         }
6606     }
6607     if (!found || PL_utf8cache < 0) {
6608         const STRLEN real_len = utf8_length(s, send);
6609
6610         if (found && PL_utf8cache < 0) {
6611             if (len != real_len) {
6612                 /* Need to turn the assertions off otherwise we may recurse
6613                    infinitely while printing error messages.  */
6614                 SAVEI8(PL_utf8cache);
6615                 PL_utf8cache = 0;
6616                 Perl_croak(aTHX_ "panic: sv_pos_b2u cache %"UVuf
6617                            " real %"UVuf" for %"SVf,
6618                            (UV) len, (UV) real_len, SVfARG(sv));
6619             }
6620         }
6621         len = real_len;
6622     }
6623     *offsetp = len;
6624
6625     if (PL_utf8cache)
6626         utf8_mg_pos_cache_update(sv, &mg, byte, len, blen);
6627 }
6628
6629 /*
6630 =for apidoc sv_eq
6631
6632 Returns a boolean indicating whether the strings in the two SVs are
6633 identical. Is UTF-8 and 'use bytes' aware, handles get magic, and will
6634 coerce its args to strings if necessary.
6635
6636 =cut
6637 */
6638
6639 I32
6640 Perl_sv_eq(pTHX_ register SV *sv1, register SV *sv2)
6641 {
6642     dVAR;
6643     const char *pv1;
6644     STRLEN cur1;
6645     const char *pv2;
6646     STRLEN cur2;
6647     I32  eq     = 0;
6648     char *tpv   = NULL;
6649     SV* svrecode = NULL;
6650
6651     if (!sv1) {
6652         pv1 = "";
6653         cur1 = 0;
6654     }
6655     else {
6656         /* if pv1 and pv2 are the same, second SvPV_const call may
6657          * invalidate pv1, so we may need to make a copy */
6658         if (sv1 == sv2 && (SvTHINKFIRST(sv1) || SvGMAGICAL(sv1))) {
6659             pv1 = SvPV_const(sv1, cur1);
6660             sv1 = newSVpvn_flags(pv1, cur1, SVs_TEMP | SvUTF8(sv2));
6661         }
6662         pv1 = SvPV_const(sv1, cur1);
6663     }
6664
6665     if (!sv2){
6666         pv2 = "";
6667         cur2 = 0;
6668     }
6669     else
6670         pv2 = SvPV_const(sv2, cur2);
6671
6672     if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
6673         /* Differing utf8ness.
6674          * Do not UTF8size the comparands as a side-effect. */
6675          if (PL_encoding) {
6676               if (SvUTF8(sv1)) {
6677                    svrecode = newSVpvn(pv2, cur2);
6678                    sv_recode_to_utf8(svrecode, PL_encoding);
6679                    pv2 = SvPV_const(svrecode, cur2);
6680               }
6681               else {
6682                    svrecode = newSVpvn(pv1, cur1);
6683                    sv_recode_to_utf8(svrecode, PL_encoding);
6684                    pv1 = SvPV_const(svrecode, cur1);
6685               }
6686               /* Now both are in UTF-8. */
6687               if (cur1 != cur2) {
6688                    SvREFCNT_dec(svrecode);
6689                    return FALSE;
6690               }
6691          }
6692          else {
6693               bool is_utf8 = TRUE;
6694
6695               if (SvUTF8(sv1)) {
6696                    /* sv1 is the UTF-8 one,
6697                     * if is equal it must be downgrade-able */
6698                    char * const pv = (char*)bytes_from_utf8((const U8*)pv1,
6699                                                      &cur1, &is_utf8);
6700                    if (pv != pv1)
6701                         pv1 = tpv = pv;
6702               }
6703               else {
6704                    /* sv2 is the UTF-8 one,
6705                     * if is equal it must be downgrade-able */
6706                    char * const pv = (char *)bytes_from_utf8((const U8*)pv2,
6707                                                       &cur2, &is_utf8);
6708                    if (pv != pv2)
6709                         pv2 = tpv = pv;
6710               }
6711               if (is_utf8) {
6712                    /* Downgrade not possible - cannot be eq */
6713                    assert (tpv == 0);
6714                    return FALSE;
6715               }
6716          }
6717     }
6718
6719     if (cur1 == cur2)
6720         eq = (pv1 == pv2) || memEQ(pv1, pv2, cur1);
6721         
6722     SvREFCNT_dec(svrecode);
6723     if (tpv)
6724         Safefree(tpv);
6725
6726     return eq;
6727 }
6728
6729 /*
6730 =for apidoc sv_cmp
6731
6732 Compares the strings in two SVs.  Returns -1, 0, or 1 indicating whether the
6733 string in C<sv1> is less than, equal to, or greater than the string in
6734 C<sv2>. Is UTF-8 and 'use bytes' aware, handles get magic, and will
6735 coerce its args to strings if necessary.  See also C<sv_cmp_locale>.
6736
6737 =cut
6738 */
6739
6740 I32
6741 Perl_sv_cmp(pTHX_ register SV *const sv1, register SV *const sv2)
6742 {
6743     dVAR;
6744     STRLEN cur1, cur2;
6745     const char *pv1, *pv2;
6746     char *tpv = NULL;
6747     I32  cmp;
6748     SV *svrecode = NULL;
6749
6750     if (!sv1) {
6751         pv1 = "";
6752         cur1 = 0;
6753     }
6754     else
6755         pv1 = SvPV_const(sv1, cur1);
6756
6757     if (!sv2) {
6758         pv2 = "";
6759         cur2 = 0;
6760     }
6761     else
6762         pv2 = SvPV_const(sv2, cur2);
6763
6764     if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
6765         /* Differing utf8ness.
6766          * Do not UTF8size the comparands as a side-effect. */
6767         if (SvUTF8(sv1)) {
6768             if (PL_encoding) {
6769                  svrecode = newSVpvn(pv2, cur2);
6770                  sv_recode_to_utf8(svrecode, PL_encoding);
6771                  pv2 = SvPV_const(svrecode, cur2);
6772             }
6773             else {
6774                  pv2 = tpv = (char*)bytes_to_utf8((const U8*)pv2, &cur2);
6775             }
6776         }
6777         else {
6778             if (PL_encoding) {
6779                  svrecode = newSVpvn(pv1, cur1);
6780                  sv_recode_to_utf8(svrecode, PL_encoding);
6781                  pv1 = SvPV_const(svrecode, cur1);
6782             }
6783             else {
6784                  pv1 = tpv = (char*)bytes_to_utf8((const U8*)pv1, &cur1);
6785             }
6786         }
6787     }
6788
6789     if (!cur1) {
6790         cmp = cur2 ? -1 : 0;
6791     } else if (!cur2) {
6792         cmp = 1;
6793     } else {
6794         const I32 retval = memcmp((const void*)pv1, (const void*)pv2, cur1 < cur2 ? cur1 : cur2);
6795
6796         if (retval) {
6797             cmp = retval < 0 ? -1 : 1;
6798         } else if (cur1 == cur2) {
6799             cmp = 0;
6800         } else {
6801             cmp = cur1 < cur2 ? -1 : 1;
6802         }
6803     }
6804
6805     SvREFCNT_dec(svrecode);
6806     if (tpv)
6807         Safefree(tpv);
6808
6809     return cmp;
6810 }
6811
6812 /*
6813 =for apidoc sv_cmp_locale
6814
6815 Compares the strings in two SVs in a locale-aware manner. Is UTF-8 and
6816 'use bytes' aware, handles get magic, and will coerce its args to strings
6817 if necessary.  See also C<sv_cmp>.
6818
6819 =cut
6820 */
6821
6822 I32
6823 Perl_sv_cmp_locale(pTHX_ register SV *const sv1, register SV *const sv2)
6824 {
6825     dVAR;
6826 #ifdef USE_LOCALE_COLLATE
6827
6828     char *pv1, *pv2;
6829     STRLEN len1, len2;
6830     I32 retval;
6831
6832     if (PL_collation_standard)
6833         goto raw_compare;
6834
6835     len1 = 0;
6836     pv1 = sv1 ? sv_collxfrm(sv1, &len1) : (char *) NULL;
6837     len2 = 0;
6838     pv2 = sv2 ? sv_collxfrm(sv2, &len2) : (char *) NULL;
6839
6840     if (!pv1 || !len1) {
6841         if (pv2 && len2)
6842             return -1;
6843         else
6844             goto raw_compare;
6845     }
6846     else {
6847         if (!pv2 || !len2)
6848             return 1;
6849     }
6850
6851     retval = memcmp((void*)pv1, (void*)pv2, len1 < len2 ? len1 : len2);
6852
6853     if (retval)
6854         return retval < 0 ? -1 : 1;
6855
6856     /*
6857      * When the result of collation is equality, that doesn't mean
6858      * that there are no differences -- some locales exclude some
6859      * characters from consideration.  So to avoid false equalities,
6860      * we use the raw string as a tiebreaker.
6861      */
6862
6863   raw_compare:
6864     /*FALLTHROUGH*/
6865
6866 #endif /* USE_LOCALE_COLLATE */
6867
6868     return sv_cmp(sv1, sv2);
6869 }
6870
6871
6872 #ifdef USE_LOCALE_COLLATE
6873
6874 /*
6875 =for apidoc sv_collxfrm
6876
6877 Add Collate Transform magic to an SV if it doesn't already have it.
6878
6879 Any scalar variable may carry PERL_MAGIC_collxfrm magic that contains the
6880 scalar data of the variable, but transformed to such a format that a normal
6881 memory comparison can be used to compare the data according to the locale
6882 settings.
6883
6884 =cut
6885 */
6886
6887 char *
6888 Perl_sv_collxfrm(pTHX_ SV *const sv, STRLEN *const nxp)
6889 {
6890     dVAR;
6891     MAGIC *mg;
6892
6893     PERL_ARGS_ASSERT_SV_COLLXFRM;
6894
6895     mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_collxfrm) : (MAGIC *) NULL;
6896     if (!mg || !mg->mg_ptr || *(U32*)mg->mg_ptr != PL_collation_ix) {
6897         const char *s;
6898         char *xf;
6899         STRLEN len, xlen;
6900
6901         if (mg)
6902             Safefree(mg->mg_ptr);
6903         s = SvPV_const(sv, len);
6904         if ((xf = mem_collxfrm(s, len, &xlen))) {
6905             if (! mg) {
6906 #ifdef PERL_OLD_COPY_ON_WRITE
6907                 if (SvIsCOW(sv))
6908                     sv_force_normal_flags(sv, 0);
6909 #endif
6910                 mg = sv_magicext(sv, 0, PERL_MAGIC_collxfrm, &PL_vtbl_collxfrm,
6911                                  0, 0);
6912                 assert(mg);
6913             }
6914             mg->mg_ptr = xf;
6915             mg->mg_len = xlen;
6916         }
6917         else {
6918             if (mg) {
6919                 mg->mg_ptr = NULL;
6920                 mg->mg_len = -1;
6921             }
6922         }
6923     }
6924     if (mg && mg->mg_ptr) {
6925         *nxp = mg->mg_len;
6926         return mg->mg_ptr + sizeof(PL_collation_ix);
6927     }
6928     else {
6929         *nxp = 0;
6930         return NULL;
6931     }
6932 }
6933
6934 #endif /* USE_LOCALE_COLLATE */
6935
6936 /*
6937 =for apidoc sv_gets
6938
6939 Get a line from the filehandle and store it into the SV, optionally
6940 appending to the currently-stored string.
6941
6942 =cut
6943 */
6944
6945 char *
6946 Perl_sv_gets(pTHX_ register SV *const sv, register PerlIO *const fp, I32 append)
6947 {
6948     dVAR;
6949     const char *rsptr;
6950     STRLEN rslen;
6951     register STDCHAR rslast;
6952     register STDCHAR *bp;
6953     register I32 cnt;
6954     I32 i = 0;
6955     I32 rspara = 0;
6956
6957     PERL_ARGS_ASSERT_SV_GETS;
6958
6959     if (SvTHINKFIRST(sv))
6960         sv_force_normal_flags(sv, append ? 0 : SV_COW_DROP_PV);
6961     /* XXX. If you make this PVIV, then copy on write can copy scalars read
6962        from <>.
6963        However, perlbench says it's slower, because the existing swipe code
6964        is faster than copy on write.
6965        Swings and roundabouts.  */
6966     SvUPGRADE(sv, SVt_PV);
6967
6968     SvSCREAM_off(sv);
6969
6970     if (append) {
6971         if (PerlIO_isutf8(fp)) {
6972             if (!SvUTF8(sv)) {
6973                 sv_utf8_upgrade_nomg(sv);
6974                 sv_pos_u2b(sv,&append,0);
6975             }
6976         } else if (SvUTF8(sv)) {
6977             SV * const tsv = newSV(0);
6978             sv_gets(tsv, fp, 0);
6979             sv_utf8_upgrade_nomg(tsv);
6980             SvCUR_set(sv,append);
6981             sv_catsv(sv,tsv);
6982             sv_free(tsv);
6983             goto return_string_or_null;
6984         }
6985     }
6986
6987     SvPOK_only(sv);
6988     if (PerlIO_isutf8(fp))
6989         SvUTF8_on(sv);
6990
6991     if (IN_PERL_COMPILETIME) {
6992         /* we always read code in line mode */
6993         rsptr = "\n";
6994         rslen = 1;
6995     }
6996     else if (RsSNARF(PL_rs)) {
6997         /* If it is a regular disk file use size from stat() as estimate
6998            of amount we are going to read -- may result in mallocing
6999            more memory than we really need if the layers below reduce
7000            the size we read (e.g. CRLF or a gzip layer).
7001          */
7002         Stat_t st;
7003         if (!PerlLIO_fstat(PerlIO_fileno(fp), &st) && S_ISREG(st.st_mode))  {
7004             const Off_t offset = PerlIO_tell(fp);
7005             if (offset != (Off_t) -1 && st.st_size + append > offset) {
7006                 (void) SvGROW(sv, (STRLEN)((st.st_size - offset) + append + 1));
7007             }
7008         }
7009         rsptr = NULL;
7010         rslen = 0;
7011     }
7012     else if (RsRECORD(PL_rs)) {
7013       I32 bytesread;
7014       char *buffer;
7015       U32 recsize;
7016 #ifdef VMS
7017       int fd;
7018 #endif
7019
7020       /* Grab the size of the record we're getting */
7021       recsize = SvUV(SvRV(PL_rs)); /* RsRECORD() guarantees > 0. */
7022       buffer = SvGROW(sv, (STRLEN)(recsize + append + 1)) + append;
7023       /* Go yank in */
7024 #ifdef VMS
7025       /* VMS wants read instead of fread, because fread doesn't respect */
7026       /* RMS record boundaries. This is not necessarily a good thing to be */
7027       /* doing, but we've got no other real choice - except avoid stdio
7028          as implementation - perhaps write a :vms layer ?
7029        */
7030       fd = PerlIO_fileno(fp);
7031       if (fd == -1) { /* in-memory file from PerlIO::Scalar */
7032           bytesread = PerlIO_read(fp, buffer, recsize);
7033       }
7034       else {
7035           bytesread = PerlLIO_read(fd, buffer, recsize);
7036       }
7037 #else
7038       bytesread = PerlIO_read(fp, buffer, recsize);
7039 #endif
7040       if (bytesread < 0)
7041           bytesread = 0;
7042       SvCUR_set(sv, bytesread + append);
7043       buffer[bytesread] = '\0';
7044       goto return_string_or_null;
7045     }
7046     else if (RsPARA(PL_rs)) {
7047         rsptr = "\n\n";
7048         rslen = 2;
7049         rspara = 1;
7050     }
7051     else {
7052         /* Get $/ i.e. PL_rs into same encoding as stream wants */
7053         if (PerlIO_isutf8(fp)) {
7054             rsptr = SvPVutf8(PL_rs, rslen);
7055         }
7056         else {
7057             if (SvUTF8(PL_rs)) {
7058                 if (!sv_utf8_downgrade(PL_rs, TRUE)) {
7059                     Perl_croak(aTHX_ "Wide character in $/");
7060                 }
7061             }
7062             rsptr = SvPV_const(PL_rs, rslen);
7063         }
7064     }
7065
7066     rslast = rslen ? rsptr[rslen - 1] : '\0';
7067
7068     if (rspara) {               /* have to do this both before and after */
7069         do {                    /* to make sure file boundaries work right */
7070             if (PerlIO_eof(fp))
7071                 return 0;
7072             i = PerlIO_getc(fp);
7073             if (i != '\n') {
7074                 if (i == -1)
7075                     return 0;
7076                 PerlIO_ungetc(fp,i);
7077                 break;
7078             }
7079         } while (i != EOF);
7080     }
7081
7082     /* See if we know enough about I/O mechanism to cheat it ! */
7083
7084     /* This used to be #ifdef test - it is made run-time test for ease
7085        of abstracting out stdio interface. One call should be cheap
7086        enough here - and may even be a macro allowing compile
7087        time optimization.
7088      */
7089
7090     if (PerlIO_fast_gets(fp)) {
7091
7092     /*
7093      * We're going to steal some values from the stdio struct
7094      * and put EVERYTHING in the innermost loop into registers.
7095      */
7096     register STDCHAR *ptr;
7097     STRLEN bpx;
7098     I32 shortbuffered;
7099
7100 #if defined(VMS) && defined(PERLIO_IS_STDIO)
7101     /* An ungetc()d char is handled separately from the regular
7102      * buffer, so we getc() it back out and stuff it in the buffer.
7103      */
7104     i = PerlIO_getc(fp);
7105     if (i == EOF) return 0;
7106     *(--((*fp)->_ptr)) = (unsigned char) i;
7107     (*fp)->_cnt++;
7108 #endif
7109
7110     /* Here is some breathtakingly efficient cheating */
7111
7112     cnt = PerlIO_get_cnt(fp);                   /* get count into register */
7113     /* make sure we have the room */
7114     if ((I32)(SvLEN(sv) - append) <= cnt + 1) {
7115         /* Not room for all of it
7116            if we are looking for a separator and room for some
7117          */
7118         if (rslen && cnt > 80 && (I32)SvLEN(sv) > append) {
7119             /* just process what we have room for */
7120             shortbuffered = cnt - SvLEN(sv) + append + 1;
7121             cnt -= shortbuffered;
7122         }
7123         else {
7124             shortbuffered = 0;
7125             /* remember that cnt can be negative */
7126             SvGROW(sv, (STRLEN)(append + (cnt <= 0 ? 2 : (cnt + 1))));
7127         }
7128     }
7129     else
7130         shortbuffered = 0;
7131     bp = (STDCHAR*)SvPVX_const(sv) + append;  /* move these two too to registers */
7132     ptr = (STDCHAR*)PerlIO_get_ptr(fp);
7133     DEBUG_P(PerlIO_printf(Perl_debug_log,
7134         "Screamer: entering, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
7135     DEBUG_P(PerlIO_printf(Perl_debug_log,
7136         "Screamer: entering: PerlIO * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
7137                PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
7138                PTR2UV(PerlIO_has_base(fp) ? PerlIO_get_base(fp) : 0)));
7139     for (;;) {
7140       screamer:
7141         if (cnt > 0) {
7142             if (rslen) {
7143                 while (cnt > 0) {                    /* this     |  eat */
7144                     cnt--;
7145                     if ((*bp++ = *ptr++) == rslast)  /* really   |  dust */
7146                         goto thats_all_folks;        /* screams  |  sed :-) */
7147                 }
7148             }
7149             else {
7150                 Copy(ptr, bp, cnt, char);            /* this     |  eat */
7151                 bp += cnt;                           /* screams  |  dust */
7152                 ptr += cnt;                          /* louder   |  sed :-) */
7153                 cnt = 0;
7154             }
7155         }
7156         
7157         if (shortbuffered) {            /* oh well, must extend */
7158             cnt = shortbuffered;
7159             shortbuffered = 0;
7160             bpx = bp - (STDCHAR*)SvPVX_const(sv); /* box up before relocation */
7161             SvCUR_set(sv, bpx);
7162             SvGROW(sv, SvLEN(sv) + append + cnt + 2);
7163             bp = (STDCHAR*)SvPVX_const(sv) + bpx; /* unbox after relocation */
7164             continue;
7165         }
7166
7167         DEBUG_P(PerlIO_printf(Perl_debug_log,
7168                               "Screamer: going to getc, ptr=%"UVuf", cnt=%ld\n",
7169                               PTR2UV(ptr),(long)cnt));
7170         PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt); /* deregisterize cnt and ptr */
7171 #if 0
7172         DEBUG_P(PerlIO_printf(Perl_debug_log,
7173             "Screamer: pre: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
7174             PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
7175             PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
7176 #endif
7177         /* This used to call 'filbuf' in stdio form, but as that behaves like
7178            getc when cnt <= 0 we use PerlIO_getc here to avoid introducing
7179            another abstraction.  */
7180         i   = PerlIO_getc(fp);          /* get more characters */
7181 #if 0
7182         DEBUG_P(PerlIO_printf(Perl_debug_log,
7183             "Screamer: post: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
7184             PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
7185             PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
7186 #endif
7187         cnt = PerlIO_get_cnt(fp);
7188         ptr = (STDCHAR*)PerlIO_get_ptr(fp);     /* reregisterize cnt and ptr */
7189         DEBUG_P(PerlIO_printf(Perl_debug_log,
7190             "Screamer: after getc, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
7191
7192         if (i == EOF)                   /* all done for ever? */
7193             goto thats_really_all_folks;
7194
7195         bpx = bp - (STDCHAR*)SvPVX_const(sv);   /* box up before relocation */
7196         SvCUR_set(sv, bpx);
7197         SvGROW(sv, bpx + cnt + 2);
7198         bp = (STDCHAR*)SvPVX_const(sv) + bpx;   /* unbox after relocation */
7199
7200         *bp++ = (STDCHAR)i;             /* store character from PerlIO_getc */
7201
7202         if (rslen && (STDCHAR)i == rslast)  /* all done for now? */
7203             goto thats_all_folks;
7204     }
7205
7206 thats_all_folks:
7207     if ((rslen > 1 && (STRLEN)(bp - (STDCHAR*)SvPVX_const(sv)) < rslen) ||
7208           memNE((char*)bp - rslen, rsptr, rslen))
7209         goto screamer;                          /* go back to the fray */
7210 thats_really_all_folks:
7211     if (shortbuffered)
7212         cnt += shortbuffered;
7213         DEBUG_P(PerlIO_printf(Perl_debug_log,
7214             "Screamer: quitting, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
7215     PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt);  /* put these back or we're in trouble */
7216     DEBUG_P(PerlIO_printf(Perl_debug_log,
7217         "Screamer: end: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
7218         PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
7219         PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
7220     *bp = '\0';
7221     SvCUR_set(sv, bp - (STDCHAR*)SvPVX_const(sv));      /* set length */
7222     DEBUG_P(PerlIO_printf(Perl_debug_log,
7223         "Screamer: done, len=%ld, string=|%.*s|\n",
7224         (long)SvCUR(sv),(int)SvCUR(sv),SvPVX_const(sv)));
7225     }
7226    else
7227     {
7228        /*The big, slow, and stupid way. */
7229 #ifdef USE_HEAP_INSTEAD_OF_STACK        /* Even slower way. */
7230         STDCHAR *buf = NULL;
7231         Newx(buf, 8192, STDCHAR);
7232         assert(buf);
7233 #else
7234         STDCHAR buf[8192];
7235 #endif
7236
7237 screamer2:
7238         if (rslen) {
7239             register const STDCHAR * const bpe = buf + sizeof(buf);
7240             bp = buf;
7241             while ((i = PerlIO_getc(fp)) != EOF && (*bp++ = (STDCHAR)i) != rslast && bp < bpe)
7242                 ; /* keep reading */
7243             cnt = bp - buf;
7244         }
7245         else {
7246             cnt = PerlIO_read(fp,(char*)buf, sizeof(buf));
7247             /* Accomodate broken VAXC compiler, which applies U8 cast to
7248              * both args of ?: operator, causing EOF to change into 255
7249              */
7250             if (cnt > 0)
7251                  i = (U8)buf[cnt - 1];
7252             else
7253                  i = EOF;
7254         }
7255
7256         if (cnt < 0)
7257             cnt = 0;  /* we do need to re-set the sv even when cnt <= 0 */
7258         if (append)
7259              sv_catpvn(sv, (char *) buf, cnt);
7260         else
7261              sv_setpvn(sv, (char *) buf, cnt);
7262
7263         if (i != EOF &&                 /* joy */
7264             (!rslen ||
7265              SvCUR(sv) < rslen ||
7266              memNE(SvPVX_const(sv) + SvCUR(sv) - rslen, rsptr, rslen)))
7267         {
7268             append = -1;
7269             /*
7270              * If we're reading from a TTY and we get a short read,
7271              * indicating that the user hit his EOF character, we need
7272              * to notice it now, because if we try to read from the TTY
7273              * again, the EOF condition will disappear.
7274              *
7275              * The comparison of cnt to sizeof(buf) is an optimization
7276              * that prevents unnecessary calls to feof().
7277              *
7278              * - jik 9/25/96
7279              */
7280             if (!(cnt < (I32)sizeof(buf) && PerlIO_eof(fp)))
7281                 goto screamer2;
7282         }
7283
7284 #ifdef USE_HEAP_INSTEAD_OF_STACK
7285         Safefree(buf);
7286 #endif
7287     }
7288
7289     if (rspara) {               /* have to do this both before and after */
7290         while (i != EOF) {      /* to make sure file boundaries work right */
7291             i = PerlIO_getc(fp);
7292             if (i != '\n') {
7293                 PerlIO_ungetc(fp,i);
7294                 break;
7295             }
7296         }
7297     }
7298
7299 return_string_or_null:
7300     return (SvCUR(sv) - append) ? SvPVX(sv) : NULL;
7301 }
7302
7303 /*
7304 =for apidoc sv_inc
7305
7306 Auto-increment of the value in the SV, doing string to numeric conversion
7307 if necessary. Handles 'get' magic.
7308
7309 =cut
7310 */
7311
7312 void
7313 Perl_sv_inc(pTHX_ register SV *const sv)
7314 {
7315     dVAR;
7316     register char *d;
7317     int flags;
7318
7319     if (!sv)
7320         return;
7321     SvGETMAGIC(sv);
7322     if (SvTHINKFIRST(sv)) {
7323         if (SvIsCOW(sv))
7324             sv_force_normal_flags(sv, 0);
7325         if (SvREADONLY(sv)) {
7326             if (IN_PERL_RUNTIME)
7327                 Perl_croak(aTHX_ "%s", PL_no_modify);
7328         }
7329         if (SvROK(sv)) {
7330             IV i;
7331             if (SvAMAGIC(sv) && AMG_CALLun(sv,inc))
7332                 return;
7333             i = PTR2IV(SvRV(sv));
7334             sv_unref(sv);
7335             sv_setiv(sv, i);
7336         }
7337     }
7338     flags = SvFLAGS(sv);
7339     if ((flags & (SVp_NOK|SVp_IOK)) == SVp_NOK) {
7340         /* It's (privately or publicly) a float, but not tested as an
7341            integer, so test it to see. */
7342         (void) SvIV(sv);
7343         flags = SvFLAGS(sv);
7344     }
7345     if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
7346         /* It's publicly an integer, or privately an integer-not-float */
7347 #ifdef PERL_PRESERVE_IVUV
7348       oops_its_int:
7349 #endif
7350         if (SvIsUV(sv)) {
7351             if (SvUVX(sv) == UV_MAX)
7352                 sv_setnv(sv, UV_MAX_P1);
7353             else
7354                 (void)SvIOK_only_UV(sv);
7355                 SvUV_set(sv, SvUVX(sv) + 1);
7356         } else {
7357             if (SvIVX(sv) == IV_MAX)
7358                 sv_setuv(sv, (UV)IV_MAX + 1);
7359             else {
7360                 (void)SvIOK_only(sv);
7361                 SvIV_set(sv, SvIVX(sv) + 1);
7362             }   
7363         }
7364         return;
7365     }
7366     if (flags & SVp_NOK) {
7367         const NV was = SvNVX(sv);
7368         if (NV_OVERFLOWS_INTEGERS_AT &&
7369             was >= NV_OVERFLOWS_INTEGERS_AT) {
7370             Perl_ck_warner(aTHX_ packWARN(WARN_IMPRECISION),
7371                            "Lost precision when incrementing %" NVff " by 1",
7372                            was);
7373         }
7374         (void)SvNOK_only(sv);
7375         SvNV_set(sv, was + 1.0);
7376         return;
7377     }
7378
7379     if (!(flags & SVp_POK) || !*SvPVX_const(sv)) {
7380         if ((flags & SVTYPEMASK) < SVt_PVIV)
7381             sv_upgrade(sv, ((flags & SVTYPEMASK) > SVt_IV ? SVt_PVIV : SVt_IV));
7382         (void)SvIOK_only(sv);
7383         SvIV_set(sv, 1);
7384         return;
7385     }
7386     d = SvPVX(sv);
7387     while (isALPHA(*d)) d++;
7388     while (isDIGIT(*d)) d++;
7389     if (d < SvEND(sv)) {
7390 #ifdef PERL_PRESERVE_IVUV
7391         /* Got to punt this as an integer if needs be, but we don't issue
7392            warnings. Probably ought to make the sv_iv_please() that does
7393            the conversion if possible, and silently.  */
7394         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), NULL);
7395         if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
7396             /* Need to try really hard to see if it's an integer.
7397                9.22337203685478e+18 is an integer.
7398                but "9.22337203685478e+18" + 0 is UV=9223372036854779904
7399                so $a="9.22337203685478e+18"; $a+0; $a++
7400                needs to be the same as $a="9.22337203685478e+18"; $a++
7401                or we go insane. */
7402         
7403             (void) sv_2iv(sv);
7404             if (SvIOK(sv))
7405                 goto oops_its_int;
7406
7407             /* sv_2iv *should* have made this an NV */
7408             if (flags & SVp_NOK) {
7409                 (void)SvNOK_only(sv);
7410                 SvNV_set(sv, SvNVX(sv) + 1.0);
7411                 return;
7412             }
7413             /* I don't think we can get here. Maybe I should assert this
7414                And if we do get here I suspect that sv_setnv will croak. NWC
7415                Fall through. */
7416 #if defined(USE_LONG_DOUBLE)
7417             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",
7418                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
7419 #else
7420             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_inc punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
7421                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
7422 #endif
7423         }
7424 #endif /* PERL_PRESERVE_IVUV */
7425         sv_setnv(sv,Atof(SvPVX_const(sv)) + 1.0);
7426         return;
7427     }
7428     d--;
7429     while (d >= SvPVX_const(sv)) {
7430         if (isDIGIT(*d)) {
7431             if (++*d <= '9')
7432                 return;
7433             *(d--) = '0';
7434         }
7435         else {
7436 #ifdef EBCDIC
7437             /* MKS: The original code here died if letters weren't consecutive.
7438              * at least it didn't have to worry about non-C locales.  The
7439              * new code assumes that ('z'-'a')==('Z'-'A'), letters are
7440              * arranged in order (although not consecutively) and that only
7441              * [A-Za-z] are accepted by isALPHA in the C locale.
7442              */
7443             if (*d != 'z' && *d != 'Z') {
7444                 do { ++*d; } while (!isALPHA(*d));
7445                 return;
7446             }
7447             *(d--) -= 'z' - 'a';
7448 #else
7449             ++*d;
7450             if (isALPHA(*d))
7451                 return;
7452             *(d--) -= 'z' - 'a' + 1;
7453 #endif
7454         }
7455     }
7456     /* oh,oh, the number grew */
7457     SvGROW(sv, SvCUR(sv) + 2);
7458     SvCUR_set(sv, SvCUR(sv) + 1);
7459     for (d = SvPVX(sv) + SvCUR(sv); d > SvPVX_const(sv); d--)
7460         *d = d[-1];
7461     if (isDIGIT(d[1]))
7462         *d = '1';
7463     else
7464         *d = d[1];
7465 }
7466
7467 /*
7468 =for apidoc sv_dec
7469
7470 Auto-decrement of the value in the SV, doing string to numeric conversion
7471 if necessary. Handles 'get' magic.
7472
7473 =cut
7474 */
7475
7476 void
7477 Perl_sv_dec(pTHX_ register SV *const sv)
7478 {
7479     dVAR;
7480     int flags;
7481
7482     if (!sv)
7483         return;
7484     SvGETMAGIC(sv);
7485     if (SvTHINKFIRST(sv)) {
7486         if (SvIsCOW(sv))
7487             sv_force_normal_flags(sv, 0);
7488         if (SvREADONLY(sv)) {
7489             if (IN_PERL_RUNTIME)
7490                 Perl_croak(aTHX_ "%s", PL_no_modify);
7491         }
7492         if (SvROK(sv)) {
7493             IV i;
7494             if (SvAMAGIC(sv) && AMG_CALLun(sv,dec))
7495                 return;
7496             i = PTR2IV(SvRV(sv));
7497             sv_unref(sv);
7498             sv_setiv(sv, i);
7499         }
7500     }
7501     /* Unlike sv_inc we don't have to worry about string-never-numbers
7502        and keeping them magic. But we mustn't warn on punting */
7503     flags = SvFLAGS(sv);
7504     if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
7505         /* It's publicly an integer, or privately an integer-not-float */
7506 #ifdef PERL_PRESERVE_IVUV
7507       oops_its_int:
7508 #endif
7509         if (SvIsUV(sv)) {
7510             if (SvUVX(sv) == 0) {
7511                 (void)SvIOK_only(sv);
7512                 SvIV_set(sv, -1);
7513             }
7514             else {
7515                 (void)SvIOK_only_UV(sv);
7516                 SvUV_set(sv, SvUVX(sv) - 1);
7517             }   
7518         } else {
7519             if (SvIVX(sv) == IV_MIN) {
7520                 sv_setnv(sv, (NV)IV_MIN);
7521                 goto oops_its_num;
7522             }
7523             else {
7524                 (void)SvIOK_only(sv);
7525                 SvIV_set(sv, SvIVX(sv) - 1);
7526             }   
7527         }
7528         return;
7529     }
7530     if (flags & SVp_NOK) {
7531     oops_its_num:
7532         {
7533             const NV was = SvNVX(sv);
7534             if (NV_OVERFLOWS_INTEGERS_AT &&
7535                 was <= -NV_OVERFLOWS_INTEGERS_AT) {
7536                 Perl_ck_warner(aTHX_ packWARN(WARN_IMPRECISION),
7537                                "Lost precision when decrementing %" NVff " by 1",
7538                                was);
7539             }
7540             (void)SvNOK_only(sv);
7541             SvNV_set(sv, was - 1.0);
7542             return;
7543         }
7544     }
7545     if (!(flags & SVp_POK)) {
7546         if ((flags & SVTYPEMASK) < SVt_PVIV)
7547             sv_upgrade(sv, ((flags & SVTYPEMASK) > SVt_IV) ? SVt_PVIV : SVt_IV);
7548         SvIV_set(sv, -1);
7549         (void)SvIOK_only(sv);
7550         return;
7551     }
7552 #ifdef PERL_PRESERVE_IVUV
7553     {
7554         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), NULL);
7555         if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
7556             /* Need to try really hard to see if it's an integer.
7557                9.22337203685478e+18 is an integer.
7558                but "9.22337203685478e+18" + 0 is UV=9223372036854779904
7559                so $a="9.22337203685478e+18"; $a+0; $a--
7560                needs to be the same as $a="9.22337203685478e+18"; $a--
7561                or we go insane. */
7562         
7563             (void) sv_2iv(sv);
7564             if (SvIOK(sv))
7565                 goto oops_its_int;
7566
7567             /* sv_2iv *should* have made this an NV */
7568             if (flags & SVp_NOK) {
7569                 (void)SvNOK_only(sv);
7570                 SvNV_set(sv, SvNVX(sv) - 1.0);
7571                 return;
7572             }
7573             /* I don't think we can get here. Maybe I should assert this
7574                And if we do get here I suspect that sv_setnv will croak. NWC
7575                Fall through. */
7576 #if defined(USE_LONG_DOUBLE)
7577             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",
7578                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
7579 #else
7580             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_dec punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
7581                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
7582 #endif
7583         }
7584     }
7585 #endif /* PERL_PRESERVE_IVUV */
7586     sv_setnv(sv,Atof(SvPVX_const(sv)) - 1.0);   /* punt */
7587 }
7588
7589 /* this define is used to eliminate a chunk of duplicated but shared logic
7590  * it has the suffix __SV_C to signal that it isnt API, and isnt meant to be
7591  * used anywhere but here - yves
7592  */
7593 #define PUSH_EXTEND_MORTAL__SV_C(AnSv) \
7594     STMT_START {      \
7595         EXTEND_MORTAL(1); \
7596         PL_tmps_stack[++PL_tmps_ix] = (AnSv); \
7597     } STMT_END
7598
7599 /*
7600 =for apidoc sv_mortalcopy
7601
7602 Creates a new SV which is a copy of the original SV (using C<sv_setsv>).
7603 The new SV is marked as mortal. It will be destroyed "soon", either by an
7604 explicit call to FREETMPS, or by an implicit call at places such as
7605 statement boundaries.  See also C<sv_newmortal> and C<sv_2mortal>.
7606
7607 =cut
7608 */
7609
7610 /* Make a string that will exist for the duration of the expression
7611  * evaluation.  Actually, it may have to last longer than that, but
7612  * hopefully we won't free it until it has been assigned to a
7613  * permanent location. */
7614
7615 SV *
7616 Perl_sv_mortalcopy(pTHX_ SV *const oldstr)
7617 {
7618     dVAR;
7619     register SV *sv;
7620
7621     new_SV(sv);
7622     sv_setsv(sv,oldstr);
7623     PUSH_EXTEND_MORTAL__SV_C(sv);
7624     SvTEMP_on(sv);
7625     return sv;
7626 }
7627
7628 /*
7629 =for apidoc sv_newmortal
7630
7631 Creates a new null SV which is mortal.  The reference count of the SV is
7632 set to 1. It will be destroyed "soon", either by an explicit call to
7633 FREETMPS, or by an implicit call at places such as statement boundaries.
7634 See also C<sv_mortalcopy> and C<sv_2mortal>.
7635
7636 =cut
7637 */
7638
7639 SV *
7640 Perl_sv_newmortal(pTHX)
7641 {
7642     dVAR;
7643     register SV *sv;
7644
7645     new_SV(sv);
7646     SvFLAGS(sv) = SVs_TEMP;
7647     PUSH_EXTEND_MORTAL__SV_C(sv);
7648     return sv;
7649 }
7650
7651
7652 /*
7653 =for apidoc newSVpvn_flags
7654
7655 Creates a new SV and copies a string into it.  The reference count for the
7656 SV is set to 1.  Note that if C<len> is zero, Perl will create a zero length
7657 string.  You are responsible for ensuring that the source string is at least
7658 C<len> bytes long.  If the C<s> argument is NULL the new SV will be undefined.
7659 Currently the only flag bits accepted are C<SVf_UTF8> and C<SVs_TEMP>.
7660 If C<SVs_TEMP> is set, then C<sv2mortal()> is called on the result before
7661 returning. If C<SVf_UTF8> is set, C<s> is considered to be in UTF-8 and the
7662 C<SVf_UTF8> flag will be set on the new SV.
7663 C<newSVpvn_utf8()> is a convenience wrapper for this function, defined as
7664
7665     #define newSVpvn_utf8(s, len, u)                    \
7666         newSVpvn_flags((s), (len), (u) ? SVf_UTF8 : 0)
7667
7668 =cut
7669 */
7670
7671 SV *
7672 Perl_newSVpvn_flags(pTHX_ const char *const s, const STRLEN len, const U32 flags)
7673 {
7674     dVAR;
7675     register SV *sv;
7676
7677     /* All the flags we don't support must be zero.
7678        And we're new code so I'm going to assert this from the start.  */
7679     assert(!(flags & ~(SVf_UTF8|SVs_TEMP)));
7680     new_SV(sv);
7681     sv_setpvn(sv,s,len);
7682
7683     /* This code used to a sv_2mortal(), however we now unroll the call to sv_2mortal()
7684      * and do what it does outselves here.
7685      * Since we have asserted that flags can only have the SVf_UTF8 and/or SVs_TEMP flags
7686      * set above we can use it to enable the sv flags directly (bypassing SvTEMP_on), which
7687      * in turn means we dont need to mask out the SVf_UTF8 flag below, which means that we
7688      * eleminate quite a few steps than it looks - Yves (explaining patch by gfx)
7689      */
7690
7691     SvFLAGS(sv) |= flags;
7692
7693     if(flags & SVs_TEMP){
7694         PUSH_EXTEND_MORTAL__SV_C(sv);
7695     }
7696
7697     return sv;
7698 }
7699
7700 /*
7701 =for apidoc sv_2mortal
7702
7703 Marks an existing SV as mortal.  The SV will be destroyed "soon", either
7704 by an explicit call to FREETMPS, or by an implicit call at places such as
7705 statement boundaries.  SvTEMP() is turned on which means that the SV's
7706 string buffer can be "stolen" if this SV is copied. See also C<sv_newmortal>
7707 and C<sv_mortalcopy>.
7708
7709 =cut
7710 */
7711
7712 SV *
7713 Perl_sv_2mortal(pTHX_ register SV *const sv)
7714 {
7715     dVAR;
7716     if (!sv)
7717         return NULL;
7718     if (SvREADONLY(sv) && SvIMMORTAL(sv))
7719         return sv;
7720     PUSH_EXTEND_MORTAL__SV_C(sv);
7721     SvTEMP_on(sv);
7722     return sv;
7723 }
7724
7725 /*
7726 =for apidoc newSVpv
7727
7728 Creates a new SV and copies a string into it.  The reference count for the
7729 SV is set to 1.  If C<len> is zero, Perl will compute the length using
7730 strlen().  For efficiency, consider using C<newSVpvn> instead.
7731
7732 =cut
7733 */
7734
7735 SV *
7736 Perl_newSVpv(pTHX_ const char *const s, const STRLEN len)
7737 {
7738     dVAR;
7739     register SV *sv;
7740
7741     new_SV(sv);
7742     sv_setpvn(sv, s, len || s == NULL ? len : strlen(s));
7743     return sv;
7744 }
7745
7746 /*
7747 =for apidoc newSVpvn
7748
7749 Creates a new SV and copies a string into it.  The reference count for the
7750 SV is set to 1.  Note that if C<len> is zero, Perl will create a zero length
7751 string.  You are responsible for ensuring that the source string is at least
7752 C<len> bytes long.  If the C<s> argument is NULL the new SV will be undefined.
7753
7754 =cut
7755 */
7756
7757 SV *
7758 Perl_newSVpvn(pTHX_ const char *const s, const STRLEN len)
7759 {
7760     dVAR;
7761     register SV *sv;
7762
7763     new_SV(sv);
7764     sv_setpvn(sv,s,len);
7765     return sv;
7766 }
7767
7768 /*
7769 =for apidoc newSVhek
7770
7771 Creates a new SV from the hash key structure.  It will generate scalars that
7772 point to the shared string table where possible. Returns a new (undefined)
7773 SV if the hek is NULL.
7774
7775 =cut
7776 */
7777
7778 SV *
7779 Perl_newSVhek(pTHX_ const HEK *const hek)
7780 {
7781     dVAR;
7782     if (!hek) {
7783         SV *sv;
7784
7785         new_SV(sv);
7786         return sv;
7787     }
7788
7789     if (HEK_LEN(hek) == HEf_SVKEY) {
7790         return newSVsv(*(SV**)HEK_KEY(hek));
7791     } else {
7792         const int flags = HEK_FLAGS(hek);
7793         if (flags & HVhek_WASUTF8) {
7794             /* Trouble :-)
7795                Andreas would like keys he put in as utf8 to come back as utf8
7796             */
7797             STRLEN utf8_len = HEK_LEN(hek);
7798             const U8 *as_utf8 = bytes_to_utf8 ((U8*)HEK_KEY(hek), &utf8_len);
7799             SV * const sv = newSVpvn ((const char*)as_utf8, utf8_len);
7800
7801             SvUTF8_on (sv);
7802             Safefree (as_utf8); /* bytes_to_utf8() allocates a new string */
7803             return sv;
7804         } else if (flags & (HVhek_REHASH|HVhek_UNSHARED)) {
7805             /* We don't have a pointer to the hv, so we have to replicate the
7806                flag into every HEK. This hv is using custom a hasing
7807                algorithm. Hence we can't return a shared string scalar, as
7808                that would contain the (wrong) hash value, and might get passed
7809                into an hv routine with a regular hash.
7810                Similarly, a hash that isn't using shared hash keys has to have
7811                the flag in every key so that we know not to try to call
7812                share_hek_kek on it.  */
7813
7814             SV * const sv = newSVpvn (HEK_KEY(hek), HEK_LEN(hek));
7815             if (HEK_UTF8(hek))
7816                 SvUTF8_on (sv);
7817             return sv;
7818         }
7819         /* This will be overwhelminly the most common case.  */
7820         {
7821             /* Inline most of newSVpvn_share(), because share_hek_hek() is far
7822                more efficient than sharepvn().  */
7823             SV *sv;
7824
7825             new_SV(sv);
7826             sv_upgrade(sv, SVt_PV);
7827             SvPV_set(sv, (char *)HEK_KEY(share_hek_hek(hek)));
7828             SvCUR_set(sv, HEK_LEN(hek));
7829             SvLEN_set(sv, 0);
7830             SvREADONLY_on(sv);
7831             SvFAKE_on(sv);
7832             SvPOK_on(sv);
7833             if (HEK_UTF8(hek))
7834                 SvUTF8_on(sv);
7835             return sv;
7836         }
7837     }
7838 }
7839
7840 /*
7841 =for apidoc newSVpvn_share
7842
7843 Creates a new SV with its SvPVX_const pointing to a shared string in the string
7844 table. If the string does not already exist in the table, it is created
7845 first.  Turns on READONLY and FAKE. If the C<hash> parameter is non-zero, that
7846 value is used; otherwise the hash is computed. The string's hash can be later
7847 be retrieved from the SV with the C<SvSHARED_HASH()> macro. The idea here is
7848 that as the string table is used for shared hash keys these strings will have
7849 SvPVX_const == HeKEY and hash lookup will avoid string compare.
7850
7851 =cut
7852 */
7853
7854 SV *
7855 Perl_newSVpvn_share(pTHX_ const char *src, I32 len, U32 hash)
7856 {
7857     dVAR;
7858     register SV *sv;
7859     bool is_utf8 = FALSE;
7860     const char *const orig_src = src;
7861
7862     if (len < 0) {
7863         STRLEN tmplen = -len;
7864         is_utf8 = TRUE;
7865         /* See the note in hv.c:hv_fetch() --jhi */
7866         src = (char*)bytes_from_utf8((const U8*)src, &tmplen, &is_utf8);
7867         len = tmplen;
7868     }
7869     if (!hash)
7870         PERL_HASH(hash, src, len);
7871     new_SV(sv);
7872     /* The logic for this is inlined in S_mro_get_linear_isa_dfs(), so if it
7873        changes here, update it there too.  */
7874     sv_upgrade(sv, SVt_PV);
7875     SvPV_set(sv, sharepvn(src, is_utf8?-len:len, hash));
7876     SvCUR_set(sv, len);
7877     SvLEN_set(sv, 0);
7878     SvREADONLY_on(sv);
7879     SvFAKE_on(sv);
7880     SvPOK_on(sv);
7881     if (is_utf8)
7882         SvUTF8_on(sv);
7883     if (src != orig_src)
7884         Safefree(src);
7885     return sv;
7886 }
7887
7888
7889 #if defined(PERL_IMPLICIT_CONTEXT)
7890
7891 /* pTHX_ magic can't cope with varargs, so this is a no-context
7892  * version of the main function, (which may itself be aliased to us).
7893  * Don't access this version directly.
7894  */
7895
7896 SV *
7897 Perl_newSVpvf_nocontext(const char *const pat, ...)
7898 {
7899     dTHX;
7900     register SV *sv;
7901     va_list args;
7902
7903     PERL_ARGS_ASSERT_NEWSVPVF_NOCONTEXT;
7904
7905     va_start(args, pat);
7906     sv = vnewSVpvf(pat, &args);
7907     va_end(args);
7908     return sv;
7909 }
7910 #endif
7911
7912 /*
7913 =for apidoc newSVpvf
7914
7915 Creates a new SV and initializes it with the string formatted like
7916 C<sprintf>.
7917
7918 =cut
7919 */
7920
7921 SV *
7922 Perl_newSVpvf(pTHX_ const char *const pat, ...)
7923 {
7924     register SV *sv;
7925     va_list args;
7926
7927     PERL_ARGS_ASSERT_NEWSVPVF;
7928
7929     va_start(args, pat);
7930     sv = vnewSVpvf(pat, &args);
7931     va_end(args);
7932     return sv;
7933 }
7934
7935 /* backend for newSVpvf() and newSVpvf_nocontext() */
7936
7937 SV *
7938 Perl_vnewSVpvf(pTHX_ const char *const pat, va_list *const args)
7939 {
7940     dVAR;
7941     register SV *sv;
7942
7943     PERL_ARGS_ASSERT_VNEWSVPVF;
7944
7945     new_SV(sv);
7946     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
7947     return sv;
7948 }
7949
7950 /*
7951 =for apidoc newSVnv
7952
7953 Creates a new SV and copies a floating point value into it.
7954 The reference count for the SV is set to 1.
7955
7956 =cut
7957 */
7958
7959 SV *
7960 Perl_newSVnv(pTHX_ const NV n)
7961 {
7962     dVAR;
7963     register SV *sv;
7964
7965     new_SV(sv);
7966     sv_setnv(sv,n);
7967     return sv;
7968 }
7969
7970 /*
7971 =for apidoc newSViv
7972
7973 Creates a new SV and copies an integer into it.  The reference count for the
7974 SV is set to 1.
7975
7976 =cut
7977 */
7978
7979 SV *
7980 Perl_newSViv(pTHX_ const IV i)
7981 {
7982     dVAR;
7983     register SV *sv;
7984
7985     new_SV(sv);
7986     sv_setiv(sv,i);
7987     return sv;
7988 }
7989
7990 /*
7991 =for apidoc newSVuv
7992
7993 Creates a new SV and copies an unsigned integer into it.
7994 The reference count for the SV is set to 1.
7995
7996 =cut
7997 */
7998
7999 SV *
8000 Perl_newSVuv(pTHX_ const UV u)
8001 {
8002     dVAR;
8003     register SV *sv;
8004
8005     new_SV(sv);
8006     sv_setuv(sv,u);
8007     return sv;
8008 }
8009
8010 /*
8011 =for apidoc newSV_type
8012
8013 Creates a new SV, of the type specified.  The reference count for the new SV
8014 is set to 1.
8015
8016 =cut
8017 */
8018
8019 SV *
8020 Perl_newSV_type(pTHX_ const svtype type)
8021 {
8022     register SV *sv;
8023
8024     new_SV(sv);
8025     sv_upgrade(sv, type);
8026     return sv;
8027 }
8028
8029 /*
8030 =for apidoc newRV_noinc
8031
8032 Creates an RV wrapper for an SV.  The reference count for the original
8033 SV is B<not> incremented.
8034
8035 =cut
8036 */
8037
8038 SV *
8039 Perl_newRV_noinc(pTHX_ SV *const tmpRef)
8040 {
8041     dVAR;
8042     register SV *sv = newSV_type(SVt_IV);
8043
8044     PERL_ARGS_ASSERT_NEWRV_NOINC;
8045
8046     SvTEMP_off(tmpRef);
8047     SvRV_set(sv, tmpRef);
8048     SvROK_on(sv);
8049     return sv;
8050 }
8051
8052 /* newRV_inc is the official function name to use now.
8053  * newRV_inc is in fact #defined to newRV in sv.h
8054  */
8055
8056 SV *
8057 Perl_newRV(pTHX_ SV *const sv)
8058 {
8059     dVAR;
8060
8061     PERL_ARGS_ASSERT_NEWRV;
8062
8063     return newRV_noinc(SvREFCNT_inc_simple_NN(sv));
8064 }
8065
8066 /*
8067 =for apidoc newSVsv
8068
8069 Creates a new SV which is an exact duplicate of the original SV.
8070 (Uses C<sv_setsv>).
8071
8072 =cut
8073 */
8074
8075 SV *
8076 Perl_newSVsv(pTHX_ register SV *const old)
8077 {
8078     dVAR;
8079     register SV *sv;
8080
8081     if (!old)
8082         return NULL;
8083     if (SvTYPE(old) == SVTYPEMASK) {
8084         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "semi-panic: attempt to dup freed string");
8085         return NULL;
8086     }
8087     new_SV(sv);
8088     /* SV_GMAGIC is the default for sv_setv()
8089        SV_NOSTEAL prevents TEMP buffers being, well, stolen, and saves games
8090        with SvTEMP_off and SvTEMP_on round a call to sv_setsv.  */
8091     sv_setsv_flags(sv, old, SV_GMAGIC | SV_NOSTEAL);
8092     return sv;
8093 }
8094
8095 /*
8096 =for apidoc sv_reset
8097
8098 Underlying implementation for the C<reset> Perl function.
8099 Note that the perl-level function is vaguely deprecated.
8100
8101 =cut
8102 */
8103
8104 void
8105 Perl_sv_reset(pTHX_ register const char *s, HV *const stash)
8106 {
8107     dVAR;
8108     char todo[PERL_UCHAR_MAX+1];
8109
8110     PERL_ARGS_ASSERT_SV_RESET;
8111
8112     if (!stash)
8113         return;
8114
8115     if (!*s) {          /* reset ?? searches */
8116         MAGIC * const mg = mg_find((const SV *)stash, PERL_MAGIC_symtab);
8117         if (mg) {
8118             const U32 count = mg->mg_len / sizeof(PMOP**);
8119             PMOP **pmp = (PMOP**) mg->mg_ptr;
8120             PMOP *const *const end = pmp + count;
8121
8122             while (pmp < end) {
8123 #ifdef USE_ITHREADS
8124                 SvREADONLY_off(PL_regex_pad[(*pmp)->op_pmoffset]);
8125 #else
8126                 (*pmp)->op_pmflags &= ~PMf_USED;
8127 #endif
8128                 ++pmp;
8129             }
8130         }
8131         return;
8132     }
8133
8134     /* reset variables */
8135
8136     if (!HvARRAY(stash))
8137         return;
8138
8139     Zero(todo, 256, char);
8140     while (*s) {
8141         I32 max;
8142         I32 i = (unsigned char)*s;
8143         if (s[1] == '-') {
8144             s += 2;
8145         }
8146         max = (unsigned char)*s++;
8147         for ( ; i <= max; i++) {
8148             todo[i] = 1;
8149         }
8150         for (i = 0; i <= (I32) HvMAX(stash); i++) {
8151             HE *entry;
8152             for (entry = HvARRAY(stash)[i];
8153                  entry;
8154                  entry = HeNEXT(entry))
8155             {
8156                 register GV *gv;
8157                 register SV *sv;
8158
8159                 if (!todo[(U8)*HeKEY(entry)])
8160                     continue;
8161                 gv = MUTABLE_GV(HeVAL(entry));
8162                 sv = GvSV(gv);
8163                 if (sv) {
8164                     if (SvTHINKFIRST(sv)) {
8165                         if (!SvREADONLY(sv) && SvROK(sv))
8166                             sv_unref(sv);
8167                         /* XXX Is this continue a bug? Why should THINKFIRST
8168                            exempt us from resetting arrays and hashes?  */
8169                         continue;
8170                     }
8171                     SvOK_off(sv);
8172                     if (SvTYPE(sv) >= SVt_PV) {
8173                         SvCUR_set(sv, 0);
8174                         if (SvPVX_const(sv) != NULL)
8175                             *SvPVX(sv) = '\0';
8176                         SvTAINT(sv);
8177                     }
8178                 }
8179                 if (GvAV(gv)) {
8180                     av_clear(GvAV(gv));
8181                 }
8182                 if (GvHV(gv) && !HvNAME_get(GvHV(gv))) {
8183 #if defined(VMS)
8184                     Perl_die(aTHX_ "Can't reset %%ENV on this system");
8185 #else /* ! VMS */
8186                     hv_clear(GvHV(gv));
8187 #  if defined(USE_ENVIRON_ARRAY)
8188                     if (gv == PL_envgv)
8189                         my_clearenv();
8190 #  endif /* USE_ENVIRON_ARRAY */
8191 #endif /* VMS */
8192                 }
8193             }
8194         }
8195     }
8196 }
8197
8198 /*
8199 =for apidoc sv_2io
8200
8201 Using various gambits, try to get an IO from an SV: the IO slot if its a
8202 GV; or the recursive result if we're an RV; or the IO slot of the symbol
8203 named after the PV if we're a string.
8204
8205 =cut
8206 */
8207
8208 IO*
8209 Perl_sv_2io(pTHX_ SV *const sv)
8210 {
8211     IO* io;
8212     GV* gv;
8213
8214     PERL_ARGS_ASSERT_SV_2IO;
8215
8216     switch (SvTYPE(sv)) {
8217     case SVt_PVIO:
8218         io = MUTABLE_IO(sv);
8219         break;
8220     case SVt_PVGV:
8221         if (isGV_with_GP(sv)) {
8222             gv = MUTABLE_GV(sv);
8223             io = GvIO(gv);
8224             if (!io)
8225                 Perl_croak(aTHX_ "Bad filehandle: %s", GvNAME(gv));
8226             break;
8227         }
8228         /* FALL THROUGH */
8229     default:
8230         if (!SvOK(sv))
8231             Perl_croak(aTHX_ PL_no_usym, "filehandle");
8232         if (SvROK(sv))
8233             return sv_2io(SvRV(sv));
8234         gv = gv_fetchsv(sv, 0, SVt_PVIO);
8235         if (gv)
8236             io = GvIO(gv);
8237         else
8238             io = 0;
8239         if (!io)
8240             Perl_croak(aTHX_ "Bad filehandle: %"SVf, SVfARG(sv));
8241         break;
8242     }
8243     return io;
8244 }
8245
8246 /*
8247 =for apidoc sv_2cv
8248
8249 Using various gambits, try to get a CV from an SV; in addition, try if
8250 possible to set C<*st> and C<*gvp> to the stash and GV associated with it.
8251 The flags in C<lref> are passed to gv_fetchsv.
8252
8253 =cut
8254 */
8255
8256 CV *
8257 Perl_sv_2cv(pTHX_ SV *sv, HV **const st, GV **const gvp, const I32 lref)
8258 {
8259     dVAR;
8260     GV *gv = NULL;
8261     CV *cv = NULL;
8262
8263     PERL_ARGS_ASSERT_SV_2CV;
8264
8265     if (!sv) {
8266         *st = NULL;
8267         *gvp = NULL;
8268         return NULL;
8269     }
8270     switch (SvTYPE(sv)) {
8271     case SVt_PVCV:
8272         *st = CvSTASH(sv);
8273         *gvp = NULL;
8274         return MUTABLE_CV(sv);
8275     case SVt_PVHV:
8276     case SVt_PVAV:
8277         *st = NULL;
8278         *gvp = NULL;
8279         return NULL;
8280     case SVt_PVGV:
8281         if (isGV_with_GP(sv)) {
8282             gv = MUTABLE_GV(sv);
8283             *gvp = gv;
8284             *st = GvESTASH(gv);
8285             goto fix_gv;
8286         }
8287         /* FALL THROUGH */
8288
8289     default:
8290         if (SvROK(sv)) {
8291             SV * const *sp = &sv;       /* Used in tryAMAGICunDEREF macro. */
8292             SvGETMAGIC(sv);
8293             tryAMAGICunDEREF(to_cv);
8294
8295             sv = SvRV(sv);
8296             if (SvTYPE(sv) == SVt_PVCV) {
8297                 cv = MUTABLE_CV(sv);
8298                 *gvp = NULL;
8299                 *st = CvSTASH(cv);
8300                 return cv;
8301             }
8302             else if(isGV_with_GP(sv))
8303                 gv = MUTABLE_GV(sv);
8304             else
8305                 Perl_croak(aTHX_ "Not a subroutine reference");
8306         }
8307         else if (isGV_with_GP(sv)) {
8308             SvGETMAGIC(sv);
8309             gv = MUTABLE_GV(sv);
8310         }
8311         else
8312             gv = gv_fetchsv(sv, lref, SVt_PVCV); /* Calls get magic */
8313         *gvp = gv;
8314         if (!gv) {
8315             *st = NULL;
8316             return NULL;
8317         }
8318         /* Some flags to gv_fetchsv mean don't really create the GV  */
8319         if (!isGV_with_GP(gv)) {
8320             *st = NULL;
8321             return NULL;
8322         }
8323         *st = GvESTASH(gv);
8324     fix_gv:
8325         if (lref && !GvCVu(gv)) {
8326             SV *tmpsv;
8327             ENTER;
8328             tmpsv = newSV(0);
8329             gv_efullname3(tmpsv, gv, NULL);
8330             /* XXX this is probably not what they think they're getting.
8331              * It has the same effect as "sub name;", i.e. just a forward
8332              * declaration! */
8333             newSUB(start_subparse(FALSE, 0),
8334                    newSVOP(OP_CONST, 0, tmpsv),
8335                    NULL, NULL);
8336             LEAVE;
8337             if (!GvCVu(gv))
8338                 Perl_croak(aTHX_ "Unable to create sub named \"%"SVf"\"",
8339                            SVfARG(SvOK(sv) ? sv : &PL_sv_no));
8340         }
8341         return GvCVu(gv);
8342     }
8343 }
8344
8345 /*
8346 =for apidoc sv_true
8347
8348 Returns true if the SV has a true value by Perl's rules.
8349 Use the C<SvTRUE> macro instead, which may call C<sv_true()> or may
8350 instead use an in-line version.
8351
8352 =cut
8353 */
8354
8355 I32
8356 Perl_sv_true(pTHX_ register SV *const sv)
8357 {
8358     if (!sv)
8359         return 0;
8360     if (SvPOK(sv)) {
8361         register const XPV* const tXpv = (XPV*)SvANY(sv);
8362         if (tXpv &&
8363                 (tXpv->xpv_cur > 1 ||
8364                 (tXpv->xpv_cur && *sv->sv_u.svu_pv != '0')))
8365             return 1;
8366         else
8367             return 0;
8368     }
8369     else {
8370         if (SvIOK(sv))
8371             return SvIVX(sv) != 0;
8372         else {
8373             if (SvNOK(sv))
8374                 return SvNVX(sv) != 0.0;
8375             else
8376                 return sv_2bool(sv);
8377         }
8378     }
8379 }
8380
8381 /*
8382 =for apidoc sv_pvn_force
8383
8384 Get a sensible string out of the SV somehow.
8385 A private implementation of the C<SvPV_force> macro for compilers which
8386 can't cope with complex macro expressions. Always use the macro instead.
8387
8388 =for apidoc sv_pvn_force_flags
8389
8390 Get a sensible string out of the SV somehow.
8391 If C<flags> has C<SV_GMAGIC> bit set, will C<mg_get> on C<sv> if
8392 appropriate, else not. C<sv_pvn_force> and C<sv_pvn_force_nomg> are
8393 implemented in terms of this function.
8394 You normally want to use the various wrapper macros instead: see
8395 C<SvPV_force> and C<SvPV_force_nomg>
8396
8397 =cut
8398 */
8399
8400 char *
8401 Perl_sv_pvn_force_flags(pTHX_ SV *const sv, STRLEN *const lp, const I32 flags)
8402 {
8403     dVAR;
8404
8405     PERL_ARGS_ASSERT_SV_PVN_FORCE_FLAGS;
8406
8407     if (SvTHINKFIRST(sv) && !SvROK(sv))
8408         sv_force_normal_flags(sv, 0);
8409
8410     if (SvPOK(sv)) {
8411         if (lp)
8412             *lp = SvCUR(sv);
8413     }
8414     else {
8415         char *s;
8416         STRLEN len;
8417  
8418         if (SvREADONLY(sv) && !(flags & SV_MUTABLE_RETURN)) {
8419             const char * const ref = sv_reftype(sv,0);
8420             if (PL_op)
8421                 Perl_croak(aTHX_ "Can't coerce readonly %s to string in %s",
8422                            ref, OP_DESC(PL_op));
8423             else
8424                 Perl_croak(aTHX_ "Can't coerce readonly %s to string", ref);
8425         }
8426         if ((SvTYPE(sv) > SVt_PVLV && SvTYPE(sv) != SVt_PVFM)
8427             || isGV_with_GP(sv))
8428             Perl_croak(aTHX_ "Can't coerce %s to string in %s", sv_reftype(sv,0),
8429                 OP_DESC(PL_op));
8430         s = sv_2pv_flags(sv, &len, flags);
8431         if (lp)
8432             *lp = len;
8433
8434         if (s != SvPVX_const(sv)) {     /* Almost, but not quite, sv_setpvn() */
8435             if (SvROK(sv))
8436                 sv_unref(sv);
8437             SvUPGRADE(sv, SVt_PV);              /* Never FALSE */
8438             SvGROW(sv, len + 1);
8439             Move(s,SvPVX(sv),len,char);
8440             SvCUR_set(sv, len);
8441             SvPVX(sv)[len] = '\0';
8442         }
8443         if (!SvPOK(sv)) {
8444             SvPOK_on(sv);               /* validate pointer */
8445             SvTAINT(sv);
8446             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
8447                                   PTR2UV(sv),SvPVX_const(sv)));
8448         }
8449     }
8450     return SvPVX_mutable(sv);
8451 }
8452
8453 /*
8454 =for apidoc sv_pvbyten_force
8455
8456 The backend for the C<SvPVbytex_force> macro. Always use the macro instead.
8457
8458 =cut
8459 */
8460
8461 char *
8462 Perl_sv_pvbyten_force(pTHX_ SV *const sv, STRLEN *const lp)
8463 {
8464     PERL_ARGS_ASSERT_SV_PVBYTEN_FORCE;
8465
8466     sv_pvn_force(sv,lp);
8467     sv_utf8_downgrade(sv,0);
8468     *lp = SvCUR(sv);
8469     return SvPVX(sv);
8470 }
8471
8472 /*
8473 =for apidoc sv_pvutf8n_force
8474
8475 The backend for the C<SvPVutf8x_force> macro. Always use the macro instead.
8476
8477 =cut
8478 */
8479
8480 char *
8481 Perl_sv_pvutf8n_force(pTHX_ SV *const sv, STRLEN *const lp)
8482 {
8483     PERL_ARGS_ASSERT_SV_PVUTF8N_FORCE;
8484
8485     sv_pvn_force(sv,lp);
8486     sv_utf8_upgrade(sv);
8487     *lp = SvCUR(sv);
8488     return SvPVX(sv);
8489 }
8490
8491 /*
8492 =for apidoc sv_reftype
8493
8494 Returns a string describing what the SV is a reference to.
8495
8496 =cut
8497 */
8498
8499 const char *
8500 Perl_sv_reftype(pTHX_ const SV *const sv, const int ob)
8501 {
8502     PERL_ARGS_ASSERT_SV_REFTYPE;
8503
8504     /* The fact that I don't need to downcast to char * everywhere, only in ?:
8505        inside return suggests a const propagation bug in g++.  */
8506     if (ob && SvOBJECT(sv)) {
8507         char * const name = HvNAME_get(SvSTASH(sv));
8508         return name ? name : (char *) "__ANON__";
8509     }
8510     else {
8511         switch (SvTYPE(sv)) {
8512         case SVt_NULL:
8513         case SVt_IV:
8514         case SVt_NV:
8515         case SVt_PV:
8516         case SVt_PVIV:
8517         case SVt_PVNV:
8518         case SVt_PVMG:
8519                                 if (SvVOK(sv))
8520                                     return "VSTRING";
8521                                 if (SvROK(sv))
8522                                     return "REF";
8523                                 else
8524                                     return "SCALAR";
8525
8526         case SVt_PVLV:          return (char *)  (SvROK(sv) ? "REF"
8527                                 /* tied lvalues should appear to be
8528                                  * scalars for backwards compatitbility */
8529                                 : (LvTYPE(sv) == 't' || LvTYPE(sv) == 'T')
8530                                     ? "SCALAR" : "LVALUE");
8531         case SVt_PVAV:          return "ARRAY";
8532         case SVt_PVHV:          return "HASH";
8533         case SVt_PVCV:          return "CODE";
8534         case SVt_PVGV:          return (char *) (isGV_with_GP(sv)
8535                                     ? "GLOB" : "SCALAR");
8536         case SVt_PVFM:          return "FORMAT";
8537         case SVt_PVIO:          return "IO";
8538         case SVt_BIND:          return "BIND";
8539         case SVt_REGEXP:        return "REGEXP"; 
8540         default:                return "UNKNOWN";
8541         }
8542     }
8543 }
8544
8545 /*
8546 =for apidoc sv_isobject
8547
8548 Returns a boolean indicating whether the SV is an RV pointing to a blessed
8549 object.  If the SV is not an RV, or if the object is not blessed, then this
8550 will return false.
8551
8552 =cut
8553 */
8554
8555 int
8556 Perl_sv_isobject(pTHX_ SV *sv)
8557 {
8558     if (!sv)
8559         return 0;
8560     SvGETMAGIC(sv);
8561     if (!SvROK(sv))
8562         return 0;
8563     sv = SvRV(sv);
8564     if (!SvOBJECT(sv))
8565         return 0;
8566     return 1;
8567 }
8568
8569 /*
8570 =for apidoc sv_isa
8571
8572 Returns a boolean indicating whether the SV is blessed into the specified
8573 class.  This does not check for subtypes; use C<sv_derived_from> to verify
8574 an inheritance relationship.
8575
8576 =cut
8577 */
8578
8579 int
8580 Perl_sv_isa(pTHX_ SV *sv, const char *const name)
8581 {
8582     const char *hvname;
8583
8584     PERL_ARGS_ASSERT_SV_ISA;
8585
8586     if (!sv)
8587         return 0;
8588     SvGETMAGIC(sv);
8589     if (!SvROK(sv))
8590         return 0;
8591     sv = SvRV(sv);
8592     if (!SvOBJECT(sv))
8593         return 0;
8594     hvname = HvNAME_get(SvSTASH(sv));
8595     if (!hvname)
8596         return 0;
8597
8598     return strEQ(hvname, name);
8599 }
8600
8601 /*
8602 =for apidoc newSVrv
8603
8604 Creates a new SV for the RV, C<rv>, to point to.  If C<rv> is not an RV then
8605 it will be upgraded to one.  If C<classname> is non-null then the new SV will
8606 be blessed in the specified package.  The new SV is returned and its
8607 reference count is 1.
8608
8609 =cut
8610 */
8611
8612 SV*
8613 Perl_newSVrv(pTHX_ SV *const rv, const char *const classname)
8614 {
8615     dVAR;
8616     SV *sv;
8617
8618     PERL_ARGS_ASSERT_NEWSVRV;
8619
8620     new_SV(sv);
8621
8622     SV_CHECK_THINKFIRST_COW_DROP(rv);
8623     (void)SvAMAGIC_off(rv);
8624
8625     if (SvTYPE(rv) >= SVt_PVMG) {
8626         const U32 refcnt = SvREFCNT(rv);
8627         SvREFCNT(rv) = 0;
8628         sv_clear(rv);
8629         SvFLAGS(rv) = 0;
8630         SvREFCNT(rv) = refcnt;
8631
8632         sv_upgrade(rv, SVt_IV);
8633     } else if (SvROK(rv)) {
8634         SvREFCNT_dec(SvRV(rv));
8635     } else {
8636         prepare_SV_for_RV(rv);
8637     }
8638
8639     SvOK_off(rv);
8640     SvRV_set(rv, sv);
8641     SvROK_on(rv);
8642
8643     if (classname) {
8644         HV* const stash = gv_stashpv(classname, GV_ADD);
8645         (void)sv_bless(rv, stash);
8646     }
8647     return sv;
8648 }
8649
8650 /*
8651 =for apidoc sv_setref_pv
8652
8653 Copies a pointer into a new SV, optionally blessing the SV.  The C<rv>
8654 argument will be upgraded to an RV.  That RV will be modified to point to
8655 the new SV.  If the C<pv> argument is NULL then C<PL_sv_undef> will be placed
8656 into the SV.  The C<classname> argument indicates the package for the
8657 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
8658 will have a reference count of 1, and the RV will be returned.
8659
8660 Do not use with other Perl types such as HV, AV, SV, CV, because those
8661 objects will become corrupted by the pointer copy process.
8662
8663 Note that C<sv_setref_pvn> copies the string while this copies the pointer.
8664
8665 =cut
8666 */
8667
8668 SV*
8669 Perl_sv_setref_pv(pTHX_ SV *const rv, const char *const classname, void *const pv)
8670 {
8671     dVAR;
8672
8673     PERL_ARGS_ASSERT_SV_SETREF_PV;
8674
8675     if (!pv) {
8676         sv_setsv(rv, &PL_sv_undef);
8677         SvSETMAGIC(rv);
8678     }
8679     else
8680         sv_setiv(newSVrv(rv,classname), PTR2IV(pv));
8681     return rv;
8682 }
8683
8684 /*
8685 =for apidoc sv_setref_iv
8686
8687 Copies an integer into a new SV, optionally blessing the SV.  The C<rv>
8688 argument will be upgraded to an RV.  That RV will be modified to point to
8689 the new SV.  The C<classname> argument indicates the package for the
8690 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
8691 will have a reference count of 1, and the RV will be returned.
8692
8693 =cut
8694 */
8695
8696 SV*
8697 Perl_sv_setref_iv(pTHX_ SV *const rv, const char *const classname, const IV iv)
8698 {
8699     PERL_ARGS_ASSERT_SV_SETREF_IV;
8700
8701     sv_setiv(newSVrv(rv,classname), iv);
8702     return rv;
8703 }
8704
8705 /*
8706 =for apidoc sv_setref_uv
8707
8708 Copies an unsigned integer into a new SV, optionally blessing the SV.  The C<rv>
8709 argument will be upgraded to an RV.  That RV will be modified to point to
8710 the new SV.  The C<classname> argument indicates the package for the
8711 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
8712 will have a reference count of 1, and the RV will be returned.
8713
8714 =cut
8715 */
8716
8717 SV*
8718 Perl_sv_setref_uv(pTHX_ SV *const rv, const char *const classname, const UV uv)
8719 {
8720     PERL_ARGS_ASSERT_SV_SETREF_UV;
8721
8722     sv_setuv(newSVrv(rv,classname), uv);
8723     return rv;
8724 }
8725
8726 /*
8727 =for apidoc sv_setref_nv
8728
8729 Copies a double into a new SV, optionally blessing the SV.  The C<rv>
8730 argument will be upgraded to an RV.  That RV will be modified to point to
8731 the new SV.  The C<classname> argument indicates the package for the
8732 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
8733 will have a reference count of 1, and the RV will be returned.
8734
8735 =cut
8736 */
8737
8738 SV*
8739 Perl_sv_setref_nv(pTHX_ SV *const rv, const char *const classname, const NV nv)
8740 {
8741     PERL_ARGS_ASSERT_SV_SETREF_NV;
8742
8743     sv_setnv(newSVrv(rv,classname), nv);
8744     return rv;
8745 }
8746
8747 /*
8748 =for apidoc sv_setref_pvn
8749
8750 Copies a string into a new SV, optionally blessing the SV.  The length of the
8751 string must be specified with C<n>.  The C<rv> argument will be upgraded to
8752 an RV.  That RV will be modified to point to the new SV.  The C<classname>
8753 argument indicates the package for the blessing.  Set C<classname> to
8754 C<NULL> to avoid the blessing.  The new SV will have a reference count
8755 of 1, and the RV will be returned.
8756
8757 Note that C<sv_setref_pv> copies the pointer while this copies the string.
8758
8759 =cut
8760 */
8761
8762 SV*
8763 Perl_sv_setref_pvn(pTHX_ SV *const rv, const char *const classname,
8764                    const char *const pv, const STRLEN n)
8765 {
8766     PERL_ARGS_ASSERT_SV_SETREF_PVN;
8767
8768     sv_setpvn(newSVrv(rv,classname), pv, n);
8769     return rv;
8770 }
8771
8772 /*
8773 =for apidoc sv_bless
8774
8775 Blesses an SV into a specified package.  The SV must be an RV.  The package
8776 must be designated by its stash (see C<gv_stashpv()>).  The reference count
8777 of the SV is unaffected.
8778
8779 =cut
8780 */
8781
8782 SV*
8783 Perl_sv_bless(pTHX_ SV *const sv, HV *const stash)
8784 {
8785     dVAR;
8786     SV *tmpRef;
8787
8788     PERL_ARGS_ASSERT_SV_BLESS;
8789
8790     if (!SvROK(sv))
8791         Perl_croak(aTHX_ "Can't bless non-reference value");
8792     tmpRef = SvRV(sv);
8793     if (SvFLAGS(tmpRef) & (SVs_OBJECT|SVf_READONLY)) {
8794         if (SvIsCOW(tmpRef))
8795             sv_force_normal_flags(tmpRef, 0);
8796         if (SvREADONLY(tmpRef))
8797             Perl_croak(aTHX_ "%s", PL_no_modify);
8798         if (SvOBJECT(tmpRef)) {
8799             if (SvTYPE(tmpRef) != SVt_PVIO)
8800                 --PL_sv_objcount;
8801             SvREFCNT_dec(SvSTASH(tmpRef));
8802         }
8803     }
8804     SvOBJECT_on(tmpRef);
8805     if (SvTYPE(tmpRef) != SVt_PVIO)
8806         ++PL_sv_objcount;
8807     SvUPGRADE(tmpRef, SVt_PVMG);
8808     SvSTASH_set(tmpRef, MUTABLE_HV(SvREFCNT_inc_simple(stash)));
8809
8810     if (Gv_AMG(stash))
8811         SvAMAGIC_on(sv);
8812     else
8813         (void)SvAMAGIC_off(sv);
8814
8815     if(SvSMAGICAL(tmpRef))
8816         if(mg_find(tmpRef, PERL_MAGIC_ext) || mg_find(tmpRef, PERL_MAGIC_uvar))
8817             mg_set(tmpRef);
8818
8819
8820
8821     return sv;
8822 }
8823
8824 /* Downgrades a PVGV to a PVMG.
8825  */
8826
8827 STATIC void
8828 S_sv_unglob(pTHX_ SV *const sv)
8829 {
8830     dVAR;
8831     void *xpvmg;
8832     HV *stash;
8833     SV * const temp = sv_newmortal();
8834
8835     PERL_ARGS_ASSERT_SV_UNGLOB;
8836
8837     assert(SvTYPE(sv) == SVt_PVGV);
8838     SvFAKE_off(sv);
8839     gv_efullname3(temp, MUTABLE_GV(sv), "*");
8840
8841     if (GvGP(sv)) {
8842         if(GvCVu((const GV *)sv) && (stash = GvSTASH(MUTABLE_GV(sv)))
8843            && HvNAME_get(stash))
8844             mro_method_changed_in(stash);
8845         gp_free(MUTABLE_GV(sv));
8846     }
8847     if (GvSTASH(sv)) {
8848         sv_del_backref(MUTABLE_SV(GvSTASH(sv)), sv);
8849         GvSTASH(sv) = NULL;
8850     }
8851     GvMULTI_off(sv);
8852     if (GvNAME_HEK(sv)) {
8853         unshare_hek(GvNAME_HEK(sv));
8854     }
8855     isGV_with_GP_off(sv);
8856
8857     /* need to keep SvANY(sv) in the right arena */
8858     xpvmg = new_XPVMG();
8859     StructCopy(SvANY(sv), xpvmg, XPVMG);
8860     del_XPVGV(SvANY(sv));
8861     SvANY(sv) = xpvmg;
8862
8863     SvFLAGS(sv) &= ~SVTYPEMASK;
8864     SvFLAGS(sv) |= SVt_PVMG;
8865
8866     /* Intentionally not calling any local SET magic, as this isn't so much a
8867        set operation as merely an internal storage change.  */
8868     sv_setsv_flags(sv, temp, 0);
8869 }
8870
8871 /*
8872 =for apidoc sv_unref_flags
8873
8874 Unsets the RV status of the SV, and decrements the reference count of
8875 whatever was being referenced by the RV.  This can almost be thought of
8876 as a reversal of C<newSVrv>.  The C<cflags> argument can contain
8877 C<SV_IMMEDIATE_UNREF> to force the reference count to be decremented
8878 (otherwise the decrementing is conditional on the reference count being
8879 different from one or the reference being a readonly SV).
8880 See C<SvROK_off>.
8881
8882 =cut
8883 */
8884
8885 void
8886 Perl_sv_unref_flags(pTHX_ SV *const ref, const U32 flags)
8887 {
8888     SV* const target = SvRV(ref);
8889
8890     PERL_ARGS_ASSERT_SV_UNREF_FLAGS;
8891
8892     if (SvWEAKREF(ref)) {
8893         sv_del_backref(target, ref);
8894         SvWEAKREF_off(ref);
8895         SvRV_set(ref, NULL);
8896         return;
8897     }
8898     SvRV_set(ref, NULL);
8899     SvROK_off(ref);
8900     /* You can't have a || SvREADONLY(target) here, as $a = $$a, where $a was
8901        assigned to as BEGIN {$a = \"Foo"} will fail.  */
8902     if (SvREFCNT(target) != 1 || (flags & SV_IMMEDIATE_UNREF))
8903         SvREFCNT_dec(target);
8904     else /* XXX Hack, but hard to make $a=$a->[1] work otherwise */
8905         sv_2mortal(target);     /* Schedule for freeing later */
8906 }
8907
8908 /*
8909 =for apidoc sv_untaint
8910
8911 Untaint an SV. Use C<SvTAINTED_off> instead.
8912 =cut
8913 */
8914
8915 void
8916 Perl_sv_untaint(pTHX_ SV *const sv)
8917 {
8918     PERL_ARGS_ASSERT_SV_UNTAINT;
8919
8920     if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
8921         MAGIC * const mg = mg_find(sv, PERL_MAGIC_taint);
8922         if (mg)
8923             mg->mg_len &= ~1;
8924     }
8925 }
8926
8927 /*
8928 =for apidoc sv_tainted
8929
8930 Test an SV for taintedness. Use C<SvTAINTED> instead.
8931 =cut
8932 */
8933
8934 bool
8935 Perl_sv_tainted(pTHX_ SV *const sv)
8936 {
8937     PERL_ARGS_ASSERT_SV_TAINTED;
8938
8939     if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
8940         const MAGIC * const mg = mg_find(sv, PERL_MAGIC_taint);
8941         if (mg && (mg->mg_len & 1) )
8942             return TRUE;
8943     }
8944     return FALSE;
8945 }
8946
8947 /*
8948 =for apidoc sv_setpviv
8949
8950 Copies an integer into the given SV, also updating its string value.
8951 Does not handle 'set' magic.  See C<sv_setpviv_mg>.
8952
8953 =cut
8954 */
8955
8956 void
8957 Perl_sv_setpviv(pTHX_ SV *const sv, const IV iv)
8958 {
8959     char buf[TYPE_CHARS(UV)];
8960     char *ebuf;
8961     char * const ptr = uiv_2buf(buf, iv, 0, 0, &ebuf);
8962
8963     PERL_ARGS_ASSERT_SV_SETPVIV;
8964
8965     sv_setpvn(sv, ptr, ebuf - ptr);
8966 }
8967
8968 /*
8969 =for apidoc sv_setpviv_mg
8970
8971 Like C<sv_setpviv>, but also handles 'set' magic.
8972
8973 =cut
8974 */
8975
8976 void
8977 Perl_sv_setpviv_mg(pTHX_ SV *const sv, const IV iv)
8978 {
8979     PERL_ARGS_ASSERT_SV_SETPVIV_MG;
8980
8981     sv_setpviv(sv, iv);
8982     SvSETMAGIC(sv);
8983 }
8984
8985 #if defined(PERL_IMPLICIT_CONTEXT)
8986
8987 /* pTHX_ magic can't cope with varargs, so this is a no-context
8988  * version of the main function, (which may itself be aliased to us).
8989  * Don't access this version directly.
8990  */
8991
8992 void
8993 Perl_sv_setpvf_nocontext(SV *const sv, const char *const pat, ...)
8994 {
8995     dTHX;
8996     va_list args;
8997
8998     PERL_ARGS_ASSERT_SV_SETPVF_NOCONTEXT;
8999
9000     va_start(args, pat);
9001     sv_vsetpvf(sv, pat, &args);
9002     va_end(args);
9003 }
9004
9005 /* pTHX_ magic can't cope with varargs, so this is a no-context
9006  * version of the main function, (which may itself be aliased to us).
9007  * Don't access this version directly.
9008  */
9009
9010 void
9011 Perl_sv_setpvf_mg_nocontext(SV *const sv, const char *const pat, ...)
9012 {
9013     dTHX;
9014     va_list args;
9015
9016     PERL_ARGS_ASSERT_SV_SETPVF_MG_NOCONTEXT;
9017
9018     va_start(args, pat);
9019     sv_vsetpvf_mg(sv, pat, &args);
9020     va_end(args);
9021 }
9022 #endif
9023
9024 /*
9025 =for apidoc sv_setpvf
9026
9027 Works like C<sv_catpvf> but copies the text into the SV instead of
9028 appending it.  Does not handle 'set' magic.  See C<sv_setpvf_mg>.
9029
9030 =cut
9031 */
9032
9033 void
9034 Perl_sv_setpvf(pTHX_ SV *const sv, const char *const pat, ...)
9035 {
9036     va_list args;
9037
9038     PERL_ARGS_ASSERT_SV_SETPVF;
9039
9040     va_start(args, pat);
9041     sv_vsetpvf(sv, pat, &args);
9042     va_end(args);
9043 }
9044
9045 /*
9046 =for apidoc sv_vsetpvf
9047
9048 Works like C<sv_vcatpvf> but copies the text into the SV instead of
9049 appending it.  Does not handle 'set' magic.  See C<sv_vsetpvf_mg>.
9050
9051 Usually used via its frontend C<sv_setpvf>.
9052
9053 =cut
9054 */
9055
9056 void
9057 Perl_sv_vsetpvf(pTHX_ SV *const sv, const char *const pat, va_list *const args)
9058 {
9059     PERL_ARGS_ASSERT_SV_VSETPVF;
9060
9061     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
9062 }
9063
9064 /*
9065 =for apidoc sv_setpvf_mg
9066
9067 Like C<sv_setpvf>, but also handles 'set' magic.
9068
9069 =cut
9070 */
9071
9072 void
9073 Perl_sv_setpvf_mg(pTHX_ SV *const sv, const char *const pat, ...)
9074 {
9075     va_list args;
9076
9077     PERL_ARGS_ASSERT_SV_SETPVF_MG;
9078
9079     va_start(args, pat);
9080     sv_vsetpvf_mg(sv, pat, &args);
9081     va_end(args);
9082 }
9083
9084 /*
9085 =for apidoc sv_vsetpvf_mg
9086
9087 Like C<sv_vsetpvf>, but also handles 'set' magic.
9088
9089 Usually used via its frontend C<sv_setpvf_mg>.
9090
9091 =cut
9092 */
9093
9094 void
9095 Perl_sv_vsetpvf_mg(pTHX_ SV *const sv, const char *const pat, va_list *const args)
9096 {
9097     PERL_ARGS_ASSERT_SV_VSETPVF_MG;
9098
9099     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
9100     SvSETMAGIC(sv);
9101 }
9102
9103 #if defined(PERL_IMPLICIT_CONTEXT)
9104
9105 /* pTHX_ magic can't cope with varargs, so this is a no-context
9106  * version of the main function, (which may itself be aliased to us).
9107  * Don't access this version directly.
9108  */
9109
9110 void
9111 Perl_sv_catpvf_nocontext(SV *const sv, const char *const pat, ...)
9112 {
9113     dTHX;
9114     va_list args;
9115
9116     PERL_ARGS_ASSERT_SV_CATPVF_NOCONTEXT;
9117
9118     va_start(args, pat);
9119     sv_vcatpvf(sv, pat, &args);
9120     va_end(args);
9121 }
9122
9123 /* pTHX_ magic can't cope with varargs, so this is a no-context
9124  * version of the main function, (which may itself be aliased to us).
9125  * Don't access this version directly.
9126  */
9127
9128 void
9129 Perl_sv_catpvf_mg_nocontext(SV *const sv, const char *const pat, ...)
9130 {
9131     dTHX;
9132     va_list args;
9133
9134     PERL_ARGS_ASSERT_SV_CATPVF_MG_NOCONTEXT;
9135
9136     va_start(args, pat);
9137     sv_vcatpvf_mg(sv, pat, &args);
9138     va_end(args);
9139 }
9140 #endif
9141
9142 /*
9143 =for apidoc sv_catpvf
9144
9145 Processes its arguments like C<sprintf> and appends the formatted
9146 output to an SV.  If the appended data contains "wide" characters
9147 (including, but not limited to, SVs with a UTF-8 PV formatted with %s,
9148 and characters >255 formatted with %c), the original SV might get
9149 upgraded to UTF-8.  Handles 'get' magic, but not 'set' magic.  See
9150 C<sv_catpvf_mg>. If the original SV was UTF-8, the pattern should be
9151 valid UTF-8; if the original SV was bytes, the pattern should be too.
9152
9153 =cut */
9154
9155 void
9156 Perl_sv_catpvf(pTHX_ SV *const sv, const char *const pat, ...)
9157 {
9158     va_list args;
9159
9160     PERL_ARGS_ASSERT_SV_CATPVF;
9161
9162     va_start(args, pat);
9163     sv_vcatpvf(sv, pat, &args);
9164     va_end(args);
9165 }
9166
9167 /*
9168 =for apidoc sv_vcatpvf
9169
9170 Processes its arguments like C<vsprintf> and appends the formatted output
9171 to an SV.  Does not handle 'set' magic.  See C<sv_vcatpvf_mg>.
9172
9173 Usually used via its frontend C<sv_catpvf>.
9174
9175 =cut
9176 */
9177
9178 void
9179 Perl_sv_vcatpvf(pTHX_ SV *const sv, const char *const pat, va_list *const args)
9180 {
9181     PERL_ARGS_ASSERT_SV_VCATPVF;
9182
9183     sv_vcatpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
9184 }
9185
9186 /*
9187 =for apidoc sv_catpvf_mg
9188
9189 Like C<sv_catpvf>, but also handles 'set' magic.
9190
9191 =cut
9192 */
9193
9194 void
9195 Perl_sv_catpvf_mg(pTHX_ SV *const sv, const char *const pat, ...)
9196 {
9197     va_list args;
9198
9199     PERL_ARGS_ASSERT_SV_CATPVF_MG;
9200
9201     va_start(args, pat);
9202     sv_vcatpvf_mg(sv, pat, &args);
9203     va_end(args);
9204 }
9205
9206 /*
9207 =for apidoc sv_vcatpvf_mg
9208
9209 Like C<sv_vcatpvf>, but also handles 'set' magic.
9210
9211 Usually used via its frontend C<sv_catpvf_mg>.
9212
9213 =cut
9214 */
9215
9216 void
9217 Perl_sv_vcatpvf_mg(pTHX_ SV *const sv, const char *const pat, va_list *const args)
9218 {
9219     PERL_ARGS_ASSERT_SV_VCATPVF_MG;
9220
9221     sv_vcatpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
9222     SvSETMAGIC(sv);
9223 }
9224
9225 /*
9226 =for apidoc sv_vsetpvfn
9227
9228 Works like C<sv_vcatpvfn> but copies the text into the SV instead of
9229 appending it.
9230
9231 Usually used via one of its frontends C<sv_vsetpvf> and C<sv_vsetpvf_mg>.
9232
9233 =cut
9234 */
9235
9236 void
9237 Perl_sv_vsetpvfn(pTHX_ SV *const sv, const char *const pat, const STRLEN patlen,
9238                  va_list *const args, SV **const svargs, const I32 svmax, bool *const maybe_tainted)
9239 {
9240     PERL_ARGS_ASSERT_SV_VSETPVFN;
9241
9242     sv_setpvs(sv, "");
9243     sv_vcatpvfn(sv, pat, patlen, args, svargs, svmax, maybe_tainted);
9244 }
9245
9246
9247 /*
9248  * Warn of missing argument to sprintf, and then return a defined value
9249  * to avoid inappropriate "use of uninit" warnings [perl #71000].
9250  */
9251 #define WARN_MISSING WARN_UNINITIALIZED /* Not sure we want a new category */
9252 STATIC SV*
9253 S_vcatpvfn_missing_argument(pTHX) {
9254     if (ckWARN(WARN_MISSING)) {
9255         Perl_warner(aTHX_ packWARN(WARN_MISSING), "Missing argument in %s",
9256                 PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn()");
9257     }
9258     return &PL_sv_no;
9259 }
9260
9261
9262 STATIC I32
9263 S_expect_number(pTHX_ char **const pattern)
9264 {
9265     dVAR;
9266     I32 var = 0;
9267
9268     PERL_ARGS_ASSERT_EXPECT_NUMBER;
9269
9270     switch (**pattern) {
9271     case '1': case '2': case '3':
9272     case '4': case '5': case '6':
9273     case '7': case '8': case '9':
9274         var = *(*pattern)++ - '0';
9275         while (isDIGIT(**pattern)) {
9276             const I32 tmp = var * 10 + (*(*pattern)++ - '0');
9277             if (tmp < var)
9278                 Perl_croak(aTHX_ "Integer overflow in format string for %s", (PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn"));
9279             var = tmp;
9280         }
9281     }
9282     return var;
9283 }
9284
9285 STATIC char *
9286 S_F0convert(NV nv, char *const endbuf, STRLEN *const len)
9287 {
9288     const int neg = nv < 0;
9289     UV uv;
9290
9291     PERL_ARGS_ASSERT_F0CONVERT;
9292
9293     if (neg)
9294         nv = -nv;
9295     if (nv < UV_MAX) {
9296         char *p = endbuf;
9297         nv += 0.5;
9298         uv = (UV)nv;
9299         if (uv & 1 && uv == nv)
9300             uv--;                       /* Round to even */
9301         do {
9302             const unsigned dig = uv % 10;
9303             *--p = '0' + dig;
9304         } while (uv /= 10);
9305         if (neg)
9306             *--p = '-';
9307         *len = endbuf - p;
9308         return p;
9309     }
9310     return NULL;
9311 }
9312
9313
9314 /*
9315 =for apidoc sv_vcatpvfn
9316
9317 Processes its arguments like C<vsprintf> and appends the formatted output
9318 to an SV.  Uses an array of SVs if the C style variable argument list is
9319 missing (NULL).  When running with taint checks enabled, indicates via
9320 C<maybe_tainted> if results are untrustworthy (often due to the use of
9321 locales).
9322
9323 Usually used via one of its frontends C<sv_vcatpvf> and C<sv_vcatpvf_mg>.
9324
9325 =cut
9326 */
9327
9328
9329 #define VECTORIZE_ARGS  vecsv = va_arg(*args, SV*);\
9330                         vecstr = (U8*)SvPV_const(vecsv,veclen);\
9331                         vec_utf8 = DO_UTF8(vecsv);
9332
9333 /* XXX maybe_tainted is never assigned to, so the doc above is lying. */
9334
9335 void
9336 Perl_sv_vcatpvfn(pTHX_ SV *const sv, const char *const pat, const STRLEN patlen,
9337                  va_list *const args, SV **const svargs, const I32 svmax, bool *const maybe_tainted)
9338 {
9339     dVAR;
9340     char *p;
9341     char *q;
9342     const char *patend;
9343     STRLEN origlen;
9344     I32 svix = 0;
9345     static const char nullstr[] = "(null)";
9346     SV *argsv = NULL;
9347     bool has_utf8 = DO_UTF8(sv);    /* has the result utf8? */
9348     const bool pat_utf8 = has_utf8; /* the pattern is in utf8? */
9349     SV *nsv = NULL;
9350     /* Times 4: a decimal digit takes more than 3 binary digits.
9351      * NV_DIG: mantissa takes than many decimal digits.
9352      * Plus 32: Playing safe. */
9353     char ebuf[IV_DIG * 4 + NV_DIG + 32];
9354     /* large enough for "%#.#f" --chip */
9355     /* what about long double NVs? --jhi */
9356
9357     PERL_ARGS_ASSERT_SV_VCATPVFN;
9358     PERL_UNUSED_ARG(maybe_tainted);
9359
9360     /* no matter what, this is a string now */
9361     (void)SvPV_force(sv, origlen);
9362
9363     /* special-case "", "%s", and "%-p" (SVf - see below) */
9364     if (patlen == 0)
9365         return;
9366     if (patlen == 2 && pat[0] == '%' && pat[1] == 's') {
9367         if (args) {
9368             const char * const s = va_arg(*args, char*);
9369             sv_catpv(sv, s ? s : nullstr);
9370         }
9371         else if (svix < svmax) {
9372             sv_catsv(sv, *svargs);
9373         }
9374         else
9375             S_vcatpvfn_missing_argument(aTHX);
9376         return;
9377     }
9378     if (args && patlen == 3 && pat[0] == '%' &&
9379                 pat[1] == '-' && pat[2] == 'p') {
9380         argsv = MUTABLE_SV(va_arg(*args, void*));
9381         sv_catsv(sv, argsv);
9382         return;
9383     }
9384
9385 #ifndef USE_LONG_DOUBLE
9386     /* special-case "%.<number>[gf]" */
9387     if ( !args && patlen <= 5 && pat[0] == '%' && pat[1] == '.'
9388          && (pat[patlen-1] == 'g' || pat[patlen-1] == 'f') ) {
9389         unsigned digits = 0;
9390         const char *pp;
9391
9392         pp = pat + 2;
9393         while (*pp >= '0' && *pp <= '9')
9394             digits = 10 * digits + (*pp++ - '0');
9395         if (pp - pat == (int)patlen - 1 && svix < svmax) {
9396             const NV nv = SvNV(*svargs);
9397             if (*pp == 'g') {
9398                 /* Add check for digits != 0 because it seems that some
9399                    gconverts are buggy in this case, and we don't yet have
9400                    a Configure test for this.  */
9401                 if (digits && digits < sizeof(ebuf) - NV_DIG - 10) {
9402                      /* 0, point, slack */
9403                     Gconvert(nv, (int)digits, 0, ebuf);
9404                     sv_catpv(sv, ebuf);
9405                     if (*ebuf)  /* May return an empty string for digits==0 */
9406                         return;
9407                 }
9408             } else if (!digits) {
9409                 STRLEN l;
9410
9411                 if ((p = F0convert(nv, ebuf + sizeof ebuf, &l))) {
9412                     sv_catpvn(sv, p, l);
9413                     return;
9414                 }
9415             }
9416         }
9417     }
9418 #endif /* !USE_LONG_DOUBLE */
9419
9420     if (!args && svix < svmax && DO_UTF8(*svargs))
9421         has_utf8 = TRUE;
9422
9423     patend = (char*)pat + patlen;
9424     for (p = (char*)pat; p < patend; p = q) {
9425         bool alt = FALSE;
9426         bool left = FALSE;
9427         bool vectorize = FALSE;
9428         bool vectorarg = FALSE;
9429         bool vec_utf8 = FALSE;
9430         char fill = ' ';
9431         char plus = 0;
9432         char intsize = 0;
9433         STRLEN width = 0;
9434         STRLEN zeros = 0;
9435         bool has_precis = FALSE;
9436         STRLEN precis = 0;
9437         const I32 osvix = svix;
9438         bool is_utf8 = FALSE;  /* is this item utf8?   */
9439 #ifdef HAS_LDBL_SPRINTF_BUG
9440         /* This is to try to fix a bug with irix/nonstop-ux/powerux and
9441            with sfio - Allen <allens@cpan.org> */
9442         bool fix_ldbl_sprintf_bug = FALSE;
9443 #endif
9444
9445         char esignbuf[4];
9446         U8 utf8buf[UTF8_MAXBYTES+1];
9447         STRLEN esignlen = 0;
9448
9449         const char *eptr = NULL;
9450         const char *fmtstart;
9451         STRLEN elen = 0;
9452         SV *vecsv = NULL;
9453         const U8 *vecstr = NULL;
9454         STRLEN veclen = 0;
9455         char c = 0;
9456         int i;
9457         unsigned base = 0;
9458         IV iv = 0;
9459         UV uv = 0;
9460         /* we need a long double target in case HAS_LONG_DOUBLE but
9461            not USE_LONG_DOUBLE
9462         */
9463 #if defined(HAS_LONG_DOUBLE) && LONG_DOUBLESIZE > DOUBLESIZE
9464         long double nv;
9465 #else
9466         NV nv;
9467 #endif
9468         STRLEN have;
9469         STRLEN need;
9470         STRLEN gap;
9471         const char *dotstr = ".";
9472         STRLEN dotstrlen = 1;
9473         I32 efix = 0; /* explicit format parameter index */
9474         I32 ewix = 0; /* explicit width index */
9475         I32 epix = 0; /* explicit precision index */
9476         I32 evix = 0; /* explicit vector index */
9477         bool asterisk = FALSE;
9478
9479         /* echo everything up to the next format specification */
9480         for (q = p; q < patend && *q != '%'; ++q) ;
9481         if (q > p) {
9482             if (has_utf8 && !pat_utf8)
9483                 sv_catpvn_utf8_upgrade(sv, p, q - p, nsv);
9484             else
9485                 sv_catpvn(sv, p, q - p);
9486             p = q;
9487         }
9488         if (q++ >= patend)
9489             break;
9490
9491         fmtstart = q;
9492
9493 /*
9494     We allow format specification elements in this order:
9495         \d+\$              explicit format parameter index
9496         [-+ 0#]+           flags
9497         v|\*(\d+\$)?v      vector with optional (optionally specified) arg
9498         0                  flag (as above): repeated to allow "v02"     
9499         \d+|\*(\d+\$)?     width using optional (optionally specified) arg
9500         \.(\d*|\*(\d+\$)?) precision using optional (optionally specified) arg
9501         [hlqLV]            size
9502     [%bcdefginopsuxDFOUX] format (mandatory)
9503 */
9504
9505         if (args) {
9506 /*  
9507         As of perl5.9.3, printf format checking is on by default.
9508         Internally, perl uses %p formats to provide an escape to
9509         some extended formatting.  This block deals with those
9510         extensions: if it does not match, (char*)q is reset and
9511         the normal format processing code is used.
9512
9513         Currently defined extensions are:
9514                 %p              include pointer address (standard)      
9515                 %-p     (SVf)   include an SV (previously %_)
9516                 %-<num>p        include an SV with precision <num>      
9517                 %<num>p         reserved for future extensions
9518
9519         Robin Barker 2005-07-14
9520
9521                 %1p     (VDf)   removed.  RMB 2007-10-19
9522 */
9523             char* r = q; 
9524             bool sv = FALSE;    
9525             STRLEN n = 0;
9526             if (*q == '-')
9527                 sv = *q++;
9528             n = expect_number(&q);
9529             if (*q++ == 'p') {
9530                 if (sv) {                       /* SVf */
9531                     if (n) {
9532                         precis = n;
9533                         has_precis = TRUE;
9534                     }
9535                     argsv = MUTABLE_SV(va_arg(*args, void*));
9536                     eptr = SvPV_const(argsv, elen);
9537                     if (DO_UTF8(argsv))
9538                         is_utf8 = TRUE;
9539                     goto string;
9540                 }
9541                 else if (n) {
9542                     Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
9543                                      "internal %%<num>p might conflict with future printf extensions");
9544                 }
9545             }
9546             q = r; 
9547         }
9548
9549         if ( (width = expect_number(&q)) ) {
9550             if (*q == '$') {
9551                 ++q;
9552                 efix = width;
9553             } else {
9554                 goto gotwidth;
9555             }
9556         }
9557
9558         /* FLAGS */
9559
9560         while (*q) {
9561             switch (*q) {
9562             case ' ':
9563             case '+':
9564                 if (plus == '+' && *q == ' ') /* '+' over ' ' */
9565                     q++;
9566                 else
9567                     plus = *q++;
9568                 continue;
9569
9570             case '-':
9571                 left = TRUE;
9572                 q++;
9573                 continue;
9574
9575             case '0':
9576                 fill = *q++;
9577                 continue;
9578
9579             case '#':
9580                 alt = TRUE;
9581                 q++;
9582                 continue;
9583
9584             default:
9585                 break;
9586             }
9587             break;
9588         }
9589
9590       tryasterisk:
9591         if (*q == '*') {
9592             q++;
9593             if ( (ewix = expect_number(&q)) )
9594                 if (*q++ != '$')
9595                     goto unknown;
9596             asterisk = TRUE;
9597         }
9598         if (*q == 'v') {
9599             q++;
9600             if (vectorize)
9601                 goto unknown;
9602             if ((vectorarg = asterisk)) {
9603                 evix = ewix;
9604                 ewix = 0;
9605                 asterisk = FALSE;
9606             }
9607             vectorize = TRUE;
9608             goto tryasterisk;
9609         }
9610
9611         if (!asterisk)
9612         {
9613             if( *q == '0' )
9614                 fill = *q++;
9615             width = expect_number(&q);
9616         }
9617
9618         if (vectorize) {
9619             if (vectorarg) {
9620                 if (args)
9621                     vecsv = va_arg(*args, SV*);
9622                 else if (evix) {
9623                     vecsv = (evix > 0 && evix <= svmax)
9624                         ? svargs[evix-1] : S_vcatpvfn_missing_argument(aTHX);
9625                 } else {
9626                     vecsv = svix < svmax
9627                         ? svargs[svix++] : S_vcatpvfn_missing_argument(aTHX);
9628                 }
9629                 dotstr = SvPV_const(vecsv, dotstrlen);
9630                 /* Keep the DO_UTF8 test *after* the SvPV call, else things go
9631                    bad with tied or overloaded values that return UTF8.  */
9632                 if (DO_UTF8(vecsv))
9633                     is_utf8 = TRUE;
9634                 else if (has_utf8) {
9635                     vecsv = sv_mortalcopy(vecsv);
9636                     sv_utf8_upgrade(vecsv);
9637                     dotstr = SvPV_const(vecsv, dotstrlen);
9638                     is_utf8 = TRUE;
9639                 }                   
9640             }
9641             if (args) {
9642                 VECTORIZE_ARGS
9643             }
9644             else if (efix ? (efix > 0 && efix <= svmax) : svix < svmax) {
9645                 vecsv = svargs[efix ? efix-1 : svix++];
9646                 vecstr = (U8*)SvPV_const(vecsv,veclen);
9647                 vec_utf8 = DO_UTF8(vecsv);
9648
9649                 /* if this is a version object, we need to convert
9650                  * back into v-string notation and then let the
9651                  * vectorize happen normally
9652                  */
9653                 if (sv_derived_from(vecsv, "version")) {
9654                     char *version = savesvpv(vecsv);
9655                     if ( hv_exists(MUTABLE_HV(SvRV(vecsv)), "alpha", 5 ) ) {
9656                         Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
9657                         "vector argument not supported with alpha versions");
9658                         goto unknown;
9659                     }
9660                     vecsv = sv_newmortal();
9661                     scan_vstring(version, version + veclen, vecsv);
9662                     vecstr = (U8*)SvPV_const(vecsv, veclen);
9663                     vec_utf8 = DO_UTF8(vecsv);
9664                     Safefree(version);
9665                 }
9666             }
9667             else {
9668                 vecstr = (U8*)"";
9669                 veclen = 0;
9670             }
9671         }
9672
9673         if (asterisk) {
9674             if (args)
9675                 i = va_arg(*args, int);
9676             else
9677                 i = (ewix ? ewix <= svmax : svix < svmax) ?
9678                     SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
9679             left |= (i < 0);
9680             width = (i < 0) ? -i : i;
9681         }
9682       gotwidth:
9683
9684         /* PRECISION */
9685
9686         if (*q == '.') {
9687             q++;
9688             if (*q == '*') {
9689                 q++;
9690                 if ( ((epix = expect_number(&q))) && (*q++ != '$') )
9691                     goto unknown;
9692                 /* XXX: todo, support specified precision parameter */
9693                 if (epix)
9694                     goto unknown;
9695                 if (args)
9696                     i = va_arg(*args, int);
9697                 else
9698                     i = (ewix ? ewix <= svmax : svix < svmax)
9699                         ? SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
9700                 precis = i;
9701                 has_precis = !(i < 0);
9702             }
9703             else {
9704                 precis = 0;
9705                 while (isDIGIT(*q))
9706                     precis = precis * 10 + (*q++ - '0');
9707                 has_precis = TRUE;
9708             }
9709         }
9710
9711         /* SIZE */
9712
9713         switch (*q) {
9714 #ifdef WIN32
9715         case 'I':                       /* Ix, I32x, and I64x */
9716 #  ifdef WIN64
9717             if (q[1] == '6' && q[2] == '4') {
9718                 q += 3;
9719                 intsize = 'q';
9720                 break;
9721             }
9722 #  endif
9723             if (q[1] == '3' && q[2] == '2') {
9724                 q += 3;
9725                 break;
9726             }
9727 #  ifdef WIN64
9728             intsize = 'q';
9729 #  endif
9730             q++;
9731             break;
9732 #endif
9733 #if defined(HAS_QUAD) || defined(HAS_LONG_DOUBLE)
9734         case 'L':                       /* Ld */
9735             /*FALLTHROUGH*/
9736 #ifdef HAS_QUAD
9737         case 'q':                       /* qd */
9738 #endif
9739             intsize = 'q';
9740             q++;
9741             break;
9742 #endif
9743         case 'l':
9744 #if defined(HAS_QUAD) || defined(HAS_LONG_DOUBLE)
9745             if (*(q + 1) == 'l') {      /* lld, llf */
9746                 intsize = 'q';
9747                 q += 2;
9748                 break;
9749              }
9750 #endif
9751             /*FALLTHROUGH*/
9752         case 'h':
9753             /*FALLTHROUGH*/
9754         case 'V':
9755             intsize = *q++;
9756             break;
9757         }
9758
9759         /* CONVERSION */
9760
9761         if (*q == '%') {
9762             eptr = q++;
9763             elen = 1;
9764             if (vectorize) {
9765                 c = '%';
9766                 goto unknown;
9767             }
9768             goto string;
9769         }
9770
9771         if (!vectorize && !args) {
9772             if (efix) {
9773                 const I32 i = efix-1;
9774                 argsv = (i >= 0 && i < svmax)
9775                     ? svargs[i] : S_vcatpvfn_missing_argument(aTHX);
9776             } else {
9777                 argsv = (svix >= 0 && svix < svmax)
9778                     ? svargs[svix++] : S_vcatpvfn_missing_argument(aTHX);
9779             }
9780         }
9781
9782         switch (c = *q++) {
9783
9784             /* STRINGS */
9785
9786         case 'c':
9787             if (vectorize)
9788                 goto unknown;
9789             uv = (args) ? va_arg(*args, int) : SvIV(argsv);
9790             if ((uv > 255 ||
9791                  (!UNI_IS_INVARIANT(uv) && SvUTF8(sv)))
9792                 && !IN_BYTES) {
9793                 eptr = (char*)utf8buf;
9794                 elen = uvchr_to_utf8((U8*)eptr, uv) - utf8buf;
9795                 is_utf8 = TRUE;
9796             }
9797             else {
9798                 c = (char)uv;
9799                 eptr = &c;
9800                 elen = 1;
9801             }
9802             goto string;
9803
9804         case 's':
9805             if (vectorize)
9806                 goto unknown;
9807             if (args) {
9808                 eptr = va_arg(*args, char*);
9809                 if (eptr)
9810                     elen = strlen(eptr);
9811                 else {
9812                     eptr = (char *)nullstr;
9813                     elen = sizeof nullstr - 1;
9814                 }
9815             }
9816             else {
9817                 eptr = SvPV_const(argsv, elen);
9818                 if (DO_UTF8(argsv)) {
9819                     STRLEN old_precis = precis;
9820                     if (has_precis && precis < elen) {
9821                         STRLEN ulen = sv_len_utf8(argsv);
9822                         I32 p = precis > ulen ? ulen : precis;
9823                         sv_pos_u2b(argsv, &p, 0); /* sticks at end */
9824                         precis = p;
9825                     }
9826                     if (width) { /* fudge width (can't fudge elen) */
9827                         if (has_precis && precis < elen)
9828                             width += precis - old_precis;
9829                         else
9830                             width += elen - sv_len_utf8(argsv);
9831                     }
9832                     is_utf8 = TRUE;
9833                 }
9834             }
9835
9836         string:
9837             if (has_precis && precis < elen)
9838                 elen = precis;
9839             break;
9840
9841             /* INTEGERS */
9842
9843         case 'p':
9844             if (alt || vectorize)
9845                 goto unknown;
9846             uv = PTR2UV(args ? va_arg(*args, void*) : argsv);
9847             base = 16;
9848             goto integer;
9849
9850         case 'D':
9851 #ifdef IV_IS_QUAD
9852             intsize = 'q';
9853 #else
9854             intsize = 'l';
9855 #endif
9856             /*FALLTHROUGH*/
9857         case 'd':
9858         case 'i':
9859 #if vdNUMBER
9860         format_vd:
9861 #endif
9862             if (vectorize) {
9863                 STRLEN ulen;
9864                 if (!veclen)
9865                     continue;
9866                 if (vec_utf8)
9867                     uv = utf8n_to_uvchr(vecstr, veclen, &ulen,
9868                                         UTF8_ALLOW_ANYUV);
9869                 else {
9870                     uv = *vecstr;
9871                     ulen = 1;
9872                 }
9873                 vecstr += ulen;
9874                 veclen -= ulen;
9875                 if (plus)
9876                      esignbuf[esignlen++] = plus;
9877             }
9878             else if (args) {
9879                 switch (intsize) {
9880                 case 'h':       iv = (short)va_arg(*args, int); break;
9881                 case 'l':       iv = va_arg(*args, long); break;
9882                 case 'V':       iv = va_arg(*args, IV); break;
9883                 default:        iv = va_arg(*args, int); break;
9884                 case 'q':
9885 #ifdef HAS_QUAD
9886                                 iv = va_arg(*args, Quad_t); break;
9887 #else
9888                                 goto unknown;
9889 #endif
9890                 }
9891             }
9892             else {
9893                 IV tiv = SvIV(argsv); /* work around GCC bug #13488 */
9894                 switch (intsize) {
9895                 case 'h':       iv = (short)tiv; break;
9896                 case 'l':       iv = (long)tiv; break;
9897                 case 'V':
9898                 default:        iv = tiv; break;
9899                 case 'q':
9900 #ifdef HAS_QUAD
9901                                 iv = (Quad_t)tiv; break;
9902 #else
9903                                 goto unknown;
9904 #endif
9905                 }
9906             }
9907             if ( !vectorize )   /* we already set uv above */
9908             {
9909                 if (iv >= 0) {
9910                     uv = iv;
9911                     if (plus)
9912                         esignbuf[esignlen++] = plus;
9913                 }
9914                 else {
9915                     uv = -iv;
9916                     esignbuf[esignlen++] = '-';
9917                 }
9918             }
9919             base = 10;
9920             goto integer;
9921
9922         case 'U':
9923 #ifdef IV_IS_QUAD
9924             intsize = 'q';
9925 #else
9926             intsize = 'l';
9927 #endif
9928             /*FALLTHROUGH*/
9929         case 'u':
9930             base = 10;
9931             goto uns_integer;
9932
9933         case 'B':
9934         case 'b':
9935             base = 2;
9936             goto uns_integer;
9937
9938         case 'O':
9939 #ifdef IV_IS_QUAD
9940             intsize = 'q';
9941 #else
9942             intsize = 'l';
9943 #endif
9944             /*FALLTHROUGH*/
9945         case 'o':
9946             base = 8;
9947             goto uns_integer;
9948
9949         case 'X':
9950         case 'x':
9951             base = 16;
9952
9953         uns_integer:
9954             if (vectorize) {
9955                 STRLEN ulen;
9956         vector:
9957                 if (!veclen)
9958                     continue;
9959                 if (vec_utf8)
9960                     uv = utf8n_to_uvchr(vecstr, veclen, &ulen,
9961                                         UTF8_ALLOW_ANYUV);
9962                 else {
9963                     uv = *vecstr;
9964                     ulen = 1;
9965                 }
9966                 vecstr += ulen;
9967                 veclen -= ulen;
9968             }
9969             else if (args) {
9970                 switch (intsize) {
9971                 case 'h':  uv = (unsigned short)va_arg(*args, unsigned); break;
9972                 case 'l':  uv = va_arg(*args, unsigned long); break;
9973                 case 'V':  uv = va_arg(*args, UV); break;
9974                 default:   uv = va_arg(*args, unsigned); break;
9975                 case 'q':
9976 #ifdef HAS_QUAD
9977                            uv = va_arg(*args, Uquad_t); break;
9978 #else
9979                            goto unknown;
9980 #endif
9981                 }
9982             }
9983             else {
9984                 UV tuv = SvUV(argsv); /* work around GCC bug #13488 */
9985                 switch (intsize) {
9986                 case 'h':       uv = (unsigned short)tuv; break;
9987                 case 'l':       uv = (unsigned long)tuv; break;
9988                 case 'V':
9989                 default:        uv = tuv; break;
9990                 case 'q':
9991 #ifdef HAS_QUAD
9992                                 uv = (Uquad_t)tuv; break;
9993 #else
9994                                 goto unknown;
9995 #endif
9996                 }
9997             }
9998
9999         integer:
10000             {
10001                 char *ptr = ebuf + sizeof ebuf;
10002                 bool tempalt = uv ? alt : FALSE; /* Vectors can't change alt */
10003                 zeros = 0;
10004
10005                 switch (base) {
10006                     unsigned dig;
10007                 case 16:
10008                     p = (char *)((c == 'X') ? PL_hexdigit + 16 : PL_hexdigit);
10009                     do {
10010                         dig = uv & 15;
10011                         *--ptr = p[dig];
10012                     } while (uv >>= 4);
10013                     if (tempalt) {
10014                         esignbuf[esignlen++] = '0';
10015                         esignbuf[esignlen++] = c;  /* 'x' or 'X' */
10016                     }
10017                     break;
10018                 case 8:
10019                     do {
10020                         dig = uv & 7;
10021                         *--ptr = '0' + dig;
10022                     } while (uv >>= 3);
10023                     if (alt && *ptr != '0')
10024                         *--ptr = '0';
10025                     break;
10026                 case 2:
10027                     do {
10028                         dig = uv & 1;
10029                         *--ptr = '0' + dig;
10030                     } while (uv >>= 1);
10031                     if (tempalt) {
10032                         esignbuf[esignlen++] = '0';
10033                         esignbuf[esignlen++] = c;
10034                     }
10035                     break;
10036                 default:                /* it had better be ten or less */
10037                     do {
10038                         dig = uv % base;
10039                         *--ptr = '0' + dig;
10040                     } while (uv /= base);
10041                     break;
10042                 }
10043                 elen = (ebuf + sizeof ebuf) - ptr;
10044                 eptr = ptr;
10045                 if (has_precis) {
10046                     if (precis > elen)
10047                         zeros = precis - elen;
10048                     else if (precis == 0 && elen == 1 && *eptr == '0'
10049                              && !(base == 8 && alt)) /* "%#.0o" prints "0" */
10050                         elen = 0;
10051
10052                 /* a precision nullifies the 0 flag. */
10053                     if (fill == '0')
10054                         fill = ' ';
10055                 }
10056             }
10057             break;
10058
10059             /* FLOATING POINT */
10060
10061         case 'F':
10062             c = 'f';            /* maybe %F isn't supported here */
10063             /*FALLTHROUGH*/
10064         case 'e': case 'E':
10065         case 'f':
10066         case 'g': case 'G':
10067             if (vectorize)
10068                 goto unknown;
10069
10070             /* This is evil, but floating point is even more evil */
10071
10072             /* for SV-style calling, we can only get NV
10073                for C-style calling, we assume %f is double;
10074                for simplicity we allow any of %Lf, %llf, %qf for long double
10075             */
10076             switch (intsize) {
10077             case 'V':
10078 #if defined(USE_LONG_DOUBLE)
10079                 intsize = 'q';
10080 #endif
10081                 break;
10082 /* [perl #20339] - we should accept and ignore %lf rather than die */
10083             case 'l':
10084                 /*FALLTHROUGH*/
10085             default:
10086 #if defined(USE_LONG_DOUBLE)
10087                 intsize = args ? 0 : 'q';
10088 #endif
10089                 break;
10090             case 'q':
10091 #if defined(HAS_LONG_DOUBLE)
10092                 break;
10093 #else
10094                 /*FALLTHROUGH*/
10095 #endif
10096             case 'h':
10097                 goto unknown;
10098             }
10099
10100             /* now we need (long double) if intsize == 'q', else (double) */
10101             nv = (args) ?
10102 #if LONG_DOUBLESIZE > DOUBLESIZE
10103                 intsize == 'q' ?
10104                     va_arg(*args, long double) :
10105                     va_arg(*args, double)
10106 #else
10107                     va_arg(*args, double)
10108 #endif
10109                 : SvNV(argsv);
10110
10111             need = 0;
10112             /* nv * 0 will be NaN for NaN, +Inf and -Inf, and 0 for anything
10113                else. frexp() has some unspecified behaviour for those three */
10114             if (c != 'e' && c != 'E' && (nv * 0) == 0) {
10115                 i = PERL_INT_MIN;
10116                 /* FIXME: if HAS_LONG_DOUBLE but not USE_LONG_DOUBLE this
10117                    will cast our (long double) to (double) */
10118                 (void)Perl_frexp(nv, &i);
10119                 if (i == PERL_INT_MIN)
10120                     Perl_die(aTHX_ "panic: frexp");
10121                 if (i > 0)
10122                     need = BIT_DIGITS(i);
10123             }
10124             need += has_precis ? precis : 6; /* known default */
10125
10126             if (need < width)
10127                 need = width;
10128
10129 #ifdef HAS_LDBL_SPRINTF_BUG
10130             /* This is to try to fix a bug with irix/nonstop-ux/powerux and
10131                with sfio - Allen <allens@cpan.org> */
10132
10133 #  ifdef DBL_MAX
10134 #    define MY_DBL_MAX DBL_MAX
10135 #  else /* XXX guessing! HUGE_VAL may be defined as infinity, so not using */
10136 #    if DOUBLESIZE >= 8
10137 #      define MY_DBL_MAX 1.7976931348623157E+308L
10138 #    else
10139 #      define MY_DBL_MAX 3.40282347E+38L
10140 #    endif
10141 #  endif
10142
10143 #  ifdef HAS_LDBL_SPRINTF_BUG_LESS1 /* only between -1L & 1L - Allen */
10144 #    define MY_DBL_MAX_BUG 1L
10145 #  else
10146 #    define MY_DBL_MAX_BUG MY_DBL_MAX
10147 #  endif
10148
10149 #  ifdef DBL_MIN
10150 #    define MY_DBL_MIN DBL_MIN
10151 #  else  /* XXX guessing! -Allen */
10152 #    if DOUBLESIZE >= 8
10153 #      define MY_DBL_MIN 2.2250738585072014E-308L
10154 #    else
10155 #      define MY_DBL_MIN 1.17549435E-38L
10156 #    endif
10157 #  endif
10158
10159             if ((intsize == 'q') && (c == 'f') &&
10160                 ((nv < MY_DBL_MAX_BUG) && (nv > -MY_DBL_MAX_BUG)) &&
10161                 (need < DBL_DIG)) {
10162                 /* it's going to be short enough that
10163                  * long double precision is not needed */
10164
10165                 if ((nv <= 0L) && (nv >= -0L))
10166                     fix_ldbl_sprintf_bug = TRUE; /* 0 is 0 - easiest */
10167                 else {
10168                     /* would use Perl_fp_class as a double-check but not
10169                      * functional on IRIX - see perl.h comments */
10170
10171                     if ((nv >= MY_DBL_MIN) || (nv <= -MY_DBL_MIN)) {
10172                         /* It's within the range that a double can represent */
10173 #if defined(DBL_MAX) && !defined(DBL_MIN)
10174                         if ((nv >= ((long double)1/DBL_MAX)) ||
10175                             (nv <= (-(long double)1/DBL_MAX)))
10176 #endif
10177                         fix_ldbl_sprintf_bug = TRUE;
10178                     }
10179                 }
10180                 if (fix_ldbl_sprintf_bug == TRUE) {
10181                     double temp;
10182
10183                     intsize = 0;
10184                     temp = (double)nv;
10185                     nv = (NV)temp;
10186                 }
10187             }
10188
10189 #  undef MY_DBL_MAX
10190 #  undef MY_DBL_MAX_BUG
10191 #  undef MY_DBL_MIN
10192
10193 #endif /* HAS_LDBL_SPRINTF_BUG */
10194
10195             need += 20; /* fudge factor */
10196             if (PL_efloatsize < need) {
10197                 Safefree(PL_efloatbuf);
10198                 PL_efloatsize = need + 20; /* more fudge */
10199                 Newx(PL_efloatbuf, PL_efloatsize, char);
10200                 PL_efloatbuf[0] = '\0';
10201             }
10202
10203             if ( !(width || left || plus || alt) && fill != '0'
10204                  && has_precis && intsize != 'q' ) {    /* Shortcuts */
10205                 /* See earlier comment about buggy Gconvert when digits,
10206                    aka precis is 0  */
10207                 if ( c == 'g' && precis) {
10208                     Gconvert((NV)nv, (int)precis, 0, PL_efloatbuf);
10209                     /* May return an empty string for digits==0 */
10210                     if (*PL_efloatbuf) {
10211                         elen = strlen(PL_efloatbuf);
10212                         goto float_converted;
10213                     }
10214                 } else if ( c == 'f' && !precis) {
10215                     if ((eptr = F0convert(nv, ebuf + sizeof ebuf, &elen)))
10216                         break;
10217                 }
10218             }
10219             {
10220                 char *ptr = ebuf + sizeof ebuf;
10221                 *--ptr = '\0';
10222                 *--ptr = c;
10223                 /* FIXME: what to do if HAS_LONG_DOUBLE but not PERL_PRIfldbl? */
10224 #if defined(HAS_LONG_DOUBLE) && defined(PERL_PRIfldbl)
10225                 if (intsize == 'q') {
10226                     /* Copy the one or more characters in a long double
10227                      * format before the 'base' ([efgEFG]) character to
10228                      * the format string. */
10229                     static char const prifldbl[] = PERL_PRIfldbl;
10230                     char const *p = prifldbl + sizeof(prifldbl) - 3;
10231                     while (p >= prifldbl) { *--ptr = *p--; }
10232                 }
10233 #endif
10234                 if (has_precis) {
10235                     base = precis;
10236                     do { *--ptr = '0' + (base % 10); } while (base /= 10);
10237                     *--ptr = '.';
10238                 }
10239                 if (width) {
10240                     base = width;
10241                     do { *--ptr = '0' + (base % 10); } while (base /= 10);
10242                 }
10243                 if (fill == '0')
10244                     *--ptr = fill;
10245                 if (left)
10246                     *--ptr = '-';
10247                 if (plus)
10248                     *--ptr = plus;
10249                 if (alt)
10250                     *--ptr = '#';
10251                 *--ptr = '%';
10252
10253                 /* No taint.  Otherwise we are in the strange situation
10254                  * where printf() taints but print($float) doesn't.
10255                  * --jhi */
10256 #if defined(HAS_LONG_DOUBLE)
10257                 elen = ((intsize == 'q')
10258                         ? my_snprintf(PL_efloatbuf, PL_efloatsize, ptr, nv)
10259                         : my_snprintf(PL_efloatbuf, PL_efloatsize, ptr, (double)nv));
10260 #else
10261                 elen = my_sprintf(PL_efloatbuf, ptr, nv);
10262 #endif
10263             }
10264         float_converted:
10265             eptr = PL_efloatbuf;
10266             break;
10267
10268             /* SPECIAL */
10269
10270         case 'n':
10271             if (vectorize)
10272                 goto unknown;
10273             i = SvCUR(sv) - origlen;
10274             if (args) {
10275                 switch (intsize) {
10276                 case 'h':       *(va_arg(*args, short*)) = i; break;
10277                 default:        *(va_arg(*args, int*)) = i; break;
10278                 case 'l':       *(va_arg(*args, long*)) = i; break;
10279                 case 'V':       *(va_arg(*args, IV*)) = i; break;
10280                 case 'q':
10281 #ifdef HAS_QUAD
10282                                 *(va_arg(*args, Quad_t*)) = i; break;
10283 #else
10284                                 goto unknown;
10285 #endif
10286                 }
10287             }
10288             else
10289                 sv_setuv_mg(argsv, (UV)i);
10290             continue;   /* not "break" */
10291
10292             /* UNKNOWN */
10293
10294         default:
10295       unknown:
10296             if (!args
10297                 && (PL_op->op_type == OP_PRTF || PL_op->op_type == OP_SPRINTF)
10298                 && ckWARN(WARN_PRINTF))
10299             {
10300                 SV * const msg = sv_newmortal();
10301                 Perl_sv_setpvf(aTHX_ msg, "Invalid conversion in %sprintf: ",
10302                           (PL_op->op_type == OP_PRTF) ? "" : "s");
10303                 if (fmtstart < patend) {
10304                     const char * const fmtend = q < patend ? q : patend;
10305                     const char * f;
10306                     sv_catpvs(msg, "\"%");
10307                     for (f = fmtstart; f < fmtend; f++) {
10308                         if (isPRINT(*f)) {
10309                             sv_catpvn(msg, f, 1);
10310                         } else {
10311                             Perl_sv_catpvf(aTHX_ msg,
10312                                            "\\%03"UVof, (UV)*f & 0xFF);
10313                         }
10314                     }
10315                     sv_catpvs(msg, "\"");
10316                 } else {
10317                     sv_catpvs(msg, "end of string");
10318                 }
10319                 Perl_warner(aTHX_ packWARN(WARN_PRINTF), "%"SVf, SVfARG(msg)); /* yes, this is reentrant */
10320             }
10321
10322             /* output mangled stuff ... */
10323             if (c == '\0')
10324                 --q;
10325             eptr = p;
10326             elen = q - p;
10327
10328             /* ... right here, because formatting flags should not apply */
10329             SvGROW(sv, SvCUR(sv) + elen + 1);
10330             p = SvEND(sv);
10331             Copy(eptr, p, elen, char);
10332             p += elen;
10333             *p = '\0';
10334             SvCUR_set(sv, p - SvPVX_const(sv));
10335             svix = osvix;
10336             continue;   /* not "break" */
10337         }
10338
10339         if (is_utf8 != has_utf8) {
10340             if (is_utf8) {
10341                 if (SvCUR(sv))
10342                     sv_utf8_upgrade(sv);
10343             }
10344             else {
10345                 const STRLEN old_elen = elen;
10346                 SV * const nsv = newSVpvn_flags(eptr, elen, SVs_TEMP);
10347                 sv_utf8_upgrade(nsv);
10348                 eptr = SvPVX_const(nsv);
10349                 elen = SvCUR(nsv);
10350
10351                 if (width) { /* fudge width (can't fudge elen) */
10352                     width += elen - old_elen;
10353                 }
10354                 is_utf8 = TRUE;
10355             }
10356         }
10357
10358         have = esignlen + zeros + elen;
10359         if (have < zeros)
10360             Perl_croak_nocontext("%s", PL_memory_wrap);
10361
10362         need = (have > width ? have : width);
10363         gap = need - have;
10364
10365         if (need >= (((STRLEN)~0) - SvCUR(sv) - dotstrlen - 1))
10366             Perl_croak_nocontext("%s", PL_memory_wrap);
10367         SvGROW(sv, SvCUR(sv) + need + dotstrlen + 1);
10368         p = SvEND(sv);
10369         if (esignlen && fill == '0') {
10370             int i;
10371             for (i = 0; i < (int)esignlen; i++)
10372                 *p++ = esignbuf[i];
10373         }
10374         if (gap && !left) {
10375             memset(p, fill, gap);
10376             p += gap;
10377         }
10378         if (esignlen && fill != '0') {
10379             int i;
10380             for (i = 0; i < (int)esignlen; i++)
10381                 *p++ = esignbuf[i];
10382         }
10383         if (zeros) {
10384             int i;
10385             for (i = zeros; i; i--)
10386                 *p++ = '0';
10387         }
10388         if (elen) {
10389             Copy(eptr, p, elen, char);
10390             p += elen;
10391         }
10392         if (gap && left) {
10393             memset(p, ' ', gap);
10394             p += gap;
10395         }
10396         if (vectorize) {
10397             if (veclen) {
10398                 Copy(dotstr, p, dotstrlen, char);
10399                 p += dotstrlen;
10400             }
10401             else
10402                 vectorize = FALSE;              /* done iterating over vecstr */
10403         }
10404         if (is_utf8)
10405             has_utf8 = TRUE;
10406         if (has_utf8)
10407             SvUTF8_on(sv);
10408         *p = '\0';
10409         SvCUR_set(sv, p - SvPVX_const(sv));
10410         if (vectorize) {
10411             esignlen = 0;
10412             goto vector;
10413         }
10414     }
10415     SvTAINT(sv);
10416 }
10417
10418 /* =========================================================================
10419
10420 =head1 Cloning an interpreter
10421
10422 All the macros and functions in this section are for the private use of
10423 the main function, perl_clone().
10424
10425 The foo_dup() functions make an exact copy of an existing foo thingy.
10426 During the course of a cloning, a hash table is used to map old addresses
10427 to new addresses. The table is created and manipulated with the
10428 ptr_table_* functions.
10429
10430 =cut
10431
10432  * =========================================================================*/
10433
10434
10435 #if defined(USE_ITHREADS)
10436
10437 /* XXX Remove this so it doesn't have to go thru the macro and return for nothing */
10438 #ifndef GpREFCNT_inc
10439 #  define GpREFCNT_inc(gp)      ((gp) ? (++(gp)->gp_refcnt, (gp)) : (GP*)NULL)
10440 #endif
10441
10442
10443 /* Certain cases in Perl_ss_dup have been merged, by relying on the fact
10444    that currently av_dup, gv_dup and hv_dup are the same as sv_dup.
10445    If this changes, please unmerge ss_dup.
10446    Likewise, sv_dup_inc_multiple() relies on this fact.  */
10447 #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
10448 #define sv_dup_inc_NN(s,t)      SvREFCNT_inc_NN(sv_dup(s,t))
10449 #define av_dup(s,t)     MUTABLE_AV(sv_dup((const SV *)s,t))
10450 #define av_dup_inc(s,t) MUTABLE_AV(SvREFCNT_inc(sv_dup((const SV *)s,t)))
10451 #define hv_dup(s,t)     MUTABLE_HV(sv_dup((const SV *)s,t))
10452 #define hv_dup_inc(s,t) MUTABLE_HV(SvREFCNT_inc(sv_dup((const SV *)s,t)))
10453 #define cv_dup(s,t)     MUTABLE_CV(sv_dup((const SV *)s,t))
10454 #define cv_dup_inc(s,t) MUTABLE_CV(SvREFCNT_inc(sv_dup((const SV *)s,t)))
10455 #define io_dup(s,t)     MUTABLE_IO(sv_dup((const SV *)s,t))
10456 #define io_dup_inc(s,t) MUTABLE_IO(SvREFCNT_inc(sv_dup((const SV *)s,t)))
10457 #define gv_dup(s,t)     MUTABLE_GV(sv_dup((const SV *)s,t))
10458 #define gv_dup_inc(s,t) MUTABLE_GV(SvREFCNT_inc(sv_dup((const SV *)s,t)))
10459 #define SAVEPV(p)       ((p) ? savepv(p) : NULL)
10460 #define SAVEPVN(p,n)    ((p) ? savepvn(p,n) : NULL)
10461
10462 /* clone a parser */
10463
10464 yy_parser *
10465 Perl_parser_dup(pTHX_ const yy_parser *const proto, CLONE_PARAMS *const param)
10466 {
10467     yy_parser *parser;
10468
10469     PERL_ARGS_ASSERT_PARSER_DUP;
10470
10471     if (!proto)
10472         return NULL;
10473
10474     /* look for it in the table first */
10475     parser = (yy_parser *)ptr_table_fetch(PL_ptr_table, proto);
10476     if (parser)
10477         return parser;
10478
10479     /* create anew and remember what it is */
10480     Newxz(parser, 1, yy_parser);
10481     ptr_table_store(PL_ptr_table, proto, parser);
10482
10483     parser->yyerrstatus = 0;
10484     parser->yychar = YYEMPTY;           /* Cause a token to be read.  */
10485
10486     /* XXX these not yet duped */
10487     parser->old_parser = NULL;
10488     parser->stack = NULL;
10489     parser->ps = NULL;
10490     parser->stack_size = 0;
10491     /* XXX parser->stack->state = 0; */
10492
10493     /* XXX eventually, just Copy() most of the parser struct ? */
10494
10495     parser->lex_brackets = proto->lex_brackets;
10496     parser->lex_casemods = proto->lex_casemods;
10497     parser->lex_brackstack = savepvn(proto->lex_brackstack,
10498                     (proto->lex_brackets < 120 ? 120 : proto->lex_brackets));
10499     parser->lex_casestack = savepvn(proto->lex_casestack,
10500                     (proto->lex_casemods < 12 ? 12 : proto->lex_casemods));
10501     parser->lex_defer   = proto->lex_defer;
10502     parser->lex_dojoin  = proto->lex_dojoin;
10503     parser->lex_expect  = proto->lex_expect;
10504     parser->lex_formbrack = proto->lex_formbrack;
10505     parser->lex_inpat   = proto->lex_inpat;
10506     parser->lex_inwhat  = proto->lex_inwhat;
10507     parser->lex_op      = proto->lex_op;
10508     parser->lex_repl    = sv_dup_inc(proto->lex_repl, param);
10509     parser->lex_starts  = proto->lex_starts;
10510     parser->lex_stuff   = sv_dup_inc(proto->lex_stuff, param);
10511     parser->multi_close = proto->multi_close;
10512     parser->multi_open  = proto->multi_open;
10513     parser->multi_start = proto->multi_start;
10514     parser->multi_end   = proto->multi_end;
10515     parser->pending_ident = proto->pending_ident;
10516     parser->preambled   = proto->preambled;
10517     parser->sublex_info = proto->sublex_info; /* XXX not quite right */
10518     parser->linestr     = sv_dup_inc(proto->linestr, param);
10519     parser->expect      = proto->expect;
10520     parser->copline     = proto->copline;
10521     parser->last_lop_op = proto->last_lop_op;
10522     parser->lex_state   = proto->lex_state;
10523     parser->rsfp        = fp_dup(proto->rsfp, '<', param);
10524     /* rsfp_filters entries have fake IoDIRP() */
10525     parser->rsfp_filters= av_dup_inc(proto->rsfp_filters, param);
10526     parser->in_my       = proto->in_my;
10527     parser->in_my_stash = hv_dup(proto->in_my_stash, param);
10528     parser->error_count = proto->error_count;
10529
10530
10531     parser->linestr     = sv_dup_inc(proto->linestr, param);
10532
10533     {
10534         char * const ols = SvPVX(proto->linestr);
10535         char * const ls  = SvPVX(parser->linestr);
10536
10537         parser->bufptr      = ls + (proto->bufptr >= ols ?
10538                                     proto->bufptr -  ols : 0);
10539         parser->oldbufptr   = ls + (proto->oldbufptr >= ols ?
10540                                     proto->oldbufptr -  ols : 0);
10541         parser->oldoldbufptr= ls + (proto->oldoldbufptr >= ols ?
10542                                     proto->oldoldbufptr -  ols : 0);
10543         parser->linestart   = ls + (proto->linestart >= ols ?
10544                                     proto->linestart -  ols : 0);
10545         parser->last_uni    = ls + (proto->last_uni >= ols ?
10546                                     proto->last_uni -  ols : 0);
10547         parser->last_lop    = ls + (proto->last_lop >= ols ?
10548                                     proto->last_lop -  ols : 0);
10549
10550         parser->bufend      = ls + SvCUR(parser->linestr);
10551     }
10552
10553     Copy(proto->tokenbuf, parser->tokenbuf, 256, char);
10554
10555
10556 #ifdef PERL_MAD
10557     parser->endwhite    = proto->endwhite;
10558     parser->faketokens  = proto->faketokens;
10559     parser->lasttoke    = proto->lasttoke;
10560     parser->nextwhite   = proto->nextwhite;
10561     parser->realtokenstart = proto->realtokenstart;
10562     parser->skipwhite   = proto->skipwhite;
10563     parser->thisclose   = proto->thisclose;
10564     parser->thismad     = proto->thismad;
10565     parser->thisopen    = proto->thisopen;
10566     parser->thisstuff   = proto->thisstuff;
10567     parser->thistoken   = proto->thistoken;
10568     parser->thiswhite   = proto->thiswhite;
10569
10570     Copy(proto->nexttoke, parser->nexttoke, 5, NEXTTOKE);
10571     parser->curforce    = proto->curforce;
10572 #else
10573     Copy(proto->nextval, parser->nextval, 5, YYSTYPE);
10574     Copy(proto->nexttype, parser->nexttype, 5,  I32);
10575     parser->nexttoke    = proto->nexttoke;
10576 #endif
10577
10578     /* XXX should clone saved_curcop here, but we aren't passed
10579      * proto_perl; so do it in perl_clone_using instead */
10580
10581     return parser;
10582 }
10583
10584
10585 /* duplicate a file handle */
10586
10587 PerlIO *
10588 Perl_fp_dup(pTHX_ PerlIO *const fp, const char type, CLONE_PARAMS *const param)
10589 {
10590     PerlIO *ret;
10591
10592     PERL_ARGS_ASSERT_FP_DUP;
10593     PERL_UNUSED_ARG(type);
10594
10595     if (!fp)
10596         return (PerlIO*)NULL;
10597
10598     /* look for it in the table first */
10599     ret = (PerlIO*)ptr_table_fetch(PL_ptr_table, fp);
10600     if (ret)
10601         return ret;
10602
10603     /* create anew and remember what it is */
10604     ret = PerlIO_fdupopen(aTHX_ fp, param, PERLIO_DUP_CLONE);
10605     ptr_table_store(PL_ptr_table, fp, ret);
10606     return ret;
10607 }
10608
10609 /* duplicate a directory handle */
10610
10611 DIR *
10612 Perl_dirp_dup(pTHX_ DIR *const dp)
10613 {
10614     PERL_UNUSED_CONTEXT;
10615     if (!dp)
10616         return (DIR*)NULL;
10617     /* XXX TODO */
10618     return dp;
10619 }
10620
10621 /* duplicate a typeglob */
10622
10623 GP *
10624 Perl_gp_dup(pTHX_ GP *const gp, CLONE_PARAMS *const param)
10625 {
10626     GP *ret;
10627
10628     PERL_ARGS_ASSERT_GP_DUP;
10629
10630     if (!gp)
10631         return (GP*)NULL;
10632     /* look for it in the table first */
10633     ret = (GP*)ptr_table_fetch(PL_ptr_table, gp);
10634     if (ret)
10635         return ret;
10636
10637     /* create anew and remember what it is */
10638     Newxz(ret, 1, GP);
10639     ptr_table_store(PL_ptr_table, gp, ret);
10640
10641     /* clone */
10642     /* ret->gp_refcnt must be 0 before any other dups are called. We're relying
10643        on Newxz() to do this for us.  */
10644     ret->gp_sv          = sv_dup_inc(gp->gp_sv, param);
10645     ret->gp_io          = io_dup_inc(gp->gp_io, param);
10646     ret->gp_form        = cv_dup_inc(gp->gp_form, param);
10647     ret->gp_av          = av_dup_inc(gp->gp_av, param);
10648     ret->gp_hv          = hv_dup_inc(gp->gp_hv, param);
10649     ret->gp_egv = gv_dup(gp->gp_egv, param);/* GvEGV is not refcounted */
10650     ret->gp_cv          = cv_dup_inc(gp->gp_cv, param);
10651     ret->gp_cvgen       = gp->gp_cvgen;
10652     ret->gp_line        = gp->gp_line;
10653     ret->gp_file_hek    = hek_dup(gp->gp_file_hek, param);
10654     return ret;
10655 }
10656
10657 /* duplicate a chain of magic */
10658
10659 MAGIC *
10660 Perl_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *const param)
10661 {
10662     MAGIC *mgret = NULL;
10663     MAGIC **mgprev_p = &mgret;
10664
10665     PERL_ARGS_ASSERT_MG_DUP;
10666
10667     for (; mg; mg = mg->mg_moremagic) {
10668         MAGIC *nmg;
10669         Newx(nmg, 1, MAGIC);
10670         *mgprev_p = nmg;
10671         mgprev_p = &(nmg->mg_moremagic);
10672
10673         /* There was a comment "XXX copy dynamic vtable?" but as we don't have
10674            dynamic vtables, I'm not sure why Sarathy wrote it. The comment dates
10675            from the original commit adding Perl_mg_dup() - revision 4538.
10676            Similarly there is the annotation "XXX random ptr?" next to the
10677            assignment to nmg->mg_ptr.  */
10678         *nmg = *mg;
10679
10680         /* FIXME for plugins
10681         if (nmg->mg_type == PERL_MAGIC_qr) {
10682             nmg->mg_obj = MUTABLE_SV(CALLREGDUPE((REGEXP*)nmg->mg_obj, param));
10683         }
10684         else
10685         */
10686         if(nmg->mg_type == PERL_MAGIC_backref) {
10687             /* The backref AV has its reference count deliberately bumped by
10688                1.  */
10689             nmg->mg_obj
10690                 = SvREFCNT_inc(av_dup_inc((const AV *) nmg->mg_obj, param));
10691         }
10692         else {
10693             nmg->mg_obj = (nmg->mg_flags & MGf_REFCOUNTED)
10694                               ? sv_dup_inc(nmg->mg_obj, param)
10695                               : sv_dup(nmg->mg_obj, param);
10696         }
10697
10698         if (nmg->mg_ptr && nmg->mg_type != PERL_MAGIC_regex_global) {
10699             if (nmg->mg_len > 0) {
10700                 nmg->mg_ptr     = SAVEPVN(nmg->mg_ptr, nmg->mg_len);
10701                 if (nmg->mg_type == PERL_MAGIC_overload_table &&
10702                         AMT_AMAGIC((AMT*)nmg->mg_ptr))
10703                 {
10704                     AMT * const namtp = (AMT*)nmg->mg_ptr;
10705                     sv_dup_inc_multiple((SV**)(namtp->table),
10706                                         (SV**)(namtp->table), NofAMmeth, param);
10707                 }
10708             }
10709             else if (nmg->mg_len == HEf_SVKEY)
10710                 nmg->mg_ptr = (char*)sv_dup_inc((const SV *)nmg->mg_ptr, param);
10711         }
10712         if ((nmg->mg_flags & MGf_DUP) && nmg->mg_virtual && nmg->mg_virtual->svt_dup) {
10713             CALL_FPTR(nmg->mg_virtual->svt_dup)(aTHX_ nmg, param);
10714         }
10715     }
10716     return mgret;
10717 }
10718
10719 #endif /* USE_ITHREADS */
10720
10721 struct ptr_tbl_arena {
10722     struct ptr_tbl_arena *next;
10723     struct ptr_tbl_ent array[1023/3]; /* as ptr_tbl_ent has 3 pointers.  */
10724 };
10725
10726 /* create a new pointer-mapping table */
10727
10728 PTR_TBL_t *
10729 Perl_ptr_table_new(pTHX)
10730 {
10731     PTR_TBL_t *tbl;
10732     PERL_UNUSED_CONTEXT;
10733
10734     Newx(tbl, 1, PTR_TBL_t);
10735     tbl->tbl_max        = 511;
10736     tbl->tbl_items      = 0;
10737     tbl->tbl_arena      = NULL;
10738     tbl->tbl_arena_next = NULL;
10739     tbl->tbl_arena_end  = NULL;
10740     Newxz(tbl->tbl_ary, tbl->tbl_max + 1, PTR_TBL_ENT_t*);
10741     return tbl;
10742 }
10743
10744 #define PTR_TABLE_HASH(ptr) \
10745   ((PTR2UV(ptr) >> 3) ^ (PTR2UV(ptr) >> (3 + 7)) ^ (PTR2UV(ptr) >> (3 + 17)))
10746
10747 /* map an existing pointer using a table */
10748
10749 STATIC PTR_TBL_ENT_t *
10750 S_ptr_table_find(PTR_TBL_t *const tbl, const void *const sv)
10751 {
10752     PTR_TBL_ENT_t *tblent;
10753     const UV hash = PTR_TABLE_HASH(sv);
10754
10755     PERL_ARGS_ASSERT_PTR_TABLE_FIND;
10756
10757     tblent = tbl->tbl_ary[hash & tbl->tbl_max];
10758     for (; tblent; tblent = tblent->next) {
10759         if (tblent->oldval == sv)
10760             return tblent;
10761     }
10762     return NULL;
10763 }
10764
10765 void *
10766 Perl_ptr_table_fetch(pTHX_ PTR_TBL_t *const tbl, const void *const sv)
10767 {
10768     PTR_TBL_ENT_t const *const tblent = ptr_table_find(tbl, sv);
10769
10770     PERL_ARGS_ASSERT_PTR_TABLE_FETCH;
10771     PERL_UNUSED_CONTEXT;
10772
10773     return tblent ? tblent->newval : NULL;
10774 }
10775
10776 /* add a new entry to a pointer-mapping table */
10777
10778 void
10779 Perl_ptr_table_store(pTHX_ PTR_TBL_t *const tbl, const void *const oldsv, void *const newsv)
10780 {
10781     PTR_TBL_ENT_t *tblent = ptr_table_find(tbl, oldsv);
10782
10783     PERL_ARGS_ASSERT_PTR_TABLE_STORE;
10784     PERL_UNUSED_CONTEXT;
10785
10786     if (tblent) {
10787         tblent->newval = newsv;
10788     } else {
10789         const UV entry = PTR_TABLE_HASH(oldsv) & tbl->tbl_max;
10790
10791         if (tbl->tbl_arena_next == tbl->tbl_arena_end) {
10792             struct ptr_tbl_arena *new_arena;
10793
10794             Newx(new_arena, 1, struct ptr_tbl_arena);
10795             new_arena->next = tbl->tbl_arena;
10796             tbl->tbl_arena = new_arena;
10797             tbl->tbl_arena_next = new_arena->array;
10798             tbl->tbl_arena_end = new_arena->array
10799                 + sizeof(new_arena->array) / sizeof(new_arena->array[0]);
10800         }
10801
10802         tblent = tbl->tbl_arena_next++;
10803
10804         tblent->oldval = oldsv;
10805         tblent->newval = newsv;
10806         tblent->next = tbl->tbl_ary[entry];
10807         tbl->tbl_ary[entry] = tblent;
10808         tbl->tbl_items++;
10809         if (tblent->next && tbl->tbl_items > tbl->tbl_max)
10810             ptr_table_split(tbl);
10811     }
10812 }
10813
10814 /* double the hash bucket size of an existing ptr table */
10815
10816 void
10817 Perl_ptr_table_split(pTHX_ PTR_TBL_t *const tbl)
10818 {
10819     PTR_TBL_ENT_t **ary = tbl->tbl_ary;
10820     const UV oldsize = tbl->tbl_max + 1;
10821     UV newsize = oldsize * 2;
10822     UV i;
10823
10824     PERL_ARGS_ASSERT_PTR_TABLE_SPLIT;
10825     PERL_UNUSED_CONTEXT;
10826
10827     Renew(ary, newsize, PTR_TBL_ENT_t*);
10828     Zero(&ary[oldsize], newsize-oldsize, PTR_TBL_ENT_t*);
10829     tbl->tbl_max = --newsize;
10830     tbl->tbl_ary = ary;
10831     for (i=0; i < oldsize; i++, ary++) {
10832         PTR_TBL_ENT_t **curentp, **entp, *ent;
10833         if (!*ary)
10834             continue;
10835         curentp = ary + oldsize;
10836         for (entp = ary, ent = *ary; ent; ent = *entp) {
10837             if ((newsize & PTR_TABLE_HASH(ent->oldval)) != i) {
10838                 *entp = ent->next;
10839                 ent->next = *curentp;
10840                 *curentp = ent;
10841                 continue;
10842             }
10843             else
10844                 entp = &ent->next;
10845         }
10846     }
10847 }
10848
10849 /* remove all the entries from a ptr table */
10850 /* Deprecated - will be removed post 5.14 */
10851
10852 void
10853 Perl_ptr_table_clear(pTHX_ PTR_TBL_t *const tbl)
10854 {
10855     if (tbl && tbl->tbl_items) {
10856         struct ptr_tbl_arena *arena = tbl->tbl_arena;
10857
10858         Zero(tbl->tbl_ary, tbl->tbl_max + 1, struct ptr_tbl_ent **);
10859
10860         while (arena) {
10861             struct ptr_tbl_arena *next = arena->next;
10862
10863             Safefree(arena);
10864             arena = next;
10865         };
10866
10867         tbl->tbl_items = 0;
10868         tbl->tbl_arena = NULL;
10869         tbl->tbl_arena_next = NULL;
10870         tbl->tbl_arena_end = NULL;
10871     }
10872 }
10873
10874 /* clear and free a ptr table */
10875
10876 void
10877 Perl_ptr_table_free(pTHX_ PTR_TBL_t *const tbl)
10878 {
10879     struct ptr_tbl_arena *arena;
10880
10881     if (!tbl) {
10882         return;
10883     }
10884
10885     arena = tbl->tbl_arena;
10886
10887     while (arena) {
10888         struct ptr_tbl_arena *next = arena->next;
10889
10890         Safefree(arena);
10891         arena = next;
10892     }
10893
10894     Safefree(tbl->tbl_ary);
10895     Safefree(tbl);
10896 }
10897
10898 #if defined(USE_ITHREADS)
10899
10900 void
10901 Perl_rvpv_dup(pTHX_ SV *const dstr, const SV *const sstr, CLONE_PARAMS *const param)
10902 {
10903     PERL_ARGS_ASSERT_RVPV_DUP;
10904
10905     if (SvROK(sstr)) {
10906         SvRV_set(dstr, SvWEAKREF(sstr)
10907                        ? sv_dup(SvRV_const(sstr), param)
10908                        : sv_dup_inc(SvRV_const(sstr), param));
10909
10910     }
10911     else if (SvPVX_const(sstr)) {
10912         /* Has something there */
10913         if (SvLEN(sstr)) {
10914             /* Normal PV - clone whole allocated space */
10915             SvPV_set(dstr, SAVEPVN(SvPVX_const(sstr), SvLEN(sstr)-1));
10916             if (SvREADONLY(sstr) && SvFAKE(sstr)) {
10917                 /* Not that normal - actually sstr is copy on write.
10918                    But we are a true, independant SV, so:  */
10919                 SvREADONLY_off(dstr);
10920                 SvFAKE_off(dstr);
10921             }
10922         }
10923         else {
10924             /* Special case - not normally malloced for some reason */
10925             if (isGV_with_GP(sstr)) {
10926                 /* Don't need to do anything here.  */
10927             }
10928             else if ((SvREADONLY(sstr) && SvFAKE(sstr))) {
10929                 /* A "shared" PV - clone it as "shared" PV */
10930                 SvPV_set(dstr,
10931                          HEK_KEY(hek_dup(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)),
10932                                          param)));
10933             }
10934             else {
10935                 /* Some other special case - random pointer */
10936                 SvPV_set(dstr, (char *) SvPVX_const(sstr));             
10937             }
10938         }
10939     }
10940     else {
10941         /* Copy the NULL */
10942         SvPV_set(dstr, NULL);
10943     }
10944 }
10945
10946 /* duplicate a list of SVs. source and dest may point to the same memory.  */
10947 static SV **
10948 S_sv_dup_inc_multiple(pTHX_ SV *const *source, SV **dest,
10949                       SSize_t items, CLONE_PARAMS *const param)
10950 {
10951     PERL_ARGS_ASSERT_SV_DUP_INC_MULTIPLE;
10952
10953     while (items-- > 0) {
10954         *dest++ = sv_dup_inc(*source++, param);
10955     }
10956
10957     return dest;
10958 }
10959
10960 /* duplicate an SV of any type (including AV, HV etc) */
10961
10962 SV *
10963 Perl_sv_dup(pTHX_ const SV *const sstr, CLONE_PARAMS *const param)
10964 {
10965     dVAR;
10966     SV *dstr;
10967
10968     PERL_ARGS_ASSERT_SV_DUP;
10969
10970     if (!sstr)
10971         return NULL;
10972     if (SvTYPE(sstr) == SVTYPEMASK) {
10973 #ifdef DEBUG_LEAKING_SCALARS_ABORT
10974         abort();
10975 #endif
10976         return NULL;
10977     }
10978     /* look for it in the table first */
10979     dstr = MUTABLE_SV(ptr_table_fetch(PL_ptr_table, sstr));
10980     if (dstr)
10981         return dstr;
10982
10983     if(param->flags & CLONEf_JOIN_IN) {
10984         /** We are joining here so we don't want do clone
10985             something that is bad **/
10986         if (SvTYPE(sstr) == SVt_PVHV) {
10987             const HEK * const hvname = HvNAME_HEK(sstr);
10988             if (hvname)
10989                 /** don't clone stashes if they already exist **/
10990                 return MUTABLE_SV(gv_stashpvn(HEK_KEY(hvname), HEK_LEN(hvname), 0));
10991         }
10992     }
10993
10994     /* create anew and remember what it is */
10995     new_SV(dstr);
10996
10997 #ifdef DEBUG_LEAKING_SCALARS
10998     dstr->sv_debug_optype = sstr->sv_debug_optype;
10999     dstr->sv_debug_line = sstr->sv_debug_line;
11000     dstr->sv_debug_inpad = sstr->sv_debug_inpad;
11001     dstr->sv_debug_cloned = 1;
11002     dstr->sv_debug_file = savepv(sstr->sv_debug_file);
11003 #endif
11004
11005     ptr_table_store(PL_ptr_table, sstr, dstr);
11006
11007     /* clone */
11008     SvFLAGS(dstr)       = SvFLAGS(sstr);
11009     SvFLAGS(dstr)       &= ~SVf_OOK;            /* don't propagate OOK hack */
11010     SvREFCNT(dstr)      = 0;                    /* must be before any other dups! */
11011
11012 #ifdef DEBUGGING
11013     if (SvANY(sstr) && PL_watch_pvx && SvPVX_const(sstr) == PL_watch_pvx)
11014         PerlIO_printf(Perl_debug_log, "watch at %p hit, found string \"%s\"\n",
11015                       (void*)PL_watch_pvx, SvPVX_const(sstr));
11016 #endif
11017
11018     /* don't clone objects whose class has asked us not to */
11019     if (SvOBJECT(sstr) && ! (SvFLAGS(SvSTASH(sstr)) & SVphv_CLONEABLE)) {
11020         SvFLAGS(dstr) = 0;
11021         return dstr;
11022     }
11023
11024     switch (SvTYPE(sstr)) {
11025     case SVt_NULL:
11026         SvANY(dstr)     = NULL;
11027         break;
11028     case SVt_IV:
11029         SvANY(dstr)     = (XPVIV*)((char*)&(dstr->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
11030         if(SvROK(sstr)) {
11031             Perl_rvpv_dup(aTHX_ dstr, sstr, param);
11032         } else {
11033             SvIV_set(dstr, SvIVX(sstr));
11034         }
11035         break;
11036     case SVt_NV:
11037         SvANY(dstr)     = new_XNV();
11038         SvNV_set(dstr, SvNVX(sstr));
11039         break;
11040         /* case SVt_BIND: */
11041     default:
11042         {
11043             /* These are all the types that need complex bodies allocating.  */
11044             void *new_body;
11045             const svtype sv_type = SvTYPE(sstr);
11046             const struct body_details *const sv_type_details
11047                 = bodies_by_type + sv_type;
11048
11049             switch (sv_type) {
11050             default:
11051                 Perl_croak(aTHX_ "Bizarre SvTYPE [%" IVdf "]", (IV)SvTYPE(sstr));
11052                 break;
11053
11054             case SVt_PVGV:
11055             case SVt_PVIO:
11056             case SVt_PVFM:
11057             case SVt_PVHV:
11058             case SVt_PVAV:
11059             case SVt_PVCV:
11060             case SVt_PVLV:
11061             case SVt_REGEXP:
11062             case SVt_PVMG:
11063             case SVt_PVNV:
11064             case SVt_PVIV:
11065             case SVt_PV:
11066                 assert(sv_type_details->body_size);
11067                 if (sv_type_details->arena) {
11068                     new_body_inline(new_body, sv_type);
11069                     new_body
11070                         = (void*)((char*)new_body - sv_type_details->offset);
11071                 } else {
11072                     new_body = new_NOARENA(sv_type_details);
11073                 }
11074             }
11075             assert(new_body);
11076             SvANY(dstr) = new_body;
11077
11078 #ifndef PURIFY
11079             Copy(((char*)SvANY(sstr)) + sv_type_details->offset,
11080                  ((char*)SvANY(dstr)) + sv_type_details->offset,
11081                  sv_type_details->copy, char);
11082 #else
11083             Copy(((char*)SvANY(sstr)),
11084                  ((char*)SvANY(dstr)),
11085                  sv_type_details->body_size + sv_type_details->offset, char);
11086 #endif
11087
11088             if (sv_type != SVt_PVAV && sv_type != SVt_PVHV
11089                 && !isGV_with_GP(dstr))
11090                 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
11091
11092             /* The Copy above means that all the source (unduplicated) pointers
11093                are now in the destination.  We can check the flags and the
11094                pointers in either, but it's possible that there's less cache
11095                missing by always going for the destination.
11096                FIXME - instrument and check that assumption  */
11097             if (sv_type >= SVt_PVMG) {
11098                 if ((sv_type == SVt_PVMG) && SvPAD_OUR(dstr)) {
11099                     SvOURSTASH_set(dstr, hv_dup_inc(SvOURSTASH(dstr), param));
11100                 } else if (SvMAGIC(dstr))
11101                     SvMAGIC_set(dstr, mg_dup(SvMAGIC(dstr), param));
11102                 if (SvSTASH(dstr))
11103                     SvSTASH_set(dstr, hv_dup_inc(SvSTASH(dstr), param));
11104             }
11105
11106             /* The cast silences a GCC warning about unhandled types.  */
11107             switch ((int)sv_type) {
11108             case SVt_PV:
11109                 break;
11110             case SVt_PVIV:
11111                 break;
11112             case SVt_PVNV:
11113                 break;
11114             case SVt_PVMG:
11115                 break;
11116             case SVt_REGEXP:
11117                 /* FIXME for plugins */
11118                 re_dup_guts((REGEXP*) sstr, (REGEXP*) dstr, param);
11119                 break;
11120             case SVt_PVLV:
11121                 /* XXX LvTARGOFF sometimes holds PMOP* when DEBUGGING */
11122                 if (LvTYPE(dstr) == 't') /* for tie: unrefcnted fake (SV**) */
11123                     LvTARG(dstr) = dstr;
11124                 else if (LvTYPE(dstr) == 'T') /* for tie: fake HE */
11125                     LvTARG(dstr) = MUTABLE_SV(he_dup((HE*)LvTARG(dstr), 0, param));
11126                 else
11127                     LvTARG(dstr) = sv_dup_inc(LvTARG(dstr), param);
11128             case SVt_PVGV:
11129                 if(isGV_with_GP(sstr)) {
11130                     GvNAME_HEK(dstr) = hek_dup(GvNAME_HEK(dstr), param);
11131                     /* Don't call sv_add_backref here as it's going to be
11132                        created as part of the magic cloning of the symbol
11133                        table--unless this is during a join and the stash
11134                        is not actually being cloned.  */
11135                     /* Danger Will Robinson - GvGP(dstr) isn't initialised
11136                        at the point of this comment.  */
11137                     GvSTASH(dstr) = hv_dup(GvSTASH(dstr), param);
11138                     if(param->flags & CLONEf_JOIN_IN) {
11139                         const HEK * const hvname
11140                          = HvNAME_HEK(GvSTASH(dstr));
11141                         if( hvname
11142                          && GvSTASH(dstr) == gv_stashpvn(
11143                              HEK_KEY(hvname), HEK_LEN(hvname), 0
11144                             )
11145                           )
11146                             Perl_sv_add_backref(
11147                              aTHX_ MUTABLE_SV(GvSTASH(dstr)), dstr
11148                             );
11149                     }
11150                     GvGP(dstr)  = gp_dup(GvGP(sstr), param);
11151                     (void)GpREFCNT_inc(GvGP(dstr));
11152                 } else
11153                     Perl_rvpv_dup(aTHX_ dstr, sstr, param);
11154                 break;
11155             case SVt_PVIO:
11156                 IoIFP(dstr)     = fp_dup(IoIFP(dstr), IoTYPE(dstr), param);
11157                 if (IoOFP(dstr) == IoIFP(sstr))
11158                     IoOFP(dstr) = IoIFP(dstr);
11159                 else
11160                     IoOFP(dstr) = fp_dup(IoOFP(dstr), IoTYPE(dstr), param);
11161                 /* PL_parser->rsfp_filters entries have fake IoDIRP() */
11162                 if(IoFLAGS(dstr) & IOf_FAKE_DIRP) {
11163                     /* I have no idea why fake dirp (rsfps)
11164                        should be treated differently but otherwise
11165                        we end up with leaks -- sky*/
11166                     IoTOP_GV(dstr)      = gv_dup_inc(IoTOP_GV(dstr), param);
11167                     IoFMT_GV(dstr)      = gv_dup_inc(IoFMT_GV(dstr), param);
11168                     IoBOTTOM_GV(dstr)   = gv_dup_inc(IoBOTTOM_GV(dstr), param);
11169                 } else {
11170                     IoTOP_GV(dstr)      = gv_dup(IoTOP_GV(dstr), param);
11171                     IoFMT_GV(dstr)      = gv_dup(IoFMT_GV(dstr), param);
11172                     IoBOTTOM_GV(dstr)   = gv_dup(IoBOTTOM_GV(dstr), param);
11173                     if (IoDIRP(dstr)) {
11174                         IoDIRP(dstr)    = dirp_dup(IoDIRP(dstr));
11175                     } else {
11176                         NOOP;
11177                         /* IoDIRP(dstr) is already a copy of IoDIRP(sstr)  */
11178                     }
11179                 }
11180                 IoTOP_NAME(dstr)        = SAVEPV(IoTOP_NAME(dstr));
11181                 IoFMT_NAME(dstr)        = SAVEPV(IoFMT_NAME(dstr));
11182                 IoBOTTOM_NAME(dstr)     = SAVEPV(IoBOTTOM_NAME(dstr));
11183                 break;
11184             case SVt_PVAV:
11185                 /* avoid cloning an empty array */
11186                 if (AvARRAY((const AV *)sstr) && AvFILLp((const AV *)sstr) >= 0) {
11187                     SV **dst_ary, **src_ary;
11188                     SSize_t items = AvFILLp((const AV *)sstr) + 1;
11189
11190                     src_ary = AvARRAY((const AV *)sstr);
11191                     Newxz(dst_ary, AvMAX((const AV *)sstr)+1, SV*);
11192                     ptr_table_store(PL_ptr_table, src_ary, dst_ary);
11193                     AvARRAY(MUTABLE_AV(dstr)) = dst_ary;
11194                     AvALLOC((const AV *)dstr) = dst_ary;
11195                     if (AvREAL((const AV *)sstr)) {
11196                         dst_ary = sv_dup_inc_multiple(src_ary, dst_ary, items,
11197                                                       param);
11198                     }
11199                     else {
11200                         while (items-- > 0)
11201                             *dst_ary++ = sv_dup(*src_ary++, param);
11202                         if (!(param->flags & CLONEf_COPY_STACKS)
11203                              && AvREIFY(sstr))
11204                         {
11205                             av_reify(MUTABLE_AV(dstr)); /* #41138 */
11206                         }
11207                     }
11208                     items = AvMAX((const AV *)sstr) - AvFILLp((const AV *)sstr);
11209                     while (items-- > 0) {
11210                         *dst_ary++ = &PL_sv_undef;
11211                     }
11212                 }
11213                 else {
11214                     AvARRAY(MUTABLE_AV(dstr))   = NULL;
11215                     AvALLOC((const AV *)dstr)   = (SV**)NULL;
11216                     AvMAX(  (const AV *)dstr)   = -1;
11217                     AvFILLp((const AV *)dstr)   = -1;
11218                 }
11219                 break;
11220             case SVt_PVHV:
11221                 if (HvARRAY((const HV *)sstr)) {
11222                     STRLEN i = 0;
11223                     const bool sharekeys = !!HvSHAREKEYS(sstr);
11224                     XPVHV * const dxhv = (XPVHV*)SvANY(dstr);
11225                     XPVHV * const sxhv = (XPVHV*)SvANY(sstr);
11226                     char *darray;
11227                     Newx(darray, PERL_HV_ARRAY_ALLOC_BYTES(dxhv->xhv_max+1)
11228                         + (SvOOK(sstr) ? sizeof(struct xpvhv_aux) : 0),
11229                         char);
11230                     HvARRAY(dstr) = (HE**)darray;
11231                     while (i <= sxhv->xhv_max) {
11232                         const HE * const source = HvARRAY(sstr)[i];
11233                         HvARRAY(dstr)[i] = source
11234                             ? he_dup(source, sharekeys, param) : 0;
11235                         ++i;
11236                     }
11237                     if (SvOOK(sstr)) {
11238                         HEK *hvname;
11239                         const struct xpvhv_aux * const saux = HvAUX(sstr);
11240                         struct xpvhv_aux * const daux = HvAUX(dstr);
11241                         /* This flag isn't copied.  */
11242                         /* SvOOK_on(hv) attacks the IV flags.  */
11243                         SvFLAGS(dstr) |= SVf_OOK;
11244
11245                         hvname = saux->xhv_name;
11246                         daux->xhv_name = hek_dup(hvname, param);
11247
11248                         daux->xhv_riter = saux->xhv_riter;
11249                         daux->xhv_eiter = saux->xhv_eiter
11250                             ? he_dup(saux->xhv_eiter,
11251                                         cBOOL(HvSHAREKEYS(sstr)), param) : 0;
11252                         /* backref array needs refcnt=2; see sv_add_backref */
11253                         daux->xhv_backreferences =
11254                             saux->xhv_backreferences
11255                             ? MUTABLE_AV(SvREFCNT_inc(
11256                                                       sv_dup_inc((const SV *)saux->xhv_backreferences, param)))
11257                                 : 0;
11258
11259                         daux->xhv_mro_meta = saux->xhv_mro_meta
11260                             ? mro_meta_dup(saux->xhv_mro_meta, param)
11261                             : 0;
11262
11263                         /* Record stashes for possible cloning in Perl_clone(). */
11264                         if (hvname)
11265                             av_push(param->stashes, dstr);
11266                     }
11267                 }
11268                 else
11269                     HvARRAY(MUTABLE_HV(dstr)) = NULL;
11270                 break;
11271             case SVt_PVCV:
11272                 if (!(param->flags & CLONEf_COPY_STACKS)) {
11273                     CvDEPTH(dstr) = 0;
11274                 }
11275             case SVt_PVFM:
11276                 /* NOTE: not refcounted */
11277                 CvSTASH(dstr)   = hv_dup(CvSTASH(dstr), param);
11278                 OP_REFCNT_LOCK;
11279                 if (!CvISXSUB(dstr))
11280                     CvROOT(dstr) = OpREFCNT_inc(CvROOT(dstr));
11281                 OP_REFCNT_UNLOCK;
11282                 if (CvCONST(dstr) && CvISXSUB(dstr)) {
11283                     CvXSUBANY(dstr).any_ptr =
11284                         sv_dup_inc((const SV *)CvXSUBANY(dstr).any_ptr, param);
11285                 }
11286                 /* don't dup if copying back - CvGV isn't refcounted, so the
11287                  * duped GV may never be freed. A bit of a hack! DAPM */
11288                 CvGV(dstr)      = (param->flags & CLONEf_JOIN_IN) ?
11289                     NULL : gv_dup(CvGV(dstr), param) ;
11290                 PAD_DUP(CvPADLIST(dstr), CvPADLIST(sstr), param);
11291                 CvOUTSIDE(dstr) =
11292                     CvWEAKOUTSIDE(sstr)
11293                     ? cv_dup(    CvOUTSIDE(dstr), param)
11294                     : cv_dup_inc(CvOUTSIDE(dstr), param);
11295                 if (!CvISXSUB(dstr))
11296                     CvFILE(dstr) = SAVEPV(CvFILE(dstr));
11297                 break;
11298             }
11299         }
11300     }
11301
11302     if (SvOBJECT(dstr) && SvTYPE(dstr) != SVt_PVIO)
11303         ++PL_sv_objcount;
11304
11305     return dstr;
11306  }
11307
11308 /* duplicate a context */
11309
11310 PERL_CONTEXT *
11311 Perl_cx_dup(pTHX_ PERL_CONTEXT *cxs, I32 ix, I32 max, CLONE_PARAMS* param)
11312 {
11313     PERL_CONTEXT *ncxs;
11314
11315     PERL_ARGS_ASSERT_CX_DUP;
11316
11317     if (!cxs)
11318         return (PERL_CONTEXT*)NULL;
11319
11320     /* look for it in the table first */
11321     ncxs = (PERL_CONTEXT*)ptr_table_fetch(PL_ptr_table, cxs);
11322     if (ncxs)
11323         return ncxs;
11324
11325     /* create anew and remember what it is */
11326     Newx(ncxs, max + 1, PERL_CONTEXT);
11327     ptr_table_store(PL_ptr_table, cxs, ncxs);
11328     Copy(cxs, ncxs, max + 1, PERL_CONTEXT);
11329
11330     while (ix >= 0) {
11331         PERL_CONTEXT * const ncx = &ncxs[ix];
11332         if (CxTYPE(ncx) == CXt_SUBST) {
11333             Perl_croak(aTHX_ "Cloning substitution context is unimplemented");
11334         }
11335         else {
11336             switch (CxTYPE(ncx)) {
11337             case CXt_SUB:
11338                 ncx->blk_sub.cv         = (ncx->blk_sub.olddepth == 0
11339                                            ? cv_dup_inc(ncx->blk_sub.cv, param)
11340                                            : cv_dup(ncx->blk_sub.cv,param));
11341                 ncx->blk_sub.argarray   = (CxHASARGS(ncx)
11342                                            ? av_dup_inc(ncx->blk_sub.argarray,
11343                                                         param)
11344                                            : NULL);
11345                 ncx->blk_sub.savearray  = av_dup_inc(ncx->blk_sub.savearray,
11346                                                      param);
11347                 ncx->blk_sub.oldcomppad = (PAD*)ptr_table_fetch(PL_ptr_table,
11348                                            ncx->blk_sub.oldcomppad);
11349                 break;
11350             case CXt_EVAL:
11351                 ncx->blk_eval.old_namesv = sv_dup_inc(ncx->blk_eval.old_namesv,
11352                                                       param);
11353                 ncx->blk_eval.cur_text  = sv_dup(ncx->blk_eval.cur_text, param);
11354                 break;
11355             case CXt_LOOP_LAZYSV:
11356                 ncx->blk_loop.state_u.lazysv.end
11357                     = sv_dup_inc(ncx->blk_loop.state_u.lazysv.end, param);
11358                 /* We are taking advantage of av_dup_inc and sv_dup_inc
11359                    actually being the same function, and order equivalance of
11360                    the two unions.
11361                    We can assert the later [but only at run time :-(]  */
11362                 assert ((void *) &ncx->blk_loop.state_u.ary.ary ==
11363                         (void *) &ncx->blk_loop.state_u.lazysv.cur);
11364             case CXt_LOOP_FOR:
11365                 ncx->blk_loop.state_u.ary.ary
11366                     = av_dup_inc(ncx->blk_loop.state_u.ary.ary, param);
11367             case CXt_LOOP_LAZYIV:
11368             case CXt_LOOP_PLAIN:
11369                 if (CxPADLOOP(ncx)) {
11370                     ncx->blk_loop.oldcomppad
11371                         = (PAD*)ptr_table_fetch(PL_ptr_table,
11372                                                 ncx->blk_loop.oldcomppad);
11373                 } else {
11374                     ncx->blk_loop.oldcomppad
11375                         = (PAD*)gv_dup((const GV *)ncx->blk_loop.oldcomppad,
11376                                        param);
11377                 }
11378                 break;
11379             case CXt_FORMAT:
11380                 ncx->blk_format.cv      = cv_dup(ncx->blk_format.cv, param);
11381                 ncx->blk_format.gv      = gv_dup(ncx->blk_format.gv, param);
11382                 ncx->blk_format.dfoutgv = gv_dup_inc(ncx->blk_format.dfoutgv,
11383                                                      param);
11384                 break;
11385             case CXt_BLOCK:
11386             case CXt_NULL:
11387                 break;
11388             }
11389         }
11390         --ix;
11391     }
11392     return ncxs;
11393 }
11394
11395 /* duplicate a stack info structure */
11396
11397 PERL_SI *
11398 Perl_si_dup(pTHX_ PERL_SI *si, CLONE_PARAMS* param)
11399 {
11400     PERL_SI *nsi;
11401
11402     PERL_ARGS_ASSERT_SI_DUP;
11403
11404     if (!si)
11405         return (PERL_SI*)NULL;
11406
11407     /* look for it in the table first */
11408     nsi = (PERL_SI*)ptr_table_fetch(PL_ptr_table, si);
11409     if (nsi)
11410         return nsi;
11411
11412     /* create anew and remember what it is */
11413     Newxz(nsi, 1, PERL_SI);
11414     ptr_table_store(PL_ptr_table, si, nsi);
11415
11416     nsi->si_stack       = av_dup_inc(si->si_stack, param);
11417     nsi->si_cxix        = si->si_cxix;
11418     nsi->si_cxmax       = si->si_cxmax;
11419     nsi->si_cxstack     = cx_dup(si->si_cxstack, si->si_cxix, si->si_cxmax, param);
11420     nsi->si_type        = si->si_type;
11421     nsi->si_prev        = si_dup(si->si_prev, param);
11422     nsi->si_next        = si_dup(si->si_next, param);
11423     nsi->si_markoff     = si->si_markoff;
11424
11425     return nsi;
11426 }
11427
11428 #define POPINT(ss,ix)   ((ss)[--(ix)].any_i32)
11429 #define TOPINT(ss,ix)   ((ss)[ix].any_i32)
11430 #define POPLONG(ss,ix)  ((ss)[--(ix)].any_long)
11431 #define TOPLONG(ss,ix)  ((ss)[ix].any_long)
11432 #define POPIV(ss,ix)    ((ss)[--(ix)].any_iv)
11433 #define TOPIV(ss,ix)    ((ss)[ix].any_iv)
11434 #define POPUV(ss,ix)    ((ss)[--(ix)].any_uv)
11435 #define TOPUV(ss,ix)    ((ss)[ix].any_uv)
11436 #define POPBOOL(ss,ix)  ((ss)[--(ix)].any_bool)
11437 #define TOPBOOL(ss,ix)  ((ss)[ix].any_bool)
11438 #define POPPTR(ss,ix)   ((ss)[--(ix)].any_ptr)
11439 #define TOPPTR(ss,ix)   ((ss)[ix].any_ptr)
11440 #define POPDPTR(ss,ix)  ((ss)[--(ix)].any_dptr)
11441 #define TOPDPTR(ss,ix)  ((ss)[ix].any_dptr)
11442 #define POPDXPTR(ss,ix) ((ss)[--(ix)].any_dxptr)
11443 #define TOPDXPTR(ss,ix) ((ss)[ix].any_dxptr)
11444
11445 /* XXXXX todo */
11446 #define pv_dup_inc(p)   SAVEPV(p)
11447 #define pv_dup(p)       SAVEPV(p)
11448 #define svp_dup_inc(p,pp)       any_dup(p,pp)
11449
11450 /* map any object to the new equivent - either something in the
11451  * ptr table, or something in the interpreter structure
11452  */
11453
11454 void *
11455 Perl_any_dup(pTHX_ void *v, const PerlInterpreter *proto_perl)
11456 {
11457     void *ret;
11458
11459     PERL_ARGS_ASSERT_ANY_DUP;
11460
11461     if (!v)
11462         return (void*)NULL;
11463
11464     /* look for it in the table first */
11465     ret = ptr_table_fetch(PL_ptr_table, v);
11466     if (ret)
11467         return ret;
11468
11469     /* see if it is part of the interpreter structure */
11470     if (v >= (void*)proto_perl && v < (void*)(proto_perl+1))
11471         ret = (void*)(((char*)aTHX) + (((char*)v) - (char*)proto_perl));
11472     else {
11473         ret = v;
11474     }
11475
11476     return ret;
11477 }
11478
11479 /* duplicate the save stack */
11480
11481 ANY *
11482 Perl_ss_dup(pTHX_ PerlInterpreter *proto_perl, CLONE_PARAMS* param)
11483 {
11484     dVAR;
11485     ANY * const ss      = proto_perl->Isavestack;
11486     const I32 max       = proto_perl->Isavestack_max;
11487     I32 ix              = proto_perl->Isavestack_ix;
11488     ANY *nss;
11489     const SV *sv;
11490     const GV *gv;
11491     const AV *av;
11492     const HV *hv;
11493     void* ptr;
11494     int intval;
11495     long longval;
11496     GP *gp;
11497     IV iv;
11498     I32 i;
11499     char *c = NULL;
11500     void (*dptr) (void*);
11501     void (*dxptr) (pTHX_ void*);
11502
11503     PERL_ARGS_ASSERT_SS_DUP;
11504
11505     Newxz(nss, max, ANY);
11506
11507     while (ix > 0) {
11508         const UV uv = POPUV(ss,ix);
11509         const U8 type = (U8)uv & SAVE_MASK;
11510
11511         TOPUV(nss,ix) = uv;
11512         switch (type) {
11513         case SAVEt_CLEARSV:
11514             break;
11515         case SAVEt_HELEM:               /* hash element */
11516             sv = (const SV *)POPPTR(ss,ix);
11517             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
11518             /* fall through */
11519         case SAVEt_ITEM:                        /* normal string */
11520         case SAVEt_SV:                          /* scalar reference */
11521             sv = (const SV *)POPPTR(ss,ix);
11522             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
11523             /* fall through */
11524         case SAVEt_FREESV:
11525         case SAVEt_MORTALIZESV:
11526             sv = (const SV *)POPPTR(ss,ix);
11527             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
11528             break;
11529         case SAVEt_SHARED_PVREF:                /* char* in shared space */
11530             c = (char*)POPPTR(ss,ix);
11531             TOPPTR(nss,ix) = savesharedpv(c);
11532             ptr = POPPTR(ss,ix);
11533             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11534             break;
11535         case SAVEt_GENERIC_SVREF:               /* generic sv */
11536         case SAVEt_SVREF:                       /* scalar reference */
11537             sv = (const SV *)POPPTR(ss,ix);
11538             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
11539             ptr = POPPTR(ss,ix);
11540             TOPPTR(nss,ix) = svp_dup_inc((SV**)ptr, proto_perl);/* XXXXX */
11541             break;
11542         case SAVEt_HV:                          /* hash reference */
11543         case SAVEt_AV:                          /* array reference */
11544             sv = (const SV *) POPPTR(ss,ix);
11545             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
11546             /* fall through */
11547         case SAVEt_COMPPAD:
11548         case SAVEt_NSTAB:
11549             sv = (const SV *) POPPTR(ss,ix);
11550             TOPPTR(nss,ix) = sv_dup(sv, param);
11551             break;
11552         case SAVEt_INT:                         /* int reference */
11553             ptr = POPPTR(ss,ix);
11554             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11555             intval = (int)POPINT(ss,ix);
11556             TOPINT(nss,ix) = intval;
11557             break;
11558         case SAVEt_LONG:                        /* long reference */
11559             ptr = POPPTR(ss,ix);
11560             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11561             longval = (long)POPLONG(ss,ix);
11562             TOPLONG(nss,ix) = longval;
11563             break;
11564         case SAVEt_I32:                         /* I32 reference */
11565         case SAVEt_COP_ARYBASE:                 /* call CopARYBASE_set */
11566             ptr = POPPTR(ss,ix);
11567             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11568             i = POPINT(ss,ix);
11569             TOPINT(nss,ix) = i;
11570             break;
11571         case SAVEt_IV:                          /* IV reference */
11572             ptr = POPPTR(ss,ix);
11573             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11574             iv = POPIV(ss,ix);
11575             TOPIV(nss,ix) = iv;
11576             break;
11577         case SAVEt_HPTR:                        /* HV* reference */
11578         case SAVEt_APTR:                        /* AV* reference */
11579         case SAVEt_SPTR:                        /* SV* reference */
11580             ptr = POPPTR(ss,ix);
11581             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11582             sv = (const SV *)POPPTR(ss,ix);
11583             TOPPTR(nss,ix) = sv_dup(sv, param);
11584             break;
11585         case SAVEt_VPTR:                        /* random* reference */
11586             ptr = POPPTR(ss,ix);
11587             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11588             /* Fall through */
11589         case SAVEt_INT_SMALL:
11590         case SAVEt_I32_SMALL:
11591         case SAVEt_I16:                         /* I16 reference */
11592         case SAVEt_I8:                          /* I8 reference */
11593         case SAVEt_BOOL:
11594             ptr = POPPTR(ss,ix);
11595             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11596             break;
11597         case SAVEt_GENERIC_PVREF:               /* generic char* */
11598         case SAVEt_PPTR:                        /* char* reference */
11599             ptr = POPPTR(ss,ix);
11600             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11601             c = (char*)POPPTR(ss,ix);
11602             TOPPTR(nss,ix) = pv_dup(c);
11603             break;
11604         case SAVEt_GP:                          /* scalar reference */
11605             gv = (const GV *)POPPTR(ss,ix);
11606             TOPPTR(nss,ix) = gv_dup_inc(gv, param);
11607             gp = (GP*)POPPTR(ss,ix);
11608             TOPPTR(nss,ix) = gp = gp_dup(gp, param);
11609             (void)GpREFCNT_inc(gp);
11610             i = POPINT(ss,ix);
11611             TOPINT(nss,ix) = i;
11612             break;
11613         case SAVEt_FREEOP:
11614             ptr = POPPTR(ss,ix);
11615             if (ptr && (((OP*)ptr)->op_private & OPpREFCOUNTED)) {
11616                 /* these are assumed to be refcounted properly */
11617                 OP *o;
11618                 switch (((OP*)ptr)->op_type) {
11619                 case OP_LEAVESUB:
11620                 case OP_LEAVESUBLV:
11621                 case OP_LEAVEEVAL:
11622                 case OP_LEAVE:
11623                 case OP_SCOPE:
11624                 case OP_LEAVEWRITE:
11625                     TOPPTR(nss,ix) = ptr;
11626                     o = (OP*)ptr;
11627                     OP_REFCNT_LOCK;
11628                     (void) OpREFCNT_inc(o);
11629                     OP_REFCNT_UNLOCK;
11630                     break;
11631                 default:
11632                     TOPPTR(nss,ix) = NULL;
11633                     break;
11634                 }
11635             }
11636             else
11637                 TOPPTR(nss,ix) = NULL;
11638             break;
11639         case SAVEt_DELETE:
11640             hv = (const HV *)POPPTR(ss,ix);
11641             TOPPTR(nss,ix) = hv_dup_inc(hv, param);
11642             i = POPINT(ss,ix);
11643             TOPINT(nss,ix) = i;
11644             /* Fall through */
11645         case SAVEt_FREEPV:
11646             c = (char*)POPPTR(ss,ix);
11647             TOPPTR(nss,ix) = pv_dup_inc(c);
11648             break;
11649         case SAVEt_STACK_POS:           /* Position on Perl stack */
11650             i = POPINT(ss,ix);
11651             TOPINT(nss,ix) = i;
11652             break;
11653         case SAVEt_DESTRUCTOR:
11654             ptr = POPPTR(ss,ix);
11655             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);  /* XXX quite arbitrary */
11656             dptr = POPDPTR(ss,ix);
11657             TOPDPTR(nss,ix) = DPTR2FPTR(void (*)(void*),
11658                                         any_dup(FPTR2DPTR(void *, dptr),
11659                                                 proto_perl));
11660             break;
11661         case SAVEt_DESTRUCTOR_X:
11662             ptr = POPPTR(ss,ix);
11663             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);  /* XXX quite arbitrary */
11664             dxptr = POPDXPTR(ss,ix);
11665             TOPDXPTR(nss,ix) = DPTR2FPTR(void (*)(pTHX_ void*),
11666                                          any_dup(FPTR2DPTR(void *, dxptr),
11667                                                  proto_perl));
11668             break;
11669         case SAVEt_REGCONTEXT:
11670         case SAVEt_ALLOC:
11671             ix -= uv >> SAVE_TIGHT_SHIFT;
11672             break;
11673         case SAVEt_AELEM:               /* array element */
11674             sv = (const SV *)POPPTR(ss,ix);
11675             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
11676             i = POPINT(ss,ix);
11677             TOPINT(nss,ix) = i;
11678             av = (const AV *)POPPTR(ss,ix);
11679             TOPPTR(nss,ix) = av_dup_inc(av, param);
11680             break;
11681         case SAVEt_OP:
11682             ptr = POPPTR(ss,ix);
11683             TOPPTR(nss,ix) = ptr;
11684             break;
11685         case SAVEt_HINTS:
11686             ptr = POPPTR(ss,ix);
11687             if (ptr) {
11688                 HINTS_REFCNT_LOCK;
11689                 ((struct refcounted_he *)ptr)->refcounted_he_refcnt++;
11690                 HINTS_REFCNT_UNLOCK;
11691             }
11692             TOPPTR(nss,ix) = ptr;
11693             i = POPINT(ss,ix);
11694             TOPINT(nss,ix) = i;
11695             if (i & HINT_LOCALIZE_HH) {
11696                 hv = (const HV *)POPPTR(ss,ix);
11697                 TOPPTR(nss,ix) = hv_dup_inc(hv, param);
11698             }
11699             break;
11700         case SAVEt_PADSV_AND_MORTALIZE:
11701             longval = (long)POPLONG(ss,ix);
11702             TOPLONG(nss,ix) = longval;
11703             ptr = POPPTR(ss,ix);
11704             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11705             sv = (const SV *)POPPTR(ss,ix);
11706             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
11707             break;
11708         case SAVEt_SET_SVFLAGS:
11709             i = POPINT(ss,ix);
11710             TOPINT(nss,ix) = i;
11711             i = POPINT(ss,ix);
11712             TOPINT(nss,ix) = i;
11713             sv = (const SV *)POPPTR(ss,ix);
11714             TOPPTR(nss,ix) = sv_dup(sv, param);
11715             break;
11716         case SAVEt_RE_STATE:
11717             {
11718                 const struct re_save_state *const old_state
11719                     = (struct re_save_state *)
11720                     (ss + ix - SAVESTACK_ALLOC_FOR_RE_SAVE_STATE);
11721                 struct re_save_state *const new_state
11722                     = (struct re_save_state *)
11723                     (nss + ix - SAVESTACK_ALLOC_FOR_RE_SAVE_STATE);
11724
11725                 Copy(old_state, new_state, 1, struct re_save_state);
11726                 ix -= SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
11727
11728                 new_state->re_state_bostr
11729                     = pv_dup(old_state->re_state_bostr);
11730                 new_state->re_state_reginput
11731                     = pv_dup(old_state->re_state_reginput);
11732                 new_state->re_state_regeol
11733                     = pv_dup(old_state->re_state_regeol);
11734                 new_state->re_state_regoffs
11735                     = (regexp_paren_pair*)
11736                         any_dup(old_state->re_state_regoffs, proto_perl);
11737                 new_state->re_state_reglastparen
11738                     = (U32*) any_dup(old_state->re_state_reglastparen, 
11739                               proto_perl);
11740                 new_state->re_state_reglastcloseparen
11741                     = (U32*)any_dup(old_state->re_state_reglastcloseparen,
11742                               proto_perl);
11743                 /* XXX This just has to be broken. The old save_re_context
11744                    code did SAVEGENERICPV(PL_reg_start_tmp);
11745                    PL_reg_start_tmp is char **.
11746                    Look above to what the dup code does for
11747                    SAVEt_GENERIC_PVREF
11748                    It can never have worked.
11749                    So this is merely a faithful copy of the exiting bug:  */
11750                 new_state->re_state_reg_start_tmp
11751                     = (char **) pv_dup((char *)
11752                                       old_state->re_state_reg_start_tmp);
11753                 /* I assume that it only ever "worked" because no-one called
11754                    (pseudo)fork while the regexp engine had re-entered itself.
11755                 */
11756 #ifdef PERL_OLD_COPY_ON_WRITE
11757                 new_state->re_state_nrs
11758                     = sv_dup(old_state->re_state_nrs, param);
11759 #endif
11760                 new_state->re_state_reg_magic
11761                     = (MAGIC*) any_dup(old_state->re_state_reg_magic, 
11762                                proto_perl);
11763                 new_state->re_state_reg_oldcurpm
11764                     = (PMOP*) any_dup(old_state->re_state_reg_oldcurpm, 
11765                               proto_perl);
11766                 new_state->re_state_reg_curpm
11767                     = (PMOP*)  any_dup(old_state->re_state_reg_curpm, 
11768                                proto_perl);
11769                 new_state->re_state_reg_oldsaved
11770                     = pv_dup(old_state->re_state_reg_oldsaved);
11771                 new_state->re_state_reg_poscache
11772                     = pv_dup(old_state->re_state_reg_poscache);
11773                 new_state->re_state_reg_starttry
11774                     = pv_dup(old_state->re_state_reg_starttry);
11775                 break;
11776             }
11777         case SAVEt_COMPILE_WARNINGS:
11778             ptr = POPPTR(ss,ix);
11779             TOPPTR(nss,ix) = DUP_WARNINGS((STRLEN*)ptr);
11780             break;
11781         case SAVEt_PARSER:
11782             ptr = POPPTR(ss,ix);
11783             TOPPTR(nss,ix) = parser_dup((const yy_parser*)ptr, param);
11784             break;
11785         default:
11786             Perl_croak(aTHX_
11787                        "panic: ss_dup inconsistency (%"IVdf")", (IV) type);
11788         }
11789     }
11790
11791     return nss;
11792 }
11793
11794
11795 /* if sv is a stash, call $class->CLONE_SKIP(), and set the SVphv_CLONEABLE
11796  * flag to the result. This is done for each stash before cloning starts,
11797  * so we know which stashes want their objects cloned */
11798
11799 static void
11800 do_mark_cloneable_stash(pTHX_ SV *const sv)
11801 {
11802     const HEK * const hvname = HvNAME_HEK((const HV *)sv);
11803     if (hvname) {
11804         GV* const cloner = gv_fetchmethod_autoload(MUTABLE_HV(sv), "CLONE_SKIP", 0);
11805         SvFLAGS(sv) |= SVphv_CLONEABLE; /* clone objects by default */
11806         if (cloner && GvCV(cloner)) {
11807             dSP;
11808             UV status;
11809
11810             ENTER;
11811             SAVETMPS;
11812             PUSHMARK(SP);
11813             mXPUSHs(newSVhek(hvname));
11814             PUTBACK;
11815             call_sv(MUTABLE_SV(GvCV(cloner)), G_SCALAR);
11816             SPAGAIN;
11817             status = POPu;
11818             PUTBACK;
11819             FREETMPS;
11820             LEAVE;
11821             if (status)
11822                 SvFLAGS(sv) &= ~SVphv_CLONEABLE;
11823         }
11824     }
11825 }
11826
11827
11828
11829 /*
11830 =for apidoc perl_clone
11831
11832 Create and return a new interpreter by cloning the current one.
11833
11834 perl_clone takes these flags as parameters:
11835
11836 CLONEf_COPY_STACKS - is used to, well, copy the stacks also,
11837 without it we only clone the data and zero the stacks,
11838 with it we copy the stacks and the new perl interpreter is
11839 ready to run at the exact same point as the previous one.
11840 The pseudo-fork code uses COPY_STACKS while the
11841 threads->create doesn't.
11842
11843 CLONEf_KEEP_PTR_TABLE
11844 perl_clone keeps a ptr_table with the pointer of the old
11845 variable as a key and the new variable as a value,
11846 this allows it to check if something has been cloned and not
11847 clone it again but rather just use the value and increase the
11848 refcount. If KEEP_PTR_TABLE is not set then perl_clone will kill
11849 the ptr_table using the function
11850 C<ptr_table_free(PL_ptr_table); PL_ptr_table = NULL;>,
11851 reason to keep it around is if you want to dup some of your own
11852 variable who are outside the graph perl scans, example of this
11853 code is in threads.xs create
11854
11855 CLONEf_CLONE_HOST
11856 This is a win32 thing, it is ignored on unix, it tells perls
11857 win32host code (which is c++) to clone itself, this is needed on
11858 win32 if you want to run two threads at the same time,
11859 if you just want to do some stuff in a separate perl interpreter
11860 and then throw it away and return to the original one,
11861 you don't need to do anything.
11862
11863 =cut
11864 */
11865
11866 /* XXX the above needs expanding by someone who actually understands it ! */
11867 EXTERN_C PerlInterpreter *
11868 perl_clone_host(PerlInterpreter* proto_perl, UV flags);
11869
11870 PerlInterpreter *
11871 perl_clone(PerlInterpreter *proto_perl, UV flags)
11872 {
11873    dVAR;
11874 #ifdef PERL_IMPLICIT_SYS
11875
11876     PERL_ARGS_ASSERT_PERL_CLONE;
11877
11878    /* perlhost.h so we need to call into it
11879    to clone the host, CPerlHost should have a c interface, sky */
11880
11881    if (flags & CLONEf_CLONE_HOST) {
11882        return perl_clone_host(proto_perl,flags);
11883    }
11884    return perl_clone_using(proto_perl, flags,
11885                             proto_perl->IMem,
11886                             proto_perl->IMemShared,
11887                             proto_perl->IMemParse,
11888                             proto_perl->IEnv,
11889                             proto_perl->IStdIO,
11890                             proto_perl->ILIO,
11891                             proto_perl->IDir,
11892                             proto_perl->ISock,
11893                             proto_perl->IProc);
11894 }
11895
11896 PerlInterpreter *
11897 perl_clone_using(PerlInterpreter *proto_perl, UV flags,
11898                  struct IPerlMem* ipM, struct IPerlMem* ipMS,
11899                  struct IPerlMem* ipMP, struct IPerlEnv* ipE,
11900                  struct IPerlStdIO* ipStd, struct IPerlLIO* ipLIO,
11901                  struct IPerlDir* ipD, struct IPerlSock* ipS,
11902                  struct IPerlProc* ipP)
11903 {
11904     /* XXX many of the string copies here can be optimized if they're
11905      * constants; they need to be allocated as common memory and just
11906      * their pointers copied. */
11907
11908     IV i;
11909     CLONE_PARAMS clone_params;
11910     CLONE_PARAMS* const param = &clone_params;
11911
11912     PerlInterpreter * const my_perl = (PerlInterpreter*)(*ipM->pMalloc)(ipM, sizeof(PerlInterpreter));
11913
11914     PERL_ARGS_ASSERT_PERL_CLONE_USING;
11915 #else           /* !PERL_IMPLICIT_SYS */
11916     IV i;
11917     CLONE_PARAMS clone_params;
11918     CLONE_PARAMS* param = &clone_params;
11919     PerlInterpreter * const my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
11920
11921     PERL_ARGS_ASSERT_PERL_CLONE;
11922 #endif          /* PERL_IMPLICIT_SYS */
11923
11924     /* for each stash, determine whether its objects should be cloned */
11925     S_visit(proto_perl, do_mark_cloneable_stash, SVt_PVHV, SVTYPEMASK);
11926     PERL_SET_THX(my_perl);
11927
11928 #ifdef DEBUGGING
11929     PoisonNew(my_perl, 1, PerlInterpreter);
11930     PL_op = NULL;
11931     PL_curcop = NULL;
11932     PL_markstack = 0;
11933     PL_scopestack = 0;
11934     PL_scopestack_name = 0;
11935     PL_savestack = 0;
11936     PL_savestack_ix = 0;
11937     PL_savestack_max = -1;
11938     PL_sig_pending = 0;
11939     PL_parser = NULL;
11940     Zero(&PL_debug_pad, 1, struct perl_debug_pad);
11941 #  ifdef DEBUG_LEAKING_SCALARS
11942     PL_sv_serial = (((U32)my_perl >> 2) & 0xfff) * 1000000;
11943 #  endif
11944 #else   /* !DEBUGGING */
11945     Zero(my_perl, 1, PerlInterpreter);
11946 #endif  /* DEBUGGING */
11947
11948 #ifdef PERL_IMPLICIT_SYS
11949     /* host pointers */
11950     PL_Mem              = ipM;
11951     PL_MemShared        = ipMS;
11952     PL_MemParse         = ipMP;
11953     PL_Env              = ipE;
11954     PL_StdIO            = ipStd;
11955     PL_LIO              = ipLIO;
11956     PL_Dir              = ipD;
11957     PL_Sock             = ipS;
11958     PL_Proc             = ipP;
11959 #endif          /* PERL_IMPLICIT_SYS */
11960
11961     param->flags = flags;
11962     param->proto_perl = proto_perl;
11963
11964     INIT_TRACK_MEMPOOL(my_perl->Imemory_debug_header, my_perl);
11965
11966     PL_body_arenas = NULL;
11967     Zero(&PL_body_roots, 1, PL_body_roots);
11968     
11969     PL_nice_chunk       = NULL;
11970     PL_nice_chunk_size  = 0;
11971     PL_sv_count         = 0;
11972     PL_sv_objcount      = 0;
11973     PL_sv_root          = NULL;
11974     PL_sv_arenaroot     = NULL;
11975
11976     PL_debug            = proto_perl->Idebug;
11977
11978     PL_hash_seed        = proto_perl->Ihash_seed;
11979     PL_rehash_seed      = proto_perl->Irehash_seed;
11980
11981 #ifdef USE_REENTRANT_API
11982     /* XXX: things like -Dm will segfault here in perlio, but doing
11983      *  PERL_SET_CONTEXT(proto_perl);
11984      * breaks too many other things
11985      */
11986     Perl_reentrant_init(aTHX);
11987 #endif
11988
11989     /* create SV map for pointer relocation */
11990     PL_ptr_table = ptr_table_new();
11991
11992     /* initialize these special pointers as early as possible */
11993     SvANY(&PL_sv_undef)         = NULL;
11994     SvREFCNT(&PL_sv_undef)      = (~(U32)0)/2;
11995     SvFLAGS(&PL_sv_undef)       = SVf_READONLY|SVt_NULL;
11996     ptr_table_store(PL_ptr_table, &proto_perl->Isv_undef, &PL_sv_undef);
11997
11998     SvANY(&PL_sv_no)            = new_XPVNV();
11999     SvREFCNT(&PL_sv_no)         = (~(U32)0)/2;
12000     SvFLAGS(&PL_sv_no)          = SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
12001                                   |SVp_POK|SVf_POK|SVf_READONLY|SVt_PVNV;
12002     SvPV_set(&PL_sv_no, savepvn(PL_No, 0));
12003     SvCUR_set(&PL_sv_no, 0);
12004     SvLEN_set(&PL_sv_no, 1);
12005     SvIV_set(&PL_sv_no, 0);
12006     SvNV_set(&PL_sv_no, 0);
12007     ptr_table_store(PL_ptr_table, &proto_perl->Isv_no, &PL_sv_no);
12008
12009     SvANY(&PL_sv_yes)           = new_XPVNV();
12010     SvREFCNT(&PL_sv_yes)        = (~(U32)0)/2;
12011     SvFLAGS(&PL_sv_yes)         = SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
12012                                   |SVp_POK|SVf_POK|SVf_READONLY|SVt_PVNV;
12013     SvPV_set(&PL_sv_yes, savepvn(PL_Yes, 1));
12014     SvCUR_set(&PL_sv_yes, 1);
12015     SvLEN_set(&PL_sv_yes, 2);
12016     SvIV_set(&PL_sv_yes, 1);
12017     SvNV_set(&PL_sv_yes, 1);
12018     ptr_table_store(PL_ptr_table, &proto_perl->Isv_yes, &PL_sv_yes);
12019
12020     /* dbargs array probably holds garbage */
12021     PL_dbargs           = NULL;
12022
12023     /* create (a non-shared!) shared string table */
12024     PL_strtab           = newHV();
12025     HvSHAREKEYS_off(PL_strtab);
12026     hv_ksplit(PL_strtab, HvTOTALKEYS(proto_perl->Istrtab));
12027     ptr_table_store(PL_ptr_table, proto_perl->Istrtab, PL_strtab);
12028
12029     PL_compiling = proto_perl->Icompiling;
12030
12031     /* These two PVs will be free'd special way so must set them same way op.c does */
12032     PL_compiling.cop_stashpv = savesharedpv(PL_compiling.cop_stashpv);
12033     ptr_table_store(PL_ptr_table, proto_perl->Icompiling.cop_stashpv, PL_compiling.cop_stashpv);
12034
12035     PL_compiling.cop_file    = savesharedpv(PL_compiling.cop_file);
12036     ptr_table_store(PL_ptr_table, proto_perl->Icompiling.cop_file, PL_compiling.cop_file);
12037
12038     ptr_table_store(PL_ptr_table, &proto_perl->Icompiling, &PL_compiling);
12039     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
12040     if (PL_compiling.cop_hints_hash) {
12041         HINTS_REFCNT_LOCK;
12042         PL_compiling.cop_hints_hash->refcounted_he_refcnt++;
12043         HINTS_REFCNT_UNLOCK;
12044     }
12045     PL_curcop           = (COP*)any_dup(proto_perl->Icurcop, proto_perl);
12046 #ifdef PERL_DEBUG_READONLY_OPS
12047     PL_slabs = NULL;
12048     PL_slab_count = 0;
12049 #endif
12050
12051     /* pseudo environmental stuff */
12052     PL_origargc         = proto_perl->Iorigargc;
12053     PL_origargv         = proto_perl->Iorigargv;
12054
12055     param->stashes      = newAV();  /* Setup array of objects to call clone on */
12056
12057     /* Set tainting stuff before PerlIO_debug can possibly get called */
12058     PL_tainting         = proto_perl->Itainting;
12059     PL_taint_warn       = proto_perl->Itaint_warn;
12060
12061 #ifdef PERLIO_LAYERS
12062     /* Clone PerlIO tables as soon as we can handle general xx_dup() */
12063     PerlIO_clone(aTHX_ proto_perl, param);
12064 #endif
12065
12066     PL_envgv            = gv_dup(proto_perl->Ienvgv, param);
12067     PL_incgv            = gv_dup(proto_perl->Iincgv, param);
12068     PL_hintgv           = gv_dup(proto_perl->Ihintgv, param);
12069     PL_origfilename     = SAVEPV(proto_perl->Iorigfilename);
12070     PL_diehook          = sv_dup_inc(proto_perl->Idiehook, param);
12071     PL_warnhook         = sv_dup_inc(proto_perl->Iwarnhook, param);
12072
12073     /* switches */
12074     PL_minus_c          = proto_perl->Iminus_c;
12075     PL_patchlevel       = sv_dup_inc(proto_perl->Ipatchlevel, param);
12076     PL_localpatches     = proto_perl->Ilocalpatches;
12077     PL_splitstr         = proto_perl->Isplitstr;
12078     PL_minus_n          = proto_perl->Iminus_n;
12079     PL_minus_p          = proto_perl->Iminus_p;
12080     PL_minus_l          = proto_perl->Iminus_l;
12081     PL_minus_a          = proto_perl->Iminus_a;
12082     PL_minus_E          = proto_perl->Iminus_E;
12083     PL_minus_F          = proto_perl->Iminus_F;
12084     PL_doswitches       = proto_perl->Idoswitches;
12085     PL_dowarn           = proto_perl->Idowarn;
12086     PL_doextract        = proto_perl->Idoextract;
12087     PL_sawampersand     = proto_perl->Isawampersand;
12088     PL_unsafe           = proto_perl->Iunsafe;
12089     PL_inplace          = SAVEPV(proto_perl->Iinplace);
12090     PL_e_script         = sv_dup_inc(proto_perl->Ie_script, param);
12091     PL_perldb           = proto_perl->Iperldb;
12092     PL_perl_destruct_level = proto_perl->Iperl_destruct_level;
12093     PL_exit_flags       = proto_perl->Iexit_flags;
12094
12095     /* magical thingies */
12096     /* XXX time(&PL_basetime) when asked for? */
12097     PL_basetime         = proto_perl->Ibasetime;
12098     PL_formfeed         = sv_dup(proto_perl->Iformfeed, param);
12099
12100     PL_maxsysfd         = proto_perl->Imaxsysfd;
12101     PL_statusvalue      = proto_perl->Istatusvalue;
12102 #ifdef VMS
12103     PL_statusvalue_vms  = proto_perl->Istatusvalue_vms;
12104 #else
12105     PL_statusvalue_posix = proto_perl->Istatusvalue_posix;
12106 #endif
12107     PL_encoding         = sv_dup(proto_perl->Iencoding, param);
12108
12109     sv_setpvs(PERL_DEBUG_PAD(0), "");   /* For regex debugging. */
12110     sv_setpvs(PERL_DEBUG_PAD(1), "");   /* ext/re needs these */
12111     sv_setpvs(PERL_DEBUG_PAD(2), "");   /* even without DEBUGGING. */
12112
12113    
12114     /* RE engine related */
12115     Zero(&PL_reg_state, 1, struct re_save_state);
12116     PL_reginterp_cnt    = 0;
12117     PL_regmatch_slab    = NULL;
12118     
12119     /* Clone the regex array */
12120     /* ORANGE FIXME for plugins, probably in the SV dup code.
12121        newSViv(PTR2IV(CALLREGDUPE(
12122        INT2PTR(REGEXP *, SvIVX(regex)), param))))
12123     */
12124     PL_regex_padav = av_dup_inc(proto_perl->Iregex_padav, param);
12125     PL_regex_pad = AvARRAY(PL_regex_padav);
12126
12127     /* shortcuts to various I/O objects */
12128     PL_ofsgv            = gv_dup(proto_perl->Iofsgv, param);
12129     PL_stdingv          = gv_dup(proto_perl->Istdingv, param);
12130     PL_stderrgv         = gv_dup(proto_perl->Istderrgv, param);
12131     PL_defgv            = gv_dup(proto_perl->Idefgv, param);
12132     PL_argvgv           = gv_dup(proto_perl->Iargvgv, param);
12133     PL_argvoutgv        = gv_dup(proto_perl->Iargvoutgv, param);
12134     PL_argvout_stack    = av_dup_inc(proto_perl->Iargvout_stack, param);
12135
12136     /* shortcuts to regexp stuff */
12137     PL_replgv           = gv_dup(proto_perl->Ireplgv, param);
12138
12139     /* shortcuts to misc objects */
12140     PL_errgv            = gv_dup(proto_perl->Ierrgv, param);
12141
12142     /* shortcuts to debugging objects */
12143     PL_DBgv             = gv_dup(proto_perl->IDBgv, param);
12144     PL_DBline           = gv_dup(proto_perl->IDBline, param);
12145     PL_DBsub            = gv_dup(proto_perl->IDBsub, param);
12146     PL_DBsingle         = sv_dup(proto_perl->IDBsingle, param);
12147     PL_DBtrace          = sv_dup(proto_perl->IDBtrace, param);
12148     PL_DBsignal         = sv_dup(proto_perl->IDBsignal, param);
12149
12150     /* symbol tables */
12151     PL_defstash         = hv_dup_inc(proto_perl->Idefstash, param);
12152     PL_curstash         = hv_dup(proto_perl->Icurstash, param);
12153     PL_debstash         = hv_dup(proto_perl->Idebstash, param);
12154     PL_globalstash      = hv_dup(proto_perl->Iglobalstash, param);
12155     PL_curstname        = sv_dup_inc(proto_perl->Icurstname, param);
12156
12157     PL_beginav          = av_dup_inc(proto_perl->Ibeginav, param);
12158     PL_beginav_save     = av_dup_inc(proto_perl->Ibeginav_save, param);
12159     PL_checkav_save     = av_dup_inc(proto_perl->Icheckav_save, param);
12160     PL_unitcheckav      = av_dup_inc(proto_perl->Iunitcheckav, param);
12161     PL_unitcheckav_save = av_dup_inc(proto_perl->Iunitcheckav_save, param);
12162     PL_endav            = av_dup_inc(proto_perl->Iendav, param);
12163     PL_checkav          = av_dup_inc(proto_perl->Icheckav, param);
12164     PL_initav           = av_dup_inc(proto_perl->Iinitav, param);
12165
12166     PL_sub_generation   = proto_perl->Isub_generation;
12167     PL_isarev           = hv_dup_inc(proto_perl->Iisarev, param);
12168
12169     /* funky return mechanisms */
12170     PL_forkprocess      = proto_perl->Iforkprocess;
12171
12172     /* subprocess state */
12173     PL_fdpid            = av_dup_inc(proto_perl->Ifdpid, param);
12174
12175     /* internal state */
12176     PL_maxo             = proto_perl->Imaxo;
12177     if (proto_perl->Iop_mask)
12178         PL_op_mask      = SAVEPVN(proto_perl->Iop_mask, PL_maxo);
12179     else
12180         PL_op_mask      = NULL;
12181     /* PL_asserting        = proto_perl->Iasserting; */
12182
12183     /* current interpreter roots */
12184     PL_main_cv          = cv_dup_inc(proto_perl->Imain_cv, param);
12185     OP_REFCNT_LOCK;
12186     PL_main_root        = OpREFCNT_inc(proto_perl->Imain_root);
12187     OP_REFCNT_UNLOCK;
12188     PL_main_start       = proto_perl->Imain_start;
12189     PL_eval_root        = proto_perl->Ieval_root;
12190     PL_eval_start       = proto_perl->Ieval_start;
12191
12192     /* runtime control stuff */
12193     PL_curcopdb         = (COP*)any_dup(proto_perl->Icurcopdb, proto_perl);
12194
12195     PL_filemode         = proto_perl->Ifilemode;
12196     PL_lastfd           = proto_perl->Ilastfd;
12197     PL_oldname          = proto_perl->Ioldname;         /* XXX not quite right */
12198     PL_Argv             = NULL;
12199     PL_Cmd              = NULL;
12200     PL_gensym           = proto_perl->Igensym;
12201     PL_preambleav       = av_dup_inc(proto_perl->Ipreambleav, param);
12202     PL_laststatval      = proto_perl->Ilaststatval;
12203     PL_laststype        = proto_perl->Ilaststype;
12204     PL_mess_sv          = NULL;
12205
12206     PL_ors_sv           = sv_dup_inc(proto_perl->Iors_sv, param);
12207
12208     /* interpreter atexit processing */
12209     PL_exitlistlen      = proto_perl->Iexitlistlen;
12210     if (PL_exitlistlen) {
12211         Newx(PL_exitlist, PL_exitlistlen, PerlExitListEntry);
12212         Copy(proto_perl->Iexitlist, PL_exitlist, PL_exitlistlen, PerlExitListEntry);
12213     }
12214     else
12215         PL_exitlist     = (PerlExitListEntry*)NULL;
12216
12217     PL_my_cxt_size = proto_perl->Imy_cxt_size;
12218     if (PL_my_cxt_size) {
12219         Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
12220         Copy(proto_perl->Imy_cxt_list, PL_my_cxt_list, PL_my_cxt_size, void *);
12221 #ifdef PERL_GLOBAL_STRUCT_PRIVATE
12222         Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
12223         Copy(proto_perl->Imy_cxt_keys, PL_my_cxt_keys, PL_my_cxt_size, char *);
12224 #endif
12225     }
12226     else {
12227         PL_my_cxt_list  = (void**)NULL;
12228 #ifdef PERL_GLOBAL_STRUCT_PRIVATE
12229         PL_my_cxt_keys  = (const char**)NULL;
12230 #endif
12231     }
12232     PL_modglobal        = hv_dup_inc(proto_perl->Imodglobal, param);
12233     PL_custom_op_names  = hv_dup_inc(proto_perl->Icustom_op_names,param);
12234     PL_custom_op_descs  = hv_dup_inc(proto_perl->Icustom_op_descs,param);
12235
12236     PL_profiledata      = NULL;
12237
12238     PL_compcv                   = cv_dup(proto_perl->Icompcv, param);
12239
12240     PAD_CLONE_VARS(proto_perl, param);
12241
12242 #ifdef HAVE_INTERP_INTERN
12243     sys_intern_dup(&proto_perl->Isys_intern, &PL_sys_intern);
12244 #endif
12245
12246     /* more statics moved here */
12247     PL_generation       = proto_perl->Igeneration;
12248     PL_DBcv             = cv_dup(proto_perl->IDBcv, param);
12249
12250     PL_in_clean_objs    = proto_perl->Iin_clean_objs;
12251     PL_in_clean_all     = proto_perl->Iin_clean_all;
12252
12253     PL_uid              = proto_perl->Iuid;
12254     PL_euid             = proto_perl->Ieuid;
12255     PL_gid              = proto_perl->Igid;
12256     PL_egid             = proto_perl->Iegid;
12257     PL_nomemok          = proto_perl->Inomemok;
12258     PL_an               = proto_perl->Ian;
12259     PL_evalseq          = proto_perl->Ievalseq;
12260     PL_origenviron      = proto_perl->Iorigenviron;     /* XXX not quite right */
12261     PL_origalen         = proto_perl->Iorigalen;
12262 #ifdef PERL_USES_PL_PIDSTATUS
12263     PL_pidstatus        = newHV();                      /* XXX flag for cloning? */
12264 #endif
12265     PL_osname           = SAVEPV(proto_perl->Iosname);
12266     PL_sighandlerp      = proto_perl->Isighandlerp;
12267
12268     PL_runops           = proto_perl->Irunops;
12269
12270     PL_parser           = parser_dup(proto_perl->Iparser, param);
12271
12272     /* XXX this only works if the saved cop has already been cloned */
12273     if (proto_perl->Iparser) {
12274         PL_parser->saved_curcop = (COP*)any_dup(
12275                                     proto_perl->Iparser->saved_curcop,
12276                                     proto_perl);
12277     }
12278
12279     PL_subline          = proto_perl->Isubline;
12280     PL_subname          = sv_dup_inc(proto_perl->Isubname, param);
12281
12282 #ifdef FCRYPT
12283     PL_cryptseen        = proto_perl->Icryptseen;
12284 #endif
12285
12286     PL_hints            = proto_perl->Ihints;
12287
12288     PL_amagic_generation        = proto_perl->Iamagic_generation;
12289
12290 #ifdef USE_LOCALE_COLLATE
12291     PL_collation_ix     = proto_perl->Icollation_ix;
12292     PL_collation_name   = SAVEPV(proto_perl->Icollation_name);
12293     PL_collation_standard       = proto_perl->Icollation_standard;
12294     PL_collxfrm_base    = proto_perl->Icollxfrm_base;
12295     PL_collxfrm_mult    = proto_perl->Icollxfrm_mult;
12296 #endif /* USE_LOCALE_COLLATE */
12297
12298 #ifdef USE_LOCALE_NUMERIC
12299     PL_numeric_name     = SAVEPV(proto_perl->Inumeric_name);
12300     PL_numeric_standard = proto_perl->Inumeric_standard;
12301     PL_numeric_local    = proto_perl->Inumeric_local;
12302     PL_numeric_radix_sv = sv_dup_inc(proto_perl->Inumeric_radix_sv, param);
12303 #endif /* !USE_LOCALE_NUMERIC */
12304
12305     /* utf8 character classes */
12306     PL_utf8_alnum       = sv_dup_inc(proto_perl->Iutf8_alnum, param);
12307     PL_utf8_ascii       = sv_dup_inc(proto_perl->Iutf8_ascii, param);
12308     PL_utf8_alpha       = sv_dup_inc(proto_perl->Iutf8_alpha, param);
12309     PL_utf8_space       = sv_dup_inc(proto_perl->Iutf8_space, param);
12310     PL_utf8_cntrl       = sv_dup_inc(proto_perl->Iutf8_cntrl, param);
12311     PL_utf8_graph       = sv_dup_inc(proto_perl->Iutf8_graph, param);
12312     PL_utf8_digit       = sv_dup_inc(proto_perl->Iutf8_digit, param);
12313     PL_utf8_upper       = sv_dup_inc(proto_perl->Iutf8_upper, param);
12314     PL_utf8_lower       = sv_dup_inc(proto_perl->Iutf8_lower, param);
12315     PL_utf8_print       = sv_dup_inc(proto_perl->Iutf8_print, param);
12316     PL_utf8_punct       = sv_dup_inc(proto_perl->Iutf8_punct, param);
12317     PL_utf8_xdigit      = sv_dup_inc(proto_perl->Iutf8_xdigit, param);
12318     PL_utf8_mark        = sv_dup_inc(proto_perl->Iutf8_mark, param);
12319     PL_utf8_X_begin     = sv_dup_inc(proto_perl->Iutf8_X_begin, param);
12320     PL_utf8_X_extend    = sv_dup_inc(proto_perl->Iutf8_X_extend, param);
12321     PL_utf8_X_prepend   = sv_dup_inc(proto_perl->Iutf8_X_prepend, param);
12322     PL_utf8_X_non_hangul        = sv_dup_inc(proto_perl->Iutf8_X_non_hangul, param);
12323     PL_utf8_X_L = sv_dup_inc(proto_perl->Iutf8_X_L, param);
12324     PL_utf8_X_LV        = sv_dup_inc(proto_perl->Iutf8_X_LV, param);
12325     PL_utf8_X_LVT       = sv_dup_inc(proto_perl->Iutf8_X_LVT, param);
12326     PL_utf8_X_T = sv_dup_inc(proto_perl->Iutf8_X_T, param);
12327     PL_utf8_X_V = sv_dup_inc(proto_perl->Iutf8_X_V, param);
12328     PL_utf8_X_LV_LVT_V  = sv_dup_inc(proto_perl->Iutf8_X_LV_LVT_V, param);
12329     PL_utf8_toupper     = sv_dup_inc(proto_perl->Iutf8_toupper, param);
12330     PL_utf8_totitle     = sv_dup_inc(proto_perl->Iutf8_totitle, param);
12331     PL_utf8_tolower     = sv_dup_inc(proto_perl->Iutf8_tolower, param);
12332     PL_utf8_tofold      = sv_dup_inc(proto_perl->Iutf8_tofold, param);
12333     PL_utf8_idstart     = sv_dup_inc(proto_perl->Iutf8_idstart, param);
12334     PL_utf8_idcont      = sv_dup_inc(proto_perl->Iutf8_idcont, param);
12335
12336     /* Did the locale setup indicate UTF-8? */
12337     PL_utf8locale       = proto_perl->Iutf8locale;
12338     /* Unicode features (see perlrun/-C) */
12339     PL_unicode          = proto_perl->Iunicode;
12340
12341     /* Pre-5.8 signals control */
12342     PL_signals          = proto_perl->Isignals;
12343
12344     /* times() ticks per second */
12345     PL_clocktick        = proto_perl->Iclocktick;
12346
12347     /* Recursion stopper for PerlIO_find_layer */
12348     PL_in_load_module   = proto_perl->Iin_load_module;
12349
12350     /* sort() routine */
12351     PL_sort_RealCmp     = proto_perl->Isort_RealCmp;
12352
12353     /* Not really needed/useful since the reenrant_retint is "volatile",
12354      * but do it for consistency's sake. */
12355     PL_reentrant_retint = proto_perl->Ireentrant_retint;
12356
12357     /* Hooks to shared SVs and locks. */
12358     PL_sharehook        = proto_perl->Isharehook;
12359     PL_lockhook         = proto_perl->Ilockhook;
12360     PL_unlockhook       = proto_perl->Iunlockhook;
12361     PL_threadhook       = proto_perl->Ithreadhook;
12362     PL_destroyhook      = proto_perl->Idestroyhook;
12363
12364 #ifdef THREADS_HAVE_PIDS
12365     PL_ppid             = proto_perl->Ippid;
12366 #endif
12367
12368     /* swatch cache */
12369     PL_last_swash_hv    = NULL; /* reinits on demand */
12370     PL_last_swash_klen  = 0;
12371     PL_last_swash_key[0]= '\0';
12372     PL_last_swash_tmps  = (U8*)NULL;
12373     PL_last_swash_slen  = 0;
12374
12375     PL_glob_index       = proto_perl->Iglob_index;
12376     PL_srand_called     = proto_perl->Isrand_called;
12377
12378     if (proto_perl->Ipsig_pend) {
12379         Newxz(PL_psig_pend, SIG_SIZE, int);
12380     }
12381     else {
12382         PL_psig_pend    = (int*)NULL;
12383     }
12384
12385     if (proto_perl->Ipsig_name) {
12386         Newx(PL_psig_name, 2 * SIG_SIZE, SV*);
12387         sv_dup_inc_multiple(proto_perl->Ipsig_name, PL_psig_name, 2 * SIG_SIZE,
12388                             param);
12389         PL_psig_ptr = PL_psig_name + SIG_SIZE;
12390     }
12391     else {
12392         PL_psig_ptr     = (SV**)NULL;
12393         PL_psig_name    = (SV**)NULL;
12394     }
12395
12396     /* intrpvar.h stuff */
12397
12398     if (flags & CLONEf_COPY_STACKS) {
12399         /* next allocation will be PL_tmps_stack[PL_tmps_ix+1] */
12400         PL_tmps_ix              = proto_perl->Itmps_ix;
12401         PL_tmps_max             = proto_perl->Itmps_max;
12402         PL_tmps_floor           = proto_perl->Itmps_floor;
12403         Newx(PL_tmps_stack, PL_tmps_max, SV*);
12404         sv_dup_inc_multiple(proto_perl->Itmps_stack, PL_tmps_stack,
12405                             PL_tmps_ix+1, param);
12406
12407         /* next PUSHMARK() sets *(PL_markstack_ptr+1) */
12408         i = proto_perl->Imarkstack_max - proto_perl->Imarkstack;
12409         Newxz(PL_markstack, i, I32);
12410         PL_markstack_max        = PL_markstack + (proto_perl->Imarkstack_max
12411                                                   - proto_perl->Imarkstack);
12412         PL_markstack_ptr        = PL_markstack + (proto_perl->Imarkstack_ptr
12413                                                   - proto_perl->Imarkstack);
12414         Copy(proto_perl->Imarkstack, PL_markstack,
12415              PL_markstack_ptr - PL_markstack + 1, I32);
12416
12417         /* next push_scope()/ENTER sets PL_scopestack[PL_scopestack_ix]
12418          * NOTE: unlike the others! */
12419         PL_scopestack_ix        = proto_perl->Iscopestack_ix;
12420         PL_scopestack_max       = proto_perl->Iscopestack_max;
12421         Newxz(PL_scopestack, PL_scopestack_max, I32);
12422         Copy(proto_perl->Iscopestack, PL_scopestack, PL_scopestack_ix, I32);
12423
12424 #ifdef DEBUGGING
12425         Newxz(PL_scopestack_name, PL_scopestack_max, const char *);
12426         Copy(proto_perl->Iscopestack_name, PL_scopestack_name, PL_scopestack_ix, const char *);
12427 #endif
12428         /* NOTE: si_dup() looks at PL_markstack */
12429         PL_curstackinfo         = si_dup(proto_perl->Icurstackinfo, param);
12430
12431         /* PL_curstack          = PL_curstackinfo->si_stack; */
12432         PL_curstack             = av_dup(proto_perl->Icurstack, param);
12433         PL_mainstack            = av_dup(proto_perl->Imainstack, param);
12434
12435         /* next PUSHs() etc. set *(PL_stack_sp+1) */
12436         PL_stack_base           = AvARRAY(PL_curstack);
12437         PL_stack_sp             = PL_stack_base + (proto_perl->Istack_sp
12438                                                    - proto_perl->Istack_base);
12439         PL_stack_max            = PL_stack_base + AvMAX(PL_curstack);
12440
12441         /* next SSPUSHFOO() sets PL_savestack[PL_savestack_ix]
12442          * NOTE: unlike the others! */
12443         PL_savestack_ix         = proto_perl->Isavestack_ix;
12444         PL_savestack_max        = proto_perl->Isavestack_max;
12445         /*Newxz(PL_savestack, PL_savestack_max, ANY);*/
12446         PL_savestack            = ss_dup(proto_perl, param);
12447     }
12448     else {
12449         init_stacks();
12450         ENTER;                  /* perl_destruct() wants to LEAVE; */
12451
12452         /* although we're not duplicating the tmps stack, we should still
12453          * add entries for any SVs on the tmps stack that got cloned by a
12454          * non-refcount means (eg a temp in @_); otherwise they will be
12455          * orphaned
12456          */
12457         for (i = 0; i<= proto_perl->Itmps_ix; i++) {
12458             SV * const nsv = MUTABLE_SV(ptr_table_fetch(PL_ptr_table,
12459                     proto_perl->Itmps_stack[i]));
12460             if (nsv && !SvREFCNT(nsv)) {
12461                 PUSH_EXTEND_MORTAL__SV_C(SvREFCNT_inc_simple(nsv));
12462             }
12463         }
12464     }
12465
12466     PL_start_env        = proto_perl->Istart_env;       /* XXXXXX */
12467     PL_top_env          = &PL_start_env;
12468
12469     PL_op               = proto_perl->Iop;
12470
12471     PL_Sv               = NULL;
12472     PL_Xpv              = (XPV*)NULL;
12473     my_perl->Ina        = proto_perl->Ina;
12474
12475     PL_statbuf          = proto_perl->Istatbuf;
12476     PL_statcache        = proto_perl->Istatcache;
12477     PL_statgv           = gv_dup(proto_perl->Istatgv, param);
12478     PL_statname         = sv_dup_inc(proto_perl->Istatname, param);
12479 #ifdef HAS_TIMES
12480     PL_timesbuf         = proto_perl->Itimesbuf;
12481 #endif
12482
12483     PL_tainted          = proto_perl->Itainted;
12484     PL_curpm            = proto_perl->Icurpm;   /* XXX No PMOP ref count */
12485     PL_rs               = sv_dup_inc(proto_perl->Irs, param);
12486     PL_last_in_gv       = gv_dup(proto_perl->Ilast_in_gv, param);
12487     PL_defoutgv         = gv_dup_inc(proto_perl->Idefoutgv, param);
12488     PL_chopset          = proto_perl->Ichopset; /* XXX never deallocated */
12489     PL_toptarget        = sv_dup_inc(proto_perl->Itoptarget, param);
12490     PL_bodytarget       = sv_dup_inc(proto_perl->Ibodytarget, param);
12491     PL_formtarget       = sv_dup(proto_perl->Iformtarget, param);
12492
12493     PL_restartjmpenv    = proto_perl->Irestartjmpenv;
12494     PL_restartop        = proto_perl->Irestartop;
12495     PL_in_eval          = proto_perl->Iin_eval;
12496     PL_delaymagic       = proto_perl->Idelaymagic;
12497     PL_dirty            = proto_perl->Idirty;
12498     PL_localizing       = proto_perl->Ilocalizing;
12499
12500     PL_errors           = sv_dup_inc(proto_perl->Ierrors, param);
12501     PL_hv_fetch_ent_mh  = NULL;
12502     PL_modcount         = proto_perl->Imodcount;
12503     PL_lastgotoprobe    = NULL;
12504     PL_dumpindent       = proto_perl->Idumpindent;
12505
12506     PL_sortcop          = (OP*)any_dup(proto_perl->Isortcop, proto_perl);
12507     PL_sortstash        = hv_dup(proto_perl->Isortstash, param);
12508     PL_firstgv          = gv_dup(proto_perl->Ifirstgv, param);
12509     PL_secondgv         = gv_dup(proto_perl->Isecondgv, param);
12510     PL_efloatbuf        = NULL;         /* reinits on demand */
12511     PL_efloatsize       = 0;                    /* reinits on demand */
12512
12513     /* regex stuff */
12514
12515     PL_screamfirst      = NULL;
12516     PL_screamnext       = NULL;
12517     PL_maxscream        = -1;                   /* reinits on demand */
12518     PL_lastscream       = NULL;
12519
12520
12521     PL_regdummy         = proto_perl->Iregdummy;
12522     PL_colorset         = 0;            /* reinits PL_colors[] */
12523     /*PL_colors[6]      = {0,0,0,0,0,0};*/
12524
12525
12526
12527     /* Pluggable optimizer */
12528     PL_peepp            = proto_perl->Ipeepp;
12529     /* op_free() hook */
12530     PL_opfreehook       = proto_perl->Iopfreehook;
12531
12532     PL_stashcache       = newHV();
12533
12534     PL_watchaddr        = (char **) ptr_table_fetch(PL_ptr_table,
12535                                             proto_perl->Iwatchaddr);
12536     PL_watchok          = PL_watchaddr ? * PL_watchaddr : NULL;
12537     if (PL_debug && PL_watchaddr) {
12538         PerlIO_printf(Perl_debug_log,
12539           "WATCHING: %"UVxf" cloned as %"UVxf" with value %"UVxf"\n",
12540           PTR2UV(proto_perl->Iwatchaddr), PTR2UV(PL_watchaddr),
12541           PTR2UV(PL_watchok));
12542     }
12543
12544     PL_registered_mros  = hv_dup_inc(proto_perl->Iregistered_mros, param);
12545
12546     /* Call the ->CLONE method, if it exists, for each of the stashes
12547        identified by sv_dup() above.
12548     */
12549     while(av_len(param->stashes) != -1) {
12550         HV* const stash = MUTABLE_HV(av_shift(param->stashes));
12551         GV* const cloner = gv_fetchmethod_autoload(stash, "CLONE", 0);
12552         if (cloner && GvCV(cloner)) {
12553             dSP;
12554             ENTER;
12555             SAVETMPS;
12556             PUSHMARK(SP);
12557             mXPUSHs(newSVhek(HvNAME_HEK(stash)));
12558             PUTBACK;
12559             call_sv(MUTABLE_SV(GvCV(cloner)), G_DISCARD);
12560             FREETMPS;
12561             LEAVE;
12562         }
12563     }
12564
12565     if (!(flags & CLONEf_KEEP_PTR_TABLE)) {
12566         ptr_table_free(PL_ptr_table);
12567         PL_ptr_table = NULL;
12568     }
12569
12570
12571     SvREFCNT_dec(param->stashes);
12572
12573     /* orphaned? eg threads->new inside BEGIN or use */
12574     if (PL_compcv && ! SvREFCNT(PL_compcv)) {
12575         SvREFCNT_inc_simple_void(PL_compcv);
12576         SAVEFREESV(PL_compcv);
12577     }
12578
12579     return my_perl;
12580 }
12581
12582 #endif /* USE_ITHREADS */
12583
12584 /*
12585 =head1 Unicode Support
12586
12587 =for apidoc sv_recode_to_utf8
12588
12589 The encoding is assumed to be an Encode object, on entry the PV
12590 of the sv is assumed to be octets in that encoding, and the sv
12591 will be converted into Unicode (and UTF-8).
12592
12593 If the sv already is UTF-8 (or if it is not POK), or if the encoding
12594 is not a reference, nothing is done to the sv.  If the encoding is not
12595 an C<Encode::XS> Encoding object, bad things will happen.
12596 (See F<lib/encoding.pm> and L<Encode>).
12597
12598 The PV of the sv is returned.
12599
12600 =cut */
12601
12602 char *
12603 Perl_sv_recode_to_utf8(pTHX_ SV *sv, SV *encoding)
12604 {
12605     dVAR;
12606
12607     PERL_ARGS_ASSERT_SV_RECODE_TO_UTF8;
12608
12609     if (SvPOK(sv) && !SvUTF8(sv) && !IN_BYTES && SvROK(encoding)) {
12610         SV *uni;
12611         STRLEN len;
12612         const char *s;
12613         dSP;
12614         ENTER;
12615         SAVETMPS;
12616         save_re_context();
12617         PUSHMARK(sp);
12618         EXTEND(SP, 3);
12619         XPUSHs(encoding);
12620         XPUSHs(sv);
12621 /*
12622   NI-S 2002/07/09
12623   Passing sv_yes is wrong - it needs to be or'ed set of constants
12624   for Encode::XS, while UTf-8 decode (currently) assumes a true value means
12625   remove converted chars from source.
12626
12627   Both will default the value - let them.
12628
12629         XPUSHs(&PL_sv_yes);
12630 */
12631         PUTBACK;
12632         call_method("decode", G_SCALAR);
12633         SPAGAIN;
12634         uni = POPs;
12635         PUTBACK;
12636         s = SvPV_const(uni, len);
12637         if (s != SvPVX_const(sv)) {
12638             SvGROW(sv, len + 1);
12639             Move(s, SvPVX(sv), len + 1, char);
12640             SvCUR_set(sv, len);
12641         }
12642         FREETMPS;
12643         LEAVE;
12644         SvUTF8_on(sv);
12645         return SvPVX(sv);
12646     }
12647     return SvPOKp(sv) ? SvPVX(sv) : NULL;
12648 }
12649
12650 /*
12651 =for apidoc sv_cat_decode
12652
12653 The encoding is assumed to be an Encode object, the PV of the ssv is
12654 assumed to be octets in that encoding and decoding the input starts
12655 from the position which (PV + *offset) pointed to.  The dsv will be
12656 concatenated the decoded UTF-8 string from ssv.  Decoding will terminate
12657 when the string tstr appears in decoding output or the input ends on
12658 the PV of the ssv. The value which the offset points will be modified
12659 to the last input position on the ssv.
12660
12661 Returns TRUE if the terminator was found, else returns FALSE.
12662
12663 =cut */
12664
12665 bool
12666 Perl_sv_cat_decode(pTHX_ SV *dsv, SV *encoding,
12667                    SV *ssv, int *offset, char *tstr, int tlen)
12668 {
12669     dVAR;
12670     bool ret = FALSE;
12671
12672     PERL_ARGS_ASSERT_SV_CAT_DECODE;
12673
12674     if (SvPOK(ssv) && SvPOK(dsv) && SvROK(encoding) && offset) {
12675         SV *offsv;
12676         dSP;
12677         ENTER;
12678         SAVETMPS;
12679         save_re_context();
12680         PUSHMARK(sp);
12681         EXTEND(SP, 6);
12682         XPUSHs(encoding);
12683         XPUSHs(dsv);
12684         XPUSHs(ssv);
12685         offsv = newSViv(*offset);
12686         mXPUSHs(offsv);
12687         mXPUSHp(tstr, tlen);
12688         PUTBACK;
12689         call_method("cat_decode", G_SCALAR);
12690         SPAGAIN;
12691         ret = SvTRUE(TOPs);
12692         *offset = SvIV(offsv);
12693         PUTBACK;
12694         FREETMPS;
12695         LEAVE;
12696     }
12697     else
12698         Perl_croak(aTHX_ "Invalid argument to sv_cat_decode");
12699     return ret;
12700
12701 }
12702
12703 /* ---------------------------------------------------------------------
12704  *
12705  * support functions for report_uninit()
12706  */
12707
12708 /* the maxiumum size of array or hash where we will scan looking
12709  * for the undefined element that triggered the warning */
12710
12711 #define FUV_MAX_SEARCH_SIZE 1000
12712
12713 /* Look for an entry in the hash whose value has the same SV as val;
12714  * If so, return a mortal copy of the key. */
12715
12716 STATIC SV*
12717 S_find_hash_subscript(pTHX_ const HV *const hv, const SV *const val)
12718 {
12719     dVAR;
12720     register HE **array;
12721     I32 i;
12722
12723     PERL_ARGS_ASSERT_FIND_HASH_SUBSCRIPT;
12724
12725     if (!hv || SvMAGICAL(hv) || !HvARRAY(hv) ||
12726                         (HvTOTALKEYS(hv) > FUV_MAX_SEARCH_SIZE))
12727         return NULL;
12728
12729     array = HvARRAY(hv);
12730
12731     for (i=HvMAX(hv); i>0; i--) {
12732         register HE *entry;
12733         for (entry = array[i]; entry; entry = HeNEXT(entry)) {
12734             if (HeVAL(entry) != val)
12735                 continue;
12736             if (    HeVAL(entry) == &PL_sv_undef ||
12737                     HeVAL(entry) == &PL_sv_placeholder)
12738                 continue;
12739             if (!HeKEY(entry))
12740                 return NULL;
12741             if (HeKLEN(entry) == HEf_SVKEY)
12742                 return sv_mortalcopy(HeKEY_sv(entry));
12743             return sv_2mortal(newSVhek(HeKEY_hek(entry)));
12744         }
12745     }
12746     return NULL;
12747 }
12748
12749 /* Look for an entry in the array whose value has the same SV as val;
12750  * If so, return the index, otherwise return -1. */
12751
12752 STATIC I32
12753 S_find_array_subscript(pTHX_ const AV *const av, const SV *const val)
12754 {
12755     dVAR;
12756
12757     PERL_ARGS_ASSERT_FIND_ARRAY_SUBSCRIPT;
12758
12759     if (!av || SvMAGICAL(av) || !AvARRAY(av) ||
12760                         (AvFILLp(av) > FUV_MAX_SEARCH_SIZE))
12761         return -1;
12762
12763     if (val != &PL_sv_undef) {
12764         SV ** const svp = AvARRAY(av);
12765         I32 i;
12766
12767         for (i=AvFILLp(av); i>=0; i--)
12768             if (svp[i] == val)
12769                 return i;
12770     }
12771     return -1;
12772 }
12773
12774 /* S_varname(): return the name of a variable, optionally with a subscript.
12775  * If gv is non-zero, use the name of that global, along with gvtype (one
12776  * of "$", "@", "%"); otherwise use the name of the lexical at pad offset
12777  * targ.  Depending on the value of the subscript_type flag, return:
12778  */
12779
12780 #define FUV_SUBSCRIPT_NONE      1       /* "@foo"          */
12781 #define FUV_SUBSCRIPT_ARRAY     2       /* "$foo[aindex]"  */
12782 #define FUV_SUBSCRIPT_HASH      3       /* "$foo{keyname}" */
12783 #define FUV_SUBSCRIPT_WITHIN    4       /* "within @foo"   */
12784
12785 STATIC SV*
12786 S_varname(pTHX_ const GV *const gv, const char gvtype, PADOFFSET targ,
12787         const SV *const keyname, I32 aindex, int subscript_type)
12788 {
12789
12790     SV * const name = sv_newmortal();
12791     if (gv) {
12792         char buffer[2];
12793         buffer[0] = gvtype;
12794         buffer[1] = 0;
12795
12796         /* as gv_fullname4(), but add literal '^' for $^FOO names  */
12797
12798         gv_fullname4(name, gv, buffer, 0);
12799
12800         if ((unsigned int)SvPVX(name)[1] <= 26) {
12801             buffer[0] = '^';
12802             buffer[1] = SvPVX(name)[1] + 'A' - 1;
12803
12804             /* Swap the 1 unprintable control character for the 2 byte pretty
12805                version - ie substr($name, 1, 1) = $buffer; */
12806             sv_insert(name, 1, 1, buffer, 2);
12807         }
12808     }
12809     else {
12810         CV * const cv = find_runcv(NULL);
12811         SV *sv;
12812         AV *av;
12813
12814         if (!cv || !CvPADLIST(cv))
12815             return NULL;
12816         av = MUTABLE_AV((*av_fetch(CvPADLIST(cv), 0, FALSE)));
12817         sv = *av_fetch(av, targ, FALSE);
12818         sv_setpvn(name, SvPV_nolen_const(sv), SvCUR(sv));
12819     }
12820
12821     if (subscript_type == FUV_SUBSCRIPT_HASH) {
12822         SV * const sv = newSV(0);
12823         *SvPVX(name) = '$';
12824         Perl_sv_catpvf(aTHX_ name, "{%s}",
12825             pv_display(sv,SvPVX_const(keyname), SvCUR(keyname), 0, 32));
12826         SvREFCNT_dec(sv);
12827     }
12828     else if (subscript_type == FUV_SUBSCRIPT_ARRAY) {
12829         *SvPVX(name) = '$';
12830         Perl_sv_catpvf(aTHX_ name, "[%"IVdf"]", (IV)aindex);
12831     }
12832     else if (subscript_type == FUV_SUBSCRIPT_WITHIN) {
12833         /* We know that name has no magic, so can use 0 instead of SV_GMAGIC */
12834         Perl_sv_insert_flags(aTHX_ name, 0, 0,  STR_WITH_LEN("within "), 0);
12835     }
12836
12837     return name;
12838 }
12839
12840
12841 /*
12842 =for apidoc find_uninit_var
12843
12844 Find the name of the undefined variable (if any) that caused the operator o
12845 to issue a "Use of uninitialized value" warning.
12846 If match is true, only return a name if it's value matches uninit_sv.
12847 So roughly speaking, if a unary operator (such as OP_COS) generates a
12848 warning, then following the direct child of the op may yield an
12849 OP_PADSV or OP_GV that gives the name of the undefined variable. On the
12850 other hand, with OP_ADD there are two branches to follow, so we only print
12851 the variable name if we get an exact match.
12852
12853 The name is returned as a mortal SV.
12854
12855 Assumes that PL_op is the op that originally triggered the error, and that
12856 PL_comppad/PL_curpad points to the currently executing pad.
12857
12858 =cut
12859 */
12860
12861 STATIC SV *
12862 S_find_uninit_var(pTHX_ const OP *const obase, const SV *const uninit_sv,
12863                   bool match)
12864 {
12865     dVAR;
12866     SV *sv;
12867     const GV *gv;
12868     const OP *o, *o2, *kid;
12869
12870     if (!obase || (match && (!uninit_sv || uninit_sv == &PL_sv_undef ||
12871                             uninit_sv == &PL_sv_placeholder)))
12872         return NULL;
12873
12874     switch (obase->op_type) {
12875
12876     case OP_RV2AV:
12877     case OP_RV2HV:
12878     case OP_PADAV:
12879     case OP_PADHV:
12880       {
12881         const bool pad  = (obase->op_type == OP_PADAV || obase->op_type == OP_PADHV);
12882         const bool hash = (obase->op_type == OP_PADHV || obase->op_type == OP_RV2HV);
12883         I32 index = 0;
12884         SV *keysv = NULL;
12885         int subscript_type = FUV_SUBSCRIPT_WITHIN;
12886
12887         if (pad) { /* @lex, %lex */
12888             sv = PAD_SVl(obase->op_targ);
12889             gv = NULL;
12890         }
12891         else {
12892             if (cUNOPx(obase)->op_first->op_type == OP_GV) {
12893             /* @global, %global */
12894                 gv = cGVOPx_gv(cUNOPx(obase)->op_first);
12895                 if (!gv)
12896                     break;
12897                 sv = hash ? MUTABLE_SV(GvHV(gv)): MUTABLE_SV(GvAV(gv));
12898             }
12899             else /* @{expr}, %{expr} */
12900                 return find_uninit_var(cUNOPx(obase)->op_first,
12901                                                     uninit_sv, match);
12902         }
12903
12904         /* attempt to find a match within the aggregate */
12905         if (hash) {
12906             keysv = find_hash_subscript((const HV*)sv, uninit_sv);
12907             if (keysv)
12908                 subscript_type = FUV_SUBSCRIPT_HASH;
12909         }
12910         else {
12911             index = find_array_subscript((const AV *)sv, uninit_sv);
12912             if (index >= 0)
12913                 subscript_type = FUV_SUBSCRIPT_ARRAY;
12914         }
12915
12916         if (match && subscript_type == FUV_SUBSCRIPT_WITHIN)
12917             break;
12918
12919         return varname(gv, hash ? '%' : '@', obase->op_targ,
12920                                     keysv, index, subscript_type);
12921       }
12922
12923     case OP_PADSV:
12924         if (match && PAD_SVl(obase->op_targ) != uninit_sv)
12925             break;
12926         return varname(NULL, '$', obase->op_targ,
12927                                     NULL, 0, FUV_SUBSCRIPT_NONE);
12928
12929     case OP_GVSV:
12930         gv = cGVOPx_gv(obase);
12931         if (!gv || (match && GvSV(gv) != uninit_sv))
12932             break;
12933         return varname(gv, '$', 0, NULL, 0, FUV_SUBSCRIPT_NONE);
12934
12935     case OP_AELEMFAST:
12936         if (obase->op_flags & OPf_SPECIAL) { /* lexical array */
12937             if (match) {
12938                 SV **svp;
12939                 AV *av = MUTABLE_AV(PAD_SV(obase->op_targ));
12940                 if (!av || SvRMAGICAL(av))
12941                     break;
12942                 svp = av_fetch(av, (I32)obase->op_private, FALSE);
12943                 if (!svp || *svp != uninit_sv)
12944                     break;
12945             }
12946             return varname(NULL, '$', obase->op_targ,
12947                     NULL, (I32)obase->op_private, FUV_SUBSCRIPT_ARRAY);
12948         }
12949         else {
12950             gv = cGVOPx_gv(obase);
12951             if (!gv)
12952                 break;
12953             if (match) {
12954                 SV **svp;
12955                 AV *const av = GvAV(gv);
12956                 if (!av || SvRMAGICAL(av))
12957                     break;
12958                 svp = av_fetch(av, (I32)obase->op_private, FALSE);
12959                 if (!svp || *svp != uninit_sv)
12960                     break;
12961             }
12962             return varname(gv, '$', 0,
12963                     NULL, (I32)obase->op_private, FUV_SUBSCRIPT_ARRAY);
12964         }
12965         break;
12966
12967     case OP_EXISTS:
12968         o = cUNOPx(obase)->op_first;
12969         if (!o || o->op_type != OP_NULL ||
12970                 ! (o->op_targ == OP_AELEM || o->op_targ == OP_HELEM))
12971             break;
12972         return find_uninit_var(cBINOPo->op_last, uninit_sv, match);
12973
12974     case OP_AELEM:
12975     case OP_HELEM:
12976         if (PL_op == obase)
12977             /* $a[uninit_expr] or $h{uninit_expr} */
12978             return find_uninit_var(cBINOPx(obase)->op_last, uninit_sv, match);
12979
12980         gv = NULL;
12981         o = cBINOPx(obase)->op_first;
12982         kid = cBINOPx(obase)->op_last;
12983
12984         /* get the av or hv, and optionally the gv */
12985         sv = NULL;
12986         if  (o->op_type == OP_PADAV || o->op_type == OP_PADHV) {
12987             sv = PAD_SV(o->op_targ);
12988         }
12989         else if ((o->op_type == OP_RV2AV || o->op_type == OP_RV2HV)
12990                 && cUNOPo->op_first->op_type == OP_GV)
12991         {
12992             gv = cGVOPx_gv(cUNOPo->op_first);
12993             if (!gv)
12994                 break;
12995             sv = o->op_type
12996                 == OP_RV2HV ? MUTABLE_SV(GvHV(gv)) : MUTABLE_SV(GvAV(gv));
12997         }
12998         if (!sv)
12999             break;
13000
13001         if (kid && kid->op_type == OP_CONST && SvOK(cSVOPx_sv(kid))) {
13002             /* index is constant */
13003             if (match) {
13004                 if (SvMAGICAL(sv))
13005                     break;
13006                 if (obase->op_type == OP_HELEM) {
13007                     HE* he = hv_fetch_ent(MUTABLE_HV(sv), cSVOPx_sv(kid), 0, 0);
13008                     if (!he || HeVAL(he) != uninit_sv)
13009                         break;
13010                 }
13011                 else {
13012                     SV * const * const svp = av_fetch(MUTABLE_AV(sv), SvIV(cSVOPx_sv(kid)), FALSE);
13013                     if (!svp || *svp != uninit_sv)
13014                         break;
13015                 }
13016             }
13017             if (obase->op_type == OP_HELEM)
13018                 return varname(gv, '%', o->op_targ,
13019                             cSVOPx_sv(kid), 0, FUV_SUBSCRIPT_HASH);
13020             else
13021                 return varname(gv, '@', o->op_targ, NULL,
13022                             SvIV(cSVOPx_sv(kid)), FUV_SUBSCRIPT_ARRAY);
13023         }
13024         else  {
13025             /* index is an expression;
13026              * attempt to find a match within the aggregate */
13027             if (obase->op_type == OP_HELEM) {
13028                 SV * const keysv = find_hash_subscript((const HV*)sv, uninit_sv);
13029                 if (keysv)
13030                     return varname(gv, '%', o->op_targ,
13031                                                 keysv, 0, FUV_SUBSCRIPT_HASH);
13032             }
13033             else {
13034                 const I32 index
13035                     = find_array_subscript((const AV *)sv, uninit_sv);
13036                 if (index >= 0)
13037                     return varname(gv, '@', o->op_targ,
13038                                         NULL, index, FUV_SUBSCRIPT_ARRAY);
13039             }
13040             if (match)
13041                 break;
13042             return varname(gv,
13043                 (o->op_type == OP_PADAV || o->op_type == OP_RV2AV)
13044                 ? '@' : '%',
13045                 o->op_targ, NULL, 0, FUV_SUBSCRIPT_WITHIN);
13046         }
13047         break;
13048
13049     case OP_AASSIGN:
13050         /* only examine RHS */
13051         return find_uninit_var(cBINOPx(obase)->op_first, uninit_sv, match);
13052
13053     case OP_OPEN:
13054         o = cUNOPx(obase)->op_first;
13055         if (o->op_type == OP_PUSHMARK)
13056             o = o->op_sibling;
13057
13058         if (!o->op_sibling) {
13059             /* one-arg version of open is highly magical */
13060
13061             if (o->op_type == OP_GV) { /* open FOO; */
13062                 gv = cGVOPx_gv(o);
13063                 if (match && GvSV(gv) != uninit_sv)
13064                     break;
13065                 return varname(gv, '$', 0,
13066                             NULL, 0, FUV_SUBSCRIPT_NONE);
13067             }
13068             /* other possibilities not handled are:
13069              * open $x; or open my $x;  should return '${*$x}'
13070              * open expr;               should return '$'.expr ideally
13071              */
13072              break;
13073         }
13074         goto do_op;
13075
13076     /* ops where $_ may be an implicit arg */
13077     case OP_TRANS:
13078     case OP_SUBST:
13079     case OP_MATCH:
13080         if ( !(obase->op_flags & OPf_STACKED)) {
13081             if (uninit_sv == ((obase->op_private & OPpTARGET_MY)
13082                                  ? PAD_SVl(obase->op_targ)
13083                                  : DEFSV))
13084             {
13085                 sv = sv_newmortal();
13086                 sv_setpvs(sv, "$_");
13087                 return sv;
13088             }
13089         }
13090         goto do_op;
13091
13092     case OP_PRTF:
13093     case OP_PRINT:
13094     case OP_SAY:
13095         match = 1; /* print etc can return undef on defined args */
13096         /* skip filehandle as it can't produce 'undef' warning  */
13097         o = cUNOPx(obase)->op_first;
13098         if ((obase->op_flags & OPf_STACKED) && o->op_type == OP_PUSHMARK)
13099             o = o->op_sibling->op_sibling;
13100         goto do_op2;
13101
13102
13103     case OP_ENTEREVAL: /* could be eval $undef or $x='$undef'; eval $x */
13104     case OP_RV2SV:
13105     case OP_CUSTOM: /* XS or custom code could trigger random warnings */
13106
13107         /* the following ops are capable of returning PL_sv_undef even for
13108          * defined arg(s) */
13109
13110     case OP_BACKTICK:
13111     case OP_PIPE_OP:
13112     case OP_FILENO:
13113     case OP_BINMODE:
13114     case OP_TIED:
13115     case OP_GETC:
13116     case OP_SYSREAD:
13117     case OP_SEND:
13118     case OP_IOCTL:
13119     case OP_SOCKET:
13120     case OP_SOCKPAIR:
13121     case OP_BIND:
13122     case OP_CONNECT:
13123     case OP_LISTEN:
13124     case OP_ACCEPT:
13125     case OP_SHUTDOWN:
13126     case OP_SSOCKOPT:
13127     case OP_GETPEERNAME:
13128     case OP_FTRREAD:
13129     case OP_FTRWRITE:
13130     case OP_FTREXEC:
13131     case OP_FTROWNED:
13132     case OP_FTEREAD:
13133     case OP_FTEWRITE:
13134     case OP_FTEEXEC:
13135     case OP_FTEOWNED:
13136     case OP_FTIS:
13137     case OP_FTZERO:
13138     case OP_FTSIZE:
13139     case OP_FTFILE:
13140     case OP_FTDIR:
13141     case OP_FTLINK:
13142     case OP_FTPIPE:
13143     case OP_FTSOCK:
13144     case OP_FTBLK:
13145     case OP_FTCHR:
13146     case OP_FTTTY:
13147     case OP_FTSUID:
13148     case OP_FTSGID:
13149     case OP_FTSVTX:
13150     case OP_FTTEXT:
13151     case OP_FTBINARY:
13152     case OP_FTMTIME:
13153     case OP_FTATIME:
13154     case OP_FTCTIME:
13155     case OP_READLINK:
13156     case OP_OPEN_DIR:
13157     case OP_READDIR:
13158     case OP_TELLDIR:
13159     case OP_SEEKDIR:
13160     case OP_REWINDDIR:
13161     case OP_CLOSEDIR:
13162     case OP_GMTIME:
13163     case OP_ALARM:
13164     case OP_SEMGET:
13165     case OP_GETLOGIN:
13166     case OP_UNDEF:
13167     case OP_SUBSTR:
13168     case OP_AEACH:
13169     case OP_EACH:
13170     case OP_SORT:
13171     case OP_CALLER:
13172     case OP_DOFILE:
13173     case OP_PROTOTYPE:
13174     case OP_NCMP:
13175     case OP_SMARTMATCH:
13176     case OP_UNPACK:
13177     case OP_SYSOPEN:
13178     case OP_SYSSEEK:
13179         match = 1;
13180         goto do_op;
13181
13182     case OP_ENTERSUB:
13183     case OP_GOTO:
13184         /* XXX tmp hack: these two may call an XS sub, and currently
13185           XS subs don't have a SUB entry on the context stack, so CV and
13186           pad determination goes wrong, and BAD things happen. So, just
13187           don't try to determine the value under those circumstances.
13188           Need a better fix at dome point. DAPM 11/2007 */
13189         break;
13190
13191     case OP_FLIP:
13192     case OP_FLOP:
13193     {
13194         GV * const gv = gv_fetchpvs(".", GV_NOTQUAL, SVt_PV);
13195         if (gv && GvSV(gv) == uninit_sv)
13196             return newSVpvs_flags("$.", SVs_TEMP);
13197         goto do_op;
13198     }
13199
13200     case OP_POS:
13201         /* def-ness of rval pos() is independent of the def-ness of its arg */
13202         if ( !(obase->op_flags & OPf_MOD))
13203             break;
13204
13205     case OP_SCHOMP:
13206     case OP_CHOMP:
13207         if (SvROK(PL_rs) && uninit_sv == SvRV(PL_rs))
13208             return newSVpvs_flags("${$/}", SVs_TEMP);
13209         /*FALLTHROUGH*/
13210
13211     default:
13212     do_op:
13213         if (!(obase->op_flags & OPf_KIDS))
13214             break;
13215         o = cUNOPx(obase)->op_first;
13216         
13217     do_op2:
13218         if (!o)
13219             break;
13220
13221         /* if all except one arg are constant, or have no side-effects,
13222          * or are optimized away, then it's unambiguous */
13223         o2 = NULL;
13224         for (kid=o; kid; kid = kid->op_sibling) {
13225             if (kid) {
13226                 const OPCODE type = kid->op_type;
13227                 if ( (type == OP_CONST && SvOK(cSVOPx_sv(kid)))
13228                   || (type == OP_NULL  && ! (kid->op_flags & OPf_KIDS))
13229                   || (type == OP_PUSHMARK)
13230                 )
13231                 continue;
13232             }
13233             if (o2) { /* more than one found */
13234                 o2 = NULL;
13235                 break;
13236             }
13237             o2 = kid;
13238         }
13239         if (o2)
13240             return find_uninit_var(o2, uninit_sv, match);
13241
13242         /* scan all args */
13243         while (o) {
13244             sv = find_uninit_var(o, uninit_sv, 1);
13245             if (sv)
13246                 return sv;
13247             o = o->op_sibling;
13248         }
13249         break;
13250     }
13251     return NULL;
13252 }
13253
13254
13255 /*
13256 =for apidoc report_uninit
13257
13258 Print appropriate "Use of uninitialized variable" warning
13259
13260 =cut
13261 */
13262
13263 void
13264 Perl_report_uninit(pTHX_ const SV *uninit_sv)
13265 {
13266     dVAR;
13267     if (PL_op) {
13268         SV* varname = NULL;
13269         if (uninit_sv) {
13270             varname = find_uninit_var(PL_op, uninit_sv,0);
13271             if (varname)
13272                 sv_insert(varname, 0, 0, " ", 1);
13273         }
13274         Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
13275                 varname ? SvPV_nolen_const(varname) : "",
13276                 " in ", OP_DESC(PL_op));
13277     }
13278     else
13279         Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
13280                     "", "", "");
13281 }
13282
13283 /*
13284  * Local variables:
13285  * c-indentation-style: bsd
13286  * c-basic-offset: 4
13287  * indent-tabs-mode: t
13288  * End:
13289  *
13290  * ex: set ts=8 sts=4 sw=4 noet:
13291  */