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