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