fix core-cpan-diff treatment of 'undef'
[perl.git] / sv.c
1 /*    sv.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 by Larry Wall
5  *    and others
6  *
7  *    You may distribute under the terms of either the GNU General Public
8  *    License or the Artistic License, as specified in the README file.
9  *
10  */
11
12 /*
13  * 'I wonder what the Entish is for "yes" and "no",' he thought.
14  *                                                      --Pippin
15  *
16  *     [p.480 of _The Lord of the Rings_, III/iv: "Treebeard"]
17  */
18
19 /*
20  *
21  *
22  * This file contains the code that creates, manipulates and destroys
23  * scalar values (SVs). The other types (AV, HV, GV, etc.) reuse the
24  * structure of an SV, so their creation and destruction is handled
25  * here; higher-level functions are in av.c, hv.c, and so on. Opcode
26  * level functions (eg. substr, split, join) for each of the types are
27  * in the pp*.c files.
28  */
29
30 #include "EXTERN.h"
31 #define PERL_IN_SV_C
32 #include "perl.h"
33 #include "regcomp.h"
34
35 #ifndef HAS_C99
36 # if __STDC_VERSION__ >= 199901L && !defined(VMS)
37 #  define HAS_C99 1
38 # endif
39 #endif
40 #if HAS_C99
41 # include <stdint.h>
42 #endif
43
44 #define FCALL *f
45
46 #ifdef __Lynx__
47 /* Missing proto on LynxOS */
48   char *gconvert(double, int, int,  char *);
49 #endif
50
51 #ifdef PERL_UTF8_CACHE_ASSERT
52 /* if adding more checks watch out for the following tests:
53  *   t/op/index.t t/op/length.t t/op/pat.t t/op/substr.t
54  *   lib/utf8.t lib/Unicode/Collate/t/index.t
55  * --jhi
56  */
57 #   define ASSERT_UTF8_CACHE(cache) \
58     STMT_START { if (cache) { assert((cache)[0] <= (cache)[1]); \
59                               assert((cache)[2] <= (cache)[3]); \
60                               assert((cache)[3] <= (cache)[1]);} \
61                               } STMT_END
62 #else
63 #   define ASSERT_UTF8_CACHE(cache) NOOP
64 #endif
65
66 #ifdef PERL_OLD_COPY_ON_WRITE
67 #define SV_COW_NEXT_SV(sv)      INT2PTR(SV *,SvUVX(sv))
68 #define SV_COW_NEXT_SV_SET(current,next)        SvUV_set(current, PTR2UV(next))
69 #endif
70
71 /* ============================================================================
72
73 =head1 Allocation and deallocation of SVs.
74
75 An SV (or AV, HV, etc.) is allocated in two parts: the head (struct
76 sv, av, hv...) contains type and reference count information, and for
77 many types, a pointer to the body (struct xrv, xpv, xpviv...), which
78 contains fields specific to each type.  Some types store all they need
79 in the head, so don't have a body.
80
81 In all but the most memory-paranoid configurations (ex: PURIFY), heads
82 and bodies are allocated out of arenas, which by default are
83 approximately 4K chunks of memory parcelled up into N heads or bodies.
84 Sv-bodies are allocated by their sv-type, guaranteeing size
85 consistency needed to allocate safely from arrays.
86
87 For SV-heads, the first slot in each arena is reserved, and holds a
88 link to the next arena, some flags, and a note of the number of slots.
89 Snaked through each arena chain is a linked list of free items; when
90 this becomes empty, an extra arena is allocated and divided up into N
91 items which are threaded into the free list.
92
93 SV-bodies are similar, but they use arena-sets by default, which
94 separate the link and info from the arena itself, and reclaim the 1st
95 slot in the arena.  SV-bodies are further described later.
96
97 The following global variables are associated with arenas:
98
99     PL_sv_arenaroot     pointer to list of SV arenas
100     PL_sv_root          pointer to list of free SV structures
101
102     PL_body_arenas      head of linked-list of body arenas
103     PL_body_roots[]     array of pointers to list of free bodies of svtype
104                         arrays are indexed by the svtype needed
105
106 A few special SV heads are not allocated from an arena, but are
107 instead directly created in the interpreter structure, eg PL_sv_undef.
108 The size of arenas can be changed from the default by setting
109 PERL_ARENA_SIZE appropriately at compile time.
110
111 The SV arena serves the secondary purpose of allowing still-live SVs
112 to be located and destroyed during final cleanup.
113
114 At the lowest level, the macros new_SV() and del_SV() grab and free
115 an SV head.  (If debugging with -DD, del_SV() calls the function S_del_sv()
116 to return the SV to the free list with error checking.) new_SV() calls
117 more_sv() / sv_add_arena() to add an extra arena if the free list is empty.
118 SVs in the free list have their SvTYPE field set to all ones.
119
120 At the time of very final cleanup, sv_free_arenas() is called from
121 perl_destruct() to physically free all the arenas allocated since the
122 start of the interpreter.
123
124 The function visit() scans the SV arenas list, and calls a specified
125 function for each SV it finds which is still live - ie which has an SvTYPE
126 other than all 1's, and a non-zero SvREFCNT. visit() is used by the
127 following functions (specified as [function that calls visit()] / [function
128 called by visit() for each SV]):
129
130     sv_report_used() / do_report_used()
131                         dump all remaining SVs (debugging aid)
132
133     sv_clean_objs() / do_clean_objs(),do_clean_named_objs(),
134                       do_clean_named_io_objs(),do_curse()
135                         Attempt to free all objects pointed to by RVs,
136                         try to do the same for all objects indir-
137                         ectly referenced by typeglobs too, and
138                         then do a final sweep, cursing any
139                         objects that remain.  Called once from
140                         perl_destruct(), prior to calling sv_clean_all()
141                         below.
142
143     sv_clean_all() / do_clean_all()
144                         SvREFCNT_dec(sv) each remaining SV, possibly
145                         triggering an sv_free(). It also sets the
146                         SVf_BREAK flag on the SV to indicate that the
147                         refcnt has been artificially lowered, and thus
148                         stopping sv_free() from giving spurious warnings
149                         about SVs which unexpectedly have a refcnt
150                         of zero.  called repeatedly from perl_destruct()
151                         until there are no SVs left.
152
153 =head2 Arena allocator API Summary
154
155 Private API to rest of sv.c
156
157     new_SV(),  del_SV(),
158
159     new_XPVNV(), del_XPVGV(),
160     etc
161
162 Public API:
163
164     sv_report_used(), sv_clean_objs(), sv_clean_all(), sv_free_arenas()
165
166 =cut
167
168  * ========================================================================= */
169
170 /*
171  * "A time to plant, and a time to uproot what was planted..."
172  */
173
174 #ifdef PERL_MEM_LOG
175 #  define MEM_LOG_NEW_SV(sv, file, line, func)  \
176             Perl_mem_log_new_sv(sv, file, line, func)
177 #  define MEM_LOG_DEL_SV(sv, file, line, func)  \
178             Perl_mem_log_del_sv(sv, file, line, func)
179 #else
180 #  define MEM_LOG_NEW_SV(sv, file, line, func)  NOOP
181 #  define MEM_LOG_DEL_SV(sv, file, line, func)  NOOP
182 #endif
183
184 #ifdef DEBUG_LEAKING_SCALARS
185 #  define FREE_SV_DEBUG_FILE(sv) STMT_START { \
186         if ((sv)->sv_debug_file) PerlMemShared_free((sv)->sv_debug_file); \
187     } STMT_END
188 #  define DEBUG_SV_SERIAL(sv)                                               \
189     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) del_SV\n",    \
190             PTR2UV(sv), (long)(sv)->sv_debug_serial))
191 #else
192 #  define FREE_SV_DEBUG_FILE(sv)
193 #  define DEBUG_SV_SERIAL(sv)   NOOP
194 #endif
195
196 #ifdef PERL_POISON
197 #  define SvARENA_CHAIN(sv)     ((sv)->sv_u.svu_rv)
198 #  define SvARENA_CHAIN_SET(sv,val)     (sv)->sv_u.svu_rv = MUTABLE_SV((val))
199 /* Whilst I'd love to do this, it seems that things like to check on
200    unreferenced scalars
201 #  define POSION_SV_HEAD(sv)    PoisonNew(sv, 1, struct STRUCT_SV)
202 */
203 #  define POSION_SV_HEAD(sv)    PoisonNew(&SvANY(sv), 1, void *), \
204                                 PoisonNew(&SvREFCNT(sv), 1, U32)
205 #else
206 #  define SvARENA_CHAIN(sv)     SvANY(sv)
207 #  define SvARENA_CHAIN_SET(sv,val)     SvANY(sv) = (void *)(val)
208 #  define POSION_SV_HEAD(sv)
209 #endif
210
211 /* Mark an SV head as unused, and add to free list.
212  *
213  * If SVf_BREAK is set, skip adding it to the free list, as this SV had
214  * its refcount artificially decremented during global destruction, so
215  * there may be dangling pointers to it. The last thing we want in that
216  * case is for it to be reused. */
217
218 #define plant_SV(p) \
219     STMT_START {                                        \
220         const U32 old_flags = SvFLAGS(p);                       \
221         MEM_LOG_DEL_SV(p, __FILE__, __LINE__, FUNCTION__);  \
222         DEBUG_SV_SERIAL(p);                             \
223         FREE_SV_DEBUG_FILE(p);                          \
224         POSION_SV_HEAD(p);                              \
225         SvFLAGS(p) = SVTYPEMASK;                        \
226         if (!(old_flags & SVf_BREAK)) {         \
227             SvARENA_CHAIN_SET(p, PL_sv_root);   \
228             PL_sv_root = (p);                           \
229         }                                               \
230         --PL_sv_count;                                  \
231     } STMT_END
232
233 #define uproot_SV(p) \
234     STMT_START {                                        \
235         (p) = PL_sv_root;                               \
236         PL_sv_root = MUTABLE_SV(SvARENA_CHAIN(p));              \
237         ++PL_sv_count;                                  \
238     } STMT_END
239
240
241 /* make some more SVs by adding another arena */
242
243 STATIC SV*
244 S_more_sv(pTHX)
245 {
246     dVAR;
247     SV* sv;
248     char *chunk;                /* must use New here to match call to */
249     Newx(chunk,PERL_ARENA_SIZE,char);  /* Safefree() in sv_free_arenas() */
250     sv_add_arena(chunk, PERL_ARENA_SIZE, 0);
251     uproot_SV(sv);
252     return sv;
253 }
254
255 /* new_SV(): return a new, empty SV head */
256
257 #ifdef DEBUG_LEAKING_SCALARS
258 /* provide a real function for a debugger to play with */
259 STATIC SV*
260 S_new_SV(pTHX_ const char *file, int line, const char *func)
261 {
262     SV* sv;
263
264     if (PL_sv_root)
265         uproot_SV(sv);
266     else
267         sv = S_more_sv(aTHX);
268     SvANY(sv) = 0;
269     SvREFCNT(sv) = 1;
270     SvFLAGS(sv) = 0;
271     sv->sv_debug_optype = PL_op ? PL_op->op_type : 0;
272     sv->sv_debug_line = (U16) (PL_parser && PL_parser->copline != NOLINE
273                 ? PL_parser->copline
274                 :  PL_curcop
275                     ? CopLINE(PL_curcop)
276                     : 0
277             );
278     sv->sv_debug_inpad = 0;
279     sv->sv_debug_parent = NULL;
280     sv->sv_debug_file = PL_curcop ? savesharedpv(CopFILE(PL_curcop)): NULL;
281
282     sv->sv_debug_serial = PL_sv_serial++;
283
284     MEM_LOG_NEW_SV(sv, file, line, func);
285     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) new_SV (from %s:%d [%s])\n",
286             PTR2UV(sv), (long)sv->sv_debug_serial, file, line, func));
287
288     return sv;
289 }
290 #  define new_SV(p) (p)=S_new_SV(aTHX_ __FILE__, __LINE__, FUNCTION__)
291
292 #else
293 #  define new_SV(p) \
294     STMT_START {                                        \
295         if (PL_sv_root)                                 \
296             uproot_SV(p);                               \
297         else                                            \
298             (p) = S_more_sv(aTHX);                      \
299         SvANY(p) = 0;                                   \
300         SvREFCNT(p) = 1;                                \
301         SvFLAGS(p) = 0;                                 \
302         MEM_LOG_NEW_SV(p, __FILE__, __LINE__, FUNCTION__);  \
303     } STMT_END
304 #endif
305
306
307 /* del_SV(): return an empty SV head to the free list */
308
309 #ifdef DEBUGGING
310
311 #define del_SV(p) \
312     STMT_START {                                        \
313         if (DEBUG_D_TEST)                               \
314             del_sv(p);                                  \
315         else                                            \
316             plant_SV(p);                                \
317     } STMT_END
318
319 STATIC void
320 S_del_sv(pTHX_ SV *p)
321 {
322     dVAR;
323
324     PERL_ARGS_ASSERT_DEL_SV;
325
326     if (DEBUG_D_TEST) {
327         SV* sva;
328         bool ok = 0;
329         for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
330             const SV * const sv = sva + 1;
331             const SV * const svend = &sva[SvREFCNT(sva)];
332             if (p >= sv && p < svend) {
333                 ok = 1;
334                 break;
335             }
336         }
337         if (!ok) {
338             Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
339                              "Attempt to free non-arena SV: 0x%"UVxf
340                              pTHX__FORMAT, PTR2UV(p) pTHX__VALUE);
341             return;
342         }
343     }
344     plant_SV(p);
345 }
346
347 #else /* ! DEBUGGING */
348
349 #define del_SV(p)   plant_SV(p)
350
351 #endif /* DEBUGGING */
352
353
354 /*
355 =head1 SV Manipulation Functions
356
357 =for apidoc sv_add_arena
358
359 Given a chunk of memory, link it to the head of the list of arenas,
360 and split it into a list of free SVs.
361
362 =cut
363 */
364
365 static void
366 S_sv_add_arena(pTHX_ char *const ptr, const U32 size, const U32 flags)
367 {
368     dVAR;
369     SV *const sva = MUTABLE_SV(ptr);
370     SV* sv;
371     SV* svend;
372
373     PERL_ARGS_ASSERT_SV_ADD_ARENA;
374
375     /* The first SV in an arena isn't an SV. */
376     SvANY(sva) = (void *) PL_sv_arenaroot;              /* ptr to next arena */
377     SvREFCNT(sva) = size / sizeof(SV);          /* number of SV slots */
378     SvFLAGS(sva) = flags;                       /* FAKE if not to be freed */
379
380     PL_sv_arenaroot = sva;
381     PL_sv_root = sva + 1;
382
383     svend = &sva[SvREFCNT(sva) - 1];
384     sv = sva + 1;
385     while (sv < svend) {
386         SvARENA_CHAIN_SET(sv, (sv + 1));
387 #ifdef DEBUGGING
388         SvREFCNT(sv) = 0;
389 #endif
390         /* Must always set typemask because it's always checked in on cleanup
391            when the arenas are walked looking for objects.  */
392         SvFLAGS(sv) = SVTYPEMASK;
393         sv++;
394     }
395     SvARENA_CHAIN_SET(sv, 0);
396 #ifdef DEBUGGING
397     SvREFCNT(sv) = 0;
398 #endif
399     SvFLAGS(sv) = SVTYPEMASK;
400 }
401
402 /* visit(): call the named function for each non-free SV in the arenas
403  * whose flags field matches the flags/mask args. */
404
405 STATIC I32
406 S_visit(pTHX_ SVFUNC_t f, const U32 flags, const U32 mask)
407 {
408     dVAR;
409     SV* sva;
410     I32 visited = 0;
411
412     PERL_ARGS_ASSERT_VISIT;
413
414     for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
415         const SV * const svend = &sva[SvREFCNT(sva)];
416         SV* sv;
417         for (sv = sva + 1; sv < svend; ++sv) {
418             if (SvTYPE(sv) != (svtype)SVTYPEMASK
419                     && (sv->sv_flags & mask) == flags
420                     && SvREFCNT(sv))
421             {
422                 (FCALL)(aTHX_ sv);
423                 ++visited;
424             }
425         }
426     }
427     return visited;
428 }
429
430 #ifdef DEBUGGING
431
432 /* called by sv_report_used() for each live SV */
433
434 static void
435 do_report_used(pTHX_ SV *const sv)
436 {
437     if (SvTYPE(sv) != (svtype)SVTYPEMASK) {
438         PerlIO_printf(Perl_debug_log, "****\n");
439         sv_dump(sv);
440     }
441 }
442 #endif
443
444 /*
445 =for apidoc sv_report_used
446
447 Dump the contents of all SVs not yet freed (debugging aid).
448
449 =cut
450 */
451
452 void
453 Perl_sv_report_used(pTHX)
454 {
455 #ifdef DEBUGGING
456     visit(do_report_used, 0, 0);
457 #else
458     PERL_UNUSED_CONTEXT;
459 #endif
460 }
461
462 /* called by sv_clean_objs() for each live SV */
463
464 static void
465 do_clean_objs(pTHX_ SV *const ref)
466 {
467     dVAR;
468     assert (SvROK(ref));
469     {
470         SV * const target = SvRV(ref);
471         if (SvOBJECT(target)) {
472             DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning object ref:\n "), sv_dump(ref)));
473             if (SvWEAKREF(ref)) {
474                 sv_del_backref(target, ref);
475                 SvWEAKREF_off(ref);
476                 SvRV_set(ref, NULL);
477             } else {
478                 SvROK_off(ref);
479                 SvRV_set(ref, NULL);
480                 SvREFCNT_dec_NN(target);
481             }
482         }
483     }
484 }
485
486
487 /* clear any slots in a GV which hold objects - except IO;
488  * called by sv_clean_objs() for each live GV */
489
490 static void
491 do_clean_named_objs(pTHX_ SV *const sv)
492 {
493     dVAR;
494     SV *obj;
495     assert(SvTYPE(sv) == SVt_PVGV);
496     assert(isGV_with_GP(sv));
497     if (!GvGP(sv))
498         return;
499
500     /* freeing GP entries may indirectly free the current GV;
501      * hold onto it while we mess with the GP slots */
502     SvREFCNT_inc(sv);
503
504     if ( ((obj = GvSV(sv) )) && SvOBJECT(obj)) {
505         DEBUG_D((PerlIO_printf(Perl_debug_log,
506                 "Cleaning named glob SV object:\n "), sv_dump(obj)));
507         GvSV(sv) = NULL;
508         SvREFCNT_dec_NN(obj);
509     }
510     if ( ((obj = MUTABLE_SV(GvAV(sv)) )) && SvOBJECT(obj)) {
511         DEBUG_D((PerlIO_printf(Perl_debug_log,
512                 "Cleaning named glob AV object:\n "), sv_dump(obj)));
513         GvAV(sv) = NULL;
514         SvREFCNT_dec_NN(obj);
515     }
516     if ( ((obj = MUTABLE_SV(GvHV(sv)) )) && SvOBJECT(obj)) {
517         DEBUG_D((PerlIO_printf(Perl_debug_log,
518                 "Cleaning named glob HV object:\n "), sv_dump(obj)));
519         GvHV(sv) = NULL;
520         SvREFCNT_dec_NN(obj);
521     }
522     if ( ((obj = MUTABLE_SV(GvCV(sv)) )) && SvOBJECT(obj)) {
523         DEBUG_D((PerlIO_printf(Perl_debug_log,
524                 "Cleaning named glob CV object:\n "), sv_dump(obj)));
525         GvCV_set(sv, NULL);
526         SvREFCNT_dec_NN(obj);
527     }
528     SvREFCNT_dec_NN(sv); /* undo the inc above */
529 }
530
531 /* clear any IO slots in a GV which hold objects (except stderr, defout);
532  * called by sv_clean_objs() for each live GV */
533
534 static void
535 do_clean_named_io_objs(pTHX_ SV *const sv)
536 {
537     dVAR;
538     SV *obj;
539     assert(SvTYPE(sv) == SVt_PVGV);
540     assert(isGV_with_GP(sv));
541     if (!GvGP(sv) || sv == (SV*)PL_stderrgv || sv == (SV*)PL_defoutgv)
542         return;
543
544     SvREFCNT_inc(sv);
545     if ( ((obj = MUTABLE_SV(GvIO(sv)) )) && SvOBJECT(obj)) {
546         DEBUG_D((PerlIO_printf(Perl_debug_log,
547                 "Cleaning named glob IO object:\n "), sv_dump(obj)));
548         GvIOp(sv) = NULL;
549         SvREFCNT_dec_NN(obj);
550     }
551     SvREFCNT_dec_NN(sv); /* undo the inc above */
552 }
553
554 /* Void wrapper to pass to visit() */
555 static void
556 do_curse(pTHX_ SV * const sv) {
557     if ((PL_stderrgv && GvGP(PL_stderrgv) && (SV*)GvIO(PL_stderrgv) == sv)
558      || (PL_defoutgv && GvGP(PL_defoutgv) && (SV*)GvIO(PL_defoutgv) == sv))
559         return;
560     (void)curse(sv, 0);
561 }
562
563 /*
564 =for apidoc sv_clean_objs
565
566 Attempt to destroy all objects not yet freed.
567
568 =cut
569 */
570
571 void
572 Perl_sv_clean_objs(pTHX)
573 {
574     dVAR;
575     GV *olddef, *olderr;
576     PL_in_clean_objs = TRUE;
577     visit(do_clean_objs, SVf_ROK, SVf_ROK);
578     /* Some barnacles may yet remain, clinging to typeglobs.
579      * Run the non-IO destructors first: they may want to output
580      * error messages, close files etc */
581     visit(do_clean_named_objs, SVt_PVGV|SVpgv_GP, SVTYPEMASK|SVp_POK|SVpgv_GP);
582     visit(do_clean_named_io_objs, SVt_PVGV|SVpgv_GP, SVTYPEMASK|SVp_POK|SVpgv_GP);
583     /* And if there are some very tenacious barnacles clinging to arrays,
584        closures, or what have you.... */
585     visit(do_curse, SVs_OBJECT, SVs_OBJECT);
586     olddef = PL_defoutgv;
587     PL_defoutgv = NULL; /* disable skip of PL_defoutgv */
588     if (olddef && isGV_with_GP(olddef))
589         do_clean_named_io_objs(aTHX_ MUTABLE_SV(olddef));
590     olderr = PL_stderrgv;
591     PL_stderrgv = NULL; /* disable skip of PL_stderrgv */
592     if (olderr && isGV_with_GP(olderr))
593         do_clean_named_io_objs(aTHX_ MUTABLE_SV(olderr));
594     SvREFCNT_dec(olddef);
595     PL_in_clean_objs = FALSE;
596 }
597
598 /* called by sv_clean_all() for each live SV */
599
600 static void
601 do_clean_all(pTHX_ SV *const sv)
602 {
603     dVAR;
604     if (sv == (const SV *) PL_fdpid || sv == (const SV *)PL_strtab) {
605         /* don't clean pid table and strtab */
606         return;
607     }
608     DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning loops: SV at 0x%"UVxf"\n", PTR2UV(sv)) ));
609     SvFLAGS(sv) |= SVf_BREAK;
610     SvREFCNT_dec_NN(sv);
611 }
612
613 /*
614 =for apidoc sv_clean_all
615
616 Decrement the refcnt of each remaining SV, possibly triggering a
617 cleanup.  This function may have to be called multiple times to free
618 SVs which are in complex self-referential hierarchies.
619
620 =cut
621 */
622
623 I32
624 Perl_sv_clean_all(pTHX)
625 {
626     dVAR;
627     I32 cleaned;
628     PL_in_clean_all = TRUE;
629     cleaned = visit(do_clean_all, 0,0);
630     return cleaned;
631 }
632
633 /*
634   ARENASETS: a meta-arena implementation which separates arena-info
635   into struct arena_set, which contains an array of struct
636   arena_descs, each holding info for a single arena.  By separating
637   the meta-info from the arena, we recover the 1st slot, formerly
638   borrowed for list management.  The arena_set is about the size of an
639   arena, avoiding the needless malloc overhead of a naive linked-list.
640
641   The cost is 1 arena-set malloc per ~320 arena-mallocs, + the unused
642   memory in the last arena-set (1/2 on average).  In trade, we get
643   back the 1st slot in each arena (ie 1.7% of a CV-arena, less for
644   smaller types).  The recovery of the wasted space allows use of
645   small arenas for large, rare body types, by changing array* fields
646   in body_details_by_type[] below.
647 */
648 struct arena_desc {
649     char       *arena;          /* the raw storage, allocated aligned */
650     size_t      size;           /* its size ~4k typ */
651     svtype      utype;          /* bodytype stored in arena */
652 };
653
654 struct arena_set;
655
656 /* Get the maximum number of elements in set[] such that struct arena_set
657    will fit within PERL_ARENA_SIZE, which is probably just under 4K, and
658    therefore likely to be 1 aligned memory page.  */
659
660 #define ARENAS_PER_SET  ((PERL_ARENA_SIZE - sizeof(struct arena_set*) \
661                           - 2 * sizeof(int)) / sizeof (struct arena_desc))
662
663 struct arena_set {
664     struct arena_set* next;
665     unsigned int   set_size;    /* ie ARENAS_PER_SET */
666     unsigned int   curr;        /* index of next available arena-desc */
667     struct arena_desc set[ARENAS_PER_SET];
668 };
669
670 /*
671 =for apidoc sv_free_arenas
672
673 Deallocate the memory used by all arenas.  Note that all the individual SV
674 heads and bodies within the arenas must already have been freed.
675
676 =cut
677 */
678 void
679 Perl_sv_free_arenas(pTHX)
680 {
681     dVAR;
682     SV* sva;
683     SV* svanext;
684     unsigned int i;
685
686     /* Free arenas here, but be careful about fake ones.  (We assume
687        contiguity of the fake ones with the corresponding real ones.) */
688
689     for (sva = PL_sv_arenaroot; sva; sva = svanext) {
690         svanext = MUTABLE_SV(SvANY(sva));
691         while (svanext && SvFAKE(svanext))
692             svanext = MUTABLE_SV(SvANY(svanext));
693
694         if (!SvFAKE(sva))
695             Safefree(sva);
696     }
697
698     {
699         struct arena_set *aroot = (struct arena_set*) PL_body_arenas;
700
701         while (aroot) {
702             struct arena_set *current = aroot;
703             i = aroot->curr;
704             while (i--) {
705                 assert(aroot->set[i].arena);
706                 Safefree(aroot->set[i].arena);
707             }
708             aroot = aroot->next;
709             Safefree(current);
710         }
711     }
712     PL_body_arenas = 0;
713
714     i = PERL_ARENA_ROOTS_SIZE;
715     while (i--)
716         PL_body_roots[i] = 0;
717
718     PL_sv_arenaroot = 0;
719     PL_sv_root = 0;
720 }
721
722 /*
723   Here are mid-level routines that manage the allocation of bodies out
724   of the various arenas.  There are 5 kinds of arenas:
725
726   1. SV-head arenas, which are discussed and handled above
727   2. regular body arenas
728   3. arenas for reduced-size bodies
729   4. Hash-Entry arenas
730
731   Arena types 2 & 3 are chained by body-type off an array of
732   arena-root pointers, which is indexed by svtype.  Some of the
733   larger/less used body types are malloced singly, since a large
734   unused block of them is wasteful.  Also, several svtypes dont have
735   bodies; the data fits into the sv-head itself.  The arena-root
736   pointer thus has a few unused root-pointers (which may be hijacked
737   later for arena types 4,5)
738
739   3 differs from 2 as an optimization; some body types have several
740   unused fields in the front of the structure (which are kept in-place
741   for consistency).  These bodies can be allocated in smaller chunks,
742   because the leading fields arent accessed.  Pointers to such bodies
743   are decremented to point at the unused 'ghost' memory, knowing that
744   the pointers are used with offsets to the real memory.
745
746
747 =head1 SV-Body Allocation
748
749 Allocation of SV-bodies is similar to SV-heads, differing as follows;
750 the allocation mechanism is used for many body types, so is somewhat
751 more complicated, it uses arena-sets, and has no need for still-live
752 SV detection.
753
754 At the outermost level, (new|del)_X*V macros return bodies of the
755 appropriate type.  These macros call either (new|del)_body_type or
756 (new|del)_body_allocated macro pairs, depending on specifics of the
757 type.  Most body types use the former pair, the latter pair is used to
758 allocate body types with "ghost fields".
759
760 "ghost fields" are fields that are unused in certain types, and
761 consequently don't need to actually exist.  They are declared because
762 they're part of a "base type", which allows use of functions as
763 methods.  The simplest examples are AVs and HVs, 2 aggregate types
764 which don't use the fields which support SCALAR semantics.
765
766 For these types, the arenas are carved up into appropriately sized
767 chunks, we thus avoid wasted memory for those unaccessed members.
768 When bodies are allocated, we adjust the pointer back in memory by the
769 size of the part not allocated, so it's as if we allocated the full
770 structure.  (But things will all go boom if you write to the part that
771 is "not there", because you'll be overwriting the last members of the
772 preceding structure in memory.)
773
774 We calculate the correction using the STRUCT_OFFSET macro on the first
775 member present. If the allocated structure is smaller (no initial NV
776 actually allocated) then the net effect is to subtract the size of the NV
777 from the pointer, to return a new pointer as if an initial NV were actually
778 allocated. (We were using structures named *_allocated for this, but
779 this turned out to be a subtle bug, because a structure without an NV
780 could have a lower alignment constraint, but the compiler is allowed to
781 optimised accesses based on the alignment constraint of the actual pointer
782 to the full structure, for example, using a single 64 bit load instruction
783 because it "knows" that two adjacent 32 bit members will be 8-byte aligned.)
784
785 This is the same trick as was used for NV and IV bodies. Ironically it
786 doesn't need to be used for NV bodies any more, because NV is now at
787 the start of the structure. IV bodies don't need it either, because
788 they are no longer allocated.
789
790 In turn, the new_body_* allocators call S_new_body(), which invokes
791 new_body_inline macro, which takes a lock, and takes a body off the
792 linked list at PL_body_roots[sv_type], calling Perl_more_bodies() if
793 necessary to refresh an empty list.  Then the lock is released, and
794 the body is returned.
795
796 Perl_more_bodies allocates a new arena, and carves it up into an array of N
797 bodies, which it strings into a linked list.  It looks up arena-size
798 and body-size from the body_details table described below, thus
799 supporting the multiple body-types.
800
801 If PURIFY is defined, or PERL_ARENA_SIZE=0, arenas are not used, and
802 the (new|del)_X*V macros are mapped directly to malloc/free.
803
804 For each sv-type, struct body_details bodies_by_type[] carries
805 parameters which control these aspects of SV handling:
806
807 Arena_size determines whether arenas are used for this body type, and if
808 so, how big they are.  PURIFY or PERL_ARENA_SIZE=0 set this field to
809 zero, forcing individual mallocs and frees.
810
811 Body_size determines how big a body is, and therefore how many fit into
812 each arena.  Offset carries the body-pointer adjustment needed for
813 "ghost fields", and is used in *_allocated macros.
814
815 But its main purpose is to parameterize info needed in
816 Perl_sv_upgrade().  The info here dramatically simplifies the function
817 vs the implementation in 5.8.8, making it table-driven.  All fields
818 are used for this, except for arena_size.
819
820 For the sv-types that have no bodies, arenas are not used, so those
821 PL_body_roots[sv_type] are unused, and can be overloaded.  In
822 something of a special case, SVt_NULL is borrowed for HE arenas;
823 PL_body_roots[HE_SVSLOT=SVt_NULL] is filled by S_more_he, but the
824 bodies_by_type[SVt_NULL] slot is not used, as the table is not
825 available in hv.c.
826
827 */
828
829 struct body_details {
830     U8 body_size;       /* Size to allocate  */
831     U8 copy;            /* Size of structure to copy (may be shorter)  */
832     U8 offset;
833     unsigned int type : 4;          /* We have space for a sanity check.  */
834     unsigned int cant_upgrade : 1;  /* Cannot upgrade this type */
835     unsigned int zero_nv : 1;       /* zero the NV when upgrading from this */
836     unsigned int arena : 1;         /* Allocated from an arena */
837     size_t arena_size;              /* Size of arena to allocate */
838 };
839
840 #define HADNV FALSE
841 #define NONV TRUE
842
843
844 #ifdef PURIFY
845 /* With -DPURFIY we allocate everything directly, and don't use arenas.
846    This seems a rather elegant way to simplify some of the code below.  */
847 #define HASARENA FALSE
848 #else
849 #define HASARENA TRUE
850 #endif
851 #define NOARENA FALSE
852
853 /* Size the arenas to exactly fit a given number of bodies.  A count
854    of 0 fits the max number bodies into a PERL_ARENA_SIZE.block,
855    simplifying the default.  If count > 0, the arena is sized to fit
856    only that many bodies, allowing arenas to be used for large, rare
857    bodies (XPVFM, XPVIO) without undue waste.  The arena size is
858    limited by PERL_ARENA_SIZE, so we can safely oversize the
859    declarations.
860  */
861 #define FIT_ARENA0(body_size)                           \
862     ((size_t)(PERL_ARENA_SIZE / body_size) * body_size)
863 #define FIT_ARENAn(count,body_size)                     \
864     ( count * body_size <= PERL_ARENA_SIZE)             \
865     ? count * body_size                                 \
866     : FIT_ARENA0 (body_size)
867 #define FIT_ARENA(count,body_size)                      \
868     count                                               \
869     ? FIT_ARENAn (count, body_size)                     \
870     : FIT_ARENA0 (body_size)
871
872 /* Calculate the length to copy. Specifically work out the length less any
873    final padding the compiler needed to add.  See the comment in sv_upgrade
874    for why copying the padding proved to be a bug.  */
875
876 #define copy_length(type, last_member) \
877         STRUCT_OFFSET(type, last_member) \
878         + sizeof (((type*)SvANY((const SV *)0))->last_member)
879
880 static const struct body_details bodies_by_type[] = {
881     /* HEs use this offset for their arena.  */
882     { 0, 0, 0, SVt_NULL, FALSE, NONV, NOARENA, 0 },
883
884     /* The bind placeholder pretends to be an RV for now.
885        Also it's marked as "can't upgrade" to stop anyone using it before it's
886        implemented.  */
887     { 0, 0, 0, SVt_DUMMY, TRUE, NONV, NOARENA, 0 },
888
889     /* IVs are in the head, so the allocation size is 0.  */
890     { 0,
891       sizeof(IV), /* This is used to copy out the IV body.  */
892       STRUCT_OFFSET(XPVIV, xiv_iv), SVt_IV, FALSE, NONV,
893       NOARENA /* IVS don't need an arena  */, 0
894     },
895
896     { sizeof(NV), sizeof(NV),
897       STRUCT_OFFSET(XPVNV, xnv_u),
898       SVt_NV, FALSE, HADNV, HASARENA, FIT_ARENA(0, sizeof(NV)) },
899
900     { sizeof(XPV) - STRUCT_OFFSET(XPV, xpv_cur),
901       copy_length(XPV, xpv_len) - STRUCT_OFFSET(XPV, xpv_cur),
902       + STRUCT_OFFSET(XPV, xpv_cur),
903       SVt_PV, FALSE, NONV, HASARENA,
904       FIT_ARENA(0, sizeof(XPV) - STRUCT_OFFSET(XPV, xpv_cur)) },
905
906     { sizeof(XPVIV) - STRUCT_OFFSET(XPV, xpv_cur),
907       copy_length(XPVIV, xiv_u) - STRUCT_OFFSET(XPV, xpv_cur),
908       + STRUCT_OFFSET(XPV, xpv_cur),
909       SVt_PVIV, FALSE, NONV, HASARENA,
910       FIT_ARENA(0, sizeof(XPVIV) - STRUCT_OFFSET(XPV, xpv_cur)) },
911
912     { sizeof(XPVNV) - STRUCT_OFFSET(XPV, xpv_cur),
913       copy_length(XPVNV, xnv_u) - STRUCT_OFFSET(XPV, xpv_cur),
914       + STRUCT_OFFSET(XPV, xpv_cur),
915       SVt_PVNV, FALSE, HADNV, HASARENA,
916       FIT_ARENA(0, sizeof(XPVNV) - STRUCT_OFFSET(XPV, xpv_cur)) },
917
918     { sizeof(XPVMG), copy_length(XPVMG, xnv_u), 0, SVt_PVMG, FALSE, HADNV,
919       HASARENA, FIT_ARENA(0, sizeof(XPVMG)) },
920
921     { sizeof(regexp),
922       sizeof(regexp),
923       0,
924       SVt_REGEXP, FALSE, NONV, HASARENA,
925       FIT_ARENA(0, sizeof(regexp))
926     },
927
928     { sizeof(XPVGV), sizeof(XPVGV), 0, SVt_PVGV, TRUE, HADNV,
929       HASARENA, FIT_ARENA(0, sizeof(XPVGV)) },
930     
931     { sizeof(XPVLV), sizeof(XPVLV), 0, SVt_PVLV, TRUE, HADNV,
932       HASARENA, FIT_ARENA(0, sizeof(XPVLV)) },
933
934     { sizeof(XPVAV),
935       copy_length(XPVAV, xav_alloc),
936       0,
937       SVt_PVAV, TRUE, NONV, HASARENA,
938       FIT_ARENA(0, sizeof(XPVAV)) },
939
940     { sizeof(XPVHV),
941       copy_length(XPVHV, xhv_max),
942       0,
943       SVt_PVHV, TRUE, NONV, HASARENA,
944       FIT_ARENA(0, sizeof(XPVHV)) },
945
946     { sizeof(XPVCV),
947       sizeof(XPVCV),
948       0,
949       SVt_PVCV, TRUE, NONV, HASARENA,
950       FIT_ARENA(0, sizeof(XPVCV)) },
951
952     { sizeof(XPVFM),
953       sizeof(XPVFM),
954       0,
955       SVt_PVFM, TRUE, NONV, NOARENA,
956       FIT_ARENA(20, sizeof(XPVFM)) },
957
958     { sizeof(XPVIO),
959       sizeof(XPVIO),
960       0,
961       SVt_PVIO, TRUE, NONV, HASARENA,
962       FIT_ARENA(24, sizeof(XPVIO)) },
963 };
964
965 #define new_body_allocated(sv_type)             \
966     (void *)((char *)S_new_body(aTHX_ sv_type)  \
967              - bodies_by_type[sv_type].offset)
968
969 /* return a thing to the free list */
970
971 #define del_body(thing, root)                           \
972     STMT_START {                                        \
973         void ** const thing_copy = (void **)thing;      \
974         *thing_copy = *root;                            \
975         *root = (void*)thing_copy;                      \
976     } STMT_END
977
978 #ifdef PURIFY
979
980 #define new_XNV()       safemalloc(sizeof(XPVNV))
981 #define new_XPVNV()     safemalloc(sizeof(XPVNV))
982 #define new_XPVMG()     safemalloc(sizeof(XPVMG))
983
984 #define del_XPVGV(p)    safefree(p)
985
986 #else /* !PURIFY */
987
988 #define new_XNV()       new_body_allocated(SVt_NV)
989 #define new_XPVNV()     new_body_allocated(SVt_PVNV)
990 #define new_XPVMG()     new_body_allocated(SVt_PVMG)
991
992 #define del_XPVGV(p)    del_body(p + bodies_by_type[SVt_PVGV].offset,   \
993                                  &PL_body_roots[SVt_PVGV])
994
995 #endif /* PURIFY */
996
997 /* no arena for you! */
998
999 #define new_NOARENA(details) \
1000         safemalloc((details)->body_size + (details)->offset)
1001 #define new_NOARENAZ(details) \
1002         safecalloc((details)->body_size + (details)->offset, 1)
1003
1004 void *
1005 Perl_more_bodies (pTHX_ const svtype sv_type, const size_t body_size,
1006                   const size_t arena_size)
1007 {
1008     dVAR;
1009     void ** const root = &PL_body_roots[sv_type];
1010     struct arena_desc *adesc;
1011     struct arena_set *aroot = (struct arena_set *) PL_body_arenas;
1012     unsigned int curr;
1013     char *start;
1014     const char *end;
1015     const size_t good_arena_size = Perl_malloc_good_size(arena_size);
1016 #if defined(DEBUGGING) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
1017     static bool done_sanity_check;
1018
1019     /* PERL_GLOBAL_STRUCT_PRIVATE cannot coexist with global
1020      * variables like done_sanity_check. */
1021     if (!done_sanity_check) {
1022         unsigned int i = SVt_LAST;
1023
1024         done_sanity_check = TRUE;
1025
1026         while (i--)
1027             assert (bodies_by_type[i].type == i);
1028     }
1029 #endif
1030
1031     assert(arena_size);
1032
1033     /* may need new arena-set to hold new arena */
1034     if (!aroot || aroot->curr >= aroot->set_size) {
1035         struct arena_set *newroot;
1036         Newxz(newroot, 1, struct arena_set);
1037         newroot->set_size = ARENAS_PER_SET;
1038         newroot->next = aroot;
1039         aroot = newroot;
1040         PL_body_arenas = (void *) newroot;
1041         DEBUG_m(PerlIO_printf(Perl_debug_log, "new arenaset %p\n", (void*)aroot));
1042     }
1043
1044     /* ok, now have arena-set with at least 1 empty/available arena-desc */
1045     curr = aroot->curr++;
1046     adesc = &(aroot->set[curr]);
1047     assert(!adesc->arena);
1048     
1049     Newx(adesc->arena, good_arena_size, char);
1050     adesc->size = good_arena_size;
1051     adesc->utype = sv_type;
1052     DEBUG_m(PerlIO_printf(Perl_debug_log, "arena %d added: %p size %"UVuf"\n", 
1053                           curr, (void*)adesc->arena, (UV)good_arena_size));
1054
1055     start = (char *) adesc->arena;
1056
1057     /* Get the address of the byte after the end of the last body we can fit.
1058        Remember, this is integer division:  */
1059     end = start + good_arena_size / body_size * body_size;
1060
1061     /* computed count doesn't reflect the 1st slot reservation */
1062 #if defined(MYMALLOC) || defined(HAS_MALLOC_GOOD_SIZE)
1063     DEBUG_m(PerlIO_printf(Perl_debug_log,
1064                           "arena %p end %p arena-size %d (from %d) type %d "
1065                           "size %d ct %d\n",
1066                           (void*)start, (void*)end, (int)good_arena_size,
1067                           (int)arena_size, sv_type, (int)body_size,
1068                           (int)good_arena_size / (int)body_size));
1069 #else
1070     DEBUG_m(PerlIO_printf(Perl_debug_log,
1071                           "arena %p end %p arena-size %d type %d size %d ct %d\n",
1072                           (void*)start, (void*)end,
1073                           (int)arena_size, sv_type, (int)body_size,
1074                           (int)good_arena_size / (int)body_size));
1075 #endif
1076     *root = (void *)start;
1077
1078     while (1) {
1079         /* Where the next body would start:  */
1080         char * const next = start + body_size;
1081
1082         if (next >= end) {
1083             /* This is the last body:  */
1084             assert(next == end);
1085
1086             *(void **)start = 0;
1087             return *root;
1088         }
1089
1090         *(void**) start = (void *)next;
1091         start = next;
1092     }
1093 }
1094
1095 /* grab a new thing from the free list, allocating more if necessary.
1096    The inline version is used for speed in hot routines, and the
1097    function using it serves the rest (unless PURIFY).
1098 */
1099 #define new_body_inline(xpv, sv_type) \
1100     STMT_START { \
1101         void ** const r3wt = &PL_body_roots[sv_type]; \
1102         xpv = (PTR_TBL_ENT_t*) (*((void **)(r3wt))      \
1103           ? *((void **)(r3wt)) : Perl_more_bodies(aTHX_ sv_type, \
1104                                              bodies_by_type[sv_type].body_size,\
1105                                              bodies_by_type[sv_type].arena_size)); \
1106         *(r3wt) = *(void**)(xpv); \
1107     } STMT_END
1108
1109 #ifndef PURIFY
1110
1111 STATIC void *
1112 S_new_body(pTHX_ const svtype sv_type)
1113 {
1114     dVAR;
1115     void *xpv;
1116     new_body_inline(xpv, sv_type);
1117     return xpv;
1118 }
1119
1120 #endif
1121
1122 static const struct body_details fake_rv =
1123     { 0, 0, 0, SVt_IV, FALSE, NONV, NOARENA, 0 };
1124
1125 /*
1126 =for apidoc sv_upgrade
1127
1128 Upgrade an SV to a more complex form.  Generally adds a new body type to the
1129 SV, then copies across as much information as possible from the old body.
1130 It croaks if the SV is already in a more complex form than requested.  You
1131 generally want to use the C<SvUPGRADE> macro wrapper, which checks the type
1132 before calling C<sv_upgrade>, and hence does not croak.  See also
1133 C<svtype>.
1134
1135 =cut
1136 */
1137
1138 void
1139 Perl_sv_upgrade(pTHX_ SV *const sv, svtype new_type)
1140 {
1141     dVAR;
1142     void*       old_body;
1143     void*       new_body;
1144     const svtype old_type = SvTYPE(sv);
1145     const struct body_details *new_type_details;
1146     const struct body_details *old_type_details
1147         = bodies_by_type + old_type;
1148     SV *referant = NULL;
1149
1150     PERL_ARGS_ASSERT_SV_UPGRADE;
1151
1152     if (old_type == new_type)
1153         return;
1154
1155     /* This clause was purposefully added ahead of the early return above to
1156        the shared string hackery for (sort {$a <=> $b} keys %hash), with the
1157        inference by Nick I-S that it would fix other troublesome cases. See
1158        changes 7162, 7163 (f130fd4589cf5fbb24149cd4db4137c8326f49c1 and parent)
1159
1160        Given that shared hash key scalars are no longer PVIV, but PV, there is
1161        no longer need to unshare so as to free up the IVX slot for its proper
1162        purpose. So it's safe to move the early return earlier.  */
1163
1164     if (new_type > SVt_PVMG && SvIsCOW(sv)) {
1165         sv_force_normal_flags(sv, 0);
1166     }
1167
1168     old_body = SvANY(sv);
1169
1170     /* Copying structures onto other structures that have been neatly zeroed
1171        has a subtle gotcha. Consider XPVMG
1172
1173        +------+------+------+------+------+-------+-------+
1174        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |
1175        +------+------+------+------+------+-------+-------+
1176        0      4      8     12     16     20      24      28
1177
1178        where NVs are aligned to 8 bytes, so that sizeof that structure is
1179        actually 32 bytes long, with 4 bytes of padding at the end:
1180
1181        +------+------+------+------+------+-------+-------+------+
1182        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH | ???  |
1183        +------+------+------+------+------+-------+-------+------+
1184        0      4      8     12     16     20      24      28     32
1185
1186        so what happens if you allocate memory for this structure:
1187
1188        +------+------+------+------+------+-------+-------+------+------+...
1189        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |  GP  | NAME |
1190        +------+------+------+------+------+-------+-------+------+------+...
1191        0      4      8     12     16     20      24      28     32     36
1192
1193        zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
1194        expect, because you copy the area marked ??? onto GP. Now, ??? may have
1195        started out as zero once, but it's quite possible that it isn't. So now,
1196        rather than a nicely zeroed GP, you have it pointing somewhere random.
1197        Bugs ensue.
1198
1199        (In fact, GP ends up pointing at a previous GP structure, because the
1200        principle cause of the padding in XPVMG getting garbage is a copy of
1201        sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob. Right now
1202        this happens to be moot because XPVGV has been re-ordered, with GP
1203        no longer after STASH)
1204
1205        So we are careful and work out the size of used parts of all the
1206        structures.  */
1207
1208     switch (old_type) {
1209     case SVt_NULL:
1210         break;
1211     case SVt_IV:
1212         if (SvROK(sv)) {
1213             referant = SvRV(sv);
1214             old_type_details = &fake_rv;
1215             if (new_type == SVt_NV)
1216                 new_type = SVt_PVNV;
1217         } else {
1218             if (new_type < SVt_PVIV) {
1219                 new_type = (new_type == SVt_NV)
1220                     ? SVt_PVNV : SVt_PVIV;
1221             }
1222         }
1223         break;
1224     case SVt_NV:
1225         if (new_type < SVt_PVNV) {
1226             new_type = SVt_PVNV;
1227         }
1228         break;
1229     case SVt_PV:
1230         assert(new_type > SVt_PV);
1231         assert(SVt_IV < SVt_PV);
1232         assert(SVt_NV < SVt_PV);
1233         break;
1234     case SVt_PVIV:
1235         break;
1236     case SVt_PVNV:
1237         break;
1238     case SVt_PVMG:
1239         /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1240            there's no way that it can be safely upgraded, because perl.c
1241            expects to Safefree(SvANY(PL_mess_sv))  */
1242         assert(sv != PL_mess_sv);
1243         /* This flag bit is used to mean other things in other scalar types.
1244            Given that it only has meaning inside the pad, it shouldn't be set
1245            on anything that can get upgraded.  */
1246         assert(!SvPAD_TYPED(sv));
1247         break;
1248     default:
1249         if (UNLIKELY(old_type_details->cant_upgrade))
1250             Perl_croak(aTHX_ "Can't upgrade %s (%" UVuf ") to %" UVuf,
1251                        sv_reftype(sv, 0), (UV) old_type, (UV) new_type);
1252     }
1253
1254     if (UNLIKELY(old_type > new_type))
1255         Perl_croak(aTHX_ "sv_upgrade from type %d down to type %d",
1256                 (int)old_type, (int)new_type);
1257
1258     new_type_details = bodies_by_type + new_type;
1259
1260     SvFLAGS(sv) &= ~SVTYPEMASK;
1261     SvFLAGS(sv) |= new_type;
1262
1263     /* This can't happen, as SVt_NULL is <= all values of new_type, so one of
1264        the return statements above will have triggered.  */
1265     assert (new_type != SVt_NULL);
1266     switch (new_type) {
1267     case SVt_IV:
1268         assert(old_type == SVt_NULL);
1269         SvANY(sv) = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
1270         SvIV_set(sv, 0);
1271         return;
1272     case SVt_NV:
1273         assert(old_type == SVt_NULL);
1274         SvANY(sv) = new_XNV();
1275         SvNV_set(sv, 0);
1276         return;
1277     case SVt_PVHV:
1278     case SVt_PVAV:
1279         assert(new_type_details->body_size);
1280
1281 #ifndef PURIFY  
1282         assert(new_type_details->arena);
1283         assert(new_type_details->arena_size);
1284         /* This points to the start of the allocated area.  */
1285         new_body_inline(new_body, new_type);
1286         Zero(new_body, new_type_details->body_size, char);
1287         new_body = ((char *)new_body) - new_type_details->offset;
1288 #else
1289         /* We always allocated the full length item with PURIFY. To do this
1290            we fake things so that arena is false for all 16 types..  */
1291         new_body = new_NOARENAZ(new_type_details);
1292 #endif
1293         SvANY(sv) = new_body;
1294         if (new_type == SVt_PVAV) {
1295             AvMAX(sv)   = -1;
1296             AvFILLp(sv) = -1;
1297             AvREAL_only(sv);
1298             if (old_type_details->body_size) {
1299                 AvALLOC(sv) = 0;
1300             } else {
1301                 /* It will have been zeroed when the new body was allocated.
1302                    Lets not write to it, in case it confuses a write-back
1303                    cache.  */
1304             }
1305         } else {
1306             assert(!SvOK(sv));
1307             SvOK_off(sv);
1308 #ifndef NODEFAULT_SHAREKEYS
1309             HvSHAREKEYS_on(sv);         /* key-sharing on by default */
1310 #endif
1311             /* start with PERL_HASH_DEFAULT_HvMAX+1 buckets: */
1312             HvMAX(sv) = PERL_HASH_DEFAULT_HvMAX;
1313         }
1314
1315         /* SVt_NULL isn't the only thing upgraded to AV or HV.
1316            The target created by newSVrv also is, and it can have magic.
1317            However, it never has SvPVX set.
1318         */
1319         if (old_type == SVt_IV) {
1320             assert(!SvROK(sv));
1321         } else if (old_type >= SVt_PV) {
1322             assert(SvPVX_const(sv) == 0);
1323         }
1324
1325         if (old_type >= SVt_PVMG) {
1326             SvMAGIC_set(sv, ((XPVMG*)old_body)->xmg_u.xmg_magic);
1327             SvSTASH_set(sv, ((XPVMG*)old_body)->xmg_stash);
1328         } else {
1329             sv->sv_u.svu_array = NULL; /* or svu_hash  */
1330         }
1331         break;
1332
1333     case SVt_PVIV:
1334         /* XXX Is this still needed?  Was it ever needed?   Surely as there is
1335            no route from NV to PVIV, NOK can never be true  */
1336         assert(!SvNOKp(sv));
1337         assert(!SvNOK(sv));
1338     case SVt_PVIO:
1339     case SVt_PVFM:
1340     case SVt_PVGV:
1341     case SVt_PVCV:
1342     case SVt_PVLV:
1343     case SVt_REGEXP:
1344     case SVt_PVMG:
1345     case SVt_PVNV:
1346     case SVt_PV:
1347
1348         assert(new_type_details->body_size);
1349         /* We always allocated the full length item with PURIFY. To do this
1350            we fake things so that arena is false for all 16 types..  */
1351         if(new_type_details->arena) {
1352             /* This points to the start of the allocated area.  */
1353             new_body_inline(new_body, new_type);
1354             Zero(new_body, new_type_details->body_size, char);
1355             new_body = ((char *)new_body) - new_type_details->offset;
1356         } else {
1357             new_body = new_NOARENAZ(new_type_details);
1358         }
1359         SvANY(sv) = new_body;
1360
1361         if (old_type_details->copy) {
1362             /* There is now the potential for an upgrade from something without
1363                an offset (PVNV or PVMG) to something with one (PVCV, PVFM)  */
1364             int offset = old_type_details->offset;
1365             int length = old_type_details->copy;
1366
1367             if (new_type_details->offset > old_type_details->offset) {
1368                 const int difference
1369                     = new_type_details->offset - old_type_details->offset;
1370                 offset += difference;
1371                 length -= difference;
1372             }
1373             assert (length >= 0);
1374                 
1375             Copy((char *)old_body + offset, (char *)new_body + offset, length,
1376                  char);
1377         }
1378
1379 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1380         /* If NV 0.0 is stores as all bits 0 then Zero() already creates a
1381          * correct 0.0 for us.  Otherwise, if the old body didn't have an
1382          * NV slot, but the new one does, then we need to initialise the
1383          * freshly created NV slot with whatever the correct bit pattern is
1384          * for 0.0  */
1385         if (old_type_details->zero_nv && !new_type_details->zero_nv
1386             && !isGV_with_GP(sv))
1387             SvNV_set(sv, 0);
1388 #endif
1389
1390         if (UNLIKELY(new_type == SVt_PVIO)) {
1391             IO * const io = MUTABLE_IO(sv);
1392             GV *iogv = gv_fetchpvs("IO::File::", GV_ADD, SVt_PVHV);
1393
1394             SvOBJECT_on(io);
1395             /* Clear the stashcache because a new IO could overrule a package
1396                name */
1397             DEBUG_o(Perl_deb(aTHX_ "sv_upgrade clearing PL_stashcache\n"));
1398             hv_clear(PL_stashcache);
1399
1400             SvSTASH_set(io, MUTABLE_HV(SvREFCNT_inc(GvHV(iogv))));
1401             IoPAGE_LEN(sv) = 60;
1402         }
1403         if (UNLIKELY(new_type == SVt_REGEXP))
1404             sv->sv_u.svu_rx = (regexp *)new_body;
1405         else if (old_type < SVt_PV) {
1406             /* referant will be NULL unless the old type was SVt_IV emulating
1407                SVt_RV */
1408             sv->sv_u.svu_rv = referant;
1409         }
1410         break;
1411     default:
1412         Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu",
1413                    (unsigned long)new_type);
1414     }
1415
1416     if (old_type > SVt_IV) {
1417 #ifdef PURIFY
1418         safefree(old_body);
1419 #else
1420         /* Note that there is an assumption that all bodies of types that
1421            can be upgraded came from arenas. Only the more complex non-
1422            upgradable types are allowed to be directly malloc()ed.  */
1423         assert(old_type_details->arena);
1424         del_body((void*)((char*)old_body + old_type_details->offset),
1425                  &PL_body_roots[old_type]);
1426 #endif
1427     }
1428 }
1429
1430 /*
1431 =for apidoc sv_backoff
1432
1433 Remove any string offset.  You should normally use the C<SvOOK_off> macro
1434 wrapper instead.
1435
1436 =cut
1437 */
1438
1439 int
1440 Perl_sv_backoff(pTHX_ SV *const sv)
1441 {
1442     STRLEN delta;
1443     const char * const s = SvPVX_const(sv);
1444
1445     PERL_ARGS_ASSERT_SV_BACKOFF;
1446     PERL_UNUSED_CONTEXT;
1447
1448     assert(SvOOK(sv));
1449     assert(SvTYPE(sv) != SVt_PVHV);
1450     assert(SvTYPE(sv) != SVt_PVAV);
1451
1452     SvOOK_offset(sv, delta);
1453     
1454     SvLEN_set(sv, SvLEN(sv) + delta);
1455     SvPV_set(sv, SvPVX(sv) - delta);
1456     Move(s, SvPVX(sv), SvCUR(sv)+1, char);
1457     SvFLAGS(sv) &= ~SVf_OOK;
1458     return 0;
1459 }
1460
1461 /*
1462 =for apidoc sv_grow
1463
1464 Expands the character buffer in the SV.  If necessary, uses C<sv_unref> and
1465 upgrades the SV to C<SVt_PV>.  Returns a pointer to the character buffer.
1466 Use the C<SvGROW> wrapper instead.
1467
1468 =cut
1469 */
1470
1471 char *
1472 Perl_sv_grow(pTHX_ SV *const sv, STRLEN newlen)
1473 {
1474     char *s;
1475
1476     PERL_ARGS_ASSERT_SV_GROW;
1477
1478 #ifdef HAS_64K_LIMIT
1479     if (newlen >= 0x10000) {
1480         PerlIO_printf(Perl_debug_log,
1481                       "Allocation too large: %"UVxf"\n", (UV)newlen);
1482         my_exit(1);
1483     }
1484 #endif /* HAS_64K_LIMIT */
1485     if (SvROK(sv))
1486         sv_unref(sv);
1487     if (SvTYPE(sv) < SVt_PV) {
1488         sv_upgrade(sv, SVt_PV);
1489         s = SvPVX_mutable(sv);
1490     }
1491     else if (SvOOK(sv)) {       /* pv is offset? */
1492         sv_backoff(sv);
1493         s = SvPVX_mutable(sv);
1494         if (newlen > SvLEN(sv))
1495             newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1496 #ifdef HAS_64K_LIMIT
1497         if (newlen >= 0x10000)
1498             newlen = 0xFFFF;
1499 #endif
1500     }
1501     else
1502     {
1503         if (SvIsCOW(sv)) sv_force_normal(sv);
1504         s = SvPVX_mutable(sv);
1505     }
1506
1507 #ifdef PERL_NEW_COPY_ON_WRITE
1508     /* the new COW scheme uses SvPVX(sv)[SvLEN(sv)-1] (if spare)
1509      * to store the COW count. So in general, allocate one more byte than
1510      * asked for, to make it likely this byte is always spare: and thus
1511      * make more strings COW-able.
1512      * If the new size is a big power of two, don't bother: we assume the
1513      * caller wanted a nice 2^N sized block and will be annoyed at getting
1514      * 2^N+1 */
1515     if (newlen & 0xff)
1516         newlen++;
1517 #endif
1518
1519     if (newlen > SvLEN(sv)) {           /* need more room? */
1520         STRLEN minlen = SvCUR(sv);
1521         minlen += (minlen >> PERL_STRLEN_EXPAND_SHIFT) + 10;
1522         if (newlen < minlen)
1523             newlen = minlen;
1524 #ifndef Perl_safesysmalloc_size
1525         newlen = PERL_STRLEN_ROUNDUP(newlen);
1526 #endif
1527         if (SvLEN(sv) && s) {
1528             s = (char*)saferealloc(s, newlen);
1529         }
1530         else {
1531             s = (char*)safemalloc(newlen);
1532             if (SvPVX_const(sv) && SvCUR(sv)) {
1533                 Move(SvPVX_const(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1534             }
1535         }
1536         SvPV_set(sv, s);
1537 #ifdef Perl_safesysmalloc_size
1538         /* Do this here, do it once, do it right, and then we will never get
1539            called back into sv_grow() unless there really is some growing
1540            needed.  */
1541         SvLEN_set(sv, Perl_safesysmalloc_size(s));
1542 #else
1543         SvLEN_set(sv, newlen);
1544 #endif
1545     }
1546     return s;
1547 }
1548
1549 /*
1550 =for apidoc sv_setiv
1551
1552 Copies an integer into the given SV, upgrading first if necessary.
1553 Does not handle 'set' magic.  See also C<sv_setiv_mg>.
1554
1555 =cut
1556 */
1557
1558 void
1559 Perl_sv_setiv(pTHX_ SV *const sv, const IV i)
1560 {
1561     dVAR;
1562
1563     PERL_ARGS_ASSERT_SV_SETIV;
1564
1565     SV_CHECK_THINKFIRST_COW_DROP(sv);
1566     switch (SvTYPE(sv)) {
1567     case SVt_NULL:
1568     case SVt_NV:
1569         sv_upgrade(sv, SVt_IV);
1570         break;
1571     case SVt_PV:
1572         sv_upgrade(sv, SVt_PVIV);
1573         break;
1574
1575     case SVt_PVGV:
1576         if (!isGV_with_GP(sv))
1577             break;
1578     case SVt_PVAV:
1579     case SVt_PVHV:
1580     case SVt_PVCV:
1581     case SVt_PVFM:
1582     case SVt_PVIO:
1583         /* diag_listed_as: Can't coerce %s to %s in %s */
1584         Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1585                    OP_DESC(PL_op));
1586     default: NOOP;
1587     }
1588     (void)SvIOK_only(sv);                       /* validate number */
1589     SvIV_set(sv, i);
1590     SvTAINT(sv);
1591 }
1592
1593 /*
1594 =for apidoc sv_setiv_mg
1595
1596 Like C<sv_setiv>, but also handles 'set' magic.
1597
1598 =cut
1599 */
1600
1601 void
1602 Perl_sv_setiv_mg(pTHX_ SV *const sv, const IV i)
1603 {
1604     PERL_ARGS_ASSERT_SV_SETIV_MG;
1605
1606     sv_setiv(sv,i);
1607     SvSETMAGIC(sv);
1608 }
1609
1610 /*
1611 =for apidoc sv_setuv
1612
1613 Copies an unsigned integer into the given SV, upgrading first if necessary.
1614 Does not handle 'set' magic.  See also C<sv_setuv_mg>.
1615
1616 =cut
1617 */
1618
1619 void
1620 Perl_sv_setuv(pTHX_ SV *const sv, const UV u)
1621 {
1622     PERL_ARGS_ASSERT_SV_SETUV;
1623
1624     /* With the if statement to ensure that integers are stored as IVs whenever
1625        possible:
1626        u=1.49  s=0.52  cu=72.49  cs=10.64  scripts=270  tests=20865
1627
1628        without
1629        u=1.35  s=0.47  cu=73.45  cs=11.43  scripts=270  tests=20865
1630
1631        If you wish to remove the following if statement, so that this routine
1632        (and its callers) always return UVs, please benchmark to see what the
1633        effect is. Modern CPUs may be different. Or may not :-)
1634     */
1635     if (u <= (UV)IV_MAX) {
1636        sv_setiv(sv, (IV)u);
1637        return;
1638     }
1639     sv_setiv(sv, 0);
1640     SvIsUV_on(sv);
1641     SvUV_set(sv, u);
1642 }
1643
1644 /*
1645 =for apidoc sv_setuv_mg
1646
1647 Like C<sv_setuv>, but also handles 'set' magic.
1648
1649 =cut
1650 */
1651
1652 void
1653 Perl_sv_setuv_mg(pTHX_ SV *const sv, const UV u)
1654 {
1655     PERL_ARGS_ASSERT_SV_SETUV_MG;
1656
1657     sv_setuv(sv,u);
1658     SvSETMAGIC(sv);
1659 }
1660
1661 /*
1662 =for apidoc sv_setnv
1663
1664 Copies a double into the given SV, upgrading first if necessary.
1665 Does not handle 'set' magic.  See also C<sv_setnv_mg>.
1666
1667 =cut
1668 */
1669
1670 void
1671 Perl_sv_setnv(pTHX_ SV *const sv, const NV num)
1672 {
1673     dVAR;
1674
1675     PERL_ARGS_ASSERT_SV_SETNV;
1676
1677     SV_CHECK_THINKFIRST_COW_DROP(sv);
1678     switch (SvTYPE(sv)) {
1679     case SVt_NULL:
1680     case SVt_IV:
1681         sv_upgrade(sv, SVt_NV);
1682         break;
1683     case SVt_PV:
1684     case SVt_PVIV:
1685         sv_upgrade(sv, SVt_PVNV);
1686         break;
1687
1688     case SVt_PVGV:
1689         if (!isGV_with_GP(sv))
1690             break;
1691     case SVt_PVAV:
1692     case SVt_PVHV:
1693     case SVt_PVCV:
1694     case SVt_PVFM:
1695     case SVt_PVIO:
1696         /* diag_listed_as: Can't coerce %s to %s in %s */
1697         Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
1698                    OP_DESC(PL_op));
1699     default: NOOP;
1700     }
1701     SvNV_set(sv, num);
1702     (void)SvNOK_only(sv);                       /* validate number */
1703     SvTAINT(sv);
1704 }
1705
1706 /*
1707 =for apidoc sv_setnv_mg
1708
1709 Like C<sv_setnv>, but also handles 'set' magic.
1710
1711 =cut
1712 */
1713
1714 void
1715 Perl_sv_setnv_mg(pTHX_ SV *const sv, const NV num)
1716 {
1717     PERL_ARGS_ASSERT_SV_SETNV_MG;
1718
1719     sv_setnv(sv,num);
1720     SvSETMAGIC(sv);
1721 }
1722
1723 /* Print an "isn't numeric" warning, using a cleaned-up,
1724  * printable version of the offending string
1725  */
1726
1727 STATIC void
1728 S_not_a_number(pTHX_ SV *const sv)
1729 {
1730      dVAR;
1731      SV *dsv;
1732      char tmpbuf[64];
1733      const char *pv;
1734
1735      PERL_ARGS_ASSERT_NOT_A_NUMBER;
1736
1737      if (DO_UTF8(sv)) {
1738           dsv = newSVpvs_flags("", SVs_TEMP);
1739           pv = sv_uni_display(dsv, sv, 10, UNI_DISPLAY_ISPRINT);
1740      } else {
1741           char *d = tmpbuf;
1742           const char * const limit = tmpbuf + sizeof(tmpbuf) - 8;
1743           /* each *s can expand to 4 chars + "...\0",
1744              i.e. need room for 8 chars */
1745         
1746           const char *s = SvPVX_const(sv);
1747           const char * const end = s + SvCUR(sv);
1748           for ( ; s < end && d < limit; s++ ) {
1749                int ch = *s & 0xFF;
1750                if (ch & 128 && !isPRINT_LC(ch)) {
1751                     *d++ = 'M';
1752                     *d++ = '-';
1753                     ch &= 127;
1754                }
1755                if (ch == '\n') {
1756                     *d++ = '\\';
1757                     *d++ = 'n';
1758                }
1759                else if (ch == '\r') {
1760                     *d++ = '\\';
1761                     *d++ = 'r';
1762                }
1763                else if (ch == '\f') {
1764                     *d++ = '\\';
1765                     *d++ = 'f';
1766                }
1767                else if (ch == '\\') {
1768                     *d++ = '\\';
1769                     *d++ = '\\';
1770                }
1771                else if (ch == '\0') {
1772                     *d++ = '\\';
1773                     *d++ = '0';
1774                }
1775                else if (isPRINT_LC(ch))
1776                     *d++ = ch;
1777                else {
1778                     *d++ = '^';
1779                     *d++ = toCTRL(ch);
1780                }
1781           }
1782           if (s < end) {
1783                *d++ = '.';
1784                *d++ = '.';
1785                *d++ = '.';
1786           }
1787           *d = '\0';
1788           pv = tmpbuf;
1789     }
1790
1791     if (PL_op)
1792         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1793                     /* diag_listed_as: Argument "%s" isn't numeric%s */
1794                     "Argument \"%s\" isn't numeric in %s", pv,
1795                     OP_DESC(PL_op));
1796     else
1797         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1798                     /* diag_listed_as: Argument "%s" isn't numeric%s */
1799                     "Argument \"%s\" isn't numeric", pv);
1800 }
1801
1802 /*
1803 =for apidoc looks_like_number
1804
1805 Test if the content of an SV looks like a number (or is a number).
1806 C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1807 non-numeric warning), even if your atof() doesn't grok them.  Get-magic is
1808 ignored.
1809
1810 =cut
1811 */
1812
1813 I32
1814 Perl_looks_like_number(pTHX_ SV *const sv)
1815 {
1816     const char *sbegin;
1817     STRLEN len;
1818
1819     PERL_ARGS_ASSERT_LOOKS_LIKE_NUMBER;
1820
1821     if (SvPOK(sv) || SvPOKp(sv)) {
1822         sbegin = SvPV_nomg_const(sv, len);
1823     }
1824     else
1825         return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
1826     return grok_number(sbegin, len, NULL);
1827 }
1828
1829 STATIC bool
1830 S_glob_2number(pTHX_ GV * const gv)
1831 {
1832     PERL_ARGS_ASSERT_GLOB_2NUMBER;
1833
1834     /* We know that all GVs stringify to something that is not-a-number,
1835         so no need to test that.  */
1836     if (ckWARN(WARN_NUMERIC))
1837     {
1838         SV *const buffer = sv_newmortal();
1839         gv_efullname3(buffer, gv, "*");
1840         not_a_number(buffer);
1841     }
1842     /* We just want something true to return, so that S_sv_2iuv_common
1843         can tail call us and return true.  */
1844     return TRUE;
1845 }
1846
1847 /* Actually, ISO C leaves conversion of UV to IV undefined, but
1848    until proven guilty, assume that things are not that bad... */
1849
1850 /*
1851    NV_PRESERVES_UV:
1852
1853    As 64 bit platforms often have an NV that doesn't preserve all bits of
1854    an IV (an assumption perl has been based on to date) it becomes necessary
1855    to remove the assumption that the NV always carries enough precision to
1856    recreate the IV whenever needed, and that the NV is the canonical form.
1857    Instead, IV/UV and NV need to be given equal rights. So as to not lose
1858    precision as a side effect of conversion (which would lead to insanity
1859    and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1860    1) to distinguish between IV/UV/NV slots that have cached a valid
1861       conversion where precision was lost and IV/UV/NV slots that have a
1862       valid conversion which has lost no precision
1863    2) to ensure that if a numeric conversion to one form is requested that
1864       would lose precision, the precise conversion (or differently
1865       imprecise conversion) is also performed and cached, to prevent
1866       requests for different numeric formats on the same SV causing
1867       lossy conversion chains. (lossless conversion chains are perfectly
1868       acceptable (still))
1869
1870
1871    flags are used:
1872    SvIOKp is true if the IV slot contains a valid value
1873    SvIOK  is true only if the IV value is accurate (UV if SvIOK_UV true)
1874    SvNOKp is true if the NV slot contains a valid value
1875    SvNOK  is true only if the NV value is accurate
1876
1877    so
1878    while converting from PV to NV, check to see if converting that NV to an
1879    IV(or UV) would lose accuracy over a direct conversion from PV to
1880    IV(or UV). If it would, cache both conversions, return NV, but mark
1881    SV as IOK NOKp (ie not NOK).
1882
1883    While converting from PV to IV, check to see if converting that IV to an
1884    NV would lose accuracy over a direct conversion from PV to NV. If it
1885    would, cache both conversions, flag similarly.
1886
1887    Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1888    correctly because if IV & NV were set NV *always* overruled.
1889    Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1890    changes - now IV and NV together means that the two are interchangeable:
1891    SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
1892
1893    The benefit of this is that operations such as pp_add know that if
1894    SvIOK is true for both left and right operands, then integer addition
1895    can be used instead of floating point (for cases where the result won't
1896    overflow). Before, floating point was always used, which could lead to
1897    loss of precision compared with integer addition.
1898
1899    * making IV and NV equal status should make maths accurate on 64 bit
1900      platforms
1901    * may speed up maths somewhat if pp_add and friends start to use
1902      integers when possible instead of fp. (Hopefully the overhead in
1903      looking for SvIOK and checking for overflow will not outweigh the
1904      fp to integer speedup)
1905    * will slow down integer operations (callers of SvIV) on "inaccurate"
1906      values, as the change from SvIOK to SvIOKp will cause a call into
1907      sv_2iv each time rather than a macro access direct to the IV slot
1908    * should speed up number->string conversion on integers as IV is
1909      favoured when IV and NV are equally accurate
1910
1911    ####################################################################
1912    You had better be using SvIOK_notUV if you want an IV for arithmetic:
1913    SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
1914    On the other hand, SvUOK is true iff UV.
1915    ####################################################################
1916
1917    Your mileage will vary depending your CPU's relative fp to integer
1918    performance ratio.
1919 */
1920
1921 #ifndef NV_PRESERVES_UV
1922 #  define IS_NUMBER_UNDERFLOW_IV 1
1923 #  define IS_NUMBER_UNDERFLOW_UV 2
1924 #  define IS_NUMBER_IV_AND_UV    2
1925 #  define IS_NUMBER_OVERFLOW_IV  4
1926 #  define IS_NUMBER_OVERFLOW_UV  5
1927
1928 /* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
1929
1930 /* For sv_2nv these three cases are "SvNOK and don't bother casting"  */
1931 STATIC int
1932 S_sv_2iuv_non_preserve(pTHX_ SV *const sv
1933 #  ifdef DEBUGGING
1934                        , I32 numtype
1935 #  endif
1936                        )
1937 {
1938     dVAR;
1939
1940     PERL_ARGS_ASSERT_SV_2IUV_NON_PRESERVE;
1941
1942     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));
1943     if (SvNVX(sv) < (NV)IV_MIN) {
1944         (void)SvIOKp_on(sv);
1945         (void)SvNOK_on(sv);
1946         SvIV_set(sv, IV_MIN);
1947         return IS_NUMBER_UNDERFLOW_IV;
1948     }
1949     if (SvNVX(sv) > (NV)UV_MAX) {
1950         (void)SvIOKp_on(sv);
1951         (void)SvNOK_on(sv);
1952         SvIsUV_on(sv);
1953         SvUV_set(sv, UV_MAX);
1954         return IS_NUMBER_OVERFLOW_UV;
1955     }
1956     (void)SvIOKp_on(sv);
1957     (void)SvNOK_on(sv);
1958     /* Can't use strtol etc to convert this string.  (See truth table in
1959        sv_2iv  */
1960     if (SvNVX(sv) <= (UV)IV_MAX) {
1961         SvIV_set(sv, I_V(SvNVX(sv)));
1962         if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
1963             SvIOK_on(sv); /* Integer is precise. NOK, IOK */
1964         } else {
1965             /* Integer is imprecise. NOK, IOKp */
1966         }
1967         return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
1968     }
1969     SvIsUV_on(sv);
1970     SvUV_set(sv, U_V(SvNVX(sv)));
1971     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
1972         if (SvUVX(sv) == UV_MAX) {
1973             /* As we know that NVs don't preserve UVs, UV_MAX cannot
1974                possibly be preserved by NV. Hence, it must be overflow.
1975                NOK, IOKp */
1976             return IS_NUMBER_OVERFLOW_UV;
1977         }
1978         SvIOK_on(sv); /* Integer is precise. NOK, UOK */
1979     } else {
1980         /* Integer is imprecise. NOK, IOKp */
1981     }
1982     return IS_NUMBER_OVERFLOW_IV;
1983 }
1984 #endif /* !NV_PRESERVES_UV*/
1985
1986 STATIC bool
1987 S_sv_2iuv_common(pTHX_ SV *const sv)
1988 {
1989     dVAR;
1990
1991     PERL_ARGS_ASSERT_SV_2IUV_COMMON;
1992
1993     if (SvNOKp(sv)) {
1994         /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
1995          * without also getting a cached IV/UV from it at the same time
1996          * (ie PV->NV conversion should detect loss of accuracy and cache
1997          * IV or UV at same time to avoid this. */
1998         /* IV-over-UV optimisation - choose to cache IV if possible */
1999
2000         if (SvTYPE(sv) == SVt_NV)
2001             sv_upgrade(sv, SVt_PVNV);
2002
2003         (void)SvIOKp_on(sv);    /* Must do this first, to clear any SvOOK */
2004         /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
2005            certainly cast into the IV range at IV_MAX, whereas the correct
2006            answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
2007            cases go to UV */
2008 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
2009         if (Perl_isnan(SvNVX(sv))) {
2010             SvUV_set(sv, 0);
2011             SvIsUV_on(sv);
2012             return FALSE;
2013         }
2014 #endif
2015         if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2016             SvIV_set(sv, I_V(SvNVX(sv)));
2017             if (SvNVX(sv) == (NV) SvIVX(sv)
2018 #ifndef NV_PRESERVES_UV
2019                 && (((UV)1 << NV_PRESERVES_UV_BITS) >
2020                     (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2021                 /* Don't flag it as "accurately an integer" if the number
2022                    came from a (by definition imprecise) NV operation, and
2023                    we're outside the range of NV integer precision */
2024 #endif
2025                 ) {
2026                 if (SvNOK(sv))
2027                     SvIOK_on(sv);  /* Can this go wrong with rounding? NWC */
2028                 else {
2029                     /* scalar has trailing garbage, eg "42a" */
2030                 }
2031                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2032                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
2033                                       PTR2UV(sv),
2034                                       SvNVX(sv),
2035                                       SvIVX(sv)));
2036
2037             } else {
2038                 /* IV not precise.  No need to convert from PV, as NV
2039                    conversion would already have cached IV if it detected
2040                    that PV->IV would be better than PV->NV->IV
2041                    flags already correct - don't set public IOK.  */
2042                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2043                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
2044                                       PTR2UV(sv),
2045                                       SvNVX(sv),
2046                                       SvIVX(sv)));
2047             }
2048             /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2049                but the cast (NV)IV_MIN rounds to a the value less (more
2050                negative) than IV_MIN which happens to be equal to SvNVX ??
2051                Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2052                NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2053                (NV)UVX == NVX are both true, but the values differ. :-(
2054                Hopefully for 2s complement IV_MIN is something like
2055                0x8000000000000000 which will be exact. NWC */
2056         }
2057         else {
2058             SvUV_set(sv, U_V(SvNVX(sv)));
2059             if (
2060                 (SvNVX(sv) == (NV) SvUVX(sv))
2061 #ifndef  NV_PRESERVES_UV
2062                 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2063                 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2064                 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2065                 /* Don't flag it as "accurately an integer" if the number
2066                    came from a (by definition imprecise) NV operation, and
2067                    we're outside the range of NV integer precision */
2068 #endif
2069                 && SvNOK(sv)
2070                 )
2071                 SvIOK_on(sv);
2072             SvIsUV_on(sv);
2073             DEBUG_c(PerlIO_printf(Perl_debug_log,
2074                                   "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
2075                                   PTR2UV(sv),
2076                                   SvUVX(sv),
2077                                   SvUVX(sv)));
2078         }
2079     }
2080     else if (SvPOKp(sv)) {
2081         UV value;
2082         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2083         /* We want to avoid a possible problem when we cache an IV/ a UV which
2084            may be later translated to an NV, and the resulting NV is not
2085            the same as the direct translation of the initial string
2086            (eg 123.456 can shortcut to the IV 123 with atol(), but we must
2087            be careful to ensure that the value with the .456 is around if the
2088            NV value is requested in the future).
2089         
2090            This means that if we cache such an IV/a UV, we need to cache the
2091            NV as well.  Moreover, we trade speed for space, and do not
2092            cache the NV if we are sure it's not needed.
2093          */
2094
2095         /* SVt_PVNV is one higher than SVt_PVIV, hence this order  */
2096         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2097              == IS_NUMBER_IN_UV) {
2098             /* It's definitely an integer, only upgrade to PVIV */
2099             if (SvTYPE(sv) < SVt_PVIV)
2100                 sv_upgrade(sv, SVt_PVIV);
2101             (void)SvIOK_on(sv);
2102         } else if (SvTYPE(sv) < SVt_PVNV)
2103             sv_upgrade(sv, SVt_PVNV);
2104
2105         /* If NVs preserve UVs then we only use the UV value if we know that
2106            we aren't going to call atof() below. If NVs don't preserve UVs
2107            then the value returned may have more precision than atof() will
2108            return, even though value isn't perfectly accurate.  */
2109         if ((numtype & (IS_NUMBER_IN_UV
2110 #ifdef NV_PRESERVES_UV
2111                         | IS_NUMBER_NOT_INT
2112 #endif
2113             )) == IS_NUMBER_IN_UV) {
2114             /* This won't turn off the public IOK flag if it was set above  */
2115             (void)SvIOKp_on(sv);
2116
2117             if (!(numtype & IS_NUMBER_NEG)) {
2118                 /* positive */;
2119                 if (value <= (UV)IV_MAX) {
2120                     SvIV_set(sv, (IV)value);
2121                 } else {
2122                     /* it didn't overflow, and it was positive. */
2123                     SvUV_set(sv, value);
2124                     SvIsUV_on(sv);
2125                 }
2126             } else {
2127                 /* 2s complement assumption  */
2128                 if (value <= (UV)IV_MIN) {
2129                     SvIV_set(sv, -(IV)value);
2130                 } else {
2131                     /* Too negative for an IV.  This is a double upgrade, but
2132                        I'm assuming it will be rare.  */
2133                     if (SvTYPE(sv) < SVt_PVNV)
2134                         sv_upgrade(sv, SVt_PVNV);
2135                     SvNOK_on(sv);
2136                     SvIOK_off(sv);
2137                     SvIOKp_on(sv);
2138                     SvNV_set(sv, -(NV)value);
2139                     SvIV_set(sv, IV_MIN);
2140                 }
2141             }
2142         }
2143         /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2144            will be in the previous block to set the IV slot, and the next
2145            block to set the NV slot.  So no else here.  */
2146         
2147         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2148             != IS_NUMBER_IN_UV) {
2149             /* It wasn't an (integer that doesn't overflow the UV). */
2150             SvNV_set(sv, Atof(SvPVX_const(sv)));
2151
2152             if (! numtype && ckWARN(WARN_NUMERIC))
2153                 not_a_number(sv);
2154
2155 #if defined(USE_LONG_DOUBLE)
2156             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" PERL_PRIgldbl ")\n",
2157                                   PTR2UV(sv), SvNVX(sv)));
2158 #else
2159             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"NVgf")\n",
2160                                   PTR2UV(sv), SvNVX(sv)));
2161 #endif
2162
2163 #ifdef NV_PRESERVES_UV
2164             (void)SvIOKp_on(sv);
2165             (void)SvNOK_on(sv);
2166             if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2167                 SvIV_set(sv, I_V(SvNVX(sv)));
2168                 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2169                     SvIOK_on(sv);
2170                 } else {
2171                     NOOP;  /* Integer is imprecise. NOK, IOKp */
2172                 }
2173                 /* UV will not work better than IV */
2174             } else {
2175                 if (SvNVX(sv) > (NV)UV_MAX) {
2176                     SvIsUV_on(sv);
2177                     /* Integer is inaccurate. NOK, IOKp, is UV */
2178                     SvUV_set(sv, UV_MAX);
2179                 } else {
2180                     SvUV_set(sv, U_V(SvNVX(sv)));
2181                     /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2182                        NV preservse UV so can do correct comparison.  */
2183                     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2184                         SvIOK_on(sv);
2185                     } else {
2186                         NOOP;   /* Integer is imprecise. NOK, IOKp, is UV */
2187                     }
2188                 }
2189                 SvIsUV_on(sv);
2190             }
2191 #else /* NV_PRESERVES_UV */
2192             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2193                 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2194                 /* The IV/UV slot will have been set from value returned by
2195                    grok_number above.  The NV slot has just been set using
2196                    Atof.  */
2197                 SvNOK_on(sv);
2198                 assert (SvIOKp(sv));
2199             } else {
2200                 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2201                     U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2202                     /* Small enough to preserve all bits. */
2203                     (void)SvIOKp_on(sv);
2204                     SvNOK_on(sv);
2205                     SvIV_set(sv, I_V(SvNVX(sv)));
2206                     if ((NV)(SvIVX(sv)) == SvNVX(sv))
2207                         SvIOK_on(sv);
2208                     /* Assumption: first non-preserved integer is < IV_MAX,
2209                        this NV is in the preserved range, therefore: */
2210                     if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2211                           < (UV)IV_MAX)) {
2212                         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);
2213                     }
2214                 } else {
2215                     /* IN_UV NOT_INT
2216                          0      0       already failed to read UV.
2217                          0      1       already failed to read UV.
2218                          1      0       you won't get here in this case. IV/UV
2219                                         slot set, public IOK, Atof() unneeded.
2220                          1      1       already read UV.
2221                        so there's no point in sv_2iuv_non_preserve() attempting
2222                        to use atol, strtol, strtoul etc.  */
2223 #  ifdef DEBUGGING
2224                     sv_2iuv_non_preserve (sv, numtype);
2225 #  else
2226                     sv_2iuv_non_preserve (sv);
2227 #  endif
2228                 }
2229             }
2230 #endif /* NV_PRESERVES_UV */
2231         /* It might be more code efficient to go through the entire logic above
2232            and conditionally set with SvIOKp_on() rather than SvIOK(), but it
2233            gets complex and potentially buggy, so more programmer efficient
2234            to do it this way, by turning off the public flags:  */
2235         if (!numtype)
2236             SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2237         }
2238     }
2239     else  {
2240         if (isGV_with_GP(sv))
2241             return glob_2number(MUTABLE_GV(sv));
2242
2243         if (!SvPADTMP(sv)) {
2244             if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2245                 report_uninit(sv);
2246         }
2247         if (SvTYPE(sv) < SVt_IV)
2248             /* Typically the caller expects that sv_any is not NULL now.  */
2249             sv_upgrade(sv, SVt_IV);
2250         /* Return 0 from the caller.  */
2251         return TRUE;
2252     }
2253     return FALSE;
2254 }
2255
2256 /*
2257 =for apidoc sv_2iv_flags
2258
2259 Return the integer value of an SV, doing any necessary string
2260 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2261 Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2262
2263 =cut
2264 */
2265
2266 IV
2267 Perl_sv_2iv_flags(pTHX_ SV *const sv, const I32 flags)
2268 {
2269     dVAR;
2270
2271     if (!sv)
2272         return 0;
2273
2274     if (SvGMAGICAL(sv) && (flags & SV_GMAGIC))
2275         mg_get(sv);
2276
2277     if (SvROK(sv)) {
2278         if (SvAMAGIC(sv)) {
2279             SV * tmpstr;
2280             if (flags & SV_SKIP_OVERLOAD)
2281                 return 0;
2282             tmpstr = AMG_CALLunary(sv, numer_amg);
2283             if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2284                 return SvIV(tmpstr);
2285             }
2286         }
2287         return PTR2IV(SvRV(sv));
2288     }
2289
2290     if (SvVALID(sv) || isREGEXP(sv)) {
2291         /* FBMs use the space for SvIVX and SvNVX for other purposes, and use
2292            the same flag bit as SVf_IVisUV, so must not let them cache IVs.
2293            In practice they are extremely unlikely to actually get anywhere
2294            accessible by user Perl code - the only way that I'm aware of is when
2295            a constant subroutine which is used as the second argument to index.
2296
2297            Regexps have no SvIVX and SvNVX fields.
2298         */
2299         assert(isREGEXP(sv) || SvPOKp(sv));
2300         {
2301             UV value;
2302             const char * const ptr =
2303                 isREGEXP(sv) ? RX_WRAPPED((REGEXP*)sv) : SvPVX_const(sv);
2304             const int numtype
2305                 = grok_number(ptr, SvCUR(sv), &value);
2306
2307             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2308                 == IS_NUMBER_IN_UV) {
2309                 /* It's definitely an integer */
2310                 if (numtype & IS_NUMBER_NEG) {
2311                     if (value < (UV)IV_MIN)
2312                         return -(IV)value;
2313                 } else {
2314                     if (value < (UV)IV_MAX)
2315                         return (IV)value;
2316                 }
2317             }
2318             if (!numtype) {
2319                 if (ckWARN(WARN_NUMERIC))
2320                     not_a_number(sv);
2321             }
2322             return I_V(Atof(ptr));
2323         }
2324     }
2325
2326     if (SvTHINKFIRST(sv)) {
2327 #ifdef PERL_OLD_COPY_ON_WRITE
2328         if (SvIsCOW(sv)) {
2329             sv_force_normal_flags(sv, 0);
2330         }
2331 #endif
2332         if (SvREADONLY(sv) && !SvOK(sv)) {
2333             if (ckWARN(WARN_UNINITIALIZED))
2334                 report_uninit(sv);
2335             return 0;
2336         }
2337     }
2338
2339     if (!SvIOKp(sv)) {
2340         if (S_sv_2iuv_common(aTHX_ sv))
2341             return 0;
2342     }
2343
2344     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2345         PTR2UV(sv),SvIVX(sv)));
2346     return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
2347 }
2348
2349 /*
2350 =for apidoc sv_2uv_flags
2351
2352 Return the unsigned integer value of an SV, doing any necessary string
2353 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2354 Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
2355
2356 =cut
2357 */
2358
2359 UV
2360 Perl_sv_2uv_flags(pTHX_ SV *const sv, const I32 flags)
2361 {
2362     dVAR;
2363
2364     if (!sv)
2365         return 0;
2366
2367     if (SvGMAGICAL(sv) && (flags & SV_GMAGIC))
2368         mg_get(sv);
2369
2370     if (SvROK(sv)) {
2371         if (SvAMAGIC(sv)) {
2372             SV *tmpstr;
2373             if (flags & SV_SKIP_OVERLOAD)
2374                 return 0;
2375             tmpstr = AMG_CALLunary(sv, numer_amg);
2376             if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2377                 return SvUV(tmpstr);
2378             }
2379         }
2380         return PTR2UV(SvRV(sv));
2381     }
2382
2383     if (SvVALID(sv) || isREGEXP(sv)) {
2384         /* FBMs use the space for SvIVX and SvNVX for other purposes, and use
2385            the same flag bit as SVf_IVisUV, so must not let them cache IVs.  
2386            Regexps have no SvIVX and SvNVX fields. */
2387         assert(isREGEXP(sv) || SvPOKp(sv));
2388         {
2389             UV value;
2390             const char * const ptr =
2391                 isREGEXP(sv) ? RX_WRAPPED((REGEXP*)sv) : SvPVX_const(sv);
2392             const int numtype
2393                 = grok_number(ptr, SvCUR(sv), &value);
2394
2395             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2396                 == IS_NUMBER_IN_UV) {
2397                 /* It's definitely an integer */
2398                 if (!(numtype & IS_NUMBER_NEG))
2399                     return value;
2400             }
2401             if (!numtype) {
2402                 if (ckWARN(WARN_NUMERIC))
2403                     not_a_number(sv);
2404             }
2405             return U_V(Atof(ptr));
2406         }
2407     }
2408
2409     if (SvTHINKFIRST(sv)) {
2410 #ifdef PERL_OLD_COPY_ON_WRITE
2411         if (SvIsCOW(sv)) {
2412             sv_force_normal_flags(sv, 0);
2413         }
2414 #endif
2415         if (SvREADONLY(sv) && !SvOK(sv)) {
2416             if (ckWARN(WARN_UNINITIALIZED))
2417                 report_uninit(sv);
2418             return 0;
2419         }
2420     }
2421
2422     if (!SvIOKp(sv)) {
2423         if (S_sv_2iuv_common(aTHX_ sv))
2424             return 0;
2425     }
2426
2427     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2428                           PTR2UV(sv),SvUVX(sv)));
2429     return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
2430 }
2431
2432 /*
2433 =for apidoc sv_2nv_flags
2434
2435 Return the num value of an SV, doing any necessary string or integer
2436 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2437 Normally used via the C<SvNV(sv)> and C<SvNVx(sv)> macros.
2438
2439 =cut
2440 */
2441
2442 NV
2443 Perl_sv_2nv_flags(pTHX_ SV *const sv, const I32 flags)
2444 {
2445     dVAR;
2446     if (!sv)
2447         return 0.0;
2448     if (SvGMAGICAL(sv) || SvVALID(sv) || isREGEXP(sv)) {
2449         /* FBMs use the space for SvIVX and SvNVX for other purposes, and use
2450            the same flag bit as SVf_IVisUV, so must not let them cache NVs.
2451            Regexps have no SvIVX and SvNVX fields.  */
2452         const char *ptr;
2453         if (flags & SV_GMAGIC)
2454             mg_get(sv);
2455         if (SvNOKp(sv))
2456             return SvNVX(sv);
2457         if (SvPOKp(sv) && !SvIOKp(sv)) {
2458             ptr = SvPVX_const(sv);
2459           grokpv:
2460             if (!SvIOKp(sv) && ckWARN(WARN_NUMERIC) &&
2461                 !grok_number(ptr, SvCUR(sv), NULL))
2462                 not_a_number(sv);
2463             return Atof(ptr);
2464         }
2465         if (SvIOKp(sv)) {
2466             if (SvIsUV(sv))
2467                 return (NV)SvUVX(sv);
2468             else
2469                 return (NV)SvIVX(sv);
2470         }
2471         if (SvROK(sv)) {
2472             goto return_rok;
2473         }
2474         if (isREGEXP(sv)) {
2475             ptr = RX_WRAPPED((REGEXP *)sv);
2476             goto grokpv;
2477         }
2478         assert(SvTYPE(sv) >= SVt_PVMG);
2479         /* This falls through to the report_uninit near the end of the
2480            function. */
2481     } else if (SvTHINKFIRST(sv)) {
2482         if (SvROK(sv)) {
2483         return_rok:
2484             if (SvAMAGIC(sv)) {
2485                 SV *tmpstr;
2486                 if (flags & SV_SKIP_OVERLOAD)
2487                     return 0;
2488                 tmpstr = AMG_CALLunary(sv, numer_amg);
2489                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2490                     return SvNV(tmpstr);
2491                 }
2492             }
2493             return PTR2NV(SvRV(sv));
2494         }
2495 #ifdef PERL_OLD_COPY_ON_WRITE
2496         if (SvIsCOW(sv)) {
2497             sv_force_normal_flags(sv, 0);
2498         }
2499 #endif
2500         if (SvREADONLY(sv) && !SvOK(sv)) {
2501             if (ckWARN(WARN_UNINITIALIZED))
2502                 report_uninit(sv);
2503             return 0.0;
2504         }
2505     }
2506     if (SvTYPE(sv) < SVt_NV) {
2507         /* The logic to use SVt_PVNV if necessary is in sv_upgrade.  */
2508         sv_upgrade(sv, SVt_NV);
2509 #ifdef USE_LONG_DOUBLE
2510         DEBUG_c({
2511             STORE_NUMERIC_LOCAL_SET_STANDARD();
2512             PerlIO_printf(Perl_debug_log,
2513                           "0x%"UVxf" num(%" PERL_PRIgldbl ")\n",
2514                           PTR2UV(sv), SvNVX(sv));
2515             RESTORE_NUMERIC_LOCAL();
2516         });
2517 #else
2518         DEBUG_c({
2519             STORE_NUMERIC_LOCAL_SET_STANDARD();
2520             PerlIO_printf(Perl_debug_log, "0x%"UVxf" num(%"NVgf")\n",
2521                           PTR2UV(sv), SvNVX(sv));
2522             RESTORE_NUMERIC_LOCAL();
2523         });
2524 #endif
2525     }
2526     else if (SvTYPE(sv) < SVt_PVNV)
2527         sv_upgrade(sv, SVt_PVNV);
2528     if (SvNOKp(sv)) {
2529         return SvNVX(sv);
2530     }
2531     if (SvIOKp(sv)) {
2532         SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
2533 #ifdef NV_PRESERVES_UV
2534         if (SvIOK(sv))
2535             SvNOK_on(sv);
2536         else
2537             SvNOKp_on(sv);
2538 #else
2539         /* Only set the public NV OK flag if this NV preserves the IV  */
2540         /* Check it's not 0xFFFFFFFFFFFFFFFF */
2541         if (SvIOK(sv) &&
2542             SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
2543                        : (SvIVX(sv) == I_V(SvNVX(sv))))
2544             SvNOK_on(sv);
2545         else
2546             SvNOKp_on(sv);
2547 #endif
2548     }
2549     else if (SvPOKp(sv)) {
2550         UV value;
2551         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2552         if (!SvIOKp(sv) && !numtype && ckWARN(WARN_NUMERIC))
2553             not_a_number(sv);
2554 #ifdef NV_PRESERVES_UV
2555         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2556             == IS_NUMBER_IN_UV) {
2557             /* It's definitely an integer */
2558             SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
2559         } else
2560             SvNV_set(sv, Atof(SvPVX_const(sv)));
2561         if (numtype)
2562             SvNOK_on(sv);
2563         else
2564             SvNOKp_on(sv);
2565 #else
2566         SvNV_set(sv, Atof(SvPVX_const(sv)));
2567         /* Only set the public NV OK flag if this NV preserves the value in
2568            the PV at least as well as an IV/UV would.
2569            Not sure how to do this 100% reliably. */
2570         /* if that shift count is out of range then Configure's test is
2571            wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2572            UV_BITS */
2573         if (((UV)1 << NV_PRESERVES_UV_BITS) >
2574             U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2575             SvNOK_on(sv); /* Definitely small enough to preserve all bits */
2576         } else if (!(numtype & IS_NUMBER_IN_UV)) {
2577             /* Can't use strtol etc to convert this string, so don't try.
2578                sv_2iv and sv_2uv will use the NV to convert, not the PV.  */
2579             SvNOK_on(sv);
2580         } else {
2581             /* value has been set.  It may not be precise.  */
2582             if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2583                 /* 2s complement assumption for (UV)IV_MIN  */
2584                 SvNOK_on(sv); /* Integer is too negative.  */
2585             } else {
2586                 SvNOKp_on(sv);
2587                 SvIOKp_on(sv);
2588
2589                 if (numtype & IS_NUMBER_NEG) {
2590                     SvIV_set(sv, -(IV)value);
2591                 } else if (value <= (UV)IV_MAX) {
2592                     SvIV_set(sv, (IV)value);
2593                 } else {
2594                     SvUV_set(sv, value);
2595                     SvIsUV_on(sv);
2596                 }
2597
2598                 if (numtype & IS_NUMBER_NOT_INT) {
2599                     /* I believe that even if the original PV had decimals,
2600                        they are lost beyond the limit of the FP precision.
2601                        However, neither is canonical, so both only get p
2602                        flags.  NWC, 2000/11/25 */
2603                     /* Both already have p flags, so do nothing */
2604                 } else {
2605                     const NV nv = SvNVX(sv);
2606                     if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2607                         if (SvIVX(sv) == I_V(nv)) {
2608                             SvNOK_on(sv);
2609                         } else {
2610                             /* It had no "." so it must be integer.  */
2611                         }
2612                         SvIOK_on(sv);
2613                     } else {
2614                         /* between IV_MAX and NV(UV_MAX).
2615                            Could be slightly > UV_MAX */
2616
2617                         if (numtype & IS_NUMBER_NOT_INT) {
2618                             /* UV and NV both imprecise.  */
2619                         } else {
2620                             const UV nv_as_uv = U_V(nv);
2621
2622                             if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2623                                 SvNOK_on(sv);
2624                             }
2625                             SvIOK_on(sv);
2626                         }
2627                     }
2628                 }
2629             }
2630         }
2631         /* It might be more code efficient to go through the entire logic above
2632            and conditionally set with SvNOKp_on() rather than SvNOK(), but it
2633            gets complex and potentially buggy, so more programmer efficient
2634            to do it this way, by turning off the public flags:  */
2635         if (!numtype)
2636             SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2637 #endif /* NV_PRESERVES_UV */
2638     }
2639     else  {
2640         if (isGV_with_GP(sv)) {
2641             glob_2number(MUTABLE_GV(sv));
2642             return 0.0;
2643         }
2644
2645         if (!PL_localizing && !SvPADTMP(sv) && ckWARN(WARN_UNINITIALIZED))
2646             report_uninit(sv);
2647         assert (SvTYPE(sv) >= SVt_NV);
2648         /* Typically the caller expects that sv_any is not NULL now.  */
2649         /* XXX Ilya implies that this is a bug in callers that assume this
2650            and ideally should be fixed.  */
2651         return 0.0;
2652     }
2653 #if defined(USE_LONG_DOUBLE)
2654     DEBUG_c({
2655         STORE_NUMERIC_LOCAL_SET_STANDARD();
2656         PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" PERL_PRIgldbl ")\n",
2657                       PTR2UV(sv), SvNVX(sv));
2658         RESTORE_NUMERIC_LOCAL();
2659     });
2660 #else
2661     DEBUG_c({
2662         STORE_NUMERIC_LOCAL_SET_STANDARD();
2663         PerlIO_printf(Perl_debug_log, "0x%"UVxf" 1nv(%"NVgf")\n",
2664                       PTR2UV(sv), SvNVX(sv));
2665         RESTORE_NUMERIC_LOCAL();
2666     });
2667 #endif
2668     return SvNVX(sv);
2669 }
2670
2671 /*
2672 =for apidoc sv_2num
2673
2674 Return an SV with the numeric value of the source SV, doing any necessary
2675 reference or overload conversion.  You must use the C<SvNUM(sv)> macro to
2676 access this function.
2677
2678 =cut
2679 */
2680
2681 SV *
2682 Perl_sv_2num(pTHX_ SV *const sv)
2683 {
2684     PERL_ARGS_ASSERT_SV_2NUM;
2685
2686     if (!SvROK(sv))
2687         return sv;
2688     if (SvAMAGIC(sv)) {
2689         SV * const tmpsv = AMG_CALLunary(sv, numer_amg);
2690         TAINT_IF(tmpsv && SvTAINTED(tmpsv));
2691         if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
2692             return sv_2num(tmpsv);
2693     }
2694     return sv_2mortal(newSVuv(PTR2UV(SvRV(sv))));
2695 }
2696
2697 /* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2698  * UV as a string towards the end of buf, and return pointers to start and
2699  * end of it.
2700  *
2701  * We assume that buf is at least TYPE_CHARS(UV) long.
2702  */
2703
2704 static char *
2705 S_uiv_2buf(char *const buf, const IV iv, UV uv, const int is_uv, char **const peob)
2706 {
2707     char *ptr = buf + TYPE_CHARS(UV);
2708     char * const ebuf = ptr;
2709     int sign;
2710
2711     PERL_ARGS_ASSERT_UIV_2BUF;
2712
2713     if (is_uv)
2714         sign = 0;
2715     else if (iv >= 0) {
2716         uv = iv;
2717         sign = 0;
2718     } else {
2719         uv = -iv;
2720         sign = 1;
2721     }
2722     do {
2723         *--ptr = '0' + (char)(uv % 10);
2724     } while (uv /= 10);
2725     if (sign)
2726         *--ptr = '-';
2727     *peob = ebuf;
2728     return ptr;
2729 }
2730
2731 /*
2732 =for apidoc sv_2pv_flags
2733
2734 Returns a pointer to the string value of an SV, and sets *lp to its length.
2735 If flags includes SV_GMAGIC, does an mg_get() first.  Coerces sv to a
2736 string if necessary.  Normally invoked via the C<SvPV_flags> macro.
2737 C<sv_2pv()> and C<sv_2pv_nomg> usually end up here too.
2738
2739 =cut
2740 */
2741
2742 char *
2743 Perl_sv_2pv_flags(pTHX_ SV *const sv, STRLEN *const lp, const I32 flags)
2744 {
2745     dVAR;
2746     char *s;
2747
2748     if (!sv) {
2749         if (lp)
2750             *lp = 0;
2751         return (char *)"";
2752     }
2753     if (SvGMAGICAL(sv) && (flags & SV_GMAGIC))
2754         mg_get(sv);
2755     if (SvROK(sv)) {
2756         if (SvAMAGIC(sv)) {
2757             SV *tmpstr;
2758             if (flags & SV_SKIP_OVERLOAD)
2759                 return NULL;
2760             tmpstr = AMG_CALLunary(sv, string_amg);
2761             TAINT_IF(tmpstr && SvTAINTED(tmpstr));
2762             if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2763                 /* Unwrap this:  */
2764                 /* char *pv = lp ? SvPV(tmpstr, *lp) : SvPV_nolen(tmpstr);
2765                  */
2766
2767                 char *pv;
2768                 if ((SvFLAGS(tmpstr) & (SVf_POK)) == SVf_POK) {
2769                     if (flags & SV_CONST_RETURN) {
2770                         pv = (char *) SvPVX_const(tmpstr);
2771                     } else {
2772                         pv = (flags & SV_MUTABLE_RETURN)
2773                             ? SvPVX_mutable(tmpstr) : SvPVX(tmpstr);
2774                     }
2775                     if (lp)
2776                         *lp = SvCUR(tmpstr);
2777                 } else {
2778                     pv = sv_2pv_flags(tmpstr, lp, flags);
2779                 }
2780                 if (SvUTF8(tmpstr))
2781                     SvUTF8_on(sv);
2782                 else
2783                     SvUTF8_off(sv);
2784                 return pv;
2785             }
2786         }
2787         {
2788             STRLEN len;
2789             char *retval;
2790             char *buffer;
2791             SV *const referent = SvRV(sv);
2792
2793             if (!referent) {
2794                 len = 7;
2795                 retval = buffer = savepvn("NULLREF", len);
2796             } else if (SvTYPE(referent) == SVt_REGEXP &&
2797                        (!(PL_curcop->cop_hints & HINT_NO_AMAGIC) ||
2798                         amagic_is_enabled(string_amg))) {
2799                 REGEXP * const re = (REGEXP *)MUTABLE_PTR(referent);
2800
2801                 assert(re);
2802                         
2803                 /* If the regex is UTF-8 we want the containing scalar to
2804                    have an UTF-8 flag too */
2805                 if (RX_UTF8(re))
2806                     SvUTF8_on(sv);
2807                 else
2808                     SvUTF8_off(sv);     
2809
2810                 if (lp)
2811                     *lp = RX_WRAPLEN(re);
2812  
2813                 return RX_WRAPPED(re);
2814             } else {
2815                 const char *const typestr = sv_reftype(referent, 0);
2816                 const STRLEN typelen = strlen(typestr);
2817                 UV addr = PTR2UV(referent);
2818                 const char *stashname = NULL;
2819                 STRLEN stashnamelen = 0; /* hush, gcc */
2820                 const char *buffer_end;
2821
2822                 if (SvOBJECT(referent)) {
2823                     const HEK *const name = HvNAME_HEK(SvSTASH(referent));
2824
2825                     if (name) {
2826                         stashname = HEK_KEY(name);
2827                         stashnamelen = HEK_LEN(name);
2828
2829                         if (HEK_UTF8(name)) {
2830                             SvUTF8_on(sv);
2831                         } else {
2832                             SvUTF8_off(sv);
2833                         }
2834                     } else {
2835                         stashname = "__ANON__";
2836                         stashnamelen = 8;
2837                     }
2838                     len = stashnamelen + 1 /* = */ + typelen + 3 /* (0x */
2839                         + 2 * sizeof(UV) + 2 /* )\0 */;
2840                 } else {
2841                     len = typelen + 3 /* (0x */
2842                         + 2 * sizeof(UV) + 2 /* )\0 */;
2843                 }
2844
2845                 Newx(buffer, len, char);
2846                 buffer_end = retval = buffer + len;
2847
2848                 /* Working backwards  */
2849                 *--retval = '\0';
2850                 *--retval = ')';
2851                 do {
2852                     *--retval = PL_hexdigit[addr & 15];
2853                 } while (addr >>= 4);
2854                 *--retval = 'x';
2855                 *--retval = '0';
2856                 *--retval = '(';
2857
2858                 retval -= typelen;
2859                 memcpy(retval, typestr, typelen);
2860
2861                 if (stashname) {
2862                     *--retval = '=';
2863                     retval -= stashnamelen;
2864                     memcpy(retval, stashname, stashnamelen);
2865                 }
2866                 /* retval may not necessarily have reached the start of the
2867                    buffer here.  */
2868                 assert (retval >= buffer);
2869
2870                 len = buffer_end - retval - 1; /* -1 for that \0  */
2871             }
2872             if (lp)
2873                 *lp = len;
2874             SAVEFREEPV(buffer);
2875             return retval;
2876         }
2877     }
2878
2879     if (SvPOKp(sv)) {
2880         if (lp)
2881             *lp = SvCUR(sv);
2882         if (flags & SV_MUTABLE_RETURN)
2883             return SvPVX_mutable(sv);
2884         if (flags & SV_CONST_RETURN)
2885             return (char *)SvPVX_const(sv);
2886         return SvPVX(sv);
2887     }
2888
2889     if (SvIOK(sv)) {
2890         /* I'm assuming that if both IV and NV are equally valid then
2891            converting the IV is going to be more efficient */
2892         const U32 isUIOK = SvIsUV(sv);
2893         char buf[TYPE_CHARS(UV)];
2894         char *ebuf, *ptr;
2895         STRLEN len;
2896
2897         if (SvTYPE(sv) < SVt_PVIV)
2898             sv_upgrade(sv, SVt_PVIV);
2899         ptr = uiv_2buf(buf, SvIVX(sv), SvUVX(sv), isUIOK, &ebuf);
2900         len = ebuf - ptr;
2901         /* inlined from sv_setpvn */
2902         s = SvGROW_mutable(sv, len + 1);
2903         Move(ptr, s, len, char);
2904         s += len;
2905         *s = '\0';
2906         SvPOK_on(sv);
2907     }
2908     else if (SvNOK(sv)) {
2909         if (SvTYPE(sv) < SVt_PVNV)
2910             sv_upgrade(sv, SVt_PVNV);
2911         if (SvNVX(sv) == 0.0) {
2912             s = SvGROW_mutable(sv, 2);
2913             *s++ = '0';
2914             *s = '\0';
2915         } else {
2916             dSAVE_ERRNO;
2917             /* The +20 is pure guesswork.  Configure test needed. --jhi */
2918             s = SvGROW_mutable(sv, NV_DIG + 20);
2919             /* some Xenix systems wipe out errno here */
2920
2921 #ifndef USE_LOCALE_NUMERIC
2922             Gconvert(SvNVX(sv), NV_DIG, 0, s);
2923             SvPOK_on(sv);
2924 #else
2925             /* Gconvert always uses the current locale.  That's the right thing
2926              * to do if we're supposed to be using locales.  But otherwise, we
2927              * want the result to be based on the C locale, so we need to
2928              * change to the C locale during the Gconvert and then change back.
2929              * But if we're already in the C locale (PL_numeric_standard is
2930              * TRUE in that case), no need to do any changing */
2931             if (PL_numeric_standard || IN_LOCALE_RUNTIME) {
2932                 Gconvert(SvNVX(sv), NV_DIG, 0, s);
2933             }
2934             else {
2935                 char *loc = savepv(setlocale(LC_NUMERIC, NULL));
2936                 setlocale(LC_NUMERIC, "C");
2937                 Gconvert(SvNVX(sv), NV_DIG, 0, s);
2938                 setlocale(LC_NUMERIC, loc);
2939                 Safefree(loc);
2940             }
2941
2942             /* We don't call SvPOK_on(), because it may come to pass that the
2943              * locale changes so that the stringification we just did is no
2944              * longer correct.  We will have to re-stringify every time it is
2945              * needed */
2946 #endif
2947             RESTORE_ERRNO;
2948             while (*s) s++;
2949         }
2950 #ifdef hcx
2951         if (s[-1] == '.')
2952             *--s = '\0';
2953 #endif
2954     }
2955     else if (isGV_with_GP(sv)) {
2956         GV *const gv = MUTABLE_GV(sv);
2957         SV *const buffer = sv_newmortal();
2958
2959         gv_efullname3(buffer, gv, "*");
2960
2961         assert(SvPOK(buffer));
2962         if (SvUTF8(buffer))
2963             SvUTF8_on(sv);
2964         if (lp)
2965             *lp = SvCUR(buffer);
2966         return SvPVX(buffer);
2967     }
2968     else if (isREGEXP(sv)) {
2969         if (lp) *lp = RX_WRAPLEN((REGEXP *)sv);
2970         return RX_WRAPPED((REGEXP *)sv);
2971     }
2972     else {
2973         if (lp)
2974             *lp = 0;
2975         if (flags & SV_UNDEF_RETURNS_NULL)
2976             return NULL;
2977         if (!PL_localizing && !SvPADTMP(sv) && ckWARN(WARN_UNINITIALIZED))
2978             report_uninit(sv);
2979         /* Typically the caller expects that sv_any is not NULL now.  */
2980         if (!SvREADONLY(sv) && SvTYPE(sv) < SVt_PV)
2981             sv_upgrade(sv, SVt_PV);
2982         return (char *)"";
2983     }
2984
2985     {
2986         const STRLEN len = s - SvPVX_const(sv);
2987         if (lp) 
2988             *lp = len;
2989         SvCUR_set(sv, len);
2990     }
2991     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
2992                           PTR2UV(sv),SvPVX_const(sv)));
2993     if (flags & SV_CONST_RETURN)
2994         return (char *)SvPVX_const(sv);
2995     if (flags & SV_MUTABLE_RETURN)
2996         return SvPVX_mutable(sv);
2997     return SvPVX(sv);
2998 }
2999
3000 /*
3001 =for apidoc sv_copypv
3002
3003 Copies a stringified representation of the source SV into the
3004 destination SV.  Automatically performs any necessary mg_get and
3005 coercion of numeric values into strings.  Guaranteed to preserve
3006 UTF8 flag even from overloaded objects.  Similar in nature to
3007 sv_2pv[_flags] but operates directly on an SV instead of just the
3008 string.  Mostly uses sv_2pv_flags to do its work, except when that
3009 would lose the UTF-8'ness of the PV.
3010
3011 =for apidoc sv_copypv_nomg
3012
3013 Like sv_copypv, but doesn't invoke get magic first.
3014
3015 =for apidoc sv_copypv_flags
3016
3017 Implementation of sv_copypv and sv_copypv_nomg.  Calls get magic iff flags
3018 include SV_GMAGIC.
3019
3020 =cut
3021 */
3022
3023 void
3024 Perl_sv_copypv(pTHX_ SV *const dsv, SV *const ssv)
3025 {
3026     PERL_ARGS_ASSERT_SV_COPYPV;
3027
3028     sv_copypv_flags(dsv, ssv, 0);
3029 }
3030
3031 void
3032 Perl_sv_copypv_flags(pTHX_ SV *const dsv, SV *const ssv, const I32 flags)
3033 {
3034     STRLEN len;
3035     const char *s;
3036
3037     PERL_ARGS_ASSERT_SV_COPYPV_FLAGS;
3038
3039     if ((flags & SV_GMAGIC) && SvGMAGICAL(ssv))
3040         mg_get(ssv);
3041     s = SvPV_nomg_const(ssv,len);
3042     sv_setpvn(dsv,s,len);
3043     if (SvUTF8(ssv))
3044         SvUTF8_on(dsv);
3045     else
3046         SvUTF8_off(dsv);
3047 }
3048
3049 /*
3050 =for apidoc sv_2pvbyte
3051
3052 Return a pointer to the byte-encoded representation of the SV, and set *lp
3053 to its length.  May cause the SV to be downgraded from UTF-8 as a
3054 side-effect.
3055
3056 Usually accessed via the C<SvPVbyte> macro.
3057
3058 =cut
3059 */
3060
3061 char *
3062 Perl_sv_2pvbyte(pTHX_ SV *sv, STRLEN *const lp)
3063 {
3064     PERL_ARGS_ASSERT_SV_2PVBYTE;
3065
3066     if (((SvREADONLY(sv) || SvFAKE(sv)) && !SvIsCOW(sv))
3067      || isGV_with_GP(sv) || SvROK(sv)) {
3068         SV *sv2 = sv_newmortal();
3069         sv_copypv(sv2,sv);
3070         sv = sv2;
3071     }
3072     else SvGETMAGIC(sv);
3073     sv_utf8_downgrade(sv,0);
3074     return lp ? SvPV_nomg(sv,*lp) : SvPV_nomg_nolen(sv);
3075 }
3076
3077 /*
3078 =for apidoc sv_2pvutf8
3079
3080 Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
3081 to its length.  May cause the SV to be upgraded to UTF-8 as a side-effect.
3082
3083 Usually accessed via the C<SvPVutf8> macro.
3084
3085 =cut
3086 */
3087
3088 char *
3089 Perl_sv_2pvutf8(pTHX_ SV *sv, STRLEN *const lp)
3090 {
3091     PERL_ARGS_ASSERT_SV_2PVUTF8;
3092
3093     if (((SvREADONLY(sv) || SvFAKE(sv)) && !SvIsCOW(sv))
3094      || isGV_with_GP(sv) || SvROK(sv))
3095         sv = sv_mortalcopy(sv);
3096     else
3097         SvGETMAGIC(sv);
3098     sv_utf8_upgrade_nomg(sv);
3099     return lp ? SvPV_nomg(sv,*lp) : SvPV_nomg_nolen(sv);
3100 }
3101
3102
3103 /*
3104 =for apidoc sv_2bool
3105
3106 This macro is only used by sv_true() or its macro equivalent, and only if
3107 the latter's argument is neither SvPOK, SvIOK nor SvNOK.
3108 It calls sv_2bool_flags with the SV_GMAGIC flag.
3109
3110 =for apidoc sv_2bool_flags
3111
3112 This function is only used by sv_true() and friends,  and only if
3113 the latter's argument is neither SvPOK, SvIOK nor SvNOK.  If the flags
3114 contain SV_GMAGIC, then it does an mg_get() first.
3115
3116
3117 =cut
3118 */
3119
3120 bool
3121 Perl_sv_2bool_flags(pTHX_ SV *const sv, const I32 flags)
3122 {
3123     dVAR;
3124
3125     PERL_ARGS_ASSERT_SV_2BOOL_FLAGS;
3126
3127     if(flags & SV_GMAGIC) SvGETMAGIC(sv);
3128
3129     if (!SvOK(sv))
3130         return 0;
3131     if (SvROK(sv)) {
3132         if (SvAMAGIC(sv)) {
3133             SV * const tmpsv = AMG_CALLunary(sv, bool__amg);
3134             if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
3135                 return cBOOL(SvTRUE(tmpsv));
3136         }
3137         return SvRV(sv) != 0;
3138     }
3139     return SvTRUE_common(sv, isGV_with_GP(sv) ? 1 : 0);
3140 }
3141
3142 /*
3143 =for apidoc sv_utf8_upgrade
3144
3145 Converts the PV of an SV to its UTF-8-encoded form.
3146 Forces the SV to string form if it is not already.
3147 Will C<mg_get> on C<sv> if appropriate.
3148 Always sets the SvUTF8 flag to avoid future validity checks even
3149 if the whole string is the same in UTF-8 as not.
3150 Returns the number of bytes in the converted string
3151
3152 This is not a general purpose byte encoding to Unicode interface:
3153 use the Encode extension for that.
3154
3155 =for apidoc sv_utf8_upgrade_nomg
3156
3157 Like sv_utf8_upgrade, but doesn't do magic on C<sv>.
3158
3159 =for apidoc sv_utf8_upgrade_flags
3160
3161 Converts the PV of an SV to its UTF-8-encoded form.
3162 Forces the SV to string form if it is not already.
3163 Always sets the SvUTF8 flag to avoid future validity checks even
3164 if all the bytes are invariant in UTF-8.
3165 If C<flags> has C<SV_GMAGIC> bit set,
3166 will C<mg_get> on C<sv> if appropriate, else not.
3167 Returns the number of bytes in the converted string
3168 C<sv_utf8_upgrade> and
3169 C<sv_utf8_upgrade_nomg> are implemented in terms of this function.
3170
3171 This is not a general purpose byte encoding to Unicode interface:
3172 use the Encode extension for that.
3173
3174 =cut
3175
3176 The grow version is currently not externally documented.  It adds a parameter,
3177 extra, which is the number of unused bytes the string of 'sv' is guaranteed to
3178 have free after it upon return.  This allows the caller to reserve extra space
3179 that it intends to fill, to avoid extra grows.
3180
3181 Also externally undocumented for the moment is the flag SV_FORCE_UTF8_UPGRADE,
3182 which can be used to tell this function to not first check to see if there are
3183 any characters that are different in UTF-8 (variant characters) which would
3184 force it to allocate a new string to sv, but to assume there are.  Typically
3185 this flag is used by a routine that has already parsed the string to find that
3186 there are such characters, and passes this information on so that the work
3187 doesn't have to be repeated.
3188
3189 (One might think that the calling routine could pass in the position of the
3190 first such variant, so it wouldn't have to be found again.  But that is not the
3191 case, because typically when the caller is likely to use this flag, it won't be
3192 calling this routine unless it finds something that won't fit into a byte.
3193 Otherwise it tries to not upgrade and just use bytes.  But some things that
3194 do fit into a byte are variants in utf8, and the caller may not have been
3195 keeping track of these.)
3196
3197 If the routine itself changes the string, it adds a trailing NUL.  Such a NUL
3198 isn't guaranteed due to having other routines do the work in some input cases,
3199 or if the input is already flagged as being in utf8.
3200
3201 The speed of this could perhaps be improved for many cases if someone wanted to
3202 write a fast function that counts the number of variant characters in a string,
3203 especially if it could return the position of the first one.
3204
3205 */
3206
3207 STRLEN
3208 Perl_sv_utf8_upgrade_flags_grow(pTHX_ SV *const sv, const I32 flags, STRLEN extra)
3209 {
3210     dVAR;
3211
3212     PERL_ARGS_ASSERT_SV_UTF8_UPGRADE_FLAGS_GROW;
3213
3214     if (sv == &PL_sv_undef)
3215         return 0;
3216     if (!SvPOK_nog(sv)) {
3217         STRLEN len = 0;
3218         if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
3219             (void) sv_2pv_flags(sv,&len, flags);
3220             if (SvUTF8(sv)) {
3221                 if (extra) SvGROW(sv, SvCUR(sv) + extra);
3222                 return len;
3223             }
3224         } else {
3225             (void) SvPV_force_flags(sv,len,flags & SV_GMAGIC);
3226         }
3227     }
3228
3229     if (SvUTF8(sv)) {
3230         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3231         return SvCUR(sv);
3232     }
3233
3234     if (SvIsCOW(sv)) {
3235         sv_force_normal_flags(sv, 0);
3236     }
3237
3238     if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING)) {
3239         sv_recode_to_utf8(sv, PL_encoding);
3240         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3241         return SvCUR(sv);
3242     }
3243
3244     if (SvCUR(sv) == 0) {
3245         if (extra) SvGROW(sv, extra);
3246     } else { /* Assume Latin-1/EBCDIC */
3247         /* This function could be much more efficient if we
3248          * had a FLAG in SVs to signal if there are any variant
3249          * chars in the PV.  Given that there isn't such a flag
3250          * make the loop as fast as possible (although there are certainly ways
3251          * to speed this up, eg. through vectorization) */
3252         U8 * s = (U8 *) SvPVX_const(sv);
3253         U8 * e = (U8 *) SvEND(sv);
3254         U8 *t = s;
3255         STRLEN two_byte_count = 0;
3256         
3257         if (flags & SV_FORCE_UTF8_UPGRADE) goto must_be_utf8;
3258
3259         /* See if really will need to convert to utf8.  We mustn't rely on our
3260          * incoming SV being well formed and having a trailing '\0', as certain
3261          * code in pp_formline can send us partially built SVs. */
3262
3263         while (t < e) {
3264             const U8 ch = *t++;
3265             if (NATIVE_IS_INVARIANT(ch)) continue;
3266
3267             t--;    /* t already incremented; re-point to first variant */
3268             two_byte_count = 1;
3269             goto must_be_utf8;
3270         }
3271
3272         /* utf8 conversion not needed because all are invariants.  Mark as
3273          * UTF-8 even if no variant - saves scanning loop */
3274         SvUTF8_on(sv);
3275         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3276         return SvCUR(sv);
3277
3278 must_be_utf8:
3279
3280         /* Here, the string should be converted to utf8, either because of an
3281          * input flag (two_byte_count = 0), or because a character that
3282          * requires 2 bytes was found (two_byte_count = 1).  t points either to
3283          * the beginning of the string (if we didn't examine anything), or to
3284          * the first variant.  In either case, everything from s to t - 1 will
3285          * occupy only 1 byte each on output.
3286          *
3287          * There are two main ways to convert.  One is to create a new string
3288          * and go through the input starting from the beginning, appending each
3289          * converted value onto the new string as we go along.  It's probably
3290          * best to allocate enough space in the string for the worst possible
3291          * case rather than possibly running out of space and having to
3292          * reallocate and then copy what we've done so far.  Since everything
3293          * from s to t - 1 is invariant, the destination can be initialized
3294          * with these using a fast memory copy
3295          *
3296          * The other way is to figure out exactly how big the string should be
3297          * by parsing the entire input.  Then you don't have to make it big
3298          * enough to handle the worst possible case, and more importantly, if
3299          * the string you already have is large enough, you don't have to
3300          * allocate a new string, you can copy the last character in the input
3301          * string to the final position(s) that will be occupied by the
3302          * converted string and go backwards, stopping at t, since everything
3303          * before that is invariant.
3304          *
3305          * There are advantages and disadvantages to each method.
3306          *
3307          * In the first method, we can allocate a new string, do the memory
3308          * copy from the s to t - 1, and then proceed through the rest of the
3309          * string byte-by-byte.
3310          *
3311          * In the second method, we proceed through the rest of the input
3312          * string just calculating how big the converted string will be.  Then
3313          * there are two cases:
3314          *  1)  if the string has enough extra space to handle the converted
3315          *      value.  We go backwards through the string, converting until we
3316          *      get to the position we are at now, and then stop.  If this
3317          *      position is far enough along in the string, this method is
3318          *      faster than the other method.  If the memory copy were the same
3319          *      speed as the byte-by-byte loop, that position would be about
3320          *      half-way, as at the half-way mark, parsing to the end and back
3321          *      is one complete string's parse, the same amount as starting
3322          *      over and going all the way through.  Actually, it would be
3323          *      somewhat less than half-way, as it's faster to just count bytes
3324          *      than to also copy, and we don't have the overhead of allocating
3325          *      a new string, changing the scalar to use it, and freeing the
3326          *      existing one.  But if the memory copy is fast, the break-even
3327          *      point is somewhere after half way.  The counting loop could be
3328          *      sped up by vectorization, etc, to move the break-even point
3329          *      further towards the beginning.
3330          *  2)  if the string doesn't have enough space to handle the converted
3331          *      value.  A new string will have to be allocated, and one might
3332          *      as well, given that, start from the beginning doing the first
3333          *      method.  We've spent extra time parsing the string and in
3334          *      exchange all we've gotten is that we know precisely how big to
3335          *      make the new one.  Perl is more optimized for time than space,
3336          *      so this case is a loser.
3337          * So what I've decided to do is not use the 2nd method unless it is
3338          * guaranteed that a new string won't have to be allocated, assuming
3339          * the worst case.  I also decided not to put any more conditions on it
3340          * than this, for now.  It seems likely that, since the worst case is
3341          * twice as big as the unknown portion of the string (plus 1), we won't
3342          * be guaranteed enough space, causing us to go to the first method,
3343          * unless the string is short, or the first variant character is near
3344          * the end of it.  In either of these cases, it seems best to use the
3345          * 2nd method.  The only circumstance I can think of where this would
3346          * be really slower is if the string had once had much more data in it
3347          * than it does now, but there is still a substantial amount in it  */
3348
3349         {
3350             STRLEN invariant_head = t - s;
3351             STRLEN size = invariant_head + (e - t) * 2 + 1 + extra;
3352             if (SvLEN(sv) < size) {
3353
3354                 /* Here, have decided to allocate a new string */
3355
3356                 U8 *dst;
3357                 U8 *d;
3358
3359                 Newx(dst, size, U8);
3360
3361                 /* If no known invariants at the beginning of the input string,
3362                  * set so starts from there.  Otherwise, can use memory copy to
3363                  * get up to where we are now, and then start from here */
3364
3365                 if (invariant_head <= 0) {
3366                     d = dst;
3367                 } else {
3368                     Copy(s, dst, invariant_head, char);
3369                     d = dst + invariant_head;
3370                 }
3371
3372                 while (t < e) {
3373                     const UV uv = NATIVE8_TO_UNI(*t++);
3374                     if (UNI_IS_INVARIANT(uv))
3375                         *d++ = (U8)UNI_TO_NATIVE(uv);
3376                     else {
3377                         *d++ = (U8)UTF8_EIGHT_BIT_HI(uv);
3378                         *d++ = (U8)UTF8_EIGHT_BIT_LO(uv);
3379                     }
3380                 }
3381                 *d = '\0';
3382                 SvPV_free(sv); /* No longer using pre-existing string */
3383                 SvPV_set(sv, (char*)dst);
3384                 SvCUR_set(sv, d - dst);
3385                 SvLEN_set(sv, size);
3386             } else {
3387
3388                 /* Here, have decided to get the exact size of the string.
3389                  * Currently this happens only when we know that there is
3390                  * guaranteed enough space to fit the converted string, so
3391                  * don't have to worry about growing.  If two_byte_count is 0,
3392                  * then t points to the first byte of the string which hasn't
3393                  * been examined yet.  Otherwise two_byte_count is 1, and t
3394                  * points to the first byte in the string that will expand to
3395                  * two.  Depending on this, start examining at t or 1 after t.
3396                  * */
3397
3398                 U8 *d = t + two_byte_count;
3399
3400
3401                 /* Count up the remaining bytes that expand to two */
3402
3403                 while (d < e) {
3404                     const U8 chr = *d++;
3405                     if (! NATIVE_IS_INVARIANT(chr)) two_byte_count++;
3406                 }
3407
3408                 /* The string will expand by just the number of bytes that
3409                  * occupy two positions.  But we are one afterwards because of
3410                  * the increment just above.  This is the place to put the
3411                  * trailing NUL, and to set the length before we decrement */
3412
3413                 d += two_byte_count;
3414                 SvCUR_set(sv, d - s);
3415                 *d-- = '\0';
3416
3417
3418                 /* Having decremented d, it points to the position to put the
3419                  * very last byte of the expanded string.  Go backwards through
3420                  * the string, copying and expanding as we go, stopping when we
3421                  * get to the part that is invariant the rest of the way down */
3422
3423                 e--;
3424                 while (e >= t) {
3425                     const U8 ch = NATIVE8_TO_UNI(*e--);
3426                     if (UNI_IS_INVARIANT(ch)) {
3427                         *d-- = UNI_TO_NATIVE(ch);
3428                     } else {
3429                         *d-- = (U8)UTF8_EIGHT_BIT_LO(ch);
3430                         *d-- = (U8)UTF8_EIGHT_BIT_HI(ch);
3431                     }
3432                 }
3433             }
3434
3435             if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3436                 /* Update pos. We do it at the end rather than during
3437                  * the upgrade, to avoid slowing down the common case
3438                  * (upgrade without pos) */
3439                 MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3440                 if (mg) {
3441                     I32 pos = mg->mg_len;
3442                     if (pos > 0 && (U32)pos > invariant_head) {
3443                         U8 *d = (U8*) SvPVX(sv) + invariant_head;
3444                         STRLEN n = (U32)pos - invariant_head;
3445                         while (n > 0) {
3446                             if (UTF8_IS_START(*d))
3447                                 d++;
3448                             d++;
3449                             n--;
3450                         }
3451                         mg->mg_len  = d - (U8*)SvPVX(sv);
3452                     }
3453                 }
3454                 if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3455                     magic_setutf8(sv,mg); /* clear UTF8 cache */
3456             }
3457         }
3458     }
3459
3460     /* Mark as UTF-8 even if no variant - saves scanning loop */
3461     SvUTF8_on(sv);
3462     return SvCUR(sv);
3463 }
3464
3465 /*
3466 =for apidoc sv_utf8_downgrade
3467
3468 Attempts to convert the PV of an SV from characters to bytes.
3469 If the PV contains a character that cannot fit
3470 in a byte, this conversion will fail;
3471 in this case, either returns false or, if C<fail_ok> is not
3472 true, croaks.
3473
3474 This is not a general purpose Unicode to byte encoding interface:
3475 use the Encode extension for that.
3476
3477 =cut
3478 */
3479
3480 bool
3481 Perl_sv_utf8_downgrade(pTHX_ SV *const sv, const bool fail_ok)
3482 {
3483     dVAR;
3484
3485     PERL_ARGS_ASSERT_SV_UTF8_DOWNGRADE;
3486
3487     if (SvPOKp(sv) && SvUTF8(sv)) {
3488         if (SvCUR(sv)) {
3489             U8 *s;
3490             STRLEN len;
3491             int mg_flags = SV_GMAGIC;
3492
3493             if (SvIsCOW(sv)) {
3494                 sv_force_normal_flags(sv, 0);
3495             }
3496             if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3497                 /* update pos */
3498                 MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3499                 if (mg) {
3500                     I32 pos = mg->mg_len;
3501                     if (pos > 0) {
3502                         sv_pos_b2u(sv, &pos);
3503                         mg_flags = 0; /* sv_pos_b2u does get magic */
3504                         mg->mg_len  = pos;
3505                     }
3506                 }
3507                 if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3508                     magic_setutf8(sv,mg); /* clear UTF8 cache */
3509
3510             }
3511             s = (U8 *) SvPV_flags(sv, len, mg_flags);
3512
3513             if (!utf8_to_bytes(s, &len)) {
3514                 if (fail_ok)
3515                     return FALSE;
3516                 else {
3517                     if (PL_op)
3518                         Perl_croak(aTHX_ "Wide character in %s",
3519                                    OP_DESC(PL_op));
3520                     else
3521                         Perl_croak(aTHX_ "Wide character");
3522                 }
3523             }
3524             SvCUR_set(sv, len);
3525         }
3526     }
3527     SvUTF8_off(sv);
3528     return TRUE;
3529 }
3530
3531 /*
3532 =for apidoc sv_utf8_encode
3533
3534 Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3535 flag off so that it looks like octets again.
3536
3537 =cut
3538 */
3539
3540 void
3541 Perl_sv_utf8_encode(pTHX_ SV *const sv)
3542 {
3543     PERL_ARGS_ASSERT_SV_UTF8_ENCODE;
3544
3545     if (SvREADONLY(sv)) {
3546         sv_force_normal_flags(sv, 0);
3547     }
3548     (void) sv_utf8_upgrade(sv);
3549     SvUTF8_off(sv);
3550 }
3551
3552 /*
3553 =for apidoc sv_utf8_decode
3554
3555 If the PV of the SV is an octet sequence in UTF-8
3556 and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3557 so that it looks like a character.  If the PV contains only single-byte
3558 characters, the C<SvUTF8> flag stays off.
3559 Scans PV for validity and returns false if the PV is invalid UTF-8.
3560
3561 =cut
3562 */
3563
3564 bool
3565 Perl_sv_utf8_decode(pTHX_ SV *const sv)
3566 {
3567     PERL_ARGS_ASSERT_SV_UTF8_DECODE;
3568
3569     if (SvPOKp(sv)) {
3570         const U8 *start, *c;
3571         const U8 *e;
3572
3573         /* The octets may have got themselves encoded - get them back as
3574          * bytes
3575          */
3576         if (!sv_utf8_downgrade(sv, TRUE))
3577             return FALSE;
3578
3579         /* it is actually just a matter of turning the utf8 flag on, but
3580          * we want to make sure everything inside is valid utf8 first.
3581          */
3582         c = start = (const U8 *) SvPVX_const(sv);
3583         if (!is_utf8_string(c, SvCUR(sv)))
3584             return FALSE;
3585         e = (const U8 *) SvEND(sv);
3586         while (c < e) {
3587             const U8 ch = *c++;
3588             if (!UTF8_IS_INVARIANT(ch)) {
3589                 SvUTF8_on(sv);
3590                 break;
3591             }
3592         }
3593         if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3594             /* adjust pos to the start of a UTF8 char sequence */
3595             MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3596             if (mg) {
3597                 I32 pos = mg->mg_len;
3598                 if (pos > 0) {
3599                     for (c = start + pos; c > start; c--) {
3600                         if (UTF8_IS_START(*c))
3601                             break;
3602                     }
3603                     mg->mg_len  = c - start;
3604                 }
3605             }
3606             if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3607                 magic_setutf8(sv,mg); /* clear UTF8 cache */
3608         }
3609     }
3610     return TRUE;
3611 }
3612
3613 /*
3614 =for apidoc sv_setsv
3615
3616 Copies the contents of the source SV C<ssv> into the destination SV
3617 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3618 function if the source SV needs to be reused.  Does not handle 'set' magic.
3619 Loosely speaking, it performs a copy-by-value, obliterating any previous
3620 content of the destination.
3621
3622 You probably want to use one of the assortment of wrappers, such as
3623 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3624 C<SvSetMagicSV_nosteal>.
3625
3626 =for apidoc sv_setsv_flags
3627
3628 Copies the contents of the source SV C<ssv> into the destination SV
3629 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3630 function if the source SV needs to be reused.  Does not handle 'set' magic.
3631 Loosely speaking, it performs a copy-by-value, obliterating any previous
3632 content of the destination.
3633 If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
3634 C<ssv> if appropriate, else not.  If the C<flags>
3635 parameter has the C<NOSTEAL> bit set then the
3636 buffers of temps will not be stolen.  <sv_setsv>
3637 and C<sv_setsv_nomg> are implemented in terms of this function.
3638
3639 You probably want to use one of the assortment of wrappers, such as
3640 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3641 C<SvSetMagicSV_nosteal>.
3642
3643 This is the primary function for copying scalars, and most other
3644 copy-ish functions and macros use this underneath.
3645
3646 =cut
3647 */
3648
3649 static void
3650 S_glob_assign_glob(pTHX_ SV *const dstr, SV *const sstr, const int dtype)
3651 {
3652     I32 mro_changes = 0; /* 1 = method, 2 = isa, 3 = recursive isa */
3653     HV *old_stash = NULL;
3654
3655     PERL_ARGS_ASSERT_GLOB_ASSIGN_GLOB;
3656
3657     if (dtype != SVt_PVGV && !isGV_with_GP(dstr)) {
3658         const char * const name = GvNAME(sstr);
3659         const STRLEN len = GvNAMELEN(sstr);
3660         {
3661             if (dtype >= SVt_PV) {
3662                 SvPV_free(dstr);
3663                 SvPV_set(dstr, 0);
3664                 SvLEN_set(dstr, 0);
3665                 SvCUR_set(dstr, 0);
3666             }
3667             SvUPGRADE(dstr, SVt_PVGV);
3668             (void)SvOK_off(dstr);
3669             /* We have to turn this on here, even though we turn it off
3670                below, as GvSTASH will fail an assertion otherwise. */
3671             isGV_with_GP_on(dstr);
3672         }
3673         GvSTASH(dstr) = GvSTASH(sstr);
3674         if (GvSTASH(dstr))
3675             Perl_sv_add_backref(aTHX_ MUTABLE_SV(GvSTASH(dstr)), dstr);
3676         gv_name_set(MUTABLE_GV(dstr), name, len,
3677                         GV_ADD | (GvNAMEUTF8(sstr) ? SVf_UTF8 : 0 ));
3678         SvFAKE_on(dstr);        /* can coerce to non-glob */
3679     }
3680
3681     if(GvGP(MUTABLE_GV(sstr))) {
3682         /* If source has method cache entry, clear it */
3683         if(GvCVGEN(sstr)) {
3684             SvREFCNT_dec(GvCV(sstr));
3685             GvCV_set(sstr, NULL);
3686             GvCVGEN(sstr) = 0;
3687         }
3688         /* If source has a real method, then a method is
3689            going to change */
3690         else if(
3691          GvCV((const GV *)sstr) && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3692         ) {
3693             mro_changes = 1;
3694         }
3695     }
3696
3697     /* If dest already had a real method, that's a change as well */
3698     if(
3699         !mro_changes && GvGP(MUTABLE_GV(dstr)) && GvCVu((const GV *)dstr)
3700      && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3701     ) {
3702         mro_changes = 1;
3703     }
3704
3705     /* We don't need to check the name of the destination if it was not a
3706        glob to begin with. */
3707     if(dtype == SVt_PVGV) {
3708         const char * const name = GvNAME((const GV *)dstr);
3709         if(
3710             strEQ(name,"ISA")
3711          /* The stash may have been detached from the symbol table, so
3712             check its name. */
3713          && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3714         )
3715             mro_changes = 2;
3716         else {
3717             const STRLEN len = GvNAMELEN(dstr);
3718             if ((len > 1 && name[len-2] == ':' && name[len-1] == ':')
3719              || (len == 1 && name[0] == ':')) {
3720                 mro_changes = 3;
3721
3722                 /* Set aside the old stash, so we can reset isa caches on
3723                    its subclasses. */
3724                 if((old_stash = GvHV(dstr)))
3725                     /* Make sure we do not lose it early. */
3726                     SvREFCNT_inc_simple_void_NN(
3727                      sv_2mortal((SV *)old_stash)
3728                     );
3729             }
3730         }
3731     }
3732
3733     gp_free(MUTABLE_GV(dstr));
3734     isGV_with_GP_off(dstr); /* SvOK_off does not like globs. */
3735     (void)SvOK_off(dstr);
3736     isGV_with_GP_on(dstr);
3737     GvINTRO_off(dstr);          /* one-shot flag */
3738     GvGP_set(dstr, gp_ref(GvGP(sstr)));
3739     if (SvTAINTED(sstr))
3740         SvTAINT(dstr);
3741     if (GvIMPORTED(dstr) != GVf_IMPORTED
3742         && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3743         {
3744             GvIMPORTED_on(dstr);
3745         }
3746     GvMULTI_on(dstr);
3747     if(mro_changes == 2) {
3748       if (GvAV((const GV *)sstr)) {
3749         MAGIC *mg;
3750         SV * const sref = (SV *)GvAV((const GV *)dstr);
3751         if (SvSMAGICAL(sref) && (mg = mg_find(sref, PERL_MAGIC_isa))) {
3752             if (SvTYPE(mg->mg_obj) != SVt_PVAV) {
3753                 AV * const ary = newAV();
3754                 av_push(ary, mg->mg_obj); /* takes the refcount */
3755                 mg->mg_obj = (SV *)ary;
3756             }
3757             av_push((AV *)mg->mg_obj, SvREFCNT_inc_simple_NN(dstr));
3758         }
3759         else sv_magic(sref, dstr, PERL_MAGIC_isa, NULL, 0);
3760       }
3761       mro_isa_changed_in(GvSTASH(dstr));
3762     }
3763     else if(mro_changes == 3) {
3764         HV * const stash = GvHV(dstr);
3765         if(old_stash ? (HV *)HvENAME_get(old_stash) : stash)
3766             mro_package_moved(
3767                 stash, old_stash,
3768                 (GV *)dstr, 0
3769             );
3770     }
3771     else if(mro_changes) mro_method_changed_in(GvSTASH(dstr));
3772     if (GvIO(dstr) && dtype == SVt_PVGV) {
3773         DEBUG_o(Perl_deb(aTHX_
3774                         "glob_assign_glob clearing PL_stashcache\n"));
3775         /* It's a cache. It will rebuild itself quite happily.
3776            It's a lot of effort to work out exactly which key (or keys)
3777            might be invalidated by the creation of the this file handle.
3778          */
3779         hv_clear(PL_stashcache);
3780     }
3781     return;
3782 }
3783
3784 static void
3785 S_glob_assign_ref(pTHX_ SV *const dstr, SV *const sstr)
3786 {
3787     SV * const sref = SvRV(sstr);
3788     SV *dref;
3789     const int intro = GvINTRO(dstr);
3790     SV **location;
3791     U8 import_flag = 0;
3792     const U32 stype = SvTYPE(sref);
3793
3794     PERL_ARGS_ASSERT_GLOB_ASSIGN_REF;
3795
3796     if (intro) {
3797         GvINTRO_off(dstr);      /* one-shot flag */
3798         GvLINE(dstr) = CopLINE(PL_curcop);
3799         GvEGV(dstr) = MUTABLE_GV(dstr);
3800     }
3801     GvMULTI_on(dstr);
3802     switch (stype) {
3803     case SVt_PVCV:
3804         location = (SV **) &(GvGP(dstr)->gp_cv); /* XXX bypassing GvCV_set */
3805         import_flag = GVf_IMPORTED_CV;
3806         goto common;
3807     case SVt_PVHV:
3808         location = (SV **) &GvHV(dstr);
3809         import_flag = GVf_IMPORTED_HV;
3810         goto common;
3811     case SVt_PVAV:
3812         location = (SV **) &GvAV(dstr);
3813         import_flag = GVf_IMPORTED_AV;
3814         goto common;
3815     case SVt_PVIO:
3816         location = (SV **) &GvIOp(dstr);
3817         goto common;
3818     case SVt_PVFM:
3819         location = (SV **) &GvFORM(dstr);
3820         goto common;
3821     default:
3822         location = &GvSV(dstr);
3823         import_flag = GVf_IMPORTED_SV;
3824     common:
3825         if (intro) {
3826             if (stype == SVt_PVCV) {
3827                 /*if (GvCVGEN(dstr) && (GvCV(dstr) != (const CV *)sref || GvCVGEN(dstr))) {*/
3828                 if (GvCVGEN(dstr)) {
3829                     SvREFCNT_dec(GvCV(dstr));
3830                     GvCV_set(dstr, NULL);
3831                     GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3832                 }
3833             }
3834             /* SAVEt_GVSLOT takes more room on the savestack and has more
3835                overhead in leave_scope than SAVEt_GENERIC_SV.  But for CVs
3836                leave_scope needs access to the GV so it can reset method
3837                caches.  We must use SAVEt_GVSLOT whenever the type is
3838                SVt_PVCV, even if the stash is anonymous, as the stash may
3839                gain a name somehow before leave_scope. */
3840             if (stype == SVt_PVCV) {
3841                 /* There is no save_pushptrptrptr.  Creating it for this
3842                    one call site would be overkill.  So inline the ss add
3843                    routines here. */
3844                 dSS_ADD;
3845                 SS_ADD_PTR(dstr);
3846                 SS_ADD_PTR(location);
3847                 SS_ADD_PTR(SvREFCNT_inc(*location));
3848                 SS_ADD_UV(SAVEt_GVSLOT);
3849                 SS_ADD_END(4);
3850             }
3851             else SAVEGENERICSV(*location);
3852         }
3853         dref = *location;
3854         if (stype == SVt_PVCV && (*location != sref || GvCVGEN(dstr))) {
3855             CV* const cv = MUTABLE_CV(*location);
3856             if (cv) {
3857                 if (!GvCVGEN((const GV *)dstr) &&
3858                     (CvROOT(cv) || CvXSUB(cv)) &&
3859                     /* redundant check that avoids creating the extra SV
3860                        most of the time: */
3861                     (CvCONST(cv) || ckWARN(WARN_REDEFINE)))
3862                     {
3863                         SV * const new_const_sv =
3864                             CvCONST((const CV *)sref)
3865                                  ? cv_const_sv((const CV *)sref)
3866                                  : NULL;
3867                         report_redefined_cv(
3868                            sv_2mortal(Perl_newSVpvf(aTHX_
3869                                 "%"HEKf"::%"HEKf,
3870                                 HEKfARG(
3871                                  HvNAME_HEK(GvSTASH((const GV *)dstr))
3872                                 ),
3873                                 HEKfARG(GvENAME_HEK(MUTABLE_GV(dstr)))
3874                            )),
3875                            cv,
3876                            CvCONST((const CV *)sref) ? &new_const_sv : NULL
3877                         );
3878                     }
3879                 if (!intro)
3880                     cv_ckproto_len_flags(cv, (const GV *)dstr,
3881                                    SvPOK(sref) ? CvPROTO(sref) : NULL,
3882                                    SvPOK(sref) ? CvPROTOLEN(sref) : 0,
3883                                    SvPOK(sref) ? SvUTF8(sref) : 0);
3884             }
3885             GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3886             GvASSUMECV_on(dstr);
3887             if(GvSTASH(dstr)) gv_method_changed(dstr); /* sub foo { 1 } sub bar { 2 } *bar = \&foo */
3888         }
3889         *location = SvREFCNT_inc_simple_NN(sref);
3890         if (import_flag && !(GvFLAGS(dstr) & import_flag)
3891             && CopSTASH_ne(PL_curcop, GvSTASH(dstr))) {
3892             GvFLAGS(dstr) |= import_flag;
3893         }
3894         if (stype == SVt_PVHV) {
3895             const char * const name = GvNAME((GV*)dstr);
3896             const STRLEN len = GvNAMELEN(dstr);
3897             if (
3898                 (
3899                    (len > 1 && name[len-2] == ':' && name[len-1] == ':')
3900                 || (len == 1 && name[0] == ':')
3901                 )
3902              && (!dref || HvENAME_get(dref))
3903             ) {
3904                 mro_package_moved(
3905                     (HV *)sref, (HV *)dref,
3906                     (GV *)dstr, 0
3907                 );
3908             }
3909         }
3910         else if (
3911             stype == SVt_PVAV && sref != dref
3912          && strEQ(GvNAME((GV*)dstr), "ISA")
3913          /* The stash may have been detached from the symbol table, so
3914             check its name before doing anything. */
3915          && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3916         ) {
3917             MAGIC *mg;
3918             MAGIC * const omg = dref && SvSMAGICAL(dref)
3919                                  ? mg_find(dref, PERL_MAGIC_isa)
3920                                  : NULL;
3921             if (SvSMAGICAL(sref) && (mg = mg_find(sref, PERL_MAGIC_isa))) {
3922                 if (SvTYPE(mg->mg_obj) != SVt_PVAV) {
3923                     AV * const ary = newAV();
3924                     av_push(ary, mg->mg_obj); /* takes the refcount */
3925                     mg->mg_obj = (SV *)ary;
3926                 }
3927                 if (omg) {
3928                     if (SvTYPE(omg->mg_obj) == SVt_PVAV) {
3929                         SV **svp = AvARRAY((AV *)omg->mg_obj);
3930                         I32 items = AvFILLp((AV *)omg->mg_obj) + 1;
3931                         while (items--)
3932                             av_push(
3933                              (AV *)mg->mg_obj,
3934                              SvREFCNT_inc_simple_NN(*svp++)
3935                             );
3936                     }
3937                     else
3938                         av_push(
3939                          (AV *)mg->mg_obj,
3940                          SvREFCNT_inc_simple_NN(omg->mg_obj)
3941                         );
3942                 }
3943                 else
3944                     av_push((AV *)mg->mg_obj,SvREFCNT_inc_simple_NN(dstr));
3945             }
3946             else
3947             {
3948                 sv_magic(
3949                  sref, omg ? omg->mg_obj : dstr, PERL_MAGIC_isa, NULL, 0
3950                 );
3951                 mg = mg_find(sref, PERL_MAGIC_isa);
3952             }
3953             /* Since the *ISA assignment could have affected more than
3954                one stash, don't call mro_isa_changed_in directly, but let
3955                magic_clearisa do it for us, as it already has the logic for
3956                dealing with globs vs arrays of globs. */
3957             assert(mg);
3958             Perl_magic_clearisa(aTHX_ NULL, mg);
3959         }
3960         else if (stype == SVt_PVIO) {
3961             DEBUG_o(Perl_deb(aTHX_ "glob_assign_ref clearing PL_stashcache\n"));
3962             /* It's a cache. It will rebuild itself quite happily.
3963                It's a lot of effort to work out exactly which key (or keys)
3964                might be invalidated by the creation of the this file handle.
3965             */
3966             hv_clear(PL_stashcache);
3967         }
3968         break;
3969     }
3970     if (!intro) SvREFCNT_dec(dref);
3971     if (SvTAINTED(sstr))
3972         SvTAINT(dstr);
3973     return;
3974 }
3975
3976 /* Work around compiler warnings about unsigned >= THRESHOLD when thres-
3977    hold is 0. */
3978 #if SV_COW_THRESHOLD
3979 # define GE_COW_THRESHOLD(len)          ((len) >= SV_COW_THRESHOLD)
3980 #else
3981 # define GE_COW_THRESHOLD(len)          1
3982 #endif
3983 #if SV_COWBUF_THRESHOLD
3984 # define GE_COWBUF_THRESHOLD(len)       ((len) >= SV_COWBUF_THRESHOLD)
3985 #else
3986 # define GE_COWBUF_THRESHOLD(len)       1
3987 #endif
3988
3989 void
3990 Perl_sv_setsv_flags(pTHX_ SV *dstr, SV* sstr, const I32 flags)
3991 {
3992     dVAR;
3993     U32 sflags;
3994     int dtype;
3995     svtype stype;
3996
3997     PERL_ARGS_ASSERT_SV_SETSV_FLAGS;
3998
3999     if (sstr == dstr)
4000         return;
4001
4002     if (SvIS_FREED(dstr)) {
4003         Perl_croak(aTHX_ "panic: attempt to copy value %" SVf
4004                    " to a freed scalar %p", SVfARG(sstr), (void *)dstr);
4005     }
4006     SV_CHECK_THINKFIRST_COW_DROP(dstr);
4007     if (!sstr)
4008         sstr = &PL_sv_undef;
4009     if (SvIS_FREED(sstr)) {
4010         Perl_croak(aTHX_ "panic: attempt to copy freed scalar %p to %p",
4011                    (void*)sstr, (void*)dstr);
4012     }
4013     stype = SvTYPE(sstr);
4014     dtype = SvTYPE(dstr);
4015
4016     /* There's a lot of redundancy below but we're going for speed here */
4017
4018     switch (stype) {
4019     case SVt_NULL:
4020       undef_sstr:
4021         if (dtype != SVt_PVGV && dtype != SVt_PVLV) {
4022             (void)SvOK_off(dstr);
4023             return;
4024         }
4025         break;
4026     case SVt_IV:
4027         if (SvIOK(sstr)) {
4028             switch (dtype) {
4029             case SVt_NULL:
4030                 sv_upgrade(dstr, SVt_IV);
4031                 break;
4032             case SVt_NV:
4033             case SVt_PV:
4034                 sv_upgrade(dstr, SVt_PVIV);
4035                 break;
4036             case SVt_PVGV:
4037             case SVt_PVLV:
4038                 goto end_of_first_switch;
4039             }
4040             (void)SvIOK_only(dstr);
4041             SvIV_set(dstr,  SvIVX(sstr));
4042             if (SvIsUV(sstr))
4043                 SvIsUV_on(dstr);
4044             /* SvTAINTED can only be true if the SV has taint magic, which in
4045                turn means that the SV type is PVMG (or greater). This is the
4046                case statement for SVt_IV, so this cannot be true (whatever gcov
4047                may say).  */
4048             assert(!SvTAINTED(sstr));
4049             return;
4050         }
4051         if (!SvROK(sstr))
4052             goto undef_sstr;
4053         if (dtype < SVt_PV && dtype != SVt_IV)
4054             sv_upgrade(dstr, SVt_IV);
4055         break;
4056
4057     case SVt_NV:
4058         if (SvNOK(sstr)) {
4059             switch (dtype) {
4060             case SVt_NULL:
4061             case SVt_IV:
4062                 sv_upgrade(dstr, SVt_NV);
4063                 break;
4064             case SVt_PV:
4065             case SVt_PVIV:
4066                 sv_upgrade(dstr, SVt_PVNV);
4067                 break;
4068             case SVt_PVGV:
4069             case SVt_PVLV:
4070                 goto end_of_first_switch;
4071             }
4072             SvNV_set(dstr, SvNVX(sstr));
4073             (void)SvNOK_only(dstr);
4074             /* SvTAINTED can only be true if the SV has taint magic, which in
4075                turn means that the SV type is PVMG (or greater). This is the
4076                case statement for SVt_NV, so this cannot be true (whatever gcov
4077                may say).  */
4078             assert(!SvTAINTED(sstr));
4079             return;
4080         }
4081         goto undef_sstr;
4082
4083     case SVt_PV:
4084         if (dtype < SVt_PV)
4085             sv_upgrade(dstr, SVt_PV);
4086         break;
4087     case SVt_PVIV:
4088         if (dtype < SVt_PVIV)
4089             sv_upgrade(dstr, SVt_PVIV);
4090         break;
4091     case SVt_PVNV:
4092         if (dtype < SVt_PVNV)
4093             sv_upgrade(dstr, SVt_PVNV);
4094         break;
4095     default:
4096         {
4097         const char * const type = sv_reftype(sstr,0);
4098         if (PL_op)
4099             /* diag_listed_as: Bizarre copy of %s */
4100             Perl_croak(aTHX_ "Bizarre copy of %s in %s", type, OP_DESC(PL_op));
4101         else
4102             Perl_croak(aTHX_ "Bizarre copy of %s", type);
4103         }
4104         break;
4105
4106     case SVt_REGEXP:
4107       upgregexp:
4108         if (dtype < SVt_REGEXP)
4109         {
4110             if (dtype >= SVt_PV) {
4111                 SvPV_free(dstr);
4112                 SvPV_set(dstr, 0);
4113                 SvLEN_set(dstr, 0);
4114                 SvCUR_set(dstr, 0);
4115             }
4116             sv_upgrade(dstr, SVt_REGEXP);
4117         }
4118         break;
4119
4120         /* case SVt_DUMMY: */
4121     case SVt_PVLV:
4122     case SVt_PVGV:
4123     case SVt_PVMG:
4124         if (SvGMAGICAL(sstr) && (flags & SV_GMAGIC)) {
4125             mg_get(sstr);
4126             if (SvTYPE(sstr) != stype)
4127                 stype = SvTYPE(sstr);
4128         }
4129         if (isGV_with_GP(sstr) && dtype <= SVt_PVLV) {
4130                     glob_assign_glob(dstr, sstr, dtype);
4131                     return;
4132         }
4133         if (stype == SVt_PVLV)
4134         {
4135             if (isREGEXP(sstr)) goto upgregexp;
4136             SvUPGRADE(dstr, SVt_PVNV);
4137         }
4138         else
4139             SvUPGRADE(dstr, (svtype)stype);
4140     }
4141  end_of_first_switch:
4142
4143     /* dstr may have been upgraded.  */
4144     dtype = SvTYPE(dstr);
4145     sflags = SvFLAGS(sstr);
4146
4147     if (dtype == SVt_PVCV) {
4148         /* Assigning to a subroutine sets the prototype.  */
4149         if (SvOK(sstr)) {
4150             STRLEN len;
4151             const char *const ptr = SvPV_const(sstr, len);
4152
4153             SvGROW(dstr, len + 1);
4154             Copy(ptr, SvPVX(dstr), len + 1, char);
4155             SvCUR_set(dstr, len);
4156             SvPOK_only(dstr);
4157             SvFLAGS(dstr) |= sflags & SVf_UTF8;
4158             CvAUTOLOAD_off(dstr);
4159         } else {
4160             SvOK_off(dstr);
4161         }
4162     }
4163     else if (dtype == SVt_PVAV || dtype == SVt_PVHV || dtype == SVt_PVFM) {
4164         const char * const type = sv_reftype(dstr,0);
4165         if (PL_op)
4166             /* diag_listed_as: Cannot copy to %s */
4167             Perl_croak(aTHX_ "Cannot copy to %s in %s", type, OP_DESC(PL_op));
4168         else
4169             Perl_croak(aTHX_ "Cannot copy to %s", type);
4170     } else if (sflags & SVf_ROK) {
4171         if (isGV_with_GP(dstr)
4172             && SvTYPE(SvRV(sstr)) == SVt_PVGV && isGV_with_GP(SvRV(sstr))) {
4173             sstr = SvRV(sstr);
4174             if (sstr == dstr) {
4175                 if (GvIMPORTED(dstr) != GVf_IMPORTED
4176                     && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
4177                 {
4178                     GvIMPORTED_on(dstr);
4179                 }
4180                 GvMULTI_on(dstr);
4181                 return;
4182             }
4183             glob_assign_glob(dstr, sstr, dtype);
4184             return;
4185         }
4186
4187         if (dtype >= SVt_PV) {
4188             if (isGV_with_GP(dstr)) {
4189                 glob_assign_ref(dstr, sstr);
4190                 return;
4191             }
4192             if (SvPVX_const(dstr)) {
4193                 SvPV_free(dstr);
4194                 SvLEN_set(dstr, 0);
4195                 SvCUR_set(dstr, 0);
4196             }
4197         }
4198         (void)SvOK_off(dstr);
4199         SvRV_set(dstr, SvREFCNT_inc(SvRV(sstr)));
4200         SvFLAGS(dstr) |= sflags & SVf_ROK;
4201         assert(!(sflags & SVp_NOK));
4202         assert(!(sflags & SVp_IOK));
4203         assert(!(sflags & SVf_NOK));
4204         assert(!(sflags & SVf_IOK));
4205     }
4206     else if (isGV_with_GP(dstr)) {
4207         if (!(sflags & SVf_OK)) {
4208             Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4209                            "Undefined value assigned to typeglob");
4210         }
4211         else {
4212             GV *gv = gv_fetchsv_nomg(sstr, GV_ADD, SVt_PVGV);
4213             if (dstr != (const SV *)gv) {
4214                 const char * const name = GvNAME((const GV *)dstr);
4215                 const STRLEN len = GvNAMELEN(dstr);
4216                 HV *old_stash = NULL;
4217                 bool reset_isa = FALSE;
4218                 if ((len > 1 && name[len-2] == ':' && name[len-1] == ':')
4219                  || (len == 1 && name[0] == ':')) {
4220                     /* Set aside the old stash, so we can reset isa caches
4221                        on its subclasses. */
4222                     if((old_stash = GvHV(dstr))) {
4223                         /* Make sure we do not lose it early. */
4224                         SvREFCNT_inc_simple_void_NN(
4225                          sv_2mortal((SV *)old_stash)
4226                         );
4227                     }
4228                     reset_isa = TRUE;
4229                 }
4230
4231                 if (GvGP(dstr))
4232                     gp_free(MUTABLE_GV(dstr));
4233                 GvGP_set(dstr, gp_ref(GvGP(gv)));
4234
4235                 if (reset_isa) {
4236                     HV * const stash = GvHV(dstr);
4237                     if(
4238                         old_stash ? (HV *)HvENAME_get(old_stash) : stash
4239                     )
4240                         mro_package_moved(
4241                          stash, old_stash,
4242                          (GV *)dstr, 0
4243                         );
4244                 }
4245             }
4246         }
4247     }
4248     else if ((dtype == SVt_REGEXP || dtype == SVt_PVLV)
4249           && (stype == SVt_REGEXP || isREGEXP(sstr))) {
4250         reg_temp_copy((REGEXP*)dstr, (REGEXP*)sstr);
4251     }
4252     else if (sflags & SVp_POK) {
4253         bool isSwipe = 0;
4254         const STRLEN cur = SvCUR(sstr);
4255         const STRLEN len = SvLEN(sstr);
4256
4257         /*
4258          * Check to see if we can just swipe the string.  If so, it's a
4259          * possible small lose on short strings, but a big win on long ones.
4260          * It might even be a win on short strings if SvPVX_const(dstr)
4261          * has to be allocated and SvPVX_const(sstr) has to be freed.
4262          * Likewise if we can set up COW rather than doing an actual copy, we
4263          * drop to the else clause, as the swipe code and the COW setup code
4264          * have much in common.
4265          */
4266
4267         /* Whichever path we take through the next code, we want this true,
4268            and doing it now facilitates the COW check.  */
4269         (void)SvPOK_only(dstr);
4270
4271         if (
4272             /* If we're already COW then this clause is not true, and if COW
4273                is allowed then we drop down to the else and make dest COW 
4274                with us.  If caller hasn't said that we're allowed to COW
4275                shared hash keys then we don't do the COW setup, even if the
4276                source scalar is a shared hash key scalar.  */
4277             (((flags & SV_COW_SHARED_HASH_KEYS)
4278                ? !(sflags & SVf_IsCOW)
4279 #ifdef PERL_NEW_COPY_ON_WRITE
4280                 || (len &&
4281                     ((!GE_COWBUF_THRESHOLD(cur) && SvLEN(dstr) > cur)
4282                    /* If this is a regular (non-hek) COW, only so many COW
4283                       "copies" are possible. */
4284                     || CowREFCNT(sstr) == SV_COW_REFCNT_MAX))
4285 #endif
4286                : 1 /* If making a COW copy is forbidden then the behaviour we
4287                        desire is as if the source SV isn't actually already
4288                        COW, even if it is.  So we act as if the source flags
4289                        are not COW, rather than actually testing them.  */
4290               )
4291 #ifndef PERL_ANY_COW
4292              /* The change that added SV_COW_SHARED_HASH_KEYS makes the logic
4293                 when PERL_OLD_COPY_ON_WRITE is defined a little wrong.
4294                 Conceptually PERL_OLD_COPY_ON_WRITE being defined should
4295                 override SV_COW_SHARED_HASH_KEYS, because it means "always COW"
4296                 but in turn, it's somewhat dead code, never expected to go
4297                 live, but more kept as a placeholder on how to do it better
4298                 in a newer implementation.  */
4299              /* If we are COW and dstr is a suitable target then we drop down
4300                 into the else and make dest a COW of us.  */
4301              || (SvFLAGS(dstr) & SVf_BREAK)
4302 #endif
4303              )
4304             &&
4305             !(isSwipe =
4306 #ifdef PERL_NEW_COPY_ON_WRITE
4307                                 /* slated for free anyway (and not COW)? */
4308                  (sflags & (SVs_TEMP|SVf_IsCOW)) == SVs_TEMP &&
4309 #else
4310                  (sflags & SVs_TEMP) &&   /* slated for free anyway? */
4311 #endif
4312                  !(sflags & SVf_OOK) &&   /* and not involved in OOK hack? */
4313                  (!(flags & SV_NOSTEAL)) &&
4314                                         /* and we're allowed to steal temps */
4315                  SvREFCNT(sstr) == 1 &&   /* and no other references to it? */
4316                  len)             /* and really is a string */
4317 #ifdef PERL_ANY_COW
4318             && ((flags & SV_COW_SHARED_HASH_KEYS)
4319                 ? (!((sflags & CAN_COW_MASK) == CAN_COW_FLAGS
4320 # ifdef PERL_OLD_COPY_ON_WRITE
4321                      && (SvFLAGS(dstr) & CAN_COW_MASK) == CAN_COW_FLAGS
4322                      && SvTYPE(sstr) >= SVt_PVIV
4323 # else
4324                      && !(SvFLAGS(dstr) & SVf_BREAK)
4325                      && !(sflags & SVf_IsCOW)
4326                      && GE_COW_THRESHOLD(cur) && cur+1 < len
4327                      && (GE_COWBUF_THRESHOLD(cur) || SvLEN(dstr) < cur+1)
4328 # endif
4329                     ))
4330                 : 1)
4331 #endif
4332             ) {
4333             /* Failed the swipe test, and it's not a shared hash key either.
4334                Have to copy the string.  */
4335             SvGROW(dstr, cur + 1);      /* inlined from sv_setpvn */
4336             Move(SvPVX_const(sstr),SvPVX(dstr),cur,char);
4337             SvCUR_set(dstr, cur);
4338             *SvEND(dstr) = '\0';
4339         } else {
4340             /* If PERL_OLD_COPY_ON_WRITE is not defined, then isSwipe will always
4341                be true in here.  */
4342             /* Either it's a shared hash key, or it's suitable for
4343                copy-on-write or we can swipe the string.  */
4344             if (DEBUG_C_TEST) {
4345                 PerlIO_printf(Perl_debug_log, "Copy on write: sstr --> dstr\n");
4346                 sv_dump(sstr);
4347                 sv_dump(dstr);
4348             }
4349 #ifdef PERL_ANY_COW
4350             if (!isSwipe) {
4351                 if (!(sflags & SVf_IsCOW)) {
4352                     SvIsCOW_on(sstr);
4353 # ifdef PERL_OLD_COPY_ON_WRITE
4354                     /* Make the source SV into a loop of 1.
4355                        (about to become 2) */
4356                     SV_COW_NEXT_SV_SET(sstr, sstr);
4357 # else
4358                     CowREFCNT(sstr) = 0;
4359 # endif
4360                 }
4361             }
4362 #endif
4363             /* Initial code is common.  */
4364             if (SvPVX_const(dstr)) {    /* we know that dtype >= SVt_PV */
4365                 SvPV_free(dstr);
4366             }
4367
4368             if (!isSwipe) {
4369                 /* making another shared SV.  */
4370 #ifdef PERL_ANY_COW
4371                 if (len) {
4372 # ifdef PERL_OLD_COPY_ON_WRITE
4373                     assert (SvTYPE(dstr) >= SVt_PVIV);
4374                     /* SvIsCOW_normal */
4375                     /* splice us in between source and next-after-source.  */
4376                     SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4377                     SV_COW_NEXT_SV_SET(sstr, dstr);
4378 # else
4379                     CowREFCNT(sstr)++;
4380 # endif
4381                     SvPV_set(dstr, SvPVX_mutable(sstr));
4382                 } else
4383 #endif
4384                 {
4385                     /* SvIsCOW_shared_hash */
4386                     DEBUG_C(PerlIO_printf(Perl_debug_log,
4387                                           "Copy on write: Sharing hash\n"));
4388
4389                     assert (SvTYPE(dstr) >= SVt_PV);
4390                     SvPV_set(dstr,
4391                              HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)))));
4392                 }
4393                 SvLEN_set(dstr, len);
4394                 SvCUR_set(dstr, cur);
4395                 SvIsCOW_on(dstr);
4396             }
4397             else
4398                 {       /* Passes the swipe test.  */
4399                 SvPV_set(dstr, SvPVX_mutable(sstr));
4400                 SvLEN_set(dstr, SvLEN(sstr));
4401                 SvCUR_set(dstr, SvCUR(sstr));
4402
4403                 SvTEMP_off(dstr);
4404                 (void)SvOK_off(sstr);   /* NOTE: nukes most SvFLAGS on sstr */
4405                 SvPV_set(sstr, NULL);
4406                 SvLEN_set(sstr, 0);
4407                 SvCUR_set(sstr, 0);
4408                 SvTEMP_off(sstr);
4409             }
4410         }
4411         if (sflags & SVp_NOK) {
4412             SvNV_set(dstr, SvNVX(sstr));
4413         }
4414         if (sflags & SVp_IOK) {
4415             SvIV_set(dstr, SvIVX(sstr));
4416             /* Must do this otherwise some other overloaded use of 0x80000000
4417                gets confused. I guess SVpbm_VALID */
4418             if (sflags & SVf_IVisUV)
4419                 SvIsUV_on(dstr);
4420         }
4421         SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_NOK|SVp_NOK|SVf_UTF8);
4422         {
4423             const MAGIC * const smg = SvVSTRING_mg(sstr);
4424             if (smg) {
4425                 sv_magic(dstr, NULL, PERL_MAGIC_vstring,
4426                          smg->mg_ptr, smg->mg_len);
4427                 SvRMAGICAL_on(dstr);
4428             }
4429         }
4430     }
4431     else if (sflags & (SVp_IOK|SVp_NOK)) {
4432         (void)SvOK_off(dstr);
4433         SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_IVisUV|SVf_NOK|SVp_NOK);
4434         if (sflags & SVp_IOK) {
4435             /* XXXX Do we want to set IsUV for IV(ROK)?  Be extra safe... */
4436             SvIV_set(dstr, SvIVX(sstr));
4437         }
4438         if (sflags & SVp_NOK) {
4439             SvNV_set(dstr, SvNVX(sstr));
4440         }
4441     }
4442     else {
4443         if (isGV_with_GP(sstr)) {
4444             gv_efullname3(dstr, MUTABLE_GV(sstr), "*");
4445         }
4446         else
4447             (void)SvOK_off(dstr);
4448     }
4449     if (SvTAINTED(sstr))
4450         SvTAINT(dstr);
4451 }
4452
4453 /*
4454 =for apidoc sv_setsv_mg
4455
4456 Like C<sv_setsv>, but also handles 'set' magic.
4457
4458 =cut
4459 */
4460
4461 void
4462 Perl_sv_setsv_mg(pTHX_ SV *const dstr, SV *const sstr)
4463 {
4464     PERL_ARGS_ASSERT_SV_SETSV_MG;
4465
4466     sv_setsv(dstr,sstr);
4467     SvSETMAGIC(dstr);
4468 }
4469
4470 #ifdef PERL_ANY_COW
4471 # ifdef PERL_OLD_COPY_ON_WRITE
4472 #  define SVt_COW SVt_PVIV
4473 # else
4474 #  define SVt_COW SVt_PV
4475 # endif
4476 SV *
4477 Perl_sv_setsv_cow(pTHX_ SV *dstr, SV *sstr)
4478 {
4479     STRLEN cur = SvCUR(sstr);
4480     STRLEN len = SvLEN(sstr);
4481     char *new_pv;
4482
4483     PERL_ARGS_ASSERT_SV_SETSV_COW;
4484
4485     if (DEBUG_C_TEST) {
4486         PerlIO_printf(Perl_debug_log, "Fast copy on write: %p -> %p\n",
4487                       (void*)sstr, (void*)dstr);
4488         sv_dump(sstr);
4489         if (dstr)
4490                     sv_dump(dstr);
4491     }
4492
4493     if (dstr) {
4494         if (SvTHINKFIRST(dstr))
4495             sv_force_normal_flags(dstr, SV_COW_DROP_PV);
4496         else if (SvPVX_const(dstr))
4497             Safefree(SvPVX_mutable(dstr));
4498     }
4499     else
4500         new_SV(dstr);
4501     SvUPGRADE(dstr, SVt_COW);
4502
4503     assert (SvPOK(sstr));
4504     assert (SvPOKp(sstr));
4505 # ifdef PERL_OLD_COPY_ON_WRITE
4506     assert (!SvIOK(sstr));
4507     assert (!SvIOKp(sstr));
4508     assert (!SvNOK(sstr));
4509     assert (!SvNOKp(sstr));
4510 # endif
4511
4512     if (SvIsCOW(sstr)) {
4513
4514         if (SvLEN(sstr) == 0) {
4515             /* source is a COW shared hash key.  */
4516             DEBUG_C(PerlIO_printf(Perl_debug_log,
4517                                   "Fast copy on write: Sharing hash\n"));
4518             new_pv = HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr))));
4519             goto common_exit;
4520         }
4521 # ifdef PERL_OLD_COPY_ON_WRITE
4522         SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4523 # else
4524         assert(SvCUR(sstr)+1 < SvLEN(sstr));
4525         assert(CowREFCNT(sstr) < SV_COW_REFCNT_MAX);
4526 # endif
4527     } else {
4528         assert ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS);
4529         SvUPGRADE(sstr, SVt_COW);
4530         SvIsCOW_on(sstr);
4531         DEBUG_C(PerlIO_printf(Perl_debug_log,
4532                               "Fast copy on write: Converting sstr to COW\n"));
4533 # ifdef PERL_OLD_COPY_ON_WRITE
4534         SV_COW_NEXT_SV_SET(dstr, sstr);
4535 # else
4536         CowREFCNT(sstr) = 0;    
4537 # endif
4538     }
4539 # ifdef PERL_OLD_COPY_ON_WRITE
4540     SV_COW_NEXT_SV_SET(sstr, dstr);
4541 # else
4542     CowREFCNT(sstr)++;  
4543 # endif
4544     new_pv = SvPVX_mutable(sstr);
4545
4546   common_exit:
4547     SvPV_set(dstr, new_pv);
4548     SvFLAGS(dstr) = (SVt_COW|SVf_POK|SVp_POK|SVf_IsCOW);
4549     if (SvUTF8(sstr))
4550         SvUTF8_on(dstr);
4551     SvLEN_set(dstr, len);
4552     SvCUR_set(dstr, cur);
4553     if (DEBUG_C_TEST) {
4554         sv_dump(dstr);
4555     }
4556     return dstr;
4557 }
4558 #endif
4559
4560 /*
4561 =for apidoc sv_setpvn
4562
4563 Copies a string into an SV.  The C<len> parameter indicates the number of
4564 bytes to be copied.  If the C<ptr> argument is NULL the SV will become
4565 undefined.  Does not handle 'set' magic.  See C<sv_setpvn_mg>.
4566
4567 =cut
4568 */
4569
4570 void
4571 Perl_sv_setpvn(pTHX_ SV *const sv, const char *const ptr, const STRLEN len)
4572 {
4573     dVAR;
4574     char *dptr;
4575
4576     PERL_ARGS_ASSERT_SV_SETPVN;
4577
4578     SV_CHECK_THINKFIRST_COW_DROP(sv);
4579     if (!ptr) {
4580         (void)SvOK_off(sv);
4581         return;
4582     }
4583     else {
4584         /* len is STRLEN which is unsigned, need to copy to signed */
4585         const IV iv = len;
4586         if (iv < 0)
4587             Perl_croak(aTHX_ "panic: sv_setpvn called with negative strlen %"
4588                        IVdf, iv);
4589     }
4590     SvUPGRADE(sv, SVt_PV);
4591
4592     dptr = SvGROW(sv, len + 1);
4593     Move(ptr,dptr,len,char);
4594     dptr[len] = '\0';
4595     SvCUR_set(sv, len);
4596     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4597     SvTAINT(sv);
4598     if (SvTYPE(sv) == SVt_PVCV) CvAUTOLOAD_off(sv);
4599 }
4600
4601 /*
4602 =for apidoc sv_setpvn_mg
4603
4604 Like C<sv_setpvn>, but also handles 'set' magic.
4605
4606 =cut
4607 */
4608
4609 void
4610 Perl_sv_setpvn_mg(pTHX_ SV *const sv, const char *const ptr, const STRLEN len)
4611 {
4612     PERL_ARGS_ASSERT_SV_SETPVN_MG;
4613
4614     sv_setpvn(sv,ptr,len);
4615     SvSETMAGIC(sv);
4616 }
4617
4618 /*
4619 =for apidoc sv_setpv
4620
4621 Copies a string into an SV.  The string must be null-terminated.  Does not
4622 handle 'set' magic.  See C<sv_setpv_mg>.
4623
4624 =cut
4625 */
4626
4627 void
4628 Perl_sv_setpv(pTHX_ SV *const sv, const char *const ptr)
4629 {
4630     dVAR;
4631     STRLEN len;
4632
4633     PERL_ARGS_ASSERT_SV_SETPV;
4634
4635     SV_CHECK_THINKFIRST_COW_DROP(sv);
4636     if (!ptr) {
4637         (void)SvOK_off(sv);
4638         return;
4639     }
4640     len = strlen(ptr);
4641     SvUPGRADE(sv, SVt_PV);
4642
4643     SvGROW(sv, len + 1);
4644     Move(ptr,SvPVX(sv),len+1,char);
4645     SvCUR_set(sv, len);
4646     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4647     SvTAINT(sv);
4648     if (SvTYPE(sv) == SVt_PVCV) CvAUTOLOAD_off(sv);
4649 }
4650
4651 /*
4652 =for apidoc sv_setpv_mg
4653
4654 Like C<sv_setpv>, but also handles 'set' magic.
4655
4656 =cut
4657 */
4658
4659 void
4660 Perl_sv_setpv_mg(pTHX_ SV *const sv, const char *const ptr)
4661 {
4662     PERL_ARGS_ASSERT_SV_SETPV_MG;
4663
4664     sv_setpv(sv,ptr);
4665     SvSETMAGIC(sv);
4666 }
4667
4668 void
4669 Perl_sv_sethek(pTHX_ SV *const sv, const HEK *const hek)
4670 {
4671     dVAR;
4672
4673     PERL_ARGS_ASSERT_SV_SETHEK;
4674
4675     if (!hek) {
4676         return;
4677     }
4678
4679     if (HEK_LEN(hek) == HEf_SVKEY) {
4680         sv_setsv(sv, *(SV**)HEK_KEY(hek));
4681         return;
4682     } else {
4683         const int flags = HEK_FLAGS(hek);
4684         if (flags & HVhek_WASUTF8) {
4685             STRLEN utf8_len = HEK_LEN(hek);
4686             char *as_utf8 = (char *)bytes_to_utf8((U8*)HEK_KEY(hek), &utf8_len);
4687             sv_usepvn_flags(sv, as_utf8, utf8_len, SV_HAS_TRAILING_NUL);
4688             SvUTF8_on(sv);
4689             return;
4690         } else if (flags & HVhek_UNSHARED) {
4691             sv_setpvn(sv, HEK_KEY(hek), HEK_LEN(hek));
4692             if (HEK_UTF8(hek))
4693                 SvUTF8_on(sv);
4694             else SvUTF8_off(sv);
4695             return;
4696         }
4697         {
4698             SV_CHECK_THINKFIRST_COW_DROP(sv);
4699             SvUPGRADE(sv, SVt_PV);
4700             Safefree(SvPVX(sv));
4701             SvPV_set(sv,(char *)HEK_KEY(share_hek_hek(hek)));
4702             SvCUR_set(sv, HEK_LEN(hek));
4703             SvLEN_set(sv, 0);
4704             SvIsCOW_on(sv);
4705             SvPOK_on(sv);
4706             if (HEK_UTF8(hek))
4707                 SvUTF8_on(sv);
4708             else SvUTF8_off(sv);
4709             return;
4710         }
4711     }
4712 }
4713
4714
4715 /*
4716 =for apidoc sv_usepvn_flags
4717
4718 Tells an SV to use C<ptr> to find its string value.  Normally the
4719 string is stored inside the SV but sv_usepvn allows the SV to use an
4720 outside string.  The C<ptr> should point to memory that was allocated
4721 by C<malloc>.  It must be the start of a mallocked block
4722 of memory, and not a pointer to the middle of it.  The
4723 string length, C<len>, must be supplied.  By default
4724 this function will realloc (i.e. move) the memory pointed to by C<ptr>,
4725 so that pointer should not be freed or used by the programmer after
4726 giving it to sv_usepvn, and neither should any pointers from "behind"
4727 that pointer (e.g. ptr + 1) be used.
4728
4729 If C<flags> & SV_SMAGIC is true, will call SvSETMAGIC.  If C<flags> &
4730 SV_HAS_TRAILING_NUL is true, then C<ptr[len]> must be NUL, and the realloc
4731 will be skipped (i.e. the buffer is actually at least 1 byte longer than
4732 C<len>, and already meets the requirements for storing in C<SvPVX>).
4733
4734 =cut
4735 */
4736
4737 void
4738 Perl_sv_usepvn_flags(pTHX_ SV *const sv, char *ptr, const STRLEN len, const U32 flags)
4739 {
4740     dVAR;
4741     STRLEN allocate;
4742
4743     PERL_ARGS_ASSERT_SV_USEPVN_FLAGS;
4744
4745     SV_CHECK_THINKFIRST_COW_DROP(sv);
4746     SvUPGRADE(sv, SVt_PV);
4747     if (!ptr) {
4748         (void)SvOK_off(sv);
4749         if (flags & SV_SMAGIC)
4750             SvSETMAGIC(sv);
4751         return;
4752     }
4753     if (SvPVX_const(sv))
4754         SvPV_free(sv);
4755
4756 #ifdef DEBUGGING
4757     if (flags & SV_HAS_TRAILING_NUL)
4758         assert(ptr[len] == '\0');
4759 #endif
4760
4761     allocate = (flags & SV_HAS_TRAILING_NUL)
4762         ? len + 1 :
4763 #ifdef Perl_safesysmalloc_size
4764         len + 1;
4765 #else 
4766         PERL_STRLEN_ROUNDUP(len + 1);
4767 #endif
4768     if (flags & SV_HAS_TRAILING_NUL) {
4769         /* It's long enough - do nothing.
4770            Specifically Perl_newCONSTSUB is relying on this.  */
4771     } else {
4772 #ifdef DEBUGGING
4773         /* Force a move to shake out bugs in callers.  */
4774         char *new_ptr = (char*)safemalloc(allocate);
4775         Copy(ptr, new_ptr, len, char);
4776         PoisonFree(ptr,len,char);
4777         Safefree(ptr);
4778         ptr = new_ptr;
4779 #else
4780         ptr = (char*) saferealloc (ptr, allocate);
4781 #endif
4782     }
4783 #ifdef Perl_safesysmalloc_size
4784     SvLEN_set(sv, Perl_safesysmalloc_size(ptr));
4785 #else
4786     SvLEN_set(sv, allocate);
4787 #endif
4788     SvCUR_set(sv, len);
4789     SvPV_set(sv, ptr);
4790     if (!(flags & SV_HAS_TRAILING_NUL)) {
4791         ptr[len] = '\0';
4792     }
4793     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4794     SvTAINT(sv);
4795     if (flags & SV_SMAGIC)
4796         SvSETMAGIC(sv);
4797 }
4798
4799 #ifdef PERL_OLD_COPY_ON_WRITE
4800 /* Need to do this *after* making the SV normal, as we need the buffer
4801    pointer to remain valid until after we've copied it.  If we let go too early,
4802    another thread could invalidate it by unsharing last of the same hash key
4803    (which it can do by means other than releasing copy-on-write Svs)
4804    or by changing the other copy-on-write SVs in the loop.  */
4805 STATIC void
4806 S_sv_release_COW(pTHX_ SV *sv, const char *pvx, SV *after)
4807 {
4808     PERL_ARGS_ASSERT_SV_RELEASE_COW;
4809
4810     { /* this SV was SvIsCOW_normal(sv) */
4811          /* we need to find the SV pointing to us.  */
4812         SV *current = SV_COW_NEXT_SV(after);
4813
4814         if (current == sv) {
4815             /* The SV we point to points back to us (there were only two of us
4816                in the loop.)
4817                Hence other SV is no longer copy on write either.  */
4818             SvIsCOW_off(after);
4819         } else {
4820             /* We need to follow the pointers around the loop.  */
4821             SV *next;
4822             while ((next = SV_COW_NEXT_SV(current)) != sv) {
4823                 assert (next);
4824                 current = next;
4825                  /* don't loop forever if the structure is bust, and we have
4826                     a pointer into a closed loop.  */
4827                 assert (current != after);
4828                 assert (SvPVX_const(current) == pvx);
4829             }
4830             /* Make the SV before us point to the SV after us.  */
4831             SV_COW_NEXT_SV_SET(current, after);
4832         }
4833     }
4834 }
4835 #endif
4836 /*
4837 =for apidoc sv_force_normal_flags
4838
4839 Undo various types of fakery on an SV, where fakery means
4840 "more than" a string: if the PV is a shared string, make
4841 a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
4842 an xpvmg; if we're a copy-on-write scalar, this is the on-write time when
4843 we do the copy, and is also used locally; if this is a
4844 vstring, drop the vstring magic.  If C<SV_COW_DROP_PV> is set
4845 then a copy-on-write scalar drops its PV buffer (if any) and becomes
4846 SvPOK_off rather than making a copy.  (Used where this
4847 scalar is about to be set to some other value.)  In addition,
4848 the C<flags> parameter gets passed to C<sv_unref_flags()>
4849 when unreffing.  C<sv_force_normal> calls this function
4850 with flags set to 0.
4851
4852 =cut
4853 */
4854
4855 void
4856 Perl_sv_force_normal_flags(pTHX_ SV *const sv, const U32 flags)
4857 {
4858     dVAR;
4859
4860     PERL_ARGS_ASSERT_SV_FORCE_NORMAL_FLAGS;
4861
4862 #ifdef PERL_ANY_COW
4863     if (SvREADONLY(sv)) {
4864         if (IN_PERL_RUNTIME)
4865             Perl_croak_no_modify();
4866     }
4867     else if (SvIsCOW(sv)) {
4868         const char * const pvx = SvPVX_const(sv);
4869         const STRLEN len = SvLEN(sv);
4870         const STRLEN cur = SvCUR(sv);
4871 # ifdef PERL_OLD_COPY_ON_WRITE
4872         /* next COW sv in the loop.  If len is 0 then this is a shared-hash
4873            key scalar, so we mustn't attempt to call SV_COW_NEXT_SV(), as
4874            we'll fail an assertion.  */
4875         SV * const next = len ? SV_COW_NEXT_SV(sv) : 0;
4876 # endif
4877
4878         if (DEBUG_C_TEST) {
4879                 PerlIO_printf(Perl_debug_log,
4880                               "Copy on write: Force normal %ld\n",
4881                               (long) flags);
4882                 sv_dump(sv);
4883         }
4884         SvIsCOW_off(sv);
4885 # ifdef PERL_NEW_COPY_ON_WRITE
4886         if (len && CowREFCNT(sv) == 0)
4887             /* We own the buffer ourselves. */
4888             NOOP;
4889         else
4890 # endif
4891         {
4892                 
4893             /* This SV doesn't own the buffer, so need to Newx() a new one:  */
4894 # ifdef PERL_NEW_COPY_ON_WRITE
4895             /* Must do this first, since the macro uses SvPVX. */
4896             if (len) CowREFCNT(sv)--;
4897 # endif
4898             SvPV_set(sv, NULL);
4899             SvLEN_set(sv, 0);
4900             if (flags & SV_COW_DROP_PV) {
4901                 /* OK, so we don't need to copy our buffer.  */
4902                 SvPOK_off(sv);
4903             } else {
4904                 SvGROW(sv, cur + 1);
4905                 Move(pvx,SvPVX(sv),cur,char);
4906                 SvCUR_set(sv, cur);
4907                 *SvEND(sv) = '\0';
4908             }
4909             if (len) {
4910 # ifdef PERL_OLD_COPY_ON_WRITE
4911                 sv_release_COW(sv, pvx, next);
4912 # endif
4913             } else {
4914                 unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4915             }
4916             if (DEBUG_C_TEST) {
4917                 sv_dump(sv);
4918             }
4919         }
4920     }
4921 #else
4922     if (SvREADONLY(sv)) {
4923         if (IN_PERL_RUNTIME)
4924             Perl_croak_no_modify();
4925     }
4926     else
4927         if (SvIsCOW(sv)) {
4928             const char * const pvx = SvPVX_const(sv);
4929             const STRLEN len = SvCUR(sv);
4930             SvIsCOW_off(sv);
4931             SvPV_set(sv, NULL);
4932             SvLEN_set(sv, 0);
4933             if (flags & SV_COW_DROP_PV) {
4934                 /* OK, so we don't need to copy our buffer.  */
4935                 SvPOK_off(sv);
4936             } else {
4937                 SvGROW(sv, len + 1);
4938                 Move(pvx,SvPVX(sv),len,char);
4939                 *SvEND(sv) = '\0';
4940             }
4941             unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4942         }
4943 #endif
4944     if (SvROK(sv))
4945         sv_unref_flags(sv, flags);
4946     else if (SvFAKE(sv) && isGV_with_GP(sv))
4947         sv_unglob(sv, flags);
4948     else if (SvFAKE(sv) && isREGEXP(sv)) {
4949         /* Need to downgrade the REGEXP to a simple(r) scalar. This is analogous
4950            to sv_unglob. We only need it here, so inline it.  */
4951         const bool islv = SvTYPE(sv) == SVt_PVLV;
4952         const svtype new_type =
4953           islv ? SVt_NULL : SvMAGIC(sv) || SvSTASH(sv) ? SVt_PVMG : SVt_PV;
4954         SV *const temp = newSV_type(new_type);
4955         regexp *const temp_p = ReANY((REGEXP *)sv);
4956
4957         if (new_type == SVt_PVMG) {
4958             SvMAGIC_set(temp, SvMAGIC(sv));
4959             SvMAGIC_set(sv, NULL);
4960             SvSTASH_set(temp, SvSTASH(sv));
4961             SvSTASH_set(sv, NULL);
4962         }
4963         if (!islv) SvCUR_set(temp, SvCUR(sv));
4964         /* Remember that SvPVX is in the head, not the body.  But
4965            RX_WRAPPED is in the body. */
4966         assert(ReANY((REGEXP *)sv)->mother_re);
4967         /* Their buffer is already owned by someone else. */
4968         if (flags & SV_COW_DROP_PV) {
4969             /* SvLEN is already 0.  For SVt_REGEXP, we have a brand new
4970                zeroed body.  For SVt_PVLV, it should have been set to 0
4971                before turning into a regexp. */
4972             assert(!SvLEN(islv ? sv : temp));
4973             sv->sv_u.svu_pv = 0;
4974         }
4975         else {
4976             sv->sv_u.svu_pv = savepvn(RX_WRAPPED((REGEXP *)sv), SvCUR(sv));
4977             SvLEN_set(islv ? sv : temp, SvCUR(sv)+1);
4978             SvPOK_on(sv);
4979         }
4980
4981         /* Now swap the rest of the bodies. */
4982
4983         SvFAKE_off(sv);
4984         if (!islv) {
4985             SvFLAGS(sv) &= ~SVTYPEMASK;
4986             SvFLAGS(sv) |= new_type;
4987             SvANY(sv) = SvANY(temp);
4988         }
4989
4990         SvFLAGS(temp) &= ~(SVTYPEMASK);
4991         SvFLAGS(temp) |= SVt_REGEXP|SVf_FAKE;
4992         SvANY(temp) = temp_p;
4993         temp->sv_u.svu_rx = (regexp *)temp_p;
4994
4995         SvREFCNT_dec_NN(temp);
4996     }
4997     else if (SvVOK(sv)) sv_unmagic(sv, PERL_MAGIC_vstring);
4998 }
4999
5000 /*
5001 =for apidoc sv_chop
5002
5003 Efficient removal of characters from the beginning of the string buffer.
5004 SvPOK(sv), or at least SvPOKp(sv), must be true and the C<ptr> must be a
5005 pointer to somewhere inside the string buffer.  The C<ptr> becomes the first
5006 character of the adjusted string.  Uses the "OOK hack".  On return, only
5007 SvPOK(sv) and SvPOKp(sv) among the OK flags will be true.
5008
5009 Beware: after this function returns, C<ptr> and SvPVX_const(sv) may no longer
5010 refer to the same chunk of data.
5011
5012 The unfortunate similarity of this function's name to that of Perl's C<chop>
5013 operator is strictly coincidental.  This function works from the left;
5014 C<chop> works from the right.
5015
5016 =cut
5017 */
5018
5019 void
5020 Perl_sv_chop(pTHX_ SV *const sv, const char *const ptr)
5021 {
5022     STRLEN delta;
5023     STRLEN old_delta;
5024     U8 *p;
5025 #ifdef DEBUGGING
5026     const U8 *evacp;
5027     STRLEN evacn;
5028 #endif
5029     STRLEN max_delta;
5030
5031     PERL_ARGS_ASSERT_SV_CHOP;
5032
5033     if (!ptr || !SvPOKp(sv))
5034         return;
5035     delta = ptr - SvPVX_const(sv);
5036     if (!delta) {
5037         /* Nothing to do.  */
5038         return;
5039     }
5040     max_delta = SvLEN(sv) ? SvLEN(sv) : SvCUR(sv);
5041     if (delta > max_delta)
5042         Perl_croak(aTHX_ "panic: sv_chop ptr=%p, start=%p, end=%p",
5043                    ptr, SvPVX_const(sv), SvPVX_const(sv) + max_delta);
5044     /* SvPVX(sv) may move in SV_CHECK_THINKFIRST(sv), so don't use ptr any more */
5045     SV_CHECK_THINKFIRST(sv);
5046     SvPOK_only_UTF8(sv);
5047
5048     if (!SvOOK(sv)) {
5049         if (!SvLEN(sv)) { /* make copy of shared string */
5050             const char *pvx = SvPVX_const(sv);
5051             const STRLEN len = SvCUR(sv);
5052             SvGROW(sv, len + 1);
5053             Move(pvx,SvPVX(sv),len,char);
5054             *SvEND(sv) = '\0';
5055         }
5056         SvOOK_on(sv);
5057         old_delta = 0;
5058     } else {
5059         SvOOK_offset(sv, old_delta);
5060     }
5061     SvLEN_set(sv, SvLEN(sv) - delta);
5062     SvCUR_set(sv, SvCUR(sv) - delta);
5063     SvPV_set(sv, SvPVX(sv) + delta);
5064
5065     p = (U8 *)SvPVX_const(sv);
5066
5067 #ifdef DEBUGGING
5068     /* how many bytes were evacuated?  we will fill them with sentinel
5069        bytes, except for the part holding the new offset of course. */
5070     evacn = delta;
5071     if (old_delta)
5072         evacn += (old_delta < 0x100 ? 1 : 1 + sizeof(STRLEN));
5073     assert(evacn);
5074     assert(evacn <= delta + old_delta);
5075     evacp = p - evacn;
5076 #endif
5077
5078     delta += old_delta;
5079     assert(delta);
5080     if (delta < 0x100) {
5081         *--p = (U8) delta;
5082     } else {
5083         *--p = 0;
5084         p -= sizeof(STRLEN);
5085         Copy((U8*)&delta, p, sizeof(STRLEN), U8);
5086     }
5087
5088 #ifdef DEBUGGING
5089     /* Fill the preceding buffer with sentinals to verify that no-one is
5090        using it.  */
5091     while (p > evacp) {
5092         --p;
5093         *p = (U8)PTR2UV(p);
5094     }
5095 #endif
5096 }
5097
5098 /*
5099 =for apidoc sv_catpvn
5100
5101 Concatenates the string onto the end of the string which is in the SV.  The
5102 C<len> indicates number of bytes to copy.  If the SV has the UTF-8
5103 status set, then the bytes appended should be valid UTF-8.
5104 Handles 'get' magic, but not 'set' magic.  See C<sv_catpvn_mg>.
5105
5106 =for apidoc sv_catpvn_flags
5107
5108 Concatenates the string onto the end of the string which is in the SV.  The
5109 C<len> indicates number of bytes to copy.  If the SV has the UTF-8
5110 status set, then the bytes appended should be valid UTF-8.
5111 If C<flags> has the C<SV_SMAGIC> bit set, will
5112 C<mg_set> on C<dsv> afterwards if appropriate.
5113 C<sv_catpvn> and C<sv_catpvn_nomg> are implemented
5114 in terms of this function.
5115
5116 =cut
5117 */
5118
5119 void
5120 Perl_sv_catpvn_flags(pTHX_ SV *const dsv, const char *sstr, const STRLEN slen, const I32 flags)
5121 {
5122     dVAR;
5123     STRLEN dlen;
5124     const char * const dstr = SvPV_force_flags(dsv, dlen, flags);
5125
5126     PERL_ARGS_ASSERT_SV_CATPVN_FLAGS;
5127     assert((flags & (SV_CATBYTES|SV_CATUTF8)) != (SV_CATBYTES|SV_CATUTF8));
5128
5129     if (!(flags & SV_CATBYTES) || !SvUTF8(dsv)) {
5130       if (flags & SV_CATUTF8 && !SvUTF8(dsv)) {
5131          sv_utf8_upgrade_flags_grow(dsv, 0, slen + 1);
5132          dlen = SvCUR(dsv);
5133       }
5134       else SvGROW(dsv, dlen + slen + 1);
5135       if (sstr == dstr)
5136         sstr = SvPVX_const(dsv);
5137       Move(sstr, SvPVX(dsv) + dlen, slen, char);
5138       SvCUR_set(dsv, SvCUR(dsv) + slen);
5139     }
5140     else {
5141         /* We inline bytes_to_utf8, to avoid an extra malloc. */
5142         const char * const send = sstr + slen;
5143         U8 *d;
5144
5145         /* Something this code does not account for, which I think is
5146            impossible; it would require the same pv to be treated as
5147            bytes *and* utf8, which would indicate a bug elsewhere. */
5148         assert(sstr != dstr);
5149
5150         SvGROW(dsv, dlen + slen * 2 + 1);
5151         d = (U8 *)SvPVX(dsv) + dlen;
5152
5153         while (sstr < send) {
5154             const UV uv = NATIVE_TO_ASCII((U8)*sstr++);
5155             if (UNI_IS_INVARIANT(uv))
5156                 *d++ = (U8)UTF_TO_NATIVE(uv);
5157             else {
5158                 *d++ = (U8)UTF8_EIGHT_BIT_HI(uv);
5159                 *d++ = (U8)UTF8_EIGHT_BIT_LO(uv);
5160             }
5161         }
5162         SvCUR_set(dsv, d-(const U8 *)SvPVX(dsv));
5163     }
5164     *SvEND(dsv) = '\0';
5165     (void)SvPOK_only_UTF8(dsv);         /* validate pointer */
5166     SvTAINT(dsv);
5167     if (flags & SV_SMAGIC)
5168         SvSETMAGIC(dsv);
5169 }
5170
5171 /*
5172 =for apidoc sv_catsv
5173
5174 Concatenates the string from SV C<ssv> onto the end of the string in SV
5175 C<dsv>.  If C<ssv> is null, does nothing; otherwise modifies only C<dsv>.
5176 Handles 'get' magic on both SVs, but no 'set' magic.  See C<sv_catsv_mg> and
5177 C<sv_catsv_nomg>.
5178
5179 =for apidoc sv_catsv_flags
5180
5181 Concatenates the string from SV C<ssv> onto the end of the string in SV
5182 C<dsv>.  If C<ssv> is null, does nothing; otherwise modifies only C<dsv>.
5183 If C<flags> include C<SV_GMAGIC> bit set, will call C<mg_get> on both SVs if
5184 appropriate.  If C<flags> include C<SV_SMAGIC>, C<mg_set> will be called on
5185 the modified SV afterward, if appropriate.  C<sv_catsv>, C<sv_catsv_nomg>,
5186 and C<sv_catsv_mg> are implemented in terms of this function.
5187
5188 =cut */
5189
5190 void
5191 Perl_sv_catsv_flags(pTHX_ SV *const dsv, SV *const ssv, const I32 flags)
5192 {
5193     dVAR;
5194  
5195     PERL_ARGS_ASSERT_SV_CATSV_FLAGS;
5196
5197     if (ssv) {
5198         STRLEN slen;
5199         const char *spv = SvPV_flags_const(ssv, slen, flags);
5200         if (spv) {
5201             if (flags & SV_GMAGIC)
5202                 SvGETMAGIC(dsv);
5203             sv_catpvn_flags(dsv, spv, slen,
5204                             DO_UTF8(ssv) ? SV_CATUTF8 : SV_CATBYTES);
5205             if (flags & SV_SMAGIC)
5206                 SvSETMAGIC(dsv);
5207         }
5208     }
5209 }
5210
5211 /*
5212 =for apidoc sv_catpv
5213
5214 Concatenates the string onto the end of the string which is in the SV.
5215 If the SV has the UTF-8 status set, then the bytes appended should be
5216 valid UTF-8.  Handles 'get' magic, but not 'set' magic.  See C<sv_catpv_mg>.
5217
5218 =cut */
5219
5220 void
5221 Perl_sv_catpv(pTHX_ SV *const sv, const char *ptr)
5222 {
5223     dVAR;
5224     STRLEN len;
5225     STRLEN tlen;
5226     char *junk;
5227
5228     PERL_ARGS_ASSERT_SV_CATPV;
5229
5230     if (!ptr)
5231         return;
5232     junk = SvPV_force(sv, tlen);
5233     len = strlen(ptr);
5234     SvGROW(sv, tlen + len + 1);
5235     if (ptr == junk)
5236         ptr = SvPVX_const(sv);
5237     Move(ptr,SvPVX(sv)+tlen,len+1,char);
5238     SvCUR_set(sv, SvCUR(sv) + len);
5239     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
5240     SvTAINT(sv);
5241 }
5242
5243 /*
5244 =for apidoc sv_catpv_flags
5245
5246 Concatenates the string onto the end of the string which is in the SV.
5247 If the SV has the UTF-8 status set, then the bytes appended should
5248 be valid UTF-8.  If C<flags> has the C<SV_SMAGIC> bit set, will C<mg_set>
5249 on the modified SV if appropriate.
5250
5251 =cut
5252 */
5253
5254 void
5255 Perl_sv_catpv_flags(pTHX_ SV *dstr, const char *sstr, const I32 flags)
5256 {
5257     PERL_ARGS_ASSERT_SV_CATPV_FLAGS;
5258     sv_catpvn_flags(dstr, sstr, strlen(sstr), flags);
5259 }
5260
5261 /*
5262 =for apidoc sv_catpv_mg
5263
5264 Like C<sv_catpv>, but also handles 'set' magic.
5265
5266 =cut
5267 */
5268
5269 void
5270 Perl_sv_catpv_mg(pTHX_ SV *const sv, const char *const ptr)
5271 {
5272     PERL_ARGS_ASSERT_SV_CATPV_MG;
5273
5274     sv_catpv(sv,ptr);
5275     SvSETMAGIC(sv);
5276 }
5277
5278 /*
5279 =for apidoc newSV
5280
5281 Creates a new SV.  A non-zero C<len> parameter indicates the number of
5282 bytes of preallocated string space the SV should have.  An extra byte for a
5283 trailing NUL is also reserved.  (SvPOK is not set for the SV even if string
5284 space is allocated.)  The reference count for the new SV is set to 1.
5285
5286 In 5.9.3, newSV() replaces the older NEWSV() API, and drops the first
5287 parameter, I<x>, a debug aid which allowed callers to identify themselves.
5288 This aid has been superseded by a new build option, PERL_MEM_LOG (see
5289 L<perlhacktips/PERL_MEM_LOG>).  The older API is still there for use in XS
5290 modules supporting older perls.
5291
5292 =cut
5293 */
5294
5295 SV *
5296 Perl_newSV(pTHX_ const STRLEN len)
5297 {
5298     dVAR;
5299     SV *sv;
5300
5301     new_SV(sv);
5302     if (len) {
5303         sv_upgrade(sv, SVt_PV);
5304         SvGROW(sv, len + 1);
5305     }
5306     return sv;
5307 }
5308 /*
5309 =for apidoc sv_magicext
5310
5311 Adds magic to an SV, upgrading it if necessary.  Applies the
5312 supplied vtable and returns a pointer to the magic added.
5313
5314 Note that C<sv_magicext> will allow things that C<sv_magic> will not.
5315 In particular, you can add magic to SvREADONLY SVs, and add more than
5316 one instance of the same 'how'.
5317
5318 If C<namlen> is greater than zero then a C<savepvn> I<copy> of C<name> is
5319 stored, if C<namlen> is zero then C<name> is stored as-is and - as another
5320 special case - if C<(name && namlen == HEf_SVKEY)> then C<name> is assumed
5321 to contain an C<SV*> and is stored as-is with its REFCNT incremented.
5322
5323 (This is now used as a subroutine by C<sv_magic>.)
5324
5325 =cut
5326 */
5327 MAGIC * 
5328 Perl_sv_magicext(pTHX_ SV *const sv, SV *const obj, const int how, 
5329                 const MGVTBL *const vtable, const char *const name, const I32 namlen)
5330 {
5331     dVAR;
5332     MAGIC* mg;
5333
5334     PERL_ARGS_ASSERT_SV_MAGICEXT;
5335
5336     SvUPGRADE(sv, SVt_PVMG);
5337     Newxz(mg, 1, MAGIC);
5338     mg->mg_moremagic = SvMAGIC(sv);
5339     SvMAGIC_set(sv, mg);
5340
5341     /* Sometimes a magic contains a reference loop, where the sv and
5342        object refer to each other.  To prevent a reference loop that
5343        would prevent such objects being freed, we look for such loops
5344        and if we find one we avoid incrementing the object refcount.
5345
5346        Note we cannot do this to avoid self-tie loops as intervening RV must
5347        have its REFCNT incremented to keep it in existence.
5348
5349     */
5350     if (!obj || obj == sv ||
5351         how == PERL_MAGIC_arylen ||
5352         how == PERL_MAGIC_symtab ||
5353         (SvTYPE(obj) == SVt_PVGV &&
5354             (GvSV(obj) == sv || GvHV(obj) == (const HV *)sv
5355              || GvAV(obj) == (const AV *)sv || GvCV(obj) == (const CV *)sv
5356              || GvIOp(obj) == (const IO *)sv || GvFORM(obj) == (const CV *)sv)))
5357     {
5358         mg->mg_obj = obj;
5359     }
5360     else {
5361         mg->mg_obj = SvREFCNT_inc_simple(obj);
5362         mg->mg_flags |= MGf_REFCOUNTED;
5363     }
5364
5365     /* Normal self-ties simply pass a null object, and instead of
5366        using mg_obj directly, use the SvTIED_obj macro to produce a
5367        new RV as needed.  For glob "self-ties", we are tieing the PVIO
5368        with an RV obj pointing to the glob containing the PVIO.  In
5369        this case, to avoid a reference loop, we need to weaken the
5370        reference.
5371     */
5372
5373     if (how == PERL_MAGIC_tiedscalar && SvTYPE(sv) == SVt_PVIO &&
5374         obj && SvROK(obj) && GvIO(SvRV(obj)) == (const IO *)sv)
5375     {
5376       sv_rvweaken(obj);
5377     }
5378
5379     mg->mg_type = how;
5380     mg->mg_len = namlen;
5381     if (name) {
5382         if (namlen > 0)
5383             mg->mg_ptr = savepvn(name, namlen);
5384         else if (namlen == HEf_SVKEY) {
5385             /* Yes, this is casting away const. This is only for the case of
5386                HEf_SVKEY. I think we need to document this aberation of the
5387                constness of the API, rather than making name non-const, as
5388                that change propagating outwards a long way.  */
5389             mg->mg_ptr = (char*)SvREFCNT_inc_simple_NN((SV *)name);
5390         } else
5391             mg->mg_ptr = (char *) name;
5392     }
5393     mg->mg_virtual = (MGVTBL *) vtable;
5394
5395     mg_magical(sv);
5396     return mg;
5397 }
5398
5399 /*
5400 =for apidoc sv_magic
5401
5402 Adds magic to an SV.  First upgrades C<sv> to type C<SVt_PVMG> if
5403 necessary, then adds a new magic item of type C<how> to the head of the
5404 magic list.
5405
5406 See C<sv_magicext> (which C<sv_magic> now calls) for a description of the
5407 handling of the C<name> and C<namlen> arguments.
5408
5409 You need to use C<sv_magicext> to add magic to SvREADONLY SVs and also
5410 to add more than one instance of the same 'how'.
5411
5412 =cut
5413 */
5414
5415 void
5416 Perl_sv_magic(pTHX_ SV *const sv, SV *const obj, const int how,
5417              const char *const name, const I32 namlen)
5418 {
5419     dVAR;
5420     const MGVTBL *vtable;
5421     MAGIC* mg;
5422     unsigned int flags;
5423     unsigned int vtable_index;
5424
5425     PERL_ARGS_ASSERT_SV_MAGIC;
5426
5427     if (how < 0 || (unsigned)how > C_ARRAY_LENGTH(PL_magic_data)
5428         || ((flags = PL_magic_data[how]),
5429             (vtable_index = flags & PERL_MAGIC_VTABLE_MASK)
5430             > magic_vtable_max))
5431         Perl_croak(aTHX_ "Don't know how to handle magic of type \\%o", how);
5432
5433     /* PERL_MAGIC_ext is reserved for use by extensions not perl internals.
5434        Useful for attaching extension internal data to perl vars.
5435        Note that multiple extensions may clash if magical scalars
5436        etc holding private data from one are passed to another. */
5437
5438     vtable = (vtable_index == magic_vtable_max)
5439         ? NULL : PL_magic_vtables + vtable_index;
5440
5441 #ifdef PERL_ANY_COW
5442     if (SvIsCOW(sv))
5443         sv_force_normal_flags(sv, 0);
5444 #endif
5445     if (SvREADONLY(sv)) {
5446         if (
5447             /* its okay to attach magic to shared strings */
5448             !SvIsCOW(sv)
5449
5450             && IN_PERL_RUNTIME
5451             && !PERL_MAGIC_TYPE_READONLY_ACCEPTABLE(how)
5452            )
5453         {
5454             Perl_croak_no_modify();
5455         }
5456     }
5457     if (SvMAGICAL(sv) || (how == PERL_MAGIC_taint && SvTYPE(sv) >= SVt_PVMG)) {
5458         if (SvMAGIC(sv) && (mg = mg_find(sv, how))) {
5459             /* sv_magic() refuses to add a magic of the same 'how' as an
5460                existing one
5461              */
5462             if (how == PERL_MAGIC_taint)
5463                 mg->mg_len |= 1;
5464             return;
5465         }
5466     }
5467
5468     /* Rest of work is done else where */
5469     mg = sv_magicext(sv,obj,how,vtable,name,namlen);
5470
5471     switch (how) {
5472     case PERL_MAGIC_taint:
5473         mg->mg_len = 1;
5474         break;
5475     case PERL_MAGIC_ext:
5476     case PERL_MAGIC_dbfile:
5477         SvRMAGICAL_on(sv);
5478         break;
5479     }
5480 }
5481
5482 static int
5483 S_sv_unmagicext_flags(pTHX_ SV *const sv, const int type, MGVTBL *vtbl, const U32 flags)
5484 {
5485     MAGIC* mg;
5486     MAGIC** mgp;
5487
5488     assert(flags <= 1);
5489
5490     if (SvTYPE(sv) < SVt_PVMG || !SvMAGIC(sv))
5491         return 0;
5492     mgp = &(((XPVMG*) SvANY(sv))->xmg_u.xmg_magic);
5493     for (mg = *mgp; mg; mg = *mgp) {
5494         const MGVTBL* const virt = mg->mg_virtual;
5495         if (mg->mg_type == type && (!flags || virt == vtbl)) {
5496             *mgp = mg->mg_moremagic;
5497             if (virt && virt->svt_free)
5498                 virt->svt_free(aTHX_ sv, mg);
5499             if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) {
5500                 if (mg->mg_len > 0)
5501                     Safefree(mg->mg_ptr);
5502                 else if (mg->mg_len == HEf_SVKEY)
5503                     SvREFCNT_dec(MUTABLE_SV(mg->mg_ptr));
5504                 else if (mg->mg_type == PERL_MAGIC_utf8)
5505                     Safefree(mg->mg_ptr);
5506             }
5507             if (mg->mg_flags & MGf_REFCOUNTED)
5508                 SvREFCNT_dec(mg->mg_obj);
5509             Safefree(mg);
5510         }
5511         else
5512             mgp = &mg->mg_moremagic;
5513     }
5514     if (SvMAGIC(sv)) {
5515         if (SvMAGICAL(sv))      /* if we're under save_magic, wait for restore_magic; */
5516             mg_magical(sv);     /*    else fix the flags now */
5517     }
5518     else {
5519         SvMAGICAL_off(sv);
5520         SvFLAGS(sv) |= (SvFLAGS(sv) & (SVp_IOK|SVp_NOK|SVp_POK)) >> PRIVSHIFT;
5521     }
5522     return 0;
5523 }
5524
5525 /*
5526 =for apidoc sv_unmagic
5527
5528 Removes all magic of type C<type> from an SV.
5529
5530 =cut
5531 */
5532
5533 int
5534 Perl_sv_unmagic(pTHX_ SV *const sv, const int type)
5535 {
5536     PERL_ARGS_ASSERT_SV_UNMAGIC;
5537     return S_sv_unmagicext_flags(aTHX_ sv, type, NULL, 0);
5538 }
5539
5540 /*
5541 =for apidoc sv_unmagicext
5542
5543 Removes all magic of type C<type> with the specified C<vtbl> from an SV.
5544
5545 =cut
5546 */
5547
5548 int
5549 Perl_sv_unmagicext(pTHX_ SV *const sv, const int type, MGVTBL *vtbl)
5550 {
5551     PERL_ARGS_ASSERT_SV_UNMAGICEXT;
5552     return S_sv_unmagicext_flags(aTHX_ sv, type, vtbl, 1);
5553 }
5554
5555 /*
5556 =for apidoc sv_rvweaken
5557
5558 Weaken a reference: set the C<SvWEAKREF> flag on this RV; give the
5559 referred-to SV C<PERL_MAGIC_backref> magic if it hasn't already; and
5560 push a back-reference to this RV onto the array of backreferences
5561 associated with that magic.  If the RV is magical, set magic will be
5562 called after the RV is cleared.
5563
5564 =cut
5565 */
5566
5567 SV *
5568 Perl_sv_rvweaken(pTHX_ SV *const sv)
5569 {
5570     SV *tsv;
5571
5572     PERL_ARGS_ASSERT_SV_RVWEAKEN;
5573
5574     if (!SvOK(sv))  /* let undefs pass */
5575         return sv;
5576     if (!SvROK(sv))
5577         Perl_croak(aTHX_ "Can't weaken a nonreference");
5578     else if (SvWEAKREF(sv)) {
5579         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Reference is already weak");
5580         return sv;
5581     }
5582     else if (SvREADONLY(sv)) croak_no_modify();
5583     tsv = SvRV(sv);
5584     Perl_sv_add_backref(aTHX_ tsv, sv);
5585     SvWEAKREF_on(sv);
5586     SvREFCNT_dec_NN(tsv);
5587     return sv;
5588 }
5589
5590 /* Give tsv backref magic if it hasn't already got it, then push a
5591  * back-reference to sv onto the array associated with the backref magic.
5592  *
5593  * As an optimisation, if there's only one backref and it's not an AV,
5594  * store it directly in the HvAUX or mg_obj slot, avoiding the need to
5595  * allocate an AV. (Whether the slot holds an AV tells us whether this is
5596  * active.)
5597  */
5598
5599 /* A discussion about the backreferences array and its refcount:
5600  *
5601  * The AV holding the backreferences is pointed to either as the mg_obj of
5602  * PERL_MAGIC_backref, or in the specific case of a HV, from the
5603  * xhv_backreferences field. The array is created with a refcount
5604  * of 2. This means that if during global destruction the array gets
5605  * picked on before its parent to have its refcount decremented by the
5606  * random zapper, it won't actually be freed, meaning it's still there for
5607  * when its parent gets freed.
5608  *
5609  * When the parent SV is freed, the extra ref is killed by
5610  * Perl_sv_kill_backrefs.  The other ref is killed, in the case of magic,
5611  * by mg_free() / MGf_REFCOUNTED, or for a hash, by Perl_hv_kill_backrefs.
5612  *
5613  * When a single backref SV is stored directly, it is not reference
5614  * counted.
5615  */
5616
5617 void
5618 Perl_sv_add_backref(pTHX_ SV *const tsv, SV *const sv)
5619 {
5620     dVAR;
5621     SV **svp;
5622     AV *av = NULL;
5623     MAGIC *mg = NULL;
5624
5625     PERL_ARGS_ASSERT_SV_ADD_BACKREF;
5626
5627     /* find slot to store array or singleton backref */
5628
5629     if (SvTYPE(tsv) == SVt_PVHV) {
5630         svp = (SV**)Perl_hv_backreferences_p(aTHX_ MUTABLE_HV(tsv));
5631     } else {
5632         if (! ((mg =
5633             (SvMAGICAL(tsv) ? mg_find(tsv, PERL_MAGIC_backref) : NULL))))
5634         {
5635             sv_magic(tsv, NULL, PERL_MAGIC_backref, NULL, 0);
5636             mg = mg_find(tsv, PERL_MAGIC_backref);
5637         }
5638         svp = &(mg->mg_obj);
5639     }
5640
5641     /* create or retrieve the array */
5642
5643     if (   (!*svp && SvTYPE(sv) == SVt_PVAV)
5644         || (*svp && SvTYPE(*svp) != SVt_PVAV)
5645     ) {
5646         /* create array */
5647         av = newAV();
5648         AvREAL_off(av);
5649         SvREFCNT_inc_simple_void(av);
5650         /* av now has a refcnt of 2; see discussion above */
5651         if (*svp) {
5652             /* move single existing backref to the array */
5653             av_extend(av, 1);
5654             AvARRAY(av)[++AvFILLp(av)] = *svp; /* av_push() */
5655         }
5656         *svp = (SV*)av;
5657         if (mg)
5658             mg->mg_flags |= MGf_REFCOUNTED;
5659     }
5660     else
5661         av = MUTABLE_AV(*svp);
5662
5663     if (!av) {
5664         /* optimisation: store single backref directly in HvAUX or mg_obj */
5665         *svp = sv;
5666         return;
5667     }
5668     /* push new backref */
5669     assert(SvTYPE(av) == SVt_PVAV);
5670     if (AvFILLp(av) >= AvMAX(av)) {
5671         av_extend(av, AvFILLp(av)+1);
5672     }
5673     AvARRAY(av)[++AvFILLp(av)] = sv; /* av_push() */
5674 }
5675
5676 /* delete a back-reference to ourselves from the backref magic associated
5677  * with the SV we point to.
5678  */
5679
5680 void
5681 Perl_sv_del_backref(pTHX_ SV *const tsv, SV *const sv)
5682 {
5683     dVAR;
5684     SV **svp = NULL;
5685
5686     PERL_ARGS_ASSERT_SV_DEL_BACKREF;
5687
5688     if (SvTYPE(tsv) == SVt_PVHV) {
5689         if (SvOOK(tsv))
5690             svp = (SV**)Perl_hv_backreferences_p(aTHX_ MUTABLE_HV(tsv));
5691     }
5692     else if (SvIS_FREED(tsv) && PL_phase == PERL_PHASE_DESTRUCT) {
5693         /* It's possible for the the last (strong) reference to tsv to have
5694            become freed *before* the last thing holding a weak reference.
5695            If both survive longer than the backreferences array, then when
5696            the referent's reference count drops to 0 and it is freed, it's
5697            not able to chase the backreferences, so they aren't NULLed.
5698
5699            For example, a CV holds a weak reference to its stash. If both the
5700            CV and the stash survive longer than the backreferences array,
5701            and the CV gets picked for the SvBREAK() treatment first,
5702            *and* it turns out that the stash is only being kept alive because
5703            of an our variable in the pad of the CV, then midway during CV
5704            destruction the stash gets freed, but CvSTASH() isn't set to NULL.
5705            It ends up pointing to the freed HV. Hence it's chased in here, and
5706            if this block wasn't here, it would hit the !svp panic just below.
5707
5708            I don't believe that "better" destruction ordering is going to help
5709            here - during global destruction there's always going to be the
5710            chance that something goes out of order. We've tried to make it
5711            foolproof before, and it only resulted in evolutionary pressure on
5712            fools. Which made us look foolish for our hubris. :-(
5713         */
5714         return;
5715     }
5716     else {
5717         MAGIC *const mg
5718             = SvMAGICAL(tsv) ? mg_find(tsv, PERL_MAGIC_backref) : NULL;
5719         svp =  mg ? &(mg->mg_obj) : NULL;
5720     }
5721
5722     if (!svp)
5723         Perl_croak(aTHX_ "panic: del_backref, svp=0");
5724     if (!*svp) {
5725         /* It's possible that sv is being freed recursively part way through the
5726            freeing of tsv. If this happens, the backreferences array of tsv has
5727            already been freed, and so svp will be NULL. If this is the case,
5728            we should not panic. Instead, nothing needs doing, so return.  */
5729         if (PL_phase == PERL_PHASE_DESTRUCT && SvREFCNT(tsv) == 0)
5730             return;
5731         Perl_croak(aTHX_ "panic: del_backref, *svp=%p phase=%s refcnt=%" UVuf,
5732                    *svp, PL_phase_names[PL_phase], (UV)SvREFCNT(tsv));
5733     }
5734
5735     if (SvTYPE(*svp) == SVt_PVAV) {
5736 #ifdef DEBUGGING
5737         int count = 1;
5738 #endif
5739         AV * const av = (AV*)*svp;
5740         SSize_t fill;
5741         assert(!SvIS_FREED(av));
5742         fill = AvFILLp(av);
5743         assert(fill > -1);
5744         svp = AvARRAY(av);
5745         /* for an SV with N weak references to it, if all those
5746          * weak refs are deleted, then sv_del_backref will be called
5747          * N times and O(N^2) compares will be done within the backref
5748          * array. To ameliorate this potential slowness, we:
5749          * 1) make sure this code is as tight as possible;
5750          * 2) when looking for SV, look for it at both the head and tail of the
5751          *    array first before searching the rest, since some create/destroy
5752          *    patterns will cause the backrefs to be freed in order.
5753          */
5754         if (*svp == sv) {
5755             AvARRAY(av)++;
5756             AvMAX(av)--;
5757         }
5758         else {
5759             SV **p = &svp[fill];
5760             SV *const topsv = *p;
5761             if (topsv != sv) {
5762 #ifdef DEBUGGING
5763                 count = 0;
5764 #endif
5765                 while (--p > svp) {
5766                     if (*p == sv) {
5767                         /* We weren't the last entry.
5768                            An unordered list has this property that you
5769                            can take the last element off the end to fill
5770                            the hole, and it's still an unordered list :-)
5771                         */
5772                         *p = topsv;
5773 #ifdef DEBUGGING
5774                         count++;
5775 #else
5776                         break; /* should only be one */
5777 #endif
5778                     }
5779                 }
5780             }
5781         }
5782         assert(count ==1);
5783         AvFILLp(av) = fill-1;
5784     }
5785     else if (SvIS_FREED(*svp) && PL_phase == PERL_PHASE_DESTRUCT) {
5786         /* freed AV; skip */
5787     }
5788     else {
5789         /* optimisation: only a single backref, stored directly */
5790         if (*svp != sv)
5791             Perl_croak(aTHX_ "panic: del_backref, *svp=%p, sv=%p", *svp, sv);
5792         *svp = NULL;
5793     }
5794
5795 }
5796
5797 void
5798 Perl_sv_kill_backrefs(pTHX_ SV *const sv, AV *const av)
5799 {
5800     SV **svp;
5801     SV **last;
5802     bool is_array;
5803
5804     PERL_ARGS_ASSERT_SV_KILL_BACKREFS;
5805
5806     if (!av)
5807         return;
5808
5809     /* after multiple passes through Perl_sv_clean_all() for a thingy
5810      * that has badly leaked, the backref array may have gotten freed,
5811      * since we only protect it against 1 round of cleanup */
5812     if (SvIS_FREED(av)) {
5813         if (PL_in_clean_all) /* All is fair */
5814             return;
5815         Perl_croak(aTHX_
5816                    "panic: magic_killbackrefs (freed backref AV/SV)");
5817     }
5818
5819
5820     is_array = (SvTYPE(av) == SVt_PVAV);
5821     if (is_array) {
5822         assert(!SvIS_FREED(av));
5823         svp = AvARRAY(av);
5824         if (svp)
5825             last = svp + AvFILLp(av);
5826     }
5827     else {
5828         /* optimisation: only a single backref, stored directly */
5829         svp = (SV**)&av;
5830         last = svp;
5831     }
5832
5833     if (svp) {
5834         while (svp <= last) {
5835             if (*svp) {
5836                 SV *const referrer = *svp;
5837                 if (SvWEAKREF(referrer)) {
5838                     /* XXX Should we check that it hasn't changed? */
5839                     assert(SvROK(referrer));
5840                     SvRV_set(referrer, 0);
5841                     SvOK_off(referrer);
5842                     SvWEAKREF_off(referrer);
5843                     SvSETMAGIC(referrer);
5844                 } else if (SvTYPE(referrer) == SVt_PVGV ||
5845                            SvTYPE(referrer) == SVt_PVLV) {
5846                     assert(SvTYPE(sv) == SVt_PVHV); /* stash backref */
5847                     /* You lookin' at me?  */
5848                     assert(GvSTASH(referrer));
5849                     assert(GvSTASH(referrer) == (const HV *)sv);
5850                     GvSTASH(referrer) = 0;
5851                 } else if (SvTYPE(referrer) == SVt_PVCV ||
5852                            SvTYPE(referrer) == SVt_PVFM) {
5853                     if (SvTYPE(sv) == SVt_PVHV) { /* stash backref */
5854                         /* You lookin' at me?  */
5855                         assert(CvSTASH(referrer));
5856                         assert(CvSTASH(referrer) == (const HV *)sv);
5857                         SvANY(MUTABLE_CV(referrer))->xcv_stash = 0;
5858                     }
5859                     else {
5860                         assert(SvTYPE(sv) == SVt_PVGV);
5861                         /* You lookin' at me?  */
5862                         assert(CvGV(referrer));
5863                         assert(CvGV(referrer) == (const GV *)sv);
5864                         anonymise_cv_maybe(MUTABLE_GV(sv),
5865                                                 MUTABLE_CV(referrer));
5866                     }
5867
5868                 } else {
5869                     Perl_croak(aTHX_
5870                                "panic: magic_killbackrefs (flags=%"UVxf")",
5871                                (UV)SvFLAGS(referrer));
5872                 }
5873
5874                 if (is_array)
5875                     *svp = NULL;
5876             }
5877             svp++;
5878         }
5879     }
5880     if (is_array) {
5881         AvFILLp(av) = -1;
5882         SvREFCNT_dec_NN(av); /* remove extra count added by sv_add_backref() */
5883     }
5884     return;
5885 }
5886
5887 /*
5888 =for apidoc sv_insert
5889
5890 Inserts a string at the specified offset/length within the SV.  Similar to
5891 the Perl substr() function.  Handles get magic.
5892
5893 =for apidoc sv_insert_flags
5894
5895 Same as C<sv_insert>, but the extra C<flags> are passed to the
5896 C<SvPV_force_flags> that applies to C<bigstr>.
5897
5898 =cut
5899 */
5900
5901 void
5902 Perl_sv_insert_flags(pTHX_ SV *const bigstr, const STRLEN offset, const STRLEN len, const char *const little, const STRLEN littlelen, const U32 flags)
5903 {
5904     dVAR;
5905     char *big;
5906     char *mid;
5907     char *midend;
5908     char *bigend;
5909     SSize_t i;          /* better be sizeof(STRLEN) or bad things happen */
5910     STRLEN curlen;
5911
5912     PERL_ARGS_ASSERT_SV_INSERT_FLAGS;
5913
5914     if (!bigstr)
5915         Perl_croak(aTHX_ "Can't modify nonexistent substring");
5916     SvPV_force_flags(bigstr, curlen, flags);
5917     (void)SvPOK_only_UTF8(bigstr);
5918     if (offset + len > curlen) {
5919         SvGROW(bigstr, offset+len+1);
5920         Zero(SvPVX(bigstr)+curlen, offset+len-curlen, char);
5921         SvCUR_set(bigstr, offset+len);
5922     }
5923
5924     SvTAINT(bigstr);
5925     i = littlelen - len;
5926     if (i > 0) {                        /* string might grow */
5927         big = SvGROW(bigstr, SvCUR(bigstr) + i + 1);
5928         mid = big + offset + len;
5929         midend = bigend = big + SvCUR(bigstr);
5930         bigend += i;
5931         *bigend = '\0';
5932         while (midend > mid)            /* shove everything down */
5933             *--bigend = *--midend;
5934         Move(little,big+offset,littlelen,char);
5935         SvCUR_set(bigstr, SvCUR(bigstr) + i);
5936         SvSETMAGIC(bigstr);
5937         return;
5938     }
5939     else if (i == 0) {
5940         Move(little,SvPVX(bigstr)+offset,len,char);
5941         SvSETMAGIC(bigstr);
5942         return;
5943     }
5944
5945     big = SvPVX(bigstr);
5946     mid = big + offset;
5947     midend = mid + len;
5948     bigend = big + SvCUR(bigstr);
5949
5950     if (midend > bigend)
5951         Perl_croak(aTHX_ "panic: sv_insert, midend=%p, bigend=%p",
5952                    midend, bigend);
5953
5954     if (mid - big > bigend - midend) {  /* faster to shorten from end */
5955         if (littlelen) {
5956             Move(little, mid, littlelen,char);
5957             mid += littlelen;
5958         }
5959         i = bigend - midend;
5960         if (i > 0) {
5961             Move(midend, mid, i,char);
5962             mid += i;
5963         }
5964         *mid = '\0';
5965         SvCUR_set(bigstr, mid - big);
5966     }
5967     else if ((i = mid - big)) { /* faster from front */
5968         midend -= littlelen;
5969         mid = midend;
5970         Move(big, midend - i, i, char);
5971         sv_chop(bigstr,midend-i);
5972         if (littlelen)
5973             Move(little, mid, littlelen,char);
5974     }
5975     else if (littlelen) {
5976         midend -= littlelen;
5977         sv_chop(bigstr,midend);
5978         Move(little,midend,littlelen,char);
5979     }
5980     else {
5981         sv_chop(bigstr,midend);
5982     }
5983     SvSETMAGIC(bigstr);
5984 }
5985
5986 /*
5987 =for apidoc sv_replace
5988
5989 Make the first argument a copy of the second, then delete the original.
5990 The target SV physically takes over ownership of the body of the source SV
5991 and inherits its flags; however, the target keeps any magic it owns,
5992 and any magic in the source is discarded.
5993 Note that this is a rather specialist SV copying operation; most of the
5994 time you'll want to use C<sv_setsv> or one of its many macro front-ends.
5995
5996 =cut
5997 */
5998
5999 void
6000 Perl_sv_replace(pTHX_ SV *const sv, SV *const nsv)
6001 {
6002     dVAR;
6003     const U32 refcnt = SvREFCNT(sv);
6004
6005     PERL_ARGS_ASSERT_SV_REPLACE;
6006
6007     SV_CHECK_THINKFIRST_COW_DROP(sv);
6008     if (SvREFCNT(nsv) != 1) {
6009         Perl_croak(aTHX_ "panic: reference miscount on nsv in sv_replace()"
6010                    " (%" UVuf " != 1)", (UV) SvREFCNT(nsv));
6011     }
6012     if (SvMAGICAL(sv)) {
6013         if (SvMAGICAL(nsv))
6014             mg_free(nsv);
6015         else
6016             sv_upgrade(nsv, SVt_PVMG);
6017         SvMAGIC_set(nsv, SvMAGIC(sv));
6018         SvFLAGS(nsv) |= SvMAGICAL(sv);
6019         SvMAGICAL_off(sv);
6020         SvMAGIC_set(sv, NULL);
6021     }
6022     SvREFCNT(sv) = 0;
6023     sv_clear(sv);
6024     assert(!SvREFCNT(sv));
6025 #ifdef DEBUG_LEAKING_SCALARS
6026     sv->sv_flags  = nsv->sv_flags;
6027     sv->sv_any    = nsv->sv_any;
6028     sv->sv_refcnt = nsv->sv_refcnt;
6029     sv->sv_u      = nsv->sv_u;
6030 #else
6031     StructCopy(nsv,sv,SV);
6032 #endif
6033     if(SvTYPE(sv) == SVt_IV) {
6034         SvANY(sv)
6035             = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
6036     }
6037         
6038
6039 #ifdef PERL_OLD_COPY_ON_WRITE
6040     if (SvIsCOW_normal(nsv)) {
6041         /* We need to follow the pointers around the loop to make the
6042            previous SV point to sv, rather than nsv.  */
6043         SV *next;
6044         SV *current = nsv;
6045         while ((next = SV_COW_NEXT_SV(current)) != nsv) {
6046             assert(next);
6047             current = next;
6048             assert(SvPVX_const(current) == SvPVX_const(nsv));
6049         }
6050         /* Make the SV before us point to the SV after us.  */
6051         if (DEBUG_C_TEST) {
6052             PerlIO_printf(Perl_debug_log, "previous is\n");
6053             sv_dump(current);
6054             PerlIO_printf(Perl_debug_log,
6055                           "move it from 0x%"UVxf" to 0x%"UVxf"\n",
6056                           (UV) SV_COW_NEXT_SV(current), (UV) sv);
6057         }
6058         SV_COW_NEXT_SV_SET(current, sv);
6059     }
6060 #endif
6061     SvREFCNT(sv) = refcnt;
6062     SvFLAGS(nsv) |= SVTYPEMASK;         /* Mark as freed */
6063     SvREFCNT(nsv) = 0;
6064     del_SV(nsv);
6065 }
6066
6067 /* We're about to free a GV which has a CV that refers back to us.
6068  * If that CV will outlive us, make it anonymous (i.e. fix up its CvGV
6069  * field) */
6070
6071 STATIC void
6072 S_anonymise_cv_maybe(pTHX_ GV *gv, CV* cv)
6073 {
6074     SV *gvname;
6075     GV *anongv;
6076
6077     PERL_ARGS_ASSERT_ANONYMISE_CV_MAYBE;
6078
6079     /* be assertive! */
6080     assert(SvREFCNT(gv) == 0);
6081     assert(isGV(gv) && isGV_with_GP(gv));
6082     assert(GvGP(gv));
6083     assert(!CvANON(cv));
6084     assert(CvGV(cv) == gv);
6085     assert(!CvNAMED(cv));
6086
6087     /* will the CV shortly be freed by gp_free() ? */
6088     if (GvCV(gv) == cv && GvGP(gv)->gp_refcnt < 2 && SvREFCNT(cv) < 2) {
6089         SvANY(cv)->xcv_gv_u.xcv_gv = NULL;
6090         return;
6091     }
6092
6093     /* if not, anonymise: */
6094     gvname = (GvSTASH(gv) && HvNAME(GvSTASH(gv)) && HvENAME(GvSTASH(gv)))
6095                     ? newSVhek(HvENAME_HEK(GvSTASH(gv)))
6096                     : newSVpvn_flags( "__ANON__", 8, 0 );
6097     sv_catpvs(gvname, "::__ANON__");
6098     anongv = gv_fetchsv(gvname, GV_ADDMULTI, SVt_PVCV);
6099     SvREFCNT_dec_NN(gvname);
6100
6101     CvANON_on(cv);
6102     CvCVGV_RC_on(cv);
6103     SvANY(cv)->xcv_gv_u.xcv_gv = MUTABLE_GV(SvREFCNT_inc(anongv));
6104 }
6105
6106
6107 /*
6108 =for apidoc sv_clear
6109
6110 Clear an SV: call any destructors, free up any memory used by the body,
6111 and free the body itself.  The SV's head is I<not> freed, although
6112 its type is set to all 1's so that it won't inadvertently be assumed
6113 to be live during global destruction etc.
6114 This function should only be called when REFCNT is zero.  Most of the time
6115 you'll want to call C<sv_free()> (or its macro wrapper C<SvREFCNT_dec>)
6116 instead.
6117
6118 =cut
6119 */
6120
6121 void
6122 Perl_sv_clear(pTHX_ SV *const orig_sv)
6123 {
6124     dVAR;
6125     HV *stash;
6126     U32 type;
6127     const struct body_details *sv_type_details;
6128     SV* iter_sv = NULL;
6129     SV* next_sv = NULL;
6130     SV *sv = orig_sv;
6131     STRLEN hash_index;
6132
6133     PERL_ARGS_ASSERT_SV_CLEAR;
6134
6135     /* within this loop, sv is the SV currently being freed, and
6136      * iter_sv is the most recent AV or whatever that's being iterated
6137      * over to provide more SVs */
6138
6139     while (sv) {
6140
6141         type = SvTYPE(sv);
6142
6143         assert(SvREFCNT(sv) == 0);
6144         assert(SvTYPE(sv) != (svtype)SVTYPEMASK);
6145
6146         if (type <= SVt_IV) {
6147             /* See the comment in sv.h about the collusion between this
6148              * early return and the overloading of the NULL slots in the
6149              * size table.  */
6150             if (SvROK(sv))
6151                 goto free_rv;
6152             SvFLAGS(sv) &= SVf_BREAK;
6153             SvFLAGS(sv) |= SVTYPEMASK;
6154             goto free_head;
6155         }
6156
6157         assert(!SvOBJECT(sv) || type >= SVt_PVMG); /* objs are always >= MG */
6158
6159         if (type >= SVt_PVMG) {
6160             if (SvOBJECT(sv)) {
6161                 if (!curse(sv, 1)) goto get_next_sv;
6162                 type = SvTYPE(sv); /* destructor may have changed it */
6163             }
6164             /* Free back-references before magic, in case the magic calls
6165              * Perl code that has weak references to sv. */
6166             if (type == SVt_PVHV) {
6167                 Perl_hv_kill_backrefs(aTHX_ MUTABLE_HV(sv));
6168                 if (SvMAGIC(sv))
6169                     mg_free(sv);
6170             }
6171             else if (type == SVt_PVMG && SvPAD_OUR(sv)) {
6172                 SvREFCNT_dec(SvOURSTASH(sv));
6173             } else if (SvMAGIC(sv)) {
6174                 /* Free back-references before other types of magic. */
6175                 sv_unmagic(sv, PERL_MAGIC_backref);
6176                 mg_free(sv);
6177             }
6178             SvMAGICAL_off(sv);
6179             if (type == SVt_PVMG && SvPAD_TYPED(sv))
6180                 SvREFCNT_dec(SvSTASH(sv));
6181         }
6182         switch (type) {
6183             /* case SVt_DUMMY: */
6184         case SVt_PVIO:
6185             if (IoIFP(sv) &&
6186                 IoIFP(sv) != PerlIO_stdin() &&
6187                 IoIFP(sv) != PerlIO_stdout() &&
6188                 IoIFP(sv) != PerlIO_stderr() &&
6189                 !(IoFLAGS(sv) & IOf_FAKE_DIRP))
6190             {
6191                 io_close(MUTABLE_IO(sv), FALSE);
6192             }
6193             if (IoDIRP(sv) && !(IoFLAGS(sv) & IOf_FAKE_DIRP))
6194                 PerlDir_close(IoDIRP(sv));
6195             IoDIRP(sv) = (DIR*)NULL;
6196             Safefree(IoTOP_NAME(sv));
6197             Safefree(IoFMT_NAME(sv));
6198             Safefree(IoBOTTOM_NAME(sv));
6199             if ((const GV *)sv == PL_statgv)
6200                 PL_statgv = NULL;
6201             goto freescalar;
6202         case SVt_REGEXP:
6203             /* FIXME for plugins */
6204           freeregexp:
6205             pregfree2((REGEXP*) sv);
6206             goto freescalar;
6207         case SVt_PVCV:
6208         case SVt_PVFM:
6209             cv_undef(MUTABLE_CV(sv));
6210             /* If we're in a stash, we don't own a reference to it.
6211              * However it does have a back reference to us, which needs to
6212              * be cleared.  */
6213             if ((stash = CvSTASH(sv)))
6214                 sv_del_backref(MUTABLE_SV(stash), sv);
6215             goto freescalar;
6216         case SVt_PVHV:
6217             if (PL_last_swash_hv == (const HV *)sv) {
6218                 PL_last_swash_hv = NULL;
6219             }
6220             if (HvTOTALKEYS((HV*)sv) > 0) {
6221                 const char *name;
6222                 /* this statement should match the one at the beginning of
6223                  * hv_undef_flags() */
6224                 if (   PL_phase != PERL_PHASE_DESTRUCT
6225                     && (name = HvNAME((HV*)sv)))
6226                 {
6227                     if (PL_stashcache) {
6228                     DEBUG_o(Perl_deb(aTHX_ "sv_clear clearing PL_stashcache for '%"SVf"'\n",
6229                                      sv));
6230                         (void)hv_delete(PL_stashcache, name,
6231                             HvNAMEUTF8((HV*)sv) ? -HvNAMELEN_get((HV*)sv) : HvNAMELEN_get((HV*)sv), G_DISCARD);
6232                     }
6233                     hv_name_set((HV*)sv, NULL, 0, 0);
6234                 }
6235
6236                 /* save old iter_sv in unused SvSTASH field */
6237                 assert(!SvOBJECT(sv));
6238                 SvSTASH(sv) = (HV*)iter_sv;
6239                 iter_sv = sv;
6240
6241                 /* save old hash_index in unused SvMAGIC field */
6242                 assert(!SvMAGICAL(sv));
6243                 assert(!SvMAGIC(sv));
6244                 ((XPVMG*) SvANY(sv))->xmg_u.xmg_hash_index = hash_index;
6245                 hash_index = 0;
6246
6247                 next_sv = Perl_hfree_next_entry(aTHX_ (HV*)sv, &hash_index);
6248                 goto get_next_sv; /* process this new sv */
6249             }
6250             /* free empty hash */
6251             Perl_hv_undef_flags(aTHX_ MUTABLE_HV(sv), HV_NAME_SETALL);
6252             assert(!HvARRAY((HV*)sv));
6253             break;
6254         case SVt_PVAV:
6255             {
6256                 AV* av = MUTABLE_AV(sv);
6257                 if (PL_comppad == av) {
6258                     PL_comppad = NULL;
6259                     PL_curpad = NULL;
6260                 }
6261                 if (AvREAL(av) && AvFILLp(av) > -1) {
6262                     next_sv = AvARRAY(av)[AvFILLp(av)--];
6263                     /* save old iter_sv in top-most slot of AV,
6264                      * and pray that it doesn't get wiped in the meantime */
6265                     AvARRAY(av)[AvMAX(av)] = iter_sv;
6266                     iter_sv = sv;
6267                     goto get_next_sv; /* process this new sv */
6268                 }
6269                 Safefree(AvALLOC(av));
6270             }
6271
6272             break;
6273         case SVt_PVLV:
6274             if (LvTYPE(sv) == 'T') { /* for tie: return HE to pool */
6275                 SvREFCNT_dec(HeKEY_sv((HE*)LvTARG(sv)));
6276                 HeNEXT((HE*)LvTARG(sv)) = PL_hv_fetch_ent_mh;
6277                 PL_hv_fetch_ent_mh = (HE*)LvTARG(sv);
6278             }
6279             else if (LvTYPE(sv) != 't') /* unless tie: unrefcnted fake SV**  */
6280                 SvREFCNT_dec(LvTARG(sv));
6281             if (isREGEXP(sv)) goto freeregexp;
6282         case SVt_PVGV:
6283             if (isGV_with_GP(sv)) {
6284                 if(GvCVu((const GV *)sv) && (stash = GvSTASH(MUTABLE_GV(sv)))
6285                    && HvENAME_get(stash))
6286                     mro_method_changed_in(stash);
6287                 gp_free(MUTABLE_GV(sv));
6288                 if (GvNAME_HEK(sv))
6289                     unshare_hek(GvNAME_HEK(sv));
6290                 /* If we're in a stash, we don't own a reference to it.
6291                  * However it does have a back reference to us, which
6292                  * needs to be cleared.  */
6293                 if (!SvVALID(sv) && (stash = GvSTASH(sv)))
6294                         sv_del_backref(MUTABLE_SV(stash), sv);
6295             }
6296             /* FIXME. There are probably more unreferenced pointers to SVs
6297              * in the interpreter struct that we should check and tidy in
6298              * a similar fashion to this:  */
6299             /* See also S_sv_unglob, which does the same thing. */
6300             if ((const GV *)sv == PL_last_in_gv)
6301                 PL_last_in_gv = NULL;
6302             else if ((const GV *)sv == PL_statgv)
6303                 PL_statgv = NULL;
6304             else if ((const GV *)sv == PL_stderrgv)
6305                 PL_stderrgv = NULL;
6306         case SVt_PVMG:
6307         case SVt_PVNV:
6308         case SVt_PVIV:
6309         case SVt_PV:
6310           freescalar:
6311             /* Don't bother with SvOOK_off(sv); as we're only going to
6312              * free it.  */
6313             if (SvOOK(sv)) {
6314                 STRLEN offset;
6315                 SvOOK_offset(sv, offset);
6316                 SvPV_set(sv, SvPVX_mutable(sv) - offset);
6317                 /* Don't even bother with turning off the OOK flag.  */
6318             }
6319             if (SvROK(sv)) {
6320             free_rv:
6321                 {
6322                     SV * const target = SvRV(sv);
6323                     if (SvWEAKREF(sv))
6324                         sv_del_backref(target, sv);
6325                     else
6326                         next_sv = target;
6327                 }
6328             }
6329 #ifdef PERL_ANY_COW
6330             else if (SvPVX_const(sv)
6331                      && !(SvTYPE(sv) == SVt_PVIO
6332                      && !(IoFLAGS(sv) & IOf_FAKE_DIRP)))
6333             {
6334                 if (SvIsCOW(sv)) {
6335                     if (DEBUG_C_TEST) {
6336                         PerlIO_printf(Perl_debug_log, "Copy on write: clear\n");
6337                         sv_dump(sv);
6338                     }
6339                     if (SvLEN(sv)) {
6340 # ifdef PERL_OLD_COPY_ON_WRITE
6341                         sv_release_COW(sv, SvPVX_const(sv), SV_COW_NEXT_SV(sv));
6342 # else
6343                         if (CowREFCNT(sv)) {
6344                             CowREFCNT(sv)--;
6345                             SvLEN_set(sv, 0);
6346                         }
6347 # endif
6348                     } else {
6349                         unshare_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sv)));
6350                     }
6351
6352                 }
6353 # ifdef PERL_OLD_COPY_ON_WRITE
6354                 else
6355 # endif
6356                 if (SvLEN(sv)) {
6357                     Safefree(SvPVX_mutable(sv));
6358                 }
6359             }
6360 #else
6361             else if (SvPVX_const(sv) && SvLEN(sv)
6362                      && !(SvTYPE(sv) == SVt_PVIO
6363                      && !(IoFLAGS(sv) & IOf_FAKE_DIRP)))
6364                 Safefree(SvPVX_mutable(sv));
6365             else if (SvPVX_const(sv) && SvIsCOW(sv)) {
6366                 unshare_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sv)));
6367             }
6368 #endif
6369             break;
6370         case SVt_NV:
6371             break;
6372         }
6373
6374       free_body:
6375
6376         SvFLAGS(sv) &= SVf_BREAK;
6377         SvFLAGS(sv) |= SVTYPEMASK;
6378
6379         sv_type_details = bodies_by_type + type;
6380         if (sv_type_details->arena) {
6381             del_body(((char *)SvANY(sv) + sv_type_details->offset),
6382                      &PL_body_roots[type]);
6383         }
6384         else if (sv_type_details->body_size) {
6385             safefree(SvANY(sv));
6386         }
6387
6388       free_head:
6389         /* caller is responsible for freeing the head of the original sv */
6390         if (sv != orig_sv && !SvREFCNT(sv))
6391             del_SV(sv);
6392
6393         /* grab and free next sv, if any */
6394       get_next_sv:
6395         while (1) {
6396             sv = NULL;
6397             if (next_sv) {
6398                 sv = next_sv;
6399                 next_sv = NULL;
6400             }
6401             else if (!iter_sv) {
6402                 break;
6403             } else if (SvTYPE(iter_sv) == SVt_PVAV) {
6404                 AV *const av = (AV*)iter_sv;
6405                 if (AvFILLp(av) > -1) {
6406                     sv = AvARRAY(av)[AvFILLp(av)--];
6407                 }
6408                 else { /* no more elements of current AV to free */
6409                     sv = iter_sv;
6410                     type = SvTYPE(sv);
6411                     /* restore previous value, squirrelled away */
6412                     iter_sv = AvARRAY(av)[AvMAX(av)];
6413                     Safefree(AvALLOC(av));
6414                     goto free_body;
6415                 }
6416             } else if (SvTYPE(iter_sv) == SVt_PVHV) {
6417                 sv = Perl_hfree_next_entry(aTHX_ (HV*)iter_sv, &hash_index);
6418                 if (!sv && !HvTOTALKEYS((HV *)iter_sv)) {
6419                     /* no more elements of current HV to free */
6420                     sv = iter_sv;
6421                     type = SvTYPE(sv);
6422                     /* Restore previous values of iter_sv and hash_index,
6423                      * squirrelled away */
6424                     assert(!SvOBJECT(sv));
6425                     iter_sv = (SV*)SvSTASH(sv);
6426                     assert(!SvMAGICAL(sv));
6427                     hash_index = ((XPVMG*) SvANY(sv))->xmg_u.xmg_hash_index;
6428 #ifdef DEBUGGING
6429                     /* perl -DA does not like rubbish in SvMAGIC. */
6430                     SvMAGIC_set(sv, 0);
6431 #endif
6432
6433                     /* free any remaining detritus from the hash struct */
6434                     Perl_hv_undef_flags(aTHX_ MUTABLE_HV(sv), HV_NAME_SETALL);
6435                     assert(!HvARRAY((HV*)sv));
6436                     goto free_body;
6437                 }
6438             }
6439
6440             /* unrolled SvREFCNT_dec and sv_free2 follows: */
6441
6442             if (!sv)
6443                 continue;
6444             if (!SvREFCNT(sv)) {
6445                 sv_free(sv);
6446                 continue;
6447             }
6448             if (--(SvREFCNT(sv)))
6449                 continue;
6450 #ifdef DEBUGGING
6451             if (SvTEMP(sv)) {
6452                 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEBUGGING),
6453                          "Attempt to free temp prematurely: SV 0x%"UVxf
6454                          pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
6455                 continue;
6456             }
6457 #endif
6458             if (SvIMMORTAL(sv)) {
6459                 /* make sure SvREFCNT(sv)==0 happens very seldom */
6460                 SvREFCNT(sv) = SvREFCNT_IMMORTAL;
6461                 continue;
6462             }
6463             break;
6464         } /* while 1