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