This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
op.h: Correct PERL_LOADMOD_IMPORT_OPS comment
[perl5.git] / sv.c
1 /*    sv.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 by Larry Wall
5  *    and others
6  *
7  *    You may distribute under the terms of either the GNU General Public
8  *    License or the Artistic License, as specified in the README file.
9  *
10  */
11
12 /*
13  * 'I wonder what the Entish is for "yes" and "no",' he thought.
14  *                                                      --Pippin
15  *
16  *     [p.480 of _The Lord of the Rings_, III/iv: "Treebeard"]
17  */
18
19 /*
20  *
21  *
22  * This file contains the code that creates, manipulates and destroys
23  * scalar values (SVs). The other types (AV, HV, GV, etc.) reuse the
24  * structure of an SV, so their creation and destruction is handled
25  * here; higher-level functions are in av.c, hv.c, and so on. Opcode
26  * level functions (eg. substr, split, join) for each of the types are
27  * in the pp*.c files.
28  */
29
30 #include "EXTERN.h"
31 #define PERL_IN_SV_C
32 #include "perl.h"
33 #include "regcomp.h"
34 #ifdef __VMS
35 # include <rms.h>
36 #endif
37
38 #ifdef __Lynx__
39 /* Missing proto on LynxOS */
40   char *gconvert(double, int, int,  char *);
41 #endif
42
43 #ifdef PERL_NEW_COPY_ON_WRITE
44 #   ifndef SV_COW_THRESHOLD
45 #    define SV_COW_THRESHOLD                    0   /* COW iff len > K */
46 #   endif
47 #   ifndef SV_COWBUF_THRESHOLD
48 #    define SV_COWBUF_THRESHOLD                 1250 /* COW iff len > K */
49 #   endif
50 #   ifndef SV_COW_MAX_WASTE_THRESHOLD
51 #    define SV_COW_MAX_WASTE_THRESHOLD          80   /* COW iff (len - cur) < K */
52 #   endif
53 #   ifndef SV_COWBUF_WASTE_THRESHOLD
54 #    define SV_COWBUF_WASTE_THRESHOLD           80   /* COW iff (len - cur) < K */
55 #   endif
56 #   ifndef SV_COW_MAX_WASTE_FACTOR_THRESHOLD
57 #    define SV_COW_MAX_WASTE_FACTOR_THRESHOLD   2    /* COW iff len < (cur * K) */
58 #   endif
59 #   ifndef SV_COWBUF_WASTE_FACTOR_THRESHOLD
60 #    define SV_COWBUF_WASTE_FACTOR_THRESHOLD    2    /* COW iff len < (cur * K) */
61 #   endif
62 #endif
63 /* Work around compiler warnings about unsigned >= THRESHOLD when thres-
64    hold is 0. */
65 #if SV_COW_THRESHOLD
66 # define GE_COW_THRESHOLD(cur) ((cur) >= SV_COW_THRESHOLD)
67 #else
68 # define GE_COW_THRESHOLD(cur) 1
69 #endif
70 #if SV_COWBUF_THRESHOLD
71 # define GE_COWBUF_THRESHOLD(cur) ((cur) >= SV_COWBUF_THRESHOLD)
72 #else
73 # define GE_COWBUF_THRESHOLD(cur) 1
74 #endif
75 #if SV_COW_MAX_WASTE_THRESHOLD
76 # define GE_COW_MAX_WASTE_THRESHOLD(cur,len) (((len)-(cur)) < SV_COW_MAX_WASTE_THRESHOLD)
77 #else
78 # define GE_COW_MAX_WASTE_THRESHOLD(cur,len) 1
79 #endif
80 #if SV_COWBUF_WASTE_THRESHOLD
81 # define GE_COWBUF_WASTE_THRESHOLD(cur,len) (((len)-(cur)) < SV_COWBUF_WASTE_THRESHOLD)
82 #else
83 # define GE_COWBUF_WASTE_THRESHOLD(cur,len) 1
84 #endif
85 #if SV_COW_MAX_WASTE_FACTOR_THRESHOLD
86 # define GE_COW_MAX_WASTE_FACTOR_THRESHOLD(cur,len) ((len) < SV_COW_MAX_WASTE_FACTOR_THRESHOLD * (cur))
87 #else
88 # define GE_COW_MAX_WASTE_FACTOR_THRESHOLD(cur,len) 1
89 #endif
90 #if SV_COWBUF_WASTE_FACTOR_THRESHOLD
91 # define GE_COWBUF_WASTE_FACTOR_THRESHOLD(cur,len) ((len) < SV_COWBUF_WASTE_FACTOR_THRESHOLD * (cur))
92 #else
93 # define GE_COWBUF_WASTE_FACTOR_THRESHOLD(cur,len) 1
94 #endif
95
96 #define CHECK_COW_THRESHOLD(cur,len) (\
97     GE_COW_THRESHOLD((cur)) && \
98     GE_COW_MAX_WASTE_THRESHOLD((cur),(len)) && \
99     GE_COW_MAX_WASTE_FACTOR_THRESHOLD((cur),(len)) \
100 )
101 #define CHECK_COWBUF_THRESHOLD(cur,len) (\
102     GE_COWBUF_THRESHOLD((cur)) && \
103     GE_COWBUF_WASTE_THRESHOLD((cur),(len)) && \
104     GE_COWBUF_WASTE_FACTOR_THRESHOLD((cur),(len)) \
105 )
106
107 #ifdef PERL_UTF8_CACHE_ASSERT
108 /* if adding more checks watch out for the following tests:
109  *   t/op/index.t t/op/length.t t/op/pat.t t/op/substr.t
110  *   lib/utf8.t lib/Unicode/Collate/t/index.t
111  * --jhi
112  */
113 #   define ASSERT_UTF8_CACHE(cache) \
114     STMT_START { if (cache) { assert((cache)[0] <= (cache)[1]); \
115                               assert((cache)[2] <= (cache)[3]); \
116                               assert((cache)[3] <= (cache)[1]);} \
117                               } STMT_END
118 #else
119 #   define ASSERT_UTF8_CACHE(cache) NOOP
120 #endif
121
122 #ifdef PERL_OLD_COPY_ON_WRITE
123 #define SV_COW_NEXT_SV(sv)      INT2PTR(SV *,SvUVX(sv))
124 #define SV_COW_NEXT_SV_SET(current,next)        SvUV_set(current, PTR2UV(next))
125 #endif
126
127 /* ============================================================================
128
129 =head1 Allocation and deallocation of SVs.
130 An SV (or AV, HV, etc.) is allocated in two parts: the head (struct
131 sv, av, hv...) contains type and reference count information, and for
132 many types, a pointer to the body (struct xrv, xpv, xpviv...), which
133 contains fields specific to each type.  Some types store all they need
134 in the head, so don't have a body.
135
136 In all but the most memory-paranoid configurations (ex: PURIFY), heads
137 and bodies are allocated out of arenas, which by default are
138 approximately 4K chunks of memory parcelled up into N heads or bodies.
139 Sv-bodies are allocated by their sv-type, guaranteeing size
140 consistency needed to allocate safely from arrays.
141
142 For SV-heads, the first slot in each arena is reserved, and holds a
143 link to the next arena, some flags, and a note of the number of slots.
144 Snaked through each arena chain is a linked list of free items; when
145 this becomes empty, an extra arena is allocated and divided up into N
146 items which are threaded into the free list.
147
148 SV-bodies are similar, but they use arena-sets by default, which
149 separate the link and info from the arena itself, and reclaim the 1st
150 slot in the arena.  SV-bodies are further described later.
151
152 The following global variables are associated with arenas:
153
154  PL_sv_arenaroot     pointer to list of SV arenas
155  PL_sv_root          pointer to list of free SV structures
156
157  PL_body_arenas      head of linked-list of body arenas
158  PL_body_roots[]     array of pointers to list of free bodies of svtype
159                      arrays are indexed by the svtype needed
160
161 A few special SV heads are not allocated from an arena, but are
162 instead directly created in the interpreter structure, eg PL_sv_undef.
163 The size of arenas can be changed from the default by setting
164 PERL_ARENA_SIZE appropriately at compile time.
165
166 The SV arena serves the secondary purpose of allowing still-live SVs
167 to be located and destroyed during final cleanup.
168
169 At the lowest level, the macros new_SV() and del_SV() grab and free
170 an SV head.  (If debugging with -DD, del_SV() calls the function S_del_sv()
171 to return the SV to the free list with error checking.) new_SV() calls
172 more_sv() / sv_add_arena() to add an extra arena if the free list is empty.
173 SVs in the free list have their SvTYPE field set to all ones.
174
175 At the time of very final cleanup, sv_free_arenas() is called from
176 perl_destruct() to physically free all the arenas allocated since the
177 start of the interpreter.
178
179 The function visit() scans the SV arenas list, and calls a specified
180 function for each SV it finds which is still live - ie which has an SvTYPE
181 other than all 1's, and a non-zero SvREFCNT. visit() is used by the
182 following functions (specified as [function that calls visit()] / [function
183 called by visit() for each SV]):
184
185     sv_report_used() / do_report_used()
186                         dump all remaining SVs (debugging aid)
187
188     sv_clean_objs() / do_clean_objs(),do_clean_named_objs(),
189                       do_clean_named_io_objs(),do_curse()
190                         Attempt to free all objects pointed to by RVs,
191                         try to do the same for all objects indir-
192                         ectly referenced by typeglobs too, and
193                         then do a final sweep, cursing any
194                         objects that remain.  Called once from
195                         perl_destruct(), prior to calling sv_clean_all()
196                         below.
197
198     sv_clean_all() / do_clean_all()
199                         SvREFCNT_dec(sv) each remaining SV, possibly
200                         triggering an sv_free(). It also sets the
201                         SVf_BREAK flag on the SV to indicate that the
202                         refcnt has been artificially lowered, and thus
203                         stopping sv_free() from giving spurious warnings
204                         about SVs which unexpectedly have a refcnt
205                         of zero.  called repeatedly from perl_destruct()
206                         until there are no SVs left.
207
208 =head2 Arena allocator API Summary
209
210 Private API to rest of sv.c
211
212     new_SV(),  del_SV(),
213
214     new_XPVNV(), del_XPVGV(),
215     etc
216
217 Public API:
218
219     sv_report_used(), sv_clean_objs(), sv_clean_all(), sv_free_arenas()
220
221 =cut
222
223  * ========================================================================= */
224
225 /*
226  * "A time to plant, and a time to uproot what was planted..."
227  */
228
229 #ifdef PERL_MEM_LOG
230 #  define MEM_LOG_NEW_SV(sv, file, line, func)  \
231             Perl_mem_log_new_sv(sv, file, line, func)
232 #  define MEM_LOG_DEL_SV(sv, file, line, func)  \
233             Perl_mem_log_del_sv(sv, file, line, func)
234 #else
235 #  define MEM_LOG_NEW_SV(sv, file, line, func)  NOOP
236 #  define MEM_LOG_DEL_SV(sv, file, line, func)  NOOP
237 #endif
238
239 #ifdef DEBUG_LEAKING_SCALARS
240 #  define FREE_SV_DEBUG_FILE(sv) STMT_START { \
241         if ((sv)->sv_debug_file) PerlMemShared_free((sv)->sv_debug_file); \
242     } STMT_END
243 #  define DEBUG_SV_SERIAL(sv)                                               \
244     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) del_SV\n",    \
245             PTR2UV(sv), (long)(sv)->sv_debug_serial))
246 #else
247 #  define FREE_SV_DEBUG_FILE(sv)
248 #  define DEBUG_SV_SERIAL(sv)   NOOP
249 #endif
250
251 #ifdef PERL_POISON
252 #  define SvARENA_CHAIN(sv)     ((sv)->sv_u.svu_rv)
253 #  define SvARENA_CHAIN_SET(sv,val)     (sv)->sv_u.svu_rv = MUTABLE_SV((val))
254 /* Whilst I'd love to do this, it seems that things like to check on
255    unreferenced scalars
256 #  define POSION_SV_HEAD(sv)    PoisonNew(sv, 1, struct STRUCT_SV)
257 */
258 #  define POSION_SV_HEAD(sv)    PoisonNew(&SvANY(sv), 1, void *), \
259                                 PoisonNew(&SvREFCNT(sv), 1, U32)
260 #else
261 #  define SvARENA_CHAIN(sv)     SvANY(sv)
262 #  define SvARENA_CHAIN_SET(sv,val)     SvANY(sv) = (void *)(val)
263 #  define POSION_SV_HEAD(sv)
264 #endif
265
266 /* Mark an SV head as unused, and add to free list.
267  *
268  * If SVf_BREAK is set, skip adding it to the free list, as this SV had
269  * its refcount artificially decremented during global destruction, so
270  * there may be dangling pointers to it. The last thing we want in that
271  * case is for it to be reused. */
272
273 #define plant_SV(p) \
274     STMT_START {                                        \
275         const U32 old_flags = SvFLAGS(p);                       \
276         MEM_LOG_DEL_SV(p, __FILE__, __LINE__, FUNCTION__);  \
277         DEBUG_SV_SERIAL(p);                             \
278         FREE_SV_DEBUG_FILE(p);                          \
279         POSION_SV_HEAD(p);                              \
280         SvFLAGS(p) = SVTYPEMASK;                        \
281         if (!(old_flags & SVf_BREAK)) {         \
282             SvARENA_CHAIN_SET(p, PL_sv_root);   \
283             PL_sv_root = (p);                           \
284         }                                               \
285         --PL_sv_count;                                  \
286     } STMT_END
287
288 #define uproot_SV(p) \
289     STMT_START {                                        \
290         (p) = PL_sv_root;                               \
291         PL_sv_root = MUTABLE_SV(SvARENA_CHAIN(p));              \
292         ++PL_sv_count;                                  \
293     } STMT_END
294
295
296 /* make some more SVs by adding another arena */
297
298 STATIC SV*
299 S_more_sv(pTHX)
300 {
301     SV* sv;
302     char *chunk;                /* must use New here to match call to */
303     Newx(chunk,PERL_ARENA_SIZE,char);  /* Safefree() in sv_free_arenas() */
304     sv_add_arena(chunk, PERL_ARENA_SIZE, 0);
305     uproot_SV(sv);
306     return sv;
307 }
308
309 /* new_SV(): return a new, empty SV head */
310
311 #ifdef DEBUG_LEAKING_SCALARS
312 /* provide a real function for a debugger to play with */
313 STATIC SV*
314 S_new_SV(pTHX_ const char *file, int line, const char *func)
315 {
316     SV* sv;
317
318     if (PL_sv_root)
319         uproot_SV(sv);
320     else
321         sv = S_more_sv(aTHX);
322     SvANY(sv) = 0;
323     SvREFCNT(sv) = 1;
324     SvFLAGS(sv) = 0;
325     sv->sv_debug_optype = PL_op ? PL_op->op_type : 0;
326     sv->sv_debug_line = (U16) (PL_parser && PL_parser->copline != NOLINE
327                 ? PL_parser->copline
328                 :  PL_curcop
329                     ? CopLINE(PL_curcop)
330                     : 0
331             );
332     sv->sv_debug_inpad = 0;
333     sv->sv_debug_parent = NULL;
334     sv->sv_debug_file = PL_curcop ? savesharedpv(CopFILE(PL_curcop)): NULL;
335
336     sv->sv_debug_serial = PL_sv_serial++;
337
338     MEM_LOG_NEW_SV(sv, file, line, func);
339     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) new_SV (from %s:%d [%s])\n",
340             PTR2UV(sv), (long)sv->sv_debug_serial, file, line, func));
341
342     return sv;
343 }
344 #  define new_SV(p) (p)=S_new_SV(aTHX_ __FILE__, __LINE__, FUNCTION__)
345
346 #else
347 #  define new_SV(p) \
348     STMT_START {                                        \
349         if (PL_sv_root)                                 \
350             uproot_SV(p);                               \
351         else                                            \
352             (p) = S_more_sv(aTHX);                      \
353         SvANY(p) = 0;                                   \
354         SvREFCNT(p) = 1;                                \
355         SvFLAGS(p) = 0;                                 \
356         MEM_LOG_NEW_SV(p, __FILE__, __LINE__, FUNCTION__);  \
357     } STMT_END
358 #endif
359
360
361 /* del_SV(): return an empty SV head to the free list */
362
363 #ifdef DEBUGGING
364
365 #define del_SV(p) \
366     STMT_START {                                        \
367         if (DEBUG_D_TEST)                               \
368             del_sv(p);                                  \
369         else                                            \
370             plant_SV(p);                                \
371     } STMT_END
372
373 STATIC void
374 S_del_sv(pTHX_ SV *p)
375 {
376     PERL_ARGS_ASSERT_DEL_SV;
377
378     if (DEBUG_D_TEST) {
379         SV* sva;
380         bool ok = 0;
381         for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
382             const SV * const sv = sva + 1;
383             const SV * const svend = &sva[SvREFCNT(sva)];
384             if (p >= sv && p < svend) {
385                 ok = 1;
386                 break;
387             }
388         }
389         if (!ok) {
390             Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
391                              "Attempt to free non-arena SV: 0x%"UVxf
392                              pTHX__FORMAT, PTR2UV(p) pTHX__VALUE);
393             return;
394         }
395     }
396     plant_SV(p);
397 }
398
399 #else /* ! DEBUGGING */
400
401 #define del_SV(p)   plant_SV(p)
402
403 #endif /* DEBUGGING */
404
405
406 /*
407 =head1 SV Manipulation Functions
408
409 =for apidoc sv_add_arena
410
411 Given a chunk of memory, link it to the head of the list of arenas,
412 and split it into a list of free SVs.
413
414 =cut
415 */
416
417 static void
418 S_sv_add_arena(pTHX_ char *const ptr, const U32 size, const U32 flags)
419 {
420     SV *const sva = MUTABLE_SV(ptr);
421     SV* sv;
422     SV* svend;
423
424     PERL_ARGS_ASSERT_SV_ADD_ARENA;
425
426     /* The first SV in an arena isn't an SV. */
427     SvANY(sva) = (void *) PL_sv_arenaroot;              /* ptr to next arena */
428     SvREFCNT(sva) = size / sizeof(SV);          /* number of SV slots */
429     SvFLAGS(sva) = flags;                       /* FAKE if not to be freed */
430
431     PL_sv_arenaroot = sva;
432     PL_sv_root = sva + 1;
433
434     svend = &sva[SvREFCNT(sva) - 1];
435     sv = sva + 1;
436     while (sv < svend) {
437         SvARENA_CHAIN_SET(sv, (sv + 1));
438 #ifdef DEBUGGING
439         SvREFCNT(sv) = 0;
440 #endif
441         /* Must always set typemask because it's always checked in on cleanup
442            when the arenas are walked looking for objects.  */
443         SvFLAGS(sv) = SVTYPEMASK;
444         sv++;
445     }
446     SvARENA_CHAIN_SET(sv, 0);
447 #ifdef DEBUGGING
448     SvREFCNT(sv) = 0;
449 #endif
450     SvFLAGS(sv) = SVTYPEMASK;
451 }
452
453 /* visit(): call the named function for each non-free SV in the arenas
454  * whose flags field matches the flags/mask args. */
455
456 STATIC I32
457 S_visit(pTHX_ SVFUNC_t f, const U32 flags, const U32 mask)
458 {
459     SV* sva;
460     I32 visited = 0;
461
462     PERL_ARGS_ASSERT_VISIT;
463
464     for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
465         const SV * const svend = &sva[SvREFCNT(sva)];
466         SV* sv;
467         for (sv = sva + 1; sv < svend; ++sv) {
468             if (SvTYPE(sv) != (svtype)SVTYPEMASK
469                     && (sv->sv_flags & mask) == flags
470                     && SvREFCNT(sv))
471             {
472                 (*f)(aTHX_ sv);
473                 ++visited;
474             }
475         }
476     }
477     return visited;
478 }
479
480 #ifdef DEBUGGING
481
482 /* called by sv_report_used() for each live SV */
483
484 static void
485 do_report_used(pTHX_ SV *const sv)
486 {
487     if (SvTYPE(sv) != (svtype)SVTYPEMASK) {
488         PerlIO_printf(Perl_debug_log, "****\n");
489         sv_dump(sv);
490     }
491 }
492 #endif
493
494 /*
495 =for apidoc sv_report_used
496
497 Dump the contents of all SVs not yet freed (debugging aid).
498
499 =cut
500 */
501
502 void
503 Perl_sv_report_used(pTHX)
504 {
505 #ifdef DEBUGGING
506     visit(do_report_used, 0, 0);
507 #else
508     PERL_UNUSED_CONTEXT;
509 #endif
510 }
511
512 /* called by sv_clean_objs() for each live SV */
513
514 static void
515 do_clean_objs(pTHX_ SV *const ref)
516 {
517     assert (SvROK(ref));
518     {
519         SV * const target = SvRV(ref);
520         if (SvOBJECT(target)) {
521             DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning object ref:\n "), sv_dump(ref)));
522             if (SvWEAKREF(ref)) {
523                 sv_del_backref(target, ref);
524                 SvWEAKREF_off(ref);
525                 SvRV_set(ref, NULL);
526             } else {
527                 SvROK_off(ref);
528                 SvRV_set(ref, NULL);
529                 SvREFCNT_dec_NN(target);
530             }
531         }
532     }
533 }
534
535
536 /* clear any slots in a GV which hold objects - except IO;
537  * called by sv_clean_objs() for each live GV */
538
539 static void
540 do_clean_named_objs(pTHX_ SV *const sv)
541 {
542     SV *obj;
543     assert(SvTYPE(sv) == SVt_PVGV);
544     assert(isGV_with_GP(sv));
545     if (!GvGP(sv))
546         return;
547
548     /* freeing GP entries may indirectly free the current GV;
549      * hold onto it while we mess with the GP slots */
550     SvREFCNT_inc(sv);
551
552     if ( ((obj = GvSV(sv) )) && SvOBJECT(obj)) {
553         DEBUG_D((PerlIO_printf(Perl_debug_log,
554                 "Cleaning named glob SV object:\n "), sv_dump(obj)));
555         GvSV(sv) = NULL;
556         SvREFCNT_dec_NN(obj);
557     }
558     if ( ((obj = MUTABLE_SV(GvAV(sv)) )) && SvOBJECT(obj)) {
559         DEBUG_D((PerlIO_printf(Perl_debug_log,
560                 "Cleaning named glob AV object:\n "), sv_dump(obj)));
561         GvAV(sv) = NULL;
562         SvREFCNT_dec_NN(obj);
563     }
564     if ( ((obj = MUTABLE_SV(GvHV(sv)) )) && SvOBJECT(obj)) {
565         DEBUG_D((PerlIO_printf(Perl_debug_log,
566                 "Cleaning named glob HV object:\n "), sv_dump(obj)));
567         GvHV(sv) = NULL;
568         SvREFCNT_dec_NN(obj);
569     }
570     if ( ((obj = MUTABLE_SV(GvCV(sv)) )) && SvOBJECT(obj)) {
571         DEBUG_D((PerlIO_printf(Perl_debug_log,
572                 "Cleaning named glob CV object:\n "), sv_dump(obj)));
573         GvCV_set(sv, NULL);
574         SvREFCNT_dec_NN(obj);
575     }
576     SvREFCNT_dec_NN(sv); /* undo the inc above */
577 }
578
579 /* clear any IO slots in a GV which hold objects (except stderr, defout);
580  * called by sv_clean_objs() for each live GV */
581
582 static void
583 do_clean_named_io_objs(pTHX_ SV *const sv)
584 {
585     SV *obj;
586     assert(SvTYPE(sv) == SVt_PVGV);
587     assert(isGV_with_GP(sv));
588     if (!GvGP(sv) || sv == (SV*)PL_stderrgv || sv == (SV*)PL_defoutgv)
589         return;
590
591     SvREFCNT_inc(sv);
592     if ( ((obj = MUTABLE_SV(GvIO(sv)) )) && SvOBJECT(obj)) {
593         DEBUG_D((PerlIO_printf(Perl_debug_log,
594                 "Cleaning named glob IO object:\n "), sv_dump(obj)));
595         GvIOp(sv) = NULL;
596         SvREFCNT_dec_NN(obj);
597     }
598     SvREFCNT_dec_NN(sv); /* undo the inc above */
599 }
600
601 /* Void wrapper to pass to visit() */
602 static void
603 do_curse(pTHX_ SV * const sv) {
604     if ((PL_stderrgv && GvGP(PL_stderrgv) && (SV*)GvIO(PL_stderrgv) == sv)
605      || (PL_defoutgv && GvGP(PL_defoutgv) && (SV*)GvIO(PL_defoutgv) == sv))
606         return;
607     (void)curse(sv, 0);
608 }
609
610 /*
611 =for apidoc sv_clean_objs
612
613 Attempt to destroy all objects not yet freed.
614
615 =cut
616 */
617
618 void
619 Perl_sv_clean_objs(pTHX)
620 {
621     GV *olddef, *olderr;
622     PL_in_clean_objs = TRUE;
623     visit(do_clean_objs, SVf_ROK, SVf_ROK);
624     /* Some barnacles may yet remain, clinging to typeglobs.
625      * Run the non-IO destructors first: they may want to output
626      * error messages, close files etc */
627     visit(do_clean_named_objs, SVt_PVGV|SVpgv_GP, SVTYPEMASK|SVp_POK|SVpgv_GP);
628     visit(do_clean_named_io_objs, SVt_PVGV|SVpgv_GP, SVTYPEMASK|SVp_POK|SVpgv_GP);
629     /* And if there are some very tenacious barnacles clinging to arrays,
630        closures, or what have you.... */
631     visit(do_curse, SVs_OBJECT, SVs_OBJECT);
632     olddef = PL_defoutgv;
633     PL_defoutgv = NULL; /* disable skip of PL_defoutgv */
634     if (olddef && isGV_with_GP(olddef))
635         do_clean_named_io_objs(aTHX_ MUTABLE_SV(olddef));
636     olderr = PL_stderrgv;
637     PL_stderrgv = NULL; /* disable skip of PL_stderrgv */
638     if (olderr && isGV_with_GP(olderr))
639         do_clean_named_io_objs(aTHX_ MUTABLE_SV(olderr));
640     SvREFCNT_dec(olddef);
641     PL_in_clean_objs = FALSE;
642 }
643
644 /* called by sv_clean_all() for each live SV */
645
646 static void
647 do_clean_all(pTHX_ SV *const sv)
648 {
649     if (sv == (const SV *) PL_fdpid || sv == (const SV *)PL_strtab) {
650         /* don't clean pid table and strtab */
651         return;
652     }
653     DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning loops: SV at 0x%"UVxf"\n", PTR2UV(sv)) ));
654     SvFLAGS(sv) |= SVf_BREAK;
655     SvREFCNT_dec_NN(sv);
656 }
657
658 /*
659 =for apidoc sv_clean_all
660
661 Decrement the refcnt of each remaining SV, possibly triggering a
662 cleanup.  This function may have to be called multiple times to free
663 SVs which are in complex self-referential hierarchies.
664
665 =cut
666 */
667
668 I32
669 Perl_sv_clean_all(pTHX)
670 {
671     I32 cleaned;
672     PL_in_clean_all = TRUE;
673     cleaned = visit(do_clean_all, 0,0);
674     return cleaned;
675 }
676
677 /*
678   ARENASETS: a meta-arena implementation which separates arena-info
679   into struct arena_set, which contains an array of struct
680   arena_descs, each holding info for a single arena.  By separating
681   the meta-info from the arena, we recover the 1st slot, formerly
682   borrowed for list management.  The arena_set is about the size of an
683   arena, avoiding the needless malloc overhead of a naive linked-list.
684
685   The cost is 1 arena-set malloc per ~320 arena-mallocs, + the unused
686   memory in the last arena-set (1/2 on average).  In trade, we get
687   back the 1st slot in each arena (ie 1.7% of a CV-arena, less for
688   smaller types).  The recovery of the wasted space allows use of
689   small arenas for large, rare body types, by changing array* fields
690   in body_details_by_type[] below.
691 */
692 struct arena_desc {
693     char       *arena;          /* the raw storage, allocated aligned */
694     size_t      size;           /* its size ~4k typ */
695     svtype      utype;          /* bodytype stored in arena */
696 };
697
698 struct arena_set;
699
700 /* Get the maximum number of elements in set[] such that struct arena_set
701    will fit within PERL_ARENA_SIZE, which is probably just under 4K, and
702    therefore likely to be 1 aligned memory page.  */
703
704 #define ARENAS_PER_SET  ((PERL_ARENA_SIZE - sizeof(struct arena_set*) \
705                           - 2 * sizeof(int)) / sizeof (struct arena_desc))
706
707 struct arena_set {
708     struct arena_set* next;
709     unsigned int   set_size;    /* ie ARENAS_PER_SET */
710     unsigned int   curr;        /* index of next available arena-desc */
711     struct arena_desc set[ARENAS_PER_SET];
712 };
713
714 /*
715 =for apidoc sv_free_arenas
716
717 Deallocate the memory used by all arenas.  Note that all the individual SV
718 heads and bodies within the arenas must already have been freed.
719
720 =cut
721
722 */
723 void
724 Perl_sv_free_arenas(pTHX)
725 {
726     SV* sva;
727     SV* svanext;
728     unsigned int i;
729
730     /* Free arenas here, but be careful about fake ones.  (We assume
731        contiguity of the fake ones with the corresponding real ones.) */
732
733     for (sva = PL_sv_arenaroot; sva; sva = svanext) {
734         svanext = MUTABLE_SV(SvANY(sva));
735         while (svanext && SvFAKE(svanext))
736             svanext = MUTABLE_SV(SvANY(svanext));
737
738         if (!SvFAKE(sva))
739             Safefree(sva);
740     }
741
742     {
743         struct arena_set *aroot = (struct arena_set*) PL_body_arenas;
744
745         while (aroot) {
746             struct arena_set *current = aroot;
747             i = aroot->curr;
748             while (i--) {
749                 assert(aroot->set[i].arena);
750                 Safefree(aroot->set[i].arena);
751             }
752             aroot = aroot->next;
753             Safefree(current);
754         }
755     }
756     PL_body_arenas = 0;
757
758     i = PERL_ARENA_ROOTS_SIZE;
759     while (i--)
760         PL_body_roots[i] = 0;
761
762     PL_sv_arenaroot = 0;
763     PL_sv_root = 0;
764 }
765
766 /*
767   Here are mid-level routines that manage the allocation of bodies out
768   of the various arenas.  There are 5 kinds of arenas:
769
770   1. SV-head arenas, which are discussed and handled above
771   2. regular body arenas
772   3. arenas for reduced-size bodies
773   4. Hash-Entry arenas
774
775   Arena types 2 & 3 are chained by body-type off an array of
776   arena-root pointers, which is indexed by svtype.  Some of the
777   larger/less used body types are malloced singly, since a large
778   unused block of them is wasteful.  Also, several svtypes dont have
779   bodies; the data fits into the sv-head itself.  The arena-root
780   pointer thus has a few unused root-pointers (which may be hijacked
781   later for arena types 4,5)
782
783   3 differs from 2 as an optimization; some body types have several
784   unused fields in the front of the structure (which are kept in-place
785   for consistency).  These bodies can be allocated in smaller chunks,
786   because the leading fields arent accessed.  Pointers to such bodies
787   are decremented to point at the unused 'ghost' memory, knowing that
788   the pointers are used with offsets to the real memory.
789
790
791 =head1 SV-Body Allocation
792
793 =cut
794
795 Allocation of SV-bodies is similar to SV-heads, differing as follows;
796 the allocation mechanism is used for many body types, so is somewhat
797 more complicated, it uses arena-sets, and has no need for still-live
798 SV detection.
799
800 At the outermost level, (new|del)_X*V macros return bodies of the
801 appropriate type.  These macros call either (new|del)_body_type or
802 (new|del)_body_allocated macro pairs, depending on specifics of the
803 type.  Most body types use the former pair, the latter pair is used to
804 allocate body types with "ghost fields".
805
806 "ghost fields" are fields that are unused in certain types, and
807 consequently don't need to actually exist.  They are declared because
808 they're part of a "base type", which allows use of functions as
809 methods.  The simplest examples are AVs and HVs, 2 aggregate types
810 which don't use the fields which support SCALAR semantics.
811
812 For these types, the arenas are carved up into appropriately sized
813 chunks, we thus avoid wasted memory for those unaccessed members.
814 When bodies are allocated, we adjust the pointer back in memory by the
815 size of the part not allocated, so it's as if we allocated the full
816 structure.  (But things will all go boom if you write to the part that
817 is "not there", because you'll be overwriting the last members of the
818 preceding structure in memory.)
819
820 We calculate the correction using the STRUCT_OFFSET macro on the first
821 member present.  If the allocated structure is smaller (no initial NV
822 actually allocated) then the net effect is to subtract the size of the NV
823 from the pointer, to return a new pointer as if an initial NV were actually
824 allocated.  (We were using structures named *_allocated for this, but
825 this turned out to be a subtle bug, because a structure without an NV
826 could have a lower alignment constraint, but the compiler is allowed to
827 optimised accesses based on the alignment constraint of the actual pointer
828 to the full structure, for example, using a single 64 bit load instruction
829 because it "knows" that two adjacent 32 bit members will be 8-byte aligned.)
830
831 This is the same trick as was used for NV and IV bodies.  Ironically it
832 doesn't need to be used for NV bodies any more, because NV is now at
833 the start of the structure.  IV bodies don't need it either, because
834 they are no longer allocated.
835
836 In turn, the new_body_* allocators call S_new_body(), which invokes
837 new_body_inline macro, which takes a lock, and takes a body off the
838 linked list at PL_body_roots[sv_type], calling Perl_more_bodies() if
839 necessary to refresh an empty list.  Then the lock is released, and
840 the body is returned.
841
842 Perl_more_bodies allocates a new arena, and carves it up into an array of N
843 bodies, which it strings into a linked list.  It looks up arena-size
844 and body-size from the body_details table described below, thus
845 supporting the multiple body-types.
846
847 If PURIFY is defined, or PERL_ARENA_SIZE=0, arenas are not used, and
848 the (new|del)_X*V macros are mapped directly to malloc/free.
849
850 For each sv-type, struct body_details bodies_by_type[] carries
851 parameters which control these aspects of SV handling:
852
853 Arena_size determines whether arenas are used for this body type, and if
854 so, how big they are.  PURIFY or PERL_ARENA_SIZE=0 set this field to
855 zero, forcing individual mallocs and frees.
856
857 Body_size determines how big a body is, and therefore how many fit into
858 each arena.  Offset carries the body-pointer adjustment needed for
859 "ghost fields", and is used in *_allocated macros.
860
861 But its main purpose is to parameterize info needed in
862 Perl_sv_upgrade().  The info here dramatically simplifies the function
863 vs the implementation in 5.8.8, making it table-driven.  All fields
864 are used for this, except for arena_size.
865
866 For the sv-types that have no bodies, arenas are not used, so those
867 PL_body_roots[sv_type] are unused, and can be overloaded.  In
868 something of a special case, SVt_NULL is borrowed for HE arenas;
869 PL_body_roots[HE_SVSLOT=SVt_NULL] is filled by S_more_he, but the
870 bodies_by_type[SVt_NULL] slot is not used, as the table is not
871 available in hv.c.
872
873 */
874
875 struct body_details {
876     U8 body_size;       /* Size to allocate  */
877     U8 copy;            /* Size of structure to copy (may be shorter)  */
878     U8 offset;
879     unsigned int type : 4;          /* We have space for a sanity check.  */
880     unsigned int cant_upgrade : 1;  /* Cannot upgrade this type */
881     unsigned int zero_nv : 1;       /* zero the NV when upgrading from this */
882     unsigned int arena : 1;         /* Allocated from an arena */
883     size_t arena_size;              /* Size of arena to allocate */
884 };
885
886 #define HADNV FALSE
887 #define NONV TRUE
888
889
890 #ifdef PURIFY
891 /* With -DPURFIY we allocate everything directly, and don't use arenas.
892    This seems a rather elegant way to simplify some of the code below.  */
893 #define HASARENA FALSE
894 #else
895 #define HASARENA TRUE
896 #endif
897 #define NOARENA FALSE
898
899 /* Size the arenas to exactly fit a given number of bodies.  A count
900    of 0 fits the max number bodies into a PERL_ARENA_SIZE.block,
901    simplifying the default.  If count > 0, the arena is sized to fit
902    only that many bodies, allowing arenas to be used for large, rare
903    bodies (XPVFM, XPVIO) without undue waste.  The arena size is
904    limited by PERL_ARENA_SIZE, so we can safely oversize the
905    declarations.
906  */
907 #define FIT_ARENA0(body_size)                           \
908     ((size_t)(PERL_ARENA_SIZE / body_size) * body_size)
909 #define FIT_ARENAn(count,body_size)                     \
910     ( count * body_size <= PERL_ARENA_SIZE)             \
911     ? count * body_size                                 \
912     : FIT_ARENA0 (body_size)
913 #define FIT_ARENA(count,body_size)                      \
914     count                                               \
915     ? FIT_ARENAn (count, body_size)                     \
916     : FIT_ARENA0 (body_size)
917
918 /* Calculate the length to copy. Specifically work out the length less any
919    final padding the compiler needed to add.  See the comment in sv_upgrade
920    for why copying the padding proved to be a bug.  */
921
922 #define copy_length(type, last_member) \
923         STRUCT_OFFSET(type, last_member) \
924         + sizeof (((type*)SvANY((const SV *)0))->last_member)
925
926 static const struct body_details bodies_by_type[] = {
927     /* HEs use this offset for their arena.  */
928     { 0, 0, 0, SVt_NULL, FALSE, NONV, NOARENA, 0 },
929
930     /* IVs are in the head, so the allocation size is 0.  */
931     { 0,
932       sizeof(IV), /* This is used to copy out the IV body.  */
933       STRUCT_OFFSET(XPVIV, xiv_iv), SVt_IV, FALSE, NONV,
934       NOARENA /* IVS don't need an arena  */, 0
935     },
936
937     { sizeof(NV), sizeof(NV),
938       STRUCT_OFFSET(XPVNV, xnv_u),
939       SVt_NV, FALSE, HADNV, HASARENA, FIT_ARENA(0, sizeof(NV)) },
940
941     { sizeof(XPV) - STRUCT_OFFSET(XPV, xpv_cur),
942       copy_length(XPV, xpv_len) - STRUCT_OFFSET(XPV, xpv_cur),
943       + STRUCT_OFFSET(XPV, xpv_cur),
944       SVt_PV, FALSE, NONV, HASARENA,
945       FIT_ARENA(0, sizeof(XPV) - STRUCT_OFFSET(XPV, xpv_cur)) },
946
947     { sizeof(XINVLIST) - STRUCT_OFFSET(XPV, xpv_cur),
948       copy_length(XINVLIST, is_offset) - STRUCT_OFFSET(XPV, xpv_cur),
949       + STRUCT_OFFSET(XPV, xpv_cur),
950       SVt_INVLIST, TRUE, NONV, HASARENA,
951       FIT_ARENA(0, sizeof(XINVLIST) - STRUCT_OFFSET(XPV, xpv_cur)) },
952
953     { sizeof(XPVIV) - STRUCT_OFFSET(XPV, xpv_cur),
954       copy_length(XPVIV, xiv_u) - STRUCT_OFFSET(XPV, xpv_cur),
955       + STRUCT_OFFSET(XPV, xpv_cur),
956       SVt_PVIV, FALSE, NONV, HASARENA,
957       FIT_ARENA(0, sizeof(XPVIV) - STRUCT_OFFSET(XPV, xpv_cur)) },
958
959     { sizeof(XPVNV) - STRUCT_OFFSET(XPV, xpv_cur),
960       copy_length(XPVNV, xnv_u) - STRUCT_OFFSET(XPV, xpv_cur),
961       + STRUCT_OFFSET(XPV, xpv_cur),
962       SVt_PVNV, FALSE, HADNV, HASARENA,
963       FIT_ARENA(0, sizeof(XPVNV) - STRUCT_OFFSET(XPV, xpv_cur)) },
964
965     { sizeof(XPVMG), copy_length(XPVMG, xnv_u), 0, SVt_PVMG, FALSE, HADNV,
966       HASARENA, FIT_ARENA(0, sizeof(XPVMG)) },
967
968     { sizeof(regexp),
969       sizeof(regexp),
970       0,
971       SVt_REGEXP, TRUE, NONV, HASARENA,
972       FIT_ARENA(0, sizeof(regexp))
973     },
974
975     { sizeof(XPVGV), sizeof(XPVGV), 0, SVt_PVGV, TRUE, HADNV,
976       HASARENA, FIT_ARENA(0, sizeof(XPVGV)) },
977     
978     { sizeof(XPVLV), sizeof(XPVLV), 0, SVt_PVLV, TRUE, HADNV,
979       HASARENA, FIT_ARENA(0, sizeof(XPVLV)) },
980
981     { sizeof(XPVAV),
982       copy_length(XPVAV, xav_alloc),
983       0,
984       SVt_PVAV, TRUE, NONV, HASARENA,
985       FIT_ARENA(0, sizeof(XPVAV)) },
986
987     { sizeof(XPVHV),
988       copy_length(XPVHV, xhv_max),
989       0,
990       SVt_PVHV, TRUE, NONV, HASARENA,
991       FIT_ARENA(0, sizeof(XPVHV)) },
992
993     { sizeof(XPVCV),
994       sizeof(XPVCV),
995       0,
996       SVt_PVCV, TRUE, NONV, HASARENA,
997       FIT_ARENA(0, sizeof(XPVCV)) },
998
999     { sizeof(XPVFM),
1000       sizeof(XPVFM),
1001       0,
1002       SVt_PVFM, TRUE, NONV, NOARENA,
1003       FIT_ARENA(20, sizeof(XPVFM)) },
1004
1005     { sizeof(XPVIO),
1006       sizeof(XPVIO),
1007       0,
1008       SVt_PVIO, TRUE, NONV, HASARENA,
1009       FIT_ARENA(24, sizeof(XPVIO)) },
1010 };
1011
1012 #define new_body_allocated(sv_type)             \
1013     (void *)((char *)S_new_body(aTHX_ sv_type)  \
1014              - bodies_by_type[sv_type].offset)
1015
1016 /* return a thing to the free list */
1017
1018 #define del_body(thing, root)                           \
1019     STMT_START {                                        \
1020         void ** const thing_copy = (void **)thing;      \
1021         *thing_copy = *root;                            \
1022         *root = (void*)thing_copy;                      \
1023     } STMT_END
1024
1025 #ifdef PURIFY
1026
1027 #define new_XNV()       safemalloc(sizeof(XPVNV))
1028 #define new_XPVNV()     safemalloc(sizeof(XPVNV))
1029 #define new_XPVMG()     safemalloc(sizeof(XPVMG))
1030
1031 #define del_XPVGV(p)    safefree(p)
1032
1033 #else /* !PURIFY */
1034
1035 #define new_XNV()       new_body_allocated(SVt_NV)
1036 #define new_XPVNV()     new_body_allocated(SVt_PVNV)
1037 #define new_XPVMG()     new_body_allocated(SVt_PVMG)
1038
1039 #define del_XPVGV(p)    del_body(p + bodies_by_type[SVt_PVGV].offset,   \
1040                                  &PL_body_roots[SVt_PVGV])
1041
1042 #endif /* PURIFY */
1043
1044 /* no arena for you! */
1045
1046 #define new_NOARENA(details) \
1047         safemalloc((details)->body_size + (details)->offset)
1048 #define new_NOARENAZ(details) \
1049         safecalloc((details)->body_size + (details)->offset, 1)
1050
1051 void *
1052 Perl_more_bodies (pTHX_ const svtype sv_type, const size_t body_size,
1053                   const size_t arena_size)
1054 {
1055     void ** const root = &PL_body_roots[sv_type];
1056     struct arena_desc *adesc;
1057     struct arena_set *aroot = (struct arena_set *) PL_body_arenas;
1058     unsigned int curr;
1059     char *start;
1060     const char *end;
1061     const size_t good_arena_size = Perl_malloc_good_size(arena_size);
1062 #if defined(DEBUGGING) && defined(PERL_GLOBAL_STRUCT)
1063     dVAR;
1064 #endif
1065 #if defined(DEBUGGING) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
1066     static bool done_sanity_check;
1067
1068     /* PERL_GLOBAL_STRUCT_PRIVATE cannot coexist with global
1069      * variables like done_sanity_check. */
1070     if (!done_sanity_check) {
1071         unsigned int i = SVt_LAST;
1072
1073         done_sanity_check = TRUE;
1074
1075         while (i--)
1076             assert (bodies_by_type[i].type == i);
1077     }
1078 #endif
1079
1080     assert(arena_size);
1081
1082     /* may need new arena-set to hold new arena */
1083     if (!aroot || aroot->curr >= aroot->set_size) {
1084         struct arena_set *newroot;
1085         Newxz(newroot, 1, struct arena_set);
1086         newroot->set_size = ARENAS_PER_SET;
1087         newroot->next = aroot;
1088         aroot = newroot;
1089         PL_body_arenas = (void *) newroot;
1090         DEBUG_m(PerlIO_printf(Perl_debug_log, "new arenaset %p\n", (void*)aroot));
1091     }
1092
1093     /* ok, now have arena-set with at least 1 empty/available arena-desc */
1094     curr = aroot->curr++;
1095     adesc = &(aroot->set[curr]);
1096     assert(!adesc->arena);
1097     
1098     Newx(adesc->arena, good_arena_size, char);
1099     adesc->size = good_arena_size;
1100     adesc->utype = sv_type;
1101     DEBUG_m(PerlIO_printf(Perl_debug_log, "arena %d added: %p size %"UVuf"\n", 
1102                           curr, (void*)adesc->arena, (UV)good_arena_size));
1103
1104     start = (char *) adesc->arena;
1105
1106     /* Get the address of the byte after the end of the last body we can fit.
1107        Remember, this is integer division:  */
1108     end = start + good_arena_size / body_size * body_size;
1109
1110     /* computed count doesn't reflect the 1st slot reservation */
1111 #if defined(MYMALLOC) || defined(HAS_MALLOC_GOOD_SIZE)
1112     DEBUG_m(PerlIO_printf(Perl_debug_log,
1113                           "arena %p end %p arena-size %d (from %d) type %d "
1114                           "size %d ct %d\n",
1115                           (void*)start, (void*)end, (int)good_arena_size,
1116                           (int)arena_size, sv_type, (int)body_size,
1117                           (int)good_arena_size / (int)body_size));
1118 #else
1119     DEBUG_m(PerlIO_printf(Perl_debug_log,
1120                           "arena %p end %p arena-size %d type %d size %d ct %d\n",
1121                           (void*)start, (void*)end,
1122                           (int)arena_size, sv_type, (int)body_size,
1123                           (int)good_arena_size / (int)body_size));
1124 #endif
1125     *root = (void *)start;
1126
1127     while (1) {
1128         /* Where the next body would start:  */
1129         char * const next = start + body_size;
1130
1131         if (next >= end) {
1132             /* This is the last body:  */
1133             assert(next == end);
1134
1135             *(void **)start = 0;
1136             return *root;
1137         }
1138
1139         *(void**) start = (void *)next;
1140         start = next;
1141     }
1142 }
1143
1144 /* grab a new thing from the free list, allocating more if necessary.
1145    The inline version is used for speed in hot routines, and the
1146    function using it serves the rest (unless PURIFY).
1147 */
1148 #define new_body_inline(xpv, sv_type) \
1149     STMT_START { \
1150         void ** const r3wt = &PL_body_roots[sv_type]; \
1151         xpv = (PTR_TBL_ENT_t*) (*((void **)(r3wt))      \
1152           ? *((void **)(r3wt)) : Perl_more_bodies(aTHX_ sv_type, \
1153                                              bodies_by_type[sv_type].body_size,\
1154                                              bodies_by_type[sv_type].arena_size)); \
1155         *(r3wt) = *(void**)(xpv); \
1156     } STMT_END
1157
1158 #ifndef PURIFY
1159
1160 STATIC void *
1161 S_new_body(pTHX_ const svtype sv_type)
1162 {
1163     void *xpv;
1164     new_body_inline(xpv, sv_type);
1165     return xpv;
1166 }
1167
1168 #endif
1169
1170 static const struct body_details fake_rv =
1171     { 0, 0, 0, SVt_IV, FALSE, NONV, NOARENA, 0 };
1172
1173 /*
1174 =for apidoc sv_upgrade
1175
1176 Upgrade an SV to a more complex form.  Generally adds a new body type to the
1177 SV, then copies across as much information as possible from the old body.
1178 It croaks if the SV is already in a more complex form than requested.  You
1179 generally want to use the C<SvUPGRADE> macro wrapper, which checks the type
1180 before calling C<sv_upgrade>, and hence does not croak.  See also
1181 C<svtype>.
1182
1183 =cut
1184 */
1185
1186 void
1187 Perl_sv_upgrade(pTHX_ SV *const sv, svtype new_type)
1188 {
1189     void*       old_body;
1190     void*       new_body;
1191     const svtype old_type = SvTYPE(sv);
1192     const struct body_details *new_type_details;
1193     const struct body_details *old_type_details
1194         = bodies_by_type + old_type;
1195     SV *referant = NULL;
1196
1197     PERL_ARGS_ASSERT_SV_UPGRADE;
1198
1199     if (old_type == new_type)
1200         return;
1201
1202     /* This clause was purposefully added ahead of the early return above to
1203        the shared string hackery for (sort {$a <=> $b} keys %hash), with the
1204        inference by Nick I-S that it would fix other troublesome cases. See
1205        changes 7162, 7163 (f130fd4589cf5fbb24149cd4db4137c8326f49c1 and parent)
1206
1207        Given that shared hash key scalars are no longer PVIV, but PV, there is
1208        no longer need to unshare so as to free up the IVX slot for its proper
1209        purpose. So it's safe to move the early return earlier.  */
1210
1211     if (new_type > SVt_PVMG && SvIsCOW(sv)) {
1212         sv_force_normal_flags(sv, 0);
1213     }
1214
1215     old_body = SvANY(sv);
1216
1217     /* Copying structures onto other structures that have been neatly zeroed
1218        has a subtle gotcha. Consider XPVMG
1219
1220        +------+------+------+------+------+-------+-------+
1221        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |
1222        +------+------+------+------+------+-------+-------+
1223        0      4      8     12     16     20      24      28
1224
1225        where NVs are aligned to 8 bytes, so that sizeof that structure is
1226        actually 32 bytes long, with 4 bytes of padding at the end:
1227
1228        +------+------+------+------+------+-------+-------+------+
1229        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH | ???  |
1230        +------+------+------+------+------+-------+-------+------+
1231        0      4      8     12     16     20      24      28     32
1232
1233        so what happens if you allocate memory for this structure:
1234
1235        +------+------+------+------+------+-------+-------+------+------+...
1236        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |  GP  | NAME |
1237        +------+------+------+------+------+-------+-------+------+------+...
1238        0      4      8     12     16     20      24      28     32     36
1239
1240        zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
1241        expect, because you copy the area marked ??? onto GP. Now, ??? may have
1242        started out as zero once, but it's quite possible that it isn't. So now,
1243        rather than a nicely zeroed GP, you have it pointing somewhere random.
1244        Bugs ensue.
1245
1246        (In fact, GP ends up pointing at a previous GP structure, because the
1247        principle cause of the padding in XPVMG getting garbage is a copy of
1248        sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob. Right now
1249        this happens to be moot because XPVGV has been re-ordered, with GP
1250        no longer after STASH)
1251
1252        So we are careful and work out the size of used parts of all the
1253        structures.  */
1254
1255     switch (old_type) {
1256     case SVt_NULL:
1257         break;
1258     case SVt_IV:
1259         if (SvROK(sv)) {
1260             referant = SvRV(sv);
1261             old_type_details = &fake_rv;
1262             if (new_type == SVt_NV)
1263                 new_type = SVt_PVNV;
1264         } else {
1265             if (new_type < SVt_PVIV) {
1266                 new_type = (new_type == SVt_NV)
1267                     ? SVt_PVNV : SVt_PVIV;
1268             }
1269         }
1270         break;
1271     case SVt_NV:
1272         if (new_type < SVt_PVNV) {
1273             new_type = SVt_PVNV;
1274         }
1275         break;
1276     case SVt_PV:
1277         assert(new_type > SVt_PV);
1278         assert(SVt_IV < SVt_PV);
1279         assert(SVt_NV < SVt_PV);
1280         break;
1281     case SVt_PVIV:
1282         break;
1283     case SVt_PVNV:
1284         break;
1285     case SVt_PVMG:
1286         /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1287            there's no way that it can be safely upgraded, because perl.c
1288            expects to Safefree(SvANY(PL_mess_sv))  */
1289         assert(sv != PL_mess_sv);
1290         /* This flag bit is used to mean other things in other scalar types.
1291            Given that it only has meaning inside the pad, it shouldn't be set
1292            on anything that can get upgraded.  */
1293         assert(!SvPAD_TYPED(sv));
1294         break;
1295     default:
1296         if (UNLIKELY(old_type_details->cant_upgrade))
1297             Perl_croak(aTHX_ "Can't upgrade %s (%" UVuf ") to %" UVuf,
1298                        sv_reftype(sv, 0), (UV) old_type, (UV) new_type);
1299     }
1300
1301     if (UNLIKELY(old_type > new_type))
1302         Perl_croak(aTHX_ "sv_upgrade from type %d down to type %d",
1303                 (int)old_type, (int)new_type);
1304
1305     new_type_details = bodies_by_type + new_type;
1306
1307     SvFLAGS(sv) &= ~SVTYPEMASK;
1308     SvFLAGS(sv) |= new_type;
1309
1310     /* This can't happen, as SVt_NULL is <= all values of new_type, so one of
1311        the return statements above will have triggered.  */
1312     assert (new_type != SVt_NULL);
1313     switch (new_type) {
1314     case SVt_IV:
1315         assert(old_type == SVt_NULL);
1316         SvANY(sv) = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
1317         SvIV_set(sv, 0);
1318         return;
1319     case SVt_NV:
1320         assert(old_type == SVt_NULL);
1321         SvANY(sv) = new_XNV();
1322         SvNV_set(sv, 0);
1323         return;
1324     case SVt_PVHV:
1325     case SVt_PVAV:
1326         assert(new_type_details->body_size);
1327
1328 #ifndef PURIFY  
1329         assert(new_type_details->arena);
1330         assert(new_type_details->arena_size);
1331         /* This points to the start of the allocated area.  */
1332         new_body_inline(new_body, new_type);
1333         Zero(new_body, new_type_details->body_size, char);
1334         new_body = ((char *)new_body) - new_type_details->offset;
1335 #else
1336         /* We always allocated the full length item with PURIFY. To do this
1337            we fake things so that arena is false for all 16 types..  */
1338         new_body = new_NOARENAZ(new_type_details);
1339 #endif
1340         SvANY(sv) = new_body;
1341         if (new_type == SVt_PVAV) {
1342             AvMAX(sv)   = -1;
1343             AvFILLp(sv) = -1;
1344             AvREAL_only(sv);
1345             if (old_type_details->body_size) {
1346                 AvALLOC(sv) = 0;
1347             } else {
1348                 /* It will have been zeroed when the new body was allocated.
1349                    Lets not write to it, in case it confuses a write-back
1350                    cache.  */
1351             }
1352         } else {
1353             assert(!SvOK(sv));
1354             SvOK_off(sv);
1355 #ifndef NODEFAULT_SHAREKEYS
1356             HvSHAREKEYS_on(sv);         /* key-sharing on by default */
1357 #endif
1358             /* start with PERL_HASH_DEFAULT_HvMAX+1 buckets: */
1359             HvMAX(sv) = PERL_HASH_DEFAULT_HvMAX;
1360         }
1361
1362         /* SVt_NULL isn't the only thing upgraded to AV or HV.
1363            The target created by newSVrv also is, and it can have magic.
1364            However, it never has SvPVX set.
1365         */
1366         if (old_type == SVt_IV) {
1367             assert(!SvROK(sv));
1368         } else if (old_type >= SVt_PV) {
1369             assert(SvPVX_const(sv) == 0);
1370         }
1371
1372         if (old_type >= SVt_PVMG) {
1373             SvMAGIC_set(sv, ((XPVMG*)old_body)->xmg_u.xmg_magic);
1374             SvSTASH_set(sv, ((XPVMG*)old_body)->xmg_stash);
1375         } else {
1376             sv->sv_u.svu_array = NULL; /* or svu_hash  */
1377         }
1378         break;
1379
1380     case SVt_PVIV:
1381         /* XXX Is this still needed?  Was it ever needed?   Surely as there is
1382            no route from NV to PVIV, NOK can never be true  */
1383         assert(!SvNOKp(sv));
1384         assert(!SvNOK(sv));
1385     case SVt_PVIO:
1386     case SVt_PVFM:
1387     case SVt_PVGV:
1388     case SVt_PVCV:
1389     case SVt_PVLV:
1390     case SVt_INVLIST:
1391     case SVt_REGEXP:
1392     case SVt_PVMG:
1393     case SVt_PVNV:
1394     case SVt_PV:
1395
1396         assert(new_type_details->body_size);
1397         /* We always allocated the full length item with PURIFY. To do this
1398            we fake things so that arena is false for all 16 types..  */
1399         if(new_type_details->arena) {
1400             /* This points to the start of the allocated area.  */
1401             new_body_inline(new_body, new_type);
1402             Zero(new_body, new_type_details->body_size, char);
1403             new_body = ((char *)new_body) - new_type_details->offset;
1404         } else {
1405             new_body = new_NOARENAZ(new_type_details);
1406         }
1407         SvANY(sv) = new_body;
1408
1409         if (old_type_details->copy) {
1410             /* There is now the potential for an upgrade from something without
1411                an offset (PVNV or PVMG) to something with one (PVCV, PVFM)  */
1412             int offset = old_type_details->offset;
1413             int length = old_type_details->copy;
1414
1415             if (new_type_details->offset > old_type_details->offset) {
1416                 const int difference
1417                     = new_type_details->offset - old_type_details->offset;
1418                 offset += difference;
1419                 length -= difference;
1420             }
1421             assert (length >= 0);
1422                 
1423             Copy((char *)old_body + offset, (char *)new_body + offset, length,
1424                  char);
1425         }
1426
1427 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1428         /* If NV 0.0 is stores as all bits 0 then Zero() already creates a
1429          * correct 0.0 for us.  Otherwise, if the old body didn't have an
1430          * NV slot, but the new one does, then we need to initialise the
1431          * freshly created NV slot with whatever the correct bit pattern is
1432          * for 0.0  */
1433         if (old_type_details->zero_nv && !new_type_details->zero_nv
1434             && !isGV_with_GP(sv))
1435             SvNV_set(sv, 0);
1436 #endif
1437
1438         if (UNLIKELY(new_type == SVt_PVIO)) {
1439             IO * const io = MUTABLE_IO(sv);
1440             GV *iogv = gv_fetchpvs("IO::File::", GV_ADD, SVt_PVHV);
1441
1442             SvOBJECT_on(io);
1443             /* Clear the stashcache because a new IO could overrule a package
1444                name */
1445             DEBUG_o(Perl_deb(aTHX_ "sv_upgrade clearing PL_stashcache\n"));
1446             hv_clear(PL_stashcache);
1447
1448             SvSTASH_set(io, MUTABLE_HV(SvREFCNT_inc(GvHV(iogv))));
1449             IoPAGE_LEN(sv) = 60;
1450         }
1451         if (UNLIKELY(new_type == SVt_REGEXP))
1452             sv->sv_u.svu_rx = (regexp *)new_body;
1453         else if (old_type < SVt_PV) {
1454             /* referant will be NULL unless the old type was SVt_IV emulating
1455                SVt_RV */
1456             sv->sv_u.svu_rv = referant;
1457         }
1458         break;
1459     default:
1460         Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu",
1461                    (unsigned long)new_type);
1462     }
1463
1464     if (old_type > SVt_IV) {
1465 #ifdef PURIFY
1466         safefree(old_body);
1467 #else
1468         /* Note that there is an assumption that all bodies of types that
1469            can be upgraded came from arenas. Only the more complex non-
1470            upgradable types are allowed to be directly malloc()ed.  */
1471         assert(old_type_details->arena);
1472         del_body((void*)((char*)old_body + old_type_details->offset),
1473                  &PL_body_roots[old_type]);
1474 #endif
1475     }
1476 }
1477
1478 /*
1479 =for apidoc sv_backoff
1480
1481 Remove any string offset.  You should normally use the C<SvOOK_off> macro
1482 wrapper instead.
1483
1484 =cut
1485 */
1486
1487 int
1488 Perl_sv_backoff(SV *const sv)
1489 {
1490     STRLEN delta;
1491     const char * const s = SvPVX_const(sv);
1492
1493     PERL_ARGS_ASSERT_SV_BACKOFF;
1494
1495     assert(SvOOK(sv));
1496     assert(SvTYPE(sv) != SVt_PVHV);
1497     assert(SvTYPE(sv) != SVt_PVAV);
1498
1499     SvOOK_offset(sv, delta);
1500     
1501     SvLEN_set(sv, SvLEN(sv) + delta);
1502     SvPV_set(sv, SvPVX(sv) - delta);
1503     Move(s, SvPVX(sv), SvCUR(sv)+1, char);
1504     SvFLAGS(sv) &= ~SVf_OOK;
1505     return 0;
1506 }
1507
1508 /*
1509 =for apidoc sv_grow
1510
1511 Expands the character buffer in the SV.  If necessary, uses C<sv_unref> and
1512 upgrades the SV to C<SVt_PV>.  Returns a pointer to the character buffer.
1513 Use the C<SvGROW> wrapper instead.
1514
1515 =cut
1516 */
1517
1518 static void S_sv_uncow(pTHX_ SV * const sv, const U32 flags);
1519
1520 char *
1521 Perl_sv_grow(pTHX_ SV *const sv, STRLEN newlen)
1522 {
1523     char *s;
1524
1525     PERL_ARGS_ASSERT_SV_GROW;
1526
1527     if (SvROK(sv))
1528         sv_unref(sv);
1529     if (SvTYPE(sv) < SVt_PV) {
1530         sv_upgrade(sv, SVt_PV);
1531         s = SvPVX_mutable(sv);
1532     }
1533     else if (SvOOK(sv)) {       /* pv is offset? */
1534         sv_backoff(sv);
1535         s = SvPVX_mutable(sv);
1536         if (newlen > SvLEN(sv))
1537             newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1538     }
1539     else
1540     {
1541         if (SvIsCOW(sv)) S_sv_uncow(aTHX_ sv, 0);
1542         s = SvPVX_mutable(sv);
1543     }
1544
1545 #ifdef PERL_NEW_COPY_ON_WRITE
1546     /* the new COW scheme uses SvPVX(sv)[SvLEN(sv)-1] (if spare)
1547      * to store the COW count. So in general, allocate one more byte than
1548      * asked for, to make it likely this byte is always spare: and thus
1549      * make more strings COW-able.
1550      * If the new size is a big power of two, don't bother: we assume the
1551      * caller wanted a nice 2^N sized block and will be annoyed at getting
1552      * 2^N+1 */
1553     if (newlen & 0xff)
1554         newlen++;
1555 #endif
1556
1557 #if defined(PERL_USE_MALLOC_SIZE) && defined(Perl_safesysmalloc_size)
1558 #define PERL_UNWARANTED_CHUMMINESS_WITH_MALLOC
1559 #endif
1560
1561     if (newlen > SvLEN(sv)) {           /* need more room? */
1562         STRLEN minlen = SvCUR(sv);
1563         minlen += (minlen >> PERL_STRLEN_EXPAND_SHIFT) + 10;
1564         if (newlen < minlen)
1565             newlen = minlen;
1566 #ifndef PERL_UNWARANTED_CHUMMINESS_WITH_MALLOC
1567
1568         /* Don't round up on the first allocation, as odds are pretty good that
1569          * the initial request is accurate as to what is really needed */
1570         if (SvLEN(sv)) {
1571             newlen = PERL_STRLEN_ROUNDUP(newlen);
1572         }
1573 #endif
1574         if (SvLEN(sv) && s) {
1575             s = (char*)saferealloc(s, newlen);
1576         }
1577         else {
1578             s = (char*)safemalloc(newlen);
1579             if (SvPVX_const(sv) && SvCUR(sv)) {
1580                 Move(SvPVX_const(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1581             }
1582         }
1583         SvPV_set(sv, s);
1584 #ifdef PERL_UNWARANTED_CHUMMINESS_WITH_MALLOC
1585         /* Do this here, do it once, do it right, and then we will never get
1586            called back into sv_grow() unless there really is some growing
1587            needed.  */
1588         SvLEN_set(sv, Perl_safesysmalloc_size(s));
1589 #else
1590         SvLEN_set(sv, newlen);
1591 #endif
1592     }
1593     return s;
1594 }
1595
1596 /*
1597 =for apidoc sv_setiv
1598
1599 Copies an integer into the given SV, upgrading first if necessary.
1600 Does not handle 'set' magic.  See also C<sv_setiv_mg>.
1601
1602 =cut
1603 */
1604
1605 void
1606 Perl_sv_setiv(pTHX_ SV *const sv, const IV i)
1607 {
1608     PERL_ARGS_ASSERT_SV_SETIV;
1609
1610     SV_CHECK_THINKFIRST_COW_DROP(sv);
1611     switch (SvTYPE(sv)) {
1612     case SVt_NULL:
1613     case SVt_NV:
1614         sv_upgrade(sv, SVt_IV);
1615         break;
1616     case SVt_PV:
1617         sv_upgrade(sv, SVt_PVIV);
1618         break;
1619
1620     case SVt_PVGV:
1621         if (!isGV_with_GP(sv))
1622             break;
1623     case SVt_PVAV:
1624     case SVt_PVHV:
1625     case SVt_PVCV:
1626     case SVt_PVFM:
1627     case SVt_PVIO:
1628         /* diag_listed_as: Can't coerce %s to %s in %s */
1629         Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1630                    OP_DESC(PL_op));
1631     default: NOOP;
1632     }
1633     (void)SvIOK_only(sv);                       /* validate number */
1634     SvIV_set(sv, i);
1635     SvTAINT(sv);
1636 }
1637
1638 /*
1639 =for apidoc sv_setiv_mg
1640
1641 Like C<sv_setiv>, but also handles 'set' magic.
1642
1643 =cut
1644 */
1645
1646 void
1647 Perl_sv_setiv_mg(pTHX_ SV *const sv, const IV i)
1648 {
1649     PERL_ARGS_ASSERT_SV_SETIV_MG;
1650
1651     sv_setiv(sv,i);
1652     SvSETMAGIC(sv);
1653 }
1654
1655 /*
1656 =for apidoc sv_setuv
1657
1658 Copies an unsigned integer into the given SV, upgrading first if necessary.
1659 Does not handle 'set' magic.  See also C<sv_setuv_mg>.
1660
1661 =cut
1662 */
1663
1664 void
1665 Perl_sv_setuv(pTHX_ SV *const sv, const UV u)
1666 {
1667     PERL_ARGS_ASSERT_SV_SETUV;
1668
1669     /* With the if statement to ensure that integers are stored as IVs whenever
1670        possible:
1671        u=1.49  s=0.52  cu=72.49  cs=10.64  scripts=270  tests=20865
1672
1673        without
1674        u=1.35  s=0.47  cu=73.45  cs=11.43  scripts=270  tests=20865
1675
1676        If you wish to remove the following if statement, so that this routine
1677        (and its callers) always return UVs, please benchmark to see what the
1678        effect is. Modern CPUs may be different. Or may not :-)
1679     */
1680     if (u <= (UV)IV_MAX) {
1681        sv_setiv(sv, (IV)u);
1682        return;
1683     }
1684     sv_setiv(sv, 0);
1685     SvIsUV_on(sv);
1686     SvUV_set(sv, u);
1687 }
1688
1689 /*
1690 =for apidoc sv_setuv_mg
1691
1692 Like C<sv_setuv>, but also handles 'set' magic.
1693
1694 =cut
1695 */
1696
1697 void
1698 Perl_sv_setuv_mg(pTHX_ SV *const sv, const UV u)
1699 {
1700     PERL_ARGS_ASSERT_SV_SETUV_MG;
1701
1702     sv_setuv(sv,u);
1703     SvSETMAGIC(sv);
1704 }
1705
1706 /*
1707 =for apidoc sv_setnv
1708
1709 Copies a double into the given SV, upgrading first if necessary.
1710 Does not handle 'set' magic.  See also C<sv_setnv_mg>.
1711
1712 =cut
1713 */
1714
1715 void
1716 Perl_sv_setnv(pTHX_ SV *const sv, const NV num)
1717 {
1718     PERL_ARGS_ASSERT_SV_SETNV;
1719
1720     SV_CHECK_THINKFIRST_COW_DROP(sv);
1721     switch (SvTYPE(sv)) {
1722     case SVt_NULL:
1723     case SVt_IV:
1724         sv_upgrade(sv, SVt_NV);
1725         break;
1726     case SVt_PV:
1727     case SVt_PVIV:
1728         sv_upgrade(sv, SVt_PVNV);
1729         break;
1730
1731     case SVt_PVGV:
1732         if (!isGV_with_GP(sv))
1733             break;
1734     case SVt_PVAV:
1735     case SVt_PVHV:
1736     case SVt_PVCV:
1737     case SVt_PVFM:
1738     case SVt_PVIO:
1739         /* diag_listed_as: Can't coerce %s to %s in %s */
1740         Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
1741                    OP_DESC(PL_op));
1742     default: NOOP;
1743     }
1744     SvNV_set(sv, num);
1745     (void)SvNOK_only(sv);                       /* validate number */
1746     SvTAINT(sv);
1747 }
1748
1749 /*
1750 =for apidoc sv_setnv_mg
1751
1752 Like C<sv_setnv>, but also handles 'set' magic.
1753
1754 =cut
1755 */
1756
1757 void
1758 Perl_sv_setnv_mg(pTHX_ SV *const sv, const NV num)
1759 {
1760     PERL_ARGS_ASSERT_SV_SETNV_MG;
1761
1762     sv_setnv(sv,num);
1763     SvSETMAGIC(sv);
1764 }
1765
1766 /* Return a cleaned-up, printable version of sv, for non-numeric, or
1767  * not incrementable warning display.
1768  * Originally part of S_not_a_number().
1769  * The return value may be != tmpbuf.
1770  */
1771
1772 STATIC const char *
1773 S_sv_display(pTHX_ SV *const sv, char *tmpbuf, STRLEN tmpbuf_size) {
1774     const char *pv;
1775
1776      PERL_ARGS_ASSERT_SV_DISPLAY;
1777
1778      if (DO_UTF8(sv)) {
1779           SV *dsv = newSVpvs_flags("", SVs_TEMP);
1780           pv = sv_uni_display(dsv, sv, 10, UNI_DISPLAY_ISPRINT);
1781      } else {
1782           char *d = tmpbuf;
1783           const char * const limit = tmpbuf + tmpbuf_size - 8;
1784           /* each *s can expand to 4 chars + "...\0",
1785              i.e. need room for 8 chars */
1786         
1787           const char *s = SvPVX_const(sv);
1788           const char * const end = s + SvCUR(sv);
1789           for ( ; s < end && d < limit; s++ ) {
1790                int ch = *s & 0xFF;
1791                if (! isASCII(ch) && !isPRINT_LC(ch)) {
1792                     *d++ = 'M';
1793                     *d++ = '-';
1794
1795                     /* Map to ASCII "equivalent" of Latin1 */
1796                     ch = LATIN1_TO_NATIVE(NATIVE_TO_LATIN1(ch) & 127);
1797                }
1798                if (ch == '\n') {
1799                     *d++ = '\\';
1800                     *d++ = 'n';
1801                }
1802                else if (ch == '\r') {
1803                     *d++ = '\\';
1804                     *d++ = 'r';
1805                }
1806                else if (ch == '\f') {
1807                     *d++ = '\\';
1808                     *d++ = 'f';
1809                }
1810                else if (ch == '\\') {
1811                     *d++ = '\\';
1812                     *d++ = '\\';
1813                }
1814                else if (ch == '\0') {
1815                     *d++ = '\\';
1816                     *d++ = '0';
1817                }
1818                else if (isPRINT_LC(ch))
1819                     *d++ = ch;
1820                else {
1821                     *d++ = '^';
1822                     *d++ = toCTRL(ch);
1823                }
1824           }
1825           if (s < end) {
1826                *d++ = '.';
1827                *d++ = '.';
1828                *d++ = '.';
1829           }
1830           *d = '\0';
1831           pv = tmpbuf;
1832     }
1833
1834     return pv;
1835 }
1836
1837 /* Print an "isn't numeric" warning, using a cleaned-up,
1838  * printable version of the offending string
1839  */
1840
1841 STATIC void
1842 S_not_a_number(pTHX_ SV *const sv)
1843 {
1844      char tmpbuf[64];
1845      const char *pv;
1846
1847      PERL_ARGS_ASSERT_NOT_A_NUMBER;
1848
1849      pv = sv_display(sv, tmpbuf, sizeof(tmpbuf));
1850
1851     if (PL_op)
1852         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1853                     /* diag_listed_as: Argument "%s" isn't numeric%s */
1854                     "Argument \"%s\" isn't numeric in %s", pv,
1855                     OP_DESC(PL_op));
1856     else
1857         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1858                     /* diag_listed_as: Argument "%s" isn't numeric%s */
1859                     "Argument \"%s\" isn't numeric", pv);
1860 }
1861
1862 STATIC void
1863 S_not_incrementable(pTHX_ SV *const sv) {
1864      char tmpbuf[64];
1865      const char *pv;
1866
1867      PERL_ARGS_ASSERT_NOT_INCREMENTABLE;
1868
1869      pv = sv_display(sv, tmpbuf, sizeof(tmpbuf));
1870
1871      Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1872                  "Argument \"%s\" treated as 0 in increment (++)", pv);
1873 }
1874
1875 /*
1876 =for apidoc looks_like_number
1877
1878 Test if the content of an SV looks like a number (or is a number).
1879 C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1880 non-numeric warning), even if your atof() doesn't grok them.  Get-magic is
1881 ignored.
1882
1883 =cut
1884 */
1885
1886 I32
1887 Perl_looks_like_number(pTHX_ SV *const sv)
1888 {
1889     const char *sbegin;
1890     STRLEN len;
1891
1892     PERL_ARGS_ASSERT_LOOKS_LIKE_NUMBER;
1893
1894     if (SvPOK(sv) || SvPOKp(sv)) {
1895         sbegin = SvPV_nomg_const(sv, len);
1896     }
1897     else
1898         return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
1899     return grok_number(sbegin, len, NULL);
1900 }
1901
1902 STATIC bool
1903 S_glob_2number(pTHX_ GV * const gv)
1904 {
1905     PERL_ARGS_ASSERT_GLOB_2NUMBER;
1906
1907     /* We know that all GVs stringify to something that is not-a-number,
1908         so no need to test that.  */
1909     if (ckWARN(WARN_NUMERIC))
1910     {
1911         SV *const buffer = sv_newmortal();
1912         gv_efullname3(buffer, gv, "*");
1913         not_a_number(buffer);
1914     }
1915     /* We just want something true to return, so that S_sv_2iuv_common
1916         can tail call us and return true.  */
1917     return TRUE;
1918 }
1919
1920 /* Actually, ISO C leaves conversion of UV to IV undefined, but
1921    until proven guilty, assume that things are not that bad... */
1922
1923 /*
1924    NV_PRESERVES_UV:
1925
1926    As 64 bit platforms often have an NV that doesn't preserve all bits of
1927    an IV (an assumption perl has been based on to date) it becomes necessary
1928    to remove the assumption that the NV always carries enough precision to
1929    recreate the IV whenever needed, and that the NV is the canonical form.
1930    Instead, IV/UV and NV need to be given equal rights. So as to not lose
1931    precision as a side effect of conversion (which would lead to insanity
1932    and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1933    1) to distinguish between IV/UV/NV slots that have a valid conversion cached
1934       where precision was lost, and IV/UV/NV slots that have a valid conversion
1935       which has lost no precision
1936    2) to ensure that if a numeric conversion to one form is requested that
1937       would lose precision, the precise conversion (or differently
1938       imprecise conversion) is also performed and cached, to prevent
1939       requests for different numeric formats on the same SV causing
1940       lossy conversion chains. (lossless conversion chains are perfectly
1941       acceptable (still))
1942
1943
1944    flags are used:
1945    SvIOKp is true if the IV slot contains a valid value
1946    SvIOK  is true only if the IV value is accurate (UV if SvIOK_UV true)
1947    SvNOKp is true if the NV slot contains a valid value
1948    SvNOK  is true only if the NV value is accurate
1949
1950    so
1951    while converting from PV to NV, check to see if converting that NV to an
1952    IV(or UV) would lose accuracy over a direct conversion from PV to
1953    IV(or UV). If it would, cache both conversions, return NV, but mark
1954    SV as IOK NOKp (ie not NOK).
1955
1956    While converting from PV to IV, check to see if converting that IV to an
1957    NV would lose accuracy over a direct conversion from PV to NV. If it
1958    would, cache both conversions, flag similarly.
1959
1960    Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1961    correctly because if IV & NV were set NV *always* overruled.
1962    Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1963    changes - now IV and NV together means that the two are interchangeable:
1964    SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
1965
1966    The benefit of this is that operations such as pp_add know that if
1967    SvIOK is true for both left and right operands, then integer addition
1968    can be used instead of floating point (for cases where the result won't
1969    overflow). Before, floating point was always used, which could lead to
1970    loss of precision compared with integer addition.
1971
1972    * making IV and NV equal status should make maths accurate on 64 bit
1973      platforms
1974    * may speed up maths somewhat if pp_add and friends start to use
1975      integers when possible instead of fp. (Hopefully the overhead in
1976      looking for SvIOK and checking for overflow will not outweigh the
1977      fp to integer speedup)
1978    * will slow down integer operations (callers of SvIV) on "inaccurate"
1979      values, as the change from SvIOK to SvIOKp will cause a call into
1980      sv_2iv each time rather than a macro access direct to the IV slot
1981    * should speed up number->string conversion on integers as IV is
1982      favoured when IV and NV are equally accurate
1983
1984    ####################################################################
1985    You had better be using SvIOK_notUV if you want an IV for arithmetic:
1986    SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
1987    On the other hand, SvUOK is true iff UV.
1988    ####################################################################
1989
1990    Your mileage will vary depending your CPU's relative fp to integer
1991    performance ratio.
1992 */
1993
1994 #ifndef NV_PRESERVES_UV
1995 #  define IS_NUMBER_UNDERFLOW_IV 1
1996 #  define IS_NUMBER_UNDERFLOW_UV 2
1997 #  define IS_NUMBER_IV_AND_UV    2
1998 #  define IS_NUMBER_OVERFLOW_IV  4
1999 #  define IS_NUMBER_OVERFLOW_UV  5
2000
2001 /* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
2002
2003 /* For sv_2nv these three cases are "SvNOK and don't bother casting"  */
2004 STATIC int
2005 S_sv_2iuv_non_preserve(pTHX_ SV *const sv
2006 #  ifdef DEBUGGING
2007                        , I32 numtype
2008 #  endif
2009                        )
2010 {
2011     PERL_ARGS_ASSERT_SV_2IUV_NON_PRESERVE;
2012     PERL_UNUSED_CONTEXT;
2013
2014     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));
2015     if (SvNVX(sv) < (NV)IV_MIN) {
2016         (void)SvIOKp_on(sv);
2017         (void)SvNOK_on(sv);
2018         SvIV_set(sv, IV_MIN);
2019         return IS_NUMBER_UNDERFLOW_IV;
2020     }
2021     if (SvNVX(sv) > (NV)UV_MAX) {
2022         (void)SvIOKp_on(sv);
2023         (void)SvNOK_on(sv);
2024         SvIsUV_on(sv);
2025         SvUV_set(sv, UV_MAX);
2026         return IS_NUMBER_OVERFLOW_UV;
2027     }
2028     (void)SvIOKp_on(sv);
2029     (void)SvNOK_on(sv);
2030     /* Can't use strtol etc to convert this string.  (See truth table in
2031        sv_2iv  */
2032     if (SvNVX(sv) <= (UV)IV_MAX) {
2033         SvIV_set(sv, I_V(SvNVX(sv)));
2034         if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2035             SvIOK_on(sv); /* Integer is precise. NOK, IOK */
2036         } else {
2037             /* Integer is imprecise. NOK, IOKp */
2038         }
2039         return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
2040     }
2041     SvIsUV_on(sv);
2042     SvUV_set(sv, U_V(SvNVX(sv)));
2043     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2044         if (SvUVX(sv) == UV_MAX) {
2045             /* As we know that NVs don't preserve UVs, UV_MAX cannot
2046                possibly be preserved by NV. Hence, it must be overflow.
2047                NOK, IOKp */
2048             return IS_NUMBER_OVERFLOW_UV;
2049         }
2050         SvIOK_on(sv); /* Integer is precise. NOK, UOK */
2051     } else {
2052         /* Integer is imprecise. NOK, IOKp */
2053     }
2054     return IS_NUMBER_OVERFLOW_IV;
2055 }
2056 #endif /* !NV_PRESERVES_UV*/
2057
2058 STATIC bool
2059 S_sv_2iuv_common(pTHX_ SV *const sv)
2060 {
2061     PERL_ARGS_ASSERT_SV_2IUV_COMMON;
2062
2063     if (SvNOKp(sv)) {
2064         /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
2065          * without also getting a cached IV/UV from it at the same time
2066          * (ie PV->NV conversion should detect loss of accuracy and cache
2067          * IV or UV at same time to avoid this. */
2068         /* IV-over-UV optimisation - choose to cache IV if possible */
2069
2070         if (SvTYPE(sv) == SVt_NV)
2071             sv_upgrade(sv, SVt_PVNV);
2072
2073         (void)SvIOKp_on(sv);    /* Must do this first, to clear any SvOOK */
2074         /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
2075            certainly cast into the IV range at IV_MAX, whereas the correct
2076            answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
2077            cases go to UV */
2078 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
2079         if (Perl_isnan(SvNVX(sv))) {
2080             SvUV_set(sv, 0);
2081             SvIsUV_on(sv);
2082             return FALSE;
2083         }
2084 #endif
2085         if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2086             SvIV_set(sv, I_V(SvNVX(sv)));
2087             if (SvNVX(sv) == (NV) SvIVX(sv)
2088 #ifndef NV_PRESERVES_UV
2089                 && (((UV)1 << NV_PRESERVES_UV_BITS) >
2090                     (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2091                 /* Don't flag it as "accurately an integer" if the number
2092                    came from a (by definition imprecise) NV operation, and
2093                    we're outside the range of NV integer precision */
2094 #endif
2095                 ) {
2096                 if (SvNOK(sv))
2097                     SvIOK_on(sv);  /* Can this go wrong with rounding? NWC */
2098                 else {
2099                     /* scalar has trailing garbage, eg "42a" */
2100                 }
2101                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2102                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
2103                                       PTR2UV(sv),
2104                                       SvNVX(sv),
2105                                       SvIVX(sv)));
2106
2107             } else {
2108                 /* IV not precise.  No need to convert from PV, as NV
2109                    conversion would already have cached IV if it detected
2110                    that PV->IV would be better than PV->NV->IV
2111                    flags already correct - don't set public IOK.  */
2112                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2113                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
2114                                       PTR2UV(sv),
2115                                       SvNVX(sv),
2116                                       SvIVX(sv)));
2117             }
2118             /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2119                but the cast (NV)IV_MIN rounds to a the value less (more
2120                negative) than IV_MIN which happens to be equal to SvNVX ??
2121                Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2122                NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2123                (NV)UVX == NVX are both true, but the values differ. :-(
2124                Hopefully for 2s complement IV_MIN is something like
2125                0x8000000000000000 which will be exact. NWC */
2126         }
2127         else {
2128             SvUV_set(sv, U_V(SvNVX(sv)));
2129             if (
2130                 (SvNVX(sv) == (NV) SvUVX(sv))
2131 #ifndef  NV_PRESERVES_UV
2132                 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2133                 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2134                 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2135                 /* Don't flag it as "accurately an integer" if the number
2136                    came from a (by definition imprecise) NV operation, and
2137                    we're outside the range of NV integer precision */
2138 #endif
2139                 && SvNOK(sv)
2140                 )
2141                 SvIOK_on(sv);
2142             SvIsUV_on(sv);
2143             DEBUG_c(PerlIO_printf(Perl_debug_log,
2144                                   "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
2145                                   PTR2UV(sv),
2146                                   SvUVX(sv),
2147                                   SvUVX(sv)));
2148         }
2149     }
2150     else if (SvPOKp(sv)) {
2151         UV value;
2152         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2153         /* We want to avoid a possible problem when we cache an IV/ a UV which
2154            may be later translated to an NV, and the resulting NV is not
2155            the same as the direct translation of the initial string
2156            (eg 123.456 can shortcut to the IV 123 with atol(), but we must
2157            be careful to ensure that the value with the .456 is around if the
2158            NV value is requested in the future).
2159         
2160            This means that if we cache such an IV/a UV, we need to cache the
2161            NV as well.  Moreover, we trade speed for space, and do not
2162            cache the NV if we are sure it's not needed.
2163          */
2164
2165         /* SVt_PVNV is one higher than SVt_PVIV, hence this order  */
2166         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2167              == IS_NUMBER_IN_UV) {
2168             /* It's definitely an integer, only upgrade to PVIV */
2169             if (SvTYPE(sv) < SVt_PVIV)
2170                 sv_upgrade(sv, SVt_PVIV);
2171             (void)SvIOK_on(sv);
2172         } else if (SvTYPE(sv) < SVt_PVNV)
2173             sv_upgrade(sv, SVt_PVNV);
2174
2175         /* If NVs preserve UVs then we only use the UV value if we know that
2176            we aren't going to call atof() below. If NVs don't preserve UVs
2177            then the value returned may have more precision than atof() will
2178            return, even though value isn't perfectly accurate.  */
2179         if ((numtype & (IS_NUMBER_IN_UV
2180 #ifdef NV_PRESERVES_UV
2181                         | IS_NUMBER_NOT_INT
2182 #endif
2183             )) == IS_NUMBER_IN_UV) {
2184             /* This won't turn off the public IOK flag if it was set above  */
2185             (void)SvIOKp_on(sv);
2186
2187             if (!(numtype & IS_NUMBER_NEG)) {
2188                 /* positive */;
2189                 if (value <= (UV)IV_MAX) {
2190                     SvIV_set(sv, (IV)value);
2191                 } else {
2192                     /* it didn't overflow, and it was positive. */
2193                     SvUV_set(sv, value);
2194                     SvIsUV_on(sv);
2195                 }
2196             } else {
2197                 /* 2s complement assumption  */
2198                 if (value <= (UV)IV_MIN) {
2199                     SvIV_set(sv, -(IV)value);
2200                 } else {
2201                     /* Too negative for an IV.  This is a double upgrade, but
2202                        I'm assuming it will be rare.  */
2203                     if (SvTYPE(sv) < SVt_PVNV)
2204                         sv_upgrade(sv, SVt_PVNV);
2205                     SvNOK_on(sv);
2206                     SvIOK_off(sv);
2207                     SvIOKp_on(sv);
2208                     SvNV_set(sv, -(NV)value);
2209                     SvIV_set(sv, IV_MIN);
2210                 }
2211             }
2212         }
2213         /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2214            will be in the previous block to set the IV slot, and the next
2215            block to set the NV slot.  So no else here.  */
2216         
2217         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2218             != IS_NUMBER_IN_UV) {
2219             /* It wasn't an (integer that doesn't overflow the UV). */
2220             SvNV_set(sv, Atof(SvPVX_const(sv)));
2221
2222             if (! numtype && ckWARN(WARN_NUMERIC))
2223                 not_a_number(sv);
2224
2225             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" NVgf ")\n",
2226                                   PTR2UV(sv), SvNVX(sv)));
2227
2228 #ifdef NV_PRESERVES_UV
2229             (void)SvIOKp_on(sv);
2230             (void)SvNOK_on(sv);
2231             if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2232                 SvIV_set(sv, I_V(SvNVX(sv)));
2233                 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2234                     SvIOK_on(sv);
2235                 } else {
2236                     NOOP;  /* Integer is imprecise. NOK, IOKp */
2237                 }
2238                 /* UV will not work better than IV */
2239             } else {
2240                 if (SvNVX(sv) > (NV)UV_MAX) {
2241                     SvIsUV_on(sv);
2242                     /* Integer is inaccurate. NOK, IOKp, is UV */
2243                     SvUV_set(sv, UV_MAX);
2244                 } else {
2245                     SvUV_set(sv, U_V(SvNVX(sv)));
2246                     /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2247                        NV preservse UV so can do correct comparison.  */
2248                     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2249                         SvIOK_on(sv);
2250                     } else {
2251                         NOOP;   /* Integer is imprecise. NOK, IOKp, is UV */
2252                     }
2253                 }
2254                 SvIsUV_on(sv);
2255             }
2256 #else /* NV_PRESERVES_UV */
2257             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2258                 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2259                 /* The IV/UV slot will have been set from value returned by
2260                    grok_number above.  The NV slot has just been set using
2261                    Atof.  */
2262                 SvNOK_on(sv);
2263                 assert (SvIOKp(sv));
2264             } else {
2265                 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2266                     U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2267                     /* Small enough to preserve all bits. */
2268                     (void)SvIOKp_on(sv);
2269                     SvNOK_on(sv);
2270                     SvIV_set(sv, I_V(SvNVX(sv)));
2271                     if ((NV)(SvIVX(sv)) == SvNVX(sv))
2272                         SvIOK_on(sv);
2273                     /* Assumption: first non-preserved integer is < IV_MAX,
2274                        this NV is in the preserved range, therefore: */
2275                     if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2276                           < (UV)IV_MAX)) {
2277                         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);
2278                     }
2279                 } else {
2280                     /* IN_UV NOT_INT
2281                          0      0       already failed to read UV.
2282                          0      1       already failed to read UV.
2283                          1      0       you won't get here in this case. IV/UV
2284                                         slot set, public IOK, Atof() unneeded.
2285                          1      1       already read UV.
2286                        so there's no point in sv_2iuv_non_preserve() attempting
2287                        to use atol, strtol, strtoul etc.  */
2288 #  ifdef DEBUGGING
2289                     sv_2iuv_non_preserve (sv, numtype);
2290 #  else
2291                     sv_2iuv_non_preserve (sv);
2292 #  endif
2293                 }
2294             }
2295 #endif /* NV_PRESERVES_UV */
2296         /* It might be more code efficient to go through the entire logic above
2297            and conditionally set with SvIOKp_on() rather than SvIOK(), but it
2298            gets complex and potentially buggy, so more programmer efficient
2299            to do it this way, by turning off the public flags:  */
2300         if (!numtype)
2301             SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2302         }
2303     }
2304     else  {
2305         if (isGV_with_GP(sv))
2306             return glob_2number(MUTABLE_GV(sv));
2307
2308         if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2309                 report_uninit(sv);
2310         if (SvTYPE(sv) < SVt_IV)
2311             /* Typically the caller expects that sv_any is not NULL now.  */
2312             sv_upgrade(sv, SVt_IV);
2313         /* Return 0 from the caller.  */
2314         return TRUE;
2315     }
2316     return FALSE;
2317 }
2318
2319 /*
2320 =for apidoc sv_2iv_flags
2321
2322 Return the integer value of an SV, doing any necessary string
2323 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2324 Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2325
2326 =cut
2327 */
2328
2329 IV
2330 Perl_sv_2iv_flags(pTHX_ SV *const sv, const I32 flags)
2331 {
2332     PERL_ARGS_ASSERT_SV_2IV_FLAGS;
2333
2334     assert (SvTYPE(sv) != SVt_PVAV && SvTYPE(sv) != SVt_PVHV
2335          && SvTYPE(sv) != SVt_PVFM);
2336
2337     if (SvGMAGICAL(sv) && (flags & SV_GMAGIC))
2338         mg_get(sv);
2339
2340     if (SvROK(sv)) {
2341         if (SvAMAGIC(sv)) {
2342             SV * tmpstr;
2343             if (flags & SV_SKIP_OVERLOAD)
2344                 return 0;
2345             tmpstr = AMG_CALLunary(sv, numer_amg);
2346             if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2347                 return SvIV(tmpstr);
2348             }
2349         }
2350         return PTR2IV(SvRV(sv));
2351     }
2352
2353     if (SvVALID(sv) || isREGEXP(sv)) {
2354         /* FBMs use the space for SvIVX and SvNVX for other purposes, and use
2355            the same flag bit as SVf_IVisUV, so must not let them cache IVs.
2356            In practice they are extremely unlikely to actually get anywhere
2357            accessible by user Perl code - the only way that I'm aware of is when
2358            a constant subroutine which is used as the second argument to index.
2359
2360            Regexps have no SvIVX and SvNVX fields.
2361         */
2362         assert(isREGEXP(sv) || SvPOKp(sv));
2363         {
2364             UV value;
2365             const char * const ptr =
2366                 isREGEXP(sv) ? RX_WRAPPED((REGEXP*)sv) : SvPVX_const(sv);
2367             const int numtype
2368                 = grok_number(ptr, SvCUR(sv), &value);
2369
2370             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2371                 == IS_NUMBER_IN_UV) {
2372                 /* It's definitely an integer */
2373                 if (numtype & IS_NUMBER_NEG) {
2374                     if (value < (UV)IV_MIN)
2375                         return -(IV)value;
2376                 } else {
2377                     if (value < (UV)IV_MAX)
2378                         return (IV)value;
2379                 }
2380             }
2381             if (!numtype) {
2382                 if (ckWARN(WARN_NUMERIC))
2383                     not_a_number(sv);
2384             }
2385             return I_V(Atof(ptr));
2386         }
2387     }
2388
2389     if (SvTHINKFIRST(sv)) {
2390 #ifdef PERL_OLD_COPY_ON_WRITE
2391         if (SvIsCOW(sv)) {
2392             sv_force_normal_flags(sv, 0);
2393         }
2394 #endif
2395         if (SvREADONLY(sv) && !SvOK(sv)) {
2396             if (ckWARN(WARN_UNINITIALIZED))
2397                 report_uninit(sv);
2398             return 0;
2399         }
2400     }
2401
2402     if (!SvIOKp(sv)) {
2403         if (S_sv_2iuv_common(aTHX_ sv))
2404             return 0;
2405     }
2406
2407     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2408         PTR2UV(sv),SvIVX(sv)));
2409     return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
2410 }
2411
2412 /*
2413 =for apidoc sv_2uv_flags
2414
2415 Return the unsigned integer value of an SV, doing any necessary string
2416 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2417 Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
2418
2419 =cut
2420 */
2421
2422 UV
2423 Perl_sv_2uv_flags(pTHX_ SV *const sv, const I32 flags)
2424 {
2425     PERL_ARGS_ASSERT_SV_2UV_FLAGS;
2426
2427     if (SvGMAGICAL(sv) && (flags & SV_GMAGIC))
2428         mg_get(sv);
2429
2430     if (SvROK(sv)) {
2431         if (SvAMAGIC(sv)) {
2432             SV *tmpstr;
2433             if (flags & SV_SKIP_OVERLOAD)
2434                 return 0;
2435             tmpstr = AMG_CALLunary(sv, numer_amg);
2436             if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2437                 return SvUV(tmpstr);
2438             }
2439         }
2440         return PTR2UV(SvRV(sv));
2441     }
2442
2443     if (SvVALID(sv) || isREGEXP(sv)) {
2444         /* FBMs use the space for SvIVX and SvNVX for other purposes, and use
2445            the same flag bit as SVf_IVisUV, so must not let them cache IVs.  
2446            Regexps have no SvIVX and SvNVX fields. */
2447         assert(isREGEXP(sv) || SvPOKp(sv));
2448         {
2449             UV value;
2450             const char * const ptr =
2451                 isREGEXP(sv) ? RX_WRAPPED((REGEXP*)sv) : SvPVX_const(sv);
2452             const int numtype
2453                 = grok_number(ptr, SvCUR(sv), &value);
2454
2455             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2456                 == IS_NUMBER_IN_UV) {
2457                 /* It's definitely an integer */
2458                 if (!(numtype & IS_NUMBER_NEG))
2459                     return value;
2460             }
2461             if (!numtype) {
2462                 if (ckWARN(WARN_NUMERIC))
2463                     not_a_number(sv);
2464             }
2465             return U_V(Atof(ptr));
2466         }
2467     }
2468
2469     if (SvTHINKFIRST(sv)) {
2470 #ifdef PERL_OLD_COPY_ON_WRITE
2471         if (SvIsCOW(sv)) {
2472             sv_force_normal_flags(sv, 0);
2473         }
2474 #endif
2475         if (SvREADONLY(sv) && !SvOK(sv)) {
2476             if (ckWARN(WARN_UNINITIALIZED))
2477                 report_uninit(sv);
2478             return 0;
2479         }
2480     }
2481
2482     if (!SvIOKp(sv)) {
2483         if (S_sv_2iuv_common(aTHX_ sv))
2484             return 0;
2485     }
2486
2487     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2488                           PTR2UV(sv),SvUVX(sv)));
2489     return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
2490 }
2491
2492 /*
2493 =for apidoc sv_2nv_flags
2494
2495 Return the num value of an SV, doing any necessary string or integer
2496 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2497 Normally used via the C<SvNV(sv)> and C<SvNVx(sv)> macros.
2498
2499 =cut
2500 */
2501
2502 NV
2503 Perl_sv_2nv_flags(pTHX_ SV *const sv, const I32 flags)
2504 {
2505     PERL_ARGS_ASSERT_SV_2NV_FLAGS;
2506
2507     assert (SvTYPE(sv) != SVt_PVAV && SvTYPE(sv) != SVt_PVHV
2508          && SvTYPE(sv) != SVt_PVFM);
2509     if (SvGMAGICAL(sv) || SvVALID(sv) || isREGEXP(sv)) {
2510         /* FBMs use the space for SvIVX and SvNVX for other purposes, and use
2511            the same flag bit as SVf_IVisUV, so must not let them cache NVs.
2512            Regexps have no SvIVX and SvNVX fields.  */
2513         const char *ptr;
2514         if (flags & SV_GMAGIC)
2515             mg_get(sv);
2516         if (SvNOKp(sv))
2517             return SvNVX(sv);
2518         if (SvPOKp(sv) && !SvIOKp(sv)) {
2519             ptr = SvPVX_const(sv);
2520           grokpv:
2521             if (!SvIOKp(sv) && ckWARN(WARN_NUMERIC) &&
2522                 !grok_number(ptr, SvCUR(sv), NULL))
2523                 not_a_number(sv);
2524             return Atof(ptr);
2525         }
2526         if (SvIOKp(sv)) {
2527             if (SvIsUV(sv))
2528                 return (NV)SvUVX(sv);
2529             else
2530                 return (NV)SvIVX(sv);
2531         }
2532         if (SvROK(sv)) {
2533             goto return_rok;
2534         }
2535         if (isREGEXP(sv)) {
2536             ptr = RX_WRAPPED((REGEXP *)sv);
2537             goto grokpv;
2538         }
2539         assert(SvTYPE(sv) >= SVt_PVMG);
2540         /* This falls through to the report_uninit near the end of the
2541            function. */
2542     } else if (SvTHINKFIRST(sv)) {
2543         if (SvROK(sv)) {
2544         return_rok:
2545             if (SvAMAGIC(sv)) {
2546                 SV *tmpstr;
2547                 if (flags & SV_SKIP_OVERLOAD)
2548                     return 0;
2549                 tmpstr = AMG_CALLunary(sv, numer_amg);
2550                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2551                     return SvNV(tmpstr);
2552                 }
2553             }
2554             return PTR2NV(SvRV(sv));
2555         }
2556 #ifdef PERL_OLD_COPY_ON_WRITE
2557         if (SvIsCOW(sv)) {
2558             sv_force_normal_flags(sv, 0);
2559         }
2560 #endif
2561         if (SvREADONLY(sv) && !SvOK(sv)) {
2562             if (ckWARN(WARN_UNINITIALIZED))
2563                 report_uninit(sv);
2564             return 0.0;
2565         }
2566     }
2567     if (SvTYPE(sv) < SVt_NV) {
2568         /* The logic to use SVt_PVNV if necessary is in sv_upgrade.  */
2569         sv_upgrade(sv, SVt_NV);
2570         DEBUG_c({
2571             STORE_NUMERIC_LOCAL_SET_STANDARD();
2572             PerlIO_printf(Perl_debug_log,
2573                           "0x%"UVxf" num(%" NVgf ")\n",
2574                           PTR2UV(sv), SvNVX(sv));
2575             RESTORE_NUMERIC_LOCAL();
2576         });
2577     }
2578     else if (SvTYPE(sv) < SVt_PVNV)
2579         sv_upgrade(sv, SVt_PVNV);
2580     if (SvNOKp(sv)) {
2581         return SvNVX(sv);
2582     }
2583     if (SvIOKp(sv)) {
2584         SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
2585 #ifdef NV_PRESERVES_UV
2586         if (SvIOK(sv))
2587             SvNOK_on(sv);
2588         else
2589             SvNOKp_on(sv);
2590 #else
2591         /* Only set the public NV OK flag if this NV preserves the IV  */
2592         /* Check it's not 0xFFFFFFFFFFFFFFFF */
2593         if (SvIOK(sv) &&
2594             SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
2595                        : (SvIVX(sv) == I_V(SvNVX(sv))))
2596             SvNOK_on(sv);
2597         else
2598             SvNOKp_on(sv);
2599 #endif
2600     }
2601     else if (SvPOKp(sv)) {
2602         UV value;
2603         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2604         if (!SvIOKp(sv) && !numtype && ckWARN(WARN_NUMERIC))
2605             not_a_number(sv);
2606 #ifdef NV_PRESERVES_UV
2607         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2608             == IS_NUMBER_IN_UV) {
2609             /* It's definitely an integer */
2610             SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
2611         } else
2612             SvNV_set(sv, Atof(SvPVX_const(sv)));
2613         if (numtype)
2614             SvNOK_on(sv);
2615         else
2616             SvNOKp_on(sv);
2617 #else
2618         SvNV_set(sv, Atof(SvPVX_const(sv)));
2619         /* Only set the public NV OK flag if this NV preserves the value in
2620            the PV at least as well as an IV/UV would.
2621            Not sure how to do this 100% reliably. */
2622         /* if that shift count is out of range then Configure's test is
2623            wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2624            UV_BITS */
2625         if (((UV)1 << NV_PRESERVES_UV_BITS) >
2626             U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2627             SvNOK_on(sv); /* Definitely small enough to preserve all bits */
2628         } else if (!(numtype & IS_NUMBER_IN_UV)) {
2629             /* Can't use strtol etc to convert this string, so don't try.
2630                sv_2iv and sv_2uv will use the NV to convert, not the PV.  */
2631             SvNOK_on(sv);
2632         } else {
2633             /* value has been set.  It may not be precise.  */
2634             if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2635                 /* 2s complement assumption for (UV)IV_MIN  */
2636                 SvNOK_on(sv); /* Integer is too negative.  */
2637             } else {
2638                 SvNOKp_on(sv);
2639                 SvIOKp_on(sv);
2640
2641                 if (numtype & IS_NUMBER_NEG) {
2642                     SvIV_set(sv, -(IV)value);
2643                 } else if (value <= (UV)IV_MAX) {
2644                     SvIV_set(sv, (IV)value);
2645                 } else {
2646                     SvUV_set(sv, value);
2647                     SvIsUV_on(sv);
2648                 }
2649
2650                 if (numtype & IS_NUMBER_NOT_INT) {
2651                     /* I believe that even if the original PV had decimals,
2652                        they are lost beyond the limit of the FP precision.
2653                        However, neither is canonical, so both only get p
2654                        flags.  NWC, 2000/11/25 */
2655                     /* Both already have p flags, so do nothing */
2656                 } else {
2657                     const NV nv = SvNVX(sv);
2658                     if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2659                         if (SvIVX(sv) == I_V(nv)) {
2660                             SvNOK_on(sv);
2661                         } else {
2662                             /* It had no "." so it must be integer.  */
2663                         }
2664                         SvIOK_on(sv);
2665                     } else {
2666                         /* between IV_MAX and NV(UV_MAX).
2667                            Could be slightly > UV_MAX */
2668
2669                         if (numtype & IS_NUMBER_NOT_INT) {
2670                             /* UV and NV both imprecise.  */
2671                         } else {
2672                             const UV nv_as_uv = U_V(nv);
2673
2674                             if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2675                                 SvNOK_on(sv);
2676                             }
2677                             SvIOK_on(sv);
2678                         }
2679                     }
2680                 }
2681             }
2682         }
2683         /* It might be more code efficient to go through the entire logic above
2684            and conditionally set with SvNOKp_on() rather than SvNOK(), but it
2685            gets complex and potentially buggy, so more programmer efficient
2686            to do it this way, by turning off the public flags:  */
2687         if (!numtype)
2688             SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2689 #endif /* NV_PRESERVES_UV */
2690     }
2691     else  {
2692         if (isGV_with_GP(sv)) {
2693             glob_2number(MUTABLE_GV(sv));
2694             return 0.0;
2695         }
2696
2697         if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2698             report_uninit(sv);
2699         assert (SvTYPE(sv) >= SVt_NV);
2700         /* Typically the caller expects that sv_any is not NULL now.  */
2701         /* XXX Ilya implies that this is a bug in callers that assume this
2702            and ideally should be fixed.  */
2703         return 0.0;
2704     }
2705     DEBUG_c({
2706         STORE_NUMERIC_LOCAL_SET_STANDARD();
2707         PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" NVgf ")\n",
2708                       PTR2UV(sv), SvNVX(sv));
2709         RESTORE_NUMERIC_LOCAL();
2710     });
2711     return SvNVX(sv);
2712 }
2713
2714 /*
2715 =for apidoc sv_2num
2716
2717 Return an SV with the numeric value of the source SV, doing any necessary
2718 reference or overload conversion.  You must use the C<SvNUM(sv)> macro to
2719 access this function.
2720
2721 =cut
2722 */
2723
2724 SV *
2725 Perl_sv_2num(pTHX_ SV *const sv)
2726 {
2727     PERL_ARGS_ASSERT_SV_2NUM;
2728
2729     if (!SvROK(sv))
2730         return sv;
2731     if (SvAMAGIC(sv)) {
2732         SV * const tmpsv = AMG_CALLunary(sv, numer_amg);
2733         TAINT_IF(tmpsv && SvTAINTED(tmpsv));
2734         if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
2735             return sv_2num(tmpsv);
2736     }
2737     return sv_2mortal(newSVuv(PTR2UV(SvRV(sv))));
2738 }
2739
2740 /* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2741  * UV as a string towards the end of buf, and return pointers to start and
2742  * end of it.
2743  *
2744  * We assume that buf is at least TYPE_CHARS(UV) long.
2745  */
2746
2747 static char *
2748 S_uiv_2buf(char *const buf, const IV iv, UV uv, const int is_uv, char **const peob)
2749 {
2750     char *ptr = buf + TYPE_CHARS(UV);
2751     char * const ebuf = ptr;
2752     int sign;
2753
2754     PERL_ARGS_ASSERT_UIV_2BUF;
2755
2756     if (is_uv)
2757         sign = 0;
2758     else if (iv >= 0) {
2759         uv = iv;
2760         sign = 0;
2761     } else {
2762         uv = -iv;
2763         sign = 1;
2764     }
2765     do {
2766         *--ptr = '0' + (char)(uv % 10);
2767     } while (uv /= 10);
2768     if (sign)
2769         *--ptr = '-';
2770     *peob = ebuf;
2771     return ptr;
2772 }
2773
2774 /* Helper for sv_2pv_flags and sv_vcatpvfn_flags.  If the NV is an
2775  * infinity or a not-a-number, writes the appropriate strings to the
2776  * buffer, including a zero byte.  On success returns the written length,
2777  * excluding the zero byte, on failure returns zero. */
2778 STATIC size_t
2779 S_infnan_copy(NV nv, char* buffer, size_t maxlen) {
2780     if (maxlen < 4)
2781         return 0;
2782     else {
2783         char* s = buffer;
2784         if (Perl_isinf(nv)) {
2785             if (nv < 0) {
2786                 if (maxlen < 5)
2787                     return 0;
2788                 *s++ = '-';
2789             }
2790             *s++ = 'I';
2791             *s++ = 'n';
2792             *s++ = 'f';
2793         }
2794         else if (Perl_isnan(nv)) {
2795             *s++ = 'N';
2796             *s++ = 'a';
2797             *s++ = 'N';
2798             /* XXX output the payload mantissa bits as "(hhh...)" */
2799         }
2800         else
2801             return 0;
2802         *s++ = 0;
2803         return s - buffer - 1;
2804     }
2805 }
2806
2807 /*
2808 =for apidoc sv_2pv_flags
2809
2810 Returns a pointer to the string value of an SV, and sets *lp to its length.
2811 If flags includes SV_GMAGIC, does an mg_get() first.  Coerces sv to a
2812 string if necessary.  Normally invoked via the C<SvPV_flags> macro.
2813 C<sv_2pv()> and C<sv_2pv_nomg> usually end up here too.
2814
2815 =cut
2816 */
2817
2818 char *
2819 Perl_sv_2pv_flags(pTHX_ SV *const sv, STRLEN *const lp, const I32 flags)
2820 {
2821     char *s;
2822
2823     PERL_ARGS_ASSERT_SV_2PV_FLAGS;
2824
2825     assert (SvTYPE(sv) != SVt_PVAV && SvTYPE(sv) != SVt_PVHV
2826          && SvTYPE(sv) != SVt_PVFM);
2827     if (SvGMAGICAL(sv) && (flags & SV_GMAGIC))
2828         mg_get(sv);
2829     if (SvROK(sv)) {
2830         if (SvAMAGIC(sv)) {
2831             SV *tmpstr;
2832             if (flags & SV_SKIP_OVERLOAD)
2833                 return NULL;
2834             tmpstr = AMG_CALLunary(sv, string_amg);
2835             TAINT_IF(tmpstr && SvTAINTED(tmpstr));
2836             if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2837                 /* Unwrap this:  */
2838                 /* char *pv = lp ? SvPV(tmpstr, *lp) : SvPV_nolen(tmpstr);
2839                  */
2840
2841                 char *pv;
2842                 if ((SvFLAGS(tmpstr) & (SVf_POK)) == SVf_POK) {
2843                     if (flags & SV_CONST_RETURN) {
2844                         pv = (char *) SvPVX_const(tmpstr);
2845                     } else {
2846                         pv = (flags & SV_MUTABLE_RETURN)
2847                             ? SvPVX_mutable(tmpstr) : SvPVX(tmpstr);
2848                     }
2849                     if (lp)
2850                         *lp = SvCUR(tmpstr);
2851                 } else {
2852                     pv = sv_2pv_flags(tmpstr, lp, flags);
2853                 }
2854                 if (SvUTF8(tmpstr))
2855                     SvUTF8_on(sv);
2856                 else
2857                     SvUTF8_off(sv);
2858                 return pv;
2859             }
2860         }
2861         {
2862             STRLEN len;
2863             char *retval;
2864             char *buffer;
2865             SV *const referent = SvRV(sv);
2866
2867             if (!referent) {
2868                 len = 7;
2869                 retval = buffer = savepvn("NULLREF", len);
2870             } else if (SvTYPE(referent) == SVt_REGEXP &&
2871                        (!(PL_curcop->cop_hints & HINT_NO_AMAGIC) ||
2872                         amagic_is_enabled(string_amg))) {
2873                 REGEXP * const re = (REGEXP *)MUTABLE_PTR(referent);
2874
2875                 assert(re);
2876                         
2877                 /* If the regex is UTF-8 we want the containing scalar to
2878                    have an UTF-8 flag too */
2879                 if (RX_UTF8(re))
2880                     SvUTF8_on(sv);
2881                 else
2882                     SvUTF8_off(sv);     
2883
2884                 if (lp)
2885                     *lp = RX_WRAPLEN(re);
2886  
2887                 return RX_WRAPPED(re);
2888             } else {
2889                 const char *const typestr = sv_reftype(referent, 0);
2890                 const STRLEN typelen = strlen(typestr);
2891                 UV addr = PTR2UV(referent);
2892                 const char *stashname = NULL;
2893                 STRLEN stashnamelen = 0; /* hush, gcc */
2894                 const char *buffer_end;
2895
2896                 if (SvOBJECT(referent)) {
2897                     const HEK *const name = HvNAME_HEK(SvSTASH(referent));
2898
2899                     if (name) {
2900                         stashname = HEK_KEY(name);
2901                         stashnamelen = HEK_LEN(name);
2902
2903                         if (HEK_UTF8(name)) {
2904                             SvUTF8_on(sv);
2905                         } else {
2906                             SvUTF8_off(sv);
2907                         }
2908                     } else {
2909                         stashname = "__ANON__";
2910                         stashnamelen = 8;
2911                     }
2912                     len = stashnamelen + 1 /* = */ + typelen + 3 /* (0x */
2913                         + 2 * sizeof(UV) + 2 /* )\0 */;
2914                 } else {
2915                     len = typelen + 3 /* (0x */
2916                         + 2 * sizeof(UV) + 2 /* )\0 */;
2917                 }
2918
2919                 Newx(buffer, len, char);
2920                 buffer_end = retval = buffer + len;
2921
2922                 /* Working backwards  */
2923                 *--retval = '\0';
2924                 *--retval = ')';
2925                 do {
2926                     *--retval = PL_hexdigit[addr & 15];
2927                 } while (addr >>= 4);
2928                 *--retval = 'x';
2929                 *--retval = '0';
2930                 *--retval = '(';
2931
2932                 retval -= typelen;
2933                 memcpy(retval, typestr, typelen);
2934
2935                 if (stashname) {
2936                     *--retval = '=';
2937                     retval -= stashnamelen;
2938                     memcpy(retval, stashname, stashnamelen);
2939                 }
2940                 /* retval may not necessarily have reached the start of the
2941                    buffer here.  */
2942                 assert (retval >= buffer);
2943
2944                 len = buffer_end - retval - 1; /* -1 for that \0  */
2945             }
2946             if (lp)
2947                 *lp = len;
2948             SAVEFREEPV(buffer);
2949             return retval;
2950         }
2951     }
2952
2953     if (SvPOKp(sv)) {
2954         if (lp)
2955             *lp = SvCUR(sv);
2956         if (flags & SV_MUTABLE_RETURN)
2957             return SvPVX_mutable(sv);
2958         if (flags & SV_CONST_RETURN)
2959             return (char *)SvPVX_const(sv);
2960         return SvPVX(sv);
2961     }
2962
2963     if (SvIOK(sv)) {
2964         /* I'm assuming that if both IV and NV are equally valid then
2965            converting the IV is going to be more efficient */
2966         const U32 isUIOK = SvIsUV(sv);
2967         char buf[TYPE_CHARS(UV)];
2968         char *ebuf, *ptr;
2969         STRLEN len;
2970
2971         if (SvTYPE(sv) < SVt_PVIV)
2972             sv_upgrade(sv, SVt_PVIV);
2973         ptr = uiv_2buf(buf, SvIVX(sv), SvUVX(sv), isUIOK, &ebuf);
2974         len = ebuf - ptr;
2975         /* inlined from sv_setpvn */
2976         s = SvGROW_mutable(sv, len + 1);
2977         Move(ptr, s, len, char);
2978         s += len;
2979         *s = '\0';
2980         SvPOK_on(sv);
2981     }
2982     else if (SvNOK(sv)) {
2983         if (SvTYPE(sv) < SVt_PVNV)
2984             sv_upgrade(sv, SVt_PVNV);
2985         if (SvNVX(sv) == 0.0) {
2986             s = SvGROW_mutable(sv, 2);
2987             *s++ = '0';
2988             *s = '\0';
2989         } else {
2990             STRLEN len;
2991             /* The +20 is pure guesswork.  Configure test needed. --jhi */
2992             s = SvGROW_mutable(sv, NV_DIG + 20);
2993
2994             len = S_infnan_copy(SvNVX(sv), s, 5);
2995             if (len > 0)
2996                 s += len;
2997             else {
2998                 dSAVE_ERRNO;
2999                 /* some Xenix systems wipe out errno here */
3000
3001 #ifndef USE_LOCALE_NUMERIC
3002                 PERL_UNUSED_RESULT(Gconvert(SvNVX(sv), NV_DIG, 0, s));
3003                 SvPOK_on(sv);
3004 #else
3005                 {
3006                     DECLARE_STORE_LC_NUMERIC_SET_TO_NEEDED();
3007                     PERL_UNUSED_RESULT(Gconvert(SvNVX(sv), NV_DIG, 0, s));
3008
3009                     /* If the radix character is UTF-8, and actually is in the
3010                      * output, turn on the UTF-8 flag for the scalar */
3011                     if (PL_numeric_local
3012                         && PL_numeric_radix_sv && SvUTF8(PL_numeric_radix_sv)
3013                         && instr(s, SvPVX_const(PL_numeric_radix_sv)))
3014                         {
3015                             SvUTF8_on(sv);
3016                         }
3017                     RESTORE_LC_NUMERIC();
3018                 }
3019
3020                 /* We don't call SvPOK_on(), because it may come to
3021                  * pass that the locale changes so that the
3022                  * stringification we just did is no longer correct.  We
3023                  * will have to re-stringify every time it is needed */
3024 #endif
3025                 RESTORE_ERRNO;
3026             }
3027             while (*s) s++;
3028         }
3029     }
3030     else if (isGV_with_GP(sv)) {
3031         GV *const gv = MUTABLE_GV(sv);
3032         SV *const buffer = sv_newmortal();
3033
3034         gv_efullname3(buffer, gv, "*");
3035
3036         assert(SvPOK(buffer));
3037         if (SvUTF8(buffer))
3038             SvUTF8_on(sv);
3039         if (lp)
3040             *lp = SvCUR(buffer);
3041         return SvPVX(buffer);
3042     }
3043     else if (isREGEXP(sv)) {
3044         if (lp) *lp = RX_WRAPLEN((REGEXP *)sv);
3045         return RX_WRAPPED((REGEXP *)sv);
3046     }
3047     else {
3048         if (lp)
3049             *lp = 0;
3050         if (flags & SV_UNDEF_RETURNS_NULL)
3051             return NULL;
3052         if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
3053             report_uninit(sv);
3054         /* Typically the caller expects that sv_any is not NULL now.  */
3055         if (!SvREADONLY(sv) && SvTYPE(sv) < SVt_PV)
3056             sv_upgrade(sv, SVt_PV);
3057         return (char *)"";
3058     }
3059
3060     {
3061         const STRLEN len = s - SvPVX_const(sv);
3062         if (lp) 
3063             *lp = len;
3064         SvCUR_set(sv, len);
3065     }
3066     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
3067                           PTR2UV(sv),SvPVX_const(sv)));
3068     if (flags & SV_CONST_RETURN)
3069         return (char *)SvPVX_const(sv);
3070     if (flags & SV_MUTABLE_RETURN)
3071         return SvPVX_mutable(sv);
3072     return SvPVX(sv);
3073 }
3074
3075 /*
3076 =for apidoc sv_copypv
3077
3078 Copies a stringified representation of the source SV into the
3079 destination SV.  Automatically performs any necessary mg_get and
3080 coercion of numeric values into strings.  Guaranteed to preserve
3081 UTF8 flag even from overloaded objects.  Similar in nature to
3082 sv_2pv[_flags] but operates directly on an SV instead of just the
3083 string.  Mostly uses sv_2pv_flags to do its work, except when that
3084 would lose the UTF-8'ness of the PV.
3085
3086 =for apidoc sv_copypv_nomg
3087
3088 Like sv_copypv, but doesn't invoke get magic first.
3089
3090 =for apidoc sv_copypv_flags
3091
3092 Implementation of sv_copypv and sv_copypv_nomg.  Calls get magic iff flags
3093 include SV_GMAGIC.
3094
3095 =cut
3096 */
3097
3098 void
3099 Perl_sv_copypv(pTHX_ SV *const dsv, SV *const ssv)
3100 {
3101     PERL_ARGS_ASSERT_SV_COPYPV;
3102
3103     sv_copypv_flags(dsv, ssv, 0);
3104 }
3105
3106 void
3107 Perl_sv_copypv_flags(pTHX_ SV *const dsv, SV *const ssv, const I32 flags)
3108 {
3109     STRLEN len;
3110     const char *s;
3111
3112     PERL_ARGS_ASSERT_SV_COPYPV_FLAGS;
3113
3114     if ((flags & SV_GMAGIC) && SvGMAGICAL(ssv))
3115         mg_get(ssv);
3116     s = SvPV_nomg_const(ssv,len);
3117     sv_setpvn(dsv,s,len);
3118     if (SvUTF8(ssv))
3119         SvUTF8_on(dsv);
3120     else
3121         SvUTF8_off(dsv);
3122 }
3123
3124 /*
3125 =for apidoc sv_2pvbyte
3126
3127 Return a pointer to the byte-encoded representation of the SV, and set *lp
3128 to its length.  May cause the SV to be downgraded from UTF-8 as a
3129 side-effect.
3130
3131 Usually accessed via the C<SvPVbyte> macro.
3132
3133 =cut
3134 */
3135
3136 char *
3137 Perl_sv_2pvbyte(pTHX_ SV *sv, STRLEN *const lp)
3138 {
3139     PERL_ARGS_ASSERT_SV_2PVBYTE;
3140
3141     SvGETMAGIC(sv);
3142     if (((SvREADONLY(sv) || SvFAKE(sv)) && !SvIsCOW(sv))
3143      || isGV_with_GP(sv) || SvROK(sv)) {
3144         SV *sv2 = sv_newmortal();
3145         sv_copypv_nomg(sv2,sv);
3146         sv = sv2;
3147     }
3148     sv_utf8_downgrade(sv,0);
3149     return lp ? SvPV_nomg(sv,*lp) : SvPV_nomg_nolen(sv);
3150 }
3151
3152 /*
3153 =for apidoc sv_2pvutf8
3154
3155 Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
3156 to its length.  May cause the SV to be upgraded to UTF-8 as a side-effect.
3157
3158 Usually accessed via the C<SvPVutf8> macro.
3159
3160 =cut
3161 */
3162
3163 char *
3164 Perl_sv_2pvutf8(pTHX_ SV *sv, STRLEN *const lp)
3165 {
3166     PERL_ARGS_ASSERT_SV_2PVUTF8;
3167
3168     if (((SvREADONLY(sv) || SvFAKE(sv)) && !SvIsCOW(sv))
3169      || isGV_with_GP(sv) || SvROK(sv))
3170         sv = sv_mortalcopy(sv);
3171     else
3172         SvGETMAGIC(sv);
3173     sv_utf8_upgrade_nomg(sv);
3174     return lp ? SvPV_nomg(sv,*lp) : SvPV_nomg_nolen(sv);
3175 }
3176
3177
3178 /*
3179 =for apidoc sv_2bool
3180
3181 This macro is only used by sv_true() or its macro equivalent, and only if
3182 the latter's argument is neither SvPOK, SvIOK nor SvNOK.
3183 It calls sv_2bool_flags with the SV_GMAGIC flag.
3184
3185 =for apidoc sv_2bool_flags
3186
3187 This function is only used by sv_true() and friends,  and only if
3188 the latter's argument is neither SvPOK, SvIOK nor SvNOK.  If the flags
3189 contain SV_GMAGIC, then it does an mg_get() first.
3190
3191
3192 =cut
3193 */
3194
3195 bool
3196 Perl_sv_2bool_flags(pTHX_ SV *sv, I32 flags)
3197 {
3198     PERL_ARGS_ASSERT_SV_2BOOL_FLAGS;
3199
3200     restart:
3201     if(flags & SV_GMAGIC) SvGETMAGIC(sv);
3202
3203     if (!SvOK(sv))
3204         return 0;
3205     if (SvROK(sv)) {
3206         if (SvAMAGIC(sv)) {
3207             SV * const tmpsv = AMG_CALLunary(sv, bool__amg);
3208             if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv)))) {
3209                 bool svb;
3210                 sv = tmpsv;
3211                 if(SvGMAGICAL(sv)) {
3212                     flags = SV_GMAGIC;
3213                     goto restart; /* call sv_2bool */
3214                 }
3215                 /* expanded SvTRUE_common(sv, (flags = 0, goto restart)) */
3216                 else if(!SvOK(sv)) {
3217                     svb = 0;
3218                 }
3219                 else if(SvPOK(sv)) {
3220                     svb = SvPVXtrue(sv);
3221                 }
3222                 else if((SvFLAGS(sv) & (SVf_IOK|SVf_NOK))) {
3223                     svb = (SvIOK(sv) && SvIVX(sv) != 0)
3224                         || (SvNOK(sv) && SvNVX(sv) != 0.0);
3225                 }
3226                 else {
3227                     flags = 0;
3228                     goto restart; /* call sv_2bool_nomg */
3229                 }
3230                 return cBOOL(svb);
3231             }
3232         }
3233         return SvRV(sv) != 0;
3234     }
3235     if (isREGEXP(sv))
3236         return
3237           RX_WRAPLEN(sv) > 1 || (RX_WRAPLEN(sv) && *RX_WRAPPED(sv) != '0');
3238     return SvTRUE_common(sv, isGV_with_GP(sv) ? 1 : 0);
3239 }
3240
3241 /*
3242 =for apidoc sv_utf8_upgrade
3243
3244 Converts the PV of an SV to its UTF-8-encoded form.
3245 Forces the SV to string form if it is not already.
3246 Will C<mg_get> on C<sv> if appropriate.
3247 Always sets the SvUTF8 flag to avoid future validity checks even
3248 if the whole string is the same in UTF-8 as not.
3249 Returns the number of bytes in the converted string
3250
3251 This is not a general purpose byte encoding to Unicode interface:
3252 use the Encode extension for that.
3253
3254 =for apidoc sv_utf8_upgrade_nomg
3255
3256 Like sv_utf8_upgrade, but doesn't do magic on C<sv>.
3257
3258 =for apidoc sv_utf8_upgrade_flags
3259
3260 Converts the PV of an SV to its UTF-8-encoded form.
3261 Forces the SV to string form if it is not already.
3262 Always sets the SvUTF8 flag to avoid future validity checks even
3263 if all the bytes are invariant in UTF-8.
3264 If C<flags> has C<SV_GMAGIC> bit set,
3265 will C<mg_get> on C<sv> if appropriate, else not.
3266
3267 If C<flags> has SV_FORCE_UTF8_UPGRADE set, this function assumes that the PV
3268 will expand when converted to UTF-8, and skips the extra work of checking for
3269 that.  Typically this flag is used by a routine that has already parsed the
3270 string and found such characters, and passes this information on so that the
3271 work doesn't have to be repeated.
3272
3273 Returns the number of bytes in the converted string.
3274
3275 This is not a general purpose byte encoding to Unicode interface:
3276 use the Encode extension for that.
3277
3278 =for apidoc sv_utf8_upgrade_flags_grow
3279
3280 Like sv_utf8_upgrade_flags, but has an additional parameter C<extra>, which is
3281 the number of unused bytes the string of 'sv' is guaranteed to have free after
3282 it upon return.  This allows the caller to reserve extra space that it intends
3283 to fill, to avoid extra grows.
3284
3285 C<sv_utf8_upgrade>, C<sv_utf8_upgrade_nomg>, and C<sv_utf8_upgrade_flags>
3286 are implemented in terms of this function.
3287
3288 Returns the number of bytes in the converted string (not including the spares).
3289
3290 =cut
3291
3292 (One might think that the calling routine could pass in the position of the
3293 first variant character when it has set SV_FORCE_UTF8_UPGRADE, so it wouldn't
3294 have to be found again.  But that is not the case, because typically when the
3295 caller is likely to use this flag, it won't be calling this routine unless it
3296 finds something that won't fit into a byte.  Otherwise it tries to not upgrade
3297 and just use bytes.  But some things that do fit into a byte are variants in
3298 utf8, and the caller may not have been keeping track of these.)
3299
3300 If the routine itself changes the string, it adds a trailing C<NUL>.  Such a
3301 C<NUL> isn't guaranteed due to having other routines do the work in some input
3302 cases, or if the input is already flagged as being in utf8.
3303
3304 The speed of this could perhaps be improved for many cases if someone wanted to
3305 write a fast function that counts the number of variant characters in a string,
3306 especially if it could return the position of the first one.
3307
3308 */
3309
3310 STRLEN
3311 Perl_sv_utf8_upgrade_flags_grow(pTHX_ SV *const sv, const I32 flags, STRLEN extra)
3312 {
3313     PERL_ARGS_ASSERT_SV_UTF8_UPGRADE_FLAGS_GROW;
3314
3315     if (sv == &PL_sv_undef)
3316         return 0;
3317     if (!SvPOK_nog(sv)) {
3318         STRLEN len = 0;
3319         if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
3320             (void) sv_2pv_flags(sv,&len, flags);
3321             if (SvUTF8(sv)) {
3322                 if (extra) SvGROW(sv, SvCUR(sv) + extra);
3323                 return len;
3324             }
3325         } else {
3326             (void) SvPV_force_flags(sv,len,flags & SV_GMAGIC);
3327         }
3328     }
3329
3330     if (SvUTF8(sv)) {
3331         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3332         return SvCUR(sv);
3333     }
3334
3335     if (SvIsCOW(sv)) {
3336         S_sv_uncow(aTHX_ sv, 0);
3337     }
3338
3339     if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING)) {
3340         sv_recode_to_utf8(sv, PL_encoding);
3341         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3342         return SvCUR(sv);
3343     }
3344
3345     if (SvCUR(sv) == 0) {
3346         if (extra) SvGROW(sv, extra);
3347     } else { /* Assume Latin-1/EBCDIC */
3348         /* This function could be much more efficient if we
3349          * had a FLAG in SVs to signal if there are any variant
3350          * chars in the PV.  Given that there isn't such a flag
3351          * make the loop as fast as possible (although there are certainly ways
3352          * to speed this up, eg. through vectorization) */
3353         U8 * s = (U8 *) SvPVX_const(sv);
3354         U8 * e = (U8 *) SvEND(sv);
3355         U8 *t = s;
3356         STRLEN two_byte_count = 0;
3357         
3358         if (flags & SV_FORCE_UTF8_UPGRADE) goto must_be_utf8;
3359
3360         /* See if really will need to convert to utf8.  We mustn't rely on our
3361          * incoming SV being well formed and having a trailing '\0', as certain
3362          * code in pp_formline can send us partially built SVs. */
3363
3364         while (t < e) {
3365             const U8 ch = *t++;
3366             if (NATIVE_BYTE_IS_INVARIANT(ch)) continue;
3367
3368             t--;    /* t already incremented; re-point to first variant */
3369             two_byte_count = 1;
3370             goto must_be_utf8;
3371         }
3372
3373         /* utf8 conversion not needed because all are invariants.  Mark as
3374          * UTF-8 even if no variant - saves scanning loop */
3375         SvUTF8_on(sv);
3376         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3377         return SvCUR(sv);
3378
3379 must_be_utf8:
3380
3381         /* Here, the string should be converted to utf8, either because of an
3382          * input flag (two_byte_count = 0), or because a character that
3383          * requires 2 bytes was found (two_byte_count = 1).  t points either to
3384          * the beginning of the string (if we didn't examine anything), or to
3385          * the first variant.  In either case, everything from s to t - 1 will
3386          * occupy only 1 byte each on output.
3387          *
3388          * There are two main ways to convert.  One is to create a new string
3389          * and go through the input starting from the beginning, appending each
3390          * converted value onto the new string as we go along.  It's probably
3391          * best to allocate enough space in the string for the worst possible
3392          * case rather than possibly running out of space and having to
3393          * reallocate and then copy what we've done so far.  Since everything
3394          * from s to t - 1 is invariant, the destination can be initialized
3395          * with these using a fast memory copy
3396          *
3397          * The other way is to figure out exactly how big the string should be
3398          * by parsing the entire input.  Then you don't have to make it big
3399          * enough to handle the worst possible case, and more importantly, if
3400          * the string you already have is large enough, you don't have to
3401          * allocate a new string, you can copy the last character in the input
3402          * string to the final position(s) that will be occupied by the
3403          * converted string and go backwards, stopping at t, since everything
3404          * before that is invariant.
3405          *
3406          * There are advantages and disadvantages to each method.
3407          *
3408          * In the first method, we can allocate a new string, do the memory
3409          * copy from the s to t - 1, and then proceed through the rest of the
3410          * string byte-by-byte.
3411          *
3412          * In the second method, we proceed through the rest of the input
3413          * string just calculating how big the converted string will be.  Then
3414          * there are two cases:
3415          *  1)  if the string has enough extra space to handle the converted
3416          *      value.  We go backwards through the string, converting until we
3417          *      get to the position we are at now, and then stop.  If this
3418          *      position is far enough along in the string, this method is
3419          *      faster than the other method.  If the memory copy were the same
3420          *      speed as the byte-by-byte loop, that position would be about
3421          *      half-way, as at the half-way mark, parsing to the end and back
3422          *      is one complete string's parse, the same amount as starting
3423          *      over and going all the way through.  Actually, it would be
3424          *      somewhat less than half-way, as it's faster to just count bytes
3425          *      than to also copy, and we don't have the overhead of allocating
3426          *      a new string, changing the scalar to use it, and freeing the
3427          *      existing one.  But if the memory copy is fast, the break-even
3428          *      point is somewhere after half way.  The counting loop could be
3429          *      sped up by vectorization, etc, to move the break-even point
3430          *      further towards the beginning.
3431          *  2)  if the string doesn't have enough space to handle the converted
3432          *      value.  A new string will have to be allocated, and one might
3433          *      as well, given that, start from the beginning doing the first
3434          *      method.  We've spent extra time parsing the string and in
3435          *      exchange all we've gotten is that we know precisely how big to
3436          *      make the new one.  Perl is more optimized for time than space,
3437          *      so this case is a loser.
3438          * So what I've decided to do is not use the 2nd method unless it is
3439          * guaranteed that a new string won't have to be allocated, assuming
3440          * the worst case.  I also decided not to put any more conditions on it
3441          * than this, for now.  It seems likely that, since the worst case is
3442          * twice as big as the unknown portion of the string (plus 1), we won't
3443          * be guaranteed enough space, causing us to go to the first method,
3444          * unless the string is short, or the first variant character is near
3445          * the end of it.  In either of these cases, it seems best to use the
3446          * 2nd method.  The only circumstance I can think of where this would
3447          * be really slower is if the string had once had much more data in it
3448          * than it does now, but there is still a substantial amount in it  */
3449
3450         {
3451             STRLEN invariant_head = t - s;
3452             STRLEN size = invariant_head + (e - t) * 2 + 1 + extra;
3453             if (SvLEN(sv) < size) {
3454
3455                 /* Here, have decided to allocate a new string */
3456
3457                 U8 *dst;
3458                 U8 *d;
3459
3460                 Newx(dst, size, U8);
3461
3462                 /* If no known invariants at the beginning of the input string,
3463                  * set so starts from there.  Otherwise, can use memory copy to
3464                  * get up to where we are now, and then start from here */
3465
3466                 if (invariant_head == 0) {
3467                     d = dst;
3468                 } else {
3469                     Copy(s, dst, invariant_head, char);
3470                     d = dst + invariant_head;
3471                 }
3472
3473                 while (t < e) {
3474                     append_utf8_from_native_byte(*t, &d);
3475                     t++;
3476                 }
3477                 *d = '\0';
3478                 SvPV_free(sv); /* No longer using pre-existing string */
3479                 SvPV_set(sv, (char*)dst);
3480                 SvCUR_set(sv, d - dst);
3481                 SvLEN_set(sv, size);
3482             } else {
3483
3484                 /* Here, have decided to get the exact size of the string.
3485                  * Currently this happens only when we know that there is
3486                  * guaranteed enough space to fit the converted string, so
3487                  * don't have to worry about growing.  If two_byte_count is 0,
3488                  * then t points to the first byte of the string which hasn't
3489                  * been examined yet.  Otherwise two_byte_count is 1, and t
3490                  * points to the first byte in the string that will expand to
3491                  * two.  Depending on this, start examining at t or 1 after t.
3492                  * */
3493
3494                 U8 *d = t + two_byte_count;
3495
3496
3497                 /* Count up the remaining bytes that expand to two */
3498
3499                 while (d < e) {
3500                     const U8 chr = *d++;
3501                     if (! NATIVE_BYTE_IS_INVARIANT(chr)) two_byte_count++;
3502                 }
3503
3504                 /* The string will expand by just the number of bytes that
3505                  * occupy two positions.  But we are one afterwards because of
3506                  * the increment just above.  This is the place to put the
3507                  * trailing NUL, and to set the length before we decrement */
3508
3509                 d += two_byte_count;
3510                 SvCUR_set(sv, d - s);
3511                 *d-- = '\0';
3512
3513
3514                 /* Having decremented d, it points to the position to put the
3515                  * very last byte of the expanded string.  Go backwards through
3516                  * the string, copying and expanding as we go, stopping when we
3517                  * get to the part that is invariant the rest of the way down */
3518
3519                 e--;
3520                 while (e >= t) {
3521                     if (NATIVE_BYTE_IS_INVARIANT(*e)) {
3522                         *d-- = *e;
3523                     } else {
3524                         *d-- = UTF8_EIGHT_BIT_LO(*e);
3525                         *d-- = UTF8_EIGHT_BIT_HI(*e);
3526                     }
3527                     e--;
3528                 }
3529             }
3530
3531             if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3532                 /* Update pos. We do it at the end rather than during
3533                  * the upgrade, to avoid slowing down the common case
3534                  * (upgrade without pos).
3535                  * pos can be stored as either bytes or characters.  Since
3536                  * this was previously a byte string we can just turn off
3537                  * the bytes flag. */
3538                 MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3539                 if (mg) {
3540                     mg->mg_flags &= ~MGf_BYTES;
3541                 }
3542                 if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3543                     magic_setutf8(sv,mg); /* clear UTF8 cache */
3544             }
3545         }
3546     }
3547
3548     /* Mark as UTF-8 even if no variant - saves scanning loop */
3549     SvUTF8_on(sv);
3550     return SvCUR(sv);
3551 }
3552
3553 /*
3554 =for apidoc sv_utf8_downgrade
3555
3556 Attempts to convert the PV of an SV from characters to bytes.
3557 If the PV contains a character that cannot fit
3558 in a byte, this conversion will fail;
3559 in this case, either returns false or, if C<fail_ok> is not
3560 true, croaks.
3561
3562 This is not a general purpose Unicode to byte encoding interface:
3563 use the Encode extension for that.
3564
3565 =cut
3566 */
3567
3568 bool
3569 Perl_sv_utf8_downgrade(pTHX_ SV *const sv, const bool fail_ok)
3570 {
3571     PERL_ARGS_ASSERT_SV_UTF8_DOWNGRADE;
3572
3573     if (SvPOKp(sv) && SvUTF8(sv)) {
3574         if (SvCUR(sv)) {
3575             U8 *s;
3576             STRLEN len;
3577             int mg_flags = SV_GMAGIC;
3578
3579             if (SvIsCOW(sv)) {
3580                 S_sv_uncow(aTHX_ sv, 0);
3581             }
3582             if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3583                 /* update pos */
3584                 MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3585                 if (mg && mg->mg_len > 0 && mg->mg_flags & MGf_BYTES) {
3586                         mg->mg_len = sv_pos_b2u_flags(sv, mg->mg_len,
3587                                                 SV_GMAGIC|SV_CONST_RETURN);
3588                         mg_flags = 0; /* sv_pos_b2u does get magic */
3589                 }
3590                 if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3591                     magic_setutf8(sv,mg); /* clear UTF8 cache */
3592
3593             }
3594             s = (U8 *) SvPV_flags(sv, len, mg_flags);
3595
3596             if (!utf8_to_bytes(s, &len)) {
3597                 if (fail_ok)
3598                     return FALSE;
3599                 else {
3600                     if (PL_op)
3601                         Perl_croak(aTHX_ "Wide character in %s",
3602                                    OP_DESC(PL_op));
3603                     else
3604                         Perl_croak(aTHX_ "Wide character");
3605                 }
3606             }
3607             SvCUR_set(sv, len);
3608         }
3609     }
3610     SvUTF8_off(sv);
3611     return TRUE;
3612 }
3613
3614 /*
3615 =for apidoc sv_utf8_encode
3616
3617 Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3618 flag off so that it looks like octets again.
3619
3620 =cut
3621 */
3622
3623 void
3624 Perl_sv_utf8_encode(pTHX_ SV *const sv)
3625 {
3626     PERL_ARGS_ASSERT_SV_UTF8_ENCODE;
3627
3628     if (SvREADONLY(sv)) {
3629         sv_force_normal_flags(sv, 0);
3630     }
3631     (void) sv_utf8_upgrade(sv);
3632     SvUTF8_off(sv);
3633 }
3634
3635 /*
3636 =for apidoc sv_utf8_decode
3637
3638 If the PV of the SV is an octet sequence in UTF-8
3639 and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3640 so that it looks like a character.  If the PV contains only single-byte
3641 characters, the C<SvUTF8> flag stays off.
3642 Scans PV for validity and returns false if the PV is invalid UTF-8.
3643
3644 =cut
3645 */
3646
3647 bool
3648 Perl_sv_utf8_decode(pTHX_ SV *const sv)
3649 {
3650     PERL_ARGS_ASSERT_SV_UTF8_DECODE;
3651
3652     if (SvPOKp(sv)) {
3653         const U8 *start, *c;
3654         const U8 *e;
3655
3656         /* The octets may have got themselves encoded - get them back as
3657          * bytes
3658          */
3659         if (!sv_utf8_downgrade(sv, TRUE))
3660             return FALSE;
3661
3662         /* it is actually just a matter of turning the utf8 flag on, but
3663          * we want to make sure everything inside is valid utf8 first.
3664          */
3665         c = start = (const U8 *) SvPVX_const(sv);
3666         if (!is_utf8_string(c, SvCUR(sv)))
3667             return FALSE;
3668         e = (const U8 *) SvEND(sv);
3669         while (c < e) {
3670             const U8 ch = *c++;
3671             if (!UTF8_IS_INVARIANT(ch)) {
3672                 SvUTF8_on(sv);
3673                 break;
3674             }
3675         }
3676         if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3677             /* XXX Is this dead code?  XS_utf8_decode calls SvSETMAGIC
3678                    after this, clearing pos.  Does anything on CPAN
3679                    need this? */
3680             /* adjust pos to the start of a UTF8 char sequence */
3681             MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3682             if (mg) {
3683                 I32 pos = mg->mg_len;
3684                 if (pos > 0) {
3685                     for (c = start + pos; c > start; c--) {
3686                         if (UTF8_IS_START(*c))
3687                             break;
3688                     }
3689                     mg->mg_len  = c - start;
3690                 }
3691             }
3692             if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3693                 magic_setutf8(sv,mg); /* clear UTF8 cache */
3694         }
3695     }
3696     return TRUE;
3697 }
3698
3699 /*
3700 =for apidoc sv_setsv
3701
3702 Copies the contents of the source SV C<ssv> into the destination SV
3703 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3704 function if the source SV needs to be reused.  Does not handle 'set' magic on
3705 destination SV.  Calls 'get' magic on source SV.  Loosely speaking, it
3706 performs a copy-by-value, obliterating any previous content of the
3707 destination.
3708
3709 You probably want to use one of the assortment of wrappers, such as
3710 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3711 C<SvSetMagicSV_nosteal>.
3712
3713 =for apidoc sv_setsv_flags
3714
3715 Copies the contents of the source SV C<ssv> into the destination SV
3716 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3717 function if the source SV needs to be reused.  Does not handle 'set' magic.
3718 Loosely speaking, it performs a copy-by-value, obliterating any previous
3719 content of the destination.
3720 If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
3721 C<ssv> if appropriate, else not.  If the C<flags>
3722 parameter has the C<SV_NOSTEAL> bit set then the
3723 buffers of temps will not be stolen.  <sv_setsv>
3724 and C<sv_setsv_nomg> are implemented in terms of this function.
3725
3726 You probably want to use one of the assortment of wrappers, such as
3727 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3728 C<SvSetMagicSV_nosteal>.
3729
3730 This is the primary function for copying scalars, and most other
3731 copy-ish functions and macros use this underneath.
3732
3733 =cut
3734 */
3735
3736 static void
3737 S_glob_assign_glob(pTHX_ SV *const dstr, SV *const sstr, const int dtype)
3738 {
3739     I32 mro_changes = 0; /* 1 = method, 2 = isa, 3 = recursive isa */
3740     HV *old_stash = NULL;
3741
3742     PERL_ARGS_ASSERT_GLOB_ASSIGN_GLOB;
3743
3744     if (dtype != SVt_PVGV && !isGV_with_GP(dstr)) {
3745         const char * const name = GvNAME(sstr);
3746         const STRLEN len = GvNAMELEN(sstr);
3747         {
3748             if (dtype >= SVt_PV) {
3749                 SvPV_free(dstr);
3750                 SvPV_set(dstr, 0);
3751                 SvLEN_set(dstr, 0);
3752                 SvCUR_set(dstr, 0);
3753             }
3754             SvUPGRADE(dstr, SVt_PVGV);
3755             (void)SvOK_off(dstr);
3756             isGV_with_GP_on(dstr);
3757         }
3758         GvSTASH(dstr) = GvSTASH(sstr);
3759         if (GvSTASH(dstr))
3760             Perl_sv_add_backref(aTHX_ MUTABLE_SV(GvSTASH(dstr)), dstr);
3761         gv_name_set(MUTABLE_GV(dstr), name, len,
3762                         GV_ADD | (GvNAMEUTF8(sstr) ? SVf_UTF8 : 0 ));
3763         SvFAKE_on(dstr);        /* can coerce to non-glob */
3764     }
3765
3766     if(GvGP(MUTABLE_GV(sstr))) {
3767         /* If source has method cache entry, clear it */
3768         if(GvCVGEN(sstr)) {
3769             SvREFCNT_dec(GvCV(sstr));
3770             GvCV_set(sstr, NULL);
3771             GvCVGEN(sstr) = 0;
3772         }
3773         /* If source has a real method, then a method is
3774            going to change */
3775         else if(
3776          GvCV((const GV *)sstr) && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3777         ) {
3778             mro_changes = 1;
3779         }
3780     }
3781
3782     /* If dest already had a real method, that's a change as well */
3783     if(
3784         !mro_changes && GvGP(MUTABLE_GV(dstr)) && GvCVu((const GV *)dstr)
3785      && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3786     ) {
3787         mro_changes = 1;
3788     }
3789
3790     /* We don't need to check the name of the destination if it was not a
3791        glob to begin with. */
3792     if(dtype == SVt_PVGV) {
3793         const char * const name = GvNAME((const GV *)dstr);
3794         if(
3795             strEQ(name,"ISA")
3796          /* The stash may have been detached from the symbol table, so
3797             check its name. */
3798          && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3799         )
3800             mro_changes = 2;
3801         else {
3802             const STRLEN len = GvNAMELEN(dstr);
3803             if ((len > 1 && name[len-2] == ':' && name[len-1] == ':')
3804              || (len == 1 && name[0] == ':')) {
3805                 mro_changes = 3;
3806
3807                 /* Set aside the old stash, so we can reset isa caches on
3808                    its subclasses. */
3809                 if((old_stash = GvHV(dstr)))
3810                     /* Make sure we do not lose it early. */
3811                     SvREFCNT_inc_simple_void_NN(
3812                      sv_2mortal((SV *)old_stash)
3813                     );
3814             }
3815         }
3816
3817         SvREFCNT_inc_simple_void_NN(sv_2mortal(dstr));
3818     }
3819
3820     gp_free(MUTABLE_GV(dstr));
3821     GvINTRO_off(dstr);          /* one-shot flag */
3822     GvGP_set(dstr, gp_ref(GvGP(sstr)));
3823     if (SvTAINTED(sstr))
3824         SvTAINT(dstr);
3825     if (GvIMPORTED(dstr) != GVf_IMPORTED
3826         && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3827         {
3828             GvIMPORTED_on(dstr);
3829         }
3830     GvMULTI_on(dstr);
3831     if(mro_changes == 2) {
3832       if (GvAV((const GV *)sstr)) {
3833         MAGIC *mg;
3834         SV * const sref = (SV *)GvAV((const GV *)dstr);
3835         if (SvSMAGICAL(sref) && (mg = mg_find(sref, PERL_MAGIC_isa))) {
3836             if (SvTYPE(mg->mg_obj) != SVt_PVAV) {
3837                 AV * const ary = newAV();
3838                 av_push(ary, mg->mg_obj); /* takes the refcount */
3839                 mg->mg_obj = (SV *)ary;
3840             }
3841             av_push((AV *)mg->mg_obj, SvREFCNT_inc_simple_NN(dstr));
3842         }
3843         else sv_magic(sref, dstr, PERL_MAGIC_isa, NULL, 0);
3844       }
3845       mro_isa_changed_in(GvSTASH(dstr));
3846     }
3847     else if(mro_changes == 3) {
3848         HV * const stash = GvHV(dstr);
3849         if(old_stash ? (HV *)HvENAME_get(old_stash) : stash)
3850             mro_package_moved(
3851                 stash, old_stash,
3852                 (GV *)dstr, 0
3853             );
3854     }
3855     else if(mro_changes) mro_method_changed_in(GvSTASH(dstr));
3856     if (GvIO(dstr) && dtype == SVt_PVGV) {
3857         DEBUG_o(Perl_deb(aTHX_
3858                         "glob_assign_glob clearing PL_stashcache\n"));
3859         /* It's a cache. It will rebuild itself quite happily.
3860            It's a lot of effort to work out exactly which key (or keys)
3861            might be invalidated by the creation of the this file handle.
3862          */
3863         hv_clear(PL_stashcache);
3864     }
3865     return;
3866 }
3867
3868 static void
3869 S_glob_assign_ref(pTHX_ SV *const dstr, SV *const sstr)
3870 {
3871     SV * const sref = SvRV(sstr);
3872     SV *dref;
3873     const int intro = GvINTRO(dstr);
3874     SV **location;
3875     U8 import_flag = 0;
3876     const U32 stype = SvTYPE(sref);
3877
3878     PERL_ARGS_ASSERT_GLOB_ASSIGN_REF;
3879
3880     if (intro) {
3881         GvINTRO_off(dstr);      /* one-shot flag */
3882         GvLINE(dstr) = CopLINE(PL_curcop);
3883         GvEGV(dstr) = MUTABLE_GV(dstr);
3884     }
3885     GvMULTI_on(dstr);
3886     switch (stype) {
3887     case SVt_PVCV:
3888         location = (SV **) &(GvGP(dstr)->gp_cv); /* XXX bypassing GvCV_set */
3889         import_flag = GVf_IMPORTED_CV;
3890         goto common;
3891     case SVt_PVHV:
3892         location = (SV **) &GvHV(dstr);
3893         import_flag = GVf_IMPORTED_HV;
3894         goto common;
3895     case SVt_PVAV:
3896         location = (SV **) &GvAV(dstr);
3897         import_flag = GVf_IMPORTED_AV;
3898         goto common;
3899     case SVt_PVIO:
3900         location = (SV **) &GvIOp(dstr);
3901         goto common;
3902     case SVt_PVFM:
3903         location = (SV **) &GvFORM(dstr);
3904         goto common;
3905     default:
3906         location = &GvSV(dstr);
3907         import_flag = GVf_IMPORTED_SV;
3908     common:
3909         if (intro) {
3910             if (stype == SVt_PVCV) {
3911                 /*if (GvCVGEN(dstr) && (GvCV(dstr) != (const CV *)sref || GvCVGEN(dstr))) {*/
3912                 if (GvCVGEN(dstr)) {
3913                     SvREFCNT_dec(GvCV(dstr));
3914                     GvCV_set(dstr, NULL);
3915                     GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3916                 }
3917             }
3918             /* SAVEt_GVSLOT takes more room on the savestack and has more
3919                overhead in leave_scope than SAVEt_GENERIC_SV.  But for CVs
3920                leave_scope needs access to the GV so it can reset method
3921                caches.  We must use SAVEt_GVSLOT whenever the type is
3922                SVt_PVCV, even if the stash is anonymous, as the stash may
3923                gain a name somehow before leave_scope. */
3924             if (stype == SVt_PVCV) {
3925                 /* There is no save_pushptrptrptr.  Creating it for this
3926                    one call site would be overkill.  So inline the ss add
3927                    routines here. */
3928                 dSS_ADD;
3929                 SS_ADD_PTR(dstr);
3930                 SS_ADD_PTR(location);
3931                 SS_ADD_PTR(SvREFCNT_inc(*location));
3932                 SS_ADD_UV(SAVEt_GVSLOT);
3933                 SS_ADD_END(4);
3934             }
3935             else SAVEGENERICSV(*location);
3936         }
3937         dref = *location;
3938         if (stype == SVt_PVCV && (*location != sref || GvCVGEN(dstr))) {
3939             CV* const cv = MUTABLE_CV(*location);
3940             if (cv) {
3941                 if (!GvCVGEN((const GV *)dstr) &&
3942                     (CvROOT(cv) || CvXSUB(cv)) &&
3943                     /* redundant check that avoids creating the extra SV
3944                        most of the time: */
3945                     (CvCONST(cv) || ckWARN(WARN_REDEFINE)))
3946                     {
3947                         SV * const new_const_sv =
3948                             CvCONST((const CV *)sref)
3949                                  ? cv_const_sv((const CV *)sref)
3950                                  : NULL;
3951                         report_redefined_cv(
3952                            sv_2mortal(Perl_newSVpvf(aTHX_
3953                                 "%"HEKf"::%"HEKf,
3954                                 HEKfARG(
3955                                  HvNAME_HEK(GvSTASH((const GV *)dstr))
3956                                 ),
3957                                 HEKfARG(GvENAME_HEK(MUTABLE_GV(dstr)))
3958                            )),
3959                            cv,
3960                            CvCONST((const CV *)sref) ? &new_const_sv : NULL
3961                         );
3962                     }
3963                 if (!intro)
3964                     cv_ckproto_len_flags(cv, (const GV *)dstr,
3965                                    SvPOK(sref) ? CvPROTO(sref) : NULL,
3966                                    SvPOK(sref) ? CvPROTOLEN(sref) : 0,
3967                                    SvPOK(sref) ? SvUTF8(sref) : 0);
3968             }
3969             GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3970             GvASSUMECV_on(dstr);
3971             if(GvSTASH(dstr)) { /* sub foo { 1 } sub bar { 2 } *bar = \&foo */
3972                 if (intro && GvREFCNT(dstr) > 1) {
3973                     /* temporary remove extra savestack's ref */
3974                     --GvREFCNT(dstr);
3975                     gv_method_changed(dstr);
3976                     ++GvREFCNT(dstr);
3977                 }
3978                 else gv_method_changed(dstr);
3979             }
3980         }
3981         *location = SvREFCNT_inc_simple_NN(sref);
3982         if (import_flag && !(GvFLAGS(dstr) & import_flag)
3983             && CopSTASH_ne(PL_curcop, GvSTASH(dstr))) {
3984             GvFLAGS(dstr) |= import_flag;
3985         }
3986         if (stype == SVt_PVHV) {
3987             const char * const name = GvNAME((GV*)dstr);
3988             const STRLEN len = GvNAMELEN(dstr);
3989             if (
3990                 (
3991                    (len > 1 && name[len-2] == ':' && name[len-1] == ':')
3992                 || (len == 1 && name[0] == ':')
3993                 )
3994              && (!dref || HvENAME_get(dref))
3995             ) {
3996                 mro_package_moved(
3997                     (HV *)sref, (HV *)dref,
3998                     (GV *)dstr, 0
3999                 );
4000             }
4001         }
4002         else if (
4003             stype == SVt_PVAV && sref != dref
4004          && strEQ(GvNAME((GV*)dstr), "ISA")
4005          /* The stash may have been detached from the symbol table, so
4006             check its name before doing anything. */
4007          && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
4008         ) {
4009             MAGIC *mg;
4010             MAGIC * const omg = dref && SvSMAGICAL(dref)
4011                                  ? mg_find(dref, PERL_MAGIC_isa)
4012                                  : NULL;
4013             if (SvSMAGICAL(sref) && (mg = mg_find(sref, PERL_MAGIC_isa))) {
4014                 if (SvTYPE(mg->mg_obj) != SVt_PVAV) {
4015                     AV * const ary = newAV();
4016                     av_push(ary, mg->mg_obj); /* takes the refcount */
4017                     mg->mg_obj = (SV *)ary;
4018                 }
4019                 if (omg) {
4020                     if (SvTYPE(omg->mg_obj) == SVt_PVAV) {
4021                         SV **svp = AvARRAY((AV *)omg->mg_obj);
4022                         I32 items = AvFILLp((AV *)omg->mg_obj) + 1;
4023                         while (items--)
4024                             av_push(
4025                              (AV *)mg->mg_obj,
4026                              SvREFCNT_inc_simple_NN(*svp++)
4027                             );
4028                     }
4029                     else
4030                         av_push(
4031                          (AV *)mg->mg_obj,
4032                          SvREFCNT_inc_simple_NN(omg->mg_obj)
4033                         );
4034                 }
4035                 else
4036                     av_push((AV *)mg->mg_obj,SvREFCNT_inc_simple_NN(dstr));
4037             }
4038             else
4039             {
4040                 sv_magic(
4041                  sref, omg ? omg->mg_obj : dstr, PERL_MAGIC_isa, NULL, 0
4042                 );
4043                 mg = mg_find(sref, PERL_MAGIC_isa);
4044             }
4045             /* Since the *ISA assignment could have affected more than
4046                one stash, don't call mro_isa_changed_in directly, but let
4047                magic_clearisa do it for us, as it already has the logic for
4048                dealing with globs vs arrays of globs. */
4049             assert(mg);
4050             Perl_magic_clearisa(aTHX_ NULL, mg);
4051         }
4052         else if (stype == SVt_PVIO) {
4053             DEBUG_o(Perl_deb(aTHX_ "glob_assign_ref clearing PL_stashcache\n"));
4054             /* It's a cache. It will rebuild itself quite happily.
4055                It's a lot of effort to work out exactly which key (or keys)
4056                might be invalidated by the creation of the this file handle.
4057             */
4058             hv_clear(PL_stashcache);
4059         }
4060         break;
4061     }
4062     if (!intro) SvREFCNT_dec(dref);
4063     if (SvTAINTED(sstr))
4064         SvTAINT(dstr);
4065     return;
4066 }
4067
4068
4069
4070
4071 #ifdef PERL_DEBUG_READONLY_COW
4072 # include <sys/mman.h>
4073
4074 # ifndef PERL_MEMORY_DEBUG_HEADER_SIZE
4075 #  define PERL_MEMORY_DEBUG_HEADER_SIZE 0
4076 # endif
4077
4078 void
4079 Perl_sv_buf_to_ro(pTHX_ SV *sv)
4080 {
4081     struct perl_memory_debug_header * const header =
4082         (struct perl_memory_debug_header *)(SvPVX(sv)-PERL_MEMORY_DEBUG_HEADER_SIZE);
4083     const MEM_SIZE len = header->size;
4084     PERL_ARGS_ASSERT_SV_BUF_TO_RO;
4085 # ifdef PERL_TRACK_MEMPOOL
4086     if (!header->readonly) header->readonly = 1;
4087 # endif
4088     if (mprotect(header, len, PROT_READ))
4089         Perl_warn(aTHX_ "mprotect RW for COW string %p %lu failed with %d",
4090                          header, len, errno);
4091 }
4092
4093 static void
4094 S_sv_buf_to_rw(pTHX_ SV *sv)
4095 {
4096     struct perl_memory_debug_header * const header =
4097         (struct perl_memory_debug_header *)(SvPVX(sv)-PERL_MEMORY_DEBUG_HEADER_SIZE);
4098     const MEM_SIZE len = header->size;
4099     PERL_ARGS_ASSERT_SV_BUF_TO_RW;
4100     if (mprotect(header, len, PROT_READ|PROT_WRITE))
4101         Perl_warn(aTHX_ "mprotect for COW string %p %lu failed with %d",
4102                          header, len, errno);
4103 # ifdef PERL_TRACK_MEMPOOL
4104     header->readonly = 0;
4105 # endif
4106 }
4107
4108 #else
4109 # define sv_buf_to_ro(sv)       NOOP
4110 # define sv_buf_to_rw(sv)       NOOP
4111 #endif
4112
4113 void
4114 Perl_sv_setsv_flags(pTHX_ SV *dstr, SV* sstr, const I32 flags)
4115 {
4116     U32 sflags;
4117     int dtype;
4118     svtype stype;
4119
4120     PERL_ARGS_ASSERT_SV_SETSV_FLAGS;
4121
4122     if (sstr == dstr)
4123         return;
4124
4125     if (SvIS_FREED(dstr)) {
4126         Perl_croak(aTHX_ "panic: attempt to copy value %" SVf
4127                    " to a freed scalar %p", SVfARG(sstr), (void *)dstr);
4128     }
4129     SV_CHECK_THINKFIRST_COW_DROP(dstr);
4130     if (!sstr)
4131         sstr = &PL_sv_undef;
4132     if (SvIS_FREED(sstr)) {
4133         Perl_croak(aTHX_ "panic: attempt to copy freed scalar %p to %p",
4134                    (void*)sstr, (void*)dstr);
4135     }
4136     stype = SvTYPE(sstr);
4137     dtype = SvTYPE(dstr);
4138
4139     /* There's a lot of redundancy below but we're going for speed here */
4140
4141     switch (stype) {
4142     case SVt_NULL:
4143       undef_sstr:
4144         if (dtype != SVt_PVGV && dtype != SVt_PVLV) {
4145             (void)SvOK_off(dstr);
4146             return;
4147         }
4148         break;
4149     case SVt_IV:
4150         if (SvIOK(sstr)) {
4151             switch (dtype) {
4152             case SVt_NULL:
4153                 sv_upgrade(dstr, SVt_IV);
4154                 break;
4155             case SVt_NV:
4156             case SVt_PV:
4157                 sv_upgrade(dstr, SVt_PVIV);
4158                 break;
4159             case SVt_PVGV:
4160             case SVt_PVLV:
4161                 goto end_of_first_switch;
4162             }
4163             (void)SvIOK_only(dstr);
4164             SvIV_set(dstr,  SvIVX(sstr));
4165             if (SvIsUV(sstr))
4166                 SvIsUV_on(dstr);
4167             /* SvTAINTED can only be true if the SV has taint magic, which in
4168                turn means that the SV type is PVMG (or greater). This is the
4169                case statement for SVt_IV, so this cannot be true (whatever gcov
4170                may say).  */
4171             assert(!SvTAINTED(sstr));
4172             return;
4173         }
4174         if (!SvROK(sstr))
4175             goto undef_sstr;
4176         if (dtype < SVt_PV && dtype != SVt_IV)
4177             sv_upgrade(dstr, SVt_IV);
4178         break;
4179
4180     case SVt_NV:
4181         if (SvNOK(sstr)) {
4182             switch (dtype) {
4183             case SVt_NULL:
4184             case SVt_IV:
4185                 sv_upgrade(dstr, SVt_NV);
4186                 break;
4187             case SVt_PV:
4188             case SVt_PVIV:
4189                 sv_upgrade(dstr, SVt_PVNV);
4190                 break;
4191             case SVt_PVGV:
4192             case SVt_PVLV:
4193                 goto end_of_first_switch;
4194             }
4195             SvNV_set(dstr, SvNVX(sstr));
4196             (void)SvNOK_only(dstr);
4197             /* SvTAINTED can only be true if the SV has taint magic, which in
4198                turn means that the SV type is PVMG (or greater). This is the
4199                case statement for SVt_NV, so this cannot be true (whatever gcov
4200                may say).  */
4201             assert(!SvTAINTED(sstr));
4202             return;
4203         }
4204         goto undef_sstr;
4205
4206     case SVt_PV:
4207         if (dtype < SVt_PV)
4208             sv_upgrade(dstr, SVt_PV);
4209         break;
4210     case SVt_PVIV:
4211         if (dtype < SVt_PVIV)
4212             sv_upgrade(dstr, SVt_PVIV);
4213         break;
4214     case SVt_PVNV:
4215         if (dtype < SVt_PVNV)
4216             sv_upgrade(dstr, SVt_PVNV);
4217         break;
4218     default:
4219         {
4220         const char * const type = sv_reftype(sstr,0);
4221         if (PL_op)
4222             /* diag_listed_as: Bizarre copy of %s */
4223             Perl_croak(aTHX_ "Bizarre copy of %s in %s", type, OP_DESC(PL_op));
4224         else
4225             Perl_croak(aTHX_ "Bizarre copy of %s", type);
4226         }
4227         NOT_REACHED; /* NOTREACHED */
4228
4229     case SVt_REGEXP:
4230       upgregexp:
4231         if (dtype < SVt_REGEXP)
4232         {
4233             if (dtype >= SVt_PV) {
4234                 SvPV_free(dstr);
4235                 SvPV_set(dstr, 0);
4236                 SvLEN_set(dstr, 0);
4237                 SvCUR_set(dstr, 0);
4238             }
4239             sv_upgrade(dstr, SVt_REGEXP);
4240         }
4241         break;
4242
4243         case SVt_INVLIST:
4244     case SVt_PVLV:
4245     case SVt_PVGV:
4246     case SVt_PVMG:
4247         if (SvGMAGICAL(sstr) && (flags & SV_GMAGIC)) {
4248             mg_get(sstr);
4249             if (SvTYPE(sstr) != stype)
4250                 stype = SvTYPE(sstr);
4251         }
4252         if (isGV_with_GP(sstr) && dtype <= SVt_PVLV) {
4253                     glob_assign_glob(dstr, sstr, dtype);
4254                     return;
4255         }
4256         if (stype == SVt_PVLV)
4257         {
4258             if (isREGEXP(sstr)) goto upgregexp;
4259             SvUPGRADE(dstr, SVt_PVNV);
4260         }
4261         else
4262             SvUPGRADE(dstr, (svtype)stype);
4263     }
4264  end_of_first_switch:
4265
4266     /* dstr may have been upgraded.  */
4267     dtype = SvTYPE(dstr);
4268     sflags = SvFLAGS(sstr);
4269
4270     if (dtype == SVt_PVCV) {
4271         /* Assigning to a subroutine sets the prototype.  */
4272         if (SvOK(sstr)) {
4273             STRLEN len;
4274             const char *const ptr = SvPV_const(sstr, len);
4275
4276             SvGROW(dstr, len + 1);
4277             Copy(ptr, SvPVX(dstr), len + 1, char);
4278             SvCUR_set(dstr, len);
4279             SvPOK_only(dstr);
4280             SvFLAGS(dstr) |= sflags & SVf_UTF8;
4281             CvAUTOLOAD_off(dstr);
4282         } else {
4283             SvOK_off(dstr);
4284         }
4285     }
4286     else if (dtype == SVt_PVAV || dtype == SVt_PVHV || dtype == SVt_PVFM) {
4287         const char * const type = sv_reftype(dstr,0);
4288         if (PL_op)
4289             /* diag_listed_as: Cannot copy to %s */
4290             Perl_croak(aTHX_ "Cannot copy to %s in %s", type, OP_DESC(PL_op));
4291         else
4292             Perl_croak(aTHX_ "Cannot copy to %s", type);
4293     } else if (sflags & SVf_ROK) {
4294         if (isGV_with_GP(dstr)
4295             && SvTYPE(SvRV(sstr)) == SVt_PVGV && isGV_with_GP(SvRV(sstr))) {
4296             sstr = SvRV(sstr);
4297             if (sstr == dstr) {
4298                 if (GvIMPORTED(dstr) != GVf_IMPORTED
4299                     && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
4300                 {
4301                     GvIMPORTED_on(dstr);
4302                 }
4303                 GvMULTI_on(dstr);
4304                 return;
4305             }
4306             glob_assign_glob(dstr, sstr, dtype);
4307             return;
4308         }
4309
4310         if (dtype >= SVt_PV) {
4311             if (isGV_with_GP(dstr)) {
4312                 glob_assign_ref(dstr, sstr);
4313                 return;
4314             }
4315             if (SvPVX_const(dstr)) {
4316                 SvPV_free(dstr);
4317                 SvLEN_set(dstr, 0);
4318                 SvCUR_set(dstr, 0);
4319             }
4320         }
4321         (void)SvOK_off(dstr);
4322         SvRV_set(dstr, SvREFCNT_inc(SvRV(sstr)));
4323         SvFLAGS(dstr) |= sflags & SVf_ROK;
4324         assert(!(sflags & SVp_NOK));
4325         assert(!(sflags & SVp_IOK));
4326         assert(!(sflags & SVf_NOK));
4327         assert(!(sflags & SVf_IOK));
4328     }
4329     else if (isGV_with_GP(dstr)) {
4330         if (!(sflags & SVf_OK)) {
4331             Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4332                            "Undefined value assigned to typeglob");
4333         }
4334         else {
4335             GV *gv = gv_fetchsv_nomg(sstr, GV_ADD, SVt_PVGV);
4336             if (dstr != (const SV *)gv) {
4337                 const char * const name = GvNAME((const GV *)dstr);
4338                 const STRLEN len = GvNAMELEN(dstr);
4339                 HV *old_stash = NULL;
4340                 bool reset_isa = FALSE;
4341                 if ((len > 1 && name[len-2] == ':' && name[len-1] == ':')
4342                  || (len == 1 && name[0] == ':')) {
4343                     /* Set aside the old stash, so we can reset isa caches
4344                        on its subclasses. */
4345                     if((old_stash = GvHV(dstr))) {
4346                         /* Make sure we do not lose it early. */
4347                         SvREFCNT_inc_simple_void_NN(
4348                          sv_2mortal((SV *)old_stash)
4349                         );
4350                     }
4351                     reset_isa = TRUE;
4352                 }
4353
4354                 if (GvGP(dstr)) {
4355                     SvREFCNT_inc_simple_void_NN(sv_2mortal(dstr));
4356                     gp_free(MUTABLE_GV(dstr));
4357                 }
4358                 GvGP_set(dstr, gp_ref(GvGP(gv)));
4359
4360                 if (reset_isa) {
4361                     HV * const stash = GvHV(dstr);
4362                     if(
4363                         old_stash ? (HV *)HvENAME_get(old_stash) : stash
4364                     )
4365                         mro_package_moved(
4366                          stash, old_stash,
4367                          (GV *)dstr, 0
4368                         );
4369                 }
4370             }
4371         }
4372     }
4373     else if ((dtype == SVt_REGEXP || dtype == SVt_PVLV)
4374           && (stype == SVt_REGEXP || isREGEXP(sstr))) {
4375         reg_temp_copy((REGEXP*)dstr, (REGEXP*)sstr);
4376     }
4377     else if (sflags & SVp_POK) {
4378         const STRLEN cur = SvCUR(sstr);
4379         const STRLEN len = SvLEN(sstr);
4380
4381         /*
4382          * We have three basic ways to copy the string:
4383          *
4384          *  1. Swipe
4385          *  2. Copy-on-write
4386          *  3. Actual copy
4387          * 
4388          * Which we choose is based on various factors.  The following
4389          * things are listed in order of speed, fastest to slowest:
4390          *  - Swipe
4391          *  - Copying a short string
4392          *  - Copy-on-write bookkeeping
4393          *  - malloc
4394          *  - Copying a long string
4395          * 
4396          * We swipe the string (steal the string buffer) if the SV on the
4397          * rhs is about to be freed anyway (TEMP and refcnt==1).  This is a
4398          * big win on long strings.  It should be a win on short strings if
4399          * SvPVX_const(dstr) has to be allocated.  If not, it should not 
4400          * slow things down, as SvPVX_const(sstr) would have been freed
4401          * soon anyway.
4402          * 
4403          * We also steal the buffer from a PADTMP (operator target) if it
4404          * is â€˜long enough’.  For short strings, a swipe does not help
4405          * here, as it causes more malloc calls the next time the target
4406          * is used.  Benchmarks show that even if SvPVX_const(dstr) has to
4407          * be allocated it is still not worth swiping PADTMPs for short
4408          * strings, as the savings here are small.
4409          * 
4410          * If the rhs is already flagged as a copy-on-write string and COW
4411          * is possible here, we use copy-on-write and make both SVs share
4412          * the string buffer.
4413          * 
4414          * If the rhs is not flagged as copy-on-write, then we see whether
4415          * it is worth upgrading it to such.  If the lhs already has a buf-
4416          * fer big enough and the string is short, we skip it and fall back
4417          * to method 3, since memcpy is faster for short strings than the
4418          * later bookkeeping overhead that copy-on-write entails.
4419          * 
4420          * If there is no buffer on the left, or the buffer is too small,
4421          * then we use copy-on-write.
4422          */
4423
4424         /* Whichever path we take through the next code, we want this true,
4425            and doing it now facilitates the COW check.  */
4426         (void)SvPOK_only(dstr);
4427
4428         if (
4429                  (              /* Either ... */
4430                                 /* slated for free anyway (and not COW)? */
4431                     (sflags & (SVs_TEMP|SVf_IsCOW)) == SVs_TEMP
4432                                 /* or a swipable TARG */
4433                  || ((sflags & (SVs_PADTMP|SVf_READONLY|SVf_IsCOW))
4434                        == SVs_PADTMP
4435                                 /* whose buffer is worth stealing */
4436                      && CHECK_COWBUF_THRESHOLD(cur,len)
4437                     )
4438                  ) &&
4439                  !(sflags & SVf_OOK) &&   /* and not involved in OOK hack? */
4440                  (!(flags & SV_NOSTEAL)) &&
4441                                         /* and we're allowed to steal temps */
4442                  SvREFCNT(sstr) == 1 &&   /* and no other references to it? */
4443                  len)             /* and really is a string */
4444         {       /* Passes the swipe test.  */
4445             if (SvPVX_const(dstr))      /* we know that dtype >= SVt_PV */
4446                 SvPV_free(dstr);
4447             SvPV_set(dstr, SvPVX_mutable(sstr));
4448             SvLEN_set(dstr, SvLEN(sstr));
4449             SvCUR_set(dstr, SvCUR(sstr));
4450
4451             SvTEMP_off(dstr);
4452             (void)SvOK_off(sstr);       /* NOTE: nukes most SvFLAGS on sstr */
4453             SvPV_set(sstr, NULL);
4454             SvLEN_set(sstr, 0);
4455             SvCUR_set(sstr, 0);
4456             SvTEMP_off(sstr);
4457         }
4458         else if (flags & SV_COW_SHARED_HASH_KEYS
4459               &&
4460 #ifdef PERL_OLD_COPY_ON_WRITE
4461                  (  sflags & SVf_IsCOW
4462                  || (   (sflags & CAN_COW_MASK) == CAN_COW_FLAGS
4463                      && (SvFLAGS(dstr) & CAN_COW_MASK) == CAN_COW_FLAGS
4464                      && SvTYPE(sstr) >= SVt_PVIV && len
4465                     )
4466                  )
4467 #elif defined(PERL_NEW_COPY_ON_WRITE)
4468                  (sflags & SVf_IsCOW
4469                    ? (!len ||
4470                        (  (CHECK_COWBUF_THRESHOLD(cur,len) || SvLEN(dstr) < cur+1)
4471                           /* If this is a regular (non-hek) COW, only so
4472                              many COW "copies" are possible. */
4473                        && CowREFCNT(sstr) != SV_COW_REFCNT_MAX  ))
4474                    : (  (sflags & CAN_COW_MASK) == CAN_COW_FLAGS
4475                      && !(SvFLAGS(dstr) & SVf_BREAK)
4476                      && CHECK_COW_THRESHOLD(cur,len) && cur+1 < len
4477                      && (CHECK_COWBUF_THRESHOLD(cur,len) || SvLEN(dstr) < cur+1)
4478                     ))
4479 #else
4480                  sflags & SVf_IsCOW
4481               && !(SvFLAGS(dstr) & SVf_BREAK)
4482 #endif
4483             ) {
4484             /* Either it's a shared hash key, or it's suitable for
4485                copy-on-write.  */
4486             if (DEBUG_C_TEST) {
4487                 PerlIO_printf(Perl_debug_log, "Copy on write: sstr --> dstr\n");
4488                 sv_dump(sstr);
4489                 sv_dump(dstr);
4490             }
4491 #ifdef PERL_ANY_COW
4492             if (!(sflags & SVf_IsCOW)) {
4493                     SvIsCOW_on(sstr);
4494 # ifdef PERL_OLD_COPY_ON_WRITE
4495                     /* Make the source SV into a loop of 1.
4496                        (about to become 2) */
4497                     SV_COW_NEXT_SV_SET(sstr, sstr);
4498 # else
4499                     CowREFCNT(sstr) = 0;
4500 # endif
4501             }
4502 #endif
4503             if (SvPVX_const(dstr)) {    /* we know that dtype >= SVt_PV */
4504                 SvPV_free(dstr);
4505             }
4506
4507 #ifdef PERL_ANY_COW
4508             if (len) {
4509 # ifdef PERL_OLD_COPY_ON_WRITE
4510                     assert (SvTYPE(dstr) >= SVt_PVIV);
4511                     /* SvIsCOW_normal */
4512                     /* splice us in between source and next-after-source.  */
4513                     SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4514                     SV_COW_NEXT_SV_SET(sstr, dstr);
4515 # else
4516                     if (sflags & SVf_IsCOW) {
4517                         sv_buf_to_rw(sstr);
4518                     }
4519                     CowREFCNT(sstr)++;
4520 # endif
4521                     SvPV_set(dstr, SvPVX_mutable(sstr));
4522                     sv_buf_to_ro(sstr);
4523             } else
4524 #endif
4525             {
4526                     /* SvIsCOW_shared_hash */
4527                     DEBUG_C(PerlIO_printf(Perl_debug_log,
4528                                           "Copy on write: Sharing hash\n"));
4529
4530                     assert (SvTYPE(dstr) >= SVt_PV);
4531                     SvPV_set(dstr,
4532                              HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)))));
4533             }
4534             SvLEN_set(dstr, len);
4535             SvCUR_set(dstr, cur);
4536             SvIsCOW_on(dstr);
4537         } else {
4538             /* Failed the swipe test, and we cannot do copy-on-write either.
4539                Have to copy the string.  */
4540             SvGROW(dstr, cur + 1);      /* inlined from sv_setpvn */
4541             Move(SvPVX_const(sstr),SvPVX(dstr),cur,char);
4542             SvCUR_set(dstr, cur);
4543             *SvEND(dstr) = '\0';
4544         }
4545         if (sflags & SVp_NOK) {
4546             SvNV_set(dstr, SvNVX(sstr));
4547         }
4548         if (sflags & SVp_IOK) {
4549             SvIV_set(dstr, SvIVX(sstr));
4550             /* Must do this otherwise some other overloaded use of 0x80000000
4551                gets confused. I guess SVpbm_VALID */
4552             if (sflags & SVf_IVisUV)
4553                 SvIsUV_on(dstr);
4554         }
4555         SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_NOK|SVp_NOK|SVf_UTF8);
4556         {
4557             const MAGIC * const smg = SvVSTRING_mg(sstr);
4558             if (smg) {
4559                 sv_magic(dstr, NULL, PERL_MAGIC_vstring,
4560                          smg->mg_ptr, smg->mg_len);
4561                 SvRMAGICAL_on(dstr);
4562             }
4563         }
4564     }
4565     else if (sflags & (SVp_IOK|SVp_NOK)) {
4566         (void)SvOK_off(dstr);
4567         SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_IVisUV|SVf_NOK|SVp_NOK);
4568         if (sflags & SVp_IOK) {
4569             /* XXXX Do we want to set IsUV for IV(ROK)?  Be extra safe... */
4570             SvIV_set(dstr, SvIVX(sstr));
4571         }
4572         if (sflags & SVp_NOK) {
4573             SvNV_set(dstr, SvNVX(sstr));
4574         }
4575     }
4576     else {
4577         if (isGV_with_GP(sstr)) {
4578             gv_efullname3(dstr, MUTABLE_GV(sstr), "*");
4579         }
4580         else
4581             (void)SvOK_off(dstr);
4582     }
4583     if (SvTAINTED(sstr))
4584         SvTAINT(dstr);
4585 }
4586
4587 /*
4588 =for apidoc sv_setsv_mg
4589
4590 Like C<sv_setsv>, but also handles 'set' magic.
4591
4592 =cut
4593 */
4594
4595 void
4596 Perl_sv_setsv_mg(pTHX_ SV *const dstr, SV *const sstr)
4597 {
4598     PERL_ARGS_ASSERT_SV_SETSV_MG;
4599
4600     sv_setsv(dstr,sstr);
4601     SvSETMAGIC(dstr);
4602 }
4603
4604 #ifdef PERL_ANY_COW
4605 # ifdef PERL_OLD_COPY_ON_WRITE
4606 #  define SVt_COW SVt_PVIV
4607 # else
4608 #  define SVt_COW SVt_PV
4609 # endif
4610 SV *
4611 Perl_sv_setsv_cow(pTHX_ SV *dstr, SV *sstr)
4612 {
4613     STRLEN cur = SvCUR(sstr);
4614     STRLEN len = SvLEN(sstr);
4615     char *new_pv;
4616 #if defined(PERL_DEBUG_READONLY_COW) && defined(PERL_NEW_COPY_ON_WRITE)
4617     const bool already = cBOOL(SvIsCOW(sstr));
4618 #endif
4619
4620     PERL_ARGS_ASSERT_SV_SETSV_COW;
4621
4622     if (DEBUG_C_TEST) {
4623         PerlIO_printf(Perl_debug_log, "Fast copy on write: %p -> %p\n",
4624                       (void*)sstr, (void*)dstr);
4625         sv_dump(sstr);
4626         if (dstr)
4627                     sv_dump(dstr);
4628     }
4629
4630     if (dstr) {
4631         if (SvTHINKFIRST(dstr))
4632             sv_force_normal_flags(dstr, SV_COW_DROP_PV);
4633         else if (SvPVX_const(dstr))
4634             Safefree(SvPVX_mutable(dstr));
4635     }
4636     else
4637         new_SV(dstr);
4638     SvUPGRADE(dstr, SVt_COW);
4639
4640     assert (SvPOK(sstr));
4641     assert (SvPOKp(sstr));
4642 # ifdef PERL_OLD_COPY_ON_WRITE
4643     assert (!SvIOK(sstr));
4644     assert (!SvIOKp(sstr));
4645     assert (!SvNOK(sstr));
4646     assert (!SvNOKp(sstr));
4647 # endif
4648
4649     if (SvIsCOW(sstr)) {
4650
4651         if (SvLEN(sstr) == 0) {
4652             /* source is a COW shared hash key.  */
4653             DEBUG_C(PerlIO_printf(Perl_debug_log,
4654                                   "Fast copy on write: Sharing hash\n"));
4655             new_pv = HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr))));
4656             goto common_exit;
4657         }
4658 # ifdef PERL_OLD_COPY_ON_WRITE
4659         SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4660 # else
4661         assert(SvCUR(sstr)+1 < SvLEN(sstr));
4662         assert(CowREFCNT(sstr) < SV_COW_REFCNT_MAX);
4663 # endif
4664     } else {
4665         assert ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS);
4666         SvUPGRADE(sstr, SVt_COW);
4667         SvIsCOW_on(sstr);
4668         DEBUG_C(PerlIO_printf(Perl_debug_log,
4669                               "Fast copy on write: Converting sstr to COW\n"));
4670 # ifdef PERL_OLD_COPY_ON_WRITE
4671         SV_COW_NEXT_SV_SET(dstr, sstr);
4672 # else
4673         CowREFCNT(sstr) = 0;    
4674 # endif
4675     }
4676 # ifdef PERL_OLD_COPY_ON_WRITE
4677     SV_COW_NEXT_SV_SET(sstr, dstr);
4678 # else
4679 #  ifdef PERL_DEBUG_READONLY_COW
4680     if (already) sv_buf_to_rw(sstr);
4681 #  endif
4682     CowREFCNT(sstr)++;  
4683 # endif
4684     new_pv = SvPVX_mutable(sstr);
4685     sv_buf_to_ro(sstr);
4686
4687   common_exit:
4688     SvPV_set(dstr, new_pv);
4689     SvFLAGS(dstr) = (SVt_COW|SVf_POK|SVp_POK|SVf_IsCOW);
4690     if (SvUTF8(sstr))
4691         SvUTF8_on(dstr);
4692     SvLEN_set(dstr, len);
4693     SvCUR_set(dstr, cur);
4694     if (DEBUG_C_TEST) {
4695         sv_dump(dstr);
4696     }
4697     return dstr;
4698 }
4699 #endif
4700
4701 /*
4702 =for apidoc sv_setpvn
4703
4704 Copies a string (possibly containing embedded C<NUL> characters) into an SV.
4705 The C<len> parameter indicates the number of
4706 bytes to be copied.  If the C<ptr> argument is NULL the SV will become
4707 undefined.  Does not handle 'set' magic.  See C<sv_setpvn_mg>.
4708
4709 =cut
4710 */
4711
4712 void
4713 Perl_sv_setpvn(pTHX_ SV *const sv, const char *const ptr, const STRLEN len)
4714 {
4715     char *dptr;
4716
4717     PERL_ARGS_ASSERT_SV_SETPVN;
4718
4719     SV_CHECK_THINKFIRST_COW_DROP(sv);
4720     if (!ptr) {
4721         (void)SvOK_off(sv);
4722         return;
4723     }
4724     else {
4725         /* len is STRLEN which is unsigned, need to copy to signed */
4726         const IV iv = len;
4727         if (iv < 0)
4728             Perl_croak(aTHX_ "panic: sv_setpvn called with negative strlen %"
4729                        IVdf, iv);
4730     }
4731     SvUPGRADE(sv, SVt_PV);
4732
4733     dptr = SvGROW(sv, len + 1);
4734     Move(ptr,dptr,len,char);
4735     dptr[len] = '\0';
4736     SvCUR_set(sv, len);
4737     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4738     SvTAINT(sv);
4739     if (SvTYPE(sv) == SVt_PVCV) CvAUTOLOAD_off(sv);
4740 }
4741
4742 /*
4743 =for apidoc sv_setpvn_mg
4744
4745 Like C<sv_setpvn>, but also handles 'set' magic.
4746
4747 =cut
4748 */
4749
4750 void
4751 Perl_sv_setpvn_mg(pTHX_ SV *const sv, const char *const ptr, const STRLEN len)
4752 {
4753     PERL_ARGS_ASSERT_SV_SETPVN_MG;
4754
4755     sv_setpvn(sv,ptr,len);
4756     SvSETMAGIC(sv);
4757 }
4758
4759 /*
4760 =for apidoc sv_setpv
4761
4762 Copies a string into an SV.  The string must be terminated with a C<NUL>
4763 character.
4764 Does not handle 'set' magic.  See C<sv_setpv_mg>.
4765
4766 =cut
4767 */
4768
4769 void
4770 Perl_sv_setpv(pTHX_ SV *const sv, const char *const ptr)
4771 {
4772     STRLEN len;
4773
4774     PERL_ARGS_ASSERT_SV_SETPV;
4775
4776     SV_CHECK_THINKFIRST_COW_DROP(sv);
4777     if (!ptr) {
4778         (void)SvOK_off(sv);
4779         return;
4780     }
4781     len = strlen(ptr);
4782     SvUPGRADE(sv, SVt_PV);
4783
4784     SvGROW(sv, len + 1);
4785     Move(ptr,SvPVX(sv),len+1,char);
4786     SvCUR_set(sv, len);
4787     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4788     SvTAINT(sv);
4789     if (SvTYPE(sv) == SVt_PVCV) CvAUTOLOAD_off(sv);
4790 }
4791
4792 /*
4793 =for apidoc sv_setpv_mg
4794
4795 Like C<sv_setpv>, but also handles 'set' magic.
4796
4797 =cut
4798 */
4799
4800 void
4801 Perl_sv_setpv_mg(pTHX_ SV *const sv, const char *const ptr)
4802 {
4803     PERL_ARGS_ASSERT_SV_SETPV_MG;
4804
4805     sv_setpv(sv,ptr);
4806     SvSETMAGIC(sv);
4807 }
4808
4809 void
4810 Perl_sv_sethek(pTHX_ SV *const sv, const HEK *const hek)
4811 {
4812     PERL_ARGS_ASSERT_SV_SETHEK;
4813
4814     if (!hek) {
4815         return;
4816     }
4817
4818     if (HEK_LEN(hek) == HEf_SVKEY) {
4819         sv_setsv(sv, *(SV**)HEK_KEY(hek));
4820         return;
4821     } else {
4822         const int flags = HEK_FLAGS(hek);
4823         if (flags & HVhek_WASUTF8) {
4824             STRLEN utf8_len = HEK_LEN(hek);
4825             char *as_utf8 = (char *)bytes_to_utf8((U8*)HEK_KEY(hek), &utf8_len);
4826             sv_usepvn_flags(sv, as_utf8, utf8_len, SV_HAS_TRAILING_NUL);
4827             SvUTF8_on(sv);
4828             return;
4829         } else if (flags & HVhek_UNSHARED) {
4830             sv_setpvn(sv, HEK_KEY(hek), HEK_LEN(hek));
4831             if (HEK_UTF8(hek))
4832                 SvUTF8_on(sv);
4833             else SvUTF8_off(sv);
4834             return;
4835         }
4836         {
4837             SV_CHECK_THINKFIRST_COW_DROP(sv);
4838             SvUPGRADE(sv, SVt_PV);
4839             SvPV_free(sv);
4840             SvPV_set(sv,(char *)HEK_KEY(share_hek_hek(hek)));
4841             SvCUR_set(sv, HEK_LEN(hek));
4842             SvLEN_set(sv, 0);
4843             SvIsCOW_on(sv);
4844             SvPOK_on(sv);
4845             if (HEK_UTF8(hek))
4846                 SvUTF8_on(sv);
4847             else SvUTF8_off(sv);
4848             return;
4849         }
4850     }
4851 }
4852
4853
4854 /*
4855 =for apidoc sv_usepvn_flags
4856
4857 Tells an SV to use C<ptr> to find its string value.  Normally the
4858 string is stored inside the SV, but sv_usepvn allows the SV to use an
4859 outside string.  The C<ptr> should point to memory that was allocated
4860 by L<Newx|perlclib/Memory Management and String Handling>. It must be
4861 the start of a Newx-ed block of memory, and not a pointer to the
4862 middle of it (beware of L<OOK|perlguts/Offsets> and copy-on-write),
4863 and not be from a non-Newx memory allocator like C<malloc>. The
4864 string length, C<len>, must be supplied.  By default this function
4865 will C<Renew> (i.e. realloc, move) the memory pointed to by C<ptr>,
4866 so that pointer should not be freed or used by the programmer after
4867 giving it to sv_usepvn, and neither should any pointers from "behind"
4868 that pointer (e.g. ptr + 1) be used.
4869
4870 If C<flags> & SV_SMAGIC is true, will call SvSETMAGIC.  If C<flags> &
4871 SV_HAS_TRAILING_NUL is true, then C<ptr[len]> must be C<NUL>, and the realloc
4872 will be skipped (i.e. the buffer is actually at least 1 byte longer than
4873 C<len>, and already meets the requirements for storing in C<SvPVX>).
4874
4875 =cut
4876 */
4877
4878 void
4879 Perl_sv_usepvn_flags(pTHX_ SV *const sv, char *ptr, const STRLEN len, const U32 flags)
4880 {
4881     STRLEN allocate;
4882
4883     PERL_ARGS_ASSERT_SV_USEPVN_FLAGS;
4884
4885     SV_CHECK_THINKFIRST_COW_DROP(sv);
4886     SvUPGRADE(sv, SVt_PV);
4887     if (!ptr) {
4888         (void)SvOK_off(sv);
4889         if (flags & SV_SMAGIC)
4890             SvSETMAGIC(sv);
4891         return;
4892     }
4893     if (SvPVX_const(sv))
4894         SvPV_free(sv);
4895
4896 #ifdef DEBUGGING
4897     if (flags & SV_HAS_TRAILING_NUL)
4898         assert(ptr[len] == '\0');
4899 #endif
4900
4901     allocate = (flags & SV_HAS_TRAILING_NUL)
4902         ? len + 1 :
4903 #ifdef Perl_safesysmalloc_size
4904         len + 1;
4905 #else 
4906         PERL_STRLEN_ROUNDUP(len + 1);
4907 #endif
4908     if (flags & SV_HAS_TRAILING_NUL) {
4909         /* It's long enough - do nothing.
4910            Specifically Perl_newCONSTSUB is relying on this.  */
4911     } else {
4912 #ifdef DEBUGGING
4913         /* Force a move to shake out bugs in callers.  */
4914         char *new_ptr = (char*)safemalloc(allocate);
4915         Copy(ptr, new_ptr, len, char);
4916         PoisonFree(ptr,len,char);
4917         Safefree(ptr);
4918         ptr = new_ptr;
4919 #else
4920         ptr = (char*) saferealloc (ptr, allocate);
4921 #endif
4922     }
4923 #ifdef Perl_safesysmalloc_size
4924     SvLEN_set(sv, Perl_safesysmalloc_size(ptr));
4925 #else
4926     SvLEN_set(sv, allocate);
4927 #endif
4928     SvCUR_set(sv, len);
4929     SvPV_set(sv, ptr);
4930     if (!(flags & SV_HAS_TRAILING_NUL)) {
4931         ptr[len] = '\0';
4932     }
4933     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4934     SvTAINT(sv);
4935     if (flags & SV_SMAGIC)
4936         SvSETMAGIC(sv);
4937 }
4938
4939 #ifdef PERL_OLD_COPY_ON_WRITE
4940 /* Need to do this *after* making the SV normal, as we need the buffer
4941    pointer to remain valid until after we've copied it.  If we let go too early,
4942    another thread could invalidate it by unsharing last of the same hash key
4943    (which it can do by means other than releasing copy-on-write Svs)
4944    or by changing the other copy-on-write SVs in the loop.  */
4945 STATIC void
4946 S_sv_release_COW(pTHX_ SV *sv, const char *pvx, SV *after)
4947 {
4948     PERL_ARGS_ASSERT_SV_RELEASE_COW;
4949
4950     { /* this SV was SvIsCOW_normal(sv) */
4951          /* we need to find the SV pointing to us.  */
4952         SV *current = SV_COW_NEXT_SV(after);
4953
4954         if (current == sv) {
4955             /* The SV we point to points back to us (there were only two of us
4956                in the loop.)
4957                Hence other SV is no longer copy on write either.  */
4958             SvIsCOW_off(after);
4959             sv_buf_to_rw(after);
4960         } else {
4961             /* We need to follow the pointers around the loop.  */
4962             SV *next;
4963             while ((next = SV_COW_NEXT_SV(current)) != sv) {
4964                 assert (next);
4965                 current = next;
4966                  /* don't loop forever if the structure is bust, and we have
4967                     a pointer into a closed loop.  */
4968                 assert (current != after);
4969                 assert (SvPVX_const(current) == pvx);
4970             }
4971             /* Make the SV before us point to the SV after us.  */
4972             SV_COW_NEXT_SV_SET(current, after);
4973         }
4974     }
4975 }
4976 #endif
4977 /*
4978 =for apidoc sv_force_normal_flags
4979
4980 Undo various types of fakery on an SV, where fakery means
4981 "more than" a string: if the PV is a shared string, make
4982 a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
4983 an xpvmg; if we're a copy-on-write scalar, this is the on-write time when
4984 we do the copy, and is also used locally; if this is a
4985 vstring, drop the vstring magic.  If C<SV_COW_DROP_PV> is set
4986 then a copy-on-write scalar drops its PV buffer (if any) and becomes
4987 SvPOK_off rather than making a copy.  (Used where this
4988 scalar is about to be set to some other value.)  In addition,
4989 the C<flags> parameter gets passed to C<sv_unref_flags()>
4990 when unreffing.  C<sv_force_normal> calls this function
4991 with flags set to 0.
4992
4993 This function is expected to be used to signal to perl that this SV is
4994 about to be written to, and any extra book-keeping needs to be taken care
4995 of.  Hence, it croaks on read-only values.
4996
4997 =cut
4998 */
4999
5000 static void
5001 S_sv_uncow(pTHX_ SV * const sv, const U32 flags)
5002 {
5003     assert(SvIsCOW(sv));
5004     {
5005 #ifdef PERL_ANY_COW
5006         const char * const pvx = SvPVX_const(sv);
5007         const STRLEN len = SvLEN(sv);
5008         const STRLEN cur = SvCUR(sv);
5009 # ifdef PERL_OLD_COPY_ON_WRITE
5010         /* next COW sv in the loop.  If len is 0 then this is a shared-hash
5011            key scalar, so we mustn't attempt to call SV_COW_NEXT_SV(), as
5012            we'll fail an assertion.  */
5013         SV * const next = len ? SV_COW_NEXT_SV(sv) : 0;
5014 # endif
5015
5016         if (DEBUG_C_TEST) {
5017                 PerlIO_printf(Perl_debug_log,
5018                               "Copy on write: Force normal %ld\n",
5019                               (long) flags);
5020                 sv_dump(sv);
5021         }
5022         SvIsCOW_off(sv);
5023 # ifdef PERL_NEW_COPY_ON_WRITE
5024         if (len && CowREFCNT(sv) == 0)
5025             /* We own the buffer ourselves. */
5026             sv_buf_to_rw(sv);
5027         else
5028 # endif
5029         {
5030                 
5031             /* This SV doesn't own the buffer, so need to Newx() a new one:  */
5032 # ifdef PERL_NEW_COPY_ON_WRITE
5033             /* Must do this first, since the macro uses SvPVX. */
5034             if (len) {
5035                 sv_buf_to_rw(sv);
5036                 CowREFCNT(sv)--;
5037                 sv_buf_to_ro(sv);
5038             }
5039 # endif
5040             SvPV_set(sv, NULL);
5041             SvCUR_set(sv, 0);
5042             SvLEN_set(sv, 0);
5043             if (flags & SV_COW_DROP_PV) {
5044                 /* OK, so we don't need to copy our buffer.  */
5045                 SvPOK_off(sv);
5046             } else {
5047                 SvGROW(sv, cur + 1);
5048                 Move(pvx,SvPVX(sv),cur,char);
5049                 SvCUR_set(sv, cur);
5050                 *SvEND(sv) = '\0';
5051             }
5052             if (len) {
5053 # ifdef PERL_OLD_COPY_ON_WRITE
5054                 sv_release_COW(sv, pvx, next);
5055 # endif
5056             } else {
5057                 unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
5058             }
5059             if (DEBUG_C_TEST) {
5060                 sv_dump(sv);
5061             }
5062         }
5063 #else
5064             const char * const pvx = SvPVX_const(sv);
5065             const STRLEN len = SvCUR(sv);
5066             SvIsCOW_off(sv);
5067             SvPV_set(sv, NULL);
5068             SvLEN_set(sv, 0);
5069             if (flags & SV_COW_DROP_PV) {
5070                 /* OK, so we don't need to copy our buffer.  */
5071                 SvPOK_off(sv);
5072             } else {
5073                 SvGROW(sv, len + 1);
5074                 Move(pvx,SvPVX(sv),len,char);
5075                 *SvEND(sv) = '\0';
5076             }
5077             unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
5078 #endif
5079     }
5080 }
5081
5082 void
5083 Perl_sv_force_normal_flags(pTHX_ SV *const sv, const U32 flags)
5084 {
5085     PERL_ARGS_ASSERT_SV_FORCE_NORMAL_FLAGS;
5086
5087     if (SvREADONLY(sv))
5088         Perl_croak_no_modify();
5089     else if (SvIsCOW(sv))
5090         S_sv_uncow(aTHX_ sv, flags);
5091     if (SvROK(sv))
5092         sv_unref_flags(sv, flags);
5093     else if (SvFAKE(sv) && isGV_with_GP(sv))
5094         sv_unglob(sv, flags);
5095     else if (SvFAKE(sv) && isREGEXP(sv)) {
5096         /* Need to downgrade the REGEXP to a simple(r) scalar. This is analogous
5097            to sv_unglob. We only need it here, so inline it.  */
5098         const bool islv = SvTYPE(sv) == SVt_PVLV;
5099         const svtype new_type =
5100           islv ? SVt_NULL : SvMAGIC(sv) || SvSTASH(sv) ? SVt_PVMG : SVt_PV;
5101         SV *const temp = newSV_type(new_type);
5102         regexp *const temp_p = ReANY((REGEXP *)sv);
5103
5104         if (new_type == SVt_PVMG) {
5105             SvMAGIC_set(temp, SvMAGIC(sv));
5106             SvMAGIC_set(sv, NULL);
5107             SvSTASH_set(temp, SvSTASH(sv));
5108             SvSTASH_set(sv, NULL);
5109         }
5110         if (!islv) SvCUR_set(temp, SvCUR(sv));
5111         /* Remember that SvPVX is in the head, not the body.  But
5112            RX_WRAPPED is in the body. */
5113         assert(ReANY((REGEXP *)sv)->mother_re);
5114         /* Their buffer is already owned by someone else. */
5115         if (flags & SV_COW_DROP_PV) {
5116             /* SvLEN is already 0.  For SVt_REGEXP, we have a brand new
5117                zeroed body.  For SVt_PVLV, it should have been set to 0
5118                before turning into a regexp. */
5119             assert(!SvLEN(islv ? sv : temp));
5120             sv->sv_u.svu_pv = 0;
5121         }
5122         else {
5123             sv->sv_u.svu_pv = savepvn(RX_WRAPPED((REGEXP *)sv), SvCUR(sv));
5124             SvLEN_set(islv ? sv : temp, SvCUR(sv)+1);
5125             SvPOK_on(sv);
5126         }
5127
5128         /* Now swap the rest of the bodies. */
5129
5130         SvFAKE_off(sv);
5131         if (!islv) {
5132             SvFLAGS(sv) &= ~SVTYPEMASK;
5133             SvFLAGS(sv) |= new_type;
5134             SvANY(sv) = SvANY(temp);
5135         }
5136
5137         SvFLAGS(temp) &= ~(SVTYPEMASK);
5138         SvFLAGS(temp) |= SVt_REGEXP|SVf_FAKE;
5139         SvANY(temp) = temp_p;
5140         temp->sv_u.svu_rx = (regexp *)temp_p;
5141
5142         SvREFCNT_dec_NN(temp);
5143     }
5144     else if (SvVOK(sv)) sv_unmagic(sv, PERL_MAGIC_vstring);
5145 }
5146
5147 /*
5148 =for apidoc sv_chop
5149
5150 Efficient removal of characters from the beginning of the string buffer.
5151 SvPOK(sv), or at least SvPOKp(sv), must be true and the C<ptr> must be a
5152 pointer to somewhere inside the string buffer.  The C<ptr> becomes the first
5153 character of the adjusted string.  Uses the "OOK hack".  On return, only
5154 SvPOK(sv) and SvPOKp(sv) among the OK flags will be true.
5155
5156 Beware: after this function returns, C<ptr> and SvPVX_const(sv) may no longer
5157 refer to the same chunk of data.
5158
5159 The unfortunate similarity of this function's name to that of Perl's C<chop>
5160 operator is strictly coincidental.  This function works from the left;
5161 C<chop> works from the right.
5162
5163 =cut
5164 */
5165
5166 void
5167 Perl_sv_chop(pTHX_ SV *const sv, const char *const ptr)
5168 {
5169     STRLEN delta;
5170     STRLEN old_delta;
5171     U8 *p;
5172 #ifdef DEBUGGING
5173     const U8 *evacp;
5174     STRLEN evacn;
5175 #endif
5176     STRLEN max_delta;
5177
5178     PERL_ARGS_ASSERT_SV_CHOP;
5179
5180     if (!ptr || !SvPOKp(sv))
5181         return;
5182     delta = ptr - SvPVX_const(sv);
5183     if (!delta) {
5184         /* Nothing to do.  */
5185         return;
5186     }
5187     max_delta = SvLEN(sv) ? SvLEN(sv) : SvCUR(sv);
5188     if (delta > max_delta)
5189         Perl_croak(aTHX_ "panic: sv_chop ptr=%p, start=%p, end=%p",
5190                    ptr, SvPVX_const(sv), SvPVX_const(sv) + max_delta);
5191     /* SvPVX(sv) may move in SV_CHECK_THINKFIRST(sv), so don't use ptr any more */
5192     SV_CHECK_THINKFIRST(sv);
5193     SvPOK_only_UTF8(sv);
5194
5195     if (!SvOOK(sv)) {
5196         if (!SvLEN(sv)) { /* make copy of shared string */
5197             const char *pvx = SvPVX_const(sv);
5198             const STRLEN len = SvCUR(sv);
5199             SvGROW(sv, len + 1);
5200             Move(pvx,SvPVX(sv),len,char);
5201             *SvEND(sv) = '\0';
5202         }
5203         SvOOK_on(sv);
5204         old_delta = 0;
5205     } else {
5206         SvOOK_offset(sv, old_delta);
5207     }
5208     SvLEN_set(sv, SvLEN(sv) - delta);
5209     SvCUR_set(sv, SvCUR(sv) - delta);
5210     SvPV_set(sv, SvPVX(sv) + delta);
5211
5212     p = (U8 *)SvPVX_const(sv);
5213
5214 #ifdef DEBUGGING
5215     /* how many bytes were evacuated?  we will fill them with sentinel
5216        bytes, except for the part holding the new offset of course. */
5217     evacn = delta;
5218     if (old_delta)
5219         evacn += (old_delta < 0x100 ? 1 : 1 + sizeof(STRLEN));
5220     assert(evacn);
5221     assert(evacn <= delta + old_delta);
5222     evacp = p - evacn;
5223 #endif
5224
5225     /* This sets 'delta' to the accumulated value of all deltas so far */
5226     delta += old_delta;
5227     assert(delta);
5228
5229     /* If 'delta' fits in a byte, store it just prior to the new beginning of
5230      * the string; otherwise store a 0 byte there and store 'delta' just prior
5231      * to that, using as many bytes as a STRLEN occupies.  Thus it overwrites a
5232      * portion of the chopped part of the string */
5233     if (delta < 0x100) {
5234         *--p = (U8) delta;
5235     } else {
5236         *--p = 0;
5237         p -= sizeof(STRLEN);
5238         Copy((U8*)&delta, p, sizeof(STRLEN), U8);
5239     }
5240
5241 #ifdef DEBUGGING
5242     /* Fill the preceding buffer with sentinals to verify that no-one is
5243        using it.  */
5244     while (p > evacp) {
5245         --p;
5246         *p = (U8)PTR2UV(p);
5247     }
5248 #endif
5249 }
5250
5251 /*
5252 =for apidoc sv_catpvn
5253
5254 Concatenates the string onto the end of the string which is in the SV.  The
5255 C<len> indicates number of bytes to copy.  If the SV has the UTF-8
5256 status set, then the bytes appended should be valid UTF-8.
5257 Handles 'get' magic, but not 'set' magic.  See C<sv_catpvn_mg>.
5258
5259 =for apidoc sv_catpvn_flags
5260
5261 Concatenates the string onto the end of the string which is in the SV.  The
5262 C<len> indicates number of bytes to copy.  If the SV has the UTF-8
5263 status set, then the bytes appended should be valid UTF-8.
5264 If C<flags> has the C<SV_SMAGIC> bit set, will
5265 C<mg_set> on C<dsv> afterwards if appropriate.
5266 C<sv_catpvn> and C<sv_catpvn_nomg> are implemented
5267 in terms of this function.
5268
5269 =cut
5270 */
5271
5272 void
5273 Perl_sv_catpvn_flags(pTHX_ SV *const dsv, const char *sstr, const STRLEN slen, const I32 flags)
5274 {
5275     STRLEN dlen;
5276     const char * const dstr = SvPV_force_flags(dsv, dlen, flags);
5277
5278     PERL_ARGS_ASSERT_SV_CATPVN_FLAGS;
5279     assert((flags & (SV_CATBYTES|SV_CATUTF8)) != (SV_CATBYTES|SV_CATUTF8));
5280
5281     if (!(flags & SV_CATBYTES) || !SvUTF8(dsv)) {
5282       if (flags & SV_CATUTF8 && !SvUTF8(dsv)) {
5283          sv_utf8_upgrade_flags_grow(dsv, 0, slen + 1);
5284          dlen = SvCUR(dsv);
5285       }
5286       else SvGROW(dsv, dlen + slen + 1);
5287       if (sstr == dstr)
5288         sstr = SvPVX_const(dsv);
5289       Move(sstr, SvPVX(dsv) + dlen, slen, char);
5290       SvCUR_set(dsv, SvCUR(dsv) + slen);
5291     }
5292     else {
5293         /* We inline bytes_to_utf8, to avoid an extra malloc. */
5294         const char * const send = sstr + slen;
5295         U8 *d;
5296
5297         /* Something this code does not account for, which I think is
5298            impossible; it would require the same pv to be treated as
5299            bytes *and* utf8, which would indicate a bug elsewhere. */
5300         assert(sstr != dstr);
5301
5302         SvGROW(dsv, dlen + slen * 2 + 1);
5303         d = (U8 *)SvPVX(dsv) + dlen;
5304
5305         while (sstr < send) {
5306             append_utf8_from_native_byte(*sstr, &d);
5307             sstr++;
5308         }
5309         SvCUR_set(dsv, d-(const U8 *)SvPVX(dsv));
5310     }
5311     *SvEND(dsv) = '\0';
5312     (void)SvPOK_only_UTF8(dsv);         /* validate pointer */
5313     SvTAINT(dsv);
5314     if (flags & SV_SMAGIC)
5315         SvSETMAGIC(dsv);
5316 }
5317
5318 /*
5319 =for apidoc sv_catsv
5320
5321 Concatenates the string from SV C<ssv> onto the end of the string in SV
5322 C<dsv>.  If C<ssv> is null, does nothing; otherwise modifies only C<dsv>.
5323 Handles 'get' magic on both SVs, but no 'set' magic.  See C<sv_catsv_mg> and
5324 C<sv_catsv_nomg>.
5325
5326 =for apidoc sv_catsv_flags
5327
5328 Concatenates the string from SV C<ssv> onto the end of the string in SV
5329 C<dsv>.  If C<ssv> is null, does nothing; otherwise modifies only C<dsv>.
5330 If C<flags> include C<SV_GMAGIC> bit set, will call C<mg_get> on both SVs if
5331 appropriate.  If C<flags> include C<SV_SMAGIC>, C<mg_set> will be called on
5332 the modified SV afterward, if appropriate.  C<sv_catsv>, C<sv_catsv_nomg>,
5333 and C<sv_catsv_mg> are implemented in terms of this function.
5334
5335 =cut */
5336
5337 void
5338 Perl_sv_catsv_flags(pTHX_ SV *const dsv, SV *const ssv, const I32 flags)
5339 {
5340     PERL_ARGS_ASSERT_SV_CATSV_FLAGS;
5341
5342     if (ssv) {
5343         STRLEN slen;
5344         const char *spv = SvPV_flags_const(ssv, slen, flags);
5345         if (spv) {
5346             if (flags & SV_GMAGIC)
5347                 SvGETMAGIC(dsv);
5348             sv_catpvn_flags(dsv, spv, slen,
5349                             DO_UTF8(ssv) ? SV_CATUTF8 : SV_CATBYTES);
5350             if (flags & SV_SMAGIC)
5351                 SvSETMAGIC(dsv);
5352         }
5353     }
5354 }
5355
5356 /*
5357 =for apidoc sv_catpv
5358
5359 Concatenates the C<NUL>-terminated string onto the end of the string which is
5360 in the SV.
5361 If the SV has the UTF-8 status set, then the bytes appended should be
5362 valid UTF-8.  Handles 'get' magic, but not 'set' magic.  See C<sv_catpv_mg>.
5363
5364 =cut */
5365
5366 void
5367 Perl_sv_catpv(pTHX_ SV *const sv, const char *ptr)
5368 {
5369     STRLEN len;
5370     STRLEN tlen;
5371     char *junk;
5372
5373     PERL_ARGS_ASSERT_SV_CATPV;
5374
5375     if (!ptr)
5376         return;
5377     junk = SvPV_force(sv, tlen);
5378     len = strlen(ptr);
5379     SvGROW(sv, tlen + len + 1);
5380     if (ptr == junk)
5381         ptr = SvPVX_const(sv);
5382     Move(ptr,SvPVX(sv)+tlen,len+1,char);
5383     SvCUR_set(sv, SvCUR(sv) + len);
5384     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
5385     SvTAINT(sv);
5386 }
5387
5388 /*
5389 =for apidoc sv_catpv_flags
5390
5391 Concatenates the C<NUL>-terminated string onto the end of the string which is
5392 in the SV.
5393 If the SV has the UTF-8 status set, then the bytes appended should
5394 be valid UTF-8.  If C<flags> has the C<SV_SMAGIC> bit set, will C<mg_set>
5395 on the modified SV if appropriate.
5396
5397 =cut
5398 */
5399
5400 void
5401 Perl_sv_catpv_flags(pTHX_ SV *dstr, const char *sstr, const I32 flags)
5402 {
5403     PERL_ARGS_ASSERT_SV_CATPV_FLAGS;
5404     sv_catpvn_flags(dstr, sstr, strlen(sstr), flags);
5405 }
5406
5407 /*
5408 =for apidoc sv_catpv_mg
5409
5410 Like C<sv_catpv>, but also handles 'set' magic.
5411
5412 =cut
5413 */
5414
5415 void
5416 Perl_sv_catpv_mg(pTHX_ SV *const sv, const char *const ptr)
5417 {
5418     PERL_ARGS_ASSERT_SV_CATPV_MG;
5419
5420     sv_catpv(sv,ptr);
5421     SvSETMAGIC(sv);
5422 }
5423
5424 /*
5425 =for apidoc newSV
5426
5427 Creates a new SV.  A non-zero C<len> parameter indicates the number of
5428 bytes of preallocated string space the SV should have.  An extra byte for a
5429 trailing C<NUL> is also reserved.  (SvPOK is not set for the SV even if string
5430 space is allocated.)  The reference count for the new SV is set to 1.
5431
5432 In 5.9.3, newSV() replaces the older NEWSV() API, and drops the first
5433 parameter, I<x>, a debug aid which allowed callers to identify themselves.
5434 This aid has been superseded by a new build option, PERL_MEM_LOG (see
5435 L<perlhacktips/PERL_MEM_LOG>).  The older API is still there for use in XS
5436 modules supporting older perls.
5437
5438 =cut
5439 */
5440
5441 SV *
5442 Perl_newSV(pTHX_ const STRLEN len)
5443 {
5444     SV *sv;
5445
5446     new_SV(sv);
5447     if (len) {
5448         sv_upgrade(sv, SVt_PV);
5449         SvGROW(sv, len + 1);
5450     }
5451     return sv;
5452 }
5453 /*
5454 =for apidoc sv_magicext
5455
5456 Adds magic to an SV, upgrading it if necessary.  Applies the
5457 supplied vtable and returns a pointer to the magic added.
5458
5459 Note that C<sv_magicext> will allow things that C<sv_magic> will not.
5460 In particular, you can add magic to SvREADONLY SVs, and add more than
5461 one instance of the same 'how'.
5462
5463 If C<namlen> is greater than zero then a C<savepvn> I<copy> of C<name> is
5464 stored, if C<namlen> is zero then C<name> is stored as-is and - as another
5465 special case - if C<(name && namlen == HEf_SVKEY)> then C<name> is assumed
5466 to contain an C<SV*> and is stored as-is with its REFCNT incremented.
5467
5468 (This is now used as a subroutine by C<sv_magic>.)
5469
5470 =cut
5471 */
5472 MAGIC * 
5473 Perl_sv_magicext(pTHX_ SV *const sv, SV *const obj, const int how, 
5474                 const MGVTBL *const vtable, const char *const name, const I32 namlen)
5475 {
5476     MAGIC* mg;
5477
5478     PERL_ARGS_ASSERT_SV_MAGICEXT;
5479
5480     if (SvTYPE(sv)==SVt_PVAV) { assert (!AvPAD_NAMELIST(sv)); }
5481
5482     SvUPGRADE(sv, SVt_PVMG);
5483     Newxz(mg, 1, MAGIC);
5484     mg->mg_moremagic = SvMAGIC(sv);
5485     SvMAGIC_set(sv, mg);
5486
5487     /* Sometimes a magic contains a reference loop, where the sv and
5488        object refer to each other.  To prevent a reference loop that
5489        would prevent such objects being freed, we look for such loops
5490        and if we find one we avoid incrementing the object refcount.
5491
5492        Note we cannot do this to avoid self-tie loops as intervening RV must
5493        have its REFCNT incremented to keep it in existence.
5494
5495     */
5496     if (!obj || obj == sv ||
5497         how == PERL_MAGIC_arylen ||
5498         how == PERL_MAGIC_symtab ||
5499         (SvTYPE(obj) == SVt_PVGV &&
5500             (GvSV(obj) == sv || GvHV(obj) == (const HV *)sv
5501              || GvAV(obj) == (const AV *)sv || GvCV(obj) == (const CV *)sv
5502              || GvIOp(obj) == (const IO *)sv || GvFORM(obj) == (const CV *)sv)))
5503     {
5504         mg->mg_obj = obj;
5505     }
5506     else {
5507         mg->mg_obj = SvREFCNT_inc_simple(obj);
5508         mg->mg_flags |= MGf_REFCOUNTED;
5509     }
5510
5511     /* Normal self-ties simply pass a null object, and instead of
5512        using mg_obj directly, use the SvTIED_obj macro to produce a
5513        new RV as needed.  For glob "self-ties", we are tieing the PVIO
5514        with an RV obj pointing to the glob containing the PVIO.  In
5515        this case, to avoid a reference loop, we need to weaken the
5516        reference.
5517     */
5518
5519     if (how == PERL_MAGIC_tiedscalar && SvTYPE(sv) == SVt_PVIO &&
5520         obj && SvROK(obj) && GvIO(SvRV(obj)) == (const IO *)sv)
5521     {
5522       sv_rvweaken(obj);
5523     }
5524
5525     mg->mg_type = how;
5526     mg->mg_len = namlen;
5527     if (name) {
5528         if (namlen > 0)
5529             mg->mg_ptr = savepvn(name, namlen);
5530         else if (namlen == HEf_SVKEY) {
5531             /* Yes, this is casting away const. This is only for the case of
5532                HEf_SVKEY. I think we need to document this aberation of the
5533                constness of the API, rather than making name non-const, as
5534                that change propagating outwards a long way.  */
5535             mg->mg_ptr = (char*)SvREFCNT_inc_simple_NN((SV *)name);
5536         } else
5537             mg->mg_ptr = (char *) name;
5538     }
5539     mg->mg_virtual = (MGVTBL *) vtable;
5540
5541     mg_magical(sv);
5542     return mg;
5543 }
5544
5545 MAGIC *
5546 Perl_sv_magicext_mglob(pTHX_ SV *sv)
5547 {
5548     PERL_ARGS_ASSERT_SV_MAGICEXT_MGLOB;
5549     if (SvTYPE(sv) == SVt_PVLV && LvTYPE(sv) == 'y') {
5550         /* This sv is only a delegate.  //g magic must be attached to
5551            its target. */
5552         vivify_defelem(sv);
5553         sv = LvTARG(sv);
5554     }
5555 #ifdef PERL_OLD_COPY_ON_WRITE
5556     if (SvIsCOW(sv))
5557         sv_force_normal_flags(sv, 0);
5558 #endif
5559     return sv_magicext(sv, NULL, PERL_MAGIC_regex_global,
5560                        &PL_vtbl_mglob, 0, 0);
5561 }
5562
5563 /*
5564 =for apidoc sv_magic
5565
5566 Adds magic to an SV.  First upgrades C<sv> to type C<SVt_PVMG> if
5567 necessary, then adds a new magic item of type C<how> to the head of the
5568 magic list.
5569
5570 See C<sv_magicext> (which C<sv_magic> now calls) for a description of the
5571 handling of the C<name> and C<namlen> arguments.
5572
5573 You need to use C<sv_magicext> to add magic to SvREADONLY SVs and also
5574 to add more than one instance of the same 'how'.
5575
5576 =cut
5577 */
5578
5579 void
5580 Perl_sv_magic(pTHX_ SV *const sv, SV *const obj, const int how,
5581              const char *const name, const I32 namlen)
5582 {
5583     const MGVTBL *vtable;
5584     MAGIC* mg;
5585     unsigned int flags;
5586     unsigned int vtable_index;
5587
5588     PERL_ARGS_ASSERT_SV_MAGIC;
5589
5590     if (how < 0 || (unsigned)how >= C_ARRAY_LENGTH(PL_magic_data)
5591         || ((flags = PL_magic_data[how]),
5592             (vtable_index = flags & PERL_MAGIC_VTABLE_MASK)
5593             > magic_vtable_max))
5594         Perl_croak(aTHX_ "Don't know how to handle magic of type \\%o", how);
5595
5596     /* PERL_MAGIC_ext is reserved for use by extensions not perl internals.
5597        Useful for attaching extension internal data to perl vars.
5598        Note that multiple extensions may clash if magical scalars
5599        etc holding private data from one are passed to another. */
5600
5601     vtable = (vtable_index == magic_vtable_max)
5602         ? NULL : PL_magic_vtables + vtable_index;
5603
5604 #ifdef PERL_OLD_COPY_ON_WRITE
5605     if (SvIsCOW(sv))
5606         sv_force_normal_flags(sv, 0);
5607 #endif
5608     if (SvREADONLY(sv)) {
5609         if (
5610             !PERL_MAGIC_TYPE_READONLY_ACCEPTABLE(how)
5611            )
5612         {
5613             Perl_croak_no_modify();
5614         }
5615     }
5616     if (SvMAGICAL(sv) || (how == PERL_MAGIC_taint && SvTYPE(sv) >= SVt_PVMG)) {
5617         if (SvMAGIC(sv) && (mg = mg_find(sv, how))) {
5618             /* sv_magic() refuses to add a magic of the same 'how' as an
5619                existing one
5620              */
5621             if (how == PERL_MAGIC_taint)
5622                 mg->mg_len |= 1;
5623             return;
5624         }
5625     }
5626
5627     /* Force pos to be stored as characters, not bytes. */
5628     if (SvMAGICAL(sv) && DO_UTF8(sv)
5629       && (mg = mg_find(sv, PERL_MAGIC_regex_global))
5630       && mg->mg_len != -1
5631       && mg->mg_flags & MGf_BYTES) {
5632         mg->mg_len = (SSize_t)sv_pos_b2u_flags(sv, (STRLEN)mg->mg_len,
5633                                                SV_CONST_RETURN);
5634         mg->mg_flags &= ~MGf_BYTES;
5635     }
5636
5637     /* Rest of work is done else where */
5638     mg = sv_magicext(sv,obj,how,vtable,name,namlen);
5639
5640     switch (how) {
5641     case PERL_MAGIC_taint:
5642         mg->mg_len = 1;
5643         break;
5644     case PERL_MAGIC_ext:
5645     case PERL_MAGIC_dbfile:
5646         SvRMAGICAL_on(sv);
5647         break;
5648     }
5649 }
5650
5651 static int
5652 S_sv_unmagicext_flags(pTHX_ SV *const sv, const int type, MGVTBL *vtbl, const U32 flags)
5653 {
5654     MAGIC* mg;
5655     MAGIC** mgp;
5656
5657     assert(flags <= 1);
5658
5659     if (SvTYPE(sv) < SVt_PVMG || !SvMAGIC(sv))
5660         return 0;
5661     mgp = &(((XPVMG*) SvANY(sv))->xmg_u.xmg_magic);
5662     for (mg = *mgp; mg; mg = *mgp) {
5663         const MGVTBL* const virt = mg->mg_virtual;
5664         if (mg->mg_type == type && (!flags || virt == vtbl)) {
5665             *mgp = mg->mg_moremagic;
5666             if (virt && virt->svt_free)
5667                 virt->svt_free(aTHX_ sv, mg);
5668             if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) {
5669                 if (mg->mg_len > 0)
5670                     Safefree(mg->mg_ptr);
5671                 else if (mg->mg_len == HEf_SVKEY)
5672                     SvREFCNT_dec(MUTABLE_SV(mg->mg_ptr));
5673                 else if (mg->mg_type == PERL_MAGIC_utf8)
5674                     Safefree(mg->mg_ptr);
5675             }
5676             if (mg->mg_flags & MGf_REFCOUNTED)
5677                 SvREFCNT_dec(mg->mg_obj);
5678             Safefree(mg);
5679         }
5680         else
5681             mgp = &mg->mg_moremagic;
5682     }
5683     if (SvMAGIC(sv)) {
5684         if (SvMAGICAL(sv))      /* if we're under save_magic, wait for restore_magic; */
5685             mg_magical(sv);     /*    else fix the flags now */
5686     }
5687     else {
5688         SvMAGICAL_off(sv);
5689         SvFLAGS(sv) |= (SvFLAGS(sv) & (SVp_IOK|SVp_NOK|SVp_POK)) >> PRIVSHIFT;
5690     }
5691     return 0;
5692 }
5693
5694 /*
5695 =for apidoc sv_unmagic
5696
5697 Removes all magic of type C<type> from an SV.
5698
5699 =cut
5700 */
5701
5702 int
5703 Perl_sv_unmagic(pTHX_ SV *const sv, const int type)
5704 {
5705     PERL_ARGS_ASSERT_SV_UNMAGIC;
5706     return S_sv_unmagicext_flags(aTHX_ sv, type, NULL, 0);
5707 }
5708
5709 /*
5710 =for apidoc sv_unmagicext
5711
5712 Removes all magic of type C<type> with the specified C<vtbl> from an SV.
5713
5714 =cut
5715 */
5716
5717 int
5718 Perl_sv_unmagicext(pTHX_ SV *const sv, const int type, MGVTBL *vtbl)
5719 {
5720     PERL_ARGS_ASSERT_SV_UNMAGICEXT;
5721     return S_sv_unmagicext_flags(aTHX_ sv, type, vtbl, 1);
5722 }
5723
5724 /*
5725 =for apidoc sv_rvweaken
5726
5727 Weaken a reference: set the C<SvWEAKREF> flag on this RV; give the
5728 referred-to SV C<PERL_MAGIC_backref> magic if it hasn't already; and
5729 push a back-reference to this RV onto the array of backreferences
5730 associated with that magic.  If the RV is magical, set magic will be
5731 called after the RV is cleared.
5732
5733 =cut
5734 */
5735
5736 SV *
5737 Perl_sv_rvweaken(pTHX_ SV *const sv)
5738 {
5739     SV *tsv;
5740
5741     PERL_ARGS_ASSERT_SV_RVWEAKEN;
5742
5743     if (!SvOK(sv))  /* let undefs pass */
5744         return sv;
5745     if (!SvROK(sv))
5746         Perl_croak(aTHX_ "Can't weaken a nonreference");
5747     else if (SvWEAKREF(sv)) {
5748         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Reference is already weak");
5749         return sv;
5750     }
5751     else if (SvREADONLY(sv)) croak_no_modify();
5752     tsv = SvRV(sv);
5753     Perl_sv_add_backref(aTHX_ tsv, sv);
5754     SvWEAKREF_on(sv);
5755     SvREFCNT_dec_NN(tsv);
5756     return sv;
5757 }
5758
5759 /* Give tsv backref magic if it hasn't already got it, then push a
5760  * back-reference to sv onto the array associated with the backref magic.
5761  *
5762  * As an optimisation, if there's only one backref and it's not an AV,
5763  * store it directly in the HvAUX or mg_obj slot, avoiding the need to
5764  * allocate an AV. (Whether the slot holds an AV tells us whether this is
5765  * active.)
5766  */
5767
5768 /* A discussion about the backreferences array and its refcount:
5769  *
5770  * The AV holding the backreferences is pointed to either as the mg_obj of
5771  * PERL_MAGIC_backref, or in the specific case of a HV, from the
5772  * xhv_backreferences field. The array is created with a refcount
5773  * of 2. This means that if during global destruction the array gets
5774  * picked on before its parent to have its refcount decremented by the
5775  * random zapper, it won't actually be freed, meaning it's still there for
5776  * when its parent gets freed.
5777  *
5778  * When the parent SV is freed, the extra ref is killed by
5779  * Perl_sv_kill_backrefs.  The other ref is killed, in the case of magic,
5780  * by mg_free() / MGf_REFCOUNTED, or for a hash, by Perl_hv_kill_backrefs.
5781  *
5782  * When a single backref SV is stored directly, it is not reference
5783  * counted.
5784  */
5785
5786 void
5787 Perl_sv_add_backref(pTHX_ SV *const tsv, SV *const sv)
5788 {
5789     SV **svp;
5790     AV *av = NULL;
5791     MAGIC *mg = NULL;
5792
5793     PERL_ARGS_ASSERT_SV_ADD_BACKREF;
5794
5795     /* find slot to store array or singleton backref */
5796
5797     if (SvTYPE(tsv) == SVt_PVHV) {
5798         svp = (SV**)Perl_hv_backreferences_p(aTHX_ MUTABLE_HV(tsv));
5799     } else {
5800         if (SvMAGICAL(tsv))
5801             mg = mg_find(tsv, PERL_MAGIC_backref);
5802         if (!mg)
5803             mg = sv_magicext(tsv, NULL, PERL_MAGIC_backref, &PL_vtbl_backref, NULL, 0);
5804         svp = &(mg->mg_obj);
5805     }
5806
5807     /* create or retrieve the array */
5808
5809     if (   (!*svp && SvTYPE(sv) == SVt_PVAV)
5810         || (*svp && SvTYPE(*svp) != SVt_PVAV)
5811     ) {
5812         /* create array */
5813         if (mg)
5814             mg->mg_flags |= MGf_REFCOUNTED;
5815         av = newAV();
5816         AvREAL_off(av);
5817         SvREFCNT_inc_simple_void_NN(av);
5818         /* av now has a refcnt of 2; see discussion above */
5819         av_extend(av, *svp ? 2 : 1);
5820         if (*svp) {
5821             /* move single existing backref to the array */
5822             AvARRAY(av)[++AvFILLp(av)] = *svp; /* av_push() */
5823         }
5824         *svp = (SV*)av;
5825     }
5826     else {
5827         av = MUTABLE_AV(*svp);
5828         if (!av) {
5829             /* optimisation: store single backref directly in HvAUX or mg_obj */
5830             *svp = sv;
5831             return;
5832         }
5833         assert(SvTYPE(av) == SVt_PVAV);
5834         if (AvFILLp(av) >= AvMAX(av)) {
5835             av_extend(av, AvFILLp(av)+1);
5836         }
5837     }
5838     /* push new backref */
5839     AvARRAY(av)[++AvFILLp(av)] = sv; /* av_push() */
5840 }
5841
5842 /* delete a back-reference to ourselves from the backref magic associated
5843  * with the SV we point to.
5844  */
5845
5846 void
5847 Perl_sv_del_backref(pTHX_ SV *const tsv, SV *const sv)
5848 {
5849     SV **svp = NULL;
5850
5851     PERL_ARGS_ASSERT_SV_DEL_BACKREF;
5852
5853     if (SvTYPE(tsv) == SVt_PVHV) {
5854         if (SvOOK(tsv))
5855             svp = (SV**)Perl_hv_backreferences_p(aTHX_ MUTABLE_HV(tsv));
5856     }
5857     else if (SvIS_FREED(tsv) && PL_phase == PERL_PHASE_DESTRUCT) {
5858         /* It's possible for the the last (strong) reference to tsv to have
5859            become freed *before* the last thing holding a weak reference.
5860            If both survive longer than the backreferences array, then when
5861            the referent's reference count drops to 0 and it is freed, it's
5862            not able to chase the backreferences, so they aren't NULLed.
5863
5864            For example, a CV holds a weak reference to its stash. If both the
5865            CV and the stash survive longer than the backreferences array,
5866            and the CV gets picked for the SvBREAK() treatment first,
5867            *and* it turns out that the stash is only being kept alive because
5868            of an our variable in the pad of the CV, then midway during CV
5869            destruction the stash gets freed, but CvSTASH() isn't set to NULL.
5870            It ends up pointing to the freed HV. Hence it's chased in here, and
5871            if this block wasn't here, it would hit the !svp panic just below.
5872
5873            I don't believe that "better" destruction ordering is going to help
5874            here - during global destruction there's always going to be the
5875            chance that something goes out of order. We've tried to make it
5876            foolproof before, and it only resulted in evolutionary pressure on
5877            fools. Which made us look foolish for our hubris. :-(
5878         */
5879         return;
5880     }
5881     else {
5882         MAGIC *const mg
5883             = SvMAGICAL(tsv) ? mg_find(tsv, PERL_MAGIC_backref) : NULL;
5884         svp =  mg ? &(mg->mg_obj) : NULL;
5885     }
5886
5887     if (!svp)
5888         Perl_croak(aTHX_ "panic: del_backref, svp=0");
5889     if (!*svp) {
5890         /* It's possible that sv is being freed recursively part way through the
5891            freeing of tsv. If this happens, the backreferences array of tsv has
5892            already been freed, and so svp will be NULL. If this is the case,
5893            we should not panic. Instead, nothing needs doing, so return.  */
5894         if (PL_phase == PERL_PHASE_DESTRUCT && SvREFCNT(tsv) == 0)
5895             return;
5896         Perl_croak(aTHX_ "panic: del_backref, *svp=%p phase=%s refcnt=%" UVuf,
5897                    (void*)*svp, PL_phase_names[PL_phase], (UV)SvREFCNT(tsv));
5898     }
5899
5900     if (SvTYPE(*svp) == SVt_PVAV) {
5901 #ifdef DEBUGGING
5902         int count = 1;
5903 #endif
5904         AV * const av = (AV*)*svp;
5905         SSize_t fill;
5906         assert(!SvIS_FREED(av));
5907         fill = AvFILLp(av);
5908         assert(fill > -1);
5909         svp = AvARRAY(av);
5910         /* for an SV with N weak references to it, if all those
5911          * weak refs are deleted, then sv_del_backref will be called
5912          * N times and O(N^2) compares will be done within the backref
5913          * array. To ameliorate this potential slowness, we:
5914          * 1) make sure this code is as tight as possible;
5915          * 2) when looking for SV, look for it at both the head and tail of the
5916          *    array first before searching the rest, since some create/destroy
5917          *    patterns will cause the backrefs to be freed in order.
5918          */
5919         if (*svp == sv) {
5920             AvARRAY(av)++;
5921             AvMAX(av)--;
5922         }
5923         else {
5924             SV **p = &svp[fill];
5925             SV *const topsv = *p;
5926             if (topsv != sv) {
5927 #ifdef DEBUGGING
5928                 count = 0;
5929 #endif
5930                 while (--p > svp) {
5931                     if (*p == sv) {
5932                         /* We weren't the last entry.
5933                            An unordered list has this property that you
5934                            can take the last element off the end to fill
5935                            the hole, and it's still an unordered list :-)
5936                         */
5937                         *p = topsv;
5938 #ifdef DEBUGGING
5939                         count++;
5940 #else
5941                         break; /* should only be one */
5942 #endif
5943                     }
5944                 }
5945             }
5946         }
5947         assert(count ==1);
5948         AvFILLp(av) = fill-1;
5949     }
5950     else if (SvIS_FREED(*svp) && PL_phase == PERL_PHASE_DESTRUCT) {
5951         /* freed AV; skip */
5952     }
5953     else {
5954         /* optimisation: only a single backref, stored directly */
5955         if (*svp != sv)
5956             Perl_croak(aTHX_ "panic: del_backref, *svp=%p, sv=%p",
5957                        (void*)*svp, (void*)sv);
5958         *svp = NULL;
5959     }
5960
5961 }
5962
5963 void
5964 Perl_sv_kill_backrefs(pTHX_ SV *const sv, AV *const av)
5965 {
5966     SV **svp;
5967     SV **last;
5968     bool is_array;
5969
5970     PERL_ARGS_ASSERT_SV_KILL_BACKREFS;
5971
5972     if (!av)
5973         return;
5974
5975     /* after multiple passes through Perl_sv_clean_all() for a thingy
5976      * that has badly leaked, the backref array may have gotten freed,
5977      * since we only protect it against 1 round of cleanup */
5978     if (SvIS_FREED(av)) {
5979         if (PL_in_clean_all) /* All is fair */
5980             return;
5981         Perl_croak(aTHX_
5982                    "panic: magic_killbackrefs (freed backref AV/SV)");
5983     }
5984
5985
5986     is_array = (SvTYPE(av) == SVt_PVAV);
5987     if (is_array) {
5988         assert(!SvIS_FREED(av));
5989         svp = AvARRAY(av);
5990         if (svp)
5991             last = svp + AvFILLp(av);
5992     }
5993     else {
5994         /* optimisation: only a single backref, stored directly */
5995         svp = (SV**)&av;
5996         last = svp;
5997     }
5998
5999     if (svp) {
6000         while (svp <= last) {
6001             if (*svp) {
6002                 SV *const referrer = *svp;
6003                 if (SvWEAKREF(referrer)) {
6004                     /* XXX Should we check that it hasn't changed? */
6005                     assert(SvROK(referrer));
6006                     SvRV_set(referrer, 0);
6007                     SvOK_off(referrer);
6008                     SvWEAKREF_off(referrer);
6009                     SvSETMAGIC(referrer);
6010                 } else if (SvTYPE(referrer) == SVt_PVGV ||
6011                            SvTYPE(referrer) == SVt_PVLV) {
6012                     assert(SvTYPE(sv) == SVt_PVHV); /* stash backref */
6013                     /* You lookin' at me?  */
6014                     assert(GvSTASH(referrer));
6015                     assert(GvSTASH(referrer) == (const HV *)sv);
6016                     GvSTASH(referrer) = 0;
6017                 } else if (SvTYPE(referrer) == SVt_PVCV ||
6018                            SvTYPE(referrer) == SVt_PVFM) {
6019                     if (SvTYPE(sv) == SVt_PVHV) { /* stash backref */
6020                         /* You lookin' at me?  */
6021                         assert(CvSTASH(referrer));
6022                         assert(CvSTASH(referrer) == (const HV *)sv);
6023                         SvANY(MUTABLE_CV(referrer))->xcv_stash = 0;
6024                     }
6025                     else {
6026                         assert(SvTYPE(sv) == SVt_PVGV);
6027                         /* You lookin' at me?  */
6028                         assert(CvGV(referrer));
6029                         assert(CvGV(referrer) == (const GV *)sv);
6030                         anonymise_cv_maybe(MUTABLE_GV(sv),
6031                                                 MUTABLE_CV(referrer));
6032                     }
6033
6034                 } else {
6035                     Perl_croak(aTHX_
6036                                "panic: magic_killbackrefs (flags=%"UVxf")",
6037                                (UV)SvFLAGS(referrer));
6038                 }
6039
6040                 if (is_array)
6041                     *svp = NULL;
6042             }
6043             svp++;
6044         }
6045     }
6046     if (is_array) {
6047         AvFILLp(av) = -1;
6048         SvREFCNT_dec_NN(av); /* remove extra count added by sv_add_backref() */
6049     }
6050     return;
6051 }
6052
6053 /*
6054 =for apidoc sv_insert
6055
6056 Inserts a string at the specified offset/length within the SV.  Similar to
6057 the Perl substr() function.  Handles get magic.
6058
6059 =for apidoc sv_insert_flags
6060
6061 Same as C<sv_insert>, but the extra C<flags> are passed to the
6062 C<SvPV_force_flags> that applies to C<bigstr>.
6063
6064 =cut
6065 */
6066
6067 void
6068 Perl_sv_insert_flags(pTHX_ SV *const bigstr, const STRLEN offset, const STRLEN len, const char *const little, const STRLEN littlelen, const U32 flags)
6069 {
6070     char *big;
6071     char *mid;
6072     char *midend;
6073     char *bigend;
6074     SSize_t i;          /* better be sizeof(STRLEN) or bad things happen */
6075     STRLEN curlen;
6076
6077     PERL_ARGS_ASSERT_SV_INSERT_FLAGS;
6078
6079     if (!bigstr)
6080         Perl_croak(aTHX_ "Can't modify nonexistent substring");
6081     SvPV_force_flags(bigstr, curlen, flags);
6082     (void)SvPOK_only_UTF8(bigstr);
6083     if (offset + len > curlen) {
6084         SvGROW(bigstr, offset+len+1);
6085         Zero(SvPVX(bigstr)+curlen, offset+len-curlen, char);
6086         SvCUR_set(bigstr, offset+len);
6087     }
6088
6089     SvTAINT(bigstr);
6090     i = littlelen - len;
6091     if (i > 0) {                        /* string might grow */
6092         big = SvGROW(bigstr, SvCUR(bigstr) + i + 1);
6093         mid = big + offset + len;
6094         midend = bigend = big + SvCUR(bigstr);
6095         bigend += i;
6096         *bigend = '\0';
6097         while (midend > mid)            /* shove everything down */
6098             *--bigend = *--midend;
6099         Move(little,big+offset,littlelen,char);
6100         SvCUR_set(bigstr, SvCUR(bigstr) + i);
6101         SvSETMAGIC(bigstr);
6102         return;
6103     }
6104     else if (i == 0) {
6105         Move(little,SvPVX(bigstr)+offset,len,char);
6106         SvSETMAGIC(bigstr);
6107         return;
6108     }
6109
6110     big = SvPVX(bigstr);
6111     mid = big + offset;
6112     midend = mid + len;
6113     bigend = big + SvCUR(bigstr);
6114
6115     if (midend > bigend)
6116         Perl_croak(aTHX_ "panic: sv_insert, midend=%p, bigend=%p",
6117                    midend, bigend);
6118
6119     if (mid - big > bigend - midend) {  /* faster to shorten from end */
6120         if (littlelen) {
6121             Move(little, mid, littlelen,char);
6122             mid += littlelen;
6123         }
6124         i = bigend - midend;
6125         if (i > 0) {
6126             Move(midend, mid, i,char);
6127             mid += i;
6128         }
6129         *mid = '\0';
6130         SvCUR_set(bigstr, mid - big);
6131     }
6132     else if ((i = mid - big)) { /* faster from front */
6133         midend -= littlelen;
6134         mid = midend;
6135         Move(big, midend - i, i, char);
6136         sv_chop(bigstr,midend-i);
6137         if (littlelen)
6138             Move(little, mid, littlelen,char);
6139     }
6140     else if (littlelen) {
6141         midend -= littlelen;
6142         sv_chop(bigstr,midend);
6143         Move(little,midend,littlelen,char);
6144     }
6145     else {
6146         sv_chop(bigstr,midend);
6147     }
6148     SvSETMAGIC(bigstr);
6149 }
6150
6151 /*
6152 =for apidoc sv_replace
6153
6154 Make the first argument a copy of the second, then delete the original.
6155 The target SV physically takes over ownership of the body of the source SV
6156 and inherits its flags; however, the target keeps any magic it owns,
6157 and any magic in the source is discarded.
6158 Note that this is a rather specialist SV copying operation; most of the
6159 time you'll want to use C<sv_setsv> or one of its many macro front-ends.
6160
6161 =cut
6162 */
6163
6164 void
6165 Perl_sv_replace(pTHX_ SV *const sv, SV *const nsv)
6166 {
6167     const U32 refcnt = SvREFCNT(sv);
6168
6169     PERL_ARGS_ASSERT_SV_REPLACE;
6170
6171     SV_CHECK_THINKFIRST_COW_DROP(sv);
6172     if (SvREFCNT(nsv) != 1) {
6173         Perl_croak(aTHX_ "panic: reference miscount on nsv in sv_replace()"
6174                    " (%" UVuf " != 1)", (UV) SvREFCNT(nsv));
6175     }
6176     if (SvMAGICAL(sv)) {
6177         if (SvMAGICAL(nsv))
6178             mg_free(nsv);
6179         else
6180             sv_upgrade(nsv, SVt_PVMG);
6181         SvMAGIC_set(nsv, SvMAGIC(sv));
6182         SvFLAGS(nsv) |= SvMAGICAL(sv);
6183         SvMAGICAL_off(sv);
6184         SvMAGIC_set(sv, NULL);
6185     }
6186     SvREFCNT(sv) = 0;
6187     sv_clear(sv);
6188     assert(!SvREFCNT(sv));
6189 #ifdef DEBUG_LEAKING_SCALARS
6190     sv->sv_flags  = nsv->sv_flags;
6191     sv->sv_any    = nsv->sv_any;
6192     sv->sv_refcnt = nsv->sv_refcnt;
6193     sv->sv_u      = nsv->sv_u;
6194 #else
6195     StructCopy(nsv,sv,SV);
6196 #endif
6197     if(SvTYPE(sv) == SVt_IV) {
6198         SvANY(sv)
6199             = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
6200     }
6201         
6202
6203 #ifdef PERL_OLD_COPY_ON_WRITE
6204     if (SvIsCOW_normal(nsv)) {
6205         /* We need to follow the pointers around the loop to make the
6206            previous SV point to sv, rather than nsv.  */
6207         SV *next;
6208         SV *current = nsv;
6209         while ((next = SV_COW_NEXT_SV(current)) != nsv) {
6210             assert(next);
6211             current = next;
6212             assert(SvPVX_const(current) == SvPVX_const(nsv));
6213         }
6214         /* Make the SV before us point to the SV after us.  */
6215         if (DEBUG_C_TEST) {
6216             PerlIO_printf(Perl_debug_log, "previous is\n");
6217             sv_dump(current);
6218             PerlIO_printf(Perl_debug_log,
6219                           "move it from 0x%"UVxf" to 0x%"UVxf"\n",
6220                           (UV) SV_COW_NEXT_SV(current), (UV) sv);
6221         }
6222         SV_COW_NEXT_SV_SET(current, sv);
6223     }
6224 #endif
6225     SvREFCNT(sv) = refcnt;
6226     SvFLAGS(nsv) |= SVTYPEMASK;         /* Mark as freed */
6227     SvREFCNT(nsv) = 0;
6228     del_SV(nsv);
6229 }
6230
6231 /* We're about to free a GV which has a CV that refers back to us.
6232  * If that CV will outlive us, make it anonymous (i.e. fix up its CvGV
6233  * field) */
6234
6235 STATIC void
6236 S_anonymise_cv_maybe(pTHX_ GV *gv, CV* cv)
6237 {
6238     SV *gvname;
6239     GV *anongv;
6240
6241     PERL_ARGS_ASSERT_ANONYMISE_CV_MAYBE;
6242
6243     /* be assertive! */
6244     assert(SvREFCNT(gv) == 0);
6245     assert(isGV(gv) && isGV_with_GP(gv));
6246     assert(GvGP(gv));
6247     assert(!CvANON(cv));
6248     assert(CvGV(cv) == gv);
6249     assert(!CvNAMED(cv));
6250
6251     /* will the CV shortly be freed by gp_free() ? */
6252     if (GvCV(gv) == cv && GvGP(gv)->gp_refcnt < 2 && SvREFCNT(cv) < 2) {
6253         SvANY(cv)->xcv_gv_u.xcv_gv = NULL;
6254         return;
6255     }
6256
6257     /* if not, anonymise: */
6258     gvname = (GvSTASH(gv) && HvNAME(GvSTASH(gv)) && HvENAME(GvSTASH(gv)))
6259                     ? newSVhek(HvENAME_HEK(GvSTASH(gv)))
6260                     : newSVpvn_flags( "__ANON__", 8, 0 );
6261     sv_catpvs(gvname, "::__ANON__");
6262     anongv = gv_fetchsv(gvname, GV_ADDMULTI, SVt_PVCV);
6263     SvREFCNT_dec_NN(gvname);
6264
6265     CvANON_on(cv);
6266     CvCVGV_RC_on(cv);
6267     SvANY(cv)->xcv_gv_u.xcv_gv = MUTABLE_GV(SvREFCNT_inc(anongv));
6268 }
6269
6270
6271 /*
6272 =for apidoc sv_clear
6273
6274 Clear an SV: call any destructors, free up any memory used by the body,
6275 and free the body itself.  The SV's head is I<not> freed, although
6276 its type is set to all 1's so that it won't inadvertently be assumed
6277 to be live during global destruction etc.
6278 This function should only be called when REFCNT is zero.  Most of the time
6279 you'll want to call C<sv_free()> (or its macro wrapper C<SvREFCNT_dec>)
6280 instead.
6281
6282 =cut
6283 */
6284
6285 void
6286 Perl_sv_clear(pTHX_ SV *const orig_sv)
6287 {
6288     dVAR;
6289     HV *stash;
6290     U32 type;
6291     const struct body_details *sv_type_details;
6292     SV* iter_sv = NULL;
6293     SV* next_sv = NULL;
6294     SV *sv = orig_sv;
6295     STRLEN hash_index;
6296
6297     PERL_ARGS_ASSERT_SV_CLEAR;
6298
6299     /* within this loop, sv is the SV currently being freed, and
6300      * iter_sv is the most recent AV or whatever that's being iterated
6301      * over to provide more SVs */
6302
6303     while (sv) {
6304
6305         type = SvTYPE(sv);
6306
6307         assert(SvREFCNT(sv) == 0);
6308         assert(SvTYPE(sv) != (svtype)SVTYPEMASK);
6309
6310         if (type <= SVt_IV) {
6311             /* See the comment in sv.h about the collusion between this
6312              * early return and the overloading of the NULL slots in the
6313              * size table.  */
6314             if (SvROK(sv))
6315                 goto free_rv;
6316             SvFLAGS(sv) &= SVf_BREAK;
6317             SvFLAGS(sv) |= SVTYPEMASK;
6318             goto free_head;
6319         }
6320
6321         assert(!SvOBJECT(sv) || type >= SVt_PVMG); /* objs are always >= MG */
6322
6323         if (type >= SVt_PVMG) {
6324             if (SvOBJECT(sv)) {
6325                 if (!curse(sv, 1)) goto get_next_sv;
6326                 type = SvTYPE(sv); /* destructor may have changed it */
6327             }
6328             /* Free back-references before magic, in case the magic calls
6329              * Perl code that has weak references to sv. */
6330             if (type == SVt_PVHV) {
6331                 Perl_hv_kill_backrefs(aTHX_ MUTABLE_HV(sv));
6332                 if (SvMAGIC(sv))
6333                     mg_free(sv);
6334             }
6335             else if (type == SVt_PVMG && SvPAD_OUR(sv)) {
6336                 SvREFCNT_dec(SvOURSTASH(sv));
6337             }
6338             else if (type == SVt_PVAV && AvPAD_NAMELIST(sv)) {
6339                 assert(!SvMAGICAL(sv));
6340             } else if (SvMAGIC(sv)) {
6341                 /* Free back-references before other types of magic. */
6342                 sv_unmagic(sv, PERL_MAGIC_backref);
6343                 mg_free(sv);
6344             }
6345             SvMAGICAL_off(sv);
6346             if (type == SVt_PVMG && SvPAD_TYPED(sv))
6347                 SvREFCNT_dec(SvSTASH(sv));
6348         }
6349         switch (type) {
6350             /* case SVt_INVLIST: */
6351         case SVt_PVIO:
6352             if (IoIFP(sv) &&
6353                 IoIFP(sv) != PerlIO_stdin() &&
6354                 IoIFP(sv) != PerlIO_stdout() &&
6355                 IoIFP(sv) != PerlIO_stderr() &&
6356                 !(IoFLAGS(sv) & IOf_FAKE_DIRP))
6357             {
6358                 io_close(MUTABLE_IO(sv), FALSE);
6359             }
6360             if (IoDIRP(sv) && !(IoFLAGS(sv) & IOf_FAKE_DIRP))
6361                 PerlDir_close(IoDIRP(sv));
6362             IoDIRP(sv) = (DIR*)NULL;
6363             Safefree(IoTOP_NAME(sv));
6364             Safefree(IoFMT_NAME(sv));
6365             Safefree(IoBOTTOM_NAME(sv));
6366             if ((const GV *)sv == PL_statgv)
6367                 PL_statgv = NULL;
6368             goto freescalar;
6369         case SVt_REGEXP:
6370             /* FIXME for plugins */
6371           freeregexp:
6372             pregfree2((REGEXP*) sv);
6373             goto freescalar;
6374         case SVt_PVCV:
6375         case SVt_PVFM:
6376             cv_undef(MUTABLE_CV(sv));
6377             /* If we're in a stash, we don't own a reference to it.
6378              * However it does have a back reference to us, which needs to
6379              * be cleared.  */
6380             if ((stash = CvSTASH(sv)))
6381                 sv_del_backref(MUTABLE_SV(stash), sv);
6382             goto freescalar;
6383         case SVt_PVHV:
6384             if (PL_last_swash_hv == (const HV *)sv) {
6385                 PL_last_swash_hv = NULL;
6386             }
6387             if (HvTOTALKEYS((HV*)sv) > 0) {
6388                 const char *name;
6389                 /* this statement should match the one at the beginning of
6390                  * hv_undef_flags() */
6391                 if (   PL_phase != PERL_PHASE_DESTRUCT
6392                     && (name = HvNAME((HV*)sv)))
6393                 {
6394                     if (PL_stashcache) {
6395                     DEBUG_o(Perl_deb(aTHX_ "sv_clear clearing PL_stashcache for '%"SVf"'\n",
6396                                      SVfARG(sv)));
6397                         (void)hv_deletehek(PL_stashcache,
6398                                            HvNAME_HEK((HV*)sv), G_DISCARD);
6399                     }
6400                     hv_name_set((HV*)sv, NULL, 0, 0);
6401                 }
6402
6403                 /* save old iter_sv in unused SvSTASH field */
6404                 assert(!SvOBJECT(sv));
6405                 SvSTASH(sv) = (HV*)iter_sv;
6406                 iter_sv = sv;
6407
6408                 /* save old hash_index in unused SvMAGIC field */
6409                 assert(!SvMAGICAL(sv));
6410                 assert(!SvMAGIC(sv));
6411                 ((XPVMG*) SvANY(sv))->xmg_u.xmg_hash_index = hash_index;
6412                 hash_index = 0;
6413
6414                 next_sv = Perl_hfree_next_entry(aTHX_ (HV*)sv, &hash_index);
6415                 goto get_next_sv; /* process this new sv */
6416             }
6417             /* free empty hash */
6418             Perl_hv_undef_flags(aTHX_ MUTABLE_HV(sv), HV_NAME_SETALL);
6419             assert(!HvARRAY((HV*)sv));
6420             break;
6421         case SVt_PVAV:
6422             {
6423                 AV* av = MUTABLE_AV(sv);
6424                 if (PL_comppad == av) {
6425                     PL_comppad = NULL;
6426                     PL_curpad = NULL;
6427                 }
6428                 if (AvREAL(av) && AvFILLp(av) > -1) {
6429                     next_sv = AvARRAY(av)[AvFILLp(av)--];
6430                     /* save old iter_sv in top-most slot of AV,
6431                      * and pray that it doesn't get wiped in the meantime */
6432                     AvARRAY(av)[AvMAX(av)] = iter_sv;
6433                     iter_sv = sv;
6434                     goto get_next_sv; /* process this new sv */
6435                 }
6436                 Safefree(AvALLOC(av));
6437             }
6438
6439             break;
6440         case SVt_PVLV:
6441             if (LvTYPE(sv) == 'T') { /* for tie: return HE to pool */
6442                 SvREFCNT_dec(HeKEY_sv((HE*)LvTARG(sv)));
6443                 HeNEXT((HE*)LvTARG(sv)) = PL_hv_fetch_ent_mh;
6444                 PL_hv_fetch_ent_mh = (HE*)LvTARG(sv);
6445             }
6446             else if (LvTYPE(sv) != 't') /* unless tie: unrefcnted fake SV**  */
6447                 SvREFCNT_dec(LvTARG(sv));
6448             if (isREGEXP(sv)) goto freeregexp;
6449         case SVt_PVGV:
6450             if (isGV_with_GP(sv)) {
6451                 if(GvCVu((const GV *)sv) && (stash = GvSTASH(MUTABLE_GV(sv)))
6452                    && HvENAME_get(stash))
6453                     mro_method_changed_in(stash);
6454                 gp_free(MUTABLE_GV(sv));
6455                 if (GvNAME_HEK(sv))
6456                     unshare_hek(GvNAME_HEK(sv));
6457                 /* If we're in a stash, we don't own a reference to it.
6458                  * However it does have a back reference to us, which
6459                  * needs to be cleared.  */
6460                 if (!SvVALID(sv) && (stash = GvSTASH(sv)))
6461                         sv_del_backref(MUTABLE_SV(stash), sv);
6462             }
6463             /* FIXME. There are probably more unreferenced pointers to SVs
6464              * in the interpreter struct that we should check and tidy in
6465              * a similar fashion to this:  */
6466             /* See also S_sv_unglob, which does the same thing. */
6467             if ((const GV *)sv == PL_last_in_gv)
6468                 PL_last_in_gv = NULL;
6469             else if ((const GV *)sv == PL_statgv)
6470                 PL_statgv = NULL;
6471             else if ((const GV *)sv == PL_stderrgv)
6472                 PL_stderrgv = NULL;
6473         case SVt_PVMG:
6474         case SVt_PVNV:
6475         case SVt_PVIV:
6476         case SVt_INVLIST:
6477         case SVt_PV:
6478           freescalar:
6479             /* Don't bother with SvOOK_off(sv); as we're only going to
6480              * free it.  */
6481             if (SvOOK(sv)) {
6482                 STRLEN offset;
6483                 SvOOK_offset(sv, offset);
6484                 SvPV_set(sv, SvPVX_mutable(sv) - offset);
6485                 /* Don't even bother with turning off the OOK flag.  */
6486             }
6487             if (SvROK(sv)) {
6488             free_rv:
6489                 {
6490                     SV * const target = SvRV(sv);
6491                     if (SvWEAKREF(sv))
6492                         sv_del_backref(target, sv);
6493                     else
6494                         next_sv = target;
6495                 }
6496             }
6497 #ifdef PERL_ANY_COW
6498             else if (SvPVX_const(sv)
6499                      && !(SvTYPE(sv) == SVt_PVIO
6500                      && !(IoFLAGS(sv) & IOf_FAKE_DIRP)))
6501             {
6502                 if (SvIsCOW(sv)) {
6503                     if (DEBUG_C_TEST) {
6504                         PerlIO_printf(Perl_debug_log, "Copy on write: clear\n");
6505                         sv_dump(sv);
6506                     }
6507                     if (SvLEN(sv)) {
6508 # ifdef PERL_OLD_COPY_ON_WRITE
6509                         sv_release_COW(sv, SvPVX_const(sv), SV_COW_NEXT_SV(sv));
6510 # else
6511                         if (CowREFCNT(sv)) {
6512                             sv_buf_to_rw(sv);
6513                             CowREFCNT(sv)--;
6514                             sv_buf_to_ro(sv);
6515                             SvLEN_set(sv, 0);
6516                         }
6517 # endif
6518                     } else {
6519                         unshare_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sv)));
6520                     }
6521
6522                 }
6523 # ifdef PERL_OLD_COPY_ON_WRITE
6524                 else
6525 # endif
6526                 if (SvLEN(sv)) {
6527                     Safefree(SvPVX_mutable(sv));
6528                 }
6529             }
6530 #else
6531             else if (SvPVX_const(sv) && SvLEN(sv)
6532                      && !(SvTYPE(sv) == SVt_PVIO
6533                      && !(IoFLAGS(sv) & IOf_FAKE_DIRP)))
6534                 Safefree(SvPVX_mutable(sv));
6535             else if (SvPVX_const(sv) && SvIsCOW(sv)) {
6536                 unshare_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sv)));
6537             }
6538 #endif
6539             break;
6540         case SVt_NV:
6541             break;
6542         }
6543
6544       free_body:
6545
6546         SvFLAGS(sv) &= SVf_BREAK;
6547         SvFLAGS(sv) |= SVTYPEMASK;
6548
6549         sv_type_details = bodies_by_type + type;
6550         if (sv_type_details->arena) {
6551             del_body(((char *)SvANY(sv) + sv_type_details->offset),
6552                      &PL_body_roots[type]);
6553         }
6554         else if (sv_type_details->body_size) {
6555             safefree(SvANY(sv));
6556         }
6557
6558       free_head:
6559         /* caller is responsible for freeing the head of the original sv */
6560         if (sv != orig_sv && !SvREFCNT(sv))
6561             del_SV(sv);
6562
6563         /* grab and free next sv, if any */
6564       get_next_sv:
6565         while (1) {
6566             sv = NULL;
6567             if (next_sv) {
6568                 sv = next_sv;
6569                 next_sv = NULL;
6570             }
6571             else if (!iter_sv) {
6572                 break;
6573             } else if (SvTYPE(iter_sv) == SVt_PVAV) {
6574                 AV *const av = (AV*)iter_sv;
6575                 if (AvFILLp(av) > -1) {
6576                     sv = AvARRAY(av)[AvFILLp(av)--];
6577                 }
6578                 else { /* no more elements of current AV to free */
6579                     sv = iter_sv;
6580                     type = SvTYPE(sv);
6581                     /* restore previous value, squirrelled away */
6582                     iter_sv = AvARRAY(av)[AvMAX(av)];
6583                     Safefree(AvALLOC(av));
6584                     goto free_body;
6585                 }
6586             } else if (SvTYPE(iter_sv) == SVt_PVHV) {
6587                 sv = Perl_hfree_next_entry(aTHX_ (HV*)iter_sv, &hash_index);
6588                 if (!sv && !HvTOTALKEYS((HV *)iter_sv)) {
6589                     /* no more elements of current HV to free */
6590                     sv = iter_sv;
6591                     type = SvTYPE(sv);
6592                     /* Restore previous values of iter_sv and hash_index,
6593                      * squirrelled away */
6594                     assert(!SvOBJECT(sv));
6595                     iter_sv = (SV*)SvSTASH(sv);
6596                     assert(!SvMAGICAL(sv));
6597                     hash_index = ((XPVMG*) SvANY(sv))->xmg_u.xmg_hash_index;
6598 #ifdef DEBUGGING
6599                     /* perl -DA does not like rubbish in SvMAGIC. */
6600                     SvMAGIC_set(sv, 0);
6601 #endif
6602
6603                     /* free any remaining detritus from the hash struct */
6604                     Perl_hv_undef_flags(aTHX_ MUTABLE_HV(sv), HV_NAME_SETALL);
6605                     assert(!HvARRAY((HV*)sv));
6606                     goto free_body;
6607                 }
6608             }
6609
6610             /* unrolled SvREFCNT_dec and sv_free2 follows: */
6611
6612             if (!sv)
6613                 continue;
6614             if (!SvREFCNT(sv)) {
6615                 sv_free(sv);
6616                 continue;
6617             }
6618             if (--(SvREFCNT(sv)))
6619                 continue;
6620 #ifdef DEBUGGING
6621             if (SvTEMP(sv)) {
6622                 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEBUGGING),
6623                          "Attempt to free temp prematurely: SV 0x%"UVxf
6624                          pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
6625                 continue;
6626             }
6627 #endif
6628             if (SvIMMORTAL(sv)) {
6629                 /* make sure SvREFCNT(sv)==0 happens very seldom */
6630                 SvREFCNT(sv) = SvREFCNT_IMMORTAL;
6631                 continue;
6632             }
6633             break;
6634         } /* while 1 */
6635
6636     } /* while sv */
6637 }
6638
6639 /* This routine curses the sv itself, not the object referenced by sv. So
6640    sv does not have to be ROK. */
6641
6642 static bool
6643 S_curse(pTHX_ SV * const sv, const bool check_refcnt) {
6644     PERL_ARGS_ASSERT_CURSE;
6645     assert(SvOBJECT(sv));
6646
6647     if (PL_defstash &&  /* Still have a symbol table? */
6648         SvDESTROYABLE(sv))
6649     {
6650         dSP;
6651         HV* stash;
6652         do {
6653           stash = SvSTASH(sv);
6654           assert(SvTYPE(stash) == SVt_PVHV);
6655           if (HvNAME(stash)) {
6656             CV* destructor = NULL;
6657             assert (SvOOK(stash));
6658             if (!SvOBJECT(stash)) destructor = (CV *)SvSTASH(stash);
6659             if (!destructor || HvMROMETA(stash)->destroy_gen
6660                                 != PL_sub_generation)
6661             {
6662                 GV * const gv =
6663                     gv_fetchmeth_autoload(stash, "DESTROY", 7, 0);
6664                 if (gv) destructor = GvCV(gv);
6665                 if (!SvOBJECT(stash))
6666                 {
6667                     SvSTASH(stash) =
6668                         destructor ? (HV *)destructor : ((HV *)0)+1;
6669                     HvAUX(stash)->xhv_mro_meta->destroy_gen =
6670                         PL_sub_generation;
6671                 }
6672             }
6673             assert(!destructor || destructor == ((CV *)0)+1
6674                 || SvTYPE(destructor) == SVt_PVCV);
6675             if (destructor && destructor != ((CV *)0)+1
6676                 /* A constant subroutine can have no side effects, so
6677                    don't bother calling it.  */
6678                 && !CvCONST(destructor)
6679                 /* Don't bother calling an empty destructor or one that
6680                    returns immediately. */
6681                 && (CvISXSUB(destructor)
6682                 || (CvSTART(destructor)
6683                     && (CvSTART(destructor)->op_next->op_type
6684                                         != OP_LEAVESUB)
6685                     && (CvSTART(destructor)->op_next->op_type
6686                                         != OP_PUSHMARK
6687                         || CvSTART(destructor)->op_next->op_next->op_type
6688                                         != OP_RETURN
6689                        )
6690                    ))
6691                )
6692             {
6693                 SV* const tmpref = newRV(sv);
6694                 SvREADONLY_on(tmpref); /* DESTROY() could be naughty */
6695                 ENTER;
6696                 PUSHSTACKi(PERLSI_DESTROY);
6697                 EXTEND(SP, 2);
6698                 PUSHMARK(SP);
6699                 PUSHs(tmpref);
6700                 PUTBACK;
6701                 call_sv(MUTABLE_SV(destructor),
6702                             G_DISCARD|G_EVAL|G_KEEPERR|G_VOID);
6703                 POPSTACK;
6704                 SPAGAIN;
6705                 LEAVE;
6706                 if(SvREFCNT(tmpref) < 2) {
6707                     /* tmpref is not kept alive! */
6708                     SvREFCNT(sv)--;
6709                     SvRV_set(tmpref, NULL);
6710                     SvROK_off(tmpref);
6711                 }
6712                 SvREFCNT_dec_NN(tmpref);
6713             }
6714           }
6715         } while (SvOBJECT(sv) && SvSTASH(sv) != stash);
6716
6717
6718         if (check_refcnt && SvREFCNT(sv)) {
6719             if (PL_in_clean_objs)
6720                 Perl_croak(aTHX_
6721                   "DESTROY created new reference to dead object '%"HEKf"'",
6722                    HEKfARG(HvNAME_HEK(stash)));
6723             /* DESTROY gave object new lease on life */
6724             return FALSE;
6725         }
6726     }
6727
6728     if (SvOBJECT(sv)) {
6729         HV * const stash = SvSTASH(sv);
6730         /* Curse before freeing the stash, as freeing the stash could cause
6731            a recursive call into S_curse. */
6732         SvOBJECT_off(sv);       /* Curse the object. */
6733         SvSTASH_set(sv,0);      /* SvREFCNT_dec may try to read this */
6734         SvREFCNT_dec(stash); /* possibly of changed persuasion */
6735     }
6736     return TRUE;
6737 }
6738
6739 /*
6740 =for apidoc sv_newref
6741
6742 Increment an SV's reference count.  Use the C<SvREFCNT_inc()> wrapper
6743 instead.
6744
6745 =cut
6746 */
6747
6748 SV *
6749 Perl_sv_newref(pTHX_ SV *const sv)
6750 {
6751     PERL_UNUSED_CONTEXT;
6752     if (sv)
6753         (SvREFCNT(sv))++;
6754     return sv;
6755 }
6756
6757 /*
6758 =for apidoc sv_free
6759
6760 Decrement an SV's reference count, and if it drops to zero, call
6761 C<sv_clear> to invoke destructors and free up any memory used by
6762 the body; finally, deallocate the SV's head itself.
6763 Normally called via a wrapper macro C<SvREFCNT_dec>.
6764
6765 =cut
6766 */
6767
6768 void
6769 Perl_sv_free(pTHX_ SV *const sv)
6770 {
6771     SvREFCNT_dec(sv);
6772 }
6773
6774
6775 /* Private helper function for SvREFCNT_dec().
6776  * Called with rc set to original SvREFCNT(sv), where rc == 0 or 1 */
6777
6778 void
6779 Perl_sv_free2(pTHX_ SV *const sv, const U32 rc)
6780 {
6781     dVAR;
6782
6783     PERL_ARGS_ASSERT_SV_FREE2;
6784
6785     if (LIKELY( rc == 1 )) {
6786         /* normal case */
6787         SvREFCNT(sv) = 0;
6788
6789 #ifdef DEBUGGING
6790         if (SvTEMP(sv)) {
6791             Perl_ck_warner_d(aTHX_ packWARN(WARN_DEBUGGING),
6792                              "Attempt to free temp prematurely: SV 0x%"UVxf
6793                              pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
6794             return;
6795         }
6796 #endif
6797         if (SvIMMORTAL(sv)) {
6798             /* make sure SvREFCNT(sv)==0 happens very seldom */
6799             SvREFCNT(sv) = SvREFCNT_IMMORTAL;
6800             return;
6801         }
6802         sv_clear(sv);
6803         if (! SvREFCNT(sv)) /* may have have been resurrected */
6804             del_SV(sv);
6805         return;
6806     }
6807
6808     /* handle exceptional cases */
6809
6810     assert(rc == 0);
6811
6812     if (SvFLAGS(sv) & SVf_BREAK)
6813         /* this SV's refcnt has been artificially decremented to
6814          * trigger cleanup */
6815         return;
6816     if (PL_in_clean_all) /* All is fair */
6817         return;
6818     if (SvIMMORTAL(sv)) {
6819         /* make sure SvREFCNT(sv)==0 happens very seldom */
6820         SvREFCNT(sv) = SvREFCNT_IMMORTAL;
6821         return;
6822     }
6823     if (ckWARN_d(WARN_INTERNAL)) {
6824 #ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
6825         Perl_dump_sv_child(aTHX_ sv);
6826 #else
6827     #ifdef DEBUG_LEAKING_SCALARS
6828         sv_dump(sv);
6829     #endif
6830 #ifdef DEBUG_LEAKING_SCALARS_ABORT
6831         if (PL_warnhook == PERL_WARNHOOK_FATAL
6832             || ckDEAD(packWARN(WARN_INTERNAL))) {
6833             /* Don't let Perl_warner cause us to escape our fate:  */
6834             abort();
6835         }
6836 #endif
6837         /* This may not return:  */
6838         Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
6839                     "Attempt to free unreferenced scalar: SV 0x%"UVxf
6840                     pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
6841 #endif
6842     }
6843 #ifdef DEBUG_LEAKING_SCALARS_ABORT
6844     abort();
6845 #endif
6846
6847 }
6848
6849
6850 /*
6851 =for apidoc sv_len
6852
6853 Returns the length of the string in the SV.  Handles magic and type
6854 coercion and sets the UTF8 flag appropriately.  See also C<SvCUR>, which
6855 gives raw access to the xpv_cur slot.
6856
6857 =cut
6858 */
6859
6860 STRLEN
6861 Perl_sv_len(pTHX_ SV *const sv)
6862 {
6863     STRLEN len;
6864
6865     if (!sv)
6866         return 0;
6867
6868     (void)SvPV_const(sv, len);
6869     return len;
6870 }
6871
6872 /*
6873 =for apidoc sv_len_utf8
6874
6875 Returns the number of characters in the string in an SV, counting wide
6876 UTF-8 bytes as a single character.  Handles magic and type coercion.
6877
6878 =cut
6879 */
6880
6881 /*
6882  * The length is cached in PERL_MAGIC_utf8, in the mg_len field.  Also the
6883  * mg_ptr is used, by sv_pos_u2b() and sv_pos_b2u() - see the comments below.
6884  * (Note that the mg_len is not the length of the mg_ptr field.
6885  * This allows the cache to store the character length of the string without
6886  * needing to malloc() extra storage to attach to the mg_ptr.)
6887  *
6888  */
6889
6890 STRLEN
6891 Perl_sv_len_utf8(pTHX_ SV *const sv)
6892 {
6893     if (!sv)
6894         return 0;
6895
6896     SvGETMAGIC(sv);
6897     return sv_len_utf8_nomg(sv);
6898 }
6899
6900 STRLEN
6901 Perl_sv_len_utf8_nomg(pTHX_ SV * const sv)
6902 {
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     const char *pv1;
7578     STRLEN cur1;
7579     const char *pv2;
7580     STRLEN cur2;
7581     I32  eq     = 0;
7582     SV* svrecode = NULL;
7583
7584     if (!sv1) {
7585         pv1 = "";
7586         cur1 = 0;
7587     }
7588     else {
7589         /* if pv1 and pv2 are the same, second SvPV_const call may
7590          * invalidate pv1 (if we are handling magic), so we may need to
7591          * make a copy */
7592         if (sv1 == sv2 && flags & SV_GMAGIC
7593          && (SvTHINKFIRST(sv1) || SvGMAGICAL(sv1))) {
7594             pv1 = SvPV_const(sv1, cur1);
7595             sv1 = newSVpvn_flags(pv1, cur1, SVs_TEMP | SvUTF8(sv2));
7596         }
7597         pv1 = SvPV_flags_const(sv1, cur1, flags);
7598     }
7599
7600     if (!sv2){
7601         pv2 = "";
7602         cur2 = 0;
7603     }
7604     else
7605         pv2 = SvPV_flags_const(sv2, cur2, flags);
7606
7607     if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
7608         /* Differing utf8ness.
7609          * Do not UTF8size the comparands as a side-effect. */
7610          if (PL_encoding) {
7611               if (SvUTF8(sv1)) {
7612                    svrecode = newSVpvn(pv2, cur2);
7613                    sv_recode_to_utf8(svrecode, PL_encoding);
7614                    pv2 = SvPV_const(svrecode, cur2);
7615               }
7616               else {
7617                    svrecode = newSVpvn(pv1, cur1);
7618                    sv_recode_to_utf8(svrecode, PL_encoding);
7619                    pv1 = SvPV_const(svrecode, cur1);
7620               }
7621               /* Now both are in UTF-8. */
7622               if (cur1 != cur2) {
7623                    SvREFCNT_dec_NN(svrecode);
7624                    return FALSE;
7625               }
7626          }
7627          else {
7628               if (SvUTF8(sv1)) {
7629                   /* sv1 is the UTF-8 one  */
7630                   return bytes_cmp_utf8((const U8*)pv2, cur2,
7631                                         (const U8*)pv1, cur1) == 0;
7632               }
7633               else {
7634                   /* sv2 is the UTF-8 one  */
7635                   return bytes_cmp_utf8((const U8*)pv1, cur1,
7636                                         (const U8*)pv2, cur2) == 0;
7637               }
7638          }
7639     }
7640
7641     if (cur1 == cur2)
7642         eq = (pv1 == pv2) || memEQ(pv1, pv2, cur1);
7643         
7644     SvREFCNT_dec(svrecode);
7645
7646     return eq;
7647 }
7648
7649 /*
7650 =for apidoc sv_cmp
7651
7652 Compares the strings in two SVs.  Returns -1, 0, or 1 indicating whether the
7653 string in C<sv1> is less than, equal to, or greater than the string in
7654 C<sv2>.  Is UTF-8 and 'use bytes' aware, handles get magic, and will
7655 coerce its args to strings if necessary.  See also C<sv_cmp_locale>.
7656
7657 =for apidoc sv_cmp_flags
7658
7659 Compares the strings in two SVs.  Returns -1, 0, or 1 indicating whether the
7660 string in C<sv1> is less than, equal to, or greater than the string in
7661 C<sv2>.  Is UTF-8 and 'use bytes' aware and will coerce its args to strings
7662 if necessary.  If the flags include SV_GMAGIC, it handles get magic.  See
7663 also C<sv_cmp_locale_flags>.
7664
7665 =cut
7666 */
7667
7668 I32
7669 Perl_sv_cmp(pTHX_ SV *const sv1, SV *const sv2)
7670 {
7671     return sv_cmp_flags(sv1, sv2, SV_GMAGIC);
7672 }
7673
7674 I32
7675 Perl_sv_cmp_flags(pTHX_ SV *const sv1, SV *const sv2,
7676                   const U32 flags)
7677 {
7678     STRLEN cur1, cur2;
7679     const char *pv1, *pv2;
7680     I32  cmp;
7681     SV *svrecode = NULL;
7682
7683     if (!sv1) {
7684         pv1 = "";
7685         cur1 = 0;
7686     }
7687     else
7688         pv1 = SvPV_flags_const(sv1, cur1, flags);
7689
7690     if (!sv2) {
7691         pv2 = "";
7692         cur2 = 0;
7693     }
7694     else
7695         pv2 = SvPV_flags_const(sv2, cur2, flags);
7696
7697     if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
7698         /* Differing utf8ness.
7699          * Do not UTF8size the comparands as a side-effect. */
7700         if (SvUTF8(sv1)) {
7701             if (PL_encoding) {
7702                  svrecode = newSVpvn(pv2, cur2);
7703                  sv_recode_to_utf8(svrecode, PL_encoding);
7704                  pv2 = SvPV_const(svrecode, cur2);
7705             }
7706             else {
7707                 const int retval = -bytes_cmp_utf8((const U8*)pv2, cur2,
7708                                                    (const U8*)pv1, cur1);
7709                 return retval ? retval < 0 ? -1 : +1 : 0;
7710             }
7711         }
7712         else {
7713             if (PL_encoding) {
7714                  svrecode = newSVpvn(pv1, cur1);
7715                  sv_recode_to_utf8(svrecode, PL_encoding);
7716                  pv1 = SvPV_const(svrecode, cur1);
7717             }
7718             else {
7719                 const int retval = bytes_cmp_utf8((const U8*)pv1, cur1,
7720                                                   (const U8*)pv2, cur2);
7721                 return retval ? retval < 0 ? -1 : +1 : 0;
7722             }
7723         }
7724     }
7725
7726     if (!cur1) {
7727         cmp = cur2 ? -1 : 0;
7728     } else if (!cur2) {
7729         cmp = 1;
7730     } else {
7731         const I32 retval = memcmp((const void*)pv1, (const void*)pv2, cur1 < cur2 ? cur1 : cur2);
7732
7733         if (retval) {
7734             cmp = retval < 0 ? -1 : 1;
7735         } else if (cur1 == cur2) {
7736             cmp = 0;
7737         } else {
7738             cmp = cur1 < cur2 ? -1 : 1;
7739         }
7740     }
7741
7742     SvREFCNT_dec(svrecode);
7743
7744     return cmp;
7745 }
7746
7747 /*
7748 =for apidoc sv_cmp_locale
7749
7750 Compares the strings in two SVs in a locale-aware manner.  Is UTF-8 and
7751 'use bytes' aware, handles get magic, and will coerce its args to strings
7752 if necessary.  See also C<sv_cmp>.
7753
7754 =for apidoc sv_cmp_locale_flags
7755
7756 Compares the strings in two SVs in a locale-aware manner.  Is UTF-8 and
7757 'use bytes' aware and will coerce its args to strings if necessary.  If the
7758 flags contain SV_GMAGIC, it handles get magic.  See also C<sv_cmp_flags>.
7759
7760 =cut
7761 */
7762
7763 I32
7764 Perl_sv_cmp_locale(pTHX_ SV *const sv1, SV *const sv2)
7765 {
7766     return sv_cmp_locale_flags(sv1, sv2, SV_GMAGIC);
7767 }
7768
7769 I32
7770 Perl_sv_cmp_locale_flags(pTHX_ SV *const sv1, SV *const sv2,
7771                          const U32 flags)
7772 {
7773 #ifdef USE_LOCALE_COLLATE
7774
7775     char *pv1, *pv2;
7776     STRLEN len1, len2;
7777     I32 retval;
7778
7779     if (PL_collation_standard)
7780         goto raw_compare;
7781
7782     len1 = 0;
7783     pv1 = sv1 ? sv_collxfrm_flags(sv1, &len1, flags) : (char *) NULL;
7784     len2 = 0;
7785     pv2 = sv2 ? sv_collxfrm_flags(sv2, &len2, flags) : (char *) NULL;
7786
7787     if (!pv1 || !len1) {
7788         if (pv2 && len2)
7789             return -1;
7790         else
7791             goto raw_compare;
7792     }
7793     else {
7794         if (!pv2 || !len2)
7795             return 1;
7796     }
7797
7798     retval = memcmp((void*)pv1, (void*)pv2, len1 < len2 ? len1 : len2);
7799
7800     if (retval)
7801         return retval < 0 ? -1 : 1;
7802
7803     /*
7804      * When the result of collation is equality, that doesn't mean
7805      * that there are no differences -- some locales exclude some
7806      * characters from consideration.  So to avoid false equalities,
7807      * we use the raw string as a tiebreaker.
7808      */
7809
7810   raw_compare:
7811     /* FALLTHROUGH */
7812
7813 #else
7814     PERL_UNUSED_ARG(flags);
7815 #endif /* USE_LOCALE_COLLATE */
7816
7817     return sv_cmp(sv1, sv2);
7818 }
7819
7820
7821 #ifdef USE_LOCALE_COLLATE
7822
7823 /*
7824 =for apidoc sv_collxfrm
7825
7826 This calls C<sv_collxfrm_flags> with the SV_GMAGIC flag.  See
7827 C<sv_collxfrm_flags>.
7828
7829 =for apidoc sv_collxfrm_flags
7830
7831 Add Collate Transform magic to an SV if it doesn't already have it.  If the
7832 flags contain SV_GMAGIC, it handles get-magic.
7833
7834 Any scalar variable may carry PERL_MAGIC_collxfrm magic that contains the
7835 scalar data of the variable, but transformed to such a format that a normal
7836 memory comparison can be used to compare the data according to the locale
7837 settings.
7838
7839 =cut
7840 */
7841
7842 char *
7843 Perl_sv_collxfrm_flags(pTHX_ SV *const sv, STRLEN *const nxp, const I32 flags)
7844 {
7845     MAGIC *mg;
7846
7847     PERL_ARGS_ASSERT_SV_COLLXFRM_FLAGS;
7848
7849     mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_collxfrm) : (MAGIC *) NULL;
7850     if (!mg || !mg->mg_ptr || *(U32*)mg->mg_ptr != PL_collation_ix) {
7851         const char *s;
7852         char *xf;
7853         STRLEN len, xlen;
7854
7855         if (mg)
7856             Safefree(mg->mg_ptr);
7857         s = SvPV_flags_const(sv, len, flags);
7858         if ((xf = mem_collxfrm(s, len, &xlen))) {
7859             if (! mg) {
7860 #ifdef PERL_OLD_COPY_ON_WRITE
7861                 if (SvIsCOW(sv))
7862                     sv_force_normal_flags(sv, 0);
7863 #endif
7864                 mg = sv_magicext(sv, 0, PERL_MAGIC_collxfrm, &PL_vtbl_collxfrm,
7865                                  0, 0);
7866                 assert(mg);
7867             }
7868             mg->mg_ptr = xf;
7869             mg->mg_len = xlen;
7870         }
7871         else {
7872             if (mg) {
7873                 mg->mg_ptr = NULL;
7874                 mg->mg_len = -1;
7875             }
7876         }
7877     }
7878     if (mg && mg->mg_ptr) {
7879         *nxp = mg->mg_len;
7880         return mg->mg_ptr + sizeof(PL_collation_ix);
7881     }
7882     else {
7883         *nxp = 0;
7884         return NULL;
7885     }
7886 }
7887
7888 #endif /* USE_LOCALE_COLLATE */
7889
7890 static char *
7891 S_sv_gets_append_to_utf8(pTHX_ SV *const sv, PerlIO *const fp, I32 append)
7892 {
7893     SV * const tsv = newSV(0);
7894     ENTER;
7895     SAVEFREESV(tsv);
7896     sv_gets(tsv, fp, 0);
7897     sv_utf8_upgrade_nomg(tsv);
7898     SvCUR_set(sv,append);
7899     sv_catsv(sv,tsv);
7900     LEAVE;
7901     return (SvCUR(sv) - append) ? SvPVX(sv) : NULL;
7902 }
7903
7904 static char *
7905 S_sv_gets_read_record(pTHX_ SV *const sv, PerlIO *const fp, I32 append)
7906 {
7907     SSize_t bytesread;
7908     const STRLEN recsize = SvUV(SvRV(PL_rs)); /* RsRECORD() guarantees > 0. */
7909       /* Grab the size of the record we're getting */
7910     char *buffer = SvGROW(sv, (STRLEN)(recsize + append + 1)) + append;
7911     
7912     /* Go yank in */
7913 #ifdef __VMS
7914     int fd;
7915     Stat_t st;
7916
7917     /* With a true, record-oriented file on VMS, we need to use read directly
7918      * to ensure that we respect RMS record boundaries.  The user is responsible
7919      * for providing a PL_rs value that corresponds to the FAB$W_MRS (maximum
7920      * record size) field.  N.B. This is likely to produce invalid results on
7921      * varying-width character data when a record ends mid-character.
7922      */
7923     fd = PerlIO_fileno(fp);
7924     if (fd != -1
7925         && PerlLIO_fstat(fd, &st) == 0
7926         && (st.st_fab_rfm == FAB$C_VAR
7927             || st.st_fab_rfm == FAB$C_VFC
7928             || st.st_fab_rfm == FAB$C_FIX)) {
7929
7930         bytesread = PerlLIO_read(fd, buffer, recsize);
7931     }
7932     else /* in-memory file from PerlIO::Scalar
7933           * or not a record-oriented file
7934           */
7935 #endif
7936     {
7937         bytesread = PerlIO_read(fp, buffer, recsize);
7938
7939         /* At this point, the logic in sv_get() means that sv will
7940            be treated as utf-8 if the handle is utf8.
7941         */
7942         if (PerlIO_isutf8(fp) && bytesread > 0) {
7943             char *bend = buffer + bytesread;
7944             char *bufp = buffer;
7945             size_t charcount = 0;
7946             bool charstart = TRUE;
7947             STRLEN skip = 0;
7948
7949             while (charcount < recsize) {
7950                 /* count accumulated characters */
7951                 while (bufp < bend) {
7952                     if (charstart) {
7953                         skip = UTF8SKIP(bufp);
7954                     }
7955                     if (bufp + skip > bend) {
7956                         /* partial at the end */
7957                         charstart = FALSE;
7958                         break;
7959                     }
7960                     else {
7961                         ++charcount;
7962                         bufp += skip;
7963                         charstart = TRUE;
7964                     }
7965                 }
7966
7967                 if (charcount < recsize) {
7968                     STRLEN readsize;
7969                     STRLEN bufp_offset = bufp - buffer;
7970                     SSize_t morebytesread;
7971
7972                     /* originally I read enough to fill any incomplete
7973                        character and the first byte of the next
7974                        character if needed, but if there's many
7975                        multi-byte encoded characters we're going to be
7976                        making a read call for every character beyond
7977                        the original read size.
7978
7979                        So instead, read the rest of the character if
7980                        any, and enough bytes to match at least the
7981                        start bytes for each character we're going to
7982                        read.
7983                     */
7984                     if (charstart)
7985                         readsize = recsize - charcount;
7986                     else 
7987                         readsize = skip - (bend - bufp) + recsize - charcount - 1;
7988                     buffer = SvGROW(sv, append + bytesread + readsize + 1) + append;
7989                     bend = buffer + bytesread;
7990                     morebytesread = PerlIO_read(fp, bend, readsize);
7991                     if (morebytesread <= 0) {
7992                         /* we're done, if we still have incomplete
7993                            characters the check code in sv_gets() will
7994                            warn about them.
7995
7996                            I'd originally considered doing
7997                            PerlIO_ungetc() on all but the lead
7998                            character of the incomplete character, but
7999                            read() doesn't do that, so I don't.
8000                         */
8001                         break;
8002                     }
8003
8004                     /* prepare to scan some more */
8005                     bytesread += morebytesread;
8006                     bend = buffer + bytesread;
8007                     bufp = buffer + bufp_offset;
8008                 }
8009             }
8010         }
8011     }
8012
8013     if (bytesread < 0)
8014         bytesread = 0;
8015     SvCUR_set(sv, bytesread + append);
8016     buffer[bytesread] = '\0';
8017     return (SvCUR(sv) - append) ? SvPVX(sv) : NULL;
8018 }
8019
8020 /*
8021 =for apidoc sv_gets
8022
8023 Get a line from the filehandle and store it into the SV, optionally
8024 appending to the currently-stored string.  If C<append> is not 0, the
8025 line is appended to the SV instead of overwriting it.  C<append> should
8026 be set to the byte offset that the appended string should start at
8027 in the SV (typically, C<SvCUR(sv)> is a suitable choice).
8028
8029 =cut
8030 */
8031
8032 char *
8033 Perl_sv_gets(pTHX_ SV *const sv, PerlIO *const fp, I32 append)
8034 {
8035     const char *rsptr;
8036     STRLEN rslen;
8037     STDCHAR rslast;
8038     STDCHAR *bp;
8039     SSize_t cnt;
8040     int i = 0;
8041     int rspara = 0;
8042
8043     PERL_ARGS_ASSERT_SV_GETS;
8044
8045     if (SvTHINKFIRST(sv))
8046         sv_force_normal_flags(sv, append ? 0 : SV_COW_DROP_PV);
8047     /* XXX. If you make this PVIV, then copy on write can copy scalars read
8048        from <>.
8049        However, perlbench says it's slower, because the existing swipe code
8050        is faster than copy on write.
8051        Swings and roundabouts.  */
8052     SvUPGRADE(sv, SVt_PV);
8053
8054     if (append) {
8055         /* line is going to be appended to the existing buffer in the sv */
8056         if (PerlIO_isutf8(fp)) {
8057             if (!SvUTF8(sv)) {
8058                 sv_utf8_upgrade_nomg(sv);
8059                 sv_pos_u2b(sv,&append,0);
8060             }
8061         } else if (SvUTF8(sv)) {
8062             return S_sv_gets_append_to_utf8(aTHX_ sv, fp, append);
8063         }
8064     }
8065
8066     SvPOK_only(sv);
8067     if (!append) {
8068         /* not appending - "clear" the string by setting SvCUR to 0,
8069          * the pv is still avaiable. */
8070         SvCUR_set(sv,0);
8071     }
8072     if (PerlIO_isutf8(fp))
8073         SvUTF8_on(sv);
8074
8075     if (IN_PERL_COMPILETIME) {
8076         /* we always read code in line mode */
8077         rsptr = "\n";
8078         rslen = 1;
8079     }
8080     else if (RsSNARF(PL_rs)) {
8081         /* If it is a regular disk file use size from stat() as estimate
8082            of amount we are going to read -- may result in mallocing
8083            more memory than we really need if the layers below reduce
8084            the size we read (e.g. CRLF or a gzip layer).
8085          */
8086         Stat_t st;
8087         if (!PerlLIO_fstat(PerlIO_fileno(fp), &st) && S_ISREG(st.st_mode))  {
8088             const Off_t offset = PerlIO_tell(fp);
8089             if (offset != (Off_t) -1 && st.st_size + append > offset) {
8090 #ifdef PERL_NEW_COPY_ON_WRITE
8091                 /* Add an extra byte for the sake of copy-on-write's
8092                  * buffer reference count. */
8093                 (void) SvGROW(sv, (STRLEN)((st.st_size - offset) + append + 2));
8094 #else
8095                 (void) SvGROW(sv, (STRLEN)((st.st_size - offset) + append + 1));
8096 #endif
8097             }
8098         }
8099         rsptr = NULL;
8100         rslen = 0;
8101     }
8102     else if (RsRECORD(PL_rs)) {
8103         return S_sv_gets_read_record(aTHX_ sv, fp, append);
8104     }
8105     else if (RsPARA(PL_rs)) {
8106         rsptr = "\n\n";
8107         rslen = 2;
8108         rspara = 1;
8109     }
8110     else {
8111         /* Get $/ i.e. PL_rs into same encoding as stream wants */
8112         if (PerlIO_isutf8(fp)) {
8113             rsptr = SvPVutf8(PL_rs, rslen);
8114         }
8115         else {
8116             if (SvUTF8(PL_rs)) {
8117                 if (!sv_utf8_downgrade(PL_rs, TRUE)) {
8118                     Perl_croak(aTHX_ "Wide character in $/");
8119                 }
8120             }
8121             /* extract the raw pointer to the record separator */
8122             rsptr = SvPV_const(PL_rs, rslen);
8123         }
8124     }
8125
8126     /* rslast is the last character in the record separator
8127      * note we don't use rslast except when rslen is true, so the
8128      * null assign is a placeholder. */
8129     rslast = rslen ? rsptr[rslen - 1] : '\0';
8130
8131     if (rspara) {               /* have to do this both before and after */
8132         do {                    /* to make sure file boundaries work right */
8133             if (PerlIO_eof(fp))
8134                 return 0;
8135             i = PerlIO_getc(fp);
8136             if (i != '\n') {
8137                 if (i == -1)
8138                     return 0;
8139                 PerlIO_ungetc(fp,i);
8140                 break;
8141             }
8142         } while (i != EOF);
8143     }
8144
8145     /* See if we know enough about I/O mechanism to cheat it ! */
8146
8147     /* This used to be #ifdef test - it is made run-time test for ease
8148        of abstracting out stdio interface. One call should be cheap
8149        enough here - and may even be a macro allowing compile
8150        time optimization.
8151      */
8152
8153     if (PerlIO_fast_gets(fp)) {
8154     /*
8155      * We can do buffer based IO operations on this filehandle.
8156      *
8157      * This means we can bypass a lot of subcalls and process
8158      * the buffer directly, it also means we know the upper bound
8159      * on the amount of data we might read of the current buffer
8160      * into our sv. Knowing this allows us to preallocate the pv
8161      * to be able to hold that maximum, which allows us to simplify
8162      * a lot of logic. */
8163
8164     /*
8165      * We're going to steal some values from the stdio struct
8166      * and put EVERYTHING in the innermost loop into registers.
8167      */
8168     STDCHAR *ptr;       /* pointer into fp's read-ahead buffer */
8169     STRLEN bpx;         /* length of the data in the target sv
8170                            used to fix pointers after a SvGROW */
8171     I32 shortbuffered;  /* If the pv buffer is shorter than the amount
8172                            of data left in the read-ahead buffer.
8173                            If 0 then the pv buffer can hold the full
8174                            amount left, otherwise this is the amount it
8175                            can hold. */
8176
8177 #if defined(__VMS) && defined(PERLIO_IS_STDIO)
8178     /* An ungetc()d char is handled separately from the regular
8179      * buffer, so we getc() it back out and stuff it in the buffer.
8180      */
8181     i = PerlIO_getc(fp);
8182     if (i == EOF) return 0;
8183     *(--((*fp)->_ptr)) = (unsigned char) i;
8184     (*fp)->_cnt++;
8185 #endif
8186
8187     /* Here is some breathtakingly efficient cheating */
8188
8189     /* When you read the following logic resist the urge to think
8190      * of record separators that are 1 byte long. They are an
8191      * uninteresting special (simple) case.
8192      *
8193      * Instead think of record separators which are at least 2 bytes
8194      * long, and keep in mind that we need to deal with such
8195      * separators when they cross a read-ahead buffer boundary.
8196      *
8197      * Also consider that we need to gracefully deal with separators
8198      * that may be longer than a single read ahead buffer.
8199      *
8200      * Lastly do not forget we want to copy the delimiter as well. We
8201      * are copying all data in the file _up_to_and_including_ the separator
8202      * itself.
8203      *
8204      * Now that you have all that in mind here is what is happening below:
8205      *
8206      * 1. When we first enter the loop we do some memory book keeping to see
8207      * how much free space there is in the target SV. (This sub assumes that
8208      * it is operating on the same SV most of the time via $_ and that it is
8209      * going to be able to reuse the same pv buffer each call.) If there is
8210      * "enough" room then we set "shortbuffered" to how much space there is
8211      * and start reading forward.
8212      *
8213      * 2. When we scan forward we copy from the read-ahead buffer to the target
8214      * SV's pv buffer. While we go we watch for the end of the read-ahead buffer,
8215      * and the end of the of pv, as well as for the "rslast", which is the last
8216      * char of the separator.
8217      *
8218      * 3. When scanning forward if we see rslast then we jump backwards in *pv*
8219      * (which has a "complete" record up to the point we saw rslast) and check
8220      * it to see if it matches the separator. If it does we are done. If it doesn't
8221      * we continue on with the scan/copy.
8222      *
8223      * 4. If we run out of read-ahead buffer (cnt goes to 0) then we have to get
8224      * the IO system to read the next buffer. We do this by doing a getc(), which
8225      * returns a single char read (or EOF), and prefills the buffer, and also
8226      * allows us to find out how full the buffer is.  We use this information to
8227      * SvGROW() the sv to the size remaining in the buffer, after which we copy
8228      * the returned single char into the target sv, and then go back into scan
8229      * forward mode.
8230      *
8231      * 5. If we run out of write-buffer then we SvGROW() it by the size of the
8232      * remaining space in the read-buffer.
8233      *
8234      * Note that this code despite its twisty-turny nature is pretty darn slick.
8235      * It manages single byte separators, multi-byte cross boundary separators,
8236      * and cross-read-buffer separators cleanly and efficiently at the cost
8237      * of potentially greatly overallocating the target SV.
8238      *
8239      * Yves
8240      */
8241
8242
8243     /* get the number of bytes remaining in the read-ahead buffer
8244      * on first call on a given fp this will return 0.*/
8245     cnt = PerlIO_get_cnt(fp);
8246
8247     /* make sure we have the room */
8248     if ((I32)(SvLEN(sv) - append) <= cnt + 1) {
8249         /* Not room for all of it
8250            if we are looking for a separator and room for some
8251          */
8252         if (rslen && cnt > 80 && (I32)SvLEN(sv) > append) {
8253             /* just process what we have room for */
8254             shortbuffered = cnt - SvLEN(sv) + append + 1;
8255             cnt -= shortbuffered;
8256         }
8257         else {
8258             /* ensure that the target sv has enough room to hold
8259              * the rest of the read-ahead buffer */
8260             shortbuffered = 0;
8261             /* remember that cnt can be negative */
8262             SvGROW(sv, (STRLEN)(append + (cnt <= 0 ? 2 : (cnt + 1))));
8263         }
8264     }
8265     else {
8266         /* we have enough room to hold the full buffer, lets scream */
8267         shortbuffered = 0;
8268     }
8269
8270     /* extract the pointer to sv's string buffer, offset by append as necessary */
8271     bp = (STDCHAR*)SvPVX_const(sv) + append;  /* move these two too to registers */
8272     /* extract the point to the read-ahead buffer */
8273     ptr = (STDCHAR*)PerlIO_get_ptr(fp);
8274
8275     /* some trace debug output */
8276     DEBUG_P(PerlIO_printf(Perl_debug_log,
8277         "Screamer: entering, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
8278     DEBUG_P(PerlIO_printf(Perl_debug_log,
8279         "Screamer: entering: PerlIO * thinks ptr=%"UVuf", cnt=%"IVdf", base=%"
8280          UVuf"\n",
8281                PTR2UV(PerlIO_get_ptr(fp)), (IV)PerlIO_get_cnt(fp),
8282                PTR2UV(PerlIO_has_base(fp) ? PerlIO_get_base(fp) : 0)));
8283
8284     for (;;) {
8285       screamer:
8286         /* if there is stuff left in the read-ahead buffer */
8287         if (cnt > 0) {
8288             /* if there is a separator */
8289             if (rslen) {
8290                 /* loop until we hit the end of the read-ahead buffer */
8291                 while (cnt > 0) {                    /* this     |  eat */
8292                     /* scan forward copying and searching for rslast as we go */
8293                     cnt--;
8294                     if ((*bp++ = *ptr++) == rslast)  /* really   |  dust */
8295                         goto thats_all_folks;        /* screams  |  sed :-) */
8296                 }
8297             }
8298             else {
8299                 /* no separator, slurp the full buffer */
8300                 Copy(ptr, bp, cnt, char);            /* this     |  eat */
8301                 bp += cnt;                           /* screams  |  dust */
8302                 ptr += cnt;                          /* louder   |  sed :-) */
8303                 cnt = 0;
8304                 assert (!shortbuffered);
8305                 goto cannot_be_shortbuffered;
8306             }
8307         }
8308         
8309         if (shortbuffered) {            /* oh well, must extend */
8310             /* we didnt have enough room to fit the line into the target buffer
8311              * so we must extend the target buffer and keep going */
8312             cnt = shortbuffered;
8313             shortbuffered = 0;
8314             bpx = bp - (STDCHAR*)SvPVX_const(sv); /* box up before relocation */
8315             SvCUR_set(sv, bpx);
8316             /* extned the target sv's buffer so it can hold the full read-ahead buffer */
8317             SvGROW(sv, SvLEN(sv) + append + cnt + 2);
8318             bp = (STDCHAR*)SvPVX_const(sv) + bpx; /* unbox after relocation */
8319             continue;
8320         }
8321
8322     cannot_be_shortbuffered:
8323         /* we need to refill the read-ahead buffer if possible */
8324
8325         DEBUG_P(PerlIO_printf(Perl_debug_log,
8326                              "Screamer: going to getc, ptr=%"UVuf", cnt=%"IVdf"\n",
8327                               PTR2UV(ptr),(IV)cnt));
8328         PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt); /* deregisterize cnt and ptr */
8329
8330         DEBUG_Pv(PerlIO_printf(Perl_debug_log,
8331            "Screamer: pre: FILE * thinks ptr=%"UVuf", cnt=%"IVdf", base=%"UVuf"\n",
8332             PTR2UV(PerlIO_get_ptr(fp)), (IV)PerlIO_get_cnt(fp),
8333             PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
8334
8335         /*
8336             call PerlIO_getc() to let it prefill the lookahead buffer
8337
8338             This used to call 'filbuf' in stdio form, but as that behaves like
8339             getc when cnt <= 0 we use PerlIO_getc here to avoid introducing
8340             another abstraction.
8341
8342             Note we have to deal with the char in 'i' if we are not at EOF
8343         */
8344         i   = PerlIO_getc(fp);          /* get more characters */
8345
8346         DEBUG_Pv(PerlIO_printf(Perl_debug_log,
8347            "Screamer: post: FILE * thinks ptr=%"UVuf", cnt=%"IVdf", base=%"UVuf"\n",
8348             PTR2UV(PerlIO_get_ptr(fp)), (IV)PerlIO_get_cnt(fp),
8349             PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
8350
8351         /* find out how much is left in the read-ahead buffer, and rextract its pointer */
8352         cnt = PerlIO_get_cnt(fp);
8353         ptr = (STDCHAR*)PerlIO_get_ptr(fp);     /* reregisterize cnt and ptr */
8354         DEBUG_P(PerlIO_printf(Perl_debug_log,
8355             "Screamer: after getc, ptr=%"UVuf", cnt=%"IVdf"\n",
8356             PTR2UV(ptr),(IV)cnt));
8357
8358         if (i == EOF)                   /* all done for ever? */
8359             goto thats_really_all_folks;
8360
8361         /* make sure we have enough space in the target sv */
8362         bpx = bp - (STDCHAR*)SvPVX_const(sv);   /* box up before relocation */
8363         SvCUR_set(sv, bpx);
8364         SvGROW(sv, bpx + cnt + 2);
8365         bp = (STDCHAR*)SvPVX_const(sv) + bpx;   /* unbox after relocation */
8366
8367         /* copy of the char we got from getc() */
8368         *bp++ = (STDCHAR)i;             /* store character from PerlIO_getc */
8369
8370         /* make sure we deal with the i being the last character of a separator */
8371         if (rslen && (STDCHAR)i == rslast)  /* all done for now? */
8372             goto thats_all_folks;
8373     }
8374
8375 thats_all_folks:
8376     /* check if we have actually found the separator - only really applies
8377      * when rslen > 1 */
8378     if ((rslen > 1 && (STRLEN)(bp - (STDCHAR*)SvPVX_const(sv)) < rslen) ||
8379           memNE((char*)bp - rslen, rsptr, rslen))
8380         goto screamer;                          /* go back to the fray */
8381 thats_really_all_folks:
8382     if (shortbuffered)
8383         cnt += shortbuffered;
8384         DEBUG_P(PerlIO_printf(Perl_debug_log,
8385              "Screamer: quitting, ptr=%"UVuf", cnt=%"IVdf"\n",PTR2UV(ptr),(IV)cnt));
8386     PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt);  /* put these back or we're in trouble */
8387     DEBUG_P(PerlIO_printf(Perl_debug_log,
8388         "Screamer: end: FILE * thinks ptr=%"UVuf", cnt=%"IVdf", base=%"UVuf
8389         "\n",
8390         PTR2UV(PerlIO_get_ptr(fp)), (IV)PerlIO_get_cnt(fp),
8391         PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
8392     *bp = '\0';
8393     SvCUR_set(sv, bp - (STDCHAR*)SvPVX_const(sv));      /* set length */
8394     DEBUG_P(PerlIO_printf(Perl_debug_log,
8395         "Screamer: done, len=%ld, string=|%.*s|\n",
8396         (long)SvCUR(sv),(int)SvCUR(sv),SvPVX_const(sv)));
8397     }
8398    else
8399     {
8400        /*The big, slow, and stupid way. */
8401 #ifdef USE_HEAP_INSTEAD_OF_STACK        /* Even slower way. */
8402         STDCHAR *buf = NULL;
8403         Newx(buf, 8192, STDCHAR);
8404         assert(buf);
8405 #else
8406         STDCHAR buf[8192];
8407 #endif
8408
8409 screamer2:
8410         if (rslen) {
8411             const STDCHAR * const bpe = buf + sizeof(buf);
8412             bp = buf;
8413             while ((i = PerlIO_getc(fp)) != EOF && (*bp++ = (STDCHAR)i) != rslast && bp < bpe)
8414                 ; /* keep reading */
8415             cnt = bp - buf;
8416         }
8417         else {
8418             cnt = PerlIO_read(fp,(char*)buf, sizeof(buf));
8419             /* Accommodate broken VAXC compiler, which applies U8 cast to
8420              * both args of ?: operator, causing EOF to change into 255
8421              */
8422             if (cnt > 0)
8423                  i = (U8)buf[cnt - 1];
8424             else
8425                  i = EOF;
8426         }
8427
8428         if (cnt < 0)
8429             cnt = 0;  /* we do need to re-set the sv even when cnt <= 0 */
8430         if (append)
8431             sv_catpvn_nomg(sv, (char *) buf, cnt);
8432         else
8433             sv_setpvn(sv, (char *) buf, cnt);   /* "nomg" is implied */
8434
8435         if (i != EOF &&                 /* joy */
8436             (!rslen ||
8437              SvCUR(sv) < rslen ||
8438              memNE(SvPVX_const(sv) + SvCUR(sv) - rslen, rsptr, rslen)))
8439         {
8440             append = -1;
8441             /*
8442              * If we're reading from a TTY and we get a short read,
8443              * indicating that the user hit his EOF character, we need
8444              * to notice it now, because if we try to read from the TTY
8445              * again, the EOF condition will disappear.
8446              *
8447              * The comparison of cnt to sizeof(buf) is an optimization
8448              * that prevents unnecessary calls to feof().
8449              *
8450              * - jik 9/25/96
8451              */
8452             if (!(cnt < (I32)sizeof(buf) && PerlIO_eof(fp)))
8453                 goto screamer2;
8454         }
8455
8456 #ifdef USE_HEAP_INSTEAD_OF_STACK
8457         Safefree(buf);
8458 #endif
8459     }
8460
8461     if (rspara) {               /* have to do this both before and after */
8462         while (i != EOF) {      /* to make sure file boundaries work right */
8463             i = PerlIO_getc(fp);
8464             if (i != '\n') {
8465                 PerlIO_ungetc(fp,i);
8466                 break;
8467             }
8468         }
8469     }
8470
8471     return (SvCUR(sv) - append) ? SvPVX(sv) : NULL;
8472 }
8473
8474 /*
8475 =for apidoc sv_inc
8476
8477 Auto-increment of the value in the SV, doing string to numeric conversion
8478 if necessary.  Handles 'get' magic and operator overloading.
8479
8480 =cut
8481 */
8482
8483 void
8484 Perl_sv_inc(pTHX_ SV *const sv)
8485 {
8486     if (!sv)
8487         return;
8488     SvGETMAGIC(sv);
8489     sv_inc_nomg(sv);
8490 }
8491
8492 /*
8493 =for apidoc sv_inc_nomg
8494
8495 Auto-increment of the value in the SV, doing string to numeric conversion
8496 if necessary.  Handles operator overloading.  Skips handling 'get' magic.
8497
8498 =cut
8499 */
8500
8501 void
8502 Perl_sv_inc_nomg(pTHX_ SV *const sv)
8503 {
8504     char *d;
8505     int flags;
8506
8507     if (!sv)
8508         return;
8509     if (SvTHINKFIRST(sv)) {
8510         if (SvREADONLY(sv)) {
8511                 Perl_croak_no_modify();
8512         }
8513         if (SvROK(sv)) {
8514             IV i;
8515             if (SvAMAGIC(sv) && AMG_CALLunary(sv, inc_amg))
8516                 return;
8517             i = PTR2IV(SvRV(sv));
8518             sv_unref(sv);
8519             sv_setiv(sv, i);
8520         }
8521         else sv_force_normal_flags(sv, 0);
8522     }
8523     flags = SvFLAGS(sv);
8524     if ((flags & (SVp_NOK|SVp_IOK)) == SVp_NOK) {
8525         /* It's (privately or publicly) a float, but not tested as an
8526            integer, so test it to see. */
8527         (void) SvIV(sv);
8528         flags = SvFLAGS(sv);
8529     }
8530     if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
8531         /* It's publicly an integer, or privately an integer-not-float */
8532 #ifdef PERL_PRESERVE_IVUV
8533       oops_its_int:
8534 #endif
8535         if (SvIsUV(sv)) {
8536             if (SvUVX(sv) == UV_MAX)
8537                 sv_setnv(sv, UV_MAX_P1);
8538             else
8539                 (void)SvIOK_only_UV(sv);
8540                 SvUV_set(sv, SvUVX(sv) + 1);
8541         } else {
8542             if (SvIVX(sv) == IV_MAX)
8543                 sv_setuv(sv, (UV)IV_MAX + 1);
8544             else {
8545                 (void)SvIOK_only(sv);
8546                 SvIV_set(sv, SvIVX(sv) + 1);
8547             }   
8548         }
8549         return;
8550     }
8551     if (flags & SVp_NOK) {
8552         const NV was = SvNVX(sv);
8553         if (NV_OVERFLOWS_INTEGERS_AT &&
8554             was >= NV_OVERFLOWS_INTEGERS_AT) {
8555             /* diag_listed_as: Lost precision when %s %f by 1 */
8556             Perl_ck_warner(aTHX_ packWARN(WARN_IMPRECISION),
8557                            "Lost precision when incrementing %" NVff " by 1",
8558                            was);
8559         }
8560         (void)SvNOK_only(sv);
8561         SvNV_set(sv, was + 1.0);
8562         return;
8563     }
8564
8565     if (!(flags & SVp_POK) || !*SvPVX_const(sv)) {
8566         if ((flags & SVTYPEMASK) < SVt_PVIV)
8567             sv_upgrade(sv, ((flags & SVTYPEMASK) > SVt_IV ? SVt_PVIV : SVt_IV));
8568         (void)SvIOK_only(sv);
8569         SvIV_set(sv, 1);
8570         return;
8571     }
8572     d = SvPVX(sv);
8573     while (isALPHA(*d)) d++;
8574     while (isDIGIT(*d)) d++;
8575     if (d < SvEND(sv)) {
8576         const int numtype = grok_number_flags(SvPVX_const(sv), SvCUR(sv), NULL, PERL_SCAN_TRAILING);
8577 #ifdef PERL_PRESERVE_IVUV
8578         /* Got to punt this as an integer if needs be, but we don't issue
8579            warnings. Probably ought to make the sv_iv_please() that does
8580            the conversion if possible, and silently.  */
8581         if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
8582             /* Need to try really hard to see if it's an integer.
8583                9.22337203685478e+18 is an integer.
8584                but "9.22337203685478e+18" + 0 is UV=9223372036854779904
8585                so $a="9.22337203685478e+18"; $a+0; $a++
8586                needs to be the same as $a="9.22337203685478e+18"; $a++
8587                or we go insane. */
8588         
8589             (void) sv_2iv(sv);
8590             if (SvIOK(sv))
8591                 goto oops_its_int;
8592
8593             /* sv_2iv *should* have made this an NV */
8594             if (flags & SVp_NOK) {
8595                 (void)SvNOK_only(sv);
8596                 SvNV_set(sv, SvNVX(sv) + 1.0);
8597                 return;
8598             }
8599             /* I don't think we can get here. Maybe I should assert this
8600                And if we do get here I suspect that sv_setnv will croak. NWC
8601                Fall through. */
8602             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_inc punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
8603                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
8604         }
8605 #endif /* PERL_PRESERVE_IVUV */
8606         if (!numtype && ckWARN(WARN_NUMERIC))
8607             not_incrementable(sv);
8608         sv_setnv(sv,Atof(SvPVX_const(sv)) + 1.0);
8609         return;
8610     }
8611     d--;
8612     while (d >= SvPVX_const(sv)) {
8613         if (isDIGIT(*d)) {
8614             if (++*d <= '9')
8615                 return;
8616             *(d--) = '0';
8617         }
8618         else {
8619 #ifdef EBCDIC
8620             /* MKS: The original code here died if letters weren't consecutive.
8621              * at least it didn't have to worry about non-C locales.  The
8622              * new code assumes that ('z'-'a')==('Z'-'A'), letters are
8623              * arranged in order (although not consecutively) and that only
8624              * [A-Za-z] are accepted by isALPHA in the C locale.
8625              */
8626             if (isALPHA_FOLD_NE(*d, 'z')) {
8627                 do { ++*d; } while (!isALPHA(*d));
8628                 return;
8629             }
8630             *(d--) -= 'z' - 'a';
8631 #else
8632             ++*d;
8633             if (isALPHA(*d))
8634                 return;
8635             *(d--) -= 'z' - 'a' + 1;
8636 #endif
8637         }
8638     }
8639     /* oh,oh, the number grew */
8640     SvGROW(sv, SvCUR(sv) + 2);
8641     SvCUR_set(sv, SvCUR(sv) + 1);
8642     for (d = SvPVX(sv) + SvCUR(sv); d > SvPVX_const(sv); d--)
8643         *d = d[-1];
8644     if (isDIGIT(d[1]))
8645         *d = '1';
8646     else
8647         *d = d[1];
8648 }
8649
8650 /*
8651 =for apidoc sv_dec
8652
8653 Auto-decrement of the value in the SV, doing string to numeric conversion
8654 if necessary.  Handles 'get' magic and operator overloading.
8655
8656 =cut
8657 */
8658
8659 void
8660 Perl_sv_dec(pTHX_ SV *const sv)
8661 {
8662     if (!sv)
8663         return;
8664     SvGETMAGIC(sv);
8665     sv_dec_nomg(sv);
8666 }
8667
8668 /*
8669 =for apidoc sv_dec_nomg
8670
8671 Auto-decrement of the value in the SV, doing string to numeric conversion
8672 if necessary.  Handles operator overloading.  Skips handling 'get' magic.
8673
8674 =cut
8675 */
8676
8677 void
8678 Perl_sv_dec_nomg(pTHX_ SV *const sv)
8679 {
8680     int flags;
8681
8682     if (!sv)
8683         return;
8684     if (SvTHINKFIRST(sv)) {
8685         if (SvREADONLY(sv)) {
8686                 Perl_croak_no_modify();
8687         }
8688         if (SvROK(sv)) {
8689             IV i;
8690             if (SvAMAGIC(sv) && AMG_CALLunary(sv, dec_amg))
8691                 return;
8692             i = PTR2IV(SvRV(sv));
8693             sv_unref(sv);
8694             sv_setiv(sv, i);
8695         }
8696         else sv_force_normal_flags(sv, 0);
8697     }
8698     /* Unlike sv_inc we don't have to worry about string-never-numbers
8699        and keeping them magic. But we mustn't warn on punting */
8700     flags = SvFLAGS(sv);
8701     if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
8702         /* It's publicly an integer, or privately an integer-not-float */
8703 #ifdef PERL_PRESERVE_IVUV
8704       oops_its_int:
8705 #endif
8706         if (SvIsUV(sv)) {
8707             if (SvUVX(sv) == 0) {
8708                 (void)SvIOK_only(sv);
8709                 SvIV_set(sv, -1);
8710             }
8711             else {
8712                 (void)SvIOK_only_UV(sv);
8713                 SvUV_set(sv, SvUVX(sv) - 1);
8714             }   
8715         } else {
8716             if (SvIVX(sv) == IV_MIN) {
8717                 sv_setnv(sv, (NV)IV_MIN);
8718                 goto oops_its_num;
8719             }
8720             else {
8721                 (void)SvIOK_only(sv);
8722                 SvIV_set(sv, SvIVX(sv) - 1);
8723             }   
8724         }
8725         return;
8726     }
8727     if (flags & SVp_NOK) {
8728     oops_its_num:
8729         {
8730             const NV was = SvNVX(sv);
8731             if (NV_OVERFLOWS_INTEGERS_AT &&
8732                 was <= -NV_OVERFLOWS_INTEGERS_AT) {
8733                 /* diag_listed_as: Lost precision when %s %f by 1 */
8734                 Perl_ck_warner(aTHX_ packWARN(WARN_IMPRECISION),
8735                                "Lost precision when decrementing %" NVff " by 1",
8736                                was);
8737             }
8738             (void)SvNOK_only(sv);
8739             SvNV_set(sv, was - 1.0);
8740             return;
8741         }
8742     }
8743     if (!(flags & SVp_POK)) {
8744         if ((flags & SVTYPEMASK) < SVt_PVIV)
8745             sv_upgrade(sv, ((flags & SVTYPEMASK) > SVt_IV) ? SVt_PVIV : SVt_IV);
8746         SvIV_set(sv, -1);
8747         (void)SvIOK_only(sv);
8748         return;
8749     }
8750 #ifdef PERL_PRESERVE_IVUV
8751     {
8752         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), NULL);
8753         if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
8754             /* Need to try really hard to see if it's an integer.
8755                9.22337203685478e+18 is an integer.
8756                but "9.22337203685478e+18" + 0 is UV=9223372036854779904
8757                so $a="9.22337203685478e+18"; $a+0; $a--
8758                needs to be the same as $a="9.22337203685478e+18"; $a--
8759                or we go insane. */
8760         
8761             (void) sv_2iv(sv);
8762             if (SvIOK(sv))
8763                 goto oops_its_int;
8764
8765             /* sv_2iv *should* have made this an NV */
8766             if (flags & SVp_NOK) {
8767                 (void)SvNOK_only(sv);
8768                 SvNV_set(sv, SvNVX(sv) - 1.0);
8769                 return;
8770             }
8771             /* I don't think we can get here. Maybe I should assert this
8772                And if we do get here I suspect that sv_setnv will croak. NWC
8773                Fall through. */
8774             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_dec punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
8775                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
8776         }
8777     }
8778 #endif /* PERL_PRESERVE_IVUV */
8779     sv_setnv(sv,Atof(SvPVX_const(sv)) - 1.0);   /* punt */
8780 }
8781
8782 /* this define is used to eliminate a chunk of duplicated but shared logic
8783  * it has the suffix __SV_C to signal that it isnt API, and isnt meant to be
8784  * used anywhere but here - yves
8785  */
8786 #define PUSH_EXTEND_MORTAL__SV_C(AnSv) \
8787     STMT_START {      \
8788         EXTEND_MORTAL(1); \
8789         PL_tmps_stack[++PL_tmps_ix] = (AnSv); \
8790     } STMT_END
8791
8792 /*
8793 =for apidoc sv_mortalcopy
8794
8795 Creates a new SV which is a copy of the original SV (using C<sv_setsv>).
8796 The new SV is marked as mortal.  It will be destroyed "soon", either by an
8797 explicit call to FREETMPS, or by an implicit call at places such as
8798 statement boundaries.  See also C<sv_newmortal> and C<sv_2mortal>.
8799
8800 =cut
8801 */
8802
8803 /* Make a string that will exist for the duration of the expression
8804  * evaluation.  Actually, it may have to last longer than that, but
8805  * hopefully we won't free it until it has been assigned to a
8806  * permanent location. */
8807
8808 SV *
8809 Perl_sv_mortalcopy_flags(pTHX_ SV *const oldstr, U32 flags)
8810 {
8811     SV *sv;
8812
8813     if (flags & SV_GMAGIC)
8814         SvGETMAGIC(oldstr); /* before new_SV, in case it dies */
8815     new_SV(sv);
8816     sv_setsv_flags(sv,oldstr,flags & ~SV_GMAGIC);
8817     PUSH_EXTEND_MORTAL__SV_C(sv);
8818     SvTEMP_on(sv);
8819     return sv;
8820 }
8821
8822 /*
8823 =for apidoc sv_newmortal
8824
8825 Creates a new null SV which is mortal.  The reference count of the SV is
8826 set to 1.  It will be destroyed "soon", either by an explicit call to
8827 FREETMPS, or by an implicit call at places such as statement boundaries.
8828 See also C<sv_mortalcopy> and C<sv_2mortal>.
8829
8830 =cut
8831 */
8832
8833 SV *
8834 Perl_sv_newmortal(pTHX)
8835 {
8836     SV *sv;
8837
8838     new_SV(sv);
8839     SvFLAGS(sv) = SVs_TEMP;
8840     PUSH_EXTEND_MORTAL__SV_C(sv);
8841     return sv;
8842 }
8843
8844
8845 /*
8846 =for apidoc newSVpvn_flags
8847
8848 Creates a new SV and copies a string (which may contain C<NUL> (C<\0>)
8849 characters) into it.  The reference count for the
8850 SV is set to 1.  Note that if C<len> is zero, Perl will create a zero length
8851 string.  You are responsible for ensuring that the source string is at least
8852 C<len> bytes long.  If the C<s> argument is NULL the new SV will be undefined.
8853 Currently the only flag bits accepted are C<SVf_UTF8> and C<SVs_TEMP>.
8854 If C<SVs_TEMP> is set, then C<sv_2mortal()> is called on the result before
8855 returning.  If C<SVf_UTF8> is set, C<s>
8856 is considered to be in UTF-8 and the
8857 C<SVf_UTF8> flag will be set on the new SV.
8858 C<newSVpvn_utf8()> is a convenience wrapper for this function, defined as
8859
8860     #define newSVpvn_utf8(s, len, u)                    \
8861         newSVpvn_flags((s), (len), (u) ? SVf_UTF8 : 0)
8862
8863 =cut
8864 */
8865
8866 SV *
8867 Perl_newSVpvn_flags(pTHX_ const char *const s, const STRLEN len, const U32 flags)
8868 {
8869     SV *sv;
8870
8871     /* All the flags we don't support must be zero.
8872        And we're new code so I'm going to assert this from the start.  */
8873     assert(!(flags & ~(SVf_UTF8|SVs_TEMP)));
8874     new_SV(sv);
8875     sv_setpvn(sv,s,len);
8876
8877     /* This code used to do a sv_2mortal(), however we now unroll the call to
8878      * sv_2mortal() and do what it does ourselves here.  Since we have asserted
8879      * that flags can only have the SVf_UTF8 and/or SVs_TEMP flags set above we
8880      * can use it to enable the sv flags directly (bypassing SvTEMP_on), which
8881      * in turn means we dont need to mask out the SVf_UTF8 flag below, which
8882      * means that we eliminate quite a few steps than it looks - Yves
8883      * (explaining patch by gfx) */
8884
8885     SvFLAGS(sv) |= flags;
8886
8887     if(flags & SVs_TEMP){
8888         PUSH_EXTEND_MORTAL__SV_C(sv);
8889     }
8890
8891     return sv;
8892 }
8893
8894 /*
8895 =for apidoc sv_2mortal
8896
8897 Marks an existing SV as mortal.  The SV will be destroyed "soon", either
8898 by an explicit call to FREETMPS, or by an implicit call at places such as
8899 statement boundaries.  SvTEMP() is turned on which means that the SV's
8900 string buffer can be "stolen" if this SV is copied.  See also C<sv_newmortal>
8901 and C<sv_mortalcopy>.
8902
8903 =cut
8904 */
8905
8906 SV *
8907 Perl_sv_2mortal(pTHX_ SV *const sv)
8908 {
8909     dVAR;
8910     if (!sv)
8911         return NULL;
8912     if (SvIMMORTAL(sv))
8913         return sv;
8914     PUSH_EXTEND_MORTAL__SV_C(sv);
8915     SvTEMP_on(sv);
8916     return sv;
8917 }
8918
8919 /*
8920 =for apidoc newSVpv
8921
8922 Creates a new SV and copies a string (which may contain C<NUL> (C<\0>)
8923 characters) into it.  The reference count for the
8924 SV is set to 1.  If C<len> is zero, Perl will compute the length using
8925 strlen(), (which means if you use this option, that C<s> can't have embedded
8926 C<NUL> characters and has to have a terminating C<NUL> byte).
8927
8928 For efficiency, consider using C<newSVpvn> instead.
8929
8930 =cut
8931 */
8932
8933 SV *
8934 Perl_newSVpv(pTHX_ const char *const s, const STRLEN len)
8935 {
8936     SV *sv;
8937
8938     new_SV(sv);
8939     sv_setpvn(sv, s, len || s == NULL ? len : strlen(s));
8940     return sv;
8941 }
8942
8943 /*
8944 =for apidoc newSVpvn
8945
8946 Creates a new SV and copies a string into it, which may contain C<NUL> characters
8947 (C<\0>) and other binary data.  The reference count for the SV is set to 1.
8948 Note that if C<len> is zero, Perl will create a zero length (Perl) string.  You
8949 are responsible for ensuring that the source buffer is at least
8950 C<len> bytes long.  If the C<buffer> argument is NULL the new SV will be
8951 undefined.
8952
8953 =cut
8954 */
8955
8956 SV *
8957 Perl_newSVpvn(pTHX_ const char *const buffer, const STRLEN len)
8958 {
8959     SV *sv;
8960     new_SV(sv);
8961     sv_setpvn(sv,buffer,len);
8962     return sv;
8963 }
8964
8965 /*
8966 =for apidoc newSVhek
8967
8968 Creates a new SV from the hash key structure.  It will generate scalars that
8969 point to the shared string table where possible.  Returns a new (undefined)
8970 SV if the hek is NULL.
8971
8972 =cut
8973 */
8974
8975 SV *
8976 Perl_newSVhek(pTHX_ const HEK *const hek)
8977 {
8978     if (!hek) {
8979         SV *sv;
8980
8981         new_SV(sv);
8982         return sv;
8983     }
8984
8985     if (HEK_LEN(hek) == HEf_SVKEY) {
8986         return newSVsv(*(SV**)HEK_KEY(hek));
8987     } else {
8988         const int flags = HEK_FLAGS(hek);
8989         if (flags & HVhek_WASUTF8) {
8990             /* Trouble :-)
8991                Andreas would like keys he put in as utf8 to come back as utf8
8992             */
8993             STRLEN utf8_len = HEK_LEN(hek);
8994             SV * const sv = newSV_type(SVt_PV);
8995             char *as_utf8 = (char *)bytes_to_utf8 ((U8*)HEK_KEY(hek), &utf8_len);
8996             /* bytes_to_utf8() allocates a new string, which we can repurpose: */
8997             sv_usepvn_flags(sv, as_utf8, utf8_len, SV_HAS_TRAILING_NUL);
8998             SvUTF8_on (sv);
8999             return sv;
9000         } else if (flags & HVhek_UNSHARED) {
9001             /* A hash that isn't using shared hash keys has to have
9002                the flag in every key so that we know not to try to call
9003                share_hek_hek on it.  */
9004
9005             SV * const sv = newSVpvn (HEK_KEY(hek), HEK_LEN(hek));
9006             if (HEK_UTF8(hek))
9007                 SvUTF8_on (sv);
9008             return sv;
9009         }
9010         /* This will be overwhelminly the most common case.  */
9011         {
9012             /* Inline most of newSVpvn_share(), because share_hek_hek() is far
9013                more efficient than sharepvn().  */
9014             SV *sv;
9015
9016             new_SV(sv);
9017             sv_upgrade(sv, SVt_PV);
9018             SvPV_set(sv, (char *)HEK_KEY(share_hek_hek(hek)));
9019             SvCUR_set(sv, HEK_LEN(hek));
9020             SvLEN_set(sv, 0);
9021             SvIsCOW_on(sv);
9022             SvPOK_on(sv);
9023             if (HEK_UTF8(hek))
9024                 SvUTF8_on(sv);
9025             return sv;
9026         }
9027     }
9028 }
9029
9030 /*
9031 =for apidoc newSVpvn_share
9032
9033 Creates a new SV with its SvPVX_const pointing to a shared string in the string
9034 table.  If the string does not already exist in the table, it is
9035 created first.  Turns on the SvIsCOW flag (or READONLY
9036 and FAKE in 5.16 and earlier).  If the C<hash> parameter
9037 is non-zero, that value is used; otherwise the hash is computed.
9038 The string's hash can later be retrieved from the SV
9039 with the C<SvSHARED_HASH()> macro.  The idea here is
9040 that as the string table is used for shared hash keys these strings will have
9041 SvPVX_const == HeKEY and hash lookup will avoid string compare.
9042
9043 =cut
9044 */
9045
9046 SV *
9047 Perl_newSVpvn_share(pTHX_ const char *src, I32 len, U32 hash)
9048 {
9049     dVAR;
9050     SV *sv;
9051     bool is_utf8 = FALSE;
9052     const char *const orig_src = src;
9053
9054     if (len < 0) {
9055         STRLEN tmplen = -len;
9056         is_utf8 = TRUE;
9057         /* See the note in hv.c:hv_fetch() --jhi */
9058         src = (char*)bytes_from_utf8((const U8*)src, &tmplen, &is_utf8);
9059         len = tmplen;
9060     }
9061     if (!hash)
9062         PERL_HASH(hash, src, len);
9063     new_SV(sv);
9064     /* The logic for this is inlined in S_mro_get_linear_isa_dfs(), so if it
9065        changes here, update it there too.  */
9066     sv_upgrade(sv, SVt_PV);
9067     SvPV_set(sv, sharepvn(src, is_utf8?-len:len, hash));
9068     SvCUR_set(sv, len);
9069     SvLEN_set(sv, 0);
9070     SvIsCOW_on(sv);
9071     SvPOK_on(sv);
9072     if (is_utf8)
9073         SvUTF8_on(sv);
9074     if (src != orig_src)
9075         Safefree(src);
9076     return sv;
9077 }
9078
9079 /*
9080 =for apidoc newSVpv_share
9081
9082 Like C<newSVpvn_share>, but takes a C<NUL>-terminated string instead of a
9083 string/length pair.
9084
9085 =cut
9086 */
9087
9088 SV *
9089 Perl_newSVpv_share(pTHX_ const char *src, U32 hash)
9090 {
9091     return newSVpvn_share(src, strlen(src), hash);
9092 }
9093
9094 #if defined(PERL_IMPLICIT_CONTEXT)
9095
9096 /* pTHX_ magic can't cope with varargs, so this is a no-context
9097  * version of the main function, (which may itself be aliased to us).
9098  * Don't access this version directly.
9099  */
9100
9101 SV *
9102 Perl_newSVpvf_nocontext(const char *const pat, ...)
9103 {
9104     dTHX;
9105     SV *sv;
9106     va_list args;
9107
9108     PERL_ARGS_ASSERT_NEWSVPVF_NOCONTEXT;
9109
9110     va_start(args, pat);
9111     sv = vnewSVpvf(pat, &args);
9112     va_end(args);
9113     return sv;
9114 }
9115 #endif
9116
9117 /*
9118 =for apidoc newSVpvf
9119
9120 Creates a new SV and initializes it with the string formatted like
9121 C<sprintf>.
9122
9123 =cut
9124 */
9125
9126 SV *
9127 Perl_newSVpvf(pTHX_ const char *const pat, ...)
9128 {
9129     SV *sv;
9130     va_list args;
9131
9132     PERL_ARGS_ASSERT_NEWSVPVF;
9133
9134     va_start(args, pat);
9135     sv = vnewSVpvf(pat, &args);
9136     va_end(args);
9137     return sv;
9138 }
9139
9140 /* backend for newSVpvf() and newSVpvf_nocontext() */
9141
9142 SV *
9143 Perl_vnewSVpvf(pTHX_ const char *const pat, va_list *const args)
9144 {
9145     SV *sv;
9146
9147     PERL_ARGS_ASSERT_VNEWSVPVF;
9148
9149     new_SV(sv);
9150     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
9151     return sv;
9152 }
9153
9154 /*
9155 =for apidoc newSVnv
9156
9157 Creates a new SV and copies a floating point value into it.
9158 The reference count for the SV is set to 1.
9159
9160 =cut
9161 */
9162
9163 SV *
9164 Perl_newSVnv(pTHX_ const NV n)
9165 {
9166     SV *sv;
9167
9168     new_SV(sv);
9169     sv_setnv(sv,n);
9170     return sv;
9171 }
9172
9173 /*
9174 =for apidoc newSViv
9175
9176 Creates a new SV and copies an integer into it.  The reference count for the
9177 SV is set to 1.
9178
9179 =cut
9180 */
9181
9182 SV *
9183 Perl_newSViv(pTHX_ const IV i)
9184 {
9185     SV *sv;
9186
9187     new_SV(sv);
9188     sv_setiv(sv,i);
9189     return sv;
9190 }
9191
9192 /*
9193 =for apidoc newSVuv
9194
9195 Creates a new SV and copies an unsigned integer into it.
9196 The reference count for the SV is set to 1.
9197
9198 =cut
9199 */
9200
9201 SV *
9202 Perl_newSVuv(pTHX_ const UV u)
9203 {
9204     SV *sv;
9205
9206     new_SV(sv);
9207     sv_setuv(sv,u);
9208     return sv;
9209 }
9210
9211 /*
9212 =for apidoc newSV_type
9213
9214 Creates a new SV, of the type specified.  The reference count for the new SV
9215 is set to 1.
9216
9217 =cut
9218 */
9219
9220 SV *
9221 Perl_newSV_type(pTHX_ const svtype type)
9222 {
9223     SV *sv;
9224
9225     new_SV(sv);
9226     sv_upgrade(sv, type);
9227     return sv;
9228 }
9229
9230 /*
9231 =for apidoc newRV_noinc
9232
9233 Creates an RV wrapper for an SV.  The reference count for the original
9234 SV is B<not> incremented.
9235
9236 =cut
9237 */
9238
9239 SV *
9240 Perl_newRV_noinc(pTHX_ SV *const tmpRef)
9241 {
9242     SV *sv = newSV_type(SVt_IV);
9243
9244     PERL_ARGS_ASSERT_NEWRV_NOINC;
9245
9246     SvTEMP_off(tmpRef);
9247     SvRV_set(sv, tmpRef);
9248     SvROK_on(sv);
9249     return sv;
9250 }
9251
9252 /* newRV_inc is the official function name to use now.
9253  * newRV_inc is in fact #defined to newRV in sv.h
9254  */
9255
9256 SV *
9257 Perl_newRV(pTHX_ SV *const sv)
9258 {
9259     PERL_ARGS_ASSERT_NEWRV;
9260
9261     return newRV_noinc(SvREFCNT_inc_simple_NN(sv));
9262 }
9263
9264 /*
9265 =for apidoc newSVsv
9266
9267 Creates a new SV which is an exact duplicate of the original SV.
9268 (Uses C<sv_setsv>.)
9269
9270 =cut
9271 */
9272
9273 SV *
9274 Perl_newSVsv(pTHX_ SV *const old)
9275 {
9276     SV *sv;
9277
9278     if (!old)
9279         return NULL;
9280     if (SvTYPE(old) == (svtype)SVTYPEMASK) {
9281         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "semi-panic: attempt to dup freed string");
9282         return NULL;
9283     }
9284     /* Do this here, otherwise we leak the new SV if this croaks. */
9285     SvGETMAGIC(old);
9286     new_SV(sv);
9287     /* SV_NOSTEAL prevents TEMP buffers being, well, stolen, and saves games
9288        with SvTEMP_off and SvTEMP_on round a call to sv_setsv.  */
9289     sv_setsv_flags(sv, old, SV_NOSTEAL);
9290     return sv;
9291 }
9292
9293 /*
9294 =for apidoc sv_reset
9295
9296 Underlying implementation for the C<reset> Perl function.
9297 Note that the perl-level function is vaguely deprecated.
9298
9299 =cut
9300 */
9301
9302 void
9303 Perl_sv_reset(pTHX_ const char *s, HV *const stash)
9304 {
9305     PERL_ARGS_ASSERT_SV_RESET;
9306
9307     sv_resetpvn(*s ? s : NULL, strlen(s), stash);
9308 }
9309
9310 void
9311 Perl_sv_resetpvn(pTHX_ const char *s, STRLEN len, HV * const stash)
9312 {
9313     char todo[PERL_UCHAR_MAX+1];
9314     const char *send;
9315
9316     if (!stash || SvTYPE(stash) != SVt_PVHV)
9317         return;
9318
9319     if (!s) {           /* reset ?? searches */
9320         MAGIC * const mg = mg_find((const SV *)stash, PERL_MAGIC_symtab);
9321         if (mg) {
9322             const U32 count = mg->mg_len / sizeof(PMOP**);
9323             PMOP **pmp = (PMOP**) mg->mg_ptr;
9324             PMOP *const *const end = pmp + count;
9325
9326             while (pmp < end) {
9327 #ifdef USE_ITHREADS
9328                 SvREADONLY_off(PL_regex_pad[(*pmp)->op_pmoffset]);
9329 #else
9330                 (*pmp)->op_pmflags &= ~PMf_USED;
9331 #endif
9332                 ++pmp;
9333             }
9334         }
9335         return;
9336     }
9337
9338     /* reset variables */
9339
9340     if (!HvARRAY(stash))
9341         return;
9342
9343     Zero(todo, 256, char);
9344     send = s + len;
9345     while (s < send) {
9346         I32 max;
9347         I32 i = (unsigned char)*s;
9348         if (s[1] == '-') {
9349             s += 2;
9350         }
9351         max = (unsigned char)*s++;
9352         for ( ; i <= max; i++) {
9353             todo[i] = 1;
9354         }
9355         for (i = 0; i <= (I32) HvMAX(stash); i++) {
9356             HE *entry;
9357             for (entry = HvARRAY(stash)[i];
9358                  entry;
9359                  entry = HeNEXT(entry))
9360             {
9361                 GV *gv;
9362                 SV *sv;
9363
9364                 if (!todo[(U8)*HeKEY(entry)])
9365                     continue;
9366                 gv = MUTABLE_GV(HeVAL(entry));
9367                 sv = GvSV(gv);
9368                 if (sv && !SvREADONLY(sv)) {
9369                     SV_CHECK_THINKFIRST_COW_DROP(sv);
9370                     if (!isGV(sv)) SvOK_off(sv);
9371                 }
9372                 if (GvAV(gv)) {
9373                     av_clear(GvAV(gv));
9374                 }
9375                 if (GvHV(gv) && !HvNAME_get(GvHV(gv))) {
9376                     hv_clear(GvHV(gv));
9377                 }
9378             }
9379         }
9380     }
9381 }
9382
9383 /*
9384 =for apidoc sv_2io
9385
9386 Using various gambits, try to get an IO from an SV: the IO slot if its a
9387 GV; or the recursive result if we're an RV; or the IO slot of the symbol
9388 named after the PV if we're a string.
9389
9390 'Get' magic is ignored on the sv passed in, but will be called on
9391 C<SvRV(sv)> if sv is an RV.
9392
9393 =cut
9394 */
9395
9396 IO*
9397 Perl_sv_2io(pTHX_ SV *const sv)
9398 {
9399     IO* io;
9400     GV* gv;
9401
9402     PERL_ARGS_ASSERT_SV_2IO;
9403
9404     switch (SvTYPE(sv)) {
9405     case SVt_PVIO:
9406         io = MUTABLE_IO(sv);
9407         break;
9408     case SVt_PVGV:
9409     case SVt_PVLV:
9410         if (isGV_with_GP(sv)) {
9411             gv = MUTABLE_GV(sv);
9412             io = GvIO(gv);
9413             if (!io)
9414                 Perl_croak(aTHX_ "Bad filehandle: %"HEKf,
9415                                     HEKfARG(GvNAME_HEK(gv)));
9416             break;
9417         }
9418         /* FALLTHROUGH */
9419     default:
9420         if (!SvOK(sv))
9421             Perl_croak(aTHX_ PL_no_usym, "filehandle");
9422         if (SvROK(sv)) {
9423             SvGETMAGIC(SvRV(sv));
9424             return sv_2io(SvRV(sv));
9425         }
9426         gv = gv_fetchsv_nomg(sv, 0, SVt_PVIO);
9427         if (gv)
9428             io = GvIO(gv);
9429         else
9430             io = 0;
9431         if (!io) {
9432             SV *newsv = sv;
9433             if (SvGMAGICAL(sv)) {
9434                 newsv = sv_newmortal();
9435                 sv_setsv_nomg(newsv, sv);
9436             }
9437             Perl_croak(aTHX_ "Bad filehandle: %"SVf, SVfARG(newsv));
9438         }
9439         break;
9440     }
9441     return io;
9442 }
9443
9444 /*
9445 =for apidoc sv_2cv
9446
9447 Using various gambits, try to get a CV from an SV; in addition, try if
9448 possible to set C<*st> and C<*gvp> to the stash and GV associated with it.
9449 The flags in C<lref> are passed to gv_fetchsv.
9450
9451 =cut
9452 */
9453
9454 CV *
9455 Perl_sv_2cv(pTHX_ SV *sv, HV **const st, GV **const gvp, const I32 lref)
9456 {
9457     GV *gv = NULL;
9458     CV *cv = NULL;
9459
9460     PERL_ARGS_ASSERT_SV_2CV;
9461
9462     if (!sv) {
9463         *st = NULL;
9464         *gvp = NULL;
9465         return NULL;
9466     }
9467     switch (SvTYPE(sv)) {
9468     case SVt_PVCV:
9469         *st = CvSTASH(sv);
9470         *gvp = NULL;
9471         return MUTABLE_CV(sv);
9472     case SVt_PVHV:
9473     case SVt_PVAV:
9474         *st = NULL;
9475         *gvp = NULL;
9476         return NULL;
9477     default:
9478         SvGETMAGIC(sv);
9479         if (SvROK(sv)) {
9480             if (SvAMAGIC(sv))
9481                 sv = amagic_deref_call(sv, to_cv_amg);
9482
9483             sv = SvRV(sv);
9484             if (SvTYPE(sv) == SVt_PVCV) {
9485                 cv = MUTABLE_CV(sv);
9486                 *gvp = NULL;
9487                 *st = CvSTASH(cv);
9488                 return cv;
9489             }
9490             else if(SvGETMAGIC(sv), isGV_with_GP(sv))
9491                 gv = MUTABLE_GV(sv);
9492             else
9493                 Perl_croak(aTHX_ "Not a subroutine reference");
9494         }
9495         else if (isGV_with_GP(sv)) {
9496             gv = MUTABLE_GV(sv);
9497         }
9498         else {
9499             gv = gv_fetchsv_nomg(sv, lref, SVt_PVCV);
9500         }
9501         *gvp = gv;
9502         if (!gv) {
9503             *st = NULL;
9504             return NULL;
9505         }
9506         /* Some flags to gv_fetchsv mean don't really create the GV  */
9507         if (!isGV_with_GP(gv)) {
9508             *st = NULL;
9509             return NULL;
9510         }
9511         *st = GvESTASH(gv);
9512         if (lref & ~GV_ADDMG && !GvCVu(gv)) {
9513             /* XXX this is probably not what they think they're getting.
9514              * It has the same effect as "sub name;", i.e. just a forward
9515              * declaration! */
9516             newSTUB(gv,0);
9517         }
9518         return GvCVu(gv);
9519     }
9520 }
9521
9522 /*
9523 =for apidoc sv_true
9524
9525 Returns true if the SV has a true value by Perl's rules.
9526 Use the C<SvTRUE> macro instead, which may call C<sv_true()> or may
9527 instead use an in-line version.
9528
9529 =cut
9530 */
9531
9532 I32
9533 Perl_sv_true(pTHX_ SV *const sv)
9534 {
9535     if (!sv)
9536         return 0;
9537     if (SvPOK(sv)) {
9538         const XPV* const tXpv = (XPV*)SvANY(sv);
9539         if (tXpv &&
9540                 (tXpv->xpv_cur > 1 ||
9541                 (tXpv->xpv_cur && *sv->sv_u.svu_pv != '0')))
9542             return 1;
9543         else
9544             return 0;
9545     }
9546     else {
9547         if (SvIOK(sv))
9548             return SvIVX(sv) != 0;
9549         else {
9550             if (SvNOK(sv))
9551                 return SvNVX(sv) != 0.0;
9552             else
9553                 return sv_2bool(sv);
9554         }
9555     }
9556 }
9557
9558 /*
9559 =for apidoc sv_pvn_force
9560
9561 Get a sensible string out of the SV somehow.
9562 A private implementation of the C<SvPV_force> macro for compilers which
9563 can't cope with complex macro expressions.  Always use the macro instead.
9564
9565 =for apidoc sv_pvn_force_flags
9566
9567 Get a sensible string out of the SV somehow.
9568 If C<flags> has C<SV_GMAGIC> bit set, will C<mg_get> on C<sv> if
9569 appropriate, else not.  C<sv_pvn_force> and C<sv_pvn_force_nomg> are
9570 implemented in terms of this function.
9571 You normally want to use the various wrapper macros instead: see
9572 C<SvPV_force> and C<SvPV_force_nomg>
9573
9574 =cut
9575 */
9576
9577 char *
9578 Perl_sv_pvn_force_flags(pTHX_ SV *const sv, STRLEN *const lp, const I32 flags)
9579 {
9580     PERL_ARGS_ASSERT_SV_PVN_FORCE_FLAGS;
9581
9582     if (flags & SV_GMAGIC) SvGETMAGIC(sv);
9583     if (SvTHINKFIRST(sv) && (!SvROK(sv) || SvREADONLY(sv)))
9584         sv_force_normal_flags(sv, 0);
9585
9586     if (SvPOK(sv)) {
9587         if (lp)
9588             *lp = SvCUR(sv);
9589     }
9590     else {
9591         char *s;
9592         STRLEN len;
9593  
9594         if (SvTYPE(sv) > SVt_PVLV
9595             || isGV_with_GP(sv))
9596             /* diag_listed_as: Can't coerce %s to %s in %s */
9597             Perl_croak(aTHX_ "Can't coerce %s to string in %s", sv_reftype(sv,0),
9598                 OP_DESC(PL_op));
9599         s = sv_2pv_flags(sv, &len, flags &~ SV_GMAGIC);
9600         if (!s) {
9601           s = (char *)"";
9602         }
9603         if (lp)
9604             *lp = len;
9605
9606         if (SvTYPE(sv) < SVt_PV ||
9607             s != SvPVX_const(sv)) {     /* Almost, but not quite, sv_setpvn() */
9608             if (SvROK(sv))
9609                 sv_unref(sv);
9610             SvUPGRADE(sv, SVt_PV);              /* Never FALSE */
9611             SvGROW(sv, len + 1);
9612             Move(s,SvPVX(sv),len,char);
9613             SvCUR_set(sv, len);
9614             SvPVX(sv)[len] = '\0';
9615         }
9616         if (!SvPOK(sv)) {
9617             SvPOK_on(sv);               /* validate pointer */
9618             SvTAINT(sv);
9619             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
9620                                   PTR2UV(sv),SvPVX_const(sv)));
9621         }
9622     }
9623     (void)SvPOK_only_UTF8(sv);
9624     return SvPVX_mutable(sv);
9625 }
9626
9627 /*
9628 =for apidoc sv_pvbyten_force
9629
9630 The backend for the C<SvPVbytex_force> macro.  Always use the macro
9631 instead.
9632
9633 =cut
9634 */
9635
9636 char *
9637 Perl_sv_pvbyten_force(pTHX_ SV *const sv, STRLEN *const lp)
9638 {
9639     PERL_ARGS_ASSERT_SV_PVBYTEN_FORCE;
9640
9641     sv_pvn_force(sv,lp);
9642     sv_utf8_downgrade(sv,0);
9643     *lp = SvCUR(sv);
9644     return SvPVX(sv);
9645 }
9646
9647 /*
9648 =for apidoc sv_pvutf8n_force
9649
9650 The backend for the C<SvPVutf8x_force> macro.  Always use the macro
9651 instead.
9652
9653 =cut
9654 */
9655
9656 char *
9657 Perl_sv_pvutf8n_force(pTHX_ SV *const sv, STRLEN *const lp)
9658 {
9659     PERL_ARGS_ASSERT_SV_PVUTF8N_FORCE;
9660
9661     sv_pvn_force(sv,0);
9662     sv_utf8_upgrade_nomg(sv);
9663     *lp = SvCUR(sv);
9664     return SvPVX(sv);
9665 }
9666
9667 /*
9668 =for apidoc sv_reftype
9669
9670 Returns a string describing what the SV is a reference to.
9671
9672 =cut
9673 */
9674
9675 const char *
9676 Perl_sv_reftype(pTHX_ const SV *const sv, const int ob)
9677 {
9678     PERL_ARGS_ASSERT_SV_REFTYPE;
9679     if (ob && SvOBJECT(sv)) {
9680         return SvPV_nolen_const(sv_ref(NULL, sv, ob));
9681     }
9682     else {
9683         /* WARNING - There is code, for instance in mg.c, that assumes that
9684          * the only reason that sv_reftype(sv,0) would return a string starting
9685          * with 'L' or 'S' is that it is a LVALUE or a SCALAR.
9686          * Yes this a dodgy way to do type checking, but it saves practically reimplementing
9687          * this routine inside other subs, and it saves time.
9688          * Do not change this assumption without searching for "dodgy type check" in
9689          * the code.
9690          * - Yves */
9691         switch (SvTYPE(sv)) {
9692         case SVt_NULL:
9693         case SVt_IV:
9694         case SVt_NV:
9695         case SVt_PV:
9696         case SVt_PVIV:
9697         case SVt_PVNV:
9698         case SVt_PVMG:
9699                                 if (SvVOK(sv))
9700                                     return "VSTRING";
9701                                 if (SvROK(sv))
9702                                     return "REF";
9703                                 else
9704                                     return "SCALAR";
9705
9706         case SVt_PVLV:          return (char *)  (SvROK(sv) ? "REF"
9707                                 /* tied lvalues should appear to be
9708                                  * scalars for backwards compatibility */
9709                                 : (isALPHA_FOLD_EQ(LvTYPE(sv), 't'))
9710                                     ? "SCALAR" : "LVALUE");
9711         case SVt_PVAV:          return "ARRAY";
9712         case SVt_PVHV:          return "HASH";
9713         case SVt_PVCV:          return "CODE";
9714         case SVt_PVGV:          return (char *) (isGV_with_GP(sv)
9715                                     ? "GLOB" : "SCALAR");
9716         case SVt_PVFM:          return "FORMAT";
9717         case SVt_PVIO:          return "IO";
9718         case SVt_INVLIST:       return "INVLIST";
9719         case SVt_REGEXP:        return "REGEXP";
9720         default:                return "UNKNOWN";
9721         }
9722     }
9723 }
9724
9725 /*
9726 =for apidoc sv_ref
9727
9728 Returns a SV describing what the SV passed in is a reference to.
9729
9730 =cut
9731 */
9732
9733 SV *
9734 Perl_sv_ref(pTHX_ SV *dst, const SV *const sv, const int ob)
9735 {
9736     PERL_ARGS_ASSERT_SV_REF;
9737
9738     if (!dst)
9739         dst = sv_newmortal();
9740
9741     if (ob && SvOBJECT(sv)) {
9742         HvNAME_get(SvSTASH(sv))
9743                     ? sv_sethek(dst, HvNAME_HEK(SvSTASH(sv)))
9744                     : sv_setpvn(dst, "__ANON__", 8);
9745     }
9746     else {
9747         const char * reftype = sv_reftype(sv, 0);
9748         sv_setpv(dst, reftype);
9749     }
9750     return dst;
9751 }
9752
9753 /*
9754 =for apidoc sv_isobject
9755
9756 Returns a boolean indicating whether the SV is an RV pointing to a blessed
9757 object.  If the SV is not an RV, or if the object is not blessed, then this
9758 will return false.
9759
9760 =cut
9761 */
9762
9763 int
9764 Perl_sv_isobject(pTHX_ SV *sv)
9765 {
9766     if (!sv)
9767         return 0;
9768     SvGETMAGIC(sv);
9769     if (!SvROK(sv))
9770         return 0;
9771     sv = SvRV(sv);
9772     if (!SvOBJECT(sv))
9773         return 0;
9774     return 1;
9775 }
9776
9777 /*
9778 =for apidoc sv_isa
9779
9780 Returns a boolean indicating whether the SV is blessed into the specified
9781 class.  This does not check for subtypes; use C<sv_derived_from> to verify
9782 an inheritance relationship.
9783
9784 =cut
9785 */
9786
9787 int
9788 Perl_sv_isa(pTHX_ SV *sv, const char *const name)
9789 {
9790     const char *hvname;
9791
9792     PERL_ARGS_ASSERT_SV_ISA;
9793
9794     if (!sv)
9795         return 0;
9796     SvGETMAGIC(sv);
9797     if (!SvROK(sv))
9798         return 0;
9799     sv = SvRV(sv);
9800     if (!SvOBJECT(sv))
9801         return 0;
9802     hvname = HvNAME_get(SvSTASH(sv));
9803     if (!hvname)
9804         return 0;
9805
9806     return strEQ(hvname, name);
9807 }
9808
9809 /*
9810 =for apidoc newSVrv
9811
9812 Creates a new SV for the existing RV, C<rv>, to point to.  If C<rv> is not an
9813 RV then it will be upgraded to one.  If C<classname> is non-null then the new
9814 SV will be blessed in the specified package.  The new SV is returned and its
9815 reference count is 1.  The reference count 1 is owned by C<rv>.
9816
9817 =cut
9818 */
9819
9820 SV*
9821 Perl_newSVrv(pTHX_ SV *const rv, const char *const classname)
9822 {
9823     SV *sv;
9824
9825     PERL_ARGS_ASSERT_NEWSVRV;
9826
9827     new_SV(sv);
9828
9829     SV_CHECK_THINKFIRST_COW_DROP(rv);
9830
9831     if (SvTYPE(rv) >= SVt_PVMG) {
9832         const U32 refcnt = SvREFCNT(rv);
9833         SvREFCNT(rv) = 0;
9834         sv_clear(rv);
9835         SvFLAGS(rv) = 0;
9836         SvREFCNT(rv) = refcnt;
9837
9838         sv_upgrade(rv, SVt_IV);
9839     } else if (SvROK(rv)) {
9840         SvREFCNT_dec(SvRV(rv));
9841     } else {
9842         prepare_SV_for_RV(rv);
9843     }
9844
9845     SvOK_off(rv);
9846     SvRV_set(rv, sv);
9847     SvROK_on(rv);
9848
9849     if (classname) {
9850         HV* const stash = gv_stashpv(classname, GV_ADD);
9851         (void)sv_bless(rv, stash);
9852     }
9853     return sv;
9854 }
9855
9856 SV *
9857 Perl_newSVavdefelem(pTHX_ AV *av, SSize_t ix, bool extendible)
9858 {
9859     SV * const lv = newSV_type(SVt_PVLV);
9860     PERL_ARGS_ASSERT_NEWSVAVDEFELEM;
9861     LvTYPE(lv) = 'y';
9862     sv_magic(lv, NULL, PERL_MAGIC_defelem, NULL, 0);
9863     LvTARG(lv) = SvREFCNT_inc_simple_NN(av);
9864     LvSTARGOFF(lv) = ix;
9865     LvTARGLEN(lv) = extendible ? 1 : (STRLEN)UV_MAX;
9866     return lv;
9867 }
9868
9869 /*
9870 =for apidoc sv_setref_pv
9871
9872 Copies a pointer into a new SV, optionally blessing the SV.  The C<rv>
9873 argument will be upgraded to an RV.  That RV will be modified to point to
9874 the new SV.  If the C<pv> argument is NULL then C<PL_sv_undef> will be placed
9875 into the SV.  The C<classname> argument indicates the package for the
9876 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
9877 will have a reference count of 1, and the RV will be returned.
9878
9879 Do not use with other Perl types such as HV, AV, SV, CV, because those
9880 objects will become corrupted by the pointer copy process.
9881
9882 Note that C<sv_setref_pvn> copies the string while this copies the pointer.
9883
9884 =cut
9885 */
9886
9887 SV*
9888 Perl_sv_setref_pv(pTHX_ SV *const rv, const char *const classname, void *const pv)
9889 {
9890     PERL_ARGS_ASSERT_SV_SETREF_PV;
9891
9892     if (!pv) {
9893         sv_setsv(rv, &PL_sv_undef);
9894         SvSETMAGIC(rv);
9895     }
9896     else
9897         sv_setiv(newSVrv(rv,classname), PTR2IV(pv));
9898     return rv;
9899 }
9900
9901 /*
9902 =for apidoc sv_setref_iv
9903
9904 Copies an integer 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.  The C<classname> argument indicates the package for the
9907 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
9908 will have a reference count of 1, and the RV will be returned.
9909
9910 =cut
9911 */
9912
9913 SV*
9914 Perl_sv_setref_iv(pTHX_ SV *const rv, const char *const classname, const IV iv)
9915 {
9916     PERL_ARGS_ASSERT_SV_SETREF_IV;
9917
9918     sv_setiv(newSVrv(rv,classname), iv);
9919     return rv;
9920 }
9921
9922 /*
9923 =for apidoc sv_setref_uv
9924
9925 Copies an unsigned integer into a new SV, optionally blessing the SV.  The C<rv>
9926 argument will be upgraded to an RV.  That RV will be modified to point to
9927 the new SV.  The C<classname> argument indicates the package for the
9928 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
9929 will have a reference count of 1, and the RV will be returned.
9930
9931 =cut
9932 */
9933
9934 SV*
9935 Perl_sv_setref_uv(pTHX_ SV *const rv, const char *const classname, const UV uv)
9936 {
9937     PERL_ARGS_ASSERT_SV_SETREF_UV;
9938
9939     sv_setuv(newSVrv(rv,classname), uv);
9940     return rv;
9941 }
9942
9943 /*
9944 =for apidoc sv_setref_nv
9945
9946 Copies a double into a new SV, optionally blessing the SV.  The C<rv>
9947 argument will be upgraded to an RV.  That RV will be modified to point to
9948 the new SV.  The C<classname> argument indicates the package for the
9949 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
9950 will have a reference count of 1, and the RV will be returned.
9951
9952 =cut
9953 */
9954
9955 SV*
9956 Perl_sv_setref_nv(pTHX_ SV *const rv, const char *const classname, const NV nv)
9957 {
9958     PERL_ARGS_ASSERT_SV_SETREF_NV;
9959
9960     sv_setnv(newSVrv(rv,classname), nv);
9961     return rv;
9962 }
9963
9964 /*
9965 =for apidoc sv_setref_pvn
9966
9967 Copies a string into a new SV, optionally blessing the SV.  The length of the
9968 string must be specified with C<n>.  The C<rv> argument will be upgraded to
9969 an RV.  That RV will be modified to point to the new SV.  The C<classname>
9970 argument indicates the package for the blessing.  Set C<classname> to
9971 C<NULL> to avoid the blessing.  The new SV will have a reference count
9972 of 1, and the RV will be returned.
9973
9974 Note that C<sv_setref_pv> copies the pointer while this copies the string.
9975
9976 =cut
9977 */
9978
9979 SV*
9980 Perl_sv_setref_pvn(pTHX_ SV *const rv, const char *const classname,
9981                    const char *const pv, const STRLEN n)
9982 {
9983     PERL_ARGS_ASSERT_SV_SETREF_PVN;
9984
9985     sv_setpvn(newSVrv(rv,classname), pv, n);
9986     return rv;
9987 }
9988
9989 /*
9990 =for apidoc sv_bless
9991
9992 Blesses an SV into a specified package.  The SV must be an RV.  The package
9993 must be designated by its stash (see C<gv_stashpv()>).  The reference count
9994 of the SV is unaffected.
9995
9996 =cut
9997 */
9998
9999 SV*
10000 Perl_sv_bless(pTHX_ SV *const sv, HV *const stash)
10001 {
10002     SV *tmpRef;
10003     HV *oldstash = NULL;
10004
10005     PERL_ARGS_ASSERT_SV_BLESS;
10006
10007     SvGETMAGIC(sv);
10008     if (!SvROK(sv))
10009         Perl_croak(aTHX_ "Can't bless non-reference value");
10010     tmpRef = SvRV(sv);
10011     if (SvFLAGS(tmpRef) & (SVs_OBJECT|SVf_READONLY)) {
10012         if (SvREADONLY(tmpRef))
10013             Perl_croak_no_modify();
10014         if (SvOBJECT(tmpRef)) {
10015             oldstash = SvSTASH(tmpRef);
10016         }
10017     }
10018     SvOBJECT_on(tmpRef);
10019     SvUPGRADE(tmpRef, SVt_PVMG);
10020     SvSTASH_set(tmpRef, MUTABLE_HV(SvREFCNT_inc_simple(stash)));
10021     SvREFCNT_dec(oldstash);
10022
10023     if(SvSMAGICAL(tmpRef))
10024         if(mg_find(tmpRef, PERL_MAGIC_ext) || mg_find(tmpRef, PERL_MAGIC_uvar))
10025             mg_set(tmpRef);
10026
10027
10028
10029     return sv;
10030 }
10031
10032 /* Downgrades a PVGV to a PVMG. If it's actually a PVLV, we leave the type
10033  * as it is after unglobbing it.
10034  */
10035
10036 PERL_STATIC_INLINE void
10037 S_sv_unglob(pTHX_ SV *const sv, U32 flags)
10038 {
10039     void *xpvmg;
10040     HV *stash;
10041     SV * const temp = flags & SV_COW_DROP_PV ? NULL : sv_newmortal();
10042
10043     PERL_ARGS_ASSERT_SV_UNGLOB;
10044
10045     assert(SvTYPE(sv) == SVt_PVGV || SvTYPE(sv) == SVt_PVLV);
10046     SvFAKE_off(sv);
10047     if (!(flags & SV_COW_DROP_PV))
10048         gv_efullname3(temp, MUTABLE_GV(sv), "*");
10049
10050     SvREFCNT_inc_simple_void_NN(sv_2mortal(sv));
10051     if (GvGP(sv)) {
10052         if(GvCVu((const GV *)sv) && (stash = GvSTASH(MUTABLE_GV(sv)))
10053            && HvNAME_get(stash))
10054             mro_method_changed_in(stash);
10055         gp_free(MUTABLE_GV(sv));
10056     }
10057     if (GvSTASH(sv)) {
10058         sv_del_backref(MUTABLE_SV(GvSTASH(sv)), sv);
10059         GvSTASH(sv) = NULL;
10060     }
10061     GvMULTI_off(sv);
10062     if (GvNAME_HEK(sv)) {
10063         unshare_hek(GvNAME_HEK(sv));
10064     }
10065     isGV_with_GP_off(sv);
10066
10067     if(SvTYPE(sv) == SVt_PVGV) {
10068         /* need to keep SvANY(sv) in the right arena */
10069         xpvmg = new_XPVMG();
10070         StructCopy(SvANY(sv), xpvmg, XPVMG);
10071         del_XPVGV(SvANY(sv));
10072         SvANY(sv) = xpvmg;
10073
10074         SvFLAGS(sv) &= ~SVTYPEMASK;
10075         SvFLAGS(sv) |= SVt_PVMG;
10076     }
10077
10078     /* Intentionally not calling any local SET magic, as this isn't so much a
10079        set operation as merely an internal storage change.  */
10080     if (flags & SV_COW_DROP_PV) SvOK_off(sv);
10081     else sv_setsv_flags(sv, temp, 0);
10082
10083     if ((const GV *)sv == PL_last_in_gv)
10084         PL_last_in_gv = NULL;
10085     else if ((const GV *)sv == PL_statgv)
10086         PL_statgv = NULL;
10087 }
10088
10089 /*
10090 =for apidoc sv_unref_flags
10091
10092 Unsets the RV status of the SV, and decrements the reference count of
10093 whatever was being referenced by the RV.  This can almost be thought of
10094 as a reversal of C<newSVrv>.  The C<cflags> argument can contain
10095 C<SV_IMMEDIATE_UNREF> to force the reference count to be decremented
10096 (otherwise the decrementing is conditional on the reference count being
10097 different from one or the reference being a readonly SV).
10098 See C<SvROK_off>.
10099
10100 =cut
10101 */
10102
10103 void
10104 Perl_sv_unref_flags(pTHX_ SV *const ref, const U32 flags)
10105 {
10106     SV* const target = SvRV(ref);
10107
10108     PERL_ARGS_ASSERT_SV_UNREF_FLAGS;
10109
10110     if (SvWEAKREF(ref)) {
10111         sv_del_backref(target, ref);
10112         SvWEAKREF_off(ref);
10113         SvRV_set(ref, NULL);
10114         return;
10115     }
10116     SvRV_set(ref, NULL);
10117     SvROK_off(ref);
10118     /* You can't have a || SvREADONLY(target) here, as $a = $$a, where $a was
10119        assigned to as BEGIN {$a = \"Foo"} will fail.  */
10120     if (SvREFCNT(target) != 1 || (flags & SV_IMMEDIATE_UNREF))
10121         SvREFCNT_dec_NN(target);
10122     else /* XXX Hack, but hard to make $a=$a->[1] work otherwise */
10123         sv_2mortal(target);     /* Schedule for freeing later */
10124 }
10125
10126 /*
10127 =for apidoc sv_untaint
10128
10129 Untaint an SV.  Use C<SvTAINTED_off> instead.
10130
10131 =cut
10132 */
10133
10134 void
10135 Perl_sv_untaint(pTHX_ SV *const sv)
10136 {
10137     PERL_ARGS_ASSERT_SV_UNTAINT;
10138     PERL_UNUSED_CONTEXT;
10139
10140     if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
10141         MAGIC * const mg = mg_find(sv, PERL_MAGIC_taint);
10142         if (mg)
10143             mg->mg_len &= ~1;
10144     }
10145 }
10146
10147 /*
10148 =for apidoc sv_tainted
10149
10150 Test an SV for taintedness.  Use C<SvTAINTED> instead.
10151
10152 =cut
10153 */
10154
10155 bool
10156 Perl_sv_tainted(pTHX_ SV *const sv)
10157 {
10158     PERL_ARGS_ASSERT_SV_TAINTED;
10159     PERL_UNUSED_CONTEXT;
10160
10161     if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
10162         const MAGIC * const mg = mg_find(sv, PERL_MAGIC_taint);
10163         if (mg && (mg->mg_len & 1) )
10164             return TRUE;
10165     }
10166     return FALSE;
10167 }
10168
10169 /*
10170 =for apidoc sv_setpviv
10171
10172 Copies an integer into the given SV, also updating its string value.
10173 Does not handle 'set' magic.  See C<sv_setpviv_mg>.
10174
10175 =cut
10176 */
10177
10178 void
10179 Perl_sv_setpviv(pTHX_ SV *const sv, const IV iv)
10180 {
10181     char buf[TYPE_CHARS(UV)];
10182     char *ebuf;
10183     char * const ptr = uiv_2buf(buf, iv, 0, 0, &ebuf);
10184
10185     PERL_ARGS_ASSERT_SV_SETPVIV;
10186
10187     sv_setpvn(sv, ptr, ebuf - ptr);
10188 }
10189
10190 /*
10191 =for apidoc sv_setpviv_mg
10192
10193 Like C<sv_setpviv>, but also handles 'set' magic.
10194
10195 =cut
10196 */
10197
10198 void
10199 Perl_sv_setpviv_mg(pTHX_ SV *const sv, const IV iv)
10200 {
10201     PERL_ARGS_ASSERT_SV_SETPVIV_MG;
10202
10203     sv_setpviv(sv, iv);
10204     SvSETMAGIC(sv);
10205 }
10206
10207 #if defined(PERL_IMPLICIT_CONTEXT)
10208
10209 /* pTHX_ magic can't cope with varargs, so this is a no-context
10210  * version of the main function, (which may itself be aliased to us).
10211  * Don't access this version directly.
10212  */
10213
10214 void
10215 Perl_sv_setpvf_nocontext(SV *const sv, const char *const pat, ...)
10216 {
10217     dTHX;
10218     va_list args;
10219
10220     PERL_ARGS_ASSERT_SV_SETPVF_NOCONTEXT;
10221
10222     va_start(args, pat);
10223     sv_vsetpvf(sv, pat, &args);
10224     va_end(args);
10225 }
10226
10227 /* pTHX_ magic can't cope with varargs, so this is a no-context
10228  * version of the main function, (which may itself be aliased to us).
10229  * Don't access this version directly.
10230  */
10231
10232 void
10233 Perl_sv_setpvf_mg_nocontext(SV *const sv, const char *const pat, ...)
10234 {
10235     dTHX;
10236     va_list args;
10237
10238     PERL_ARGS_ASSERT_SV_SETPVF_MG_NOCONTEXT;
10239
10240     va_start(args, pat);
10241     sv_vsetpvf_mg(sv, pat, &args);
10242     va_end(args);
10243 }
10244 #endif
10245
10246 /*
10247 =for apidoc sv_setpvf
10248
10249 Works like C<sv_catpvf> but copies the text into the SV instead of
10250 appending it.  Does not handle 'set' magic.  See C<sv_setpvf_mg>.
10251
10252 =cut
10253 */
10254
10255 void
10256 Perl_sv_setpvf(pTHX_ SV *const sv, const char *const pat, ...)
10257 {
10258     va_list args;
10259
10260     PERL_ARGS_ASSERT_SV_SETPVF;
10261
10262     va_start(args, pat);
10263     sv_vsetpvf(sv, pat, &args);
10264     va_end(args);
10265 }
10266
10267 /*
10268 =for apidoc sv_vsetpvf
10269
10270 Works like C<sv_vcatpvf> but copies the text into the SV instead of
10271 appending it.  Does not handle 'set' magic.  See C<sv_vsetpvf_mg>.
10272
10273 Usually used via its frontend C<sv_setpvf>.
10274
10275 =cut
10276 */
10277
10278 void
10279 Perl_sv_vsetpvf(pTHX_ SV *const sv, const char *const pat, va_list *const args)
10280 {
10281     PERL_ARGS_ASSERT_SV_VSETPVF;
10282
10283     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
10284 }
10285
10286 /*
10287 =for apidoc sv_setpvf_mg
10288
10289 Like C<sv_setpvf>, but also handles 'set' magic.
10290
10291 =cut
10292 */
10293
10294 void
10295 Perl_sv_setpvf_mg(pTHX_ SV *const sv, const char *const pat, ...)
10296 {
10297     va_list args;
10298
10299     PERL_ARGS_ASSERT_SV_SETPVF_MG;
10300
10301     va_start(args, pat);
10302     sv_vsetpvf_mg(sv, pat, &args);
10303     va_end(args);
10304 }
10305
10306 /*
10307 =for apidoc sv_vsetpvf_mg
10308
10309 Like C<sv_vsetpvf>, but also handles 'set' magic.
10310
10311 Usually used via its frontend C<sv_setpvf_mg>.
10312
10313 =cut
10314 */
10315
10316 void
10317 Perl_sv_vsetpvf_mg(pTHX_ SV *const sv, const char *const pat, va_list *const args)
10318 {
10319     PERL_ARGS_ASSERT_SV_VSETPVF_MG;
10320
10321     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
10322     SvSETMAGIC(sv);
10323 }
10324
10325 #if defined(PERL_IMPLICIT_CONTEXT)
10326
10327 /* pTHX_ magic can't cope with varargs, so this is a no-context
10328  * version of the main function, (which may itself be aliased to us).
10329  * Don't access this version directly.
10330  */
10331
10332 void
10333 Perl_sv_catpvf_nocontext(SV *const sv, const char *const pat, ...)
10334 {
10335     dTHX;
10336     va_list args;
10337
10338     PERL_ARGS_ASSERT_SV_CATPVF_NOCONTEXT;
10339
10340     va_start(args, pat);
10341     sv_vcatpvfn_flags(sv, pat, strlen(pat), &args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
10342     va_end(args);
10343 }
10344
10345 /* pTHX_ magic can't cope with varargs, so this is a no-context
10346  * version of the main function, (which may itself be aliased to us).
10347  * Don't access this version directly.
10348  */
10349
10350 void
10351 Perl_sv_catpvf_mg_nocontext(SV *const sv, const char *const pat, ...)
10352 {
10353     dTHX;
10354     va_list args;
10355
10356     PERL_ARGS_ASSERT_SV_CATPVF_MG_NOCONTEXT;
10357
10358     va_start(args, pat);
10359     sv_vcatpvfn_flags(sv, pat, strlen(pat), &args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
10360     SvSETMAGIC(sv);
10361     va_end(args);
10362 }
10363 #endif
10364
10365 /*
10366 =for apidoc sv_catpvf
10367
10368 Processes its arguments like C<sprintf> and appends the formatted
10369 output to an SV.  If the appended data contains "wide" characters
10370 (including, but not limited to, SVs with a UTF-8 PV formatted with %s,
10371 and characters >255 formatted with %c), the original SV might get
10372 upgraded to UTF-8.  Handles 'get' magic, but not 'set' magic.  See
10373 C<sv_catpvf_mg>.  If the original SV was UTF-8, the pattern should be
10374 valid UTF-8; if the original SV was bytes, the pattern should be too.
10375
10376 =cut */
10377
10378 void
10379 Perl_sv_catpvf(pTHX_ SV *const sv, const char *const pat, ...)
10380 {
10381     va_list args;
10382
10383     PERL_ARGS_ASSERT_SV_CATPVF;
10384
10385     va_start(args, pat);
10386     sv_vcatpvfn_flags(sv, pat, strlen(pat), &args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
10387     va_end(args);
10388 }
10389
10390 /*
10391 =for apidoc sv_vcatpvf
10392
10393 Processes its arguments like C<vsprintf> and appends the formatted output
10394 to an SV.  Does not handle 'set' magic.  See C<sv_vcatpvf_mg>.
10395
10396 Usually used via its frontend C<sv_catpvf>.
10397
10398 =cut
10399 */
10400
10401 void
10402 Perl_sv_vcatpvf(pTHX_ SV *const sv, const char *const pat, va_list *const args)
10403 {
10404     PERL_ARGS_ASSERT_SV_VCATPVF;
10405
10406     sv_vcatpvfn_flags(sv, pat, strlen(pat), args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
10407 }
10408
10409 /*
10410 =for apidoc sv_catpvf_mg
10411
10412 Like C<sv_catpvf>, but also handles 'set' magic.
10413
10414 =cut
10415 */
10416
10417 void
10418 Perl_sv_catpvf_mg(pTHX_ SV *const sv, const char *const pat, ...)
10419 {
10420     va_list args;
10421
10422     PERL_ARGS_ASSERT_SV_CATPVF_MG;
10423
10424     va_start(args, pat);
10425     sv_vcatpvfn_flags(sv, pat, strlen(pat), &args, NULL, 0, NULL, SV_GMAGIC|SV_SMAGIC);
10426     SvSETMAGIC(sv);
10427     va_end(args);
10428 }
10429
10430 /*
10431 =for apidoc sv_vcatpvf_mg
10432
10433 Like C<sv_vcatpvf>, but also handles 'set' magic.
10434
10435 Usually used via its frontend C<sv_catpvf_mg>.
10436
10437 =cut
10438 */
10439
10440 void
10441 Perl_sv_vcatpvf_mg(pTHX_ SV *const sv, const char *const pat, va_list *const args)
10442 {
10443     PERL_ARGS_ASSERT_SV_VCATPVF_MG;
10444
10445     sv_vcatpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
10446     SvSETMAGIC(sv);
10447 }
10448
10449 /*
10450 =for apidoc sv_vsetpvfn
10451
10452 Works like C<sv_vcatpvfn> but copies the text into the SV instead of
10453 appending it.
10454
10455 Usually used via one of its frontends C<sv_vsetpvf> and C<sv_vsetpvf_mg>.
10456
10457 =cut
10458 */
10459
10460 void
10461 Perl_sv_vsetpvfn(pTHX_ SV *const sv, const char *const pat, const STRLEN patlen,
10462                  va_list *const args, SV **const svargs, const I32 svmax, bool *const maybe_tainted)
10463 {
10464     PERL_ARGS_ASSERT_SV_VSETPVFN;
10465
10466     sv_setpvs(sv, "");
10467     sv_vcatpvfn_flags(sv, pat, patlen, args, svargs, svmax, maybe_tainted, 0);
10468 }
10469
10470
10471 /*
10472  * Warn of missing argument to sprintf, and then return a defined value
10473  * to avoid inappropriate "use of uninit" warnings [perl #71000].
10474  */
10475 STATIC SV*
10476 S_vcatpvfn_missing_argument(pTHX) {
10477     if (ckWARN(WARN_MISSING)) {
10478         Perl_warner(aTHX_ packWARN(WARN_MISSING), "Missing argument in %s",
10479                 PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn()");
10480     }
10481     return &PL_sv_no;
10482 }
10483
10484
10485 STATIC I32
10486 S_expect_number(pTHX_ char **const pattern)
10487 {
10488     I32 var = 0;
10489
10490     PERL_ARGS_ASSERT_EXPECT_NUMBER;
10491
10492     switch (**pattern) {
10493     case '1': case '2': case '3':
10494     case '4': case '5': case '6':
10495     case '7': case '8': case '9':
10496         var = *(*pattern)++ - '0';
10497         while (isDIGIT(**pattern)) {
10498             const I32 tmp = var * 10 + (*(*pattern)++ - '0');
10499             if (tmp < var)
10500                 Perl_croak(aTHX_ "Integer overflow in format string for %s", (PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn"));
10501             var = tmp;
10502         }
10503     }
10504     return var;
10505 }
10506
10507 STATIC char *
10508 S_F0convert(NV nv, char *const endbuf, STRLEN *const len)
10509 {
10510     const int neg = nv < 0;
10511     UV uv;
10512
10513     PERL_ARGS_ASSERT_F0CONVERT;
10514
10515     if (neg)
10516         nv = -nv;
10517     if (nv < UV_MAX) {
10518         char *p = endbuf;
10519         nv += 0.5;
10520         uv = (UV)nv;
10521         if (uv & 1 && uv == nv)
10522             uv--;                       /* Round to even */
10523         do {
10524             const unsigned dig = uv % 10;
10525             *--p = '0' + dig;
10526         } while (uv /= 10);
10527         if (neg)
10528             *--p = '-';
10529         *len = endbuf - p;
10530         return p;
10531     }
10532     return NULL;
10533 }
10534
10535
10536 /*
10537 =for apidoc sv_vcatpvfn
10538
10539 =for apidoc sv_vcatpvfn_flags
10540
10541 Processes its arguments like C<vsprintf> and appends the formatted output
10542 to an SV.  Uses an array of SVs if the C style variable argument list is
10543 missing (NULL).  When running with taint checks enabled, indicates via
10544 C<maybe_tainted> if results are untrustworthy (often due to the use of
10545 locales).
10546
10547 If called as C<sv_vcatpvfn> or flags include C<SV_GMAGIC>, calls get magic.
10548
10549 Usually used via one of its frontends C<sv_vcatpvf> and C<sv_vcatpvf_mg>.
10550
10551 =cut
10552 */
10553
10554 #define VECTORIZE_ARGS  vecsv = va_arg(*args, SV*);\
10555                         vecstr = (U8*)SvPV_const(vecsv,veclen);\
10556                         vec_utf8 = DO_UTF8(vecsv);
10557
10558 /* XXX maybe_tainted is never assigned to, so the doc above is lying. */
10559
10560 void
10561 Perl_sv_vcatpvfn(pTHX_ SV *const sv, const char *const pat, const STRLEN patlen,
10562                  va_list *const args, SV **const svargs, const I32 svmax, bool *const maybe_tainted)
10563 {
10564     PERL_ARGS_ASSERT_SV_VCATPVFN;
10565
10566     sv_vcatpvfn_flags(sv, pat, patlen, args, svargs, svmax, maybe_tainted, SV_GMAGIC|SV_SMAGIC);
10567 }
10568
10569 /* vhex will contain the values (0..15) of the hex digits ("nybbles"
10570  * of 4 bits); 1 for the implicit 1, and at most 128 bits of mantissa,
10571  * four bits per xdigit. */
10572 #define VHEX_SIZE (1+128/4)
10573
10574 /* If we do not have a known long double format, (including not using
10575  * long doubles, or long doubles being equal to doubles) then we will
10576  * fall back to the ldexp/frexp route, with which we can retrieve at
10577  * most as many bits as our widest unsigned integer type is.  We try
10578  * to get a 64-bit unsigned integer even if we are not having 64-bit
10579  * UV. */
10580 #if defined(HAS_QUAD) && defined(Uquad_t)
10581 #  define MANTISSATYPE Uquad_t
10582 #  define MANTISSASIZE 8
10583 #else
10584 #  define MANTISSATYPE UV /* May lose precision if UVSIZE is not 8. */
10585 #  define MANTISSASIZE UVSIZE
10586 #endif
10587
10588 /* S_hextract() is a helper for Perl_sv_vcatpvfn_flags, for extracting
10589  * the hexadecimal values (for %a/%A).  The nv is the NV where the value
10590  * are being extracted from (either directly from the long double in-memory
10591  * presentation, or from the uquad computed via frexp+ldexp).  frexp also
10592  * is used to update the exponent.  vhex is the pointer to the beginning
10593  * of the output buffer (of VHEX_SIZE).
10594  *
10595  * The tricky part is that S_hextract() needs to be called twice:
10596  * the first time with vend as NULL, and the second time with vend as
10597  * the pointer returned by the first call.  What happens is that on
10598  * the first round the output size is computed, and the intended
10599  * extraction sanity checked.  On the second round the actual output
10600  * (the extraction of the hexadecimal values) takes place.
10601  * Sanity failures cause fatal failures during both rounds. */
10602 STATIC U8*
10603 S_hextract(pTHX_ const NV nv, int* exponent, U8* vhex, U8* vend)
10604 {
10605     U8* v = vhex;
10606     int ix;
10607     int ixmin = 0, ixmax = 0;
10608
10609     /* XXX Inf/NaN/denormal handling in the HEXTRACT_IMPLICIT_BIT,
10610      * and elsewhere. */
10611
10612     /* These macros are just to reduce typos, they have multiple
10613      * repetitions below, but usually only one (or sometimes two)
10614      * of them is really being used. */
10615     /* HEXTRACT_OUTPUT() extracts the high nybble first. */
10616 #define HEXTRACT_OUTPUT_HI(ix) (*v++ = nvp[ix] >> 4)
10617 #define HEXTRACT_OUTPUT_LO(ix) (*v++ = nvp[ix] & 0xF)
10618 #define HEXTRACT_OUTPUT(ix) \
10619     STMT_START { \
10620         HEXTRACT_OUTPUT_HI(ix); \
10621         HEXTRACT_OUTPUT_LO(ix); \
10622     } STMT_END
10623 #define HEXTRACT_COUNT(ix, c) \
10624     STMT_START { \
10625       v += c; \
10626       if (ix < ixmin) \
10627         ixmin = ix; \
10628       else if (ix > ixmax) \
10629         ixmax = ix; \
10630     } STMT_END
10631 #define HEXTRACT_IMPLICIT_BIT() \
10632     if (exponent) { \
10633         if (vend) \
10634             *v++ = 1; \
10635         else \
10636             v++; \
10637     }
10638
10639     /* First see if we are using long doubles. */
10640 #if NVSIZE > DOUBLESIZE && LONG_DOUBLEKIND != LONG_DOUBLE_IS_DOUBLE
10641     const U8* nvp = (const U8*)(&nv);
10642 #  define HEXTRACTSIZE NVSIZE
10643     (void)Perl_frexp(PERL_ABS(nv), exponent);
10644 #  if LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
10645     /* Used in e.g. VMS and HP-UX IA-64, e.g. -0.1L:
10646      * 9a 99 99 99 99 99 99 99 99 99 99 99 99 99 fb 3f */
10647     /* The bytes 13..0 are the mantissa/fraction,
10648      * the 15,14 are the sign+exponent. */
10649     HEXTRACT_IMPLICIT_BIT();
10650     for (ix = 13; ix >= 0; ix--) {
10651         if (vend)
10652             HEXTRACT_OUTPUT(ix);
10653         else
10654             HEXTRACT_COUNT(ix, 2);
10655     }
10656 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
10657     /* Used in e.g. Solaris Sparc and HP-UX PA-RISC, e.g. -0.1L:
10658      * bf fb 99 99 99 99 99 99 99 99 99 99 99 99 99 9a */
10659     /* The bytes 2..15 are the mantissa/fraction,
10660      * the 0,1 are the sign+exponent. */
10661     HEXTRACT_IMPLICIT_BIT();
10662     for (ix = 2; ix <= 15; ix++) {
10663         if (vend)
10664             HEXTRACT_OUTPUT(ix);
10665         else
10666             HEXTRACT_COUNT(ix, 2);
10667     }
10668 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN
10669     /* x86 80-bit "extended precision", 64 bits of mantissa / fraction /
10670      * significand, 15 bits of exponent, 1 bit of sign.  NVSIZE can
10671      * be either 12 (ILP32, Solaris x86) or 16 (LP64, Linux and OS X),
10672      * meaning that 2 or 6 bytes are empty padding. */
10673     /* The bytes 7..0 are the mantissa/fraction */
10674     /* There explicitly is *no* implicit bit in this case. */
10675     for (ix = 7; ix >= 0; ix--) {
10676         if (vend)
10677             HEXTRACT_OUTPUT(ix);
10678         else
10679             HEXTRACT_COUNT(ix, 2);
10680     }
10681 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN
10682     /* (does this format ever happen?) */
10683     /* There explicitly is *no* implicit bit in this case. */
10684     for (ix = 0; ix < 8; ix++) {
10685         if (vend)
10686             HEXTRACT_OUTPUT(ix);
10687         else
10688             HEXTRACT_COUNT(ix, 2);
10689     }
10690 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LITTLE_ENDIAN
10691     /* Where is this used?
10692      * 9a 99 99 99 99 99 59 bc 9a 99 99 99 99 99 b9 3f */
10693     HEXTRACT_IMPLICIT_BIT();
10694     if (vend)
10695         HEXTRACT_OUTPUT_LO(14);
10696     else
10697         HEXTRACT_COUNT(14, 1);
10698     for (ix = 13; ix >= 8; ix--) {
10699         if (vend)
10700             HEXTRACT_OUTPUT(ix);
10701         else
10702             HEXTRACT_COUNT(ix, 2);
10703     }
10704     /* XXX not extracting from the second double -- see the discussion
10705      * below for the big endian double double. */
10706 #    if 0
10707     if (vend)
10708         HEXTRACT_OUTPUT_LO(6);
10709     else
10710         HEXTRACT_COUNT(6, 1);
10711     for (ix = 5; ix >= 0; ix--) {
10712         if (vend)
10713             HEXTRACT_OUTPUT(ix);
10714         else
10715             HEXTRACT_COUNT(ix, 2);
10716     }
10717 #    endif
10718 #  elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BIG_ENDIAN
10719     /* Used in e.g. PPC/Power (AIX) and MIPS.
10720      *
10721      * The mantissa bits are in two separate stretches, e.g. for -0.1L:
10722      * 3f b9 99 99 99 99 99 9a bc 59 99 99 99 99 99 9a
10723      */
10724     HEXTRACT_IMPLICIT_BIT();
10725     if (vend)
10726         HEXTRACT_OUTPUT_LO(1);
10727     else
10728         HEXTRACT_COUNT(1, 1);
10729     for (ix = 2; ix < 8; ix++) {
10730         if (vend)
10731             HEXTRACT_OUTPUT(ix);
10732         else
10733             HEXTRACT_COUNT(ix, 2);
10734     }
10735     /* XXX not extracting the second double mantissa bits- this is not
10736      * right nor ideal (we effectively reduce the output format to
10737      * that of a "single double", only 53 bits), but we do not know
10738      * exactly how to do the extraction correctly so that it matches
10739      * the semantics of, say, the IEEE quadruple float. */
10740 #    if 0
10741     if (vend)
10742         HEXTRACT_OUTPUT_LO(9);
10743     else
10744         HEXTRACT_COUNT(9, 1);
10745     for (ix = 10; ix < 16; ix++) {
10746         if (vend)
10747             HEXTRACT_OUTPUT(ix);
10748         else
10749             HEXTRACT_COUNT(ix, 2);
10750     }
10751 #   endif
10752 #  else
10753     Perl_croak(aTHX_
10754                "Hexadecimal float: unsupported long double format");
10755 #  endif
10756 #else
10757     /* If not using long doubles (or if the long double format is
10758      * known but not yet supported), try to retrieve the mantissa bits
10759      * via frexp+ldexp. */
10760
10761     NV norm = Perl_frexp(PERL_ABS(nv), exponent);
10762     /* Theoretically we have all the bytes [0, MANTISSASIZE-1] to
10763      * inspect; but in practice we don't want the leading nybbles that
10764      * are zero.  With the common IEEE 754 value for NV_MANT_DIG being
10765      * 53, we want the limit byte to be (int)((53-1)/8) == 6.
10766      *
10767      * Note that this is _not_ inspecting the in-memory format of the
10768      * nv (as opposed to the long double method), but instead the UV
10769      * retrieved with the frexp+ldexp invocation. */
10770 #  if MANTISSASIZE * 8 > NV_MANT_DIG
10771     MANTISSATYPE mantissa = (MANTISSATYPE)Perl_ldexp(norm, NV_MANT_DIG);
10772     int limit_byte = (NV_MANT_DIG - 1) / 8;
10773 #  else
10774     /* There will be low-order precision loss.  Try to salvage as many
10775      * bits as possible.  Will truncate, not round. */
10776     MANTISSATYPE mantissa =
10777     Perl_ldexp(norm,
10778                /* The highest possible shift by two that fits in the
10779                 * mantissa and is aligned (by four) the same was as
10780                 * NV_MANT_DIG. */
10781                MANTISSASIZE * 8 - (4 - NV_MANT_DIG % 4));
10782     int limit_byte = MANTISSASIZE - 1;
10783 #  endif
10784     const U8* nvp = (const U8*)(&mantissa);
10785 #  define HEXTRACTSIZE MANTISSASIZE
10786     /* We make here the wild assumption that the endianness of doubles
10787      * is similar to the endianness of integers, and that there is no
10788      * middle-endianness.  This may come back to haunt us (the rumor
10789      * has it that ARM can be quite haunted).
10790      *
10791      * We generate 4-bit xdigits (nybble/nibble) instead of 8-bit
10792      * bytes, since we might need to handle printf precision, and also
10793      * insert the radix.
10794      */
10795 #  if BYTEORDER == 0x12345678 || BYTEORDER == 0x1234 || \
10796      LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN || \
10797      LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN || \
10798      LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LITTLE_ENDIAN
10799     /* Little endian. */
10800     for (ix = limit_byte; ix >= 0; ix--) {
10801         if (vend)
10802             HEXTRACT_OUTPUT(ix);
10803         else
10804             HEXTRACT_COUNT(ix, 2);
10805     }
10806 #  else
10807     /* Big endian. */
10808     for (ix = MANTISSASIZE - 1 - limit_byte; ix < MANTISSASIZE; ix++) {
10809         if (vend)
10810             HEXTRACT_OUTPUT(ix);
10811         else
10812             HEXTRACT_COUNT(ix, 2);
10813     }
10814 #  endif
10815     /* If there are not enough bits in MANTISSATYPE, we couldn't get
10816      * all of them, issue a warning.
10817      *
10818      * Note that NV_PRESERVES_UV_BITS would not help here, it is the
10819      * wrong way around. */
10820 #  if NV_MANT_DIG > MANTISSASIZE * 8
10821     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
10822                    "Hexadecimal float: precision loss");
10823 #  endif
10824 #endif
10825     /* Croak for various reasons: if the output pointer escaped the
10826      * output buffer, if the extraction index escaped the extraction
10827      * buffer, or if the ending output pointer didn't match the
10828      * previously computed value. */
10829     if (v <= vhex || v - vhex >= VHEX_SIZE ||
10830         ixmin < 0 || ixmax >= HEXTRACTSIZE ||
10831         (vend && v != vend))
10832         Perl_croak(aTHX_ "Hexadecimal float: internal error");
10833     return v;
10834 }
10835
10836 void
10837 Perl_sv_vcatpvfn_flags(pTHX_ SV *const sv, const char *const pat, const STRLEN patlen,
10838                        va_list *const args, SV **const svargs, const I32 svmax, bool *const maybe_tainted,
10839                        const U32 flags)
10840 {
10841     char *p;
10842     char *q;
10843     const char *patend;
10844     STRLEN origlen;
10845     I32 svix = 0;
10846     static const char nullstr[] = "(null)";
10847     SV *argsv = NULL;
10848     bool has_utf8 = DO_UTF8(sv);    /* has the result utf8? */
10849     const bool pat_utf8 = has_utf8; /* the pattern is in utf8? */
10850     SV *nsv = NULL;
10851     /* Times 4: a decimal digit takes more than 3 binary digits.
10852      * NV_DIG: mantissa takes than many decimal digits.
10853      * Plus 32: Playing safe. */
10854     char ebuf[IV_DIG * 4 + NV_DIG + 32];
10855     /* large enough for "%#.#f" --chip */
10856     /* what about long double NVs? --jhi */
10857     bool no_redundant_warning = FALSE; /* did we use any explicit format parameter index? */
10858     bool hexfp = FALSE;
10859
10860     DECLARATION_FOR_STORE_LC_NUMERIC_SET_TO_NEEDED;
10861
10862     PERL_ARGS_ASSERT_SV_VCATPVFN_FLAGS;
10863     PERL_UNUSED_ARG(maybe_tainted);
10864
10865     if (flags & SV_GMAGIC)
10866         SvGETMAGIC(sv);
10867
10868     /* no matter what, this is a string now */
10869     (void)SvPV_force_nomg(sv, origlen);
10870
10871     /* special-case "", "%s", and "%-p" (SVf - see below) */
10872     if (patlen == 0) {
10873         if (svmax && ckWARN(WARN_REDUNDANT))
10874             Perl_warner(aTHX_ packWARN(WARN_REDUNDANT), "Redundant argument in %s",
10875                         PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn()");
10876         return;
10877     }
10878     if (patlen == 2 && pat[0] == '%' && pat[1] == 's') {
10879         if (svmax > 1 && ckWARN(WARN_REDUNDANT))
10880             Perl_warner(aTHX_ packWARN(WARN_REDUNDANT), "Redundant argument in %s",
10881                         PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn()");
10882
10883         if (args) {
10884             const char * const s = va_arg(*args, char*);
10885             sv_catpv_nomg(sv, s ? s : nullstr);
10886         }
10887         else if (svix < svmax) {
10888             /* we want get magic on the source but not the target. sv_catsv can't do that, though */
10889             SvGETMAGIC(*svargs);
10890             sv_catsv_nomg(sv, *svargs);
10891         }
10892         else
10893             S_vcatpvfn_missing_argument(aTHX);
10894         return;
10895     }
10896     if (args && patlen == 3 && pat[0] == '%' &&
10897                 pat[1] == '-' && pat[2] == 'p') {
10898         if (svmax > 1 && ckWARN(WARN_REDUNDANT))
10899             Perl_warner(aTHX_ packWARN(WARN_REDUNDANT), "Redundant argument in %s",
10900                         PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn()");
10901         argsv = MUTABLE_SV(va_arg(*args, void*));
10902         sv_catsv_nomg(sv, argsv);
10903         return;
10904     }
10905
10906 #ifndef USE_LONG_DOUBLE
10907     /* special-case "%.<number>[gf]" */
10908     if ( !args && patlen <= 5 && pat[0] == '%' && pat[1] == '.'
10909          && (pat[patlen-1] == 'g' || pat[patlen-1] == 'f') ) {
10910         unsigned digits = 0;
10911         const char *pp;
10912
10913         pp = pat + 2;
10914         while (*pp >= '0' && *pp <= '9')
10915             digits = 10 * digits + (*pp++ - '0');
10916
10917         /* XXX: Why do this `svix < svmax` test? Couldn't we just
10918            format the first argument and WARN_REDUNDANT if svmax > 1?
10919            Munged by Nicholas Clark in v5.13.0-209-g95ea86d */
10920         if (pp - pat == (int)patlen - 1 && svix < svmax) {
10921             const NV nv = SvNV(*svargs);
10922             if (*pp == 'g') {
10923                 /* Add check for digits != 0 because it seems that some
10924                    gconverts are buggy in this case, and we don't yet have
10925                    a Configure test for this.  */
10926                 if (digits && digits < sizeof(ebuf) - NV_DIG - 10) {
10927                      /* 0, point, slack */
10928                     STORE_LC_NUMERIC_SET_TO_NEEDED();
10929                     PERL_UNUSED_RESULT(Gconvert(nv, (int)digits, 0, ebuf));
10930                     sv_catpv_nomg(sv, ebuf);
10931                     if (*ebuf)  /* May return an empty string for digits==0 */
10932                         return;
10933                 }
10934             } else if (!digits) {
10935                 STRLEN l;
10936
10937                 if ((p = F0convert(nv, ebuf + sizeof ebuf, &l))) {
10938                     sv_catpvn_nomg(sv, p, l);
10939                     return;
10940                 }
10941             }
10942         }
10943     }
10944 #endif /* !USE_LONG_DOUBLE */
10945
10946     if (!args && svix < svmax && DO_UTF8(*svargs))
10947         has_utf8 = TRUE;
10948
10949     patend = (char*)pat + patlen;
10950     for (p = (char*)pat; p < patend; p = q) {
10951         bool alt = FALSE;
10952         bool left = FALSE;
10953         bool vectorize = FALSE;
10954         bool vectorarg = FALSE;
10955         bool vec_utf8 = FALSE;
10956         char fill = ' ';
10957         char plus = 0;
10958         char intsize = 0;
10959         STRLEN width = 0;
10960         STRLEN zeros = 0;
10961         bool has_precis = FALSE;
10962         STRLEN precis = 0;
10963         const I32 osvix = svix;
10964         bool is_utf8 = FALSE;  /* is this item utf8?   */
10965 #ifdef HAS_LDBL_SPRINTF_BUG
10966         /* This is to try to fix a bug with irix/nonstop-ux/powerux and
10967            with sfio - Allen <allens@cpan.org> */
10968         bool fix_ldbl_sprintf_bug = FALSE;
10969 #endif
10970
10971         char esignbuf[4];
10972         U8 utf8buf[UTF8_MAXBYTES+1];
10973         STRLEN esignlen = 0;
10974
10975         const char *eptr = NULL;
10976         const char *fmtstart;
10977         STRLEN elen = 0;
10978         SV *vecsv = NULL;
10979         const U8 *vecstr = NULL;
10980         STRLEN veclen = 0;
10981         char c = 0;
10982         int i;
10983         unsigned base = 0;
10984         IV iv = 0;
10985         UV uv = 0;
10986         /* we need a long double target in case HAS_LONG_DOUBLE but
10987            not USE_LONG_DOUBLE
10988         */
10989 #if defined(HAS_LONG_DOUBLE) && LONG_DOUBLESIZE > DOUBLESIZE
10990         long double nv;
10991 #  define myNVgf PERL_PRIgldbl
10992 #else
10993         NV nv;
10994 #  define myNVgf NVgf
10995 #endif
10996         STRLEN have;
10997         STRLEN need;
10998         STRLEN gap;
10999         const char *dotstr = ".";
11000         STRLEN dotstrlen = 1;
11001         I32 efix = 0; /* explicit format parameter index */
11002         I32 ewix = 0; /* explicit width index */
11003         I32 epix = 0; /* explicit precision index */
11004         I32 evix = 0; /* explicit vector index */
11005         bool asterisk = FALSE;
11006         bool infnan = FALSE;
11007
11008         /* echo everything up to the next format specification */
11009         for (q = p; q < patend && *q != '%'; ++q) ;
11010         if (q > p) {
11011             if (has_utf8 && !pat_utf8)
11012                 sv_catpvn_nomg_utf8_upgrade(sv, p, q - p, nsv);
11013             else
11014                 sv_catpvn_nomg(sv, p, q - p);
11015             p = q;
11016         }
11017         if (q++ >= patend)
11018             break;
11019
11020         fmtstart = q;
11021
11022 /*
11023     We allow format specification elements in this order:
11024         \d+\$              explicit format parameter index
11025         [-+ 0#]+           flags
11026         v|\*(\d+\$)?v      vector with optional (optionally specified) arg
11027         0                  flag (as above): repeated to allow "v02"     
11028         \d+|\*(\d+\$)?     width using optional (optionally specified) arg
11029         \.(\d*|\*(\d+\$)?) precision using optional (optionally specified) arg
11030         [hlqLV]            size
11031     [%bcdefginopsuxDFOUX] format (mandatory)
11032 */
11033
11034         if (args) {
11035 /*  
11036         As of perl5.9.3, printf format checking is on by default.
11037         Internally, perl uses %p formats to provide an escape to
11038         some extended formatting.  This block deals with those
11039         extensions: if it does not match, (char*)q is reset and
11040         the normal format processing code is used.
11041
11042         Currently defined extensions are:
11043                 %p              include pointer address (standard)      
11044                 %-p     (SVf)   include an SV (previously %_)
11045                 %-<num>p        include an SV with precision <num>      
11046                 %2p             include a HEK
11047                 %3p             include a HEK with precision of 256
11048                 %4p             char* preceded by utf8 flag and length
11049                 %<num>p         (where num is 1 or > 4) reserved for future
11050                                 extensions
11051
11052         Robin Barker 2005-07-14 (but modified since)
11053
11054                 %1p     (VDf)   removed.  RMB 2007-10-19
11055 */
11056             char* r = q; 
11057             bool sv = FALSE;    
11058             STRLEN n = 0;
11059             if (*q == '-')
11060                 sv = *q++;
11061             else if (strnEQ(q, UTF8f, sizeof(UTF8f)-1)) { /* UTF8f */
11062                 /* The argument has already gone through cBOOL, so the cast
11063                    is safe. */
11064                 is_utf8 = (bool)va_arg(*args, int);
11065                 elen = va_arg(*args, UV);
11066                 eptr = va_arg(*args, char *);
11067                 q += sizeof(UTF8f)-1;
11068                 goto string;
11069             }
11070             n = expect_number(&q);
11071             if (*q++ == 'p') {
11072                 if (sv) {                       /* SVf */
11073                     if (n) {
11074                         precis = n;
11075                         has_precis = TRUE;
11076                     }
11077                     argsv = MUTABLE_SV(va_arg(*args, void*));
11078                     eptr = SvPV_const(argsv, elen);
11079                     if (DO_UTF8(argsv))
11080                         is_utf8 = TRUE;
11081                     goto string;
11082                 }
11083                 else if (n==2 || n==3) {        /* HEKf */
11084                     HEK * const hek = va_arg(*args, HEK *);
11085                     eptr = HEK_KEY(hek);
11086                     elen = HEK_LEN(hek);
11087                     if (HEK_UTF8(hek)) is_utf8 = TRUE;
11088                     if (n==3) precis = 256, has_precis = TRUE;
11089                     goto string;
11090                 }
11091                 else if (n) {
11092                     Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
11093                                      "internal %%<num>p might conflict with future printf extensions");
11094                 }
11095             }
11096             q = r; 
11097         }
11098
11099         if ( (width = expect_number(&q)) ) {
11100             if (*q == '$') {
11101                 ++q;
11102                 efix = width;
11103                 if (!no_redundant_warning)
11104                     /* I've forgotten if it's a better
11105                        micro-optimization to always set this or to
11106                        only set it if it's unset */
11107                     no_redundant_warning = TRUE;
11108             } else {
11109                 goto gotwidth;
11110             }
11111         }
11112
11113         /* FLAGS */
11114
11115         while (*q) {
11116             switch (*q) {
11117             case ' ':
11118             case '+':
11119                 if (plus == '+' && *q == ' ') /* '+' over ' ' */
11120                     q++;
11121                 else
11122                     plus = *q++;
11123                 continue;
11124
11125             case '-':
11126                 left = TRUE;
11127                 q++;
11128                 continue;
11129
11130             case '0':
11131                 fill = *q++;
11132                 continue;
11133
11134             case '#':
11135                 alt = TRUE;
11136                 q++;
11137                 continue;
11138
11139             default:
11140                 break;
11141             }
11142             break;
11143         }
11144
11145       tryasterisk:
11146         if (*q == '*') {
11147             q++;
11148             if ( (ewix = expect_number(&q)) )
11149                 if (*q++ != '$')
11150                     goto unknown;
11151             asterisk = TRUE;
11152         }
11153         if (*q == 'v') {
11154             q++;
11155             if (vectorize)
11156                 goto unknown;
11157             if ((vectorarg = asterisk)) {
11158                 evix = ewix;
11159                 ewix = 0;
11160                 asterisk = FALSE;
11161             }
11162             vectorize = TRUE;
11163             goto tryasterisk;
11164         }
11165
11166         if (!asterisk)
11167         {
11168             if( *q == '0' )
11169                 fill = *q++;
11170             width = expect_number(&q);
11171         }
11172
11173         if (vectorize && vectorarg) {
11174             /* vectorizing, but not with the default "." */
11175             if (args)
11176                 vecsv = va_arg(*args, SV*);
11177             else if (evix) {
11178                 vecsv = (evix > 0 && evix <= svmax)
11179                     ? svargs[evix-1] : S_vcatpvfn_missing_argument(aTHX);
11180             } else {
11181                 vecsv = svix < svmax
11182                     ? svargs[svix++] : S_vcatpvfn_missing_argument(aTHX);
11183             }
11184             dotstr = SvPV_const(vecsv, dotstrlen);
11185             /* Keep the DO_UTF8 test *after* the SvPV call, else things go
11186                bad with tied or overloaded values that return UTF8.  */
11187             if (DO_UTF8(vecsv))
11188                 is_utf8 = TRUE;
11189             else if (has_utf8) {
11190                 vecsv = sv_mortalcopy(vecsv);
11191                 sv_utf8_upgrade(vecsv);
11192                 dotstr = SvPV_const(vecsv, dotstrlen);
11193                 is_utf8 = TRUE;
11194             }               
11195         }
11196
11197         if (asterisk) {
11198             if (args)
11199                 i = va_arg(*args, int);
11200             else
11201                 i = (ewix ? ewix <= svmax : svix < svmax) ?
11202                     SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
11203             left |= (i < 0);
11204             width = (i < 0) ? -i : i;
11205         }
11206       gotwidth:
11207
11208         /* PRECISION */
11209
11210         if (*q == '.') {
11211             q++;
11212             if (*q == '*') {
11213                 q++;
11214                 if ( ((epix = expect_number(&q))) && (*q++ != '$') )
11215                     goto unknown;
11216                 /* XXX: todo, support specified precision parameter */
11217                 if (epix)
11218                     goto unknown;
11219                 if (args)
11220                     i = va_arg(*args, int);
11221                 else
11222                     i = (ewix ? ewix <= svmax : svix < svmax)
11223                         ? SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
11224                 precis = i;
11225                 has_precis = !(i < 0);
11226             }
11227             else {
11228                 precis = 0;
11229                 while (isDIGIT(*q))
11230                     precis = precis * 10 + (*q++ - '0');
11231                 has_precis = TRUE;
11232             }
11233         }
11234
11235         if (vectorize) {
11236             if (args) {
11237                 VECTORIZE_ARGS
11238             }
11239             else if (efix ? (efix > 0 && efix <= svmax) : svix < svmax) {
11240                 vecsv = svargs[efix ? efix-1 : svix++];
11241                 vecstr = (U8*)SvPV_const(vecsv,veclen);
11242                 vec_utf8 = DO_UTF8(vecsv);
11243
11244                 /* if this is a version object, we need to convert
11245                  * back into v-string notation and then let the
11246                  * vectorize happen normally
11247                  */
11248                 if (sv_isobject(vecsv) && sv_derived_from(vecsv, "version")) {
11249                     if ( hv_exists(MUTABLE_HV(SvRV(vecsv)), "alpha", 5 ) ) {
11250                         Perl_ck_warner_d(aTHX_ packWARN(WARN_PRINTF),
11251                         "vector argument not supported with alpha versions");
11252                         goto vdblank;
11253                     }
11254                     vecsv = sv_newmortal();
11255                     scan_vstring((char *)vecstr, (char *)vecstr + veclen,
11256                                  vecsv);
11257                     vecstr = (U8*)SvPV_const(vecsv, veclen);
11258                     vec_utf8 = DO_UTF8(vecsv);
11259                 }
11260             }
11261             else {
11262               vdblank:
11263                 vecstr = (U8*)"";
11264                 veclen = 0;
11265             }
11266         }
11267
11268         /* SIZE */
11269
11270         switch (*q) {
11271 #ifdef WIN32
11272         case 'I':                       /* Ix, I32x, and I64x */
11273 #  ifdef USE_64_BIT_INT
11274             if (q[1] == '6' && q[2] == '4') {
11275                 q += 3;
11276                 intsize = 'q';
11277                 break;
11278             }
11279 #  endif
11280             if (q[1] == '3' && q[2] == '2') {
11281                 q += 3;
11282                 break;
11283             }
11284 #  ifdef USE_64_BIT_INT
11285             intsize = 'q';
11286 #  endif
11287             q++;
11288             break;
11289 #endif
11290 #if IVSIZE >= 8 || defined(HAS_LONG_DOUBLE)
11291         case 'L':                       /* Ld */
11292             /* FALLTHROUGH */
11293 #if IVSIZE >= 8
11294         case 'q':                       /* qd */
11295 #endif
11296             intsize = 'q';
11297             q++;
11298             break;
11299 #endif
11300         case 'l':
11301             ++q;
11302 #if IVSIZE >= 8 || defined(HAS_LONG_DOUBLE)
11303             if (*q == 'l') {    /* lld, llf */
11304                 intsize = 'q';
11305                 ++q;
11306             }
11307             else
11308 #endif
11309                 intsize = 'l';
11310             break;
11311         case 'h':
11312             if (*++q == 'h') {  /* hhd, hhu */
11313                 intsize = 'c';
11314                 ++q;
11315             }
11316             else
11317                 intsize = 'h';
11318             break;
11319         case 'V':
11320         case 'z':
11321         case 't':
11322 #ifdef I_STDINT
11323         case 'j':
11324 #endif
11325             intsize = *q++;
11326             break;
11327         }
11328
11329         /* CONVERSION */
11330
11331         if (*q == '%') {
11332             eptr = q++;
11333             elen = 1;
11334             if (vectorize) {
11335                 c = '%';
11336                 goto unknown;
11337             }
11338             goto string;
11339         }
11340
11341         if (!vectorize && !args) {
11342             if (efix) {
11343                 const I32 i = efix-1;
11344                 argsv = (i >= 0 && i < svmax)
11345                     ? svargs[i] : S_vcatpvfn_missing_argument(aTHX);
11346             } else {
11347                 argsv = (svix >= 0 && svix < svmax)
11348                     ? svargs[svix++] : S_vcatpvfn_missing_argument(aTHX);
11349             }
11350         }
11351
11352         if (argsv && SvNOK(argsv)) {
11353             /* XXX va_arg(*args) case? */
11354             infnan = Perl_isinfnan(SvNV(argsv));
11355         }
11356
11357         switch (c = *q++) {
11358
11359             /* STRINGS */
11360
11361         case 'c':
11362             if (vectorize)
11363                 goto unknown;
11364             uv = (args) ? va_arg(*args, int) :
11365                 infnan ? UNICODE_REPLACEMENT : SvIV(argsv);
11366             if ((uv > 255 ||
11367                  (!UVCHR_IS_INVARIANT(uv) && SvUTF8(sv)))
11368                 && !IN_BYTES) {
11369                 eptr = (char*)utf8buf;
11370                 elen = uvchr_to_utf8((U8*)eptr, uv) - utf8buf;
11371                 is_utf8 = TRUE;
11372             }
11373             else {
11374                 c = (char)uv;
11375                 eptr = &c;
11376                 elen = 1;
11377             }
11378             goto string;
11379
11380         case 's':
11381             if (vectorize)
11382                 goto unknown;
11383             if (args) {
11384                 eptr = va_arg(*args, char*);
11385                 if (eptr)
11386                     elen = strlen(eptr);
11387                 else {
11388                     eptr = (char *)nullstr;
11389                     elen = sizeof nullstr - 1;
11390                 }
11391             }
11392             else {
11393                 eptr = SvPV_const(argsv, elen);
11394                 if (DO_UTF8(argsv)) {
11395                     STRLEN old_precis = precis;
11396                     if (has_precis && precis < elen) {
11397                         STRLEN ulen = sv_or_pv_len_utf8(argsv, eptr, elen);
11398                         STRLEN p = precis > ulen ? ulen : precis;
11399                         precis = sv_or_pv_pos_u2b(argsv, eptr, p, 0);
11400                                                         /* sticks at end */
11401                     }
11402                     if (width) { /* fudge width (can't fudge elen) */
11403                         if (has_precis && precis < elen)
11404                             width += precis - old_precis;
11405                         else
11406                             width +=
11407                                 elen - sv_or_pv_len_utf8(argsv,eptr,elen);
11408                     }
11409                     is_utf8 = TRUE;
11410                 }
11411             }
11412
11413         string:
11414             if (has_precis && precis < elen)
11415                 elen = precis;
11416             break;
11417
11418             /* INTEGERS */
11419
11420         case 'p':
11421             if (infnan) {
11422                 c = 'g';
11423                 goto floating_point;
11424             }
11425             if (alt || vectorize)
11426                 goto unknown;
11427             uv = PTR2UV(args ? va_arg(*args, void*) : argsv);
11428             base = 16;
11429             goto integer;
11430
11431         case 'D':
11432 #ifdef IV_IS_QUAD
11433             intsize = 'q';
11434 #else
11435             intsize = 'l';
11436 #endif
11437             /* FALLTHROUGH */
11438         case 'd':
11439         case 'i':
11440             if (infnan) {
11441                 c = 'g';
11442                 goto floating_point;
11443             }
11444             if (vectorize) {
11445                 STRLEN ulen;
11446                 if (!veclen)
11447                     continue;
11448                 if (vec_utf8)
11449                     uv = utf8n_to_uvchr(vecstr, veclen, &ulen,
11450                                         UTF8_ALLOW_ANYUV);
11451                 else {
11452                     uv = *vecstr;
11453                     ulen = 1;
11454                 }
11455                 vecstr += ulen;
11456                 veclen -= ulen;
11457                 if (plus)
11458                      esignbuf[esignlen++] = plus;
11459             }
11460             else if (args) {
11461                 switch (intsize) {
11462                 case 'c':       iv = (char)va_arg(*args, int); break;
11463                 case 'h':       iv = (short)va_arg(*args, int); break;
11464                 case 'l':       iv = va_arg(*args, long); break;
11465                 case 'V':       iv = va_arg(*args, IV); break;
11466                 case 'z':       iv = va_arg(*args, SSize_t); break;
11467 #ifdef HAS_PTRDIFF_T
11468                 case 't':       iv = va_arg(*args, ptrdiff_t); break;
11469 #endif
11470                 default:        iv = va_arg(*args, int); break;
11471 #ifdef I_STDINT
11472                 case 'j':       iv = va_arg(*args, intmax_t); break;
11473 #endif
11474                 case 'q':
11475 #if IVSIZE >= 8
11476                                 iv = va_arg(*args, Quad_t); break;
11477 #else
11478                                 goto unknown;
11479 #endif
11480                 }
11481             }
11482             else {
11483                 IV tiv = SvIV(argsv); /* work around GCC bug #13488 */
11484                 switch (intsize) {
11485                 case 'c':       iv = (char)tiv; break;
11486                 case 'h':       iv = (short)tiv; break;
11487                 case 'l':       iv = (long)tiv; break;
11488                 case 'V':
11489                 default:        iv = tiv; break;
11490                 case 'q':
11491 #if IVSIZE >= 8
11492                                 iv = (Quad_t)tiv; break;
11493 #else
11494                                 goto unknown;
11495 #endif
11496                 }
11497             }
11498             if ( !vectorize )   /* we already set uv above */
11499             {
11500                 if (iv >= 0) {
11501                     uv = iv;
11502                     if (plus)
11503                         esignbuf[esignlen++] = plus;
11504                 }
11505                 else {
11506                     uv = -iv;
11507                     esignbuf[esignlen++] = '-';
11508                 }
11509             }
11510             base = 10;
11511             goto integer;
11512
11513         case 'U':
11514 #ifdef IV_IS_QUAD
11515             intsize = 'q';
11516 #else
11517             intsize = 'l';
11518 #endif
11519             /* FALLTHROUGH */
11520         case 'u':
11521             base = 10;
11522             goto uns_integer;
11523
11524         case 'B':
11525         case 'b':
11526             base = 2;
11527             goto uns_integer;
11528
11529         case 'O':
11530 #ifdef IV_IS_QUAD
11531             intsize = 'q';
11532 #else
11533             intsize = 'l';
11534 #endif
11535             /* FALLTHROUGH */
11536         case 'o':
11537             base = 8;
11538             goto uns_integer;
11539
11540         case 'X':
11541         case 'x':
11542             base = 16;
11543
11544         uns_integer:
11545             if (infnan) {
11546                 c = 'g';
11547                 goto floating_point;
11548             }
11549             if (vectorize) {
11550                 STRLEN ulen;
11551         vector:
11552                 if (!veclen)
11553                     continue;
11554                 if (vec_utf8)
11555                     uv = utf8n_to_uvchr(vecstr, veclen, &ulen,
11556                                         UTF8_ALLOW_ANYUV);
11557                 else {
11558                     uv = *vecstr;
11559                     ulen = 1;
11560                 }
11561                 vecstr += ulen;
11562                 veclen -= ulen;
11563             }
11564             else if (args) {
11565                 switch (intsize) {
11566                 case 'c':  uv = (unsigned char)va_arg(*args, unsigned); break;
11567                 case 'h':  uv = (unsigned short)va_arg(*args, unsigned); break;
11568                 case 'l':  uv = va_arg(*args, unsigned long); break;
11569                 case 'V':  uv = va_arg(*args, UV); break;
11570                 case 'z':  uv = va_arg(*args, Size_t); break;
11571 #ifdef HAS_PTRDIFF_T
11572                 case 't':  uv = va_arg(*args, ptrdiff_t); break; /* will sign extend, but there is no uptrdiff_t, so oh well */
11573 #endif
11574 #ifdef I_STDINT
11575                 case 'j':  uv = va_arg(*args, uintmax_t); break;
11576 #endif
11577                 default:   uv = va_arg(*args, unsigned); break;
11578                 case 'q':
11579 #if IVSIZE >= 8
11580                            uv = va_arg(*args, Uquad_t); break;
11581 #else
11582                            goto unknown;
11583 #endif
11584                 }
11585             }
11586             else {
11587                 UV tuv = SvUV(argsv); /* work around GCC bug #13488 */
11588                 switch (intsize) {
11589                 case 'c':       uv = (unsigned char)tuv; break;
11590                 case 'h':       uv = (unsigned short)tuv; break;
11591                 case 'l':       uv = (unsigned long)tuv; break;
11592                 case 'V':
11593                 default:        uv = tuv; break;
11594                 case 'q':
11595 #if IVSIZE >= 8
11596                                 uv = (Uquad_t)tuv; break;
11597 #else
11598                                 goto unknown;
11599 #endif
11600                 }
11601             }
11602
11603         integer:
11604             {
11605                 char *ptr = ebuf + sizeof ebuf;
11606                 bool tempalt = uv ? alt : FALSE; /* Vectors can't change alt */
11607                 unsigned dig;
11608                 zeros = 0;
11609
11610                 switch (base) {
11611                 case 16:
11612                     p = (char *)((c == 'X') ? PL_hexdigit + 16 : PL_hexdigit);
11613                     do {
11614                         dig = uv & 15;
11615                         *--ptr = p[dig];
11616                     } while (uv >>= 4);
11617                     if (tempalt) {
11618                         esignbuf[esignlen++] = '0';
11619                         esignbuf[esignlen++] = c;  /* 'x' or 'X' */
11620                     }
11621                     break;
11622                 case 8:
11623                     do {
11624                         dig = uv & 7;
11625                         *--ptr = '0' + dig;
11626                     } while (uv >>= 3);
11627                     if (alt && *ptr != '0')
11628                         *--ptr = '0';
11629                     break;
11630                 case 2:
11631                     do {
11632                         dig = uv & 1;
11633                         *--ptr = '0' + dig;
11634                     } while (uv >>= 1);
11635                     if (tempalt) {
11636                         esignbuf[esignlen++] = '0';
11637                         esignbuf[esignlen++] = c;
11638                     }
11639                     break;
11640                 default:                /* it had better be ten or less */
11641                     do {
11642                         dig = uv % base;
11643                         *--ptr = '0' + dig;
11644                     } while (uv /= base);
11645                     break;
11646                 }
11647                 elen = (ebuf + sizeof ebuf) - ptr;
11648                 eptr = ptr;
11649                 if (has_precis) {
11650                     if (precis > elen)
11651                         zeros = precis - elen;
11652                     else if (precis == 0 && elen == 1 && *eptr == '0'
11653                              && !(base == 8 && alt)) /* "%#.0o" prints "0" */
11654                         elen = 0;
11655
11656                 /* a precision nullifies the 0 flag. */
11657                     if (fill == '0')
11658                         fill = ' ';
11659                 }
11660             }
11661             break;
11662
11663             /* FLOATING POINT */
11664
11665         floating_point:
11666
11667         case 'F':
11668             c = 'f';            /* maybe %F isn't supported here */
11669             /* FALLTHROUGH */
11670         case 'e': case 'E':
11671         case 'f':
11672         case 'g': case 'G':
11673         case 'a': case 'A':
11674             if (vectorize)
11675                 goto unknown;
11676
11677             /* This is evil, but floating point is even more evil */
11678
11679             /* for SV-style calling, we can only get NV
11680                for C-style calling, we assume %f is double;
11681                for simplicity we allow any of %Lf, %llf, %qf for long double
11682             */
11683             switch (intsize) {
11684             case 'V':
11685 #if defined(USE_LONG_DOUBLE)
11686                 intsize = 'q';
11687 #endif
11688                 break;
11689 /* [perl #20339] - we should accept and ignore %lf rather than die */
11690             case 'l':
11691                 /* FALLTHROUGH */
11692             default:
11693 #if defined(USE_LONG_DOUBLE)
11694                 intsize = args ? 0 : 'q';
11695 #endif
11696                 break;
11697             case 'q':
11698 #if defined(HAS_LONG_DOUBLE)
11699                 break;
11700 #else
11701                 /* FALLTHROUGH */
11702 #endif
11703             case 'c':
11704             case 'h':
11705             case 'z':
11706             case 't':
11707             case 'j':
11708                 goto unknown;
11709             }
11710
11711             /* now we need (long double) if intsize == 'q', else (double) */
11712             nv = (args) ?
11713 #if LONG_DOUBLESIZE > DOUBLESIZE
11714                 intsize == 'q' ?
11715                     va_arg(*args, long double) :
11716                     va_arg(*args, double)
11717 #else
11718                     va_arg(*args, double)
11719 #endif
11720                 : SvNV(argsv);
11721
11722             need = 0;
11723             /* frexp() (or frexpl) has some unspecified behaviour for
11724              * nan/inf/-inf, so let's avoid calling that on non-finites. */
11725             if (isALPHA_FOLD_NE(c, 'e') && Perl_isfinite(nv)) {
11726                 i = PERL_INT_MIN;
11727                 (void)Perl_frexp(nv, &i);
11728                 if (i == PERL_INT_MIN)
11729                     Perl_die(aTHX_ "panic: frexp: %"myNVgf, nv);
11730                 /* Do not set hexfp earlier since we want to printf
11731                  * Inf/NaN for Inf/NAN, not their hexfp. */
11732                 hexfp = isALPHA_FOLD_EQ(c, 'a');
11733                 if (UNLIKELY(hexfp)) {
11734                     /* This seriously overshoots in most cases, but
11735                      * better the undershooting.  Firstly, all bytes
11736                      * of the NV are not mantissa, some of them are
11737                      * exponent.  Secondly, for the reasonably common
11738                      * long doubles case, the "80-bit extended", two
11739                      * or six bytes of the NV are unused. */
11740                     need +=
11741                         (nv < 0) ? 1 : 0 + /* possible unary minus */
11742                         2 + /* "0x" */
11743                         1 + /* the very unlikely carry */
11744                         1 + /* "1" */
11745                         1 + /* "." */
11746                         2 * NVSIZE + /* 2 hexdigits for each byte */
11747                         2 + /* "p+" */
11748                         BIT_DIGITS(NV_MAX_EXP) + /* exponent */
11749                         1;   /* \0 */
11750 #if LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LITTLE_ENDIAN || \
11751     LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BIG_ENDIAN
11752                     /* However, for the "double double", we need more.
11753                      * Since each double has their own exponent, the
11754                      * doubles may float (haha) rather far from each
11755                      * other, and the number of required bits is much
11756                      * larger, up to total of 1028 bits.  (NOTE: this
11757                      * is not actually implemented properly yet,
11758                      * we are using just the first double, see
11759                      * S_hextract() for details.  But let's prepare
11760                      * for the future.) */
11761
11762                     /* 2 hexdigits for each byte. */ 
11763                     need += (1028/8 - DOUBLESIZE + 1) * 2;
11764 #endif
11765 #ifdef USE_LOCALE_NUMERIC
11766                         STORE_LC_NUMERIC_SET_TO_NEEDED();
11767                         if (PL_numeric_radix_sv && IN_LC(LC_NUMERIC))
11768                             need += SvLEN(PL_numeric_radix_sv);
11769                         RESTORE_LC_NUMERIC();
11770 #endif
11771                 }
11772                 else if (i > 0) {
11773                     need = BIT_DIGITS(i);
11774                 } /* if i < 0, the number of digits is hard to predict. */
11775             }
11776             need += has_precis ? precis : 6; /* known default */
11777
11778             if (need < width)
11779                 need = width;
11780
11781 #ifdef HAS_LDBL_SPRINTF_BUG
11782             /* This is to try to fix a bug with irix/nonstop-ux/powerux and
11783                with sfio - Allen <allens@cpan.org> */
11784
11785 #  ifdef DBL_MAX
11786 #    define MY_DBL_MAX DBL_MAX
11787 #  else /* XXX guessing! HUGE_VAL may be defined as infinity, so not using */
11788 #    if DOUBLESIZE >= 8
11789 #      define MY_DBL_MAX 1.7976931348623157E+308L
11790 #    else
11791 #      define MY_DBL_MAX 3.40282347E+38L
11792 #    endif
11793 #  endif
11794
11795 #  ifdef HAS_LDBL_SPRINTF_BUG_LESS1 /* only between -1L & 1L - Allen */
11796 #    define MY_DBL_MAX_BUG 1L
11797 #  else
11798 #    define MY_DBL_MAX_BUG MY_DBL_MAX
11799 #  endif
11800
11801 #  ifdef DBL_MIN
11802 #    define MY_DBL_MIN DBL_MIN
11803 #  else  /* XXX guessing! -Allen */
11804 #    if DOUBLESIZE >= 8
11805 #      define MY_DBL_MIN 2.2250738585072014E-308L
11806 #    else
11807 #      define MY_DBL_MIN 1.17549435E-38L
11808 #    endif
11809 #  endif
11810
11811             if ((intsize == 'q') && (c == 'f') &&
11812                 ((nv < MY_DBL_MAX_BUG) && (nv > -MY_DBL_MAX_BUG)) &&
11813                 (need < DBL_DIG)) {
11814                 /* it's going to be short enough that
11815                  * long double precision is not needed */
11816
11817                 if ((nv <= 0L) && (nv >= -0L))
11818                     fix_ldbl_sprintf_bug = TRUE; /* 0 is 0 - easiest */
11819                 else {
11820                     /* would use Perl_fp_class as a double-check but not
11821                      * functional on IRIX - see perl.h comments */
11822
11823                     if ((nv >= MY_DBL_MIN) || (nv <= -MY_DBL_MIN)) {
11824                         /* It's within the range that a double can represent */
11825 #if defined(DBL_MAX) && !defined(DBL_MIN)
11826                         if ((nv >= ((long double)1/DBL_MAX)) ||
11827                             (nv <= (-(long double)1/DBL_MAX)))
11828 #endif
11829                         fix_ldbl_sprintf_bug = TRUE;
11830                     }
11831                 }
11832                 if (fix_ldbl_sprintf_bug == TRUE) {
11833                     double temp;
11834
11835                     intsize = 0;
11836                     temp = (double)nv;
11837                     nv = (NV)temp;
11838                 }
11839             }
11840
11841 #  undef MY_DBL_MAX
11842 #  undef MY_DBL_MAX_BUG
11843 #  undef MY_DBL_MIN
11844
11845 #endif /* HAS_LDBL_SPRINTF_BUG */
11846
11847             need += 20; /* fudge factor */
11848             if (PL_efloatsize < need) {
11849                 Safefree(PL_efloatbuf);
11850                 PL_efloatsize = need + 20; /* more fudge */
11851                 Newx(PL_efloatbuf, PL_efloatsize, char);
11852                 PL_efloatbuf[0] = '\0';
11853             }
11854
11855             if ( !(width || left || plus || alt) && fill != '0'
11856                  && has_precis && intsize != 'q' ) {    /* Shortcuts */
11857                 /* See earlier comment about buggy Gconvert when digits,
11858                    aka precis is 0  */
11859                 if ( c == 'g' && precis) {
11860                     STORE_LC_NUMERIC_SET_TO_NEEDED();
11861                     PERL_UNUSED_RESULT(Gconvert((NV)nv, (int)precis, 0, PL_efloatbuf));
11862                     /* May return an empty string for digits==0 */
11863                     if (*PL_efloatbuf) {
11864                         elen = strlen(PL_efloatbuf);
11865                         goto float_converted;
11866                     }
11867                 } else if ( c == 'f' && !precis) {
11868                     if ((eptr = F0convert(nv, ebuf + sizeof ebuf, &elen)))
11869                         break;
11870                 }
11871             }
11872
11873             if (UNLIKELY(hexfp)) {
11874                 /* Hexadecimal floating point. */
11875                 char* p = PL_efloatbuf;
11876                 U8 vhex[VHEX_SIZE];
11877                 U8* v = vhex; /* working pointer to vhex */
11878                 U8* vend; /* pointer to one beyond last digit of vhex */
11879                 U8* vfnz = NULL; /* first non-zero */
11880                 const bool lower = (c == 'a');
11881                 /* At output the values of vhex (up to vend) will
11882                  * be mapped through the xdig to get the actual
11883                  * human-readable xdigits. */
11884                 const char* xdig = PL_hexdigit;
11885                 int zerotail = 0; /* how many extra zeros to append */
11886                 int exponent = 0; /* exponent of the floating point input */
11887
11888                 /* XXX: denormals, NaN, Inf.
11889                  *
11890                  * For example with denormals, (assuming the vanilla
11891                  * 64-bit double): the exponent is zero. 1xp-1074 is
11892                  * the smallest denormal and the smallest double, it
11893                  * should be output as 0x0.0000000000001p-1022 to
11894                  * match its internal structure. */
11895
11896                 vend = S_hextract(aTHX_ nv, &exponent, vhex, NULL);
11897                 S_hextract(aTHX_ nv, &exponent, vhex, vend);
11898
11899 #if NVSIZE > DOUBLESIZE && defined(LONG_DOUBLEKIND)
11900 #  if LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN || \
11901       LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN
11902                 exponent -= 4;
11903 #  else
11904                 exponent--;
11905 #  endif
11906 #endif
11907
11908                 if (nv < 0)
11909                     *p++ = '-';
11910                 else if (plus)
11911                     *p++ = plus;
11912                 *p++ = '0';
11913                 if (lower) {
11914                     *p++ = 'x';
11915                 }
11916                 else {
11917                     *p++ = 'X';
11918                     xdig += 16; /* Use uppercase hex. */
11919                 }
11920
11921                 /* Find the first non-zero xdigit. */
11922                 for (v = vhex; v < vend; v++) {
11923                     if (*v) {
11924                         vfnz = v;
11925                         break;
11926                     }
11927                 }
11928
11929                 if (vfnz) {
11930                     U8* vlnz = NULL; /* The last non-zero. */
11931
11932                     /* Find the last non-zero xdigit. */
11933                     for (v = vend - 1; v >= vhex; v--) {
11934                         if (*v) {
11935                             vlnz = v;
11936                             break;
11937                         }
11938                     }
11939
11940 #if NVSIZE == DOUBLESIZE
11941                     exponent--;
11942 #endif
11943
11944                     if (precis > 0) {
11945                         v = vhex + precis + 1;
11946                         if (v < vend) {
11947                             /* Round away from zero: if the tail
11948                              * beyond the precis xdigits is equal to
11949                              * or greater than 0x8000... */
11950                             bool round = *v > 0x8;
11951                             if (!round && *v == 0x8) {
11952                                 for (v++; v < vend; v++) {
11953                                     if (*v) {
11954                                         round = TRUE;
11955                                         break;
11956                                     }
11957                                 }
11958                             }
11959                             if (round) {
11960                                 for (v = vhex + precis; v >= vhex; v--) {
11961                                     if (*v < 0xF) {
11962                                         (*v)++;
11963                                         break;
11964                                     }
11965                                     *v = 0;
11966                                     if (v == vhex) {
11967                                         /* If the carry goes all the way to
11968                                          * the front, we need to output
11969                                          * a single '1'. This goes against
11970                                          * the "xdigit and then radix"
11971                                          * but since this is "cannot happen"
11972                                          * category, that is probably good. */
11973                                         *p++ = xdig[1];
11974                                     }
11975                                 }
11976                             }
11977                             /* The new effective "last non zero". */
11978                             vlnz = vhex + precis;
11979                         }
11980                         else {
11981                             zerotail = precis - (vlnz - vhex);
11982                         }
11983                     }
11984
11985                     v = vhex;
11986                     *p++ = xdig[*v++];
11987
11988                     /* The radix is always output after the first
11989                      * non-zero xdigit, or if alt.  */
11990                     if (vfnz < vlnz || alt) {
11991 #ifndef USE_LOCALE_NUMERIC
11992                         *p++ = '.';
11993 #else
11994                         STORE_LC_NUMERIC_SET_TO_NEEDED();
11995                         if (PL_numeric_radix_sv && IN_LC(LC_NUMERIC)) {
11996                             STRLEN n;
11997                             const char* r = SvPV(PL_numeric_radix_sv, n);
11998                             Copy(r, p, n, char);
11999                             p += n;
12000                         }
12001                         else {
12002                             *p++ = '.';
12003                         }
12004                         RESTORE_LC_NUMERIC();
12005 #endif
12006                     }
12007
12008                     while (v <= vlnz)
12009                         *p++ = xdig[*v++];
12010
12011                     while (zerotail--)
12012                         *p++ = '0';
12013                 }
12014                 else {
12015                     *p++ = '0';
12016                     exponent = 0;
12017                 }
12018
12019                 elen = p - PL_efloatbuf;
12020                 elen += my_snprintf(p, PL_efloatsize - elen,
12021                                     "%c%+d", lower ? 'p' : 'P',
12022                                     exponent);
12023
12024                 if (elen < width) {
12025                     if (left) {
12026                         /* Pad the back with spaces. */
12027                         memset(PL_efloatbuf + elen, ' ', width - elen);
12028                     }
12029                     else if (fill == '0') {
12030                         /* Insert the zeros between the "0x" and
12031                          * the digits, otherwise we end up with
12032                          * "0000xHHH..." */
12033                         STRLEN nzero = width - elen;
12034                         char* zerox = PL_efloatbuf + 2;
12035                         Move(zerox, zerox + nzero,  elen - 2, char);
12036                         memset(zerox, fill, nzero);
12037                     }
12038                     else {
12039                         /* Move it to the right. */
12040                         Move(PL_efloatbuf, PL_efloatbuf + width - elen,
12041                              elen, char);
12042                         /* Pad the front with spaces. */
12043                         memset(PL_efloatbuf, ' ', width - elen);
12044                     }
12045                     elen = width;
12046                 }
12047             }
12048             else
12049                 elen = S_infnan_copy(nv, PL_efloatbuf, 5);
12050             if (elen == 0) {
12051                 char *ptr = ebuf + sizeof ebuf;
12052                 *--ptr = '\0';
12053                 *--ptr = c;
12054                 /* FIXME: what to do if HAS_LONG_DOUBLE but not PERL_PRIfldbl? */
12055 #if defined(HAS_LONG_DOUBLE) && defined(PERL_PRIfldbl)
12056                 /* Note that this is HAS_LONG_DOUBLE and PERL_PRIfldbl,
12057                  * not USE_LONG_DOUBLE and NVff.  In other words,
12058                  * this needs to work without USE_LONG_DOUBLE. */
12059                 if (intsize == 'q') {
12060                     /* Copy the one or more characters in a long double
12061                      * format before the 'base' ([efgEFG]) character to
12062                      * the format string. */
12063                     static char const ldblf[] = PERL_PRIfldbl;
12064                     char const *p = ldblf + sizeof(ldblf) - 3;
12065                     while (p >= ldblf) { *--ptr = *p--; }
12066                 }
12067 #endif
12068                 if (has_precis) {
12069                     base = precis;
12070                     do { *--ptr = '0' + (base % 10); } while (base /= 10);
12071                     *--ptr = '.';
12072                 }
12073                 if (width) {
12074                     base = width;
12075                     do { *--ptr = '0' + (base % 10); } while (base /= 10);
12076                 }
12077                 if (fill == '0')
12078                     *--ptr = fill;
12079                 if (left)
12080                     *--ptr = '-';
12081                 if (plus)
12082                     *--ptr = plus;
12083                 if (alt)
12084                     *--ptr = '#';
12085                 *--ptr = '%';
12086
12087                 /* No taint.  Otherwise we are in the strange situation
12088                  * where printf() taints but print($float) doesn't.
12089                  * --jhi */
12090
12091                 STORE_LC_NUMERIC_SET_TO_NEEDED();
12092
12093                 /* hopefully the above makes ptr a very constrained format
12094                  * that is safe to use, even though it's not literal */
12095                 GCC_DIAG_IGNORE(-Wformat-nonliteral);
12096 #if defined(HAS_LONG_DOUBLE)
12097                 elen = ((intsize == 'q')
12098                         ? my_snprintf(PL_efloatbuf, PL_efloatsize, ptr, nv)
12099                         : my_snprintf(PL_efloatbuf, PL_efloatsize, ptr, (double)nv));
12100 #else
12101                 elen = my_sprintf(PL_efloatbuf, ptr, nv);
12102 #endif
12103                 GCC_DIAG_RESTORE;
12104             }
12105
12106         float_converted:
12107             eptr = PL_efloatbuf;
12108
12109 #ifdef USE_LOCALE_NUMERIC
12110             /* If the decimal point character in the string is UTF-8, make the
12111              * output utf8 */
12112             if (PL_numeric_radix_sv && SvUTF8(PL_numeric_radix_sv)
12113                 && instr(eptr, SvPVX_const(PL_numeric_radix_sv)))
12114             {
12115                 is_utf8 = TRUE;
12116             }
12117 #endif
12118
12119             break;
12120
12121             /* SPECIAL */
12122
12123         case 'n':
12124             if (vectorize)
12125                 goto unknown;
12126             i = SvCUR(sv) - origlen;
12127             if (args) {
12128                 switch (intsize) {
12129                 case 'c':       *(va_arg(*args, char*)) = i; break;
12130                 case 'h':       *(va_arg(*args, short*)) = i; break;
12131                 default:        *(va_arg(*args, int*)) = i; break;
12132                 case 'l':       *(va_arg(*args, long*)) = i; break;
12133                 case 'V':       *(va_arg(*args, IV*)) = i; break;
12134                 case 'z':       *(va_arg(*args, SSize_t*)) = i; break;
12135 #ifdef HAS_PTRDIFF_T
12136                 case 't':       *(va_arg(*args, ptrdiff_t*)) = i; break;
12137 #endif
12138 #ifdef I_STDINT
12139                 case 'j':       *(va_arg(*args, intmax_t*)) = i; break;
12140 #endif
12141                 case 'q':
12142 #if IVSIZE >= 8
12143                                 *(va_arg(*args, Quad_t*)) = i; break;
12144 #else
12145                                 goto unknown;
12146 #endif
12147                 }
12148             }
12149             else
12150                 sv_setuv_mg(argsv, has_utf8 ? (UV)sv_len_utf8(sv) : (UV)i);
12151             continue;   /* not "break" */
12152
12153             /* UNKNOWN */
12154
12155         default:
12156       unknown:
12157             if (!args
12158                 && (PL_op->op_type == OP_PRTF || PL_op->op_type == OP_SPRINTF)
12159                 && ckWARN(WARN_PRINTF))
12160             {
12161                 SV * const msg = sv_newmortal();
12162                 Perl_sv_setpvf(aTHX_ msg, "Invalid conversion in %sprintf: ",
12163                           (PL_op->op_type == OP_PRTF) ? "" : "s");
12164                 if (fmtstart < patend) {
12165                     const char * const fmtend = q < patend ? q : patend;
12166                     const char * f;
12167                     sv_catpvs(msg, "\"%");
12168                     for (f = fmtstart; f < fmtend; f++) {
12169                         if (isPRINT(*f)) {
12170                             sv_catpvn_nomg(msg, f, 1);
12171                         } else {
12172                             Perl_sv_catpvf(aTHX_ msg,
12173                                            "\\%03"UVof, (UV)*f & 0xFF);
12174                         }
12175                     }
12176                     sv_catpvs(msg, "\"");
12177                 } else {
12178                     sv_catpvs(msg, "end of string");
12179                 }
12180                 Perl_warner(aTHX_ packWARN(WARN_PRINTF), "%"SVf, SVfARG(msg)); /* yes, this is reentrant */
12181             }
12182
12183             /* output mangled stuff ... */
12184             if (c == '\0')
12185                 --q;
12186             eptr = p;
12187             elen = q - p;
12188
12189             /* ... right here, because formatting flags should not apply */
12190             SvGROW(sv, SvCUR(sv) + elen + 1);
12191             p = SvEND(sv);
12192             Copy(eptr, p, elen, char);
12193             p += elen;
12194             *p = '\0';
12195             SvCUR_set(sv, p - SvPVX_const(sv));
12196             svix = osvix;
12197             continue;   /* not "break" */
12198         }
12199
12200         if (is_utf8 != has_utf8) {
12201             if (is_utf8) {
12202                 if (SvCUR(sv))
12203                     sv_utf8_upgrade(sv);
12204             }
12205             else {
12206                 const STRLEN old_elen = elen;
12207                 SV * const nsv = newSVpvn_flags(eptr, elen, SVs_TEMP);
12208                 sv_utf8_upgrade(nsv);
12209                 eptr = SvPVX_const(nsv);
12210                 elen = SvCUR(nsv);
12211
12212                 if (width) { /* fudge width (can't fudge elen) */
12213                     width += elen - old_elen;
12214                 }
12215                 is_utf8 = TRUE;
12216             }
12217         }
12218
12219         have = esignlen + zeros + elen;
12220         if (have < zeros)
12221             croak_memory_wrap();
12222
12223         need = (have > width ? have : width);
12224         gap = need - have;
12225
12226         if (need >= (((STRLEN)~0) - SvCUR(sv) - dotstrlen - 1))
12227             croak_memory_wrap();
12228         SvGROW(sv, SvCUR(sv) + need + dotstrlen + 1);
12229         p = SvEND(sv);
12230         if (esignlen && fill == '0') {
12231             int i;
12232             for (i = 0; i < (int)esignlen; i++)
12233                 *p++ = esignbuf[i];
12234         }
12235         if (gap && !left) {
12236             memset(p, fill, gap);
12237             p += gap;
12238         }
12239         if (esignlen && fill != '0') {
12240             int i;
12241             for (i = 0; i < (int)esignlen; i++)
12242                 *p++ = esignbuf[i];
12243         }
12244         if (zeros) {
12245             int i;
12246             for (i = zeros; i; i--)
12247                 *p++ = '0';
12248         }
12249         if (elen) {
12250             Copy(eptr, p, elen, char);
12251             p += elen;
12252         }
12253         if (gap && left) {
12254             memset(p, ' ', gap);
12255             p += gap;
12256         }
12257         if (vectorize) {
12258             if (veclen) {
12259                 Copy(dotstr, p, dotstrlen, char);
12260                 p += dotstrlen;
12261             }
12262             else
12263                 vectorize = FALSE;              /* done iterating over vecstr */
12264         }
12265         if (is_utf8)
12266             has_utf8 = TRUE;
12267         if (has_utf8)
12268             SvUTF8_on(sv);
12269         *p = '\0';
12270         SvCUR_set(sv, p - SvPVX_const(sv));
12271         if (vectorize) {
12272             esignlen = 0;
12273             goto vector;
12274         }
12275     }
12276
12277     /* Now that we've consumed all our printf format arguments (svix)
12278      * do we have things left on the stack that we didn't use?
12279      */
12280     if (!no_redundant_warning && svmax >= svix + 1 && ckWARN(WARN_REDUNDANT)) {
12281         Perl_warner(aTHX_ packWARN(WARN_REDUNDANT), "Redundant argument in %s",
12282                 PL_op ? OP_DESC(PL_op) : "sv_vcatpvfn()");
12283     }
12284
12285     SvTAINT(sv);
12286
12287     RESTORE_LC_NUMERIC();   /* Done outside loop, so don't have to save/restore
12288                                each iteration. */
12289 }
12290
12291 /* =========================================================================
12292
12293 =head1 Cloning an interpreter
12294
12295 =cut
12296
12297 All the macros and functions in this section are for the private use of
12298 the main function, perl_clone().
12299
12300 The foo_dup() functions make an exact copy of an existing foo thingy.
12301 During the course of a cloning, a hash table is used to map old addresses
12302 to new addresses.  The table is created and manipulated with the
12303 ptr_table_* functions.
12304
12305  * =========================================================================*/
12306
12307
12308 #if defined(USE_ITHREADS)
12309
12310 /* XXX Remove this so it doesn't have to go thru the macro and return for nothing */
12311 #ifndef GpREFCNT_inc
12312 #  define GpREFCNT_inc(gp)      ((gp) ? (++(gp)->gp_refcnt, (gp)) : (GP*)NULL)
12313 #endif
12314
12315
12316 /* Certain cases in Perl_ss_dup have been merged, by relying on the fact
12317    that currently av_dup, gv_dup and hv_dup are the same as sv_dup.
12318    If this changes, please unmerge ss_dup.
12319    Likewise, sv_dup_inc_multiple() relies on this fact.  */
12320 #define sv_dup_inc_NN(s,t)      SvREFCNT_inc_NN(sv_dup_inc(s,t))
12321 #define av_dup(s,t)     MUTABLE_AV(sv_dup((const SV *)s,t))
12322 #define av_dup_inc(s,t) MUTABLE_AV(sv_dup_inc((const SV *)s,t))
12323 #define hv_dup(s,t)     MUTABLE_HV(sv_dup((const SV *)s,t))
12324 #define hv_dup_inc(s,t) MUTABLE_HV(sv_dup_inc((const SV *)s,t))
12325 #define cv_dup(s,t)     MUTABLE_CV(sv_dup((const SV *)s,t))
12326 #define cv_dup_inc(s,t) MUTABLE_CV(sv_dup_inc((const SV *)s,t))
12327 #define io_dup(s,t)     MUTABLE_IO(sv_dup((const SV *)s,t))
12328 #define io_dup_inc(s,t) MUTABLE_IO(sv_dup_inc((const SV *)s,t))
12329 #define gv_dup(s,t)     MUTABLE_GV(sv_dup((const SV *)s,t))
12330 #define gv_dup_inc(s,t) MUTABLE_GV(sv_dup_inc((const SV *)s,t))
12331 #define SAVEPV(p)       ((p) ? savepv(p) : NULL)
12332 #define SAVEPVN(p,n)    ((p) ? savepvn(p,n) : NULL)
12333
12334 /* clone a parser */
12335
12336 yy_parser *
12337 Perl_parser_dup(pTHX_ const yy_parser *const proto, CLONE_PARAMS *const param)
12338 {
12339     yy_parser *parser;
12340
12341     PERL_ARGS_ASSERT_PARSER_DUP;
12342
12343     if (!proto)
12344         return NULL;
12345
12346     /* look for it in the table first */
12347     parser = (yy_parser *)ptr_table_fetch(PL_ptr_table, proto);
12348     if (parser)
12349         return parser;
12350
12351     /* create anew and remember what it is */
12352     Newxz(parser, 1, yy_parser);
12353     ptr_table_store(PL_ptr_table, proto, parser);
12354
12355     /* XXX these not yet duped */
12356     parser->old_parser = NULL;
12357     parser->stack = NULL;
12358     parser->ps = NULL;
12359     parser->stack_size = 0;
12360     /* XXX parser->stack->state = 0; */
12361
12362     /* XXX eventually, just Copy() most of the parser struct ? */
12363
12364     parser->lex_brackets = proto->lex_brackets;
12365     parser->lex_casemods = proto->lex_casemods;
12366     parser->lex_brackstack = savepvn(proto->lex_brackstack,
12367                     (proto->lex_brackets < 120 ? 120 : proto->lex_brackets));
12368     parser->lex_casestack = savepvn(proto->lex_casestack,
12369                     (proto->lex_casemods < 12 ? 12 : proto->lex_casemods));
12370     parser->lex_defer   = proto->lex_defer;
12371     parser->lex_dojoin  = proto->lex_dojoin;
12372     parser->lex_formbrack = proto->lex_formbrack;
12373     parser->lex_inpat   = proto->lex_inpat;
12374     parser->lex_inwhat  = proto->lex_inwhat;
12375     parser->lex_op      = proto->lex_op;
12376     parser->lex_repl    = sv_dup_inc(proto->lex_repl, param);
12377     parser->lex_starts  = proto->lex_starts;
12378     parser->lex_stuff   = sv_dup_inc(proto->lex_stuff, param);
12379     parser->multi_close = proto->multi_close;
12380     parser->multi_open  = proto->multi_open;
12381     parser->multi_start = proto->multi_start;
12382     parser->multi_end   = proto->multi_end;
12383     parser->preambled   = proto->preambled;
12384     parser->sublex_info = proto->sublex_info; /* XXX not quite right */
12385     parser->linestr     = sv_dup_inc(proto->linestr, param);
12386     parser->expect      = proto->expect;
12387     parser->copline     = proto->copline;
12388     parser->last_lop_op = proto->last_lop_op;
12389     parser->lex_state   = proto->lex_state;
12390     parser->rsfp        = fp_dup(proto->rsfp, '<', param);
12391     /* rsfp_filters entries have fake IoDIRP() */
12392     parser->rsfp_filters= av_dup_inc(proto->rsfp_filters, param);
12393     parser->in_my       = proto->in_my;
12394     parser->in_my_stash = hv_dup(proto->in_my_stash, param);
12395     parser->error_count = proto->error_count;
12396
12397
12398     parser->linestr     = sv_dup_inc(proto->linestr, param);
12399
12400     {
12401         char * const ols = SvPVX(proto->linestr);
12402         char * const ls  = SvPVX(parser->linestr);
12403
12404         parser->bufptr      = ls + (proto->bufptr >= ols ?
12405                                     proto->bufptr -  ols : 0);
12406         parser->oldbufptr   = ls + (proto->oldbufptr >= ols ?
12407                                     proto->oldbufptr -  ols : 0);
12408         parser->oldoldbufptr= ls + (proto->oldoldbufptr >= ols ?
12409                                     proto->oldoldbufptr -  ols : 0);
12410         parser->linestart   = ls + (proto->linestart >= ols ?
12411                                     proto->linestart -  ols : 0);
12412         parser->last_uni    = ls + (proto->last_uni >= ols ?
12413                                     proto->last_uni -  ols : 0);
12414         parser->last_lop    = ls + (proto->last_lop >= ols ?
12415                                     proto->last_lop -  ols : 0);
12416
12417         parser->bufend      = ls + SvCUR(parser->linestr);
12418     }
12419
12420     Copy(proto->tokenbuf, parser->tokenbuf, 256, char);
12421
12422
12423     Copy(proto->nextval, parser->nextval, 5, YYSTYPE);
12424     Copy(proto->nexttype, parser->nexttype, 5,  I32);
12425     parser->nexttoke    = proto->nexttoke;
12426
12427     /* XXX should clone saved_curcop here, but we aren't passed
12428      * proto_perl; so do it in perl_clone_using instead */
12429
12430     return parser;
12431 }
12432
12433
12434 /* duplicate a file handle */
12435
12436 PerlIO *
12437 Perl_fp_dup(pTHX_ PerlIO *const fp, const char type, CLONE_PARAMS *const param)
12438 {
12439     PerlIO *ret;
12440
12441     PERL_ARGS_ASSERT_FP_DUP;
12442     PERL_UNUSED_ARG(type);
12443
12444     if (!fp)
12445         return (PerlIO*)NULL;
12446
12447     /* look for it in the table first */
12448     ret = (PerlIO*)ptr_table_fetch(PL_ptr_table, fp);
12449     if (ret)
12450         return ret;
12451
12452     /* create anew and remember what it is */
12453     ret = PerlIO_fdupopen(aTHX_ fp, param, PERLIO_DUP_CLONE);
12454     ptr_table_store(PL_ptr_table, fp, ret);
12455     return ret;
12456 }
12457
12458 /* duplicate a directory handle */
12459
12460 DIR *
12461 Perl_dirp_dup(pTHX_ DIR *const dp, CLONE_PARAMS *const param)
12462 {
12463     DIR *ret;
12464
12465 #if defined(HAS_FCHDIR) && defined(HAS_TELLDIR) && defined(HAS_SEEKDIR)
12466     DIR *pwd;
12467     const Direntry_t *dirent;
12468     char smallbuf[256];
12469     char *name = NULL;
12470     STRLEN len = 0;
12471     long pos;
12472 #endif
12473
12474     PERL_UNUSED_CONTEXT;
12475     PERL_ARGS_ASSERT_DIRP_DUP;
12476
12477     if (!dp)
12478         return (DIR*)NULL;
12479
12480     /* look for it in the table first */
12481     ret = (DIR*)ptr_table_fetch(PL_ptr_table, dp);
12482     if (ret)
12483         return ret;
12484
12485 #if defined(HAS_FCHDIR) && defined(HAS_TELLDIR) && defined(HAS_SEEKDIR)
12486
12487     PERL_UNUSED_ARG(param);
12488
12489     /* create anew */
12490
12491     /* open the current directory (so we can switch back) */
12492     if (!(pwd = PerlDir_open("."))) return (DIR *)NULL;
12493
12494     /* chdir to our dir handle and open the present working directory */
12495     if (fchdir(my_dirfd(dp)) < 0 || !(ret = PerlDir_open("."))) {
12496         PerlDir_close(pwd);
12497         return (DIR *)NULL;
12498     }
12499     /* Now we should have two dir handles pointing to the same dir. */
12500
12501     /* Be nice to the calling code and chdir back to where we were. */
12502     /* XXX If this fails, then what? */
12503     PERL_UNUSED_RESULT(fchdir(my_dirfd(pwd)));
12504
12505     /* We have no need of the pwd handle any more. */
12506     PerlDir_close(pwd);
12507
12508 #ifdef DIRNAMLEN
12509 # define d_namlen(d) (d)->d_namlen
12510 #else
12511 # define d_namlen(d) strlen((d)->d_name)
12512 #endif
12513     /* Iterate once through dp, to get the file name at the current posi-
12514        tion. Then step back. */
12515     pos = PerlDir_tell(dp);
12516     if ((dirent = PerlDir_read(dp))) {
12517         len = d_namlen(dirent);
12518         if (len <= sizeof smallbuf) name = smallbuf;
12519         else Newx(name, len, char);
12520         Move(dirent->d_name, name, len, char);
12521     }
12522     PerlDir_seek(dp, pos);
12523
12524     /* Iterate through the new dir handle, till we find a file with the
12525        right name. */
12526     if (!dirent) /* just before the end */
12527         for(;;) {
12528             pos = PerlDir_tell(ret);
12529             if (PerlDir_read(ret)) continue; /* not there yet */
12530             PerlDir_seek(ret, pos); /* step back */
12531             break;
12532         }
12533     else {
12534         const long pos0 = PerlDir_tell(ret);
12535         for(;;) {
12536             pos = PerlDir_tell(ret);
12537             if ((dirent = PerlDir_read(ret))) {
12538                 if (len == (STRLEN)d_namlen(dirent)
12539                     && memEQ(name, dirent->d_name, len)) {
12540                     /* found it */
12541                     PerlDir_seek(ret, pos); /* step back */
12542                     break;
12543                 }
12544                 /* else we are not there yet; keep iterating */
12545             }
12546             else { /* This is not meant to happen. The best we can do is
12547                       reset the iterator to the beginning. */
12548                 PerlDir_seek(ret, pos0);
12549                 break;
12550             }
12551         }
12552     }
12553 #undef d_namlen
12554
12555     if (name && name != smallbuf)
12556         Safefree(name);
12557 #endif
12558
12559 #ifdef WIN32
12560     ret = win32_dirp_dup(dp, param);
12561 #endif
12562
12563     /* pop it in the pointer table */
12564     if (ret)
12565         ptr_table_store(PL_ptr_table, dp, ret);
12566
12567     return ret;
12568 }
12569
12570 /* duplicate a typeglob */
12571
12572 GP *
12573 Perl_gp_dup(pTHX_ GP *const gp, CLONE_PARAMS *const param)
12574 {
12575     GP *ret;
12576
12577     PERL_ARGS_ASSERT_GP_DUP;
12578
12579     if (!gp)
12580         return (GP*)NULL;
12581     /* look for it in the table first */
12582     ret = (GP*)ptr_table_fetch(PL_ptr_table, gp);
12583     if (ret)
12584         return ret;
12585
12586     /* create anew and remember what it is */
12587     Newxz(ret, 1, GP);
12588     ptr_table_store(PL_ptr_table, gp, ret);
12589
12590     /* clone */
12591     /* ret->gp_refcnt must be 0 before any other dups are called. We're relying
12592        on Newxz() to do this for us.  */
12593     ret->gp_sv          = sv_dup_inc(gp->gp_sv, param);
12594     ret->gp_io          = io_dup_inc(gp->gp_io, param);
12595     ret->gp_form        = cv_dup_inc(gp->gp_form, param);
12596     ret->gp_av          = av_dup_inc(gp->gp_av, param);
12597     ret->gp_hv          = hv_dup_inc(gp->gp_hv, param);
12598     ret->gp_egv = gv_dup(gp->gp_egv, param);/* GvEGV is not refcounted */
12599     ret->gp_cv          = cv_dup_inc(gp->gp_cv, param);
12600     ret->gp_cvgen       = gp->gp_cvgen;
12601     ret->gp_line        = gp->gp_line;
12602     ret->gp_file_hek    = hek_dup(gp->gp_file_hek, param);
12603     return ret;
12604 }
12605
12606 /* duplicate a chain of magic */
12607
12608 MAGIC *
12609 Perl_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *const param)
12610 {
12611     MAGIC *mgret = NULL;
12612     MAGIC **mgprev_p = &mgret;
12613
12614     PERL_ARGS_ASSERT_MG_DUP;
12615
12616     for (; mg; mg = mg->mg_moremagic) {
12617         MAGIC *nmg;
12618
12619         if ((param->flags & CLONEf_JOIN_IN)
12620                 && mg->mg_type == PERL_MAGIC_backref)
12621             /* when joining, we let the individual SVs add themselves to
12622              * backref as needed. */
12623             continue;
12624
12625         Newx(nmg, 1, MAGIC);
12626         *mgprev_p = nmg;
12627         mgprev_p = &(nmg->mg_moremagic);
12628
12629         /* There was a comment "XXX copy dynamic vtable?" but as we don't have
12630            dynamic vtables, I'm not sure why Sarathy wrote it. The comment dates
12631            from the original commit adding Perl_mg_dup() - revision 4538.
12632            Similarly there is the annotation "XXX random ptr?" next to the
12633            assignment to nmg->mg_ptr.  */
12634         *nmg = *mg;
12635
12636         /* FIXME for plugins
12637         if (nmg->mg_type == PERL_MAGIC_qr) {
12638             nmg->mg_obj = MUTABLE_SV(CALLREGDUPE((REGEXP*)nmg->mg_obj, param));
12639         }
12640         else
12641         */
12642         nmg->mg_obj = (nmg->mg_flags & MGf_REFCOUNTED)
12643                           ? nmg->mg_type == PERL_MAGIC_backref
12644                                 /* The backref AV has its reference
12645                                  * count deliberately bumped by 1 */
12646                                 ? SvREFCNT_inc(av_dup_inc((const AV *)
12647                                                     nmg->mg_obj, param))
12648                                 : sv_dup_inc(nmg->mg_obj, param)
12649                           : sv_dup(nmg->mg_obj, param);
12650
12651         if (nmg->mg_ptr && nmg->mg_type != PERL_MAGIC_regex_global) {
12652             if (nmg->mg_len > 0) {
12653                 nmg->mg_ptr     = SAVEPVN(nmg->mg_ptr, nmg->mg_len);
12654                 if (nmg->mg_type == PERL_MAGIC_overload_table &&
12655                         AMT_AMAGIC((AMT*)nmg->mg_ptr))
12656                 {
12657                     AMT * const namtp = (AMT*)nmg->mg_ptr;
12658                     sv_dup_inc_multiple((SV**)(namtp->table),
12659                                         (SV**)(namtp->table), NofAMmeth, param);
12660                 }
12661             }
12662             else if (nmg->mg_len == HEf_SVKEY)
12663                 nmg->mg_ptr = (char*)sv_dup_inc((const SV *)nmg->mg_ptr, param);
12664         }
12665         if ((nmg->mg_flags & MGf_DUP) && nmg->mg_virtual && nmg->mg_virtual->svt_dup) {
12666             nmg->mg_virtual->svt_dup(aTHX_ nmg, param);
12667         }
12668     }
12669     return mgret;
12670 }
12671
12672 #endif /* USE_ITHREADS */
12673
12674 struct ptr_tbl_arena {
12675     struct ptr_tbl_arena *next;
12676     struct ptr_tbl_ent array[1023/3]; /* as ptr_tbl_ent has 3 pointers.  */
12677 };
12678
12679 /* create a new pointer-mapping table */
12680
12681 PTR_TBL_t *
12682 Perl_ptr_table_new(pTHX)
12683 {
12684     PTR_TBL_t *tbl;
12685     PERL_UNUSED_CONTEXT;
12686
12687     Newx(tbl, 1, PTR_TBL_t);
12688     tbl->tbl_max        = 511;
12689     tbl->tbl_items      = 0;
12690     tbl->tbl_arena      = NULL;
12691     tbl->tbl_arena_next = NULL;
12692     tbl->tbl_arena_end  = NULL;
12693     Newxz(tbl->tbl_ary, tbl->tbl_max + 1, PTR_TBL_ENT_t*);
12694     return tbl;
12695 }
12696
12697 #define PTR_TABLE_HASH(ptr) \
12698   ((PTR2UV(ptr) >> 3) ^ (PTR2UV(ptr) >> (3 + 7)) ^ (PTR2UV(ptr) >> (3 + 17)))
12699
12700 /* map an existing pointer using a table */
12701
12702 STATIC PTR_TBL_ENT_t *
12703 S_ptr_table_find(PTR_TBL_t *const tbl, const void *const sv)
12704 {
12705     PTR_TBL_ENT_t *tblent;
12706     const UV hash = PTR_TABLE_HASH(sv);
12707
12708     PERL_ARGS_ASSERT_PTR_TABLE_FIND;
12709
12710     tblent = tbl->tbl_ary[hash & tbl->tbl_max];
12711     for (; tblent; tblent = tblent->next) {
12712         if (tblent->oldval == sv)
12713             return tblent;
12714     }
12715     return NULL;
12716 }
12717
12718 void *
12719 Perl_ptr_table_fetch(pTHX_ PTR_TBL_t *const tbl, const void *const sv)
12720 {
12721     PTR_TBL_ENT_t const *const tblent = ptr_table_find(tbl, sv);
12722
12723     PERL_ARGS_ASSERT_PTR_TABLE_FETCH;
12724     PERL_UNUSED_CONTEXT;
12725
12726     return tblent ? tblent->newval : NULL;
12727 }
12728
12729 /* add a new entry to a pointer-mapping table 'tbl'.  In hash terms, 'oldsv' is
12730  * the key; 'newsv' is the value.  The names "old" and "new" are specific to
12731  * the core's typical use of ptr_tables in thread cloning. */
12732
12733 void
12734 Perl_ptr_table_store(pTHX_ PTR_TBL_t *const tbl, const void *const oldsv, void *const newsv)
12735 {
12736     PTR_TBL_ENT_t *tblent = ptr_table_find(tbl, oldsv);
12737
12738     PERL_ARGS_ASSERT_PTR_TABLE_STORE;
12739     PERL_UNUSED_CONTEXT;
12740
12741     if (tblent) {
12742         tblent->newval = newsv;
12743     } else {
12744         const UV entry = PTR_TABLE_HASH(oldsv) & tbl->tbl_max;
12745
12746         if (tbl->tbl_arena_next == tbl->tbl_arena_end) {
12747             struct ptr_tbl_arena *new_arena;
12748
12749             Newx(new_arena, 1, struct ptr_tbl_arena);
12750             new_arena->next = tbl->tbl_arena;
12751             tbl->tbl_arena = new_arena;
12752             tbl->tbl_arena_next = new_arena->array;
12753             tbl->tbl_arena_end = C_ARRAY_END(new_arena->array);
12754         }
12755
12756         tblent = tbl->tbl_arena_next++;
12757
12758         tblent->oldval = oldsv;
12759         tblent->newval = newsv;
12760         tblent->next = tbl->tbl_ary[entry];
12761         tbl->tbl_ary[entry] = tblent;
12762         tbl->tbl_items++;
12763         if (tblent->next && tbl->tbl_items > tbl->tbl_max)
12764             ptr_table_split(tbl);
12765     }
12766 }
12767
12768 /* double the hash bucket size of an existing ptr table */
12769
12770 void
12771 Perl_ptr_table_split(pTHX_ PTR_TBL_t *const tbl)
12772 {
12773     PTR_TBL_ENT_t **ary = tbl->tbl_ary;
12774     const UV oldsize = tbl->tbl_max + 1;
12775     UV newsize = oldsize * 2;
12776     UV i;
12777
12778     PERL_ARGS_ASSERT_PTR_TABLE_SPLIT;
12779     PERL_UNUSED_CONTEXT;
12780
12781     Renew(ary, newsize, PTR_TBL_ENT_t*);
12782     Zero(&ary[oldsize], newsize-oldsize, PTR_TBL_ENT_t*);
12783     tbl->tbl_max = --newsize;
12784     tbl->tbl_ary = ary;
12785     for (i=0; i < oldsize; i++, ary++) {
12786         PTR_TBL_ENT_t **entp = ary;
12787         PTR_TBL_ENT_t *ent = *ary;
12788         PTR_TBL_ENT_t **curentp;
12789         if (!ent)
12790             continue;
12791         curentp = ary + oldsize;
12792         do {
12793             if ((newsize & PTR_TABLE_HASH(ent->oldval)) != i) {
12794                 *entp = ent->next;
12795                 ent->next = *curentp;
12796                 *curentp = ent;
12797             }
12798             else
12799                 entp = &ent->next;
12800             ent = *entp;
12801         } while (ent);
12802     }
12803 }
12804
12805 /* remove all the entries from a ptr table */
12806 /* Deprecated - will be removed post 5.14 */
12807
12808 void
12809 Perl_ptr_table_clear(pTHX_ PTR_TBL_t *const tbl)
12810 {
12811     PERL_UNUSED_CONTEXT;
12812     if (tbl && tbl->tbl_items) {
12813         struct ptr_tbl_arena *arena = tbl->tbl_arena;
12814
12815         Zero(tbl->tbl_ary, tbl->tbl_max + 1, struct ptr_tbl_ent **);
12816
12817         while (arena) {
12818             struct ptr_tbl_arena *next = arena->next;
12819
12820             Safefree(arena);
12821             arena = next;
12822         };
12823
12824         tbl->tbl_items = 0;
12825         tbl->tbl_arena = NULL;
12826         tbl->tbl_arena_next = NULL;
12827         tbl->tbl_arena_end = NULL;
12828     }
12829 }
12830
12831 /* clear and free a ptr table */
12832
12833 void
12834 Perl_ptr_table_free(pTHX_ PTR_TBL_t *const tbl)
12835 {
12836     struct ptr_tbl_arena *arena;
12837
12838     PERL_UNUSED_CONTEXT;
12839
12840     if (!tbl) {
12841         return;
12842     }
12843
12844     arena = tbl->tbl_arena;
12845
12846     while (arena) {
12847         struct ptr_tbl_arena *next = arena->next;
12848
12849         Safefree(arena);
12850         arena = next;
12851     }
12852
12853     Safefree(tbl->tbl_ary);
12854     Safefree(tbl);
12855 }
12856
12857 #if defined(USE_ITHREADS)
12858
12859 void
12860 Perl_rvpv_dup(pTHX_ SV *const dstr, const SV *const sstr, CLONE_PARAMS *const param)
12861 {
12862     PERL_ARGS_ASSERT_RVPV_DUP;
12863
12864     assert(!isREGEXP(sstr));
12865     if (SvROK(sstr)) {
12866         if (SvWEAKREF(sstr)) {
12867             SvRV_set(dstr, sv_dup(SvRV_const(sstr), param));
12868             if (param->flags & CLONEf_JOIN_IN) {
12869                 /* if joining, we add any back references individually rather
12870                  * than copying the whole backref array */
12871                 Perl_sv_add_backref(aTHX_ SvRV(dstr), dstr);
12872             }
12873         }
12874         else
12875             SvRV_set(dstr, sv_dup_inc(SvRV_const(sstr), param));
12876     }
12877     else if (SvPVX_const(sstr)) {
12878         /* Has something there */
12879         if (SvLEN(sstr)) {
12880             /* Normal PV - clone whole allocated space */
12881             SvPV_set(dstr, SAVEPVN(SvPVX_const(sstr), SvLEN(sstr)-1));
12882             /* sstr may not be that normal, but actually copy on write.
12883                But we are a true, independent SV, so:  */
12884             SvIsCOW_off(dstr);
12885         }
12886         else {
12887             /* Special case - not normally malloced for some reason */
12888             if (isGV_with_GP(sstr)) {
12889                 /* Don't need to do anything here.  */
12890             }
12891             else if ((SvIsCOW(sstr))) {
12892                 /* A "shared" PV - clone it as "shared" PV */
12893                 SvPV_set(dstr,
12894                          HEK_KEY(hek_dup(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)),
12895                                          param)));
12896             }
12897             else {
12898                 /* Some other special case - random pointer */
12899                 SvPV_set(dstr, (char *) SvPVX_const(sstr));             
12900             }
12901         }
12902     }
12903     else {
12904         /* Copy the NULL */
12905         SvPV_set(dstr, NULL);
12906     }
12907 }
12908
12909 /* duplicate a list of SVs. source and dest may point to the same memory.  */
12910 static SV **
12911 S_sv_dup_inc_multiple(pTHX_ SV *const *source, SV **dest,
12912                       SSize_t items, CLONE_PARAMS *const param)
12913 {
12914     PERL_ARGS_ASSERT_SV_DUP_INC_MULTIPLE;
12915
12916     while (items-- > 0) {
12917         *dest++ = sv_dup_inc(*source++, param);
12918     }
12919
12920     return dest;
12921 }
12922
12923 /* duplicate an SV of any type (including AV, HV etc) */
12924
12925 static SV *
12926 S_sv_dup_common(pTHX_ const SV *const sstr, CLONE_PARAMS *const param)
12927 {
12928     dVAR;
12929     SV *dstr;
12930
12931     PERL_ARGS_ASSERT_SV_DUP_COMMON;
12932
12933     if (SvTYPE(sstr) == (svtype)SVTYPEMASK) {
12934 #ifdef DEBUG_LEAKING_SCALARS_ABORT
12935         abort();
12936 #endif
12937         return NULL;
12938     }
12939     /* look for it in the table first */
12940     dstr = MUTABLE_SV(ptr_table_fetch(PL_ptr_table, sstr));
12941     if (dstr)
12942         return dstr;
12943
12944     if(param->flags & CLONEf_JOIN_IN) {
12945         /** We are joining here so we don't want do clone
12946             something that is bad **/
12947         if (SvTYPE(sstr) == SVt_PVHV) {
12948             const HEK * const hvname = HvNAME_HEK(sstr);
12949             if (hvname) {
12950                 /** don't clone stashes if they already exist **/
12951                 dstr = MUTABLE_SV(gv_stashpvn(HEK_KEY(hvname), HEK_LEN(hvname),
12952                                                 HEK_UTF8(hvname) ? SVf_UTF8 : 0));
12953                 ptr_table_store(PL_ptr_table, sstr, dstr);
12954                 return dstr;
12955             }
12956         }
12957         else if (SvTYPE(sstr) == SVt_PVGV && !SvFAKE(sstr)) {
12958             HV *stash = GvSTASH(sstr);
12959             const HEK * hvname;
12960             if (stash && (hvname = HvNAME_HEK(stash))) {
12961                 /** don't clone GVs if they already exist **/
12962                 SV **svp;
12963                 stash = gv_stashpvn(HEK_KEY(hvname), HEK_LEN(hvname),
12964                                     HEK_UTF8(hvname) ? SVf_UTF8 : 0);
12965                 svp = hv_fetch(
12966                         stash, GvNAME(sstr),
12967                         GvNAMEUTF8(sstr)
12968                             ? -GvNAMELEN(sstr)
12969                             :  GvNAMELEN(sstr),
12970                         0
12971                       );
12972                 if (svp && *svp && SvTYPE(*svp) == SVt_PVGV) {
12973                     ptr_table_store(PL_ptr_table, sstr, *svp);
12974                     return *svp;
12975                 }
12976             }
12977         }
12978     }
12979
12980     /* create anew and remember what it is */
12981     new_SV(dstr);
12982
12983 #ifdef DEBUG_LEAKING_SCALARS
12984     dstr->sv_debug_optype = sstr->sv_debug_optype;
12985     dstr->sv_debug_line = sstr->sv_debug_line;
12986     dstr->sv_debug_inpad = sstr->sv_debug_inpad;
12987     dstr->sv_debug_parent = (SV*)sstr;
12988     FREE_SV_DEBUG_FILE(dstr);
12989     dstr->sv_debug_file = savesharedpv(sstr->sv_debug_file);
12990 #endif
12991
12992     ptr_table_store(PL_ptr_table, sstr, dstr);
12993
12994     /* clone */
12995     SvFLAGS(dstr)       = SvFLAGS(sstr);
12996     SvFLAGS(dstr)       &= ~SVf_OOK;            /* don't propagate OOK hack */
12997     SvREFCNT(dstr)      = 0;                    /* must be before any other dups! */
12998
12999 #ifdef DEBUGGING
13000     if (SvANY(sstr) && PL_watch_pvx && SvPVX_const(sstr) == PL_watch_pvx)
13001         PerlIO_printf(Perl_debug_log, "watch at %p hit, found string \"%s\"\n",
13002                       (void*)PL_watch_pvx, SvPVX_const(sstr));
13003 #endif
13004
13005     /* don't clone objects whose class has asked us not to */
13006     if (SvOBJECT(sstr) && ! (SvFLAGS(SvSTASH(sstr)) & SVphv_CLONEABLE)) {
13007         SvFLAGS(dstr) = 0;
13008         return dstr;
13009     }
13010
13011     switch (SvTYPE(sstr)) {
13012     case SVt_NULL:
13013         SvANY(dstr)     = NULL;
13014         break;
13015     case SVt_IV:
13016         SvANY(dstr)     = (XPVIV*)((char*)&(dstr->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
13017         if(SvROK(sstr)) {
13018             Perl_rvpv_dup(aTHX_ dstr, sstr, param);
13019         } else {
13020             SvIV_set(dstr, SvIVX(sstr));
13021         }
13022         break;
13023     case SVt_NV:
13024         SvANY(dstr)     = new_XNV();
13025         SvNV_set(dstr, SvNVX(sstr));
13026         break;
13027     default:
13028         {
13029             /* These are all the types that need complex bodies allocating.  */
13030             void *new_body;
13031             const svtype sv_type = SvTYPE(sstr);
13032             const struct body_details *const sv_type_details
13033                 = bodies_by_type + sv_type;
13034
13035             switch (sv_type) {
13036             default:
13037                 Perl_croak(aTHX_ "Bizarre SvTYPE [%" IVdf "]", (IV)SvTYPE(sstr));
13038                 break;
13039
13040             case SVt_PVGV:
13041             case SVt_PVIO:
13042             case SVt_PVFM:
13043             case SVt_PVHV:
13044             case SVt_PVAV:
13045             case SVt_PVCV:
13046             case SVt_PVLV:
13047             case SVt_REGEXP:
13048             case SVt_PVMG:
13049             case SVt_PVNV:
13050             case SVt_PVIV:
13051             case SVt_INVLIST:
13052             case SVt_PV:
13053                 assert(sv_type_details->body_size);
13054                 if (sv_type_details->arena) {
13055                     new_body_inline(new_body, sv_type);
13056                     new_body
13057                         = (void*)((char*)new_body - sv_type_details->offset);
13058                 } else {
13059                     new_body = new_NOARENA(sv_type_details);
13060                 }
13061             }
13062             assert(new_body);
13063             SvANY(dstr) = new_body;
13064
13065 #ifndef PURIFY
13066             Copy(((char*)SvANY(sstr)) + sv_type_details->offset,
13067                  ((char*)SvANY(dstr)) + sv_type_details->offset,
13068                  sv_type_details->copy, char);
13069 #else
13070             Copy(((char*)SvANY(sstr)),
13071                  ((char*)SvANY(dstr)),
13072                  sv_type_details->body_size + sv_type_details->offset, char);
13073 #endif
13074
13075             if (sv_type != SVt_PVAV && sv_type != SVt_PVHV
13076                 && !isGV_with_GP(dstr)
13077                 && !isREGEXP(dstr)
13078                 && !(sv_type == SVt_PVIO && !(IoFLAGS(dstr) & IOf_FAKE_DIRP)))
13079                 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
13080
13081             /* The Copy above means that all the source (unduplicated) pointers
13082                are now in the destination.  We can check the flags and the
13083                pointers in either, but it's possible that there's less cache
13084                missing by always going for the destination.
13085                FIXME - instrument and check that assumption  */
13086             if (sv_type >= SVt_PVMG) {
13087                 if ((sv_type == SVt_PVMG) && SvPAD_OUR(dstr)) {
13088                     SvOURSTASH_set(dstr, hv_dup_inc(SvOURSTASH(dstr), param));
13089                 } else if (sv_type == SVt_PVAV && AvPAD_NAMELIST(dstr)) {
13090                     NOOP;
13091                 } else if (SvMAGIC(dstr))
13092                     SvMAGIC_set(dstr, mg_dup(SvMAGIC(dstr), param));
13093                 if (SvOBJECT(dstr) && SvSTASH(dstr))
13094                     SvSTASH_set(dstr, hv_dup_inc(SvSTASH(dstr), param));
13095                 else SvSTASH_set(dstr, 0); /* don't copy DESTROY cache */
13096             }
13097
13098             /* The cast silences a GCC warning about unhandled types.  */
13099             switch ((int)sv_type) {
13100             case SVt_PV:
13101                 break;
13102             case SVt_PVIV:
13103                 break;
13104             case SVt_PVNV:
13105                 break;
13106             case SVt_PVMG:
13107                 break;
13108             case SVt_REGEXP:
13109               duprex:
13110                 /* FIXME for plugins */
13111                 dstr->sv_u.svu_rx = ((REGEXP *)dstr)->sv_any;
13112                 re_dup_guts((REGEXP*) sstr, (REGEXP*) dstr, param);
13113                 break;
13114             case SVt_PVLV:
13115                 /* XXX LvTARGOFF sometimes holds PMOP* when DEBUGGING */
13116                 if (LvTYPE(dstr) == 't') /* for tie: unrefcnted fake (SV**) */
13117                     LvTARG(dstr) = dstr;
13118                 else if (LvTYPE(dstr) == 'T') /* for tie: fake HE */
13119                     LvTARG(dstr) = MUTABLE_SV(he_dup((HE*)LvTARG(dstr), 0, param));
13120                 else
13121                     LvTARG(dstr) = sv_dup_inc(LvTARG(dstr), param);
13122                 if (isREGEXP(sstr)) goto duprex;
13123             case SVt_PVGV:
13124                 /* non-GP case already handled above */
13125                 if(isGV_with_GP(sstr)) {
13126                     GvNAME_HEK(dstr) = hek_dup(GvNAME_HEK(dstr), param);
13127                     /* Don't call sv_add_backref here as it's going to be
13128                        created as part of the magic cloning of the symbol
13129                        table--unless this is during a join and the stash
13130                        is not actually being cloned.  */
13131                     /* Danger Will Robinson - GvGP(dstr) isn't initialised
13132                        at the point of this comment.  */
13133                     GvSTASH(dstr) = hv_dup(GvSTASH(dstr), param);
13134                     if (param->flags & CLONEf_JOIN_IN)
13135                         Perl_sv_add_backref(aTHX_ MUTABLE_SV(GvSTASH(dstr)), dstr);
13136                     GvGP_set(dstr, gp_dup(GvGP(sstr), param));
13137                     (void)GpREFCNT_inc(GvGP(dstr));
13138                 }
13139                 break;
13140             case SVt_PVIO:
13141                 /* PL_parser->rsfp_filters entries have fake IoDIRP() */
13142                 if(IoFLAGS(dstr) & IOf_FAKE_DIRP) {
13143                     /* I have no idea why fake dirp (rsfps)
13144                        should be treated differently but otherwise
13145                        we end up with leaks -- sky*/
13146                     IoTOP_GV(dstr)      = gv_dup_inc(IoTOP_GV(dstr), param);
13147                     IoFMT_GV(dstr)      = gv_dup_inc(IoFMT_GV(dstr), param);
13148                     IoBOTTOM_GV(dstr)   = gv_dup_inc(IoBOTTOM_GV(dstr), param);
13149                 } else {
13150                     IoTOP_GV(dstr)      = gv_dup(IoTOP_GV(dstr), param);
13151                     IoFMT_GV(dstr)      = gv_dup(IoFMT_GV(dstr), param);
13152                     IoBOTTOM_GV(dstr)   = gv_dup(IoBOTTOM_GV(dstr), param);
13153                     if (IoDIRP(dstr)) {
13154                         IoDIRP(dstr)    = dirp_dup(IoDIRP(dstr), param);
13155                     } else {
13156                         NOOP;
13157                         /* IoDIRP(dstr) is already a copy of IoDIRP(sstr)  */
13158                     }
13159                     IoIFP(dstr) = fp_dup(IoIFP(sstr), IoTYPE(dstr), param);
13160                 }
13161                 if (IoOFP(dstr) == IoIFP(sstr))
13162                     IoOFP(dstr) = IoIFP(dstr);
13163                 else
13164                     IoOFP(dstr) = fp_dup(IoOFP(dstr), IoTYPE(dstr), param);
13165                 IoTOP_NAME(dstr)        = SAVEPV(IoTOP_NAME(dstr));
13166                 IoFMT_NAME(dstr)        = SAVEPV(IoFMT_NAME(dstr));
13167                 IoBOTTOM_NAME(dstr)     = SAVEPV(IoBOTTOM_NAME(dstr));
13168                 break;
13169             case SVt_PVAV:
13170                 /* avoid cloning an empty array */
13171                 if (AvARRAY((const AV *)sstr) && AvFILLp((const AV *)sstr) >= 0) {
13172                     SV **dst_ary, **src_ary;
13173                     SSize_t items = AvFILLp((const AV *)sstr) + 1;
13174
13175                     src_ary = AvARRAY((const AV *)sstr);
13176                     Newxz(dst_ary, AvMAX((const AV *)sstr)+1, SV*);
13177                     ptr_table_store(PL_ptr_table, src_ary, dst_ary);
13178                     AvARRAY(MUTABLE_AV(dstr)) = dst_ary;
13179                     AvALLOC((const AV *)dstr) = dst_ary;
13180                     if (AvREAL((const AV *)sstr)) {
13181                         dst_ary = sv_dup_inc_multiple(src_ary, dst_ary, items,
13182                                                       param);
13183                     }
13184                     else {
13185                         while (items-- > 0)
13186                             *dst_ary++ = sv_dup(*src_ary++, param);
13187                     }
13188                     items = AvMAX((const AV *)sstr) - AvFILLp((const AV *)sstr);
13189                     while (items-- > 0) {
13190                         *dst_ary++ = &PL_sv_undef;
13191                     }
13192                 }
13193                 else {
13194                     AvARRAY(MUTABLE_AV(dstr))   = NULL;
13195                     AvALLOC((const AV *)dstr)   = (SV**)NULL;
13196                     AvMAX(  (const AV *)dstr)   = -1;
13197                     AvFILLp((const AV *)dstr)   = -1;
13198                 }
13199                 break;
13200             case SVt_PVHV:
13201                 if (HvARRAY((const HV *)sstr)) {
13202                     STRLEN i = 0;
13203                     const bool sharekeys = !!HvSHAREKEYS(sstr);
13204                     XPVHV * const dxhv = (XPVHV*)SvANY(dstr);
13205                     XPVHV * const sxhv = (XPVHV*)SvANY(sstr);
13206                     char *darray;
13207                     Newx(darray, PERL_HV_ARRAY_ALLOC_BYTES(dxhv->xhv_max+1)
13208                         + (SvOOK(sstr) ? sizeof(struct xpvhv_aux) : 0),
13209                         char);
13210                     HvARRAY(dstr) = (HE**)darray;
13211                     while (i <= sxhv->xhv_max) {
13212                         const HE * const source = HvARRAY(sstr)[i];
13213                         HvARRAY(dstr)[i] = source
13214                             ? he_dup(source, sharekeys, param) : 0;
13215                         ++i;
13216                     }
13217                     if (SvOOK(sstr)) {
13218                         const struct xpvhv_aux * const saux = HvAUX(sstr);
13219                         struct xpvhv_aux * const daux = HvAUX(dstr);
13220                         /* This flag isn't copied.  */
13221                         SvOOK_on(dstr);
13222
13223                         if (saux->xhv_name_count) {
13224                             HEK ** const sname = saux->xhv_name_u.xhvnameu_names;
13225                             const I32 count
13226                              = saux->xhv_name_count < 0
13227                                 ? -saux->xhv_name_count
13228                                 :  saux->xhv_name_count;
13229                             HEK **shekp = sname + count;
13230                             HEK **dhekp;
13231                             Newx(daux->xhv_name_u.xhvnameu_names, count, HEK *);
13232                             dhekp = daux->xhv_name_u.xhvnameu_names + count;
13233                             while (shekp-- > sname) {
13234                                 dhekp--;
13235                                 *dhekp = hek_dup(*shekp, param);
13236                             }
13237                         }
13238                         else {
13239                             daux->xhv_name_u.xhvnameu_name
13240                                 = hek_dup(saux->xhv_name_u.xhvnameu_name,
13241                                           param);
13242                         }
13243                         daux->xhv_name_count = saux->xhv_name_count;
13244
13245                         daux->xhv_fill_lazy = saux->xhv_fill_lazy;
13246                         daux->xhv_aux_flags = saux->xhv_aux_flags;
13247 #ifdef PERL_HASH_RANDOMIZE_KEYS
13248                         daux->xhv_rand = saux->xhv_rand;
13249                         daux->xhv_last_rand = saux->xhv_last_rand;
13250 #endif
13251                         daux->xhv_riter = saux->xhv_riter;
13252                         daux->xhv_eiter = saux->xhv_eiter
13253                             ? he_dup(saux->xhv_eiter,
13254                                         cBOOL(HvSHAREKEYS(sstr)), param) : 0;
13255                         /* backref array needs refcnt=2; see sv_add_backref */
13256                         daux->xhv_backreferences =
13257                             (param->flags & CLONEf_JOIN_IN)
13258                                 /* when joining, we let the individual GVs and
13259                                  * CVs add themselves to backref as
13260                                  * needed. This avoids pulling in stuff
13261                                  * that isn't required, and simplifies the
13262                                  * case where stashes aren't cloned back
13263                                  * if they already exist in the parent
13264                                  * thread */
13265                             ? NULL
13266                             : saux->xhv_backreferences
13267                                 ? (SvTYPE(saux->xhv_backreferences) == SVt_PVAV)
13268                                     ? MUTABLE_AV(SvREFCNT_inc(
13269                                           sv_dup_inc((const SV *)
13270                                             saux->xhv_backreferences, param)))
13271                                     : MUTABLE_AV(sv_dup((const SV *)
13272                                             saux->xhv_backreferences, param))
13273                                 : 0;
13274
13275                         daux->xhv_mro_meta = saux->xhv_mro_meta
13276                             ? mro_meta_dup(saux->xhv_mro_meta, param)
13277                             : 0;
13278
13279                         /* Record stashes for possible cloning in Perl_clone(). */
13280                         if (HvNAME(sstr))
13281                             av_push(param->stashes, dstr);
13282                     }
13283                 }
13284                 else
13285                     HvARRAY(MUTABLE_HV(dstr)) = NULL;
13286                 break;
13287             case SVt_PVCV:
13288                 if (!(param->flags & CLONEf_COPY_STACKS)) {
13289                     CvDEPTH(dstr) = 0;
13290                 }
13291                 /* FALLTHROUGH */
13292             case SVt_PVFM:
13293                 /* NOTE: not refcounted */
13294                 SvANY(MUTABLE_CV(dstr))->xcv_stash =
13295                     hv_dup(CvSTASH(dstr), param);
13296                 if ((param->flags & CLONEf_JOIN_IN) && CvSTASH(dstr))
13297                     Perl_sv_add_backref(aTHX_ MUTABLE_SV(CvSTASH(dstr)), dstr);
13298                 if (!CvISXSUB(dstr)) {
13299                     OP_REFCNT_LOCK;
13300                     CvROOT(dstr) = OpREFCNT_inc(CvROOT(dstr));
13301                     OP_REFCNT_UNLOCK;
13302                     CvSLABBED_off(dstr);
13303                 } else if (CvCONST(dstr)) {
13304                     CvXSUBANY(dstr).any_ptr =
13305                         sv_dup_inc((const SV *)CvXSUBANY(dstr).any_ptr, param);
13306                 }
13307                 assert(!CvSLABBED(dstr));
13308                 if (CvDYNFILE(dstr)) CvFILE(dstr) = SAVEPV(CvFILE(dstr));
13309                 if (CvNAMED(dstr))
13310                     SvANY((CV *)dstr)->xcv_gv_u.xcv_hek =
13311                         share_hek_hek(CvNAME_HEK((CV *)sstr));
13312                 /* don't dup if copying back - CvGV isn't refcounted, so the
13313                  * duped GV may never be freed. A bit of a hack! DAPM */
13314                 else
13315                   SvANY(MUTABLE_CV(dstr))->xcv_gv_u.xcv_gv =
13316                     CvCVGV_RC(dstr)
13317                     ? gv_dup_inc(CvGV(sstr), param)
13318                     : (param->flags & CLONEf_JOIN_IN)
13319                         ? NULL
13320                         : gv_dup(CvGV(sstr), param);
13321
13322                 CvPADLIST(dstr) = padlist_dup(CvPADLIST(sstr), param);
13323                 CvOUTSIDE(dstr) =
13324                     CvWEAKOUTSIDE(sstr)
13325                     ? cv_dup(    CvOUTSIDE(dstr), param)
13326                     : cv_dup_inc(CvOUTSIDE(dstr), param);
13327                 break;
13328             }
13329         }
13330     }
13331
13332     return dstr;
13333  }
13334
13335 SV *
13336 Perl_sv_dup_inc(pTHX_ const SV *const sstr, CLONE_PARAMS *const param)
13337 {
13338     PERL_ARGS_ASSERT_SV_DUP_INC;
13339     return sstr ? SvREFCNT_inc(sv_dup_common(sstr, param)) : NULL;
13340 }
13341
13342 SV *
13343 Perl_sv_dup(pTHX_ const SV *const sstr, CLONE_PARAMS *const param)
13344 {
13345     SV *dstr = sstr ? sv_dup_common(sstr, param) : NULL;
13346     PERL_ARGS_ASSERT_SV_DUP;
13347
13348     /* Track every SV that (at least initially) had a reference count of 0.
13349        We need to do this by holding an actual reference to it in this array.
13350        If we attempt to cheat, turn AvREAL_off(), and store only pointers
13351        (akin to the stashes hash, and the perl stack), we come unstuck if
13352        a weak reference (or other SV legitimately SvREFCNT() == 0 for this
13353        thread) is manipulated in a CLONE method, because CLONE runs before the
13354        unreferenced array is walked to find SVs still with SvREFCNT() == 0
13355        (and fix things up by giving each a reference via the temps stack).
13356        Instead, during CLONE, if the 0-referenced SV has SvREFCNT_inc() and
13357        then SvREFCNT_dec(), it will be cleaned up (and added to the free list)
13358        before the walk of unreferenced happens and a reference to that is SV
13359        added to the temps stack. At which point we have the same SV considered
13360        to be in use, and free to be re-used. Not good.
13361     */
13362     if (dstr && !(param->flags & CLONEf_COPY_STACKS) && !SvREFCNT(dstr)) {
13363         assert(param->unreferenced);
13364         av_push(param->unreferenced, SvREFCNT_inc(dstr));
13365     }
13366
13367     return dstr;
13368 }
13369
13370 /* duplicate a context */
13371
13372 PERL_CONTEXT *
13373 Perl_cx_dup(pTHX_ PERL_CONTEXT *cxs, I32 ix, I32 max, CLONE_PARAMS* param)
13374 {
13375     PERL_CONTEXT *ncxs;
13376
13377     PERL_ARGS_ASSERT_CX_DUP;
13378
13379     if (!cxs)
13380         return (PERL_CONTEXT*)NULL;
13381
13382     /* look for it in the table first */
13383     ncxs = (PERL_CONTEXT*)ptr_table_fetch(PL_ptr_table, cxs);
13384     if (ncxs)
13385         return ncxs;
13386
13387     /* create anew and remember what it is */
13388     Newx(ncxs, max + 1, PERL_CONTEXT);
13389     ptr_table_store(PL_ptr_table, cxs, ncxs);
13390     Copy(cxs, ncxs, max + 1, PERL_CONTEXT);
13391
13392     while (ix >= 0) {
13393         PERL_CONTEXT * const ncx = &ncxs[ix];
13394         if (CxTYPE(ncx) == CXt_SUBST) {
13395             Perl_croak(aTHX_ "Cloning substitution context is unimplemented");
13396         }
13397         else {
13398             ncx->blk_oldcop = (COP*)any_dup(ncx->blk_oldcop, param->proto_perl);
13399             switch (CxTYPE(ncx)) {
13400             case CXt_SUB:
13401                 ncx->blk_sub.cv         = (ncx->blk_sub.olddepth == 0
13402                                            ? cv_dup_inc(ncx->blk_sub.cv, param)
13403                                            : cv_dup(ncx->blk_sub.cv,param));
13404                 if(CxHASARGS(ncx)){
13405                     ncx->blk_sub.argarray = av_dup_inc(ncx->blk_sub.argarray,param);
13406                     ncx->blk_sub.savearray = av_dup_inc(ncx->blk_sub.savearray,param);
13407                 } else {
13408                     ncx->blk_sub.argarray = NULL;
13409                     ncx->blk_sub.savearray = NULL;
13410                 }
13411                 ncx->blk_sub.oldcomppad = (PAD*)ptr_table_fetch(PL_ptr_table,
13412                                            ncx->blk_sub.oldcomppad);
13413                 break;
13414             case CXt_EVAL:
13415                 ncx->blk_eval.old_namesv = sv_dup_inc(ncx->blk_eval.old_namesv,
13416                                                       param);
13417                 ncx->blk_eval.cur_text  = sv_dup(ncx->blk_eval.cur_text, param);
13418                 ncx->blk_eval.cv = cv_dup(ncx->blk_eval.cv, param);
13419                 break;
13420             case CXt_LOOP_LAZYSV:
13421                 ncx->blk_loop.state_u.lazysv.end
13422                     = sv_dup_inc(ncx->blk_loop.state_u.lazysv.end, param);
13423                 /* We are taking advantage of av_dup_inc and sv_dup_inc
13424                    actually being the same function, and order equivalence of
13425                    the two unions.
13426                    We can assert the later [but only at run time :-(]  */
13427                 assert ((void *) &ncx->blk_loop.state_u.ary.ary ==
13428                         (void *) &ncx->blk_loop.state_u.lazysv.cur);
13429             case CXt_LOOP_FOR:
13430                 ncx->blk_loop.state_u.ary.ary
13431                     = av_dup_inc(ncx->blk_loop.state_u.ary.ary, param);
13432             case CXt_LOOP_LAZYIV:
13433             case CXt_LOOP_PLAIN:
13434                 if (CxPADLOOP(ncx)) {
13435                     ncx->blk_loop.itervar_u.oldcomppad
13436                         = (PAD*)ptr_table_fetch(PL_ptr_table,
13437                                         ncx->blk_loop.itervar_u.oldcomppad);
13438                 } else {
13439                     ncx->blk_loop.itervar_u.gv
13440                         = gv_dup((const GV *)ncx->blk_loop.itervar_u.gv,
13441                                     param);
13442                 }
13443                 break;
13444             case CXt_FORMAT:
13445                 ncx->blk_format.cv      = cv_dup(ncx->blk_format.cv, param);
13446                 ncx->blk_format.gv      = gv_dup(ncx->blk_format.gv, param);
13447                 ncx->blk_format.dfoutgv = gv_dup_inc(ncx->blk_format.dfoutgv,
13448                                                      param);
13449                 break;
13450             case CXt_BLOCK:
13451             case CXt_NULL:
13452             case CXt_WHEN:
13453             case CXt_GIVEN:
13454                 break;
13455             }
13456         }
13457         --ix;
13458     }
13459     return ncxs;
13460 }
13461
13462 /* duplicate a stack info structure */
13463
13464 PERL_SI *
13465 Perl_si_dup(pTHX_ PERL_SI *si, CLONE_PARAMS* param)
13466 {
13467     PERL_SI *nsi;
13468
13469     PERL_ARGS_ASSERT_SI_DUP;
13470
13471     if (!si)
13472         return (PERL_SI*)NULL;
13473
13474     /* look for it in the table first */
13475     nsi = (PERL_SI*)ptr_table_fetch(PL_ptr_table, si);
13476     if (nsi)
13477         return nsi;
13478
13479     /* create anew and remember what it is */
13480     Newxz(nsi, 1, PERL_SI);
13481     ptr_table_store(PL_ptr_table, si, nsi);
13482
13483     nsi->si_stack       = av_dup_inc(si->si_stack, param);
13484     nsi->si_cxix        = si->si_cxix;
13485     nsi->si_cxmax       = si->si_cxmax;
13486     nsi->si_cxstack     = cx_dup(si->si_cxstack, si->si_cxix, si->si_cxmax, param);
13487     nsi->si_type        = si->si_type;
13488     nsi->si_prev        = si_dup(si->si_prev, param);
13489     nsi->si_next        = si_dup(si->si_next, param);
13490     nsi->si_markoff     = si->si_markoff;
13491
13492     return nsi;
13493 }
13494
13495 #define POPINT(ss,ix)   ((ss)[--(ix)].any_i32)
13496 #define TOPINT(ss,ix)   ((ss)[ix].any_i32)
13497 #define POPLONG(ss,ix)  ((ss)[--(ix)].any_long)
13498 #define TOPLONG(ss,ix)  ((ss)[ix].any_long)
13499 #define POPIV(ss,ix)    ((ss)[--(ix)].any_iv)
13500 #define TOPIV(ss,ix)    ((ss)[ix].any_iv)
13501 #define POPUV(ss,ix)    ((ss)[--(ix)].any_uv)
13502 #define TOPUV(ss,ix)    ((ss)[ix].any_uv)
13503 #define POPBOOL(ss,ix)  ((ss)[--(ix)].any_bool)
13504 #define TOPBOOL(ss,ix)  ((ss)[ix].any_bool)
13505 #define POPPTR(ss,ix)   ((ss)[--(ix)].any_ptr)
13506 #define TOPPTR(ss,ix)   ((ss)[ix].any_ptr)
13507 #define POPDPTR(ss,ix)  ((ss)[--(ix)].any_dptr)
13508 #define TOPDPTR(ss,ix)  ((ss)[ix].any_dptr)
13509 #define POPDXPTR(ss,ix) ((ss)[--(ix)].any_dxptr)
13510 #define TOPDXPTR(ss,ix) ((ss)[ix].any_dxptr)
13511
13512 /* XXXXX todo */
13513 #define pv_dup_inc(p)   SAVEPV(p)
13514 #define pv_dup(p)       SAVEPV(p)
13515 #define svp_dup_inc(p,pp)       any_dup(p,pp)
13516
13517 /* map any object to the new equivent - either something in the
13518  * ptr table, or something in the interpreter structure
13519  */
13520
13521 void *
13522 Perl_any_dup(pTHX_ void *v, const PerlInterpreter *proto_perl)
13523 {
13524     void *ret;
13525
13526     PERL_ARGS_ASSERT_ANY_DUP;
13527
13528     if (!v)
13529         return (void*)NULL;
13530
13531     /* look for it in the table first */
13532     ret = ptr_table_fetch(PL_ptr_table, v);
13533     if (ret)
13534         return ret;
13535
13536     /* see if it is part of the interpreter structure */
13537     if (v >= (void*)proto_perl && v < (void*)(proto_perl+1))
13538         ret = (void*)(((char*)aTHX) + (((char*)v) - (char*)proto_perl));
13539     else {
13540         ret = v;
13541     }
13542
13543     return ret;
13544 }
13545
13546 /* duplicate the save stack */
13547
13548 ANY *
13549 Perl_ss_dup(pTHX_ PerlInterpreter *proto_perl, CLONE_PARAMS* param)
13550 {
13551     dVAR;
13552     ANY * const ss      = proto_perl->Isavestack;
13553     const I32 max       = proto_perl->Isavestack_max;
13554     I32 ix              = proto_perl->Isavestack_ix;
13555     ANY *nss;
13556     const SV *sv;
13557     const GV *gv;
13558     const AV *av;
13559     const HV *hv;
13560     void* ptr;
13561     int intval;
13562     long longval;
13563     GP *gp;
13564     IV iv;
13565     I32 i;
13566     char *c = NULL;
13567     void (*dptr) (void*);
13568     void (*dxptr) (pTHX_ void*);
13569
13570     PERL_ARGS_ASSERT_SS_DUP;
13571
13572     Newxz(nss, max, ANY);
13573
13574     while (ix > 0) {
13575         const UV uv = POPUV(ss,ix);
13576         const U8 type = (U8)uv & SAVE_MASK;
13577
13578         TOPUV(nss,ix) = uv;
13579         switch (type) {
13580         case SAVEt_CLEARSV:
13581         case SAVEt_CLEARPADRANGE:
13582             break;
13583         case SAVEt_HELEM:               /* hash element */
13584             sv = (const SV *)POPPTR(ss,ix);
13585             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13586             /* FALLTHROUGH */
13587         case SAVEt_ITEM:                        /* normal string */
13588         case SAVEt_GVSV:                        /* scalar slot in GV */
13589         case SAVEt_SV:                          /* scalar reference */
13590             sv = (const SV *)POPPTR(ss,ix);
13591             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13592             /* FALLTHROUGH */
13593         case SAVEt_FREESV:
13594         case SAVEt_MORTALIZESV:
13595         case SAVEt_READONLY_OFF:
13596             sv = (const SV *)POPPTR(ss,ix);
13597             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13598             break;
13599         case SAVEt_SHARED_PVREF:                /* char* in shared space */
13600             c = (char*)POPPTR(ss,ix);
13601             TOPPTR(nss,ix) = savesharedpv(c);
13602             ptr = POPPTR(ss,ix);
13603             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13604             break;
13605         case SAVEt_GENERIC_SVREF:               /* generic sv */
13606         case SAVEt_SVREF:                       /* scalar reference */
13607             sv = (const SV *)POPPTR(ss,ix);
13608             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13609             ptr = POPPTR(ss,ix);
13610             TOPPTR(nss,ix) = svp_dup_inc((SV**)ptr, proto_perl);/* XXXXX */
13611             break;
13612         case SAVEt_GVSLOT:              /* any slot in GV */
13613             sv = (const SV *)POPPTR(ss,ix);
13614             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13615             ptr = POPPTR(ss,ix);
13616             TOPPTR(nss,ix) = svp_dup_inc((SV**)ptr, proto_perl);/* XXXXX */
13617             sv = (const SV *)POPPTR(ss,ix);
13618             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13619             break;
13620         case SAVEt_HV:                          /* hash reference */
13621         case SAVEt_AV:                          /* array reference */
13622             sv = (const SV *) POPPTR(ss,ix);
13623             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13624             /* FALLTHROUGH */
13625         case SAVEt_COMPPAD:
13626         case SAVEt_NSTAB:
13627             sv = (const SV *) POPPTR(ss,ix);
13628             TOPPTR(nss,ix) = sv_dup(sv, param);
13629             break;
13630         case SAVEt_INT:                         /* int reference */
13631             ptr = POPPTR(ss,ix);
13632             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13633             intval = (int)POPINT(ss,ix);
13634             TOPINT(nss,ix) = intval;
13635             break;
13636         case SAVEt_LONG:                        /* long reference */
13637             ptr = POPPTR(ss,ix);
13638             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13639             longval = (long)POPLONG(ss,ix);
13640             TOPLONG(nss,ix) = longval;
13641             break;
13642         case SAVEt_I32:                         /* I32 reference */
13643             ptr = POPPTR(ss,ix);
13644             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13645             i = POPINT(ss,ix);
13646             TOPINT(nss,ix) = i;
13647             break;
13648         case SAVEt_IV:                          /* IV reference */
13649         case SAVEt_STRLEN:                      /* STRLEN/size_t ref */
13650             ptr = POPPTR(ss,ix);
13651             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13652             iv = POPIV(ss,ix);
13653             TOPIV(nss,ix) = iv;
13654             break;
13655         case SAVEt_HPTR:                        /* HV* reference */
13656         case SAVEt_APTR:                        /* AV* reference */
13657         case SAVEt_SPTR:                        /* SV* reference */
13658             ptr = POPPTR(ss,ix);
13659             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13660             sv = (const SV *)POPPTR(ss,ix);
13661             TOPPTR(nss,ix) = sv_dup(sv, param);
13662             break;
13663         case SAVEt_VPTR:                        /* random* reference */
13664             ptr = POPPTR(ss,ix);
13665             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13666             /* FALLTHROUGH */
13667         case SAVEt_INT_SMALL:
13668         case SAVEt_I32_SMALL:
13669         case SAVEt_I16:                         /* I16 reference */
13670         case SAVEt_I8:                          /* I8 reference */
13671         case SAVEt_BOOL:
13672             ptr = POPPTR(ss,ix);
13673             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13674             break;
13675         case SAVEt_GENERIC_PVREF:               /* generic char* */
13676         case SAVEt_PPTR:                        /* char* reference */
13677             ptr = POPPTR(ss,ix);
13678             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13679             c = (char*)POPPTR(ss,ix);
13680             TOPPTR(nss,ix) = pv_dup(c);
13681             break;
13682         case SAVEt_GP:                          /* scalar reference */
13683             gp = (GP*)POPPTR(ss,ix);
13684             TOPPTR(nss,ix) = gp = gp_dup(gp, param);
13685             (void)GpREFCNT_inc(gp);
13686             gv = (const GV *)POPPTR(ss,ix);
13687             TOPPTR(nss,ix) = gv_dup_inc(gv, param);
13688             break;
13689         case SAVEt_FREEOP:
13690             ptr = POPPTR(ss,ix);
13691             if (ptr && (((OP*)ptr)->op_private & OPpREFCOUNTED)) {
13692                 /* these are assumed to be refcounted properly */
13693                 OP *o;
13694                 switch (((OP*)ptr)->op_type) {
13695                 case OP_LEAVESUB:
13696                 case OP_LEAVESUBLV:
13697                 case OP_LEAVEEVAL:
13698                 case OP_LEAVE:
13699                 case OP_SCOPE:
13700                 case OP_LEAVEWRITE:
13701                     TOPPTR(nss,ix) = ptr;
13702                     o = (OP*)ptr;
13703                     OP_REFCNT_LOCK;
13704                     (void) OpREFCNT_inc(o);
13705                     OP_REFCNT_UNLOCK;
13706                     break;
13707                 default:
13708                     TOPPTR(nss,ix) = NULL;
13709                     break;
13710                 }
13711             }
13712             else
13713                 TOPPTR(nss,ix) = NULL;
13714             break;
13715         case SAVEt_FREECOPHH:
13716             ptr = POPPTR(ss,ix);
13717             TOPPTR(nss,ix) = cophh_copy((COPHH *)ptr);
13718             break;
13719         case SAVEt_ADELETE:
13720             av = (const AV *)POPPTR(ss,ix);
13721             TOPPTR(nss,ix) = av_dup_inc(av, param);
13722             i = POPINT(ss,ix);
13723             TOPINT(nss,ix) = i;
13724             break;
13725         case SAVEt_DELETE:
13726             hv = (const HV *)POPPTR(ss,ix);
13727             TOPPTR(nss,ix) = hv_dup_inc(hv, param);
13728             i = POPINT(ss,ix);
13729             TOPINT(nss,ix) = i;
13730             /* FALLTHROUGH */
13731         case SAVEt_FREEPV:
13732             c = (char*)POPPTR(ss,ix);
13733             TOPPTR(nss,ix) = pv_dup_inc(c);
13734             break;
13735         case SAVEt_STACK_POS:           /* Position on Perl stack */
13736             i = POPINT(ss,ix);
13737             TOPINT(nss,ix) = i;
13738             break;
13739         case SAVEt_DESTRUCTOR:
13740             ptr = POPPTR(ss,ix);
13741             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);  /* XXX quite arbitrary */
13742             dptr = POPDPTR(ss,ix);
13743             TOPDPTR(nss,ix) = DPTR2FPTR(void (*)(void*),
13744                                         any_dup(FPTR2DPTR(void *, dptr),
13745                                                 proto_perl));
13746             break;
13747         case SAVEt_DESTRUCTOR_X:
13748             ptr = POPPTR(ss,ix);
13749             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);  /* XXX quite arbitrary */
13750             dxptr = POPDXPTR(ss,ix);
13751             TOPDXPTR(nss,ix) = DPTR2FPTR(void (*)(pTHX_ void*),
13752                                          any_dup(FPTR2DPTR(void *, dxptr),
13753                                                  proto_perl));
13754             break;
13755         case SAVEt_REGCONTEXT:
13756         case SAVEt_ALLOC:
13757             ix -= uv >> SAVE_TIGHT_SHIFT;
13758             break;
13759         case SAVEt_AELEM:               /* array element */
13760             sv = (const SV *)POPPTR(ss,ix);
13761             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13762             i = POPINT(ss,ix);
13763             TOPINT(nss,ix) = i;
13764             av = (const AV *)POPPTR(ss,ix);
13765             TOPPTR(nss,ix) = av_dup_inc(av, param);
13766             break;
13767         case SAVEt_OP:
13768             ptr = POPPTR(ss,ix);
13769             TOPPTR(nss,ix) = ptr;
13770             break;
13771         case SAVEt_HINTS:
13772             ptr = POPPTR(ss,ix);
13773             ptr = cophh_copy((COPHH*)ptr);
13774             TOPPTR(nss,ix) = ptr;
13775             i = POPINT(ss,ix);
13776             TOPINT(nss,ix) = i;
13777             if (i & HINT_LOCALIZE_HH) {
13778                 hv = (const HV *)POPPTR(ss,ix);
13779                 TOPPTR(nss,ix) = hv_dup_inc(hv, param);
13780             }
13781             break;
13782         case SAVEt_PADSV_AND_MORTALIZE:
13783             longval = (long)POPLONG(ss,ix);
13784             TOPLONG(nss,ix) = longval;
13785             ptr = POPPTR(ss,ix);
13786             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
13787             sv = (const SV *)POPPTR(ss,ix);
13788             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
13789             break;
13790         case SAVEt_SET_SVFLAGS:
13791             i = POPINT(ss,ix);
13792             TOPINT(nss,ix) = i;
13793             i = POPINT(ss,ix);
13794             TOPINT(nss,ix) = i;
13795             sv = (const SV *)POPPTR(ss,ix);
13796             TOPPTR(nss,ix) = sv_dup(sv, param);
13797             break;
13798         case SAVEt_COMPILE_WARNINGS:
13799             ptr = POPPTR(ss,ix);
13800             TOPPTR(nss,ix) = DUP_WARNINGS((STRLEN*)ptr);
13801             break;
13802         case SAVEt_PARSER:
13803             ptr = POPPTR(ss,ix);
13804             TOPPTR(nss,ix) = parser_dup((const yy_parser*)ptr, param);
13805             break;
13806         default:
13807             Perl_croak(aTHX_
13808                        "panic: ss_dup inconsistency (%"IVdf")", (IV) type);
13809         }
13810     }
13811
13812     return nss;
13813 }
13814
13815
13816 /* if sv is a stash, call $class->CLONE_SKIP(), and set the SVphv_CLONEABLE
13817  * flag to the result. This is done for each stash before cloning starts,
13818  * so we know which stashes want their objects cloned */
13819
13820 static void
13821 do_mark_cloneable_stash(pTHX_ SV *const sv)
13822 {
13823     const HEK * const hvname = HvNAME_HEK((const HV *)sv);
13824     if (hvname) {
13825         GV* const cloner = gv_fetchmethod_autoload(MUTABLE_HV(sv), "CLONE_SKIP", 0);
13826         SvFLAGS(sv) |= SVphv_CLONEABLE; /* clone objects by default */
13827         if (cloner && GvCV(cloner)) {
13828             dSP;
13829             UV status;
13830
13831             ENTER;
13832             SAVETMPS;
13833             PUSHMARK(SP);
13834             mXPUSHs(newSVhek(hvname));
13835             PUTBACK;
13836             call_sv(MUTABLE_SV(GvCV(cloner)), G_SCALAR);
13837             SPAGAIN;
13838             status = POPu;
13839             PUTBACK;
13840             FREETMPS;
13841             LEAVE;
13842             if (status)
13843                 SvFLAGS(sv) &= ~SVphv_CLONEABLE;
13844         }
13845     }
13846 }
13847
13848
13849
13850 /*
13851 =for apidoc perl_clone
13852
13853 Create and return a new interpreter by cloning the current one.
13854
13855 perl_clone takes these flags as parameters:
13856
13857 CLONEf_COPY_STACKS - is used to, well, copy the stacks also,
13858 without it we only clone the data and zero the stacks,
13859 with it we copy the stacks and the new perl interpreter is
13860 ready to run at the exact same point as the previous one.
13861 The pseudo-fork code uses COPY_STACKS while the
13862 threads->create doesn't.
13863
13864 CLONEf_KEEP_PTR_TABLE -
13865 perl_clone keeps a ptr_table with the pointer of the old
13866 variable as a key and the new variable as a value,
13867 this allows it to check if something has been cloned and not
13868 clone it again but rather just use the value and increase the
13869 refcount.  If KEEP_PTR_TABLE is not set then perl_clone will kill
13870 the ptr_table using the function
13871 C<ptr_table_free(PL_ptr_table); PL_ptr_table = NULL;>,
13872 reason to keep it around is if you want to dup some of your own
13873 variable who are outside the graph perl scans, example of this
13874 code is in threads.xs create.
13875
13876 CLONEf_CLONE_HOST -
13877 This is a win32 thing, it is ignored on unix, it tells perls
13878 win32host code (which is c++) to clone itself, this is needed on
13879 win32 if you want to run two threads at the same time,
13880 if you just want to do some stuff in a separate perl interpreter
13881 and then throw it away and return to the original one,
13882 you don't need to do anything.
13883
13884 =cut
13885 */
13886
13887 /* XXX the above needs expanding by someone who actually understands it ! */
13888 EXTERN_C PerlInterpreter *
13889 perl_clone_host(PerlInterpreter* proto_perl, UV flags);
13890
13891 PerlInterpreter *
13892 perl_clone(PerlInterpreter *proto_perl, UV flags)
13893 {
13894    dVAR;
13895 #ifdef PERL_IMPLICIT_SYS
13896
13897     PERL_ARGS_ASSERT_PERL_CLONE;
13898
13899    /* perlhost.h so we need to call into it
13900    to clone the host, CPerlHost should have a c interface, sky */
13901
13902    if (flags & CLONEf_CLONE_HOST) {
13903        return perl_clone_host(proto_perl,flags);
13904    }
13905    return perl_clone_using(proto_perl, flags,
13906                             proto_perl->IMem,
13907                             proto_perl->IMemShared,
13908                             proto_perl->IMemParse,
13909                             proto_perl->IEnv,
13910                             proto_perl->IStdIO,
13911                             proto_perl->ILIO,
13912                             proto_perl->IDir,
13913                             proto_perl->ISock,
13914                             proto_perl->IProc);
13915 }
13916
13917 PerlInterpreter *
13918 perl_clone_using(PerlInterpreter *proto_perl, UV flags,
13919                  struct IPerlMem* ipM, struct IPerlMem* ipMS,
13920                  struct IPerlMem* ipMP, struct IPerlEnv* ipE,
13921                  struct IPerlStdIO* ipStd, struct IPerlLIO* ipLIO,
13922                  struct IPerlDir* ipD, struct IPerlSock* ipS,
13923                  struct IPerlProc* ipP)
13924 {
13925     /* XXX many of the string copies here can be optimized if they're
13926      * constants; they need to be allocated as common memory and just
13927      * their pointers copied. */
13928
13929     IV i;
13930     CLONE_PARAMS clone_params;
13931     CLONE_PARAMS* const param = &clone_params;
13932
13933     PerlInterpreter * const my_perl = (PerlInterpreter*)(*ipM->pMalloc)(ipM, sizeof(PerlInterpreter));
13934
13935     PERL_ARGS_ASSERT_PERL_CLONE_USING;
13936 #else           /* !PERL_IMPLICIT_SYS */
13937     IV i;
13938     CLONE_PARAMS clone_params;
13939     CLONE_PARAMS* param = &clone_params;
13940     PerlInterpreter * const my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
13941
13942     PERL_ARGS_ASSERT_PERL_CLONE;
13943 #endif          /* PERL_IMPLICIT_SYS */
13944
13945     /* for each stash, determine whether its objects should be cloned */
13946     S_visit(proto_perl, do_mark_cloneable_stash, SVt_PVHV, SVTYPEMASK);
13947     PERL_SET_THX(my_perl);
13948
13949 #ifdef DEBUGGING
13950     PoisonNew(my_perl, 1, PerlInterpreter);
13951     PL_op = NULL;
13952     PL_curcop = NULL;
13953     PL_defstash = NULL; /* may be used by perl malloc() */
13954     PL_markstack = 0;
13955     PL_scopestack = 0;
13956     PL_scopestack_name = 0;
13957     PL_savestack = 0;
13958     PL_savestack_ix = 0;
13959     PL_savestack_max = -1;
13960     PL_sig_pending = 0;
13961     PL_parser = NULL;
13962     Zero(&PL_debug_pad, 1, struct perl_debug_pad);
13963 #  ifdef DEBUG_LEAKING_SCALARS
13964     PL_sv_serial = (((UV)my_perl >> 2) & 0xfff) * 1000000;
13965 #  endif
13966 #else   /* !DEBUGGING */
13967     Zero(my_perl, 1, PerlInterpreter);
13968 #endif  /* DEBUGGING */
13969
13970 #ifdef PERL_IMPLICIT_SYS
13971     /* host pointers */
13972     PL_Mem              = ipM;
13973     PL_MemShared        = ipMS;
13974     PL_MemParse         = ipMP;
13975     PL_Env              = ipE;
13976     PL_StdIO            = ipStd;
13977     PL_LIO              = ipLIO;
13978     PL_Dir              = ipD;
13979     PL_Sock             = ipS;
13980     PL_Proc             = ipP;
13981 #endif          /* PERL_IMPLICIT_SYS */
13982
13983
13984     param->flags = flags;
13985     /* Nothing in the core code uses this, but we make it available to
13986        extensions (using mg_dup).  */
13987     param->proto_perl = proto_perl;
13988     /* Likely nothing will use this, but it is initialised to be consistent
13989        with Perl_clone_params_new().  */
13990     param->new_perl = my_perl;
13991     param->unreferenced = NULL;
13992
13993
13994     INIT_TRACK_MEMPOOL(my_perl->Imemory_debug_header, my_perl);
13995
13996     PL_body_arenas = NULL;
13997     Zero(&PL_body_roots, 1, PL_body_roots);
13998     
13999     PL_sv_count         = 0;
14000     PL_sv_root          = NULL;
14001     PL_sv_arenaroot     = NULL;
14002
14003     PL_debug            = proto_perl->Idebug;
14004
14005     /* dbargs array probably holds garbage */
14006     PL_dbargs           = NULL;
14007
14008     PL_compiling = proto_perl->Icompiling;
14009
14010     /* pseudo environmental stuff */
14011     PL_origargc         = proto_perl->Iorigargc;
14012     PL_origargv         = proto_perl->Iorigargv;
14013
14014 #ifndef NO_TAINT_SUPPORT
14015     /* Set tainting stuff before PerlIO_debug can possibly get called */
14016     PL_tainting         = proto_perl->Itainting;
14017     PL_taint_warn       = proto_perl->Itaint_warn;
14018 #else
14019     PL_tainting         = FALSE;
14020     PL_taint_warn       = FALSE;
14021 #endif
14022
14023     PL_minus_c          = proto_perl->Iminus_c;
14024
14025     PL_localpatches     = proto_perl->Ilocalpatches;
14026     PL_splitstr         = proto_perl->Isplitstr;
14027     PL_minus_n          = proto_perl->Iminus_n;
14028     PL_minus_p          = proto_perl->Iminus_p;
14029     PL_minus_l          = proto_perl->Iminus_l;
14030     PL_minus_a          = proto_perl->Iminus_a;
14031     PL_minus_E          = proto_perl->Iminus_E;
14032     PL_minus_F          = proto_perl->Iminus_F;
14033     PL_doswitches       = proto_perl->Idoswitches;
14034     PL_dowarn           = proto_perl->Idowarn;
14035 #ifdef PERL_SAWAMPERSAND
14036     PL_sawampersand     = proto_perl->Isawampersand;
14037 #endif
14038     PL_unsafe           = proto_perl->Iunsafe;
14039     PL_perldb           = proto_perl->Iperldb;
14040     PL_perl_destruct_level = proto_perl->Iperl_destruct_level;
14041     PL_exit_flags       = proto_perl->Iexit_flags;
14042
14043     /* XXX time(&PL_basetime) when asked for? */
14044     PL_basetime         = proto_perl->Ibasetime;
14045
14046     PL_maxsysfd         = proto_perl->Imaxsysfd;
14047     PL_statusvalue      = proto_perl->Istatusvalue;
14048 #ifdef __VMS
14049     PL_statusvalue_vms  = proto_perl->Istatusvalue_vms;
14050 #else
14051     PL_statusvalue_posix = proto_perl->Istatusvalue_posix;
14052 #endif
14053
14054     /* RE engine related */
14055     PL_regmatch_slab    = NULL;
14056     PL_reg_curpm        = NULL;
14057
14058     PL_sub_generation   = proto_perl->Isub_generation;
14059
14060     /* funky return mechanisms */
14061     PL_forkprocess      = proto_perl->Iforkprocess;
14062
14063     /* internal state */
14064     PL_maxo             = proto_perl->Imaxo;
14065
14066     PL_main_start       = proto_perl->Imain_start;
14067     PL_eval_root        = proto_perl->Ieval_root;
14068     PL_eval_start       = proto_perl->Ieval_start;
14069
14070     PL_filemode         = proto_perl->Ifilemode;
14071     PL_lastfd           = proto_perl->Ilastfd;
14072     PL_oldname          = proto_perl->Ioldname;         /* XXX not quite right */
14073     PL_Argv             = NULL;
14074     PL_Cmd              = NULL;
14075     PL_gensym           = proto_perl->Igensym;
14076
14077     PL_laststatval      = proto_perl->Ilaststatval;
14078     PL_laststype        = proto_perl->Ilaststype;
14079     PL_mess_sv          = NULL;
14080
14081     PL_profiledata      = NULL;
14082
14083     PL_generation       = proto_perl->Igeneration;
14084
14085     PL_in_clean_objs    = proto_perl->Iin_clean_objs;
14086     PL_in_clean_all     = proto_perl->Iin_clean_all;
14087
14088     PL_delaymagic_uid   = proto_perl->Idelaymagic_uid;
14089     PL_delaymagic_euid  = proto_perl->Idelaymagic_euid;
14090     PL_delaymagic_gid   = proto_perl->Idelaymagic_gid;
14091     PL_delaymagic_egid  = proto_perl->Idelaymagic_egid;
14092     PL_nomemok          = proto_perl->Inomemok;
14093     PL_an               = proto_perl->Ian;
14094     PL_evalseq          = proto_perl->Ievalseq;
14095     PL_origenviron      = proto_perl->Iorigenviron;     /* XXX not quite right */
14096     PL_origalen         = proto_perl->Iorigalen;
14097
14098     PL_sighandlerp      = proto_perl->Isighandlerp;
14099
14100     PL_runops           = proto_perl->Irunops;
14101
14102     PL_subline          = proto_perl->Isubline;
14103
14104 #ifdef FCRYPT
14105     PL_cryptseen        = proto_perl->Icryptseen;
14106 #endif
14107
14108 #ifdef USE_LOCALE_COLLATE
14109     PL_collation_ix     = proto_perl->Icollation_ix;
14110     PL_collation_standard       = proto_perl->Icollation_standard;
14111     PL_collxfrm_base    = proto_perl->Icollxfrm_base;
14112     PL_collxfrm_mult    = proto_perl->Icollxfrm_mult;
14113 #endif /* USE_LOCALE_COLLATE */
14114
14115 #ifdef USE_LOCALE_NUMERIC
14116     PL_numeric_standard = proto_perl->Inumeric_standard;
14117     PL_numeric_local    = proto_perl->Inumeric_local;
14118 #endif /* !USE_LOCALE_NUMERIC */
14119
14120     /* Did the locale setup indicate UTF-8? */
14121     PL_utf8locale       = proto_perl->Iutf8locale;
14122     PL_in_utf8_CTYPE_locale = proto_perl->Iin_utf8_CTYPE_locale;
14123     /* Unicode features (see perlrun/-C) */
14124     PL_unicode          = proto_perl->Iunicode;
14125
14126     /* Pre-5.8 signals control */
14127     PL_signals          = proto_perl->Isignals;
14128
14129     /* times() ticks per second */
14130     PL_clocktick        = proto_perl->Iclocktick;
14131
14132     /* Recursion stopper for PerlIO_find_layer */
14133     PL_in_load_module   = proto_perl->Iin_load_module;
14134
14135     /* sort() routine */
14136     PL_sort_RealCmp     = proto_perl->Isort_RealCmp;
14137
14138     /* Not really needed/useful since the reenrant_retint is "volatile",
14139      * but do it for consistency's sake. */
14140     PL_reentrant_retint = proto_perl->Ireentrant_retint;
14141
14142     /* Hooks to shared SVs and locks. */
14143     PL_sharehook        = proto_perl->Isharehook;
14144     PL_lockhook         = proto_perl->Ilockhook;
14145     PL_unlockhook       = proto_perl->Iunlockhook;
14146     PL_threadhook       = proto_perl->Ithreadhook;
14147     PL_destroyhook      = proto_perl->Idestroyhook;
14148     PL_signalhook       = proto_perl->Isignalhook;
14149
14150     PL_globhook         = proto_perl->Iglobhook;
14151
14152     /* swatch cache */
14153     PL_last_swash_hv    = NULL; /* reinits on demand */
14154     PL_last_swash_klen  = 0;
14155     PL_last_swash_key[0]= '\0';
14156     PL_last_swash_tmps  = (U8*)NULL;
14157     PL_last_swash_slen  = 0;
14158
14159     PL_srand_called     = proto_perl->Isrand_called;
14160     Copy(&(proto_perl->Irandom_state), &PL_random_state, 1, PL_RANDOM_STATE_TYPE);
14161
14162     if (flags & CLONEf_COPY_STACKS) {
14163         /* next allocation will be PL_tmps_stack[PL_tmps_ix+1] */
14164         PL_tmps_ix              = proto_perl->Itmps_ix;
14165         PL_tmps_max             = proto_perl->Itmps_max;
14166         PL_tmps_floor           = proto_perl->Itmps_floor;
14167
14168         /* next push_scope()/ENTER sets PL_scopestack[PL_scopestack_ix]
14169          * NOTE: unlike the others! */
14170         PL_scopestack_ix        = proto_perl->Iscopestack_ix;
14171         PL_scopestack_max       = proto_perl->Iscopestack_max;
14172
14173         /* next SSPUSHFOO() sets PL_savestack[PL_savestack_ix]
14174          * NOTE: unlike the others! */
14175         PL_savestack_ix         = proto_perl->Isavestack_ix;
14176         PL_savestack_max        = proto_perl->Isavestack_max;
14177     }
14178
14179     PL_start_env        = proto_perl->Istart_env;       /* XXXXXX */
14180     PL_top_env          = &PL_start_env;
14181
14182     PL_op               = proto_perl->Iop;
14183
14184     PL_Sv               = NULL;
14185     PL_Xpv              = (XPV*)NULL;
14186     my_perl->Ina        = proto_perl->Ina;
14187
14188     PL_statbuf          = proto_perl->Istatbuf;
14189     PL_statcache        = proto_perl->Istatcache;
14190
14191 #ifndef NO_TAINT_SUPPORT
14192     PL_tainted          = proto_perl->Itainted;
14193 #else
14194     PL_tainted          = FALSE;
14195 #endif
14196     PL_curpm            = proto_perl->Icurpm;   /* XXX No PMOP ref count */
14197
14198     PL_chopset          = proto_perl->Ichopset; /* XXX never deallocated */
14199
14200     PL_restartjmpenv    = proto_perl->Irestartjmpenv;
14201     PL_restartop        = proto_perl->Irestartop;
14202     PL_in_eval          = proto_perl->Iin_eval;
14203     PL_delaymagic       = proto_perl->Idelaymagic;
14204     PL_phase            = proto_perl->Iphase;
14205     PL_localizing       = proto_perl->Ilocalizing;
14206
14207     PL_hv_fetch_ent_mh  = NULL;
14208     PL_modcount         = proto_perl->Imodcount;
14209     PL_lastgotoprobe    = NULL;
14210     PL_dumpindent       = proto_perl->Idumpindent;
14211
14212     PL_efloatbuf        = NULL;         /* reinits on demand */
14213     PL_efloatsize       = 0;                    /* reinits on demand */
14214
14215     /* regex stuff */
14216
14217     PL_colorset         = 0;            /* reinits PL_colors[] */
14218     /*PL_colors[6]      = {0,0,0,0,0,0};*/
14219
14220     /* Pluggable optimizer */
14221     PL_peepp            = proto_perl->Ipeepp;
14222     PL_rpeepp           = proto_perl->Irpeepp;
14223     /* op_free() hook */
14224     PL_opfreehook       = proto_perl->Iopfreehook;
14225
14226 #ifdef USE_REENTRANT_API
14227     /* XXX: things like -Dm will segfault here in perlio, but doing
14228      *  PERL_SET_CONTEXT(proto_perl);
14229      * breaks too many other things
14230      */
14231     Perl_reentrant_init(aTHX);
14232 #endif
14233
14234     /* create SV map for pointer relocation */
14235     PL_ptr_table = ptr_table_new();
14236
14237     /* initialize these special pointers as early as possible */
14238     init_constants();
14239     ptr_table_store(PL_ptr_table, &proto_perl->Isv_undef, &PL_sv_undef);
14240     ptr_table_store(PL_ptr_table, &proto_perl->Isv_no, &PL_sv_no);
14241     ptr_table_store(PL_ptr_table, &proto_perl->Isv_yes, &PL_sv_yes);
14242
14243     /* create (a non-shared!) shared string table */
14244     PL_strtab           = newHV();
14245     HvSHAREKEYS_off(PL_strtab);
14246     hv_ksplit(PL_strtab, HvTOTALKEYS(proto_perl->Istrtab));
14247     ptr_table_store(PL_ptr_table, proto_perl->Istrtab, PL_strtab);
14248
14249     Zero(PL_sv_consts, SV_CONSTS_COUNT, SV*);
14250
14251     /* This PV will be free'd special way so must set it same way op.c does */
14252     PL_compiling.cop_file    = savesharedpv(PL_compiling.cop_file);
14253     ptr_table_store(PL_ptr_table, proto_perl->Icompiling.cop_file, PL_compiling.cop_file);
14254
14255     ptr_table_store(PL_ptr_table, &proto_perl->Icompiling, &PL_compiling);
14256     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
14257     CopHINTHASH_set(&PL_compiling, cophh_copy(CopHINTHASH_get(&PL_compiling)));
14258     PL_curcop           = (COP*)any_dup(proto_perl->Icurcop, proto_perl);
14259
14260     param->stashes      = newAV();  /* Setup array of objects to call clone on */
14261     /* This makes no difference to the implementation, as it always pushes
14262        and shifts pointers to other SVs without changing their reference
14263        count, with the array becoming empty before it is freed. However, it
14264        makes it conceptually clear what is going on, and will avoid some
14265        work inside av.c, filling slots between AvFILL() and AvMAX() with
14266        &PL_sv_undef, and SvREFCNT_dec()ing those.  */
14267     AvREAL_off(param->stashes);
14268
14269     if (!(flags & CLONEf_COPY_STACKS)) {
14270         param->unreferenced = newAV();
14271     }
14272
14273 #ifdef PERLIO_LAYERS
14274     /* Clone PerlIO tables as soon as we can handle general xx_dup() */
14275     PerlIO_clone(aTHX_ proto_perl, param);
14276 #endif
14277
14278     PL_envgv            = gv_dup_inc(proto_perl->Ienvgv, param);
14279     PL_incgv            = gv_dup_inc(proto_perl->Iincgv, param);
14280     PL_hintgv           = gv_dup_inc(proto_perl->Ihintgv, param);
14281     PL_origfilename     = SAVEPV(proto_perl->Iorigfilename);
14282     PL_diehook          = sv_dup_inc(proto_perl->Idiehook, param);
14283     PL_warnhook         = sv_dup_inc(proto_perl->Iwarnhook, param);
14284
14285     /* switches */
14286     PL_patchlevel       = sv_dup_inc(proto_perl->Ipatchlevel, param);
14287     PL_apiversion       = sv_dup_inc(proto_perl->Iapiversion, param);
14288     PL_inplace          = SAVEPV(proto_perl->Iinplace);
14289     PL_e_script         = sv_dup_inc(proto_perl->Ie_script, param);
14290
14291     /* magical thingies */
14292
14293     PL_encoding         = sv_dup(proto_perl->Iencoding, param);
14294
14295     sv_setpvs(PERL_DEBUG_PAD(0), "");   /* For regex debugging. */
14296     sv_setpvs(PERL_DEBUG_PAD(1), "");   /* ext/re needs these */
14297     sv_setpvs(PERL_DEBUG_PAD(2), "");   /* even without DEBUGGING. */
14298
14299    
14300     /* Clone the regex array */
14301     /* ORANGE FIXME for plugins, probably in the SV dup code.
14302        newSViv(PTR2IV(CALLREGDUPE(
14303        INT2PTR(REGEXP *, SvIVX(regex)), param))))
14304     */
14305     PL_regex_padav = av_dup_inc(proto_perl->Iregex_padav, param);
14306     PL_regex_pad = AvARRAY(PL_regex_padav);
14307
14308     PL_stashpadmax      = proto_perl->Istashpadmax;
14309     PL_stashpadix       = proto_perl->Istashpadix ;
14310     Newx(PL_stashpad, PL_stashpadmax, HV *);
14311     {
14312         PADOFFSET o = 0;
14313         for (; o < PL_stashpadmax; ++o)
14314             PL_stashpad[o] = hv_dup(proto_perl->Istashpad[o], param);
14315     }
14316
14317     /* shortcuts to various I/O objects */
14318     PL_ofsgv            = gv_dup_inc(proto_perl->Iofsgv, param);
14319     PL_stdingv          = gv_dup(proto_perl->Istdingv, param);
14320     PL_stderrgv         = gv_dup(proto_perl->Istderrgv, param);
14321     PL_defgv            = gv_dup(proto_perl->Idefgv, param);
14322     PL_argvgv           = gv_dup_inc(proto_perl->Iargvgv, param);
14323     PL_argvoutgv        = gv_dup(proto_perl->Iargvoutgv, param);
14324     PL_argvout_stack    = av_dup_inc(proto_perl->Iargvout_stack, param);
14325
14326     /* shortcuts to regexp stuff */
14327     PL_replgv           = gv_dup_inc(proto_perl->Ireplgv, param);
14328
14329     /* shortcuts to misc objects */
14330     PL_errgv            = gv_dup(proto_perl->Ierrgv, param);
14331
14332     /* shortcuts to debugging objects */
14333     PL_DBgv             = gv_dup_inc(proto_perl->IDBgv, param);
14334     PL_DBline           = gv_dup_inc(proto_perl->IDBline, param);
14335     PL_DBsub            = gv_dup_inc(proto_perl->IDBsub, param);
14336     PL_DBsingle         = sv_dup(proto_perl->IDBsingle, param);
14337     PL_DBtrace          = sv_dup(proto_perl->IDBtrace, param);
14338     PL_DBsignal         = sv_dup(proto_perl->IDBsignal, param);
14339
14340     /* symbol tables */
14341     PL_defstash         = hv_dup_inc(proto_perl->Idefstash, param);
14342     PL_curstash         = hv_dup_inc(proto_perl->Icurstash, param);
14343     PL_debstash         = hv_dup(proto_perl->Idebstash, param);
14344     PL_globalstash      = hv_dup(proto_perl->Iglobalstash, param);
14345     PL_curstname        = sv_dup_inc(proto_perl->Icurstname, param);
14346
14347     PL_beginav          = av_dup_inc(proto_perl->Ibeginav, param);
14348     PL_beginav_save     = av_dup_inc(proto_perl->Ibeginav_save, param);
14349     PL_checkav_save     = av_dup_inc(proto_perl->Icheckav_save, param);
14350     PL_unitcheckav      = av_dup_inc(proto_perl->Iunitcheckav, param);
14351     PL_unitcheckav_save = av_dup_inc(proto_perl->Iunitcheckav_save, param);
14352     PL_endav            = av_dup_inc(proto_perl->Iendav, param);
14353     PL_checkav          = av_dup_inc(proto_perl->Icheckav, param);
14354     PL_initav           = av_dup_inc(proto_perl->Iinitav, param);
14355
14356     PL_isarev           = hv_dup_inc(proto_perl->Iisarev, param);
14357
14358     /* subprocess state */
14359     PL_fdpid            = av_dup_inc(proto_perl->Ifdpid, param);
14360
14361     if (proto_perl->Iop_mask)
14362         PL_op_mask      = SAVEPVN(proto_perl->Iop_mask, PL_maxo);
14363     else
14364         PL_op_mask      = NULL;
14365     /* PL_asserting        = proto_perl->Iasserting; */
14366
14367     /* current interpreter roots */
14368     PL_main_cv          = cv_dup_inc(proto_perl->Imain_cv, param);
14369     OP_REFCNT_LOCK;
14370     PL_main_root        = OpREFCNT_inc(proto_perl->Imain_root);
14371     OP_REFCNT_UNLOCK;
14372
14373     /* runtime control stuff */
14374     PL_curcopdb         = (COP*)any_dup(proto_perl->Icurcopdb, proto_perl);
14375
14376     PL_preambleav       = av_dup_inc(proto_perl->Ipreambleav, param);
14377
14378     PL_ors_sv           = sv_dup_inc(proto_perl->Iors_sv, param);
14379
14380     /* interpreter atexit processing */
14381     PL_exitlistlen      = proto_perl->Iexitlistlen;
14382     if (PL_exitlistlen) {
14383         Newx(PL_exitlist, PL_exitlistlen, PerlExitListEntry);
14384         Copy(proto_perl->Iexitlist, PL_exitlist, PL_exitlistlen, PerlExitListEntry);
14385     }
14386     else
14387         PL_exitlist     = (PerlExitListEntry*)NULL;
14388
14389     PL_my_cxt_size = proto_perl->Imy_cxt_size;
14390     if (PL_my_cxt_size) {
14391         Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
14392         Copy(proto_perl->Imy_cxt_list, PL_my_cxt_list, PL_my_cxt_size, void *);
14393 #ifdef PERL_GLOBAL_STRUCT_PRIVATE
14394         Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
14395         Copy(proto_perl->Imy_cxt_keys, PL_my_cxt_keys, PL_my_cxt_size, char *);
14396 #endif
14397     }
14398     else {
14399         PL_my_cxt_list  = (void**)NULL;
14400 #ifdef PERL_GLOBAL_STRUCT_PRIVATE
14401         PL_my_cxt_keys  = (const char**)NULL;
14402 #endif
14403     }
14404     PL_modglobal        = hv_dup_inc(proto_perl->Imodglobal, param);
14405     PL_custom_op_names  = hv_dup_inc(proto_perl->Icustom_op_names,param);
14406     PL_custom_op_descs  = hv_dup_inc(proto_perl->Icustom_op_descs,param);
14407     PL_custom_ops       = hv_dup_inc(proto_perl->Icustom_ops, param);
14408
14409     PL_compcv                   = cv_dup(proto_perl->Icompcv, param);
14410
14411     PAD_CLONE_VARS(proto_perl, param);
14412
14413 #ifdef HAVE_INTERP_INTERN
14414     sys_intern_dup(&proto_perl->Isys_intern, &PL_sys_intern);
14415 #endif
14416
14417     PL_DBcv             = cv_dup(proto_perl->IDBcv, param);
14418
14419 #ifdef PERL_USES_PL_PIDSTATUS
14420     PL_pidstatus        = newHV();                      /* XXX flag for cloning? */
14421 #endif
14422     PL_osname           = SAVEPV(proto_perl->Iosname);
14423     PL_parser           = parser_dup(proto_perl->Iparser, param);
14424
14425     /* XXX this only works if the saved cop has already been cloned */
14426     if (proto_perl->Iparser) {
14427         PL_parser->saved_curcop = (COP*)any_dup(
14428                                     proto_perl->Iparser->saved_curcop,
14429                                     proto_perl);
14430     }
14431
14432     PL_subname          = sv_dup_inc(proto_perl->Isubname, param);
14433
14434 #ifdef USE_LOCALE_COLLATE
14435     PL_collation_name   = SAVEPV(proto_perl->Icollation_name);
14436 #endif /* USE_LOCALE_COLLATE */
14437
14438 #ifdef USE_LOCALE_NUMERIC
14439     PL_numeric_name     = SAVEPV(proto_perl->Inumeric_name);
14440     PL_numeric_radix_sv = sv_dup_inc(proto_perl->Inumeric_radix_sv, param);
14441 #endif /* !USE_LOCALE_NUMERIC */
14442
14443     /* Unicode inversion lists */
14444     PL_Latin1           = sv_dup_inc(proto_perl->ILatin1, param);
14445     PL_UpperLatin1      = sv_dup_inc(proto_perl->IUpperLatin1, param);
14446     PL_AboveLatin1      = sv_dup_inc(proto_perl->IAboveLatin1, param);
14447     PL_InBitmap         = sv_dup_inc(proto_perl->IInBitmap, param);
14448
14449     PL_NonL1NonFinalFold = sv_dup_inc(proto_perl->INonL1NonFinalFold, param);
14450     PL_HasMultiCharFold = sv_dup_inc(proto_perl->IHasMultiCharFold, param);
14451
14452     /* utf8 character class swashes */
14453     for (i = 0; i < POSIX_SWASH_COUNT; i++) {
14454         PL_utf8_swash_ptrs[i] = sv_dup_inc(proto_perl->Iutf8_swash_ptrs[i], param);
14455     }
14456     for (i = 0; i < POSIX_CC_COUNT; i++) {
14457         PL_XPosix_ptrs[i] = sv_dup_inc(proto_perl->IXPosix_ptrs[i], param);
14458     }
14459     PL_utf8_mark        = sv_dup_inc(proto_perl->Iutf8_mark, param);
14460     PL_utf8_X_regular_begin     = sv_dup_inc(proto_perl->Iutf8_X_regular_begin, param);
14461     PL_utf8_X_extend    = sv_dup_inc(proto_perl->Iutf8_X_extend, param);
14462     PL_utf8_toupper     = sv_dup_inc(proto_perl->Iutf8_toupper, param);
14463     PL_utf8_totitle     = sv_dup_inc(proto_perl->Iutf8_totitle, param);
14464     PL_utf8_tolower     = sv_dup_inc(proto_perl->Iutf8_tolower, param);
14465     PL_utf8_tofold      = sv_dup_inc(proto_perl->Iutf8_tofold, param);
14466     PL_utf8_idstart     = sv_dup_inc(proto_perl->Iutf8_idstart, param);
14467     PL_utf8_xidstart    = sv_dup_inc(proto_perl->Iutf8_xidstart, param);
14468     PL_utf8_perl_idstart = sv_dup_inc(proto_perl->Iutf8_perl_idstart, param);
14469     PL_utf8_perl_idcont = sv_dup_inc(proto_perl->Iutf8_perl_idcont, param);
14470     PL_utf8_idcont      = sv_dup_inc(proto_perl->Iutf8_idcont, param);
14471     PL_utf8_xidcont     = sv_dup_inc(proto_perl->Iutf8_xidcont, param);
14472     PL_utf8_foldable    = sv_dup_inc(proto_perl->Iutf8_foldable, param);
14473     PL_utf8_charname_begin = sv_dup_inc(proto_perl->Iutf8_charname_begin, param);
14474     PL_utf8_charname_continue = sv_dup_inc(proto_perl->Iutf8_charname_continue, param);
14475
14476     if (proto_perl->Ipsig_pend) {
14477         Newxz(PL_psig_pend, SIG_SIZE, int);
14478     }
14479     else {
14480         PL_psig_pend    = (int*)NULL;
14481     }
14482
14483     if (proto_perl->Ipsig_name) {
14484         Newx(PL_psig_name, 2 * SIG_SIZE, SV*);
14485         sv_dup_inc_multiple(proto_perl->Ipsig_name, PL_psig_name, 2 * SIG_SIZE,
14486                             param);
14487         PL_psig_ptr = PL_psig_name + SIG_SIZE;
14488     }
14489     else {
14490         PL_psig_ptr     = (SV**)NULL;
14491         PL_psig_name    = (SV**)NULL;
14492     }
14493
14494     if (flags & CLONEf_COPY_STACKS) {
14495         Newx(PL_tmps_stack, PL_tmps_max, SV*);
14496         sv_dup_inc_multiple(proto_perl->Itmps_stack, PL_tmps_stack,
14497                             PL_tmps_ix+1, param);
14498
14499         /* next PUSHMARK() sets *(PL_markstack_ptr+1) */
14500         i = proto_perl->Imarkstack_max - proto_perl->Imarkstack;
14501         Newxz(PL_markstack, i, I32);
14502         PL_markstack_max        = PL_markstack + (proto_perl->Imarkstack_max
14503                                                   - proto_perl->Imarkstack);
14504         PL_markstack_ptr        = PL_markstack + (proto_perl->Imarkstack_ptr
14505                                                   - proto_perl->Imarkstack);
14506         Copy(proto_perl->Imarkstack, PL_markstack,
14507              PL_markstack_ptr - PL_markstack + 1, I32);
14508
14509         /* next push_scope()/ENTER sets PL_scopestack[PL_scopestack_ix]
14510          * NOTE: unlike the others! */
14511         Newxz(PL_scopestack, PL_scopestack_max, I32);
14512         Copy(proto_perl->Iscopestack, PL_scopestack, PL_scopestack_ix, I32);
14513
14514 #ifdef DEBUGGING
14515         Newxz(PL_scopestack_name, PL_scopestack_max, const char *);
14516         Copy(proto_perl->Iscopestack_name, PL_scopestack_name, PL_scopestack_ix, const char *);
14517 #endif
14518         /* reset stack AV to correct length before its duped via
14519          * PL_curstackinfo */
14520         AvFILLp(proto_perl->Icurstack) =
14521                             proto_perl->Istack_sp - proto_perl->Istack_base;
14522
14523         /* NOTE: si_dup() looks at PL_markstack */
14524         PL_curstackinfo         = si_dup(proto_perl->Icurstackinfo, param);
14525
14526         /* PL_curstack          = PL_curstackinfo->si_stack; */
14527         PL_curstack             = av_dup(proto_perl->Icurstack, param);
14528         PL_mainstack            = av_dup(proto_perl->Imainstack, param);
14529
14530         /* next PUSHs() etc. set *(PL_stack_sp+1) */
14531         PL_stack_base           = AvARRAY(PL_curstack);
14532         PL_stack_sp             = PL_stack_base + (proto_perl->Istack_sp
14533                                                    - proto_perl->Istack_base);
14534         PL_stack_max            = PL_stack_base + AvMAX(PL_curstack);
14535
14536         /*Newxz(PL_savestack, PL_savestack_max, ANY);*/
14537         PL_savestack            = ss_dup(proto_perl, param);
14538     }
14539     else {
14540         init_stacks();
14541         ENTER;                  /* perl_destruct() wants to LEAVE; */
14542     }
14543
14544     PL_statgv           = gv_dup(proto_perl->Istatgv, param);
14545     PL_statname         = sv_dup_inc(proto_perl->Istatname, param);
14546
14547     PL_rs               = sv_dup_inc(proto_perl->Irs, param);
14548     PL_last_in_gv       = gv_dup(proto_perl->Ilast_in_gv, param);
14549     PL_defoutgv         = gv_dup_inc(proto_perl->Idefoutgv, param);
14550     PL_toptarget        = sv_dup_inc(proto_perl->Itoptarget, param);
14551     PL_bodytarget       = sv_dup_inc(proto_perl->Ibodytarget, param);
14552     PL_formtarget       = sv_dup(proto_perl->Iformtarget, param);
14553
14554     PL_errors           = sv_dup_inc(proto_perl->Ierrors, param);
14555
14556     PL_sortcop          = (OP*)any_dup(proto_perl->Isortcop, proto_perl);
14557     PL_firstgv          = gv_dup_inc(proto_perl->Ifirstgv, param);
14558     PL_secondgv         = gv_dup_inc(proto_perl->Isecondgv, param);
14559
14560     PL_stashcache       = newHV();
14561
14562     PL_watchaddr        = (char **) ptr_table_fetch(PL_ptr_table,
14563                                             proto_perl->Iwatchaddr);
14564     PL_watchok          = PL_watchaddr ? * PL_watchaddr : NULL;
14565     if (PL_debug && PL_watchaddr) {
14566         PerlIO_printf(Perl_debug_log,
14567           "WATCHING: %"UVxf" cloned as %"UVxf" with value %"UVxf"\n",
14568           PTR2UV(proto_perl->Iwatchaddr), PTR2UV(PL_watchaddr),
14569           PTR2UV(PL_watchok));
14570     }
14571
14572     PL_registered_mros  = hv_dup_inc(proto_perl->Iregistered_mros, param);
14573     PL_blockhooks       = av_dup_inc(proto_perl->Iblockhooks, param);
14574     PL_utf8_foldclosures = hv_dup_inc(proto_perl->Iutf8_foldclosures, param);
14575
14576     /* Call the ->CLONE method, if it exists, for each of the stashes
14577        identified by sv_dup() above.
14578     */
14579     while(av_tindex(param->stashes) != -1) {
14580         HV* const stash = MUTABLE_HV(av_shift(param->stashes));
14581         GV* const cloner = gv_fetchmethod_autoload(stash, "CLONE", 0);
14582         if (cloner && GvCV(cloner)) {
14583             dSP;
14584             ENTER;
14585             SAVETMPS;
14586             PUSHMARK(SP);
14587             mXPUSHs(newSVhek(HvNAME_HEK(stash)));
14588             PUTBACK;
14589             call_sv(MUTABLE_SV(GvCV(cloner)), G_DISCARD);
14590             FREETMPS;
14591             LEAVE;
14592         }
14593     }
14594
14595     if (!(flags & CLONEf_KEEP_PTR_TABLE)) {
14596         ptr_table_free(PL_ptr_table);
14597         PL_ptr_table = NULL;
14598     }
14599
14600     if (!(flags & CLONEf_COPY_STACKS)) {
14601         unreferenced_to_tmp_stack(param->unreferenced);
14602     }
14603
14604     SvREFCNT_dec(param->stashes);
14605
14606     /* orphaned? eg threads->new inside BEGIN or use */
14607     if (PL_compcv && ! SvREFCNT(PL_compcv)) {
14608         SvREFCNT_inc_simple_void(PL_compcv);
14609         SAVEFREESV(PL_compcv);
14610     }
14611
14612     return my_perl;
14613 }
14614
14615 static void
14616 S_unreferenced_to_tmp_stack(pTHX_ AV *const unreferenced)
14617 {
14618     PERL_ARGS_ASSERT_UNREFERENCED_TO_TMP_STACK;
14619     
14620     if (AvFILLp(unreferenced) > -1) {
14621         SV **svp = AvARRAY(unreferenced);
14622         SV **const last = svp + AvFILLp(unreferenced);
14623         SSize_t count = 0;
14624
14625         do {
14626             if (SvREFCNT(*svp) == 1)
14627                 ++count;
14628         } while (++svp <= last);
14629
14630         EXTEND_MORTAL(count);
14631         svp = AvARRAY(unreferenced);
14632
14633         do {
14634             if (SvREFCNT(*svp) == 1) {
14635                 /* Our reference is the only one to this SV. This means that
14636                    in this thread, the scalar effectively has a 0 reference.
14637                    That doesn't work (cleanup never happens), so donate our
14638                    reference to it onto the save stack. */
14639                 PL_tmps_stack[++PL_tmps_ix] = *svp;
14640             } else {
14641                 /* As an optimisation, because we are already walking the
14642                    entire array, instead of above doing either
14643                    SvREFCNT_inc(*svp) or *svp = &PL_sv_undef, we can instead
14644                    release our reference to the scalar, so that at the end of
14645                    the array owns zero references to the scalars it happens to
14646                    point to. We are effectively converting the array from
14647                    AvREAL() on to AvREAL() off. This saves the av_clear()
14648                    (triggered by the SvREFCNT_dec(unreferenced) below) from
14649                    walking the array a second time.  */
14650                 SvREFCNT_dec(*svp);
14651             }
14652
14653         } while (++svp <= last);
14654         AvREAL_off(unreferenced);
14655     }
14656     SvREFCNT_dec_NN(unreferenced);
14657 }
14658
14659 void
14660 Perl_clone_params_del(CLONE_PARAMS *param)
14661 {
14662     /* This seemingly funky ordering keeps the build with PERL_GLOBAL_STRUCT
14663        happy: */
14664     PerlInterpreter *const to = param->new_perl;
14665     dTHXa(to);
14666     PerlInterpreter *const was = PERL_GET_THX;
14667
14668     PERL_ARGS_ASSERT_CLONE_PARAMS_DEL;
14669
14670     if (was != to) {
14671         PERL_SET_THX(to);
14672     }
14673
14674     SvREFCNT_dec(param->stashes);
14675     if (param->unreferenced)
14676         unreferenced_to_tmp_stack(param->unreferenced);
14677
14678     Safefree(param);
14679
14680     if (was != to) {
14681         PERL_SET_THX(was);
14682     }
14683 }
14684
14685 CLONE_PARAMS *
14686 Perl_clone_params_new(PerlInterpreter *const from, PerlInterpreter *const to)
14687 {
14688     dVAR;
14689     /* Need to play this game, as newAV() can call safesysmalloc(), and that
14690        does a dTHX; to get the context from thread local storage.
14691        FIXME - under PERL_CORE Newx(), Safefree() and friends should expand to
14692        a version that passes in my_perl.  */
14693     PerlInterpreter *const was = PERL_GET_THX;
14694     CLONE_PARAMS *param;
14695
14696     PERL_ARGS_ASSERT_CLONE_PARAMS_NEW;
14697
14698     if (was != to) {
14699         PERL_SET_THX(to);
14700     }
14701
14702     /* Given that we've set the context, we can do this unshared.  */
14703     Newx(param, 1, CLONE_PARAMS);
14704
14705     param->flags = 0;
14706     param->proto_perl = from;
14707     param->new_perl = to;
14708     param->stashes = (AV *)Perl_newSV_type(to, SVt_PVAV);
14709     AvREAL_off(param->stashes);
14710     param->unreferenced = (AV *)Perl_newSV_type(to, SVt_PVAV);
14711
14712     if (was != to) {
14713         PERL_SET_THX(was);
14714     }
14715     return param;
14716 }
14717
14718 #endif /* USE_ITHREADS */
14719
14720 void
14721 Perl_init_constants(pTHX)
14722 {
14723     SvREFCNT(&PL_sv_undef)      = SvREFCNT_IMMORTAL;
14724     SvFLAGS(&PL_sv_undef)       = SVf_READONLY|SVt_NULL;
14725     SvANY(&PL_sv_undef)         = NULL;
14726
14727     SvANY(&PL_sv_no)            = new_XPVNV();
14728     SvREFCNT(&PL_sv_no)         = SvREFCNT_IMMORTAL;
14729     SvFLAGS(&PL_sv_no)          = SVt_PVNV|SVf_READONLY
14730                                   |SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
14731                                   |SVp_POK|SVf_POK;
14732
14733     SvANY(&PL_sv_yes)           = new_XPVNV();
14734     SvREFCNT(&PL_sv_yes)        = SvREFCNT_IMMORTAL;
14735     SvFLAGS(&PL_sv_yes)         = SVt_PVNV|SVf_READONLY
14736                                   |SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
14737                                   |SVp_POK|SVf_POK;
14738
14739     SvPV_set(&PL_sv_no, (char*)PL_No);
14740     SvCUR_set(&PL_sv_no, 0);
14741     SvLEN_set(&PL_sv_no, 0);
14742     SvIV_set(&PL_sv_no, 0);
14743     SvNV_set(&PL_sv_no, 0);
14744
14745     SvPV_set(&PL_sv_yes, (char*)PL_Yes);
14746     SvCUR_set(&PL_sv_yes, 1);
14747     SvLEN_set(&PL_sv_yes, 0);
14748     SvIV_set(&PL_sv_yes, 1);
14749     SvNV_set(&PL_sv_yes, 1);
14750 }
14751
14752 /*
14753 =head1 Unicode Support
14754
14755 =for apidoc sv_recode_to_utf8
14756
14757 The encoding is assumed to be an Encode object, on entry the PV
14758 of the sv is assumed to be octets in that encoding, and the sv
14759 will be converted into Unicode (and UTF-8).
14760
14761 If the sv already is UTF-8 (or if it is not POK), or if the encoding
14762 is not a reference, nothing is done to the sv.  If the encoding is not
14763 an C<Encode::XS> Encoding object, bad things will happen.
14764 (See F<lib/encoding.pm> and L<Encode>.)
14765
14766 The PV of the sv is returned.
14767
14768 =cut */
14769
14770 char *
14771 Perl_sv_recode_to_utf8(pTHX_ SV *sv, SV *encoding)
14772 {
14773     PERL_ARGS_ASSERT_SV_RECODE_TO_UTF8;
14774
14775     if (SvPOK(sv) && !SvUTF8(sv) && !IN_BYTES && SvROK(encoding)) {
14776         SV *uni;
14777         STRLEN len;
14778         const char *s;
14779         dSP;
14780         SV *nsv = sv;
14781         ENTER;
14782         PUSHSTACK;
14783         SAVETMPS;
14784         if (SvPADTMP(nsv)) {
14785             nsv = sv_newmortal();
14786             SvSetSV_nosteal(nsv, sv);
14787         }
14788         save_re_context();
14789         PUSHMARK(sp);
14790         EXTEND(SP, 3);
14791         PUSHs(encoding);
14792         PUSHs(nsv);
14793 /*
14794   NI-S 2002/07/09
14795   Passing sv_yes is wrong - it needs to be or'ed set of constants
14796   for Encode::XS, while UTf-8 decode (currently) assumes a true value means
14797   remove converted chars from source.
14798
14799   Both will default the value - let them.
14800
14801         XPUSHs(&PL_sv_yes);
14802 */
14803         PUTBACK;
14804         call_method("decode", G_SCALAR);
14805         SPAGAIN;
14806         uni = POPs;
14807         PUTBACK;
14808         s = SvPV_const(uni, len);
14809         if (s != SvPVX_const(sv)) {
14810             SvGROW(sv, len + 1);
14811             Move(s, SvPVX(sv), len + 1, char);
14812             SvCUR_set(sv, len);
14813         }
14814         FREETMPS;
14815         POPSTACK;
14816         LEAVE;
14817         if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
14818             /* clear pos and any utf8 cache */
14819             MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
14820             if (mg)
14821                 mg->mg_len = -1;
14822             if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
14823                 magic_setutf8(sv,mg); /* clear UTF8 cache */
14824         }
14825         SvUTF8_on(sv);
14826         return SvPVX(sv);
14827     }
14828     return SvPOKp(sv) ? SvPVX(sv) : NULL;
14829 }
14830
14831 /*
14832 =for apidoc sv_cat_decode
14833
14834 The encoding is assumed to be an Encode object, the PV of the ssv is
14835 assumed to be octets in that encoding and decoding the input starts
14836 from the position which (PV + *offset) pointed to.  The dsv will be
14837 concatenated the decoded UTF-8 string from ssv.  Decoding will terminate
14838 when the string tstr appears in decoding output or the input ends on
14839 the PV of the ssv.  The value which the offset points will be modified
14840 to the last input position on the ssv.
14841
14842 Returns TRUE if the terminator was found, else returns FALSE.
14843
14844 =cut */
14845
14846 bool
14847 Perl_sv_cat_decode(pTHX_ SV *dsv, SV *encoding,
14848                    SV *ssv, int *offset, char *tstr, int tlen)
14849 {
14850     bool ret = FALSE;
14851
14852     PERL_ARGS_ASSERT_SV_CAT_DECODE;
14853
14854     if (SvPOK(ssv) && SvPOK(dsv) && SvROK(encoding) && offset) {
14855         SV *offsv;
14856         dSP;
14857         ENTER;
14858         SAVETMPS;
14859         save_re_context();
14860         PUSHMARK(sp);
14861         EXTEND(SP, 6);
14862         PUSHs(encoding);
14863         PUSHs(dsv);
14864         PUSHs(ssv);
14865         offsv = newSViv(*offset);
14866         mPUSHs(offsv);
14867         mPUSHp(tstr, tlen);
14868         PUTBACK;
14869         call_method("cat_decode", G_SCALAR);
14870         SPAGAIN;
14871         ret = SvTRUE(TOPs);
14872         *offset = SvIV(offsv);
14873         PUTBACK;
14874         FREETMPS;
14875         LEAVE;
14876     }
14877     else
14878         Perl_croak(aTHX_ "Invalid argument to sv_cat_decode");
14879     return ret;
14880
14881 }
14882
14883 /* ---------------------------------------------------------------------
14884  *
14885  * support functions for report_uninit()
14886  */
14887
14888 /* the maxiumum size of array or hash where we will scan looking
14889  * for the undefined element that triggered the warning */
14890
14891 #define FUV_MAX_SEARCH_SIZE 1000
14892
14893 /* Look for an entry in the hash whose value has the same SV as val;
14894  * If so, return a mortal copy of the key. */
14895
14896 STATIC SV*
14897 S_find_hash_subscript(pTHX_ const HV *const hv, const SV *const val)
14898 {
14899     dVAR;
14900     HE **array;
14901     I32 i;
14902
14903     PERL_ARGS_ASSERT_FIND_HASH_SUBSCRIPT;
14904
14905     if (!hv || SvMAGICAL(hv) || !HvARRAY(hv) ||
14906                         (HvTOTALKEYS(hv) > FUV_MAX_SEARCH_SIZE))
14907         return NULL;
14908
14909     array = HvARRAY(hv);
14910
14911     for (i=HvMAX(hv); i>=0; i--) {
14912         HE *entry;
14913         for (entry = array[i]; entry; entry = HeNEXT(entry)) {
14914             if (HeVAL(entry) != val)
14915                 continue;
14916             if (    HeVAL(entry) == &PL_sv_undef ||
14917                     HeVAL(entry) == &PL_sv_placeholder)
14918                 continue;
14919             if (!HeKEY(entry))
14920                 return NULL;
14921             if (HeKLEN(entry) == HEf_SVKEY)
14922                 return sv_mortalcopy(HeKEY_sv(entry));
14923             return sv_2mortal(newSVhek(HeKEY_hek(entry)));
14924         }
14925     }
14926     return NULL;
14927 }
14928
14929 /* Look for an entry in the array whose value has the same SV as val;
14930  * If so, return the index, otherwise return -1. */
14931
14932 STATIC I32
14933 S_find_array_subscript(pTHX_ const AV *const av, const SV *const val)
14934 {
14935     PERL_ARGS_ASSERT_FIND_ARRAY_SUBSCRIPT;
14936
14937     if (!av || SvMAGICAL(av) || !AvARRAY(av) ||
14938                         (AvFILLp(av) > FUV_MAX_SEARCH_SIZE))
14939         return -1;
14940
14941     if (val != &PL_sv_undef) {
14942         SV ** const svp = AvARRAY(av);
14943         I32 i;
14944
14945         for (i=AvFILLp(av); i>=0; i--)
14946             if (svp[i] == val)
14947                 return i;
14948     }
14949     return -1;
14950 }
14951
14952 /* varname(): return the name of a variable, optionally with a subscript.
14953  * If gv is non-zero, use the name of that global, along with gvtype (one
14954  * of "$", "@", "%"); otherwise use the name of the lexical at pad offset
14955  * targ.  Depending on the value of the subscript_type flag, return:
14956  */
14957
14958 #define FUV_SUBSCRIPT_NONE      1       /* "@foo"          */
14959 #define FUV_SUBSCRIPT_ARRAY     2       /* "$foo[aindex]"  */
14960 #define FUV_SUBSCRIPT_HASH      3       /* "$foo{keyname}" */
14961 #define FUV_SUBSCRIPT_WITHIN    4       /* "within @foo"   */
14962
14963 SV*
14964 Perl_varname(pTHX_ const GV *const gv, const char gvtype, PADOFFSET targ,
14965         const SV *const keyname, I32 aindex, int subscript_type)
14966 {
14967
14968     SV * const name = sv_newmortal();
14969     if (gv && isGV(gv)) {
14970         char buffer[2];
14971         buffer[0] = gvtype;
14972         buffer[1] = 0;
14973
14974         /* as gv_fullname4(), but add literal '^' for $^FOO names  */
14975
14976         gv_fullname4(name, gv, buffer, 0);
14977
14978         if ((unsigned int)SvPVX(name)[1] <= 26) {
14979             buffer[0] = '^';
14980             buffer[1] = SvPVX(name)[1] + 'A' - 1;
14981
14982             /* Swap the 1 unprintable control character for the 2 byte pretty
14983                version - ie substr($name, 1, 1) = $buffer; */
14984             sv_insert(name, 1, 1, buffer, 2);
14985         }
14986     }
14987     else {
14988         CV * const cv = gv ? ((CV *)gv) : find_runcv(NULL);
14989         SV *sv;
14990         AV *av;
14991
14992         assert(!cv || SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
14993
14994         if (!cv || !CvPADLIST(cv))
14995             return NULL;
14996         av = *PadlistARRAY(CvPADLIST(cv));
14997         sv = *av_fetch(av, targ, FALSE);
14998         sv_setsv_flags(name, sv, 0);
14999     }
15000
15001     if (subscript_type == FUV_SUBSCRIPT_HASH) {
15002         SV * const sv = newSV(0);
15003         *SvPVX(name) = '$';
15004         Perl_sv_catpvf(aTHX_ name, "{%s}",
15005             pv_pretty(sv, SvPVX_const(keyname), SvCUR(keyname), 32, NULL, NULL,
15006                     PERL_PV_PRETTY_DUMP | PERL_PV_ESCAPE_UNI_DETECT ));
15007         SvREFCNT_dec_NN(sv);
15008     }
15009     else if (subscript_type == FUV_SUBSCRIPT_ARRAY) {
15010         *SvPVX(name) = '$';
15011         Perl_sv_catpvf(aTHX_ name, "[%"IVdf"]", (IV)aindex);
15012     }
15013     else if (subscript_type == FUV_SUBSCRIPT_WITHIN) {
15014         /* We know that name has no magic, so can use 0 instead of SV_GMAGIC */
15015         Perl_sv_insert_flags(aTHX_ name, 0, 0,  STR_WITH_LEN("within "), 0);
15016     }
15017
15018     return name;
15019 }
15020
15021
15022 /*
15023 =for apidoc find_uninit_var
15024
15025 Find the name of the undefined variable (if any) that caused the operator
15026 to issue a "Use of uninitialized value" warning.
15027 If match is true, only return a name if its value matches uninit_sv.
15028 So roughly speaking, if a unary operator (such as OP_COS) generates a
15029 warning, then following the direct child of the op may yield an
15030 OP_PADSV or OP_GV that gives the name of the undefined variable.  On the
15031 other hand, with OP_ADD there are two branches to follow, so we only print
15032 the variable name if we get an exact match.
15033
15034 The name is returned as a mortal SV.
15035
15036 Assumes that PL_op is the op that originally triggered the error, and that
15037 PL_comppad/PL_curpad points to the currently executing pad.
15038
15039 =cut
15040 */
15041
15042 STATIC SV *
15043 S_find_uninit_var(pTHX_ const OP *const obase, const SV *const uninit_sv,
15044                   bool match)
15045 {
15046     dVAR;
15047     SV *sv;
15048     const GV *gv;
15049     const OP *o, *o2, *kid;
15050
15051     if (!obase || (match && (!uninit_sv || uninit_sv == &PL_sv_undef ||
15052                             uninit_sv == &PL_sv_placeholder)))
15053         return NULL;
15054
15055     switch (obase->op_type) {
15056
15057     case OP_RV2AV:
15058     case OP_RV2HV:
15059     case OP_PADAV:
15060     case OP_PADHV:
15061       {
15062         const bool pad  = (    obase->op_type == OP_PADAV
15063                             || obase->op_type == OP_PADHV
15064                             || obase->op_type == OP_PADRANGE
15065                           );
15066
15067         const bool hash = (    obase->op_type == OP_PADHV
15068                             || obase->op_type == OP_RV2HV
15069                             || (obase->op_type == OP_PADRANGE
15070                                 && SvTYPE(PAD_SVl(obase->op_targ)) == SVt_PVHV)
15071                           );
15072         I32 index = 0;
15073         SV *keysv = NULL;
15074         int subscript_type = FUV_SUBSCRIPT_WITHIN;
15075
15076         if (pad) { /* @lex, %lex */
15077             sv = PAD_SVl(obase->op_targ);
15078             gv = NULL;
15079         }
15080         else {
15081             if (cUNOPx(obase)->op_first->op_type == OP_GV) {
15082             /* @global, %global */
15083                 gv = cGVOPx_gv(cUNOPx(obase)->op_first);
15084                 if (!gv)
15085                     break;
15086                 sv = hash ? MUTABLE_SV(GvHV(gv)): MUTABLE_SV(GvAV(gv));
15087             }
15088             else if (obase == PL_op) /* @{expr}, %{expr} */
15089                 return find_uninit_var(cUNOPx(obase)->op_first,
15090                                                     uninit_sv, match);
15091             else /* @{expr}, %{expr} as a sub-expression */
15092                 return NULL;
15093         }
15094
15095         /* attempt to find a match within the aggregate */
15096         if (hash) {
15097             keysv = find_hash_subscript((const HV*)sv, uninit_sv);
15098             if (keysv)
15099                 subscript_type = FUV_SUBSCRIPT_HASH;
15100         }
15101         else {
15102             index = find_array_subscript((const AV *)sv, uninit_sv);
15103             if (index >= 0)
15104                 subscript_type = FUV_SUBSCRIPT_ARRAY;
15105         }
15106
15107         if (match && subscript_type == FUV_SUBSCRIPT_WITHIN)
15108             break;
15109
15110         return varname(gv, hash ? '%' : '@', obase->op_targ,
15111                                     keysv, index, subscript_type);
15112       }
15113
15114     case OP_RV2SV:
15115         if (cUNOPx(obase)->op_first->op_type == OP_GV) {
15116             /* $global */
15117             gv = cGVOPx_gv(cUNOPx(obase)->op_first);
15118             if (!gv || !GvSTASH(gv))
15119                 break;
15120             if (match && (GvSV(gv) != uninit_sv))
15121                 break;
15122             return varname(gv, '$', 0, NULL, 0, FUV_SUBSCRIPT_NONE);
15123         }
15124         /* ${expr} */
15125         return find_uninit_var(cUNOPx(obase)->op_first, uninit_sv, 1);
15126
15127     case OP_PADSV:
15128         if (match && PAD_SVl(obase->op_targ) != uninit_sv)
15129             break;
15130         return varname(NULL, '$', obase->op_targ,
15131                                     NULL, 0, FUV_SUBSCRIPT_NONE);
15132
15133     case OP_GVSV:
15134         gv = cGVOPx_gv(obase);
15135         if (!gv || (match && GvSV(gv) != uninit_sv) || !GvSTASH(gv))
15136             break;
15137         return varname(gv, '$', 0, NULL, 0, FUV_SUBSCRIPT_NONE);
15138
15139     case OP_AELEMFAST_LEX:
15140         if (match) {
15141             SV **svp;
15142             AV *av = MUTABLE_AV(PAD_SV(obase->op_targ));
15143             if (!av || SvRMAGICAL(av))
15144                 break;
15145             svp = av_fetch(av, (I8)obase->op_private, FALSE);
15146             if (!svp || *svp != uninit_sv)
15147                 break;
15148         }
15149         return varname(NULL, '$', obase->op_targ,
15150                        NULL, (I8)obase->op_private, FUV_SUBSCRIPT_ARRAY);
15151     case OP_AELEMFAST:
15152         {
15153             gv = cGVOPx_gv(obase);
15154             if (!gv)
15155                 break;
15156             if (match) {
15157                 SV **svp;
15158                 AV *const av = GvAV(gv);
15159                 if (!av || SvRMAGICAL(av))
15160                     break;
15161                 svp = av_fetch(av, (I8)obase->op_private, FALSE);
15162                 if (!svp || *svp != uninit_sv)
15163                     break;
15164             }
15165             return varname(gv, '$', 0,
15166                     NULL, (I8)obase->op_private, FUV_SUBSCRIPT_ARRAY);
15167         }
15168         NOT_REACHED; /* NOTREACHED */
15169
15170     case OP_EXISTS:
15171         o = cUNOPx(obase)->op_first;
15172         if (!o || o->op_type != OP_NULL ||
15173                 ! (o->op_targ == OP_AELEM || o->op_targ == OP_HELEM))
15174             break;
15175         return find_uninit_var(cBINOPo->op_last, uninit_sv, match);
15176
15177     case OP_AELEM:
15178     case OP_HELEM:
15179     {
15180         bool negate = FALSE;
15181
15182         if (PL_op == obase)
15183             /* $a[uninit_expr] or $h{uninit_expr} */
15184             return find_uninit_var(cBINOPx(obase)->op_last, uninit_sv, match);
15185
15186         gv = NULL;
15187         o = cBINOPx(obase)->op_first;
15188         kid = cBINOPx(obase)->op_last;
15189
15190         /* get the av or hv, and optionally the gv */
15191         sv = NULL;
15192         if  (o->op_type == OP_PADAV || o->op_type == OP_PADHV) {
15193             sv = PAD_SV(o->op_targ);
15194         }
15195         else if ((o->op_type == OP_RV2AV || o->op_type == OP_RV2HV)
15196                 && cUNOPo->op_first->op_type == OP_GV)
15197         {
15198             gv = cGVOPx_gv(cUNOPo->op_first);
15199             if (!gv)
15200                 break;
15201             sv = o->op_type
15202                 == OP_RV2HV ? MUTABLE_SV(GvHV(gv)) : MUTABLE_SV(GvAV(gv));
15203         }
15204         if (!sv)
15205             break;
15206
15207         if (kid && kid->op_type == OP_NEGATE) {
15208             negate = TRUE;
15209             kid = cUNOPx(kid)->op_first;
15210         }
15211
15212         if (kid && kid->op_type == OP_CONST && SvOK(cSVOPx_sv(kid))) {
15213             /* index is constant */
15214             SV* kidsv;
15215             if (negate) {
15216                 kidsv = sv_2mortal(newSVpvs("-"));
15217                 sv_catsv(kidsv, cSVOPx_sv(kid));
15218             }
15219             else
15220                 kidsv = cSVOPx_sv(kid);
15221             if (match) {
15222                 if (SvMAGICAL(sv))
15223                     break;
15224                 if (obase->op_type == OP_HELEM) {
15225                     HE* he = hv_fetch_ent(MUTABLE_HV(sv), kidsv, 0, 0);
15226                     if (!he || HeVAL(he) != uninit_sv)
15227                         break;
15228                 }
15229                 else {
15230                     SV * const  opsv = cSVOPx_sv(kid);
15231                     const IV  opsviv = SvIV(opsv);
15232                     SV * const * const svp = av_fetch(MUTABLE_AV(sv),
15233                         negate ? - opsviv : opsviv,
15234                         FALSE);
15235                     if (!svp || *svp != uninit_sv)
15236                         break;
15237                 }
15238             }
15239             if (obase->op_type == OP_HELEM)
15240                 return varname(gv, '%', o->op_targ,
15241                             kidsv, 0, FUV_SUBSCRIPT_HASH);
15242             else
15243                 return varname(gv, '@', o->op_targ, NULL,
15244                     negate ? - SvIV(cSVOPx_sv(kid)) : SvIV(cSVOPx_sv(kid)),
15245                     FUV_SUBSCRIPT_ARRAY);
15246         }
15247         else  {
15248             /* index is an expression;
15249              * attempt to find a match within the aggregate */
15250             if (obase->op_type == OP_HELEM) {
15251                 SV * const keysv = find_hash_subscript((const HV*)sv, uninit_sv);
15252                 if (keysv)
15253                     return varname(gv, '%', o->op_targ,
15254                                                 keysv, 0, FUV_SUBSCRIPT_HASH);
15255             }
15256             else {
15257                 const I32 index
15258                     = find_array_subscript((const AV *)sv, uninit_sv);
15259                 if (index >= 0)
15260                     return varname(gv, '@', o->op_targ,
15261                                         NULL, index, FUV_SUBSCRIPT_ARRAY);
15262             }
15263             if (match)
15264                 break;
15265             return varname(gv,
15266                 (o->op_type == OP_PADAV || o->op_type == OP_RV2AV)
15267                 ? '@' : '%',
15268                 o->op_targ, NULL, 0, FUV_SUBSCRIPT_WITHIN);
15269         }
15270         NOT_REACHED; /* NOTREACHED */
15271     }
15272
15273     case OP_AASSIGN:
15274         /* only examine RHS */
15275         return find_uninit_var(cBINOPx(obase)->op_first, uninit_sv, match);
15276
15277     case OP_OPEN:
15278         o = cUNOPx(obase)->op_first;
15279         if (   o->op_type == OP_PUSHMARK
15280            || (o->op_type == OP_NULL && o->op_targ == OP_PUSHMARK)
15281         )
15282             o = OP_SIBLING(o);
15283
15284         if (!OP_HAS_SIBLING(o)) {
15285             /* one-arg version of open is highly magical */
15286
15287             if (o->op_type == OP_GV) { /* open FOO; */
15288                 gv = cGVOPx_gv(o);
15289                 if (match && GvSV(gv) != uninit_sv)
15290                     break;
15291                 return varname(gv, '$', 0,
15292                             NULL, 0, FUV_SUBSCRIPT_NONE);
15293             }
15294             /* other possibilities not handled are:
15295              * open $x; or open my $x;  should return '${*$x}'
15296              * open expr;               should return '$'.expr ideally
15297              */
15298              break;
15299         }
15300         goto do_op;
15301
15302     /* ops where $_ may be an implicit arg */
15303     case OP_TRANS:
15304     case OP_TRANSR:
15305     case OP_SUBST:
15306     case OP_MATCH:
15307         if ( !(obase->op_flags & OPf_STACKED)) {
15308             if (uninit_sv == ((obase->op_private & OPpTARGET_MY)
15309                                  ? PAD_SVl(obase->op_targ)
15310                                  : DEFSV))
15311             {
15312                 sv = sv_newmortal();
15313                 sv_setpvs(sv, "$_");
15314                 return sv;
15315             }
15316         }
15317         goto do_op;
15318
15319     case OP_PRTF:
15320     case OP_PRINT:
15321     case OP_SAY:
15322         match = 1; /* print etc can return undef on defined args */
15323         /* skip filehandle as it can't produce 'undef' warning  */
15324         o = cUNOPx(obase)->op_first;
15325         if ((obase->op_flags & OPf_STACKED)
15326             &&
15327                (   o->op_type == OP_PUSHMARK
15328                || (o->op_type == OP_NULL && o->op_targ == OP_PUSHMARK)))
15329             o = OP_SIBLING(OP_SIBLING(o));
15330         goto do_op2;
15331
15332
15333     case OP_ENTEREVAL: /* could be eval $undef or $x='$undef'; eval $x */
15334     case OP_CUSTOM: /* XS or custom code could trigger random warnings */
15335
15336         /* the following ops are capable of returning PL_sv_undef even for
15337          * defined arg(s) */
15338
15339     case OP_BACKTICK:
15340     case OP_PIPE_OP:
15341     case OP_FILENO:
15342     case OP_BINMODE:
15343     case OP_TIED:
15344     case OP_GETC:
15345     case OP_SYSREAD:
15346     case OP_SEND:
15347     case OP_IOCTL:
15348     case OP_SOCKET:
15349     case OP_SOCKPAIR:
15350     case OP_BIND:
15351     case OP_CONNECT:
15352     case OP_LISTEN:
15353     case OP_ACCEPT:
15354     case OP_SHUTDOWN:
15355     case OP_SSOCKOPT:
15356     case OP_GETPEERNAME:
15357     case OP_FTRREAD:
15358     case OP_FTRWRITE:
15359     case OP_FTREXEC:
15360     case OP_FTROWNED:
15361     case OP_FTEREAD:
15362     case OP_FTEWRITE:
15363     case OP_FTEEXEC:
15364     case OP_FTEOWNED:
15365     case OP_FTIS:
15366     case OP_FTZERO:
15367     case OP_FTSIZE:
15368     case OP_FTFILE:
15369     case OP_FTDIR:
15370     case OP_FTLINK:
15371     case OP_FTPIPE:
15372     case OP_FTSOCK:
15373     case OP_FTBLK:
15374     case OP_FTCHR:
15375     case OP_FTTTY:
15376     case OP_FTSUID:
15377     case OP_FTSGID:
15378     case OP_FTSVTX:
15379     case OP_FTTEXT:
15380     case OP_FTBINARY:
15381     case OP_FTMTIME:
15382     case OP_FTATIME:
15383     case OP_FTCTIME:
15384     case OP_READLINK:
15385     case OP_OPEN_DIR:
15386     case OP_READDIR:
15387     case OP_TELLDIR:
15388     case OP_SEEKDIR:
15389     case OP_REWINDDIR:
15390     case OP_CLOSEDIR:
15391     case OP_GMTIME:
15392     case OP_ALARM:
15393     case OP_SEMGET:
15394     case OP_GETLOGIN:
15395     case OP_UNDEF:
15396     case OP_SUBSTR:
15397     case OP_AEACH:
15398     case OP_EACH:
15399     case OP_SORT:
15400     case OP_CALLER:
15401     case OP_DOFILE:
15402     case OP_PROTOTYPE:
15403     case OP_NCMP:
15404     case OP_SMARTMATCH:
15405     case OP_UNPACK:
15406     case OP_SYSOPEN:
15407     case OP_SYSSEEK:
15408         match = 1;
15409         goto do_op;
15410
15411     case OP_ENTERSUB:
15412     case OP_GOTO:
15413         /* XXX tmp hack: these two may call an XS sub, and currently
15414           XS subs don't have a SUB entry on the context stack, so CV and
15415           pad determination goes wrong, and BAD things happen. So, just
15416           don't try to determine the value under those circumstances.
15417           Need a better fix at dome point. DAPM 11/2007 */
15418         break;
15419
15420     case OP_FLIP:
15421     case OP_FLOP:
15422     {
15423         GV * const gv = gv_fetchpvs(".", GV_NOTQUAL, SVt_PV);
15424         if (gv && GvSV(gv) == uninit_sv)
15425             return newSVpvs_flags("$.", SVs_TEMP);
15426         goto do_op;
15427     }
15428
15429     case OP_POS:
15430         /* def-ness of rval pos() is independent of the def-ness of its arg */
15431         if ( !(obase->op_flags & OPf_MOD))
15432             break;
15433
15434     case OP_SCHOMP:
15435     case OP_CHOMP:
15436         if (SvROK(PL_rs) && uninit_sv == SvRV(PL_rs))
15437             return newSVpvs_flags("${$/}", SVs_TEMP);
15438         /* FALLTHROUGH */
15439
15440     default:
15441     do_op:
15442         if (!(obase->op_flags & OPf_KIDS))
15443             break;
15444         o = cUNOPx(obase)->op_first;
15445         
15446     do_op2:
15447         if (!o)
15448             break;
15449
15450         /* This loop checks all the kid ops, skipping any that cannot pos-
15451          * sibly be responsible for the uninitialized value; i.e., defined
15452          * constants and ops that return nothing.  If there is only one op
15453          * left that is not skipped, then we *know* it is responsible for
15454          * the uninitialized value.  If there is more than one op left, we
15455          * have to look for an exact match in the while() loop below.
15456          * Note that we skip padrange, because the individual pad ops that
15457          * it replaced are still in the tree, so we work on them instead.
15458          */
15459         o2 = NULL;
15460         for (kid=o; kid; kid = OP_SIBLING(kid)) {
15461             const OPCODE type = kid->op_type;
15462             if ( (type == OP_CONST && SvOK(cSVOPx_sv(kid)))
15463               || (type == OP_NULL  && ! (kid->op_flags & OPf_KIDS))
15464               || (type == OP_PUSHMARK)
15465               || (type == OP_PADRANGE)
15466             )
15467             continue;
15468
15469             if (o2) { /* more than one found */
15470                 o2 = NULL;
15471                 break;
15472             }
15473             o2 = kid;
15474         }
15475         if (o2)
15476             return find_uninit_var(o2, uninit_sv, match);
15477
15478         /* scan all args */
15479         while (o) {
15480             sv = find_uninit_var(o, uninit_sv, 1);
15481             if (sv)
15482                 return sv;
15483             o = OP_SIBLING(o);
15484         }
15485         break;
15486     }
15487     return NULL;
15488 }
15489
15490
15491 /*
15492 =for apidoc report_uninit
15493
15494 Print appropriate "Use of uninitialized variable" warning.
15495
15496 =cut
15497 */
15498
15499 void
15500 Perl_report_uninit(pTHX_ const SV *uninit_sv)
15501 {
15502     if (PL_op) {
15503         SV* varname = NULL;
15504         if (uninit_sv && PL_curpad) {
15505             varname = find_uninit_var(PL_op, uninit_sv,0);
15506             if (varname)
15507                 sv_insert(varname, 0, 0, " ", 1);
15508         }
15509         /* PL_warn_uninit_sv is constant */
15510         GCC_DIAG_IGNORE(-Wformat-nonliteral);
15511         /* diag_listed_as: Use of uninitialized value%s */
15512         Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit_sv,
15513                 SVfARG(varname ? varname : &PL_sv_no),
15514                 " in ", OP_DESC(PL_op));
15515         GCC_DIAG_RESTORE;
15516     }
15517     else {
15518         /* PL_warn_uninit is constant */
15519         GCC_DIAG_IGNORE(-Wformat-nonliteral);
15520         Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
15521                     "", "", "");
15522         GCC_DIAG_RESTORE;
15523     }
15524 }
15525
15526 /*
15527  * Local variables:
15528  * c-indentation-style: bsd
15529  * c-basic-offset: 4
15530  * indent-tabs-mode: nil
15531  * End:
15532  *
15533  * ex: set ts=8 sts=4 sw=4 et:
15534  */