This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
win32.c: Add mutexes around some calls
[perl5.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 #ifdef __VMS
35 # include <rms.h>
36 #endif
37
38 #ifdef __Lynx__
39 /* Missing proto on LynxOS */
40   char *gconvert(double, int, int,  char *);
41 #endif
42
43 #ifdef USE_QUADMATH
44 #  define SNPRINTF_G(nv, buffer, size, ndig) \
45     quadmath_snprintf(buffer, size, "%.*Qg", (int)ndig, (NV)(nv))
46 #else
47 #  define SNPRINTF_G(nv, buffer, size, ndig) \
48     PERL_UNUSED_RESULT(Gconvert((NV)(nv), (int)ndig, 0, buffer))
49 #endif
50
51 #ifndef SV_COW_THRESHOLD
52 #    define SV_COW_THRESHOLD                    0   /* COW iff len > K */
53 #endif
54 #ifndef SV_COWBUF_THRESHOLD
55 #    define SV_COWBUF_THRESHOLD                 1250 /* COW iff len > K */
56 #endif
57 #ifndef SV_COW_MAX_WASTE_THRESHOLD
58 #    define SV_COW_MAX_WASTE_THRESHOLD          80   /* COW iff (len - cur) < K */
59 #endif
60 #ifndef SV_COWBUF_WASTE_THRESHOLD
61 #    define SV_COWBUF_WASTE_THRESHOLD           80   /* COW iff (len - cur) < K */
62 #endif
63 #ifndef SV_COW_MAX_WASTE_FACTOR_THRESHOLD
64 #    define SV_COW_MAX_WASTE_FACTOR_THRESHOLD   2    /* COW iff len < (cur * K) */
65 #endif
66 #ifndef SV_COWBUF_WASTE_FACTOR_THRESHOLD
67 #    define SV_COWBUF_WASTE_FACTOR_THRESHOLD    2    /* COW iff len < (cur * K) */
68 #endif
69 /* Work around compiler warnings about unsigned >= THRESHOLD when thres-
70    hold is 0. */
71 #if SV_COW_THRESHOLD
72 # define GE_COW_THRESHOLD(cur) ((cur) >= SV_COW_THRESHOLD)
73 #else
74 # define GE_COW_THRESHOLD(cur) 1
75 #endif
76 #if SV_COWBUF_THRESHOLD
77 # define GE_COWBUF_THRESHOLD(cur) ((cur) >= SV_COWBUF_THRESHOLD)
78 #else
79 # define GE_COWBUF_THRESHOLD(cur) 1
80 #endif
81 #if SV_COW_MAX_WASTE_THRESHOLD
82 # define GE_COW_MAX_WASTE_THRESHOLD(cur,len) (((len)-(cur)) < SV_COW_MAX_WASTE_THRESHOLD)
83 #else
84 # define GE_COW_MAX_WASTE_THRESHOLD(cur,len) 1
85 #endif
86 #if SV_COWBUF_WASTE_THRESHOLD
87 # define GE_COWBUF_WASTE_THRESHOLD(cur,len) (((len)-(cur)) < SV_COWBUF_WASTE_THRESHOLD)
88 #else
89 # define GE_COWBUF_WASTE_THRESHOLD(cur,len) 1
90 #endif
91 #if SV_COW_MAX_WASTE_FACTOR_THRESHOLD
92 # define GE_COW_MAX_WASTE_FACTOR_THRESHOLD(cur,len) ((len) < SV_COW_MAX_WASTE_FACTOR_THRESHOLD * (cur))
93 #else
94 # define GE_COW_MAX_WASTE_FACTOR_THRESHOLD(cur,len) 1
95 #endif
96 #if SV_COWBUF_WASTE_FACTOR_THRESHOLD
97 # define GE_COWBUF_WASTE_FACTOR_THRESHOLD(cur,len) ((len) < SV_COWBUF_WASTE_FACTOR_THRESHOLD * (cur))
98 #else
99 # define GE_COWBUF_WASTE_FACTOR_THRESHOLD(cur,len) 1
100 #endif
101
102 #define CHECK_COW_THRESHOLD(cur,len) (\
103     GE_COW_THRESHOLD((cur)) && \
104     GE_COW_MAX_WASTE_THRESHOLD((cur),(len)) && \
105     GE_COW_MAX_WASTE_FACTOR_THRESHOLD((cur),(len)) \
106 )
107 #define CHECK_COWBUF_THRESHOLD(cur,len) (\
108     GE_COWBUF_THRESHOLD((cur)) && \
109     GE_COWBUF_WASTE_THRESHOLD((cur),(len)) && \
110     GE_COWBUF_WASTE_FACTOR_THRESHOLD((cur),(len)) \
111 )
112
113 #ifdef PERL_UTF8_CACHE_ASSERT
114 /* if adding more checks watch out for the following tests:
115  *   t/op/index.t t/op/length.t t/op/pat.t t/op/substr.t
116  *   lib/utf8.t lib/Unicode/Collate/t/index.t
117  * --jhi
118  */
119 #   define ASSERT_UTF8_CACHE(cache) \
120     STMT_START { if (cache) { assert((cache)[0] <= (cache)[1]); \
121                               assert((cache)[2] <= (cache)[3]); \
122                               assert((cache)[3] <= (cache)[1]);} \
123                               } STMT_END
124 #else
125 #   define ASSERT_UTF8_CACHE(cache) NOOP
126 #endif
127
128 static const char S_destroy[] = "DESTROY";
129 #define S_destroy_len (sizeof(S_destroy)-1)
130
131 /* ============================================================================
132
133 An SV (or AV, HV, etc.) is allocated in two parts: the head (struct
134 sv, av, hv...) contains type and reference count information, and for
135 many types, a pointer to the body (struct xrv, xpv, xpviv...), which
136 contains fields specific to each type.  Some types store all they need
137 in the head, so don't have a body.
138
139 In all but the most memory-paranoid configurations (ex: PURIFY), heads
140 and bodies are allocated out of arenas, which by default are
141 approximately 4K chunks of memory parcelled up into N heads or bodies.
142 Sv-bodies are allocated by their sv-type, guaranteeing size
143 consistency needed to allocate safely from arrays.
144
145 For SV-heads, the first slot in each arena is reserved, and holds a
146 link to the next arena, some flags, and a note of the number of slots.
147 Snaked through each arena chain is a linked list of free items; when
148 this becomes empty, an extra arena is allocated and divided up into N
149 items which are threaded into the free list.
150
151 SV-bodies are similar, but they use arena-sets by default, which
152 separate the link and info from the arena itself, and reclaim the 1st
153 slot in the arena.  SV-bodies are further described later.
154
155 The following global variables are associated with arenas:
156
157  PL_sv_arenaroot     pointer to list of SV arenas
158  PL_sv_root          pointer to list of free SV structures
159
160  PL_body_arenas      head of linked-list of body arenas
161  PL_body_roots[]     array of pointers to list of free bodies of svtype
162                      arrays are indexed by the svtype needed
163
164 A few special SV heads are not allocated from an arena, but are
165 instead directly created in the interpreter structure, eg PL_sv_undef.
166 The size of arenas can be changed from the default by setting
167 PERL_ARENA_SIZE appropriately at compile time.
168
169 The SV arena serves the secondary purpose of allowing still-live SVs
170 to be located and destroyed during final cleanup.
171
172 At the lowest level, the macros new_SV() and del_SV() grab and free
173 an SV head.  (If debugging with -DD, del_SV() calls the function S_del_sv()
174 to return the SV to the free list with error checking.) new_SV() calls
175 more_sv() / sv_add_arena() to add an extra arena if the free list is empty.
176 SVs in the free list have their SvTYPE field set to all ones.
177
178 At the time of very final cleanup, sv_free_arenas() is called from
179 perl_destruct() to physically free all the arenas allocated since the
180 start of the interpreter.
181
182 The internal function visit() scans the SV arenas list, and calls a specified
183 function for each SV it finds which is still live, I<i.e.> which has an SvTYPE
184 other than all 1's, and a non-zero SvREFCNT. visit() is used by the
185 following functions (specified as [function that calls visit()] / [function
186 called by visit() for each SV]):
187
188     sv_report_used() / do_report_used()
189                         dump all remaining SVs (debugging aid)
190
191     sv_clean_objs() / do_clean_objs(),do_clean_named_objs(),
192                       do_clean_named_io_objs(),do_curse()
193                         Attempt to free all objects pointed to by RVs,
194                         try to do the same for all objects indir-
195                         ectly referenced by typeglobs too, and
196                         then do a final sweep, cursing any
197                         objects that remain.  Called once from
198                         perl_destruct(), prior to calling sv_clean_all()
199                         below.
200
201     sv_clean_all() / do_clean_all()
202                         SvREFCNT_dec(sv) each remaining SV, possibly
203                         triggering an sv_free(). It also sets the
204                         SVf_BREAK flag on the SV to indicate that the
205                         refcnt has been artificially lowered, and thus
206                         stopping sv_free() from giving spurious warnings
207                         about SVs which unexpectedly have a refcnt
208                         of zero.  called repeatedly from perl_destruct()
209                         until there are no SVs left.
210
211 =head2 Arena allocator API Summary
212
213 Private API to rest of sv.c
214
215     new_SV(),  del_SV(),
216
217     new_XPVNV(), del_body()
218     etc
219
220 Public API:
221
222     sv_report_used(), sv_clean_objs(), sv_clean_all(), sv_free_arenas()
223
224 =cut
225
226  * ========================================================================= */
227
228 /*
229  * "A time to plant, and a time to uproot what was planted..."
230  */
231
232 #ifdef DEBUG_LEAKING_SCALARS
233 #  define FREE_SV_DEBUG_FILE(sv) STMT_START { \
234         if ((sv)->sv_debug_file) PerlMemShared_free((sv)->sv_debug_file); \
235     } STMT_END
236 #  define DEBUG_SV_SERIAL(sv)                                               \
237     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) del_SV\n",    \
238             PTR2UV(sv), (long)(sv)->sv_debug_serial))
239 #else
240 #  define FREE_SV_DEBUG_FILE(sv)
241 #  define DEBUG_SV_SERIAL(sv)   NOOP
242 #endif
243
244 /* Mark an SV head as unused, and add to free list.
245  *
246  * If SVf_BREAK is set, skip adding it to the free list, as this SV had
247  * its refcount artificially decremented during global destruction, so
248  * there may be dangling pointers to it. The last thing we want in that
249  * case is for it to be reused. */
250
251 #define plant_SV(p) \
252     STMT_START {                                        \
253         const U32 old_flags = SvFLAGS(p);                       \
254         MEM_LOG_DEL_SV(p, __FILE__, __LINE__, FUNCTION__);  \
255         DEBUG_SV_SERIAL(p);                             \
256         FREE_SV_DEBUG_FILE(p);                          \
257         POISON_SV_HEAD(p);                              \
258         SvFLAGS(p) = SVTYPEMASK;                        \
259         if (!(old_flags & SVf_BREAK)) {         \
260             SvARENA_CHAIN_SET(p, PL_sv_root);   \
261             PL_sv_root = (p);                           \
262         }                                               \
263         --PL_sv_count;                                  \
264     } STMT_END
265
266
267 /* make some more SVs by adding another arena */
268
269 SV*
270 Perl_more_sv(pTHX)
271 {
272     SV* sv;
273     char *chunk;                /* must use New here to match call to */
274     Newx(chunk,PERL_ARENA_SIZE,char);  /* Safefree() in sv_free_arenas() */
275     sv_add_arena(chunk, PERL_ARENA_SIZE, 0);
276     uproot_SV(sv);
277     return sv;
278 }
279
280 /* del_SV(): return an empty SV head to the free list */
281
282 #ifdef DEBUGGING
283
284 #define del_SV(p) \
285     STMT_START {                                        \
286         if (DEBUG_D_TEST)                               \
287             del_sv(p);                                  \
288         else                                            \
289             plant_SV(p);                                \
290     } STMT_END
291
292 STATIC void
293 S_del_sv(pTHX_ SV *p)
294 {
295     PERL_ARGS_ASSERT_DEL_SV;
296
297     if (DEBUG_D_TEST) {
298         SV* sva;
299         bool ok = 0;
300         for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
301             const SV * const sv = sva + 1;
302             const SV * const svend = &sva[SvREFCNT(sva)];
303             if (p >= sv && p < svend) {
304                 ok = 1;
305                 break;
306             }
307         }
308         if (!ok) {
309             Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
310                              "Attempt to free non-arena SV: 0x%" UVxf
311                              pTHX__FORMAT, PTR2UV(p) pTHX__VALUE);
312             return;
313         }
314     }
315     plant_SV(p);
316 }
317
318 #else /* ! DEBUGGING */
319
320 #define del_SV(p)   plant_SV(p)
321
322 #endif /* DEBUGGING */
323
324
325 /*
326 =for apidoc_section $SV
327
328 =for apidoc sv_add_arena
329
330 Given a chunk of memory, link it to the head of the list of arenas,
331 and split it into a list of free SVs.
332
333 =cut
334 */
335
336 static void
337 S_sv_add_arena(pTHX_ char *const ptr, const U32 size, const U32 flags)
338 {
339     SV *const sva = MUTABLE_SV(ptr);
340     SV* sv;
341     SV* svend;
342
343     PERL_ARGS_ASSERT_SV_ADD_ARENA;
344
345     /* The first SV in an arena isn't an SV. */
346     SvANY(sva) = (void *) PL_sv_arenaroot;              /* ptr to next arena */
347     SvREFCNT(sva) = size / sizeof(SV);          /* number of SV slots */
348     SvFLAGS(sva) = flags;                       /* FAKE if not to be freed */
349
350     PL_sv_arenaroot = sva;
351     PL_sv_root = sva + 1;
352
353     svend = &sva[SvREFCNT(sva) - 1];
354     sv = sva + 1;
355     while (sv < svend) {
356         SvARENA_CHAIN_SET(sv, (sv + 1));
357 #ifdef DEBUGGING
358         SvREFCNT(sv) = 0;
359 #endif
360         /* Must always set typemask because it's always checked in on cleanup
361            when the arenas are walked looking for objects.  */
362         SvFLAGS(sv) = SVTYPEMASK;
363         sv++;
364     }
365     SvARENA_CHAIN_SET(sv, 0);
366 #ifdef DEBUGGING
367     SvREFCNT(sv) = 0;
368 #endif
369     SvFLAGS(sv) = SVTYPEMASK;
370 }
371
372 /* visit(): call the named function for each non-free SV in the arenas
373  * whose flags field matches the flags/mask args. */
374
375 STATIC I32
376 S_visit(pTHX_ SVFUNC_t f, const U32 flags, const U32 mask)
377 {
378     SV* sva;
379     I32 visited = 0;
380
381     PERL_ARGS_ASSERT_VISIT;
382
383     for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
384         const SV * const svend = &sva[SvREFCNT(sva)];
385         SV* sv;
386         for (sv = sva + 1; sv < svend; ++sv) {
387             if (SvTYPE(sv) != (svtype)SVTYPEMASK
388                     && (sv->sv_flags & mask) == flags
389                     && SvREFCNT(sv))
390             {
391                 (*f)(aTHX_ sv);
392                 ++visited;
393             }
394         }
395     }
396     return visited;
397 }
398
399 #ifdef DEBUGGING
400
401 /* called by sv_report_used() for each live SV */
402
403 static void
404 do_report_used(pTHX_ SV *const sv)
405 {
406     if (SvTYPE(sv) != (svtype)SVTYPEMASK) {
407         PerlIO_printf(Perl_debug_log, "****\n");
408         sv_dump(sv);
409     }
410 }
411 #endif
412
413 /*
414 =for apidoc sv_report_used
415
416 Dump the contents of all SVs not yet freed (debugging aid).
417
418 =cut
419 */
420
421 void
422 Perl_sv_report_used(pTHX)
423 {
424 #ifdef DEBUGGING
425     visit(do_report_used, 0, 0);
426 #else
427     PERL_UNUSED_CONTEXT;
428 #endif
429 }
430
431 /* called by sv_clean_objs() for each live SV */
432
433 static void
434 do_clean_objs(pTHX_ SV *const ref)
435 {
436     assert (SvROK(ref));
437     {
438         SV * const target = SvRV(ref);
439         if (SvOBJECT(target)) {
440             DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning object ref:\n "), sv_dump(ref)));
441             if (SvWEAKREF(ref)) {
442                 sv_del_backref(target, ref);
443                 SvWEAKREF_off(ref);
444                 SvRV_set(ref, NULL);
445             } else {
446                 SvROK_off(ref);
447                 SvRV_set(ref, NULL);
448                 SvREFCNT_dec_NN(target);
449             }
450         }
451     }
452 }
453
454
455 /* clear any slots in a GV which hold objects - except IO;
456  * called by sv_clean_objs() for each live GV */
457
458 static void
459 do_clean_named_objs(pTHX_ SV *const sv)
460 {
461     SV *obj;
462     assert(SvTYPE(sv) == SVt_PVGV);
463     assert(isGV_with_GP(sv));
464     if (!GvGP(sv))
465         return;
466
467     /* freeing GP entries may indirectly free the current GV;
468      * hold onto it while we mess with the GP slots */
469     SvREFCNT_inc(sv);
470
471     if ( ((obj = GvSV(sv) )) && SvOBJECT(obj)) {
472         DEBUG_D((PerlIO_printf(Perl_debug_log,
473                 "Cleaning named glob SV object:\n "), sv_dump(obj)));
474         GvSV(sv) = NULL;
475         SvREFCNT_dec_NN(obj);
476     }
477     if ( ((obj = MUTABLE_SV(GvAV(sv)) )) && SvOBJECT(obj)) {
478         DEBUG_D((PerlIO_printf(Perl_debug_log,
479                 "Cleaning named glob AV object:\n "), sv_dump(obj)));
480         GvAV(sv) = NULL;
481         SvREFCNT_dec_NN(obj);
482     }
483     if ( ((obj = MUTABLE_SV(GvHV(sv)) )) && SvOBJECT(obj)) {
484         DEBUG_D((PerlIO_printf(Perl_debug_log,
485                 "Cleaning named glob HV object:\n "), sv_dump(obj)));
486         GvHV(sv) = NULL;
487         SvREFCNT_dec_NN(obj);
488     }
489     if ( ((obj = MUTABLE_SV(GvCV(sv)) )) && SvOBJECT(obj)) {
490         DEBUG_D((PerlIO_printf(Perl_debug_log,
491                 "Cleaning named glob CV object:\n "), sv_dump(obj)));
492         GvCV_set(sv, NULL);
493         SvREFCNT_dec_NN(obj);
494     }
495     SvREFCNT_dec_NN(sv); /* undo the inc above */
496 }
497
498 /* clear any IO slots in a GV which hold objects (except stderr, defout);
499  * called by sv_clean_objs() for each live GV */
500
501 static void
502 do_clean_named_io_objs(pTHX_ SV *const sv)
503 {
504     SV *obj;
505     assert(SvTYPE(sv) == SVt_PVGV);
506     assert(isGV_with_GP(sv));
507     if (!GvGP(sv) || sv == (SV*)PL_stderrgv || sv == (SV*)PL_defoutgv)
508         return;
509
510     SvREFCNT_inc(sv);
511     if ( ((obj = MUTABLE_SV(GvIO(sv)) )) && SvOBJECT(obj)) {
512         DEBUG_D((PerlIO_printf(Perl_debug_log,
513                 "Cleaning named glob IO object:\n "), sv_dump(obj)));
514         GvIOp(sv) = NULL;
515         SvREFCNT_dec_NN(obj);
516     }
517     SvREFCNT_dec_NN(sv); /* undo the inc above */
518 }
519
520 /* Void wrapper to pass to visit() */
521 static void
522 do_curse(pTHX_ SV * const sv) {
523     if ((PL_stderrgv && GvGP(PL_stderrgv) && (SV*)GvIO(PL_stderrgv) == sv)
524      || (PL_defoutgv && GvGP(PL_defoutgv) && (SV*)GvIO(PL_defoutgv) == sv))
525         return;
526     (void)curse(sv, 0);
527 }
528
529 /*
530 =for apidoc sv_clean_objs
531
532 Attempt to destroy all objects not yet freed.
533
534 =cut
535 */
536
537 void
538 Perl_sv_clean_objs(pTHX)
539 {
540     GV *olddef, *olderr;
541     PL_in_clean_objs = TRUE;
542     visit(do_clean_objs, SVf_ROK, SVf_ROK);
543     /* Some barnacles may yet remain, clinging to typeglobs.
544      * Run the non-IO destructors first: they may want to output
545      * error messages, close files etc */
546     visit(do_clean_named_objs, SVt_PVGV|SVpgv_GP, SVTYPEMASK|SVp_POK|SVpgv_GP);
547     visit(do_clean_named_io_objs, SVt_PVGV|SVpgv_GP, SVTYPEMASK|SVp_POK|SVpgv_GP);
548     /* And if there are some very tenacious barnacles clinging to arrays,
549        closures, or what have you.... */
550     visit(do_curse, SVs_OBJECT, SVs_OBJECT);
551     olddef = PL_defoutgv;
552     PL_defoutgv = NULL; /* disable skip of PL_defoutgv */
553     if (olddef && isGV_with_GP(olddef))
554         do_clean_named_io_objs(aTHX_ MUTABLE_SV(olddef));
555     olderr = PL_stderrgv;
556     PL_stderrgv = NULL; /* disable skip of PL_stderrgv */
557     if (olderr && isGV_with_GP(olderr))
558         do_clean_named_io_objs(aTHX_ MUTABLE_SV(olderr));
559     SvREFCNT_dec(olddef);
560     PL_in_clean_objs = FALSE;
561 }
562
563 /* called by sv_clean_all() for each live SV */
564
565 static void
566 do_clean_all(pTHX_ SV *const sv)
567 {
568     if (sv == (const SV *) PL_fdpid || sv == (const SV *)PL_strtab) {
569         /* don't clean pid table and strtab */
570         return;
571     }
572     DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning loops: SV at 0x%" UVxf "\n", PTR2UV(sv)) ));
573     SvFLAGS(sv) |= SVf_BREAK;
574     SvREFCNT_dec_NN(sv);
575 }
576
577 /*
578 =for apidoc sv_clean_all
579
580 Decrement the refcnt of each remaining SV, possibly triggering a
581 cleanup.  This function may have to be called multiple times to free
582 SVs which are in complex self-referential hierarchies.
583
584 =cut
585 */
586
587 I32
588 Perl_sv_clean_all(pTHX)
589 {
590     I32 cleaned;
591     PL_in_clean_all = TRUE;
592     cleaned = visit(do_clean_all, 0,0);
593     return cleaned;
594 }
595
596 /*
597   ARENASETS: a meta-arena implementation which separates arena-info
598   into struct arena_set, which contains an array of struct
599   arena_descs, each holding info for a single arena.  By separating
600   the meta-info from the arena, we recover the 1st slot, formerly
601   borrowed for list management.  The arena_set is about the size of an
602   arena, avoiding the needless malloc overhead of a naive linked-list.
603
604   The cost is 1 arena-set malloc per ~320 arena-mallocs, + the unused
605   memory in the last arena-set (1/2 on average).  In trade, we get
606   back the 1st slot in each arena (ie 1.7% of a CV-arena, less for
607   smaller types).  The recovery of the wasted space allows use of
608   small arenas for large, rare body types, by changing array* fields
609   in body_details_by_type[] below.
610 */
611 struct arena_desc {
612     char       *arena;          /* the raw storage, allocated aligned */
613     size_t      size;           /* its size ~4k typ */
614     svtype      utype;          /* bodytype stored in arena */
615 };
616
617 struct arena_set;
618
619 /* Get the maximum number of elements in set[] such that struct arena_set
620    will fit within PERL_ARENA_SIZE, which is probably just under 4K, and
621    therefore likely to be 1 aligned memory page.  */
622
623 #define ARENAS_PER_SET  ((PERL_ARENA_SIZE - sizeof(struct arena_set*) \
624                           - 2 * sizeof(int)) / sizeof (struct arena_desc))
625
626 struct arena_set {
627     struct arena_set* next;
628     unsigned int   set_size;    /* ie ARENAS_PER_SET */
629     unsigned int   curr;        /* index of next available arena-desc */
630     struct arena_desc set[ARENAS_PER_SET];
631 };
632
633 /*
634 =for apidoc sv_free_arenas
635
636 Deallocate the memory used by all arenas.  Note that all the individual SV
637 heads and bodies within the arenas must already have been freed.
638
639 =cut
640
641 */
642 void
643 Perl_sv_free_arenas(pTHX)
644 {
645     SV* sva;
646     SV* svanext;
647     unsigned int i;
648
649     /* Free arenas here, but be careful about fake ones.  (We assume
650        contiguity of the fake ones with the corresponding real ones.) */
651
652     for (sva = PL_sv_arenaroot; sva; sva = svanext) {
653         svanext = MUTABLE_SV(SvANY(sva));
654         while (svanext && SvFAKE(svanext))
655             svanext = MUTABLE_SV(SvANY(svanext));
656
657         if (!SvFAKE(sva))
658             Safefree(sva);
659     }
660
661     {
662         struct arena_set *aroot = (struct arena_set*) PL_body_arenas;
663
664         while (aroot) {
665             struct arena_set *current = aroot;
666             i = aroot->curr;
667             while (i--) {
668                 assert(aroot->set[i].arena);
669                 Safefree(aroot->set[i].arena);
670             }
671             aroot = aroot->next;
672             Safefree(current);
673         }
674     }
675     PL_body_arenas = 0;
676
677     i = PERL_ARENA_ROOTS_SIZE;
678     while (i--)
679         PL_body_roots[i] = 0;
680
681     PL_sv_arenaroot = 0;
682     PL_sv_root = 0;
683 }
684
685 /*
686   Historically, here were mid-level routines that manage the
687   allocation of bodies out of the various arenas. Some of these
688   routines and related definitions remain here, but otherse were
689   moved into sv_inline.h to facilitate inlining of newSV_type().
690
691   There are 4 kinds of arenas:
692
693   1. SV-head arenas, which are discussed and handled above
694   2. regular body arenas
695   3. arenas for reduced-size bodies
696   4. Hash-Entry arenas
697
698   Arena types 2 & 3 are chained by body-type off an array of
699   arena-root pointers, which is indexed by svtype.  Some of the
700   larger/less used body types are malloced singly, since a large
701   unused block of them is wasteful.  Also, several svtypes dont have
702   bodies; the data fits into the sv-head itself.  The arena-root
703   pointer thus has a few unused root-pointers (which may be hijacked
704   later for arena type 4)
705
706   3 differs from 2 as an optimization; some body types have several
707   unused fields in the front of the structure (which are kept in-place
708   for consistency).  These bodies can be allocated in smaller chunks,
709   because the leading fields arent accessed.  Pointers to such bodies
710   are decremented to point at the unused 'ghost' memory, knowing that
711   the pointers are used with offsets to the real memory.
712
713 Allocation of SV-bodies is similar to SV-heads, differing as follows;
714 the allocation mechanism is used for many body types, so is somewhat
715 more complicated, it uses arena-sets, and has no need for still-live
716 SV detection.
717
718 At the outermost level, (new|del)_X*V macros return bodies of the
719 appropriate type.  These macros call either (new|del)_body_type or
720 (new|del)_body_allocated macro pairs, depending on specifics of the
721 type.  Most body types use the former pair, the latter pair is used to
722 allocate body types with "ghost fields".
723
724 "ghost fields" are fields that are unused in certain types, and
725 consequently don't need to actually exist.  They are declared because
726 they're part of a "base type", which allows use of functions as
727 methods.  The simplest examples are AVs and HVs, 2 aggregate types
728 which don't use the fields which support SCALAR semantics.
729
730 For these types, the arenas are carved up into appropriately sized
731 chunks, we thus avoid wasted memory for those unaccessed members.
732 When bodies are allocated, we adjust the pointer back in memory by the
733 size of the part not allocated, so it's as if we allocated the full
734 structure.  (But things will all go boom if you write to the part that
735 is "not there", because you'll be overwriting the last members of the
736 preceding structure in memory.)
737
738 We calculate the correction using the STRUCT_OFFSET macro on the first
739 member present.  If the allocated structure is smaller (no initial NV
740 actually allocated) then the net effect is to subtract the size of the NV
741 from the pointer, to return a new pointer as if an initial NV were actually
742 allocated.  (We were using structures named *_allocated for this, but
743 this turned out to be a subtle bug, because a structure without an NV
744 could have a lower alignment constraint, but the compiler is allowed to
745 optimised accesses based on the alignment constraint of the actual pointer
746 to the full structure, for example, using a single 64 bit load instruction
747 because it "knows" that two adjacent 32 bit members will be 8-byte aligned.)
748
749 This is the same trick as was used for NV and IV bodies.  Ironically it
750 doesn't need to be used for NV bodies any more, because NV is now at
751 the start of the structure.  IV bodies, and also in some builds NV bodies,
752 don't need it either, because they are no longer allocated.
753
754 In turn, the new_body_* allocators call S_new_body(), which invokes
755 new_body_from_arena macro, which takes a lock, and takes a body off the
756 linked list at PL_body_roots[sv_type], calling Perl_more_bodies() if
757 necessary to refresh an empty list.  Then the lock is released, and
758 the body is returned.
759
760 Perl_more_bodies allocates a new arena, and carves it up into an array of N
761 bodies, which it strings into a linked list.  It looks up arena-size
762 and body-size from the body_details table described below, thus
763 supporting the multiple body-types.
764
765 If PURIFY is defined, or PERL_ARENA_SIZE=0, arenas are not used, and
766 the (new|del)_X*V macros are mapped directly to malloc/free.
767
768 For each sv-type, struct body_details bodies_by_type[] carries
769 parameters which control these aspects of SV handling:
770
771 Arena_size determines whether arenas are used for this body type, and if
772 so, how big they are.  PURIFY or PERL_ARENA_SIZE=0 set this field to
773 zero, forcing individual mallocs and frees.
774
775 Body_size determines how big a body is, and therefore how many fit into
776 each arena.  Offset carries the body-pointer adjustment needed for
777 "ghost fields", and is used in *_allocated macros.
778
779 But its main purpose is to parameterize info needed in
780 Perl_sv_upgrade().  The info here dramatically simplifies the function
781 vs the implementation in 5.8.8, making it table-driven.  All fields
782 are used for this, except for arena_size.
783
784 For the sv-types that have no bodies, arenas are not used, so those
785 PL_body_roots[sv_type] are unused, and can be overloaded.  In
786 something of a special case, SVt_NULL is borrowed for HE arenas;
787 PL_body_roots[HE_ARENA_ROOT_IX=SVt_NULL] is filled by S_more_he, but the
788 bodies_by_type[SVt_NULL] slot is not used, as the table is not
789 available in hv.c. Similarly SVt_IV is re-used for HVAUX_ARENA_ROOT_IX.
790
791 */
792
793 /* return a thing to the free list */
794
795 #define del_body(thing, root)                           \
796     STMT_START {                                        \
797         void ** const thing_copy = (void **)thing;      \
798         *thing_copy = *root;                            \
799         *root = (void*)thing_copy;                      \
800     } STMT_END
801
802
803 void *
804 Perl_more_bodies (pTHX_ const svtype sv_type, const size_t body_size,
805                   const size_t arena_size)
806 {
807     void ** const root = &PL_body_roots[sv_type];
808     struct arena_desc *adesc;
809     struct arena_set *aroot = (struct arena_set *) PL_body_arenas;
810     unsigned int curr;
811     char *start;
812     const char *end;
813     const size_t good_arena_size = Perl_malloc_good_size(arena_size);
814 #if defined(DEBUGGING)
815     static bool done_sanity_check;
816
817     if (!done_sanity_check) {
818         unsigned int i = SVt_LAST;
819
820         done_sanity_check = TRUE;
821
822         while (i--)
823             assert (bodies_by_type[i].type == i);
824     }
825 #endif
826
827     assert(arena_size);
828
829     /* may need new arena-set to hold new arena */
830     if (!aroot || aroot->curr >= aroot->set_size) {
831         struct arena_set *newroot;
832         Newxz(newroot, 1, struct arena_set);
833         newroot->set_size = ARENAS_PER_SET;
834         newroot->next = aroot;
835         aroot = newroot;
836         PL_body_arenas = (void *) newroot;
837         DEBUG_m(PerlIO_printf(Perl_debug_log, "new arenaset %p\n", (void*)aroot));
838     }
839
840     /* ok, now have arena-set with at least 1 empty/available arena-desc */
841     curr = aroot->curr++;
842     adesc = &(aroot->set[curr]);
843     assert(!adesc->arena);
844
845     Newx(adesc->arena, good_arena_size, char);
846     adesc->size = good_arena_size;
847     adesc->utype = sv_type;
848     DEBUG_m(PerlIO_printf(Perl_debug_log, "arena %d added: %p size %" UVuf "\n",
849                           curr, (void*)adesc->arena, (UV)good_arena_size));
850
851     start = (char *) adesc->arena;
852
853     /* Get the address of the byte after the end of the last body we can fit.
854        Remember, this is integer division:  */
855     end = start + good_arena_size / body_size * body_size;
856
857     /* computed count doesn't reflect the 1st slot reservation */
858 #if defined(MYMALLOC) || defined(HAS_MALLOC_GOOD_SIZE)
859     DEBUG_m(PerlIO_printf(Perl_debug_log,
860                           "arena %p end %p arena-size %d (from %d) type %d "
861                           "size %d ct %d\n",
862                           (void*)start, (void*)end, (int)good_arena_size,
863                           (int)arena_size, sv_type, (int)body_size,
864                           (int)good_arena_size / (int)body_size));
865 #else
866     DEBUG_m(PerlIO_printf(Perl_debug_log,
867                           "arena %p end %p arena-size %d type %d size %d ct %d\n",
868                           (void*)start, (void*)end,
869                           (int)arena_size, sv_type, (int)body_size,
870                           (int)good_arena_size / (int)body_size));
871 #endif
872     *root = (void *)start;
873
874     while (1) {
875         /* Where the next body would start:  */
876         char * const next = start + body_size;
877
878         if (next >= end) {
879             /* This is the last body:  */
880             assert(next == end);
881
882             *(void **)start = 0;
883             return *root;
884         }
885
886         *(void**) start = (void *)next;
887         start = next;
888     }
889 }
890
891 /*
892 =for apidoc sv_upgrade
893
894 Upgrade an SV to a more complex form.  Generally adds a new body type to the
895 SV, then copies across as much information as possible from the old body.
896 It croaks if the SV is already in a more complex form than requested.  You
897 generally want to use the C<SvUPGRADE> macro wrapper, which checks the type
898 before calling C<sv_upgrade>, and hence does not croak.  See also
899 C<L</svtype>>.
900
901 =cut
902 */
903
904 void
905 Perl_sv_upgrade(pTHX_ SV *const sv, svtype new_type)
906 {
907     void*       old_body;
908     void*       new_body;
909     const svtype old_type = SvTYPE(sv);
910     const struct body_details *new_type_details;
911     const struct body_details *old_type_details
912         = bodies_by_type + old_type;
913     SV *referent = NULL;
914
915     PERL_ARGS_ASSERT_SV_UPGRADE;
916
917     if (old_type == new_type)
918         return;
919
920     /* This clause was purposefully added ahead of the early return above to
921        the shared string hackery for (sort {$a <=> $b} keys %hash), with the
922        inference by Nick I-S that it would fix other troublesome cases. See
923        changes 7162, 7163 (f130fd4589cf5fbb24149cd4db4137c8326f49c1 and parent)
924
925        Given that shared hash key scalars are no longer PVIV, but PV, there is
926        no longer need to unshare so as to free up the IVX slot for its proper
927        purpose. So it's safe to move the early return earlier.  */
928
929     if (new_type > SVt_PVMG && SvIsCOW(sv)) {
930         sv_force_normal_flags(sv, 0);
931     }
932
933     old_body = SvANY(sv);
934
935     /* Copying structures onto other structures that have been neatly zeroed
936        has a subtle gotcha. Consider XPVMG
937
938        +------+------+------+------+------+-------+-------+
939        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |
940        +------+------+------+------+------+-------+-------+
941        0      4      8     12     16     20      24      28
942
943        where NVs are aligned to 8 bytes, so that sizeof that structure is
944        actually 32 bytes long, with 4 bytes of padding at the end:
945
946        +------+------+------+------+------+-------+-------+------+
947        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH | ???  |
948        +------+------+------+------+------+-------+-------+------+
949        0      4      8     12     16     20      24      28     32
950
951        so what happens if you allocate memory for this structure:
952
953        +------+------+------+------+------+-------+-------+------+------+...
954        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |  GP  | NAME |
955        +------+------+------+------+------+-------+-------+------+------+...
956        0      4      8     12     16     20      24      28     32     36
957
958        zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
959        expect, because you copy the area marked ??? onto GP. Now, ??? may have
960        started out as zero once, but it's quite possible that it isn't. So now,
961        rather than a nicely zeroed GP, you have it pointing somewhere random.
962        Bugs ensue.
963
964        (In fact, GP ends up pointing at a previous GP structure, because the
965        principle cause of the padding in XPVMG getting garbage is a copy of
966        sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob. Right now
967        this happens to be moot because XPVGV has been re-ordered, with GP
968        no longer after STASH)
969
970        So we are careful and work out the size of used parts of all the
971        structures.  */
972
973     switch (old_type) {
974     case SVt_NULL:
975         break;
976     case SVt_IV:
977         if (SvROK(sv)) {
978             referent = SvRV(sv);
979             old_type_details = &fake_rv;
980             if (new_type == SVt_NV)
981                 new_type = SVt_PVNV;
982         } else {
983             if (new_type < SVt_PVIV) {
984                 new_type = (new_type == SVt_NV)
985                     ? SVt_PVNV : SVt_PVIV;
986             }
987         }
988         break;
989     case SVt_NV:
990         if (new_type < SVt_PVNV) {
991             new_type = SVt_PVNV;
992         }
993         break;
994     case SVt_PV:
995         assert(new_type > SVt_PV);
996         STATIC_ASSERT_STMT(SVt_IV < SVt_PV);
997         STATIC_ASSERT_STMT(SVt_NV < SVt_PV);
998         break;
999     case SVt_PVIV:
1000         break;
1001     case SVt_PVNV:
1002         break;
1003     case SVt_PVMG:
1004         /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1005            there's no way that it can be safely upgraded, because perl.c
1006            expects to Safefree(SvANY(PL_mess_sv))  */
1007         assert(sv != PL_mess_sv);
1008         break;
1009     default:
1010         if (UNLIKELY(old_type_details->cant_upgrade))
1011             Perl_croak(aTHX_ "Can't upgrade %s (%" UVuf ") to %" UVuf,
1012                        sv_reftype(sv, 0), (UV) old_type, (UV) new_type);
1013     }
1014
1015     if (UNLIKELY(old_type > new_type))
1016         Perl_croak(aTHX_ "sv_upgrade from type %d down to type %d",
1017                 (int)old_type, (int)new_type);
1018
1019     new_type_details = bodies_by_type + new_type;
1020
1021     SvFLAGS(sv) &= ~SVTYPEMASK;
1022     SvFLAGS(sv) |= new_type;
1023
1024     /* This can't happen, as SVt_NULL is <= all values of new_type, so one of
1025        the return statements above will have triggered.  */
1026     assert (new_type != SVt_NULL);
1027     switch (new_type) {
1028     case SVt_IV:
1029         assert(old_type == SVt_NULL);
1030         SET_SVANY_FOR_BODYLESS_IV(sv);
1031         SvIV_set(sv, 0);
1032         return;
1033     case SVt_NV:
1034         assert(old_type == SVt_NULL);
1035 #if NVSIZE <= IVSIZE
1036         SET_SVANY_FOR_BODYLESS_NV(sv);
1037 #else
1038         SvANY(sv) = new_XNV();
1039 #endif
1040         SvNV_set(sv, 0);
1041         return;
1042     case SVt_PVHV:
1043     case SVt_PVAV:
1044         assert(new_type_details->body_size);
1045
1046 #ifndef PURIFY
1047         assert(new_type_details->arena);
1048         assert(new_type_details->arena_size);
1049         /* This points to the start of the allocated area.  */
1050         new_body = S_new_body(aTHX_ new_type);
1051         /* xpvav and xpvhv have no offset, so no need to adjust new_body */
1052         assert(!(new_type_details->offset));
1053 #else
1054         /* We always allocated the full length item with PURIFY. To do this
1055            we fake things so that arena is false for all 16 types..  */
1056         new_body = new_NOARENAZ(new_type_details);
1057 #endif
1058         SvANY(sv) = new_body;
1059         if (new_type == SVt_PVAV) {
1060             *((XPVAV*) SvANY(sv)) = (XPVAV) {
1061                 .xmg_stash = NULL, .xmg_u = {.xmg_magic = NULL},
1062                 .xav_fill = -1, .xav_max = -1, .xav_alloc = 0
1063                 };
1064
1065             AvREAL_only(sv);
1066         } else {
1067             *((XPVHV*) SvANY(sv)) = (XPVHV) {
1068                 .xmg_stash = NULL, .xmg_u = {.xmg_magic = NULL},
1069                 .xhv_keys = 0,
1070                 /* start with PERL_HASH_DEFAULT_HvMAX+1 buckets: */
1071                 .xhv_max = PERL_HASH_DEFAULT_HvMAX
1072                 };
1073
1074             assert(!SvOK(sv));
1075             SvOK_off(sv);
1076 #ifndef NODEFAULT_SHAREKEYS
1077             HvSHAREKEYS_on(sv);         /* key-sharing on by default */
1078 #endif
1079         }
1080
1081         /* SVt_NULL isn't the only thing upgraded to AV or HV.
1082            The target created by newSVrv also is, and it can have magic.
1083            However, it never has SvPVX set.
1084         */
1085         if (old_type == SVt_IV) {
1086             assert(!SvROK(sv));
1087         } else if (old_type >= SVt_PV) {
1088             assert(SvPVX_const(sv) == 0);
1089         }
1090
1091         if (old_type >= SVt_PVMG) {
1092             SvMAGIC_set(sv, ((XPVMG*)old_body)->xmg_u.xmg_magic);
1093             SvSTASH_set(sv, ((XPVMG*)old_body)->xmg_stash);
1094         } else {
1095             sv->sv_u.svu_array = NULL; /* or svu_hash  */
1096         }
1097         break;
1098
1099     case SVt_PVIV:
1100         /* XXX Is this still needed?  Was it ever needed?   Surely as there is
1101            no route from NV to PVIV, NOK can never be true  */
1102         assert(!SvNOKp(sv));
1103         assert(!SvNOK(sv));
1104         /* FALLTHROUGH */
1105     case SVt_PVIO:
1106     case SVt_PVFM:
1107     case SVt_PVGV:
1108     case SVt_PVCV:
1109     case SVt_PVLV:
1110     case SVt_INVLIST:
1111     case SVt_REGEXP:
1112     case SVt_PVMG:
1113     case SVt_PVNV:
1114     case SVt_PV:
1115
1116         assert(new_type_details->body_size);
1117         /* We always allocated the full length item with PURIFY. To do this
1118            we fake things so that arena is false for all 16 types..  */
1119 #ifndef PURIFY
1120         if(new_type_details->arena) {
1121             /* This points to the start of the allocated area.  */
1122             new_body = S_new_body(aTHX_ new_type);
1123             Zero(new_body, new_type_details->body_size, char);
1124             new_body = ((char *)new_body) - new_type_details->offset;
1125         } else
1126 #endif
1127         {
1128             new_body = new_NOARENAZ(new_type_details);
1129         }
1130         SvANY(sv) = new_body;
1131
1132         if (old_type_details->copy) {
1133             /* There is now the potential for an upgrade from something without
1134                an offset (PVNV or PVMG) to something with one (PVCV, PVFM)  */
1135             int offset = old_type_details->offset;
1136             int length = old_type_details->copy;
1137
1138             if (new_type_details->offset > old_type_details->offset) {
1139                 const int difference
1140                     = new_type_details->offset - old_type_details->offset;
1141                 offset += difference;
1142                 length -= difference;
1143             }
1144             assert (length >= 0);
1145
1146             Copy((char *)old_body + offset, (char *)new_body + offset, length,
1147                  char);
1148         }
1149
1150 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1151         /* If NV 0.0 is stores as all bits 0 then Zero() already creates a
1152          * correct 0.0 for us.  Otherwise, if the old body didn't have an
1153          * NV slot, but the new one does, then we need to initialise the
1154          * freshly created NV slot with whatever the correct bit pattern is
1155          * for 0.0  */
1156         if (old_type_details->zero_nv && !new_type_details->zero_nv
1157             && !isGV_with_GP(sv))
1158             SvNV_set(sv, 0);
1159 #endif
1160
1161         if (UNLIKELY(new_type == SVt_PVIO)) {
1162             IO * const io = MUTABLE_IO(sv);
1163             GV *iogv = gv_fetchpvs("IO::File::", GV_ADD, SVt_PVHV);
1164
1165             SvOBJECT_on(io);
1166             /* Clear the stashcache because a new IO could overrule a package
1167                name */
1168             DEBUG_o(Perl_deb(aTHX_ "sv_upgrade clearing PL_stashcache\n"));
1169             hv_clear(PL_stashcache);
1170
1171             SvSTASH_set(io, MUTABLE_HV(SvREFCNT_inc(GvHV(iogv))));
1172             IoPAGE_LEN(sv) = 60;
1173         }
1174         if (old_type < SVt_PV) {
1175             /* referent will be NULL unless the old type was SVt_IV emulating
1176                SVt_RV */
1177             sv->sv_u.svu_rv = referent;
1178         }
1179         break;
1180     default:
1181         Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu",
1182                    (unsigned long)new_type);
1183     }
1184
1185     /* if this is zero, this is a body-less SVt_NULL, SVt_IV/SVt_RV,
1186        and sometimes SVt_NV */
1187     if (old_type_details->body_size) {
1188 #ifdef PURIFY
1189         safefree(old_body);
1190 #else
1191         /* Note that there is an assumption that all bodies of types that
1192            can be upgraded came from arenas. Only the more complex non-
1193            upgradable types are allowed to be directly malloc()ed.  */
1194         assert(old_type_details->arena);
1195         del_body((void*)((char*)old_body + old_type_details->offset),
1196                  &PL_body_roots[old_type]);
1197 #endif
1198     }
1199 }
1200
1201 struct xpvhv_aux*
1202 Perl_hv_auxalloc(pTHX_ HV *hv) {
1203     const struct body_details *old_type_details = bodies_by_type + SVt_PVHV;
1204     void *old_body;
1205     void *new_body;
1206
1207     PERL_ARGS_ASSERT_HV_AUXALLOC;
1208     assert(SvTYPE(hv) == SVt_PVHV);
1209     assert(!HvHasAUX(hv));
1210
1211 #ifdef PURIFY
1212     new_body = new_NOARENAZ(&fake_hv_with_aux);
1213 #else
1214     new_body_from_arena(new_body, HVAUX_ARENA_ROOT_IX, fake_hv_with_aux);
1215 #endif
1216
1217     old_body = SvANY(hv);
1218
1219     Copy((char *)old_body + old_type_details->offset,
1220          (char *)new_body + fake_hv_with_aux.offset,
1221          old_type_details->copy,
1222          char);
1223
1224 #ifdef PURIFY
1225     safefree(old_body);
1226 #else
1227     assert(old_type_details->arena);
1228     del_body((void*)((char*)old_body + old_type_details->offset),
1229              &PL_body_roots[SVt_PVHV]);
1230 #endif
1231
1232     SvANY(hv) = (XPVHV *) new_body;
1233     SvFLAGS(hv) |= SVphv_HasAUX;
1234     return HvAUX(hv);
1235 }
1236
1237 /*
1238 =for apidoc sv_backoff
1239
1240 Remove any string offset.  You should normally use the C<SvOOK_off> macro
1241 wrapper instead.
1242
1243 =cut
1244 */
1245
1246 /* prior to 5.000 stable, this function returned the new OOK-less SvFLAGS
1247    prior to 5.23.4 this function always returned 0
1248 */
1249
1250 void
1251 Perl_sv_backoff(SV *const sv)
1252 {
1253     STRLEN delta;
1254     const char * const s = SvPVX_const(sv);
1255
1256     PERL_ARGS_ASSERT_SV_BACKOFF;
1257
1258     assert(SvOOK(sv));
1259     assert(SvTYPE(sv) != SVt_PVHV);
1260     assert(SvTYPE(sv) != SVt_PVAV);
1261
1262     SvOOK_offset(sv, delta);
1263
1264     SvLEN_set(sv, SvLEN(sv) + delta);
1265     SvPV_set(sv, SvPVX(sv) - delta);
1266     SvFLAGS(sv) &= ~SVf_OOK;
1267     Move(s, SvPVX(sv), SvCUR(sv)+1, char);
1268     return;
1269 }
1270
1271
1272 /* forward declaration */
1273 static void S_sv_uncow(pTHX_ SV * const sv, const U32 flags);
1274
1275
1276 /*
1277 =for apidoc sv_grow
1278
1279 Expands the character buffer in the SV.  If necessary, uses C<sv_unref> and
1280 upgrades the SV to C<SVt_PV>.  Returns a pointer to the character buffer.
1281 Use the C<SvGROW> wrapper instead.
1282
1283 =cut
1284 */
1285
1286
1287 char *
1288 Perl_sv_grow(pTHX_ SV *const sv, STRLEN newlen)
1289 {
1290     char *s;
1291
1292     PERL_ARGS_ASSERT_SV_GROW;
1293
1294     if (SvROK(sv))
1295         sv_unref(sv);
1296     if (SvTYPE(sv) < SVt_PV) {
1297         sv_upgrade(sv, SVt_PV);
1298         s = SvPVX_mutable(sv);
1299     }
1300     else if (SvOOK(sv)) {       /* pv is offset? */
1301         sv_backoff(sv);
1302         s = SvPVX_mutable(sv);
1303         if (newlen > SvLEN(sv))
1304             newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1305     }
1306     else
1307     {
1308         if (SvIsCOW(sv)) S_sv_uncow(aTHX_ sv, 0);
1309         s = SvPVX_mutable(sv);
1310     }
1311
1312 #ifdef PERL_COPY_ON_WRITE
1313     /* the new COW scheme uses SvPVX(sv)[SvLEN(sv)-1] (if spare)
1314      * to store the COW count. So in general, allocate one more byte than
1315      * asked for, to make it likely this byte is always spare: and thus
1316      * make more strings COW-able.
1317      *
1318      * Only increment if the allocation isn't MEM_SIZE_MAX,
1319      * otherwise it will wrap to 0.
1320      */
1321     if ( newlen != MEM_SIZE_MAX )
1322         newlen++;
1323 #endif
1324
1325 #if defined(PERL_USE_MALLOC_SIZE) && defined(Perl_safesysmalloc_size)
1326 #define PERL_UNWARANTED_CHUMMINESS_WITH_MALLOC
1327 #endif
1328
1329     if (newlen > SvLEN(sv)) {           /* need more room? */
1330         STRLEN minlen = SvCUR(sv);
1331         minlen += (minlen >> PERL_STRLEN_EXPAND_SHIFT) + 10;
1332         if (newlen < minlen)
1333             newlen = minlen;
1334 #ifndef PERL_UNWARANTED_CHUMMINESS_WITH_MALLOC
1335
1336         /* Don't round up on the first allocation, as odds are pretty good that
1337          * the initial request is accurate as to what is really needed */
1338         if (SvLEN(sv)) {
1339             STRLEN rounded = PERL_STRLEN_ROUNDUP(newlen);
1340             if (rounded > newlen)
1341                 newlen = rounded;
1342         }
1343 #endif
1344         if (SvLEN(sv) && s) {
1345             s = (char*)saferealloc(s, newlen);
1346         }
1347         else {
1348             s = (char*)safemalloc(newlen);
1349             if (SvPVX_const(sv) && SvCUR(sv)) {
1350                 Move(SvPVX_const(sv), s, SvCUR(sv), char);
1351             }
1352         }
1353         SvPV_set(sv, s);
1354 #ifdef PERL_UNWARANTED_CHUMMINESS_WITH_MALLOC
1355         /* Do this here, do it once, do it right, and then we will never get
1356            called back into sv_grow() unless there really is some growing
1357            needed.  */
1358         SvLEN_set(sv, Perl_safesysmalloc_size(s));
1359 #else
1360         SvLEN_set(sv, newlen);
1361 #endif
1362     }
1363     return s;
1364 }
1365
1366 /*
1367 =for apidoc sv_grow_fresh
1368
1369 A cut-down version of sv_grow intended only for when sv is a freshly-minted
1370 SVt_PV, SVt_PVIV, SVt_PVNV, or SVt_PVMG. i.e. sv has the default flags, has
1371 never been any other type, and does not have an existing string. Basically,
1372 just assigns a char buffer and returns a pointer to it.
1373
1374 =cut
1375 */
1376
1377
1378 char *
1379 Perl_sv_grow_fresh(pTHX_ SV *const sv, STRLEN newlen)
1380 {
1381     char *s;
1382
1383     PERL_ARGS_ASSERT_SV_GROW_FRESH;
1384
1385     assert(SvTYPE(sv) >= SVt_PV && SvTYPE(sv) <= SVt_PVMG);
1386     assert(!SvROK(sv));
1387     assert(!SvOOK(sv));
1388     assert(!SvIsCOW(sv));
1389     assert(!SvLEN(sv));
1390     assert(!SvCUR(sv));
1391
1392 #ifdef PERL_COPY_ON_WRITE
1393     /* the new COW scheme uses SvPVX(sv)[SvLEN(sv)-1] (if spare)
1394      * to store the COW count. So in general, allocate one more byte than
1395      * asked for, to make it likely this byte is always spare: and thus
1396      * make more strings COW-able.
1397      *
1398      * Only increment if the allocation isn't MEM_SIZE_MAX,
1399      * otherwise it will wrap to 0.
1400      */
1401     if ( newlen != MEM_SIZE_MAX )
1402         newlen++;
1403 #endif
1404
1405     /* 10 is a longstanding, hardcoded minimum length in sv_grow. */
1406     /* Just doing the same here for consistency. */
1407     if (newlen < 10)
1408         newlen = 10;
1409
1410     s = (char*)safemalloc(newlen);
1411     SvPV_set(sv, s);
1412
1413     /* No PERL_UNWARANTED_CHUMMINESS_WITH_MALLOC here, since many strings */
1414     /* will never be grown once set. Let the real sv_grow worry about that. */
1415     SvLEN_set(sv, newlen);
1416     return s;
1417 }
1418
1419 /*
1420 =for apidoc sv_setiv
1421 =for apidoc_item sv_setiv_mg
1422
1423 These copy an integer into the given SV, upgrading first if necessary.
1424
1425 They differ only in that C<sv_setiv_mg> handles 'set' magic; C<sv_setiv> does
1426 not.
1427
1428 =cut
1429 */
1430
1431 void
1432 Perl_sv_setiv(pTHX_ SV *const sv, const IV i)
1433 {
1434     PERL_ARGS_ASSERT_SV_SETIV;
1435
1436     SV_CHECK_THINKFIRST_COW_DROP(sv);
1437     switch (SvTYPE(sv)) {
1438     case SVt_NULL:
1439     case SVt_NV:
1440         sv_upgrade(sv, SVt_IV);
1441         break;
1442     case SVt_PV:
1443         sv_upgrade(sv, SVt_PVIV);
1444         break;
1445
1446     case SVt_PVGV:
1447         if (!isGV_with_GP(sv))
1448             break;
1449         /* FALLTHROUGH */
1450     case SVt_PVAV:
1451     case SVt_PVHV:
1452     case SVt_PVCV:
1453     case SVt_PVFM:
1454     case SVt_PVIO:
1455         /* diag_listed_as: Can't coerce %s to %s in %s */
1456         Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1457                    OP_DESC(PL_op));
1458         NOT_REACHED; /* NOTREACHED */
1459         break;
1460     default: NOOP;
1461     }
1462     (void)SvIOK_only(sv);                       /* validate number */
1463     SvIV_set(sv, i);
1464     SvTAINT(sv);
1465 }
1466
1467 void
1468 Perl_sv_setiv_mg(pTHX_ SV *const sv, const IV i)
1469 {
1470     PERL_ARGS_ASSERT_SV_SETIV_MG;
1471
1472     sv_setiv(sv,i);
1473     SvSETMAGIC(sv);
1474 }
1475
1476 /*
1477 =for apidoc sv_setuv
1478 =for apidoc_item sv_setuv_mg
1479
1480 These copy an unsigned integer into the given SV, upgrading first if necessary.
1481
1482
1483 They differ only in that C<sv_setuv_mg> handles 'set' magic; C<sv_setuv> does
1484 not.
1485
1486 =cut
1487 */
1488
1489 void
1490 Perl_sv_setuv(pTHX_ SV *const sv, const UV u)
1491 {
1492     PERL_ARGS_ASSERT_SV_SETUV;
1493
1494     /* With the if statement to ensure that integers are stored as IVs whenever
1495        possible:
1496        u=1.49  s=0.52  cu=72.49  cs=10.64  scripts=270  tests=20865
1497
1498        without
1499        u=1.35  s=0.47  cu=73.45  cs=11.43  scripts=270  tests=20865
1500
1501        If you wish to remove the following if statement, so that this routine
1502        (and its callers) always return UVs, please benchmark to see what the
1503        effect is. Modern CPUs may be different. Or may not :-)
1504     */
1505     if (u <= (UV)IV_MAX) {
1506        sv_setiv(sv, (IV)u);
1507        return;
1508     }
1509     sv_setiv(sv, 0);
1510     SvIsUV_on(sv);
1511     SvUV_set(sv, u);
1512 }
1513
1514 void
1515 Perl_sv_setuv_mg(pTHX_ SV *const sv, const UV u)
1516 {
1517     PERL_ARGS_ASSERT_SV_SETUV_MG;
1518
1519     sv_setuv(sv,u);
1520     SvSETMAGIC(sv);
1521 }
1522
1523 /*
1524 =for apidoc sv_setnv
1525 =for apidoc_item sv_setnv_mg
1526
1527 These copy a double into the given SV, upgrading first if necessary.
1528
1529 They differ only in that C<sv_setnv_mg> handles 'set' magic; C<sv_setnv> does
1530 not.
1531
1532 =cut
1533 */
1534
1535 void
1536 Perl_sv_setnv(pTHX_ SV *const sv, const NV num)
1537 {
1538     PERL_ARGS_ASSERT_SV_SETNV;
1539
1540     SV_CHECK_THINKFIRST_COW_DROP(sv);
1541     switch (SvTYPE(sv)) {
1542     case SVt_NULL:
1543     case SVt_IV:
1544         sv_upgrade(sv, SVt_NV);
1545         break;
1546     case SVt_PV:
1547     case SVt_PVIV:
1548         sv_upgrade(sv, SVt_PVNV);
1549         break;
1550
1551     case SVt_PVGV:
1552         if (!isGV_with_GP(sv))
1553             break;
1554         /* FALLTHROUGH */
1555     case SVt_PVAV:
1556     case SVt_PVHV:
1557     case SVt_PVCV:
1558     case SVt_PVFM:
1559     case SVt_PVIO:
1560         /* diag_listed_as: Can't coerce %s to %s in %s */
1561         Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
1562                    OP_DESC(PL_op));
1563         NOT_REACHED; /* NOTREACHED */
1564         break;
1565     default: NOOP;
1566     }
1567     SvNV_set(sv, num);
1568     (void)SvNOK_only(sv);                       /* validate number */
1569     SvTAINT(sv);
1570 }
1571
1572 void
1573 Perl_sv_setnv_mg(pTHX_ SV *const sv, const NV num)
1574 {
1575     PERL_ARGS_ASSERT_SV_SETNV_MG;
1576
1577     sv_setnv(sv,num);
1578     SvSETMAGIC(sv);
1579 }
1580
1581 /*
1582 =for apidoc sv_setrv_noinc
1583 =for apidoc_item sv_setrv_noinc_mg
1584
1585 Copies an SV pointer into the given SV as an SV reference, upgrading it if
1586 necessary. After this, C<SvRV(sv)> is equal to I<ref>. This does not adjust
1587 the reference count of I<ref>. The reference I<ref> must not be NULL.
1588
1589 C<sv_setrv_noinc_mg> will invoke 'set' magic on the SV; C<sv_setrv_noinc> will
1590 not.
1591
1592 =cut
1593 */
1594
1595 void
1596 Perl_sv_setrv_noinc(pTHX_ SV *const sv, SV *const ref)
1597 {
1598     PERL_ARGS_ASSERT_SV_SETRV_NOINC;
1599
1600     SV_CHECK_THINKFIRST_COW_DROP(sv);
1601     prepare_SV_for_RV(sv);
1602
1603     SvOK_off(sv);
1604     SvRV_set(sv, ref);
1605     SvROK_on(sv);
1606 }
1607
1608 void
1609 Perl_sv_setrv_noinc_mg(pTHX_ SV *const sv, SV *const ref)
1610 {
1611     PERL_ARGS_ASSERT_SV_SETRV_NOINC_MG;
1612
1613     sv_setrv_noinc(sv, ref);
1614     SvSETMAGIC(sv);
1615 }
1616
1617 /*
1618 =for apidoc sv_setrv_inc
1619 =for apidoc_item sv_setrv_inc_mg
1620
1621 As C<sv_setrv_noinc> but increments the reference count of I<ref>.
1622
1623 C<sv_setrv_inc_mg> will invoke 'set' magic on the SV; C<sv_setrv_inc> will
1624 not.
1625
1626 =cut
1627 */
1628
1629 void
1630 Perl_sv_setrv_inc(pTHX_ SV *const sv, SV *const ref)
1631 {
1632     PERL_ARGS_ASSERT_SV_SETRV_INC;
1633
1634     sv_setrv_noinc(sv, SvREFCNT_inc_simple_NN(ref));
1635 }
1636
1637 void
1638 Perl_sv_setrv_inc_mg(pTHX_ SV *const sv, SV *const ref)
1639 {
1640     PERL_ARGS_ASSERT_SV_SETRV_INC_MG;
1641
1642     sv_setrv_noinc(sv, SvREFCNT_inc_simple_NN(ref));
1643     SvSETMAGIC(sv);
1644 }
1645
1646 /* Return a cleaned-up, printable version of sv, for non-numeric, or
1647  * not incrementable warning display.
1648  * Originally part of S_not_a_number().
1649  * The return value may be != tmpbuf.
1650  */
1651
1652 STATIC const char *
1653 S_sv_display(pTHX_ SV *const sv, char *tmpbuf, STRLEN tmpbuf_size) {
1654     const char *pv;
1655
1656      PERL_ARGS_ASSERT_SV_DISPLAY;
1657
1658      if (DO_UTF8(sv)) {
1659           SV *dsv = newSVpvs_flags("", SVs_TEMP);
1660           pv = sv_uni_display(dsv, sv, 32, UNI_DISPLAY_ISPRINT);
1661      } else {
1662           char *d = tmpbuf;
1663           const char * const limit = tmpbuf + tmpbuf_size - 8;
1664           /* each *s can expand to 4 chars + "...\0",
1665              i.e. need room for 8 chars */
1666
1667           const char *s = SvPVX_const(sv);
1668           const char * const end = s + SvCUR(sv);
1669           for ( ; s < end && d < limit; s++ ) {
1670                int ch = (U8) *s;
1671                if (! isASCII(ch) && !isPRINT_LC(ch)) {
1672                     *d++ = 'M';
1673                     *d++ = '-';
1674
1675                     /* Map to ASCII "equivalent" of Latin1 */
1676                     ch = LATIN1_TO_NATIVE(NATIVE_TO_LATIN1(ch) & 127);
1677                }
1678                if (ch == '\n') {
1679                     *d++ = '\\';
1680                     *d++ = 'n';
1681                }
1682                else if (ch == '\r') {
1683                     *d++ = '\\';
1684                     *d++ = 'r';
1685                }
1686                else if (ch == '\f') {
1687                     *d++ = '\\';
1688                     *d++ = 'f';
1689                }
1690                else if (ch == '\\') {
1691                     *d++ = '\\';
1692                     *d++ = '\\';
1693                }
1694                else if (ch == '\0') {
1695                     *d++ = '\\';
1696                     *d++ = '0';
1697                }
1698                else if (isPRINT_LC(ch))
1699                     *d++ = ch;
1700                else {
1701                     *d++ = '^';
1702                     *d++ = toCTRL(ch);
1703                }
1704           }
1705           if (s < end) {
1706                *d++ = '.';
1707                *d++ = '.';
1708                *d++ = '.';
1709           }
1710           *d = '\0';
1711           pv = tmpbuf;
1712     }
1713
1714     return pv;
1715 }
1716
1717 /* Print an "isn't numeric" warning, using a cleaned-up,
1718  * printable version of the offending string
1719  */
1720
1721 STATIC void
1722 S_not_a_number(pTHX_ SV *const sv)
1723 {
1724      char tmpbuf[64];
1725      const char *pv;
1726
1727      PERL_ARGS_ASSERT_NOT_A_NUMBER;
1728
1729      pv = sv_display(sv, tmpbuf, sizeof(tmpbuf));
1730
1731     if (PL_op)
1732         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1733                     /* diag_listed_as: Argument "%s" isn't numeric%s */
1734                     "Argument \"%s\" isn't numeric in %s", pv,
1735                     OP_DESC(PL_op));
1736     else
1737         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1738                     /* diag_listed_as: Argument "%s" isn't numeric%s */
1739                     "Argument \"%s\" isn't numeric", pv);
1740 }
1741
1742 STATIC void
1743 S_not_incrementable(pTHX_ SV *const sv) {
1744      char tmpbuf[64];
1745      const char *pv;
1746
1747      PERL_ARGS_ASSERT_NOT_INCREMENTABLE;
1748
1749      pv = sv_display(sv, tmpbuf, sizeof(tmpbuf));
1750
1751      Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1752                  "Argument \"%s\" treated as 0 in increment (++)", pv);
1753 }
1754
1755 /*
1756 =for apidoc looks_like_number
1757
1758 Test if the content of an SV looks like a number (or is a number).
1759 C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1760 non-numeric warning), even if your C<atof()> doesn't grok them.  Get-magic is
1761 ignored.
1762
1763 =cut
1764 */
1765
1766 I32
1767 Perl_looks_like_number(pTHX_ SV *const sv)
1768 {
1769     const char *sbegin;
1770     STRLEN len;
1771     int numtype;
1772
1773     PERL_ARGS_ASSERT_LOOKS_LIKE_NUMBER;
1774
1775     if (SvPOK(sv) || SvPOKp(sv)) {
1776         sbegin = SvPV_nomg_const(sv, len);
1777     }
1778     else
1779         return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
1780     numtype = grok_number(sbegin, len, NULL);
1781     return ((numtype & IS_NUMBER_TRAILING)) ? 0 : numtype;
1782 }
1783
1784 STATIC bool
1785 S_glob_2number(pTHX_ GV * const gv)
1786 {
1787     PERL_ARGS_ASSERT_GLOB_2NUMBER;
1788
1789     /* We know that all GVs stringify to something that is not-a-number,
1790         so no need to test that.  */
1791     if (ckWARN(WARN_NUMERIC))
1792     {
1793         SV *const buffer = sv_newmortal();
1794         gv_efullname3(buffer, gv, "*");
1795         not_a_number(buffer);
1796     }
1797     /* We just want something true to return, so that S_sv_2iuv_common
1798         can tail call us and return true.  */
1799     return TRUE;
1800 }
1801
1802 /* Actually, ISO C leaves conversion of UV to IV undefined, but
1803    until proven guilty, assume that things are not that bad... */
1804
1805 /*
1806    NV_PRESERVES_UV:
1807
1808    As 64 bit platforms often have an NV that doesn't preserve all bits of
1809    an IV (an assumption perl has been based on to date) it becomes necessary
1810    to remove the assumption that the NV always carries enough precision to
1811    recreate the IV whenever needed, and that the NV is the canonical form.
1812    Instead, IV/UV and NV need to be given equal rights. So as to not lose
1813    precision as a side effect of conversion (which would lead to insanity
1814    and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1815    1) to distinguish between IV/UV/NV slots that have a valid conversion cached
1816       where precision was lost, and IV/UV/NV slots that have a valid conversion
1817       which has lost no precision
1818    2) to ensure that if a numeric conversion to one form is requested that
1819       would lose precision, the precise conversion (or differently
1820       imprecise conversion) is also performed and cached, to prevent
1821       requests for different numeric formats on the same SV causing
1822       lossy conversion chains. (lossless conversion chains are perfectly
1823       acceptable (still))
1824
1825
1826    flags are used:
1827    SvIOKp is true if the IV slot contains a valid value
1828    SvIOK  is true only if the IV value is accurate (UV if SvIOK_UV true)
1829    SvNOKp is true if the NV slot contains a valid value
1830    SvNOK  is true only if the NV value is accurate
1831
1832    so
1833    while converting from PV to NV, check to see if converting that NV to an
1834    IV(or UV) would lose accuracy over a direct conversion from PV to
1835    IV(or UV). If it would, cache both conversions, return NV, but mark
1836    SV as IOK NOKp (ie not NOK).
1837
1838    While converting from PV to IV, check to see if converting that IV to an
1839    NV would lose accuracy over a direct conversion from PV to NV. If it
1840    would, cache both conversions, flag similarly.
1841
1842    Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1843    correctly because if IV & NV were set NV *always* overruled.
1844    Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1845    changes - now IV and NV together means that the two are interchangeable:
1846    SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
1847
1848    The benefit of this is that operations such as pp_add know that if
1849    SvIOK is true for both left and right operands, then integer addition
1850    can be used instead of floating point (for cases where the result won't
1851    overflow). Before, floating point was always used, which could lead to
1852    loss of precision compared with integer addition.
1853
1854    * making IV and NV equal status should make maths accurate on 64 bit
1855      platforms
1856    * may speed up maths somewhat if pp_add and friends start to use
1857      integers when possible instead of fp. (Hopefully the overhead in
1858      looking for SvIOK and checking for overflow will not outweigh the
1859      fp to integer speedup)
1860    * will slow down integer operations (callers of SvIV) on "inaccurate"
1861      values, as the change from SvIOK to SvIOKp will cause a call into
1862      sv_2iv each time rather than a macro access direct to the IV slot
1863    * should speed up number->string conversion on integers as IV is
1864      favoured when IV and NV are equally accurate
1865
1866    ####################################################################
1867    You had better be using SvIOK_notUV if you want an IV for arithmetic:
1868    SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
1869    On the other hand, SvUOK is true iff UV.
1870    ####################################################################
1871
1872    Your mileage will vary depending your CPU's relative fp to integer
1873    performance ratio.
1874 */
1875
1876 #ifndef NV_PRESERVES_UV
1877 #  define IS_NUMBER_UNDERFLOW_IV 1
1878 #  define IS_NUMBER_UNDERFLOW_UV 2
1879 #  define IS_NUMBER_IV_AND_UV    2
1880 #  define IS_NUMBER_OVERFLOW_IV  4
1881 #  define IS_NUMBER_OVERFLOW_UV  5
1882
1883 /* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
1884
1885 /* For sv_2nv these three cases are "SvNOK and don't bother casting"  */
1886 STATIC int
1887 S_sv_2iuv_non_preserve(pTHX_ SV *const sv
1888 #  ifdef DEBUGGING
1889                        , I32 numtype
1890 #  endif
1891                        )
1892 {
1893     PERL_ARGS_ASSERT_SV_2IUV_NON_PRESERVE;
1894     PERL_UNUSED_CONTEXT;
1895
1896     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));
1897     if (SvNVX(sv) < (NV)IV_MIN) {
1898         (void)SvIOKp_on(sv);
1899         (void)SvNOK_on(sv);
1900         SvIV_set(sv, IV_MIN);
1901         return IS_NUMBER_UNDERFLOW_IV;
1902     }
1903     if (SvNVX(sv) > (NV)UV_MAX) {
1904         (void)SvIOKp_on(sv);
1905         (void)SvNOK_on(sv);
1906         SvIsUV_on(sv);
1907         SvUV_set(sv, UV_MAX);
1908         return IS_NUMBER_OVERFLOW_UV;
1909     }
1910     (void)SvIOKp_on(sv);
1911     (void)SvNOK_on(sv);
1912     /* Can't use strtol etc to convert this string.  (See truth table in
1913        sv_2iv  */
1914     if (SvNVX(sv) < IV_MAX_P1) {
1915         SvIV_set(sv, I_V(SvNVX(sv)));
1916         if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
1917             SvIOK_on(sv); /* Integer is precise. NOK, IOK */
1918         } else {
1919             /* Integer is imprecise. NOK, IOKp */
1920         }
1921         return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
1922     }
1923     SvIsUV_on(sv);
1924     SvUV_set(sv, U_V(SvNVX(sv)));
1925     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
1926         if (SvUVX(sv) == UV_MAX) {
1927             /* As we know that NVs don't preserve UVs, UV_MAX cannot
1928                possibly be preserved by NV. Hence, it must be overflow.
1929                NOK, IOKp */
1930             return IS_NUMBER_OVERFLOW_UV;
1931         }
1932         SvIOK_on(sv); /* Integer is precise. NOK, UOK */
1933     } else {
1934         /* Integer is imprecise. NOK, IOKp */
1935     }
1936     return IS_NUMBER_OVERFLOW_IV;
1937 }
1938 #endif /* !NV_PRESERVES_UV*/
1939
1940 /* If numtype is infnan, set the NV of the sv accordingly.
1941  * If numtype is anything else, try setting the NV using Atof(PV). */
1942 static void
1943 S_sv_setnv(pTHX_ SV* sv, int numtype)
1944 {
1945     bool pok = cBOOL(SvPOK(sv));
1946     bool nok = FALSE;
1947 #ifdef NV_INF
1948     if ((numtype & IS_NUMBER_INFINITY)) {
1949         SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -NV_INF : NV_INF);
1950         nok = TRUE;
1951     } else
1952 #endif
1953 #ifdef NV_NAN
1954     if ((numtype & IS_NUMBER_NAN)) {
1955         SvNV_set(sv, NV_NAN);
1956         nok = TRUE;
1957     } else
1958 #endif
1959     if (pok) {
1960         SvNV_set(sv, Atof(SvPVX_const(sv)));
1961         /* Purposefully no true nok here, since we don't want to blow
1962          * away the possible IOK/UV of an existing sv. */
1963     }
1964     if (nok) {
1965         SvNOK_only(sv); /* No IV or UV please, this is pure infnan. */
1966         if (pok)
1967             SvPOK_on(sv); /* PV is okay, though. */
1968     }
1969 }
1970
1971 STATIC bool
1972 S_sv_2iuv_common(pTHX_ SV *const sv)
1973 {
1974     PERL_ARGS_ASSERT_SV_2IUV_COMMON;
1975
1976     if (SvNOKp(sv)) {
1977         /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
1978          * without also getting a cached IV/UV from it at the same time
1979          * (ie PV->NV conversion should detect loss of accuracy and cache
1980          * IV or UV at same time to avoid this. */
1981         /* IV-over-UV optimisation - choose to cache IV if possible */
1982
1983         if (SvTYPE(sv) == SVt_NV)
1984             sv_upgrade(sv, SVt_PVNV);
1985
1986     got_nv:
1987         (void)SvIOKp_on(sv);    /* Must do this first, to clear any SvOOK */
1988         /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
1989            certainly cast into the IV range at IV_MAX, whereas the correct
1990            answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
1991            cases go to UV */
1992 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
1993         if (Perl_isnan(SvNVX(sv))) {
1994             SvUV_set(sv, 0);
1995             SvIsUV_on(sv);
1996             return FALSE;
1997         }
1998 #endif
1999         if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2000             SvIV_set(sv, I_V(SvNVX(sv)));
2001             if (SvNVX(sv) == (NV) SvIVX(sv)
2002 #ifndef NV_PRESERVES_UV
2003                 && SvIVX(sv) != IV_MIN /* avoid negating IV_MIN below */
2004                 && (((UV)1 << NV_PRESERVES_UV_BITS) >
2005                     (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2006                 /* Don't flag it as "accurately an integer" if the number
2007                    came from a (by definition imprecise) NV operation, and
2008                    we're outside the range of NV integer precision */
2009 #endif
2010                 ) {
2011                 if (SvNOK(sv))
2012                     SvIOK_on(sv);  /* Can this go wrong with rounding? NWC */
2013                 else {
2014                     /* scalar has trailing garbage, eg "42a" */
2015                 }
2016                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2017                                       "0x%" UVxf " iv(%" NVgf " => %" IVdf ") (precise)\n",
2018                                       PTR2UV(sv),
2019                                       SvNVX(sv),
2020                                       SvIVX(sv)));
2021
2022             } else {
2023                 /* IV not precise.  No need to convert from PV, as NV
2024                    conversion would already have cached IV if it detected
2025                    that PV->IV would be better than PV->NV->IV
2026                    flags already correct - don't set public IOK.  */
2027                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2028                                       "0x%" UVxf " iv(%" NVgf " => %" IVdf ") (imprecise)\n",
2029                                       PTR2UV(sv),
2030                                       SvNVX(sv),
2031                                       SvIVX(sv)));
2032             }
2033             /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2034                but the cast (NV)IV_MIN rounds to a the value less (more
2035                negative) than IV_MIN which happens to be equal to SvNVX ??
2036                Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2037                NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2038                (NV)UVX == NVX are both true, but the values differ. :-(
2039                Hopefully for 2s complement IV_MIN is something like
2040                0x8000000000000000 which will be exact. NWC */
2041         }
2042         else {
2043             SvUV_set(sv, U_V(SvNVX(sv)));
2044             if (
2045                 (SvNVX(sv) == (NV) SvUVX(sv))
2046 #ifndef  NV_PRESERVES_UV
2047                 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2048                 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2049                 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2050                 /* Don't flag it as "accurately an integer" if the number
2051                    came from a (by definition imprecise) NV operation, and
2052                    we're outside the range of NV integer precision */
2053 #endif
2054                 && SvNOK(sv)
2055                 )
2056                 SvIOK_on(sv);
2057             SvIsUV_on(sv);
2058             DEBUG_c(PerlIO_printf(Perl_debug_log,
2059                                   "0x%" UVxf " 2iv(%" UVuf " => %" IVdf ") (as unsigned)\n",
2060                                   PTR2UV(sv),
2061                                   SvUVX(sv),
2062                                   SvUVX(sv)));
2063         }
2064     }
2065     else if (SvPOKp(sv)) {
2066         UV value;
2067         int numtype;
2068         const char *s = SvPVX_const(sv);
2069         const STRLEN cur = SvCUR(sv);
2070
2071         /* short-cut for a single digit string like "1" */
2072
2073         if (cur == 1) {
2074             char c = *s;
2075             if (isDIGIT(c)) {
2076                 if (SvTYPE(sv) < SVt_PVIV)
2077                     sv_upgrade(sv, SVt_PVIV);
2078                 (void)SvIOK_on(sv);
2079                 SvIV_set(sv, (IV)(c - '0'));
2080                 return FALSE;
2081             }
2082         }
2083
2084         numtype = grok_number(s, cur, &value);
2085         /* We want to avoid a possible problem when we cache an IV/ a UV which
2086            may be later translated to an NV, and the resulting NV is not
2087            the same as the direct translation of the initial string
2088            (eg 123.456 can shortcut to the IV 123 with atol(), but we must
2089            be careful to ensure that the value with the .456 is around if the
2090            NV value is requested in the future).
2091
2092            This means that if we cache such an IV/a UV, we need to cache the
2093            NV as well.  Moreover, we trade speed for space, and do not
2094            cache the NV if we are sure it's not needed.
2095          */
2096
2097         /* SVt_PVNV is one higher than SVt_PVIV, hence this order  */
2098         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2099              == IS_NUMBER_IN_UV) {
2100             /* It's definitely an integer, only upgrade to PVIV */
2101             if (SvTYPE(sv) < SVt_PVIV)
2102                 sv_upgrade(sv, SVt_PVIV);
2103             (void)SvIOK_on(sv);
2104         } else if (SvTYPE(sv) < SVt_PVNV)
2105             sv_upgrade(sv, SVt_PVNV);
2106
2107         if ((numtype & (IS_NUMBER_INFINITY | IS_NUMBER_NAN))) {
2108             if (ckWARN(WARN_NUMERIC) && ((numtype & IS_NUMBER_TRAILING)))
2109                 not_a_number(sv);
2110             S_sv_setnv(aTHX_ sv, numtype);
2111             goto got_nv;        /* Fill IV/UV slot and set IOKp */
2112         }
2113
2114         /* If NVs preserve UVs then we only use the UV value if we know that
2115            we aren't going to call atof() below. If NVs don't preserve UVs
2116            then the value returned may have more precision than atof() will
2117            return, even though value isn't perfectly accurate.  */
2118         if ((numtype & (IS_NUMBER_IN_UV
2119 #ifdef NV_PRESERVES_UV
2120                         | IS_NUMBER_NOT_INT
2121 #endif
2122             )) == IS_NUMBER_IN_UV) {
2123             /* This won't turn off the public IOK flag if it was set above  */
2124             (void)SvIOKp_on(sv);
2125
2126             if (!(numtype & IS_NUMBER_NEG)) {
2127                 /* positive */;
2128                 if (value <= (UV)IV_MAX) {
2129                     SvIV_set(sv, (IV)value);
2130                 } else {
2131                     /* it didn't overflow, and it was positive. */
2132                     SvUV_set(sv, value);
2133                     SvIsUV_on(sv);
2134                 }
2135             } else {
2136                 /* 2s complement assumption  */
2137                 if (value <= (UV)IV_MIN) {
2138                     SvIV_set(sv, value == (UV)IV_MIN
2139                                     ? IV_MIN : -(IV)value);
2140                 } else {
2141                     /* Too negative for an IV.  This is a double upgrade, but
2142                        I'm assuming it will be rare.  */
2143                     if (SvTYPE(sv) < SVt_PVNV)
2144                         sv_upgrade(sv, SVt_PVNV);
2145                     SvNOK_on(sv);
2146                     SvIOK_off(sv);
2147                     SvIOKp_on(sv);
2148                     SvNV_set(sv, -(NV)value);
2149                     SvIV_set(sv, IV_MIN);
2150                 }
2151             }
2152         }
2153         /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2154            will be in the previous block to set the IV slot, and the next
2155            block to set the NV slot.  So no else here.  */
2156
2157         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2158             != IS_NUMBER_IN_UV) {
2159             /* It wasn't an (integer that doesn't overflow the UV). */
2160             S_sv_setnv(aTHX_ sv, numtype);
2161
2162             if (! numtype && ckWARN(WARN_NUMERIC))
2163                 not_a_number(sv);
2164
2165             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%" UVxf " 2iv(%" NVgf ")\n",
2166                                   PTR2UV(sv), SvNVX(sv)));
2167
2168 #ifdef NV_PRESERVES_UV
2169             SvNOKp_on(sv);
2170             if (numtype)
2171                 SvNOK_on(sv);
2172             goto got_nv;        /* Fill IV/UV slot and set IOKp, maybe IOK */
2173 #else /* NV_PRESERVES_UV */
2174             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2175                 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2176                 /* The IV/UV slot will have been set from value returned by
2177                    grok_number above.  The NV slot has just been set using
2178                    Atof.  */
2179                 SvNOK_on(sv);
2180                 assert (SvIOKp(sv));
2181             } else {
2182                 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2183                     U_V(Perl_fabs(SvNVX(sv)))) {
2184                     /* Small enough to preserve all bits. */
2185                     (void)SvIOKp_on(sv);
2186                     SvNOK_on(sv);
2187                     SvIV_set(sv, I_V(SvNVX(sv)));
2188                     if ((NV)(SvIVX(sv)) == SvNVX(sv))
2189                         SvIOK_on(sv);
2190                     /* There had been runtime checking for
2191                        "U_V(Perl_fabs(SvNVX(sv))) < (UV)IV_MAX" here to ensure
2192                        that this NV is in the preserved range, but this should
2193                        be always true if the following assertion is true: */
2194                     STATIC_ASSERT_STMT(((UV)1 << NV_PRESERVES_UV_BITS) <=
2195                                        (UV)IV_MAX);
2196                 } else {
2197                     /* IN_UV NOT_INT
2198                          0      0       already failed to read UV.
2199                          0      1       already failed to read UV.
2200                          1      0       you won't get here in this case. IV/UV
2201                                         slot set, public IOK, Atof() unneeded.
2202                          1      1       already read UV.
2203                        so there's no point in sv_2iuv_non_preserve() attempting
2204                        to use atol, strtol, strtoul etc.  */
2205 #  ifdef DEBUGGING
2206                     sv_2iuv_non_preserve (sv, numtype);
2207 #  else
2208                     sv_2iuv_non_preserve (sv);
2209 #  endif
2210                 }
2211             }
2212         /* It might be more code efficient to go through the entire logic above
2213            and conditionally set with SvIOKp_on() rather than SvIOK(), but it
2214            gets complex and potentially buggy, so more programmer efficient
2215            to do it this way, by turning off the public flags:  */
2216         if (!numtype)
2217             SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2218 #endif /* NV_PRESERVES_UV */
2219         }
2220     }
2221     else {
2222         if (isGV_with_GP(sv))
2223             return glob_2number(MUTABLE_GV(sv));
2224
2225         if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2226                 report_uninit(sv);
2227         if (SvTYPE(sv) < SVt_IV)
2228             /* Typically the caller expects that sv_any is not NULL now.  */
2229             sv_upgrade(sv, SVt_IV);
2230         /* Return 0 from the caller.  */
2231         return TRUE;
2232     }
2233     return FALSE;
2234 }
2235
2236 /*
2237 =for apidoc sv_2iv_flags
2238
2239 Return the integer value of an SV, doing any necessary string
2240 conversion.  If C<flags> has the C<SV_GMAGIC> bit set, does an C<mg_get()> first.
2241 Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2242
2243 =cut
2244 */
2245
2246 IV
2247 Perl_sv_2iv_flags(pTHX_ SV *const sv, const I32 flags)
2248 {
2249     PERL_ARGS_ASSERT_SV_2IV_FLAGS;
2250
2251     assert (SvTYPE(sv) != SVt_PVAV && SvTYPE(sv) != SVt_PVHV
2252          && SvTYPE(sv) != SVt_PVFM);
2253
2254     if (SvGMAGICAL(sv) && (flags & SV_GMAGIC))
2255         mg_get(sv);
2256
2257     if (SvROK(sv)) {
2258         if (SvAMAGIC(sv)) {
2259             SV * tmpstr;
2260             if (flags & SV_SKIP_OVERLOAD)
2261                 return 0;
2262             tmpstr = AMG_CALLunary(sv, numer_amg);
2263             if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2264                 return SvIV(tmpstr);
2265             }
2266         }
2267         return PTR2IV(SvRV(sv));
2268     }
2269
2270     if (SvVALID(sv) || isREGEXP(sv)) {
2271         /* FBMs use the space for SvIVX and SvNVX for other purposes, so
2272            must not let them cache IVs.
2273            In practice they are extremely unlikely to actually get anywhere
2274            accessible by user Perl code - the only way that I'm aware of is when
2275            a constant subroutine which is used as the second argument to index.
2276
2277            Regexps have no SvIVX and SvNVX fields.
2278         */
2279         assert(SvPOKp(sv));
2280         {
2281             UV value;
2282             const char * const ptr =
2283                 isREGEXP(sv) ? RX_WRAPPED((REGEXP*)sv) : SvPVX_const(sv);
2284             const int numtype
2285                 = grok_number(ptr, SvCUR(sv), &value);
2286
2287             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2288                 == IS_NUMBER_IN_UV) {
2289                 /* It's definitely an integer */
2290                 if (numtype & IS_NUMBER_NEG) {
2291                     if (value < (UV)IV_MIN)
2292                         return -(IV)value;
2293                 } else {
2294                     if (value < (UV)IV_MAX)
2295                         return (IV)value;
2296                 }
2297             }
2298
2299             /* Quite wrong but no good choices. */
2300             if ((numtype & IS_NUMBER_INFINITY)) {
2301                 return (numtype & IS_NUMBER_NEG) ? IV_MIN : IV_MAX;
2302             } else if ((numtype & IS_NUMBER_NAN)) {
2303                 return 0; /* So wrong. */
2304             }
2305
2306             if (!numtype) {
2307                 if (ckWARN(WARN_NUMERIC))
2308                     not_a_number(sv);
2309             }
2310             return I_V(Atof(ptr));
2311         }
2312     }
2313
2314     if (SvTHINKFIRST(sv)) {
2315         if (SvREADONLY(sv) && !SvOK(sv)) {
2316             if (ckWARN(WARN_UNINITIALIZED))
2317                 report_uninit(sv);
2318             return 0;
2319         }
2320     }
2321
2322     if (!SvIOKp(sv)) {
2323         if (S_sv_2iuv_common(aTHX_ sv))
2324             return 0;
2325     }
2326
2327     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%" UVxf " 2iv(%" IVdf ")\n",
2328         PTR2UV(sv),SvIVX(sv)));
2329     return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
2330 }
2331
2332 /*
2333 =for apidoc sv_2uv_flags
2334
2335 Return the unsigned integer value of an SV, doing any necessary string
2336 conversion.  If C<flags> has the C<SV_GMAGIC> bit set, does an C<mg_get()> first.
2337 Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
2338
2339 =for apidoc Amnh||SV_GMAGIC
2340
2341 =cut
2342 */
2343
2344 UV
2345 Perl_sv_2uv_flags(pTHX_ SV *const sv, const I32 flags)
2346 {
2347     PERL_ARGS_ASSERT_SV_2UV_FLAGS;
2348
2349     if (SvGMAGICAL(sv) && (flags & SV_GMAGIC))
2350         mg_get(sv);
2351
2352     if (SvROK(sv)) {
2353         if (SvAMAGIC(sv)) {
2354             SV *tmpstr;
2355             if (flags & SV_SKIP_OVERLOAD)
2356                 return 0;
2357             tmpstr = AMG_CALLunary(sv, numer_amg);
2358             if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2359                 return SvUV(tmpstr);
2360             }
2361         }
2362         return PTR2UV(SvRV(sv));
2363     }
2364
2365     if (SvVALID(sv) || isREGEXP(sv)) {
2366         /* FBMs use the space for SvIVX and SvNVX for other purposes, and use
2367            the same flag bit as SVf_IVisUV, so must not let them cache IVs.
2368            Regexps have no SvIVX and SvNVX fields. */
2369         assert(SvPOKp(sv));
2370         {
2371             UV value;
2372             const char * const ptr =
2373                 isREGEXP(sv) ? RX_WRAPPED((REGEXP*)sv) : SvPVX_const(sv);
2374             const int numtype
2375                 = grok_number(ptr, SvCUR(sv), &value);
2376
2377             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2378                 == IS_NUMBER_IN_UV) {
2379                 /* It's definitely an integer */
2380                 if (!(numtype & IS_NUMBER_NEG))
2381                     return value;
2382             }
2383
2384             /* Quite wrong but no good choices. */
2385             if ((numtype & IS_NUMBER_INFINITY)) {
2386                 return UV_MAX; /* So wrong. */
2387             } else if ((numtype & IS_NUMBER_NAN)) {
2388                 return 0; /* So wrong. */
2389             }
2390
2391             if (!numtype) {
2392                 if (ckWARN(WARN_NUMERIC))
2393                     not_a_number(sv);
2394             }
2395             return U_V(Atof(ptr));
2396         }
2397     }
2398
2399     if (SvTHINKFIRST(sv)) {
2400         if (SvREADONLY(sv) && !SvOK(sv)) {
2401             if (ckWARN(WARN_UNINITIALIZED))
2402                 report_uninit(sv);
2403             return 0;
2404         }
2405     }
2406
2407     if (!SvIOKp(sv)) {
2408         if (S_sv_2iuv_common(aTHX_ sv))
2409             return 0;
2410     }
2411
2412     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%" UVxf " 2uv(%" UVuf ")\n",
2413                           PTR2UV(sv),SvUVX(sv)));
2414     return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
2415 }
2416
2417 /*
2418 =for apidoc sv_2nv_flags
2419
2420 Return the num value of an SV, doing any necessary string or integer
2421 conversion.  If C<flags> has the C<SV_GMAGIC> bit set, does an C<mg_get()> first.
2422 Normally used via the C<SvNV(sv)> and C<SvNVx(sv)> macros.
2423
2424 =cut
2425 */
2426
2427 NV
2428 Perl_sv_2nv_flags(pTHX_ SV *const sv, const I32 flags)
2429 {
2430     PERL_ARGS_ASSERT_SV_2NV_FLAGS;
2431
2432     assert (SvTYPE(sv) != SVt_PVAV && SvTYPE(sv) != SVt_PVHV
2433          && SvTYPE(sv) != SVt_PVFM);
2434     if (SvGMAGICAL(sv) || SvVALID(sv) || isREGEXP(sv)) {
2435         /* FBMs use the space for SvIVX and SvNVX for other purposes, and use
2436            the same flag bit as SVf_IVisUV, so must not let them cache NVs.
2437            Regexps have no SvIVX and SvNVX fields.  */
2438         const char *ptr;
2439         if (flags & SV_GMAGIC)
2440             mg_get(sv);
2441         if (SvNOKp(sv))
2442             return SvNVX(sv);
2443         if (SvPOKp(sv) && !SvIOKp(sv)) {
2444             ptr = SvPVX_const(sv);
2445             if (!SvIOKp(sv) && ckWARN(WARN_NUMERIC) &&
2446                 !grok_number(ptr, SvCUR(sv), NULL))
2447                 not_a_number(sv);
2448             return Atof(ptr);
2449         }
2450         if (SvIOKp(sv)) {
2451             if (SvIsUV(sv))
2452                 return (NV)SvUVX(sv);
2453             else
2454                 return (NV)SvIVX(sv);
2455         }
2456         if (SvROK(sv)) {
2457             goto return_rok;
2458         }
2459         assert(SvTYPE(sv) >= SVt_PVMG);
2460         /* This falls through to the report_uninit near the end of the
2461            function. */
2462     } else if (SvTHINKFIRST(sv)) {
2463         if (SvROK(sv)) {
2464         return_rok:
2465             if (SvAMAGIC(sv)) {
2466                 SV *tmpstr;
2467                 if (flags & SV_SKIP_OVERLOAD)
2468                     return 0;
2469                 tmpstr = AMG_CALLunary(sv, numer_amg);
2470                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2471                     return SvNV(tmpstr);
2472                 }
2473             }
2474             return PTR2NV(SvRV(sv));
2475         }
2476         if (SvREADONLY(sv) && !SvOK(sv)) {
2477             if (ckWARN(WARN_UNINITIALIZED))
2478                 report_uninit(sv);
2479             return 0.0;
2480         }
2481     }
2482     if (SvTYPE(sv) < SVt_NV) {
2483         /* The logic to use SVt_PVNV if necessary is in sv_upgrade.  */
2484         sv_upgrade(sv, SVt_NV);
2485         CLANG_DIAG_IGNORE_STMT(-Wthread-safety);
2486         DEBUG_c({
2487             DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
2488             STORE_LC_NUMERIC_SET_STANDARD();
2489             PerlIO_printf(Perl_debug_log,
2490                           "0x%" UVxf " num(%" NVgf ")\n",
2491                           PTR2UV(sv), SvNVX(sv));
2492             RESTORE_LC_NUMERIC();
2493         });
2494         CLANG_DIAG_RESTORE_STMT;
2495
2496     }
2497     else if (SvTYPE(sv) < SVt_PVNV)
2498         sv_upgrade(sv, SVt_PVNV);
2499     if (SvNOKp(sv)) {
2500         return SvNVX(sv);
2501     }
2502     if (SvIOKp(sv)) {
2503         SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
2504 #ifdef NV_PRESERVES_UV
2505         if (SvIOK(sv))
2506             SvNOK_on(sv);
2507         else
2508             SvNOKp_on(sv);
2509 #else
2510         /* Only set the public NV OK flag if this NV preserves the IV  */
2511         /* Check it's not 0xFFFFFFFFFFFFFFFF */
2512         if (SvIOK(sv) &&
2513             SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
2514                        : (SvIVX(sv) == I_V(SvNVX(sv))))
2515             SvNOK_on(sv);
2516         else
2517             SvNOKp_on(sv);
2518 #endif
2519     }
2520     else if (SvPOKp(sv)) {
2521         UV value;
2522         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2523         if (!SvIOKp(sv) && !numtype && ckWARN(WARN_NUMERIC))
2524             not_a_number(sv);
2525 #ifdef NV_PRESERVES_UV
2526         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2527             == IS_NUMBER_IN_UV) {
2528             /* It's definitely an integer */
2529             SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
2530         } else {
2531             S_sv_setnv(aTHX_ sv, numtype);
2532         }
2533         if (numtype)
2534             SvNOK_on(sv);
2535         else
2536             SvNOKp_on(sv);
2537 #else
2538         SvNV_set(sv, Atof(SvPVX_const(sv)));
2539         /* Only set the public NV OK flag if this NV preserves the value in
2540            the PV at least as well as an IV/UV would.
2541            Not sure how to do this 100% reliably. */
2542         /* if that shift count is out of range then Configure's test is
2543            wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2544            UV_BITS */
2545         if (((UV)1 << NV_PRESERVES_UV_BITS) > U_V(Perl_fabs(SvNVX(sv)))) {
2546             SvNOK_on(sv); /* Definitely small enough to preserve all bits */
2547         } else if (!(numtype & IS_NUMBER_IN_UV)) {
2548             /* Can't use strtol etc to convert this string, so don't try.
2549                sv_2iv and sv_2uv will use the NV to convert, not the PV.  */
2550             SvNOK_on(sv);
2551         } else {
2552             /* value has been set.  It may not be precise.  */
2553             if ((numtype & IS_NUMBER_NEG) && (value >= (UV)IV_MIN)) {
2554                 /* 2s complement assumption for (UV)IV_MIN  */
2555                 SvNOK_on(sv); /* Integer is too negative.  */
2556             } else {
2557                 SvNOKp_on(sv);
2558                 SvIOKp_on(sv);
2559
2560                 if (numtype & IS_NUMBER_NEG) {
2561                     /* -IV_MIN is undefined, but we should never reach
2562                      * this point with both IS_NUMBER_NEG and value ==
2563                      * (UV)IV_MIN */
2564                     assert(value != (UV)IV_MIN);
2565                     SvIV_set(sv, -(IV)value);
2566                 } else if (value <= (UV)IV_MAX) {
2567                     SvIV_set(sv, (IV)value);
2568                 } else {
2569                     SvUV_set(sv, value);
2570                     SvIsUV_on(sv);
2571                 }
2572
2573                 if (numtype & IS_NUMBER_NOT_INT) {
2574                     /* I believe that even if the original PV had decimals,
2575                        they are lost beyond the limit of the FP precision.
2576                        However, neither is canonical, so both only get p
2577                        flags.  NWC, 2000/11/25 */
2578                     /* Both already have p flags, so do nothing */
2579                 } else {
2580                     const NV nv = SvNVX(sv);
2581                     /* XXX should this spot have NAN_COMPARE_BROKEN, too? */
2582                     if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2583                         if (SvIVX(sv) == I_V(nv)) {
2584                             SvNOK_on(sv);
2585                         } else {
2586                             /* It had no "." so it must be integer.  */
2587                         }
2588                         SvIOK_on(sv);
2589                     } else {
2590                         /* between IV_MAX and NV(UV_MAX).
2591                            Could be slightly > UV_MAX */
2592
2593                         if (numtype & IS_NUMBER_NOT_INT) {
2594                             /* UV and NV both imprecise.  */
2595                         } else {
2596                             const UV nv_as_uv = U_V(nv);
2597
2598                             if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2599                                 SvNOK_on(sv);
2600                             }
2601                             SvIOK_on(sv);
2602                         }
2603                     }
2604                 }
2605             }
2606         }
2607         /* It might be more code efficient to go through the entire logic above
2608            and conditionally set with SvNOKp_on() rather than SvNOK(), but it
2609            gets complex and potentially buggy, so more programmer efficient
2610            to do it this way, by turning off the public flags:  */
2611         if (!numtype)
2612             SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2613 #endif /* NV_PRESERVES_UV */
2614     }
2615     else {
2616         if (isGV_with_GP(sv)) {
2617             glob_2number(MUTABLE_GV(sv));
2618             return 0.0;
2619         }
2620
2621         if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2622             report_uninit(sv);
2623         assert (SvTYPE(sv) >= SVt_NV);
2624         /* Typically the caller expects that sv_any is not NULL now.  */
2625         /* XXX Ilya implies that this is a bug in callers that assume this
2626            and ideally should be fixed.  */
2627         return 0.0;
2628     }
2629     CLANG_DIAG_IGNORE_STMT(-Wthread-safety);
2630     DEBUG_c({
2631         DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
2632         STORE_LC_NUMERIC_SET_STANDARD();
2633         PerlIO_printf(Perl_debug_log, "0x%" UVxf " 2nv(%" NVgf ")\n",
2634                       PTR2UV(sv), SvNVX(sv));
2635         RESTORE_LC_NUMERIC();
2636     });
2637     CLANG_DIAG_RESTORE_STMT;
2638     return SvNVX(sv);
2639 }
2640
2641 /*
2642 =for apidoc sv_2num
2643
2644 Return an SV with the numeric value of the source SV, doing any necessary
2645 reference or overload conversion.  The caller is expected to have handled
2646 get-magic already.
2647
2648 =cut
2649 */
2650
2651 SV *
2652 Perl_sv_2num(pTHX_ SV *const sv)
2653 {
2654     PERL_ARGS_ASSERT_SV_2NUM;
2655
2656     if (!SvROK(sv))
2657         return sv;
2658     if (SvAMAGIC(sv)) {
2659         SV * const tmpsv = AMG_CALLunary(sv, numer_amg);
2660         TAINT_IF(tmpsv && SvTAINTED(tmpsv));
2661         if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
2662             return sv_2num(tmpsv);
2663     }
2664     return sv_2mortal(newSVuv(PTR2UV(SvRV(sv))));
2665 }
2666
2667 /* int2str_table: lookup table containing string representations of all
2668  * two digit numbers. For example, int2str_table.arr[0] is "00" and
2669  * int2str_table.arr[12*2] is "12".
2670  *
2671  * We are going to read two bytes at a time, so we have to ensure that
2672  * the array is aligned to a 2 byte boundary. That's why it was made a
2673  * union with a dummy U16 member. */
2674 static const union {
2675     char arr[200];
2676     U16 dummy;
2677 } int2str_table = {{
2678     '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6',
2679     '0', '7', '0', '8', '0', '9', '1', '0', '1', '1', '1', '2', '1', '3',
2680     '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', '2', '0',
2681     '2', '1', '2', '2', '2', '3', '2', '4', '2', '5', '2', '6', '2', '7',
2682     '2', '8', '2', '9', '3', '0', '3', '1', '3', '2', '3', '3', '3', '4',
2683     '3', '5', '3', '6', '3', '7', '3', '8', '3', '9', '4', '0', '4', '1',
2684     '4', '2', '4', '3', '4', '4', '4', '5', '4', '6', '4', '7', '4', '8',
2685     '4', '9', '5', '0', '5', '1', '5', '2', '5', '3', '5', '4', '5', '5',
2686     '5', '6', '5', '7', '5', '8', '5', '9', '6', '0', '6', '1', '6', '2',
2687     '6', '3', '6', '4', '6', '5', '6', '6', '6', '7', '6', '8', '6', '9',
2688     '7', '0', '7', '1', '7', '2', '7', '3', '7', '4', '7', '5', '7', '6',
2689     '7', '7', '7', '8', '7', '9', '8', '0', '8', '1', '8', '2', '8', '3',
2690     '8', '4', '8', '5', '8', '6', '8', '7', '8', '8', '8', '9', '9', '0',
2691     '9', '1', '9', '2', '9', '3', '9', '4', '9', '5', '9', '6', '9', '7',
2692     '9', '8', '9', '9'
2693 }};
2694
2695 /* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2696  * UV as a string towards the end of buf, and return pointers to start and
2697  * end of it.
2698  *
2699  * We assume that buf is at least TYPE_CHARS(UV) long.
2700  */
2701
2702 PERL_STATIC_INLINE char *
2703 S_uiv_2buf(char *const buf, const IV iv, UV uv, const int is_uv, char **const peob)
2704 {
2705     char *ptr = buf + TYPE_CHARS(UV);
2706     char * const ebuf = ptr;
2707     int sign;
2708     U16 *word_ptr, *word_table;
2709
2710     PERL_ARGS_ASSERT_UIV_2BUF;
2711
2712     /* ptr has to be properly aligned, because we will cast it to U16* */
2713     assert(PTR2nat(ptr) % 2 == 0);
2714     /* we are going to read/write two bytes at a time */
2715     word_ptr = (U16*)ptr;
2716     word_table = (U16*)int2str_table.arr;
2717
2718     if (UNLIKELY(is_uv))
2719         sign = 0;
2720     else if (iv >= 0) {
2721         uv = iv;
2722         sign = 0;
2723     } else {
2724         /* Using 0- here to silence bogus warning from MS VC */
2725         uv = (UV) (0 - (UV) iv);
2726         sign = 1;
2727     }
2728
2729     while (uv > 99) {
2730         *--word_ptr = word_table[uv % 100];
2731         uv /= 100;
2732     }
2733     ptr = (char*)word_ptr;
2734
2735     if (uv < 10)
2736         *--ptr = (char)uv + '0';
2737     else {
2738         *--word_ptr = word_table[uv];
2739         ptr = (char*)word_ptr;
2740     }
2741
2742     if (sign)
2743         *--ptr = '-';
2744
2745     *peob = ebuf;
2746     return ptr;
2747 }
2748
2749 /* Helper for sv_2pv_flags and sv_vcatpvfn_flags.  If the NV is an
2750  * infinity or a not-a-number, writes the appropriate strings to the
2751  * buffer, including a zero byte.  On success returns the written length,
2752  * excluding the zero byte, on failure (not an infinity, not a nan)
2753  * returns zero, assert-fails on maxlen being too short.
2754  *
2755  * XXX for "Inf", "-Inf", and "NaN", we could have three read-only
2756  * shared string constants we point to, instead of generating a new
2757  * string for each instance. */
2758 STATIC size_t
2759 S_infnan_2pv(NV nv, char* buffer, size_t maxlen, char plus) {
2760     char* s = buffer;
2761     assert(maxlen >= 4);
2762     if (Perl_isinf(nv)) {
2763         if (nv < 0) {
2764             if (maxlen < 5) /* "-Inf\0"  */
2765                 return 0;
2766             *s++ = '-';
2767         } else if (plus) {
2768             *s++ = '+';
2769         }
2770         *s++ = 'I';
2771         *s++ = 'n';
2772         *s++ = 'f';
2773     }
2774     else if (Perl_isnan(nv)) {
2775         *s++ = 'N';
2776         *s++ = 'a';
2777         *s++ = 'N';
2778         /* XXX optionally output the payload mantissa bits as
2779          * "(unsigned)" (to match the nan("...") C99 function,
2780          * or maybe as "(0xhhh...)"  would make more sense...
2781          * provide a format string so that the user can decide?
2782          * NOTE: would affect the maxlen and assert() logic.*/
2783     }
2784     else {
2785       return 0;
2786     }
2787     assert((s == buffer + 3) || (s == buffer + 4));
2788     *s = 0;
2789     return s - buffer;
2790 }
2791
2792 /*
2793 =for apidoc      sv_2pv
2794 =for apidoc_item sv_2pv_flags
2795
2796 These implement the various forms of the L<perlapi/C<SvPV>> macros.
2797 The macros are the preferred interface.
2798
2799 These return a pointer to the string value of an SV (coercing it to a string if
2800 necessary), and set C<*lp> to its length in bytes.
2801
2802 The forms differ in that plain C<sv_2pvbyte> always processes 'get' magic; and
2803 C<sv_2pvbyte_flags> processes 'get' magic if and only if C<flags> contains
2804 C<SV_GMAGIC>.
2805
2806 =for apidoc Amnh||SV_GMAGIC
2807
2808 =cut
2809 */
2810
2811 char *
2812 Perl_sv_2pv_flags(pTHX_ SV *const sv, STRLEN *const lp, const U32 flags)
2813 {
2814     char *s;
2815
2816     PERL_ARGS_ASSERT_SV_2PV_FLAGS;
2817
2818     assert (SvTYPE(sv) != SVt_PVAV && SvTYPE(sv) != SVt_PVHV
2819          && SvTYPE(sv) != SVt_PVFM);
2820     if (SvGMAGICAL(sv) && (flags & SV_GMAGIC))
2821         mg_get(sv);
2822     if (SvROK(sv)) {
2823         if (SvAMAGIC(sv)) {
2824             SV *tmpstr;
2825             if (flags & SV_SKIP_OVERLOAD)
2826                 return NULL;
2827             tmpstr = AMG_CALLunary(sv, string_amg);
2828             TAINT_IF(tmpstr && SvTAINTED(tmpstr));
2829             if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2830                 /* Unwrap this:  */
2831                 /* char *pv = lp ? SvPV(tmpstr, *lp) : SvPV_nolen(tmpstr);
2832                  */
2833
2834                 char *pv;
2835                 if ((SvFLAGS(tmpstr) & (SVf_POK)) == SVf_POK) {
2836                     if (flags & SV_CONST_RETURN) {
2837                         pv = (char *) SvPVX_const(tmpstr);
2838                     } else {
2839                         pv = (flags & SV_MUTABLE_RETURN)
2840                             ? SvPVX_mutable(tmpstr) : SvPVX(tmpstr);
2841                     }
2842                     if (lp)
2843                         *lp = SvCUR(tmpstr);
2844                 } else {
2845                     pv = sv_2pv_flags(tmpstr, lp, flags);
2846                 }
2847                 if (SvUTF8(tmpstr))
2848                     SvUTF8_on(sv);
2849                 else
2850                     SvUTF8_off(sv);
2851                 return pv;
2852             }
2853         }
2854         {
2855             STRLEN len;
2856             char *retval;
2857             char *buffer;
2858             SV *const referent = SvRV(sv);
2859
2860             if (!referent) {
2861                 len = 7;
2862                 retval = buffer = savepvn("NULLREF", len);
2863             } else if (SvTYPE(referent) == SVt_REGEXP &&
2864                        (!(PL_curcop->cop_hints & HINT_NO_AMAGIC) ||
2865                         amagic_is_enabled(string_amg))) {
2866                 REGEXP * const re = (REGEXP *)MUTABLE_PTR(referent);
2867
2868                 assert(re);
2869
2870                 /* If the regex is UTF-8 we want the containing scalar to
2871                    have an UTF-8 flag too */
2872                 if (RX_UTF8(re))
2873                     SvUTF8_on(sv);
2874                 else
2875                     SvUTF8_off(sv);
2876
2877                 if (lp)
2878                     *lp = RX_WRAPLEN(re);
2879
2880                 return RX_WRAPPED(re);
2881             } else {
2882                 const char *const typestring = sv_reftype(referent, 0);
2883                 const STRLEN typelen = strlen(typestring);
2884                 UV addr = PTR2UV(referent);
2885                 const char *stashname = NULL;
2886                 STRLEN stashnamelen = 0; /* hush, gcc */
2887                 const char *buffer_end;
2888
2889                 if (SvOBJECT(referent)) {
2890                     const HEK *const name = HvNAME_HEK(SvSTASH(referent));
2891
2892                     if (name) {
2893                         stashname = HEK_KEY(name);
2894                         stashnamelen = HEK_LEN(name);
2895
2896                         if (HEK_UTF8(name)) {
2897                             SvUTF8_on(sv);
2898                         } else {
2899                             SvUTF8_off(sv);
2900                         }
2901                     } else {
2902                         stashname = "__ANON__";
2903                         stashnamelen = 8;
2904                     }
2905                     len = stashnamelen + 1 /* = */ + typelen + 3 /* (0x */
2906                         + 2 * sizeof(UV) + 2 /* )\0 */;
2907                 } else {
2908                     len = typelen + 3 /* (0x */
2909                         + 2 * sizeof(UV) + 2 /* )\0 */;
2910                 }
2911
2912                 Newx(buffer, len, char);
2913                 buffer_end = retval = buffer + len;
2914
2915                 /* Working backwards  */
2916                 *--retval = '\0';
2917                 *--retval = ')';
2918                 do {
2919                     *--retval = PL_hexdigit[addr & 15];
2920                 } while (addr >>= 4);
2921                 *--retval = 'x';
2922                 *--retval = '0';
2923                 *--retval = '(';
2924
2925                 retval -= typelen;
2926                 memcpy(retval, typestring, typelen);
2927
2928                 if (stashname) {
2929                     *--retval = '=';
2930                     retval -= stashnamelen;
2931                     memcpy(retval, stashname, stashnamelen);
2932                 }
2933                 /* retval may not necessarily have reached the start of the
2934                    buffer here.  */
2935                 assert (retval >= buffer);
2936
2937                 len = buffer_end - retval - 1; /* -1 for that \0  */
2938             }
2939             if (lp)
2940                 *lp = len;
2941             SAVEFREEPV(buffer);
2942             return retval;
2943         }
2944     }
2945
2946     if (SvPOKp(sv)) {
2947         if (lp)
2948             *lp = SvCUR(sv);
2949         if (flags & SV_MUTABLE_RETURN)
2950             return SvPVX_mutable(sv);
2951         if (flags & SV_CONST_RETURN)
2952             return (char *)SvPVX_const(sv);
2953         return SvPVX(sv);
2954     }
2955
2956     if (SvIOK(sv)) {
2957         /* I'm assuming that if both IV and NV are equally valid then
2958            converting the IV is going to be more efficient */
2959         const U32 isUIOK = SvIsUV(sv);
2960         /* The purpose of this union is to ensure that arr is aligned on
2961            a 2 byte boundary, because that is what uiv_2buf() requires */
2962         union {
2963             char arr[TYPE_CHARS(UV)];
2964             U16 dummy;
2965         } buf;
2966         char *ebuf, *ptr;
2967         STRLEN len;
2968
2969         if (SvTYPE(sv) < SVt_PVIV)
2970             sv_upgrade(sv, SVt_PVIV);
2971         ptr = uiv_2buf(buf.arr, SvIVX(sv), SvUVX(sv), isUIOK, &ebuf);
2972         len = ebuf - ptr;
2973         /* inlined from sv_setpvn */
2974         s = SvGROW_mutable(sv, len + 1);
2975         Move(ptr, s, len, char);
2976         s += len;
2977         *s = '\0';
2978         /* We used to call SvPOK_on(). Whilst this is fine for (most) Perl code,
2979            it means that after this stringification is cached, there is no way
2980            to distinguish between values originally assigned as $a = 42; and
2981            $a = "42"; (or results of string operators vs numeric operators)
2982            where the value has subsequently been used in the other sense
2983            and had a value cached.
2984            This (somewhat) hack means that we retain the cached stringification,
2985            but don't set SVf_POK. Hence if a value is SVf_IOK|SVf_POK then it
2986            originated as "42", whereas if it's SVf_IOK then it originated as 42.
2987            (ignore SVp_IOK and SVp_POK)
2988            The SvPV macros are now updated to recognise this specific case
2989            (and that there isn't overloading or magic that could alter the
2990            cached value) and so return the cached value immediately without
2991            re-entering this function, getting back here to this block of code,
2992            and repeating the same conversion. */
2993         SvPOKp_on(sv);
2994     }
2995     else if (SvNOK(sv)) {
2996         if (SvTYPE(sv) < SVt_PVNV)
2997             sv_upgrade(sv, SVt_PVNV);
2998         if (SvNVX(sv) == 0.0
2999 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
3000             && !Perl_isnan(SvNVX(sv))
3001 #endif
3002         ) {
3003             s = SvGROW_mutable(sv, 2);
3004             *s++ = '0';
3005             *s = '\0';
3006         } else {
3007             STRLEN len;
3008             STRLEN size = 5; /* "-Inf\0" */
3009
3010             s = SvGROW_mutable(sv, size);
3011             len = S_infnan_2pv(SvNVX(sv), s, size, 0);
3012             if (len > 0) {
3013                 s += len;
3014                 SvPOKp_on(sv);
3015             }
3016             else {
3017                 /* some Xenix systems wipe out errno here */
3018                 dSAVE_ERRNO;
3019
3020                 size =
3021                     1 + /* sign */
3022                     1 + /* "." */
3023                     NV_DIG +
3024                     1 + /* "e" */
3025                     1 + /* sign */
3026                     5 + /* exponent digits */
3027                     1 + /* \0 */
3028                     2; /* paranoia */
3029
3030                 s = SvGROW_mutable(sv, size);
3031 #ifndef USE_LOCALE_NUMERIC
3032                 SNPRINTF_G(SvNVX(sv), s, SvLEN(sv), NV_DIG);
3033
3034                 SvPOKp_on(sv);
3035 #else
3036                 {
3037                     bool local_radix;
3038                     DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
3039                     STORE_LC_NUMERIC_SET_TO_NEEDED();
3040
3041                     local_radix = NOT_IN_NUMERIC_STANDARD_;
3042                     if (local_radix && SvCUR(PL_numeric_radix_sv) > 1) {
3043                         size += SvCUR(PL_numeric_radix_sv) - 1;
3044                         s = SvGROW_mutable(sv, size);
3045                     }
3046
3047                     SNPRINTF_G(SvNVX(sv), s, SvLEN(sv), NV_DIG);
3048
3049                     /* If the radix character is UTF-8, and actually is in the
3050                      * output, turn on the UTF-8 flag for the scalar */
3051                     if (   local_radix
3052                         && SvUTF8(PL_numeric_radix_sv)
3053                         && instr(s, SvPVX_const(PL_numeric_radix_sv)))
3054                     {
3055                         SvUTF8_on(sv);
3056                     }
3057
3058                     RESTORE_LC_NUMERIC();
3059                 }
3060
3061                 /* We don't call SvPOK_on(), because it may come to
3062                  * pass that the locale changes so that the
3063                  * stringification we just did is no longer correct.  We
3064                  * will have to re-stringify every time it is needed */
3065 #endif
3066                 RESTORE_ERRNO;
3067             }
3068             while (*s) s++;
3069         }
3070     }
3071     else if (isGV_with_GP(sv)) {
3072         GV *const gv = MUTABLE_GV(sv);
3073         SV *const buffer = sv_newmortal();
3074
3075         gv_efullname3(buffer, gv, "*");
3076
3077         assert(SvPOK(buffer));
3078         if (SvUTF8(buffer))
3079             SvUTF8_on(sv);
3080         else
3081             SvUTF8_off(sv);
3082         if (lp)
3083             *lp = SvCUR(buffer);
3084         return SvPVX(buffer);
3085     }
3086     else {
3087         if (lp)
3088             *lp = 0;
3089         if (flags & SV_UNDEF_RETURNS_NULL)
3090             return NULL;
3091         if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
3092             report_uninit(sv);
3093         /* Typically the caller expects that sv_any is not NULL now.  */
3094         if (!SvREADONLY(sv) && SvTYPE(sv) < SVt_PV)
3095             sv_upgrade(sv, SVt_PV);
3096         return (char *)"";
3097     }
3098
3099     {
3100         const STRLEN len = s - SvPVX_const(sv);
3101         if (lp)
3102             *lp = len;
3103         SvCUR_set(sv, len);
3104     }
3105     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%" UVxf " 2pv(%s)\n",
3106                           PTR2UV(sv),SvPVX_const(sv)));
3107     if (flags & SV_CONST_RETURN)
3108         return (char *)SvPVX_const(sv);
3109     if (flags & SV_MUTABLE_RETURN)
3110         return SvPVX_mutable(sv);
3111     return SvPVX(sv);
3112 }
3113
3114 /*
3115 =for apidoc sv_copypv
3116 =for apidoc_item sv_copypv_flags
3117 =for apidoc_item sv_copypv_nomg
3118
3119 These copy a stringified representation of the source SV into the
3120 destination SV.  They automatically perform coercion of numeric values into
3121 strings.  Guaranteed to preserve the C<UTF8> flag even from overloaded objects.
3122 Similar in nature to C<sv_2pv[_flags]> but they operate directly on an SV
3123 instead of just the string.  Mostly they use L</C<sv_2pv_flags>> to
3124 do the work, except when that would lose the UTF-8'ness of the PV.
3125
3126 The three forms differ only in whether or not they perform 'get magic' on
3127 C<sv>.  C<sv_copypv_nomg> skips 'get magic'; C<sv_copypv> performs it; and
3128 C<sv_copypv_flags> either performs it (if the C<SV_GMAGIC> bit is set in
3129 C<flags>) or doesn't (if that bit is cleared).
3130
3131 =cut
3132 */
3133
3134 void
3135 Perl_sv_copypv_flags(pTHX_ SV *const dsv, SV *const ssv, const I32 flags)
3136 {
3137     STRLEN len;
3138     const char *s;
3139
3140     PERL_ARGS_ASSERT_SV_COPYPV_FLAGS;
3141
3142     s = SvPV_flags_const(ssv,len,(flags & SV_GMAGIC));
3143     sv_setpvn(dsv,s,len);
3144     if (SvUTF8(ssv))
3145         SvUTF8_on(dsv);
3146     else
3147         SvUTF8_off(dsv);
3148 }
3149
3150 /*
3151 =for apidoc      sv_2pvbyte
3152 =for apidoc_item sv_2pvbyte_flags
3153
3154 These implement the various forms of the L<perlapi/C<SvPVbyte>> macros.
3155 The macros are the preferred interface.
3156
3157 These return a pointer to the byte-encoded representation of the SV, and set
3158 C<*lp> to its length.  If the SV is marked as being encoded as UTF-8, it will
3159 be downgraded, if possible, to a byte string.  If the SV cannot be downgraded,
3160 they croak.
3161
3162 The forms differ in that plain C<sv_2pvbyte> always processes 'get' magic; and
3163 C<sv_2pvbyte_flags> processes 'get' magic if and only if C<flags> contains
3164 C<SV_GMAGIC>.
3165
3166 =for apidoc Amnh||SV_GMAGIC
3167
3168 =cut
3169 */
3170
3171 char *
3172 Perl_sv_2pvbyte_flags(pTHX_ SV *sv, STRLEN *const lp, const U32 flags)
3173 {
3174     PERL_ARGS_ASSERT_SV_2PVBYTE_FLAGS;
3175
3176     if (SvGMAGICAL(sv) && (flags & SV_GMAGIC))
3177         mg_get(sv);
3178     if (((SvREADONLY(sv) || SvFAKE(sv)) && !SvIsCOW(sv))
3179      || isGV_with_GP(sv) || SvROK(sv)) {
3180         SV *sv2 = sv_newmortal();
3181         sv_copypv_nomg(sv2,sv);
3182         sv = sv2;
3183     }
3184     sv_utf8_downgrade_nomg(sv,0);
3185     return lp ? SvPV_nomg(sv,*lp) : SvPV_nomg_nolen(sv);
3186 }
3187
3188 /*
3189 =for apidoc      sv_2pvutf8
3190 =for apidoc_item sv_2pvutf8_flags
3191
3192 These implement the various forms of the L<perlapi/C<SvPVutf8>> macros.
3193 The macros are the preferred interface.
3194
3195 These return a pointer to the UTF-8-encoded representation of the SV, and set
3196 C<*lp> to its length in bytes.  They may cause the SV to be upgraded to UTF-8
3197 as a side-effect.
3198
3199 The forms differ in that plain C<sv_2pvutf8> always processes 'get' magic; and
3200 C<sv_2pvutf8_flags> processes 'get' magic if and only if C<flags> contains
3201 C<SV_GMAGIC>.
3202
3203 =cut
3204 */
3205
3206 char *
3207 Perl_sv_2pvutf8_flags(pTHX_ SV *sv, STRLEN *const lp, const U32 flags)
3208 {
3209     PERL_ARGS_ASSERT_SV_2PVUTF8_FLAGS;
3210
3211     if (SvGMAGICAL(sv) && (flags & SV_GMAGIC))
3212         mg_get(sv);
3213     if (((SvREADONLY(sv) || SvFAKE(sv)) && !SvIsCOW(sv))
3214      || isGV_with_GP(sv) || SvROK(sv)) {
3215         SV *sv2 = sv_newmortal();
3216         sv_copypv_nomg(sv2,sv);
3217         sv = sv2;
3218     }
3219     sv_utf8_upgrade_nomg(sv);
3220     return lp ? SvPV_nomg(sv,*lp) : SvPV_nomg_nolen(sv);
3221 }
3222
3223
3224 /*
3225 =for apidoc sv_2bool
3226
3227 This macro is only used by C<sv_true()> or its macro equivalent, and only if
3228 the latter's argument is neither C<SvPOK>, C<SvIOK> nor C<SvNOK>.
3229 It calls C<sv_2bool_flags> with the C<SV_GMAGIC> flag.
3230
3231 =for apidoc sv_2bool_flags
3232
3233 This function is only used by C<sv_true()> and friends,  and only if
3234 the latter's argument is neither C<SvPOK>, C<SvIOK> nor C<SvNOK>.  If the flags
3235 contain C<SV_GMAGIC>, then it does an C<mg_get()> first.
3236
3237
3238 =cut
3239 */
3240
3241 bool
3242 Perl_sv_2bool_flags(pTHX_ SV *sv, I32 flags)
3243 {
3244     PERL_ARGS_ASSERT_SV_2BOOL_FLAGS;
3245
3246     restart:
3247     if(flags & SV_GMAGIC) SvGETMAGIC(sv);
3248
3249     if (!SvOK(sv))
3250         return 0;
3251     if (SvROK(sv)) {
3252         if (SvAMAGIC(sv)) {
3253             SV * const tmpsv = AMG_CALLunary(sv, bool__amg);
3254             if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv)))) {
3255                 bool svb;
3256                 sv = tmpsv;
3257                 if(SvGMAGICAL(sv)) {
3258                     flags = SV_GMAGIC;
3259                     goto restart; /* call sv_2bool */
3260                 }
3261                 /* expanded SvTRUE_common(sv, (flags = 0, goto restart)) */
3262                 else if(!SvOK(sv)) {
3263                     svb = 0;
3264                 }
3265                 else if(SvPOK(sv)) {
3266                     svb = SvPVXtrue(sv);
3267                 }
3268                 else if((SvFLAGS(sv) & (SVf_IOK|SVf_NOK))) {
3269                     svb = (SvIOK(sv) && SvIVX(sv) != 0)
3270                         || (SvNOK(sv) && SvNVX(sv) != 0.0);
3271                 }
3272                 else {
3273                     flags = 0;
3274                     goto restart; /* call sv_2bool_nomg */
3275                 }
3276                 return cBOOL(svb);
3277             }
3278         }
3279         assert(SvRV(sv));
3280         return TRUE;
3281     }
3282     if (isREGEXP(sv))
3283         return
3284           RX_WRAPLEN(sv) > 1 || (RX_WRAPLEN(sv) && *RX_WRAPPED(sv) != '0');
3285
3286     if (SvNOK(sv) && !SvPOK(sv))
3287         return SvNVX(sv) != 0.0;
3288
3289     return SvTRUE_common(sv, 0);
3290 }
3291
3292 /*
3293 =for apidoc sv_utf8_upgrade
3294 =for apidoc_item sv_utf8_upgrade_flags
3295 =for apidoc_item sv_utf8_upgrade_flags_grow
3296 =for apidoc_item sv_utf8_upgrade_nomg
3297
3298 These convert the PV of an SV to its UTF-8-encoded form.
3299 The SV is forced to string form if it is not already.
3300 They always set the C<SvUTF8> flag to avoid future validity checks even if the
3301 whole string is the same in UTF-8 as not.
3302 They return the number of bytes in the converted string
3303
3304 The forms differ in just two ways.  The main difference is whether or not they
3305 perform 'get magic' on C<sv>.  C<sv_utf8_upgrade_nomg> skips 'get magic';
3306 C<sv_utf8_upgrade> performs it; and C<sv_utf8_upgrade_flags> and
3307 C<sv_utf8_upgrade_flags_grow> either perform it (if the C<SV_GMAGIC> bit is set
3308 in C<flags>) or don't (if that bit is cleared).
3309
3310 The other difference is that C<sv_utf8_upgrade_flags_grow> has an additional
3311 parameter, C<extra>, which allows the caller to specify an amount of space to
3312 be reserved as spare beyond what is needed for the actual conversion.  This is
3313 used when the caller knows it will soon be needing yet more space, and it is
3314 more efficient to request space from the system in a single call.
3315 This form is otherwise identical to C<sv_utf8_upgrade_flags>.
3316
3317 These are not a general purpose byte encoding to Unicode interface: use the
3318 Encode extension for that.
3319
3320 The C<SV_FORCE_UTF8_UPGRADE> flag is now ignored.
3321
3322 =for apidoc Amnh||SV_GMAGIC|
3323 =for apidoc Amnh||SV_FORCE_UTF8_UPGRADE|
3324
3325 =cut
3326
3327 If the routine itself changes the string, it adds a trailing C<NUL>.  Such a
3328 C<NUL> isn't guaranteed due to having other routines do the work in some input
3329 cases, or if the input is already flagged as being in utf8.
3330
3331 */
3332
3333 STRLEN
3334 Perl_sv_utf8_upgrade_flags_grow(pTHX_ SV *const sv, const I32 flags, STRLEN extra)
3335 {
3336     PERL_ARGS_ASSERT_SV_UTF8_UPGRADE_FLAGS_GROW;
3337
3338     if (sv == &PL_sv_undef)
3339         return 0;
3340     if (!SvPOK_nog(sv)) {
3341         STRLEN len = 0;
3342         if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
3343             (void) sv_2pv_flags(sv,&len, flags);
3344             if (SvUTF8(sv)) {
3345                 if (extra) SvGROW(sv, SvCUR(sv) + extra);
3346                 return len;
3347             }
3348         } else {
3349             (void) SvPV_force_flags(sv,len,flags & SV_GMAGIC);
3350         }
3351     }
3352
3353     /* SVt_REGEXP's shouldn't be upgraded to UTF8 - they're already
3354      * compiled and individual nodes will remain non-utf8 even if the
3355      * stringified version of the pattern gets upgraded. Whether the
3356      * PVX of a REGEXP should be grown or we should just croak, I don't
3357      * know - DAPM */
3358     if (SvUTF8(sv) || isREGEXP(sv)) {
3359         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3360         return SvCUR(sv);
3361     }
3362
3363     if (SvIsCOW(sv)) {
3364         S_sv_uncow(aTHX_ sv, 0);
3365     }
3366
3367     if (SvCUR(sv) == 0) {
3368         if (extra) SvGROW(sv, extra + 1); /* Make sure is room for a trailing
3369                                              byte */
3370     } else { /* Assume Latin-1/EBCDIC */
3371         /* This function could be much more efficient if we
3372          * had a FLAG in SVs to signal if there are any variant
3373          * chars in the PV.  Given that there isn't such a flag
3374          * make the loop as fast as possible. */
3375         U8 * s = (U8 *) SvPVX_const(sv);
3376         U8 *t = s;
3377
3378         if (is_utf8_invariant_string_loc(s, SvCUR(sv), (const U8 **) &t)) {
3379
3380             /* utf8 conversion not needed because all are invariants.  Mark
3381              * as UTF-8 even if no variant - saves scanning loop */
3382             SvUTF8_on(sv);
3383             if (extra) SvGROW(sv, SvCUR(sv) + extra);
3384             return SvCUR(sv);
3385         }
3386
3387         /* Here, there is at least one variant (t points to the first one), so
3388          * the string should be converted to utf8.  Everything from 's' to
3389          * 't - 1' will occupy only 1 byte each on output.
3390          *
3391          * Note that the incoming SV may not have a trailing '\0', as certain
3392          * code in pp_formline can send us partially built SVs.
3393          *
3394          * There are two main ways to convert.  One is to create a new string
3395          * and go through the input starting from the beginning, appending each
3396          * converted value onto the new string as we go along.  Going this
3397          * route, it's probably best to initially allocate enough space in the
3398          * string rather than possibly running out of space and having to
3399          * reallocate and then copy what we've done so far.  Since everything
3400          * from 's' to 't - 1' is invariant, the destination can be initialized
3401          * with these using a fast memory copy.  To be sure to allocate enough
3402          * space, one could use the worst case scenario, where every remaining
3403          * byte expands to two under UTF-8, or one could parse it and count
3404          * exactly how many do expand.
3405          *
3406          * The other way is to unconditionally parse the remainder of the
3407          * string to figure out exactly how big the expanded string will be,
3408          * growing if needed.  Then start at the end of the string and place
3409          * the character there at the end of the unfilled space in the expanded
3410          * one, working backwards until reaching 't'.
3411          *
3412          * The problem with assuming the worst case scenario is that for very
3413          * long strings, we could allocate much more memory than actually
3414          * needed, which can create performance problems.  If we have to parse
3415          * anyway, the second method is the winner as it may avoid an extra
3416          * copy.  The code used to use the first method under some
3417          * circumstances, but now that there is faster variant counting on
3418          * ASCII platforms, the second method is used exclusively, eliminating
3419          * some code that no longer has to be maintained. */
3420
3421         {
3422             /* Count the total number of variants there are.  We can start
3423              * just beyond the first one, which is known to be at 't' */
3424             const Size_t invariant_length = t - s;
3425             U8 * e = (U8 *) SvEND(sv);
3426
3427             /* The length of the left overs, plus 1. */
3428             const Size_t remaining_length_p1 = e - t;
3429
3430             /* We expand by 1 for the variant at 't' and one for each remaining
3431              * variant (we start looking at 't+1') */
3432             Size_t expansion = 1 + variant_under_utf8_count(t + 1, e);
3433
3434             /* +1 = trailing NUL */
3435             Size_t need = SvCUR(sv) + expansion + extra + 1;
3436             U8 * d;
3437
3438             /* Grow if needed */
3439             if (SvLEN(sv) < need) {
3440                 t = invariant_length + (U8*) SvGROW(sv, need);
3441                 e = t + remaining_length_p1;
3442             }
3443             SvCUR_set(sv, invariant_length + remaining_length_p1 + expansion);
3444
3445             /* Set the NUL at the end */
3446             d = (U8 *) SvEND(sv);
3447             *d-- = '\0';
3448
3449             /* Having decremented d, it points to the position to put the
3450              * very last byte of the expanded string.  Go backwards through
3451              * the string, copying and expanding as we go, stopping when we
3452              * get to the part that is invariant the rest of the way down */
3453
3454             e--;
3455             while (e >= t) {
3456                 if (NATIVE_BYTE_IS_INVARIANT(*e)) {
3457                     *d-- = *e;
3458                 } else {
3459                     *d-- = UTF8_EIGHT_BIT_LO(*e);
3460                     *d-- = UTF8_EIGHT_BIT_HI(*e);
3461                 }
3462                 e--;
3463             }
3464
3465             if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3466                 /* Update pos. We do it at the end rather than during
3467                  * the upgrade, to avoid slowing down the common case
3468                  * (upgrade without pos).
3469                  * pos can be stored as either bytes or characters.  Since
3470                  * this was previously a byte string we can just turn off
3471                  * the bytes flag. */
3472                 MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3473                 if (mg) {
3474                     mg->mg_flags &= ~MGf_BYTES;
3475                 }
3476                 if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3477                     magic_setutf8(sv,mg); /* clear UTF8 cache */
3478             }
3479         }
3480     }
3481
3482     SvUTF8_on(sv);
3483     return SvCUR(sv);
3484 }
3485
3486 /*
3487 =for apidoc sv_utf8_downgrade
3488 =for apidoc_item sv_utf8_downgrade_flags
3489 =for apidoc_item sv_utf8_downgrade_nomg
3490
3491 These attempt to convert the PV of an SV from characters to bytes.  If the PV
3492 contains a character that cannot fit in a byte, this conversion will fail; in
3493 this case, C<FALSE> is returned if C<fail_ok> is true; otherwise they croak.
3494
3495 They are not a general purpose Unicode to byte encoding interface:
3496 use the C<Encode> extension for that.
3497
3498 They differ only in that:
3499
3500 C<sv_utf8_downgrade> processes 'get' magic on C<sv>.
3501
3502 C<sv_utf8_downgrade_nomg> does not.
3503
3504 C<sv_utf8_downgrade_flags> has an additional C<flags> parameter in which you can specify
3505 C<SV_GMAGIC> to process 'get' magic, or leave it cleared to not process 'get' magic.
3506
3507 =cut
3508 */
3509
3510 bool
3511 Perl_sv_utf8_downgrade_flags(pTHX_ SV *const sv, const bool fail_ok, const U32 flags)
3512 {
3513     PERL_ARGS_ASSERT_SV_UTF8_DOWNGRADE_FLAGS;
3514
3515     if (SvPOKp(sv) && SvUTF8(sv)) {
3516         if (SvCUR(sv)) {
3517             U8 *s;
3518             STRLEN len;
3519             U32 mg_flags = flags & SV_GMAGIC;
3520
3521             if (SvIsCOW(sv)) {
3522                 S_sv_uncow(aTHX_ sv, 0);
3523             }
3524             if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3525                 /* update pos */
3526                 MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3527                 if (mg && mg->mg_len > 0 && mg->mg_flags & MGf_BYTES) {
3528                         mg->mg_len = sv_pos_b2u_flags(sv, mg->mg_len,
3529                                                 mg_flags|SV_CONST_RETURN);
3530                         mg_flags = 0; /* sv_pos_b2u does get magic */
3531                 }
3532                 if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3533                     magic_setutf8(sv,mg); /* clear UTF8 cache */
3534
3535             }
3536             s = (U8 *) SvPV_flags(sv, len, mg_flags);
3537
3538             if (!utf8_to_bytes(s, &len)) {
3539                 if (fail_ok)
3540                     return FALSE;
3541                 else {
3542                     if (PL_op)
3543                         Perl_croak(aTHX_ "Wide character in %s",
3544                                    OP_DESC(PL_op));
3545                     else
3546                         Perl_croak(aTHX_ "Wide character");
3547                 }
3548             }
3549             SvCUR_set(sv, len);
3550         }
3551     }
3552     SvUTF8_off(sv);
3553     return TRUE;
3554 }
3555
3556 /*
3557 =for apidoc sv_utf8_encode
3558
3559 Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3560 flag off so that it looks like octets again.
3561
3562 =cut
3563 */
3564
3565 void
3566 Perl_sv_utf8_encode(pTHX_ SV *const sv)
3567 {
3568     PERL_ARGS_ASSERT_SV_UTF8_ENCODE;
3569
3570     if (SvREADONLY(sv)) {
3571         sv_force_normal_flags(sv, 0);
3572     }
3573     (void) sv_utf8_upgrade(sv);
3574     SvUTF8_off(sv);
3575 }
3576
3577 /*
3578 =for apidoc sv_utf8_decode
3579
3580 If the PV of the SV is an octet sequence in Perl's extended UTF-8
3581 and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3582 so that it looks like a character.  If the PV contains only single-byte
3583 characters, the C<SvUTF8> flag stays off.
3584 Scans PV for validity and returns FALSE if the PV is invalid UTF-8.
3585
3586 =cut
3587 */
3588
3589 bool
3590 Perl_sv_utf8_decode(pTHX_ SV *const sv)
3591 {
3592     PERL_ARGS_ASSERT_SV_UTF8_DECODE;
3593
3594     if (SvPOKp(sv)) {
3595         const U8 *start, *c, *first_variant;
3596
3597         /* The octets may have got themselves encoded - get them back as
3598          * bytes
3599          */
3600         if (!sv_utf8_downgrade(sv, TRUE))
3601             return FALSE;
3602
3603         /* it is actually just a matter of turning the utf8 flag on, but
3604          * we want to make sure everything inside is valid utf8 first.
3605          */
3606         c = start = (const U8 *) SvPVX_const(sv);
3607         if (! is_utf8_invariant_string_loc(c, SvCUR(sv), &first_variant)) {
3608             if (!is_utf8_string(first_variant, SvCUR(sv) - (first_variant -c)))
3609                 return FALSE;
3610             SvUTF8_on(sv);
3611         }
3612         if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3613             /* XXX Is this dead code?  XS_utf8_decode calls SvSETMAGIC
3614                    after this, clearing pos.  Does anything on CPAN
3615                    need this? */
3616             /* adjust pos to the start of a UTF8 char sequence */
3617             MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3618             if (mg) {
3619                 I32 pos = mg->mg_len;
3620                 if (pos > 0) {
3621                     for (c = start + pos; c > start; c--) {
3622                         if (UTF8_IS_START(*c))
3623                             break;
3624                     }
3625                     mg->mg_len  = c - start;
3626                 }
3627             }
3628             if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3629                 magic_setutf8(sv,mg); /* clear UTF8 cache */
3630         }
3631     }
3632     return TRUE;
3633 }
3634
3635 /*
3636 =for apidoc sv_setsv
3637 =for apidoc_item sv_setsv_flags
3638 =for apidoc_item sv_setsv_mg
3639 =for apidoc_item sv_setsv_nomg
3640
3641 These copy the contents of the source SV C<ssv> into the destination SV C<dsv>.
3642 C<ssv> may be destroyed if it is mortal, so don't use these functions if
3643 the source SV needs to be reused.
3644 Loosely speaking, they perform a copy-by-value, obliterating any previous
3645 content of the destination.
3646
3647 They differ only in that:
3648
3649 C<sv_setsv> calls 'get' magic on C<ssv>, but skips 'set' magic on C<dsv>.
3650
3651 C<sv_setsv_mg> calls both 'get' magic on C<ssv> and 'set' magic on C<dsv>.
3652
3653 C<sv_setsv_nomg> skips all magic.
3654
3655 C<sv_setsv_flags> has a C<flags> parameter which you can use to specify any
3656 combination of magic handling, and also you can specify C<SV_NOSTEAL> so that
3657 the buffers of temps will not be stolen.
3658
3659 You probably want to instead use one of the assortment of wrappers, such as
3660 C<L</SvSetSV>>, C<L</SvSetSV_nosteal>>, C<L</SvSetMagicSV>> and
3661 C<L</SvSetMagicSV_nosteal>>.
3662
3663 C<sv_setsv_flags> is the primary function for copying scalars, and most other
3664 copy-ish functions and macros use it underneath.
3665
3666 =for apidoc Amnh||SV_NOSTEAL
3667
3668 =cut
3669 */
3670
3671 static void
3672 S_glob_assign_glob(pTHX_ SV *const dsv, SV *const ssv, const int dtype)
3673 {
3674     I32 mro_changes = 0; /* 1 = method, 2 = isa, 3 = recursive isa */
3675     HV *old_stash = NULL;
3676
3677     PERL_ARGS_ASSERT_GLOB_ASSIGN_GLOB;
3678
3679     if (dtype != SVt_PVGV && !isGV_with_GP(dsv)) {
3680         const char * const name = GvNAME(ssv);
3681         const STRLEN len = GvNAMELEN(ssv);
3682         {
3683             if (dtype >= SVt_PV) {
3684                 SvPV_free(dsv);
3685                 SvPV_set(dsv, 0);
3686                 SvLEN_set(dsv, 0);
3687                 SvCUR_set(dsv, 0);
3688             }
3689             SvUPGRADE(dsv, SVt_PVGV);
3690             (void)SvOK_off(dsv);
3691             isGV_with_GP_on(dsv);
3692         }
3693         GvSTASH(dsv) = GvSTASH(ssv);
3694         if (GvSTASH(dsv))
3695             Perl_sv_add_backref(aTHX_ MUTABLE_SV(GvSTASH(dsv)), dsv);
3696         gv_name_set(MUTABLE_GV(dsv), name, len,
3697                         GV_ADD | (GvNAMEUTF8(ssv) ? SVf_UTF8 : 0 ));
3698         SvFAKE_on(dsv); /* can coerce to non-glob */
3699     }
3700
3701     if(GvGP(MUTABLE_GV(ssv))) {
3702         /* If source has method cache entry, clear it */
3703         if(GvCVGEN(ssv)) {
3704             SvREFCNT_dec(GvCV(ssv));
3705             GvCV_set(ssv, NULL);
3706             GvCVGEN(ssv) = 0;
3707         }
3708         /* If source has a real method, then a method is
3709            going to change */
3710         else if(
3711          GvCV((const GV *)ssv) && GvSTASH(dsv) && HvENAME(GvSTASH(dsv))
3712         ) {
3713             mro_changes = 1;
3714         }
3715     }
3716
3717     /* If dest already had a real method, that's a change as well */
3718     if(
3719         !mro_changes && GvGP(MUTABLE_GV(dsv)) && GvCVu((const GV *)dsv)
3720      && GvSTASH(dsv) && HvENAME(GvSTASH(dsv))
3721     ) {
3722         mro_changes = 1;
3723     }
3724
3725     /* We don't need to check the name of the destination if it was not a
3726        glob to begin with. */
3727     if(dtype == SVt_PVGV) {
3728         const char * const name = GvNAME((const GV *)dsv);
3729         const STRLEN len = GvNAMELEN(dsv);
3730         if(memEQs(name, len, "ISA")
3731          /* The stash may have been detached from the symbol table, so
3732             check its name. */
3733          && GvSTASH(dsv) && HvENAME(GvSTASH(dsv))
3734         )
3735             mro_changes = 2;
3736         else {
3737             if ((len > 1 && name[len-2] == ':' && name[len-1] == ':')
3738              || (len == 1 && name[0] == ':')) {
3739                 mro_changes = 3;
3740
3741                 /* Set aside the old stash, so we can reset isa caches on
3742                    its subclasses. */
3743                 if((old_stash = GvHV(dsv)))
3744                     /* Make sure we do not lose it early. */
3745                     SvREFCNT_inc_simple_void_NN(
3746                      sv_2mortal((SV *)old_stash)
3747                     );
3748             }
3749         }
3750
3751         SvREFCNT_inc_simple_void_NN(sv_2mortal(dsv));
3752     }
3753
3754     /* freeing dsv's GP might free ssv (e.g. *x = $x),
3755      * so temporarily protect it */
3756     ENTER;
3757     SAVEFREESV(SvREFCNT_inc_simple_NN(ssv));
3758     gp_free(MUTABLE_GV(dsv));
3759     GvINTRO_off(dsv);           /* one-shot flag */
3760     GvGP_set(dsv, gp_ref(GvGP(ssv)));
3761     LEAVE;
3762
3763     if (SvTAINTED(ssv))
3764         SvTAINT(dsv);
3765     if (GvIMPORTED(dsv) != GVf_IMPORTED
3766         && CopSTASH_ne(PL_curcop, GvSTASH(dsv)))
3767         {
3768             GvIMPORTED_on(dsv);
3769         }
3770     GvMULTI_on(dsv);
3771     if(mro_changes == 2) {
3772       if (GvAV((const GV *)ssv)) {
3773         MAGIC *mg;
3774         SV * const sref = (SV *)GvAV((const GV *)dsv);
3775         if (SvSMAGICAL(sref) && (mg = mg_find(sref, PERL_MAGIC_isa))) {
3776             if (SvTYPE(mg->mg_obj) != SVt_PVAV) {
3777                 AV * const ary = newAV_alloc_x(2);
3778                 av_push_simple(ary, mg->mg_obj); /* takes the refcount */
3779                 av_push_simple(ary, SvREFCNT_inc_simple_NN(dsv));
3780                 mg->mg_obj = (SV *)ary;
3781             } else {
3782                 av_push((AV *)mg->mg_obj, SvREFCNT_inc_simple_NN(dsv));
3783             }
3784         }
3785         else sv_magic(sref, dsv, PERL_MAGIC_isa, NULL, 0);
3786       }
3787       mro_isa_changed_in(GvSTASH(dsv));
3788     }
3789     else if(mro_changes == 3) {
3790         HV * const stash = GvHV(dsv);
3791         if(old_stash ? (HV *)HvENAME_get(old_stash) : stash)
3792             mro_package_moved(
3793                 stash, old_stash,
3794                 (GV *)dsv, 0
3795             );
3796     }
3797     else if(mro_changes) mro_method_changed_in(GvSTASH(dsv));
3798     if (GvIO(dsv) && dtype == SVt_PVGV) {
3799         DEBUG_o(Perl_deb(aTHX_
3800                         "glob_assign_glob clearing PL_stashcache\n"));
3801         /* It's a cache. It will rebuild itself quite happily.
3802            It's a lot of effort to work out exactly which key (or keys)
3803            might be invalidated by the creation of the this file handle.
3804          */
3805         hv_clear(PL_stashcache);
3806     }
3807     return;
3808 }
3809
3810 void
3811 Perl_gv_setref(pTHX_ SV *const dsv, SV *const ssv)
3812 {
3813     SV * const sref = SvRV(ssv);
3814     SV *dref;
3815     const int intro = GvINTRO(dsv);
3816     SV **location;
3817     U8 import_flag = 0;
3818     const U32 stype = SvTYPE(sref);
3819
3820     PERL_ARGS_ASSERT_GV_SETREF;
3821
3822     if (intro) {
3823         GvINTRO_off(dsv);       /* one-shot flag */
3824         GvLINE(dsv) = CopLINE(PL_curcop);
3825         GvEGV(dsv) = MUTABLE_GV(dsv);
3826     }
3827     GvMULTI_on(dsv);
3828     switch (stype) {
3829     case SVt_PVCV:
3830         location = (SV **) &(GvGP(dsv)->gp_cv); /* XXX bypassing GvCV_set */
3831         import_flag = GVf_IMPORTED_CV;
3832         goto common;
3833     case SVt_PVHV:
3834         location = (SV **) &GvHV(dsv);
3835         import_flag = GVf_IMPORTED_HV;
3836         goto common;
3837     case SVt_PVAV:
3838         location = (SV **) &GvAV(dsv);
3839         import_flag = GVf_IMPORTED_AV;
3840         goto common;
3841     case SVt_PVIO:
3842         location = (SV **) &GvIOp(dsv);
3843         goto common;
3844     case SVt_PVFM:
3845         location = (SV **) &GvFORM(dsv);
3846         goto common;
3847     default:
3848         location = &GvSV(dsv);
3849         import_flag = GVf_IMPORTED_SV;
3850     common:
3851         if (intro) {
3852             if (stype == SVt_PVCV) {
3853                 /*if (GvCVGEN(dsv) && (GvCV(dsv) != (const CV *)sref || GvCVGEN(dsv))) {*/
3854                 if (GvCVGEN(dsv)) {
3855                     SvREFCNT_dec(GvCV(dsv));
3856                     GvCV_set(dsv, NULL);
3857                     GvCVGEN(dsv) = 0; /* Switch off cacheness. */
3858                 }
3859             }
3860             /* SAVEt_GVSLOT takes more room on the savestack and has more
3861                overhead in leave_scope than SAVEt_GENERIC_SV.  But for CVs
3862                leave_scope needs access to the GV so it can reset method
3863                caches.  We must use SAVEt_GVSLOT whenever the type is
3864                SVt_PVCV, even if the stash is anonymous, as the stash may
3865                gain a name somehow before leave_scope. */
3866             if (stype == SVt_PVCV) {
3867                 /* There is no save_pushptrptrptr.  Creating it for this
3868                    one call site would be overkill.  So inline the ss add
3869                    routines here. */
3870                 dSS_ADD;
3871                 SS_ADD_PTR(dsv);
3872                 SS_ADD_PTR(location);
3873                 SS_ADD_PTR(SvREFCNT_inc(*location));
3874                 SS_ADD_UV(SAVEt_GVSLOT);
3875                 SS_ADD_END(4);
3876             }
3877             else SAVEGENERICSV(*location);
3878         }
3879         dref = *location;
3880         if (stype == SVt_PVCV && (*location != sref || GvCVGEN(dsv))) {
3881             CV* const cv = MUTABLE_CV(*location);
3882             if (cv) {
3883                 if (!GvCVGEN((const GV *)dsv) &&
3884                     (CvROOT(cv) || CvXSUB(cv)) &&
3885                     /* redundant check that avoids creating the extra SV
3886                        most of the time: */
3887                     (CvCONST(cv) || (ckWARN(WARN_REDEFINE) && !intro)))
3888                     {
3889                         SV * const new_const_sv =
3890                             CvCONST((const CV *)sref)
3891                                  ? cv_const_sv((const CV *)sref)
3892                                  : NULL;
3893                         HV * const stash = GvSTASH((const GV *)dsv);
3894                         report_redefined_cv(
3895                            sv_2mortal(
3896                              stash
3897                                ? Perl_newSVpvf(aTHX_
3898                                     "%" HEKf "::%" HEKf,
3899                                     HEKfARG(HvNAME_HEK(stash)),
3900                                     HEKfARG(GvENAME_HEK(MUTABLE_GV(dsv))))
3901                                : Perl_newSVpvf(aTHX_
3902                                     "%" HEKf,
3903                                     HEKfARG(GvENAME_HEK(MUTABLE_GV(dsv))))
3904                            ),
3905                            cv,
3906                            CvCONST((const CV *)sref) ? &new_const_sv : NULL
3907                         );
3908                     }
3909                 if (!intro)
3910                     cv_ckproto_len_flags(cv, (const GV *)dsv,
3911                                    SvPOK(sref) ? CvPROTO(sref) : NULL,
3912                                    SvPOK(sref) ? CvPROTOLEN(sref) : 0,
3913                                    SvPOK(sref) ? SvUTF8(sref) : 0);
3914             }
3915             GvCVGEN(dsv) = 0; /* Switch off cacheness. */
3916             GvASSUMECV_on(dsv);
3917             if(GvSTASH(dsv)) { /* sub foo { 1 } sub bar { 2 } *bar = \&foo */
3918                 if (intro && GvREFCNT(dsv) > 1) {
3919                     /* temporary remove extra savestack's ref */
3920                     --GvREFCNT(dsv);
3921                     gv_method_changed(dsv);
3922                     ++GvREFCNT(dsv);
3923                 }
3924                 else gv_method_changed(dsv);
3925             }
3926         }
3927         *location = SvREFCNT_inc_simple_NN(sref);
3928         if (import_flag && !(GvFLAGS(dsv) & import_flag)
3929             && CopSTASH_ne(PL_curcop, GvSTASH(dsv))) {
3930             GvFLAGS(dsv) |= import_flag;
3931         }
3932
3933         if (stype == SVt_PVHV) {
3934             const char * const name = GvNAME((GV*)dsv);
3935             const STRLEN len = GvNAMELEN(dsv);
3936             if (
3937                 (
3938                    (len > 1 && name[len-2] == ':' && name[len-1] == ':')
3939                 || (len == 1 && name[0] == ':')
3940                 )
3941              && (!dref || HvENAME_get(dref))
3942             ) {
3943                 mro_package_moved(
3944                     (HV *)sref, (HV *)dref,
3945                     (GV *)dsv, 0
3946                 );
3947             }
3948         }
3949         else if (
3950             stype == SVt_PVAV && sref != dref
3951          && memEQs(GvNAME((GV*)dsv), GvNAMELEN((GV*)dsv), "ISA")
3952          /* The stash may have been detached from the symbol table, so
3953             check its name before doing anything. */
3954          && GvSTASH(dsv) && HvENAME(GvSTASH(dsv))
3955         ) {
3956             MAGIC *mg;
3957             MAGIC * const omg = dref && SvSMAGICAL(dref)
3958                                  ? mg_find(dref, PERL_MAGIC_isa)
3959                                  : NULL;
3960             if (SvSMAGICAL(sref) && (mg = mg_find(sref, PERL_MAGIC_isa))) {
3961                 if (SvTYPE(mg->mg_obj) != SVt_PVAV) {
3962                     AV * const ary = newAV_alloc_xz(4);
3963                     av_push_simple(ary, mg->mg_obj); /* takes the refcount */
3964                     mg->mg_obj = (SV *)ary;
3965                 }
3966                 if (omg) {
3967                     if (SvTYPE(omg->mg_obj) == SVt_PVAV) {
3968                         SV **svp = AvARRAY((AV *)omg->mg_obj);
3969                         I32 items = AvFILLp((AV *)omg->mg_obj) + 1;
3970                         while (items--)
3971                             av_push(
3972                              (AV *)mg->mg_obj,
3973                              SvREFCNT_inc_simple_NN(*svp++)
3974                             );
3975                     }
3976                     else
3977                         av_push(
3978                          (AV *)mg->mg_obj,
3979                          SvREFCNT_inc_simple_NN(omg->mg_obj)
3980                         );
3981                 }
3982                 else
3983                     av_push((AV *)mg->mg_obj,SvREFCNT_inc_simple_NN(dsv));
3984             }
3985             else
3986             {
3987                 SSize_t i;
3988                 sv_magic(
3989                  sref, omg ? omg->mg_obj : dsv, PERL_MAGIC_isa, NULL, 0
3990                 );
3991                 for (i = 0; i <= AvFILL(sref); ++i) {
3992                     SV **elem = av_fetch ((AV*)sref, i, 0);
3993                     if (elem) {
3994                         sv_magic(
3995                           *elem, sref, PERL_MAGIC_isaelem, NULL, i
3996                         );
3997                     }
3998                 }
3999                 mg = mg_find(sref, PERL_MAGIC_isa);
4000             }
4001             /* Since the *ISA assignment could have affected more than
4002                one stash, don't call mro_isa_changed_in directly, but let
4003                magic_clearisa do it for us, as it already has the logic for
4004                dealing with globs vs arrays of globs. */
4005             assert(mg);
4006             Perl_magic_clearisa(aTHX_ NULL, mg);
4007         }
4008         else if (stype == SVt_PVIO) {
4009             DEBUG_o(Perl_deb(aTHX_ "gv_setref clearing PL_stashcache\n"));
4010             /* It's a cache. It will rebuild itself quite happily.
4011                It's a lot of effort to work out exactly which key (or keys)
4012                might be invalidated by the creation of the this file handle.
4013             */
4014             hv_clear(PL_stashcache);
4015         }
4016         break;
4017     }
4018     if (!intro) SvREFCNT_dec(dref);
4019     if (SvTAINTED(ssv))
4020         SvTAINT(dsv);
4021     return;
4022 }
4023
4024
4025
4026
4027 #ifdef PERL_DEBUG_READONLY_COW
4028 # include <sys/mman.h>
4029
4030 # ifndef PERL_MEMORY_DEBUG_HEADER_SIZE
4031 #  define PERL_MEMORY_DEBUG_HEADER_SIZE 0
4032 # endif
4033
4034 void
4035 Perl_sv_buf_to_ro(pTHX_ SV *sv)
4036 {
4037     struct perl_memory_debug_header * const header =
4038         (struct perl_memory_debug_header *)(SvPVX(sv)-PERL_MEMORY_DEBUG_HEADER_SIZE);
4039     const MEM_SIZE len = header->size;
4040     PERL_ARGS_ASSERT_SV_BUF_TO_RO;
4041 # ifdef PERL_TRACK_MEMPOOL
4042     if (!header->readonly) header->readonly = 1;
4043 # endif
4044     if (mprotect(header, len, PROT_READ))
4045         Perl_warn(aTHX_ "mprotect RW for COW string %p %lu failed with %d",
4046                          header, len, errno);
4047 }
4048
4049 static void
4050 S_sv_buf_to_rw(pTHX_ SV *sv)
4051 {
4052     struct perl_memory_debug_header * const header =
4053         (struct perl_memory_debug_header *)(SvPVX(sv)-PERL_MEMORY_DEBUG_HEADER_SIZE);
4054     const MEM_SIZE len = header->size;
4055     PERL_ARGS_ASSERT_SV_BUF_TO_RW;
4056     if (mprotect(header, len, PROT_READ|PROT_WRITE))
4057         Perl_warn(aTHX_ "mprotect for COW string %p %lu failed with %d",
4058                          header, len, errno);
4059 # ifdef PERL_TRACK_MEMPOOL
4060     header->readonly = 0;
4061 # endif
4062 }
4063
4064 #else
4065 # define sv_buf_to_ro(sv)       NOOP
4066 # define sv_buf_to_rw(sv)       NOOP
4067 #endif
4068
4069 void
4070 Perl_sv_setsv_flags(pTHX_ SV *dsv, SV* ssv, const I32 flags)
4071 {
4072     U32 sflags;
4073     int dtype;
4074     svtype stype;
4075     unsigned int both_type;
4076
4077     PERL_ARGS_ASSERT_SV_SETSV_FLAGS;
4078
4079     if (UNLIKELY( ssv == dsv ))
4080         return;
4081
4082     if (UNLIKELY( !ssv ))
4083         ssv = &PL_sv_undef;
4084
4085     stype = SvTYPE(ssv);
4086     dtype = SvTYPE(dsv);
4087     both_type = (stype | dtype);
4088
4089     /* with these values, we can check that both SVs are NULL/IV (and not
4090      * freed) just by testing the or'ed types */
4091     STATIC_ASSERT_STMT(SVt_NULL == 0);
4092     STATIC_ASSERT_STMT(SVt_IV   == 1);
4093     if (both_type <= 1) {
4094         /* both src and dst are UNDEF/IV/RV, so we can do a lot of
4095          * special-casing */
4096         U32 sflags;
4097         U32 new_dflags;
4098         SV *old_rv = NULL;
4099
4100         /* minimal subset of SV_CHECK_THINKFIRST_COW_DROP(dsv) */
4101         if (SvREADONLY(dsv))
4102             Perl_croak_no_modify();
4103         if (SvROK(dsv)) {
4104             if (SvWEAKREF(dsv))
4105                 sv_unref_flags(dsv, 0);
4106             else
4107                 old_rv = SvRV(dsv);
4108         }
4109
4110         assert(!SvGMAGICAL(ssv));
4111         assert(!SvGMAGICAL(dsv));
4112
4113         sflags = SvFLAGS(ssv);
4114         if (sflags & (SVf_IOK|SVf_ROK)) {
4115             SET_SVANY_FOR_BODYLESS_IV(dsv);
4116             new_dflags = SVt_IV;
4117
4118             if (sflags & SVf_ROK) {
4119                 dsv->sv_u.svu_rv = SvREFCNT_inc(SvRV(ssv));
4120                 new_dflags |= SVf_ROK;
4121             }
4122             else {
4123                 /* both src and dst are <= SVt_IV, so sv_any points to the
4124                  * head; so access the head directly
4125                  */
4126                 assert(    &(ssv->sv_u.svu_iv)
4127                         == &(((XPVIV*) SvANY(ssv))->xiv_iv));
4128                 assert(    &(dsv->sv_u.svu_iv)
4129                         == &(((XPVIV*) SvANY(dsv))->xiv_iv));
4130                 dsv->sv_u.svu_iv = ssv->sv_u.svu_iv;
4131                 new_dflags |= (SVf_IOK|SVp_IOK|(sflags & SVf_IVisUV));
4132             }
4133         }
4134         else {
4135             new_dflags = dtype; /* turn off everything except the type */
4136         }
4137         SvFLAGS(dsv) = new_dflags;
4138         SvREFCNT_dec(old_rv);
4139
4140         return;
4141     }
4142
4143     if (UNLIKELY(both_type == SVTYPEMASK)) {
4144         if (SvIS_FREED(dsv)) {
4145             Perl_croak(aTHX_ "panic: attempt to copy value %" SVf
4146                        " to a freed scalar %p", SVfARG(ssv), (void *)dsv);
4147         }
4148         if (SvIS_FREED(ssv)) {
4149             Perl_croak(aTHX_ "panic: attempt to copy freed scalar %p to %p",
4150                        (void*)ssv, (void*)dsv);
4151         }
4152     }
4153
4154
4155
4156     SV_CHECK_THINKFIRST_COW_DROP(dsv);
4157     dtype = SvTYPE(dsv); /* THINKFIRST may have changed type */
4158
4159     /* There's a lot of redundancy below but we're going for speed here
4160      * Note: some of the cases below do return; rather than break; so the
4161      * if-elseif-else logic below this switch does not see all cases. */
4162
4163     switch (stype) {
4164     case SVt_NULL:
4165       undef_sstr:
4166         if (LIKELY( dtype != SVt_PVGV && dtype != SVt_PVLV )) {
4167             (void)SvOK_off(dsv);
4168             return;
4169         }
4170         break;
4171     case SVt_IV:
4172         if (SvIOK(ssv)) {
4173             switch (dtype) {
4174             case SVt_NULL:
4175                 /* For performance, we inline promoting to type SVt_IV. */
4176                 /* We're starting from SVt_NULL, so provided that define is
4177                  * actual 0, we don't have to unset any SV type flags
4178                  * to promote to SVt_IV. */
4179                 STATIC_ASSERT_STMT(SVt_NULL == 0);
4180                 SET_SVANY_FOR_BODYLESS_IV(dsv);
4181                 SvFLAGS(dsv) |= SVt_IV;
4182                 break;
4183             case SVt_NV:
4184             case SVt_PV:
4185                 sv_upgrade(dsv, SVt_PVIV);
4186                 break;
4187             case SVt_PVGV:
4188             case SVt_PVLV:
4189                 goto end_of_first_switch;
4190             }
4191             (void)SvIOK_only(dsv);
4192             SvIV_set(dsv,  SvIVX(ssv));
4193             if (SvIsUV(ssv))
4194                 SvIsUV_on(dsv);
4195             /* SvTAINTED can only be true if the SV has taint magic, which in
4196                turn means that the SV type is PVMG (or greater). This is the
4197                case statement for SVt_IV, so this cannot be true (whatever gcov
4198                may say).  */
4199             assert(!SvTAINTED(ssv));
4200             return;
4201         }
4202         if (!SvROK(ssv))
4203             goto undef_sstr;
4204         if (dtype < SVt_PV && dtype != SVt_IV)
4205             sv_upgrade(dsv, SVt_IV);
4206         break;
4207
4208     case SVt_NV:
4209         if (LIKELY( SvNOK(ssv) )) {
4210             switch (dtype) {
4211             case SVt_NULL:
4212             case SVt_IV:
4213                 sv_upgrade(dsv, SVt_NV);
4214                 break;
4215             case SVt_PV:
4216             case SVt_PVIV:
4217                 sv_upgrade(dsv, SVt_PVNV);
4218                 break;
4219             case SVt_PVGV:
4220             case SVt_PVLV:
4221                 goto end_of_first_switch;
4222             }
4223             SvNV_set(dsv, SvNVX(ssv));
4224             (void)SvNOK_only(dsv);
4225             /* SvTAINTED can only be true if the SV has taint magic, which in
4226                turn means that the SV type is PVMG (or greater). This is the
4227                case statement for SVt_NV, so this cannot be true (whatever gcov
4228                may say).  */
4229             assert(!SvTAINTED(ssv));
4230             return;
4231         }
4232         goto undef_sstr;
4233
4234     case SVt_PV:
4235         if (dtype < SVt_PV)
4236             sv_upgrade(dsv, SVt_PV);
4237         break;
4238     case SVt_PVIV:
4239         if (dtype < SVt_PVIV)
4240             sv_upgrade(dsv, SVt_PVIV);
4241         break;
4242     case SVt_PVNV:
4243         if (dtype < SVt_PVNV)
4244             sv_upgrade(dsv, SVt_PVNV);
4245         break;
4246
4247     case SVt_INVLIST:
4248         invlist_clone(ssv, dsv);
4249         return;
4250     default:
4251         {
4252         const char * const type = sv_reftype(ssv,0);
4253         if (PL_op)
4254             /* diag_listed_as: Bizarre copy of %s */
4255             Perl_croak(aTHX_ "Bizarre copy of %s in %s", type, OP_DESC(PL_op));
4256         else
4257             Perl_croak(aTHX_ "Bizarre copy of %s", type);
4258         }
4259         NOT_REACHED; /* NOTREACHED */
4260
4261     case SVt_REGEXP:
4262       upgregexp:
4263         if (dtype < SVt_REGEXP)
4264             sv_upgrade(dsv, SVt_REGEXP);
4265         break;
4266
4267     case SVt_PVLV:
4268     case SVt_PVGV:
4269     case SVt_PVMG:
4270         if (SvGMAGICAL(ssv) && (flags & SV_GMAGIC)) {
4271             mg_get(ssv);
4272             if (SvTYPE(ssv) != stype)
4273                 stype = SvTYPE(ssv);
4274         }
4275         if (isGV_with_GP(ssv) && dtype <= SVt_PVLV) {
4276                     glob_assign_glob(dsv, ssv, dtype);
4277                     return;
4278         }
4279         if (stype == SVt_PVLV)
4280         {
4281             if (isREGEXP(ssv)) goto upgregexp;
4282             SvUPGRADE(dsv, SVt_PVNV);
4283         }
4284         else
4285             SvUPGRADE(dsv, (svtype)stype);
4286     }
4287  end_of_first_switch:
4288
4289     /* dsv may have been upgraded.  */
4290     dtype = SvTYPE(dsv);
4291     sflags = SvFLAGS(ssv);
4292
4293     if (UNLIKELY( dtype == SVt_PVCV )) {
4294         /* Assigning to a subroutine sets the prototype.  */
4295         if (SvOK(ssv)) {
4296             STRLEN len;
4297             const char *const ptr = SvPV_const(ssv, len);
4298
4299             SvGROW(dsv, len + 1);
4300             Copy(ptr, SvPVX(dsv), len + 1, char);
4301             SvCUR_set(dsv, len);
4302             SvPOK_only(dsv);
4303             SvFLAGS(dsv) |= sflags & SVf_UTF8;
4304             CvAUTOLOAD_off(dsv);
4305         } else {
4306             SvOK_off(dsv);
4307         }
4308     }
4309     else if (UNLIKELY(dtype == SVt_PVAV || dtype == SVt_PVHV
4310              || dtype == SVt_PVFM))
4311     {
4312         const char * const type = sv_reftype(dsv,0);
4313         if (PL_op)
4314             /* diag_listed_as: Cannot copy to %s */
4315             Perl_croak(aTHX_ "Cannot copy to %s in %s", type, OP_DESC(PL_op));
4316         else
4317             Perl_croak(aTHX_ "Cannot copy to %s", type);
4318     } else if (sflags & SVf_ROK) {
4319         if (isGV_with_GP(dsv)
4320             && SvTYPE(SvRV(ssv)) == SVt_PVGV && isGV_with_GP(SvRV(ssv))) {
4321             ssv = SvRV(ssv);
4322             if (ssv == dsv) {
4323                 if (GvIMPORTED(dsv) != GVf_IMPORTED
4324                     && CopSTASH_ne(PL_curcop, GvSTASH(dsv)))
4325                 {
4326                     GvIMPORTED_on(dsv);
4327                 }
4328                 GvMULTI_on(dsv);
4329                 return;
4330             }
4331             glob_assign_glob(dsv, ssv, dtype);
4332             return;
4333         }
4334
4335         if (dtype >= SVt_PV) {
4336             if (isGV_with_GP(dsv)) {
4337                 gv_setref(dsv, ssv);
4338                 return;
4339             }
4340             if (SvPVX_const(dsv)) {
4341                 SvPV_free(dsv);
4342                 SvLEN_set(dsv, 0);
4343                 SvCUR_set(dsv, 0);
4344             }
4345         }
4346         (void)SvOK_off(dsv);
4347         SvRV_set(dsv, SvREFCNT_inc(SvRV(ssv)));
4348         SvFLAGS(dsv) |= sflags & SVf_ROK;
4349         assert(!(sflags & SVp_NOK));
4350         assert(!(sflags & SVp_IOK));
4351         assert(!(sflags & SVf_NOK));
4352         assert(!(sflags & SVf_IOK));
4353     }
4354     else if (isGV_with_GP(dsv)) {
4355         if (!(sflags & SVf_OK)) {
4356             Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4357                            "Undefined value assigned to typeglob");
4358         }
4359         else {
4360             GV *gv = gv_fetchsv_nomg(ssv, GV_ADD, SVt_PVGV);
4361             if (dsv != (const SV *)gv) {
4362                 const char * const name = GvNAME((const GV *)dsv);
4363                 const STRLEN len = GvNAMELEN(dsv);
4364                 HV *old_stash = NULL;
4365                 bool reset_isa = FALSE;
4366                 if ((len > 1 && name[len-2] == ':' && name[len-1] == ':')
4367                  || (len == 1 && name[0] == ':')) {
4368                     /* Set aside the old stash, so we can reset isa caches
4369                        on its subclasses. */
4370                     if((old_stash = GvHV(dsv))) {
4371                         /* Make sure we do not lose it early. */
4372                         SvREFCNT_inc_simple_void_NN(
4373                          sv_2mortal((SV *)old_stash)
4374                         );
4375                     }
4376                     reset_isa = TRUE;
4377                 }
4378
4379                 if (GvGP(dsv)) {
4380                     SvREFCNT_inc_simple_void_NN(sv_2mortal(dsv));
4381                     gp_free(MUTABLE_GV(dsv));
4382                 }
4383                 GvGP_set(dsv, gp_ref(GvGP(gv)));
4384
4385                 if (reset_isa) {
4386                     HV * const stash = GvHV(dsv);
4387                     if(
4388                         old_stash ? (HV *)HvENAME_get(old_stash) : stash
4389                     )
4390                         mro_package_moved(
4391                          stash, old_stash,
4392                          (GV *)dsv, 0
4393                         );
4394                 }
4395             }
4396         }
4397     }
4398     else if ((dtype == SVt_REGEXP || dtype == SVt_PVLV)
4399           && (stype == SVt_REGEXP || isREGEXP(ssv))) {
4400         reg_temp_copy((REGEXP*)dsv, (REGEXP*)ssv);
4401     }
4402     else if (sflags & SVp_POK) {
4403         const STRLEN cur = SvCUR(ssv);
4404         const STRLEN len = SvLEN(ssv);
4405
4406         /*
4407          * We have three basic ways to copy the string:
4408          *
4409          *  1. Swipe
4410          *  2. Copy-on-write
4411          *  3. Actual copy
4412          *
4413          * Which we choose is based on various factors.  The following
4414          * things are listed in order of speed, fastest to slowest:
4415          *  - Swipe
4416          *  - Copying a short string
4417          *  - Copy-on-write bookkeeping
4418          *  - malloc
4419          *  - Copying a long string
4420          *
4421          * We swipe the string (steal the string buffer) if the SV on the
4422          * rhs is about to be freed anyway (TEMP and refcnt==1).  This is a
4423          * big win on long strings.  It should be a win on short strings if
4424          * SvPVX_const(dsv) has to be allocated.  If not, it should not
4425          * slow things down, as SvPVX_const(ssv) would have been freed
4426          * soon anyway.
4427          *
4428          * We also steal the buffer from a PADTMP (operator target) if it
4429          * is â€˜long enough’.  For short strings, a swipe does not help
4430          * here, as it causes more malloc calls the next time the target
4431          * is used.  Benchmarks show that even if SvPVX_const(dsv) has to
4432          * be allocated it is still not worth swiping PADTMPs for short
4433          * strings, as the savings here are small.
4434          *
4435          * If swiping is not an option, then we see whether it is worth using
4436          * copy-on-write.  If the lhs already has a buffer big enough and the
4437          * string is short, we skip it and fall back to method 3, since memcpy
4438          * is faster for short strings than the later bookkeeping overhead that
4439          * copy-on-write entails.
4440
4441          * If the rhs is not a copy-on-write string yet, then we also
4442          * consider whether the buffer is too large relative to the string
4443          * it holds.  Some operations such as readline allocate a large
4444          * buffer in the expectation of reusing it.  But turning such into
4445          * a COW buffer is counter-productive because it increases memory
4446          * usage by making readline allocate a new large buffer the sec-
4447          * ond time round.  So, if the buffer is too large, again, we use
4448          * method 3 (copy).
4449          *
4450          * Finally, if there is no buffer on the left, or the buffer is too
4451          * small, then we use copy-on-write and make both SVs share the
4452          * string buffer.
4453          *
4454          */
4455
4456         /* Whichever path we take through the next code, we want this true,
4457            and doing it now facilitates the COW check.  */
4458         (void)SvPOK_only(dsv);
4459
4460         if (
4461                  (              /* Either ... */
4462                                 /* slated for free anyway (and not COW)? */
4463                     (sflags & (SVs_TEMP|SVf_IsCOW)) == SVs_TEMP
4464                                 /* or a swipable TARG */
4465                  || ((sflags &
4466                            (SVs_PADTMP|SVf_READONLY|SVf_PROTECT|SVf_IsCOW))
4467                        == SVs_PADTMP
4468                                 /* whose buffer is worth stealing */
4469                      && CHECK_COWBUF_THRESHOLD(cur,len)
4470                     )
4471                  ) &&
4472                  !(sflags & SVf_OOK) &&   /* and not involved in OOK hack? */
4473                  (!(flags & SV_NOSTEAL)) &&
4474                                         /* and we're allowed to steal temps */
4475                  SvREFCNT(ssv) == 1 &&   /* and no other references to it? */
4476                  len)             /* and really is a string */
4477         {       /* Passes the swipe test.  */
4478             if (SvPVX_const(dsv))       /* we know that dtype >= SVt_PV */
4479                 SvPV_free(dsv);
4480             SvPV_set(dsv, SvPVX_mutable(ssv));
4481             SvLEN_set(dsv, SvLEN(ssv));
4482             SvCUR_set(dsv, SvCUR(ssv));
4483
4484             SvTEMP_off(dsv);
4485             (void)SvOK_off(ssv);        /* NOTE: nukes most SvFLAGS on ssv */
4486             SvPV_set(ssv, NULL);
4487             SvLEN_set(ssv, 0);
4488             SvCUR_set(ssv, 0);
4489             SvTEMP_off(ssv);
4490         }
4491         /* We must check for SvIsCOW_static() even without
4492          * SV_COW_SHARED_HASH_KEYS being set or else we'll break SvIsBOOL()
4493          */
4494         else if (SvIsCOW_static(ssv)) {
4495             if (SvPVX_const(dsv)) {     /* we know that dtype >= SVt_PV */
4496                 SvPV_free(dsv);
4497             }
4498             SvPV_set(dsv, SvPVX(ssv));
4499             SvLEN_set(dsv, 0);
4500             SvCUR_set(dsv, cur);
4501             SvFLAGS(dsv) |= (SVf_IsCOW|SVppv_STATIC);
4502         }
4503         else if (flags & SV_COW_SHARED_HASH_KEYS
4504               &&
4505 #ifdef PERL_COPY_ON_WRITE
4506                  (sflags & SVf_IsCOW
4507                    ? (!len ||
4508                        (  (CHECK_COWBUF_THRESHOLD(cur,len) || SvLEN(dsv) < cur+1)
4509                           /* If this is a regular (non-hek) COW, only so
4510                              many COW "copies" are possible. */
4511                        && CowREFCNT(ssv) != SV_COW_REFCNT_MAX  ))
4512                    : (  (sflags & CAN_COW_MASK) == CAN_COW_FLAGS
4513                      && !(SvFLAGS(dsv) & SVf_BREAK)
4514                      && CHECK_COW_THRESHOLD(cur,len) && cur+1 < len
4515                      && (CHECK_COWBUF_THRESHOLD(cur,len) || SvLEN(dsv) < cur+1)
4516                     ))
4517 #else
4518                  sflags & SVf_IsCOW
4519               && !(SvFLAGS(dsv) & SVf_BREAK)
4520 #endif
4521             ) {
4522             /* Either it's a shared hash key, or it's suitable for
4523                copy-on-write.  */
4524 #ifdef DEBUGGING
4525             if (DEBUG_C_TEST) {
4526                 PerlIO_printf(Perl_debug_log, "Copy on write: ssv --> dsv\n");
4527                 sv_dump(ssv);
4528                 sv_dump(dsv);
4529             }
4530 #endif
4531 #ifdef PERL_ANY_COW
4532             if (!(sflags & SVf_IsCOW)) {
4533                     SvIsCOW_on(ssv);
4534                     CowREFCNT(ssv) = 0;
4535             }
4536 #endif
4537             if (SvPVX_const(dsv)) {     /* we know that dtype >= SVt_PV */
4538                 SvPV_free(dsv);
4539             }
4540
4541 #ifdef PERL_ANY_COW
4542             if (len) {
4543                     if (sflags & SVf_IsCOW) {
4544                         sv_buf_to_rw(ssv);
4545                     }
4546                     CowREFCNT(ssv)++;
4547                     SvPV_set(dsv, SvPVX_mutable(ssv));
4548                     sv_buf_to_ro(ssv);
4549             } else
4550 #endif
4551             {
4552                     /* SvIsCOW_shared_hash */
4553                     DEBUG_C(PerlIO_printf(Perl_debug_log,
4554                                           "Copy on write: Sharing hash\n"));
4555
4556                     assert (SvTYPE(dsv) >= SVt_PV);
4557                     SvPV_set(dsv,
4558                              HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(ssv)))));
4559             }
4560             SvLEN_set(dsv, len);
4561             SvCUR_set(dsv, cur);
4562             SvIsCOW_on(dsv);
4563         } else {
4564             /* Failed the swipe test, and we cannot do copy-on-write either.
4565                Have to copy the string.  */
4566             SvGROW(dsv, cur + 1);       /* inlined from sv_setpvn */
4567             Move(SvPVX_const(ssv),SvPVX(dsv),cur,char);
4568             SvCUR_set(dsv, cur);
4569             *SvEND(dsv) = '\0';
4570         }
4571         if (sflags & SVp_NOK) {
4572             SvNV_set(dsv, SvNVX(ssv));
4573             if ((sflags & SVf_NOK) && !(sflags & SVf_POK)) {
4574                 /* Source was SVf_NOK|SVp_NOK|SVp_POK but not SVf_POK, meaning
4575                    a value set as floating point and later stringified, where
4576                   the value happens to be one of the few that we know aren't
4577                   affected by the numeric locale, hence we can cache the
4578                   stringification. Currently that's  +Inf, -Inf and NaN, but
4579                   conceivably we might extend this to -9 .. +9 (excluding -0).
4580                   So mark destination the same: */
4581                 SvFLAGS(dsv) &= ~SVf_POK;
4582             }
4583         }
4584         if (sflags & SVp_IOK) {
4585             SvIV_set(dsv, SvIVX(ssv));
4586             if (sflags & SVf_IVisUV)
4587                 SvIsUV_on(dsv);
4588             if ((sflags & SVf_IOK) && !(sflags & SVf_POK)) {
4589                 /* Source was SVf_IOK|SVp_IOK|SVp_POK but not SVf_POK, meaning
4590                    a value set as an integer and later stringified. So mark
4591                    destination the same: */
4592                 SvFLAGS(dsv) &= ~SVf_POK;
4593             }
4594         }
4595         SvFLAGS(dsv) |= sflags & (SVf_IOK|SVp_IOK|SVf_NOK|SVp_NOK|SVf_UTF8);
4596         {
4597             const MAGIC * const smg = SvVSTRING_mg(ssv);
4598             if (smg) {
4599                 sv_magic(dsv, NULL, PERL_MAGIC_vstring,
4600                          smg->mg_ptr, smg->mg_len);
4601                 SvRMAGICAL_on(dsv);
4602             }
4603         }
4604     }
4605     else if (sflags & (SVp_IOK|SVp_NOK)) {
4606         (void)SvOK_off(dsv);
4607         SvFLAGS(dsv) |= sflags & (SVf_IOK|SVp_IOK|SVf_IVisUV|SVf_NOK|SVp_NOK);
4608         if (sflags & SVp_IOK) {
4609             /* XXXX Do we want to set IsUV for IV(ROK)?  Be extra safe... */
4610             SvIV_set(dsv, SvIVX(ssv));
4611         }
4612         if (sflags & SVp_NOK) {
4613             SvNV_set(dsv, SvNVX(ssv));
4614         }
4615     }
4616     else {
4617         if (isGV_with_GP(ssv)) {
4618             gv_efullname3(dsv, MUTABLE_GV(ssv), "*");
4619         }
4620         else
4621             (void)SvOK_off(dsv);
4622     }
4623     if (SvTAINTED(ssv))
4624         SvTAINT(dsv);
4625 }
4626
4627
4628 /*
4629 =for apidoc sv_set_undef
4630
4631 Equivalent to C<sv_setsv(sv, &PL_sv_undef)>, but more efficient.
4632 Doesn't handle set magic.
4633
4634 The perl equivalent is C<$sv = undef;>. Note that it doesn't free any string
4635 buffer, unlike C<undef $sv>.
4636
4637 Introduced in perl 5.25.12.
4638
4639 =cut
4640 */
4641
4642 void
4643 Perl_sv_set_undef(pTHX_ SV *sv)
4644 {
4645     U32 type = SvTYPE(sv);
4646
4647     PERL_ARGS_ASSERT_SV_SET_UNDEF;
4648
4649     /* shortcut, NULL, IV, RV */
4650
4651     if (type <= SVt_IV) {
4652         assert(!SvGMAGICAL(sv));
4653         if (SvREADONLY(sv)) {
4654             /* does undeffing PL_sv_undef count as modifying a read-only
4655              * variable? Some XS code does this */
4656             if (sv == &PL_sv_undef)
4657                 return;
4658             Perl_croak_no_modify();
4659         }
4660
4661         if (SvROK(sv)) {
4662             if (SvWEAKREF(sv))
4663                 sv_unref_flags(sv, 0);
4664             else {
4665                 SV *rv = SvRV(sv);
4666                 SvFLAGS(sv) = type; /* quickly turn off all flags */
4667                 SvREFCNT_dec_NN(rv);
4668                 return;
4669             }
4670         }
4671         SvFLAGS(sv) = type; /* quickly turn off all flags */
4672         return;
4673     }
4674
4675     if (SvIS_FREED(sv))
4676         Perl_croak(aTHX_ "panic: attempt to undefine a freed scalar %p",
4677             (void *)sv);
4678
4679     SV_CHECK_THINKFIRST_COW_DROP(sv);
4680
4681     if (isGV_with_GP(sv))
4682         Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4683                        "Undefined value assigned to typeglob");
4684     else
4685         SvOK_off(sv);
4686 }
4687
4688 /*
4689 =for apidoc sv_set_true
4690
4691 Equivalent to C<sv_setsv(sv, &PL_sv_yes)>, but may be made more
4692 efficient in the future. Doesn't handle set magic.
4693
4694 The perl equivalent is C<$sv = !0;>.
4695
4696 Introduced in perl 5.35.11.
4697
4698 =cut
4699 */
4700
4701 void
4702 Perl_sv_set_true(pTHX_ SV *sv)
4703 {
4704     PERL_ARGS_ASSERT_SV_SET_TRUE;
4705     sv_setsv(sv, &PL_sv_yes);
4706 }
4707
4708 /*
4709 =for apidoc sv_set_false
4710
4711 Equivalent to C<sv_setsv(sv, &PL_sv_no)>, but may be made more
4712 efficient in the future. Doesn't handle set magic.
4713
4714 The perl equivalent is C<$sv = !1;>.
4715
4716 Introduced in perl 5.35.11.
4717
4718 =cut
4719 */
4720
4721 void
4722 Perl_sv_set_false(pTHX_ SV *sv)
4723 {
4724     PERL_ARGS_ASSERT_SV_SET_FALSE;
4725     sv_setsv(sv, &PL_sv_no);
4726 }
4727
4728 /*
4729 =for apidoc sv_set_bool
4730
4731 Equivalent to C<sv_setsv(sv, bool_val ? &Pl_sv_yes : &PL_sv_no)>, but
4732 may be made more efficient in the future. Doesn't handle set magic.
4733
4734 The perl equivalent is C<$sv = !!$expr;>.
4735
4736 Introduced in perl 5.35.11.
4737
4738 =cut
4739 */
4740
4741 void
4742 Perl_sv_set_bool(pTHX_ SV *sv, const bool bool_val)
4743 {
4744     PERL_ARGS_ASSERT_SV_SET_BOOL;
4745     sv_setsv(sv, bool_val ? &PL_sv_yes : &PL_sv_no);
4746 }
4747
4748
4749 void
4750 Perl_sv_setsv_mg(pTHX_ SV *const dsv, SV *const ssv)
4751 {
4752     PERL_ARGS_ASSERT_SV_SETSV_MG;
4753
4754     sv_setsv(dsv,ssv);
4755     SvSETMAGIC(dsv);
4756 }
4757
4758 #ifdef PERL_ANY_COW
4759 #  define SVt_COW SVt_PV
4760 SV *
4761 Perl_sv_setsv_cow(pTHX_ SV *dsv, SV *ssv)
4762 {
4763     STRLEN cur = SvCUR(ssv);
4764     STRLEN len = SvLEN(ssv);
4765     char *new_pv;
4766     U32 new_flags = (SVt_COW|SVf_POK|SVp_POK|SVf_IsCOW);
4767 #if defined(PERL_DEBUG_READONLY_COW) && defined(PERL_COPY_ON_WRITE)
4768     const bool already = cBOOL(SvIsCOW(ssv));
4769 #endif
4770
4771     PERL_ARGS_ASSERT_SV_SETSV_COW;
4772 #ifdef DEBUGGING
4773     if (DEBUG_C_TEST) {
4774         PerlIO_printf(Perl_debug_log, "Fast copy on write: %p -> %p\n",
4775                       (void*)ssv, (void*)dsv);
4776         sv_dump(ssv);
4777         if (dsv)
4778                     sv_dump(dsv);
4779     }
4780 #endif
4781     if (dsv) {
4782         if (SvTHINKFIRST(dsv))
4783             sv_force_normal_flags(dsv, SV_COW_DROP_PV);
4784         else if (SvPVX_const(dsv))
4785             Safefree(SvPVX_mutable(dsv));
4786         SvUPGRADE(dsv, SVt_COW);
4787     }
4788     else
4789         dsv = newSV_type(SVt_COW);
4790
4791     assert (SvPOK(ssv));
4792     assert (SvPOKp(ssv));
4793
4794     if (SvIsCOW(ssv)) {
4795         if (SvIsCOW_shared_hash(ssv)) {
4796             /* source is a COW shared hash key.  */
4797             DEBUG_C(PerlIO_printf(Perl_debug_log,
4798                                   "Fast copy on write: Sharing hash\n"));
4799             new_pv = HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(ssv))));
4800             goto common_exit;
4801         }
4802         else if (SvIsCOW_static(ssv)) {
4803             /* source is static constant; preserve this */
4804             new_pv = SvPVX(ssv);
4805             new_flags |= SVppv_STATIC;
4806             goto common_exit;
4807         }
4808         assert(SvCUR(ssv)+1 < SvLEN(ssv));
4809         assert(CowREFCNT(ssv) < SV_COW_REFCNT_MAX);
4810     } else {
4811         assert ((SvFLAGS(ssv) & CAN_COW_MASK) == CAN_COW_FLAGS);
4812         SvUPGRADE(ssv, SVt_COW);
4813         SvIsCOW_on(ssv);
4814         DEBUG_C(PerlIO_printf(Perl_debug_log,
4815                               "Fast copy on write: Converting ssv to COW\n"));
4816         CowREFCNT(ssv) = 0;
4817     }
4818 #  ifdef PERL_DEBUG_READONLY_COW
4819     if (already) sv_buf_to_rw(ssv);
4820 #  endif
4821     CowREFCNT(ssv)++;
4822     new_pv = SvPVX_mutable(ssv);
4823     sv_buf_to_ro(ssv);
4824
4825   common_exit:
4826     SvPV_set(dsv, new_pv);
4827     SvFLAGS(dsv) = new_flags;
4828     if (SvUTF8(ssv))
4829         SvUTF8_on(dsv);
4830     SvLEN_set(dsv, len);
4831     SvCUR_set(dsv, cur);
4832 #ifdef DEBUGGING
4833     if (DEBUG_C_TEST)
4834                 sv_dump(dsv);
4835 #endif
4836     return dsv;
4837 }
4838 #endif
4839
4840 /*
4841 =for apidoc sv_setpv_bufsize
4842
4843 Sets the SV to be a string of cur bytes length, with at least
4844 len bytes available. Ensures that there is a null byte at SvEND.
4845 Returns a char * pointer to the SvPV buffer.
4846
4847 =cut
4848 */
4849
4850 char *
4851 Perl_sv_setpv_bufsize(pTHX_ SV *const sv, const STRLEN cur, const STRLEN len)
4852 {
4853     char *pv;
4854
4855     PERL_ARGS_ASSERT_SV_SETPV_BUFSIZE;
4856
4857     SV_CHECK_THINKFIRST_COW_DROP(sv);
4858     SvUPGRADE(sv, SVt_PV);
4859     pv = SvGROW(sv, len + 1);
4860     SvCUR_set(sv, cur);
4861     *(SvEND(sv))= '\0';
4862     (void)SvPOK_only_UTF8(sv);                /* validate pointer */
4863
4864     SvTAINT(sv);
4865     if (SvTYPE(sv) == SVt_PVCV) CvAUTOLOAD_off(sv);
4866     return pv;
4867 }
4868
4869 /*
4870 =for apidoc            sv_setpv
4871 =for apidoc_item       sv_setpv_mg
4872 =for apidoc_item       sv_setpvn
4873 =for apidoc_item       sv_setpvn_fresh
4874 =for apidoc_item       sv_setpvn_mg
4875 =for apidoc_item |void|sv_setpvs|SV* sv|"literal string"
4876 =for apidoc_item |void|sv_setpvs_mg|SV* sv|"literal string"
4877
4878 These copy a string into the SV C<sv>, making sure it is C<L</SvPOK_only>>.
4879
4880 In the C<pvs> forms, the string must be a C literal string, enclosed in double
4881 quotes.
4882
4883 In the C<pvn> forms, the first byte of the string is pointed to by C<ptr>, and
4884 C<len> indicates the number of bytes to be copied, potentially including
4885 embedded C<NUL> characters.
4886
4887 In the plain C<pv> forms, C<ptr> points to a NUL-terminated C string.  That is,
4888 it points to the first byte of the string, and the copy proceeds up through the
4889 first enountered C<NUL> byte.
4890
4891 In the forms that take a C<ptr> argument, if it is NULL, the SV will become
4892 undefined.
4893
4894 The UTF-8 flag is not changed by these functions.  A terminating NUL byte is
4895 guaranteed in the result.
4896
4897 The C<_mg> forms handle 'set' magic; the other forms skip all magic.
4898
4899 C<sv_setpvn_fresh> is a cut-down alternative to C<sv_setpvn>, intended ONLY
4900 to be used with a fresh sv that has been upgraded to a SVt_PV, SVt_PVIV,
4901 SVt_PVNV, or SVt_PVMG.
4902
4903 =cut
4904 */
4905
4906 void
4907 Perl_sv_setpvn(pTHX_ SV *const sv, const char *const ptr, const STRLEN len)
4908 {
4909     char *dptr;
4910
4911     PERL_ARGS_ASSERT_SV_SETPVN;
4912
4913     SV_CHECK_THINKFIRST_COW_DROP(sv);
4914     if (isGV_with_GP(sv))
4915         Perl_croak_no_modify();
4916     if (!ptr) {
4917         (void)SvOK_off(sv);
4918         return;
4919     }
4920     else {
4921         /* len is STRLEN which is unsigned, need to copy to signed */
4922         const IV iv = len;
4923         if (iv < 0)
4924             Perl_croak(aTHX_ "panic: sv_setpvn called with negative strlen %"
4925                        IVdf, iv);
4926     }
4927     SvUPGRADE(sv, SVt_PV);
4928
4929     dptr = SvGROW(sv, len + 1);
4930     Move(ptr,dptr,len,char);
4931     dptr[len] = '\0';
4932     SvCUR_set(sv, len);
4933     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4934     SvTAINT(sv);
4935     if (SvTYPE(sv) == SVt_PVCV) CvAUTOLOAD_off(sv);
4936 }
4937
4938 void
4939 Perl_sv_setpvn_mg(pTHX_ SV *const sv, const char *const ptr, const STRLEN len)
4940 {
4941     PERL_ARGS_ASSERT_SV_SETPVN_MG;
4942
4943     sv_setpvn(sv,ptr,len);
4944     SvSETMAGIC(sv);
4945 }
4946
4947 void
4948 Perl_sv_setpvn_fresh(pTHX_ SV *const sv, const char *const ptr, const STRLEN len)
4949 {
4950     char *dptr;
4951
4952     PERL_ARGS_ASSERT_SV_SETPVN_FRESH;
4953     assert(SvTYPE(sv) >= SVt_PV && SvTYPE(sv) <= SVt_PVMG);
4954     assert(!SvTHINKFIRST(sv));
4955     assert(!isGV_with_GP(sv));
4956
4957     if (ptr) {
4958         const IV iv = len;
4959         /* len is STRLEN which is unsigned, need to copy to signed */
4960         if (iv < 0)
4961             Perl_croak(aTHX_ "panic: sv_setpvn_fresh called with negative strlen %"
4962                        IVdf, iv);
4963
4964         dptr = sv_grow_fresh(sv, len + 1);
4965         Move(ptr,dptr,len,char);
4966         dptr[len] = '\0';
4967         SvCUR_set(sv, len);
4968         SvPOK_on(sv);
4969         SvTAINT(sv);
4970     }
4971 }
4972
4973 void
4974 Perl_sv_setpv(pTHX_ SV *const sv, const char *const ptr)
4975 {
4976     STRLEN len;
4977
4978     PERL_ARGS_ASSERT_SV_SETPV;
4979
4980     SV_CHECK_THINKFIRST_COW_DROP(sv);
4981     if (!ptr) {
4982         (void)SvOK_off(sv);
4983         return;
4984     }
4985     len = strlen(ptr);
4986     SvUPGRADE(sv, SVt_PV);
4987
4988     SvGROW(sv, len + 1);
4989     Move(ptr,SvPVX(sv),len+1,char);
4990     SvCUR_set(sv, len);
4991     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4992     SvTAINT(sv);
4993     if (SvTYPE(sv) == SVt_PVCV) CvAUTOLOAD_off(sv);
4994 }
4995
4996 void
4997 Perl_sv_setpv_mg(pTHX_ SV *const sv, const char *const ptr)
4998 {
4999     PERL_ARGS_ASSERT_SV_SETPV_MG;
5000
5001     sv_setpv(sv,ptr);
5002     SvSETMAGIC(sv);
5003 }
5004
5005 void
5006 Perl_sv_sethek(pTHX_ SV *const sv, const HEK *const hek)
5007 {
5008     PERL_ARGS_ASSERT_SV_SETHEK;
5009
5010     if (!hek) {
5011         return;
5012     }
5013
5014     if (HEK_LEN(hek) == HEf_SVKEY) {
5015         sv_setsv(sv, *(SV**)HEK_KEY(hek));
5016         return;
5017     } else {
5018         const int flags = HEK_FLAGS(hek);
5019         if (flags & HVhek_WASUTF8) {
5020             STRLEN utf8_len = HEK_LEN(hek);
5021             char *as_utf8 = (char *)bytes_to_utf8((U8*)HEK_KEY(hek), &utf8_len);
5022             sv_usepvn_flags(sv, as_utf8, utf8_len, SV_HAS_TRAILING_NUL);
5023             SvUTF8_on(sv);
5024             return;
5025         } else if (flags & HVhek_NOTSHARED) {
5026             sv_setpvn(sv, HEK_KEY(hek), HEK_LEN(hek));
5027             if (HEK_UTF8(hek))
5028                 SvUTF8_on(sv);
5029             else SvUTF8_off(sv);
5030             return;
5031         }
5032         {
5033             SV_CHECK_THINKFIRST_COW_DROP(sv);
5034             SvUPGRADE(sv, SVt_PV);
5035             SvPV_free(sv);
5036             SvPV_set(sv,(char *)HEK_KEY(share_hek_hek(hek)));
5037             SvCUR_set(sv, HEK_LEN(hek));
5038             SvLEN_set(sv, 0);
5039             SvIsCOW_on(sv);
5040             SvPOK_on(sv);
5041             if (HEK_UTF8(hek))
5042                 SvUTF8_on(sv);
5043             else SvUTF8_off(sv);
5044             return;
5045         }
5046     }
5047 }
5048
5049
5050 /*
5051 =for apidoc      sv_usepvn
5052 =for apidoc_item sv_usepvn_flags
5053 =for apidoc_item sv_usepvn_mg
5054
5055 These tell an SV to use C<ptr> for its string value.  Normally SVs have
5056 their string stored inside the SV, but these tell the SV to use an
5057 external string instead.
5058
5059 C<ptr> should point to memory that was allocated
5060 by L</C<Newx>>.  It must be
5061 the start of a C<Newx>-ed block of memory, and not a pointer to the
5062 middle of it (beware of L<C<OOK>|perlguts/Offsets> and copy-on-write),
5063 and not be from a non-C<Newx> memory allocator like C<malloc>.  The
5064 string length, C<len>, must be supplied.  By default this function
5065 will L</C<Renew>> (i.e. realloc, move) the memory pointed to by C<ptr>,
5066 so that the pointer should not be freed or used by the programmer after giving
5067 it to C<sv_usepvn>, and neither should any pointers from "behind" that pointer
5068 (I<e.g.>, S<C<ptr> + 1>) be used.
5069
5070 In the C<sv_usepvn_flags> form, if S<C<flags & SV_SMAGIC>> is true,
5071 C<SvSETMAGIC> is called before returning.
5072 And if S<C<flags & SV_HAS_TRAILING_NUL>> is true, then C<ptr[len]> must be
5073 C<NUL>, and the realloc will be skipped (I<i.e.>, the buffer is actually at
5074 least 1 byte longer than C<len>, and already meets the requirements for storing
5075 in C<SvPVX>).
5076
5077 C<sv_usepvn> is merely C<sv_usepvn_flags> with C<flags> set to 0, so 'set'
5078 magic is skipped.
5079
5080 C<sv_usepvn_mg> is merely C<sv_usepvn_flags> with C<flags> set to C<SV_SMAGIC>,
5081 so 'set' magic is performed.
5082
5083 =for apidoc Amnh||SV_SMAGIC
5084 =for apidoc Amnh||SV_HAS_TRAILING_NUL
5085
5086 =cut
5087 */
5088
5089 void
5090 Perl_sv_usepvn_flags(pTHX_ SV *const sv, char *ptr, const STRLEN len, const U32 flags)
5091 {
5092     STRLEN allocate;
5093
5094     PERL_ARGS_ASSERT_SV_USEPVN_FLAGS;
5095
5096     SV_CHECK_THINKFIRST_COW_DROP(sv);
5097     SvUPGRADE(sv, SVt_PV);
5098     if (!ptr) {
5099         (void)SvOK_off(sv);
5100         if (flags & SV_SMAGIC)
5101             SvSETMAGIC(sv);
5102         return;
5103     }
5104     if (SvPVX_const(sv))
5105         SvPV_free(sv);
5106
5107 #ifdef DEBUGGING
5108     if (flags & SV_HAS_TRAILING_NUL)
5109         assert(ptr[len] == '\0');
5110 #endif
5111
5112     allocate = (flags & SV_HAS_TRAILING_NUL)
5113         ? len + 1 :
5114 #ifdef Perl_safesysmalloc_size
5115         len + 1;
5116 #else
5117         PERL_STRLEN_ROUNDUP(len + 1);
5118 #endif
5119     if (flags & SV_HAS_TRAILING_NUL) {
5120         /* It's long enough - do nothing.
5121            Specifically Perl_newCONSTSUB is relying on this.  */
5122     } else {
5123 #ifdef DEBUGGING
5124         /* Force a move to shake out bugs in callers.  */
5125         char *new_ptr = (char*)safemalloc(allocate);
5126         Copy(ptr, new_ptr, len, char);
5127         PoisonFree(ptr,len,char);
5128         Safefree(ptr);
5129         ptr = new_ptr;
5130 #else
5131         ptr = (char*) saferealloc (ptr, allocate);
5132 #endif
5133     }
5134 #ifdef Perl_safesysmalloc_size
5135     SvLEN_set(sv, Perl_safesysmalloc_size(ptr));
5136 #else
5137     SvLEN_set(sv, allocate);
5138 #endif
5139     SvCUR_set(sv, len);
5140     SvPV_set(sv, ptr);
5141     if (!(flags & SV_HAS_TRAILING_NUL)) {
5142         ptr[len] = '\0';
5143     }
5144     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
5145     SvTAINT(sv);
5146     if (flags & SV_SMAGIC)
5147         SvSETMAGIC(sv);
5148 }
5149
5150
5151 static void
5152 S_sv_uncow(pTHX_ SV * const sv, const U32 flags)
5153 {
5154     assert(SvIsCOW(sv));
5155     {
5156 #ifdef PERL_ANY_COW
5157         const char * const pvx = SvPVX_const(sv);
5158         const STRLEN len = SvLEN(sv);
5159         const STRLEN cur = SvCUR(sv);
5160         const bool was_shared_hek = SvIsCOW_shared_hash(sv);
5161
5162 #ifdef DEBUGGING
5163         if (DEBUG_C_TEST) {
5164                 PerlIO_printf(Perl_debug_log,
5165                               "Copy on write: Force normal %ld\n",
5166                               (long) flags);
5167                 sv_dump(sv);
5168         }
5169 #endif
5170         SvIsCOW_off(sv);
5171 # ifdef PERL_COPY_ON_WRITE
5172         if (len) {
5173             /* Must do this first, since the CowREFCNT uses SvPVX and
5174             we need to write to CowREFCNT, or de-RO the whole buffer if we are
5175             the only owner left of the buffer. */
5176             sv_buf_to_rw(sv); /* NOOP if RO-ing not supported */
5177             {
5178                 U8 cowrefcnt = CowREFCNT(sv);
5179                 if(cowrefcnt != 0) {
5180                     cowrefcnt--;
5181                     CowREFCNT(sv) = cowrefcnt;
5182                     sv_buf_to_ro(sv);
5183                     goto copy_over;
5184                 }
5185             }
5186             /* Else we are the only owner of the buffer. */
5187         }
5188         else
5189 # endif
5190         {
5191             /* This SV doesn't own the buffer, so need to Newx() a new one:  */
5192             copy_over:
5193             SvPV_set(sv, NULL);
5194             SvCUR_set(sv, 0);
5195             SvLEN_set(sv, 0);
5196             if (flags & SV_COW_DROP_PV) {
5197                 /* OK, so we don't need to copy our buffer.  */
5198                 SvPOK_off(sv);
5199             } else {
5200                 SvGROW(sv, cur + 1);
5201                 Move(pvx,SvPVX(sv),cur,char);
5202                 SvCUR_set(sv, cur);
5203                 *SvEND(sv) = '\0';
5204             }
5205             if (was_shared_hek) {
5206                         unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
5207             }
5208 #ifdef DEBUGGING
5209             if (DEBUG_C_TEST)
5210                 sv_dump(sv);
5211 #endif
5212         }
5213 #else
5214             const char * const pvx = SvPVX_const(sv);
5215             const STRLEN len = SvCUR(sv);
5216             SvIsCOW_off(sv);
5217             SvPV_set(sv, NULL);
5218             SvLEN_set(sv, 0);
5219             if (flags & SV_COW_DROP_PV) {
5220                 /* OK, so we don't need to copy our buffer.  */
5221                 SvPOK_off(sv);
5222             } else {
5223                 SvGROW(sv, len + 1);
5224                 Move(pvx,SvPVX(sv),len,char);
5225                 *SvEND(sv) = '\0';
5226             }
5227             unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
5228 #endif
5229     }
5230 }
5231
5232
5233 /*
5234 =for apidoc sv_force_normal_flags
5235
5236 Undo various types of fakery on an SV, where fakery means
5237 "more than" a string: if the PV is a shared string, make
5238 a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
5239 an C<xpvmg>; if we're a copy-on-write scalar, this is the on-write time when
5240 we do the copy, and is also used locally; if this is a
5241 vstring, drop the vstring magic.  If C<SV_COW_DROP_PV> is set
5242 then a copy-on-write scalar drops its PV buffer (if any) and becomes
5243 C<SvPOK_off> rather than making a copy.  (Used where this
5244 scalar is about to be set to some other value.)  In addition,
5245 the C<flags> parameter gets passed to C<sv_unref_flags()>
5246 when unreffing.  C<sv_force_normal> calls this function
5247 with flags set to 0.
5248
5249 This function is expected to be used to signal to perl that this SV is
5250 about to be written to, and any extra book-keeping needs to be taken care
5251 of.  Hence, it croaks on read-only values.
5252
5253 =for apidoc Amnh||SV_COW_DROP_PV
5254
5255 =cut
5256 */
5257
5258 void
5259 Perl_sv_force_normal_flags(pTHX_ SV *const sv, const U32 flags)
5260 {
5261     PERL_ARGS_ASSERT_SV_FORCE_NORMAL_FLAGS;
5262
5263     if (SvREADONLY(sv))
5264         Perl_croak_no_modify();
5265     else if (SvIsCOW(sv) && LIKELY(SvTYPE(sv) != SVt_PVHV))
5266         S_sv_uncow(aTHX_ sv, flags);
5267     if (SvROK(sv))
5268         sv_unref_flags(sv, flags);
5269     else if (SvFAKE(sv) && isGV_with_GP(sv))
5270         sv_unglob(sv, flags);
5271     else if (SvFAKE(sv) && isREGEXP(sv)) {
5272         /* Need to downgrade the REGEXP to a simple(r) scalar. This is analogous
5273            to sv_unglob. We only need it here, so inline it.  */
5274         const bool islv = SvTYPE(sv) == SVt_PVLV;
5275         const svtype new_type =
5276           islv ? SVt_NULL : SvMAGIC(sv) || SvSTASH(sv) ? SVt_PVMG : SVt_PV;
5277         SV *const temp = newSV_type(new_type);
5278         regexp *old_rx_body;
5279
5280         if (new_type == SVt_PVMG) {
5281             SvMAGIC_set(temp, SvMAGIC(sv));
5282             SvMAGIC_set(sv, NULL);
5283             SvSTASH_set(temp, SvSTASH(sv));
5284             SvSTASH_set(sv, NULL);
5285         }
5286         if (!islv)
5287             SvCUR_set(temp, SvCUR(sv));
5288         /* Remember that SvPVX is in the head, not the body. */
5289         assert(ReANY((REGEXP *)sv)->mother_re);
5290
5291         if (islv) {
5292             /* LV-as-regex has sv->sv_any pointing to an XPVLV body,
5293              * whose xpvlenu_rx field points to the regex body */
5294             XPV *xpv = (XPV*)(SvANY(sv));
5295             old_rx_body = xpv->xpv_len_u.xpvlenu_rx;
5296             xpv->xpv_len_u.xpvlenu_rx = NULL;
5297         }
5298         else
5299             old_rx_body = ReANY((REGEXP *)sv);
5300
5301         /* Their buffer is already owned by someone else. */
5302         if (flags & SV_COW_DROP_PV) {
5303             /* SvLEN is already 0.  For SVt_REGEXP, we have a brand new
5304                zeroed body.  For SVt_PVLV, we zeroed it above (len field
5305                a union with xpvlenu_rx) */
5306             assert(!SvLEN(islv ? sv : temp));
5307             sv->sv_u.svu_pv = 0;
5308         }
5309         else {
5310             sv->sv_u.svu_pv = savepvn(RX_WRAPPED((REGEXP *)sv), SvCUR(sv));
5311             SvLEN_set(islv ? sv : temp, SvCUR(sv)+1);
5312             SvPOK_on(sv);
5313         }
5314
5315         /* Now swap the rest of the bodies. */
5316
5317         SvFAKE_off(sv);
5318         if (!islv) {
5319             SvFLAGS(sv) &= ~SVTYPEMASK;
5320             SvFLAGS(sv) |= new_type;
5321             SvANY(sv) = SvANY(temp);
5322         }
5323
5324         SvFLAGS(temp) &= ~(SVTYPEMASK);
5325         SvFLAGS(temp) |= SVt_REGEXP|SVf_FAKE;
5326         SvANY(temp) = old_rx_body;
5327
5328         /* temp is now rebuilt as a correctly structured SVt_REGEXP, so this
5329          * will trigger a call to sv_clear() which will correctly free the
5330          * body. */
5331         SvREFCNT_dec_NN(temp);
5332     }
5333     else if (SvVOK(sv)) sv_unmagic(sv, PERL_MAGIC_vstring);
5334 }
5335
5336 /*
5337 =for apidoc sv_chop
5338
5339 Efficient removal of characters from the beginning of the string buffer.
5340 C<SvPOK(sv)>, or at least C<SvPOKp(sv)>, must be true and C<ptr> must be a
5341 pointer to somewhere inside the string buffer.  C<ptr> becomes the first
5342 character of the adjusted string.  Uses the C<OOK> hack.  On return, only
5343 C<SvPOK(sv)> and C<SvPOKp(sv)> among the C<OK> flags will be true.
5344
5345 Beware: after this function returns, C<ptr> and SvPVX_const(sv) may no longer
5346 refer to the same chunk of data.
5347
5348 The unfortunate similarity of this function's name to that of Perl's C<chop>
5349 operator is strictly coincidental.  This function works from the left;
5350 C<chop> works from the right.
5351
5352 =cut
5353 */
5354
5355 void
5356 Perl_sv_chop(pTHX_ SV *const sv, const char *const ptr)
5357 {
5358     STRLEN delta;
5359     STRLEN old_delta;
5360     U8 *p;
5361 #ifdef DEBUGGING
5362     const U8 *evacp;
5363     STRLEN evacn;
5364 #endif
5365     STRLEN max_delta;
5366
5367     PERL_ARGS_ASSERT_SV_CHOP;
5368
5369     if (!ptr || !SvPOKp(sv))
5370         return;
5371     delta = ptr - SvPVX_const(sv);
5372     if (!delta) {
5373         /* Nothing to do.  */
5374         return;
5375     }
5376     max_delta = SvLEN(sv) ? SvLEN(sv) : SvCUR(sv);
5377     if (delta > max_delta)
5378         Perl_croak(aTHX_ "panic: sv_chop ptr=%p, start=%p, end=%p",
5379                    ptr, SvPVX_const(sv), SvPVX_const(sv) + max_delta);
5380     /* SvPVX(sv) may move in SV_CHECK_THINKFIRST(sv), so don't use ptr any more */
5381     SV_CHECK_THINKFIRST(sv);
5382     SvPOK_only_UTF8(sv);
5383
5384     if (!SvOOK(sv)) {
5385         if (!SvLEN(sv)) { /* make copy of shared string */
5386             const char *pvx = SvPVX_const(sv);
5387             const STRLEN len = SvCUR(sv);
5388             SvGROW(sv, len + 1);
5389             Move(pvx,SvPVX(sv),len,char);
5390             *SvEND(sv) = '\0';
5391         }
5392         SvOOK_on(sv);
5393         old_delta = 0;
5394     } else {
5395         SvOOK_offset(sv, old_delta);
5396     }
5397     SvLEN_set(sv, SvLEN(sv) - delta);
5398     SvCUR_set(sv, SvCUR(sv) - delta);
5399     SvPV_set(sv, SvPVX(sv) + delta);
5400
5401     p = (U8 *)SvPVX_const(sv);
5402
5403 #ifdef DEBUGGING
5404     /* how many bytes were evacuated?  we will fill them with sentinel
5405        bytes, except for the part holding the new offset of course. */
5406     evacn = delta;
5407     if (old_delta)
5408         evacn += (old_delta < 0x100 ? 1 : 1 + sizeof(STRLEN));
5409     assert(evacn);
5410     assert(evacn <= delta + old_delta);
5411     evacp = p - evacn;
5412 #endif
5413
5414     /* This sets 'delta' to the accumulated value of all deltas so far */
5415     delta += old_delta;
5416     assert(delta);
5417
5418     /* If 'delta' fits in a byte, store it just prior to the new beginning of
5419      * the string; otherwise store a 0 byte there and store 'delta' just prior
5420      * to that, using as many bytes as a STRLEN occupies.  Thus it overwrites a
5421      * portion of the chopped part of the string */
5422     if (delta < 0x100) {
5423         *--p = (U8) delta;
5424     } else {
5425         *--p = 0;
5426         p -= sizeof(STRLEN);
5427         Copy((U8*)&delta, p, sizeof(STRLEN), U8);
5428     }
5429
5430 #ifdef DEBUGGING
5431     /* Fill the preceding buffer with sentinals to verify that no-one is
5432        using it.  */
5433     while (p > evacp) {
5434         --p;
5435         *p = (U8)PTR2UV(p);
5436     }
5437 #endif
5438 }
5439
5440 /*
5441 =for apidoc sv_catpvn
5442 =for apidoc_item sv_catpvn_flags
5443 =for apidoc_item sv_catpvn_mg
5444 =for apidoc_item sv_catpvn_nomg
5445
5446 These concatenate the C<len> bytes of the string beginning at C<ptr> onto the
5447 end of the string which is in C<dsv>.  The caller must make sure C<ptr>
5448 contains at least C<len> bytes.
5449
5450 For all but C<sv_catpvn_flags>, the string appended is assumed to be valid
5451 UTF-8 if the SV has the UTF-8 status set, and a string of bytes otherwise.
5452
5453 They differ in that:
5454
5455 C<sv_catpvn_mg> performs both 'get' and 'set' magic on C<dsv>.
5456
5457 C<sv_catpvn> performs only 'get' magic.
5458
5459 C<sv_catpvn_nomg> skips all magic.
5460
5461 C<sv_catpvn_flags> has an extra C<flags> parameter which allows you to specify
5462 any combination of magic handling (using C<SV_GMAGIC> and/or C<SV_SMAGIC>) and
5463 to also override the UTF-8 handling.  By supplying the C<SV_CATBYTES> flag, the
5464 appended string is interpreted as plain bytes; by supplying instead the
5465 C<SV_CATUTF8> flag, it will be interpreted as UTF-8, and the C<dsv> will be
5466 upgraded to UTF-8 if necessary.
5467
5468 C<sv_catpvn>, C<sv_catpvn_mg>, and C<sv_catpvn_nomg> are implemented
5469 in terms of C<sv_catpvn_flags>.
5470
5471 =for apidoc Amnh||SV_CATUTF8
5472 =for apidoc Amnh||SV_CATBYTES
5473
5474 =cut
5475 */
5476
5477 void
5478 Perl_sv_catpvn_flags(pTHX_ SV *const dsv, const char *sstr, const STRLEN slen, const I32 flags)
5479 {
5480     STRLEN dlen;
5481     const char * const dstr = SvPV_force_flags(dsv, dlen, flags);
5482
5483     PERL_ARGS_ASSERT_SV_CATPVN_FLAGS;
5484     assert((flags & (SV_CATBYTES|SV_CATUTF8)) != (SV_CATBYTES|SV_CATUTF8));
5485
5486     if (!(flags & SV_CATBYTES) || !SvUTF8(dsv)) {
5487       if (flags & SV_CATUTF8 && !SvUTF8(dsv)) {
5488          sv_utf8_upgrade_flags_grow(dsv, 0, slen + 1);
5489          dlen = SvCUR(dsv);
5490       }
5491       else SvGROW(dsv, dlen + slen + 3);
5492       if (sstr == dstr)
5493         sstr = SvPVX_const(dsv);
5494       Move(sstr, SvPVX(dsv) + dlen, slen, char);
5495       SvCUR_set(dsv, SvCUR(dsv) + slen);
5496     }
5497     else {
5498         /* We inline bytes_to_utf8, to avoid an extra malloc. */
5499         const char * const send = sstr + slen;
5500         U8 *d;
5501
5502         /* Something this code does not account for, which I think is
5503            impossible; it would require the same pv to be treated as
5504            bytes *and* utf8, which would indicate a bug elsewhere. */
5505         assert(sstr != dstr);
5506
5507         SvGROW(dsv, dlen + slen * 2 + 3);
5508         d = (U8 *)SvPVX(dsv) + dlen;
5509
5510         while (sstr < send) {
5511             append_utf8_from_native_byte(*sstr, &d);
5512             sstr++;
5513         }
5514         SvCUR_set(dsv, d-(const U8 *)SvPVX(dsv));
5515     }
5516     *SvEND(dsv) = '\0';
5517     (void)SvPOK_only_UTF8(dsv);         /* validate pointer */
5518     SvTAINT(dsv);
5519     if (flags & SV_SMAGIC)
5520         SvSETMAGIC(dsv);
5521 }
5522
5523 /*
5524 =for apidoc sv_catsv
5525 =for apidoc_item sv_catsv_flags
5526 =for apidoc_item sv_catsv_mg
5527 =for apidoc_item sv_catsv_nomg
5528
5529 These concatenate the string from SV C<sstr> onto the end of the string in SV
5530 C<dsv>.  If C<sstr> is null, these are no-ops; otherwise only C<dsv> is
5531 modified.
5532
5533 They differ only in what magic they perform:
5534
5535 C<sv_catsv_mg> performs 'get' magic on both SVs before the copy, and 'set' magic
5536 on C<dsv> afterwards.
5537
5538 C<sv_catsv> performs just 'get' magic, on both SVs.
5539
5540 C<sv_catsv_nomg> skips all magic.
5541
5542 C<sv_catsv_flags> has an extra C<flags> parameter which allows you to use
5543 C<SV_GMAGIC> and/or C<SV_SMAGIC> to specify any combination of magic handling
5544 (although either both or neither SV will have 'get' magic applied to it.)
5545
5546 C<sv_catsv>, C<sv_catsv_mg>, and C<sv_catsv_nomg> are implemented
5547 in terms of C<sv_catsv_flags>.
5548
5549 =cut */
5550
5551 void
5552 Perl_sv_catsv_flags(pTHX_ SV *const dsv, SV *const sstr, const I32 flags)
5553 {
5554     PERL_ARGS_ASSERT_SV_CATSV_FLAGS;
5555
5556     if (sstr) {
5557         STRLEN slen;
5558         const char *spv = SvPV_flags_const(sstr, slen, flags);
5559         if (flags & SV_GMAGIC)
5560                 SvGETMAGIC(dsv);
5561         sv_catpvn_flags(dsv, spv, slen,
5562                             DO_UTF8(sstr) ? SV_CATUTF8 : SV_CATBYTES);
5563         if (flags & SV_SMAGIC)
5564                 SvSETMAGIC(dsv);
5565     }
5566 }
5567
5568 /*
5569 =for apidoc sv_catpv
5570 =for apidoc_item sv_catpv_flags
5571 =for apidoc_item sv_catpv_mg
5572 =for apidoc_item sv_catpv_nomg
5573
5574 These concatenate the C<NUL>-terminated string C<sstr> onto the end of the
5575 string which is in the SV.
5576 If the SV has the UTF-8 status set, then the bytes appended should be
5577 valid UTF-8.
5578
5579 They differ only in how they handle magic:
5580
5581 C<sv_catpv_mg> performs both 'get' and 'set' magic.
5582
5583 C<sv_catpv> performs only 'get' magic.
5584
5585 C<sv_catpv_nomg> skips all magic.
5586
5587 C<sv_catpv_flags> has an extra C<flags> parameter which allows you to specify
5588 any combination of magic handling (using C<SV_GMAGIC> and/or C<SV_SMAGIC>), and
5589 to also override the UTF-8 handling.  By supplying the C<SV_CATUTF8> flag, the
5590 appended string is forced to be interpreted as UTF-8; by supplying instead the
5591 C<SV_CATBYTES> flag, it will be interpreted as just bytes.  Either the SV or
5592 the string appended will be upgraded to UTF-8 if necessary.
5593
5594 =cut
5595 */
5596
5597 void
5598 Perl_sv_catpv(pTHX_ SV *const dsv, const char *sstr)
5599 {
5600     STRLEN len;
5601     STRLEN tlen;
5602     char *junk;
5603
5604     PERL_ARGS_ASSERT_SV_CATPV;
5605
5606     if (!sstr)
5607         return;
5608     junk = SvPV_force(dsv, tlen);
5609     len = strlen(sstr);
5610     SvGROW(dsv, tlen + len + 1);
5611     if (sstr == junk)
5612         sstr = SvPVX_const(dsv);
5613     Move(sstr,SvPVX(dsv)+tlen,len+1,char);
5614     SvCUR_set(dsv, SvCUR(dsv) + len);
5615     (void)SvPOK_only_UTF8(dsv);         /* validate pointer */
5616     SvTAINT(dsv);
5617 }
5618
5619 void
5620 Perl_sv_catpv_flags(pTHX_ SV *dsv, const char *sstr, const I32 flags)
5621 {
5622     PERL_ARGS_ASSERT_SV_CATPV_FLAGS;
5623     sv_catpvn_flags(dsv, sstr, strlen(sstr), flags);
5624 }
5625
5626 void
5627 Perl_sv_catpv_mg(pTHX_ SV *const dsv, const char *const sstr)
5628 {
5629     PERL_ARGS_ASSERT_SV_CATPV_MG;
5630
5631     sv_catpv(dsv,sstr);
5632     SvSETMAGIC(dsv);
5633 }
5634
5635 /*
5636 =for apidoc newSV
5637
5638 Creates a new SV.  A non-zero C<len> parameter indicates the number of
5639 bytes of preallocated string space the SV should have.  An extra byte for a
5640 trailing C<NUL> is also reserved.  (C<SvPOK> is not set for the SV even if string
5641 space is allocated.)  The reference count for the new SV is set to 1.
5642
5643 In 5.9.3, C<newSV()> replaces the older C<NEWSV()> API, and drops the first
5644 parameter, I<x>, a debug aid which allowed callers to identify themselves.
5645 This aid has been superseded by a new build option, C<PERL_MEM_LOG> (see
5646 L<perlhacktips/PERL_MEM_LOG>).  The older API is still there for use in XS
5647 modules supporting older perls.
5648
5649 =cut
5650 */
5651
5652 SV *
5653 Perl_newSV(pTHX_ const STRLEN len)
5654 {
5655     SV *sv;
5656
5657     if (!len)
5658         new_SV(sv);
5659     else {
5660         sv = newSV_type(SVt_PV);
5661         sv_grow_fresh(sv, len + 1);
5662     }
5663     return sv;
5664 }
5665 /*
5666 =for apidoc sv_magicext
5667
5668 Adds magic to an SV, upgrading it if necessary.  Applies the
5669 supplied C<vtable> and returns a pointer to the magic added.
5670
5671 Note that C<sv_magicext> will allow things that C<sv_magic> will not.
5672 In particular, you can add magic to C<SvREADONLY> SVs, and add more than
5673 one instance of the same C<how>.
5674
5675 If C<namlen> is greater than zero then a C<savepvn> I<copy> of C<name> is
5676 stored, if C<namlen> is zero then C<name> is stored as-is and - as another
5677 special case - if C<(name && namlen == HEf_SVKEY)> then C<name> is assumed
5678 to contain an SV* and is stored as-is with its C<REFCNT> incremented.
5679
5680 (This is now used as a subroutine by C<sv_magic>.)
5681
5682 =cut
5683 */
5684 MAGIC *
5685 Perl_sv_magicext(pTHX_ SV *const sv, SV *const obj, const int how,
5686                 const MGVTBL *const vtable, const char *const name, const I32 namlen)
5687 {
5688     MAGIC* mg;
5689
5690     PERL_ARGS_ASSERT_SV_MAGICEXT;
5691
5692     SvUPGRADE(sv, SVt_PVMG);
5693     Newxz(mg, 1, MAGIC);
5694     mg->mg_moremagic = SvMAGIC(sv);
5695     SvMAGIC_set(sv, mg);
5696
5697     /* Sometimes a magic contains a reference loop, where the sv and
5698        object refer to each other.  To prevent a reference loop that
5699        would prevent such objects being freed, we look for such loops
5700        and if we find one we avoid incrementing the object refcount.
5701
5702        Note we cannot do this to avoid self-tie loops as intervening RV must
5703        have its REFCNT incremented to keep it in existence.
5704
5705     */
5706     if (!obj || obj == sv ||
5707         how == PERL_MAGIC_arylen ||
5708         how == PERL_MAGIC_regdata ||
5709         how == PERL_MAGIC_regdatum ||
5710         how == PERL_MAGIC_symtab ||
5711         (SvTYPE(obj) == SVt_PVGV &&
5712             (GvSV(obj) == sv || GvHV(obj) == (const HV *)sv
5713              || GvAV(obj) == (const AV *)sv || GvCV(obj) == (const CV *)sv
5714              || GvIOp(obj) == (const IO *)sv || GvFORM(obj) == (const CV *)sv)))
5715     {
5716         mg->mg_obj = obj;
5717     }
5718     else {
5719         mg->mg_obj = SvREFCNT_inc_simple(obj);
5720         mg->mg_flags |= MGf_REFCOUNTED;
5721     }
5722
5723     /* Normal self-ties simply pass a null object, and instead of
5724        using mg_obj directly, use the SvTIED_obj macro to produce a
5725        new RV as needed.  For glob "self-ties", we are tieing the PVIO
5726        with an RV obj pointing to the glob containing the PVIO.  In
5727        this case, to avoid a reference loop, we need to weaken the
5728        reference.
5729     */
5730
5731     if (how == PERL_MAGIC_tiedscalar && SvTYPE(sv) == SVt_PVIO &&
5732         obj && SvROK(obj) && GvIO(SvRV(obj)) == (const IO *)sv)
5733     {
5734       sv_rvweaken(obj);
5735     }
5736
5737     mg->mg_type = how;
5738     mg->mg_len = namlen;
5739     if (name) {
5740         if (namlen > 0)
5741             mg->mg_ptr = savepvn(name, namlen);
5742         else if (namlen == HEf_SVKEY) {
5743             /* Yes, this is casting away const. This is only for the case of
5744                HEf_SVKEY. I think we need to document this aberation of the
5745                constness of the API, rather than making name non-const, as
5746                that change propagating outwards a long way.  */
5747             mg->mg_ptr = (char*)SvREFCNT_inc_simple_NN((SV *)name);
5748         } else
5749             mg->mg_ptr = (char *) name;
5750     }
5751     mg->mg_virtual = (MGVTBL *) vtable;
5752
5753     mg_magical(sv);
5754     return mg;
5755 }
5756
5757 MAGIC *
5758 Perl_sv_magicext_mglob(pTHX_ SV *sv)
5759 {
5760     PERL_ARGS_ASSERT_SV_MAGICEXT_MGLOB;
5761     if (SvTYPE(sv) == SVt_PVLV && LvTYPE(sv) == 'y') {
5762         /* This sv is only a delegate.  //g magic must be attached to
5763            its target. */
5764         vivify_defelem(sv);
5765         sv = LvTARG(sv);
5766     }
5767     return sv_magicext(sv, NULL, PERL_MAGIC_regex_global,
5768                        &PL_vtbl_mglob, 0, 0);
5769 }
5770
5771 /*
5772 =for apidoc sv_magic
5773
5774 Adds magic to an SV.  First upgrades C<sv> to type C<SVt_PVMG> if
5775 necessary, then adds a new magic item of type C<how> to the head of the
5776 magic list.
5777
5778 See C<L</sv_magicext>> (which C<sv_magic> now calls) for a description of the
5779 handling of the C<name> and C<namlen> arguments.
5780
5781 You need to use C<sv_magicext> to add magic to C<SvREADONLY> SVs and also
5782 to add more than one instance of the same C<how>.
5783
5784 =cut
5785 */
5786
5787 void
5788 Perl_sv_magic(pTHX_ SV *const sv, SV *const obj, const int how,
5789              const char *const name, const I32 namlen)
5790 {
5791     const MGVTBL *vtable;
5792     MAGIC* mg;
5793     unsigned int flags;
5794     unsigned int vtable_index;
5795
5796     PERL_ARGS_ASSERT_SV_MAGIC;
5797
5798     if (how < 0 || (unsigned)how >= C_ARRAY_LENGTH(PL_magic_data)
5799         || ((flags = PL_magic_data[how]),
5800             (vtable_index = flags & PERL_MAGIC_VTABLE_MASK)
5801             > magic_vtable_max))
5802         Perl_croak(aTHX_ "Don't know how to handle magic of type \\%o", how);
5803
5804     /* PERL_MAGIC_ext is reserved for use by extensions not perl internals.
5805        Useful for attaching extension internal data to perl vars.
5806        Note that multiple extensions may clash if magical scalars
5807        etc holding private data from one are passed to another. */
5808
5809     vtable = (vtable_index == magic_vtable_max)
5810         ? NULL : PL_magic_vtables + vtable_index;
5811
5812     if (SvREADONLY(sv)) {
5813         if (
5814             !PERL_MAGIC_TYPE_READONLY_ACCEPTABLE(how)
5815            )
5816         {
5817             Perl_croak_no_modify();
5818         }
5819     }
5820     if (SvMAGICAL(sv) || (how == PERL_MAGIC_taint && SvTYPE(sv) >= SVt_PVMG)) {
5821         if (SvMAGIC(sv) && (mg = mg_find(sv, how))) {
5822             /* sv_magic() refuses to add a magic of the same 'how' as an
5823                existing one
5824              */
5825             if (how == PERL_MAGIC_taint)
5826                 mg->mg_len |= 1;
5827             return;
5828         }
5829     }
5830
5831     /* Rest of work is done else where */
5832     mg = sv_magicext(sv,obj,how,vtable,name,namlen);
5833
5834     switch (how) {
5835     case PERL_MAGIC_taint:
5836         mg->mg_len = 1;
5837         break;
5838     case PERL_MAGIC_ext:
5839     case PERL_MAGIC_dbfile:
5840         SvRMAGICAL_on(sv);
5841         break;
5842     }
5843 }
5844
5845 static int
5846 S_sv_unmagicext_flags(pTHX_ SV *const sv, const int type, MGVTBL *vtbl, const U32 flags)
5847 {
5848     MAGIC* mg;
5849     MAGIC** mgp;
5850
5851     assert(flags <= 1);
5852
5853     if (SvTYPE(sv) < SVt_PVMG || !SvMAGIC(sv))
5854         return 0;
5855     mgp = &(((XPVMG*) SvANY(sv))->xmg_u.xmg_magic);
5856     for (mg = *mgp; mg; mg = *mgp) {
5857         const MGVTBL* const virt = mg->mg_virtual;
5858         if (mg->mg_type == type && (!flags || virt == vtbl)) {
5859             *mgp = mg->mg_moremagic;
5860             if (virt && virt->svt_free)
5861                 virt->svt_free(aTHX_ sv, mg);
5862             if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) {
5863                 if (mg->mg_len > 0)
5864                     Safefree(mg->mg_ptr);
5865                 else if (mg->mg_len == HEf_SVKEY)
5866                     SvREFCNT_dec(MUTABLE_SV(mg->mg_ptr));
5867                 else if (mg->mg_type == PERL_MAGIC_utf8)
5868                     Safefree(mg->mg_ptr);
5869             }
5870             if (mg->mg_flags & MGf_REFCOUNTED)
5871                 SvREFCNT_dec(mg->mg_obj);
5872             Safefree(mg);
5873         }
5874         else
5875             mgp = &mg->mg_moremagic;
5876     }
5877     if (SvMAGIC(sv)) {
5878         if (SvMAGICAL(sv))      /* if we're under save_magic, wait for restore_magic; */
5879             mg_magical(sv);     /*    else fix the flags now */
5880     }
5881     else
5882         SvMAGICAL_off(sv);
5883
5884     return 0;
5885 }
5886
5887 /*
5888 =for apidoc sv_unmagic
5889
5890 Removes all magic of type C<type> from an SV.
5891
5892 =cut
5893 */
5894
5895 int
5896 Perl_sv_unmagic(pTHX_ SV *const sv, const int type)
5897 {
5898     PERL_ARGS_ASSERT_SV_UNMAGIC;
5899     return S_sv_unmagicext_flags(aTHX_ sv, type, NULL, 0);
5900 }
5901
5902 /*
5903 =for apidoc sv_unmagicext
5904
5905 Removes all magic of type C<type> with the specified C<vtbl> from an SV.
5906
5907 =cut
5908 */
5909
5910 int
5911 Perl_sv_unmagicext(pTHX_ SV *const sv, const int type, MGVTBL *vtbl)
5912 {
5913     PERL_ARGS_ASSERT_SV_UNMAGICEXT;
5914     return S_sv_unmagicext_flags(aTHX_ sv, type, vtbl, 1);
5915 }
5916
5917 /*
5918 =for apidoc sv_rvweaken
5919
5920 Weaken a reference: set the C<SvWEAKREF> flag on this RV; give the
5921 referred-to SV C<PERL_MAGIC_backref> magic if it hasn't already; and
5922 push a back-reference to this RV onto the array of backreferences
5923 associated with that magic.  If the RV is magical, set magic will be
5924 called after the RV is cleared.  Silently ignores C<undef> and warns
5925 on already-weak references.
5926
5927 =cut
5928 */
5929
5930 SV *
5931 Perl_sv_rvweaken(pTHX_ SV *const sv)
5932 {
5933     SV *tsv;
5934
5935     PERL_ARGS_ASSERT_SV_RVWEAKEN;
5936
5937     if (!SvOK(sv))  /* let undefs pass */
5938         return sv;
5939     if (!SvROK(sv))
5940         Perl_croak(aTHX_ "Can't weaken a nonreference");
5941     else if (SvWEAKREF(sv)) {
5942         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Reference is already weak");
5943         return sv;
5944     }
5945     else if (SvREADONLY(sv)) croak_no_modify();
5946     tsv = SvRV(sv);
5947     Perl_sv_add_backref(aTHX_ tsv, sv);
5948     SvWEAKREF_on(sv);
5949     SvREFCNT_dec_NN(tsv);
5950     return sv;
5951 }
5952
5953 /*
5954 =for apidoc sv_rvunweaken
5955
5956 Unweaken a reference: Clear the C<SvWEAKREF> flag on this RV; remove
5957 the backreference to this RV from the array of backreferences
5958 associated with the target SV, increment the refcount of the target.
5959 Silently ignores C<undef> and warns on non-weak references.
5960
5961 =cut
5962 */
5963
5964 SV *
5965 Perl_sv_rvunweaken(pTHX_ SV *const sv)
5966 {
5967     SV *tsv;
5968
5969     PERL_ARGS_ASSERT_SV_RVUNWEAKEN;
5970
5971     if (!SvOK(sv)) /* let undefs pass */
5972         return sv;
5973     if (!SvROK(sv))
5974         Perl_croak(aTHX_ "Can't unweaken a nonreference");
5975     else if (!SvWEAKREF(sv)) {
5976         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Reference is not weak");
5977         return sv;
5978     }
5979     else if (SvREADONLY(sv)) croak_no_modify();
5980
5981     tsv = SvRV(sv);
5982     SvWEAKREF_off(sv);
5983     SvROK_on(sv);
5984     SvREFCNT_inc_NN(tsv);
5985     Perl_sv_del_backref(aTHX_ tsv, sv);
5986     return sv;
5987 }
5988
5989 /*
5990 =for apidoc sv_get_backrefs
5991
5992 If C<sv> is the target of a weak reference then it returns the back
5993 references structure associated with the sv; otherwise return C<NULL>.
5994
5995 When returning a non-null result the type of the return is relevant. If it
5996 is an AV then the elements of the AV are the weak reference RVs which
5997 point at this item. If it is any other type then the item itself is the
5998 weak reference.
5999
6000 See also C<Perl_sv_add_backref()>, C<Perl_sv_del_backref()>,
6001 C<Perl_sv_kill_backrefs()>
6002
6003 =cut
6004 */
6005
6006 SV *
6007 Perl_sv_get_backrefs(SV *const sv)
6008 {
6009     SV *backrefs= NULL;
6010
6011     PERL_ARGS_ASSERT_SV_GET_BACKREFS;
6012
6013     /* find slot to store array or singleton backref */
6014
6015     if (SvTYPE(sv) == SVt_PVHV) {
6016         if (HvHasAUX(sv)) {
6017             struct xpvhv_aux * const iter = HvAUX((HV *)sv);
6018             backrefs = (SV *)iter->xhv_backreferences;
6019         }
6020     } else if (SvMAGICAL(sv)) {
6021         MAGIC *mg = mg_find(sv, PERL_MAGIC_backref);
6022         if (mg)
6023             backrefs = mg->mg_obj;
6024     }
6025     return backrefs;
6026 }
6027
6028 /* Give tsv backref magic if it hasn't already got it, then push a
6029  * back-reference to sv onto the array associated with the backref magic.
6030  *
6031  * As an optimisation, if there's only one backref and it's not an AV,
6032  * store it directly in the HvAUX or mg_obj slot, avoiding the need to
6033  * allocate an AV. (Whether the slot holds an AV tells us whether this is
6034  * active.)
6035  */
6036
6037 /* A discussion about the backreferences array and its refcount:
6038  *
6039  * The AV holding the backreferences is pointed to either as the mg_obj of
6040  * PERL_MAGIC_backref, or in the specific case of a HV, from the
6041  * xhv_backreferences field. The array is created with a refcount
6042  * of 2. This means that if during global destruction the array gets
6043  * picked on before its parent to have its refcount decremented by the
6044  * random zapper, it won't actually be freed, meaning it's still there for
6045  * when its parent gets freed.
6046  *
6047  * When the parent SV is freed, the extra ref is killed by
6048  * Perl_sv_kill_backrefs.  The other ref is killed, in the case of magic,
6049  * by mg_free() / MGf_REFCOUNTED, or for a hash, by Perl_hv_kill_backrefs.
6050  *
6051  * When a single backref SV is stored directly, it is not reference
6052  * counted.
6053  */
6054
6055 void
6056 Perl_sv_add_backref(pTHX_ SV *const tsv, SV *const sv)
6057 {
6058     SV **svp;
6059     AV *av = NULL;
6060     MAGIC *mg = NULL;
6061
6062     PERL_ARGS_ASSERT_SV_ADD_BACKREF;
6063
6064     /* find slot to store array or singleton backref */
6065
6066     if (SvTYPE(tsv) == SVt_PVHV) {
6067         svp = (SV**)Perl_hv_backreferences_p(aTHX_ MUTABLE_HV(tsv));
6068     } else {
6069         if (SvMAGICAL(tsv))
6070             mg = mg_find(tsv, PERL_MAGIC_backref);
6071         if (!mg)
6072             mg = sv_magicext(tsv, NULL, PERL_MAGIC_backref, &PL_vtbl_backref, NULL, 0);
6073         svp = &(mg->mg_obj);
6074     }
6075
6076     /* create or retrieve the array */
6077
6078     if (   (!*svp && SvTYPE(sv) == SVt_PVAV)
6079         || (*svp && SvTYPE(*svp) != SVt_PVAV)
6080     ) {
6081         /* create array */
6082         if (mg)
6083             mg->mg_flags |= MGf_REFCOUNTED;
6084         av = newAV();
6085         AvREAL_off(av);
6086         SvREFCNT_inc_simple_void_NN(av);
6087         /* av now has a refcnt of 2; see discussion above */
6088         av_extend(av, *svp ? 2 : 1);
6089         if (*svp) {
6090             /* move single existing backref to the array */
6091             AvARRAY(av)[++AvFILLp(av)] = *svp; /* av_push() */
6092         }
6093         *svp = (SV*)av;
6094     }
6095     else {
6096         av = MUTABLE_AV(*svp);
6097         if (!av) {
6098             /* optimisation: store single backref directly in HvAUX or mg_obj */
6099             *svp = sv;
6100             return;
6101         }
6102         assert(SvTYPE(av) == SVt_PVAV);
6103         if (AvFILLp(av) >= AvMAX(av)) {
6104             av_extend(av, AvFILLp(av)+1);
6105         }
6106     }
6107     /* push new backref */
6108     AvARRAY(av)[++AvFILLp(av)] = sv; /* av_push() */
6109 }
6110
6111 /* delete a back-reference to ourselves from the backref magic associated
6112  * with the SV we point to.
6113  */
6114
6115 void
6116 Perl_sv_del_backref(pTHX_ SV *const tsv, SV *const sv)
6117 {
6118     SV **svp = NULL;
6119
6120     PERL_ARGS_ASSERT_SV_DEL_BACKREF;
6121
6122     if (SvTYPE(tsv) == SVt_PVHV) {
6123         if (HvHasAUX(tsv))
6124             svp = (SV**)Perl_hv_backreferences_p(aTHX_ MUTABLE_HV(tsv));
6125     }
6126     else if (SvIS_FREED(tsv) && PL_phase == PERL_PHASE_DESTRUCT) {
6127         /* It's possible for the the last (strong) reference to tsv to have
6128            become freed *before* the last thing holding a weak reference.
6129            If both survive longer than the backreferences array, then when
6130            the referent's reference count drops to 0 and it is freed, it's
6131            not able to chase the backreferences, so they aren't NULLed.
6132
6133            For example, a CV holds a weak reference to its stash. If both the
6134            CV and the stash survive longer than the backreferences array,
6135            and the CV gets picked for the SvBREAK() treatment first,
6136            *and* it turns out that the stash is only being kept alive because
6137            of an our variable in the pad of the CV, then midway during CV
6138            destruction the stash gets freed, but CvSTASH() isn't set to NULL.
6139            It ends up pointing to the freed HV. Hence it's chased in here, and
6140            if this block wasn't here, it would hit the !svp panic just below.
6141
6142            I don't believe that "better" destruction ordering is going to help
6143            here - during global destruction there's always going to be the
6144            chance that something goes out of order. We've tried to make it
6145            foolproof before, and it only resulted in evolutionary pressure on
6146            fools. Which made us look foolish for our hubris. :-(
6147         */
6148         return;
6149     }
6150     else {
6151         MAGIC *const mg
6152             = SvMAGICAL(tsv) ? mg_find(tsv, PERL_MAGIC_backref) : NULL;
6153         svp =  mg ? &(mg->mg_obj) : NULL;
6154     }
6155
6156     if (!svp)
6157         Perl_croak(aTHX_ "panic: del_backref, svp=0");
6158     if (!*svp) {
6159         /* It's possible that sv is being freed recursively part way through the
6160            freeing of tsv. If this happens, the backreferences array of tsv has
6161            already been freed, and so svp will be NULL. If this is the case,
6162            we should not panic. Instead, nothing needs doing, so return.  */
6163         if (PL_phase == PERL_PHASE_DESTRUCT && SvREFCNT(tsv) == 0)
6164             return;
6165         Perl_croak(aTHX_ "panic: del_backref, *svp=%p phase=%s refcnt=%" UVuf,
6166                    (void*)*svp, PL_phase_names[PL_phase], (UV)SvREFCNT(tsv));
6167     }
6168
6169     if (SvTYPE(*svp) == SVt_PVAV) {
6170 #ifdef DEBUGGING
6171         int count = 1;
6172 #endif
6173         AV * const av = (AV*)*svp;
6174         SSize_t fill;
6175         assert(!SvIS_FREED(av));
6176         fill = AvFILLp(av);
6177         assert(fill > -1);
6178         svp = AvARRAY(av);
6179         /* for an SV with N weak references to it, if all those
6180          * weak refs are deleted, then sv_del_backref will be called
6181          * N times and O(N^2) compares will be done within the backref
6182          * array. To ameliorate this potential slowness, we:
6183          * 1) make sure this code is as tight as possible;
6184          * 2) when looking for SV, look for it at both the head and tail of the
6185          *    array first before searching the rest, since some create/destroy
6186          *    patterns will cause the backrefs to be freed in order.
6187          */
6188         if (*svp == sv) {
6189             AvARRAY(av)++;
6190             AvMAX(av)--;
6191         }
6192         else {
6193             SV **p = &svp[fill];
6194             SV *const topsv = *p;
6195             if (topsv != sv) {
6196 #ifdef DEBUGGING
6197                 count = 0;
6198 #endif
6199                 while (--p > svp) {
6200                     if (*p == sv) {
6201                         /* We weren't the last entry.
6202                            An unordered list has this property that you
6203                            can take the last element off the end to fill
6204                            the hole, and it's still an unordered list :-)
6205                         */
6206                         *p = topsv;
6207 #ifdef DEBUGGING
6208                         count++;
6209 #else
6210                         break; /* should only be one */
6211 #endif
6212                     }
6213                 }
6214             }
6215         }
6216         assert(count ==1);
6217         AvFILLp(av) = fill-1;
6218     }
6219     else if (SvIS_FREED(*svp) && PL_phase == PERL_PHASE_DESTRUCT) {
6220         /* freed AV; skip */
6221     }
6222     else {
6223         /* optimisation: only a single backref, stored directly */
6224         if (*svp != sv)
6225             Perl_croak(aTHX_ "panic: del_backref, *svp=%p, sv=%p",
6226                        (void*)*svp, (void*)sv);
6227         *svp = NULL;
6228     }
6229
6230 }
6231
6232 void
6233 Perl_sv_kill_backrefs(pTHX_ SV *const sv, AV *const av)
6234 {
6235     SV **svp;
6236     SV **last;
6237     bool is_array;
6238
6239     PERL_ARGS_ASSERT_SV_KILL_BACKREFS;
6240
6241     if (!av)
6242         return;
6243
6244     /* after multiple passes through Perl_sv_clean_all() for a thingy
6245      * that has badly leaked, the backref array may have gotten freed,
6246      * since we only protect it against 1 round of cleanup */
6247     if (SvIS_FREED(av)) {
6248         if (PL_in_clean_all) /* All is fair */
6249             return;
6250         Perl_croak(aTHX_
6251                    "panic: magic_killbackrefs (freed backref AV/SV)");
6252     }
6253
6254
6255     is_array = (SvTYPE(av) == SVt_PVAV);
6256     if (is_array) {
6257         assert(!SvIS_FREED(av));
6258         svp = AvARRAY(av);
6259         if (svp)
6260             last = svp + AvFILLp(av);
6261     }
6262     else {
6263         /* optimisation: only a single backref, stored directly */
6264         svp = (SV**)&av;
6265         last = svp;
6266     }
6267
6268     if (svp) {
6269         while (svp <= last) {
6270             if (*svp) {
6271                 SV *const referrer = *svp;
6272                 if (SvWEAKREF(referrer)) {
6273                     /* XXX Should we check that it hasn't changed? */
6274                     assert(SvROK(referrer));
6275                     SvRV_set(referrer, 0);
6276                     SvOK_off(referrer);
6277                     SvWEAKREF_off(referrer);
6278                     SvSETMAGIC(referrer);
6279                 } else if (SvTYPE(referrer) == SVt_PVGV ||
6280                            SvTYPE(referrer) == SVt_PVLV) {
6281                     assert(SvTYPE(sv) == SVt_PVHV); /* stash backref */
6282                     /* You lookin' at me?  */
6283                     assert(GvSTASH(referrer));
6284                     assert(GvSTASH(referrer) == (const HV *)sv);
6285                     GvSTASH(referrer) = 0;
6286                 } else if (SvTYPE(referrer) == SVt_PVCV ||
6287                            SvTYPE(referrer) == SVt_PVFM) {
6288                     if (SvTYPE(sv) == SVt_PVHV) { /* stash backref */
6289                         /* You lookin' at me?  */
6290                         assert(CvSTASH(referrer));
6291                         assert(CvSTASH(referrer) == (const HV *)sv);
6292                         SvANY(MUTABLE_CV(referrer))->xcv_stash = 0;
6293                     }
6294                     else {
6295                         assert(SvTYPE(sv) == SVt_PVGV);
6296                         /* You lookin' at me?  */
6297                         assert(CvGV(referrer));
6298                         assert(CvGV(referrer) == (const GV *)sv);
6299                         anonymise_cv_maybe(MUTABLE_GV(sv),
6300                                                 MUTABLE_CV(referrer));
6301                     }
6302
6303                 } else {
6304                     Perl_croak(aTHX_
6305                                "panic: magic_killbackrefs (flags=%" UVxf ")",
6306                                (UV)SvFLAGS(referrer));
6307                 }
6308
6309                 if (is_array)
6310                     *svp = NULL;
6311             }
6312             svp++;
6313         }
6314     }
6315     if (is_array) {
6316         AvFILLp(av) = -1;
6317         SvREFCNT_dec_NN(av); /* remove extra count added by sv_add_backref() */
6318     }
6319     return;
6320 }
6321
6322 /*
6323 =for apidoc sv_insert
6324
6325 Inserts and/or replaces a string at the specified offset/length within the SV.
6326 Similar to the Perl C<substr()> function, with C<littlelen> bytes starting at
6327 C<little> replacing C<len> bytes of the string in C<bigstr> starting at
6328 C<offset>.  Handles get magic.
6329
6330 =for apidoc sv_insert_flags
6331
6332 Same as C<sv_insert>, but the extra C<flags> are passed to the
6333 C<SvPV_force_flags> that applies to C<bigstr>.
6334
6335 =cut
6336 */
6337
6338 void
6339 Perl_sv_insert_flags(pTHX_ SV *const bigstr, const STRLEN offset, const STRLEN len, const char *little, const STRLEN littlelen, const U32 flags)
6340 {
6341     char *big;
6342     char *mid;
6343     char *midend;
6344     char *bigend;
6345     SSize_t i;          /* better be sizeof(STRLEN) or bad things happen */
6346     STRLEN curlen;
6347
6348     PERL_ARGS_ASSERT_SV_INSERT_FLAGS;
6349
6350     SvPV_force_flags(bigstr, curlen, flags);
6351     (void)SvPOK_only_UTF8(bigstr);
6352
6353     if (little >= SvPVX(bigstr) &&
6354         little < SvPVX(bigstr) + (SvLEN(bigstr) ? SvLEN(bigstr) : SvCUR(bigstr))) {
6355         /* little is a pointer to within bigstr, since we can reallocate bigstr,
6356            or little...little+littlelen might overlap offset...offset+len we make a copy
6357         */
6358         little = savepvn(little, littlelen);
6359         SAVEFREEPV(little);
6360     }
6361
6362     if (offset + len > curlen) {
6363         SvGROW(bigstr, offset+len+1);
6364         Zero(SvPVX(bigstr)+curlen, offset+len-curlen, char);
6365         SvCUR_set(bigstr, offset+len);
6366     }
6367
6368     SvTAINT(bigstr);
6369     i = littlelen - len;
6370     if (i > 0) {                        /* string might grow */
6371         big = SvGROW(bigstr, SvCUR(bigstr) + i + 1);
6372         mid = big + offset + len;
6373         midend = bigend = big + SvCUR(bigstr);
6374         bigend += i;
6375         *bigend = '\0';
6376         while (midend > mid)            /* shove everything down */
6377             *--bigend = *--midend;
6378         Move(little,big+offset,littlelen,char);
6379         SvCUR_set(bigstr, SvCUR(bigstr) + i);
6380         SvSETMAGIC(bigstr);
6381         return;
6382     }
6383     else if (i == 0) {
6384         Move(little,SvPVX(bigstr)+offset,len,char);
6385         SvSETMAGIC(bigstr);
6386         return;
6387     }
6388
6389     big = SvPVX(bigstr);
6390     mid = big + offset;
6391     midend = mid + len;
6392     bigend = big + SvCUR(bigstr);
6393
6394     if (midend > bigend)
6395         Perl_croak(aTHX_ "panic: sv_insert, midend=%p, bigend=%p",
6396                    midend, bigend);
6397
6398     if (mid - big > bigend - midend) {  /* faster to shorten from end */
6399         if (littlelen) {
6400             Move(little, mid, littlelen,char);
6401             mid += littlelen;
6402         }
6403         i = bigend - midend;
6404         if (i > 0) {
6405             Move(midend, mid, i,char);
6406             mid += i;
6407         }
6408         *mid = '\0';
6409         SvCUR_set(bigstr, mid - big);
6410     }
6411     else if ((i = mid - big)) { /* faster from front */
6412         midend -= littlelen;
6413         mid = midend;
6414         Move(big, midend - i, i, char);
6415         sv_chop(bigstr,midend-i);
6416         if (littlelen)
6417             Move(little, mid, littlelen,char);
6418     }
6419     else if (littlelen) {
6420         midend -= littlelen;
6421         sv_chop(bigstr,midend);
6422         Move(little,midend,littlelen,char);
6423     }
6424     else {
6425         sv_chop(bigstr,midend);
6426     }
6427     SvSETMAGIC(bigstr);
6428 }
6429
6430 /*
6431 =for apidoc sv_replace
6432
6433 Make the first argument a copy of the second, then delete the original.
6434 The target SV physically takes over ownership of the body of the source SV
6435 and inherits its flags; however, the target keeps any magic it owns,
6436 and any magic in the source is discarded.
6437 Note that this is a rather specialist SV copying operation; most of the
6438 time you'll want to use C<sv_setsv> or one of its many macro front-ends.
6439
6440 =cut
6441 */
6442
6443 void
6444 Perl_sv_replace(pTHX_ SV *const sv, SV *const nsv)
6445 {
6446     const U32 refcnt = SvREFCNT(sv);
6447
6448     PERL_ARGS_ASSERT_SV_REPLACE;
6449
6450     SV_CHECK_THINKFIRST_COW_DROP(sv);
6451     if (SvREFCNT(nsv) != 1) {
6452         Perl_croak(aTHX_ "panic: reference miscount on nsv in sv_replace()"
6453                    " (%" UVuf " != 1)", (UV) SvREFCNT(nsv));
6454     }
6455     if (SvMAGICAL(sv)) {
6456         if (SvMAGICAL(nsv))
6457             mg_free(nsv);
6458         else
6459             sv_upgrade(nsv, SVt_PVMG);
6460         SvMAGIC_set(nsv, SvMAGIC(sv));
6461         SvFLAGS(nsv) |= SvMAGICAL(sv);
6462         SvMAGICAL_off(sv);
6463         SvMAGIC_set(sv, NULL);
6464     }
6465     SvREFCNT(sv) = 0;
6466     sv_clear(sv);
6467     assert(!SvREFCNT(sv));
6468 #ifdef DEBUG_LEAKING_SCALARS
6469     sv->sv_flags  = nsv->sv_flags;
6470     sv->sv_any    = nsv->sv_any;
6471     sv->sv_refcnt = nsv->sv_refcnt;
6472     sv->sv_u      = nsv->sv_u;
6473 #else
6474     StructCopy(nsv,sv,SV);
6475 #endif
6476     if(SvTYPE(sv) == SVt_IV) {
6477         SET_SVANY_FOR_BODYLESS_IV(sv);
6478     }
6479
6480
6481     SvREFCNT(sv) = refcnt;
6482     SvFLAGS(nsv) |= SVTYPEMASK;         /* Mark as freed */
6483     SvREFCNT(nsv) = 0;
6484     del_SV(nsv);
6485 }
6486
6487 /* We're about to free a GV which has a CV that refers back to us.
6488  * If that CV will outlive us, make it anonymous (i.e. fix up its CvGV
6489  * field) */
6490
6491 STATIC void
6492 S_anonymise_cv_maybe(pTHX_ GV *gv, CV* cv)
6493 {
6494     SV *gvname;
6495     GV *anongv;
6496
6497     PERL_ARGS_ASSERT_ANONYMISE_CV_MAYBE;
6498
6499     /* be assertive! */
6500     assert(SvREFCNT(gv) == 0);
6501     assert(isGV(gv) && isGV_with_GP(gv));
6502     assert(GvGP(gv));
6503     assert(!CvANON(cv));
6504     assert(CvGV(cv) == gv);
6505     assert(!CvNAMED(cv));
6506
6507     /* will the CV shortly be freed by gp_free() ? */
6508     if (GvCV(gv) == cv && GvGP(gv)->gp_refcnt < 2 && SvREFCNT(cv) < 2) {
6509         SvANY(cv)->xcv_gv_u.xcv_gv = NULL;
6510         return;
6511     }
6512
6513     /* if not, anonymise: */
6514     gvname = (GvSTASH(gv) && HvNAME(GvSTASH(gv)) && HvENAME(GvSTASH(gv)))
6515                     ? newSVhek(HvENAME_HEK(GvSTASH(gv)))
6516                     : newSVpvn_flags( "__ANON__", 8, 0 );
6517     sv_catpvs(gvname, "::__ANON__");
6518     anongv = gv_fetchsv(gvname, GV_ADDMULTI, SVt_PVCV);
6519     SvREFCNT_dec_NN(gvname);
6520
6521     CvANON_on(cv);
6522     CvCVGV_RC_on(cv);
6523     SvANY(cv)->xcv_gv_u.xcv_gv = MUTABLE_GV(SvREFCNT_inc(anongv));
6524 }
6525
6526
6527 /*
6528 =for apidoc sv_clear
6529
6530 Clear an SV: call any destructors, free up any memory used by the body,
6531 and free the body itself.  The SV's head is I<not> freed, although
6532 its type is set to all 1's so that it won't inadvertently be assumed
6533 to be live during global destruction etc.
6534 This function should only be called when C<REFCNT> is zero.  Most of the time
6535 you'll want to call C<sv_free()> (or its macro wrapper C<SvREFCNT_dec>)
6536 instead.
6537
6538 =cut
6539 */
6540
6541 void
6542 Perl_sv_clear(pTHX_ SV *const orig_sv)
6543 {
6544     SV* iter_sv = NULL;
6545     SV* next_sv = NULL;
6546     SV *sv = orig_sv;
6547     STRLEN hash_index = 0; /* initialise to make Coverity et al happy.
6548                               Not strictly necessary */
6549
6550     PERL_ARGS_ASSERT_SV_CLEAR;
6551
6552     /* within this loop, sv is the SV currently being freed, and
6553      * iter_sv is the most recent AV or whatever that's being iterated
6554      * over to provide more SVs */
6555
6556     while (sv) {
6557         U32 type = SvTYPE(sv);
6558         HV *stash;
6559
6560         assert(SvREFCNT(sv) == 0);
6561         assert(SvTYPE(sv) != (svtype)SVTYPEMASK);
6562
6563         if (type <= SVt_IV) {
6564             /* Historically this check on type was needed so that the code to
6565              * free bodies wasn't reached for these types, because the arena
6566              * slots were re-used for HEs and pointer table entries. The
6567              * metadata table `bodies_by_type` had the information for the sizes
6568              * for HEs and PTEs, hence the code here had to have a special-case
6569              * check to ensure that the "regular" body freeing code wasn't
6570              * reached, and get confused by the "lies" in `bodies_by_type`.
6571              *
6572              * However, it hasn't actually been needed for that reason since
6573              * Aug 2010 (commit 829cd18aa7f45221), because `bodies_by_type` was
6574              * changed to always hold the accurate metadata for the SV types.
6575              * This was possible because PTEs were no longer allocated from the
6576              * "SVt_IV" arena, and the code to allocate HEs from the "SVt_NULL"
6577              * arena is entirely in hv.c, so doesn't access the table.
6578              *
6579              * Some sort of check is still needed to handle SVt_IVs - pure RVs
6580              * need to take one code path which is common with RVs stored in
6581              * SVt_PV (or larger), but pure IVs mustn't take the "PV but not RV"
6582              * path, as SvPVX() doesn't point to valid memory.
6583              *
6584              * Hence this code is still the most efficient way to handle this.
6585              */
6586
6587             if (SvROK(sv))
6588                 goto free_rv;
6589             SvFLAGS(sv) &= SVf_BREAK;
6590             SvFLAGS(sv) |= SVTYPEMASK;
6591             goto free_head;
6592         }
6593
6594         /* objs are always >= MG, but pad names use the SVs_OBJECT flag
6595            for another purpose  */
6596         assert(!SvOBJECT(sv) || type >= SVt_PVMG);
6597
6598         if (type >= SVt_PVMG) {
6599             if (SvOBJECT(sv)) {
6600                 if (!curse(sv, 1)) goto get_next_sv;
6601                 type = SvTYPE(sv); /* destructor may have changed it */
6602             }
6603             /* Free back-references before magic, in case the magic calls
6604              * Perl code that has weak references to sv. */
6605             if (type == SVt_PVHV) {
6606                 Perl_hv_kill_backrefs(aTHX_ MUTABLE_HV(sv));
6607                 if (SvMAGIC(sv))
6608                     mg_free(sv);
6609             }
6610             else if (SvMAGIC(sv)) {
6611                 /* Free back-references before other types of magic. */
6612                 sv_unmagic(sv, PERL_MAGIC_backref);
6613                 mg_free(sv);
6614             }
6615             SvMAGICAL_off(sv);
6616         }
6617         switch (type) {
6618             /* case SVt_INVLIST: */
6619         case SVt_PVIO:
6620             if (IoIFP(sv) &&
6621                 IoIFP(sv) != PerlIO_stdin() &&
6622                 IoIFP(sv) != PerlIO_stdout() &&
6623                 IoIFP(sv) != PerlIO_stderr() &&
6624                 !(IoFLAGS(sv) & IOf_FAKE_DIRP))
6625             {
6626                 io_close(MUTABLE_IO(sv), NULL, FALSE,
6627                          (IoTYPE(sv) == IoTYPE_WRONLY ||
6628                           IoTYPE(sv) == IoTYPE_RDWR   ||
6629                           IoTYPE(sv) == IoTYPE_APPEND));
6630             }
6631             if (IoDIRP(sv) && !(IoFLAGS(sv) & IOf_FAKE_DIRP))
6632                 PerlDir_close(IoDIRP(sv));
6633             IoDIRP(sv) = (DIR*)NULL;
6634             Safefree(IoTOP_NAME(sv));
6635             Safefree(IoFMT_NAME(sv));
6636             Safefree(IoBOTTOM_NAME(sv));
6637             if ((const GV *)sv == PL_statgv)
6638                 PL_statgv = NULL;
6639             goto freescalar;
6640         case SVt_REGEXP:
6641             /* FIXME for plugins */
6642             pregfree2((REGEXP*) sv);
6643             goto freescalar;
6644         case SVt_PVCV:
6645         case SVt_PVFM:
6646             cv_undef(MUTABLE_CV(sv));
6647             /* If we're in a stash, we don't own a reference to it.
6648              * However it does have a back reference to us, which needs to
6649              * be cleared.  */
6650             if ((stash = CvSTASH(sv)))
6651                 sv_del_backref(MUTABLE_SV(stash), sv);
6652             goto freescalar;
6653         case SVt_PVHV:
6654             if (HvTOTALKEYS((HV*)sv) > 0) {
6655                 const HEK *hek;
6656                 /* this statement should match the one at the beginning of
6657                  * hv_undef_flags() */
6658                 if (   PL_phase != PERL_PHASE_DESTRUCT
6659                     && (hek = HvNAME_HEK((HV*)sv)))
6660                 {
6661                     if (PL_stashcache) {
6662                         DEBUG_o(Perl_deb(aTHX_
6663                             "sv_clear clearing PL_stashcache for '%" HEKf
6664                             "'\n",
6665                              HEKfARG(hek)));
6666                         (void)hv_deletehek(PL_stashcache,
6667                                            hek, G_DISCARD);
6668                     }
6669                     hv_name_set((HV*)sv, NULL, 0, 0);
6670                 }
6671
6672                 /* save old iter_sv in unused SvSTASH field */
6673                 assert(!SvOBJECT(sv));
6674                 SvSTASH(sv) = (HV*)iter_sv;
6675                 iter_sv = sv;
6676
6677                 /* save old hash_index in unused SvMAGIC field */
6678                 assert(!SvMAGICAL(sv));
6679                 assert(!SvMAGIC(sv));
6680                 ((XPVMG*) SvANY(sv))->xmg_u.xmg_hash_index = hash_index;
6681                 hash_index = 0;
6682
6683                 next_sv = Perl_hfree_next_entry(aTHX_ (HV*)sv, &hash_index);
6684                 goto get_next_sv; /* process this new sv */
6685             }
6686             /* free empty hash */
6687             Perl_hv_undef_flags(aTHX_ MUTABLE_HV(sv), HV_NAME_SETALL);
6688             assert(!HvARRAY((HV*)sv));
6689             break;
6690         case SVt_PVAV:
6691             {
6692                 AV* av = MUTABLE_AV(sv);
6693                 if (PL_comppad == av) {
6694                     PL_comppad = NULL;
6695                     PL_curpad = NULL;
6696                 }
6697                 if (AvREAL(av) && AvFILLp(av) > -1) {
6698                     next_sv = AvARRAY(av)[AvFILLp(av)--];
6699                     /* save old iter_sv in top-most slot of AV,
6700                      * and pray that it doesn't get wiped in the meantime */
6701                     AvARRAY(av)[AvMAX(av)] = iter_sv;
6702                     iter_sv = sv;
6703                     goto get_next_sv; /* process this new sv */
6704                 }
6705                 Safefree(AvALLOC(av));
6706             }
6707
6708             break;
6709         case SVt_PVLV:
6710             if (LvTYPE(sv) == 'T') { /* for tie: return HE to pool */
6711                 SvREFCNT_dec(HeKEY_sv((HE*)LvTARG(sv)));
6712                 HeNEXT((HE*)LvTARG(sv)) = PL_hv_fetch_ent_mh;
6713                 PL_hv_fetch_ent_mh = (HE*)LvTARG(sv);
6714             }
6715             else if (LvTYPE(sv) != 't') /* unless tie: unrefcnted fake SV**  */
6716                 SvREFCNT_dec(LvTARG(sv));
6717             if (isREGEXP(sv)) {
6718                 /* This PVLV has had a REGEXP assigned to it - the memory
6719                  * normally used to store SvLEN instead points to a regex body.
6720                  * Retrieving the pointer to the regex body from the correct
6721                  * location is normally abstracted by ReANY(), which handles
6722                  * both SVt_PVLV and SVt_REGEXP
6723                  *
6724                  * This code is unwinding the storage specific to SVt_PVLV.
6725                  * We get the body pointer directly from the union, free it,
6726                  * then set SvLEN to whatever value was in the now-freed regex
6727                  * body. The PVX buffer is shared by multiple re's and only
6728                  * freed once, by the re whose SvLEN is non-null.
6729                  *
6730                  * Perl_sv_force_normal_flags() also has code to free this
6731                  * hidden body - it swaps the body into a temporary SV it has
6732                  * just allocated, then frees that SV. That causes execution
6733                  * to reach the SVt_REGEXP: case about 60 lines earlier in this
6734                  * function.
6735                  *
6736                  * See Perl_reg_temp_copy() for the code that sets up this
6737                  * REGEXP body referenced by the PVLV. */
6738                 struct regexp *r = ((XPV*)SvANY(sv))->xpv_len_u.xpvlenu_rx;
6739                 STRLEN len = r->xpv_len;
6740                 pregfree2((REGEXP*) sv);
6741                 del_body_by_type(r, SVt_REGEXP);
6742                 SvLEN_set((sv), len);
6743                 goto freescalar;
6744             }
6745             /* FALLTHROUGH */
6746         case SVt_PVGV:
6747             if (isGV_with_GP(sv)) {
6748                 if(GvCVu((const GV *)sv) && (stash = GvSTASH(MUTABLE_GV(sv)))
6749                    && HvENAME_get(stash))
6750                     mro_method_changed_in(stash);
6751                 gp_free(MUTABLE_GV(sv));
6752                 if (GvNAME_HEK(sv))
6753                     unshare_hek(GvNAME_HEK(sv));
6754                 /* If we're in a stash, we don't own a reference to it.
6755                  * However it does have a back reference to us, which
6756                  * needs to be cleared.  */
6757                 if ((stash = GvSTASH(sv)))
6758                         sv_del_backref(MUTABLE_SV(stash), sv);
6759             }
6760             /* FIXME. There are probably more unreferenced pointers to SVs
6761              * in the interpreter struct that we should check and tidy in
6762              * a similar fashion to this:  */
6763             /* See also S_sv_unglob, which does the same thing. */
6764             if ((const GV *)sv == PL_last_in_gv)
6765                 PL_last_in_gv = NULL;
6766             else if ((const GV *)sv == PL_statgv)
6767                 PL_statgv = NULL;
6768             else if ((const GV *)sv == PL_stderrgv)
6769                 PL_stderrgv = NULL;
6770             /* FALLTHROUGH */
6771         case SVt_PVMG:
6772         case SVt_PVNV:
6773         case SVt_PVIV:
6774         case SVt_INVLIST:
6775         case SVt_PV:
6776           freescalar:
6777             /* Don't bother with SvOOK_off(sv); as we're only going to
6778              * free it.  */
6779             if (SvOOK(sv)) {
6780                 STRLEN offset;
6781                 SvOOK_offset(sv, offset);
6782                 SvPV_set(sv, SvPVX_mutable(sv) - offset);
6783                 /* Don't even bother with turning off the OOK flag.  */
6784             }
6785             if (SvROK(sv)) {
6786             free_rv:
6787                 {
6788                     SV * const target = SvRV(sv);
6789                     if (SvWEAKREF(sv))
6790                         sv_del_backref(target, sv);
6791                     else
6792                         next_sv = target;
6793                 }
6794             }
6795 #ifdef PERL_ANY_COW
6796             else if (SvPVX_const(sv)
6797                      && !(SvTYPE(sv) == SVt_PVIO
6798                      && !(IoFLAGS(sv) & IOf_FAKE_DIRP)))
6799             {
6800                 if (SvIsCOW(sv)) {
6801 #ifdef DEBUGGING
6802                     if (DEBUG_C_TEST) {
6803                         PerlIO_printf(Perl_debug_log, "Copy on write: clear\n");
6804                         sv_dump(sv);
6805                     }
6806 #endif
6807                     if (SvIsCOW_static(sv)) {
6808                         SvLEN_set(sv, 0);
6809                     }
6810                     else if (SvIsCOW_shared_hash(sv)) {
6811                         unshare_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sv)));
6812                     }
6813                     else {
6814                         if (CowREFCNT(sv)) {
6815                             sv_buf_to_rw(sv);
6816                             CowREFCNT(sv)--;
6817                             sv_buf_to_ro(sv);
6818                             SvLEN_set(sv, 0);
6819                         }
6820                     }
6821                 }
6822                 if (SvLEN(sv)) {
6823                     Safefree(SvPVX_mutable(sv));
6824                 }
6825             }
6826 #else
6827             else if (SvPVX_const(sv) && SvLEN(sv)
6828                      && !(SvTYPE(sv) == SVt_PVIO
6829                      && !(IoFLAGS(sv) & IOf_FAKE_DIRP)))
6830                 Safefree(SvPVX_mutable(sv));
6831             else if (SvPVX_const(sv) && SvIsCOW(sv)) {
6832                 unshare_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sv)));
6833             }
6834 #endif
6835             break;
6836         case SVt_NV:
6837             break;
6838         }
6839
6840       free_body:
6841
6842         {
6843             U32 arena_index;
6844             const struct body_details *sv_type_details;
6845
6846             if (type == SVt_PVHV && HvHasAUX(sv)) {
6847                 arena_index = HVAUX_ARENA_ROOT_IX;
6848                 sv_type_details = &fake_hv_with_aux;
6849             }
6850             else {
6851                 arena_index = type;
6852                 sv_type_details = bodies_by_type + arena_index;
6853             }
6854
6855             SvFLAGS(sv) &= SVf_BREAK;
6856             SvFLAGS(sv) |= SVTYPEMASK;
6857
6858             if (sv_type_details->arena) {
6859                 del_body(((char *)SvANY(sv) + sv_type_details->offset),
6860                          &PL_body_roots[arena_index]);
6861             }
6862             else if (sv_type_details->body_size) {
6863                 safefree(SvANY(sv));
6864             }
6865         }
6866
6867       free_head:
6868         /* caller is responsible for freeing the head of the original sv */
6869         if (sv != orig_sv && !SvREFCNT(sv))
6870             del_SV(sv);
6871
6872         /* grab and free next sv, if any */
6873       get_next_sv:
6874         while (1) {
6875             sv = NULL;
6876             if (next_sv) {
6877                 sv = next_sv;
6878                 next_sv = NULL;
6879             }
6880             else if (!iter_sv) {
6881                 break;
6882             } else if (SvTYPE(iter_sv) == SVt_PVAV) {
6883                 AV *const av = (AV*)iter_sv;
6884                 if (AvFILLp(av) > -1) {
6885                     sv = AvARRAY(av)[AvFILLp(av)--];
6886                 }
6887                 else { /* no more elements of current AV to free */
6888                     sv = iter_sv;
6889                     type = SvTYPE(sv);
6890                     /* restore previous value, squirrelled away */
6891                     iter_sv = AvARRAY(av)[AvMAX(av)];
6892                     Safefree(AvALLOC(av));
6893                     goto free_body;
6894                 }
6895             } else if (SvTYPE(iter_sv) == SVt_PVHV) {
6896                 sv = Perl_hfree_next_entry(aTHX_ (HV*)iter_sv, &hash_index);
6897                 if (!sv && !HvTOTALKEYS((HV *)iter_sv)) {
6898                     /* no more elements of current HV to free */
6899                     sv = iter_sv;
6900                     type = SvTYPE(sv);
6901                     /* Restore previous values of iter_sv and hash_index,
6902                      * squirrelled away */
6903                     assert(!SvOBJECT(sv));
6904                     iter_sv = (SV*)SvSTASH(sv);
6905                     assert(!SvMAGICAL(sv));
6906                     hash_index = ((XPVMG*) SvANY(sv))->xmg_u.xmg_hash_index;
6907 #ifdef DEBUGGING
6908                     /* perl -DA does not like rubbish in SvMAGIC. */
6909                     SvMAGIC_set(sv, 0);
6910 #endif
6911
6912                     /* free any remaining detritus from the hash struct */
6913                     Perl_hv_undef_flags(aTHX_ MUTABLE_HV(sv), HV_NAME_SETALL);
6914                     assert(!HvARRAY((HV*)sv));
6915                     goto free_body;
6916                 }
6917             }
6918
6919             /* unrolled SvREFCNT_dec and sv_free2 follows: */
6920
6921             if (!sv)
6922                 continue;
6923             if (!SvREFCNT(sv)) {
6924                 sv_free(sv);
6925                 continue;
6926             }
6927             if (--(SvREFCNT(sv)))
6928                 continue;
6929 #ifdef DEBUGGING
6930             if (SvTEMP(sv)) {
6931                 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEBUGGING),
6932                          "Attempt to free temp prematurely: SV 0x%" UVxf
6933                          pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
6934                 continue;
6935             }
6936 #endif
6937             if (SvIMMORTAL(sv)) {
6938                 /* make sure SvREFCNT(sv)==0 happens very seldom */
6939                 SvREFCNT(sv) = SvREFCNT_IMMORTAL;
6940                 continue;
6941             }
6942             break;
6943         } /* while 1 */
6944
6945     } /* while sv */
6946 }
6947
6948 /* This routine curses the sv itself, not the object referenced by sv. So
6949    sv does not have to be ROK. */
6950
6951 static bool
6952 S_curse(pTHX_ SV * const sv, const bool check_refcnt) {
6953     PERL_ARGS_ASSERT_CURSE;
6954     assert(SvOBJECT(sv));
6955
6956     if (PL_defstash &&  /* Still have a symbol table? */
6957         SvDESTROYABLE(sv))
6958     {
6959         dSP;
6960         HV* stash;
6961         do {
6962           stash = SvSTASH(sv);
6963           assert(SvTYPE(stash) == SVt_PVHV);
6964           if (HvNAME(stash)) {
6965             CV* destructor = NULL;
6966             struct mro_meta *meta;
6967
6968             assert (HvHasAUX(stash));
6969
6970             DEBUG_o( Perl_deb(aTHX_ "Looking for DESTROY method for %s\n",
6971                          HvNAME(stash)) );
6972
6973             /* don't make this an initialization above the assert, since it needs
6974                an AUX structure */
6975             meta = HvMROMETA(stash);
6976             if (meta->destroy_gen && meta->destroy_gen == PL_sub_generation) {
6977                 destructor = meta->destroy;
6978                 DEBUG_o( Perl_deb(aTHX_ "Using cached DESTROY method %p for %s\n",
6979                              (void *)destructor, HvNAME(stash)) );
6980             }
6981             else {
6982                 bool autoload = FALSE;
6983                 GV *gv =
6984                     gv_fetchmeth_pvn(stash, S_destroy, S_destroy_len, -1, 0);
6985                 if (gv)
6986                     destructor = GvCV(gv);
6987                 if (!destructor) {
6988                     gv = gv_autoload_pvn(stash, S_destroy, S_destroy_len,
6989                                          GV_AUTOLOAD_ISMETHOD);
6990                     if (gv)
6991                         destructor = GvCV(gv);
6992                     if (destructor)
6993                         autoload = TRUE;
6994                 }
6995                 /* we don't cache AUTOLOAD for DESTROY, since this code
6996                    would then need to set $__PACKAGE__::AUTOLOAD, or the
6997                    equivalent for XS AUTOLOADs */
6998                 if (!autoload) {
6999                     meta->destroy_gen = PL_sub_generation;
7000                     meta->destroy = destructor;
7001
7002                     DEBUG_o( Perl_deb(aTHX_ "Set cached DESTROY method %p for %s\n",
7003                                       (void *)destructor, HvNAME(stash)) );
7004                 }
7005                 else {
7006                     DEBUG_o( Perl_deb(aTHX_ "Not caching AUTOLOAD for DESTROY method for %s\n",
7007                                       HvNAME(stash)) );
7008                 }
7009             }
7010             assert(!destructor || SvTYPE(destructor) == SVt_PVCV);
7011             if (destructor
7012                 /* A constant subroutine can have no side effects, so
7013                    don't bother calling it.  */
7014                 && !CvCONST(destructor)
7015                 /* Don't bother calling an empty destructor or one that
7016                    returns immediately. */
7017                 && (CvISXSUB(destructor)
7018                 || (CvSTART(destructor)
7019                     && (CvSTART(destructor)->op_next->op_type
7020                                         != OP_LEAVESUB)
7021                     && (CvSTART(destructor)->op_next->op_type
7022                                         != OP_PUSHMARK
7023                         || CvSTART(destructor)->op_next->op_next->op_type
7024                                         != OP_RETURN
7025                        )
7026                    ))
7027                )
7028             {
7029                 SV* const tmpref = newRV(sv);
7030                 SvREADONLY_on(tmpref); /* DESTROY() could be naughty */
7031                 ENTER;
7032                 PUSHSTACKi(PERLSI_DESTROY);
7033                 EXTEND(SP, 2);
7034                 PUSHMARK(SP);
7035                 PUSHs(tmpref);
7036                 PUTBACK;
7037                 call_sv(MUTABLE_SV(destructor),
7038                             G_DISCARD|G_EVAL|G_KEEPERR|G_VOID);
7039                 POPSTACK;
7040                 SPAGAIN;
7041                 LEAVE;
7042                 if(SvREFCNT(tmpref) < 2) {
7043                     /* tmpref is not kept alive! */
7044                     SvREFCNT(sv)--;
7045                     SvRV_set(tmpref, NULL);
7046                     SvROK_off(tmpref);
7047                 }
7048                 SvREFCNT_dec_NN(tmpref);
7049             }
7050           }
7051         } while (SvOBJECT(sv) && SvSTASH(sv) != stash);
7052
7053
7054         if (check_refcnt && SvREFCNT(sv)) {
7055             if (PL_in_clean_objs)
7056                 Perl_croak(aTHX_
7057                   "DESTROY created new reference to dead object '%" HEKf "'",
7058                    HEKfARG(HvNAME_HEK(stash)));
7059             /* DESTROY gave object new lease on life */
7060             return FALSE;
7061         }
7062     }
7063
7064     if (SvOBJECT(sv)) {
7065         HV * const stash = SvSTASH(sv);
7066         /* Curse before freeing the stash, as freeing the stash could cause
7067            a recursive call into S_curse. */
7068         SvOBJECT_off(sv);       /* Curse the object. */
7069         SvSTASH_set(sv,0);      /* SvREFCNT_dec may try to read this */
7070         SvREFCNT_dec(stash); /* possibly of changed persuasion */
7071     }
7072     return TRUE;
7073 }
7074
7075 /*
7076 =for apidoc sv_newref
7077
7078 Increment an SV's reference count.  Use the C<SvREFCNT_inc()> wrapper
7079 instead.
7080
7081 =cut
7082 */
7083
7084 SV *
7085 Perl_sv_newref(pTHX_ SV *const sv)
7086 {
7087     PERL_UNUSED_CONTEXT;
7088     if (sv)
7089         (SvREFCNT(sv))++;
7090     return sv;
7091 }
7092
7093 /*
7094 =for apidoc sv_free
7095
7096 Decrement an SV's reference count, and if it drops to zero, call
7097 C<sv_clear> to invoke destructors and free up any memory used by
7098 the body; finally, deallocating the SV's head itself.
7099 Normally called via a wrapper macro C<SvREFCNT_dec>.
7100
7101 =cut
7102 */
7103
7104 void
7105 Perl_sv_free(pTHX_ SV *const sv)
7106 {
7107     SvREFCNT_dec(sv);
7108 }
7109
7110
7111 /* Private helper function for SvREFCNT_dec().
7112  * Called with rc set to original SvREFCNT(sv), where rc == 0 or 1 */
7113
7114 void
7115 Perl_sv_free2(pTHX_ SV *const sv, const U32 rc)
7116 {
7117
7118     PERL_ARGS_ASSERT_SV_FREE2;
7119
7120     if (LIKELY( rc == 1 )) {
7121         /* normal case */
7122         SvREFCNT(sv) = 0;
7123
7124 #ifdef DEBUGGING
7125         if (SvTEMP(sv)) {
7126             Perl_ck_warner_d(aTHX_ packWARN(WARN_DEBUGGING),
7127                              "Attempt to free temp prematurely: SV 0x%" UVxf
7128                              pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
7129             return;
7130         }
7131 #endif
7132         if (SvIMMORTAL(sv)) {
7133             /* make sure SvREFCNT(sv)==0 happens very seldom */
7134             SvREFCNT(sv) = SvREFCNT_IMMORTAL;
7135             return;
7136         }
7137         sv_clear(sv);
7138         if (! SvREFCNT(sv)) /* may have have been resurrected */
7139             del_SV(sv);
7140         return;
7141     }
7142
7143     /* handle exceptional cases */
7144
7145     assert(rc == 0);
7146
7147     if (SvFLAGS(sv) & SVf_BREAK)
7148         /* this SV's refcnt has been artificially decremented to
7149          * trigger cleanup */
7150         return;
7151     if (PL_in_clean_all) /* All is fair */
7152         return;
7153     if (SvIMMORTAL(sv)) {
7154         /* make sure SvREFCNT(sv)==0 happens very seldom */
7155         SvREFCNT(sv) = SvREFCNT_IMMORTAL;
7156         return;
7157     }
7158     if (ckWARN_d(WARN_INTERNAL)) {
7159 #ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
7160         Perl_dump_sv_child(aTHX_ sv);
7161 #else
7162     #ifdef DEBUG_LEAKING_SCALARS
7163         sv_dump(sv);
7164     #endif
7165 #ifdef DEBUG_LEAKING_SCALARS_ABORT
7166         if (PL_warnhook == PERL_WARNHOOK_FATAL
7167             || ckDEAD(packWARN(WARN_INTERNAL))) {
7168             /* Don't let Perl_warner cause us to escape our fate:  */
7169             abort();
7170         }
7171 #endif
7172         /* This may not return:  */
7173         Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
7174                     "Attempt to free unreferenced scalar: SV 0x%" UVxf
7175                     pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
7176 #endif
7177     }
7178 #ifdef DEBUG_LEAKING_SCALARS_ABORT
7179     abort();
7180 #endif
7181
7182 }
7183
7184
7185 /*
7186 =for apidoc sv_len
7187
7188 Returns the length of the string in the SV.  Handles magic and type
7189 coercion and sets the UTF8 flag appropriately.  See also C<L</SvCUR>>, which
7190 gives raw access to the C<xpv_cur> slot.
7191
7192 =cut
7193 */
7194
7195 STRLEN
7196 Perl_sv_len(pTHX_ SV *const sv)
7197 {
7198     STRLEN len;
7199
7200     if (!sv)
7201         return 0;
7202
7203     (void)SvPV_const(sv, len);
7204     return len;
7205 }
7206
7207 /*
7208 =for apidoc sv_len_utf8
7209 =for apidoc_item sv_len_utf8_nomg
7210
7211 These return the number of characters in the string in an SV, counting wide
7212 UTF-8 bytes as a single character.  Both handle type coercion.
7213 They differ only in that C<sv_len_utf8> performs 'get' magic;
7214 C<sv_len_utf8_nomg> skips any magic.
7215
7216 =cut
7217 */
7218
7219 /*
7220  * The length is cached in PERL_MAGIC_utf8, in the mg_len field.  Also the
7221  * mg_ptr is used, by sv_pos_u2b() and sv_pos_b2u() - see the comments below.
7222  * (Note that the mg_len is not the length of the mg_ptr field.
7223  * This allows the cache to store the character length of the string without
7224  * needing to malloc() extra storage to attach to the mg_ptr.)
7225  *
7226  */
7227
7228 STRLEN
7229 Perl_sv_len_utf8(pTHX_ SV *const sv)
7230 {
7231     if (!sv)
7232         return 0;
7233
7234     SvGETMAGIC(sv);
7235     return sv_len_utf8_nomg(sv);
7236 }
7237
7238 STRLEN
7239 Perl_sv_len_utf8_nomg(pTHX_ SV * const sv)
7240 {
7241     STRLEN len;
7242     const U8 *s = (U8*)SvPV_nomg_const(sv, len);
7243
7244     PERL_ARGS_ASSERT_SV_LEN_UTF8_NOMG;
7245
7246     if (PL_utf8cache && SvUTF8(sv)) {
7247             STRLEN ulen;
7248             MAGIC *mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
7249
7250             if (mg && (mg->mg_len != -1 || mg->mg_ptr)) {
7251                 if (mg->mg_len != -1)
7252                     ulen = mg->mg_len;
7253                 else {
7254                     /* We can use the offset cache for a headstart.
7255                        The longer value is stored in the first pair.  */
7256                     STRLEN *cache = (STRLEN *) mg->mg_ptr;
7257
7258                     ulen = cache[0] + Perl_utf8_length(aTHX_ s + cache[1],
7259                                                        s + len);
7260                 }
7261
7262                 if (PL_utf8cache < 0) {
7263                     const STRLEN real = Perl_utf8_length(aTHX_ s, s + len);
7264                     assert_uft8_cache_coherent("sv_len_utf8", ulen, real, sv);
7265                 }
7266             }
7267             else {
7268                 ulen = Perl_utf8_length(aTHX_ s, s + len);
7269                 utf8_mg_len_cache_update(sv, &mg, ulen);
7270             }
7271             return ulen;
7272     }
7273     return SvUTF8(sv) ? Perl_utf8_length(aTHX_ s, s + len) : len;
7274 }
7275
7276 /* Walk forwards to find the byte corresponding to the passed in UTF-8
7277    offset.  */
7278 static STRLEN
7279 S_sv_pos_u2b_forwards(const U8 *const start, const U8 *const send,
7280                       STRLEN *const uoffset_p, bool *const at_end,
7281                       bool* canonical_position)
7282 {
7283     const U8 *s = start;
7284     STRLEN uoffset = *uoffset_p;
7285
7286     PERL_ARGS_ASSERT_SV_POS_U2B_FORWARDS;
7287
7288     while (s < send && uoffset) {
7289         --uoffset;
7290         s += UTF8SKIP(s);
7291     }
7292     if (s == send) {
7293         *at_end = TRUE;
7294     }
7295     else if (s > send) {
7296         *at_end = TRUE;
7297         /* This is the existing behaviour. Possibly it should be a croak, as
7298            it's actually a bounds error  */
7299         s = send;
7300     }
7301     /* If the unicode position is beyond the end, we return the end but
7302        shouldn't cache that position */
7303     *canonical_position = (uoffset == 0);
7304     *uoffset_p -= uoffset;
7305     return s - start;
7306 }
7307
7308 /* Given the length of the string in both bytes and UTF-8 characters, decide
7309    whether to walk forwards or backwards to find the byte corresponding to
7310    the passed in UTF-8 offset.  */
7311 static STRLEN
7312 S_sv_pos_u2b_midway(const U8 *const start, const U8 *send,
7313                     STRLEN uoffset, const STRLEN uend)
7314 {
7315     STRLEN backw = uend - uoffset;
7316
7317     PERL_ARGS_ASSERT_SV_POS_U2B_MIDWAY;
7318
7319     if (uoffset < 2 * backw) {
7320         /* The assumption is that going forwards is twice the speed of going
7321            forward (that's where the 2 * backw comes from).
7322            (The real figure of course depends on the UTF-8 data.)  */
7323         const U8 *s = start;
7324
7325         while (s < send && uoffset--)
7326             s += UTF8SKIP(s);
7327         assert (s <= send);
7328         if (s > send)
7329             s = send;
7330         return s - start;
7331     }
7332
7333     while (backw--) {
7334         send--;
7335         while (UTF8_IS_CONTINUATION(*send))
7336             send--;
7337     }
7338     return send - start;
7339 }
7340
7341 /* For the string representation of the given scalar, find the byte
7342    corresponding to the passed in UTF-8 offset.  uoffset0 and boffset0
7343    give another position in the string, *before* the sought offset, which
7344    (which is always true, as 0, 0 is a valid pair of positions), which should
7345    help reduce the amount of linear searching.
7346    If *mgp is non-NULL, it should point to the UTF-8 cache magic, which
7347    will be used to reduce the amount of linear searching. The cache will be
7348    created if necessary, and the found value offered to it for update.  */
7349 static STRLEN
7350 S_sv_pos_u2b_cached(pTHX_ SV *const sv, MAGIC **const mgp, const U8 *const start,
7351                     const U8 *const send, STRLEN uoffset,
7352                     STRLEN uoffset0, STRLEN boffset0)
7353 {
7354     STRLEN boffset = 0; /* Actually always set, but let's keep gcc happy.  */
7355     bool found = FALSE;
7356     bool at_end = FALSE;
7357     bool canonical_position = FALSE;
7358
7359     PERL_ARGS_ASSERT_SV_POS_U2B_CACHED;
7360
7361     assert (uoffset >= uoffset0);
7362
7363     if (!uoffset)
7364         return 0;
7365
7366     if (!SvREADONLY(sv) && !SvGMAGICAL(sv) && SvPOK(sv)
7367         && PL_utf8cache
7368         && (*mgp || (SvTYPE(sv) >= SVt_PVMG &&
7369                      (*mgp = mg_find(sv, PERL_MAGIC_utf8))))) {
7370         if ((*mgp)->mg_ptr) {
7371             STRLEN *cache = (STRLEN *) (*mgp)->mg_ptr;
7372             if (cache[0] == uoffset) {
7373                 /* An exact match. */
7374                 return cache[1];
7375             }
7376             if (cache[2] == uoffset) {
7377                 /* An exact match. */
7378                 return cache[3];
7379             }
7380
7381             if (cache[0] < uoffset) {
7382                 /* The cache already knows part of the way.   */
7383                 if (cache[0] > uoffset0) {
7384                     /* The cache knows more than the passed in pair  */
7385                     uoffset0 = cache[0];
7386                     boffset0 = cache[1];
7387                 }
7388                 if ((*mgp)->mg_len != -1) {
7389                     /* And we know the end too.  */
7390                     boffset = boffset0
7391                         + sv_pos_u2b_midway(start + boffset0, send,
7392                                               uoffset - uoffset0,
7393                                               (*mgp)->mg_len - uoffset0);
7394                 } else {
7395                     uoffset -= uoffset0;
7396                     boffset = boffset0
7397                         + sv_pos_u2b_forwards(start + boffset0,
7398                                               send, &uoffset, &at_end,
7399                                               &canonical_position);
7400                     uoffset += uoffset0;
7401                 }
7402             }
7403             else if (cache[2] < uoffset) {
7404                 /* We're between the two cache entries.  */
7405                 if (cache[2] > uoffset0) {
7406                     /* and the cache knows more than the passed in pair  */
7407                     uoffset0 = cache[2];
7408                     boffset0 = cache[3];
7409                 }
7410
7411                 boffset = boffset0
7412                     + sv_pos_u2b_midway(start + boffset0,
7413                                           start + cache[1],
7414                                           uoffset - uoffset0,
7415                                           cache[0] - uoffset0);
7416             } else {
7417                 boffset = boffset0
7418                     + sv_pos_u2b_midway(start + boffset0,
7419                                           start + cache[3],
7420                                           uoffset - uoffset0,
7421                                           cache[2] - uoffset0);
7422             }
7423             found = TRUE;
7424         }
7425         else if ((*mgp)->mg_len != -1) {
7426             /* If we can take advantage of a passed in offset, do so.  */
7427             /* In fact, offset0 is either 0, or less than offset, so don't
7428                need to worry about the other possibility.  */
7429             boffset = boffset0
7430                 + sv_pos_u2b_midway(start + boffset0, send,
7431                                       uoffset - uoffset0,
7432                                       (*mgp)->mg_len - uoffset0);
7433             found = TRUE;
7434         }
7435     }
7436
7437     if (!found || PL_utf8cache < 0) {
7438         STRLEN real_boffset;
7439         uoffset -= uoffset0;
7440         real_boffset = boffset0 + sv_pos_u2b_forwards(start + boffset0,
7441                                                       send, &uoffset, &at_end,
7442                                                       &canonical_position);
7443         uoffset += uoffset0;
7444
7445         if (found && PL_utf8cache < 0)
7446             assert_uft8_cache_coherent("sv_pos_u2b_cache", boffset,
7447                                        real_boffset, sv);
7448         boffset = real_boffset;
7449     }
7450
7451     if (PL_utf8cache && canonical_position && !SvGMAGICAL(sv) && SvPOK(sv)) {
7452         if (at_end)
7453             utf8_mg_len_cache_update(sv, mgp, uoffset);
7454         else
7455             utf8_mg_pos_cache_update(sv, mgp, boffset, uoffset, send - start);
7456     }
7457     return boffset;
7458 }
7459
7460
7461 /*
7462 =for apidoc sv_pos_u2b_flags
7463
7464 Converts the offset from a count of UTF-8 chars from
7465 the start of the string, to a count of the equivalent number of bytes; if
7466 C<lenp> is non-zero, it does the same to C<lenp>, but this time starting from
7467 C<offset>, rather than from the start
7468 of the string.  Handles type coercion.
7469 C<flags> is passed to C<SvPV_flags>, and usually should be
7470 C<SV_GMAGIC|SV_CONST_RETURN> to handle magic.
7471
7472 =cut
7473 */
7474
7475 /*
7476  * sv_pos_u2b_flags() uses, like sv_pos_b2u(), the mg_ptr of the potential
7477  * PERL_MAGIC_utf8 of the sv to store the mapping between UTF-8 and
7478  * byte offsets.  See also the comments of S_utf8_mg_pos_cache_update().
7479  *
7480  */
7481
7482 STRLEN
7483 Perl_sv_pos_u2b_flags(pTHX_ SV *const sv, STRLEN uoffset, STRLEN *const lenp,
7484                       U32 flags)
7485 {
7486     const U8 *start;
7487     STRLEN len;
7488     STRLEN boffset;
7489
7490     PERL_ARGS_ASSERT_SV_POS_U2B_FLAGS;
7491
7492     start = (U8*)SvPV_flags(sv, len, flags);
7493     if (len) {
7494         const U8 * const send = start + len;
7495         MAGIC *mg = NULL;
7496         boffset = sv_pos_u2b_cached(sv, &mg, start, send, uoffset, 0, 0);
7497
7498         if (lenp
7499             && *lenp /* don't bother doing work for 0, as its bytes equivalent
7500                         is 0, and *lenp is already set to that.  */) {
7501             /* Convert the relative offset to absolute.  */
7502             const STRLEN uoffset2 = uoffset + *lenp;
7503             const STRLEN boffset2
7504                 = sv_pos_u2b_cached(sv, &mg, start, send, uoffset2,
7505                                       uoffset, boffset) - boffset;
7506
7507             *lenp = boffset2;
7508         }
7509     } else {
7510         if (lenp)
7511             *lenp = 0;
7512         boffset = 0;
7513     }
7514
7515     return boffset;
7516 }
7517
7518 /*
7519 =for apidoc sv_pos_u2b
7520
7521 Converts the value pointed to by C<offsetp> from a count of UTF-8 chars from
7522 the start of the string, to a count of the equivalent number of bytes; if
7523 C<lenp> is non-zero, it does the same to C<lenp>, but this time starting from
7524 the offset, rather than from the start of the string.  Handles magic and
7525 type coercion.
7526
7527 Use C<sv_pos_u2b_flags> in preference, which correctly handles strings longer
7528 than 2Gb.
7529
7530 =cut
7531 */
7532
7533 /*
7534  * sv_pos_u2b() uses, like sv_pos_b2u(), the mg_ptr of the potential
7535  * PERL_MAGIC_utf8 of the sv to store the mapping between UTF-8 and
7536  * byte offsets.  See also the comments of S_utf8_mg_pos_cache_update().
7537  *
7538  */
7539
7540 /* This function is subject to size and sign problems */
7541
7542 void
7543 Perl_sv_pos_u2b(pTHX_ SV *const sv, I32 *const offsetp, I32 *const lenp)
7544 {
7545     PERL_ARGS_ASSERT_SV_POS_U2B;
7546
7547     if (lenp) {
7548         STRLEN ulen = (STRLEN)*lenp;
7549         *offsetp = (I32)sv_pos_u2b_flags(sv, (STRLEN)*offsetp, &ulen,
7550                                          SV_GMAGIC|SV_CONST_RETURN);
7551         *lenp = (I32)ulen;
7552     } else {
7553         *offsetp = (I32)sv_pos_u2b_flags(sv, (STRLEN)*offsetp, NULL,
7554                                          SV_GMAGIC|SV_CONST_RETURN);
7555     }
7556 }
7557
7558 static void
7559 S_utf8_mg_len_cache_update(pTHX_ SV *const sv, MAGIC **const mgp,
7560                            const STRLEN ulen)
7561 {
7562     PERL_ARGS_ASSERT_UTF8_MG_LEN_CACHE_UPDATE;
7563     if (SvREADONLY(sv) || SvGMAGICAL(sv) || !SvPOK(sv))
7564         return;
7565
7566     if (!*mgp && (SvTYPE(sv) < SVt_PVMG ||
7567                   !(*mgp = mg_find(sv, PERL_MAGIC_utf8)))) {
7568         *mgp = sv_magicext(sv, 0, PERL_MAGIC_utf8, &PL_vtbl_utf8, 0, 0);
7569     }
7570     assert(*mgp);
7571
7572     (*mgp)->mg_len = ulen;
7573 }
7574
7575 /* Create and update the UTF8 magic offset cache, with the proffered utf8/
7576    byte length pairing. The (byte) length of the total SV is passed in too,
7577    as blen, because for some (more esoteric) SVs, the call to SvPV_const()
7578    may not have updated SvCUR, so we can't rely on reading it directly.
7579
7580    The proffered utf8/byte length pairing isn't used if the cache already has
7581    two pairs, and swapping either for the proffered pair would increase the
7582    RMS of the intervals between known byte offsets.
7583
7584    The cache itself consists of 4 STRLEN values
7585    0: larger UTF-8 offset
7586    1: corresponding byte offset
7587    2: smaller UTF-8 offset
7588    3: corresponding byte offset
7589
7590    Unused cache pairs have the value 0, 0.
7591    Keeping the cache "backwards" means that the invariant of
7592    cache[0] >= cache[2] is maintained even with empty slots, which means that
7593    the code that uses it doesn't need to worry if only 1 entry has actually
7594    been set to non-zero.  It also makes the "position beyond the end of the
7595    cache" logic much simpler, as the first slot is always the one to start
7596    from.
7597 */
7598 static void
7599 S_utf8_mg_pos_cache_update(pTHX_ SV *const sv, MAGIC **const mgp, const STRLEN byte,
7600                            const STRLEN utf8, const STRLEN blen)
7601 {
7602     STRLEN *cache;
7603
7604     PERL_ARGS_ASSERT_UTF8_MG_POS_CACHE_UPDATE;
7605
7606     if (SvREADONLY(sv))
7607         return;
7608
7609     if (!*mgp && (SvTYPE(sv) < SVt_PVMG ||
7610                   !(*mgp = mg_find(sv, PERL_MAGIC_utf8)))) {
7611         *mgp = sv_magicext(sv, 0, PERL_MAGIC_utf8, (MGVTBL*)&PL_vtbl_utf8, 0,
7612                            0);
7613         (*mgp)->mg_len = -1;
7614     }
7615     assert(*mgp);
7616
7617     if (!(cache = (STRLEN *)(*mgp)->mg_ptr)) {
7618         Newxz(cache, PERL_MAGIC_UTF8_CACHESIZE * 2, STRLEN);
7619         (*mgp)->mg_ptr = (char *) cache;
7620     }
7621     assert(cache);
7622
7623     if (PL_utf8cache < 0 && SvPOKp(sv)) {
7624         /* SvPOKp() because, if sv is a reference, then SvPVX() is actually
7625            a pointer.  Note that we no longer cache utf8 offsets on refer-
7626            ences, but this check is still a good idea, for robustness.  */
7627         const U8 *start = (const U8 *) SvPVX_const(sv);
7628         const STRLEN realutf8 = utf8_length(start, start + byte);
7629
7630         assert_uft8_cache_coherent("utf8_mg_pos_cache_update", utf8, realutf8,
7631                                    sv);
7632     }
7633
7634     /* Cache is held with the later position first, to simplify the code
7635        that deals with unbounded ends.  */
7636
7637     ASSERT_UTF8_CACHE(cache);
7638     if (cache[1] == 0) {
7639         /* Cache is totally empty  */
7640         cache[0] = utf8;
7641         cache[1] = byte;
7642     } else if (cache[3] == 0) {
7643         if (byte > cache[1]) {
7644             /* New one is larger, so goes first.  */
7645             cache[2] = cache[0];
7646             cache[3] = cache[1];
7647             cache[0] = utf8;
7648             cache[1] = byte;
7649         } else {
7650             cache[2] = utf8;
7651             cache[3] = byte;
7652         }
7653     } else {
7654 /* float casts necessary? XXX */
7655 #define THREEWAY_SQUARE(a,b,c,d) \
7656             ((float)((d) - (c))) * ((float)((d) - (c))) \
7657             + ((float)((c) - (b))) * ((float)((c) - (b))) \
7658                + ((float)((b) - (a))) * ((float)((b) - (a)))
7659
7660         /* Cache has 2 slots in use, and we know three potential pairs.
7661            Keep the two that give the lowest RMS distance. Do the
7662            calculation in bytes simply because we always know the byte
7663            length.  squareroot has the same ordering as the positive value,
7664            so don't bother with the actual square root.  */
7665         if (byte > cache[1]) {
7666             /* New position is after the existing pair of pairs.  */
7667             const float keep_earlier
7668                 = THREEWAY_SQUARE(0, cache[3], byte, blen);
7669             const float keep_later
7670                 = THREEWAY_SQUARE(0, cache[1], byte, blen);
7671
7672             if (keep_later < keep_earlier) {
7673                 cache[2] = cache[0];
7674                 cache[3] = cache[1];
7675             }
7676             cache[0] = utf8;
7677             cache[1] = byte;
7678         }
7679         else {
7680             const float keep_later = THREEWAY_SQUARE(0, byte, cache[1], blen);
7681             float b, c, keep_earlier;
7682             if (byte > cache[3]) {
7683                 /* New position is between the existing pair of pairs.  */
7684                 b = (float)cache[3];
7685                 c = (float)byte;
7686             } else {
7687                 /* New position is before the existing pair of pairs.  */
7688                 b = (float)byte;
7689                 c = (float)cache[3];
7690             }
7691             keep_earlier = THREEWAY_SQUARE(0, b, c, blen);
7692             if (byte > cache[3]) {
7693                 if (keep_later < keep_earlier) {
7694                     cache[2] = utf8;
7695                     cache[3] = byte;
7696                 }
7697                 else {
7698                     cache[0] = utf8;
7699                     cache[1] = byte;
7700                 }
7701             }
7702             else {
7703                 if (! (keep_later < keep_earlier)) {
7704                     cache[0] = cache[2];
7705                     cache[1] = cache[3];
7706                 }
7707                 cache[2] = utf8;
7708                 cache[3] = byte;
7709             }
7710         }
7711     }
7712     ASSERT_UTF8_CACHE(cache);
7713 }
7714
7715 /* We already know all of the way, now we may be able to walk back.  The same
7716    assumption is made as in S_sv_pos_u2b_midway(), namely that walking
7717    backward is half the speed of walking forward. */
7718 static STRLEN
7719 S_sv_pos_b2u_midway(pTHX_ const U8 *const s, const U8 *const target,
7720                     const U8 *end, STRLEN endu)
7721 {
7722     const STRLEN forw = target - s;
7723     STRLEN backw = end - target;
7724
7725     PERL_ARGS_ASSERT_SV_POS_B2U_MIDWAY;
7726
7727     if (forw < 2 * backw) {
7728         return utf8_length(s, target);
7729     }
7730
7731     while (end > target) {
7732         end--;
7733         while (UTF8_IS_CONTINUATION(*end)) {
7734             end--;
7735         }
7736         endu--;
7737     }
7738     return endu;
7739 }
7740
7741 /*
7742 =for apidoc sv_pos_b2u_flags
7743
7744 Converts C<offset> from a count of bytes from the start of the string, to
7745 a count of the equivalent number of UTF-8 chars.  Handles type coercion.
7746 C<flags> is passed to C<SvPV_flags>, and usually should be
7747 C<SV_GMAGIC|SV_CONST_RETURN> to handle magic.
7748
7749 =cut
7750 */
7751
7752 /*
7753  * sv_pos_b2u_flags() uses, like sv_pos_u2b_flags(), the mg_ptr of the
7754  * potential PERL_MAGIC_utf8 of the sv to store the mapping between UTF-8
7755  * and byte offsets.
7756  *
7757  */
7758 STRLEN
7759 Perl_sv_pos_b2u_flags(pTHX_ SV *const sv, STRLEN const offset, U32 flags)
7760 {
7761     const U8* s;
7762     STRLEN len = 0; /* Actually always set, but let's keep gcc happy.  */
7763     STRLEN blen;
7764     MAGIC* mg = NULL;
7765     const U8* send;
7766     bool found = FALSE;
7767
7768     PERL_ARGS_ASSERT_SV_POS_B2U_FLAGS;
7769
7770     s = (const U8*)SvPV_flags(sv, blen, flags);
7771
7772     if (blen < offset)
7773         Perl_croak(aTHX_ "panic: sv_pos_b2u: bad byte offset, blen=%" UVuf
7774                    ", byte=%" UVuf, (UV)blen, (UV)offset);
7775
7776     send = s + offset;
7777
7778     if (!SvREADONLY(sv)
7779         && PL_utf8cache
7780         && SvTYPE(sv) >= SVt_PVMG
7781         && (mg = mg_find(sv, PERL_MAGIC_utf8)))
7782     {
7783         if (mg->mg_ptr) {
7784             STRLEN * const cache = (STRLEN *) mg->mg_ptr;
7785             if (cache[1] == offset) {
7786                 /* An exact match. */
7787                 return cache[0];
7788             }
7789             if (cache[3] == offset) {
7790                 /* An exact match. */
7791                 return cache[2];
7792             }
7793
7794             if (cache[1] < offset) {
7795                 /* We already know part of the way. */
7796                 if (mg->mg_len != -1) {
7797                     /* Actually, we know the end too.  */
7798                     len = cache[0]
7799                         + S_sv_pos_b2u_midway(aTHX_ s + cache[1], send,
7800                                               s + blen, mg->mg_len - cache[0]);
7801                 } else {
7802                     len = cache[0] + utf8_length(s + cache[1], send);
7803                 }
7804             }
7805             else if (cache[3] < offset) {
7806                 /* We're between the two cached pairs, so we do the calculation
7807                    offset by the byte/utf-8 positions for the earlier pair,
7808                    then add the utf-8 characters from the string start to
7809                    there.  */
7810                 len = S_sv_pos_b2u_midway(aTHX_ s + cache[3], send,
7811                                           s + cache[1], cache[0] - cache[2])
7812                     + cache[2];
7813
7814             }
7815             else { /* cache[3] > offset */
7816                 len = S_sv_pos_b2u_midway(aTHX_ s, send, s + cache[3],
7817                                           cache[2]);
7818
7819             }
7820             ASSERT_UTF8_CACHE(cache);
7821             found = TRUE;
7822         } else if (mg->mg_len != -1) {
7823             len = S_sv_pos_b2u_midway(aTHX_ s, send, s + blen, mg->mg_len);
7824             found = TRUE;
7825         }
7826     }
7827     if (!found || PL_utf8cache < 0) {
7828         const STRLEN real_len = utf8_length(s, send);
7829
7830         if (found && PL_utf8cache < 0)
7831             assert_uft8_cache_coherent("sv_pos_b2u", len, real_len, sv);
7832         len = real_len;
7833     }
7834
7835     if (PL_utf8cache) {
7836         if (blen == offset)
7837             utf8_mg_len_cache_update(sv, &mg, len);
7838         else
7839             utf8_mg_pos_cache_update(sv, &mg, offset, len, blen);
7840     }
7841
7842     return len;
7843 }
7844
7845 /*
7846 =for apidoc sv_pos_b2u
7847
7848 Converts the value pointed to by C<offsetp> from a count of bytes from the
7849 start of the string, to a count of the equivalent number of UTF-8 chars.
7850 Handles magic and type coercion.
7851
7852 Use C<sv_pos_b2u_flags> in preference, which correctly handles strings
7853 longer than 2Gb.
7854
7855 =cut
7856 */
7857
7858 /*
7859  * sv_pos_b2u() uses, like sv_pos_u2b(), the mg_ptr of the potential
7860  * PERL_MAGIC_utf8 of the sv to store the mapping between UTF-8 and
7861  * byte offsets.
7862  *
7863  */
7864 void
7865 Perl_sv_pos_b2u(pTHX_ SV *const sv, I32 *const offsetp)
7866 {
7867     PERL_ARGS_ASSERT_SV_POS_B2U;
7868
7869     if (!sv)
7870         return;
7871
7872     *offsetp = (I32)sv_pos_b2u_flags(sv, (STRLEN)*offsetp,
7873                                      SV_GMAGIC|SV_CONST_RETURN);
7874 }
7875
7876 static void
7877 S_assert_uft8_cache_coherent(pTHX_ const char *const func, STRLEN from_cache,
7878                              STRLEN real, SV *const sv)
7879 {
7880     PERL_ARGS_ASSERT_ASSERT_UFT8_CACHE_COHERENT;
7881
7882     /* As this is debugging only code, save space by keeping this test here,
7883        rather than inlining it in all the callers.  */
7884     if (from_cache == real)
7885         return;
7886
7887     /* Need to turn the assertions off otherwise we may recurse infinitely
7888        while printing error messages.  */
7889     SAVEI8(PL_utf8cache);
7890     PL_utf8cache = 0;
7891     Perl_croak(aTHX_ "panic: %s cache %" UVuf " real %" UVuf " for %" SVf,
7892                func, (UV) from_cache, (UV) real, SVfARG(sv));
7893 }
7894
7895 /*
7896 =for apidoc sv_eq
7897
7898 Returns a boolean indicating whether the strings in the two SVs are
7899 identical.  Is UTF-8 and S<C<'use bytes'>> aware, handles get magic, and will
7900 coerce its args to strings if necessary.
7901
7902 This function does not handle operator overloading. For a version that does,
7903 see instead C<sv_streq>.
7904
7905 =for apidoc sv_eq_flags
7906
7907 Returns a boolean indicating whether the strings in the two SVs are
7908 identical.  Is UTF-8 and S<C<'use bytes'>> aware and coerces its args to strings
7909 if necessary.  If the flags has the C<SV_GMAGIC> bit set, it handles get-magic, too.
7910
7911 This function does not handle operator overloading. For a version that does,
7912 see instead C<sv_streq_flags>.
7913
7914 =cut
7915 */
7916
7917 I32
7918 Perl_sv_eq_flags(pTHX_ SV *sv1, SV *sv2, const U32 flags)
7919 {
7920     const char *pv1;
7921     STRLEN cur1;
7922     const char *pv2;
7923     STRLEN cur2;
7924
7925     if (!sv1) {
7926         pv1 = "";
7927         cur1 = 0;
7928     }
7929     else {
7930         /* if pv1 and pv2 are the same, second SvPV_const call may
7931          * invalidate pv1 (if we are handling magic), so we may need to
7932          * make a copy */
7933         if (sv1 == sv2 && flags & SV_GMAGIC
7934          && (SvTHINKFIRST(sv1) || SvGMAGICAL(sv1))) {
7935             pv1 = SvPV_const(sv1, cur1);
7936             sv1 = newSVpvn_flags(pv1, cur1, SVs_TEMP | SvUTF8(sv2));
7937         }
7938         pv1 = SvPV_flags_const(sv1, cur1, flags);
7939     }
7940
7941     if (!sv2){
7942         pv2 = "";
7943         cur2 = 0;
7944     }
7945     else
7946         pv2 = SvPV_flags_const(sv2, cur2, flags);
7947
7948     if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
7949         /* Differing utf8ness.  */
7950         if (SvUTF8(sv1)) {
7951                   /* sv1 is the UTF-8 one  */
7952                   return bytes_cmp_utf8((const U8*)pv2, cur2,
7953                                         (const U8*)pv1, cur1) == 0;
7954         }
7955         else {
7956                   /* sv2 is the UTF-8 one  */
7957                   return bytes_cmp_utf8((const U8*)pv1, cur1,
7958                                         (const U8*)pv2, cur2) == 0;
7959         }
7960     }
7961
7962     if (cur1 == cur2)
7963         return (pv1 == pv2) || memEQ(pv1, pv2, cur1);
7964     else
7965         return 0;
7966 }
7967
7968 /*
7969 =for apidoc sv_streq_flags
7970
7971 Returns a boolean indicating whether the strings in the two SVs are
7972 identical. If the flags argument has the C<SV_GMAGIC> bit set, it handles
7973 get-magic too. Will coerce its args to strings if necessary. Treats
7974 C<NULL> as undef. Correctly handles the UTF8 flag.
7975
7976 If flags does not have the C<SV_SKIP_OVERLOAD> bit set, an attempt to use
7977 C<eq> overloading will be made. If such overloading does not exist or the
7978 flag is set, then regular string comparison will be used instead.
7979
7980 =for apidoc sv_streq
7981
7982 A convenient shortcut for calling C<sv_streq_flags> with the C<SV_GMAGIC>
7983 flag. This function basically behaves like the Perl code C<$sv1 eq $sv2>.
7984
7985 =cut
7986 */
7987
7988 bool
7989 Perl_sv_streq_flags(pTHX_ SV *sv1, SV *sv2, const U32 flags)
7990 {
7991     PERL_ARGS_ASSERT_SV_STREQ_FLAGS;
7992
7993     if(flags & SV_GMAGIC) {
7994         if(sv1)
7995             SvGETMAGIC(sv1);
7996         if(sv2)
7997             SvGETMAGIC(sv2);
7998     }
7999
8000     /* Treat NULL as undef */
8001     if(!sv1)
8002         sv1 = &PL_sv_undef;
8003     if(!sv2)
8004         sv2 = &PL_sv_undef;
8005
8006     if(!(flags & SV_SKIP_OVERLOAD) &&
8007             (SvAMAGIC(sv1) || SvAMAGIC(sv2))) {
8008         SV *ret = amagic_call(sv1, sv2, seq_amg, 0);
8009         if(ret)
8010             return SvTRUE(ret);
8011     }
8012
8013     return sv_eq_flags(sv1, sv2, 0);
8014 }
8015
8016 /*
8017 =for apidoc sv_numeq_flags
8018
8019 Returns a boolean indicating whether the numbers in the two SVs are
8020 identical. If the flags argument has the C<SV_GMAGIC> bit set, it handles
8021 get-magic too. Will coerce its args to numbers if necessary. Treats
8022 C<NULL> as undef.
8023
8024 If flags does not have the C<SV_SKIP_OVERLOAD> bit set, an attempt to use
8025 C<==> overloading will be made. If such overloading does not exist or the
8026 flag is set, then regular numerical comparison will be used instead.
8027
8028 =for apidoc sv_numeq
8029
8030 A convenient shortcut for calling C<sv_numeq_flags> with the C<SV_GMAGIC>
8031 flag. This function basically behaves like the Perl code C<$sv1 == $sv2>.
8032
8033 =cut
8034 */
8035
8036 bool
8037 Perl_sv_numeq_flags(pTHX_ SV *sv1, SV *sv2, const U32 flags)
8038 {
8039     PERL_ARGS_ASSERT_SV_NUMEQ_FLAGS;
8040
8041     if(flags & SV_GMAGIC) {
8042         if(sv1)
8043             SvGETMAGIC(sv1);
8044         if(sv2)
8045             SvGETMAGIC(sv2);
8046     }
8047
8048     /* Treat NULL as undef */
8049     if(!sv1)
8050         sv1 = &PL_sv_undef;
8051     if(!sv2)
8052         sv2 = &PL_sv_undef;
8053
8054     if(!(flags & SV_SKIP_OVERLOAD) &&
8055             (SvAMAGIC(sv1) || SvAMAGIC(sv2))) {
8056         SV *ret = amagic_call(sv1, sv2, eq_amg, 0);
8057         if(ret)
8058             return SvTRUE(ret);
8059     }
8060
8061     return do_ncmp(sv1, sv2) == 0;
8062 }
8063
8064 /*
8065 =for apidoc sv_cmp
8066
8067 Compares the strings in two SVs.  Returns -1, 0, or 1 indicating whether the
8068 string in C<sv1> is less than, equal to, or greater than the string in
8069 C<sv2>.  Is UTF-8 and S<C<'use bytes'>> aware, handles get magic, and will
8070 coerce its args to strings if necessary.  See also C<L</sv_cmp_locale>>.
8071
8072 =for apidoc sv_cmp_flags
8073
8074 Compares the strings in two SVs.  Returns -1, 0, or 1 indicating whether the
8075 string in C<sv1> is less than, equal to, or greater than the string in
8076 C<sv2>.  Is UTF-8 and S<C<'use bytes'>> aware and will coerce its args to strings
8077 if necessary.  If the flags has the C<SV_GMAGIC> bit set, it handles get magic.  See
8078 also C<L</sv_cmp_locale_flags>>.
8079
8080 =cut
8081 */
8082
8083 I32
8084 Perl_sv_cmp(pTHX_ SV *const sv1, SV *const sv2)
8085 {
8086     return sv_cmp_flags(sv1, sv2, SV_GMAGIC);
8087 }
8088
8089 I32
8090 Perl_sv_cmp_flags(pTHX_ SV *const sv1, SV *const sv2,
8091                   const U32 flags)
8092 {
8093     STRLEN cur1, cur2;
8094     const char *pv1, *pv2;
8095     I32  cmp;
8096     SV *svrecode = NULL;
8097
8098     if (!sv1) {
8099         pv1 = "";
8100         cur1 = 0;
8101     }
8102     else
8103         pv1 = SvPV_flags_const(sv1, cur1, flags);
8104
8105     if (!sv2) {
8106         pv2 = "";
8107         cur2 = 0;
8108     }
8109     else
8110         pv2 = SvPV_flags_const(sv2, cur2, flags);
8111
8112     if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
8113         /* Differing utf8ness.  */
8114         if (SvUTF8(sv1)) {
8115                 const int retval = -bytes_cmp_utf8((const U8*)pv2, cur2,
8116                                                    (const U8*)pv1, cur1);
8117                 return retval ? retval < 0 ? -1 : +1 : 0;
8118         }
8119         else {
8120                 const int retval = bytes_cmp_utf8((const U8*)pv1, cur1,
8121                                                   (const U8*)pv2, cur2);
8122                 return retval ? retval < 0 ? -1 : +1 : 0;
8123         }
8124     }
8125
8126     /* Here, if both are non-NULL, then they have the same UTF8ness. */
8127
8128     if (!cur1) {
8129         cmp = cur2 ? -1 : 0;
8130     } else if (!cur2) {
8131         cmp = 1;
8132     } else {
8133         STRLEN shortest_len = cur1 < cur2 ? cur1 : cur2;
8134
8135 #ifdef EBCDIC
8136         if (! DO_UTF8(sv1)) {
8137 #endif
8138             const I32 retval = memcmp((const void*)pv1,
8139                                       (const void*)pv2,
8140                                       shortest_len);
8141             if (retval) {
8142                 cmp = retval < 0 ? -1 : 1;
8143             } else if (cur1 == cur2) {
8144                 cmp = 0;
8145             } else {
8146                 cmp = cur1 < cur2 ? -1 : 1;
8147             }
8148 #ifdef EBCDIC
8149         }
8150         else {  /* Both are to be treated as UTF-EBCDIC */
8151
8152             /* EBCDIC UTF-8 is complicated by the fact that it is based on I8
8153              * which remaps code points 0-255.  We therefore generally have to
8154              * unmap back to the original values to get an accurate comparison.
8155              * But we don't have to do that for UTF-8 invariants, as by
8156              * definition, they aren't remapped, nor do we have to do it for
8157              * above-latin1 code points, as they also aren't remapped.  (This
8158              * code also works on ASCII platforms, but the memcmp() above is
8159              * much faster). */
8160
8161             const char *e = pv1 + shortest_len;
8162
8163             /* Find the first bytes that differ between the two strings */
8164             while (pv1 < e && *pv1 == *pv2) {
8165                 pv1++;
8166                 pv2++;
8167             }
8168
8169
8170             if (pv1 == e) { /* Are the same all the way to the end */
8171                 if (cur1 == cur2) {
8172                     cmp = 0;
8173                 } else {
8174                     cmp = cur1 < cur2 ? -1 : 1;
8175                 }
8176             }
8177             else   /* Here *pv1 and *pv2 are not equal, but all bytes earlier
8178                     * in the strings were.  The current bytes may or may not be
8179                     * at the beginning of a character.  But neither or both are
8180                     * (or else earlier bytes would have been different).  And
8181                     * if we are in the middle of a character, the two
8182                     * characters are comprised of the same number of bytes
8183                     * (because in this case the start bytes are the same, and
8184                     * the start bytes encode the character's length). */
8185                  if (UTF8_IS_INVARIANT(*pv1))
8186             {
8187                 /* If both are invariants; can just compare directly */
8188                 if (UTF8_IS_INVARIANT(*pv2)) {
8189                     cmp = ((U8) *pv1 < (U8) *pv2) ? -1 : 1;
8190                 }
8191                 else   /* Since *pv1 is invariant, it is the whole character,
8192                           which means it is at the beginning of a character.
8193                           That means pv2 is also at the beginning of a
8194                           character (see earlier comment).  Since it isn't
8195                           invariant, it must be a start byte.  If it starts a
8196                           character whose code point is above 255, that
8197                           character is greater than any single-byte char, which
8198                           *pv1 is */
8199                       if (UTF8_IS_ABOVE_LATIN1_START(*pv2))
8200                 {
8201                     cmp = -1;
8202                 }
8203                 else {
8204                     /* Here, pv2 points to a character composed of 2 bytes
8205                      * whose code point is < 256.  Get its code point and
8206                      * compare with *pv1 */
8207                     cmp = ((U8) *pv1 < EIGHT_BIT_UTF8_TO_NATIVE(*pv2, *(pv2 + 1)))
8208                            ?  -1
8209                            : 1;
8210                 }
8211             }
8212             else   /* The code point starting at pv1 isn't a single byte */
8213                  if (UTF8_IS_INVARIANT(*pv2))
8214             {
8215                 /* But here, the code point starting at *pv2 is a single byte,
8216                  * and so *pv1 must begin a character, hence is a start byte.
8217                  * If that character is above 255, it is larger than any
8218                  * single-byte char, which *pv2 is */
8219                 if (UTF8_IS_ABOVE_LATIN1_START(*pv1)) {
8220                     cmp = 1;
8221                 }
8222                 else {
8223                     /* Here, pv1 points to a character composed of 2 bytes
8224                      * whose code point is < 256.  Get its code point and
8225                      * compare with the single byte character *pv2 */
8226                     cmp = (EIGHT_BIT_UTF8_TO_NATIVE(*pv1, *(pv1 + 1)) < (U8) *pv2)
8227                           ?  -1
8228                           : 1;
8229                 }
8230             }
8231             else   /* Here, we've ruled out either *pv1 and *pv2 being
8232                       invariant.  That means both are part of variants, but not
8233                       necessarily at the start of a character */
8234                  if (   UTF8_IS_ABOVE_LATIN1_START(*pv1)
8235                      || UTF8_IS_ABOVE_LATIN1_START(*pv2))
8236             {
8237                 /* Here, at least one is the start of a character, which means
8238                  * the other is also a start byte.  And the code point of at
8239                  * least one of the characters is above 255.  It is a
8240                  * characteristic of UTF-EBCDIC that all start bytes for
8241                  * above-latin1 code points are well behaved as far as code
8242                  * point comparisons go, and all are larger than all other
8243                  * start bytes, so the comparison with those is also well
8244                  * behaved */
8245                 cmp = ((U8) *pv1 < (U8) *pv2) ? -1 : 1;
8246             }
8247             else {
8248                 /* Here both *pv1 and *pv2 are part of variant characters.
8249                  * They could be both continuations, or both start characters.
8250                  * (One or both could even be an illegal start character (for
8251                  * an overlong) which for the purposes of sorting we treat as
8252                  * legal. */
8253                 if (UTF8_IS_CONTINUATION(*pv1)) {
8254
8255                     /* If they are continuations for code points above 255,
8256                      * then comparing the current byte is sufficient, as there
8257                      * is no remapping of these and so the comparison is
8258                      * well-behaved.   We determine if they are such
8259                      * continuations by looking at the preceding byte.  It
8260                      * could be a start byte, from which we can tell if it is
8261                      * for an above 255 code point.  Or it could be a
8262                      * continuation, which means the character occupies at
8263                      * least 3 bytes, so must be above 255.  */
8264                     if (   UTF8_IS_CONTINUATION(*(pv2 - 1))
8265                         || UTF8_IS_ABOVE_LATIN1_START(*(pv2 -1)))
8266                     {
8267                         cmp = ((U8) *pv1 < (U8) *pv2) ? -1 : 1;
8268                         goto cmp_done;
8269                     }
8270
8271                     /* Here, the continuations are for code points below 256;
8272                      * back up one to get to the start byte */
8273                     pv1--;
8274                     pv2--;
8275                 }
8276
8277                 /* We need to get the actual native code point of each of these
8278                  * variants in order to compare them */
8279                 cmp =  (  EIGHT_BIT_UTF8_TO_NATIVE(*pv1, *(pv1 + 1))
8280                         < EIGHT_BIT_UTF8_TO_NATIVE(*pv2, *(pv2 + 1)))
8281                         ? -1
8282                         : 1;
8283             }
8284         }
8285       cmp_done: ;
8286 #endif
8287     }
8288
8289     SvREFCNT_dec(svrecode);
8290
8291     return cmp;
8292 }
8293
8294 /*
8295 =for apidoc sv_cmp_locale
8296
8297 Compares the strings in two SVs in a locale-aware manner.  Is UTF-8 and
8298 S<C<'use bytes'>> aware, handles get magic, and will coerce its args to strings
8299 if necessary.  See also C<L</sv_cmp>>.
8300
8301 =for apidoc sv_cmp_locale_flags
8302
8303 Compares the strings in two SVs in a locale-aware manner.  Is UTF-8 and
8304 S<C<'use bytes'>> aware and will coerce its args to strings if necessary.  If
8305 the flags contain C<SV_GMAGIC>, it handles get magic.  See also
8306 C<L</sv_cmp_flags>>.
8307
8308 =cut
8309 */
8310
8311 I32
8312 Perl_sv_cmp_locale(pTHX_ SV *const sv1, SV *const sv2)
8313 {
8314     return sv_cmp_locale_flags(sv1, sv2, SV_GMAGIC);
8315 }
8316
8317 I32
8318 Perl_sv_cmp_locale_flags(pTHX_ SV *const sv1, SV *const sv2,
8319                          const U32 flags)
8320 {
8321 #ifdef USE_LOCALE_COLLATE
8322
8323     char *pv1, *pv2;
8324     STRLEN len1, len2;
8325     I32 retval;
8326
8327     if (PL_collation_standard)
8328         goto raw_compare;
8329
8330     len1 = len2 = 0;
8331
8332     /* Revert to using raw compare if both operands exist, but either one
8333      * doesn't transform properly for collation */
8334     if (sv1 && sv2) {
8335         pv1 = sv_collxfrm_flags(sv1, &len1, flags);
8336         if (! pv1) {
8337             goto raw_compare;
8338         }
8339         pv2 = sv_collxfrm_flags(sv2, &len2, flags);
8340         if (! pv2) {
8341             goto raw_compare;
8342         }
8343     }
8344     else {
8345         pv1 = sv1 ? sv_collxfrm_flags(sv1, &len1, flags) : (char *) NULL;
8346         pv2 = sv2 ? sv_collxfrm_flags(sv2, &len2, flags) : (char *) NULL;
8347     }
8348
8349     if (!pv1 || !len1) {
8350         if (pv2 && len2)
8351             return -1;
8352         else
8353             goto raw_compare;
8354     }
8355     else {
8356         if (!pv2 || !len2)
8357             return 1;
8358     }
8359
8360     retval = memcmp((void*)pv1, (void*)pv2, len1 < len2 ? len1 : len2);
8361
8362     if (retval)
8363         return retval < 0 ? -1 : 1;
8364
8365     /*
8366      * When the result of collation is equality, that doesn't mean
8367      * that there are no differences -- some locales exclude some
8368      * characters from consideration.  So to avoid false equalities,
8369      * we use the raw string as a tiebreaker.
8370      */
8371
8372   raw_compare:
8373     /* FALLTHROUGH */
8374
8375 #else
8376     PERL_UNUSED_ARG(flags);
8377 #endif /* USE_LOCALE_COLLATE */
8378
8379     return sv_cmp(sv1, sv2);
8380 }
8381
8382
8383 #ifdef USE_LOCALE_COLLATE
8384
8385 /*
8386 =for apidoc sv_collxfrm
8387
8388 This calls C<sv_collxfrm_flags> with the SV_GMAGIC flag.  See
8389 C<L</sv_collxfrm_flags>>.
8390
8391 =for apidoc sv_collxfrm_flags
8392
8393 Add Collate Transform magic to an SV if it doesn't already have it.  If the
8394 flags contain C<SV_GMAGIC>, it handles get-magic.
8395
8396 Any scalar variable may carry C<PERL_MAGIC_collxfrm> magic that contains the
8397 scalar data of the variable, but transformed to such a format that a normal
8398 memory comparison can be used to compare the data according to the locale
8399 settings.
8400
8401 =cut
8402 */
8403
8404 char *
8405 Perl_sv_collxfrm_flags(pTHX_ SV *const sv, STRLEN *const nxp, const I32 flags)
8406 {
8407     MAGIC *mg;
8408
8409     PERL_ARGS_ASSERT_SV_COLLXFRM_FLAGS;
8410
8411     mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_collxfrm) : (MAGIC *) NULL;
8412
8413     /* If we don't have collation magic on 'sv', or the locale has changed
8414      * since the last time we calculated it, get it and save it now */
8415     if (!mg || !mg->mg_ptr || *(U32*)mg->mg_ptr != PL_collation_ix) {
8416         const char *s;
8417         char *xf;
8418         STRLEN len, xlen;
8419
8420         /* Free the old space */
8421         if (mg)
8422             Safefree(mg->mg_ptr);
8423
8424         s = SvPV_flags_const(sv, len, flags);
8425         if ((xf = mem_collxfrm_(s, len, &xlen, cBOOL(SvUTF8(sv))))) {
8426             if (! mg) {
8427                 mg = sv_magicext(sv, 0, PERL_MAGIC_collxfrm, &PL_vtbl_collxfrm,
8428                                  0, 0);
8429                 assert(mg);
8430             }
8431             mg->mg_ptr = xf;
8432             mg->mg_len = xlen;
8433         }
8434         else {
8435             if (mg) {
8436                 mg->mg_ptr = NULL;
8437                 mg->mg_len = -1;
8438             }
8439         }
8440     }
8441
8442     if (mg && mg->mg_ptr) {
8443         *nxp = mg->mg_len;
8444         return mg->mg_ptr + sizeof(PL_collation_ix);
8445     }
8446     else {
8447         *nxp = 0;
8448         return NULL;
8449     }
8450 }
8451
8452 #endif /* USE_LOCALE_COLLATE */
8453
8454 static char *
8455 S_sv_gets_append_to_utf8(pTHX_ SV *const sv, PerlIO *const fp, I32 append)
8456 {
8457     SV * const tsv = newSV_type(SVt_NULL);
8458     ENTER;
8459     SAVEFREESV(tsv);
8460     sv_gets(tsv, fp, 0);
8461     sv_utf8_upgrade_nomg(tsv);
8462     SvCUR_set(sv,append);
8463     sv_catsv(sv,tsv);
8464     LEAVE;
8465     return (SvCUR(sv) - append) ? SvPVX(sv) : NULL;
8466 }
8467
8468 static char *
8469 S_sv_gets_read_record(pTHX_ SV *const sv, PerlIO *const fp, I32 append)
8470 {
8471     SSize_t bytesread;
8472     const STRLEN recsize = SvUV(SvRV(PL_rs)); /* RsRECORD() guarantees > 0. */
8473       /* Grab the size of the record we're getting */
8474     char *buffer = SvGROW(sv, (STRLEN)(recsize + append + 1)) + append;
8475
8476     /* Go yank in */
8477 #ifdef __VMS
8478     int fd;
8479     Stat_t st;
8480
8481     /* With a true, record-oriented file on VMS, we need to use read directly
8482      * to ensure that we respect RMS record boundaries.  The user is responsible
8483      * for providing a PL_rs value that corresponds to the FAB$W_MRS (maximum
8484      * record size) field.  N.B. This is likely to produce invalid results on
8485      * varying-width character data when a record ends mid-character.
8486      */
8487     fd = PerlIO_fileno(fp);
8488     if (fd != -1
8489         && PerlLIO_fstat(fd, &st) == 0
8490         && (st.st_fab_rfm == FAB$C_VAR
8491             || st.st_fab_rfm == FAB$C_VFC
8492             || st.st_fab_rfm == FAB$C_FIX)) {
8493
8494         bytesread = PerlLIO_read(fd, buffer, recsize);
8495     }
8496     else /* in-memory file from PerlIO::Scalar
8497           * or not a record-oriented file
8498           */
8499 #endif
8500     {
8501         bytesread = PerlIO_read(fp, buffer, recsize);
8502
8503         /* At this point, the logic in sv_get() means that sv will
8504            be treated as utf-8 if the handle is utf8.
8505         */
8506         if (PerlIO_isutf8(fp) && bytesread > 0) {
8507             char *bend = buffer + bytesread;
8508             char *bufp = buffer;
8509             size_t charcount = 0;
8510             bool charstart = TRUE;
8511             STRLEN skip = 0;
8512
8513             while (charcount < recsize) {
8514                 /* count accumulated characters */
8515                 while (bufp < bend) {
8516                     if (charstart) {
8517                         skip = UTF8SKIP(bufp);
8518                     }
8519                     if (bufp + skip > bend) {
8520                         /* partial at the end */
8521                         charstart = FALSE;
8522                         break;
8523                     }
8524                     else {
8525                         ++charcount;
8526                         bufp += skip;
8527                         charstart = TRUE;
8528                     }
8529                 }
8530
8531                 if (charcount < recsize) {
8532                     STRLEN readsize;
8533                     STRLEN bufp_offset = bufp - buffer;
8534                     SSize_t morebytesread;
8535
8536                     /* originally I read enough to fill any incomplete
8537                        character and the first byte of the next
8538                        character if needed, but if there's many
8539                        multi-byte encoded characters we're going to be
8540                        making a read call for every character beyond
8541                        the original read size.
8542
8543                        So instead, read the rest of the character if
8544                        any, and enough bytes to match at least the
8545                        start bytes for each character we're going to
8546                        read.
8547                     */
8548                     if (charstart)
8549                         readsize = recsize - charcount;
8550                     else
8551                         readsize = skip - (bend - bufp) + recsize - charcount - 1;
8552                     buffer = SvGROW(sv, append + bytesread + readsize + 1) + append;
8553                     bend = buffer + bytesread;
8554                     morebytesread = PerlIO_read(fp, bend, readsize);
8555                     if (morebytesread <= 0) {
8556                         /* we're done, if we still have incomplete
8557                            characters the check code in sv_gets() will
8558                            warn about them.
8559
8560                            I'd originally considered doing
8561                            PerlIO_ungetc() on all but the lead
8562                            character of the incomplete character, but
8563                            read() doesn't do that, so I don't.
8564                         */
8565                         break;
8566                     }
8567
8568                     /* prepare to scan some more */
8569                     bytesread += morebytesread;
8570                     bend = buffer + bytesread;
8571                     bufp = buffer + bufp_offset;
8572                 }
8573             }
8574         }
8575     }
8576
8577     if (bytesread < 0)
8578         bytesread = 0;
8579     SvCUR_set(sv, bytesread + append);
8580     buffer[bytesread] = '\0';
8581     return (SvCUR(sv) - append) ? SvPVX(sv) : NULL;
8582 }
8583
8584 /*
8585 =for apidoc sv_gets
8586
8587 Get a line from the filehandle and store it into the SV, optionally
8588 appending to the currently-stored string.  If C<append> is not 0, the
8589 line is appended to the SV instead of overwriting it.  C<append> should
8590 be set to the byte offset that the appended string should start at
8591 in the SV (typically, C<SvCUR(sv)> is a suitable choice).
8592
8593 =cut
8594 */
8595
8596 char *
8597 Perl_sv_gets(pTHX_ SV *const sv, PerlIO *const fp, I32 append)
8598 {
8599     const char *rsptr;
8600     STRLEN rslen;
8601     STDCHAR rslast;
8602     STDCHAR *bp;
8603     SSize_t cnt;
8604     int i = 0;
8605     int rspara = 0;
8606
8607     PERL_ARGS_ASSERT_SV_GETS;
8608
8609     if (SvTHINKFIRST(sv))
8610         sv_force_normal_flags(sv, append ? 0 : SV_COW_DROP_PV);
8611     /* XXX. If you make this PVIV, then copy on write can copy scalars read
8612        from <>.
8613        However, perlbench says it's slower, because the existing swipe code
8614        is faster than copy on write.
8615        Swings and roundabouts.  */
8616     SvUPGRADE(sv, SVt_PV);
8617
8618     if (append) {
8619         /* line is going to be appended to the existing buffer in the sv */
8620         if (PerlIO_isutf8(fp)) {
8621             if (!SvUTF8(sv)) {
8622                 sv_utf8_upgrade_nomg(sv);
8623                 sv_pos_u2b(sv,&append,0);
8624             }
8625         } else if (SvUTF8(sv)) {
8626             return S_sv_gets_append_to_utf8(aTHX_ sv, fp, append);
8627         }
8628     }
8629
8630     SvPOK_only(sv);
8631     if (!append) {
8632         /* not appending - "clear" the string by setting SvCUR to 0,
8633          * the pv is still avaiable. */
8634         SvCUR_set(sv,0);
8635     }
8636     if (PerlIO_isutf8(fp))
8637         SvUTF8_on(sv);
8638
8639     if (IN_PERL_COMPILETIME) {
8640         /* we always read code in line mode */
8641         rsptr = "\n";
8642         rslen = 1;
8643     }
8644     else if (RsSNARF(PL_rs)) {
8645         /* If it is a regular disk file use size from stat() as estimate
8646            of amount we are going to read -- may result in mallocing
8647            more memory than we really need if the layers below reduce
8648            the size we read (e.g. CRLF or a gzip layer).
8649          */
8650         Stat_t st;
8651         int fd = PerlIO_fileno(fp);
8652         if (fd >= 0 && (PerlLIO_fstat(fd, &st) == 0) && S_ISREG(st.st_mode))  {
8653             const Off_t offset = PerlIO_tell(fp);
8654             if (offset != (Off_t) -1 && st.st_size + append > offset) {
8655 #ifdef PERL_COPY_ON_WRITE
8656                 /* Add an extra byte for the sake of copy-on-write's
8657                  * buffer reference count. */
8658                 (void) SvGROW(sv, (STRLEN)((st.st_size - offset) + append + 2));
8659 #else
8660                 (void) SvGROW(sv, (STRLEN)((st.st_size - offset) + append + 1));
8661 #endif
8662             }
8663         }
8664         rsptr = NULL;
8665         rslen = 0;
8666     }
8667     else if (RsRECORD(PL_rs)) {
8668         return S_sv_gets_read_record(aTHX_ sv, fp, append);
8669     }
8670     else if (RsPARA(PL_rs)) {
8671         rsptr = "\n\n";
8672         rslen = 2;
8673         rspara = 1;
8674     }
8675     else {
8676         /* Get $/ i.e. PL_rs into same encoding as stream wants */
8677         if (PerlIO_isutf8(fp)) {
8678             rsptr = SvPVutf8(PL_rs, rslen);
8679         }
8680         else {
8681             if (SvUTF8(PL_rs)) {
8682                 if (!sv_utf8_downgrade(PL_rs, TRUE)) {
8683                     Perl_croak(aTHX_ "Wide character in $/");
8684                 }
8685             }
8686             /* extract the raw pointer to the record separator */
8687             rsptr = SvPV_const(PL_rs, rslen);
8688         }
8689     }
8690
8691     /* rslast is the last character in the record separator
8692      * note we don't use rslast except when rslen is true, so the
8693      * null assign is a placeholder. */
8694     rslast = rslen ? rsptr[rslen - 1] : '\0';
8695
8696     if (rspara) {        /* have to do this both before and after */
8697                          /* to make sure file boundaries work right */
8698         while (1) {
8699             if (PerlIO_eof(fp))
8700                 return 0;
8701             i = PerlIO_getc(fp);
8702             if (i != '\n') {
8703                 if (i == -1)
8704                     return 0;
8705                 PerlIO_ungetc(fp,i);
8706                 break;
8707             }
8708         }
8709     }
8710
8711     /* See if we know enough about I/O mechanism to cheat it ! */
8712
8713     /* This used to be #ifdef test - it is made run-time test for ease
8714        of abstracting out stdio interface. One call should be cheap
8715        enough here - and may even be a macro allowing compile
8716        time optimization.
8717      */
8718
8719     if (PerlIO_fast_gets(fp)) {
8720     /*
8721      * We can do buffer based IO operations on this filehandle.
8722      *
8723      * This means we can bypass a lot of subcalls and process
8724      * the buffer directly, it also means we know the upper bound
8725      * on the amount of data we might read of the current buffer
8726      * into our sv. Knowing this allows us to preallocate the pv
8727      * to be able to hold that maximum, which allows us to simplify
8728      * a lot of logic. */
8729
8730     /*
8731      * We're going to steal some values from the stdio struct
8732      * and put EVERYTHING in the innermost loop into registers.
8733      */
8734     STDCHAR *ptr;       /* pointer into fp's read-ahead buffer */
8735     STRLEN bpx;         /* length of the data in the target sv
8736                            used to fix pointers after a SvGROW */
8737     I32 shortbuffered;  /* If the pv buffer is shorter than the amount
8738                            of data left in the read-ahead buffer.
8739                            If 0 then the pv buffer can hold the full
8740                            amount left, otherwise this is the amount it
8741                            can hold. */
8742
8743     /* Here is some breathtakingly efficient cheating */
8744
8745     /* When you read the following logic resist the urge to think
8746      * of record separators that are 1 byte long. They are an
8747      * uninteresting special (simple) case.
8748      *
8749      * Instead think of record separators which are at least 2 bytes
8750      * long, and keep in mind that we need to deal with such
8751      * separators when they cross a read-ahead buffer boundary.
8752      *
8753      * Also consider that we need to gracefully deal with separators
8754      * that may be longer than a single read ahead buffer.
8755      *
8756      * Lastly do not forget we want to copy the delimiter as well. We
8757      * are copying all data in the file _up_to_and_including_ the separator
8758      * itself.
8759      *
8760      * Now that you have all that in mind here is what is happening below:
8761      *
8762      * 1. When we first enter the loop we do some memory book keeping to see
8763      * how much free space there is in the target SV. (This sub assumes that
8764      * it is operating on the same SV most of the time via $_ and that it is
8765      * going to be able to reuse the same pv buffer each call.) If there is
8766      * "enough" room then we set "shortbuffered" to how much space there is
8767      * and start reading forward.
8768      *
8769      * 2. When we scan forward we copy from the read-ahead buffer to the target
8770      * SV's pv buffer. While we go we watch for the end of the read-ahead buffer,
8771      * and the end of the of pv, as well as for the "rslast", which is the last
8772      * char of the separator.
8773      *
8774      * 3. When scanning forward if we see rslast then we jump backwards in *pv*
8775      * (which has a "complete" record up to the point we saw rslast) and check
8776      * it to see if it matches the separator. If it does we are done. If it doesn't
8777      * we continue on with the scan/copy.
8778      *
8779      * 4. If we run out of read-ahead buffer (cnt goes to 0) then we have to get
8780      * the IO system to read the next buffer. We do this by doing a getc(), which
8781      * returns a single char read (or EOF), and prefills the buffer, and also
8782      * allows us to find out how full the buffer is.  We use this information to
8783      * SvGROW() the sv to the size remaining in the buffer, after which we copy
8784      * the returned single char into the target sv, and then go back into scan
8785      * forward mode.
8786      *
8787      * 5. If we run out of write-buffer then we SvGROW() it by the size of the
8788      * remaining space in the read-buffer.
8789      *
8790      * Note that this code despite its twisty-turny nature is pretty darn slick.
8791      * It manages single byte separators, multi-byte cross boundary separators,
8792      * and cross-read-buffer separators cleanly and efficiently at the cost
8793      * of potentially greatly overallocating the target SV.
8794      *
8795      * Yves
8796      */
8797
8798
8799     /* get the number of bytes remaining in the read-ahead buffer
8800      * on first call on a given fp this will return 0.*/
8801     cnt = PerlIO_get_cnt(fp);
8802
8803     /* make sure we have the room */
8804     if ((I32)(SvLEN(sv) - append) <= cnt + 1) {
8805         /* Not room for all of it
8806            if we are looking for a separator and room for some
8807          */
8808         if (rslen && cnt > 80 && (I32)SvLEN(sv) > append) {
8809             /* just process what we have room for */
8810             shortbuffered = cnt - SvLEN(sv) + append + 1;
8811             cnt -= shortbuffered;
8812         }
8813         else {
8814             /* ensure that the target sv has enough room to hold
8815              * the rest of the read-ahead buffer */
8816             shortbuffered = 0;
8817             /* remember that cnt can be negative */
8818             SvGROW(sv, (STRLEN)(append + (cnt <= 0 ? 2 : (cnt + 1))));
8819         }
8820     }
8821     else {
8822         /* we have enough room to hold the full buffer, lets scream */
8823         shortbuffered = 0;
8824     }
8825
8826     /* extract the pointer to sv's string buffer, offset by append as necessary */
8827     bp = (STDCHAR*)SvPVX_const(sv) + append;  /* move these two too to registers */
8828     /* extract the point to the read-ahead buffer */
8829     ptr = (STDCHAR*)PerlIO_get_ptr(fp);
8830
8831     /* some trace debug output */
8832     DEBUG_P(PerlIO_printf(Perl_debug_log,
8833         "Screamer: entering, ptr=%" UVuf ", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
8834     DEBUG_P(PerlIO_printf(Perl_debug_log,
8835         "Screamer: entering: PerlIO * thinks ptr=%" UVuf ", cnt=%" IVdf ", base=%"
8836          UVuf "\n",
8837                PTR2UV(PerlIO_get_ptr(fp)), (IV)PerlIO_get_cnt(fp),
8838                PTR2UV(PerlIO_has_base(fp) ? PerlIO_get_base(fp) : 0)));
8839
8840     for (;;) {
8841       screamer:
8842         /* if there is stuff left in the read-ahead buffer */
8843         if (cnt > 0) {
8844             /* if there is a separator */
8845             if (rslen) {
8846                 /* find next rslast */
8847                 STDCHAR *p;
8848
8849                 /* shortcut common case of blank line */
8850                 cnt--;
8851                 if ((*bp++ = *ptr++) == rslast)
8852                     goto thats_all_folks;
8853
8854                 p = (STDCHAR *)memchr(ptr, rslast, cnt);
8855                 if (p) {
8856                     SSize_t got = p - ptr + 1;
8857                     Copy(ptr, bp, got, STDCHAR);
8858                     ptr += got;
8859                     bp  += got;
8860                     cnt -= got;
8861                     goto thats_all_folks;
8862                 }
8863                 Copy(ptr, bp, cnt, STDCHAR);
8864                 ptr += cnt;
8865                 bp  += cnt;
8866                 cnt = 0;
8867             }
8868             else {
8869                 /* no separator, slurp the full buffer */
8870                 Copy(ptr, bp, cnt, char);            /* this     |  eat */
8871                 bp += cnt;                           /* screams  |  dust */
8872                 ptr += cnt;                          /* louder   |  sed :-) */
8873                 cnt = 0;
8874                 assert (!shortbuffered);
8875                 goto cannot_be_shortbuffered;
8876             }
8877         }
8878
8879         if (shortbuffered) {            /* oh well, must extend */
8880             /* we didnt have enough room to fit the line into the target buffer
8881              * so we must extend the target buffer and keep going */
8882             cnt = shortbuffered;
8883             shortbuffered = 0;
8884             bpx = bp - (STDCHAR*)SvPVX_const(sv); /* box up before relocation */
8885             SvCUR_set(sv, bpx);
8886             /* extned the target sv's buffer so it can hold the full read-ahead buffer */
8887             SvGROW(sv, SvLEN(sv) + append + cnt + 2);
8888             bp = (STDCHAR*)SvPVX_const(sv) + bpx; /* unbox after relocation */
8889             continue;
8890         }
8891
8892     cannot_be_shortbuffered:
8893         /* we need to refill the read-ahead buffer if possible */
8894
8895         DEBUG_P(PerlIO_printf(Perl_debug_log,
8896                              "Screamer: going to getc, ptr=%" UVuf ", cnt=%" IVdf "\n",
8897                               PTR2UV(ptr),(IV)cnt));
8898         PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt); /* deregisterize cnt and ptr */
8899
8900         DEBUG_Pv(PerlIO_printf(Perl_debug_log,
8901            "Screamer: pre: FILE * thinks ptr=%" UVuf ", cnt=%" IVdf ", base=%" UVuf "\n",
8902             PTR2UV(PerlIO_get_ptr(fp)), (IV)PerlIO_get_cnt(fp),
8903             PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
8904
8905         /*
8906             call PerlIO_getc() to let it prefill the lookahead buffer
8907
8908             This used to call 'filbuf' in stdio form, but as that behaves like
8909             getc when cnt <= 0 we use PerlIO_getc here to avoid introducing
8910             another abstraction.
8911
8912             Note we have to deal with the char in 'i' if we are not at EOF
8913         */
8914         bpx = bp - (STDCHAR*)SvPVX_const(sv);
8915         /* signals might be called here, possibly modifying sv */
8916         i   = PerlIO_getc(fp);          /* get more characters */
8917         bp = (STDCHAR*)SvPVX_const(sv) + bpx;
8918
8919         DEBUG_Pv(PerlIO_printf(Perl_debug_log,
8920            "Screamer: post: FILE * thinks ptr=%" UVuf ", cnt=%" IVdf ", base=%" UVuf "\n",
8921             PTR2UV(PerlIO_get_ptr(fp)), (IV)PerlIO_get_cnt(fp),
8922             PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
8923
8924         /* find out how much is left in the read-ahead buffer, and rextract its pointer */
8925         cnt = PerlIO_get_cnt(fp);
8926         ptr = (STDCHAR*)PerlIO_get_ptr(fp);     /* reregisterize cnt and ptr */
8927         DEBUG_P(PerlIO_printf(Perl_debug_log,
8928             "Screamer: after getc, ptr=%" UVuf ", cnt=%" IVdf "\n",
8929             PTR2UV(ptr),(IV)cnt));
8930
8931         if (i == EOF)                   /* all done for ever? */
8932             goto thats_really_all_folks;
8933
8934         /* make sure we have enough space in the target sv */
8935         bpx = bp - (STDCHAR*)SvPVX_const(sv);   /* box up before relocation */
8936         SvCUR_set(sv, bpx);
8937         SvGROW(sv, bpx + cnt + 2);
8938         bp = (STDCHAR*)SvPVX_const(sv) + bpx;   /* unbox after relocation */
8939
8940         /* copy of the char we got from getc() */
8941         *bp++ = (STDCHAR)i;             /* store character from PerlIO_getc */
8942
8943         /* make sure we deal with the i being the last character of a separator */
8944         if (rslen && (STDCHAR)i == rslast)  /* all done for now? */
8945             goto thats_all_folks;
8946     }
8947
8948   thats_all_folks:
8949     /* check if we have actually found the separator - only really applies
8950      * when rslen > 1 */
8951     if ((rslen > 1 && (STRLEN)(bp - (STDCHAR*)SvPVX_const(sv)) < rslen) ||
8952           memNE((char*)bp - rslen, rsptr, rslen))
8953         goto screamer;                          /* go back to the fray */
8954   thats_really_all_folks:
8955     if (shortbuffered)
8956         cnt += shortbuffered;
8957     DEBUG_P(PerlIO_printf(Perl_debug_log,
8958          "Screamer: quitting, ptr=%" UVuf ", cnt=%" IVdf "\n",PTR2UV(ptr),(IV)cnt));
8959     PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt);  /* put these back or we're in trouble */
8960     DEBUG_P(PerlIO_printf(Perl_debug_log,
8961         "Screamer: end: FILE * thinks ptr=%" UVuf ", cnt=%" IVdf ", base=%" UVuf
8962         "\n",
8963         PTR2UV(PerlIO_get_ptr(fp)), (IV)PerlIO_get_cnt(fp),
8964         PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
8965     *bp = '\0';
8966     SvCUR_set(sv, bp - (STDCHAR*)SvPVX_const(sv));      /* set length */
8967     DEBUG_P(PerlIO_printf(Perl_debug_log,
8968         "Screamer: done, len=%ld, string=|%.*s|\n",
8969         (long)SvCUR(sv),(int)SvCUR(sv),SvPVX_const(sv)));
8970     }
8971    else
8972     {
8973        /*The big, slow, and stupid way. */
8974         STDCHAR buf[8192];
8975
8976       screamer2:
8977         if (rslen) {
8978             const STDCHAR * const bpe = buf + sizeof(buf);
8979             bp = buf;
8980             while ((i = PerlIO_getc(fp)) != EOF && (*bp++ = (STDCHAR)i) != rslast && bp < bpe)
8981                 ; /* keep reading */
8982             cnt = bp - buf;
8983         }
8984         else {
8985             cnt = PerlIO_read(fp,(char*)buf, sizeof(buf));
8986             /* Accommodate broken VAXC compiler, which applies U8 cast to
8987              * both args of ?: operator, causing EOF to change into 255
8988              */
8989             if (cnt > 0)
8990                  i = (U8)buf[cnt - 1];
8991             else
8992                  i = EOF;
8993         }
8994
8995         if (cnt < 0)
8996             cnt = 0;  /* we do need to re-set the sv even when cnt <= 0 */
8997         if (append)
8998             sv_catpvn_nomg(sv, (char *) buf, cnt);
8999         else
9000             sv_setpvn(sv, (char *) buf, cnt);   /* "nomg" is implied */
9001
9002         if (i != EOF &&                 /* joy */
9003             (!rslen ||
9004              SvCUR(sv) < rslen ||
9005              memNE(SvPVX_const(sv) + SvCUR(sv) - rslen, rsptr, rslen)))
9006         {
9007             append = -1;
9008             /*
9009              * If we're reading from a TTY and we get a short read,
9010              * indicating that the user hit his EOF character, we need
9011              * to notice it now, because if we try to read from the TTY
9012              * again, the EOF condition will disappear.
9013              *
9014              * The comparison of cnt to sizeof(buf) is an optimization
9015              * that prevents unnecessary calls to feof().
9016              *
9017              * - jik 9/25/96
9018              */
9019             if (!(cnt < (I32)sizeof(buf) && PerlIO_eof(fp)))
9020                 goto screamer2;
9021         }
9022
9023     }
9024
9025     if (rspara) {               /* have to do this both before and after */
9026         while (i != EOF) {      /* to make sure file boundaries work right */
9027             i = PerlIO_getc(fp);
9028             if (i != '\n') {
9029                 PerlIO_ungetc(fp,i);
9030                 break;
9031             }
9032         }
9033     }
9034
9035     return (SvCUR(sv) - append) ? SvPVX(sv) : NULL;
9036 }
9037
9038 /*
9039 =for apidoc sv_inc
9040 =for apidoc_item sv_inc_nomg
9041
9042 These auto-increment the value in the SV, doing string to numeric conversion
9043 if necessary.  They both handle operator overloading.
9044
9045 They differ only in that C<sv_inc> performs 'get' magic; C<sv_inc_nomg> skips
9046 any magic.
9047
9048 =cut
9049 */
9050
9051 void
9052 Perl_sv_inc(pTHX_ SV *const sv)
9053 {
9054     if (!sv)
9055         return;
9056     SvGETMAGIC(sv);
9057     sv_inc_nomg(sv);
9058 }
9059
9060 void
9061 Perl_sv_inc_nomg(pTHX_ SV *const sv)
9062 {
9063     char *d;
9064     int flags;
9065
9066     if (!sv)
9067         return;
9068     if (SvTHINKFIRST(sv)) {
9069         if (SvREADONLY(sv)) {
9070                 Perl_croak_no_modify();
9071         }
9072         if (SvROK(sv)) {
9073             IV i;
9074             if (SvAMAGIC(sv) && AMG_CALLunary(sv, inc_amg))
9075                 return;
9076             i = PTR2IV(SvRV(sv));
9077             sv_unref(sv);
9078             sv_setiv(sv, i);
9079         }
9080         else sv_force_normal_flags(sv, 0);
9081     }
9082     flags = SvFLAGS(sv);
9083     if ((flags & (SVp_NOK|SVp_IOK)) == SVp_NOK) {
9084         /* It's (privately or publicly) a float, but not tested as an
9085            integer, so test it to see. */
9086         (void) SvIV(sv);
9087         flags = SvFLAGS(sv);
9088     }
9089     if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
9090         /* It's publicly an integer, or privately an integer-not-float */
9091 #ifdef PERL_PRESERVE_IVUV
9092       oops_its_int:
9093 #endif
9094         if (SvIsUV(sv)) {
9095             if (SvUVX(sv) == UV_MAX)
9096                 sv_setnv(sv, UV_MAX_P1);
9097             else {
9098                 (void)SvIOK_only_UV(sv);
9099                 SvUV_set(sv, SvUVX(sv) + 1);
9100             }
9101         } else {
9102             if (SvIVX(sv) == IV_MAX)
9103                 sv_setuv(sv, (UV)IV_MAX + 1);
9104             else {
9105                 (void)SvIOK_only(sv);
9106                 SvIV_set(sv, SvIVX(sv) + 1);
9107             }
9108         }
9109         return;
9110     }
9111     if (flags & SVp_NOK) {
9112         const NV was = SvNVX(sv);
9113         if (NV_OVERFLOWS_INTEGERS_AT != 0.0 &&
9114             /* If NVX was NaN, the following comparisons return always false */
9115             UNLIKELY(was >= NV_OVERFLOWS_INTEGERS_AT ||
9116                      was < -NV_OVERFLOWS_INTEGERS_AT) &&
9117 #if defined(NAN_COMPARE_BROKEN)
9118             LIKELY(!Perl_isinfnan(was))
9119 #else
9120             LIKELY(!Perl_isinf(was))
9121 #endif
9122             ) {
9123             /* diag_listed_as: Lost precision when %s %f by 1 */
9124             Perl_ck_warner(aTHX_ packWARN(WARN_IMPRECISION),
9125                            "Lost precision when incrementing %" NVff " by 1",
9126                            was);
9127         }
9128         (void)SvNOK_only(sv);
9129         SvNV_set(sv, was + 1.0);
9130         return;
9131     }
9132
9133     /* treat AV/HV/CV/FM/IO and non-fake GVs as immutable */
9134     if (SvTYPE(sv) >= SVt_PVAV || (isGV_with_GP(sv) && !SvFAKE(sv)))
9135         Perl_croak_no_modify();
9136
9137     if (!(flags & SVp_POK) || !*SvPVX_const(sv)) {
9138         if ((flags & SVTYPEMASK) < SVt_PVIV)
9139             sv_upgrade(sv, ((flags & SVTYPEMASK) > SVt_IV ? SVt_PVIV : SVt_IV));
9140         (void)SvIOK_only(sv);
9141         SvIV_set(sv, 1);
9142         return;
9143     }
9144     d = SvPVX(sv);
9145     while (isALPHA(*d)) d++;
9146     while (isDIGIT(*d)) d++;
9147     if (d < SvEND(sv)) {
9148         const int numtype = grok_number_flags(SvPVX_const(sv), SvCUR(sv), NULL, PERL_SCAN_TRAILING);
9149 #ifdef PERL_PRESERVE_IVUV
9150         /* Got to punt this as an integer if needs be, but we don't issue
9151            warnings. Probably ought to make the sv_iv_please() that does
9152            the conversion if possible, and silently.  */
9153         if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
9154             /* Need to try really hard to see if it's an integer.
9155                9.22337203685478e+18 is an integer.
9156                but "9.22337203685478e+18" + 0 is UV=9223372036854779904
9157                so $a="9.22337203685478e+18"; $a+0; $a++
9158                needs to be the same as $a="9.22337203685478e+18"; $a++
9159                or we go insane. */
9160
9161             (void) sv_2iv(sv);
9162             if (SvIOK(sv))
9163                 goto oops_its_int;
9164
9165             /* sv_2iv *should* have made this an NV */
9166             if (flags & SVp_NOK) {
9167                 (void)SvNOK_only(sv);
9168                 SvNV_set(sv, SvNVX(sv) + 1.0);
9169                 return;
9170             }
9171             /* I don't think we can get here. Maybe I should assert this
9172                And if we do get here I suspect that sv_setnv will croak. NWC
9173                Fall through. */
9174             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_inc punt failed to convert '%s' to IOK or NOKp, UV=0x%" UVxf " NV=%" NVgf "\n",
9175                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
9176         }
9177 #endif /* PERL_PRESERVE_IVUV */
9178         if (!numtype && ckWARN(WARN_NUMERIC))
9179             not_incrementable(sv);
9180         sv_setnv(sv,Atof(SvPVX_const(sv)) + 1.0);
9181         return;
9182     }
9183     d--;
9184     while (d >= SvPVX_const(sv)) {
9185         if (isDIGIT(*d)) {
9186             if (++*d <= '9')
9187                 return;
9188             *(d--) = '0';
9189         }
9190         else {
9191 #ifdef EBCDIC
9192             /* MKS: The original code here died if letters weren't consecutive.
9193              * at least it didn't have to worry about non-C locales.  The
9194              * new code assumes that ('z'-'a')==('Z'-'A'), letters are
9195              * arranged in order (although not consecutively) and that only
9196              * [A-Za-z] are accepted by isALPHA in the C locale.
9197              */
9198             if (isALPHA_FOLD_NE(*d, 'z')) {
9199                 do { ++*d; } while (!isALPHA(*d));
9200                 return;
9201             }
9202             *(d--) -= 'z' - 'a';
9203 #else
9204             ++*d;
9205             if (isALPHA(*d))
9206                 return;
9207             *(d--) -= 'z' - 'a' + 1;
9208 #endif
9209         }
9210     }
9211     /* oh,oh, the number grew */
9212     SvGROW(sv, SvCUR(sv) + 2);
9213     SvCUR_set(sv, SvCUR(sv) + 1);
9214     for (d = SvPVX(sv) + SvCUR(sv); d > SvPVX_const(sv); d--)
9215         *d = d[-1];
9216     if (isDIGIT(d[1]))
9217         *d = '1';
9218     else
9219         *d = d[1];
9220 }
9221
9222 /*
9223 =for apidoc sv_dec
9224 =for apidoc_item sv_dec_nomg
9225
9226 These auto-decrement the value in the SV, doing string to numeric conversion
9227 if necessary.  They both handle operator overloading.
9228
9229 They differ only in that:
9230
9231 C<sv_dec> handles 'get' magic; C<sv_dec_nomg> skips 'get' magic.
9232
9233 =cut
9234 */
9235
9236 void
9237 Perl_sv_dec(pTHX_ SV *const sv)
9238 {
9239     if (!sv)
9240         return;
9241     SvGETMAGIC(sv);
9242     sv_dec_nomg(sv);
9243 }
9244
9245 void
9246 Perl_sv_dec_nomg(pTHX_ SV *const sv)
9247 {
9248     int flags;
9249
9250     if (!sv)
9251         return;
9252     if (SvTHINKFIRST(sv)) {
9253         if (SvREADONLY(sv)) {
9254                 Perl_croak_no_modify();
9255         }
9256         if (SvROK(sv)) {
9257             IV i;
9258             if (SvAMAGIC(sv) && AMG_CALLunary(sv, dec_amg))
9259                 return;
9260             i = PTR2IV(SvRV(sv));
9261             sv_unref(sv);
9262             sv_setiv(sv, i);
9263         }
9264         else sv_force_normal_flags(sv, 0);
9265     }
9266     /* Unlike sv_inc we don't have to worry about string-never-numbers
9267        and keeping them magic. But we mustn't warn on punting */
9268     flags = SvFLAGS(sv);
9269     if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
9270         /* It's publicly an integer, or privately an integer-not-float */
9271 #ifdef PERL_PRESERVE_IVUV
9272       oops_its_int:
9273 #endif
9274         if (SvIsUV(sv)) {
9275             if (SvUVX(sv) == 0) {
9276                 (void)SvIOK_only(sv);
9277                 SvIV_set(sv, -1);
9278             }
9279             else {
9280                 (void)SvIOK_only_UV(sv);
9281                 SvUV_set(sv, SvUVX(sv) - 1);
9282             }
9283         } else {
9284             if (SvIVX(sv) == IV_MIN) {
9285                 sv_setnv(sv, (NV)IV_MIN);
9286                 goto oops_its_num;
9287             }
9288             else {
9289                 (void)SvIOK_only(sv);
9290                 SvIV_set(sv, SvIVX(sv) - 1);
9291             }
9292         }
9293         return;
9294     }
9295     if (flags & SVp_NOK) {
9296     oops_its_num:
9297         {
9298             const NV was = SvNVX(sv);
9299             if (NV_OVERFLOWS_INTEGERS_AT != 0.0 &&
9300                 /* If NVX was NaN, these comparisons return always false */
9301                 UNLIKELY(was <= -NV_OVERFLOWS_INTEGERS_AT ||
9302                          was > NV_OVERFLOWS_INTEGERS_AT) &&
9303 #if defined(NAN_COMPARE_BROKEN)
9304                 LIKELY(!Perl_isinfnan(was))
9305 #else
9306                 LIKELY(!Perl_isinf(was))
9307 #endif
9308                 ) {
9309                 /* diag_listed_as: Lost precision when %s %f by 1 */
9310                 Perl_ck_warner(aTHX_ packWARN(WARN_IMPRECISION),
9311                                "Lost precision when decrementing %" NVff " by 1",
9312                                was);
9313             }
9314             (void)SvNOK_only(sv);
9315             SvNV_set(sv, was - 1.0);
9316             return;
9317         }
9318     }
9319
9320     /* treat AV/HV/CV/FM/IO and non-fake GVs as immutable */
9321     if (SvTYPE(sv) >= SVt_PVAV || (isGV_with_GP(sv) && !SvFAKE(sv)))
9322         Perl_croak_no_modify();
9323
9324     if (!(flags & SVp_POK)) {
9325         if ((flags & SVTYPEMASK) < SVt_PVIV)
9326             sv_upgrade(sv, ((flags & SVTYPEMASK) > SVt_IV) ? SVt_PVIV : SVt_IV);
9327         SvIV_set(sv, -1);
9328         (void)SvIOK_only(sv);
9329         return;
9330     }
9331 #ifdef PERL_PRESERVE_IVUV
9332     {
9333         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), NULL);
9334         if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
9335             /* Need to try really hard to see if it's an integer.
9336                9.22337203685478e+18 is an integer.
9337                but "9.22337203685478e+18" + 0 is UV=9223372036854779904
9338                so $a="9.22337203685478e+18"; $a+0; $a--
9339                needs to be the same as $a="9.22337203685478e+18"; $a--
9340                or we go insane. */
9341
9342             (void) sv_2iv(sv);
9343             if (SvIOK(sv))
9344                 goto oops_its_int;
9345
9346             /* sv_2iv *should* have made this an NV */
9347             if (flags & SVp_NOK) {
9348                 (void)SvNOK_only(sv);
9349                 SvNV_set(sv, SvNVX(sv) - 1.0);
9350                 return;
9351             }
9352             /* I don't think we can get here. Maybe I should assert this
9353                And if we do get here I suspect that sv_setnv will croak. NWC
9354                Fall through. */
9355             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_dec punt failed to convert '%s' to IOK or NOKp, UV=0x%" UVxf " NV=%" NVgf "\n",
9356                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
9357         }
9358     }
9359 #endif /* PERL_PRESERVE_IVUV */
9360     sv_setnv(sv,Atof(SvPVX_const(sv)) - 1.0);   /* punt */
9361 }
9362
9363 /* this define is used to eliminate a chunk of duplicated but shared logic
9364  * it has the suffix __SV_C to signal that it isnt API, and isnt meant to be
9365  * used anywhere but here - yves
9366  */
9367 #define PUSH_EXTEND_MORTAL__SV_C(AnSv) \
9368     STMT_START {      \
9369         SSize_t ix = ++PL_tmps_ix;              \
9370         if (UNLIKELY(ix >= PL_tmps_max))        \
9371             ix = tmps_grow_p(ix);                       \
9372         PL_tmps_stack[ix] = (AnSv); \
9373     } STMT_END
9374
9375 /*
9376 =for apidoc sv_mortalcopy
9377
9378 Creates a new SV which is a copy of the original SV (using C<sv_setsv>).
9379 The new SV is marked as mortal.  It will be destroyed "soon", either by an
9380 explicit call to C<FREETMPS>, or by an implicit call at places such as
9381 statement boundaries.  See also C<L</sv_newmortal>> and C<L</sv_2mortal>>.
9382
9383 =for apidoc sv_mortalcopy_flags
9384
9385 Like C<sv_mortalcopy>, but the extra C<flags> are passed to the
9386 C<sv_setsv_flags>.
9387
9388 =cut
9389 */
9390
9391 /* Make a string that will exist for the duration of the expression
9392  * evaluation.  Actually, it may have to last longer than that, but
9393  * hopefully we won't free it until it has been assigned to a
9394  * permanent location. */
9395
9396 SV *
9397 Perl_sv_mortalcopy_flags(pTHX_ SV *const oldstr, U32 flags)
9398 {
9399     SV *sv;
9400
9401     if (flags & SV_GMAGIC)
9402         SvGETMAGIC(oldstr); /* before new_SV, in case it dies */
9403     new_SV(sv);
9404     sv_setsv_flags(sv,oldstr,flags & ~SV_GMAGIC);
9405     PUSH_EXTEND_MORTAL__SV_C(sv);
9406     SvTEMP_on(sv);
9407     return sv;
9408 }
9409
9410 /*
9411 =for apidoc sv_newmortal
9412
9413 Creates a new null SV which is mortal.  The reference count of the SV is
9414 set to 1.  It will be destroyed "soon", either by an explicit call to
9415 C<FREETMPS>, or by an implicit call at places such as statement boundaries.
9416 See also C<L</sv_mortalcopy>> and C<L</sv_2mortal>>.
9417
9418 =cut
9419 */
9420
9421 SV *
9422 Perl_sv_newmortal(pTHX)
9423 {
9424     SV *sv;
9425
9426     new_SV(sv);
9427     SvFLAGS(sv) = SVs_TEMP;
9428     PUSH_EXTEND_MORTAL__SV_C(sv);
9429     return sv;
9430 }
9431
9432
9433 /*
9434 =for apidoc newSVpvn_flags
9435
9436 Creates a new SV and copies a string (which may contain C<NUL> (C<\0>)
9437 characters) into it.  The reference count for the
9438 SV is set to 1.  Note that if C<len> is zero, Perl will create a zero length
9439 string.  You are responsible for ensuring that the source string is at least
9440 C<len> bytes long.  If the C<s> argument is NULL the new SV will be undefined.
9441 Currently the only flag bits accepted are C<SVf_UTF8> and C<SVs_TEMP>.
9442 If C<SVs_TEMP> is set, then C<sv_2mortal()> is called on the result before
9443 returning.  If C<SVf_UTF8> is set, C<s>
9444 is considered to be in UTF-8 and the
9445 C<SVf_UTF8> flag will be set on the new SV.
9446 C<newSVpvn_utf8()> is a convenience wrapper for this function, defined as
9447
9448     #define newSVpvn_utf8(s, len, u)                    \
9449         newSVpvn_flags((s), (len), (u) ? SVf_UTF8 : 0)
9450
9451 =for apidoc Amnh||SVs_TEMP
9452
9453 =cut
9454 */
9455
9456 SV *
9457 Perl_newSVpvn_flags(pTHX_ const char *const s, const STRLEN len, const U32 flags)
9458 {
9459     SV *sv;
9460
9461     /* All the flags we don't support must be zero.
9462        And we're new code so I'm going to assert this from the start.  */
9463     assert(!(flags & ~(SVf_UTF8|SVs_TEMP)));
9464     sv = newSV_type(SVt_PV);
9465     sv_setpvn_fresh(sv,s,len);
9466
9467     /* This code used to do a sv_2mortal(), however we now unroll the call to
9468      * sv_2mortal() and do what it does ourselves here.  Since we have asserted
9469      * that flags can only have the SVf_UTF8 and/or SVs_TEMP flags set above we
9470      * can use it to enable the sv flags directly (bypassing SvTEMP_on), which
9471      * in turn means we dont need to mask out the SVf_UTF8 flag below, which
9472      * means that we eliminate quite a few steps than it looks - Yves
9473      * (explaining patch by gfx) */
9474
9475     SvFLAGS(sv) |= flags;
9476
9477     if(flags & SVs_TEMP){
9478         PUSH_EXTEND_MORTAL__SV_C(sv);
9479     }
9480
9481     return sv;
9482 }
9483
9484 /*
9485 =for apidoc sv_2mortal
9486
9487 Marks an existing SV as mortal.  The SV will be destroyed "soon", either
9488 by an explicit call to C<FREETMPS>, or by an implicit call at places such as
9489 statement boundaries.  C<SvTEMP()> is turned on which means that the SV's
9490 string buffer can be "stolen" if this SV is copied.  See also
9491 C<L</sv_newmortal>> and C<L</sv_mortalcopy>>.
9492
9493 =cut
9494 */
9495
9496 SV *
9497 Perl_sv_2mortal(pTHX_ SV *const sv)
9498 {
9499     if (!sv)
9500         return sv;
9501     if (SvIMMORTAL(sv))
9502         return sv;
9503     PUSH_EXTEND_MORTAL__SV_C(sv);
9504     SvTEMP_on(sv);
9505     return sv;
9506 }
9507
9508 /*
9509 =for apidoc newSVpv
9510
9511 Creates a new SV and copies a string (which may contain C<NUL> (C<\0>)
9512 characters) into it.  The reference count for the
9513 SV is set to 1.  If C<len> is zero, Perl will compute the length using
9514 C<strlen()>, (which means if you use this option, that C<s> can't have embedded
9515 C<NUL> characters and has to have a terminating C<NUL> byte).
9516
9517 This function can cause reliability issues if you are likely to pass in
9518 empty strings that are not null terminated, because it will run
9519 strlen on the string and potentially run past valid memory.
9520
9521 Using L</newSVpvn> is a safer alternative for non C<NUL> terminated strings.
9522 For string literals use L</newSVpvs> instead.  This function will work fine for
9523 C<NUL> terminated strings, but if you want to avoid the if statement on whether
9524 to call C<strlen> use C<newSVpvn> instead (calling C<strlen> yourself).
9525
9526 =cut
9527 */
9528
9529 SV *
9530 Perl_newSVpv(pTHX_ const char *const s, const STRLEN len)
9531 {
9532     SV *sv = newSV_type(SVt_PV);
9533     sv_setpvn_fresh(sv, s, len || s == NULL ? len : strlen(s));
9534     return sv;
9535 }
9536
9537 /*
9538 =for apidoc newSVpvn
9539
9540 Creates a new SV and copies a string into it, which may contain C<NUL> characters
9541 (C<\0>) and other binary data.  The reference count for the SV is set to 1.
9542 Note that if C<len> is zero, Perl will create a zero length (Perl) string.  You
9543 are responsible for ensuring that the source buffer is at least
9544 C<len> bytes long.  If the C<buffer> argument is NULL the new SV will be
9545 undefined.
9546
9547 =cut
9548 */
9549
9550 SV *
9551 Perl_newSVpvn(pTHX_ const char *const buffer, const STRLEN len)
9552 {
9553     SV *sv = newSV_type(SVt_PV);
9554     sv_setpvn_fresh(sv,buffer,len);
9555     return sv;
9556 }
9557
9558 /*
9559 =for apidoc newSVhek_mortal
9560
9561 Creates a new mortal SV from the hash key structure.  It will generate
9562 scalars that point to the shared string table where possible.  Returns
9563 a new (undefined) SV if C<hek> is NULL.
9564
9565 This is more efficient than using sv_2mortal(newSVhek( ... ))
9566
9567 =cut
9568 */
9569
9570 SV *
9571 Perl_newSVhek_mortal(pTHX_ const HEK *const hek)
9572 {
9573     SV * const sv = newSVhek(hek);
9574     assert(sv);
9575     assert(!SvIMMORTAL(sv));
9576
9577     PUSH_EXTEND_MORTAL__SV_C(sv);
9578     SvTEMP_on(sv);
9579     return sv;
9580 }
9581
9582 /*
9583 =for apidoc newSVhek
9584
9585 Creates a new SV from the hash key structure.  It will generate scalars that
9586 point to the shared string table where possible.  Returns a new (undefined)
9587 SV if C<hek> is NULL.
9588
9589 =cut
9590 */
9591
9592 SV *
9593 Perl_newSVhek(pTHX_ const HEK *const hek)
9594 {
9595     if (!hek) {
9596         SV *sv;
9597
9598         new_SV(sv);
9599         return sv;
9600     }
9601
9602     if (HEK_LEN(hek) == HEf_SVKEY) {
9603         return newSVsv(*(SV**)HEK_KEY(hek));
9604     } else {
9605         const int flags = HEK_FLAGS(hek);
9606         if (flags & HVhek_WASUTF8) {
9607             /* Trouble :-)
9608                Andreas would like keys he put in as utf8 to come back as utf8
9609             */
9610             STRLEN utf8_len = HEK_LEN(hek);
9611             SV * const sv = newSV_type(SVt_PV);
9612             char *as_utf8 = (char *)bytes_to_utf8 ((U8*)HEK_KEY(hek), &utf8_len);
9613             /* bytes_to_utf8() allocates a new string, which we can repurpose: */
9614             sv_usepvn_flags(sv, as_utf8, utf8_len, SV_HAS_TRAILING_NUL);
9615             SvUTF8_on (sv);
9616             return sv;
9617         } else if (flags & HVhek_NOTSHARED) {
9618             /* A hash that isn't using shared hash keys has to have
9619                the flag in every key so that we know not to try to call
9620                share_hek_hek on it.  */
9621
9622             SV * const sv = newSVpvn (HEK_KEY(hek), HEK_LEN(hek));
9623             if (HEK_UTF8(hek))
9624                 SvUTF8_on (sv);
9625             return sv;
9626         }
9627         /* This will be overwhelminly the most common case.  */
9628         {
9629             /* Inline most of newSVpvn_share(), because share_hek_hek() is far
9630                more efficient than sharepvn().  */
9631             SV *sv = newSV_type(SVt_PV);
9632
9633             SvPV_set(sv, (char *)HEK_KEY(share_hek_hek(hek)));
9634             SvCUR_set(sv, HEK_LEN(hek));
9635             SvLEN_set(sv, 0);
9636             SvIsCOW_on(sv);
9637             SvPOK_on(sv);
9638             if (HEK_UTF8(hek))
9639                 SvUTF8_on(sv);
9640             return sv;
9641         }
9642     }
9643 }
9644
9645 /*
9646 =for apidoc newSVpvn_share
9647
9648 Creates a new SV with its C<SvPVX_const> pointing to a shared string in the string
9649 table.  If the string does not already exist in the table, it is
9650 created first.  Turns on the C<SvIsCOW> flag (or C<READONLY>
9651 and C<FAKE> in 5.16 and earlier).  If the C<hash> parameter
9652 is non-zero, that value is used; otherwise the hash is computed.
9653 The string's hash can later be retrieved from the SV
9654 with the C<L</SvSHARED_HASH>> macro.  The idea here is
9655 that as the string table is used for shared hash keys these strings will have
9656 C<SvPVX_const == HeKEY> and hash lookup will avoid string compare.
9657
9658 =cut
9659 */
9660
9661 SV *
9662 Perl_newSVpvn_share(pTHX_ const char *src, I32 len, U32 hash)
9663 {
9664     SV *sv;
9665     bool is_utf8 = FALSE;
9666     const char *const orig_src = src;
9667
9668     if (len < 0) {
9669         STRLEN tmplen = -len;
9670         is_utf8 = TRUE;
9671         /* See the note in hv.c:hv_fetch() --jhi */
9672         src = (char*)bytes_from_utf8((const U8*)src, &tmplen, &is_utf8);
9673         len = tmplen;
9674     }
9675     if (!hash)
9676         PERL_HASH(hash, src, len);
9677     sv = newSV_type(SVt_PV);
9678     /* The logic for this is inlined in S_mro_get_linear_isa_dfs(), so if it
9679        changes here, update it there too.  */
9680     SvPV_set(sv, sharepvn(src, is_utf8?-len:len, hash));
9681     SvCUR_set(sv, len);
9682     SvLEN_set(sv, 0);
9683     SvIsCOW_on(sv);
9684     SvPOK_on(sv);
9685     if (is_utf8)
9686         SvUTF8_on(sv);
9687     if (src != orig_src)
9688         Safefree(src);
9689     return sv;
9690 }
9691
9692 /*
9693 =for apidoc newSVpv_share
9694
9695 Like C<newSVpvn_share>, but takes a C<NUL>-terminated string instead of a
9696 string/length pair.
9697
9698 =cut
9699 */
9700
9701 SV *
9702 Perl_newSVpv_share(pTHX_ const char *src, U32 hash)
9703 {
9704     return newSVpvn_share(src, strlen(src), hash);
9705 }
9706
9707 #if defined(MULTIPLICITY)
9708
9709 /* pTHX_ magic can't cope with varargs, so this is a no-context
9710  * version of the main function, (which may itself be aliased to us).
9711  * Don't access this version directly.
9712  */
9713
9714 SV *
9715 Perl_newSVpvf_nocontext(const char *const pat, ...)
9716 {
9717     dTHX;
9718     SV *sv;
9719     va_list args;
9720
9721     PERL_ARGS_ASSERT_NEWSVPVF_NOCONTEXT;
9722
9723     va_start(args, pat);
9724     sv = vnewSVpvf(pat, &args);
9725     va_end(args);
9726     return sv;
9727 }
9728 #endif
9729
9730 /*
9731 =for apidoc newSVpvf
9732
9733 Creates a new SV and initializes it with the string formatted like
9734 C<sv_catpvf>.
9735
9736 =for apidoc newSVpvf_nocontext
9737 Like C<L</newSVpvf>> but does not take a thread context (C<aTHX>) parameter,
9738 so is used in situations where the caller doesn't already have the thread
9739 context.
9740
9741 =for apidoc vnewSVpvf
9742 Like C<L</newSVpvf>> but the arguments are an encapsulated argument list.
9743
9744 =cut
9745 */
9746
9747 SV *
9748 Perl_newSVpvf(pTHX_ const char *const pat, ...)
9749 {
9750     SV *sv;
9751     va_list args;
9752
9753     PERL_ARGS_ASSERT_NEWSVPVF;
9754
9755     va_start(args, pat);
9756     sv = vnewSVpvf(pat, &args);
9757     va_end(args);
9758     return sv;
9759 }
9760
9761 /* backend for newSVpvf() and newSVpvf_nocontext() */
9762
9763 SV *
9764 Perl_vnewSVpvf(pTHX_ const char *const pat, va_list *const args)
9765 {
9766     SV *sv;
9767
9768     PERL_ARGS_ASSERT_VNEWSVPVF;
9769
9770     sv = newSV(1);
9771     SvPVCLEAR_FRESH(sv);
9772     sv_vcatpvfn_flags(sv, pat, strlen(pat), args, NULL, 0, NULL, 0);
9773     return sv;
9774 }
9775
9776 /*
9777 =for apidoc newSVnv
9778
9779 Creates a new SV and copies a floating point value into it.
9780 The reference count for the SV is set to 1.
9781
9782 =cut
9783 */
9784
9785 SV *
9786 Perl_newSVnv(pTHX_ const NV n)
9787 {
9788     SV *sv = newSV_type(SVt_NV);
9789     (void)SvNOK_on(sv);
9790
9791     SvNV_set(sv, n);
9792     SvTAINT(sv);
9793
9794     return sv;
9795 }
9796
9797 /*
9798 =for apidoc newSViv
9799
9800 Creates a new SV and copies an integer into it.  The reference count for the
9801 SV is set to 1.
9802
9803 =cut
9804 */
9805
9806 SV *
9807 Perl_newSViv(pTHX_ const IV i)
9808 {
9809     SV *sv = newSV_type(SVt_IV);
9810     (void)SvIOK_on(sv);
9811
9812     SvIV_set(sv, i);
9813     SvTAINT(sv);
9814
9815     return sv;
9816 }
9817
9818 /*
9819 =for apidoc newSVuv
9820
9821 Creates a new SV and copies an unsigned integer into it.
9822 The reference count for the SV is set to 1.
9823
9824 =cut
9825 */
9826
9827 SV *
9828 Perl_newSVuv(pTHX_ const UV u)
9829 {
9830     SV *sv;
9831
9832     /* Inlining ONLY the small relevant subset of sv_setuv here
9833      * for performance. Makes a significant difference. */
9834
9835     /* Using ivs is more efficient than using uvs - see sv_setuv */
9836     if (u <= (UV)IV_MAX) {
9837         return newSViv((IV)u);
9838     }
9839
9840     new_SV(sv);
9841
9842     /* We're starting from SVt_FIRST, so provided that's
9843      * actual 0, we don't have to unset any SV type flags
9844      * to promote to SVt_IV. */
9845     STATIC_ASSERT_STMT(SVt_FIRST == 0);
9846
9847     SET_SVANY_FOR_BODYLESS_IV(sv);
9848     SvFLAGS(sv) |= SVt_IV;
9849     (void)SvIOK_on(sv);
9850     (void)SvIsUV_on(sv);
9851
9852     SvUV_set(sv, u);
9853     SvTAINT(sv);
9854
9855     return sv;
9856 }
9857
9858 /*
9859 =for apidoc newSVbool
9860
9861 Creates a new SV boolean.
9862
9863 =cut
9864 */
9865
9866 SV *
9867 Perl_newSVbool(pTHX_ bool bool_val)
9868 {
9869     PERL_ARGS_ASSERT_NEWSVBOOL;
9870     SV *sv = newSVsv(bool_val ? &PL_sv_yes : &PL_sv_no);
9871
9872     return sv;
9873 }
9874
9875 /*
9876 =for apidoc newSV_true
9877
9878 Creates a new SV that is a boolean true.
9879
9880 =cut
9881 */
9882 SV *
9883 Perl_newSV_true(pTHX)
9884 {
9885     PERL_ARGS_ASSERT_NEWSV_TRUE;
9886     SV *sv = newSVsv(&PL_sv_yes);
9887
9888     return sv;
9889 }
9890
9891 /*
9892 =for apidoc newSV_false
9893
9894 Creates a new SV that is a boolean false.
9895
9896 =cut
9897 */
9898
9899 SV *
9900 Perl_newSV_false(pTHX)
9901 {
9902     PERL_ARGS_ASSERT_NEWSV_FALSE;
9903     SV *sv = newSVsv(&PL_sv_no);
9904
9905     return sv;
9906 }
9907
9908 /* newRV_inc is the official function name to use now.
9909  * newRV_inc is in fact #defined to newRV in sv.h
9910  */
9911
9912 SV *
9913 Perl_newRV(pTHX_ SV *const sv)
9914 {
9915     PERL_ARGS_ASSERT_NEWRV;
9916
9917     return newRV_noinc(SvREFCNT_inc_simple_NN(sv));
9918 }
9919
9920 /*
9921 =for apidoc newSVsv
9922 =for apidoc_item newSVsv_flags
9923 =for apidoc_item newSVsv_nomg
9924
9925 These create a new SV which is an exact duplicate of the original SV
9926 (using C<sv_setsv>.)
9927
9928 They differ only in that C<newSVsv> performs 'get' magic; C<newSVsv_nomg> skips
9929 any magic; and C<newSVsv_flags> allows you to explicitly set a C<flags>
9930 parameter.
9931
9932 =cut
9933 */
9934
9935 SV *
9936 Perl_newSVsv_flags(pTHX_ SV *const old, I32 flags)
9937 {
9938     SV *sv;
9939
9940     if (!old)
9941         return NULL;
9942     if (SvTYPE(old) == (svtype)SVTYPEMASK) {
9943         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "semi-panic: attempt to dup freed string");
9944         return NULL;
9945     }
9946     /* Do this here, otherwise we leak the new SV if this croaks. */
9947     if (flags & SV_GMAGIC)
9948         SvGETMAGIC(old);
9949     new_SV(sv);
9950     sv_setsv_flags(sv, old, flags & ~SV_GMAGIC);
9951     return sv;
9952 }
9953
9954 /*
9955 =for apidoc sv_reset
9956
9957 Underlying implementation for the C<reset> Perl function.
9958 Note that the perl-level function is vaguely deprecated.
9959
9960 =cut
9961 */
9962
9963 void
9964 Perl_sv_reset(pTHX_ const char *s, HV *const stash)
9965 {
9966     PERL_ARGS_ASSERT_SV_RESET;
9967
9968     sv_resetpvn(*s ? s : NULL, strlen(s), stash);
9969 }
9970
9971 void
9972 Perl_sv_resetpvn(pTHX_ const char *s, STRLEN len, HV * const stash)
9973 {
9974     char todo[PERL_UCHAR_MAX+1];
9975     const char *send;
9976
9977     if (!stash || SvTYPE(stash) != SVt_PVHV)
9978         return;
9979
9980     if (!s) {           /* reset ?? searches */
9981         MAGIC * const mg = mg_find((const SV *)stash, PERL_MAGIC_symtab);
9982         if (mg && mg->mg_len) {
9983             const U32 count = mg->mg_len / sizeof(PMOP**);
9984             PMOP **pmp = (PMOP**) mg->mg_ptr;
9985             PMOP *const *const end = pmp + count;
9986
9987             while (pmp < end) {
9988 #ifdef USE_ITHREADS
9989                 SvREADONLY_off(PL_regex_pad[(*pmp)->op_pmoffset]);
9990 #else
9991                 (*pmp)->op_pmflags &= ~PMf_USED;
9992 #endif
9993                 ++pmp;
9994             }
9995         }
9996         return;
9997     }
9998
9999     /* reset variables */
10000
10001     if (!HvTOTALKEYS(stash))
10002         return;
10003
10004     Zero(todo, 256, char);
10005     send = s + len;
10006     while (s < send) {
10007         I32 max;
10008         I32 i = (unsigned char)*s;
10009         if (s[1] == '-') {
10010             s += 2;
10011         }
10012         max = (unsigned char)*s++;
10013         for ( ; i <= max; i++) {
10014             todo[i] = 1;
10015         }
10016         for (i = 0; i <= (I32) HvMAX(stash); i++) {
10017             HE *entry;
10018             for (entry = HvARRAY(stash)[i];
10019                  entry;
10020                  entry = HeNEXT(entry))
10021             {
10022                 GV *gv;
10023                 SV *sv;
10024
10025                 if (!todo[(U8)*HeKEY(entry)])
10026                     continue;
10027                 gv = MUTABLE_GV(HeVAL(entry));
10028                 if (!isGV(gv))
10029                     continue;
10030                 sv = GvSV(gv);
10031                 if (sv && !SvREADONLY(sv)) {
10032                     SV_CHECK_THINKFIRST_COW_DROP(sv);
10033                     if (!isGV(sv)) SvOK_off(sv);
10034                 }
10035                 if (GvAV(gv)) {
10036                     av_clear(GvAV(gv));
10037                 }
10038                 if (GvHV(gv) && !HvNAME_get(GvHV(gv))) {
10039                     hv_clear(GvHV(gv));
10040                 }
10041             }
10042         }
10043     }
10044 }
10045
10046 /*
10047 =for apidoc sv_2io
10048
10049 Using various gambits, try to get an IO from an SV: the IO slot if its a
10050 GV; or the recursive result if we're an RV; or the IO slot of the symbol
10051 named after the PV if we're a string.
10052
10053 'Get' magic is ignored on the C<sv> passed in, but will be called on
10054 C<SvRV(sv)> if C<sv> is an RV.
10055
10056 =cut
10057 */
10058
10059 IO*
10060 Perl_sv_2io(pTHX_ SV *const sv)
10061 {
10062     IO* io;
10063     GV* gv;
10064
10065     PERL_ARGS_ASSERT_SV_2IO;
10066
10067     switch (SvTYPE(sv)) {
10068     case SVt_PVIO:
10069         io = MUTABLE_IO(sv);
10070         break;
10071     case SVt_PVGV:
10072     case SVt_PVLV:
10073         if (isGV_with_GP(sv)) {
10074             gv = MUTABLE_GV(sv);
10075             io = GvIO(gv);
10076             if (!io)
10077                 Perl_croak(aTHX_ "Bad filehandle: %" HEKf,
10078                                     HEKfARG(GvNAME_HEK(gv)));
10079             break;
10080         }
10081         /* FALLTHROUGH */
10082     default:
10083         if (!SvOK(sv))
10084             Perl_croak(aTHX_ PL_no_usym, "filehandle");
10085         if (SvROK(sv)) {
10086             SvGETMAGIC(SvRV(sv));
10087             return sv_2io(SvRV(sv));
10088         }
10089         gv = gv_fetchsv_nomg(sv, 0, SVt_PVIO);
10090         if (gv)
10091             io = GvIO(gv);
10092         else
10093             io = 0;
10094         if (!io) {
10095             SV *newsv = sv;
10096             if (SvGMAGICAL(sv)) {
10097                 newsv = sv_newmortal();
10098                 sv_setsv_nomg(newsv, sv);
10099             }
10100             Perl_croak(aTHX_ "Bad filehandle: %" SVf, SVfARG(newsv));
10101         }
10102         break;
10103     }
10104     return io;
10105 }
10106
10107 /*
10108 =for apidoc sv_2cv
10109
10110 Using various gambits, try to get a CV from an SV; in addition, try if
10111 possible to set C<*st> and C<*gvp> to the stash and GV associated with it.
10112 The flags in C<lref> are passed to C<gv_fetchsv>.
10113
10114 =cut
10115 */
10116
10117 CV *
10118 Perl_sv_2cv(pTHX_ SV *sv, HV **const st, GV **const gvp, const I32 lref)
10119 {
10120     GV *gv = NULL;
10121     CV *cv = NULL;
10122
10123     PERL_ARGS_ASSERT_SV_2CV;
10124
10125     if (!sv) {
10126         *st = NULL;
10127         *gvp = NULL;
10128         return NULL;
10129     }
10130     switch (SvTYPE(sv)) {
10131     case SVt_PVCV:
10132         *st = CvSTASH(sv);
10133         *gvp = NULL;
10134         return MUTABLE_CV(sv);
10135     case SVt_PVHV:
10136     case SVt_PVAV:
10137         *st = NULL;
10138         *gvp = NULL;
10139         return NULL;
10140     default:
10141         SvGETMAGIC(sv);
10142         if (SvROK(sv)) {
10143             if (SvAMAGIC(sv))
10144                 sv = amagic_deref_call(sv, to_cv_amg);
10145
10146             sv = SvRV(sv);
10147             if (SvTYPE(sv) == SVt_PVCV) {
10148                 cv = MUTABLE_CV(sv);
10149                 *gvp = NULL;
10150                 *st = CvSTASH(cv);
10151                 return cv;
10152             }
10153             else if(SvGETMAGIC(sv), isGV_with_GP(sv))
10154                 gv = MUTABLE_GV(sv);
10155             else
10156                 Perl_croak(aTHX_ "Not a subroutine reference");
10157         }
10158         else if (isGV_with_GP(sv)) {
10159             gv = MUTABLE_GV(sv);
10160         }
10161         else {
10162             gv = gv_fetchsv_nomg(sv, lref, SVt_PVCV);
10163         }
10164         *gvp = gv;
10165         if (!gv) {
10166             *st = NULL;
10167             return NULL;
10168         }
10169         /* Some flags to gv_fetchsv mean don't really create the GV  */
10170         if (!isGV_with_GP(gv)) {
10171             *st = NULL;
10172             return NULL;
10173         }
10174         *st = GvESTASH(gv);
10175         if (lref & ~GV_ADDMG && !GvCVu(gv)) {
10176             /* XXX this is probably not what they think they're getting.
10177              * It has the same effect as "sub name;", i.e. just a forward
10178              * declaration! */
10179             newSTUB(gv,0);
10180         }
10181         return GvCVu(gv);
10182     }
10183 }
10184
10185 /*
10186 =for apidoc sv_true
10187
10188 Returns true if the SV has a true value by Perl's rules.
10189 Use the C<SvTRUE> macro instead, which may call C<sv_true()> or may
10190 instead use an in-line version.
10191
10192 =cut
10193 */
10194
10195 I32
10196 Perl_sv_true(pTHX_ SV *const sv)
10197 {
10198     if (!sv)
10199         return 0;
10200     if (SvPOK(sv)) {
10201         const XPV* const tXpv = (XPV*)SvANY(sv);
10202         if (tXpv &&
10203                 (tXpv->xpv_cur > 1 ||
10204                 (tXpv->xpv_cur && *sv->sv_u.svu_pv != '0')))
10205             return 1;
10206         else
10207             return 0;
10208     }
10209     else {
10210         if (SvIOK(sv))
10211             return SvIVX(sv) != 0;
10212         else {
10213             if (SvNOK(sv))
10214                 return SvNVX(sv) != 0.0;
10215             else
10216                 return sv_2bool(sv);
10217         }
10218     }
10219 }
10220
10221 /*
10222 =for apidoc sv_pvn_force
10223
10224 Get a sensible string out of the SV somehow.
10225 A private implementation of the C<SvPV_force> macro for compilers which
10226 can't cope with complex macro expressions.  Always use the macro instead.
10227
10228 =for apidoc sv_pvn_force_flags
10229
10230 Get a sensible string out of the SV somehow.
10231 If C<flags> has the C<SV_GMAGIC> bit set, will C<L</mg_get>> on C<sv> if
10232 appropriate, else not.  C<sv_pvn_force> and C<sv_pvn_force_nomg> are
10233 implemented in terms of this function.
10234 You normally want to use the various wrapper macros instead: see
10235 C<L</SvPV_force>> and C<L</SvPV_force_nomg>>.
10236
10237 =cut
10238 */
10239
10240 char *
10241 Perl_sv_pvn_force_flags(pTHX_ SV *const sv, STRLEN *const lp, const U32 flags)
10242 {
10243     PERL_ARGS_ASSERT_SV_PVN_FORCE_FLAGS;
10244
10245     if (flags & SV_GMAGIC) SvGETMAGIC(sv);
10246     if (SvTHINKFIRST(sv) && (!SvROK(sv) || SvREADONLY(sv)))
10247         sv_force_normal_flags(sv, 0);
10248
10249     if (SvPOK(sv)) {
10250         if (lp)
10251             *lp = SvCUR(sv);
10252     }
10253     else {
10254         char *s;
10255         STRLEN len;
10256
10257         if (SvTYPE(sv) > SVt_PVLV
10258             || isGV_with_GP(sv))
10259             /* diag_listed_as: Can't coerce %s to %s in %s */
10260             Perl_croak(aTHX_ "Can't coerce %s to string in %s", sv_reftype(sv,0),
10261                 OP_DESC(PL_op));
10262         s = sv_2pv_flags(sv, &len, flags &~ SV_GMAGIC);
10263         if (!s) {
10264           s = (char *)"";
10265         }
10266         if (lp)
10267             *lp = len;
10268
10269         if (SvTYPE(sv) < SVt_PV ||
10270             s != SvPVX_const(sv)) {     /* Almost, but not quite, sv_setpvn() */
10271             if (SvROK(sv))
10272                 sv_unref(sv);
10273             SvUPGRADE(sv, SVt_PV);              /* Never FALSE */
10274             SvGROW(sv, len + 1);
10275             Move(s,SvPVX(sv),len,char);
10276             SvCUR_set(sv, len);
10277             SvPVX(sv)[len] = '\0';
10278         }
10279         if (!SvPOK(sv)) {
10280             SvPOK_on(sv);               /* validate pointer */
10281             SvTAINT(sv);
10282             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%" UVxf " 2pv(%s)\n",
10283                                   PTR2UV(sv),SvPVX_const(sv)));
10284         }
10285     }
10286     (void)SvPOK_only_UTF8(sv);
10287     return SvPVX_mutable(sv);
10288 }
10289
10290 /*
10291 =for apidoc sv_pvbyten_force
10292
10293 The backend for the C<SvPVbytex_force> macro.  Always use the macro
10294 instead.  If the SV cannot be downgraded from UTF-8, this croaks.
10295
10296 =cut
10297 */
10298
10299 char *
10300 Perl_sv_pvbyten_force(pTHX_ SV *const sv, STRLEN *const lp)
10301 {
10302     PERL_ARGS_ASSERT_SV_PVBYTEN_FORCE;
10303
10304     sv_pvn_force(sv,lp);
10305     (void)sv_utf8_downgrade(sv,0);
10306     *lp = SvCUR(sv);
10307     return SvPVX(sv);
10308 }
10309
10310 /*
10311 =for apidoc sv_pvutf8n_force
10312
10313 The backend for the C<SvPVutf8x_force> macro.  Always use the macro
10314 instead.
10315
10316 =cut
10317 */
10318
10319 char *
10320 Perl_sv_pvutf8n_force(pTHX_ SV *const sv, STRLEN *const lp)
10321 {
10322     PERL_ARGS_ASSERT_SV_PVUTF8N_FORCE;
10323
10324     sv_pvn_force(sv,0);
10325     sv_utf8_upgrade_nomg(sv);
10326     *lp = SvCUR(sv);
10327     return SvPVX(sv);
10328 }
10329
10330 /*
10331 =for apidoc sv_reftype
10332
10333 Returns a string describing what the SV is a reference to.
10334
10335 If ob is true and the SV is blessed, the string is the class name,
10336 otherwise it is the type of the SV, "SCALAR", "ARRAY" etc.
10337
10338 =cut
10339 */
10340
10341 const char *
10342 Perl_sv_reftype(pTHX_ const SV *const sv, const int ob)
10343 {
10344     PERL_ARGS_ASSERT_SV_REFTYPE;
10345     if (ob && SvOBJECT(sv)) {
10346         return SvPV_nolen_const(sv_ref(NULL, sv, ob));
10347     }
10348     else {
10349         /* WARNING - There is code, for instance in mg.c, that assumes that
10350          * the only reason that sv_reftype(sv,0) would return a string starting
10351          * with 'L' or 'S' is that it is a LVALUE or a SCALAR.
10352          * Yes this a dodgy way to do type checking, but it saves practically reimplementing
10353          * this routine inside other subs, and it saves time.
10354          * Do not change this assumption without searching for "dodgy type check" in
10355          * the code.
10356          * - Yves */
10357         switch (SvTYPE(sv)) {
10358         case SVt_NULL:
10359         case SVt_IV:
10360         case SVt_NV:
10361         case SVt_PV:
10362         case SVt_PVIV:
10363         case SVt_PVNV:
10364         case SVt_PVMG:
10365                                 if (SvVOK(sv))
10366                                     return "VSTRING";
10367                                 if (SvROK(sv))
10368                                     return "REF";
10369                                 else
10370                                     return "SCALAR";
10371
10372         case SVt_PVLV:          return (char *)  (SvROK(sv) ? "REF"
10373                                 /* tied lvalues should appear to be
10374                                  * scalars for backwards compatibility */
10375                                 : (isALPHA_FOLD_EQ(LvTYPE(sv), 't'))
10376                                     ? "SCALAR" : "LVALUE");
10377         case SVt_PVAV:          return "ARRAY";
10378         case SVt_PVHV:          return "HASH";
10379         case SVt_PVCV:          return "CODE";
10380         case SVt_PVGV:          return (char *) (isGV_with_GP(sv)
10381                                     ? "GLOB" : "SCALAR");
10382         case SVt_PVFM:          return "FORMAT";
10383         case SVt_PVIO:          return "IO";
10384         case SVt_INVLIST:       return "INVLIST";
10385         case SVt_REGEXP:        return "REGEXP";
10386         default:                return "UNKNOWN";
10387         }
10388     }
10389 }
10390
10391 /*
10392 =for apidoc sv_ref
10393
10394 Returns a SV describing what the SV passed in is a reference to.
10395
10396 dst can be a SV to be set to the description or NULL, in which case a
10397 mortal SV is returned.
10398
10399 If ob is true and the SV is blessed, the description is the class
10400 name, otherwise it is the type of the SV, "SCALAR", "ARRAY" etc.
10401
10402 =cut
10403 */
10404
10405 SV *
10406 Perl_sv_ref(pTHX_ SV *dst, const SV *const sv, const int ob)
10407 {
10408     PERL_ARGS_ASSERT_SV_REF;
10409
10410     if (!dst)
10411         dst = sv_newmortal();
10412
10413     if (ob && SvOBJECT(sv)) {
10414         HvNAME_get(SvSTASH(sv))
10415                     ? sv_sethek(dst, HvNAME_HEK(SvSTASH(sv)))
10416                     : sv_setpvs(dst, "__ANON__");
10417     }
10418     else {
10419         const char * reftype = sv_reftype(sv, 0);
10420         sv_setpv(dst, reftype);
10421     }
10422     return dst;
10423 }
10424
10425 /*
10426 =for apidoc sv_isobject
10427
10428 Returns a boolean indicating whether the SV is an RV pointing to a blessed
10429 object.  If the SV is not an RV, or if the object is not blessed, then this
10430 will return false.
10431
10432 =cut
10433 */
10434
10435 int
10436 Perl_sv_isobject(pTHX_ SV *sv)
10437 {
10438     if (!sv)
10439         return 0;
10440     SvGETMAGIC(sv);
10441     if (!SvROK(sv))
10442         return 0;
10443     sv = SvRV(sv);
10444     if (!SvOBJECT(sv))
10445         return 0;
10446     return 1;
10447 }
10448
10449 /*
10450 =for apidoc sv_isa
10451
10452 Returns a boolean indicating whether the SV is blessed into the specified
10453 class.
10454
10455 This does not check for subtypes or method overloading. Use C<sv_isa_sv> to
10456 verify an inheritance relationship in the same way as the C<isa> operator by
10457 respecting any C<isa()> method overloading; or C<sv_derived_from_sv> to test
10458 directly on the actual object type.
10459
10460 =cut
10461 */
10462
10463 int
10464 Perl_sv_isa(pTHX_ SV *sv, const char *const name)
10465 {
10466     const char *hvname;
10467
10468     PERL_ARGS_ASSERT_SV_ISA;
10469
10470     if (!sv)
10471         return 0;
10472     SvGETMAGIC(sv);
10473     if (!SvROK(sv))
10474         return 0;
10475     sv = SvRV(sv);
10476     if (!SvOBJECT(sv))
10477         return 0;
10478     hvname = HvNAME_get(SvSTASH(sv));
10479     if (!hvname)
10480         return 0;
10481
10482     return strEQ(hvname, name);
10483 }
10484
10485 /*
10486 =for apidoc newSVrv
10487
10488 Creates a new SV for the existing RV, C<rv>, to point to.  If C<rv> is not an
10489 RV then it will be upgraded to one.  If C<classname> is non-null then the new
10490 SV will be blessed in the specified package.  The new SV is returned and its
10491 reference count is 1.  The reference count 1 is owned by C<rv>. See also
10492 newRV_inc() and newRV_noinc() for creating a new RV properly.
10493
10494 =cut
10495 */
10496
10497 SV*
10498 Perl_newSVrv(pTHX_ SV *const rv, const char *const classname)
10499 {
10500     SV *sv;
10501
10502     PERL_ARGS_ASSERT_NEWSVRV;
10503
10504     new_SV(sv);
10505
10506     SV_CHECK_THINKFIRST_COW_DROP(rv);
10507
10508     if (UNLIKELY( SvTYPE(rv) >= SVt_PVMG )) {
10509         const U32 refcnt = SvREFCNT(rv);
10510         SvREFCNT(rv) = 0;
10511         sv_clear(rv);
10512         SvFLAGS(rv) = 0;
10513         SvREFCNT(rv) = refcnt;
10514
10515         sv_upgrade(rv, SVt_IV);
10516     } else if (SvROK(rv)) {
10517         SvREFCNT_dec(SvRV(rv));
10518     } else {
10519         prepare_SV_for_RV(rv);
10520     }
10521
10522     SvOK_off(rv);
10523     SvRV_set(rv, sv);
10524     SvROK_on(rv);
10525
10526     if (classname) {
10527         HV* const stash = gv_stashpv(classname, GV_ADD);
10528         (void)sv_bless(rv, stash);
10529     }
10530     return sv;
10531 }
10532
10533 SV *
10534 Perl_newSVavdefelem(pTHX_ AV *av, SSize_t ix, bool extendible)
10535 {
10536     SV * const lv = newSV_type(SVt_PVLV);
10537     PERL_ARGS_ASSERT_NEWSVAVDEFELEM;
10538     LvTYPE(lv) = 'y';
10539     sv_magic(lv, NULL, PERL_MAGIC_defelem, NULL, 0);
10540     LvTARG(lv) = SvREFCNT_inc_simple_NN(av);
10541     LvSTARGOFF(lv) = ix;
10542     LvTARGLEN(lv) = extendible ? 1 : (STRLEN)UV_MAX;
10543     return lv;
10544 }
10545
10546 /*
10547 =for apidoc sv_setref_pv
10548
10549 Copies a pointer into a new SV, optionally blessing the SV.  The C<rv>
10550 argument will be upgraded to an RV.  That RV will be modified to point to
10551 the new SV.  If the C<pv> argument is C<NULL>, then C<PL_sv_undef> will be placed
10552 into the SV.  The C<classname> argument indicates the package for the
10553 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
10554 will have a reference count of 1, and the RV will be returned.
10555
10556 Do not use with other Perl types such as HV, AV, SV, CV, because those
10557 objects will become corrupted by the pointer copy process.
10558
10559 Note that C<sv_setref_pvn> copies the string while this copies the pointer.
10560
10561 =cut
10562 */
10563
10564 SV*
10565 Perl_sv_setref_pv(pTHX_ SV *const rv, const char *const classname, void *const pv)
10566 {
10567     PERL_ARGS_ASSERT_SV_SETREF_PV;
10568
10569     if (!pv) {
10570         sv_set_undef(rv);
10571         SvSETMAGIC(rv);
10572     }
10573     else
10574         sv_setiv(newSVrv(rv,classname), PTR2IV(pv));
10575     return rv;
10576 }
10577
10578 /*
10579 =for apidoc sv_setref_iv
10580
10581 Copies an integer into a new SV, optionally blessing the SV.  The C<rv>
10582 argument will be upgraded to an RV.  That RV will be modified to point to
10583 the new SV.  The C<classname> argument indicates the package for the
10584 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
10585 will have a reference count of 1, and the RV will be returned.
10586
10587 =cut
10588 */
10589
10590 SV*
10591 Perl_sv_setref_iv(pTHX_ SV *const rv, const char *const classname, const IV iv)
10592 {
10593     PERL_ARGS_ASSERT_SV_SETREF_IV;
10594
10595     sv_setiv(newSVrv(rv,classname), iv);
10596     return rv;
10597 }
10598
10599 /*
10600 =for apidoc sv_setref_uv
10601
10602 Copies an unsigned integer into a new SV, optionally blessing the SV.  The C<rv>
10603 argument will be upgraded to an RV.  That RV will be modified to point to
10604 the new SV.  The C<classname> argument indicates the package for the
10605 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
10606 will have a reference count of 1, and the RV will be returned.
10607
10608 =cut
10609 */
10610
10611 SV*
10612 Perl_sv_setref_uv(pTHX_ SV *const rv, const char *const classname, const UV uv)
10613 {
10614     PERL_ARGS_ASSERT_SV_SETREF_UV;
10615
10616     sv_setuv(newSVrv(rv,classname), uv);
10617     return rv;
10618 }
10619
10620 /*
10621 =for apidoc sv_setref_nv
10622
10623 Copies a double into a new SV, optionally blessing the SV.  The C<rv>
10624 argument will be upgraded to an RV.  That RV will be modified to point to
10625 the new SV.  The C<classname> argument indicates the package for the
10626 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
10627 will have a reference count of 1, and the RV will be returned.
10628
10629 =cut
10630 */
10631
10632 SV*
10633 Perl_sv_setref_nv(pTHX_ SV *const rv, const char *const classname, const NV nv)
10634 {
10635     PERL_ARGS_ASSERT_SV_SETREF_NV;
10636
10637     sv_setnv(newSVrv(rv,classname), nv);
10638     return rv;
10639 }
10640
10641 /*
10642 =for apidoc sv_setref_pvn
10643
10644 Copies a string into a new SV, optionally blessing the SV.  The length of the
10645 string must be specified with C<n>.  The C<rv> argument will be upgraded to
10646 an RV.  That RV will be modified to point to the new SV.  The C<classname>
10647 argument indicates the package for the blessing.  Set C<classname> to
10648 C<NULL> to avoid the blessing.  The new SV will have a reference count
10649 of 1, and the RV will be returned.
10650
10651 Note that C<sv_setref_pv> copies the pointer while this copies the string.
10652
10653 =cut
10654 */
10655
10656 SV*
10657 Perl_sv_setref_pvn(pTHX_ SV *const rv, const char *const classname,
10658                    const char *const pv, const STRLEN n)
10659 {
10660     PERL_ARGS_ASSERT_SV_SETREF_PVN;
10661
10662     sv_setpvn(newSVrv(rv,classname), pv, n);
10663     return rv;
10664 }
10665
10666 /*
10667 =for apidoc sv_bless
10668
10669 Blesses an SV into a specified package.  The SV must be an RV.  The package
10670 must be designated by its stash (see C<L</gv_stashpv>>).  The reference count
10671 of the SV is unaffected.
10672
10673 =cut
10674 */
10675
10676 SV*
10677 Perl_sv_bless(pTHX_ SV *const sv, HV *const stash)
10678 {
10679     SV *tmpRef;
10680     HV *oldstash = NULL;
10681
10682     PERL_ARGS_ASSERT_SV_BLESS;
10683
10684     SvGETMAGIC(sv);
10685     if (!SvROK(sv))
10686         Perl_croak(aTHX_ "Can't bless non-reference value");
10687     tmpRef = SvRV(sv);
10688     if (SvFLAGS(tmpRef) & (SVs_OBJECT|SVf_READONLY|SVf_PROTECT)) {
10689         if (SvREADONLY(tmpRef))
10690             Perl_croak_no_modify();
10691         if (SvOBJECT(tmpRef)) {
10692             oldstash = SvSTASH(tmpRef);
10693         }
10694     }
10695     SvOBJECT_on(tmpRef);
10696     SvUPGRADE(tmpRef, SVt_PVMG);
10697     SvSTASH_set(tmpRef, MUTABLE_HV(SvREFCNT_inc_simple(stash)));
10698     SvREFCNT_dec(oldstash);
10699
10700     if(SvSMAGICAL(tmpRef))
10701         if(mg_find(tmpRef, PERL_MAGIC_ext) || mg_find(tmpRef, PERL_MAGIC_uvar))
10702             mg_set(tmpRef);
10703
10704
10705
10706     return sv;
10707 }
10708
10709 /* Downgrades a PVGV to a PVMG. If it's actually a PVLV, we leave the type
10710  * as it is after unglobbing it.
10711  */
10712
10713 PERL_STATIC_INLINE void
10714 S_sv_unglob(pTHX_ SV *const sv, U32 flags)
10715 {
10716     void *xpvmg;
10717     HV *stash;
10718     SV * const temp = flags & SV_COW_DROP_PV ? NULL : sv_newmortal();
10719
10720     PERL_ARGS_ASSERT_SV_UNGLOB;
10721
10722     assert(SvTYPE(sv) == SVt_PVGV || SvTYPE(sv) == SVt_PVLV);
10723     SvFAKE_off(sv);
10724     if (!(flags & SV_COW_DROP_PV))
10725         gv_efullname3(temp, MUTABLE_GV(sv), "*");
10726
10727     SvREFCNT_inc_simple_void_NN(sv_2mortal(sv));
10728     if (GvGP(sv)) {
10729         if(GvCVu((const GV *)sv) && (stash = GvSTASH(MUTABLE_GV(sv)))
10730            && HvNAME_get(stash))
10731             mro_method_changed_in(stash);
10732         gp_free(MUTABLE_GV(sv));
10733     }
10734     if (GvSTASH(sv)) {
10735         sv_del_backref(MUTABLE_SV(GvSTASH(sv)), sv);
10736         GvSTASH(sv) = NULL;
10737     }
10738     GvMULTI_off(sv);
10739     if (GvNAME_HEK(sv)) {
10740         unshare_hek(GvNAME_HEK(sv));
10741     }
10742     isGV_with_GP_off(sv);
10743
10744     if(SvTYPE(sv) == SVt_PVGV) {
10745         /* need to keep SvANY(sv) in the right arena */
10746         xpvmg = new_XPVMG();
10747         StructCopy(SvANY(sv), xpvmg, XPVMG);
10748         del_body_by_type(SvANY(sv), SVt_PVGV);
10749         SvANY(sv) = xpvmg;
10750
10751         SvFLAGS(sv) &= ~SVTYPEMASK;
10752         SvFLAGS(sv) |= SVt_PVMG;
10753     }
10754
10755     /* Intentionally not calling any local SET magic, as this isn't so much a
10756        set operation as merely an internal storage change.  */
10757     if (flags & SV_COW_DROP_PV) SvOK_off(sv);
10758     else sv_setsv_flags(sv, temp, 0);
10759
10760     if ((const GV *)sv == PL_last_in_gv)
10761         PL_last_in_gv = NULL;
10762     else if ((const GV *)sv == PL_statgv)
10763         PL_statgv = NULL;
10764 }
10765
10766 /*
10767 =for apidoc sv_unref_flags
10768
10769 Unsets the RV status of the SV, and decrements the reference count of
10770 whatever was being referenced by the RV.  This can almost be thought of
10771 as a reversal of C<newSVrv>.  The C<cflags> argument can contain
10772 C<SV_IMMEDIATE_UNREF> to force the reference count to be decremented
10773 (otherwise the decrementing is conditional on the reference count being
10774 different from one or the reference being a readonly SV).
10775 See C<L</SvROK_off>>.
10776
10777 =for apidoc Amnh||SV_IMMEDIATE_UNREF
10778
10779 =cut
10780 */
10781
10782 void
10783 Perl_sv_unref_flags(pTHX_ SV *const ref, const U32 flags)
10784 {
10785     SV* const target = SvRV(ref);
10786
10787     PERL_ARGS_ASSERT_SV_UNREF_FLAGS;
10788
10789     if (SvWEAKREF(ref)) {
10790         sv_del_backref(target, ref);
10791         SvWEAKREF_off(ref);
10792         SvRV_set(ref, NULL);
10793         return;
10794     }
10795     SvRV_set(ref, NULL);
10796     SvROK_off(ref);
10797     /* You can't have a || SvREADONLY(target) here, as $a = $$a, where $a was
10798        assigned to as BEGIN {$a = \"Foo"} will fail.  */
10799     if (SvREFCNT(target) != 1 || (flags & SV_IMMEDIATE_UNREF))
10800         SvREFCNT_dec_NN(target);
10801     else /* XXX Hack, but hard to make $a=$a->[1] work otherwise */
10802         sv_2mortal(target);     /* Schedule for freeing later */
10803 }
10804
10805 /*
10806 =for apidoc sv_untaint
10807
10808 Untaint an SV.  Use C<SvTAINTED_off> instead.
10809
10810 =cut
10811 */
10812
10813 void
10814 Perl_sv_untaint(pTHX_ SV *const sv)
10815 {
10816     PERL_ARGS_ASSERT_SV_UNTAINT;
10817     PERL_UNUSED_CONTEXT;
10818
10819     if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
10820         MAGIC * const mg = mg_find(sv, PERL_MAGIC_taint);
10821         if (mg)
10822             mg->mg_len &= ~1;
10823     }
10824 }
10825
10826 /*
10827 =for apidoc sv_tainted
10828
10829 Test an SV for taintedness.  Use C<SvTAINTED> instead.
10830
10831 =cut
10832 */
10833
10834 bool
10835 Perl_sv_tainted(pTHX_ SV *const sv)
10836 {
10837     PERL_ARGS_ASSERT_SV_TAINTED;
10838     PERL_UNUSED_CONTEXT;
10839
10840     if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
10841         const MAGIC * const mg = mg_find(sv, PERL_MAGIC_taint);
10842         if (mg && (mg->mg_len & 1) )
10843             return TRUE;
10844     }
10845     return FALSE;
10846 }
10847
10848 #if defined(MULTIPLICITY)
10849
10850 /* pTHX_ magic can't cope with varargs, so this is a no-context
10851  * version of the main function, (which may itself be aliased to us).
10852  * Don't access this version directly.
10853  */
10854
10855 void
10856 Perl_sv_setpvf_nocontext(SV *const sv, const char *const pat, ...)
10857 {
10858     dTHX;
10859     va_list args;
10860
10861     PERL_ARGS_ASSERT_SV_SETPVF_NOCONTEXT;
10862
10863     va_start(args, pat);
10864     sv_vsetpvf(sv, pat, &args);
10865     va_end(args);
10866 }
10867
10868 /* pTHX_ magic can't cope with varargs, so this is a no-context
10869  * version of the main function, (which may itself be aliased to us).
10870  * Don't access this version directly.
10871  */
10872
10873 void
10874 Perl_sv_setpvf_mg_nocontext(SV *const sv, const char *const pat, ...)
10875 {
10876     dTHX;
10877     va_list args;
10878
10879     PERL_ARGS_ASSERT_SV_SETPVF_MG_NOCONTEXT;
10880
10881     va_start(args, pat);
10882     sv_vsetpvf_mg(sv, pat, &args);
10883     va_end(args);
10884 }
10885 #endif
10886
10887 /*
10888 =for apidoc      sv_setpvf
10889 =for apidoc_item sv_setpvf_mg
10890 =for apidoc_item sv_setpvf_mg_nocontext
10891 =for apidoc_item sv_setpvf_nocontext
10892
10893 These work like C<L</sv_catpvf>> but copy the text into the SV instead of
10894 appending it.
10895
10896 The differences between these are:
10897
10898 C<sv_setpvf_mg> and C<sv_setpvf_mg_nocontext> perform 'set' magic; C<sv_setpvf>
10899 and C<sv_setpvf_nocontext> skip all magic.
10900
10901 C<sv_setpvf_nocontext> and C<sv_setpvf_mg_nocontext> do not take a thread
10902 context (C<aTHX>) parameter, so are used in situations where the caller
10903 doesn't already have the thread context.
10904
10905 =cut
10906 */
10907
10908 void
10909 Perl_sv_setpvf(pTHX_ SV *const sv, const char *const pat, ...)
10910 {
10911     va_list args;
10912
10913     PERL_ARGS_ASSERT_SV_SETPVF;
10914
10915     va_start(args, pat);
10916     sv_vsetpvf(sv, pat, &args);
10917     va_end(args);
10918 }
10919
10920 /*
10921 =for apidoc sv_vsetpvf
10922 =for apidoc_item sv_vsetpvf_mg
10923
10924 These work like C<L</sv_vcatpvf>> but copy the text into the SV instead of
10925 appending it.
10926
10927 They differ only in that C<sv_vsetpvf_mg> performs 'set' magic;
10928 C<sv_vsetpvf> skips all magic.
10929
10930 They are usually used via their frontends, C<L</sv_setpvf>> and
10931 C<L</sv_setpvf_mg>>.
10932
10933 =cut
10934 */
10935
10936 void
10937 Perl_sv_vsetpvf(pTHX_ SV *const sv, const char *const pat, va_list *const args)
10938 {
10939     PERL_ARGS_ASSERT_SV_VSETPVF;
10940
10941     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
10942 }
10943
10944 void
10945 Perl_sv_setpvf_mg(pTHX_ SV *const sv, const char *const pat, ...)
10946 {
10947     va_list args;
10948
10949     PERL_ARGS_ASSERT_SV_SETPVF_MG;
10950
10951     va_start(args, pat);
10952     sv_vsetpvf_mg(sv, pat, &args);
10953     va_end(args);
10954 }
10955
10956 void
10957 Perl_sv_vsetpvf_mg(pTHX_ SV *const sv, const char *const pat, va_list *const args)
10958 {
10959     PERL_ARGS_ASSERT_SV_VSETPVF_MG;
10960
10961     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
10962     SvSETMAGIC(sv);
10963 }
10964
10965 #if defined(MULTIPLICITY)
10966
10967 /* pTHX_ magic can't cope with varargs, so this is a no-context
10968  * version of the main function, (which may itself be aliased to us).
10969  * Don't access this version directly.
10970  */
10971
10972 void
10973 Perl_sv_catpvf_nocontext(SV *const sv, const char *const pat, ...)
10974 {
10975     dTHX;
10976     va_list args;
10977
10978     PERL_ARGS_ASSERT_SV_CATPVF_NOCONTEXT;
10979
10980     va_start(args, pat);
10981     sv_vcatpvfn_flags(sv, pat, strlen(pat), &args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
10982     va_end(args);
10983 }
10984
10985 /* pTHX_ magic can't cope with varargs, so this is a no-context
10986  * version of the main function, (which may itself be aliased to us).
10987  * Don't access this version directly.
10988  */
10989
10990 void
10991 Perl_sv_catpvf_mg_nocontext(SV *const sv, const char *const pat, ...)
10992 {
10993     dTHX;
10994     va_list args;
10995
10996     PERL_ARGS_ASSERT_SV_CATPVF_MG_NOCONTEXT;
10997
10998     va_start(args, pat);
10999     sv_vcatpvfn_flags(sv, pat, strlen(pat), &args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
11000     SvSETMAGIC(sv);
11001     va_end(args);
11002 }
11003 #endif
11004
11005 /*
11006 =for apidoc sv_catpvf
11007 =for apidoc_item sv_catpvf_mg
11008 =for apidoc_item sv_catpvf_mg_nocontext
11009 =for apidoc_item sv_catpvf_nocontext
11010
11011 These process their arguments like C<sprintf>, and append the formatted
11012 output to an SV.  As with C<sv_vcatpvfn>, argument reordering is not supporte
11013 when called with a non-null C-style variable argument list.
11014
11015 If the appended data contains "wide" characters
11016 (including, but not limited to, SVs with a UTF-8 PV formatted with C<%s>,
11017 and characters >255 formatted with C<%c>), the original SV might get
11018 upgraded to UTF-8.
11019
11020 If the original SV was UTF-8, the pattern should be
11021 valid UTF-8; if the original SV was bytes, the pattern should be too.
11022
11023 All perform 'get' magic, but only C<sv_catpvf_mg> and C<sv_catpvf_mg_nocontext>
11024 perform 'set' magic.
11025
11026 C<sv_catpvf_nocontext> and C<sv_catpvf_mg_nocontext> do not take a thread
11027 context (C<aTHX>) parameter, so are used in situations where the caller
11028 doesn't already have the thread context.
11029
11030 =cut
11031 */
11032
11033 void
11034 Perl_sv_catpvf(pTHX_ SV *const sv, const char *const pat, ...)
11035 {
11036     va_list args;
11037
11038     PERL_ARGS_ASSERT_SV_CATPVF;
11039
11040     va_start(args, pat);
11041     sv_vcatpvfn_flags(sv, pat, strlen(pat), &args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
11042     va_end(args);
11043 }
11044
11045 /*
11046 =for apidoc sv_vcatpvf
11047 =for apidoc_item sv_vcatpvf_mg
11048
11049 These process their arguments like C<sv_vcatpvfn> called with a non-null
11050 C-style variable argument list, and append the formatted output to C<sv>.
11051
11052 They differ only in that C<sv_vcatpvf_mg> performs 'set' magic;
11053 C<sv_vcatpvf> skips 'set' magic.
11054
11055 Both perform 'get' magic.
11056
11057 They are usually accessed via their frontends C<L</sv_catpvf>> and
11058 C<L</sv_catpvf_mg>>.
11059
11060 =cut
11061 */
11062
11063 void
11064 Perl_sv_vcatpvf(pTHX_ SV *const sv, const char *const pat, va_list *const args)
11065 {
11066     PERL_ARGS_ASSERT_SV_VCATPVF;
11067
11068     sv_vcatpvfn_flags(sv, pat, strlen(pat), args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
11069 }
11070
11071 void
11072 Perl_sv_catpvf_mg(pTHX_ SV *const sv, const char *const pat, ...)
11073 {
11074     va_list args;
11075
11076     PERL_ARGS_ASSERT_SV_CATPVF_MG;
11077
11078     va_start(args, pat);
11079     sv_vcatpvfn_flags(sv, pat, strlen(pat), &args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
11080     SvSETMAGIC(sv);
11081     va_end(args);
11082 }
11083
11084 void
11085 Perl_sv_vcatpvf_mg(pTHX_ SV *const sv, const char *const pat, va_list *const args)
11086 {
11087     PERL_ARGS_ASSERT_SV_VCATPVF_MG;
11088
11089     sv_vcatpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
11090     SvSETMAGIC(sv);
11091 }
11092
11093 /*
11094 =for apidoc sv_vsetpvfn
11095
11096 Works like C<sv_vcatpvfn> but copies the text into the SV instead of
11097 appending it.
11098
11099 Usually used via one of its frontends L</C<sv_vsetpvf>> and
11100 L</C<sv_vsetpvf_mg>>.
11101
11102 =cut
11103 */
11104
11105 void
11106 Perl_sv_vsetpvfn(pTHX_ SV *const sv, const char *const pat, const STRLEN patlen,
11107                  va_list *const args, SV **const svargs, const Size_t sv_count, bool *const maybe_tainted)
11108 {
11109     PERL_ARGS_ASSERT_SV_VSETPVFN;
11110
11111     SvPVCLEAR(sv);
11112     sv_vcatpvfn_flags(sv, pat, patlen, args, svargs, sv_count, maybe_tainted, 0);
11113 }
11114
11115
11116 /* simplified inline Perl_sv_catpvn_nomg() when you know the SV's SvPOK */
11117
11118 PERL_STATIC_INLINE void
11119 S_sv_catpvn_simple(pTHX_ SV *const sv, const char* const buf, const STRLEN len)
11120 {
11121     STRLEN const need = len + SvCUR(sv) + 1;
11122     char *end;
11123
11124     /* can't wrap as both len and SvCUR() are allocated in
11125      * memory and together can't consume all the address space
11126      */
11127     assert(need > len);
11128
11129     assert(SvPOK(sv));
11130     SvGROW(sv, need);
11131     end = SvEND(sv);
11132     Copy(buf, end, len, char);
11133     end += len;
11134     *end = '\0';
11135     SvCUR_set(sv, need - 1);
11136 }
11137
11138
11139 /*
11140  * Warn of missing argument to sprintf. The value used in place of such
11141  * arguments should be &PL_sv_no; an undefined value would yield
11142  * inappropriate "use of uninit" warnings [perl #71000].
11143  */
11144 STATIC void
11145 S_warn_vcatpvfn_missing_argument(pTHX) {
11146     if (ckWARN(WARN_MISSING)) {
11147         Perl_warner(aTHX_ packWARN(WARN_MISSING), "Missing argument in %s",
11148                 PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn()");
11149     }
11150 }
11151
11152
11153 static void
11154 S_croak_overflow()
11155 {
11156     dTHX;
11157     Perl_croak(aTHX_ "Integer overflow in format string for %s",
11158                     (PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn"));
11159 }
11160
11161
11162 /* Given an int i from the next arg (if args is true) or an sv from an arg
11163  * (if args is false), try to extract a STRLEN-ranged value from the arg,
11164  * with overflow checking.
11165  * Sets *neg to true if the value was negative (untouched otherwise.
11166  * Returns the absolute value.
11167  * As an extra margin of safety, it croaks if the returned value would
11168  * exceed the maximum value of a STRLEN / 4.
11169  */
11170
11171 static STRLEN
11172 S_sprintf_arg_num_val(pTHX_ va_list *const args, int i, SV *sv, bool *neg)
11173 {
11174     IV iv;
11175
11176     if (args) {
11177         iv = i;
11178         goto do_iv;
11179     }
11180
11181     if (!sv)
11182         return 0;
11183
11184     SvGETMAGIC(sv);
11185
11186     if (UNLIKELY(SvIsUV(sv))) {
11187         UV uv = SvUV_nomg(sv);
11188         if (uv > IV_MAX)
11189             S_croak_overflow();
11190         iv = uv;
11191     }
11192     else {
11193         iv = SvIV_nomg(sv);
11194       do_iv:
11195         if (iv < 0) {
11196             if (iv < -IV_MAX)
11197                 S_croak_overflow();
11198             iv = -iv;
11199             *neg = TRUE;
11200         }
11201     }
11202
11203     if (iv > (IV)(((STRLEN)~0) / 4))
11204         S_croak_overflow();
11205
11206     return (STRLEN)iv;
11207 }
11208
11209 /* Read in and return a number. Updates *pattern to point to the char
11210  * following the number. Expects the first char to 1..9.
11211  * Croaks if the number exceeds 1/4 of the maximum value of STRLEN.
11212  * This is a belt-and-braces safety measure to complement any
11213  * overflow/wrap checks done in the main body of sv_vcatpvfn_flags.
11214  * It means that e.g. on a 32-bit system the width/precision can't be more
11215  * than 1G, which seems reasonable.
11216  */
11217
11218 STATIC STRLEN
11219 S_expect_number(pTHX_ const char **const pattern)
11220 {
11221     STRLEN var;
11222
11223     PERL_ARGS_ASSERT_EXPECT_NUMBER;
11224
11225     assert(inRANGE(**pattern, '1', '9'));
11226
11227     var = *(*pattern)++ - '0';
11228     while (isDIGIT(**pattern)) {
11229         /* if var * 10 + 9 would exceed 1/4 max strlen, croak */
11230         if (var > ((((STRLEN)~0) / 4 - 9) / 10))
11231             S_croak_overflow();
11232         var = var * 10 + (*(*pattern)++ - '0');
11233     }
11234     return var;
11235 }
11236
11237 /* Implement a fast "%.0f": given a pointer to the end of a buffer (caller
11238  * ensures it's big enough), back fill it with the rounded integer part of
11239  * nv. Returns ptr to start of string, and sets *len to its length.
11240  * Returns NULL if not convertible.
11241  */
11242
11243 STATIC char *
11244 S_F0convert(NV nv, char *const endbuf, STRLEN *const len)
11245 {
11246     const int neg = nv < 0;
11247     UV uv;
11248
11249     PERL_ARGS_ASSERT_F0CONVERT;
11250
11251     assert(!Perl_isinfnan(nv));
11252     if (neg)
11253         nv = -nv;
11254     if (nv != 0.0 && nv < (NV) UV_MAX) {
11255         char *p = endbuf;
11256         uv = (UV)nv;
11257         if (uv != nv) {
11258             nv += 0.5;
11259             uv = (UV)nv;
11260             if (uv & 1 && uv == nv)
11261                 uv--;                   /* Round to even */
11262         }
11263         do {
11264             const unsigned dig = uv % 10;
11265             *--p = '0' + dig;
11266         } while (uv /= 10);
11267         if (neg)
11268             *--p = '-';
11269         *len = endbuf - p;
11270         return p;
11271     }
11272     return NULL;
11273 }
11274
11275
11276 /* XXX maybe_tainted is never assigned to, so the doc above is lying. */
11277
11278 void
11279 Perl_sv_vcatpvfn(pTHX_ SV *const sv, const char *const pat, const STRLEN patlen,
11280                  va_list *const args, SV **const svargs, const Size_t sv_count, bool *const maybe_tainted)
11281 {
11282     PERL_ARGS_ASSERT_SV_VCATPVFN;
11283
11284     sv_vcatpvfn_flags(sv, pat, patlen, args, svargs, sv_count, maybe_tainted, SV_GMAGIC|SV_SMAGIC);
11285 }
11286
11287
11288 /* For the vcatpvfn code, we need a long double target in case
11289  * HAS_LONG_DOUBLE, even without USE_LONG_DOUBLE, so that we can printf
11290  * with long double formats, even without NV being long double.  But we
11291  * call the target 'fv' instead of 'nv', since most of the time it is not
11292  * (most compilers these days recognize "long double", even if only as a
11293  * synonym for "double").
11294 */
11295 #if defined(HAS_LONG_DOUBLE) && LONG_DOUBLESIZE > DOUBLESIZE && \
11296         defined(PERL_PRIgldbl) && !defined(USE_QUADMATH)
11297 #  define VCATPVFN_FV_GF PERL_PRIgldbl
11298 #  if defined(__VMS) && defined(__ia64) && defined(__IEEE_FLOAT)
11299        /* Work around breakage in OTS$CVT_FLOAT_T_X */
11300 #    define VCATPVFN_NV_TO_FV(nv,fv)                    \
11301             STMT_START {                                \
11302                 double _dv = nv;                        \
11303                 fv = Perl_isnan(_dv) ? LDBL_QNAN : _dv; \
11304             } STMT_END
11305 #  else
11306 #    define VCATPVFN_NV_TO_FV(nv,fv) (fv)=(nv)
11307 #  endif
11308    typedef long double vcatpvfn_long_double_t;
11309 #else
11310 #  define VCATPVFN_FV_GF NVgf
11311 #  define VCATPVFN_NV_TO_FV(nv,fv) (fv)=(nv)
11312    typedef NV vcatpvfn_long_double_t;
11313 #endif
11314
11315 #ifdef LONGDOUBLE_DOUBLEDOUBLE
11316 /* The first double can be as large as 2**1023, or '1' x '0' x 1023.
11317  * The second double can be as small as 2**-1074, or '0' x 1073 . '1'.
11318  * The sum of them can be '1' . '0' x 2096 . '1', with implied radix point
11319  * after the first 1023 zero bits.
11320  *
11321  * XXX The 2098 is quite large (262.25 bytes) and therefore some sort
11322  * of dynamically growing buffer might be better, start at just 16 bytes
11323  * (for example) and grow only when necessary.  Or maybe just by looking
11324  * at the exponents of the two doubles? */
11325 #  define DOUBLEDOUBLE_MAXBITS 2098
11326 #endif
11327
11328 /* vhex will contain the values (0..15) of the hex digits ("nybbles"
11329  * of 4 bits); 1 for the implicit 1, and the mantissa bits, four bits
11330  * per xdigit.  For the double-double case, this can be rather many.
11331  * The non-double-double-long-double overshoots since all bits of NV
11332  * are not mantissa bits, there are also exponent bits. */
11333 #ifdef LONGDOUBLE_DOUBLEDOUBLE
11334 #  define VHEX_SIZE (3+DOUBLEDOUBLE_MAXBITS/4)
11335 #else
11336 #  define VHEX_SIZE (1+(NVSIZE * 8)/4)
11337 #endif
11338
11339 /* If we do not have a known long double format, (including not using
11340  * long doubles, or long doubles being equal to doubles) then we will
11341  * fall back to the ldexp/frexp route, with which we can retrieve at
11342  * most as many bits as our widest unsigned integer type is.  We try
11343  * to get a 64-bit unsigned integer even if we are not using a 64-bit UV.
11344  *
11345  * (If you want to test the case of UVSIZE == 4, NVSIZE == 8,
11346  *  set the MANTISSATYPE to int and the MANTISSASIZE to 4.)
11347  */
11348 #if defined(HAS_QUAD) && defined(Uquad_t)
11349 #  define MANTISSATYPE Uquad_t
11350 #  define MANTISSASIZE 8
11351 #else
11352 #  define MANTISSATYPE UV
11353 #  define MANTISSASIZE UVSIZE
11354 #endif
11355
11356 #if defined(DOUBLE_LITTLE_ENDIAN) || defined(LONGDOUBLE_LITTLE_ENDIAN)
11357 #  define HEXTRACT_LITTLE_ENDIAN
11358 #elif defined(DOUBLE_BIG_ENDIAN) || defined(LONGDOUBLE_BIG_ENDIAN)
11359 #  define HEXTRACT_BIG_ENDIAN
11360 #else
11361 #  define HEXTRACT_MIX_ENDIAN
11362 #endif
11363
11364 /* S_hextract() is a helper for S_format_hexfp, for extracting
11365  * the hexadecimal values (for %a/%A).  The nv is the NV where the value
11366  * are being extracted from (either directly from the long double in-memory
11367  * presentation, or from the uquad computed via frexp+ldexp).  frexp also
11368  * is used to update the exponent.  The subnormal is set to true
11369  * for IEEE 754 subnormals/denormals (including the x86 80-bit format).
11370  * The vhex is the pointer to the beginning of the output buffer of VHEX_SIZE.
11371  *
11372  * The tricky part is that S_hextract() needs to be called twice:
11373  * the first time with vend as NULL, and the second time with vend as
11374  * the pointer returned by the first call.  What happens is that on
11375  * the first round the output size is computed, and the intended
11376  * extraction sanity checked.  On the second round the actual output
11377  * (the extraction of the hexadecimal values) takes place.
11378  * Sanity failures cause fatal failures during both rounds. */
11379 STATIC U8*
11380 S_hextract(pTHX_ const NV nv, int* exponent, bool *subnormal,
11381            U8* vhex, U8* vend)
11382 {
11383     U8* v = vhex;
11384     int ix;
11385     int ixmin = 0, ixmax = 0;
11386
11387     /* XXX Inf/NaN are not handled here, since it is
11388      * assumed they are to be output as "Inf" and "NaN". */
11389
11390     /* These macros are just to reduce typos, they have multiple
11391      * repetitions below, but usually only one (or sometimes two)
11392      * of them is really being used. */
11393     /* HEXTRACT_OUTPUT() extracts the high nybble first. */
11394 #define HEXTRACT_OUTPUT_HI(ix) (*v++ = nvp[ix] >> 4)
11395 #define HEXTRACT_OUTPUT_LO(ix) (*v++ = nvp[ix] & 0xF)
11396 #define HEXTRACT_OUTPUT(ix) \
11397     STMT_START { \
11398       HEXTRACT_OUTPUT_HI(ix); HEXTRACT_OUTPUT_LO(ix); \
11399    } STMT_END
11400 #define HEXTRACT_COUNT(ix, c) \
11401     STMT_START { \
11402       v += c; if (ix < ixmin) ixmin = ix; else if (ix > ixmax) ixmax = ix; \
11403    } STMT_END
11404 #define HEXTRACT_BYTE(ix) \
11405     STMT_START { \
11406       if (vend) HEXTRACT_OUTPUT(ix); else HEXTRACT_COUNT(ix, 2); \
11407    } STMT_END
11408 #define HEXTRACT_LO_NYBBLE(ix) \
11409     STMT_START { \
11410       if (vend) HEXTRACT_OUTPUT_LO(ix); else HEXTRACT_COUNT(ix, 1); \
11411    } STMT_END
11412     /* HEXTRACT_TOP_NYBBLE is just convenience disguise,
11413      * to make it look less odd when the top bits of a NV
11414      * are extracted using HEXTRACT_LO_NYBBLE: the highest
11415      * order bits can be in the "low nybble" of a byte. */
11416 #define HEXTRACT_TOP_NYBBLE(ix) HEXTRACT_LO_NYBBLE(ix)
11417 #define HEXTRACT_BYTES_LE(a, b) \
11418     for (ix = a; ix >= b; ix--) { HEXTRACT_BYTE(ix); }
11419 #define HEXTRACT_BYTES_BE(a, b) \
11420     for (ix = a; ix <= b; ix++) { HEXTRACT_BYTE(ix); }
11421 #define HEXTRACT_GET_SUBNORMAL(nv) *subnormal = Perl_fp_class_denorm(nv)
11422 #define HEXTRACT_IMPLICIT_BIT(nv) \
11423     STMT_START { \
11424         if (!*subnormal) { \
11425             if (vend) *v++ = ((nv) == 0.0) ? 0 : 1; else v++; \
11426         } \
11427    } STMT_END
11428
11429 /* Most formats do.  Those which don't should undef this.
11430  *
11431  * But also note that IEEE 754 subnormals do not have it, or,
11432  * expressed alternatively, their implicit bit is zero. */
11433 #define HEXTRACT_HAS_IMPLICIT_BIT
11434
11435 /* Many formats do.  Those which don't should undef this. */
11436 #define HEXTRACT_HAS_TOP_NYBBLE
11437
11438     /* HEXTRACTSIZE is the maximum number of xdigits. */
11439 #if defined(USE_LONG_DOUBLE) && defined(LONGDOUBLE_DOUBLEDOUBLE)
11440 #  define HEXTRACTSIZE (2+DOUBLEDOUBLE_MAXBITS/4)
11441 #else
11442 #  define HEXTRACTSIZE 2 * NVSIZE
11443 #endif
11444
11445     const U8* vmaxend = vhex + HEXTRACTSIZE;
11446
11447     assert(HEXTRACTSIZE <= VHEX_SIZE);
11448
11449     PERL_UNUSED_VAR(ix); /* might happen */
11450     (void)Perl_frexp(PERL_ABS(nv), exponent);
11451     *subnormal = FALSE;
11452     if (vend && (vend <= vhex || vend > vmaxend)) {
11453         /* diag_listed_as: Hexadecimal float: internal error (%s) */
11454         Perl_croak(aTHX_ "Hexadecimal float: internal error (entry)");
11455     }
11456     {
11457         /* First check if using long doubles. */
11458 #if defined(USE_LONG_DOUBLE) && (NVSIZE > DOUBLESIZE)
11459 #  if LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
11460         /* Used in e.g. VMS and HP-UX IA-64, e.g. -0.1L:
11461          * 9a 99 99 99 99 99 99 99 99 99 99 99 99 99 fb bf */
11462         /* The bytes 13..0 are the mantissa/fraction,
11463          * the 15,14 are the sign+exponent. */
11464         const U8* nvp = (const U8*)(&nv);
11465         HEXTRACT_GET_SUBNORMAL(nv);
11466         HEXTRACT_IMPLICIT_BIT(nv);
11467 #    undef HEXTRACT_HAS_TOP_NYBBLE
11468         HEXTRACT_BYTES_LE(13, 0);
11469 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
11470         /* Used in e.g. Solaris Sparc and HP-UX PA-RISC, e.g. -0.1L:
11471          * bf fb 99 99 99 99 99 99 99 99 99 99 99 99 99 9a */
11472         /* The bytes 2..15 are the mantissa/fraction,
11473          * the 0,1 are the sign+exponent. */
11474         const U8* nvp = (const U8*)(&nv);
11475         HEXTRACT_GET_SUBNORMAL(nv);
11476         HEXTRACT_IMPLICIT_BIT(nv);
11477 #    undef HEXTRACT_HAS_TOP_NYBBLE
11478         HEXTRACT_BYTES_BE(2, 15);
11479 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN
11480         /* x86 80-bit "extended precision", 64 bits of mantissa / fraction /
11481          * significand, 15 bits of exponent, 1 bit of sign.  No implicit bit.
11482          * NVSIZE can be either 12 (ILP32, Solaris x86) or 16 (LP64, Linux
11483          * and OS X), meaning that 2 or 6 bytes are empty padding. */
11484         /* The bytes 0..1 are the sign+exponent,
11485          * the bytes 2..9 are the mantissa/fraction. */
11486         const U8* nvp = (const U8*)(&nv);
11487 #    undef HEXTRACT_HAS_IMPLICIT_BIT
11488 #    undef HEXTRACT_HAS_TOP_NYBBLE
11489         HEXTRACT_GET_SUBNORMAL(nv);
11490         HEXTRACT_BYTES_LE(7, 0);
11491 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN
11492         /* Does this format ever happen? (Wikipedia says the Motorola
11493          * 6888x math coprocessors used format _like_ this but padded
11494          * to 96 bits with 16 unused bits between the exponent and the
11495          * mantissa.) */
11496         const U8* nvp = (const U8*)(&nv);
11497 #    undef HEXTRACT_HAS_IMPLICIT_BIT
11498 #    undef HEXTRACT_HAS_TOP_NYBBLE
11499         HEXTRACT_GET_SUBNORMAL(nv);
11500         HEXTRACT_BYTES_BE(0, 7);
11501 #  else
11502 #    define HEXTRACT_FALLBACK
11503         /* Double-double format: two doubles next to each other.
11504          * The first double is the high-order one, exactly like
11505          * it would be for a "lone" double.  The second double
11506          * is shifted down using the exponent so that that there
11507          * are no common bits.  The tricky part is that the value
11508          * of the double-double is the SUM of the two doubles and
11509          * the second one can be also NEGATIVE.
11510          *
11511          * Because of this tricky construction the bytewise extraction we
11512          * use for the other long double formats doesn't work, we must
11513          * extract the values bit by bit.
11514          *
11515          * The little-endian double-double is used .. somewhere?
11516          *
11517          * The big endian double-double is used in e.g. PPC/Power (AIX)
11518          * and MIPS (SGI).
11519          *
11520          * The mantissa bits are in two separate stretches, e.g. for -0.1L:
11521          * 9a 99 99 99 99 99 59 bc 9a 99 99 99 99 99 b9 3f (LE)
11522          * 3f b9 99 99 99 99 99 9a bc 59 99 99 99 99 99 9a (BE)
11523          */
11524 #  endif
11525 #else /* #if defined(USE_LONG_DOUBLE) && (NVSIZE > DOUBLESIZE) */
11526         /* Using normal doubles, not long doubles.
11527          *
11528          * We generate 4-bit xdigits (nybble/nibble) instead of 8-bit
11529          * bytes, since we might need to handle printf precision, and
11530          * also need to insert the radix. */
11531 #  if NVSIZE == 8
11532 #    ifdef HEXTRACT_LITTLE_ENDIAN
11533         /* 0 1 2 3 4 5 6 7 (MSB = 7, LSB = 0, 6+7 = exponent+sign) */
11534         const U8* nvp = (const U8*)(&nv);
11535         HEXTRACT_GET_SUBNORMAL(nv);
11536         HEXTRACT_IMPLICIT_BIT(nv);
11537         HEXTRACT_TOP_NYBBLE(6);
11538         HEXTRACT_BYTES_LE(5, 0);
11539 #    elif defined(HEXTRACT_BIG_ENDIAN)
11540         /* 7 6 5 4 3 2 1 0 (MSB = 7, LSB = 0, 6+7 = exponent+sign) */
11541         const U8* nvp = (const U8*)(&nv);
11542         HEXTRACT_GET_SUBNORMAL(nv);
11543         HEXTRACT_IMPLICIT_BIT(nv);
11544         HEXTRACT_TOP_NYBBLE(1);
11545         HEXTRACT_BYTES_BE(2, 7);
11546 #    elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_LE_BE
11547         /* 4 5 6 7 0 1 2 3 (MSB = 7, LSB = 0, 6:7 = nybble:exponent:sign) */
11548         const U8* nvp = (const U8*)(&nv);
11549         HEXTRACT_GET_SUBNORMAL(nv);
11550         HEXTRACT_IMPLICIT_BIT(nv);
11551         HEXTRACT_TOP_NYBBLE(2); /* 6 */
11552         HEXTRACT_BYTE(1); /* 5 */
11553         HEXTRACT_BYTE(0); /* 4 */
11554         HEXTRACT_BYTE(7); /* 3 */
11555         HEXTRACT_BYTE(6); /* 2 */
11556         HEXTRACT_BYTE(5); /* 1 */
11557         HEXTRACT_BYTE(4); /* 0 */
11558 #    elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_BE_LE
11559         /* 3 2 1 0 7 6 5 4 (MSB = 7, LSB = 0, 7:6 = sign:exponent:nybble) */
11560         const U8* nvp = (const U8*)(&nv);
11561         HEXTRACT_GET_SUBNORMAL(nv);
11562         HEXTRACT_IMPLICIT_BIT(nv);
11563         HEXTRACT_TOP_NYBBLE(5); /* 6 */
11564         HEXTRACT_BYTE(6); /* 5 */
11565         HEXTRACT_BYTE(7); /* 4 */
11566         HEXTRACT_BYTE(0); /* 3 */
11567         HEXTRACT_BYTE(1); /* 2 */
11568         HEXTRACT_BYTE(2); /* 1 */
11569         HEXTRACT_BYTE(3); /* 0 */
11570 #    else
11571 #      define HEXTRACT_FALLBACK
11572 #    endif
11573 #  else
11574 #    define HEXTRACT_FALLBACK
11575 #  endif
11576 #endif /* #if defined(USE_LONG_DOUBLE) && (NVSIZE > DOUBLESIZE) #else */
11577
11578 #ifdef HEXTRACT_FALLBACK
11579         HEXTRACT_GET_SUBNORMAL(nv);
11580 #  undef HEXTRACT_HAS_TOP_NYBBLE /* Meaningless, but consistent. */
11581         /* The fallback is used for the double-double format, and
11582          * for unknown long double formats, and for unknown double
11583          * formats, or in general unknown NV formats. */
11584         if (nv == (NV)0.0) {
11585             if (vend)
11586                 *v++ = 0;
11587             else
11588                 v++;
11589             *exponent = 0;
11590         }
11591         else {
11592             NV d = nv < 0 ? -nv : nv;
11593             NV e = (NV)1.0;
11594             U8 ha = 0x0; /* hexvalue accumulator */
11595             U8 hd = 0x8; /* hexvalue digit */
11596
11597             /* Shift d and e (and update exponent) so that e <= d < 2*e,
11598              * this is essentially manual frexp(). Multiplying by 0.5 and
11599              * doubling should be lossless in binary floating point. */
11600
11601             *exponent = 1;
11602
11603             while (e > d) {
11604                 e *= (NV)0.5;
11605                 (*exponent)--;
11606             }
11607             /* Now d >= e */
11608
11609             while (d >= e + e) {
11610                 e += e;
11611                 (*exponent)++;
11612             }
11613             /* Now e <= d < 2*e */
11614
11615             /* First extract the leading hexdigit (the implicit bit). */
11616             if (d >= e) {
11617                 d -= e;
11618                 if (vend)
11619                     *v++ = 1;
11620                 else
11621                     v++;
11622             }
11623             else {
11624                 if (vend)
11625                     *v++ = 0;
11626                 else
11627                     v++;
11628             }
11629             e *= (NV)0.5;
11630
11631             /* Then extract the remaining hexdigits. */
11632             while (d > (NV)0.0) {
11633                 if (d >= e) {
11634                     ha |= hd;
11635                     d -= e;
11636                 }
11637                 if (hd == 1) {
11638                     /* Output or count in groups of four bits,
11639                      * that is, when the hexdigit is down to one. */
11640                     if (vend)
11641                         *v++ = ha;
11642                     else
11643                         v++;
11644                     /* Reset the hexvalue. */
11645                     ha = 0x0;
11646                     hd = 0x8;
11647                 }
11648                 else
11649                     hd >>= 1;
11650                 e *= (NV)0.5;
11651             }
11652
11653             /* Flush possible pending hexvalue. */
11654             if (ha) {
11655                 if (vend)
11656                     *v++ = ha;
11657                 else
11658                     v++;
11659             }
11660         }
11661 #endif
11662     }
11663     /* Croak for various reasons: if the output pointer escaped the
11664      * output buffer, if the extraction index escaped the extraction
11665      * buffer, or if the ending output pointer didn't match the
11666      * previously computed value. */
11667     if (v <= vhex || v - vhex >= VHEX_SIZE ||
11668         /* For double-double the ixmin and ixmax stay at zero,
11669          * which is convenient since the HEXTRACTSIZE is tricky
11670          * for double-double. */
11671         ixmin < 0 || ixmax >= NVSIZE ||
11672         (vend && v != vend)) {
11673         /* diag_listed_as: Hexadecimal float: internal error (%s) */
11674         Perl_croak(aTHX_ "Hexadecimal float: internal error (overflow)");
11675     }
11676     return v;
11677 }
11678
11679
11680 /* S_format_hexfp(): helper function for Perl_sv_vcatpvfn_flags().
11681  *
11682  * Processes the %a/%A hexadecimal floating-point format, since the
11683  * built-in snprintf()s which are used for most of the f/p formats, don't
11684  * universally handle %a/%A.
11685  * Populates buf of length bufsize, and returns the length of the created
11686  * string.
11687  * The rest of the args have the same meaning as the local vars of the
11688  * same name within Perl_sv_vcatpvfn_flags().
11689  *
11690  * The caller's determination of IN_LC(LC_NUMERIC), passed as in_lc_numeric,
11691  * is used to ensure we do the right thing when we need to access the locale's
11692  * numeric radix.
11693  *
11694  * It requires the caller to make buf large enough.
11695  */
11696
11697 static STRLEN
11698 S_format_hexfp(pTHX_ char * const buf, const STRLEN bufsize, const char c,
11699                     const NV nv, const vcatpvfn_long_double_t fv,
11700                     bool has_precis, STRLEN precis, STRLEN width,
11701                     bool alt, char plus, bool left, bool fill, bool in_lc_numeric)
11702 {
11703     /* Hexadecimal floating point. */
11704     char* p = buf;
11705     U8 vhex[VHEX_SIZE];
11706     U8* v = vhex; /* working pointer to vhex */
11707     U8* vend; /* pointer to one beyond last digit of vhex */
11708     U8* vfnz = NULL; /* first non-zero */
11709     U8* vlnz = NULL; /* last non-zero */
11710     U8* v0 = NULL; /* first output */
11711     const bool lower = (c == 'a');
11712     /* At output the values of vhex (up to vend) will
11713      * be mapped through the xdig to get the actual
11714      * human-readable xdigits. */
11715     const char* xdig = PL_hexdigit;
11716     STRLEN zerotail = 0; /* how many extra zeros to append */
11717     int exponent = 0; /* exponent of the floating point input */
11718     bool hexradix = FALSE; /* should we output the radix */
11719     bool subnormal = FALSE; /* IEEE 754 subnormal/denormal */
11720     bool negative = FALSE;
11721     STRLEN elen;
11722
11723     /* XXX: NaN, Inf -- though they are printed as "NaN" and "Inf".
11724      *
11725      * For example with denormals, (assuming the vanilla
11726      * 64-bit double): the exponent is zero. 1xp-1074 is
11727      * the smallest denormal and the smallest double, it
11728      * could be output also as 0x0.0000000000001p-1022 to
11729      * match its internal structure. */
11730
11731     vend = S_hextract(aTHX_ nv, &exponent, &subnormal, vhex, NULL);
11732     S_hextract(aTHX_ nv, &exponent, &subnormal, vhex, vend);
11733
11734 #if NVSIZE > DOUBLESIZE
11735 #  ifdef HEXTRACT_HAS_IMPLICIT_BIT
11736     /* In this case there is an implicit bit,
11737      * and therefore the exponent is shifted by one. */
11738     exponent--;
11739 #  elif defined(NV_X86_80_BIT)
11740     if (subnormal) {
11741         /* The subnormals of the x86-80 have a base exponent of -16382,
11742          * (while the physical exponent bits are zero) but the frexp()
11743          * returned the scientific-style floating exponent.  We want
11744          * to map the last one as:
11745          * -16831..-16384 -> -16382 (the last normal is 0x1p-16382)
11746          * -16835..-16388 -> -16384
11747          * since we want to keep the first hexdigit
11748          * as one of the [8421]. */
11749         exponent = -4 * ( (exponent + 1) / -4) - 2;
11750     } else {
11751         exponent -= 4;
11752     }
11753     /* TBD: other non-implicit-bit platforms than the x86-80. */
11754 #  endif
11755 #endif
11756
11757     negative = fv < 0 || Perl_signbit(nv);
11758     if (negative)
11759         *p++ = '-';
11760     else if (plus)
11761         *p++ = plus;
11762     *p++ = '0';
11763     if (lower) {
11764         *p++ = 'x';
11765     }
11766     else {
11767         *p++ = 'X';
11768         xdig += 16; /* Use uppercase hex. */
11769     }
11770
11771     /* Find the first non-zero xdigit. */
11772     for (v = vhex; v < vend; v++) {
11773         if (*v) {
11774             vfnz = v;
11775             break;
11776         }
11777     }
11778
11779     if (vfnz) {
11780         /* Find the last non-zero xdigit. */
11781         for (v = vend - 1; v >= vhex; v--) {
11782             if (*v) {
11783                 vlnz = v;
11784                 break;
11785             }
11786         }
11787
11788 #if NVSIZE == DOUBLESIZE
11789         if (fv != 0.0)
11790             exponent--;
11791 #endif
11792
11793         if (subnormal) {
11794 #ifndef NV_X86_80_BIT
11795           if (vfnz[0] > 1) {
11796             /* IEEE 754 subnormals (but not the x86 80-bit):
11797              * we want "normalize" the subnormal,
11798              * so we need to right shift the hex nybbles
11799              * so that the output of the subnormal starts
11800              * from the first true bit.  (Another, equally
11801              * valid, policy would be to dump the subnormal
11802              * nybbles as-is, to display the "physical" layout.) */
11803             int i, n;
11804             U8 *vshr;
11805             /* Find the ceil(log2(v[0])) of
11806              * the top non-zero nybble. */
11807             for (i = vfnz[0], n = 0; i > 1; i >>= 1, n++) { }
11808             assert(n < 4);
11809             assert(vlnz);
11810             vlnz[1] = 0;
11811             for (vshr = vlnz; vshr >= vfnz; vshr--) {
11812               vshr[1] |= (vshr[0] & (0xF >> (4 - n))) << (4 - n);
11813               vshr[0] >>= n;
11814             }
11815             if (vlnz[1]) {
11816               vlnz++;
11817             }
11818           }
11819 #endif
11820           v0 = vfnz;
11821         } else {
11822           v0 = vhex;
11823         }
11824
11825         if (has_precis) {
11826             U8* ve = (subnormal ? vlnz + 1 : vend);
11827             SSize_t vn = ve - v0;
11828             assert(vn >= 1);
11829             if (precis < (Size_t)(vn - 1)) {
11830                 bool overflow = FALSE;
11831                 if (v0[precis + 1] < 0x8) {
11832                     /* Round down, nothing to do. */
11833                 } else if (v0[precis + 1] > 0x8) {
11834                     /* Round up. */
11835                     v0[precis]++;
11836                     overflow = v0[precis] > 0xF;
11837                     v0[precis] &= 0xF;
11838                 } else { /* v0[precis] == 0x8 */
11839                     /* Half-point: round towards the one
11840                      * with the even least-significant digit:
11841                      * 08 -> 0  88 -> 8
11842                      * 18 -> 2  98 -> a
11843                      * 28 -> 2  a8 -> a
11844                      * 38 -> 4  b8 -> c
11845                      * 48 -> 4  c8 -> c
11846                      * 58 -> 6  d8 -> e
11847                      * 68 -> 6  e8 -> e
11848                      * 78 -> 8  f8 -> 10 */
11849                     if ((v0[precis] & 0x1)) {
11850                         v0[precis]++;
11851                     }
11852                     overflow = v0[precis] > 0xF;
11853                     v0[precis] &= 0xF;
11854                 }
11855
11856                 if (overflow) {
11857                     for (v = v0 + precis - 1; v >= v0; v--) {
11858                         (*v)++;
11859                         overflow = *v > 0xF;
11860                         (*v) &= 0xF;
11861                         if (!overflow) {
11862                             break;
11863                         }
11864                     }
11865                     if (v == v0 - 1 && overflow) {
11866                         /* If the overflow goes all the
11867                          * way to the front, we need to
11868                          * insert 0x1 in front, and adjust
11869                          * the exponent. */
11870                         Move(v0, v0 + 1, vn - 1, char);
11871                         *v0 = 0x1;
11872                         exponent += 4;
11873                     }
11874                 }
11875
11876                 /* The new effective "last non zero". */
11877                 vlnz = v0 + precis;
11878             }
11879             else {
11880                 zerotail =
11881                   subnormal ? precis - vn + 1 :
11882                   precis - (vlnz - vhex);
11883             }
11884         }
11885
11886         v = v0;
11887         *p++ = xdig[*v++];
11888
11889         /* If there are non-zero xdigits, the radix
11890          * is output after the first one. */
11891         if (vfnz < vlnz) {
11892           hexradix = TRUE;
11893         }
11894     }
11895     else {
11896         *p++ = '0';
11897         exponent = 0;
11898         zerotail = has_precis ? precis : 0;
11899     }
11900
11901     /* The radix is always output if precis, or if alt. */
11902     if ((has_precis && precis > 0) || alt) {
11903       hexradix = TRUE;
11904     }
11905
11906     if (hexradix) {
11907 #ifndef USE_LOCALE_NUMERIC
11908         PERL_UNUSED_ARG(in_lc_numeric);
11909
11910         *p++ = '.';
11911 #else
11912         if (in_lc_numeric) {
11913             STRLEN n;
11914             WITH_LC_NUMERIC_SET_TO_NEEDED_IN(TRUE, {
11915                 const char* r = SvPV(PL_numeric_radix_sv, n);
11916                 Copy(r, p, n, char);
11917             });
11918             p += n;
11919         }
11920         else {
11921             *p++ = '.';
11922         }
11923 #endif
11924     }
11925
11926     if (vlnz) {
11927         while (v <= vlnz)
11928             *p++ = xdig[*v++];
11929     }
11930
11931     if (zerotail > 0) {
11932       while (zerotail--) {
11933         *p++ = '0';
11934       }
11935     }
11936
11937     elen = p - buf;
11938
11939     /* sanity checks */
11940     if (elen >= bufsize || width >= bufsize)
11941         /* diag_listed_as: Hexadecimal float: internal error (%s) */
11942         Perl_croak(aTHX_ "Hexadecimal float: internal error (overflow)");
11943
11944     elen += my_snprintf(p, bufsize - elen,
11945                         "%c%+d", lower ? 'p' : 'P',
11946                         exponent);
11947
11948     if (elen < width) {
11949         STRLEN gap = (STRLEN)(width - elen);
11950         if (left) {
11951             /* Pad the back with spaces. */
11952             memset(buf + elen, ' ', gap);
11953         }
11954         else if (fill) {
11955             /* Insert the zeros after the "0x" and the
11956              * the potential sign, but before the digits,
11957              * otherwise we end up with "0000xH.HHH...",
11958              * when we want "0x000H.HHH..."  */
11959             STRLEN nzero = gap;
11960             char* zerox = buf + 2;
11961             STRLEN nmove = elen - 2;
11962             if (negative || plus) {
11963                 zerox++;
11964                 nmove--;
11965             }
11966             Move(zerox, zerox + nzero, nmove, char);
11967             memset(zerox, fill ? '0' : ' ', nzero);
11968         }
11969         else {
11970             /* Move it to the right. */
11971             Move(buf, buf + gap,
11972                  elen, char);
11973             /* Pad the front with spaces. */
11974             memset(buf, ' ', gap);
11975         }
11976         elen = width;
11977     }
11978     return elen;
11979 }
11980
11981 /*
11982 =for apidoc sv_vcatpvfn
11983 =for apidoc_item sv_vcatpvfn_flags
11984
11985 These process their arguments like C<L<vsprintf(3)>> and append the formatted output
11986 to an SV.  They use an array of SVs if the C-style variable argument list is
11987 missing (C<NULL>). Argument reordering (using format specifiers like C<%2$d> or
11988 C<%*2$d>) is supported only when using an array of SVs; using a C-style
11989 C<va_list> argument list with a format string that uses argument reordering
11990 will yield an exception.
11991
11992 When running with taint checks enabled, they indicate via C<maybe_tainted> if
11993 results are untrustworthy (often due to the use of locales).
11994
11995 They assume that C<pat> has the same utf8-ness as C<sv>.  It's the caller's
11996 responsibility to ensure that this is so.
11997
11998 They differ in that C<sv_vcatpvfn_flags> has a C<flags> parameter in which you
11999 can set or clear the C<SV_GMAGIC> and/or S<SV_SMAGIC> flags, to specify which
12000 magic to handle or not handle; whereas plain C<sv_vcatpvfn> always specifies
12001 both 'get' and 'set' magic.
12002
12003 They are usually used via one of the frontends L</C<sv_vcatpvf>> and
12004 L</C<sv_vcatpvf_mg>>.
12005
12006 =cut
12007 */
12008
12009
12010 void
12011 Perl_sv_vcatpvfn_flags(pTHX_ SV *const sv, const char *const pat, const STRLEN patlen,
12012                        va_list *const args, SV **const svargs, const Size_t sv_count, bool *const maybe_tainted,
12013                        const U32 flags)
12014 {
12015     const char *fmtstart; /* character following the current '%' */
12016     const char *q;        /* current position within format */
12017     const char *patend;
12018     STRLEN origlen;
12019     Size_t svix = 0;
12020     static const char nullstr[] = "(null)";
12021     bool has_utf8 = DO_UTF8(sv);    /* has the result utf8? */
12022     const bool pat_utf8 = has_utf8; /* the pattern is in utf8? */
12023     /* Times 4: a decimal digit takes more than 3 binary digits.
12024      * NV_DIG: mantissa takes that many decimal digits.
12025      * Plus 32: Playing safe. */
12026     char ebuf[IV_DIG * 4 + NV_DIG + 32];
12027     bool no_redundant_warning = FALSE; /* did we use any explicit format parameter index? */
12028 #ifdef USE_LOCALE_NUMERIC
12029     bool have_in_lc_numeric = FALSE;
12030 #endif
12031     /* we never change this unless USE_LOCALE_NUMERIC */
12032     bool in_lc_numeric = FALSE;
12033     SV *tmp_sv = NULL;
12034
12035     PERL_ARGS_ASSERT_SV_VCATPVFN_FLAGS;
12036     PERL_UNUSED_ARG(maybe_tainted);
12037
12038     if (flags & SV_GMAGIC)
12039         SvGETMAGIC(sv);
12040
12041     /* no matter what, this is a string now */
12042     (void)SvPV_force_nomg(sv, origlen);
12043
12044     /* the code that scans for flags etc following a % relies on
12045      * a '\0' being present to avoid falling off the end. Ideally that
12046      * should be fixed */
12047     assert(pat[patlen] == '\0');
12048
12049
12050     /* Special-case "", "%s", "%-p" (SVf - see below) and "%.0f".
12051      * In each case, if there isn't the correct number of args, instead
12052      * fall through to the main code to handle the issuing of any
12053      * warnings etc.
12054      */
12055
12056     if (patlen == 0 && (args || sv_count == 0))
12057         return;
12058
12059     if (patlen <= 4 && pat[0] == '%' && (args || sv_count == 1)) {
12060
12061         /* "%s" */
12062         if (patlen == 2 && pat[1] == 's') {
12063             if (args) {
12064                 const char * const s = va_arg(*args, char*);
12065                 sv_catpv_nomg(sv, s ? s : nullstr);
12066             }
12067             else {
12068                 /* we want get magic on the source but not the target.
12069                  * sv_catsv can't do that, though */
12070                 SvGETMAGIC(*svargs);
12071                 sv_catsv_nomg(sv, *svargs);
12072             }
12073             return;
12074         }
12075
12076         /* "%-p" */
12077         if (args) {
12078             if (patlen == 3  && pat[1] == '-' && pat[2] == 'p') {
12079                 SV *asv = MUTABLE_SV(va_arg(*args, void*));
12080                 sv_catsv_nomg(sv, asv);
12081                 return;
12082             }
12083         }
12084 #if !defined(USE_LONG_DOUBLE) && !defined(USE_QUADMATH)
12085         /* special-case "%.0f" */
12086         else if (   patlen == 4
12087                  && pat[1] == '.' && pat[2] == '0' && pat[3] == 'f')
12088         {
12089             const NV nv = SvNV(*svargs);
12090             if (LIKELY(!Perl_isinfnan(nv))) {
12091                 STRLEN l;
12092                 char *p;
12093
12094                 if ((p = F0convert(nv, ebuf + sizeof ebuf, &l))) {
12095                     sv_catpvn_nomg(sv, p, l);
12096                     return;
12097                 }
12098             }
12099         }
12100 #endif /* !USE_LONG_DOUBLE */
12101     }
12102
12103
12104     patend = (char*)pat + patlen;
12105     for (fmtstart = pat; fmtstart < patend; fmtstart = q) {
12106         char intsize     = 0;         /* size qualifier in "%hi..." etc */
12107         bool alt         = FALSE;     /* has      "%#..."    */
12108         bool left        = FALSE;     /* has      "%-..."    */
12109         bool fill        = FALSE;     /* has      "%0..."    */
12110         char plus        = 0;         /* has      "%+..."    */
12111         STRLEN width     = 0;         /* value of "%NNN..."  */
12112         bool has_precis  = FALSE;     /* has      "%.NNN..." */
12113         STRLEN precis    = 0;         /* value of "%.NNN..." */
12114         int base         = 0;         /* base to print in, e.g. 8 for %o */
12115         UV uv            = 0;         /* the value to print of int-ish args */
12116
12117         bool vectorize   = FALSE;     /* has      "%v..."    */
12118         bool vec_utf8    = FALSE;     /* SvUTF8(vec arg)     */
12119         const U8 *vecstr = NULL;      /* SvPVX(vec arg)      */
12120         STRLEN veclen    = 0;         /* SvCUR(vec arg)      */
12121         const char *dotstr = NULL;    /* separator string for %v */
12122         STRLEN dotstrlen;             /* length of separator string for %v */
12123
12124         Size_t efix      = 0;         /* explicit format parameter index */
12125         const Size_t osvix  = svix;   /* original index in case of bad fmt */
12126
12127         SV *argsv        = NULL;
12128         bool is_utf8     = FALSE;     /* is this item utf8?   */
12129         bool arg_missing = FALSE;     /* give "Missing argument" warning */
12130         char esignbuf[4];             /* holds sign prefix, e.g. "-0x" */
12131         STRLEN esignlen  = 0;         /* length of e.g. "-0x" */
12132         STRLEN zeros     = 0;         /* how many '0' to prepend */
12133
12134         const char *eptr = NULL;      /* the address of the element string */
12135         STRLEN elen      = 0;         /* the length  of the element string */
12136
12137         char c;                       /* the actual format ('d', s' etc) */
12138
12139         bool escape_it   = FALSE;     /* if this is a string should we quote and escape it? */
12140
12141
12142         /* echo everything up to the next format specification */
12143         for (q = fmtstart; q < patend && *q != '%'; ++q)
12144             {};
12145
12146         if (q > fmtstart) {
12147             if (has_utf8 && !pat_utf8) {
12148                 /* upgrade and copy the bytes of fmtstart..q-1 to utf8 on
12149                  * the fly */
12150                 const char *p;
12151                 char *dst;
12152                 STRLEN need = SvCUR(sv) + (q - fmtstart) + 1;
12153
12154                 for (p = fmtstart; p < q; p++)
12155                     if (!NATIVE_BYTE_IS_INVARIANT(*p))
12156                         need++;
12157                 SvGROW(sv, need);
12158
12159                 dst = SvEND(sv);
12160                 for (p = fmtstart; p < q; p++)
12161                     append_utf8_from_native_byte((U8)*p, (U8**)&dst);
12162                 *dst = '\0';
12163                 SvCUR_set(sv, need - 1);
12164             }
12165             else
12166                 S_sv_catpvn_simple(aTHX_ sv, fmtstart, q - fmtstart);
12167         }
12168         if (q++ >= patend)
12169             break;
12170
12171         fmtstart = q; /* fmtstart is char following the '%' */
12172
12173 /*
12174     We allow format specification elements in this order:
12175         \d+\$              explicit format parameter index
12176         [-+ 0#]+           flags
12177         v|\*(\d+\$)?v      vector with optional (optionally specified) arg
12178         0                  flag (as above): repeated to allow "v02"
12179         \d+|\*(\d+\$)?     width using optional (optionally specified) arg
12180         \.(\d*|\*(\d+\$)?) precision using optional (optionally specified) arg
12181         [hlqLV]            size
12182     [%bcdefginopsuxDFOUX] format (mandatory)
12183 */
12184
12185         if (inRANGE(*q, '1', '9')) {
12186             width = expect_number(&q);
12187             if (*q == '$') {
12188                 if (args)
12189                     Perl_croak_nocontext(
12190                         "Cannot yet reorder sv_vcatpvfn() arguments from va_list");
12191                 ++q;
12192                 efix = (Size_t)width;
12193                 width = 0;
12194                 no_redundant_warning = TRUE;
12195             } else {
12196                 goto gotwidth;
12197             }
12198         }
12199
12200         /* FLAGS */
12201
12202         while (*q) {
12203             switch (*q) {
12204             case ' ':
12205             case '+':
12206                 if (plus == '+' && *q == ' ') /* '+' over ' ' */
12207                     q++;
12208                 else
12209                     plus = *q++;
12210                 continue;
12211
12212             case '-':
12213                 left = TRUE;
12214                 q++;
12215                 continue;
12216
12217             case '0':
12218                 fill = TRUE;
12219                 q++;
12220                 continue;
12221
12222             case '#':
12223                 alt = TRUE;
12224                 q++;
12225                 continue;
12226
12227             default:
12228                 break;
12229             }
12230             break;
12231         }
12232
12233       /* at this point we can expect one of:
12234        *
12235        *  123  an explicit width
12236        *  *    width taken from next arg
12237        *  *12$ width taken from 12th arg
12238        *       or no width
12239        *
12240        * But any width specification may be preceded by a v, in one of its
12241        * forms:
12242        *        v
12243        *        *v
12244        *        *12$v
12245        * So an asterisk may be either a width specifier or a vector
12246        * separator arg specifier, and we don't know which initially
12247        */
12248
12249       tryasterisk:
12250         if (*q == '*') {
12251             STRLEN ix; /* explicit width/vector separator index */
12252             q++;
12253             if (inRANGE(*q, '1', '9')) {
12254                 ix = expect_number(&q);
12255                 if (*q++ == '$') {
12256                     if (args)
12257                         Perl_croak_nocontext(
12258                             "Cannot yet reorder sv_vcatpvfn() arguments from va_list");
12259                     no_redundant_warning = TRUE;
12260                 } else
12261                     goto unknown;
12262             }
12263             else
12264                 ix = 0;
12265
12266             if (*q == 'v') {
12267                 SV *vecsv;
12268                 /* The asterisk was for  *v, *NNN$v: vectorizing, but not
12269                  * with the default "." */
12270                 q++;
12271                 if (vectorize)
12272                     goto unknown;
12273                 if (args)
12274                     vecsv = va_arg(*args, SV*);
12275                 else {
12276                     ix = ix ? ix - 1 : svix++;
12277                     vecsv = ix < sv_count ? svargs[ix]
12278                                        : (arg_missing = TRUE, &PL_sv_no);
12279                 }
12280                 dotstr = SvPV_const(vecsv, dotstrlen);
12281                 /* Keep the DO_UTF8 test *after* the SvPV call, else things go
12282                    bad with tied or overloaded values that return UTF8.  */
12283                 if (DO_UTF8(vecsv))
12284                     is_utf8 = TRUE;
12285                 else if (has_utf8) {
12286                     vecsv = sv_mortalcopy(vecsv);
12287                     sv_utf8_upgrade(vecsv);
12288                     dotstr = SvPV_const(vecsv, dotstrlen);
12289                     is_utf8 = TRUE;
12290                 }
12291                 vectorize = TRUE;
12292                 goto tryasterisk;
12293             }
12294
12295             /* the asterisk specified a width */
12296             {
12297                 int i = 0;
12298                 SV *width_sv = NULL;
12299                 if (args)
12300                     i = va_arg(*args, int);
12301                 else {
12302                     ix = ix ? ix - 1 : svix++;
12303                     width_sv = (ix < sv_count) ? svargs[ix]
12304                                       : (arg_missing = TRUE, (SV*)NULL);
12305                 }
12306                 width = S_sprintf_arg_num_val(aTHX_ args, i, width_sv, &left);
12307             }
12308         }
12309         else if (*q == 'v') {
12310             q++;
12311             if (vectorize)
12312                 goto unknown;
12313             vectorize = TRUE;
12314             dotstr = ".";
12315             dotstrlen = 1;
12316             goto tryasterisk;
12317
12318         }
12319         else {
12320         /* explicit width? */
12321             if(*q == '0') {
12322                 fill = TRUE;
12323                 q++;
12324             }
12325             if (inRANGE(*q, '1', '9'))
12326                 width = expect_number(&q);
12327         }
12328
12329       gotwidth:
12330
12331         /* PRECISION */
12332
12333         if (*q == '.') {
12334             q++;
12335             if (*q == '*') {
12336                 STRLEN ix; /* explicit precision index */
12337                 q++;
12338                 if (inRANGE(*q, '1', '9')) {
12339                     ix = expect_number(&q);
12340                     if (*q++ == '$') {
12341                         if (args)
12342                             Perl_croak_nocontext(
12343                                 "Cannot yet reorder sv_vcatpvfn() arguments from va_list");
12344                         no_redundant_warning = TRUE;
12345                     } else
12346                         goto unknown;
12347                 }
12348                 else
12349                     ix = 0;
12350
12351                 {
12352                     int i = 0;
12353                     SV *width_sv = NULL;
12354                     bool neg = FALSE;
12355
12356                     if (args)
12357                         i = va_arg(*args, int);
12358                     else {
12359                         ix = ix ? ix - 1 : svix++;
12360                         width_sv = (ix < sv_count) ? svargs[ix]
12361                                           : (arg_missing = TRUE, (SV*)NULL);
12362                     }
12363                     precis = S_sprintf_arg_num_val(aTHX_ args, i, width_sv, &neg);
12364                     has_precis = !neg;
12365                     /* ignore negative precision */
12366                     if (!has_precis)
12367                         precis = 0;
12368                 }
12369             }
12370             else {
12371                 /* although it doesn't seem documented, this code has long
12372                  * behaved so that:
12373                  *   no digits following the '.' is treated like '.0'
12374                  *   the number may be preceded by any number of zeroes,
12375                  *      e.g. "%.0001f", which is the same as "%.1f"
12376                  * so I've kept that behaviour. DAPM May 2017
12377                  */
12378                 while (*q == '0')
12379                     q++;
12380                 precis = inRANGE(*q, '1', '9') ? expect_number(&q) : 0;
12381                 has_precis = TRUE;
12382             }
12383         }
12384
12385         /* SIZE */
12386
12387         switch (*q) {
12388 #ifdef WIN32
12389         case 'I':                       /* Ix, I32x, and I64x */
12390 #  ifdef USE_64_BIT_INT
12391             if (q[1] == '6' && q[2] == '4') {
12392                 q += 3;
12393                 intsize = 'q';
12394                 break;
12395             }
12396 #  endif
12397             if (q[1] == '3' && q[2] == '2') {
12398                 q += 3;
12399                 break;
12400             }
12401 #  ifdef USE_64_BIT_INT
12402             intsize = 'q';
12403 #  endif
12404             q++;
12405             break;
12406 #endif
12407 #if (IVSIZE >= 8 || defined(HAS_LONG_DOUBLE)) || \
12408     (IVSIZE == 4 && !defined(HAS_LONG_DOUBLE))
12409         case 'L':                       /* Ld */
12410             /* FALLTHROUGH */
12411 #  if IVSIZE >= 8
12412         case 'q':                       /* qd */
12413 #  endif
12414             intsize = 'q';
12415             q++;
12416             break;
12417 #endif
12418         case 'l':
12419             ++q;
12420 #if (IVSIZE >= 8 || defined(HAS_LONG_DOUBLE)) || \
12421     (IVSIZE == 4 && !defined(HAS_LONG_DOUBLE))
12422             if (*q == 'l') {    /* lld, llf */
12423                 intsize = 'q';
12424                 ++q;
12425             }
12426             else
12427 #endif
12428                 intsize = 'l';
12429             break;
12430         case 'h':
12431             if (*++q == 'h') {  /* hhd, hhu */
12432                 intsize = 'c';
12433                 ++q;
12434             }
12435             else
12436                 intsize = 'h';
12437             break;
12438 #ifdef USE_QUADMATH
12439         case 'Q':
12440 #endif
12441         case 'V':
12442         case 'z':
12443         case 't':
12444         case 'j':
12445             intsize = *q++;
12446             break;
12447         }
12448
12449         /* CONVERSION */
12450
12451         c = *q++; /* c now holds the conversion type */
12452
12453         /* '%' doesn't have an arg, so skip arg processing */
12454         if (c == '%') {
12455             eptr = q - 1;
12456             elen = 1;
12457             if (vectorize)
12458                 goto unknown;
12459             goto string;
12460         }
12461
12462         if (vectorize && !memCHRs("BbDdiOouUXx", c))
12463             goto unknown;
12464
12465         /* get next arg (individual branches do their own va_arg()
12466          * handling for the args case) */
12467
12468         if (!args) {
12469             efix = efix ? efix - 1 : svix++;
12470             argsv = efix < sv_count ? svargs[efix]
12471                                  : (arg_missing = TRUE, &PL_sv_no);
12472         }
12473
12474
12475         switch (c) {
12476
12477             /* STRINGS */
12478
12479         case 's':
12480             if (args) {
12481                 eptr = va_arg(*args, char*);
12482                 if (eptr)
12483                     if (has_precis)
12484                         elen = my_strnlen(eptr, precis);
12485                     else
12486                         elen = strlen(eptr);
12487                 else {
12488                     eptr = (char *)nullstr;
12489                     elen = sizeof nullstr - 1;
12490                 }
12491             }
12492             else {
12493                 eptr = SvPV_const(argsv, elen);
12494                 if (DO_UTF8(argsv)) {
12495                     STRLEN old_precis = precis;
12496                     if (has_precis && precis < elen) {
12497                         STRLEN ulen = sv_or_pv_len_utf8(argsv, eptr, elen);
12498                         STRLEN p = precis > ulen ? ulen : precis;
12499                         precis = sv_or_pv_pos_u2b(argsv, eptr, p, 0);
12500                                                         /* sticks at end */
12501                     }
12502                     if (width) { /* fudge width (can't fudge elen) */
12503                         if (has_precis && precis < elen)
12504                             width += precis - old_precis;
12505                         else
12506                             width +=
12507                                 elen - sv_or_pv_len_utf8(argsv,eptr,elen);
12508                     }
12509                     is_utf8 = TRUE;
12510                 }
12511             }
12512
12513         string:
12514             if (escape_it) {
12515                 U32 flags = PERL_PV_PRETTY_QUOTEDPREFIX;
12516                 if (is_utf8)
12517                     flags |= PERL_PV_ESCAPE_UNI;
12518
12519                 if (!tmp_sv) {
12520                     /* "blah"... where blah might be made up
12521                      * of characters like \x{1234} */
12522                     tmp_sv = newSV(1 + (PERL_QUOTEDPREFIX_LEN * 8) + 1 + 3);
12523                     sv_2mortal(tmp_sv);
12524                 }
12525                 pv_pretty(tmp_sv, eptr, elen, PERL_QUOTEDPREFIX_LEN,
12526                             NULL, NULL, flags);
12527                 eptr = SvPV_const(tmp_sv, elen);
12528             }
12529             if (has_precis && precis < elen)
12530                 elen = precis;
12531             break;
12532
12533             /* INTEGERS */
12534
12535         case 'p':
12536
12537             /* BEGIN NOTE
12538              *
12539              * We want to extend the C level sprintf format API with
12540              * custom formats for specific types (eg SV*) and behavior.
12541              * However some C compilers are "sprintf aware" and will
12542              * throw compile time exceptions when an illegal sprintf is
12543              * encountered, so we can't just add new format letters.
12544              *
12545              * However it turns out the length argument to the %p format
12546              * is more or less useless (the size of a pointer does not
12547              * change over time) and is not really used in the C level
12548              * code. Accordingly we can map our special behavior to
12549              * specific "length" options to the %p format. We hide these
12550              * mappings behind defines anyway, so nobody needs to know
12551              * that HEKf is actually %2p. This keeps the C compiler
12552              * happy while allowing us to add new formats.
12553              *
12554              * Note the existing logic for which number is used for what
12555              * is torturous. All negative values are used for SVf, and
12556              * non-negative values have arbitrary meanings with no
12557              * structure to them. This may change in the future.
12558              *
12559              * NEVER use the raw %p values directly. Always use the define
12560              * as the underlying mapping may change in the future.
12561              *
12562              * END NOTE
12563              *
12564              * %p extensions:
12565              *
12566              * "%...p" is normally treated like "%...x", except that the
12567              * number to print is the SV's address (or a pointer address
12568              * for C-ish sprintf).
12569              *
12570              * However, the C-ish sprintf variant allows a few special
12571              * extensions. These are currently:
12572              *
12573              * %-p       (SVf)  Like %s, but gets the string from an SV*
12574              *                  arg rather than a char* arg. Use C<SVfARG()>
12575              *                  to set up the argument properly.
12576              *                  (This was previously %_).
12577              *
12578              * %-<num>p         Ditto but like %.<num>s (i.e. num is max
12579              *                  width), there is no escaped and quoted version
12580              *                  of this.
12581              *
12582              * %1p       (PVf_QUOTEDPREFIX). Like raw %s, but it is escaped
12583              *                  and quoted.
12584              *
12585              * %5p       (SVf_QUOTEDPREFIX) Like SVf, but length restricted,
12586              *                  escaped and quoted with pv_pretty. Intended
12587              *                  for error messages.
12588              *
12589              * %2p       (HEKf) Like %s, but using the key string in a HEK
12590              * %7p       (HEKf_QUOTEDPREFIX) ... but escaped and quoted.
12591              *
12592              * %3p       (HEKf256) Ditto but like %.256s
12593              * %8p       (HEKf256_QUOTEDPREFIX) ... but escaped and quoted
12594              *
12595              * %d%lu%4p  (UTF8f) A utf8 string. Consumes 3 args:
12596              *                       (cBOOL(utf8), len, string_buf).
12597              *                   It's handled by the "case 'd'" branch
12598              *                   rather than here.
12599              * %d%lu%9p  (UTF8f_QUOTEDPREFIX) .. but escaped and quoted.
12600              *
12601              *
12602              * %<num>p   where num is > 9: reserved for future
12603              *           extensions. Warns, but then is treated as a
12604              *           general %p (print hex address) format.
12605              *
12606              * NOTE: If you add a new magic %p value you will
12607              * need to update F<t/porting/diag.t> to be aware of it
12608              * on top of adding the various defines and etc. Do not
12609              * forget to add it to F<pod/perlguts.pod> as well.
12610              */
12611
12612             if (   args
12613                 && !intsize
12614                 && !fill
12615                 && !plus
12616                 && !has_precis
12617                     /* not %*p or %*1$p - any width was explicit */
12618                 && q[-2] != '*'
12619                 && q[-2] != '$'
12620             ) {
12621                 if (left || width == 5) {                /* %-p (SVf), %-NNNp, %5p */
12622                     if (left && width) {
12623                         precis = width;
12624                         has_precis = TRUE;
12625                     } else if (width == 5) {
12626                         escape_it = TRUE;
12627                     }
12628                     argsv = MUTABLE_SV(va_arg(*args, void*));
12629                     eptr = SvPV_const(argsv, elen);
12630                     if (DO_UTF8(argsv))
12631                         is_utf8 = TRUE;
12632                     width = 0;
12633                     goto string;
12634                 }
12635                 else if (width == 2 || width == 3 ||
12636                          width == 7 || width == 8)
12637                 {        /* HEKf, HEKf256, HEKf_QUOTEDPREFIX, HEKf256_QUOTEDPREFIX */
12638                     HEK * const hek = va_arg(*args, HEK *);
12639                     eptr = HEK_KEY(hek);
12640                     elen = HEK_LEN(hek);
12641                     if (HEK_UTF8(hek))
12642                         is_utf8 = TRUE;
12643                     if (width == 3) {
12644                         precis = 256;
12645                         has_precis = TRUE;
12646                     }
12647                     if (width > 5)
12648                         escape_it = TRUE;
12649                     width = 0;
12650                     goto string;
12651                 }
12652                 else if (width == 1) {
12653                     eptr = va_arg(*args,char *);
12654                     elen = strlen(eptr);
12655                     escape_it = TRUE;
12656                     width = 0;
12657                     goto string;
12658                 }
12659                 else if (width) {
12660                     /* note width=4 or width=9 is handled under %d */
12661                     Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
12662                          "internal %%<num>p might conflict with future printf extensions");
12663                 }
12664             }
12665
12666             /* treat as normal %...p */
12667
12668             uv = PTR2UV(args ? va_arg(*args, void*) : argsv);
12669             base = 16;
12670             c = 'x';    /* in case the format string contains '#' */
12671             goto do_integer;
12672
12673         case 'c':
12674             /* Ignore any size specifiers, since they're not documented as
12675              * being allowed for %c (ideally we should warn on e.g. '%hc').
12676              * Setting a default intsize, along with a positive
12677              * (which signals unsigned) base, causes, for C-ish use, the
12678              * va_arg to be interpreted as an unsigned int, when it's
12679              * actually signed, which will convert -ve values to high +ve
12680              * values. Note that unlike the libc %c, values > 255 will
12681              * convert to high unicode points rather than being truncated
12682              * to 8 bits. For perlish use, it will do SvUV(argsv), which
12683              * will again convert -ve args to high -ve values.
12684              */
12685             intsize = 0;
12686             base = 1; /* special value that indicates we're doing a 'c' */
12687             goto get_int_arg_val;
12688
12689         case 'D':
12690 #ifdef IV_IS_QUAD
12691             intsize = 'q';
12692 #else
12693             intsize = 'l';
12694 #endif
12695             base = -10;
12696             goto get_int_arg_val;
12697
12698         case 'd':
12699             /* probably just a plain %d, but it might be the start of the
12700              * special UTF8f format, which usually looks something like
12701              * "%d%lu%4p" (the lu may vary by platform) or
12702              * "%d%lu%9p" for an escaped version.
12703              */
12704             assert((UTF8f)[0] == 'd');
12705             assert((UTF8f)[1] == '%');
12706
12707              if (   args              /* UTF8f only valid for C-ish sprintf */
12708                  && q == fmtstart + 1 /* plain %d, not %....d */
12709                  && patend >= fmtstart + sizeof(UTF8f) - 1 /* long enough */
12710                  && *q == '%'
12711                  && strnEQ(q + 1, (UTF8f) + 2, sizeof(UTF8f) - 5)
12712                  && q[sizeof(UTF8f)-3] == 'p'
12713                  && (q[sizeof(UTF8f)-4] == '4' ||
12714                      q[sizeof(UTF8f)-4] == '9'))
12715             {
12716                 /* The argument has already gone through cBOOL, so the cast
12717                    is safe. */
12718                 if (q[sizeof(UTF8f)-4] == '9')
12719                     escape_it = TRUE;
12720                 is_utf8 = (bool)va_arg(*args, int);
12721                 elen = va_arg(*args, UV);
12722                 /* if utf8 length is larger than 0x7ffff..., then it might
12723                  * have been a signed value that wrapped */
12724                 if (elen  > ((~(STRLEN)0) >> 1)) {
12725                     assert(0); /* in DEBUGGING build we want to crash */
12726                     elen = 0; /* otherwise we want to treat this as an empty string */
12727                 }
12728                 eptr = va_arg(*args, char *);
12729                 q += sizeof(UTF8f) - 2;
12730                 goto string;
12731             }
12732
12733             /* FALLTHROUGH */
12734         case 'i':
12735             base = -10;
12736             goto get_int_arg_val;
12737
12738         case 'U':
12739 #ifdef IV_IS_QUAD
12740             intsize = 'q';
12741 #else
12742             intsize = 'l';
12743 #endif
12744             /* FALLTHROUGH */
12745         case 'u':
12746             base = 10;
12747             goto get_int_arg_val;
12748
12749         case 'B':
12750         case 'b':
12751             base = 2;
12752             goto get_int_arg_val;
12753
12754         case 'O':
12755 #ifdef IV_IS_QUAD
12756             intsize = 'q';
12757 #else
12758             intsize = 'l';
12759 #endif
12760             /* FALLTHROUGH */
12761         case 'o':
12762             base = 8;
12763             goto get_int_arg_val;
12764
12765         case 'X':
12766         case 'x':
12767             base = 16;
12768
12769           get_int_arg_val:
12770
12771             if (vectorize) {
12772                 STRLEN ulen;
12773                 SV *vecsv;
12774
12775                 if (base < 0) {
12776                     base = -base;
12777                     if (plus)
12778                          esignbuf[esignlen++] = plus;
12779                 }
12780
12781                 /* initialise the vector string to iterate over */
12782
12783                 vecsv = args ? va_arg(*args, SV*) : argsv;
12784
12785                 /* if this is a version object, we need to convert
12786                  * back into v-string notation and then let the
12787                  * vectorize happen normally
12788                  */
12789                 if (sv_isobject(vecsv) && sv_derived_from(vecsv, "version")) {
12790                     if ( hv_existss(MUTABLE_HV(SvRV(vecsv)), "alpha") ) {
12791                         Perl_ck_warner_d(aTHX_ packWARN(WARN_PRINTF),
12792                         "vector argument not supported with alpha versions");
12793                         vecsv = &PL_sv_no;
12794                     }
12795                     else {
12796                         vecstr = (U8*)SvPV_const(vecsv,veclen);
12797                         vecsv = sv_newmortal();
12798                         scan_vstring((char *)vecstr, (char *)vecstr + veclen,
12799                                      vecsv);
12800                     }
12801                 }
12802                 vecstr = (U8*)SvPV_const(vecsv, veclen);
12803                 vec_utf8 = DO_UTF8(vecsv);
12804
12805               /* This is the re-entry point for when we're iterating
12806                * over the individual characters of a vector arg */
12807               vector:
12808                 if (!veclen)
12809                     goto done_valid_conversion;
12810                 if (vec_utf8)
12811                     uv = utf8n_to_uvchr(vecstr, veclen, &ulen,
12812                                         UTF8_ALLOW_ANYUV);
12813                 else {
12814                     uv = *vecstr;
12815                     ulen = 1;
12816                 }
12817                 vecstr += ulen;
12818                 veclen -= ulen;
12819             }
12820             else {
12821                 /* test arg for inf/nan. This can trigger an unwanted
12822                  * 'str' overload, so manually force 'num' overload first
12823                  * if necessary */
12824                 if (argsv) {
12825                     SvGETMAGIC(argsv);
12826                     if (UNLIKELY(SvAMAGIC(argsv)))
12827                         argsv = sv_2num(argsv);
12828                     if (UNLIKELY(isinfnansv(argsv)))
12829                         goto handle_infnan_argsv;
12830                 }
12831
12832                 if (base < 0) {
12833                     /* signed int type */
12834                     IV iv;
12835                     base = -base;
12836                     if (args) {
12837                         switch (intsize) {
12838                         case 'c':  iv = (char)va_arg(*args, int);  break;
12839                         case 'h':  iv = (short)va_arg(*args, int); break;
12840                         case 'l':  iv = va_arg(*args, long);       break;
12841                         case 'V':  iv = va_arg(*args, IV);         break;
12842                         case 'z':  iv = va_arg(*args, SSize_t);    break;
12843 #ifdef HAS_PTRDIFF_T
12844                         case 't':  iv = va_arg(*args, ptrdiff_t);  break;
12845 #endif
12846                         default:   iv = va_arg(*args, int);        break;
12847                         case 'j':  iv = (IV) va_arg(*args, PERL_INTMAX_T); break;
12848                         case 'q':
12849 #if IVSIZE >= 8
12850                                    iv = va_arg(*args, Quad_t);     break;
12851 #else
12852                                    goto unknown;
12853 #endif
12854                         }
12855                     }
12856                     else {
12857                         /* assign to tiv then cast to iv to work around
12858                          * 2003 GCC cast bug (gnu.org bugzilla #13488) */
12859                         IV tiv = SvIV_nomg(argsv);
12860                         switch (intsize) {
12861                         case 'c':  iv = (char)tiv;   break;
12862                         case 'h':  iv = (short)tiv;  break;
12863                         case 'l':  iv = (long)tiv;   break;
12864                         case 'V':
12865                         default:   iv = tiv;         break;
12866                         case 'q':
12867 #if IVSIZE >= 8
12868                                    iv = (Quad_t)tiv; break;
12869 #else
12870                                    goto unknown;
12871 #endif
12872                         }
12873                     }
12874
12875                     /* now convert iv to uv */
12876                     if (iv >= 0) {
12877                         uv = iv;
12878                         if (plus)
12879                             esignbuf[esignlen++] = plus;
12880                     }
12881                     else {
12882                         /* Using 0- here to silence bogus warning from MS VC */
12883                         uv = (UV) (0 - (UV) iv);
12884                         esignbuf[esignlen++] = '-';
12885                     }
12886                 }
12887                 else {
12888                     /* unsigned int type */
12889                     if (args) {
12890                         switch (intsize) {
12891                         case 'c': uv = (unsigned char)va_arg(*args, unsigned);
12892                                   break;
12893                         case 'h': uv = (unsigned short)va_arg(*args, unsigned);
12894                                   break;
12895                         case 'l': uv = va_arg(*args, unsigned long); break;
12896                         case 'V': uv = va_arg(*args, UV);            break;
12897                         case 'z': uv = va_arg(*args, Size_t);        break;
12898 #ifdef HAS_PTRDIFF_T
12899                                   /* will sign extend, but there is no
12900                                    * uptrdiff_t, so oh well */
12901                         case 't': uv = va_arg(*args, ptrdiff_t);     break;
12902 #endif
12903                         case 'j': uv = (UV) va_arg(*args, PERL_UINTMAX_T); break;
12904                         default:  uv = va_arg(*args, unsigned);      break;
12905                         case 'q':
12906 #if IVSIZE >= 8
12907                                   uv = va_arg(*args, Uquad_t);       break;
12908 #else
12909                                   goto unknown;
12910 #endif
12911                         }
12912                     }
12913                     else {
12914                         /* assign to tiv then cast to iv to work around
12915                          * 2003 GCC cast bug (gnu.org bugzilla #13488) */
12916                         UV tuv = SvUV_nomg(argsv);
12917                         switch (intsize) {
12918                         case 'c': uv = (unsigned char)tuv;  break;
12919                         case 'h': uv = (unsigned short)tuv; break;
12920                         case 'l': uv = (unsigned long)tuv;  break;
12921                         case 'V':
12922                         default:  uv = tuv;                 break;
12923                         case 'q':
12924 #if IVSIZE >= 8
12925                                   uv = (Uquad_t)tuv;        break;
12926 #else
12927                                   goto unknown;
12928 #endif
12929                         }
12930                     }
12931                 }
12932             }
12933
12934         do_integer:
12935             {
12936                 char *ptr = ebuf + sizeof ebuf;
12937                 unsigned dig;
12938                 zeros = 0;
12939
12940                 switch (base) {
12941                 case 16:
12942                     {
12943                     const char * const p =
12944                             (c == 'X') ? PL_hexdigit + 16 : PL_hexdigit;
12945
12946                         do {
12947                             dig = uv & 15;
12948                             *--ptr = p[dig];
12949                         } while (uv >>= 4);
12950                         if (alt && *ptr != '0') {
12951                             esignbuf[esignlen++] = '0';
12952                             esignbuf[esignlen++] = c;  /* 'x' or 'X' */
12953                         }
12954                         break;
12955                     }
12956                 case 8:
12957                     do {
12958                         dig = uv & 7;
12959                         *--ptr = '0' + dig;
12960                     } while (uv >>= 3);
12961                     if (alt && *ptr != '0')
12962                         *--ptr = '0';
12963                     break;
12964                 case 2:
12965                     do {
12966                         dig = uv & 1;
12967                         *--ptr = '0' + dig;
12968                     } while (uv >>= 1);
12969                     if (alt && *ptr != '0') {
12970                         esignbuf[esignlen++] = '0';
12971                         esignbuf[esignlen++] = c; /* 'b' or 'B' */
12972                     }
12973                     break;
12974
12975                 case 1:
12976                     /* special-case: base 1 indicates a 'c' format:
12977                      * we use the common code for extracting a uv,
12978                      * but handle that value differently here than
12979                      * all the other int types */
12980                     if ((uv > 255 ||
12981                          (!UVCHR_IS_INVARIANT(uv) && SvUTF8(sv)))
12982                         && !IN_BYTES)
12983                     {
12984                         STATIC_ASSERT_STMT(sizeof(ebuf) >= UTF8_MAXBYTES + 1);
12985                         eptr = ebuf;
12986                         elen = uvchr_to_utf8((U8*)eptr, uv) - (U8*)ebuf;
12987                         is_utf8 = TRUE;
12988                     }
12989                     else {
12990                         eptr = ebuf;
12991                         ebuf[0] = (char)uv;
12992                         elen = 1;
12993                     }
12994                     goto string;
12995
12996                 default:                /* it had better be ten or less */
12997                     do {
12998                         dig = uv % base;
12999                         *--ptr = '0' + dig;
13000                     } while (uv /= base);
13001                     break;
13002                 }
13003                 elen = (ebuf + sizeof ebuf) - ptr;
13004                 eptr = ptr;
13005                 if (has_precis) {
13006                     if (precis > elen)
13007                         zeros = precis - elen;
13008                     else if (precis == 0 && elen == 1 && *eptr == '0'
13009                              && !(base == 8 && alt)) /* "%#.0o" prints "0" */
13010                         elen = 0;
13011
13012                     /* a precision nullifies the 0 flag. */
13013                     fill = FALSE;
13014                 }
13015             }
13016             break;
13017
13018             /* FLOATING POINT */
13019
13020         case 'F':
13021             c = 'f';            /* maybe %F isn't supported here */
13022             /* FALLTHROUGH */
13023         case 'e': case 'E':
13024         case 'f':
13025         case 'g': case 'G':
13026         case 'a': case 'A':
13027
13028         {
13029             STRLEN float_need; /* what PL_efloatsize needs to become */
13030             bool hexfp;        /* hexadecimal floating point? */
13031
13032             vcatpvfn_long_double_t fv;
13033             NV                     nv;
13034
13035             /* This is evil, but floating point is even more evil */
13036
13037             /* for SV-style calling, we can only get NV
13038                for C-style calling, we assume %f is double;
13039                for simplicity we allow any of %Lf, %llf, %qf for long double
13040             */
13041             switch (intsize) {
13042 #if defined(USE_QUADMATH)
13043             case 'Q':
13044                 break;
13045 #endif
13046             case 'V':
13047 #if defined(USE_LONG_DOUBLE) || defined(USE_QUADMATH)
13048                 intsize = 'q';
13049 #endif
13050                 break;
13051 /* [perl #20339] - we should accept and ignore %lf rather than die */
13052             case 'l':
13053                 /* FALLTHROUGH */
13054             default:
13055 #if defined(USE_LONG_DOUBLE) || defined(USE_QUADMATH)
13056                 intsize = args ? 0 : 'q';
13057 #endif
13058                 break;
13059             case 'q':
13060 #if defined(HAS_LONG_DOUBLE)
13061                 break;
13062 #else
13063                 /* FALLTHROUGH */
13064 #endif
13065             case 'c':
13066             case 'h':
13067             case 'z':
13068             case 't':
13069             case 'j':
13070                 goto unknown;
13071             }
13072
13073             /* Now we need (long double) if intsize == 'q', else (double). */
13074             if (args) {
13075                 /* Note: do not pull NVs off the va_list with va_arg()
13076                  * (pull doubles instead) because if you have a build
13077                  * with long doubles, you would always be pulling long
13078                  * doubles, which would badly break anyone using only
13079                  * doubles (i.e. the majority of builds). In other
13080                  * words, you cannot mix doubles and long doubles.
13081                  * The only case where you can pull off long doubles
13082                  * is when the format specifier explicitly asks so with
13083                  * e.g. "%Lg". */
13084 #ifdef USE_QUADMATH
13085                 nv = intsize == 'Q' ? va_arg(*args, NV) :
13086                     intsize == 'q' ? va_arg(*args, long double) :
13087                     va_arg(*args, double);
13088                 fv = nv;
13089 #elif LONG_DOUBLESIZE > DOUBLESIZE
13090                 if (intsize == 'q') {
13091                     fv = va_arg(*args, long double);
13092                     nv = fv;
13093                 } else {
13094                     nv = va_arg(*args, double);
13095                     VCATPVFN_NV_TO_FV(nv, fv);
13096                 }
13097 #else
13098                 nv = va_arg(*args, double);
13099                 fv = nv;
13100 #endif
13101             }
13102             else
13103             {
13104                 SvGETMAGIC(argsv);
13105                 /* we jump here if an int-ish format encountered an
13106                  * infinite/Nan argsv. After setting nv/fv, it falls
13107                  * into the isinfnan block which follows */
13108               handle_infnan_argsv:
13109                 nv = SvNV_nomg(argsv);
13110                 VCATPVFN_NV_TO_FV(nv, fv);
13111             }
13112
13113             if (Perl_isinfnan(nv)) {
13114                 if (c == 'c')
13115                     Perl_croak(aTHX_ "Cannot printf %" NVgf " with '%c'",
13116                                nv, (int)c);
13117
13118                 elen = S_infnan_2pv(nv, ebuf, sizeof(ebuf), plus);
13119                 assert(elen);
13120                 eptr = ebuf;
13121                 zeros     = 0;
13122                 esignlen  = 0;
13123                 dotstrlen = 0;
13124                 break;
13125             }
13126
13127             /* special-case "%.0f" */
13128             if (   c == 'f'
13129                 && !precis
13130                 && has_precis
13131                 && !(width || left || plus || alt)
13132                 && !fill
13133                 && intsize != 'q'
13134                 && ((eptr = F0convert(nv, ebuf + sizeof ebuf, &elen)))
13135             )
13136                 goto float_concat;
13137
13138             /* Determine the buffer size needed for the various
13139              * floating-point formats.
13140              *
13141              * The basic possibilities are:
13142              *
13143              *               <---P--->
13144              *    %f 1111111.123456789
13145              *    %e       1.111111123e+06
13146              *    %a     0x1.0f4471f9bp+20
13147              *    %g        1111111.12
13148              *    %g        1.11111112e+15
13149              *
13150              * where P is the value of the precision in the format, or 6
13151              * if not specified. Note the two possible output formats of
13152              * %g; in both cases the number of significant digits is <=
13153              * precision.
13154              *
13155              * For most of the format types the maximum buffer size needed
13156              * is precision, plus: any leading 1 or 0x1, the radix
13157              * point, and an exponent.  The difficult one is %f: for a
13158              * large positive exponent it can have many leading digits,
13159              * which needs to be calculated specially. Also %a is slightly
13160              * different in that in the absence of a specified precision,
13161              * it uses as many digits as necessary to distinguish
13162              * different values.
13163              *
13164              * First, here are the constant bits. For ease of calculation
13165              * we over-estimate the needed buffer size, for example by
13166              * assuming all formats have an exponent and a leading 0x1.
13167              *
13168              * Also for production use, add a little extra overhead for
13169              * safety's sake. Under debugging don't, as it means we're
13170              * more likely to quickly spot issues during development.
13171              */
13172
13173             float_need =     1  /* possible unary minus */
13174                           +  4  /* "0x1" plus very unlikely carry */
13175                           +  1  /* default radix point '.' */
13176                           +  2  /* "e-", "p+" etc */
13177                           +  6  /* exponent: up to 16383 (quad fp) */
13178 #ifndef DEBUGGING
13179                           + 20  /* safety net */
13180 #endif
13181                           +  1; /* \0 */
13182
13183
13184             /* determine the radix point len, e.g. length(".") in "1.2" */
13185 #ifdef USE_LOCALE_NUMERIC
13186             /* note that we may either explicitly use PL_numeric_radix_sv
13187              * below, or implicitly, via an snprintf() variant.
13188              * Note also things like ps_AF.utf8 which has
13189              * "\N{ARABIC DECIMAL SEPARATOR} as a radix point */
13190             if (! have_in_lc_numeric) {
13191                 in_lc_numeric = IN_LC(LC_NUMERIC);
13192                 have_in_lc_numeric = TRUE;
13193             }
13194
13195             if (in_lc_numeric) {
13196                 WITH_LC_NUMERIC_SET_TO_NEEDED_IN(TRUE, {
13197                     /* this can't wrap unless PL_numeric_radix_sv is a string
13198                      * consuming virtually all the 32-bit or 64-bit address
13199                      * space
13200                      */
13201                     float_need += (SvCUR(PL_numeric_radix_sv) - 1);
13202
13203                     /* floating-point formats only get utf8 if the radix point
13204                      * is utf8. All other characters in the string are < 128
13205                      * and so can be safely appended to both a non-utf8 and utf8
13206                      * string as-is.
13207                      * Note that this will convert the output to utf8 even if
13208                      * the radix point didn't get output.
13209                      */
13210                     if (SvUTF8(PL_numeric_radix_sv) && !has_utf8) {
13211                         sv_utf8_upgrade(sv);
13212                         has_utf8 = TRUE;
13213                     }
13214                 });
13215             }
13216 #endif
13217
13218             hexfp = FALSE;
13219
13220             if (isALPHA_FOLD_EQ(c, 'f')) {
13221                 /* Determine how many digits before the radix point
13222                  * might be emitted.  frexp() (or frexpl) has some
13223                  * unspecified behaviour for nan/inf/-inf, so lucky we've
13224                  * already handled them above */
13225                 STRLEN digits;
13226                 int i = PERL_INT_MIN;
13227                 (void)Perl_frexp((NV)fv, &i);
13228                 if (i == PERL_INT_MIN)
13229                     Perl_die(aTHX_ "panic: frexp: %" VCATPVFN_FV_GF, fv);
13230
13231                 if (i > 0) {
13232                     digits = BIT_DIGITS(i);
13233                     /* this can't overflow. 'digits' will only be a few
13234                      * thousand even for the largest floating-point types.
13235                      * And up until now float_need is just some small
13236                      * constants plus radix len, which can't be in
13237                      * overflow territory unless the radix SV is consuming
13238                      * over 1/2 the address space */
13239                     assert(float_need < ((STRLEN)~0) - digits);
13240                     float_need += digits;
13241                 }
13242             }
13243             else if (UNLIKELY(isALPHA_FOLD_EQ(c, 'a'))) {
13244                 hexfp = TRUE;
13245                 if (!has_precis) {
13246                     /* %a in the absence of precision may print as many
13247                      * digits as needed to represent the entire mantissa
13248                      * bit pattern.
13249                      * This estimate seriously overshoots in most cases,
13250                      * but better the undershooting.  Firstly, all bytes
13251                      * of the NV are not mantissa, some of them are
13252                      * exponent.  Secondly, for the reasonably common
13253                      * long doubles case, the "80-bit extended", two
13254                      * or six bytes of the NV are unused. Also, we'll
13255                      * still pick up an extra +6 from the default
13256                      * precision calculation below. */
13257                     STRLEN digits =
13258 #ifdef LONGDOUBLE_DOUBLEDOUBLE
13259                         /* For the "double double", we need more.
13260                          * Since each double has their own exponent, the
13261                          * doubles may float (haha) rather far from each
13262                          * other, and the number of required bits is much
13263                          * larger, up to total of DOUBLEDOUBLE_MAXBITS bits.
13264                          * See the definition of DOUBLEDOUBLE_MAXBITS.
13265                          *
13266                          * Need 2 hexdigits for each byte. */
13267                         (DOUBLEDOUBLE_MAXBITS/8 + 1) * 2;
13268 #else
13269                         NVSIZE * 2; /* 2 hexdigits for each byte */
13270 #endif
13271                     /* see "this can't overflow" comment above */
13272                     assert(float_need < ((STRLEN)~0) - digits);
13273                     float_need += digits;
13274                 }
13275             }
13276             /* special-case "%.<number>g" if it will fit in ebuf */
13277             else if (c == 'g'
13278                 && precis   /* See earlier comment about buggy Gconvert
13279                                when digits, aka precis, is 0  */
13280                 && has_precis
13281                 /* check that "%.<number>g" formatting will fit in ebuf  */
13282                 && sizeof(ebuf) - float_need > precis
13283                 /* sizeof(ebuf) - float_need will have wrapped if float_need > sizeof(ebuf).     *
13284                  * Therefore we should check that float_need < sizeof(ebuf). Normally, we would  *
13285                  * have run this check first, but that triggers incorrect -Wformat-overflow      *
13286                  * compilation warnings with some versions of gcc if Gconvert invokes sprintf(). *
13287                  * ( See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89161 )                   *
13288                  * So, instead, we check it next:                                                */
13289                 && float_need < sizeof(ebuf)
13290                 && !(width || left || plus || alt)
13291                 && !fill
13292                 && intsize != 'q'
13293             ) {
13294                 WITH_LC_NUMERIC_SET_TO_NEEDED_IN(in_lc_numeric,
13295                     SNPRINTF_G(fv, ebuf, sizeof(ebuf), precis)
13296                 );
13297                 elen = strlen(ebuf);
13298                 eptr = ebuf;
13299                 goto float_concat;
13300             }
13301
13302
13303             {
13304                 STRLEN pr = has_precis ? precis : 6; /* known default */
13305                 /* this probably can't wrap, since precis is limited
13306                  * to 1/4 address space size, but better safe than sorry
13307                  */
13308                 if (float_need >= ((STRLEN)~0) - pr)
13309                     croak_memory_wrap();
13310                 float_need += pr;
13311             }
13312
13313             if (float_need < width)
13314                 float_need = width;
13315
13316             if (float_need > INT_MAX) {
13317                 /* snprintf() returns an int, and we use that return value,
13318                    so die horribly if the expected size is too large for int
13319                 */
13320                 Perl_croak(aTHX_ "Numeric format result too large");
13321             }
13322
13323             if (PL_efloatsize <= float_need) {
13324                 /* PL_efloatbuf should be at least 1 greater than
13325                  * float_need to allow a trailing \0 to be returned by
13326                  * snprintf().  If we need to grow, overgrow for the
13327                  * benefit of future generations */
13328                 const STRLEN extra = 0x20;
13329                 if (float_need >= ((STRLEN)~0) - extra)
13330                     croak_memory_wrap();
13331                 float_need += extra;
13332                 Safefree(PL_efloatbuf);
13333                 PL_efloatsize = float_need;
13334                 Newx(PL_efloatbuf, PL_efloatsize, char);
13335                 PL_efloatbuf[0] = '\0';
13336             }
13337
13338             if (UNLIKELY(hexfp)) {
13339                 elen = S_format_hexfp(aTHX_ PL_efloatbuf, PL_efloatsize, c,
13340                                 nv, fv, has_precis, precis, width,
13341                                 alt, plus, left, fill, in_lc_numeric);
13342             }
13343             else {
13344                 char *ptr = ebuf + sizeof ebuf;
13345                 *--ptr = '\0';
13346                 *--ptr = c;
13347 #if defined(USE_QUADMATH)
13348                 /* always use Q here.  my_snprint() throws an exception if we
13349                    fallthrough to the double/long double code, even when the
13350                    format is correct, presumably to avoid any accidentally
13351                    missing Q.
13352                 */
13353                 *--ptr = 'Q';
13354                 /* FIXME: what to do if HAS_LONG_DOUBLE but not PERL_PRIfldbl? */
13355 #elif defined(HAS_LONG_DOUBLE) && defined(PERL_PRIfldbl)
13356                 /* Note that this is HAS_LONG_DOUBLE and PERL_PRIfldbl,
13357                  * not USE_LONG_DOUBLE and NVff.  In other words,
13358                  * this needs to work without USE_LONG_DOUBLE. */
13359                 if (intsize == 'q') {
13360                     /* Copy the one or more characters in a long double
13361                      * format before the 'base' ([efgEFG]) character to
13362                      * the format string. */
13363                     static char const ldblf[] = PERL_PRIfldbl;
13364                     char const *p = ldblf + sizeof(ldblf) - 3;
13365                     while (p >= ldblf) { *--ptr = *p--; }
13366                 }
13367 #endif
13368                 if (has_precis) {
13369                     base = precis;
13370                     do { *--ptr = '0' + (base % 10); } while (base /= 10);
13371                     *--ptr = '.';
13372                 }
13373                 if (width) {
13374                     base = width;
13375                     do { *--ptr = '0' + (base % 10); } while (base /= 10);
13376                 }
13377                 if (fill)
13378                     *--ptr = '0';
13379                 if (left)
13380                     *--ptr = '-';
13381                 if (plus)
13382                     *--ptr = plus;
13383                 if (alt)
13384                     *--ptr = '#';
13385                 *--ptr = '%';
13386
13387                 /* No taint.  Otherwise we are in the strange situation
13388                  * where printf() taints but print($float) doesn't.
13389                  * --jhi */
13390
13391                 /* hopefully the above makes ptr a very constrained format
13392                  * that is safe to use, even though it's not literal */
13393                 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
13394 #ifdef USE_QUADMATH
13395                 {
13396                     if (!quadmath_format_valid(ptr))
13397                         Perl_croak_nocontext("panic: quadmath invalid format \"%s\"", ptr);
13398                     WITH_LC_NUMERIC_SET_TO_NEEDED_IN(in_lc_numeric,
13399                         elen = quadmath_snprintf(PL_efloatbuf, PL_efloatsize,
13400                                                  ptr, nv);
13401                     );
13402                     if ((IV)elen == -1) {
13403                         Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", ptr);
13404                     }
13405                 }
13406 #elif defined(HAS_LONG_DOUBLE)
13407                 WITH_LC_NUMERIC_SET_TO_NEEDED_IN(in_lc_numeric,
13408                     elen = ((intsize == 'q')
13409                             ? my_snprintf(PL_efloatbuf, PL_efloatsize, ptr, fv)
13410                             : my_snprintf(PL_efloatbuf, PL_efloatsize, ptr, (double)fv))
13411                 );
13412 #else
13413                 WITH_LC_NUMERIC_SET_TO_NEEDED_IN(in_lc_numeric,
13414                     elen = my_snprintf(PL_efloatbuf, PL_efloatsize, ptr, fv)
13415                 );
13416 #endif
13417                 GCC_DIAG_RESTORE_STMT;
13418             }
13419
13420             eptr = PL_efloatbuf;
13421
13422           float_concat:
13423
13424             /* Since floating-point formats do their own formatting and
13425              * padding, we skip the main block of code at the end of this
13426              * loop which handles appending eptr to sv, and do our own
13427              * stripped-down version */
13428
13429             assert(!zeros);
13430             assert(!esignlen);
13431             assert(elen);
13432             assert(elen >= width);
13433
13434             S_sv_catpvn_simple(aTHX_ sv, eptr, elen);
13435
13436             goto done_valid_conversion;
13437         }
13438
13439             /* SPECIAL */
13440
13441         case 'n':
13442             {
13443                 STRLEN len;
13444                 /* XXX ideally we should warn if any flags etc have been
13445                  * set, e.g. "%-4.5n" */
13446                 /* XXX if sv was originally non-utf8 with a char in the
13447                  * range 0x80-0xff, then if it got upgraded, we should
13448                  * calculate char len rather than byte len here */
13449                 len = SvCUR(sv) - origlen;
13450                 if (args) {
13451                     int i = (len > PERL_INT_MAX) ? PERL_INT_MAX : (int)len;
13452
13453                     switch (intsize) {
13454                     case 'c':  *(va_arg(*args, char*))      = i; break;
13455                     case 'h':  *(va_arg(*args, short*))     = i; break;
13456                     default:   *(va_arg(*args, int*))       = i; break;
13457                     case 'l':  *(va_arg(*args, long*))      = i; break;
13458                     case 'V':  *(va_arg(*args, IV*))        = i; break;
13459                     case 'z':  *(va_arg(*args, SSize_t*))   = i; break;
13460 #ifdef HAS_PTRDIFF_T
13461                     case 't':  *(va_arg(*args, ptrdiff_t*)) = i; break;
13462 #endif
13463                     case 'j':  *(va_arg(*args, PERL_INTMAX_T*)) = i; break;
13464                     case 'q':
13465 #if IVSIZE >= 8
13466                                *(va_arg(*args, Quad_t*))    = i; break;
13467 #else
13468                                goto unknown;
13469 #endif
13470                     }
13471                 }
13472                 else {
13473                     if (arg_missing)
13474                         Perl_croak_nocontext(
13475                             "Missing argument for %%n in %s",
13476                                 PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn()");
13477                     sv_setuv_mg(argsv, has_utf8
13478                         ? (UV)utf8_length((U8*)SvPVX(sv), (U8*)SvEND(sv))
13479                         : (UV)len);
13480                 }
13481                 goto done_valid_conversion;
13482             }
13483
13484             /* UNKNOWN */
13485
13486         default:
13487       unknown:
13488             if (!args
13489                 && (PL_op->op_type == OP_PRTF || PL_op->op_type == OP_SPRINTF)
13490                 && ckWARN(WARN_PRINTF))
13491             {
13492                 SV * const msg = sv_newmortal();
13493                 Perl_sv_setpvf(aTHX_ msg, "Invalid conversion in %sprintf: ",
13494                           (PL_op->op_type == OP_PRTF) ? "" : "s");
13495                 if (fmtstart < patend) {
13496                     const char * const fmtend = q < patend ? q : patend;
13497                     const char * f;
13498                     sv_catpvs(msg, "\"%");
13499                     for (f = fmtstart; f < fmtend; f++) {
13500                         if (isPRINT(*f)) {
13501                             sv_catpvn_nomg(msg, f, 1);
13502                         } else {
13503                             Perl_sv_catpvf(aTHX_ msg, "\\%03o", (U8) *f);
13504                         }
13505                     }
13506                     sv_catpvs(msg, "\"");
13507                 } else {
13508                     sv_catpvs(msg, "end of string");
13509                 }
13510                 Perl_warner(aTHX_ packWARN(WARN_PRINTF), "%" SVf, SVfARG(msg)); /* yes, this is reentrant */
13511             }
13512
13513             /* mangled format: output the '%', then continue from the
13514              * character following that */
13515             sv_catpvn_nomg(sv, fmtstart-1, 1);
13516             q = fmtstart;
13517             svix = osvix;
13518             /* Any "redundant arg" warning from now onwards will probably
13519              * just be misleading, so don't bother. */
13520             no_redundant_warning = TRUE;
13521             continue;   /* not "break" */
13522         }
13523
13524         if (is_utf8 != has_utf8) {
13525             if (is_utf8) {
13526                 if (SvCUR(sv))
13527                     sv_utf8_upgrade(sv);
13528             }
13529             else {
13530                 const STRLEN old_elen = elen;
13531                 SV * const nsv = newSVpvn_flags(eptr, elen, SVs_TEMP);
13532                 sv_utf8_upgrade(nsv);
13533                 eptr = SvPVX_const(nsv);
13534                 elen = SvCUR(nsv);
13535
13536                 if (width) { /* fudge width (can't fudge elen) */
13537                     width += elen - old_elen;
13538                 }
13539                 is_utf8 = TRUE;
13540             }
13541         }
13542
13543
13544         /* append esignbuf, filler, zeros, eptr and dotstr to sv */
13545
13546         {
13547             STRLEN need, have, gap;
13548             STRLEN i;
13549             char *s;
13550
13551             /* signed value that's wrapped? */
13552             assert(elen  <= ((~(STRLEN)0) >> 1));
13553
13554             /* if zeros is non-zero, then it represents filler between
13555              * elen and precis. So adding elen and zeros together will
13556              * always be <= precis, and the addition can never wrap */
13557             assert(!zeros || (precis > elen && precis - elen == zeros));
13558             have = elen + zeros;
13559
13560             if (have >= (((STRLEN)~0) - esignlen))
13561                 croak_memory_wrap();
13562             have += esignlen;
13563
13564             need = (have > width ? have : width);
13565             gap = need - have;
13566
13567             if (need >= (((STRLEN)~0) - (SvCUR(sv) + 1)))
13568                 croak_memory_wrap();
13569             need += (SvCUR(sv) + 1);
13570
13571             SvGROW(sv, need);
13572
13573             s = SvEND(sv);
13574
13575             if (left) {
13576                 for (i = 0; i < esignlen; i++)
13577                     *s++ = esignbuf[i];
13578                 for (i = zeros; i; i--)
13579                     *s++ = '0';
13580                 Copy(eptr, s, elen, char);
13581                 s += elen;
13582                 for (i = gap; i; i--)
13583                     *s++ = ' ';
13584             }
13585             else {
13586                 if (fill) {
13587                     for (i = 0; i < esignlen; i++)
13588                         *s++ = esignbuf[i];
13589                     assert(!zeros);
13590                     zeros = gap;
13591                 }
13592                 else {
13593                     for (i = gap; i; i--)
13594                         *s++ = ' ';
13595                     for (i = 0; i < esignlen; i++)
13596                         *s++ = esignbuf[i];
13597                 }
13598
13599                 for (i = zeros; i; i--)
13600                     *s++ = '0';
13601                 Copy(eptr, s, elen, char);
13602                 s += elen;
13603             }
13604
13605             *s = '\0';
13606             SvCUR_set(sv, s - SvPVX_const(sv));
13607
13608             if (is_utf8)
13609                 has_utf8 = TRUE;
13610             if (has_utf8)
13611                 SvUTF8_on(sv);
13612         }
13613
13614         if (vectorize && veclen) {
13615             /* we append the vector separator separately since %v isn't
13616              * very common: don't slow down the general case by adding
13617              * dotstrlen to need etc */
13618             sv_catpvn_nomg(sv, dotstr, dotstrlen);
13619             esignlen = 0;
13620             goto vector; /* do next iteration */
13621         }
13622
13623       done_valid_conversion:
13624
13625         if (arg_missing)
13626             S_warn_vcatpvfn_missing_argument(aTHX);
13627     }
13628
13629     /* Now that we've consumed all our printf format arguments (svix)
13630      * do we have things left on the stack that we didn't use?
13631      */
13632     if (!no_redundant_warning && sv_count >= svix + 1 && ckWARN(WARN_REDUNDANT)) {
13633         Perl_warner(aTHX_ packWARN(WARN_REDUNDANT), "Redundant argument in %s",
13634                 PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn()");
13635     }
13636
13637     if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
13638         /* while we shouldn't set the cache, it may have been previously
13639            set in the caller, so clear it */
13640         MAGIC *mg = mg_find(sv, PERL_MAGIC_utf8);
13641         if (mg)
13642             magic_setutf8(sv,mg); /* clear UTF8 cache */
13643     }
13644     SvTAINT(sv);
13645 }
13646
13647 /* =========================================================================
13648
13649 =for apidoc_section $embedding
13650
13651 =cut
13652
13653 All the macros and functions in this section are for the private use of
13654 the main function, perl_clone().
13655
13656 The foo_dup() functions make an exact copy of an existing foo thingy.
13657 During the course of a cloning, a hash table is used to map old addresses
13658 to new addresses.  The table is created and manipulated with the
13659 ptr_table_* functions.
13660
13661  * =========================================================================*/
13662
13663
13664 #if defined(USE_ITHREADS)
13665
13666 /* XXX Remove this so it doesn't have to go thru the macro and return for nothing */
13667 #ifndef GpREFCNT_inc
13668 #  define GpREFCNT_inc(gp)      ((gp) ? (++(gp)->gp_refcnt, (gp)) : (GP*)NULL)
13669 #endif
13670
13671
13672 /* Certain cases in Perl_ss_dup have been merged, by relying on the fact
13673    that currently av_dup, gv_dup and hv_dup are the same as sv_dup.
13674    If this changes, please unmerge ss_dup.
13675    Likewise, sv_dup_inc_multiple() relies on this fact.  */
13676 #define sv_dup_inc_NN(s,t)      SvREFCNT_inc_NN(sv_dup_inc(s,t))
13677 #define av_dup(s,t)     MUTABLE_AV(sv_dup((const SV *)s,t))
13678 #define av_dup_inc(s,t) MUTABLE_AV(sv_dup_inc((const SV *)s,t))
13679 #define hv_dup(s,t)     MUTABLE_HV(sv_dup((const SV *)s,t))
13680 #define hv_dup_inc(s,t) MUTABLE_HV(sv_dup_inc((const SV *)s,t))
13681 #define cv_dup(s,t)     MUTABLE_CV(sv_dup((const SV *)s,t))
13682 #define cv_dup_inc(s,t) MUTABLE_CV(sv_dup_inc((const SV *)s,t))
13683 #define io_dup(s,t)     MUTABLE_IO(sv_dup((const SV *)s,t))
13684 #define io_dup_inc(s,t) MUTABLE_IO(sv_dup_inc((const SV *)s,t))
13685 #define gv_dup(s,t)     MUTABLE_GV(sv_dup((const SV *)s,t))
13686 #define gv_dup_inc(s,t) MUTABLE_GV(sv_dup_inc((const SV *)s,t))
13687 #define SAVEPV(p)       ((p) ? savepv(p) : NULL)
13688 #define SAVEPVN(p,n)    ((p) ? savepvn(p,n) : NULL)
13689
13690 /* clone a parser */
13691
13692 yy_parser *
13693 Perl_parser_dup(pTHX_ const yy_parser *const proto, CLONE_PARAMS *const param)
13694 {
13695     yy_parser *parser;
13696
13697     PERL_ARGS_ASSERT_PARSER_DUP;
13698
13699     if (!proto)
13700         return NULL;
13701
13702     /* look for it in the table first */
13703     parser = (yy_parser *)ptr_table_fetch(PL_ptr_table, proto);
13704     if (parser)
13705         return parser;
13706
13707     /* create anew and remember what it is */
13708     Newxz(parser, 1, yy_parser);
13709     ptr_table_store(PL_ptr_table, proto, parser);
13710
13711     /* XXX eventually, just Copy() most of the parser struct ? */
13712
13713     parser->lex_brackets = proto->lex_brackets;
13714     parser->lex_casemods = proto->lex_casemods;
13715     parser->lex_brackstack = savepvn(proto->lex_brackstack,
13716                     (proto->lex_brackets < 120 ? 120 : proto->lex_brackets));
13717     parser->lex_casestack = savepvn(proto->lex_casestack,
13718                     (proto->lex_casemods < 12 ? 12 : proto->lex_casemods));
13719     parser->lex_defer   = proto->lex_defer;
13720     parser->lex_dojoin  = proto->lex_dojoin;
13721     parser->lex_formbrack = proto->lex_formbrack;
13722     parser->lex_inpat   = proto->lex_inpat;
13723     parser->lex_inwhat  = proto->lex_inwhat;
13724     parser->lex_op      = proto->lex_op;
13725     parser->lex_repl    = sv_dup_inc(proto->lex_repl, param);
13726     parser->lex_starts  = proto->lex_starts;
13727     parser->lex_stuff   = sv_dup_inc(proto->lex_stuff, param);
13728     parser->multi_close = proto->multi_close;
13729     parser->multi_open  = proto->multi_open;
13730     parser->multi_start = proto->multi_start;
13731     parser->multi_end   = proto->multi_end;
13732     parser->preambled   = proto->preambled;
13733     parser->lex_super_state = proto->lex_super_state;
13734     parser->lex_sub_inwhat  = proto->lex_sub_inwhat;
13735     parser->lex_sub_op  = proto->lex_sub_op;
13736     parser->lex_sub_repl= sv_dup_inc(proto->lex_sub_repl, param);
13737     parser->linestr     = sv_dup_inc(proto->linestr, param);
13738     parser->expect      = proto->expect;
13739     parser->copline     = proto->copline;
13740     parser->last_lop_op = proto->last_lop_op;
13741     parser->lex_state   = proto->lex_state;
13742     parser->rsfp        = fp_dup(proto->rsfp, '<', param);
13743     /* rsfp_filters entries have fake IoDIRP() */
13744     parser->rsfp_filters= av_dup_inc(proto->rsfp_filters, param);
13745     parser->in_my       = proto->in_my;
13746     parser->in_my_stash = hv_dup(proto->in_my_stash, param);
13747     parser->error_count = proto->error_count;
13748     parser->sig_elems   = proto->sig_elems;
13749     parser->sig_optelems= proto->sig_optelems;
13750     parser->sig_slurpy  = proto->sig_slurpy;
13751     parser->recheck_utf8_validity = proto->recheck_utf8_validity;
13752
13753     {
13754         char * const ols = SvPVX(proto->linestr);
13755         char * const ls  = SvPVX(parser->linestr);
13756
13757         parser->bufptr      = ls + (proto->bufptr >= ols ?
13758                                     proto->bufptr -  ols : 0);
13759         parser->oldbufptr   = ls + (proto->oldbufptr >= ols ?
13760                                     proto->oldbufptr -  ols : 0);
13761         parser->oldoldbufptr= ls + (proto->oldoldbufptr >= ols ?
13762                                     proto->oldoldbufptr -  ols : 0);
13763         parser->linestart   = ls + (proto->linestart >= ols ?
13764                                     proto->linestart -  ols : 0);
13765         parser->last_uni    = ls + (proto->last_uni >= ols ?
13766                                     proto->last_uni -  ols : 0);
13767         parser->last_lop    = ls + (proto->last_lop >= ols ?
13768                                     proto->last_lop -  ols : 0);
13769
13770         parser->bufend      = ls + SvCUR(parser->linestr);
13771     }
13772
13773     Copy(proto->tokenbuf, parser->tokenbuf, 256, char);
13774
13775
13776     Copy(proto->nextval, parser->nextval, 5, YYSTYPE);
13777     Copy(proto->nexttype, parser->nexttype, 5,  I32);
13778     parser->nexttoke    = proto->nexttoke;
13779
13780     /* XXX should clone saved_curcop here, but we aren't passed
13781      * proto_perl; so do it in perl_clone_using instead */
13782
13783     return parser;
13784 }
13785
13786 /*
13787 =for apidoc_section $io
13788 =for apidoc fp_dup
13789
13790 Duplicate a file handle, returning a pointer to the cloned object.
13791
13792 =cut
13793 */
13794
13795 PerlIO *
13796 Perl_fp_dup(pTHX_ PerlIO *const fp, const char type, CLONE_PARAMS *const param)
13797 {
13798     PerlIO *ret;
13799
13800     PERL_ARGS_ASSERT_FP_DUP;
13801     PERL_UNUSED_ARG(type);
13802
13803     if (!fp)
13804         return (PerlIO*)NULL;
13805
13806     /* look for it in the table first */
13807     ret = (PerlIO*)ptr_table_fetch(PL_ptr_table, fp);
13808     if (ret)
13809         return ret;
13810
13811     /* create anew and remember what it is */
13812 #ifdef __amigaos4__
13813     ret = PerlIO_fdupopen(aTHX_ fp, param, PERLIO_DUP_CLONE|PERLIO_DUP_FD);
13814 #else
13815     ret = PerlIO_fdupopen(aTHX_ fp, param, PERLIO_DUP_CLONE);
13816 #endif
13817     ptr_table_store(PL_ptr_table, fp, ret);
13818     return ret;
13819 }
13820
13821 /*
13822 =for apidoc_section $io
13823 =for apidoc dirp_dup
13824
13825 Duplicate a directory handle, returning a pointer to the cloned object.
13826
13827 =cut
13828 */
13829
13830 DIR *
13831 Perl_dirp_dup(pTHX_ DIR *const dp, CLONE_PARAMS *const param)
13832 {
13833     DIR *ret;
13834
13835 #if defined(HAS_FCHDIR) && defined(HAS_TELLDIR) && defined(HAS_SEEKDIR)
13836     DIR *pwd;
13837     const Direntry_t *dirent;
13838     char smallbuf[256]; /* XXX MAXPATHLEN, surely? */
13839     char *name = NULL;
13840     STRLEN len = 0;
13841     long pos;
13842 #endif
13843
13844     PERL_UNUSED_CONTEXT;
13845     PERL_ARGS_ASSERT_DIRP_DUP;
13846
13847     if (!dp)
13848         return (DIR*)NULL;
13849
13850     /* look for it in the table first */
13851     ret = (DIR*)ptr_table_fetch(PL_ptr_table, dp);
13852     if (ret)
13853         return ret;
13854
13855 #if defined(HAS_FCHDIR) && defined(HAS_TELLDIR) && defined(HAS_SEEKDIR)
13856
13857     PERL_UNUSED_ARG(param);
13858
13859     /* create anew */
13860
13861     /* open the current directory (so we can switch back) */
13862     if (!(pwd = PerlDir_open("."))) return (DIR *)NULL;
13863
13864     /* chdir to our dir handle and open the present working directory */
13865     if (fchdir(my_dirfd(dp)) < 0 || !(ret = PerlDir_open("."))) {
13866         PerlDir_close(pwd);
13867         return (DIR *)NULL;
13868     }
13869     /* Now we should have two dir handles pointing to the same dir. */
13870
13871     /* Be nice to the calling code and chdir back to where we were. */
13872     /* XXX If this fails, then what? */
13873     PERL_UNUSED_RESULT(fchdir(my_dirfd(pwd)));
13874
13875     /* We have no need of the pwd handle any more. */
13876     PerlDir_close(pwd);
13877
13878 #ifdef DIRNAMLEN
13879 # define d_namlen(d) (d)->d_namlen
13880 #else
13881 # define d_namlen(d) strlen((d)->d_name)
13882 #endif
13883     /* Iterate once through dp, to get the file name at the current posi-
13884        tion. Then step back. */
13885     pos = PerlDir_tell(dp);
13886     if ((dirent = PerlDir_read(dp))) {
13887         len = d_namlen(dirent);
13888         if (len > sizeof(dirent->d_name) && sizeof(dirent->d_name) > PTRSIZE) {
13889             /* If the len is somehow magically longer than the
13890              * maximum length of the directory entry, even though
13891              * we could fit it in a buffer, we could not copy it
13892              * from the dirent.  Bail out. */
13893             PerlDir_close(ret);
13894             return (DIR*)NULL;
13895         }
13896         if (len <= sizeof smallbuf) name = smallbuf;
13897         else Newx(name, len, char);
13898         Move(dirent->d_name, name, len, char);
13899     }
13900     PerlDir_seek(dp, pos);
13901
13902     /* Iterate through the new dir handle, till we find a file with the
13903        right name. */
13904     if (!dirent) /* just before the end */
13905         for(;;) {
13906             pos = PerlDir_tell(ret);
13907             if (PerlDir_read(ret)) continue; /* not there yet */
13908             PerlDir_seek(ret, pos); /* step back */
13909             break;
13910         }
13911     else {
13912         const long pos0 = PerlDir_tell(ret);
13913         for(;;) {
13914             pos = PerlDir_tell(ret);
13915             if ((dirent = PerlDir_read(ret))) {
13916                 if (len == (STRLEN)d_namlen(dirent)
13917                     && memEQ(name, dirent->d_name, len)) {
13918                     /* found it */
13919                     PerlDir_seek(ret, pos); /* step back */
13920                     break;
13921                 }
13922                 /* else we are not there yet; keep iterating */
13923             }
13924             else { /* This is not meant to happen. The best we can do is
13925                       reset the iterator to the beginning. */
13926                 PerlDir_seek(ret, pos0);
13927                 break;
13928             }
13929         }
13930     }
13931 #undef d_namlen
13932
13933     if (name && name != smallbuf)
13934         Safefree(name);
13935 #endif
13936
13937 #ifdef WIN32
13938     ret = win32_dirp_dup(dp, param);
13939 #endif
13940
13941     /* pop it in the pointer table */
13942     if (ret)
13943         ptr_table_store(PL_ptr_table, dp, ret);
13944
13945     return ret;
13946 }
13947
13948 /*
13949 =for apidoc_section $GV
13950 =for apidoc gp_dup
13951
13952 Duplicate a typeglob, returning a pointer to the cloned object.
13953
13954 =cut
13955 */
13956
13957 GP *
13958 Perl_gp_dup(pTHX_ GP *const gp, CLONE_PARAMS *const param)
13959 {
13960     GP *ret;
13961
13962     PERL_ARGS_ASSERT_GP_DUP;
13963
13964     if (!gp)
13965         return (GP*)NULL;
13966     /* look for it in the table first */
13967     ret = (GP*)ptr_table_fetch(PL_ptr_table, gp);
13968     if (ret)
13969         return ret;
13970
13971     /* create anew and remember what it is */
13972     Newxz(ret, 1, GP);
13973     ptr_table_store(PL_ptr_table, gp, ret);
13974
13975     /* clone */
13976     /* ret->gp_refcnt must be 0 before any other dups are called. We're relying
13977        on Newxz() to do this for us.  */
13978     ret->gp_sv          = sv_dup_inc(gp->gp_sv, param);
13979     ret->gp_io          = io_dup_inc(gp->gp_io, param);
13980     ret->gp_form        = cv_dup_inc(gp->gp_form, param);
13981     ret->gp_av          = av_dup_inc(gp->gp_av, param);
13982     ret->gp_hv          = hv_dup_inc(gp->gp_hv, param);
13983     ret->gp_egv = gv_dup(gp->gp_egv, param);/* GvEGV is not refcounted */
13984     ret->gp_cv          = cv_dup_inc(gp->gp_cv, param);
13985     ret->gp_cvgen       = gp->gp_cvgen;
13986     ret->gp_line        = gp->gp_line;
13987     ret->gp_file_hek    = hek_dup(gp->gp_file_hek, param);
13988     return ret;
13989 }
13990
13991
13992 /*
13993 =for apidoc_section $magic
13994 =for apidoc mg_dup
13995
13996 Duplicate a chain of magic, returning a pointer to the cloned object.
13997
13998 =cut
13999 */
14000
14001 MAGIC *
14002 Perl_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *const param)
14003 {
14004     MAGIC *mgret = NULL;
14005     MAGIC **mgprev_p = &mgret;
14006
14007     PERL_ARGS_ASSERT_MG_DUP;
14008
14009     for (; mg; mg = mg->mg_moremagic) {
14010         MAGIC *nmg;
14011
14012         if ((param->flags & CLONEf_JOIN_IN)
14013                 && mg->mg_type == PERL_MAGIC_backref)
14014             /* when joining, we let the individual SVs add themselves to
14015              * backref as needed. */
14016             continue;
14017
14018         Newx(nmg, 1, MAGIC);
14019         *mgprev_p = nmg;
14020         mgprev_p = &(nmg->mg_moremagic);
14021
14022         /* There was a comment "XXX copy dynamic vtable?" but as we don't have
14023            dynamic vtables, I'm not sure why Sarathy wrote it. The comment dates
14024            from the original commit adding Perl_mg_dup() - revision 4538.
14025            Similarly there is the annotation "XXX random ptr?" next to the
14026            assignment to nmg->mg_ptr.  */
14027         *nmg = *mg;
14028
14029         /* FIXME for plugins
14030         if (nmg->mg_type == PERL_MAGIC_qr) {
14031             nmg->mg_obj = MUTABLE_SV(CALLREGDUPE((REGEXP*)nmg->mg_obj, param));
14032         }
14033         else
14034         */
14035         nmg->mg_obj = (nmg->mg_flags & MGf_REFCOUNTED)
14036                           ? nmg->mg_type == PERL_MAGIC_backref
14037                                 /* The backref AV has its reference
14038                                  * count deliberately bumped by 1 */
14039                                 ? SvREFCNT_inc(av_dup_inc((const AV *)
14040                                                     nmg->mg_obj, param))
14041                                 : sv_dup_inc(nmg->mg_obj, param)
14042                           : (nmg->mg_type == PERL_MAGIC_regdatum ||
14043                              nmg->mg_type == PERL_MAGIC_regdata)
14044                                   ? nmg->mg_obj
14045                                   : sv_dup(nmg->mg_obj, param);
14046
14047         if (nmg->mg_ptr && nmg->mg_type != PERL_MAGIC_regex_global) {
14048             if (nmg->mg_len > 0) {
14049                 nmg->mg_ptr     = SAVEPVN(nmg->mg_ptr, nmg->mg_len);
14050                 if (nmg->mg_type == PERL_MAGIC_overload_table &&
14051                         AMT_AMAGIC((AMT*)nmg->mg_ptr))
14052                 {
14053                     AMT * const namtp = (AMT*)nmg->mg_ptr;
14054                     sv_dup_inc_multiple((SV**)(namtp->table),
14055                                         (SV**)(namtp->table), NofAMmeth, param);
14056                 }
14057             }
14058             else if (nmg->mg_len == HEf_SVKEY)
14059                 nmg->mg_ptr = (char*)sv_dup_inc((const SV *)nmg->mg_ptr, param);
14060         }
14061         if ((nmg->mg_flags & MGf_DUP) && nmg->mg_virtual && nmg->mg_virtual->svt_dup) {
14062             nmg->mg_virtual->svt_dup(aTHX_ nmg, param);
14063         }
14064     }
14065     return mgret;
14066 }
14067
14068 #endif /* USE_ITHREADS */
14069
14070 struct ptr_tbl_arena {
14071     struct ptr_tbl_arena *next;
14072     struct ptr_tbl_ent array[1023/3]; /* as ptr_tbl_ent has 3 pointers.  */
14073 };
14074
14075 /*
14076 =for apidoc ptr_table_new
14077
14078 Create a new pointer-mapping table
14079
14080 =cut
14081 */
14082
14083 PTR_TBL_t *
14084 Perl_ptr_table_new(pTHX)
14085 {
14086     PTR_TBL_t *tbl;
14087     PERL_UNUSED_CONTEXT;
14088
14089     Newx(tbl, 1, PTR_TBL_t);
14090     tbl->tbl_max        = 511;
14091     tbl->tbl_items      = 0;
14092     tbl->tbl_arena      = NULL;
14093     tbl->tbl_arena_next = NULL;
14094     tbl->tbl_arena_end  = NULL;
14095     Newxz(tbl->tbl_ary, tbl->tbl_max + 1, PTR_TBL_ENT_t*);
14096     return tbl;
14097 }
14098
14099 #define PTR_TABLE_HASH(ptr) \
14100   ((PTR2UV(ptr) >> 3) ^ (PTR2UV(ptr) >> (3 + 7)) ^ (PTR2UV(ptr) >> (3 + 17)))
14101
14102 /* map an existing pointer using a table */
14103
14104 STATIC PTR_TBL_ENT_t *
14105 S_ptr_table_find(PTR_TBL_t *const tbl, const void *const sv)
14106 {
14107     PTR_TBL_ENT_t *tblent;
14108     const UV hash = PTR_TABLE_HASH(sv);
14109
14110     PERL_ARGS_ASSERT_PTR_TABLE_FIND;
14111
14112     tblent = tbl->tbl_ary[hash & tbl->tbl_max];
14113     for (; tblent; tblent = tblent->next) {
14114         if (tblent->oldval == sv)
14115             return tblent;
14116     }
14117     return NULL;
14118 }
14119
14120 /*
14121 =for apidoc ptr_table_fetch
14122
14123 Look for C<sv> in the pointer-mapping table C<tbl>, returning its value, or
14124 NULL if not found.
14125
14126 =cut
14127 */
14128
14129 void *
14130 Perl_ptr_table_fetch(pTHX_ PTR_TBL_t *const tbl, const void *const sv)
14131 {
14132     PTR_TBL_ENT_t const *const tblent = ptr_table_find(tbl, sv);
14133
14134     PERL_ARGS_ASSERT_PTR_TABLE_FETCH;
14135     PERL_UNUSED_CONTEXT;
14136
14137     return tblent ? tblent->newval : NULL;
14138 }
14139
14140 /*
14141 =for apidoc ptr_table_store
14142
14143 Add a new entry to a pointer-mapping table C<tbl>.
14144 In hash terms, C<oldsv> is the key; Cnewsv> is the value.
14145
14146 The names "old" and "new" are specific to the core's typical use of ptr_tables
14147 in thread cloning.
14148
14149 =cut
14150 */
14151
14152 void
14153 Perl_ptr_table_store(pTHX_ PTR_TBL_t *const tbl, const void *const oldsv, void *const newsv)
14154 {
14155     PTR_TBL_ENT_t *tblent = ptr_table_find(tbl, oldsv);
14156
14157     PERL_ARGS_ASSERT_PTR_TABLE_STORE;
14158     PERL_UNUSED_CONTEXT;
14159
14160     if (tblent) {
14161         tblent->newval = newsv;
14162     } else {
14163         const UV entry = PTR_TABLE_HASH(oldsv) & tbl->tbl_max;
14164
14165         if (tbl->tbl_arena_next == tbl->tbl_arena_end) {
14166             struct ptr_tbl_arena *new_arena;
14167
14168             Newx(new_arena, 1, struct ptr_tbl_arena);
14169             new_arena->next = tbl->tbl_arena;
14170             tbl->tbl_arena = new_arena;
14171             tbl->tbl_arena_next = new_arena->array;
14172             tbl->tbl_arena_end = C_ARRAY_END(new_arena->array);
14173         }
14174
14175         tblent = tbl->tbl_arena_next++;
14176
14177         tblent->oldval = oldsv;
14178         tblent->newval = newsv;
14179         tblent->next = tbl->tbl_ary[entry];
14180         tbl->tbl_ary[entry] = tblent;
14181         tbl->tbl_items++;
14182         if (tblent->next && tbl->tbl_items > tbl->tbl_max)
14183             ptr_table_split(tbl);
14184     }
14185 }
14186
14187 /*
14188 =for apidoc ptr_table_split
14189
14190 Double the hash bucket size of an existing ptr table
14191
14192 =cut
14193 */
14194
14195 void
14196 Perl_ptr_table_split(pTHX_ PTR_TBL_t *const tbl)
14197 {
14198     PTR_TBL_ENT_t **ary = tbl->tbl_ary;
14199     const UV oldsize = tbl->tbl_max + 1;
14200     UV newsize = oldsize * 2;
14201     UV i;
14202
14203     PERL_ARGS_ASSERT_PTR_TABLE_SPLIT;
14204     PERL_UNUSED_CONTEXT;
14205
14206     Renew(ary, newsize, PTR_TBL_ENT_t*);
14207     Zero(&ary[oldsize], newsize-oldsize, PTR_TBL_ENT_t*);
14208     tbl->tbl_max = --newsize;
14209     tbl->tbl_ary = ary;
14210     for (i=0; i < oldsize; i++, ary++) {
14211         PTR_TBL_ENT_t **entp = ary;
14212         PTR_TBL_ENT_t *ent = *ary;
14213         PTR_TBL_ENT_t **curentp;
14214         if (!ent)
14215             continue;
14216         curentp = ary + oldsize;
14217         do {
14218             if ((newsize & PTR_TABLE_HASH(ent->oldval)) != i) {
14219                 *entp = ent->next;
14220                 ent->next = *curentp;
14221                 *curentp = ent;
14222             }
14223             else
14224                 entp = &ent->next;
14225             ent = *entp;
14226         } while (ent);
14227     }
14228 }
14229
14230 /*
14231 =for apidoc ptr_table_free
14232
14233 Clear and free a ptr table
14234
14235 =cut
14236 */
14237
14238 void
14239 Perl_ptr_table_free(pTHX_ PTR_TBL_t *const tbl)
14240 {
14241     struct ptr_tbl_arena *arena;
14242
14243     PERL_UNUSED_CONTEXT;
14244
14245     if (!tbl) {
14246         return;
14247     }
14248
14249     arena = tbl->tbl_arena;
14250
14251     while (arena) {
14252         struct ptr_tbl_arena *next = arena->next;
14253
14254         Safefree(arena);
14255         arena = next;
14256     }
14257
14258     Safefree(tbl->tbl_ary);
14259     Safefree(tbl);
14260 }
14261
14262 #if defined(USE_ITHREADS)
14263
14264 void
14265 Perl_rvpv_dup(pTHX_ SV *const dsv, const SV *const ssv, CLONE_PARAMS *const param)
14266 {
14267     PERL_ARGS_ASSERT_RVPV_DUP;
14268
14269     assert(!isREGEXP(ssv));
14270     if (SvROK(ssv)) {
14271         if (SvWEAKREF(ssv)) {
14272             SvRV_set(dsv, sv_dup(SvRV_const(ssv), param));
14273             if (param->flags & CLONEf_JOIN_IN) {
14274                 /* if joining, we add any back references individually rather
14275                  * than copying the whole backref array */
14276                 Perl_sv_add_backref(aTHX_ SvRV(dsv), dsv);
14277             }
14278         }
14279         else
14280             SvRV_set(dsv, sv_dup_inc(SvRV_const(ssv), param));
14281     }
14282     else if (SvPVX_const(ssv)) {
14283         /* Has something there */
14284         if (SvLEN(ssv)) {
14285             /* Normal PV - clone whole allocated space */
14286             SvPV_set(dsv, SAVEPVN(SvPVX_const(ssv), SvLEN(ssv)-1));
14287             /* ssv may not be that normal, but actually copy on write.
14288                But we are a true, independent SV, so:  */
14289             SvIsCOW_off(dsv);
14290         }
14291         else {
14292             /* Special case - not normally malloced for some reason */
14293             if (isGV_with_GP(ssv)) {
14294                 /* Don't need to do anything here.  */
14295             }
14296             else if ((SvIsCOW_shared_hash(ssv))) {
14297                 /* A "shared" PV - clone it as "shared" PV */
14298                 SvPV_set(dsv,
14299                          HEK_KEY(hek_dup(SvSHARED_HEK_FROM_PV(SvPVX_const(ssv)),
14300                                          param)));
14301             }
14302             else {
14303                 /* Some other special case - random pointer */
14304                 SvPV_set(dsv, (char *) SvPVX_const(ssv));
14305             }
14306         }
14307     }
14308     else {
14309         /* Copy the NULL */
14310         SvPV_set(dsv, NULL);
14311     }
14312 }
14313
14314 /* duplicate a list of SVs. source and dest may point to the same memory.  */
14315 static SV **
14316 S_sv_dup_inc_multiple(pTHX_ SV *const *source, SV **dest,
14317                       SSize_t items, CLONE_PARAMS *const param)
14318 {
14319     PERL_ARGS_ASSERT_SV_DUP_INC_MULTIPLE;
14320
14321     while (items-- > 0) {
14322         *dest++ = sv_dup_inc(*source++, param);
14323     }
14324
14325     return dest;
14326 }
14327
14328 /* duplicate an SV of any type (including AV, HV etc) */
14329
14330 static SV *
14331 S_sv_dup_common(pTHX_ const SV *const ssv, CLONE_PARAMS *const param)
14332 {
14333     SV *dsv;
14334
14335     PERL_ARGS_ASSERT_SV_DUP_COMMON;
14336
14337     if (SvTYPE(ssv) == (svtype)SVTYPEMASK) {
14338 #ifdef DEBUG_LEAKING_SCALARS_ABORT
14339         abort();
14340 #endif
14341         return NULL;
14342     }
14343     /* look for it in the table first */
14344     dsv = MUTABLE_SV(ptr_table_fetch(PL_ptr_table, ssv));
14345     if (dsv)
14346         return dsv;
14347
14348     if(param->flags & CLONEf_JOIN_IN) {
14349         /** We are joining here so we don't want do clone
14350             something that is bad **/
14351         if (SvTYPE(ssv) == SVt_PVHV) {
14352             const HEK * const hvname = HvNAME_HEK(ssv);
14353             if (hvname) {
14354                 /** don't clone stashes if they already exist **/
14355                 dsv = MUTABLE_SV(gv_stashpvn(HEK_KEY(hvname), HEK_LEN(hvname),
14356                                                 HEK_UTF8(hvname) ? SVf_UTF8 : 0));
14357                 ptr_table_store(PL_ptr_table, ssv, dsv);
14358                 return dsv;
14359             }
14360         }
14361         else if (SvTYPE(ssv) == SVt_PVGV && !SvFAKE(ssv)) {
14362             HV *stash = GvSTASH(ssv);
14363             const HEK * hvname;
14364             if (stash && (hvname = HvNAME_HEK(stash))) {
14365                 /** don't clone GVs if they already exist **/
14366                 SV **svp;
14367                 stash = gv_stashpvn(HEK_KEY(hvname), HEK_LEN(hvname),
14368                                     HEK_UTF8(hvname) ? SVf_UTF8 : 0);
14369                 svp = hv_fetch(
14370                         stash, GvNAME(ssv),
14371                         GvNAMEUTF8(ssv)
14372                             ? -GvNAMELEN(ssv)
14373                             :  GvNAMELEN(ssv),
14374                         0
14375                       );
14376                 if (svp && *svp && SvTYPE(*svp) == SVt_PVGV) {
14377                     ptr_table_store(PL_ptr_table, ssv, *svp);
14378                     return *svp;
14379                 }
14380             }
14381         }
14382     }
14383
14384     /* create anew and remember what it is */
14385     new_SV(dsv);
14386
14387 #ifdef DEBUG_LEAKING_SCALARS
14388     dsv->sv_debug_optype = ssv->sv_debug_optype;
14389     dsv->sv_debug_line = ssv->sv_debug_line;
14390     dsv->sv_debug_inpad = ssv->sv_debug_inpad;
14391     dsv->sv_debug_parent = (SV*)ssv;
14392     FREE_SV_DEBUG_FILE(dsv);
14393     dsv->sv_debug_file = savesharedpv(ssv->sv_debug_file);
14394 #endif
14395
14396     ptr_table_store(PL_ptr_table, ssv, dsv);
14397
14398     /* clone */
14399     SvFLAGS(dsv)        = SvFLAGS(ssv);
14400     SvFLAGS(dsv)        &= ~SVf_OOK;            /* don't propagate OOK hack */
14401     SvREFCNT(dsv)       = 0;                    /* must be before any other dups! */
14402
14403 #ifdef DEBUGGING
14404     if (SvANY(ssv) && PL_watch_pvx && SvPVX_const(ssv) == PL_watch_pvx)
14405         PerlIO_printf(Perl_debug_log, "watch at %p hit, found string \"%s\"\n",
14406                       (void*)PL_watch_pvx, SvPVX_const(ssv));
14407 #endif
14408
14409     /* don't clone objects whose class has asked us not to */
14410     if (SvOBJECT(ssv)
14411      && ! (SvFLAGS(SvSTASH(ssv)) & SVphv_CLONEABLE))
14412     {
14413         SvFLAGS(dsv) = 0;
14414         return dsv;
14415     }
14416
14417     switch (SvTYPE(ssv)) {
14418     case SVt_NULL:
14419         SvANY(dsv)      = NULL;
14420         break;
14421     case SVt_IV:
14422         SET_SVANY_FOR_BODYLESS_IV(dsv);
14423         if(SvROK(ssv)) {
14424             Perl_rvpv_dup(aTHX_ dsv, ssv, param);
14425         } else {
14426             SvIV_set(dsv, SvIVX(ssv));
14427         }
14428         break;
14429     case SVt_NV:
14430 #if NVSIZE <= IVSIZE
14431         SET_SVANY_FOR_BODYLESS_NV(dsv);
14432 #else
14433         SvANY(dsv)      = new_XNV();
14434 #endif
14435         SvNV_set(dsv, SvNVX(ssv));
14436         break;
14437     default:
14438         {
14439             /* These are all the types that need complex bodies allocating.  */
14440             void *new_body;
14441             const svtype sv_type = SvTYPE(ssv);
14442             const struct body_details *sv_type_details
14443                 = bodies_by_type + sv_type;
14444
14445             switch (sv_type) {
14446             default:
14447                 Perl_croak(aTHX_ "Bizarre SvTYPE [%" IVdf "]", (IV)SvTYPE(ssv));
14448                 NOT_REACHED; /* NOTREACHED */
14449                 break;
14450
14451             case SVt_PVHV:
14452                 if (HvHasAUX(ssv)) {
14453                     sv_type_details = &fake_hv_with_aux;
14454 #ifdef PURIFY
14455                     new_body = new_NOARENA(sv_type_details);
14456 #else
14457                     new_body_from_arena(new_body, HVAUX_ARENA_ROOT_IX, fake_hv_with_aux);
14458 #endif
14459                     goto have_body;
14460                 }
14461                 /* FALLTHROUGH */
14462             case SVt_PVGV:
14463             case SVt_PVIO:
14464             case SVt_PVFM:
14465             case SVt_PVAV:
14466             case SVt_PVCV:
14467             case SVt_PVLV:
14468             case SVt_REGEXP:
14469             case SVt_PVMG:
14470             case SVt_PVNV:
14471             case SVt_PVIV:
14472             case SVt_INVLIST:
14473             case SVt_PV:
14474                 assert(sv_type_details->body_size);
14475 #ifndef PURIFY
14476                 if (sv_type_details->arena) {
14477                     new_body = S_new_body(aTHX_ sv_type);
14478                     new_body
14479                         = (void*)((char*)new_body - sv_type_details->offset);
14480                 } else
14481 #endif
14482                 {
14483                     new_body = new_NOARENA(sv_type_details);
14484                 }
14485             }
14486         have_body:
14487             assert(new_body);
14488             SvANY(dsv) = new_body;
14489
14490 #ifndef PURIFY
14491             Copy(((char*)SvANY(ssv)) + sv_type_details->offset,
14492                  ((char*)SvANY(dsv)) + sv_type_details->offset,
14493                  sv_type_details->copy, char);
14494 #else
14495             Copy(((char*)SvANY(ssv)),
14496                  ((char*)SvANY(dsv)),
14497                  sv_type_details->body_size + sv_type_details->offset, char);
14498 #endif
14499
14500             if (sv_type != SVt_PVAV && sv_type != SVt_PVHV
14501                 && !isGV_with_GP(dsv)
14502                 && !isREGEXP(dsv)
14503                 && !(sv_type == SVt_PVIO && !(IoFLAGS(dsv) & IOf_FAKE_DIRP)))
14504                 Perl_rvpv_dup(aTHX_ dsv, ssv, param);
14505
14506             /* The Copy above means that all the source (unduplicated) pointers
14507                are now in the destination.  We can check the flags and the
14508                pointers in either, but it's possible that there's less cache
14509                missing by always going for the destination.
14510                FIXME - instrument and check that assumption  */
14511             if (sv_type >= SVt_PVMG) {
14512                 if (SvMAGIC(dsv))
14513                     SvMAGIC_set(dsv, mg_dup(SvMAGIC(dsv), param));
14514                 if (SvOBJECT(dsv) && SvSTASH(dsv))
14515                     SvSTASH_set(dsv, hv_dup_inc(SvSTASH(dsv), param));
14516                 else SvSTASH_set(dsv, 0); /* don't copy DESTROY cache */
14517             }
14518
14519             /* The cast silences a GCC warning about unhandled types.  */
14520             switch ((int)sv_type) {
14521             case SVt_PV:
14522                 break;
14523             case SVt_PVIV:
14524                 break;
14525             case SVt_PVNV:
14526                 break;
14527             case SVt_PVMG:
14528                 break;
14529             case SVt_REGEXP:
14530               duprex:
14531                 /* FIXME for plugins */
14532                 re_dup_guts((REGEXP*) ssv, (REGEXP*) dsv, param);
14533                 break;
14534             case SVt_PVLV:
14535                 /* XXX LvTARGOFF sometimes holds PMOP* when DEBUGGING */
14536                 if (LvTYPE(dsv) == 't') /* for tie: unrefcnted fake (SV**) */
14537                     LvTARG(dsv) = dsv;
14538                 else if (LvTYPE(dsv) == 'T') /* for tie: fake HE */
14539                     LvTARG(dsv) = MUTABLE_SV(he_dup((HE*)LvTARG(dsv), FALSE, param));
14540                 else
14541                     LvTARG(dsv) = sv_dup_inc(LvTARG(dsv), param);
14542                 if (isREGEXP(ssv)) goto duprex;
14543                 /* FALLTHROUGH */
14544             case SVt_PVGV:
14545                 /* non-GP case already handled above */
14546                 if(isGV_with_GP(ssv)) {
14547                     GvNAME_HEK(dsv) = hek_dup(GvNAME_HEK(dsv), param);
14548                     /* Don't call sv_add_backref here as it's going to be
14549                        created as part of the magic cloning of the symbol
14550                        table--unless this is during a join and the stash
14551                        is not actually being cloned.  */
14552                     /* Danger Will Robinson - GvGP(dsv) isn't initialised
14553                        at the point of this comment.  */
14554                     GvSTASH(dsv) = hv_dup(GvSTASH(dsv), param);
14555                     if (param->flags & CLONEf_JOIN_IN)
14556                         Perl_sv_add_backref(aTHX_ MUTABLE_SV(GvSTASH(dsv)), dsv);
14557                     GvGP_set(dsv, gp_dup(GvGP(ssv), param));
14558                     (void)GpREFCNT_inc(GvGP(dsv));
14559                 }
14560                 break;
14561             case SVt_PVIO:
14562                 /* PL_parser->rsfp_filters entries have fake IoDIRP() */
14563                 if(IoFLAGS(dsv) & IOf_FAKE_DIRP) {
14564                     /* I have no idea why fake dirp (rsfps)
14565                        should be treated differently but otherwise
14566                        we end up with leaks -- sky*/
14567                     IoTOP_GV(dsv)      = gv_dup_inc(IoTOP_GV(dsv), param);
14568                     IoFMT_GV(dsv)      = gv_dup_inc(IoFMT_GV(dsv), param);
14569                     IoBOTTOM_GV(dsv)   = gv_dup_inc(IoBOTTOM_GV(dsv), param);
14570                 } else {
14571                     IoTOP_GV(dsv)      = gv_dup(IoTOP_GV(dsv), param);
14572                     IoFMT_GV(dsv)      = gv_dup(IoFMT_GV(dsv), param);
14573                     IoBOTTOM_GV(dsv)   = gv_dup(IoBOTTOM_GV(dsv), param);
14574                     if (IoDIRP(dsv)) {
14575                         IoDIRP(dsv)     = dirp_dup(IoDIRP(dsv), param);
14576                     } else {
14577                         NOOP;
14578                         /* IoDIRP(dsv) is already a copy of IoDIRP(ssv)  */
14579                     }
14580                     IoIFP(dsv)  = fp_dup(IoIFP(ssv), IoTYPE(dsv), param);
14581                 }
14582                 if (IoOFP(dsv) == IoIFP(ssv))
14583                     IoOFP(dsv) = IoIFP(dsv);
14584                 else
14585                     IoOFP(dsv)  = fp_dup(IoOFP(dsv), IoTYPE(dsv), param);
14586                 IoTOP_NAME(dsv) = SAVEPV(IoTOP_NAME(dsv));
14587                 IoFMT_NAME(dsv) = SAVEPV(IoFMT_NAME(dsv));
14588                 IoBOTTOM_NAME(dsv)      = SAVEPV(IoBOTTOM_NAME(dsv));
14589                 break;
14590             case SVt_PVAV:
14591                 /* avoid cloning an empty array */
14592                 if (AvARRAY((const AV *)ssv) && AvFILLp((const AV *)ssv) >= 0) {
14593                     SV **dst_ary, **src_ary;
14594                     SSize_t items = AvFILLp((const AV *)ssv) + 1;
14595
14596                     src_ary = AvARRAY((const AV *)ssv);
14597                     Newx(dst_ary, AvMAX((const AV *)ssv)+1, SV*);
14598                     ptr_table_store(PL_ptr_table, src_ary, dst_ary);
14599                     AvARRAY(MUTABLE_AV(dsv)) = dst_ary;
14600                     AvALLOC((const AV *)dsv) = dst_ary;
14601                     if (AvREAL((const AV *)ssv)) {
14602                         dst_ary = sv_dup_inc_multiple(src_ary, dst_ary, items,
14603                                                       param);
14604                     }
14605                     else {
14606                         while (items-- > 0)
14607                             *dst_ary++ = sv_dup(*src_ary++, param);
14608                     }
14609                     items = AvMAX((const AV *)ssv) - AvFILLp((const AV *)ssv);
14610                     while (items-- > 0) {
14611                         *dst_ary++ = NULL;
14612                     }
14613                 }
14614                 else {
14615                     AvARRAY(MUTABLE_AV(dsv))    = NULL;
14616                     AvALLOC((const AV *)dsv)    = (SV**)NULL;
14617                     AvMAX(  (const AV *)dsv)    = -1;
14618                     AvFILLp((const AV *)dsv)    = -1;
14619                 }
14620                 break;
14621             case SVt_PVHV:
14622                 if (HvARRAY((const HV *)ssv)) {
14623                     STRLEN i = 0;
14624                     XPVHV * const dxhv = (XPVHV*)SvANY(dsv);
14625                     XPVHV * const sxhv = (XPVHV*)SvANY(ssv);
14626                     char *darray;
14627                     Newx(darray, PERL_HV_ARRAY_ALLOC_BYTES(dxhv->xhv_max+1),
14628                         char);
14629                     HvARRAY(dsv) = (HE**)darray;
14630                     while (i <= sxhv->xhv_max) {
14631                         const HE * const source = HvARRAY(ssv)[i];
14632                         HvARRAY(dsv)[i] = source
14633                             ? he_dup(source, FALSE, param) : 0;
14634                         ++i;
14635                     }
14636                     if (HvHasAUX(ssv)) {
14637                         const struct xpvhv_aux * const saux = HvAUX(ssv);
14638                         struct xpvhv_aux * const daux = HvAUX(dsv);
14639                         /* This flag isn't copied.  */
14640                         SvOOK_on(dsv);
14641
14642                         if (saux->xhv_name_count) {
14643                             HEK ** const sname = saux->xhv_name_u.xhvnameu_names;
14644                             const I32 count
14645                              = saux->xhv_name_count < 0
14646                                 ? -saux->xhv_name_count
14647                                 :  saux->xhv_name_count;
14648                             HEK **shekp = sname + count;
14649                             HEK **dhekp;
14650                             Newx(daux->xhv_name_u.xhvnameu_names, count, HEK *);
14651                             dhekp = daux->xhv_name_u.xhvnameu_names + count;
14652                             while (shekp-- > sname) {
14653                                 dhekp--;
14654                                 *dhekp = hek_dup(*shekp, param);
14655                             }
14656                         }
14657                         else {
14658                             daux->xhv_name_u.xhvnameu_name
14659                                 = hek_dup(saux->xhv_name_u.xhvnameu_name,
14660                                           param);
14661                         }
14662                         daux->xhv_name_count = saux->xhv_name_count;
14663
14664                         daux->xhv_aux_flags = saux->xhv_aux_flags;
14665 #ifdef PERL_HASH_RANDOMIZE_KEYS
14666                         daux->xhv_rand = saux->xhv_rand;
14667                         daux->xhv_last_rand = saux->xhv_last_rand;
14668 #endif
14669                         daux->xhv_riter = saux->xhv_riter;
14670                         daux->xhv_eiter = saux->xhv_eiter
14671                             ? he_dup(saux->xhv_eiter, FALSE, param) : 0;
14672                         /* backref array needs refcnt=2; see sv_add_backref */
14673                         daux->xhv_backreferences =
14674                             (param->flags & CLONEf_JOIN_IN)
14675                                 /* when joining, we let the individual GVs and
14676                                  * CVs add themselves to backref as
14677                                  * needed. This avoids pulling in stuff
14678                                  * that isn't required, and simplifies the
14679                                  * case where stashes aren't cloned back
14680                                  * if they already exist in the parent
14681                                  * thread */
14682                             ? NULL
14683                             : saux->xhv_backreferences
14684                                 ? (SvTYPE(saux->xhv_backreferences) == SVt_PVAV)
14685                                     ? MUTABLE_AV(SvREFCNT_inc(
14686                                           sv_dup_inc((const SV *)
14687                                             saux->xhv_backreferences, param)))
14688                                     : MUTABLE_AV(sv_dup((const SV *)
14689                                             saux->xhv_backreferences, param))
14690                                 : 0;
14691
14692                         daux->xhv_mro_meta = saux->xhv_mro_meta
14693                             ? mro_meta_dup(saux->xhv_mro_meta, param)
14694                             : 0;
14695
14696                         /* Record stashes for possible cloning in Perl_clone(). */
14697                         if (HvNAME(ssv))
14698                             av_push(param->stashes, dsv);
14699                     }
14700                 }
14701                 else
14702                     HvARRAY(MUTABLE_HV(dsv)) = NULL;
14703                 break;
14704             case SVt_PVCV:
14705                 if (!(param->flags & CLONEf_COPY_STACKS)) {
14706                     CvDEPTH(dsv) = 0;
14707                 }
14708                 /* FALLTHROUGH */
14709             case SVt_PVFM:
14710                 /* NOTE: not refcounted */
14711                 SvANY(MUTABLE_CV(dsv))->xcv_stash =
14712                     hv_dup(CvSTASH(dsv), param);
14713                 if ((param->flags & CLONEf_JOIN_IN) && CvSTASH(dsv))
14714                     Perl_sv_add_backref(aTHX_ MUTABLE_SV(CvSTASH(dsv)), dsv);
14715                 if (!CvISXSUB(dsv)) {
14716                     OP_REFCNT_LOCK;
14717                     CvROOT(dsv) = OpREFCNT_inc(CvROOT(dsv));
14718                     OP_REFCNT_UNLOCK;
14719                     CvSLABBED_off(dsv);
14720                 } else if (CvCONST(dsv)) {
14721                     CvXSUBANY(dsv).any_ptr =
14722                         sv_dup_inc((const SV *)CvXSUBANY(dsv).any_ptr, param);
14723                 } else if (CvREFCOUNTED_ANYSV(dsv)) {
14724                     CvXSUBANY(dsv).any_sv =
14725                         sv_dup_inc((const SV *)CvXSUBANY(dsv).any_sv, param);
14726                 }
14727                 assert(!CvSLABBED(dsv));
14728                 if (CvDYNFILE(dsv)) CvFILE(dsv) = SAVEPV(CvFILE(dsv));
14729                 if (CvNAMED(dsv))
14730                     SvANY((CV *)dsv)->xcv_gv_u.xcv_hek =
14731                         hek_dup(CvNAME_HEK((CV *)ssv), param);
14732                 /* don't dup if copying back - CvGV isn't refcounted, so the
14733                  * duped GV may never be freed. A bit of a hack! DAPM */
14734                 else
14735                   SvANY(MUTABLE_CV(dsv))->xcv_gv_u.xcv_gv =
14736                     CvCVGV_RC(dsv)
14737                     ? gv_dup_inc(CvGV(ssv), param)
14738                     : (param->flags & CLONEf_JOIN_IN)
14739                         ? NULL
14740                         : gv_dup(CvGV(ssv), param);
14741
14742                 if (!CvISXSUB(ssv)) {
14743                     PADLIST * padlist = CvPADLIST(ssv);
14744                     if(padlist)
14745                         padlist = padlist_dup(padlist, param);
14746                     CvPADLIST_set(dsv, padlist);
14747                 } else
14748 /* unthreaded perl can't sv_dup so we dont support unthreaded's CvHSCXT */
14749                     PoisonPADLIST(dsv);
14750
14751                 CvOUTSIDE(dsv)  =
14752                     CvWEAKOUTSIDE(ssv)
14753                     ? cv_dup(    CvOUTSIDE(dsv), param)
14754                     : cv_dup_inc(CvOUTSIDE(dsv), param);
14755                 break;
14756             }
14757         }
14758     }
14759
14760     return dsv;
14761  }
14762
14763 SV *
14764 Perl_sv_dup_inc(pTHX_ const SV *const ssv, CLONE_PARAMS *const param)
14765 {
14766     PERL_ARGS_ASSERT_SV_DUP_INC;
14767     return ssv ? SvREFCNT_inc(sv_dup_common(ssv, param)) : NULL;
14768 }
14769
14770 SV *
14771 Perl_sv_dup(pTHX_ const SV *const ssv, CLONE_PARAMS *const param)
14772 {
14773     SV *dsv = ssv ? sv_dup_common(ssv, param) : NULL;
14774     PERL_ARGS_ASSERT_SV_DUP;
14775
14776     /* Track every SV that (at least initially) had a reference count of 0.
14777        We need to do this by holding an actual reference to it in this array.
14778        If we attempt to cheat, turn AvREAL_off(), and store only pointers
14779        (akin to the stashes hash, and the perl stack), we come unstuck if
14780        a weak reference (or other SV legitimately SvREFCNT() == 0 for this
14781        thread) is manipulated in a CLONE method, because CLONE runs before the
14782        unreferenced array is walked to find SVs still with SvREFCNT() == 0
14783        (and fix things up by giving each a reference via the temps stack).
14784        Instead, during CLONE, if the 0-referenced SV has SvREFCNT_inc() and
14785        then SvREFCNT_dec(), it will be cleaned up (and added to the free list)
14786        before the walk of unreferenced happens and a reference to that is SV
14787        added to the temps stack. At which point we have the same SV considered
14788        to be in use, and free to be re-used. Not good.
14789     */
14790     if (dsv && !(param->flags & CLONEf_COPY_STACKS) && !SvREFCNT(dsv)) {
14791         assert(param->unreferenced);
14792         av_push(param->unreferenced, SvREFCNT_inc(dsv));
14793     }
14794
14795     return dsv;
14796 }
14797
14798 /* duplicate a context */
14799
14800 PERL_CONTEXT *
14801 Perl_cx_dup(pTHX_ PERL_CONTEXT *cxs, I32 ix, I32 max, CLONE_PARAMS* param)
14802 {
14803     PERL_CONTEXT *ncxs;
14804
14805     PERL_ARGS_ASSERT_CX_DUP;
14806
14807     if (!cxs)
14808         return (PERL_CONTEXT*)NULL;
14809
14810     /* look for it in the table first */
14811     ncxs = (PERL_CONTEXT*)ptr_table_fetch(PL_ptr_table, cxs);
14812     if (ncxs)
14813         return ncxs;
14814
14815     /* create anew and remember what it is */
14816     Newx(ncxs, max + 1, PERL_CONTEXT);
14817     ptr_table_store(PL_ptr_table, cxs, ncxs);
14818     Copy(cxs, ncxs, max + 1, PERL_CONTEXT);
14819
14820     while (ix >= 0) {
14821         PERL_CONTEXT * const ncx = &ncxs[ix];
14822         if (CxTYPE(ncx) == CXt_SUBST) {
14823             Perl_croak(aTHX_ "Cloning substitution context is unimplemented");
14824         }
14825         else {
14826             ncx->blk_oldcop = (COP*)any_dup(ncx->blk_oldcop, param->proto_perl);
14827             switch (CxTYPE(ncx)) {
14828             case CXt_SUB:
14829                 ncx->blk_sub.cv         = cv_dup_inc(ncx->blk_sub.cv, param);
14830                 if(CxHASARGS(ncx)){
14831                     ncx->blk_sub.savearray = av_dup_inc(ncx->blk_sub.savearray,param);
14832                 } else {
14833                     ncx->blk_sub.savearray = NULL;
14834                 }
14835                 ncx->blk_sub.prevcomppad = (PAD*)ptr_table_fetch(PL_ptr_table,
14836                                            ncx->blk_sub.prevcomppad);
14837                 break;
14838             case CXt_EVAL:
14839                 ncx->blk_eval.old_namesv = sv_dup_inc(ncx->blk_eval.old_namesv,
14840                                                       param);
14841                 /* XXX should this sv_dup_inc? Or only if CxEVAL_TXT_REFCNTED ???? */
14842                 ncx->blk_eval.cur_text  = sv_dup(ncx->blk_eval.cur_text, param);
14843                 ncx->blk_eval.cv = cv_dup(ncx->blk_eval.cv, param);
14844                 /* XXX what to do with cur_top_env ???? */
14845                 break;
14846             case CXt_LOOP_LAZYSV:
14847                 ncx->blk_loop.state_u.lazysv.end
14848                     = sv_dup_inc(ncx->blk_loop.state_u.lazysv.end, param);
14849                 /* Fallthrough: duplicate lazysv.cur by using the ary.ary
14850                    duplication code instead.
14851                    We are taking advantage of (1) av_dup_inc and sv_dup_inc
14852                    actually being the same function, and (2) order
14853                    equivalence of the two unions.
14854                    We can assert the later [but only at run time :-(]  */
14855                 assert ((void *) &ncx->blk_loop.state_u.ary.ary ==
14856                         (void *) &ncx->blk_loop.state_u.lazysv.cur);
14857                 /* FALLTHROUGH */
14858             case CXt_LOOP_ARY:
14859                 ncx->blk_loop.state_u.ary.ary
14860                     = av_dup_inc(ncx->blk_loop.state_u.ary.ary, param);
14861                 /* FALLTHROUGH */
14862             case CXt_LOOP_LIST:
14863             case CXt_LOOP_LAZYIV:
14864                 /* code common to all 'for' CXt_LOOP_* types */
14865                 ncx->blk_loop.itersave =
14866                                     sv_dup_inc(ncx->blk_loop.itersave, param);
14867                 if (CxPADLOOP(ncx)) {
14868                     PADOFFSET off = ncx->blk_loop.itervar_u.svp
14869                                     - &CX_CURPAD_SV(ncx->blk_loop, 0);
14870                     ncx->blk_loop.oldcomppad =
14871                                     (PAD*)ptr_table_fetch(PL_ptr_table,
14872                                                 ncx->blk_loop.oldcomppad);
14873                     ncx->blk_loop.itervar_u.svp =
14874                                     &CX_CURPAD_SV(ncx->blk_loop, off);
14875                 }
14876                 else {
14877                     /* this copies the GV if CXp_FOR_GV, or the SV for an
14878                      * alias (for \$x (...)) - relies on gv_dup being the
14879                      * same as sv_dup */
14880                     ncx->blk_loop.itervar_u.gv
14881                         = gv_dup((const GV *)ncx->blk_loop.itervar_u.gv,
14882                                     param);
14883                 }
14884                 break;
14885             case CXt_LOOP_PLAIN:
14886                 break;
14887             case CXt_FORMAT:
14888                 ncx->blk_format.prevcomppad =
14889                         (PAD*)ptr_table_fetch(PL_ptr_table,
14890                                            ncx->blk_format.prevcomppad);
14891                 ncx->blk_format.cv      = cv_dup_inc(ncx->blk_format.cv, param);
14892                 ncx->blk_format.gv      = gv_dup(ncx->blk_format.gv, param);
14893                 ncx->blk_format.dfoutgv = gv_dup_inc(ncx->blk_format.dfoutgv,
14894                                                      param);
14895                 break;
14896             case CXt_GIVEN:
14897                 ncx->blk_givwhen.defsv_save =
14898                                 sv_dup_inc(ncx->blk_givwhen.defsv_save, param);
14899                 break;
14900             case CXt_BLOCK:
14901             case CXt_NULL:
14902             case CXt_WHEN:
14903             case CXt_DEFER:
14904                 break;
14905             }
14906         }
14907         --ix;
14908     }
14909     return ncxs;
14910 }
14911
14912 /*
14913 =for apidoc si_dup
14914
14915 Duplicate a stack info structure, returning a pointer to the cloned object.
14916
14917 =cut
14918 */
14919
14920 PERL_SI *
14921 Perl_si_dup(pTHX_ PERL_SI *si, CLONE_PARAMS* param)
14922 {
14923     PERL_SI *nsi;
14924
14925     PERL_ARGS_ASSERT_SI_DUP;
14926
14927     if (!si)
14928         return (PERL_SI*)NULL;
14929
14930     /* look for it in the table first */
14931     nsi = (PERL_SI*)ptr_table_fetch(PL_ptr_table, si);
14932     if (nsi)
14933         return nsi;
14934
14935     /* create anew and remember what it is */
14936     Newx(nsi, 1, PERL_SI);
14937     ptr_table_store(PL_ptr_table, si, nsi);
14938
14939     nsi->si_stack       = av_dup_inc(si->si_stack, param);
14940     nsi->si_cxix        = si->si_cxix;
14941     nsi->si_cxsubix     = si->si_cxsubix;
14942     nsi->si_cxmax       = si->si_cxmax;
14943     nsi->si_cxstack     = cx_dup(si->si_cxstack, si->si_cxix, si->si_cxmax, param);
14944     nsi->si_type        = si->si_type;
14945     nsi->si_prev        = si_dup(si->si_prev, param);
14946     nsi->si_next        = si_dup(si->si_next, param);
14947     nsi->si_markoff     = si->si_markoff;
14948 #if defined DEBUGGING && !defined DEBUGGING_RE_ONLY
14949     nsi->si_stack_hwm   = 0;
14950 #endif
14951
14952     return nsi;
14953 }
14954
14955 #define POPINT(ss,ix)   ((ss)[--(ix)].any_i32)
14956 #define TOPINT(ss,ix)   ((ss)[ix].any_i32)
14957 #define POPLONG(ss,ix)  ((ss)[--(ix)].any_long)
14958 #define TOPLONG(ss,ix)  ((ss)[ix].any_long)
14959 #define POPIV(ss,ix)    ((ss)[--(ix)].any_iv)
14960 #define TOPIV(ss,ix)    ((ss)[ix].any_iv)
14961 #define POPUV(ss,ix)    ((ss)[--(ix)].any_uv)
14962 #define TOPUV(ss,ix)    ((ss)[ix].any_uv)
14963 #define POPBOOL(ss,ix)  ((ss)[--(ix)].any_bool)
14964 #define TOPBOOL(ss,ix)  ((ss)[ix].any_bool)
14965 #define POPPTR(ss,ix)   ((ss)[--(ix)].any_ptr)
14966 #define TOPPTR(ss,ix)   ((ss)[ix].any_ptr)
14967 #define POPDPTR(ss,ix)  ((ss)[--(ix)].any_dptr)
14968 #define TOPDPTR(ss,ix)  ((ss)[ix].any_dptr)
14969 #define POPDXPTR(ss,ix) ((ss)[--(ix)].any_dxptr)
14970 #define TOPDXPTR(ss,ix) ((ss)[ix].any_dxptr)
14971
14972 /* XXXXX todo */
14973 #define pv_dup_inc(p)   SAVEPV(p)
14974 #define pv_dup(p)       SAVEPV(p)
14975 #define svp_dup_inc(p,pp)       any_dup(p,pp)
14976
14977 /* map any object to the new equivent - either something in the
14978  * ptr table, or something in the interpreter structure
14979  */
14980
14981 void *
14982 Perl_any_dup(pTHX_ void *v, const PerlInterpreter *proto_perl)
14983 {
14984     void *ret;
14985
14986     PERL_ARGS_ASSERT_ANY_DUP;
14987
14988     if (!v)
14989         return (void*)NULL;
14990
14991     /* look for it in the table first */
14992     ret = ptr_table_fetch(PL_ptr_table, v);
14993     if (ret)
14994         return ret;
14995
14996     /* see if it is part of the interpreter structure */
14997     if (v >= (void*)proto_perl && v < (void*)(proto_perl+1))
14998         ret = (void*)(((char*)aTHX) + (((char*)v) - (char*)proto_perl));
14999     else {
15000         ret = v;
15001     }
15002
15003     return ret;
15004 }
15005
15006 /*
15007 =for apidoc ss_dup
15008
15009 Duplicate the save stack, returning a pointer to the cloned object.
15010
15011 =cut
15012 */
15013
15014 ANY *
15015 Perl_ss_dup(pTHX_ PerlInterpreter *proto_perl, CLONE_PARAMS* param)
15016 {
15017     ANY * const ss      = proto_perl->Isavestack;
15018     const I32 max       = proto_perl->Isavestack_max + SS_MAXPUSH;
15019     I32 ix              = proto_perl->Isavestack_ix;
15020     ANY *nss;
15021     const SV *sv;
15022     const GV *gv;
15023     const AV *av;
15024     const HV *hv;
15025     void* ptr;
15026     int intval;
15027     long longval;
15028     GP *gp;
15029     IV iv;
15030     I32 i;
15031     char *c = NULL;
15032     void (*dptr) (void*);
15033     void (*dxptr) (pTHX_ void*);
15034
15035     PERL_ARGS_ASSERT_SS_DUP;
15036
15037     Newx(nss, max, ANY);
15038
15039     while (ix > 0) {
15040         const UV uv = POPUV(ss,ix);
15041         const U8 type = (U8)uv & SAVE_MASK;
15042
15043         TOPUV(nss,ix) = uv;
15044         switch (type) {
15045         case SAVEt_CLEARSV:
15046         case SAVEt_CLEARPADRANGE:
15047             break;
15048         case SAVEt_HELEM:               /* hash element */
15049         case SAVEt_SV:                  /* scalar reference */
15050             sv = (const SV *)POPPTR(ss,ix);
15051             TOPPTR(nss,ix) = SvREFCNT_inc(sv_dup_inc(sv, param));
15052             /* FALLTHROUGH */
15053         case SAVEt_ITEM:                        /* normal string */
15054         case SAVEt_GVSV:                        /* scalar slot in GV */
15055             sv = (const SV *)POPPTR(ss,ix);
15056             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
15057             if (type == SAVEt_SV)
15058                 break;
15059             /* FALLTHROUGH */
15060         case SAVEt_FREESV:
15061         case SAVEt_MORTALIZESV:
15062         case SAVEt_READONLY_OFF:
15063             sv = (const SV *)POPPTR(ss,ix);
15064             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
15065             break;
15066         case SAVEt_FREEPADNAME:
15067             ptr = POPPTR(ss,ix);
15068             TOPPTR(nss,ix) = padname_dup((PADNAME *)ptr, param);
15069             PadnameREFCNT((PADNAME *)TOPPTR(nss,ix))++;
15070             break;
15071         case SAVEt_SHARED_PVREF:                /* char* in shared space */
15072             c = (char*)POPPTR(ss,ix);
15073             TOPPTR(nss,ix) = savesharedpv(c);
15074             ptr = POPPTR(ss,ix);
15075             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
15076             break;
15077         case SAVEt_GENERIC_SVREF:               /* generic sv */
15078         case SAVEt_SVREF:                       /* scalar reference */
15079             sv = (const SV *)POPPTR(ss,ix);
15080             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
15081             if (type == SAVEt_SVREF)
15082                 SvREFCNT_inc_simple_void((SV *)TOPPTR(nss,ix));
15083             ptr = POPPTR(ss,ix);
15084             TOPPTR(nss,ix) = svp_dup_inc((SV**)ptr, proto_perl);/* XXXXX */
15085             break;
15086         case SAVEt_GVSLOT:              /* any slot in GV */
15087             sv = (const SV *)POPPTR(ss,ix);
15088             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
15089             ptr = POPPTR(ss,ix);
15090             TOPPTR(nss,ix) = svp_dup_inc((SV**)ptr, proto_perl);/* XXXXX */
15091             sv = (const SV *)POPPTR(ss,ix);
15092             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
15093             break;
15094         case SAVEt_HV:                          /* hash reference */
15095         case SAVEt_AV:                          /* array reference */
15096             sv = (const SV *) POPPTR(ss,ix);
15097             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
15098             /* FALLTHROUGH */
15099         case SAVEt_COMPPAD:
15100         case SAVEt_NSTAB:
15101             sv = (const SV *) POPPTR(ss,ix);
15102             TOPPTR(nss,ix) = sv_dup(sv, param);
15103             break;
15104         case SAVEt_INT:                         /* int reference */
15105             ptr = POPPTR(ss,ix);
15106             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
15107             intval = (int)POPINT(ss,ix);
15108             TOPINT(nss,ix) = intval;
15109             break;
15110         case SAVEt_LONG:                        /* long reference */
15111             ptr = POPPTR(ss,ix);
15112             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
15113             longval = (long)POPLONG(ss,ix);
15114             TOPLONG(nss,ix) = longval;
15115             break;
15116         case SAVEt_I32:                         /* I32 reference */
15117             ptr = POPPTR(ss,ix);
15118             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
15119             i = POPINT(ss,ix);
15120             TOPINT(nss,ix) = i;
15121             break;
15122         case SAVEt_IV:                          /* IV reference */
15123         case SAVEt_STRLEN:                      /* STRLEN/size_t ref */
15124             ptr = POPPTR(ss,ix);
15125             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
15126             iv = POPIV(ss,ix);
15127             TOPIV(nss,ix) = iv;
15128             break;
15129         case SAVEt_TMPSFLOOR:
15130             iv = POPIV(ss,ix);
15131             TOPIV(nss,ix) = iv;
15132             break;
15133         case SAVEt_HPTR:                        /* HV* reference */
15134         case SAVEt_APTR:                        /* AV* reference */
15135         case SAVEt_SPTR:                        /* SV* reference */
15136             ptr = POPPTR(ss,ix);
15137             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
15138             sv = (const SV *)POPPTR(ss,ix);
15139             TOPPTR(nss,ix) = sv_dup(sv, param);
15140             break;
15141         case SAVEt_VPTR:                        /* random* reference */
15142             ptr = POPPTR(ss,ix);
15143             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
15144             /* FALLTHROUGH */
15145         case SAVEt_STRLEN_SMALL:
15146         case SAVEt_INT_SMALL:
15147         case SAVEt_I32_SMALL:
15148         case SAVEt_I16:                         /* I16 reference */
15149         case SAVEt_I8:                          /* I8 reference */
15150         case SAVEt_BOOL:
15151             ptr = POPPTR(ss,ix);
15152             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
15153             break;
15154         case SAVEt_GENERIC_PVREF:               /* generic char* */
15155         case SAVEt_PPTR:                        /* char* reference */
15156             ptr = POPPTR(ss,ix);
15157             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
15158             c = (char*)POPPTR(ss,ix);
15159             TOPPTR(nss,ix) = pv_dup(c);
15160             break;
15161         case SAVEt_GP:                          /* scalar reference */
15162             gp = (GP*)POPPTR(ss,ix);
15163             TOPPTR(nss,ix) = gp = gp_dup(gp, param);
15164             (void)GpREFCNT_inc(gp);
15165             gv = (const GV *)POPPTR(ss,ix);
15166             TOPPTR(nss,ix) = gv_dup_inc(gv, param);
15167             break;
15168         case SAVEt_FREEOP:
15169             ptr = POPPTR(ss,ix);
15170             if (ptr && (((OP*)ptr)->op_private & OPpREFCOUNTED)) {
15171                 /* these are assumed to be refcounted properly */
15172                 OP *o;
15173                 switch (((OP*)ptr)->op_type) {
15174                 case OP_LEAVESUB:
15175                 case OP_LEAVESUBLV:
15176                 case OP_LEAVEEVAL:
15177                 case OP_LEAVE:
15178                 case OP_SCOPE:
15179                 case OP_LEAVEWRITE:
15180                     TOPPTR(nss,ix) = ptr;
15181                     o = (OP*)ptr;
15182                     OP_REFCNT_LOCK;
15183                     (void) OpREFCNT_inc(o);
15184                     OP_REFCNT_UNLOCK;
15185                     break;
15186                 default:
15187                     TOPPTR(nss,ix) = NULL;
15188                     break;
15189                 }
15190             }
15191             else
15192                 TOPPTR(nss,ix) = NULL;
15193             break;
15194         case SAVEt_FREECOPHH:
15195             ptr = POPPTR(ss,ix);
15196             TOPPTR(nss,ix) = cophh_copy((COPHH *)ptr);
15197             break;
15198         case SAVEt_ADELETE:
15199             av = (const AV *)POPPTR(ss,ix);
15200             TOPPTR(nss,ix) = av_dup_inc(av, param);
15201             i = POPINT(ss,ix);
15202             TOPINT(nss,ix) = i;
15203             break;
15204         case SAVEt_DELETE:
15205             hv = (const HV *)POPPTR(ss,ix);
15206             TOPPTR(nss,ix) = hv_dup_inc(hv, param);
15207             i = POPINT(ss,ix);
15208             TOPINT(nss,ix) = i;
15209             /* FALLTHROUGH */
15210         case SAVEt_FREEPV:
15211             c = (char*)POPPTR(ss,ix);
15212             TOPPTR(nss,ix) = pv_dup_inc(c);
15213             break;
15214         case SAVEt_STACK_POS:           /* Position on Perl stack */
15215             i = POPINT(ss,ix);
15216             TOPINT(nss,ix) = i;
15217             break;
15218         case SAVEt_DESTRUCTOR:
15219             ptr = POPPTR(ss,ix);
15220             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);  /* XXX quite arbitrary */
15221             dptr = POPDPTR(ss,ix);
15222             TOPDPTR(nss,ix) = DPTR2FPTR(void (*)(void*),
15223                                         any_dup(FPTR2DPTR(void *, dptr),
15224                                                 proto_perl));
15225             break;
15226         case SAVEt_DESTRUCTOR_X:
15227             ptr = POPPTR(ss,ix);
15228             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);  /* XXX quite arbitrary */
15229             dxptr = POPDXPTR(ss,ix);
15230             TOPDXPTR(nss,ix) = DPTR2FPTR(void (*)(pTHX_ void*),
15231                                          any_dup(FPTR2DPTR(void *, dxptr),
15232                                                  proto_perl));
15233             break;
15234         case SAVEt_REGCONTEXT:
15235         case SAVEt_ALLOC:
15236             ix -= uv >> SAVE_TIGHT_SHIFT;
15237             break;
15238         case SAVEt_AELEM:               /* array element */
15239             sv = (const SV *)POPPTR(ss,ix);
15240             TOPPTR(nss,ix) = SvREFCNT_inc(sv_dup_inc(sv, param));
15241             iv = POPIV(ss,ix);
15242             TOPIV(nss,ix) = iv;
15243             av = (const AV *)POPPTR(ss,ix);
15244             TOPPTR(nss,ix) = av_dup_inc(av, param);
15245             break;
15246         case SAVEt_OP:
15247             ptr = POPPTR(ss,ix);
15248             TOPPTR(nss,ix) = ptr;
15249             break;
15250         case SAVEt_HINTS_HH:
15251             hv = (const HV *)POPPTR(ss,ix);
15252             TOPPTR(nss,ix) = hv_dup_inc(hv, param);
15253             /* FALLTHROUGH */
15254         case SAVEt_HINTS:
15255             ptr = POPPTR(ss,ix);
15256             ptr = cophh_copy((COPHH*)ptr);
15257             TOPPTR(nss,ix) = ptr;
15258             i = POPINT(ss,ix);
15259             TOPINT(nss,ix) = i;
15260             break;
15261         case SAVEt_PADSV_AND_MORTALIZE:
15262             longval = (long)POPLONG(ss,ix);
15263             TOPLONG(nss,ix) = longval;
15264             ptr = POPPTR(ss,ix);
15265             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
15266             sv = (const SV *)POPPTR(ss,ix);
15267             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
15268             break;
15269         case SAVEt_SET_SVFLAGS:
15270             i = POPINT(ss,ix);
15271             TOPINT(nss,ix) = i;
15272             i = POPINT(ss,ix);
15273             TOPINT(nss,ix) = i;
15274             sv = (const SV *)POPPTR(ss,ix);
15275             TOPPTR(nss,ix) = sv_dup(sv, param);
15276             break;
15277         case SAVEt_COMPILE_WARNINGS:
15278             ptr = POPPTR(ss,ix);
15279             TOPPTR(nss,ix) = DUP_WARNINGS((STRLEN*)ptr);
15280             break;
15281         case SAVEt_PARSER:
15282             ptr = POPPTR(ss,ix);
15283             TOPPTR(nss,ix) = parser_dup((const yy_parser*)ptr, param);
15284             break;
15285         default:
15286             Perl_croak(aTHX_
15287                        "panic: ss_dup inconsistency (%" IVdf ")", (IV) type);
15288         }
15289     }
15290
15291     return nss;
15292 }
15293
15294
15295 /* if sv is a stash, call $class->CLONE_SKIP(), and set the SVphv_CLONEABLE
15296  * flag to the result. This is done for each stash before cloning starts,
15297  * so we know which stashes want their objects cloned */
15298
15299 static void
15300 do_mark_cloneable_stash(pTHX_ SV *const sv)
15301 {
15302     const HEK * const hvname = HvNAME_HEK((const HV *)sv);
15303     if (hvname) {
15304         GV* const cloner = gv_fetchmethod_autoload(MUTABLE_HV(sv), "CLONE_SKIP", 0);
15305         SvFLAGS(sv) |= SVphv_CLONEABLE; /* clone objects by default */
15306         if (cloner && GvCV(cloner)) {
15307             dSP;
15308             UV status;
15309
15310             ENTER;
15311             SAVETMPS;
15312             PUSHMARK(SP);
15313             mXPUSHs(newSVhek(hvname));
15314             PUTBACK;
15315             call_sv(MUTABLE_SV(GvCV(cloner)), G_SCALAR);
15316             SPAGAIN;
15317             status = POPu;
15318             PUTBACK;
15319             FREETMPS;
15320             LEAVE;
15321             if (status)
15322                 SvFLAGS(sv) &= ~SVphv_CLONEABLE;
15323         }
15324     }
15325 }
15326
15327
15328
15329 /*
15330 =for apidoc perl_clone
15331
15332 Create and return a new interpreter by cloning the current one.
15333
15334 C<perl_clone> takes these flags as parameters:
15335
15336 C<CLONEf_COPY_STACKS> - is used to, well, copy the stacks also,
15337 without it we only clone the data and zero the stacks,
15338 with it we copy the stacks and the new perl interpreter is
15339 ready to run at the exact same point as the previous one.
15340 The pseudo-fork code uses C<COPY_STACKS> while the
15341 threads->create doesn't.
15342
15343 C<CLONEf_KEEP_PTR_TABLE> -
15344 C<perl_clone> keeps a ptr_table with the pointer of the old
15345 variable as a key and the new variable as a value,
15346 this allows it to check if something has been cloned and not
15347 clone it again, but rather just use the value and increase the
15348 refcount.
15349 If C<KEEP_PTR_TABLE> is not set then C<perl_clone> will kill the ptr_table
15350 using the function S<C<ptr_table_free(PL_ptr_table); PL_ptr_table = NULL;>>.
15351 A reason to keep it around is if you want to dup some of your own
15352 variables which are outside the graph that perl scans.
15353
15354 C<CLONEf_CLONE_HOST> -
15355 This is a win32 thing, it is ignored on unix, it tells perl's
15356 win32host code (which is c++) to clone itself, this is needed on
15357 win32 if you want to run two threads at the same time,
15358 if you just want to do some stuff in a separate perl interpreter
15359 and then throw it away and return to the original one,
15360 you don't need to do anything.
15361
15362 =cut
15363 */
15364
15365 /* XXX the above needs expanding by someone who actually understands it ! */
15366 EXTERN_C PerlInterpreter *
15367 perl_clone_host(PerlInterpreter* proto_perl, UV flags);
15368
15369 PerlInterpreter *
15370 perl_clone(PerlInterpreter *proto_perl, UV flags)
15371 {
15372 #ifdef PERL_IMPLICIT_SYS
15373
15374     PERL_ARGS_ASSERT_PERL_CLONE;
15375
15376    /* perlhost.h so we need to call into it
15377    to clone the host, CPerlHost should have a c interface, sky */
15378
15379 #ifndef __amigaos4__
15380    if (flags & CLONEf_CLONE_HOST) {
15381        return perl_clone_host(proto_perl,flags);
15382    }
15383 #endif
15384    return perl_clone_using(proto_perl, flags,
15385                             proto_perl->IMem,
15386                             proto_perl->IMemShared,
15387                             proto_perl->IMemParse,
15388                             proto_perl->IEnv,
15389                             proto_perl->IStdIO,
15390                             proto_perl->ILIO,
15391                             proto_perl->IDir,
15392                             proto_perl->ISock,
15393                             proto_perl->IProc);
15394 }
15395
15396 PerlInterpreter *
15397 perl_clone_using(PerlInterpreter *proto_perl, UV flags,
15398                  struct IPerlMem* ipM, struct IPerlMem* ipMS,
15399                  struct IPerlMem* ipMP, struct IPerlEnv* ipE,
15400                  struct IPerlStdIO* ipStd, struct IPerlLIO* ipLIO,
15401                  struct IPerlDir* ipD, struct IPerlSock* ipS,
15402                  struct IPerlProc* ipP)
15403 {
15404     /* XXX many of the string copies here can be optimized if they're
15405      * constants; they need to be allocated as common memory and just
15406      * their pointers copied. */
15407
15408     IV i;
15409     CLONE_PARAMS clone_params;
15410     CLONE_PARAMS* const param = &clone_params;
15411
15412     PerlInterpreter * const my_perl = (PerlInterpreter*)(*ipM->pMalloc)(ipM, sizeof(PerlInterpreter));
15413
15414     PERL_ARGS_ASSERT_PERL_CLONE_USING;
15415 #else           /* !PERL_IMPLICIT_SYS */
15416     IV i;
15417     CLONE_PARAMS clone_params;
15418     CLONE_PARAMS* param = &clone_params;
15419     PerlInterpreter * const my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
15420
15421     PERL_ARGS_ASSERT_PERL_CLONE;
15422 #endif          /* PERL_IMPLICIT_SYS */
15423
15424     /* for each stash, determine whether its objects should be cloned */
15425     S_visit(proto_perl, do_mark_cloneable_stash, SVt_PVHV, SVTYPEMASK);
15426     PERL_SET_THX(my_perl);
15427
15428 #ifdef DEBUGGING
15429     PoisonNew(my_perl, 1, PerlInterpreter);
15430     PL_op = NULL;
15431     PL_curcop = NULL;
15432     PL_defstash = NULL; /* may be used by perl malloc() */
15433     PL_markstack = 0;
15434     PL_scopestack = 0;
15435     PL_scopestack_name = 0;
15436     PL_savestack = 0;
15437     PL_savestack_ix = 0;
15438     PL_savestack_max = -1;
15439     PL_sig_pending = 0;
15440     PL_parser = NULL;
15441     PL_eval_begin_nest_depth = proto_perl->Ieval_begin_nest_depth;
15442     Zero(&PL_debug_pad, 1, struct perl_debug_pad);
15443     Zero(&PL_padname_undef, 1, PADNAME);
15444     Zero(&PL_padname_const, 1, PADNAME);
15445 #  ifdef DEBUG_LEAKING_SCALARS
15446     PL_sv_serial = (((UV)my_perl >> 2) & 0xfff) * 1000000;
15447 #  endif
15448 #  ifdef PERL_TRACE_OPS
15449     Zero(PL_op_exec_cnt, OP_max+2, UV);
15450 #  endif
15451 #else   /* !DEBUGGING */
15452     Zero(my_perl, 1, PerlInterpreter);
15453 #endif  /* DEBUGGING */
15454
15455 #ifdef PERL_IMPLICIT_SYS
15456     /* host pointers */
15457     PL_Mem              = ipM;
15458     PL_MemShared        = ipMS;
15459     PL_MemParse         = ipMP;
15460     PL_Env              = ipE;
15461     PL_StdIO            = ipStd;
15462     PL_LIO              = ipLIO;
15463     PL_Dir              = ipD;
15464     PL_Sock             = ipS;
15465     PL_Proc             = ipP;
15466 #endif          /* PERL_IMPLICIT_SYS */
15467
15468
15469     param->flags = flags;
15470     /* Nothing in the core code uses this, but we make it available to
15471        extensions (using mg_dup).  */
15472     param->proto_perl = proto_perl;
15473     /* Likely nothing will use this, but it is initialised to be consistent
15474        with Perl_clone_params_new().  */
15475     param->new_perl = my_perl;
15476     param->unreferenced = NULL;
15477
15478
15479     INIT_TRACK_MEMPOOL(my_perl->Imemory_debug_header, my_perl);
15480
15481     PL_body_arenas = NULL;
15482     Zero(&PL_body_roots, 1, PL_body_roots);
15483
15484     PL_sv_count         = 0;
15485     PL_sv_root          = NULL;
15486     PL_sv_arenaroot     = NULL;
15487
15488     PL_debug            = proto_perl->Idebug;
15489
15490     /* dbargs array probably holds garbage */
15491     PL_dbargs           = NULL;
15492
15493     PL_compiling = proto_perl->Icompiling;
15494
15495     /* pseudo environmental stuff */
15496     PL_origargc         = proto_perl->Iorigargc;
15497     PL_origargv         = proto_perl->Iorigargv;
15498
15499 #ifndef NO_TAINT_SUPPORT
15500     /* Set tainting stuff before PerlIO_debug can possibly get called */
15501     PL_tainting         = proto_perl->Itainting;
15502     PL_taint_warn       = proto_perl->Itaint_warn;
15503 #else
15504     PL_tainting         = FALSE;
15505     PL_taint_warn       = FALSE;
15506 #endif
15507
15508     PL_minus_c          = proto_perl->Iminus_c;
15509
15510     PL_localpatches     = proto_perl->Ilocalpatches;
15511     PL_splitstr         = proto_perl->Isplitstr;
15512     PL_minus_n          = proto_perl->Iminus_n;
15513     PL_minus_p          = proto_perl->Iminus_p;
15514     PL_minus_l          = proto_perl->Iminus_l;
15515     PL_minus_a          = proto_perl->Iminus_a;
15516     PL_minus_E          = proto_perl->Iminus_E;
15517     PL_minus_F          = proto_perl->Iminus_F;
15518     PL_doswitches       = proto_perl->Idoswitches;
15519     PL_dowarn           = proto_perl->Idowarn;
15520 #ifdef PERL_SAWAMPERSAND
15521     PL_sawampersand     = proto_perl->Isawampersand;
15522 #endif
15523     PL_unsafe           = proto_perl->Iunsafe;
15524     PL_perldb           = proto_perl->Iperldb;
15525     PL_perl_destruct_level = proto_perl->Iperl_destruct_level;
15526     PL_exit_flags       = proto_perl->Iexit_flags;
15527
15528     /* XXX time(&PL_basetime) when asked for? */
15529     PL_basetime         = proto_perl->Ibasetime;
15530
15531     PL_maxsysfd         = proto_perl->Imaxsysfd;
15532     PL_statusvalue      = proto_perl->Istatusvalue;
15533 #ifdef __VMS
15534     PL_statusvalue_vms  = proto_perl->Istatusvalue_vms;
15535 #else
15536     PL_statusvalue_posix = proto_perl->Istatusvalue_posix;
15537 #endif
15538
15539     /* RE engine related */
15540     PL_regmatch_slab    = NULL;
15541     PL_reg_curpm        = NULL;
15542
15543     PL_sub_generation   = proto_perl->Isub_generation;
15544
15545     /* funky return mechanisms */
15546     PL_forkprocess      = proto_perl->Iforkprocess;
15547
15548     /* internal state */
15549     PL_main_start       = proto_perl->Imain_start;
15550     PL_eval_root        = proto_perl->Ieval_root;
15551     PL_eval_start       = proto_perl->Ieval_start;
15552
15553     PL_filemode         = proto_perl->Ifilemode;
15554     PL_lastfd           = proto_perl->Ilastfd;
15555     PL_oldname          = proto_perl->Ioldname;         /* XXX not quite right */
15556     PL_gensym           = proto_perl->Igensym;
15557
15558     PL_laststatval      = proto_perl->Ilaststatval;
15559     PL_laststype        = proto_perl->Ilaststype;
15560     PL_mess_sv          = NULL;
15561
15562     PL_profiledata      = NULL;
15563
15564     PL_generation       = proto_perl->Igeneration;
15565
15566     PL_in_clean_objs    = proto_perl->Iin_clean_objs;
15567     PL_in_clean_all     = proto_perl->Iin_clean_all;
15568
15569     PL_delaymagic_uid   = proto_perl->Idelaymagic_uid;
15570     PL_delaymagic_euid  = proto_perl->Idelaymagic_euid;
15571     PL_delaymagic_gid   = proto_perl->Idelaymagic_gid;
15572     PL_delaymagic_egid  = proto_perl->Idelaymagic_egid;
15573     PL_nomemok          = proto_perl->Inomemok;
15574     PL_an               = proto_perl->Ian;
15575     PL_evalseq          = proto_perl->Ievalseq;
15576     PL_origalen         = proto_perl->Iorigalen;
15577
15578     PL_sighandlerp      = proto_perl->Isighandlerp;
15579     PL_sighandler1p     = proto_perl->Isighandler1p;
15580     PL_sighandler3p     = proto_perl->Isighandler3p;
15581
15582     PL_runops           = proto_perl->Irunops;
15583
15584     PL_subline          = proto_perl->Isubline;
15585
15586     PL_cv_has_eval      = proto_perl->Icv_has_eval;
15587
15588 #ifdef USE_LOCALE_COLLATE
15589     PL_collation_ix     = proto_perl->Icollation_ix;
15590     PL_collation_standard = proto_perl->Icollation_standard;
15591     PL_collxfrm_base    = proto_perl->Icollxfrm_base;
15592     PL_collxfrm_mult    = proto_perl->Icollxfrm_mult;
15593     PL_strxfrm_max_cp   = proto_perl->Istrxfrm_max_cp;
15594     PL_strxfrm_is_behaved = proto_perl->Istrxfrm_is_behaved;
15595     PL_strxfrm_NUL_replacement = proto_perl->Istrxfrm_NUL_replacement;
15596 #endif /* USE_LOCALE_COLLATE */
15597
15598 #ifdef USE_LOCALE_NUMERIC
15599     PL_numeric_standard = proto_perl->Inumeric_standard;
15600     PL_numeric_underlying       = proto_perl->Inumeric_underlying;
15601     PL_numeric_underlying_is_standard   = proto_perl->Inumeric_underlying_is_standard;
15602 #endif /* !USE_LOCALE_NUMERIC */
15603
15604     /* Did the locale setup indicate UTF-8? */
15605     PL_utf8locale       = proto_perl->Iutf8locale;
15606
15607 #ifdef USE_LOCALE_THREADS
15608     assert(PL_locale_mutex_depth <= 0);
15609     PL_locale_mutex_depth = 0;
15610 #endif
15611     /* Unicode features (see perlrun/-C) */
15612     PL_unicode          = proto_perl->Iunicode;
15613
15614     /* Pre-5.8 signals control */
15615     PL_signals          = proto_perl->Isignals;
15616
15617     /* times() ticks per second */
15618     PL_clocktick        = proto_perl->Iclocktick;
15619
15620     /* Recursion stopper for PerlIO_find_layer */
15621     PL_in_load_module   = proto_perl->Iin_load_module;
15622
15623     /* Not really needed/useful since the reenrant_retint is "volatile",
15624      * but do it for consistency's sake. */
15625     PL_reentrant_retint = proto_perl->Ireentrant_retint;
15626
15627     /* Hooks to shared SVs and locks. */
15628     PL_sharehook        = proto_perl->Isharehook;
15629     PL_lockhook         = proto_perl->Ilockhook;
15630     PL_unlockhook       = proto_perl->Iunlockhook;
15631     PL_threadhook       = proto_perl->Ithreadhook;
15632     PL_destroyhook      = proto_perl->Idestroyhook;
15633     PL_signalhook       = proto_perl->Isignalhook;
15634
15635     PL_globhook         = proto_perl->Iglobhook;
15636
15637     PL_srand_called     = proto_perl->Isrand_called;
15638     Copy(&(proto_perl->Irandom_state), &PL_random_state, 1, PL_RANDOM_STATE_TYPE);
15639     PL_srand_override   = proto_perl->Isrand_override;
15640     PL_srand_override_next = proto_perl->Isrand_override_next;
15641
15642     if (flags & CLONEf_COPY_STACKS) {
15643         /* next allocation will be PL_tmps_stack[PL_tmps_ix+1] */
15644         PL_tmps_ix              = proto_perl->Itmps_ix;
15645         PL_tmps_max             = proto_perl->Itmps_max;
15646         PL_tmps_floor           = proto_perl->Itmps_floor;
15647
15648         /* next push_scope()/ENTER sets PL_scopestack[PL_scopestack_ix]
15649          * NOTE: unlike the others! */
15650         PL_scopestack_ix        = proto_perl->Iscopestack_ix;
15651         PL_scopestack_max       = proto_perl->Iscopestack_max;
15652
15653         /* next SSPUSHFOO() sets PL_savestack[PL_savestack_ix]
15654          * NOTE: unlike the others! */
15655         PL_savestack_ix         = proto_perl->Isavestack_ix;
15656         PL_savestack_max        = proto_perl->Isavestack_max;
15657     }
15658
15659     PL_start_env        = proto_perl->Istart_env;       /* XXXXXX */
15660     PL_top_env          = &PL_start_env;
15661
15662     PL_op               = proto_perl->Iop;
15663
15664     PL_Sv               = NULL;
15665     PL_Xpv              = (XPV*)NULL;
15666     my_perl->Ina        = proto_perl->Ina;
15667
15668     PL_statcache        = proto_perl->Istatcache;
15669
15670 #ifndef NO_TAINT_SUPPORT
15671     PL_tainted          = proto_perl->Itainted;
15672 #else
15673     PL_tainted          = FALSE;
15674 #endif
15675     PL_curpm            = proto_perl->Icurpm;   /* XXX No PMOP ref count */
15676
15677     PL_chopset          = proto_perl->Ichopset; /* XXX never deallocated */
15678
15679     PL_restartjmpenv    = proto_perl->Irestartjmpenv;
15680     PL_restartop        = proto_perl->Irestartop;
15681     PL_in_eval          = proto_perl->Iin_eval;
15682     PL_delaymagic       = proto_perl->Idelaymagic;
15683     PL_phase            = proto_perl->Iphase;
15684     PL_localizing       = proto_perl->Ilocalizing;
15685
15686     PL_hv_fetch_ent_mh  = NULL;
15687     PL_modcount         = proto_perl->Imodcount;
15688     PL_lastgotoprobe    = NULL;
15689     PL_dumpindent       = proto_perl->Idumpindent;
15690
15691     PL_efloatbuf        = NULL;         /* reinits on demand */
15692     PL_efloatsize       = 0;                    /* reinits on demand */
15693
15694     /* regex stuff */
15695
15696     PL_colorset         = 0;            /* reinits PL_colors[] */
15697     /*PL_colors[6]      = {0,0,0,0,0,0};*/
15698
15699     /* Pluggable optimizer */
15700     PL_peepp            = proto_perl->Ipeepp;
15701     PL_rpeepp           = proto_perl->Irpeepp;
15702     /* op_free() hook */
15703     PL_opfreehook       = proto_perl->Iopfreehook;
15704
15705 #  ifdef PERL_MEM_LOG
15706     Zero(PL_mem_log, sizeof(PL_mem_log), char);
15707 #  endif
15708
15709 #ifdef USE_REENTRANT_API
15710     /* XXX: things like -Dm will segfault here in perlio, but doing
15711      *  PERL_SET_CONTEXT(proto_perl);
15712      * breaks too many other things
15713      */
15714     Perl_reentrant_init(aTHX);
15715 #endif
15716
15717     /* create SV map for pointer relocation */
15718     PL_ptr_table = ptr_table_new();
15719
15720     /* initialize these special pointers as early as possible */
15721     init_constants();
15722     ptr_table_store(PL_ptr_table, &proto_perl->Isv_undef, &PL_sv_undef);
15723     ptr_table_store(PL_ptr_table, &proto_perl->Isv_no, &PL_sv_no);
15724     ptr_table_store(PL_ptr_table, &proto_perl->Isv_zero, &PL_sv_zero);
15725     ptr_table_store(PL_ptr_table, &proto_perl->Isv_yes, &PL_sv_yes);
15726     ptr_table_store(PL_ptr_table, &proto_perl->Ipadname_const,
15727                     &PL_padname_const);
15728
15729     /* create (a non-shared!) shared string table */
15730     PL_strtab           = newHV();
15731     HvSHAREKEYS_off(PL_strtab);
15732     hv_ksplit(PL_strtab, HvTOTALKEYS(proto_perl->Istrtab));
15733     ptr_table_store(PL_ptr_table, proto_perl->Istrtab, PL_strtab);
15734
15735     Zero(PL_sv_consts, SV_CONSTS_COUNT, SV*);
15736
15737     /* This PV will be free'd special way so must set it same way op.c does */
15738     PL_compiling.cop_file    = savesharedpv(PL_compiling.cop_file);
15739     ptr_table_store(PL_ptr_table, proto_perl->Icompiling.cop_file, PL_compiling.cop_file);
15740
15741     ptr_table_store(PL_ptr_table, &proto_perl->Icompiling, &PL_compiling);
15742     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
15743     CopHINTHASH_set(&PL_compiling, cophh_copy(CopHINTHASH_get(&PL_compiling)));
15744     PL_curcop           = (COP*)any_dup(proto_perl->Icurcop, proto_perl);
15745
15746     param->stashes      = newAV();  /* Setup array of objects to call clone on */
15747     /* This makes no difference to the implementation, as it always pushes
15748        and shifts pointers to other SVs without changing their reference
15749        count, with the array becoming empty before it is freed. However, it
15750        makes it conceptually clear what is going on, and will avoid some
15751        work inside av.c, filling slots between AvFILL() and AvMAX() with
15752        &PL_sv_undef, and SvREFCNT_dec()ing those.  */
15753     AvREAL_off(param->stashes);
15754
15755     if (!(flags & CLONEf_COPY_STACKS)) {
15756         param->unreferenced = newAV();
15757     }
15758
15759 #ifdef PERLIO_LAYERS
15760     /* Clone PerlIO tables as soon as we can handle general xx_dup() */
15761     PerlIO_clone(aTHX_ proto_perl, param);
15762 #endif
15763
15764     PL_envgv            = gv_dup_inc(proto_perl->Ienvgv, param);
15765     PL_incgv            = gv_dup_inc(proto_perl->Iincgv, param);
15766     PL_hintgv           = gv_dup_inc(proto_perl->Ihintgv, param);
15767     PL_origfilename     = SAVEPV(proto_perl->Iorigfilename);
15768     PL_xsubfilename     = proto_perl->Ixsubfilename;
15769     PL_diehook          = sv_dup_inc(proto_perl->Idiehook, param);
15770     PL_warnhook         = sv_dup_inc(proto_perl->Iwarnhook, param);
15771
15772     /* switches */
15773     PL_patchlevel       = sv_dup_inc(proto_perl->Ipatchlevel, param);
15774     PL_inplace          = SAVEPV(proto_perl->Iinplace);
15775     PL_e_script         = sv_dup_inc(proto_perl->Ie_script, param);
15776
15777     /* magical thingies */
15778
15779     SvPVCLEAR(PERL_DEBUG_PAD(0));        /* For regex debugging. */
15780     SvPVCLEAR(PERL_DEBUG_PAD(1));        /* ext/re needs these */
15781     SvPVCLEAR(PERL_DEBUG_PAD(2));        /* even without DEBUGGING. */
15782
15783
15784     /* Clone the regex array */
15785     /* ORANGE FIXME for plugins, probably in the SV dup code.
15786        newSViv(PTR2IV(CALLREGDUPE(
15787        INT2PTR(REGEXP *, SvIVX(regex)), param))))
15788     */
15789     PL_regex_padav = av_dup_inc(proto_perl->Iregex_padav, param);
15790     PL_regex_pad = AvARRAY(PL_regex_padav);
15791
15792     PL_stashpadmax      = proto_perl->Istashpadmax;
15793     PL_stashpadix       = proto_perl->Istashpadix ;
15794     Newx(PL_stashpad, PL_stashpadmax, HV *);
15795     {
15796         PADOFFSET o = 0;
15797         for (; o < PL_stashpadmax; ++o)
15798             PL_stashpad[o] = hv_dup(proto_perl->Istashpad[o], param);
15799     }
15800
15801     /* shortcuts to various I/O objects */
15802     PL_ofsgv            = gv_dup_inc(proto_perl->Iofsgv, param);
15803     PL_stdingv          = gv_dup(proto_perl->Istdingv, param);
15804     PL_stderrgv         = gv_dup(proto_perl->Istderrgv, param);
15805     PL_defgv            = gv_dup(proto_perl->Idefgv, param);
15806     PL_argvgv           = gv_dup_inc(proto_perl->Iargvgv, param);
15807     PL_argvoutgv        = gv_dup(proto_perl->Iargvoutgv, param);
15808     PL_argvout_stack    = av_dup_inc(proto_perl->Iargvout_stack, param);
15809
15810     /* shortcuts to regexp stuff */
15811     PL_replgv           = gv_dup_inc(proto_perl->Ireplgv, param);
15812
15813     /* shortcuts to misc objects */
15814     PL_errgv            = gv_dup(proto_perl->Ierrgv, param);
15815
15816     /* shortcuts to debugging objects */
15817     PL_DBgv             = gv_dup_inc(proto_perl->IDBgv, param);
15818     PL_DBline           = gv_dup_inc(proto_perl->IDBline, param);
15819     PL_DBsub            = gv_dup_inc(proto_perl->IDBsub, param);
15820     PL_DBsingle         = sv_dup(proto_perl->IDBsingle, param);
15821     PL_DBtrace          = sv_dup(proto_perl->IDBtrace, param);
15822     PL_DBsignal         = sv_dup(proto_perl->IDBsignal, param);
15823     Copy(proto_perl->IDBcontrol, PL_DBcontrol, DBVARMG_COUNT, IV);
15824
15825     /* symbol tables */
15826     PL_defstash         = hv_dup_inc(proto_perl->Idefstash, param);
15827     PL_curstash         = hv_dup_inc(proto_perl->Icurstash, param);
15828     PL_debstash         = hv_dup(proto_perl->Idebstash, param);
15829     PL_globalstash      = hv_dup(proto_perl->Iglobalstash, param);
15830     PL_curstname        = sv_dup_inc(proto_perl->Icurstname, param);
15831
15832     PL_beginav          = av_dup_inc(proto_perl->Ibeginav, param);
15833     PL_beginav_save     = av_dup_inc(proto_perl->Ibeginav_save, param);
15834     PL_checkav_save     = av_dup_inc(proto_perl->Icheckav_save, param);
15835     PL_unitcheckav      = av_dup_inc(proto_perl->Iunitcheckav, param);
15836     PL_unitcheckav_save = av_dup_inc(proto_perl->Iunitcheckav_save, param);
15837     PL_endav            = av_dup_inc(proto_perl->Iendav, param);
15838     PL_checkav          = av_dup_inc(proto_perl->Icheckav, param);
15839     PL_initav           = av_dup_inc(proto_perl->Iinitav, param);
15840     PL_savebegin        = proto_perl->Isavebegin;
15841
15842     PL_isarev           = hv_dup_inc(proto_perl->Iisarev, param);
15843
15844     /* subprocess state */
15845     PL_fdpid            = av_dup_inc(proto_perl->Ifdpid, param);
15846
15847     if (proto_perl->Iop_mask)
15848         PL_op_mask      = SAVEPVN(proto_perl->Iop_mask, PL_maxo);
15849     else
15850         PL_op_mask      = NULL;
15851     /* PL_asserting        = proto_perl->Iasserting; */
15852
15853     /* current interpreter roots */
15854     PL_main_cv          = cv_dup_inc(proto_perl->Imain_cv, param);
15855     OP_REFCNT_LOCK;
15856     PL_main_root        = OpREFCNT_inc(proto_perl->Imain_root);
15857     OP_REFCNT_UNLOCK;
15858
15859     /* runtime control stuff */
15860     PL_curcopdb         = (COP*)any_dup(proto_perl->Icurcopdb, proto_perl);
15861
15862     PL_preambleav       = av_dup_inc(proto_perl->Ipreambleav, param);
15863
15864     PL_ors_sv           = sv_dup_inc(proto_perl->Iors_sv, param);
15865
15866     /* interpreter atexit processing */
15867     PL_exitlistlen      = proto_perl->Iexitlistlen;
15868     if (PL_exitlistlen) {
15869         Newx(PL_exitlist, PL_exitlistlen, PerlExitListEntry);
15870         Copy(proto_perl->Iexitlist, PL_exitlist, PL_exitlistlen, PerlExitListEntry);
15871     }
15872     else
15873         PL_exitlist     = (PerlExitListEntry*)NULL;
15874
15875     PL_my_cxt_size = proto_perl->Imy_cxt_size;
15876     if (PL_my_cxt_size) {
15877         Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
15878         Copy(proto_perl->Imy_cxt_list, PL_my_cxt_list, PL_my_cxt_size, void *);
15879     }
15880     else {
15881         PL_my_cxt_list  = (void**)NULL;
15882     }
15883     PL_modglobal        = hv_dup_inc(proto_perl->Imodglobal, param);
15884     PL_custom_op_names  = hv_dup_inc(proto_perl->Icustom_op_names,param);
15885     PL_custom_op_descs  = hv_dup_inc(proto_perl->Icustom_op_descs,param);
15886     PL_custom_ops       = hv_dup_inc(proto_perl->Icustom_ops, param);
15887
15888     PL_compcv                   = cv_dup(proto_perl->Icompcv, param);
15889
15890     PAD_CLONE_VARS(proto_perl, param);
15891
15892 #ifdef HAVE_INTERP_INTERN
15893     sys_intern_dup(&proto_perl->Isys_intern, &PL_sys_intern);
15894 #endif
15895
15896     PL_DBcv             = cv_dup(proto_perl->IDBcv, param);
15897
15898 #ifdef PERL_USES_PL_PIDSTATUS
15899     PL_pidstatus        = newHV();                      /* XXX flag for cloning? */
15900 #endif
15901     PL_osname           = SAVEPV(proto_perl->Iosname);
15902     PL_parser           = parser_dup(proto_perl->Iparser, param);
15903
15904     /* XXX this only works if the saved cop has already been cloned */
15905     if (proto_perl->Iparser) {
15906         PL_parser->saved_curcop = (COP*)any_dup(
15907                                     proto_perl->Iparser->saved_curcop,
15908                                     proto_perl);
15909     }
15910
15911     PL_subname          = sv_dup_inc(proto_perl->Isubname, param);
15912
15913 #ifdef USE_PL_CURLOCALES
15914     for (i = 0; i < (int) C_ARRAY_LENGTH(PL_curlocales); i++) {
15915         PL_curlocales[i] = SAVEPV(proto_perl->Icurlocales[i]);
15916     }
15917 #endif
15918 #ifdef USE_LOCALE_CTYPE
15919     Copy(proto_perl->Ifold_locale, PL_fold_locale, 256, U8);
15920     /* Should we warn if uses locale? */
15921     PL_ctype_name       = SAVEPV(proto_perl->Ictype_name);
15922     PL_warn_locale      = sv_dup_inc(proto_perl->Iwarn_locale, param);
15923     PL_utf8locale             = proto_perl->Iutf8locale;
15924     PL_in_utf8_CTYPE_locale   = proto_perl->Iin_utf8_CTYPE_locale;
15925     PL_in_utf8_turkic_locale  = proto_perl->Iin_utf8_turkic_locale;
15926 #endif
15927
15928 #ifdef USE_LOCALE_COLLATE
15929     PL_in_utf8_COLLATE_locale = proto_perl->Iin_utf8_COLLATE_locale;
15930     PL_collation_name   = SAVEPV(proto_perl->Icollation_name);
15931 #endif /* USE_LOCALE_COLLATE */
15932
15933 #ifdef USE_LOCALE_NUMERIC
15934     PL_numeric_name     = SAVEPV(proto_perl->Inumeric_name);
15935     PL_numeric_radix_sv = sv_dup_inc(proto_perl->Inumeric_radix_sv, param);
15936     PL_underlying_radix_sv = sv_dup_inc(proto_perl->Iunderlying_radix_sv, param);
15937
15938 #  if defined(USE_POSIX_2008_LOCALE)
15939     PL_underlying_numeric_obj = NULL;
15940 #  endif
15941 #endif /* !USE_LOCALE_NUMERIC */
15942 #if defined(USE_POSIX_2008_LOCALE)
15943     PL_scratch_locale_obj = NULL;
15944 #endif
15945
15946 #ifdef HAS_MBRLEN
15947     PL_mbrlen_ps = proto_perl->Imbrlen_ps;
15948 #endif
15949 #ifdef HAS_MBRTOWC
15950     PL_mbrtowc_ps = proto_perl->Imbrtowc_ps;
15951 #endif
15952 #ifdef HAS_WCRTOMB
15953     PL_wcrtomb_ps = proto_perl->Iwcrtomb_ps;
15954 #endif
15955
15956     PL_langinfo_buf = NULL;
15957     PL_langinfo_bufsize = 0;
15958
15959     PL_setlocale_buf = NULL;
15960     PL_setlocale_bufsize = 0;
15961
15962     PL_stdize_locale_buf = NULL;
15963     PL_stdize_locale_bufsize = 0;
15964
15965     /* Unicode inversion lists */
15966
15967     PL_AboveLatin1            = sv_dup_inc(proto_perl->IAboveLatin1, param);
15968     PL_Assigned_invlist       = sv_dup_inc(proto_perl->IAssigned_invlist, param);
15969     PL_GCB_invlist            = sv_dup_inc(proto_perl->IGCB_invlist, param);
15970     PL_HasMultiCharFold       = sv_dup_inc(proto_perl->IHasMultiCharFold, param);
15971     PL_InMultiCharFold        = sv_dup_inc(proto_perl->IInMultiCharFold, param);
15972     PL_Latin1                 = sv_dup_inc(proto_perl->ILatin1, param);
15973     PL_LB_invlist             = sv_dup_inc(proto_perl->ILB_invlist, param);
15974     PL_SB_invlist             = sv_dup_inc(proto_perl->ISB_invlist, param);
15975     PL_SCX_invlist            = sv_dup_inc(proto_perl->ISCX_invlist, param);
15976     PL_UpperLatin1            = sv_dup_inc(proto_perl->IUpperLatin1, param);
15977     PL_in_some_fold           = sv_dup_inc(proto_perl->Iin_some_fold, param);
15978     PL_utf8_foldclosures      = sv_dup_inc(proto_perl->Iutf8_foldclosures, param);
15979     PL_utf8_idcont            = sv_dup_inc(proto_perl->Iutf8_idcont, param);
15980     PL_utf8_idstart           = sv_dup_inc(proto_perl->Iutf8_idstart, param);
15981     PL_utf8_perl_idcont       = sv_dup_inc(proto_perl->Iutf8_perl_idcont, param);
15982     PL_utf8_perl_idstart      = sv_dup_inc(proto_perl->Iutf8_perl_idstart, param);
15983     PL_utf8_xidcont           = sv_dup_inc(proto_perl->Iutf8_xidcont, param);
15984     PL_utf8_xidstart          = sv_dup_inc(proto_perl->Iutf8_xidstart, param);
15985     PL_WB_invlist             = sv_dup_inc(proto_perl->IWB_invlist, param);
15986     for (i = 0; i < POSIX_CC_COUNT; i++) {
15987         PL_XPosix_ptrs[i]     = sv_dup_inc(proto_perl->IXPosix_ptrs[i], param);
15988         if (i != CC_CASED_ && i != CC_VERTSPACE_) {
15989             PL_Posix_ptrs[i]  = sv_dup_inc(proto_perl->IPosix_ptrs[i], param);
15990         }
15991     }
15992     PL_Posix_ptrs[CC_CASED_]  = PL_Posix_ptrs[CC_ALPHA_];
15993     PL_Posix_ptrs[CC_VERTSPACE_] = NULL;
15994
15995     PL_utf8_toupper           = sv_dup_inc(proto_perl->Iutf8_toupper, param);
15996     PL_utf8_totitle           = sv_dup_inc(proto_perl->Iutf8_totitle, param);
15997     PL_utf8_tolower           = sv_dup_inc(proto_perl->Iutf8_tolower, param);
15998     PL_utf8_tofold            = sv_dup_inc(proto_perl->Iutf8_tofold, param);
15999     PL_utf8_tosimplefold      = sv_dup_inc(proto_perl->Iutf8_tosimplefold, param);
16000     PL_utf8_charname_begin    = sv_dup_inc(proto_perl->Iutf8_charname_begin, param);
16001     PL_utf8_charname_continue = sv_dup_inc(proto_perl->Iutf8_charname_continue, param);
16002     PL_utf8_mark              = sv_dup_inc(proto_perl->Iutf8_mark, param);
16003     PL_InBitmap               = sv_dup_inc(proto_perl->IInBitmap, param);
16004     PL_CCC_non0_non230        = sv_dup_inc(proto_perl->ICCC_non0_non230, param);
16005     PL_Private_Use            = sv_dup_inc(proto_perl->IPrivate_Use, param);
16006
16007 #if 0
16008     PL_seen_deprecated_macro = hv_dup_inc(proto_perl->Iseen_deprecated_macro, param);
16009 #endif
16010
16011     if (proto_perl->Ipsig_pend) {
16012         Newxz(PL_psig_pend, SIG_SIZE, int);
16013     }
16014     else {
16015         PL_psig_pend    = (int*)NULL;
16016     }
16017
16018     if (proto_perl->Ipsig_name) {
16019         Newx(PL_psig_name, 2 * SIG_SIZE, SV*);
16020         sv_dup_inc_multiple(proto_perl->Ipsig_name, PL_psig_name, 2 * SIG_SIZE,
16021                             param);
16022         PL_psig_ptr = PL_psig_name + SIG_SIZE;
16023     }
16024     else {
16025         PL_psig_ptr     = (SV**)NULL;
16026         PL_psig_name    = (SV**)NULL;
16027     }
16028
16029     if (flags & CLONEf_COPY_STACKS) {
16030         Newx(PL_tmps_stack, PL_tmps_max, SV*);
16031         sv_dup_inc_multiple(proto_perl->Itmps_stack, PL_tmps_stack,
16032                             PL_tmps_ix+1, param);
16033
16034         /* next PUSHMARK() sets *(PL_markstack_ptr+1) */
16035         i = proto_perl->Imarkstack_max - proto_perl->Imarkstack;
16036         Newx(PL_markstack, i, I32);
16037         PL_markstack_max        = PL_markstack + (proto_perl->Imarkstack_max
16038                                                   - proto_perl->Imarkstack);
16039         PL_markstack_ptr        = PL_markstack + (proto_perl->Imarkstack_ptr
16040                                                   - proto_perl->Imarkstack);
16041         Copy(proto_perl->Imarkstack, PL_markstack,
16042              PL_markstack_ptr - PL_markstack + 1, I32);
16043
16044         /* next push_scope()/ENTER sets PL_scopestack[PL_scopestack_ix]
16045          * NOTE: unlike the others! */
16046         Newx(PL_scopestack, PL_scopestack_max, I32);
16047         Copy(proto_perl->Iscopestack, PL_scopestack, PL_scopestack_ix, I32);
16048
16049 #ifdef DEBUGGING
16050         Newx(PL_scopestack_name, PL_scopestack_max, const char *);
16051         Copy(proto_perl->Iscopestack_name, PL_scopestack_name, PL_scopestack_ix, const char *);
16052 #endif
16053         /* reset stack AV to correct length before its duped via
16054          * PL_curstackinfo */
16055         AvFILLp(proto_perl->Icurstack) =
16056                             proto_perl->Istack_sp - proto_perl->Istack_base;
16057
16058         /* NOTE: si_dup() looks at PL_markstack */
16059         PL_curstackinfo         = si_dup(proto_perl->Icurstackinfo, param);
16060
16061         /* PL_curstack          = PL_curstackinfo->si_stack; */
16062         PL_curstack             = av_dup(proto_perl->Icurstack, param);
16063         PL_mainstack            = av_dup(proto_perl->Imainstack, param);
16064
16065         /* next PUSHs() etc. set *(PL_stack_sp+1) */
16066         PL_stack_base           = AvARRAY(PL_curstack);
16067         PL_stack_sp             = PL_stack_base + (proto_perl->Istack_sp
16068                                                    - proto_perl->Istack_base);
16069         PL_stack_max            = PL_stack_base + AvMAX(PL_curstack);
16070
16071         /*Newxz(PL_savestack, PL_savestack_max, ANY);*/
16072         PL_savestack            = ss_dup(proto_perl, param);
16073     }
16074     else {
16075         init_stacks();
16076         ENTER;                  /* perl_destruct() wants to LEAVE; */
16077     }
16078
16079     PL_statgv           = gv_dup(proto_perl->Istatgv, param);
16080     PL_statname         = sv_dup_inc(proto_perl->Istatname, param);
16081
16082     PL_rs               = sv_dup_inc(proto_perl->Irs, param);
16083     PL_last_in_gv       = gv_dup(proto_perl->Ilast_in_gv, param);
16084     PL_defoutgv         = gv_dup_inc(proto_perl->Idefoutgv, param);
16085     PL_toptarget        = sv_dup_inc(proto_perl->Itoptarget, param);
16086     PL_bodytarget       = sv_dup_inc(proto_perl->Ibodytarget, param);
16087     PL_formtarget       = sv_dup(proto_perl->Iformtarget, param);
16088
16089     PL_errors           = sv_dup_inc(proto_perl->Ierrors, param);
16090
16091     PL_sortcop          = (OP*)any_dup(proto_perl->Isortcop, proto_perl);
16092     PL_firstgv          = gv_dup_inc(proto_perl->Ifirstgv, param);
16093     PL_secondgv         = gv_dup_inc(proto_perl->Isecondgv, param);
16094
16095     PL_stashcache       = newHV();
16096
16097     PL_watchaddr        = (char **) ptr_table_fetch(PL_ptr_table,
16098                                             proto_perl->Iwatchaddr);
16099     PL_watchok          = PL_watchaddr ? * PL_watchaddr : NULL;
16100     if (PL_debug && PL_watchaddr) {
16101         PerlIO_printf(Perl_debug_log,
16102           "WATCHING: %" UVxf " cloned as %" UVxf " with value %" UVxf "\n",
16103           PTR2UV(proto_perl->Iwatchaddr), PTR2UV(PL_watchaddr),
16104           PTR2UV(PL_watchok));
16105     }
16106
16107     PL_registered_mros  = hv_dup_inc(proto_perl->Iregistered_mros, param);
16108     PL_blockhooks       = av_dup_inc(proto_perl->Iblockhooks, param);
16109
16110     /* Call the ->CLONE method, if it exists, for each of the stashes
16111        identified by sv_dup() above.
16112     */
16113     while(av_count(param->stashes) != 0) {
16114         HV* const stash = MUTABLE_HV(av_shift(param->stashes));
16115         GV* const cloner = gv_fetchmethod_autoload(stash, "CLONE", 0);
16116         if (cloner && GvCV(cloner)) {
16117             dSP;
16118             ENTER;
16119             SAVETMPS;
16120             PUSHMARK(SP);
16121             mXPUSHs(newSVhek(HvNAME_HEK(stash)));
16122             PUTBACK;
16123             call_sv(MUTABLE_SV(GvCV(cloner)), G_DISCARD);
16124             FREETMPS;
16125             LEAVE;
16126         }
16127     }
16128
16129     if (!(flags & CLONEf_KEEP_PTR_TABLE)) {
16130         ptr_table_free(PL_ptr_table);
16131         PL_ptr_table = NULL;
16132     }
16133
16134     if (!(flags & CLONEf_COPY_STACKS)) {
16135         unreferenced_to_tmp_stack(param->unreferenced);
16136     }
16137
16138     SvREFCNT_dec(param->stashes);
16139
16140     /* orphaned? eg threads->new inside BEGIN or use */
16141     if (PL_compcv && ! SvREFCNT(PL_compcv)) {
16142         SvREFCNT_inc_simple_void(PL_compcv);
16143         SAVEFREESV(PL_compcv);
16144     }
16145
16146     return my_perl;
16147 }
16148
16149 static void
16150 S_unreferenced_to_tmp_stack(pTHX_ AV *const unreferenced)
16151 {
16152     PERL_ARGS_ASSERT_UNREFERENCED_TO_TMP_STACK;
16153
16154     if (AvFILLp(unreferenced) > -1) {
16155         SV **svp = AvARRAY(unreferenced);
16156         SV **const last = svp + AvFILLp(unreferenced);
16157         SSize_t count = 0;
16158
16159         do {
16160             if (SvREFCNT(*svp) == 1)
16161                 ++count;
16162         } while (++svp <= last);
16163
16164         EXTEND_MORTAL(count);
16165         svp = AvARRAY(unreferenced);
16166
16167         do {
16168             if (SvREFCNT(*svp) == 1) {
16169                 /* Our reference is the only one to this SV. This means that
16170                    in this thread, the scalar effectively has a 0 reference.
16171                    That doesn't work (cleanup never happens), so donate our
16172                    reference to it onto the save stack. */
16173                 PL_tmps_stack[++PL_tmps_ix] = *svp;
16174             } else {
16175                 /* As an optimisation, because we are already walking the
16176                    entire array, instead of above doing either
16177                    SvREFCNT_inc(*svp) or *svp = &PL_sv_undef, we can instead
16178                    release our reference to the scalar, so that at the end of
16179                    the array owns zero references to the scalars it happens to
16180                    point to. We are effectively converting the array from
16181                    AvREAL() on to AvREAL() off. This saves the av_clear()
16182                    (triggered by the SvREFCNT_dec(unreferenced) below) from
16183                    walking the array a second time.  */
16184                 SvREFCNT_dec(*svp);
16185             }
16186
16187         } while (++svp <= last);
16188         AvREAL_off(unreferenced);
16189     }
16190     SvREFCNT_dec_NN(unreferenced);
16191 }
16192
16193 void
16194 Perl_clone_params_del(CLONE_PARAMS *param)
16195 {
16196     PerlInterpreter *const was = PERL_GET_THX;
16197     PerlInterpreter *const to = param->new_perl;
16198     dTHXa(to);
16199
16200     PERL_ARGS_ASSERT_CLONE_PARAMS_DEL;
16201
16202     if (was != to) {
16203         PERL_SET_THX(to);
16204     }
16205
16206     SvREFCNT_dec(param->stashes);
16207     if (param->unreferenced)
16208         unreferenced_to_tmp_stack(param->unreferenced);
16209
16210     Safefree(param);
16211
16212     if (was != to) {
16213         PERL_SET_THX(was);
16214     }
16215 }
16216
16217 CLONE_PARAMS *
16218 Perl_clone_params_new(PerlInterpreter *const from, PerlInterpreter *const to)
16219 {
16220     /* Need to play this game, as newAV() can call safesysmalloc(), and that
16221        does a dTHX; to get the context from thread local storage.
16222        FIXME - under PERL_CORE Newx(), Safefree() and friends should expand to
16223        a version that passes in my_perl.  */
16224     PerlInterpreter *const was = PERL_GET_THX;
16225     CLONE_PARAMS *param;
16226
16227     PERL_ARGS_ASSERT_CLONE_PARAMS_NEW;
16228
16229     if (was != to) {
16230         PERL_SET_THX(to);
16231     }
16232
16233     /* Given that we've set the context, we can do this unshared.  */
16234     Newx(param, 1, CLONE_PARAMS);
16235
16236     param->flags = 0;
16237     param->proto_perl = from;
16238     param->new_perl = to;
16239     param->stashes = (AV *)Perl_newSV_type(to, SVt_PVAV);
16240     AvREAL_off(param->stashes);
16241     param->unreferenced = (AV *)Perl_newSV_type(to, SVt_PVAV);
16242
16243     if (was != to) {
16244         PERL_SET_THX(was);
16245     }
16246     return param;
16247 }
16248
16249 #endif /* USE_ITHREADS */
16250
16251 void
16252 Perl_init_constants(pTHX)
16253 {
16254
16255     SvREFCNT(&PL_sv_undef)      = SvREFCNT_IMMORTAL;
16256     SvFLAGS(&PL_sv_undef)       = SVf_READONLY|SVf_PROTECT|SVt_NULL;
16257     SvANY(&PL_sv_undef)         = NULL;
16258
16259     SvANY(&PL_sv_no)            = new_XPVNV();
16260     SvREFCNT(&PL_sv_no)         = SvREFCNT_IMMORTAL;
16261     SvFLAGS(&PL_sv_no)          = SVt_PVNV|SVf_READONLY|SVf_PROTECT
16262                                   |SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
16263                                   |SVp_POK|SVf_POK|SVf_IsCOW|SVppv_STATIC;
16264
16265     SvANY(&PL_sv_yes)           = new_XPVNV();
16266     SvREFCNT(&PL_sv_yes)        = SvREFCNT_IMMORTAL;
16267     SvFLAGS(&PL_sv_yes)         = SVt_PVNV|SVf_READONLY|SVf_PROTECT
16268                                   |SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
16269                                   |SVp_POK|SVf_POK|SVf_IsCOW|SVppv_STATIC;
16270
16271     SvANY(&PL_sv_zero)          = new_XPVNV();
16272     SvREFCNT(&PL_sv_zero)       = SvREFCNT_IMMORTAL;
16273     SvFLAGS(&PL_sv_zero)        = SVt_PVNV|SVf_READONLY|SVf_PROTECT
16274                                   |SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
16275                                   |SVp_POK|SVf_POK
16276                                   |SVs_PADTMP;
16277
16278     SvPV_set(&PL_sv_no, (char*)PL_No);
16279     SvCUR_set(&PL_sv_no, 0);
16280     SvLEN_set(&PL_sv_no, 0);
16281     SvIV_set(&PL_sv_no, 0);
16282     SvNV_set(&PL_sv_no, 0);
16283
16284     SvPV_set(&PL_sv_yes, (char*)PL_Yes);
16285     SvCUR_set(&PL_sv_yes, 1);
16286     SvLEN_set(&PL_sv_yes, 0);
16287     SvIV_set(&PL_sv_yes, 1);
16288     SvNV_set(&PL_sv_yes, 1);
16289
16290     SvPV_set(&PL_sv_zero, (char*)PL_Zero);
16291     SvCUR_set(&PL_sv_zero, 1);
16292     SvLEN_set(&PL_sv_zero, 0);
16293     SvIV_set(&PL_sv_zero, 0);
16294     SvNV_set(&PL_sv_zero, 0);
16295
16296     PadnamePV(&PL_padname_const) = (char *)PL_No;
16297
16298     assert(SvIMMORTAL_INTERP(&PL_sv_yes));
16299     assert(SvIMMORTAL_INTERP(&PL_sv_undef));
16300     assert(SvIMMORTAL_INTERP(&PL_sv_no));
16301     assert(SvIMMORTAL_INTERP(&PL_sv_zero));
16302
16303     assert(SvIMMORTAL(&PL_sv_yes));
16304     assert(SvIMMORTAL(&PL_sv_undef));
16305     assert(SvIMMORTAL(&PL_sv_no));
16306     assert(SvIMMORTAL(&PL_sv_zero));
16307
16308     assert( SvIMMORTAL_TRUE(&PL_sv_yes));
16309     assert(!SvIMMORTAL_TRUE(&PL_sv_undef));
16310     assert(!SvIMMORTAL_TRUE(&PL_sv_no));
16311     assert(!SvIMMORTAL_TRUE(&PL_sv_zero));
16312
16313     assert( SvTRUE_nomg_NN(&PL_sv_yes));
16314     assert(!SvTRUE_nomg_NN(&PL_sv_undef));
16315     assert(!SvTRUE_nomg_NN(&PL_sv_no));
16316     assert(!SvTRUE_nomg_NN(&PL_sv_zero));
16317 }
16318
16319 /*
16320 =for apidoc_section $unicode
16321
16322 =for apidoc sv_recode_to_utf8
16323
16324 C<encoding> is assumed to be an C<Encode> object, on entry the PV
16325 of C<sv> is assumed to be octets in that encoding, and C<sv>
16326 will be converted into Unicode (and UTF-8).
16327
16328 If C<sv> already is UTF-8 (or if it is not C<POK>), or if C<encoding>
16329 is not a reference, nothing is done to C<sv>.  If C<encoding> is not
16330 an C<Encode::XS> Encoding object, bad things will happen.
16331 (See L<encoding> and L<Encode>.)
16332
16333 The PV of C<sv> is returned.
16334
16335 =cut */
16336
16337 char *
16338 Perl_sv_recode_to_utf8(pTHX_ SV *sv, SV *encoding)
16339 {
16340     PERL_ARGS_ASSERT_SV_RECODE_TO_UTF8;
16341
16342     if (SvPOK(sv) && !SvUTF8(sv) && !IN_BYTES && SvROK(encoding)) {
16343         SV *uni;
16344         STRLEN len;
16345         const char *s;
16346         dSP;
16347         SV *nsv = sv;
16348         ENTER;
16349         PUSHSTACK;
16350         SAVETMPS;
16351         if (SvPADTMP(nsv)) {
16352             nsv = sv_newmortal();
16353             SvSetSV_nosteal(nsv, sv);
16354         }
16355         save_re_context();
16356         PUSHMARK(sp);
16357         EXTEND(SP, 3);
16358         PUSHs(encoding);
16359         PUSHs(nsv);
16360 /*
16361   NI-S 2002/07/09
16362   Passing sv_yes is wrong - it needs to be or'ed set of constants
16363   for Encode::XS, while UTf-8 decode (currently) assumes a true value means
16364   remove converted chars from source.
16365
16366   Both will default the value - let them.
16367
16368         XPUSHs(&PL_sv_yes);
16369 */
16370         PUTBACK;
16371         call_method("decode", G_SCALAR);
16372         SPAGAIN;
16373         uni = POPs;
16374         PUTBACK;
16375         s = SvPV_const(uni, len);
16376         if (s != SvPVX_const(sv)) {
16377             SvGROW(sv, len + 1);
16378             Move(s, SvPVX(sv), len + 1, char);
16379             SvCUR_set(sv, len);
16380         }
16381         FREETMPS;
16382         POPSTACK;
16383         LEAVE;
16384         if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
16385             /* clear pos and any utf8 cache */
16386             MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
16387             if (mg)
16388                 mg->mg_len = -1;
16389             if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
16390                 magic_setutf8(sv,mg); /* clear UTF8 cache */
16391         }
16392         SvUTF8_on(sv);
16393         return SvPVX(sv);
16394     }
16395     return SvPOKp(sv) ? SvPVX(sv) : NULL;
16396 }
16397
16398 /*
16399 =for apidoc sv_cat_decode
16400
16401 C<encoding> is assumed to be an C<Encode> object, the PV of C<ssv> is
16402 assumed to be octets in that encoding and decoding the input starts
16403 from the position which S<C<(PV + *offset)>> pointed to.  C<dsv> will be
16404 concatenated with the decoded UTF-8 string from C<ssv>.  Decoding will terminate
16405 when the string C<tstr> appears in decoding output or the input ends on
16406 the PV of C<ssv>.  The value which C<offset> points will be modified
16407 to the last input position on C<ssv>.
16408
16409 Returns TRUE if the terminator was found, else returns FALSE.
16410
16411 =cut */
16412
16413 bool
16414 Perl_sv_cat_decode(pTHX_ SV *dsv, SV *encoding,
16415                    SV *ssv, int *offset, char *tstr, int tlen)
16416 {
16417     bool ret = FALSE;
16418
16419     PERL_ARGS_ASSERT_SV_CAT_DECODE;
16420
16421     if (SvPOK(ssv) && SvPOK(dsv) && SvROK(encoding)) {
16422         SV *offsv;
16423         dSP;
16424         ENTER;
16425         SAVETMPS;
16426         save_re_context();
16427         PUSHMARK(sp);
16428         EXTEND(SP, 6);
16429         PUSHs(encoding);
16430         PUSHs(dsv);
16431         PUSHs(ssv);
16432         offsv = newSViv(*offset);
16433         mPUSHs(offsv);
16434         mPUSHp(tstr, tlen);
16435         PUTBACK;
16436         call_method("cat_decode", G_SCALAR);
16437         SPAGAIN;
16438         ret = SvTRUE(TOPs);
16439         *offset = SvIV(offsv);
16440         PUTBACK;
16441         FREETMPS;
16442         LEAVE;
16443     }
16444     else
16445         Perl_croak(aTHX_ "Invalid argument to sv_cat_decode");
16446     return ret;
16447
16448 }
16449
16450 /* ---------------------------------------------------------------------
16451  *
16452  * support functions for report_uninit()
16453  */
16454
16455 /* the maxiumum size of array or hash where we will scan looking
16456  * for the undefined element that triggered the warning */
16457
16458 #define FUV_MAX_SEARCH_SIZE 1000
16459
16460 /* Look for an entry in the hash whose value has the same SV as val;
16461  * If so, return a mortal copy of the key. */
16462
16463 STATIC SV*
16464 S_find_hash_subscript(pTHX_ const HV *const hv, const SV *const val)
16465 {
16466     HE **array;
16467     I32 i;
16468
16469     PERL_ARGS_ASSERT_FIND_HASH_SUBSCRIPT;
16470
16471     if (!hv || SvMAGICAL(hv) || !HvTOTALKEYS(hv) ||
16472                         (HvTOTALKEYS(hv) > FUV_MAX_SEARCH_SIZE))
16473         return NULL;
16474
16475     if (val == &PL_sv_undef || val == &PL_sv_placeholder)
16476         return NULL;
16477
16478     array = HvARRAY(hv);
16479
16480     for (i=HvMAX(hv); i>=0; i--) {
16481         HE *entry;
16482         for (entry = array[i]; entry; entry = HeNEXT(entry)) {
16483             if (HeVAL(entry) == val)
16484                 return newSVhek_mortal(HeKEY_hek(entry));
16485         }
16486     }
16487     return NULL;
16488 }
16489
16490 /* Look for an entry in the array whose value has the same SV as val;
16491  * If so, return the index, otherwise return -1. */
16492
16493 STATIC SSize_t
16494 S_find_array_subscript(pTHX_ const AV *const av, const SV *const val)
16495 {
16496     PERL_ARGS_ASSERT_FIND_ARRAY_SUBSCRIPT;
16497
16498     if (!av || SvMAGICAL(av) || !AvARRAY(av) ||
16499                         (AvFILLp(av) > FUV_MAX_SEARCH_SIZE))
16500         return -1;
16501
16502     if (val != &PL_sv_undef) {
16503         SV ** const svp = AvARRAY(av);
16504         SSize_t i;
16505
16506         for (i=AvFILLp(av); i>=0; i--)
16507             if (svp[i] == val)
16508                 return i;
16509     }
16510     return -1;
16511 }
16512
16513 /* varname(): return the name of a variable, optionally with a subscript.
16514  * If gv is non-zero, use the name of that global, along with gvtype (one
16515  * of "$", "@", "%"); otherwise use the name of the lexical at pad offset
16516  * targ.  Depending on the value of the subscript_type flag, return:
16517  */
16518
16519 #define FUV_SUBSCRIPT_NONE      1       /* "@foo"          */
16520 #define FUV_SUBSCRIPT_ARRAY     2       /* "$foo[aindex]"  */
16521 #define FUV_SUBSCRIPT_HASH      3       /* "$foo{keyname}" */
16522 #define FUV_SUBSCRIPT_WITHIN    4       /* "within @foo"   */
16523
16524 SV*
16525 Perl_varname(pTHX_ const GV *const gv, const char gvtype, PADOFFSET targ,
16526         const SV *const keyname, SSize_t aindex, int subscript_type)
16527 {
16528
16529     SV * const name = sv_newmortal();
16530     if (gv && isGV(gv)) {
16531         char buffer[2];
16532         buffer[0] = gvtype;
16533         buffer[1] = 0;
16534
16535         /* as gv_fullname4(), but add literal '^' for $^FOO names  */
16536
16537         gv_fullname4(name, gv, buffer, 0);
16538
16539         if ((unsigned int)SvPVX(name)[1] <= 26) {
16540             buffer[0] = '^';
16541             buffer[1] = SvPVX(name)[1] + 'A' - 1;
16542
16543             /* Swap the 1 unprintable control character for the 2 byte pretty
16544                version - ie substr($name, 1, 1) = $buffer; */
16545             sv_insert(name, 1, 1, buffer, 2);
16546         }
16547     }
16548     else {
16549         CV * const cv = gv ? ((CV *)gv) : find_runcv(NULL);
16550         PADNAME *sv;
16551
16552         assert(!cv || SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
16553
16554         if (!cv || !CvPADLIST(cv))
16555             return NULL;
16556         sv = padnamelist_fetch(PadlistNAMES(CvPADLIST(cv)), targ);
16557         sv_setpvn(name, PadnamePV(sv), PadnameLEN(sv));
16558         SvUTF8_on(name);
16559     }
16560
16561     if (subscript_type == FUV_SUBSCRIPT_HASH) {
16562         SV * const sv = newSV_type(SVt_NULL);
16563         STRLEN len;
16564         const char * const pv = SvPV_nomg_const((SV*)keyname, len);
16565
16566         *SvPVX(name) = '$';
16567         Perl_sv_catpvf(aTHX_ name, "{%s}",
16568             pv_pretty(sv, pv, len, 32, NULL, NULL,
16569                     PERL_PV_PRETTY_DUMP | PERL_PV_ESCAPE_UNI_DETECT ));
16570         SvREFCNT_dec_NN(sv);
16571     }
16572     else if (subscript_type == FUV_SUBSCRIPT_ARRAY) {
16573         *SvPVX(name) = '$';
16574         Perl_sv_catpvf(aTHX_ name, "[%" IVdf "]", (IV)aindex);
16575     }
16576     else if (subscript_type == FUV_SUBSCRIPT_WITHIN) {
16577         /* We know that name has no magic, so can use 0 instead of SV_GMAGIC */
16578         Perl_sv_insert_flags(aTHX_ name, 0, 0,  STR_WITH_LEN("within "), 0);
16579     }
16580
16581     return name;
16582 }
16583
16584
16585 /*
16586 =apidoc_section $warning
16587 =for apidoc find_uninit_var
16588
16589 Find the name of the undefined variable (if any) that caused the operator
16590 to issue a "Use of uninitialized value" warning.
16591 If match is true, only return a name if its value matches C<uninit_sv>.
16592 So roughly speaking, if a unary operator (such as C<OP_COS>) generates a
16593 warning, then following the direct child of the op may yield an
16594 C<OP_PADSV> or C<OP_GV> that gives the name of the undefined variable.  On the
16595 other hand, with C<OP_ADD> there are two branches to follow, so we only print
16596 the variable name if we get an exact match.
16597 C<desc_p> points to a string pointer holding the description of the op.
16598 This may be updated if needed.
16599
16600 The name is returned as a mortal SV.
16601
16602 Assumes that C<PL_op> is the OP that originally triggered the error, and that
16603 C<PL_comppad>/C<PL_curpad> points to the currently executing pad.
16604
16605 =cut
16606 */
16607
16608 STATIC SV *
16609 S_find_uninit_var(pTHX_ const OP *const obase, const SV *const uninit_sv,
16610                   bool match, const char **desc_p)
16611 {
16612     SV *sv;
16613     const GV *gv;
16614     const OP *o, *o2, *kid;
16615
16616     PERL_ARGS_ASSERT_FIND_UNINIT_VAR;
16617
16618     if (!obase || (match && (!uninit_sv || uninit_sv == &PL_sv_undef ||
16619                             uninit_sv == &PL_sv_placeholder)))
16620         return NULL;
16621
16622     switch (obase->op_type) {
16623
16624     case OP_UNDEF:
16625         /* undef should care if its args are undef - any warnings
16626          * will be from tied/magic vars */
16627         break;
16628
16629     case OP_RV2AV:
16630     case OP_RV2HV:
16631     case OP_PADAV:
16632     case OP_PADHV:
16633       {
16634         const bool pad  = (    obase->op_type == OP_PADAV
16635                             || obase->op_type == OP_PADHV
16636                             || obase->op_type == OP_PADRANGE
16637                           );
16638
16639         const bool hash = (    obase->op_type == OP_PADHV
16640                             || obase->op_type == OP_RV2HV
16641                             || (obase->op_type == OP_PADRANGE
16642                                 && SvTYPE(PAD_SVl(obase->op_targ)) == SVt_PVHV)
16643                           );
16644         SSize_t index = 0;
16645         SV *keysv = NULL;
16646         int subscript_type = FUV_SUBSCRIPT_WITHIN;
16647
16648         if (pad) { /* @lex, %lex */
16649             sv = PAD_SVl(obase->op_targ);
16650             gv = NULL;
16651         }
16652         else {
16653             if (cUNOPx(obase)->op_first->op_type == OP_GV) {
16654             /* @global, %global */
16655                 gv = cGVOPx_gv(cUNOPx(obase)->op_first);
16656                 if (!gv)
16657                     break;
16658                 sv = hash ? MUTABLE_SV(GvHV(gv)): MUTABLE_SV(GvAV(gv));
16659             }
16660             else if (obase == PL_op) /* @{expr}, %{expr} */
16661                 return find_uninit_var(cUNOPx(obase)->op_first,
16662                                                 uninit_sv, match, desc_p);
16663             else /* @{expr}, %{expr} as a sub-expression */
16664                 return NULL;
16665         }
16666
16667         /* attempt to find a match within the aggregate */
16668         if (hash) {
16669             keysv = find_hash_subscript((const HV*)sv, uninit_sv);
16670             if (keysv)
16671                 subscript_type = FUV_SUBSCRIPT_HASH;
16672         }
16673         else {
16674             index = find_array_subscript((const AV *)sv, uninit_sv);
16675             if (index >= 0)
16676                 subscript_type = FUV_SUBSCRIPT_ARRAY;
16677         }
16678
16679         if (match && subscript_type == FUV_SUBSCRIPT_WITHIN)
16680             break;
16681
16682         return varname(gv, (char)(hash ? '%' : '@'), obase->op_targ,
16683                                     keysv, index, subscript_type);
16684       }
16685
16686     case OP_RV2SV:
16687         if (cUNOPx(obase)->op_first->op_type == OP_GV) {
16688             /* $global */
16689             gv = cGVOPx_gv(cUNOPx(obase)->op_first);
16690             if (!gv || !GvSTASH(gv))
16691                 break;
16692             if (match && (GvSV(gv) != uninit_sv))
16693                 break;
16694             return varname(gv, '$', 0, NULL, 0, FUV_SUBSCRIPT_NONE);
16695         }
16696         /* ${expr} */
16697         return find_uninit_var(cUNOPx(obase)->op_first, uninit_sv, 1, desc_p);
16698
16699     case OP_PADSV:
16700         if (match && PAD_SVl(obase->op_targ) != uninit_sv)
16701             break;
16702         return varname(NULL, '$', obase->op_targ,
16703                                     NULL, 0, FUV_SUBSCRIPT_NONE);
16704
16705     case OP_GVSV:
16706         gv = cGVOPx_gv(obase);
16707         if (!gv || (match && GvSV(gv) != uninit_sv) || !GvSTASH(gv))
16708             break;
16709         return varname(gv, '$', 0, NULL, 0, FUV_SUBSCRIPT_NONE);
16710
16711     case OP_AELEMFAST_LEX:
16712         if (match) {
16713             SV **svp;
16714             AV *av = MUTABLE_AV(PAD_SV(obase->op_targ));
16715             if (!av || SvRMAGICAL(av))
16716                 break;
16717             svp = av_fetch(av, (I8)obase->op_private, FALSE);
16718             if (!svp || *svp != uninit_sv)
16719                 break;
16720         }
16721         return varname(NULL, '$', obase->op_targ,
16722                        NULL, (I8)obase->op_private, FUV_SUBSCRIPT_ARRAY);
16723     case OP_AELEMFAST:
16724         {
16725             gv = cGVOPx_gv(obase);
16726             if (!gv)
16727                 break;
16728             if (match) {
16729                 SV **svp;
16730                 AV *const av = GvAV(gv);
16731                 if (!av || SvRMAGICAL(av))
16732                     break;
16733                 svp = av_fetch(av, (I8)obase->op_private, FALSE);
16734                 if (!svp || *svp != uninit_sv)
16735                     break;
16736             }
16737             return varname(gv, '$', 0,
16738                     NULL, (I8)obase->op_private, FUV_SUBSCRIPT_ARRAY);
16739         }
16740         NOT_REACHED; /* NOTREACHED */
16741
16742     case OP_EXISTS:
16743         o = cUNOPx(obase)->op_first;
16744         if (!o || o->op_type != OP_NULL ||
16745                 ! (o->op_targ == OP_AELEM || o->op_targ == OP_HELEM))
16746             break;
16747         return find_uninit_var(cBINOPo->op_last, uninit_sv, match, desc_p);
16748
16749     case OP_AELEM:
16750     case OP_HELEM:
16751     {
16752         bool negate = FALSE;
16753
16754         if (PL_op == obase)
16755             /* $a[uninit_expr] or $h{uninit_expr} */
16756             return find_uninit_var(cBINOPx(obase)->op_last,
16757                                                 uninit_sv, match, desc_p);
16758
16759         gv = NULL;
16760         o = cBINOPx(obase)->op_first;
16761         kid = cBINOPx(obase)->op_last;
16762
16763         /* get the av or hv, and optionally the gv */
16764         sv = NULL;
16765         if  (o->op_type == OP_PADAV || o->op_type == OP_PADHV) {
16766             sv = PAD_SV(o->op_targ);
16767         }
16768         else if ((o->op_type == OP_RV2AV || o->op_type == OP_RV2HV)
16769                 && cUNOPo->op_first->op_type == OP_GV)
16770         {
16771             gv = cGVOPx_gv(cUNOPo->op_first);
16772             if (!gv)
16773                 break;
16774             sv = o->op_type
16775                 == OP_RV2HV ? MUTABLE_SV(GvHV(gv)) : MUTABLE_SV(GvAV(gv));
16776         }
16777         if (!sv)
16778             break;
16779
16780         if (kid && kid->op_type == OP_NEGATE) {
16781             negate = TRUE;
16782             kid = cUNOPx(kid)->op_first;
16783         }
16784
16785         if (kid && kid->op_type == OP_CONST && SvOK(cSVOPx_sv(kid))) {
16786             /* index is constant */
16787             SV* kidsv;
16788             if (negate) {
16789                 kidsv = newSVpvs_flags("-", SVs_TEMP);
16790                 sv_catsv(kidsv, cSVOPx_sv(kid));
16791             }
16792             else
16793                 kidsv = cSVOPx_sv(kid);
16794             if (match) {
16795                 if (SvMAGICAL(sv))
16796                     break;
16797                 if (obase->op_type == OP_HELEM) {
16798                     HE* he = hv_fetch_ent(MUTABLE_HV(sv), kidsv, 0, 0);
16799                     if (!he || HeVAL(he) != uninit_sv)
16800                         break;
16801                 }
16802                 else {
16803                     SV * const  opsv = cSVOPx_sv(kid);
16804                     const IV  opsviv = SvIV(opsv);
16805                     SV * const * const svp = av_fetch(MUTABLE_AV(sv),
16806                         negate ? - opsviv : opsviv,
16807                         FALSE);
16808                     if (!svp || *svp != uninit_sv)
16809                         break;
16810                 }
16811             }
16812             if (obase->op_type == OP_HELEM)
16813                 return varname(gv, '%', o->op_targ,
16814                             kidsv, 0, FUV_SUBSCRIPT_HASH);
16815             else
16816                 return varname(gv, '@', o->op_targ, NULL,
16817                     negate ? - SvIV(cSVOPx_sv(kid)) : SvIV(cSVOPx_sv(kid)),
16818                     FUV_SUBSCRIPT_ARRAY);
16819         }
16820         else {
16821             /* index is an expression;
16822              * attempt to find a match within the aggregate */
16823             if (obase->op_type == OP_HELEM) {
16824                 SV * const keysv = find_hash_subscript((const HV*)sv, uninit_sv);
16825                 if (keysv)
16826                     return varname(gv, '%', o->op_targ,
16827                                                 keysv, 0, FUV_SUBSCRIPT_HASH);
16828             }
16829             else {
16830                 const SSize_t index
16831                     = find_array_subscript((const AV *)sv, uninit_sv);
16832                 if (index >= 0)
16833                     return varname(gv, '@', o->op_targ,
16834                                         NULL, index, FUV_SUBSCRIPT_ARRAY);
16835             }
16836             if (match)
16837                 break;
16838             return varname(gv,
16839                 (char)((o->op_type == OP_PADAV || o->op_type == OP_RV2AV)
16840                 ? '@' : '%'),
16841                 o->op_targ, NULL, 0, FUV_SUBSCRIPT_WITHIN);
16842         }
16843         NOT_REACHED; /* NOTREACHED */
16844     }
16845
16846     case OP_MULTIDEREF: {
16847         /* If we were executing OP_MULTIDEREF when the undef warning
16848          * triggered, then it must be one of the index values within
16849          * that triggered it. If not, then the only possibility is that
16850          * the value retrieved by the last aggregate index might be the
16851          * culprit. For the former, we set PL_multideref_pc each time before
16852          * using an index, so work though the item list until we reach
16853          * that point. For the latter, just work through the entire item
16854          * list; the last aggregate retrieved will be the candidate.
16855          * There is a third rare possibility: something triggered
16856          * magic while fetching an array/hash element. Just display
16857          * nothing in this case.
16858          */
16859
16860         /* the named aggregate, if any */
16861         PADOFFSET agg_targ = 0;
16862         GV       *agg_gv   = NULL;
16863         /* the last-seen index */
16864         UV        index_type;
16865         PADOFFSET index_targ;
16866         GV       *index_gv;
16867         IV        index_const_iv = 0; /* init for spurious compiler warn */
16868         SV       *index_const_sv;
16869         int       depth = 0;  /* how many array/hash lookups we've done */
16870
16871         UNOP_AUX_item *items = cUNOP_AUXx(obase)->op_aux;
16872         UNOP_AUX_item *last = NULL;
16873         UV actions = items->uv;
16874         bool is_hv;
16875
16876         if (PL_op == obase) {
16877             last = PL_multideref_pc;
16878             assert(last >= items && last <= items + items[-1].uv);
16879         }
16880
16881         assert(actions);
16882
16883         while (1) {
16884             is_hv = FALSE;
16885             switch (actions & MDEREF_ACTION_MASK) {
16886
16887             case MDEREF_reload:
16888                 actions = (++items)->uv;
16889                 continue;
16890
16891             case MDEREF_HV_padhv_helem:               /* $lex{...} */
16892                 is_hv = TRUE;
16893                 /* FALLTHROUGH */
16894             case MDEREF_AV_padav_aelem:               /* $lex[...] */
16895                 agg_targ = (++items)->pad_offset;
16896                 agg_gv = NULL;
16897                 break;
16898
16899             case MDEREF_HV_gvhv_helem:                /* $pkg{...} */
16900                 is_hv = TRUE;
16901                 /* FALLTHROUGH */
16902             case MDEREF_AV_gvav_aelem:                /* $pkg[...] */
16903                 agg_targ = 0;
16904                 agg_gv = (GV*)UNOP_AUX_item_sv(++items);
16905                 assert(isGV_with_GP(agg_gv));
16906                 break;
16907
16908             case MDEREF_HV_gvsv_vivify_rv2hv_helem:   /* $pkg->{...} */
16909             case MDEREF_HV_padsv_vivify_rv2hv_helem:  /* $lex->{...} */
16910                 ++items;
16911                 /* FALLTHROUGH */
16912             case MDEREF_HV_pop_rv2hv_helem:           /* expr->{...} */
16913             case MDEREF_HV_vivify_rv2hv_helem:        /* vivify, ->{...} */
16914                 agg_targ = 0;
16915                 agg_gv   = NULL;
16916                 is_hv    = TRUE;
16917                 break;
16918
16919             case MDEREF_AV_gvsv_vivify_rv2av_aelem:   /* $pkg->[...] */
16920             case MDEREF_AV_padsv_vivify_rv2av_aelem:  /* $lex->[...] */
16921                 ++items;
16922                 /* FALLTHROUGH */
16923             case MDEREF_AV_pop_rv2av_aelem:           /* expr->[...] */
16924             case MDEREF_AV_vivify_rv2av_aelem:        /* vivify, ->[...] */
16925                 agg_targ = 0;
16926                 agg_gv   = NULL;
16927             } /* switch */
16928
16929             index_targ     = 0;
16930             index_gv       = NULL;
16931             index_const_sv = NULL;
16932
16933             index_type = (actions & MDEREF_INDEX_MASK);
16934             switch (index_type) {
16935             case MDEREF_INDEX_none:
16936                 break;
16937             case MDEREF_INDEX_const:
16938                 if (is_hv)
16939                     index_const_sv = UNOP_AUX_item_sv(++items)
16940                 else
16941                     index_const_iv = (++items)->iv;
16942                 break;
16943             case MDEREF_INDEX_padsv:
16944                 index_targ = (++items)->pad_offset;
16945                 break;
16946             case MDEREF_INDEX_gvsv:
16947                 index_gv = (GV*)UNOP_AUX_item_sv(++items);
16948                 assert(isGV_with_GP(index_gv));
16949                 break;
16950             }
16951
16952             if (index_type != MDEREF_INDEX_none)
16953                 depth++;
16954
16955             if (   index_type == MDEREF_INDEX_none
16956                 || (actions & MDEREF_FLAG_last)
16957                 || (last && items >= last)
16958             )
16959                 break;
16960
16961             actions >>= MDEREF_SHIFT;
16962         } /* while */
16963
16964         if (PL_op == obase) {
16965             /* most likely index was undef */
16966
16967             *desc_p = (    (actions & MDEREF_FLAG_last)
16968                         && (obase->op_private
16969                                 & (OPpMULTIDEREF_EXISTS|OPpMULTIDEREF_DELETE)))
16970                         ?
16971                             (obase->op_private & OPpMULTIDEREF_EXISTS)
16972                                 ? "exists"
16973                                 : "delete"
16974                         : is_hv ? "hash element" : "array element";
16975             assert(index_type != MDEREF_INDEX_none);
16976             if (index_gv) {
16977                 if (GvSV(index_gv) == uninit_sv)
16978                     return varname(index_gv, '$', 0, NULL, 0,
16979                                                     FUV_SUBSCRIPT_NONE);
16980                 else
16981                     return NULL;
16982             }
16983             if (index_targ) {
16984                 if (PL_curpad[index_targ] == uninit_sv)
16985                     return varname(NULL, '$', index_targ,
16986                                     NULL, 0, FUV_SUBSCRIPT_NONE);
16987                 else
16988                     return NULL;
16989             }
16990             /* If we got to this point it was undef on a const subscript,
16991              * so magic probably involved, e.g. $ISA[0]. Give up. */
16992             return NULL;
16993         }
16994
16995         /* the SV returned by pp_multideref() was undef, if anything was */
16996
16997         if (depth != 1)
16998             break;
16999
17000         if (agg_targ)
17001             sv = PAD_SV(agg_targ);
17002         else if (agg_gv) {
17003             sv = is_hv ? MUTABLE_SV(GvHV(agg_gv)) : MUTABLE_SV(GvAV(agg_gv));
17004             if (!sv)
17005                 break;
17006             }
17007         else
17008             break;
17009
17010         if (index_type == MDEREF_INDEX_const) {
17011             if (match) {
17012                 if (SvMAGICAL(sv))
17013                     break;
17014                 if (is_hv) {
17015                     HE* he = hv_fetch_ent(MUTABLE_HV(sv), index_const_sv, 0, 0);
17016                     if (!he || HeVAL(he) != uninit_sv)
17017                         break;
17018                 }
17019                 else {
17020                     SV * const * const svp =
17021                             av_fetch(MUTABLE_AV(sv), index_const_iv, FALSE);
17022                     if (!svp || *svp != uninit_sv)
17023                         break;
17024                 }
17025             }
17026             return is_hv
17027                 ? varname(agg_gv, '%', agg_targ,
17028                                 index_const_sv, 0,    FUV_SUBSCRIPT_HASH)
17029                 : varname(agg_gv, '@', agg_targ,
17030                                 NULL, index_const_iv, FUV_SUBSCRIPT_ARRAY);
17031         }
17032         else {
17033             /* index is an var */
17034             if (is_hv) {
17035                 SV * const keysv = find_hash_subscript((const HV*)sv, uninit_sv);
17036                 if (keysv)
17037                     return varname(agg_gv, '%', agg_targ,
17038                                                 keysv, 0, FUV_SUBSCRIPT_HASH);
17039             }
17040             else {
17041                 const SSize_t index
17042                     = find_array_subscript((const AV *)sv, uninit_sv);
17043                 if (index >= 0)
17044                     return varname(agg_gv, '@', agg_targ,
17045                                         NULL, index, FUV_SUBSCRIPT_ARRAY);
17046             }
17047             /* look for an element not found */
17048             if (!SvMAGICAL(sv)) {
17049                 SV *index_sv = NULL;
17050                 if (index_targ) {
17051                     index_sv = PL_curpad[index_targ];
17052                 }
17053                 else if (index_gv) {
17054                     index_sv = GvSV(index_gv);
17055                 }
17056                 if (index_sv && !SvMAGICAL(index_sv) && !SvROK(index_sv)) {
17057                     if (is_hv) {
17058                         SV *report_index_sv = SvOK(index_sv) ? index_sv : &PL_sv_no;
17059                         HE *he = hv_fetch_ent(MUTABLE_HV(sv), report_index_sv, 0, 0);
17060                         if (!he) {
17061                             return varname(agg_gv, '%', agg_targ,
17062                                            report_index_sv, 0, FUV_SUBSCRIPT_HASH);
17063                         }
17064                     }
17065                     else {
17066                         SSize_t index = SvOK(index_sv) ? SvIV(index_sv) : 0;
17067                         SV * const * const svp =
17068                             av_fetch(MUTABLE_AV(sv), index, FALSE);
17069                         if (!svp) {
17070                             return varname(agg_gv, '@', agg_targ,
17071                                            NULL, index, FUV_SUBSCRIPT_ARRAY);
17072                         }
17073                     }
17074                 }
17075             }
17076             if (match)
17077                 break;
17078             return varname(agg_gv,
17079                 is_hv ? '%' : '@',
17080                 agg_targ, NULL, 0, FUV_SUBSCRIPT_WITHIN);
17081         }
17082         NOT_REACHED; /* NOTREACHED */
17083     }
17084
17085     case OP_AASSIGN:
17086         /* only examine RHS */
17087         return find_uninit_var(cBINOPx(obase)->op_first, uninit_sv,
17088                                                                 match, desc_p);
17089
17090     case OP_OPEN:
17091         o = cUNOPx(obase)->op_first;
17092         if (   o->op_type == OP_PUSHMARK
17093            || (o->op_type == OP_NULL && o->op_targ == OP_PUSHMARK)
17094         )
17095             o = OpSIBLING(o);
17096
17097         if (!OpHAS_SIBLING(o)) {
17098             /* one-arg version of open is highly magical */
17099
17100             if (o->op_type == OP_GV) { /* open FOO; */
17101                 gv = cGVOPx_gv(o);
17102                 if (match && GvSV(gv) != uninit_sv)
17103                     break;
17104                 return varname(gv, '$', 0,
17105                             NULL, 0, FUV_SUBSCRIPT_NONE);
17106             }
17107             /* other possibilities not handled are:
17108              * open $x; or open my $x;  should return '${*$x}'
17109              * open expr;               should return '$'.expr ideally
17110              */
17111              break;
17112         }
17113         match = 1;
17114         goto do_op;
17115
17116     /* ops where $_ may be an implicit arg */
17117     case OP_TRANS:
17118     case OP_TRANSR:
17119     case OP_SUBST:
17120     case OP_MATCH:
17121         if ( !(obase->op_flags & OPf_STACKED)) {
17122             if (uninit_sv == DEFSV)
17123                 return newSVpvs_flags("$_", SVs_TEMP);
17124             else if (obase->op_targ
17125                   && uninit_sv == PAD_SVl(obase->op_targ))
17126                 return varname(NULL, '$', obase->op_targ, NULL, 0,
17127                                FUV_SUBSCRIPT_NONE);
17128         }
17129         goto do_op;
17130
17131     case OP_PRTF:
17132     case OP_PRINT:
17133     case OP_SAY:
17134         match = 1; /* print etc can return undef on defined args */
17135         /* skip filehandle as it can't produce 'undef' warning  */
17136         o = cUNOPx(obase)->op_first;
17137         if ((obase->op_flags & OPf_STACKED)
17138             &&
17139                (   o->op_type == OP_PUSHMARK
17140                || (o->op_type == OP_NULL && o->op_targ == OP_PUSHMARK)))
17141             o = OpSIBLING(OpSIBLING(o));
17142         goto do_op2;
17143
17144
17145     case OP_ENTEREVAL: /* could be eval $undef or $x='$undef'; eval $x */
17146     case OP_CUSTOM: /* XS or custom code could trigger random warnings */
17147
17148         /* the following ops are capable of returning PL_sv_undef even for
17149          * defined arg(s) */
17150
17151     case OP_BACKTICK:
17152     case OP_PIPE_OP:
17153     case OP_FILENO:
17154     case OP_BINMODE:
17155     case OP_TIED:
17156     case OP_GETC:
17157     case OP_SYSREAD:
17158     case OP_SEND:
17159     case OP_IOCTL:
17160     case OP_SOCKET:
17161     case OP_SOCKPAIR:
17162     case OP_BIND:
17163     case OP_CONNECT:
17164     case OP_LISTEN:
17165     case OP_ACCEPT:
17166     case OP_SHUTDOWN:
17167     case OP_SSOCKOPT:
17168     case OP_GETPEERNAME:
17169     case OP_FTRREAD:
17170     case OP_FTRWRITE:
17171     case OP_FTREXEC:
17172     case OP_FTROWNED:
17173     case OP_FTEREAD:
17174     case OP_FTEWRITE:
17175     case OP_FTEEXEC:
17176     case OP_FTEOWNED:
17177     case OP_FTIS:
17178     case OP_FTZERO:
17179     case OP_FTSIZE:
17180     case OP_FTFILE:
17181     case OP_FTDIR:
17182     case OP_FTLINK:
17183     case OP_FTPIPE:
17184     case OP_FTSOCK:
17185     case OP_FTBLK:
17186     case OP_FTCHR:
17187     case OP_FTTTY:
17188     case OP_FTSUID:
17189     case OP_FTSGID:
17190     case OP_FTSVTX:
17191     case OP_FTTEXT:
17192     case OP_FTBINARY:
17193     case OP_FTMTIME:
17194     case OP_FTATIME:
17195     case OP_FTCTIME:
17196     case OP_READLINK:
17197     case OP_OPEN_DIR:
17198     case OP_READDIR:
17199     case OP_TELLDIR:
17200     case OP_SEEKDIR:
17201     case OP_REWINDDIR:
17202     case OP_CLOSEDIR:
17203     case OP_GMTIME:
17204     case OP_ALARM:
17205     case OP_SEMGET:
17206     case OP_GETLOGIN:
17207     case OP_SUBSTR:
17208     case OP_AEACH:
17209     case OP_EACH:
17210     case OP_SORT:
17211     case OP_CALLER:
17212     case OP_DOFILE:
17213     case OP_PROTOTYPE:
17214     case OP_NCMP:
17215     case OP_SMARTMATCH:
17216     case OP_UNPACK:
17217     case OP_SYSOPEN:
17218     case OP_SYSSEEK:
17219         match = 1;
17220         goto do_op;
17221
17222     case OP_ENTERSUB:
17223     case OP_GOTO:
17224         /* XXX tmp hack: these two may call an XS sub, and currently
17225           XS subs don't have a SUB entry on the context stack, so CV and
17226           pad determination goes wrong, and BAD things happen. So, just
17227           don't try to determine the value under those circumstances.
17228           Need a better fix at dome point. DAPM 11/2007 */
17229         break;
17230
17231     case OP_FLIP:
17232     case OP_FLOP:
17233     {
17234         GV * const gv = gv_fetchpvs(".", GV_NOTQUAL, SVt_PV);
17235         if (gv && GvSV(gv) == uninit_sv)
17236             return newSVpvs_flags("$.", SVs_TEMP);
17237         goto do_op;
17238     }
17239
17240     case OP_POS:
17241         /* def-ness of rval pos() is independent of the def-ness of its arg */
17242         if ( !(obase->op_flags & OPf_MOD))
17243             break;
17244         /* FALLTHROUGH */
17245
17246     case OP_SCHOMP:
17247     case OP_CHOMP:
17248         if (SvROK(PL_rs) && uninit_sv == SvRV(PL_rs))
17249             return newSVpvs_flags("${$/}", SVs_TEMP);
17250         /* FALLTHROUGH */
17251
17252     default:
17253     do_op:
17254         if (!(obase->op_flags & OPf_KIDS))
17255             break;
17256         o = cUNOPx(obase)->op_first;
17257
17258     do_op2:
17259         if (!o)
17260             break;
17261
17262         /* This loop checks all the kid ops, skipping any that cannot pos-
17263          * sibly be responsible for the uninitialized value; i.e., defined
17264          * constants and ops that return nothing.  If there is only one op
17265          * left that is not skipped, then we *know* it is responsible for
17266          * the uninitialized value.  If there is more than one op left, we
17267          * have to look for an exact match in the while() loop below.
17268          * Note that we skip padrange, because the individual pad ops that
17269          * it replaced are still in the tree, so we work on them instead.
17270          */
17271         o2 = NULL;
17272         for (kid=o; kid; kid = OpSIBLING(kid)) {
17273             const OPCODE type = kid->op_type;
17274             if ( (type == OP_CONST && SvOK(cSVOPx_sv(kid)))
17275               || (type == OP_NULL  && ! (kid->op_flags & OPf_KIDS))
17276               || (type == OP_PUSHMARK)
17277               || (type == OP_PADRANGE)
17278             )
17279             continue;
17280
17281             if (o2) { /* more than one found */
17282                 o2 = NULL;
17283                 break;
17284             }
17285             o2 = kid;
17286         }
17287         if (o2)
17288             return find_uninit_var(o2, uninit_sv, match, desc_p);
17289
17290         /* scan all args */
17291         while (o) {
17292             sv = find_uninit_var(o, uninit_sv, 1, desc_p);
17293             if (sv)
17294                 return sv;
17295             o = OpSIBLING(o);
17296         }
17297         break;
17298     }
17299     return NULL;
17300 }
17301
17302
17303 /*
17304 =for apidoc_section $warning
17305 =for apidoc report_uninit
17306
17307 Print appropriate "Use of uninitialized variable" warning.
17308
17309 =cut
17310 */
17311
17312 void
17313 Perl_report_uninit(pTHX_ const SV *uninit_sv)
17314 {
17315     const char *desc = NULL;
17316     SV* varname = NULL;
17317
17318     if (PL_op) {
17319         desc = PL_op->op_type == OP_STRINGIFY && PL_op->op_folded
17320                 ? "join or string"
17321                 : PL_op->op_type == OP_MULTICONCAT
17322                     && (PL_op->op_private & OPpMULTICONCAT_FAKE)
17323                 ? "sprintf"
17324                 : OP_DESC(PL_op);
17325         if (uninit_sv && PL_curpad) {
17326             varname = find_uninit_var(PL_op, uninit_sv, 0, &desc);
17327             if (varname)
17328                 sv_insert(varname, 0, 0, " ", 1);
17329         }
17330     }
17331     else if (PL_curstackinfo->si_type == PERLSI_SORT && cxstack_ix == 0)
17332         /* we've reached the end of a sort block or sub,
17333          * and the uninit value is probably what that code returned */
17334         desc = "sort";
17335
17336     /* PL_warn_uninit_sv is constant */
17337     GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
17338     if (desc)
17339         /* diag_listed_as: Use of uninitialized value%s */
17340         Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit_sv,
17341                 SVfARG(varname ? varname : &PL_sv_no),
17342                 " in ", desc);
17343     else
17344         Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
17345                 "", "", "");
17346     GCC_DIAG_RESTORE_STMT;
17347 }
17348
17349 /*
17350  * ex: set ts=8 sts=4 sw=4 et:
17351  */