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