Cannot use a L<> within a preformatted section of a Pod document.
[p5sagit/p5-mst-13.2.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, 2006, 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 /* if adding more checks watch out for the following tests:
34  *   t/op/index.t t/op/length.t t/op/pat.t t/op/substr.t
35  *   lib/utf8.t lib/Unicode/Collate/t/index.t
36  * --jhi
37  */
38 #   define ASSERT_UTF8_CACHE(cache) \
39     STMT_START { if (cache) { assert((cache)[0] <= (cache)[1]); \
40                               assert((cache)[2] <= (cache)[3]); \
41                               assert((cache)[3] <= (cache)[1]);} \
42                               } STMT_END
43 #else
44 #   define ASSERT_UTF8_CACHE(cache) NOOP
45 #endif
46
47 #ifdef PERL_OLD_COPY_ON_WRITE
48 #define SV_COW_NEXT_SV(sv)      INT2PTR(SV *,SvUVX(sv))
49 #define SV_COW_NEXT_SV_SET(current,next)        SvUV_set(current, PTR2UV(next))
50 /* This is a pessimistic view. Scalar must be purely a read-write PV to copy-
51    on-write.  */
52 #endif
53
54 /* ============================================================================
55
56 =head1 Allocation and deallocation of SVs.
57
58 An SV (or AV, HV, etc.) is allocated in two parts: the head (struct
59 sv, av, hv...) contains type and reference count information, and for
60 many types, a pointer to the body (struct xrv, xpv, xpviv...), which
61 contains fields specific to each type.  Some types store all they need
62 in the head, so don't have a body.
63
64 In all but the most memory-paranoid configuations (ex: PURIFY), heads
65 and bodies are allocated out of arenas, which by default are
66 approximately 4K chunks of memory parcelled up into N heads or bodies.
67 Sv-bodies are allocated by their sv-type, guaranteeing size
68 consistency needed to allocate safely from arrays.
69
70 For SV-heads, the first slot in each arena is reserved, and holds a
71 link to the next arena, some flags, and a note of the number of slots.
72 Snaked through each arena chain is a linked list of free items; when
73 this becomes empty, an extra arena is allocated and divided up into N
74 items which are threaded into the free list.
75
76 SV-bodies are similar, but they use arena-sets by default, which
77 separate the link and info from the arena itself, and reclaim the 1st
78 slot in the arena.  SV-bodies are further described later.
79
80 The following global variables are associated with arenas:
81
82     PL_sv_arenaroot     pointer to list of SV arenas
83     PL_sv_root          pointer to list of free SV structures
84
85     PL_body_arenas      head of linked-list of body arenas
86     PL_body_roots[]     array of pointers to list of free bodies of svtype
87                         arrays are indexed by the svtype needed
88
89 A few special SV heads are not allocated from an arena, but are
90 instead directly created in the interpreter structure, eg PL_sv_undef.
91 The size of arenas can be changed from the default by setting
92 PERL_ARENA_SIZE appropriately at compile time.
93
94 The SV arena serves the secondary purpose of allowing still-live SVs
95 to be located and destroyed during final cleanup.
96
97 At the lowest level, the macros new_SV() and del_SV() grab and free
98 an SV head.  (If debugging with -DD, del_SV() calls the function S_del_sv()
99 to return the SV to the free list with error checking.) new_SV() calls
100 more_sv() / sv_add_arena() to add an extra arena if the free list is empty.
101 SVs in the free list have their SvTYPE field set to all ones.
102
103 At the time of very final cleanup, sv_free_arenas() is called from
104 perl_destruct() to physically free all the arenas allocated since the
105 start of the interpreter.
106
107 Manipulation of any of the PL_*root pointers is protected by enclosing
108 LOCK_SV_MUTEX; ... UNLOCK_SV_MUTEX calls which should Do the Right Thing
109 if threads are enabled.
110
111 The function visit() scans the SV arenas list, and calls a specified
112 function for each SV it finds which is still live - ie which has an SvTYPE
113 other than all 1's, and a non-zero SvREFCNT. visit() is used by the
114 following functions (specified as [function that calls visit()] / [function
115 called by visit() for each SV]):
116
117     sv_report_used() / do_report_used()
118                         dump all remaining SVs (debugging aid)
119
120     sv_clean_objs() / do_clean_objs(),do_clean_named_objs()
121                         Attempt to free all objects pointed to by RVs,
122                         and, unless DISABLE_DESTRUCTOR_KLUDGE is defined,
123                         try to do the same for all objects indirectly
124                         referenced by typeglobs too.  Called once from
125                         perl_destruct(), prior to calling sv_clean_all()
126                         below.
127
128     sv_clean_all() / do_clean_all()
129                         SvREFCNT_dec(sv) each remaining SV, possibly
130                         triggering an sv_free(). It also sets the
131                         SVf_BREAK flag on the SV to indicate that the
132                         refcnt has been artificially lowered, and thus
133                         stopping sv_free() from giving spurious warnings
134                         about SVs which unexpectedly have a refcnt
135                         of zero.  called repeatedly from perl_destruct()
136                         until there are no SVs left.
137
138 =head2 Arena allocator API Summary
139
140 Private API to rest of sv.c
141
142     new_SV(),  del_SV(),
143
144     new_XIV(), del_XIV(),
145     new_XNV(), del_XNV(),
146     etc
147
148 Public API:
149
150     sv_report_used(), sv_clean_objs(), sv_clean_all(), sv_free_arenas()
151
152 =cut
153
154 ============================================================================ */
155
156 /*
157  * "A time to plant, and a time to uproot what was planted..."
158  */
159
160 /*
161  * nice_chunk and nice_chunk size need to be set
162  * and queried under the protection of sv_mutex
163  */
164 void
165 Perl_offer_nice_chunk(pTHX_ void *chunk, U32 chunk_size)
166 {
167     dVAR;
168     void *new_chunk;
169     U32 new_chunk_size;
170     LOCK_SV_MUTEX;
171     new_chunk = (void *)(chunk);
172     new_chunk_size = (chunk_size);
173     if (new_chunk_size > PL_nice_chunk_size) {
174         Safefree(PL_nice_chunk);
175         PL_nice_chunk = (char *) new_chunk;
176         PL_nice_chunk_size = new_chunk_size;
177     } else {
178         Safefree(chunk);
179     }
180     UNLOCK_SV_MUTEX;
181 }
182
183 #ifdef DEBUG_LEAKING_SCALARS
184 #  define FREE_SV_DEBUG_FILE(sv) Safefree((sv)->sv_debug_file)
185 #else
186 #  define FREE_SV_DEBUG_FILE(sv)
187 #endif
188
189 #ifdef PERL_POISON
190 #  define SvARENA_CHAIN(sv)     ((sv)->sv_u.svu_rv)
191 /* Whilst I'd love to do this, it seems that things like to check on
192    unreferenced scalars
193 #  define POSION_SV_HEAD(sv)    PoisonNew(sv, 1, struct STRUCT_SV)
194 */
195 #  define POSION_SV_HEAD(sv)    PoisonNew(&SvANY(sv), 1, void *), \
196                                 PoisonNew(&SvREFCNT(sv), 1, U32)
197 #else
198 #  define SvARENA_CHAIN(sv)     SvANY(sv)
199 #  define POSION_SV_HEAD(sv)
200 #endif
201
202 #define plant_SV(p) \
203     STMT_START {                                        \
204         FREE_SV_DEBUG_FILE(p);                          \
205         POSION_SV_HEAD(p);                              \
206         SvARENA_CHAIN(p) = (void *)PL_sv_root;          \
207         SvFLAGS(p) = SVTYPEMASK;                        \
208         PL_sv_root = (p);                               \
209         --PL_sv_count;                                  \
210     } STMT_END
211
212 /* sv_mutex must be held while calling uproot_SV() */
213 #define uproot_SV(p) \
214     STMT_START {                                        \
215         (p) = PL_sv_root;                               \
216         PL_sv_root = (SV*)SvARENA_CHAIN(p);             \
217         ++PL_sv_count;                                  \
218     } STMT_END
219
220
221 /* make some more SVs by adding another arena */
222
223 /* sv_mutex must be held while calling more_sv() */
224 STATIC SV*
225 S_more_sv(pTHX)
226 {
227     dVAR;
228     SV* sv;
229
230     if (PL_nice_chunk) {
231         sv_add_arena(PL_nice_chunk, PL_nice_chunk_size, 0);
232         PL_nice_chunk = NULL;
233         PL_nice_chunk_size = 0;
234     }
235     else {
236         char *chunk;                /* must use New here to match call to */
237         Newx(chunk,PERL_ARENA_SIZE,char);  /* Safefree() in sv_free_arenas() */
238         sv_add_arena(chunk, PERL_ARENA_SIZE, 0);
239     }
240     uproot_SV(sv);
241     return sv;
242 }
243
244 /* new_SV(): return a new, empty SV head */
245
246 #ifdef DEBUG_LEAKING_SCALARS
247 /* provide a real function for a debugger to play with */
248 STATIC SV*
249 S_new_SV(pTHX)
250 {
251     SV* sv;
252
253     LOCK_SV_MUTEX;
254     if (PL_sv_root)
255         uproot_SV(sv);
256     else
257         sv = S_more_sv(aTHX);
258     UNLOCK_SV_MUTEX;
259     SvANY(sv) = 0;
260     SvREFCNT(sv) = 1;
261     SvFLAGS(sv) = 0;
262     sv->sv_debug_optype = PL_op ? PL_op->op_type : 0;
263     sv->sv_debug_line = (U16) ((PL_copline == NOLINE) ?
264         (PL_curcop ? CopLINE(PL_curcop) : 0) : PL_copline);
265     sv->sv_debug_inpad = 0;
266     sv->sv_debug_cloned = 0;
267     sv->sv_debug_file = PL_curcop ? savepv(CopFILE(PL_curcop)): NULL;
268     
269     return sv;
270 }
271 #  define new_SV(p) (p)=S_new_SV(aTHX)
272
273 #else
274 #  define new_SV(p) \
275     STMT_START {                                        \
276         LOCK_SV_MUTEX;                                  \
277         if (PL_sv_root)                                 \
278             uproot_SV(p);                               \
279         else                                            \
280             (p) = S_more_sv(aTHX);                      \
281         UNLOCK_SV_MUTEX;                                \
282         SvANY(p) = 0;                                   \
283         SvREFCNT(p) = 1;                                \
284         SvFLAGS(p) = 0;                                 \
285     } STMT_END
286 #endif
287
288
289 /* del_SV(): return an empty SV head to the free list */
290
291 #ifdef DEBUGGING
292
293 #define del_SV(p) \
294     STMT_START {                                        \
295         LOCK_SV_MUTEX;                                  \
296         if (DEBUG_D_TEST)                               \
297             del_sv(p);                                  \
298         else                                            \
299             plant_SV(p);                                \
300         UNLOCK_SV_MUTEX;                                \
301     } STMT_END
302
303 STATIC void
304 S_del_sv(pTHX_ SV *p)
305 {
306     dVAR;
307     if (DEBUG_D_TEST) {
308         SV* sva;
309         bool ok = 0;
310         for (sva = PL_sv_arenaroot; sva; sva = (SV *) SvANY(sva)) {
311             const SV * const sv = sva + 1;
312             const SV * const svend = &sva[SvREFCNT(sva)];
313             if (p >= sv && p < svend) {
314                 ok = 1;
315                 break;
316             }
317         }
318         if (!ok) {
319             if (ckWARN_d(WARN_INTERNAL))        
320                 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
321                             "Attempt to free non-arena SV: 0x%"UVxf
322                             pTHX__FORMAT, PTR2UV(p) pTHX__VALUE);
323             return;
324         }
325     }
326     plant_SV(p);
327 }
328
329 #else /* ! DEBUGGING */
330
331 #define del_SV(p)   plant_SV(p)
332
333 #endif /* DEBUGGING */
334
335
336 /*
337 =head1 SV Manipulation Functions
338
339 =for apidoc sv_add_arena
340
341 Given a chunk of memory, link it to the head of the list of arenas,
342 and split it into a list of free SVs.
343
344 =cut
345 */
346
347 void
348 Perl_sv_add_arena(pTHX_ char *ptr, U32 size, U32 flags)
349 {
350     dVAR;
351     SV* const sva = (SV*)ptr;
352     register SV* sv;
353     register SV* svend;
354
355     /* The first SV in an arena isn't an SV. */
356     SvANY(sva) = (void *) PL_sv_arenaroot;              /* ptr to next arena */
357     SvREFCNT(sva) = size / sizeof(SV);          /* number of SV slots */
358     SvFLAGS(sva) = flags;                       /* FAKE if not to be freed */
359
360     PL_sv_arenaroot = sva;
361     PL_sv_root = sva + 1;
362
363     svend = &sva[SvREFCNT(sva) - 1];
364     sv = sva + 1;
365     while (sv < svend) {
366         SvARENA_CHAIN(sv) = (void *)(SV*)(sv + 1);
367 #ifdef DEBUGGING
368         SvREFCNT(sv) = 0;
369 #endif
370         /* Must always set typemask because it's awlays checked in on cleanup
371            when the arenas are walked looking for objects.  */
372         SvFLAGS(sv) = SVTYPEMASK;
373         sv++;
374     }
375     SvARENA_CHAIN(sv) = 0;
376 #ifdef DEBUGGING
377     SvREFCNT(sv) = 0;
378 #endif
379     SvFLAGS(sv) = SVTYPEMASK;
380 }
381
382 /* visit(): call the named function for each non-free SV in the arenas
383  * whose flags field matches the flags/mask args. */
384
385 STATIC I32
386 S_visit(pTHX_ SVFUNC_t f, U32 flags, U32 mask)
387 {
388     dVAR;
389     SV* sva;
390     I32 visited = 0;
391
392     for (sva = PL_sv_arenaroot; sva; sva = (SV*)SvANY(sva)) {
393         register const SV * const svend = &sva[SvREFCNT(sva)];
394         register SV* sv;
395         for (sv = sva + 1; sv < svend; ++sv) {
396             if (SvTYPE(sv) != SVTYPEMASK
397                     && (sv->sv_flags & mask) == flags
398                     && SvREFCNT(sv))
399             {
400                 (FCALL)(aTHX_ sv);
401                 ++visited;
402             }
403         }
404     }
405     return visited;
406 }
407
408 #ifdef DEBUGGING
409
410 /* called by sv_report_used() for each live SV */
411
412 static void
413 do_report_used(pTHX_ SV *sv)
414 {
415     if (SvTYPE(sv) != SVTYPEMASK) {
416         PerlIO_printf(Perl_debug_log, "****\n");
417         sv_dump(sv);
418     }
419 }
420 #endif
421
422 /*
423 =for apidoc sv_report_used
424
425 Dump the contents of all SVs not yet freed. (Debugging aid).
426
427 =cut
428 */
429
430 void
431 Perl_sv_report_used(pTHX)
432 {
433 #ifdef DEBUGGING
434     visit(do_report_used, 0, 0);
435 #else
436     PERL_UNUSED_CONTEXT;
437 #endif
438 }
439
440 /* called by sv_clean_objs() for each live SV */
441
442 static void
443 do_clean_objs(pTHX_ SV *ref)
444 {
445     dVAR;
446     if (SvROK(ref)) {
447         SV * const target = SvRV(ref);
448         if (SvOBJECT(target)) {
449             DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning object ref:\n "), sv_dump(ref)));
450             if (SvWEAKREF(ref)) {
451                 sv_del_backref(target, ref);
452                 SvWEAKREF_off(ref);
453                 SvRV_set(ref, NULL);
454             } else {
455                 SvROK_off(ref);
456                 SvRV_set(ref, NULL);
457                 SvREFCNT_dec(target);
458             }
459         }
460     }
461
462     /* XXX Might want to check arrays, etc. */
463 }
464
465 /* called by sv_clean_objs() for each live SV */
466
467 #ifndef DISABLE_DESTRUCTOR_KLUDGE
468 static void
469 do_clean_named_objs(pTHX_ SV *sv)
470 {
471     dVAR;
472     if (SvTYPE(sv) == SVt_PVGV && isGV_with_GP(sv) && GvGP(sv)) {
473         if ((
474 #ifdef PERL_DONT_CREATE_GVSV
475              GvSV(sv) &&
476 #endif
477              SvOBJECT(GvSV(sv))) ||
478              (GvAV(sv) && SvOBJECT(GvAV(sv))) ||
479              (GvHV(sv) && SvOBJECT(GvHV(sv))) ||
480              (GvIO(sv) && SvOBJECT(GvIO(sv))) ||
481              (GvCV(sv) && SvOBJECT(GvCV(sv))) )
482         {
483             DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning named glob object:\n "), sv_dump(sv)));
484             SvFLAGS(sv) |= SVf_BREAK;
485             SvREFCNT_dec(sv);
486         }
487     }
488 }
489 #endif
490
491 /*
492 =for apidoc sv_clean_objs
493
494 Attempt to destroy all objects not yet freed
495
496 =cut
497 */
498
499 void
500 Perl_sv_clean_objs(pTHX)
501 {
502     dVAR;
503     PL_in_clean_objs = TRUE;
504     visit(do_clean_objs, SVf_ROK, SVf_ROK);
505 #ifndef DISABLE_DESTRUCTOR_KLUDGE
506     /* some barnacles may yet remain, clinging to typeglobs */
507     visit(do_clean_named_objs, SVt_PVGV, SVTYPEMASK);
508 #endif
509     PL_in_clean_objs = FALSE;
510 }
511
512 /* called by sv_clean_all() for each live SV */
513
514 static void
515 do_clean_all(pTHX_ SV *sv)
516 {
517     dVAR;
518     DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning loops: SV at 0x%"UVxf"\n", PTR2UV(sv)) ));
519     SvFLAGS(sv) |= SVf_BREAK;
520     if (PL_comppad == (AV*)sv) {
521         PL_comppad = NULL;
522         PL_curpad = NULL;
523     }
524     SvREFCNT_dec(sv);
525 }
526
527 /*
528 =for apidoc sv_clean_all
529
530 Decrement the refcnt of each remaining SV, possibly triggering a
531 cleanup. This function may have to be called multiple times to free
532 SVs which are in complex self-referential hierarchies.
533
534 =cut
535 */
536
537 I32
538 Perl_sv_clean_all(pTHX)
539 {
540     dVAR;
541     I32 cleaned;
542     PL_in_clean_all = TRUE;
543     cleaned = visit(do_clean_all, 0,0);
544     PL_in_clean_all = FALSE;
545     return cleaned;
546 }
547
548 /*
549   ARENASETS: a meta-arena implementation which separates arena-info
550   into struct arena_set, which contains an array of struct
551   arena_descs, each holding info for a single arena.  By separating
552   the meta-info from the arena, we recover the 1st slot, formerly
553   borrowed for list management.  The arena_set is about the size of an
554   arena, avoiding the needless malloc overhead of a naive linked-list
555
556   The cost is 1 arena-set malloc per ~320 arena-mallocs, + the unused
557   memory in the last arena-set (1/2 on average).  In trade, we get
558   back the 1st slot in each arena (ie 1.7% of a CV-arena, less for
559   smaller types).  The recovery of the wasted space allows use of
560   small arenas for large, rare body types,
561 */
562 struct arena_desc {
563     char       *arena;          /* the raw storage, allocated aligned */
564     size_t      size;           /* its size ~4k typ */
565     int         unit_type;      /* useful for arena audits */
566     /* info for sv-heads (eventually)
567        int count, flags;
568     */
569 };
570
571 struct arena_set;
572
573 /* Get the maximum number of elements in set[] such that struct arena_set
574    will fit within PERL_ARENA_SIZE, which is probabably just under 4K, and
575    therefore likely to be 1 aligned memory page.  */
576
577 #define ARENAS_PER_SET  ((PERL_ARENA_SIZE - sizeof(struct arena_set*) \
578                           - 2 * sizeof(int)) / sizeof (struct arena_desc))
579
580 struct arena_set {
581     struct arena_set* next;
582     int   set_size;             /* ie ARENAS_PER_SET */
583     int   curr;                 /* index of next available arena-desc */
584     struct arena_desc set[ARENAS_PER_SET];
585 };
586
587 /*
588 =for apidoc sv_free_arenas
589
590 Deallocate the memory used by all arenas. Note that all the individual SV
591 heads and bodies within the arenas must already have been freed.
592
593 =cut
594 */
595 void
596 Perl_sv_free_arenas(pTHX)
597 {
598     dVAR;
599     SV* sva;
600     SV* svanext;
601     int i;
602
603     /* Free arenas here, but be careful about fake ones.  (We assume
604        contiguity of the fake ones with the corresponding real ones.) */
605
606     for (sva = PL_sv_arenaroot; sva; sva = svanext) {
607         svanext = (SV*) SvANY(sva);
608         while (svanext && SvFAKE(svanext))
609             svanext = (SV*) SvANY(svanext);
610
611         if (!SvFAKE(sva))
612             Safefree(sva);
613     }
614
615     {
616         struct arena_set *next, *aroot = (struct arena_set*) PL_body_arenas;
617         
618         for (; aroot; aroot = next) {
619             const int max = aroot->curr;
620             for (i=0; i<max; i++) {
621                 assert(aroot->set[i].arena);
622                 Safefree(aroot->set[i].arena);
623             }
624             next = aroot->next;
625             Safefree(aroot);
626         }
627     }
628     PL_body_arenas = 0;
629
630     for (i=0; i<PERL_ARENA_ROOTS_SIZE; i++)
631         PL_body_roots[i] = 0;
632
633     Safefree(PL_nice_chunk);
634     PL_nice_chunk = NULL;
635     PL_nice_chunk_size = 0;
636     PL_sv_arenaroot = 0;
637     PL_sv_root = 0;
638 }
639
640 /*
641   Here are mid-level routines that manage the allocation of bodies out
642   of the various arenas.  There are 5 kinds of arenas:
643
644   1. SV-head arenas, which are discussed and handled above
645   2. regular body arenas
646   3. arenas for reduced-size bodies
647   4. Hash-Entry arenas
648   5. pte arenas (thread related)
649
650   Arena types 2 & 3 are chained by body-type off an array of
651   arena-root pointers, which is indexed by svtype.  Some of the
652   larger/less used body types are malloced singly, since a large
653   unused block of them is wasteful.  Also, several svtypes dont have
654   bodies; the data fits into the sv-head itself.  The arena-root
655   pointer thus has a few unused root-pointers (which may be hijacked
656   later for arena types 4,5)
657
658   3 differs from 2 as an optimization; some body types have several
659   unused fields in the front of the structure (which are kept in-place
660   for consistency).  These bodies can be allocated in smaller chunks,
661   because the leading fields arent accessed.  Pointers to such bodies
662   are decremented to point at the unused 'ghost' memory, knowing that
663   the pointers are used with offsets to the real memory.
664
665   HE, HEK arenas are managed separately, with separate code, but may
666   be merge-able later..
667
668   PTE arenas are not sv-bodies, but they share these mid-level
669   mechanics, so are considered here.  The new mid-level mechanics rely
670   on the sv_type of the body being allocated, so we just reserve one
671   of the unused body-slots for PTEs, then use it in those (2) PTE
672   contexts below (line ~10k)
673 */
674
675 /* get_arena(size): this creates custom-sized arenas
676    TBD: export properly for hv.c: S_more_he().
677 */
678 void*
679 Perl_get_arena(pTHX_ int arena_size)
680 {
681     dVAR;
682     struct arena_desc* adesc;
683     struct arena_set *newroot, **aroot = (struct arena_set**) &PL_body_arenas;
684     int curr;
685
686     /* shouldnt need this
687     if (!arena_size)    arena_size = PERL_ARENA_SIZE;
688     */
689
690     /* may need new arena-set to hold new arena */
691     if (!*aroot || (*aroot)->curr >= (*aroot)->set_size) {
692         Newxz(newroot, 1, struct arena_set);
693         newroot->set_size = ARENAS_PER_SET;
694         newroot->next = *aroot;
695         *aroot = newroot;
696         DEBUG_m(PerlIO_printf(Perl_debug_log, "new arenaset %p\n", (void*)*aroot));
697     }
698
699     /* ok, now have arena-set with at least 1 empty/available arena-desc */
700     curr = (*aroot)->curr++;
701     adesc = &((*aroot)->set[curr]);
702     assert(!adesc->arena);
703     
704     Newxz(adesc->arena, arena_size, char);
705     adesc->size = arena_size;
706     DEBUG_m(PerlIO_printf(Perl_debug_log, "arena %d added: %p size %d\n", 
707                           curr, adesc->arena, arena_size));
708
709     return adesc->arena;
710 }
711
712
713 /* return a thing to the free list */
714
715 #define del_body(thing, root)                   \
716     STMT_START {                                \
717         void ** const thing_copy = (void **)thing;\
718         LOCK_SV_MUTEX;                          \
719         *thing_copy = *root;                    \
720         *root = (void*)thing_copy;              \
721         UNLOCK_SV_MUTEX;                        \
722     } STMT_END
723
724 /* 
725
726 =head1 SV-Body Allocation
727
728 Allocation of SV-bodies is similar to SV-heads, differing as follows;
729 the allocation mechanism is used for many body types, so is somewhat
730 more complicated, it uses arena-sets, and has no need for still-live
731 SV detection.
732
733 At the outermost level, (new|del)_X*V macros return bodies of the
734 appropriate type.  These macros call either (new|del)_body_type or
735 (new|del)_body_allocated macro pairs, depending on specifics of the
736 type.  Most body types use the former pair, the latter pair is used to
737 allocate body types with "ghost fields".
738
739 "ghost fields" are fields that are unused in certain types, and
740 consequently dont need to actually exist.  They are declared because
741 they're part of a "base type", which allows use of functions as
742 methods.  The simplest examples are AVs and HVs, 2 aggregate types
743 which don't use the fields which support SCALAR semantics.
744
745 For these types, the arenas are carved up into *_allocated size
746 chunks, we thus avoid wasted memory for those unaccessed members.
747 When bodies are allocated, we adjust the pointer back in memory by the
748 size of the bit not allocated, so it's as if we allocated the full
749 structure.  (But things will all go boom if you write to the part that
750 is "not there", because you'll be overwriting the last members of the
751 preceding structure in memory.)
752
753 We calculate the correction using the STRUCT_OFFSET macro. For
754 example, if xpv_allocated is the same structure as XPV then the two
755 OFFSETs sum to zero, and the pointer is unchanged. If the allocated
756 structure is smaller (no initial NV actually allocated) then the net
757 effect is to subtract the size of the NV from the pointer, to return a
758 new pointer as if an initial NV were actually allocated.
759
760 This is the same trick as was used for NV and IV bodies. Ironically it
761 doesn't need to be used for NV bodies any more, because NV is now at
762 the start of the structure. IV bodies don't need it either, because
763 they are no longer allocated.
764
765 In turn, the new_body_* allocators call S_new_body(), which invokes
766 new_body_inline macro, which takes a lock, and takes a body off the
767 linked list at PL_body_roots[sv_type], calling S_more_bodies() if
768 necessary to refresh an empty list.  Then the lock is released, and
769 the body is returned.
770
771 S_more_bodies calls get_arena(), and carves it up into an array of N
772 bodies, which it strings into a linked list.  It looks up arena-size
773 and body-size from the body_details table described below, thus
774 supporting the multiple body-types.
775
776 If PURIFY is defined, or PERL_ARENA_SIZE=0, arenas are not used, and
777 the (new|del)_X*V macros are mapped directly to malloc/free.
778
779 */
780
781 /* 
782
783 For each sv-type, struct body_details bodies_by_type[] carries
784 parameters which control these aspects of SV handling:
785
786 Arena_size determines whether arenas are used for this body type, and if
787 so, how big they are.  PURIFY or PERL_ARENA_SIZE=0 set this field to
788 zero, forcing individual mallocs and frees.
789
790 Body_size determines how big a body is, and therefore how many fit into
791 each arena.  Offset carries the body-pointer adjustment needed for
792 *_allocated body types, and is used in *_allocated macros.
793
794 But its main purpose is to parameterize info needed in
795 Perl_sv_upgrade().  The info here dramatically simplifies the function
796 vs the implementation in 5.8.7, making it table-driven.  All fields
797 are used for this, except for arena_size.
798
799 For the sv-types that have no bodies, arenas are not used, so those
800 PL_body_roots[sv_type] are unused, and can be overloaded.  In
801 something of a special case, SVt_NULL is borrowed for HE arenas;
802 PL_body_roots[SVt_NULL] is filled by S_more_he, but the
803 bodies_by_type[SVt_NULL] slot is not used, as the table is not
804 available in hv.c,
805
806 PTEs also use arenas, but are never seen in Perl_sv_upgrade.
807 Nonetheless, they get their own slot in bodies_by_type[SVt_NULL], so
808 they can just use the same allocation semantics.  At first, PTEs were
809 also overloaded to a non-body sv-type, but this yielded hard-to-find
810 malloc bugs, so was simplified by claiming a new slot.  This choice
811 has no consequence at this time.
812
813 */
814
815 struct body_details {
816     U8 body_size;       /* Size to allocate  */
817     U8 copy;            /* Size of structure to copy (may be shorter)  */
818     U8 offset;
819     unsigned int type : 4;          /* We have space for a sanity check.  */
820     unsigned int cant_upgrade : 1;  /* Cannot upgrade this type */
821     unsigned int zero_nv : 1;       /* zero the NV when upgrading from this */
822     unsigned int arena : 1;         /* Allocated from an arena */
823     size_t arena_size;              /* Size of arena to allocate */
824 };
825
826 #define HADNV FALSE
827 #define NONV TRUE
828
829
830 #ifdef PURIFY
831 /* With -DPURFIY we allocate everything directly, and don't use arenas.
832    This seems a rather elegant way to simplify some of the code below.  */
833 #define HASARENA FALSE
834 #else
835 #define HASARENA TRUE
836 #endif
837 #define NOARENA FALSE
838
839 /* Size the arenas to exactly fit a given number of bodies.  A count
840    of 0 fits the max number bodies into a PERL_ARENA_SIZE.block,
841    simplifying the default.  If count > 0, the arena is sized to fit
842    only that many bodies, allowing arenas to be used for large, rare
843    bodies (XPVFM, XPVIO) without undue waste.  The arena size is
844    limited by PERL_ARENA_SIZE, so we can safely oversize the
845    declarations.
846  */
847 #define FIT_ARENA0(body_size)                           \
848     ((size_t)(PERL_ARENA_SIZE / body_size) * body_size)
849 #define FIT_ARENAn(count,body_size)                     \
850     ( count * body_size <= PERL_ARENA_SIZE)             \
851     ? count * body_size                                 \
852     : FIT_ARENA0 (body_size)
853 #define FIT_ARENA(count,body_size)                      \
854     count                                               \
855     ? FIT_ARENAn (count, body_size)                     \
856     : FIT_ARENA0 (body_size)
857
858 /* A macro to work out the offset needed to subtract from a pointer to (say)
859
860 typedef struct {
861     STRLEN      xpv_cur;
862     STRLEN      xpv_len;
863 } xpv_allocated;
864
865 to make its members accessible via a pointer to (say)
866
867 struct xpv {
868     NV          xnv_nv;
869     STRLEN      xpv_cur;
870     STRLEN      xpv_len;
871 };
872
873 */
874
875 #define relative_STRUCT_OFFSET(longer, shorter, member) \
876     (STRUCT_OFFSET(shorter, member) - STRUCT_OFFSET(longer, member))
877
878 /* Calculate the length to copy. Specifically work out the length less any
879    final padding the compiler needed to add.  See the comment in sv_upgrade
880    for why copying the padding proved to be a bug.  */
881
882 #define copy_length(type, last_member) \
883         STRUCT_OFFSET(type, last_member) \
884         + sizeof (((type*)SvANY((SV*)0))->last_member)
885
886 static const struct body_details bodies_by_type[] = {
887     { sizeof(HE), 0, 0, SVt_NULL,
888       FALSE, NONV, NOARENA, FIT_ARENA(0, sizeof(HE)) },
889
890     /* IVs are in the head, so the allocation size is 0.
891        However, the slot is overloaded for PTEs.  */
892     { sizeof(struct ptr_tbl_ent), /* This is used for PTEs.  */
893       sizeof(IV), /* This is used to copy out the IV body.  */
894       STRUCT_OFFSET(XPVIV, xiv_iv), SVt_IV, FALSE, NONV,
895       NOARENA /* IVS don't need an arena  */,
896       /* But PTEs need to know the size of their arena  */
897       FIT_ARENA(0, sizeof(struct ptr_tbl_ent))
898     },
899
900     /* 8 bytes on most ILP32 with IEEE doubles */
901     { sizeof(NV), sizeof(NV), 0, SVt_NV, FALSE, HADNV, HASARENA,
902       FIT_ARENA(0, sizeof(NV)) },
903
904     /* RVs are in the head now.  */
905     { 0, 0, 0, SVt_RV, FALSE, NONV, NOARENA, 0 },
906
907     /* The bind placeholder pretends to be an RV for now.  */
908     { 0, 0, 0, SVt_BIND, FALSE, NONV, NOARENA, 0 },
909
910     /* 8 bytes on most ILP32 with IEEE doubles */
911     { sizeof(xpv_allocated),
912       copy_length(XPV, xpv_len)
913       - relative_STRUCT_OFFSET(xpv_allocated, XPV, xpv_cur),
914       + relative_STRUCT_OFFSET(xpv_allocated, XPV, xpv_cur),
915       SVt_PV, FALSE, NONV, HASARENA, FIT_ARENA(0, sizeof(xpv_allocated)) },
916
917     /* 12 */
918     { sizeof(xpviv_allocated),
919       copy_length(XPVIV, xiv_u)
920       - relative_STRUCT_OFFSET(xpviv_allocated, XPVIV, xpv_cur),
921       + relative_STRUCT_OFFSET(xpviv_allocated, XPVIV, xpv_cur),
922       SVt_PVIV, FALSE, NONV, HASARENA, FIT_ARENA(0, sizeof(xpviv_allocated)) },
923
924     /* 20 */
925     { sizeof(XPVNV), copy_length(XPVNV, xiv_u), 0, SVt_PVNV, FALSE, HADNV,
926       HASARENA, FIT_ARENA(0, sizeof(XPVNV)) },
927
928     /* 28 */
929     { sizeof(XPVMG), copy_length(XPVMG, xmg_stash), 0, SVt_PVMG, FALSE, HADNV,
930       HASARENA, FIT_ARENA(0, sizeof(XPVMG)) },
931     
932     /* 48 */
933     { sizeof(XPVGV), sizeof(XPVGV), 0, SVt_PVGV, TRUE, HADNV,
934       HASARENA, FIT_ARENA(0, sizeof(XPVGV)) },
935     
936     /* 64 */
937     { sizeof(XPVLV), sizeof(XPVLV), 0, SVt_PVLV, TRUE, HADNV,
938       HASARENA, FIT_ARENA(0, sizeof(XPVLV)) },
939
940     { sizeof(xpvav_allocated),
941       copy_length(XPVAV, xmg_stash)
942       - relative_STRUCT_OFFSET(xpvav_allocated, XPVAV, xav_fill),
943       + relative_STRUCT_OFFSET(xpvav_allocated, XPVAV, xav_fill),
944       SVt_PVAV, TRUE, HADNV, HASARENA, FIT_ARENA(0, sizeof(xpvav_allocated)) },
945
946     { sizeof(xpvhv_allocated),
947       copy_length(XPVHV, xmg_stash)
948       - relative_STRUCT_OFFSET(xpvhv_allocated, XPVHV, xhv_fill),
949       + relative_STRUCT_OFFSET(xpvhv_allocated, XPVHV, xhv_fill),
950       SVt_PVHV, TRUE, HADNV, HASARENA, FIT_ARENA(0, sizeof(xpvhv_allocated)) },
951
952     /* 56 */
953     { sizeof(xpvcv_allocated), sizeof(xpvcv_allocated),
954       + relative_STRUCT_OFFSET(xpvcv_allocated, XPVCV, xpv_cur),
955       SVt_PVCV, TRUE, NONV, HASARENA, FIT_ARENA(0, sizeof(xpvcv_allocated)) },
956
957     { sizeof(xpvfm_allocated), sizeof(xpvfm_allocated),
958       + relative_STRUCT_OFFSET(xpvfm_allocated, XPVFM, xpv_cur),
959       SVt_PVFM, TRUE, NONV, NOARENA, FIT_ARENA(20, sizeof(xpvfm_allocated)) },
960
961     /* XPVIO is 84 bytes, fits 48x */
962     { sizeof(XPVIO), sizeof(XPVIO), 0, SVt_PVIO, TRUE, HADNV,
963       HASARENA, FIT_ARENA(24, sizeof(XPVIO)) },
964 };
965
966 #define new_body_type(sv_type)          \
967     (void *)((char *)S_new_body(aTHX_ sv_type))
968
969 #define del_body_type(p, sv_type)       \
970     del_body(p, &PL_body_roots[sv_type])
971
972
973 #define new_body_allocated(sv_type)             \
974     (void *)((char *)S_new_body(aTHX_ sv_type)  \
975              - bodies_by_type[sv_type].offset)
976
977 #define del_body_allocated(p, sv_type)          \
978     del_body(p + bodies_by_type[sv_type].offset, &PL_body_roots[sv_type])
979
980
981 #define my_safemalloc(s)        (void*)safemalloc(s)
982 #define my_safecalloc(s)        (void*)safecalloc(s, 1)
983 #define my_safefree(p)  safefree((char*)p)
984
985 #ifdef PURIFY
986
987 #define new_XNV()       my_safemalloc(sizeof(XPVNV))
988 #define del_XNV(p)      my_safefree(p)
989
990 #define new_XPVNV()     my_safemalloc(sizeof(XPVNV))
991 #define del_XPVNV(p)    my_safefree(p)
992
993 #define new_XPVAV()     my_safemalloc(sizeof(XPVAV))
994 #define del_XPVAV(p)    my_safefree(p)
995
996 #define new_XPVHV()     my_safemalloc(sizeof(XPVHV))
997 #define del_XPVHV(p)    my_safefree(p)
998
999 #define new_XPVMG()     my_safemalloc(sizeof(XPVMG))
1000 #define del_XPVMG(p)    my_safefree(p)
1001
1002 #define new_XPVGV()     my_safemalloc(sizeof(XPVGV))
1003 #define del_XPVGV(p)    my_safefree(p)
1004
1005 #else /* !PURIFY */
1006
1007 #define new_XNV()       new_body_type(SVt_NV)
1008 #define del_XNV(p)      del_body_type(p, SVt_NV)
1009
1010 #define new_XPVNV()     new_body_type(SVt_PVNV)
1011 #define del_XPVNV(p)    del_body_type(p, SVt_PVNV)
1012
1013 #define new_XPVAV()     new_body_allocated(SVt_PVAV)
1014 #define del_XPVAV(p)    del_body_allocated(p, SVt_PVAV)
1015
1016 #define new_XPVHV()     new_body_allocated(SVt_PVHV)
1017 #define del_XPVHV(p)    del_body_allocated(p, SVt_PVHV)
1018
1019 #define new_XPVMG()     new_body_type(SVt_PVMG)
1020 #define del_XPVMG(p)    del_body_type(p, SVt_PVMG)
1021
1022 #define new_XPVGV()     new_body_type(SVt_PVGV)
1023 #define del_XPVGV(p)    del_body_type(p, SVt_PVGV)
1024
1025 #endif /* PURIFY */
1026
1027 /* no arena for you! */
1028
1029 #define new_NOARENA(details) \
1030         my_safemalloc((details)->body_size + (details)->offset)
1031 #define new_NOARENAZ(details) \
1032         my_safecalloc((details)->body_size + (details)->offset)
1033
1034 #if defined(DEBUGGING) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
1035 static bool done_sanity_check;
1036 #endif
1037
1038 STATIC void *
1039 S_more_bodies (pTHX_ svtype sv_type)
1040 {
1041     dVAR;
1042     void ** const root = &PL_body_roots[sv_type];
1043     const struct body_details * const bdp = &bodies_by_type[sv_type];
1044     const size_t body_size = bdp->body_size;
1045     char *start;
1046     const char *end;
1047
1048     assert(bdp->arena_size);
1049
1050 #if defined(DEBUGGING) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
1051     /* PERL_GLOBAL_STRUCT_PRIVATE cannot coexist with global
1052      * variables like done_sanity_check. */
1053     if (!done_sanity_check) {
1054         unsigned int i = SVt_LAST;
1055
1056         done_sanity_check = TRUE;
1057
1058         while (i--)
1059             assert (bodies_by_type[i].type == i);
1060     }
1061 #endif
1062
1063     start = (char*) Perl_get_arena(aTHX_ bdp->arena_size);
1064
1065     end = start + bdp->arena_size - body_size;
1066
1067     /* computed count doesnt reflect the 1st slot reservation */
1068     DEBUG_m(PerlIO_printf(Perl_debug_log,
1069                           "arena %p end %p arena-size %d type %d size %d ct %d\n",
1070                           start, end,
1071                           (int)bdp->arena_size, sv_type, (int)body_size,
1072                           (int)bdp->arena_size / (int)body_size));
1073
1074     *root = (void *)start;
1075
1076     while (start < end) {
1077         char * const next = start + body_size;
1078         *(void**) start = (void *)next;
1079         start = next;
1080     }
1081     *(void **)start = 0;
1082
1083     return *root;
1084 }
1085
1086 /* grab a new thing from the free list, allocating more if necessary.
1087    The inline version is used for speed in hot routines, and the
1088    function using it serves the rest (unless PURIFY).
1089 */
1090 #define new_body_inline(xpv, sv_type) \
1091     STMT_START { \
1092         void ** const r3wt = &PL_body_roots[sv_type]; \
1093         LOCK_SV_MUTEX; \
1094         xpv = (PTR_TBL_ENT_t*) (*((void **)(r3wt))      \
1095           ? *((void **)(r3wt)) : more_bodies(sv_type)); \
1096         *(r3wt) = *(void**)(xpv); \
1097         UNLOCK_SV_MUTEX; \
1098     } STMT_END
1099
1100 #ifndef PURIFY
1101
1102 STATIC void *
1103 S_new_body(pTHX_ svtype sv_type)
1104 {
1105     dVAR;
1106     void *xpv;
1107     new_body_inline(xpv, sv_type);
1108     return xpv;
1109 }
1110
1111 #endif
1112
1113 /*
1114 =for apidoc sv_upgrade
1115
1116 Upgrade an SV to a more complex form.  Generally adds a new body type to the
1117 SV, then copies across as much information as possible from the old body.
1118 You generally want to use the C<SvUPGRADE> macro wrapper. See also C<svtype>.
1119
1120 =cut
1121 */
1122
1123 void
1124 Perl_sv_upgrade(pTHX_ register SV *sv, svtype new_type)
1125 {
1126     dVAR;
1127     void*       old_body;
1128     void*       new_body;
1129     const svtype old_type = SvTYPE(sv);
1130     const struct body_details *new_type_details;
1131     const struct body_details *const old_type_details
1132         = bodies_by_type + old_type;
1133
1134     if (new_type != SVt_PV && SvIsCOW(sv)) {
1135         sv_force_normal_flags(sv, 0);
1136     }
1137
1138     if (old_type == new_type)
1139         return;
1140
1141     if (old_type > new_type)
1142         Perl_croak(aTHX_ "sv_upgrade from type %d down to type %d",
1143                 (int)old_type, (int)new_type);
1144
1145
1146     old_body = SvANY(sv);
1147
1148     /* Copying structures onto other structures that have been neatly zeroed
1149        has a subtle gotcha. Consider XPVMG
1150
1151        +------+------+------+------+------+-------+-------+
1152        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |
1153        +------+------+------+------+------+-------+-------+
1154        0      4      8     12     16     20      24      28
1155
1156        where NVs are aligned to 8 bytes, so that sizeof that structure is
1157        actually 32 bytes long, with 4 bytes of padding at the end:
1158
1159        +------+------+------+------+------+-------+-------+------+
1160        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH | ???  |
1161        +------+------+------+------+------+-------+-------+------+
1162        0      4      8     12     16     20      24      28     32
1163
1164        so what happens if you allocate memory for this structure:
1165
1166        +------+------+------+------+------+-------+-------+------+------+...
1167        |     NV      | CUR  | LEN  |  IV  | MAGIC | STASH |  GP  | NAME |
1168        +------+------+------+------+------+-------+-------+------+------+...
1169        0      4      8     12     16     20      24      28     32     36
1170
1171        zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
1172        expect, because you copy the area marked ??? onto GP. Now, ??? may have
1173        started out as zero once, but it's quite possible that it isn't. So now,
1174        rather than a nicely zeroed GP, you have it pointing somewhere random.
1175        Bugs ensue.
1176
1177        (In fact, GP ends up pointing at a previous GP structure, because the
1178        principle cause of the padding in XPVMG getting garbage is a copy of
1179        sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob)
1180
1181        So we are careful and work out the size of used parts of all the
1182        structures.  */
1183
1184     switch (old_type) {
1185     case SVt_NULL:
1186         break;
1187     case SVt_IV:
1188         if (new_type < SVt_PVIV) {
1189             new_type = (new_type == SVt_NV)
1190                 ? SVt_PVNV : SVt_PVIV;
1191         }
1192         break;
1193     case SVt_NV:
1194         if (new_type < SVt_PVNV) {
1195             new_type = SVt_PVNV;
1196         }
1197         break;
1198     case SVt_RV:
1199         break;
1200     case SVt_PV:
1201         assert(new_type > SVt_PV);
1202         assert(SVt_IV < SVt_PV);
1203         assert(SVt_NV < SVt_PV);
1204         break;
1205     case SVt_PVIV:
1206         break;
1207     case SVt_PVNV:
1208         break;
1209     case SVt_PVMG:
1210         /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1211            there's no way that it can be safely upgraded, because perl.c
1212            expects to Safefree(SvANY(PL_mess_sv))  */
1213         assert(sv != PL_mess_sv);
1214         /* This flag bit is used to mean other things in other scalar types.
1215            Given that it only has meaning inside the pad, it shouldn't be set
1216            on anything that can get upgraded.  */
1217         assert(!SvPAD_TYPED(sv));
1218         break;
1219     default:
1220         if (old_type_details->cant_upgrade)
1221             Perl_croak(aTHX_ "Can't upgrade %s (%" UVuf ") to %" UVuf,
1222                        sv_reftype(sv, 0), (UV) old_type, (UV) new_type);
1223     }
1224     new_type_details = bodies_by_type + new_type;
1225
1226     SvFLAGS(sv) &= ~SVTYPEMASK;
1227     SvFLAGS(sv) |= new_type;
1228
1229     /* This can't happen, as SVt_NULL is <= all values of new_type, so one of
1230        the return statements above will have triggered.  */
1231     assert (new_type != SVt_NULL);
1232     switch (new_type) {
1233     case SVt_IV:
1234         assert(old_type == SVt_NULL);
1235         SvANY(sv) = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
1236         SvIV_set(sv, 0);
1237         return;
1238     case SVt_NV:
1239         assert(old_type == SVt_NULL);
1240         SvANY(sv) = new_XNV();
1241         SvNV_set(sv, 0);
1242         return;
1243     case SVt_RV:
1244         assert(old_type == SVt_NULL);
1245         SvANY(sv) = &sv->sv_u.svu_rv;
1246         SvRV_set(sv, 0);
1247         return;
1248     case SVt_PVHV:
1249     case SVt_PVAV:
1250         assert(new_type_details->body_size);
1251
1252 #ifndef PURIFY  
1253         assert(new_type_details->arena);
1254         assert(new_type_details->arena_size);
1255         /* This points to the start of the allocated area.  */
1256         new_body_inline(new_body, new_type);
1257         Zero(new_body, new_type_details->body_size, char);
1258         new_body = ((char *)new_body) - new_type_details->offset;
1259 #else
1260         /* We always allocated the full length item with PURIFY. To do this
1261            we fake things so that arena is false for all 16 types..  */
1262         new_body = new_NOARENAZ(new_type_details);
1263 #endif
1264         SvANY(sv) = new_body;
1265         if (new_type == SVt_PVAV) {
1266             AvMAX(sv)   = -1;
1267             AvFILLp(sv) = -1;
1268             AvREAL_only(sv);
1269         }
1270
1271         /* SVt_NULL isn't the only thing upgraded to AV or HV.
1272            The target created by newSVrv also is, and it can have magic.
1273            However, it never has SvPVX set.
1274         */
1275         if (old_type >= SVt_RV) {
1276             assert(SvPVX_const(sv) == 0);
1277         }
1278
1279         if (old_type >= SVt_PVMG) {
1280             SvMAGIC_set(sv, ((XPVMG*)old_body)->xmg_u.xmg_magic);
1281             SvSTASH_set(sv, ((XPVMG*)old_body)->xmg_stash);
1282         } else {
1283             sv->sv_u.svu_array = NULL; /* or svu_hash  */
1284         }
1285         break;
1286
1287
1288     case SVt_PVIV:
1289         /* XXX Is this still needed?  Was it ever needed?   Surely as there is
1290            no route from NV to PVIV, NOK can never be true  */
1291         assert(!SvNOKp(sv));
1292         assert(!SvNOK(sv));
1293     case SVt_PVIO:
1294     case SVt_PVFM:
1295     case SVt_PVGV:
1296     case SVt_PVCV:
1297     case SVt_PVLV:
1298     case SVt_PVMG:
1299     case SVt_PVNV:
1300     case SVt_PV:
1301
1302         assert(new_type_details->body_size);
1303         /* We always allocated the full length item with PURIFY. To do this
1304            we fake things so that arena is false for all 16 types..  */
1305         if(new_type_details->arena) {
1306             /* This points to the start of the allocated area.  */
1307             new_body_inline(new_body, new_type);
1308             Zero(new_body, new_type_details->body_size, char);
1309             new_body = ((char *)new_body) - new_type_details->offset;
1310         } else {
1311             new_body = new_NOARENAZ(new_type_details);
1312         }
1313         SvANY(sv) = new_body;
1314
1315         if (old_type_details->copy) {
1316             /* There is now the potential for an upgrade from something without
1317                an offset (PVNV or PVMG) to something with one (PVCV, PVFM)  */
1318             int offset = old_type_details->offset;
1319             int length = old_type_details->copy;
1320
1321             if (new_type_details->offset > old_type_details->offset) {
1322                 const int difference
1323                     = new_type_details->offset - old_type_details->offset;
1324                 offset += difference;
1325                 length -= difference;
1326             }
1327             assert (length >= 0);
1328                 
1329             Copy((char *)old_body + offset, (char *)new_body + offset, length,
1330                  char);
1331         }
1332
1333 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1334         /* If NV 0.0 is stores as all bits 0 then Zero() already creates a
1335          * correct 0.0 for us.  Otherwise, if the old body didn't have an
1336          * NV slot, but the new one does, then we need to initialise the
1337          * freshly created NV slot with whatever the correct bit pattern is
1338          * for 0.0  */
1339         if (old_type_details->zero_nv && !new_type_details->zero_nv)
1340             SvNV_set(sv, 0);
1341 #endif
1342
1343         if (new_type == SVt_PVIO)
1344             IoPAGE_LEN(sv) = 60;
1345         if (old_type < SVt_RV)
1346             SvPV_set(sv, NULL);
1347         break;
1348     default:
1349         Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu",
1350                    (unsigned long)new_type);
1351     }
1352
1353     if (old_type_details->arena) {
1354         /* If there was an old body, then we need to free it.
1355            Note that there is an assumption that all bodies of types that
1356            can be upgraded came from arenas. Only the more complex non-
1357            upgradable types are allowed to be directly malloc()ed.  */
1358 #ifdef PURIFY
1359         my_safefree(old_body);
1360 #else
1361         del_body((void*)((char*)old_body + old_type_details->offset),
1362                  &PL_body_roots[old_type]);
1363 #endif
1364     }
1365 }
1366
1367 /*
1368 =for apidoc sv_backoff
1369
1370 Remove any string offset. You should normally use the C<SvOOK_off> macro
1371 wrapper instead.
1372
1373 =cut
1374 */
1375
1376 int
1377 Perl_sv_backoff(pTHX_ register SV *sv)
1378 {
1379     PERL_UNUSED_CONTEXT;
1380     assert(SvOOK(sv));
1381     assert(SvTYPE(sv) != SVt_PVHV);
1382     assert(SvTYPE(sv) != SVt_PVAV);
1383     if (SvIVX(sv)) {
1384         const char * const s = SvPVX_const(sv);
1385         SvLEN_set(sv, SvLEN(sv) + SvIVX(sv));
1386         SvPV_set(sv, SvPVX(sv) - SvIVX(sv));
1387         SvIV_set(sv, 0);
1388         Move(s, SvPVX(sv), SvCUR(sv)+1, char);
1389     }
1390     SvFLAGS(sv) &= ~SVf_OOK;
1391     return 0;
1392 }
1393
1394 /*
1395 =for apidoc sv_grow
1396
1397 Expands the character buffer in the SV.  If necessary, uses C<sv_unref> and
1398 upgrades the SV to C<SVt_PV>.  Returns a pointer to the character buffer.
1399 Use the C<SvGROW> wrapper instead.
1400
1401 =cut
1402 */
1403
1404 char *
1405 Perl_sv_grow(pTHX_ register SV *sv, register STRLEN newlen)
1406 {
1407     register char *s;
1408
1409     if (PL_madskills && newlen >= 0x100000) {
1410         PerlIO_printf(Perl_debug_log,
1411                       "Allocation too large: %"UVxf"\n", (UV)newlen);
1412     }
1413 #ifdef HAS_64K_LIMIT
1414     if (newlen >= 0x10000) {
1415         PerlIO_printf(Perl_debug_log,
1416                       "Allocation too large: %"UVxf"\n", (UV)newlen);
1417         my_exit(1);
1418     }
1419 #endif /* HAS_64K_LIMIT */
1420     if (SvROK(sv))
1421         sv_unref(sv);
1422     if (SvTYPE(sv) < SVt_PV) {
1423         sv_upgrade(sv, SVt_PV);
1424         s = SvPVX_mutable(sv);
1425     }
1426     else if (SvOOK(sv)) {       /* pv is offset? */
1427         sv_backoff(sv);
1428         s = SvPVX_mutable(sv);
1429         if (newlen > SvLEN(sv))
1430             newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1431 #ifdef HAS_64K_LIMIT
1432         if (newlen >= 0x10000)
1433             newlen = 0xFFFF;
1434 #endif
1435     }
1436     else
1437         s = SvPVX_mutable(sv);
1438
1439     if (newlen > SvLEN(sv)) {           /* need more room? */
1440         newlen = PERL_STRLEN_ROUNDUP(newlen);
1441         if (SvLEN(sv) && s) {
1442 #ifdef MYMALLOC
1443             const STRLEN l = malloced_size((void*)SvPVX_const(sv));
1444             if (newlen <= l) {
1445                 SvLEN_set(sv, l);
1446                 return s;
1447             } else
1448 #endif
1449             s = (char*)saferealloc(s, newlen);
1450         }
1451         else {
1452             s = (char*)safemalloc(newlen);
1453             if (SvPVX_const(sv) && SvCUR(sv)) {
1454                 Move(SvPVX_const(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1455             }
1456         }
1457         SvPV_set(sv, s);
1458         SvLEN_set(sv, newlen);
1459     }
1460     return s;
1461 }
1462
1463 /*
1464 =for apidoc sv_setiv
1465
1466 Copies an integer into the given SV, upgrading first if necessary.
1467 Does not handle 'set' magic.  See also C<sv_setiv_mg>.
1468
1469 =cut
1470 */
1471
1472 void
1473 Perl_sv_setiv(pTHX_ register SV *sv, IV i)
1474 {
1475     dVAR;
1476     SV_CHECK_THINKFIRST_COW_DROP(sv);
1477     switch (SvTYPE(sv)) {
1478     case SVt_NULL:
1479         sv_upgrade(sv, SVt_IV);
1480         break;
1481     case SVt_NV:
1482         sv_upgrade(sv, SVt_PVNV);
1483         break;
1484     case SVt_RV:
1485     case SVt_PV:
1486         sv_upgrade(sv, SVt_PVIV);
1487         break;
1488
1489     case SVt_PVGV:
1490     case SVt_PVAV:
1491     case SVt_PVHV:
1492     case SVt_PVCV:
1493     case SVt_PVFM:
1494     case SVt_PVIO:
1495         Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1496                    OP_DESC(PL_op));
1497     default: NOOP;
1498     }
1499     (void)SvIOK_only(sv);                       /* validate number */
1500     SvIV_set(sv, i);
1501     SvTAINT(sv);
1502 }
1503
1504 /*
1505 =for apidoc sv_setiv_mg
1506
1507 Like C<sv_setiv>, but also handles 'set' magic.
1508
1509 =cut
1510 */
1511
1512 void
1513 Perl_sv_setiv_mg(pTHX_ register SV *sv, IV i)
1514 {
1515     sv_setiv(sv,i);
1516     SvSETMAGIC(sv);
1517 }
1518
1519 /*
1520 =for apidoc sv_setuv
1521
1522 Copies an unsigned integer into the given SV, upgrading first if necessary.
1523 Does not handle 'set' magic.  See also C<sv_setuv_mg>.
1524
1525 =cut
1526 */
1527
1528 void
1529 Perl_sv_setuv(pTHX_ register SV *sv, UV u)
1530 {
1531     /* With these two if statements:
1532        u=1.49  s=0.52  cu=72.49  cs=10.64  scripts=270  tests=20865
1533
1534        without
1535        u=1.35  s=0.47  cu=73.45  cs=11.43  scripts=270  tests=20865
1536
1537        If you wish to remove them, please benchmark to see what the effect is
1538     */
1539     if (u <= (UV)IV_MAX) {
1540        sv_setiv(sv, (IV)u);
1541        return;
1542     }
1543     sv_setiv(sv, 0);
1544     SvIsUV_on(sv);
1545     SvUV_set(sv, u);
1546 }
1547
1548 /*
1549 =for apidoc sv_setuv_mg
1550
1551 Like C<sv_setuv>, but also handles 'set' magic.
1552
1553 =cut
1554 */
1555
1556 void
1557 Perl_sv_setuv_mg(pTHX_ register SV *sv, UV u)
1558 {
1559     sv_setuv(sv,u);
1560     SvSETMAGIC(sv);
1561 }
1562
1563 /*
1564 =for apidoc sv_setnv
1565
1566 Copies a double into the given SV, upgrading first if necessary.
1567 Does not handle 'set' magic.  See also C<sv_setnv_mg>.
1568
1569 =cut
1570 */
1571
1572 void
1573 Perl_sv_setnv(pTHX_ register SV *sv, NV num)
1574 {
1575     dVAR;
1576     SV_CHECK_THINKFIRST_COW_DROP(sv);
1577     switch (SvTYPE(sv)) {
1578     case SVt_NULL:
1579     case SVt_IV:
1580         sv_upgrade(sv, SVt_NV);
1581         break;
1582     case SVt_RV:
1583     case SVt_PV:
1584     case SVt_PVIV:
1585         sv_upgrade(sv, SVt_PVNV);
1586         break;
1587
1588     case SVt_PVGV:
1589     case SVt_PVAV:
1590     case SVt_PVHV:
1591     case SVt_PVCV:
1592     case SVt_PVFM:
1593     case SVt_PVIO:
1594         Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
1595                    OP_NAME(PL_op));
1596     default: NOOP;
1597     }
1598     SvNV_set(sv, num);
1599     (void)SvNOK_only(sv);                       /* validate number */
1600     SvTAINT(sv);
1601 }
1602
1603 /*
1604 =for apidoc sv_setnv_mg
1605
1606 Like C<sv_setnv>, but also handles 'set' magic.
1607
1608 =cut
1609 */
1610
1611 void
1612 Perl_sv_setnv_mg(pTHX_ register SV *sv, NV num)
1613 {
1614     sv_setnv(sv,num);
1615     SvSETMAGIC(sv);
1616 }
1617
1618 /* Print an "isn't numeric" warning, using a cleaned-up,
1619  * printable version of the offending string
1620  */
1621
1622 STATIC void
1623 S_not_a_number(pTHX_ SV *sv)
1624 {
1625      dVAR;
1626      SV *dsv;
1627      char tmpbuf[64];
1628      const char *pv;
1629
1630      if (DO_UTF8(sv)) {
1631           dsv = sv_2mortal(newSVpvs(""));
1632           pv = sv_uni_display(dsv, sv, 10, 0);
1633      } else {
1634           char *d = tmpbuf;
1635           const char * const limit = tmpbuf + sizeof(tmpbuf) - 8;
1636           /* each *s can expand to 4 chars + "...\0",
1637              i.e. need room for 8 chars */
1638         
1639           const char *s = SvPVX_const(sv);
1640           const char * const end = s + SvCUR(sv);
1641           for ( ; s < end && d < limit; s++ ) {
1642                int ch = *s & 0xFF;
1643                if (ch & 128 && !isPRINT_LC(ch)) {
1644                     *d++ = 'M';
1645                     *d++ = '-';
1646                     ch &= 127;
1647                }
1648                if (ch == '\n') {
1649                     *d++ = '\\';
1650                     *d++ = 'n';
1651                }
1652                else if (ch == '\r') {
1653                     *d++ = '\\';
1654                     *d++ = 'r';
1655                }
1656                else if (ch == '\f') {
1657                     *d++ = '\\';
1658                     *d++ = 'f';
1659                }
1660                else if (ch == '\\') {
1661                     *d++ = '\\';
1662                     *d++ = '\\';
1663                }
1664                else if (ch == '\0') {
1665                     *d++ = '\\';
1666                     *d++ = '0';
1667                }
1668                else if (isPRINT_LC(ch))
1669                     *d++ = ch;
1670                else {
1671                     *d++ = '^';
1672                     *d++ = toCTRL(ch);
1673                }
1674           }
1675           if (s < end) {
1676                *d++ = '.';
1677                *d++ = '.';
1678                *d++ = '.';
1679           }
1680           *d = '\0';
1681           pv = tmpbuf;
1682     }
1683
1684     if (PL_op)
1685         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1686                     "Argument \"%s\" isn't numeric in %s", pv,
1687                     OP_DESC(PL_op));
1688     else
1689         Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1690                     "Argument \"%s\" isn't numeric", pv);
1691 }
1692
1693 /*
1694 =for apidoc looks_like_number
1695
1696 Test if the content of an SV looks like a number (or is a number).
1697 C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1698 non-numeric warning), even if your atof() doesn't grok them.
1699
1700 =cut
1701 */
1702
1703 I32
1704 Perl_looks_like_number(pTHX_ SV *sv)
1705 {
1706     register const char *sbegin;
1707     STRLEN len;
1708
1709     if (SvPOK(sv)) {
1710         sbegin = SvPVX_const(sv);
1711         len = SvCUR(sv);
1712     }
1713     else if (SvPOKp(sv))
1714         sbegin = SvPV_const(sv, len);
1715     else
1716         return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
1717     return grok_number(sbegin, len, NULL);
1718 }
1719
1720 STATIC bool
1721 S_glob_2number(pTHX_ GV * const gv)
1722 {
1723     const U32 wasfake = SvFLAGS(gv) & SVf_FAKE;
1724     SV *const buffer = sv_newmortal();
1725
1726     /* FAKE globs can get coerced, so need to turn this off temporarily if it
1727        is on.  */
1728     SvFAKE_off(gv);
1729     gv_efullname3(buffer, gv, "*");
1730     SvFLAGS(gv) |= wasfake;
1731
1732     /* We know that all GVs stringify to something that is not-a-number,
1733         so no need to test that.  */
1734     if (ckWARN(WARN_NUMERIC))
1735         not_a_number(buffer);
1736     /* We just want something true to return, so that S_sv_2iuv_common
1737         can tail call us and return true.  */
1738     return TRUE;
1739 }
1740
1741 STATIC char *
1742 S_glob_2pv(pTHX_ GV * const gv, STRLEN * const len)
1743 {
1744     const U32 wasfake = SvFLAGS(gv) & SVf_FAKE;
1745     SV *const buffer = sv_newmortal();
1746
1747     /* FAKE globs can get coerced, so need to turn this off temporarily if it
1748        is on.  */
1749     SvFAKE_off(gv);
1750     gv_efullname3(buffer, gv, "*");
1751     SvFLAGS(gv) |= wasfake;
1752
1753     assert(SvPOK(buffer));
1754     if (len) {
1755         *len = SvCUR(buffer);
1756     }
1757     return SvPVX(buffer);
1758 }
1759
1760 /* Actually, ISO C leaves conversion of UV to IV undefined, but
1761    until proven guilty, assume that things are not that bad... */
1762
1763 /*
1764    NV_PRESERVES_UV:
1765
1766    As 64 bit platforms often have an NV that doesn't preserve all bits of
1767    an IV (an assumption perl has been based on to date) it becomes necessary
1768    to remove the assumption that the NV always carries enough precision to
1769    recreate the IV whenever needed, and that the NV is the canonical form.
1770    Instead, IV/UV and NV need to be given equal rights. So as to not lose
1771    precision as a side effect of conversion (which would lead to insanity
1772    and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1773    1) to distinguish between IV/UV/NV slots that have cached a valid
1774       conversion where precision was lost and IV/UV/NV slots that have a
1775       valid conversion which has lost no precision
1776    2) to ensure that if a numeric conversion to one form is requested that
1777       would lose precision, the precise conversion (or differently
1778       imprecise conversion) is also performed and cached, to prevent
1779       requests for different numeric formats on the same SV causing
1780       lossy conversion chains. (lossless conversion chains are perfectly
1781       acceptable (still))
1782
1783
1784    flags are used:
1785    SvIOKp is true if the IV slot contains a valid value
1786    SvIOK  is true only if the IV value is accurate (UV if SvIOK_UV true)
1787    SvNOKp is true if the NV slot contains a valid value
1788    SvNOK  is true only if the NV value is accurate
1789
1790    so
1791    while converting from PV to NV, check to see if converting that NV to an
1792    IV(or UV) would lose accuracy over a direct conversion from PV to
1793    IV(or UV). If it would, cache both conversions, return NV, but mark
1794    SV as IOK NOKp (ie not NOK).
1795
1796    While converting from PV to IV, check to see if converting that IV to an
1797    NV would lose accuracy over a direct conversion from PV to NV. If it
1798    would, cache both conversions, flag similarly.
1799
1800    Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1801    correctly because if IV & NV were set NV *always* overruled.
1802    Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1803    changes - now IV and NV together means that the two are interchangeable:
1804    SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
1805
1806    The benefit of this is that operations such as pp_add know that if
1807    SvIOK is true for both left and right operands, then integer addition
1808    can be used instead of floating point (for cases where the result won't
1809    overflow). Before, floating point was always used, which could lead to
1810    loss of precision compared with integer addition.
1811
1812    * making IV and NV equal status should make maths accurate on 64 bit
1813      platforms
1814    * may speed up maths somewhat if pp_add and friends start to use
1815      integers when possible instead of fp. (Hopefully the overhead in
1816      looking for SvIOK and checking for overflow will not outweigh the
1817      fp to integer speedup)
1818    * will slow down integer operations (callers of SvIV) on "inaccurate"
1819      values, as the change from SvIOK to SvIOKp will cause a call into
1820      sv_2iv each time rather than a macro access direct to the IV slot
1821    * should speed up number->string conversion on integers as IV is
1822      favoured when IV and NV are equally accurate
1823
1824    ####################################################################
1825    You had better be using SvIOK_notUV if you want an IV for arithmetic:
1826    SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
1827    On the other hand, SvUOK is true iff UV.
1828    ####################################################################
1829
1830    Your mileage will vary depending your CPU's relative fp to integer
1831    performance ratio.
1832 */
1833
1834 #ifndef NV_PRESERVES_UV
1835 #  define IS_NUMBER_UNDERFLOW_IV 1
1836 #  define IS_NUMBER_UNDERFLOW_UV 2
1837 #  define IS_NUMBER_IV_AND_UV    2
1838 #  define IS_NUMBER_OVERFLOW_IV  4
1839 #  define IS_NUMBER_OVERFLOW_UV  5
1840
1841 /* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
1842
1843 /* For sv_2nv these three cases are "SvNOK and don't bother casting"  */
1844 STATIC int
1845 S_sv_2iuv_non_preserve(pTHX_ register SV *sv, I32 numtype)
1846 {
1847     dVAR;
1848     PERL_UNUSED_ARG(numtype); /* Used only under DEBUGGING? */
1849     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));
1850     if (SvNVX(sv) < (NV)IV_MIN) {
1851         (void)SvIOKp_on(sv);
1852         (void)SvNOK_on(sv);
1853         SvIV_set(sv, IV_MIN);
1854         return IS_NUMBER_UNDERFLOW_IV;
1855     }
1856     if (SvNVX(sv) > (NV)UV_MAX) {
1857         (void)SvIOKp_on(sv);
1858         (void)SvNOK_on(sv);
1859         SvIsUV_on(sv);
1860         SvUV_set(sv, UV_MAX);
1861         return IS_NUMBER_OVERFLOW_UV;
1862     }
1863     (void)SvIOKp_on(sv);
1864     (void)SvNOK_on(sv);
1865     /* Can't use strtol etc to convert this string.  (See truth table in
1866        sv_2iv  */
1867     if (SvNVX(sv) <= (UV)IV_MAX) {
1868         SvIV_set(sv, I_V(SvNVX(sv)));
1869         if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
1870             SvIOK_on(sv); /* Integer is precise. NOK, IOK */
1871         } else {
1872             /* Integer is imprecise. NOK, IOKp */
1873         }
1874         return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
1875     }
1876     SvIsUV_on(sv);
1877     SvUV_set(sv, U_V(SvNVX(sv)));
1878     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
1879         if (SvUVX(sv) == UV_MAX) {
1880             /* As we know that NVs don't preserve UVs, UV_MAX cannot
1881                possibly be preserved by NV. Hence, it must be overflow.
1882                NOK, IOKp */
1883             return IS_NUMBER_OVERFLOW_UV;
1884         }
1885         SvIOK_on(sv); /* Integer is precise. NOK, UOK */
1886     } else {
1887         /* Integer is imprecise. NOK, IOKp */
1888     }
1889     return IS_NUMBER_OVERFLOW_IV;
1890 }
1891 #endif /* !NV_PRESERVES_UV*/
1892
1893 STATIC bool
1894 S_sv_2iuv_common(pTHX_ SV *sv) {
1895     dVAR;
1896     if (SvNOKp(sv)) {
1897         /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
1898          * without also getting a cached IV/UV from it at the same time
1899          * (ie PV->NV conversion should detect loss of accuracy and cache
1900          * IV or UV at same time to avoid this. */
1901         /* IV-over-UV optimisation - choose to cache IV if possible */
1902
1903         if (SvTYPE(sv) == SVt_NV)
1904             sv_upgrade(sv, SVt_PVNV);
1905
1906         (void)SvIOKp_on(sv);    /* Must do this first, to clear any SvOOK */
1907         /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
1908            certainly cast into the IV range at IV_MAX, whereas the correct
1909            answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
1910            cases go to UV */
1911 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
1912         if (Perl_isnan(SvNVX(sv))) {
1913             SvUV_set(sv, 0);
1914             SvIsUV_on(sv);
1915             return FALSE;
1916         }
1917 #endif
1918         if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
1919             SvIV_set(sv, I_V(SvNVX(sv)));
1920             if (SvNVX(sv) == (NV) SvIVX(sv)
1921 #ifndef NV_PRESERVES_UV
1922                 && (((UV)1 << NV_PRESERVES_UV_BITS) >
1923                     (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
1924                 /* Don't flag it as "accurately an integer" if the number
1925                    came from a (by definition imprecise) NV operation, and
1926                    we're outside the range of NV integer precision */
1927 #endif
1928                 ) {
1929                 SvIOK_on(sv);  /* Can this go wrong with rounding? NWC */
1930                 DEBUG_c(PerlIO_printf(Perl_debug_log,
1931                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
1932                                       PTR2UV(sv),
1933                                       SvNVX(sv),
1934                                       SvIVX(sv)));
1935
1936             } else {
1937                 /* IV not precise.  No need to convert from PV, as NV
1938                    conversion would already have cached IV if it detected
1939                    that PV->IV would be better than PV->NV->IV
1940                    flags already correct - don't set public IOK.  */
1941                 DEBUG_c(PerlIO_printf(Perl_debug_log,
1942                                       "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
1943                                       PTR2UV(sv),
1944                                       SvNVX(sv),
1945                                       SvIVX(sv)));
1946             }
1947             /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
1948                but the cast (NV)IV_MIN rounds to a the value less (more
1949                negative) than IV_MIN which happens to be equal to SvNVX ??
1950                Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
1951                NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
1952                (NV)UVX == NVX are both true, but the values differ. :-(
1953                Hopefully for 2s complement IV_MIN is something like
1954                0x8000000000000000 which will be exact. NWC */
1955         }
1956         else {
1957             SvUV_set(sv, U_V(SvNVX(sv)));
1958             if (
1959                 (SvNVX(sv) == (NV) SvUVX(sv))
1960 #ifndef  NV_PRESERVES_UV
1961                 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
1962                 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
1963                 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
1964                 /* Don't flag it as "accurately an integer" if the number
1965                    came from a (by definition imprecise) NV operation, and
1966                    we're outside the range of NV integer precision */
1967 #endif
1968                 )
1969                 SvIOK_on(sv);
1970             SvIsUV_on(sv);
1971             DEBUG_c(PerlIO_printf(Perl_debug_log,
1972                                   "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
1973                                   PTR2UV(sv),
1974                                   SvUVX(sv),
1975                                   SvUVX(sv)));
1976         }
1977     }
1978     else if (SvPOKp(sv) && SvLEN(sv)) {
1979         UV value;
1980         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
1981         /* We want to avoid a possible problem when we cache an IV/ a UV which
1982            may be later translated to an NV, and the resulting NV is not
1983            the same as the direct translation of the initial string
1984            (eg 123.456 can shortcut to the IV 123 with atol(), but we must
1985            be careful to ensure that the value with the .456 is around if the
1986            NV value is requested in the future).
1987         
1988            This means that if we cache such an IV/a UV, we need to cache the
1989            NV as well.  Moreover, we trade speed for space, and do not
1990            cache the NV if we are sure it's not needed.
1991          */
1992
1993         /* SVt_PVNV is one higher than SVt_PVIV, hence this order  */
1994         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
1995              == IS_NUMBER_IN_UV) {
1996             /* It's definitely an integer, only upgrade to PVIV */
1997             if (SvTYPE(sv) < SVt_PVIV)
1998                 sv_upgrade(sv, SVt_PVIV);
1999             (void)SvIOK_on(sv);
2000         } else if (SvTYPE(sv) < SVt_PVNV)
2001             sv_upgrade(sv, SVt_PVNV);
2002
2003         /* If NVs preserve UVs then we only use the UV value if we know that
2004            we aren't going to call atof() below. If NVs don't preserve UVs
2005            then the value returned may have more precision than atof() will
2006            return, even though value isn't perfectly accurate.  */
2007         if ((numtype & (IS_NUMBER_IN_UV
2008 #ifdef NV_PRESERVES_UV
2009                         | IS_NUMBER_NOT_INT
2010 #endif
2011             )) == IS_NUMBER_IN_UV) {
2012             /* This won't turn off the public IOK flag if it was set above  */
2013             (void)SvIOKp_on(sv);
2014
2015             if (!(numtype & IS_NUMBER_NEG)) {
2016                 /* positive */;
2017                 if (value <= (UV)IV_MAX) {
2018                     SvIV_set(sv, (IV)value);
2019                 } else {
2020                     /* it didn't overflow, and it was positive. */
2021                     SvUV_set(sv, value);
2022                     SvIsUV_on(sv);
2023                 }
2024             } else {
2025                 /* 2s complement assumption  */
2026                 if (value <= (UV)IV_MIN) {
2027                     SvIV_set(sv, -(IV)value);
2028                 } else {
2029                     /* Too negative for an IV.  This is a double upgrade, but
2030                        I'm assuming it will be rare.  */
2031                     if (SvTYPE(sv) < SVt_PVNV)
2032                         sv_upgrade(sv, SVt_PVNV);
2033                     SvNOK_on(sv);
2034                     SvIOK_off(sv);
2035                     SvIOKp_on(sv);
2036                     SvNV_set(sv, -(NV)value);
2037                     SvIV_set(sv, IV_MIN);
2038                 }
2039             }
2040         }
2041         /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2042            will be in the previous block to set the IV slot, and the next
2043            block to set the NV slot.  So no else here.  */
2044         
2045         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2046             != IS_NUMBER_IN_UV) {
2047             /* It wasn't an (integer that doesn't overflow the UV). */
2048             SvNV_set(sv, Atof(SvPVX_const(sv)));
2049
2050             if (! numtype && ckWARN(WARN_NUMERIC))
2051                 not_a_number(sv);
2052
2053 #if defined(USE_LONG_DOUBLE)
2054             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" PERL_PRIgldbl ")\n",
2055                                   PTR2UV(sv), SvNVX(sv)));
2056 #else
2057             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"NVgf")\n",
2058                                   PTR2UV(sv), SvNVX(sv)));
2059 #endif
2060
2061 #ifdef NV_PRESERVES_UV
2062             (void)SvIOKp_on(sv);
2063             (void)SvNOK_on(sv);
2064             if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2065                 SvIV_set(sv, I_V(SvNVX(sv)));
2066                 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2067                     SvIOK_on(sv);
2068                 } else {
2069                     NOOP;  /* Integer is imprecise. NOK, IOKp */
2070                 }
2071                 /* UV will not work better than IV */
2072             } else {
2073                 if (SvNVX(sv) > (NV)UV_MAX) {
2074                     SvIsUV_on(sv);
2075                     /* Integer is inaccurate. NOK, IOKp, is UV */
2076                     SvUV_set(sv, UV_MAX);
2077                 } else {
2078                     SvUV_set(sv, U_V(SvNVX(sv)));
2079                     /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2080                        NV preservse UV so can do correct comparison.  */
2081                     if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2082                         SvIOK_on(sv);
2083                     } else {
2084                         NOOP;   /* Integer is imprecise. NOK, IOKp, is UV */
2085                     }
2086                 }
2087                 SvIsUV_on(sv);
2088             }
2089 #else /* NV_PRESERVES_UV */
2090             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2091                 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2092                 /* The IV/UV slot will have been set from value returned by
2093                    grok_number above.  The NV slot has just been set using
2094                    Atof.  */
2095                 SvNOK_on(sv);
2096                 assert (SvIOKp(sv));
2097             } else {
2098                 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2099                     U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2100                     /* Small enough to preserve all bits. */
2101                     (void)SvIOKp_on(sv);
2102                     SvNOK_on(sv);
2103                     SvIV_set(sv, I_V(SvNVX(sv)));
2104                     if ((NV)(SvIVX(sv)) == SvNVX(sv))
2105                         SvIOK_on(sv);
2106                     /* Assumption: first non-preserved integer is < IV_MAX,
2107                        this NV is in the preserved range, therefore: */
2108                     if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2109                           < (UV)IV_MAX)) {
2110                         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);
2111                     }
2112                 } else {
2113                     /* IN_UV NOT_INT
2114                          0      0       already failed to read UV.
2115                          0      1       already failed to read UV.
2116                          1      0       you won't get here in this case. IV/UV
2117                                         slot set, public IOK, Atof() unneeded.
2118                          1      1       already read UV.
2119                        so there's no point in sv_2iuv_non_preserve() attempting
2120                        to use atol, strtol, strtoul etc.  */
2121                     sv_2iuv_non_preserve (sv, numtype);
2122                 }
2123             }
2124 #endif /* NV_PRESERVES_UV */
2125         }
2126     }
2127     else  {
2128         if (isGV_with_GP(sv))
2129             return glob_2number((GV *)sv);
2130
2131         if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2132             if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2133                 report_uninit(sv);
2134         }
2135         if (SvTYPE(sv) < SVt_IV)
2136             /* Typically the caller expects that sv_any is not NULL now.  */
2137             sv_upgrade(sv, SVt_IV);
2138         /* Return 0 from the caller.  */
2139         return TRUE;
2140     }
2141     return FALSE;
2142 }
2143
2144 /*
2145 =for apidoc sv_2iv_flags
2146
2147 Return the integer value of an SV, doing any necessary string
2148 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2149 Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2150
2151 =cut
2152 */
2153
2154 IV
2155 Perl_sv_2iv_flags(pTHX_ register SV *sv, I32 flags)
2156 {
2157     dVAR;
2158     if (!sv)
2159         return 0;
2160     if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2161         /* FBMs use the same flag bit as SVf_IVisUV, so must let them
2162            cache IVs just in case. In practice it seems that they never
2163            actually anywhere accessible by user Perl code, let alone get used
2164            in anything other than a string context.  */
2165         if (flags & SV_GMAGIC)
2166             mg_get(sv);
2167         if (SvIOKp(sv))
2168             return SvIVX(sv);
2169         if (SvNOKp(sv)) {
2170             return I_V(SvNVX(sv));
2171         }
2172         if (SvPOKp(sv) && SvLEN(sv)) {
2173             UV value;
2174             const int numtype
2175                 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2176
2177             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2178                 == IS_NUMBER_IN_UV) {
2179                 /* It's definitely an integer */
2180                 if (numtype & IS_NUMBER_NEG) {
2181                     if (value < (UV)IV_MIN)
2182                         return -(IV)value;
2183                 } else {
2184                     if (value < (UV)IV_MAX)
2185                         return (IV)value;
2186                 }
2187             }
2188             if (!numtype) {
2189                 if (ckWARN(WARN_NUMERIC))
2190                     not_a_number(sv);
2191             }
2192             return I_V(Atof(SvPVX_const(sv)));
2193         }
2194         if (SvROK(sv)) {
2195             goto return_rok;
2196         }
2197         assert(SvTYPE(sv) >= SVt_PVMG);
2198         /* This falls through to the report_uninit inside S_sv_2iuv_common.  */
2199     } else if (SvTHINKFIRST(sv)) {
2200         if (SvROK(sv)) {
2201         return_rok:
2202             if (SvAMAGIC(sv)) {
2203                 SV * const tmpstr=AMG_CALLun(sv,numer);
2204                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2205                     return SvIV(tmpstr);
2206                 }
2207             }
2208             return PTR2IV(SvRV(sv));
2209         }
2210         if (SvIsCOW(sv)) {
2211             sv_force_normal_flags(sv, 0);
2212         }
2213         if (SvREADONLY(sv) && !SvOK(sv)) {
2214             if (ckWARN(WARN_UNINITIALIZED))
2215                 report_uninit(sv);
2216             return 0;
2217         }
2218     }
2219     if (!SvIOKp(sv)) {
2220         if (S_sv_2iuv_common(aTHX_ sv))
2221             return 0;
2222     }
2223     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2224         PTR2UV(sv),SvIVX(sv)));
2225     return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
2226 }
2227
2228 /*
2229 =for apidoc sv_2uv_flags
2230
2231 Return the unsigned integer value of an SV, doing any necessary string
2232 conversion.  If flags includes SV_GMAGIC, does an mg_get() first.
2233 Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
2234
2235 =cut
2236 */
2237
2238 UV
2239 Perl_sv_2uv_flags(pTHX_ register SV *sv, I32 flags)
2240 {
2241     dVAR;
2242     if (!sv)
2243         return 0;
2244     if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2245         /* FBMs use the same flag bit as SVf_IVisUV, so must let them
2246            cache IVs just in case.  */
2247         if (flags & SV_GMAGIC)
2248             mg_get(sv);
2249         if (SvIOKp(sv))
2250             return SvUVX(sv);
2251         if (SvNOKp(sv))
2252             return U_V(SvNVX(sv));
2253         if (SvPOKp(sv) && SvLEN(sv)) {
2254             UV value;
2255             const int numtype
2256                 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2257
2258             if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2259                 == IS_NUMBER_IN_UV) {
2260                 /* It's definitely an integer */
2261                 if (!(numtype & IS_NUMBER_NEG))
2262                     return value;
2263             }
2264             if (!numtype) {
2265                 if (ckWARN(WARN_NUMERIC))
2266                     not_a_number(sv);
2267             }
2268             return U_V(Atof(SvPVX_const(sv)));
2269         }
2270         if (SvROK(sv)) {
2271             goto return_rok;
2272         }
2273         assert(SvTYPE(sv) >= SVt_PVMG);
2274         /* This falls through to the report_uninit inside S_sv_2iuv_common.  */
2275     } else if (SvTHINKFIRST(sv)) {
2276         if (SvROK(sv)) {
2277         return_rok:
2278             if (SvAMAGIC(sv)) {
2279                 SV *const tmpstr = AMG_CALLun(sv,numer);
2280                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2281                     return SvUV(tmpstr);
2282                 }
2283             }
2284             return PTR2UV(SvRV(sv));
2285         }
2286         if (SvIsCOW(sv)) {
2287             sv_force_normal_flags(sv, 0);
2288         }
2289         if (SvREADONLY(sv) && !SvOK(sv)) {
2290             if (ckWARN(WARN_UNINITIALIZED))
2291                 report_uninit(sv);
2292             return 0;
2293         }
2294     }
2295     if (!SvIOKp(sv)) {
2296         if (S_sv_2iuv_common(aTHX_ sv))
2297             return 0;
2298     }
2299
2300     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2301                           PTR2UV(sv),SvUVX(sv)));
2302     return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
2303 }
2304
2305 /*
2306 =for apidoc sv_2nv
2307
2308 Return the num value of an SV, doing any necessary string or integer
2309 conversion, magic etc. Normally used via the C<SvNV(sv)> and C<SvNVx(sv)>
2310 macros.
2311
2312 =cut
2313 */
2314
2315 NV
2316 Perl_sv_2nv(pTHX_ register SV *sv)
2317 {
2318     dVAR;
2319     if (!sv)
2320         return 0.0;
2321     if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2322         /* FBMs use the same flag bit as SVf_IVisUV, so must let them
2323            cache IVs just in case.  */
2324         mg_get(sv);
2325         if (SvNOKp(sv))
2326             return SvNVX(sv);
2327         if ((SvPOKp(sv) && SvLEN(sv)) && !SvIOKp(sv)) {
2328             if (!SvIOKp(sv) && ckWARN(WARN_NUMERIC) &&
2329                 !grok_number(SvPVX_const(sv), SvCUR(sv), NULL))
2330                 not_a_number(sv);
2331             return Atof(SvPVX_const(sv));
2332         }
2333         if (SvIOKp(sv)) {
2334             if (SvIsUV(sv))
2335                 return (NV)SvUVX(sv);
2336             else
2337                 return (NV)SvIVX(sv);
2338         }
2339         if (SvROK(sv)) {
2340             goto return_rok;
2341         }
2342         assert(SvTYPE(sv) >= SVt_PVMG);
2343         /* This falls through to the report_uninit near the end of the
2344            function. */
2345     } else if (SvTHINKFIRST(sv)) {
2346         if (SvROK(sv)) {
2347         return_rok:
2348             if (SvAMAGIC(sv)) {
2349                 SV *const tmpstr = AMG_CALLun(sv,numer);
2350                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2351                     return SvNV(tmpstr);
2352                 }
2353             }
2354             return PTR2NV(SvRV(sv));
2355         }
2356         if (SvIsCOW(sv)) {
2357             sv_force_normal_flags(sv, 0);
2358         }
2359         if (SvREADONLY(sv) && !SvOK(sv)) {
2360             if (ckWARN(WARN_UNINITIALIZED))
2361                 report_uninit(sv);
2362             return 0.0;
2363         }
2364     }
2365     if (SvTYPE(sv) < SVt_NV) {
2366         /* The logic to use SVt_PVNV if necessary is in sv_upgrade.  */
2367         sv_upgrade(sv, SVt_NV);
2368 #ifdef USE_LONG_DOUBLE
2369         DEBUG_c({
2370             STORE_NUMERIC_LOCAL_SET_STANDARD();
2371             PerlIO_printf(Perl_debug_log,
2372                           "0x%"UVxf" num(%" PERL_PRIgldbl ")\n",
2373                           PTR2UV(sv), SvNVX(sv));
2374             RESTORE_NUMERIC_LOCAL();
2375         });
2376 #else
2377         DEBUG_c({
2378             STORE_NUMERIC_LOCAL_SET_STANDARD();
2379             PerlIO_printf(Perl_debug_log, "0x%"UVxf" num(%"NVgf")\n",
2380                           PTR2UV(sv), SvNVX(sv));
2381             RESTORE_NUMERIC_LOCAL();
2382         });
2383 #endif
2384     }
2385     else if (SvTYPE(sv) < SVt_PVNV)
2386         sv_upgrade(sv, SVt_PVNV);
2387     if (SvNOKp(sv)) {
2388         return SvNVX(sv);
2389     }
2390     if (SvIOKp(sv)) {
2391         SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
2392 #ifdef NV_PRESERVES_UV
2393         SvNOK_on(sv);
2394 #else
2395         /* Only set the public NV OK flag if this NV preserves the IV  */
2396         /* Check it's not 0xFFFFFFFFFFFFFFFF */
2397         if (SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
2398                        : (SvIVX(sv) == I_V(SvNVX(sv))))
2399             SvNOK_on(sv);
2400         else
2401             SvNOKp_on(sv);
2402 #endif
2403     }
2404     else if (SvPOKp(sv) && SvLEN(sv)) {
2405         UV value;
2406         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2407         if (!SvIOKp(sv) && !numtype && ckWARN(WARN_NUMERIC))
2408             not_a_number(sv);
2409 #ifdef NV_PRESERVES_UV
2410         if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2411             == IS_NUMBER_IN_UV) {
2412             /* It's definitely an integer */
2413             SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
2414         } else
2415             SvNV_set(sv, Atof(SvPVX_const(sv)));
2416         SvNOK_on(sv);
2417 #else
2418         SvNV_set(sv, Atof(SvPVX_const(sv)));
2419         /* Only set the public NV OK flag if this NV preserves the value in
2420            the PV at least as well as an IV/UV would.
2421            Not sure how to do this 100% reliably. */
2422         /* if that shift count is out of range then Configure's test is
2423            wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2424            UV_BITS */
2425         if (((UV)1 << NV_PRESERVES_UV_BITS) >
2426             U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2427             SvNOK_on(sv); /* Definitely small enough to preserve all bits */
2428         } else if (!(numtype & IS_NUMBER_IN_UV)) {
2429             /* Can't use strtol etc to convert this string, so don't try.
2430                sv_2iv and sv_2uv will use the NV to convert, not the PV.  */
2431             SvNOK_on(sv);
2432         } else {
2433             /* value has been set.  It may not be precise.  */
2434             if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2435                 /* 2s complement assumption for (UV)IV_MIN  */
2436                 SvNOK_on(sv); /* Integer is too negative.  */
2437             } else {
2438                 SvNOKp_on(sv);
2439                 SvIOKp_on(sv);
2440
2441                 if (numtype & IS_NUMBER_NEG) {
2442                     SvIV_set(sv, -(IV)value);
2443                 } else if (value <= (UV)IV_MAX) {
2444                     SvIV_set(sv, (IV)value);
2445                 } else {
2446                     SvUV_set(sv, value);
2447                     SvIsUV_on(sv);
2448                 }
2449
2450                 if (numtype & IS_NUMBER_NOT_INT) {
2451                     /* I believe that even if the original PV had decimals,
2452                        they are lost beyond the limit of the FP precision.
2453                        However, neither is canonical, so both only get p
2454                        flags.  NWC, 2000/11/25 */
2455                     /* Both already have p flags, so do nothing */
2456                 } else {
2457                     const NV nv = SvNVX(sv);
2458                     if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2459                         if (SvIVX(sv) == I_V(nv)) {
2460                             SvNOK_on(sv);
2461                         } else {
2462                             /* It had no "." so it must be integer.  */
2463                         }
2464                         SvIOK_on(sv);
2465                     } else {
2466                         /* between IV_MAX and NV(UV_MAX).
2467                            Could be slightly > UV_MAX */
2468
2469                         if (numtype & IS_NUMBER_NOT_INT) {
2470                             /* UV and NV both imprecise.  */
2471                         } else {
2472                             const UV nv_as_uv = U_V(nv);
2473
2474                             if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2475                                 SvNOK_on(sv);
2476                             }
2477                             SvIOK_on(sv);
2478                         }
2479                     }
2480                 }
2481             }
2482         }
2483 #endif /* NV_PRESERVES_UV */
2484     }
2485     else  {
2486         if (isGV_with_GP(sv)) {
2487             glob_2number((GV *)sv);
2488             return 0.0;
2489         }
2490
2491         if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
2492             report_uninit(sv);
2493         assert (SvTYPE(sv) >= SVt_NV);
2494         /* Typically the caller expects that sv_any is not NULL now.  */
2495         /* XXX Ilya implies that this is a bug in callers that assume this
2496            and ideally should be fixed.  */
2497         return 0.0;
2498     }
2499 #if defined(USE_LONG_DOUBLE)
2500     DEBUG_c({
2501         STORE_NUMERIC_LOCAL_SET_STANDARD();
2502         PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" PERL_PRIgldbl ")\n",
2503                       PTR2UV(sv), SvNVX(sv));
2504         RESTORE_NUMERIC_LOCAL();
2505     });
2506 #else
2507     DEBUG_c({
2508         STORE_NUMERIC_LOCAL_SET_STANDARD();
2509         PerlIO_printf(Perl_debug_log, "0x%"UVxf" 1nv(%"NVgf")\n",
2510                       PTR2UV(sv), SvNVX(sv));
2511         RESTORE_NUMERIC_LOCAL();
2512     });
2513 #endif
2514     return SvNVX(sv);
2515 }
2516
2517 /* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2518  * UV as a string towards the end of buf, and return pointers to start and
2519  * end of it.
2520  *
2521  * We assume that buf is at least TYPE_CHARS(UV) long.
2522  */
2523
2524 static char *
2525 S_uiv_2buf(char *buf, IV iv, UV uv, int is_uv, char **peob)
2526 {
2527     char *ptr = buf + TYPE_CHARS(UV);
2528     char * const ebuf = ptr;
2529     int sign;
2530
2531     if (is_uv)
2532         sign = 0;
2533     else if (iv >= 0) {
2534         uv = iv;
2535         sign = 0;
2536     } else {
2537         uv = -iv;
2538         sign = 1;
2539     }
2540     do {
2541         *--ptr = '0' + (char)(uv % 10);
2542     } while (uv /= 10);
2543     if (sign)
2544         *--ptr = '-';
2545     *peob = ebuf;
2546     return ptr;
2547 }
2548
2549 /*
2550 =for apidoc sv_2pv_flags
2551
2552 Returns a pointer to the string value of an SV, and sets *lp to its length.
2553 If flags includes SV_GMAGIC, does an mg_get() first. Coerces sv to a string
2554 if necessary.
2555 Normally invoked via the C<SvPV_flags> macro. C<sv_2pv()> and C<sv_2pv_nomg>
2556 usually end up here too.
2557
2558 =cut
2559 */
2560
2561 char *
2562 Perl_sv_2pv_flags(pTHX_ register SV *sv, STRLEN *lp, I32 flags)
2563 {
2564     dVAR;
2565     register char *s;
2566
2567     if (!sv) {
2568         if (lp)
2569             *lp = 0;
2570         return (char *)"";
2571     }
2572     if (SvGMAGICAL(sv)) {
2573         if (flags & SV_GMAGIC)
2574             mg_get(sv);
2575         if (SvPOKp(sv)) {
2576             if (lp)
2577                 *lp = SvCUR(sv);
2578             if (flags & SV_MUTABLE_RETURN)
2579                 return SvPVX_mutable(sv);
2580             if (flags & SV_CONST_RETURN)
2581                 return (char *)SvPVX_const(sv);
2582             return SvPVX(sv);
2583         }
2584         if (SvIOKp(sv) || SvNOKp(sv)) {
2585             char tbuf[64];  /* Must fit sprintf/Gconvert of longest IV/NV */
2586             STRLEN len;
2587
2588             if (SvIOKp(sv)) {
2589                 len = SvIsUV(sv)
2590                     ? my_snprintf(tbuf, sizeof(tbuf), "%"UVuf, (UV)SvUVX(sv))
2591                     : my_snprintf(tbuf, sizeof(tbuf), "%"IVdf, (IV)SvIVX(sv));
2592             } else {
2593                 Gconvert(SvNVX(sv), NV_DIG, 0, tbuf);
2594                 len = strlen(tbuf);
2595             }
2596             assert(!SvROK(sv));
2597             {
2598                 dVAR;
2599
2600 #ifdef FIXNEGATIVEZERO
2601                 if (len == 2 && tbuf[0] == '-' && tbuf[1] == '0') {
2602                     tbuf[0] = '0';
2603                     tbuf[1] = 0;
2604                     len = 1;
2605                 }
2606 #endif
2607                 SvUPGRADE(sv, SVt_PV);
2608                 if (lp)
2609                     *lp = len;
2610                 s = SvGROW_mutable(sv, len + 1);
2611                 SvCUR_set(sv, len);
2612                 SvPOKp_on(sv);
2613                 return (char*)memcpy(s, tbuf, len + 1);
2614             }
2615         }
2616         if (SvROK(sv)) {
2617             goto return_rok;
2618         }
2619         assert(SvTYPE(sv) >= SVt_PVMG);
2620         /* This falls through to the report_uninit near the end of the
2621            function. */
2622     } else if (SvTHINKFIRST(sv)) {
2623         if (SvROK(sv)) {
2624         return_rok:
2625             if (SvAMAGIC(sv)) {
2626                 SV *const tmpstr = AMG_CALLun(sv,string);
2627                 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2628                     /* Unwrap this:  */
2629                     /* char *pv = lp ? SvPV(tmpstr, *lp) : SvPV_nolen(tmpstr);
2630                      */
2631
2632                     char *pv;
2633                     if ((SvFLAGS(tmpstr) & (SVf_POK)) == SVf_POK) {
2634                         if (flags & SV_CONST_RETURN) {
2635                             pv = (char *) SvPVX_const(tmpstr);
2636                         } else {
2637                             pv = (flags & SV_MUTABLE_RETURN)
2638                                 ? SvPVX_mutable(tmpstr) : SvPVX(tmpstr);
2639                         }
2640                         if (lp)
2641                             *lp = SvCUR(tmpstr);
2642                     } else {
2643                         pv = sv_2pv_flags(tmpstr, lp, flags);
2644                     }
2645                     if (SvUTF8(tmpstr))
2646                         SvUTF8_on(sv);
2647                     else
2648                         SvUTF8_off(sv);
2649                     return pv;
2650                 }
2651             }
2652             {
2653                 STRLEN len;
2654                 char *retval;
2655                 char *buffer;
2656                 MAGIC *mg;
2657                 const SV *const referent = (SV*)SvRV(sv);
2658
2659                 if (!referent) {
2660                     len = 7;
2661                     retval = buffer = savepvn("NULLREF", len);
2662                 } else if (SvTYPE(referent) == SVt_PVMG
2663                            && ((SvFLAGS(referent) &
2664                                 (SVs_OBJECT|SVf_OK|SVs_GMG|SVs_SMG|SVs_RMG))
2665                                == (SVs_OBJECT|SVs_SMG))
2666                            && (mg = mg_find(referent, PERL_MAGIC_qr)))
2667                 {
2668                     char *str = NULL;
2669                     I32 haseval = 0;
2670                     U32 flags = 0;
2671                     (str) = CALLREG_AS_STR(mg,lp,&flags,&haseval);
2672                     if (flags & 1)
2673                         SvUTF8_on(sv);
2674                     else
2675                         SvUTF8_off(sv);
2676                     PL_reginterp_cnt += haseval;
2677                     return str;
2678                 } else {
2679                     const char *const typestr = sv_reftype(referent, 0);
2680                     const STRLEN typelen = strlen(typestr);
2681                     UV addr = PTR2UV(referent);
2682                     const char *stashname = NULL;
2683                     STRLEN stashnamelen = 0; /* hush, gcc */
2684                     const char *buffer_end;
2685
2686                     if (SvOBJECT(referent)) {
2687                         const HEK *const name = HvNAME_HEK(SvSTASH(referent));
2688
2689                         if (name) {
2690                             stashname = HEK_KEY(name);
2691                             stashnamelen = HEK_LEN(name);
2692
2693                             if (HEK_UTF8(name)) {
2694                                 SvUTF8_on(sv);
2695                             } else {
2696                                 SvUTF8_off(sv);
2697                             }
2698                         } else {
2699                             stashname = "__ANON__";
2700                             stashnamelen = 8;
2701                         }
2702                         len = stashnamelen + 1 /* = */ + typelen + 3 /* (0x */
2703                             + 2 * sizeof(UV) + 2 /* )\0 */;
2704                     } else {
2705                         len = typelen + 3 /* (0x */
2706                             + 2 * sizeof(UV) + 2 /* )\0 */;
2707                     }
2708
2709                     Newx(buffer, len, char);
2710                     buffer_end = retval = buffer + len;
2711
2712                     /* Working backwards  */
2713                     *--retval = '\0';
2714                     *--retval = ')';
2715                     do {
2716                         *--retval = PL_hexdigit[addr & 15];
2717                     } while (addr >>= 4);
2718                     *--retval = 'x';
2719                     *--retval = '0';
2720                     *--retval = '(';
2721
2722                     retval -= typelen;
2723                     memcpy(retval, typestr, typelen);
2724
2725                     if (stashname) {
2726                         *--retval = '=';
2727                         retval -= stashnamelen;
2728                         memcpy(retval, stashname, stashnamelen);
2729                     }
2730                     /* retval may not neccesarily have reached the start of the
2731                        buffer here.  */
2732                     assert (retval >= buffer);
2733
2734                     len = buffer_end - retval - 1; /* -1 for that \0  */
2735                 }
2736                 if (lp)
2737                     *lp = len;
2738                 SAVEFREEPV(buffer);
2739                 return retval;
2740             }
2741         }
2742         if (SvREADONLY(sv) && !SvOK(sv)) {
2743             if (ckWARN(WARN_UNINITIALIZED))
2744                 report_uninit(sv);
2745             if (lp)
2746                 *lp = 0;
2747             return (char *)"";
2748         }
2749     }
2750     if (SvIOK(sv) || ((SvIOKp(sv) && !SvNOKp(sv)))) {
2751         /* I'm assuming that if both IV and NV are equally valid then
2752            converting the IV is going to be more efficient */
2753         const U32 isUIOK = SvIsUV(sv);
2754         char buf[TYPE_CHARS(UV)];
2755         char *ebuf, *ptr;
2756
2757         if (SvTYPE(sv) < SVt_PVIV)
2758             sv_upgrade(sv, SVt_PVIV);
2759         ptr = uiv_2buf(buf, SvIVX(sv), SvUVX(sv), isUIOK, &ebuf);
2760         /* inlined from sv_setpvn */
2761         SvGROW_mutable(sv, (STRLEN)(ebuf - ptr + 1));
2762         Move(ptr,SvPVX_mutable(sv),ebuf - ptr,char);
2763         SvCUR_set(sv, ebuf - ptr);
2764         s = SvEND(sv);
2765         *s = '\0';
2766     }
2767     else if (SvNOKp(sv)) {
2768         const int olderrno = errno;
2769         if (SvTYPE(sv) < SVt_PVNV)
2770             sv_upgrade(sv, SVt_PVNV);
2771         /* The +20 is pure guesswork.  Configure test needed. --jhi */
2772         s = SvGROW_mutable(sv, NV_DIG + 20);
2773         /* some Xenix systems wipe out errno here */
2774 #ifdef apollo
2775         if (SvNVX(sv) == 0.0)
2776             my_strlcpy(s, "0", SvLEN(sv));
2777         else
2778 #endif /*apollo*/
2779         {
2780             Gconvert(SvNVX(sv), NV_DIG, 0, s);
2781         }
2782         errno = olderrno;
2783 #ifdef FIXNEGATIVEZERO
2784         if (*s == '-' && s[1] == '0' && !s[2])
2785             my_strlcpy(s, "0", SvLEN(s));
2786 #endif
2787         while (*s) s++;
2788 #ifdef hcx
2789         if (s[-1] == '.')
2790             *--s = '\0';
2791 #endif
2792     }
2793     else {
2794         if (isGV_with_GP(sv))
2795             return glob_2pv((GV *)sv, lp);
2796
2797         if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
2798             report_uninit(sv);
2799         if (lp)
2800             *lp = 0;
2801         if (SvTYPE(sv) < SVt_PV)
2802             /* Typically the caller expects that sv_any is not NULL now.  */
2803             sv_upgrade(sv, SVt_PV);
2804         return (char *)"";
2805     }
2806     {
2807         const STRLEN len = s - SvPVX_const(sv);
2808         if (lp) 
2809             *lp = len;
2810         SvCUR_set(sv, len);
2811     }
2812     SvPOK_on(sv);
2813     DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
2814                           PTR2UV(sv),SvPVX_const(sv)));
2815     if (flags & SV_CONST_RETURN)
2816         return (char *)SvPVX_const(sv);
2817     if (flags & SV_MUTABLE_RETURN)
2818         return SvPVX_mutable(sv);
2819     return SvPVX(sv);
2820 }
2821
2822 /*
2823 =for apidoc sv_copypv
2824
2825 Copies a stringified representation of the source SV into the
2826 destination SV.  Automatically performs any necessary mg_get and
2827 coercion of numeric values into strings.  Guaranteed to preserve
2828 UTF-8 flag even from overloaded objects.  Similar in nature to
2829 sv_2pv[_flags] but operates directly on an SV instead of just the
2830 string.  Mostly uses sv_2pv_flags to do its work, except when that
2831 would lose the UTF-8'ness of the PV.
2832
2833 =cut
2834 */
2835
2836 void
2837 Perl_sv_copypv(pTHX_ SV *dsv, register SV *ssv)
2838 {
2839     STRLEN len;
2840     const char * const s = SvPV_const(ssv,len);
2841     sv_setpvn(dsv,s,len);
2842     if (SvUTF8(ssv))
2843         SvUTF8_on(dsv);
2844     else
2845         SvUTF8_off(dsv);
2846 }
2847
2848 /*
2849 =for apidoc sv_2pvbyte
2850
2851 Return a pointer to the byte-encoded representation of the SV, and set *lp
2852 to its length.  May cause the SV to be downgraded from UTF-8 as a
2853 side-effect.
2854
2855 Usually accessed via the C<SvPVbyte> macro.
2856
2857 =cut
2858 */
2859
2860 char *
2861 Perl_sv_2pvbyte(pTHX_ register SV *sv, STRLEN *lp)
2862 {
2863     sv_utf8_downgrade(sv,0);
2864     return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
2865 }
2866
2867 /*
2868 =for apidoc sv_2pvutf8
2869
2870 Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
2871 to its length.  May cause the SV to be upgraded to UTF-8 as a side-effect.
2872
2873 Usually accessed via the C<SvPVutf8> macro.
2874
2875 =cut
2876 */
2877
2878 char *
2879 Perl_sv_2pvutf8(pTHX_ register SV *sv, STRLEN *lp)
2880 {
2881     sv_utf8_upgrade(sv);
2882     return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
2883 }
2884
2885
2886 /*
2887 =for apidoc sv_2bool
2888
2889 This function is only called on magical items, and is only used by
2890 sv_true() or its macro equivalent.
2891
2892 =cut
2893 */
2894
2895 bool
2896 Perl_sv_2bool(pTHX_ register SV *sv)
2897 {
2898     dVAR;
2899     SvGETMAGIC(sv);
2900
2901     if (!SvOK(sv))
2902         return 0;
2903     if (SvROK(sv)) {
2904         if (SvAMAGIC(sv)) {
2905             SV * const tmpsv = AMG_CALLun(sv,bool_);
2906             if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
2907                 return (bool)SvTRUE(tmpsv);
2908         }
2909         return SvRV(sv) != 0;
2910     }
2911     if (SvPOKp(sv)) {
2912         register XPV* const Xpvtmp = (XPV*)SvANY(sv);
2913         if (Xpvtmp &&
2914                 (*sv->sv_u.svu_pv > '0' ||
2915                 Xpvtmp->xpv_cur > 1 ||
2916                 (Xpvtmp->xpv_cur && *sv->sv_u.svu_pv != '0')))
2917             return 1;
2918         else
2919             return 0;
2920     }
2921     else {
2922         if (SvIOKp(sv))
2923             return SvIVX(sv) != 0;
2924         else {
2925             if (SvNOKp(sv))
2926                 return SvNVX(sv) != 0.0;
2927             else {
2928                 if (isGV_with_GP(sv))
2929                     return TRUE;
2930                 else
2931                     return FALSE;
2932             }
2933         }
2934     }
2935 }
2936
2937 /*
2938 =for apidoc sv_utf8_upgrade
2939
2940 Converts the PV of an SV to its UTF-8-encoded form.
2941 Forces the SV to string form if it is not already.
2942 Always sets the SvUTF8 flag to avoid future validity checks even
2943 if all the bytes have hibit clear.
2944
2945 This is not as a general purpose byte encoding to Unicode interface:
2946 use the Encode extension for that.
2947
2948 =for apidoc sv_utf8_upgrade_flags
2949
2950 Converts the PV of an SV to its UTF-8-encoded form.
2951 Forces the SV to string form if it is not already.
2952 Always sets the SvUTF8 flag to avoid future validity checks even
2953 if all the bytes have hibit clear. If C<flags> has C<SV_GMAGIC> bit set,
2954 will C<mg_get> on C<sv> if appropriate, else not. C<sv_utf8_upgrade> and
2955 C<sv_utf8_upgrade_nomg> are implemented in terms of this function.
2956
2957 This is not as a general purpose byte encoding to Unicode interface:
2958 use the Encode extension for that.
2959
2960 =cut
2961 */
2962
2963 STRLEN
2964 Perl_sv_utf8_upgrade_flags(pTHX_ register SV *sv, I32 flags)
2965 {
2966     dVAR;
2967     if (sv == &PL_sv_undef)
2968         return 0;
2969     if (!SvPOK(sv)) {
2970         STRLEN len = 0;
2971         if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
2972             (void) sv_2pv_flags(sv,&len, flags);
2973             if (SvUTF8(sv))
2974                 return len;
2975         } else {
2976             (void) SvPV_force(sv,len);
2977         }
2978     }
2979
2980     if (SvUTF8(sv)) {
2981         return SvCUR(sv);
2982     }
2983
2984     if (SvIsCOW(sv)) {
2985         sv_force_normal_flags(sv, 0);
2986     }
2987
2988     if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING))
2989         sv_recode_to_utf8(sv, PL_encoding);
2990     else { /* Assume Latin-1/EBCDIC */
2991         /* This function could be much more efficient if we
2992          * had a FLAG in SVs to signal if there are any hibit
2993          * chars in the PV.  Given that there isn't such a flag
2994          * make the loop as fast as possible. */
2995         const U8 * const s = (U8 *) SvPVX_const(sv);
2996         const U8 * const e = (U8 *) SvEND(sv);
2997         const U8 *t = s;
2998         
2999         while (t < e) {
3000             const U8 ch = *t++;
3001             /* Check for hi bit */
3002             if (!NATIVE_IS_INVARIANT(ch)) {
3003                 STRLEN len = SvCUR(sv) + 1; /* Plus the \0 */
3004                 U8 * const recoded = bytes_to_utf8((U8*)s, &len);
3005
3006                 SvPV_free(sv); /* No longer using what was there before. */
3007                 SvPV_set(sv, (char*)recoded);
3008                 SvCUR_set(sv, len - 1);
3009                 SvLEN_set(sv, len); /* No longer know the real size. */
3010                 break;
3011             }
3012         }
3013         /* Mark as UTF-8 even if no hibit - saves scanning loop */
3014         SvUTF8_on(sv);
3015     }
3016     return SvCUR(sv);
3017 }
3018
3019 /*
3020 =for apidoc sv_utf8_downgrade
3021
3022 Attempts to convert the PV of an SV from characters to bytes.
3023 If the PV contains a character beyond byte, this conversion will fail;
3024 in this case, either returns false or, if C<fail_ok> is not
3025 true, croaks.
3026
3027 This is not as a general purpose Unicode to byte encoding interface:
3028 use the Encode extension for that.
3029
3030 =cut
3031 */
3032
3033 bool
3034 Perl_sv_utf8_downgrade(pTHX_ register SV* sv, bool fail_ok)
3035 {
3036     dVAR;
3037     if (SvPOKp(sv) && SvUTF8(sv)) {
3038         if (SvCUR(sv)) {
3039             U8 *s;
3040             STRLEN len;
3041
3042             if (SvIsCOW(sv)) {
3043                 sv_force_normal_flags(sv, 0);
3044             }
3045             s = (U8 *) SvPV(sv, len);
3046             if (!utf8_to_bytes(s, &len)) {
3047                 if (fail_ok)
3048                     return FALSE;
3049                 else {
3050                     if (PL_op)
3051                         Perl_croak(aTHX_ "Wide character in %s",
3052                                    OP_DESC(PL_op));
3053                     else
3054                         Perl_croak(aTHX_ "Wide character");
3055                 }
3056             }
3057             SvCUR_set(sv, len);
3058         }
3059     }
3060     SvUTF8_off(sv);
3061     return TRUE;
3062 }
3063
3064 /*
3065 =for apidoc sv_utf8_encode
3066
3067 Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3068 flag off so that it looks like octets again.
3069
3070 =cut
3071 */
3072
3073 void
3074 Perl_sv_utf8_encode(pTHX_ register SV *sv)
3075 {
3076     if (SvIsCOW(sv)) {
3077         sv_force_normal_flags(sv, 0);
3078     }
3079     if (SvREADONLY(sv)) {
3080         Perl_croak(aTHX_ PL_no_modify);
3081     }
3082     (void) sv_utf8_upgrade(sv);
3083     SvUTF8_off(sv);
3084 }
3085
3086 /*
3087 =for apidoc sv_utf8_decode
3088
3089 If the PV of the SV is an octet sequence in UTF-8
3090 and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3091 so that it looks like a character. If the PV contains only single-byte
3092 characters, the C<SvUTF8> flag stays being off.
3093 Scans PV for validity and returns false if the PV is invalid UTF-8.
3094
3095 =cut
3096 */
3097
3098 bool
3099 Perl_sv_utf8_decode(pTHX_ register SV *sv)
3100 {
3101     if (SvPOKp(sv)) {
3102         const U8 *c;
3103         const U8 *e;
3104
3105         /* The octets may have got themselves encoded - get them back as
3106          * bytes
3107          */
3108         if (!sv_utf8_downgrade(sv, TRUE))
3109             return FALSE;
3110
3111         /* it is actually just a matter of turning the utf8 flag on, but
3112          * we want to make sure everything inside is valid utf8 first.
3113          */
3114         c = (const U8 *) SvPVX_const(sv);
3115         if (!is_utf8_string(c, SvCUR(sv)+1))
3116             return FALSE;
3117         e = (const U8 *) SvEND(sv);
3118         while (c < e) {
3119             const U8 ch = *c++;
3120             if (!UTF8_IS_INVARIANT(ch)) {
3121                 SvUTF8_on(sv);
3122                 break;
3123             }
3124         }
3125     }
3126     return TRUE;
3127 }
3128
3129 /*
3130 =for apidoc sv_setsv
3131
3132 Copies the contents of the source SV C<ssv> into the destination SV
3133 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3134 function if the source SV needs to be reused. Does not handle 'set' magic.
3135 Loosely speaking, it performs a copy-by-value, obliterating any previous
3136 content of the destination.
3137
3138 You probably want to use one of the assortment of wrappers, such as
3139 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3140 C<SvSetMagicSV_nosteal>.
3141
3142 =for apidoc sv_setsv_flags
3143
3144 Copies the contents of the source SV C<ssv> into the destination SV
3145 C<dsv>.  The source SV may be destroyed if it is mortal, so don't use this
3146 function if the source SV needs to be reused. Does not handle 'set' magic.
3147 Loosely speaking, it performs a copy-by-value, obliterating any previous
3148 content of the destination.
3149 If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
3150 C<ssv> if appropriate, else not. If the C<flags> parameter has the
3151 C<NOSTEAL> bit set then the buffers of temps will not be stolen. <sv_setsv>
3152 and C<sv_setsv_nomg> are implemented in terms of this function.
3153
3154 You probably want to use one of the assortment of wrappers, such as
3155 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3156 C<SvSetMagicSV_nosteal>.
3157
3158 This is the primary function for copying scalars, and most other
3159 copy-ish functions and macros use this underneath.
3160
3161 =cut
3162 */
3163
3164 static void
3165 S_glob_assign_glob(pTHX_ SV *dstr, SV *sstr, const int dtype)
3166 {
3167     if (dtype != SVt_PVGV) {
3168         const char * const name = GvNAME(sstr);
3169         const STRLEN len = GvNAMELEN(sstr);
3170         /* don't upgrade SVt_PVLV: it can hold a glob */
3171         if (dtype != SVt_PVLV) {
3172             if (dtype >= SVt_PV) {
3173                 SvPV_free(dstr);
3174                 SvPV_set(dstr, 0);
3175                 SvLEN_set(dstr, 0);
3176                 SvCUR_set(dstr, 0);
3177             }
3178             sv_upgrade(dstr, SVt_PVGV);
3179             (void)SvOK_off(dstr);
3180             /* FIXME - why are we doing this, then turning it off and on again
3181                below?  */
3182             isGV_with_GP_on(dstr);
3183         }
3184         GvSTASH(dstr) = GvSTASH(sstr);
3185         if (GvSTASH(dstr))
3186             Perl_sv_add_backref(aTHX_ (SV*)GvSTASH(dstr), dstr);
3187         gv_name_set((GV *)dstr, name, len, GV_ADD);
3188         SvFAKE_on(dstr);        /* can coerce to non-glob */
3189     }
3190
3191 #ifdef GV_UNIQUE_CHECK
3192     if (GvUNIQUE((GV*)dstr)) {
3193         Perl_croak(aTHX_ PL_no_modify);
3194     }
3195 #endif
3196
3197     gp_free((GV*)dstr);
3198     isGV_with_GP_off(dstr);
3199     (void)SvOK_off(dstr);
3200     isGV_with_GP_on(dstr);
3201     GvINTRO_off(dstr);          /* one-shot flag */
3202     GvGP(dstr) = gp_ref(GvGP(sstr));
3203     if (SvTAINTED(sstr))
3204         SvTAINT(dstr);
3205     if (GvIMPORTED(dstr) != GVf_IMPORTED
3206         && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3207         {
3208             GvIMPORTED_on(dstr);
3209         }
3210     GvMULTI_on(dstr);
3211     return;
3212 }
3213
3214 static void
3215 S_glob_assign_ref(pTHX_ SV *dstr, SV *sstr) {
3216     SV * const sref = SvREFCNT_inc(SvRV(sstr));
3217     SV *dref = NULL;
3218     const int intro = GvINTRO(dstr);
3219     SV **location;
3220     U8 import_flag = 0;
3221     const U32 stype = SvTYPE(sref);
3222
3223
3224 #ifdef GV_UNIQUE_CHECK
3225     if (GvUNIQUE((GV*)dstr)) {
3226         Perl_croak(aTHX_ PL_no_modify);
3227     }
3228 #endif
3229
3230     if (intro) {
3231         GvINTRO_off(dstr);      /* one-shot flag */
3232         GvLINE(dstr) = CopLINE(PL_curcop);
3233         GvEGV(dstr) = (GV*)dstr;
3234     }
3235     GvMULTI_on(dstr);
3236     switch (stype) {
3237     case SVt_PVCV:
3238         location = (SV **) &GvCV(dstr);
3239         import_flag = GVf_IMPORTED_CV;
3240         goto common;
3241     case SVt_PVHV:
3242         location = (SV **) &GvHV(dstr);
3243         import_flag = GVf_IMPORTED_HV;
3244         goto common;
3245     case SVt_PVAV:
3246         location = (SV **) &GvAV(dstr);
3247         import_flag = GVf_IMPORTED_AV;
3248         goto common;
3249     case SVt_PVIO:
3250         location = (SV **) &GvIOp(dstr);
3251         goto common;
3252     case SVt_PVFM:
3253         location = (SV **) &GvFORM(dstr);
3254     default:
3255         location = &GvSV(dstr);
3256         import_flag = GVf_IMPORTED_SV;
3257     common:
3258         if (intro) {
3259             if (stype == SVt_PVCV) {
3260                 if (GvCVGEN(dstr) && GvCV(dstr) != (CV*)sref) {
3261                     SvREFCNT_dec(GvCV(dstr));
3262                     GvCV(dstr) = NULL;
3263                     GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3264                     PL_sub_generation++;
3265                 }
3266             }
3267             SAVEGENERICSV(*location);
3268         }
3269         else
3270             dref = *location;
3271         if (stype == SVt_PVCV && *location != sref) {
3272             CV* const cv = (CV*)*location;
3273             if (cv) {
3274                 if (!GvCVGEN((GV*)dstr) &&
3275                     (CvROOT(cv) || CvXSUB(cv)))
3276                     {
3277                         /* Redefining a sub - warning is mandatory if
3278                            it was a const and its value changed. */
3279                         if (CvCONST(cv) && CvCONST((CV*)sref)
3280                             && cv_const_sv(cv) == cv_const_sv((CV*)sref)) {
3281                             NOOP;
3282                             /* They are 2 constant subroutines generated from
3283                                the same constant. This probably means that
3284                                they are really the "same" proxy subroutine
3285                                instantiated in 2 places. Most likely this is
3286                                when a constant is exported twice.  Don't warn.
3287                             */
3288                         }
3289                         else if (ckWARN(WARN_REDEFINE)
3290                                  || (CvCONST(cv)
3291                                      && (!CvCONST((CV*)sref)
3292                                          || sv_cmp(cv_const_sv(cv),
3293                                                    cv_const_sv((CV*)sref))))) {
3294                             Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
3295                                         (const char *)
3296                                         (CvCONST(cv)
3297                                          ? "Constant subroutine %s::%s redefined"
3298                                          : "Subroutine %s::%s redefined"),
3299                                         HvNAME_get(GvSTASH((GV*)dstr)),
3300                                         GvENAME((GV*)dstr));
3301                         }
3302                     }
3303                 if (!intro)
3304                     cv_ckproto_len(cv, (GV*)dstr,
3305                                    SvPOK(sref) ? SvPVX_const(sref) : NULL,
3306                                    SvPOK(sref) ? SvCUR(sref) : 0);
3307             }
3308             GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3309             GvASSUMECV_on(dstr);
3310             PL_sub_generation++;
3311         }
3312         *location = sref;
3313         if (import_flag && !(GvFLAGS(dstr) & import_flag)
3314             && CopSTASH_ne(PL_curcop, GvSTASH(dstr))) {
3315             GvFLAGS(dstr) |= import_flag;
3316         }
3317         break;
3318     }
3319     SvREFCNT_dec(dref);
3320     if (SvTAINTED(sstr))
3321         SvTAINT(dstr);
3322     return;
3323 }
3324
3325 void
3326 Perl_sv_setsv_flags(pTHX_ SV *dstr, register SV *sstr, I32 flags)
3327 {
3328     dVAR;
3329     register U32 sflags;
3330     register int dtype;
3331     register svtype stype;
3332
3333     if (sstr == dstr)
3334         return;
3335
3336     if (SvIS_FREED(dstr)) {
3337         Perl_croak(aTHX_ "panic: attempt to copy value %" SVf
3338                    " to a freed scalar %p", sstr, dstr);
3339     }
3340     SV_CHECK_THINKFIRST_COW_DROP(dstr);
3341     if (!sstr)
3342         sstr = &PL_sv_undef;
3343     if (SvIS_FREED(sstr)) {
3344         Perl_croak(aTHX_ "panic: attempt to copy freed scalar %p to %p", sstr,
3345                    dstr);
3346     }
3347     stype = SvTYPE(sstr);
3348     dtype = SvTYPE(dstr);
3349
3350     SvAMAGIC_off(dstr);
3351     if ( SvVOK(dstr) )
3352     {
3353         /* need to nuke the magic */
3354         mg_free(dstr);
3355         SvRMAGICAL_off(dstr);
3356     }
3357
3358     /* There's a lot of redundancy below but we're going for speed here */
3359
3360     switch (stype) {
3361     case SVt_NULL:
3362       undef_sstr:
3363         if (dtype != SVt_PVGV) {
3364             (void)SvOK_off(dstr);
3365             return;
3366         }
3367         break;
3368     case SVt_IV:
3369         if (SvIOK(sstr)) {
3370             switch (dtype) {
3371             case SVt_NULL:
3372                 sv_upgrade(dstr, SVt_IV);
3373                 break;
3374             case SVt_NV:
3375             case SVt_RV:
3376             case SVt_PV:
3377                 sv_upgrade(dstr, SVt_PVIV);
3378                 break;
3379             case SVt_PVGV:
3380                 goto end_of_first_switch;
3381             }
3382             (void)SvIOK_only(dstr);
3383             SvIV_set(dstr,  SvIVX(sstr));
3384             if (SvIsUV(sstr))
3385                 SvIsUV_on(dstr);
3386             /* SvTAINTED can only be true if the SV has taint magic, which in
3387                turn means that the SV type is PVMG (or greater). This is the
3388                case statement for SVt_IV, so this cannot be true (whatever gcov
3389                may say).  */
3390             assert(!SvTAINTED(sstr));
3391             return;
3392         }
3393         goto undef_sstr;
3394
3395     case SVt_NV:
3396         if (SvNOK(sstr)) {
3397             switch (dtype) {
3398             case SVt_NULL:
3399             case SVt_IV:
3400                 sv_upgrade(dstr, SVt_NV);
3401                 break;
3402             case SVt_RV:
3403             case SVt_PV:
3404             case SVt_PVIV:
3405                 sv_upgrade(dstr, SVt_PVNV);
3406                 break;
3407             case SVt_PVGV:
3408                 goto end_of_first_switch;
3409             }
3410             SvNV_set(dstr, SvNVX(sstr));
3411             (void)SvNOK_only(dstr);
3412             /* SvTAINTED can only be true if the SV has taint magic, which in
3413                turn means that the SV type is PVMG (or greater). This is the
3414                case statement for SVt_NV, so this cannot be true (whatever gcov
3415                may say).  */
3416             assert(!SvTAINTED(sstr));
3417             return;
3418         }
3419         goto undef_sstr;
3420
3421     case SVt_RV:
3422         if (dtype < SVt_RV)
3423             sv_upgrade(dstr, SVt_RV);
3424         break;
3425     case SVt_PVFM:
3426 #ifdef PERL_OLD_COPY_ON_WRITE
3427         if ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS) {
3428             if (dtype < SVt_PVIV)
3429                 sv_upgrade(dstr, SVt_PVIV);
3430             break;
3431         }
3432         /* Fall through */
3433 #endif
3434     case SVt_PV:
3435         if (dtype < SVt_PV)
3436             sv_upgrade(dstr, SVt_PV);
3437         break;
3438     case SVt_PVIV:
3439         if (dtype < SVt_PVIV)
3440             sv_upgrade(dstr, SVt_PVIV);
3441         break;
3442     case SVt_PVNV:
3443         if (dtype < SVt_PVNV)
3444             sv_upgrade(dstr, SVt_PVNV);
3445         break;
3446     default:
3447         {
3448         const char * const type = sv_reftype(sstr,0);
3449         if (PL_op)
3450             Perl_croak(aTHX_ "Bizarre copy of %s in %s", type, OP_NAME(PL_op));
3451         else
3452             Perl_croak(aTHX_ "Bizarre copy of %s", type);
3453         }
3454         break;
3455
3456         /* case SVt_BIND: */
3457     case SVt_PVGV:
3458         if (isGV_with_GP(sstr) && dtype <= SVt_PVGV) {
3459             glob_assign_glob(dstr, sstr, dtype);
3460             return;
3461         }
3462         /* SvVALID means that this PVGV is playing at being an FBM.  */
3463         /*FALLTHROUGH*/
3464
3465     case SVt_PVMG:
3466     case SVt_PVLV:
3467         if (SvGMAGICAL(sstr) && (flags & SV_GMAGIC)) {
3468             mg_get(sstr);
3469             if (SvTYPE(sstr) != stype) {
3470                 stype = SvTYPE(sstr);
3471                 if (isGV_with_GP(sstr) && stype == SVt_PVGV && dtype <= SVt_PVGV) {
3472                     glob_assign_glob(dstr, sstr, dtype);
3473                     return;
3474                 }
3475             }
3476         }
3477         if (stype == SVt_PVLV)
3478             SvUPGRADE(dstr, SVt_PVNV);
3479         else
3480             SvUPGRADE(dstr, (svtype)stype);
3481     }
3482  end_of_first_switch:
3483
3484     /* dstr may have been upgraded.  */
3485     dtype = SvTYPE(dstr);
3486     sflags = SvFLAGS(sstr);
3487
3488     if (dtype == SVt_PVCV) {
3489         /* Assigning to a subroutine sets the prototype.  */
3490         if (SvOK(sstr)) {
3491             STRLEN len;
3492             const char *const ptr = SvPV_const(sstr, len);
3493
3494             SvGROW(dstr, len + 1);
3495             Copy(ptr, SvPVX(dstr), len + 1, char);
3496             SvCUR_set(dstr, len);
3497             SvPOK_only(dstr);
3498         } else {
3499             SvOK_off(dstr);
3500         }
3501     } else if (sflags & SVf_ROK) {
3502         if (isGV_with_GP(dstr) && dtype == SVt_PVGV
3503             && SvTYPE(SvRV(sstr)) == SVt_PVGV) {
3504             sstr = SvRV(sstr);
3505             if (sstr == dstr) {
3506                 if (GvIMPORTED(dstr) != GVf_IMPORTED
3507                     && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3508                 {
3509                     GvIMPORTED_on(dstr);
3510                 }
3511                 GvMULTI_on(dstr);
3512                 return;
3513             }
3514             glob_assign_glob(dstr, sstr, dtype);
3515             return;
3516         }
3517
3518         if (dtype >= SVt_PV) {
3519             if (dtype == SVt_PVGV) {
3520                 glob_assign_ref(dstr, sstr);
3521                 return;
3522             }
3523             if (SvPVX_const(dstr)) {
3524                 SvPV_free(dstr);
3525                 SvLEN_set(dstr, 0);
3526                 SvCUR_set(dstr, 0);
3527             }
3528         }
3529         (void)SvOK_off(dstr);
3530         SvRV_set(dstr, SvREFCNT_inc(SvRV(sstr)));
3531         SvFLAGS(dstr) |= sflags & SVf_ROK;
3532         assert(!(sflags & SVp_NOK));
3533         assert(!(sflags & SVp_IOK));
3534         assert(!(sflags & SVf_NOK));
3535         assert(!(sflags & SVf_IOK));
3536     }
3537     else if (dtype == SVt_PVGV && isGV_with_GP(dstr)) {
3538         if (!(sflags & SVf_OK)) {
3539             if (ckWARN(WARN_MISC))
3540                 Perl_warner(aTHX_ packWARN(WARN_MISC),
3541                             "Undefined value assigned to typeglob");
3542         }
3543         else {
3544             GV *gv = gv_fetchsv(sstr, GV_ADD, SVt_PVGV);
3545             if (dstr != (SV*)gv) {
3546                 if (GvGP(dstr))
3547                     gp_free((GV*)dstr);
3548                 GvGP(dstr) = gp_ref(GvGP(gv));
3549             }
3550         }
3551     }
3552     else if (sflags & SVp_POK) {
3553         bool isSwipe = 0;
3554
3555         /*
3556          * Check to see if we can just swipe the string.  If so, it's a
3557          * possible small lose on short strings, but a big win on long ones.
3558          * It might even be a win on short strings if SvPVX_const(dstr)
3559          * has to be allocated and SvPVX_const(sstr) has to be freed.
3560          * Likewise if we can set up COW rather than doing an actual copy, we
3561          * drop to the else clause, as the swipe code and the COW setup code
3562          * have much in common.
3563          */
3564
3565         /* Whichever path we take through the next code, we want this true,
3566            and doing it now facilitates the COW check.  */
3567         (void)SvPOK_only(dstr);
3568
3569         if (
3570             /* If we're already COW then this clause is not true, and if COW
3571                is allowed then we drop down to the else and make dest COW 
3572                with us.  If caller hasn't said that we're allowed to COW
3573                shared hash keys then we don't do the COW setup, even if the
3574                source scalar is a shared hash key scalar.  */
3575             (((flags & SV_COW_SHARED_HASH_KEYS)
3576                ? (sflags & (SVf_FAKE|SVf_READONLY)) != (SVf_FAKE|SVf_READONLY)
3577                : 1 /* If making a COW copy is forbidden then the behaviour we
3578                        desire is as if the source SV isn't actually already
3579                        COW, even if it is.  So we act as if the source flags
3580                        are not COW, rather than actually testing them.  */
3581               )
3582 #ifndef PERL_OLD_COPY_ON_WRITE
3583              /* The change that added SV_COW_SHARED_HASH_KEYS makes the logic
3584                 when PERL_OLD_COPY_ON_WRITE is defined a little wrong.
3585                 Conceptually PERL_OLD_COPY_ON_WRITE being defined should
3586                 override SV_COW_SHARED_HASH_KEYS, because it means "always COW"
3587                 but in turn, it's somewhat dead code, never expected to go
3588                 live, but more kept as a placeholder on how to do it better
3589                 in a newer implementation.  */
3590              /* If we are COW and dstr is a suitable target then we drop down
3591                 into the else and make dest a COW of us.  */
3592              || (SvFLAGS(dstr) & CAN_COW_MASK) != CAN_COW_FLAGS
3593 #endif
3594              )
3595             &&
3596             !(isSwipe =
3597                  (sflags & SVs_TEMP) &&   /* slated for free anyway? */
3598                  !(sflags & SVf_OOK) &&   /* and not involved in OOK hack? */
3599                  (!(flags & SV_NOSTEAL)) &&
3600                                         /* and we're allowed to steal temps */
3601                  SvREFCNT(sstr) == 1 &&   /* and no other references to it? */
3602                  SvLEN(sstr)    &&        /* and really is a string */
3603                                 /* and won't be needed again, potentially */
3604               !(PL_op && PL_op->op_type == OP_AASSIGN))
3605 #ifdef PERL_OLD_COPY_ON_WRITE
3606             && !((sflags & CAN_COW_MASK) == CAN_COW_FLAGS
3607                  && (SvFLAGS(dstr) & CAN_COW_MASK) == CAN_COW_FLAGS
3608                  && SvTYPE(sstr) >= SVt_PVIV)
3609 #endif
3610             ) {
3611             /* Failed the swipe test, and it's not a shared hash key either.
3612                Have to copy the string.  */
3613             STRLEN len = SvCUR(sstr);
3614             SvGROW(dstr, len + 1);      /* inlined from sv_setpvn */
3615             Move(SvPVX_const(sstr),SvPVX(dstr),len,char);
3616             SvCUR_set(dstr, len);
3617             *SvEND(dstr) = '\0';
3618         } else {
3619             /* If PERL_OLD_COPY_ON_WRITE is not defined, then isSwipe will always
3620                be true in here.  */
3621             /* Either it's a shared hash key, or it's suitable for
3622                copy-on-write or we can swipe the string.  */
3623             if (DEBUG_C_TEST) {
3624                 PerlIO_printf(Perl_debug_log, "Copy on write: sstr --> dstr\n");
3625                 sv_dump(sstr);
3626                 sv_dump(dstr);
3627             }
3628 #ifdef PERL_OLD_COPY_ON_WRITE
3629             if (!isSwipe) {
3630                 /* I believe I should acquire a global SV mutex if
3631                    it's a COW sv (not a shared hash key) to stop
3632                    it going un copy-on-write.
3633                    If the source SV has gone un copy on write between up there
3634                    and down here, then (assert() that) it is of the correct
3635                    form to make it copy on write again */
3636                 if ((sflags & (SVf_FAKE | SVf_READONLY))
3637                     != (SVf_FAKE | SVf_READONLY)) {
3638                     SvREADONLY_on(sstr);
3639                     SvFAKE_on(sstr);
3640                     /* Make the source SV into a loop of 1.
3641                        (about to become 2) */
3642                     SV_COW_NEXT_SV_SET(sstr, sstr);
3643                 }
3644             }
3645 #endif
3646             /* Initial code is common.  */
3647             if (SvPVX_const(dstr)) {    /* we know that dtype >= SVt_PV */
3648                 SvPV_free(dstr);
3649             }
3650
3651             if (!isSwipe) {
3652                 /* making another shared SV.  */
3653                 STRLEN cur = SvCUR(sstr);
3654                 STRLEN len = SvLEN(sstr);
3655 #ifdef PERL_OLD_COPY_ON_WRITE
3656                 if (len) {
3657                     assert (SvTYPE(dstr) >= SVt_PVIV);
3658                     /* SvIsCOW_normal */
3659                     /* splice us in between source and next-after-source.  */
3660                     SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
3661                     SV_COW_NEXT_SV_SET(sstr, dstr);
3662                     SvPV_set(dstr, SvPVX_mutable(sstr));
3663                 } else
3664 #endif
3665                 {
3666                     /* SvIsCOW_shared_hash */
3667                     DEBUG_C(PerlIO_printf(Perl_debug_log,
3668                                           "Copy on write: Sharing hash\n"));
3669
3670                     assert (SvTYPE(dstr) >= SVt_PV);
3671                     SvPV_set(dstr,
3672                              HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)))));
3673                 }
3674                 SvLEN_set(dstr, len);
3675                 SvCUR_set(dstr, cur);
3676                 SvREADONLY_on(dstr);
3677                 SvFAKE_on(dstr);
3678                 /* Relesase a global SV mutex.  */
3679             }
3680             else
3681                 {       /* Passes the swipe test.  */
3682                 SvPV_set(dstr, SvPVX_mutable(sstr));
3683                 SvLEN_set(dstr, SvLEN(sstr));
3684                 SvCUR_set(dstr, SvCUR(sstr));
3685
3686                 SvTEMP_off(dstr);
3687                 (void)SvOK_off(sstr);   /* NOTE: nukes most SvFLAGS on sstr */
3688                 SvPV_set(sstr, NULL);
3689                 SvLEN_set(sstr, 0);
3690                 SvCUR_set(sstr, 0);
3691                 SvTEMP_off(sstr);
3692             }
3693         }
3694         if (sflags & SVp_NOK) {
3695             SvNV_set(dstr, SvNVX(sstr));
3696         }
3697         if (sflags & SVp_IOK) {
3698             SvRELEASE_IVX(dstr);
3699             SvIV_set(dstr, SvIVX(sstr));
3700             /* Must do this otherwise some other overloaded use of 0x80000000
3701                gets confused. I guess SVpbm_VALID */
3702             if (sflags & SVf_IVisUV)
3703                 SvIsUV_on(dstr);
3704         }
3705         SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_NOK|SVp_NOK|SVf_UTF8);
3706         {
3707             const MAGIC * const smg = SvVSTRING_mg(sstr);
3708             if (smg) {
3709                 sv_magic(dstr, NULL, PERL_MAGIC_vstring,
3710                          smg->mg_ptr, smg->mg_len);
3711                 SvRMAGICAL_on(dstr);
3712             }
3713         }
3714     }
3715     else if (sflags & (SVp_IOK|SVp_NOK)) {
3716         (void)SvOK_off(dstr);
3717         SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_IVisUV|SVf_NOK|SVp_NOK);
3718         if (sflags & SVp_IOK) {
3719             /* XXXX Do we want to set IsUV for IV(ROK)?  Be extra safe... */
3720             SvIV_set(dstr, SvIVX(sstr));
3721         }
3722         if (sflags & SVp_NOK) {
3723             SvNV_set(dstr, SvNVX(sstr));
3724         }
3725     }
3726     else {
3727         if (isGV_with_GP(sstr)) {
3728             /* This stringification rule for globs is spread in 3 places.
3729                This feels bad. FIXME.  */
3730             const U32 wasfake = sflags & SVf_FAKE;
3731
3732             /* FAKE globs can get coerced, so need to turn this off
3733                temporarily if it is on.  */
3734             SvFAKE_off(sstr);
3735             gv_efullname3(dstr, (GV *)sstr, "*");
3736             SvFLAGS(sstr) |= wasfake;
3737         }
3738         else
3739             (void)SvOK_off(dstr);
3740     }
3741     if (SvTAINTED(sstr))
3742         SvTAINT(dstr);
3743 }
3744
3745 /*
3746 =for apidoc sv_setsv_mg
3747
3748 Like C<sv_setsv>, but also handles 'set' magic.
3749
3750 =cut
3751 */
3752
3753 void
3754 Perl_sv_setsv_mg(pTHX_ SV *dstr, register SV *sstr)
3755 {
3756     sv_setsv(dstr,sstr);
3757     SvSETMAGIC(dstr);
3758 }
3759
3760 #ifdef PERL_OLD_COPY_ON_WRITE
3761 SV *
3762 Perl_sv_setsv_cow(pTHX_ SV *dstr, SV *sstr)
3763 {
3764     STRLEN cur = SvCUR(sstr);
3765     STRLEN len = SvLEN(sstr);
3766     register char *new_pv;
3767
3768     if (DEBUG_C_TEST) {
3769         PerlIO_printf(Perl_debug_log, "Fast copy on write: %p -> %p\n",
3770                       sstr, dstr);
3771         sv_dump(sstr);
3772         if (dstr)
3773                     sv_dump(dstr);
3774     }
3775
3776     if (dstr) {
3777         if (SvTHINKFIRST(dstr))
3778             sv_force_normal_flags(dstr, SV_COW_DROP_PV);
3779         else if (SvPVX_const(dstr))
3780             Safefree(SvPVX_const(dstr));
3781     }
3782     else
3783         new_SV(dstr);
3784     SvUPGRADE(dstr, SVt_PVIV);
3785
3786     assert (SvPOK(sstr));
3787     assert (SvPOKp(sstr));
3788     assert (!SvIOK(sstr));
3789     assert (!SvIOKp(sstr));
3790     assert (!SvNOK(sstr));
3791     assert (!SvNOKp(sstr));
3792
3793     if (SvIsCOW(sstr)) {
3794
3795         if (SvLEN(sstr) == 0) {
3796             /* source is a COW shared hash key.  */
3797             DEBUG_C(PerlIO_printf(Perl_debug_log,
3798                                   "Fast copy on write: Sharing hash\n"));
3799             new_pv = HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr))));
3800             goto common_exit;
3801         }
3802         SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
3803     } else {
3804         assert ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS);
3805         SvUPGRADE(sstr, SVt_PVIV);
3806         SvREADONLY_on(sstr);
3807         SvFAKE_on(sstr);
3808         DEBUG_C(PerlIO_printf(Perl_debug_log,
3809                               "Fast copy on write: Converting sstr to COW\n"));
3810         SV_COW_NEXT_SV_SET(dstr, sstr);
3811     }
3812     SV_COW_NEXT_SV_SET(sstr, dstr);
3813     new_pv = SvPVX_mutable(sstr);
3814
3815   common_exit:
3816     SvPV_set(dstr, new_pv);
3817     SvFLAGS(dstr) = (SVt_PVIV|SVf_POK|SVp_POK|SVf_FAKE|SVf_READONLY);
3818     if (SvUTF8(sstr))
3819         SvUTF8_on(dstr);
3820     SvLEN_set(dstr, len);
3821     SvCUR_set(dstr, cur);
3822     if (DEBUG_C_TEST) {
3823         sv_dump(dstr);
3824     }
3825     return dstr;
3826 }
3827 #endif
3828
3829 /*
3830 =for apidoc sv_setpvn
3831
3832 Copies a string into an SV.  The C<len> parameter indicates the number of
3833 bytes to be copied.  If the C<ptr> argument is NULL the SV will become
3834 undefined.  Does not handle 'set' magic.  See C<sv_setpvn_mg>.
3835
3836 =cut
3837 */
3838
3839 void
3840 Perl_sv_setpvn(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
3841 {
3842     dVAR;
3843     register char *dptr;
3844
3845     SV_CHECK_THINKFIRST_COW_DROP(sv);
3846     if (!ptr) {
3847         (void)SvOK_off(sv);
3848         return;
3849     }
3850     else {
3851         /* len is STRLEN which is unsigned, need to copy to signed */
3852         const IV iv = len;
3853         if (iv < 0)
3854             Perl_croak(aTHX_ "panic: sv_setpvn called with negative strlen");
3855     }
3856     SvUPGRADE(sv, SVt_PV);
3857
3858     dptr = SvGROW(sv, len + 1);
3859     Move(ptr,dptr,len,char);
3860     dptr[len] = '\0';
3861     SvCUR_set(sv, len);
3862     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
3863     SvTAINT(sv);
3864 }
3865
3866 /*
3867 =for apidoc sv_setpvn_mg
3868
3869 Like C<sv_setpvn>, but also handles 'set' magic.
3870
3871 =cut
3872 */
3873
3874 void
3875 Perl_sv_setpvn_mg(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
3876 {
3877     sv_setpvn(sv,ptr,len);
3878     SvSETMAGIC(sv);
3879 }
3880
3881 /*
3882 =for apidoc sv_setpv
3883
3884 Copies a string into an SV.  The string must be null-terminated.  Does not
3885 handle 'set' magic.  See C<sv_setpv_mg>.
3886
3887 =cut
3888 */
3889
3890 void
3891 Perl_sv_setpv(pTHX_ register SV *sv, register const char *ptr)
3892 {
3893     dVAR;
3894     register STRLEN len;
3895
3896     SV_CHECK_THINKFIRST_COW_DROP(sv);
3897     if (!ptr) {
3898         (void)SvOK_off(sv);
3899         return;
3900     }
3901     len = strlen(ptr);
3902     SvUPGRADE(sv, SVt_PV);
3903
3904     SvGROW(sv, len + 1);
3905     Move(ptr,SvPVX(sv),len+1,char);
3906     SvCUR_set(sv, len);
3907     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
3908     SvTAINT(sv);
3909 }
3910
3911 /*
3912 =for apidoc sv_setpv_mg
3913
3914 Like C<sv_setpv>, but also handles 'set' magic.
3915
3916 =cut
3917 */
3918
3919 void
3920 Perl_sv_setpv_mg(pTHX_ register SV *sv, register const char *ptr)
3921 {
3922     sv_setpv(sv,ptr);
3923     SvSETMAGIC(sv);
3924 }
3925
3926 /*
3927 =for apidoc sv_usepvn_flags
3928
3929 Tells an SV to use C<ptr> to find its string value.  Normally the
3930 string is stored inside the SV but sv_usepvn allows the SV to use an
3931 outside string.  The C<ptr> should point to memory that was allocated
3932 by C<malloc>.  The string length, C<len>, must be supplied.  By default
3933 this function will realloc (i.e. move) the memory pointed to by C<ptr>,
3934 so that pointer should not be freed or used by the programmer after
3935 giving it to sv_usepvn, and neither should any pointers from "behind"
3936 that pointer (e.g. ptr + 1) be used.
3937
3938 If C<flags> & SV_SMAGIC is true, will call SvSETMAGIC. If C<flags> &
3939 SV_HAS_TRAILING_NUL is true, then C<ptr[len]> must be NUL, and the realloc
3940 will be skipped. (i.e. the buffer is actually at least 1 byte longer than
3941 C<len>, and already meets the requirements for storing in C<SvPVX>)
3942
3943 =cut
3944 */
3945
3946 void
3947 Perl_sv_usepvn_flags(pTHX_ SV *sv, char *ptr, STRLEN len, U32 flags)
3948 {
3949     dVAR;
3950     STRLEN allocate;
3951     SV_CHECK_THINKFIRST_COW_DROP(sv);
3952     SvUPGRADE(sv, SVt_PV);
3953     if (!ptr) {
3954         (void)SvOK_off(sv);
3955         if (flags & SV_SMAGIC)
3956             SvSETMAGIC(sv);
3957         return;
3958     }
3959     if (SvPVX_const(sv))
3960         SvPV_free(sv);
3961
3962 #ifdef DEBUGGING
3963     if (flags & SV_HAS_TRAILING_NUL)
3964         assert(ptr[len] == '\0');
3965 #endif
3966
3967     allocate = (flags & SV_HAS_TRAILING_NUL)
3968         ? len + 1: PERL_STRLEN_ROUNDUP(len + 1);
3969     if (flags & SV_HAS_TRAILING_NUL) {
3970         /* It's long enough - do nothing.
3971            Specfically Perl_newCONSTSUB is relying on this.  */
3972     } else {
3973 #ifdef DEBUGGING
3974         /* Force a move to shake out bugs in callers.  */
3975         char *new_ptr = (char*)safemalloc(allocate);
3976         Copy(ptr, new_ptr, len, char);
3977         PoisonFree(ptr,len,char);
3978         Safefree(ptr);
3979         ptr = new_ptr;
3980 #else
3981         ptr = (char*) saferealloc (ptr, allocate);
3982 #endif
3983     }
3984     SvPV_set(sv, ptr);
3985     SvCUR_set(sv, len);
3986     SvLEN_set(sv, allocate);
3987     if (!(flags & SV_HAS_TRAILING_NUL)) {
3988         *SvEND(sv) = '\0';
3989     }
3990     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
3991     SvTAINT(sv);
3992     if (flags & SV_SMAGIC)
3993         SvSETMAGIC(sv);
3994 }
3995
3996 #ifdef PERL_OLD_COPY_ON_WRITE
3997 /* Need to do this *after* making the SV normal, as we need the buffer
3998    pointer to remain valid until after we've copied it.  If we let go too early,
3999    another thread could invalidate it by unsharing last of the same hash key
4000    (which it can do by means other than releasing copy-on-write Svs)
4001    or by changing the other copy-on-write SVs in the loop.  */
4002 STATIC void
4003 S_sv_release_COW(pTHX_ register SV *sv, const char *pvx, STRLEN len, SV *after)
4004 {
4005     if (len) { /* this SV was SvIsCOW_normal(sv) */
4006          /* we need to find the SV pointing to us.  */
4007         SV *current = SV_COW_NEXT_SV(after);
4008
4009         if (current == sv) {
4010             /* The SV we point to points back to us (there were only two of us
4011                in the loop.)
4012                Hence other SV is no longer copy on write either.  */
4013             SvFAKE_off(after);
4014             SvREADONLY_off(after);
4015         } else {
4016             /* We need to follow the pointers around the loop.  */
4017             SV *next;
4018             while ((next = SV_COW_NEXT_SV(current)) != sv) {
4019                 assert (next);
4020                 current = next;
4021                  /* don't loop forever if the structure is bust, and we have
4022                     a pointer into a closed loop.  */
4023                 assert (current != after);
4024                 assert (SvPVX_const(current) == pvx);
4025             }
4026             /* Make the SV before us point to the SV after us.  */
4027             SV_COW_NEXT_SV_SET(current, after);
4028         }
4029     } else {
4030         unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4031     }
4032 }
4033
4034 int
4035 Perl_sv_release_IVX(pTHX_ register SV *sv)
4036 {
4037     if (SvIsCOW(sv))
4038         sv_force_normal_flags(sv, 0);
4039     SvOOK_off(sv);
4040     return 0;
4041 }
4042 #endif
4043 /*
4044 =for apidoc sv_force_normal_flags
4045
4046 Undo various types of fakery on an SV: if the PV is a shared string, make
4047 a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
4048 an xpvmg; if we're a copy-on-write scalar, this is the on-write time when
4049 we do the copy, and is also used locally. If C<SV_COW_DROP_PV> is set
4050 then a copy-on-write scalar drops its PV buffer (if any) and becomes
4051 SvPOK_off rather than making a copy. (Used where this scalar is about to be
4052 set to some other value.) In addition, the C<flags> parameter gets passed to
4053 C<sv_unref_flags()> when unrefing. C<sv_force_normal> calls this function
4054 with flags set to 0.
4055
4056 =cut
4057 */
4058
4059 void
4060 Perl_sv_force_normal_flags(pTHX_ register SV *sv, U32 flags)
4061 {
4062     dVAR;
4063 #ifdef PERL_OLD_COPY_ON_WRITE
4064     if (SvREADONLY(sv)) {
4065         /* At this point I believe I should acquire a global SV mutex.  */
4066         if (SvFAKE(sv)) {
4067             const char * const pvx = SvPVX_const(sv);
4068             const STRLEN len = SvLEN(sv);
4069             const STRLEN cur = SvCUR(sv);
4070             SV * const next = SV_COW_NEXT_SV(sv);   /* next COW sv in the loop. */
4071             if (DEBUG_C_TEST) {
4072                 PerlIO_printf(Perl_debug_log,
4073                               "Copy on write: Force normal %ld\n",
4074                               (long) flags);
4075                 sv_dump(sv);
4076             }
4077             SvFAKE_off(sv);
4078             SvREADONLY_off(sv);
4079             /* This SV doesn't own the buffer, so need to Newx() a new one:  */
4080             SvPV_set(sv, NULL);
4081             SvLEN_set(sv, 0);
4082             if (flags & SV_COW_DROP_PV) {
4083                 /* OK, so we don't need to copy our buffer.  */
4084                 SvPOK_off(sv);
4085             } else {
4086                 SvGROW(sv, cur + 1);
4087                 Move(pvx,SvPVX(sv),cur,char);
4088                 SvCUR_set(sv, cur);
4089                 *SvEND(sv) = '\0';
4090             }
4091             sv_release_COW(sv, pvx, len, next);
4092             if (DEBUG_C_TEST) {
4093                 sv_dump(sv);
4094             }
4095         }
4096         else if (IN_PERL_RUNTIME)
4097             Perl_croak(aTHX_ PL_no_modify);
4098         /* At this point I believe that I can drop the global SV mutex.  */
4099     }
4100 #else
4101     if (SvREADONLY(sv)) {
4102         if (SvFAKE(sv)) {
4103             const char * const pvx = SvPVX_const(sv);
4104             const STRLEN len = SvCUR(sv);
4105             SvFAKE_off(sv);
4106             SvREADONLY_off(sv);
4107             SvPV_set(sv, NULL);
4108             SvLEN_set(sv, 0);
4109             SvGROW(sv, len + 1);
4110             Move(pvx,SvPVX(sv),len,char);
4111             *SvEND(sv) = '\0';
4112             unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4113         }
4114         else if (IN_PERL_RUNTIME)
4115             Perl_croak(aTHX_ PL_no_modify);
4116     }
4117 #endif
4118     if (SvROK(sv))
4119         sv_unref_flags(sv, flags);
4120     else if (SvFAKE(sv) && SvTYPE(sv) == SVt_PVGV)
4121         sv_unglob(sv);
4122 }
4123
4124 /*
4125 =for apidoc sv_chop
4126
4127 Efficient removal of characters from the beginning of the string buffer.
4128 SvPOK(sv) must be true and the C<ptr> must be a pointer to somewhere inside
4129 the string buffer.  The C<ptr> becomes the first character of the adjusted
4130 string. Uses the "OOK hack".
4131 Beware: after this function returns, C<ptr> and SvPVX_const(sv) may no longer
4132 refer to the same chunk of data.
4133
4134 =cut
4135 */
4136
4137 void
4138 Perl_sv_chop(pTHX_ register SV *sv, register const char *ptr)
4139 {
4140     register STRLEN delta;
4141     if (!ptr || !SvPOKp(sv))
4142         return;
4143     delta = ptr - SvPVX_const(sv);
4144     SV_CHECK_THINKFIRST(sv);
4145     if (SvTYPE(sv) < SVt_PVIV)
4146         sv_upgrade(sv,SVt_PVIV);
4147
4148     if (!SvOOK(sv)) {
4149         if (!SvLEN(sv)) { /* make copy of shared string */
4150             const char *pvx = SvPVX_const(sv);
4151             const STRLEN len = SvCUR(sv);
4152             SvGROW(sv, len + 1);
4153             Move(pvx,SvPVX(sv),len,char);
4154             *SvEND(sv) = '\0';
4155         }
4156         SvIV_set(sv, 0);
4157         /* Same SvOOK_on but SvOOK_on does a SvIOK_off
4158            and we do that anyway inside the SvNIOK_off
4159         */
4160         SvFLAGS(sv) |= SVf_OOK;
4161     }
4162     SvNIOK_off(sv);
4163     SvLEN_set(sv, SvLEN(sv) - delta);
4164     SvCUR_set(sv, SvCUR(sv) - delta);
4165     SvPV_set(sv, SvPVX(sv) + delta);
4166     SvIV_set(sv, SvIVX(sv) + delta);
4167 }
4168
4169 /*
4170 =for apidoc sv_catpvn
4171
4172 Concatenates the string onto the end of the string which is in the SV.  The
4173 C<len> indicates number of bytes to copy.  If the SV has the UTF-8
4174 status set, then the bytes appended should be valid UTF-8.
4175 Handles 'get' magic, but not 'set' magic.  See C<sv_catpvn_mg>.
4176
4177 =for apidoc sv_catpvn_flags
4178
4179 Concatenates the string onto the end of the string which is in the SV.  The
4180 C<len> indicates number of bytes to copy.  If the SV has the UTF-8
4181 status set, then the bytes appended should be valid UTF-8.
4182 If C<flags> has C<SV_GMAGIC> bit set, will C<mg_get> on C<dsv> if
4183 appropriate, else not. C<sv_catpvn> and C<sv_catpvn_nomg> are implemented
4184 in terms of this function.
4185
4186 =cut
4187 */
4188
4189 void
4190 Perl_sv_catpvn_flags(pTHX_ register SV *dsv, register const char *sstr, register STRLEN slen, I32 flags)
4191 {
4192     dVAR;
4193     STRLEN dlen;
4194     const char * const dstr = SvPV_force_flags(dsv, dlen, flags);
4195
4196     SvGROW(dsv, dlen + slen + 1);
4197     if (sstr == dstr)
4198         sstr = SvPVX_const(dsv);
4199     Move(sstr, SvPVX(dsv) + dlen, slen, char);
4200     SvCUR_set(dsv, SvCUR(dsv) + slen);
4201     *SvEND(dsv) = '\0';
4202     (void)SvPOK_only_UTF8(dsv);         /* validate pointer */
4203     SvTAINT(dsv);
4204     if (flags & SV_SMAGIC)
4205         SvSETMAGIC(dsv);
4206 }
4207
4208 /*
4209 =for apidoc sv_catsv
4210
4211 Concatenates the string from SV C<ssv> onto the end of the string in
4212 SV C<dsv>.  Modifies C<dsv> but not C<ssv>.  Handles 'get' magic, but
4213 not 'set' magic.  See C<sv_catsv_mg>.
4214
4215 =for apidoc sv_catsv_flags
4216
4217 Concatenates the string from SV C<ssv> onto the end of the string in
4218 SV C<dsv>.  Modifies C<dsv> but not C<ssv>.  If C<flags> has C<SV_GMAGIC>
4219 bit set, will C<mg_get> on the SVs if appropriate, else not. C<sv_catsv>
4220 and C<sv_catsv_nomg> are implemented in terms of this function.
4221
4222 =cut */
4223
4224 void
4225 Perl_sv_catsv_flags(pTHX_ SV *dsv, register SV *ssv, I32 flags)
4226 {
4227     dVAR;
4228     if (ssv) {
4229         STRLEN slen;
4230         const char *spv = SvPV_const(ssv, slen);
4231         if (spv) {
4232             /*  sutf8 and dutf8 were type bool, but under USE_ITHREADS,
4233                 gcc version 2.95.2 20000220 (Debian GNU/Linux) for
4234                 Linux xxx 2.2.17 on sparc64 with gcc -O2, we erroneously
4235                 get dutf8 = 0x20000000, (i.e.  SVf_UTF8) even though
4236                 dsv->sv_flags doesn't have that bit set.
4237                 Andy Dougherty  12 Oct 2001
4238             */
4239             const I32 sutf8 = DO_UTF8(ssv);
4240             I32 dutf8;
4241
4242             if (SvGMAGICAL(dsv) && (flags & SV_GMAGIC))
4243                 mg_get(dsv);
4244             dutf8 = DO_UTF8(dsv);
4245
4246             if (dutf8 != sutf8) {
4247                 if (dutf8) {
4248                     /* Not modifying source SV, so taking a temporary copy. */
4249                     SV* const csv = sv_2mortal(newSVpvn(spv, slen));
4250
4251                     sv_utf8_upgrade(csv);
4252                     spv = SvPV_const(csv, slen);
4253                 }
4254                 else
4255                     sv_utf8_upgrade_nomg(dsv);
4256             }
4257             sv_catpvn_nomg(dsv, spv, slen);
4258         }
4259     }
4260     if (flags & SV_SMAGIC)
4261         SvSETMAGIC(dsv);
4262 }
4263
4264 /*
4265 =for apidoc sv_catpv
4266
4267 Concatenates the string onto the end of the string which is in the SV.
4268 If the SV has the UTF-8 status set, then the bytes appended should be
4269 valid UTF-8.  Handles 'get' magic, but not 'set' magic.  See C<sv_catpv_mg>.
4270
4271 =cut */
4272
4273 void
4274 Perl_sv_catpv(pTHX_ register SV *sv, register const char *ptr)
4275 {
4276     dVAR;
4277     register STRLEN len;
4278     STRLEN tlen;
4279     char *junk;
4280
4281     if (!ptr)
4282         return;
4283     junk = SvPV_force(sv, tlen);
4284     len = strlen(ptr);
4285     SvGROW(sv, tlen + len + 1);
4286     if (ptr == junk)
4287         ptr = SvPVX_const(sv);
4288     Move(ptr,SvPVX(sv)+tlen,len+1,char);
4289     SvCUR_set(sv, SvCUR(sv) + len);
4290     (void)SvPOK_only_UTF8(sv);          /* validate pointer */
4291     SvTAINT(sv);
4292 }
4293
4294 /*
4295 =for apidoc sv_catpv_mg
4296
4297 Like C<sv_catpv>, but also handles 'set' magic.
4298
4299 =cut
4300 */
4301
4302 void
4303 Perl_sv_catpv_mg(pTHX_ register SV *sv, register const char *ptr)
4304 {
4305     sv_catpv(sv,ptr);
4306     SvSETMAGIC(sv);
4307 }
4308
4309 /*
4310 =for apidoc newSV
4311
4312 Creates a new SV.  A non-zero C<len> parameter indicates the number of
4313 bytes of preallocated string space the SV should have.  An extra byte for a
4314 trailing NUL is also reserved.  (SvPOK is not set for the SV even if string
4315 space is allocated.)  The reference count for the new SV is set to 1.
4316
4317 In 5.9.3, newSV() replaces the older NEWSV() API, and drops the first
4318 parameter, I<x>, a debug aid which allowed callers to identify themselves.
4319 This aid has been superseded by a new build option, PERL_MEM_LOG (see
4320 L<perlhack/PERL_MEM_LOG>).  The older API is still there for use in XS
4321 modules supporting older perls.
4322
4323 =cut
4324 */
4325
4326 SV *
4327 Perl_newSV(pTHX_ STRLEN len)
4328 {
4329     dVAR;
4330     register SV *sv;
4331
4332     new_SV(sv);
4333     if (len) {
4334         sv_upgrade(sv, SVt_PV);
4335         SvGROW(sv, len + 1);
4336     }
4337     return sv;
4338 }
4339 /*
4340 =for apidoc sv_magicext
4341
4342 Adds magic to an SV, upgrading it if necessary. Applies the
4343 supplied vtable and returns a pointer to the magic added.
4344
4345 Note that C<sv_magicext> will allow things that C<sv_magic> will not.
4346 In particular, you can add magic to SvREADONLY SVs, and add more than
4347 one instance of the same 'how'.
4348
4349 If C<namlen> is greater than zero then a C<savepvn> I<copy> of C<name> is
4350 stored, if C<namlen> is zero then C<name> is stored as-is and - as another
4351 special case - if C<(name && namlen == HEf_SVKEY)> then C<name> is assumed
4352 to contain an C<SV*> and is stored as-is with its REFCNT incremented.
4353
4354 (This is now used as a subroutine by C<sv_magic>.)
4355
4356 =cut
4357 */
4358 MAGIC * 
4359 Perl_sv_magicext(pTHX_ SV* sv, SV* obj, int how, MGVTBL *vtable,
4360                  const char* name, I32 namlen)
4361 {
4362     dVAR;
4363     MAGIC* mg;
4364
4365     if (SvTYPE(sv) < SVt_PVMG) {
4366         SvUPGRADE(sv, SVt_PVMG);
4367     }
4368     Newxz(mg, 1, MAGIC);
4369     mg->mg_moremagic = SvMAGIC(sv);
4370     SvMAGIC_set(sv, mg);
4371
4372     /* Sometimes a magic contains a reference loop, where the sv and
4373        object refer to each other.  To prevent a reference loop that
4374        would prevent such objects being freed, we look for such loops
4375        and if we find one we avoid incrementing the object refcount.
4376
4377        Note we cannot do this to avoid self-tie loops as intervening RV must
4378        have its REFCNT incremented to keep it in existence.
4379
4380     */
4381     if (!obj || obj == sv ||
4382         how == PERL_MAGIC_arylen ||
4383         how == PERL_MAGIC_qr ||
4384         how == PERL_MAGIC_symtab ||
4385         (SvTYPE(obj) == SVt_PVGV &&
4386             (GvSV(obj) == sv || GvHV(obj) == (HV*)sv || GvAV(obj) == (AV*)sv ||
4387             GvCV(obj) == (CV*)sv || GvIOp(obj) == (IO*)sv ||
4388             GvFORM(obj) == (CV*)sv)))
4389     {
4390         mg->mg_obj = obj;
4391     }
4392     else {
4393         mg->mg_obj = SvREFCNT_inc_simple(obj);
4394         mg->mg_flags |= MGf_REFCOUNTED;
4395     }
4396
4397     /* Normal self-ties simply pass a null object, and instead of
4398        using mg_obj directly, use the SvTIED_obj macro to produce a
4399        new RV as needed.  For glob "self-ties", we are tieing the PVIO
4400        with an RV obj pointing to the glob containing the PVIO.  In
4401        this case, to avoid a reference loop, we need to weaken the
4402        reference.
4403     */
4404
4405     if (how == PERL_MAGIC_tiedscalar && SvTYPE(sv) == SVt_PVIO &&
4406         obj && SvROK(obj) && GvIO(SvRV(obj)) == (IO*)sv)
4407     {
4408       sv_rvweaken(obj);
4409     }
4410
4411     mg->mg_type = how;
4412     mg->mg_len = namlen;
4413     if (name) {
4414         if (namlen > 0)
4415             mg->mg_ptr = savepvn(name, namlen);
4416         else if (namlen == HEf_SVKEY)
4417             mg->mg_ptr = (char*)SvREFCNT_inc_simple_NN((SV*)name);
4418         else
4419             mg->mg_ptr = (char *) name;
4420     }
4421     mg->mg_virtual = vtable;
4422
4423     mg_magical(sv);
4424     if (SvGMAGICAL(sv))
4425         SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK|SVf_POK);
4426     return mg;
4427 }
4428
4429 /*
4430 =for apidoc sv_magic
4431
4432 Adds magic to an SV. First upgrades C<sv> to type C<SVt_PVMG> if necessary,
4433 then adds a new magic item of type C<how> to the head of the magic list.
4434
4435 See C<sv_magicext> (which C<sv_magic> now calls) for a description of the
4436 handling of the C<name> and C<namlen> arguments.
4437
4438 You need to use C<sv_magicext> to add magic to SvREADONLY SVs and also
4439 to add more than one instance of the same 'how'.
4440
4441 =cut
4442 */
4443
4444 void
4445 Perl_sv_magic(pTHX_ register SV *sv, SV *obj, int how, const char *name, I32 namlen)
4446 {
4447     dVAR;
4448     MGVTBL *vtable;
4449     MAGIC* mg;
4450
4451 #ifdef PERL_OLD_COPY_ON_WRITE
4452     if (SvIsCOW(sv))
4453         sv_force_normal_flags(sv, 0);
4454 #endif
4455     if (SvREADONLY(sv)) {
4456         if (
4457             /* its okay to attach magic to shared strings; the subsequent
4458              * upgrade to PVMG will unshare the string */
4459             !(SvFAKE(sv) && SvTYPE(sv) < SVt_PVMG)
4460
4461             && IN_PERL_RUNTIME
4462             && how != PERL_MAGIC_regex_global
4463             && how != PERL_MAGIC_bm
4464             && how != PERL_MAGIC_fm
4465             && how != PERL_MAGIC_sv
4466             && how != PERL_MAGIC_backref
4467            )
4468         {
4469             Perl_croak(aTHX_ PL_no_modify);
4470         }
4471     }
4472     if (SvMAGICAL(sv) || (how == PERL_MAGIC_taint && SvTYPE(sv) >= SVt_PVMG)) {
4473         if (SvMAGIC(sv) && (mg = mg_find(sv, how))) {
4474             /* sv_magic() refuses to add a magic of the same 'how' as an
4475                existing one
4476              */
4477             if (how == PERL_MAGIC_taint) {
4478                 mg->mg_len |= 1;
4479                 /* Any scalar which already had taint magic on which someone
4480                    (erroneously?) did SvIOK_on() or similar will now be
4481                    incorrectly sporting public "OK" flags.  */
4482                 SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK|SVf_POK);
4483             }
4484             return;
4485         }
4486     }
4487
4488     switch (how) {
4489     case PERL_MAGIC_sv:
4490         vtable = &PL_vtbl_sv;
4491         break;
4492     case PERL_MAGIC_overload:
4493         vtable = &PL_vtbl_amagic;
4494         break;
4495     case PERL_MAGIC_overload_elem:
4496         vtable = &PL_vtbl_amagicelem;
4497         break;
4498     case PERL_MAGIC_overload_table:
4499         vtable = &PL_vtbl_ovrld;
4500         break;
4501     case PERL_MAGIC_bm:
4502         vtable = &PL_vtbl_bm;
4503         break;
4504     case PERL_MAGIC_regdata:
4505         vtable = &PL_vtbl_regdata;
4506         break;
4507     case PERL_MAGIC_regdata_names:
4508         vtable = &PL_vtbl_regdata_names;
4509         break;
4510     case PERL_MAGIC_regdatum:
4511         vtable = &PL_vtbl_regdatum;
4512         break;
4513     case PERL_MAGIC_env:
4514         vtable = &PL_vtbl_env;
4515         break;
4516     case PERL_MAGIC_fm:
4517         vtable = &PL_vtbl_fm;
4518         break;
4519     case PERL_MAGIC_envelem:
4520         vtable = &PL_vtbl_envelem;
4521         break;
4522     case PERL_MAGIC_regex_global:
4523         vtable = &PL_vtbl_mglob;
4524         break;
4525     case PERL_MAGIC_isa:
4526         vtable = &PL_vtbl_isa;
4527         break;
4528     case PERL_MAGIC_isaelem:
4529         vtable = &PL_vtbl_isaelem;
4530         break;
4531     case PERL_MAGIC_nkeys:
4532         vtable = &PL_vtbl_nkeys;
4533         break;
4534     case PERL_MAGIC_dbfile:
4535         vtable = NULL;
4536         break;
4537     case PERL_MAGIC_dbline:
4538         vtable = &PL_vtbl_dbline;
4539         break;
4540 #ifdef USE_LOCALE_COLLATE
4541     case PERL_MAGIC_collxfrm:
4542         vtable = &PL_vtbl_collxfrm;
4543         break;
4544 #endif /* USE_LOCALE_COLLATE */
4545     case PERL_MAGIC_tied:
4546         vtable = &PL_vtbl_pack;
4547         break;
4548     case PERL_MAGIC_tiedelem:
4549     case PERL_MAGIC_tiedscalar:
4550         vtable = &PL_vtbl_packelem;
4551         break;
4552     case PERL_MAGIC_qr:
4553         vtable = &PL_vtbl_regexp;
4554         break;
4555     case PERL_MAGIC_hints:
4556         /* As this vtable is all NULL, we can reuse it.  */
4557     case PERL_MAGIC_sig:
4558         vtable = &PL_vtbl_sig;
4559         break;
4560     case PERL_MAGIC_sigelem:
4561         vtable = &PL_vtbl_sigelem;
4562         break;
4563     case PERL_MAGIC_taint:
4564         vtable = &PL_vtbl_taint;
4565         break;
4566     case PERL_MAGIC_uvar:
4567         vtable = &PL_vtbl_uvar;
4568         break;
4569     case PERL_MAGIC_vec:
4570         vtable = &PL_vtbl_vec;
4571         break;
4572     case PERL_MAGIC_arylen_p:
4573     case PERL_MAGIC_rhash:
4574     case PERL_MAGIC_symtab:
4575     case PERL_MAGIC_vstring:
4576         vtable = NULL;
4577         break;
4578     case PERL_MAGIC_utf8:
4579         vtable = &PL_vtbl_utf8;
4580         break;
4581     case PERL_MAGIC_substr:
4582         vtable = &PL_vtbl_substr;
4583         break;
4584     case PERL_MAGIC_defelem:
4585         vtable = &PL_vtbl_defelem;
4586         break;
4587     case PERL_MAGIC_arylen:
4588         vtable = &PL_vtbl_arylen;
4589         break;
4590     case PERL_MAGIC_pos:
4591         vtable = &PL_vtbl_pos;
4592         break;
4593     case PERL_MAGIC_backref:
4594         vtable = &PL_vtbl_backref;
4595         break;
4596     case PERL_MAGIC_hintselem:
4597         vtable = &PL_vtbl_hintselem;
4598         break;
4599     case PERL_MAGIC_ext:
4600         /* Reserved for use by extensions not perl internals.           */
4601         /* Useful for attaching extension internal data to perl vars.   */
4602         /* Note that multiple extensions may clash if magical scalars   */
4603         /* etc holding private data from one are passed to another.     */
4604         vtable = NULL;
4605         break;
4606     default:
4607         Perl_croak(aTHX_ "Don't know how to handle magic of type \\%o", how);
4608     }
4609
4610     /* Rest of work is done else where */
4611     mg = sv_magicext(sv,obj,how,vtable,name,namlen);
4612
4613     switch (how) {
4614     case PERL_MAGIC_taint:
4615         mg->mg_len = 1;
4616         break;
4617     case PERL_MAGIC_ext:
4618     case PERL_MAGIC_dbfile:
4619         SvRMAGICAL_on(sv);
4620         break;
4621     }
4622 }
4623
4624 /*
4625 =for apidoc sv_unmagic
4626
4627 Removes all magic of type C<type> from an SV.
4628
4629 =cut
4630 */
4631
4632 int
4633 Perl_sv_unmagic(pTHX_ SV *sv, int type)
4634 {
4635     MAGIC* mg;
4636     MAGIC** mgp;
4637     if (SvTYPE(sv) < SVt_PVMG || !SvMAGIC(sv))
4638         return 0;
4639     mgp = &(((XPVMG*) SvANY(sv))->xmg_u.xmg_magic);
4640     for (mg = *mgp; mg; mg = *mgp) {
4641         if (mg->mg_type == type) {
4642             const MGVTBL* const vtbl = mg->mg_virtual;
4643             *mgp = mg->mg_moremagic;
4644             if (vtbl && vtbl->svt_free)
4645                 CALL_FPTR(vtbl->svt_free)(aTHX_ sv, mg);
4646             if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) {
4647                 if (mg->mg_len > 0)
4648                     Safefree(mg->mg_ptr);
4649                 else if (mg->mg_len == HEf_SVKEY)
4650                     SvREFCNT_dec((SV*)mg->mg_ptr);
4651                 else if (mg->mg_type == PERL_MAGIC_utf8)
4652                     Safefree(mg->mg_ptr);
4653             }
4654             if (mg->mg_flags & MGf_REFCOUNTED)
4655                 SvREFCNT_dec(mg->mg_obj);
4656             Safefree(mg);
4657         }
4658         else
4659             mgp = &mg->mg_moremagic;
4660     }
4661     if (!SvMAGIC(sv)) {
4662         SvMAGICAL_off(sv);
4663         SvFLAGS(sv) |= (SvFLAGS(sv) & (SVp_IOK|SVp_NOK|SVp_POK)) >> PRIVSHIFT;
4664         SvMAGIC_set(sv, NULL);
4665     }
4666
4667     return 0;
4668 }
4669
4670 /*
4671 =for apidoc sv_rvweaken
4672
4673 Weaken a reference: set the C<SvWEAKREF> flag on this RV; give the
4674 referred-to SV C<PERL_MAGIC_backref> magic if it hasn't already; and
4675 push a back-reference to this RV onto the array of backreferences
4676 associated with that magic. If the RV is magical, set magic will be
4677 called after the RV is cleared.
4678
4679 =cut
4680 */
4681
4682 SV *
4683 Perl_sv_rvweaken(pTHX_ SV *sv)
4684 {
4685     SV *tsv;
4686     if (!SvOK(sv))  /* let undefs pass */
4687         return sv;
4688     if (!SvROK(sv))
4689         Perl_croak(aTHX_ "Can't weaken a nonreference");
4690     else if (SvWEAKREF(sv)) {
4691         if (ckWARN(WARN_MISC))
4692             Perl_warner(aTHX_ packWARN(WARN_MISC), "Reference is already weak");
4693         return sv;
4694     }
4695     tsv = SvRV(sv);
4696     Perl_sv_add_backref(aTHX_ tsv, sv);
4697     SvWEAKREF_on(sv);
4698     SvREFCNT_dec(tsv);
4699     return sv;
4700 }
4701
4702 /* Give tsv backref magic if it hasn't already got it, then push a
4703  * back-reference to sv onto the array associated with the backref magic.
4704  */
4705
4706 void
4707 Perl_sv_add_backref(pTHX_ SV *tsv, SV *sv)
4708 {
4709     dVAR;
4710     AV *av;
4711
4712     if (SvTYPE(tsv) == SVt_PVHV) {
4713         AV **const avp = Perl_hv_backreferences_p(aTHX_ (HV*)tsv);
4714
4715         av = *avp;
4716         if (!av) {
4717             /* There is no AV in the offical place - try a fixup.  */
4718             MAGIC *const mg = mg_find(tsv, PERL_MAGIC_backref);
4719
4720             if (mg) {
4721                 /* Aha. They've got it stowed in magic.  Bring it back.  */
4722                 av = (AV*)mg->mg_obj;
4723                 /* Stop mg_free decreasing the refernce count.  */
4724                 mg->mg_obj = NULL;
4725                 /* Stop mg_free even calling the destructor, given that
4726                    there's no AV to free up.  */
4727                 mg->mg_virtual = 0;
4728                 sv_unmagic(tsv, PERL_MAGIC_backref);
4729             } else {
4730                 av = newAV();
4731                 AvREAL_off(av);
4732                 SvREFCNT_inc_simple_void(av);
4733             }
4734             *avp = av;
4735         }
4736     } else {
4737         const MAGIC *const mg
4738             = SvMAGICAL(tsv) ? mg_find(tsv, PERL_MAGIC_backref) : NULL;
4739         if (mg)
4740             av = (AV*)mg->mg_obj;
4741         else {
4742             av = newAV();
4743             AvREAL_off(av);
4744             sv_magic(tsv, (SV*)av, PERL_MAGIC_backref, NULL, 0);
4745             /* av now has a refcnt of 2, which avoids it getting freed
4746              * before us during global cleanup. The extra ref is removed
4747              * by magic_killbackrefs() when tsv is being freed */
4748         }
4749     }
4750     if (AvFILLp(av) >= AvMAX(av)) {
4751         av_extend(av, AvFILLp(av)+1);
4752     }
4753     AvARRAY(av)[++AvFILLp(av)] = sv; /* av_push() */
4754 }
4755
4756 /* delete a back-reference to ourselves from the backref magic associated
4757  * with the SV we point to.
4758  */
4759
4760 STATIC void
4761 S_sv_del_backref(pTHX_ SV *tsv, SV *sv)
4762 {
4763     dVAR;
4764     AV *av = NULL;
4765     SV **svp;
4766     I32 i;
4767
4768     if (SvTYPE(tsv) == SVt_PVHV && SvOOK(tsv)) {
4769         av = *Perl_hv_backreferences_p(aTHX_ (HV*)tsv);
4770         /* We mustn't attempt to "fix up" the hash here by moving the
4771            backreference array back to the hv_aux structure, as that is stored
4772            in the main HvARRAY(), and hfreentries assumes that no-one
4773            reallocates HvARRAY() while it is running.  */
4774     }
4775     if (!av) {
4776         const MAGIC *const mg
4777             = SvMAGICAL(tsv) ? mg_find(tsv, PERL_MAGIC_backref) : NULL;
4778         if (mg)
4779             av = (AV *)mg->mg_obj;
4780     }
4781     if (!av) {
4782         if (PL_in_clean_all)
4783             return;
4784         Perl_croak(aTHX_ "panic: del_backref");
4785     }
4786
4787     if (SvIS_FREED(av))
4788         return;
4789
4790     svp = AvARRAY(av);
4791     /* We shouldn't be in here more than once, but for paranoia reasons lets
4792        not assume this.  */
4793     for (i = AvFILLp(av); i >= 0; i--) {
4794         if (svp[i] == sv) {
4795             const SSize_t fill = AvFILLp(av);
4796             if (i != fill) {
4797                 /* We weren't the last entry.
4798                    An unordered list has this property that you can take the
4799                    last element off the end to fill the hole, and it's still
4800                    an unordered list :-)
4801                 */
4802                 svp[i] = svp[fill];
4803             }
4804             svp[fill] = NULL;
4805             AvFILLp(av) = fill - 1;
4806         }
4807     }
4808 }
4809
4810 int
4811 Perl_sv_kill_backrefs(pTHX_ SV *sv, AV *av)
4812 {
4813     SV **svp = AvARRAY(av);
4814
4815     PERL_UNUSED_ARG(sv);
4816
4817     /* Not sure why the av can get freed ahead of its sv, but somehow it does
4818        in ext/B/t/bytecode.t test 15 (involving print <DATA>)  */
4819     if (svp && !SvIS_FREED(av)) {
4820         SV *const *const last = svp + AvFILLp(av);
4821
4822         while (svp <= last) {
4823             if (*svp) {
4824                 SV *const referrer = *svp;
4825                 if (SvWEAKREF(referrer)) {
4826                     /* XXX Should we check that it hasn't changed? */
4827                     SvRV_set(referrer, 0);
4828                     SvOK_off(referrer);
4829                     SvWEAKREF_off(referrer);
4830                     SvSETMAGIC(referrer);
4831                 } else if (SvTYPE(referrer) == SVt_PVGV ||
4832                            SvTYPE(referrer) == SVt_PVLV) {
4833                     /* You lookin' at me?  */
4834                     assert(GvSTASH(referrer));
4835                     assert(GvSTASH(referrer) == (HV*)sv);
4836                     GvSTASH(referrer) = 0;
4837                 } else {
4838                     Perl_croak(aTHX_
4839                                "panic: magic_killbackrefs (flags=%"UVxf")",
4840                                (UV)SvFLAGS(referrer));
4841                 }
4842
4843                 *svp = NULL;
4844             }
4845             svp++;
4846         }
4847     }
4848     SvREFCNT_dec(av); /* remove extra count added by sv_add_backref() */
4849     return 0;
4850 }
4851
4852 /*
4853 =for apidoc sv_insert
4854
4855 Inserts a string at the specified offset/length within the SV. Similar to
4856 the Perl substr() function.
4857
4858 =cut
4859 */
4860
4861 void
4862 Perl_sv_insert(pTHX_ SV *bigstr, STRLEN offset, STRLEN len, const char *little, STRLEN littlelen)
4863 {
4864     dVAR;
4865     register char *big;
4866     register char *mid;
4867     register char *midend;
4868     register char *bigend;
4869     register I32 i;
4870     STRLEN curlen;
4871
4872
4873     if (!bigstr)
4874         Perl_croak(aTHX_ "Can't modify non-existent substring");
4875     SvPV_force(bigstr, curlen);
4876     (void)SvPOK_only_UTF8(bigstr);
4877     if (offset + len > curlen) {
4878         SvGROW(bigstr, offset+len+1);
4879         Zero(SvPVX(bigstr)+curlen, offset+len-curlen, char);
4880         SvCUR_set(bigstr, offset+len);
4881     }
4882
4883     SvTAINT(bigstr);
4884     i = littlelen - len;
4885     if (i > 0) {                        /* string might grow */
4886         big = SvGROW(bigstr, SvCUR(bigstr) + i + 1);
4887         mid = big + offset + len;
4888         midend = bigend = big + SvCUR(bigstr);
4889         bigend += i;
4890         *bigend = '\0';
4891         while (midend > mid)            /* shove everything down */
4892             *--bigend = *--midend;
4893         Move(little,big+offset,littlelen,char);
4894         SvCUR_set(bigstr, SvCUR(bigstr) + i);
4895         SvSETMAGIC(bigstr);
4896         return;
4897     }
4898     else if (i == 0) {
4899         Move(little,SvPVX(bigstr)+offset,len,char);
4900         SvSETMAGIC(bigstr);
4901         return;
4902     }
4903
4904     big = SvPVX(bigstr);
4905     mid = big + offset;
4906     midend = mid + len;
4907     bigend = big + SvCUR(bigstr);
4908
4909     if (midend > bigend)
4910         Perl_croak(aTHX_ "panic: sv_insert");
4911
4912     if (mid - big > bigend - midend) {  /* faster to shorten from end */
4913         if (littlelen) {
4914             Move(little, mid, littlelen,char);
4915             mid += littlelen;
4916         }
4917         i = bigend - midend;
4918         if (i > 0) {
4919             Move(midend, mid, i,char);
4920             mid += i;
4921         }
4922         *mid = '\0';
4923         SvCUR_set(bigstr, mid - big);
4924     }
4925     else if ((i = mid - big)) { /* faster from front */
4926         midend -= littlelen;
4927         mid = midend;
4928         sv_chop(bigstr,midend-i);
4929         big += i;
4930         while (i--)
4931             *--midend = *--big;
4932         if (littlelen)
4933             Move(little, mid, littlelen,char);
4934     }
4935     else if (littlelen) {
4936         midend -= littlelen;
4937         sv_chop(bigstr,midend);
4938         Move(little,midend,littlelen,char);
4939     }
4940     else {
4941         sv_chop(bigstr,midend);
4942     }
4943     SvSETMAGIC(bigstr);
4944 }
4945
4946 /*
4947 =for apidoc sv_replace
4948
4949 Make the first argument a copy of the second, then delete the original.
4950 The target SV physically takes over ownership of the body of the source SV
4951 and inherits its flags; however, the target keeps any magic it owns,
4952 and any magic in the source is discarded.
4953 Note that this is a rather specialist SV copying operation; most of the
4954 time you'll want to use C<sv_setsv> or one of its many macro front-ends.
4955
4956 =cut
4957 */
4958
4959 void
4960 Perl_sv_replace(pTHX_ register SV *sv, register SV *nsv)
4961 {
4962     dVAR;
4963     const U32 refcnt = SvREFCNT(sv);
4964     SV_CHECK_THINKFIRST_COW_DROP(sv);
4965     if (SvREFCNT(nsv) != 1) {
4966         Perl_croak(aTHX_ "panic: reference miscount on nsv in sv_replace() (%"
4967                    UVuf " != 1)", (UV) SvREFCNT(nsv));
4968     }
4969     if (SvMAGICAL(sv)) {
4970         if (SvMAGICAL(nsv))
4971             mg_free(nsv);
4972         else
4973             sv_upgrade(nsv, SVt_PVMG);
4974         SvMAGIC_set(nsv, SvMAGIC(sv));
4975         SvFLAGS(nsv) |= SvMAGICAL(sv);
4976         SvMAGICAL_off(sv);
4977         SvMAGIC_set(sv, NULL);
4978     }
4979     SvREFCNT(sv) = 0;
4980     sv_clear(sv);
4981     assert(!SvREFCNT(sv));
4982 #ifdef DEBUG_LEAKING_SCALARS
4983     sv->sv_flags  = nsv->sv_flags;
4984     sv->sv_any    = nsv->sv_any;
4985     sv->sv_refcnt = nsv->sv_refcnt;
4986     sv->sv_u      = nsv->sv_u;
4987 #else
4988     StructCopy(nsv,sv,SV);
4989 #endif
4990     /* Currently could join these into one piece of pointer arithmetic, but
4991        it would be unclear.  */
4992     if(SvTYPE(sv) == SVt_IV)
4993         SvANY(sv)
4994             = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
4995     else if (SvTYPE(sv) == SVt_RV) {
4996         SvANY(sv) = &sv->sv_u.svu_rv;
4997     }
4998         
4999
5000 #ifdef PERL_OLD_COPY_ON_WRITE
5001     if (SvIsCOW_normal(nsv)) {
5002         /* We need to follow the pointers around the loop to make the
5003            previous SV point to sv, rather than nsv.  */
5004         SV *next;
5005         SV *current = nsv;
5006         while ((next = SV_COW_NEXT_SV(current)) != nsv) {
5007             assert(next);
5008             current = next;
5009             assert(SvPVX_const(current) == SvPVX_const(nsv));
5010         }
5011         /* Make the SV before us point to the SV after us.  */
5012         if (DEBUG_C_TEST) {
5013             PerlIO_printf(Perl_debug_log, "previous is\n");
5014             sv_dump(current);
5015             PerlIO_printf(Perl_debug_log,
5016                           "move it from 0x%"UVxf" to 0x%"UVxf"\n",
5017                           (UV) SV_COW_NEXT_SV(current), (UV) sv);
5018         }
5019         SV_COW_NEXT_SV_SET(current, sv);
5020     }
5021 #endif
5022     SvREFCNT(sv) = refcnt;
5023     SvFLAGS(nsv) |= SVTYPEMASK;         /* Mark as freed */
5024     SvREFCNT(nsv) = 0;
5025     del_SV(nsv);
5026 }
5027
5028 /*
5029 =for apidoc sv_clear
5030
5031 Clear an SV: call any destructors, free up any memory used by the body,
5032 and free the body itself. The SV's head is I<not> freed, although
5033 its type is set to all 1's so that it won't inadvertently be assumed
5034 to be live during global destruction etc.
5035 This function should only be called when REFCNT is zero. Most of the time
5036 you'll want to call C<sv_free()> (or its macro wrapper C<SvREFCNT_dec>)
5037 instead.
5038
5039 =cut
5040 */
5041
5042 void
5043 Perl_sv_clear(pTHX_ register SV *sv)
5044 {
5045     dVAR;
5046     const U32 type = SvTYPE(sv);
5047     const struct body_details *const sv_type_details
5048         = bodies_by_type + type;
5049
5050     assert(sv);
5051     assert(SvREFCNT(sv) == 0);
5052
5053     if (type <= SVt_IV) {
5054         /* See the comment in sv.h about the collusion between this early
5055            return and the overloading of the NULL and IV slots in the size
5056            table.  */
5057         return;
5058     }
5059
5060     if (SvOBJECT(sv)) {
5061         if (PL_defstash) {              /* Still have a symbol table? */
5062             dSP;
5063             HV* stash;
5064             do {        
5065                 CV* destructor;
5066                 stash = SvSTASH(sv);
5067                 destructor = StashHANDLER(stash,DESTROY);
5068                 if (destructor) {
5069                     SV* const tmpref = newRV(sv);
5070                     SvREADONLY_on(tmpref);   /* DESTROY() could be naughty */
5071                     ENTER;
5072                     PUSHSTACKi(PERLSI_DESTROY);
5073                     EXTEND(SP, 2);
5074                     PUSHMARK(SP);
5075                     PUSHs(tmpref);
5076                     PUTBACK;
5077                     call_sv((SV*)destructor, G_DISCARD|G_EVAL|G_KEEPERR|G_VOID);
5078                 
5079                 
5080                     POPSTACK;
5081                     SPAGAIN;
5082                     LEAVE;
5083                     if(SvREFCNT(tmpref) < 2) {
5084                         /* tmpref is not kept alive! */
5085                         SvREFCNT(sv)--;
5086                         SvRV_set(tmpref, NULL);
5087                         SvROK_off(tmpref);
5088                     }
5089                     SvREFCNT_dec(tmpref);
5090                 }
5091             } while (SvOBJECT(sv) && SvSTASH(sv) != stash);
5092
5093
5094             if (SvREFCNT(sv)) {
5095                 if (PL_in_clean_objs)
5096                     Perl_croak(aTHX_ "DESTROY created new reference to dead object '%s'",
5097                           HvNAME_get(stash));
5098                 /* DESTROY gave object new lease on life */
5099                 return;
5100             }
5101         }
5102
5103         if (SvOBJECT(sv)) {
5104             SvREFCNT_dec(SvSTASH(sv));  /* possibly of changed persuasion */
5105             SvOBJECT_off(sv);   /* Curse the object. */
5106             if (type != SVt_PVIO)
5107                 --PL_sv_objcount;       /* XXX Might want something more general */
5108         }
5109     }
5110     if (type >= SVt_PVMG) {
5111         if (type == SVt_PVMG && SvPAD_OUR(sv)) {
5112             SvREFCNT_dec(OURSTASH(sv));
5113         } else if (SvMAGIC(sv))
5114             mg_free(sv);
5115         if (type == SVt_PVMG && SvPAD_TYPED(sv))
5116             SvREFCNT_dec(SvSTASH(sv));
5117     }
5118     switch (type) {
5119         /* case SVt_BIND: */
5120     case SVt_PVIO:
5121         if (IoIFP(sv) &&
5122             IoIFP(sv) != PerlIO_stdin() &&
5123             IoIFP(sv) != PerlIO_stdout() &&
5124             IoIFP(sv) != PerlIO_stderr())
5125         {
5126             io_close((IO*)sv, FALSE);
5127         }
5128         if (IoDIRP(sv) && !(IoFLAGS(sv) & IOf_FAKE_DIRP))
5129             PerlDir_close(IoDIRP(sv));
5130         IoDIRP(sv) = (DIR*)NULL;
5131         Safefree(IoTOP_NAME(sv));
5132         Safefree(IoFMT_NAME(sv));
5133         Safefree(IoBOTTOM_NAME(sv));
5134         goto freescalar;
5135     case SVt_PVCV:
5136     case SVt_PVFM:
5137         cv_undef((CV*)sv);
5138         goto freescalar;
5139     case SVt_PVHV:
5140         Perl_hv_kill_backrefs(aTHX_ (HV*)sv);
5141         hv_undef((HV*)sv);
5142         break;
5143     case SVt_PVAV:
5144         av_undef((AV*)sv);
5145         break;
5146     case SVt_PVLV:
5147         if (LvTYPE(sv) == 'T') { /* for tie: return HE to pool */
5148             SvREFCNT_dec(HeKEY_sv((HE*)LvTARG(sv)));
5149             HeNEXT((HE*)LvTARG(sv)) = PL_hv_fetch_ent_mh;
5150             PL_hv_fetch_ent_mh = (HE*)LvTARG(sv);
5151         }
5152         else if (LvTYPE(sv) != 't') /* unless tie: unrefcnted fake SV**  */
5153             SvREFCNT_dec(LvTARG(sv));
5154         goto freescalar;
5155     case SVt_PVGV:
5156         if (isGV_with_GP(sv)) {
5157             gp_free((GV*)sv);
5158             if (GvNAME_HEK(sv))
5159                 unshare_hek(GvNAME_HEK(sv));
5160         /* If we're in a stash, we don't own a reference to it. However it does
5161            have a back reference to us, which needs to be cleared.  */
5162         if (!SvVALID(sv) && GvSTASH(sv))
5163                 sv_del_backref((SV*)GvSTASH(sv), sv);
5164         }
5165     case SVt_PVMG:
5166     case SVt_PVNV:
5167     case SVt_PVIV:
5168       freescalar:
5169         /* Don't bother with SvOOK_off(sv); as we're only going to free it.  */
5170         if (SvOOK(sv)) {
5171             SvPV_set(sv, SvPVX_mutable(sv) - SvIVX(sv));
5172             /* Don't even bother with turning off the OOK flag.  */
5173         }
5174     case SVt_PV:
5175     case SVt_RV:
5176         if (SvROK(sv)) {
5177             SV * const target = SvRV(sv);
5178             if (SvWEAKREF(sv))
5179                 sv_del_backref(target, sv);
5180             else
5181                 SvREFCNT_dec(target);
5182         }
5183 #ifdef PERL_OLD_COPY_ON_WRITE
5184         else if (SvPVX_const(sv)) {
5185             if (SvIsCOW(sv)) {
5186                 /* I believe I need to grab the global SV mutex here and
5187                    then recheck the COW status.  */
5188                 if (DEBUG_C_TEST) {
5189                     PerlIO_printf(Perl_debug_log, "Copy on write: clear\n");
5190                     sv_dump(sv);
5191                 }
5192                 sv_release_COW(sv, SvPVX_const(sv), SvLEN(sv),
5193                                SV_COW_NEXT_SV(sv));
5194                 /* And drop it here.  */
5195                 SvFAKE_off(sv);
5196             } else if (SvLEN(sv)) {
5197                 Safefree(SvPVX_const(sv));
5198             }
5199         }
5200 #else
5201         else if (SvPVX_const(sv) && SvLEN(sv))
5202             Safefree(SvPVX_mutable(sv));
5203         else if (SvPVX_const(sv) && SvREADONLY(sv) && SvFAKE(sv)) {
5204             unshare_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sv)));
5205             SvFAKE_off(sv);
5206         }
5207 #endif
5208         break;
5209     case SVt_NV:
5210         break;
5211     }
5212
5213     SvFLAGS(sv) &= SVf_BREAK;
5214     SvFLAGS(sv) |= SVTYPEMASK;
5215
5216     if (sv_type_details->arena) {
5217         del_body(((char *)SvANY(sv) + sv_type_details->offset),
5218                  &PL_body_roots[type]);
5219     }
5220     else if (sv_type_details->body_size) {
5221         my_safefree(SvANY(sv));
5222     }
5223 }
5224
5225 /*
5226 =for apidoc sv_newref
5227
5228 Increment an SV's reference count. Use the C<SvREFCNT_inc()> wrapper
5229 instead.
5230
5231 =cut
5232 */
5233
5234 SV *
5235 Perl_sv_newref(pTHX_ SV *sv)
5236 {
5237     PERL_UNUSED_CONTEXT;
5238     if (sv)
5239         (SvREFCNT(sv))++;
5240     return sv;
5241 }
5242
5243 /*
5244 =for apidoc sv_free
5245
5246 Decrement an SV's reference count, and if it drops to zero, call
5247 C<sv_clear> to invoke destructors and free up any memory used by
5248 the body; finally, deallocate the SV's head itself.
5249 Normally called via a wrapper macro C<SvREFCNT_dec>.
5250
5251 =cut
5252 */
5253
5254 void
5255 Perl_sv_free(pTHX_ SV *sv)
5256 {
5257     dVAR;
5258     if (!sv)
5259         return;
5260     if (SvREFCNT(sv) == 0) {
5261         if (SvFLAGS(sv) & SVf_BREAK)
5262             /* this SV's refcnt has been artificially decremented to
5263              * trigger cleanup */
5264             return;
5265         if (PL_in_clean_all) /* All is fair */
5266             return;
5267         if (SvREADONLY(sv) && SvIMMORTAL(sv)) {
5268             /* make sure SvREFCNT(sv)==0 happens very seldom */
5269             SvREFCNT(sv) = (~(U32)0)/2;
5270             return;
5271         }
5272         if (ckWARN_d(WARN_INTERNAL)) {
5273             Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
5274                         "Attempt to free unreferenced scalar: SV 0x%"UVxf
5275                         pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
5276 #ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
5277             Perl_dump_sv_child(aTHX_ sv);
5278 #endif
5279         }
5280         return;
5281     }
5282     if (--(SvREFCNT(sv)) > 0)
5283         return;
5284     Perl_sv_free2(aTHX_ sv);
5285 }
5286
5287 void
5288 Perl_sv_free2(pTHX_ SV *sv)
5289 {
5290     dVAR;
5291 #ifdef DEBUGGING
5292     if (SvTEMP(sv)) {
5293         if (ckWARN_d(WARN_DEBUGGING))
5294             Perl_warner(aTHX_ packWARN(WARN_DEBUGGING),
5295                         "Attempt to free temp prematurely: SV 0x%"UVxf
5296                         pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
5297         return;
5298     }
5299 #endif
5300     if (SvREADONLY(sv) && SvIMMORTAL(sv)) {
5301         /* make sure SvREFCNT(sv)==0 happens very seldom */
5302         SvREFCNT(sv) = (~(U32)0)/2;
5303         return;
5304     }
5305     sv_clear(sv);
5306     if (! SvREFCNT(sv))
5307         del_SV(sv);
5308 }
5309
5310 /*
5311 =for apidoc sv_len
5312
5313 Returns the length of the string in the SV. Handles magic and type
5314 coercion.  See also C<SvCUR>, which gives raw access to the xpv_cur slot.
5315
5316 =cut
5317 */
5318
5319 STRLEN
5320 Perl_sv_len(pTHX_ register SV *sv)
5321 {
5322     STRLEN len;
5323
5324     if (!sv)
5325         return 0;
5326
5327     if (SvGMAGICAL(sv))
5328         len = mg_length(sv);
5329     else
5330         (void)SvPV_const(sv, len);
5331     return len;
5332 }
5333
5334 /*
5335 =for apidoc sv_len_utf8
5336
5337 Returns the number of characters in the string in an SV, counting wide
5338 UTF-8 bytes as a single character. Handles magic and type coercion.
5339
5340 =cut
5341 */
5342
5343 /*
5344  * The length is cached in PERL_UTF8_magic, in the mg_len field.  Also the
5345  * mg_ptr is used, by sv_pos_u2b() and sv_pos_b2u() - see the comments below.
5346  * (Note that the mg_len is not the length of the mg_ptr field.
5347  * This allows the cache to store the character length of the string without
5348  * needing to malloc() extra storage to attach to the mg_ptr.)
5349  *
5350  */
5351
5352 STRLEN
5353 Perl_sv_len_utf8(pTHX_ register SV *sv)
5354 {
5355     if (!sv)
5356         return 0;
5357
5358     if (SvGMAGICAL(sv))
5359         return mg_length(sv);
5360     else
5361     {
5362         STRLEN len;
5363         const U8 *s = (U8*)SvPV_const(sv, len);
5364
5365         if (PL_utf8cache) {
5366             STRLEN ulen;
5367             MAGIC *mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : 0;
5368
5369             if (mg && mg->mg_len != -1) {
5370                 ulen = mg->mg_len;
5371                 if (PL_utf8cache < 0) {
5372                     const STRLEN real = Perl_utf8_length(aTHX_ s, s + len);
5373                     if (real != ulen) {
5374                         /* Need to turn the assertions off otherwise we may
5375                            recurse infinitely while printing error messages.
5376                         */
5377                         SAVEI8(PL_utf8cache);
5378                         PL_utf8cache = 0;
5379                         Perl_croak(aTHX_ "panic: sv_len_utf8 cache %"UVuf
5380                                    " real %"UVuf" for %"SVf,
5381                                    (UV) ulen, (UV) real, (void*)sv);
5382                     }
5383                 }
5384             }
5385             else {
5386                 ulen = Perl_utf8_length(aTHX_ s, s + len);
5387                 if (!SvREADONLY(sv)) {
5388                     if (!mg) {
5389                         mg = sv_magicext(sv, 0, PERL_MAGIC_utf8,
5390                                          &PL_vtbl_utf8, 0, 0);
5391                     }
5392                     assert(mg);
5393                     mg->mg_len = ulen;
5394                 }
5395             }
5396             return ulen;
5397         }
5398         return Perl_utf8_length(aTHX_ s, s + len);
5399     }
5400 }
5401
5402 /* Walk forwards to find the byte corresponding to the passed in UTF-8
5403    offset.  */
5404 static STRLEN
5405 S_sv_pos_u2b_forwards(const U8 *const start, const U8 *const send,
5406                       STRLEN uoffset)
5407 {
5408     const U8 *s = start;
5409
5410     while (s < send && uoffset--)
5411         s += UTF8SKIP(s);
5412     if (s > send) {
5413         /* This is the existing behaviour. Possibly it should be a croak, as
5414            it's actually a bounds error  */
5415         s = send;
5416     }
5417     return s - start;
5418 }
5419
5420 /* Given the length of the string in both bytes and UTF-8 characters, decide
5421    whether to walk forwards or backwards to find the byte corresponding to
5422    the passed in UTF-8 offset.  */
5423 static STRLEN
5424 S_sv_pos_u2b_midway(const U8 *const start, const U8 *send,
5425                       STRLEN uoffset, STRLEN uend)
5426 {
5427     STRLEN backw = uend - uoffset;
5428     if (uoffset < 2 * backw) {
5429         /* The assumption is that going forwards is twice the speed of going
5430            forward (that's where the 2 * backw comes from).
5431            (The real figure of course depends on the UTF-8 data.)  */
5432         return sv_pos_u2b_forwards(start, send, uoffset);
5433     }
5434
5435     while (backw--) {
5436         send--;
5437         while (UTF8_IS_CONTINUATION(*send))
5438             send--;
5439     }
5440     return send - start;
5441 }
5442
5443 /* For the string representation of the given scalar, find the byte
5444    corresponding to the passed in UTF-8 offset.  uoffset0 and boffset0
5445    give another position in the string, *before* the sought offset, which
5446    (which is always true, as 0, 0 is a valid pair of positions), which should
5447    help reduce the amount of linear searching.
5448    If *mgp is non-NULL, it should point to the UTF-8 cache magic, which
5449    will be used to reduce the amount of linear searching. The cache will be
5450    created if necessary, and the found value offered to it for update.  */
5451 static STRLEN
5452 S_sv_pos_u2b_cached(pTHX_ SV *sv, MAGIC **mgp, const U8 *const start,
5453                     const U8 *const send, STRLEN uoffset,
5454                     STRLEN uoffset0, STRLEN boffset0) {
5455     STRLEN boffset = 0; /* Actually always set, but let's keep gcc happy.  */
5456     bool found = FALSE;
5457
5458     assert (uoffset >= uoffset0);
5459
5460     if (SvMAGICAL(sv) && !SvREADONLY(sv) && PL_utf8cache
5461         && (*mgp || (*mgp = mg_find(sv, PERL_MAGIC_utf8)))) {
5462         if ((*mgp)->mg_ptr) {
5463             STRLEN *cache = (STRLEN *) (*mgp)->mg_ptr;
5464             if (cache[0] == uoffset) {
5465                 /* An exact match. */
5466                 return cache[1];
5467             }
5468             if (cache[2] == uoffset) {
5469                 /* An exact match. */
5470                 return cache[3];
5471             }
5472
5473             if (cache[0] < uoffset) {
5474                 /* The cache already knows part of the way.   */
5475                 if (cache[0] > uoffset0) {
5476                     /* The cache knows more than the passed in pair  */
5477                     uoffset0 = cache[0];
5478                     boffset0 = cache[1];
5479                 }
5480                 if ((*mgp)->mg_len != -1) {
5481                     /* And we know the end too.  */
5482                     boffset = boffset0
5483                         + sv_pos_u2b_midway(start + boffset0, send,
5484                                               uoffset - uoffset0,
5485                                               (*mgp)->mg_len - uoffset0);
5486                 } else {
5487                     boffset = boffset0
5488                         + sv_pos_u2b_forwards(start + boffset0,
5489                                                 send, uoffset - uoffset0);
5490                 }
5491             }
5492             else if (cache[2] < uoffset) {
5493                 /* We're between the two cache entries.  */
5494                 if (cache[2] > uoffset0) {
5495                     /* and the cache knows more than the passed in pair  */
5496                     uoffset0 = cache[2];
5497                     boffset0 = cache[3];
5498                 }
5499
5500                 boffset = boffset0
5501                     + sv_pos_u2b_midway(start + boffset0,
5502                                           start + cache[1],
5503                                           uoffset - uoffset0,
5504                                           cache[0] - uoffset0);
5505             } else {
5506                 boffset = boffset0
5507                     + sv_pos_u2b_midway(start + boffset0,
5508                                           start + cache[3],
5509                                           uoffset - uoffset0,
5510                                           cache[2] - uoffset0);
5511             }
5512             found = TRUE;
5513         }
5514         else if ((*mgp)->mg_len != -1) {
5515             /* If we can take advantage of a passed in offset, do so.  */
5516             /* In fact, offset0 is either 0, or less than offset, so don't
5517                need to worry about the other possibility.  */
5518             boffset = boffset0
5519                 + sv_pos_u2b_midway(start + boffset0, send,
5520                                       uoffset - uoffset0,
5521                                       (*mgp)->mg_len - uoffset0);
5522             found = TRUE;
5523         }
5524     }
5525
5526     if (!found || PL_utf8cache < 0) {
5527         const STRLEN real_boffset
5528             = boffset0 + sv_pos_u2b_forwards(start + boffset0,
5529                                                send, uoffset - uoffset0);
5530
5531         if (found && PL_utf8cache < 0) {
5532             if (real_boffset != boffset) {
5533                 /* Need to turn the assertions off otherwise we may recurse
5534                    infinitely while printing error messages.  */
5535                 SAVEI8(PL_utf8cache);
5536                 PL_utf8cache = 0;
5537                 Perl_croak(aTHX_ "panic: sv_pos_u2b_cache cache %"UVuf
5538                            " real %"UVuf" for %"SVf,
5539                            (UV) boffset, (UV) real_boffset, (void*)sv);
5540             }
5541         }
5542         boffset = real_boffset;
5543     }
5544
5545     S_utf8_mg_pos_cache_update(aTHX_ sv, mgp, boffset, uoffset, send - start);
5546     return boffset;
5547 }
5548
5549
5550 /*
5551 =for apidoc sv_pos_u2b
5552
5553 Converts the value pointed to by offsetp from a count of UTF-8 chars from
5554 the start of the string, to a count of the equivalent number of bytes; if
5555 lenp is non-zero, it does the same to lenp, but this time starting from
5556 the offset, rather than from the start of the string. Handles magic and
5557 type coercion.
5558
5559 =cut
5560 */
5561
5562 /*
5563  * sv_pos_u2b() uses, like sv_pos_b2u(), the mg_ptr of the potential
5564  * PERL_UTF8_magic of the sv to store the mapping between UTF-8 and
5565  * byte offsets.  See also the comments of S_utf8_mg_pos_cache_update().
5566  *
5567  */
5568
5569 void
5570 Perl_sv_pos_u2b(pTHX_ register SV *sv, I32* offsetp, I32* lenp)
5571 {
5572     const U8 *start;
5573     STRLEN len;
5574
5575     if (!sv)
5576         return;
5577
5578     start = (U8*)SvPV_const(sv, len);
5579     if (len) {
5580         STRLEN uoffset = (STRLEN) *offsetp;
5581         const U8 * const send = start + len;
5582         MAGIC *mg = NULL;
5583         const STRLEN boffset = sv_pos_u2b_cached(sv, &mg, start, send,
5584                                              uoffset, 0, 0);
5585
5586         *offsetp = (I32) boffset;
5587
5588         if (lenp) {
5589             /* Convert the relative offset to absolute.  */
5590             const STRLEN uoffset2 = uoffset + (STRLEN) *lenp;
5591             const STRLEN boffset2
5592                 = sv_pos_u2b_cached(sv, &mg, start, send, uoffset2,
5593                                       uoffset, boffset) - boffset;
5594
5595             *lenp = boffset2;
5596         }
5597     }
5598     else {
5599          *offsetp = 0;
5600          if (lenp)
5601               *lenp = 0;
5602     }
5603
5604     return;
5605 }
5606
5607 /* Create and update the UTF8 magic offset cache, with the proffered utf8/
5608    byte length pairing. The (byte) length of the total SV is passed in too,
5609    as blen, because for some (more esoteric) SVs, the call to SvPV_const()
5610    may not have updated SvCUR, so we can't rely on reading it directly.
5611
5612    The proffered utf8/byte length pairing isn't used if the cache already has
5613    two pairs, and swapping either for the proffered pair would increase the
5614    RMS of the intervals between known byte offsets.
5615
5616    The cache itself consists of 4 STRLEN values
5617    0: larger UTF-8 offset
5618    1: corresponding byte offset
5619    2: smaller UTF-8 offset
5620    3: corresponding byte offset
5621
5622    Unused cache pairs have the value 0, 0.
5623    Keeping the cache "backwards" means that the invariant of
5624    cache[0] >= cache[2] is maintained even with empty slots, which means that
5625    the code that uses it doesn't need to worry if only 1 entry has actually
5626    been set to non-zero.  It also makes the "position beyond the end of the
5627    cache" logic much simpler, as the first slot is always the one to start
5628    from.   
5629 */
5630 static void
5631 S_utf8_mg_pos_cache_update(pTHX_ SV *sv, MAGIC **mgp, STRLEN byte, STRLEN utf8,
5632                            STRLEN blen)
5633 {
5634     STRLEN *cache;
5635     if (SvREADONLY(sv))
5636         return;
5637
5638     if (!*mgp) {
5639         *mgp = sv_magicext(sv, 0, PERL_MAGIC_utf8, (MGVTBL*)&PL_vtbl_utf8, 0,
5640                            0);
5641         (*mgp)->mg_len = -1;
5642     }
5643     assert(*mgp);
5644
5645     if (!(cache = (STRLEN *)(*mgp)->mg_ptr)) {
5646         Newxz(cache, PERL_MAGIC_UTF8_CACHESIZE * 2, STRLEN);
5647         (*mgp)->mg_ptr = (char *) cache;
5648     }
5649     assert(cache);
5650
5651     if (PL_utf8cache < 0) {
5652         const U8 *start = (const U8 *) SvPVX_const(sv);
5653         const STRLEN realutf8 = utf8_length(start, start + byte);
5654
5655         if (realutf8 != utf8) {
5656             /* Need to turn the assertions off otherwise we may recurse
5657                infinitely while printing error messages.  */
5658             SAVEI8(PL_utf8cache);
5659             PL_utf8cache = 0;
5660             Perl_croak(aTHX_ "panic: utf8_mg_pos_cache_update cache %"UVuf
5661                        " real %"UVuf" for %"SVf, (UV) utf8, (UV) realutf8, (void*)sv);
5662         }
5663     }
5664
5665     /* Cache is held with the later position first, to simplify the code
5666        that deals with unbounded ends.  */
5667        
5668     ASSERT_UTF8_CACHE(cache);
5669     if (cache[1] == 0) {
5670         /* Cache is totally empty  */
5671         cache[0] = utf8;
5672         cache[1] = byte;
5673     } else if (cache[3] == 0) {
5674         if (byte > cache[1]) {
5675             /* New one is larger, so goes first.  */
5676             cache[2] = cache[0];
5677             cache[3] = cache[1];
5678             cache[0] = utf8;
5679             cache[1] = byte;
5680         } else {
5681             cache[2] = utf8;
5682             cache[3] = byte;
5683         }
5684     } else {
5685 #define THREEWAY_SQUARE(a,b,c,d) \
5686             ((float)((d) - (c))) * ((float)((d) - (c))) \
5687             + ((float)((c) - (b))) * ((float)((c) - (b))) \
5688                + ((float)((b) - (a))) * ((float)((b) - (a)))
5689
5690         /* Cache has 2 slots in use, and we know three potential pairs.
5691            Keep the two that give the lowest RMS distance. Do the
5692            calcualation in bytes simply because we always know the byte
5693            length.  squareroot has the same ordering as the positive value,
5694            so don't bother with the actual square root.  */
5695         const float existing = THREEWAY_SQUARE(0, cache[3], cache[1], blen);
5696         if (byte > cache[1]) {
5697             /* New position is after the existing pair of pairs.  */
5698             const float keep_earlier
5699                 = THREEWAY_SQUARE(0, cache[3], byte, blen);
5700             const float keep_later
5701                 = THREEWAY_SQUARE(0, cache[1], byte, blen);
5702
5703             if (keep_later < keep_earlier) {
5704                 if (keep_later < existing) {
5705                     cache[2] = cache[0];
5706                     cache[3] = cache[1];
5707                     cache[0] = utf8;
5708                     cache[1] = byte;
5709                 }
5710             }
5711             else {
5712                 if (keep_earlier < existing) {
5713                     cache[0] = utf8;
5714                     cache[1] = byte;
5715                 }
5716             }
5717         }
5718         else if (byte > cache[3]) {
5719             /* New position is between the existing pair of pairs.  */
5720             const float keep_earlier
5721                 = THREEWAY_SQUARE(0, cache[3], byte, blen);
5722             const float keep_later
5723                 = THREEWAY_SQUARE(0, byte, cache[1], blen);
5724
5725             if (keep_later < keep_earlier) {
5726                 if (keep_later < existing) {
5727                     cache[2] = utf8;
5728                     cache[3] = byte;
5729                 }
5730             }
5731             else {
5732                 if (keep_earlier < existing) {
5733                     cache[0] = utf8;
5734                     cache[1] = byte;
5735                 }
5736             }
5737         }
5738         else {
5739             /* New position is before the existing pair of pairs.  */
5740             const float keep_earlier
5741                 = THREEWAY_SQUARE(0, byte, cache[3], blen);
5742             const float keep_later
5743                 = THREEWAY_SQUARE(0, byte, cache[1], blen);
5744
5745             if (keep_later < keep_earlier) {
5746                 if (keep_later < existing) {
5747                     cache[2] = utf8;
5748                     cache[3] = byte;
5749                 }
5750             }
5751             else {
5752                 if (keep_earlier < existing) {
5753                     cache[0] = cache[2];
5754                     cache[1] = cache[3];
5755                     cache[2] = utf8;
5756                     cache[3] = byte;
5757                 }
5758             }
5759         }
5760     }
5761     ASSERT_UTF8_CACHE(cache);
5762 }
5763
5764 /* We already know all of the way, now we may be able to walk back.  The same
5765    assumption is made as in S_sv_pos_u2b_midway(), namely that walking
5766    backward is half the speed of walking forward. */
5767 static STRLEN
5768 S_sv_pos_b2u_midway(pTHX_ const U8 *s, const U8 *const target, const U8 *end,
5769                     STRLEN endu)
5770 {
5771     const STRLEN forw = target - s;
5772     STRLEN backw = end - target;
5773
5774     if (forw < 2 * backw) {
5775         return utf8_length(s, target);
5776     }
5777
5778     while (end > target) {
5779         end--;
5780         while (UTF8_IS_CONTINUATION(*end)) {
5781             end--;
5782         }
5783         endu--;
5784     }
5785     return endu;
5786 }
5787
5788 /*
5789 =for apidoc sv_pos_b2u
5790
5791 Converts the value pointed to by offsetp from a count of bytes from the
5792 start of the string, to a count of the equivalent number of UTF-8 chars.
5793 Handles magic and type coercion.
5794
5795 =cut
5796 */
5797
5798 /*
5799  * sv_pos_b2u() uses, like sv_pos_u2b(), the mg_ptr of the potential
5800  * PERL_UTF8_magic of the sv to store the mapping between UTF-8 and
5801  * byte offsets.
5802  *
5803  */
5804 void
5805 Perl_sv_pos_b2u(pTHX_ register SV* sv, I32* offsetp)
5806 {
5807     const U8* s;
5808     const STRLEN byte = *offsetp;
5809     STRLEN len = 0; /* Actually always set, but let's keep gcc happy.  */
5810     STRLEN blen;
5811     MAGIC* mg = NULL;
5812     const U8* send;
5813     bool found = FALSE;
5814
5815     if (!sv)
5816         return;
5817
5818     s = (const U8*)SvPV_const(sv, blen);
5819
5820     if (blen < byte)
5821         Perl_croak(aTHX_ "panic: sv_pos_b2u: bad byte offset");
5822
5823     send = s + byte;
5824
5825     if (SvMAGICAL(sv) && !SvREADONLY(sv) && PL_utf8cache
5826         && (mg = mg_find(sv, PERL_MAGIC_utf8))) {
5827         if (mg->mg_ptr) {
5828             STRLEN * const cache = (STRLEN *) mg->mg_ptr;
5829             if (cache[1] == byte) {
5830                 /* An exact match. */
5831                 *offsetp = cache[0];
5832                 return;
5833             }
5834             if (cache[3] == byte) {
5835                 /* An exact match. */
5836                 *offsetp = cache[2];
5837                 return;
5838             }
5839
5840             if (cache[1] < byte) {
5841                 /* We already know part of the way. */
5842                 if (mg->mg_len != -1) {
5843                     /* Actually, we know the end too.  */
5844                     len = cache[0]
5845                         + S_sv_pos_b2u_midway(aTHX_ s + cache[1], send,
5846                                               s + blen, mg->mg_len - cache[0]);
5847                 } else {
5848                     len = cache[0] + utf8_length(s + cache[1], send);
5849                 }
5850             }
5851             else if (cache[3] < byte) {
5852                 /* We're between the two cached pairs, so we do the calculation
5853                    offset by the byte/utf-8 positions for the earlier pair,
5854                    then add the utf-8 characters from the string start to
5855                    there.  */
5856                 len = S_sv_pos_b2u_midway(aTHX_ s + cache[3], send,
5857                                           s + cache[1], cache[0] - cache[2])
5858                     + cache[2];
5859
5860             }
5861             else { /* cache[3] > byte */
5862                 len = S_sv_pos_b2u_midway(aTHX_ s, send, s + cache[3],
5863                                           cache[2]);
5864
5865             }
5866             ASSERT_UTF8_CACHE(cache);
5867             found = TRUE;
5868         } else if (mg->mg_len != -1) {
5869             len = S_sv_pos_b2u_midway(aTHX_ s, send, s + blen, mg->mg_len);
5870             found = TRUE;
5871         }
5872     }
5873     if (!found || PL_utf8cache < 0) {
5874         const STRLEN real_len = utf8_length(s, send);
5875
5876         if (found && PL_utf8cache < 0) {
5877             if (len != real_len) {
5878                 /* Need to turn the assertions off otherwise we may recurse
5879                    infinitely while printing error messages.  */
5880                 SAVEI8(PL_utf8cache);
5881                 PL_utf8cache = 0;
5882                 Perl_croak(aTHX_ "panic: sv_pos_b2u cache %"UVuf
5883                            " real %"UVuf" for %"SVf,
5884                            (UV) len, (UV) real_len, (void*)sv);
5885             }
5886         }
5887         len = real_len;
5888     }
5889     *offsetp = len;
5890
5891     S_utf8_mg_pos_cache_update(aTHX_ sv, &mg, byte, len, blen);
5892 }
5893
5894 /*
5895 =for apidoc sv_eq
5896
5897 Returns a boolean indicating whether the strings in the two SVs are
5898 identical. Is UTF-8 and 'use bytes' aware, handles get magic, and will
5899 coerce its args to strings if necessary.
5900
5901 =cut
5902 */
5903
5904 I32
5905 Perl_sv_eq(pTHX_ register SV *sv1, register SV *sv2)
5906 {
5907     dVAR;
5908     const char *pv1;
5909     STRLEN cur1;
5910     const char *pv2;
5911     STRLEN cur2;
5912     I32  eq     = 0;
5913     char *tpv   = NULL;
5914     SV* svrecode = NULL;
5915
5916     if (!sv1) {
5917         pv1 = "";
5918         cur1 = 0;
5919     }
5920     else {
5921         /* if pv1 and pv2 are the same, second SvPV_const call may
5922          * invalidate pv1, so we may need to make a copy */
5923         if (sv1 == sv2 && (SvTHINKFIRST(sv1) || SvGMAGICAL(sv1))) {
5924             pv1 = SvPV_const(sv1, cur1);
5925             sv1 = sv_2mortal(newSVpvn(pv1, cur1));
5926             if (SvUTF8(sv2)) SvUTF8_on(sv1);
5927         }
5928         pv1 = SvPV_const(sv1, cur1);
5929     }
5930
5931     if (!sv2){
5932         pv2 = "";
5933         cur2 = 0;
5934     }
5935     else
5936         pv2 = SvPV_const(sv2, cur2);
5937
5938     if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
5939         /* Differing utf8ness.
5940          * Do not UTF8size the comparands as a side-effect. */
5941          if (PL_encoding) {
5942               if (SvUTF8(sv1)) {
5943                    svrecode = newSVpvn(pv2, cur2);
5944                    sv_recode_to_utf8(svrecode, PL_encoding);
5945                    pv2 = SvPV_const(svrecode, cur2);
5946               }
5947               else {
5948                    svrecode = newSVpvn(pv1, cur1);
5949                    sv_recode_to_utf8(svrecode, PL_encoding);
5950                    pv1 = SvPV_const(svrecode, cur1);
5951               }
5952               /* Now both are in UTF-8. */
5953               if (cur1 != cur2) {
5954                    SvREFCNT_dec(svrecode);
5955                    return FALSE;
5956               }
5957          }
5958          else {
5959               bool is_utf8 = TRUE;
5960
5961               if (SvUTF8(sv1)) {
5962                    /* sv1 is the UTF-8 one,
5963                     * if is equal it must be downgrade-able */
5964                    char * const pv = (char*)bytes_from_utf8((const U8*)pv1,
5965                                                      &cur1, &is_utf8);
5966                    if (pv != pv1)
5967                         pv1 = tpv = pv;
5968               }
5969               else {
5970                    /* sv2 is the UTF-8 one,
5971                     * if is equal it must be downgrade-able */
5972                    char * const pv = (char *)bytes_from_utf8((const U8*)pv2,
5973                                                       &cur2, &is_utf8);
5974                    if (pv != pv2)
5975                         pv2 = tpv = pv;
5976               }
5977               if (is_utf8) {
5978                    /* Downgrade not possible - cannot be eq */
5979                    assert (tpv == 0);
5980                    return FALSE;
5981               }
5982          }
5983     }
5984
5985     if (cur1 == cur2)
5986         eq = (pv1 == pv2) || memEQ(pv1, pv2, cur1);
5987         
5988     SvREFCNT_dec(svrecode);
5989     if (tpv)
5990         Safefree(tpv);
5991
5992     return eq;
5993 }
5994
5995 /*
5996 =for apidoc sv_cmp
5997
5998 Compares the strings in two SVs.  Returns -1, 0, or 1 indicating whether the
5999 string in C<sv1> is less than, equal to, or greater than the string in
6000 C<sv2>. Is UTF-8 and 'use bytes' aware, handles get magic, and will
6001 coerce its args to strings if necessary.  See also C<sv_cmp_locale>.
6002
6003 =cut
6004 */
6005
6006 I32
6007 Perl_sv_cmp(pTHX_ register SV *sv1, register SV *sv2)
6008 {
6009     dVAR;
6010     STRLEN cur1, cur2;
6011     const char *pv1, *pv2;
6012     char *tpv = NULL;
6013     I32  cmp;
6014     SV *svrecode = NULL;
6015
6016     if (!sv1) {
6017         pv1 = "";
6018         cur1 = 0;
6019     }
6020     else
6021         pv1 = SvPV_const(sv1, cur1);
6022
6023     if (!sv2) {
6024         pv2 = "";
6025         cur2 = 0;
6026     }
6027     else
6028         pv2 = SvPV_const(sv2, cur2);
6029
6030     if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
6031         /* Differing utf8ness.
6032          * Do not UTF8size the comparands as a side-effect. */
6033         if (SvUTF8(sv1)) {
6034             if (PL_encoding) {
6035                  svrecode = newSVpvn(pv2, cur2);
6036                  sv_recode_to_utf8(svrecode, PL_encoding);
6037                  pv2 = SvPV_const(svrecode, cur2);
6038             }
6039             else {
6040                  pv2 = tpv = (char*)bytes_to_utf8((const U8*)pv2, &cur2);
6041             }
6042         }
6043         else {
6044             if (PL_encoding) {
6045                  svrecode = newSVpvn(pv1, cur1);
6046                  sv_recode_to_utf8(svrecode, PL_encoding);
6047                  pv1 = SvPV_const(svrecode, cur1);
6048             }
6049             else {
6050                  pv1 = tpv = (char*)bytes_to_utf8((const U8*)pv1, &cur1);
6051             }
6052         }
6053     }
6054
6055     if (!cur1) {
6056         cmp = cur2 ? -1 : 0;
6057     } else if (!cur2) {
6058         cmp = 1;
6059     } else {
6060         const I32 retval = memcmp((const void*)pv1, (const void*)pv2, cur1 < cur2 ? cur1 : cur2);
6061
6062         if (retval) {
6063             cmp = retval < 0 ? -1 : 1;
6064         } else if (cur1 == cur2) {
6065             cmp = 0;
6066         } else {
6067             cmp = cur1 < cur2 ? -1 : 1;
6068         }
6069     }
6070
6071     SvREFCNT_dec(svrecode);
6072     if (tpv)
6073         Safefree(tpv);
6074
6075     return cmp;
6076 }
6077
6078 /*
6079 =for apidoc sv_cmp_locale
6080
6081 Compares the strings in two SVs in a locale-aware manner. Is UTF-8 and
6082 'use bytes' aware, handles get magic, and will coerce its args to strings
6083 if necessary.  See also C<sv_cmp_locale>.  See also C<sv_cmp>.
6084
6085 =cut
6086 */
6087
6088 I32
6089 Perl_sv_cmp_locale(pTHX_ register SV *sv1, register SV *sv2)
6090 {
6091     dVAR;
6092 #ifdef USE_LOCALE_COLLATE
6093
6094     char *pv1, *pv2;
6095     STRLEN len1, len2;
6096     I32 retval;
6097
6098     if (PL_collation_standard)
6099         goto raw_compare;
6100
6101     len1 = 0;
6102     pv1 = sv1 ? sv_collxfrm(sv1, &len1) : (char *) NULL;
6103     len2 = 0;
6104     pv2 = sv2 ? sv_collxfrm(sv2, &len2) : (char *) NULL;
6105
6106     if (!pv1 || !len1) {
6107         if (pv2 && len2)
6108             return -1;
6109         else
6110             goto raw_compare;
6111     }
6112     else {
6113         if (!pv2 || !len2)
6114             return 1;
6115     }
6116
6117     retval = memcmp((void*)pv1, (void*)pv2, len1 < len2 ? len1 : len2);
6118
6119     if (retval)
6120         return retval < 0 ? -1 : 1;
6121
6122     /*
6123      * When the result of collation is equality, that doesn't mean
6124      * that there are no differences -- some locales exclude some
6125      * characters from consideration.  So to avoid false equalities,
6126      * we use the raw string as a tiebreaker.
6127      */
6128
6129   raw_compare:
6130     /*FALLTHROUGH*/
6131
6132 #endif /* USE_LOCALE_COLLATE */
6133
6134     return sv_cmp(sv1, sv2);
6135 }
6136
6137
6138 #ifdef USE_LOCALE_COLLATE
6139
6140 /*
6141 =for apidoc sv_collxfrm
6142
6143 Add Collate Transform magic to an SV if it doesn't already have it.
6144
6145 Any scalar variable may carry PERL_MAGIC_collxfrm magic that contains the
6146 scalar data of the variable, but transformed to such a format that a normal
6147 memory comparison can be used to compare the data according to the locale
6148 settings.
6149
6150 =cut
6151 */
6152
6153 char *
6154 Perl_sv_collxfrm(pTHX_ SV *sv, STRLEN *nxp)
6155 {
6156     dVAR;
6157     MAGIC *mg;
6158
6159     mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_collxfrm) : (MAGIC *) NULL;
6160     if (!mg || !mg->mg_ptr || *(U32*)mg->mg_ptr != PL_collation_ix) {
6161         const char *s;
6162         char *xf;
6163         STRLEN len, xlen;
6164
6165         if (mg)
6166             Safefree(mg->mg_ptr);
6167         s = SvPV_const(sv, len);
6168         if ((xf = mem_collxfrm(s, len, &xlen))) {
6169             if (SvREADONLY(sv)) {
6170                 SAVEFREEPV(xf);
6171                 *nxp = xlen;
6172                 return xf + sizeof(PL_collation_ix);
6173             }
6174             if (! mg) {
6175 #ifdef PERL_OLD_COPY_ON_WRITE
6176                 if (SvIsCOW(sv))
6177                     sv_force_normal_flags(sv, 0);
6178 #endif
6179                 mg = sv_magicext(sv, 0, PERL_MAGIC_collxfrm, &PL_vtbl_collxfrm,
6180                                  0, 0);
6181                 assert(mg);
6182             }
6183             mg->mg_ptr = xf;
6184             mg->mg_len = xlen;
6185         }
6186         else {
6187             if (mg) {
6188                 mg->mg_ptr = NULL;
6189                 mg->mg_len = -1;
6190             }
6191         }
6192     }
6193     if (mg && mg->mg_ptr) {
6194         *nxp = mg->mg_len;
6195         return mg->mg_ptr + sizeof(PL_collation_ix);
6196     }
6197     else {
6198         *nxp = 0;
6199         return NULL;
6200     }
6201 }
6202
6203 #endif /* USE_LOCALE_COLLATE */
6204
6205 /*
6206 =for apidoc sv_gets
6207
6208 Get a line from the filehandle and store it into the SV, optionally
6209 appending to the currently-stored string.
6210
6211 =cut
6212 */
6213
6214 char *
6215 Perl_sv_gets(pTHX_ register SV *sv, register PerlIO *fp, I32 append)
6216 {
6217     dVAR;
6218     const char *rsptr;
6219     STRLEN rslen;
6220     register STDCHAR rslast;
6221     register STDCHAR *bp;
6222     register I32 cnt;
6223     I32 i = 0;
6224     I32 rspara = 0;
6225
6226     if (SvTHINKFIRST(sv))
6227         sv_force_normal_flags(sv, append ? 0 : SV_COW_DROP_PV);
6228     /* XXX. If you make this PVIV, then copy on write can copy scalars read
6229        from <>.
6230        However, perlbench says it's slower, because the existing swipe code
6231        is faster than copy on write.
6232        Swings and roundabouts.  */
6233     SvUPGRADE(sv, SVt_PV);
6234
6235     SvSCREAM_off(sv);
6236
6237     if (append) {
6238         if (PerlIO_isutf8(fp)) {
6239             if (!SvUTF8(sv)) {
6240                 sv_utf8_upgrade_nomg(sv);
6241                 sv_pos_u2b(sv,&append,0);
6242             }
6243         } else if (SvUTF8(sv)) {
6244             SV * const tsv = newSV(0);
6245             sv_gets(tsv, fp, 0);
6246             sv_utf8_upgrade_nomg(tsv);
6247             SvCUR_set(sv,append);
6248             sv_catsv(sv,tsv);
6249             sv_free(tsv);
6250             goto return_string_or_null;
6251         }
6252     }
6253
6254     SvPOK_only(sv);
6255     if (PerlIO_isutf8(fp))
6256         SvUTF8_on(sv);
6257
6258     if (IN_PERL_COMPILETIME) {
6259         /* we always read code in line mode */
6260         rsptr = "\n";
6261         rslen = 1;
6262     }
6263     else if (RsSNARF(PL_rs)) {
6264         /* If it is a regular disk file use size from stat() as estimate
6265            of amount we are going to read -- may result in mallocing
6266            more memory than we really need if the layers below reduce
6267            the size we read (e.g. CRLF or a gzip layer).
6268          */
6269         Stat_t st;
6270         if (!PerlLIO_fstat(PerlIO_fileno(fp), &st) && S_ISREG(st.st_mode))  {
6271             const Off_t offset = PerlIO_tell(fp);
6272             if (offset != (Off_t) -1 && st.st_size + append > offset) {
6273                 (void) SvGROW(sv, (STRLEN)((st.st_size - offset) + append + 1));
6274             }
6275         }
6276         rsptr = NULL;
6277         rslen = 0;
6278     }
6279     else if (RsRECORD(PL_rs)) {
6280       I32 bytesread;
6281       char *buffer;
6282       U32 recsize;
6283
6284       /* Grab the size of the record we're getting */
6285       recsize = SvUV(SvRV(PL_rs)); /* RsRECORD() guarantees > 0. */
6286       buffer = SvGROW(sv, (STRLEN)(recsize + append + 1)) + append;
6287       /* Go yank in */
6288 #ifdef VMS
6289       /* VMS wants read instead of fread, because fread doesn't respect */
6290       /* RMS record boundaries. This is not necessarily a good thing to be */
6291       /* doing, but we've got no other real choice - except avoid stdio
6292          as implementation - perhaps write a :vms layer ?
6293        */
6294       bytesread = PerlLIO_read(PerlIO_fileno(fp), buffer, recsize);
6295 #else
6296       bytesread = PerlIO_read(fp, buffer, recsize);
6297 #endif
6298       if (bytesread < 0)
6299           bytesread = 0;
6300       SvCUR_set(sv, bytesread += append);
6301       buffer[bytesread] = '\0';
6302       goto return_string_or_null;
6303     }
6304     else if (RsPARA(PL_rs)) {
6305         rsptr = "\n\n";
6306         rslen = 2;
6307         rspara = 1;
6308     }
6309     else {
6310         /* Get $/ i.e. PL_rs into same encoding as stream wants */
6311         if (PerlIO_isutf8(fp)) {
6312             rsptr = SvPVutf8(PL_rs, rslen);
6313         }
6314         else {
6315             if (SvUTF8(PL_rs)) {
6316                 if (!sv_utf8_downgrade(PL_rs, TRUE)) {
6317                     Perl_croak(aTHX_ "Wide character in $/");
6318                 }
6319             }
6320             rsptr = SvPV_const(PL_rs, rslen);
6321         }
6322     }
6323
6324     rslast = rslen ? rsptr[rslen - 1] : '\0';
6325
6326     if (rspara) {               /* have to do this both before and after */
6327         do {                    /* to make sure file boundaries work right */
6328             if (PerlIO_eof(fp))
6329                 return 0;
6330             i = PerlIO_getc(fp);
6331             if (i != '\n') {
6332                 if (i == -1)
6333                     return 0;
6334                 PerlIO_ungetc(fp,i);
6335                 break;
6336             }
6337         } while (i != EOF);
6338     }
6339
6340     /* See if we know enough about I/O mechanism to cheat it ! */
6341
6342     /* This used to be #ifdef test - it is made run-time test for ease
6343        of abstracting out stdio interface. One call should be cheap
6344        enough here - and may even be a macro allowing compile
6345        time optimization.
6346      */
6347
6348     if (PerlIO_fast_gets(fp)) {
6349
6350     /*
6351      * We're going to steal some values from the stdio struct
6352      * and put EVERYTHING in the innermost loop into registers.
6353      */
6354     register STDCHAR *ptr;
6355     STRLEN bpx;
6356     I32 shortbuffered;
6357
6358 #if defined(VMS) && defined(PERLIO_IS_STDIO)
6359     /* An ungetc()d char is handled separately from the regular
6360      * buffer, so we getc() it back out and stuff it in the buffer.
6361      */
6362     i = PerlIO_getc(fp);
6363     if (i == EOF) return 0;
6364     *(--((*fp)->_ptr)) = (unsigned char) i;
6365     (*fp)->_cnt++;
6366 #endif
6367
6368     /* Here is some breathtakingly efficient cheating */
6369
6370     cnt = PerlIO_get_cnt(fp);                   /* get count into register */
6371     /* make sure we have the room */
6372     if ((I32)(SvLEN(sv) - append) <= cnt + 1) {
6373         /* Not room for all of it
6374            if we are looking for a separator and room for some
6375          */
6376         if (rslen && cnt > 80 && (I32)SvLEN(sv) > append) {
6377             /* just process what we have room for */
6378             shortbuffered = cnt - SvLEN(sv) + append + 1;
6379             cnt -= shortbuffered;
6380         }
6381         else {
6382             shortbuffered = 0;
6383             /* remember that cnt can be negative */
6384             SvGROW(sv, (STRLEN)(append + (cnt <= 0 ? 2 : (cnt + 1))));
6385         }
6386     }
6387     else
6388         shortbuffered = 0;
6389     bp = (STDCHAR*)SvPVX_const(sv) + append;  /* move these two too to registers */
6390     ptr = (STDCHAR*)PerlIO_get_ptr(fp);
6391     DEBUG_P(PerlIO_printf(Perl_debug_log,
6392         "Screamer: entering, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
6393     DEBUG_P(PerlIO_printf(Perl_debug_log,
6394         "Screamer: entering: PerlIO * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
6395                PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
6396                PTR2UV(PerlIO_has_base(fp) ? PerlIO_get_base(fp) : 0)));
6397     for (;;) {
6398       screamer:
6399         if (cnt > 0) {
6400             if (rslen) {
6401                 while (cnt > 0) {                    /* this     |  eat */
6402                     cnt--;
6403                     if ((*bp++ = *ptr++) == rslast)  /* really   |  dust */
6404                         goto thats_all_folks;        /* screams  |  sed :-) */
6405                 }
6406             }
6407             else {
6408                 Copy(ptr, bp, cnt, char);            /* this     |  eat */
6409                 bp += cnt;                           /* screams  |  dust */
6410                 ptr += cnt;                          /* louder   |  sed :-) */
6411                 cnt = 0;
6412             }
6413         }
6414         
6415         if (shortbuffered) {            /* oh well, must extend */
6416             cnt = shortbuffered;
6417             shortbuffered = 0;
6418             bpx = bp - (STDCHAR*)SvPVX_const(sv); /* box up before relocation */
6419             SvCUR_set(sv, bpx);
6420             SvGROW(sv, SvLEN(sv) + append + cnt + 2);
6421             bp = (STDCHAR*)SvPVX_const(sv) + bpx; /* unbox after relocation */
6422             continue;
6423         }
6424
6425         DEBUG_P(PerlIO_printf(Perl_debug_log,
6426                               "Screamer: going to getc, ptr=%"UVuf", cnt=%ld\n",
6427                               PTR2UV(ptr),(long)cnt));
6428         PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt); /* deregisterize cnt and ptr */
6429 #if 0
6430         DEBUG_P(PerlIO_printf(Perl_debug_log,
6431             "Screamer: pre: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
6432             PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
6433             PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
6434 #endif
6435         /* This used to call 'filbuf' in stdio form, but as that behaves like
6436            getc when cnt <= 0 we use PerlIO_getc here to avoid introducing
6437            another abstraction.  */
6438         i   = PerlIO_getc(fp);          /* get more characters */
6439 #if 0
6440         DEBUG_P(PerlIO_printf(Perl_debug_log,
6441             "Screamer: post: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
6442             PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
6443             PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
6444 #endif
6445         cnt = PerlIO_get_cnt(fp);
6446         ptr = (STDCHAR*)PerlIO_get_ptr(fp);     /* reregisterize cnt and ptr */
6447         DEBUG_P(PerlIO_printf(Perl_debug_log,
6448             "Screamer: after getc, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
6449
6450         if (i == EOF)                   /* all done for ever? */
6451             goto thats_really_all_folks;
6452
6453         bpx = bp - (STDCHAR*)SvPVX_const(sv);   /* box up before relocation */
6454         SvCUR_set(sv, bpx);
6455         SvGROW(sv, bpx + cnt + 2);
6456         bp = (STDCHAR*)SvPVX_const(sv) + bpx;   /* unbox after relocation */
6457
6458         *bp++ = (STDCHAR)i;             /* store character from PerlIO_getc */
6459
6460         if (rslen && (STDCHAR)i == rslast)  /* all done for now? */
6461             goto thats_all_folks;
6462     }
6463
6464 thats_all_folks:
6465     if ((rslen > 1 && (STRLEN)(bp - (STDCHAR*)SvPVX_const(sv)) < rslen) ||
6466           memNE((char*)bp - rslen, rsptr, rslen))
6467         goto screamer;                          /* go back to the fray */
6468 thats_really_all_folks:
6469     if (shortbuffered)
6470         cnt += shortbuffered;
6471         DEBUG_P(PerlIO_printf(Perl_debug_log,
6472             "Screamer: quitting, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
6473     PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt);  /* put these back or we're in trouble */
6474     DEBUG_P(PerlIO_printf(Perl_debug_log,
6475         "Screamer: end: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
6476         PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
6477         PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
6478     *bp = '\0';
6479     SvCUR_set(sv, bp - (STDCHAR*)SvPVX_const(sv));      /* set length */
6480     DEBUG_P(PerlIO_printf(Perl_debug_log,
6481         "Screamer: done, len=%ld, string=|%.*s|\n",
6482         (long)SvCUR(sv),(int)SvCUR(sv),SvPVX_const(sv)));
6483     }
6484    else
6485     {
6486        /*The big, slow, and stupid way. */
6487 #ifdef USE_HEAP_INSTEAD_OF_STACK        /* Even slower way. */
6488         STDCHAR *buf = NULL;
6489         Newx(buf, 8192, STDCHAR);
6490         assert(buf);
6491 #else
6492         STDCHAR buf[8192];
6493 #endif
6494
6495 screamer2:
6496         if (rslen) {
6497             register const STDCHAR * const bpe = buf + sizeof(buf);
6498             bp = buf;
6499             while ((i = PerlIO_getc(fp)) != EOF && (*bp++ = (STDCHAR)i) != rslast && bp < bpe)
6500                 ; /* keep reading */
6501             cnt = bp - buf;
6502         }
6503         else {
6504             cnt = PerlIO_read(fp,(char*)buf, sizeof(buf));
6505             /* Accomodate broken VAXC compiler, which applies U8 cast to
6506              * both args of ?: operator, causing EOF to change into 255
6507              */
6508             if (cnt > 0)
6509                  i = (U8)buf[cnt - 1];
6510             else
6511                  i = EOF;
6512         }
6513
6514         if (cnt < 0)
6515             cnt = 0;  /* we do need to re-set the sv even when cnt <= 0 */
6516         if (append)
6517              sv_catpvn(sv, (char *) buf, cnt);
6518         else
6519              sv_setpvn(sv, (char *) buf, cnt);
6520
6521         if (i != EOF &&                 /* joy */
6522             (!rslen ||
6523              SvCUR(sv) < rslen ||
6524              memNE(SvPVX_const(sv) + SvCUR(sv) - rslen, rsptr, rslen)))
6525         {
6526             append = -1;
6527             /*
6528              * If we're reading from a TTY and we get a short read,
6529              * indicating that the user hit his EOF character, we need
6530              * to notice it now, because if we try to read from the TTY
6531              * again, the EOF condition will disappear.
6532              *
6533              * The comparison of cnt to sizeof(buf) is an optimization
6534              * that prevents unnecessary calls to feof().
6535              *
6536              * - jik 9/25/96
6537              */
6538             if (!(cnt < (I32)sizeof(buf) && PerlIO_eof(fp)))
6539                 goto screamer2;
6540         }
6541
6542 #ifdef USE_HEAP_INSTEAD_OF_STACK
6543         Safefree(buf);
6544 #endif
6545     }
6546
6547     if (rspara) {               /* have to do this both before and after */
6548         while (i != EOF) {      /* to make sure file boundaries work right */
6549             i = PerlIO_getc(fp);
6550             if (i != '\n') {
6551                 PerlIO_ungetc(fp,i);
6552                 break;
6553             }
6554         }
6555     }
6556
6557 return_string_or_null:
6558     return (SvCUR(sv) - append) ? SvPVX(sv) : NULL;
6559 }
6560
6561 /*
6562 =for apidoc sv_inc
6563
6564 Auto-increment of the value in the SV, doing string to numeric conversion
6565 if necessary. Handles 'get' magic.
6566
6567 =cut
6568 */
6569
6570 void
6571 Perl_sv_inc(pTHX_ register SV *sv)
6572 {
6573     dVAR;
6574     register char *d;
6575     int flags;
6576
6577     if (!sv)
6578         return;
6579     SvGETMAGIC(sv);
6580     if (SvTHINKFIRST(sv)) {
6581         if (SvIsCOW(sv))
6582             sv_force_normal_flags(sv, 0);
6583         if (SvREADONLY(sv)) {
6584             if (IN_PERL_RUNTIME)
6585                 Perl_croak(aTHX_ PL_no_modify);
6586         }
6587         if (SvROK(sv)) {
6588             IV i;
6589             if (SvAMAGIC(sv) && AMG_CALLun(sv,inc))
6590                 return;
6591             i = PTR2IV(SvRV(sv));
6592             sv_unref(sv);
6593             sv_setiv(sv, i);
6594         }
6595     }
6596     flags = SvFLAGS(sv);
6597     if ((flags & (SVp_NOK|SVp_IOK)) == SVp_NOK) {
6598         /* It's (privately or publicly) a float, but not tested as an
6599            integer, so test it to see. */
6600         (void) SvIV(sv);
6601         flags = SvFLAGS(sv);
6602     }
6603     if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
6604         /* It's publicly an integer, or privately an integer-not-float */
6605 #ifdef PERL_PRESERVE_IVUV
6606       oops_its_int:
6607 #endif
6608         if (SvIsUV(sv)) {
6609             if (SvUVX(sv) == UV_MAX)
6610                 sv_setnv(sv, UV_MAX_P1);
6611             else
6612                 (void)SvIOK_only_UV(sv);
6613                 SvUV_set(sv, SvUVX(sv) + 1);
6614         } else {
6615             if (SvIVX(sv) == IV_MAX)
6616                 sv_setuv(sv, (UV)IV_MAX + 1);
6617             else {
6618                 (void)SvIOK_only(sv);
6619                 SvIV_set(sv, SvIVX(sv) + 1);
6620             }   
6621         }
6622         return;
6623     }
6624     if (flags & SVp_NOK) {
6625         (void)SvNOK_only(sv);
6626         SvNV_set(sv, SvNVX(sv) + 1.0);
6627         return;
6628     }
6629
6630     if (!(flags & SVp_POK) || !*SvPVX_const(sv)) {
6631         if ((flags & SVTYPEMASK) < SVt_PVIV)
6632             sv_upgrade(sv, ((flags & SVTYPEMASK) > SVt_IV ? SVt_PVIV : SVt_IV));
6633         (void)SvIOK_only(sv);
6634         SvIV_set(sv, 1);
6635         return;
6636     }
6637     d = SvPVX(sv);
6638     while (isALPHA(*d)) d++;
6639     while (isDIGIT(*d)) d++;
6640     if (*d) {
6641 #ifdef PERL_PRESERVE_IVUV
6642         /* Got to punt this as an integer if needs be, but we don't issue
6643            warnings. Probably ought to make the sv_iv_please() that does
6644            the conversion if possible, and silently.  */
6645         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), NULL);
6646         if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
6647             /* Need to try really hard to see if it's an integer.
6648                9.22337203685478e+18 is an integer.
6649                but "9.22337203685478e+18" + 0 is UV=9223372036854779904
6650                so $a="9.22337203685478e+18"; $a+0; $a++
6651                needs to be the same as $a="9.22337203685478e+18"; $a++
6652                or we go insane. */
6653         
6654             (void) sv_2iv(sv);
6655             if (SvIOK(sv))
6656                 goto oops_its_int;
6657
6658             /* sv_2iv *should* have made this an NV */
6659             if (flags & SVp_NOK) {
6660                 (void)SvNOK_only(sv);
6661                 SvNV_set(sv, SvNVX(sv) + 1.0);
6662                 return;
6663             }
6664             /* I don't think we can get here. Maybe I should assert this
6665                And if we do get here I suspect that sv_setnv will croak. NWC
6666                Fall through. */
6667 #if defined(USE_LONG_DOUBLE)
6668             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_inc punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"PERL_PRIgldbl"\n",
6669                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
6670 #else
6671             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_inc punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
6672                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
6673 #endif
6674         }
6675 #endif /* PERL_PRESERVE_IVUV */
6676         sv_setnv(sv,Atof(SvPVX_const(sv)) + 1.0);
6677         return;
6678     }
6679     d--;
6680     while (d >= SvPVX_const(sv)) {
6681         if (isDIGIT(*d)) {
6682             if (++*d <= '9')
6683                 return;
6684             *(d--) = '0';
6685         }
6686         else {
6687 #ifdef EBCDIC
6688             /* MKS: The original code here died if letters weren't consecutive.
6689              * at least it didn't have to worry about non-C locales.  The
6690              * new code assumes that ('z'-'a')==('Z'-'A'), letters are
6691              * arranged in order (although not consecutively) and that only
6692              * [A-Za-z] are accepted by isALPHA in the C locale.
6693              */
6694             if (*d != 'z' && *d != 'Z') {
6695                 do { ++*d; } while (!isALPHA(*d));
6696                 return;
6697             }
6698             *(d--) -= 'z' - 'a';
6699 #else
6700             ++*d;
6701             if (isALPHA(*d))
6702                 return;
6703             *(d--) -= 'z' - 'a' + 1;
6704 #endif
6705         }
6706     }
6707     /* oh,oh, the number grew */
6708     SvGROW(sv, SvCUR(sv) + 2);
6709     SvCUR_set(sv, SvCUR(sv) + 1);
6710     for (d = SvPVX(sv) + SvCUR(sv); d > SvPVX_const(sv); d--)
6711         *d = d[-1];
6712     if (isDIGIT(d[1]))
6713         *d = '1';
6714     else
6715         *d = d[1];
6716 }
6717
6718 /*
6719 =for apidoc sv_dec
6720
6721 Auto-decrement of the value in the SV, doing string to numeric conversion
6722 if necessary. Handles 'get' magic.
6723
6724 =cut
6725 */
6726
6727 void
6728 Perl_sv_dec(pTHX_ register SV *sv)
6729 {
6730     dVAR;
6731     int flags;
6732
6733     if (!sv)
6734         return;
6735     SvGETMAGIC(sv);
6736     if (SvTHINKFIRST(sv)) {
6737         if (SvIsCOW(sv))
6738             sv_force_normal_flags(sv, 0);
6739         if (SvREADONLY(sv)) {
6740             if (IN_PERL_RUNTIME)
6741                 Perl_croak(aTHX_ PL_no_modify);
6742         }
6743         if (SvROK(sv)) {
6744             IV i;
6745             if (SvAMAGIC(sv) && AMG_CALLun(sv,dec))
6746                 return;
6747             i = PTR2IV(SvRV(sv));
6748             sv_unref(sv);
6749             sv_setiv(sv, i);
6750         }
6751     }
6752     /* Unlike sv_inc we don't have to worry about string-never-numbers
6753        and keeping them magic. But we mustn't warn on punting */
6754     flags = SvFLAGS(sv);
6755     if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
6756         /* It's publicly an integer, or privately an integer-not-float */
6757 #ifdef PERL_PRESERVE_IVUV
6758       oops_its_int:
6759 #endif
6760         if (SvIsUV(sv)) {
6761             if (SvUVX(sv) == 0) {
6762                 (void)SvIOK_only(sv);
6763                 SvIV_set(sv, -1);
6764             }
6765             else {
6766                 (void)SvIOK_only_UV(sv);
6767                 SvUV_set(sv, SvUVX(sv) - 1);
6768             }   
6769         } else {
6770             if (SvIVX(sv) == IV_MIN)
6771                 sv_setnv(sv, (NV)IV_MIN - 1.0);
6772             else {
6773                 (void)SvIOK_only(sv);
6774                 SvIV_set(sv, SvIVX(sv) - 1);
6775             }   
6776         }
6777         return;
6778     }
6779     if (flags & SVp_NOK) {
6780         SvNV_set(sv, SvNVX(sv) - 1.0);
6781         (void)SvNOK_only(sv);
6782         return;
6783     }
6784     if (!(flags & SVp_POK)) {
6785         if ((flags & SVTYPEMASK) < SVt_PVIV)
6786             sv_upgrade(sv, ((flags & SVTYPEMASK) > SVt_IV) ? SVt_PVIV : SVt_IV);
6787         SvIV_set(sv, -1);
6788         (void)SvIOK_only(sv);
6789         return;
6790     }
6791 #ifdef PERL_PRESERVE_IVUV
6792     {
6793         const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), NULL);
6794         if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
6795             /* Need to try really hard to see if it's an integer.
6796                9.22337203685478e+18 is an integer.
6797                but "9.22337203685478e+18" + 0 is UV=9223372036854779904
6798                so $a="9.22337203685478e+18"; $a+0; $a--
6799                needs to be the same as $a="9.22337203685478e+18"; $a--
6800                or we go insane. */
6801         
6802             (void) sv_2iv(sv);
6803             if (SvIOK(sv))
6804                 goto oops_its_int;
6805
6806             /* sv_2iv *should* have made this an NV */
6807             if (flags & SVp_NOK) {
6808                 (void)SvNOK_only(sv);
6809                 SvNV_set(sv, SvNVX(sv) - 1.0);
6810                 return;
6811             }
6812             /* I don't think we can get here. Maybe I should assert this
6813                And if we do get here I suspect that sv_setnv will croak. NWC
6814                Fall through. */
6815 #if defined(USE_LONG_DOUBLE)
6816             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_dec punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"PERL_PRIgldbl"\n",
6817                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
6818 #else
6819             DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_dec punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
6820                                   SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
6821 #endif
6822         }
6823     }
6824 #endif /* PERL_PRESERVE_IVUV */
6825     sv_setnv(sv,Atof(SvPVX_const(sv)) - 1.0);   /* punt */
6826 }
6827
6828 /*
6829 =for apidoc sv_mortalcopy
6830
6831 Creates a new SV which is a copy of the original SV (using C<sv_setsv>).
6832 The new SV is marked as mortal. It will be destroyed "soon", either by an
6833 explicit call to FREETMPS, or by an implicit call at places such as
6834 statement boundaries.  See also C<sv_newmortal> and C<sv_2mortal>.
6835
6836 =cut
6837 */
6838
6839 /* Make a string that will exist for the duration of the expression
6840  * evaluation.  Actually, it may have to last longer than that, but
6841  * hopefully we won't free it until it has been assigned to a
6842  * permanent location. */
6843
6844 SV *
6845 Perl_sv_mortalcopy(pTHX_ SV *oldstr)
6846 {
6847     dVAR;
6848     register SV *sv;
6849
6850     new_SV(sv);
6851     sv_setsv(sv,oldstr);
6852     EXTEND_MORTAL(1);
6853     PL_tmps_stack[++PL_tmps_ix] = sv;
6854     SvTEMP_on(sv);
6855     return sv;
6856 }
6857
6858 /*
6859 =for apidoc sv_newmortal
6860
6861 Creates a new null SV which is mortal.  The reference count of the SV is
6862 set to 1. It will be destroyed "soon", either by an explicit call to
6863 FREETMPS, or by an implicit call at places such as statement boundaries.
6864 See also C<sv_mortalcopy> and C<sv_2mortal>.
6865
6866 =cut
6867 */
6868
6869 SV *
6870 Perl_sv_newmortal(pTHX)
6871 {
6872     dVAR;
6873     register SV *sv;
6874
6875     new_SV(sv);
6876     SvFLAGS(sv) = SVs_TEMP;
6877     EXTEND_MORTAL(1);
6878     PL_tmps_stack[++PL_tmps_ix] = sv;
6879     return sv;
6880 }
6881
6882 /*
6883 =for apidoc sv_2mortal
6884
6885 Marks an existing SV as mortal.  The SV will be destroyed "soon", either
6886 by an explicit call to FREETMPS, or by an implicit call at places such as
6887 statement boundaries.  SvTEMP() is turned on which means that the SV's
6888 string buffer can be "stolen" if this SV is copied. See also C<sv_newmortal>
6889 and C<sv_mortalcopy>.
6890
6891 =cut
6892 */
6893
6894 SV *
6895 Perl_sv_2mortal(pTHX_ register SV *sv)
6896 {
6897     dVAR;
6898     if (!sv)
6899         return NULL;
6900     if (SvREADONLY(sv) && SvIMMORTAL(sv))
6901         return sv;
6902     EXTEND_MORTAL(1);
6903     PL_tmps_stack[++PL_tmps_ix] = sv;
6904     SvTEMP_on(sv);
6905     return sv;
6906 }
6907
6908 /*
6909 =for apidoc newSVpv
6910
6911 Creates a new SV and copies a string into it.  The reference count for the
6912 SV is set to 1.  If C<len> is zero, Perl will compute the length using
6913 strlen().  For efficiency, consider using C<newSVpvn> instead.
6914
6915 =cut
6916 */
6917
6918 SV *
6919 Perl_newSVpv(pTHX_ const char *s, STRLEN len)
6920 {
6921     dVAR;
6922     register SV *sv;
6923
6924     new_SV(sv);
6925     sv_setpvn(sv, s, len || s == NULL ? len : strlen(s));
6926     return sv;
6927 }
6928
6929 /*
6930 =for apidoc newSVpvn
6931
6932 Creates a new SV and copies a string into it.  The reference count for the
6933 SV is set to 1.  Note that if C<len> is zero, Perl will create a zero length
6934 string.  You are responsible for ensuring that the source string is at least
6935 C<len> bytes long.  If the C<s> argument is NULL the new SV will be undefined.
6936
6937 =cut
6938 */
6939
6940 SV *
6941 Perl_newSVpvn(pTHX_ const char *s, STRLEN len)
6942 {
6943     dVAR;
6944     register SV *sv;
6945
6946     new_SV(sv);
6947     sv_setpvn(sv,s,len);
6948     return sv;
6949 }
6950
6951
6952 /*
6953 =for apidoc newSVhek
6954
6955 Creates a new SV from the hash key structure.  It will generate scalars that
6956 point to the shared string table where possible. Returns a new (undefined)
6957 SV if the hek is NULL.
6958
6959 =cut
6960 */
6961
6962 SV *
6963 Perl_newSVhek(pTHX_ const HEK *hek)
6964 {
6965     dVAR;
6966     if (!hek) {
6967         SV *sv;
6968
6969         new_SV(sv);
6970         return sv;
6971     }
6972
6973     if (HEK_LEN(hek) == HEf_SVKEY) {
6974         return newSVsv(*(SV**)HEK_KEY(hek));
6975     } else {
6976         const int flags = HEK_FLAGS(hek);
6977         if (flags & HVhek_WASUTF8) {
6978             /* Trouble :-)
6979                Andreas would like keys he put in as utf8 to come back as utf8
6980             */
6981             STRLEN utf8_len = HEK_LEN(hek);
6982             const U8 *as_utf8 = bytes_to_utf8 ((U8*)HEK_KEY(hek), &utf8_len);
6983             SV * const sv = newSVpvn ((const char*)as_utf8, utf8_len);
6984
6985             SvUTF8_on (sv);
6986             Safefree (as_utf8); /* bytes_to_utf8() allocates a new string */
6987             return sv;
6988         } else if (flags & (HVhek_REHASH|HVhek_UNSHARED)) {
6989             /* We don't have a pointer to the hv, so we have to replicate the
6990                flag into every HEK. This hv is using custom a hasing
6991                algorithm. Hence we can't return a shared string scalar, as
6992                that would contain the (wrong) hash value, and might get passed
6993                into an hv routine with a regular hash.
6994                Similarly, a hash that isn't using shared hash keys has to have
6995                the flag in every key so that we know not to try to call
6996                share_hek_kek on it.  */
6997
6998             SV * const sv = newSVpvn (HEK_KEY(hek), HEK_LEN(hek));
6999             if (HEK_UTF8(hek))
7000                 SvUTF8_on (sv);
7001             return sv;
7002         }
7003         /* This will be overwhelminly the most common case.  */
7004         {
7005             /* Inline most of newSVpvn_share(), because share_hek_hek() is far
7006                more efficient than sharepvn().  */
7007             SV *sv;
7008
7009             new_SV(sv);
7010             sv_upgrade(sv, SVt_PV);
7011             SvPV_set(sv, (char *)HEK_KEY(share_hek_hek(hek)));
7012             SvCUR_set(sv, HEK_LEN(hek));
7013             SvLEN_set(sv, 0);
7014             SvREADONLY_on(sv);
7015             SvFAKE_on(sv);
7016             SvPOK_on(sv);
7017             if (HEK_UTF8(hek))
7018                 SvUTF8_on(sv);
7019             return sv;
7020         }
7021     }
7022 }
7023
7024 /*
7025 =for apidoc newSVpvn_share
7026
7027 Creates a new SV with its SvPVX_const pointing to a shared string in the string
7028 table. If the string does not already exist in the table, it is created
7029 first.  Turns on READONLY and FAKE.  The string's hash is stored in the UV
7030 slot of the SV; if the C<hash> parameter is non-zero, that value is used;
7031 otherwise the hash is computed.  The idea here is that as the string table
7032 is used for shared hash keys these strings will have SvPVX_const == HeKEY and
7033 hash lookup will avoid string compare.
7034
7035 =cut
7036 */
7037
7038 SV *
7039 Perl_newSVpvn_share(pTHX_ const char *src, I32 len, U32 hash)
7040 {
7041     dVAR;
7042     register SV *sv;
7043     bool is_utf8 = FALSE;
7044     const char *const orig_src = src;
7045
7046     if (len < 0) {
7047         STRLEN tmplen = -len;
7048         is_utf8 = TRUE;
7049         /* See the note in hv.c:hv_fetch() --jhi */
7050         src = (char*)bytes_from_utf8((const U8*)src, &tmplen, &is_utf8);
7051         len = tmplen;
7052     }
7053     if (!hash)
7054         PERL_HASH(hash, src, len);
7055     new_SV(sv);
7056     sv_upgrade(sv, SVt_PV);
7057     SvPV_set(sv, sharepvn(src, is_utf8?-len:len, hash));
7058     SvCUR_set(sv, len);
7059     SvLEN_set(sv, 0);
7060     SvREADONLY_on(sv);
7061     SvFAKE_on(sv);
7062     SvPOK_on(sv);
7063     if (is_utf8)
7064         SvUTF8_on(sv);
7065     if (src != orig_src)
7066         Safefree(src);
7067     return sv;
7068 }
7069
7070
7071 #if defined(PERL_IMPLICIT_CONTEXT)
7072
7073 /* pTHX_ magic can't cope with varargs, so this is a no-context
7074  * version of the main function, (which may itself be aliased to us).
7075  * Don't access this version directly.
7076  */
7077
7078 SV *
7079 Perl_newSVpvf_nocontext(const char* pat, ...)
7080 {
7081     dTHX;
7082     register SV *sv;
7083     va_list args;
7084     va_start(args, pat);
7085     sv = vnewSVpvf(pat, &args);
7086     va_end(args);
7087     return sv;
7088 }
7089 #endif
7090
7091 /*
7092 =for apidoc newSVpvf
7093
7094 Creates a new SV and initializes it with the string formatted like
7095 C<sprintf>.
7096
7097 =cut
7098 */
7099
7100 SV *
7101 Perl_newSVpvf(pTHX_ const char* pat, ...)
7102 {
7103     register SV *sv;
7104     va_list args;
7105     va_start(args, pat);
7106     sv = vnewSVpvf(pat, &args);
7107     va_end(args);
7108     return sv;
7109 }
7110
7111 /* backend for newSVpvf() and newSVpvf_nocontext() */
7112
7113 SV *
7114 Perl_vnewSVpvf(pTHX_ const char* pat, va_list* args)
7115 {
7116     dVAR;
7117     register SV *sv;
7118     new_SV(sv);
7119     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
7120     return sv;
7121 }
7122
7123 /*
7124 =for apidoc newSVnv
7125
7126 Creates a new SV and copies a floating point value into it.
7127 The reference count for the SV is set to 1.
7128
7129 =cut
7130 */
7131
7132 SV *
7133 Perl_newSVnv(pTHX_ NV n)
7134 {
7135     dVAR;
7136     register SV *sv;
7137
7138     new_SV(sv);
7139     sv_setnv(sv,n);
7140     return sv;
7141 }
7142
7143 /*
7144 =for apidoc newSViv
7145
7146 Creates a new SV and copies an integer into it.  The reference count for the
7147 SV is set to 1.
7148
7149 =cut
7150 */
7151
7152 SV *
7153 Perl_newSViv(pTHX_ IV i)
7154 {
7155     dVAR;
7156     register SV *sv;
7157
7158     new_SV(sv);
7159     sv_setiv(sv,i);
7160     return sv;
7161 }
7162
7163 /*
7164 =for apidoc newSVuv
7165
7166 Creates a new SV and copies an unsigned integer into it.
7167 The reference count for the SV is set to 1.
7168
7169 =cut
7170 */
7171
7172 SV *
7173 Perl_newSVuv(pTHX_ UV u)
7174 {
7175     dVAR;
7176     register SV *sv;
7177
7178     new_SV(sv);
7179     sv_setuv(sv,u);
7180     return sv;
7181 }
7182
7183 /*
7184 =for apidoc newRV_noinc
7185
7186 Creates an RV wrapper for an SV.  The reference count for the original
7187 SV is B<not> incremented.
7188
7189 =cut
7190 */
7191
7192 SV *
7193 Perl_newRV_noinc(pTHX_ SV *tmpRef)
7194 {
7195     dVAR;
7196     register SV *sv;
7197
7198     new_SV(sv);
7199     sv_upgrade(sv, SVt_RV);
7200     SvTEMP_off(tmpRef);
7201     SvRV_set(sv, tmpRef);
7202     SvROK_on(sv);
7203     return sv;
7204 }
7205
7206 /* newRV_inc is the official function name to use now.
7207  * newRV_inc is in fact #defined to newRV in sv.h
7208  */
7209
7210 SV *
7211 Perl_newRV(pTHX_ SV *sv)
7212 {
7213     dVAR;
7214     return newRV_noinc(SvREFCNT_inc_simple_NN(sv));
7215 }
7216
7217 /*
7218 =for apidoc newSVsv
7219
7220 Creates a new SV which is an exact duplicate of the original SV.
7221 (Uses C<sv_setsv>).
7222
7223 =cut
7224 */
7225
7226 SV *
7227 Perl_newSVsv(pTHX_ register SV *old)
7228 {
7229     dVAR;
7230     register SV *sv;
7231
7232     if (!old)
7233         return NULL;
7234     if (SvTYPE(old) == SVTYPEMASK) {
7235         if (ckWARN_d(WARN_INTERNAL))
7236             Perl_warner(aTHX_ packWARN(WARN_INTERNAL), "semi-panic: attempt to dup freed string");
7237         return NULL;
7238     }
7239     new_SV(sv);
7240     /* SV_GMAGIC is the default for sv_setv()
7241        SV_NOSTEAL prevents TEMP buffers being, well, stolen, and saves games
7242        with SvTEMP_off and SvTEMP_on round a call to sv_setsv.  */
7243     sv_setsv_flags(sv, old, SV_GMAGIC | SV_NOSTEAL);
7244     return sv;
7245 }
7246
7247 /*
7248 =for apidoc sv_reset
7249
7250 Underlying implementation for the C<reset> Perl function.
7251 Note that the perl-level function is vaguely deprecated.
7252
7253 =cut
7254 */
7255
7256 void
7257 Perl_sv_reset(pTHX_ register const char *s, HV *stash)
7258 {
7259     dVAR;
7260     char todo[PERL_UCHAR_MAX+1];
7261
7262     if (!stash)
7263         return;
7264
7265     if (!*s) {          /* reset ?? searches */
7266         MAGIC * const mg = mg_find((SV *)stash, PERL_MAGIC_symtab);
7267         if (mg) {
7268             PMOP *pm = (PMOP *) mg->mg_obj;
7269             while (pm) {
7270                 pm->op_pmdynflags &= ~PMdf_USED;
7271                 pm = pm->op_pmnext;
7272             }
7273         }
7274         return;
7275     }
7276
7277     /* reset variables */
7278
7279     if (!HvARRAY(stash))
7280         return;
7281
7282     Zero(todo, 256, char);
7283     while (*s) {
7284         I32 max;
7285         I32 i = (unsigned char)*s;
7286         if (s[1] == '-') {
7287             s += 2;
7288         }
7289         max = (unsigned char)*s++;
7290         for ( ; i <= max; i++) {
7291             todo[i] = 1;
7292         }
7293         for (i = 0; i <= (I32) HvMAX(stash); i++) {
7294             HE *entry;
7295             for (entry = HvARRAY(stash)[i];
7296                  entry;
7297                  entry = HeNEXT(entry))
7298             {
7299                 register GV *gv;
7300                 register SV *sv;
7301
7302                 if (!todo[(U8)*HeKEY(entry)])
7303                     continue;
7304                 gv = (GV*)HeVAL(entry);
7305                 sv = GvSV(gv);
7306                 if (sv) {
7307                     if (SvTHINKFIRST(sv)) {
7308                         if (!SvREADONLY(sv) && SvROK(sv))
7309                             sv_unref(sv);
7310                         /* XXX Is this continue a bug? Why should THINKFIRST
7311                            exempt us from resetting arrays and hashes?  */
7312                         continue;
7313                     }
7314                     SvOK_off(sv);
7315                     if (SvTYPE(sv) >= SVt_PV) {
7316                         SvCUR_set(sv, 0);
7317                         if (SvPVX_const(sv) != NULL)
7318                             *SvPVX(sv) = '\0';
7319                         SvTAINT(sv);
7320                     }
7321                 }
7322                 if (GvAV(gv)) {
7323                     av_clear(GvAV(gv));
7324                 }
7325                 if (GvHV(gv) && !HvNAME_get(GvHV(gv))) {
7326 #if defined(VMS)
7327                     Perl_die(aTHX_ "Can't reset %%ENV on this system");
7328 #else /* ! VMS */
7329                     hv_clear(GvHV(gv));
7330 #  if defined(USE_ENVIRON_ARRAY)
7331                     if (gv == PL_envgv)
7332                         my_clearenv();
7333 #  endif /* USE_ENVIRON_ARRAY */
7334 #endif /* VMS */
7335                 }
7336             }
7337         }
7338     }
7339 }
7340
7341 /*
7342 =for apidoc sv_2io
7343
7344 Using various gambits, try to get an IO from an SV: the IO slot if its a
7345 GV; or the recursive result if we're an RV; or the IO slot of the symbol
7346 named after the PV if we're a string.
7347
7348 =cut
7349 */
7350
7351 IO*
7352 Perl_sv_2io(pTHX_ SV *sv)
7353 {
7354     IO* io;
7355     GV* gv;
7356
7357     switch (SvTYPE(sv)) {
7358     case SVt_PVIO:
7359         io = (IO*)sv;
7360         break;
7361     case SVt_PVGV:
7362         gv = (GV*)sv;
7363         io = GvIO(gv);
7364         if (!io)
7365             Perl_croak(aTHX_ "Bad filehandle: %s", GvNAME(gv));
7366         break;
7367     default:
7368         if (!SvOK(sv))
7369             Perl_croak(aTHX_ PL_no_usym, "filehandle");
7370         if (SvROK(sv))
7371             return sv_2io(SvRV(sv));
7372         gv = gv_fetchsv(sv, 0, SVt_PVIO);
7373         if (gv)
7374             io = GvIO(gv);
7375         else
7376             io = 0;
7377         if (!io)
7378             Perl_croak(aTHX_ "Bad filehandle: %"SVf, (void*)sv);
7379         break;
7380     }
7381     return io;
7382 }
7383
7384 /*
7385 =for apidoc sv_2cv
7386
7387 Using various gambits, try to get a CV from an SV; in addition, try if
7388 possible to set C<*st> and C<*gvp> to the stash and GV associated with it.
7389 The flags in C<lref> are passed to sv_fetchsv.
7390
7391 =cut
7392 */
7393
7394 CV *
7395 Perl_sv_2cv(pTHX_ SV *sv, HV **st, GV **gvp, I32 lref)
7396 {
7397     dVAR;
7398     GV *gv = NULL;
7399     CV *cv = NULL;
7400
7401     if (!sv) {
7402         *st = NULL;
7403         *gvp = NULL;
7404         return NULL;
7405     }
7406     switch (SvTYPE(sv)) {
7407     case SVt_PVCV:
7408         *st = CvSTASH(sv);
7409         *gvp = NULL;
7410         return (CV*)sv;
7411     case SVt_PVHV:
7412     case SVt_PVAV:
7413         *st = NULL;
7414         *gvp = NULL;
7415         return NULL;
7416     case SVt_PVGV:
7417         gv = (GV*)sv;
7418         *gvp = gv;
7419         *st = GvESTASH(gv);
7420         goto fix_gv;
7421
7422     default:
7423         SvGETMAGIC(sv);
7424         if (SvROK(sv)) {
7425             SV * const *sp = &sv;       /* Used in tryAMAGICunDEREF macro. */
7426             tryAMAGICunDEREF(to_cv);
7427
7428             sv = SvRV(sv);
7429             if (SvTYPE(sv) == SVt_PVCV) {
7430                 cv = (CV*)sv;
7431                 *gvp = NULL;
7432                 *st = CvSTASH(cv);
7433                 return cv;
7434             }
7435             else if(isGV(sv))
7436                 gv = (GV*)sv;
7437             else
7438                 Perl_croak(aTHX_ "Not a subroutine reference");
7439         }
7440         else if (isGV(sv))
7441             gv = (GV*)sv;
7442         else
7443             gv = gv_fetchsv(sv, lref, SVt_PVCV);
7444         *gvp = gv;
7445         if (!gv) {
7446             *st = NULL;
7447             return NULL;
7448         }
7449         /* Some flags to gv_fetchsv mean don't really create the GV  */
7450         if (SvTYPE(gv) != SVt_PVGV) {
7451             *st = NULL;
7452             return NULL;
7453         }
7454         *st = GvESTASH(gv);
7455     fix_gv:
7456         if (lref && !GvCVu(gv)) {
7457             SV *tmpsv;
7458             ENTER;
7459             tmpsv = newSV(0);
7460             gv_efullname3(tmpsv, gv, NULL);
7461             /* XXX this is probably not what they think they're getting.
7462              * It has the same effect as "sub name;", i.e. just a forward
7463              * declaration! */
7464             newSUB(start_subparse(FALSE, 0),
7465                    newSVOP(OP_CONST, 0, tmpsv),
7466                    NULL, NULL);
7467             LEAVE;
7468             if (!GvCVu(gv))
7469                 Perl_croak(aTHX_ "Unable to create sub named \"%"SVf"\"",
7470                            (void*)sv);
7471         }
7472         return GvCVu(gv);
7473     }
7474 }
7475
7476 /*
7477 =for apidoc sv_true
7478
7479 Returns true if the SV has a true value by Perl's rules.
7480 Use the C<SvTRUE> macro instead, which may call C<sv_true()> or may
7481 instead use an in-line version.
7482
7483 =cut
7484 */
7485
7486 I32
7487 Perl_sv_true(pTHX_ register SV *sv)
7488 {
7489     if (!sv)
7490         return 0;
7491     if (SvPOK(sv)) {
7492         register const XPV* const tXpv = (XPV*)SvANY(sv);
7493         if (tXpv &&
7494                 (tXpv->xpv_cur > 1 ||
7495                 (tXpv->xpv_cur && *sv->sv_u.svu_pv != '0')))
7496             return 1;
7497         else
7498             return 0;
7499     }
7500     else {
7501         if (SvIOK(sv))
7502             return SvIVX(sv) != 0;
7503         else {
7504             if (SvNOK(sv))
7505                 return SvNVX(sv) != 0.0;
7506             else
7507                 return sv_2bool(sv);
7508         }
7509     }
7510 }
7511
7512 /*
7513 =for apidoc sv_pvn_force
7514
7515 Get a sensible string out of the SV somehow.
7516 A private implementation of the C<SvPV_force> macro for compilers which
7517 can't cope with complex macro expressions. Always use the macro instead.
7518
7519 =for apidoc sv_pvn_force_flags
7520
7521 Get a sensible string out of the SV somehow.
7522 If C<flags> has C<SV_GMAGIC> bit set, will C<mg_get> on C<sv> if
7523 appropriate, else not. C<sv_pvn_force> and C<sv_pvn_force_nomg> are
7524 implemented in terms of this function.
7525 You normally want to use the various wrapper macros instead: see
7526 C<SvPV_force> and C<SvPV_force_nomg>
7527
7528 =cut
7529 */
7530
7531 char *
7532 Perl_sv_pvn_force_flags(pTHX_ SV *sv, STRLEN *lp, I32 flags)
7533 {
7534     dVAR;
7535     if (SvTHINKFIRST(sv) && !SvROK(sv))
7536         sv_force_normal_flags(sv, 0);
7537
7538     if (SvPOK(sv)) {
7539         if (lp)
7540             *lp = SvCUR(sv);
7541     }
7542     else {
7543         char *s;
7544         STRLEN len;
7545  
7546         if (SvREADONLY(sv) && !(flags & SV_MUTABLE_RETURN)) {
7547             const char * const ref = sv_reftype(sv,0);
7548             if (PL_op)
7549                 Perl_croak(aTHX_ "Can't coerce readonly %s to string in %s",
7550                            ref, OP_NAME(PL_op));
7551             else
7552                 Perl_croak(aTHX_ "Can't coerce readonly %s to string", ref);
7553         }
7554         if (SvTYPE(sv) > SVt_PVLV && SvTYPE(sv) != SVt_PVFM)
7555             Perl_croak(aTHX_ "Can't coerce %s to string in %s", sv_reftype(sv,0),
7556                 OP_NAME(PL_op));
7557         s = sv_2pv_flags(sv, &len, flags);
7558         if (lp)
7559             *lp = len;
7560
7561         if (s != SvPVX_const(sv)) {     /* Almost, but not quite, sv_setpvn() */
7562             if (SvROK(sv))
7563                 sv_unref(sv);
7564             SvUPGRADE(sv, SVt_PV);              /* Never FALSE */
7565             SvGROW(sv, len + 1);
7566             Move(s,SvPVX(sv),len,char);
7567             SvCUR_set(sv, len);
7568             *SvEND(sv) = '\0';
7569         }
7570         if (!SvPOK(sv)) {
7571             SvPOK_on(sv);               /* validate pointer */
7572             SvTAINT(sv);
7573             DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
7574                                   PTR2UV(sv),SvPVX_const(sv)));
7575         }
7576     }
7577     return SvPVX_mutable(sv);
7578 }
7579
7580 /*
7581 =for apidoc sv_pvbyten_force
7582
7583 The backend for the C<SvPVbytex_force> macro. Always use the macro instead.
7584
7585 =cut
7586 */
7587
7588 char *
7589 Perl_sv_pvbyten_force(pTHX_ SV *sv, STRLEN *lp)
7590 {
7591     sv_pvn_force(sv,lp);
7592     sv_utf8_downgrade(sv,0);
7593     *lp = SvCUR(sv);
7594     return SvPVX(sv);
7595 }
7596
7597 /*
7598 =for apidoc sv_pvutf8n_force
7599
7600 The backend for the C<SvPVutf8x_force> macro. Always use the macro instead.
7601
7602 =cut
7603 */
7604
7605 char *
7606 Perl_sv_pvutf8n_force(pTHX_ SV *sv, STRLEN *lp)
7607 {
7608     sv_pvn_force(sv,lp);
7609     sv_utf8_upgrade(sv);
7610     *lp = SvCUR(sv);
7611     return SvPVX(sv);
7612 }
7613
7614 /*
7615 =for apidoc sv_reftype
7616
7617 Returns a string describing what the SV is a reference to.
7618
7619 =cut
7620 */
7621
7622 const char *
7623 Perl_sv_reftype(pTHX_ const SV *sv, int ob)
7624 {
7625     /* The fact that I don't need to downcast to char * everywhere, only in ?:
7626        inside return suggests a const propagation bug in g++.  */
7627     if (ob && SvOBJECT(sv)) {
7628         char * const name = HvNAME_get(SvSTASH(sv));
7629         return name ? name : (char *) "__ANON__";
7630     }
7631     else {
7632         switch (SvTYPE(sv)) {
7633         case SVt_NULL:
7634         case SVt_IV:
7635         case SVt_NV:
7636         case SVt_RV:
7637         case SVt_PV:
7638         case SVt_PVIV:
7639         case SVt_PVNV:
7640         case SVt_PVMG:
7641                                 if (SvVOK(sv))
7642                                     return "VSTRING";
7643                                 if (SvROK(sv))
7644                                     return "REF";
7645                                 else
7646                                     return "SCALAR";
7647
7648         case SVt_PVLV:          return (char *)  (SvROK(sv) ? "REF"
7649                                 /* tied lvalues should appear to be
7650                                  * scalars for backwards compatitbility */
7651                                 : (LvTYPE(sv) == 't' || LvTYPE(sv) == 'T')
7652                                     ? "SCALAR" : "LVALUE");
7653         case SVt_PVAV:          return "ARRAY";
7654         case SVt_PVHV:          return "HASH";
7655         case SVt_PVCV:          return "CODE";
7656         case SVt_PVGV:          return "GLOB";
7657         case SVt_PVFM:          return "FORMAT";
7658         case SVt_PVIO:          return "IO";
7659         case SVt_BIND:          return "BIND";
7660         default:                return "UNKNOWN";
7661         }
7662     }
7663 }
7664
7665 /*
7666 =for apidoc sv_isobject
7667
7668 Returns a boolean indicating whether the SV is an RV pointing to a blessed
7669 object.  If the SV is not an RV, or if the object is not blessed, then this
7670 will return false.
7671
7672 =cut
7673 */
7674
7675 int
7676 Perl_sv_isobject(pTHX_ SV *sv)
7677 {
7678     if (!sv)
7679         return 0;
7680     SvGETMAGIC(sv);
7681     if (!SvROK(sv))
7682         return 0;
7683     sv = (SV*)SvRV(sv);
7684     if (!SvOBJECT(sv))
7685         return 0;
7686     return 1;
7687 }
7688
7689 /*
7690 =for apidoc sv_isa
7691
7692 Returns a boolean indicating whether the SV is blessed into the specified
7693 class.  This does not check for subtypes; use C<sv_derived_from> to verify
7694 an inheritance relationship.
7695
7696 =cut
7697 */
7698
7699 int
7700 Perl_sv_isa(pTHX_ SV *sv, const char *name)
7701 {
7702     const char *hvname;
7703     if (!sv)
7704         return 0;
7705     SvGETMAGIC(sv);
7706     if (!SvROK(sv))
7707         return 0;
7708     sv = (SV*)SvRV(sv);
7709     if (!SvOBJECT(sv))
7710         return 0;
7711     hvname = HvNAME_get(SvSTASH(sv));
7712     if (!hvname)
7713         return 0;
7714
7715     return strEQ(hvname, name);
7716 }
7717
7718 /*
7719 =for apidoc newSVrv
7720
7721 Creates a new SV for the RV, C<rv>, to point to.  If C<rv> is not an RV then
7722 it will be upgraded to one.  If C<classname> is non-null then the new SV will
7723 be blessed in the specified package.  The new SV is returned and its
7724 reference count is 1.
7725
7726 =cut
7727 */
7728
7729 SV*
7730 Perl_newSVrv(pTHX_ SV *rv, const char *classname)
7731 {
7732     dVAR;
7733     SV *sv;
7734
7735     new_SV(sv);
7736
7737     SV_CHECK_THINKFIRST_COW_DROP(rv);
7738     SvAMAGIC_off(rv);
7739
7740     if (SvTYPE(rv) >= SVt_PVMG) {
7741         const U32 refcnt = SvREFCNT(rv);
7742         SvREFCNT(rv) = 0;
7743         sv_clear(rv);
7744         SvFLAGS(rv) = 0;
7745         SvREFCNT(rv) = refcnt;
7746
7747         sv_upgrade(rv, SVt_RV);
7748     } else if (SvROK(rv)) {
7749         SvREFCNT_dec(SvRV(rv));
7750     } else if (SvTYPE(rv) < SVt_RV)
7751         sv_upgrade(rv, SVt_RV);
7752     else if (SvTYPE(rv) > SVt_RV) {
7753         SvPV_free(rv);
7754         SvCUR_set(rv, 0);
7755         SvLEN_set(rv, 0);
7756     }
7757
7758     SvOK_off(rv);
7759     SvRV_set(rv, sv);
7760     SvROK_on(rv);
7761
7762     if (classname) {
7763         HV* const stash = gv_stashpv(classname, TRUE);
7764         (void)sv_bless(rv, stash);
7765     }
7766     return sv;
7767 }
7768
7769 /*
7770 =for apidoc sv_setref_pv
7771
7772 Copies a pointer into a new SV, optionally blessing the SV.  The C<rv>
7773 argument will be upgraded to an RV.  That RV will be modified to point to
7774 the new SV.  If the C<pv> argument is NULL then C<PL_sv_undef> will be placed
7775 into the SV.  The C<classname> argument indicates the package for the
7776 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
7777 will have a reference count of 1, and the RV will be returned.
7778
7779 Do not use with other Perl types such as HV, AV, SV, CV, because those
7780 objects will become corrupted by the pointer copy process.
7781
7782 Note that C<sv_setref_pvn> copies the string while this copies the pointer.
7783
7784 =cut
7785 */
7786
7787 SV*
7788 Perl_sv_setref_pv(pTHX_ SV *rv, const char *classname, void *pv)
7789 {
7790     dVAR;
7791     if (!pv) {
7792         sv_setsv(rv, &PL_sv_undef);
7793         SvSETMAGIC(rv);
7794     }
7795     else
7796         sv_setiv(newSVrv(rv,classname), PTR2IV(pv));
7797     return rv;
7798 }
7799
7800 /*
7801 =for apidoc sv_setref_iv
7802
7803 Copies an integer into a new SV, optionally blessing the SV.  The C<rv>
7804 argument will be upgraded to an RV.  That RV will be modified to point to
7805 the new SV.  The C<classname> argument indicates the package for the
7806 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
7807 will have a reference count of 1, and the RV will be returned.
7808
7809 =cut
7810 */
7811
7812 SV*
7813 Perl_sv_setref_iv(pTHX_ SV *rv, const char *classname, IV iv)
7814 {
7815     sv_setiv(newSVrv(rv,classname), iv);
7816     return rv;
7817 }
7818
7819 /*
7820 =for apidoc sv_setref_uv
7821
7822 Copies an unsigned integer into a new SV, optionally blessing the SV.  The C<rv>
7823 argument will be upgraded to an RV.  That RV will be modified to point to
7824 the new SV.  The C<classname> argument indicates the package for the
7825 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
7826 will have a reference count of 1, and the RV will be returned.
7827
7828 =cut
7829 */
7830
7831 SV*
7832 Perl_sv_setref_uv(pTHX_ SV *rv, const char *classname, UV uv)
7833 {
7834     sv_setuv(newSVrv(rv,classname), uv);
7835     return rv;
7836 }
7837
7838 /*
7839 =for apidoc sv_setref_nv
7840
7841 Copies a double into a new SV, optionally blessing the SV.  The C<rv>
7842 argument will be upgraded to an RV.  That RV will be modified to point to
7843 the new SV.  The C<classname> argument indicates the package for the
7844 blessing.  Set C<classname> to C<NULL> to avoid the blessing.  The new SV
7845 will have a reference count of 1, and the RV will be returned.
7846
7847 =cut
7848 */
7849
7850 SV*
7851 Perl_sv_setref_nv(pTHX_ SV *rv, const char *classname, NV nv)
7852 {
7853     sv_setnv(newSVrv(rv,classname), nv);
7854     return rv;
7855 }
7856
7857 /*
7858 =for apidoc sv_setref_pvn
7859
7860 Copies a string into a new SV, optionally blessing the SV.  The length of the
7861 string must be specified with C<n>.  The C<rv> argument will be upgraded to
7862 an RV.  That RV will be modified to point to the new SV.  The C<classname>
7863 argument indicates the package for the blessing.  Set C<classname> to
7864 C<NULL> to avoid the blessing.  The new SV will have a reference count
7865 of 1, and the RV will be returned.
7866
7867 Note that C<sv_setref_pv> copies the pointer while this copies the string.
7868
7869 =cut
7870 */
7871
7872 SV*
7873 Perl_sv_setref_pvn(pTHX_ SV *rv, const char *classname, const char *pv, STRLEN n)
7874 {
7875     sv_setpvn(newSVrv(rv,classname), pv, n);
7876     return rv;
7877 }
7878
7879 /*
7880 =for apidoc sv_bless
7881
7882 Blesses an SV into a specified package.  The SV must be an RV.  The package
7883 must be designated by its stash (see C<gv_stashpv()>).  The reference count
7884 of the SV is unaffected.
7885
7886 =cut
7887 */
7888
7889 SV*
7890 Perl_sv_bless(pTHX_ SV *sv, HV *stash)
7891 {
7892     dVAR;
7893     SV *tmpRef;
7894     if (!SvROK(sv))
7895         Perl_croak(aTHX_ "Can't bless non-reference value");
7896     tmpRef = SvRV(sv);
7897     if (SvFLAGS(tmpRef) & (SVs_OBJECT|SVf_READONLY)) {
7898         if (SvREADONLY(tmpRef))
7899             Perl_croak(aTHX_ PL_no_modify);
7900         if (SvOBJECT(tmpRef)) {
7901             if (SvTYPE(tmpRef) != SVt_PVIO)
7902                 --PL_sv_objcount;
7903             SvREFCNT_dec(SvSTASH(tmpRef));
7904         }
7905     }
7906     SvOBJECT_on(tmpRef);
7907     if (SvTYPE(tmpRef) != SVt_PVIO)
7908         ++PL_sv_objcount;
7909     SvUPGRADE(tmpRef, SVt_PVMG);
7910     SvSTASH_set(tmpRef, (HV*)SvREFCNT_inc_simple(stash));
7911
7912     if (Gv_AMG(stash))
7913         SvAMAGIC_on(sv);
7914     else
7915         SvAMAGIC_off(sv);
7916
7917     if(SvSMAGICAL(tmpRef))
7918         if(mg_find(tmpRef, PERL_MAGIC_ext) || mg_find(tmpRef, PERL_MAGIC_uvar))
7919             mg_set(tmpRef);
7920
7921
7922
7923     return sv;
7924 }
7925
7926 /* Downgrades a PVGV to a PVMG.
7927  */
7928
7929 STATIC void
7930 S_sv_unglob(pTHX_ SV *sv)
7931 {
7932     dVAR;
7933     void *xpvmg;
7934     SV * const temp = sv_newmortal();
7935
7936     assert(SvTYPE(sv) == SVt_PVGV);
7937     SvFAKE_off(sv);
7938     gv_efullname3(temp, (GV *) sv, "*");
7939
7940     if (GvGP(sv)) {
7941         gp_free((GV*)sv);
7942     }
7943     if (GvSTASH(sv)) {
7944         sv_del_backref((SV*)GvSTASH(sv), sv);
7945         GvSTASH(sv) = NULL;
7946     }
7947     GvMULTI_off(sv);
7948     if (GvNAME_HEK(sv)) {
7949         unshare_hek(GvNAME_HEK(sv));
7950     }
7951     isGV_with_GP_off(sv);
7952
7953     /* need to keep SvANY(sv) in the right arena */
7954     xpvmg = new_XPVMG();
7955     StructCopy(SvANY(sv), xpvmg, XPVMG);
7956     del_XPVGV(SvANY(sv));
7957     SvANY(sv) = xpvmg;
7958
7959     SvFLAGS(sv) &= ~SVTYPEMASK;
7960     SvFLAGS(sv) |= SVt_PVMG;
7961
7962     /* Intentionally not calling any local SET magic, as this isn't so much a
7963        set operation as merely an internal storage change.  */
7964     sv_setsv_flags(sv, temp, 0);
7965 }
7966
7967 /*
7968 =for apidoc sv_unref_flags
7969
7970 Unsets the RV status of the SV, and decrements the reference count of
7971 whatever was being referenced by the RV.  This can almost be thought of
7972 as a reversal of C<newSVrv>.  The C<cflags> argument can contain
7973 C<SV_IMMEDIATE_UNREF> to force the reference count to be decremented
7974 (otherwise the decrementing is conditional on the reference count being
7975 different from one or the reference being a readonly SV).
7976 See C<SvROK_off>.
7977
7978 =cut
7979 */
7980
7981 void
7982 Perl_sv_unref_flags(pTHX_ SV *ref, U32 flags)
7983 {
7984     SV* const target = SvRV(ref);
7985
7986     if (SvWEAKREF(ref)) {
7987         sv_del_backref(target, ref);
7988         SvWEAKREF_off(ref);
7989         SvRV_set(ref, NULL);
7990         return;
7991     }
7992     SvRV_set(ref, NULL);
7993     SvROK_off(ref);
7994     /* You can't have a || SvREADONLY(target) here, as $a = $$a, where $a was
7995        assigned to as BEGIN {$a = \"Foo"} will fail.  */
7996     if (SvREFCNT(target) != 1 || (flags & SV_IMMEDIATE_UNREF))
7997         SvREFCNT_dec(target);
7998     else /* XXX Hack, but hard to make $a=$a->[1] work otherwise */
7999         sv_2mortal(target);     /* Schedule for freeing later */
8000 }
8001
8002 /*
8003 =for apidoc sv_untaint
8004
8005 Untaint an SV. Use C<SvTAINTED_off> instead.
8006 =cut
8007 */
8008
8009 void
8010 Perl_sv_untaint(pTHX_ SV *sv)
8011 {
8012     if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
8013         MAGIC * const mg = mg_find(sv, PERL_MAGIC_taint);
8014         if (mg)
8015             mg->mg_len &= ~1;
8016     }
8017 }
8018
8019 /*
8020 =for apidoc sv_tainted
8021
8022 Test an SV for taintedness. Use C<SvTAINTED> instead.
8023 =cut
8024 */
8025
8026 bool
8027 Perl_sv_tainted(pTHX_ SV *sv)
8028 {
8029     if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
8030         const MAGIC * const mg = mg_find(sv, PERL_MAGIC_taint);
8031         if (mg && (mg->mg_len & 1) )
8032             return TRUE;
8033     }
8034     return FALSE;
8035 }
8036
8037 /*
8038 =for apidoc sv_setpviv
8039
8040 Copies an integer into the given SV, also updating its string value.
8041 Does not handle 'set' magic.  See C<sv_setpviv_mg>.
8042
8043 =cut
8044 */
8045
8046 void
8047 Perl_sv_setpviv(pTHX_ SV *sv, IV iv)
8048 {
8049     char buf[TYPE_CHARS(UV)];
8050     char *ebuf;
8051     char * const ptr = uiv_2buf(buf, iv, 0, 0, &ebuf);
8052
8053     sv_setpvn(sv, ptr, ebuf - ptr);
8054 }
8055
8056 /*
8057 =for apidoc sv_setpviv_mg
8058
8059 Like C<sv_setpviv>, but also handles 'set' magic.
8060
8061 =cut
8062 */
8063
8064 void
8065 Perl_sv_setpviv_mg(pTHX_ SV *sv, IV iv)
8066 {
8067     sv_setpviv(sv, iv);
8068     SvSETMAGIC(sv);
8069 }
8070
8071 #if defined(PERL_IMPLICIT_CONTEXT)
8072
8073 /* pTHX_ magic can't cope with varargs, so this is a no-context
8074  * version of the main function, (which may itself be aliased to us).
8075  * Don't access this version directly.
8076  */
8077
8078 void
8079 Perl_sv_setpvf_nocontext(SV *sv, const char* pat, ...)
8080 {
8081     dTHX;
8082     va_list args;
8083     va_start(args, pat);
8084     sv_vsetpvf(sv, pat, &args);
8085     va_end(args);
8086 }
8087
8088 /* pTHX_ magic can't cope with varargs, so this is a no-context
8089  * version of the main function, (which may itself be aliased to us).
8090  * Don't access this version directly.
8091  */
8092
8093 void
8094 Perl_sv_setpvf_mg_nocontext(SV *sv, const char* pat, ...)
8095 {
8096     dTHX;
8097     va_list args;
8098     va_start(args, pat);
8099     sv_vsetpvf_mg(sv, pat, &args);
8100     va_end(args);
8101 }
8102 #endif
8103
8104 /*
8105 =for apidoc sv_setpvf
8106
8107 Works like C<sv_catpvf> but copies the text into the SV instead of
8108 appending it.  Does not handle 'set' magic.  See C<sv_setpvf_mg>.
8109
8110 =cut
8111 */
8112
8113 void
8114 Perl_sv_setpvf(pTHX_ SV *sv, const char* pat, ...)
8115 {
8116     va_list args;
8117     va_start(args, pat);
8118     sv_vsetpvf(sv, pat, &args);
8119     va_end(args);
8120 }
8121
8122 /*
8123 =for apidoc sv_vsetpvf
8124
8125 Works like C<sv_vcatpvf> but copies the text into the SV instead of
8126 appending it.  Does not handle 'set' magic.  See C<sv_vsetpvf_mg>.
8127
8128 Usually used via its frontend C<sv_setpvf>.
8129
8130 =cut
8131 */
8132
8133 void
8134 Perl_sv_vsetpvf(pTHX_ SV *sv, const char* pat, va_list* args)
8135 {
8136     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
8137 }
8138
8139 /*
8140 =for apidoc sv_setpvf_mg
8141
8142 Like C<sv_setpvf>, but also handles 'set' magic.
8143
8144 =cut
8145 */
8146
8147 void
8148 Perl_sv_setpvf_mg(pTHX_ SV *sv, const char* pat, ...)
8149 {
8150     va_list args;
8151     va_start(args, pat);
8152     sv_vsetpvf_mg(sv, pat, &args);
8153     va_end(args);
8154 }
8155
8156 /*
8157 =for apidoc sv_vsetpvf_mg
8158
8159 Like C<sv_vsetpvf>, but also handles 'set' magic.
8160
8161 Usually used via its frontend C<sv_setpvf_mg>.
8162
8163 =cut
8164 */
8165
8166 void
8167 Perl_sv_vsetpvf_mg(pTHX_ SV *sv, const char* pat, va_list* args)
8168 {
8169     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
8170     SvSETMAGIC(sv);
8171 }
8172
8173 #if defined(PERL_IMPLICIT_CONTEXT)
8174
8175 /* pTHX_ magic can't cope with varargs, so this is a no-context
8176  * version of the main function, (which may itself be aliased to us).
8177  * Don't access this version directly.
8178  */
8179
8180 void
8181 Perl_sv_catpvf_nocontext(SV *sv, const char* pat, ...)
8182 {
8183     dTHX;
8184     va_list args;
8185     va_start(args, pat);
8186     sv_vcatpvf(sv, pat, &args);
8187     va_end(args);
8188 }
8189
8190 /* pTHX_ magic can't cope with varargs, so this is a no-context
8191  * version of the main function, (which may itself be aliased to us).
8192  * Don't access this version directly.
8193  */
8194
8195 void
8196 Perl_sv_catpvf_mg_nocontext(SV *sv, const char* pat, ...)
8197 {
8198     dTHX;
8199     va_list args;
8200     va_start(args, pat);
8201     sv_vcatpvf_mg(sv, pat, &args);
8202     va_end(args);
8203 }
8204 #endif
8205
8206 /*
8207 =for apidoc sv_catpvf
8208
8209 Processes its arguments like C<sprintf> and appends the formatted
8210 output to an SV.  If the appended data contains "wide" characters
8211 (including, but not limited to, SVs with a UTF-8 PV formatted with %s,
8212 and characters >255 formatted with %c), the original SV might get
8213 upgraded to UTF-8.  Handles 'get' magic, but not 'set' magic.  See
8214 C<sv_catpvf_mg>. If the original SV was UTF-8, the pattern should be
8215 valid UTF-8; if the original SV was bytes, the pattern should be too.
8216
8217 =cut */
8218
8219 void
8220 Perl_sv_catpvf(pTHX_ SV *sv, const char* pat, ...)
8221 {
8222     va_list args;
8223     va_start(args, pat);
8224     sv_vcatpvf(sv, pat, &args);
8225     va_end(args);
8226 }
8227
8228 /*
8229 =for apidoc sv_vcatpvf
8230
8231 Processes its arguments like C<vsprintf> and appends the formatted output
8232 to an SV.  Does not handle 'set' magic.  See C<sv_vcatpvf_mg>.
8233
8234 Usually used via its frontend C<sv_catpvf>.
8235
8236 =cut
8237 */
8238
8239 void
8240 Perl_sv_vcatpvf(pTHX_ SV *sv, const char* pat, va_list* args)
8241 {
8242     sv_vcatpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
8243 }
8244
8245 /*
8246 =for apidoc sv_catpvf_mg
8247
8248 Like C<sv_catpvf>, but also handles 'set' magic.
8249
8250 =cut
8251 */
8252
8253 void
8254 Perl_sv_catpvf_mg(pTHX_ SV *sv, const char* pat, ...)
8255 {
8256     va_list args;
8257     va_start(args, pat);
8258     sv_vcatpvf_mg(sv, pat, &args);
8259     va_end(args);
8260 }
8261
8262 /*
8263 =for apidoc sv_vcatpvf_mg
8264
8265 Like C<sv_vcatpvf>, but also handles 'set' magic.
8266
8267 Usually used via its frontend C<sv_catpvf_mg>.
8268
8269 =cut
8270 */
8271
8272 void
8273 Perl_sv_vcatpvf_mg(pTHX_ SV *sv, const char* pat, va_list* args)
8274 {
8275     sv_vcatpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
8276     SvSETMAGIC(sv);
8277 }
8278
8279 /*
8280 =for apidoc sv_vsetpvfn
8281
8282 Works like C<sv_vcatpvfn> but copies the text into the SV instead of
8283 appending it.
8284
8285 Usually used via one of its frontends C<sv_vsetpvf> and C<sv_vsetpvf_mg>.
8286
8287 =cut
8288 */
8289
8290 void
8291 Perl_sv_vsetpvfn(pTHX_ SV *sv, const char *pat, STRLEN patlen, va_list *args, SV **svargs, I32 svmax, bool *maybe_tainted)
8292 {
8293     sv_setpvn(sv, "", 0);
8294     sv_vcatpvfn(sv, pat, patlen, args, svargs, svmax, maybe_tainted);
8295 }
8296
8297 STATIC I32
8298 S_expect_number(pTHX_ char** pattern)
8299 {
8300     dVAR;
8301     I32 var = 0;
8302     switch (**pattern) {
8303     case '1': case '2': case '3':
8304     case '4': case '5': case '6':
8305     case '7': case '8': case '9':
8306         var = *(*pattern)++ - '0';
8307         while (isDIGIT(**pattern)) {
8308             const I32 tmp = var * 10 + (*(*pattern)++ - '0');
8309             if (tmp < var)
8310                 Perl_croak(aTHX_ "Integer overflow in format string for %s", (PL_op ? OP_NAME(PL_op) : "sv_vcatpvfn"));
8311             var = tmp;
8312         }
8313     }
8314     return var;
8315 }
8316
8317 STATIC char *
8318 S_F0convert(NV nv, char *endbuf, STRLEN *len)
8319 {
8320     const int neg = nv < 0;
8321     UV uv;
8322
8323     if (neg)
8324         nv = -nv;
8325     if (nv < UV_MAX) {
8326         char *p = endbuf;
8327         nv += 0.5;
8328         uv = (UV)nv;
8329         if (uv & 1 && uv == nv)
8330             uv--;                       /* Round to even */
8331         do {
8332             const unsigned dig = uv % 10;
8333             *--p = '0' + dig;
8334         } while (uv /= 10);
8335         if (neg)
8336             *--p = '-';
8337         *len = endbuf - p;
8338         return p;
8339     }
8340     return NULL;
8341 }
8342
8343
8344 /*
8345 =for apidoc sv_vcatpvfn
8346
8347 Processes its arguments like C<vsprintf> and appends the formatted output
8348 to an SV.  Uses an array of SVs if the C style variable argument list is
8349 missing (NULL).  When running with taint checks enabled, indicates via
8350 C<maybe_tainted> if results are untrustworthy (often due to the use of
8351 locales).
8352
8353 Usually used via one of its frontends C<sv_vcatpvf> and C<sv_vcatpvf_mg>.
8354
8355 =cut
8356 */
8357
8358
8359 #define VECTORIZE_ARGS  vecsv = va_arg(*args, SV*);\
8360                         vecstr = (U8*)SvPV_const(vecsv,veclen);\
8361                         vec_utf8 = DO_UTF8(vecsv);
8362
8363 /* XXX maybe_tainted is never assigned to, so the doc above is lying. */
8364
8365 void
8366 Perl_sv_vcatpvfn(pTHX_ SV *sv, const char *pat, STRLEN patlen, va_list *args, SV **svargs, I32 svmax, bool *maybe_tainted)
8367 {
8368     dVAR;
8369     char *p;
8370     char *q;
8371     const char *patend;
8372     STRLEN origlen;
8373     I32 svix = 0;
8374     static const char nullstr[] = "(null)";
8375     SV *argsv = NULL;
8376     bool has_utf8 = DO_UTF8(sv);    /* has the result utf8? */
8377     const bool pat_utf8 = has_utf8; /* the pattern is in utf8? */
8378     SV *nsv = NULL;
8379     /* Times 4: a decimal digit takes more than 3 binary digits.
8380      * NV_DIG: mantissa takes than many decimal digits.
8381      * Plus 32: Playing safe. */
8382     char ebuf[IV_DIG * 4 + NV_DIG + 32];
8383     /* large enough for "%#.#f" --chip */
8384     /* what about long double NVs? --jhi */
8385
8386     PERL_UNUSED_ARG(maybe_tainted);
8387
8388     /* no matter what, this is a string now */
8389     (void)SvPV_force(sv, origlen);
8390
8391     /* special-case "", "%s", and "%-p" (SVf - see below) */
8392     if (patlen == 0)
8393         return;
8394     if (patlen == 2 && pat[0] == '%' && pat[1] == 's') {
8395         if (args) {
8396             const char * const s = va_arg(*args, char*);
8397             sv_catpv(sv, s ? s : nullstr);
8398         }
8399         else if (svix < svmax) {
8400             sv_catsv(sv, *svargs);
8401         }
8402         return;
8403     }
8404     if (args && patlen == 3 && pat[0] == '%' &&
8405                 pat[1] == '-' && pat[2] == 'p') {
8406         argsv = va_arg(*args, SV*);
8407         sv_catsv(sv, argsv);
8408         return;
8409     }
8410
8411 #ifndef USE_LONG_DOUBLE
8412     /* special-case "%.<number>[gf]" */
8413     if ( !args && patlen <= 5 && pat[0] == '%' && pat[1] == '.'
8414          && (pat[patlen-1] == 'g' || pat[patlen-1] == 'f') ) {
8415         unsigned digits = 0;
8416         const char *pp;
8417
8418         pp = pat + 2;
8419         while (*pp >= '0' && *pp <= '9')
8420             digits = 10 * digits + (*pp++ - '0');
8421         if (pp - pat == (int)patlen - 1) {
8422             NV nv;
8423
8424             if (svix < svmax)
8425                 nv = SvNV(*svargs);
8426             else
8427                 return;
8428             if (*pp == 'g') {
8429                 /* Add check for digits != 0 because it seems that some
8430                    gconverts are buggy in this case, and we don't yet have
8431                    a Configure test for this.  */
8432                 if (digits && digits < sizeof(ebuf) - NV_DIG - 10) {
8433                      /* 0, point, slack */
8434                     Gconvert(nv, (int)digits, 0, ebuf);
8435                     sv_catpv(sv, ebuf);
8436                     if (*ebuf)  /* May return an empty string for digits==0 */
8437                         return;
8438                 }
8439             } else if (!digits) {
8440                 STRLEN l;
8441
8442                 if ((p = F0convert(nv, ebuf + sizeof ebuf, &l))) {
8443                     sv_catpvn(sv, p, l);
8444                     return;
8445                 }
8446             }
8447         }
8448     }
8449 #endif /* !USE_LONG_DOUBLE */
8450
8451     if (!args && svix < svmax && DO_UTF8(*svargs))
8452         has_utf8 = TRUE;
8453
8454     patend = (char*)pat + patlen;
8455     for (p = (char*)pat; p < patend; p = q) {
8456         bool alt = FALSE;
8457         bool left = FALSE;
8458         bool vectorize = FALSE;
8459         bool vectorarg = FALSE;
8460         bool vec_utf8 = FALSE;
8461         char fill = ' ';
8462         char plus = 0;
8463         char intsize = 0;
8464         STRLEN width = 0;
8465         STRLEN zeros = 0;
8466         bool has_precis = FALSE;
8467         STRLEN precis = 0;
8468         const I32 osvix = svix;
8469         bool is_utf8 = FALSE;  /* is this item utf8?   */
8470 #ifdef HAS_LDBL_SPRINTF_BUG
8471         /* This is to try to fix a bug with irix/nonstop-ux/powerux and
8472            with sfio - Allen <allens@cpan.org> */
8473         bool fix_ldbl_sprintf_bug = FALSE;
8474 #endif
8475
8476         char esignbuf[4];
8477         U8 utf8buf[UTF8_MAXBYTES+1];
8478         STRLEN esignlen = 0;
8479
8480         const char *eptr = NULL;
8481         STRLEN elen = 0;
8482         SV *vecsv = NULL;
8483         const U8 *vecstr = NULL;
8484         STRLEN veclen = 0;
8485         char c = 0;
8486         int i;
8487         unsigned base = 0;
8488         IV iv = 0;
8489         UV uv = 0;
8490         /* we need a long double target in case HAS_LONG_DOUBLE but
8491            not USE_LONG_DOUBLE
8492         */
8493 #if defined(HAS_LONG_DOUBLE) && LONG_DOUBLESIZE > DOUBLESIZE
8494         long double nv;
8495 #else
8496         NV nv;
8497 #endif
8498         STRLEN have;
8499         STRLEN need;
8500         STRLEN gap;
8501         const char *dotstr = ".";
8502         STRLEN dotstrlen = 1;
8503         I32 efix = 0; /* explicit format parameter index */
8504         I32 ewix = 0; /* explicit width index */
8505         I32 epix = 0; /* explicit precision index */
8506         I32 evix = 0; /* explicit vector index */
8507         bool asterisk = FALSE;
8508
8509         /* echo everything up to the next format specification */
8510         for (q = p; q < patend && *q != '%'; ++q) ;
8511         if (q > p) {
8512             if (has_utf8 && !pat_utf8)
8513                 sv_catpvn_utf8_upgrade(sv, p, q - p, nsv);
8514             else
8515                 sv_catpvn(sv, p, q - p);
8516             p = q;
8517         }
8518         if (q++ >= patend)
8519             break;
8520
8521 /*
8522     We allow format specification elements in this order:
8523         \d+\$              explicit format parameter index
8524         [-+ 0#]+           flags
8525         v|\*(\d+\$)?v      vector with optional (optionally specified) arg
8526         0                  flag (as above): repeated to allow "v02"     
8527         \d+|\*(\d+\$)?     width using optional (optionally specified) arg
8528         \.(\d*|\*(\d+\$)?) precision using optional (optionally specified) arg
8529         [hlqLV]            size
8530     [%bcdefginopsuxDFOUX] format (mandatory)
8531 */
8532
8533         if (args) {
8534 /*  
8535         As of perl5.9.3, printf format checking is on by default.
8536         Internally, perl uses %p formats to provide an escape to
8537         some extended formatting.  This block deals with those
8538         extensions: if it does not match, (char*)q is reset and
8539         the normal format processing code is used.
8540
8541         Currently defined extensions are:
8542                 %p              include pointer address (standard)      
8543                 %-p     (SVf)   include an SV (previously %_)
8544                 %-<num>p        include an SV with precision <num>      
8545                 %1p     (VDf)   include a v-string (as %vd)
8546                 %<num>p         reserved for future extensions
8547
8548         Robin Barker 2005-07-14
8549 */
8550             char* r = q; 
8551             bool sv = FALSE;    
8552             STRLEN n = 0;
8553             if (*q == '-')
8554                 sv = *q++;
8555             n = expect_number(&q);
8556             if (*q++ == 'p') {
8557                 if (sv) {                       /* SVf */
8558                     if (n) {
8559                         precis = n;
8560                         has_precis = TRUE;
8561                     }
8562                     argsv = va_arg(*args, SV*);
8563                     eptr = SvPVx_const(argsv, elen);
8564                     if (DO_UTF8(argsv))
8565                         is_utf8 = TRUE;
8566                     goto string;
8567                 }
8568 #if vdNUMBER
8569                 else if (n == vdNUMBER) {       /* VDf */
8570                     vectorize = TRUE;
8571                     VECTORIZE_ARGS
8572                     goto format_vd;
8573                 }
8574 #endif
8575                 else if (n) {
8576                     if (ckWARN_d(WARN_INTERNAL))
8577                         Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
8578                         "internal %%<num>p might conflict with future printf extensions");
8579                 }
8580             }
8581             q = r; 
8582         }
8583
8584         if ( (width = expect_number(&q)) ) {
8585             if (*q == '$') {
8586                 ++q;
8587                 efix = width;
8588             } else {
8589                 goto gotwidth;
8590             }
8591         }
8592
8593         /* FLAGS */
8594
8595         while (*q) {
8596             switch (*q) {
8597             case ' ':
8598             case '+':
8599                 if (plus == '+' && *q == ' ') /* '+' over ' ' */
8600                     q++;
8601                 else
8602                     plus = *q++;
8603                 continue;
8604
8605             case '-':
8606                 left = TRUE;
8607                 q++;
8608                 continue;
8609
8610             case '0':
8611                 fill = *q++;
8612                 continue;
8613
8614             case '#':
8615                 alt = TRUE;
8616                 q++;
8617                 continue;
8618
8619             default:
8620                 break;
8621             }
8622             break;
8623         }
8624
8625       tryasterisk:
8626         if (*q == '*') {
8627             q++;
8628             if ( (ewix = expect_number(&q)) )
8629                 if (*q++ != '$')
8630                     goto unknown;
8631             asterisk = TRUE;
8632         }
8633         if (*q == 'v') {
8634             q++;
8635             if (vectorize)
8636                 goto unknown;
8637             if ((vectorarg = asterisk)) {
8638                 evix = ewix;
8639                 ewix = 0;
8640                 asterisk = FALSE;
8641             }
8642             vectorize = TRUE;
8643             goto tryasterisk;
8644         }
8645
8646         if (!asterisk)
8647         {
8648             if( *q == '0' )
8649                 fill = *q++;
8650             width = expect_number(&q);
8651         }
8652
8653         if (vectorize) {
8654             if (vectorarg) {
8655                 if (args)
8656                     vecsv = va_arg(*args, SV*);
8657                 else if (evix) {
8658                     vecsv = (evix > 0 && evix <= svmax)
8659                         ? svargs[evix-1] : &PL_sv_undef;
8660                 } else {
8661                     vecsv = svix < svmax ? svargs[svix++] : &PL_sv_undef;
8662                 }
8663                 dotstr = SvPV_const(vecsv, dotstrlen);
8664                 /* Keep the DO_UTF8 test *after* the SvPV call, else things go
8665                    bad with tied or overloaded values that return UTF8.  */
8666                 if (DO_UTF8(vecsv))
8667                     is_utf8 = TRUE;
8668                 else if (has_utf8) {
8669                     vecsv = sv_mortalcopy(vecsv);
8670                     sv_utf8_upgrade(vecsv);
8671                     dotstr = SvPV_const(vecsv, dotstrlen);
8672                     is_utf8 = TRUE;
8673                 }                   
8674             }
8675             if (args) {
8676                 VECTORIZE_ARGS
8677             }
8678             else if (efix ? (efix > 0 && efix <= svmax) : svix < svmax) {
8679                 vecsv = svargs[efix ? efix-1 : svix++];
8680                 vecstr = (U8*)SvPV_const(vecsv,veclen);
8681                 vec_utf8 = DO_UTF8(vecsv);
8682
8683                 /* if this is a version object, we need to convert
8684                  * back into v-string notation and then let the
8685                  * vectorize happen normally
8686                  */
8687                 if (sv_derived_from(vecsv, "version")) {
8688                     char *version = savesvpv(vecsv);
8689                     if ( hv_exists((HV*)SvRV(vecsv), "alpha", 5 ) ) {
8690                         Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
8691                         "vector argument not supported with alpha versions");
8692                         goto unknown;
8693                     }
8694                     vecsv = sv_newmortal();
8695                     /* scan_vstring is expected to be called during
8696                      * tokenization, so we need to fake up the end
8697                      * of the buffer for it
8698                      */
8699                     PL_bufend = version + veclen;
8700                     scan_vstring(version, vecsv);
8701                     vecstr = (U8*)SvPV_const(vecsv, veclen);
8702                     vec_utf8 = DO_UTF8(vecsv);
8703                     Safefree(version);
8704                 }
8705             }
8706             else {
8707                 vecstr = (U8*)"";
8708                 veclen = 0;
8709             }
8710         }
8711
8712         if (asterisk) {
8713             if (args)
8714                 i = va_arg(*args, int);
8715             else
8716                 i = (ewix ? ewix <= svmax : svix < svmax) ?
8717                     SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
8718             left |= (i < 0);
8719             width = (i < 0) ? -i : i;
8720         }
8721       gotwidth:
8722
8723         /* PRECISION */
8724
8725         if (*q == '.') {
8726             q++;
8727             if (*q == '*') {
8728                 q++;
8729                 if ( ((epix = expect_number(&q))) && (*q++ != '$') )
8730                     goto unknown;
8731                 /* XXX: todo, support specified precision parameter */
8732                 if (epix)
8733                     goto unknown;
8734                 if (args)
8735                     i = va_arg(*args, int);
8736                 else
8737                     i = (ewix ? ewix <= svmax : svix < svmax)
8738                         ? SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
8739                 precis = i;
8740                 has_precis = !(i < 0);
8741             }
8742             else {
8743                 precis = 0;
8744                 while (isDIGIT(*q))
8745                     precis = precis * 10 + (*q++ - '0');
8746                 has_precis = TRUE;
8747             }
8748         }
8749
8750         /* SIZE */
8751
8752         switch (*q) {
8753 #ifdef WIN32
8754         case 'I':                       /* Ix, I32x, and I64x */
8755 #  ifdef WIN64
8756             if (q[1] == '6' && q[2] == '4') {
8757                 q += 3;
8758                 intsize = 'q';
8759                 break;
8760             }
8761 #  endif
8762             if (q[1] == '3' && q[2] == '2') {
8763                 q += 3;
8764                 break;
8765             }
8766 #  ifdef WIN64
8767             intsize = 'q';
8768 #  endif
8769             q++;
8770             break;
8771 #endif
8772 #if defined(HAS_QUAD) || defined(HAS_LONG_DOUBLE)
8773         case 'L':                       /* Ld */
8774             /*FALLTHROUGH*/
8775 #ifdef HAS_QUAD
8776         case 'q':                       /* qd */
8777 #endif
8778             intsize = 'q';
8779             q++;
8780             break;
8781 #endif
8782         case 'l':
8783 #if defined(HAS_QUAD) || defined(HAS_LONG_DOUBLE)
8784             if (*(q + 1) == 'l') {      /* lld, llf */
8785                 intsize = 'q';
8786                 q += 2;
8787                 break;
8788              }
8789 #endif
8790             /*FALLTHROUGH*/
8791         case 'h':
8792             /*FALLTHROUGH*/
8793         case 'V':
8794             intsize = *q++;
8795             break;
8796         }
8797
8798         /* CONVERSION */
8799
8800         if (*q == '%') {
8801             eptr = q++;
8802             elen = 1;
8803             if (vectorize) {
8804                 c = '%';
8805                 goto unknown;
8806             }
8807             goto string;
8808         }
8809
8810         if (!vectorize && !args) {
8811             if (efix) {
8812                 const I32 i = efix-1;
8813                 argsv = (i >= 0 && i < svmax) ? svargs[i] : &PL_sv_undef;
8814             } else {
8815                 argsv = (svix >= 0 && svix < svmax)
8816                     ? svargs[svix++] : &PL_sv_undef;
8817             }
8818         }
8819
8820         switch (c = *q++) {
8821
8822             /* STRINGS */
8823
8824         case 'c':
8825             if (vectorize)
8826                 goto unknown;
8827             uv = (args) ? va_arg(*args, int) : SvIVx(argsv);
8828             if ((uv > 255 ||
8829                  (!UNI_IS_INVARIANT(uv) && SvUTF8(sv)))
8830                 && !IN_BYTES) {
8831                 eptr = (char*)utf8buf;
8832                 elen = uvchr_to_utf8((U8*)eptr, uv) - utf8buf;
8833                 is_utf8 = TRUE;
8834             }
8835             else {
8836                 c = (char)uv;
8837                 eptr = &c;
8838                 elen = 1;
8839             }
8840             goto string;
8841
8842         case 's':
8843             if (vectorize)
8844                 goto unknown;
8845             if (args) {
8846                 eptr = va_arg(*args, char*);
8847                 if (eptr)
8848 #ifdef MACOS_TRADITIONAL
8849                   /* On MacOS, %#s format is used for Pascal strings */
8850                   if (alt)
8851                     elen = *eptr++;
8852                   else
8853 #endif
8854                     elen = strlen(eptr);
8855                 else {
8856                     eptr = (char *)nullstr;
8857                     elen = sizeof nullstr - 1;
8858                 }
8859             }
8860             else {
8861                 eptr = SvPVx_const(argsv, elen);
8862                 if (DO_UTF8(argsv)) {
8863                     I32 old_precis = precis;
8864                     if (has_precis && precis < elen) {
8865                         I32 p = precis;
8866                         sv_pos_u2b(argsv, &p, 0); /* sticks at end */
8867                         precis = p;
8868                     }
8869                     if (width) { /* fudge width (can't fudge elen) */
8870                         if (has_precis && precis < elen)
8871                             width += precis - old_precis;
8872                         else
8873                             width += elen - sv_len_utf8(argsv);
8874                     }
8875                     is_utf8 = TRUE;
8876                 }
8877             }
8878
8879         string:
8880             if (has_precis && elen > precis)
8881                 elen = precis;
8882             break;
8883
8884             /* INTEGERS */
8885
8886         case 'p':
8887             if (alt || vectorize)
8888                 goto unknown;
8889             uv = PTR2UV(args ? va_arg(*args, void*) : argsv);
8890             base = 16;
8891             goto integer;
8892
8893         case 'D':
8894 #ifdef IV_IS_QUAD
8895             intsize = 'q';
8896 #else
8897             intsize = 'l';
8898 #endif
8899             /*FALLTHROUGH*/
8900         case 'd':
8901         case 'i':
8902 #if vdNUMBER
8903         format_vd:
8904 #endif
8905             if (vectorize) {
8906                 STRLEN ulen;
8907                 if (!veclen)
8908                     continue;
8909                 if (vec_utf8)
8910                     uv = utf8n_to_uvchr(vecstr, veclen, &ulen,
8911                                         UTF8_ALLOW_ANYUV);
8912                 else {
8913                     uv = *vecstr;
8914                     ulen = 1;
8915                 }
8916                 vecstr += ulen;
8917                 veclen -= ulen;
8918                 if (plus)
8919                      esignbuf[esignlen++] = plus;
8920             }
8921             else if (args) {
8922                 switch (intsize) {
8923                 case 'h':       iv = (short)va_arg(*args, int); break;
8924                 case 'l':       iv = va_arg(*args, long); break;
8925                 case 'V':       iv = va_arg(*args, IV); break;
8926                 default:        iv = va_arg(*args, int); break;
8927 #ifdef HAS_QUAD
8928                 case 'q':       iv = va_arg(*args, Quad_t); break;
8929 #endif
8930                 }
8931             }
8932             else {
8933                 IV tiv = SvIVx(argsv); /* work around GCC bug #13488 */
8934                 switch (intsize) {
8935                 case 'h':       iv = (short)tiv; break;
8936                 case 'l':       iv = (long)tiv; break;
8937                 case 'V':
8938                 default:        iv = tiv; break;
8939 #ifdef HAS_QUAD
8940                 case 'q':       iv = (Quad_t)tiv; break;
8941 #endif
8942                 }
8943             }
8944             if ( !vectorize )   /* we already set uv above */
8945             {
8946                 if (iv >= 0) {
8947                     uv = iv;
8948                     if (plus)
8949                         esignbuf[esignlen++] = plus;
8950                 }
8951                 else {
8952                     uv = -iv;
8953                     esignbuf[esignlen++] = '-';
8954                 }
8955             }
8956             base = 10;
8957             goto integer;
8958
8959         case 'U':
8960 #ifdef IV_IS_QUAD
8961             intsize = 'q';
8962 #else
8963             intsize = 'l';
8964 #endif
8965             /*FALLTHROUGH*/
8966         case 'u':
8967             base = 10;
8968             goto uns_integer;
8969
8970         case 'B':
8971         case 'b':
8972             base = 2;
8973             goto uns_integer;
8974
8975         case 'O':
8976 #ifdef IV_IS_QUAD
8977             intsize = 'q';
8978 #else
8979             intsize = 'l';
8980 #endif
8981             /*FALLTHROUGH*/
8982         case 'o':
8983             base = 8;
8984             goto uns_integer;
8985
8986         case 'X':
8987         case 'x':
8988             base = 16;
8989
8990         uns_integer:
8991             if (vectorize) {
8992                 STRLEN ulen;
8993         vector:
8994                 if (!veclen)
8995                     continue;
8996                 if (vec_utf8)
8997                     uv = utf8n_to_uvchr(vecstr, veclen, &ulen,
8998                                         UTF8_ALLOW_ANYUV);
8999                 else {
9000                     uv = *vecstr;
9001                     ulen = 1;
9002                 }
9003                 vecstr += ulen;
9004                 veclen -= ulen;
9005             }
9006             else if (args) {
9007                 switch (intsize) {
9008                 case 'h':  uv = (unsigned short)va_arg(*args, unsigned); break;
9009                 case 'l':  uv = va_arg(*args, unsigned long); break;
9010                 case 'V':  uv = va_arg(*args, UV); break;
9011                 default:   uv = va_arg(*args, unsigned); break;
9012 #ifdef HAS_QUAD
9013                 case 'q':  uv = va_arg(*args, Uquad_t); break;
9014 #endif
9015                 }
9016             }
9017             else {
9018                 UV tuv = SvUVx(argsv); /* work around GCC bug #13488 */
9019                 switch (intsize) {
9020                 case 'h':       uv = (unsigned short)tuv; break;
9021                 case 'l':       uv = (unsigned long)tuv; break;
9022                 case 'V':
9023                 default:        uv = tuv; break;
9024 #ifdef HAS_QUAD
9025                 case 'q':       uv = (Uquad_t)tuv; break;
9026 #endif
9027                 }
9028             }
9029
9030         integer:
9031             {
9032                 char *ptr = ebuf + sizeof ebuf;
9033                 bool tempalt = uv ? alt : FALSE; /* Vectors can't change alt */
9034                 zeros = 0;
9035
9036                 switch (base) {
9037                     unsigned dig;
9038                 case 16:
9039                     p = (char *)((c == 'X') ? PL_hexdigit + 16 : PL_hexdigit);
9040                     do {
9041                         dig = uv & 15;
9042                         *--ptr = p[dig];
9043                     } while (uv >>= 4);
9044                     if (tempalt) {
9045                         esignbuf[esignlen++] = '0';
9046                         esignbuf[esignlen++] = c;  /* 'x' or 'X' */
9047                     }
9048                     break;
9049                 case 8:
9050                     do {
9051                         dig = uv & 7;
9052                         *--ptr = '0' + dig;
9053                     } while (uv >>= 3);
9054                     if (alt && *ptr != '0')
9055                         *--ptr = '0';
9056                     break;
9057                 case 2:
9058                     do {
9059                         dig = uv & 1;
9060                         *--ptr = '0' + dig;
9061                     } while (uv >>= 1);
9062                     if (tempalt) {
9063                         esignbuf[esignlen++] = '0';
9064                         esignbuf[esignlen++] = c;
9065                     }
9066                     break;
9067                 default:                /* it had better be ten or less */
9068                     do {
9069                         dig = uv % base;
9070                         *--ptr = '0' + dig;
9071                     } while (uv /= base);
9072                     break;
9073                 }
9074                 elen = (ebuf + sizeof ebuf) - ptr;
9075                 eptr = ptr;
9076                 if (has_precis) {
9077                     if (precis > elen)
9078                         zeros = precis - elen;
9079                     else if (precis == 0 && elen == 1 && *eptr == '0'
9080                              && !(base == 8 && alt)) /* "%#.0o" prints "0" */
9081                         elen = 0;
9082
9083                 /* a precision nullifies the 0 flag. */
9084                     if (fill == '0')
9085                         fill = ' ';
9086                 }
9087             }
9088             break;
9089
9090             /* FLOATING POINT */
9091
9092         case 'F':
9093             c = 'f';            /* maybe %F isn't supported here */
9094             /*FALLTHROUGH*/
9095         case 'e': case 'E':
9096         case 'f':
9097         case 'g': case 'G':
9098             if (vectorize)
9099                 goto unknown;
9100
9101             /* This is evil, but floating point is even more evil */
9102
9103             /* for SV-style calling, we can only get NV
9104                for C-style calling, we assume %f is double;
9105                for simplicity we allow any of %Lf, %llf, %qf for long double
9106             */
9107             switch (intsize) {
9108             case 'V':
9109 #if defined(USE_LONG_DOUBLE)
9110                 intsize = 'q';
9111 #endif
9112                 break;
9113 /* [perl #20339] - we should accept and ignore %lf rather than die */
9114             case 'l':
9115                 /*FALLTHROUGH*/
9116             default:
9117 #if defined(USE_LONG_DOUBLE)
9118                 intsize = args ? 0 : 'q';
9119 #endif
9120                 break;
9121             case 'q':
9122 #if defined(HAS_LONG_DOUBLE)
9123                 break;
9124 #else
9125                 /*FALLTHROUGH*/
9126 #endif
9127             case 'h':
9128                 goto unknown;
9129             }
9130
9131             /* now we need (long double) if intsize == 'q', else (double) */
9132             nv = (args) ?
9133 #if LONG_DOUBLESIZE > DOUBLESIZE
9134                 intsize == 'q' ?
9135                     va_arg(*args, long double) :
9136                     va_arg(*args, double)
9137 #else
9138                     va_arg(*args, double)
9139 #endif
9140                 : SvNVx(argsv);
9141
9142             need = 0;
9143             if (c != 'e' && c != 'E') {
9144                 i = PERL_INT_MIN;
9145                 /* FIXME: if HAS_LONG_DOUBLE but not USE_LONG_DOUBLE this
9146                    will cast our (long double) to (double) */
9147                 (void)Perl_frexp(nv, &i);
9148                 if (i == PERL_INT_MIN)
9149                     Perl_die(aTHX_ "panic: frexp");
9150                 if (i > 0)
9151                     need = BIT_DIGITS(i);
9152             }
9153             need += has_precis ? precis : 6; /* known default */
9154
9155             if (need < width)
9156                 need = width;
9157
9158 #ifdef HAS_LDBL_SPRINTF_BUG
9159             /* This is to try to fix a bug with irix/nonstop-ux/powerux and
9160                with sfio - Allen <allens@cpan.org> */
9161
9162 #  ifdef DBL_MAX
9163 #    define MY_DBL_MAX DBL_MAX
9164 #  else /* XXX guessing! HUGE_VAL may be defined as infinity, so not using */
9165 #    if DOUBLESIZE >= 8
9166 #      define MY_DBL_MAX 1.7976931348623157E+308L
9167 #    else
9168 #      define MY_DBL_MAX 3.40282347E+38L
9169 #    endif
9170 #  endif
9171
9172 #  ifdef HAS_LDBL_SPRINTF_BUG_LESS1 /* only between -1L & 1L - Allen */
9173 #    define MY_DBL_MAX_BUG 1L
9174 #  else
9175 #    define MY_DBL_MAX_BUG MY_DBL_MAX
9176 #  endif
9177
9178 #  ifdef DBL_MIN
9179 #    define MY_DBL_MIN DBL_MIN
9180 #  else  /* XXX guessing! -Allen */
9181 #    if DOUBLESIZE >= 8
9182 #      define MY_DBL_MIN 2.2250738585072014E-308L
9183 #    else
9184 #      define MY_DBL_MIN 1.17549435E-38L
9185 #    endif
9186 #  endif
9187
9188             if ((intsize == 'q') && (c == 'f') &&
9189                 ((nv < MY_DBL_MAX_BUG) && (nv > -MY_DBL_MAX_BUG)) &&
9190                 (need < DBL_DIG)) {
9191                 /* it's going to be short enough that
9192                  * long double precision is not needed */
9193
9194                 if ((nv <= 0L) && (nv >= -0L))
9195                     fix_ldbl_sprintf_bug = TRUE; /* 0 is 0 - easiest */
9196                 else {
9197                     /* would use Perl_fp_class as a double-check but not
9198                      * functional on IRIX - see perl.h comments */
9199
9200                     if ((nv >= MY_DBL_MIN) || (nv <= -MY_DBL_MIN)) {
9201                         /* It's within the range that a double can represent */
9202 #if defined(DBL_MAX) && !defined(DBL_MIN)
9203                         if ((nv >= ((long double)1/DBL_MAX)) ||
9204                             (nv <= (-(long double)1/DBL_MAX)))
9205 #endif
9206                         fix_ldbl_sprintf_bug = TRUE;
9207                     }
9208                 }
9209                 if (fix_ldbl_sprintf_bug == TRUE) {
9210                     double temp;
9211
9212                     intsize = 0;
9213                     temp = (double)nv;
9214                     nv = (NV)temp;
9215                 }
9216             }
9217
9218 #  undef MY_DBL_MAX
9219 #  undef MY_DBL_MAX_BUG
9220 #  undef MY_DBL_MIN
9221
9222 #endif /* HAS_LDBL_SPRINTF_BUG */
9223
9224             need += 20; /* fudge factor */
9225             if (PL_efloatsize < need) {
9226                 Safefree(PL_efloatbuf);
9227                 PL_efloatsize = need + 20; /* more fudge */
9228                 Newx(PL_efloatbuf, PL_efloatsize, char);
9229                 PL_efloatbuf[0] = '\0';
9230             }
9231
9232             if ( !(width || left || plus || alt) && fill != '0'
9233                  && has_precis && intsize != 'q' ) {    /* Shortcuts */
9234                 /* See earlier comment about buggy Gconvert when digits,
9235                    aka precis is 0  */
9236                 if ( c == 'g' && precis) {
9237                     Gconvert((NV)nv, (int)precis, 0, PL_efloatbuf);
9238                     /* May return an empty string for digits==0 */
9239                     if (*PL_efloatbuf) {
9240                         elen = strlen(PL_efloatbuf);
9241                         goto float_converted;
9242                     }
9243                 } else if ( c == 'f' && !precis) {
9244                     if ((eptr = F0convert(nv, ebuf + sizeof ebuf, &elen)))
9245                         break;
9246                 }
9247             }
9248             {
9249                 char *ptr = ebuf + sizeof ebuf;
9250                 *--ptr = '\0';
9251                 *--ptr = c;
9252                 /* FIXME: what to do if HAS_LONG_DOUBLE but not PERL_PRIfldbl? */
9253 #if defined(HAS_LONG_DOUBLE) && defined(PERL_PRIfldbl)
9254                 if (intsize == 'q') {
9255                     /* Copy the one or more characters in a long double
9256                      * format before the 'base' ([efgEFG]) character to
9257                      * the format string. */
9258                     static char const prifldbl[] = PERL_PRIfldbl;
9259                     char const *p = prifldbl + sizeof(prifldbl) - 3;
9260                     while (p >= prifldbl) { *--ptr = *p--; }
9261                 }
9262 #endif
9263                 if (has_precis) {
9264                     base = precis;
9265                     do { *--ptr = '0' + (base % 10); } while (base /= 10);
9266                     *--ptr = '.';
9267                 }
9268                 if (width) {
9269                     base = width;
9270                     do { *--ptr = '0' + (base % 10); } while (base /= 10);
9271                 }
9272                 if (fill == '0')
9273                     *--ptr = fill;
9274                 if (left)
9275                     *--ptr = '-';
9276                 if (plus)
9277                     *--ptr = plus;
9278                 if (alt)
9279                     *--ptr = '#';
9280                 *--ptr = '%';
9281
9282                 /* No taint.  Otherwise we are in the strange situation
9283                  * where printf() taints but print($float) doesn't.
9284                  * --jhi */
9285 #if defined(HAS_LONG_DOUBLE)
9286                 elen = ((intsize == 'q')
9287                         ? my_snprintf(PL_efloatbuf, PL_efloatsize, ptr, nv)
9288                         : my_snprintf(PL_efloatbuf, PL_efloatsize, ptr, (double)nv));
9289 #else
9290                 elen = my_sprintf(PL_efloatbuf, ptr, nv);
9291 #endif
9292             }
9293         float_converted:
9294             eptr = PL_efloatbuf;
9295             break;
9296
9297             /* SPECIAL */
9298
9299         case 'n':
9300             if (vectorize)
9301                 goto unknown;
9302             i = SvCUR(sv) - origlen;
9303             if (args) {
9304                 switch (intsize) {
9305                 case 'h':       *(va_arg(*args, short*)) = i; break;
9306                 default:        *(va_arg(*args, int*)) = i; break;
9307                 case 'l':       *(va_arg(*args, long*)) = i; break;
9308                 case 'V':       *(va_arg(*args, IV*)) = i; break;
9309 #ifdef HAS_QUAD
9310                 case 'q':       *(va_arg(*args, Quad_t*)) = i; break;
9311 #endif
9312                 }
9313             }
9314             else
9315                 sv_setuv_mg(argsv, (UV)i);
9316             continue;   /* not "break" */
9317
9318             /* UNKNOWN */
9319
9320         default:
9321       unknown:
9322             if (!args
9323                 && (PL_op->op_type == OP_PRTF || PL_op->op_type == OP_SPRINTF)
9324                 && ckWARN(WARN_PRINTF))
9325             {
9326                 SV * const msg = sv_newmortal();
9327                 Perl_sv_setpvf(aTHX_ msg, "Invalid conversion in %sprintf: ",
9328                           (PL_op->op_type == OP_PRTF) ? "" : "s");
9329                 if (c) {
9330                     if (isPRINT(c))
9331                         Perl_sv_catpvf(aTHX_ msg,
9332                                        "\"%%%c\"", c & 0xFF);
9333                     else
9334                         Perl_sv_catpvf(aTHX_ msg,
9335                                        "\"%%\\%03"UVof"\"",
9336                                        (UV)c & 0xFF);
9337                 } else
9338                     sv_catpvs(msg, "end of string");
9339                 Perl_warner(aTHX_ packWARN(WARN_PRINTF), "%"SVf, (void*)msg); /* yes, this is reentrant */
9340             }
9341
9342             /* output mangled stuff ... */
9343             if (c == '\0')
9344                 --q;
9345             eptr = p;
9346             elen = q - p;
9347
9348             /* ... right here, because formatting flags should not apply */
9349             SvGROW(sv, SvCUR(sv) + elen + 1);
9350             p = SvEND(sv);
9351             Copy(eptr, p, elen, char);
9352             p += elen;
9353             *p = '\0';
9354             SvCUR_set(sv, p - SvPVX_const(sv));
9355             svix = osvix;
9356             continue;   /* not "break" */
9357         }
9358
9359         if (is_utf8 != has_utf8) {
9360             if (is_utf8) {
9361                 if (SvCUR(sv))
9362                     sv_utf8_upgrade(sv);
9363             }
9364             else {
9365                 const STRLEN old_elen = elen;
9366                 SV * const nsv = sv_2mortal(newSVpvn(eptr, elen));
9367                 sv_utf8_upgrade(nsv);
9368                 eptr = SvPVX_const(nsv);
9369                 elen = SvCUR(nsv);
9370
9371                 if (width) { /* fudge width (can't fudge elen) */
9372                     width += elen - old_elen;
9373                 }
9374                 is_utf8 = TRUE;
9375             }
9376         }
9377
9378         have = esignlen + zeros + elen;
9379         if (have < zeros)
9380             Perl_croak_nocontext(PL_memory_wrap);
9381
9382         need = (have > width ? have : width);
9383         gap = need - have;
9384
9385         if (need >= (((STRLEN)~0) - SvCUR(sv) - dotstrlen - 1))
9386             Perl_croak_nocontext(PL_memory_wrap);
9387         SvGROW(sv, SvCUR(sv) + need + dotstrlen + 1);
9388         p = SvEND(sv);
9389         if (esignlen && fill == '0') {
9390             int i;
9391             for (i = 0; i < (int)esignlen; i++)
9392                 *p++ = esignbuf[i];
9393         }
9394         if (gap && !left) {
9395             memset(p, fill, gap);
9396             p += gap;
9397         }
9398         if (esignlen && fill != '0') {
9399             int i;
9400             for (i = 0; i < (int)esignlen; i++)
9401                 *p++ = esignbuf[i];
9402         }
9403         if (zeros) {
9404             int i;
9405             for (i = zeros; i; i--)
9406                 *p++ = '0';
9407         }
9408         if (elen) {
9409             Copy(eptr, p, elen, char);
9410             p += elen;
9411         }
9412         if (gap && left) {
9413             memset(p, ' ', gap);
9414             p += gap;
9415         }
9416         if (vectorize) {
9417             if (veclen) {
9418                 Copy(dotstr, p, dotstrlen, char);
9419                 p += dotstrlen;
9420             }
9421             else
9422                 vectorize = FALSE;              /* done iterating over vecstr */
9423         }
9424         if (is_utf8)
9425             has_utf8 = TRUE;
9426         if (has_utf8)
9427             SvUTF8_on(sv);
9428         *p = '\0';
9429         SvCUR_set(sv, p - SvPVX_const(sv));
9430         if (vectorize) {
9431             esignlen = 0;
9432             goto vector;
9433         }
9434     }
9435 }
9436
9437 /* =========================================================================
9438
9439 =head1 Cloning an interpreter
9440
9441 All the macros and functions in this section are for the private use of
9442 the main function, perl_clone().
9443
9444 The foo_dup() functions make an exact copy of an existing foo thinngy.
9445 During the course of a cloning, a hash table is used to map old addresses
9446 to new addresses. The table is created and manipulated with the
9447 ptr_table_* functions.
9448
9449 =cut
9450
9451 ============================================================================*/
9452
9453
9454 #if defined(USE_ITHREADS)
9455
9456 /* XXX Remove this so it doesn't have to go thru the macro and return for nothing */
9457 #ifndef GpREFCNT_inc
9458 #  define GpREFCNT_inc(gp)      ((gp) ? (++(gp)->gp_refcnt, (gp)) : (GP*)NULL)
9459 #endif
9460
9461
9462 /* Certain cases in Perl_ss_dup have been merged, by relying on the fact
9463    that currently av_dup, gv_dup and hv_dup are the same as sv_dup.
9464    If this changes, please unmerge ss_dup.  */
9465 #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
9466 #define sv_dup_inc_NN(s,t)      SvREFCNT_inc_NN(sv_dup(s,t))
9467 #define av_dup(s,t)     (AV*)sv_dup((SV*)s,t)
9468 #define av_dup_inc(s,t) (AV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9469 #define hv_dup(s,t)     (HV*)sv_dup((SV*)s,t)
9470 #define hv_dup_inc(s,t) (HV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9471 #define cv_dup(s,t)     (CV*)sv_dup((SV*)s,t)
9472 #define cv_dup_inc(s,t) (CV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9473 #define io_dup(s,t)     (IO*)sv_dup((SV*)s,t)
9474 #define io_dup_inc(s,t) (IO*)SvREFCNT_inc(sv_dup((SV*)s,t))
9475 #define gv_dup(s,t)     (GV*)sv_dup((SV*)s,t)
9476 #define gv_dup_inc(s,t) (GV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9477 #define SAVEPV(p)       ((p) ? savepv(p) : NULL)
9478 #define SAVEPVN(p,n)    ((p) ? savepvn(p,n) : NULL)
9479
9480
9481 /* duplicate a file handle */
9482
9483 PerlIO *
9484 Perl_fp_dup(pTHX_ PerlIO *fp, char type, CLONE_PARAMS *param)
9485 {
9486     PerlIO *ret;
9487
9488     PERL_UNUSED_ARG(type);
9489
9490     if (!fp)
9491         return (PerlIO*)NULL;
9492
9493     /* look for it in the table first */
9494     ret = (PerlIO*)ptr_table_fetch(PL_ptr_table, fp);
9495     if (ret)
9496         return ret;
9497
9498     /* create anew and remember what it is */
9499     ret = PerlIO_fdupopen(aTHX_ fp, param, PERLIO_DUP_CLONE);
9500     ptr_table_store(PL_ptr_table, fp, ret);
9501     return ret;
9502 }
9503
9504 /* duplicate a directory handle */
9505
9506 DIR *
9507 Perl_dirp_dup(pTHX_ DIR *dp)
9508 {
9509     PERL_UNUSED_CONTEXT;
9510     if (!dp)
9511         return (DIR*)NULL;
9512     /* XXX TODO */
9513     return dp;
9514 }
9515
9516 /* duplicate a typeglob */
9517
9518 GP *
9519 Perl_gp_dup(pTHX_ GP *gp, CLONE_PARAMS* param)
9520 {
9521     GP *ret;
9522
9523     if (!gp)
9524         return (GP*)NULL;
9525     /* look for it in the table first */
9526     ret = (GP*)ptr_table_fetch(PL_ptr_table, gp);
9527     if (ret)
9528         return ret;
9529
9530     /* create anew and remember what it is */
9531     Newxz(ret, 1, GP);
9532     ptr_table_store(PL_ptr_table, gp, ret);
9533
9534     /* clone */
9535     ret->gp_refcnt      = 0;                    /* must be before any other dups! */
9536     ret->gp_sv          = sv_dup_inc(gp->gp_sv, param);
9537     ret->gp_io          = io_dup_inc(gp->gp_io, param);
9538     ret->gp_form        = cv_dup_inc(gp->gp_form, param);
9539     ret->gp_av          = av_dup_inc(gp->gp_av, param);
9540     ret->gp_hv          = hv_dup_inc(gp->gp_hv, param);
9541     ret->gp_egv = gv_dup(gp->gp_egv, param);/* GvEGV is not refcounted */
9542     ret->gp_cv          = cv_dup_inc(gp->gp_cv, param);
9543     ret->gp_cvgen       = gp->gp_cvgen;
9544     ret->gp_line        = gp->gp_line;
9545     ret->gp_file_hek    = hek_dup(gp->gp_file_hek, param);
9546     return ret;
9547 }
9548
9549 /* duplicate a chain of magic */
9550
9551 MAGIC *
9552 Perl_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS* param)
9553 {
9554     MAGIC *mgprev = (MAGIC*)NULL;
9555     MAGIC *mgret;
9556     if (!mg)
9557         return (MAGIC*)NULL;
9558     /* look for it in the table first */
9559     mgret = (MAGIC*)ptr_table_fetch(PL_ptr_table, mg);
9560     if (mgret)
9561         return mgret;
9562
9563     for (; mg; mg = mg->mg_moremagic) {
9564         MAGIC *nmg;
9565         Newxz(nmg, 1, MAGIC);
9566         if (mgprev)
9567             mgprev->mg_moremagic = nmg;
9568         else
9569             mgret = nmg;
9570         nmg->mg_virtual = mg->mg_virtual;       /* XXX copy dynamic vtable? */
9571         nmg->mg_private = mg->mg_private;
9572         nmg->mg_type    = mg->mg_type;
9573         nmg->mg_flags   = mg->mg_flags;
9574         if (mg->mg_type == PERL_MAGIC_qr) {
9575             nmg->mg_obj = (SV*)CALLREGDUPE((REGEXP*)mg->mg_obj, param);
9576         }
9577         else if(mg->mg_type == PERL_MAGIC_backref) {
9578             /* The backref AV has its reference count deliberately bumped by
9579                1.  */
9580             nmg->mg_obj = SvREFCNT_inc(av_dup_inc((AV*) mg->mg_obj, param));
9581         }
9582         else if (mg->mg_type == PERL_MAGIC_symtab) {
9583             nmg->mg_obj = mg->mg_obj;
9584         }
9585         else {
9586             nmg->mg_obj = (mg->mg_flags & MGf_REFCOUNTED)
9587                               ? sv_dup_inc(mg->mg_obj, param)
9588                               : sv_dup(mg->mg_obj, param);
9589         }
9590         nmg->mg_len     = mg->mg_len;
9591         nmg->mg_ptr     = mg->mg_ptr;   /* XXX random ptr? */
9592         if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) {
9593             if (mg->mg_len > 0) {
9594                 nmg->mg_ptr     = SAVEPVN(mg->mg_ptr, mg->mg_len);
9595                 if (mg->mg_type == PERL_MAGIC_overload_table &&
9596                         AMT_AMAGIC((AMT*)mg->mg_ptr))
9597                 {
9598                     const AMT * const amtp = (AMT*)mg->mg_ptr;
9599                     AMT * const namtp = (AMT*)nmg->mg_ptr;
9600                     I32 i;
9601                     for (i = 1; i < NofAMmeth; i++) {
9602                         namtp->table[i] = cv_dup_inc(amtp->table[i], param);
9603                     }
9604                 }
9605             }
9606             else if (mg->mg_len == HEf_SVKEY)
9607                 nmg->mg_ptr     = (char*)sv_dup_inc((SV*)mg->mg_ptr, param);
9608         }
9609         if ((mg->mg_flags & MGf_DUP) && mg->mg_virtual && mg->mg_virtual->svt_dup) {
9610             CALL_FPTR(nmg->mg_virtual->svt_dup)(aTHX_ nmg, param);
9611         }
9612         mgprev = nmg;
9613     }
9614     return mgret;
9615 }
9616
9617 /* create a new pointer-mapping table */
9618
9619 PTR_TBL_t *
9620 Perl_ptr_table_new(pTHX)
9621 {
9622     PTR_TBL_t *tbl;
9623     PERL_UNUSED_CONTEXT;
9624
9625     Newxz(tbl, 1, PTR_TBL_t);
9626     tbl->tbl_max        = 511;
9627     tbl->tbl_items      = 0;
9628     Newxz(tbl->tbl_ary, tbl->tbl_max + 1, PTR_TBL_ENT_t*);
9629     return tbl;
9630 }
9631
9632 #define PTR_TABLE_HASH(ptr) \
9633   ((PTR2UV(ptr) >> 3) ^ (PTR2UV(ptr) >> (3 + 7)) ^ (PTR2UV(ptr) >> (3 + 17)))
9634
9635 /* 
9636    we use the PTE_SVSLOT 'reservation' made above, both here (in the
9637    following define) and at call to new_body_inline made below in 
9638    Perl_ptr_table_store()
9639  */
9640
9641 #define del_pte(p)     del_body_type(p, PTE_SVSLOT)
9642
9643 /* map an existing pointer using a table */
9644
9645 STATIC PTR_TBL_ENT_t *
9646 S_ptr_table_find(PTR_TBL_t *tbl, const void *sv) {
9647     PTR_TBL_ENT_t *tblent;
9648     const UV hash = PTR_TABLE_HASH(sv);
9649     assert(tbl);
9650     tblent = tbl->tbl_ary[hash & tbl->tbl_max];
9651     for (; tblent; tblent = tblent->next) {
9652         if (tblent->oldval == sv)
9653             return tblent;
9654     }
9655     return NULL;
9656 }
9657
9658 void *
9659 Perl_ptr_table_fetch(pTHX_ PTR_TBL_t *tbl, const void *sv)
9660 {
9661     PTR_TBL_ENT_t const *const tblent = ptr_table_find(tbl, sv);
9662     PERL_UNUSED_CONTEXT;
9663     return tblent ? tblent->newval : NULL;
9664 }
9665
9666 /* add a new entry to a pointer-mapping table */
9667
9668 void
9669 Perl_ptr_table_store(pTHX_ PTR_TBL_t *tbl, const void *oldsv, void *newsv)
9670 {
9671     PTR_TBL_ENT_t *tblent = ptr_table_find(tbl, oldsv);
9672     PERL_UNUSED_CONTEXT;
9673
9674     if (tblent) {
9675         tblent->newval = newsv;
9676     } else {
9677         const UV entry = PTR_TABLE_HASH(oldsv) & tbl->tbl_max;
9678
9679         new_body_inline(tblent, PTE_SVSLOT);
9680
9681         tblent->oldval = oldsv;
9682         tblent->newval = newsv;
9683         tblent->next = tbl->tbl_ary[entry];
9684         tbl->tbl_ary[entry] = tblent;
9685         tbl->tbl_items++;
9686         if (tblent->next && tbl->tbl_items > tbl->tbl_max)
9687             ptr_table_split(tbl);
9688     }
9689 }
9690
9691 /* double the hash bucket size of an existing ptr table */
9692
9693 void
9694 Perl_ptr_table_split(pTHX_ PTR_TBL_t *tbl)
9695 {
9696     PTR_TBL_ENT_t **ary = tbl->tbl_ary;
9697     const UV oldsize = tbl->tbl_max + 1;
9698     UV newsize = oldsize * 2;
9699     UV i;
9700     PERL_UNUSED_CONTEXT;
9701
9702     Renew(ary, newsize, PTR_TBL_ENT_t*);
9703     Zero(&ary[oldsize], newsize-oldsize, PTR_TBL_ENT_t*);
9704     tbl->tbl_max = --newsize;
9705     tbl->tbl_ary = ary;
9706     for (i=0; i < oldsize; i++, ary++) {
9707         PTR_TBL_ENT_t **curentp, **entp, *ent;
9708         if (!*ary)
9709             continue;
9710         curentp = ary + oldsize;
9711         for (entp = ary, ent = *ary; ent; ent = *entp) {
9712             if ((newsize & PTR_TABLE_HASH(ent->oldval)) != i) {
9713                 *entp = ent->next;
9714                 ent->next = *curentp;
9715                 *curentp = ent;
9716                 continue;
9717             }
9718             else
9719                 entp = &ent->next;
9720         }
9721     }
9722 }
9723
9724 /* remove all the entries from a ptr table */
9725
9726 void
9727 Perl_ptr_table_clear(pTHX_ PTR_TBL_t *tbl)
9728 {
9729     if (tbl && tbl->tbl_items) {
9730         register PTR_TBL_ENT_t * const * const array = tbl->tbl_ary;
9731         UV riter = tbl->tbl_max;
9732
9733         do {
9734             PTR_TBL_ENT_t *entry = array[riter];
9735
9736             while (entry) {
9737                 PTR_TBL_ENT_t * const oentry = entry;
9738                 entry = entry->next;
9739                 del_pte(oentry);
9740             }
9741         } while (riter--);
9742
9743         tbl->tbl_items = 0;
9744     }
9745 }
9746
9747 /* clear and free a ptr table */
9748
9749 void
9750 Perl_ptr_table_free(pTHX_ PTR_TBL_t *tbl)
9751 {
9752     if (!tbl) {
9753         return;
9754     }
9755     ptr_table_clear(tbl);
9756     Safefree(tbl->tbl_ary);
9757     Safefree(tbl);
9758 }
9759
9760
9761 void
9762 Perl_rvpv_dup(pTHX_ SV *dstr, const SV *sstr, CLONE_PARAMS* param)
9763 {
9764     if (SvROK(sstr)) {
9765         SvRV_set(dstr, SvWEAKREF(sstr)
9766                        ? sv_dup(SvRV(sstr), param)
9767                        : sv_dup_inc(SvRV(sstr), param));
9768
9769     }
9770     else if (SvPVX_const(sstr)) {
9771         /* Has something there */
9772         if (SvLEN(sstr)) {
9773             /* Normal PV - clone whole allocated space */
9774             SvPV_set(dstr, SAVEPVN(SvPVX_const(sstr), SvLEN(sstr)-1));
9775             if (SvREADONLY(sstr) && SvFAKE(sstr)) {
9776                 /* Not that normal - actually sstr is copy on write.
9777                    But we are a true, independant SV, so:  */
9778                 SvREADONLY_off(dstr);
9779                 SvFAKE_off(dstr);
9780             }
9781         }
9782         else {
9783             /* Special case - not normally malloced for some reason */
9784             if (isGV_with_GP(sstr)) {
9785                 /* Don't need to do anything here.  */
9786             }
9787             else if ((SvREADONLY(sstr) && SvFAKE(sstr))) {
9788                 /* A "shared" PV - clone it as "shared" PV */
9789                 SvPV_set(dstr,
9790                          HEK_KEY(hek_dup(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)),
9791                                          param)));
9792             }
9793             else {
9794                 /* Some other special case - random pointer */
9795                 SvPV_set(dstr, SvPVX(sstr));            
9796             }
9797         }
9798     }
9799     else {
9800         /* Copy the NULL */
9801         if (SvTYPE(dstr) == SVt_RV)
9802             SvRV_set(dstr, NULL);
9803         else
9804             SvPV_set(dstr, NULL);
9805     }
9806 }
9807
9808 /* duplicate an SV of any type (including AV, HV etc) */
9809
9810 SV *
9811 Perl_sv_dup(pTHX_ const SV *sstr, CLONE_PARAMS* param)
9812 {
9813     dVAR;
9814     SV *dstr;
9815
9816     if (!sstr || SvTYPE(sstr) == SVTYPEMASK)
9817         return NULL;
9818     /* look for it in the table first */
9819     dstr = (SV*)ptr_table_fetch(PL_ptr_table, sstr);
9820     if (dstr)
9821         return dstr;
9822
9823     if(param->flags & CLONEf_JOIN_IN) {
9824         /** We are joining here so we don't want do clone
9825             something that is bad **/
9826         if (SvTYPE(sstr) == SVt_PVHV) {
9827             const char * const hvname = HvNAME_get(sstr);
9828             if (hvname)
9829                 /** don't clone stashes if they already exist **/
9830                 return (SV*)gv_stashpv(hvname,0);
9831         }
9832     }
9833
9834     /* create anew and remember what it is */
9835     new_SV(dstr);
9836
9837 #ifdef DEBUG_LEAKING_SCALARS
9838     dstr->sv_debug_optype = sstr->sv_debug_optype;
9839     dstr->sv_debug_line = sstr->sv_debug_line;
9840     dstr->sv_debug_inpad = sstr->sv_debug_inpad;
9841     dstr->sv_debug_cloned = 1;
9842     dstr->sv_debug_file = savepv(sstr->sv_debug_file);
9843 #endif
9844
9845     ptr_table_store(PL_ptr_table, sstr, dstr);
9846
9847     /* clone */
9848     SvFLAGS(dstr)       = SvFLAGS(sstr);
9849     SvFLAGS(dstr)       &= ~SVf_OOK;            /* don't propagate OOK hack */
9850     SvREFCNT(dstr)      = 0;                    /* must be before any other dups! */
9851
9852 #ifdef DEBUGGING
9853     if (SvANY(sstr) && PL_watch_pvx && SvPVX_const(sstr) == PL_watch_pvx)
9854         PerlIO_printf(Perl_debug_log, "watch at %p hit, found string \"%s\"\n",
9855                       PL_watch_pvx, SvPVX_const(sstr));
9856 #endif
9857
9858     /* don't clone objects whose class has asked us not to */
9859     if (SvOBJECT(sstr) && ! (SvFLAGS(SvSTASH(sstr)) & SVphv_CLONEABLE)) {
9860         SvFLAGS(dstr) &= ~SVTYPEMASK;
9861         SvOBJECT_off(dstr);
9862         return dstr;
9863     }
9864
9865     switch (SvTYPE(sstr)) {
9866     case SVt_NULL:
9867         SvANY(dstr)     = NULL;
9868         break;
9869     case SVt_IV:
9870         SvANY(dstr)     = (XPVIV*)((char*)&(dstr->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
9871         SvIV_set(dstr, SvIVX(sstr));
9872         break;
9873     case SVt_NV:
9874         SvANY(dstr)     = new_XNV();
9875         SvNV_set(dstr, SvNVX(sstr));
9876         break;
9877     case SVt_RV:
9878         SvANY(dstr)     = &(dstr->sv_u.svu_rv);
9879         Perl_rvpv_dup(aTHX_ dstr, sstr, param);
9880         break;
9881         /* case SVt_BIND: */
9882     default:
9883         {
9884             /* These are all the types that need complex bodies allocating.  */
9885             void *new_body;
9886             const svtype sv_type = SvTYPE(sstr);
9887             const struct body_details *const sv_type_details
9888                 = bodies_by_type + sv_type;
9889
9890             switch (sv_type) {
9891             default:
9892                 Perl_croak(aTHX_ "Bizarre SvTYPE [%" IVdf "]", (IV)SvTYPE(sstr));
9893                 break;
9894
9895             case SVt_PVGV:
9896                 if (GvUNIQUE((GV*)sstr)) {
9897                     NOOP;   /* Do sharing here, and fall through */
9898                 }
9899             case SVt_PVIO:
9900             case SVt_PVFM:
9901             case SVt_PVHV:
9902             case SVt_PVAV:
9903             case SVt_PVCV:
9904             case SVt_PVLV:
9905             case SVt_PVMG:
9906             case SVt_PVNV:
9907             case SVt_PVIV:
9908             case SVt_PV:
9909                 assert(sv_type_details->body_size);
9910                 if (sv_type_details->arena) {
9911                     new_body_inline(new_body, sv_type);
9912                     new_body
9913                         = (void*)((char*)new_body - sv_type_details->offset);
9914                 } else {
9915                     new_body = new_NOARENA(sv_type_details);
9916                 }
9917             }
9918             assert(new_body);
9919             SvANY(dstr) = new_body;
9920
9921 #ifndef PURIFY
9922             Copy(((char*)SvANY(sstr)) + sv_type_details->offset,
9923                  ((char*)SvANY(dstr)) + sv_type_details->offset,
9924                  sv_type_details->copy, char);
9925 #else
9926             Copy(((char*)SvANY(sstr)),
9927                  ((char*)SvANY(dstr)),
9928                  sv_type_details->body_size + sv_type_details->offset, char);
9929 #endif
9930
9931             if (sv_type != SVt_PVAV && sv_type != SVt_PVHV
9932                 && !isGV_with_GP(dstr))
9933                 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
9934
9935             /* The Copy above means that all the source (unduplicated) pointers
9936                are now in the destination.  We can check the flags and the
9937                pointers in either, but it's possible that there's less cache
9938                missing by always going for the destination.
9939                FIXME - instrument and check that assumption  */
9940             if (sv_type >= SVt_PVMG) {
9941                 if ((sv_type == SVt_PVMG) && SvPAD_OUR(dstr)) {
9942                     OURSTASH_set(dstr, hv_dup_inc(OURSTASH(dstr), param));
9943                 } else if (SvMAGIC(dstr))
9944                     SvMAGIC_set(dstr, mg_dup(SvMAGIC(dstr), param));
9945                 if (SvSTASH(dstr))
9946                     SvSTASH_set(dstr, hv_dup_inc(SvSTASH(dstr), param));
9947             }
9948
9949             /* The cast silences a GCC warning about unhandled types.  */
9950             switch ((int)sv_type) {
9951             case SVt_PV:
9952                 break;
9953             case SVt_PVIV:
9954                 break;
9955             case SVt_PVNV:
9956                 break;
9957             case SVt_PVMG:
9958                 break;
9959             case SVt_PVLV:
9960                 /* XXX LvTARGOFF sometimes holds PMOP* when DEBUGGING */
9961                 if (LvTYPE(dstr) == 't') /* for tie: unrefcnted fake (SV**) */
9962                     LvTARG(dstr) = dstr;
9963                 else if (LvTYPE(dstr) == 'T') /* for tie: fake HE */
9964                     LvTARG(dstr) = (SV*)he_dup((HE*)LvTARG(dstr), 0, param);
9965                 else
9966                     LvTARG(dstr) = sv_dup_inc(LvTARG(dstr), param);
9967                 break;
9968             case SVt_PVGV:
9969                 if(isGV_with_GP(sstr)) {
9970                     if (GvNAME_HEK(dstr))
9971                         GvNAME_HEK(dstr) = hek_dup(GvNAME_HEK(dstr), param);
9972                 }
9973
9974                 /* Don't call sv_add_backref here as it's going to be created
9975                    as part of the magic cloning of the symbol table.  */
9976                 if(!SvVALID(dstr))
9977                     GvSTASH(dstr) = hv_dup(GvSTASH(dstr), param);
9978                 if(isGV_with_GP(sstr)) {
9979                     /* Danger Will Robinson - GvGP(dstr) isn't initialised
9980                        at the point of this comment.  */
9981                     GvGP(dstr)  = gp_dup(GvGP(sstr), param);
9982                     (void)GpREFCNT_inc(GvGP(dstr));
9983                 } else
9984                     Perl_rvpv_dup(aTHX_ dstr, sstr, param);
9985                 break;
9986             case SVt_PVIO:
9987                 IoIFP(dstr)     = fp_dup(IoIFP(dstr), IoTYPE(dstr), param);
9988                 if (IoOFP(dstr) == IoIFP(sstr))
9989                     IoOFP(dstr) = IoIFP(dstr);
9990                 else
9991                     IoOFP(dstr) = fp_dup(IoOFP(dstr), IoTYPE(dstr), param);
9992                 /* PL_rsfp_filters entries have fake IoDIRP() */
9993                 if(IoFLAGS(dstr) & IOf_FAKE_DIRP) {
9994                     /* I have no idea why fake dirp (rsfps)
9995                        should be treated differently but otherwise
9996                        we end up with leaks -- sky*/
9997                     IoTOP_GV(dstr)      = gv_dup_inc(IoTOP_GV(dstr), param);
9998                     IoFMT_GV(dstr)      = gv_dup_inc(IoFMT_GV(dstr), param);
9999                     IoBOTTOM_GV(dstr)   = gv_dup_inc(IoBOTTOM_GV(dstr), param);
10000                 } else {
10001                     IoTOP_GV(dstr)      = gv_dup(IoTOP_GV(dstr), param);
10002                     IoFMT_GV(dstr)      = gv_dup(IoFMT_GV(dstr), param);
10003                     IoBOTTOM_GV(dstr)   = gv_dup(IoBOTTOM_GV(dstr), param);
10004                     if (IoDIRP(dstr)) {
10005                         IoDIRP(dstr)    = dirp_dup(IoDIRP(dstr));
10006                     } else {
10007                         NOOP;
10008                         /* IoDIRP(dstr) is already a copy of IoDIRP(sstr)  */
10009                     }
10010                 }
10011                 IoTOP_NAME(dstr)        = SAVEPV(IoTOP_NAME(dstr));
10012                 IoFMT_NAME(dstr)        = SAVEPV(IoFMT_NAME(dstr));
10013                 IoBOTTOM_NAME(dstr)     = SAVEPV(IoBOTTOM_NAME(dstr));
10014                 break;
10015             case SVt_PVAV:
10016                 if (AvARRAY((AV*)sstr)) {
10017                     SV **dst_ary, **src_ary;
10018                     SSize_t items = AvFILLp((AV*)sstr) + 1;
10019
10020                     src_ary = AvARRAY((AV*)sstr);
10021                     Newxz(dst_ary, AvMAX((AV*)sstr)+1, SV*);
10022                     ptr_table_store(PL_ptr_table, src_ary, dst_ary);
10023                     AvARRAY((AV*)dstr) = dst_ary;
10024                     AvALLOC((AV*)dstr) = dst_ary;
10025                     if (AvREAL((AV*)sstr)) {
10026                         while (items-- > 0)
10027                             *dst_ary++ = sv_dup_inc(*src_ary++, param);
10028                     }
10029                     else {
10030                         while (items-- > 0)
10031                             *dst_ary++ = sv_dup(*src_ary++, param);
10032                     }
10033                     items = AvMAX((AV*)sstr) - AvFILLp((AV*)sstr);
10034                     while (items-- > 0) {
10035                         *dst_ary++ = &PL_sv_undef;
10036                     }
10037                 }
10038                 else {
10039                     AvARRAY((AV*)dstr)  = NULL;
10040                     AvALLOC((AV*)dstr)  = (SV**)NULL;
10041                 }
10042                 break;
10043             case SVt_PVHV:
10044                 if (HvARRAY((HV*)sstr)) {
10045                     STRLEN i = 0;
10046                     const bool sharekeys = !!HvSHAREKEYS(sstr);
10047                     XPVHV * const dxhv = (XPVHV*)SvANY(dstr);
10048                     XPVHV * const sxhv = (XPVHV*)SvANY(sstr);
10049                     char *darray;
10050                     Newx(darray, PERL_HV_ARRAY_ALLOC_BYTES(dxhv->xhv_max+1)
10051                         + (SvOOK(sstr) ? sizeof(struct xpvhv_aux) : 0),
10052                         char);
10053                     HvARRAY(dstr) = (HE**)darray;
10054                     while (i <= sxhv->xhv_max) {
10055                         const HE * const source = HvARRAY(sstr)[i];
10056                         HvARRAY(dstr)[i] = source
10057                             ? he_dup(source, sharekeys, param) : 0;
10058                         ++i;
10059                     }
10060                     if (SvOOK(sstr)) {
10061                         HEK *hvname;
10062                         const struct xpvhv_aux * const saux = HvAUX(sstr);
10063                         struct xpvhv_aux * const daux = HvAUX(dstr);
10064                         /* This flag isn't copied.  */
10065                         /* SvOOK_on(hv) attacks the IV flags.  */
10066                         SvFLAGS(dstr) |= SVf_OOK;
10067
10068                         hvname = saux->xhv_name;
10069                         daux->xhv_name = hvname ? hek_dup(hvname, param) : hvname;
10070
10071                         daux->xhv_riter = saux->xhv_riter;
10072                         daux->xhv_eiter = saux->xhv_eiter
10073                             ? he_dup(saux->xhv_eiter,
10074                                         (bool)!!HvSHAREKEYS(sstr), param) : 0;
10075                         daux->xhv_backreferences =
10076                             saux->xhv_backreferences
10077                                 ? (AV*) SvREFCNT_inc(
10078                                         sv_dup((SV*)saux->xhv_backreferences, param))
10079                                 : 0;
10080                         /* Record stashes for possible cloning in Perl_clone(). */
10081                         if (hvname)
10082                             av_push(param->stashes, dstr);
10083                     }
10084                 }
10085                 else
10086                     HvARRAY((HV*)dstr) = NULL;
10087                 break;
10088             case SVt_PVCV:
10089                 if (!(param->flags & CLONEf_COPY_STACKS)) {
10090                     CvDEPTH(dstr) = 0;
10091                 }
10092             case SVt_PVFM:
10093                 /* NOTE: not refcounted */
10094                 CvSTASH(dstr)   = hv_dup(CvSTASH(dstr), param);
10095                 OP_REFCNT_LOCK;
10096                 if (!CvISXSUB(dstr))
10097                     CvROOT(dstr) = OpREFCNT_inc(CvROOT(dstr));
10098                 OP_REFCNT_UNLOCK;
10099                 if (CvCONST(dstr) && CvISXSUB(dstr)) {
10100                     CvXSUBANY(dstr).any_ptr = GvUNIQUE(CvGV(dstr)) ?
10101                         SvREFCNT_inc(CvXSUBANY(dstr).any_ptr) :
10102                         sv_dup_inc((SV *)CvXSUBANY(dstr).any_ptr, param);
10103                 }
10104                 /* don't dup if copying back - CvGV isn't refcounted, so the
10105                  * duped GV may never be freed. A bit of a hack! DAPM */
10106                 CvGV(dstr)      = (param->flags & CLONEf_JOIN_IN) ?
10107                     NULL : gv_dup(CvGV(dstr), param) ;
10108                 PAD_DUP(CvPADLIST(dstr), CvPADLIST(sstr), param);
10109                 CvOUTSIDE(dstr) =
10110                     CvWEAKOUTSIDE(sstr)
10111                     ? cv_dup(    CvOUTSIDE(dstr), param)
10112                     : cv_dup_inc(CvOUTSIDE(dstr), param);
10113                 if (!CvISXSUB(dstr))
10114                     CvFILE(dstr) = SAVEPV(CvFILE(dstr));
10115                 break;
10116             }
10117         }
10118     }
10119
10120     if (SvOBJECT(dstr) && SvTYPE(dstr) != SVt_PVIO)
10121         ++PL_sv_objcount;
10122
10123     return dstr;
10124  }
10125
10126 /* duplicate a context */
10127
10128 PERL_CONTEXT *
10129 Perl_cx_dup(pTHX_ PERL_CONTEXT *cxs, I32 ix, I32 max, CLONE_PARAMS* param)
10130 {
10131     PERL_CONTEXT *ncxs;
10132
10133     if (!cxs)
10134         return (PERL_CONTEXT*)NULL;
10135
10136     /* look for it in the table first */
10137     ncxs = (PERL_CONTEXT*)ptr_table_fetch(PL_ptr_table, cxs);
10138     if (ncxs)
10139         return ncxs;
10140
10141     /* create anew and remember what it is */
10142     Newxz(ncxs, max + 1, PERL_CONTEXT);
10143     ptr_table_store(PL_ptr_table, cxs, ncxs);
10144
10145     while (ix >= 0) {
10146         PERL_CONTEXT * const cx = &cxs[ix];
10147         PERL_CONTEXT * const ncx = &ncxs[ix];
10148         ncx->cx_type    = cx->cx_type;
10149         if (CxTYPE(cx) == CXt_SUBST) {
10150             Perl_croak(aTHX_ "Cloning substitution context is unimplemented");
10151         }
10152         else {
10153             ncx->blk_oldsp      = cx->blk_oldsp;
10154             ncx->blk_oldcop     = cx->blk_oldcop;
10155             ncx->blk_oldmarksp  = cx->blk_oldmarksp;
10156             ncx->blk_oldscopesp = cx->blk_oldscopesp;
10157             ncx->blk_oldpm      = cx->blk_oldpm;
10158             ncx->blk_gimme      = cx->blk_gimme;
10159             switch (CxTYPE(cx)) {
10160             case CXt_SUB:
10161                 ncx->blk_sub.cv         = (cx->blk_sub.olddepth == 0
10162                                            ? cv_dup_inc(cx->blk_sub.cv, param)
10163                                            : cv_dup(cx->blk_sub.cv,param));
10164                 ncx->blk_sub.argarray   = (cx->blk_sub.hasargs
10165                                            ? av_dup_inc(cx->blk_sub.argarray, param)
10166                                            : NULL);
10167                 ncx->blk_sub.savearray  = av_dup_inc(cx->blk_sub.savearray, param);
10168                 ncx->blk_sub.olddepth   = cx->blk_sub.olddepth;
10169                 ncx->blk_sub.hasargs    = cx->blk_sub.hasargs;
10170                 ncx->blk_sub.lval       = cx->blk_sub.lval;
10171                 ncx->blk_sub.retop      = cx->blk_sub.retop;
10172                 ncx->blk_sub.oldcomppad = (PAD*)ptr_table_fetch(PL_ptr_table,
10173                                            cx->blk_sub.oldcomppad);
10174                 break;
10175             case CXt_EVAL:
10176                 ncx->blk_eval.old_in_eval = cx->blk_eval.old_in_eval;
10177                 ncx->blk_eval.old_op_type = cx->blk_eval.old_op_type;
10178                 ncx->blk_eval.old_namesv = sv_dup_inc(cx->blk_eval.old_namesv, param);
10179                 ncx->blk_eval.old_eval_root = cx->blk_eval.old_eval_root;
10180                 ncx->blk_eval.cur_text  = sv_dup(cx->blk_eval.cur_text, param);
10181                 ncx->blk_eval.retop = cx->blk_eval.retop;
10182                 break;
10183             case CXt_LOOP:
10184                 ncx->blk_loop.label     = cx->blk_loop.label;
10185                 ncx->blk_loop.resetsp   = cx->blk_loop.resetsp;
10186                 ncx->blk_loop.my_op     = cx->blk_loop.my_op;
10187                 ncx->blk_loop.iterdata  = (CxPADLOOP(cx)
10188                                            ? cx->blk_loop.iterdata
10189                                            : gv_dup((GV*)cx->blk_loop.iterdata, param));
10190                 ncx->blk_loop.oldcomppad
10191                     = (PAD*)ptr_table_fetch(PL_ptr_table,
10192                                             cx->blk_loop.oldcomppad);
10193                 ncx->blk_loop.itersave  = sv_dup_inc(cx->blk_loop.itersave, param);
10194                 ncx->blk_loop.iterlval  = sv_dup_inc(cx->blk_loop.iterlval, param);
10195                 ncx->blk_loop.iterary   = av_dup_inc(cx->blk_loop.iterary, param);
10196                 ncx->blk_loop.iterix    = cx->blk_loop.iterix;
10197                 ncx->blk_loop.itermax   = cx->blk_loop.itermax;
10198                 break;
10199             case CXt_FORMAT:
10200                 ncx->blk_sub.cv         = cv_dup(cx->blk_sub.cv, param);
10201                 ncx->blk_sub.gv         = gv_dup(cx->blk_sub.gv, param);
10202                 ncx->blk_sub.dfoutgv    = gv_dup_inc(cx->blk_sub.dfoutgv, param);
10203                 ncx->blk_sub.hasargs    = cx->blk_sub.hasargs;
10204                 ncx->blk_sub.retop      = cx->blk_sub.retop;
10205                 break;
10206             case CXt_BLOCK:
10207             case CXt_NULL:
10208                 break;
10209             }
10210         }
10211         --ix;
10212     }
10213     return ncxs;
10214 }
10215
10216 /* duplicate a stack info structure */
10217
10218 PERL_SI *
10219 Perl_si_dup(pTHX_ PERL_SI *si, CLONE_PARAMS* param)
10220 {
10221     PERL_SI *nsi;
10222
10223     if (!si)
10224         return (PERL_SI*)NULL;
10225
10226     /* look for it in the table first */
10227     nsi = (PERL_SI*)ptr_table_fetch(PL_ptr_table, si);
10228     if (nsi)
10229         return nsi;
10230
10231     /* create anew and remember what it is */
10232     Newxz(nsi, 1, PERL_SI);
10233     ptr_table_store(PL_ptr_table, si, nsi);
10234
10235     nsi->si_stack       = av_dup_inc(si->si_stack, param);
10236     nsi->si_cxix        = si->si_cxix;
10237     nsi->si_cxmax       = si->si_cxmax;
10238     nsi->si_cxstack     = cx_dup(si->si_cxstack, si->si_cxix, si->si_cxmax, param);
10239     nsi->si_type        = si->si_type;
10240     nsi->si_prev        = si_dup(si->si_prev, param);
10241     nsi->si_next        = si_dup(si->si_next, param);
10242     nsi->si_markoff     = si->si_markoff;
10243
10244     return nsi;
10245 }
10246
10247 #define POPINT(ss,ix)   ((ss)[--(ix)].any_i32)
10248 #define TOPINT(ss,ix)   ((ss)[ix].any_i32)
10249 #define POPLONG(ss,ix)  ((ss)[--(ix)].any_long)
10250 #define TOPLONG(ss,ix)  ((ss)[ix].any_long)
10251 #define POPIV(ss,ix)    ((ss)[--(ix)].any_iv)
10252 #define TOPIV(ss,ix)    ((ss)[ix].any_iv)
10253 #define POPBOOL(ss,ix)  ((ss)[--(ix)].any_bool)
10254 #define TOPBOOL(ss,ix)  ((ss)[ix].any_bool)
10255 #define POPPTR(ss,ix)   ((ss)[--(ix)].any_ptr)
10256 #define TOPPTR(ss,ix)   ((ss)[ix].any_ptr)
10257 #define POPDPTR(ss,ix)  ((ss)[--(ix)].any_dptr)
10258 #define TOPDPTR(ss,ix)  ((ss)[ix].any_dptr)
10259 #define POPDXPTR(ss,ix) ((ss)[--(ix)].any_dxptr)
10260 #define TOPDXPTR(ss,ix) ((ss)[ix].any_dxptr)
10261
10262 /* XXXXX todo */
10263 #define pv_dup_inc(p)   SAVEPV(p)
10264 #define pv_dup(p)       SAVEPV(p)
10265 #define svp_dup_inc(p,pp)       any_dup(p,pp)
10266
10267 /* map any object to the new equivent - either something in the
10268  * ptr table, or something in the interpreter structure
10269  */
10270
10271 void *
10272 Perl_any_dup(pTHX_ void *v, const PerlInterpreter *proto_perl)
10273 {
10274     void *ret;
10275
10276     if (!v)
10277         return (void*)NULL;
10278
10279     /* look for it in the table first */
10280     ret = ptr_table_fetch(PL_ptr_table, v);
10281     if (ret)
10282         return ret;
10283
10284     /* see if it is part of the interpreter structure */
10285     if (v >= (void*)proto_perl && v < (void*)(proto_perl+1))
10286         ret = (void*)(((char*)aTHX) + (((char*)v) - (char*)proto_perl));
10287     else {
10288         ret = v;
10289     }
10290
10291     return ret;
10292 }
10293
10294 /* duplicate the save stack */
10295
10296 ANY *
10297 Perl_ss_dup(pTHX_ PerlInterpreter *proto_perl, CLONE_PARAMS* param)
10298 {
10299     ANY * const ss      = proto_perl->Tsavestack;
10300     const I32 max       = proto_perl->Tsavestack_max;
10301     I32 ix              = proto_perl->Tsavestack_ix;
10302     ANY *nss;
10303     SV *sv;
10304     GV *gv;
10305     AV *av;
10306     HV *hv;
10307     void* ptr;
10308     int intval;
10309     long longval;
10310     GP *gp;
10311     IV iv;
10312     I32 i;
10313     char *c = NULL;
10314     void (*dptr) (void*);
10315     void (*dxptr) (pTHX_ void*);
10316
10317     Newxz(nss, max, ANY);
10318
10319     while (ix > 0) {
10320         const I32 type = POPINT(ss,ix);
10321         TOPINT(nss,ix) = type;
10322         switch (type) {
10323         case SAVEt_HELEM:               /* hash element */
10324             sv = (SV*)POPPTR(ss,ix);
10325             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10326             /* fall through */
10327         case SAVEt_ITEM:                        /* normal string */
10328         case SAVEt_SV:                          /* scalar reference */
10329             sv = (SV*)POPPTR(ss,ix);
10330             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10331             /* fall through */
10332         case SAVEt_FREESV:
10333         case SAVEt_MORTALIZESV:
10334             sv = (SV*)POPPTR(ss,ix);
10335             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10336             break;
10337         case SAVEt_SHARED_PVREF:                /* char* in shared space */
10338             c = (char*)POPPTR(ss,ix);
10339             TOPPTR(nss,ix) = savesharedpv(c);
10340             ptr = POPPTR(ss,ix);
10341             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10342             break;
10343         case SAVEt_GENERIC_SVREF:               /* generic sv */
10344         case SAVEt_SVREF:                       /* scalar reference */
10345             sv = (SV*)POPPTR(ss,ix);
10346             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10347             ptr = POPPTR(ss,ix);
10348             TOPPTR(nss,ix) = svp_dup_inc((SV**)ptr, proto_perl);/* XXXXX */
10349             break;
10350         case SAVEt_HV:                          /* hash reference */
10351         case SAVEt_AV:                          /* array reference */
10352             sv = (SV*) POPPTR(ss,ix);
10353             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10354             /* fall through */
10355         case SAVEt_COMPPAD:
10356         case SAVEt_NSTAB:
10357             sv = (SV*) POPPTR(ss,ix);
10358             TOPPTR(nss,ix) = sv_dup(sv, param);
10359             break;
10360         case SAVEt_INT:                         /* int reference */
10361             ptr = POPPTR(ss,ix);
10362             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10363             intval = (int)POPINT(ss,ix);
10364             TOPINT(nss,ix) = intval;
10365             break;
10366         case SAVEt_LONG:                        /* long reference */
10367             ptr = POPPTR(ss,ix);
10368             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10369             /* fall through */
10370         case SAVEt_CLEARSV:
10371             longval = (long)POPLONG(ss,ix);
10372             TOPLONG(nss,ix) = longval;
10373             break;
10374         case SAVEt_I32:                         /* I32 reference */
10375         case SAVEt_I16:                         /* I16 reference */
10376         case SAVEt_I8:                          /* I8 reference */
10377         case SAVEt_COP_ARYBASE:                 /* call CopARYBASE_set */
10378             ptr = POPPTR(ss,ix);
10379             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10380             i = POPINT(ss,ix);
10381             TOPINT(nss,ix) = i;
10382             break;
10383         case SAVEt_IV:                          /* IV reference */
10384             ptr = POPPTR(ss,ix);
10385             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10386             iv = POPIV(ss,ix);
10387             TOPIV(nss,ix) = iv;
10388             break;
10389         case SAVEt_HPTR:                        /* HV* reference */
10390         case SAVEt_APTR:                        /* AV* reference */
10391         case SAVEt_SPTR:                        /* SV* reference */
10392             ptr = POPPTR(ss,ix);
10393             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10394             sv = (SV*)POPPTR(ss,ix);
10395             TOPPTR(nss,ix) = sv_dup(sv, param);
10396             break;
10397         case SAVEt_VPTR:                        /* random* reference */
10398             ptr = POPPTR(ss,ix);
10399             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10400             ptr = POPPTR(ss,ix);
10401             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10402             break;
10403         case SAVEt_GENERIC_PVREF:               /* generic char* */
10404         case SAVEt_PPTR:                        /* char* reference */
10405             ptr = POPPTR(ss,ix);
10406             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10407             c = (char*)POPPTR(ss,ix);
10408             TOPPTR(nss,ix) = pv_dup(c);
10409             break;
10410         case SAVEt_GP:                          /* scalar reference */
10411             gp = (GP*)POPPTR(ss,ix);
10412             TOPPTR(nss,ix) = gp = gp_dup(gp, param);
10413             (void)GpREFCNT_inc(gp);
10414             gv = (GV*)POPPTR(ss,ix);
10415             TOPPTR(nss,ix) = gv_dup_inc(gv, param);
10416             break;
10417         case SAVEt_FREEOP:
10418             ptr = POPPTR(ss,ix);
10419             if (ptr && (((OP*)ptr)->op_private & OPpREFCOUNTED)) {
10420                 /* these are assumed to be refcounted properly */
10421                 OP *o;
10422                 switch (((OP*)ptr)->op_type) {
10423                 case OP_LEAVESUB:
10424                 case OP_LEAVESUBLV:
10425                 case OP_LEAVEEVAL:
10426                 case OP_LEAVE:
10427                 case OP_SCOPE:
10428                 case OP_LEAVEWRITE:
10429                     TOPPTR(nss,ix) = ptr;
10430                     o = (OP*)ptr;
10431                     OP_REFCNT_LOCK;
10432                     OpREFCNT_inc(o);
10433                     OP_REFCNT_UNLOCK;
10434                     break;
10435                 default:
10436                     TOPPTR(nss,ix) = NULL;
10437                     break;
10438                 }
10439             }
10440             else
10441                 TOPPTR(nss,ix) = NULL;
10442             break;
10443         case SAVEt_FREEPV:
10444             c = (char*)POPPTR(ss,ix);
10445             TOPPTR(nss,ix) = pv_dup_inc(c);
10446             break;
10447         case SAVEt_DELETE:
10448             hv = (HV*)POPPTR(ss,ix);
10449             TOPPTR(nss,ix) = hv_dup_inc(hv, param);
10450             c = (char*)POPPTR(ss,ix);
10451             TOPPTR(nss,ix) = pv_dup_inc(c);
10452             /* fall through */
10453         case SAVEt_STACK_POS:           /* Position on Perl stack */
10454             i = POPINT(ss,ix);
10455             TOPINT(nss,ix) = i;
10456             break;
10457         case SAVEt_DESTRUCTOR:
10458             ptr = POPPTR(ss,ix);
10459             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);  /* XXX quite arbitrary */
10460             dptr = POPDPTR(ss,ix);
10461             TOPDPTR(nss,ix) = DPTR2FPTR(void (*)(void*),
10462                                         any_dup(FPTR2DPTR(void *, dptr),
10463                                                 proto_perl));
10464             break;
10465         case SAVEt_DESTRUCTOR_X:
10466             ptr = POPPTR(ss,ix);
10467             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);  /* XXX quite arbitrary */
10468             dxptr = POPDXPTR(ss,ix);
10469             TOPDXPTR(nss,ix) = DPTR2FPTR(void (*)(pTHX_ void*),
10470                                          any_dup(FPTR2DPTR(void *, dxptr),
10471                                                  proto_perl));
10472             break;
10473         case SAVEt_REGCONTEXT:
10474         case SAVEt_ALLOC:
10475             i = POPINT(ss,ix);
10476             TOPINT(nss,ix) = i;
10477             ix -= i;
10478             break;
10479         case SAVEt_AELEM:               /* array element */
10480             sv = (SV*)POPPTR(ss,ix);
10481             TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10482             i = POPINT(ss,ix);
10483             TOPINT(nss,ix) = i;
10484             av = (AV*)POPPTR(ss,ix);
10485             TOPPTR(nss,ix) = av_dup_inc(av, param);
10486             break;
10487         case SAVEt_OP:
10488             ptr = POPPTR(ss,ix);
10489             TOPPTR(nss,ix) = ptr;
10490             break;
10491         case SAVEt_HINTS:
10492             i = POPINT(ss,ix);
10493             TOPINT(nss,ix) = i;
10494             ptr = POPPTR(ss,ix);
10495             if (ptr) {
10496                 HINTS_REFCNT_LOCK;
10497                 ((struct refcounted_he *)ptr)->refcounted_he_refcnt++;
10498                 HINTS_REFCNT_UNLOCK;
10499             }
10500             TOPPTR(nss,ix) = ptr;
10501             if (i & HINT_LOCALIZE_HH) {
10502                 hv = (HV*)POPPTR(ss,ix);
10503                 TOPPTR(nss,ix) = hv_dup_inc(hv, param);
10504             }
10505             break;
10506         case SAVEt_PADSV:
10507             longval = (long)POPLONG(ss,ix);
10508             TOPLONG(nss,ix) = longval;
10509             ptr = POPPTR(ss,ix);
10510             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10511             sv = (SV*)POPPTR(ss,ix);
10512             TOPPTR(nss,ix) = sv_dup(sv, param);
10513             break;
10514         case SAVEt_BOOL:
10515             ptr = POPPTR(ss,ix);
10516             TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10517             longval = (long)POPBOOL(ss,ix);
10518             TOPBOOL(nss,ix) = (bool)longval;
10519             break;
10520         case SAVEt_SET_SVFLAGS:
10521             i = POPINT(ss,ix);
10522             TOPINT(nss,ix) = i;
10523             i = POPINT(ss,ix);
10524             TOPINT(nss,ix) = i;
10525             sv = (SV*)POPPTR(ss,ix);
10526             TOPPTR(nss,ix) = sv_dup(sv, param);
10527             break;
10528         case SAVEt_RE_STATE:
10529             {
10530                 const struct re_save_state *const old_state
10531                     = (struct re_save_state *)
10532                     (ss + ix - SAVESTACK_ALLOC_FOR_RE_SAVE_STATE);
10533                 struct re_save_state *const new_state
10534                     = (struct re_save_state *)
10535                     (nss + ix - SAVESTACK_ALLOC_FOR_RE_SAVE_STATE);
10536
10537                 Copy(old_state, new_state, 1, struct re_save_state);
10538                 ix -= SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
10539
10540                 new_state->re_state_bostr
10541                     = pv_dup(old_state->re_state_bostr);
10542                 new_state->re_state_reginput
10543                     = pv_dup(old_state->re_state_reginput);
10544                 new_state->re_state_regeol
10545                     = pv_dup(old_state->re_state_regeol);
10546                 new_state->re_state_regstartp
10547                     = (I32*) any_dup(old_state->re_state_regstartp, proto_perl);
10548                 new_state->re_state_regendp
10549                     = (I32*) any_dup(old_state->re_state_regendp, proto_perl);
10550                 new_state->re_state_reglastparen
10551                     = (U32*) any_dup(old_state->re_state_reglastparen, 
10552                               proto_perl);
10553                 new_state->re_state_reglastcloseparen
10554                     = (U32*)any_dup(old_state->re_state_reglastcloseparen,
10555                               proto_perl);
10556                 /* XXX This just has to be broken. The old save_re_context
10557                    code did SAVEGENERICPV(PL_reg_start_tmp);
10558                    PL_reg_start_tmp is char **.
10559                    Look above to what the dup code does for
10560                    SAVEt_GENERIC_PVREF
10561                    It can never have worked.
10562                    So this is merely a faithful copy of the exiting bug:  */
10563                 new_state->re_state_reg_start_tmp
10564                     = (char **) pv_dup((char *)
10565                                       old_state->re_state_reg_start_tmp);
10566                 /* I assume that it only ever "worked" because no-one called
10567                    (pseudo)fork while the regexp engine had re-entered itself.
10568                 */
10569 #ifdef PERL_OLD_COPY_ON_WRITE
10570                 new_state->re_state_nrs
10571                     = sv_dup(old_state->re_state_nrs, param);
10572 #endif
10573                 new_state->re_state_reg_magic
10574                     = (MAGIC*) any_dup(old_state->re_state_reg_magic, 
10575                                proto_perl);
10576                 new_state->re_state_reg_oldcurpm
10577                     = (PMOP*) any_dup(old_state->re_state_reg_oldcurpm, 
10578                               proto_perl);
10579                 new_state->re_state_reg_curpm
10580                     = (PMOP*)  any_dup(old_state->re_state_reg_curpm, 
10581                                proto_perl);
10582                 new_state->re_state_reg_oldsaved
10583                     = pv_dup(old_state->re_state_reg_oldsaved);
10584                 new_state->re_state_reg_poscache
10585                     = pv_dup(old_state->re_state_reg_poscache);
10586                 new_state->re_state_reg_starttry
10587                     = pv_dup(old_state->re_state_reg_starttry);
10588                 break;
10589             }
10590         case SAVEt_COMPILE_WARNINGS:
10591             ptr = POPPTR(ss,ix);
10592             TOPPTR(nss,ix) = DUP_WARNINGS((STRLEN*)ptr);
10593             break;
10594         default:
10595             Perl_croak(aTHX_
10596                        "panic: ss_dup inconsistency (%"IVdf")", (IV) type);
10597         }
10598     }
10599
10600     return nss;
10601 }
10602
10603
10604 /* if sv is a stash, call $class->CLONE_SKIP(), and set the SVphv_CLONEABLE
10605  * flag to the result. This is done for each stash before cloning starts,
10606  * so we know which stashes want their objects cloned */
10607
10608 static void
10609 do_mark_cloneable_stash(pTHX_ SV *sv)
10610 {
10611     const HEK * const hvname = HvNAME_HEK((HV*)sv);
10612     if (hvname) {
10613         GV* const cloner = gv_fetchmethod_autoload((HV*)sv, "CLONE_SKIP", 0);
10614         SvFLAGS(sv) |= SVphv_CLONEABLE; /* clone objects by default */
10615         if (cloner && GvCV(cloner)) {
10616             dSP;
10617             UV status;
10618
10619             ENTER;
10620             SAVETMPS;
10621             PUSHMARK(SP);
10622             XPUSHs(sv_2mortal(newSVhek(hvname)));
10623             PUTBACK;
10624             call_sv((SV*)GvCV(cloner), G_SCALAR);
10625             SPAGAIN;
10626             status = POPu;
10627             PUTBACK;
10628             FREETMPS;
10629             LEAVE;
10630             if (status)
10631                 SvFLAGS(sv) &= ~SVphv_CLONEABLE;
10632         }
10633     }
10634 }
10635
10636
10637
10638 /*
10639 =for apidoc perl_clone
10640
10641 Create and return a new interpreter by cloning the current one.
10642
10643 perl_clone takes these flags as parameters:
10644
10645 CLONEf_COPY_STACKS - is used to, well, copy the stacks also,
10646 without it we only clone the data and zero the stacks,
10647 with it we copy the stacks and the new perl interpreter is
10648 ready to run at the exact same point as the previous one.
10649 The pseudo-fork code uses COPY_STACKS while the
10650 threads->new doesn't.
10651
10652 CLONEf_KEEP_PTR_TABLE
10653 perl_clone keeps a ptr_table with the pointer of the old
10654 variable as a key and the new variable as a value,
10655 this allows it to check if something has been cloned and not
10656 clone it again but rather just use the value and increase the
10657 refcount. If KEEP_PTR_TABLE is not set then perl_clone will kill
10658 the ptr_table using the function
10659 C<ptr_table_free(PL_ptr_table); PL_ptr_table = NULL;>,
10660 reason to keep it around is if you want to dup some of your own
10661 variable who are outside the graph perl scans, example of this
10662 code is in threads.xs create
10663
10664 CLONEf_CLONE_HOST
10665 This is a win32 thing, it is ignored on unix, it tells perls
10666 win32host code (which is c++) to clone itself, this is needed on
10667 win32 if you want to run two threads at the same time,
10668 if you just want to do some stuff in a separate perl interpreter
10669 and then throw it away and return to the original one,
10670 you don't need to do anything.
10671
10672 =cut
10673 */
10674
10675 /* XXX the above needs expanding by someone who actually understands it ! */
10676 EXTERN_C PerlInterpreter *
10677 perl_clone_host(PerlInterpreter* proto_perl, UV flags);
10678
10679 PerlInterpreter *
10680 perl_clone(PerlInterpreter *proto_perl, UV flags)
10681 {
10682    dVAR;
10683 #ifdef PERL_IMPLICIT_SYS
10684
10685    /* perlhost.h so we need to call into it
10686    to clone the host, CPerlHost should have a c interface, sky */
10687
10688    if (flags & CLONEf_CLONE_HOST) {
10689        return perl_clone_host(proto_perl,flags);
10690    }
10691    return perl_clone_using(proto_perl, flags,
10692                             proto_perl->IMem,
10693                             proto_perl->IMemShared,
10694                             proto_perl->IMemParse,
10695                             proto_perl->IEnv,
10696                             proto_perl->IStdIO,
10697                             proto_perl->ILIO,
10698                             proto_perl->IDir,
10699                             proto_perl->ISock,
10700                             proto_perl->IProc);
10701 }
10702
10703 PerlInterpreter *
10704 perl_clone_using(PerlInterpreter *proto_perl, UV flags,
10705                  struct IPerlMem* ipM, struct IPerlMem* ipMS,
10706                  struct IPerlMem* ipMP, struct IPerlEnv* ipE,
10707                  struct IPerlStdIO* ipStd, struct IPerlLIO* ipLIO,
10708                  struct IPerlDir* ipD, struct IPerlSock* ipS,
10709                  struct IPerlProc* ipP)
10710 {
10711     /* XXX many of the string copies here can be optimized if they're
10712      * constants; they need to be allocated as common memory and just
10713      * their pointers copied. */
10714
10715     IV i;
10716     CLONE_PARAMS clone_params;
10717     CLONE_PARAMS* const param = &clone_params;
10718
10719     PerlInterpreter * const my_perl = (PerlInterpreter*)(*ipM->pMalloc)(ipM, sizeof(PerlInterpreter));
10720     /* for each stash, determine whether its objects should be cloned */
10721     S_visit(proto_perl, do_mark_cloneable_stash, SVt_PVHV, SVTYPEMASK);
10722     PERL_SET_THX(my_perl);
10723
10724 #  ifdef DEBUGGING
10725     PoisonNew(my_perl, 1, PerlInterpreter);
10726     PL_op = NULL;
10727     PL_curcop = NULL;
10728     PL_markstack = 0;
10729     PL_scopestack = 0;
10730     PL_savestack = 0;
10731     PL_savestack_ix = 0;
10732     PL_savestack_max = -1;
10733     PL_sig_pending = 0;
10734     Zero(&PL_debug_pad, 1, struct perl_debug_pad);
10735 #  else /* !DEBUGGING */
10736     Zero(my_perl, 1, PerlInterpreter);
10737 #  endif        /* DEBUGGING */
10738
10739     /* host pointers */
10740     PL_Mem              = ipM;
10741     PL_MemShared        = ipMS;
10742     PL_MemParse         = ipMP;
10743     PL_Env              = ipE;
10744     PL_StdIO            = ipStd;
10745     PL_LIO              = ipLIO;
10746     PL_Dir              = ipD;
10747     PL_Sock             = ipS;
10748     PL_Proc             = ipP;
10749 #else           /* !PERL_IMPLICIT_SYS */
10750     IV i;
10751     CLONE_PARAMS clone_params;
10752     CLONE_PARAMS* param = &clone_params;
10753     PerlInterpreter * const my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
10754     /* for each stash, determine whether its objects should be cloned */
10755     S_visit(proto_perl, do_mark_cloneable_stash, SVt_PVHV, SVTYPEMASK);
10756     PERL_SET_THX(my_perl);
10757
10758 #    ifdef DEBUGGING
10759     PoisonNew(my_perl, 1, PerlInterpreter);
10760     PL_op = NULL;
10761     PL_curcop = NULL;
10762     PL_markstack = 0;
10763     PL_scopestack = 0;
10764     PL_savestack = 0;
10765     PL_savestack_ix = 0;
10766     PL_savestack_max = -1;
10767     PL_sig_pending = 0;
10768     Zero(&PL_debug_pad, 1, struct perl_debug_pad);
10769 #    else       /* !DEBUGGING */
10770     Zero(my_perl, 1, PerlInterpreter);
10771 #    endif      /* DEBUGGING */
10772 #endif          /* PERL_IMPLICIT_SYS */
10773     param->flags = flags;
10774     param->proto_perl = proto_perl;
10775
10776     INIT_TRACK_MEMPOOL(my_perl->Imemory_debug_header, my_perl);
10777
10778     PL_body_arenas = NULL;
10779     Zero(&PL_body_roots, 1, PL_body_roots);
10780     
10781     PL_nice_chunk       = NULL;
10782     PL_nice_chunk_size  = 0;
10783     PL_sv_count         = 0;
10784     PL_sv_objcount      = 0;
10785     PL_sv_root          = NULL;
10786     PL_sv_arenaroot     = NULL;
10787
10788     PL_debug            = proto_perl->Idebug;
10789
10790     PL_hash_seed        = proto_perl->Ihash_seed;
10791     PL_rehash_seed      = proto_perl->Irehash_seed;
10792
10793 #ifdef USE_REENTRANT_API
10794     /* XXX: things like -Dm will segfault here in perlio, but doing
10795      *  PERL_SET_CONTEXT(proto_perl);
10796      * breaks too many other things
10797      */
10798     Perl_reentrant_init(aTHX);
10799 #endif
10800
10801     /* create SV map for pointer relocation */
10802     PL_ptr_table = ptr_table_new();
10803
10804     /* initialize these special pointers as early as possible */
10805     SvANY(&PL_sv_undef)         = NULL;
10806     SvREFCNT(&PL_sv_undef)      = (~(U32)0)/2;
10807     SvFLAGS(&PL_sv_undef)       = SVf_READONLY|SVt_NULL;
10808     ptr_table_store(PL_ptr_table, &proto_perl->Isv_undef, &PL_sv_undef);
10809
10810     SvANY(&PL_sv_no)            = new_XPVNV();
10811     SvREFCNT(&PL_sv_no)         = (~(U32)0)/2;
10812     SvFLAGS(&PL_sv_no)          = SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
10813                                   |SVp_POK|SVf_POK|SVf_READONLY|SVt_PVNV;
10814     SvPV_set(&PL_sv_no, savepvn(PL_No, 0));
10815     SvCUR_set(&PL_sv_no, 0);
10816     SvLEN_set(&PL_sv_no, 1);
10817     SvIV_set(&PL_sv_no, 0);
10818     SvNV_set(&PL_sv_no, 0);
10819     ptr_table_store(PL_ptr_table, &proto_perl->Isv_no, &PL_sv_no);
10820
10821     SvANY(&PL_sv_yes)           = new_XPVNV();
10822     SvREFCNT(&PL_sv_yes)        = (~(U32)0)/2;
10823     SvFLAGS(&PL_sv_yes)         = SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
10824                                   |SVp_POK|SVf_POK|SVf_READONLY|SVt_PVNV;
10825     SvPV_set(&PL_sv_yes, savepvn(PL_Yes, 1));
10826     SvCUR_set(&PL_sv_yes, 1);
10827     SvLEN_set(&PL_sv_yes, 2);
10828     SvIV_set(&PL_sv_yes, 1);
10829     SvNV_set(&PL_sv_yes, 1);
10830     ptr_table_store(PL_ptr_table, &proto_perl->Isv_yes, &PL_sv_yes);
10831
10832     /* create (a non-shared!) shared string table */
10833     PL_strtab           = newHV();
10834     HvSHAREKEYS_off(PL_strtab);
10835     hv_ksplit(PL_strtab, HvTOTALKEYS(proto_perl->Istrtab));
10836     ptr_table_store(PL_ptr_table, proto_perl->Istrtab, PL_strtab);
10837
10838     PL_compiling = proto_perl->Icompiling;
10839
10840     /* These two PVs will be free'd special way so must set them same way op.c does */
10841     PL_compiling.cop_stashpv = savesharedpv(PL_compiling.cop_stashpv);
10842     ptr_table_store(PL_ptr_table, proto_perl->Icompiling.cop_stashpv, PL_compiling.cop_stashpv);
10843
10844     PL_compiling.cop_file    = savesharedpv(PL_compiling.cop_file);
10845     ptr_table_store(PL_ptr_table, proto_perl->Icompiling.cop_file, PL_compiling.cop_file);
10846
10847     ptr_table_store(PL_ptr_table, &proto_perl->Icompiling, &PL_compiling);
10848     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
10849     if (PL_compiling.cop_hints_hash) {
10850         HINTS_REFCNT_LOCK;
10851         PL_compiling.cop_hints_hash->refcounted_he_refcnt++;
10852         HINTS_REFCNT_UNLOCK;
10853     }
10854     PL_curcop           = (COP*)any_dup(proto_perl->Tcurcop, proto_perl);
10855
10856     /* pseudo environmental stuff */
10857     PL_origargc         = proto_perl->Iorigargc;
10858     PL_origargv         = proto_perl->Iorigargv;
10859
10860     param->stashes      = newAV();  /* Setup array of objects to call clone on */
10861
10862     /* Set tainting stuff before PerlIO_debug can possibly get called */
10863     PL_tainting         = proto_perl->Itainting;
10864     PL_taint_warn       = proto_perl->Itaint_warn;
10865
10866 #ifdef PERLIO_LAYERS
10867     /* Clone PerlIO tables as soon as we can handle general xx_dup() */
10868     PerlIO_clone(aTHX_ proto_perl, param);
10869 #endif
10870
10871     PL_envgv            = gv_dup(proto_perl->Ienvgv, param);
10872     PL_incgv            = gv_dup(proto_perl->Iincgv, param);
10873     PL_hintgv           = gv_dup(proto_perl->Ihintgv, param);
10874     PL_origfilename     = SAVEPV(proto_perl->Iorigfilename);
10875     PL_diehook          = sv_dup_inc(proto_perl->Idiehook, param);
10876     PL_warnhook         = sv_dup_inc(proto_perl->Iwarnhook, param);
10877
10878     /* switches */
10879     PL_minus_c          = proto_perl->Iminus_c;
10880     PL_patchlevel       = sv_dup_inc(proto_perl->Ipatchlevel, param);
10881     PL_localpatches     = proto_perl->Ilocalpatches;
10882     PL_splitstr         = proto_perl->Isplitstr;
10883     PL_preprocess       = proto_perl->Ipreprocess;
10884     PL_minus_n          = proto_perl->Iminus_n;
10885     PL_minus_p          = proto_perl->Iminus_p;
10886     PL_minus_l          = proto_perl->Iminus_l;
10887     PL_minus_a          = proto_perl->Iminus_a;
10888     PL_minus_E          = proto_perl->Iminus_E;
10889     PL_minus_F          = proto_perl->Iminus_F;
10890     PL_doswitches       = proto_perl->Idoswitches;
10891     PL_dowarn           = proto_perl->Idowarn;
10892     PL_doextract        = proto_perl->Idoextract;
10893     PL_sawampersand     = proto_perl->Isawampersand;
10894     PL_unsafe           = proto_perl->Iunsafe;
10895     PL_inplace          = SAVEPV(proto_perl->Iinplace);
10896     PL_e_script         = sv_dup_inc(proto_perl->Ie_script, param);
10897     PL_perldb           = proto_perl->Iperldb;
10898     PL_perl_destruct_level = proto_perl->Iperl_destruct_level;
10899     PL_exit_flags       = proto_perl->Iexit_flags;
10900
10901     /* magical thingies */
10902     /* XXX time(&PL_basetime) when asked for? */
10903     PL_basetime         = proto_perl->Ibasetime;
10904     PL_formfeed         = sv_dup(proto_perl->Iformfeed, param);
10905
10906     PL_maxsysfd         = proto_perl->Imaxsysfd;
10907     PL_statusvalue      = proto_perl->Istatusvalue;
10908 #ifdef VMS
10909     PL_statusvalue_vms  = proto_perl->Istatusvalue_vms;
10910 #else
10911     PL_statusvalue_posix = proto_perl->Istatusvalue_posix;
10912 #endif
10913     PL_encoding         = sv_dup(proto_perl->Iencoding, param);
10914
10915     sv_setpvn(PERL_DEBUG_PAD(0), "", 0);        /* For regex debugging. */
10916     sv_setpvn(PERL_DEBUG_PAD(1), "", 0);        /* ext/re needs these */
10917     sv_setpvn(PERL_DEBUG_PAD(2), "", 0);        /* even without DEBUGGING. */
10918
10919    
10920     /* RE engine related */
10921     Zero(&PL_reg_state, 1, struct re_save_state);
10922     PL_reginterp_cnt    = 0;
10923     PL_regmatch_slab    = NULL;
10924     
10925     /* Clone the regex array */
10926     PL_regex_padav = newAV();
10927     {
10928         const I32 len = av_len((AV*)proto_perl->Iregex_padav);
10929         SV* const * const regexen = AvARRAY((AV*)proto_perl->Iregex_padav);
10930         IV i;
10931         av_push(PL_regex_padav, sv_dup_inc_NN(regexen[0],param));
10932         for(i = 1; i <= len; i++) {
10933             const SV * const regex = regexen[i];
10934             SV * const sv =
10935                 SvREPADTMP(regex)
10936                     ? sv_dup_inc(regex, param)
10937                     : SvREFCNT_inc(
10938                         newSViv(PTR2IV(CALLREGDUPE(
10939                                 INT2PTR(REGEXP *, SvIVX(regex)), param))))
10940                 ;
10941             av_push(PL_regex_padav, sv);
10942         }
10943     }
10944     PL_regex_pad = AvARRAY(PL_regex_padav);
10945
10946     /* shortcuts to various I/O objects */
10947     PL_stdingv          = gv_dup(proto_perl->Istdingv, param);
10948     PL_stderrgv         = gv_dup(proto_perl->Istderrgv, param);
10949     PL_defgv            = gv_dup(proto_perl->Idefgv, param);
10950     PL_argvgv           = gv_dup(proto_perl->Iargvgv, param);
10951     PL_argvoutgv        = gv_dup(proto_perl->Iargvoutgv, param);
10952     PL_argvout_stack    = av_dup_inc(proto_perl->Iargvout_stack, param);
10953
10954     /* shortcuts to regexp stuff */
10955     PL_replgv           = gv_dup(proto_perl->Ireplgv, param);
10956
10957     /* shortcuts to misc objects */
10958     PL_errgv            = gv_dup(proto_perl->Ierrgv, param);
10959
10960     /* shortcuts to debugging objects */
10961     PL_DBgv             = gv_dup(proto_perl->IDBgv, param);
10962     PL_DBline           = gv_dup(proto_perl->IDBline, param);
10963     PL_DBsub            = gv_dup(proto_perl->IDBsub, param);
10964     PL_DBsingle         = sv_dup(proto_perl->IDBsingle, param);
10965     PL_DBtrace          = sv_dup(proto_perl->IDBtrace, param);
10966     PL_DBsignal         = sv_dup(proto_perl->IDBsignal, param);
10967     PL_DBassertion      = sv_dup(proto_perl->IDBassertion, param);
10968     PL_lineary          = av_dup(proto_perl->Ilineary, param);
10969     PL_dbargs           = av_dup(proto_perl->Idbargs, param);
10970
10971     /* symbol tables */
10972     PL_defstash         = hv_dup_inc(proto_perl->Tdefstash, param);
10973     PL_curstash         = hv_dup(proto_perl->Tcurstash, param);
10974     PL_debstash         = hv_dup(proto_perl->Idebstash, param);
10975     PL_globalstash      = hv_dup(proto_perl->Iglobalstash, param);
10976     PL_curstname        = sv_dup_inc(proto_perl->Icurstname, param);
10977
10978     PL_beginav          = av_dup_inc(proto_perl->Ibeginav, param);
10979     PL_beginav_save     = av_dup_inc(proto_perl->Ibeginav_save, param);
10980     PL_checkav_save     = av_dup_inc(proto_perl->Icheckav_save, param);
10981     PL_unitcheckav      = av_dup_inc(proto_perl->Iunitcheckav, param);
10982     PL_unitcheckav_save = av_dup_inc(proto_perl->Iunitcheckav_save, param);
10983     PL_endav            = av_dup_inc(proto_perl->Iendav, param);
10984     PL_checkav          = av_dup_inc(proto_perl->Icheckav, param);
10985     PL_initav           = av_dup_inc(proto_perl->Iinitav, param);
10986
10987     PL_sub_generation   = proto_perl->Isub_generation;
10988
10989     /* funky return mechanisms */
10990     PL_forkprocess      = proto_perl->Iforkprocess;
10991
10992     /* subprocess state */
10993     PL_fdpid            = av_dup_inc(proto_perl->Ifdpid, param);
10994
10995     /* internal state */
10996     PL_maxo             = proto_perl->Imaxo;
10997     if (proto_perl->Iop_mask)
10998         PL_op_mask      = SAVEPVN(proto_perl->Iop_mask, PL_maxo);
10999     else
11000         PL_op_mask      = NULL;
11001     /* PL_asserting        = proto_perl->Iasserting; */
11002
11003     /* current interpreter roots */
11004     PL_main_cv          = cv_dup_inc(proto_perl->Imain_cv, param);
11005     OP_REFCNT_LOCK;
11006     PL_main_root        = OpREFCNT_inc(proto_perl->Imain_root);
11007     OP_REFCNT_UNLOCK;
11008     PL_main_start       = proto_perl->Imain_start;
11009     PL_eval_root        = proto_perl->Ieval_root;
11010     PL_eval_start       = proto_perl->Ieval_start;
11011
11012     /* runtime control stuff */
11013     PL_curcopdb         = (COP*)any_dup(proto_perl->Icurcopdb, proto_perl);
11014     PL_copline          = proto_perl->Icopline;
11015
11016     PL_filemode         = proto_perl->Ifilemode;
11017     PL_lastfd           = proto_perl->Ilastfd;
11018     PL_oldname          = proto_perl->Ioldname;         /* XXX not quite right */
11019     PL_Argv             = NULL;
11020     PL_Cmd              = NULL;
11021     PL_gensym           = proto_perl->Igensym;
11022     PL_preambled        = proto_perl->Ipreambled;
11023     PL_preambleav       = av_dup_inc(proto_perl->Ipreambleav, param);
11024     PL_laststatval      = proto_perl->Ilaststatval;
11025     PL_laststype        = proto_perl->Ilaststype;
11026     PL_mess_sv          = NULL;
11027
11028     PL_ors_sv           = sv_dup_inc(proto_perl->Iors_sv, param);
11029
11030     /* interpreter atexit processing */
11031     PL_exitlistlen      = proto_perl->Iexitlistlen;
11032     if (PL_exitlistlen) {
11033         Newx(PL_exitlist, PL_exitlistlen, PerlExitListEntry);
11034         Copy(proto_perl->Iexitlist, PL_exitlist, PL_exitlistlen, PerlExitListEntry);
11035     }
11036     else
11037         PL_exitlist     = (PerlExitListEntry*)NULL;
11038
11039     PL_my_cxt_size = proto_perl->Imy_cxt_size;
11040     if (PL_my_cxt_size) {
11041         Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
11042         Copy(proto_perl->Imy_cxt_list, PL_my_cxt_list, PL_my_cxt_size, void *);
11043     }
11044     else
11045         PL_my_cxt_list  = (void**)NULL;
11046     PL_modglobal        = hv_dup_inc(proto_perl->Imodglobal, param);
11047     PL_custom_op_names  = hv_dup_inc(proto_perl->Icustom_op_names,param);
11048     PL_custom_op_descs  = hv_dup_inc(proto_perl->Icustom_op_descs,param);
11049
11050     PL_profiledata      = NULL;
11051     PL_rsfp             = fp_dup(proto_perl->Irsfp, '<', param);
11052     /* PL_rsfp_filters entries have fake IoDIRP() */
11053     PL_rsfp_filters     = av_dup_inc(proto_perl->Irsfp_filters, param);
11054
11055     PL_compcv                   = cv_dup(proto_perl->Icompcv, param);
11056
11057     PAD_CLONE_VARS(proto_perl, param);
11058
11059 #ifdef HAVE_INTERP_INTERN
11060     sys_intern_dup(&proto_perl->Isys_intern, &PL_sys_intern);
11061 #endif
11062
11063     /* more statics moved here */
11064     PL_generation       = proto_perl->Igeneration;
11065     PL_DBcv             = cv_dup(proto_perl->IDBcv, param);
11066
11067     PL_in_clean_objs    = proto_perl->Iin_clean_objs;
11068     PL_in_clean_all     = proto_perl->Iin_clean_all;
11069
11070     PL_uid              = proto_perl->Iuid;
11071     PL_euid             = proto_perl->Ieuid;
11072     PL_gid              = proto_perl->Igid;
11073     PL_egid             = proto_perl->Iegid;
11074     PL_nomemok          = proto_perl->Inomemok;
11075     PL_an               = proto_perl->Ian;
11076     PL_evalseq          = proto_perl->Ievalseq;
11077     PL_origenviron      = proto_perl->Iorigenviron;     /* XXX not quite right */
11078     PL_origalen         = proto_perl->Iorigalen;
11079 #ifdef PERL_USES_PL_PIDSTATUS
11080     PL_pidstatus        = newHV();                      /* XXX flag for cloning? */
11081 #endif
11082     PL_osname           = SAVEPV(proto_perl->Iosname);
11083     PL_sighandlerp      = proto_perl->Isighandlerp;
11084
11085     PL_runops           = proto_perl->Irunops;
11086
11087     Copy(proto_perl->Itokenbuf, PL_tokenbuf, 256, char);
11088
11089 #ifdef CSH
11090     PL_cshlen           = proto_perl->Icshlen;
11091     PL_cshname          = proto_perl->Icshname; /* XXX never deallocated */
11092 #endif
11093
11094     PL_lex_state        = proto_perl->Ilex_state;
11095     PL_lex_defer        = proto_perl->Ilex_defer;
11096     PL_lex_expect       = proto_perl->Ilex_expect;
11097     PL_lex_formbrack    = proto_perl->Ilex_formbrack;
11098     PL_lex_dojoin       = proto_perl->Ilex_dojoin;
11099     PL_lex_starts       = proto_perl->Ilex_starts;
11100     PL_lex_stuff        = sv_dup_inc(proto_perl->Ilex_stuff, param);
11101     PL_lex_repl         = sv_dup_inc(proto_perl->Ilex_repl, param);
11102     PL_lex_op           = proto_perl->Ilex_op;
11103     PL_lex_inpat        = proto_perl->Ilex_inpat;
11104     PL_lex_inwhat       = proto_perl->Ilex_inwhat;
11105     PL_lex_brackets     = proto_perl->Ilex_brackets;
11106     i = (PL_lex_brackets < 120 ? 120 : PL_lex_brackets);
11107     PL_lex_brackstack   = SAVEPVN(proto_perl->Ilex_brackstack,i);
11108     PL_lex_casemods     = proto_perl->Ilex_casemods;
11109     i = (PL_lex_casemods < 12 ? 12 : PL_lex_casemods);
11110     PL_lex_casestack    = SAVEPVN(proto_perl->Ilex_casestack,i);
11111
11112 #ifdef PERL_MAD
11113     Copy(proto_perl->Inexttoke, PL_nexttoke, 5, NEXTTOKE);
11114     PL_lasttoke         = proto_perl->Ilasttoke;
11115     PL_realtokenstart   = proto_perl->Irealtokenstart;
11116     PL_faketokens       = proto_perl->Ifaketokens;
11117     PL_thismad          = proto_perl->Ithismad;
11118     PL_thistoken        = proto_perl->Ithistoken;
11119     PL_thisopen         = proto_perl->Ithisopen;
11120     PL_thisstuff        = proto_perl->Ithisstuff;
11121     PL_thisclose        = proto_perl->Ithisclose;
11122     PL_thiswhite        = proto_perl->Ithiswhite;
11123     PL_nextwhite        = proto_perl->Inextwhite;
11124     PL_skipwhite        = proto_perl->Iskipwhite;
11125     PL_endwhite         = proto_perl->Iendwhite;
11126     PL_curforce         = proto_perl->Icurforce;
11127 #else
11128     Copy(proto_perl->Inextval, PL_nextval, 5, YYSTYPE);
11129     Copy(proto_perl->Inexttype, PL_nexttype, 5, I32);
11130     PL_nexttoke         = proto_perl->Inexttoke;
11131 #endif
11132
11133     /* XXX This is probably masking the deeper issue of why
11134      * SvANY(proto_perl->Ilinestr) can be NULL at this point. For test case:
11135      * http://archive.develooper.com/perl5-porters%40perl.org/msg83298.html
11136      * (A little debugging with a watchpoint on it may help.)
11137      */
11138     if (SvANY(proto_perl->Ilinestr)) {
11139         PL_linestr              = sv_dup_inc(proto_perl->Ilinestr, param);
11140         i = proto_perl->Ibufptr - SvPVX_const(proto_perl->Ilinestr);
11141         PL_bufptr               = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11142         i = proto_perl->Ioldbufptr - SvPVX_const(proto_perl->Ilinestr);
11143         PL_oldbufptr    = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11144         i = proto_perl->Ioldoldbufptr - SvPVX_const(proto_perl->Ilinestr);
11145         PL_oldoldbufptr = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11146         i = proto_perl->Ilinestart - SvPVX_const(proto_perl->Ilinestr);
11147         PL_linestart    = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11148     }
11149     else {
11150         PL_linestr = newSV(79);
11151         sv_upgrade(PL_linestr,SVt_PVIV);
11152         sv_setpvn(PL_linestr,"",0);
11153         PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart = SvPVX(PL_linestr);
11154     }
11155     PL_bufend           = SvPVX(PL_linestr) + SvCUR(PL_linestr);
11156     PL_pending_ident    = proto_perl->Ipending_ident;
11157     PL_sublex_info      = proto_perl->Isublex_info;     /* XXX not quite right */
11158
11159     PL_expect           = proto_perl->Iexpect;
11160
11161     PL_multi_start      = proto_perl->Imulti_start;
11162     PL_multi_end        = proto_perl->Imulti_end;
11163     PL_multi_open       = proto_perl->Imulti_open;
11164     PL_multi_close      = proto_perl->Imulti_close;
11165
11166     PL_error_count      = proto_perl->Ierror_count;
11167     PL_subline          = proto_perl->Isubline;
11168     PL_subname          = sv_dup_inc(proto_perl->Isubname, param);
11169
11170     /* XXX See comment on SvANY(proto_perl->Ilinestr) above */
11171     if (SvANY(proto_perl->Ilinestr)) {
11172         i = proto_perl->Ilast_uni - SvPVX_const(proto_perl->Ilinestr);
11173         PL_last_uni             = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11174         i = proto_perl->Ilast_lop - SvPVX_const(proto_perl->Ilinestr);
11175         PL_last_lop             = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11176         PL_last_lop_op  = proto_perl->Ilast_lop_op;
11177     }
11178     else {
11179         PL_last_uni     = SvPVX(PL_linestr);
11180         PL_last_lop     = SvPVX(PL_linestr);
11181         PL_last_lop_op  = 0;
11182     }
11183     PL_in_my            = proto_perl->Iin_my;
11184     PL_in_my_stash      = hv_dup(proto_perl->Iin_my_stash, param);
11185 #ifdef FCRYPT
11186     PL_cryptseen        = proto_perl->Icryptseen;
11187 #endif
11188
11189     PL_hints            = proto_perl->Ihints;
11190
11191     PL_amagic_generation        = proto_perl->Iamagic_generation;
11192
11193 #ifdef USE_LOCALE_COLLATE
11194     PL_collation_ix     = proto_perl->Icollation_ix;
11195     PL_collation_name   = SAVEPV(proto_perl->Icollation_name);
11196     PL_collation_standard       = proto_perl->Icollation_standard;
11197     PL_collxfrm_base    = proto_perl->Icollxfrm_base;
11198     PL_collxfrm_mult    = proto_perl->Icollxfrm_mult;
11199 #endif /* USE_LOCALE_COLLATE */
11200
11201 #ifdef USE_LOCALE_NUMERIC
11202     PL_numeric_name     = SAVEPV(proto_perl->Inumeric_name);
11203     PL_numeric_standard = proto_perl->Inumeric_standard;
11204     PL_numeric_local    = proto_perl->Inumeric_local;
11205     PL_numeric_radix_sv = sv_dup_inc(proto_perl->Inumeric_radix_sv, param);
11206 #endif /* !USE_LOCALE_NUMERIC */
11207
11208     /* utf8 character classes */
11209     PL_utf8_alnum       = sv_dup_inc(proto_perl->Iutf8_alnum, param);
11210     PL_utf8_alnumc      = sv_dup_inc(proto_perl->Iutf8_alnumc, param);
11211     PL_utf8_ascii       = sv_dup_inc(proto_perl->Iutf8_ascii, param);
11212     PL_utf8_alpha       = sv_dup_inc(proto_perl->Iutf8_alpha, param);
11213     PL_utf8_space       = sv_dup_inc(proto_perl->Iutf8_space, param);
11214     PL_utf8_cntrl       = sv_dup_inc(proto_perl->Iutf8_cntrl, param);
11215     PL_utf8_graph       = sv_dup_inc(proto_perl->Iutf8_graph, param);
11216     PL_utf8_digit       = sv_dup_inc(proto_perl->Iutf8_digit, param);
11217     PL_utf8_upper       = sv_dup_inc(proto_perl->Iutf8_upper, param);
11218     PL_utf8_lower       = sv_dup_inc(proto_perl->Iutf8_lower, param);
11219     PL_utf8_print       = sv_dup_inc(proto_perl->Iutf8_print, param);
11220     PL_utf8_punct       = sv_dup_inc(proto_perl->Iutf8_punct, param);
11221     PL_utf8_xdigit      = sv_dup_inc(proto_perl->Iutf8_xdigit, param);
11222     PL_utf8_mark        = sv_dup_inc(proto_perl->Iutf8_mark, param);
11223     PL_utf8_toupper     = sv_dup_inc(proto_perl->Iutf8_toupper, param);
11224     PL_utf8_totitle     = sv_dup_inc(proto_perl->Iutf8_totitle, param);
11225     PL_utf8_tolower     = sv_dup_inc(proto_perl->Iutf8_tolower, param);
11226     PL_utf8_tofold      = sv_dup_inc(proto_perl->Iutf8_tofold, param);
11227     PL_utf8_idstart     = sv_dup_inc(proto_perl->Iutf8_idstart, param);
11228     PL_utf8_idcont      = sv_dup_inc(proto_perl->Iutf8_idcont, param);
11229
11230     /* Did the locale setup indicate UTF-8? */
11231     PL_utf8locale       = proto_perl->Iutf8locale;
11232     /* Unicode features (see perlrun/-C) */
11233     PL_unicode          = proto_perl->Iunicode;
11234
11235     /* Pre-5.8 signals control */
11236     PL_signals          = proto_perl->Isignals;
11237
11238     /* times() ticks per second */
11239     PL_clocktick        = proto_perl->Iclocktick;
11240
11241     /* Recursion stopper for PerlIO_find_layer */
11242     PL_in_load_module   = proto_perl->Iin_load_module;
11243
11244     /* sort() routine */
11245     PL_sort_RealCmp     = proto_perl->Isort_RealCmp;
11246
11247     /* Not really needed/useful since the reenrant_retint is "volatile",
11248      * but do it for consistency's sake. */
11249     PL_reentrant_retint = proto_perl->Ireentrant_retint;
11250
11251     /* Hooks to shared SVs and locks. */
11252     PL_sharehook        = proto_perl->Isharehook;
11253     PL_lockhook         = proto_perl->Ilockhook;
11254     PL_unlockhook       = proto_perl->Iunlockhook;
11255     PL_threadhook       = proto_perl->Ithreadhook;
11256
11257     PL_runops_std       = proto_perl->Irunops_std;
11258     PL_runops_dbg       = proto_perl->Irunops_dbg;
11259
11260 #ifdef THREADS_HAVE_PIDS
11261     PL_ppid             = proto_perl->Ippid;
11262 #endif
11263
11264     /* swatch cache */
11265     PL_last_swash_hv    = NULL; /* reinits on demand */
11266     PL_last_swash_klen  = 0;
11267     PL_last_swash_key[0]= '\0';
11268     PL_last_swash_tmps  = (U8*)NULL;
11269     PL_last_swash_slen  = 0;
11270
11271     PL_glob_index       = proto_perl->Iglob_index;
11272     PL_srand_called     = proto_perl->Isrand_called;
11273     PL_uudmap[(U32) 'M']        = 0;    /* reinits on demand */
11274     PL_bitcount         = NULL; /* reinits on demand */
11275
11276     if (proto_perl->Ipsig_pend) {
11277         Newxz(PL_psig_pend, SIG_SIZE, int);
11278     }
11279     else {
11280         PL_psig_pend    = (int*)NULL;
11281     }
11282
11283     if (proto_perl->Ipsig_ptr) {
11284         Newxz(PL_psig_ptr,  SIG_SIZE, SV*);
11285         Newxz(PL_psig_name, SIG_SIZE, SV*);
11286         for (i = 1; i < SIG_SIZE; i++) {
11287             PL_psig_ptr[i]  = sv_dup_inc(proto_perl->Ipsig_ptr[i], param);
11288             PL_psig_name[i] = sv_dup_inc(proto_perl->Ipsig_name[i], param);
11289         }
11290     }
11291     else {
11292         PL_psig_ptr     = (SV**)NULL;
11293         PL_psig_name    = (SV**)NULL;
11294     }
11295
11296     /* thrdvar.h stuff */
11297
11298     if (flags & CLONEf_COPY_STACKS) {
11299         /* next allocation will be PL_tmps_stack[PL_tmps_ix+1] */
11300         PL_tmps_ix              = proto_perl->Ttmps_ix;
11301         PL_tmps_max             = proto_perl->Ttmps_max;
11302         PL_tmps_floor           = proto_perl->Ttmps_floor;
11303         Newxz(PL_tmps_stack, PL_tmps_max, SV*);
11304         i = 0;
11305         while (i <= PL_tmps_ix) {
11306             PL_tmps_stack[i]    = sv_dup_inc(proto_perl->Ttmps_stack[i], param);
11307             ++i;
11308         }
11309
11310         /* next PUSHMARK() sets *(PL_markstack_ptr+1) */
11311         i = proto_perl->Tmarkstack_max - proto_perl->Tmarkstack;
11312         Newxz(PL_markstack, i, I32);
11313         PL_markstack_max        = PL_markstack + (proto_perl->Tmarkstack_max
11314                                                   - proto_perl->Tmarkstack);
11315         PL_markstack_ptr        = PL_markstack + (proto_perl->Tmarkstack_ptr
11316                                                   - proto_perl->Tmarkstack);
11317         Copy(proto_perl->Tmarkstack, PL_markstack,
11318              PL_markstack_ptr - PL_markstack + 1, I32);
11319
11320         /* next push_scope()/ENTER sets PL_scopestack[PL_scopestack_ix]
11321          * NOTE: unlike the others! */
11322         PL_scopestack_ix        = proto_perl->Tscopestack_ix;
11323         PL_scopestack_max       = proto_perl->Tscopestack_max;
11324         Newxz(PL_scopestack, PL_scopestack_max, I32);
11325         Copy(proto_perl->Tscopestack, PL_scopestack, PL_scopestack_ix, I32);
11326
11327         /* NOTE: si_dup() looks at PL_markstack */
11328         PL_curstackinfo         = si_dup(proto_perl->Tcurstackinfo, param);
11329
11330         /* PL_curstack          = PL_curstackinfo->si_stack; */
11331         PL_curstack             = av_dup(proto_perl->Tcurstack, param);
11332         PL_mainstack            = av_dup(proto_perl->Tmainstack, param);
11333
11334         /* next PUSHs() etc. set *(PL_stack_sp+1) */
11335         PL_stack_base           = AvARRAY(PL_curstack);
11336         PL_stack_sp             = PL_stack_base + (proto_perl->Tstack_sp
11337                                                    - proto_perl->Tstack_base);
11338         PL_stack_max            = PL_stack_base + AvMAX(PL_curstack);
11339
11340         /* next SSPUSHFOO() sets PL_savestack[PL_savestack_ix]
11341          * NOTE: unlike the others! */
11342         PL_savestack_ix         = proto_perl->Tsavestack_ix;
11343         PL_savestack_max        = proto_perl->Tsavestack_max;
11344         /*Newxz(PL_savestack, PL_savestack_max, ANY);*/
11345         PL_savestack            = ss_dup(proto_perl, param);
11346     }
11347     else {
11348         init_stacks();
11349         ENTER;                  /* perl_destruct() wants to LEAVE; */
11350
11351         /* although we're not duplicating the tmps stack, we should still
11352          * add entries for any SVs on the tmps stack that got cloned by a
11353          * non-refcount means (eg a temp in @_); otherwise they will be
11354          * orphaned
11355          */
11356         for (i = 0; i<= proto_perl->Ttmps_ix; i++) {
11357             SV * const nsv = (SV*)ptr_table_fetch(PL_ptr_table,
11358                     proto_perl->Ttmps_stack[i]);
11359             if (nsv && !SvREFCNT(nsv)) {
11360                 EXTEND_MORTAL(1);
11361                 PL_tmps_stack[++PL_tmps_ix] = SvREFCNT_inc_simple(nsv);
11362             }
11363         }
11364     }
11365
11366     PL_start_env        = proto_perl->Tstart_env;       /* XXXXXX */
11367     PL_top_env          = &PL_start_env;
11368
11369     PL_op               = proto_perl->Top;
11370
11371     PL_Sv               = NULL;
11372     PL_Xpv              = (XPV*)NULL;
11373     PL_na               = proto_perl->Tna;
11374
11375     PL_statbuf          = proto_perl->Tstatbuf;
11376     PL_statcache        = proto_perl->Tstatcache;
11377     PL_statgv           = gv_dup(proto_perl->Tstatgv, param);
11378     PL_statname         = sv_dup_inc(proto_perl->Tstatname, param);
11379 #ifdef HAS_TIMES
11380     PL_timesbuf         = proto_perl->Ttimesbuf;
11381 #endif
11382
11383     PL_tainted          = proto_perl->Ttainted;
11384     PL_curpm            = proto_perl->Tcurpm;   /* XXX No PMOP ref count */
11385     PL_rs               = sv_dup_inc(proto_perl->Trs, param);
11386     PL_last_in_gv       = gv_dup(proto_perl->Tlast_in_gv, param);
11387     PL_ofs_sv           = sv_dup_inc(proto_perl->Tofs_sv, param);
11388     PL_defoutgv         = gv_dup_inc(proto_perl->Tdefoutgv, param);
11389     PL_chopset          = proto_perl->Tchopset; /* XXX never deallocated */
11390     PL_toptarget        = sv_dup_inc(proto_perl->Ttoptarget, param);
11391     PL_bodytarget       = sv_dup_inc(proto_perl->Tbodytarget, param);
11392     PL_formtarget       = sv_dup(proto_perl->Tformtarget, param);
11393
11394     PL_restartop        = proto_perl->Trestartop;
11395     PL_in_eval          = proto_perl->Tin_eval;
11396     PL_delaymagic       = proto_perl->Tdelaymagic;
11397     PL_dirty            = proto_perl->Tdirty;
11398     PL_localizing       = proto_perl->Tlocalizing;
11399
11400     PL_errors           = sv_dup_inc(proto_perl->Terrors, param);
11401     PL_hv_fetch_ent_mh  = NULL;
11402     PL_modcount         = proto_perl->Tmodcount;
11403     PL_lastgotoprobe    = NULL;
11404     PL_dumpindent       = proto_perl->Tdumpindent;
11405
11406     PL_sortcop          = (OP*)any_dup(proto_perl->Tsortcop, proto_perl);
11407     PL_sortstash        = hv_dup(proto_perl->Tsortstash, param);
11408     PL_firstgv          = gv_dup(proto_perl->Tfirstgv, param);
11409     PL_secondgv         = gv_dup(proto_perl->Tsecondgv, param);
11410     PL_efloatbuf        = NULL;         /* reinits on demand */
11411     PL_efloatsize       = 0;                    /* reinits on demand */
11412
11413     /* regex stuff */
11414
11415     PL_screamfirst      = NULL;
11416     PL_screamnext       = NULL;
11417     PL_maxscream        = -1;                   /* reinits on demand */
11418     PL_lastscream       = NULL;
11419
11420     PL_watchaddr        = NULL;
11421     PL_watchok          = NULL;
11422
11423     PL_regdummy         = proto_perl->Tregdummy;
11424     PL_colorset         = 0;            /* reinits PL_colors[] */
11425     /*PL_colors[6]      = {0,0,0,0,0,0};*/
11426
11427
11428
11429     /* Pluggable optimizer */
11430     PL_peepp            = proto_perl->Tpeepp;
11431
11432     PL_stashcache       = newHV();
11433
11434     if (!(flags & CLONEf_KEEP_PTR_TABLE)) {
11435         ptr_table_free(PL_ptr_table);
11436         PL_ptr_table = NULL;
11437     }
11438
11439     /* Call the ->CLONE method, if it exists, for each of the stashes
11440        identified by sv_dup() above.
11441     */
11442     while(av_len(param->stashes) != -1) {
11443         HV* const stash = (HV*) av_shift(param->stashes);
11444         GV* const cloner = gv_fetchmethod_autoload(stash, "CLONE", 0);
11445         if (cloner && GvCV(cloner)) {
11446             dSP;
11447             ENTER;
11448             SAVETMPS;
11449             PUSHMARK(SP);
11450             XPUSHs(sv_2mortal(newSVhek(HvNAME_HEK(stash))));
11451             PUTBACK;
11452             call_sv((SV*)GvCV(cloner), G_DISCARD);
11453             FREETMPS;
11454             LEAVE;
11455         }
11456     }
11457
11458     SvREFCNT_dec(param->stashes);
11459
11460     /* orphaned? eg threads->new inside BEGIN or use */
11461     if (PL_compcv && ! SvREFCNT(PL_compcv)) {
11462         SvREFCNT_inc_simple_void(PL_compcv);
11463         SAVEFREESV(PL_compcv);
11464     }
11465
11466     return my_perl;
11467 }
11468
11469 #endif /* USE_ITHREADS */
11470
11471 /*
11472 =head1 Unicode Support
11473
11474 =for apidoc sv_recode_to_utf8
11475
11476 The encoding is assumed to be an Encode object, on entry the PV
11477 of the sv is assumed to be octets in that encoding, and the sv
11478 will be converted into Unicode (and UTF-8).
11479
11480 If the sv already is UTF-8 (or if it is not POK), or if the encoding
11481 is not a reference, nothing is done to the sv.  If the encoding is not
11482 an C<Encode::XS> Encoding object, bad things will happen.
11483 (See F<lib/encoding.pm> and L<Encode>).
11484
11485 The PV of the sv is returned.
11486
11487 =cut */
11488
11489 char *
11490 Perl_sv_recode_to_utf8(pTHX_ SV *sv, SV *encoding)
11491 {
11492     dVAR;
11493     if (SvPOK(sv) && !SvUTF8(sv) && !IN_BYTES && SvROK(encoding)) {
11494         SV *uni;
11495         STRLEN len;
11496         const char *s;
11497         dSP;
11498         ENTER;
11499         SAVETMPS;
11500         save_re_context();
11501         PUSHMARK(sp);
11502         EXTEND(SP, 3);
11503         XPUSHs(encoding);
11504         XPUSHs(sv);
11505 /*
11506   NI-S 2002/07/09
11507   Passing sv_yes is wrong - it needs to be or'ed set of constants
11508   for Encode::XS, while UTf-8 decode (currently) assumes a true value means
11509   remove converted chars from source.
11510
11511   Both will default the value - let them.
11512
11513         XPUSHs(&PL_sv_yes);
11514 */
11515         PUTBACK;
11516         call_method("decode", G_SCALAR);
11517         SPAGAIN;
11518         uni = POPs;
11519         PUTBACK;
11520         s = SvPV_const(uni, len);
11521         if (s != SvPVX_const(sv)) {
11522             SvGROW(sv, len + 1);
11523             Move(s, SvPVX(sv), len + 1, char);
11524             SvCUR_set(sv, len);
11525         }
11526         FREETMPS;
11527         LEAVE;
11528         SvUTF8_on(sv);
11529         return SvPVX(sv);
11530     }
11531     return SvPOKp(sv) ? SvPVX(sv) : NULL;
11532 }
11533
11534 /*
11535 =for apidoc sv_cat_decode
11536
11537 The encoding is assumed to be an Encode object, the PV of the ssv is
11538 assumed to be octets in that encoding and decoding the input starts
11539 from the position which (PV + *offset) pointed to.  The dsv will be
11540 concatenated the decoded UTF-8 string from ssv.  Decoding will terminate
11541 when the string tstr appears in decoding output or the input ends on
11542 the PV of the ssv. The value which the offset points will be modified
11543 to the last input position on the ssv.
11544
11545 Returns TRUE if the terminator was found, else returns FALSE.
11546
11547 =cut */
11548
11549 bool
11550 Perl_sv_cat_decode(pTHX_ SV *dsv, SV *encoding,
11551                    SV *ssv, int *offset, char *tstr, int tlen)
11552 {
11553     dVAR;
11554     bool ret = FALSE;
11555     if (SvPOK(ssv) && SvPOK(dsv) && SvROK(encoding) && offset) {
11556         SV *offsv;
11557         dSP;
11558         ENTER;
11559         SAVETMPS;
11560         save_re_context();
11561         PUSHMARK(sp);
11562         EXTEND(SP, 6);
11563         XPUSHs(encoding);
11564         XPUSHs(dsv);
11565         XPUSHs(ssv);
11566         XPUSHs(offsv = sv_2mortal(newSViv(*offset)));
11567         XPUSHs(sv_2mortal(newSVpvn(tstr, tlen)));
11568         PUTBACK;
11569         call_method("cat_decode", G_SCALAR);
11570         SPAGAIN;
11571         ret = SvTRUE(TOPs);
11572         *offset = SvIV(offsv);
11573         PUTBACK;
11574         FREETMPS;
11575         LEAVE;
11576     }
11577     else
11578         Perl_croak(aTHX_ "Invalid argument to sv_cat_decode");
11579     return ret;
11580
11581 }
11582
11583 /* ---------------------------------------------------------------------
11584  *
11585  * support functions for report_uninit()
11586  */
11587
11588 /* the maxiumum size of array or hash where we will scan looking
11589  * for the undefined element that triggered the warning */
11590
11591 #define FUV_MAX_SEARCH_SIZE 1000
11592
11593 /* Look for an entry in the hash whose value has the same SV as val;
11594  * If so, return a mortal copy of the key. */
11595
11596 STATIC SV*
11597 S_find_hash_subscript(pTHX_ HV *hv, SV* val)
11598 {
11599     dVAR;
11600     register HE **array;
11601     I32 i;
11602
11603     if (!hv || SvMAGICAL(hv) || !HvARRAY(hv) ||
11604                         (HvTOTALKEYS(hv) > FUV_MAX_SEARCH_SIZE))
11605         return NULL;
11606
11607     array = HvARRAY(hv);
11608
11609     for (i=HvMAX(hv); i>0; i--) {
11610         register HE *entry;
11611         for (entry = array[i]; entry; entry = HeNEXT(entry)) {
11612             if (HeVAL(entry) != val)
11613                 continue;
11614             if (    HeVAL(entry) == &PL_sv_undef ||
11615                     HeVAL(entry) == &PL_sv_placeholder)
11616                 continue;
11617             if (!HeKEY(entry))
11618                 return NULL;
11619             if (HeKLEN(entry) == HEf_SVKEY)
11620                 return sv_mortalcopy(HeKEY_sv(entry));
11621             return sv_2mortal(newSVpvn(HeKEY(entry), HeKLEN(entry)));
11622         }
11623     }
11624     return NULL;
11625 }
11626
11627 /* Look for an entry in the array whose value has the same SV as val;
11628  * If so, return the index, otherwise return -1. */
11629
11630 STATIC I32
11631 S_find_array_subscript(pTHX_ AV *av, SV* val)
11632 {
11633     dVAR;
11634     if (!av || SvMAGICAL(av) || !AvARRAY(av) ||
11635                         (AvFILLp(av) > FUV_MAX_SEARCH_SIZE))
11636         return -1;
11637
11638     if (val != &PL_sv_undef) {
11639         SV ** const svp = AvARRAY(av);
11640         I32 i;
11641
11642         for (i=AvFILLp(av); i>=0; i--)
11643             if (svp[i] == val)
11644                 return i;
11645     }
11646     return -1;
11647 }
11648
11649 /* S_varname(): return the name of a variable, optionally with a subscript.
11650  * If gv is non-zero, use the name of that global, along with gvtype (one
11651  * of "$", "@", "%"); otherwise use the name of the lexical at pad offset
11652  * targ.  Depending on the value of the subscript_type flag, return:
11653  */
11654
11655 #define FUV_SUBSCRIPT_NONE      1       /* "@foo"          */
11656 #define FUV_SUBSCRIPT_ARRAY     2       /* "$foo[aindex]"  */
11657 #define FUV_SUBSCRIPT_HASH      3       /* "$foo{keyname}" */
11658 #define FUV_SUBSCRIPT_WITHIN    4       /* "within @foo"   */
11659
11660 STATIC SV*
11661 S_varname(pTHX_ GV *gv, const char gvtype, PADOFFSET targ,
11662         SV* keyname, I32 aindex, int subscript_type)
11663 {
11664
11665     SV * const name = sv_newmortal();
11666     if (gv) {
11667         char buffer[2];
11668         buffer[0] = gvtype;
11669         buffer[1] = 0;
11670
11671         /* as gv_fullname4(), but add literal '^' for $^FOO names  */
11672
11673         gv_fullname4(name, gv, buffer, 0);
11674
11675         if ((unsigned int)SvPVX(name)[1] <= 26) {
11676             buffer[0] = '^';
11677             buffer[1] = SvPVX(name)[1] + 'A' - 1;
11678
11679             /* Swap the 1 unprintable control character for the 2 byte pretty
11680                version - ie substr($name, 1, 1) = $buffer; */
11681             sv_insert(name, 1, 1, buffer, 2);
11682         }
11683     }
11684     else {
11685         U32 unused;
11686         CV * const cv = find_runcv(&unused);
11687         SV *sv;
11688         AV *av;
11689
11690         if (!cv || !CvPADLIST(cv))
11691             return NULL;
11692         av = (AV*)(*av_fetch(CvPADLIST(cv), 0, FALSE));
11693         sv = *av_fetch(av, targ, FALSE);
11694         /* SvLEN in a pad name is not to be trusted */
11695         sv_setpv(name, SvPV_nolen_const(sv));
11696     }
11697
11698     if (subscript_type == FUV_SUBSCRIPT_HASH) {
11699         SV * const sv = newSV(0);
11700         *SvPVX(name) = '$';
11701         Perl_sv_catpvf(aTHX_ name, "{%s}",
11702             pv_display(sv,SvPVX_const(keyname), SvCUR(keyname), 0, 32));
11703         SvREFCNT_dec(sv);
11704     }
11705     else if (subscript_type == FUV_SUBSCRIPT_ARRAY) {
11706         *SvPVX(name) = '$';
11707         Perl_sv_catpvf(aTHX_ name, "[%"IVdf"]", (IV)aindex);
11708     }
11709     else if (subscript_type == FUV_SUBSCRIPT_WITHIN)
11710         Perl_sv_insert(aTHX_ name, 0, 0,  STR_WITH_LEN("within "));
11711
11712     return name;
11713 }
11714
11715
11716 /*
11717 =for apidoc find_uninit_var
11718
11719 Find the name of the undefined variable (if any) that caused the operator o
11720 to issue a "Use of uninitialized value" warning.
11721 If match is true, only return a name if it's value matches uninit_sv.
11722 So roughly speaking, if a unary operator (such as OP_COS) generates a
11723 warning, then following the direct child of the op may yield an
11724 OP_PADSV or OP_GV that gives the name of the undefined variable. On the
11725 other hand, with OP_ADD there are two branches to follow, so we only print
11726 the variable name if we get an exact match.
11727
11728 The name is returned as a mortal SV.
11729
11730 Assumes that PL_op is the op that originally triggered the error, and that
11731 PL_comppad/PL_curpad points to the currently executing pad.
11732
11733 =cut
11734 */
11735
11736 STATIC SV *
11737 S_find_uninit_var(pTHX_ OP* obase, SV* uninit_sv, bool match)
11738 {
11739     dVAR;
11740     SV *sv;
11741     AV *av;
11742     GV *gv;
11743     OP *o, *o2, *kid;
11744
11745     if (!obase || (match && (!uninit_sv || uninit_sv == &PL_sv_undef ||
11746                             uninit_sv == &PL_sv_placeholder)))
11747         return NULL;
11748
11749     switch (obase->op_type) {
11750
11751     case OP_RV2AV:
11752     case OP_RV2HV:
11753     case OP_PADAV:
11754     case OP_PADHV:
11755       {
11756         const bool pad  = (obase->op_type == OP_PADAV || obase->op_type == OP_PADHV);
11757         const bool hash = (obase->op_type == OP_PADHV || obase->op_type == OP_RV2HV);
11758         I32 index = 0;
11759         SV *keysv = NULL;
11760         int subscript_type = FUV_SUBSCRIPT_WITHIN;
11761
11762         if (pad) { /* @lex, %lex */
11763             sv = PAD_SVl(obase->op_targ);
11764             gv = NULL;
11765         }
11766         else {
11767             if (cUNOPx(obase)->op_first->op_type == OP_GV) {
11768             /* @global, %global */
11769                 gv = cGVOPx_gv(cUNOPx(obase)->op_first);
11770                 if (!gv)
11771                     break;
11772                 sv = hash ? (SV*)GvHV(gv): (SV*)GvAV(gv);
11773             }
11774             else /* @{expr}, %{expr} */
11775                 return find_uninit_var(cUNOPx(obase)->op_first,
11776                                                     uninit_sv, match);
11777         }
11778
11779         /* attempt to find a match within the aggregate */
11780         if (hash) {
11781             keysv = find_hash_subscript((HV*)sv, uninit_sv);
11782             if (keysv)
11783                 subscript_type = FUV_SUBSCRIPT_HASH;
11784         }
11785         else {
11786             index = find_array_subscript((AV*)sv, uninit_sv);
11787             if (index >= 0)
11788                 subscript_type = FUV_SUBSCRIPT_ARRAY;
11789         }
11790
11791         if (match && subscript_type == FUV_SUBSCRIPT_WITHIN)
11792             break;
11793
11794         return varname(gv, hash ? '%' : '@', obase->op_targ,
11795                                     keysv, index, subscript_type);
11796       }
11797
11798     case OP_PADSV:
11799         if (match && PAD_SVl(obase->op_targ) != uninit_sv)
11800             break;
11801         return varname(NULL, '$', obase->op_targ,
11802                                     NULL, 0, FUV_SUBSCRIPT_NONE);
11803
11804     case OP_GVSV:
11805         gv = cGVOPx_gv(obase);
11806         if (!gv || (match && GvSV(gv) != uninit_sv))
11807             break;
11808         return varname(gv, '$', 0, NULL, 0, FUV_SUBSCRIPT_NONE);
11809
11810     case OP_AELEMFAST:
11811         if (obase->op_flags & OPf_SPECIAL) { /* lexical array */
11812             if (match) {
11813                 SV **svp;
11814                 av = (AV*)PAD_SV(obase->op_targ);
11815                 if (!av || SvRMAGICAL(av))
11816                     break;
11817                 svp = av_fetch(av, (I32)obase->op_private, FALSE);
11818                 if (!svp || *svp != uninit_sv)
11819                     break;
11820             }
11821             return varname(NULL, '$', obase->op_targ,
11822                     NULL, (I32)obase->op_private, FUV_SUBSCRIPT_ARRAY);
11823         }
11824         else {
11825             gv = cGVOPx_gv(obase);
11826             if (!gv)
11827                 break;
11828             if (match) {
11829                 SV **svp;
11830                 av = GvAV(gv);
11831                 if (!av || SvRMAGICAL(av))
11832                     break;
11833                 svp = av_fetch(av, (I32)obase->op_private, FALSE);
11834                 if (!svp || *svp != uninit_sv)
11835                     break;
11836             }
11837             return varname(gv, '$', 0,
11838                     NULL, (I32)obase->op_private, FUV_SUBSCRIPT_ARRAY);
11839         }
11840         break;
11841
11842     case OP_EXISTS:
11843         o = cUNOPx(obase)->op_first;
11844         if (!o || o->op_type != OP_NULL ||
11845                 ! (o->op_targ == OP_AELEM || o->op_targ == OP_HELEM))
11846             break;
11847         return find_uninit_var(cBINOPo->op_last, uninit_sv, match);
11848
11849     case OP_AELEM:
11850     case OP_HELEM:
11851         if (PL_op == obase)
11852             /* $a[uninit_expr] or $h{uninit_expr} */
11853             return find_uninit_var(cBINOPx(obase)->op_last, uninit_sv, match);
11854
11855         gv = NULL;
11856         o = cBINOPx(obase)->op_first;
11857         kid = cBINOPx(obase)->op_last;
11858
11859         /* get the av or hv, and optionally the gv */
11860         sv = NULL;
11861         if  (o->op_type == OP_PADAV || o->op_type == OP_PADHV) {
11862             sv = PAD_SV(o->op_targ);
11863         }
11864         else if ((o->op_type == OP_RV2AV || o->op_type == OP_RV2HV)
11865                 && cUNOPo->op_first->op_type == OP_GV)
11866         {
11867             gv = cGVOPx_gv(cUNOPo->op_first);
11868             if (!gv)
11869                 break;
11870             sv = o->op_type == OP_RV2HV ? (SV*)GvHV(gv) : (SV*)GvAV(gv);
11871         }
11872         if (!sv)
11873             break;
11874
11875         if (kid && kid->op_type == OP_CONST && SvOK(cSVOPx_sv(kid))) {
11876             /* index is constant */
11877             if (match) {
11878                 if (SvMAGICAL(sv))
11879                     break;
11880                 if (obase->op_type == OP_HELEM) {
11881                     HE* he = hv_fetch_ent((HV*)sv, cSVOPx_sv(kid), 0, 0);
11882                     if (!he || HeVAL(he) != uninit_sv)
11883                         break;
11884                 }
11885                 else {
11886                     SV * const * const svp = av_fetch((AV*)sv, SvIV(cSVOPx_sv(kid)), FALSE);
11887                     if (!svp || *svp != uninit_sv)
11888                         break;
11889                 }
11890             }
11891             if (obase->op_type == OP_HELEM)
11892                 return varname(gv, '%', o->op_targ,
11893                             cSVOPx_sv(kid), 0, FUV_SUBSCRIPT_HASH);
11894             else
11895                 return varname(gv, '@', o->op_targ, NULL,
11896                             SvIV(cSVOPx_sv(kid)), FUV_SUBSCRIPT_ARRAY);
11897         }
11898         else  {
11899             /* index is an expression;
11900              * attempt to find a match within the aggregate */
11901             if (obase->op_type == OP_HELEM) {
11902                 SV * const keysv = find_hash_subscript((HV*)sv, uninit_sv);
11903                 if (keysv)
11904                     return varname(gv, '%', o->op_targ,
11905                                                 keysv, 0, FUV_SUBSCRIPT_HASH);
11906             }
11907             else {
11908                 const I32 index = find_array_subscript((AV*)sv, uninit_sv);
11909                 if (index >= 0)
11910                     return varname(gv, '@', o->op_targ,
11911                                         NULL, index, FUV_SUBSCRIPT_ARRAY);
11912             }
11913             if (match)
11914                 break;
11915             return varname(gv,
11916                 (o->op_type == OP_PADAV || o->op_type == OP_RV2AV)
11917                 ? '@' : '%',
11918                 o->op_targ, NULL, 0, FUV_SUBSCRIPT_WITHIN);
11919         }
11920         break;
11921
11922     case OP_AASSIGN:
11923         /* only examine RHS */
11924         return find_uninit_var(cBINOPx(obase)->op_first, uninit_sv, match);
11925
11926     case OP_OPEN:
11927         o = cUNOPx(obase)->op_first;
11928         if (o->op_type == OP_PUSHMARK)
11929             o = o->op_sibling;
11930
11931         if (!o->op_sibling) {
11932             /* one-arg version of open is highly magical */
11933
11934             if (o->op_type == OP_GV) { /* open FOO; */
11935                 gv = cGVOPx_gv(o);
11936                 if (match && GvSV(gv) != uninit_sv)
11937                     break;
11938                 return varname(gv, '$', 0,
11939                             NULL, 0, FUV_SUBSCRIPT_NONE);
11940             }
11941             /* other possibilities not handled are:
11942              * open $x; or open my $x;  should return '${*$x}'
11943              * open expr;               should return '$'.expr ideally
11944              */
11945              break;
11946         }
11947         goto do_op;
11948
11949     /* ops where $_ may be an implicit arg */
11950     case OP_TRANS:
11951     case OP_SUBST:
11952     case OP_MATCH:
11953         if ( !(obase->op_flags & OPf_STACKED)) {
11954             if (uninit_sv == ((obase->op_private & OPpTARGET_MY)
11955                                  ? PAD_SVl(obase->op_targ)
11956                                  : DEFSV))
11957             {
11958                 sv = sv_newmortal();
11959                 sv_setpvn(sv, "$_", 2);
11960                 return sv;
11961             }
11962         }
11963         goto do_op;
11964
11965     case OP_PRTF:
11966     case OP_PRINT:
11967         /* skip filehandle as it can't produce 'undef' warning  */
11968         o = cUNOPx(obase)->op_first;
11969         if ((obase->op_flags & OPf_STACKED) && o->op_type == OP_PUSHMARK)
11970             o = o->op_sibling->op_sibling;
11971         goto do_op2;
11972
11973
11974     case OP_RV2SV:
11975     case OP_CUSTOM:
11976     case OP_ENTERSUB:
11977         match = 1; /* XS or custom code could trigger random warnings */
11978         goto do_op;
11979
11980     case OP_SCHOMP:
11981     case OP_CHOMP:
11982         if (SvROK(PL_rs) && uninit_sv == SvRV(PL_rs))
11983             return sv_2mortal(newSVpvs("${$/}"));
11984         /*FALLTHROUGH*/
11985
11986     default:
11987     do_op:
11988         if (!(obase->op_flags & OPf_KIDS))
11989             break;
11990         o = cUNOPx(obase)->op_first;
11991         
11992     do_op2:
11993         if (!o)
11994             break;
11995
11996         /* if all except one arg are constant, or have no side-effects,
11997          * or are optimized away, then it's unambiguous */
11998         o2 = NULL;
11999         for (kid=o; kid; kid = kid->op_sibling) {
12000             if (kid) {
12001                 const OPCODE type = kid->op_type;
12002                 if ( (type == OP_CONST && SvOK(cSVOPx_sv(kid)))
12003                   || (type == OP_NULL  && ! (kid->op_flags & OPf_KIDS))
12004                   || (type == OP_PUSHMARK)
12005                 )
12006                 continue;
12007             }
12008             if (o2) { /* more than one found */
12009                 o2 = NULL;
12010                 break;
12011             }
12012             o2 = kid;
12013         }
12014         if (o2)
12015             return find_uninit_var(o2, uninit_sv, match);
12016
12017         /* scan all args */
12018         while (o) {
12019             sv = find_uninit_var(o, uninit_sv, 1);
12020             if (sv)
12021                 return sv;
12022             o = o->op_sibling;
12023         }
12024         break;
12025     }
12026     return NULL;
12027 }
12028
12029
12030 /*
12031 =for apidoc report_uninit
12032
12033 Print appropriate "Use of uninitialized variable" warning
12034
12035 =cut
12036 */
12037
12038 void
12039 Perl_report_uninit(pTHX_ SV* uninit_sv)
12040 {
12041     dVAR;
12042     if (PL_op) {
12043         SV* varname = NULL;
12044         if (uninit_sv) {
12045             varname = find_uninit_var(PL_op, uninit_sv,0);
12046             if (varname)
12047                 sv_insert(varname, 0, 0, " ", 1);
12048         }
12049         Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
12050                 varname ? SvPV_nolen_const(varname) : "",
12051                 " in ", OP_DESC(PL_op));
12052     }
12053     else
12054         Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
12055                     "", "", "");
12056 }
12057
12058 /*
12059  * Local variables:
12060  * c-indentation-style: bsd
12061  * c-basic-offset: 4
12062  * indent-tabs-mode: t
12063  * End:
12064  *
12065  * ex: set ts=8 sts=4 sw=4 noet:
12066  */