This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
assert that HvARRAY is NULL when freeing an HV
[perl5.git] / sv.c
1 /*    sv.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 by Larry Wall
5  *    and others
6  *
7  *    You may distribute under the terms of either the GNU General Public
8  *    License or the Artistic License, as specified in the README file.
9  *
10  */
11
12 /*
13  * 'I wonder what the Entish is for "yes" and "no",' he thought.
14  *                                                      --Pippin
15  *
16  *     [p.480 of _The Lord of the Rings_, III/iv: "Treebeard"]
17  */
18
19 /*
20  *
21  *
22  * This file contains the code that creates, manipulates and destroys
23  * scalar values (SVs). The other types (AV, HV, GV, etc.) reuse the
24  * structure of an SV, so their creation and destruction is handled
25  * here; higher-level functions are in av.c, hv.c, and so on. Opcode
26  * level functions (eg. substr, split, join) for each of the types are
27  * in the pp*.c files.
28  */
29
30 #include "EXTERN.h"
31 #define PERL_IN_SV_C
32 #include "perl.h"
33 #include "regcomp.h"
34
35 #ifndef HAS_C99
36 # if __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 /* This is a pessimistic view. Scalar must be purely a read-write PV to copy-
70    on-write.  */
71 #endif
72
73 /* ============================================================================
74
75 =head1 Allocation and deallocation of SVs.
76
77 An SV (or AV, HV, etc.) is allocated in two parts: the head (struct
78 sv, av, hv...) contains type and reference count information, and for
79 many types, a pointer to the body (struct xrv, xpv, xpviv...), which
80 contains fields specific to each type.  Some types store all they need
81 in the head, so don't have a body.
82
83 In all but the most memory-paranoid configurations (ex: PURIFY), heads
84 and bodies are allocated out of arenas, which by default are
85 approximately 4K chunks of memory parcelled up into N heads or bodies.
86 Sv-bodies are allocated by their sv-type, guaranteeing size
87 consistency needed to allocate safely from arrays.
88
89 For SV-heads, the first slot in each arena is reserved, and holds a
90 link to the next arena, some flags, and a note of the number of slots.
91 Snaked through each arena chain is a linked list of free items; when
92 this becomes empty, an extra arena is allocated and divided up into N
93 items which are threaded into the free list.
94
95 SV-bodies are similar, but they use arena-sets by default, which
96 separate the link and info from the arena itself, and reclaim the 1st
97 slot in the arena.  SV-bodies are further described later.
98
99 The following global variables are associated with arenas:
100
101     PL_sv_arenaroot     pointer to list of SV arenas
102     PL_sv_root          pointer to list of free SV structures
103
104     PL_body_arenas      head of linked-list of body arenas
105     PL_body_roots[]     array of pointers to list of free bodies of svtype
106                         arrays are indexed by the svtype needed
107
108 A few special SV heads are not allocated from an arena, but are
109 instead directly created in the interpreter structure, eg PL_sv_undef.
110 The size of arenas can be changed from the default by setting
111 PERL_ARENA_SIZE appropriately at compile time.
112
113 The SV arena serves the secondary purpose of allowing still-live SVs
114 to be located and destroyed during final cleanup.
115
116 At the lowest level, the macros new_SV() and del_SV() grab and free
117 an SV head.  (If debugging with -DD, del_SV() calls the function S_del_sv()
118 to return the SV to the free list with error checking.) new_SV() calls
119 more_sv() / sv_add_arena() to add an extra arena if the free list is empty.
120 SVs in the free list have their SvTYPE field set to all ones.
121
122 At the time of very final cleanup, sv_free_arenas() is called from
123 perl_destruct() to physically free all the arenas allocated since the
124 start of the interpreter.
125
126 The function visit() scans the SV arenas list, and calls a specified
127 function for each SV it finds which is still live - ie which has an SvTYPE
128 other than all 1's, and a non-zero SvREFCNT. visit() is used by the
129 following functions (specified as [function that calls visit()] / [function
130 called by visit() for each SV]):
131
132     sv_report_used() / do_report_used()
133                         dump all remaining SVs (debugging aid)
134
135     sv_clean_objs() / do_clean_objs(),do_clean_named_objs(),
136                       do_clean_named_io_objs()
137                         Attempt to free all objects pointed to by RVs,
138                         and try to do the same for all objects indirectly
139                         referenced by typeglobs too.  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) Safefree((sv)->sv_debug_file)
186 #  define DEBUG_SV_SERIAL(sv)                                               \
187     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) del_SV\n",    \
188             PTR2UV(sv), (long)(sv)->sv_debug_serial))
189 #else
190 #  define FREE_SV_DEBUG_FILE(sv)
191 #  define DEBUG_SV_SERIAL(sv)   NOOP
192 #endif
193
194 #ifdef PERL_POISON
195 #  define SvARENA_CHAIN(sv)     ((sv)->sv_u.svu_rv)
196 #  define SvARENA_CHAIN_SET(sv,val)     (sv)->sv_u.svu_rv = MUTABLE_SV((val))
197 /* Whilst I'd love to do this, it seems that things like to check on
198    unreferenced scalars
199 #  define POSION_SV_HEAD(sv)    PoisonNew(sv, 1, struct STRUCT_SV)
200 */
201 #  define POSION_SV_HEAD(sv)    PoisonNew(&SvANY(sv), 1, void *), \
202                                 PoisonNew(&SvREFCNT(sv), 1, U32)
203 #else
204 #  define SvARENA_CHAIN(sv)     SvANY(sv)
205 #  define SvARENA_CHAIN_SET(sv,val)     SvANY(sv) = (void *)(val)
206 #  define POSION_SV_HEAD(sv)
207 #endif
208
209 /* Mark an SV head as unused, and add to free list.
210  *
211  * If SVf_BREAK is set, skip adding it to the free list, as this SV had
212  * its refcount artificially decremented during global destruction, so
213  * there may be dangling pointers to it. The last thing we want in that
214  * case is for it to be reused. */
215
216 #define plant_SV(p) \
217     STMT_START {                                        \
218         const U32 old_flags = SvFLAGS(p);                       \
219         MEM_LOG_DEL_SV(p, __FILE__, __LINE__, FUNCTION__);  \
220         DEBUG_SV_SERIAL(p);                             \
221         FREE_SV_DEBUG_FILE(p);                          \
222         POSION_SV_HEAD(p);                              \
223         SvFLAGS(p) = SVTYPEMASK;                        \
224         if (!(old_flags & SVf_BREAK)) {         \
225             SvARENA_CHAIN_SET(p, PL_sv_root);   \
226             PL_sv_root = (p);                           \
227         }                                               \
228         --PL_sv_count;                                  \
229     } STMT_END
230
231 #define uproot_SV(p) \
232     STMT_START {                                        \
233         (p) = PL_sv_root;                               \
234         PL_sv_root = MUTABLE_SV(SvARENA_CHAIN(p));              \
235         ++PL_sv_count;                                  \
236     } STMT_END
237
238
239 /* make some more SVs by adding another arena */
240
241 STATIC SV*
242 S_more_sv(pTHX)
243 {
244     dVAR;
245     SV* sv;
246     char *chunk;                /* must use New here to match call to */
247     Newx(chunk,PERL_ARENA_SIZE,char);  /* Safefree() in sv_free_arenas() */
248     sv_add_arena(chunk, PERL_ARENA_SIZE, 0);
249     uproot_SV(sv);
250     return sv;
251 }
252
253 /* new_SV(): return a new, empty SV head */
254
255 #ifdef DEBUG_LEAKING_SCALARS
256 /* provide a real function for a debugger to play with */
257 STATIC SV*
258 S_new_SV(pTHX_ const char *file, int line, const char *func)
259 {
260     SV* sv;
261
262     if (PL_sv_root)
263         uproot_SV(sv);
264     else
265         sv = S_more_sv(aTHX);
266     SvANY(sv) = 0;
267     SvREFCNT(sv) = 1;
268     SvFLAGS(sv) = 0;
269     sv->sv_debug_optype = PL_op ? PL_op->op_type : 0;
270     sv->sv_debug_line = (U16) (PL_parser && PL_parser->copline != NOLINE
271                 ? PL_parser->copline
272                 :  PL_curcop
273                     ? CopLINE(PL_curcop)
274                     : 0
275             );
276     sv->sv_debug_inpad = 0;
277     sv->sv_debug_parent = NULL;
278     sv->sv_debug_file = PL_curcop ? savepv(CopFILE(PL_curcop)): NULL;
279
280     sv->sv_debug_serial = PL_sv_serial++;
281
282     MEM_LOG_NEW_SV(sv, file, line, func);
283     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) new_SV (from %s:%d [%s])\n",
284             PTR2UV(sv), (long)sv->sv_debug_serial, file, line, func));
285
286     return sv;
287 }
288 #  define new_SV(p) (p)=S_new_SV(aTHX_ __FILE__, __LINE__, FUNCTION__)
289
290 #else
291 #  define new_SV(p) \
292     STMT_START {                                        \
293         if (PL_sv_root)                                 \
294             uproot_SV(p);                               \
295         else                                            \
296             (p) = S_more_sv(aTHX);                      \
297         SvANY(p) = 0;                                   \
298         SvREFCNT(p) = 1;                                \
299         SvFLAGS(p) = 0;                                 \
300         MEM_LOG_NEW_SV(p, __FILE__, __LINE__, FUNCTION__);  \
301     } STMT_END
302 #endif
303
304
305 /* del_SV(): return an empty SV head to the free list */
306
307 #ifdef DEBUGGING
308
309 #define del_SV(p) \
310     STMT_START {                                        \
311         if (DEBUG_D_TEST)                               \
312             del_sv(p);                                  \
313         else                                            \
314             plant_SV(p);                                \
315     } STMT_END
316
317 STATIC void
318 S_del_sv(pTHX_ SV *p)
319 {
320     dVAR;
321
322     PERL_ARGS_ASSERT_DEL_SV;
323
324     if (DEBUG_D_TEST) {
325         SV* sva;
326         bool ok = 0;
327         for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
328             const SV * const sv = sva + 1;
329             const SV * const svend = &sva[SvREFCNT(sva)];
330             if (p >= sv && p < svend) {
331                 ok = 1;
332                 break;
333             }
334         }
335         if (!ok) {
336             Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
337                              "Attempt to free non-arena SV: 0x%"UVxf
338                              pTHX__FORMAT, PTR2UV(p) pTHX__VALUE);
339             return;
340         }
341     }
342     plant_SV(p);
343 }
344
345 #else /* ! DEBUGGING */
346
347 #define del_SV(p)   plant_SV(p)
348
349 #endif /* DEBUGGING */
350
351
352 /*
353 =head1 SV Manipulation Functions
354
355 =for apidoc sv_add_arena
356
357 Given a chunk of memory, link it to the head of the list of arenas,
358 and split it into a list of free SVs.
359
360 =cut
361 */
362
363 static void
364 S_sv_add_arena(pTHX_ char *const ptr, const U32 size, const U32 flags)
365 {
366     dVAR;
367     SV *const sva = MUTABLE_SV(ptr);
368     register SV* sv;
369     register SV* svend;
370
371     PERL_ARGS_ASSERT_SV_ADD_ARENA;
372
373     /* The first SV in an arena isn't an SV. */
374     SvANY(sva) = (void *) PL_sv_arenaroot;              /* ptr to next arena */
375     SvREFCNT(sva) = size / sizeof(SV);          /* number of SV slots */
376     SvFLAGS(sva) = flags;                       /* FAKE if not to be freed */
377
378     PL_sv_arenaroot = sva;
379     PL_sv_root = sva + 1;
380
381     svend = &sva[SvREFCNT(sva) - 1];
382     sv = sva + 1;
383     while (sv < svend) {
384         SvARENA_CHAIN_SET(sv, (sv + 1));
385 #ifdef DEBUGGING
386         SvREFCNT(sv) = 0;
387 #endif
388         /* Must always set typemask because it's always checked in on cleanup
389            when the arenas are walked looking for objects.  */
390         SvFLAGS(sv) = SVTYPEMASK;
391         sv++;
392     }
393     SvARENA_CHAIN_SET(sv, 0);
394 #ifdef DEBUGGING
395     SvREFCNT(sv) = 0;
396 #endif
397     SvFLAGS(sv) = SVTYPEMASK;
398 }
399
400 /* visit(): call the named function for each non-free SV in the arenas
401  * whose flags field matches the flags/mask args. */
402
403 STATIC I32
404 S_visit(pTHX_ SVFUNC_t f, const U32 flags, const U32 mask)
405 {
406     dVAR;
407     SV* sva;
408     I32 visited = 0;
409
410     PERL_ARGS_ASSERT_VISIT;
411
412     for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
413         register const SV * const svend = &sva[SvREFCNT(sva)];
414         register SV* sv;
415         for (sv = sva + 1; sv < svend; ++sv) {
416             if (SvTYPE(sv) != SVTYPEMASK
417                     && (sv->sv_flags & mask) == flags
418                     && SvREFCNT(sv))
419             {
420                 (FCALL)(aTHX_ sv);
421                 ++visited;
422             }
423         }
424     }
425     return visited;
426 }
427
428 #ifdef DEBUGGING
429
430 /* called by sv_report_used() for each live SV */
431
432 static void
433 do_report_used(pTHX_ SV *const sv)
434 {
435     if (SvTYPE(sv) != SVTYPEMASK) {
436         PerlIO_printf(Perl_debug_log, "****\n");
437         sv_dump(sv);
438     }
439 }
440 #endif
441
442 /*
443 =for apidoc sv_report_used
444
445 Dump the contents of all SVs not yet freed. (Debugging aid).
446
447 =cut
448 */
449
450 void
451 Perl_sv_report_used(pTHX)
452 {
453 #ifdef DEBUGGING
454     visit(do_report_used, 0, 0);
455 #else
456     PERL_UNUSED_CONTEXT;
457 #endif
458 }
459
460 /* called by sv_clean_objs() for each live SV */
461
462 static void
463 do_clean_objs(pTHX_ SV *const ref)
464 {
465     dVAR;
466     assert (SvROK(ref));
467     {
468         SV * const target = SvRV(ref);
469         if (SvOBJECT(target)) {
470             DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning object ref:\n "), sv_dump(ref)));
471             if (SvWEAKREF(ref)) {
472                 sv_del_backref(target, ref);
473                 SvWEAKREF_off(ref);
474                 SvRV_set(ref, NULL);
475             } else {
476                 SvROK_off(ref);
477                 SvRV_set(ref, NULL);
478                 SvREFCNT_dec(target);
479             }
480         }
481     }
482
483     /* XXX Might want to check arrays, etc. */
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(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(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(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(obj);
527     }
528     SvREFCNT_dec(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(obj);
550     }
551     SvREFCNT_dec(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(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_BIND, 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     /* 8 bytes on most ILP32 with IEEE doubles */
897     { sizeof(NV), sizeof(NV),
898       STRUCT_OFFSET(XPVNV, xnv_u),
899       SVt_NV, FALSE, HADNV, HASARENA, FIT_ARENA(0, sizeof(NV)) },
900
901     /* 8 bytes on most ILP32 with IEEE doubles */
902     { sizeof(XPV) - STRUCT_OFFSET(XPV, xpv_cur),
903       copy_length(XPV, xpv_len) - STRUCT_OFFSET(XPV, xpv_cur),
904       + STRUCT_OFFSET(XPV, xpv_cur),
905       SVt_PV, FALSE, NONV, HASARENA,
906       FIT_ARENA(0, sizeof(XPV) - STRUCT_OFFSET(XPV, xpv_cur)) },
907
908     /* 12 */
909     { sizeof(XPVIV) - STRUCT_OFFSET(XPV, xpv_cur),
910       copy_length(XPVIV, xiv_u) - STRUCT_OFFSET(XPV, xpv_cur),
911       + STRUCT_OFFSET(XPV, xpv_cur),
912       SVt_PVIV, FALSE, NONV, HASARENA,
913       FIT_ARENA(0, sizeof(XPVIV) - STRUCT_OFFSET(XPV, xpv_cur)) },
914
915     /* 20 */
916     { sizeof(XPVNV) - STRUCT_OFFSET(XPV, xpv_cur),
917       copy_length(XPVNV, xnv_u) - STRUCT_OFFSET(XPV, xpv_cur),
918       + STRUCT_OFFSET(XPV, xpv_cur),
919       SVt_PVNV, FALSE, HADNV, HASARENA,
920       FIT_ARENA(0, sizeof(XPVNV) - STRUCT_OFFSET(XPV, xpv_cur)) },
921
922     /* 28 */
923     { sizeof(XPVMG), copy_length(XPVMG, xnv_u), 0, SVt_PVMG, FALSE, HADNV,
924       HASARENA, FIT_ARENA(0, sizeof(XPVMG)) },
925
926     /* something big */
927     { sizeof(regexp),
928       sizeof(regexp),
929       0,
930       SVt_REGEXP, FALSE, NONV, HASARENA,
931       FIT_ARENA(0, sizeof(regexp))
932     },
933
934     /* 48 */
935     { sizeof(XPVGV), sizeof(XPVGV), 0, SVt_PVGV, TRUE, HADNV,
936       HASARENA, FIT_ARENA(0, sizeof(XPVGV)) },
937     
938     /* 64 */
939     { sizeof(XPVLV), sizeof(XPVLV), 0, SVt_PVLV, TRUE, HADNV,
940       HASARENA, FIT_ARENA(0, sizeof(XPVLV)) },
941
942     { sizeof(XPVAV),
943       copy_length(XPVAV, xav_alloc),
944       0,
945       SVt_PVAV, TRUE, NONV, HASARENA,
946       FIT_ARENA(0, sizeof(XPVAV)) },
947
948     { sizeof(XPVHV),
949       copy_length(XPVHV, xhv_max),
950       0,
951       SVt_PVHV, TRUE, NONV, HASARENA,
952       FIT_ARENA(0, sizeof(XPVHV)) },
953
954     /* 56 */
955     { sizeof(XPVCV),
956       sizeof(XPVCV),
957       0,
958       SVt_PVCV, TRUE, NONV, HASARENA,
959       FIT_ARENA(0, sizeof(XPVCV)) },
960
961     { sizeof(XPVFM),
962       sizeof(XPVFM),
963       0,
964       SVt_PVFM, TRUE, NONV, NOARENA,
965       FIT_ARENA(20, sizeof(XPVFM)) },
966
967     /* XPVIO is 84 bytes, fits 48x */
968     { sizeof(XPVIO),
969       sizeof(XPVIO),
970       0,
971       SVt_PVIO, TRUE, NONV, HASARENA,
972       FIT_ARENA(24, sizeof(XPVIO)) },
973 };
974
975 #define new_body_allocated(sv_type)             \
976     (void *)((char *)S_new_body(aTHX_ sv_type)  \
977              - bodies_by_type[sv_type].offset)
978
979 /* return a thing to the free list */
980
981 #define del_body(thing, root)                           \
982     STMT_START {                                        \
983         void ** const thing_copy = (void **)thing;      \
984         *thing_copy = *root;                            \
985         *root = (void*)thing_copy;                      \
986     } STMT_END
987
988 #ifdef PURIFY
989
990 #define new_XNV()       safemalloc(sizeof(XPVNV))
991 #define new_XPVNV()     safemalloc(sizeof(XPVNV))
992 #define new_XPVMG()     safemalloc(sizeof(XPVMG))
993
994 #define del_XPVGV(p)    safefree(p)
995
996 #else /* !PURIFY */
997
998 #define new_XNV()       new_body_allocated(SVt_NV)
999 #define new_XPVNV()     new_body_allocated(SVt_PVNV)
1000 #define new_XPVMG()     new_body_allocated(SVt_PVMG)
1001
1002 #define del_XPVGV(p)    del_body(p + bodies_by_type[SVt_PVGV].offset,   \
1003                                  &PL_body_roots[SVt_PVGV])
1004
1005 #endif /* PURIFY */
1006
1007 /* no arena for you! */
1008
1009 #define new_NOARENA(details) \
1010         safemalloc((details)->body_size + (details)->offset)
1011 #define new_NOARENAZ(details) \
1012         safecalloc((details)->body_size + (details)->offset, 1)
1013
1014 void *
1015 Perl_more_bodies (pTHX_ const svtype sv_type, const size_t body_size,
1016                   const size_t arena_size)
1017 {
1018     dVAR;
1019     void ** const root = &PL_body_roots[sv_type];
1020     struct arena_desc *adesc;
1021     struct arena_set *aroot = (struct arena_set *) PL_body_arenas;
1022     unsigned int curr;
1023     char *start;
1024     const char *end;
1025     const size_t good_arena_size = Perl_malloc_good_size(arena_size);
1026 #if defined(DEBUGGING) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
1027     static bool done_sanity_check;
1028
1029     /* PERL_GLOBAL_STRUCT_PRIVATE cannot coexist with global
1030      * variables like done_sanity_check. */
1031     if (!done_sanity_check) {
1032         unsigned int i = SVt_LAST;
1033
1034         done_sanity_check = TRUE;
1035
1036         while (i--)
1037             assert (bodies_by_type[i].type == i);
1038     }
1039 #endif
1040
1041     assert(arena_size);
1042
1043     /* may need new arena-set to hold new arena */
1044     if (!aroot || aroot->curr >= aroot->set_size) {
1045         struct arena_set *newroot;
1046         Newxz(newroot, 1, struct arena_set);
1047         newroot->set_size = ARENAS_PER_SET;
1048         newroot->next = aroot;
1049         aroot = newroot;
1050         PL_body_arenas = (void *) newroot;
1051         DEBUG_m(PerlIO_printf(Perl_debug_log, "new arenaset %p\n", (void*)aroot));
1052     }
1053
1054     /* ok, now have arena-set with at least 1 empty/available arena-desc */
1055     curr = aroot->curr++;
1056     adesc = &(aroot->set[curr]);
1057     assert(!adesc->arena);
1058     
1059     Newx(adesc->arena, good_arena_size, char);
1060     adesc->size = good_arena_size;
1061     adesc->utype = sv_type;
1062     DEBUG_m(PerlIO_printf(Perl_debug_log, "arena %d added: %p size %"UVuf"\n", 
1063                           curr, (void*)adesc->arena, (UV)good_arena_size));
1064
1065     start = (char *) adesc->arena;
1066
1067     /* Get the address of the byte after the end of the last body we can fit.
1068        Remember, this is integer division:  */
1069     end = start + good_arena_size / body_size * body_size;
1070
1071     /* computed count doesn't reflect the 1st slot reservation */
1072 #if defined(MYMALLOC) || defined(HAS_MALLOC_GOOD_SIZE)
1073     DEBUG_m(PerlIO_printf(Perl_debug_log,
1074                           "arena %p end %p arena-size %d (from %d) type %d "
1075                           "size %d ct %d\n",
1076                           (void*)start, (void*)end, (int)good_arena_size,
1077                           (int)arena_size, sv_type, (int)body_size,
1078                           (int)good_arena_size / (int)body_size));
1079 #else
1080     DEBUG_m(PerlIO_printf(Perl_debug_log,
1081                           "arena %p end %p arena-size %d type %d size %d ct %d\n",
1082                           (void*)start, (void*)end,
1083                           (int)arena_size, sv_type, (int)body_size,
1084                           (int)good_arena_size / (int)body_size));
1085 #endif
1086     *root = (void *)start;
1087
1088     while (1) {
1089         /* Where the next body would start:  */
1090         char * const next = start + body_size;
1091
1092         if (next >= end) {
1093             /* This is the last body:  */
1094             assert(next == end);
1095
1096             *(void **)start = 0;
1097             return *root;
1098         }
1099
1100         *(void**) start = (void *)next;
1101         start = next;
1102     }
1103 }
1104
1105 /* grab a new thing from the free list, allocating more if necessary.
1106    The inline version is used for speed in hot routines, and the
1107    function using it serves the rest (unless PURIFY).
1108 */
1109 #define new_body_inline(xpv, sv_type) \
1110     STMT_START { \
1111         void ** const r3wt = &PL_body_roots[sv_type]; \
1112         xpv = (PTR_TBL_ENT_t*) (*((void **)(r3wt))      \
1113           ? *((void **)(r3wt)) : Perl_more_bodies(aTHX_ sv_type, \
1114                                              bodies_by_type[sv_type].body_size,\
1115                                              bodies_by_type[sv_type].arena_size)); \
1116         *(r3wt) = *(void**)(xpv); \
1117     } STMT_END
1118
1119 #ifndef PURIFY
1120
1121 STATIC void *
1122 S_new_body(pTHX_ const svtype sv_type)
1123 {
1124     dVAR;
1125     void *xpv;
1126     new_body_inline(xpv, sv_type);
1127     return xpv;
1128 }
1129
1130 #endif
1131
1132 static const struct body_details fake_rv =
1133     { 0, 0, 0, SVt_IV, FALSE, NONV, NOARENA, 0 };
1134
1135 /*
1136 =for apidoc sv_upgrade
1137
1138 Upgrade an SV to a more complex form.  Generally adds a new body type to the
1139 SV, then copies across as much information as possible from the old body.
1140 You generally want to use the C<SvUPGRADE> macro wrapper. See also C<svtype>.
1141
1142 =cut
1143 */
1144
1145 void
1146 Perl_sv_upgrade(pTHX_ register SV *const sv, svtype new_type)
1147 {
1148     dVAR;
1149     void*       old_body;
1150     void*       new_body;
1151     const svtype old_type = SvTYPE(sv);
1152     const struct body_details *new_type_details;
1153     const struct body_details *old_type_details
1154         = bodies_by_type + old_type;
1155     SV *referant = NULL;
1156
1157     PERL_ARGS_ASSERT_SV_UPGRADE;
1158
1159     if (old_type == new_type)
1160         return;
1161
1162     /* This clause was purposefully added ahead of the early return above to
1163        the shared string hackery for (sort {$a <=> $b} keys %hash), with the
1164        inference by Nick I-S that it would fix other troublesome cases. See
1165        changes 7162, 7163 (f130fd4589cf5fbb24149cd4db4137c8326f49c1 and parent)
1166
1167        Given that shared hash key scalars are no longer PVIV, but PV, there is
1168        no longer need to unshare so as to free up the IVX slot for its proper
1169        purpose. So it's safe to move the early return earlier.  */
1170
1171     if (new_type != SVt_PV && SvIsCOW(sv)) {
1172         sv_force_normal_flags(sv, 0);
1173     }
1174
1175     old_body = SvANY(sv);
1176
1177     /* Copying structures onto other structures that have been neatly zeroed
1178        has a subtle gotcha. Consider XPVMG
1179
1180        +------+------+------+------+------+-------+-------+
1181        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |
1182        +------+------+------+------+------+-------+-------+
1183        0      4      8     12     16     20      24      28
1184
1185        where NVs are aligned to 8 bytes, so that sizeof that structure is
1186        actually 32 bytes long, with 4 bytes of padding at the end:
1187
1188        +------+------+------+------+------+-------+-------+------+
1189        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH | ???  |
1190        +------+------+------+------+------+-------+-------+------+
1191        0      4      8     12     16     20      24      28     32
1192
1193        so what happens if you allocate memory for this structure:
1194
1195        +------+------+------+------+------+-------+-------+------+------+...
1196        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |  GP  | NAME |
1197        +------+------+------+------+------+-------+-------+------+------+...
1198        0      4      8     12     16     20      24      28     32     36
1199
1200        zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
1201        expect, because you copy the area marked ??? onto GP. Now, ??? may have
1202        started out as zero once, but it's quite possible that it isn't. So now,
1203        rather than a nicely zeroed GP, you have it pointing somewhere random.
1204        Bugs ensue.
1205
1206        (In fact, GP ends up pointing at a previous GP structure, because the
1207        principle cause of the padding in XPVMG getting garbage is a copy of
1208        sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob. Right now
1209        this happens to be moot because XPVGV has been re-ordered, with GP
1210        no longer after STASH)
1211
1212        So we are careful and work out the size of used parts of all the
1213        structures.  */
1214
1215     switch (old_type) {
1216     case SVt_NULL:
1217         break;
1218     case SVt_IV:
1219         if (SvROK(sv)) {
1220             referant = SvRV(sv);
1221             old_type_details = &fake_rv;
1222             if (new_type == SVt_NV)
1223                 new_type = SVt_PVNV;
1224         } else {
1225             if (new_type < SVt_PVIV) {
1226                 new_type = (new_type == SVt_NV)
1227                     ? SVt_PVNV : SVt_PVIV;
1228             }
1229         }
1230         break;
1231     case SVt_NV:
1232         if (new_type < SVt_PVNV) {
1233             new_type = SVt_PVNV;
1234         }
1235         break;
1236     case SVt_PV:
1237         assert(new_type > SVt_PV);
1238         assert(SVt_IV < SVt_PV);
1239         assert(SVt_NV < SVt_PV);
1240         break;
1241     case SVt_PVIV:
1242         break;
1243     case SVt_PVNV:
1244         break;
1245     case SVt_PVMG:
1246         /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1247            there's no way that it can be safely upgraded, because perl.c
1248            expects to Safefree(SvANY(PL_mess_sv))  */
1249         assert(sv != PL_mess_sv);
1250         /* This flag bit is used to mean other things in other scalar types.
1251            Given that it only has meaning inside the pad, it shouldn't be set
1252            on anything that can get upgraded.  */
1253         assert(!SvPAD_TYPED(sv));
1254         break;
1255     default:
1256         if (old_type_details->cant_upgrade)
1257             Perl_croak(aTHX_ "Can't upgrade %s (%" UVuf ") to %" UVuf,
1258                        sv_reftype(sv, 0), (UV) old_type, (UV) new_type);
1259     }
1260
1261     if (old_type > new_type)
1262         Perl_croak(aTHX_ "sv_upgrade from type %d down to type %d",
1263                 (int)old_type, (int)new_type);
1264
1265     new_type_details = bodies_by_type + new_type;
1266
1267     SvFLAGS(sv) &= ~SVTYPEMASK;
1268     SvFLAGS(sv) |= new_type;
1269
1270     /* This can't happen, as SVt_NULL is <= all values of new_type, so one of
1271        the return statements above will have triggered.  */
1272     assert (new_type != SVt_NULL);
1273     switch (new_type) {
1274     case SVt_IV:
1275         assert(old_type == SVt_NULL);
1276         SvANY(sv) = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
1277         SvIV_set(sv, 0);
1278         return;
1279     case SVt_NV:
1280         assert(old_type == SVt_NULL);
1281         SvANY(sv) = new_XNV();
1282         SvNV_set(sv, 0);
1283         return;
1284     case SVt_PVHV:
1285     case SVt_PVAV:
1286         assert(new_type_details->body_size);
1287
1288 #ifndef PURIFY  
1289         assert(new_type_details->arena);
1290         assert(new_type_details->arena_size);
1291         /* This points to the start of the allocated area.  */
1292         new_body_inline(new_body, new_type);
1293         Zero(new_body, new_type_details->body_size, char);
1294         new_body = ((char *)new_body) - new_type_details->offset;
1295 #else
1296         /* We always allocated the full length item with PURIFY. To do this
1297            we fake things so that arena is false for all 16 types..  */
1298         new_body = new_NOARENAZ(new_type_details);
1299 #endif
1300         SvANY(sv) = new_body;
1301         if (new_type == SVt_PVAV) {
1302             AvMAX(sv)   = -1;
1303             AvFILLp(sv) = -1;
1304             AvREAL_only(sv);
1305             if (old_type_details->body_size) {
1306                 AvALLOC(sv) = 0;
1307             } else {
1308                 /* It will have been zeroed when the new body was allocated.
1309                    Lets not write to it, in case it confuses a write-back
1310                    cache.  */
1311             }
1312         } else {
1313             assert(!SvOK(sv));
1314             SvOK_off(sv);
1315 #ifndef NODEFAULT_SHAREKEYS
1316             HvSHAREKEYS_on(sv);         /* key-sharing on by default */
1317 #endif
1318             HvMAX(sv) = 7; /* (start with 8 buckets) */
1319         }
1320
1321         /* SVt_NULL isn't the only thing upgraded to AV or HV.
1322            The target created by newSVrv also is, and it can have magic.
1323            However, it never has SvPVX set.
1324         */
1325         if (old_type == SVt_IV) {
1326             assert(!SvROK(sv));
1327         } else if (old_type >= SVt_PV) {
1328             assert(SvPVX_const(sv) == 0);
1329         }
1330
1331         if (old_type >= SVt_PVMG) {
1332             SvMAGIC_set(sv, ((XPVMG*)old_body)->xmg_u.xmg_magic);
1333             SvSTASH_set(sv, ((XPVMG*)old_body)->xmg_stash);
1334         } else {
1335             sv->sv_u.svu_array = NULL; /* or svu_hash  */
1336         }
1337         break;
1338
1339
1340     case SVt_REGEXP:
1341         /* This ensures that SvTHINKFIRST(sv) is true, and hence that
1342            sv_force_normal_flags(sv) is called.  */
1343         SvFAKE_on(sv);
1344     case SVt_PVIV:
1345         /* XXX Is this still needed?  Was it ever needed?   Surely as there is
1346            no route from NV to PVIV, NOK can never be true  */
1347         assert(!SvNOKp(sv));
1348         assert(!SvNOK(sv));
1349     case SVt_PVIO:
1350     case SVt_PVFM:
1351     case SVt_PVGV:
1352     case SVt_PVCV:
1353     case SVt_PVLV:
1354     case SVt_PVMG:
1355     case SVt_PVNV:
1356     case SVt_PV:
1357
1358         assert(new_type_details->body_size);
1359         /* We always allocated the full length item with PURIFY. To do this
1360            we fake things so that arena is false for all 16 types..  */
1361         if(new_type_details->arena) {
1362             /* This points to the start of the allocated area.  */
1363             new_body_inline(new_body, new_type);
1364             Zero(new_body, new_type_details->body_size, char);
1365             new_body = ((char *)new_body) - new_type_details->offset;
1366         } else {
1367             new_body = new_NOARENAZ(new_type_details);
1368         }
1369         SvANY(sv) = new_body;
1370
1371         if (old_type_details->copy) {
1372             /* There is now the potential for an upgrade from something without
1373                an offset (PVNV or PVMG) to something with one (PVCV, PVFM)  */
1374             int offset = old_type_details->offset;
1375             int length = old_type_details->copy;
1376
1377             if (new_type_details->offset > old_type_details->offset) {
1378                 const int difference
1379                     = new_type_details->offset - old_type_details->offset;
1380                 offset += difference;
1381                 length -= difference;
1382             }
1383             assert (length >= 0);
1384                 
1385             Copy((char *)old_body + offset, (char *)new_body + offset, length,
1386                  char);
1387         }
1388
1389 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1390         /* If NV 0.0 is stores as all bits 0 then Zero() already creates a
1391          * correct 0.0 for us.  Otherwise, if the old body didn't have an
1392          * NV slot, but the new one does, then we need to initialise the
1393          * freshly created NV slot with whatever the correct bit pattern is
1394          * for 0.0  */
1395         if (old_type_details->zero_nv && !new_type_details->zero_nv
1396             && !isGV_with_GP(sv))
1397             SvNV_set(sv, 0);
1398 #endif
1399
1400         if (new_type == SVt_PVIO) {
1401             IO * const io = MUTABLE_IO(sv);
1402             GV *iogv = gv_fetchpvs("IO::File::", GV_ADD, SVt_PVHV);
1403
1404             SvOBJECT_on(io);
1405             /* Clear the stashcache because a new IO could overrule a package
1406                name */
1407             hv_clear(PL_stashcache);
1408
1409             SvSTASH_set(io, MUTABLE_HV(SvREFCNT_inc(GvHV(iogv))));
1410             IoPAGE_LEN(sv) = 60;
1411         }
1412         if (old_type < SVt_PV) {
1413             /* referant will be NULL unless the old type was SVt_IV emulating
1414                SVt_RV */
1415             sv->sv_u.svu_rv = referant;
1416         }
1417         break;
1418     default:
1419         Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu",
1420                    (unsigned long)new_type);
1421     }
1422
1423     if (old_type > SVt_IV) {
1424 #ifdef PURIFY
1425         safefree(old_body);
1426 #else
1427         /* Note that there is an assumption that all bodies of types that
1428            can be upgraded came from arenas. Only the more complex non-
1429            upgradable types are allowed to be directly malloc()ed.  */
1430         assert(old_type_details->arena);
1431         del_body((void*)((char*)old_body + old_type_details->offset),
1432                  &PL_body_roots[old_type]);
1433 #endif
1434     }
1435 }
1436
1437 /*
1438 =for apidoc sv_backoff
1439
1440 Remove any string offset. You should normally use the C<SvOOK_off> macro
1441 wrapper instead.
1442
1443 =cut
1444 */
1445
1446 int
1447 Perl_sv_backoff(pTHX_ register SV *const sv)
1448 {
1449     STRLEN delta;
1450     const char * const s = SvPVX_const(sv);
1451
1452     PERL_ARGS_ASSERT_SV_BACKOFF;
1453     PERL_UNUSED_CONTEXT;
1454
1455     assert(SvOOK(sv));
1456     assert(SvTYPE(sv) != SVt_PVHV);
1457     assert(SvTYPE(sv) != SVt_PVAV);
1458
1459     SvOOK_offset(sv, delta);
1460     
1461     SvLEN_set(sv, SvLEN(sv) + delta);
1462     SvPV_set(sv, SvPVX(sv) - delta);
1463     Move(s, SvPVX(sv), SvCUR(sv)+1, char);
1464     SvFLAGS(sv) &= ~SVf_OOK;
1465     return 0;
1466 }
1467
1468 /*
1469 =for apidoc sv_grow
1470
1471 Expands the character buffer in the SV.  If necessary, uses C<sv_unref> and
1472 upgrades the SV to C<SVt_PV>.  Returns a pointer to the character buffer.
1473 Use the C<SvGROW> wrapper instead.
1474
1475 =cut
1476 */
1477
1478 char *
1479 Perl_sv_grow(pTHX_ register SV *const sv, register STRLEN newlen)
1480 {
1481     register char *s;
1482
1483     PERL_ARGS_ASSERT_SV_GROW;
1484
1485     if (PL_madskills && newlen >= 0x100000) {
1486         PerlIO_printf(Perl_debug_log,
1487                       "Allocation too large: %"UVxf"\n", (UV)newlen);
1488     }
1489 #ifdef HAS_64K_LIMIT
1490     if (newlen >= 0x10000) {
1491         PerlIO_printf(Perl_debug_log,
1492                       "Allocation too large: %"UVxf"\n", (UV)newlen);
1493         my_exit(1);
1494     }
1495 #endif /* HAS_64K_LIMIT */
1496     if (SvROK(sv))
1497         sv_unref(sv);
1498     if (SvTYPE(sv) < SVt_PV) {
1499         sv_upgrade(sv, SVt_PV);
1500         s = SvPVX_mutable(sv);
1501     }
1502     else if (SvOOK(sv)) {       /* pv is offset? */
1503         sv_backoff(sv);
1504         s = SvPVX_mutable(sv);
1505         if (newlen > SvLEN(sv))
1506             newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1507 #ifdef HAS_64K_LIMIT
1508         if (newlen >= 0x10000)
1509             newlen = 0xFFFF;
1510 #endif
1511     }
1512     else
1513         s = SvPVX_mutable(sv);
1514
1515     if (newlen > SvLEN(sv)) {           /* need more room? */
1516         STRLEN minlen = SvCUR(sv);
1517         minlen += (minlen >> PERL_STRLEN_EXPAND_SHIFT) + 10;
1518         if (newlen < minlen)
1519             newlen = minlen;
1520 #ifndef Perl_safesysmalloc_size
1521         newlen = PERL_STRLEN_ROUNDUP(newlen);
1522 #endif
1523         if (SvLEN(sv) && s) {
1524             s = (char*)saferealloc(s, newlen);
1525         }
1526         else {
1527             s = (char*)safemalloc(newlen);
1528             if (SvPVX_const(sv) && SvCUR(sv)) {
1529                 Move(SvPVX_const(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1530             }
1531         }
1532         SvPV_set(sv, s);
1533 #ifdef Perl_safesysmalloc_size
1534         /* Do this here, do it once, do it right, and then we will never get
1535            called back into sv_grow() unless there really is some growing
1536            needed.  */
1537         SvLEN_set(sv, Perl_safesysmalloc_size(s));
1538 #else
1539         SvLEN_set(sv, newlen);
1540 #endif
1541     }
1542     return s;
1543 }
1544
1545 /*
1546 =for apidoc sv_setiv
1547
1548 Copies an integer into the given SV, upgrading first if necessary.
1549 Does not handle 'set' magic.  See also C<sv_setiv_mg>.
1550
1551 =cut
1552 */
1553
1554 void
1555 Perl_sv_setiv(pTHX_ register SV *const sv, const IV i)
1556 {
1557     dVAR;
1558
1559     PERL_ARGS_ASSERT_SV_SETIV;
1560
1561     SV_CHECK_THINKFIRST_COW_DROP(sv);
1562     switch (SvTYPE(sv)) {
1563     case SVt_NULL:
1564     case SVt_NV:
1565         sv_upgrade(sv, SVt_IV);
1566         break;
1567     case SVt_PV:
1568         sv_upgrade(sv, SVt_PVIV);
1569         break;
1570
1571     case SVt_PVGV:
1572         if (!isGV_with_GP(sv))
1573             break;
1574     case SVt_PVAV:
1575     case SVt_PVHV:
1576     case SVt_PVCV:
1577     case SVt_PVFM:
1578     case SVt_PVIO:
1579         /* diag_listed_as: Can't coerce %s to %s in %s */
1580         Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1581                    OP_DESC(PL_op));
1582     default: NOOP;
1583     }
1584     (void)SvIOK_only(sv);                       /* validate number */
1585     SvIV_set(sv, i);
1586     SvTAINT(sv);
1587 }
1588
1589 /*
1590 =for apidoc sv_setiv_mg
1591
1592 Like C<sv_setiv>, but also handles 'set' magic.
1593
1594 =cut
1595 */
1596
1597 void
1598 Perl_sv_setiv_mg(pTHX_ register SV *const sv, const IV i)
1599 {
1600     PERL_ARGS_ASSERT_SV_SETIV_MG;
1601
1602     sv_setiv(sv,i);
1603     SvSETMAGIC(sv);
1604 }
1605
1606 /*
1607 =for apidoc sv_setuv
1608
1609 Copies an unsigned integer into the given SV, upgrading first if necessary.
1610 Does not handle 'set' magic.  See also C<sv_setuv_mg>.
1611
1612 =cut
1613 */
1614
1615 void
1616 Perl_sv_setuv(pTHX_ register SV *const sv, const UV u)
1617 {
1618     PERL_ARGS_ASSERT_SV_SETUV;
1619
1620     /* With these two if statements:
1621        u=1.49  s=0.52  cu=72.49  cs=10.64  scripts=270  tests=20865
1622
1623        without
1624        u=1.35  s=0.47  cu=73.45  cs=11.43  scripts=270  tests=20865
1625
1626        If you wish to remove them, please benchmark to see what the effect is
1627     */
1628     if (u <= (UV)IV_MAX) {
1629        sv_setiv(sv, (IV)u);
1630        return;
1631     }
1632     sv_setiv(sv, 0);
1633     SvIsUV_on(sv);
1634     SvUV_set(sv, u);
1635 }
1636
1637 /*
1638 =for apidoc sv_setuv_mg
1639
1640 Like C<sv_setuv>, but also handles 'set' magic.
1641
1642 =cut
1643 */
1644
1645 void
1646 Perl_sv_setuv_mg(pTHX_ register SV *const sv, const UV u)
1647 {
1648     PERL_ARGS_ASSERT_SV_SETUV_MG;
1649
1650     sv_setuv(sv,u);
1651     SvSETMAGIC(sv);
1652 }
1653
1654 /*
1655 =for apidoc sv_setnv
1656
1657 Copies a double into the given SV, upgrading first if necessary.
1658 Does not handle 'set' magic.  See also C<sv_setnv_mg>.
1659
1660 =cut
1661 */
1662
1663 void
1664 Perl_sv_setnv(pTHX_ register SV *const sv, const NV num)
1665 {
1666     dVAR;
1667
1668     PERL_ARGS_ASSERT_SV_SETNV;
1669
1670     SV_CHECK_THINKFIRST_COW_DROP(sv);
1671     switch (SvTYPE(sv)) {
1672     case SVt_NULL:
1673     case SVt_IV:
1674         sv_upgrade(sv, SVt_NV);
1675         break;
1676     case SVt_PV:
1677     case SVt_PVIV:
1678         sv_upgrade(sv, SVt_PVNV);
1679         break;
1680
1681     case SVt_PVGV:
1682         if (!isGV_with_GP(sv))
1683             break;
1684     case SVt_PVAV:
1685     case SVt_PVHV:
1686     case SVt_PVCV:
1687     case SVt_PVFM:
1688     case SVt_PVIO:
1689         /* diag_listed_as: Can't coerce %s to %s in %s */
1690         Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
1691                    OP_DESC(PL_op));
1692     default: NOOP;
1693     }
1694     SvNV_set(sv, num);
1695     (void)SvNOK_only(sv);                       /* validate number */
1696     SvTAINT(sv);
1697 }
1698
1699 /*
1700 =for apidoc sv_setnv_mg
1701
1702 Like C<sv_setnv>, but also handles 'set' magic.
1703
1704 =cut
1705 */
1706
1707 void
1708 Perl_sv_setnv_mg(pTHX_ register SV *const sv, const NV num)
1709 {
1710     PERL_ARGS_ASSERT_SV_SETNV_MG;
1711
1712     sv_setnv(sv,num);
1713     SvSETMAGIC(sv);
1714 }
1715
1716 /* Print an "isn't numeric" warning, using a cleaned-up,
1717  * printable version of the offending string
1718  */
1719
1720 STATIC void
1721 S_not_a_number(pTHX_ SV *const sv)
1722 {
1723      dVAR;
1724      SV *dsv;
1725      char tmpbuf[64];
1726      const char *pv;
1727
1728      PERL_ARGS_ASSERT_NOT_A_NUMBER;
1729
1730      if (DO_UTF8(sv)) {
1731           dsv = newSVpvs_flags("", SVs_TEMP);
1732           pv = sv_uni_display(dsv, sv, 10, 0);
1733      } else {
1734           char *d = tmpbuf;
1735           const char * const limit = tmpbuf + sizeof(tmpbuf) - 8;
1736           /* each *s can expand to 4 chars + "...\0",
1737              i.e. need room for 8 chars */
1738         
1739           const char *s = SvPVX_const(sv);
1740           const char * const end = s + SvCUR(sv);
1741           for ( ; s < end && d < limit; s++ ) {
1742                int ch = *s & 0xFF;
1743                if (ch & 128 && !isPRINT_LC(ch)) {
1744                     *d++ = 'M';
1745                     *d++ = '-';
1746                     ch &= 127;
1747                }
1748                if (ch == '\n') {
1749                     *d++ = '\\';
1750                     *d++ = 'n';
1751                }
1752                else if (ch == '\r') {
1753                     *d++ = '\\';
1754                     *d++ = 'r';
1755                }
1756                else if (ch == '\f') {
1757                     *d++ = '\\';
1758                     *d++ = 'f';
1759                }
1760                else if (ch == '\\') {
1761                     *d++ = '\\';
1762                     *d++ = '\\';
1763                }
1764                else if (ch == '\0') {
1765                     *d++ = '\\';
1766                     *d++ = '0';
1767                }
1768                else if (isPRINT_LC(ch))
1769                     *d++ = ch;
1770                else {
1771                     *d++ = '^';
1772                     *d++ = toCTRL(ch);
1773                }
1774           }
1775           if (s < end) {
1776                *d++ = '.';
1777                *d++ = '.';
1778                *d++ = '.';
1779           }
1780           *d = '\0';
1781           pv = tmpbuf;
1782     }
1783
1784     if (PL_op)
1785         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1786                     "Argument \"%s\" isn't numeric in %s", pv,
1787                     OP_DESC(PL_op));
1788     else
1789         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1790                     "Argument \"%s\" isn't numeric", pv);
1791 }
1792
1793 /*
1794 =for apidoc looks_like_number
1795
1796 Test if the content of an SV looks like a number (or is a number).
1797 C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1798 non-numeric warning), even if your atof() doesn't grok them.
1799
1800 =cut
1801 */
1802
1803 I32
1804 Perl_looks_like_number(pTHX_ SV *const sv)
1805 {
1806     register const char *sbegin;
1807     STRLEN len;
1808
1809     PERL_ARGS_ASSERT_LOOKS_LIKE_NUMBER;
1810
1811     if (SvPOK(sv)) {
1812         sbegin = SvPVX_const(sv);
1813         len = SvCUR(sv);
1814     }
1815     else if (SvPOKp(sv))
1816         sbegin = SvPV_const(sv, len);
1817     else
1818         return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
1819     return grok_number(sbegin, len, NULL);
1820 }
1821
1822 STATIC bool
1823 S_glob_2number(pTHX_ GV * const gv)
1824 {
1825     const U32 wasfake = SvFLAGS(gv) & SVf_FAKE;
1826     SV *const buffer = sv_newmortal();
1827
1828     PERL_ARGS_ASSERT_GLOB_2NUMBER;
1829
1830     /* FAKE globs can get coerced, so need to turn this off temporarily if it
1831        is on.  */
1832     SvFAKE_off(gv);
1833     gv_efullname3(buffer, gv, "*");
1834     SvFLAGS(gv) |= wasfake;
1835
1836     /* We know that all GVs stringify to something that is not-a-number,
1837         so no need to test that.  */
1838     if (ckWARN(WARN_NUMERIC))
1839         not_a_number(buffer);
1840     /* We just want something true to return, so that S_sv_2iuv_common
1841         can tail call us and return true.  */
1842     return TRUE;
1843 }
1844
1845 /* Actually, ISO C leaves conversion of UV to IV undefined, but
1846    until proven guilty, assume that things are not that bad... */
1847
1848 /*
1849    NV_PRESERVES_UV:
1850
1851    As 64 bit platforms often have an NV that doesn't preserve all bits of
1852    an IV (an assumption perl has been based on to date) it becomes necessary
1853    to remove the assumption that the NV always carries enough precision to
1854    recreate the IV whenever needed, and that the NV is the canonical form.
1855    Instead, IV/UV and NV need to be given equal rights. So as to not lose
1856    precision as a side effect of conversion (which would lead to insanity
1857    and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1858    1) to distinguish between IV/UV/NV slots that have cached a valid
1859       conversion where precision was lost and IV/UV/NV slots that have a
1860       valid conversion which has lost no precision
1861    2) to ensure that if a numeric conversion to one form is requested that
1862       would lose precision, the precise conversion (or differently
1863       imprecise conversion) is also performed and cached, to prevent
1864       requests for different numeric formats on the same SV causing
1865       lossy conversion chains. (lossless conversion chains are perfectly
1866       acceptable (still))
1867
1868
1869    flags are used:
1870    SvIOKp is true if the IV slot contains a valid value
1871    SvIOK  is true only if the IV value is accurate (UV if SvIOK_UV true)
1872    SvNOKp is true if the NV slot contains a valid value
1873    SvNOK  is true only if the NV value is accurate
1874
1875    so
1876    while converting from PV to NV, check to see if converting that NV to an
1877    IV(or UV) would lose accuracy over a direct conversion from PV to
1878    IV(or UV). If it would, cache both conversions, return NV, but mark
1879    SV as IOK NOKp (ie not NOK).
1880
1881    While converting from PV to IV, check to see if converting that IV to an
1882    NV would lose accuracy over a direct conversion from PV to NV. If it
1883    would, cache both conversions, flag similarly.
1884
1885    Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1886    correctly because if IV & NV were set NV *always* overruled.
1887    Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1888    changes - now IV and NV together means that the two are interchangeable:
1889    SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
1890
1891    The benefit of this is that operations such as pp_add know that if
1892    SvIOK is true for both left and right operands, then integer addition
1893    can be used instead of floating point (for cases where the result won't
1894    overflow). Before, floating point was always used, which could lead to
1895    loss of precision compared with integer addition.
1896
1897    * making IV and NV equal status should make maths accurate on 64 bit
1898      platforms
1899    * may speed up maths somewhat if pp_add and friends start to use
1900      integers when possible instead of fp. (Hopefully the overhead in
1901      looking for SvIOK and checking for overflow will not outweigh the
1902      fp to integer speedup)
1903    * will slow down integer operations (callers of SvIV) on "inaccurate"
1904      values, as the change from SvIOK to SvIOKp will cause a call into
1905      sv_2iv each time rather than a macro access direct to the IV slot
1906    * should speed up number->string conversion on integers as IV is
1907      favoured when IV and NV are equally accurate
1908
1909    ####################################################################
1910    You had better be using SvIOK_notUV if you want an IV for arithmetic:
1911    SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
1912    On the other hand, SvUOK is true iff UV.
1913    ####################################################################
1914
1915    Your mileage will vary depending your CPU's relative fp to integer
1916    performance ratio.
1917 */
1918
1919 #ifndef NV_PRESERVES_UV
1920 #  define IS_NUMBER_UNDERFLOW_IV 1
1921 #  define IS_NUMBER_UNDERFLOW_UV 2
1922 #  define IS_NUMBER_IV_AND_UV    2
1923 #  define IS_NUMBER_OVERFLOW_IV  4
1924 #  define IS_NUMBER_OVERFLOW_UV  5
1925
1926 /* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
1927
1928 /* For sv_2nv these three cases are "SvNOK and don't bother casting"  */
1929 STATIC int
1930 S_sv_2iuv_non_preserve(pTHX_ register SV *const sv
1931 #  ifdef DEBUGGING
1932                        , I32 numtype
1933 #  endif
1934                        )
1935 {
1936     dVAR;
1937
1938     PERL_ARGS_ASSERT_SV_2IUV_NON_PRESERVE;
1939
1940     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));
1941     if (SvNVX(sv) < (NV)IV_MIN) {
1942         (void)SvIOKp_on(sv);
1943         (void)SvNOK_on(sv);
1944         SvIV_set(sv, IV_MIN);
1945         return IS_NUMBER_UNDERFLOW_IV;
1946     }
1947     if (SvNVX(sv) > (NV)UV_MAX) {
1948         (void)SvIOKp_on(sv);
1949         (void)SvNOK_on(sv);
1950         SvIsUV_on(sv);
1951         SvUV_set(sv, UV_MAX);
1952         return IS_NUMBER_OVERFLOW_UV;
1953     }
1954     (void)SvIOKp_on(sv);
1955     (void)SvNOK_on(sv);
1956     /* Can't use strtol etc to convert this string.  (See truth table in
1957        sv_2iv  */
1958     if (SvNVX(sv) <= (UV)IV_MAX) {
1959         SvIV_set(sv, I_V(SvNVX(sv)));
1960         if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
1961             SvIOK_on(sv); /* Integer is precise. NOK, IOK */
1962         } else {
1963             /* Integer is imprecise. NOK, IOKp */
1964         }
1965         return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
1966     }
1967     SvIsUV_on(sv);
1968     SvUV_set(sv, U_V(SvNVX(sv)));
1969     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
1970         if (SvUVX(sv) == UV_MAX) {
1971             /* As we know that NVs don't preserve UVs, UV_MAX cannot
1972                possibly be preserved by NV. Hence, it must be overflow.
1973                NOK, IOKp */
1974             return IS_NUMBER_OVERFLOW_UV;
1975         }
1976         SvIOK_on(sv); /* Integer is precise. NOK, UOK */
1977     } else {
1978         /* Integer is imprecise. NOK, IOKp */
1979     }
1980     return IS_NUMBER_OVERFLOW_IV;
1981 }
1982 #endif /* !NV_PRESERVES_UV*/
1983
1984 STATIC bool
1985 S_sv_2iuv_common(pTHX_ SV *const sv)
1986 {
1987     dVAR;
1988
1989     PERL_ARGS_ASSERT_SV_2IUV_COMMON;
1990
1991     if (SvNOKp(sv)) {
1992         /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
1993          * without also getting a cached IV/UV from it at the same time
1994          * (ie PV->NV conversion should detect loss of accuracy and cache
1995          * IV or UV at same time to avoid this. */
1996         /* IV-over-UV optimisation - choose to cache IV if possible */
1997
1998         if (SvTYPE(sv) == SVt_NV)
1999             sv_upgrade(sv, SVt_PVNV);
2000
2001         (void)SvIOKp_on(sv);    /* Must do this first, to clear any SvOOK */
2002         /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
2003            certainly cast into the IV range at IV_MAX, whereas the correct
2004            answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
2005            cases go to UV */
2006 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
2007         if (Perl_isnan(SvNVX(sv))) {
2008             SvUV_set(sv, 0);
2009             SvIsUV_on(sv);
2010             return FALSE;
2011         }
2012 #endif
2013         if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2014             SvIV_set(sv, I_V(SvNVX(sv)));
2015             if (SvNVX(sv) == (NV) SvIVX(sv)
2016 #ifndef NV_PRESERVES_UV
2017                 && (((UV)1 << NV_PRESERVES_UV_BITS) >
2018                     (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2019                 /* Don't flag it as "accurately an integer" if the number
2020                    came from a (by definition imprecise) NV operation, and
2021                    we're outside the range of NV integer precision */
2022 #endif
2023                 ) {
2024                 if (SvNOK(sv))
2025                     SvIOK_on(sv);  /* Can this go wrong with rounding? NWC */
2026                 else {
2027                     /* scalar has trailing garbage, eg "42a" */
2028                 }
2029                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2030                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
2031                                       PTR2UV(sv),
2032                                       SvNVX(sv),
2033                                       SvIVX(sv)));
2034
2035             } else {
2036                 /* IV not precise.  No need to convert from PV, as NV
2037                    conversion would already have cached IV if it detected
2038                    that PV->IV would be better than PV->NV->IV
2039                    flags already correct - don't set public IOK.  */
2040                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2041                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
2042                                       PTR2UV(sv),
2043                                       SvNVX(sv),
2044                                       SvIVX(sv)));
2045             }
2046             /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2047                but the cast (NV)IV_MIN rounds to a the value less (more
2048                negative) than IV_MIN which happens to be equal to SvNVX ??
2049                Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2050                NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2051                (NV)UVX == NVX are both true, but the values differ. :-(
2052                Hopefully for 2s complement IV_MIN is something like
2053                0x8000000000000000 which will be exact. NWC */
2054         }
2055         else {
2056             SvUV_set(sv, U_V(SvNVX(sv)));
2057             if (
2058                 (SvNVX(sv) == (NV) SvUVX(sv))
2059 #ifndef  NV_PRESERVES_UV
2060                 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2061                 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2062                 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2063                 /* Don't flag it as "accurately an integer" if the number
2064                    came from a (by definition imprecise) NV operation, and
2065                    we're outside the range of NV integer precision */
2066 #endif
2067                 && SvNOK(sv)
2068                 )
2069                 SvIOK_on(sv);
2070             SvIsUV_on(sv);
2071             DEBUG_c(PerlIO_printf(Perl_debug_log,
2072                                   "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
2073                                   PTR2UV(sv),
2074                                   SvUVX(sv),
2075                                   SvUVX(sv)));
2076         }
2077     }
2078     else if (SvPOKp(sv) && SvLEN(sv)) {
2079         UV value;
2080         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2081         /* We want to avoid a possible problem when we cache an IV/ a UV which
2082            may be later translated to an NV, and the resulting NV is not
2083            the same as the direct translation of the initial string
2084            (eg 123.456 can shortcut to the IV 123 with atol(), but we must
2085            be careful to ensure that the value with the .456 is around if the
2086            NV value is requested in the future).
2087         
2088            This means that if we cache such an IV/a UV, we need to cache the
2089            NV as well.  Moreover, we trade speed for space, and do not
2090            cache the NV if we are sure it's not needed.
2091          */
2092
2093         /* SVt_PVNV is one higher than SVt_PVIV, hence this order  */
2094         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2095              == IS_NUMBER_IN_UV) {
2096             /* It's definitely an integer, only upgrade to PVIV */
2097             if (SvTYPE(sv) < SVt_PVIV)
2098                 sv_upgrade(sv, SVt_PVIV);
2099             (void)SvIOK_on(sv);
2100         } else if (SvTYPE(sv) < SVt_PVNV)
2101             sv_upgrade(sv, SVt_PVNV);
2102
2103         /* If NVs preserve UVs then we only use the UV value if we know that
2104            we aren't going to call atof() below. If NVs don't preserve UVs
2105            then the value returned may have more precision than atof() will
2106            return, even though value isn't perfectly accurate.  */
2107         if ((numtype & (IS_NUMBER_IN_UV
2108 #ifdef NV_PRESERVES_UV
2109                         | IS_NUMBER_NOT_INT
2110 #endif
2111             )) == IS_NUMBER_IN_UV) {
2112             /* This won't turn off the public IOK flag if it was set above  */
2113             (void)SvIOKp_on(sv);
2114
2115             if (!(numtype & IS_NUMBER_NEG)) {
2116                 /* positive */;
2117                 if (value <= (UV)IV_MAX) {
2118                     SvIV_set(sv, (IV)value);
2119                 } else {
2120                     /* it didn't overflow, and it was positive. */
2121                     SvUV_set(sv, value);
2122                     SvIsUV_on(sv);
2123                 }
2124             } else {
2125                 /* 2s complement assumption  */
2126                 if (value <= (UV)IV_MIN) {
2127                     SvIV_set(sv, -(IV)value);
2128                 } else {
2129                     /* Too negative for an IV.  This is a double upgrade, but
2130                        I'm assuming it will be rare.  */
2131                     if (SvTYPE(sv) < SVt_PVNV)
2132                         sv_upgrade(sv, SVt_PVNV);
2133                     SvNOK_on(sv);
2134                     SvIOK_off(sv);
2135                     SvIOKp_on(sv);
2136                     SvNV_set(sv, -(NV)value);
2137                     SvIV_set(sv, IV_MIN);
2138                 }
2139             }
2140         }
2141         /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2142            will be in the previous block to set the IV slot, and the next
2143            block to set the NV slot.  So no else here.  */
2144         
2145         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2146             != IS_NUMBER_IN_UV) {
2147             /* It wasn't an (integer that doesn't overflow the UV). */
2148             SvNV_set(sv, Atof(SvPVX_const(sv)));
2149
2150             if (! numtype && ckWARN(WARN_NUMERIC))
2151                 not_a_number(sv);
2152
2153 #if defined(USE_LONG_DOUBLE)
2154             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" PERL_PRIgldbl ")\n",
2155                                   PTR2UV(sv), SvNVX(sv)));
2156 #else
2157             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"NVgf")\n",
2158                                   PTR2UV(sv), SvNVX(sv)));
2159 #endif
2160
2161 #ifdef NV_PRESERVES_UV
2162             (void)SvIOKp_on(sv);
2163             (void)SvNOK_on(sv);
2164             if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2165                 SvIV_set(sv, I_V(SvNVX(sv)));
2166                 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2167                     SvIOK_on(sv);
2168                 } else {
2169                     NOOP;  /* Integer is imprecise. NOK, IOKp */
2170                 }
2171                 /* UV will not work better than IV */
2172             } else {
2173                 if (SvNVX(sv) > (NV)UV_MAX) {
2174                     SvIsUV_on(sv);
2175                     /* Integer is inaccurate. NOK, IOKp, is UV */
2176                     SvUV_set(sv, UV_MAX);
2177                 } else {
2178                     SvUV_set(sv, U_V(SvNVX(sv)));
2179                     /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2180                        NV preservse UV so can do correct comparison.  */
2181                     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2182                         SvIOK_on(sv);
2183                     } else {
2184                         NOOP;   /* Integer is imprecise. NOK, IOKp, is UV */
2185                     }
2186                 }
2187                 SvIsUV_on(sv);
2188             }
2189 #else /* NV_PRESERVES_UV */
2190             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2191                 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2192                 /* The IV/UV slot will have been set from value returned by
2193                    grok_number above.  The NV slot has just been set using
2194                    Atof.  */
2195                 SvNOK_on(sv);
2196                 assert (SvIOKp(sv));
2197             } else {
2198                 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2199                     U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2200                     /* Small enough to preserve all bits. */
2201                     (void)SvIOKp_on(sv);
2202                     SvNOK_on(sv);
2203                     SvIV_set(sv, I_V(SvNVX(sv)));
2204                     if ((NV)(SvIVX(sv)) == SvNVX(sv))
2205                         SvIOK_on(sv);
2206                     /* Assumption: first non-preserved integer is < IV_MAX,
2207                        this NV is in the preserved range, therefore: */
2208                     if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2209                           < (UV)IV_MAX)) {
2210                         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);
2211                     }
2212                 } else {
2213                     /* IN_UV NOT_INT
2214                          0      0       already failed to read UV.
2215                          0      1       already failed to read UV.
2216                          1      0       you won't get here in this case. IV/UV
2217                                         slot set, public IOK, Atof() unneeded.
2218                          1      1       already read UV.
2219                        so there's no point in sv_2iuv_non_preserve() attempting
2220                        to use atol, strtol, strtoul etc.  */
2221 #  ifdef DEBUGGING
2222                     sv_2iuv_non_preserve (sv, numtype);
2223 #  else
2224                     sv_2iuv_non_preserve (sv);
2225 #  endif
2226                 }
2227             }
2228 #endif /* NV_PRESERVES_UV */
2229         /* It might be more code efficient to go through the entire logic above
2230            and conditionally set with SvIOKp_on() rather than SvIOK(), but it
2231            gets complex and potentially buggy, so more programmer efficient
2232            to do it this way, by turning off the public flags:  */
2233         if (!numtype)
2234             SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2235         }
2236     }
2237     else  {
2238         if (isGV_with_GP(sv))
2239             return glob_2number(MUTABLE_GV(sv));
2240
2241         if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2242             if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2243                 report_uninit(sv);
2244         }
2245         if (SvTYPE(sv) < SVt_IV)
2246             /* Typically the caller expects that sv_any is not NULL now.  */
2247             sv_upgrade(sv, SVt_IV);
2248         /* Return 0 from the caller.  */
2249         return TRUE;
2250     }
2251     return FALSE;
2252 }
2253
2254 /*
2255 =for apidoc sv_2iv_flags
2256
2257 Return the integer value of an SV, doing any necessary string
2258 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2259 Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2260
2261 =cut
2262 */
2263
2264 IV
2265 Perl_sv_2iv_flags(pTHX_ register SV *const sv, const I32 flags)
2266 {
2267     dVAR;
2268     if (!sv)
2269         return 0;
2270     if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2271         /* FBMs use the same flag bit as SVf_IVisUV, so must let them
2272            cache IVs just in case. In practice it seems that they never
2273            actually anywhere accessible by user Perl code, let alone get used
2274            in anything other than a string context.  */
2275         if (flags & SV_GMAGIC)
2276             mg_get(sv);
2277         if (SvIOKp(sv))
2278             return SvIVX(sv);
2279         if (SvNOKp(sv)) {
2280             return I_V(SvNVX(sv));
2281         }
2282         if (SvPOKp(sv) && SvLEN(sv)) {
2283             UV value;
2284             const int numtype
2285                 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2286
2287             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2288                 == IS_NUMBER_IN_UV) {
2289                 /* It's definitely an integer */
2290                 if (numtype & IS_NUMBER_NEG) {
2291                     if (value < (UV)IV_MIN)
2292                         return -(IV)value;
2293                 } else {
2294                     if (value < (UV)IV_MAX)
2295                         return (IV)value;
2296                 }
2297             }
2298             if (!numtype) {
2299                 if (ckWARN(WARN_NUMERIC))
2300                     not_a_number(sv);
2301             }
2302             return I_V(Atof(SvPVX_const(sv)));
2303         }
2304         if (SvROK(sv)) {
2305             goto return_rok;
2306         }
2307         assert(SvTYPE(sv) >= SVt_PVMG);
2308         /* This falls through to the report_uninit inside S_sv_2iuv_common.  */
2309     } else if (SvTHINKFIRST(sv)) {
2310         if (SvROK(sv)) {
2311         return_rok:
2312             if (SvAMAGIC(sv)) {
2313                 SV * tmpstr;
2314                 if (flags & SV_SKIP_OVERLOAD)
2315                     return 0;
2316                 tmpstr = AMG_CALLunary(sv, numer_amg);
2317                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2318                     return SvIV(tmpstr);
2319                 }
2320             }
2321             return PTR2IV(SvRV(sv));
2322         }
2323         if (SvIsCOW(sv)) {
2324             sv_force_normal_flags(sv, 0);
2325         }
2326         if (SvREADONLY(sv) && !SvOK(sv)) {
2327             if (ckWARN(WARN_UNINITIALIZED))
2328                 report_uninit(sv);
2329             return 0;
2330         }
2331     }
2332     if (!SvIOKp(sv)) {
2333         if (S_sv_2iuv_common(aTHX_ sv))
2334             return 0;
2335     }
2336     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2337         PTR2UV(sv),SvIVX(sv)));
2338     return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
2339 }
2340
2341 /*
2342 =for apidoc sv_2uv_flags
2343
2344 Return the unsigned integer value of an SV, doing any necessary string
2345 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2346 Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
2347
2348 =cut
2349 */
2350
2351 UV
2352 Perl_sv_2uv_flags(pTHX_ register SV *const sv, const I32 flags)
2353 {
2354     dVAR;
2355     if (!sv)
2356         return 0;
2357     if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2358         /* FBMs use the same flag bit as SVf_IVisUV, so must let them
2359            cache IVs just in case.  */
2360         if (flags & SV_GMAGIC)
2361             mg_get(sv);
2362         if (SvIOKp(sv))
2363             return SvUVX(sv);
2364         if (SvNOKp(sv))
2365             return U_V(SvNVX(sv));
2366         if (SvPOKp(sv) && SvLEN(sv)) {
2367             UV value;
2368             const int numtype
2369                 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2370
2371             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2372                 == IS_NUMBER_IN_UV) {
2373                 /* It's definitely an integer */
2374                 if (!(numtype & IS_NUMBER_NEG))
2375                     return value;
2376             }
2377             if (!numtype) {
2378                 if (ckWARN(WARN_NUMERIC))
2379                     not_a_number(sv);
2380             }
2381             return U_V(Atof(SvPVX_const(sv)));
2382         }
2383         if (SvROK(sv)) {
2384             goto return_rok;
2385         }
2386         assert(SvTYPE(sv) >= SVt_PVMG);
2387         /* This falls through to the report_uninit inside S_sv_2iuv_common.  */
2388     } else if (SvTHINKFIRST(sv)) {
2389         if (SvROK(sv)) {
2390         return_rok:
2391             if (SvAMAGIC(sv)) {
2392                 SV *tmpstr;
2393                 if (flags & SV_SKIP_OVERLOAD)
2394                     return 0;
2395                 tmpstr = AMG_CALLunary(sv, numer_amg);
2396                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2397                     return SvUV(tmpstr);
2398                 }
2399             }
2400             return PTR2UV(SvRV(sv));
2401         }
2402         if (SvIsCOW(sv)) {
2403             sv_force_normal_flags(sv, 0);
2404         }
2405         if (SvREADONLY(sv) && !SvOK(sv)) {
2406             if (ckWARN(WARN_UNINITIALIZED))
2407                 report_uninit(sv);
2408             return 0;
2409         }
2410     }
2411     if (!SvIOKp(sv)) {
2412         if (S_sv_2iuv_common(aTHX_ sv))
2413             return 0;
2414     }
2415
2416     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2417                           PTR2UV(sv),SvUVX(sv)));
2418     return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
2419 }
2420
2421 /*
2422 =for apidoc sv_2nv_flags
2423
2424 Return the num value of an SV, doing any necessary string or integer
2425 conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2426 Normally used via the C<SvNV(sv)> and C<SvNVx(sv)> macros.
2427
2428 =cut
2429 */
2430
2431 NV
2432 Perl_sv_2nv_flags(pTHX_ register SV *const sv, const I32 flags)
2433 {
2434     dVAR;
2435     if (!sv)
2436         return 0.0;
2437     if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2438         /* FBMs use the same flag bit as SVf_IVisUV, so must let them
2439            cache IVs just in case.  */
2440         if (flags & SV_GMAGIC)
2441             mg_get(sv);
2442         if (SvNOKp(sv))
2443             return SvNVX(sv);
2444         if ((SvPOKp(sv) && SvLEN(sv)) && !SvIOKp(sv)) {
2445             if (!SvIOKp(sv) && ckWARN(WARN_NUMERIC) &&
2446                 !grok_number(SvPVX_const(sv), SvCUR(sv), NULL))
2447                 not_a_number(sv);
2448             return Atof(SvPVX_const(sv));
2449         }
2450         if (SvIOKp(sv)) {
2451             if (SvIsUV(sv))
2452                 return (NV)SvUVX(sv);
2453             else
2454                 return (NV)SvIVX(sv);
2455         }
2456         if (SvROK(sv)) {
2457             goto return_rok;
2458         }
2459         assert(SvTYPE(sv) >= SVt_PVMG);
2460         /* This falls through to the report_uninit near the end of the
2461            function. */
2462     } else if (SvTHINKFIRST(sv)) {
2463         if (SvROK(sv)) {
2464         return_rok:
2465             if (SvAMAGIC(sv)) {
2466                 SV *tmpstr;
2467                 if (flags & SV_SKIP_OVERLOAD)
2468                     return 0;
2469                 tmpstr = AMG_CALLunary(sv, numer_amg);
2470                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2471                     return SvNV(tmpstr);
2472                 }
2473             }
2474             return PTR2NV(SvRV(sv));
2475         }
2476         if (SvIsCOW(sv)) {
2477             sv_force_normal_flags(sv, 0);
2478         }
2479         if (SvREADONLY(sv) && !SvOK(sv)) {
2480             if (ckWARN(WARN_UNINITIALIZED))
2481                 report_uninit(sv);
2482             return 0.0;
2483         }
2484     }
2485     if (SvTYPE(sv) < SVt_NV) {
2486         /* The logic to use SVt_PVNV if necessary is in sv_upgrade.  */
2487         sv_upgrade(sv, SVt_NV);
2488 #ifdef USE_LONG_DOUBLE
2489         DEBUG_c({
2490             STORE_NUMERIC_LOCAL_SET_STANDARD();
2491             PerlIO_printf(Perl_debug_log,
2492                           "0x%"UVxf" num(%" PERL_PRIgldbl ")\n",
2493                           PTR2UV(sv), SvNVX(sv));
2494             RESTORE_NUMERIC_LOCAL();
2495         });
2496 #else
2497         DEBUG_c({
2498             STORE_NUMERIC_LOCAL_SET_STANDARD();
2499             PerlIO_printf(Perl_debug_log, "0x%"UVxf" num(%"NVgf")\n",
2500                           PTR2UV(sv), SvNVX(sv));
2501             RESTORE_NUMERIC_LOCAL();
2502         });
2503 #endif
2504     }
2505     else if (SvTYPE(sv) < SVt_PVNV)
2506         sv_upgrade(sv, SVt_PVNV);
2507     if (SvNOKp(sv)) {
2508         return SvNVX(sv);
2509     }
2510     if (SvIOKp(sv)) {
2511         SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
2512 #ifdef NV_PRESERVES_UV
2513         if (SvIOK(sv))
2514             SvNOK_on(sv);
2515         else
2516             SvNOKp_on(sv);
2517 #else
2518         /* Only set the public NV OK flag if this NV preserves the IV  */
2519         /* Check it's not 0xFFFFFFFFFFFFFFFF */
2520         if (SvIOK(sv) &&
2521             SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
2522                        : (SvIVX(sv) == I_V(SvNVX(sv))))
2523             SvNOK_on(sv);
2524         else
2525             SvNOKp_on(sv);
2526 #endif
2527     }
2528     else if (SvPOKp(sv) && SvLEN(sv)) {
2529         UV value;
2530         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2531         if (!SvIOKp(sv) && !numtype && ckWARN(WARN_NUMERIC))
2532             not_a_number(sv);
2533 #ifdef NV_PRESERVES_UV
2534         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2535             == IS_NUMBER_IN_UV) {
2536             /* It's definitely an integer */
2537             SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
2538         } else
2539             SvNV_set(sv, Atof(SvPVX_const(sv)));
2540         if (numtype)
2541             SvNOK_on(sv);
2542         else
2543             SvNOKp_on(sv);
2544 #else
2545         SvNV_set(sv, Atof(SvPVX_const(sv)));
2546         /* Only set the public NV OK flag if this NV preserves the value in
2547            the PV at least as well as an IV/UV would.
2548            Not sure how to do this 100% reliably. */
2549         /* if that shift count is out of range then Configure's test is
2550            wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2551            UV_BITS */
2552         if (((UV)1 << NV_PRESERVES_UV_BITS) >
2553             U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2554             SvNOK_on(sv); /* Definitely small enough to preserve all bits */
2555         } else if (!(numtype & IS_NUMBER_IN_UV)) {
2556             /* Can't use strtol etc to convert this string, so don't try.
2557                sv_2iv and sv_2uv will use the NV to convert, not the PV.  */
2558             SvNOK_on(sv);
2559         } else {
2560             /* value has been set.  It may not be precise.  */
2561             if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2562                 /* 2s complement assumption for (UV)IV_MIN  */
2563                 SvNOK_on(sv); /* Integer is too negative.  */
2564             } else {
2565                 SvNOKp_on(sv);
2566                 SvIOKp_on(sv);
2567
2568                 if (numtype & IS_NUMBER_NEG) {
2569                     SvIV_set(sv, -(IV)value);
2570                 } else if (value <= (UV)IV_MAX) {
2571                     SvIV_set(sv, (IV)value);
2572                 } else {
2573                     SvUV_set(sv, value);
2574                     SvIsUV_on(sv);
2575                 }
2576
2577                 if (numtype & IS_NUMBER_NOT_INT) {
2578                     /* I believe that even if the original PV had decimals,
2579                        they are lost beyond the limit of the FP precision.
2580                        However, neither is canonical, so both only get p
2581                        flags.  NWC, 2000/11/25 */
2582                     /* Both already have p flags, so do nothing */
2583                 } else {
2584                     const NV nv = SvNVX(sv);
2585                     if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2586                         if (SvIVX(sv) == I_V(nv)) {
2587                             SvNOK_on(sv);
2588                         } else {
2589                             /* It had no "." so it must be integer.  */
2590                         }
2591                         SvIOK_on(sv);
2592                     } else {
2593                         /* between IV_MAX and NV(UV_MAX).
2594                            Could be slightly > UV_MAX */
2595
2596                         if (numtype & IS_NUMBER_NOT_INT) {
2597                             /* UV and NV both imprecise.  */
2598                         } else {
2599                             const UV nv_as_uv = U_V(nv);
2600
2601                             if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2602                                 SvNOK_on(sv);
2603                             }
2604                             SvIOK_on(sv);
2605                         }
2606                     }
2607                 }
2608             }
2609         }
2610         /* It might be more code efficient to go through the entire logic above
2611            and conditionally set with SvNOKp_on() rather than SvNOK(), but it
2612            gets complex and potentially buggy, so more programmer efficient
2613            to do it this way, by turning off the public flags:  */
2614         if (!numtype)
2615             SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2616 #endif /* NV_PRESERVES_UV */
2617     }
2618     else  {
2619         if (isGV_with_GP(sv)) {
2620             glob_2number(MUTABLE_GV(sv));
2621             return 0.0;
2622         }
2623
2624         if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
2625             report_uninit(sv);
2626         assert (SvTYPE(sv) >= SVt_NV);
2627         /* Typically the caller expects that sv_any is not NULL now.  */
2628         /* XXX Ilya implies that this is a bug in callers that assume this
2629            and ideally should be fixed.  */
2630         return 0.0;
2631     }
2632 #if defined(USE_LONG_DOUBLE)
2633     DEBUG_c({
2634         STORE_NUMERIC_LOCAL_SET_STANDARD();
2635         PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" PERL_PRIgldbl ")\n",
2636                       PTR2UV(sv), SvNVX(sv));
2637         RESTORE_NUMERIC_LOCAL();
2638     });
2639 #else
2640     DEBUG_c({
2641         STORE_NUMERIC_LOCAL_SET_STANDARD();
2642         PerlIO_printf(Perl_debug_log, "0x%"UVxf" 1nv(%"NVgf")\n",
2643                       PTR2UV(sv), SvNVX(sv));
2644         RESTORE_NUMERIC_LOCAL();
2645     });
2646 #endif
2647     return SvNVX(sv);
2648 }
2649
2650 /*
2651 =for apidoc sv_2num
2652
2653 Return an SV with the numeric value of the source SV, doing any necessary
2654 reference or overload conversion.  You must use the C<SvNUM(sv)> macro to
2655 access this function.
2656
2657 =cut
2658 */
2659
2660 SV *
2661 Perl_sv_2num(pTHX_ register SV *const sv)
2662 {
2663     PERL_ARGS_ASSERT_SV_2NUM;
2664
2665     if (!SvROK(sv))
2666         return sv;
2667     if (SvAMAGIC(sv)) {
2668         SV * const tmpsv = AMG_CALLunary(sv, numer_amg);
2669         TAINT_IF(tmpsv && SvTAINTED(tmpsv));
2670         if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
2671             return sv_2num(tmpsv);
2672     }
2673     return sv_2mortal(newSVuv(PTR2UV(SvRV(sv))));
2674 }
2675
2676 /* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2677  * UV as a string towards the end of buf, and return pointers to start and
2678  * end of it.
2679  *
2680  * We assume that buf is at least TYPE_CHARS(UV) long.
2681  */
2682
2683 static char *
2684 S_uiv_2buf(char *const buf, const IV iv, UV uv, const int is_uv, char **const peob)
2685 {
2686     char *ptr = buf + TYPE_CHARS(UV);
2687     char * const ebuf = ptr;
2688     int sign;
2689
2690     PERL_ARGS_ASSERT_UIV_2BUF;
2691
2692     if (is_uv)
2693         sign = 0;
2694     else if (iv >= 0) {
2695         uv = iv;
2696         sign = 0;
2697     } else {
2698         uv = -iv;
2699         sign = 1;
2700     }
2701     do {
2702         *--ptr = '0' + (char)(uv % 10);
2703     } while (uv /= 10);
2704     if (sign)
2705         *--ptr = '-';
2706     *peob = ebuf;
2707     return ptr;
2708 }
2709
2710 /*
2711 =for apidoc sv_2pv_flags
2712
2713 Returns a pointer to the string value of an SV, and sets *lp to its length.
2714 If flags includes SV_GMAGIC, does an mg_get() first. Coerces sv to a string
2715 if necessary.
2716 Normally invoked via the C<SvPV_flags> macro. C<sv_2pv()> and C<sv_2pv_nomg>
2717 usually end up here too.
2718
2719 =cut
2720 */
2721
2722 char *
2723 Perl_sv_2pv_flags(pTHX_ register SV *const sv, STRLEN *const lp, const I32 flags)
2724 {
2725     dVAR;
2726     register char *s;
2727
2728     if (!sv) {
2729         if (lp)
2730             *lp = 0;
2731         return (char *)"";
2732     }
2733     if (SvGMAGICAL(sv)) {
2734         if (flags & SV_GMAGIC)
2735             mg_get(sv);
2736         if (SvPOKp(sv)) {
2737             if (lp)
2738                 *lp = SvCUR(sv);
2739             if (flags & SV_MUTABLE_RETURN)
2740                 return SvPVX_mutable(sv);
2741             if (flags & SV_CONST_RETURN)
2742                 return (char *)SvPVX_const(sv);
2743             return SvPVX(sv);
2744         }
2745         if (SvIOKp(sv) || SvNOKp(sv)) {
2746             char tbuf[64];  /* Must fit sprintf/Gconvert of longest IV/NV */
2747             STRLEN len;
2748
2749             if (SvIOKp(sv)) {
2750                 len = SvIsUV(sv)
2751                     ? my_snprintf(tbuf, sizeof(tbuf), "%"UVuf, (UV)SvUVX(sv))
2752                     : my_snprintf(tbuf, sizeof(tbuf), "%"IVdf, (IV)SvIVX(sv));
2753             } else if(SvNVX(sv) == 0.0) {
2754                     tbuf[0] = '0';
2755                     tbuf[1] = 0;
2756                     len = 1;
2757             } else {
2758                 Gconvert(SvNVX(sv), NV_DIG, 0, tbuf);
2759                 len = strlen(tbuf);
2760             }
2761             assert(!SvROK(sv));
2762             {
2763                 dVAR;
2764
2765                 SvUPGRADE(sv, SVt_PV);
2766                 if (lp)
2767                     *lp = len;
2768                 s = SvGROW_mutable(sv, len + 1);
2769                 SvCUR_set(sv, len);
2770                 SvPOKp_on(sv);
2771                 return (char*)memcpy(s, tbuf, len + 1);
2772             }
2773         }
2774         if (SvROK(sv)) {
2775             goto return_rok;
2776         }
2777         assert(SvTYPE(sv) >= SVt_PVMG);
2778         /* This falls through to the report_uninit near the end of the
2779            function. */
2780     } else if (SvTHINKFIRST(sv)) {
2781         if (SvROK(sv)) {
2782         return_rok:
2783             if (SvAMAGIC(sv)) {
2784                 SV *tmpstr;
2785                 if (flags & SV_SKIP_OVERLOAD)
2786                     return NULL;
2787                 tmpstr = AMG_CALLunary(sv, string_amg);
2788                 TAINT_IF(tmpstr && SvTAINTED(tmpstr));
2789                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2790                     /* Unwrap this:  */
2791                     /* char *pv = lp ? SvPV(tmpstr, *lp) : SvPV_nolen(tmpstr);
2792                      */
2793
2794                     char *pv;
2795                     if ((SvFLAGS(tmpstr) & (SVf_POK)) == SVf_POK) {
2796                         if (flags & SV_CONST_RETURN) {
2797                             pv = (char *) SvPVX_const(tmpstr);
2798                         } else {
2799                             pv = (flags & SV_MUTABLE_RETURN)
2800                                 ? SvPVX_mutable(tmpstr) : SvPVX(tmpstr);
2801                         }
2802                         if (lp)
2803                             *lp = SvCUR(tmpstr);
2804                     } else {
2805                         pv = sv_2pv_flags(tmpstr, lp, flags);
2806                     }
2807                     if (SvUTF8(tmpstr))
2808                         SvUTF8_on(sv);
2809                     else
2810                         SvUTF8_off(sv);
2811                     return pv;
2812                 }
2813             }
2814             {
2815                 STRLEN len;
2816                 char *retval;
2817                 char *buffer;
2818                 SV *const referent = SvRV(sv);
2819
2820                 if (!referent) {
2821                     len = 7;
2822                     retval = buffer = savepvn("NULLREF", len);
2823                 } else if (SvTYPE(referent) == SVt_REGEXP) {
2824                     REGEXP * const re = (REGEXP *)MUTABLE_PTR(referent);
2825                     I32 seen_evals = 0;
2826
2827                     assert(re);
2828                         
2829                     /* If the regex is UTF-8 we want the containing scalar to
2830                        have an UTF-8 flag too */
2831                     if (RX_UTF8(re))
2832                         SvUTF8_on(sv);
2833                     else
2834                         SvUTF8_off(sv); 
2835
2836                     if ((seen_evals = RX_SEEN_EVALS(re)))
2837                         PL_reginterp_cnt += seen_evals;
2838
2839                     if (lp)
2840                         *lp = RX_WRAPLEN(re);
2841  
2842                     return RX_WRAPPED(re);
2843                 } else {
2844                     const char *const typestr = sv_reftype(referent, 0);
2845                     const STRLEN typelen = strlen(typestr);
2846                     UV addr = PTR2UV(referent);
2847                     const char *stashname = NULL;
2848                     STRLEN stashnamelen = 0; /* hush, gcc */
2849                     const char *buffer_end;
2850
2851                     if (SvOBJECT(referent)) {
2852                         const HEK *const name = HvNAME_HEK(SvSTASH(referent));
2853
2854                         if (name) {
2855                             stashname = HEK_KEY(name);
2856                             stashnamelen = HEK_LEN(name);
2857
2858                             if (HEK_UTF8(name)) {
2859                                 SvUTF8_on(sv);
2860                             } else {
2861                                 SvUTF8_off(sv);
2862                             }
2863                         } else {
2864                             stashname = "__ANON__";
2865                             stashnamelen = 8;
2866                         }
2867                         len = stashnamelen + 1 /* = */ + typelen + 3 /* (0x */
2868                             + 2 * sizeof(UV) + 2 /* )\0 */;
2869                     } else {
2870                         len = typelen + 3 /* (0x */
2871                             + 2 * sizeof(UV) + 2 /* )\0 */;
2872                     }
2873
2874                     Newx(buffer, len, char);
2875                     buffer_end = retval = buffer + len;
2876
2877                     /* Working backwards  */
2878                     *--retval = '\0';
2879                     *--retval = ')';
2880                     do {
2881                         *--retval = PL_hexdigit[addr & 15];
2882                     } while (addr >>= 4);
2883                     *--retval = 'x';
2884                     *--retval = '0';
2885                     *--retval = '(';
2886
2887                     retval -= typelen;
2888                     memcpy(retval, typestr, typelen);
2889
2890                     if (stashname) {
2891                         *--retval = '=';
2892                         retval -= stashnamelen;
2893                         memcpy(retval, stashname, stashnamelen);
2894                     }
2895                     /* retval may not necessarily have reached the start of the
2896                        buffer here.  */
2897                     assert (retval >= buffer);
2898
2899                     len = buffer_end - retval - 1; /* -1 for that \0  */
2900                 }
2901                 if (lp)
2902                     *lp = len;
2903                 SAVEFREEPV(buffer);
2904                 return retval;
2905             }
2906         }
2907         if (SvREADONLY(sv) && !SvOK(sv)) {
2908             if (lp)
2909                 *lp = 0;
2910             if (flags & SV_UNDEF_RETURNS_NULL)
2911                 return NULL;
2912             if (ckWARN(WARN_UNINITIALIZED))
2913                 report_uninit(sv);
2914             return (char *)"";
2915         }
2916     }
2917     if (SvIOK(sv) || ((SvIOKp(sv) && !SvNOKp(sv)))) {
2918         /* I'm assuming that if both IV and NV are equally valid then
2919            converting the IV is going to be more efficient */
2920         const U32 isUIOK = SvIsUV(sv);
2921         char buf[TYPE_CHARS(UV)];
2922         char *ebuf, *ptr;
2923         STRLEN len;
2924
2925         if (SvTYPE(sv) < SVt_PVIV)
2926             sv_upgrade(sv, SVt_PVIV);
2927         ptr = uiv_2buf(buf, SvIVX(sv), SvUVX(sv), isUIOK, &ebuf);
2928         len = ebuf - ptr;
2929         /* inlined from sv_setpvn */
2930         s = SvGROW_mutable(sv, len + 1);
2931         Move(ptr, s, len, char);
2932         s += len;
2933         *s = '\0';
2934     }
2935     else if (SvNOKp(sv)) {
2936         if (SvTYPE(sv) < SVt_PVNV)
2937             sv_upgrade(sv, SVt_PVNV);
2938         if (SvNVX(sv) == 0.0) {
2939             s = SvGROW_mutable(sv, 2);
2940             *s++ = '0';
2941             *s = '\0';
2942         } else {
2943             dSAVE_ERRNO;
2944             /* The +20 is pure guesswork.  Configure test needed. --jhi */
2945             s = SvGROW_mutable(sv, NV_DIG + 20);
2946             /* some Xenix systems wipe out errno here */
2947             Gconvert(SvNVX(sv), NV_DIG, 0, s);
2948             RESTORE_ERRNO;
2949             while (*s) s++;
2950         }
2951 #ifdef hcx
2952         if (s[-1] == '.')
2953             *--s = '\0';
2954 #endif
2955     }
2956     else {
2957         if (isGV_with_GP(sv)) {
2958             GV *const gv = MUTABLE_GV(sv);
2959             const U32 wasfake = SvFLAGS(gv) & SVf_FAKE;
2960             SV *const buffer = sv_newmortal();
2961
2962             /* FAKE globs can get coerced, so need to turn this off temporarily
2963                if it is on.  */
2964             SvFAKE_off(gv);
2965             gv_efullname3(buffer, gv, "*");
2966             SvFLAGS(gv) |= wasfake;
2967
2968             if (SvPOK(buffer)) {
2969                 if (lp) {
2970                     *lp = SvCUR(buffer);
2971                 }
2972                 return SvPVX(buffer);
2973             }
2974             else {
2975                 if (lp)
2976                     *lp = 0;
2977                 return (char *)"";
2978             }
2979         }
2980
2981         if (lp)
2982             *lp = 0;
2983         if (flags & SV_UNDEF_RETURNS_NULL)
2984             return NULL;
2985         if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
2986             report_uninit(sv);
2987         if (SvTYPE(sv) < SVt_PV)
2988             /* Typically the caller expects that sv_any is not NULL now.  */
2989             sv_upgrade(sv, SVt_PV);
2990         return (char *)"";
2991     }
2992     {
2993         const STRLEN len = s - SvPVX_const(sv);
2994         if (lp) 
2995             *lp = len;
2996         SvCUR_set(sv, len);
2997     }
2998     SvPOK_on(sv);
2999     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
3000                           PTR2UV(sv),SvPVX_const(sv)));
3001     if (flags & SV_CONST_RETURN)
3002         return (char *)SvPVX_const(sv);
3003     if (flags & SV_MUTABLE_RETURN)
3004         return SvPVX_mutable(sv);
3005     return SvPVX(sv);
3006 }
3007
3008 /*
3009 =for apidoc sv_copypv
3010
3011 Copies a stringified representation of the source SV into the
3012 destination SV.  Automatically performs any necessary mg_get and
3013 coercion of numeric values into strings.  Guaranteed to preserve
3014 UTF8 flag even from overloaded objects.  Similar in nature to
3015 sv_2pv[_flags] but operates directly on an SV instead of just the
3016 string.  Mostly uses sv_2pv_flags to do its work, except when that
3017 would lose the UTF-8'ness of the PV.
3018
3019 =cut
3020 */
3021
3022 void
3023 Perl_sv_copypv(pTHX_ SV *const dsv, register SV *const ssv)
3024 {
3025     STRLEN len;
3026     const char * const s = SvPV_const(ssv,len);
3027
3028     PERL_ARGS_ASSERT_SV_COPYPV;
3029
3030     sv_setpvn(dsv,s,len);
3031     if (SvUTF8(ssv))
3032         SvUTF8_on(dsv);
3033     else
3034         SvUTF8_off(dsv);
3035 }
3036
3037 /*
3038 =for apidoc sv_2pvbyte
3039
3040 Return a pointer to the byte-encoded representation of the SV, and set *lp
3041 to its length.  May cause the SV to be downgraded from UTF-8 as a
3042 side-effect.
3043
3044 Usually accessed via the C<SvPVbyte> macro.
3045
3046 =cut
3047 */
3048
3049 char *
3050 Perl_sv_2pvbyte(pTHX_ register SV *const sv, STRLEN *const lp)
3051 {
3052     PERL_ARGS_ASSERT_SV_2PVBYTE;
3053
3054     SvGETMAGIC(sv);
3055     sv_utf8_downgrade(sv,0);
3056     return lp ? SvPV_nomg(sv,*lp) : SvPV_nomg_nolen(sv);
3057 }
3058
3059 /*
3060 =for apidoc sv_2pvutf8
3061
3062 Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
3063 to its length.  May cause the SV to be upgraded to UTF-8 as a side-effect.
3064
3065 Usually accessed via the C<SvPVutf8> macro.
3066
3067 =cut
3068 */
3069
3070 char *
3071 Perl_sv_2pvutf8(pTHX_ register SV *const sv, STRLEN *const lp)
3072 {
3073     PERL_ARGS_ASSERT_SV_2PVUTF8;
3074
3075     sv_utf8_upgrade(sv);
3076     return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
3077 }
3078
3079
3080 /*
3081 =for apidoc sv_2bool
3082
3083 This macro is only used by sv_true() or its macro equivalent, and only if
3084 the latter's argument is neither SvPOK, SvIOK nor SvNOK.
3085 It calls sv_2bool_flags with the SV_GMAGIC flag.
3086
3087 =for apidoc sv_2bool_flags
3088
3089 This function is only used by sv_true() and friends,  and only if
3090 the latter's argument is neither SvPOK, SvIOK nor SvNOK. If the flags
3091 contain SV_GMAGIC, then it does an mg_get() first.
3092
3093
3094 =cut
3095 */
3096
3097 bool
3098 Perl_sv_2bool_flags(pTHX_ register SV *const sv, const I32 flags)
3099 {
3100     dVAR;
3101
3102     PERL_ARGS_ASSERT_SV_2BOOL_FLAGS;
3103
3104     if(flags & SV_GMAGIC) SvGETMAGIC(sv);
3105
3106     if (!SvOK(sv))
3107         return 0;
3108     if (SvROK(sv)) {
3109         if (SvAMAGIC(sv)) {
3110             SV * const tmpsv = AMG_CALLunary(sv, bool__amg);
3111             if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
3112                 return cBOOL(SvTRUE(tmpsv));
3113         }
3114         return SvRV(sv) != 0;
3115     }
3116     if (SvPOKp(sv)) {
3117         register XPV* const Xpvtmp = (XPV*)SvANY(sv);
3118         if (Xpvtmp &&
3119                 (*sv->sv_u.svu_pv > '0' ||
3120                 Xpvtmp->xpv_cur > 1 ||
3121                 (Xpvtmp->xpv_cur && *sv->sv_u.svu_pv != '0')))
3122             return 1;
3123         else
3124             return 0;
3125     }
3126     else {
3127         if (SvIOKp(sv))
3128             return SvIVX(sv) != 0;
3129         else {
3130             if (SvNOKp(sv))
3131                 return SvNVX(sv) != 0.0;
3132             else {
3133                 if (isGV_with_GP(sv))
3134                     return TRUE;
3135                 else
3136                     return FALSE;
3137             }
3138         }
3139     }
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 as 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. If C<flags> has C<SV_GMAGIC> bit set,
3165 will C<mg_get> on C<sv> if appropriate, else not.
3166 Returns the number of bytes in the converted string
3167 C<sv_utf8_upgrade> and
3168 C<sv_utf8_upgrade_nomg> are implemented in terms of this function.
3169
3170 This is not as a general purpose byte encoding to Unicode interface:
3171 use the Encode extension for that.
3172
3173 =cut
3174
3175 The grow version is currently not externally documented.  It adds a parameter,
3176 extra, which is the number of unused bytes the string of 'sv' is guaranteed to
3177 have free after it upon return.  This allows the caller to reserve extra space
3178 that it intends to fill, to avoid extra grows.
3179
3180 Also externally undocumented for the moment is the flag SV_FORCE_UTF8_UPGRADE,
3181 which can be used to tell this function to not first check to see if there are
3182 any characters that are different in UTF-8 (variant characters) which would
3183 force it to allocate a new string to sv, but to assume there are.  Typically
3184 this flag is used by a routine that has already parsed the string to find that
3185 there are such characters, and passes this information on so that the work
3186 doesn't have to be repeated.
3187
3188 (One might think that the calling routine could pass in the position of the
3189 first such variant, so it wouldn't have to be found again.  But that is not the
3190 case, because typically when the caller is likely to use this flag, it won't be
3191 calling this routine unless it finds something that won't fit into a byte.
3192 Otherwise it tries to not upgrade and just use bytes.  But some things that
3193 do fit into a byte are variants in utf8, and the caller may not have been
3194 keeping track of these.)
3195
3196 If the routine itself changes the string, it adds a trailing NUL.  Such a NUL
3197 isn't guaranteed due to having other routines do the work in some input cases,
3198 or if the input is already flagged as being in utf8.
3199
3200 The speed of this could perhaps be improved for many cases if someone wanted to
3201 write a fast function that counts the number of variant characters in a string,
3202 especially if it could return the position of the first one.
3203
3204 */
3205
3206 STRLEN
3207 Perl_sv_utf8_upgrade_flags_grow(pTHX_ register SV *const sv, const I32 flags, STRLEN extra)
3208 {
3209     dVAR;
3210
3211     PERL_ARGS_ASSERT_SV_UTF8_UPGRADE_FLAGS_GROW;
3212
3213     if (sv == &PL_sv_undef)
3214         return 0;
3215     if (!SvPOK(sv)) {
3216         STRLEN len = 0;
3217         if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
3218             (void) sv_2pv_flags(sv,&len, flags);
3219             if (SvUTF8(sv)) {
3220                 if (extra) SvGROW(sv, SvCUR(sv) + extra);
3221                 return len;
3222             }
3223         } else {
3224             (void) SvPV_force_flags(sv,len,flags & SV_GMAGIC);
3225         }
3226     }
3227
3228     if (SvUTF8(sv)) {
3229         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3230         return SvCUR(sv);
3231     }
3232
3233     if (SvIsCOW(sv)) {
3234         sv_force_normal_flags(sv, 0);
3235     }
3236
3237     if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING)) {
3238         sv_recode_to_utf8(sv, PL_encoding);
3239         if (extra) SvGROW(sv, SvCUR(sv) + extra);
3240         return SvCUR(sv);
3241     }
3242
3243     if (SvCUR(sv) == 0) {
3244         if (extra) SvGROW(sv, extra);
3245     } else { /* Assume Latin-1/EBCDIC */
3246         /* This function could be much more efficient if we
3247          * had a FLAG in SVs to signal if there are any variant
3248          * chars in the PV.  Given that there isn't such a flag
3249          * make the loop as fast as possible (although there are certainly ways
3250          * to speed this up, eg. through vectorization) */
3251         U8 * s = (U8 *) SvPVX_const(sv);
3252         U8 * e = (U8 *) SvEND(sv);
3253         U8 *t = s;
3254         STRLEN two_byte_count = 0;
3255         
3256         if (flags & SV_FORCE_UTF8_UPGRADE) goto must_be_utf8;
3257
3258         /* See if really will need to convert to utf8.  We mustn't rely on our
3259          * incoming SV being well formed and having a trailing '\0', as certain
3260          * code in pp_formline can send us partially built SVs. */
3261
3262         while (t < e) {
3263             const U8 ch = *t++;
3264             if (NATIVE_IS_INVARIANT(ch)) continue;
3265
3266             t--;    /* t already incremented; re-point to first variant */
3267             two_byte_count = 1;
3268             goto must_be_utf8;
3269         }
3270
3271         /* utf8 conversion not needed because all are invariants.  Mark as
3272          * UTF-8 even if no variant - saves scanning loop */
3273         SvUTF8_on(sv);
3274         return SvCUR(sv);
3275
3276 must_be_utf8:
3277
3278         /* Here, the string should be converted to utf8, either because of an
3279          * input flag (two_byte_count = 0), or because a character that
3280          * requires 2 bytes was found (two_byte_count = 1).  t points either to
3281          * the beginning of the string (if we didn't examine anything), or to
3282          * the first variant.  In either case, everything from s to t - 1 will
3283          * occupy only 1 byte each on output.
3284          *
3285          * There are two main ways to convert.  One is to create a new string
3286          * and go through the input starting from the beginning, appending each
3287          * converted value onto the new string as we go along.  It's probably
3288          * best to allocate enough space in the string for the worst possible
3289          * case rather than possibly running out of space and having to
3290          * reallocate and then copy what we've done so far.  Since everything
3291          * from s to t - 1 is invariant, the destination can be initialized
3292          * with these using a fast memory copy
3293          *
3294          * The other way is to figure out exactly how big the string should be
3295          * by parsing the entire input.  Then you don't have to make it big
3296          * enough to handle the worst possible case, and more importantly, if
3297          * the string you already have is large enough, you don't have to
3298          * allocate a new string, you can copy the last character in the input
3299          * string to the final position(s) that will be occupied by the
3300          * converted string and go backwards, stopping at t, since everything
3301          * before that is invariant.
3302          *
3303          * There are advantages and disadvantages to each method.
3304          *
3305          * In the first method, we can allocate a new string, do the memory
3306          * copy from the s to t - 1, and then proceed through the rest of the
3307          * string byte-by-byte.
3308          *
3309          * In the second method, we proceed through the rest of the input
3310          * string just calculating how big the converted string will be.  Then
3311          * there are two cases:
3312          *  1)  if the string has enough extra space to handle the converted
3313          *      value.  We go backwards through the string, converting until we
3314          *      get to the position we are at now, and then stop.  If this
3315          *      position is far enough along in the string, this method is
3316          *      faster than the other method.  If the memory copy were the same
3317          *      speed as the byte-by-byte loop, that position would be about
3318          *      half-way, as at the half-way mark, parsing to the end and back
3319          *      is one complete string's parse, the same amount as starting
3320          *      over and going all the way through.  Actually, it would be
3321          *      somewhat less than half-way, as it's faster to just count bytes
3322          *      than to also copy, and we don't have the overhead of allocating
3323          *      a new string, changing the scalar to use it, and freeing the
3324          *      existing one.  But if the memory copy is fast, the break-even
3325          *      point is somewhere after half way.  The counting loop could be
3326          *      sped up by vectorization, etc, to move the break-even point
3327          *      further towards the beginning.
3328          *  2)  if the string doesn't have enough space to handle the converted
3329          *      value.  A new string will have to be allocated, and one might
3330          *      as well, given that, start from the beginning doing the first
3331          *      method.  We've spent extra time parsing the string and in
3332          *      exchange all we've gotten is that we know precisely how big to
3333          *      make the new one.  Perl is more optimized for time than space,
3334          *      so this case is a loser.
3335          * So what I've decided to do is not use the 2nd method unless it is
3336          * guaranteed that a new string won't have to be allocated, assuming
3337          * the worst case.  I also decided not to put any more conditions on it
3338          * than this, for now.  It seems likely that, since the worst case is
3339          * twice as big as the unknown portion of the string (plus 1), we won't
3340          * be guaranteed enough space, causing us to go to the first method,
3341          * unless the string is short, or the first variant character is near
3342          * the end of it.  In either of these cases, it seems best to use the
3343          * 2nd method.  The only circumstance I can think of where this would
3344          * be really slower is if the string had once had much more data in it
3345          * than it does now, but there is still a substantial amount in it  */
3346
3347         {
3348             STRLEN invariant_head = t - s;
3349             STRLEN size = invariant_head + (e - t) * 2 + 1 + extra;
3350             if (SvLEN(sv) < size) {
3351
3352                 /* Here, have decided to allocate a new string */
3353
3354                 U8 *dst;
3355                 U8 *d;
3356
3357                 Newx(dst, size, U8);
3358
3359                 /* If no known invariants at the beginning of the input string,
3360                  * set so starts from there.  Otherwise, can use memory copy to
3361                  * get up to where we are now, and then start from here */
3362
3363                 if (invariant_head <= 0) {
3364                     d = dst;
3365                 } else {
3366                     Copy(s, dst, invariant_head, char);
3367                     d = dst + invariant_head;
3368                 }
3369
3370                 while (t < e) {
3371                     const UV uv = NATIVE8_TO_UNI(*t++);
3372                     if (UNI_IS_INVARIANT(uv))
3373                         *d++ = (U8)UNI_TO_NATIVE(uv);
3374                     else {
3375                         *d++ = (U8)UTF8_EIGHT_BIT_HI(uv);
3376                         *d++ = (U8)UTF8_EIGHT_BIT_LO(uv);
3377                     }
3378                 }
3379                 *d = '\0';
3380                 SvPV_free(sv); /* No longer using pre-existing string */
3381                 SvPV_set(sv, (char*)dst);
3382                 SvCUR_set(sv, d - dst);
3383                 SvLEN_set(sv, size);
3384             } else {
3385
3386                 /* Here, have decided to get the exact size of the string.
3387                  * Currently this happens only when we know that there is
3388                  * guaranteed enough space to fit the converted string, so
3389                  * don't have to worry about growing.  If two_byte_count is 0,
3390                  * then t points to the first byte of the string which hasn't
3391                  * been examined yet.  Otherwise two_byte_count is 1, and t
3392                  * points to the first byte in the string that will expand to
3393                  * two.  Depending on this, start examining at t or 1 after t.
3394                  * */
3395
3396                 U8 *d = t + two_byte_count;
3397
3398
3399                 /* Count up the remaining bytes that expand to two */
3400
3401                 while (d < e) {
3402                     const U8 chr = *d++;
3403                     if (! NATIVE_IS_INVARIANT(chr)) two_byte_count++;
3404                 }
3405
3406                 /* The string will expand by just the number of bytes that
3407                  * occupy two positions.  But we are one afterwards because of
3408                  * the increment just above.  This is the place to put the
3409                  * trailing NUL, and to set the length before we decrement */
3410
3411                 d += two_byte_count;
3412                 SvCUR_set(sv, d - s);
3413                 *d-- = '\0';
3414
3415
3416                 /* Having decremented d, it points to the position to put the
3417                  * very last byte of the expanded string.  Go backwards through
3418                  * the string, copying and expanding as we go, stopping when we
3419                  * get to the part that is invariant the rest of the way down */
3420
3421                 e--;
3422                 while (e >= t) {
3423                     const U8 ch = NATIVE8_TO_UNI(*e--);
3424                     if (UNI_IS_INVARIANT(ch)) {
3425                         *d-- = UNI_TO_NATIVE(ch);
3426                     } else {
3427                         *d-- = (U8)UTF8_EIGHT_BIT_LO(ch);
3428                         *d-- = (U8)UTF8_EIGHT_BIT_HI(ch);
3429                     }
3430                 }
3431             }
3432
3433             if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3434                 /* Update pos. We do it at the end rather than during
3435                  * the upgrade, to avoid slowing down the common case
3436                  * (upgrade without pos) */
3437                 MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3438                 if (mg) {
3439                     I32 pos = mg->mg_len;
3440                     if (pos > 0 && (U32)pos > invariant_head) {
3441                         U8 *d = (U8*) SvPVX(sv) + invariant_head;
3442                         STRLEN n = (U32)pos - invariant_head;
3443                         while (n > 0) {
3444                             if (UTF8_IS_START(*d))
3445                                 d++;
3446                             d++;
3447                             n--;
3448                         }
3449                         mg->mg_len  = d - (U8*)SvPVX(sv);
3450                     }
3451                 }
3452                 if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3453                     magic_setutf8(sv,mg); /* clear UTF8 cache */
3454             }
3455         }
3456     }
3457
3458     /* Mark as UTF-8 even if no variant - saves scanning loop */
3459     SvUTF8_on(sv);
3460     return SvCUR(sv);
3461 }
3462
3463 /*
3464 =for apidoc sv_utf8_downgrade
3465
3466 Attempts to convert the PV of an SV from characters to bytes.
3467 If the PV contains a character that cannot fit
3468 in a byte, this conversion will fail;
3469 in this case, either returns false or, if C<fail_ok> is not
3470 true, croaks.
3471
3472 This is not as a general purpose Unicode to byte encoding interface:
3473 use the Encode extension for that.
3474
3475 =cut
3476 */
3477
3478 bool
3479 Perl_sv_utf8_downgrade(pTHX_ register SV *const sv, const bool fail_ok)
3480 {
3481     dVAR;
3482
3483     PERL_ARGS_ASSERT_SV_UTF8_DOWNGRADE;
3484
3485     if (SvPOKp(sv) && SvUTF8(sv)) {
3486         if (SvCUR(sv)) {
3487             U8 *s;
3488             STRLEN len;
3489             int mg_flags = SV_GMAGIC;
3490
3491             if (SvIsCOW(sv)) {
3492                 sv_force_normal_flags(sv, 0);
3493             }
3494             if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3495                 /* update pos */
3496                 MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3497                 if (mg) {
3498                     I32 pos = mg->mg_len;
3499                     if (pos > 0) {
3500                         sv_pos_b2u(sv, &pos);
3501                         mg_flags = 0; /* sv_pos_b2u does get magic */
3502                         mg->mg_len  = pos;
3503                     }
3504                 }
3505                 if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3506                     magic_setutf8(sv,mg); /* clear UTF8 cache */
3507
3508             }
3509             s = (U8 *) SvPV_flags(sv, len, mg_flags);
3510
3511             if (!utf8_to_bytes(s, &len)) {
3512                 if (fail_ok)
3513                     return FALSE;
3514                 else {
3515                     if (PL_op)
3516                         Perl_croak(aTHX_ "Wide character in %s",
3517                                    OP_DESC(PL_op));
3518                     else
3519                         Perl_croak(aTHX_ "Wide character");
3520                 }
3521             }
3522             SvCUR_set(sv, len);
3523         }
3524     }
3525     SvUTF8_off(sv);
3526     return TRUE;
3527 }
3528
3529 /*
3530 =for apidoc sv_utf8_encode
3531
3532 Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3533 flag off so that it looks like octets again.
3534
3535 =cut
3536 */
3537
3538 void
3539 Perl_sv_utf8_encode(pTHX_ register SV *const sv)
3540 {
3541     PERL_ARGS_ASSERT_SV_UTF8_ENCODE;
3542
3543     if (SvIsCOW(sv)) {
3544         sv_force_normal_flags(sv, 0);
3545     }
3546     if (SvREADONLY(sv)) {
3547         Perl_croak_no_modify(aTHX);
3548     }
3549     (void) sv_utf8_upgrade(sv);
3550     SvUTF8_off(sv);
3551 }
3552
3553 /*
3554 =for apidoc sv_utf8_decode
3555
3556 If the PV of the SV is an octet sequence in UTF-8
3557 and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3558 so that it looks like a character. If the PV contains only single-byte
3559 characters, the C<SvUTF8> flag stays being off.
3560 Scans PV for validity and returns false if the PV is invalid UTF-8.
3561
3562 =cut
3563 */
3564
3565 bool
3566 Perl_sv_utf8_decode(pTHX_ register SV *const sv)
3567 {
3568     PERL_ARGS_ASSERT_SV_UTF8_DECODE;
3569
3570     if (SvPOKp(sv)) {
3571         const U8 *start, *c;
3572         const U8 *e;
3573
3574         /* The octets may have got themselves encoded - get them back as
3575          * bytes
3576          */
3577         if (!sv_utf8_downgrade(sv, TRUE))
3578             return FALSE;
3579
3580         /* it is actually just a matter of turning the utf8 flag on, but
3581          * we want to make sure everything inside is valid utf8 first.
3582          */
3583         c = start = (const U8 *) SvPVX_const(sv);
3584         if (!is_utf8_string(c, SvCUR(sv)+1))
3585             return FALSE;
3586         e = (const U8 *) SvEND(sv);
3587         while (c < e) {
3588             const U8 ch = *c++;
3589             if (!UTF8_IS_INVARIANT(ch)) {
3590                 SvUTF8_on(sv);
3591                 break;
3592             }
3593         }
3594         if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
3595             /* adjust pos to the start of a UTF8 char sequence */
3596             MAGIC * mg = mg_find(sv, PERL_MAGIC_regex_global);
3597             if (mg) {
3598                 I32 pos = mg->mg_len;
3599                 if (pos > 0) {
3600                     for (c = start + pos; c > start; c--) {
3601                         if (UTF8_IS_START(*c))
3602                             break;
3603                     }
3604                     mg->mg_len  = c - start;
3605                 }
3606             }
3607             if ((mg = mg_find(sv, PERL_MAGIC_utf8)))
3608                 magic_setutf8(sv,mg); /* clear UTF8 cache */
3609         }
3610     }
3611     return TRUE;
3612 }
3613
3614 /*
3615 =for apidoc sv_setsv
3616
3617 Copies the contents of the source SV C<ssv> into the destination SV
3618 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3619 function if the source SV needs to be reused. Does not handle 'set' magic.
3620 Loosely speaking, it performs a copy-by-value, obliterating any previous
3621 content of the destination.
3622
3623 You probably want to use one of the assortment of wrappers, such as
3624 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3625 C<SvSetMagicSV_nosteal>.
3626
3627 =for apidoc sv_setsv_flags
3628
3629 Copies the contents of the source SV C<ssv> into the destination SV
3630 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3631 function if the source SV needs to be reused. Does not handle 'set' magic.
3632 Loosely speaking, it performs a copy-by-value, obliterating any previous
3633 content of the destination.
3634 If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
3635 C<ssv> if appropriate, else not. If the C<flags> parameter has the
3636 C<NOSTEAL> bit set then the 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             /* FIXME - why are we doing this, then turning it off and on again
3670                below?  */
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, GV_ADD);
3677         SvFAKE_on(dstr);        /* can coerce to non-glob */
3678     }
3679
3680     if(GvGP(MUTABLE_GV(sstr))) {
3681         /* If source has method cache entry, clear it */
3682         if(GvCVGEN(sstr)) {
3683             SvREFCNT_dec(GvCV(sstr));
3684             GvCV_set(sstr, NULL);
3685             GvCVGEN(sstr) = 0;
3686         }
3687         /* If source has a real method, then a method is
3688            going to change */
3689         else if(
3690          GvCV((const GV *)sstr) && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3691         ) {
3692             mro_changes = 1;
3693         }
3694     }
3695
3696     /* If dest already had a real method, that's a change as well */
3697     if(
3698         !mro_changes && GvGP(MUTABLE_GV(dstr)) && GvCVu((const GV *)dstr)
3699      && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3700     ) {
3701         mro_changes = 1;
3702     }
3703
3704     /* We don’t need to check the name of the destination if it was not a
3705        glob to begin with. */
3706     if(dtype == SVt_PVGV) {
3707         const char * const name = GvNAME((const GV *)dstr);
3708         if(
3709             strEQ(name,"ISA")
3710          /* The stash may have been detached from the symbol table, so
3711             check its name. */
3712          && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3713          && GvAV((const GV *)sstr)
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);
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         MAGIC *mg;
3749         SV * const sref = (SV *)GvAV((const GV *)dstr);
3750         if (SvSMAGICAL(sref) && (mg = mg_find(sref, PERL_MAGIC_isa))) {
3751             if (SvTYPE(mg->mg_obj) != SVt_PVAV) {
3752                 AV * const ary = newAV();
3753                 av_push(ary, mg->mg_obj); /* takes the refcount */
3754                 mg->mg_obj = (SV *)ary;
3755             }
3756             av_push((AV *)mg->mg_obj, SvREFCNT_inc_simple_NN(dstr));
3757         }
3758         else sv_magic(sref, dstr, PERL_MAGIC_isa, NULL, 0);
3759         mro_isa_changed_in(GvSTASH(dstr));
3760     }
3761     else if(mro_changes == 3) {
3762         HV * const stash = GvHV(dstr);
3763         if(old_stash ? (HV *)HvENAME_get(old_stash) : stash)
3764             mro_package_moved(
3765                 stash, old_stash,
3766                 (GV *)dstr, 0
3767             );
3768     }
3769     else if(mro_changes) mro_method_changed_in(GvSTASH(dstr));
3770     return;
3771 }
3772
3773 static void
3774 S_glob_assign_ref(pTHX_ SV *const dstr, SV *const sstr)
3775 {
3776     SV * const sref = SvREFCNT_inc(SvRV(sstr));
3777     SV *dref = NULL;
3778     const int intro = GvINTRO(dstr);
3779     SV **location;
3780     U8 import_flag = 0;
3781     const U32 stype = SvTYPE(sref);
3782
3783     PERL_ARGS_ASSERT_GLOB_ASSIGN_REF;
3784
3785     if (intro) {
3786         GvINTRO_off(dstr);      /* one-shot flag */
3787         GvLINE(dstr) = CopLINE(PL_curcop);
3788         GvEGV(dstr) = MUTABLE_GV(dstr);
3789     }
3790     GvMULTI_on(dstr);
3791     switch (stype) {
3792     case SVt_PVCV:
3793         location = (SV **) &(GvGP(dstr)->gp_cv); /* XXX bypassing GvCV_set */
3794         import_flag = GVf_IMPORTED_CV;
3795         goto common;
3796     case SVt_PVHV:
3797         location = (SV **) &GvHV(dstr);
3798         import_flag = GVf_IMPORTED_HV;
3799         goto common;
3800     case SVt_PVAV:
3801         location = (SV **) &GvAV(dstr);
3802         import_flag = GVf_IMPORTED_AV;
3803         goto common;
3804     case SVt_PVIO:
3805         location = (SV **) &GvIOp(dstr);
3806         goto common;
3807     case SVt_PVFM:
3808         location = (SV **) &GvFORM(dstr);
3809         goto common;
3810     default:
3811         location = &GvSV(dstr);
3812         import_flag = GVf_IMPORTED_SV;
3813     common:
3814         if (intro) {
3815             if (stype == SVt_PVCV) {
3816                 /*if (GvCVGEN(dstr) && (GvCV(dstr) != (const CV *)sref || GvCVGEN(dstr))) {*/
3817                 if (GvCVGEN(dstr)) {
3818                     SvREFCNT_dec(GvCV(dstr));
3819                     GvCV_set(dstr, NULL);
3820                     GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3821                 }
3822             }
3823             SAVEGENERICSV(*location);
3824         }
3825         else
3826             dref = *location;
3827         if (stype == SVt_PVCV && (*location != sref || GvCVGEN(dstr))) {
3828             CV* const cv = MUTABLE_CV(*location);
3829             if (cv) {
3830                 if (!GvCVGEN((const GV *)dstr) &&
3831                     (CvROOT(cv) || CvXSUB(cv)))
3832                     {
3833                         /* Redefining a sub - warning is mandatory if
3834                            it was a const and its value changed. */
3835                         if (CvCONST(cv) && CvCONST((const CV *)sref)
3836                             && cv_const_sv(cv)
3837                             == cv_const_sv((const CV *)sref)) {
3838                             NOOP;
3839                             /* They are 2 constant subroutines generated from
3840                                the same constant. This probably means that
3841                                they are really the "same" proxy subroutine
3842                                instantiated in 2 places. Most likely this is
3843                                when a constant is exported twice.  Don't warn.
3844                             */
3845                         }
3846                         else if (ckWARN(WARN_REDEFINE)
3847                                  || (CvCONST(cv)
3848                                      && (!CvCONST((const CV *)sref)
3849                                          || sv_cmp(cv_const_sv(cv),
3850                                                    cv_const_sv((const CV *)
3851                                                                sref))))) {
3852                             Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
3853                                         (const char *)
3854                                         (CvCONST(cv)
3855                                          ? "Constant subroutine %s::%s redefined"
3856                                          : "Subroutine %s::%s redefined"),
3857                                         HvNAME_get(GvSTASH((const GV *)dstr)),
3858                                         GvENAME(MUTABLE_GV(dstr)));
3859                         }
3860                     }
3861                 if (!intro)
3862                     cv_ckproto_len(cv, (const GV *)dstr,
3863                                    SvPOK(sref) ? SvPVX_const(sref) : NULL,
3864                                    SvPOK(sref) ? SvCUR(sref) : 0);
3865             }
3866             GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3867             GvASSUMECV_on(dstr);
3868             if(GvSTASH(dstr)) mro_method_changed_in(GvSTASH(dstr)); /* sub foo { 1 } sub bar { 2 } *bar = \&foo */
3869         }
3870         *location = sref;
3871         if (import_flag && !(GvFLAGS(dstr) & import_flag)
3872             && CopSTASH_ne(PL_curcop, GvSTASH(dstr))) {
3873             GvFLAGS(dstr) |= import_flag;
3874         }
3875         if (stype == SVt_PVHV) {
3876             const char * const name = GvNAME((GV*)dstr);
3877             const STRLEN len = GvNAMELEN(dstr);
3878             if (
3879                 (
3880                    (len > 1 && name[len-2] == ':' && name[len-1] == ':')
3881                 || (len == 1 && name[0] == ':')
3882                 )
3883              && (!dref || HvENAME_get(dref))
3884             ) {
3885                 mro_package_moved(
3886                     (HV *)sref, (HV *)dref,
3887                     (GV *)dstr, 0
3888                 );
3889             }
3890         }
3891         else if (
3892             stype == SVt_PVAV && sref != dref
3893          && strEQ(GvNAME((GV*)dstr), "ISA")
3894          /* The stash may have been detached from the symbol table, so
3895             check its name before doing anything. */
3896          && GvSTASH(dstr) && HvENAME(GvSTASH(dstr))
3897         ) {
3898             MAGIC *mg;
3899             MAGIC * const omg = dref && SvSMAGICAL(dref)
3900                                  ? mg_find(dref, PERL_MAGIC_isa)
3901                                  : NULL;
3902             if (SvSMAGICAL(sref) && (mg = mg_find(sref, PERL_MAGIC_isa))) {
3903                 if (SvTYPE(mg->mg_obj) != SVt_PVAV) {
3904                     AV * const ary = newAV();
3905                     av_push(ary, mg->mg_obj); /* takes the refcount */
3906                     mg->mg_obj = (SV *)ary;
3907                 }
3908                 if (omg) {
3909                     if (SvTYPE(omg->mg_obj) == SVt_PVAV) {
3910                         SV **svp = AvARRAY((AV *)omg->mg_obj);
3911                         I32 items = AvFILLp((AV *)omg->mg_obj) + 1;
3912                         while (items--)
3913                             av_push(
3914                              (AV *)mg->mg_obj,
3915                              SvREFCNT_inc_simple_NN(*svp++)
3916                             );
3917                     }
3918                     else
3919                         av_push(
3920                          (AV *)mg->mg_obj,
3921                          SvREFCNT_inc_simple_NN(omg->mg_obj)
3922                         );
3923                 }
3924                 else
3925                     av_push((AV *)mg->mg_obj,SvREFCNT_inc_simple_NN(dstr));
3926             }
3927             else
3928             {
3929                 sv_magic(
3930                  sref, omg ? omg->mg_obj : dstr, PERL_MAGIC_isa, NULL, 0
3931                 );
3932                 mg = mg_find(sref, PERL_MAGIC_isa);
3933             }
3934             /* Since the *ISA assignment could have affected more than
3935                one stash, don’t call mro_isa_changed_in directly, but let
3936                magic_clearisa do it for us, as it already has the logic for
3937                dealing with globs vs arrays of globs. */
3938             assert(mg);
3939             Perl_magic_clearisa(aTHX_ NULL, mg);
3940         }
3941         break;
3942     }
3943     SvREFCNT_dec(dref);
3944     if (SvTAINTED(sstr))
3945         SvTAINT(dstr);
3946     return;
3947 }
3948
3949 void
3950 Perl_sv_setsv_flags(pTHX_ SV *dstr, register SV* sstr, const I32 flags)
3951 {
3952     dVAR;
3953     register U32 sflags;
3954     register int dtype;
3955     register svtype stype;
3956
3957     PERL_ARGS_ASSERT_SV_SETSV_FLAGS;
3958
3959     if (sstr == dstr)
3960         return;
3961
3962     if (SvIS_FREED(dstr)) {
3963         Perl_croak(aTHX_ "panic: attempt to copy value %" SVf
3964                    " to a freed scalar %p", SVfARG(sstr), (void *)dstr);
3965     }
3966     SV_CHECK_THINKFIRST_COW_DROP(dstr);
3967     if (!sstr)
3968         sstr = &PL_sv_undef;
3969     if (SvIS_FREED(sstr)) {
3970         Perl_croak(aTHX_ "panic: attempt to copy freed scalar %p to %p",
3971                    (void*)sstr, (void*)dstr);
3972     }
3973     stype = SvTYPE(sstr);
3974     dtype = SvTYPE(dstr);
3975
3976     (void)SvAMAGIC_off(dstr);
3977     if ( SvVOK(dstr) )
3978     {
3979         /* need to nuke the magic */
3980         mg_free(dstr);
3981     }
3982
3983     /* There's a lot of redundancy below but we're going for speed here */
3984
3985     switch (stype) {
3986     case SVt_NULL:
3987       undef_sstr:
3988         if (dtype != SVt_PVGV && dtype != SVt_PVLV) {
3989             (void)SvOK_off(dstr);
3990             return;
3991         }
3992         break;
3993     case SVt_IV:
3994         if (SvIOK(sstr)) {
3995             switch (dtype) {
3996             case SVt_NULL:
3997                 sv_upgrade(dstr, SVt_IV);
3998                 break;
3999             case SVt_NV:
4000             case SVt_PV:
4001                 sv_upgrade(dstr, SVt_PVIV);
4002                 break;
4003             case SVt_PVGV:
4004             case SVt_PVLV:
4005                 goto end_of_first_switch;
4006             }
4007             (void)SvIOK_only(dstr);
4008             SvIV_set(dstr,  SvIVX(sstr));
4009             if (SvIsUV(sstr))
4010                 SvIsUV_on(dstr);
4011             /* SvTAINTED can only be true if the SV has taint magic, which in
4012                turn means that the SV type is PVMG (or greater). This is the
4013                case statement for SVt_IV, so this cannot be true (whatever gcov
4014                may say).  */
4015             assert(!SvTAINTED(sstr));
4016             return;
4017         }
4018         if (!SvROK(sstr))
4019             goto undef_sstr;
4020         if (dtype < SVt_PV && dtype != SVt_IV)
4021             sv_upgrade(dstr, SVt_IV);
4022         break;
4023
4024     case SVt_NV:
4025         if (SvNOK(sstr)) {
4026             switch (dtype) {
4027             case SVt_NULL:
4028             case SVt_IV:
4029                 sv_upgrade(dstr, SVt_NV);
4030                 break;
4031             case SVt_PV:
4032             case SVt_PVIV:
4033                 sv_upgrade(dstr, SVt_PVNV);
4034                 break;
4035             case SVt_PVGV:
4036             case SVt_PVLV:
4037                 goto end_of_first_switch;
4038             }
4039             SvNV_set(dstr, SvNVX(sstr));
4040             (void)SvNOK_only(dstr);
4041             /* SvTAINTED can only be true if the SV has taint magic, which in
4042                turn means that the SV type is PVMG (or greater). This is the
4043                case statement for SVt_NV, so this cannot be true (whatever gcov
4044                may say).  */
4045             assert(!SvTAINTED(sstr));
4046             return;
4047         }
4048         goto undef_sstr;
4049
4050     case SVt_PVFM:
4051 #ifdef PERL_OLD_COPY_ON_WRITE
4052         if ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS) {
4053             if (dtype < SVt_PVIV)
4054                 sv_upgrade(dstr, SVt_PVIV);
4055             break;
4056         }
4057         /* Fall through */
4058 #endif
4059     case SVt_PV:
4060         if (dtype < SVt_PV)
4061             sv_upgrade(dstr, SVt_PV);
4062         break;
4063     case SVt_PVIV:
4064         if (dtype < SVt_PVIV)
4065             sv_upgrade(dstr, SVt_PVIV);
4066         break;
4067     case SVt_PVNV:
4068         if (dtype < SVt_PVNV)
4069             sv_upgrade(dstr, SVt_PVNV);
4070         break;
4071     default:
4072         {
4073         const char * const type = sv_reftype(sstr,0);
4074         if (PL_op)
4075             Perl_croak(aTHX_ "Bizarre copy of %s in %s", type, OP_DESC(PL_op));
4076         else
4077             Perl_croak(aTHX_ "Bizarre copy of %s", type);
4078         }
4079         break;
4080
4081     case SVt_REGEXP:
4082         if (dtype < SVt_REGEXP)
4083             sv_upgrade(dstr, SVt_REGEXP);
4084         break;
4085
4086         /* case SVt_BIND: */
4087     case SVt_PVLV:
4088     case SVt_PVGV:
4089         /* SvVALID means that this PVGV is playing at being an FBM.  */
4090
4091     case SVt_PVMG:
4092         if (SvGMAGICAL(sstr) && (flags & SV_GMAGIC)) {
4093             mg_get(sstr);
4094             if (SvTYPE(sstr) != stype)
4095                 stype = SvTYPE(sstr);
4096         }
4097         if (isGV_with_GP(sstr) && dtype <= SVt_PVLV) {
4098                     glob_assign_glob(dstr, sstr, dtype);
4099                     return;
4100         }
4101         if (stype == SVt_PVLV)
4102             SvUPGRADE(dstr, SVt_PVNV);
4103         else
4104             SvUPGRADE(dstr, (svtype)stype);
4105     }
4106  end_of_first_switch:
4107
4108     /* dstr may have been upgraded.  */
4109     dtype = SvTYPE(dstr);
4110     sflags = SvFLAGS(sstr);
4111
4112     if (dtype == SVt_PVCV || dtype == SVt_PVFM) {
4113         /* Assigning to a subroutine sets the prototype.  */
4114         if (SvOK(sstr)) {
4115             STRLEN len;
4116             const char *const ptr = SvPV_const(sstr, len);
4117
4118             SvGROW(dstr, len + 1);
4119             Copy(ptr, SvPVX(dstr), len + 1, char);
4120             SvCUR_set(dstr, len);
4121             SvPOK_only(dstr);
4122             SvFLAGS(dstr) |= sflags & SVf_UTF8;
4123         } else {
4124             SvOK_off(dstr);
4125         }
4126     } else if (dtype == SVt_PVAV || dtype == SVt_PVHV) {
4127         const char * const type = sv_reftype(dstr,0);
4128         if (PL_op)
4129             Perl_croak(aTHX_ "Cannot copy to %s in %s", type, OP_DESC(PL_op));
4130         else
4131             Perl_croak(aTHX_ "Cannot copy to %s", type);
4132     } else if (sflags & SVf_ROK) {
4133         if (isGV_with_GP(dstr)
4134             && SvTYPE(SvRV(sstr)) == SVt_PVGV && isGV_with_GP(SvRV(sstr))) {
4135             sstr = SvRV(sstr);
4136             if (sstr == dstr) {
4137                 if (GvIMPORTED(dstr) != GVf_IMPORTED
4138                     && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
4139                 {
4140                     GvIMPORTED_on(dstr);
4141                 }
4142                 GvMULTI_on(dstr);
4143                 return;
4144             }
4145             glob_assign_glob(dstr, sstr, dtype);
4146             return;
4147         }
4148
4149         if (dtype >= SVt_PV) {
4150             if (isGV_with_GP(dstr)) {
4151                 glob_assign_ref(dstr, sstr);
4152                 return;
4153             }
4154             if (SvPVX_const(dstr)) {
4155                 SvPV_free(dstr);
4156                 SvLEN_set(dstr, 0);
4157                 SvCUR_set(dstr, 0);
4158             }
4159         }
4160         (void)SvOK_off(dstr);
4161         SvRV_set(dstr, SvREFCNT_inc(SvRV(sstr)));
4162         SvFLAGS(dstr) |= sflags & SVf_ROK;
4163         assert(!(sflags & SVp_NOK));
4164         assert(!(sflags & SVp_IOK));
4165         assert(!(sflags & SVf_NOK));
4166         assert(!(sflags & SVf_IOK));
4167     }
4168     else if (isGV_with_GP(dstr)) {
4169         if (!(sflags & SVf_OK)) {
4170             Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4171                            "Undefined value assigned to typeglob");
4172         }
4173         else {
4174             GV *gv = gv_fetchsv(sstr, GV_ADD, SVt_PVGV);
4175             if (dstr != (const SV *)gv) {
4176                 const char * const name = GvNAME((const GV *)dstr);
4177                 const STRLEN len = GvNAMELEN(dstr);
4178                 HV *old_stash = NULL;
4179                 bool reset_isa = FALSE;
4180                 if ((len > 1 && name[len-2] == ':' && name[len-1] == ':')
4181                  || (len == 1 && name[0] == ':')) {
4182                     /* Set aside the old stash, so we can reset isa caches
4183                        on its subclasses. */
4184                     if((old_stash = GvHV(dstr))) {
4185                         /* Make sure we do not lose it early. */
4186                         SvREFCNT_inc_simple_void_NN(
4187                          sv_2mortal((SV *)old_stash)
4188                         );
4189                     }
4190                     reset_isa = TRUE;
4191                 }
4192
4193                 if (GvGP(dstr))
4194                     gp_free(MUTABLE_GV(dstr));
4195                 GvGP_set(dstr, gp_ref(GvGP(gv)));
4196
4197                 if (reset_isa) {
4198                     HV * const stash = GvHV(dstr);
4199                     if(
4200                         old_stash ? (HV *)HvENAME_get(old_stash) : stash
4201                     )
4202                         mro_package_moved(
4203                          stash, old_stash,
4204                          (GV *)dstr, 0
4205                         );
4206                 }
4207             }
4208         }
4209     }
4210     else if (dtype == SVt_REGEXP && stype == SVt_REGEXP) {
4211         reg_temp_copy((REGEXP*)dstr, (REGEXP*)sstr);
4212     }
4213     else if (sflags & SVp_POK) {
4214         bool isSwipe = 0;
4215
4216         /*
4217          * Check to see if we can just swipe the string.  If so, it's a
4218          * possible small lose on short strings, but a big win on long ones.
4219          * It might even be a win on short strings if SvPVX_const(dstr)
4220          * has to be allocated and SvPVX_const(sstr) has to be freed.
4221          * Likewise if we can set up COW rather than doing an actual copy, we
4222          * drop to the else clause, as the swipe code and the COW setup code
4223          * have much in common.
4224          */
4225
4226         /* Whichever path we take through the next code, we want this true,
4227            and doing it now facilitates the COW check.  */
4228         (void)SvPOK_only(dstr);
4229
4230         if (
4231             /* If we're already COW then this clause is not true, and if COW
4232                is allowed then we drop down to the else and make dest COW 
4233                with us.  If caller hasn't said that we're allowed to COW
4234                shared hash keys then we don't do the COW setup, even if the
4235                source scalar is a shared hash key scalar.  */
4236             (((flags & SV_COW_SHARED_HASH_KEYS)
4237                ? (sflags & (SVf_FAKE|SVf_READONLY)) != (SVf_FAKE|SVf_READONLY)
4238                : 1 /* If making a COW copy is forbidden then the behaviour we
4239                        desire is as if the source SV isn't actually already
4240                        COW, even if it is.  So we act as if the source flags
4241                        are not COW, rather than actually testing them.  */
4242               )
4243 #ifndef PERL_OLD_COPY_ON_WRITE
4244              /* The change that added SV_COW_SHARED_HASH_KEYS makes the logic
4245                 when PERL_OLD_COPY_ON_WRITE is defined a little wrong.
4246                 Conceptually PERL_OLD_COPY_ON_WRITE being defined should
4247                 override SV_COW_SHARED_HASH_KEYS, because it means "always COW"
4248                 but in turn, it's somewhat dead code, never expected to go
4249                 live, but more kept as a placeholder on how to do it better
4250                 in a newer implementation.  */
4251              /* If we are COW and dstr is a suitable target then we drop down
4252                 into the else and make dest a COW of us.  */
4253              || (SvFLAGS(dstr) & CAN_COW_MASK) != CAN_COW_FLAGS
4254 #endif
4255              )
4256             &&
4257             !(isSwipe =
4258                  (sflags & SVs_TEMP) &&   /* slated for free anyway? */
4259                  !(sflags & SVf_OOK) &&   /* and not involved in OOK hack? */
4260                  (!(flags & SV_NOSTEAL)) &&
4261                                         /* and we're allowed to steal temps */
4262                  SvREFCNT(sstr) == 1 &&   /* and no other references to it? */
4263                  SvLEN(sstr))             /* and really is a string */
4264 #ifdef PERL_OLD_COPY_ON_WRITE
4265             && ((flags & SV_COW_SHARED_HASH_KEYS)
4266                 ? (!((sflags & CAN_COW_MASK) == CAN_COW_FLAGS
4267                      && (SvFLAGS(dstr) & CAN_COW_MASK) == CAN_COW_FLAGS
4268                      && SvTYPE(sstr) >= SVt_PVIV && SvTYPE(sstr) != SVt_PVFM))
4269                 : 1)
4270 #endif
4271             ) {
4272             /* Failed the swipe test, and it's not a shared hash key either.
4273                Have to copy the string.  */
4274             STRLEN len = SvCUR(sstr);
4275             SvGROW(dstr, len + 1);      /* inlined from sv_setpvn */
4276             Move(SvPVX_const(sstr),SvPVX(dstr),len,char);
4277             SvCUR_set(dstr, len);
4278             *SvEND(dstr) = '\0';
4279         } else {
4280             /* If PERL_OLD_COPY_ON_WRITE is not defined, then isSwipe will always
4281                be true in here.  */
4282             /* Either it's a shared hash key, or it's suitable for
4283                copy-on-write or we can swipe the string.  */
4284             if (DEBUG_C_TEST) {
4285                 PerlIO_printf(Perl_debug_log, "Copy on write: sstr --> dstr\n");
4286                 sv_dump(sstr);
4287                 sv_dump(dstr);
4288             }
4289 #ifdef PERL_OLD_COPY_ON_WRITE
4290             if (!isSwipe) {
4291                 if ((sflags & (SVf_FAKE | SVf_READONLY))
4292                     != (SVf_FAKE | SVf_READONLY)) {
4293                     SvREADONLY_on(sstr);
4294                     SvFAKE_on(sstr);
4295                     /* Make the source SV into a loop of 1.
4296                        (about to become 2) */
4297                     SV_COW_NEXT_SV_SET(sstr, sstr);
4298                 }
4299             }
4300 #endif
4301             /* Initial code is common.  */
4302             if (SvPVX_const(dstr)) {    /* we know that dtype >= SVt_PV */
4303                 SvPV_free(dstr);
4304             }
4305
4306             if (!isSwipe) {
4307                 /* making another shared SV.  */
4308                 STRLEN cur = SvCUR(sstr);
4309                 STRLEN len = SvLEN(sstr);
4310 #ifdef PERL_OLD_COPY_ON_WRITE
4311                 if (len) {
4312                     assert (SvTYPE(dstr) >= SVt_PVIV);
4313                     /* SvIsCOW_normal */
4314                     /* splice us in between source and next-after-source.  */
4315                     SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4316                     SV_COW_NEXT_SV_SET(sstr, dstr);
4317                     SvPV_set(dstr, SvPVX_mutable(sstr));
4318                 } else
4319 #endif
4320                 {
4321                     /* SvIsCOW_shared_hash */
4322                     DEBUG_C(PerlIO_printf(Perl_debug_log,
4323                                           "Copy on write: Sharing hash\n"));
4324
4325                     assert (SvTYPE(dstr) >= SVt_PV);
4326                     SvPV_set(dstr,
4327                              HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)))));
4328                 }
4329                 SvLEN_set(dstr, len);
4330                 SvCUR_set(dstr, cur);
4331                 SvREADONLY_on(dstr);
4332                 SvFAKE_on(dstr);
4333             }
4334             else
4335                 {       /* Passes the swipe test.  */
4336                 SvPV_set(dstr, SvPVX_mutable(sstr));
4337                 SvLEN_set(dstr, SvLEN(sstr));
4338                 SvCUR_set(dstr, SvCUR(sstr));
4339
4340                 SvTEMP_off(dstr);
4341                 (void)SvOK_off(sstr);   /* NOTE: nukes most SvFLAGS on sstr */
4342                 SvPV_set(sstr, NULL);
4343                 SvLEN_set(sstr, 0);
4344                 SvCUR_set(sstr, 0);
4345                 SvTEMP_off(sstr);
4346             }
4347         }
4348         if (sflags & SVp_NOK) {
4349             SvNV_set(dstr, SvNVX(sstr));
4350         }
4351         if (sflags & SVp_IOK) {
4352             SvIV_set(dstr, SvIVX(sstr));
4353             /* Must do this otherwise some other overloaded use of 0x80000000
4354                gets confused. I guess SVpbm_VALID */
4355             if (sflags & SVf_IVisUV)
4356                 SvIsUV_on(dstr);
4357         }
4358         SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_NOK|SVp_NOK|SVf_UTF8);
4359         {
4360             const MAGIC * const smg = SvVSTRING_mg(sstr);
4361             if (smg) {
4362                 sv_magic(dstr, NULL, PERL_MAGIC_vstring,
4363                          smg->mg_ptr, smg->mg_len);
4364                 SvRMAGICAL_on(dstr);
4365             }
4366         }
4367     }
4368     else if (sflags & (SVp_IOK|SVp_NOK)) {
4369         (void)SvOK_off(dstr);
4370         SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_IVisUV|SVf_NOK|SVp_NOK);
4371         if (sflags & SVp_IOK) {
4372             /* XXXX Do we want to set IsUV for IV(ROK)?  Be extra safe... */
4373             SvIV_set(dstr, SvIVX(sstr));
4374         }
4375         if (sflags & SVp_NOK) {
4376             SvNV_set(dstr, SvNVX(sstr));
4377         }
4378     }
4379     else {
4380         if (isGV_with_GP(sstr)) {
4381             /* This stringification rule for globs is spread in 3 places.
4382                This feels bad. FIXME.  */
4383             const U32 wasfake = sflags & SVf_FAKE;
4384
4385             /* FAKE globs can get coerced, so need to turn this off
4386                temporarily if it is on.  */
4387             SvFAKE_off(sstr);
4388             gv_efullname3(dstr, MUTABLE_GV(sstr), "*");
4389             SvFLAGS(sstr) |= wasfake;
4390         }
4391         else
4392             (void)SvOK_off(dstr);
4393     }
4394     if (SvTAINTED(sstr))
4395         SvTAINT(dstr);
4396 }
4397
4398 /*
4399 =for apidoc sv_setsv_mg
4400
4401 Like C<sv_setsv>, but also handles 'set' magic.
4402
4403 =cut
4404 */
4405
4406 void
4407 Perl_sv_setsv_mg(pTHX_ SV *const dstr, register SV *const sstr)
4408 {
4409     PERL_ARGS_ASSERT_SV_SETSV_MG;
4410
4411     sv_setsv(dstr,sstr);
4412     SvSETMAGIC(dstr);
4413 }
4414
4415 #ifdef PERL_OLD_COPY_ON_WRITE
4416 SV *
4417 Perl_sv_setsv_cow(pTHX_ SV *dstr, SV *sstr)
4418 {
4419     STRLEN cur = SvCUR(sstr);
4420     STRLEN len = SvLEN(sstr);
4421     register char *new_pv;
4422
4423     PERL_ARGS_ASSERT_SV_SETSV_COW;
4424
4425     if (DEBUG_C_TEST) {
4426         PerlIO_printf(Perl_debug_log, "Fast copy on write: %p -> %p\n",
4427                       (void*)sstr, (void*)dstr);
4428         sv_dump(sstr);
4429         if (dstr)
4430                     sv_dump(dstr);
4431     }
4432
4433     if (dstr) {
4434         if (SvTHINKFIRST(dstr))
4435             sv_force_normal_flags(dstr, SV_COW_DROP_PV);
4436         else if (SvPVX_const(dstr))
4437             Safefree(SvPVX_const(dstr));
4438     }
4439     else
4440         new_SV(dstr);
4441     SvUPGRADE(dstr, SVt_PVIV);
4442
4443     assert (SvPOK(sstr));
4444     assert (SvPOKp(sstr));
4445     assert (!SvIOK(sstr));
4446     assert (!SvIOKp(sstr));
4447     assert (!SvNOK(sstr));
4448     assert (!SvNOKp(sstr));
4449
4450     if (SvIsCOW(sstr)) {
4451
4452         if (SvLEN(sstr) == 0) {
4453             /* source is a COW shared hash key.  */
4454             DEBUG_C(PerlIO_printf(Perl_debug_log,
4455                                   "Fast copy on write: Sharing hash\n"));
4456             new_pv = HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr))));
4457             goto common_exit;
4458         }
4459         SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4460     } else {
4461         assert ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS);
4462         SvUPGRADE(sstr, SVt_PVIV);
4463         SvREADONLY_on(sstr);
4464         SvFAKE_on(sstr);
4465         DEBUG_C(PerlIO_printf(Perl_debug_log,
4466                               "Fast copy on write: Converting sstr to COW\n"));
4467         SV_COW_NEXT_SV_SET(dstr, sstr);
4468     }
4469     SV_COW_NEXT_SV_SET(sstr, dstr);
4470     new_pv = SvPVX_mutable(sstr);
4471
4472   common_exit:
4473     SvPV_set(dstr, new_pv);
4474     SvFLAGS(dstr) = (SVt_PVIV|SVf_POK|SVp_POK|SVf_FAKE|SVf_READONLY);
4475     if (SvUTF8(sstr))
4476         SvUTF8_on(dstr);
4477     SvLEN_set(dstr, len);
4478     SvCUR_set(dstr, cur);
4479     if (DEBUG_C_TEST) {
4480         sv_dump(dstr);
4481     }
4482     return dstr;
4483 }
4484 #endif
4485
4486 /*
4487 =for apidoc sv_setpvn
4488
4489 Copies a string into an SV.  The C<len> parameter indicates the number of
4490 bytes to be copied.  If the C<ptr> argument is NULL the SV will become
4491 undefined.  Does not handle 'set' magic.  See C<sv_setpvn_mg>.
4492
4493 =cut
4494 */
4495
4496 void
4497 Perl_sv_setpvn(pTHX_ register SV *const sv, register const char *const ptr, register const STRLEN len)
4498 {
4499     dVAR;
4500     register char *dptr;
4501
4502     PERL_ARGS_ASSERT_SV_SETPVN;
4503
4504     SV_CHECK_THINKFIRST_COW_DROP(sv);
4505     if (!ptr) {
4506         (void)SvOK_off(sv);
4507         return;
4508     }
4509     else {
4510         /* len is STRLEN which is unsigned, need to copy to signed */
4511         const IV iv = len;
4512         if (iv < 0)
4513             Perl_croak(aTHX_ "panic: sv_setpvn called with negative strlen");
4514     }
4515     SvUPGRADE(sv, SVt_PV);
4516
4517     dptr = SvGROW(sv, len + 1);
4518     Move(ptr,dptr,len,char);
4519     dptr[len] = '\0';
4520     SvCUR_set(sv, len);
4521     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4522     SvTAINT(sv);
4523 }
4524
4525 /*
4526 =for apidoc sv_setpvn_mg
4527
4528 Like C<sv_setpvn>, but also handles 'set' magic.
4529
4530 =cut
4531 */
4532
4533 void
4534 Perl_sv_setpvn_mg(pTHX_ register SV *const sv, register const char *const ptr, register const STRLEN len)
4535 {
4536     PERL_ARGS_ASSERT_SV_SETPVN_MG;
4537
4538     sv_setpvn(sv,ptr,len);
4539     SvSETMAGIC(sv);
4540 }
4541
4542 /*
4543 =for apidoc sv_setpv
4544
4545 Copies a string into an SV.  The string must be null-terminated.  Does not
4546 handle 'set' magic.  See C<sv_setpv_mg>.
4547
4548 =cut
4549 */
4550
4551 void
4552 Perl_sv_setpv(pTHX_ register SV *const sv, register const char *const ptr)
4553 {
4554     dVAR;
4555     register STRLEN len;
4556
4557     PERL_ARGS_ASSERT_SV_SETPV;
4558
4559     SV_CHECK_THINKFIRST_COW_DROP(sv);
4560     if (!ptr) {
4561         (void)SvOK_off(sv);
4562         return;
4563     }
4564     len = strlen(ptr);
4565     SvUPGRADE(sv, SVt_PV);
4566
4567     SvGROW(sv, len + 1);
4568     Move(ptr,SvPVX(sv),len+1,char);
4569     SvCUR_set(sv, len);
4570     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4571     SvTAINT(sv);
4572 }
4573
4574 /*
4575 =for apidoc sv_setpv_mg
4576
4577 Like C<sv_setpv>, but also handles 'set' magic.
4578
4579 =cut
4580 */
4581
4582 void
4583 Perl_sv_setpv_mg(pTHX_ register SV *const sv, register const char *const ptr)
4584 {
4585     PERL_ARGS_ASSERT_SV_SETPV_MG;
4586
4587     sv_setpv(sv,ptr);
4588     SvSETMAGIC(sv);
4589 }
4590
4591 /*
4592 =for apidoc sv_usepvn_flags
4593
4594 Tells an SV to use C<ptr> to find its string value.  Normally the
4595 string is stored inside the SV but sv_usepvn allows the SV to use an
4596 outside string.  The C<ptr> should point to memory that was allocated
4597 by C<malloc>.  The string length, C<len>, must be supplied.  By default
4598 this function will realloc (i.e. move) the memory pointed to by C<ptr>,
4599 so that pointer should not be freed or used by the programmer after
4600 giving it to sv_usepvn, and neither should any pointers from "behind"
4601 that pointer (e.g. ptr + 1) be used.
4602
4603 If C<flags> & SV_SMAGIC is true, will call SvSETMAGIC. If C<flags> &
4604 SV_HAS_TRAILING_NUL is true, then C<ptr[len]> must be NUL, and the realloc
4605 will be skipped. (i.e. the buffer is actually at least 1 byte longer than
4606 C<len>, and already meets the requirements for storing in C<SvPVX>)
4607
4608 =cut
4609 */
4610
4611 void
4612 Perl_sv_usepvn_flags(pTHX_ SV *const sv, char *ptr, const STRLEN len, const U32 flags)
4613 {
4614     dVAR;
4615     STRLEN allocate;
4616
4617     PERL_ARGS_ASSERT_SV_USEPVN_FLAGS;
4618
4619     SV_CHECK_THINKFIRST_COW_DROP(sv);
4620     SvUPGRADE(sv, SVt_PV);
4621     if (!ptr) {
4622         (void)SvOK_off(sv);