This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
/x in patterns now includes all \p{PatWS}
[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
35 #ifndef HAS_C99
36 # if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L && !defined(VMS)
37 #  define HAS_C99 1
38 # endif
39 #endif
40 #ifdef HAS_C99
41 # include <stdint.h>
42 #endif
43
44 #ifdef __Lynx__
45 /* Missing proto on LynxOS */
46   char *gconvert(double, int, int,  char *);
47 #endif
48
49 #ifdef PERL_NEW_COPY_ON_WRITE
50 #   ifndef SV_COW_THRESHOLD
51 #    define SV_COW_THRESHOLD                    0   /* COW iff len > K */
52 #   endif
53 #   ifndef SV_COWBUF_THRESHOLD
54 #    define SV_COWBUF_THRESHOLD                 1250 /* COW iff len > K */
55 #   endif
56 #   ifndef SV_COW_MAX_WASTE_THRESHOLD
57 #    define SV_COW_MAX_WASTE_THRESHOLD          80   /* COW iff (len - cur) < K */
58 #   endif
59 #   ifndef SV_COWBUF_WASTE_THRESHOLD
60 #    define SV_COWBUF_WASTE_THRESHOLD           80   /* COW iff (len - cur) < K */
61 #   endif
62 #   ifndef SV_COW_MAX_WASTE_FACTOR_THRESHOLD
63 #    define SV_COW_MAX_WASTE_FACTOR_THRESHOLD   2    /* COW iff len < (cur * K) */
64 #   endif
65 #   ifndef SV_COWBUF_WASTE_FACTOR_THRESHOLD
66 #    define SV_COWBUF_WASTE_FACTOR_THRESHOLD    2    /* COW iff len < (cur * K) */
67 #   endif
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 /* void Gconvert: on Linux at least, gcvt (which Gconvert gets deffed to),
113  * has a mandatory return value, even though that value is just the same
114  * as the buf arg */
115
116 #ifdef PERL_UTF8_CACHE_ASSERT
117 /* if adding more checks watch out for the following tests:
118  *   t/op/index.t t/op/length.t t/op/pat.t t/op/substr.t
119  *   lib/utf8.t lib/Unicode/Collate/t/index.t
120  * --jhi
121  */
122 #   define ASSERT_UTF8_CACHE(cache) \
123     STMT_START { if (cache) { assert((cache)[0] <= (cache)[1]); \
124                               assert((cache)[2] <= (cache)[3]); \
125                               assert((cache)[3] <= (cache)[1]);} \
126                               } STMT_END
127 #else
128 #   define ASSERT_UTF8_CACHE(cache) NOOP
129 #endif
130
131 #ifdef PERL_OLD_COPY_ON_WRITE
132 #define SV_COW_NEXT_SV(sv)      INT2PTR(SV *,SvUVX(sv))
133 #define SV_COW_NEXT_SV_SET(current,next)        SvUV_set(current, PTR2UV(next))
134 #endif
135
136 /* ============================================================================
137
138 =head1 Allocation and deallocation of SVs.
139
140 An SV (or AV, HV, etc.) is allocated in two parts: the head (struct
141 sv, av, hv...) contains type and reference count information, and for
142 many types, a pointer to the body (struct xrv, xpv, xpviv...), which
143 contains fields specific to each type.  Some types store all they need
144 in the head, so don't have a body.
145
146 In all but the most memory-paranoid configurations (ex: PURIFY), heads
147 and bodies are allocated out of arenas, which by default are
148 approximately 4K chunks of memory parcelled up into N heads or bodies.
149 Sv-bodies are allocated by their sv-type, guaranteeing size
150 consistency needed to allocate safely from arrays.
151
152 For SV-heads, the first slot in each arena is reserved, and holds a
153 link to the next arena, some flags, and a note of the number of slots.
154 Snaked through each arena chain is a linked list of free items; when
155 this becomes empty, an extra arena is allocated and divided up into N
156 items which are threaded into the free list.
157
158 SV-bodies are similar, but they use arena-sets by default, which
159 separate the link and info from the arena itself, and reclaim the 1st
160 slot in the arena.  SV-bodies are further described later.
161
162 The following global variables are associated with arenas:
163
164     PL_sv_arenaroot     pointer to list of SV arenas
165     PL_sv_root          pointer to list of free SV structures
166
167     PL_body_arenas      head of linked-list of body arenas
168     PL_body_roots[]     array of pointers to list of free bodies of svtype
169                         arrays are indexed by the svtype needed
170
171 A few special SV heads are not allocated from an arena, but are
172 instead directly created in the interpreter structure, eg PL_sv_undef.
173 The size of arenas can be changed from the default by setting
174 PERL_ARENA_SIZE appropriately at compile time.
175
176 The SV arena serves the secondary purpose of allowing still-live SVs
177 to be located and destroyed during final cleanup.
178
179 At the lowest level, the macros new_SV() and del_SV() grab and free
180 an SV head.  (If debugging with -DD, del_SV() calls the function S_del_sv()
181 to return the SV to the free list with error checking.) new_SV() calls
182 more_sv() / sv_add_arena() to add an extra arena if the free list is empty.
183 SVs in the free list have their SvTYPE field set to all ones.
184
185 At the time of very final cleanup, sv_free_arenas() is called from
186 perl_destruct() to physically free all the arenas allocated since the
187 start of the interpreter.
188
189 The function visit() scans the SV arenas list, and calls a specified
190 function for each SV it finds which is still live - ie which has an SvTYPE
191 other than all 1's, and a non-zero SvREFCNT. visit() is used by the
192 following functions (specified as [function that calls visit()] / [function
193 called by visit() for each SV]):
194
195     sv_report_used() / do_report_used()
196                         dump all remaining SVs (debugging aid)
197
198     sv_clean_objs() / do_clean_objs(),do_clean_named_objs(),
199                       do_clean_named_io_objs(),do_curse()
200                         Attempt to free all objects pointed to by RVs,
201                         try to do the same for all objects indir-
202                         ectly referenced by typeglobs too, and
203                         then do a final sweep, cursing any
204                         objects that remain.  Called once from
205                         perl_destruct(), prior to calling sv_clean_all()
206                         below.
207
208     sv_clean_all() / do_clean_all()
209                         SvREFCNT_dec(sv) each remaining SV, possibly
210                         triggering an sv_free(). It also sets the
211                         SVf_BREAK flag on the SV to indicate that the
212                         refcnt has been artificially lowered, and thus
213                         stopping sv_free() from giving spurious warnings
214                         about SVs which unexpectedly have a refcnt
215                         of zero.  called repeatedly from perl_destruct()
216                         until there are no SVs left.
217
218 =head2 Arena allocator API Summary
219
220 Private API to rest of sv.c
221
222     new_SV(),  del_SV(),
223
224     new_XPVNV(), del_XPVGV(),
225     etc
226
227 Public API:
228
229     sv_report_used(), sv_clean_objs(), sv_clean_all(), sv_free_arenas()
230
231 =cut
232
233  * ========================================================================= */
234
235 /*
236  * "A time to plant, and a time to uproot what was planted..."
237  */
238
239 #ifdef PERL_MEM_LOG
240 #  define MEM_LOG_NEW_SV(sv, file, line, func)  \
241             Perl_mem_log_new_sv(sv, file, line, func)
242 #  define MEM_LOG_DEL_SV(sv, file, line, func)  \
243             Perl_mem_log_del_sv(sv, file, line, func)
244 #else
245 #  define MEM_LOG_NEW_SV(sv, file, line, func)  NOOP
246 #  define MEM_LOG_DEL_SV(sv, file, line, func)  NOOP
247 #endif
248
249 #ifdef DEBUG_LEAKING_SCALARS
250 #  define FREE_SV_DEBUG_FILE(sv) STMT_START { \
251         if ((sv)->sv_debug_file) PerlMemShared_free((sv)->sv_debug_file); \
252     } STMT_END
253 #  define DEBUG_SV_SERIAL(sv)                                               \
254     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) del_SV\n",    \
255             PTR2UV(sv), (long)(sv)->sv_debug_serial))
256 #else
257 #  define FREE_SV_DEBUG_FILE(sv)
258 #  define DEBUG_SV_SERIAL(sv)   NOOP
259 #endif
260
261 #ifdef PERL_POISON
262 #  define SvARENA_CHAIN(sv)     ((sv)->sv_u.svu_rv)
263 #  define SvARENA_CHAIN_SET(sv,val)     (sv)->sv_u.svu_rv = MUTABLE_SV((val))
264 /* Whilst I'd love to do this, it seems that things like to check on
265    unreferenced scalars
266 #  define POSION_SV_HEAD(sv)    PoisonNew(sv, 1, struct STRUCT_SV)
267 */
268 #  define POSION_SV_HEAD(sv)    PoisonNew(&SvANY(sv), 1, void *), \
269                                 PoisonNew(&SvREFCNT(sv), 1, U32)
270 #else
271 #  define SvARENA_CHAIN(sv)     SvANY(sv)
272 #  define SvARENA_CHAIN_SET(sv,val)     SvANY(sv) = (void *)(val)
273 #  define POSION_SV_HEAD(sv)
274 #endif
275
276 /* Mark an SV head as unused, and add to free list.
277  *
278  * If SVf_BREAK is set, skip adding it to the free list, as this SV had
279  * its refcount artificially decremented during global destruction, so
280  * there may be dangling pointers to it. The last thing we want in that
281  * case is for it to be reused. */
282
283 #define plant_SV(p) \
284     STMT_START {                                        \
285         const U32 old_flags = SvFLAGS(p);                       \
286         MEM_LOG_DEL_SV(p, __FILE__, __LINE__, FUNCTION__);  \
287         DEBUG_SV_SERIAL(p);                             \
288         FREE_SV_DEBUG_FILE(p);                          \
289         POSION_SV_HEAD(p);                              \
290         SvFLAGS(p) = SVTYPEMASK;                        \
291         if (!(old_flags & SVf_BREAK)) {         \
292             SvARENA_CHAIN_SET(p, PL_sv_root);   \
293             PL_sv_root = (p);                           \
294         }                                               \
295         --PL_sv_count;                                  \
296     } STMT_END
297
298 #define uproot_SV(p) \
299     STMT_START {                                        \
300         (p) = PL_sv_root;                               \
301         PL_sv_root = MUTABLE_SV(SvARENA_CHAIN(p));              \
302         ++PL_sv_count;                                  \
303     } STMT_END
304
305
306 /* make some more SVs by adding another arena */
307
308 STATIC SV*
309 S_more_sv(pTHX)
310 {
311     dVAR;
312     SV* sv;
313     char *chunk;                /* must use New here to match call to */
314     Newx(chunk,PERL_ARENA_SIZE,char);  /* Safefree() in sv_free_arenas() */
315     sv_add_arena(chunk, PERL_ARENA_SIZE, 0);
316     uproot_SV(sv);
317     return sv;
318 }
319
320 /* new_SV(): return a new, empty SV head */
321
322 #ifdef DEBUG_LEAKING_SCALARS
323 /* provide a real function for a debugger to play with */
324 STATIC SV*
325 S_new_SV(pTHX_ const char *file, int line, const char *func)
326 {
327     SV* sv;
328
329     if (PL_sv_root)
330         uproot_SV(sv);
331     else
332         sv = S_more_sv(aTHX);
333     SvANY(sv) = 0;
334     SvREFCNT(sv) = 1;
335     SvFLAGS(sv) = 0;
336     sv->sv_debug_optype = PL_op ? PL_op->op_type : 0;
337     sv->sv_debug_line = (U16) (PL_parser && PL_parser->copline != NOLINE
338                 ? PL_parser->copline
339                 :  PL_curcop
340                     ? CopLINE(PL_curcop)
341                     : 0
342             );
343     sv->sv_debug_inpad = 0;
344     sv->sv_debug_parent = NULL;
345     sv->sv_debug_file = PL_curcop ? savesharedpv(CopFILE(PL_curcop)): NULL;
346
347     sv->sv_debug_serial = PL_sv_serial++;
348
349     MEM_LOG_NEW_SV(sv, file, line, func);
350     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) new_SV (from %s:%d [%s])\n",
351             PTR2UV(sv), (long)sv->sv_debug_serial, file, line, func));
352
353     return sv;
354 }
355 #  define new_SV(p) (p)=S_new_SV(aTHX_ __FILE__, __LINE__, FUNCTION__)
356
357 #else
358 #  define new_SV(p) \
359     STMT_START {                                        \
360         if (PL_sv_root)                                 \
361             uproot_SV(p);                               \
362         else                                            \
363             (p) = S_more_sv(aTHX);                      \
364         SvANY(p) = 0;                                   \
365         SvREFCNT(p) = 1;                                \
366         SvFLAGS(p) = 0;                                 \
367         MEM_LOG_NEW_SV(p, __FILE__, __LINE__, FUNCTION__);  \
368     } STMT_END
369 #endif
370
371
372 /* del_SV(): return an empty SV head to the free list */
373
374 #ifdef DEBUGGING
375
376 #define del_SV(p) \
377     STMT_START {                                        \
378         if (DEBUG_D_TEST)                               \
379             del_sv(p);                                  \
380         else                                            \
381             plant_SV(p);                                \
382     } STMT_END
383
384 STATIC void
385 S_del_sv(pTHX_ SV *p)
386 {
387     dVAR;
388
389     PERL_ARGS_ASSERT_DEL_SV;
390
391     if (DEBUG_D_TEST) {
392         SV* sva;
393         bool ok = 0;
394         for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
395             const SV * const sv = sva + 1;
396             const SV * const svend = &sva[SvREFCNT(sva)];
397             if (p >= sv && p < svend) {
398                 ok = 1;
399                 break;
400             }
401         }
402         if (!ok) {
403             Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
404                              "Attempt to free non-arena SV: 0x%"UVxf
405                              pTHX__FORMAT, PTR2UV(p) pTHX__VALUE);
406             return;
407         }
408     }
409     plant_SV(p);
410 }
411
412 #else /* ! DEBUGGING */
413
414 #define del_SV(p)   plant_SV(p)
415
416 #endif /* DEBUGGING */
417
418
419 /*
420 =head1 SV Manipulation Functions
421
422 =for apidoc sv_add_arena
423
424 Given a chunk of memory, link it to the head of the list of arenas,
425 and split it into a list of free SVs.
426
427 =cut
428 */
429
430 static void
431 S_sv_add_arena(pTHX_ char *const ptr, const U32 size, const U32 flags)
432 {
433     dVAR;
434     SV *const sva = MUTABLE_SV(ptr);
435     SV* sv;
436     SV* svend;
437
438     PERL_ARGS_ASSERT_SV_ADD_ARENA;
439
440     /* The first SV in an arena isn't an SV. */
441     SvANY(sva) = (void *) PL_sv_arenaroot;              /* ptr to next arena */
442     SvREFCNT(sva) = size / sizeof(SV);          /* number of SV slots */
443     SvFLAGS(sva) = flags;                       /* FAKE if not to be freed */
444
445     PL_sv_arenaroot = sva;
446     PL_sv_root = sva + 1;
447
448     svend = &sva[SvREFCNT(sva) - 1];
449     sv = sva + 1;
450     while (sv < svend) {
451         SvARENA_CHAIN_SET(sv, (sv + 1));
452 #ifdef DEBUGGING
453         SvREFCNT(sv) = 0;
454 #endif
455         /* Must always set typemask because it's always checked in on cleanup
456            when the arenas are walked looking for objects.  */
457         SvFLAGS(sv) = SVTYPEMASK;
458         sv++;
459     }
460     SvARENA_CHAIN_SET(sv, 0);
461 #ifdef DEBUGGING
462     SvREFCNT(sv) = 0;
463 #endif
464     SvFLAGS(sv) = SVTYPEMASK;
465 }
466
467 /* visit(): call the named function for each non-free SV in the arenas
468  * whose flags field matches the flags/mask args. */
469
470 STATIC I32
471 S_visit(pTHX_ SVFUNC_t f, const U32 flags, const U32 mask)
472 {
473     dVAR;
474     SV* sva;
475     I32 visited = 0;
476
477     PERL_ARGS_ASSERT_VISIT;
478
479     for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
480         const SV * const svend = &sva[SvREFCNT(sva)];
481         SV* sv;
482         for (sv = sva + 1; sv < svend; ++sv) {
483             if (SvTYPE(sv) != (svtype)SVTYPEMASK
484                     && (sv->sv_flags & mask) == flags
485                     && SvREFCNT(sv))
486             {
487                 (*f)(aTHX_ sv);
488                 ++visited;
489             }
490         }
491     }
492     return visited;
493 }
494
495 #ifdef DEBUGGING
496
497 /* called by sv_report_used() for each live SV */
498
499 static void
500 do_report_used(pTHX_ SV *const sv)
501 {
502     if (SvTYPE(sv) != (svtype)SVTYPEMASK) {
503         PerlIO_printf(Perl_debug_log, "****\n");
504         sv_dump(sv);
505     }
506 }
507 #endif
508
509 /*
510 =for apidoc sv_report_used
511
512 Dump the contents of all SVs not yet freed (debugging aid).
513
514 =cut
515 */
516
517 void
518 Perl_sv_report_used(pTHX)
519 {
520 #ifdef DEBUGGING
521     visit(do_report_used, 0, 0);
522 #else
523     PERL_UNUSED_CONTEXT;
524 #endif
525 }
526
527 /* called by sv_clean_objs() for each live SV */
528
529 static void
530 do_clean_objs(pTHX_ SV *const ref)
531 {
532     dVAR;
533     assert (SvROK(ref));
534     {
535         SV * const target = SvRV(ref);
536         if (SvOBJECT(target)) {
537             DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning object ref:\n "), sv_dump(ref)));
538             if (SvWEAKREF(ref)) {
539                 sv_del_backref(target, ref);
540                 SvWEAKREF_off(ref);
541                 SvRV_set(ref, NULL);
542             } else {
543                 SvROK_off(ref);
544                 SvRV_set(ref, NULL);
545                 SvREFCNT_dec_NN(target);
546             }
547         }
548     }
549 }
550
551
552 /* clear any slots in a GV which hold objects - except IO;
553  * called by sv_clean_objs() for each live GV */
554
555 static void
556 do_clean_named_objs(pTHX_ SV *const sv)
557 {
558     dVAR;
559     SV *obj;
560     assert(SvTYPE(sv) == SVt_PVGV);
561     assert(isGV_with_GP(sv));
562     if (!GvGP(sv))
563         return;
564
565     /* freeing GP entries may indirectly free the current GV;
566      * hold onto it while we mess with the GP slots */
567     SvREFCNT_inc(sv);
568
569     if ( ((obj = GvSV(sv) )) && SvOBJECT(obj)) {
570         DEBUG_D((PerlIO_printf(Perl_debug_log,
571                 "Cleaning named glob SV object:\n "), sv_dump(obj)));
572         GvSV(sv) = NULL;
573         SvREFCNT_dec_NN(obj);
574     }
575     if ( ((obj = MUTABLE_SV(GvAV(sv)) )) && SvOBJECT(obj)) {
576         DEBUG_D((PerlIO_printf(Perl_debug_log,
577                 "Cleaning named glob AV object:\n "), sv_dump(obj)));
578         GvAV(sv) = NULL;
579         SvREFCNT_dec_NN(obj);
580     }
581     if ( ((obj = MUTABLE_SV(GvHV(sv)) )) && SvOBJECT(obj)) {
582         DEBUG_D((PerlIO_printf(Perl_debug_log,
583                 "Cleaning named glob HV object:\n "), sv_dump(obj)));
584         GvHV(sv) = NULL;
585         SvREFCNT_dec_NN(obj);
586     }
587     if ( ((obj = MUTABLE_SV(GvCV(sv)) )) && SvOBJECT(obj)) {
588         DEBUG_D((PerlIO_printf(Perl_debug_log,
589                 "Cleaning named glob CV object:\n "), sv_dump(obj)));
590         GvCV_set(sv, NULL);
591         SvREFCNT_dec_NN(obj);
592     }
593     SvREFCNT_dec_NN(sv); /* undo the inc above */
594 }
595
596 /* clear any IO slots in a GV which hold objects (except stderr, defout);
597  * called by sv_clean_objs() for each live GV */
598
599 static void
600 do_clean_named_io_objs(pTHX_ SV *const sv)
601 {
602     dVAR;
603     SV *obj;
604     assert(SvTYPE(sv) == SVt_PVGV);
605     assert(isGV_with_GP(sv));
606     if (!GvGP(sv) || sv == (SV*)PL_stderrgv || sv == (SV*)PL_defoutgv)
607         return;
608
609     SvREFCNT_inc(sv);
610     if ( ((obj = MUTABLE_SV(GvIO(sv)) )) && SvOBJECT(obj)) {
611         DEBUG_D((PerlIO_printf(Perl_debug_log,
612                 "Cleaning named glob IO object:\n "), sv_dump(obj)));
613         GvIOp(sv) = NULL;
614         SvREFCNT_dec_NN(obj);
615     }
616     SvREFCNT_dec_NN(sv); /* undo the inc above */
617 }
618
619 /* Void wrapper to pass to visit() */
620 static void
621 do_curse(pTHX_ SV * const sv) {
622     if ((PL_stderrgv && GvGP(PL_stderrgv) && (SV*)GvIO(PL_stderrgv) == sv)
623      || (PL_defoutgv && GvGP(PL_defoutgv) && (SV*)GvIO(PL_defoutgv) == sv))
624         return;
625     (void)curse(sv, 0);
626 }
627
628 /*
629 =for apidoc sv_clean_objs
630
631 Attempt to destroy all objects not yet freed.
632
633 =cut
634 */
635
636 void
637 Perl_sv_clean_objs(pTHX)
638 {
639     dVAR;
640     GV *olddef, *olderr;
641     PL_in_clean_objs = TRUE;
642     visit(do_clean_objs, SVf_ROK, SVf_ROK);
643     /* Some barnacles may yet remain, clinging to typeglobs.
644      * Run the non-IO destructors first: they may want to output
645      * error messages, close files etc */
646     visit(do_clean_named_objs, SVt_PVGV|SVpgv_GP, SVTYPEMASK|SVp_POK|SVpgv_GP);
647     visit(do_clean_named_io_objs, SVt_PVGV|SVpgv_GP, SVTYPEMASK|SVp_POK|SVpgv_GP);
648     /* And if there are some very tenacious barnacles clinging to arrays,
649        closures, or what have you.... */
650     visit(do_curse, SVs_OBJECT, SVs_OBJECT);
651     olddef = PL_defoutgv;
652     PL_defoutgv = NULL; /* disable skip of PL_defoutgv */
653     if (olddef && isGV_with_GP(olddef))
654         do_clean_named_io_objs(aTHX_ MUTABLE_SV(olddef));
655     olderr = PL_stderrgv;
656     PL_stderrgv = NULL; /* disable skip of PL_stderrgv */
657     if (olderr && isGV_with_GP(olderr))
658         do_clean_named_io_objs(aTHX_ MUTABLE_SV(olderr));
659     SvREFCNT_dec(olddef);
660     PL_in_clean_objs = FALSE;
661 }
662
663 /* called by sv_clean_all() for each live SV */
664
665 static void
666 do_clean_all(pTHX_ SV *const sv)
667 {
668     dVAR;
669     if (sv == (const SV *) PL_fdpid || sv == (const SV *)PL_strtab) {
670         /* don't clean pid table and strtab */
671         return;
672     }
673     DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning loops: SV at 0x%"UVxf"\n", PTR2UV(sv)) ));
674     SvFLAGS(sv) |= SVf_BREAK;
675     SvREFCNT_dec_NN(sv);
676 }
677
678 /*
679 =for apidoc sv_clean_all
680
681 Decrement the refcnt of each remaining SV, possibly triggering a
682 cleanup.  This function may have to be called multiple times to free
683 SVs which are in complex self-referential hierarchies.
684
685 =cut
686 */
687
688 I32
689 Perl_sv_clean_all(pTHX)
690 {
691     dVAR;
692     I32 cleaned;
693     PL_in_clean_all = TRUE;
694     cleaned = visit(do_clean_all, 0,0);
695     return cleaned;
696 }
697
698 /*
699   ARENASETS: a meta-arena implementation which separates arena-info
700   into struct arena_set, which contains an array of struct
701   arena_descs, each holding info for a single arena.  By separating
702   the meta-info from the arena, we recover the 1st slot, formerly
703   borrowed for list management.  The arena_set is about the size of an
704   arena, avoiding the needless malloc overhead of a naive linked-list.
705
706   The cost is 1 arena-set malloc per ~320 arena-mallocs, + the unused
707   memory in the last arena-set (1/2 on average).  In trade, we get
708   back the 1st slot in each arena (ie 1.7% of a CV-arena, less for
709   smaller types).  The recovery of the wasted space allows use of
710   small arenas for large, rare body types, by changing array* fields
711   in body_details_by_type[] below.
712 */
713 struct arena_desc {
714     char       *arena;          /* the raw storage, allocated aligned */
715     size_t      size;           /* its size ~4k typ */
716     svtype      utype;          /* bodytype stored in arena */
717 };
718
719 struct arena_set;
720
721 /* Get the maximum number of elements in set[] such that struct arena_set
722    will fit within PERL_ARENA_SIZE, which is probably just under 4K, and
723    therefore likely to be 1 aligned memory page.  */
724
725 #define ARENAS_PER_SET  ((PERL_ARENA_SIZE - sizeof(struct arena_set*) \
726                           - 2 * sizeof(int)) / sizeof (struct arena_desc))
727
728 struct arena_set {
729     struct arena_set* next;
730     unsigned int   set_size;    /* ie ARENAS_PER_SET */
731     unsigned int   curr;        /* index of next available arena-desc */
732     struct arena_desc set[ARENAS_PER_SET];
733 };
734
735 /*
736 =for apidoc sv_free_arenas
737
738 Deallocate the memory used by all arenas.  Note that all the individual SV
739 heads and bodies within the arenas must already have been freed.
740
741 =cut
742 */
743 void
744 Perl_sv_free_arenas(pTHX)
745 {
746     dVAR;
747     SV* sva;
748     SV* svanext;
749     unsigned int i;
750
751     /* Free arenas here, but be careful about fake ones.  (We assume
752        contiguity of the fake ones with the corresponding real ones.) */
753
754     for (sva = PL_sv_arenaroot; sva; sva = svanext) {
755         svanext = MUTABLE_SV(SvANY(sva));
756         while (svanext && SvFAKE(svanext))
757             svanext = MUTABLE_SV(SvANY(svanext));
758
759         if (!SvFAKE(sva))
760             Safefree(sva);
761     }
762
763     {
764         struct arena_set *aroot = (struct arena_set*) PL_body_arenas;
765
766         while (aroot) {
767             struct arena_set *current = aroot;
768             i = aroot->curr;
769             while (i--) {
770                 assert(aroot->set[i].arena);
771                 Safefree(aroot->set[i].arena);
772             }
773             aroot = aroot->next;
774             Safefree(current);
775         }
776     }
777     PL_body_arenas = 0;
778
779     i = PERL_ARENA_ROOTS_SIZE;
780     while (i--)
781         PL_body_roots[i] = 0;
782
783     PL_sv_arenaroot = 0;
784     PL_sv_root = 0;
785 }
786
787 /*
788   Here are mid-level routines that manage the allocation of bodies out
789   of the various arenas.  There are 5 kinds of arenas:
790
791   1. SV-head arenas, which are discussed and handled above
792   2. regular body arenas
793   3. arenas for reduced-size bodies
794   4. Hash-Entry arenas
795
796   Arena types 2 & 3 are chained by body-type off an array of
797   arena-root pointers, which is indexed by svtype.  Some of the
798   larger/less used body types are malloced singly, since a large
799   unused block of them is wasteful.  Also, several svtypes dont have
800   bodies; the data fits into the sv-head itself.  The arena-root
801   pointer thus has a few unused root-pointers (which may be hijacked
802   later for arena types 4,5)
803
804   3 differs from 2 as an optimization; some body types have several
805   unused fields in the front of the structure (which are kept in-place
806   for consistency).  These bodies can be allocated in smaller chunks,
807   because the leading fields arent accessed.  Pointers to such bodies
808   are decremented to point at the unused 'ghost' memory, knowing that
809   the pointers are used with offsets to the real memory.
810
811
812 =head1 SV-Body Allocation
813
814 Allocation of SV-bodies is similar to SV-heads, differing as follows;
815 the allocation mechanism is used for many body types, so is somewhat
816 more complicated, it uses arena-sets, and has no need for still-live
817 SV detection.
818
819 At the outermost level, (new|del)_X*V macros return bodies of the
820 appropriate type.  These macros call either (new|del)_body_type or
821 (new|del)_body_allocated macro pairs, depending on specifics of the
822 type.  Most body types use the former pair, the latter pair is used to
823 allocate body types with "ghost fields".
824
825 "ghost fields" are fields that are unused in certain types, and
826 consequently don't need to actually exist.  They are declared because
827 they're part of a "base type", which allows use of functions as
828 methods.  The simplest examples are AVs and HVs, 2 aggregate types
829 which don't use the fields which support SCALAR semantics.
830
831 For these types, the arenas are carved up into appropriately sized
832 chunks, we thus avoid wasted memory for those unaccessed members.
833 When bodies are allocated, we adjust the pointer back in memory by the
834 size of the part not allocated, so it's as if we allocated the full
835 structure.  (But things will all go boom if you write to the part that
836 is "not there", because you'll be overwriting the last members of the
837 preceding structure in memory.)
838
839 We calculate the correction using the STRUCT_OFFSET macro on the first
840 member present.  If the allocated structure is smaller (no initial NV
841 actually allocated) then the net effect is to subtract the size of the NV
842 from the pointer, to return a new pointer as if an initial NV were actually
843 allocated.  (We were using structures named *_allocated for this, but
844 this turned out to be a subtle bug, because a structure without an NV
845 could have a lower alignment constraint, but the compiler is allowed to
846 optimised accesses based on the alignment constraint of the actual pointer
847 to the full structure, for example, using a single 64 bit load instruction
848 because it "knows" that two adjacent 32 bit members will be 8-byte aligned.)
849
850 This is the same trick as was used for NV and IV bodies.  Ironically it
851 doesn't need to be used for NV bodies any more, because NV is now at
852 the start of the structure.  IV bodies don't need it either, because
853 they are no longer allocated.
854
855 In turn, the new_body_* allocators call S_new_body(), which invokes
856 new_body_inline macro, which takes a lock, and takes a body off the
857 linked list at PL_body_roots[sv_type], calling Perl_more_bodies() if
858 necessary to refresh an empty list.  Then the lock is released, and
859 the body is returned.
860
861 Perl_more_bodies allocates a new arena, and carves it up into an array of N
862 bodies, which it strings into a linked list.  It looks up arena-size
863 and body-size from the body_details table described below, thus
864 supporting the multiple body-types.
865
866 If PURIFY is defined, or PERL_ARENA_SIZE=0, arenas are not used, and
867 the (new|del)_X*V macros are mapped directly to malloc/free.
868
869 For each sv-type, struct body_details bodies_by_type[] carries
870 parameters which control these aspects of SV handling:
871
872 Arena_size determines whether arenas are used for this body type, and if
873 so, how big they are.  PURIFY or PERL_ARENA_SIZE=0 set this field to
874 zero, forcing individual mallocs and frees.
875
876 Body_size determines how big a body is, and therefore how many fit into
877 each arena.  Offset carries the body-pointer adjustment needed for
878 "ghost fields", and is used in *_allocated macros.
879
880 But its main purpose is to parameterize info needed in
881 Perl_sv_upgrade().  The info here dramatically simplifies the function
882 vs the implementation in 5.8.8, making it table-driven.  All fields
883 are used for this, except for arena_size.
884
885 For the sv-types that have no bodies, arenas are not used, so those
886 PL_body_roots[sv_type] are unused, and can be overloaded.  In
887 something of a special case, SVt_NULL is borrowed for HE arenas;
888 PL_body_roots[HE_SVSLOT=SVt_NULL] is filled by S_more_he, but the
889 bodies_by_type[SVt_NULL] slot is not used, as the table is not
890 available in hv.c.
891
892 */
893
894 struct body_details {
895     U8 body_size;       /* Size to allocate  */
896     U8 copy;            /* Size of structure to copy (may be shorter)  */
897     U8 offset;
898     unsigned int type : 4;          /* We have space for a sanity check.  */
899     unsigned int cant_upgrade : 1;  /* Cannot upgrade this type */
900     unsigned int zero_nv : 1;       /* zero the NV when upgrading from this */
901     unsigned int arena : 1;         /* Allocated from an arena */
902     size_t arena_size;              /* Size of arena to allocate */
903 };
904
905 #define HADNV FALSE
906 #define NONV TRUE
907
908
909 #ifdef PURIFY
910 /* With -DPURFIY we allocate everything directly, and don't use arenas.
911    This seems a rather elegant way to simplify some of the code below.  */
912 #define HASARENA FALSE
913 #else
914 #define HASARENA TRUE
915 #endif
916 #define NOARENA FALSE
917
918 /* Size the arenas to exactly fit a given number of bodies.  A count
919    of 0 fits the max number bodies into a PERL_ARENA_SIZE.block,
920    simplifying the default.  If count > 0, the arena is sized to fit
921    only that many bodies, allowing arenas to be used for large, rare
922    bodies (XPVFM, XPVIO) without undue waste.  The arena size is
923    limited by PERL_ARENA_SIZE, so we can safely oversize the
924    declarations.
925  */
926 #define FIT_ARENA0(body_size)                           \
927     ((size_t)(PERL_ARENA_SIZE / body_size) * body_size)
928 #define FIT_ARENAn(count,body_size)                     \
929     ( count * body_size <= PERL_ARENA_SIZE)             \
930     ? count * body_size                                 \
931     : FIT_ARENA0 (body_size)
932 #define FIT_ARENA(count,body_size)                      \
933     count                                               \
934     ? FIT_ARENAn (count, body_size)                     \
935     : FIT_ARENA0 (body_size)
936
937 /* Calculate the length to copy. Specifically work out the length less any
938    final padding the compiler needed to add.  See the comment in sv_upgrade
939    for why copying the padding proved to be a bug.  */
940
941 #define copy_length(type, last_member) \
942         STRUCT_OFFSET(type, last_member) \
943         + sizeof (((type*)SvANY((const SV *)0))->last_member)
944
945 static const struct body_details bodies_by_type[] = {
946     /* HEs use this offset for their arena.  */
947     { 0, 0, 0, SVt_NULL, FALSE, NONV, NOARENA, 0 },
948
949     /* IVs are in the head, so the allocation size is 0.  */
950     { 0,
951       sizeof(IV), /* This is used to copy out the IV body.  */
952       STRUCT_OFFSET(XPVIV, xiv_iv), SVt_IV, FALSE, NONV,
953       NOARENA /* IVS don't need an arena  */, 0
954     },
955
956     { sizeof(NV), sizeof(NV),
957       STRUCT_OFFSET(XPVNV, xnv_u),
958       SVt_NV, FALSE, HADNV, HASARENA, FIT_ARENA(0, sizeof(NV)) },
959
960     { sizeof(XPV) - STRUCT_OFFSET(XPV, xpv_cur),
961       copy_length(XPV, xpv_len) - STRUCT_OFFSET(XPV, xpv_cur),
962       + STRUCT_OFFSET(XPV, xpv_cur),
963       SVt_PV, FALSE, NONV, HASARENA,
964       FIT_ARENA(0, sizeof(XPV) - STRUCT_OFFSET(XPV, xpv_cur)) },
965
966     { sizeof(XINVLIST) - STRUCT_OFFSET(XPV, xpv_cur),
967       copy_length(XINVLIST, is_offset) - STRUCT_OFFSET(XPV, xpv_cur),
968       + STRUCT_OFFSET(XPV, xpv_cur),
969       SVt_INVLIST, TRUE, NONV, HASARENA,
970       FIT_ARENA(0, sizeof(XINVLIST) - STRUCT_OFFSET(XPV, xpv_cur)) },
971
972     { sizeof(XPVIV) - STRUCT_OFFSET(XPV, xpv_cur),
973       copy_length(XPVIV, xiv_u) - STRUCT_OFFSET(XPV, xpv_cur),
974       + STRUCT_OFFSET(XPV, xpv_cur),
975       SVt_PVIV, FALSE, NONV, HASARENA,
976       FIT_ARENA(0, sizeof(XPVIV) - STRUCT_OFFSET(XPV, xpv_cur)) },
977
978     { sizeof(XPVNV) - STRUCT_OFFSET(XPV, xpv_cur),
979       copy_length(XPVNV, xnv_u) - STRUCT_OFFSET(XPV, xpv_cur),
980       + STRUCT_OFFSET(XPV, xpv_cur),
981       SVt_PVNV, FALSE, HADNV, HASARENA,
982       FIT_ARENA(0, sizeof(XPVNV) - STRUCT_OFFSET(XPV, xpv_cur)) },
983
984     { sizeof(XPVMG), copy_length(XPVMG, xnv_u), 0, SVt_PVMG, FALSE, HADNV,
985       HASARENA, FIT_ARENA(0, sizeof(XPVMG)) },
986
987     { sizeof(regexp),
988       sizeof(regexp),
989       0,
990       SVt_REGEXP, TRUE, NONV, HASARENA,
991       FIT_ARENA(0, sizeof(regexp))
992     },
993
994     { sizeof(XPVGV), sizeof(XPVGV), 0, SVt_PVGV, TRUE, HADNV,
995       HASARENA, FIT_ARENA(0, sizeof(XPVGV)) },
996     
997     { sizeof(XPVLV), sizeof(XPVLV), 0, SVt_PVLV, TRUE, HADNV,
998       HASARENA, FIT_ARENA(0, sizeof(XPVLV)) },
999
1000     { sizeof(XPVAV),
1001       copy_length(XPVAV, xav_alloc),
1002       0,
1003       SVt_PVAV, TRUE, NONV, HASARENA,
1004       FIT_ARENA(0, sizeof(XPVAV)) },
1005
1006     { sizeof(XPVHV),
1007       copy_length(XPVHV, xhv_max),
1008       0,
1009       SVt_PVHV, TRUE, NONV, HASARENA,
1010       FIT_ARENA(0, sizeof(XPVHV)) },
1011
1012     { sizeof(XPVCV),
1013       sizeof(XPVCV),
1014       0,
1015       SVt_PVCV, TRUE, NONV, HASARENA,
1016       FIT_ARENA(0, sizeof(XPVCV)) },
1017
1018     { sizeof(XPVFM),
1019       sizeof(XPVFM),
1020       0,
1021       SVt_PVFM, TRUE, NONV, NOARENA,
1022       FIT_ARENA(20, sizeof(XPVFM)) },
1023
1024     { sizeof(XPVIO),
1025       sizeof(XPVIO),
1026       0,
1027       SVt_PVIO, TRUE, NONV, HASARENA,
1028       FIT_ARENA(24, sizeof(XPVIO)) },
1029 };
1030
1031 #define new_body_allocated(sv_type)             \
1032     (void *)((char *)S_new_body(aTHX_ sv_type)  \
1033              - bodies_by_type[sv_type].offset)
1034
1035 /* return a thing to the free list */
1036
1037 #define del_body(thing, root)                           \
1038     STMT_START {                                        \
1039         void ** const thing_copy = (void **)thing;      \
1040         *thing_copy = *root;                            \
1041         *root = (void*)thing_copy;                      \
1042     } STMT_END
1043
1044 #ifdef PURIFY
1045
1046 #define new_XNV()       safemalloc(sizeof(XPVNV))
1047 #define new_XPVNV()     safemalloc(sizeof(XPVNV))
1048 #define new_XPVMG()     safemalloc(sizeof(XPVMG))
1049
1050 #define del_XPVGV(p)    safefree(p)
1051
1052 #else /* !PURIFY */
1053
1054 #define new_XNV()       new_body_allocated(SVt_NV)
1055 #define new_XPVNV()     new_body_allocated(SVt_PVNV)
1056 #define new_XPVMG()     new_body_allocated(SVt_PVMG)
1057
1058 #define del_XPVGV(p)    del_body(p + bodies_by_type[SVt_PVGV].offset,   \
1059                                  &PL_body_roots[SVt_PVGV])
1060
1061 #endif /* PURIFY */
1062
1063 /* no arena for you! */
1064
1065 #define new_NOARENA(details) \
1066         safemalloc((details)->body_size + (details)->offset)
1067 #define new_NOARENAZ(details) \
1068         safecalloc((details)->body_size + (details)->offset, 1)
1069
1070 void *
1071 Perl_more_bodies (pTHX_ const svtype sv_type, const size_t body_size,
1072                   const size_t arena_size)
1073 {
1074     dVAR;
1075     void ** const root = &PL_body_roots[sv_type];
1076     struct arena_desc *adesc;
1077     struct arena_set *aroot = (struct arena_set *) PL_body_arenas;
1078     unsigned int curr;
1079     char *start;
1080     const char *end;
1081     const size_t good_arena_size = Perl_malloc_good_size(arena_size);
1082 #if defined(DEBUGGING) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
1083     static bool done_sanity_check;
1084
1085     /* PERL_GLOBAL_STRUCT_PRIVATE cannot coexist with global
1086      * variables like done_sanity_check. */
1087     if (!done_sanity_check) {
1088         unsigned int i = SVt_LAST;
1089
1090         done_sanity_check = TRUE;
1091
1092         while (i--)
1093             assert (bodies_by_type[i].type == i);
1094     }
1095 #endif
1096
1097     assert(arena_size);
1098
1099     /* may need new arena-set to hold new arena */
1100     if (!aroot || aroot->curr >= aroot->set_size) {
1101         struct arena_set *newroot;
1102         Newxz(newroot, 1, struct arena_set);
1103         newroot->set_size = ARENAS_PER_SET;
1104         newroot->next = aroot;
1105         aroot = newroot;
1106         PL_body_arenas = (void *) newroot;
1107         DEBUG_m(PerlIO_printf(Perl_debug_log, "new arenaset %p\n", (void*)aroot));
1108     }
1109
1110     /* ok, now have arena-set with at least 1 empty/available arena-desc */
1111     curr = aroot->curr++;
1112     adesc = &(aroot->set[curr]);
1113     assert(!adesc->arena);
1114     
1115     Newx(adesc->arena, good_arena_size, char);
1116     adesc->size = good_arena_size;
1117     adesc->utype = sv_type;
1118     DEBUG_m(PerlIO_printf(Perl_debug_log, "arena %d added: %p size %"UVuf"\n", 
1119                           curr, (void*)adesc->arena, (UV)good_arena_size));
1120
1121     start = (char *) adesc->arena;
1122
1123     /* Get the address of the byte after the end of the last body we can fit.
1124        Remember, this is integer division:  */
1125     end = start + good_arena_size / body_size * body_size;
1126
1127     /* computed count doesn't reflect the 1st slot reservation */
1128 #if defined(MYMALLOC) || defined(HAS_MALLOC_GOOD_SIZE)
1129     DEBUG_m(PerlIO_printf(Perl_debug_log,
1130                           "arena %p end %p arena-size %d (from %d) type %d "
1131                           "size %d ct %d\n",
1132                           (void*)start, (void*)end, (int)good_arena_size,
1133                           (int)arena_size, sv_type, (int)body_size,
1134                           (int)good_arena_size / (int)body_size));
1135 #else
1136     DEBUG_m(PerlIO_printf(Perl_debug_log,
1137                           "arena %p end %p arena-size %d type %d size %d ct %d\n",
1138                           (void*)start, (void*)end,
1139                           (int)arena_size, sv_type, (int)body_size,
1140                           (int)good_arena_size / (int)body_size));
1141 #endif
1142     *root = (void *)start;
1143
1144     while (1) {
1145         /* Where the next body would start:  */
1146         char * const next = start + body_size;
1147
1148         if (next >= end) {
1149             /* This is the last body:  */
1150             assert(next == end);
1151
1152             *(void **)start = 0;
1153             return *root;
1154         }
1155
1156         *(void**) start = (void *)next;
1157         start = next;
1158     }
1159 }
1160
1161 /* grab a new thing from the free list, allocating more if necessary.
1162    The inline version is used for speed in hot routines, and the
1163    function using it serves the rest (unless PURIFY).
1164 */
1165 #define new_body_inline(xpv, sv_type) \
1166     STMT_START { \
1167         void ** const r3wt = &PL_body_roots[sv_type]; \
1168         xpv = (PTR_TBL_ENT_t*) (*((void **)(r3wt))      \
1169           ? *((void **)(r3wt)) : Perl_more_bodies(aTHX_ sv_type, \
1170                                              bodies_by_type[sv_type].body_size,\
1171                                              bodies_by_type[sv_type].arena_size)); \
1172         *(r3wt) = *(void**)(xpv); \
1173     } STMT_END
1174
1175 #ifndef PURIFY
1176
1177 STATIC void *
1178 S_new_body(pTHX_ const svtype sv_type)
1179 {
1180     dVAR;
1181     void *xpv;
1182     new_body_inline(xpv, sv_type);
1183     return xpv;
1184 }
1185
1186 #endif
1187
1188 static const struct body_details fake_rv =
1189     { 0, 0, 0, SVt_IV, FALSE, NONV, NOARENA, 0 };
1190
1191 /*
1192 =for apidoc sv_upgrade
1193
1194 Upgrade an SV to a more complex form.  Generally adds a new body type to the
1195 SV, then copies across as much information as possible from the old body.
1196 It croaks if the SV is already in a more complex form than requested.  You
1197 generally want to use the C<SvUPGRADE> macro wrapper, which checks the type
1198 before calling C<sv_upgrade>, and hence does not croak.  See also
1199 C<svtype>.
1200
1201 =cut
1202 */
1203
1204 void
1205 Perl_sv_upgrade(pTHX_ SV *const sv, svtype new_type)
1206 {
1207     dVAR;
1208     void*       old_body;
1209     void*       new_body;
1210     const svtype old_type = SvTYPE(sv);
1211     const struct body_details *new_type_details;
1212     const struct body_details *old_type_details
1213         = bodies_by_type + old_type;
1214     SV *referant = NULL;
1215
1216     PERL_ARGS_ASSERT_SV_UPGRADE;
1217
1218     if (old_type == new_type)
1219         return;
1220
1221     /* This clause was purposefully added ahead of the early return above to
1222        the shared string hackery for (sort {$a <=> $b} keys %hash), with the
1223        inference by Nick I-S that it would fix other troublesome cases. See
1224        changes 7162, 7163 (f130fd4589cf5fbb24149cd4db4137c8326f49c1 and parent)
1225
1226        Given that shared hash key scalars are no longer PVIV, but PV, there is
1227        no longer need to unshare so as to free up the IVX slot for its proper
1228        purpose. So it's safe to move the early return earlier.  */
1229
1230     if (new_type > SVt_PVMG && SvIsCOW(sv)) {
1231         sv_force_normal_flags(sv, 0);
1232     }
1233
1234     old_body = SvANY(sv);
1235
1236     /* Copying structures onto other structures that have been neatly zeroed
1237        has a subtle gotcha. Consider XPVMG
1238
1239        +------+------+------+------+------+-------+-------+
1240        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |
1241        +------+------+------+------+------+-------+-------+
1242        0      4      8     12     16     20      24      28
1243
1244        where NVs are aligned to 8 bytes, so that sizeof that structure is
1245        actually 32 bytes long, with 4 bytes of padding at the end:
1246
1247        +------+------+------+------+------+-------+-------+------+
1248        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH | ???  |
1249        +------+------+------+------+------+-------+-------+------+
1250        0      4      8     12     16     20      24      28     32
1251
1252        so what happens if you allocate memory for this structure:
1253
1254        +------+------+------+------+------+-------+-------+------+------+...
1255        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |  GP  | NAME |
1256        +------+------+------+------+------+-------+-------+------+------+...
1257        0      4      8     12     16     20      24      28     32     36
1258
1259        zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
1260        expect, because you copy the area marked ??? onto GP. Now, ??? may have
1261        started out as zero once, but it's quite possible that it isn't. So now,
1262        rather than a nicely zeroed GP, you have it pointing somewhere random.
1263        Bugs ensue.
1264
1265        (In fact, GP ends up pointing at a previous GP structure, because the
1266        principle cause of the padding in XPVMG getting garbage is a copy of
1267        sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob. Right now
1268        this happens to be moot because XPVGV has been re-ordered, with GP
1269        no longer after STASH)
1270
1271        So we are careful and work out the size of used parts of all the
1272        structures.  */
1273
1274     switch (old_type) {
1275     case SVt_NULL:
1276         break;
1277     case SVt_IV:
1278         if (SvROK(sv)) {
1279             referant = SvRV(sv);
1280             old_type_details = &fake_rv;
1281             if (new_type == SVt_NV)
1282                 new_type = SVt_PVNV;
1283         } else {
1284             if (new_type < SVt_PVIV) {
1285                 new_type = (new_type == SVt_NV)
1286                     ? SVt_PVNV : SVt_PVIV;
1287             }
1288         }
1289         break;
1290     case SVt_NV:
1291         if (new_type < SVt_PVNV) {
1292             new_type = SVt_PVNV;
1293         }
1294         break;
1295     case SVt_PV:
1296         assert(new_type > SVt_PV);
1297         assert(SVt_IV < SVt_PV);
1298         assert(SVt_NV < SVt_PV);
1299         break;
1300     case SVt_PVIV:
1301         break;
1302     case SVt_PVNV:
1303         break;
1304     case SVt_PVMG:
1305         /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1306            there's no way that it can be safely upgraded, because perl.c
1307            expects to Safefree(SvANY(PL_mess_sv))  */
1308         assert(sv != PL_mess_sv);
1309         /* This flag bit is used to mean other things in other scalar types.
1310            Given that it only has meaning inside the pad, it shouldn't be set
1311            on anything that can get upgraded.  */
1312         assert(!SvPAD_TYPED(sv));
1313         break;
1314     default:
1315         if (UNLIKELY(old_type_details->cant_upgrade))
1316             Perl_croak(aTHX_ "Can't upgrade %s (%" UVuf ") to %" UVuf,
1317                        sv_reftype(sv, 0), (UV) old_type, (UV) new_type);
1318     }
1319
1320     if (UNLIKELY(old_type > new_type))
1321         Perl_croak(aTHX_ "sv_upgrade from type %d down to type %d",
1322                 (int)old_type, (int)new_type);
1323
1324     new_type_details = bodies_by_type + new_type;
1325
1326     SvFLAGS(sv) &= ~SVTYPEMASK;
1327     SvFLAGS(sv) |= new_type;
1328
1329     /* This can't happen, as SVt_NULL is <= all values of new_type, so one of
1330        the return statements above will have triggered.  */
1331     assert (new_type != SVt_NULL);
1332     switch (new_type) {
1333     case SVt_IV:
1334         assert(old_type == SVt_NULL);
1335         SvANY(sv) = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
1336         SvIV_set(sv, 0);
1337         return;
1338     case SVt_NV:
1339         assert(old_type == SVt_NULL);
1340         SvANY(sv) = new_XNV();
1341         SvNV_set(sv, 0);
1342         return;
1343     case SVt_PVHV:
1344     case SVt_PVAV:
1345         assert(new_type_details->body_size);
1346
1347 #ifndef PURIFY  
1348         assert(new_type_details->arena);
1349         assert(new_type_details->arena_size);
1350         /* This points to the start of the allocated area.  */
1351         new_body_inline(new_body, new_type);
1352         Zero(new_body, new_type_details->body_size, char);
1353         new_body = ((char *)new_body) - new_type_details->offset;
1354 #else
1355         /* We always allocated the full length item with PURIFY. To do this
1356            we fake things so that arena is false for all 16 types..  */
1357         new_body = new_NOARENAZ(new_type_details);
1358 #endif
1359         SvANY(sv) = new_body;
1360         if (new_type == SVt_PVAV) {
1361             AvMAX(sv)   = -1;
1362             AvFILLp(sv) = -1;
1363             AvREAL_only(sv);
1364             if (old_type_details->body_size) {
1365                 AvALLOC(sv) = 0;
1366             } else {
1367                 /* It will have been zeroed when the new body was allocated.
1368                    Lets not write to it, in case it confuses a write-back
1369                    cache.  */
1370             }
1371         } else {
1372             assert(!SvOK(sv));
1373             SvOK_off(sv);
1374 #ifndef NODEFAULT_SHAREKEYS
1375             HvSHAREKEYS_on(sv);         /* key-sharing on by default */
1376 #endif
1377             /* start with PERL_HASH_DEFAULT_HvMAX+1 buckets: */
1378             HvMAX(sv) = PERL_HASH_DEFAULT_HvMAX;
1379         }
1380
1381         /* SVt_NULL isn't the only thing upgraded to AV or HV.
1382            The target created by newSVrv also is, and it can have magic.
1383            However, it never has SvPVX set.
1384         */
1385         if (old_type == SVt_IV) {
1386             assert(!SvROK(sv));
1387         } else if (old_type >= SVt_PV) {
1388             assert(SvPVX_const(sv) == 0);
1389         }
1390
1391         if (old_type >= SVt_PVMG) {
1392             SvMAGIC_set(sv, ((XPVMG*)old_body)->xmg_u.xmg_magic);
1393             SvSTASH_set(sv, ((XPVMG*)old_body)->xmg_stash);
1394         } else {
1395             sv->sv_u.svu_array = NULL; /* or svu_hash  */
1396         }
1397         break;
1398
1399     case SVt_PVIV:
1400         /* XXX Is this still needed?  Was it ever needed?   Surely as there is
1401            no route from NV to PVIV, NOK can never be true  */
1402         assert(!SvNOKp(sv));
1403         assert(!SvNOK(sv));
1404     case SVt_PVIO:
1405     case SVt_PVFM:
1406     case SVt_PVGV:
1407     case SVt_PVCV:
1408     case SVt_PVLV:
1409     case SVt_INVLIST:
1410     case SVt_REGEXP:
1411     case SVt_PVMG:
1412     case SVt_PVNV:
1413     case SVt_PV:
1414
1415         assert(new_type_details->body_size);
1416         /* We always allocated the full length item with PURIFY. To do this
1417            we fake things so that arena is false for all 16 types..  */
1418         if(new_type_details->arena) {
1419             /* This points to the start of the allocated area.  */
1420             new_body_inline(new_body, new_type);
1421             Zero(new_body, new_type_details->body_size, char);
1422             new_body = ((char *)new_body) - new_type_details->offset;
1423         } else {
1424             new_body = new_NOARENAZ(new_type_details);
1425         }
1426         SvANY(sv) = new_body;
1427
1428         if (old_type_details->copy) {
1429             /* There is now the potential for an upgrade from something without
1430                an offset (PVNV or PVMG) to something with one (PVCV, PVFM)  */
1431             int offset = old_type_details->offset;
1432             int length = old_type_details->copy;
1433
1434             if (new_type_details->offset > old_type_details->offset) {
1435                 const int difference
1436                     = new_type_details->offset - old_type_details->offset;
1437                 offset += difference;
1438                 length -= difference;
1439             }
1440             assert (length >= 0);
1441                 
1442             Copy((char *)old_body + offset, (char *)new_body + offset, length,
1443                  char);
1444         }
1445
1446 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1447         /* If NV 0.0 is stores as all bits 0 then Zero() already creates a
1448          * correct 0.0 for us.  Otherwise, if the old body didn't have an
1449          * NV slot, but the new one does, then we need to initialise the
1450          * freshly created NV slot with whatever the correct bit pattern is
1451          * for 0.0  */
1452         if (old_type_details->zero_nv && !new_type_details->zero_nv
1453             && !isGV_with_GP(sv))
1454             SvNV_set(sv, 0);
1455 #endif
1456
1457         if (UNLIKELY(new_type == SVt_PVIO)) {
1458             IO * const io = MUTABLE_IO(sv);
1459             GV *iogv = gv_fetchpvs("IO::File::", GV_ADD, SVt_PVHV);
1460
1461             SvOBJECT_on(io);
1462             /* Clear the stashcache because a new IO could overrule a package
1463                name */
1464             DEBUG_o(Perl_deb(aTHX_ "sv_upgrade clearing PL_stashcache\n"));
1465             hv_clear(PL_stashcache);
1466
1467             SvSTASH_set(io, MUTABLE_HV(SvREFCNT_inc(GvHV(iogv))));
1468             IoPAGE_LEN(sv) = 60;
1469         }
1470         if (UNLIKELY(new_type == SVt_REGEXP))
1471             sv->sv_u.svu_rx = (regexp *)new_body;
1472         else if (old_type < SVt_PV) {
1473             /* referant will be NULL unless the old type was SVt_IV emulating
1474                SVt_RV */
1475             sv->sv_u.svu_rv = referant;
1476         }
1477         break;
1478     default:
1479         Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu",
1480                    (unsigned long)new_type);
1481     }
1482
1483     if (old_type > SVt_IV) {
1484 #ifdef PURIFY
1485         safefree(old_body);
1486 #else
1487         /* Note that there is an assumption that all bodies of types that
1488            can be upgraded came from arenas. Only the more complex non-
1489            upgradable types are allowed to be directly malloc()ed.  */
1490         assert(old_type_details->arena);
1491         del_body((void*)((char*)old_body + old_type_details->offset),
1492                  &PL_body_roots[old_type]);
1493 #endif
1494     }
1495 }
1496
1497 /*
1498 =for apidoc sv_backoff
1499
1500 Remove any string offset.  You should normally use the C<SvOOK_off> macro
1501 wrapper instead.
1502
1503 =cut
1504 */
1505
1506 int
1507 Perl_sv_backoff(pTHX_ SV *const sv)
1508 {
1509     STRLEN delta;
1510     const char * const s = SvPVX_const(sv);
1511
1512     PERL_ARGS_ASSERT_SV_BACKOFF;
1513     PERL_UNUSED_CONTEXT;
1514
1515     assert(SvOOK(sv));
1516     assert(SvTYPE(sv) != SVt_PVHV);
1517     assert(SvTYPE(sv) != SVt_PVAV);
1518
1519     SvOOK_offset(sv, delta);
1520     
1521     SvLEN_set(sv, SvLEN(sv) + delta);
1522     SvPV_set(sv, SvPVX(sv) - delta);
1523     Move(s, SvPVX(sv), SvCUR(sv)+1, char);
1524     SvFLAGS(sv) &= ~SVf_OOK;
1525     return 0;
1526 }
1527
1528 /*
1529 =for apidoc sv_grow
1530
1531 Expands the character buffer in the SV.  If necessary, uses C<sv_unref> and
1532 upgrades the SV to C<SVt_PV>.  Returns a pointer to the character buffer.
1533 Use the C<SvGROW> wrapper instead.
1534
1535 =cut
1536 */
1537
1538 static void S_sv_uncow(pTHX_ SV * const sv, const U32 flags);
1539
1540 char *
1541 Perl_sv_grow(pTHX_ SV *const sv, STRLEN newlen)
1542 {
1543     char *s;
1544
1545     PERL_ARGS_ASSERT_SV_GROW;
1546
1547     if (SvROK(sv))
1548         sv_unref(sv);
1549     if (SvTYPE(sv) < SVt_PV) {
1550         sv_upgrade(sv, SVt_PV);
1551         s = SvPVX_mutable(sv);
1552     }
1553     else if (SvOOK(sv)) {       /* pv is offset? */
1554         sv_backoff(sv);
1555         s = SvPVX_mutable(sv);
1556         if (newlen > SvLEN(sv))
1557             newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1558     }
1559     else
1560     {
1561         if (SvIsCOW(sv)) S_sv_uncow(aTHX_ sv, 0);
1562         s = SvPVX_mutable(sv);
1563     }
1564
1565 #ifdef PERL_NEW_COPY_ON_WRITE
1566     /* the new COW scheme uses SvPVX(sv)[SvLEN(sv)-1] (if spare)
1567      * to store the COW count. So in general, allocate one more byte than
1568      * asked for, to make it likely this byte is always spare: and thus
1569      * make more strings COW-able.
1570      * If the new size is a big power of two, don't bother: we assume the
1571      * caller wanted a nice 2^N sized block and will be annoyed at getting
1572      * 2^N+1 */
1573     if (newlen & 0xff)
1574         newlen++;
1575 #endif
1576
1577 #if defined(PERL_USE_MALLOC_SIZE) && defined(Perl_safesysmalloc_size)
1578 #define PERL_UNWARANTED_CHUMMINESS_WITH_MALLOC
1579 #endif
1580
1581     if (newlen > SvLEN(sv)) {           /* need more room? */
1582         STRLEN minlen = SvCUR(sv);
1583         minlen += (minlen >> PERL_STRLEN_EXPAND_SHIFT) + 10;
1584         if (newlen < minlen)
1585             newlen = minlen;
1586 #ifndef PERL_UNWARANTED_CHUMMINESS_WITH_MALLOC
1587         if (SvLEN(sv)) {
1588             newlen = PERL_STRLEN_ROUNDUP(newlen);
1589         }
1590 #endif
1591         if (SvLEN(sv) && s) {
1592             s = (char*)saferealloc(s, newlen);
1593         }
1594         else {
1595             s = (char*)safemalloc(newlen);
1596             if (SvPVX_const(sv) && SvCUR(sv)) {
1597                 Move(SvPVX_const(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1598             }
1599         }
1600         SvPV_set(sv, s);
1601 #ifdef PERL_UNWARANTED_CHUMMINESS_WITH_MALLOC
1602         /* Do this here, do it once, do it right, and then we will never get
1603            called back into sv_grow() unless there really is some growing
1604            needed.  */
1605         SvLEN_set(sv, Perl_safesysmalloc_size(s));
1606 #else
1607         SvLEN_set(sv, newlen);
1608 #endif
1609     }
1610     return s;
1611 }
1612
1613 /*
1614 =for apidoc sv_setiv
1615
1616 Copies an integer into the given SV, upgrading first if necessary.
1617 Does not handle 'set' magic.  See also C<sv_setiv_mg>.
1618
1619 =cut
1620 */
1621
1622 void
1623 Perl_sv_setiv(pTHX_ SV *const sv, const IV i)
1624 {
1625     dVAR;
1626
1627     PERL_ARGS_ASSERT_SV_SETIV;
1628
1629     SV_CHECK_THINKFIRST_COW_DROP(sv);
1630     switch (SvTYPE(sv)) {
1631     case SVt_NULL:
1632     case SVt_NV:
1633         sv_upgrade(sv, SVt_IV);
1634         break;
1635     case SVt_PV:
1636         sv_upgrade(sv, SVt_PVIV);
1637         break;
1638
1639     case SVt_PVGV:
1640         if (!isGV_with_GP(sv))
1641             break;
1642     case SVt_PVAV:
1643     case SVt_PVHV:
1644     case SVt_PVCV:
1645     case SVt_PVFM:
1646     case SVt_PVIO:
1647         /* diag_listed_as: Can't coerce %s to %s in %s */
1648         Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1649                    OP_DESC(PL_op));
1650     default: NOOP;
1651     }
1652     (void)SvIOK_only(sv);                       /* validate number */
1653     SvIV_set(sv, i);
1654     SvTAINT(sv);
1655 }
1656
1657 /*
1658 =for apidoc sv_setiv_mg
1659
1660 Like C<sv_setiv>, but also handles 'set' magic.
1661
1662 =cut
1663 */
1664
1665 void
1666 Perl_sv_setiv_mg(pTHX_ SV *const sv, const IV i)
1667 {
1668     PERL_ARGS_ASSERT_SV_SETIV_MG;
1669
1670     sv_setiv(sv,i);
1671     SvSETMAGIC(sv);
1672 }
1673
1674 /*
1675 =for apidoc sv_setuv
1676
1677 Copies an unsigned integer into the given SV, upgrading first if necessary.
1678 Does not handle 'set' magic.  See also C<sv_setuv_mg>.
1679
1680 =cut
1681 */
1682
1683 void
1684 Perl_sv_setuv(pTHX_ SV *const sv, const UV u)
1685 {
1686     PERL_ARGS_ASSERT_SV_SETUV;
1687
1688     /* With the if statement to ensure that integers are stored as IVs whenever
1689        possible:
1690        u=1.49  s=0.52  cu=72.49  cs=10.64  scripts=270  tests=20865
1691
1692        without
1693        u=1.35  s=0.47  cu=73.45  cs=11.43  scripts=270  tests=20865
1694
1695        If you wish to remove the following if statement, so that this routine
1696        (and its callers) always return UVs, please benchmark to see what the
1697        effect is. Modern CPUs may be different. Or may not :-)
1698     */
1699     if (u <= (UV)IV_MAX) {
1700        sv_setiv(sv, (IV)u);
1701        return;
1702     }
1703     sv_setiv(sv, 0);
1704     SvIsUV_on(sv);
1705     SvUV_set(sv, u);
1706 }
1707
1708 /*
1709 =for apidoc sv_setuv_mg
1710
1711 Like C<sv_setuv>, but also handles 'set' magic.
1712
1713 =cut
1714 */
1715
1716 void
1717 Perl_sv_setuv_mg(pTHX_ SV *const sv, const UV u)
1718 {
1719     PERL_ARGS_ASSERT_SV_SETUV_MG;
1720
1721     sv_setuv(sv,u);
1722     SvSETMAGIC(sv);
1723 }
1724
1725 /*
1726 =for apidoc sv_setnv
1727
1728 Copies a double into the given SV, upgrading first if necessary.
1729 Does not handle 'set' magic.  See also C<sv_setnv_mg>.
1730
1731 =cut
1732 */
1733
1734 void
1735 Perl_sv_setnv(pTHX_ SV *const sv, const NV num)
1736 {
1737     dVAR;
1738
1739     PERL_ARGS_ASSERT_SV_SETNV;
1740
1741     SV_CHECK_THINKFIRST_COW_DROP(sv);
1742     switch (SvTYPE(sv)) {
1743     case SVt_NULL:
1744     case SVt_IV:
1745         sv_upgrade(sv, SVt_NV);
1746         break;
1747     case SVt_PV:
1748     case SVt_PVIV:
1749         sv_upgrade(sv, SVt_PVNV);
1750         break;
1751
1752     case SVt_PVGV:
1753         if (!isGV_with_GP(sv))
1754             break;
1755     case SVt_PVAV:
1756     case SVt_PVHV:
1757     case SVt_PVCV:
1758     case SVt_PVFM:
1759     case SVt_PVIO:
1760         /* diag_listed_as: Can't coerce %s to %s in %s */
1761         Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
1762                    OP_DESC(PL_op));
1763     default: NOOP;
1764     }
1765     SvNV_set(sv, num);
1766     (void)SvNOK_only(sv);                       /* validate number */
1767     SvTAINT(sv);
1768 }
1769
1770 /*
1771 =for apidoc sv_setnv_mg
1772
1773 Like C<sv_setnv>, but also handles 'set' magic.
1774
1775 =cut
1776 */
1777
1778 void
1779 Perl_sv_setnv_mg(pTHX_ SV *const sv, const NV num)
1780 {
1781     PERL_ARGS_ASSERT_SV_SETNV_MG;
1782
1783     sv_setnv(sv,num);
1784     SvSETMAGIC(sv);
1785 }
1786
1787 /* Print an "isn't numeric" warning, using a cleaned-up,
1788  * printable version of the offending string
1789  */
1790
1791 STATIC void
1792 S_not_a_number(pTHX_ SV *const sv)
1793 {
1794      dVAR;
1795      SV *dsv;
1796      char tmpbuf[64];
1797      const char *pv;
1798
1799      PERL_ARGS_ASSERT_NOT_A_NUMBER;
1800
1801      if (DO_UTF8(sv)) {
1802           dsv = newSVpvs_flags("", SVs_TEMP);
1803           pv = sv_uni_display(dsv, sv, 10, UNI_DISPLAY_ISPRINT);
1804      } else {
1805           char *d = tmpbuf;
1806           const char * const limit = tmpbuf + sizeof(tmpbuf) - 8;
1807           /* each *s can expand to 4 chars + "...\0",
1808              i.e. need room for 8 chars */
1809         
1810           const char *s = SvPVX_const(sv);
1811           const char * const end = s + SvCUR(sv);
1812           for ( ; s < end && d < limit; s++ ) {
1813                int ch = *s & 0xFF;
1814                if (! isASCII(ch) && !isPRINT_LC(ch)) {
1815                     *d++ = 'M';
1816                     *d++ = '-';
1817
1818                     /* Map to ASCII "equivalent" of Latin1 */
1819                     ch = LATIN1_TO_NATIVE(NATIVE_TO_LATIN1(ch) & 127);
1820                }
1821                if (ch == '\n') {
1822                     *d++ = '\\';
1823                     *d++ = 'n';
1824                }
1825                else if (ch == '\r') {
1826                     *d++ = '\\';
1827                     *d++ = 'r';
1828                }
1829                else if (ch == '\f') {
1830                     *d++ = '\\';
1831                     *d++ = 'f';
1832                }
1833                else if (ch == '\\') {
1834                     *d++ = '\\';
1835                     *d++ = '\\';
1836                }
1837                else if (ch == '\0') {
1838                     *d++ = '\\';
1839                     *d++ = '0';
1840                }
1841                else if (isPRINT_LC(ch))
1842                     *d++ = ch;
1843                else {
1844                     *d++ = '^';
1845                     *d++ = toCTRL(ch);
1846                }
1847           }
1848           if (s < end) {
1849                *d++ = '.';
1850                *d++ = '.';
1851                *d++ = '.';
1852           }
1853           *d = '\0';
1854           pv = tmpbuf;
1855     }
1856
1857     if (PL_op)
1858         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1859                     /* diag_listed_as: Argument "%s" isn't numeric%s */
1860                     "Argument \"%s\" isn't numeric in %s", pv,
1861                     OP_DESC(PL_op));
1862     else
1863         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1864                     /* diag_listed_as: Argument "%s" isn't numeric%s */
1865                     "Argument \"%s\" isn't numeric", pv);
1866 }
1867
1868 /*
1869 =for apidoc looks_like_number
1870
1871 Test if the content of an SV looks like a number (or is a number).
1872 C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1873 non-numeric warning), even if your atof() doesn't grok them.  Get-magic is
1874 ignored.
1875
1876 =cut
1877 */
1878
1879 I32
1880 Perl_looks_like_number(pTHX_ SV *const sv)
1881 {
1882     const char *sbegin;
1883     STRLEN len;
1884
1885     PERL_ARGS_ASSERT_LOOKS_LIKE_NUMBER;
1886
1887     if (SvPOK(sv) || SvPOKp(sv)) {
1888         sbegin = SvPV_nomg_const(sv, len);
1889     }
1890     else
1891         return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
1892     return grok_number(sbegin, len, NULL);
1893 }
1894
1895 STATIC bool
1896 S_glob_2number(pTHX_ GV * const gv)
1897 {
1898     PERL_ARGS_ASSERT_GLOB_2NUMBER;
1899
1900     /* We know that all GVs stringify to something that is not-a-number,
1901         so no need to test that.  */
1902     if (ckWARN(WARN_NUMERIC))
1903     {
1904         SV *const buffer = sv_newmortal();
1905         gv_efullname3(buffer, gv, "*");
1906         not_a_number(buffer);
1907     }
1908     /* We just want something true to return, so that S_sv_2iuv_common
1909         can tail call us and return true.  */
1910     return TRUE;
1911 }
1912
1913 /* Actually, ISO C leaves conversion of UV to IV undefined, but
1914    until proven guilty, assume that things are not that bad... */
1915
1916 /*
1917    NV_PRESERVES_UV:
1918
1919    As 64 bit platforms often have an NV that doesn't preserve all bits of
1920    an IV (an assumption perl has been based on to date) it becomes necessary
1921    to remove the assumption that the NV always carries enough precision to
1922    recreate the IV whenever needed, and that the NV is the canonical form.
1923    Instead, IV/UV and NV need to be given equal rights. So as to not lose
1924    precision as a side effect of conversion (which would lead to insanity
1925    and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1926    1) to distinguish between IV/UV/NV slots that have cached a valid
1927       conversion where precision was lost and IV/UV/NV slots that have a
1928       valid conversion which has lost no precision
1929    2) to ensure that if a numeric conversion to one form is requested that
1930       would lose precision, the precise conversion (or differently
1931       imprecise conversion) is also performed and cached, to prevent
1932       requests for different numeric formats on the same SV causing
1933       lossy conversion chains. (lossless conversion chains are perfectly
1934       acceptable (still))
1935
1936
1937    flags are used:
1938    SvIOKp is true if the IV slot contains a valid value
1939    SvIOK  is true only if the IV value is accurate (UV if SvIOK_UV true)
1940    SvNOKp is true if the NV slot contains a valid value
1941    SvNOK  is true only if the NV value is accurate
1942
1943    so
1944    while converting from PV to NV, check to see if converting that NV to an
1945    IV(or UV) would lose accuracy over a direct conversion from PV to
1946    IV(or UV). If it would, cache both conversions, return NV, but mark
1947    SV as IOK NOKp (ie not NOK).
1948
1949    While converting from PV to IV, check to see if converting that IV to an
1950    NV would lose accuracy over a direct conversion from PV to NV. If it
1951    would, cache both conversions, flag similarly.
1952
1953    Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1954    correctly because if IV & NV were set NV *always* overruled.
1955    Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1956    changes - now IV and NV together means that the two are interchangeable:
1957    SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
1958
1959    The benefit of this is that operations such as pp_add know that if
1960    SvIOK is true for both left and right operands, then integer addition
1961    can be used instead of floating point (for cases where the result won't
1962    overflow). Before, floating point was always used, which could lead to
1963    loss of precision compared with integer addition.
1964
1965    * making IV and NV equal status should make maths accurate on 64 bit
1966      platforms
1967    * may speed up maths somewhat if pp_add and friends start to use
1968      integers when possible instead of fp. (Hopefully the overhead in
1969      looking for SvIOK and checking for overflow will not outweigh the
1970      fp to integer speedup)
1971    * will slow down integer operations (callers of SvIV) on "inaccurate"
1972      values, as the change from SvIOK to SvIOKp will cause a call into
1973      sv_2iv each time rather than a macro access direct to the IV slot
1974    * should speed up number->string conversion on integers as IV is
1975      favoured when IV and NV are equally accurate
1976
1977    ####################################################################
1978    You had better be using SvIOK_notUV if you want an IV for arithmetic:
1979    SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
1980    On the other hand, SvUOK is true iff UV.
1981    ####################################################################
1982
1983    Your mileage will vary depending your CPU's relative fp to integer
1984    performance ratio.
1985 */
1986
1987 #ifndef NV_PRESERVES_UV
1988 #  define IS_NUMBER_UNDERFLOW_IV 1
1989 #  define IS_NUMBER_UNDERFLOW_UV 2
1990 #  define IS_NUMBER_IV_AND_UV    2
1991 #  define IS_NUMBER_OVERFLOW_IV  4
1992 #  define IS_NUMBER_OVERFLOW_UV  5
1993
1994 /* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
1995
1996 /* For sv_2nv these three cases are "SvNOK and don't bother casting"  */
1997 STATIC int
1998 S_sv_2iuv_non_preserve(pTHX_ SV *const sv
1999 #  ifdef DEBUGGING
2000                        , I32 numtype
2001 #  endif
2002                        )
2003 {
2004     dVAR;
2005
2006     PERL_ARGS_ASSERT_SV_2IUV_NON_PRESERVE;
2007
2008     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));
2009     if (SvNVX(sv) < (NV)IV_MIN) {
2010         (void)SvIOKp_on(sv);
2011         (void)SvNOK_on(sv);
2012         SvIV_set(sv, IV_MIN);
2013         return IS_NUMBER_UNDERFLOW_IV;
2014     }
2015     if (SvNVX(sv) > (NV)UV_MAX) {
2016         (void)SvIOKp_on(sv);
2017         (void)SvNOK_on(sv);
2018         SvIsUV_on(sv);
2019         SvUV_set(sv, UV_MAX);
2020         return IS_NUMBER_OVERFLOW_UV;
2021     }
2022     (void)SvIOKp_on(sv);
2023     (void)SvNOK_on(sv);
2024     /* Can't use strtol etc to convert this string.  (See truth table in
2025        sv_2iv  */
2026     if (SvNVX(sv) <= (UV)IV_MAX) {
2027         SvIV_set(sv, I_V(SvNVX(sv)));
2028         if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2029             SvIOK_on(sv); /* Integer is precise. NOK, IOK */
2030         } else {
2031             /* Integer is imprecise. NOK, IOKp */
2032         }
2033         return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
2034     }
2035     SvIsUV_on(sv);
2036     SvUV_set(sv, U_V(SvNVX(sv)));
2037     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2038         if (SvUVX(sv) == UV_MAX) {
2039             /* As we know that NVs don't preserve UVs, UV_MAX cannot
2040                possibly be preserved by NV. Hence, it must be overflow.
2041                NOK, IOKp */
2042             return IS_NUMBER_OVERFLOW_UV;
2043         }
2044         SvIOK_on(sv); /* Integer is precise. NOK, UOK */
2045     } else {
2046         /* Integer is imprecise. NOK, IOKp */
2047     }
2048     return IS_NUMBER_OVERFLOW_IV;
2049 }
2050 #endif /* !NV_PRESERVES_UV*/
2051
2052 STATIC bool
2053 S_sv_2iuv_common(pTHX_ SV *const sv)
2054 {
2055     dVAR;
2056
2057     PERL_ARGS_ASSERT_SV_2IUV_COMMON;
2058
2059     if (SvNOKp(sv)) {
2060         /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
2061          * without also getting a cached IV/UV from it at the same time
2062          * (ie PV->NV conversion should detect loss of accuracy and cache
2063          * IV or UV at same time to avoid this. */
2064         /* IV-over-UV optimisation - choose to cache IV if possible */
2065
2066         if (SvTYPE(sv) == SVt_NV)
2067             sv_upgrade(sv, SVt_PVNV);
2068
2069         (void)SvIOKp_on(sv);    /* Must do this first, to clear any SvOOK */
2070         /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
2071            certainly cast into the IV range at IV_MAX, whereas the correct
2072            answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
2073            cases go to UV */
2074 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
2075         if (Perl_isnan(SvNVX(sv))) {
2076             SvUV_set(sv, 0);
2077             SvIsUV_on(sv);
2078             return FALSE;
2079         }
2080 #endif
2081         if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2082             SvIV_set(sv, I_V(SvNVX(sv)));
2083             if (SvNVX(sv) == (NV) SvIVX(sv)
2084 #ifndef NV_PRESERVES_UV
2085                 && (((UV)1 << NV_PRESERVES_UV_BITS) >
2086                     (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2087                 /* Don't flag it as "accurately an integer" if the number
2088                    came from a (by definition imprecise) NV operation, and
2089                    we're outside the range of NV integer precision */
2090 #endif
2091                 ) {
2092                 if (SvNOK(sv))
2093                     SvIOK_on(sv);  /* Can this go wrong with rounding? NWC */
2094                 else {
2095                     /* scalar has trailing garbage, eg "42a" */
2096                 }
2097                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2098                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
2099                                       PTR2UV(sv),
2100                                       SvNVX(sv),
2101                                       SvIVX(sv)));
2102
2103             } else {
2104                 /* IV not precise.  No need to convert from PV, as NV
2105                    conversion would already have cached IV if it detected
2106                    that PV->IV would be better than PV->NV->IV
2107                    flags already correct - don't set public IOK.  */
2108                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2109                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
2110                                       PTR2UV(sv),
2111                                       SvNVX(sv),
2112                                       SvIVX(sv)));
2113             }
2114             /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2115                but the cast (NV)IV_MIN rounds to a the value less (more
2116                negative) than IV_MIN which happens to be equal to SvNVX ??
2117                Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2118                NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2119                (NV)UVX == NVX are both true, but the values differ. :-(
2120                Hopefully for 2s complement IV_MIN is something like
2121                0x8000000000000000 which will be exact. NWC */
2122         }
2123         else {
2124             SvUV_set(sv, U_V(SvNVX(sv)));
2125             if (
2126                 (SvNVX(sv) == (NV) SvUVX(sv))
2127 #ifndef  NV_PRESERVES_UV
2128                 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2129                 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2130                 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2131                 /* Don't flag it as "accurately an integer" if the number
2132                    came from a (by definition imprecise) NV operation, and
2133                    we're outside the range of NV integer precision */
2134 #endif
2135                 && SvNOK(sv)
2136                 )
2137                 SvIOK_on(sv);
2138             SvIsUV_on(sv);
2139             DEBUG_c(PerlIO_printf(Perl_debug_log,
2140                                   "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
2141                                   PTR2UV(sv),
2142                                   SvUVX(sv),
2143                                   SvUVX(sv)));
2144         }
2145     }
2146     else if (SvPOKp(sv)) {
2147         UV value;
2148         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2149         /* We want to avoid a possible problem when we cache an IV/ a UV which
2150            may be later translated to an NV, and the resulting NV is not
2151            the same as the direct translation of the initial string
2152            (eg 123.456 can shortcut to the IV 123 with atol(), but we must
2153            be careful to ensure that the value with the .456 is around if the
2154            NV value is requested in the future).
2155         
2156            This means that if we cache such an IV/a UV, we need to cache the
2157            NV as well.  Moreover, we trade speed for space, and do not
2158            cache the NV if we are sure it's not needed.
2159          */
2160
2161         /* SVt_PVNV is one higher than SVt_PVIV, hence this order  */
2162         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2163              == IS_NUMBER_IN_UV) {
2164             /* It's definitely an integer, only upgrade to PVIV */
2165             if (SvTYPE(sv) < SVt_PVIV)
2166                 sv_upgrade(sv, SVt_PVIV);
2167             (void)SvIOK_on(sv);
2168         } else if (SvTYPE(sv) < SVt_PVNV)
2169             sv_upgrade(sv, SVt_PVNV);
2170
2171         /* If NVs preserve UVs then we only use the UV value if we know that
2172            we aren't going to call atof() below. If NVs don't preserve UVs
2173            then the value returned may have more precision than atof() will
2174            return, even though value isn't perfectly accurate.  */
2175         if ((numtype & (IS_NUMBER_IN_UV
2176 #ifdef NV_PRESERVES_UV
2177                         | IS_NUMBER_NOT_INT
2178 #endif
2179             )) == IS_NUMBER_IN_UV) {
2180             /* This won't turn off the public IOK flag if it was set above  */
2181             (void)SvIOKp_on(sv);
2182
2183             if (!(numtype & IS_NUMBER_NEG)) {
2184                 /* positive */;
2185                 if (value <= (UV)IV_MAX) {
2186                     SvIV_set(sv, (IV)value);
2187                 } else {
2188                     /* it didn't overflow, and it was positive. */
2189                     SvUV_set(sv, value);
2190                     SvIsUV_on(sv);
2191                 }
2192             } else {
2193                 /* 2s complement assumption  */
2194                 if (value <= (UV)IV_MIN) {
2195                     SvIV_set(sv, -(IV)value);
2196                 } else {
2197                     /* Too negative for an IV.  This is a double upgrade, but
2198                        I'm assuming it will be rare.  */
2199                     if (SvTYPE(sv) < SVt_PVNV)
2200                         sv_upgrade(sv, SVt_PVNV);
2201                     SvNOK_on(sv);
2202                     SvIOK_off(sv);
2203                     SvIOKp_on(sv);
2204                     SvNV_set(sv, -(NV)value);
2205                     SvIV_set(sv, IV_MIN);
2206                 }
2207             }
2208         }
2209         /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2210            will be in the previous block to set the IV slot, and the next
2211            block to set the NV slot.  So no else here.  */
2212         
2213         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2214             != IS_NUMBER_IN_UV) {
2215             /* It wasn't an (integer that doesn't overflow the UV). */
2216             SvNV_set(sv, Atof(SvPVX_const(sv)));
2217
2218             if (! numtype && ckWARN(WARN_NUMERIC))
2219                 not_a_number(sv);
2220
2221 #if defined(USE_LONG_DOUBLE)
2222             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" PERL_PRIgldbl ")\n",
2223                                   PTR2UV(sv), SvNVX(sv)));
2224 #else
2225             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"NVgf")\n",
2226                                   PTR2UV(sv), SvNVX(sv)));
2227 #endif
2228
2229 #ifdef NV_PRESERVES_UV
2230             (void)SvIOKp_on(sv);
2231             (void)SvNOK_on(sv);
2232             if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2233                 SvIV_set(sv, I_V(SvNVX(sv)));
2234                 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2235                     SvIOK_on(sv);
2236                 } else {
2237                     NOOP;  /* Integer is imprecise. NOK, IOKp */
2238                 }
2239                 /* UV will not work better than IV */
2240             } else {
2241                 if (SvNVX(sv) > (NV)UV_MAX) {
2242                     SvIsUV_on(sv);
2243                     /* Integer is inaccurate. NOK, IOKp, is UV */
2244                     SvUV_set(sv, UV_MAX);
2245                 } else {
2246                     SvUV_set(sv, U_V(SvNVX(sv)));
2247                     /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2248                        NV preservse UV so can do correct comparison.  */
2249                     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2250                         SvIOK_on(sv);
2251                     } else {
2252                         NOOP;   /* Integer is imprecise. NOK, IOKp, is UV */
2253                     }
2254                 }
2255                 SvIsUV_on(sv);
2256             }
2257 #else /* NV_PRESERVES_UV */
2258             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2259                 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2260                 /* The IV/UV slot will have been set from value returned by
2261                    grok_number above.  The NV slot has just been set using
2262                    Atof.  */
2263                 SvNOK_on(sv);
2264                 assert (SvIOKp(sv));
2265             } else {
2266                 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2267                     U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2268                     /* Small enough to preserve all bits. */
2269                     (void)SvIOKp_on(sv);
2270                     SvNOK_on(sv);
2271                     SvIV_set(sv, I_V(SvNVX(sv)));
2272                     if ((NV)(SvIVX(sv)) == SvNVX(sv))
2273                         SvIOK_on(sv);
2274                     /* Assumption: first non-preserved integer is < IV_MAX,
2275                        this NV is in the preserved range, therefore: */
2276                     if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2277                           < (UV)IV_MAX)) {
2278                         Perl_croak(aTHX_ "sv_2iv assumed (U_V(fabs((double)SvNVX(sv))) < (UV)IV_MAX) but SvNVX(sv)=%"NVgf" U_V is 0x%"UVxf", IV_MAX is 0x%"UVxf"\n", SvNVX(sv), U_V(SvNVX(sv)), (UV)IV_MAX);
2279                     }
2280                 } else {
2281                     /* IN_UV NOT_INT
2282                          0      0       already failed to read UV.
2283                          0      1       already failed to read UV.
2284                          1      0       you won't get here in this case. IV/UV
2285                                         slot set, public IOK, Atof() unneeded.
2286                          1      1       already read UV.
2287                        so there's no point in sv_2iuv_non_preserve() attempting
2288                        to use atol, strtol, strtoul etc.  */
2289 #  ifdef DEBUGGING
2290                     sv_2iuv_non_preserve (sv, numtype);
2291 #  else
2292                     sv_2iuv_non_preserve (sv);
2293 #  endif
2294                 }
2295             }
2296 #endif /* NV_PRESERVES_UV */
2297         /* It might be more code efficient to go through the entire logic above
2298            and conditionally set with SvIOKp_on() rather than SvIOK(), but it
2299            gets complex and potentially buggy, so more programmer efficient
2300            to do it this way, by turning off the public flags:  */
2301         if (!numtype)
2302             SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2303         }
2304     }
2305     else  {
2306         if (isGV_with_GP(sv))
2307             return glob_2number(MUTABLE_GV(sv));
2308
2309         if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2310                 report_uninit(sv);
2311         if (SvTYPE(sv) < SVt_IV)
2312             /* Typically the caller expects that sv_any is not NULL now.  */
2313             sv_upgrade(sv, SVt_IV);
2314         /* Return 0 from the caller.  */
2315         return TRUE;
2316     }
2317     return FALSE;
2318 }
2319
2320 /*
2321 =for apidoc sv_2iv_flags
2322
2323 Return the integer value of an SV, doing any necessary string
2324 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2325 Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2326
2327 =cut
2328 */
2329
2330 IV
2331 Perl_sv_2iv_flags(pTHX_ SV *const sv, const I32 flags)
2332 {
2333     dVAR;
2334
2335     PERL_ARGS_ASSERT_SV_2IV_FLAGS;
2336
2337     assert (SvTYPE(sv) != SVt_PVAV && SvTYPE(sv) != SVt_PVHV
2338          && SvTYPE(sv) != SVt_PVFM);
2339
2340     if (SvGMAGICAL(sv) && (flags & SV_GMAGIC))
2341         mg_get(sv);
2342
2343     if (SvROK(sv)) {
2344         if (SvAMAGIC(sv)) {
2345             SV * tmpstr;
2346             if (flags & SV_SKIP_OVERLOAD)
2347                 return 0;
2348             tmpstr = AMG_CALLunary(sv, numer_amg);
2349             if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2350                 return SvIV(tmpstr);
2351             }
2352         }
2353         return PTR2IV(SvRV(sv));
2354     }
2355
2356     if (SvVALID(sv) || isREGEXP(sv)) {
2357         /* FBMs use the space for SvIVX and SvNVX for other purposes, and use
2358            the same flag bit as SVf_IVisUV, so must not let them cache IVs.
2359            In practice they are extremely unlikely to actually get anywhere
2360            accessible by user Perl code - the only way that I'm aware of is when
2361            a constant subroutine which is used as the second argument to index.
2362
2363            Regexps have no SvIVX and SvNVX fields.
2364         */
2365         assert(isREGEXP(sv) || SvPOKp(sv));
2366         {
2367             UV value;
2368             const char * const ptr =
2369                 isREGEXP(sv) ? RX_WRAPPED((REGEXP*)sv) : SvPVX_const(sv);
2370             const int numtype
2371                 = grok_number(ptr, SvCUR(sv), &value);
2372
2373             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2374                 == IS_NUMBER_IN_UV) {
2375                 /* It's definitely an integer */
2376                 if (numtype & IS_NUMBER_NEG) {
2377                     if (value < (UV)IV_MIN)
2378                         return -(IV)value;
2379                 } else {
2380                     if (value < (UV)IV_MAX)
2381                         return (IV)value;
2382                 }
2383             }
2384             if (!numtype) {
2385                 if (ckWARN(WARN_NUMERIC))
2386                     not_a_number(sv);
2387             }
2388             return I_V(Atof(ptr));
2389         }
2390     }
2391
2392     if (SvTHINKFIRST(sv)) {
2393 #ifdef PERL_OLD_COPY_ON_WRITE
2394         if (SvIsCOW(sv)) {
2395             sv_force_normal_flags(sv, 0);
2396         }
2397 #endif
2398         if (SvREADONLY(sv) && !SvOK(sv)) {
2399             if (ckWARN(WARN_UNINITIALIZED))
2400                 report_uninit(sv);
2401             return 0;
2402         }
2403     }
2404
2405     if (!SvIOKp(sv)) {
2406         if (S_sv_2iuv_common(aTHX_ sv))
2407             return 0;
2408     }
2409
2410     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2411         PTR2UV(sv),SvIVX(sv)));
2412     return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
2413 }
2414
2415 /*
2416 =for apidoc sv_2uv_flags
2417
2418 Return the unsigned integer value of an SV, doing any necessary string
2419 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2420 Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
2421
2422 =cut
2423 */
2424
2425 UV
2426 Perl_sv_2uv_flags(pTHX_ SV *const sv, const I32 flags)
2427 {
2428     dVAR;
2429
2430     PERL_ARGS_ASSERT_SV_2UV_FLAGS;
2431
2432     if (SvGMAGICAL(sv) && (flags & SV_GMAGIC))
2433         mg_get(sv);
2434
2435     if (SvROK(sv)) {
2436         if (SvAMAGIC(sv)) {
2437             SV *tmpstr;
2438             if (flags & SV_SKIP_OVERLOAD)
2439                 return 0;
2440             tmpstr = AMG_CALLunary(sv, numer_amg);
2441             if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2442                 return SvUV(tmpstr);
2443             }
2444         }
2445         return PTR2UV(SvRV(sv));
2446     }
2447
2448     if (SvVALID(sv) || isREGEXP(sv)) {
2449         /* FBMs use the space for SvIVX and SvNVX for other purposes, and use
2450            the same flag bit as SVf_IVisUV, so must not let them cache IVs.  
2451            Regexps have no SvIVX and SvNVX fields. */
2452         assert(isREGEXP(sv) || SvPOKp(sv));
2453         {
2454             UV value;
2455             const char * const ptr =
2456                 isREGEXP(sv) ? RX_WRAPPED((REGEXP*)sv) : SvPVX_const(sv);
2457             const int numtype
2458                 = grok_number(ptr, SvCUR(sv), &value);
2459
2460             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2461                 == IS_NUMBER_IN_UV) {
2462                 /* It's definitely an integer */
2463                 if (!(numtype & IS_NUMBER_NEG))
2464                     return value;
2465             }
2466             if (!numtype) {
2467                 if (ckWARN(WARN_NUMERIC))
2468                     not_a_number(sv);
2469             }
2470             return U_V(Atof(ptr));
2471         }
2472     }
2473
2474     if (SvTHINKFIRST(sv)) {
2475 #ifdef PERL_OLD_COPY_ON_WRITE
2476         if (SvIsCOW(sv)) {
2477             sv_force_normal_flags(sv, 0);
2478         }
2479 #endif
2480         if (SvREADONLY(sv) && !SvOK(sv)) {
2481             if (ckWARN(WARN_UNINITIALIZED))
2482                 report_uninit(sv);
2483             return 0;
2484         }
2485     }
2486
2487     if (!SvIOKp(sv)) {
2488         if (S_sv_2iuv_common(aTHX_ sv))
2489             return 0;
2490     }
2491
2492     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2493                           PTR2UV(sv),SvUVX(sv)));
2494     return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
2495 }
2496
2497 /*
2498 =for apidoc sv_2nv_flags
2499
2500 Return the num value of an SV, doing any necessary string or integer
2501 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2502 Normally used via the C<SvNV(sv)> and C<SvNVx(sv)> macros.
2503
2504 =cut
2505 */
2506
2507 NV
2508 Perl_sv_2nv_flags(pTHX_ SV *const sv, const I32 flags)
2509 {
2510     dVAR;
2511
2512     PERL_ARGS_ASSERT_SV_2NV_FLAGS;
2513
2514     assert (SvTYPE(sv) != SVt_PVAV && SvTYPE(sv) != SVt_PVHV
2515          && SvTYPE(sv) != SVt_PVFM);
2516     if (SvGMAGICAL(sv) || SvVALID(sv) || isREGEXP(sv)) {
2517         /* FBMs use the space for SvIVX and SvNVX for other purposes, and use
2518            the same flag bit as SVf_IVisUV, so must not let them cache NVs.
2519            Regexps have no SvIVX and SvNVX fields.  */
2520         const char *ptr;
2521         if (flags & SV_GMAGIC)
2522             mg_get(sv);
2523         if (SvNOKp(sv))
2524             return SvNVX(sv);
2525         if (SvPOKp(sv) && !SvIOKp(sv)) {
2526             ptr = SvPVX_const(sv);
2527           grokpv:
2528             if (!SvIOKp(sv) && ckWARN(WARN_NUMERIC) &&
2529                 !grok_number(ptr, SvCUR(sv), NULL))
2530                 not_a_number(sv);
2531             return Atof(ptr);
2532         }
2533         if (SvIOKp(sv)) {
2534             if (SvIsUV(sv))
2535                 return (NV)SvUVX(sv);
2536             else
2537                 return (NV)SvIVX(sv);
2538         }
2539         if (SvROK(sv)) {
2540             goto return_rok;
2541         }
2542         if (isREGEXP(sv)) {
2543             ptr = RX_WRAPPED((REGEXP *)sv);
2544             goto grokpv;
2545         }
2546         assert(SvTYPE(sv) >= SVt_PVMG);
2547         /* This falls through to the report_uninit near the end of the
2548            function. */
2549     } else if (SvTHINKFIRST(sv)) {
2550         if (SvROK(sv)) {
2551         return_rok:
2552             if (SvAMAGIC(sv)) {
2553                 SV *tmpstr;
2554                 if (flags & SV_SKIP_OVERLOAD)
2555                     return 0;
2556                 tmpstr = AMG_CALLunary(sv, numer_amg);
2557                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2558                     return SvNV(tmpstr);
2559                 }
2560             }
2561             return PTR2NV(SvRV(sv));
2562         }
2563 #ifdef PERL_OLD_COPY_ON_WRITE
2564         if (SvIsCOW(sv)) {
2565             sv_force_normal_flags(sv, 0);
2566         }
2567 #endif
2568         if (SvREADONLY(sv) && !SvOK(sv)) {
2569             if (ckWARN(WARN_UNINITIALIZED))
2570                 report_uninit(sv);
2571             return 0.0;
2572         }
2573     }
2574     if (SvTYPE(sv) < SVt_NV) {
2575         /* The logic to use SVt_PVNV if necessary is in sv_upgrade.  */
2576         sv_upgrade(sv, SVt_NV);
2577 #ifdef USE_LONG_DOUBLE
2578         DEBUG_c({
2579             STORE_NUMERIC_LOCAL_SET_STANDARD();
2580             PerlIO_printf(Perl_debug_log,
2581                           "0x%"UVxf" num(%" PERL_PRIgldbl ")\n",
2582                           PTR2UV(sv), SvNVX(sv));
2583             RESTORE_NUMERIC_LOCAL();
2584         });
2585 #else
2586         DEBUG_c({
2587             STORE_NUMERIC_LOCAL_SET_STANDARD();
2588             PerlIO_printf(Perl_debug_log, "0x%"UVxf" num(%"NVgf")\n",
2589                           PTR2UV(sv), SvNVX(sv));
2590             RESTORE_NUMERIC_LOCAL();
2591         });
2592 #endif
2593     }
2594     else if (SvTYPE(sv) < SVt_PVNV)
2595         sv_upgrade(sv, SVt_PVNV);
2596     if (SvNOKp(sv)) {
2597         return SvNVX(sv);
2598     }
2599     if (SvIOKp(sv)) {
2600         SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
2601 #ifdef NV_PRESERVES_UV
2602         if (SvIOK(sv))
2603             SvNOK_on(sv);
2604         else
2605             SvNOKp_on(sv);
2606 #else
2607         /* Only set the public NV OK flag if this NV preserves the IV  */
2608         /* Check it's not 0xFFFFFFFFFFFFFFFF */
2609         if (SvIOK(sv) &&
2610             SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
2611                        : (SvIVX(sv) == I_V(SvNVX(sv))))
2612             SvNOK_on(sv);
2613         else
2614             SvNOKp_on(sv);
2615 #endif
2616     }
2617     else if (SvPOKp(sv)) {
2618         UV value;
2619         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2620         if (!SvIOKp(sv) && !numtype && ckWARN(WARN_NUMERIC))
2621             not_a_number(sv);
2622 #ifdef NV_PRESERVES_UV
2623         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2624             == IS_NUMBER_IN_UV) {
2625             /* It's definitely an integer */
2626             SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
2627         } else
2628             SvNV_set(sv, Atof(SvPVX_const(sv)));
2629         if (numtype)
2630             SvNOK_on(sv);
2631         else
2632             SvNOKp_on(sv);
2633 #else
2634         SvNV_set(sv, Atof(SvPVX_const(sv)));
2635         /* Only set the public NV OK flag if this NV preserves the value in
2636            the PV at least as well as an IV/UV would.
2637            Not sure how to do this 100% reliably. */
2638         /* if that shift count is out of range then Configure's test is
2639            wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2640            UV_BITS */
2641         if (((UV)1 << NV_PRESERVES_UV_BITS) >
2642             U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2643             SvNOK_on(sv); /* Definitely small enough to preserve all bits */
2644         } else if (!(numtype & IS_NUMBER_IN_UV)) {
2645             /* Can't use strtol etc to convert this string, so don't try.
2646                sv_2iv and sv_2uv will use the NV to convert, not the PV.  */
2647             SvNOK_on(sv);
2648         } else {
2649             /* value has been set.  It may not be precise.  */
2650             if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2651                 /* 2s complement assumption for (UV)IV_MIN  */
2652                 SvNOK_on(sv); /* Integer is too negative.  */
2653             } else {
2654                 SvNOKp_on(sv);
2655                 SvIOKp_on(sv);
2656
2657                 if (numtype & IS_NUMBER_NEG) {
2658                     SvIV_set(sv, -(IV)value);
2659                 } else if (value <= (UV)IV_MAX) {
2660                     SvIV_set(sv, (IV)value);
2661                 } else {
2662                     SvUV_set(sv, value);
2663                     SvIsUV_on(sv);
2664                 }
2665
2666                 if (numtype & IS_NUMBER_NOT_INT) {
2667                     /* I believe that even if the original PV had decimals,
2668                        they are lost beyond the limit of the FP precision.
2669                        However, neither is canonical, so both only get p
2670                        flags.  NWC, 2000/11/25 */
2671                     /* Both already have p flags, so do nothing */
2672                 } else {
2673                     const NV nv = SvNVX(sv);
2674                     if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2675                         if (SvIVX(sv) == I_V(nv)) {
2676                             SvNOK_on(sv);
2677                         } else {
2678                             /* It had no "." so it must be integer.  */
2679                         }
2680                         SvIOK_on(sv);
2681                     } else {
2682                         /* between IV_MAX and NV(UV_MAX).
2683                            Could be slightly > UV_MAX */
2684
2685                         if (numtype & IS_NUMBER_NOT_INT) {
2686                             /* UV and NV both imprecise.  */
2687                         } else {
2688                             const UV nv_as_uv = U_V(nv);
2689
2690                             if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2691                                 SvNOK_on(sv);
2692                             }
2693                             SvIOK_on(sv);
2694                         }
2695                     }
2696                 }
2697             }
2698         }
2699         /* It might be more code efficient to go through the entire logic above
2700            and conditionally set with SvNOKp_on() rather than SvNOK(), but it
2701            gets complex and potentially buggy, so more programmer efficient
2702            to do it this way, by turning off the public flags:  */
2703         if (!numtype)
2704             SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2705 #endif /* NV_PRESERVES_UV */
2706     }
2707     else  {
2708         if (isGV_with_GP(sv)) {
2709             glob_2number(MUTABLE_GV(sv));
2710             return 0.0;
2711         }
2712
2713         if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2714             report_uninit(sv);
2715         assert (SvTYPE(sv) >= SVt_NV);
2716         /* Typically the caller expects that sv_any is not NULL now.  */
2717         /* XXX Ilya implies that this is a bug in callers that assume this
2718            and ideally should be fixed.  */
2719         return 0.0;
2720     }
2721 #if defined(USE_LONG_DOUBLE)
2722     DEBUG_c({
2723         STORE_NUMERIC_LOCAL_SET_STANDARD();
2724         PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" PERL_PRIgldbl ")\n",
2725                       PTR2UV(sv), SvNVX(sv));
2726         RESTORE_NUMERIC_LOCAL();
2727     });
2728 #else
2729     DEBUG_c({
2730         STORE_NUMERIC_LOCAL_SET_STANDARD();
2731         PerlIO_printf(Perl_debug_log, "0x%"UVxf" 1nv(%"NVgf")\n",
2732                       PTR2UV(sv), SvNVX(sv));
2733         RESTORE_NUMERIC_LOCAL();
2734     });
2735 #endif
2736     return SvNVX(sv);
2737 }
2738
2739 /*
2740 =for apidoc sv_2num
2741
2742 Return an SV with the numeric value of the source SV, doing any necessary
2743 reference or overload conversion.  You must use the C<SvNUM(sv)> macro to
2744 access this function.
2745
2746 =cut
2747 */
2748
2749 SV *
2750 Perl_sv_2num(pTHX_ SV *const sv)
2751 {
2752     PERL_ARGS_ASSERT_SV_2NUM;
2753
2754     if (!SvROK(sv))
2755         return sv;
2756     if (SvAMAGIC(sv)) {
2757         SV * const tmpsv = AMG_CALLunary(sv, numer_amg);
2758         TAINT_IF(tmpsv && SvTAINTED(tmpsv));
2759         if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
2760             return sv_2num(tmpsv);
2761     }
2762     return sv_2mortal(newSVuv(PTR2UV(SvRV(sv))));
2763 }
2764
2765 /* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2766  * UV as a string towards the end of buf, and return pointers to start and
2767  * end of it.
2768  *
2769  * We assume that buf is at least TYPE_CHARS(UV) long.
2770  */
2771
2772 static char *
2773 S_uiv_2buf(char *const buf, const IV iv, UV uv, const int is_uv, char **const peob)
2774 {
2775     char *ptr = buf + TYPE_CHARS(UV);
2776     char * const ebuf = ptr;
2777     int sign;
2778
2779     PERL_ARGS_ASSERT_UIV_2BUF;
2780
2781     if (is_uv)
2782         sign = 0;
2783     else if (iv >= 0) {
2784         uv = iv;
2785         sign = 0;
2786     } else {
2787         uv = -iv;
2788         sign = 1;
2789     }
2790     do {
2791         *--ptr = '0' + (char)(uv % 10);
2792     } while (uv /= 10);
2793     if (sign)
2794         *--ptr = '-';
2795     *peob = ebuf;
2796     return ptr;
2797 }
2798
2799 /*
2800 =for apidoc sv_2pv_flags
2801
2802 Returns a pointer to the string value of an SV, and sets *lp to its length.
2803 If flags includes SV_GMAGIC, does an mg_get() first.  Coerces sv to a
2804 string if necessary.  Normally invoked via the C<SvPV_flags> macro.
2805 C<sv_2pv()> and C<sv_2pv_nomg> usually end up here too.
2806
2807 =cut
2808 */
2809
2810 char *
2811 Perl_sv_2pv_flags(pTHX_ SV *const sv, STRLEN *const lp, const I32 flags)
2812 {
2813     dVAR;
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 typestr = sv_reftype(referent, 0);
2883                 const STRLEN typelen = strlen(typestr);
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, typestr, 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         char buf[TYPE_CHARS(UV)];
2961         char *ebuf, *ptr;
2962         STRLEN len;
2963
2964         if (SvTYPE(sv) < SVt_PVIV)
2965             sv_upgrade(sv, SVt_PVIV);
2966         ptr = uiv_2buf(buf, SvIVX(sv), SvUVX(sv), isUIOK, &ebuf);
2967         len = ebuf - ptr;
2968         /* inlined from sv_setpvn */
2969         s = SvGROW_mutable(sv, len + 1);
2970         Move(ptr, s, len, char);
2971         s += len;
2972         *s = '\0';
2973         SvPOK_on(sv);
2974     }
2975     else if (SvNOK(sv)) {
2976         if (SvTYPE(sv) < SVt_PVNV)
2977             sv_upgrade(sv, SVt_PVNV);
2978         if (SvNVX(sv) == 0.0) {
2979             s = SvGROW_mutable(sv, 2);
2980             *s++ = '0';
2981             *s = '\0';
2982         } else {
2983             dSAVE_ERRNO;
2984             /* The +20 is pure guesswork.  Configure test needed. --jhi */
2985             s = SvGROW_mutable(sv, NV_DIG + 20);
2986             /* some Xenix systems wipe out errno here */
2987
2988 #ifndef USE_LOCALE_NUMERIC
2989             PERL_UNUSED_RESULT(Gconvert(SvNVX(sv), NV_DIG, 0, s));
2990             SvPOK_on(sv);
2991 #else
2992             {
2993                 DECLARE_STORE_LC_NUMERIC_SET_TO_NEEDED();
2994                 PERL_UNUSED_RESULT(Gconvert(SvNVX(sv), NV_DIG, 0, s));
2995
2996                 /* If the radix character is UTF-8, and actually is in the
2997                  * output, turn on the UTF-8 flag for the scalar */
2998                 if (PL_numeric_local
2999                     && PL_numeric_radix_sv && SvUTF8(PL_numeric_radix_sv)
3000                     && instr(s, SvPVX_const(PL_numeric_radix_sv)))
3001                 {
3002                     SvUTF8_on(sv);
3003                 }
3004                 RESTORE_LC_NUMERIC();
3005             }
3006
3007             /* We don't call SvPOK_on(), because it may come to pass that the
3008              * locale changes so that the stringification we just did is no
3009              * longer correct.  We will have to re-stringify every time it is
3010              * needed */
3011 #endif
3012             RESTORE_ERRNO;
3013             while (*s) s++;
3014         }
3015     }
3016     else if (isGV_with_GP(sv)) {
3017         GV *const gv = MUTABLE_GV(sv);
3018         SV *const buffer = sv_newmortal();
3019
3020         gv_efullname3(buffer, gv, "*");
3021
3022         assert(SvPOK(buffer));
3023         if (SvUTF8(buffer))
3024             SvUTF8_on(sv);
3025         if (lp)
3026             *lp = SvCUR(buffer);
3027         return SvPVX(buffer);
3028     }
3029     else if (isREGEXP(sv)) {
3030         if (lp) *lp = RX_WRAPLEN((REGEXP *)sv);
3031         return RX_WRAPPED((REGEXP *)sv);
3032     }
3033     else {
3034         if (lp)
3035             *lp = 0;
3036         if (flags & SV_UNDEF_RETURNS_NULL)
3037             return NULL;
3038         if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
3039             report_uninit(sv);
3040         /* Typically the caller expects that sv_any is not NULL now.  */
3041         if (!SvREADONLY(sv) && SvTYPE(sv) < SVt_PV)
3042             sv_upgrade(sv, SVt_PV);
3043         return (char *)"";
3044     }
3045
3046     {
3047         const STRLEN len = s - SvPVX_const(sv);
3048         if (lp) 
3049             *lp = len;
3050         SvCUR_set(sv, len);
3051     }
3052     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
3053                           PTR2UV(sv),SvPVX_const(sv)));
3054     if (flags & SV_CONST_RETURN)
3055         return (char *)SvPVX_const(sv);
3056     if (flags & SV_MUTABLE_RETURN)
3057         return SvPVX_mutable(sv);
3058     return SvPVX(sv);
3059 }
3060
3061 /*
3062 =for apidoc sv_copypv
3063
3064 Copies a stringified representation of the source SV into the
3065 destination SV.  Automatically performs any necessary mg_get and
3066 coercion of numeric values into strings.  Guaranteed to preserve
3067 UTF8 flag even from overloaded objects.  Similar in nature to
3068 sv_2pv[_flags] but operates directly on an SV instead of just the
3069 string.  Mostly uses sv_2pv_flags to do its work, except when that
3070 would lose the UTF-8'ness of the PV.
3071
3072 =for apidoc sv_copypv_nomg
3073
3074 Like sv_copypv, but doesn't invoke get magic first.
3075
3076 =for apidoc sv_copypv_flags
3077
3078 Implementation of sv_copypv and sv_copypv_nomg.  Calls get magic iff flags
3079 include SV_GMAGIC.
3080
3081 =cut
3082 */
3083
3084 void
3085 Perl_sv_copypv(pTHX_ SV *const dsv, SV *const ssv)
3086 {
3087     PERL_ARGS_ASSERT_SV_COPYPV;
3088
3089     sv_copypv_flags(dsv, ssv, 0);
3090 }
3091
3092 void
3093 Perl_sv_copypv_flags(pTHX_ SV *const dsv, SV *const ssv, const I32 flags)
3094 {
3095     STRLEN len;
3096     const char *s;
3097
3098     PERL_ARGS_ASSERT_SV_COPYPV_FLAGS;
3099
3100     if ((flags & SV_GMAGIC) && SvGMAGICAL(ssv))
3101         mg_get(ssv);
3102     s = SvPV_nomg_const(ssv,len);
3103     sv_setpvn(dsv,s,len);
3104     if (SvUTF8(ssv))
3105         SvUTF8_on(dsv);
3106     else
3107         SvUTF8_off(dsv);
3108 }
3109
3110 /*
3111 =for apidoc sv_2pvbyte
3112
3113 Return a pointer to the byte-encoded representation of the SV, and set *lp
3114 to its length.  May cause the SV to be downgraded from UTF-8 as a
3115 side-effect.
3116
3117 Usually accessed via the C<SvPVbyte> macro.
3118
3119 =cut
3120 */
3121
3122 char *
3123 Perl_sv_2pvbyte(pTHX_ SV *sv, STRLEN *const lp)
3124 {
3125     PERL_ARGS_ASSERT_SV_2PVBYTE;
3126
3127     SvGETMAGIC(sv);
3128     if (((SvREADONLY(sv) || SvFAKE(sv)) && !SvIsCOW(sv))
3129      || isGV_with_GP(sv) || SvROK(sv)) {
3130         SV *sv2 = sv_newmortal();
3131         sv_copypv_nomg(sv2,sv);
3132         sv = sv2;
3133     }
3134     sv_utf8_downgrade(sv,0);
3135     return lp ? SvPV_nomg(sv,*lp) : SvPV_nomg_nolen(sv);
3136 }
3137
3138 /*
3139 =for apidoc sv_2pvutf8
3140
3141 Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
3142 to its length.  May cause the SV to be upgraded to UTF-8 as a side-effect.
3143
3144 Usually accessed via the C<SvPVutf8> macro.
3145
3146 =cut
3147 */
3148
3149 char *
3150 Perl_sv_2pvutf8(pTHX_ SV *sv, STRLEN *const lp)
3151 {
3152     PERL_ARGS_ASSERT_SV_2PVUTF8;
3153
3154     if (((SvREADONLY(sv) || SvFAKE(sv)) && !SvIsCOW(sv))
3155      || isGV_with_GP(sv) || SvROK(sv))
3156         sv = sv_mortalcopy(sv);
3157     else
3158         SvGETMAGIC(sv);
3159     sv_utf8_upgrade_nomg(sv);
3160     return lp ? SvPV_nomg(sv,*lp) : SvPV_nomg_nolen(sv);
3161 }
3162
3163
3164 /*
3165 =for apidoc sv_2bool
3166
3167 This macro is only used by sv_true() or its macro equivalent, and only if
3168 the latter's argument is neither SvPOK, SvIOK nor SvNOK.
3169 It calls sv_2bool_flags with the SV_GMAGIC flag.
3170
3171 =for apidoc sv_2bool_flags
3172
3173 This function is only used by sv_true() and friends,  and only if
3174 the latter's argument is neither SvPOK, SvIOK nor SvNOK.  If the flags
3175 contain SV_GMAGIC, then it does an mg_get() first.
3176
3177
3178 =cut
3179 */
3180
3181 bool
3182 Perl_sv_2bool_flags(pTHX_ SV *sv, I32 flags)
3183 {
3184     dVAR;
3185
3186     PERL_ARGS_ASSERT_SV_2BOOL_FLAGS;
3187
3188     restart:
3189     if(flags & SV_GMAGIC) SvGETMAGIC(sv);
3190
3191     if (!SvOK(sv))
3192         return 0;
3193     if (SvROK(sv)) {
3194         if (SvAMAGIC(sv)) {
3195             SV * const tmpsv = AMG_CALLunary(sv, bool__amg);
3196             if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv)))) {
3197                 bool svb;
3198                 sv = tmpsv;
3199                 if(SvGMAGICAL(sv)) {
3200                     flags = SV_GMAGIC;
3201                     goto restart; /* call sv_2bool */
3202                 }
3203                 /* expanded SvTRUE_common(sv, (flags = 0, goto restart)) */
3204                 else if(!SvOK(sv)) {
3205                     svb = 0;
3206                 }
3207                 else if(SvPOK(sv)) {
3208                     svb = SvPVXtrue(sv);
3209                 }
3210                 else if((SvFLAGS(sv) & (SVf_IOK|SVf_NOK))) {
3211                     svb = (SvIOK(sv) && SvIVX(sv) != 0)
3212                         || (SvNOK(sv) && SvNVX(sv) != 0.0);
3213                 }
3214                 else {
3215                     flags = 0;
3216                     goto restart; /* call sv_2bool_nomg */
3217                 }
3218                 return cBOOL(svb);
3219             }
3220         }
3221         return SvRV(sv) != 0;
3222     }
3223     if (isREGEXP(sv))
3224         return
3225           RX_WRAPLEN(sv) > 1 || (RX_WRAPLEN(sv) && *RX_WRAPPED(sv) != '0');
3226     return SvTRUE_common(sv, isGV_with_GP(sv) ? 1 : 0);
3227 }
3228
3229 /*
3230 =for apidoc sv_utf8_upgrade
3231
3232 Converts the PV of an SV to its UTF-8-encoded form.
3233 Forces the SV to string form if it is not already.
3234 Will C<mg_get> on C<sv> if appropriate.
3235 Always sets the SvUTF8 flag to avoid future validity checks even
3236 if the whole string is the same in UTF-8 as not.
3237 Returns the number of bytes in the converted string
3238
3239 This is not a general purpose byte encoding to Unicode interface:
3240 use the Encode extension for that.
3241
3242 =for apidoc sv_utf8_upgrade_nomg
3243
3244 Like sv_utf8_upgrade, but doesn't do magic on C<sv>.
3245
3246 =for apidoc sv_utf8_upgrade_flags
3247
3248 Converts the PV of an SV to its UTF-8-encoded form.
3249 Forces the SV to string form if it is not already.
3250 Always sets the SvUTF8 flag to avoid future validity checks even
3251 if all the bytes are invariant in UTF-8.
3252 If C<flags> has C<SV_GMAGIC> bit set,
3253 will C<mg_get> on C<sv> if appropriate, else not.
3254
3255 If C<flags> has SV_FORCE_UTF8_UPGRADE set, this function assumes that the PV
3256 will expand when converted to UTF-8, and skips the extra work of checking for
3257 that.  Typically this flag is used by a routine that has already parsed the
3258 string and found such characters, and passes this information on so that the
3259 work doesn't have to be repeated.
3260
3261 Returns the number of bytes in the converted string.
3262
3263 This is not a general purpose byte encoding to Unicode interface:
3264 use the Encode extension for that.
3265
3266 =for apidoc sv_utf8_upgrade_flags_grow
3267
3268 Like sv_utf8_upgrade_flags, but has an additional parameter C<extra>, which is
3269 the number of unused bytes the string of 'sv' is guaranteed to have free after
3270 it upon return.  This allows the caller to reserve extra space that it intends
3271 to fill, to avoid extra grows.
3272
3273 C<sv_utf8_upgrade>, C<sv_utf8_upgrade_nomg>, and C<sv_utf8_upgrade_flags>
3274 are implemented in terms of this function.
3275
3276 Returns the number of bytes in the converted string (not including the spares).
3277
3278 =cut
3279
3280 (One might think that the calling routine could pass in the position of the
3281 first variant character when it has set SV_FORCE_UTF8_UPGRADE, so it wouldn't
3282 have to be found again.  But that is not the case, because typically when the
3283 caller is likely to use this flag, it won't be calling this routine unless it
3284 finds something that won't fit into a byte.  Otherwise it tries to not upgrade
3285 and just use bytes.  But some things that do fit into a byte are variants in
3286 utf8, and the caller may not have been keeping track of these.)
3287
3288 If the routine itself changes the string, it adds a trailing NUL.  Such a NUL
3289 isn't guaranteed due to having other routines do the work in some input cases,
3290 or if the input is already flagged as being in utf8.
3291
3292 The speed of this could perhaps be improved for many cases if someone wanted to
3293 write a fast function that counts the number of variant characters in a string,
3294 especially if it could return the position of the first one.
3295
3296 */
3297
3298 STRLEN
3299 Perl_sv_utf8_upgrade_flags_grow(pTHX_ SV *const sv, const I32 flags, STRLEN extra)
3300 {
3301     dVAR;
3302
3303     PERL_ARGS_ASSERT_SV_UTF8_UPGRADE_FLAGS_GROW;
3304
3305     if (sv == &PL_sv_undef)
3306         return 0;
3307     if (!SvPOK_nog(sv)) {
3308         STRLEN len = 0;
3309         if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
3310             (void) sv_2pv_flags(sv,&len, flags);
3311             if (SvUTF8(sv)) {
3312                 if (extra) SvGROW(sv, SvCUR(sv) + extra);
3313                 return len;
3314             }
3315         } else {
3316             (void) SvPV_force_flags(sv,len,flags & SV_GMAGIC);
3317         }
3318     }
3319
3320     if (SvUTF8(sv)) {
3321         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3322         return SvCUR(sv);
3323     }
3324
3325     if (SvIsCOW(sv)) {
3326         S_sv_uncow(aTHX_ sv, 0);
3327     }
3328
3329     if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING)) {
3330         sv_recode_to_utf8(sv, PL_encoding);
3331         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3332         return SvCUR(sv);
3333     }
3334
3335     if (SvCUR(sv) == 0) {
3336         if (extra) SvGROW(sv, extra);
3337     } else { /* Assume Latin-1/EBCDIC */
3338         /* This function could be much more efficient if we
3339          * had a FLAG in SVs to signal if there are any variant
3340          * chars in the PV.  Given that there isn't such a flag
3341          * make the loop as fast as possible (although there are certainly ways
3342          * to speed this up, eg. through vectorization) */
3343         U8 * s = (U8 *) SvPVX_const(sv);
3344         U8 * e = (U8 *) SvEND(sv);
3345         U8 *t = s;
3346         STRLEN two_byte_count = 0;
3347         
3348         if (flags & SV_FORCE_UTF8_UPGRADE) goto must_be_utf8;
3349
3350         /* See if really will need to convert to utf8.  We mustn't rely on our
3351          * incoming SV being well formed and having a trailing '\0', as certain
3352          * code in pp_formline can send us partially built SVs. */
3353
3354         while (t < e) {
3355             const U8 ch = *t++;
3356             if (NATIVE_BYTE_IS_INVARIANT(ch)) continue;
3357
3358             t--;    /* t already incremented; re-point to first variant */
3359             two_byte_count = 1;
3360             goto must_be_utf8;
3361         }
3362
3363         /* utf8 conversion not needed because all are invariants.  Mark as
3364          * UTF-8 even if no variant - saves scanning loop */
3365         SvUTF8_on(sv);
3366         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3367         return SvCUR(sv);
3368
3369 must_be_utf8:
3370
3371         /* Here, the string should be converted to utf8, either because of an
3372          * input flag (two_byte_count = 0), or because a character that
3373          * requires 2 bytes was found (two_byte_count = 1).  t points either to
3374          * the beginning of the string (if we didn't examine anything), or to
3375          * the first variant.  In either case, everything from s to t - 1 will
3376          * occupy only 1 byte each on output.
3377          *
3378          * There are two main ways to convert.  One is to create a new string
3379          * and go through the input starting from the beginning, appending each
3380          * converted value onto the new string as we go along.  It's probably
3381          * best to allocate enough space in the string for the worst possible
3382          * case rather than possibly running out of space and having to
3383          * reallocate and then copy what we've done so far.  Since everything
3384          * from s to t - 1 is invariant, the destination can be initialized
3385          * with these using a fast memory copy
3386          *
3387          * The other way is to figure out exactly how big the string should be
3388          * by parsing the entire input.  Then you don't have to make it big
3389          * enough to handle the worst possible case, and more importantly, if
3390          * the string you already have is large enough, you don't have to
3391          * allocate a new string, you can copy the last character in the input
3392          * string to the final position(s) that will be occupied by the
3393          * converted string and go backwards, stopping at t, since everything
3394          * before that is invariant.
3395          *
3396          * There are advantages and disadvantages to each method.
3397          *
3398          * In the first method, we can allocate a new string, do the memory
3399          * copy from the s to t - 1, and then proceed through the rest of the
3400          * string byte-by-byte.
3401          *
3402          * In the second method, we proceed through the rest of the input
3403          * string just calculating how big the converted string will be.  Then
3404          * there are two cases:
3405          *  1)  if the string has enough extra space to handle the converted
3406          *      value.  We go backwards through the string, converting until we
3407          *      get to the position we are at now, and then stop.  If this
3408          *      position is far enough along in the string, this method is
3409          *      faster than the other method.  If the memory copy were the same
3410          *      speed as the byte-by-byte loop, that position would be about
3411          *      half-way, as at the half-way mark, parsing to the end and back
3412          *      is one complete string's parse, the same amount as starting
3413          *      over and going all the way through.  Actually, it would be
3414          *      somewhat less than half-way, as it's faster to just count bytes
3415          *      than to also copy, and we don't have the overhead of allocating
3416          *      a new string, changing the scalar to use it, and freeing the
3417          *      existing one.  But if the memory copy is fast, the break-even
3418          *      point is somewhere after half way.  The counting loop could be
3419          *      sped up by vectorization, etc, to move the break-even point
3420          *      further towards the beginning.
3421          *  2)  if the string doesn't have enough space to handle the converted
3422          *      value.  A new string will have to be allocated, and one might
3423          *      as well, given that, start from the beginning doing the first
3424          *      method.  We've spent extra time parsing the string and in
3425          *      exchange all we've gotten is that we know precisely how big to
3426          *      make the new one.  Perl is more optimized for time than space,
3427          *      so this case is a loser.
3428          * So what I've decided to do is not use the 2nd method unless it is
3429          * guaranteed that a new string won't have to be allocated, assuming
3430          * the worst case.  I also decided not to put any more conditions on it
3431          * than this, for now.  It seems likely that, since the worst case is
3432          * twice as big as the unknown portion of the string (plus 1), we won't
3433          * be guaranteed enough space, causing us to go to the first method,
3434          * unless the string is short, or the first variant character is near
3435          * the end of it.  In either of these cases, it seems best to use the
3436          * 2nd method.  The only circumstance I can think of where this would
3437          * be really slower is if the string had once had much more data in it
3438          * than it does now, but there is still a substantial amount in it  */
3439
3440         {
3441             STRLEN invariant_head = t - s;
3442             STRLEN size = invariant_head + (e - t) * 2 + 1 + extra;
3443             if (SvLEN(sv) < size) {
3444
3445                 /* Here, have decided to allocate a new string */
3446
3447                 U8 *dst;
3448                 U8 *d;
3449
3450                 Newx(dst, size, U8);
3451
3452                 /* If no known invariants at the beginning of the input string,
3453                  * set so starts from there.  Otherwise, can use memory copy to
3454                  * get up to where we are now, and then start from here */
3455
3456                 if (invariant_head <= 0) {
3457                     d = dst;
3458                 } else {
3459                     Copy(s, dst, invariant_head, char);
3460                     d = dst + invariant_head;
3461                 }
3462
3463                 while (t < e) {
3464                     append_utf8_from_native_byte(*t, &d);
3465                     t++;
3466                 }
3467                 *d = '\0';
3468                 SvPV_free(sv); /* No longer using pre-existing string */
3469                 SvPV_set(sv, (char*)dst);
3470                 SvCUR_set(sv, d - dst);
3471                 SvLEN_set(sv, size);
3472             } else {
3473
3474                 /* Here, have decided to get the exact size of the string.
3475                  * Currently this happens only when we know that there is
3476                  * guaranteed enough space to fit the converted string, so
3477                  * don't have to worry about growing.  If two_byte_count is 0,
3478                  * then t points to the first byte of the string which hasn't
3479                  * been examined yet.  Otherwise two_byte_count is 1, and t
3480                  * points to the first byte in the string that will expand to
3481                  * two.  Depending on this, start examining at t or 1 after t.
3482                  * */
3483
3484                 U8 *d = t + two_byte_count;
3485
3486
3487                 /* Count up the remaining bytes that expand to two */
3488
3489                 while (d < e) {
3490                     const U8 chr = *d++;
3491                     if (! NATIVE_BYTE_IS_INVARIANT(chr)) two_byte_count++;
3492                 }
3493
3494                 /* The string will expand by just the number of bytes that
3495                  * occupy two positions.  But we are one afterwards because of
3496                  * the increment just above.  This is the place to put the
3497                  * trailing NUL, and to set the length before we decrement */
3498
3499                 d += two_byte_count;
3500                 SvCUR_set(sv, d - s);
3501                 *d-- = '\0';
3502
3503
3504                 /* Having decremented d, it points to the position to put the
3505                  * very last byte of the expanded string.  Go backwards through
3506                  * the string, copying and expanding as we go, stopping when we
3507                  * get to the part that is invariant the rest of the way down */
3508
3509                 e--;
3510                 while (e >= t) {
3511                     if (NATIVE_BYTE_IS_INVARIANT(*e)) {
3512                         *d-- = *e;
3513                     } else {
3514                         *d-- = UTF8_EIGHT_BIT_LO(*e);
3515                         *d-- = UTF8_EIGHT_BIT_HI(*e);
3516                     }
3517                     e--;
3518                 }
3519             }
3520
3521             if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3522                 /* Update pos. We do it at the end rather than during
3523                  * the upgrade, to avoid slowing down the common case
3524                  * (upgrade without pos).
3525                  * pos can be stored as either bytes or characters.  Since
3526                  * this was previously a byte string we can just turn off
3527                  * the bytes flag. */
3528                 MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3529                 if (mg) {
3530                     mg->mg_flags &= ~MGf_BYTES;
3531                 }
3532                 if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3533                     magic_setutf8(sv,mg); /* clear UTF8 cache */
3534             }
3535         }
3536     }
3537
3538     /* Mark as UTF-8 even if no variant - saves scanning loop */
3539     SvUTF8_on(sv);
3540     return SvCUR(sv);
3541 }
3542
3543 /*
3544 =for apidoc sv_utf8_downgrade
3545
3546 Attempts to convert the PV of an SV from characters to bytes.
3547 If the PV contains a character that cannot fit
3548 in a byte, this conversion will fail;
3549 in this case, either returns false or, if C<fail_ok> is not
3550 true, croaks.
3551
3552 This is not a general purpose Unicode to byte encoding interface:
3553 use the Encode extension for that.
3554
3555 =cut
3556 */
3557
3558 bool
3559 Perl_sv_utf8_downgrade(pTHX_ SV *const sv, const bool fail_ok)
3560 {
3561     dVAR;
3562
3563     PERL_ARGS_ASSERT_SV_UTF8_DOWNGRADE;
3564
3565     if (SvPOKp(sv) && SvUTF8(sv)) {
3566         if (SvCUR(sv)) {
3567             U8 *s;
3568             STRLEN len;
3569             int mg_flags = SV_GMAGIC;
3570
3571             if (SvIsCOW(sv)) {
3572                 S_sv_uncow(aTHX_ sv, 0);
3573             }
3574             if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3575                 /* update pos */
3576                 MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3577                 if (mg && mg->mg_len > 0 && mg->mg_flags & MGf_BYTES) {
3578                         mg->mg_len = sv_pos_b2u_flags(sv, mg->mg_len,
3579                                                 SV_GMAGIC|SV_CONST_RETURN);
3580                         mg_flags = 0; /* sv_pos_b2u does get magic */
3581                 }
3582                 if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3583                     magic_setutf8(sv,mg); /* clear UTF8 cache */
3584
3585             }
3586             s = (U8 *) SvPV_flags(sv, len, mg_flags);
3587
3588             if (!utf8_to_bytes(s, &len)) {
3589                 if (fail_ok)
3590                     return FALSE;
3591                 else {
3592                     if (PL_op)
3593                         Perl_croak(aTHX_ "Wide character in %s",
3594                                    OP_DESC(PL_op));
3595                     else
3596                         Perl_croak(aTHX_ "Wide character");
3597                 }
3598             }
3599             SvCUR_set(sv, len);
3600         }
3601     }
3602     SvUTF8_off(sv);
3603     return TRUE;
3604 }
3605
3606 /*
3607 =for apidoc sv_utf8_encode
3608
3609 Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3610 flag off so that it looks like octets again.
3611
3612 =cut
3613 */
3614
3615 void
3616 Perl_sv_utf8_encode(pTHX_ SV *const sv)
3617 {
3618     PERL_ARGS_ASSERT_SV_UTF8_ENCODE;
3619
3620     if (SvREADONLY(sv)) {
3621         sv_force_normal_flags(sv, 0);
3622     }
3623     (void) sv_utf8_upgrade(sv);
3624     SvUTF8_off(sv);
3625 }
3626
3627 /*
3628 =for apidoc sv_utf8_decode
3629
3630 If the PV of the SV is an octet sequence in UTF-8
3631 and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3632 so that it looks like a character.  If the PV contains only single-byte
3633 characters, the C<SvUTF8> flag stays off.
3634 Scans PV for validity and returns false if the PV is invalid UTF-8.
3635
3636 =cut
3637 */
3638
3639 bool
3640 Perl_sv_utf8_decode(pTHX_ SV *const sv)
3641 {
3642     PERL_ARGS_ASSERT_SV_UTF8_DECODE;
3643
3644     if (SvPOKp(sv)) {
3645         const U8 *start, *c;
3646         const U8 *e;
3647
3648         /* The octets may have got themselves encoded - get them back as
3649          * bytes
3650          */
3651         if (!sv_utf8_downgrade(sv, TRUE))
3652             return FALSE;
3653
3654         /* it is actually just a matter of turning the utf8 flag on, but
3655          * we want to make sure everything inside is valid utf8 first.
3656          */
3657         c = start = (const U8 *) SvPVX_const(sv);
3658         if (!is_utf8_string(c, SvCUR(sv)))
3659             return FALSE;
3660         e = (const U8 *) SvEND(sv);
3661         while (c < e) {
3662             const U8 ch = *c++;
3663             if (!UTF8_IS_INVARIANT(ch)) {
3664                 SvUTF8_on(sv);
3665                 break;
3666             }
3667         }
3668         if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3669             /* XXX Is this dead code?  XS_utf8_decode calls SvSETMAGIC
3670                    after this, clearing pos.  Does anything on CPAN
3671                    need this? */
3672             /* adjust pos to the start of a UTF8 char sequence */
3673             MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3674             if (mg) {
3675                 I32 pos = mg->mg_len;
3676                 if (pos > 0) {
3677                     for (c = start + pos; c > start; c--) {
3678                         if (UTF8_IS_START(*c))
3679                             break;
3680                     }
3681                     mg->mg_len  = c - start;
3682                 }
3683             }
3684             if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3685                 magic_setutf8(sv,mg); /* clear UTF8 cache */
3686         }
3687     }
3688     return TRUE;
3689 }
3690
3691 /*
3692 =for apidoc sv_setsv
3693
3694 Copies the contents of the source SV C<ssv> into the destination SV
3695 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3696 function if the source SV needs to be reused.  Does not handle 'set' magic on
3697 destination SV.  Calls 'get' magic on source SV.  Loosely speaking, it
3698 performs a copy-by-value, obliterating any previous content of the
3699 destination.
3700
3701 You probably want to use one of the assortment of wrappers, such as
3702 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3703 C<SvSetMagicSV_nosteal>.
3704
3705 =for apidoc sv_setsv_flags
3706
3707 Copies the contents of the source SV C<ssv> into the destination SV
3708 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3709 function if the source SV needs to be reused.  Does not handle 'set' magic.
3710 Loosely speaking, it performs a copy-by-value, obliterating any previous
3711 content of the destination.
3712 If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
3713 C<ssv> if appropriate, else not.  If the C<flags>
3714 parameter has the C<SV_NOSTEAL> bit set then the
3715 buffers of temps will not be stolen.  <sv_setsv>
3716 and C<sv_setsv_nomg> are implemented in terms of this function.
3717
3718 You probably want to use one of the assortment of wrappers, such as
3719 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3720 C<SvSetMagicSV_nosteal>.
3721
3722 This is the primary function for copying scalars, and most other
3723 copy-ish functions and macros use this underneath.
3724
3725 =cut
3726 */
3727
3728 static void
3729 S_glob_assign_glob(pTHX_ SV *const dstr, SV *const sstr, const int dtype)
3730 {
3731     I32 mro_changes = 0; /* 1 = method, 2 = isa, 3 = recursive isa */
3732     HV *old_stash = NULL;
3733
3734     PERL_ARGS_ASSERT_GLOB_ASSIGN_GLOB;
3735
3736     if (dtype != SVt_PVGV && !isGV_with_GP(dstr)) {
3737         const char * const name = GvNAME(sstr);
3738         const STRLEN len = GvNAMELEN(sstr);
3739         {
3740             if (dtype >= SVt_PV) {
3741                 SvPV_free(dstr);
3742                 SvPV_set(dstr, 0);
3743                 SvLEN_set(dstr, 0);
3744                 SvCUR_set(dstr, 0);
3745             }
3746             SvUPGRADE(dstr, SVt_PVGV);
3747             (void)SvOK_off(dstr);
3748             isGV_with_GP_on(dstr);
3749         }
3750         GvSTASH(dstr) = GvSTASH(sstr);
3751         if (GvSTASH(dstr))
3752             Perl_sv_add_backref(aTHX_ MUTABLE_SV(GvSTASH(dstr)), dstr);
3753         gv_name_set(MUTABLE_GV(dstr), name, len,
3754                         GV_ADD | (GvNAMEUTF8(sstr) ? SVf_UTF8 : 0 ));
3755         SvFAKE_on(dstr);        /* can coerce to non-glob */
3756     }
3757
3758     if(GvGP(MUTABLE_GV(sstr))) {
3759         /* If source has method cache entry, clear it */
3760         if(GvCVGEN(sstr)) {
3761             SvREFCNT_dec(GvCV(sstr));
3762             GvCV_set(sstr, NULL);
3763             GvCVGEN(sstr) = 0;
3764         }
3765         /* If source has a real method, then a method is
3766            going to change */
3767         else if(
3768          GvCV((const GV *)sstr) && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3769         ) {
3770             mro_changes = 1;
3771         }
3772     }
3773
3774     /* If dest already had a real method, that's a change as well */
3775     if(
3776         !mro_changes && GvGP(MUTABLE_GV(dstr)) && GvCVu((const GV *)dstr)
3777      && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3778     ) {
3779         mro_changes = 1;
3780     }
3781
3782     /* We don't need to check the name of the destination if it was not a
3783        glob to begin with. */
3784     if(dtype == SVt_PVGV) {
3785         const char * const name = GvNAME((const GV *)dstr);
3786         if(
3787             strEQ(name,"ISA")
3788          /* The stash may have been detached from the symbol table, so
3789             check its name. */
3790          && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3791         )
3792             mro_changes = 2;
3793         else {
3794             const STRLEN len = GvNAMELEN(dstr);
3795             if ((len > 1 && name[len-2] == ':' && name[len-1] == ':')
3796              || (len == 1 && name[0] == ':')) {
3797                 mro_changes = 3;
3798
3799                 /* Set aside the old stash, so we can reset isa caches on
3800                    its subclasses. */
3801                 if((old_stash = GvHV(dstr)))
3802                     /* Make sure we do not lose it early. */
3803                     SvREFCNT_inc_simple_void_NN(
3804                      sv_2mortal((SV *)old_stash)
3805                     );
3806             }
3807         }
3808
3809         SvREFCNT_inc_simple_void_NN(sv_2mortal(dstr));
3810     }
3811
3812     gp_free(MUTABLE_GV(dstr));
3813     GvINTRO_off(dstr);          /* one-shot flag */
3814     GvGP_set(dstr, gp_ref(GvGP(sstr)));
3815     if (SvTAINTED(sstr))
3816         SvTAINT(dstr);
3817     if (GvIMPORTED(dstr) != GVf_IMPORTED
3818         && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3819         {
3820             GvIMPORTED_on(dstr);
3821         }
3822     GvMULTI_on(dstr);
3823     if(mro_changes == 2) {
3824       if (GvAV((const GV *)sstr)) {
3825         MAGIC *mg;
3826         SV * const sref = (SV *)GvAV((const GV *)dstr);
3827         if (SvSMAGICAL(sref) && (mg = mg_find(sref, PERL_MAGIC_isa))) {
3828             if (SvTYPE(mg->mg_obj) != SVt_PVAV) {
3829                 AV * const ary = newAV();
3830                 av_push(ary, mg->mg_obj); /* takes the refcount */
3831                 mg->mg_obj = (SV *)ary;
3832             }
3833             av_push((AV *)mg->mg_obj, SvREFCNT_inc_simple_NN(dstr));
3834         }
3835         else sv_magic(sref, dstr, PERL_MAGIC_isa, NULL, 0);
3836       }
3837       mro_isa_changed_in(GvSTASH(dstr));
3838     }
3839     else if(mro_changes == 3) {
3840         HV * const stash = GvHV(dstr);
3841         if(old_stash ? (HV *)HvENAME_get(old_stash) : stash)
3842             mro_package_moved(
3843                 stash, old_stash,
3844                 (GV *)dstr, 0
3845             );
3846     }
3847     else if(mro_changes) mro_method_changed_in(GvSTASH(dstr));
3848     if (GvIO(dstr) && dtype == SVt_PVGV) {
3849         DEBUG_o(Perl_deb(aTHX_
3850                         "glob_assign_glob clearing PL_stashcache\n"));
3851         /* It's a cache. It will rebuild itself quite happily.
3852            It's a lot of effort to work out exactly which key (or keys)
3853            might be invalidated by the creation of the this file handle.
3854          */
3855         hv_clear(PL_stashcache);
3856     }
3857     return;
3858 }
3859
3860 static void
3861 S_glob_assign_ref(pTHX_ SV *const dstr, SV *const sstr)
3862 {
3863     SV * const sref = SvRV(sstr);
3864     SV *dref;
3865     const int intro = GvINTRO(dstr);
3866     SV **location;
3867     U8 import_flag = 0;
3868     const U32 stype = SvTYPE(sref);
3869
3870     PERL_ARGS_ASSERT_GLOB_ASSIGN_REF;
3871
3872     if (intro) {
3873         GvINTRO_off(dstr);      /* one-shot flag */
3874         GvLINE(dstr) = CopLINE(PL_curcop);
3875         GvEGV(dstr) = MUTABLE_GV(dstr);
3876     }
3877     GvMULTI_on(dstr);
3878     switch (stype) {
3879     case SVt_PVCV:
3880         location = (SV **) &(GvGP(dstr)->gp_cv); /* XXX bypassing GvCV_set */
3881         import_flag = GVf_IMPORTED_CV;
3882         goto common;
3883     case SVt_PVHV:
3884         location = (SV **) &GvHV(dstr);
3885         import_flag = GVf_IMPORTED_HV;
3886         goto common;
3887     case SVt_PVAV:
3888         location = (SV **) &GvAV(dstr);
3889         import_flag = GVf_IMPORTED_AV;
3890         goto common;
3891     case SVt_PVIO:
3892         location = (SV **) &GvIOp(dstr);
3893         goto common;
3894     case SVt_PVFM:
3895         location = (SV **) &GvFORM(dstr);
3896         goto common;
3897     default:
3898         location = &GvSV(dstr);
3899         import_flag = GVf_IMPORTED_SV;
3900     common:
3901         if (intro) {
3902             if (stype == SVt_PVCV) {
3903                 /*if (GvCVGEN(dstr) && (GvCV(dstr) != (const CV *)sref || GvCVGEN(dstr))) {*/
3904                 if (GvCVGEN(dstr)) {
3905                     SvREFCNT_dec(GvCV(dstr));
3906                     GvCV_set(dstr, NULL);
3907                     GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3908                 }
3909             }
3910             /* SAVEt_GVSLOT takes more room on the savestack and has more
3911                overhead in leave_scope than SAVEt_GENERIC_SV.  But for CVs
3912                leave_scope needs access to the GV so it can reset method
3913                caches.  We must use SAVEt_GVSLOT whenever the type is
3914                SVt_PVCV, even if the stash is anonymous, as the stash may
3915                gain a name somehow before leave_scope. */
3916             if (stype == SVt_PVCV) {
3917                 /* There is no save_pushptrptrptr.  Creating it for this
3918                    one call site would be overkill.  So inline the ss add
3919                    routines here. */
3920                 dSS_ADD;
3921                 SS_ADD_PTR(dstr);
3922                 SS_ADD_PTR(location);
3923                 SS_ADD_PTR(SvREFCNT_inc(*location));
3924                 SS_ADD_UV(SAVEt_GVSLOT);
3925                 SS_ADD_END(4);
3926             }
3927             else SAVEGENERICSV(*location);
3928         }
3929         dref = *location;
3930         if (stype == SVt_PVCV && (*location != sref || GvCVGEN(dstr))) {
3931             CV* const cv = MUTABLE_CV(*location);
3932             if (cv) {
3933                 if (!GvCVGEN((const GV *)dstr) &&
3934                     (CvROOT(cv) || CvXSUB(cv)) &&
3935                     /* redundant check that avoids creating the extra SV
3936                        most of the time: */
3937                     (CvCONST(cv) || ckWARN(WARN_REDEFINE)))
3938                     {
3939                         SV * const new_const_sv =
3940                             CvCONST((const CV *)sref)
3941                                  ? cv_const_sv((const CV *)sref)
3942                                  : NULL;
3943                         report_redefined_cv(
3944                            sv_2mortal(Perl_newSVpvf(aTHX_
3945                                 "%"HEKf"::%"HEKf,
3946                                 HEKfARG(
3947                                  HvNAME_HEK(GvSTASH((const GV *)dstr))
3948                                 ),
3949                                 HEKfARG(GvENAME_HEK(MUTABLE_GV(dstr)))
3950                            )),
3951                            cv,
3952                            CvCONST((const CV *)sref) ? &new_const_sv : NULL
3953                         );
3954                     }
3955                 if (!intro)
3956                     cv_ckproto_len_flags(cv, (const GV *)dstr,
3957                                    SvPOK(sref) ? CvPROTO(sref) : NULL,
3958                                    SvPOK(sref) ? CvPROTOLEN(sref) : 0,
3959                                    SvPOK(sref) ? SvUTF8(sref) : 0);
3960             }
3961             GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3962             GvASSUMECV_on(dstr);
3963             if(GvSTASH(dstr)) gv_method_changed(dstr); /* sub foo { 1 } sub bar { 2 } *bar = \&foo */
3964         }
3965         *location = SvREFCNT_inc_simple_NN(sref);
3966         if (import_flag && !(GvFLAGS(dstr) & import_flag)
3967             && CopSTASH_ne(PL_curcop, GvSTASH(dstr))) {
3968             GvFLAGS(dstr) |= import_flag;
3969         }
3970         if (stype == SVt_PVHV) {
3971             const char * const name = GvNAME((GV*)dstr);
3972             const STRLEN len = GvNAMELEN(dstr);
3973             if (
3974                 (
3975                    (len > 1 && name[len-2] == ':' && name[len-1] == ':')
3976                 || (len == 1 && name[0] == ':')
3977                 )
3978              && (!dref || HvENAME_get(dref))
3979             ) {
3980                 mro_package_moved(
3981                     (HV *)sref, (HV *)dref,
3982                     (GV *)dstr, 0
3983                 );
3984             }
3985         }
3986         else if (
3987             stype == SVt_PVAV && sref != dref
3988          && strEQ(GvNAME((GV*)dstr), "ISA")
3989          /* The stash may have been detached from the symbol table, so
3990             check its name before doing anything. */
3991          && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3992         ) {
3993             MAGIC *mg;
3994             MAGIC * const omg = dref && SvSMAGICAL(dref)
3995                                  ? mg_find(dref, PERL_MAGIC_isa)
3996                                  : NULL;
3997             if (SvSMAGICAL(sref) && (mg = mg_find(sref, PERL_MAGIC_isa))) {
3998                 if (SvTYPE(mg->mg_obj) != SVt_PVAV) {
3999                     AV * const ary = newAV();
4000                     av_push(ary, mg->mg_obj); /* takes the refcount */
4001                     mg->mg_obj = (SV *)ary;
4002                 }
4003                 if (omg) {
4004                     if (SvTYPE(omg->mg_obj) == SVt_PVAV) {
4005                         SV **svp = AvARRAY((AV *)omg->mg_obj);
4006                         I32 items = AvFILLp((AV *)omg->mg_obj) + 1;
4007                         while (items--)
4008                             av_push(
4009                              (AV *)mg->mg_obj,
4010                              SvREFCNT_inc_simple_NN(*svp++)
4011                             );
4012                     }
4013                     else
4014                         av_push(
4015                          (AV *)mg->mg_obj,
4016                          SvREFCNT_inc_simple_NN(omg->mg_obj)
4017                         );
4018                 }
4019                 else
4020                     av_push((AV *)mg->mg_obj,SvREFCNT_inc_simple_NN(dstr));
4021             }
4022             else
4023             {
4024                 sv_magic(
4025                  sref, omg ? omg->mg_obj : dstr, PERL_MAGIC_isa, NULL, 0
4026                 );
4027                 mg = mg_find(sref, PERL_MAGIC_isa);
4028             }
4029             /* Since the *ISA assignment could have affected more than
4030                one stash, don't call mro_isa_changed_in directly, but let
4031                magic_clearisa do it for us, as it already has the logic for
4032                dealing with globs vs arrays of globs. */
4033             assert(mg);
4034             Perl_magic_clearisa(aTHX_ NULL, mg);
4035         }
4036         else if (stype == SVt_PVIO) {
4037             DEBUG_o(Perl_deb(aTHX_ "glob_assign_ref clearing PL_stashcache\n"));
4038             /* It's a cache. It will rebuild itself quite happily.
4039                It's a lot of effort to work out exactly which key (or keys)
4040                might be invalidated by the creation of the this file handle.
4041             */
4042             hv_clear(PL_stashcache);
4043         }
4044         break;
4045     }
4046     if (!intro) SvREFCNT_dec(dref);
4047     if (SvTAINTED(sstr))
4048         SvTAINT(dstr);
4049     return;
4050 }
4051
4052
4053
4054
4055 #ifdef PERL_DEBUG_READONLY_COW
4056 # include <sys/mman.h>
4057
4058 # ifndef PERL_MEMORY_DEBUG_HEADER_SIZE
4059 #  define PERL_MEMORY_DEBUG_HEADER_SIZE 0
4060 # endif
4061
4062 void
4063 Perl_sv_buf_to_ro(pTHX_ SV *sv)
4064 {
4065     struct perl_memory_debug_header * const header =
4066         (struct perl_memory_debug_header *)(SvPVX(sv)-PERL_MEMORY_DEBUG_HEADER_SIZE);
4067     const MEM_SIZE len = header->size;
4068     PERL_ARGS_ASSERT_SV_BUF_TO_RO;
4069 # ifdef PERL_TRACK_MEMPOOL
4070     if (!header->readonly) header->readonly = 1;
4071 # endif
4072     if (mprotect(header, len, PROT_READ))
4073         Perl_warn(aTHX_ "mprotect RW for COW string %p %lu failed with %d",
4074                          header, len, errno);
4075 }
4076
4077 static void
4078 S_sv_buf_to_rw(pTHX_ SV *sv)
4079 {
4080     struct perl_memory_debug_header * const header =
4081         (struct perl_memory_debug_header *)(SvPVX(sv)-PERL_MEMORY_DEBUG_HEADER_SIZE);
4082     const MEM_SIZE len = header->size;
4083     PERL_ARGS_ASSERT_SV_BUF_TO_RW;
4084     if (mprotect(header, len, PROT_READ|PROT_WRITE))
4085         Perl_warn(aTHX_ "mprotect for COW string %p %lu failed with %d",
4086                          header, len, errno);
4087 # ifdef PERL_TRACK_MEMPOOL
4088     header->readonly = 0;
4089 # endif
4090 }
4091
4092 #else
4093 # define sv_buf_to_ro(sv)       NOOP
4094 # define sv_buf_to_rw(sv)       NOOP
4095 #endif
4096
4097 void
4098 Perl_sv_setsv_flags(pTHX_ SV *dstr, SV* sstr, const I32 flags)
4099 {
4100     dVAR;
4101     U32 sflags;
4102     int dtype;
4103     svtype stype;
4104
4105     PERL_ARGS_ASSERT_SV_SETSV_FLAGS;
4106
4107     if (sstr == dstr)
4108         return;
4109
4110     if (SvIS_FREED(dstr)) {
4111         Perl_croak(aTHX_ "panic: attempt to copy value %" SVf
4112                    " to a freed scalar %p", SVfARG(sstr), (void *)dstr);
4113     }
4114     SV_CHECK_THINKFIRST_COW_DROP(dstr);
4115     if (!sstr)
4116         sstr = &PL_sv_undef;
4117     if (SvIS_FREED(sstr)) {
4118         Perl_croak(aTHX_ "panic: attempt to copy freed scalar %p to %p",
4119                    (void*)sstr, (void*)dstr);
4120     }
4121     stype = SvTYPE(sstr);
4122     dtype = SvTYPE(dstr);
4123
4124     /* There's a lot of redundancy below but we're going for speed here */
4125
4126     switch (stype) {
4127     case SVt_NULL:
4128       undef_sstr:
4129         if (dtype != SVt_PVGV && dtype != SVt_PVLV) {
4130             (void)SvOK_off(dstr);
4131             return;
4132         }
4133         break;
4134     case SVt_IV:
4135         if (SvIOK(sstr)) {
4136             switch (dtype) {
4137             case SVt_NULL:
4138                 sv_upgrade(dstr, SVt_IV);
4139                 break;
4140             case SVt_NV:
4141             case SVt_PV:
4142                 sv_upgrade(dstr, SVt_PVIV);
4143                 break;
4144             case SVt_PVGV:
4145             case SVt_PVLV:
4146                 goto end_of_first_switch;
4147             }
4148             (void)SvIOK_only(dstr);
4149             SvIV_set(dstr,  SvIVX(sstr));
4150             if (SvIsUV(sstr))
4151                 SvIsUV_on(dstr);
4152             /* SvTAINTED can only be true if the SV has taint magic, which in
4153                turn means that the SV type is PVMG (or greater). This is the
4154                case statement for SVt_IV, so this cannot be true (whatever gcov
4155                may say).  */
4156             assert(!SvTAINTED(sstr));
4157             return;
4158         }
4159         if (!SvROK(sstr))
4160             goto undef_sstr;
4161         if (dtype < SVt_PV && dtype != SVt_IV)
4162             sv_upgrade(dstr, SVt_IV);
4163         break;
4164
4165     case SVt_NV:
4166         if (SvNOK(sstr)) {
4167             switch (dtype) {
4168             case SVt_NULL:
4169             case SVt_IV:
4170                 sv_upgrade(dstr, SVt_NV);
4171                 break;
4172             case SVt_PV:
4173             case SVt_PVIV:
4174                 sv_upgrade(dstr, SVt_PVNV);
4175                 break;
4176             case SVt_PVGV:
4177             case SVt_PVLV:
4178                 goto end_of_first_switch;
4179             }
4180             SvNV_set(dstr, SvNVX(sstr));
4181             (void)SvNOK_only(dstr);
4182             /* SvTAINTED can only be true if the SV has taint magic, which in
4183                turn means that the SV type is PVMG (or greater). This is the
4184                case statement for SVt_NV, so this cannot be true (whatever gcov
4185                may say).  */
4186             assert(!SvTAINTED(sstr));
4187             return;
4188         }
4189         goto undef_sstr;
4190
4191     case SVt_PV:
4192         if (dtype < SVt_PV)
4193             sv_upgrade(dstr, SVt_PV);
4194         break;
4195     case SVt_PVIV:
4196         if (dtype < SVt_PVIV)
4197             sv_upgrade(dstr, SVt_PVIV);
4198         break;
4199     case SVt_PVNV:
4200         if (dtype < SVt_PVNV)
4201             sv_upgrade(dstr, SVt_PVNV);
4202         break;
4203     default:
4204         {
4205         const char * const type = sv_reftype(sstr,0);
4206         if (PL_op)
4207             /* diag_listed_as: Bizarre copy of %s */
4208             Perl_croak(aTHX_ "Bizarre copy of %s in %s", type, OP_DESC(PL_op));
4209         else
4210             Perl_croak(aTHX_ "Bizarre copy of %s", type);
4211         }
4212         break;
4213
4214     case SVt_REGEXP:
4215       upgregexp:
4216         if (dtype < SVt_REGEXP)
4217         {
4218             if (dtype >= SVt_PV) {
4219                 SvPV_free(dstr);
4220                 SvPV_set(dstr, 0);
4221                 SvLEN_set(dstr, 0);
4222                 SvCUR_set(dstr, 0);
4223             }
4224             sv_upgrade(dstr, SVt_REGEXP);
4225         }
4226         break;
4227
4228         case SVt_INVLIST:
4229     case SVt_PVLV:
4230     case SVt_PVGV:
4231     case SVt_PVMG:
4232         if (SvGMAGICAL(sstr) && (flags & SV_GMAGIC)) {
4233             mg_get(sstr);
4234             if (SvTYPE(sstr) != stype)
4235                 stype = SvTYPE(sstr);
4236         }
4237         if (isGV_with_GP(sstr) && dtype <= SVt_PVLV) {
4238                     glob_assign_glob(dstr, sstr, dtype);
4239                     return;
4240         }
4241         if (stype == SVt_PVLV)
4242         {
4243             if (isREGEXP(sstr)) goto upgregexp;
4244             SvUPGRADE(dstr, SVt_PVNV);
4245         }
4246         else
4247             SvUPGRADE(dstr, (svtype)stype);
4248     }
4249  end_of_first_switch:
4250
4251     /* dstr may have been upgraded.  */
4252     dtype = SvTYPE(dstr);
4253     sflags = SvFLAGS(sstr);
4254
4255     if (dtype == SVt_PVCV) {
4256         /* Assigning to a subroutine sets the prototype.  */
4257         if (SvOK(sstr)) {
4258             STRLEN len;
4259             const char *const ptr = SvPV_const(sstr, len);
4260
4261             SvGROW(dstr, len + 1);
4262             Copy(ptr, SvPVX(dstr), len + 1, char);
4263             SvCUR_set(dstr, len);
4264             SvPOK_only(dstr);
4265             SvFLAGS(dstr) |= sflags & SVf_UTF8;
4266             CvAUTOLOAD_off(dstr);
4267         } else {
4268             SvOK_off(dstr);
4269         }
4270     }
4271     else if (dtype == SVt_PVAV || dtype == SVt_PVHV || dtype == SVt_PVFM) {
4272         const char * const type = sv_reftype(dstr,0);
4273         if (PL_op)
4274             /* diag_listed_as: Cannot copy to %s */
4275             Perl_croak(aTHX_ "Cannot copy to %s in %s", type, OP_DESC(PL_op));
4276         else
4277             Perl_croak(aTHX_ "Cannot copy to %s", type);
4278     } else if (sflags & SVf_ROK) {
4279         if (isGV_with_GP(dstr)
4280             && SvTYPE(SvRV(sstr)) == SVt_PVGV && isGV_with_GP(SvRV(sstr))) {
4281             sstr = SvRV(sstr);
4282             if (sstr == dstr) {
4283                 if (GvIMPORTED(dstr) != GVf_IMPORTED
4284                     && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
4285                 {
4286                     GvIMPORTED_on(dstr);
4287                 }
4288                 GvMULTI_on(dstr);
4289                 return;
4290             }
4291             glob_assign_glob(dstr, sstr, dtype);
4292             return;
4293         }
4294
4295         if (dtype >= SVt_PV) {
4296             if (isGV_with_GP(dstr)) {
4297                 glob_assign_ref(dstr, sstr);
4298                 return;
4299             }
4300             if (SvPVX_const(dstr)) {
4301                 SvPV_free(dstr);
4302                 SvLEN_set(dstr, 0);
4303                 SvCUR_set(dstr, 0);
4304             }
4305         }
4306         (void)SvOK_off(dstr);
4307         SvRV_set(dstr, SvREFCNT_inc(SvRV(sstr)));
4308         SvFLAGS(dstr) |= sflags & SVf_ROK;
4309         assert(!(sflags & SVp_NOK));
4310         assert(!(sflags & SVp_IOK));
4311         assert(!(sflags & SVf_NOK));
4312         assert(!(sflags & SVf_IOK));
4313     }
4314     else if (isGV_with_GP(dstr)) {
4315         if (!(sflags & SVf_OK)) {
4316             Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4317                            "Undefined value assigned to typeglob");
4318         }
4319         else {
4320             GV *gv = gv_fetchsv_nomg(sstr, GV_ADD, SVt_PVGV);
4321             if (dstr != (const SV *)gv) {
4322                 const char * const name = GvNAME((const GV *)dstr);
4323                 const STRLEN len = GvNAMELEN(dstr);
4324                 HV *old_stash = NULL;
4325                 bool reset_isa = FALSE;
4326                 if ((len > 1 && name[len-2] == ':' && name[len-1] == ':')
4327                  || (len == 1 && name[0] == ':')) {
4328                     /* Set aside the old stash, so we can reset isa caches
4329                        on its subclasses. */
4330                     if((old_stash = GvHV(dstr))) {
4331                         /* Make sure we do not lose it early. */
4332                         SvREFCNT_inc_simple_void_NN(
4333                          sv_2mortal((SV *)old_stash)
4334                         );
4335                     }
4336                     reset_isa = TRUE;
4337                 }
4338
4339                 if (GvGP(dstr)) {
4340                     SvREFCNT_inc_simple_void_NN(sv_2mortal(dstr));
4341                     gp_free(MUTABLE_GV(dstr));
4342                 }
4343                 GvGP_set(dstr, gp_ref(GvGP(gv)));
4344
4345                 if (reset_isa) {
4346                     HV * const stash = GvHV(dstr);
4347                     if(
4348                         old_stash ? (HV *)HvENAME_get(old_stash) : stash
4349                     )
4350                         mro_package_moved(
4351                          stash, old_stash,
4352                          (GV *)dstr, 0
4353                         );
4354                 }
4355             }
4356         }
4357     }
4358     else if ((dtype == SVt_REGEXP || dtype == SVt_PVLV)
4359           && (stype == SVt_REGEXP || isREGEXP(sstr))) {
4360         reg_temp_copy((REGEXP*)dstr, (REGEXP*)sstr);
4361     }
4362     else if (sflags & SVp_POK) {
4363         const STRLEN cur = SvCUR(sstr);
4364         const STRLEN len = SvLEN(sstr);
4365
4366         /*
4367          * We have three basic ways to copy the string:
4368          *
4369          *  1. Swipe
4370          *  2. Copy-on-write
4371          *  3. Actual copy
4372          * 
4373          * Which we choose is based on various factors.  The following
4374          * things are listed in order of speed, fastest to slowest:
4375          *  - Swipe
4376          *  - Copying a short string
4377          *  - Copy-on-write bookkeeping
4378          *  - malloc
4379          *  - Copying a long string
4380          * 
4381          * We swipe the string (steal the string buffer) if the SV on the
4382          * rhs is about to be freed anyway (TEMP and refcnt==1).  This is a
4383          * big win on long strings.  It should be a win on short strings if
4384          * SvPVX_const(dstr) has to be allocated.  If not, it should not 
4385          * slow things down, as SvPVX_const(sstr) would have been freed
4386          * soon anyway.
4387          * 
4388          * We also steal the buffer from a PADTMP (operator target) if it
4389          * is â€˜long enough’.  For short strings, a swipe does not help
4390          * here, as it causes more malloc calls the next time the target
4391          * is used.  Benchmarks show that even if SvPVX_const(dstr) has to
4392          * be allocated it is still not worth swiping PADTMPs for short
4393          * strings, as the savings here are small.
4394          * 
4395          * If the rhs is already flagged as a copy-on-write string and COW
4396          * is possible here, we use copy-on-write and make both SVs share
4397          * the string buffer.
4398          * 
4399          * If the rhs is not flagged as copy-on-write, then we see whether
4400          * it is worth upgrading it to such.  If the lhs already has a buf-
4401          * fer big enough and the string is short, we skip it and fall back
4402          * to method 3, since memcpy is faster for short strings than the
4403          * later bookkeeping overhead that copy-on-write entails.
4404          * 
4405          * If there is no buffer on the left, or the buffer is too small,
4406          * then we use copy-on-write.
4407          */
4408
4409         /* Whichever path we take through the next code, we want this true,
4410            and doing it now facilitates the COW check.  */
4411         (void)SvPOK_only(dstr);
4412
4413         if (
4414                  (              /* Either ... */
4415                                 /* slated for free anyway (and not COW)? */
4416                     (sflags & (SVs_TEMP|SVf_IsCOW)) == SVs_TEMP
4417                                 /* or a swipable TARG */
4418                  || ((sflags & (SVs_PADTMP|SVf_READONLY|SVf_IsCOW))
4419                        == SVs_PADTMP
4420                                 /* whose buffer is worth stealing */
4421                      && CHECK_COWBUF_THRESHOLD(cur,len)
4422                     )
4423                  ) &&
4424                  !(sflags & SVf_OOK) &&   /* and not involved in OOK hack? */
4425                  (!(flags & SV_NOSTEAL)) &&
4426                                         /* and we're allowed to steal temps */
4427                  SvREFCNT(sstr) == 1 &&   /* and no other references to it? */
4428                  len)             /* and really is a string */
4429         {       /* Passes the swipe test.  */
4430             if (SvPVX_const(dstr))      /* we know that dtype >= SVt_PV */
4431                 SvPV_free(dstr);
4432             SvPV_set(dstr, SvPVX_mutable(sstr));
4433             SvLEN_set(dstr, SvLEN(sstr));
4434             SvCUR_set(dstr, SvCUR(sstr));
4435
4436             SvTEMP_off(dstr);
4437             (void)SvOK_off(sstr);       /* NOTE: nukes most SvFLAGS on sstr */
4438             SvPV_set(sstr, NULL);
4439             SvLEN_set(sstr, 0);
4440             SvCUR_set(sstr, 0);
4441             SvTEMP_off(sstr);
4442         }
4443         else if (flags & SV_COW_SHARED_HASH_KEYS
4444               &&
4445 #ifdef PERL_OLD_COPY_ON_WRITE
4446                  (  sflags & SVf_IsCOW
4447                  || (   (sflags & CAN_COW_MASK) == CAN_COW_FLAGS
4448                      && (SvFLAGS(dstr) & CAN_COW_MASK) == CAN_COW_FLAGS
4449                      && SvTYPE(sstr) >= SVt_PVIV && len
4450                     )
4451                  )
4452 #elif defined(PERL_NEW_COPY_ON_WRITE)
4453                  (sflags & SVf_IsCOW
4454                    ? (!len ||
4455                        (  (CHECK_COWBUF_THRESHOLD(cur,len) || SvLEN(dstr) < cur+1)
4456                           /* If this is a regular (non-hek) COW, only so
4457                              many COW "copies" are possible. */
4458                        && CowREFCNT(sstr) != SV_COW_REFCNT_MAX  ))
4459                    : (  (sflags & CAN_COW_MASK) == CAN_COW_FLAGS
4460                      && !(SvFLAGS(dstr) & SVf_BREAK)
4461                      && CHECK_COW_THRESHOLD(cur,len) && cur+1 < len
4462                      && (CHECK_COWBUF_THRESHOLD(cur,len) || SvLEN(dstr) < cur+1)
4463                     ))
4464 #else
4465                  sflags & SVf_IsCOW
4466               && !(SvFLAGS(dstr) & SVf_BREAK)
4467 #endif
4468             ) {
4469             /* Either it's a shared hash key, or it's suitable for
4470                copy-on-write.  */
4471             if (DEBUG_C_TEST) {
4472                 PerlIO_printf(Perl_debug_log, "Copy on write: sstr --> dstr\n");
4473                 sv_dump(sstr);
4474                 sv_dump(dstr);
4475             }
4476 #ifdef PERL_ANY_COW
4477             if (!(sflags & SVf_IsCOW)) {
4478                     SvIsCOW_on(sstr);
4479 # ifdef PERL_OLD_COPY_ON_WRITE
4480                     /* Make the source SV into a loop of 1.
4481                        (about to become 2) */
4482                     SV_COW_NEXT_SV_SET(sstr, sstr);
4483 # else
4484                     CowREFCNT(sstr) = 0;
4485 # endif
4486             }
4487 #endif
4488             if (SvPVX_const(dstr)) {    /* we know that dtype >= SVt_PV */
4489                 SvPV_free(dstr);
4490             }
4491
4492 #ifdef PERL_ANY_COW
4493             if (len) {
4494 # ifdef PERL_OLD_COPY_ON_WRITE
4495                     assert (SvTYPE(dstr) >= SVt_PVIV);
4496                     /* SvIsCOW_normal */
4497                     /* splice us in between source and next-after-source.  */
4498                     SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4499                     SV_COW_NEXT_SV_SET(sstr, dstr);
4500 # else
4501                     if (sflags & SVf_IsCOW) {
4502                         sv_buf_to_rw(sstr);
4503                     }
4504                     CowREFCNT(sstr)++;
4505 # endif
4506                     SvPV_set(dstr, SvPVX_mutable(sstr));
4507                     sv_buf_to_ro(sstr);
4508             } else
4509 #endif
4510             {
4511                     /* SvIsCOW_shared_hash */
4512                     DEBUG_C(PerlIO_printf(Perl_debug_log,
4513                                           "Copy on write: Sharing hash\n"));
4514
4515                     assert (SvTYPE(dstr) >= SVt_PV);
4516                     SvPV_set(dstr,
4517                              HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)))));
4518             }
4519             SvLEN_set(dstr, len);
4520             SvCUR_set(dstr, cur);
4521             SvIsCOW_on(dstr);
4522         } else {
4523             /* Failed the swipe test, and we cannot do copy-on-write either.
4524                Have to copy the string.  */
4525             SvGROW(dstr, cur + 1);      /* inlined from sv_setpvn */
4526             Move(SvPVX_const(sstr),SvPVX(dstr),cur,char);
4527             SvCUR_set(dstr, cur);
4528             *SvEND(dstr) = '\0';
4529         }
4530         if (sflags & SVp_NOK) {
4531             SvNV_set(dstr, SvNVX(sstr));
4532         }
4533         if (sflags & SVp_IOK) {
4534             SvIV_set(dstr, SvIVX(sstr));
4535             /* Must do this otherwise some other overloaded use of 0x80000000
4536                gets confused. I guess SVpbm_VALID */
4537             if (sflags & SVf_IVisUV)
4538                 SvIsUV_on(dstr);
4539         }
4540         SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_NOK|SVp_NOK|SVf_UTF8);
4541         {
4542             const MAGIC * const smg = SvVSTRING_mg(sstr);
4543             if (smg) {
4544                 sv_magic(dstr, NULL, PERL_MAGIC_vstring,
4545                          smg->mg_ptr, smg->mg_len);
4546                 SvRMAGICAL_on(dstr);
4547             }
4548         }
4549     }
4550     else if (sflags & (SVp_IOK|SVp_NOK)) {
4551         (void)SvOK_off(dstr);
4552         SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_IVisUV|SVf_NOK|SVp_NOK);
4553         if (sflags & SVp_IOK) {
4554             /* XXXX Do we want to set IsUV for IV(ROK)?  Be extra safe... */
4555             SvIV_set(dstr, SvIVX(sstr));
4556         }
4557         if (sflags & SVp_NOK) {
4558             SvNV_set(dstr, SvNVX(sstr));
4559         }
4560     }
4561     else {
4562         if (isGV_with_GP(sstr)) {
4563             gv_efullname3(dstr, MUTABLE_GV(sstr), "*");
4564         }
4565         else
4566             (void)SvOK_off(dstr);
4567     }
4568     if (SvTAINTED(sstr))
4569         SvTAINT(dstr);
4570 }
4571
4572 /*
4573 =for apidoc sv_setsv_mg
4574
4575 Like C<sv_setsv>, but also handles 'set' magic.
4576
4577 =cut
4578 */
4579
4580 void
4581 Perl_sv_setsv_mg(pTHX_ SV *const dstr, SV *const sstr)
4582 {
4583     PERL_ARGS_ASSERT_SV_SETSV_MG;
4584
4585     sv_setsv(dstr,sstr);
4586     SvSETMAGIC(dstr);
4587 }
4588
4589 #ifdef PERL_ANY_COW
4590 # ifdef PERL_OLD_COPY_ON_WRITE
4591 #  define SVt_COW SVt_PVIV
4592 # else
4593 #  define SVt_COW SVt_PV
4594 # endif
4595 SV *
4596 Perl_sv_setsv_cow(pTHX_ SV *dstr, SV *sstr)
4597 {
4598     STRLEN cur = SvCUR(sstr);
4599     STRLEN len = SvLEN(sstr);
4600     char *new_pv;
4601 #if defined(PERL_DEBUG_READONLY_COW) && defined(PERL_NEW_COPY_ON_WRITE)
4602     const bool already = cBOOL(SvIsCOW(sstr));
4603 #endif
4604
4605     PERL_ARGS_ASSERT_SV_SETSV_COW;
4606
4607     if (DEBUG_C_TEST) {
4608         PerlIO_printf(Perl_debug_log, "Fast copy on write: %p -> %p\n",
4609                       (void*)sstr, (void*)dstr);
4610         sv_dump(sstr);
4611         if (dstr)
4612                     sv_dump(dstr);
4613     }
4614
4615     if (dstr) {
4616         if (SvTHINKFIRST(dstr))
4617             sv_force_normal_flags(dstr, SV_COW_DROP_PV);
4618         else if (SvPVX_const(dstr))
4619             Safefree(SvPVX_mutable(dstr));
4620     }
4621     else
4622         new_SV(dstr);
4623     SvUPGRADE(dstr, SVt_COW);
4624
4625     assert (SvPOK(sstr));
4626     assert (SvPOKp(sstr));
4627 # ifdef PERL_OLD_COPY_ON_WRITE
4628     assert (!SvIOK(sstr));
4629     assert (!SvIOKp(sstr));
4630     assert (!SvNOK(sstr));
4631     assert (!SvNOKp(sstr));
4632 # endif
4633
4634     if (SvIsCOW(sstr)) {
4635
4636         if (SvLEN(sstr) == 0) {
4637             /* source is a COW shared hash key.  */
4638             DEBUG_C(PerlIO_printf(Perl_debug_log,
4639                                   "Fast copy on write: Sharing hash\n"));
4640             new_pv = HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr))));
4641             goto common_exit;
4642         }
4643 # ifdef PERL_OLD_COPY_ON_WRITE
4644         SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4645 # else
4646         assert(SvCUR(sstr)+1 < SvLEN(sstr));
4647         assert(CowREFCNT(sstr) < SV_COW_REFCNT_MAX);
4648 # endif
4649     } else {
4650         assert ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS);
4651         SvUPGRADE(sstr, SVt_COW);
4652         SvIsCOW_on(sstr);
4653         DEBUG_C(PerlIO_printf(Perl_debug_log,
4654                               "Fast copy on write: Converting sstr to COW\n"));
4655 # ifdef PERL_OLD_COPY_ON_WRITE
4656         SV_COW_NEXT_SV_SET(dstr, sstr);
4657 # else
4658         CowREFCNT(sstr) = 0;    
4659 # endif
4660     }
4661 # ifdef PERL_OLD_COPY_ON_WRITE
4662     SV_COW_NEXT_SV_SET(sstr, dstr);
4663 # else
4664 #  ifdef PERL_DEBUG_READONLY_COW
4665     if (already) sv_buf_to_rw(sstr);
4666 #  endif
4667     CowREFCNT(sstr)++;  
4668 # endif
4669     new_pv = SvPVX_mutable(sstr);
4670     sv_buf_to_ro(sstr);
4671
4672   common_exit:
4673     SvPV_set(dstr, new_pv);
4674     SvFLAGS(dstr) = (SVt_COW|SVf_POK|SVp_POK|SVf_IsCOW);
4675     if (SvUTF8(sstr))
4676         SvUTF8_on(dstr);
4677     SvLEN_set(dstr, len);
4678     SvCUR_set(dstr, cur);
4679     if (DEBUG_C_TEST) {
4680         sv_dump(dstr);
4681     }
4682     return dstr;
4683 }
4684 #endif
4685
4686 /*
4687 =for apidoc sv_setpvn
4688
4689 Copies a string into an SV.  The C<len> parameter indicates the number of
4690 bytes to be copied.  If the C<ptr> argument is NULL the SV will become
4691 undefined.  Does not handle 'set' magic.  See C<sv_setpvn_mg>.
4692
4693 =cut
4694 */
4695
4696 void
4697 Perl_sv_setpvn(pTHX_ SV *const sv, const char *const ptr, const STRLEN len)
4698 {
4699     dVAR;
4700     char *dptr;
4701
4702     PERL_ARGS_ASSERT_SV_SETPVN;
4703
4704     SV_CHECK_THINKFIRST_COW_DROP(sv);
4705     if (!ptr) {
4706         (void)SvOK_off(sv);
4707         return;
4708     }
4709     else {
4710         /* len is STRLEN which is unsigned, need to copy to signed */
4711         const IV iv = len;
4712         if (iv < 0)
4713             Perl_croak(aTHX_ "panic: sv_setpvn called with negative strlen %"
4714                        IVdf, iv);
4715     }
4716     SvUPGRADE(sv, SVt_PV);
4717
4718     dptr = SvGROW(sv, len + 1);
4719     Move(ptr,dptr,len,char);
4720     dptr[len] = '\0';
4721     SvCUR_set(sv, len);
4722     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4723     SvTAINT(sv);
4724     if (SvTYPE(sv) == SVt_PVCV) CvAUTOLOAD_off(sv);
4725 }
4726
4727 /*
4728 =for apidoc sv_setpvn_mg
4729
4730 Like C<sv_setpvn>, but also handles 'set' magic.
4731
4732 =cut
4733 */
4734
4735 void
4736 Perl_sv_setpvn_mg(pTHX_ SV *const sv, const char *const ptr, const STRLEN len)
4737 {
4738     PERL_ARGS_ASSERT_SV_SETPVN_MG;
4739
4740     sv_setpvn(sv,ptr,len);
4741     SvSETMAGIC(sv);
4742 }
4743
4744 /*
4745 =for apidoc sv_setpv
4746
4747 Copies a string into an SV.  The string must be null-terminated.  Does not
4748 handle 'set' magic.  See C<sv_setpv_mg>.
4749
4750 =cut
4751 */
4752
4753 void
4754 Perl_sv_setpv(pTHX_ SV *const sv, const char *const ptr)
4755 {
4756     dVAR;
4757     STRLEN len;
4758
4759     PERL_ARGS_ASSERT_SV_SETPV;
4760
4761     SV_CHECK_THINKFIRST_COW_DROP(sv);
4762     if (!ptr) {
4763         (void)SvOK_off(sv);
4764         return;
4765     }
4766     len = strlen(ptr);
4767     SvUPGRADE(sv, SVt_PV);
4768
4769     SvGROW(sv, len + 1);
4770     Move(ptr,SvPVX(sv),len+1,char);
4771     SvCUR_set(sv, len);
4772     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4773     SvTAINT(sv);
4774     if (SvTYPE(sv) == SVt_PVCV) CvAUTOLOAD_off(sv);
4775 }
4776
4777 /*
4778 =for apidoc sv_setpv_mg
4779
4780 Like C<sv_setpv>, but also handles 'set' magic.
4781
4782 =cut
4783 */
4784
4785 void
4786 Perl_sv_setpv_mg(pTHX_ SV *const sv, const char *const ptr)
4787 {
4788     PERL_ARGS_ASSERT_SV_SETPV_MG;
4789
4790     sv_setpv(sv,ptr);
4791     SvSETMAGIC(sv);
4792 }
4793
4794 void
4795 Perl_sv_sethek(pTHX_ SV *const sv, const HEK *const hek)
4796 {
4797     dVAR;
4798
4799     PERL_ARGS_ASSERT_SV_SETHEK;
4800
4801     if (!hek) {
4802         return;
4803     }
4804
4805     if (HEK_LEN(hek) == HEf_SVKEY) {
4806         sv_setsv(sv, *(SV**)HEK_KEY(hek));
4807         return;
4808     } else {
4809         const int flags = HEK_FLAGS(hek);
4810         if (flags & HVhek_WASUTF8) {
4811             STRLEN utf8_len = HEK_LEN(hek);
4812             char *as_utf8 = (char *)bytes_to_utf8((U8*)HEK_KEY(hek), &utf8_len);
4813             sv_usepvn_flags(sv, as_utf8, utf8_len, SV_HAS_TRAILING_NUL);
4814             SvUTF8_on(sv);
4815             return;
4816         } else if (flags & HVhek_UNSHARED) {
4817             sv_setpvn(sv, HEK_KEY(hek), HEK_LEN(hek));
4818             if (HEK_UTF8(hek))
4819                 SvUTF8_on(sv);
4820             else SvUTF8_off(sv);
4821             return;
4822         }
4823         {
4824             SV_CHECK_THINKFIRST_COW_DROP(sv);
4825             SvUPGRADE(sv, SVt_PV);
4826             SvPV_free(sv);
4827             SvPV_set(sv,(char *)HEK_KEY(share_hek_hek(hek)));
4828             SvCUR_set(sv, HEK_LEN(hek));
4829             SvLEN_set(sv, 0);
4830             SvIsCOW_on(sv);
4831             SvPOK_on(sv);
4832             if (HEK_UTF8(hek))
4833                 SvUTF8_on(sv);
4834             else SvUTF8_off(sv);
4835             return;
4836         }
4837     }
4838 }
4839
4840
4841 /*
4842 =for apidoc sv_usepvn_flags
4843
4844 Tells an SV to use C<ptr> to find its string value.  Normally the
4845 string is stored inside the SV but sv_usepvn allows the SV to use an
4846 outside string.  The C<ptr> should point to memory that was allocated
4847 by L<Newx|perlclib/Memory Management and String Handling>. It must be
4848 the start of a Newx-ed block of memory, and not a pointer to the
4849 middle of it (beware of L<OOK|perlguts/Offsets> and copy-on-write),
4850 and not be from a non-Newx memory allocator like C<malloc>. The
4851 string length, C<len>, must be supplied.  By default this function
4852 will C<Renew> (i.e. realloc, move) the memory pointed to by C<ptr>,
4853 so that pointer should not be freed or used by the programmer after
4854 giving it to sv_usepvn, and neither should any pointers from "behind"
4855 that pointer (e.g. ptr + 1) be used.
4856
4857 If C<flags> & SV_SMAGIC is true, will call SvSETMAGIC.  If C<flags> &
4858 SV_HAS_TRAILING_NUL is true, then C<ptr[len]> must be NUL, and the realloc
4859 will be skipped (i.e. the buffer is actually at least 1 byte longer than
4860 C<len>, and already meets the requirements for storing in C<SvPVX>).
4861
4862 =cut
4863 */
4864
4865 void
4866 Perl_sv_usepvn_flags(pTHX_ SV *const sv, char *ptr, const STRLEN len, const U32 flags)
4867 {
4868     dVAR;
4869     STRLEN allocate;
4870
4871     PERL_ARGS_ASSERT_SV_USEPVN_FLAGS;
4872
4873     SV_CHECK_THINKFIRST_COW_DROP(sv);
4874     SvUPGRADE(sv, SVt_PV);
4875     if (!ptr) {
4876         (void)SvOK_off(sv);
4877         if (flags & SV_SMAGIC)
4878             SvSETMAGIC(sv);
4879         return;
4880     }
4881     if (SvPVX_const(sv))
4882         SvPV_free(sv);
4883
4884 #ifdef DEBUGGING
4885     if (flags & SV_HAS_TRAILING_NUL)
4886         assert(ptr[len] == '\0');
4887 #endif
4888
4889     allocate = (flags & SV_HAS_TRAILING_NUL)
4890         ? len + 1 :
4891 #ifdef Perl_safesysmalloc_size
4892         len + 1;
4893 #else 
4894         PERL_STRLEN_ROUNDUP(len + 1);
4895 #endif
4896     if (flags & SV_HAS_TRAILING_NUL) {
4897         /* It's long enough - do nothing.
4898            Specifically Perl_newCONSTSUB is relying on this.  */
4899     } else {
4900 #ifdef DEBUGGING
4901         /* Force a move to shake out bugs in callers.  */
4902         char *new_ptr = (char*)safemalloc(allocate);
4903         Copy(ptr, new_ptr, len, char);
4904         PoisonFree(ptr,len,char);
4905         Safefree(ptr);
4906         ptr = new_ptr;
4907 #else
4908         ptr = (char*) saferealloc (ptr, allocate);
4909 #endif
4910     }
4911 #ifdef Perl_safesysmalloc_size
4912     SvLEN_set(sv, Perl_safesysmalloc_size(ptr));
4913 #else
4914     SvLEN_set(sv, allocate);
4915 #endif
4916     SvCUR_set(sv, len);
4917     SvPV_set(sv, ptr);
4918     if (!(flags & SV_HAS_TRAILING_NUL)) {
4919         ptr[len] = '\0';
4920     }
4921     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4922     SvTAINT(sv);
4923     if (flags & SV_SMAGIC)
4924         SvSETMAGIC(sv);
4925 }
4926
4927 #ifdef PERL_OLD_COPY_ON_WRITE
4928 /* Need to do this *after* making the SV normal, as we need the buffer
4929    pointer to remain valid until after we've copied it.  If we let go too early,
4930    another thread could invalidate it by unsharing last of the same hash key
4931    (which it can do by means other than releasing copy-on-write Svs)
4932    or by changing the other copy-on-write SVs in the loop.  */
4933 STATIC void
4934 S_sv_release_COW(pTHX_ SV *sv, const char *pvx, SV *after)
4935 {
4936     PERL_ARGS_ASSERT_SV_RELEASE_COW;
4937
4938     { /* this SV was SvIsCOW_normal(sv) */
4939          /* we need to find the SV pointing to us.  */
4940         SV *current = SV_COW_NEXT_SV(after);
4941
4942         if (current == sv) {
4943             /* The SV we point to points back to us (there were only two of us
4944                in the loop.)
4945                Hence other SV is no longer copy on write either.  */
4946             SvIsCOW_off(after);
4947             sv_buf_to_rw(after);
4948         } else {
4949             /* We need to follow the pointers around the loop.  */
4950             SV *next;
4951             while ((next = SV_COW_NEXT_SV(current)) != sv) {
4952                 assert (next);
4953                 current = next;
4954                  /* don't loop forever if the structure is bust, and we have
4955                     a pointer into a closed loop.  */
4956                 assert (current != after);
4957                 assert (SvPVX_const(current) == pvx);
4958             }
4959             /* Make the SV before us point to the SV after us.  */
4960             SV_COW_NEXT_SV_SET(current, after);
4961         }
4962     }
4963 }
4964 #endif
4965 /*
4966 =for apidoc sv_force_normal_flags
4967
4968 Undo various types of fakery on an SV, where fakery means
4969 "more than" a string: if the PV is a shared string, make
4970 a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
4971 an xpvmg; if we're a copy-on-write scalar, this is the on-write time when
4972 we do the copy, and is also used locally; if this is a
4973 vstring, drop the vstring magic.  If C<SV_COW_DROP_PV> is set
4974 then a copy-on-write scalar drops its PV buffer (if any) and becomes
4975 SvPOK_off rather than making a copy.  (Used where this
4976 scalar is about to be set to some other value.)  In addition,
4977 the C<flags> parameter gets passed to C<sv_unref_flags()>
4978 when unreffing.  C<sv_force_normal> calls this function
4979 with flags set to 0.
4980
4981 This function is expected to be used to signal to perl that this SV is
4982 about to be written to, and any extra book-keeping needs to be taken care
4983 of.  Hence, it croaks on read-only values.
4984
4985 =cut
4986 */
4987
4988 static void
4989 S_sv_uncow(pTHX_ SV * const sv, const U32 flags)
4990 {
4991     dVAR;
4992
4993     assert(SvIsCOW(sv));
4994     {
4995 #ifdef PERL_ANY_COW
4996         const char * const pvx = SvPVX_const(sv);
4997         const STRLEN len = SvLEN(sv);
4998         const STRLEN cur = SvCUR(sv);
4999 # ifdef PERL_OLD_COPY_ON_WRITE
5000         /* next COW sv in the loop.  If len is 0 then this is a shared-hash
5001            key scalar, so we mustn't attempt to call SV_COW_NEXT_SV(), as
5002            we'll fail an assertion.  */
5003         SV * const next = len ? SV_COW_NEXT_SV(sv) : 0;
5004 # endif
5005
5006         if (DEBUG_C_TEST) {
5007                 PerlIO_printf(Perl_debug_log,
5008                               "Copy on write: Force normal %ld\n",
5009                               (long) flags);
5010                 sv_dump(sv);
5011         }
5012         SvIsCOW_off(sv);
5013 # ifdef PERL_NEW_COPY_ON_WRITE
5014         if (len && CowREFCNT(sv) == 0)
5015             /* We own the buffer ourselves. */
5016             sv_buf_to_rw(sv);
5017         else
5018 # endif
5019         {
5020                 
5021             /* This SV doesn't own the buffer, so need to Newx() a new one:  */
5022 # ifdef PERL_NEW_COPY_ON_WRITE
5023             /* Must do this first, since the macro uses SvPVX. */
5024             if (len) {
5025                 sv_buf_to_rw(sv);
5026                 CowREFCNT(sv)--;
5027                 sv_buf_to_ro(sv);
5028             }
5029 # endif
5030             SvPV_set(sv, NULL);
5031             SvLEN_set(sv, 0);
5032             if (flags & SV_COW_DROP_PV) {
5033                 /* OK, so we don't need to copy our buffer.  */
5034                 SvPOK_off(sv);
5035             } else {
5036                 SvGROW(sv, cur + 1);
5037                 Move(pvx,SvPVX(sv),cur,char);
5038                 SvCUR_set(sv, cur);
5039                 *SvEND(sv) = '\0';
5040             }
5041             if (len) {
5042 # ifdef PERL_OLD_COPY_ON_WRITE
5043                 sv_release_COW(sv, pvx, next);
5044 # endif
5045             } else {
5046                 unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
5047             }
5048             if (DEBUG_C_TEST) {
5049                 sv_dump(sv);
5050             }
5051         }
5052 #else
5053             const char * const pvx = SvPVX_const(sv);
5054             const STRLEN len = SvCUR(sv);
5055             SvIsCOW_off(sv);
5056             SvPV_set(sv, NULL);
5057             SvLEN_set(sv, 0);
5058             if (flags & SV_COW_DROP_PV) {
5059                 /* OK, so we don't need to copy our buffer.  */
5060                 SvPOK_off(sv);
5061             } else {
5062                 SvGROW(sv, len + 1);
5063                 Move(pvx,SvPVX(sv),len,char);
5064                 *SvEND(sv) = '\0';
5065             }
5066             unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
5067 #endif
5068     }
5069 }
5070
5071 void
5072 Perl_sv_force_normal_flags(pTHX_ SV *const sv, const U32 flags)
5073 {
5074     PERL_ARGS_ASSERT_SV_FORCE_NORMAL_FLAGS;
5075
5076     if (SvREADONLY(sv))
5077         Perl_croak_no_modify();
5078     else if (SvIsCOW(sv))
5079         S_sv_uncow(aTHX_ sv, flags);
5080     if (SvROK(sv))
5081         sv_unref_flags(sv, flags);
5082     else if (SvFAKE(sv) && isGV_with_GP(sv))
5083         sv_unglob(sv, flags);
5084     else if (SvFAKE(sv) && isREGEXP(sv)) {
5085         /* Need to downgrade the REGEXP to a simple(r) scalar. This is analogous
5086            to sv_unglob. We only need it here, so inline it.  */
5087         const bool islv = SvTYPE(sv) == SVt_PVLV;
5088         const svtype new_type =
5089           islv ? SVt_NULL : SvMAGIC(sv) || SvSTASH(sv) ? SVt_PVMG : SVt_PV;
5090         SV *const temp = newSV_type(new_type);
5091         regexp *const temp_p = ReANY((REGEXP *)sv);
5092
5093         if (new_type == SVt_PVMG) {
5094             SvMAGIC_set(temp, SvMAGIC(sv));
5095             SvMAGIC_set(sv, NULL);
5096             SvSTASH_set(temp, SvSTASH(sv));
5097             SvSTASH_set(sv, NULL);
5098         }
5099         if (!islv) SvCUR_set(temp, SvCUR(sv));
5100         /* Remember that SvPVX is in the head, not the body.  But
5101            RX_WRAPPED is in the body. */
5102         assert(ReANY((REGEXP *)sv)->mother_re);
5103         /* Their buffer is already owned by someone else. */
5104         if (flags & SV_COW_DROP_PV) {
5105             /* SvLEN is already 0.  For SVt_REGEXP, we have a brand new
5106                zeroed body.  For SVt_PVLV, it should have been set to 0
5107                before turning into a regexp. */
5108             assert(!SvLEN(islv ? sv : temp));
5109             sv->sv_u.svu_pv = 0;
5110         }
5111         else {
5112             sv->sv_u.svu_pv = savepvn(RX_WRAPPED((REGEXP *)sv), SvCUR(sv));
5113             SvLEN_set(islv ? sv : temp, SvCUR(sv)+1);
5114             SvPOK_on(sv);
5115         }
5116
5117         /* Now swap the rest of the bodies. */
5118
5119         SvFAKE_off(sv);
5120         if (!islv) {
5121             SvFLAGS(sv) &= ~SVTYPEMASK;
5122             SvFLAGS(sv) |= new_type;
5123             SvANY(sv) = SvANY(temp);
5124         }
5125
5126         SvFLAGS(temp) &= ~(SVTYPEMASK);
5127         SvFLAGS(temp) |= SVt_REGEXP|SVf_FAKE;
5128         SvANY(temp) = temp_p;
5129         temp->sv_u.svu_rx = (regexp *)temp_p;
5130
5131         SvREFCNT_dec_NN(temp);
5132     }
5133     else if (SvVOK(sv)) sv_unmagic(sv, PERL_MAGIC_vstring);
5134 }
5135
5136 /*
5137 =for apidoc sv_chop
5138
5139 Efficient removal of characters from the beginning of the string buffer.
5140 SvPOK(sv), or at least SvPOKp(sv), must be true and the C<ptr> must be a
5141 pointer to somewhere inside the string buffer.  The C<ptr> becomes the first
5142 character of the adjusted string.  Uses the "OOK hack".  On return, only
5143 SvPOK(sv) and SvPOKp(sv) among the OK flags will be true.
5144
5145 Beware: after this function returns, C<ptr> and SvPVX_const(sv) may no longer
5146 refer to the same chunk of data.
5147
5148 The unfortunate similarity of this function's name to that of Perl's C<chop>
5149 operator is strictly coincidental.  This function works from the left;
5150 C<chop> works from the right.
5151
5152 =cut
5153 */
5154
5155 void
5156 Perl_sv_chop(pTHX_ SV *const sv, const char *const ptr)
5157 {
5158     STRLEN delta;
5159     STRLEN old_delta;
5160     U8 *p;
5161 #ifdef DEBUGGING
5162     const U8 *evacp;
5163     STRLEN evacn;
5164 #endif
5165     STRLEN max_delta;
5166
5167     PERL_ARGS_ASSERT_SV_CHOP;
5168
5169     if (!ptr || !SvPOKp(sv))
5170         return;
5171     delta = ptr - SvPVX_const(sv);
5172     if (!delta) {
5173         /* Nothing to do.  */
5174         return;
5175     }
5176     max_delta = SvLEN(sv) ? SvLEN(sv) : SvCUR(sv);
5177     if (delta > max_delta)
5178         Perl_croak(aTHX_ "panic: sv_chop ptr=%p, start=%p, end=%p",
5179                    ptr, SvPVX_const(sv), SvPVX_const(sv) + max_delta);
5180     /* SvPVX(sv) may move in SV_CHECK_THINKFIRST(sv), so don't use ptr any more */
5181     SV_CHECK_THINKFIRST(sv);
5182     SvPOK_only_UTF8(sv);
5183
5184     if (!SvOOK(sv)) {
5185         if (!SvLEN(sv)) { /* make copy of shared string */
5186             const char *pvx = SvPVX_const(sv);
5187             const STRLEN len = SvCUR(sv);
5188             SvGROW(sv, len + 1);
5189             Move(pvx,SvPVX(sv),len,char);
5190             *SvEND(sv) = '\0';
5191         }
5192         SvOOK_on(sv);
5193         old_delta = 0;
5194     } else {
5195         SvOOK_offset(sv, old_delta);
5196     }
5197     SvLEN_set(sv, SvLEN(sv) - delta);
5198     SvCUR_set(sv, SvCUR(sv) - delta);
5199     SvPV_set(sv, SvPVX(sv) + delta);
5200
5201     p = (U8 *)SvPVX_const(sv);
5202
5203 #ifdef DEBUGGING
5204     /* how many bytes were evacuated?  we will fill them with sentinel
5205        bytes, except for the part holding the new offset of course. */
5206     evacn = delta;
5207     if (old_delta)
5208         evacn += (old_delta < 0x100 ? 1 : 1 + sizeof(STRLEN));
5209     assert(evacn);
5210     assert(evacn <= delta + old_delta);
5211     evacp = p - evacn;
5212 #endif
5213
5214     /* This sets 'delta' to the accumulated value of all deltas so far */
5215     delta += old_delta;
5216     assert(delta);
5217
5218     /* If 'delta' fits in a byte, store it just prior to the new beginning of
5219      * the string; otherwise store a 0 byte there and store 'delta' just prior
5220      * to that, using as many bytes as a STRLEN occupies.  Thus it overwrites a
5221      * portion of the chopped part of the string */
5222     if (delta < 0x100) {
5223         *--p = (U8) delta;
5224     } else {
5225         *--p = 0;
5226         p -= sizeof(STRLEN);
5227         Copy((U8*)&delta, p, sizeof(STRLEN), U8);
5228     }
5229
5230 #ifdef DEBUGGING
5231     /* Fill the preceding buffer with sentinals to verify that no-one is
5232        using it.  */
5233     while (p > evacp) {
5234         --p;
5235         *p = (U8)PTR2UV(p);
5236     }
5237 #endif
5238 }
5239
5240 /*
5241 =for apidoc sv_catpvn
5242
5243 Concatenates the string onto the end of the string which is in the SV.  The
5244 C<len> indicates number of bytes to copy.  If the SV has the UTF-8
5245 status set, then the bytes appended should be valid UTF-8.
5246 Handles 'get' magic, but not 'set' magic.  See C<sv_catpvn_mg>.
5247
5248 =for apidoc sv_catpvn_flags
5249
5250 Concatenates the string onto the end of the string which is in the SV.  The
5251 C<len> indicates number of bytes to copy.  If the SV has the UTF-8
5252 status set, then the bytes appended should be valid UTF-8.
5253 If C<flags> has the C<SV_SMAGIC> bit set, will
5254 C<mg_set> on C<dsv> afterwards if appropriate.
5255 C<sv_catpvn> and C<sv_catpvn_nomg> are implemented
5256 in terms of this function.
5257
5258 =cut
5259 */
5260
5261 void
5262 Perl_sv_catpvn_flags(pTHX_ SV *const dsv, const char *sstr, const STRLEN slen, const I32 flags)
5263 {
5264     dVAR;
5265     STRLEN dlen;
5266     const char * const dstr = SvPV_force_flags(dsv, dlen, flags);
5267
5268     PERL_ARGS_ASSERT_SV_CATPVN_FLAGS;
5269     assert((flags & (SV_CATBYTES|SV_CATUTF8)) != (SV_CATBYTES|SV_CATUTF8));
5270
5271     if (!(flags & SV_CATBYTES) || !SvUTF8(dsv)) {
5272       if (flags & SV_CATUTF8 && !SvUTF8(dsv)) {
5273          sv_utf8_upgrade_flags_grow(dsv, 0, slen + 1);
5274          dlen = SvCUR(dsv);
5275       }
5276       else SvGROW(dsv, dlen + slen + 1);
5277       if (sstr == dstr)
5278         sstr = SvPVX_const(dsv);
5279       Move(sstr, SvPVX(dsv) + dlen, slen, char);
5280       SvCUR_set(dsv, SvCUR(dsv) + slen);
5281     }
5282     else {
5283         /* We inline bytes_to_utf8, to avoid an extra malloc. */
5284         const char * const send = sstr + slen;
5285         U8 *d;
5286
5287         /* Something this code does not account for, which I think is
5288            impossible; it would require the same pv to be treated as
5289            bytes *and* utf8, which would indicate a bug elsewhere. */
5290         assert(sstr != dstr);
5291
5292         SvGROW(dsv, dlen + slen * 2 + 1);
5293         d = (U8 *)SvPVX(dsv) + dlen;
5294
5295         while (sstr < send) {
5296             append_utf8_from_native_byte(*sstr, &d);
5297             sstr++;
5298         }
5299         SvCUR_set(dsv, d-(const U8 *)SvPVX(dsv));
5300     }
5301     *SvEND(dsv) = '\0';
5302     (void)SvPOK_only_UTF8(dsv);         /* validate pointer */
5303     SvTAINT(dsv);
5304     if (flags & SV_SMAGIC)
5305         SvSETMAGIC(dsv);
5306 }
5307
5308 /*
5309 =for apidoc sv_catsv
5310
5311 Concatenates the string from SV C<ssv> onto the end of the string in SV
5312 C<dsv>.  If C<ssv> is null, does nothing; otherwise modifies only C<dsv>.
5313 Handles 'get' magic on both SVs, but no 'set' magic.  See C<sv_catsv_mg> and
5314 C<sv_catsv_nomg>.
5315
5316 =for apidoc sv_catsv_flags
5317
5318 Concatenates the string from SV C<ssv> onto the end of the string in SV
5319 C<dsv>.  If C<ssv> is null, does nothing; otherwise modifies only C<dsv>.
5320 If C<flags> include C<SV_GMAGIC> bit set, will call C<mg_get> on both SVs if
5321 appropriate.  If C<flags> include C<SV_SMAGIC>, C<mg_set> will be called on
5322 the modified SV afterward, if appropriate.  C<sv_catsv>, C<sv_catsv_nomg>,
5323 and C<sv_catsv_mg> are implemented in terms of this function.
5324
5325 =cut */
5326
5327 void
5328 Perl_sv_catsv_flags(pTHX_ SV *const dsv, SV *const ssv, const I32 flags)
5329 {
5330     dVAR;
5331  
5332     PERL_ARGS_ASSERT_SV_CATSV_FLAGS;
5333
5334     if (ssv) {
5335         STRLEN slen;
5336         const char *spv = SvPV_flags_const(ssv, slen, flags);
5337         if (spv) {
5338             if (flags & SV_GMAGIC)
5339                 SvGETMAGIC(dsv);
5340             sv_catpvn_flags(dsv, spv, slen,
5341                             DO_UTF8(ssv) ? SV_CATUTF8 : SV_CATBYTES);
5342             if (flags & SV_SMAGIC)
5343                 SvSETMAGIC(dsv);
5344         }
5345     }
5346 }
5347
5348 /*
5349 =for apidoc sv_catpv
5350
5351 Concatenates the string onto the end of the string which is in the SV.
5352 If the SV has the UTF-8 status set, then the bytes appended should be
5353 valid UTF-8.  Handles 'get' magic, but not 'set' magic.  See C<sv_catpv_mg>.
5354
5355 =cut */
5356
5357 void
5358 Perl_sv_catpv(pTHX_ SV *const sv, const char *ptr)
5359 {
5360     dVAR;
5361     STRLEN len;
5362     STRLEN tlen;
5363     char *junk;
5364
5365     PERL_ARGS_ASSERT_SV_CATPV;
5366
5367     if (!ptr)
5368         return;
5369     junk = SvPV_force(sv, tlen);
5370     len = strlen(ptr);
5371     SvGROW(sv, tlen + len + 1);
5372     if (ptr == junk)
5373         ptr = SvPVX_const(sv);
5374     Move(ptr,SvPVX(sv)+tlen,len+1,char);
5375     SvCUR_set(sv, SvCUR(sv) + len);
5376     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
5377     SvTAINT(sv);
5378 }
5379
5380 /*
5381 =for apidoc sv_catpv_flags
5382
5383 Concatenates the string onto the end of the string which is in the SV.
5384 If the SV has the UTF-8 status set, then the bytes appended should
5385 be valid UTF-8.  If C<flags> has the C<SV_SMAGIC> bit set, will C<mg_set>
5386 on the modified SV if appropriate.
5387
5388 =cut
5389 */
5390
5391 void
5392 Perl_sv_catpv_flags(pTHX_ SV *dstr, const char *sstr, const I32 flags)
5393 {
5394     PERL_ARGS_ASSERT_SV_CATPV_FLAGS;
5395     sv_catpvn_flags(dstr, sstr, strlen(sstr), flags);
5396 }
5397
5398 /*
5399 =for apidoc sv_catpv_mg
5400
5401 Like C<sv_catpv>, but also handles 'set' magic.
5402
5403 =cut
5404 */
5405
5406 void
5407 Perl_sv_catpv_mg(pTHX_ SV *const sv, const char *const ptr)
5408 {
5409     PERL_ARGS_ASSERT_SV_CATPV_MG;
5410
5411     sv_catpv(sv,ptr);
5412     SvSETMAGIC(sv);
5413 }
5414
5415 /*
5416 =for apidoc newSV
5417
5418 Creates a new SV.  A non-zero C<len> parameter indicates the number of
5419 bytes of preallocated string space the SV should have.  An extra byte for a
5420 trailing NUL is also reserved.  (SvPOK is not set for the SV even if string
5421 space is allocated.)  The reference count for the new SV is set to 1.
5422
5423 In 5.9.3, newSV() replaces the older NEWSV() API, and drops the first
5424 parameter, I<x>, a debug aid which allowed callers to identify themselves.
5425 This aid has been superseded by a new build option, PERL_MEM_LOG (see
5426 L<perlhacktips/PERL_MEM_LOG>).  The older API is still there for use in XS
5427 modules supporting older perls.
5428
5429 =cut
5430 */
5431
5432 SV *
5433 Perl_newSV(pTHX_ const STRLEN len)
5434 {
5435     dVAR;
5436     SV *sv;
5437
5438     new_SV(sv);
5439     if (len) {
5440         sv_upgrade(sv, SVt_PV);
5441         SvGROW(sv, len + 1);
5442     }
5443     return sv;
5444 }
5445 /*
5446 =for apidoc sv_magicext
5447
5448 Adds magic to an SV, upgrading it if necessary.  Applies the
5449 supplied vtable and returns a pointer to the magic added.
5450
5451 Note that C<sv_magicext> will allow things that C<sv_magic> will not.
5452 In particular, you can add magic to SvREADONLY SVs, and add more than
5453 one instance of the same 'how'.
5454
5455 If C<namlen> is greater than zero then a C<savepvn> I<copy> of C<name> is
5456 stored, if C<namlen> is zero then C<name> is stored as-is and - as another
5457 special case - if C<(name && namlen == HEf_SVKEY)> then C<name> is assumed
5458 to contain an C<SV*> and is stored as-is with its REFCNT incremented.
5459
5460 (This is now used as a subroutine by C<sv_magic>.)
5461
5462 =cut
5463 */
5464 MAGIC * 
5465 Perl_sv_magicext(pTHX_ SV *const sv, SV *const obj, const int how, 
5466                 const MGVTBL *const vtable, const char *const name, const I32 namlen)
5467 {
5468     dVAR;
5469     MAGIC* mg;
5470
5471     PERL_ARGS_ASSERT_SV_MAGICEXT;
5472
5473     if (SvTYPE(sv)==SVt_PVAV) { assert (!AvPAD_NAMELIST(sv)); }
5474
5475     SvUPGRADE(sv, SVt_PVMG);
5476     Newxz(mg, 1, MAGIC);
5477     mg->mg_moremagic = SvMAGIC(sv);
5478     SvMAGIC_set(sv, mg);
5479
5480     /* Sometimes a magic contains a reference loop, where the sv and
5481        object refer to each other.  To prevent a reference loop that
5482        would prevent such objects being freed, we look for such loops
5483        and if we find one we avoid incrementing the object refcount.
5484
5485        Note we cannot do this to avoid self-tie loops as intervening RV must
5486        have its REFCNT incremented to keep it in existence.
5487
5488     */
5489     if (!obj || obj == sv ||
5490         how == PERL_MAGIC_arylen ||
5491         how == PERL_MAGIC_symtab ||
5492         (SvTYPE(obj) == SVt_PVGV &&
5493             (GvSV(obj) == sv || GvHV(obj) == (const HV *)sv
5494              || GvAV(obj) == (const AV *)sv || GvCV(obj) == (const CV *)sv
5495              || GvIOp(obj) == (const IO *)sv || GvFORM(obj) == (const CV *)sv)))
5496     {
5497         mg->mg_obj = obj;
5498     }
5499     else {
5500         mg->mg_obj = SvREFCNT_inc_simple(obj);
5501         mg->mg_flags |= MGf_REFCOUNTED;
5502     }
5503
5504     /* Normal self-ties simply pass a null object, and instead of
5505        using mg_obj directly, use the SvTIED_obj macro to produce a
5506        new RV as needed.  For glob "self-ties", we are tieing the PVIO
5507        with an RV obj pointing to the glob containing the PVIO.  In
5508        this case, to avoid a reference loop, we need to weaken the
5509        reference.
5510     */
5511
5512     if (how == PERL_MAGIC_tiedscalar && SvTYPE(sv) == SVt_PVIO &&
5513         obj && SvROK(obj) && GvIO(SvRV(obj)) == (const IO *)sv)
5514     {
5515       sv_rvweaken(obj);
5516     }
5517
5518     mg->mg_type = how;
5519     mg->mg_len = namlen;
5520     if (name) {
5521         if (namlen > 0)
5522             mg->mg_ptr = savepvn(name, namlen);
5523         else if (namlen == HEf_SVKEY) {
5524             /* Yes, this is casting away const. This is only for the case of
5525                HEf_SVKEY. I think we need to document this aberation of the
5526                constness of the API, rather than making name non-const, as
5527                that change propagating outwards a long way.  */
5528             mg->mg_ptr = (char*)SvREFCNT_inc_simple_NN((SV *)name);
5529         } else
5530             mg->mg_ptr = (char *) name;
5531     }
5532     mg->mg_virtual = (MGVTBL *) vtable;
5533
5534     mg_magical(sv);
5535     return mg;
5536 }
5537
5538 MAGIC *
5539 Perl_sv_magicext_mglob(pTHX_ SV *sv)
5540 {
5541     PERL_ARGS_ASSERT_SV_MAGICEXT_MGLOB;
5542     if (SvTYPE(sv) == SVt_PVLV && LvTYPE(sv) == 'y') {
5543         /* This sv is only a delegate.  //g magic must be attached to
5544            its target. */
5545         vivify_defelem(sv);
5546         sv = LvTARG(sv);
5547     }
5548 #ifdef PERL_OLD_COPY_ON_WRITE
5549     if (SvIsCOW(sv))
5550         sv_force_normal_flags(sv, 0);
5551 #endif
5552     return sv_magicext(sv, NULL, PERL_MAGIC_regex_global,
5553                        &PL_vtbl_mglob, 0, 0);
5554 }
5555
5556 /*
5557 =for apidoc sv_magic
5558
5559 Adds magic to an SV.  First upgrades C<sv> to type C<SVt_PVMG> if
5560 necessary, then adds a new magic item of type C<how> to the head of the
5561 magic list.
5562
5563 See C<sv_magicext> (which C<sv_magic> now calls) for a description of the
5564 handling of the C<name> and C<namlen> arguments.
5565
5566 You need to use C<sv_magicext> to add magic to SvREADONLY SVs and also
5567 to add more than one instance of the same 'how'.
5568
5569 =cut
5570 */
5571
5572 void
5573 Perl_sv_magic(pTHX_ SV *const sv, SV *const obj, const int how,
5574              const char *const name, const I32 namlen)
5575 {
5576     dVAR;
5577     const MGVTBL *vtable;
5578     MAGIC* mg;
5579     unsigned int flags;
5580     unsigned int vtable_index;
5581
5582     PERL_ARGS_ASSERT_SV_MAGIC;
5583
5584     if (how < 0 || (unsigned)how >= C_ARRAY_LENGTH(PL_magic_data)
5585         || ((flags = PL_magic_data[how]),
5586             (vtable_index = flags & PERL_MAGIC_VTABLE_MASK)
5587             > magic_vtable_max))
5588         Perl_croak(aTHX_ "Don't know how to handle magic of type \\%o", how);
5589
5590     /* PERL_MAGIC_ext is reserved for use by extensions not perl internals.
5591        Useful for attaching extension internal data to perl vars.
5592        Note that multiple extensions may clash if magical scalars
5593        etc holding private data from one are passed to another. */
5594
5595     vtable = (vtable_index == magic_vtable_max)
5596         ? NULL : PL_magic_vtables + vtable_index;
5597
5598 #ifdef PERL_OLD_COPY_ON_WRITE
5599     if (SvIsCOW(sv))
5600         sv_force_normal_flags(sv, 0);
5601 #endif
5602     if (SvREADONLY(sv)) {
5603         if (
5604             !PERL_MAGIC_TYPE_READONLY_ACCEPTABLE(how)
5605            )
5606         {
5607             Perl_croak_no_modify();
5608         }
5609     }
5610     if (SvMAGICAL(sv) || (how == PERL_MAGIC_taint && SvTYPE(sv) >= SVt_PVMG)) {
5611         if (SvMAGIC(sv) && (mg = mg_find(sv, how))) {
5612             /* sv_magic() refuses to add a magic of the same 'how' as an
5613                existing one
5614              */
5615             if (how == PERL_MAGIC_taint)
5616                 mg->mg_len |= 1;
5617             return;
5618         }
5619     }
5620
5621     /* Force pos to be stored as characters, not bytes. */
5622     if (SvMAGICAL(sv) && DO_UTF8(sv)
5623       && (mg = mg_find(sv, PERL_MAGIC_regex_global))
5624       && mg->mg_len != -1
5625       && mg->mg_flags & MGf_BYTES) {
5626         mg->mg_len = (SSize_t)sv_pos_b2u_flags(sv, (STRLEN)mg->mg_len,
5627                                                SV_CONST_RETURN);
5628         mg->mg_flags &= ~MGf_BYTES;
5629     }
5630
5631     /* Rest of work is done else where */
5632     mg = sv_magicext(sv,obj,how,vtable,name,namlen);
5633
5634     switch (how) {
5635     case PERL_MAGIC_taint:
5636         mg->mg_len = 1;
5637         break;
5638     case PERL_MAGIC_ext:
5639     case PERL_MAGIC_dbfile:
5640         SvRMAGICAL_on(sv);
5641         break;
5642     }
5643 }
5644
5645 static int
5646 S_sv_unmagicext_flags(pTHX_ SV *const sv, const int type, MGVTBL *vtbl, const U32 flags)
5647 {
5648     MAGIC* mg;
5649     MAGIC** mgp;
5650
5651     assert(flags <= 1);
5652
5653     if (SvTYPE(sv) < SVt_PVMG || !SvMAGIC(sv))
5654         return 0;
5655     mgp = &(((XPVMG*) SvANY(sv))->xmg_u.xmg_magic);
5656     for (mg = *mgp; mg; mg = *mgp) {
5657         const MGVTBL* const virt = mg->mg_virtual;
5658         if (mg->mg_type == type && (!flags || virt == vtbl)) {
5659             *mgp = mg->mg_moremagic;
5660             if (virt && virt->svt_free)
5661                 virt->svt_free(aTHX_ sv, mg);
5662             if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) {
5663                 if (mg->mg_len > 0)
5664                     Safefree(mg->mg_ptr);
5665                 else if (mg->mg_len == HEf_SVKEY)
5666                     SvREFCNT_dec(MUTABLE_SV(mg->mg_ptr));
5667                 else if (mg->mg_type == PERL_MAGIC_utf8)
5668                     Safefree(mg->mg_ptr);
5669             }
5670             if (mg->mg_flags & MGf_REFCOUNTED)
5671                 SvREFCNT_dec(mg->mg_obj);
5672             Safefree(mg);
5673         }
5674         else
5675             mgp = &mg->mg_moremagic;
5676     }
5677     if (SvMAGIC(sv)) {
5678         if (SvMAGICAL(sv))      /* if we're under save_magic, wait for restore_magic; */
5679             mg_magical(sv);     /*    else fix the flags now */
5680     }
5681     else {
5682         SvMAGICAL_off(sv);
5683         SvFLAGS(sv) |= (SvFLAGS(sv) & (SVp_IOK|SVp_NOK|SVp_POK)) >> PRIVSHIFT;
5684     }
5685     return 0;
5686 }
5687
5688 /*
5689 =for apidoc sv_unmagic
5690
5691 Removes all magic of type C<type> from an SV.
5692
5693 =cut
5694 */
5695
5696 int
5697 Perl_sv_unmagic(pTHX_ SV *const sv, const int type)
5698 {
5699     PERL_ARGS_ASSERT_SV_UNMAGIC;
5700     return S_sv_unmagicext_flags(aTHX_ sv, type, NULL, 0);
5701 }
5702
5703 /*
5704 =for apidoc sv_unmagicext
5705
5706 Removes all magic of type C<type> with the specified C<vtbl> from an SV.
5707
5708 =cut
5709 */
5710
5711 int
5712 Perl_sv_unmagicext(pTHX_ SV *const sv, const int type, MGVTBL *vtbl)
5713 {
5714     PERL_ARGS_ASSERT_SV_UNMAGICEXT;
5715     return S_sv_unmagicext_flags(aTHX_ sv, type, vtbl, 1);
5716 }
5717
5718 /*
5719 =for apidoc sv_rvweaken
5720
5721 Weaken a reference: set the C<SvWEAKREF> flag on this RV; give the
5722 referred-to SV C<PERL_MAGIC_backref> magic if it hasn't already; and
5723 push a back-reference to this RV onto the array of backreferences
5724 associated with that magic.  If the RV is magical, set magic will be
5725 called after the RV is cleared.
5726
5727 =cut
5728 */
5729
5730 SV *
5731 Perl_sv_rvweaken(pTHX_ SV *const sv)
5732 {
5733     SV *tsv;
5734
5735     PERL_ARGS_ASSERT_SV_RVWEAKEN;
5736
5737     if (!SvOK(sv))  /* let undefs pass */
5738         return sv;
5739     if (!SvROK(sv))
5740         Perl_croak(aTHX_ "Can't weaken a nonreference");
5741     else if (SvWEAKREF(sv)) {
5742         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Reference is already weak");
5743         return sv;
5744     }
5745     else if (SvREADONLY(sv)) croak_no_modify();
5746     tsv = SvRV(sv);
5747     Perl_sv_add_backref(aTHX_ tsv, sv);
5748     SvWEAKREF_on(sv);
5749     SvREFCNT_dec_NN(tsv);
5750     return sv;
5751 }
5752
5753 /* Give tsv backref magic if it hasn't already got it, then push a
5754  * back-reference to sv onto the array associated with the backref magic.
5755  *
5756  * As an optimisation, if there's only one backref and it's not an AV,
5757  * store it directly in the HvAUX or mg_obj slot, avoiding the need to
5758  * allocate an AV. (Whether the slot holds an AV tells us whether this is
5759  * active.)
5760  */
5761
5762 /* A discussion about the backreferences array and its refcount:
5763  *
5764  * The AV holding the backreferences is pointed to either as the mg_obj of
5765  * PERL_MAGIC_backref, or in the specific case of a HV, from the
5766  * xhv_backreferences field. The array is created with a refcount
5767  * of 2. This means that if during global destruction the array gets
5768  * picked on before its parent to have its refcount decremented by the
5769  * random zapper, it won't actually be freed, meaning it's still there for
5770  * when its parent gets freed.
5771  *
5772  * When the parent SV is freed, the extra ref is killed by
5773  * Perl_sv_kill_backrefs.  The other ref is killed, in the case of magic,
5774  * by mg_free() / MGf_REFCOUNTED, or for a hash, by Perl_hv_kill_backrefs.
5775  *
5776  * When a single backref SV is stored directly, it is not reference
5777  * counted.
5778  */
5779
5780 void
5781 Perl_sv_add_backref(pTHX_ SV *const tsv, SV *const sv)
5782 {
5783     dVAR;
5784     SV **svp;
5785     AV *av = NULL;
5786     MAGIC *mg = NULL;
5787
5788     PERL_ARGS_ASSERT_SV_ADD_BACKREF;
5789
5790     /* find slot to store array or singleton backref */
5791
5792     if (SvTYPE(tsv) == SVt_PVHV) {
5793         svp = (SV**)Perl_hv_backreferences_p(aTHX_ MUTABLE_HV(tsv));
5794     } else {
5795         if (SvMAGICAL(tsv))
5796             mg = mg_find(tsv, PERL_MAGIC_backref);
5797         if (!mg)
5798             mg = sv_magicext(tsv, NULL, PERL_MAGIC_backref, &PL_vtbl_backref, NULL, 0);
5799         svp = &(mg->mg_obj);
5800     }
5801
5802     /* create or retrieve the array */
5803
5804     if (   (!*svp && SvTYPE(sv) == SVt_PVAV)
5805         || (*svp && SvTYPE(*svp) != SVt_PVAV)
5806     ) {
5807         /* create array */
5808         if (mg)
5809             mg->mg_flags |= MGf_REFCOUNTED;
5810         av = newAV();
5811         AvREAL_off(av);
5812         SvREFCNT_inc_simple_void_NN(av);
5813         /* av now has a refcnt of 2; see discussion above */
5814         av_extend(av, *svp ? 2 : 1);
5815         if (*svp) {
5816             /* move single existing backref to the array */
5817             AvARRAY(av)[++AvFILLp(av)] = *svp; /* av_push() */
5818         }
5819         *svp = (SV*)av;
5820     }
5821     else {
5822         av = MUTABLE_AV(*svp);
5823         if (!av) {
5824             /* optimisation: store single backref directly in HvAUX or mg_obj */
5825             *svp = sv;
5826             return;
5827         }
5828         assert(SvTYPE(av) == SVt_PVAV);
5829         if (AvFILLp(av) >= AvMAX(av)) {
5830             av_extend(av, AvFILLp(av)+1);
5831         }
5832     }
5833     /* push new backref */
5834     AvARRAY(av)[++AvFILLp(av)] = sv; /* av_push() */
5835 }
5836
5837 /* delete a back-reference to ourselves from the backref magic associated
5838  * with the SV we point to.
5839  */
5840
5841 void
5842 Perl_sv_del_backref(pTHX_ SV *const tsv, SV *const sv)
5843 {
5844     dVAR;
5845     SV **svp = NULL;
5846
5847     PERL_ARGS_ASSERT_SV_DEL_BACKREF;
5848
5849     if (SvTYPE(tsv) == SVt_PVHV) {
5850         if (SvOOK(tsv))
5851             svp = (SV**)Perl_hv_backreferences_p(aTHX_ MUTABLE_HV(tsv));
5852     }
5853     else if (SvIS_FREED(tsv) && PL_phase == PERL_PHASE_DESTRUCT) {
5854         /* It's possible for the the last (strong) reference to tsv to have
5855            become freed *before* the last thing holding a weak reference.
5856            If both survive longer than the backreferences array, then when
5857            the referent's reference count drops to 0 and it is freed, it's
5858            not able to chase the backreferences, so they aren't NULLed.
5859
5860            For example, a CV holds a weak reference to its stash. If both the
5861            CV and the stash survive longer than the backreferences array,
5862            and the CV gets picked for the SvBREAK() treatment first,
5863            *and* it turns out that the stash is only being kept alive because
5864            of an our variable in the pad of the CV, then midway during CV
5865            destruction the stash gets freed, but CvSTASH() isn't set to NULL.
5866            It ends up pointing to the freed HV. Hence it's chased in here, and
5867            if this block wasn't here, it would hit the !svp panic just below.
5868
5869            I don't believe that "better" destruction ordering is going to help
5870            here - during global destruction there's always going to be the
5871            chance that something goes out of order. We've tried to make it
5872            foolproof before, and it only resulted in evolutionary pressure on
5873            fools. Which made us look foolish for our hubris. :-(
5874         */
5875         return;
5876     }
5877     else {
5878         MAGIC *const mg
5879             = SvMAGICAL(tsv) ? mg_find(tsv, PERL_MAGIC_backref) : NULL;
5880         svp =  mg ? &(mg->mg_obj) : NULL;
5881     }
5882
5883     if (!svp)
5884         Perl_croak(aTHX_ "panic: del_backref, svp=0");
5885     if (!*svp) {
5886         /* It's possible that sv is being freed recursively part way through the
5887            freeing of tsv. If this happens, the backreferences array of tsv has
5888            already been freed, and so svp will be NULL. If this is the case,
5889            we should not panic. Instead, nothing needs doing, so return.  */
5890         if (PL_phase == PERL_PHASE_DESTRUCT && SvREFCNT(tsv) == 0)
5891             return;
5892         Perl_croak(aTHX_ "panic: del_backref, *svp=%p phase=%s refcnt=%" UVuf,
5893                    *svp, PL_phase_names[PL_phase], (UV)SvREFCNT(tsv));
5894     }
5895
5896     if (SvTYPE(*svp) == SVt_PVAV) {
5897 #ifdef DEBUGGING
5898         int count = 1;
5899 #endif
5900         AV * const av = (AV*)*svp;
5901         SSize_t fill;
5902         assert(!SvIS_FREED(av));
5903         fill = AvFILLp(av);
5904         assert(fill > -1);
5905         svp = AvARRAY(av);
5906         /* for an SV with N weak references to it, if all those
5907          * weak refs are deleted, then sv_del_backref will be called
5908          * N times and O(N^2) compares will be done within the backref
5909          * array. To ameliorate this potential slowness, we:
5910          * 1) make sure this code is as tight as possible;
5911          * 2) when looking for SV, look for it at both the head and tail of the
5912          *    array first before searching the rest, since some create/destroy
5913          *    patterns will cause the backrefs to be freed in order.
5914          */
5915         if (*svp == sv) {
5916             AvARRAY(av)++;
5917             AvMAX(av)--;
5918         }
5919         else {
5920             SV **p = &svp[fill];
5921             SV *const topsv = *p;
5922             if (topsv != sv) {
5923 #ifdef DEBUGGING
5924                 count = 0;
5925 #endif
5926                 while (--p > svp) {
5927                     if (*p == sv) {
5928                         /* We weren't the last entry.
5929                            An unordered list has this property that you
5930                            can take the last element off the end to fill
5931                            the hole, and it's still an unordered list :-)
5932                         */
5933                         *p = topsv;
5934 #ifdef DEBUGGING
5935                         count++;
5936 #else
5937                         break; /* should only be one */
5938 #endif
5939                     }
5940                 }
5941             }
5942         }
5943         assert(count ==1);
5944         AvFILLp(av) = fill-1;
5945     }
5946     else if (SvIS_FREED(*svp) && PL_phase == PERL_PHASE_DESTRUCT) {
5947         /* freed AV; skip */
5948     }
5949     else {
5950         /* optimisation: only a single backref, stored directly */
5951         if (*svp != sv)
5952             Perl_croak(aTHX_ "panic: del_backref, *svp=%p, sv=%p", *svp, sv);
5953         *svp = NULL;
5954     }
5955
5956 }
5957
5958 void
5959 Perl_sv_kill_backrefs(pTHX_ SV *const sv, AV *const av)
5960 {
5961     SV **svp;
5962     SV **last;
5963     bool is_array;
5964
5965     PERL_ARGS_ASSERT_SV_KILL_BACKREFS;
5966
5967     if (!av)
5968         return;
5969
5970     /* after multiple passes through Perl_sv_clean_all() for a thingy
5971      * that has badly leaked, the backref array may have gotten freed,
5972      * since we only protect it against 1 round of cleanup */
5973     if (SvIS_FREED(av)) {
5974         if (PL_in_clean_all) /* All is fair */
5975             return;
5976         Perl_croak(aTHX_
5977                    "panic: magic_killbackrefs (freed backref AV/SV)");
5978     }
5979
5980
5981     is_array = (SvTYPE(av) == SVt_PVAV);
5982     if (is_array) {
5983         assert(!SvIS_FREED(av));
5984         svp = AvARRAY(av);
5985         if (svp)
5986             last = svp + AvFILLp(av);
5987     }
5988     else {
5989         /* optimisation: only a single backref, stored directly */
5990         svp = (SV**)&av;
5991         last = svp;
5992     }
5993
5994     if (svp) {
5995         while (svp <= last) {
5996             if (*svp) {
5997                 SV *const referrer = *svp;
5998                 if (SvWEAKREF(referrer)) {
5999                     /* XXX Should we check that it hasn't changed? */
6000                     assert(SvROK(referrer));
6001                     SvRV_set(referrer, 0);
6002                     SvOK_off(referrer);
6003                     SvWEAKREF_off(referrer);
6004                     SvSETMAGIC(referrer);
6005                 } else if (SvTYPE(referrer) == SVt_PVGV ||
6006                            SvTYPE(referrer) == SVt_PVLV) {
6007                     assert(SvTYPE(sv) == SVt_PVHV); /* stash backref */
6008                     /* You lookin' at me?  */
6009                     assert(GvSTASH(referrer));
6010                     assert(GvSTASH(referrer) == (const HV *)sv);
6011                     GvSTASH(referrer) = 0;
6012                 } else if (SvTYPE(referrer) == SVt_PVCV ||
6013                            SvTYPE(referrer) == SVt_PVFM) {
6014                     if (SvTYPE(sv) == SVt_PVHV) { /* stash backref */
6015                         /* You lookin' at me?  */
6016                         assert(CvSTASH(referrer));
6017                         assert(CvSTASH(referrer) == (const HV *)sv);
6018                         SvANY(MUTABLE_CV(referrer))->xcv_stash = 0;
6019                     }
6020                     else {
6021                         assert(SvTYPE(sv) == SVt_PVGV);
6022                         /* You lookin' at me?  */
6023                         assert(CvGV(referrer));
6024                         assert(CvGV(referrer) == (const GV *)sv);
6025                         anonymise_cv_maybe(MUTABLE_GV(sv),
6026                                                 MUTABLE_CV(referrer));
6027                     }
6028
6029                 } else {
6030                     Perl_croak(aTHX_
6031                                "panic: magic_killbackrefs (flags=%"UVxf")",
6032                                (UV)SvFLAGS(referrer));
6033                 }
6034
6035                 if (is_array)
6036                     *svp = NULL;
6037             }
6038             svp++;
6039         }
6040     }
6041     if (is_array) {
6042         AvFILLp(av) = -1;
6043         SvREFCNT_dec_NN(av); /* remove extra count added by sv_add_backref() */
6044     }
6045     return;
6046 }
6047
6048 /*
6049 =for apidoc sv_insert
6050
6051 Inserts a string at the specified offset/length within the SV.  Similar to
6052 the Perl substr() function.  Handles get magic.
6053
6054 =for apidoc sv_insert_flags
6055
6056 Same as C<sv_insert>, but the extra C<flags> are passed to the
6057 C<SvPV_force_flags> that applies to C<bigstr>.
6058
6059 =cut
6060 */
6061
6062 void
6063 Perl_sv_insert_flags(pTHX_ SV *const bigstr, const STRLEN offset, const STRLEN len, const char *const little, const STRLEN littlelen, const U32 flags)
6064 {
6065     dVAR;
6066     char *big;
6067     char *mid;
6068     char *midend;
6069     char *bigend;
6070     SSize_t i;          /* better be sizeof(STRLEN) or bad things happen */
6071     STRLEN curlen;
6072
6073     PERL_ARGS_ASSERT_SV_INSERT_FLAGS;
6074
6075     if (!bigstr)
6076         Perl_croak(aTHX_ "Can't modify nonexistent substring");
6077     SvPV_force_flags(bigstr, curlen, flags);
6078     (void)SvPOK_only_UTF8(bigstr);
6079     if (offset + len > curlen) {
6080         SvGROW(bigstr, offset+len+1);
6081         Zero(SvPVX(bigstr)+curlen, offset+len-curlen, char);
6082         SvCUR_set(bigstr, offset+len);
6083     }
6084
6085     SvTAINT(bigstr);
6086     i = littlelen - len;
6087     if (i > 0) {                        /* string might grow */
6088         big = SvGROW(bigstr, SvCUR(bigstr) + i + 1);
6089         mid = big + offset + len;
6090         midend = bigend = big + SvCUR(bigstr);
6091         bigend += i;
6092         *bigend = '\0';
6093         while (midend > mid)            /* shove everything down */
6094             *--bigend = *--midend;
6095         Move(little,big+offset,littlelen,char);
6096         SvCUR_set(bigstr, SvCUR(bigstr) + i);
6097         SvSETMAGIC(bigstr);
6098         return;
6099     }
6100     else if (i == 0) {
6101         Move(little,SvPVX(bigstr)+offset,len,char);
6102         SvSETMAGIC(bigstr);
6103         return;
6104     }
6105
6106     big = SvPVX(bigstr);
6107     mid = big + offset;
6108     midend = mid + len;
6109     bigend = big + SvCUR(bigstr);
6110
6111     if (midend > bigend)
6112         Perl_croak(aTHX_ "panic: sv_insert, midend=%p, bigend=%p",
6113                    midend, bigend);
6114
6115     if (mid - big > bigend - midend) {  /* faster to shorten from end */
6116         if (littlelen) {
6117             Move(little, mid, littlelen,char);
6118             mid += littlelen;
6119         }
6120         i = bigend - midend;
6121         if (i > 0) {
6122             Move(midend, mid, i,char);
6123             mid += i;
6124         }
6125         *mid = '\0';
6126         SvCUR_set(bigstr, mid - big);
6127     }
6128     else if ((i = mid - big)) { /* faster from front */
6129         midend -= littlelen;
6130         mid = midend;
6131         Move(big, midend - i, i, char);
6132         sv_chop(bigstr,midend-i);
6133         if (littlelen)
6134             Move(little, mid, littlelen,char);
6135     }
6136     else if (littlelen) {
6137         midend -= littlelen;
6138         sv_chop(bigstr,midend);
6139         Move(little,midend,littlelen,char);
6140     }
6141     else {
6142         sv_chop(bigstr,midend);
6143     }
6144     SvSETMAGIC(bigstr);
6145 }
6146
6147 /*
6148 =for apidoc sv_replace
6149
6150 Make the first argument a copy of the second, then delete the original.
6151 The target SV physically takes over ownership of the body of the source SV
6152 and inherits its flags; however, the target keeps any magic it owns,
6153 and any magic in the source is discarded.
6154 Note that this is a rather specialist SV copying operation; most of the
6155 time you'll want to use C<sv_setsv> or one of its many macro front-ends.
6156
6157 =cut
6158 */
6159
6160 void
6161 Perl_sv_replace(pTHX_ SV *const sv, SV *const nsv)
6162 {
6163     dVAR;
6164     const U32 refcnt = SvREFCNT(sv);
6165
6166     PERL_ARGS_ASSERT_SV_REPLACE;
6167
6168     SV_CHECK_THINKFIRST_COW_DROP(sv);
6169     if (SvREFCNT(nsv) != 1) {
6170         Perl_croak(aTHX_ "panic: reference miscount on nsv in sv_replace()"
6171                    " (%" UVuf " != 1)", (UV) SvREFCNT(nsv));
6172     }
6173     if (SvMAGICAL(sv)) {
6174         if (SvMAGICAL(nsv))
6175             mg_free(nsv);
6176         else
6177             sv_upgrade(nsv, SVt_PVMG);
6178         SvMAGIC_set(nsv, SvMAGIC(sv));
6179         SvFLAGS(nsv) |= SvMAGICAL(sv);
6180         SvMAGICAL_off(sv);
6181         SvMAGIC_set(sv, NULL);
6182     }
6183     SvREFCNT(sv) = 0;
6184     sv_clear(sv);
6185     assert(!SvREFCNT(sv));
6186 #ifdef DEBUG_LEAKING_SCALARS
6187     sv->sv_flags  = nsv->sv_flags;
6188     sv->sv_any    = nsv->sv_any;
6189     sv->sv_refcnt = nsv->sv_refcnt;
6190     sv->sv_u      = nsv->sv_u;
6191 #else
6192     StructCopy(nsv,sv,SV);
6193 #endif
6194     if(SvTYPE(sv) == SVt_IV) {
6195         SvANY(sv)
6196             = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
6197     }
6198         
6199
6200 #ifdef PERL_OLD_COPY_ON_WRITE
6201     if (SvIsCOW_normal(nsv)) {
6202         /* We need to follow the pointers around the loop to make the
6203            previous SV point to sv, rather than nsv.  */
6204         SV *next;
6205         SV *current = nsv;
6206         while ((next = SV_COW_NEXT_SV(current)) != nsv) {
6207             assert(next);
6208             current = next;
6209             assert(SvPVX_const(current) == SvPVX_const(nsv));
6210         }
6211         /* Make the SV before us point to the SV after us.  */
6212         if (DEBUG_C_TEST) {
6213             PerlIO_printf(Perl_debug_log, "previous is\n");
6214             sv_dump(current);
6215             PerlIO_printf(Perl_debug_log,
6216                           "move it from 0x%"UVxf" to 0x%"UVxf"\n",
6217                           (UV) SV_COW_NEXT_SV(current), (UV) sv);
6218         }
6219         SV_COW_NEXT_SV_SET(current, sv);
6220     }
6221 #endif
6222     SvREFCNT(sv) = refcnt;
6223     SvFLAGS(nsv) |= SVTYPEMASK;         /* Mark as freed */
6224     SvREFCNT(nsv) = 0;
6225     del_SV(nsv);
6226 }
6227
6228 /* We're about to free a GV which has a CV that refers back to us.
6229  * If that CV will outlive us, make it anonymous (i.e. fix up its CvGV
6230  * field) */
6231
6232 STATIC void
6233 S_anonymise_cv_maybe(pTHX_ GV *gv, CV* cv)
6234 {
6235     SV *gvname;
6236     GV *anongv;
6237
6238     PERL_ARGS_ASSERT_ANONYMISE_CV_MAYBE;
6239
6240     /* be assertive! */
6241     assert(SvREFCNT(gv) == 0);
6242     assert(isGV(gv) && isGV_with_GP(gv));
6243     assert(GvGP(gv));
6244     assert(!CvANON(cv));
6245     assert(CvGV(cv) == gv);
6246     assert(!CvNAMED(cv));
6247
6248     /* will the CV shortly be freed by gp_free() ? */
6249     if (GvCV(gv) == cv && GvGP(gv)->gp_refcnt < 2 && SvREFCNT(cv) < 2) {
6250         SvANY(cv)->xcv_gv_u.xcv_gv = NULL;
6251         return;
6252     }
6253
6254     /* if not, anonymise: */
6255     gvname = (GvSTASH(gv) && HvNAME(GvSTASH(gv)) && HvENAME(GvSTASH(gv)))
6256                     ? newSVhek(HvENAME_HEK(GvSTASH(gv)))
6257                     : newSVpvn_flags( "__ANON__", 8, 0 );
6258     sv_catpvs(gvname, "::__ANON__");
6259     anongv = gv_fetchsv(gvname, GV_ADDMULTI, SVt_PVCV);
6260     SvREFCNT_dec_NN(gvname);
6261
6262     CvANON_on(cv);
6263     CvCVGV_RC_on(cv);
6264     SvANY(cv)->xcv_gv_u.xcv_gv = MUTABLE_GV(SvREFCNT_inc(anongv));
6265 }
6266
6267
6268 /*
6269 =for apidoc sv_clear
6270
6271 Clear an SV: call any destructors, free up any memory used by the body,
6272 and free the body itself.  The SV's head is I<not> freed, although
6273 its type is set to all 1's so that it won't inadvertently be assumed
6274 to be live during global destruction etc.
6275 This function should only be called when REFCNT is zero.  Most of the time
6276 you'll want to call C<sv_free()> (or its macro wrapper C<SvREFCNT_dec>)
6277 instead.
6278
6279 =cut
6280 */
6281
6282 void
6283 Perl_sv_clear(pTHX_ SV *const orig_sv)
6284 {
6285     dVAR;
6286     HV *stash;
6287     U32 type;
6288     const struct body_details *sv_type_details;
6289     SV* iter_sv = NULL;
6290     SV* next_sv = NULL;
6291     SV *sv = orig_sv;
6292     STRLEN hash_index;
6293
6294     PERL_ARGS_ASSERT_SV_CLEAR;
6295
6296     /* within this loop, sv is the SV currently being freed, and
6297      * iter_sv is the most recent AV or whatever that's being iterated
6298      * over to provide more SVs */
6299
6300     while (sv) {
6301
6302         type = SvTYPE(sv);
6303
6304         assert(SvREFCNT(sv) == 0);
6305         assert(SvTYPE(sv) != (svtype)SVTYPEMASK);
6306
6307         if (type <= SVt_IV) {
6308             /* See the comment in sv.h about the collusion between this
6309              * early return and the overloading of the NULL slots in the
6310              * size table.  */
6311             if (SvROK(sv))
6312                 goto free_rv;
6313             SvFLAGS(sv) &= SVf_BREAK;
6314             SvFLAGS(sv) |= SVTYPEMASK;
6315             goto free_head;
6316         }
6317
6318         assert(!SvOBJECT(sv) || type >= SVt_PVMG); /* objs are always >= MG */
6319
6320         if (type >= SVt_PVMG) {
6321             if (SvOBJECT(sv)) {
6322                 if (!curse(sv, 1)) goto get_next_sv;
6323                 type = SvTYPE(sv); /* destructor may have changed it */
6324             }
6325             /* Free back-references before magic, in case the magic calls
6326              * Perl code that has weak references to sv. */
6327             if (type == SVt_PVHV) {
6328                 Perl_hv_kill_backrefs(aTHX_ MUTABLE_HV(sv));
6329                 if (SvMAGIC(sv))
6330                     mg_free(sv);
6331             }
6332             else if (type == SVt_PVMG && SvPAD_OUR(sv)) {
6333                 SvREFCNT_dec(SvOURSTASH(sv));
6334             }
6335             else if (type == SVt_PVAV && AvPAD_NAMELIST(sv)) {
6336                 assert(!SvMAGICAL(sv));
6337             } else if (SvMAGIC(sv)) {
6338                 /* Free back-references before other types of magic. */
6339                 sv_unmagic(sv, PERL_MAGIC_backref);
6340                 mg_free(sv);
6341             }
6342             SvMAGICAL_off(sv);
6343             if (type == SVt_PVMG && SvPAD_TYPED(sv))
6344                 SvREFCNT_dec(SvSTASH(sv));
6345         }
6346         switch (type) {
6347             /* case SVt_INVLIST: */
6348         case SVt_PVIO:
6349             if (IoIFP(sv) &&
6350                 IoIFP(sv) != PerlIO_stdin() &&
6351                 IoIFP(sv) != PerlIO_stdout() &&
6352                 IoIFP(sv) != PerlIO_stderr() &&
6353                 !(IoFLAGS(sv) & IOf_FAKE_DIRP))
6354             {
6355                 io_close(MUTABLE_IO(sv), FALSE);
6356             }
6357             if (IoDIRP(sv) && !(IoFLAGS(sv) & IOf_FAKE_DIRP))
6358                 PerlDir_close(IoDIRP(sv));
6359             IoDIRP(sv) = (DIR*)NULL;
6360             Safefree(IoTOP_NAME(sv));
6361             Safefree(IoFMT_NAME(sv));
6362             Safefree(IoBOTTOM_NAME(sv));
6363             if ((const GV *)sv == PL_statgv)
6364                 PL_statgv = NULL;
6365             goto freescalar;
6366         case SVt_REGEXP:
6367             /* FIXME for plugins */
6368           freeregexp:
6369             pregfree2((REGEXP*) sv);
6370             goto freescalar;
6371         case SVt_PVCV:
6372         case SVt_PVFM:
6373             cv_undef(MUTABLE_CV(sv));
6374             /* If we're in a stash, we don't own a reference to it.
6375              * However it does have a back reference to us, which needs to
6376              * be cleared.  */
6377             if ((stash = CvSTASH(sv)))
6378                 sv_del_backref(MUTABLE_SV(stash), sv);
6379             goto freescalar;
6380         case SVt_PVHV:
6381             if (PL_last_swash_hv == (const HV *)sv) {
6382                 PL_last_swash_hv = NULL;
6383             }
6384             if (HvTOTALKEYS((HV*)sv) > 0) {
6385                 const char *name;
6386                 /* this statement should match the one at the beginning of
6387                  * hv_undef_flags() */
6388                 if (   PL_phase != PERL_PHASE_DESTRUCT
6389                     && (name = HvNAME((HV*)sv)))
6390                 {
6391                     if (PL_stashcache) {
6392                     DEBUG_o(Perl_deb(aTHX_ "sv_clear clearing PL_stashcache for '%"SVf"'\n",
6393                                      sv));
6394                         (void)hv_deletehek(PL_stashcache,
6395                                            HvNAME_HEK((HV*)sv), G_DISCARD);
6396                     }
6397                     hv_name_set((HV*)sv, NULL, 0, 0);
6398                 }
6399
6400                 /* save old iter_sv in unused SvSTASH field */
6401                 assert(!SvOBJECT(sv));
6402                 SvSTASH(sv) = (HV*)iter_sv;
6403                 iter_sv = sv;
6404
6405                 /* save old hash_index in unused SvMAGIC field */
6406                 assert(!SvMAGICAL(sv));
6407                 assert(!SvMAGIC(sv));
6408                 ((XPVMG*) SvANY(sv))->xmg_u.xmg_hash_index = hash_index;
6409                 hash_index = 0;
6410
6411                 next_sv = Perl_hfree_next_entry(aTHX_ (HV*)sv, &hash_index);
6412                 goto get_next_sv; /* process this new sv */
6413             }
6414             /* free empty hash */
6415             Perl_hv_undef_flags(aTHX_ MUTABLE_HV(sv), HV_NAME_SETALL);
6416             assert(!HvARRAY((HV*)sv));
6417             break;
6418         case SVt_PVAV:
6419             {
6420                 AV* av = MUTABLE_AV(sv);
6421                 if (PL_comppad == av) {
6422                     PL_comppad = NULL;
6423                     PL_curpad = NULL;
6424                 }
6425                 if (AvREAL(av) && AvFILLp(av) > -1) {
6426                     next_sv = AvARRAY(av)[AvFILLp(av)--];
6427                     /* save old iter_sv in top-most slot of AV,
6428                      * and pray that it doesn't get wiped in the meantime */
6429                     AvARRAY(av)[AvMAX(av)] = iter_sv;
6430                     iter_sv = sv;
6431                     goto get_next_sv; /* process this new sv */
6432                 }
6433                 Safefree(AvALLOC(av));
6434             }
6435
6436             break;
6437         case SVt_PVLV:
6438             if (LvTYPE(sv) == 'T') { /* for tie: return HE to pool */
6439                 SvREFCNT_dec(HeKEY_sv((HE*)LvTARG(sv)));
6440                 HeNEXT((HE*)LvTARG(sv)) = PL_hv_fetch_ent_mh;
6441                 PL_hv_fetch_ent_mh = (HE*)LvTARG(sv);
6442             }
6443             else if (LvTYPE(sv) != 't') /* unless tie: unrefcnted fake SV**  */
6444                 SvREFCNT_dec(LvTARG(sv));
6445             if (isREGEXP(sv)) goto freeregexp;
6446         case SVt_PVGV:
6447             if (isGV_with_GP(sv)) {
6448                 if(GvCVu((const GV *)sv) && (stash = GvSTASH(MUTABLE_GV(sv)))
6449                    && HvENAME_get(stash))
6450                     mro_method_changed_in(stash);
6451                 gp_free(MUTABLE_GV(sv));
6452                 if (GvNAME_HEK(sv))
6453                     unshare_hek(GvNAME_HEK(sv));
6454                 /* If we're in a stash, we don't own a reference to it.
6455                  * However it does have a back reference to us, which
6456                  * needs to be cleared.  */
6457                 if (!SvVALID(sv) && (stash = GvSTASH(sv)))
6458                         sv_del_backref(MUTABLE_SV(stash), sv);
6459             }
6460             /* FIXME. There are probably more unreferenced pointers to SVs
6461              * in the interpreter struct that we should check and tidy in
6462              * a similar fashion to this:  */
6463             /* See also S_sv_unglob, which does the same thing. */
6464             if ((const GV *)sv == PL_last_in_gv)
6465                 PL_last_in_gv = NULL;
6466             else if ((const GV *)sv == PL_statgv)
6467                 PL_statgv = NULL;
6468             else if ((const GV *)sv == PL_stderrgv)
6469                 PL_stderrgv = NULL;
6470         case SVt_PVMG:
6471         case SVt_PVNV:
6472         case SVt_PVIV:
6473         case SVt_INVLIST:
6474         case SVt_PV:
6475           freescalar:
6476             /* Don't bother with SvOOK_off(sv); as we're only going to
6477              * free it.  */
6478             if (SvOOK(sv)) {
6479                 STRLEN offset;
6480                 SvOOK_offset(sv, offset);
6481                 SvPV_set(sv, SvPVX_mutable(sv) - offset);
6482                 /* Don't even bother with turning off the OOK flag.  */
6483             }
6484             if (SvROK(sv)) {
6485             free_rv:
6486                 {
6487                     SV * const target = SvRV(sv);
6488                     if (SvWEAKREF(sv))
6489                         sv_del_backref(target, sv);
6490                     else
6491                         next_sv = target;
6492                 }
6493             }
6494 #ifdef PERL_ANY_COW
6495             else if (SvPVX_const(sv)
6496                      && !(SvTYPE(sv) == SVt_PVIO
6497                      && !(IoFLAGS(sv) & IOf_FAKE_DIRP)))
6498             {
6499                 if (SvIsCOW(sv)) {
6500                     if (DEBUG_C_TEST) {
6501                         PerlIO_printf(Perl_debug_log, "Copy on write: clear\n");
6502                         sv_dump(sv);
6503                     }
6504                     if (SvLEN(sv)) {
6505 # ifdef PERL_OLD_COPY_ON_WRITE
6506                         sv_release_COW(sv, SvPVX_const(sv), SV_COW_NEXT_SV(sv));
6507 # else
6508                         if (CowREFCNT(sv)) {
6509                             sv_buf_to_rw(sv);
6510                             CowREFCNT(sv)--;
6511                             sv_buf_to_ro(sv);
6512                             SvLEN_set(sv, 0);
6513                         }
6514 # endif
6515                     } else {
6516                         unshare_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sv)));
6517                     }
6518
6519                 }
6520 # ifdef PERL_OLD_COPY_ON_WRITE
6521                 else
6522 # endif
6523                 if (SvLEN(sv)) {
6524                     Safefree(SvPVX_mutable(sv));
6525                 }
6526             }
6527 #else
6528             else if (SvPVX_const(sv) && SvLEN(sv)
6529                      && !(SvTYPE(sv) == SVt_PVIO
6530                      && !(IoFLAGS(sv) & IOf_FAKE_DIRP)))
6531                 Safefree(SvPVX_mutable(sv));
6532             else if (SvPVX_const(sv) && SvIsCOW(sv)) {
6533                 unshare_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sv)));
6534             }
6535 #endif
6536             break;
6537         case SVt_NV:
6538             break;
6539         }
6540
6541       free_body:
6542
6543         SvFLAGS(sv) &= SVf_BREAK;
6544         SvFLAGS(sv) |= SVTYPEMASK;
6545
6546         sv_type_details = bodies_by_type + type;
6547         if (sv_type_details->arena) {
6548             del_body(((char *)SvANY(sv) + sv_type_details->offset),
6549                      &PL_body_roots[type]);
6550         }
6551         else if (sv_type_details->body_size) {
6552             safefree(SvANY(sv));
6553         }
6554
6555       free_head:
6556         /* caller is responsible for freeing the head of the original sv */
6557         if (sv != orig_sv && !SvREFCNT(sv))
6558             del_SV(sv);
6559
6560         /* grab and free next sv, if any */
6561       get_next_sv:
6562         while (1) {
6563             sv = NULL;
6564             if (next_sv) {
6565                 sv = next_sv;
6566                 next_sv = NULL;
6567             }
6568             else if (!iter_sv) {
6569                 break;
6570             } else if (SvTYPE(iter_sv) == SVt_PVAV) {
6571                 AV *const av = (AV*)iter_sv;
6572                 if (AvFILLp(av) > -1) {
6573                     sv = AvARRAY(av)[AvFILLp(av)--];
6574                 }
6575                 else { /* no more elements of current AV to free */
6576                     sv = iter_sv;
6577                     type = SvTYPE(sv);
6578                     /* restore previous value, squirrelled away */
6579                     iter_sv = AvARRAY(av)[AvMAX(av)];
6580                     Safefree(AvALLOC(av));
6581                     goto free_body;
6582                 }
6583             } else if (SvTYPE(iter_sv) == SVt_PVHV) {
6584                 sv = Perl_hfree_next_entry(aTHX_ (HV*)iter_sv, &hash_index);
6585                 if (!sv && !HvTOTALKEYS((HV *)iter_sv)) {
6586                     /* no more elements of current HV to free */
6587                     sv = iter_sv;
6588                     type = SvTYPE(sv);
6589                     /* Restore previous values of iter_sv and hash_index,
6590                      * squirrelled away */
6591                     assert(!SvOBJECT(sv));
6592                     iter_sv = (SV*)SvSTASH(sv);
6593                     assert(!SvMAGICAL(sv));
6594                     hash_index = ((XPVMG*) SvANY(sv))->xmg_u.xmg_hash_index;
6595 #ifdef DEBUGGING
6596                     /* perl -DA does not like rubbish in SvMAGIC. */
6597                     SvMAGIC_set(sv, 0);
6598 #endif
6599
6600                     /* free any remaining detritus from the hash struct */
6601                     Perl_hv_undef_flags(aTHX_ MUTABLE_HV(sv), HV_NAME_SETALL);
6602                     assert(!HvARRAY((HV*)sv));
6603                     goto free_body;
6604                 }
6605             }
6606
6607             /* unrolled SvREFCNT_dec and sv_free2 follows: */
6608
6609             if (!sv)
6610                 continue;
6611             if (!SvREFCNT(sv)) {
6612                 sv_free(sv);
6613                 continue;
6614             }
6615             if (--(SvREFCNT(sv)))
6616                 continue;
6617 #ifdef DEBUGGING
6618             if (SvTEMP(sv)) {
6619                 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEBUGGING),
6620                          "Attempt to free temp prematurely: SV 0x%"UVxf
6621                          pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
6622                 continue;
6623             }
6624 #endif
6625             if (SvIMMORTAL(sv)) {
6626                 /* make sure SvREFCNT(sv)==0 happens very seldom */
6627                 SvREFCNT(sv) = SvREFCNT_IMMORTAL;
6628                 continue;
6629             }
6630             break;
6631         } /* while 1 */
6632
6633     } /* while sv */
6634 }
6635
6636 /* This routine curses the sv itself, not the object referenced by sv. So
6637    sv does not have to be ROK. */
6638
6639 static bool
6640 S_curse(pTHX_ SV * const sv, const bool check_refcnt) {
6641     dVAR;
6642
6643     PERL_ARGS_ASSERT_CURSE;
6644     assert(SvOBJECT(sv));
6645
6646     if (PL_defstash &&  /* Still have a symbol table? */
6647         SvDESTROYABLE(sv))
6648     {
6649         dSP;
6650         HV* stash;
6651         do {
6652           stash = SvSTASH(sv);
6653           assert(SvTYPE(stash) == SVt_PVHV);
6654           if (HvNAME(stash)) {
6655             CV* destructor = NULL;
6656             assert (SvOOK(stash));
6657             if (!SvOBJECT(stash)) destructor = (CV *)SvSTASH(stash);
6658             if (!destructor || HvMROMETA(stash)->destroy_gen
6659                                 != PL_sub_generation)
6660             {
6661                 GV * const gv =
6662                     gv_fetchmeth_autoload(stash, "DESTROY", 7, 0);
6663                 if (gv) destructor = GvCV(gv);
6664                 if (!SvOBJECT(stash))
6665                 {
6666                     SvSTASH(stash) =
6667                         destructor ? (HV *)destructor : ((HV *)0)+1;
6668                     HvAUX(stash)->xhv_mro_meta->destroy_gen =
6669                         PL_sub_generation;
6670                 }
6671             }
6672             assert(!destructor || destructor == ((CV *)0)+1
6673                 || SvTYPE(destructor) == SVt_PVCV);
6674             if (destructor && destructor != ((CV *)0)+1
6675                 /* A constant subroutine can have no side effects, so
6676                    don't bother calling it.  */
6677                 && !CvCONST(destructor)
6678                 /* Don't bother calling an empty destructor or one that
6679                    returns immediately. */
6680                 && (CvISXSUB(destructor)
6681                 || (CvSTART(destructor)
6682                     && (CvSTART(destructor)->op_next->op_type
6683                                         != OP_LEAVESUB)
6684                     && (CvSTART(destructor)->op_next->op_type
6685                                         != OP_PUSHMARK
6686                         || CvSTART(destructor)->op_next->op_next->op_type
6687                                         != OP_RETURN
6688                        )
6689                    ))
6690                )
6691             {
6692                 SV* const tmpref = newRV(sv);
6693                 SvREADONLY_on(tmpref); /* DESTROY() could be naughty */
6694                 ENTER;
6695                 PUSHSTACKi(PERLSI_DESTROY);
6696                 EXTEND(SP, 2);
6697                 PUSHMARK(SP);
6698                 PUSHs(tmpref);
6699                 PUTBACK;
6700                 call_sv(MUTABLE_SV(destructor),
6701                             G_DISCARD|G_EVAL|G_KEEPERR|G_VOID);
6702                 POPSTACK;
6703                 SPAGAIN;
6704                 LEAVE;
6705                 if(SvREFCNT(tmpref) < 2) {
6706                     /* tmpref is not kept alive! */
6707                     SvREFCNT(sv)--;
6708                     SvRV_set(tmpref, NULL);
6709                     SvROK_off(tmpref);
6710                 }
6711                 SvREFCNT_dec_NN(tmpref);
6712             }
6713           }
6714         } while (SvOBJECT(sv) && SvSTASH(sv) != stash);
6715
6716
6717         if (check_refcnt && SvREFCNT(sv)) {
6718             if (PL_in_clean_objs)
6719                 Perl_croak(aTHX_
6720                   "DESTROY created new reference to dead object '%"HEKf"'",
6721                    HEKfARG(HvNAME_HEK(stash)));
6722             /* DESTROY gave object new lease on life */
6723             return FALSE;
6724         }
6725     }
6726
6727     if (SvOBJECT(sv)) {
6728         HV * const stash = SvSTASH(sv);
6729         /* Curse before freeing the stash, as freeing the stash could cause
6730            a recursive call into S_curse. */
6731         SvOBJECT_off(sv);       /* Curse the object. */
6732         SvSTASH_set(sv,0);      /* SvREFCNT_dec may try to read this */
6733         SvREFCNT_dec(stash); /* possibly of changed persuasion */
6734     }
6735     return TRUE;
6736 }
6737
6738 /*
6739 =for apidoc sv_newref
6740
6741 Increment an SV's reference count.  Use the C<SvREFCNT_inc()> wrapper
6742 instead.
6743
6744 =cut
6745 */
6746
6747 SV *
6748 Perl_sv_newref(pTHX_ SV *const sv)
6749 {
6750     PERL_UNUSED_CONTEXT;
6751     if (sv)
6752         (SvREFCNT(sv))++;
6753     return sv;
6754 }
6755
6756 /*
6757 =for apidoc sv_free
6758
6759 Decrement an SV's reference count, and if it drops to zero, call
6760 C<sv_clear> to invoke destructors and free up any memory used by
6761 the body; finally, deallocate the SV's head itself.
6762 Normally called via a wrapper macro C<SvREFCNT_dec>.
6763
6764 =cut
6765 */
6766
6767 void
6768 Perl_sv_free(pTHX_ SV *const sv)
6769 {
6770     SvREFCNT_dec(sv);
6771 }
6772
6773
6774 /* Private helper function for SvREFCNT_dec().
6775  * Called with rc set to original SvREFCNT(sv), where rc == 0 or 1 */
6776
6777 void
6778 Perl_sv_free2(pTHX_ SV *const sv, const U32 rc)
6779 {
6780     dVAR;
6781
6782     PERL_ARGS_ASSERT_SV_FREE2;
6783
6784     if (LIKELY( rc == 1 )) {
6785         /* normal case */
6786         SvREFCNT(sv) = 0;
6787
6788 #ifdef DEBUGGING
6789         if (SvTEMP(sv)) {
6790             Perl_ck_warner_d(aTHX_ packWARN(WARN_DEBUGGING),
6791                              "Attempt to free temp prematurely: SV 0x%"UVxf
6792                              pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
6793             return;
6794         }
6795 #endif
6796         if (SvIMMORTAL(sv)) {
6797             /* make sure SvREFCNT(sv)==0 happens very seldom */
6798             SvREFCNT(sv) = SvREFCNT_IMMORTAL;
6799             return;
6800         }
6801         sv_clear(sv);
6802         if (! SvREFCNT(sv)) /* may have have been resurrected */
6803             del_SV(sv);
6804         return;
6805     }
6806
6807     /* handle exceptional cases */
6808
6809     assert(rc == 0);
6810
6811     if (SvFLAGS(sv) & SVf_BREAK)
6812         /* this SV's refcnt has been artificially decremented to
6813          * trigger cleanup */
6814         return;
6815     if (PL_in_clean_all) /* All is fair */
6816         return;
6817     if (SvIMMORTAL(sv)) {
6818         /* make sure SvREFCNT(sv)==0 happens very seldom */
6819         SvREFCNT(sv) = SvREFCNT_IMMORTAL;
6820         return;
6821     }
6822     if (ckWARN_d(WARN_INTERNAL)) {
6823 #ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
6824         Perl_dump_sv_child(aTHX_ sv);
6825 #else
6826     #ifdef DEBUG_LEAKING_SCALARS
6827         sv_dump(sv);
6828     #endif
6829 #ifdef DEBUG_LEAKING_SCALARS_ABORT
6830         if (PL_warnhook == PERL_WARNHOOK_FATAL
6831             || ckDEAD(packWARN(WARN_INTERNAL))) {
6832             /* Don't let Perl_warner cause us to escape our fate:  */
6833             abort();
6834         }
6835 #endif
6836         /* This may not return:  */
6837         Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
6838                     "Attempt to free unreferenced scalar: SV 0x%"UVxf
6839                     pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
6840 #endif
6841     }
6842 #ifdef DEBUG_LEAKING_SCALARS_ABORT
6843     abort();
6844 #endif
6845
6846 }
6847
6848
6849 /*
6850 =for apidoc sv_len
6851
6852 Returns the length of the string in the SV.  Handles magic and type
6853 coercion and sets the UTF8 flag appropriately.  See also C<SvCUR>, which
6854 gives raw access to the xpv_cur slot.
6855
6856 =cut
6857 */
6858
6859 STRLEN
6860 Perl_sv_len(pTHX_ SV *const sv)
6861 {
6862     STRLEN len;
6863
6864     if (!sv)
6865         return 0;
6866
6867     (void)SvPV_const(sv, len);
6868     return len;
6869 }
6870
6871 /*
6872 =for apidoc sv_len_utf8
6873
6874 Returns the number of characters in the string in an SV, counting wide
6875 UTF-8 bytes as a single character.  Handles magic and type coercion.
6876
6877 =cut
6878 */
6879
6880 /*
6881  * The length is cached in PERL_MAGIC_utf8, in the mg_len field.  Also the
6882  * mg_ptr is used, by sv_pos_u2b() and sv_pos_b2u() - see the comments below.
6883  * (Note that the mg_len is not the length of the mg_ptr field.
6884  * This allows the cache to store the character length of the string without
6885  * needing to malloc() extra storage to attach to the mg_ptr.)
6886  *
6887  */
6888
6889 STRLEN
6890 Perl_sv_len_utf8(pTHX_ SV *const sv)
6891 {
6892     if (!sv)
6893         return 0;
6894
6895     SvGETMAGIC(sv);
6896     return sv_len_utf8_nomg(sv);
6897 }
6898
6899 STRLEN
6900 Perl_sv_len_utf8_nomg(pTHX_ SV * const sv)
6901 {
6902     dVAR;
6903     STRLEN len;
6904     const U8 *s = (U8*)SvPV_nomg_const(sv, len);
6905
6906     PERL_ARGS_ASSERT_SV_LEN_UTF8_NOMG;
6907
6908     if (PL_utf8cache && SvUTF8(sv)) {
6909             STRLEN ulen;
6910             MAGIC *mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
6911
6912             if (mg && (mg->mg_len != -1 || mg->mg_ptr)) {
6913                 if (mg->mg_len != -1)
6914                     ulen = mg->mg_len;
6915                 else {
6916                     /* We can use the offset cache for a headstart.
6917                        The longer value is stored in the first pair.  */
6918                     STRLEN *cache = (STRLEN *) mg->mg_ptr;
6919
6920                     ulen = cache[0] + Perl_utf8_length(aTHX_ s + cache[1],
6921                                                        s + len);
6922                 }
6923                 
6924                 if (PL_utf8cache < 0) {
6925                     const STRLEN real = Perl_utf8_length(aTHX_ s, s + len);
6926                     assert_uft8_cache_coherent("sv_len_utf8", ulen, real, sv);
6927                 }
6928             }
6929             else {
6930                 ulen = Perl_utf8_length(aTHX_ s, s + len);
6931                 utf8_mg_len_cache_update(sv, &mg, ulen);
6932             }
6933             return ulen;
6934     }
6935     return SvUTF8(sv) ? Perl_utf8_length(aTHX_ s, s + len) : len;
6936 }
6937
6938 /* Walk forwards to find the byte corresponding to the passed in UTF-8
6939    offset.  */
6940 static STRLEN
6941 S_sv_pos_u2b_forwards(const U8 *const start, const U8 *const send,
6942                       STRLEN *const uoffset_p, bool *const at_end)
6943 {
6944     const U8 *s = start;
6945     STRLEN uoffset = *uoffset_p;
6946
6947     PERL_ARGS_ASSERT_SV_POS_U2B_FORWARDS;
6948
6949     while (s < send && uoffset) {
6950         --uoffset;
6951         s += UTF8SKIP(s);
6952     }
6953     if (s == send) {
6954         *at_end = TRUE;
6955     }
6956     else if (s > send) {
6957         *at_end = TRUE;
6958         /* This is the existing behaviour. Possibly it should be a croak, as
6959            it's actually a bounds error  */
6960         s = send;
6961     }
6962     *uoffset_p -= uoffset;
6963     return s - start;
6964 }
6965
6966 /* Given the length of the string in both bytes and UTF-8 characters, decide
6967    whether to walk forwards or backwards to find the byte corresponding to
6968    the passed in UTF-8 offset.  */
6969 static STRLEN
6970 S_sv_pos_u2b_midway(const U8 *const start, const U8 *send,
6971                     STRLEN uoffset, const STRLEN uend)
6972 {
6973     STRLEN backw = uend - uoffset;
6974
6975     PERL_ARGS_ASSERT_SV_POS_U2B_MIDWAY;
6976
6977     if (uoffset < 2 * backw) {
6978         /* The assumption is that going forwards is twice the speed of going
6979            forward (that's where the 2 * backw comes from).
6980            (The real figure of course depends on the UTF-8 data.)  */
6981         const U8 *s = start;
6982
6983         while (s < send && uoffset--)
6984             s += UTF8SKIP(s);
6985         assert (s <= send);
6986         if (s > send)
6987             s = send;
6988         return s - start;
6989     }
6990
6991     while (backw--) {
6992         send--;
6993         while (UTF8_IS_CONTINUATION(*send))
6994             send--;
6995     }
6996     return send - start;
6997 }
6998
6999 /* For the string representation of the given scalar, find the byte
7000    corresponding to the passed in UTF-8 offset.  uoffset0 and boffset0
7001    give another position in the string, *before* the sought offset, which
7002    (which is always true, as 0, 0 is a valid pair of positions), which should
7003    help reduce the amount of linear searching.
7004    If *mgp is non-NULL, it should point to the UTF-8 cache magic, which
7005    will be used to reduce the amount of linear searching. The cache will be
7006    created if necessary, and the found value offered to it for update.  */
7007 static STRLEN
7008 S_sv_pos_u2b_cached(pTHX_ SV *const sv, MAGIC **const mgp, const U8 *const start,
7009                     const U8 *const send, STRLEN uoffset,
7010                     STRLEN uoffset0, STRLEN boffset0)
7011 {
7012     STRLEN boffset = 0; /* Actually always set, but let's keep gcc happy.  */
7013     bool found = FALSE;
7014     bool at_end = FALSE;
7015
7016     PERL_ARGS_ASSERT_SV_POS_U2B_CACHED;
7017
7018     assert (uoffset >= uoffset0);
7019
7020     if (!uoffset)
7021         return 0;
7022
7023     if (!SvREADONLY(sv) && !SvGMAGICAL(sv) && SvPOK(sv)
7024         && PL_utf8cache
7025         && (*mgp || (SvTYPE(sv) >= SVt_PVMG &&
7026                      (*mgp = mg_find(sv, PERL_MAGIC_utf8))))) {
7027         if ((*mgp)->mg_ptr) {
7028             STRLEN *cache = (STRLEN *) (*mgp)->mg_ptr;
7029             if (cache[0] == uoffset) {
7030                 /* An exact match. */
7031                 return cache[1];
7032             }
7033             if (cache[2] == uoffset) {
7034                 /* An exact match. */
7035                 return cache[3];
7036             }
7037
7038             if (cache[0] < uoffset) {
7039                 /* The cache already knows part of the way.   */
7040                 if (cache[0] > uoffset0) {
7041                     /* The cache knows more than the passed in pair  */
7042                     uoffset0 = cache[0];
7043                     boffset0 = cache[1];
7044                 }
7045                 if ((*mgp)->mg_len != -1) {
7046                     /* And we know the end too.  */
7047                     boffset = boffset0
7048                         + sv_pos_u2b_midway(start + boffset0, send,
7049                                               uoffset - uoffset0,
7050                                               (*mgp)->mg_len - uoffset0);
7051                 } else {
7052                     uoffset -= uoffset0;
7053                     boffset = boffset0
7054                         + sv_pos_u2b_forwards(start + boffset0,
7055                                               send, &uoffset, &at_end);
7056                     uoffset += uoffset0;
7057                 }
7058             }
7059             else if (cache[2] < uoffset) {
7060                 /* We're between the two cache entries.  */
7061                 if (cache[2] > uoffset0) {
7062                     /* and the cache knows more than the passed in pair  */
7063                     uoffset0 = cache[2];
7064                     boffset0 = cache[3];
7065                 }
7066
7067                 boffset = boffset0
7068                     + sv_pos_u2b_midway(start + boffset0,
7069                                           start + cache[1],
7070                                           uoffset - uoffset0,
7071                                           cache[0] - uoffset0);
7072             } else {
7073                 boffset = boffset0
7074                     + sv_pos_u2b_midway(start + boffset0,
7075                                           start + cache[3],
7076                                           uoffset - uoffset0,
7077                                           cache[2] - uoffset0);
7078             }
7079             found = TRUE;
7080         }
7081         else if ((*mgp)->mg_len != -1) {
7082             /* If we can take advantage of a passed in offset, do so.  */
7083             /* In fact, offset0 is either 0, or less than offset, so don't
7084                need to worry about the other possibility.  */
7085             boffset = boffset0
7086                 + sv_pos_u2b_midway(start + boffset0, send,
7087                                       uoffset - uoffset0,
7088                                       (*mgp)->mg_len - uoffset0);
7089             found = TRUE;
7090         }
7091     }
7092
7093     if (!found || PL_utf8cache < 0) {
7094         STRLEN real_boffset;
7095         uoffset -= uoffset0;
7096         real_boffset = boffset0 + sv_pos_u2b_forwards(start + boffset0,
7097                                                       send, &uoffset, &at_end);
7098         uoffset += uoffset0;
7099
7100         if (found && PL_utf8cache < 0)
7101             assert_uft8_cache_coherent("sv_pos_u2b_cache", boffset,
7102                                        real_boffset, sv);
7103         boffset = real_boffset;
7104     }
7105
7106     if (PL_utf8cache && !SvGMAGICAL(sv) && SvPOK(sv)) {
7107         if (at_end)
7108             utf8_mg_len_cache_update(sv, mgp, uoffset);
7109         else
7110             utf8_mg_pos_cache_update(sv, mgp, boffset, uoffset, send - start);
7111     }
7112     return boffset;
7113 }
7114
7115
7116 /*
7117 =for apidoc sv_pos_u2b_flags
7118
7119 Converts the offset from a count of UTF-8 chars from
7120 the start of the string, to a count of the equivalent number of bytes; if
7121 lenp is non-zero, it does the same to lenp, but this time starting from
7122 the offset, rather than from the start
7123 of the string.  Handles type coercion.
7124 I<flags> is passed to C<SvPV_flags>, and usually should be
7125 C<SV_GMAGIC|SV_CONST_RETURN> to handle magic.
7126
7127 =cut
7128 */
7129
7130 /*
7131  * sv_pos_u2b_flags() uses, like sv_pos_b2u(), the mg_ptr of the potential
7132  * PERL_MAGIC_utf8 of the sv to store the mapping between UTF-8 and
7133  * byte offsets.  See also the comments of S_utf8_mg_pos_cache_update().
7134  *
7135  */
7136
7137 STRLEN
7138 Perl_sv_pos_u2b_flags(pTHX_ SV *const sv, STRLEN uoffset, STRLEN *const lenp,
7139                       U32 flags)
7140 {
7141     const U8 *start;
7142     STRLEN len;
7143     STRLEN boffset;
7144
7145     PERL_ARGS_ASSERT_SV_POS_U2B_FLAGS;
7146
7147     start = (U8*)SvPV_flags(sv, len, flags);
7148     if (len) {
7149         const U8 * const send = start + len;
7150         MAGIC *mg = NULL;
7151         boffset = sv_pos_u2b_cached(sv, &mg, start, send, uoffset, 0, 0);
7152
7153         if (lenp
7154             && *lenp /* don't bother doing work for 0, as its bytes equivalent
7155                         is 0, and *lenp is already set to that.  */) {
7156             /* Convert the relative offset to absolute.  */
7157             const STRLEN uoffset2 = uoffset + *lenp;
7158             const STRLEN boffset2
7159                 = sv_pos_u2b_cached(sv, &mg, start, send, uoffset2,
7160                                       uoffset, boffset) - boffset;
7161
7162             *lenp = boffset2;
7163         }
7164     } else {
7165         if (lenp)
7166             *lenp = 0;
7167         boffset = 0;
7168     }
7169
7170     return boffset;
7171 }
7172
7173 /*
7174 =for apidoc sv_pos_u2b
7175
7176 Converts the value pointed to by offsetp from a count of UTF-8 chars from
7177 the start of the string, to a count of the equivalent number of bytes; if
7178 lenp is non-zero, it does the same to lenp, but this time starting from
7179 the offset, rather than from the start of the string.  Handles magic and
7180 type coercion.
7181
7182 Use C<sv_pos_u2b_flags> in preference, which correctly handles strings longer
7183 than 2Gb.
7184
7185 =cut
7186 */
7187
7188 /*
7189  * sv_pos_u2b() uses, like sv_pos_b2u(), the mg_ptr of the potential
7190  * PERL_MAGIC_utf8 of the sv to store the mapping between UTF-8 and
7191  * byte offsets.  See also the comments of S_utf8_mg_pos_cache_update().
7192  *
7193  */
7194
7195 /* This function is subject to size and sign problems */
7196
7197 void
7198 Perl_sv_pos_u2b(pTHX_ SV *const sv, I32 *const offsetp, I32 *const lenp)
7199 {
7200     PERL_ARGS_ASSERT_SV_POS_U2B;
7201
7202     if (lenp) {
7203         STRLEN ulen = (STRLEN)*lenp;
7204         *offsetp = (I32)sv_pos_u2b_flags(sv, (STRLEN)*offsetp, &ulen,
7205                                          SV_GMAGIC|SV_CONST_RETURN);
7206         *lenp = (I32)ulen;
7207     } else {
7208         *offsetp = (I32)sv_pos_u2b_flags(sv, (STRLEN)*offsetp, NULL,
7209                                          SV_GMAGIC|SV_CONST_RETURN);
7210     }
7211 }
7212
7213 static void
7214 S_utf8_mg_len_cache_update(pTHX_ SV *const sv, MAGIC **const mgp,
7215                            const STRLEN ulen)
7216 {
7217     PERL_ARGS_ASSERT_UTF8_MG_LEN_CACHE_UPDATE;
7218     if (SvREADONLY(sv) || SvGMAGICAL(sv) || !SvPOK(sv))
7219         return;
7220
7221     if (!*mgp && (SvTYPE(sv) < SVt_PVMG ||
7222                   !(*mgp = mg_find(sv, PERL_MAGIC_utf8)))) {
7223         *mgp = sv_magicext(sv, 0, PERL_MAGIC_utf8, &PL_vtbl_utf8, 0, 0);
7224     }
7225     assert(*mgp);
7226
7227     (*mgp)->mg_len = ulen;
7228 }
7229
7230 /* Create and update the UTF8 magic offset cache, with the proffered utf8/
7231    byte length pairing. The (byte) length of the total SV is passed in too,
7232    as blen, because for some (more esoteric) SVs, the call to SvPV_const()
7233    may not have updated SvCUR, so we can't rely on reading it directly.
7234
7235    The proffered utf8/byte length pairing isn't used if the cache already has
7236    two pairs, and swapping either for the proffered pair would increase the
7237    RMS of the intervals between known byte offsets.
7238
7239    The cache itself consists of 4 STRLEN values
7240    0: larger UTF-8 offset
7241    1: corresponding byte offset
7242    2: smaller UTF-8 offset
7243    3: corresponding byte offset
7244
7245    Unused cache pairs have the value 0, 0.
7246    Keeping the cache "backwards" means that the invariant of
7247    cache[0] >= cache[2] is maintained even with empty slots, which means that
7248    the code that uses it doesn't need to worry if only 1 entry has actually
7249    been set to non-zero.  It also makes the "position beyond the end of the
7250    cache" logic much simpler, as the first slot is always the one to start
7251    from.   
7252 */
7253 static void
7254 S_utf8_mg_pos_cache_update(pTHX_ SV *const sv, MAGIC **const mgp, const STRLEN byte,
7255                            const STRLEN utf8, const STRLEN blen)
7256 {
7257     STRLEN *cache;
7258
7259     PERL_ARGS_ASSERT_UTF8_MG_POS_CACHE_UPDATE;
7260
7261     if (SvREADONLY(sv))
7262         return;
7263
7264     if (!*mgp && (SvTYPE(sv) < SVt_PVMG ||
7265                   !(*mgp = mg_find(sv, PERL_MAGIC_utf8)))) {
7266         *mgp = sv_magicext(sv, 0, PERL_MAGIC_utf8, (MGVTBL*)&PL_vtbl_utf8, 0,
7267                            0);
7268         (*mgp)->mg_len = -1;
7269     }
7270     assert(*mgp);
7271
7272     if (!(cache = (STRLEN *)(*mgp)->mg_ptr)) {
7273         Newxz(cache, PERL_MAGIC_UTF8_CACHESIZE * 2, STRLEN);
7274         (*mgp)->mg_ptr = (char *) cache;
7275     }
7276     assert(cache);
7277
7278     if (PL_utf8cache < 0 && SvPOKp(sv)) {
7279         /* SvPOKp() because it's possible that sv has string overloading, and
7280            therefore is a reference, hence SvPVX() is actually a pointer.
7281            This cures the (very real) symptoms of RT 69422, but I'm not actually
7282            sure whether we should even be caching the results of UTF-8
7283            operations on overloading, given that nothing stops overloading
7284            returning a different value every time it's called.  */
7285         const U8 *start = (const U8 *) SvPVX_const(sv);
7286         const STRLEN realutf8 = utf8_length(start, start + byte);
7287
7288         assert_uft8_cache_coherent("utf8_mg_pos_cache_update", utf8, realutf8,
7289                                    sv);
7290     }
7291
7292     /* Cache is held with the later position first, to simplify the code
7293        that deals with unbounded ends.  */
7294        
7295     ASSERT_UTF8_CACHE(cache);
7296     if (cache[1] == 0) {
7297         /* Cache is totally empty  */
7298         cache[0] = utf8;
7299         cache[1] = byte;
7300     } else if (cache[3] == 0) {
7301         if (byte > cache[1]) {
7302             /* New one is larger, so goes first.  */
7303             cache[2] = cache[0];
7304             cache[3] = cache[1];
7305             cache[0] = utf8;
7306             cache[1] = byte;
7307         } else {
7308             cache[2] = utf8;
7309             cache[3] = byte;
7310         }
7311     } else {
7312 #define THREEWAY_SQUARE(a,b,c,d) \
7313             ((float)((d) - (c))) * ((float)((d) - (c))) \
7314             + ((float)((c) - (b))) * ((float)((c) - (b))) \
7315                + ((float)((b) - (a))) * ((float)((b) - (a)))
7316
7317         /* Cache has 2 slots in use, and we know three potential pairs.
7318            Keep the two that give the lowest RMS distance. Do the
7319            calculation in bytes simply because we always know the byte
7320            length.  squareroot has the same ordering as the positive value,
7321            so don't bother with the actual square root.  */
7322         if (byte > cache[1]) {
7323             /* New position is after the existing pair of pairs.  */
7324             const float keep_earlier
7325                 = THREEWAY_SQUARE(0, cache[3], byte, blen);
7326             const float keep_later
7327                 = THREEWAY_SQUARE(0, cache[1], byte, blen);
7328
7329             if (keep_later < keep_earlier) {
7330                 cache[2] = cache[0];
7331                 cache[3] = cache[1];
7332                 cache[0] = utf8;
7333                 cache[1] = byte;
7334             }
7335             else {
7336                 cache[0] = utf8;
7337                 cache[1] = byte;
7338             }
7339         }
7340         else if (byte > cache[3]) {
7341             /* New position is between the existing pair of pairs.  */
7342             const float keep_earlier
7343                 = THREEWAY_SQUARE(0, cache[3], byte, blen);
7344             const float keep_later
7345                 = THREEWAY_SQUARE(0, byte, cache[1], blen);
7346
7347             if (keep_later < keep_earlier) {
7348                 cache[2] = utf8;
7349                 cache[3] = byte;
7350             }
7351             else {
7352                 cache[0] = utf8;
7353                 cache[1] = byte;
7354             }
7355         }
7356         else {
7357             /* New position is before the existing pair of pairs.  */
7358             const float keep_earlier
7359                 = THREEWAY_SQUARE(0, byte, cache[3], blen);
7360             const float keep_later
7361                 = THREEWAY_SQUARE(0, byte, cache[1], blen);
7362
7363             if (keep_later < keep_earlier) {
7364                 cache[2] = utf8;
7365                 cache[3] = byte;
7366             }
7367             else {
7368                 cache[0] = cache[2];
7369                 cache[1] = cache[3];
7370                 cache[2] = utf8;
7371                 cache[3] = byte;
7372             }
7373         }
7374     }
7375     ASSERT_UTF8_CACHE(cache);
7376 }
7377
7378 /* We already know all of the way, now we may be able to walk back.  The same
7379    assumption is made as in S_sv_pos_u2b_midway(), namely that walking
7380    backward is half the speed of walking forward. */
7381 static STRLEN
7382 S_sv_pos_b2u_midway(pTHX_ const U8 *const s, const U8 *const target,
7383                     const U8 *end, STRLEN endu)
7384 {
7385     const STRLEN forw = target - s;
7386     STRLEN backw = end - target;
7387
7388     PERL_ARGS_ASSERT_SV_POS_B2U_MIDWAY;
7389
7390     if (forw < 2 * backw) {
7391         return utf8_length(s, target);
7392     }
7393
7394     while (end > target) {
7395         end--;
7396         while (UTF8_IS_CONTINUATION(*end)) {
7397             end--;
7398         }
7399         endu--;
7400     }
7401     return endu;
7402 }
7403
7404 /*
7405 =for apidoc sv_pos_b2u_flags
7406
7407 Converts the offset from a count of bytes from the start of the string, to
7408 a count of the equivalent number of UTF-8 chars.  Handles type coercion.
7409 I<flags> is passed to C<SvPV_flags>, and usually should be
7410 C<SV_GMAGIC|SV_CONST_RETURN> to handle magic.
7411
7412 =cut
7413 */
7414
7415 /*
7416  * sv_pos_b2u_flags() uses, like sv_pos_u2b_flags(), the mg_ptr of the
7417  * potential PERL_MAGIC_utf8 of the sv to store the mapping between UTF-8
7418  * and byte offsets.
7419  *
7420  */
7421 STRLEN
7422 Perl_sv_pos_b2u_flags(pTHX_ SV *const sv, STRLEN const offset, U32 flags)
7423 {
7424     const U8* s;
7425     STRLEN len = 0; /* Actually always set, but let's keep gcc happy.  */
7426     STRLEN blen;
7427     MAGIC* mg = NULL;
7428     const U8* send;
7429     bool found = FALSE;
7430
7431     PERL_ARGS_ASSERT_SV_POS_B2U_FLAGS;
7432
7433     s = (const U8*)SvPV_flags(sv, blen, flags);
7434
7435     if (blen < offset)
7436         Perl_croak(aTHX_ "panic: sv_pos_b2u: bad byte offset, blen=%"UVuf
7437                    ", byte=%"UVuf, (UV)blen, (UV)offset);
7438
7439     send = s + offset;
7440
7441     if (!SvREADONLY(sv)
7442         && PL_utf8cache
7443         && SvTYPE(sv) >= SVt_PVMG
7444         && (mg = mg_find(sv, PERL_MAGIC_utf8)))
7445     {
7446         if (mg->mg_ptr) {
7447             STRLEN * const cache = (STRLEN *) mg->mg_ptr;
7448             if (cache[1] == offset) {
7449                 /* An exact match. */
7450                 return cache[0];
7451             }
7452             if (cache[3] == offset) {
7453                 /* An exact match. */
7454                 return cache[2];
7455             }
7456
7457             if (cache[1] < offset) {
7458                 /* We already know part of the way. */
7459                 if (mg->mg_len != -1) {
7460                     /* Actually, we know the end too.  */
7461                     len = cache[0]
7462                         + S_sv_pos_b2u_midway(aTHX_ s + cache[1], send,
7463                                               s + blen, mg->mg_len - cache[0]);
7464                 } else {
7465                     len = cache[0] + utf8_length(s + cache[1], send);
7466                 }
7467             }
7468             else if (cache[3] < offset) {
7469                 /* We're between the two cached pairs, so we do the calculation
7470                    offset by the byte/utf-8 positions for the earlier pair,
7471                    then add the utf-8 characters from the string start to
7472                    there.  */
7473                 len = S_sv_pos_b2u_midway(aTHX_ s + cache[3], send,
7474                                           s + cache[1], cache[0] - cache[2])
7475                     + cache[2];
7476
7477             }
7478             else { /* cache[3] > offset */
7479                 len = S_sv_pos_b2u_midway(aTHX_ s, send, s + cache[3],
7480                                           cache[2]);
7481
7482             }
7483             ASSERT_UTF8_CACHE(cache);
7484             found = TRUE;
7485         } else if (mg->mg_len != -1) {
7486             len = S_sv_pos_b2u_midway(aTHX_ s, send, s + blen, mg->mg_len);
7487             found = TRUE;
7488         }
7489     }
7490     if (!found || PL_utf8cache < 0) {
7491         const STRLEN real_len = utf8_length(s, send);
7492
7493         if (found && PL_utf8cache < 0)
7494             assert_uft8_cache_coherent("sv_pos_b2u", len, real_len, sv);
7495         len = real_len;
7496     }
7497
7498     if (PL_utf8cache) {
7499         if (blen == offset)
7500             utf8_mg_len_cache_update(sv, &mg, len);
7501         else
7502             utf8_mg_pos_cache_update(sv, &mg, offset, len, blen);
7503     }
7504
7505     return len;
7506 }
7507
7508 /*
7509 =for apidoc sv_pos_b2u
7510
7511 Converts the value pointed to by offsetp from a count of bytes from the
7512 start of the string, to a count of the equivalent number of UTF-8 chars.
7513 Handles magic and type coercion.
7514
7515 Use C<sv_pos_b2u_flags> in preference, which correctly handles strings
7516 longer than 2Gb.
7517
7518 =cut
7519 */
7520
7521 /*
7522  * sv_pos_b2u() uses, like sv_pos_u2b(), the mg_ptr of the potential
7523  * PERL_MAGIC_utf8 of the sv to store the mapping between UTF-8 and
7524  * byte offsets.
7525  *
7526  */
7527 void
7528 Perl_sv_pos_b2u(pTHX_ SV *const sv, I32 *const offsetp)
7529 {
7530     PERL_ARGS_ASSERT_SV_POS_B2U;
7531
7532     if (!sv)
7533         return;
7534
7535     *offsetp = (I32)sv_pos_b2u_flags(sv, (STRLEN)*offsetp,
7536                                      SV_GMAGIC|SV_CONST_RETURN);
7537 }
7538
7539 static void
7540 S_assert_uft8_cache_coherent(pTHX_ const char *const func, STRLEN from_cache,
7541                              STRLEN real, SV *const sv)
7542 {
7543     PERL_ARGS_ASSERT_ASSERT_UFT8_CACHE_COHERENT;
7544
7545     /* As this is debugging only code, save space by keeping this test here,
7546        rather than inlining it in all the callers.  */
7547     if (from_cache == real)
7548         return;
7549
7550     /* Need to turn the assertions off otherwise we may recurse infinitely
7551        while printing error messages.  */
7552     SAVEI8(PL_utf8cache);
7553     PL_utf8cache = 0;
7554     Perl_croak(aTHX_ "panic: %s cache %"UVuf" real %"UVuf" for %"SVf,
7555                func, (UV) from_cache, (UV) real, SVfARG(sv));
7556 }
7557
7558 /*
7559 =for apidoc sv_eq
7560
7561 Returns a boolean indicating whether the strings in the two SVs are
7562 identical.  Is UTF-8 and 'use bytes' aware, handles get magic, and will
7563 coerce its args to strings if necessary.
7564
7565 =for apidoc sv_eq_flags
7566
7567 Returns a boolean indicating whether the strings in the two SVs are
7568 identical.  Is UTF-8 and 'use bytes' aware and coerces its args to strings
7569 if necessary.  If the flags include SV_GMAGIC, it handles get-magic, too.
7570
7571 =cut
7572 */
7573
7574 I32
7575 Perl_sv_eq_flags(pTHX_ SV *sv1, SV *sv2, const U32 flags)
7576 {
7577     dVAR;
7578     const char *pv1;
7579     STRLEN cur1;
7580     const char *pv2;
7581     STRLEN cur2;
7582     I32  eq     = 0;
7583     SV* svrecode = NULL;
7584
7585     if (!sv1) {
7586         pv1 = "";
7587         cur1 = 0;
7588     }
7589     else {
7590         /* if pv1 and pv2 are the same, second SvPV_const call may
7591          * invalidate pv1 (if we are handling magic), so we may need to
7592          * make a copy */
7593         if (sv1 == sv2 && flags & SV_GMAGIC
7594          && (SvTHINKFIRST(sv1) || SvGMAGICAL(sv1))) {
7595             pv1 = SvPV_const(sv1, cur1);
7596             sv1 = newSVpvn_flags(pv1, cur1, SVs_TEMP | SvUTF8(sv2));
7597         }
7598         pv1 = SvPV_flags_const(sv1, cur1, flags);
7599     }
7600
7601     if (!sv2){
7602         pv2 = "";
7603         cur2 = 0;
7604     }
7605     else
7606         pv2 = SvPV_flags_const(sv2, cur2, flags);
7607
7608     if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
7609         /* Differing utf8ness.
7610          * Do not UTF8size the comparands as a side-effect. */
7611          if (PL_encoding) {
7612               if (SvUTF8(sv1)) {
7613                    svrecode = newSVpvn(pv2, cur2);
7614                    sv_recode_to_utf8(svrecode, PL_encoding);
7615                    pv2 = SvPV_const(svrecode, cur2);
7616               }
7617               else {
7618                    svrecode = newSVpvn(pv1, cur1);
7619                    sv_recode_to_utf8(svrecode, PL_encoding);
7620                    pv1 = SvPV_const(svrecode, cur1);
7621               }
7622               /* Now both are in UTF-8. */
7623               if (cur1 != cur2) {
7624                    SvREFCNT_dec_NN(svrecode);
7625                    return FALSE;
7626               }
7627          }
7628          else {
7629               if (SvUTF8(sv1)) {
7630                   /* sv1 is the UTF-8 one  */
7631                   return bytes_cmp_utf8((const U8*)pv2, cur2,
7632                                         (const U8*)pv1, cur1) == 0;
7633               }
7634               else {
7635                   /* sv2 is the UTF-8 one  */
7636                   return bytes_cmp_utf8((const U8*)pv1, cur1,
7637                                         (const U8*)pv2, cur2) == 0;
7638               }
7639          }
7640     }
7641
7642     if (cur1 == cur2)
7643         eq = (pv1 == pv2) || memEQ(pv1, pv2, cur1);
7644         
7645     SvREFCNT_dec(svrecode);
7646
7647     return eq;
7648 }
7649
7650 /*
7651 =for apidoc sv_cmp
7652
7653 Compares the strings in two SVs.  Returns -1, 0, or 1 indicating whether the
7654 string in C<sv1> is less than, equal to, or greater than the string in
7655 C<sv2>.  Is UTF-8 and 'use bytes' aware, handles get magic, and will
7656 coerce its args to strings if necessary.  See also C<sv_cmp_locale>.
7657
7658 =for apidoc sv_cmp_flags
7659
7660 Compares the strings in two SVs.  Returns -1, 0, or 1 indicating whether the
7661 string in C<sv1> is less than, equal to, or greater than the string in
7662 C<sv2>.  Is UTF-8 and 'use bytes' aware and will coerce its args to strings
7663 if necessary.  If the flags include SV_GMAGIC, it handles get magic.  See
7664 also C<sv_cmp_locale_flags>.
7665
7666 =cut
7667 */
7668
7669 I32
7670 Perl_sv_cmp(pTHX_ SV *const sv1, SV *const sv2)
7671 {
7672     return sv_cmp_flags(sv1, sv2, SV_GMAGIC);
7673 }
7674
7675 I32
7676 Perl_sv_cmp_flags(pTHX_ SV *const sv1, SV *const sv2,
7677                   const U32 flags)
7678 {
7679     dVAR;
7680     STRLEN cur1, cur2;
7681     const char *pv1, *pv2;
7682     I32  cmp;
7683     SV *svrecode = NULL;
7684
7685     if (!sv1) {
7686         pv1 = "";
7687         cur1 = 0;
7688     }
7689     else
7690         pv1 = SvPV_flags_const(sv1, cur1, flags);
7691
7692     if (!sv2) {
7693         pv2 = "";
7694         cur2 = 0;
7695     }
7696     else
7697         pv2 = SvPV_flags_const(sv2, cur2, flags);
7698
7699     if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
7700         /* Differing utf8ness.
7701          * Do not UTF8size the comparands as a side-effect. */
7702         if (SvUTF8(sv1)) {
7703             if (PL_encoding) {
7704                  svrecode = newSVpvn(pv2, cur2);
7705                  sv_recode_to_utf8(svrecode, PL_encoding);
7706                  pv2 = SvPV_const(svrecode, cur2);
7707             }
7708             else {
7709                 const int retval = -bytes_cmp_utf8((const U8*)pv2, cur2,
7710                                                    (const U8*)pv1, cur1);
7711                 return retval ? retval < 0 ? -1 : +1 : 0;
7712             }
7713         }
7714         else {
7715             if (PL_encoding) {
7716                  svrecode = newSVpvn(pv1, cur1);
7717                  sv_recode_to_utf8(svrecode, PL_encoding);
7718                  pv1 = SvPV_const(svrecode, cur1);
7719             }
7720             else {
7721                 const int retval = bytes_cmp_utf8((const U8*)pv1, cur1,
7722                                                   (const U8*)pv2, cur2);
7723                 return retval ? retval < 0 ? -1 : +1 : 0;
7724             }
7725         }
7726     }
7727
7728     if (!cur1) {
7729         cmp = cur2 ? -1 : 0;
7730     } else if (!cur2) {
7731         cmp = 1;
7732     } else {
7733         const I32 retval = memcmp((const void*)pv1, (const void*)pv2, cur1 < cur2 ? cur1 : cur2);
7734
7735         if (retval) {
7736             cmp = retval < 0 ? -1 : 1;
7737         } else if (cur1 == cur2) {
7738             cmp = 0;
7739         } else {
7740             cmp = cur1 < cur2 ? -1 : 1;
7741         }
7742     }
7743
7744     SvREFCNT_dec(svrecode);
7745
7746     return cmp;
7747 }
7748
7749 /*
7750 =for apidoc sv_cmp_locale
7751
7752 Compares the strings in two SVs in a locale-aware manner.  Is UTF-8 and
7753 'use bytes' aware, handles get magic, and will coerce its args to strings
7754 if necessary.  See also C<sv_cmp>.
7755
7756 =for apidoc sv_cmp_locale_flags
7757
7758 Compares the strings in two SVs in a locale-aware manner.  Is UTF-8 and
7759 'use bytes' aware and will coerce its args to strings if necessary.  If the
7760 flags contain SV_GMAGIC, it handles get magic.  See also C<sv_cmp_flags>.
7761
7762 =cut
7763 */
7764
7765 I32
7766 Perl_sv_cmp_locale(pTHX_ SV *const sv1, SV *const sv2)
7767 {
7768     return sv_cmp_locale_flags(sv1, sv2, SV_GMAGIC);
7769 }
7770
7771 I32
7772 Perl_sv_cmp_locale_flags(pTHX_ SV *const sv1, SV *const sv2,
7773                          const U32 flags)
7774 {
7775     dVAR;
7776 #ifdef USE_LOCALE_COLLATE
7777
7778     char *pv1, *pv2;
7779     STRLEN len1, len2;
7780     I32 retval;
7781
7782     if (PL_collation_standard)
7783         goto raw_compare;
7784
7785     len1 = 0;
7786     pv1 = sv1 ? sv_collxfrm_flags(sv1, &len1, flags) : (char *) NULL;
7787     len2 = 0;
7788     pv2 = sv2 ? sv_collxfrm_flags(sv2, &len2, flags) : (char *) NULL;
7789
7790     if (!pv1 || !len1) {
7791         if (pv2 && len2)
7792             return -1;
7793         else
7794             goto raw_compare;
7795     }
7796     else {
7797         if (!pv2 || !len2)
7798             return 1;
7799     }
7800
7801     retval = memcmp((void*)pv1, (void*)pv2, len1 < len2 ? len1 : len2);
7802
7803     if (retval)
7804         return retval < 0 ? -1 : 1;
7805
7806     /*
7807      * When the result of collation is equality, that doesn't mean
7808      * that there are no differences -- some locales exclude some
7809      * characters from consideration.  So to avoid false equalities,
7810      * we use the raw string as a tiebreaker.
7811      */
7812
7813   raw_compare:
7814     /* FALLTHROUGH */
7815
7816 #else
7817     PERL_UNUSED_ARG(flags);
7818 #endif /* USE_LOCALE_COLLATE */
7819
7820     return sv_cmp(sv1, sv2);
7821 }
7822
7823
7824 #ifdef USE_LOCALE_COLLATE
7825
7826 /*
7827 =for apidoc sv_collxfrm
7828
7829 This calls C<sv_collxfrm_flags> with the SV_GMAGIC flag.  See
7830 C<sv_collxfrm_flags>.
7831
7832 =for apidoc sv_collxfrm_flags
7833
7834 Add Collate Transform magic to an SV if it doesn't already have it.  If the
7835 flags contain SV_GMAGIC, it handles get-magic.
7836
7837 Any scalar variable may carry PERL_MAGIC_collxfrm magic that contains the
7838 scalar data of the variable, but transformed to such a format that a normal
7839 memory comparison can be used to compare the data according to the locale
7840 settings.
7841
7842 =cut
7843 */
7844
7845 char *
7846 Perl_sv_collxfrm_flags(pTHX_ SV *const sv, STRLEN *const nxp, const I32 flags)
7847 {
7848     dVAR;
7849     MAGIC *mg;
7850
7851     PERL_ARGS_ASSERT_SV_COLLXFRM_FLAGS;
7852
7853     mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_collxfrm) : (MAGIC *) NULL;
7854     if (!mg || !mg->mg_ptr || *(U32*)mg->mg_ptr != PL_collation_ix) {
7855         const char *s;
7856         char *xf;
7857         STRLEN len, xlen;
7858
7859         if (mg)
7860             Safefree(mg->mg_ptr);
7861         s = SvPV_flags_const(sv, len, flags);
7862         if ((xf = mem_collxfrm(s, len, &xlen))) {
7863             if (! mg) {
7864 #ifdef PERL_OLD_COPY_ON_WRITE
7865                 if (SvIsCOW(sv))
7866                     sv_force_normal_flags(sv, 0);
7867 #endif
7868                 mg = sv_magicext(sv, 0, PERL_MAGIC_collxfrm, &PL_vtbl_collxfrm,
7869                                  0, 0);
7870                 assert(mg);
7871             }
7872             mg->mg_ptr = xf;
7873             mg->mg_len = xlen;
7874         }
7875         else {
7876             if (mg) {
7877                 mg->mg_ptr = NULL;
7878                 mg->mg_len = -1;
7879             }
7880         }
7881     }
7882     if (mg && mg->mg_ptr) {
7883         *nxp = mg->mg_len;
7884         return mg->mg_ptr + sizeof(PL_collation_ix);
7885     }
7886     else {
7887         *nxp = 0;
7888         return NULL;
7889     }
7890 }
7891
7892 #endif /* USE_LOCALE_COLLATE */
7893
7894 static char *
7895 S_sv_gets_append_to_utf8(pTHX_ SV *const sv, PerlIO *const fp, I32 append)
7896 {
7897     SV * const tsv = newSV(0);
7898     ENTER;
7899     SAVEFREESV(tsv);
7900     sv_gets(tsv, fp, 0);
7901     sv_utf8_upgrade_nomg(tsv);
7902     SvCUR_set(sv,append);
7903     sv_catsv(sv,tsv);
7904     LEAVE;
7905     return (SvCUR(sv) - append) ? SvPVX(sv) : NULL;
7906 }
7907
7908 static char *
7909 S_sv_gets_read_record(pTHX_ SV *const sv, PerlIO *const fp, I32 append)
7910 {
7911     SSize_t bytesread;
7912     const STRLEN recsize = SvUV(SvRV(PL_rs)); /* RsRECORD() guarantees > 0. */
7913       /* Grab the size of the record we're getting */
7914     char *buffer = SvGROW(sv, (STRLEN)(recsize + append + 1)) + append;
7915     
7916     /* Go yank in */
7917 #ifdef VMS
7918 #include <rms.h>
7919     int fd;
7920     Stat_t st;
7921
7922     /* With a true, record-oriented file on VMS, we need to use read directly
7923      * to ensure that we respect RMS record boundaries.  The user is responsible
7924      * for providing a PL_rs value that corresponds to the FAB$W_MRS (maximum
7925      * record size) field.  N.B. This is likely to produce invalid results on
7926      * varying-width character data when a record ends mid-character.
7927      */
7928     fd = PerlIO_fileno(fp);
7929     if (fd != -1
7930         && PerlLIO_fstat(fd, &st) == 0
7931         && (st.st_fab_rfm == FAB$C_VAR
7932             || st.st_fab_rfm == FAB$C_VFC
7933             || st.st_fab_rfm == FAB$C_FIX)) {
7934
7935         bytesread = PerlLIO_read(fd, buffer, recsize);
7936     }
7937     else /* in-memory file from PerlIO::Scalar
7938           * or not a record-oriented file
7939           */
7940 #endif
7941     {
7942         bytesread = PerlIO_read(fp, buffer, recsize);
7943
7944         /* At this point, the logic in sv_get() means that sv will
7945            be treated as utf-8 if the handle is utf8.
7946         */
7947         if (PerlIO_isutf8(fp) && bytesread > 0) {
7948             char *bend = buffer + bytesread;
7949             char *bufp = buffer;
7950             size_t charcount = 0;
7951             bool charstart = TRUE;
7952             STRLEN skip = 0;
7953
7954             while (charcount < recsize) {
7955                 /* count accumulated characters */
7956                 while (bufp < bend) {
7957                     if (charstart) {
7958                         skip = UTF8SKIP(bufp);
7959                     }
7960                     if (bufp + skip > bend) {
7961                         /* partial at the end */
7962                         charstart = FALSE;
7963                         break;
7964                     }
7965                     else {
7966                         ++charcount;
7967                         bufp += skip;
7968                         charstart = TRUE;
7969                     }
7970                 }
7971
7972                 if (charcount < recsize) {
7973                     STRLEN readsize;
7974                     STRLEN bufp_offset = bufp - buffer;
7975                     SSize_t morebytesread;
7976
7977                     /* originally I read enough to fill any incomplete
7978                        character and the first byte of the next
7979                        character if needed, but if there's many
7980                        multi-byte encoded characters we're going to be
7981                        making a read call for every character beyond
7982                        the original read size.
7983
7984                        So instead, read the rest of the character if
7985                        any, and enough bytes to match at least the
7986                        start bytes for each character we're going to
7987                        read.
7988                     */
7989                     if (charstart)
7990                         readsize = recsize - charcount;
7991                     else 
7992                         readsize = skip - (bend - bufp) + recsize - charcount - 1;
7993                     buffer = SvGROW(sv, append + bytesread + readsize + 1) + append;
7994                     bend = buffer + bytesread;
7995                     morebytesread = PerlIO_read(fp, bend, readsize);
7996                     if (morebytesread <= 0) {
7997                         /* we're done, if we still have incomplete
7998                            characters the check code in sv_gets() will
7999                            warn about them.
8000
8001                            I'd originally considered doing
8002                            PerlIO_ungetc() on all but the lead
8003                            character of the incomplete character, but
8004                            read() doesn't do that, so I don't.
8005                         */
8006                         break;
8007                     }
8008
8009                     /* prepare to scan some more */
8010                     bytesread += morebytesread;
8011                     bend = buffer + bytesread;
8012                     bufp = buffer + bufp_offset;
8013                 }
8014             }
8015         }
8016     }
8017
8018     if (bytesread < 0)
8019         bytesread = 0;
8020     SvCUR_set(sv, bytesread + append);
8021     buffer[bytesread] = '\0';
8022     return (SvCUR(sv) - append) ? SvPVX(sv) : NULL;
8023 }
8024
8025 /*
8026 =for apidoc sv_gets
8027
8028 Get a line from the filehandle and store it into the SV, optionally
8029 appending to the currently-stored string.  If C<append> is not 0, the
8030 line is appended to the SV instead of overwriting it.  C<append> should
8031 be set to the byte offset that the appended string should start at
8032 in the SV (typically, C<SvCUR(sv)> is a suitable choice).
8033
8034 =cut
8035 */
8036
8037 char *
8038 Perl_sv_gets(pTHX_ SV *const sv, PerlIO *const fp, I32 append)
8039 {
8040     dVAR;
8041     const char *rsptr;
8042     STRLEN rslen;
8043     STDCHAR rslast;
8044     STDCHAR *bp;
8045     SSize_t cnt;
8046     int i = 0;
8047     int rspara = 0;
8048
8049     PERL_ARGS_ASSERT_SV_GETS;
8050
8051     if (SvTHINKFIRST(sv))
8052         sv_force_normal_flags(sv, append ? 0 : SV_COW_DROP_PV);
8053     /* XXX. If you make this PVIV, then copy on write can copy scalars read
8054        from <>.
8055        However, perlbench says it's slower, because the existing swipe code
8056        is faster than copy on write.
8057        Swings and roundabouts.  */
8058     SvUPGRADE(sv, SVt_PV);
8059
8060     if (append) {
8061         /* line is going to be appended to the existing buffer in the sv */
8062         if (PerlIO_isutf8(fp)) {
8063             if (!SvUTF8(sv)) {
8064                 sv_utf8_upgrade_nomg(sv);
8065                 sv_pos_u2b(sv,&append,0);
8066             }
8067         } else if (SvUTF8(sv)) {
8068             return S_sv_gets_append_to_utf8(aTHX_ sv, fp, append);
8069         }
8070     }
8071
8072     SvPOK_only(sv);
8073     if (!append) {
8074         /* not appending - "clear" the string by setting SvCUR to 0,
8075          * the pv is still avaiable. */
8076         SvCUR_set(sv,0);
8077     }
8078     if (PerlIO_isutf8(fp))
8079         SvUTF8_on(sv);
8080
8081     if (IN_PERL_COMPILETIME) {
8082         /* we always read code in line mode */
8083         rsptr = "\n";
8084         rslen = 1;
8085     }
8086     else if (RsSNARF(PL_rs)) {
8087         /* If it is a regular disk file use size from stat() as estimate
8088            of amount we are going to read -- may result in mallocing
8089            more memory than we really need if the layers below reduce
8090            the size we read (e.g. CRLF or a gzip layer).
8091          */
8092         Stat_t st;
8093         if (!PerlLIO_fstat(PerlIO_fileno(fp), &st) && S_ISREG(st.st_mode))  {
8094             const Off_t offset = PerlIO_tell(fp);
8095             if (offset != (Off_t) -1 && st.st_size + append > offset) {
8096 #ifdef PERL_NEW_COPY_ON_WRITE
8097                 /* Add an extra byte for the sake of copy-on-write's
8098                  * buffer reference count. */
8099                 (void) SvGROW(sv, (STRLEN)((st.st_size - offset) + append + 2));
8100 #else
8101                 (void) SvGROW(sv, (STRLEN)((st.st_size - offset) + append + 1));
8102 #endif
8103             }
8104         }
8105         rsptr = NULL;
8106         rslen = 0;
8107     }
8108     else if (RsRECORD(PL_rs)) {
8109         return S_sv_gets_read_record(aTHX_ sv, fp, append);
8110     }
8111     else if (RsPARA(PL_rs)) {
8112         rsptr = "\n\n";
8113         rslen = 2;
8114         rspara = 1;
8115     }
8116     else {
8117         /* Get $/ i.e. PL_rs into same encoding as stream wants */
8118         if (PerlIO_isutf8(fp)) {
8119             rsptr = SvPVutf8(PL_rs, rslen);
8120         }
8121         else {
8122             if (SvUTF8(PL_rs)) {
8123                 if (!sv_utf8_downgrade(PL_rs, TRUE)) {
8124                     Perl_croak(aTHX_ "Wide character in $/");
8125                 }
8126             }
8127             /* extract the raw pointer to the record separator */
8128             rsptr = SvPV_const(PL_rs, rslen);
8129         }
8130     }
8131
8132     /* rslast is the last character in the record separator
8133      * note we don't use rslast except when rslen is true, so the
8134      * null assign is a placeholder. */
8135     rslast = rslen ? rsptr[rslen - 1] : '\0';
8136
8137     if (rspara) {               /* have to do this both before and after */
8138         do {                    /* to make sure file boundaries work right */
8139             if (PerlIO_eof(fp))
8140                 return 0;
8141             i = PerlIO_getc(fp);
8142             if (i != '\n') {
8143                 if (i == -1)
8144                     return 0;
8145                 PerlIO_ungetc(fp,i);
8146                 break;
8147             }
8148         } while (i != EOF);
8149     }
8150
8151     /* See if we know enough about I/O mechanism to cheat it ! */
8152
8153     /* This used to be #ifdef test - it is made run-time test for ease
8154        of abstracting out stdio interface. One call should be cheap
8155        enough here - and may even be a macro allowing compile
8156        time optimization.
8157      */
8158
8159     if (PerlIO_fast_gets(fp)) {
8160     /*
8161      * We can do buffer based IO operations on this filehandle.
8162      *
8163      * This means we can bypass a lot of subcalls and process
8164      * the buffer directly, it also means we know the upper bound
8165      * on the amount of data we might read of the current buffer
8166      * into our sv. Knowing this allows us to preallocate the pv
8167      * to be able to hold that maximum, which allows us to simplify
8168      * a lot of logic. */
8169
8170     /*
8171      * We're going to steal some values from the stdio struct
8172      * and put EVERYTHING in the innermost loop into registers.
8173      */
8174     STDCHAR *ptr;       /* pointer into fp's read-ahead buffer */
8175     STRLEN bpx;         /* length of the data in the target sv
8176                            used to fix pointers after a SvGROW */
8177     I32 shortbuffered;  /* If the pv buffer is shorter than the amount
8178                            of data left in the read-ahead buffer.
8179                            If 0 then the pv buffer can hold the full
8180                            amount left, otherwise this is the amount it
8181                            can hold. */
8182
8183 #if defined(VMS) && defined(PERLIO_IS_STDIO)
8184     /* An ungetc()d char is handled separately from the regular
8185      * buffer, so we getc() it back out and stuff it in the buffer.
8186      */
8187     i = PerlIO_getc(fp);
8188     if (i == EOF) return 0;
8189     *(--((*fp)->_ptr)) = (unsigned char) i;
8190     (*fp)->_cnt++;
8191 #endif
8192
8193     /* Here is some breathtakingly efficient cheating */
8194
8195     /* When you read the following logic resist the urge to think
8196      * of record separators that are 1 byte long. They are an
8197      * uninteresting special (simple) case.
8198      *
8199      * Instead think of record separators which are at least 2 bytes
8200      * long, and keep in mind that we need to deal with such
8201      * separators when they cross a read-ahead buffer boundary.
8202      *
8203      * Also consider that we need to gracefully deal with separators
8204      * that may be longer than a single read ahead buffer.
8205      *
8206      * Lastly do not forget we want to copy the delimiter as well. We
8207      * are copying all data in the file _up_to_and_including_ the separator
8208      * itself.
8209      *
8210      * Now that you have all that in mind here is what is happening below:
8211      *
8212      * 1. When we first enter the loop we do some memory book keeping to see
8213      * how much free space there is in the target SV. (This sub assumes that
8214      * it is operating on the same SV most of the time via $_ and that it is
8215      * going to be able to reuse the same pv buffer each call.) If there is
8216      * "enough" room then we set "shortbuffered" to how much space there is
8217      * and start reading forward.
8218      *
8219      * 2. When we scan forward we copy from the read-ahead buffer to the target
8220      * SV's pv buffer. While we go we watch for the end of the read-ahead buffer,
8221      * and the end of the of pv, as well as for the "rslast", which is the last
8222      * char of the separator.
8223      *
8224      * 3. When scanning forward if we see rslast then we jump backwards in *pv*
8225      * (which has a "complete" record up to the point we saw rslast) and check
8226      * it to see if it matches the separator. If it does we are done. If it doesn't
8227      * we continue on with the scan/copy.
8228      *
8229      * 4. If we run out of read-ahead buffer (cnt goes to 0) then we have to get
8230      * the IO system to read the next buffer. We do this by doing a getc(), which
8231      * returns a single char read (or EOF), and prefills the buffer, and also
8232      * allows us to find out how full the buffer is.  We use this information to
8233      * SvGROW() the sv to the size remaining in the buffer, after which we copy
8234      * the returned single char into the target sv, and then go back into scan
8235      * forward mode.
8236      *
8237      * 5. If we run out of write-buffer then we SvGROW() it by the size of the
8238      * remaining space in the read-buffer.
8239      *
8240      * Note that this code despite its twisty-turny nature is pretty darn slick.
8241      * It manages single byte separators, multi-byte cross boundary separators,
8242      * and cross-read-buffer separators cleanly and efficiently at the cost
8243      * of potentially greatly overallocating the target SV.
8244      *
8245      * Yves
8246      */
8247
8248
8249     /* get the number of bytes remaining in the read-ahead buffer
8250      * on first call on a given fp this will return 0.*/
8251     cnt = PerlIO_get_cnt(fp);
8252
8253     /* make sure we have the room */
8254     if ((I32)(SvLEN(sv) - append) <= cnt + 1) {
8255         /* Not room for all of it
8256            if we are looking for a separator and room for some
8257          */
8258         if (rslen && cnt > 80 && (I32)SvLEN(sv) > append) {
8259             /* just process what we have room for */
8260             shortbuffered = cnt - SvLEN(sv) + append + 1;
8261             cnt -= shortbuffered;
8262         }
8263         else {
8264             /* ensure that the target sv has enough room to hold
8265              * the rest of the read-ahead buffer */
8266             shortbuffered = 0;
8267             /* remember that cnt can be negative */
8268             SvGROW(sv, (STRLEN)(append + (cnt <= 0 ? 2 : (cnt + 1))));
8269         }
8270     }
8271     else {
8272         /* we have enough room to hold the full buffer, lets scream */
8273         shortbuffered = 0;
8274     }
8275
8276     /* extract the pointer to sv's string buffer, offset by append as necessary */
8277     bp = (STDCHAR*)SvPVX_const(sv) + append;  /* move these two too to registers */
8278     /* extract the point to the read-ahead buffer */
8279     ptr = (STDCHAR*)PerlIO_get_ptr(fp);
8280
8281     /* some trace debug output */
8282     DEBUG_P(PerlIO_printf(Perl_debug_log,
8283         "Screamer: entering, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
8284     DEBUG_P(PerlIO_printf(Perl_debug_log,
8285         "Screamer: entering: PerlIO * thinks ptr=%"UVuf", cnt=%zd, base=%"
8286          UVuf"\n",
8287                PTR2UV(PerlIO_get_ptr(fp)), PerlIO_get_cnt(fp),
8288                PTR2UV(PerlIO_has_base(fp) ? PerlIO_get_base(fp) : 0)));
8289
8290     for (;;) {
8291       screamer:
8292         /* if there is stuff left in the read-ahead buffer */
8293         if (cnt > 0) {
8294             /* if there is a separator */
8295             if (rslen) {
8296                 /* loop until we hit the end of the read-ahead buffer */
8297                 while (cnt > 0) {                    /* this     |  eat */
8298                     /* scan forward copying and searching for rslast as we go */
8299                     cnt--;
8300                     if ((*bp++ = *ptr++) == rslast)  /* really   |  dust */
8301                         goto thats_all_folks;        /* screams  |  sed :-) */
8302                 }
8303             }
8304             else {
8305                 /* no separator, slurp the full buffer */
8306                 Copy(ptr, bp, cnt, char);            /* this     |  eat */
8307                 bp += cnt;                           /* screams  |  dust */
8308                 ptr += cnt;                          /* louder   |  sed :-) */
8309                 cnt = 0;
8310                 assert (!shortbuffered);
8311                 goto cannot_be_shortbuffered;
8312             }
8313         }
8314         
8315         if (shortbuffered) {            /* oh well, must extend */
8316             /* we didnt have enough room to fit the line into the target buffer
8317              * so we must extend the target buffer and keep going */
8318             cnt = shortbuffered;
8319             shortbuffered = 0;
8320             bpx = bp - (STDCHAR*)SvPVX_const(sv); /* box up before relocation */
8321             SvCUR_set(sv, bpx);
8322             /* extned the target sv's buffer so it can hold the full read-ahead buffer */
8323             SvGROW(sv, SvLEN(sv) + append + cnt + 2);
8324             bp = (STDCHAR*)SvPVX_const(sv) + bpx; /* unbox after relocation */
8325             continue;
8326         }
8327
8328     cannot_be_shortbuffered:
8329         /* we need to refill the read-ahead buffer if possible */
8330
8331         DEBUG_P(PerlIO_printf(Perl_debug_log,
8332                              "Screamer: going to getc, ptr=%"UVuf", cnt=%zd\n",
8333                               PTR2UV(ptr),cnt));
8334         PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt); /* deregisterize cnt and ptr */
8335
8336         DEBUG_Pv(PerlIO_printf(Perl_debug_log,
8337            "Screamer: pre: FILE * thinks ptr=%"UVuf", cnt=%zd, base=%"UVuf"\n",
8338             PTR2UV(PerlIO_get_ptr(fp)), PerlIO_get_cnt(fp),
8339             PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
8340
8341         /*
8342             call PerlIO_getc() to let it prefill the lookahead buffer
8343
8344             This used to call 'filbuf' in stdio form, but as that behaves like
8345             getc when cnt <= 0 we use PerlIO_getc here to avoid introducing
8346             another abstraction.
8347
8348             Note we have to deal with the char in 'i' if we are not at EOF
8349         */
8350         i   = PerlIO_getc(fp);          /* get more characters */
8351
8352         DEBUG_Pv(PerlIO_printf(Perl_debug_log,
8353            "Screamer: post: FILE * thinks ptr=%"UVuf", cnt=%zd, base=%"UVuf"\n",
8354             PTR2UV(PerlIO_get_ptr(fp)), PerlIO_get_cnt(fp),
8355             PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
8356
8357         /* find out how much is left in the read-ahead buffer, and rextract its pointer */
8358         cnt = PerlIO_get_cnt(fp);
8359         ptr = (STDCHAR*)PerlIO_get_ptr(fp);     /* reregisterize cnt and ptr */
8360         DEBUG_P(PerlIO_printf(Perl_debug_log,
8361             "Screamer: after getc, ptr=%"UVuf", cnt=%zd\n",
8362              PTR2UV(ptr),cnt));
8363
8364         if (i == EOF)                   /* all done for ever? */
8365             goto thats_really_all_folks;
8366
8367         /* make sure we have enough space in the target sv */
8368         bpx = bp - (STDCHAR*)SvPVX_const(sv);   /* box up before relocation */
8369         SvCUR_set(sv, bpx);
8370         SvGROW(sv, bpx + cnt + 2);
8371         bp = (STDCHAR*)SvPVX_const(sv) + bpx;   /* unbox after relocation */
8372
8373         /* copy of the char we got from getc() */
8374         *bp++ = (STDCHAR)i;             /* store character from PerlIO_getc */
8375
8376         /* make sure we deal with the i being the last character of a separator */
8377         if (rslen && (STDCHAR)i == rslast)  /* all done for now? */
8378             goto thats_all_folks;
8379     }
8380
8381 thats_all_folks:
8382     /* check if we have actually found the separator - only really applies
8383      * when rslen > 1 */
8384     if ((rslen > 1 && (STRLEN)(bp - (STDCHAR*)SvPVX_const(sv)) < rslen) ||
8385           memNE((char*)bp - rslen, rsptr, rslen))
8386         goto screamer;                          /* go back to the fray */
8387 thats_really_all_folks:
8388     if (shortbuffered)
8389         cnt += shortbuffered;
8390         DEBUG_P(PerlIO_printf(Perl_debug_log,
8391             "Screamer: quitting, ptr=%"UVuf", cnt=%zd\n",PTR2UV(ptr),cnt));
8392     PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt);  /* put these back or we're in trouble */
8393     DEBUG_P(PerlIO_printf(Perl_debug_log,
8394         "Screamer: end: FILE * thinks ptr=%"UVuf", cnt=%zd, base=%"UVuf
8395         "\n",
8396         PTR2UV(PerlIO_get_ptr(fp)), PerlIO_get_cnt(fp),
8397         PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
8398     *bp = '\0';
8399     SvCUR_set(sv, bp - (STDCHAR*)SvPVX_const(sv));      /* set length */
8400     DEBUG_P(PerlIO_printf(Perl_debug_log,
8401         "Screamer: done, len=%ld, string=|%.*s|\n",
8402         (long)SvCUR(sv),(int)SvCUR(sv),SvPVX_const(sv)));
8403     }
8404    else
8405     {
8406        /*The big, slow, and stupid way. */
8407 #ifdef USE_HEAP_INSTEAD_OF_STACK        /* Even slower way. */
8408         STDCHAR *buf = NULL;
8409         Newx(buf, 8192, STDCHAR);
8410         assert(buf);
8411 #else
8412         STDCHAR buf[8192];
8413 #endif
8414
8415 screamer2:
8416         if (rslen) {
8417             const STDCHAR * const bpe = buf + sizeof(buf);
8418             bp = buf;
8419             while ((i = PerlIO_getc(fp)) != EOF && (*bp++ = (STDCHAR)i) != rslast && bp < bpe)
8420                 ; /* keep reading */
8421             cnt = bp - buf;
8422         }
8423         else {
8424             cnt = PerlIO_read(fp,(char*)buf, sizeof(buf));
8425             /* Accommodate broken VAXC compiler, which applies U8 cast to
8426              * both args of ?: operator, causing EOF to change into 255
8427              */
8428             if (cnt > 0)
8429                  i = (U8)buf[cnt - 1];
8430             else
8431                  i = EOF;
8432         }
8433
8434         if (cnt < 0)
8435             cnt = 0;  /* we do need to re-set the sv even when cnt <= 0 */
8436         if (append)
8437             sv_catpvn_nomg(sv, (char *) buf, cnt);
8438         else
8439             sv_setpvn(sv, (char *) buf, cnt);   /* "nomg" is implied */
8440
8441         if (i != EOF &&                 /* joy */
8442             (!rslen ||
8443              SvCUR(sv) < rslen ||
8444              memNE(SvPVX_const(sv) + SvCUR(sv) - rslen, rsptr, rslen)))
8445         {
8446             append = -1;
8447             /*
8448              * If we're reading from a TTY and we get a short read,
8449              * indicating that the user hit his EOF character, we need
8450              * to notice it now, because if we try to read from the TTY
8451              * again, the EOF condition will disappear.
8452              *
8453              * The comparison of cnt to sizeof(buf) is an optimization
8454              * that prevents unnecessary calls to feof().
8455              *
8456              * - jik 9/25/96
8457              */
8458             if (!(cnt < (I32)sizeof(buf) && PerlIO_eof(fp)))
8459                 goto screamer2;
8460         }
8461
8462 #ifdef USE_HEAP_INSTEAD_OF_STACK
8463         Safefree(buf);
8464 #endif
8465     }
8466
8467     if (rspara) {               /* have to do this both before and after */
8468         while (i != EOF) {      /* to make sure file boundaries work right */
8469             i = PerlIO_getc(fp);
8470             if (i != '\n') {
8471                 PerlIO_ungetc(fp,i);
8472                 break;
8473             }
8474         }
8475     }
8476
8477     return (SvCUR(sv) - append) ? SvPVX(sv) : NULL;
8478 }
8479
8480 /*
8481 =for apidoc sv_inc
8482
8483 Auto-increment of the value in the SV, doing string to numeric conversion
8484 if necessary.  Handles 'get' magic and operator overloading.
8485
8486 =cut
8487 */
8488
8489 void
8490 Perl_sv_inc(pTHX_ SV *const sv)
8491 {
8492     if (!sv)
8493         return;
8494     SvGETMAGIC(sv);
8495     sv_inc_nomg(sv);
8496 }
8497
8498 /*
8499 =for apidoc sv_inc_nomg
8500
8501 Auto-increment of the value in the SV, doing string to numeric conversion
8502 if necessary.  Handles operator overloading.  Skips handling 'get' magic.
8503
8504 =cut
8505 */
8506
8507 void
8508 Perl_sv_inc_nomg(pTHX_ SV *const sv)
8509 {
8510     dVAR;
8511     char *d;
8512     int flags;
8513
8514     if (!sv)
8515         return;
8516     if (SvTHINKFIRST(sv)) {
8517         if (SvREADONLY(sv)) {
8518                 Perl_croak_no_modify();
8519         }
8520         if (SvROK(sv)) {
8521             IV i;
8522             if (SvAMAGIC(sv) && AMG_CALLunary(sv, inc_amg))
8523                 return;
8524             i = PTR2IV(SvRV(sv));
8525             sv_unref(sv);
8526             sv_setiv(sv, i);
8527         }
8528         else sv_force_normal_flags(sv, 0);
8529     }
8530     flags = SvFLAGS(sv);
8531     if ((flags & (SVp_NOK|SVp_IOK)) == SVp_NOK) {
8532         /* It's (privately or publicly) a float, but not tested as an
8533            integer, so test it to see. */
8534         (void) SvIV(sv);
8535         flags = SvFLAGS(sv);
8536     }
8537     if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
8538         /* It's publicly an integer, or privately an integer-not-float */
8539 #ifdef PERL_PRESERVE_IVUV
8540       oops_its_int:
8541 #endif
8542         if (SvIsUV(sv)) {
8543             if (SvUVX(sv) == UV_MAX)
8544                 sv_setnv(sv, UV_MAX_P1);
8545             else
8546                 (void)SvIOK_only_UV(sv);
8547                 SvUV_set(sv, SvUVX(sv) + 1);
8548         } else {
8549             if (SvIVX(sv) == IV_MAX)
8550                 sv_setuv(sv, (UV)IV_MAX + 1);
8551             else {
8552                 (void)SvIOK_only(sv);
8553                 SvIV_set(sv, SvIVX(sv) + 1);
8554             }   
8555         }
8556         return;
8557     }
8558     if (flags & SVp_NOK) {
8559         const NV was = SvNVX(sv);
8560         if (NV_OVERFLOWS_INTEGERS_AT &&
8561             was >= NV_OVERFLOWS_INTEGERS_AT) {
8562             /* diag_listed_as: Lost precision when %s %f by 1 */
8563             Perl_ck_warner(aTHX_ packWARN(WARN_IMPRECISION),
8564                            "Lost precision when incrementing %" NVff " by 1",
8565                            was);
8566         }
8567         (void)SvNOK_only(sv);
8568         SvNV_set(sv, was + 1.0);
8569         return;
8570     }
8571
8572     if (!(flags & SVp_POK) || !*SvPVX_const(sv)) {
8573         if ((flags & SVTYPEMASK) < SVt_PVIV)
8574             sv_upgrade(sv, ((flags & SVTYPEMASK) > SVt_IV ? SVt_PVIV : SVt_IV));
8575         (void)SvIOK_only(sv);
8576         SvIV_set(sv, 1);
8577         return;
8578     }
8579     d = SvPVX(sv);
8580     while (isALPHA(*d)) d++;
8581     while (isDIGIT(*d)) d++;
8582     if (d < SvEND(sv)) {
8583 #ifdef PERL_PRESERVE_IVUV
8584         /* Got to punt this as an integer if needs be, but we don't issue
8585            warnings. Probably ought to make the sv_iv_please() that does
8586            the conversion if possible, and silently.  */
8587         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), NULL);
8588         if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
8589             /* Need to try really hard to see if it's an integer.
8590                9.22337203685478e+18 is an integer.
8591                but "9.22337203685478e+18" + 0 is UV=9223372036854779904
8592                so $a="9.22337203685478e+18"; $a+0; $a++
8593                needs to be the same as $a="9.22337203685478e+18"; $a++
8594                or we go insane. */
8595         
8596             (void) sv_2iv(sv);
8597             if (SvIOK(sv))
8598                 goto oops_its_int;
8599
8600             /* sv_2iv *should* have made this an NV */
8601             if (flags & SVp_NOK) {
8602                 (void)SvNOK_only(sv);
8603                 SvNV_set(sv, SvNVX(sv) + 1.0);
8604                 return;
8605             }
8606             /* I don't think we can get here. Maybe I should assert this
8607                And if we do get here I suspect that sv_setnv will croak. NWC
8608                Fall through. */
8609 #if defined(USE_LONG_DOUBLE)
8610             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_inc punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"PERL_PRIgldbl"\n",
8611                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
8612 #else
8613             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_inc punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
8614                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
8615 #endif
8616         }
8617 #endif /* PERL_PRESERVE_IVUV */
8618         sv_setnv(sv,Atof(SvPVX_const(sv)) + 1.0);
8619         return;
8620     }
8621     d--;
8622     while (d >= SvPVX_const(sv)) {
8623         if (isDIGIT(*d)) {
8624             if (++*d <= '9')
8625                 return;
8626             *(d--) = '0';
8627         }
8628         else {
8629 #ifdef EBCDIC
8630             /* MKS: The original code here died if letters weren't consecutive.
8631              * at least it didn't have to worry about non-C locales.  The
8632              * new code assumes that ('z'-'a')==('Z'-'A'), letters are
8633              * arranged in order (although not consecutively) and that only
8634              * [A-Za-z] are accepted by isALPHA in the C locale.
8635              */
8636             if (*d != 'z' && *d != 'Z') {
8637                 do { ++*d; } while (!isALPHA(*d));
8638                 return;
8639             }
8640             *(d--) -= 'z' - 'a';
8641 #else
8642             ++*d;
8643             if (isALPHA(*d))
8644                 return;
8645             *(d--) -= 'z' - 'a' + 1;
8646 #endif
8647         }
8648     }
8649     /* oh,oh, the number grew */
8650     SvGROW(sv, SvCUR(sv) + 2);
8651     SvCUR_set(sv, SvCUR(sv) + 1);
8652     for (d = SvPVX(sv) + SvCUR(sv); d > SvPVX_const(sv); d--)
8653         *d = d[-1];
8654     if (isDIGIT(d[1]))
8655         *d = '1';
8656     else
8657         *d = d[1];
8658 }
8659
8660 /*
8661 =for apidoc sv_dec
8662
8663 Auto-decrement of the value in the SV, doing string to numeric conversion
8664 if necessary.  Handles 'get' magic and operator overloading.
8665
8666 =cut
8667 */
8668
8669 void
8670 Perl_sv_dec(pTHX_ SV *const sv)
8671 {
8672     dVAR;
8673     if (!sv)
8674         return;
8675     SvGETMAGIC(sv);
8676     sv_dec_nomg(sv);
8677 }
8678
8679 /*
8680 =for apidoc sv_dec_nomg
8681
8682 Auto-decrement of the value in the SV, doing string to numeric conversion
8683 if necessary.  Handles operator overloading.  Skips handling 'get' magic.
8684
8685 =cut
8686 */
8687
8688 void
8689 Perl_sv_dec_nomg(pTHX_ SV *const sv)
8690 {
8691     dVAR;
8692     int flags;
8693
8694     if (!sv)
8695         return;
8696     if (SvTHINKFIRST(sv)) {
8697         if (SvREADONLY(sv)) {
8698                 Perl_croak_no_modify();
8699         }
8700         if (SvROK(sv)) {
8701             IV i;
8702             if (SvAMAGIC(sv) && AMG_CALLunary(sv, dec_amg))
8703                 return;
8704             i = PTR2IV(SvRV(sv));
8705             sv_unref(sv);
8706             sv_setiv(sv, i);
8707         }
8708         else sv_force_normal_flags(sv, 0);
8709     }
8710     /* Unlike sv_inc we don't have to worry about string-never-numbers
8711        and keeping them magic. But we mustn't warn on punting */
8712     flags = SvFLAGS(sv);
8713     if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
8714         /* It's publicly an integer, or privately an integer-not-float */
8715 #ifdef PERL_PRESERVE_IVUV
8716       oops_its_int:
8717 #endif
8718         if (SvIsUV(sv)) {
8719             if (SvUVX(sv) == 0) {
8720                 (void)SvIOK_only(sv);
8721                 SvIV_set(sv, -1);
8722             }
8723             else {
8724                 (void)SvIOK_only_UV(sv);
8725                 SvUV_set(sv, SvUVX(sv) - 1);
8726             }   
8727         } else {
8728             if (SvIVX(sv) == IV_MIN) {
8729                 sv_setnv(sv, (NV)IV_MIN);
8730                 goto oops_its_num;
8731             }
8732             else {
8733                 (void)SvIOK_only(sv);
8734                 SvIV_set(sv, SvIVX(sv) - 1);
8735             }   
8736         }
8737         return;
8738     }
8739     if (flags & SVp_NOK) {
8740     oops_its_num:
8741         {
8742             const NV was = SvNVX(sv);
8743             if (NV_OVERFLOWS_INTEGERS_AT &&
8744                 was <= -NV_OVERFLOWS_INTEGERS_AT) {
8745                 /* diag_listed_as: Lost precision when %s %f by 1 */
8746                 Perl_ck_warner(aTHX_ packWARN(WARN_IMPRECISION),
8747                                "Lost precision when decrementing %" NVff " by 1",
8748                                was);
8749             }
8750             (void)SvNOK_only(sv);
8751             SvNV_set(sv, was - 1.0);
8752             return;
8753         }
8754     }
8755     if (!(flags & SVp_POK)) {
8756         if ((flags & SVTYPEMASK) < SVt_PVIV)
8757             sv_upgrade(sv, ((flags & SVTYPEMASK) > SVt_IV) ? SVt_PVIV : SVt_IV);
8758         SvIV_set(sv, -1);
8759         (void)SvIOK_only(sv);
8760         return;
8761     }
8762 #ifdef PERL_PRESERVE_IVUV
8763     {
8764         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), NULL);
8765         if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
8766             /* Need to try really hard to see if it's an integer.
8767                9.22337203685478e+18 is an integer.
8768                but "9.22337203685478e+18" + 0 is UV=9223372036854779904
8769                so $a="9.22337203685478e+18"; $a+0; $a--
8770                needs to be the same as $a="9.22337203685478e+18"; $a--
8771                or we go insane. */
8772         
8773             (void) sv_2iv(sv);
8774             if (SvIOK(sv))
8775                 goto oops_its_int;
8776
8777             /* sv_2iv *should* have made this an NV */
8778             if (flags & SVp_NOK) {
8779                 (void)SvNOK_only(sv);
8780                 SvNV_set(sv, SvNVX(sv) - 1.0);
8781                 return;
8782             }
8783             /* I don't think we can get here. Maybe I should assert this
8784                And if we do get here I suspect that sv_setnv will croak. NWC
8785                Fall through. */
8786 #if defined(USE_LONG_DOUBLE)
8787             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_dec punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"PERL_PRIgldbl"\n",
8788                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
8789 #else
8790             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_dec punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
8791                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
8792 #endif
8793         }
8794     }
8795 #endif /* PERL_PRESERVE_IVUV */
8796     sv_setnv(sv,Atof(SvPVX_const(sv)) - 1.0);   /* punt */
8797 }
8798
8799 /* this define is used to eliminate a chunk of duplicated but shared logic
8800  * it has the suffix __SV_C to signal that it isnt API, and isnt meant to be
8801  * used anywhere but here - yves
8802  */
8803 #define PUSH_EXTEND_MORTAL__SV_C(AnSv) \
8804     STMT_START {      \
8805         EXTEND_MORTAL(1); \
8806         PL_tmps_stack[++PL_tmps_ix] = (AnSv); \
8807     } STMT_END
8808
8809 /*
8810 =for apidoc sv_mortalcopy
8811
8812 Creates a new SV which is a copy of the original SV (using C<sv_setsv>).
8813 The new SV is marked as mortal.  It will be destroyed "soon", either by an
8814 explicit call to FREETMPS, or by an implicit call at places such as
8815 statement boundaries.  See also C<sv_newmortal> and C<sv_2mortal>.
8816
8817 =cut
8818 */
8819
8820 /* Make a string that will exist for the duration of the expression
8821  * evaluation.  Actually, it may have to last longer than that, but
8822  * hopefully we won't free it until it has been assigned to a
8823  * permanent location. */
8824
8825 SV *
8826 Perl_sv_mortalcopy_flags(pTHX_ SV *const oldstr, U32 flags)
8827 {
8828     dVAR;
8829     SV *sv;
8830
8831     if (flags & SV_GMAGIC)
8832         SvGETMAGIC(oldstr); /* before new_SV, in case it dies */
8833     new_SV(sv);
8834     sv_setsv_flags(sv,oldstr,flags & ~SV_GMAGIC);
8835     PUSH_EXTEND_MORTAL__SV_C(sv);
8836     SvTEMP_on(sv);
8837     return sv;
8838 }
8839
8840 /*
8841 =for apidoc sv_newmortal
8842
8843 Creates a new null SV which is mortal.  The reference count of the SV is
8844 set to 1.  It will be destroyed "soon", either by an explicit call to
8845 FREETMPS, or by an implicit call at places such as statement boundaries.
8846 See also C<sv_mortalcopy> and C<sv_2mortal>.
8847
8848 =cut
8849 */
8850
8851 SV *
8852 Perl_sv_newmortal(pTHX)
8853 {
8854     dVAR;
8855     SV *sv;
8856
8857     new_SV(sv);
8858     SvFLAGS(sv) = SVs_TEMP;
8859     PUSH_EXTEND_MORTAL__SV_C(sv);
8860     return sv;
8861 }
8862
8863
8864 /*
8865 =for apidoc newSVpvn_flags
8866
8867 Creates a new SV and copies a string into it.  The reference count for the
8868 SV is set to 1.  Note that if C<len> is zero, Perl will create a zero length
8869 string.  You are responsible for ensuring that the source string is at least
8870 C<len> bytes long.  If the C<s> argument is NULL the new SV will be undefined.
8871 Currently the only flag bits accepted are C<SVf_UTF8> and C<SVs_TEMP>.
8872 If C<SVs_TEMP> is set, then C<sv_2mortal()> is called on the result before
8873 returning.  If C<SVf_UTF8> is set, C<s>
8874 is considered to be in UTF-8 and the
8875 C<SVf_UTF8> flag will be set on the new SV.
8876 C<newSVpvn_utf8()> is a convenience wrapper for this function, defined as
8877
8878     #define newSVpvn_utf8(s, len, u)                    \
8879         newSVpvn_flags((s), (len), (u) ? SVf_UTF8 : 0)
8880
8881 =cut
8882 */
8883
8884 SV *
8885 Perl_newSVpvn_flags(pTHX_ const char *const s, const STRLEN len, const U32 flags)
8886 {
8887     dVAR;
8888     SV *sv;
8889
8890     /* All the flags we don't support must be zero.
8891        And we're new code so I'm going to assert this from the start.  */
8892     assert(!(flags & ~(SVf_UTF8|SVs_TEMP)));
8893     new_SV(sv);
8894     sv_setpvn(sv,s,len);
8895
8896     /* This code used to do a sv_2mortal(), however we now unroll the call to
8897      * sv_2mortal() and do what it does ourselves here.  Since we have asserted
8898      * that flags can only have the SVf_UTF8 and/or SVs_TEMP flags set above we
8899      * can use it to enable the sv flags directly (bypassing SvTEMP_on), which
8900      * in turn means we dont need to mask out the SVf_UTF8 flag below, which
8901      * means that we eliminate quite a few steps than it looks - Yves
8902      * (explaining patch by gfx) */
8903
8904     SvFLAGS(sv) |= flags;
8905
8906     if(flags & SVs_TEMP){
8907         PUSH_EXTEND_MORTAL__SV_C(sv);
8908     }
8909
8910     return sv;
8911 }
8912
8913 /*
8914 =for apidoc sv_2mortal
8915
8916 Marks an existing SV as mortal.  The SV will be destroyed "soon", either
8917 by an explicit call to FREETMPS, or by an implicit call at places such as
8918 statement boundaries.  SvTEMP() is turned on which means that the SV's
8919 string buffer can be "stolen" if this SV is copied.  See also C<sv_newmortal>
8920 and C<sv_mortalcopy>.
8921
8922 =cut
8923 */
8924
8925 SV *
8926 Perl_sv_2mortal(pTHX_ SV *const sv)
8927 {
8928     dVAR;
8929     if (!sv)
8930         return NULL;
8931     if (SvIMMORTAL(sv))
8932         return sv;
8933     PUSH_EXTEND_MORTAL__SV_C(sv);
8934     SvTEMP_on(sv);
8935     return sv;
8936 }
8937
8938 /*
8939 =for apidoc newSVpv
8940
8941 Creates a new SV and copies a string into it.  The reference count for the
8942 SV is set to 1.  If C<len> is zero, Perl will compute the length using
8943 strlen().  For efficiency, consider using C<newSVpvn> instead.
8944
8945 =cut
8946 */
8947
8948 SV *
8949 Perl_newSVpv(pTHX_ const char *const s, const STRLEN len)
8950 {
8951     dVAR;
8952     SV *sv;
8953
8954     new_SV(sv);
8955     sv_setpvn(sv, s, len || s == NULL ? len : strlen(s));
8956     return sv;
8957 }
8958
8959 /*
8960 =for apidoc newSVpvn
8961
8962 Creates a new SV and copies a buffer into it, which may contain NUL characters
8963 (C<\0>) and other binary data.  The reference count for the SV is set to 1.
8964 Note that if C<len> is zero, Perl will create a zero length (Perl) string.  You
8965 are responsible for ensuring that the source buffer is at least
8966 C<len> bytes long.  If the C<buffer> argument is NULL the new SV will be
8967 undefined.
8968
8969 =cut
8970 */
8971
8972 SV *
8973 Perl_newSVpvn(pTHX_ const char *const buffer, const STRLEN len)
8974 {
8975     dVAR;
8976     SV *sv;
8977
8978     new_SV(sv);
8979     sv_setpvn(sv,buffer,len);
8980     return sv;
8981 }
8982
8983 /*
8984 =for apidoc newSVhek
8985
8986 Creates a new SV from the hash key structure.  It will generate scalars that
8987 point to the shared string table where possible.  Returns a new (undefined)
8988 SV if the hek is NULL.
8989
8990 =cut
8991 */
8992
8993 SV *
8994 Perl_newSVhek(pTHX_ const HEK *const hek)
8995 {
8996     dVAR;
8997     if (!hek) {
8998         SV *sv;
8999
9000         new_SV(sv);
9001         return sv;
9002     }
9003
9004     if (HEK_LEN(hek) == HEf_SVKEY) {
9005         return newSVsv(*(SV**)HEK_KEY(hek));
9006     } else {
9007         const int flags = HEK_FLAGS(hek);
9008         if (flags & HVhek_WASUTF8) {
9009             /* Trouble :-)
9010                Andreas would like keys he put in as utf8 to come back as utf8
9011             */
9012             STRLEN utf8_len = HEK_LEN(hek);
9013             SV * const sv = newSV_type(SVt_PV);
9014             char *as_utf8 = (char *)bytes_to_utf8 ((U8*)HEK_KEY(hek), &utf8_len);
9015             /* bytes_to_utf8() allocates a new string, which we can repurpose: */
9016             sv_usepvn_flags(sv, as_utf8, utf8_len, SV_HAS_TRAILING_NUL);
9017             SvUTF8_on (sv);
9018             return sv;
9019         } else if (flags & HVhek_UNSHARED) {
9020             /* A hash that isn't using shared hash keys has to have
9021                the flag in every key so that we know not to try to call
9022                share_hek_hek on it.  */
9023
9024             SV * const sv = newSVpvn (HEK_KEY(hek), HEK_LEN(hek));
9025             if (HEK_UTF8(hek))
9026                 SvUTF8_on (sv);
9027             return sv;
9028         }
9029         /* This will be overwhelminly the most common case.  */
9030         {
9031             /* Inline most of newSVpvn_share(), because share_hek_hek() is far
9032                more efficient than sharepvn().  */
9033             SV *sv;
9034
9035             new_SV(sv);
9036             sv_upgrade(sv, SVt_PV);
9037             SvPV_set(sv, (char *)HEK_KEY(share_hek_hek(hek)));
9038             SvCUR_set(sv, HEK_LEN(hek));
9039             SvLEN_set(sv, 0);
9040             SvIsCOW_on(sv);
9041             SvPOK_on(sv);
9042             if (HEK_UTF8(hek))
9043                 SvUTF8_on(sv);
9044             return sv;
9045         }
9046     }
9047 }
9048
9049 /*
9050 =for apidoc newSVpvn_share
9051
9052 Creates a new SV with its SvPVX_const pointing to a shared string in the string
9053 table.  If the string does not already exist in the table, it is
9054 created first.  Turns on the SvIsCOW flag (or READONLY
9055 and FAKE in 5.16 and earlier).  If the C<hash> parameter
9056 is non-zero, that value is used; otherwise the hash is computed.
9057 The string's hash can later be retrieved from the SV
9058 with the C<SvSHARED_HASH()> macro.  The idea here is
9059 that as the string table is used for shared hash keys these strings will have
9060 SvPVX_const == HeKEY and hash lookup will avoid string compare.
9061
9062 =cut
9063 */
9064
9065 SV *
9066 Perl_newSVpvn_share(pTHX_ const char *src, I32 len, U32 hash)
9067 {
9068     dVAR;
9069     SV *sv;
9070     bool is_utf8 = FALSE;
9071     const char *const orig_src = src;
9072
9073     if (len < 0) {
9074         STRLEN tmplen = -len;
9075         is_utf8 = TRUE;
9076         /* See the note in hv.c:hv_fetch() --jhi */
9077         src = (char*)bytes_from_utf8((const U8*)src, &tmplen, &is_utf8);
9078         len = tmplen;
9079     }
9080     if (!hash)
9081         PERL_HASH(hash, src, len);
9082     new_SV(sv);
9083     /* The logic for this is inlined in S_mro_get_linear_isa_dfs(), so if it
9084        changes here, update it there too.  */
9085     sv_upgrade(sv, SVt_PV);
9086     SvPV_set(sv, sharepvn(src, is_utf8?-len:len, hash));
9087     SvCUR_set(sv, len);
9088     SvLEN_set(sv, 0);
9089     SvIsCOW_on(sv);
9090     SvPOK_on(sv);
9091     if (is_utf8)
9092         SvUTF8_on(sv);
9093     if (src != orig_src)
9094         Safefree(src);
9095     return sv;
9096 }
9097
9098 /*
9099 =for apidoc newSVpv_share
9100
9101 Like C<newSVpvn_share>, but takes a nul-terminated string instead of a
9102 string/length pair.
9103
9104 =cut
9105 */
9106
9107 SV *
9108 Perl_newSVpv_share(pTHX_ const char *src, U32 hash)
9109 {
9110     return newSVpvn_share(src, strlen(src), hash);
9111 }
9112
9113 #if defined(PERL_IMPLICIT_CONTEXT)
9114
9115 /* pTHX_ magic can't cope with varargs, so this is a no-context
9116  * version of the main function, (which may itself be aliased to us).
9117  * Don't access this version directly.
9118  */
9119
9120 SV *
9121 Perl_newSVpvf_nocontext(const char *const pat, ...)
9122 {
9123     dTHX;
9124     SV *sv;
9125     va_list args;
9126
9127     PERL_ARGS_ASSERT_NEWSVPVF_NOCONTEXT;
9128
9129     va_start(args, pat);
9130     sv = vnewSVpvf(pat, &args);
9131     va_end(args);
9132     return sv;
9133 }
9134 #endif
9135
9136 /*
9137 =for apidoc newSVpvf
9138
9139 Creates a new SV and initializes it with the string formatted like
9140 C<sprintf>.
9141
9142 =cut
9143 */
9144
9145 SV *
9146 Perl_newSVpvf(pTHX_ const char *const pat, ...)
9147 {
9148     SV *sv;
9149     va_list args;
9150
9151     PERL_ARGS_ASSERT_NEWSVPVF;
9152
9153     va_start(args, pat);
9154     sv = vnewSVpvf(pat, &args);
9155     va_end(args);
9156     return sv;
9157 }
9158
9159 /* backend for newSVpvf() and newSVpvf_nocontext() */
9160
9161 SV *
9162 Perl_vnewSVpvf(pTHX_ const char *const pat, va_list *const args)
9163 {
9164     dVAR;
9165     SV *sv;
9166
9167     PERL_ARGS_ASSERT_VNEWSVPVF;
9168
9169     new_SV(sv);
9170     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
9171     return sv;
9172 }
9173
9174 /*
9175 =for apidoc newSVnv
9176
9177 Creates a new SV and copies a floating point value into it.
9178 The reference count for the SV is set to 1.
9179
9180 =cut
9181 */
9182
9183 SV *
9184 Perl_newSVnv(pTHX_ const NV n)
9185 {
9186     dVAR;
9187     SV *sv;
9188
9189     new_SV(sv);
9190     sv_setnv(sv,n);
9191     return sv;
9192 }
9193
9194 /*
9195 =for apidoc newSViv
9196
9197 Creates a new SV and copies an integer into it.  The reference count for the
9198 SV is set to 1.
9199
9200 =cut
9201 */
9202
9203 SV *
9204 Perl_newSViv(pTHX_ const IV i)
9205 {
9206     dVAR;
9207     SV *sv;
9208
9209     new_SV(sv);
9210     sv_setiv(sv,i);
9211     return sv;
9212 }
9213
9214 /*
9215 =for apidoc newSVuv
9216
9217 Creates a new SV and copies an unsigned integer into it.
9218 The reference count for the SV is set to 1.
9219
9220 =cut
9221 */
9222
9223 SV *
9224 Perl_newSVuv(pTHX_ const UV u)
9225 {
9226     dVAR;
9227     SV *sv;
9228
9229     new_SV(sv);
9230     sv_setuv(sv,u);
9231     return sv;
9232 }
9233
9234 /*
9235 =for apidoc newSV_type
9236
9237 Creates a new SV, of the type specified.  The reference count for the new SV
9238 is set to 1.
9239
9240 =cut
9241 */
9242
9243 SV *
9244 Perl_newSV_type(pTHX_ const svtype type)
9245 {
9246     SV *sv;
9247
9248     new_SV(sv);
9249     sv_upgrade(sv, type);
9250     return sv;
9251 }
9252
9253 /*
9254 =for apidoc newRV_noinc
9255
9256 Creates an RV wrapper for an SV.  The reference count for the original
9257 SV is B<not> incremented.
9258
9259 =cut
9260 */
9261
9262 SV *
9263 Perl_newRV_noinc(pTHX_ SV *const tmpRef)
9264 {
9265     dVAR;
9266     SV *sv = newSV_type(SVt_IV);
9267
9268     PERL_ARGS_ASSERT_NEWRV_NOINC;
9269
9270     SvTEMP_off(tmpRef);
9271     SvRV_set(sv, tmpRef);
9272     SvROK_on(sv);
9273     return sv;
9274 }
9275
9276 /* newRV_inc is the official function name to use now.
9277  * newRV_inc is in fact #defined to newRV in sv.h
9278  */
9279
9280 SV *
9281 Perl_newRV(pTHX_ SV *const sv)
9282 {
9283     dVAR;
9284
9285     PERL_ARGS_ASSERT_NEWRV;
9286
9287     return newRV_noinc(SvREFCNT_inc_simple_NN(sv));
9288 }
9289
9290 /*
9291 =for apidoc newSVsv
9292
9293 Creates a new SV which is an exact duplicate of the original SV.
9294 (Uses C<sv_setsv>.)
9295
9296 =cut
9297 */
9298
9299 SV *
9300 Perl_newSVsv(pTHX_ SV *const old)
9301 {
9302     dVAR;
9303     SV *sv;
9304
9305     if (!old)
9306         return NULL;
9307     if (SvTYPE(old) == (svtype)SVTYPEMASK) {
9308         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "semi-panic: attempt to dup freed string");
9309         return NULL;
9310     }
9311     /* Do this here, otherwise we leak the new SV if this croaks. */
9312     SvGETMAGIC(old);
9313     new_SV(sv);
9314     /* SV_NOSTEAL prevents TEMP buffers being, well, stolen, and saves games
9315        with SvTEMP_off and SvTEMP_on round a call to sv_setsv.  */
9316     sv_setsv_flags(sv, old, SV_NOSTEAL);
9317     return sv;
9318 }
9319
9320 /*
9321 =for apidoc sv_reset
9322
9323 Underlying implementation for the C<reset> Perl function.
9324 Note that the perl-level function is vaguely deprecated.
9325
9326 =cut
9327 */
9328
9329 void
9330 Perl_sv_reset(pTHX_ const char *s, HV *const stash)
9331 {
9332     PERL_ARGS_ASSERT_SV_RESET;
9333
9334     sv_resetpvn(*s ? s : NULL, strlen(s), stash);
9335 }
9336
9337 void
9338 Perl_sv_resetpvn(pTHX_ const char *s, STRLEN len, HV * const stash)
9339 {
9340     dVAR;
9341     char todo[PERL_UCHAR_MAX+1];
9342     const char *send;
9343
9344     if (!stash || SvTYPE(stash) != SVt_PVHV)
9345         return;
9346
9347     if (!s) {           /* reset ?? searches */
9348         MAGIC * const mg = mg_find((const SV *)stash, PERL_MAGIC_symtab);
9349         if (mg) {
9350             const U32 count = mg->mg_len / sizeof(PMOP**);
9351             PMOP **pmp = (PMOP**) mg->mg_ptr;
9352             PMOP *const *const end = pmp + count;
9353
9354             while (pmp < end) {
9355 #ifdef USE_ITHREADS
9356                 SvREADONLY_off(PL_regex_pad[(*pmp)->op_pmoffset]);
9357 #else
9358                 (*pmp)->op_pmflags &= ~PMf_USED;
9359 #endif
9360                 ++pmp;
9361             }
9362         }
9363         return;
9364     }
9365
9366     /* reset variables */
9367
9368     if (!HvARRAY(stash))
9369         return;
9370
9371     Zero(todo, 256, char);
9372     send = s + len;
9373     while (s < send) {
9374         I32 max;
9375         I32 i = (unsigned char)*s;
9376         if (s[1] == '-') {
9377             s += 2;
9378         }
9379         max = (unsigned char)*s++;
9380         for ( ; i <= max; i++) {
9381             todo[i] = 1;
9382         }
9383         for (i = 0; i <= (I32) HvMAX(stash); i++) {
9384             HE *entry;
9385             for (entry = HvARRAY(stash)[i];
9386                  entry;
9387                  entry = HeNEXT(entry))
9388             {
9389                 GV *gv;
9390                 SV *sv;
9391
9392                 if (!todo[(U8)*HeKEY(entry)])
9393                     continue;
9394                 gv = MUTABLE_GV(HeVAL(entry));
9395                 sv = GvSV(gv);
9396                 if (sv && !SvREADONLY(sv)) {
9397                     SV_CHECK_THINKFIRST_COW_DROP(sv);
9398                     if (!isGV(sv)) SvOK_off(sv);
9399                 }
9400                 if (GvAV(gv)) {
9401                     av_clear(GvAV(gv));
9402                 }
9403                 if (GvHV(gv) && !HvNAME_get(GvHV(gv))) {
9404                     hv_clear(GvHV(gv));
9405                 }
9406             }
9407         }
9408     }
9409 }
9410
9411 /*
9412 =for apidoc sv_2io
9413
9414 Using various gambits, try to get an IO from an SV: the IO slot if its a
9415 GV; or the recursive result if we're an RV; or the IO slot of the symbol
9416 named after the PV if we're a string.
9417
9418 'Get' magic is ignored on the sv passed in, but will be called on
9419 C<SvRV(sv)> if sv is an RV.
9420
9421 =cut
9422 */
9423
9424 IO*
9425 Perl_sv_2io(pTHX_ SV *const sv)
9426 {
9427     IO* io;
9428     GV* gv;
9429
9430     PERL_ARGS_ASSERT_SV_2IO;
9431
9432     switch (SvTYPE(sv)) {
9433     case SVt_PVIO:
9434         io = MUTABLE_IO(sv);
9435         break;
9436     case SVt_PVGV:
9437     case SVt_PVLV:
9438         if (isGV_with_GP(sv)) {
9439             gv = MUTABLE_GV(sv);
9440             io = GvIO(gv);
9441             if (!io)
9442                 Perl_croak(aTHX_ "Bad filehandle: %"HEKf,
9443                                     HEKfARG(GvNAME_HEK(gv)));
9444             break;
9445         }
9446         /* FALLTHROUGH */
9447     default:
9448         if (!SvOK(sv))
9449             Perl_croak(aTHX_ PL_no_usym, "filehandle");
9450         if (SvROK(sv)) {
9451             SvGETMAGIC(SvRV(sv));
9452             return sv_2io(SvRV(sv));
9453         }
9454         gv = gv_fetchsv_nomg(sv, 0, SVt_PVIO);
9455         if (gv)
9456             io = GvIO(gv);
9457         else
9458             io = 0;
9459         if (!io) {
9460             SV *newsv = sv;
9461             if (SvGMAGICAL(sv)) {
9462                 newsv = sv_newmortal();
9463                 sv_setsv_nomg(newsv, sv);
9464             }
9465             Perl_croak(aTHX_ "Bad filehandle: %"SVf, SVfARG(newsv));
9466         }
9467         break;
9468     }
9469     return io;
9470 }
9471
9472 /*
9473 =for apidoc sv_2cv
9474
9475 Using various gambits, try to get a CV from an SV; in addition, try if
9476 possible to set C<*st> and C<*gvp> to the stash and GV associated with it.
9477 The flags in C<lref> are passed to gv_fetchsv.
9478
9479 =cut
9480 */
9481
9482 CV *
9483 Perl_sv_2cv(pTHX_ SV *sv, HV **const st, GV **const gvp, const I32 lref)
9484 {
9485     dVAR;
9486     GV *gv = NULL;
9487     CV *cv = NULL;
9488
9489     PERL_ARGS_ASSERT_SV_2CV;
9490
9491     if (!sv) {
9492         *st = NULL;
9493         *gvp = NULL;
9494         return NULL;
9495     }
9496     switch (SvTYPE(sv)) {
9497     case SVt_PVCV:
9498         *st = CvSTASH(sv);
9499         *gvp = NULL;
9500         return MUTABLE_CV(sv);
9501     case SVt_PVHV:
9502     case SVt_PVAV:
9503         *st = NULL;
9504         *gvp = NULL;
9505         return NULL;
9506     default:
9507         SvGETMAGIC(sv);
9508         if (SvROK(sv)) {
9509             if (SvAMAGIC(sv))
9510                 sv = amagic_deref_call(sv, to_cv_amg);
9511
9512             sv = SvRV(sv);
9513             if (SvTYPE(sv) == SVt_PVCV) {
9514                 cv = MUTABLE_CV(sv);
9515                 *gvp = NULL;
9516                 *st = CvSTASH(cv);
9517                 return cv;
9518             }
9519             else if(SvGETMAGIC(sv), isGV_with_GP(sv))
9520                 gv = MUTABLE_GV(sv);
9521             else
9522                 Perl_croak(aTHX_ "Not a subroutine reference");
9523         }
9524         else if (isGV_with_GP(sv)) {
9525             gv = MUTABLE_GV(sv);
9526         }
9527         else {
9528             gv = gv_fetchsv_nomg(sv, lref, SVt_PVCV);
9529         }
9530         *gvp = gv;
9531         if (!gv) {
9532             *st = NULL;
9533             return NULL;
9534         }
9535         /* Some flags to gv_fetchsv mean don't really create the GV  */
9536         if (!isGV_with_GP(gv)) {
9537             *st = NULL;
9538             return NULL;
9539         }
9540         *st = GvESTASH(gv);
9541         if (lref & ~GV_ADDMG && !GvCVu(gv)) {
9542             /* XXX this is probably not what they think they're getting.
9543              * It has the same effect as "sub name;", i.e. just a forward
9544              * declaration! */
9545             newSTUB(gv,0);
9546         }
9547         return GvCVu(gv);
9548     }
9549 }
9550
9551 /*
9552 =for apidoc sv_true
9553
9554 Returns true if the SV has a true value by Perl's rules.
9555 Use the C<SvTRUE> macro instead, which may call C<sv_true()> or may
9556 instead use an in-line version.
9557
9558 =cut
9559 */
9560
9561 I32
9562 Perl_sv_true(pTHX_ SV *const sv)
9563 {
9564     if (!sv)
9565         return 0;
9566     if (SvPOK(sv)) {
9567         const XPV* const tXpv = (XPV*)SvANY(sv);
9568         if (tXpv &&
9569                 (tXpv->xpv_cur > 1 ||
9570                 (tXpv->xpv_cur && *sv->sv_u.svu_pv != '0')))
9571             return 1;
9572         else
9573             return 0;
9574     }
9575     else {
9576         if (SvIOK(sv))
9577             return SvIVX(sv) != 0;
9578         else {
9579             if (SvNOK(sv))
9580                 return SvNVX(sv) != 0.0;
9581             else
9582                 return sv_2bool(sv);
9583         }
9584     }
9585 }
9586
9587 /*
9588 =for apidoc sv_pvn_force
9589
9590 Get a sensible string out of the SV somehow.
9591 A private implementation of the C<SvPV_force> macro for compilers which
9592 can't cope with complex macro expressions.  Always use the macro instead.
9593
9594 =for apidoc sv_pvn_force_flags
9595
9596 Get a sensible string out of the SV somehow.
9597 If C<flags> has C<SV_GMAGIC> bit set, will C<mg_get> on C<sv> if
9598 appropriate, else not.  C<sv_pvn_force> and C<sv_pvn_force_nomg> are
9599 implemented in terms of this function.
9600 You normally want to use the various wrapper macros instead: see
9601 C<SvPV_force> and C<SvPV_force_nomg>
9602
9603 =cut
9604 */
9605
9606 char *
9607 Perl_sv_pvn_force_flags(pTHX_ SV *const sv, STRLEN *const lp, const I32 flags)
9608 {
9609     dVAR;
9610
9611     PERL_ARGS_ASSERT_SV_PVN_FORCE_FLAGS;
9612
9613     if (flags & SV_GMAGIC) SvGETMAGIC(sv);
9614     if (SvTHINKFIRST(sv) && (!SvROK(sv) || SvREADONLY(sv)))
9615         sv_force_normal_flags(sv, 0);
9616
9617     if (SvPOK(sv)) {
9618         if (lp)
9619             *lp = SvCUR(sv);
9620     }
9621     else {
9622         char *s;
9623         STRLEN len;
9624  
9625         if (SvTYPE(sv) > SVt_PVLV
9626             || isGV_with_GP(sv))
9627             /* diag_listed_as: Can't coerce %s to %s in %s */
9628             Perl_croak(aTHX_ "Can't coerce %s to string in %s", sv_reftype(sv,0),
9629                 OP_DESC(PL_op));
9630         s = sv_2pv_flags(sv, &len, flags &~ SV_GMAGIC);
9631         if (!s) {
9632           s = (char *)"";
9633         }
9634         if (lp)
9635             *lp = len;
9636
9637         if (SvTYPE(sv) < SVt_PV ||
9638             s != SvPVX_const(sv)) {     /* Almost, but not quite, sv_setpvn() */
9639             if (SvROK(sv))
9640                 sv_unref(sv);
9641             SvUPGRADE(sv, SVt_PV);              /* Never FALSE */
9642             SvGROW(sv, len + 1);
9643             Move(s,SvPVX(sv),len,char);
9644             SvCUR_set(sv, len);
9645             SvPVX(sv)[len] = '\0';
9646         }
9647         if (!SvPOK(sv)) {
9648             SvPOK_on(sv);               /* validate pointer */
9649             SvTAINT(sv);
9650             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
9651                                   PTR2UV(sv),SvPVX_const(sv)));
9652         }
9653     }
9654     (void)SvPOK_only_UTF8(sv);
9655     return SvPVX_mutable(sv);
9656 }
9657
9658 /*
9659 =for apidoc sv_pvbyten_force
9660
9661 The backend for the C<SvPVbytex_force> macro.  Always use the macro
9662 instead.
9663
9664 =cut
9665 */
9666
9667 char *
9668 Perl_sv_pvbyten_force(pTHX_ SV *const sv, STRLEN *const lp)
9669 {
9670     PERL_ARGS_ASSERT_SV_PVBYTEN_FORCE;
9671
9672     sv_pvn_force(sv,lp);
9673     sv_utf8_downgrade(sv,0);
9674     *lp = SvCUR(sv);
9675     return SvPVX(sv);
9676 }
9677
9678 /*
9679 =for apidoc sv_pvutf8n_force
9680
9681 The backend for the C<SvPVutf8x_force> macro.  Always use the macro
9682 instead.
9683
9684 =cut
9685 */
9686
9687 char *
9688 Perl_sv_pvutf8n_force(pTHX_ SV *const sv, STRLEN *const lp)
9689 {
9690     PERL_ARGS_ASSERT_SV_PVUTF8N_FORCE;
9691
9692     sv_pvn_force(sv,0);
9693     sv_utf8_upgrade_nomg(sv);
9694     *lp = SvCUR(sv);
9695     return SvPVX(sv);
9696 }
9697
9698 /*
9699 =for apidoc sv_reftype
9700
9701 Returns a string describing what the SV is a reference to.
9702
9703 =cut
9704 */
9705
9706 const char *
9707 Perl_sv_reftype(pTHX_ const SV *const sv, const int ob)
9708 {
9709     PERL_ARGS_ASSERT_SV_REFTYPE;
9710     if (ob && SvOBJECT(sv)) {
9711         return SvPV_nolen_const(sv_ref(NULL, sv, ob));
9712     }
9713     else {
9714         /* WARNING - There is code, for instance in mg.c, that assumes that
9715          * the only reason that sv_reftype(sv,0) would return a string starting
9716          * with 'L' or 'S' is that it is a LVALUE or a SCALAR.
9717          * Yes this a dodgy way to do type checking, but it saves practically reimplementing
9718          * this routine inside other subs, and it saves time.
9719          * Do not change this assumption without searching for "dodgy type check" in
9720          * the code.
9721          * - Yves */
9722         switch (SvTYPE(sv)) {
9723         case SVt_NULL:
9724         case SVt_IV:
9725         case SVt_NV:
9726         case SVt_PV:
9727         case SVt_PVIV:
9728         case SVt_PVNV:
9729         case SVt_PVMG:
9730                                 if (SvVOK(sv))
9731                                     return "VSTRING";
9732                                 if (SvROK(sv))
9733                                     return "REF";
9734                                 else
9735                                     return "SCALAR";
9736
9737         case SVt_PVLV:          return (char *)  (SvROK(sv) ? "REF"
9738                                 /* tied lvalues should appear to be
9739                                  * scalars for backwards compatibility */
9740                                 : (LvTYPE(sv) == 't' || LvTYPE(sv) == 'T')
9741                                     ? "SCALAR" : "LVALUE");
9742         case SVt_PVAV:          return "ARRAY";
9743         case SVt_PVHV:          return "HASH";
9744         case SVt_PVCV:          return "CODE";
9745         case SVt_PVGV:          return (char *) (isGV_with_GP(sv)
9746                                     ? "GLOB" : "SCALAR");
9747         case SVt_PVFM:          return "FORMAT";
9748         case SVt_PVIO:          return "IO";
9749         case SVt_INVLIST:       return "INVLIST";
9750         case SVt_REGEXP:        return "REGEXP";
9751         default:                return "UNKNOWN";
9752         }
9753     }
9754 }
9755
9756 /*
9757 =for apidoc sv_ref
9758
9759 Returns a SV describing what the SV passed in is a reference to.
9760
9761 =cut
9762 */
9763
9764 SV *
9765 Perl_sv_ref(pTHX_ SV *dst, const SV *const sv, const int ob)
9766 {
9767     PERL_ARGS_ASSERT_SV_REF;
9768
9769     if (!dst)
9770         dst = sv_newmortal();
9771
9772     if (ob && SvOBJECT(sv)) {
9773         HvNAME_get(SvSTASH(sv))
9774                     ? sv_sethek(dst, HvNAME_HEK(SvSTASH(sv)))
9775                     : sv_setpvn(dst, "__ANON__", 8);
9776     }
9777     else {
9778         const char * reftype = sv_reftype(sv, 0);
9779         sv_setpv(dst, reftype);
9780     }
9781     return dst;
9782 }
9783
9784 /*
9785 =for apidoc sv_isobject
9786
9787 Returns a boolean indicating whether the SV is an RV pointing to a blessed
9788 object.  If the SV is not an RV, or if the object is not blessed, then this
9789 will return false.
9790
9791 =cut
9792 */
9793
9794 int
9795 Perl_sv_isobject(pTHX_ SV *sv)
9796 {
9797     if (!sv)
9798         return 0;
9799     SvGETMAGIC(sv);
9800     if (!SvROK(sv))
9801         return 0;
9802     sv = SvRV(sv);
9803     if (!SvOBJECT(sv))
9804         return 0;
9805     return 1;
9806 }
9807
9808 /*
9809 =for apidoc sv_isa
9810
9811 Returns a boolean indicating whether the SV is blessed into the specified
9812 class.  This does not check for subtypes; use C<sv_derived_from> to verify
9813 an inheritance relationship.
9814
9815 =cut
9816 */
9817
9818 int
9819 Perl_sv_isa(pTHX_ SV *sv, const char *const name)
9820 {
9821     const char *hvname;
9822
9823     PERL_ARGS_ASSERT_SV_ISA;
9824
9825     if (!sv)
9826         return 0;
9827     SvGETMAGIC(sv);
9828     if (!SvROK(sv))
9829         return 0;
9830     sv = SvRV(sv);
9831     if (!SvOBJECT(sv))
9832         return 0;
9833     hvname = HvNAME_get(SvSTASH(sv));
9834     if (!hvname)
9835         return 0;
9836
9837     return strEQ(hvname, name);
9838 }
9839
9840 /*
9841 =for apidoc newSVrv
9842
9843 Creates a new SV for the existing RV, C<rv>, to point to.  If C<rv> is not an
9844 RV then it will be upgraded to one.  If C<classname> is non-null then the new
9845 SV will be blessed in the specified package.  The new SV is returned and its
9846 reference count is 1.  The reference count 1 is owned by C<rv>.
9847
9848 =cut
9849 */
9850
9851 SV*
9852 Perl_newSVrv(pTHX_ SV *const rv, const char *const classname)
9853 {
9854     dVAR;
9855     SV *sv;
9856
9857     PERL_ARGS_ASSERT_NEWSVRV;
9858
9859     new_SV(sv);
9860
9861     SV_CHECK_THINKFIRST_COW_DROP(rv);
9862
9863     if (SvTYPE(rv) >= SVt_PVMG) {
9864         const U32 refcnt = SvREFCNT(rv);
9865         SvREFCNT(rv) = 0;
9866         sv_clear(rv);
9867         SvFLAGS(rv) = 0;
9868         SvREFCNT(rv) = refcnt;
9869
9870         sv_upgrade(rv, SVt_IV);
9871     } else if (SvROK(rv)) {
9872         SvREFCNT_dec(SvRV(rv));
9873     } else {
9874         prepare_SV_for_RV(rv);
9875     }
9876
9877     SvOK_off(rv);
9878     SvRV_set(rv, sv);
9879     SvROK_on(rv);
9880
9881     if (classname) {
9882         HV* const stash = gv_stashpv(classname, GV_ADD);
9883         (void)sv_bless(rv, stash);
9884     }
9885     return sv;
9886 }
9887
9888 SV *
9889 Perl_newSVavdefelem(pTHX_ AV *av, SSize_t ix, bool extendible)
9890 {
9891     SV * const lv = newSV_type(SVt_PVLV);
9892     PERL_ARGS_ASSERT_NEWSVAVDEFELEM;
9893     LvTYPE(lv) = 'y';
9894     sv_magic(lv, NULL, PERL_MAGIC_defelem, NULL, 0);
9895     LvTARG(lv) = SvREFCNT_inc_simple_NN(av);
9896     LvSTARGOFF(lv) = ix;
9897     LvTARGLEN(lv) = extendible ? 1 : (STRLEN)UV_MAX;
9898     return lv;
9899 }
9900
9901 /*
9902 =for apidoc sv_setref_pv
9903
9904 Copies a pointer into a new SV, optionally blessing the SV.  The C<rv>
9905 argument will be upgraded to an RV.  That RV will be modified to point to
9906 the new SV.  If the C<pv> argument is NULL then C<PL_sv_undef> will be placed
9907 into the SV.  The C<classname> argument indicates the package for the
9908 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
9909 will have a reference count of 1, and the RV will be returned.
9910
9911 Do not use with other Perl types such as HV, AV, SV, CV, because those
9912 objects will become corrupted by the pointer copy process.
9913
9914 Note that C<sv_setref_pvn> copies the string while this copies the pointer.
9915
9916 =cut
9917 */
9918
9919 SV*
9920 Perl_sv_setref_pv(pTHX_ SV *const rv, const char *const classname, void *const pv)
9921 {
9922     dVAR;
9923
9924     PERL_ARGS_ASSERT_SV_SETREF_PV;
9925
9926     if (!pv) {
9927         sv_setsv(rv, &PL_sv_undef);
9928         SvSETMAGIC(rv);
9929     }
9930     else
9931         sv_setiv(newSVrv(rv,classname), PTR2IV(pv));
9932     return rv;
9933 }
9934
9935 /*
9936 =for apidoc sv_setref_iv
9937
9938 Copies an integer into a new SV, optionally blessing the SV.  The C<rv>
9939 argument will be upgraded to an RV.  That RV will be modified to point to
9940 the new SV.  The C<classname> argument indicates the package for the
9941 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
9942 will have a reference count of 1, and the RV will be returned.
9943
9944 =cut
9945 */
9946
9947 SV*
9948 Perl_sv_setref_iv(pTHX_ SV *const rv, const char *const classname, const IV iv)
9949 {
9950     PERL_ARGS_ASSERT_SV_SETREF_IV;
9951
9952     sv_setiv(newSVrv(rv,classname), iv);
9953     return rv;
9954 }
9955
9956 /*
9957 =for apidoc sv_setref_uv
9958
9959 Copies an unsigned integer into a new SV, optionally blessing the SV.  The C<rv>
9960 argument will be upgraded to an RV.  That RV will be modified to point to
9961 the new SV.  The C<classname> argument indicates the package for the
9962 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
9963 will have a reference count of 1, and the RV will be returned.
9964
9965 =cut
9966 */
9967
9968 SV*
9969 Perl_sv_setref_uv(pTHX_ SV *const rv, const char *const classname, const UV uv)
9970 {
9971     PERL_ARGS_ASSERT_SV_SETREF_UV;
9972
9973     sv_setuv(newSVrv(rv,classname), uv);
9974     return rv;
9975 }
9976
9977 /*
9978 =for apidoc sv_setref_nv
9979
9980 Copies a double into a new SV, optionally blessing the SV.  The C<rv>
9981 argument will be upgraded to an RV.  That RV will be modified to point to
9982 the new SV.  The C<classname> argument indicates the package for the
9983 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
9984 will have a reference count of 1, and the RV will be returned.
9985
9986 =cut
9987 */
9988
9989 SV*
9990 Perl_sv_setref_nv(pTHX_ SV *const rv, const char *const classname, const NV nv)
9991 {
9992     PERL_ARGS_ASSERT_SV_SETREF_NV;
9993
9994     sv_setnv(newSVrv(rv,classname), nv);
9995     return rv;
9996 }
9997
9998 /*
9999 =for apidoc sv_setref_pvn
10000
10001 Copies a string into a new SV, optionally blessing the SV.  The length of the
10002 string must be specified with C<n>.  The C<rv> argument will be upgraded to
10003 an RV.  That RV will be modified to point to the new SV.  The C<classname>
10004 argument indicates the package for the blessing.  Set C<classname> to
10005 C<NULL> to avoid the blessing.  The new SV will have a reference count
10006 of 1, and the RV will be returned.
10007
10008 Note that C<sv_setref_pv> copies the pointer while this copies the string.
10009
10010 =cut
10011 */
10012
10013 SV*
10014 Perl_sv_setref_pvn(pTHX_ SV *const rv, const char *const classname,
10015                    const char *const pv, const STRLEN n)
10016 {
10017     PERL_ARGS_ASSERT_SV_SETREF_PVN;
10018
10019     sv_setpvn(newSVrv(rv,classname), pv, n);
10020     return rv;
10021 }
10022
10023 /*
10024 =for apidoc sv_bless
10025
10026 Blesses an SV into a specified package.  The SV must be an RV.  The package
10027 must be designated by its stash (see C<gv_stashpv()>).  The reference count
10028 of the SV is unaffected.
10029
10030 =cut
10031 */
10032
10033 SV*
10034 Perl_sv_bless(pTHX_ SV *const sv, HV *const stash)
10035 {
10036     dVAR;
10037     SV *tmpRef;
10038     HV *oldstash = NULL;
10039
10040     PERL_ARGS_ASSERT_SV_BLESS;
10041
10042     SvGETMAGIC(sv);
10043     if (!SvROK(sv))
10044         Perl_croak(aTHX_ "Can't bless non-reference value");
10045     tmpRef = SvRV(sv);
10046     if (SvFLAGS(tmpRef) & (SVs_OBJECT|SVf_READONLY)) {
10047         if (SvREADONLY(tmpRef))
10048             Perl_croak_no_modify();
10049         if (SvOBJECT(tmpRef)) {
10050             oldstash = SvSTASH(tmpRef);
10051         }
10052     }
10053     SvOBJECT_on(tmpRef);
10054     SvUPGRADE(tmpRef, SVt_PVMG);
10055     SvSTASH_set(tmpRef, MUTABLE_HV(SvREFCNT_inc_simple(stash)));
10056     SvREFCNT_dec(oldstash);
10057
10058     if(SvSMAGICAL(tmpRef))
10059         if(mg_find(tmpRef, PERL_MAGIC_ext) || mg_find(tmpRef, PERL_MAGIC_uvar))
10060             mg_set(tmpRef);
10061
10062
10063
10064     return sv;
10065 }
10066
10067 /* Downgrades a PVGV to a PVMG. If it's actually a PVLV, we leave the type
10068  * as it is after unglobbing it.
10069  */
10070
10071 PERL_STATIC_INLINE void
10072 S_sv_unglob(pTHX_ SV *const sv, U32 flags)
10073 {
10074     dVAR;
10075     void *xpvmg;
10076     HV *stash;
10077     SV * const temp = flags & SV_COW_DROP_PV ? NULL : sv_newmortal();
10078
10079     PERL_ARGS_ASSERT_SV_UNGLOB;
10080
10081     assert(SvTYPE(sv) == SVt_PVGV || SvTYPE(sv) == SVt_PVLV);
10082     SvFAKE_off(sv);
10083     if (!(flags & SV_COW_DROP_PV))
10084         gv_efullname3(temp, MUTABLE_GV(sv), "*");
10085
10086     SvREFCNT_inc_simple_void_NN(sv_2mortal(sv));
10087     if (GvGP(sv)) {
10088         if(GvCVu((const GV *)sv) && (stash = GvSTASH(MUTABLE_GV(sv)))
10089            && HvNAME_get(stash))
10090             mro_method_changed_in(stash);
10091         gp_free(MUTABLE_GV(sv));
10092     }
10093     if (GvSTASH(sv)) {
10094         sv_del_backref(MUTABLE_SV(GvSTASH(sv)), sv);
10095         GvSTASH(sv) = NULL;
10096     }
10097     GvMULTI_off(sv);
10098     if (GvNAME_HEK(sv)) {
10099         unshare_hek(GvNAME_HEK(sv));
10100     }
10101     isGV_with_GP_off(sv);
10102
10103     if(SvTYPE(sv) == SVt_PVGV) {
10104         /* need to keep SvANY(sv) in the right arena */
10105         xpvmg = new_XPVMG();
10106         StructCopy(SvANY(sv), xpvmg, XPVMG);
10107         del_XPVGV(SvANY(sv));
10108         SvANY(sv) = xpvmg;
10109
10110         SvFLAGS(sv) &= ~SVTYPEMASK;
10111         SvFLAGS(sv) |= SVt_PVMG;
10112     }
10113
10114     /* Intentionally not calling any local SET magic, as this isn't so much a
10115        set operation as merely an internal storage change.  */
10116     if (flags & SV_COW_DROP_PV) SvOK_off(sv);
10117     else sv_setsv_flags(sv, temp, 0);
10118
10119     if ((const GV *)sv == PL_last_in_gv)
10120         PL_last_in_gv = NULL;
10121     else if ((const GV *)sv == PL_statgv)
10122         PL_statgv = NULL;
10123 }
10124
10125 /*
10126 =for apidoc sv_unref_flags
10127
10128 Unsets the RV status of the SV, and decrements the reference count of
10129 whatever was being referenced by the RV.  This can almost be thought of
10130 as a reversal of C<newSVrv>.  The C<cflags> argument can contain
10131 C<SV_IMMEDIATE_UNREF> to force the reference count to be decremented
10132 (otherwise the decrementing is conditional on the reference count being
10133 different from one or the reference being a readonly SV).
10134 See C<SvROK_off>.
10135
10136 =cut
10137 */
10138
10139 void
10140 Perl_sv_unref_flags(pTHX_ SV *const ref, const U32 flags)
10141 {
10142     SV* const target = SvRV(ref);
10143
10144     PERL_ARGS_ASSERT_SV_UNREF_FLAGS;
10145
10146     if (SvWEAKREF(ref)) {
10147         sv_del_backref(target, ref);
10148         SvWEAKREF_off(ref);
10149         SvRV_set(ref, NULL);
10150         return;
10151     }
10152     SvRV_set(ref, NULL);
10153     SvROK_off(ref);
10154     /* You can't have a || SvREADONLY(target) here, as $a = $$a, where $a was
10155        assigned to as BEGIN {$a = \"Foo"} will fail.  */
10156     if (SvREFCNT(target) != 1 || (flags & SV_IMMEDIATE_UNREF))
10157         SvREFCNT_dec_NN(target);
10158     else /* XXX Hack, but hard to make $a=$a->[1] work otherwise */
10159         sv_2mortal(target);     /* Schedule for freeing later */
10160 }
10161
10162 /*
10163 =for apidoc sv_untaint
10164
10165 Untaint an SV.  Use C<SvTAINTED_off> instead.
10166
10167 =cut
10168 */
10169
10170 void
10171 Perl_sv_untaint(pTHX_ SV *const sv)
10172 {
10173     PERL_ARGS_ASSERT_SV_UNTAINT;
10174
10175     if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
10176         MAGIC * const mg = mg_find(sv, PERL_MAGIC_taint);
10177         if (mg)
10178             mg->mg_len &= ~1;
10179     }
10180 }
10181
10182 /*
10183 =for apidoc sv_tainted
10184
10185 Test an SV for taintedness.  Use C<SvTAINTED> instead.
10186
10187 =cut
10188 */
10189
10190 bool
10191 Perl_sv_tainted(pTHX_ SV *const sv)
10192 {
10193     PERL_ARGS_ASSERT_SV_TAINTED;
10194
10195     if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
10196         const MAGIC * const mg = mg_find(sv, PERL_MAGIC_taint);
10197         if (mg && (mg->mg_len & 1) )
10198             return TRUE;
10199     }
10200     return FALSE;
10201 }
10202
10203 /*
10204 =for apidoc sv_setpviv
10205
10206 Copies an integer into the given SV, also updating its string value.
10207 Does not handle 'set' magic.  See C<sv_setpviv_mg>.
10208
10209 =cut
10210 */
10211
10212 void
10213 Perl_sv_setpviv(pTHX_ SV *const sv, const IV iv)
10214 {
10215     char buf[TYPE_CHARS(UV)];
10216     char *ebuf;
10217     char * const ptr = uiv_2buf(buf, iv, 0, 0, &ebuf);
10218
10219     PERL_ARGS_ASSERT_SV_SETPVIV;
10220
10221     sv_setpvn(sv, ptr, ebuf - ptr);
10222 }
10223
10224 /*
10225 =for apidoc sv_setpviv_mg
10226
10227 Like C<sv_setpviv>, but also handles 'set' magic.
10228
10229 =cut
10230 */
10231
10232 void
10233 Perl_sv_setpviv_mg(pTHX_ SV *const sv, const IV iv)
10234 {
10235     PERL_ARGS_ASSERT_SV_SETPVIV_MG;
10236
10237     sv_setpviv(sv, iv);
10238     SvSETMAGIC(sv);
10239 }
10240
10241 #if defined(PERL_IMPLICIT_CONTEXT)
10242
10243 /* pTHX_ magic can't cope with varargs, so this is a no-context
10244  * version of the main function, (which may itself be aliased to us).
10245  * Don't access this version directly.
10246  */
10247
10248 void
10249 Perl_sv_setpvf_nocontext(SV *const sv, const char *const pat, ...)
10250 {
10251     dTHX;
10252     va_list args;
10253
10254     PERL_ARGS_ASSERT_SV_SETPVF_NOCONTEXT;
10255
10256     va_start(args, pat);
10257     sv_vsetpvf(sv, pat, &args);
10258     va_end(args);
10259 }
10260
10261 /* pTHX_ magic can't cope with varargs, so this is a no-context
10262  * version of the main function, (which may itself be aliased to us).
10263  * Don't access this version directly.
10264  */
10265
10266 void
10267 Perl_sv_setpvf_mg_nocontext(SV *const sv, const char *const pat, ...)
10268 {
10269     dTHX;
10270     va_list args;
10271
10272     PERL_ARGS_ASSERT_SV_SETPVF_MG_NOCONTEXT;
10273
10274     va_start(args, pat);
10275     sv_vsetpvf_mg(sv, pat, &args);
10276     va_end(args);
10277 }
10278 #endif
10279
10280 /*
10281 =for apidoc sv_setpvf
10282
10283 Works like C<sv_catpvf> but copies the text into the SV instead of
10284 appending it.  Does not handle 'set' magic.  See C<sv_setpvf_mg>.
10285
10286 =cut
10287 */
10288
10289 void
10290 Perl_sv_setpvf(pTHX_ SV *const sv, const char *const pat, ...)
10291 {
10292     va_list args;
10293
10294     PERL_ARGS_ASSERT_SV_SETPVF;
10295
10296     va_start(args, pat);
10297     sv_vsetpvf(sv, pat, &args);
10298     va_end(args);
10299 }
10300
10301 /*
10302 =for apidoc sv_vsetpvf
10303
10304 Works like C<sv_vcatpvf> but copies the text into the SV instead of
10305 appending it.  Does not handle 'set' magic.  See C<sv_vsetpvf_mg>.
10306
10307 Usually used via its frontend C<sv_setpvf>.
10308
10309 =cut
10310 */
10311
10312 void
10313 Perl_sv_vsetpvf(pTHX_ SV *const sv, const char *const pat, va_list *const args)
10314 {
10315     PERL_ARGS_ASSERT_SV_VSETPVF;
10316
10317     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
10318 }
10319
10320 /*
10321 =for apidoc sv_setpvf_mg
10322
10323 Like C<sv_setpvf>, but also handles 'set' magic.
10324
10325 =cut
10326 */
10327
10328 void
10329 Perl_sv_setpvf_mg(pTHX_ SV *const sv, const char *const pat, ...)
10330 {
10331     va_list args;
10332
10333     PERL_ARGS_ASSERT_SV_SETPVF_MG;
10334
10335     va_start(args, pat);
10336     sv_vsetpvf_mg(sv, pat, &args);
10337     va_end(args);
10338 }
10339
10340 /*
10341 =for apidoc sv_vsetpvf_mg
10342
10343 Like C<sv_vsetpvf>, but also handles 'set' magic.
10344
10345 Usually used via its frontend C<sv_setpvf_mg>.
10346
10347 =cut
10348 */
10349
10350 void
10351 Perl_sv_vsetpvf_mg(pTHX_ SV *const sv, const char *const pat, va_list *const args)
10352 {
10353     PERL_ARGS_ASSERT_SV_VSETPVF_MG;
10354
10355     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
10356     SvSETMAGIC(sv);
10357 }
10358
10359 #if defined(PERL_IMPLICIT_CONTEXT)
10360
10361 /* pTHX_ magic can't cope with varargs, so this is a no-context
10362  * version of the main function, (which may itself be aliased to us).
10363  * Don't access this version directly.
10364  */
10365
10366 void
10367 Perl_sv_catpvf_nocontext(SV *const sv, const char *const pat, ...)
10368 {
10369     dTHX;
10370     va_list args;
10371
10372     PERL_ARGS_ASSERT_SV_CATPVF_NOCONTEXT;
10373
10374     va_start(args, pat);
10375     sv_vcatpvfn_flags(sv, pat, strlen(pat), &args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
10376     va_end(args);
10377 }
10378
10379 /* pTHX_ magic can't cope with varargs, so this is a no-context
10380  * version of the main function, (which may itself be aliased to us).
10381  * Don't access this version directly.
10382  */
10383
10384 void
10385 Perl_sv_catpvf_mg_nocontext(SV *const sv, const char *const pat, ...)
10386 {
10387     dTHX;
10388     va_list args;
10389
10390     PERL_ARGS_ASSERT_SV_CATPVF_MG_NOCONTEXT;
10391
10392     va_start(args, pat);
10393     sv_vcatpvfn_flags(sv, pat, strlen(pat), &args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
10394     SvSETMAGIC(sv);
10395     va_end(args);
10396 }
10397 #endif
10398
10399 /*
10400 =for apidoc sv_catpvf
10401
10402 Processes its arguments like C<sprintf> and appends the formatted
10403 output to an SV.  If the appended data contains "wide" characters
10404 (including, but not limited to, SVs with a UTF-8 PV formatted with %s,
10405 and characters >255 formatted with %c), the original SV might get
10406 upgraded to UTF-8.  Handles 'get' magic, but not 'set' magic.  See
10407 C<sv_catpvf_mg>.  If the original SV was UTF-8, the pattern should be
10408 valid UTF-8; if the original SV was bytes, the pattern should be too.
10409
10410 =cut */
10411
10412 void
10413 Perl_sv_catpvf(pTHX_ SV *const sv, const char *const pat, ...)
10414 {
10415     va_list args;
10416
10417     PERL_ARGS_ASSERT_SV_CATPVF;
10418
10419     va_start(args, pat);
10420     sv_vcatpvfn_flags(sv, pat, strlen(pat), &args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
10421     va_end(args);
10422 }
10423
10424 /*
10425 =for apidoc sv_vcatpvf
10426
10427 Processes its arguments like C<vsprintf> and appends the formatted output
10428 to an SV.  Does not handle 'set' magic.  See C<sv_vcatpvf_mg>.
10429
10430 Usually used via its frontend C<sv_catpvf>.
10431
10432 =cut
10433 */
10434
10435 void
10436 Perl_sv_vcatpvf(pTHX_ SV *const sv, const char *const pat, va_list *const args)
10437 {
10438     PERL_ARGS_ASSERT_SV_VCATPVF;
10439
10440     sv_vcatpvfn_flags(sv, pat, strlen(pat), args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
10441 }
10442
10443 /*
10444 =for apidoc sv_catpvf_mg
10445
10446 Like C<sv_catpvf>, but also handles 'set' magic.
10447
10448 =cut
10449 */
10450
10451 void
10452 Perl_sv_catpvf_mg(pTHX_ SV *const sv, const char *const pat, ...)
10453 {
10454     va_list args;
10455
10456     PERL_ARGS_ASSERT_SV_CATPVF_MG;
10457
10458     va_start(args, pat);
10459     sv_vcatpvfn_flags(sv, pat, strlen(pat), &args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
10460     SvSETMAGIC(sv);
10461     va_end(args);
10462 }
10463
10464 /*
10465 =for apidoc sv_vcatpvf_mg
10466
10467 Like C<sv_vcatpvf>, but also handles 'set' magic.
10468
10469 Usually used via its frontend C<sv_catpvf_mg>.
10470
10471 =cut
10472 */
10473
10474 void
10475 Perl_sv_vcatpvf_mg(pTHX_ SV *const sv, const char *const pat, va_list *const args)
10476 {
10477     PERL_ARGS_ASSERT_SV_VCATPVF_MG;
10478
10479     sv_vcatpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
10480     SvSETMAGIC(sv);
10481 }
10482
10483 /*
10484 =for apidoc sv_vsetpvfn
10485
10486 Works like C<sv_vcatpvfn> but copies the text into the SV instead of
10487 appending it.
10488
10489 Usually used via one of its frontends C<sv_vsetpvf> and C<sv_vsetpvf_mg>.
10490
10491 =cut
10492 */
10493
10494 void
10495 Perl_sv_vsetpvfn(pTHX_ SV *const sv, const char *const pat, const STRLEN patlen,
10496                  va_list *const args, SV **const svargs, const I32 svmax, bool *const maybe_tainted)
10497 {
10498     PERL_ARGS_ASSERT_SV_VSETPVFN;
10499
10500     sv_setpvs(sv, "");
10501     sv_vcatpvfn_flags(sv, pat, patlen, args, svargs, svmax, maybe_tainted, 0);
10502 }
10503
10504
10505 /*
10506  * Warn of missing argument to sprintf, and then return a defined value
10507  * to avoid inappropriate "use of uninit" warnings [perl #71000].
10508  */
10509 #define WARN_MISSING WARN_UNINITIALIZED /* Not sure we want a new category */
10510 STATIC SV*
10511 S_vcatpvfn_missing_argument(pTHX) {
10512     if (ckWARN(WARN_MISSING)) {
10513         Perl_warner(aTHX_ packWARN(WARN_MISSING), "Missing argument in %s",
10514                 PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn()");
10515     }
10516     return &PL_sv_no;
10517 }
10518
10519
10520 STATIC I32
10521 S_expect_number(pTHX_ char **const pattern)
10522 {
10523     dVAR;
10524     I32 var = 0;
10525
10526     PERL_ARGS_ASSERT_EXPECT_NUMBER;
10527
10528     switch (**pattern) {
10529     case '1': case '2': case '3':
10530     case '4': case '5': case '6':
10531     case '7': case '8': case '9':
10532         var = *(*pattern)++ - '0';
10533         while (isDIGIT(**pattern)) {
10534             const I32 tmp = var * 10 + (*(*pattern)++ - '0');
10535             if (tmp < var)
10536                 Perl_croak(aTHX_ "Integer overflow in format string for %s", (PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn"));
10537             var = tmp;
10538         }
10539     }
10540     return var;
10541 }
10542
10543 STATIC char *
10544 S_F0convert(NV nv, char *const endbuf, STRLEN *const len)
10545 {
10546     const int neg = nv < 0;
10547     UV uv;
10548
10549     PERL_ARGS_ASSERT_F0CONVERT;
10550
10551     if (neg)
10552         nv = -nv;
10553     if (nv < UV_MAX) {
10554         char *p = endbuf;
10555         nv += 0.5;
10556         uv = (UV)nv;
10557         if (uv & 1 && uv == nv)
10558             uv--;                       /* Round to even */
10559         do {
10560             const unsigned dig = uv % 10;
10561             *--p = '0' + dig;
10562         } while (uv /= 10);
10563         if (neg)
10564             *--p = '-';
10565         *len = endbuf - p;
10566         return p;
10567     }
10568     return NULL;
10569 }
10570
10571
10572 /*
10573 =for apidoc sv_vcatpvfn
10574
10575 =for apidoc sv_vcatpvfn_flags
10576
10577 Processes its arguments like C<vsprintf> and appends the formatted output
10578 to an SV.  Uses an array of SVs if the C style variable argument list is
10579 missing (NULL).  When running with taint checks enabled, indicates via
10580 C<maybe_tainted> if results are untrustworthy (often due to the use of
10581 locales).
10582
10583 If called as C<sv_vcatpvfn> or flags include C<SV_GMAGIC>, calls get magic.
10584
10585 Usually used via one of its frontends C<sv_vcatpvf> and C<sv_vcatpvf_mg>.
10586
10587 =cut
10588 */
10589
10590 #define VECTORIZE_ARGS  vecsv = va_arg(*args, SV*);\
10591                         vecstr = (U8*)SvPV_const(vecsv,veclen);\
10592                         vec_utf8 = DO_UTF8(vecsv);
10593
10594 /* XXX maybe_tainted is never assigned to, so the doc above is lying. */
10595
10596 void
10597 Perl_sv_vcatpvfn(pTHX_ SV *const sv, const char *const pat, const STRLEN patlen,
10598                  va_list *const args, SV **const svargs, const I32 svmax, bool *const maybe_tainted)
10599 {
10600     PERL_ARGS_ASSERT_SV_VCATPVFN;
10601
10602     sv_vcatpvfn_flags(sv, pat, patlen, args, svargs, svmax, maybe_tainted, SV_GMAGIC|SV_SMAGIC);
10603 }
10604
10605 void
10606 Perl_sv_vcatpvfn_flags(pTHX_ SV *const sv, const char *const pat, const STRLEN patlen,
10607                        va_list *const args, SV **const svargs, const I32 svmax, bool *const maybe_tainted,
10608                        const U32 flags)
10609 {
10610     dVAR;
10611     char *p;
10612     char *q;
10613     const char *patend;
10614     STRLEN origlen;
10615     I32 svix = 0;
10616     static const char nullstr[] = "(null)";
10617     SV *argsv = NULL;
10618     bool has_utf8 = DO_UTF8(sv);    /* has the result utf8? */
10619     const bool pat_utf8 = has_utf8; /* the pattern is in utf8? */
10620     SV *nsv = NULL;
10621     /* Times 4: a decimal digit takes more than 3 binary digits.
10622      * NV_DIG: mantissa takes than many decimal digits.
10623      * Plus 32: Playing safe. */
10624     char ebuf[IV_DIG * 4 + NV_DIG + 32];
10625     /* large enough for "%#.#f" --chip */
10626     /* what about long double NVs? --jhi */
10627
10628     DECLARATION_FOR_STORE_LC_NUMERIC_SET_TO_NEEDED;
10629
10630     PERL_ARGS_ASSERT_SV_VCATPVFN_FLAGS;
10631     PERL_UNUSED_ARG(maybe_tainted);
10632
10633     if (flags & SV_GMAGIC)
10634         SvGETMAGIC(sv);
10635
10636     /* no matter what, this is a string now */
10637     (void)SvPV_force_nomg(sv, origlen);
10638
10639     /* special-case "", "%s", and "%-p" (SVf - see below) */
10640     if (patlen == 0)
10641         return;
10642     if (patlen == 2 && pat[0] == '%' && pat[1] == 's') {
10643         if (args) {
10644             const char * const s = va_arg(*args, char*);
10645             sv_catpv_nomg(sv, s ? s : nullstr);
10646         }
10647         else if (svix < svmax) {
10648             /* we want get magic on the source but not the target. sv_catsv can't do that, though */
10649             SvGETMAGIC(*svargs);
10650             sv_catsv_nomg(sv, *svargs);
10651         }
10652         else
10653             S_vcatpvfn_missing_argument(aTHX);
10654         return;
10655     }
10656     if (args && patlen == 3 && pat[0] == '%' &&
10657                 pat[1] == '-' && pat[2] == 'p') {
10658         argsv = MUTABLE_SV(va_arg(*args, void*));
10659         sv_catsv_nomg(sv, argsv);
10660         return;
10661     }
10662
10663 #ifndef USE_LONG_DOUBLE
10664     /* special-case "%.<number>[gf]" */
10665     if ( !args && patlen <= 5 && pat[0] == '%' && pat[1] == '.'
10666          && (pat[patlen-1] == 'g' || pat[patlen-1] == 'f') ) {
10667         unsigned digits = 0;
10668         const char *pp;
10669
10670         pp = pat + 2;
10671         while (*pp >= '0' && *pp <= '9')
10672             digits = 10 * digits + (*pp++ - '0');
10673         if (pp - pat == (int)patlen - 1 && svix < svmax) {
10674             const NV nv = SvNV(*svargs);
10675             if (*pp == 'g') {
10676                 /* Add check for digits != 0 because it seems that some
10677                    gconverts are buggy in this case, and we don't yet have
10678                    a Configure test for this.  */
10679                 if (digits && digits < sizeof(ebuf) - NV_DIG - 10) {
10680                      /* 0, point, slack */
10681                     STORE_LC_NUMERIC_SET_TO_NEEDED();
10682                     PERL_UNUSED_RESULT(Gconvert(nv, (int)digits, 0, ebuf));
10683                     sv_catpv_nomg(sv, ebuf);
10684                     if (*ebuf)  /* May return an empty string for digits==0 */
10685                         return;
10686                 }
10687             } else if (!digits) {
10688                 STRLEN l;
10689
10690                 if ((p = F0convert(nv, ebuf + sizeof ebuf, &l))) {
10691                     sv_catpvn_nomg(sv, p, l);
10692                     return;
10693                 }
10694             }
10695         }
10696     }
10697 #endif /* !USE_LONG_DOUBLE */
10698
10699     if (!args && svix < svmax && DO_UTF8(*svargs))
10700         has_utf8 = TRUE;
10701
10702     patend = (char*)pat + patlen;
10703     for (p = (char*)pat; p < patend; p = q) {
10704         bool alt = FALSE;
10705         bool left = FALSE;
10706         bool vectorize = FALSE;
10707         bool vectorarg = FALSE;
10708         bool vec_utf8 = FALSE;
10709         char fill = ' ';
10710         char plus = 0;
10711         char intsize = 0;
10712         STRLEN width = 0;
10713         STRLEN zeros = 0;
10714         bool has_precis = FALSE;
10715         STRLEN precis = 0;
10716         const I32 osvix = svix;
10717         bool is_utf8 = FALSE;  /* is this item utf8?   */
10718 #ifdef HAS_LDBL_SPRINTF_BUG
10719         /* This is to try to fix a bug with irix/nonstop-ux/powerux and
10720            with sfio - Allen <allens@cpan.org> */
10721         bool fix_ldbl_sprintf_bug = FALSE;
10722 #endif
10723
10724         char esignbuf[4];
10725         U8 utf8buf[UTF8_MAXBYTES+1];
10726         STRLEN esignlen = 0;
10727
10728         const char *eptr = NULL;
10729         const char *fmtstart;
10730         STRLEN elen = 0;
10731         SV *vecsv = NULL;
10732         const U8 *vecstr = NULL;
10733         STRLEN veclen = 0;
10734         char c = 0;
10735         int i;
10736         unsigned base = 0;
10737         IV iv = 0;
10738         UV uv = 0;
10739         /* we need a long double target in case HAS_LONG_DOUBLE but
10740            not USE_LONG_DOUBLE
10741         */
10742 #if defined(HAS_LONG_DOUBLE) && LONG_DOUBLESIZE > DOUBLESIZE
10743         long double nv;
10744 #else
10745         NV nv;
10746 #endif
10747         STRLEN have;
10748         STRLEN need;
10749         STRLEN gap;
10750         const char *dotstr = ".";
10751         STRLEN dotstrlen = 1;
10752         I32 efix = 0; /* explicit format parameter index */
10753         I32 ewix = 0; /* explicit width index */
10754         I32 epix = 0; /* explicit precision index */
10755         I32 evix = 0; /* explicit vector index */
10756         bool asterisk = FALSE;
10757
10758         /* echo everything up to the next format specification */
10759         for (q = p; q < patend && *q != '%'; ++q) ;
10760         if (q > p) {
10761             if (has_utf8 && !pat_utf8)
10762                 sv_catpvn_nomg_utf8_upgrade(sv, p, q - p, nsv);
10763             else
10764                 sv_catpvn_nomg(sv, p, q - p);
10765             p = q;
10766         }
10767         if (q++ >= patend)
10768             break;
10769
10770         fmtstart = q;
10771
10772 /*
10773     We allow format specification elements in this order:
10774         \d+\$              explicit format parameter index
10775         [-+ 0#]+           flags
10776         v|\*(\d+\$)?v      vector with optional (optionally specified) arg
10777         0                  flag (as above): repeated to allow "v02"     
10778         \d+|\*(\d+\$)?     width using optional (optionally specified) arg
10779         \.(\d*|\*(\d+\$)?) precision using optional (optionally specified) arg
10780         [hlqLV]            size
10781     [%bcdefginopsuxDFOUX] format (mandatory)
10782 */
10783
10784         if (args) {
10785 /*  
10786         As of perl5.9.3, printf format checking is on by default.
10787         Internally, perl uses %p formats to provide an escape to
10788         some extended formatting.  This block deals with those
10789         extensions: if it does not match, (char*)q is reset and
10790         the normal format processing code is used.
10791
10792         Currently defined extensions are:
10793                 %p              include pointer address (standard)      
10794                 %-p     (SVf)   include an SV (previously %_)
10795                 %-<num>p        include an SV with precision <num>      
10796                 %2p             include a HEK
10797                 %3p             include a HEK with precision of 256
10798                 %4p             char* preceded by utf8 flag and length
10799                 %<num>p         (where num is 1 or > 4) reserved for future
10800                                 extensions
10801
10802         Robin Barker 2005-07-14 (but modified since)
10803
10804                 %1p     (VDf)   removed.  RMB 2007-10-19
10805 */
10806             char* r = q; 
10807             bool sv = FALSE;    
10808             STRLEN n = 0;
10809             if (*q == '-')
10810                 sv = *q++;
10811             else if (strnEQ(q, UTF8f, sizeof(UTF8f)-1)) { /* UTF8f */
10812                 /* The argument has already gone through cBOOL, so the cast
10813                    is safe. */
10814                 is_utf8 = (bool)va_arg(*args, int);
10815                 elen = va_arg(*args, UV);
10816                 eptr = va_arg(*args, char *);
10817                 q += sizeof(UTF8f)-1;
10818                 goto string;
10819             }
10820             n = expect_number(&q);
10821             if (*q++ == 'p') {
10822                 if (sv) {                       /* SVf */
10823                     if (n) {
10824                         precis = n;
10825                         has_precis = TRUE;
10826                     }
10827                     argsv = MUTABLE_SV(va_arg(*args, void*));
10828                     eptr = SvPV_const(argsv, elen);
10829                     if (DO_UTF8(argsv))
10830                         is_utf8 = TRUE;
10831                     goto string;
10832                 }
10833                 else if (n==2 || n==3) {        /* HEKf */
10834                     HEK * const hek = va_arg(*args, HEK *);
10835                     eptr = HEK_KEY(hek);
10836                     elen = HEK_LEN(hek);
10837                     if (HEK_UTF8(hek)) is_utf8 = TRUE;
10838                     if (n==3) precis = 256, has_precis = TRUE;
10839                     goto string;
10840                 }
10841                 else if (n) {
10842                     Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
10843                                      "internal %%<num>p might conflict with future printf extensions");
10844                 }
10845             }
10846             q = r; 
10847         }
10848
10849         if ( (width = expect_number(&q)) ) {
10850             if (*q == '$') {
10851                 ++q;
10852                 efix = width;
10853             } else {
10854                 goto gotwidth;
10855             }
10856         }
10857
10858         /* FLAGS */
10859
10860         while (*q) {
10861             switch (*q) {
10862             case ' ':
10863             case '+':
10864                 if (plus == '+' && *q == ' ') /* '+' over ' ' */
10865                     q++;
10866                 else
10867                     plus = *q++;
10868                 continue;
10869
10870             case '-':
10871                 left = TRUE;
10872                 q++;
10873                 continue;
10874
10875             case '0':
10876                 fill = *q++;
10877                 continue;
10878
10879             case '#':
10880                 alt = TRUE;
10881                 q++;
10882                 continue;
10883
10884             default:
10885                 break;
10886             }
10887             break;
10888         }
10889
10890       tryasterisk:
10891         if (*q == '*') {
10892             q++;
10893             if ( (ewix = expect_number(&q)) )
10894                 if (*q++ != '$')
10895                     goto unknown;
10896             asterisk = TRUE;
10897         }
10898         if (*q == 'v') {
10899             q++;
10900             if (vectorize)
10901                 goto unknown;
10902             if ((vectorarg = asterisk)) {
10903                 evix = ewix;
10904                 ewix = 0;
10905                 asterisk = FALSE;
10906             }
10907             vectorize = TRUE;
10908             goto tryasterisk;
10909         }
10910
10911         if (!asterisk)
10912         {
10913             if( *q == '0' )
10914                 fill = *q++;
10915             width = expect_number(&q);
10916         }
10917
10918         if (vectorize && vectorarg) {
10919             /* vectorizing, but not with the default "." */
10920             if (args)
10921                 vecsv = va_arg(*args, SV*);
10922             else if (evix) {
10923                 vecsv = (evix > 0 && evix <= svmax)
10924                     ? svargs[evix-1] : S_vcatpvfn_missing_argument(aTHX);
10925             } else {
10926                 vecsv = svix < svmax
10927                     ? svargs[svix++] : S_vcatpvfn_missing_argument(aTHX);
10928             }
10929             dotstr = SvPV_const(vecsv, dotstrlen);
10930             /* Keep the DO_UTF8 test *after* the SvPV call, else things go
10931                bad with tied or overloaded values that return UTF8.  */
10932             if (DO_UTF8(vecsv))
10933                 is_utf8 = TRUE;
10934             else if (has_utf8) {
10935                 vecsv = sv_mortalcopy(vecsv);
10936                 sv_utf8_upgrade(vecsv);
10937                 dotstr = SvPV_const(vecsv, dotstrlen);
10938                 is_utf8 = TRUE;
10939             }               
10940         }
10941
10942         if (asterisk) {
10943             if (args)
10944                 i = va_arg(*args, int);
10945             else
10946                 i = (ewix ? ewix <= svmax : svix < svmax) ?
10947                     SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
10948             left |= (i < 0);
10949             width = (i < 0) ? -i : i;
10950         }
10951       gotwidth:
10952
10953         /* PRECISION */
10954
10955         if (*q == '.') {
10956             q++;
10957             if (*q == '*') {
10958                 q++;
10959                 if ( ((epix = expect_number(&q))) && (*q++ != '$') )
10960                     goto unknown;
10961                 /* XXX: todo, support specified precision parameter */
10962                 if (epix)
10963                     goto unknown;
10964                 if (args)
10965                     i = va_arg(*args, int);
10966                 else
10967                     i = (ewix ? ewix <= svmax : svix < svmax)
10968                         ? SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
10969                 precis = i;
10970                 has_precis = !(i < 0);
10971             }
10972             else {
10973                 precis = 0;
10974                 while (isDIGIT(*q))
10975                     precis = precis * 10 + (*q++ - '0');
10976                 has_precis = TRUE;
10977             }
10978         }
10979
10980         if (vectorize) {
10981             if (args) {
10982                 VECTORIZE_ARGS
10983             }
10984             else if (efix ? (efix > 0 && efix <= svmax) : svix < svmax) {
10985                 vecsv = svargs[efix ? efix-1 : svix++];
10986                 vecstr = (U8*)SvPV_const(vecsv,veclen);
10987                 vec_utf8 = DO_UTF8(vecsv);
10988
10989                 /* if this is a version object, we need to convert
10990                  * back into v-string notation and then let the
10991                  * vectorize happen normally
10992                  */
10993                 if (sv_isobject(vecsv) && sv_derived_from(vecsv, "version")) {
10994                     if ( hv_exists(MUTABLE_HV(SvRV(vecsv)), "alpha", 5 ) ) {
10995                         Perl_ck_warner_d(aTHX_ packWARN(WARN_PRINTF),
10996                         "vector argument not supported with alpha versions");
10997                         goto vdblank;
10998                     }
10999                     vecsv = sv_newmortal();
11000                     scan_vstring((char *)vecstr, (char *)vecstr + veclen,
11001                                  vecsv);
11002                     vecstr = (U8*)SvPV_const(vecsv, veclen);
11003                     vec_utf8 = DO_UTF8(vecsv);
11004                 }
11005             }
11006             else {
11007               vdblank:
11008                 vecstr = (U8*)"";
11009                 veclen = 0;
11010             }
11011         }
11012
11013         /* SIZE */
11014
11015         switch (*q) {
11016 #ifdef WIN32
11017         case 'I':                       /* Ix, I32x, and I64x */
11018 #  ifdef USE_64_BIT_INT
11019             if (q[1] == '6' && q[2] == '4') {
11020                 q += 3;
11021                 intsize = 'q';
11022                 break;
11023             }
11024 #  endif
11025             if (q[1] == '3' && q[2] == '2') {
11026                 q += 3;
11027                 break;
11028             }
11029 #  ifdef USE_64_BIT_INT
11030             intsize = 'q';
11031 #  endif
11032             q++;
11033             break;
11034 #endif
11035 #if IVSIZE >= 8 || defined(HAS_LONG_DOUBLE)
11036         case 'L':                       /* Ld */
11037             /* FALLTHROUGH */
11038 #if IVSIZE >= 8
11039         case 'q':                       /* qd */
11040 #endif
11041             intsize = 'q';
11042             q++;
11043             break;
11044 #endif
11045         case 'l':
11046             ++q;
11047 #if IVSIZE >= 8 || defined(HAS_LONG_DOUBLE)
11048             if (*q == 'l') {    /* lld, llf */
11049                 intsize = 'q';
11050                 ++q;
11051             }
11052             else
11053 #endif
11054                 intsize = 'l';
11055             break;
11056         case 'h':
11057             if (*++q == 'h') {  /* hhd, hhu */
11058                 intsize = 'c';
11059                 ++q;
11060             }
11061             else
11062                 intsize = 'h';
11063             break;
11064         case 'V':
11065         case 'z':
11066         case 't':
11067 #ifdef HAS_C99
11068         case 'j':
11069 #endif
11070             intsize = *q++;
11071             break;
11072         }
11073
11074         /* CONVERSION */
11075
11076         if (*q == '%') {
11077             eptr = q++;
11078             elen = 1;
11079             if (vectorize) {
11080                 c = '%';
11081                 goto unknown;
11082             }
11083             goto string;
11084         }
11085
11086         if (!vectorize && !args) {
11087             if (efix) {
11088                 const I32 i = efix-1;
11089                 argsv = (i >= 0 && i < svmax)
11090                     ? svargs[i] : S_vcatpvfn_missing_argument(aTHX);
11091             } else {
11092                 argsv = (svix >= 0 && svix < svmax)
11093                     ? svargs[svix++] : S_vcatpvfn_missing_argument(aTHX);
11094             }
11095         }
11096
11097         switch (c = *q++) {
11098
11099             /* STRINGS */
11100
11101         case 'c':
11102             if (vectorize)
11103                 goto unknown;
11104             uv = (args) ? va_arg(*args, int) : SvIV(argsv);
11105             if ((uv > 255 ||
11106                  (!UVCHR_IS_INVARIANT(uv) && SvUTF8(sv)))
11107                 && !IN_BYTES) {
11108                 eptr = (char*)utf8buf;
11109                 elen = uvchr_to_utf8((U8*)eptr, uv) - utf8buf;
11110                 is_utf8 = TRUE;
11111             }
11112             else {
11113                 c = (char)uv;
11114                 eptr = &c;
11115                 elen = 1;
11116             }
11117             goto string;
11118
11119         case 's':
11120             if (vectorize)
11121                 goto unknown;
11122             if (args) {
11123                 eptr = va_arg(*args, char*);
11124                 if (eptr)
11125                     elen = strlen(eptr);
11126                 else {
11127                     eptr = (char *)nullstr;
11128                     elen = sizeof nullstr - 1;
11129                 }
11130             }
11131             else {
11132                 eptr = SvPV_const(argsv, elen);
11133                 if (DO_UTF8(argsv)) {
11134                     STRLEN old_precis = precis;
11135                     if (has_precis && precis < elen) {
11136                         STRLEN ulen = sv_or_pv_len_utf8(argsv, eptr, elen);
11137                         STRLEN p = precis > ulen ? ulen : precis;
11138                         precis = sv_or_pv_pos_u2b(argsv, eptr, p, 0);
11139                                                         /* sticks at end */
11140                     }
11141                     if (width) { /* fudge width (can't fudge elen) */
11142                         if (has_precis && precis < elen)
11143                             width += precis - old_precis;
11144                         else
11145                             width +=
11146                                 elen - sv_or_pv_len_utf8(argsv,eptr,elen);
11147                     }
11148                     is_utf8 = TRUE;
11149                 }
11150             }
11151
11152         string:
11153             if (has_precis && precis < elen)
11154                 elen = precis;
11155             break;
11156
11157             /* INTEGERS */
11158
11159         case 'p':
11160             if (alt || vectorize)
11161                 goto unknown;
11162             uv = PTR2UV(args ? va_arg(*args, void*) : argsv);
11163             base = 16;
11164             goto integer;
11165
11166         case 'D':
11167 #ifdef IV_IS_QUAD
11168             intsize = 'q';
11169 #else
11170             intsize = 'l';
11171 #endif
11172             /* FALLTHROUGH */
11173         case 'd':
11174         case 'i':
11175             if (vectorize) {
11176                 STRLEN ulen;
11177                 if (!veclen)
11178                     continue;
11179                 if (vec_utf8)
11180                     uv = utf8n_to_uvchr(vecstr, veclen, &ulen,
11181                                         UTF8_ALLOW_ANYUV);
11182                 else {
11183                     uv = *vecstr;
11184                     ulen = 1;
11185                 }
11186                 vecstr += ulen;
11187                 veclen -= ulen;
11188                 if (plus)
11189                      esignbuf[esignlen++] = plus;
11190             }
11191             else if (args) {
11192                 switch (intsize) {
11193                 case 'c':       iv = (char)va_arg(*args, int); break;
11194                 case 'h':       iv = (short)va_arg(*args, int); break;
11195                 case 'l':       iv = va_arg(*args, long); break;
11196                 case 'V':       iv = va_arg(*args, IV); break;
11197                 case 'z':       iv = va_arg(*args, SSize_t); break;
11198                 case 't':       iv = va_arg(*args, ptrdiff_t); break;
11199                 default:        iv = va_arg(*args, int); break;
11200 #ifdef HAS_C99
11201                 case 'j':       iv = va_arg(*args, intmax_t); break;
11202 #endif
11203                 case 'q':
11204 #if IVSIZE >= 8
11205                                 iv = va_arg(*args, Quad_t); break;
11206 #else
11207                                 goto unknown;
11208 #endif
11209                 }
11210             }
11211             else {
11212                 IV tiv = SvIV(argsv); /* work around GCC bug #13488 */
11213                 switch (intsize) {
11214                 case 'c':       iv = (char)tiv; break;
11215                 case 'h':       iv = (short)tiv; break;
11216                 case 'l':       iv = (long)tiv; break;
11217                 case 'V':
11218                 default:        iv = tiv; break;
11219                 case 'q':
11220 #if IVSIZE >= 8
11221                                 iv = (Quad_t)tiv; break;
11222 #else
11223                                 goto unknown;
11224 #endif
11225                 }
11226             }
11227             if ( !vectorize )   /* we already set uv above */
11228             {
11229                 if (iv >= 0) {
11230                     uv = iv;
11231                     if (plus)
11232                         esignbuf[esignlen++] = plus;
11233                 }
11234                 else {
11235                     uv = -iv;
11236                     esignbuf[esignlen++] = '-';
11237                 }
11238             }
11239             base = 10;
11240             goto integer;
11241
11242         case 'U':
11243 #ifdef IV_IS_QUAD
11244             intsize = 'q';
11245 #else
11246             intsize = 'l';
11247 #endif
11248             /* FALLTHROUGH */
11249         case 'u':
11250             base = 10;
11251             goto uns_integer;
11252
11253         case 'B':
11254         case 'b':
11255             base = 2;
11256             goto uns_integer;
11257
11258         case 'O':
11259 #ifdef IV_IS_QUAD
11260             intsize = 'q';
11261 #else
11262             intsize = 'l';
11263 #endif
11264             /* FALLTHROUGH */
11265         case 'o':
11266             base = 8;
11267             goto uns_integer;
11268
11269         case 'X':
11270         case 'x':
11271             base = 16;
11272
11273         uns_integer:
11274             if (vectorize) {
11275                 STRLEN ulen;
11276         vector:
11277                 if (!veclen)
11278                     continue;
11279                 if (vec_utf8)
11280                     uv = utf8n_to_uvchr(vecstr, veclen, &ulen,
11281                                         UTF8_ALLOW_ANYUV);
11282                 else {
11283                     uv = *vecstr;
11284                     ulen = 1;
11285                 }
11286                 vecstr += ulen;
11287                 veclen -= ulen;
11288             }
11289             else if (args) {
11290                 switch (intsize) {
11291                 case 'c':  uv = (unsigned char)va_arg(*args, unsigned); break;
11292                 case 'h':  uv = (unsigned short)va_arg(*args, unsigned); break;
11293                 case 'l':  uv = va_arg(*args, unsigned long); break;
11294                 case 'V':  uv = va_arg(*args, UV); break;
11295                 case 'z':  uv = va_arg(*args, Size_t); break;
11296                 case 't':  uv = va_arg(*args, ptrdiff_t); break; /* will sign extend, but there is no uptrdiff_t, so oh well */
11297 #ifdef HAS_C99
11298                 case 'j':  uv = va_arg(*args, uintmax_t); break;
11299 #endif
11300                 default:   uv = va_arg(*args, unsigned); break;
11301                 case 'q':
11302 #if IVSIZE >= 8
11303                            uv = va_arg(*args, Uquad_t); break;
11304 #else
11305                            goto unknown;
11306 #endif
11307                 }
11308             }
11309             else {
11310                 UV tuv = SvUV(argsv); /* work around GCC bug #13488 */
11311                 switch (intsize) {
11312                 case 'c':       uv = (unsigned char)tuv; break;
11313                 case 'h':       uv = (unsigned short)tuv; break;
11314                 case 'l':       uv = (unsigned long)tuv; break;
11315                 case 'V':
11316                 default:        uv = tuv; break;
11317                 case 'q':
11318 #if IVSIZE >= 8
11319                                 uv = (Uquad_t)tuv; break;
11320 #else
11321                                 goto unknown;
11322 #endif
11323                 }
11324             }
11325
11326         integer:
11327             {
11328                 char *ptr = ebuf + sizeof ebuf;
11329                 bool tempalt = uv ? alt : FALSE; /* Vectors can't change alt */
11330                 zeros = 0;
11331
11332                 switch (base) {
11333                     unsigned dig;
11334                 case 16:
11335                     p = (char *)((c == 'X') ? PL_hexdigit + 16 : PL_hexdigit);
11336                     do {
11337                         dig = uv & 15;
11338                         *--ptr = p[dig];
11339                     } while (uv >>= 4);
11340                     if (tempalt) {
11341                         esignbuf[esignlen++] = '0';
11342                         esignbuf[esignlen++] = c;  /* 'x' or 'X' */
11343                     }
11344                     break;
11345                 case 8:
11346                     do {
11347                         dig = uv & 7;
11348                         *--ptr = '0' + dig;
11349                     } while (uv >>= 3);
11350                     if (alt && *ptr != '0')
11351                         *--ptr = '0';
11352                     break;
11353                 case 2:
11354                     do {
11355                         dig = uv & 1;
11356                         *--ptr = '0' + dig;
11357                     } while (uv >>= 1);
11358                     if (tempalt) {
11359                         esignbuf[esignlen++] = '0';
11360                         esignbuf[esignlen++] = c;
11361                     }
11362                     break;
11363                 default:                /* it had better be ten or less */
11364                     do {
11365                         dig = uv % base;
11366                         *--ptr = '0' + dig;
11367                     } while (uv /= base);
11368                     break;
11369                 }
11370                 elen = (ebuf + sizeof ebuf) - ptr;
11371                 eptr = ptr;
11372                 if (has_precis) {
11373                     if (precis > elen)
11374                         zeros = precis - elen;
11375                     else if (precis == 0 && elen == 1 && *eptr == '0'
11376                              && !(base == 8 && alt)) /* "%#.0o" prints "0" */
11377                         elen = 0;
11378
11379                 /* a precision nullifies the 0 flag. */
11380                     if (fill == '0')
11381                         fill = ' ';
11382                 }
11383             }
11384             break;
11385
11386             /* FLOATING POINT */
11387
11388         case 'F':
11389             c = 'f';            /* maybe %F isn't supported here */
11390             /* FALLTHROUGH */
11391         case 'e': case 'E':
11392         case 'f':
11393         case 'g': case 'G':
11394             if (vectorize)
11395                 goto unknown;
11396
11397             /* This is evil, but floating point is even more evil */
11398
11399             /* for SV-style calling, we can only get NV
11400                for C-style calling, we assume %f is double;
11401                for simplicity we allow any of %Lf, %llf, %qf for long double
11402             */
11403             switch (intsize) {
11404             case 'V':
11405 #if defined(USE_LONG_DOUBLE)
11406                 intsize = 'q';
11407 #endif
11408                 break;
11409 /* [perl #20339] - we should accept and ignore %lf rather than die */
11410             case 'l':
11411                 /* FALLTHROUGH */
11412             default:
11413 #if defined(USE_LONG_DOUBLE)
11414                 intsize = args ? 0 : 'q';
11415 #endif
11416                 break;
11417             case 'q':
11418 #if defined(HAS_LONG_DOUBLE)
11419                 break;
11420 #else
11421                 /* FALLTHROUGH */
11422 #endif
11423             case 'c':
11424             case 'h':
11425             case 'z':
11426             case 't':
11427             case 'j':
11428                 goto unknown;
11429             }
11430
11431             /* now we need (long double) if intsize == 'q', else (double) */
11432             nv = (args) ?
11433 #if LONG_DOUBLESIZE > DOUBLESIZE
11434                 intsize == 'q' ?
11435                     va_arg(*args, long double) :
11436                     va_arg(*args, double)
11437 #else
11438                     va_arg(*args, double)
11439 #endif
11440                 : SvNV(argsv);
11441
11442             need = 0;
11443             /* nv * 0 will be NaN for NaN, +Inf and -Inf, and 0 for anything
11444                else. frexp() has some unspecified behaviour for those three */
11445             if (c != 'e' && c != 'E' && (nv * 0) == 0) {
11446                 i = PERL_INT_MIN;
11447                 /* FIXME: if HAS_LONG_DOUBLE but not USE_LONG_DOUBLE this
11448                    will cast our (long double) to (double) */
11449                 (void)Perl_frexp(nv, &i);
11450                 if (i == PERL_INT_MIN)
11451                     Perl_die(aTHX_ "panic: frexp");
11452                 if (i > 0)
11453                     need = BIT_DIGITS(i);
11454             }
11455             need += has_precis ? precis : 6; /* known default */
11456
11457             if (need < width)
11458                 need = width;
11459
11460 #ifdef HAS_LDBL_SPRINTF_BUG
11461             /* This is to try to fix a bug with irix/nonstop-ux/powerux and
11462                with sfio - Allen <allens@cpan.org> */
11463
11464 #  ifdef DBL_MAX
11465 #    define MY_DBL_MAX DBL_MAX
11466 #  else /* XXX guessing! HUGE_VAL may be defined as infinity, so not using */
11467 #    if DOUBLESIZE >= 8
11468 #      define MY_DBL_MAX 1.7976931348623157E+308L
11469 #    else
11470 #      define MY_DBL_MAX 3.40282347E+38L
11471 #    endif
11472 #  endif
11473
11474 #  ifdef HAS_LDBL_SPRINTF_BUG_LESS1 /* only between -1L & 1L - Allen */
11475 #    define MY_DBL_MAX_BUG 1L
11476 #  else
11477 #    define MY_DBL_MAX_BUG MY_DBL_MAX
11478 #  endif
11479
11480 #  ifdef DBL_MIN
11481 #    define MY_DBL_MIN DBL_MIN
11482 #  else  /* XXX guessing! -Allen */
11483 #    if DOUBLESIZE >= 8
11484 #      define MY_DBL_MIN 2.2250738585072014E-308L
11485 #    else
11486 #      define MY_DBL_MIN 1.17549435E-38L
11487 #    endif
11488 #  endif
11489
11490             if ((intsize == 'q') && (c == 'f') &&
11491                 ((nv < MY_DBL_MAX_BUG) && (nv > -MY_DBL_MAX_BUG)) &&
11492                 (need < DBL_DIG)) {
11493                 /* it's going to be short enough that
11494                  * long double precision is not needed */
11495
11496                 if ((nv <= 0L) && (nv >= -0L))
11497                     fix_ldbl_sprintf_bug = TRUE; /* 0 is 0 - easiest */
11498                 else {
11499                     /* would use Perl_fp_class as a double-check but not
11500                      * functional on IRIX - see perl.h comments */
11501
11502                     if ((nv >= MY_DBL_MIN) || (nv <= -MY_DBL_MIN)) {
11503                         /* It's within the range that a double can represent */
11504 #if defined(DBL_MAX) && !defined(DBL_MIN)
11505                         if ((nv >= ((long double)1/DBL_MAX)) ||
11506                             (nv <= (-(long double)1/DBL_MAX)))
11507 #endif
11508                         fix_ldbl_sprintf_bug = TRUE;
11509                     }
11510                 }
11511                 if (fix_ldbl_sprintf_bug == TRUE) {
11512                     double temp;
11513
11514                     intsize = 0;
11515                     temp = (double)nv;
11516                     nv = (NV)temp;
11517                 }
11518             }
11519
11520 #  undef MY_DBL_MAX
11521 #  undef MY_DBL_MAX_BUG
11522 #  undef MY_DBL_MIN
11523
11524 #endif /* HAS_LDBL_SPRINTF_BUG */
11525
11526             need += 20; /* fudge factor */
11527             if (PL_efloatsize < need) {
11528                 Safefree(PL_efloatbuf);
11529                 PL_efloatsize = need + 20; /* more fudge */
11530                 Newx(PL_efloatbuf, PL_efloatsize, char);
11531                 PL_efloatbuf[0] = '\0';
11532             }
11533
11534             if ( !(width || left || plus || alt) && fill != '0'
11535                  && has_precis && intsize != 'q' ) {    /* Shortcuts */
11536                 /* See earlier comment about buggy Gconvert when digits,
11537                    aka precis is 0  */
11538                 if ( c == 'g' && precis) {
11539                     STORE_LC_NUMERIC_SET_TO_NEEDED();
11540                     PERL_UNUSED_RESULT(Gconvert((NV)nv, (int)precis, 0, PL_efloatbuf));
11541                     /* May return an empty string for digits==0 */
11542                     if (*PL_efloatbuf) {
11543                         elen = strlen(PL_efloatbuf);
11544                         goto float_converted;
11545                     }
11546                 } else if ( c == 'f' && !precis) {
11547                     if ((eptr = F0convert(nv, ebuf + sizeof ebuf, &elen)))
11548                         break;
11549                 }
11550             }
11551             {
11552                 char *ptr = ebuf + sizeof ebuf;
11553                 *--ptr = '\0';
11554                 *--ptr = c;
11555                 /* FIXME: what to do if HAS_LONG_DOUBLE but not PERL_PRIfldbl? */
11556 #if defined(HAS_LONG_DOUBLE) && defined(PERL_PRIfldbl)
11557                 if (intsize == 'q') {
11558                     /* Copy the one or more characters in a long double
11559                      * format before the 'base' ([efgEFG]) character to
11560                      * the format string. */
11561                     static char const prifldbl[] = PERL_PRIfldbl;
11562                     char const *p = prifldbl + sizeof(prifldbl) - 3;
11563                     while (p >= prifldbl) { *--ptr = *p--; }
11564                 }
11565 #endif
11566                 if (has_precis) {
11567                     base = precis;
11568                     do { *--ptr = '0' + (base % 10); } while (base /= 10);
11569                     *--ptr = '.';
11570                 }
11571                 if (width) {
11572                     base = width;
11573                     do { *--ptr = '0' + (base % 10); } while (base /= 10);
11574                 }
11575                 if (fill == '0')
11576                     *--ptr = fill;
11577                 if (left)
11578                     *--ptr = '-';
11579                 if (plus)
11580                     *--ptr = plus;
11581                 if (alt)
11582                     *--ptr = '#';
11583                 *--ptr = '%';
11584
11585                 /* No taint.  Otherwise we are in the strange situation
11586                  * where printf() taints but print($float) doesn't.
11587                  * --jhi */
11588
11589                 STORE_LC_NUMERIC_SET_TO_NEEDED();
11590
11591                 /* hopefully the above makes ptr a very constrained format
11592                  * that is safe to use, even though it's not literal */
11593                 GCC_DIAG_IGNORE(-Wformat-nonliteral);
11594 #if defined(HAS_LONG_DOUBLE)
11595                 elen = ((intsize == 'q')
11596                         ? my_snprintf(PL_efloatbuf, PL_efloatsize, ptr, nv)
11597                         : my_snprintf(PL_efloatbuf, PL_efloatsize, ptr, (double)nv));
11598 #else
11599                 elen = my_sprintf(PL_efloatbuf, ptr, nv);
11600 #endif
11601                 GCC_DIAG_RESTORE;
11602             }
11603         float_converted:
11604             eptr = PL_efloatbuf;
11605
11606 #ifdef USE_LOCALE_NUMERIC
11607             /* If the decimal point character in the string is UTF-8, make the
11608              * output utf8 */
11609             if (PL_numeric_radix_sv && SvUTF8(PL_numeric_radix_sv)
11610                 && instr(eptr, SvPVX_const(PL_numeric_radix_sv)))
11611             {
11612                 is_utf8 = TRUE;
11613             }
11614 #endif
11615
11616             break;
11617
11618             /* SPECIAL */
11619
11620         case 'n':
11621             if (vectorize)
11622                 goto unknown;
11623             i = SvCUR(sv) - origlen;
11624             if (args) {
11625                 switch (intsize) {
11626                 case 'c':       *(va_arg(*args, char*)) = i; break;
11627                 case 'h':       *(va_arg(*args, short*)) = i; break;
11628                 default:        *(va_arg(*args, int*)) = i; break;
11629                 case 'l':       *(va_arg(*args, long*)) = i; break;
11630                 case 'V':       *(va_arg(*args, IV*)) = i; break;
11631                 case 'z':       *(va_arg(*args, SSize_t*)) = i; break;
11632                 case 't':       *(va_arg(*args, ptrdiff_t*)) = i; break;
11633 #ifdef HAS_C99
11634                 case 'j':       *(va_arg(*args, intmax_t*)) = i; break;
11635 #endif
11636                 case 'q':
11637 #if IVSIZE >= 8
11638                                 *(va_arg(*args, Quad_t*)) = i; break;
11639 #else
11640                                 goto unknown;
11641 #endif
11642                 }
11643             }
11644             else
11645                 sv_setuv_mg(argsv, has_utf8 ? (UV)sv_len_utf8(sv) : (UV)i);
11646             continue;   /* not "break" */
11647
11648             /* UNKNOWN */
11649
11650         default:
11651       unknown:
11652             if (!args
11653                 && (PL_op->op_type == OP_PRTF || PL_op->op_type == OP_SPRINTF)
11654                 && ckWARN(WARN_PRINTF))
11655             {
11656                 SV * const msg = sv_newmortal();
11657                 Perl_sv_setpvf(aTHX_ msg, "Invalid conversion in %sprintf: ",
11658                           (PL_op->op_type == OP_PRTF) ? "" : "s");
11659                 if (fmtstart < patend) {
11660                     const char * const fmtend = q < patend ? q : patend;
11661                     const char * f;
11662                     sv_catpvs(msg, "\"%");
11663                     for (f = fmtstart; f < fmtend; f++) {
11664                         if (isPRINT(*f)) {
11665                             sv_catpvn_nomg(msg, f, 1);
11666                         } else {
11667                             Perl_sv_catpvf(aTHX_ msg,
11668                                            "\\%03"UVof, (UV)*f & 0xFF);
11669                         }
11670                     }
11671                     sv_catpvs(msg, "\"");
11672                 } else {
11673                     sv_catpvs(msg, "end of string");
11674                 }
11675                 Perl_warner(aTHX_ packWARN(WARN_PRINTF), "%"SVf, SVfARG(msg)); /* yes, this is reentrant */
11676             }
11677
11678             /* output mangled stuff ... */
11679             if (c == '\0')
11680                 --q;
11681             eptr = p;
11682             elen = q - p;
11683
11684             /* ... right here, because formatting flags should not apply */
11685             SvGROW(sv, SvCUR(sv) + elen + 1);
11686             p = SvEND(sv);
11687             Copy(eptr, p, elen, char);
11688             p += elen;
11689             *p = '\0';
11690             SvCUR_set(sv, p - SvPVX_const(sv));
11691             svix = osvix;
11692             continue;   /* not "break" */
11693         }
11694
11695         if (is_utf8 != has_utf8) {
11696             if (is_utf8) {
11697                 if (SvCUR(sv))
11698                     sv_utf8_upgrade(sv);
11699             }
11700             else {
11701                 const STRLEN old_elen = elen;
11702                 SV * const nsv = newSVpvn_flags(eptr, elen, SVs_TEMP);
11703                 sv_utf8_upgrade(nsv);
11704                 eptr = SvPVX_const(nsv);
11705                 elen = SvCUR(nsv);
11706
11707                 if (width) { /* fudge width (can't fudge elen) */
11708                     width += elen - old_elen;
11709                 }
11710                 is_utf8 = TRUE;
11711             }
11712         }
11713
11714         have = esignlen + zeros + elen;
11715         if (have < zeros)
11716             croak_memory_wrap();
11717
11718         need = (have > width ? have : width);
11719         gap = need - have;
11720
11721         if (need >= (((STRLEN)~0) - SvCUR(sv) - dotstrlen - 1))
11722             croak_memory_wrap();
11723         SvGROW(sv, SvCUR(sv) + need + dotstrlen + 1);
11724         p = SvEND(sv);
11725         if (esignlen && fill == '0') {
11726             int i;
11727             for (i = 0; i < (int)esignlen; i++)
11728                 *p++ = esignbuf[i];
11729         }
11730         if (gap && !left) {
11731             memset(p, fill, gap);
11732             p += gap;
11733         }
11734         if (esignlen && fill != '0') {
11735             int i;
11736             for (i = 0; i < (int)esignlen; i++)
11737                 *p++ = esignbuf[i];
11738         }
11739         if (zeros) {
11740             int i;
11741             for (i = zeros; i; i--)
11742                 *p++ = '0';
11743         }
11744         if (elen) {
11745             Copy(eptr, p, elen, char);
11746             p += elen;
11747         }
11748         if (gap && left) {
11749             memset(p, ' ', gap);
11750             p += gap;
11751         }
11752         if (vectorize) {
11753             if (veclen) {
11754                 Copy(dotstr, p, dotstrlen, char);
11755                 p += dotstrlen;
11756             }
11757             else
11758                 vectorize = FALSE;              /* done iterating over vecstr */
11759         }
11760         if (is_utf8)
11761             has_utf8 = TRUE;
11762         if (has_utf8)
11763             SvUTF8_on(sv);
11764         *p = '\0';
11765         SvCUR_set(sv, p - SvPVX_const(sv));
11766         if (vectorize) {
11767             esignlen = 0;
11768             goto vector;
11769         }
11770     }
11771     SvTAINT(sv);
11772
11773     RESTORE_LC_NUMERIC();   /* Done outside loop, so don't have to save/restore
11774                                each iteration. */
11775 }
11776
11777 /* =========================================================================
11778
11779 =head1 Cloning an interpreter
11780
11781 All the macros and functions in this section are for the private use of
11782 the main function, perl_clone().
11783
11784 The foo_dup() functions make an exact copy of an existing foo thingy.
11785 During the course of a cloning, a hash table is used to map old addresses
11786 to new addresses.  The table is created and manipulated with the
11787 ptr_table_* functions.
11788
11789 =cut
11790
11791  * =========================================================================*/
11792
11793
11794 #if defined(USE_ITHREADS)
11795
11796 /* XXX Remove this so it doesn't have to go thru the macro and return for nothing */
11797 #ifndef GpREFCNT_inc
11798 #  define GpREFCNT_inc(gp)      ((gp) ? (++(gp)->gp_refcnt, (gp)) : (GP*)NULL)
11799 #endif
11800
11801
11802 /* Certain cases in Perl_ss_dup have been merged, by relying on the fact
11803    that currently av_dup, gv_dup and hv_dup are the same as sv_dup.
11804    If this changes, please unmerge ss_dup.
11805    Likewise, sv_dup_inc_multiple() relies on this fact.  */
11806 #define sv_dup_inc_NN(s,t)      SvREFCNT_inc_NN(sv_dup_inc(s,t))
11807 #define av_dup(s,t)     MUTABLE_AV(sv_dup((const SV *)s,t))
11808 #define av_dup_inc(s,t) MUTABLE_AV(sv_dup_inc((const SV *)s,t))
11809 #define hv_dup(s,t)     MUTABLE_HV(sv_dup((const SV *)s,t))
11810 #define hv_dup_inc(s,t) MUTABLE_HV(sv_dup_inc((const SV *)s,t))
11811 #define cv_dup(s,t)     MUTABLE_CV(sv_dup((const SV *)s,t))
11812 #define cv_dup_inc(s,t) MUTABLE_CV(sv_dup_inc((const SV *)s,t))
11813 #define io_dup(s,t)     MUTABLE_IO(sv_dup((const SV *)s,t))
11814 #define io_dup_inc(s,t) MUTABLE_IO(sv_dup_inc((const SV *)s,t))
11815 #define gv_dup(s,t)     MUTABLE_GV(sv_dup((const SV *)s,t))
11816 #define gv_dup_inc(s,t) MUTABLE_GV(sv_dup_inc((const SV *)s,t))
11817 #define SAVEPV(p)       ((p) ? savepv(p) : NULL)
11818 #define SAVEPVN(p,n)    ((p) ? savepvn(p,n) : NULL)
11819
11820 /* clone a parser */
11821
11822 yy_parser *
11823 Perl_parser_dup(pTHX_ const yy_parser *const proto, CLONE_PARAMS *const param)
11824 {
11825     yy_parser *parser;
11826
11827     PERL_ARGS_ASSERT_PARSER_DUP;
11828
11829     if (!proto)
11830         return NULL;
11831
11832     /* look for it in the table first */
11833     parser = (yy_parser *)ptr_table_fetch(PL_ptr_table, proto);
11834     if (parser)
11835         return parser;
11836
11837     /* create anew and remember what it is */
11838     Newxz(parser, 1, yy_parser);
11839     ptr_table_store(PL_ptr_table, proto, parser);
11840
11841     /* XXX these not yet duped */
11842     parser->old_parser = NULL;
11843     parser->stack = NULL;
11844     parser->ps = NULL;
11845     parser->stack_size = 0;
11846     /* XXX parser->stack->state = 0; */
11847
11848     /* XXX eventually, just Copy() most of the parser struct ? */
11849
11850     parser->lex_brackets = proto->lex_brackets;
11851     parser->lex_casemods = proto->lex_casemods;
11852     parser->lex_brackstack = savepvn(proto->lex_brackstack,
11853                     (proto->lex_brackets < 120 ? 120 : proto->lex_brackets));
11854     parser->lex_casestack = savepvn(proto->lex_casestack,
11855                     (proto->lex_casemods < 12 ? 12 : proto->lex_casemods));
11856     parser->lex_defer   = proto->lex_defer;
11857     parser->lex_dojoin  = proto->lex_dojoin;
11858     parser->lex_expect  = proto->lex_expect;
11859     parser->lex_formbrack = proto->lex_formbrack;
11860     parser->lex_inpat   = proto->lex_inpat;
11861     parser->lex_inwhat  = proto->lex_inwhat;
11862     parser->lex_op      = proto->lex_op;
11863     parser->lex_repl    = sv_dup_inc(proto->lex_repl, param);
11864     parser->lex_starts  = proto->lex_starts;
11865     parser->lex_stuff   = sv_dup_inc(proto->lex_stuff, param);
11866     parser->multi_close = proto->multi_close;
11867     parser->multi_open  = proto->multi_open;
11868     parser->multi_start = proto->multi_start;
11869     parser->multi_end   = proto->multi_end;
11870     parser->preambled   = proto->preambled;
11871     parser->sublex_info = proto->sublex_info; /* XXX not quite right */
11872     parser->linestr     = sv_dup_inc(proto->linestr, param);
11873     parser->expect      = proto->expect;
11874     parser->copline     = proto->copline;
11875     parser->last_lop_op = proto->last_lop_op;
11876     parser->lex_state   = proto->lex_state;
11877     parser->rsfp        = fp_dup(proto->rsfp, '<', param);
11878     /* rsfp_filters entries have fake IoDIRP() */
11879     parser->rsfp_filters= av_dup_inc(proto->rsfp_filters, param);
11880     parser->in_my       = proto->in_my;
11881     parser->in_my_stash = hv_dup(proto->in_my_stash, param);
11882     parser->error_count = proto->error_count;
11883
11884
11885     parser->linestr     = sv_dup_inc(proto->linestr, param);
11886
11887     {
11888         char * const ols = SvPVX(proto->linestr);
11889         char * const ls  = SvPVX(parser->linestr);
11890
11891         parser->bufptr      = ls + (proto->bufptr >= ols ?
11892                                     proto->bufptr -  ols : 0);
11893         parser->oldbufptr   = ls + (proto->oldbufptr >= ols ?
11894                                     proto->oldbufptr -  ols : 0);
11895         parser->oldoldbufptr= ls + (proto->oldoldbufptr >= ols ?
11896                                     proto->oldoldbufptr -  ols : 0);
11897         parser->linestart   = ls + (proto->linestart >= ols ?
11898                                     proto->linestart -  ols : 0);
11899         parser->last_uni    = ls + (proto->last_uni >= ols ?
11900                                     proto->last_uni -  ols : 0);
11901         parser->last_lop    = ls + (proto->last_lop >= ols ?
11902                                     proto->last_lop -  ols : 0);
11903
11904         parser->bufend      = ls + SvCUR(parser->linestr);
11905     }
11906
11907     Copy(proto->tokenbuf, parser->tokenbuf, 256, char);
11908
11909
11910 #ifdef PERL_MAD
11911     parser->endwhite    = proto->endwhite;
11912     parser->faketokens  = proto->faketokens;
11913     parser->lasttoke    = proto->lasttoke;
11914     parser->nextwhite   = proto->nextwhite;
11915     parser->realtokenstart = proto->realtokenstart;
11916     parser->skipwhite   = proto->skipwhite;
11917     parser->thisclose   = proto->thisclose;
11918     parser->thismad     = proto->thismad;
11919     parser->thisopen    = proto->thisopen;
11920     parser->thisstuff   = proto->thisstuff;
11921     parser->thistoken   = proto->thistoken;
11922     parser->thiswhite   = proto->thiswhite;
11923
11924     Copy(proto->nexttoke, parser->nexttoke, 5, NEXTTOKE);
11925     parser->curforce    = proto->curforce;
11926 #else
11927     Copy(proto->nextval, parser->nextval, 5, YYSTYPE);
11928     Copy(proto->nexttype, parser->nexttype, 5,  I32);
11929     parser->nexttoke    = proto->nexttoke;
11930 #endif
11931
11932     /* XXX should clone saved_curcop here, but we aren't passed
11933      * proto_perl; so do it in perl_clone_using instead */
11934
11935     return parser;
11936 }
11937
11938
11939 /* duplicate a file handle */
11940
11941 PerlIO *
11942 Perl_fp_dup(pTHX_ PerlIO *const fp, const char type, CLONE_PARAMS *const param)
11943 {
11944     PerlIO *ret;
11945
11946     PERL_ARGS_ASSERT_FP_DUP;
11947     PERL_UNUSED_ARG(type);
11948
11949     if (!fp)
11950         return (PerlIO*)NULL;
11951
11952     /* look for it in the table first */
11953     ret = (PerlIO*)ptr_table_fetch(PL_ptr_table, fp);
11954     if (ret)
11955         return ret;
11956
11957     /* create anew and remember what it is */
11958     ret = PerlIO_fdupopen(aTHX_ fp, param, PERLIO_DUP_CLONE);
11959     ptr_table_store(PL_ptr_table, fp, ret);
11960     return ret;
11961 }
11962
11963 /* duplicate a directory handle */
11964
11965 DIR *
11966 Perl_dirp_dup(pTHX_ DIR *const dp, CLONE_PARAMS *const param)
11967 {
11968     DIR *ret;
11969
11970 #if defined(HAS_FCHDIR) && defined(HAS_TELLDIR) && defined(HAS_SEEKDIR)
11971     DIR *pwd;
11972     const Direntry_t *dirent;
11973     char smallbuf[256];
11974     char *name = NULL;
11975     STRLEN len = 0;
11976     long pos;
11977 #endif
11978
11979     PERL_UNUSED_CONTEXT;
11980     PERL_ARGS_ASSERT_DIRP_DUP;
11981
11982     if (!dp)
11983         return (DIR*)NULL;
11984
11985     /* look for it in the table first */
11986     ret = (DIR*)ptr_table_fetch(PL_ptr_table, dp);
11987     if (ret)
11988         return ret;
11989
11990 #if defined(HAS_FCHDIR) && defined(HAS_TELLDIR) && defined(HAS_SEEKDIR)
11991
11992     PERL_UNUSED_ARG(param);
11993
11994     /* create anew */
11995
11996     /* open the current directory (so we can switch back) */
11997     if (!(pwd = PerlDir_open("."))) return (DIR *)NULL;
11998
11999     /* chdir to our dir handle and open the present working directory */
12000     if (fchdir(my_dirfd(dp)) < 0 || !(ret = PerlDir_open("."))) {
12001         PerlDir_close(pwd);
12002         return (DIR *)NULL;
12003     }
12004     /* Now we should have two dir handles pointing to the same dir. */
12005
12006     /* Be nice to the calling code and chdir back to where we were. */
12007     /* XXX If this fails, then what? */
12008     PERL_UNUSED_RESULT(fchdir(my_dirfd(pwd)));
12009
12010     /* We have no need of the pwd handle any more. */
12011     PerlDir_close(pwd);
12012
12013 #ifdef DIRNAMLEN
12014 # define d_namlen(d) (d)->d_namlen
12015 #else
12016 # define d_namlen(d) strlen((d)->d_name)
12017 #endif
12018     /* Iterate once through dp, to get the file name at the current posi-
12019        tion. Then step back. */
12020     pos = PerlDir_tell(dp);
12021     if ((dirent = PerlDir_read(dp))) {
12022         len = d_namlen(dirent);
12023         if (len <= sizeof smallbuf) name = smallbuf;
12024         else Newx(name, len, char);
12025         Move(dirent->d_name, name, len, char);
12026     }
12027     PerlDir_seek(dp, pos);
12028
12029     /* Iterate through the new dir handle, till we find a file with the
12030        right name. */
12031     if (!dirent) /* just before the end */
12032         for(;;) {
12033             pos = PerlDir_tell(ret);
12034             if (PerlDir_read(ret)) continue; /* not there yet */
12035             PerlDir_seek(ret, pos); /* step back */
12036             break;
12037         }
12038     else {
12039         const long pos0 = PerlDir_tell(ret);
12040         for(;;) {
12041             pos = PerlDir_tell(ret);
12042             if ((dirent = PerlDir_read(ret))) {
12043                 if (len == d_namlen(dirent)
12044                  && memEQ(name, dirent->d_name, len)) {
12045                     /* found it */
12046                     PerlDir_seek(ret, pos); /* step back */
12047                     break;
12048                 }
12049                 /* else we are not there yet; keep iterating */
12050             }
12051             else { /* This is not meant to happen. The best we can do is
12052                       reset the iterator to the beginning. */
12053                 PerlDir_seek(ret, pos0);
12054                 break;
12055             }
12056         }
12057     }
12058 #undef d_namlen
12059
12060     if (name && name != smallbuf)
12061         Safefree(name);
12062 #endif
12063
12064 #ifdef WIN32
12065     ret = win32_dirp_dup(dp, param);
12066 #endif
12067
12068     /* pop it in the pointer table */
12069     if (ret)
12070         ptr_table_store(PL_ptr_table, dp, ret);
12071
12072     return ret;
12073 }
12074
12075 /* duplicate a typeglob */
12076
12077 GP *
12078 Perl_gp_dup(pTHX_ GP *const gp, CLONE_PARAMS *const param)
12079 {
12080     GP *ret;
12081
12082     PERL_ARGS_ASSERT_GP_DUP;
12083
12084     if (!gp)
12085         return (GP*)NULL;
12086     /* look for it in the table first */
12087     ret = (GP*)ptr_table_fetch(PL_ptr_table, gp);
12088     if (ret)
12089         return ret;
12090
12091     /* create anew and remember what it is */
12092     Newxz(ret, 1, GP);
12093     ptr_table_store(PL_ptr_table, gp, ret);
12094
12095     /* clone */
12096     /* ret->gp_refcnt must be 0 before any other dups are called. We're relying
12097        on Newxz() to do this for us.  */
12098     ret->gp_sv          = sv_dup_inc(gp->gp_sv, param);
12099     ret->gp_io          = io_dup_inc(gp->gp_io, param);
12100     ret->gp_form        = cv_dup_inc(gp->gp_form, param);
12101     ret->gp_av          = av_dup_inc(gp->gp_av, param);
12102     ret->gp_hv          = hv_dup_inc(gp->gp_hv, param);
12103     ret->gp_egv = gv_dup(gp->gp_egv, param);/* GvEGV is not refcounted */
12104     ret->gp_cv          = cv_dup_inc(gp->gp_cv, param);
12105     ret->gp_cvgen       = gp->gp_cvgen;
12106     ret->gp_line        = gp->gp_line;
12107     ret->gp_file_hek    = hek_dup(gp->gp_file_hek, param);
12108     return ret;
12109 }
12110
12111 /* duplicate a chain of magic */
12112
12113 MAGIC *
12114 Perl_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *const param)
12115 {
12116     MAGIC *mgret = NULL;
12117     MAGIC **mgprev_p = &mgret;
12118
12119     PERL_ARGS_ASSERT_MG_DUP;
12120
12121     for (; mg; mg = mg->mg_moremagic) {
12122         MAGIC *nmg;
12123
12124         if ((param->flags & CLONEf_JOIN_IN)
12125                 && mg->mg_type == PERL_MAGIC_backref)
12126             /* when joining, we let the individual SVs add themselves to
12127              * backref as needed. */
12128             continue;
12129
12130         Newx(nmg, 1, MAGIC);
12131         *mgprev_p = nmg;
12132         mgprev_p = &(nmg->mg_moremagic);
12133
12134         /* There was a comment "XXX copy dynamic vtable?" but as we don't have
12135            dynamic vtables, I'm not sure why Sarathy wrote it. The comment dates
12136            from the original commit adding Perl_mg_dup() - revision 4538.
12137            Similarly there is the annotation "XXX random ptr?" next to the
12138            assignment to nmg->mg_ptr.  */
12139         *nmg = *mg;
12140
12141         /* FIXME for plugins
12142         if (nmg->mg_type == PERL_MAGIC_qr) {
12143             nmg->mg_obj = MUTABLE_SV(CALLREGDUPE((REGEXP*)nmg->mg_obj, param));
12144         }
12145         else
12146         */
12147         nmg->mg_obj = (nmg->mg_flags & MGf_REFCOUNTED)
12148                           ? nmg->mg_type == PERL_MAGIC_backref
12149                                 /* The backref AV has its reference
12150                                  * count deliberately bumped by 1 */
12151                                 ? SvREFCNT_inc(av_dup_inc((const AV *)
12152                                                     nmg->mg_obj, param))
12153                                 : sv_dup_inc(nmg->mg_obj, param)
12154                           : sv_dup(nmg->mg_obj, param);
12155
12156         if (nmg->mg_ptr && nmg->mg_type != PERL_MAGIC_regex_global) {
12157             if (nmg->mg_len > 0) {
12158                 nmg->mg_ptr     = SAVEPVN(nmg->mg_ptr, nmg->mg_len);
12159                 if (nmg->mg_type == PERL_MAGIC_overload_table &&
12160                         AMT_AMAGIC((AMT*)nmg->mg_ptr))
12161                 {
12162                     AMT * const namtp = (AMT*)nmg->mg_ptr;
12163                     sv_dup_inc_multiple((SV**)(namtp->table),
12164                                         (SV**)(namtp->table), NofAMmeth, param);
12165                 }
12166             }
12167             else if (nmg->mg_len == HEf_SVKEY)
12168                 nmg->mg_ptr = (char*)sv_dup_inc((const SV *)nmg->mg_ptr, param);
12169         }
12170         if ((nmg->mg_flags & MGf_DUP) && nmg->mg_virtual && nmg->mg_virtual->svt_dup) {
12171             nmg->mg_virtual->svt_dup(aTHX_ nmg, param);
12172         }
12173     }
12174     return mgret;
12175 }
12176
12177 #endif /* USE_ITHREADS */
12178
12179 struct ptr_tbl_arena {
12180     struct ptr_tbl_arena *next;
12181     struct ptr_tbl_ent array[1023/3]; /* as ptr_tbl_ent has 3 pointers.  */
12182 };
12183
12184 /* create a new pointer-mapping table */
12185
12186 PTR_TBL_t *
12187 Perl_ptr_table_new(pTHX)
12188 {
12189     PTR_TBL_t *tbl;
12190     PERL_UNUSED_CONTEXT;
12191
12192     Newx(tbl, 1, PTR_TBL_t);
12193     tbl->tbl_max        = 511;
12194     tbl->tbl_items      = 0;
12195     tbl->tbl_arena      = NULL;
12196     tbl->tbl_arena_next = NULL;
12197     tbl->tbl_arena_end  = NULL;
12198     Newxz(tbl->tbl_ary, tbl->tbl_max + 1, PTR_TBL_ENT_t*);
12199     return tbl;
12200 }
12201
12202 #define PTR_TABLE_HASH(ptr) \
12203   ((PTR2UV(ptr) >> 3) ^ (PTR2UV(ptr) >> (3 + 7)) ^ (PTR2UV(ptr) >> (3 + 17)))
12204
12205 /* map an existing pointer using a table */
12206
12207 STATIC PTR_TBL_ENT_t *
12208 S_ptr_table_find(PTR_TBL_t *const tbl, const void *const sv)
12209 {
12210     PTR_TBL_ENT_t *tblent;
12211     const UV hash = PTR_TABLE_HASH(sv);
12212
12213     PERL_ARGS_ASSERT_PTR_TABLE_FIND;
12214
12215     tblent = tbl->tbl_ary[hash & tbl->tbl_max];
12216     for (; tblent; tblent = tblent->next) {
12217         if (tblent->oldval == sv)
12218             return tblent;
12219     }
12220     return NULL;
12221 }
12222
12223 void *
12224 Perl_ptr_table_fetch(pTHX_ PTR_TBL_t *const tbl, const void *const sv)
12225 {
12226     PTR_TBL_ENT_t const *const tblent = ptr_table_find(tbl, sv);
12227
12228     PERL_ARGS_ASSERT_PTR_TABLE_FETCH;
12229     PERL_UNUSED_CONTEXT;
12230
12231     return tblent ? tblent->newval : NULL;
12232 }
12233
12234 /* add a new entry to a pointer-mapping table 'tbl'.  In hash terms, 'oldsv' is
12235  * the key; 'newsv' is the value.  The names "old" and "new" are specific to
12236  * the core's typical use of ptr_tables in thread cloning. */
12237
12238 void
12239 Perl_ptr_table_store(pTHX_ PTR_TBL_t *const tbl, const void *const oldsv, void *const newsv)
12240 {
12241     PTR_TBL_ENT_t *tblent = ptr_table_find(tbl, oldsv);
12242
12243     PERL_ARGS_ASSERT_PTR_TABLE_STORE;
12244     PERL_UNUSED_CONTEXT;
12245
12246     if (tblent) {
12247         tblent->newval = newsv;
12248     } else {
12249         const UV entry = PTR_TABLE_HASH(oldsv) & tbl->tbl_max;
12250
12251         if (tbl->tbl_arena_next == tbl->tbl_arena_end) {
12252             struct ptr_tbl_arena *new_arena;
12253
12254             Newx(new_arena, 1, struct ptr_tbl_arena);
12255             new_arena->next = tbl->tbl_arena;
12256             tbl->tbl_arena = new_arena;
12257             tbl->tbl_arena_next = new_arena->array;
12258             tbl->tbl_arena_end = C_ARRAY_END(new_arena->array);
12259         }
12260
12261         tblent = tbl->tbl_arena_next++;
12262
12263         tblent->oldval = oldsv;
12264         tblent->newval = newsv;
12265         tblent->next = tbl->tbl_ary[entry];
12266         tbl->tbl_ary[entry] = tblent;
12267         tbl->tbl_items++;
12268         if (tblent->next && tbl->tbl_items > tbl->tbl_max)
12269             ptr_table_split(tbl);
12270     }
12271 }
12272
12273 /* double the hash bucket size of an existing ptr table */
12274
12275 void
12276 Perl_ptr_table_split(pTHX_ PTR_TBL_t *const tbl)
12277 {
12278     PTR_TBL_ENT_t **ary = tbl->tbl_ary;
12279     const UV oldsize = tbl->tbl_max + 1;
12280     UV newsize = oldsize * 2;
12281     UV i;
12282
12283     PERL_ARGS_ASSERT_PTR_TABLE_SPLIT;
12284     PERL_UNUSED_CONTEXT;
12285
12286     Renew(ary, newsize, PTR_TBL_ENT_t*);
12287     Zero(&ary[oldsize], newsize-oldsize, PTR_TBL_ENT_t*);
12288     tbl->tbl_max = --newsize;
12289     tbl->tbl_ary = ary;
12290     for (i=0; i < oldsize; i++, ary++) {
12291         PTR_TBL_ENT_t **entp = ary;
12292         PTR_TBL_ENT_t *ent = *ary;
12293         PTR_TBL_ENT_t **curentp;
12294         if (!ent)
12295             continue;
12296         curentp = ary + oldsize;
12297         do {
12298             if ((newsize & PTR_TABLE_HASH(ent->oldval)) != i) {
12299                 *entp = ent->next;
12300                 ent->next = *curentp;
12301                 *curentp = ent;
12302             }
12303             else
12304                 entp = &ent->next;
12305             ent = *entp;
12306         } while (ent);
12307     }
12308 }
12309
12310 /* remove all the entries from a ptr table */
12311 /* Deprecated - will be removed post 5.14 */
12312
12313 void
12314 Perl_ptr_table_clear(pTHX_ PTR_TBL_t *const tbl)
12315 {
12316     if (tbl && tbl->tbl_items) {
12317         struct ptr_tbl_arena *arena = tbl->tbl_arena;
12318
12319         Zero(tbl->tbl_ary, tbl->tbl_max + 1, struct ptr_tbl_ent **);
12320
12321         while (arena) {
12322             struct ptr_tbl_arena *next = arena->next;
12323
12324             Safefree(arena);
12325             arena = next;
12326         };
12327
12328         tbl->tbl_items = 0;
12329         tbl->tbl_arena = NULL;
12330         tbl->tbl_arena_next = NULL;
12331         tbl->tbl_arena_end = NULL;
12332     }
12333 }
12334
12335 /* clear and free a ptr table */
12336
12337 void
12338 Perl_ptr_table_free(pTHX_ PTR_TBL_t *const tbl)
12339 {
12340     struct ptr_tbl_arena *arena;
12341
12342     if (!tbl) {
12343         return;
12344     }
12345
12346     arena = tbl->tbl_arena;
12347
12348     while (arena) {
12349         struct ptr_tbl_arena *next = arena->next;
12350
12351         Safefree(arena);
12352         arena = next;
12353     }
12354
12355     Safefree(tbl->tbl_ary);
12356     Safefree(tbl);
12357 }
12358
12359 #if defined(USE_ITHREADS)
12360
12361 void
12362 Perl_rvpv_dup(pTHX_ SV *const dstr, const SV *const sstr, CLONE_PARAMS *const param)
12363 {
12364     PERL_ARGS_ASSERT_RVPV_DUP;
12365
12366     assert(!isREGEXP(sstr));
12367     if (SvROK(sstr)) {
12368         if (SvWEAKREF(sstr)) {
12369             SvRV_set(dstr, sv_dup(SvRV_const(sstr), param));
12370             if (param->flags & CLONEf_JOIN_IN) {
12371                 /* if joining, we add any back references individually rather
12372                  * than copying the whole backref array */
12373                 Perl_sv_add_backref(aTHX_ SvRV(dstr), dstr);
12374             }
12375         }
12376         else
12377             SvRV_set(dstr, sv_dup_inc(SvRV_const(sstr), param));
12378     }
12379     else if (SvPVX_const(sstr)) {
12380         /* Has something there */
12381         if (SvLEN(sstr)) {
12382             /* Normal PV - clone whole allocated space */
12383             SvPV_set(dstr, SAVEPVN(SvPVX_const(sstr), SvLEN(sstr)-1));
12384             /* sstr may not be that normal, but actually copy on write.
12385                But we are a true, independent SV, so:  */
12386             SvIsCOW_off(dstr);
12387         }
12388         else {
12389             /* Special case - not normally malloced for some reason */
12390             if (isGV_with_GP(sstr)) {
12391                 /* Don't need to do anything here.  */
12392             }
12393             else if ((SvIsCOW(sstr))) {
12394                 /* A "shared" PV - clone it as "shared" PV */
12395                 SvPV_set(dstr,
12396                          HEK_KEY(hek_dup(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)),
12397                                          param)));
12398             }
12399             else {
12400                 /* Some other special case - random pointer */
12401                 SvPV_set(dstr, (char *) SvPVX_const(sstr));             
12402             }
12403         }
12404     }
12405     else {
12406         /* Copy the NULL */
12407         SvPV_set(dstr, NULL);
12408     }
12409 }
12410
12411 /* duplicate a list of SVs. source and dest may point to the same memory.  */
12412 static SV **
12413 S_sv_dup_inc_multiple(pTHX_ SV *const *source, SV **dest,
12414                       SSize_t items, CLONE_PARAMS *const param)
12415 {
12416     PERL_ARGS_ASSERT_SV_DUP_INC_MULTIPLE;
12417
12418     while (items-- > 0) {
12419         *dest++ = sv_dup_inc(*source++, param);
12420     }
12421
12422     return dest;
12423 }
12424
12425 /* duplicate an SV of any type (including AV, HV etc) */
12426
12427 static SV *
12428 S_sv_dup_common(pTHX_ const SV *const sstr, CLONE_PARAMS *const param)
12429 {
12430     dVAR;
12431     SV *dstr;
12432
12433     PERL_ARGS_ASSERT_SV_DUP_COMMON;
12434
12435     if (SvTYPE(sstr) == (svtype)SVTYPEMASK) {
12436 #ifdef DEBUG_LEAKING_SCALARS_ABORT
12437         abort();
12438 #endif
12439         return NULL;
12440     }
12441     /* look for it in the table first */
12442     dstr = MUTABLE_SV(ptr_table_fetch(PL_ptr_table, sstr));
12443     if (dstr)
12444         return dstr;
12445
12446     if(param->flags & CLONEf_JOIN_IN) {
12447         /** We are joining here so we don't want do clone
12448             something that is bad **/
12449         if (SvTYPE(sstr) == SVt_PVHV) {
12450             const HEK * const hvname = HvNAME_HEK(sstr);
12451             if (hvname) {
12452                 /** don't clone stashes if they already exist **/
12453                 dstr = MUTABLE_SV(gv_stashpvn(HEK_KEY(hvname), HEK_LEN(hvname),
12454                                                 HEK_UTF8(hvname) ? SVf_UTF8 : 0));
12455                 ptr_table_store(PL_ptr_table, sstr, dstr);
12456                 return dstr;
12457             }
12458         }
12459         else if (SvTYPE(sstr) == SVt_PVGV && !SvFAKE(sstr)) {
12460             HV *stash = GvSTASH(sstr);
12461             const HEK * hvname;
12462             if (stash && (hvname = HvNAME_HEK(stash))) {
12463                 /** don't clone GVs if they already exist **/
12464                 SV **svp;
12465                 stash = gv_stashpvn(HEK_KEY(hvname), HEK_LEN(hvname),
12466                                     HEK_UTF8(hvname) ? SVf_UTF8 : 0);
12467                 svp = hv_fetch(
12468                         stash, GvNAME(sstr),
12469                         GvNAMEUTF8(sstr)
12470                             ? -GvNAMELEN(sstr)
12471                             :  GvNAMELEN(sstr),
12472                         0
12473                       );
12474                 if (svp && *svp && SvTYPE(*svp) == SVt_PVGV) {
12475                     ptr_table_store(PL_ptr_table, sstr, *svp);
12476                     return *svp;
12477                 }
12478             }
12479         }
12480     }
12481
12482     /* create anew and remember what it is */
12483     new_SV(dstr);
12484
12485 #ifdef DEBUG_LEAKING_SCALARS
12486     dstr->sv_debug_optype = sstr->sv_debug_optype;
12487     dstr->sv_debug_line = sstr->sv_debug_line;
12488     dstr->sv_debug_inpad = sstr->sv_debug_inpad;
12489     dstr->sv_debug_parent = (SV*)sstr;
12490     FREE_SV_DEBUG_FILE(dstr);
12491     dstr->sv_debug_file = savesharedpv(sstr->sv_debug_file);
12492 #endif
12493
12494     ptr_table_store(PL_ptr_table, sstr, dstr);
12495
12496     /* clone */
12497     SvFLAGS(dstr)       = SvFLAGS(sstr);
12498     SvFLAGS(dstr)       &= ~SVf_OOK;            /* don't propagate OOK hack */
12499     SvREFCNT(dstr)      = 0;                    /* must be before any other dups! */
12500
12501 #ifdef DEBUGGING
12502     if (SvANY(sstr) && PL_watch_pvx && SvPVX_const(sstr) == PL_watch_pvx)
12503         PerlIO_printf(Perl_debug_log, "watch at %p hit, found string \"%s\"\n",
12504                       (void*)PL_watch_pvx, SvPVX_const(sstr));
12505 #endif
12506
12507     /* don't clone objects whose class has asked us not to */
12508     if (SvOBJECT(sstr) && ! (SvFLAGS(SvSTASH(sstr)) & SVphv_CLONEABLE)) {
12509         SvFLAGS(dstr) = 0;
12510         return dstr;
12511     }
12512
12513     switch (SvTYPE(sstr)) {
12514     case SVt_NULL:
12515         SvANY(dstr)     = NULL;
12516         break;
12517     case SVt_IV:
12518         SvANY(dstr)     = (XPVIV*)((char*)&(dstr->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
12519         if(SvROK(sstr)) {
12520             Perl_rvpv_dup(aTHX_ dstr, sstr, param);
12521         } else {
12522             SvIV_set(dstr, SvIVX(sstr));
12523         }
12524         break;
12525     case SVt_NV:
12526         SvANY(dstr)     = new_XNV();
12527         SvNV_set(dstr, SvNVX(sstr));
12528         break;
12529     default:
12530         {
12531             /* These are all the types that need complex bodies allocating.  */
12532             void *new_body;
12533             const svtype sv_type = SvTYPE(sstr);
12534             const struct body_details *const sv_type_details
12535                 = bodies_by_type + sv_type;
12536
12537             switch (sv_type) {
12538             default:
12539                 Perl_croak(aTHX_ "Bizarre SvTYPE [%" IVdf "]", (IV)SvTYPE(sstr));
12540                 break;
12541
12542             case SVt_PVGV:
12543             case SVt_PVIO:
12544             case SVt_PVFM:
12545             case SVt_PVHV:
12546             case SVt_PVAV:
12547             case SVt_PVCV:
12548             case SVt_PVLV:
12549             case SVt_REGEXP:
12550             case SVt_PVMG:
12551             case SVt_PVNV:
12552             case SVt_PVIV:
12553             case SVt_INVLIST:
12554             case SVt_PV:
12555                 assert(sv_type_details->body_size);
12556                 if (sv_type_details->arena) {
12557                     new_body_inline(new_body, sv_type);
12558                     new_body
12559                         = (void*)((char*)new_body - sv_type_details->offset);
12560                 } else {
12561                     new_body = new_NOARENA(sv_type_details);
12562                 }
12563             }
12564             assert(new_body);
12565             SvANY(dstr) = new_body;
12566
12567 #ifndef PURIFY
12568             Copy(((char*)SvANY(sstr)) + sv_type_details->offset,
12569                  ((char*)SvANY(dstr)) + sv_type_details->offset,
12570                  sv_type_details->copy, char);
12571 #else
12572             Copy(((char*)SvANY(sstr)),
12573                  ((char*)SvANY(dstr)),
12574                  sv_type_details->body_size + sv_type_details->offset, char);
12575 #endif
12576
12577             if (sv_type != SVt_PVAV && sv_type != SVt_PVHV
12578                 && !isGV_with_GP(dstr)
12579                 && !isREGEXP(dstr)
12580                 && !(sv_type == SVt_PVIO && !(IoFLAGS(dstr) & IOf_FAKE_DIRP)))
12581                 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
12582
12583             /* The Copy above means that all the source (unduplicated) pointers
12584                are now in the destination.  We can check the flags and the
12585                pointers in either, but it's possible that there's less cache
12586                missing by always going for the destination.
12587                FIXME - instrument and check that assumption  */
12588             if (sv_type >= SVt_PVMG) {
12589                 if ((sv_type == SVt_PVMG) && SvPAD_OUR(dstr)) {
12590                     SvOURSTASH_set(dstr, hv_dup_inc(SvOURSTASH(dstr), param));
12591                 } else if (sv_type == SVt_PVAV && AvPAD_NAMELIST(dstr)) {
12592                     NOOP;
12593                 } else if (SvMAGIC(dstr))
12594                     SvMAGIC_set(dstr, mg_dup(SvMAGIC(dstr), param));
12595                 if (SvOBJECT(dstr) && SvSTASH(dstr))
12596                     SvSTASH_set(dstr, hv_dup_inc(SvSTASH(dstr), param));
12597                 else SvSTASH_set(dstr, 0); /* don't copy DESTROY cache */
12598             }
12599
12600             /* The cast silences a GCC warning about unhandled types.  */
12601             switch ((int)sv_type) {
12602             case SVt_PV:
12603                 break;
12604             case SVt_PVIV:
12605                 break;
12606             case SVt_PVNV:
12607                 break;
12608             case SVt_PVMG:
12609                 break;
12610             case SVt_REGEXP:
12611               duprex:
12612                 /* FIXME for plugins */
12613                 dstr->sv_u.svu_rx = ((REGEXP *)dstr)->sv_any;
12614                 re_dup_guts((REGEXP*) sstr, (REGEXP*) dstr, param);
12615                 break;
12616             case SVt_PVLV:
12617                 /* XXX LvTARGOFF sometimes holds PMOP* when DEBUGGING */
12618                 if (LvTYPE(dstr) == 't') /* for tie: unrefcnted fake (SV**) */
12619                     LvTARG(dstr) = dstr;
12620                 else if (LvTYPE(dstr) == 'T') /* for tie: fake HE */
12621                     LvTARG(dstr) = MUTABLE_SV(he_dup((HE*)LvTARG(dstr), 0, param));
12622                 else
12623                     LvTARG(dstr) = sv_dup_inc(LvTARG(dstr), param);
12624                 if (isREGEXP(sstr)) goto duprex;
12625             case SVt_PVGV:
12626                 /* non-GP case already handled above */
12627                 if(isGV_with_GP(sstr)) {
12628                     GvNAME_HEK(dstr) = hek_dup(GvNAME_HEK(dstr), param);
12629                     /* Don't call sv_add_backref here as it's going to be
12630                        created as part of the magic cloning of the symbol
12631                        table--unless this is during a join and the stash
12632                        is not actually being cloned.  */
12633                     /* Danger Will Robinson - GvGP(dstr) isn't initialised
12634                        at the point of this comment.  */
12635                     GvSTASH(dstr) = hv_dup(GvSTASH(dstr), param);
12636                     if (param->flags & CLONEf_JOIN_IN)
12637                         Perl_sv_add_backref(aTHX_ MUTABLE_SV(GvSTASH(dstr)), dstr);
12638                     GvGP_set(dstr, gp_dup(GvGP(sstr), param));
12639                     (void)GpREFCNT_inc(GvGP(dstr));
12640                 }
12641                 break;
12642             case SVt_PVIO:
12643                 /* PL_parser->rsfp_filters entries have fake IoDIRP() */
12644                 if(IoFLAGS(dstr) & IOf_FAKE_DIRP) {
12645                     /* I have no idea why fake dirp (rsfps)
12646                        should be treated differently but otherwise
12647                        we end up with leaks -- sky*/
12648                     IoTOP_GV(dstr)      = gv_dup_inc(IoTOP_GV(dstr), param);
12649                     IoFMT_GV(dstr)      = gv_dup_inc(IoFMT_GV(dstr), param);
12650                     IoBOTTOM_GV(dstr)   = gv_dup_inc(IoBOTTOM_GV(dstr), param);
12651                 } else {
12652                     IoTOP_GV(dstr)      = gv_dup(IoTOP_GV(dstr), param);
12653                     IoFMT_GV(dstr)      = gv_dup(IoFMT_GV(dstr), param);
12654                     IoBOTTOM_GV(dstr)   = gv_dup(IoBOTTOM_GV(dstr), param);
12655                     if (IoDIRP(dstr)) {
12656                         IoDIRP(dstr)    = dirp_dup(IoDIRP(dstr), param);
12657                     } else {
12658                         NOOP;
12659                         /* IoDIRP(dstr) is already a copy of IoDIRP(sstr)  */
12660                     }
12661                     IoIFP(dstr) = fp_dup(IoIFP(sstr), IoTYPE(dstr), param);
12662                 }
12663                 if (IoOFP(dstr) == IoIFP(sstr))
12664                     IoOFP(dstr) = IoIFP(dstr);
12665                 else
12666                     IoOFP(dstr) = fp_dup(IoOFP(dstr), IoTYPE(dstr), param);
12667                 IoTOP_NAME(dstr)        = SAVEPV(IoTOP_NAME(dstr));
12668                 IoFMT_NAME(dstr)        = SAVEPV(IoFMT_NAME(dstr));
12669                 IoBOTTOM_NAME(dstr)     = SAVEPV(IoBOTTOM_NAME(dstr));
12670                 break;
12671             case SVt_PVAV:
12672                 /* avoid cloning an empty array */
12673                 if (AvARRAY((const AV *)sstr) && AvFILLp((const AV *)sstr) >= 0) {
12674                     SV **dst_ary, **src_ary;
12675                     SSize_t items = AvFILLp((const AV *)sstr) + 1;
12676
12677                     src_ary = AvARRAY((const AV *)sstr);
12678                     Newxz(dst_ary, AvMAX((const AV *)sstr)+1, SV*);
12679                     ptr_table_store(PL_ptr_table, src_ary, dst_ary);
12680                     AvARRAY(MUTABLE_AV(dstr)) = dst_ary;
12681                     AvALLOC((const AV *)dstr) = dst_ary;
12682                     if (AvREAL((const AV *)sstr)) {
12683                         dst_ary = sv_dup_inc_multiple(src_ary, dst_ary, items,
12684                                                       param);
12685                     }
12686                     else {
12687                         while (items-- > 0)
12688                             *dst_ary++ = sv_dup(*src_ary++, param);
12689                     }
12690                     items = AvMAX((const AV *)sstr) - AvFILLp((const AV *)sstr);
12691                     while (items-- > 0) {
12692                         *dst_ary++ = &PL_sv_undef;
12693                     }
12694                 }
12695                 else {
12696                     AvARRAY(MUTABLE_AV(dstr))   = NULL;
12697                     AvALLOC((const AV *)dstr)   = (SV**)NULL;
12698                     AvMAX(  (const AV *)dstr)   = -1;
12699                     AvFILLp((const AV *)dstr)   = -1;
12700                 }
12701                 break;
12702             case SVt_PVHV:
12703                 if (HvARRAY((const HV *)sstr)) {
12704                     STRLEN i = 0;
12705                     const bool sharekeys = !!HvSHAREKEYS(sstr);
12706                     XPVHV * const dxhv = (XPVHV*)SvANY(dstr);
12707                     XPVHV * const sxhv = (XPVHV*)SvANY(sstr);
12708                     char *darray;
12709                     Newx(darray, PERL_HV_ARRAY_ALLOC_BYTES(dxhv->xhv_max+1)
12710                         + (SvOOK(sstr) ? sizeof(struct xpvhv_aux) : 0),
12711                         char);
12712                     HvARRAY(dstr) = (HE**)darray;
12713                     while (i <= sxhv->xhv_max) {
12714                         const HE * const source = HvARRAY(sstr)[i];
12715                         HvARRAY(dstr)[i] = source
12716                             ? he_dup(source, sharekeys, param) : 0;
12717                         ++i;
12718                     }
12719                     if (SvOOK(sstr)) {
12720                         const struct xpvhv_aux * const saux = HvAUX(sstr);
12721                         struct xpvhv_aux * const daux = HvAUX(dstr);
12722                         /* This flag isn't copied.  */
12723                         SvOOK_on(dstr);
12724
12725                         if (saux->xhv_name_count) {
12726                             HEK ** const sname = saux->xhv_name_u.xhvnameu_names;
12727                             const I32 count
12728                              = saux->xhv_name_count < 0
12729                                 ? -saux->xhv_name_count
12730                                 :  saux->xhv_name_count;
12731                             HEK **shekp = sname + count;
12732                             HEK **dhekp;
12733                             Newx(daux->xhv_name_u.xhvnameu_names, count, HEK *);
12734                             dhekp = daux->xhv_name_u.xhvnameu_names + count;
12735                             while (shekp-- > sname) {
12736                                 dhekp--;
12737                                 *dhekp = hek_dup(*shekp, param);
12738                             }
12739                         }
12740                         else {
12741                             daux->xhv_name_u.xhvnameu_name
12742                                 = hek_dup(saux->xhv_name_u.xhvnameu_name,
12743                                           param);
12744                         }
12745                         daux->xhv_name_count = saux->xhv_name_count;
12746
12747                         daux->xhv_fill_lazy = saux->xhv_fill_lazy;
12748                         daux->xhv_aux_flags = saux->xhv_aux_flags;
12749 #ifdef PERL_HASH_RANDOMIZE_KEYS
12750                         daux->xhv_rand = saux->xhv_rand;
12751                         daux->xhv_last_rand = saux->xhv_last_rand;
12752 #endif
12753                         daux->xhv_riter = saux->xhv_riter;
12754                         daux->xhv_eiter = saux->xhv_eiter
12755                             ? he_dup(saux->xhv_eiter,
12756                                         cBOOL(HvSHAREKEYS(sstr)), param) : 0;
12757                         /* backref array needs refcnt=2; see sv_add_backref */
12758                         daux->xhv_backreferences =
12759                             (param->flags & CLONEf_JOIN_IN)
12760                                 /* when joining, we let the individual GVs and
12761                                  * CVs add themselves to backref as
12762                                  * needed. This avoids pulling in stuff
12763                                  * that isn't required, and simplifies the
12764                                  * case where stashes aren't cloned back
12765                                  * if they already exist in the parent
12766                                  * thread */
12767                             ? NULL
12768                             : saux->xhv_backreferences
12769                                 ? (SvTYPE(saux->xhv_backreferences) == SVt_PVAV)
12770                                     ? MUTABLE_AV(SvREFCNT_inc(
12771                                           sv_dup_inc((const SV *)
12772                                             saux->xhv_backreferences, param)))
12773                                     : MUTABLE_AV(sv_dup((const SV *)
12774                                             saux->xhv_backreferences, param))
12775                                 : 0;
12776
12777                         daux->xhv_mro_meta = saux->xhv_mro_meta
12778                             ? mro_meta_dup(saux->xhv_mro_meta, param)
12779                             : 0;
12780
12781                         /* Record stashes for possible cloning in Perl_clone(). */
12782                         if (HvNAME(sstr))
12783                             av_push(param->stashes, dstr);
12784                     }
12785                 }
12786                 else
12787                     HvARRAY(MUTABLE_HV(dstr)) = NULL;
12788                 break;
12789             case SVt_PVCV:
12790                 if (!(param->flags & CLONEf_COPY_STACKS)) {
12791                     CvDEPTH(dstr) = 0;
12792                 }
12793                 /* FALLTHROUGH */
12794             case SVt_PVFM:
12795                 /* NOTE: not refcounted */
12796                 SvANY(MUTABLE_CV(dstr))->xcv_stash =
12797                     hv_dup(CvSTASH(dstr), param);
12798                 if ((param->flags & CLONEf_JOIN_IN) && CvSTASH(dstr))
12799                     Perl_sv_add_backref(aTHX_ MUTABLE_SV(CvSTASH(dstr)), dstr);
12800                 if (!CvISXSUB(dstr)) {
12801                     OP_REFCNT_LOCK;
12802                     CvROOT(dstr) = OpREFCNT_inc(CvROOT(dstr));
12803                     OP_REFCNT_UNLOCK;
12804                     CvSLABBED_off(dstr);
12805                 } else if (CvCONST(dstr)) {
12806                     CvXSUBANY(dstr).any_ptr =
12807                         sv_dup_inc((const SV *)CvXSUBANY(dstr).any_ptr, param);
12808                 }
12809                 assert(!CvSLABBED(dstr));
12810                 if (CvDYNFILE(dstr)) CvFILE(dstr) = SAVEPV(CvFILE(dstr));
12811                 if (CvNAMED(dstr))
12812                     SvANY((CV *)dstr)->xcv_gv_u.xcv_hek =
12813                         share_hek_hek(CvNAME_HEK((CV *)sstr));
12814                 /* don't dup if copying back - CvGV isn't refcounted, so the
12815                  * duped GV may never be freed. A bit of a hack! DAPM */
12816                 else
12817                   SvANY(MUTABLE_CV(dstr))->xcv_gv_u.xcv_gv =
12818                     CvCVGV_RC(dstr)
12819                     ? gv_dup_inc(CvGV(sstr), param)
12820                     : (param->flags & CLONEf_JOIN_IN)
12821                         ? NULL
12822                         : gv_dup(CvGV(sstr), param);
12823
12824                 CvPADLIST(dstr) = padlist_dup(CvPADLIST(sstr), param);
12825                 CvOUTSIDE(dstr) =
12826                     CvWEAKOUTSIDE(sstr)
12827                     ? cv_dup(    CvOUTSIDE(dstr), param)
12828                     : cv_dup_inc(CvOUTSIDE(dstr), param);
12829                 break;
12830             }
12831         }
12832     }
12833
12834     return dstr;
12835  }
12836
12837 SV *
12838 Perl_sv_dup_inc(pTHX_ const SV *const sstr, CLONE_PARAMS *const param)
12839 {
12840     PERL_ARGS_ASSERT_SV_DUP_INC;
12841     return sstr ? SvREFCNT_inc(sv_dup_common(sstr, param)) : NULL;
12842 }
12843
12844 SV *
12845 Perl_sv_dup(pTHX_ const SV *const sstr, CLONE_PARAMS *const param)
12846 {
12847     SV *dstr = sstr ? sv_dup_common(sstr, param) : NULL;
12848     PERL_ARGS_ASSERT_SV_DUP;
12849
12850     /* Track every SV that (at least initially) had a reference count of 0.
12851        We need to do this by holding an actual reference to it in this array.
12852        If we attempt to cheat, turn AvREAL_off(), and store only pointers
12853        (akin to the stashes hash, and the perl stack), we come unstuck if
12854        a weak reference (or other SV legitimately SvREFCNT() == 0 for this
12855        thread) is manipulated in a CLONE method, because CLONE runs before the
12856        unreferenced array is walked to find SVs still with SvREFCNT() == 0
12857        (and fix things up by giving each a reference via the temps stack).
12858        Instead, during CLONE, if the 0-referenced SV has SvREFCNT_inc() and
12859        then SvREFCNT_dec(), it will be cleaned up (and added to the free list)
12860        before the walk of unreferenced happens and a reference to that is SV
12861        added to the temps stack. At which point we have the same SV considered
12862        to be in use, and free to be re-used. Not good.
12863     */
12864     if (dstr && !(param->flags & CLONEf_COPY_STACKS) && !SvREFCNT(dstr)) {
12865         assert(param->unreferenced);
12866         av_push(param->unreferenced, SvREFCNT_inc(dstr));
12867     }
12868
12869     return dstr;
12870 }
12871
12872 /* duplicate a context */
12873
12874 PERL_CONTEXT *
12875 Perl_cx_dup(pTHX_ PERL_CONTEXT *cxs, I32 ix, I32 max, CLONE_PARAMS* param)
12876 {
12877     PERL_CONTEXT *ncxs;
12878
12879     PERL_ARGS_ASSERT_CX_DUP;
12880
12881     if (!cxs)
12882         return (PERL_CONTEXT*)NULL;
12883
12884     /* look for it in the table first */
12885     ncxs = (PERL_CONTEXT*)ptr_table_fetch(PL_ptr_table, cxs);
12886     if (ncxs)
12887         return ncxs;
12888
12889     /* create anew and remember what it is */
12890     Newx(ncxs, max + 1, PERL_CONTEXT);
12891     ptr_table_store(PL_ptr_table, cxs, ncxs);
12892     Copy(cxs, ncxs, max + 1, PERL_CONTEXT);
12893
12894     while (ix >= 0) {
12895         PERL_CONTEXT * const ncx = &ncxs[ix];
12896         if (CxTYPE(ncx) == CXt_SUBST) {
12897             Perl_croak(aTHX_ "Cloning substitution context is unimplemented");
12898         }
12899         else {
12900             ncx->blk_oldcop = (COP*)any_dup(ncx->blk_oldcop, param->proto_perl);
12901             switch (CxTYPE(ncx)) {
12902             case CXt_SUB:
12903                 ncx->blk_sub.cv         = (ncx->blk_sub.olddepth == 0
12904                                            ? cv_dup_inc(ncx->blk_sub.cv, param)
12905                                            : cv_dup(ncx->blk_sub.cv,param));
12906                 if(CxHASARGS(ncx)){
12907                     ncx->blk_sub.argarray = av_dup_inc(ncx->blk_sub.argarray,param);
12908                     ncx->blk_sub.savearray = av_dup_inc(ncx->blk_sub.savearray,param);
12909                 } else {
12910                     ncx->blk_sub.argarray = NULL;
12911                     ncx->blk_sub.savearray = NULL;
12912                 }
12913                 ncx->blk_sub.oldcomppad = (PAD*)ptr_table_fetch(PL_ptr_table,
12914                                            ncx->blk_sub.oldcomppad);
12915                 break;
12916             case CXt_EVAL:
12917                 ncx->blk_eval.old_namesv = sv_dup_inc(ncx->blk_eval.old_namesv,
12918                                                       param);
12919                 ncx->blk_eval.cur_text  = sv_dup(ncx->blk_eval.cur_text, param);
12920                 ncx->blk_eval.cv = cv_dup(ncx->blk_eval.cv, param);
12921                 break;
12922             case CXt_LOOP_LAZYSV:
12923                 ncx->blk_loop.state_u.lazysv.end
12924                     = sv_dup_inc(ncx->blk_loop.state_u.lazysv.end, param);
12925                 /* We are taking advantage of av_dup_inc and sv_dup_inc
12926                    actually being the same function, and order equivalence of
12927                    the two unions.
12928                    We can assert the later [but only at run time :-(]  */
12929                 assert ((void *) &ncx->blk_loop.state_u.ary.ary ==
12930                         (void *) &ncx->blk_loop.state_u.lazysv.cur);
12931             case CXt_LOOP_FOR:
12932                 ncx->blk_loop.state_u.ary.ary
12933                     = av_dup_inc(ncx->blk_loop.state_u.ary.ary, param);
12934             case CXt_LOOP_LAZYIV:
12935             case CXt_LOOP_PLAIN:
12936                 if (CxPADLOOP(ncx)) {
12937                     ncx->blk_loop.itervar_u.oldcomppad
12938                         = (PAD*)ptr_table_fetch(PL_ptr_table,
12939                                         ncx->blk_loop.itervar_u.oldcomppad);
12940                 } else {
12941                     ncx->blk_loop.itervar_u.gv
12942                         = gv_dup((const GV *)ncx->blk_loop.itervar_u.gv,
12943                                     param);
12944                 }
12945                 break;
12946             case CXt_FORMAT:
12947                 ncx->blk_format.cv      = cv_dup(ncx->blk_format.cv, param);
12948                 ncx->blk_format.gv      = gv_dup(ncx->blk_format.gv, param);
12949                 ncx->blk_format.dfoutgv = gv_dup_inc(ncx->blk_format.dfoutgv,
12950                                                      param);
12951                 break;
12952             case CXt_BLOCK:
12953             case CXt_NULL:
12954             case CXt_WHEN:
12955             case CXt_GIVEN:
12956                 break;
12957             }
12958         }
12959         --ix;
12960     }
12961     return ncxs;
12962 }
12963
12964 /* duplicate a stack info structure */
12965
12966 PERL_SI *
12967 Perl_si_dup(pTHX_ PERL_SI *si, CLONE_PARAMS* param)
12968 {
12969     PERL_SI *nsi;
12970
12971     PERL_ARGS_ASSERT_SI_DUP;
12972
12973     if (!si)
12974         return (PERL_SI*)NULL;
12975
12976     /* look for it in the table first */
12977     nsi = (PERL_SI*)ptr_table_fetch(PL_ptr_table, si);
12978     if (nsi)
12979         return nsi;
12980
12981     /* create anew and remember what it is */
12982     Newxz(nsi, 1, PERL_SI);
12983     ptr_table_store(PL_ptr_table, si, nsi);
12984
12985     nsi->si_stack       = av_dup_inc(si->si_stack, param);
12986     nsi->si_cxix        = si->si_cxix;
12987     nsi->si_cxmax       = si->si_cxmax;
12988     nsi->si_cxstack     = cx_dup(si->si_cxstack, si->si_cxix, si->si_cxmax, param);
12989     nsi->si_type        = si->si_type;
12990     nsi->si_prev        = si_dup(si->si_prev, param);
12991     nsi->si_next        = si_dup(si->si_next, param);
12992     nsi->si_markoff     = si->si_markoff;
12993
12994     return nsi;
12995 }
12996
12997 #define POPINT(ss,ix)   ((ss)[--(ix)].any_i32)
12998 #define TOPINT(ss,ix)   ((ss)[ix].any_i32)
12999 #define POPLONG(ss,ix)  ((ss)[--(ix)].any_long)
13000 #define TOPLONG(ss,ix)  ((ss)[ix].any_long)
13001 #define POPIV(ss,ix)    ((ss)[--(ix)].any_iv)
13002 #define TOPIV(ss,ix)    ((ss)[ix].any_iv)
13003 #define POPUV(ss,ix)    ((ss)[--(ix)].any_uv)
13004 #define TOPUV(ss,ix)    ((ss)[ix].any_uv)
13005 #define POPBOOL(ss,ix)  ((ss)[--(ix)].any_bool)
13006 #define TOPBOOL(ss,ix)  ((ss)[ix].any_bool)
13007 #define POPPTR(ss,ix)   ((ss)[--(ix)].any_ptr)
13008 #define TOPPTR(ss,ix)   ((ss)[ix].any_ptr)
13009 #define POPDPTR(ss,ix)  ((ss)[--(ix)].any_dptr)
13010 #define TOPDPTR(ss,ix)  ((ss)[ix].any_dptr)
13011 #define POPDXPTR(ss,ix) ((ss)[--(ix)].any_dxptr)
13012 #define TOPDXPTR(ss,ix) ((ss)[ix].any_dxptr)
13013
13014 /* XXXXX todo */
13015 #define pv_dup_inc(p)   SAVEPV(p)
13016 #define pv_dup(p)       SAVEPV(p)
13017 #define svp_dup_inc(p,pp)       any_dup(p,pp)
13018
13019 /* map any object to the new equivent - either something in the
13020  * ptr table, or something in the interpreter structure
13021  */
13022
13023 void *
13024 Perl_any_dup(pTHX_ void *v, const PerlInterpreter *proto_perl)
13025 {
13026     void *ret;
13027
13028     PERL_ARGS_ASSERT_ANY_DUP;
13029
13030     if (!v)
13031         return (void*)NULL;
13032
13033     /* look for it in the table first */
13034     ret = ptr_table_fetch(PL_ptr_table, v);
13035     if (ret)
13036         return ret;
13037
13038     /* see if it is part of the interpreter structure */
13039     if (v >= (void*)proto_perl && v < (void*)(proto_perl+1))
13040         ret = (void*)(((char*)aTHX) + (((char*)v) - (char*)proto_perl));
13041     else {
13042         ret = v;
13043     }
13044
13045     return ret;
13046 }
13047
13048 /* duplicate the save stack */
13049
13050 ANY *
13051 Perl_ss_dup(pTHX_ PerlInterpreter *proto_perl, CLONE_PARAMS* param)
13052 {
13053     dVAR;
13054     ANY * const ss      = proto_perl->Isavestack;
13055     const I32 max       = proto_perl->Isavestack_max;
13056     I32 ix              = proto_perl->Isavestack_ix;
13057     ANY *nss;
13058     const SV *sv;
13059     const GV *gv;
13060     const AV *av;
13061     const HV *hv;
13062     void* ptr;
13063     int intval;
13064     long longval;
13065     GP *gp;
13066     IV iv;
13067     I32 i;
13068     char *c = NULL;
13069     void (*dptr) (void*);
13070     void (*dxptr) (pTHX_ void*);
13071
13072     PERL_ARGS_ASSERT_SS_DUP;
13073
13074     Newxz(nss, max, ANY);
13075
13076     while (ix > 0) {
13077         const UV uv = POPUV(ss,ix);
13078         const U8 type = (U8)uv & SAVE_MASK;
13079
13080         TOPUV(nss,ix) = uv;
13081         switch (type) {
13082         case SAVEt_CLEARSV:
13083         case SAVEt_CLEARPADRANGE:
13084             break;
13085         case SAVEt_HELEM:               /* hash element */
13086             sv = (const SV *)POPPTR(ss,ix);
13087             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13088             /* FALLTHROUGH */
13089         case SAVEt_ITEM:                        /* normal string */
13090         case SAVEt_GVSV:                        /* scalar slot in GV */
13091         case SAVEt_SV:                          /* scalar reference */
13092             sv = (const SV *)POPPTR(ss,ix);
13093             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13094             /* FALLTHROUGH */
13095         case SAVEt_FREESV:
13096         case SAVEt_MORTALIZESV:
13097         case SAVEt_READONLY_OFF:
13098             sv = (const SV *)POPPTR(ss,ix);
13099             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13100             break;
13101         case SAVEt_SHARED_PVREF:                /* char* in shared space */
13102             c = (char*)POPPTR(ss,ix);
13103             TOPPTR(nss,ix) = savesharedpv(c);
13104             ptr = POPPTR(ss,ix);
13105             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13106             break;
13107         case SAVEt_GENERIC_SVREF:               /* generic sv */
13108         case SAVEt_SVREF:                       /* scalar reference */
13109             sv = (const SV *)POPPTR(ss,ix);
13110             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13111             ptr = POPPTR(ss,ix);
13112             TOPPTR(nss,ix) = svp_dup_inc((SV**)ptr, proto_perl);/* XXXXX */
13113             break;
13114         case SAVEt_GVSLOT:              /* any slot in GV */
13115             sv = (const SV *)POPPTR(ss,ix);
13116             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13117             ptr = POPPTR(ss,ix);
13118             TOPPTR(nss,ix) = svp_dup_inc((SV**)ptr, proto_perl);/* XXXXX */
13119             sv = (const SV *)POPPTR(ss,ix);
13120             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13121             break;
13122         case SAVEt_HV:                          /* hash reference */
13123         case SAVEt_AV:                          /* array reference */
13124             sv = (const SV *) POPPTR(ss,ix);
13125             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13126             /* FALLTHROUGH */
13127         case SAVEt_COMPPAD:
13128         case SAVEt_NSTAB:
13129             sv = (const SV *) POPPTR(ss,ix);
13130             TOPPTR(nss,ix) = sv_dup(sv, param);
13131             break;
13132         case SAVEt_INT:                         /* int reference */
13133             ptr = POPPTR(ss,ix);
13134             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13135             intval = (int)POPINT(ss,ix);
13136             TOPINT(nss,ix) = intval;
13137             break;
13138         case SAVEt_LONG:                        /* long reference */
13139             ptr = POPPTR(ss,ix);
13140             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13141             longval = (long)POPLONG(ss,ix);
13142             TOPLONG(nss,ix) = longval;
13143             break;
13144         case SAVEt_I32:                         /* I32 reference */
13145             ptr = POPPTR(ss,ix);
13146             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13147             i = POPINT(ss,ix);
13148             TOPINT(nss,ix) = i;
13149             break;
13150         case SAVEt_IV:                          /* IV reference */
13151         case SAVEt_STRLEN:                      /* STRLEN/size_t ref */
13152             ptr = POPPTR(ss,ix);
13153             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13154             iv = POPIV(ss,ix);
13155             TOPIV(nss,ix) = iv;
13156             break;
13157         case SAVEt_HPTR:                        /* HV* reference */
13158         case SAVEt_APTR:                        /* AV* reference */
13159         case SAVEt_SPTR:                        /* SV* reference */
13160             ptr = POPPTR(ss,ix);
13161             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13162             sv = (const SV *)POPPTR(ss,ix);
13163             TOPPTR(nss,ix) = sv_dup(sv, param);
13164             break;
13165         case SAVEt_VPTR:                        /* random* reference */
13166             ptr = POPPTR(ss,ix);
13167             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13168             /* FALLTHROUGH */
13169         case SAVEt_INT_SMALL:
13170         case SAVEt_I32_SMALL:
13171         case SAVEt_I16:                         /* I16 reference */
13172         case SAVEt_I8:                          /* I8 reference */
13173         case SAVEt_BOOL:
13174             ptr = POPPTR(ss,ix);
13175             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13176             break;
13177         case SAVEt_GENERIC_PVREF:               /* generic char* */
13178         case SAVEt_PPTR:                        /* char* reference */
13179             ptr = POPPTR(ss,ix);
13180             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13181             c = (char*)POPPTR(ss,ix);
13182             TOPPTR(nss,ix) = pv_dup(c);
13183             break;
13184         case SAVEt_GP:                          /* scalar reference */
13185             gp = (GP*)POPPTR(ss,ix);
13186             TOPPTR(nss,ix) = gp = gp_dup(gp, param);
13187             (void)GpREFCNT_inc(gp);
13188             gv = (const GV *)POPPTR(ss,ix);
13189             TOPPTR(nss,ix) = gv_dup_inc(gv, param);
13190             break;
13191         case SAVEt_FREEOP:
13192             ptr = POPPTR(ss,ix);
13193             if (ptr && (((OP*)ptr)->op_private & OPpREFCOUNTED)) {
13194                 /* these are assumed to be refcounted properly */
13195                 OP *o;
13196                 switch (((OP*)ptr)->op_type) {
13197                 case OP_LEAVESUB:
13198                 case OP_LEAVESUBLV:
13199                 case OP_LEAVEEVAL:
13200                 case OP_LEAVE:
13201                 case OP_SCOPE:
13202                 case OP_LEAVEWRITE:
13203                     TOPPTR(nss,ix) = ptr;
13204                     o = (OP*)ptr;
13205                     OP_REFCNT_LOCK;
13206                     (void) OpREFCNT_inc(o);
13207                     OP_REFCNT_UNLOCK;
13208                     break;
13209                 default:
13210                     TOPPTR(nss,ix) = NULL;
13211                     break;
13212                 }
13213             }
13214             else
13215                 TOPPTR(nss,ix) = NULL;
13216             break;
13217         case SAVEt_FREECOPHH:
13218             ptr = POPPTR(ss,ix);
13219             TOPPTR(nss,ix) = cophh_copy((COPHH *)ptr);
13220             break;
13221         case SAVEt_ADELETE:
13222             av = (const AV *)POPPTR(ss,ix);
13223             TOPPTR(nss,ix) = av_dup_inc(av, param);
13224             i = POPINT(ss,ix);
13225             TOPINT(nss,ix) = i;
13226             break;
13227         case SAVEt_DELETE:
13228             hv = (const HV *)POPPTR(ss,ix);
13229             TOPPTR(nss,ix) = hv_dup_inc(hv, param);
13230             i = POPINT(ss,ix);
13231             TOPINT(nss,ix) = i;
13232             /* FALLTHROUGH */
13233         case SAVEt_FREEPV:
13234             c = (char*)POPPTR(ss,ix);
13235             TOPPTR(nss,ix) = pv_dup_inc(c);
13236             break;
13237         case SAVEt_STACK_POS:           /* Position on Perl stack */
13238             i = POPINT(ss,ix);
13239             TOPINT(nss,ix) = i;
13240             break;
13241         case SAVEt_DESTRUCTOR:
13242             ptr = POPPTR(ss,ix);
13243             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);  /* XXX quite arbitrary */
13244             dptr = POPDPTR(ss,ix);
13245             TOPDPTR(nss,ix) = DPTR2FPTR(void (*)(void*),
13246                                         any_dup(FPTR2DPTR(void *, dptr),
13247                                                 proto_perl));
13248             break;
13249         case SAVEt_DESTRUCTOR_X:
13250             ptr = POPPTR(ss,ix);
13251             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);  /* XXX quite arbitrary */
13252             dxptr = POPDXPTR(ss,ix);
13253             TOPDXPTR(nss,ix) = DPTR2FPTR(void (*)(pTHX_ void*),
13254                                          any_dup(FPTR2DPTR(void *, dxptr),
13255                                                  proto_perl));
13256             break;
13257         case SAVEt_REGCONTEXT:
13258         case SAVEt_ALLOC:
13259             ix -= uv >> SAVE_TIGHT_SHIFT;
13260             break;
13261         case SAVEt_AELEM:               /* array element */
13262             sv = (const SV *)POPPTR(ss,ix);
13263             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13264             i = POPINT(ss,ix);
13265             TOPINT(nss,ix) = i;
13266             av = (const AV *)POPPTR(ss,ix);
13267             TOPPTR(nss,ix) = av_dup_inc(av, param);
13268             break;
13269         case SAVEt_OP:
13270             ptr = POPPTR(ss,ix);
13271             TOPPTR(nss,ix) = ptr;
13272             break;
13273         case SAVEt_HINTS:
13274             ptr = POPPTR(ss,ix);
13275             ptr = cophh_copy((COPHH*)ptr);
13276             TOPPTR(nss,ix) = ptr;
13277             i = POPINT(ss,ix);
13278             TOPINT(nss,ix) = i;
13279             if (i & HINT_LOCALIZE_HH) {
13280                 hv = (const HV *)POPPTR(ss,ix);
13281                 TOPPTR(nss,ix) = hv_dup_inc(hv, param);
13282             }
13283             break;
13284         case SAVEt_PADSV_AND_MORTALIZE:
13285             longval = (long)POPLONG(ss,ix);
13286             TOPLONG(nss,ix) = longval;
13287             ptr = POPPTR(ss,ix);
13288             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13289             sv = (const SV *)POPPTR(ss,ix);
13290             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13291             break;
13292         case SAVEt_SET_SVFLAGS:
13293             i = POPINT(ss,ix);
13294             TOPINT(nss,ix) = i;
13295             i = POPINT(ss,ix);
13296             TOPINT(nss,ix) = i;
13297             sv = (const SV *)POPPTR(ss,ix);
13298             TOPPTR(nss,ix) = sv_dup(sv, param);
13299             break;
13300         case SAVEt_COMPILE_WARNINGS:
13301             ptr = POPPTR(ss,ix);
13302             TOPPTR(nss,ix) = DUP_WARNINGS((STRLEN*)ptr);
13303             break;
13304         case SAVEt_PARSER:
13305             ptr = POPPTR(ss,ix);
13306             TOPPTR(nss,ix) = parser_dup((const yy_parser*)ptr, param);
13307             break;
13308         default:
13309             Perl_croak(aTHX_
13310                        "panic: ss_dup inconsistency (%"IVdf")", (IV) type);
13311         }
13312     }
13313
13314     return nss;
13315 }
13316
13317
13318 /* if sv is a stash, call $class->CLONE_SKIP(), and set the SVphv_CLONEABLE
13319  * flag to the result. This is done for each stash before cloning starts,
13320  * so we know which stashes want their objects cloned */
13321
13322 static void
13323 do_mark_cloneable_stash(pTHX_ SV *const sv)
13324 {
13325     const HEK * const hvname = HvNAME_HEK((const HV *)sv);
13326     if (hvname) {
13327         GV* const cloner = gv_fetchmethod_autoload(MUTABLE_HV(sv), "CLONE_SKIP", 0);
13328         SvFLAGS(sv) |= SVphv_CLONEABLE; /* clone objects by default */
13329         if (cloner && GvCV(cloner)) {
13330             dSP;
13331             UV status;
13332
13333             ENTER;
13334             SAVETMPS;
13335             PUSHMARK(SP);
13336             mXPUSHs(newSVhek(hvname));
13337             PUTBACK;
13338             call_sv(MUTABLE_SV(GvCV(cloner)), G_SCALAR);
13339             SPAGAIN;
13340             status = POPu;
13341             PUTBACK;
13342             FREETMPS;
13343             LEAVE;
13344             if (status)
13345                 SvFLAGS(sv) &= ~SVphv_CLONEABLE;
13346         }
13347     }
13348 }
13349
13350
13351
13352 /*
13353 =for apidoc perl_clone
13354
13355 Create and return a new interpreter by cloning the current one.
13356
13357 perl_clone takes these flags as parameters:
13358
13359 CLONEf_COPY_STACKS - is used to, well, copy the stacks also,
13360 without it we only clone the data and zero the stacks,
13361 with it we copy the stacks and the new perl interpreter is
13362 ready to run at the exact same point as the previous one.
13363 The pseudo-fork code uses COPY_STACKS while the
13364 threads->create doesn't.
13365
13366 CLONEf_KEEP_PTR_TABLE -
13367 perl_clone keeps a ptr_table with the pointer of the old
13368 variable as a key and the new variable as a value,
13369 this allows it to check if something has been cloned and not
13370 clone it again but rather just use the value and increase the
13371 refcount.  If KEEP_PTR_TABLE is not set then perl_clone will kill
13372 the ptr_table using the function
13373 C<ptr_table_free(PL_ptr_table); PL_ptr_table = NULL;>,
13374 reason to keep it around is if you want to dup some of your own
13375 variable who are outside the graph perl scans, example of this
13376 code is in threads.xs create.
13377
13378 CLONEf_CLONE_HOST -
13379 This is a win32 thing, it is ignored on unix, it tells perls
13380 win32host code (which is c++) to clone itself, this is needed on
13381 win32 if you want to run two threads at the same time,
13382 if you just want to do some stuff in a separate perl interpreter
13383 and then throw it away and return to the original one,
13384 you don't need to do anything.
13385
13386 =cut
13387 */
13388
13389 /* XXX the above needs expanding by someone who actually understands it ! */
13390 EXTERN_C PerlInterpreter *
13391 perl_clone_host(PerlInterpreter* proto_perl, UV flags);
13392
13393 PerlInterpreter *
13394 perl_clone(PerlInterpreter *proto_perl, UV flags)
13395 {
13396    dVAR;
13397 #ifdef PERL_IMPLICIT_SYS
13398
13399     PERL_ARGS_ASSERT_PERL_CLONE;
13400
13401    /* perlhost.h so we need to call into it
13402    to clone the host, CPerlHost should have a c interface, sky */
13403
13404    if (flags & CLONEf_CLONE_HOST) {
13405        return perl_clone_host(proto_perl,flags);
13406    }
13407    return perl_clone_using(proto_perl, flags,
13408                             proto_perl->IMem,
13409                             proto_perl->IMemShared,
13410                             proto_perl->IMemParse,
13411                             proto_perl->IEnv,
13412                             proto_perl->IStdIO,
13413                             proto_perl->ILIO,
13414                             proto_perl->IDir,
13415                             proto_perl->ISock,
13416                             proto_perl->IProc);
13417 }
13418
13419 PerlInterpreter *
13420 perl_clone_using(PerlInterpreter *proto_perl, UV flags,
13421                  struct IPerlMem* ipM, struct IPerlMem* ipMS,
13422                  struct IPerlMem* ipMP, struct IPerlEnv* ipE,
13423                  struct IPerlStdIO* ipStd, struct IPerlLIO* ipLIO,
13424                  struct IPerlDir* ipD, struct IPerlSock* ipS,
13425                  struct IPerlProc* ipP)
13426 {
13427     /* XXX many of the string copies here can be optimized if they're
13428      * constants; they need to be allocated as common memory and just
13429      * their pointers copied. */
13430
13431     IV i;
13432     CLONE_PARAMS clone_params;
13433     CLONE_PARAMS* const param = &clone_params;
13434
13435     PerlInterpreter * const my_perl = (PerlInterpreter*)(*ipM->pMalloc)(ipM, sizeof(PerlInterpreter));
13436
13437     PERL_ARGS_ASSERT_PERL_CLONE_USING;
13438 #else           /* !PERL_IMPLICIT_SYS */
13439     IV i;
13440     CLONE_PARAMS clone_params;
13441     CLONE_PARAMS* param = &clone_params;
13442     PerlInterpreter * const my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
13443
13444     PERL_ARGS_ASSERT_PERL_CLONE;
13445 #endif          /* PERL_IMPLICIT_SYS */
13446
13447     /* for each stash, determine whether its objects should be cloned */
13448     S_visit(proto_perl, do_mark_cloneable_stash, SVt_PVHV, SVTYPEMASK);
13449     PERL_SET_THX(my_perl);
13450
13451 #ifdef DEBUGGING
13452     PoisonNew(my_perl, 1, PerlInterpreter);
13453     PL_op = NULL;
13454     PL_curcop = NULL;
13455     PL_defstash = NULL; /* may be used by perl malloc() */
13456     PL_markstack = 0;
13457     PL_scopestack = 0;
13458     PL_scopestack_name = 0;
13459     PL_savestack = 0;
13460     PL_savestack_ix = 0;
13461     PL_savestack_max = -1;
13462     PL_sig_pending = 0;
13463     PL_parser = NULL;
13464     Zero(&PL_debug_pad, 1, struct perl_debug_pad);
13465 #  ifdef DEBUG_LEAKING_SCALARS
13466     PL_sv_serial = (((UV)my_perl >> 2) & 0xfff) * 1000000;
13467 #  endif
13468 #else   /* !DEBUGGING */
13469     Zero(my_perl, 1, PerlInterpreter);
13470 #endif  /* DEBUGGING */
13471
13472 #ifdef PERL_IMPLICIT_SYS
13473     /* host pointers */
13474     PL_Mem              = ipM;
13475     PL_MemShared        = ipMS;
13476     PL_MemParse         = ipMP;
13477     PL_Env              = ipE;
13478     PL_StdIO            = ipStd;
13479     PL_LIO              = ipLIO;
13480     PL_Dir              = ipD;
13481     PL_Sock             = ipS;
13482     PL_Proc             = ipP;
13483 #endif          /* PERL_IMPLICIT_SYS */
13484
13485
13486     param->flags = flags;
13487     /* Nothing in the core code uses this, but we make it available to
13488        extensions (using mg_dup).  */
13489     param->proto_perl = proto_perl;
13490     /* Likely nothing will use this, but it is initialised to be consistent
13491        with Perl_clone_params_new().  */
13492     param->new_perl = my_perl;
13493     param->unreferenced = NULL;
13494
13495
13496     INIT_TRACK_MEMPOOL(my_perl->Imemory_debug_header, my_perl);
13497
13498     PL_body_arenas = NULL;
13499     Zero(&PL_body_roots, 1, PL_body_roots);
13500     
13501     PL_sv_count         = 0;
13502     PL_sv_root          = NULL;
13503     PL_sv_arenaroot     = NULL;
13504
13505     PL_debug            = proto_perl->Idebug;
13506
13507     /* dbargs array probably holds garbage */
13508     PL_dbargs           = NULL;
13509
13510     PL_compiling = proto_perl->Icompiling;
13511
13512     /* pseudo environmental stuff */
13513     PL_origargc         = proto_perl->Iorigargc;
13514     PL_origargv         = proto_perl->Iorigargv;
13515
13516 #ifndef NO_TAINT_SUPPORT
13517     /* Set tainting stuff before PerlIO_debug can possibly get called */
13518     PL_tainting         = proto_perl->Itainting;
13519     PL_taint_warn       = proto_perl->Itaint_warn;
13520 #else
13521     PL_tainting         = FALSE;
13522     PL_taint_warn       = FALSE;
13523 #endif
13524
13525     PL_minus_c          = proto_perl->Iminus_c;
13526
13527     PL_localpatches     = proto_perl->Ilocalpatches;
13528     PL_splitstr         = proto_perl->Isplitstr;
13529     PL_minus_n          = proto_perl->Iminus_n;
13530     PL_minus_p          = proto_perl->Iminus_p;
13531     PL_minus_l          = proto_perl->Iminus_l;
13532     PL_minus_a          = proto_perl->Iminus_a;
13533     PL_minus_E          = proto_perl->Iminus_E;
13534     PL_minus_F          = proto_perl->Iminus_F;
13535     PL_doswitches       = proto_perl->Idoswitches;
13536     PL_dowarn           = proto_perl->Idowarn;
13537 #ifdef PERL_SAWAMPERSAND
13538     PL_sawampersand     = proto_perl->Isawampersand;
13539 #endif
13540     PL_unsafe           = proto_perl->Iunsafe;
13541     PL_perldb           = proto_perl->Iperldb;
13542     PL_perl_destruct_level = proto_perl->Iperl_destruct_level;
13543     PL_exit_flags       = proto_perl->Iexit_flags;
13544
13545     /* XXX time(&PL_basetime) when asked for? */
13546     PL_basetime         = proto_perl->Ibasetime;
13547
13548     PL_maxsysfd         = proto_perl->Imaxsysfd;
13549     PL_statusvalue      = proto_perl->Istatusvalue;
13550 #ifdef VMS
13551     PL_statusvalue_vms  = proto_perl->Istatusvalue_vms;
13552 #else
13553     PL_statusvalue_posix = proto_perl->Istatusvalue_posix;
13554 #endif
13555
13556     /* RE engine related */
13557     PL_regmatch_slab    = NULL;
13558     PL_reg_curpm        = NULL;
13559
13560     PL_sub_generation   = proto_perl->Isub_generation;
13561
13562     /* funky return mechanisms */
13563     PL_forkprocess      = proto_perl->Iforkprocess;
13564
13565     /* internal state */
13566     PL_maxo             = proto_perl->Imaxo;
13567
13568     PL_main_start       = proto_perl->Imain_start;
13569     PL_eval_root        = proto_perl->Ieval_root;
13570     PL_eval_start       = proto_perl->Ieval_start;
13571
13572     PL_filemode         = proto_perl->Ifilemode;
13573     PL_lastfd           = proto_perl->Ilastfd;
13574     PL_oldname          = proto_perl->Ioldname;         /* XXX not quite right */
13575     PL_Argv             = NULL;
13576     PL_Cmd              = NULL;
13577     PL_gensym           = proto_perl->Igensym;
13578
13579     PL_laststatval      = proto_perl->Ilaststatval;
13580     PL_laststype        = proto_perl->Ilaststype;
13581     PL_mess_sv          = NULL;
13582
13583     PL_profiledata      = NULL;
13584
13585     PL_generation       = proto_perl->Igeneration;
13586
13587     PL_in_clean_objs    = proto_perl->Iin_clean_objs;
13588     PL_in_clean_all     = proto_perl->Iin_clean_all;
13589
13590     PL_delaymagic_uid   = proto_perl->Idelaymagic_uid;
13591     PL_delaymagic_euid  = proto_perl->Idelaymagic_euid;
13592     PL_delaymagic_gid   = proto_perl->Idelaymagic_gid;
13593     PL_delaymagic_egid  = proto_perl->Idelaymagic_egid;
13594     PL_nomemok          = proto_perl->Inomemok;
13595     PL_an               = proto_perl->Ian;
13596     PL_evalseq          = proto_perl->Ievalseq;
13597     PL_origenviron      = proto_perl->Iorigenviron;     /* XXX not quite right */
13598     PL_origalen         = proto_perl->Iorigalen;
13599
13600     PL_sighandlerp      = proto_perl->Isighandlerp;
13601
13602     PL_runops           = proto_perl->Irunops;
13603
13604     PL_subline          = proto_perl->Isubline;
13605
13606 #ifdef FCRYPT
13607     PL_cryptseen        = proto_perl->Icryptseen;
13608 #endif
13609
13610 #ifdef USE_LOCALE_COLLATE
13611     PL_collation_ix     = proto_perl->Icollation_ix;
13612     PL_collation_standard       = proto_perl->Icollation_standard;
13613     PL_collxfrm_base    = proto_perl->Icollxfrm_base;
13614     PL_collxfrm_mult    = proto_perl->Icollxfrm_mult;
13615 #endif /* USE_LOCALE_COLLATE */
13616
13617 #ifdef USE_LOCALE_NUMERIC
13618     PL_numeric_standard = proto_perl->Inumeric_standard;
13619     PL_numeric_local    = proto_perl->Inumeric_local;
13620 #endif /* !USE_LOCALE_NUMERIC */
13621
13622     /* Did the locale setup indicate UTF-8? */
13623     PL_utf8locale       = proto_perl->Iutf8locale;
13624     PL_in_utf8_CTYPE_locale = proto_perl->Iin_utf8_CTYPE_locale;
13625     /* Unicode features (see perlrun/-C) */
13626     PL_unicode          = proto_perl->Iunicode;
13627
13628     /* Pre-5.8 signals control */
13629     PL_signals          = proto_perl->Isignals;
13630
13631     /* times() ticks per second */
13632     PL_clocktick        = proto_perl->Iclocktick;
13633
13634     /* Recursion stopper for PerlIO_find_layer */
13635     PL_in_load_module   = proto_perl->Iin_load_module;
13636
13637     /* sort() routine */
13638     PL_sort_RealCmp     = proto_perl->Isort_RealCmp;
13639
13640     /* Not really needed/useful since the reenrant_retint is "volatile",
13641      * but do it for consistency's sake. */
13642     PL_reentrant_retint = proto_perl->Ireentrant_retint;
13643
13644     /* Hooks to shared SVs and locks. */
13645     PL_sharehook        = proto_perl->Isharehook;
13646     PL_lockhook         = proto_perl->Ilockhook;
13647     PL_unlockhook       = proto_perl->Iunlockhook;
13648     PL_threadhook       = proto_perl->Ithreadhook;
13649     PL_destroyhook      = proto_perl->Idestroyhook;
13650     PL_signalhook       = proto_perl->Isignalhook;
13651
13652     PL_globhook         = proto_perl->Iglobhook;
13653
13654     /* swatch cache */
13655     PL_last_swash_hv    = NULL; /* reinits on demand */
13656     PL_last_swash_klen  = 0;
13657     PL_last_swash_key[0]= '\0';
13658     PL_last_swash_tmps  = (U8*)NULL;
13659     PL_last_swash_slen  = 0;
13660
13661     PL_srand_called     = proto_perl->Isrand_called;
13662     Copy(&(proto_perl->Irandom_state), &PL_random_state, 1, PL_RANDOM_STATE_TYPE);
13663
13664     if (flags & CLONEf_COPY_STACKS) {
13665         /* next allocation will be PL_tmps_stack[PL_tmps_ix+1] */
13666         PL_tmps_ix              = proto_perl->Itmps_ix;
13667         PL_tmps_max             = proto_perl->Itmps_max;
13668         PL_tmps_floor           = proto_perl->Itmps_floor;
13669
13670         /* next push_scope()/ENTER sets PL_scopestack[PL_scopestack_ix]
13671          * NOTE: unlike the others! */
13672         PL_scopestack_ix        = proto_perl->Iscopestack_ix;
13673         PL_scopestack_max       = proto_perl->Iscopestack_max;
13674
13675         /* next SSPUSHFOO() sets PL_savestack[PL_savestack_ix]
13676          * NOTE: unlike the others! */
13677         PL_savestack_ix         = proto_perl->Isavestack_ix;
13678         PL_savestack_max        = proto_perl->Isavestack_max;
13679     }
13680
13681     PL_start_env        = proto_perl->Istart_env;       /* XXXXXX */
13682     PL_top_env          = &PL_start_env;
13683
13684     PL_op               = proto_perl->Iop;
13685
13686     PL_Sv               = NULL;
13687     PL_Xpv              = (XPV*)NULL;
13688     my_perl->Ina        = proto_perl->Ina;
13689
13690     PL_statbuf          = proto_perl->Istatbuf;
13691     PL_statcache        = proto_perl->Istatcache;
13692
13693 #ifndef NO_TAINT_SUPPORT
13694     PL_tainted          = proto_perl->Itainted;
13695 #else
13696     PL_tainted          = FALSE;
13697 #endif
13698     PL_curpm            = proto_perl->Icurpm;   /* XXX No PMOP ref count */
13699
13700     PL_chopset          = proto_perl->Ichopset; /* XXX never deallocated */
13701
13702     PL_restartjmpenv    = proto_perl->Irestartjmpenv;
13703     PL_restartop        = proto_perl->Irestartop;
13704     PL_in_eval          = proto_perl->Iin_eval;
13705     PL_delaymagic       = proto_perl->Idelaymagic;
13706     PL_phase            = proto_perl->Iphase;
13707     PL_localizing       = proto_perl->Ilocalizing;
13708
13709     PL_hv_fetch_ent_mh  = NULL;
13710     PL_modcount         = proto_perl->Imodcount;
13711     PL_lastgotoprobe    = NULL;
13712     PL_dumpindent       = proto_perl->Idumpindent;
13713
13714     PL_efloatbuf        = NULL;         /* reinits on demand */
13715     PL_efloatsize       = 0;                    /* reinits on demand */
13716
13717     /* regex stuff */
13718
13719     PL_colorset         = 0;            /* reinits PL_colors[] */
13720     /*PL_colors[6]      = {0,0,0,0,0,0};*/
13721
13722     /* Pluggable optimizer */
13723     PL_peepp            = proto_perl->Ipeepp;
13724     PL_rpeepp           = proto_perl->Irpeepp;
13725     /* op_free() hook */
13726     PL_opfreehook       = proto_perl->Iopfreehook;
13727
13728 #ifdef USE_REENTRANT_API
13729     /* XXX: things like -Dm will segfault here in perlio, but doing
13730      *  PERL_SET_CONTEXT(proto_perl);
13731      * breaks too many other things
13732      */
13733     Perl_reentrant_init(aTHX);
13734 #endif
13735
13736     /* create SV map for pointer relocation */
13737     PL_ptr_table = ptr_table_new();
13738
13739     /* initialize these special pointers as early as possible */
13740     init_constants();
13741     ptr_table_store(PL_ptr_table, &proto_perl->Isv_undef, &PL_sv_undef);
13742     ptr_table_store(PL_ptr_table, &proto_perl->Isv_no, &PL_sv_no);
13743     ptr_table_store(PL_ptr_table, &proto_perl->Isv_yes, &PL_sv_yes);
13744
13745     /* create (a non-shared!) shared string table */
13746     PL_strtab           = newHV();
13747     HvSHAREKEYS_off(PL_strtab);
13748     hv_ksplit(PL_strtab, HvTOTALKEYS(proto_perl->Istrtab));
13749     ptr_table_store(PL_ptr_table, proto_perl->Istrtab, PL_strtab);
13750
13751     Zero(PL_sv_consts, SV_CONSTS_COUNT, SV*);
13752
13753     /* This PV will be free'd special way so must set it same way op.c does */
13754     PL_compiling.cop_file    = savesharedpv(PL_compiling.cop_file);
13755     ptr_table_store(PL_ptr_table, proto_perl->Icompiling.cop_file, PL_compiling.cop_file);
13756
13757     ptr_table_store(PL_ptr_table, &proto_perl->Icompiling, &PL_compiling);
13758     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
13759     CopHINTHASH_set(&PL_compiling, cophh_copy(CopHINTHASH_get(&PL_compiling)));
13760     PL_curcop           = (COP*)any_dup(proto_perl->Icurcop, proto_perl);
13761
13762     param->stashes      = newAV();  /* Setup array of objects to call clone on */
13763     /* This makes no difference to the implementation, as it always pushes
13764        and shifts pointers to other SVs without changing their reference
13765        count, with the array becoming empty before it is freed. However, it
13766        makes it conceptually clear what is going on, and will avoid some
13767        work inside av.c, filling slots between AvFILL() and AvMAX() with
13768        &PL_sv_undef, and SvREFCNT_dec()ing those.  */
13769     AvREAL_off(param->stashes);
13770
13771     if (!(flags & CLONEf_COPY_STACKS)) {
13772         param->unreferenced = newAV();
13773     }
13774
13775 #ifdef PERLIO_LAYERS
13776     /* Clone PerlIO tables as soon as we can handle general xx_dup() */
13777     PerlIO_clone(aTHX_ proto_perl, param);
13778 #endif
13779
13780     PL_envgv            = gv_dup_inc(proto_perl->Ienvgv, param);
13781     PL_incgv            = gv_dup_inc(proto_perl->Iincgv, param);
13782     PL_hintgv           = gv_dup_inc(proto_perl->Ihintgv, param);
13783     PL_origfilename     = SAVEPV(proto_perl->Iorigfilename);
13784     PL_diehook          = sv_dup_inc(proto_perl->Idiehook, param);
13785     PL_warnhook         = sv_dup_inc(proto_perl->Iwarnhook, param);
13786
13787     /* switches */
13788     PL_patchlevel       = sv_dup_inc(proto_perl->Ipatchlevel, param);
13789     PL_apiversion       = sv_dup_inc(proto_perl->Iapiversion, param);
13790     PL_inplace          = SAVEPV(proto_perl->Iinplace);
13791     PL_e_script         = sv_dup_inc(proto_perl->Ie_script, param);
13792
13793     /* magical thingies */
13794
13795     PL_encoding         = sv_dup(proto_perl->Iencoding, param);
13796
13797     sv_setpvs(PERL_DEBUG_PAD(0), "");   /* For regex debugging. */
13798     sv_setpvs(PERL_DEBUG_PAD(1), "");   /* ext/re needs these */
13799     sv_setpvs(PERL_DEBUG_PAD(2), "");   /* even without DEBUGGING. */
13800
13801    
13802     /* Clone the regex array */
13803     /* ORANGE FIXME for plugins, probably in the SV dup code.
13804        newSViv(PTR2IV(CALLREGDUPE(
13805        INT2PTR(REGEXP *, SvIVX(regex)), param))))
13806     */
13807     PL_regex_padav = av_dup_inc(proto_perl->Iregex_padav, param);
13808     PL_regex_pad = AvARRAY(PL_regex_padav);
13809
13810     PL_stashpadmax      = proto_perl->Istashpadmax;
13811     PL_stashpadix       = proto_perl->Istashpadix ;
13812     Newx(PL_stashpad, PL_stashpadmax, HV *);
13813     {
13814         PADOFFSET o = 0;
13815         for (; o < PL_stashpadmax; ++o)
13816             PL_stashpad[o] = hv_dup(proto_perl->Istashpad[o], param);
13817     }
13818
13819     /* shortcuts to various I/O objects */
13820     PL_ofsgv            = gv_dup_inc(proto_perl->Iofsgv, param);
13821     PL_stdingv          = gv_dup(proto_perl->Istdingv, param);
13822     PL_stderrgv         = gv_dup(proto_perl->Istderrgv, param);
13823     PL_defgv            = gv_dup(proto_perl->Idefgv, param);
13824     PL_argvgv           = gv_dup_inc(proto_perl->Iargvgv, param);
13825     PL_argvoutgv        = gv_dup(proto_perl->Iargvoutgv, param);
13826     PL_argvout_stack    = av_dup_inc(proto_perl->Iargvout_stack, param);
13827
13828     /* shortcuts to regexp stuff */
13829     PL_replgv           = gv_dup_inc(proto_perl->Ireplgv, param);
13830
13831     /* shortcuts to misc objects */
13832     PL_errgv            = gv_dup(proto_perl->Ierrgv, param);
13833
13834     /* shortcuts to debugging objects */
13835     PL_DBgv             = gv_dup_inc(proto_perl->IDBgv, param);
13836     PL_DBline           = gv_dup_inc(proto_perl->IDBline, param);
13837     PL_DBsub            = gv_dup_inc(proto_perl->IDBsub, param);
13838     PL_DBsingle         = sv_dup(proto_perl->IDBsingle, param);
13839     PL_DBtrace          = sv_dup(proto_perl->IDBtrace, param);
13840     PL_DBsignal         = sv_dup(proto_perl->IDBsignal, param);
13841
13842     /* symbol tables */
13843     PL_defstash         = hv_dup_inc(proto_perl->Idefstash, param);
13844     PL_curstash         = hv_dup_inc(proto_perl->Icurstash, param);
13845     PL_debstash         = hv_dup(proto_perl->Idebstash, param);
13846     PL_globalstash      = hv_dup(proto_perl->Iglobalstash, param);
13847     PL_curstname        = sv_dup_inc(proto_perl->Icurstname, param);
13848
13849     PL_beginav          = av_dup_inc(proto_perl->Ibeginav, param);
13850     PL_beginav_save     = av_dup_inc(proto_perl->Ibeginav_save, param);
13851     PL_checkav_save     = av_dup_inc(proto_perl->Icheckav_save, param);
13852     PL_unitcheckav      = av_dup_inc(proto_perl->Iunitcheckav, param);
13853     PL_unitcheckav_save = av_dup_inc(proto_perl->Iunitcheckav_save, param);
13854     PL_endav            = av_dup_inc(proto_perl->Iendav, param);
13855     PL_checkav          = av_dup_inc(proto_perl->Icheckav, param);
13856     PL_initav           = av_dup_inc(proto_perl->Iinitav, param);
13857
13858     PL_isarev           = hv_dup_inc(proto_perl->Iisarev, param);
13859
13860     /* subprocess state */
13861     PL_fdpid            = av_dup_inc(proto_perl->Ifdpid, param);
13862
13863     if (proto_perl->Iop_mask)
13864         PL_op_mask      = SAVEPVN(proto_perl->Iop_mask, PL_maxo);
13865     else
13866         PL_op_mask      = NULL;
13867     /* PL_asserting        = proto_perl->Iasserting; */
13868
13869     /* current interpreter roots */
13870     PL_main_cv          = cv_dup_inc(proto_perl->Imain_cv, param);
13871     OP_REFCNT_LOCK;
13872     PL_main_root        = OpREFCNT_inc(proto_perl->Imain_root);
13873     OP_REFCNT_UNLOCK;
13874
13875     /* runtime control stuff */
13876     PL_curcopdb         = (COP*)any_dup(proto_perl->Icurcopdb, proto_perl);
13877
13878     PL_preambleav       = av_dup_inc(proto_perl->Ipreambleav, param);
13879
13880     PL_ors_sv           = sv_dup_inc(proto_perl->Iors_sv, param);
13881
13882     /* interpreter atexit processing */
13883     PL_exitlistlen      = proto_perl->Iexitlistlen;
13884     if (PL_exitlistlen) {
13885         Newx(PL_exitlist, PL_exitlistlen, PerlExitListEntry);
13886         Copy(proto_perl->Iexitlist, PL_exitlist, PL_exitlistlen, PerlExitListEntry);
13887     }
13888     else
13889         PL_exitlist     = (PerlExitListEntry*)NULL;
13890
13891     PL_my_cxt_size = proto_perl->Imy_cxt_size;
13892     if (PL_my_cxt_size) {
13893         Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
13894         Copy(proto_perl->Imy_cxt_list, PL_my_cxt_list, PL_my_cxt_size, void *);
13895 #ifdef PERL_GLOBAL_STRUCT_PRIVATE
13896         Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
13897         Copy(proto_perl->Imy_cxt_keys, PL_my_cxt_keys, PL_my_cxt_size, char *);
13898 #endif
13899     }
13900     else {
13901         PL_my_cxt_list  = (void**)NULL;
13902 #ifdef PERL_GLOBAL_STRUCT_PRIVATE
13903         PL_my_cxt_keys  = (const char**)NULL;
13904 #endif
13905     }
13906     PL_modglobal        = hv_dup_inc(proto_perl->Imodglobal, param);
13907     PL_custom_op_names  = hv_dup_inc(proto_perl->Icustom_op_names,param);
13908     PL_custom_op_descs  = hv_dup_inc(proto_perl->Icustom_op_descs,param);
13909     PL_custom_ops       = hv_dup_inc(proto_perl->Icustom_ops, param);
13910
13911     PL_compcv                   = cv_dup(proto_perl->Icompcv, param);
13912
13913     PAD_CLONE_VARS(proto_perl, param);
13914
13915 #ifdef HAVE_INTERP_INTERN
13916     sys_intern_dup(&proto_perl->Isys_intern, &PL_sys_intern);
13917 #endif
13918
13919     PL_DBcv             = cv_dup(proto_perl->IDBcv, param);
13920
13921 #ifdef PERL_USES_PL_PIDSTATUS
13922     PL_pidstatus        = newHV();                      /* XXX flag for cloning? */
13923 #endif
13924     PL_osname           = SAVEPV(proto_perl->Iosname);
13925     PL_parser           = parser_dup(proto_perl->Iparser, param);
13926
13927     /* XXX this only works if the saved cop has already been cloned */
13928     if (proto_perl->Iparser) {
13929         PL_parser->saved_curcop = (COP*)any_dup(
13930                                     proto_perl->Iparser->saved_curcop,
13931                                     proto_perl);
13932     }
13933
13934     PL_subname          = sv_dup_inc(proto_perl->Isubname, param);
13935
13936 #ifdef USE_LOCALE_COLLATE
13937     PL_collation_name   = SAVEPV(proto_perl->Icollation_name);
13938 #endif /* USE_LOCALE_COLLATE */
13939
13940 #ifdef USE_LOCALE_NUMERIC
13941     PL_numeric_name     = SAVEPV(proto_perl->Inumeric_name);
13942     PL_numeric_radix_sv = sv_dup_inc(proto_perl->Inumeric_radix_sv, param);
13943 #endif /* !USE_LOCALE_NUMERIC */
13944
13945     /* Unicode inversion lists */
13946     PL_Latin1           = sv_dup_inc(proto_perl->ILatin1, param);
13947     PL_UpperLatin1      = sv_dup_inc(proto_perl->IUpperLatin1, param);
13948     PL_AboveLatin1      = sv_dup_inc(proto_perl->IAboveLatin1, param);
13949
13950     PL_NonL1NonFinalFold = sv_dup_inc(proto_perl->INonL1NonFinalFold, param);
13951     PL_HasMultiCharFold = sv_dup_inc(proto_perl->IHasMultiCharFold, param);
13952
13953     /* utf8 character class swashes */
13954     for (i = 0; i < POSIX_SWASH_COUNT; i++) {
13955         PL_utf8_swash_ptrs[i] = sv_dup_inc(proto_perl->Iutf8_swash_ptrs[i], param);
13956     }
13957     for (i = 0; i < POSIX_CC_COUNT; i++) {
13958         PL_XPosix_ptrs[i] = sv_dup_inc(proto_perl->IXPosix_ptrs[i], param);
13959     }
13960     PL_utf8_mark        = sv_dup_inc(proto_perl->Iutf8_mark, param);
13961     PL_utf8_X_regular_begin     = sv_dup_inc(proto_perl->Iutf8_X_regular_begin, param);
13962     PL_utf8_X_extend    = sv_dup_inc(proto_perl->Iutf8_X_extend, param);
13963     PL_utf8_toupper     = sv_dup_inc(proto_perl->Iutf8_toupper, param);
13964     PL_utf8_totitle     = sv_dup_inc(proto_perl->Iutf8_totitle, param);
13965     PL_utf8_tolower     = sv_dup_inc(proto_perl->Iutf8_tolower, param);
13966     PL_utf8_tofold      = sv_dup_inc(proto_perl->Iutf8_tofold, param);
13967     PL_utf8_idstart     = sv_dup_inc(proto_perl->Iutf8_idstart, param);
13968     PL_utf8_xidstart    = sv_dup_inc(proto_perl->Iutf8_xidstart, param);
13969     PL_utf8_perl_idstart = sv_dup_inc(proto_perl->Iutf8_perl_idstart, param);
13970     PL_utf8_perl_idcont = sv_dup_inc(proto_perl->Iutf8_perl_idcont, param);
13971     PL_utf8_idcont      = sv_dup_inc(proto_perl->Iutf8_idcont, param);
13972     PL_utf8_xidcont     = sv_dup_inc(proto_perl->Iutf8_xidcont, param);
13973     PL_utf8_foldable    = sv_dup_inc(proto_perl->Iutf8_foldable, param);
13974     PL_utf8_charname_begin = sv_dup_inc(proto_perl->Iutf8_charname_begin, param);
13975     PL_utf8_charname_continue = sv_dup_inc(proto_perl->Iutf8_charname_continue, param);
13976
13977     if (proto_perl->Ipsig_pend) {
13978         Newxz(PL_psig_pend, SIG_SIZE, int);
13979     }
13980     else {
13981         PL_psig_pend    = (int*)NULL;
13982     }
13983
13984     if (proto_perl->Ipsig_name) {
13985         Newx(PL_psig_name, 2 * SIG_SIZE, SV*);
13986         sv_dup_inc_multiple(proto_perl->Ipsig_name, PL_psig_name, 2 * SIG_SIZE,
13987                             param);
13988         PL_psig_ptr = PL_psig_name + SIG_SIZE;
13989     }
13990     else {
13991         PL_psig_ptr     = (SV**)NULL;
13992         PL_psig_name    = (SV**)NULL;
13993     }
13994
13995     if (flags & CLONEf_COPY_STACKS) {
13996         Newx(PL_tmps_stack, PL_tmps_max, SV*);
13997         sv_dup_inc_multiple(proto_perl->Itmps_stack, PL_tmps_stack,
13998                             PL_tmps_ix+1, param);
13999
14000         /* next PUSHMARK() sets *(PL_markstack_ptr+1) */
14001         i = proto_perl->Imarkstack_max - proto_perl->Imarkstack;
14002         Newxz(PL_markstack, i, I32);
14003         PL_markstack_max        = PL_markstack + (proto_perl->Imarkstack_max
14004                                                   - proto_perl->Imarkstack);
14005         PL_markstack_ptr        = PL_markstack + (proto_perl->Imarkstack_ptr
14006                                                   - proto_perl->Imarkstack);
14007         Copy(proto_perl->Imarkstack, PL_markstack,
14008              PL_markstack_ptr - PL_markstack + 1, I32);
14009
14010         /* next push_scope()/ENTER sets PL_scopestack[PL_scopestack_ix]
14011          * NOTE: unlike the others! */
14012         Newxz(PL_scopestack, PL_scopestack_max, I32);
14013         Copy(proto_perl->Iscopestack, PL_scopestack, PL_scopestack_ix, I32);
14014
14015 #ifdef DEBUGGING
14016         Newxz(PL_scopestack_name, PL_scopestack_max, const char *);
14017         Copy(proto_perl->Iscopestack_name, PL_scopestack_name, PL_scopestack_ix, const char *);
14018 #endif
14019         /* reset stack AV to correct length before its duped via
14020          * PL_curstackinfo */
14021         AvFILLp(proto_perl->Icurstack) =
14022                             proto_perl->Istack_sp - proto_perl->Istack_base;
14023
14024         /* NOTE: si_dup() looks at PL_markstack */
14025         PL_curstackinfo         = si_dup(proto_perl->Icurstackinfo, param);
14026
14027         /* PL_curstack          = PL_curstackinfo->si_stack; */
14028         PL_curstack             = av_dup(proto_perl->Icurstack, param);
14029         PL_mainstack            = av_dup(proto_perl->Imainstack, param);
14030
14031         /* next PUSHs() etc. set *(PL_stack_sp+1) */
14032         PL_stack_base           = AvARRAY(PL_curstack);
14033         PL_stack_sp             = PL_stack_base + (proto_perl->Istack_sp
14034                                                    - proto_perl->Istack_base);
14035         PL_stack_max            = PL_stack_base + AvMAX(PL_curstack);
14036
14037         /*Newxz(PL_savestack, PL_savestack_max, ANY);*/
14038         PL_savestack            = ss_dup(proto_perl, param);
14039     }
14040     else {
14041         init_stacks();
14042         ENTER;                  /* perl_destruct() wants to LEAVE; */
14043     }
14044
14045     PL_statgv           = gv_dup(proto_perl->Istatgv, param);
14046     PL_statname         = sv_dup_inc(proto_perl->Istatname, param);
14047
14048     PL_rs               = sv_dup_inc(proto_perl->Irs, param);
14049     PL_last_in_gv       = gv_dup(proto_perl->Ilast_in_gv, param);
14050     PL_defoutgv         = gv_dup_inc(proto_perl->Idefoutgv, param);
14051     PL_toptarget        = sv_dup_inc(proto_perl->Itoptarget, param);
14052     PL_bodytarget       = sv_dup_inc(proto_perl->Ibodytarget, param);
14053     PL_formtarget       = sv_dup(proto_perl->Iformtarget, param);
14054
14055     PL_errors           = sv_dup_inc(proto_perl->Ierrors, param);
14056
14057     PL_sortcop          = (OP*)any_dup(proto_perl->Isortcop, proto_perl);
14058     PL_firstgv          = gv_dup_inc(proto_perl->Ifirstgv, param);
14059     PL_secondgv         = gv_dup_inc(proto_perl->Isecondgv, param);
14060
14061     PL_stashcache       = newHV();
14062
14063     PL_watchaddr        = (char **) ptr_table_fetch(PL_ptr_table,
14064                                             proto_perl->Iwatchaddr);
14065     PL_watchok          = PL_watchaddr ? * PL_watchaddr : NULL;
14066     if (PL_debug && PL_watchaddr) {
14067         PerlIO_printf(Perl_debug_log,
14068           "WATCHING: %"UVxf" cloned as %"UVxf" with value %"UVxf"\n",
14069           PTR2UV(proto_perl->Iwatchaddr), PTR2UV(PL_watchaddr),
14070           PTR2UV(PL_watchok));
14071     }
14072
14073     PL_registered_mros  = hv_dup_inc(proto_perl->Iregistered_mros, param);
14074     PL_blockhooks       = av_dup_inc(proto_perl->Iblockhooks, param);
14075     PL_utf8_foldclosures = hv_dup_inc(proto_perl->Iutf8_foldclosures, param);
14076
14077     /* Call the ->CLONE method, if it exists, for each of the stashes
14078        identified by sv_dup() above.
14079     */
14080     while(av_tindex(param->stashes) != -1) {
14081         HV* const stash = MUTABLE_HV(av_shift(param->stashes));
14082         GV* const cloner = gv_fetchmethod_autoload(stash, "CLONE", 0);
14083         if (cloner && GvCV(cloner)) {
14084             dSP;
14085             ENTER;
14086             SAVETMPS;
14087             PUSHMARK(SP);
14088             mXPUSHs(newSVhek(HvNAME_HEK(stash)));
14089             PUTBACK;
14090             call_sv(MUTABLE_SV(GvCV(cloner)), G_DISCARD);
14091             FREETMPS;
14092             LEAVE;
14093         }
14094     }
14095
14096     if (!(flags & CLONEf_KEEP_PTR_TABLE)) {
14097         ptr_table_free(PL_ptr_table);
14098         PL_ptr_table = NULL;
14099     }
14100
14101     if (!(flags & CLONEf_COPY_STACKS)) {
14102         unreferenced_to_tmp_stack(param->unreferenced);
14103     }
14104
14105     SvREFCNT_dec(param->stashes);
14106
14107     /* orphaned? eg threads->new inside BEGIN or use */
14108     if (PL_compcv && ! SvREFCNT(PL_compcv)) {
14109         SvREFCNT_inc_simple_void(PL_compcv);
14110         SAVEFREESV(PL_compcv);
14111     }
14112
14113     return my_perl;
14114 }
14115
14116 static void
14117 S_unreferenced_to_tmp_stack(pTHX_ AV *const unreferenced)
14118 {
14119     PERL_ARGS_ASSERT_UNREFERENCED_TO_TMP_STACK;
14120     
14121     if (AvFILLp(unreferenced) > -1) {
14122         SV **svp = AvARRAY(unreferenced);
14123         SV **const last = svp + AvFILLp(unreferenced);
14124         SSize_t count = 0;
14125
14126         do {
14127             if (SvREFCNT(*svp) == 1)
14128                 ++count;
14129         } while (++svp <= last);
14130
14131         EXTEND_MORTAL(count);
14132         svp = AvARRAY(unreferenced);
14133
14134         do {
14135             if (SvREFCNT(*svp) == 1) {
14136                 /* Our reference is the only one to this SV. This means that
14137                    in this thread, the scalar effectively has a 0 reference.
14138                    That doesn't work (cleanup never happens), so donate our
14139                    reference to it onto the save stack. */
14140                 PL_tmps_stack[++PL_tmps_ix] = *svp;
14141             } else {
14142                 /* As an optimisation, because we are already walking the
14143                    entire array, instead of above doing either
14144                    SvREFCNT_inc(*svp) or *svp = &PL_sv_undef, we can instead
14145                    release our reference to the scalar, so that at the end of
14146                    the array owns zero references to the scalars it happens to
14147                    point to. We are effectively converting the array from
14148                    AvREAL() on to AvREAL() off. This saves the av_clear()
14149                    (triggered by the SvREFCNT_dec(unreferenced) below) from
14150                    walking the array a second time.  */
14151                 SvREFCNT_dec(*svp);
14152             }
14153
14154         } while (++svp <= last);
14155         AvREAL_off(unreferenced);
14156     }
14157     SvREFCNT_dec_NN(unreferenced);
14158 }
14159
14160 void
14161 Perl_clone_params_del(CLONE_PARAMS *param)
14162 {
14163     /* This seemingly funky ordering keeps the build with PERL_GLOBAL_STRUCT
14164        happy: */
14165     PerlInterpreter *const to = param->new_perl;
14166     dTHXa(to);
14167     PerlInterpreter *const was = PERL_GET_THX;
14168
14169     PERL_ARGS_ASSERT_CLONE_PARAMS_DEL;
14170
14171     if (was != to) {
14172         PERL_SET_THX(to);
14173     }
14174
14175     SvREFCNT_dec(param->stashes);
14176     if (param->unreferenced)
14177         unreferenced_to_tmp_stack(param->unreferenced);
14178
14179     Safefree(param);
14180
14181     if (was != to) {
14182         PERL_SET_THX(was);
14183     }
14184 }
14185
14186 CLONE_PARAMS *
14187 Perl_clone_params_new(PerlInterpreter *const from, PerlInterpreter *const to)
14188 {
14189     dVAR;
14190     /* Need to play this game, as newAV() can call safesysmalloc(), and that
14191        does a dTHX; to get the context from thread local storage.
14192        FIXME - under PERL_CORE Newx(), Safefree() and friends should expand to
14193        a version that passes in my_perl.  */
14194     PerlInterpreter *const was = PERL_GET_THX;
14195     CLONE_PARAMS *param;
14196
14197     PERL_ARGS_ASSERT_CLONE_PARAMS_NEW;
14198
14199     if (was != to) {
14200         PERL_SET_THX(to);
14201     }
14202
14203     /* Given that we've set the context, we can do this unshared.  */
14204     Newx(param, 1, CLONE_PARAMS);
14205
14206     param->flags = 0;
14207     param->proto_perl = from;
14208     param->new_perl = to;
14209     param->stashes = (AV *)Perl_newSV_type(to, SVt_PVAV);
14210     AvREAL_off(param->stashes);
14211     param->unreferenced = (AV *)Perl_newSV_type(to, SVt_PVAV);
14212
14213     if (was != to) {
14214         PERL_SET_THX(was);
14215     }
14216     return param;
14217 }
14218
14219 #endif /* USE_ITHREADS */
14220
14221 void
14222 Perl_init_constants(pTHX)
14223 {
14224     SvREFCNT(&PL_sv_undef)      = SvREFCNT_IMMORTAL;
14225     SvFLAGS(&PL_sv_undef)       = SVf_READONLY|SVt_NULL;
14226     SvANY(&PL_sv_undef)         = NULL;
14227
14228     SvANY(&PL_sv_no)            = new_XPVNV();
14229     SvREFCNT(&PL_sv_no)         = SvREFCNT_IMMORTAL;
14230     SvFLAGS(&PL_sv_no)          = SVt_PVNV|SVf_READONLY
14231                                   |SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
14232                                   |SVp_POK|SVf_POK;
14233
14234     SvANY(&PL_sv_yes)           = new_XPVNV();
14235     SvREFCNT(&PL_sv_yes)        = SvREFCNT_IMMORTAL;
14236     SvFLAGS(&PL_sv_yes)         = SVt_PVNV|SVf_READONLY
14237                                   |SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
14238                                   |SVp_POK|SVf_POK;
14239
14240     SvPV_set(&PL_sv_no, (char*)PL_No);
14241     SvCUR_set(&PL_sv_no, 0);
14242     SvLEN_set(&PL_sv_no, 0);
14243     SvIV_set(&PL_sv_no, 0);
14244     SvNV_set(&PL_sv_no, 0);
14245
14246     SvPV_set(&PL_sv_yes, (char*)PL_Yes);
14247     SvCUR_set(&PL_sv_yes, 1);
14248     SvLEN_set(&PL_sv_yes, 0);
14249     SvIV_set(&PL_sv_yes, 1);
14250     SvNV_set(&PL_sv_yes, 1);
14251 }
14252
14253 /*
14254 =head1 Unicode Support
14255
14256 =for apidoc sv_recode_to_utf8
14257
14258 The encoding is assumed to be an Encode object, on entry the PV
14259 of the sv is assumed to be octets in that encoding, and the sv
14260 will be converted into Unicode (and UTF-8).
14261
14262 If the sv already is UTF-8 (or if it is not POK), or if the encoding
14263 is not a reference, nothing is done to the sv.  If the encoding is not
14264 an C<Encode::XS> Encoding object, bad things will happen.
14265 (See F<lib/encoding.pm> and L<Encode>.)
14266
14267 The PV of the sv is returned.
14268
14269 =cut */
14270
14271 char *
14272 Perl_sv_recode_to_utf8(pTHX_ SV *sv, SV *encoding)
14273 {
14274     dVAR;
14275
14276     PERL_ARGS_ASSERT_SV_RECODE_TO_UTF8;
14277
14278     if (SvPOK(sv) && !SvUTF8(sv) && !IN_BYTES && SvROK(encoding)) {
14279         SV *uni;
14280         STRLEN len;
14281         const char *s;
14282         dSP;
14283         SV *nsv = sv;
14284         ENTER;
14285         PUSHSTACK;
14286         SAVETMPS;
14287         if (SvPADTMP(nsv)) {
14288             nsv = sv_newmortal();
14289             SvSetSV_nosteal(nsv, sv);
14290         }
14291         save_re_context();
14292         PUSHMARK(sp);
14293         EXTEND(SP, 3);
14294         PUSHs(encoding);
14295         PUSHs(nsv);
14296 /*
14297   NI-S 2002/07/09
14298   Passing sv_yes is wrong - it needs to be or'ed set of constants
14299   for Encode::XS, while UTf-8 decode (currently) assumes a true value means
14300   remove converted chars from source.
14301
14302   Both will default the value - let them.
14303
14304         XPUSHs(&PL_sv_yes);
14305 */
14306         PUTBACK;
14307         call_method("decode", G_SCALAR);
14308         SPAGAIN;
14309         uni = POPs;
14310         PUTBACK;
14311         s = SvPV_const(uni, len);
14312         if (s != SvPVX_const(sv)) {
14313             SvGROW(sv, len + 1);
14314             Move(s, SvPVX(sv), len + 1, char);
14315             SvCUR_set(sv, len);
14316         }
14317         FREETMPS;
14318         POPSTACK;
14319         LEAVE;
14320         if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
14321             /* clear pos and any utf8 cache */
14322             MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
14323             if (mg)
14324                 mg->mg_len = -1;
14325             if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
14326                 magic_setutf8(sv,mg); /* clear UTF8 cache */
14327         }
14328         SvUTF8_on(sv);
14329         return SvPVX(sv);
14330     }
14331     return SvPOKp(sv) ? SvPVX(sv) : NULL;
14332 }
14333
14334 /*
14335 =for apidoc sv_cat_decode
14336
14337 The encoding is assumed to be an Encode object, the PV of the ssv is
14338 assumed to be octets in that encoding and decoding the input starts
14339 from the position which (PV + *offset) pointed to.  The dsv will be
14340 concatenated the decoded UTF-8 string from ssv.  Decoding will terminate
14341 when the string tstr appears in decoding output or the input ends on
14342 the PV of the ssv.  The value which the offset points will be modified
14343 to the last input position on the ssv.
14344
14345 Returns TRUE if the terminator was found, else returns FALSE.
14346
14347 =cut */
14348
14349 bool
14350 Perl_sv_cat_decode(pTHX_ SV *dsv, SV *encoding,
14351                    SV *ssv, int *offset, char *tstr, int tlen)
14352 {
14353     dVAR;
14354     bool ret = FALSE;
14355
14356     PERL_ARGS_ASSERT_SV_CAT_DECODE;
14357
14358     if (SvPOK(ssv) && SvPOK(dsv) && SvROK(encoding) && offset) {
14359         SV *offsv;
14360         dSP;
14361         ENTER;
14362         SAVETMPS;
14363         save_re_context();
14364         PUSHMARK(sp);
14365         EXTEND(SP, 6);
14366         PUSHs(encoding);
14367         PUSHs(dsv);
14368         PUSHs(ssv);
14369         offsv = newSViv(*offset);
14370         mPUSHs(offsv);
14371         mPUSHp(tstr, tlen);
14372         PUTBACK;
14373         call_method("cat_decode", G_SCALAR);
14374         SPAGAIN;
14375         ret = SvTRUE(TOPs);
14376         *offset = SvIV(offsv);
14377         PUTBACK;
14378         FREETMPS;
14379         LEAVE;
14380     }
14381     else
14382         Perl_croak(aTHX_ "Invalid argument to sv_cat_decode");
14383     return ret;
14384
14385 }
14386
14387 /* ---------------------------------------------------------------------
14388  *
14389  * support functions for report_uninit()
14390  */
14391
14392 /* the maxiumum size of array or hash where we will scan looking
14393  * for the undefined element that triggered the warning */
14394
14395 #define FUV_MAX_SEARCH_SIZE 1000
14396
14397 /* Look for an entry in the hash whose value has the same SV as val;
14398  * If so, return a mortal copy of the key. */
14399
14400 STATIC SV*
14401 S_find_hash_subscript(pTHX_ const HV *const hv, const SV *const val)
14402 {
14403     dVAR;
14404     HE **array;
14405     I32 i;
14406
14407     PERL_ARGS_ASSERT_FIND_HASH_SUBSCRIPT;
14408
14409     if (!hv || SvMAGICAL(hv) || !HvARRAY(hv) ||
14410                         (HvTOTALKEYS(hv) > FUV_MAX_SEARCH_SIZE))
14411         return NULL;
14412
14413     array = HvARRAY(hv);
14414
14415     for (i=HvMAX(hv); i>=0; i--) {
14416         HE *entry;
14417         for (entry = array[i]; entry; entry = HeNEXT(entry)) {
14418             if (HeVAL(entry) != val)
14419                 continue;
14420             if (    HeVAL(entry) == &PL_sv_undef ||
14421                     HeVAL(entry) == &PL_sv_placeholder)
14422                 continue;
14423             if (!HeKEY(entry))
14424                 return NULL;
14425             if (HeKLEN(entry) == HEf_SVKEY)
14426                 return sv_mortalcopy(HeKEY_sv(entry));
14427             return sv_2mortal(newSVhek(HeKEY_hek(entry)));
14428         }
14429     }
14430     return NULL;
14431 }
14432
14433 /* Look for an entry in the array whose value has the same SV as val;
14434  * If so, return the index, otherwise return -1. */
14435
14436 STATIC I32
14437 S_find_array_subscript(pTHX_ const AV *const av, const SV *const val)
14438 {
14439     dVAR;
14440
14441     PERL_ARGS_ASSERT_FIND_ARRAY_SUBSCRIPT;
14442
14443     if (!av || SvMAGICAL(av) || !AvARRAY(av) ||
14444                         (AvFILLp(av) > FUV_MAX_SEARCH_SIZE))
14445         return -1;
14446
14447     if (val != &PL_sv_undef) {
14448         SV ** const svp = AvARRAY(av);
14449         I32 i;
14450
14451         for (i=AvFILLp(av); i>=0; i--)
14452             if (svp[i] == val)
14453                 return i;
14454     }
14455     return -1;
14456 }
14457
14458 /* varname(): return the name of a variable, optionally with a subscript.
14459  * If gv is non-zero, use the name of that global, along with gvtype (one
14460  * of "$", "@", "%"); otherwise use the name of the lexical at pad offset
14461  * targ.  Depending on the value of the subscript_type flag, return:
14462  */
14463
14464 #define FUV_SUBSCRIPT_NONE      1       /* "@foo"          */
14465 #define FUV_SUBSCRIPT_ARRAY     2       /* "$foo[aindex]"  */
14466 #define FUV_SUBSCRIPT_HASH      3       /* "$foo{keyname}" */
14467 #define FUV_SUBSCRIPT_WITHIN    4       /* "within @foo"   */
14468
14469 SV*
14470 Perl_varname(pTHX_ const GV *const gv, const char gvtype, PADOFFSET targ,
14471         const SV *const keyname, I32 aindex, int subscript_type)
14472 {
14473
14474     SV * const name = sv_newmortal();
14475     if (gv && isGV(gv)) {
14476         char buffer[2];
14477         buffer[0] = gvtype;
14478         buffer[1] = 0;
14479
14480         /* as gv_fullname4(), but add literal '^' for $^FOO names  */
14481
14482         gv_fullname4(name, gv, buffer, 0);
14483
14484         if ((unsigned int)SvPVX(name)[1] <= 26) {
14485             buffer[0] = '^';
14486             buffer[1] = SvPVX(name)[1] + 'A' - 1;
14487
14488             /* Swap the 1 unprintable control character for the 2 byte pretty
14489                version - ie substr($name, 1, 1) = $buffer; */
14490             sv_insert(name, 1, 1, buffer, 2);
14491         }
14492     }
14493     else {
14494         CV * const cv = gv ? ((CV *)gv) : find_runcv(NULL);
14495         SV *sv;
14496         AV *av;
14497
14498         assert(!cv || SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
14499
14500         if (!cv || !CvPADLIST(cv))
14501             return NULL;
14502         av = *PadlistARRAY(CvPADLIST(cv));
14503         sv = *av_fetch(av, targ, FALSE);
14504         sv_setsv_flags(name, sv, 0);
14505     }
14506
14507     if (subscript_type == FUV_SUBSCRIPT_HASH) {
14508         SV * const sv = newSV(0);
14509         *SvPVX(name) = '$';
14510         Perl_sv_catpvf(aTHX_ name, "{%s}",
14511             pv_pretty(sv, SvPVX_const(keyname), SvCUR(keyname), 32, NULL, NULL,
14512                     PERL_PV_PRETTY_DUMP | PERL_PV_ESCAPE_UNI_DETECT ));
14513         SvREFCNT_dec_NN(sv);
14514     }
14515     else if (subscript_type == FUV_SUBSCRIPT_ARRAY) {
14516         *SvPVX(name) = '$';
14517         Perl_sv_catpvf(aTHX_ name, "[%"IVdf"]", (IV)aindex);
14518     }
14519     else if (subscript_type == FUV_SUBSCRIPT_WITHIN) {
14520         /* We know that name has no magic, so can use 0 instead of SV_GMAGIC */
14521         Perl_sv_insert_flags(aTHX_ name, 0, 0,  STR_WITH_LEN("within "), 0);
14522     }
14523
14524     return name;
14525 }
14526
14527
14528 /*
14529 =for apidoc find_uninit_var
14530
14531 Find the name of the undefined variable (if any) that caused the operator
14532 to issue a "Use of uninitialized value" warning.
14533 If match is true, only return a name if its value matches uninit_sv.
14534 So roughly speaking, if a unary operator (such as OP_COS) generates a
14535 warning, then following the direct child of the op may yield an
14536 OP_PADSV or OP_GV that gives the name of the undefined variable.  On the
14537 other hand, with OP_ADD there are two branches to follow, so we only print
14538 the variable name if we get an exact match.
14539
14540 The name is returned as a mortal SV.
14541
14542 Assumes that PL_op is the op that originally triggered the error, and that
14543 PL_comppad/PL_curpad points to the currently executing pad.
14544
14545 =cut
14546 */
14547
14548 STATIC SV *
14549 S_find_uninit_var(pTHX_ const OP *const obase, const SV *const uninit_sv,
14550                   bool match)
14551 {
14552     dVAR;
14553     SV *sv;
14554     const GV *gv;
14555     const OP *o, *o2, *kid;
14556
14557     if (!obase || (match && (!uninit_sv || uninit_sv == &PL_sv_undef ||
14558                             uninit_sv == &PL_sv_placeholder)))
14559         return NULL;
14560
14561     switch (obase->op_type) {
14562
14563     case OP_RV2AV:
14564     case OP_RV2HV:
14565     case OP_PADAV:
14566     case OP_PADHV:
14567       {
14568         const bool pad  = (    obase->op_type == OP_PADAV
14569                             || obase->op_type == OP_PADHV
14570                             || obase->op_type == OP_PADRANGE
14571                           );
14572
14573         const bool hash = (    obase->op_type == OP_PADHV
14574                             || obase->op_type == OP_RV2HV
14575                             || (obase->op_type == OP_PADRANGE
14576                                 && SvTYPE(PAD_SVl(obase->op_targ)) == SVt_PVHV)
14577                           );
14578         I32 index = 0;
14579         SV *keysv = NULL;
14580         int subscript_type = FUV_SUBSCRIPT_WITHIN;
14581
14582         if (pad) { /* @lex, %lex */
14583             sv = PAD_SVl(obase->op_targ);
14584             gv = NULL;
14585         }
14586         else {
14587             if (cUNOPx(obase)->op_first->op_type == OP_GV) {
14588             /* @global, %global */
14589                 gv = cGVOPx_gv(cUNOPx(obase)->op_first);
14590                 if (!gv)
14591                     break;
14592                 sv = hash ? MUTABLE_SV(GvHV(gv)): MUTABLE_SV(GvAV(gv));
14593             }
14594             else if (obase == PL_op) /* @{expr}, %{expr} */
14595                 return find_uninit_var(cUNOPx(obase)->op_first,
14596                                                     uninit_sv, match);
14597             else /* @{expr}, %{expr} as a sub-expression */
14598                 return NULL;
14599         }
14600
14601         /* attempt to find a match within the aggregate */
14602         if (hash) {
14603             keysv = find_hash_subscript((const HV*)sv, uninit_sv);
14604             if (keysv)
14605                 subscript_type = FUV_SUBSCRIPT_HASH;
14606         }
14607         else {
14608             index = find_array_subscript((const AV *)sv, uninit_sv);
14609             if (index >= 0)
14610                 subscript_type = FUV_SUBSCRIPT_ARRAY;
14611         }
14612
14613         if (match && subscript_type == FUV_SUBSCRIPT_WITHIN)
14614             break;
14615
14616         return varname(gv, hash ? '%' : '@', obase->op_targ,
14617                                     keysv, index, subscript_type);
14618       }
14619
14620     case OP_RV2SV:
14621         if (cUNOPx(obase)->op_first->op_type == OP_GV) {
14622             /* $global */
14623             gv = cGVOPx_gv(cUNOPx(obase)->op_first);
14624             if (!gv || !GvSTASH(gv))
14625                 break;
14626             if (match && (GvSV(gv) != uninit_sv))
14627                 break;
14628             return varname(gv, '$', 0, NULL, 0, FUV_SUBSCRIPT_NONE);
14629         }
14630         /* ${expr} */
14631         return find_uninit_var(cUNOPx(obase)->op_first, uninit_sv, 1);
14632
14633     case OP_PADSV:
14634         if (match && PAD_SVl(obase->op_targ) != uninit_sv)
14635             break;
14636         return varname(NULL, '$', obase->op_targ,
14637                                     NULL, 0, FUV_SUBSCRIPT_NONE);
14638
14639     case OP_GVSV:
14640         gv = cGVOPx_gv(obase);
14641         if (!gv || (match && GvSV(gv) != uninit_sv) || !GvSTASH(gv))
14642             break;
14643         return varname(gv, '$', 0, NULL, 0, FUV_SUBSCRIPT_NONE);
14644
14645     case OP_AELEMFAST_LEX:
14646         if (match) {
14647             SV **svp;
14648             AV *av = MUTABLE_AV(PAD_SV(obase->op_targ));
14649             if (!av || SvRMAGICAL(av))
14650                 break;
14651             svp = av_fetch(av, (I8)obase->op_private, FALSE);
14652             if (!svp || *svp != uninit_sv)
14653                 break;
14654         }
14655         return varname(NULL, '$', obase->op_targ,
14656                        NULL, (I8)obase->op_private, FUV_SUBSCRIPT_ARRAY);
14657     case OP_AELEMFAST:
14658         {
14659             gv = cGVOPx_gv(obase);
14660             if (!gv)
14661                 break;
14662             if (match) {
14663                 SV **svp;
14664                 AV *const av = GvAV(gv);
14665                 if (!av || SvRMAGICAL(av))
14666                     break;
14667                 svp = av_fetch(av, (I8)obase->op_private, FALSE);
14668                 if (!svp || *svp != uninit_sv)
14669                     break;
14670             }
14671             return varname(gv, '$', 0,
14672                     NULL, (I8)obase->op_private, FUV_SUBSCRIPT_ARRAY);
14673         }
14674         break;
14675
14676     case OP_EXISTS:
14677         o = cUNOPx(obase)->op_first;
14678         if (!o || o->op_type != OP_NULL ||
14679                 ! (o->op_targ == OP_AELEM || o->op_targ == OP_HELEM))
14680             break;
14681         return find_uninit_var(cBINOPo->op_last, uninit_sv, match);
14682
14683     case OP_AELEM:
14684     case OP_HELEM:
14685     {
14686         bool negate = FALSE;
14687
14688         if (PL_op == obase)
14689             /* $a[uninit_expr] or $h{uninit_expr} */
14690             return find_uninit_var(cBINOPx(obase)->op_last, uninit_sv, match);
14691
14692         gv = NULL;
14693         o = cBINOPx(obase)->op_first;
14694         kid = cBINOPx(obase)->op_last;
14695
14696         /* get the av or hv, and optionally the gv */
14697         sv = NULL;
14698         if  (o->op_type == OP_PADAV || o->op_type == OP_PADHV) {
14699             sv = PAD_SV(o->op_targ);
14700         }
14701         else if ((o->op_type == OP_RV2AV || o->op_type == OP_RV2HV)
14702                 && cUNOPo->op_first->op_type == OP_GV)
14703         {
14704             gv = cGVOPx_gv(cUNOPo->op_first);
14705             if (!gv)
14706                 break;
14707             sv = o->op_type
14708                 == OP_RV2HV ? MUTABLE_SV(GvHV(gv)) : MUTABLE_SV(GvAV(gv));
14709         }
14710         if (!sv)
14711             break;
14712
14713         if (kid && kid->op_type == OP_NEGATE) {
14714             negate = TRUE;
14715             kid = cUNOPx(kid)->op_first;
14716         }
14717
14718         if (kid && kid->op_type == OP_CONST && SvOK(cSVOPx_sv(kid))) {
14719             /* index is constant */
14720             SV* kidsv;
14721             if (negate) {
14722                 kidsv = sv_2mortal(newSVpvs("-"));
14723                 sv_catsv(kidsv, cSVOPx_sv(kid));
14724             }
14725             else
14726                 kidsv = cSVOPx_sv(kid);
14727             if (match) {
14728                 if (SvMAGICAL(sv))
14729                     break;
14730                 if (obase->op_type == OP_HELEM) {
14731                     HE* he = hv_fetch_ent(MUTABLE_HV(sv), kidsv, 0, 0);
14732                     if (!he || HeVAL(he) != uninit_sv)
14733                         break;
14734                 }
14735                 else {
14736                     SV * const  opsv = cSVOPx_sv(kid);
14737                     const IV  opsviv = SvIV(opsv);
14738                     SV * const * const svp = av_fetch(MUTABLE_AV(sv),
14739                         negate ? - opsviv : opsviv,
14740                         FALSE);
14741                     if (!svp || *svp != uninit_sv)
14742                         break;
14743                 }
14744             }
14745             if (obase->op_type == OP_HELEM)
14746                 return varname(gv, '%', o->op_targ,
14747                             kidsv, 0, FUV_SUBSCRIPT_HASH);
14748             else
14749                 return varname(gv, '@', o->op_targ, NULL,
14750                     negate ? - SvIV(cSVOPx_sv(kid)) : SvIV(cSVOPx_sv(kid)),
14751                     FUV_SUBSCRIPT_ARRAY);
14752         }
14753         else  {
14754             /* index is an expression;
14755              * attempt to find a match within the aggregate */
14756             if (obase->op_type == OP_HELEM) {
14757                 SV * const keysv = find_hash_subscript((const HV*)sv, uninit_sv);
14758                 if (keysv)
14759                     return varname(gv, '%', o->op_targ,
14760                                                 keysv, 0, FUV_SUBSCRIPT_HASH);
14761             }
14762             else {
14763                 const I32 index
14764                     = find_array_subscript((const AV *)sv, uninit_sv);
14765                 if (index >= 0)
14766                     return varname(gv, '@', o->op_targ,
14767                                         NULL, index, FUV_SUBSCRIPT_ARRAY);
14768             }
14769             if (match)
14770                 break;
14771             return varname(gv,
14772                 (o->op_type == OP_PADAV || o->op_type == OP_RV2AV)
14773                 ? '@' : '%',
14774                 o->op_targ, NULL, 0, FUV_SUBSCRIPT_WITHIN);
14775         }
14776         break;
14777     }
14778
14779     case OP_AASSIGN:
14780         /* only examine RHS */
14781         return find_uninit_var(cBINOPx(obase)->op_first, uninit_sv, match);
14782
14783     case OP_OPEN:
14784         o = cUNOPx(obase)->op_first;
14785         if (   o->op_type == OP_PUSHMARK
14786            || (o->op_type == OP_NULL && o->op_targ == OP_PUSHMARK)
14787         )
14788             o = o->op_sibling;
14789
14790         if (!o->op_sibling) {
14791             /* one-arg version of open is highly magical */
14792
14793             if (o->op_type == OP_GV) { /* open FOO; */
14794                 gv = cGVOPx_gv(o);
14795                 if (match && GvSV(gv) != uninit_sv)
14796                     break;
14797                 return varname(gv, '$', 0,
14798                             NULL, 0, FUV_SUBSCRIPT_NONE);
14799             }
14800             /* other possibilities not handled are:
14801              * open $x; or open my $x;  should return '${*$x}'
14802              * open expr;               should return '$'.expr ideally
14803              */
14804              break;
14805         }
14806         goto do_op;
14807
14808     /* ops where $_ may be an implicit arg */
14809     case OP_TRANS:
14810     case OP_TRANSR:
14811     case OP_SUBST:
14812     case OP_MATCH:
14813         if ( !(obase->op_flags & OPf_STACKED)) {
14814             if (uninit_sv == ((obase->op_private & OPpTARGET_MY)
14815                                  ? PAD_SVl(obase->op_targ)
14816                                  : DEFSV))
14817             {
14818                 sv = sv_newmortal();
14819                 sv_setpvs(sv, "$_");
14820                 return sv;
14821             }
14822         }
14823         goto do_op;
14824
14825     case OP_PRTF:
14826     case OP_PRINT:
14827     case OP_SAY:
14828         match = 1; /* print etc can return undef on defined args */
14829         /* skip filehandle as it can't produce 'undef' warning  */
14830         o = cUNOPx(obase)->op_first;
14831         if ((obase->op_flags & OPf_STACKED)
14832             &&
14833                (   o->op_type == OP_PUSHMARK
14834                || (o->op_type == OP_NULL && o->op_targ == OP_PUSHMARK)))
14835             o = o->op_sibling->op_sibling;
14836         goto do_op2;
14837
14838
14839     case OP_ENTEREVAL: /* could be eval $undef or $x='$undef'; eval $x */
14840     case OP_CUSTOM: /* XS or custom code could trigger random warnings */
14841
14842         /* the following ops are capable of returning PL_sv_undef even for
14843          * defined arg(s) */
14844
14845     case OP_BACKTICK:
14846     case OP_PIPE_OP:
14847     case OP_FILENO:
14848     case OP_BINMODE:
14849     case OP_TIED:
14850     case OP_GETC:
14851     case OP_SYSREAD:
14852     case OP_SEND:
14853     case OP_IOCTL:
14854     case OP_SOCKET:
14855     case OP_SOCKPAIR:
14856     case OP_BIND:
14857     case OP_CONNECT:
14858     case OP_LISTEN:
14859     case OP_ACCEPT:
14860     case OP_SHUTDOWN:
14861     case OP_SSOCKOPT:
14862     case OP_GETPEERNAME:
14863     case OP_FTRREAD:
14864     case OP_FTRWRITE:
14865     case OP_FTREXEC:
14866     case OP_FTROWNED:
14867     case OP_FTEREAD:
14868     case OP_FTEWRITE:
14869     case OP_FTEEXEC:
14870     case OP_FTEOWNED:
14871     case OP_FTIS:
14872     case OP_FTZERO:
14873     case OP_FTSIZE:
14874     case OP_FTFILE:
14875     case OP_FTDIR:
14876     case OP_FTLINK:
14877     case OP_FTPIPE:
14878     case OP_FTSOCK:
14879     case OP_FTBLK:
14880     case OP_FTCHR:
14881     case OP_FTTTY:
14882     case OP_FTSUID:
14883     case OP_FTSGID:
14884     case OP_FTSVTX:
14885     case OP_FTTEXT:
14886     case OP_FTBINARY:
14887     case OP_FTMTIME:
14888     case OP_FTATIME:
14889     case OP_FTCTIME:
14890     case OP_READLINK:
14891     case OP_OPEN_DIR:
14892     case OP_READDIR:
14893     case OP_TELLDIR:
14894     case OP_SEEKDIR:
14895     case OP_REWINDDIR:
14896     case OP_CLOSEDIR:
14897     case OP_GMTIME:
14898     case OP_ALARM:
14899     case OP_SEMGET:
14900     case OP_GETLOGIN:
14901     case OP_UNDEF:
14902     case OP_SUBSTR:
14903     case OP_AEACH:
14904     case OP_EACH:
14905     case OP_SORT:
14906     case OP_CALLER:
14907     case OP_DOFILE:
14908     case OP_PROTOTYPE:
14909     case OP_NCMP:
14910     case OP_SMARTMATCH:
14911     case OP_UNPACK:
14912     case OP_SYSOPEN:
14913     case OP_SYSSEEK:
14914         match = 1;
14915         goto do_op;
14916
14917     case OP_ENTERSUB:
14918     case OP_GOTO:
14919         /* XXX tmp hack: these two may call an XS sub, and currently
14920           XS subs don't have a SUB entry on the context stack, so CV and
14921           pad determination goes wrong, and BAD things happen. So, just
14922           don't try to determine the value under those circumstances.
14923           Need a better fix at dome point. DAPM 11/2007 */
14924         break;
14925
14926     case OP_FLIP:
14927     case OP_FLOP:
14928     {
14929         GV * const gv = gv_fetchpvs(".", GV_NOTQUAL, SVt_PV);
14930         if (gv && GvSV(gv) == uninit_sv)
14931             return newSVpvs_flags("$.", SVs_TEMP);
14932         goto do_op;
14933     }
14934
14935     case OP_POS:
14936         /* def-ness of rval pos() is independent of the def-ness of its arg */
14937         if ( !(obase->op_flags & OPf_MOD))
14938             break;
14939
14940     case OP_SCHOMP:
14941     case OP_CHOMP:
14942         if (SvROK(PL_rs) && uninit_sv == SvRV(PL_rs))
14943             return newSVpvs_flags("${$/}", SVs_TEMP);
14944         /* FALLTHROUGH */
14945
14946     default:
14947     do_op:
14948         if (!(obase->op_flags & OPf_KIDS))
14949             break;
14950         o = cUNOPx(obase)->op_first;
14951         
14952     do_op2:
14953         if (!o)
14954             break;
14955
14956         /* This loop checks all the kid ops, skipping any that cannot pos-
14957          * sibly be responsible for the uninitialized value; i.e., defined
14958          * constants and ops that return nothing.  If there is only one op
14959          * left that is not skipped, then we *know* it is responsible for
14960          * the uninitialized value.  If there is more than one op left, we
14961          * have to look for an exact match in the while() loop below.
14962          * Note that we skip padrange, because the individual pad ops that
14963          * it replaced are still in the tree, so we work on them instead.
14964          */
14965         o2 = NULL;
14966         for (kid=o; kid; kid = kid->op_sibling) {
14967             const OPCODE type = kid->op_type;
14968             if ( (type == OP_CONST && SvOK(cSVOPx_sv(kid)))
14969               || (type == OP_NULL  && ! (kid->op_flags & OPf_KIDS))
14970               || (type == OP_PUSHMARK)
14971               || (type == OP_PADRANGE)
14972             )
14973             continue;
14974
14975             if (o2) { /* more than one found */
14976                 o2 = NULL;
14977                 break;
14978             }
14979             o2 = kid;
14980         }
14981         if (o2)
14982             return find_uninit_var(o2, uninit_sv, match);
14983
14984         /* scan all args */
14985         while (o) {
14986             sv = find_uninit_var(o, uninit_sv, 1);
14987             if (sv)
14988                 return sv;
14989             o = o->op_sibling;
14990         }
14991         break;
14992     }
14993     return NULL;
14994 }
14995
14996
14997 /*
14998 =for apidoc report_uninit
14999
15000 Print appropriate "Use of uninitialized variable" warning.
15001
15002 =cut
15003 */
15004
15005 void
15006 Perl_report_uninit(pTHX_ const SV *uninit_sv)
15007 {
15008     dVAR;
15009     if (PL_op) {
15010         SV* varname = NULL;
15011         if (uninit_sv && PL_curpad) {
15012             varname = find_uninit_var(PL_op, uninit_sv,0);
15013             if (varname)
15014                 sv_insert(varname, 0, 0, " ", 1);
15015         }
15016         /* PL_warn_uninit_sv is constant */
15017         GCC_DIAG_IGNORE(-Wformat-nonliteral);
15018         /* diag_listed_as: Use of uninitialized value%s */
15019         Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit_sv,
15020                 SVfARG(varname ? varname : &PL_sv_no),
15021                 " in ", OP_DESC(PL_op));
15022         GCC_DIAG_RESTORE;
15023     }
15024     else {
15025         /* PL_warn_uninit is constant */
15026         GCC_DIAG_IGNORE(-Wformat-nonliteral);
15027         Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
15028                     "", "", "");
15029         GCC_DIAG_RESTORE;
15030     }
15031 }
15032
15033 /*
15034  * Local variables:
15035  * c-indentation-style: bsd
15036  * c-basic-offset: 4
15037  * indent-tabs-mode: nil
15038  * End:
15039  *
15040  * ex: set ts=8 sts=4 sw=4 et:
15041  */