This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
34e26e30004f36bacd0dce02a517cd4864819a22
[perl5.git] / sv.c
1 /*    sv.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4  *    2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  * "I wonder what the Entish is for 'yes' and 'no'," he thought.
10  *
11  *
12  * This file contains the code that creates, manipulates and destroys
13  * scalar values (SVs). The other types (AV, HV, GV, etc.) reuse the
14  * structure of an SV, so their creation and destruction is handled
15  * here; higher-level functions are in av.c, hv.c, and so on. Opcode
16  * level functions (eg. substr, split, join) for each of the types are
17  * in the pp*.c files.
18  */
19
20 #include "EXTERN.h"
21 #define PERL_IN_SV_C
22 #include "perl.h"
23 #include "regcomp.h"
24
25 #define FCALL *f
26
27 #ifdef __Lynx__
28 /* Missing proto on LynxOS */
29   char *gconvert(double, int, int,  char *);
30 #endif
31
32 #ifdef PERL_UTF8_CACHE_ASSERT
33 /* The cache element 0 is the Unicode offset;
34  * the cache element 1 is the byte offset of the element 0;
35  * the cache element 2 is the Unicode length of the substring;
36  * the cache element 3 is the byte length of the substring;
37  * The checking of the substring side would be good
38  * but substr() has enough code paths to make my head spin;
39  * if adding more checks watch out for the following tests:
40  *   t/op/index.t t/op/length.t t/op/pat.t t/op/substr.t
41  *   lib/utf8.t lib/Unicode/Collate/t/index.t
42  * --jhi
43  */
44 #define ASSERT_UTF8_CACHE(cache) \
45         STMT_START { if (cache) { assert((cache)[0] <= (cache)[1]); } } STMT_END
46 #else
47 #define ASSERT_UTF8_CACHE(cache) NOOP
48 #endif
49
50 #ifdef PERL_OLD_COPY_ON_WRITE
51 #define SV_COW_NEXT_SV(sv)      INT2PTR(SV *,SvUVX(sv))
52 #define SV_COW_NEXT_SV_SET(current,next)        SvUV_set(current, PTR2UV(next))
53 /* This is a pessimistic view. Scalar must be purely a read-write PV to copy-
54    on-write.  */
55 #endif
56
57 /* ============================================================================
58
59 =head1 Allocation and deallocation of SVs.
60
61 An SV (or AV, HV, etc.) is allocated in two parts: the head (struct sv,
62 av, hv...) contains type and reference count information, as well as a
63 pointer to the body (struct xrv, xpv, xpviv...), which contains fields
64 specific to each type.
65
66 Normally, this allocation is done using arenas, which by default are
67 approximately 4K chunks of memory parcelled up into N heads or bodies.  The
68 first slot in each arena is reserved, and is used to hold a link to the next
69 arena.  In the case of heads, the unused first slot also contains some flags
70 and a note of the number of slots.  Snaked through each arena chain is a
71 linked list of free items; when this becomes empty, an extra arena is
72 allocated and divided up into N items which are threaded into the free list.
73
74 The following global variables are associated with arenas:
75
76     PL_sv_arenaroot     pointer to list of SV arenas
77     PL_sv_root          pointer to list of free SV structures
78
79     PL_foo_arenaroot    pointer to list of foo arenas,
80     PL_foo_root         pointer to list of free foo bodies
81                             ... for foo in xiv, xnv, xrv, xpv etc.
82
83 Note that some of the larger and more rarely used body types (eg xpvio)
84 are not allocated using arenas, but are instead just malloc()/free()ed as
85 required. Also, if PURIFY is defined, arenas are abandoned altogether,
86 with all items individually malloc()ed. In addition, a few SV heads are
87 not allocated from an arena, but are instead directly created as static
88 or auto variables, eg PL_sv_undef.  The size of arenas can be changed from
89 the default by setting PERL_ARENA_SIZE appropriately at compile time.
90
91 The SV arena serves the secondary purpose of allowing still-live SVs
92 to be located and destroyed during final cleanup.
93
94 At the lowest level, the macros new_SV() and del_SV() grab and free
95 an SV head.  (If debugging with -DD, del_SV() calls the function S_del_sv()
96 to return the SV to the free list with error checking.) new_SV() calls
97 more_sv() / sv_add_arena() to add an extra arena if the free list is empty.
98 SVs in the free list have their SvTYPE field set to all ones.
99
100 Similarly, there are macros new_XIV()/del_XIV(), new_XNV()/del_XNV() etc
101 that allocate and return individual body types. Normally these are mapped
102 to the arena-manipulating functions new_xiv()/del_xiv() etc, but may be
103 instead mapped directly to malloc()/free() if PURIFY is defined. The
104 new/del functions remove from, or add to, the appropriate PL_foo_root
105 list, and call more_xiv() etc to add a new arena if the list is empty.
106
107 At the time of very final cleanup, sv_free_arenas() is called from
108 perl_destruct() to physically free all the arenas allocated since the
109 start of the interpreter.  Note that this also clears PL_he_arenaroot,
110 which is otherwise dealt with in hv.c.
111
112 Manipulation of any of the PL_*root pointers is protected by enclosing
113 LOCK_SV_MUTEX; ... UNLOCK_SV_MUTEX calls which should Do the Right Thing
114 if threads are enabled.
115
116 The function visit() scans the SV arenas list, and calls a specified
117 function for each SV it finds which is still live - ie which has an SvTYPE
118 other than all 1's, and a non-zero SvREFCNT. visit() is used by the
119 following functions (specified as [function that calls visit()] / [function
120 called by visit() for each SV]):
121
122     sv_report_used() / do_report_used()
123                         dump all remaining SVs (debugging aid)
124
125     sv_clean_objs() / do_clean_objs(),do_clean_named_objs()
126                         Attempt to free all objects pointed to by RVs,
127                         and, unless DISABLE_DESTRUCTOR_KLUDGE is defined,
128                         try to do the same for all objects indirectly
129                         referenced by typeglobs too.  Called once from
130                         perl_destruct(), prior to calling sv_clean_all()
131                         below.
132
133     sv_clean_all() / do_clean_all()
134                         SvREFCNT_dec(sv) each remaining SV, possibly
135                         triggering an sv_free(). It also sets the
136                         SVf_BREAK flag on the SV to indicate that the
137                         refcnt has been artificially lowered, and thus
138                         stopping sv_free() from giving spurious warnings
139                         about SVs which unexpectedly have a refcnt
140                         of zero.  called repeatedly from perl_destruct()
141                         until there are no SVs left.
142
143 =head2 Summary
144
145 Private API to rest of sv.c
146
147     new_SV(),  del_SV(),
148
149     new_XIV(), del_XIV(),
150     new_XNV(), del_XNV(),
151     etc
152
153 Public API:
154
155     sv_report_used(), sv_clean_objs(), sv_clean_all(), sv_free_arenas()
156
157
158 =cut
159
160 ============================================================================ */
161
162
163
164 /*
165  * "A time to plant, and a time to uproot what was planted..."
166  */
167
168
169 #ifdef DEBUG_LEAKING_SCALARS
170 #  ifdef NETWARE
171 #    define FREE_SV_DEBUG_FILE(sv) PerlMemfree((sv)->sv_debug_file)
172 #  else
173 #    define FREE_SV_DEBUG_FILE(sv) PerlMemShared_free((sv)->sv_debug_file)
174 #  endif
175 #else
176 #  define FREE_SV_DEBUG_FILE(sv)
177 #endif
178
179 #define plant_SV(p) \
180     STMT_START {                                        \
181         FREE_SV_DEBUG_FILE(p);                          \
182         SvANY(p) = (void *)PL_sv_root;                  \
183         SvFLAGS(p) = SVTYPEMASK;                        \
184         PL_sv_root = (p);                               \
185         --PL_sv_count;                                  \
186     } STMT_END
187
188 /* sv_mutex must be held while calling uproot_SV() */
189 #define uproot_SV(p) \
190     STMT_START {                                        \
191         (p) = PL_sv_root;                               \
192         PL_sv_root = (SV*)SvANY(p);                     \
193         ++PL_sv_count;                                  \
194     } STMT_END
195
196
197 /* make some more SVs by adding another arena */
198
199 /* sv_mutex must be held while calling more_sv() */
200 STATIC SV*
201 S_more_sv(pTHX)
202 {
203     SV* sv;
204
205     if (PL_nice_chunk) {
206         sv_add_arena(PL_nice_chunk, PL_nice_chunk_size, 0);
207         PL_nice_chunk = Nullch;
208         PL_nice_chunk_size = 0;
209     }
210     else {
211         char *chunk;                /* must use New here to match call to */
212         New(704,chunk,PERL_ARENA_SIZE,char);   /* Safefree() in sv_free_arenas()     */
213         sv_add_arena(chunk, PERL_ARENA_SIZE, 0);
214     }
215     uproot_SV(sv);
216     return sv;
217 }
218
219 /* new_SV(): return a new, empty SV head */
220
221 #ifdef DEBUG_LEAKING_SCALARS
222 /* provide a real function for a debugger to play with */
223 STATIC SV*
224 S_new_SV(pTHX)
225 {
226     SV* sv;
227
228     LOCK_SV_MUTEX;
229     if (PL_sv_root)
230         uproot_SV(sv);
231     else
232         sv = S_more_sv(aTHX);
233     UNLOCK_SV_MUTEX;
234     SvANY(sv) = 0;
235     SvREFCNT(sv) = 1;
236     SvFLAGS(sv) = 0;
237     sv->sv_debug_optype = PL_op ? PL_op->op_type : 0;
238     sv->sv_debug_line = (U16) ((PL_copline == NOLINE) ?
239         (PL_curcop ? CopLINE(PL_curcop) : 0) : PL_copline);
240     sv->sv_debug_inpad = 0;
241     sv->sv_debug_cloned = 0;
242 #  ifdef NETWARE
243     sv->sv_debug_file = PL_curcop ? savepv(CopFILE(PL_curcop)): NULL;
244 #  else
245     sv->sv_debug_file = PL_curcop ? savesharedpv(CopFILE(PL_curcop)): NULL;
246 #  endif
247     
248     return sv;
249 }
250 #  define new_SV(p) (p)=S_new_SV(aTHX)
251
252 #else
253 #  define new_SV(p) \
254     STMT_START {                                        \
255         LOCK_SV_MUTEX;                                  \
256         if (PL_sv_root)                                 \
257             uproot_SV(p);                               \
258         else                                            \
259             (p) = S_more_sv(aTHX);                      \
260         UNLOCK_SV_MUTEX;                                \
261         SvANY(p) = 0;                                   \
262         SvREFCNT(p) = 1;                                \
263         SvFLAGS(p) = 0;                                 \
264     } STMT_END
265 #endif
266
267
268 /* del_SV(): return an empty SV head to the free list */
269
270 #ifdef DEBUGGING
271
272 #define del_SV(p) \
273     STMT_START {                                        \
274         LOCK_SV_MUTEX;                                  \
275         if (DEBUG_D_TEST)                               \
276             del_sv(p);                                  \
277         else                                            \
278             plant_SV(p);                                \
279         UNLOCK_SV_MUTEX;                                \
280     } STMT_END
281
282 STATIC void
283 S_del_sv(pTHX_ SV *p)
284 {
285     if (DEBUG_D_TEST) {
286         SV* sva;
287         bool ok = 0;
288         for (sva = PL_sv_arenaroot; sva; sva = (SV *) SvANY(sva)) {
289             const SV * const sv = sva + 1;
290             const SV * const svend = &sva[SvREFCNT(sva)];
291             if (p >= sv && p < svend) {
292                 ok = 1;
293                 break;
294             }
295         }
296         if (!ok) {
297             if (ckWARN_d(WARN_INTERNAL))        
298                 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
299                             "Attempt to free non-arena SV: 0x%"UVxf
300                             pTHX__FORMAT, PTR2UV(p) pTHX__VALUE);
301             return;
302         }
303     }
304     plant_SV(p);
305 }
306
307 #else /* ! DEBUGGING */
308
309 #define del_SV(p)   plant_SV(p)
310
311 #endif /* DEBUGGING */
312
313
314 /*
315 =head1 SV Manipulation Functions
316
317 =for apidoc sv_add_arena
318
319 Given a chunk of memory, link it to the head of the list of arenas,
320 and split it into a list of free SVs.
321
322 =cut
323 */
324
325 void
326 Perl_sv_add_arena(pTHX_ char *ptr, U32 size, U32 flags)
327 {
328     SV* sva = (SV*)ptr;
329     register SV* sv;
330     register SV* svend;
331
332     /* The first SV in an arena isn't an SV. */
333     SvANY(sva) = (void *) PL_sv_arenaroot;              /* ptr to next arena */
334     SvREFCNT(sva) = size / sizeof(SV);          /* number of SV slots */
335     SvFLAGS(sva) = flags;                       /* FAKE if not to be freed */
336
337     PL_sv_arenaroot = sva;
338     PL_sv_root = sva + 1;
339
340     svend = &sva[SvREFCNT(sva) - 1];
341     sv = sva + 1;
342     while (sv < svend) {
343         SvANY(sv) = (void *)(SV*)(sv + 1);
344 #ifdef DEBUGGING
345         SvREFCNT(sv) = 0;
346 #endif
347         /* Must always set typemask because it's awlays checked in on cleanup
348            when the arenas are walked looking for objects.  */
349         SvFLAGS(sv) = SVTYPEMASK;
350         sv++;
351     }
352     SvANY(sv) = 0;
353 #ifdef DEBUGGING
354     SvREFCNT(sv) = 0;
355 #endif
356     SvFLAGS(sv) = SVTYPEMASK;
357 }
358
359 /* visit(): call the named function for each non-free SV in the arenas
360  * whose flags field matches the flags/mask args. */
361
362 STATIC I32
363 S_visit(pTHX_ SVFUNC_t f, U32 flags, U32 mask)
364 {
365     SV* sva;
366     I32 visited = 0;
367
368     for (sva = PL_sv_arenaroot; sva; sva = (SV*)SvANY(sva)) {
369         register const SV * const svend = &sva[SvREFCNT(sva)];
370         register SV* sv;
371         for (sv = sva + 1; sv < svend; ++sv) {
372             if (SvTYPE(sv) != SVTYPEMASK
373                     && (sv->sv_flags & mask) == flags
374                     && SvREFCNT(sv))
375             {
376                 (FCALL)(aTHX_ sv);
377                 ++visited;
378             }
379         }
380     }
381     return visited;
382 }
383
384 #ifdef DEBUGGING
385
386 /* called by sv_report_used() for each live SV */
387
388 static void
389 do_report_used(pTHX_ SV *sv)
390 {
391     if (SvTYPE(sv) != SVTYPEMASK) {
392         PerlIO_printf(Perl_debug_log, "****\n");
393         sv_dump(sv);
394     }
395 }
396 #endif
397
398 /*
399 =for apidoc sv_report_used
400
401 Dump the contents of all SVs not yet freed. (Debugging aid).
402
403 =cut
404 */
405
406 void
407 Perl_sv_report_used(pTHX)
408 {
409 #ifdef DEBUGGING
410     visit(do_report_used, 0, 0);
411 #endif
412 }
413
414 /* called by sv_clean_objs() for each live SV */
415
416 static void
417 do_clean_objs(pTHX_ SV *sv)
418 {
419     SV* rv;
420
421     if (SvROK(sv) && SvOBJECT(rv = SvRV(sv))) {
422         DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning object ref:\n "), sv_dump(sv)));
423         if (SvWEAKREF(sv)) {
424             sv_del_backref(sv);
425             SvWEAKREF_off(sv);
426             SvRV_set(sv, NULL);
427         } else {
428             SvROK_off(sv);
429             SvRV_set(sv, NULL);
430             SvREFCNT_dec(rv);
431         }
432     }
433
434     /* XXX Might want to check arrays, etc. */
435 }
436
437 /* called by sv_clean_objs() for each live SV */
438
439 #ifndef DISABLE_DESTRUCTOR_KLUDGE
440 static void
441 do_clean_named_objs(pTHX_ SV *sv)
442 {
443     if (SvTYPE(sv) == SVt_PVGV && GvGP(sv)) {
444         if ( SvOBJECT(GvSV(sv)) ||
445              (GvAV(sv) && SvOBJECT(GvAV(sv))) ||
446              (GvHV(sv) && SvOBJECT(GvHV(sv))) ||
447              (GvIO(sv) && SvOBJECT(GvIO(sv))) ||
448              (GvCV(sv) && SvOBJECT(GvCV(sv))) )
449         {
450             DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning named glob object:\n "), sv_dump(sv)));
451             SvFLAGS(sv) |= SVf_BREAK;
452             SvREFCNT_dec(sv);
453         }
454     }
455 }
456 #endif
457
458 /*
459 =for apidoc sv_clean_objs
460
461 Attempt to destroy all objects not yet freed
462
463 =cut
464 */
465
466 void
467 Perl_sv_clean_objs(pTHX)
468 {
469     PL_in_clean_objs = TRUE;
470     visit(do_clean_objs, SVf_ROK, SVf_ROK);
471 #ifndef DISABLE_DESTRUCTOR_KLUDGE
472     /* some barnacles may yet remain, clinging to typeglobs */
473     visit(do_clean_named_objs, SVt_PVGV, SVTYPEMASK);
474 #endif
475     PL_in_clean_objs = FALSE;
476 }
477
478 /* called by sv_clean_all() for each live SV */
479
480 static void
481 do_clean_all(pTHX_ SV *sv)
482 {
483     DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning loops: SV at 0x%"UVxf"\n", PTR2UV(sv)) ));
484     SvFLAGS(sv) |= SVf_BREAK;
485     if (PL_comppad == (AV*)sv) {
486         PL_comppad = Nullav;
487         PL_curpad = Null(SV**);
488     }
489     SvREFCNT_dec(sv);
490 }
491
492 /*
493 =for apidoc sv_clean_all
494
495 Decrement the refcnt of each remaining SV, possibly triggering a
496 cleanup. This function may have to be called multiple times to free
497 SVs which are in complex self-referential hierarchies.
498
499 =cut
500 */
501
502 I32
503 Perl_sv_clean_all(pTHX)
504 {
505     I32 cleaned;
506     PL_in_clean_all = TRUE;
507     cleaned = visit(do_clean_all, 0,0);
508     PL_in_clean_all = FALSE;
509     return cleaned;
510 }
511
512 /*
513 =for apidoc sv_free_arenas
514
515 Deallocate the memory used by all arenas. Note that all the individual SV
516 heads and bodies within the arenas must already have been freed.
517
518 =cut
519 */
520
521 void
522 Perl_sv_free_arenas(pTHX)
523 {
524     SV* sva;
525     SV* svanext;
526     void *arena, *arenanext;
527     int i;
528     void **arenaroots[] = {
529         (void**) &PL_xnv_arenaroot,
530         (void**) &PL_xpv_arenaroot,
531         (void**) &PL_xpviv_arenaroot,
532         (void**) &PL_xpvnv_arenaroot,
533         (void**) &PL_xpvcv_arenaroot,
534         (void**) &PL_xpvav_arenaroot,
535         (void**) &PL_xpvhv_arenaroot,
536         (void**) &PL_xpvmg_arenaroot,
537         (void**) &PL_xpvgv_arenaroot,
538         (void**) &PL_xpvlv_arenaroot,
539         (void**) &PL_xpvbm_arenaroot,
540         (void**) &PL_he_arenaroot,
541 #if defined(USE_ITHREADS)
542         (void**) &PL_pte_arenaroot,
543 #endif
544         (void**) 0
545     };
546     void **roots[] = {
547         (void**) &PL_xnv_root,
548         (void**) &PL_xpv_root,
549         (void**) &PL_xpviv_root,
550         (void**) &PL_xpvnv_root,
551         (void**) &PL_xpvcv_root,
552         (void**) &PL_xpvav_root,
553         (void**) &PL_xpvhv_root,
554         (void**) &PL_xpvmg_root,
555         (void**) &PL_xpvgv_root,
556         (void**) &PL_xpvlv_root,
557         (void**) &PL_xpvbm_root,
558         (void**) &PL_he_root,
559 #if defined(USE_ITHREADS)
560         (void**) &PL_pte_root,
561 #endif
562         (void**) 0
563     };
564
565     /* Free arenas here, but be careful about fake ones.  (We assume
566        contiguity of the fake ones with the corresponding real ones.) */
567
568     for (sva = PL_sv_arenaroot; sva; sva = svanext) {
569         svanext = (SV*) SvANY(sva);
570         while (svanext && SvFAKE(svanext))
571             svanext = (SV*) SvANY(svanext);
572
573         if (!SvFAKE(sva))
574             Safefree(sva);
575     }
576     
577     assert(sizeof(arenaroots) == sizeof(roots));
578
579     for (i=0; arenaroots[i]; i++) {
580
581         arena = *arenaroots[i];
582         for (; arena; arena = arenanext) {
583             arenanext = *(void **)arena;
584             Safefree(arena);
585         }
586         *arenaroots[i] = 0;
587         *roots[i] = 0;
588     }
589
590     if (PL_nice_chunk)
591         Safefree(PL_nice_chunk);
592     PL_nice_chunk = Nullch;
593     PL_nice_chunk_size = 0;
594     PL_sv_arenaroot = 0;
595     PL_sv_root = 0;
596 }
597
598 /* ---------------------------------------------------------------------
599  *
600  * support functions for report_uninit()
601  */
602
603 /* the maxiumum size of array or hash where we will scan looking
604  * for the undefined element that triggered the warning */
605
606 #define FUV_MAX_SEARCH_SIZE 1000
607
608 /* Look for an entry in the hash whose value has the same SV as val;
609  * If so, return a mortal copy of the key. */
610
611 STATIC SV*
612 S_find_hash_subscript(pTHX_ HV *hv, SV* val)
613 {
614     dVAR;
615     register HE **array;
616     I32 i;
617
618     if (!hv || SvMAGICAL(hv) || !HvARRAY(hv) ||
619                         (HvTOTALKEYS(hv) > FUV_MAX_SEARCH_SIZE))
620         return Nullsv;
621
622     array = HvARRAY(hv);
623
624     for (i=HvMAX(hv); i>0; i--) {
625         register HE *entry;
626         for (entry = array[i]; entry; entry = HeNEXT(entry)) {
627             if (HeVAL(entry) != val)
628                 continue;
629             if (    HeVAL(entry) == &PL_sv_undef ||
630                     HeVAL(entry) == &PL_sv_placeholder)
631                 continue;
632             if (!HeKEY(entry))
633                 return Nullsv;
634             if (HeKLEN(entry) == HEf_SVKEY)
635                 return sv_mortalcopy(HeKEY_sv(entry));
636             return sv_2mortal(newSVpvn(HeKEY(entry), HeKLEN(entry)));
637         }
638     }
639     return Nullsv;
640 }
641
642 /* Look for an entry in the array whose value has the same SV as val;
643  * If so, return the index, otherwise return -1. */
644
645 STATIC I32
646 S_find_array_subscript(pTHX_ AV *av, SV* val)
647 {
648     SV** svp;
649     I32 i;
650     if (!av || SvMAGICAL(av) || !AvARRAY(av) ||
651                         (AvFILLp(av) > FUV_MAX_SEARCH_SIZE))
652         return -1;
653
654     svp = AvARRAY(av);
655     for (i=AvFILLp(av); i>=0; i--) {
656         if (svp[i] == val && svp[i] != &PL_sv_undef)
657             return i;
658     }
659     return -1;
660 }
661
662 /* S_varname(): return the name of a variable, optionally with a subscript.
663  * If gv is non-zero, use the name of that global, along with gvtype (one
664  * of "$", "@", "%"); otherwise use the name of the lexical at pad offset
665  * targ.  Depending on the value of the subscript_type flag, return:
666  */
667
668 #define FUV_SUBSCRIPT_NONE      1       /* "@foo"          */
669 #define FUV_SUBSCRIPT_ARRAY     2       /* "$foo[aindex]"  */
670 #define FUV_SUBSCRIPT_HASH      3       /* "$foo{keyname}" */
671 #define FUV_SUBSCRIPT_WITHIN    4       /* "within @foo"   */
672
673 STATIC SV*
674 S_varname(pTHX_ GV *gv, const char *gvtype, PADOFFSET targ,
675         SV* keyname, I32 aindex, int subscript_type)
676 {
677
678     SV * const name = sv_newmortal();
679     if (gv) {
680
681         /* simulate gv_fullname4(), but add literal '^' for $^FOO names
682          * XXX get rid of all this if gv_fullnameX() ever supports this
683          * directly */
684
685         const char *p;
686         HV * const hv = GvSTASH(gv);
687         sv_setpv(name, gvtype);
688         if (!hv)
689             p = "???";
690         else if (!(p=HvNAME_get(hv)))
691             p = "__ANON__";
692         if (strNE(p, "main")) {
693             sv_catpv(name,p);
694             sv_catpvn(name,"::", 2);
695         }
696         if (GvNAMELEN(gv)>= 1 &&
697             ((unsigned int)*GvNAME(gv)) <= 26)
698         { /* handle $^FOO */
699             Perl_sv_catpvf(aTHX_ name,"^%c", *GvNAME(gv) + 'A' - 1);
700             sv_catpvn(name,GvNAME(gv)+1,GvNAMELEN(gv)-1);
701         }
702         else
703             sv_catpvn(name,GvNAME(gv),GvNAMELEN(gv));
704     }
705     else {
706         U32 unused;
707         CV * const cv = find_runcv(&unused);
708         SV *sv;
709         AV *av;
710
711         if (!cv || !CvPADLIST(cv))
712             return Nullsv;;
713         av = (AV*)(*av_fetch(CvPADLIST(cv), 0, FALSE));
714         sv = *av_fetch(av, targ, FALSE);
715         /* SvLEN in a pad name is not to be trusted */
716         sv_setpv(name, SvPV_nolen_const(sv));
717     }
718
719     if (subscript_type == FUV_SUBSCRIPT_HASH) {
720         SV *sv;
721         *SvPVX(name) = '$';
722         sv = NEWSV(0,0);
723         Perl_sv_catpvf(aTHX_ name, "{%s}",
724             pv_display(sv,SvPVX_const(keyname), SvCUR(keyname), 0, 32));
725         SvREFCNT_dec(sv);
726     }
727     else if (subscript_type == FUV_SUBSCRIPT_ARRAY) {
728         *SvPVX(name) = '$';
729         Perl_sv_catpvf(aTHX_ name, "[%"IVdf"]", (IV)aindex);
730     }
731     else if (subscript_type == FUV_SUBSCRIPT_WITHIN)
732         sv_insert(name, 0, 0,  "within ", 7);
733
734     return name;
735 }
736
737
738 /*
739 =for apidoc find_uninit_var
740
741 Find the name of the undefined variable (if any) that caused the operator o
742 to issue a "Use of uninitialized value" warning.
743 If match is true, only return a name if it's value matches uninit_sv.
744 So roughly speaking, if a unary operator (such as OP_COS) generates a
745 warning, then following the direct child of the op may yield an
746 OP_PADSV or OP_GV that gives the name of the undefined variable. On the
747 other hand, with OP_ADD there are two branches to follow, so we only print
748 the variable name if we get an exact match.
749
750 The name is returned as a mortal SV.
751
752 Assumes that PL_op is the op that originally triggered the error, and that
753 PL_comppad/PL_curpad points to the currently executing pad.
754
755 =cut
756 */
757
758 STATIC SV *
759 S_find_uninit_var(pTHX_ OP* obase, SV* uninit_sv, bool match)
760 {
761     dVAR;
762     SV *sv;
763     AV *av;
764     SV **svp;
765     GV *gv;
766     OP *o, *o2, *kid;
767
768     if (!obase || (match && (!uninit_sv || uninit_sv == &PL_sv_undef ||
769                             uninit_sv == &PL_sv_placeholder)))
770         return Nullsv;
771
772     switch (obase->op_type) {
773
774     case OP_RV2AV:
775     case OP_RV2HV:
776     case OP_PADAV:
777     case OP_PADHV:
778       {
779         const bool pad  = (obase->op_type == OP_PADAV || obase->op_type == OP_PADHV);
780         const bool hash = (obase->op_type == OP_PADHV || obase->op_type == OP_RV2HV);
781         I32 index = 0;
782         SV *keysv = Nullsv;
783         int subscript_type = FUV_SUBSCRIPT_WITHIN;
784
785         if (pad) { /* @lex, %lex */
786             sv = PAD_SVl(obase->op_targ);
787             gv = Nullgv;
788         }
789         else {
790             if (cUNOPx(obase)->op_first->op_type == OP_GV) {
791             /* @global, %global */
792                 gv = cGVOPx_gv(cUNOPx(obase)->op_first);
793                 if (!gv)
794                     break;
795                 sv = hash ? (SV*)GvHV(gv): (SV*)GvAV(gv);
796             }
797             else /* @{expr}, %{expr} */
798                 return find_uninit_var(cUNOPx(obase)->op_first,
799                                                     uninit_sv, match);
800         }
801
802         /* attempt to find a match within the aggregate */
803         if (hash) {
804             keysv = S_find_hash_subscript(aTHX_ (HV*)sv, uninit_sv);
805             if (keysv)
806                 subscript_type = FUV_SUBSCRIPT_HASH;
807         }
808         else {
809             index = S_find_array_subscript(aTHX_ (AV*)sv, uninit_sv);
810             if (index >= 0)
811                 subscript_type = FUV_SUBSCRIPT_ARRAY;
812         }
813
814         if (match && subscript_type == FUV_SUBSCRIPT_WITHIN)
815             break;
816
817         return S_varname(aTHX_ gv, hash ? "%" : "@", obase->op_targ,
818                                     keysv, index, subscript_type);
819       }
820
821     case OP_PADSV:
822         if (match && PAD_SVl(obase->op_targ) != uninit_sv)
823             break;
824         return S_varname(aTHX_ Nullgv, "$", obase->op_targ,
825                                     Nullsv, 0, FUV_SUBSCRIPT_NONE);
826
827     case OP_GVSV:
828         gv = cGVOPx_gv(obase);
829         if (!gv || (match && GvSV(gv) != uninit_sv))
830             break;
831         return S_varname(aTHX_ gv, "$", 0, Nullsv, 0, FUV_SUBSCRIPT_NONE);
832
833     case OP_AELEMFAST:
834         if (obase->op_flags & OPf_SPECIAL) { /* lexical array */
835             if (match) {
836                 av = (AV*)PAD_SV(obase->op_targ);
837                 if (!av || SvRMAGICAL(av))
838                     break;
839                 svp = av_fetch(av, (I32)obase->op_private, FALSE);
840                 if (!svp || *svp != uninit_sv)
841                     break;
842             }
843             return S_varname(aTHX_ Nullgv, "$", obase->op_targ,
844                     Nullsv, (I32)obase->op_private, FUV_SUBSCRIPT_ARRAY);
845         }
846         else {
847             gv = cGVOPx_gv(obase);
848             if (!gv)
849                 break;
850             if (match) {
851                 av = GvAV(gv);
852                 if (!av || SvRMAGICAL(av))
853                     break;
854                 svp = av_fetch(av, (I32)obase->op_private, FALSE);
855                 if (!svp || *svp != uninit_sv)
856                     break;
857             }
858             return S_varname(aTHX_ gv, "$", 0,
859                     Nullsv, (I32)obase->op_private, FUV_SUBSCRIPT_ARRAY);
860         }
861         break;
862
863     case OP_EXISTS:
864         o = cUNOPx(obase)->op_first;
865         if (!o || o->op_type != OP_NULL ||
866                 ! (o->op_targ == OP_AELEM || o->op_targ == OP_HELEM))
867             break;
868         return find_uninit_var(cBINOPo->op_last, uninit_sv, match);
869
870     case OP_AELEM:
871     case OP_HELEM:
872         if (PL_op == obase)
873             /* $a[uninit_expr] or $h{uninit_expr} */
874             return find_uninit_var(cBINOPx(obase)->op_last, uninit_sv, match);
875
876         gv = Nullgv;
877         o = cBINOPx(obase)->op_first;
878         kid = cBINOPx(obase)->op_last;
879
880         /* get the av or hv, and optionally the gv */
881         sv = Nullsv;
882         if  (o->op_type == OP_PADAV || o->op_type == OP_PADHV) {
883             sv = PAD_SV(o->op_targ);
884         }
885         else if ((o->op_type == OP_RV2AV || o->op_type == OP_RV2HV)
886                 && cUNOPo->op_first->op_type == OP_GV)
887         {
888             gv = cGVOPx_gv(cUNOPo->op_first);
889             if (!gv)
890                 break;
891             sv = o->op_type == OP_RV2HV ? (SV*)GvHV(gv) : (SV*)GvAV(gv);
892         }
893         if (!sv)
894             break;
895
896         if (kid && kid->op_type == OP_CONST && SvOK(cSVOPx_sv(kid))) {
897             /* index is constant */
898             if (match) {
899                 if (SvMAGICAL(sv))
900                     break;
901                 if (obase->op_type == OP_HELEM) {
902                     HE* he = hv_fetch_ent((HV*)sv, cSVOPx_sv(kid), 0, 0);
903                     if (!he || HeVAL(he) != uninit_sv)
904                         break;
905                 }
906                 else {
907                     svp = av_fetch((AV*)sv, SvIV(cSVOPx_sv(kid)), FALSE);
908                     if (!svp || *svp != uninit_sv)
909                         break;
910                 }
911             }
912             if (obase->op_type == OP_HELEM)
913                 return S_varname(aTHX_ gv, "%", o->op_targ,
914                             cSVOPx_sv(kid), 0, FUV_SUBSCRIPT_HASH);
915             else
916                 return S_varname(aTHX_ gv, "@", o->op_targ, Nullsv,
917                             SvIV(cSVOPx_sv(kid)), FUV_SUBSCRIPT_ARRAY);
918             ;
919         }
920         else  {
921             /* index is an expression;
922              * attempt to find a match within the aggregate */
923             if (obase->op_type == OP_HELEM) {
924                 SV * const keysv = S_find_hash_subscript(aTHX_ (HV*)sv, uninit_sv);
925                 if (keysv)
926                     return S_varname(aTHX_ gv, "%", o->op_targ,
927                                                 keysv, 0, FUV_SUBSCRIPT_HASH);
928             }
929             else {
930                 const I32 index = S_find_array_subscript(aTHX_ (AV*)sv, uninit_sv);
931                 if (index >= 0)
932                     return S_varname(aTHX_ gv, "@", o->op_targ,
933                                         Nullsv, index, FUV_SUBSCRIPT_ARRAY);
934             }
935             if (match)
936                 break;
937             return S_varname(aTHX_ gv,
938                 (o->op_type == OP_PADAV || o->op_type == OP_RV2AV)
939                 ? "@" : "%",
940                 o->op_targ, Nullsv, 0, FUV_SUBSCRIPT_WITHIN);
941         }
942
943         break;
944
945     case OP_AASSIGN:
946         /* only examine RHS */
947         return find_uninit_var(cBINOPx(obase)->op_first, uninit_sv, match);
948
949     case OP_OPEN:
950         o = cUNOPx(obase)->op_first;
951         if (o->op_type == OP_PUSHMARK)
952             o = o->op_sibling;
953
954         if (!o->op_sibling) {
955             /* one-arg version of open is highly magical */
956
957             if (o->op_type == OP_GV) { /* open FOO; */
958                 gv = cGVOPx_gv(o);
959                 if (match && GvSV(gv) != uninit_sv)
960                     break;
961                 return S_varname(aTHX_ gv, "$", 0,
962                             Nullsv, 0, FUV_SUBSCRIPT_NONE);
963             }
964             /* other possibilities not handled are:
965              * open $x; or open my $x;  should return '${*$x}'
966              * open expr;               should return '$'.expr ideally
967              */
968              break;
969         }
970         goto do_op;
971
972     /* ops where $_ may be an implicit arg */
973     case OP_TRANS:
974     case OP_SUBST:
975     case OP_MATCH:
976         if ( !(obase->op_flags & OPf_STACKED)) {
977             if (uninit_sv == ((obase->op_private & OPpTARGET_MY)
978                                  ? PAD_SVl(obase->op_targ)
979                                  : DEFSV))
980             {
981                 sv = sv_newmortal();
982                 sv_setpvn(sv, "$_", 2);
983                 return sv;
984             }
985         }
986         goto do_op;
987
988     case OP_PRTF:
989     case OP_PRINT:
990         /* skip filehandle as it can't produce 'undef' warning  */
991         o = cUNOPx(obase)->op_first;
992         if ((obase->op_flags & OPf_STACKED) && o->op_type == OP_PUSHMARK)
993             o = o->op_sibling->op_sibling;
994         goto do_op2;
995
996
997     case OP_RV2SV:
998     case OP_CUSTOM:
999     case OP_ENTERSUB:
1000         match = 1; /* XS or custom code could trigger random warnings */
1001         goto do_op;
1002
1003     case OP_SCHOMP:
1004     case OP_CHOMP:
1005         if (SvROK(PL_rs) && uninit_sv == SvRV(PL_rs))
1006             return sv_2mortal(newSVpv("${$/}", 0));
1007         /* FALL THROUGH */
1008
1009     default:
1010     do_op:
1011         if (!(obase->op_flags & OPf_KIDS))
1012             break;
1013         o = cUNOPx(obase)->op_first;
1014         
1015     do_op2:
1016         if (!o)
1017             break;
1018
1019         /* if all except one arg are constant, or have no side-effects,
1020          * or are optimized away, then it's unambiguous */
1021         o2 = Nullop;
1022         for (kid=o; kid; kid = kid->op_sibling) {
1023             if (kid &&
1024                 (    (kid->op_type == OP_CONST && SvOK(cSVOPx_sv(kid)))
1025                   || (kid->op_type == OP_NULL  && ! (kid->op_flags & OPf_KIDS))
1026                   || (kid->op_type == OP_PUSHMARK)
1027                 )
1028             )
1029                 continue;
1030             if (o2) { /* more than one found */
1031                 o2 = Nullop;
1032                 break;
1033             }
1034             o2 = kid;
1035         }
1036         if (o2)
1037             return find_uninit_var(o2, uninit_sv, match);
1038
1039         /* scan all args */
1040         while (o) {
1041             sv = find_uninit_var(o, uninit_sv, 1);
1042             if (sv)
1043                 return sv;
1044             o = o->op_sibling;
1045         }
1046         break;
1047     }
1048     return Nullsv;
1049 }
1050
1051
1052 /*
1053 =for apidoc report_uninit
1054
1055 Print appropriate "Use of uninitialized variable" warning
1056
1057 =cut
1058 */
1059
1060 void
1061 Perl_report_uninit(pTHX_ SV* uninit_sv)
1062 {
1063     if (PL_op) {
1064         SV* varname = Nullsv;
1065         if (uninit_sv) {
1066             varname = find_uninit_var(PL_op, uninit_sv,0);
1067             if (varname)
1068                 sv_insert(varname, 0, 0, " ", 1);
1069         }
1070         Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
1071                 varname ? SvPV_nolen_const(varname) : "",
1072                 " in ", OP_DESC(PL_op));
1073     }
1074     else
1075         Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
1076                     "", "", "");
1077 }
1078
1079 STATIC void *
1080 S_more_bodies (pTHX_ void **arena_root, void **root, size_t size)
1081 {
1082     char *start;
1083     const char *end;
1084     const size_t count = PERL_ARENA_SIZE/size;
1085     New(0, start, count*size, char);
1086     *((void **) start) = *arena_root;
1087     *arena_root = (void *)start;
1088
1089     end = start + (count-1) * size;
1090
1091     /* The initial slot is used to link the arenas together, so it isn't to be
1092        linked into the list of ready-to-use bodies.  */
1093
1094     start += size;
1095
1096     *root = (void *)start;
1097
1098     while (start < end) {
1099         char * const next = start + size;
1100         *(void**) start = (void *)next;
1101         start = next;
1102     }
1103     *(void **)start = 0;
1104
1105     return *root;
1106 }
1107
1108 /* grab a new thing from the free list, allocating more if necessary */
1109
1110 STATIC void *
1111 S_new_body(pTHX_ void **arena_root, void **root, size_t size)
1112 {
1113     void *xpv;
1114     LOCK_SV_MUTEX;
1115     xpv = *root ? *root : S_more_bodies(aTHX_ arena_root, root, size);
1116     *root = *(void**)xpv;
1117     UNLOCK_SV_MUTEX;
1118     return xpv;
1119 }
1120
1121 /* return a thing to the free list */
1122
1123 #define del_body(thing, root)                   \
1124     STMT_START {                                \
1125         LOCK_SV_MUTEX;                          \
1126         *(void **)thing = *root;                \
1127         *root = (void*)thing;                   \
1128         UNLOCK_SV_MUTEX;                        \
1129     } STMT_END
1130
1131 /* Conventionally we simply malloc() a big block of memory, then divide it
1132    up into lots of the thing that we're allocating.
1133
1134    This macro will expand to call to S_new_body. So for XPVBM (with ithreads),
1135    it would become
1136
1137    S_new_body(my_perl, (void**)&(my_perl->Ixpvbm_arenaroot),
1138               (void**)&(my_perl->Ixpvbm_root), sizeof(XPVBM), 0)
1139 */
1140
1141 #define new_body(TYPE,lctype)                                           \
1142     S_new_body(aTHX_ (void**)&PL_ ## lctype ## _arenaroot,              \
1143                  (void**)&PL_ ## lctype ## _root,                       \
1144                  sizeof(TYPE))
1145
1146 #define del_body_type(p,TYPE,lctype)                    \
1147     del_body((void*)p, (void**)&PL_ ## lctype ## _root)
1148
1149 /* But for some types, we cheat. The type starts with some members that are
1150    never accessed. So we allocate the substructure, starting at the first used
1151    member, then adjust the pointer back in memory by the size of the bit not
1152    allocated, so it's as if we allocated the full structure.
1153    (But things will all go boom if you write to the part that is "not there",
1154    because you'll be overwriting the last members of the preceding structure
1155    in memory.)
1156
1157    We calculate the correction using the STRUCT_OFFSET macro. For example, if
1158    xpv_allocated is the same structure as XPV then the two OFFSETs sum to zero,
1159    and the pointer is unchanged. If the allocated structure is smaller (no
1160    initial NV actually allocated) then the net effect is to subtract the size
1161    of the NV from the pointer, to return a new pointer as if an initial NV were
1162    actually allocated.
1163
1164    This is the same trick as was used for NV and IV bodies. Ironically it
1165    doesn't need to be used for NV bodies any more, because NV is now at the
1166    start of the structure. IV bodies don't need it either, because they are
1167    no longer allocated.  */
1168
1169 #define new_body_allocated(TYPE,lctype,member)                          \
1170     (void*)((char*)S_new_body(aTHX_ (void**)&PL_ ## lctype ## _arenaroot, \
1171                               (void**)&PL_ ## lctype ## _root,          \
1172                               sizeof(lctype ## _allocated)) -           \
1173                               STRUCT_OFFSET(TYPE, member)               \
1174             + STRUCT_OFFSET(lctype ## _allocated, member))
1175
1176
1177 #define del_body_allocated(p,TYPE,lctype,member)                        \
1178     del_body((void*)((char*)p + STRUCT_OFFSET(TYPE, member)             \
1179                      - STRUCT_OFFSET(lctype ## _allocated, member)),    \
1180              (void**)&PL_ ## lctype ## _root)
1181
1182 #define my_safemalloc(s)        (void*)safemalloc(s)
1183 #define my_safefree(p)  safefree((char*)p)
1184
1185 #ifdef PURIFY
1186
1187 #define new_XNV()       my_safemalloc(sizeof(XPVNV))
1188 #define del_XNV(p)      my_safefree(p)
1189
1190 #define new_XPV()       my_safemalloc(sizeof(XPV))
1191 #define del_XPV(p)      my_safefree(p)
1192
1193 #define new_XPVIV()     my_safemalloc(sizeof(XPVIV))
1194 #define del_XPVIV(p)    my_safefree(p)
1195
1196 #define new_XPVNV()     my_safemalloc(sizeof(XPVNV))
1197 #define del_XPVNV(p)    my_safefree(p)
1198
1199 #define new_XPVCV()     my_safemalloc(sizeof(XPVCV))
1200 #define del_XPVCV(p)    my_safefree(p)
1201
1202 #define new_XPVAV()     my_safemalloc(sizeof(XPVAV))
1203 #define del_XPVAV(p)    my_safefree(p)
1204
1205 #define new_XPVHV()     my_safemalloc(sizeof(XPVHV))
1206 #define del_XPVHV(p)    my_safefree(p)
1207
1208 #define new_XPVMG()     my_safemalloc(sizeof(XPVMG))
1209 #define del_XPVMG(p)    my_safefree(p)
1210
1211 #define new_XPVGV()     my_safemalloc(sizeof(XPVGV))
1212 #define del_XPVGV(p)    my_safefree(p)
1213
1214 #define new_XPVLV()     my_safemalloc(sizeof(XPVLV))
1215 #define del_XPVLV(p)    my_safefree(p)
1216
1217 #define new_XPVBM()     my_safemalloc(sizeof(XPVBM))
1218 #define del_XPVBM(p)    my_safefree(p)
1219
1220 #else /* !PURIFY */
1221
1222 #define new_XNV()       new_body(NV, xnv)
1223 #define del_XNV(p)      del_body_type(p, NV, xnv)
1224
1225 #define new_XPV()       new_body_allocated(XPV, xpv, xpv_cur)
1226 #define del_XPV(p)      del_body_allocated(p, XPV, xpv, xpv_cur)
1227
1228 #define new_XPVIV()     new_body_allocated(XPVIV, xpviv, xpv_cur)
1229 #define del_XPVIV(p)    del_body_allocated(p, XPVIV, xpviv, xpv_cur)
1230
1231 #define new_XPVNV()     new_body(XPVNV, xpvnv)
1232 #define del_XPVNV(p)    del_body_type(p, XPVNV, xpvnv)
1233
1234 #define new_XPVCV()     new_body(XPVCV, xpvcv)
1235 #define del_XPVCV(p)    del_body_type(p, XPVCV, xpvcv)
1236
1237 #define new_XPVAV()     new_body_allocated(XPVAV, xpvav, xav_fill)
1238 #define del_XPVAV(p)    del_body_allocated(p, XPVAV, xpvav, xav_fill)
1239
1240 #define new_XPVHV()     new_body_allocated(XPVHV, xpvhv, xhv_fill)
1241 #define del_XPVHV(p)    del_body_allocated(p, XPVHV, xpvhv, xhv_fill)
1242
1243 #define new_XPVMG()     new_body(XPVMG, xpvmg)
1244 #define del_XPVMG(p)    del_body_type(p, XPVMG, xpvmg)
1245
1246 #define new_XPVGV()     new_body(XPVGV, xpvgv)
1247 #define del_XPVGV(p)    del_body_type(p, XPVGV, xpvgv)
1248
1249 #define new_XPVLV()     new_body(XPVLV, xpvlv)
1250 #define del_XPVLV(p)    del_body_type(p, XPVLV, xpvlv)
1251
1252 #define new_XPVBM()     new_body(XPVBM, xpvbm)
1253 #define del_XPVBM(p)    del_body_type(p, XPVBM, xpvbm)
1254
1255 #endif /* PURIFY */
1256
1257 #define new_XPVFM()     my_safemalloc(sizeof(XPVFM))
1258 #define del_XPVFM(p)    my_safefree(p)
1259
1260 #define new_XPVIO()     my_safemalloc(sizeof(XPVIO))
1261 #define del_XPVIO(p)    my_safefree(p)
1262
1263 /*
1264 =for apidoc sv_upgrade
1265
1266 Upgrade an SV to a more complex form.  Generally adds a new body type to the
1267 SV, then copies across as much information as possible from the old body.
1268 You generally want to use the C<SvUPGRADE> macro wrapper. See also C<svtype>.
1269
1270 =cut
1271 */
1272
1273 void
1274 Perl_sv_upgrade(pTHX_ register SV *sv, U32 mt)
1275 {
1276     void**      old_body_arena;
1277     size_t      old_body_offset;
1278     size_t      old_body_length;        /* Well, the length to copy.  */
1279     void*       old_body;
1280 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1281     /* If NV 0.0 is store as all bits 0 then Zero() already creates a correct
1282        0.0 for us.  */
1283     bool        zero_nv = TRUE;
1284 #endif
1285     void*       new_body;
1286     size_t      new_body_length;
1287     size_t      new_body_offset;
1288     void**      new_body_arena;
1289     void**      new_body_arenaroot;
1290     const U32   old_type = SvTYPE(sv);
1291
1292     if (mt != SVt_PV && SvIsCOW(sv)) {
1293         sv_force_normal_flags(sv, 0);
1294     }
1295
1296     if (SvTYPE(sv) == mt)
1297         return;
1298
1299     if (SvTYPE(sv) > mt)
1300         Perl_croak(aTHX_ "sv_upgrade from type %d down to type %d",
1301                 (int)SvTYPE(sv), (int)mt);
1302
1303
1304     old_body = SvANY(sv);
1305     old_body_arena = 0;
1306     old_body_offset = 0;
1307     old_body_length = 0;
1308     new_body_offset = 0;
1309     new_body_length = ~0;
1310
1311     /* Copying structures onto other structures that have been neatly zeroed
1312        has a subtle gotcha. Consider XPVMG
1313
1314        +------+------+------+------+------+-------+-------+
1315        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |
1316        +------+------+------+------+------+-------+-------+
1317        0      4      8     12     16     20      24      28
1318
1319        where NVs are aligned to 8 bytes, so that sizeof that structure is
1320        actually 32 bytes long, with 4 bytes of padding at the end:
1321
1322        +------+------+------+------+------+-------+-------+------+
1323        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH | ???  |
1324        +------+------+------+------+------+-------+-------+------+
1325        0      4      8     12     16     20      24      28     32
1326
1327        so what happens if you allocate memory for this structure:
1328
1329        +------+------+------+------+------+-------+-------+------+------+...
1330        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |  GP  | NAME |
1331        +------+------+------+------+------+-------+-------+------+------+...
1332        0      4      8     12     16     20      24      28     32     36
1333
1334        zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
1335        expect, because you copy the area marked ??? onto GP. Now, ??? may have
1336        started out as zero once, but it's quite possible that it isn't. So now,
1337        rather than a nicely zeroed GP, you have it pointing somewhere random.
1338        Bugs ensue.
1339
1340        (In fact, GP ends up pointing at a previous GP structure, because the
1341        principle cause of the padding in XPVMG getting garbage is a copy of
1342        sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob)
1343
1344        So we are careful and work out the size of used parts of all the
1345        structures.  */
1346
1347     switch (SvTYPE(sv)) {
1348     case SVt_NULL:
1349         break;
1350     case SVt_IV:
1351         if (mt == SVt_NV)
1352             mt = SVt_PVNV;
1353         else if (mt < SVt_PVIV)
1354             mt = SVt_PVIV;
1355         old_body_offset = STRUCT_OFFSET(XPVIV, xiv_iv);
1356         old_body_length = sizeof(IV);
1357         break;
1358     case SVt_NV:
1359         old_body_arena = (void **) &PL_xnv_root;
1360         old_body_length = sizeof(NV);
1361 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1362         zero_nv = FALSE;
1363 #endif
1364         if (mt < SVt_PVNV)
1365             mt = SVt_PVNV;
1366         break;
1367     case SVt_RV:
1368         break;
1369     case SVt_PV:
1370         old_body_arena = (void **) &PL_xpv_root;
1371         old_body_offset = STRUCT_OFFSET(XPV, xpv_cur)
1372             - STRUCT_OFFSET(xpv_allocated, xpv_cur);
1373         old_body_length = STRUCT_OFFSET(XPV, xpv_len)
1374             + sizeof (((XPV*)SvANY(sv))->xpv_len)
1375             - old_body_offset;
1376         if (mt <= SVt_IV)
1377             mt = SVt_PVIV;
1378         else if (mt == SVt_NV)
1379             mt = SVt_PVNV;
1380         break;
1381     case SVt_PVIV:
1382         old_body_arena = (void **) &PL_xpviv_root;
1383         old_body_offset = STRUCT_OFFSET(XPVIV, xpv_cur)
1384             - STRUCT_OFFSET(xpviv_allocated, xpv_cur);
1385         old_body_length =  STRUCT_OFFSET(XPVIV, xiv_u)
1386             + sizeof (((XPVIV*)SvANY(sv))->xiv_u)
1387             - old_body_offset;
1388         break;
1389     case SVt_PVNV:
1390         old_body_arena = (void **) &PL_xpvnv_root;
1391         old_body_length = STRUCT_OFFSET(XPVNV, xiv_u)
1392             + sizeof (((XPVNV*)SvANY(sv))->xiv_u);
1393 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1394         zero_nv = FALSE;
1395 #endif
1396         break;
1397     case SVt_PVMG:
1398         /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1399            there's no way that it can be safely upgraded, because perl.c
1400            expects to Safefree(SvANY(PL_mess_sv))  */
1401         assert(sv != PL_mess_sv);
1402         /* This flag bit is used to mean other things in other scalar types.
1403            Given that it only has meaning inside the pad, it shouldn't be set
1404            on anything that can get upgraded.  */
1405         assert((SvFLAGS(sv) & SVpad_TYPED) == 0);
1406         old_body_arena = (void **) &PL_xpvmg_root;
1407         old_body_length = STRUCT_OFFSET(XPVMG, xmg_stash)
1408             + sizeof (((XPVMG*)SvANY(sv))->xmg_stash);
1409 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1410         zero_nv = FALSE;
1411 #endif
1412         break;
1413     default:
1414         Perl_croak(aTHX_ "Can't upgrade that kind of scalar");
1415     }
1416
1417     SvFLAGS(sv) &= ~SVTYPEMASK;
1418     SvFLAGS(sv) |= mt;
1419
1420     switch (mt) {
1421     case SVt_NULL:
1422         Perl_croak(aTHX_ "Can't upgrade to undef");
1423     case SVt_IV:
1424         assert(old_type == SVt_NULL);
1425         SvANY(sv) = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
1426         SvIV_set(sv, 0);
1427         break;
1428     case SVt_NV:
1429         assert(old_type == SVt_NULL);
1430         SvANY(sv) = new_XNV();
1431         SvNV_set(sv, 0);
1432         break;
1433     case SVt_RV:
1434         assert(old_type == SVt_NULL);
1435         SvANY(sv) = &sv->sv_u.svu_rv;
1436         SvRV_set(sv, 0);
1437         break;
1438     case SVt_PVHV:
1439         SvANY(sv) = new_XPVHV();
1440         HvFILL(sv)      = 0;
1441         HvMAX(sv)       = 0;
1442         HvTOTALKEYS(sv) = 0;
1443
1444         goto hv_av_common;
1445
1446     case SVt_PVAV:
1447         SvANY(sv) = new_XPVAV();
1448         AvMAX(sv)       = -1;
1449         AvFILLp(sv)     = -1;
1450         AvALLOC(sv)     = 0;
1451         AvREAL_only(sv);
1452
1453     hv_av_common:
1454         /* SVt_NULL isn't the only thing upgraded to AV or HV.
1455            The target created by newSVrv also is, and it can have magic.
1456            However, it never has SvPVX set.
1457         */
1458         if (old_type >= SVt_RV) {
1459             assert(SvPVX_const(sv) == 0);
1460         }
1461
1462         /* Could put this in the else clause below, as PVMG must have SvPVX
1463            0 already (the assertion above)  */
1464         SvPV_set(sv, (char*)0);
1465
1466         if (old_type >= SVt_PVMG) {
1467             SvMAGIC_set(sv, ((XPVMG*)old_body)->xmg_magic);
1468             SvSTASH_set(sv, ((XPVMG*)old_body)->xmg_stash);
1469         } else {
1470             SvMAGIC_set(sv, 0);
1471             SvSTASH_set(sv, 0);
1472         }
1473         break;
1474
1475     case SVt_PVIO:
1476         new_body = new_XPVIO();
1477         new_body_length = sizeof(XPVIO);
1478         goto zero;
1479     case SVt_PVFM:
1480         new_body = new_XPVFM();
1481         new_body_length = sizeof(XPVFM);
1482         goto zero;
1483
1484     case SVt_PVBM:
1485         new_body_length = sizeof(XPVBM);
1486         new_body_arena = (void **) &PL_xpvbm_root;
1487         new_body_arenaroot = (void **) &PL_xpvbm_arenaroot;
1488         goto new_body;
1489     case SVt_PVGV:
1490         new_body_length = sizeof(XPVGV);
1491         new_body_arena = (void **) &PL_xpvgv_root;
1492         new_body_arenaroot = (void **) &PL_xpvgv_arenaroot;
1493         goto new_body;
1494     case SVt_PVCV:
1495         new_body_length = sizeof(XPVCV);
1496         new_body_arena = (void **) &PL_xpvcv_root;
1497         new_body_arenaroot = (void **) &PL_xpvcv_arenaroot;
1498         goto new_body;
1499     case SVt_PVLV:
1500         new_body_length = sizeof(XPVLV);
1501         new_body_arena = (void **) &PL_xpvlv_root;
1502         new_body_arenaroot = (void **) &PL_xpvlv_arenaroot;
1503         goto new_body;
1504     case SVt_PVMG:
1505         new_body_length = sizeof(XPVMG);
1506         new_body_arena = (void **) &PL_xpvmg_root;
1507         new_body_arenaroot = (void **) &PL_xpvmg_arenaroot;
1508         goto new_body;
1509     case SVt_PVNV:
1510         new_body_length = sizeof(XPVNV);
1511         new_body_arena = (void **) &PL_xpvnv_root;
1512         new_body_arenaroot = (void **) &PL_xpvnv_arenaroot;
1513         goto new_body;
1514     case SVt_PVIV:
1515         new_body_offset = STRUCT_OFFSET(XPVIV, xpv_cur)
1516             - STRUCT_OFFSET(xpviv_allocated, xpv_cur);
1517         new_body_length = sizeof(XPVIV) - new_body_offset;
1518         new_body_arena = (void **) &PL_xpviv_root;
1519         new_body_arenaroot = (void **) &PL_xpviv_arenaroot;
1520         /* XXX Is this still needed?  Was it ever needed?   Surely as there is
1521            no route from NV to PVIV, NOK can never be true  */
1522         if (SvNIOK(sv))
1523             (void)SvIOK_on(sv);
1524         SvNOK_off(sv);
1525         goto new_body_no_NV; 
1526     case SVt_PV:
1527         new_body_offset = STRUCT_OFFSET(XPV, xpv_cur)
1528             - STRUCT_OFFSET(xpv_allocated, xpv_cur);
1529         new_body_length = sizeof(XPV) - new_body_offset;
1530         new_body_arena = (void **) &PL_xpv_root;
1531         new_body_arenaroot = (void **) &PL_xpv_arenaroot;
1532     new_body_no_NV:
1533         /* PV and PVIV don't have an NV slot.  */
1534 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1535         zero_nv = FALSE;
1536 #endif
1537
1538     new_body:
1539         assert(new_body_length);
1540 #ifndef PURIFY
1541         /* This points to the start of the allocated area.  */
1542         new_body = S_new_body(aTHX_ new_body_arenaroot, new_body_arena,
1543                               new_body_length);
1544 #else
1545         /* We always allocated the full length item with PURIFY */
1546         new_body_length += new_body_offset;
1547         new_body_offset = 0;
1548         new_body = my_safemalloc(new_body_length);
1549
1550 #endif
1551     zero:
1552         Zero(new_body, new_body_length, char);
1553         new_body = ((char *)new_body) - new_body_offset;
1554         SvANY(sv) = new_body;
1555
1556         if (old_body_length) {
1557             Copy((char *)old_body + old_body_offset,
1558                  (char *)new_body + old_body_offset,
1559                  old_body_length, char);
1560         }
1561
1562 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1563         if (zero_nv)
1564             SvNV_set(sv, 0);
1565 #endif
1566
1567         if (mt == SVt_PVIO)
1568             IoPAGE_LEN(sv)      = 60;
1569         if (old_type < SVt_RV)
1570             SvPV_set(sv, 0);
1571         break;
1572     default:
1573         Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu", mt);
1574     }
1575
1576
1577     if (old_body_arena) {
1578 #ifdef PURIFY
1579         my_safefree(old_body);
1580 #else
1581         del_body((void*)((char*)old_body + old_body_offset),
1582                  old_body_arena);
1583 #endif
1584     }
1585 }
1586
1587 /*
1588 =for apidoc sv_backoff
1589
1590 Remove any string offset. You should normally use the C<SvOOK_off> macro
1591 wrapper instead.
1592
1593 =cut
1594 */
1595
1596 int
1597 Perl_sv_backoff(pTHX_ register SV *sv)
1598 {
1599     assert(SvOOK(sv));
1600     assert(SvTYPE(sv) != SVt_PVHV);
1601     assert(SvTYPE(sv) != SVt_PVAV);
1602     if (SvIVX(sv)) {
1603         const char * const s = SvPVX_const(sv);
1604         SvLEN_set(sv, SvLEN(sv) + SvIVX(sv));
1605         SvPV_set(sv, SvPVX(sv) - SvIVX(sv));
1606         SvIV_set(sv, 0);
1607         Move(s, SvPVX(sv), SvCUR(sv)+1, char);
1608     }
1609     SvFLAGS(sv) &= ~SVf_OOK;
1610     return 0;
1611 }
1612
1613 /*
1614 =for apidoc sv_grow
1615
1616 Expands the character buffer in the SV.  If necessary, uses C<sv_unref> and
1617 upgrades the SV to C<SVt_PV>.  Returns a pointer to the character buffer.
1618 Use the C<SvGROW> wrapper instead.
1619
1620 =cut
1621 */
1622
1623 char *
1624 Perl_sv_grow(pTHX_ register SV *sv, register STRLEN newlen)
1625 {
1626     register char *s;
1627
1628 #ifdef HAS_64K_LIMIT
1629     if (newlen >= 0x10000) {
1630         PerlIO_printf(Perl_debug_log,
1631                       "Allocation too large: %"UVxf"\n", (UV)newlen);
1632         my_exit(1);
1633     }
1634 #endif /* HAS_64K_LIMIT */
1635     if (SvROK(sv))
1636         sv_unref(sv);
1637     if (SvTYPE(sv) < SVt_PV) {
1638         sv_upgrade(sv, SVt_PV);
1639         s = SvPVX_mutable(sv);
1640     }
1641     else if (SvOOK(sv)) {       /* pv is offset? */
1642         sv_backoff(sv);
1643         s = SvPVX_mutable(sv);
1644         if (newlen > SvLEN(sv))
1645             newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1646 #ifdef HAS_64K_LIMIT
1647         if (newlen >= 0x10000)
1648             newlen = 0xFFFF;
1649 #endif
1650     }
1651     else
1652         s = SvPVX_mutable(sv);
1653
1654     if (newlen > SvLEN(sv)) {           /* need more room? */
1655         newlen = PERL_STRLEN_ROUNDUP(newlen);
1656         if (SvLEN(sv) && s) {
1657 #ifdef MYMALLOC
1658             const STRLEN l = malloced_size((void*)SvPVX_const(sv));
1659             if (newlen <= l) {
1660                 SvLEN_set(sv, l);
1661                 return s;
1662             } else
1663 #endif
1664             s = saferealloc(s, newlen);
1665         }
1666         else {
1667             s = safemalloc(newlen);
1668             if (SvPVX_const(sv) && SvCUR(sv)) {
1669                 Move(SvPVX_const(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1670             }
1671         }
1672         SvPV_set(sv, s);
1673         SvLEN_set(sv, newlen);
1674     }
1675     return s;
1676 }
1677
1678 /*
1679 =for apidoc sv_setiv
1680
1681 Copies an integer into the given SV, upgrading first if necessary.
1682 Does not handle 'set' magic.  See also C<sv_setiv_mg>.
1683
1684 =cut
1685 */
1686
1687 void
1688 Perl_sv_setiv(pTHX_ register SV *sv, IV i)
1689 {
1690     SV_CHECK_THINKFIRST_COW_DROP(sv);
1691     switch (SvTYPE(sv)) {
1692     case SVt_NULL:
1693         sv_upgrade(sv, SVt_IV);
1694         break;
1695     case SVt_NV:
1696         sv_upgrade(sv, SVt_PVNV);
1697         break;
1698     case SVt_RV:
1699     case SVt_PV:
1700         sv_upgrade(sv, SVt_PVIV);
1701         break;
1702
1703     case SVt_PVGV:
1704     case SVt_PVAV:
1705     case SVt_PVHV:
1706     case SVt_PVCV:
1707     case SVt_PVFM:
1708     case SVt_PVIO:
1709         Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1710                    OP_DESC(PL_op));
1711     }
1712     (void)SvIOK_only(sv);                       /* validate number */
1713     SvIV_set(sv, i);
1714     SvTAINT(sv);
1715 }
1716
1717 /*
1718 =for apidoc sv_setiv_mg
1719
1720 Like C<sv_setiv>, but also handles 'set' magic.
1721
1722 =cut
1723 */
1724
1725 void
1726 Perl_sv_setiv_mg(pTHX_ register SV *sv, IV i)
1727 {
1728     sv_setiv(sv,i);
1729     SvSETMAGIC(sv);
1730 }
1731
1732 /*
1733 =for apidoc sv_setuv
1734
1735 Copies an unsigned integer into the given SV, upgrading first if necessary.
1736 Does not handle 'set' magic.  See also C<sv_setuv_mg>.
1737
1738 =cut
1739 */
1740
1741 void
1742 Perl_sv_setuv(pTHX_ register SV *sv, UV u)
1743 {
1744     /* With these two if statements:
1745        u=1.49  s=0.52  cu=72.49  cs=10.64  scripts=270  tests=20865
1746
1747        without
1748        u=1.35  s=0.47  cu=73.45  cs=11.43  scripts=270  tests=20865
1749
1750        If you wish to remove them, please benchmark to see what the effect is
1751     */
1752     if (u <= (UV)IV_MAX) {
1753        sv_setiv(sv, (IV)u);
1754        return;
1755     }
1756     sv_setiv(sv, 0);
1757     SvIsUV_on(sv);
1758     SvUV_set(sv, u);
1759 }
1760
1761 /*
1762 =for apidoc sv_setuv_mg
1763
1764 Like C<sv_setuv>, but also handles 'set' magic.
1765
1766 =cut
1767 */
1768
1769 void
1770 Perl_sv_setuv_mg(pTHX_ register SV *sv, UV u)
1771 {
1772     /* With these two if statements:
1773        u=1.49  s=0.52  cu=72.49  cs=10.64  scripts=270  tests=20865
1774
1775        without
1776        u=1.35  s=0.47  cu=73.45  cs=11.43  scripts=270  tests=20865
1777
1778        If you wish to remove them, please benchmark to see what the effect is
1779     */
1780     if (u <= (UV)IV_MAX) {
1781        sv_setiv(sv, (IV)u);
1782     } else {
1783        sv_setiv(sv, 0);
1784        SvIsUV_on(sv);
1785        sv_setuv(sv,u);
1786     }
1787     SvSETMAGIC(sv);
1788 }
1789
1790 /*
1791 =for apidoc sv_setnv
1792
1793 Copies a double into the given SV, upgrading first if necessary.
1794 Does not handle 'set' magic.  See also C<sv_setnv_mg>.
1795
1796 =cut
1797 */
1798
1799 void
1800 Perl_sv_setnv(pTHX_ register SV *sv, NV num)
1801 {
1802     SV_CHECK_THINKFIRST_COW_DROP(sv);
1803     switch (SvTYPE(sv)) {
1804     case SVt_NULL:
1805     case SVt_IV:
1806         sv_upgrade(sv, SVt_NV);
1807         break;
1808     case SVt_RV:
1809     case SVt_PV:
1810     case SVt_PVIV:
1811         sv_upgrade(sv, SVt_PVNV);
1812         break;
1813
1814     case SVt_PVGV:
1815     case SVt_PVAV:
1816     case SVt_PVHV:
1817     case SVt_PVCV:
1818     case SVt_PVFM:
1819     case SVt_PVIO:
1820         Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
1821                    OP_NAME(PL_op));
1822     }
1823     SvNV_set(sv, num);
1824     (void)SvNOK_only(sv);                       /* validate number */
1825     SvTAINT(sv);
1826 }
1827
1828 /*
1829 =for apidoc sv_setnv_mg
1830
1831 Like C<sv_setnv>, but also handles 'set' magic.
1832
1833 =cut
1834 */
1835
1836 void
1837 Perl_sv_setnv_mg(pTHX_ register SV *sv, NV num)
1838 {
1839     sv_setnv(sv,num);
1840     SvSETMAGIC(sv);
1841 }
1842
1843 /* Print an "isn't numeric" warning, using a cleaned-up,
1844  * printable version of the offending string
1845  */
1846
1847 STATIC void
1848 S_not_a_number(pTHX_ SV *sv)
1849 {
1850      SV *dsv;
1851      char tmpbuf[64];
1852      char *pv;
1853
1854      if (DO_UTF8(sv)) {
1855           dsv = sv_2mortal(newSVpv("", 0));
1856           pv = sv_uni_display(dsv, sv, 10, 0);
1857      } else {
1858           char *d = tmpbuf;
1859           char *limit = tmpbuf + sizeof(tmpbuf) - 8;
1860           /* each *s can expand to 4 chars + "...\0",
1861              i.e. need room for 8 chars */
1862         
1863           const char *s, *end;
1864           for (s = SvPVX_const(sv), end = s + SvCUR(sv); s < end && d < limit;
1865                s++) {
1866                int ch = *s & 0xFF;
1867                if (ch & 128 && !isPRINT_LC(ch)) {
1868                     *d++ = 'M';
1869                     *d++ = '-';
1870                     ch &= 127;
1871                }
1872                if (ch == '\n') {
1873                     *d++ = '\\';
1874                     *d++ = 'n';
1875                }
1876                else if (ch == '\r') {
1877                     *d++ = '\\';
1878                     *d++ = 'r';
1879                }
1880                else if (ch == '\f') {
1881                     *d++ = '\\';
1882                     *d++ = 'f';
1883                }
1884                else if (ch == '\\') {
1885                     *d++ = '\\';
1886                     *d++ = '\\';
1887                }
1888                else if (ch == '\0') {
1889                     *d++ = '\\';
1890                     *d++ = '0';
1891                }
1892                else if (isPRINT_LC(ch))
1893                     *d++ = ch;
1894                else {
1895                     *d++ = '^';
1896                     *d++ = toCTRL(ch);
1897                }
1898           }
1899           if (s < end) {
1900                *d++ = '.';
1901                *d++ = '.';
1902                *d++ = '.';
1903           }
1904           *d = '\0';
1905           pv = tmpbuf;
1906     }
1907
1908     if (PL_op)
1909         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1910                     "Argument \"%s\" isn't numeric in %s", pv,
1911                     OP_DESC(PL_op));
1912     else
1913         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1914                     "Argument \"%s\" isn't numeric", pv);
1915 }
1916
1917 /*
1918 =for apidoc looks_like_number
1919
1920 Test if the content of an SV looks like a number (or is a number).
1921 C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1922 non-numeric warning), even if your atof() doesn't grok them.
1923
1924 =cut
1925 */
1926
1927 I32
1928 Perl_looks_like_number(pTHX_ SV *sv)
1929 {
1930     register const char *sbegin;
1931     STRLEN len;
1932
1933     if (SvPOK(sv)) {
1934         sbegin = SvPVX_const(sv);
1935         len = SvCUR(sv);
1936     }
1937     else if (SvPOKp(sv))
1938         sbegin = SvPV_const(sv, len);
1939     else
1940         return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
1941     return grok_number(sbegin, len, NULL);
1942 }
1943
1944 /* Actually, ISO C leaves conversion of UV to IV undefined, but
1945    until proven guilty, assume that things are not that bad... */
1946
1947 /*
1948    NV_PRESERVES_UV:
1949
1950    As 64 bit platforms often have an NV that doesn't preserve all bits of
1951    an IV (an assumption perl has been based on to date) it becomes necessary
1952    to remove the assumption that the NV always carries enough precision to
1953    recreate the IV whenever needed, and that the NV is the canonical form.
1954    Instead, IV/UV and NV need to be given equal rights. So as to not lose
1955    precision as a side effect of conversion (which would lead to insanity
1956    and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1957    1) to distinguish between IV/UV/NV slots that have cached a valid
1958       conversion where precision was lost and IV/UV/NV slots that have a
1959       valid conversion which has lost no precision
1960    2) to ensure that if a numeric conversion to one form is requested that
1961       would lose precision, the precise conversion (or differently
1962       imprecise conversion) is also performed and cached, to prevent
1963       requests for different numeric formats on the same SV causing
1964       lossy conversion chains. (lossless conversion chains are perfectly
1965       acceptable (still))
1966
1967
1968    flags are used:
1969    SvIOKp is true if the IV slot contains a valid value
1970    SvIOK  is true only if the IV value is accurate (UV if SvIOK_UV true)
1971    SvNOKp is true if the NV slot contains a valid value
1972    SvNOK  is true only if the NV value is accurate
1973
1974    so
1975    while converting from PV to NV, check to see if converting that NV to an
1976    IV(or UV) would lose accuracy over a direct conversion from PV to
1977    IV(or UV). If it would, cache both conversions, return NV, but mark
1978    SV as IOK NOKp (ie not NOK).
1979
1980    While converting from PV to IV, check to see if converting that IV to an
1981    NV would lose accuracy over a direct conversion from PV to NV. If it
1982    would, cache both conversions, flag similarly.
1983
1984    Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1985    correctly because if IV & NV were set NV *always* overruled.
1986    Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1987    changes - now IV and NV together means that the two are interchangeable:
1988    SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
1989
1990    The benefit of this is that operations such as pp_add know that if
1991    SvIOK is true for both left and right operands, then integer addition
1992    can be used instead of floating point (for cases where the result won't
1993    overflow). Before, floating point was always used, which could lead to
1994    loss of precision compared with integer addition.
1995
1996    * making IV and NV equal status should make maths accurate on 64 bit
1997      platforms
1998    * may speed up maths somewhat if pp_add and friends start to use
1999      integers when possible instead of fp. (Hopefully the overhead in
2000      looking for SvIOK and checking for overflow will not outweigh the
2001      fp to integer speedup)
2002    * will slow down integer operations (callers of SvIV) on "inaccurate"
2003      values, as the change from SvIOK to SvIOKp will cause a call into
2004      sv_2iv each time rather than a macro access direct to the IV slot
2005    * should speed up number->string conversion on integers as IV is
2006      favoured when IV and NV are equally accurate
2007
2008    ####################################################################
2009    You had better be using SvIOK_notUV if you want an IV for arithmetic:
2010    SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
2011    On the other hand, SvUOK is true iff UV.
2012    ####################################################################
2013
2014    Your mileage will vary depending your CPU's relative fp to integer
2015    performance ratio.
2016 */
2017
2018 #ifndef NV_PRESERVES_UV
2019 #  define IS_NUMBER_UNDERFLOW_IV 1
2020 #  define IS_NUMBER_UNDERFLOW_UV 2
2021 #  define IS_NUMBER_IV_AND_UV    2
2022 #  define IS_NUMBER_OVERFLOW_IV  4
2023 #  define IS_NUMBER_OVERFLOW_UV  5
2024
2025 /* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
2026
2027 /* For sv_2nv these three cases are "SvNOK and don't bother casting"  */
2028 STATIC int
2029 S_sv_2iuv_non_preserve(pTHX_ register SV *sv, I32 numtype)
2030 {
2031     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));
2032     if (SvNVX(sv) < (NV)IV_MIN) {
2033         (void)SvIOKp_on(sv);
2034         (void)SvNOK_on(sv);
2035         SvIV_set(sv, IV_MIN);
2036         return IS_NUMBER_UNDERFLOW_IV;
2037     }
2038     if (SvNVX(sv) > (NV)UV_MAX) {
2039         (void)SvIOKp_on(sv);
2040         (void)SvNOK_on(sv);
2041         SvIsUV_on(sv);
2042         SvUV_set(sv, UV_MAX);
2043         return IS_NUMBER_OVERFLOW_UV;
2044     }
2045     (void)SvIOKp_on(sv);
2046     (void)SvNOK_on(sv);
2047     /* Can't use strtol etc to convert this string.  (See truth table in
2048        sv_2iv  */
2049     if (SvNVX(sv) <= (UV)IV_MAX) {
2050         SvIV_set(sv, I_V(SvNVX(sv)));
2051         if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2052             SvIOK_on(sv); /* Integer is precise. NOK, IOK */
2053         } else {
2054             /* Integer is imprecise. NOK, IOKp */
2055         }
2056         return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
2057     }
2058     SvIsUV_on(sv);
2059     SvUV_set(sv, U_V(SvNVX(sv)));
2060     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2061         if (SvUVX(sv) == UV_MAX) {
2062             /* As we know that NVs don't preserve UVs, UV_MAX cannot
2063                possibly be preserved by NV. Hence, it must be overflow.
2064                NOK, IOKp */
2065             return IS_NUMBER_OVERFLOW_UV;
2066         }
2067         SvIOK_on(sv); /* Integer is precise. NOK, UOK */
2068     } else {
2069         /* Integer is imprecise. NOK, IOKp */
2070     }
2071     return IS_NUMBER_OVERFLOW_IV;
2072 }
2073 #endif /* !NV_PRESERVES_UV*/
2074
2075 /* sv_2iv() is now a macro using Perl_sv_2iv_flags();
2076  * this function provided for binary compatibility only
2077  */
2078
2079 IV
2080 Perl_sv_2iv(pTHX_ register SV *sv)
2081 {
2082     return sv_2iv_flags(sv, SV_GMAGIC);
2083 }
2084
2085 /*
2086 =for apidoc sv_2iv_flags
2087
2088 Return the integer value of an SV, doing any necessary string
2089 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2090 Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2091
2092 =cut
2093 */
2094
2095 IV
2096 Perl_sv_2iv_flags(pTHX_ register SV *sv, I32 flags)
2097 {
2098     if (!sv)
2099         return 0;
2100     if (SvGMAGICAL(sv)) {
2101         if (flags & SV_GMAGIC)
2102             mg_get(sv);
2103         if (SvIOKp(sv))
2104             return SvIVX(sv);
2105         if (SvNOKp(sv)) {
2106             return I_V(SvNVX(sv));
2107         }
2108         if (SvPOKp(sv) && SvLEN(sv))
2109             return asIV(sv);
2110         if (!SvROK(sv)) {
2111             if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2112                 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2113                     report_uninit(sv);
2114             }
2115             return 0;
2116         }
2117     }
2118     if (SvTHINKFIRST(sv)) {
2119         if (SvROK(sv)) {
2120           SV* tmpstr;
2121           if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,numer)) &&
2122                 (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv))))
2123               return SvIV(tmpstr);
2124           return PTR2IV(SvRV(sv));
2125         }
2126         if (SvIsCOW(sv)) {
2127             sv_force_normal_flags(sv, 0);
2128         }
2129         if (SvREADONLY(sv) && !SvOK(sv)) {
2130             if (ckWARN(WARN_UNINITIALIZED))
2131                 report_uninit(sv);
2132             return 0;
2133         }
2134     }
2135     if (SvIOKp(sv)) {
2136         if (SvIsUV(sv)) {
2137             return (IV)(SvUVX(sv));
2138         }
2139         else {
2140             return SvIVX(sv);
2141         }
2142     }
2143     if (SvNOKp(sv)) {
2144         /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
2145          * without also getting a cached IV/UV from it at the same time
2146          * (ie PV->NV conversion should detect loss of accuracy and cache
2147          * IV or UV at same time to avoid this.  NWC */
2148
2149         if (SvTYPE(sv) == SVt_NV)
2150             sv_upgrade(sv, SVt_PVNV);
2151
2152         (void)SvIOKp_on(sv);    /* Must do this first, to clear any SvOOK */
2153         /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
2154            certainly cast into the IV range at IV_MAX, whereas the correct
2155            answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
2156            cases go to UV */
2157         if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2158             SvIV_set(sv, I_V(SvNVX(sv)));
2159             if (SvNVX(sv) == (NV) SvIVX(sv)
2160 #ifndef NV_PRESERVES_UV
2161                 && (((UV)1 << NV_PRESERVES_UV_BITS) >
2162                     (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2163                 /* Don't flag it as "accurately an integer" if the number
2164                    came from a (by definition imprecise) NV operation, and
2165                    we're outside the range of NV integer precision */
2166 #endif
2167                 ) {
2168                 SvIOK_on(sv);  /* Can this go wrong with rounding? NWC */
2169                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2170                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
2171                                       PTR2UV(sv),
2172                                       SvNVX(sv),
2173                                       SvIVX(sv)));
2174
2175             } else {
2176                 /* IV not precise.  No need to convert from PV, as NV
2177                    conversion would already have cached IV if it detected
2178                    that PV->IV would be better than PV->NV->IV
2179                    flags already correct - don't set public IOK.  */
2180                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2181                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
2182                                       PTR2UV(sv),
2183                                       SvNVX(sv),
2184                                       SvIVX(sv)));
2185             }
2186             /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2187                but the cast (NV)IV_MIN rounds to a the value less (more
2188                negative) than IV_MIN which happens to be equal to SvNVX ??
2189                Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2190                NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2191                (NV)UVX == NVX are both true, but the values differ. :-(
2192                Hopefully for 2s complement IV_MIN is something like
2193                0x8000000000000000 which will be exact. NWC */
2194         }
2195         else {
2196             SvUV_set(sv, U_V(SvNVX(sv)));
2197             if (
2198                 (SvNVX(sv) == (NV) SvUVX(sv))
2199 #ifndef  NV_PRESERVES_UV
2200                 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2201                 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2202                 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2203                 /* Don't flag it as "accurately an integer" if the number
2204                    came from a (by definition imprecise) NV operation, and
2205                    we're outside the range of NV integer precision */
2206 #endif
2207                 )
2208                 SvIOK_on(sv);
2209             SvIsUV_on(sv);
2210           ret_iv_max:
2211             DEBUG_c(PerlIO_printf(Perl_debug_log,
2212                                   "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
2213                                   PTR2UV(sv),
2214                                   SvUVX(sv),
2215                                   SvUVX(sv)));
2216             return (IV)SvUVX(sv);
2217         }
2218     }
2219     else if (SvPOKp(sv) && SvLEN(sv)) {
2220         UV value;
2221         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2222         /* We want to avoid a possible problem when we cache an IV which
2223            may be later translated to an NV, and the resulting NV is not
2224            the same as the direct translation of the initial string
2225            (eg 123.456 can shortcut to the IV 123 with atol(), but we must
2226            be careful to ensure that the value with the .456 is around if the
2227            NV value is requested in the future).
2228         
2229            This means that if we cache such an IV, we need to cache the
2230            NV as well.  Moreover, we trade speed for space, and do not
2231            cache the NV if we are sure it's not needed.
2232          */
2233
2234         /* SVt_PVNV is one higher than SVt_PVIV, hence this order  */
2235         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2236              == IS_NUMBER_IN_UV) {
2237             /* It's definitely an integer, only upgrade to PVIV */
2238             if (SvTYPE(sv) < SVt_PVIV)
2239                 sv_upgrade(sv, SVt_PVIV);
2240             (void)SvIOK_on(sv);
2241         } else if (SvTYPE(sv) < SVt_PVNV)
2242             sv_upgrade(sv, SVt_PVNV);
2243
2244         /* If NV preserves UV then we only use the UV value if we know that
2245            we aren't going to call atof() below. If NVs don't preserve UVs
2246            then the value returned may have more precision than atof() will
2247            return, even though value isn't perfectly accurate.  */
2248         if ((numtype & (IS_NUMBER_IN_UV
2249 #ifdef NV_PRESERVES_UV
2250                         | IS_NUMBER_NOT_INT
2251 #endif
2252             )) == IS_NUMBER_IN_UV) {
2253             /* This won't turn off the public IOK flag if it was set above  */
2254             (void)SvIOKp_on(sv);
2255
2256             if (!(numtype & IS_NUMBER_NEG)) {
2257                 /* positive */;
2258                 if (value <= (UV)IV_MAX) {
2259                     SvIV_set(sv, (IV)value);
2260                 } else {
2261                     SvUV_set(sv, value);
2262                     SvIsUV_on(sv);
2263                 }
2264             } else {
2265                 /* 2s complement assumption  */
2266                 if (value <= (UV)IV_MIN) {
2267                     SvIV_set(sv, -(IV)value);
2268                 } else {
2269                     /* Too negative for an IV.  This is a double upgrade, but
2270                        I'm assuming it will be rare.  */
2271                     if (SvTYPE(sv) < SVt_PVNV)
2272                         sv_upgrade(sv, SVt_PVNV);
2273                     SvNOK_on(sv);
2274                     SvIOK_off(sv);
2275                     SvIOKp_on(sv);
2276                     SvNV_set(sv, -(NV)value);
2277                     SvIV_set(sv, IV_MIN);
2278                 }
2279             }
2280         }
2281         /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2282            will be in the previous block to set the IV slot, and the next
2283            block to set the NV slot.  So no else here.  */
2284         
2285         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2286             != IS_NUMBER_IN_UV) {
2287             /* It wasn't an (integer that doesn't overflow the UV). */
2288             SvNV_set(sv, Atof(SvPVX_const(sv)));
2289
2290             if (! numtype && ckWARN(WARN_NUMERIC))
2291                 not_a_number(sv);
2292
2293 #if defined(USE_LONG_DOUBLE)
2294             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" PERL_PRIgldbl ")\n",
2295                                   PTR2UV(sv), SvNVX(sv)));
2296 #else
2297             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"NVgf")\n",
2298                                   PTR2UV(sv), SvNVX(sv)));
2299 #endif
2300
2301
2302 #ifdef NV_PRESERVES_UV
2303             (void)SvIOKp_on(sv);
2304             (void)SvNOK_on(sv);
2305             if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2306                 SvIV_set(sv, I_V(SvNVX(sv)));
2307                 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2308                     SvIOK_on(sv);
2309                 } else {
2310                     /* Integer is imprecise. NOK, IOKp */
2311                 }
2312                 /* UV will not work better than IV */
2313             } else {
2314                 if (SvNVX(sv) > (NV)UV_MAX) {
2315                     SvIsUV_on(sv);
2316                     /* Integer is inaccurate. NOK, IOKp, is UV */
2317                     SvUV_set(sv, UV_MAX);
2318                     SvIsUV_on(sv);
2319                 } else {
2320                     SvUV_set(sv, U_V(SvNVX(sv)));
2321                     /* 0xFFFFFFFFFFFFFFFF not an issue in here */
2322                     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2323                         SvIOK_on(sv);
2324                         SvIsUV_on(sv);
2325                     } else {
2326                         /* Integer is imprecise. NOK, IOKp, is UV */
2327                         SvIsUV_on(sv);
2328                     }
2329                 }
2330                 goto ret_iv_max;
2331             }
2332 #else /* NV_PRESERVES_UV */
2333             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2334                 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2335                 /* The IV slot will have been set from value returned by
2336                    grok_number above.  The NV slot has just been set using
2337                    Atof.  */
2338                 SvNOK_on(sv);
2339                 assert (SvIOKp(sv));
2340             } else {
2341                 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2342                     U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2343                     /* Small enough to preserve all bits. */
2344                     (void)SvIOKp_on(sv);
2345                     SvNOK_on(sv);
2346                     SvIV_set(sv, I_V(SvNVX(sv)));
2347                     if ((NV)(SvIVX(sv)) == SvNVX(sv))
2348                         SvIOK_on(sv);
2349                     /* Assumption: first non-preserved integer is < IV_MAX,
2350                        this NV is in the preserved range, therefore: */
2351                     if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2352                           < (UV)IV_MAX)) {
2353                         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);
2354                     }
2355                 } else {
2356                     /* IN_UV NOT_INT
2357                          0      0       already failed to read UV.
2358                          0      1       already failed to read UV.
2359                          1      0       you won't get here in this case. IV/UV
2360                                         slot set, public IOK, Atof() unneeded.
2361                          1      1       already read UV.
2362                        so there's no point in sv_2iuv_non_preserve() attempting
2363                        to use atol, strtol, strtoul etc.  */
2364                     if (sv_2iuv_non_preserve (sv, numtype)
2365                         >= IS_NUMBER_OVERFLOW_IV)
2366                     goto ret_iv_max;
2367                 }
2368             }
2369 #endif /* NV_PRESERVES_UV */
2370         }
2371     } else  {
2372         if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP))
2373             report_uninit(sv);
2374         if (SvTYPE(sv) < SVt_IV)
2375             /* Typically the caller expects that sv_any is not NULL now.  */
2376             sv_upgrade(sv, SVt_IV);
2377         return 0;
2378     }
2379     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2380         PTR2UV(sv),SvIVX(sv)));
2381     return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
2382 }
2383
2384 /* sv_2uv() is now a macro using Perl_sv_2uv_flags();
2385  * this function provided for binary compatibility only
2386  */
2387
2388 UV
2389 Perl_sv_2uv(pTHX_ register SV *sv)
2390 {
2391     return sv_2uv_flags(sv, SV_GMAGIC);
2392 }
2393
2394 /*
2395 =for apidoc sv_2uv_flags
2396
2397 Return the unsigned integer value of an SV, doing any necessary string
2398 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2399 Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
2400
2401 =cut
2402 */
2403
2404 UV
2405 Perl_sv_2uv_flags(pTHX_ register SV *sv, I32 flags)
2406 {
2407     if (!sv)
2408         return 0;
2409     if (SvGMAGICAL(sv)) {
2410         if (flags & SV_GMAGIC)
2411             mg_get(sv);
2412         if (SvIOKp(sv))
2413             return SvUVX(sv);
2414         if (SvNOKp(sv))
2415             return U_V(SvNVX(sv));
2416         if (SvPOKp(sv) && SvLEN(sv))
2417             return asUV(sv);
2418         if (!SvROK(sv)) {
2419             if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2420                 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2421                     report_uninit(sv);
2422             }
2423             return 0;
2424         }
2425     }
2426     if (SvTHINKFIRST(sv)) {
2427         if (SvROK(sv)) {
2428           SV* tmpstr;
2429           if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,numer)) &&
2430                 (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv))))
2431               return SvUV(tmpstr);
2432           return PTR2UV(SvRV(sv));
2433         }
2434         if (SvIsCOW(sv)) {
2435             sv_force_normal_flags(sv, 0);
2436         }
2437         if (SvREADONLY(sv) && !SvOK(sv)) {
2438             if (ckWARN(WARN_UNINITIALIZED))
2439                 report_uninit(sv);
2440             return 0;
2441         }
2442     }
2443     if (SvIOKp(sv)) {
2444         if (SvIsUV(sv)) {
2445             return SvUVX(sv);
2446         }
2447         else {
2448             return (UV)SvIVX(sv);
2449         }
2450     }
2451     if (SvNOKp(sv)) {
2452         /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
2453          * without also getting a cached IV/UV from it at the same time
2454          * (ie PV->NV conversion should detect loss of accuracy and cache
2455          * IV or UV at same time to avoid this. */
2456         /* IV-over-UV optimisation - choose to cache IV if possible */
2457
2458         if (SvTYPE(sv) == SVt_NV)
2459             sv_upgrade(sv, SVt_PVNV);
2460
2461         (void)SvIOKp_on(sv);    /* Must do this first, to clear any SvOOK */
2462         if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2463             SvIV_set(sv, I_V(SvNVX(sv)));
2464             if (SvNVX(sv) == (NV) SvIVX(sv)
2465 #ifndef NV_PRESERVES_UV
2466                 && (((UV)1 << NV_PRESERVES_UV_BITS) >
2467                     (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2468                 /* Don't flag it as "accurately an integer" if the number
2469                    came from a (by definition imprecise) NV operation, and
2470                    we're outside the range of NV integer precision */
2471 #endif
2472                 ) {
2473                 SvIOK_on(sv);  /* Can this go wrong with rounding? NWC */
2474                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2475                                       "0x%"UVxf" uv(%"NVgf" => %"IVdf") (precise)\n",
2476                                       PTR2UV(sv),
2477                                       SvNVX(sv),
2478                                       SvIVX(sv)));
2479
2480             } else {
2481                 /* IV not precise.  No need to convert from PV, as NV
2482                    conversion would already have cached IV if it detected
2483                    that PV->IV would be better than PV->NV->IV
2484                    flags already correct - don't set public IOK.  */
2485                 DEBUG_c(PerlIO_printf(Perl_debug_log,
2486                                       "0x%"UVxf" uv(%"NVgf" => %"IVdf") (imprecise)\n",
2487                                       PTR2UV(sv),
2488                                       SvNVX(sv),
2489                                       SvIVX(sv)));
2490             }
2491             /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2492                but the cast (NV)IV_MIN rounds to a the value less (more
2493                negative) than IV_MIN which happens to be equal to SvNVX ??
2494                Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2495                NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2496                (NV)UVX == NVX are both true, but the values differ. :-(
2497                Hopefully for 2s complement IV_MIN is something like
2498                0x8000000000000000 which will be exact. NWC */
2499         }
2500         else {
2501             SvUV_set(sv, U_V(SvNVX(sv)));
2502             if (
2503                 (SvNVX(sv) == (NV) SvUVX(sv))
2504 #ifndef  NV_PRESERVES_UV
2505                 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2506                 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2507                 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2508                 /* Don't flag it as "accurately an integer" if the number
2509                    came from a (by definition imprecise) NV operation, and
2510                    we're outside the range of NV integer precision */
2511 #endif
2512                 )
2513                 SvIOK_on(sv);
2514             SvIsUV_on(sv);
2515             DEBUG_c(PerlIO_printf(Perl_debug_log,
2516                                   "0x%"UVxf" 2uv(%"UVuf" => %"IVdf") (as unsigned)\n",
2517                                   PTR2UV(sv),
2518                                   SvUVX(sv),
2519                                   SvUVX(sv)));
2520         }
2521     }
2522     else if (SvPOKp(sv) && SvLEN(sv)) {
2523         UV value;
2524         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2525
2526         /* We want to avoid a possible problem when we cache a UV which
2527            may be later translated to an NV, and the resulting NV is not
2528            the translation of the initial data.
2529         
2530            This means that if we cache such a UV, we need to cache the
2531            NV as well.  Moreover, we trade speed for space, and do not
2532            cache the NV if not needed.
2533          */
2534
2535         /* SVt_PVNV is one higher than SVt_PVIV, hence this order  */
2536         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2537              == IS_NUMBER_IN_UV) {
2538             /* It's definitely an integer, only upgrade to PVIV */
2539             if (SvTYPE(sv) < SVt_PVIV)
2540                 sv_upgrade(sv, SVt_PVIV);
2541             (void)SvIOK_on(sv);
2542         } else if (SvTYPE(sv) < SVt_PVNV)
2543             sv_upgrade(sv, SVt_PVNV);
2544
2545         /* If NV preserves UV then we only use the UV value if we know that
2546            we aren't going to call atof() below. If NVs don't preserve UVs
2547            then the value returned may have more precision than atof() will
2548            return, even though it isn't accurate.  */
2549         if ((numtype & (IS_NUMBER_IN_UV
2550 #ifdef NV_PRESERVES_UV
2551                         | IS_NUMBER_NOT_INT
2552 #endif
2553             )) == IS_NUMBER_IN_UV) {
2554             /* This won't turn off the public IOK flag if it was set above  */
2555             (void)SvIOKp_on(sv);
2556
2557             if (!(numtype & IS_NUMBER_NEG)) {
2558                 /* positive */;
2559                 if (value <= (UV)IV_MAX) {
2560                     SvIV_set(sv, (IV)value);
2561                 } else {
2562                     /* it didn't overflow, and it was positive. */
2563                     SvUV_set(sv, value);
2564                     SvIsUV_on(sv);
2565                 }
2566             } else {
2567                 /* 2s complement assumption  */
2568                 if (value <= (UV)IV_MIN) {
2569                     SvIV_set(sv, -(IV)value);
2570                 } else {
2571                     /* Too negative for an IV.  This is a double upgrade, but
2572                        I'm assuming it will be rare.  */
2573                     if (SvTYPE(sv) < SVt_PVNV)
2574                         sv_upgrade(sv, SVt_PVNV);
2575                     SvNOK_on(sv);
2576                     SvIOK_off(sv);
2577                     SvIOKp_on(sv);
2578                     SvNV_set(sv, -(NV)value);
2579                     SvIV_set(sv, IV_MIN);
2580                 }
2581             }
2582         }
2583         
2584         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2585             != IS_NUMBER_IN_UV) {
2586             /* It wasn't an integer, or it overflowed the UV. */
2587             SvNV_set(sv, Atof(SvPVX_const(sv)));
2588
2589             if (! numtype && ckWARN(WARN_NUMERIC))
2590                     not_a_number(sv);
2591
2592 #if defined(USE_LONG_DOUBLE)
2593             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%" PERL_PRIgldbl ")\n",
2594                                   PTR2UV(sv), SvNVX(sv)));
2595 #else
2596             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"NVgf")\n",
2597                                   PTR2UV(sv), SvNVX(sv)));
2598 #endif
2599
2600 #ifdef NV_PRESERVES_UV
2601             (void)SvIOKp_on(sv);
2602             (void)SvNOK_on(sv);
2603             if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2604                 SvIV_set(sv, I_V(SvNVX(sv)));
2605                 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2606                     SvIOK_on(sv);
2607                 } else {
2608                     /* Integer is imprecise. NOK, IOKp */
2609                 }
2610                 /* UV will not work better than IV */
2611             } else {
2612                 if (SvNVX(sv) > (NV)UV_MAX) {
2613                     SvIsUV_on(sv);
2614                     /* Integer is inaccurate. NOK, IOKp, is UV */
2615                     SvUV_set(sv, UV_MAX);
2616                     SvIsUV_on(sv);
2617                 } else {
2618                     SvUV_set(sv, U_V(SvNVX(sv)));
2619                     /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2620                        NV preservse UV so can do correct comparison.  */
2621                     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2622                         SvIOK_on(sv);
2623                         SvIsUV_on(sv);
2624                     } else {
2625                         /* Integer is imprecise. NOK, IOKp, is UV */
2626                         SvIsUV_on(sv);
2627                     }
2628                 }
2629             }
2630 #else /* NV_PRESERVES_UV */
2631             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2632                 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2633                 /* The UV slot will have been set from value returned by
2634                    grok_number above.  The NV slot has just been set using
2635                    Atof.  */
2636                 SvNOK_on(sv);
2637                 assert (SvIOKp(sv));
2638             } else {
2639                 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2640                     U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2641                     /* Small enough to preserve all bits. */
2642                     (void)SvIOKp_on(sv);
2643                     SvNOK_on(sv);
2644                     SvIV_set(sv, I_V(SvNVX(sv)));
2645                     if ((NV)(SvIVX(sv)) == SvNVX(sv))
2646                         SvIOK_on(sv);
2647                     /* Assumption: first non-preserved integer is < IV_MAX,
2648                        this NV is in the preserved range, therefore: */
2649                     if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2650                           < (UV)IV_MAX)) {
2651                         Perl_croak(aTHX_ "sv_2uv 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);
2652                     }
2653                 } else
2654                     sv_2iuv_non_preserve (sv, numtype);
2655             }
2656 #endif /* NV_PRESERVES_UV */
2657         }
2658     }
2659     else  {
2660         if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2661             if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2662                 report_uninit(sv);
2663         }
2664         if (SvTYPE(sv) < SVt_IV)
2665             /* Typically the caller expects that sv_any is not NULL now.  */
2666             sv_upgrade(sv, SVt_IV);
2667         return 0;
2668     }
2669
2670     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2671                           PTR2UV(sv),SvUVX(sv)));
2672     return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
2673 }
2674
2675 /*
2676 =for apidoc sv_2nv
2677
2678 Return the num value of an SV, doing any necessary string or integer
2679 conversion, magic etc. Normally used via the C<SvNV(sv)> and C<SvNVx(sv)>
2680 macros.
2681
2682 =cut
2683 */
2684
2685 NV
2686 Perl_sv_2nv(pTHX_ register SV *sv)
2687 {
2688     if (!sv)
2689         return 0.0;
2690     if (SvGMAGICAL(sv)) {
2691         mg_get(sv);
2692         if (SvNOKp(sv))
2693             return SvNVX(sv);
2694         if (SvPOKp(sv) && SvLEN(sv)) {
2695             if (ckWARN(WARN_NUMERIC) && !SvIOKp(sv) &&
2696                 !grok_number(SvPVX_const(sv), SvCUR(sv), NULL))
2697                 not_a_number(sv);
2698             return Atof(SvPVX_const(sv));
2699         }
2700         if (SvIOKp(sv)) {
2701             if (SvIsUV(sv))
2702                 return (NV)SvUVX(sv);
2703             else
2704                 return (NV)SvIVX(sv);
2705         }       
2706         if (!SvROK(sv)) {
2707             if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2708                 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2709                     report_uninit(sv);
2710             }
2711             return (NV)0;
2712         }
2713     }
2714     if (SvTHINKFIRST(sv)) {
2715         if (SvROK(sv)) {
2716           SV* tmpstr;
2717           if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,numer)) &&
2718                 (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv))))
2719               return SvNV(tmpstr);
2720           return PTR2NV(SvRV(sv));
2721         }
2722         if (SvIsCOW(sv)) {
2723             sv_force_normal_flags(sv, 0);
2724         }
2725         if (SvREADONLY(sv) && !SvOK(sv)) {
2726             if (ckWARN(WARN_UNINITIALIZED))
2727                 report_uninit(sv);
2728             return 0.0;
2729         }
2730     }
2731     if (SvTYPE(sv) < SVt_NV) {
2732         if (SvTYPE(sv) == SVt_IV)
2733             sv_upgrade(sv, SVt_PVNV);
2734         else
2735             sv_upgrade(sv, SVt_NV);
2736 #ifdef USE_LONG_DOUBLE
2737         DEBUG_c({
2738             STORE_NUMERIC_LOCAL_SET_STANDARD();
2739             PerlIO_printf(Perl_debug_log,
2740                           "0x%"UVxf" num(%" PERL_PRIgldbl ")\n",
2741                           PTR2UV(sv), SvNVX(sv));
2742             RESTORE_NUMERIC_LOCAL();
2743         });
2744 #else
2745         DEBUG_c({
2746             STORE_NUMERIC_LOCAL_SET_STANDARD();
2747             PerlIO_printf(Perl_debug_log, "0x%"UVxf" num(%"NVgf")\n",
2748                           PTR2UV(sv), SvNVX(sv));
2749             RESTORE_NUMERIC_LOCAL();
2750         });
2751 #endif
2752     }
2753     else if (SvTYPE(sv) < SVt_PVNV)
2754         sv_upgrade(sv, SVt_PVNV);
2755     if (SvNOKp(sv)) {
2756         return SvNVX(sv);
2757     }
2758     if (SvIOKp(sv)) {
2759         SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
2760 #ifdef NV_PRESERVES_UV
2761         SvNOK_on(sv);
2762 #else
2763         /* Only set the public NV OK flag if this NV preserves the IV  */
2764         /* Check it's not 0xFFFFFFFFFFFFFFFF */
2765         if (SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
2766                        : (SvIVX(sv) == I_V(SvNVX(sv))))
2767             SvNOK_on(sv);
2768         else
2769             SvNOKp_on(sv);
2770 #endif
2771     }
2772     else if (SvPOKp(sv) && SvLEN(sv)) {
2773         UV value;
2774         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2775         if (ckWARN(WARN_NUMERIC) && !SvIOKp(sv) && !numtype)
2776             not_a_number(sv);
2777 #ifdef NV_PRESERVES_UV
2778         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2779             == IS_NUMBER_IN_UV) {
2780             /* It's definitely an integer */
2781             SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
2782         } else
2783             SvNV_set(sv, Atof(SvPVX_const(sv)));
2784         SvNOK_on(sv);
2785 #else
2786         SvNV_set(sv, Atof(SvPVX_const(sv)));
2787         /* Only set the public NV OK flag if this NV preserves the value in
2788            the PV at least as well as an IV/UV would.
2789            Not sure how to do this 100% reliably. */
2790         /* if that shift count is out of range then Configure's test is
2791            wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2792            UV_BITS */
2793         if (((UV)1 << NV_PRESERVES_UV_BITS) >
2794             U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2795             SvNOK_on(sv); /* Definitely small enough to preserve all bits */
2796         } else if (!(numtype & IS_NUMBER_IN_UV)) {
2797             /* Can't use strtol etc to convert this string, so don't try.
2798                sv_2iv and sv_2uv will use the NV to convert, not the PV.  */
2799             SvNOK_on(sv);
2800         } else {
2801             /* value has been set.  It may not be precise.  */
2802             if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2803                 /* 2s complement assumption for (UV)IV_MIN  */
2804                 SvNOK_on(sv); /* Integer is too negative.  */
2805             } else {
2806                 SvNOKp_on(sv);
2807                 SvIOKp_on(sv);
2808
2809                 if (numtype & IS_NUMBER_NEG) {
2810                     SvIV_set(sv, -(IV)value);
2811                 } else if (value <= (UV)IV_MAX) {
2812                     SvIV_set(sv, (IV)value);
2813                 } else {
2814                     SvUV_set(sv, value);
2815                     SvIsUV_on(sv);
2816                 }
2817
2818                 if (numtype & IS_NUMBER_NOT_INT) {
2819                     /* I believe that even if the original PV had decimals,
2820                        they are lost beyond the limit of the FP precision.
2821                        However, neither is canonical, so both only get p
2822                        flags.  NWC, 2000/11/25 */
2823                     /* Both already have p flags, so do nothing */
2824                 } else {
2825                     const NV nv = SvNVX(sv);
2826                     if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2827                         if (SvIVX(sv) == I_V(nv)) {
2828                             SvNOK_on(sv);
2829                             SvIOK_on(sv);
2830                         } else {
2831                             SvIOK_on(sv);
2832                             /* It had no "." so it must be integer.  */
2833                         }
2834                     } else {
2835                         /* between IV_MAX and NV(UV_MAX).
2836                            Could be slightly > UV_MAX */
2837
2838                         if (numtype & IS_NUMBER_NOT_INT) {
2839                             /* UV and NV both imprecise.  */
2840                         } else {
2841                             const UV nv_as_uv = U_V(nv);
2842
2843                             if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2844                                 SvNOK_on(sv);
2845                                 SvIOK_on(sv);
2846                             } else {
2847                                 SvIOK_on(sv);
2848                             }
2849                         }
2850                     }
2851                 }
2852             }
2853         }
2854 #endif /* NV_PRESERVES_UV */
2855     }
2856     else  {
2857         if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP))
2858             report_uninit(sv);
2859         if (SvTYPE(sv) < SVt_NV)
2860             /* Typically the caller expects that sv_any is not NULL now.  */
2861             /* XXX Ilya implies that this is a bug in callers that assume this
2862                and ideally should be fixed.  */
2863             sv_upgrade(sv, SVt_NV);
2864         return 0.0;
2865     }
2866 #if defined(USE_LONG_DOUBLE)
2867     DEBUG_c({
2868         STORE_NUMERIC_LOCAL_SET_STANDARD();
2869         PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" PERL_PRIgldbl ")\n",
2870                       PTR2UV(sv), SvNVX(sv));
2871         RESTORE_NUMERIC_LOCAL();
2872     });
2873 #else
2874     DEBUG_c({
2875         STORE_NUMERIC_LOCAL_SET_STANDARD();
2876         PerlIO_printf(Perl_debug_log, "0x%"UVxf" 1nv(%"NVgf")\n",
2877                       PTR2UV(sv), SvNVX(sv));
2878         RESTORE_NUMERIC_LOCAL();
2879     });
2880 #endif
2881     return SvNVX(sv);
2882 }
2883
2884 /* asIV(): extract an integer from the string value of an SV.
2885  * Caller must validate PVX  */
2886
2887 STATIC IV
2888 S_asIV(pTHX_ SV *sv)
2889 {
2890     UV value;
2891     const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2892
2893     if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2894         == IS_NUMBER_IN_UV) {
2895         /* It's definitely an integer */
2896         if (numtype & IS_NUMBER_NEG) {
2897             if (value < (UV)IV_MIN)
2898                 return -(IV)value;
2899         } else {
2900             if (value < (UV)IV_MAX)
2901                 return (IV)value;
2902         }
2903     }
2904     if (!numtype) {
2905         if (ckWARN(WARN_NUMERIC))
2906             not_a_number(sv);
2907     }
2908     return I_V(Atof(SvPVX_const(sv)));
2909 }
2910
2911 /* asUV(): extract an unsigned integer from the string value of an SV
2912  * Caller must validate PVX  */
2913
2914 STATIC UV
2915 S_asUV(pTHX_ SV *sv)
2916 {
2917     UV value;
2918     const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2919
2920     if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2921         == IS_NUMBER_IN_UV) {
2922         /* It's definitely an integer */
2923         if (!(numtype & IS_NUMBER_NEG))
2924             return value;
2925     }
2926     if (!numtype) {
2927         if (ckWARN(WARN_NUMERIC))
2928             not_a_number(sv);
2929     }
2930     return U_V(Atof(SvPVX_const(sv)));
2931 }
2932
2933 /*
2934 =for apidoc sv_2pv_nolen
2935
2936 Like C<sv_2pv()>, but doesn't return the length too. You should usually
2937 use the macro wrapper C<SvPV_nolen(sv)> instead.
2938 =cut
2939 */
2940
2941 char *
2942 Perl_sv_2pv_nolen(pTHX_ register SV *sv)
2943 {
2944     return sv_2pv(sv, 0);
2945 }
2946
2947 /* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2948  * UV as a string towards the end of buf, and return pointers to start and
2949  * end of it.
2950  *
2951  * We assume that buf is at least TYPE_CHARS(UV) long.
2952  */
2953
2954 static char *
2955 uiv_2buf(char *buf, IV iv, UV uv, int is_uv, char **peob)
2956 {
2957     char *ptr = buf + TYPE_CHARS(UV);
2958     char *ebuf = ptr;
2959     int sign;
2960
2961     if (is_uv)
2962         sign = 0;
2963     else if (iv >= 0) {
2964         uv = iv;
2965         sign = 0;
2966     } else {
2967         uv = -iv;
2968         sign = 1;
2969     }
2970     do {
2971         *--ptr = '0' + (char)(uv % 10);
2972     } while (uv /= 10);
2973     if (sign)
2974         *--ptr = '-';
2975     *peob = ebuf;
2976     return ptr;
2977 }
2978
2979 /* sv_2pv() is now a macro using Perl_sv_2pv_flags();
2980  * this function provided for binary compatibility only
2981  */
2982
2983 char *
2984 Perl_sv_2pv(pTHX_ register SV *sv, STRLEN *lp)
2985 {
2986     return sv_2pv_flags(sv, lp, SV_GMAGIC);
2987 }
2988
2989 /*
2990 =for apidoc sv_2pv_flags
2991
2992 Returns a pointer to the string value of an SV, and sets *lp to its length.
2993 If flags includes SV_GMAGIC, does an mg_get() first. Coerces sv to a string
2994 if necessary.
2995 Normally invoked via the C<SvPV_flags> macro. C<sv_2pv()> and C<sv_2pv_nomg>
2996 usually end up here too.
2997
2998 =cut
2999 */
3000
3001 char *
3002 Perl_sv_2pv_flags(pTHX_ register SV *sv, STRLEN *lp, I32 flags)
3003 {
3004     register char *s;
3005     int olderrno;
3006     SV *tsv, *origsv;
3007     char tbuf[64];      /* Must fit sprintf/Gconvert of longest IV/NV */
3008     char *tmpbuf = tbuf;
3009
3010     if (!sv) {
3011         if (lp)
3012             *lp = 0;
3013         return (char *)"";
3014     }
3015     if (SvGMAGICAL(sv)) {
3016         if (flags & SV_GMAGIC)
3017             mg_get(sv);
3018         if (SvPOKp(sv)) {
3019             if (lp)
3020                 *lp = SvCUR(sv);
3021             if (flags & SV_MUTABLE_RETURN)
3022                 return SvPVX_mutable(sv);
3023             if (flags & SV_CONST_RETURN)
3024                 return (char *)SvPVX_const(sv);
3025             return SvPVX(sv);
3026         }
3027         if (SvIOKp(sv)) {
3028             if (SvIsUV(sv))
3029                 (void)sprintf(tmpbuf,"%"UVuf, (UV)SvUVX(sv));
3030             else
3031                 (void)sprintf(tmpbuf,"%"IVdf, (IV)SvIVX(sv));
3032             tsv = Nullsv;
3033             goto tokensave;
3034         }
3035         if (SvNOKp(sv)) {
3036             Gconvert(SvNVX(sv), NV_DIG, 0, tmpbuf);
3037             tsv = Nullsv;
3038             goto tokensave;
3039         }
3040         if (!SvROK(sv)) {
3041             if (!(SvFLAGS(sv) & SVs_PADTMP)) {
3042                 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
3043                     report_uninit(sv);
3044             }
3045             if (lp)
3046                 *lp = 0;
3047             return (char *)"";
3048         }
3049     }
3050     if (SvTHINKFIRST(sv)) {
3051         if (SvROK(sv)) {
3052             SV* tmpstr;
3053             register const char *typestr;
3054             if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,string)) &&
3055                 (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
3056                 /* Unwrap this:  */
3057                 /* char *pv = lp ? SvPV(tmpstr, *lp) : SvPV_nolen(tmpstr); */
3058
3059                 char *pv;
3060                 if ((SvFLAGS(tmpstr) & (SVf_POK)) == SVf_POK) {
3061                     if (flags & SV_CONST_RETURN) {
3062                         pv = (char *) SvPVX_const(tmpstr);
3063                     } else {
3064                         pv = (flags & SV_MUTABLE_RETURN)
3065                             ? SvPVX_mutable(tmpstr) : SvPVX(tmpstr);
3066                     }
3067                     if (lp)
3068                         *lp = SvCUR(tmpstr);
3069                 } else {
3070                     pv = sv_2pv_flags(tmpstr, lp, flags);
3071                 }
3072                 if (SvUTF8(tmpstr))
3073                     SvUTF8_on(sv);
3074                 else
3075                     SvUTF8_off(sv);
3076                 return pv;
3077             }
3078             origsv = sv;
3079             sv = (SV*)SvRV(sv);
3080             if (!sv)
3081                 typestr = "NULLREF";
3082             else {
3083                 MAGIC *mg;
3084                 
3085                 switch (SvTYPE(sv)) {
3086                 case SVt_PVMG:
3087                     if ( ((SvFLAGS(sv) &
3088                            (SVs_OBJECT|SVf_OK|SVs_GMG|SVs_SMG|SVs_RMG))
3089                           == (SVs_OBJECT|SVs_SMG))
3090                          && (mg = mg_find(sv, PERL_MAGIC_qr))) {
3091                         const regexp *re = (regexp *)mg->mg_obj;
3092
3093                         if (!mg->mg_ptr) {
3094                             const char *fptr = "msix";
3095                             char reflags[6];
3096                             char ch;
3097                             int left = 0;
3098                             int right = 4;
3099                             char need_newline = 0;
3100                             U16 reganch = (U16)((re->reganch & PMf_COMPILETIME) >> 12);
3101
3102                             while((ch = *fptr++)) {
3103                                 if(reganch & 1) {
3104                                     reflags[left++] = ch;
3105                                 }
3106                                 else {
3107                                     reflags[right--] = ch;
3108                                 }
3109                                 reganch >>= 1;
3110                             }
3111                             if(left != 4) {
3112                                 reflags[left] = '-';
3113                                 left = 5;
3114                             }
3115
3116                             mg->mg_len = re->prelen + 4 + left;
3117                             /*
3118                              * If /x was used, we have to worry about a regex
3119                              * ending with a comment later being embedded
3120                              * within another regex. If so, we don't want this
3121                              * regex's "commentization" to leak out to the
3122                              * right part of the enclosing regex, we must cap
3123                              * it with a newline.
3124                              *
3125                              * So, if /x was used, we scan backwards from the
3126                              * end of the regex. If we find a '#' before we
3127                              * find a newline, we need to add a newline
3128                              * ourself. If we find a '\n' first (or if we
3129                              * don't find '#' or '\n'), we don't need to add
3130                              * anything.  -jfriedl
3131                              */
3132                             if (PMf_EXTENDED & re->reganch)
3133                             {
3134                                 const char *endptr = re->precomp + re->prelen;
3135                                 while (endptr >= re->precomp)
3136                                 {
3137                                     const char c = *(endptr--);
3138                                     if (c == '\n')
3139                                         break; /* don't need another */
3140                                     if (c == '#') {
3141                                         /* we end while in a comment, so we
3142                                            need a newline */
3143                                         mg->mg_len++; /* save space for it */
3144                                         need_newline = 1; /* note to add it */
3145                                         break;
3146                                     }
3147                                 }
3148                             }
3149
3150                             New(616, mg->mg_ptr, mg->mg_len + 1 + left, char);
3151                             Copy("(?", mg->mg_ptr, 2, char);
3152                             Copy(reflags, mg->mg_ptr+2, left, char);
3153                             Copy(":", mg->mg_ptr+left+2, 1, char);
3154                             Copy(re->precomp, mg->mg_ptr+3+left, re->prelen, char);
3155                             if (need_newline)
3156                                 mg->mg_ptr[mg->mg_len - 2] = '\n';
3157                             mg->mg_ptr[mg->mg_len - 1] = ')';
3158                             mg->mg_ptr[mg->mg_len] = 0;
3159                         }
3160                         PL_reginterp_cnt += re->program[0].next_off;
3161
3162                         if (re->reganch & ROPT_UTF8)
3163                             SvUTF8_on(origsv);
3164                         else
3165                             SvUTF8_off(origsv);
3166                         if (lp)
3167                             *lp = mg->mg_len;
3168                         return mg->mg_ptr;
3169                     }
3170                                         /* Fall through */
3171                 case SVt_NULL:
3172                 case SVt_IV:
3173                 case SVt_NV:
3174                 case SVt_RV:
3175                 case SVt_PV:
3176                 case SVt_PVIV:
3177                 case SVt_PVNV:
3178                 case SVt_PVBM:  typestr = SvROK(sv) ? "REF" : "SCALAR"; break;
3179                 case SVt_PVLV:  typestr = SvROK(sv) ? "REF"
3180                                 /* tied lvalues should appear to be
3181                                  * scalars for backwards compatitbility */
3182                                 : (LvTYPE(sv) == 't' || LvTYPE(sv) == 'T')
3183                                     ? "SCALAR" : "LVALUE";      break;
3184                 case SVt_PVAV:  typestr = "ARRAY";      break;
3185                 case SVt_PVHV:  typestr = "HASH";       break;
3186                 case SVt_PVCV:  typestr = "CODE";       break;
3187                 case SVt_PVGV:  typestr = "GLOB";       break;
3188                 case SVt_PVFM:  typestr = "FORMAT";     break;
3189                 case SVt_PVIO:  typestr = "IO";         break;
3190                 default:        typestr = "UNKNOWN";    break;
3191                 }
3192                 tsv = NEWSV(0,0);
3193                 if (SvOBJECT(sv)) {
3194                     const char *name = HvNAME_get(SvSTASH(sv));
3195                     Perl_sv_setpvf(aTHX_ tsv, "%s=%s(0x%"UVxf")",
3196                                    name ? name : "__ANON__" , typestr, PTR2UV(sv));
3197                 }
3198                 else
3199                     Perl_sv_setpvf(aTHX_ tsv, "%s(0x%"UVxf")", typestr, PTR2UV(sv));
3200                 goto tokensaveref;
3201             }
3202             if (lp)
3203                 *lp = strlen(typestr);
3204             return (char *)typestr;
3205         }
3206         if (SvREADONLY(sv) && !SvOK(sv)) {
3207             if (ckWARN(WARN_UNINITIALIZED))
3208                 report_uninit(sv);
3209             if (lp)
3210                 *lp = 0;
3211             return (char *)"";
3212         }
3213     }
3214     if (SvIOK(sv) || ((SvIOKp(sv) && !SvNOKp(sv)))) {
3215         /* I'm assuming that if both IV and NV are equally valid then
3216            converting the IV is going to be more efficient */
3217         const U32 isIOK = SvIOK(sv);
3218         const U32 isUIOK = SvIsUV(sv);
3219         char buf[TYPE_CHARS(UV)];
3220         char *ebuf, *ptr;
3221
3222         if (SvTYPE(sv) < SVt_PVIV)
3223             sv_upgrade(sv, SVt_PVIV);
3224         if (isUIOK)
3225             ptr = uiv_2buf(buf, 0, SvUVX(sv), 1, &ebuf);
3226         else
3227             ptr = uiv_2buf(buf, SvIVX(sv), 0, 0, &ebuf);
3228         /* inlined from sv_setpvn */
3229         SvGROW_mutable(sv, (STRLEN)(ebuf - ptr + 1));
3230         Move(ptr,SvPVX_mutable(sv),ebuf - ptr,char);
3231         SvCUR_set(sv, ebuf - ptr);
3232         s = SvEND(sv);
3233         *s = '\0';
3234         if (isIOK)
3235             SvIOK_on(sv);
3236         else
3237             SvIOKp_on(sv);
3238         if (isUIOK)
3239             SvIsUV_on(sv);
3240     }
3241     else if (SvNOKp(sv)) {
3242         if (SvTYPE(sv) < SVt_PVNV)
3243             sv_upgrade(sv, SVt_PVNV);
3244         /* The +20 is pure guesswork.  Configure test needed. --jhi */
3245         s = SvGROW_mutable(sv, NV_DIG + 20);
3246         olderrno = errno;       /* some Xenix systems wipe out errno here */
3247 #ifdef apollo
3248         if (SvNVX(sv) == 0.0)
3249             (void)strcpy(s,"0");
3250         else
3251 #endif /*apollo*/
3252         {
3253             Gconvert(SvNVX(sv), NV_DIG, 0, s);
3254         }
3255         errno = olderrno;
3256 #ifdef FIXNEGATIVEZERO
3257         if (*s == '-' && s[1] == '0' && !s[2])
3258             strcpy(s,"0");
3259 #endif
3260         while (*s) s++;
3261 #ifdef hcx
3262         if (s[-1] == '.')
3263             *--s = '\0';
3264 #endif
3265     }
3266     else {
3267         if (ckWARN(WARN_UNINITIALIZED)
3268             && !PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP))
3269             report_uninit(sv);
3270         if (lp)
3271         *lp = 0;
3272         if (SvTYPE(sv) < SVt_PV)
3273             /* Typically the caller expects that sv_any is not NULL now.  */
3274             sv_upgrade(sv, SVt_PV);
3275         return (char *)"";
3276     }
3277     {
3278         STRLEN len = s - SvPVX_const(sv);
3279         if (lp) 
3280             *lp = len;
3281         SvCUR_set(sv, len);
3282     }
3283     SvPOK_on(sv);
3284     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
3285                           PTR2UV(sv),SvPVX_const(sv)));
3286     if (flags & SV_CONST_RETURN)
3287         return (char *)SvPVX_const(sv);
3288     if (flags & SV_MUTABLE_RETURN)
3289         return SvPVX_mutable(sv);
3290     return SvPVX(sv);
3291
3292   tokensave:
3293     if (SvROK(sv)) {    /* XXX Skip this when sv_pvn_force calls */
3294         /* Sneaky stuff here */
3295
3296       tokensaveref:
3297         if (!tsv)
3298             tsv = newSVpv(tmpbuf, 0);
3299         sv_2mortal(tsv);
3300         if (lp)
3301             *lp = SvCUR(tsv);
3302         return SvPVX(tsv);
3303     }
3304     else {
3305         dVAR;
3306         STRLEN len;
3307         const char *t;
3308
3309         if (tsv) {
3310             sv_2mortal(tsv);
3311             t = SvPVX_const(tsv);
3312             len = SvCUR(tsv);
3313         }
3314         else {
3315             t = tmpbuf;
3316             len = strlen(tmpbuf);
3317         }
3318 #ifdef FIXNEGATIVEZERO
3319         if (len == 2 && t[0] == '-' && t[1] == '0') {
3320             t = "0";
3321             len = 1;
3322         }
3323 #endif
3324         SvUPGRADE(sv, SVt_PV);
3325         if (lp)
3326             *lp = len;
3327         s = SvGROW_mutable(sv, len + 1);
3328         SvCUR_set(sv, len);
3329         SvPOKp_on(sv);
3330         return strcpy(s, t);
3331     }
3332 }
3333
3334 /*
3335 =for apidoc sv_copypv
3336
3337 Copies a stringified representation of the source SV into the
3338 destination SV.  Automatically performs any necessary mg_get and
3339 coercion of numeric values into strings.  Guaranteed to preserve
3340 UTF-8 flag even from overloaded objects.  Similar in nature to
3341 sv_2pv[_flags] but operates directly on an SV instead of just the
3342 string.  Mostly uses sv_2pv_flags to do its work, except when that
3343 would lose the UTF-8'ness of the PV.
3344
3345 =cut
3346 */
3347
3348 void
3349 Perl_sv_copypv(pTHX_ SV *dsv, register SV *ssv)
3350 {
3351     STRLEN len;
3352     const char * const s = SvPV_const(ssv,len);
3353     sv_setpvn(dsv,s,len);
3354     if (SvUTF8(ssv))
3355         SvUTF8_on(dsv);
3356     else
3357         SvUTF8_off(dsv);
3358 }
3359
3360 /*
3361 =for apidoc sv_2pvbyte_nolen
3362
3363 Return a pointer to the byte-encoded representation of the SV.
3364 May cause the SV to be downgraded from UTF-8 as a side-effect.
3365
3366 Usually accessed via the C<SvPVbyte_nolen> macro.
3367
3368 =cut
3369 */
3370
3371 char *
3372 Perl_sv_2pvbyte_nolen(pTHX_ register SV *sv)
3373 {
3374     return sv_2pvbyte(sv, 0);
3375 }
3376
3377 /*
3378 =for apidoc sv_2pvbyte
3379
3380 Return a pointer to the byte-encoded representation of the SV, and set *lp
3381 to its length.  May cause the SV to be downgraded from UTF-8 as a
3382 side-effect.
3383
3384 Usually accessed via the C<SvPVbyte> macro.
3385
3386 =cut
3387 */
3388
3389 char *
3390 Perl_sv_2pvbyte(pTHX_ register SV *sv, STRLEN *lp)
3391 {
3392     sv_utf8_downgrade(sv,0);
3393     return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
3394 }
3395
3396 /*
3397 =for apidoc sv_2pvutf8_nolen
3398
3399 Return a pointer to the UTF-8-encoded representation of the SV.
3400 May cause the SV to be upgraded to UTF-8 as a side-effect.
3401
3402 Usually accessed via the C<SvPVutf8_nolen> macro.
3403
3404 =cut
3405 */
3406
3407 char *
3408 Perl_sv_2pvutf8_nolen(pTHX_ register SV *sv)
3409 {
3410     return sv_2pvutf8(sv, 0);
3411 }
3412
3413 /*
3414 =for apidoc sv_2pvutf8
3415
3416 Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
3417 to its length.  May cause the SV to be upgraded to UTF-8 as a side-effect.
3418
3419 Usually accessed via the C<SvPVutf8> macro.
3420
3421 =cut
3422 */
3423
3424 char *
3425 Perl_sv_2pvutf8(pTHX_ register SV *sv, STRLEN *lp)
3426 {
3427     sv_utf8_upgrade(sv);
3428     return SvPV(sv,*lp);
3429 }
3430
3431 /*
3432 =for apidoc sv_2bool
3433
3434 This function is only called on magical items, and is only used by
3435 sv_true() or its macro equivalent.
3436
3437 =cut
3438 */
3439
3440 bool
3441 Perl_sv_2bool(pTHX_ register SV *sv)
3442 {
3443     if (SvGMAGICAL(sv))
3444         mg_get(sv);
3445
3446     if (!SvOK(sv))
3447         return 0;
3448     if (SvROK(sv)) {
3449         SV* tmpsv;
3450         if (SvAMAGIC(sv) && (tmpsv=AMG_CALLun(sv,bool_)) &&
3451                 (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
3452             return (bool)SvTRUE(tmpsv);
3453       return SvRV(sv) != 0;
3454     }
3455     if (SvPOKp(sv)) {
3456         register XPV* const Xpvtmp = (XPV*)SvANY(sv);
3457         if (Xpvtmp &&
3458                 (*sv->sv_u.svu_pv > '0' ||
3459                 Xpvtmp->xpv_cur > 1 ||
3460                 (Xpvtmp->xpv_cur && *sv->sv_u.svu_pv != '0')))
3461             return 1;
3462         else
3463             return 0;
3464     }
3465     else {
3466         if (SvIOKp(sv))
3467             return SvIVX(sv) != 0;
3468         else {
3469             if (SvNOKp(sv))
3470                 return SvNVX(sv) != 0.0;
3471             else
3472                 return FALSE;
3473         }
3474     }
3475 }
3476
3477 /* sv_utf8_upgrade() is now a macro using sv_utf8_upgrade_flags();
3478  * this function provided for binary compatibility only
3479  */
3480
3481
3482 STRLEN
3483 Perl_sv_utf8_upgrade(pTHX_ register SV *sv)
3484 {
3485     return sv_utf8_upgrade_flags(sv, SV_GMAGIC);
3486 }
3487
3488 /*
3489 =for apidoc sv_utf8_upgrade
3490
3491 Converts the PV of an SV to its UTF-8-encoded form.
3492 Forces the SV to string form if it is not already.
3493 Always sets the SvUTF8 flag to avoid future validity checks even
3494 if all the bytes have hibit clear.
3495
3496 This is not as a general purpose byte encoding to Unicode interface:
3497 use the Encode extension for that.
3498
3499 =for apidoc sv_utf8_upgrade_flags
3500
3501 Converts the PV of an SV to its UTF-8-encoded form.
3502 Forces the SV to string form if it is not already.
3503 Always sets the SvUTF8 flag to avoid future validity checks even
3504 if all the bytes have hibit clear. If C<flags> has C<SV_GMAGIC> bit set,
3505 will C<mg_get> on C<sv> if appropriate, else not. C<sv_utf8_upgrade> and
3506 C<sv_utf8_upgrade_nomg> are implemented in terms of this function.
3507
3508 This is not as a general purpose byte encoding to Unicode interface:
3509 use the Encode extension for that.
3510
3511 =cut
3512 */
3513
3514 STRLEN
3515 Perl_sv_utf8_upgrade_flags(pTHX_ register SV *sv, I32 flags)
3516 {
3517     if (sv == &PL_sv_undef)
3518         return 0;
3519     if (!SvPOK(sv)) {
3520         STRLEN len = 0;
3521         if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
3522             (void) sv_2pv_flags(sv,&len, flags);
3523             if (SvUTF8(sv))
3524                 return len;
3525         } else {
3526             (void) SvPV_force(sv,len);
3527         }
3528     }
3529
3530     if (SvUTF8(sv)) {
3531         return SvCUR(sv);
3532     }
3533
3534     if (SvIsCOW(sv)) {
3535         sv_force_normal_flags(sv, 0);
3536     }
3537
3538     if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING))
3539         sv_recode_to_utf8(sv, PL_encoding);
3540     else { /* Assume Latin-1/EBCDIC */
3541         /* This function could be much more efficient if we
3542          * had a FLAG in SVs to signal if there are any hibit
3543          * chars in the PV.  Given that there isn't such a flag
3544          * make the loop as fast as possible. */
3545         const U8 *s = (U8 *) SvPVX_const(sv);
3546         const U8 *e = (U8 *) SvEND(sv);
3547         const U8 *t = s;
3548         int hibit = 0;
3549         
3550         while (t < e) {
3551             const U8 ch = *t++;
3552             if ((hibit = !NATIVE_IS_INVARIANT(ch)))
3553                 break;
3554         }
3555         if (hibit) {
3556             STRLEN len = SvCUR(sv) + 1; /* Plus the \0 */
3557             U8 * const recoded = bytes_to_utf8((U8*)s, &len);
3558
3559             SvPV_free(sv); /* No longer using what was there before. */
3560
3561             SvPV_set(sv, (char*)recoded);
3562             SvCUR_set(sv, len - 1);
3563             SvLEN_set(sv, len); /* No longer know the real size. */
3564         }
3565         /* Mark as UTF-8 even if no hibit - saves scanning loop */
3566         SvUTF8_on(sv);
3567     }
3568     return SvCUR(sv);
3569 }
3570
3571 /*
3572 =for apidoc sv_utf8_downgrade
3573
3574 Attempts to convert the PV of an SV from characters to bytes.
3575 If the PV contains a character beyond byte, this conversion will fail;
3576 in this case, either returns false or, if C<fail_ok> is not
3577 true, croaks.
3578
3579 This is not as a general purpose Unicode to byte encoding interface:
3580 use the Encode extension for that.
3581
3582 =cut
3583 */
3584
3585 bool
3586 Perl_sv_utf8_downgrade(pTHX_ register SV* sv, bool fail_ok)
3587 {
3588     if (SvPOKp(sv) && SvUTF8(sv)) {
3589         if (SvCUR(sv)) {
3590             U8 *s;
3591             STRLEN len;
3592
3593             if (SvIsCOW(sv)) {
3594                 sv_force_normal_flags(sv, 0);
3595             }
3596             s = (U8 *) SvPV(sv, len);
3597             if (!utf8_to_bytes(s, &len)) {
3598                 if (fail_ok)
3599                     return FALSE;
3600                 else {
3601                     if (PL_op)
3602                         Perl_croak(aTHX_ "Wide character in %s",
3603                                    OP_DESC(PL_op));
3604                     else
3605                         Perl_croak(aTHX_ "Wide character");
3606                 }
3607             }
3608             SvCUR_set(sv, len);
3609         }
3610     }
3611     SvUTF8_off(sv);
3612     return TRUE;
3613 }
3614
3615 /*
3616 =for apidoc sv_utf8_encode
3617
3618 Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3619 flag off so that it looks like octets again.
3620
3621 =cut
3622 */
3623
3624 void
3625 Perl_sv_utf8_encode(pTHX_ register SV *sv)
3626 {
3627     (void) sv_utf8_upgrade(sv);
3628     if (SvIsCOW(sv)) {
3629         sv_force_normal_flags(sv, 0);
3630     }
3631     if (SvREADONLY(sv)) {
3632         Perl_croak(aTHX_ PL_no_modify);
3633     }
3634     SvUTF8_off(sv);
3635 }
3636
3637 /*
3638 =for apidoc sv_utf8_decode
3639
3640 If the PV of the SV is an octet sequence in UTF-8
3641 and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3642 so that it looks like a character. If the PV contains only single-byte
3643 characters, the C<SvUTF8> flag stays being off.
3644 Scans PV for validity and returns false if the PV is invalid UTF-8.
3645
3646 =cut
3647 */
3648
3649 bool
3650 Perl_sv_utf8_decode(pTHX_ register SV *sv)
3651 {
3652     if (SvPOKp(sv)) {
3653         const U8 *c;
3654         const U8 *e;
3655
3656         /* The octets may have got themselves encoded - get them back as
3657          * bytes
3658          */
3659         if (!sv_utf8_downgrade(sv, TRUE))
3660             return FALSE;
3661
3662         /* it is actually just a matter of turning the utf8 flag on, but
3663          * we want to make sure everything inside is valid utf8 first.
3664          */
3665         c = (const U8 *) SvPVX_const(sv);
3666         if (!is_utf8_string(c, SvCUR(sv)+1))
3667             return FALSE;
3668         e = (const U8 *) SvEND(sv);
3669         while (c < e) {
3670             U8 ch = *c++;
3671             if (!UTF8_IS_INVARIANT(ch)) {
3672                 SvUTF8_on(sv);
3673                 break;
3674             }
3675         }
3676     }
3677     return TRUE;
3678 }
3679
3680 /* sv_setsv() is now a macro using Perl_sv_setsv_flags();
3681  * this function provided for binary compatibility only
3682  */
3683
3684 void
3685 Perl_sv_setsv(pTHX_ SV *dstr, register SV *sstr)
3686 {
3687     sv_setsv_flags(dstr, sstr, SV_GMAGIC);
3688 }
3689
3690 /*
3691 =for apidoc sv_setsv
3692
3693 Copies the contents of the source SV C<ssv> into the destination SV
3694 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3695 function if the source SV needs to be reused. Does not handle 'set' magic.
3696 Loosely speaking, it performs a copy-by-value, obliterating any previous
3697 content of the destination.
3698
3699 You probably want to use one of the assortment of wrappers, such as
3700 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3701 C<SvSetMagicSV_nosteal>.
3702
3703 =for apidoc sv_setsv_flags
3704
3705 Copies the contents of the source SV C<ssv> into the destination SV
3706 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3707 function if the source SV needs to be reused. Does not handle 'set' magic.
3708 Loosely speaking, it performs a copy-by-value, obliterating any previous
3709 content of the destination.
3710 If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
3711 C<ssv> if appropriate, else not. If the C<flags> parameter has the
3712 C<NOSTEAL> bit set then the buffers of temps will not be stolen. <sv_setsv>
3713 and C<sv_setsv_nomg> are implemented in terms of this function.
3714
3715 You probably want to use one of the assortment of wrappers, such as
3716 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3717 C<SvSetMagicSV_nosteal>.
3718
3719 This is the primary function for copying scalars, and most other
3720 copy-ish functions and macros use this underneath.
3721
3722 =cut
3723 */
3724
3725 void
3726 Perl_sv_setsv_flags(pTHX_ SV *dstr, register SV *sstr, I32 flags)
3727 {
3728     register U32 sflags;
3729     register int dtype;
3730     register int stype;
3731
3732     if (sstr == dstr)
3733         return;
3734     SV_CHECK_THINKFIRST_COW_DROP(dstr);
3735     if (!sstr)
3736         sstr = &PL_sv_undef;
3737     stype = SvTYPE(sstr);
3738     dtype = SvTYPE(dstr);
3739
3740     SvAMAGIC_off(dstr);
3741     if ( SvVOK(dstr) )
3742     {
3743         /* need to nuke the magic */
3744         mg_free(dstr);
3745         SvRMAGICAL_off(dstr);
3746     }
3747
3748     /* There's a lot of redundancy below but we're going for speed here */
3749
3750     switch (stype) {
3751     case SVt_NULL:
3752       undef_sstr:
3753         if (dtype != SVt_PVGV) {
3754             (void)SvOK_off(dstr);
3755             return;
3756         }
3757         break;
3758     case SVt_IV:
3759         if (SvIOK(sstr)) {
3760             switch (dtype) {
3761             case SVt_NULL:
3762                 sv_upgrade(dstr, SVt_IV);
3763                 break;
3764             case SVt_NV:
3765                 sv_upgrade(dstr, SVt_PVNV);
3766                 break;
3767             case SVt_RV:
3768             case SVt_PV:
3769                 sv_upgrade(dstr, SVt_PVIV);
3770                 break;
3771             }
3772             (void)SvIOK_only(dstr);
3773             SvIV_set(dstr,  SvIVX(sstr));
3774             if (SvIsUV(sstr))
3775                 SvIsUV_on(dstr);
3776             if (SvTAINTED(sstr))
3777                 SvTAINT(dstr);
3778             return;
3779         }
3780         goto undef_sstr;
3781
3782     case SVt_NV:
3783         if (SvNOK(sstr)) {
3784             switch (dtype) {
3785             case SVt_NULL:
3786             case SVt_IV:
3787                 sv_upgrade(dstr, SVt_NV);
3788                 break;
3789             case SVt_RV:
3790             case SVt_PV:
3791             case SVt_PVIV:
3792                 sv_upgrade(dstr, SVt_PVNV);
3793                 break;
3794             }
3795             SvNV_set(dstr, SvNVX(sstr));
3796             (void)SvNOK_only(dstr);
3797             if (SvTAINTED(sstr))
3798                 SvTAINT(dstr);
3799             return;
3800         }
3801         goto undef_sstr;
3802
3803     case SVt_RV:
3804         if (dtype < SVt_RV)
3805             sv_upgrade(dstr, SVt_RV);
3806         else if (dtype == SVt_PVGV &&
3807                  SvROK(sstr) && SvTYPE(SvRV(sstr)) == SVt_PVGV) {
3808             sstr = SvRV(sstr);
3809             if (sstr == dstr) {
3810                 if (GvIMPORTED(dstr) != GVf_IMPORTED
3811                     && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3812                 {
3813                     GvIMPORTED_on(dstr);
3814                 }
3815                 GvMULTI_on(dstr);
3816                 return;
3817             }
3818             goto glob_assign;
3819         }
3820         break;
3821     case SVt_PVFM:
3822 #ifdef PERL_OLD_COPY_ON_WRITE
3823         if ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS) {
3824             if (dtype < SVt_PVIV)
3825                 sv_upgrade(dstr, SVt_PVIV);
3826             break;
3827         }
3828         /* Fall through */
3829 #endif
3830     case SVt_PV:
3831         if (dtype < SVt_PV)
3832             sv_upgrade(dstr, SVt_PV);
3833         break;
3834     case SVt_PVIV:
3835         if (dtype < SVt_PVIV)
3836             sv_upgrade(dstr, SVt_PVIV);
3837         break;
3838     case SVt_PVNV:
3839         if (dtype < SVt_PVNV)
3840             sv_upgrade(dstr, SVt_PVNV);
3841         break;
3842     case SVt_PVAV:
3843     case SVt_PVHV:
3844     case SVt_PVCV:
3845     case SVt_PVIO:
3846         {
3847         const char * const type = sv_reftype(sstr,0);
3848         if (PL_op)
3849             Perl_croak(aTHX_ "Bizarre copy of %s in %s", type, OP_NAME(PL_op));
3850         else
3851             Perl_croak(aTHX_ "Bizarre copy of %s", type);
3852         }
3853         break;
3854
3855     case SVt_PVGV:
3856         if (dtype <= SVt_PVGV) {
3857   glob_assign:
3858             if (dtype != SVt_PVGV) {
3859                 const char * const name = GvNAME(sstr);
3860                 const STRLEN len = GvNAMELEN(sstr);
3861                 /* don't upgrade SVt_PVLV: it can hold a glob */
3862                 if (dtype != SVt_PVLV)
3863                     sv_upgrade(dstr, SVt_PVGV);
3864                 sv_magic(dstr, dstr, PERL_MAGIC_glob, Nullch, 0);
3865                 GvSTASH(dstr) = (HV*)SvREFCNT_inc(GvSTASH(sstr));
3866                 GvNAME(dstr) = savepvn(name, len);
3867                 GvNAMELEN(dstr) = len;
3868                 SvFAKE_on(dstr);        /* can coerce to non-glob */
3869             }
3870             /* ahem, death to those who redefine active sort subs */
3871             else if (PL_curstackinfo->si_type == PERLSI_SORT
3872                      && GvCV(dstr) && PL_sortcop == CvSTART(GvCV(dstr)))
3873                 Perl_croak(aTHX_ "Can't redefine active sort subroutine %s",
3874                       GvNAME(dstr));
3875
3876 #ifdef GV_UNIQUE_CHECK
3877                 if (GvUNIQUE((GV*)dstr)) {
3878                     Perl_croak(aTHX_ PL_no_modify);
3879                 }
3880 #endif
3881
3882             (void)SvOK_off(dstr);
3883             GvINTRO_off(dstr);          /* one-shot flag */
3884             gp_free((GV*)dstr);
3885             GvGP(dstr) = gp_ref(GvGP(sstr));
3886             if (SvTAINTED(sstr))
3887                 SvTAINT(dstr);
3888             if (GvIMPORTED(dstr) != GVf_IMPORTED
3889                 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3890             {
3891                 GvIMPORTED_on(dstr);
3892             }
3893             GvMULTI_on(dstr);
3894             return;
3895         }
3896         /* FALL THROUGH */
3897
3898     default:
3899         if (SvGMAGICAL(sstr) && (flags & SV_GMAGIC)) {
3900             mg_get(sstr);
3901             if ((int)SvTYPE(sstr) != stype) {
3902                 stype = SvTYPE(sstr);
3903                 if (stype == SVt_PVGV && dtype <= SVt_PVGV)
3904                     goto glob_assign;
3905             }
3906         }
3907         if (stype == SVt_PVLV)
3908             SvUPGRADE(dstr, SVt_PVNV);
3909         else
3910             SvUPGRADE(dstr, (U32)stype);
3911     }
3912
3913     sflags = SvFLAGS(sstr);
3914
3915     if (sflags & SVf_ROK) {
3916         if (dtype >= SVt_PV) {
3917             if (dtype == SVt_PVGV) {
3918                 SV *sref = SvREFCNT_inc(SvRV(sstr));
3919                 SV *dref = 0;
3920                 const int intro = GvINTRO(dstr);
3921
3922 #ifdef GV_UNIQUE_CHECK
3923                 if (GvUNIQUE((GV*)dstr)) {
3924                     Perl_croak(aTHX_ PL_no_modify);
3925                 }
3926 #endif
3927
3928                 if (intro) {
3929                     GvINTRO_off(dstr);  /* one-shot flag */
3930                     GvLINE(dstr) = CopLINE(PL_curcop);
3931                     GvEGV(dstr) = (GV*)dstr;
3932                 }
3933                 GvMULTI_on(dstr);
3934                 switch (SvTYPE(sref)) {
3935                 case SVt_PVAV:
3936                     if (intro)
3937                         SAVEGENERICSV(GvAV(dstr));
3938                     else
3939                         dref = (SV*)GvAV(dstr);
3940                     GvAV(dstr) = (AV*)sref;
3941                     if (!GvIMPORTED_AV(dstr)
3942                         && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3943                     {
3944                         GvIMPORTED_AV_on(dstr);
3945                     }
3946                     break;
3947                 case SVt_PVHV:
3948                     if (intro)
3949                         SAVEGENERICSV(GvHV(dstr));
3950                     else
3951                         dref = (SV*)GvHV(dstr);
3952                     GvHV(dstr) = (HV*)sref;
3953                     if (!GvIMPORTED_HV(dstr)
3954                         && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3955                     {
3956                         GvIMPORTED_HV_on(dstr);
3957                     }
3958                     break;
3959                 case SVt_PVCV:
3960                     if (intro) {
3961                         if (GvCVGEN(dstr) && GvCV(dstr) != (CV*)sref) {
3962                             SvREFCNT_dec(GvCV(dstr));
3963                             GvCV(dstr) = Nullcv;
3964                             GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3965                             PL_sub_generation++;
3966                         }
3967                         SAVEGENERICSV(GvCV(dstr));
3968                     }
3969                     else
3970                         dref = (SV*)GvCV(dstr);
3971                     if (GvCV(dstr) != (CV*)sref) {
3972                         CV* cv = GvCV(dstr);
3973                         if (cv) {
3974                             if (!GvCVGEN((GV*)dstr) &&
3975                                 (CvROOT(cv) || CvXSUB(cv)))
3976                             {
3977                                 /* ahem, death to those who redefine
3978                                  * active sort subs */
3979                                 if (PL_curstackinfo->si_type == PERLSI_SORT &&
3980                                       PL_sortcop == CvSTART(cv))
3981                                     Perl_croak(aTHX_
3982                                     "Can't redefine active sort subroutine %s",
3983                                           GvENAME((GV*)dstr));
3984                                 /* Redefining a sub - warning is mandatory if
3985                                    it was a const and its value changed. */
3986                                 if (ckWARN(WARN_REDEFINE)
3987                                     || (CvCONST(cv)
3988                                         && (!CvCONST((CV*)sref)
3989                                             || sv_cmp(cv_const_sv(cv),
3990                                                       cv_const_sv((CV*)sref)))))
3991                                 {
3992                                     Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
3993                                         CvCONST(cv)
3994                                         ? "Constant subroutine %s::%s redefined"
3995                                         : "Subroutine %s::%s redefined",
3996                                         HvNAME_get(GvSTASH((GV*)dstr)),
3997                                         GvENAME((GV*)dstr));
3998                                 }
3999                             }
4000                             if (!intro)
4001                                 cv_ckproto(cv, (GV*)dstr,
4002                                            SvPOK(sref)
4003                                            ? SvPVX_const(sref) : Nullch);
4004                         }
4005                         GvCV(dstr) = (CV*)sref;
4006                         GvCVGEN(dstr) = 0; /* Switch off cacheness. */
4007                         GvASSUMECV_on(dstr);
4008                         PL_sub_generation++;
4009                     }
4010                     if (!GvIMPORTED_CV(dstr)
4011                         && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
4012                     {
4013                         GvIMPORTED_CV_on(dstr);
4014                     }
4015                     break;
4016                 case SVt_PVIO:
4017                     if (intro)
4018                         SAVEGENERICSV(GvIOp(dstr));
4019                     else
4020                         dref = (SV*)GvIOp(dstr);
4021                     GvIOp(dstr) = (IO*)sref;
4022                     break;
4023                 case SVt_PVFM:
4024                     if (intro)
4025                         SAVEGENERICSV(GvFORM(dstr));
4026                     else
4027                         dref = (SV*)GvFORM(dstr);
4028                     GvFORM(dstr) = (CV*)sref;
4029                     break;
4030                 default:
4031                     if (intro)
4032                         SAVEGENERICSV(GvSV(dstr));
4033                     else
4034                         dref = (SV*)GvSV(dstr);
4035                     GvSV(dstr) = sref;
4036                     if (!GvIMPORTED_SV(dstr)
4037                         && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
4038                     {
4039                         GvIMPORTED_SV_on(dstr);
4040                     }
4041                     break;
4042                 }
4043                 if (dref)
4044                     SvREFCNT_dec(dref);
4045                 if (SvTAINTED(sstr))
4046                     SvTAINT(dstr);
4047                 return;
4048             }
4049             if (SvPVX_const(dstr)) {
4050                 SvPV_free(dstr);
4051                 SvLEN_set(dstr, 0);
4052                 SvCUR_set(dstr, 0);
4053             }
4054         }
4055         (void)SvOK_off(dstr);
4056         SvRV_set(dstr, SvREFCNT_inc(SvRV(sstr)));
4057         SvROK_on(dstr);
4058         if (sflags & SVp_NOK) {
4059             SvNOKp_on(dstr);
4060             /* Only set the public OK flag if the source has public OK.  */
4061             if (sflags & SVf_NOK)
4062                 SvFLAGS(dstr) |= SVf_NOK;
4063             SvNV_set(dstr, SvNVX(sstr));
4064         }
4065         if (sflags & SVp_IOK) {
4066             (void)SvIOKp_on(dstr);
4067             if (sflags & SVf_IOK)
4068                 SvFLAGS(dstr) |= SVf_IOK;
4069             if (sflags & SVf_IVisUV)
4070                 SvIsUV_on(dstr);
4071             SvIV_set(dstr, SvIVX(sstr));
4072         }
4073         if (SvAMAGIC(sstr)) {
4074             SvAMAGIC_on(dstr);
4075         }
4076     }
4077     else if (sflags & SVp_POK) {
4078         bool isSwipe = 0;
4079
4080         /*
4081          * Check to see if we can just swipe the string.  If so, it's a
4082          * possible small lose on short strings, but a big win on long ones.
4083          * It might even be a win on short strings if SvPVX_const(dstr)
4084          * has to be allocated and SvPVX_const(sstr) has to be freed.
4085          */
4086
4087         /* Whichever path we take through the next code, we want this true,
4088            and doing it now facilitates the COW check.  */
4089         (void)SvPOK_only(dstr);
4090
4091         if (
4092             /* We're not already COW  */
4093             ((sflags & (SVf_FAKE | SVf_READONLY)) != (SVf_FAKE | SVf_READONLY)
4094 #ifndef PERL_OLD_COPY_ON_WRITE
4095              /* or we are, but dstr isn't a suitable target.  */
4096              || (SvFLAGS(dstr) & CAN_COW_MASK) != CAN_COW_FLAGS
4097 #endif
4098              )
4099             &&
4100             !(isSwipe =
4101                  (sflags & SVs_TEMP) &&   /* slated for free anyway? */
4102                  !(sflags & SVf_OOK) &&   /* and not involved in OOK hack? */
4103                  (!(flags & SV_NOSTEAL)) &&
4104                                         /* and we're allowed to steal temps */
4105                  SvREFCNT(sstr) == 1 &&   /* and no other references to it? */
4106                  SvLEN(sstr)    &&        /* and really is a string */
4107                                 /* and won't be needed again, potentially */
4108               !(PL_op && PL_op->op_type == OP_AASSIGN))
4109 #ifdef PERL_OLD_COPY_ON_WRITE
4110             && !((sflags & CAN_COW_MASK) == CAN_COW_FLAGS
4111                  && (SvFLAGS(dstr) & CAN_COW_MASK) == CAN_COW_FLAGS
4112                  && SvTYPE(sstr) >= SVt_PVIV)
4113 #endif
4114             ) {
4115             /* Failed the swipe test, and it's not a shared hash key either.
4116                Have to copy the string.  */
4117             STRLEN len = SvCUR(sstr);
4118             SvGROW(dstr, len + 1);      /* inlined from sv_setpvn */
4119             Move(SvPVX_const(sstr),SvPVX(dstr),len,char);
4120             SvCUR_set(dstr, len);
4121             *SvEND(dstr) = '\0';
4122         } else {
4123             /* If PERL_OLD_COPY_ON_WRITE is not defined, then isSwipe will always
4124                be true in here.  */
4125             /* Either it's a shared hash key, or it's suitable for
4126                copy-on-write or we can swipe the string.  */
4127             if (DEBUG_C_TEST) {
4128                 PerlIO_printf(Perl_debug_log, "Copy on write: sstr --> dstr\n");
4129                 sv_dump(sstr);
4130                 sv_dump(dstr);
4131             }
4132 #ifdef PERL_OLD_COPY_ON_WRITE
4133             if (!isSwipe) {
4134                 /* I believe I should acquire a global SV mutex if
4135                    it's a COW sv (not a shared hash key) to stop
4136                    it going un copy-on-write.
4137                    If the source SV has gone un copy on write between up there
4138                    and down here, then (assert() that) it is of the correct
4139                    form to make it copy on write again */
4140                 if ((sflags & (SVf_FAKE | SVf_READONLY))
4141                     != (SVf_FAKE | SVf_READONLY)) {
4142                     SvREADONLY_on(sstr);
4143                     SvFAKE_on(sstr);
4144                     /* Make the source SV into a loop of 1.
4145                        (about to become 2) */
4146                     SV_COW_NEXT_SV_SET(sstr, sstr);
4147                 }
4148             }
4149 #endif
4150             /* Initial code is common.  */
4151             if (SvPVX_const(dstr)) {            /* we know that dtype >= SVt_PV */
4152                 if (SvOOK(dstr)) {
4153                     SvFLAGS(dstr) &= ~SVf_OOK;
4154                     Safefree(SvPVX_const(dstr) - SvIVX(dstr));
4155                 }
4156                 else if (SvLEN(dstr))
4157                     Safefree(SvPVX_const(dstr));
4158             }
4159
4160             if (!isSwipe) {
4161                 /* making another shared SV.  */
4162                 STRLEN cur = SvCUR(sstr);
4163                 STRLEN len = SvLEN(sstr);
4164 #ifdef PERL_OLD_COPY_ON_WRITE
4165                 if (len) {
4166                     assert (SvTYPE(dstr) >= SVt_PVIV);
4167                     /* SvIsCOW_normal */
4168                     /* splice us in between source and next-after-source.  */
4169                     SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4170                     SV_COW_NEXT_SV_SET(sstr, dstr);
4171                     SvPV_set(dstr, SvPVX_mutable(sstr));
4172                 } else
4173 #endif
4174                 {
4175                     /* SvIsCOW_shared_hash */
4176                     DEBUG_C(PerlIO_printf(Perl_debug_log,
4177                                           "Copy on write: Sharing hash\n"));
4178
4179                     assert (SvTYPE(dstr) >= SVt_PV);
4180                     SvPV_set(dstr,
4181                              HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)))));
4182                 }
4183                 SvLEN_set(dstr, len);
4184                 SvCUR_set(dstr, cur);
4185                 SvREADONLY_on(dstr);
4186                 SvFAKE_on(dstr);
4187                 /* Relesase a global SV mutex.  */
4188             }
4189             else
4190                 {       /* Passes the swipe test.  */
4191                 SvPV_set(dstr, SvPVX_mutable(sstr));
4192                 SvLEN_set(dstr, SvLEN(sstr));
4193                 SvCUR_set(dstr, SvCUR(sstr));
4194
4195                 SvTEMP_off(dstr);
4196                 (void)SvOK_off(sstr);   /* NOTE: nukes most SvFLAGS on sstr */
4197                 SvPV_set(sstr, Nullch);
4198                 SvLEN_set(sstr, 0);
4199                 SvCUR_set(sstr, 0);
4200                 SvTEMP_off(sstr);
4201             }
4202         }
4203         if (sflags & SVf_UTF8)
4204             SvUTF8_on(dstr);
4205         if (sflags & SVp_NOK) {
4206             SvNOKp_on(dstr);
4207             if (sflags & SVf_NOK)
4208                 SvFLAGS(dstr) |= SVf_NOK;
4209             SvNV_set(dstr, SvNVX(sstr));
4210         }
4211         if (sflags & SVp_IOK) {
4212             (void)SvIOKp_on(dstr);
4213             if (sflags & SVf_IOK)
4214                 SvFLAGS(dstr) |= SVf_IOK;
4215             if (sflags & SVf_IVisUV)
4216                 SvIsUV_on(dstr);
4217             SvIV_set(dstr, SvIVX(sstr));
4218         }
4219         if (SvVOK(sstr)) {
4220             MAGIC *smg = mg_find(sstr,PERL_MAGIC_vstring);
4221             sv_magic(dstr, NULL, PERL_MAGIC_vstring,
4222                         smg->mg_ptr, smg->mg_len);
4223             SvRMAGICAL_on(dstr);
4224         }
4225     }
4226     else if (sflags & SVp_IOK) {
4227         if (sflags & SVf_IOK)
4228             (void)SvIOK_only(dstr);
4229         else {
4230             (void)SvOK_off(dstr);
4231             (void)SvIOKp_on(dstr);
4232         }
4233         /* XXXX Do we want to set IsUV for IV(ROK)?  Be extra safe... */
4234         if (sflags & SVf_IVisUV)
4235             SvIsUV_on(dstr);
4236         SvIV_set(dstr, SvIVX(sstr));
4237         if (sflags & SVp_NOK) {
4238             if (sflags & SVf_NOK)
4239                 (void)SvNOK_on(dstr);
4240             else
4241                 (void)SvNOKp_on(dstr);
4242             SvNV_set(dstr, SvNVX(sstr));
4243         }
4244     }
4245     else if (sflags & SVp_NOK) {
4246         if (sflags & SVf_NOK)
4247             (void)SvNOK_only(dstr);
4248         else {
4249             (void)SvOK_off(dstr);
4250             SvNOKp_on(dstr);
4251         }
4252         SvNV_set(dstr, SvNVX(sstr));
4253     }
4254     else {
4255         if (dtype == SVt_PVGV) {
4256             if (ckWARN(WARN_MISC))
4257                 Perl_warner(aTHX_ packWARN(WARN_MISC), "Undefined value assigned to typeglob");
4258         }
4259         else
4260             (void)SvOK_off(dstr);
4261     }
4262     if (SvTAINTED(sstr))
4263         SvTAINT(dstr);
4264 }
4265
4266 /*
4267 =for apidoc sv_setsv_mg
4268
4269 Like C<sv_setsv>, but also handles 'set' magic.
4270
4271 =cut
4272 */
4273
4274 void
4275 Perl_sv_setsv_mg(pTHX_ SV *dstr, register SV *sstr)
4276 {
4277     sv_setsv(dstr,sstr);
4278     SvSETMAGIC(dstr);
4279 }
4280
4281 #ifdef PERL_OLD_COPY_ON_WRITE
4282 SV *
4283 Perl_sv_setsv_cow(pTHX_ SV *dstr, SV *sstr)
4284 {
4285     STRLEN cur = SvCUR(sstr);
4286     STRLEN len = SvLEN(sstr);
4287     register char *new_pv;
4288
4289     if (DEBUG_C_TEST) {
4290         PerlIO_printf(Perl_debug_log, "Fast copy on write: %p -> %p\n",
4291                       sstr, dstr);
4292         sv_dump(sstr);
4293         if (dstr)
4294                     sv_dump(dstr);
4295     }
4296
4297     if (dstr) {
4298         if (SvTHINKFIRST(dstr))
4299             sv_force_normal_flags(dstr, SV_COW_DROP_PV);
4300         else if (SvPVX_const(dstr))
4301             Safefree(SvPVX_const(dstr));
4302     }
4303     else
4304         new_SV(dstr);
4305     SvUPGRADE(dstr, SVt_PVIV);
4306
4307     assert (SvPOK(sstr));
4308     assert (SvPOKp(sstr));
4309     assert (!SvIOK(sstr));
4310     assert (!SvIOKp(sstr));
4311     assert (!SvNOK(sstr));
4312     assert (!SvNOKp(sstr));
4313
4314     if (SvIsCOW(sstr)) {
4315
4316         if (SvLEN(sstr) == 0) {
4317             /* source is a COW shared hash key.  */
4318             DEBUG_C(PerlIO_printf(Perl_debug_log,
4319                                   "Fast copy on write: Sharing hash\n"));
4320             new_pv = HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr))));
4321             goto common_exit;
4322         }
4323         SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4324     } else {
4325         assert ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS);
4326         SvUPGRADE(sstr, SVt_PVIV);
4327         SvREADONLY_on(sstr);
4328         SvFAKE_on(sstr);
4329         DEBUG_C(PerlIO_printf(Perl_debug_log,
4330                               "Fast copy on write: Converting sstr to COW\n"));
4331         SV_COW_NEXT_SV_SET(dstr, sstr);
4332     }
4333     SV_COW_NEXT_SV_SET(sstr, dstr);
4334     new_pv = SvPVX_mutable(sstr);
4335
4336   common_exit:
4337     SvPV_set(dstr, new_pv);
4338     SvFLAGS(dstr) = (SVt_PVIV|SVf_POK|SVp_POK|SVf_FAKE|SVf_READONLY);
4339     if (SvUTF8(sstr))
4340         SvUTF8_on(dstr);
4341     SvLEN_set(dstr, len);
4342     SvCUR_set(dstr, cur);
4343     if (DEBUG_C_TEST) {
4344         sv_dump(dstr);
4345     }
4346     return dstr;
4347 }
4348 #endif
4349
4350 /*
4351 =for apidoc sv_setpvn
4352
4353 Copies a string into an SV.  The C<len> parameter indicates the number of
4354 bytes to be copied.  If the C<ptr> argument is NULL the SV will become
4355 undefined.  Does not handle 'set' magic.  See C<sv_setpvn_mg>.
4356
4357 =cut
4358 */
4359
4360 void
4361 Perl_sv_setpvn(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
4362 {
4363     register char *dptr;
4364
4365     SV_CHECK_THINKFIRST_COW_DROP(sv);
4366     if (!ptr) {
4367         (void)SvOK_off(sv);
4368         return;
4369     }
4370     else {
4371         /* len is STRLEN which is unsigned, need to copy to signed */
4372         const IV iv = len;
4373         if (iv < 0)
4374             Perl_croak(aTHX_ "panic: sv_setpvn called with negative strlen");
4375     }
4376     SvUPGRADE(sv, SVt_PV);
4377
4378     dptr = SvGROW(sv, len + 1);
4379     Move(ptr,dptr,len,char);
4380     dptr[len] = '\0';
4381     SvCUR_set(sv, len);
4382     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4383     SvTAINT(sv);
4384 }
4385
4386 /*
4387 =for apidoc sv_setpvn_mg
4388
4389 Like C<sv_setpvn>, but also handles 'set' magic.
4390
4391 =cut
4392 */
4393
4394 void
4395 Perl_sv_setpvn_mg(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
4396 {
4397     sv_setpvn(sv,ptr,len);
4398     SvSETMAGIC(sv);
4399 }
4400
4401 /*
4402 =for apidoc sv_setpv
4403
4404 Copies a string into an SV.  The string must be null-terminated.  Does not
4405 handle 'set' magic.  See C<sv_setpv_mg>.
4406
4407 =cut
4408 */
4409
4410 void
4411 Perl_sv_setpv(pTHX_ register SV *sv, register const char *ptr)
4412 {
4413     register STRLEN len;
4414
4415     SV_CHECK_THINKFIRST_COW_DROP(sv);
4416     if (!ptr) {
4417         (void)SvOK_off(sv);
4418         return;
4419     }
4420     len = strlen(ptr);
4421     SvUPGRADE(sv, SVt_PV);
4422
4423     SvGROW(sv, len + 1);
4424     Move(ptr,SvPVX(sv),len+1,char);
4425     SvCUR_set(sv, len);
4426     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4427     SvTAINT(sv);
4428 }
4429
4430 /*
4431 =for apidoc sv_setpv_mg
4432
4433 Like C<sv_setpv>, but also handles 'set' magic.
4434
4435 =cut
4436 */
4437
4438 void
4439 Perl_sv_setpv_mg(pTHX_ register SV *sv, register const char *ptr)
4440 {
4441     sv_setpv(sv,ptr);
4442     SvSETMAGIC(sv);
4443 }
4444
4445 /*
4446 =for apidoc sv_usepvn
4447
4448 Tells an SV to use C<ptr> to find its string value.  Normally the string is
4449 stored inside the SV but sv_usepvn allows the SV to use an outside string.
4450 The C<ptr> should point to memory that was allocated by C<malloc>.  The
4451 string length, C<len>, must be supplied.  This function will realloc the
4452 memory pointed to by C<ptr>, so that pointer should not be freed or used by
4453 the programmer after giving it to sv_usepvn.  Does not handle 'set' magic.
4454 See C<sv_usepvn_mg>.
4455
4456 =cut
4457 */
4458
4459 void
4460 Perl_sv_usepvn(pTHX_ register SV *sv, register char *ptr, register STRLEN len)
4461 {
4462     STRLEN allocate;
4463     SV_CHECK_THINKFIRST_COW_DROP(sv);
4464     SvUPGRADE(sv, SVt_PV);
4465     if (!ptr) {
4466         (void)SvOK_off(sv);
4467         return;
4468     }
4469     if (SvPVX_const(sv))
4470         SvPV_free(sv);
4471
4472     allocate = PERL_STRLEN_ROUNDUP(len + 1);
4473     ptr = saferealloc (ptr, allocate);
4474     SvPV_set(sv, ptr);
4475     SvCUR_set(sv, len);
4476     SvLEN_set(sv, allocate);
4477     *SvEND(sv) = '\0';
4478     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4479     SvTAINT(sv);
4480 }
4481
4482 /*
4483 =for apidoc sv_usepvn_mg
4484
4485 Like C<sv_usepvn>, but also handles 'set' magic.
4486
4487 =cut
4488 */
4489
4490 void
4491 Perl_sv_usepvn_mg(pTHX_ register SV *sv, register char *ptr, register STRLEN len)
4492 {
4493     sv_usepvn(sv,ptr,len);
4494     SvSETMAGIC(sv);
4495 }
4496
4497 #ifdef PERL_OLD_COPY_ON_WRITE
4498 /* Need to do this *after* making the SV normal, as we need the buffer
4499    pointer to remain valid until after we've copied it.  If we let go too early,
4500    another thread could invalidate it by unsharing last of the same hash key
4501    (which it can do by means other than releasing copy-on-write Svs)
4502    or by changing the other copy-on-write SVs in the loop.  */
4503 STATIC void
4504 S_sv_release_COW(pTHX_ register SV *sv, const char *pvx, STRLEN len, SV *after)
4505 {
4506     if (len) { /* this SV was SvIsCOW_normal(sv) */
4507          /* we need to find the SV pointing to us.  */
4508         SV *current = SV_COW_NEXT_SV(after);
4509
4510         if (current == sv) {
4511             /* The SV we point to points back to us (there were only two of us
4512                in the loop.)
4513                Hence other SV is no longer copy on write either.  */
4514             SvFAKE_off(after);
4515             SvREADONLY_off(after);
4516         } else {
4517             /* We need to follow the pointers around the loop.  */
4518             SV *next;
4519             while ((next = SV_COW_NEXT_SV(current)) != sv) {
4520                 assert (next);
4521                 current = next;
4522                  /* don't loop forever if the structure is bust, and we have
4523                     a pointer into a closed loop.  */
4524                 assert (current != after);
4525                 assert (SvPVX_const(current) == pvx);
4526             }
4527             /* Make the SV before us point to the SV after us.  */
4528             SV_COW_NEXT_SV_SET(current, after);
4529         }
4530     } else {
4531         unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4532     }
4533 }
4534
4535 int
4536 Perl_sv_release_IVX(pTHX_ register SV *sv)
4537 {
4538     if (SvIsCOW(sv))
4539         sv_force_normal_flags(sv, 0);
4540     SvOOK_off(sv);
4541     return 0;
4542 }
4543 #endif
4544 /*
4545 =for apidoc sv_force_normal_flags
4546
4547 Undo various types of fakery on an SV: if the PV is a shared string, make
4548 a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
4549 an xpvmg; if we're a copy-on-write scalar, this is the on-write time when
4550 we do the copy, and is also used locally. If C<SV_COW_DROP_PV> is set
4551 then a copy-on-write scalar drops its PV buffer (if any) and becomes
4552 SvPOK_off rather than making a copy. (Used where this scalar is about to be
4553 set to some other value.) In addition, the C<flags> parameter gets passed to
4554 C<sv_unref_flags()> when unrefing. C<sv_force_normal> calls this function
4555 with flags set to 0.
4556
4557 =cut
4558 */
4559
4560 void
4561 Perl_sv_force_normal_flags(pTHX_ register SV *sv, U32 flags)
4562 {
4563 #ifdef PERL_OLD_COPY_ON_WRITE
4564     if (SvREADONLY(sv)) {
4565         /* At this point I believe I should acquire a global SV mutex.  */
4566         if (SvFAKE(sv)) {
4567             const char *pvx = SvPVX_const(sv);
4568             const STRLEN len = SvLEN(sv);
4569             const STRLEN cur = SvCUR(sv);
4570             SV * const next = SV_COW_NEXT_SV(sv);   /* next COW sv in the loop. */
4571             if (DEBUG_C_TEST) {
4572                 PerlIO_printf(Perl_debug_log,
4573                               "Copy on write: Force normal %ld\n",
4574                               (long) flags);
4575                 sv_dump(sv);
4576             }
4577             SvFAKE_off(sv);
4578             SvREADONLY_off(sv);
4579             /* This SV doesn't own the buffer, so need to New() a new one:  */
4580             SvPV_set(sv, (char*)0);
4581             SvLEN_set(sv, 0);
4582             if (flags & SV_COW_DROP_PV) {
4583                 /* OK, so we don't need to copy our buffer.  */
4584                 SvPOK_off(sv);
4585             } else {
4586                 SvGROW(sv, cur + 1);
4587                 Move(pvx,SvPVX(sv),cur,char);
4588                 SvCUR_set(sv, cur);
4589                 *SvEND(sv) = '\0';
4590             }
4591             sv_release_COW(sv, pvx, len, next);
4592             if (DEBUG_C_TEST) {
4593                 sv_dump(sv);
4594             }
4595         }
4596         else if (IN_PERL_RUNTIME)
4597             Perl_croak(aTHX_ PL_no_modify);
4598         /* At this point I believe that I can drop the global SV mutex.  */
4599     }
4600 #else
4601     if (SvREADONLY(sv)) {
4602         if (SvFAKE(sv)) {
4603             const char *pvx = SvPVX_const(sv);
4604             const STRLEN len = SvCUR(sv);
4605             SvFAKE_off(sv);
4606             SvREADONLY_off(sv);
4607             SvPV_set(sv, Nullch);
4608             SvLEN_set(sv, 0);
4609             SvGROW(sv, len + 1);
4610             Move(pvx,SvPVX_const(sv),len,char);
4611             *SvEND(sv) = '\0';
4612             unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4613         }
4614         else if (IN_PERL_RUNTIME)
4615             Perl_croak(aTHX_ PL_no_modify);
4616     }
4617 #endif
4618     if (SvROK(sv))
4619         sv_unref_flags(sv, flags);
4620     else if (SvFAKE(sv) && SvTYPE(sv) == SVt_PVGV)
4621         sv_unglob(sv);
4622 }