3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
9 * "I wonder what the Entish is for 'yes' and 'no'," he thought.
12 * This file contains the code that creates, manipulates and destroys
13 * scalar values (SVs). The other types (AV, HV, GV, etc.) reuse the
14 * structure of an SV, so their creation and destruction is handled
15 * here; higher-level functions are in av.c, hv.c, and so on. Opcode
16 * level functions (eg. substr, split, join) for each of the types are
28 /* Missing proto on LynxOS */
29 char *gconvert(double, int, int, char *);
32 #ifdef PERL_UTF8_CACHE_ASSERT
33 /* The cache element 0 is the Unicode offset;
34 * the cache element 1 is the byte offset of the element 0;
35 * the cache element 2 is the Unicode length of the substring;
36 * the cache element 3 is the byte length of the substring;
37 * The checking of the substring side would be good
38 * but substr() has enough code paths to make my head spin;
39 * if adding more checks watch out for the following tests:
40 * t/op/index.t t/op/length.t t/op/pat.t t/op/substr.t
41 * lib/utf8.t lib/Unicode/Collate/t/index.t
44 #define ASSERT_UTF8_CACHE(cache) \
45 STMT_START { if (cache) { assert((cache)[0] <= (cache)[1]); } } STMT_END
47 #define ASSERT_UTF8_CACHE(cache) NOOP
50 #ifdef PERL_OLD_COPY_ON_WRITE
51 #define SV_COW_NEXT_SV(sv) INT2PTR(SV *,SvUVX(sv))
52 #define SV_COW_NEXT_SV_SET(current,next) SvUV_set(current, PTR2UV(next))
53 /* This is a pessimistic view. Scalar must be purely a read-write PV to copy-
57 /* ============================================================================
59 =head1 Allocation and deallocation of SVs.
61 An SV (or AV, HV, etc.) is allocated in two parts: the head (struct sv,
62 av, hv...) contains type and reference count information, as well as a
63 pointer to the body (struct xrv, xpv, xpviv...), which contains fields
64 specific to each type.
66 Normally, this allocation is done using arenas, which by default are
67 approximately 4K chunks of memory parcelled up into N heads or bodies. The
68 first slot in each arena is reserved, and is used to hold a link to the next
69 arena. In the case of heads, the unused first slot also contains some flags
70 and a note of the number of slots. Snaked through each arena chain is a
71 linked list of free items; when this becomes empty, an extra arena is
72 allocated and divided up into N items which are threaded into the free list.
74 The following global variables are associated with arenas:
76 PL_sv_arenaroot pointer to list of SV arenas
77 PL_sv_root pointer to list of free SV structures
79 PL_foo_arenaroot pointer to list of foo arenas,
80 PL_foo_root pointer to list of free foo bodies
81 ... for foo in xiv, xnv, xrv, xpv etc.
83 Note that some of the larger and more rarely used body types (eg xpvio)
84 are not allocated using arenas, but are instead just malloc()/free()ed as
85 required. Also, if PURIFY is defined, arenas are abandoned altogether,
86 with all items individually malloc()ed. In addition, a few SV heads are
87 not allocated from an arena, but are instead directly created as static
88 or auto variables, eg PL_sv_undef. The size of arenas can be changed from
89 the default by setting PERL_ARENA_SIZE appropriately at compile time.
91 The SV arena serves the secondary purpose of allowing still-live SVs
92 to be located and destroyed during final cleanup.
94 At the lowest level, the macros new_SV() and del_SV() grab and free
95 an SV head. (If debugging with -DD, del_SV() calls the function S_del_sv()
96 to return the SV to the free list with error checking.) new_SV() calls
97 more_sv() / sv_add_arena() to add an extra arena if the free list is empty.
98 SVs in the free list have their SvTYPE field set to all ones.
100 Similarly, there are macros new_XIV()/del_XIV(), new_XNV()/del_XNV() etc
101 that allocate and return individual body types. Normally these are mapped
102 to the arena-manipulating functions new_xiv()/del_xiv() etc, but may be
103 instead mapped directly to malloc()/free() if PURIFY is defined. The
104 new/del functions remove from, or add to, the appropriate PL_foo_root
105 list, and call more_xiv() etc to add a new arena if the list is empty.
107 At the time of very final cleanup, sv_free_arenas() is called from
108 perl_destruct() to physically free all the arenas allocated since the
109 start of the interpreter. Note that this also clears PL_he_arenaroot,
110 which is otherwise dealt with in hv.c.
112 Manipulation of any of the PL_*root pointers is protected by enclosing
113 LOCK_SV_MUTEX; ... UNLOCK_SV_MUTEX calls which should Do the Right Thing
114 if threads are enabled.
116 The function visit() scans the SV arenas list, and calls a specified
117 function for each SV it finds which is still live - ie which has an SvTYPE
118 other than all 1's, and a non-zero SvREFCNT. visit() is used by the
119 following functions (specified as [function that calls visit()] / [function
120 called by visit() for each SV]):
122 sv_report_used() / do_report_used()
123 dump all remaining SVs (debugging aid)
125 sv_clean_objs() / do_clean_objs(),do_clean_named_objs()
126 Attempt to free all objects pointed to by RVs,
127 and, unless DISABLE_DESTRUCTOR_KLUDGE is defined,
128 try to do the same for all objects indirectly
129 referenced by typeglobs too. Called once from
130 perl_destruct(), prior to calling sv_clean_all()
133 sv_clean_all() / do_clean_all()
134 SvREFCNT_dec(sv) each remaining SV, possibly
135 triggering an sv_free(). It also sets the
136 SVf_BREAK flag on the SV to indicate that the
137 refcnt has been artificially lowered, and thus
138 stopping sv_free() from giving spurious warnings
139 about SVs which unexpectedly have a refcnt
140 of zero. called repeatedly from perl_destruct()
141 until there are no SVs left.
145 Private API to rest of sv.c
149 new_XIV(), del_XIV(),
150 new_XNV(), del_XNV(),
155 sv_report_used(), sv_clean_objs(), sv_clean_all(), sv_free_arenas()
160 ============================================================================ */
165 * "A time to plant, and a time to uproot what was planted..."
169 #ifdef DEBUG_LEAKING_SCALARS
171 # define FREE_SV_DEBUG_FILE(sv) PerlMemfree((sv)->sv_debug_file)
173 # define FREE_SV_DEBUG_FILE(sv) PerlMemShared_free((sv)->sv_debug_file)
176 # define FREE_SV_DEBUG_FILE(sv)
179 #define plant_SV(p) \
181 FREE_SV_DEBUG_FILE(p); \
182 SvANY(p) = (void *)PL_sv_root; \
183 SvFLAGS(p) = SVTYPEMASK; \
188 /* sv_mutex must be held while calling uproot_SV() */
189 #define uproot_SV(p) \
192 PL_sv_root = (SV*)SvANY(p); \
197 /* make some more SVs by adding another arena */
199 /* sv_mutex must be held while calling more_sv() */
206 sv_add_arena(PL_nice_chunk, PL_nice_chunk_size, 0);
207 PL_nice_chunk = Nullch;
208 PL_nice_chunk_size = 0;
211 char *chunk; /* must use New here to match call to */
212 New(704,chunk,PERL_ARENA_SIZE,char); /* Safefree() in sv_free_arenas() */
213 sv_add_arena(chunk, PERL_ARENA_SIZE, 0);
219 /* new_SV(): return a new, empty SV head */
221 #ifdef DEBUG_LEAKING_SCALARS
222 /* provide a real function for a debugger to play with */
232 sv = S_more_sv(aTHX);
237 sv->sv_debug_optype = PL_op ? PL_op->op_type : 0;
238 sv->sv_debug_line = (U16) ((PL_copline == NOLINE) ?
239 (PL_curcop ? CopLINE(PL_curcop) : 0) : PL_copline);
240 sv->sv_debug_inpad = 0;
241 sv->sv_debug_cloned = 0;
243 sv->sv_debug_file = PL_curcop ? savepv(CopFILE(PL_curcop)): NULL;
245 sv->sv_debug_file = PL_curcop ? savesharedpv(CopFILE(PL_curcop)): NULL;
250 # define new_SV(p) (p)=S_new_SV(aTHX)
259 (p) = S_more_sv(aTHX); \
268 /* del_SV(): return an empty SV head to the free list */
283 S_del_sv(pTHX_ SV *p)
288 for (sva = PL_sv_arenaroot; sva; sva = (SV *) SvANY(sva)) {
290 SV *svend = &sva[SvREFCNT(sva)];
291 if (p >= sv && p < svend) {
297 if (ckWARN_d(WARN_INTERNAL))
298 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
299 "Attempt to free non-arena SV: 0x%"UVxf
300 pTHX__FORMAT, PTR2UV(p) pTHX__VALUE);
307 #else /* ! DEBUGGING */
309 #define del_SV(p) plant_SV(p)
311 #endif /* DEBUGGING */
315 =head1 SV Manipulation Functions
317 =for apidoc sv_add_arena
319 Given a chunk of memory, link it to the head of the list of arenas,
320 and split it into a list of free SVs.
326 Perl_sv_add_arena(pTHX_ char *ptr, U32 size, U32 flags)
332 /* The first SV in an arena isn't an SV. */
333 SvANY(sva) = (void *) PL_sv_arenaroot; /* ptr to next arena */
334 SvREFCNT(sva) = size / sizeof(SV); /* number of SV slots */
335 SvFLAGS(sva) = flags; /* FAKE if not to be freed */
337 PL_sv_arenaroot = sva;
338 PL_sv_root = sva + 1;
340 svend = &sva[SvREFCNT(sva) - 1];
343 SvANY(sv) = (void *)(SV*)(sv + 1);
347 /* Must always set typemask because it's awlays checked in on cleanup
348 when the arenas are walked looking for objects. */
349 SvFLAGS(sv) = SVTYPEMASK;
356 SvFLAGS(sv) = SVTYPEMASK;
359 /* visit(): call the named function for each non-free SV in the arenas
360 * whose flags field matches the flags/mask args. */
363 S_visit(pTHX_ SVFUNC_t f, U32 flags, U32 mask)
368 for (sva = PL_sv_arenaroot; sva; sva = (SV*)SvANY(sva)) {
369 register SV * const svend = &sva[SvREFCNT(sva)];
371 for (sv = sva + 1; sv < svend; ++sv) {
372 if (SvTYPE(sv) != SVTYPEMASK
373 && (sv->sv_flags & mask) == flags
386 /* called by sv_report_used() for each live SV */
389 do_report_used(pTHX_ SV *sv)
391 if (SvTYPE(sv) != SVTYPEMASK) {
392 PerlIO_printf(Perl_debug_log, "****\n");
399 =for apidoc sv_report_used
401 Dump the contents of all SVs not yet freed. (Debugging aid).
407 Perl_sv_report_used(pTHX)
410 visit(do_report_used, 0, 0);
414 /* called by sv_clean_objs() for each live SV */
417 do_clean_objs(pTHX_ SV *sv)
421 if (SvROK(sv) && SvOBJECT(rv = SvRV(sv))) {
422 DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning object ref:\n "), sv_dump(sv)));
434 /* XXX Might want to check arrays, etc. */
437 /* called by sv_clean_objs() for each live SV */
439 #ifndef DISABLE_DESTRUCTOR_KLUDGE
441 do_clean_named_objs(pTHX_ SV *sv)
443 if (SvTYPE(sv) == SVt_PVGV && GvGP(sv)) {
444 if ( SvOBJECT(GvSV(sv)) ||
445 (GvAV(sv) && SvOBJECT(GvAV(sv))) ||
446 (GvHV(sv) && SvOBJECT(GvHV(sv))) ||
447 (GvIO(sv) && SvOBJECT(GvIO(sv))) ||
448 (GvCV(sv) && SvOBJECT(GvCV(sv))) )
450 DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning named glob object:\n "), sv_dump(sv)));
451 SvFLAGS(sv) |= SVf_BREAK;
459 =for apidoc sv_clean_objs
461 Attempt to destroy all objects not yet freed
467 Perl_sv_clean_objs(pTHX)
469 PL_in_clean_objs = TRUE;
470 visit(do_clean_objs, SVf_ROK, SVf_ROK);
471 #ifndef DISABLE_DESTRUCTOR_KLUDGE
472 /* some barnacles may yet remain, clinging to typeglobs */
473 visit(do_clean_named_objs, SVt_PVGV, SVTYPEMASK);
475 PL_in_clean_objs = FALSE;
478 /* called by sv_clean_all() for each live SV */
481 do_clean_all(pTHX_ SV *sv)
483 DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning loops: SV at 0x%"UVxf"\n", PTR2UV(sv)) ));
484 SvFLAGS(sv) |= SVf_BREAK;
485 if (PL_comppad == (AV*)sv) {
487 PL_curpad = Null(SV**);
493 =for apidoc sv_clean_all
495 Decrement the refcnt of each remaining SV, possibly triggering a
496 cleanup. This function may have to be called multiple times to free
497 SVs which are in complex self-referential hierarchies.
503 Perl_sv_clean_all(pTHX)
506 PL_in_clean_all = TRUE;
507 cleaned = visit(do_clean_all, 0,0);
508 PL_in_clean_all = FALSE;
513 =for apidoc sv_free_arenas
515 Deallocate the memory used by all arenas. Note that all the individual SV
516 heads and bodies within the arenas must already have been freed.
522 Perl_sv_free_arenas(pTHX)
526 void *arena, *arenanext;
528 /* Free arenas here, but be careful about fake ones. (We assume
529 contiguity of the fake ones with the corresponding real ones.) */
531 for (sva = PL_sv_arenaroot; sva; sva = svanext) {
532 svanext = (SV*) SvANY(sva);
533 while (svanext && SvFAKE(svanext))
534 svanext = (SV*) SvANY(svanext);
540 for (arena = PL_xnv_arenaroot; arena; arena = arenanext) {
541 arenanext = *(void **)arena;
544 PL_xnv_arenaroot = 0;
547 for (arena = PL_xpv_arenaroot; arena; arena = arenanext) {
548 arenanext = *(void **)arena;
551 PL_xpv_arenaroot = 0;
554 for (arena = PL_xpviv_arenaroot; arena; arena = arenanext) {
555 arenanext = *(void **)arena;
558 PL_xpviv_arenaroot = 0;
561 for (arena = PL_xpvnv_arenaroot; arena; arena = arenanext) {
562 arenanext = *(void **)arena;
565 PL_xpvnv_arenaroot = 0;
568 for (arena = PL_xpvcv_arenaroot; arena; arena = arenanext) {
569 arenanext = *(void **)arena;
572 PL_xpvcv_arenaroot = 0;
575 for (arena = PL_xpvav_arenaroot; arena; arena = arenanext) {
576 arenanext = *(void **)arena;
579 PL_xpvav_arenaroot = 0;
582 for (arena = PL_xpvhv_arenaroot; arena; arena = arenanext) {
583 arenanext = *(void **)arena;
586 PL_xpvhv_arenaroot = 0;
589 for (arena = PL_xpvmg_arenaroot; arena; arena = arenanext) {
590 arenanext = *(void **)arena;
593 PL_xpvmg_arenaroot = 0;
596 for (arena = PL_xpvgv_arenaroot; arena; arena = arenanext) {
597 arenanext = *(void **)arena;
600 PL_xpvgv_arenaroot = 0;
603 for (arena = PL_xpvlv_arenaroot; arena; arena = arenanext) {
604 arenanext = *(void **)arena;
607 PL_xpvlv_arenaroot = 0;
610 for (arena = PL_xpvbm_arenaroot; arena; arena = arenanext) {
611 arenanext = *(void **)arena;
614 PL_xpvbm_arenaroot = 0;
620 for (he = PL_he_arenaroot; he; he = he_next) {
621 he_next = HeNEXT(he);
628 #if defined(USE_ITHREADS)
630 struct ptr_tbl_ent *pte;
631 struct ptr_tbl_ent *pte_next;
632 for (pte = PL_pte_arenaroot; pte; pte = pte_next) {
633 pte_next = pte->next;
637 PL_pte_arenaroot = 0;
642 Safefree(PL_nice_chunk);
643 PL_nice_chunk = Nullch;
644 PL_nice_chunk_size = 0;
649 /* ---------------------------------------------------------------------
651 * support functions for report_uninit()
654 /* the maxiumum size of array or hash where we will scan looking
655 * for the undefined element that triggered the warning */
657 #define FUV_MAX_SEARCH_SIZE 1000
659 /* Look for an entry in the hash whose value has the same SV as val;
660 * If so, return a mortal copy of the key. */
663 S_find_hash_subscript(pTHX_ HV *hv, SV* val)
669 if (!hv || SvMAGICAL(hv) || !HvARRAY(hv) ||
670 (HvTOTALKEYS(hv) > FUV_MAX_SEARCH_SIZE))
675 for (i=HvMAX(hv); i>0; i--) {
677 for (entry = array[i]; entry; entry = HeNEXT(entry)) {
678 if (HeVAL(entry) != val)
680 if ( HeVAL(entry) == &PL_sv_undef ||
681 HeVAL(entry) == &PL_sv_placeholder)
685 if (HeKLEN(entry) == HEf_SVKEY)
686 return sv_mortalcopy(HeKEY_sv(entry));
687 return sv_2mortal(newSVpvn(HeKEY(entry), HeKLEN(entry)));
693 /* Look for an entry in the array whose value has the same SV as val;
694 * If so, return the index, otherwise return -1. */
697 S_find_array_subscript(pTHX_ AV *av, SV* val)
701 if (!av || SvMAGICAL(av) || !AvARRAY(av) ||
702 (AvFILLp(av) > FUV_MAX_SEARCH_SIZE))
706 for (i=AvFILLp(av); i>=0; i--) {
707 if (svp[i] == val && svp[i] != &PL_sv_undef)
713 /* S_varname(): return the name of a variable, optionally with a subscript.
714 * If gv is non-zero, use the name of that global, along with gvtype (one
715 * of "$", "@", "%"); otherwise use the name of the lexical at pad offset
716 * targ. Depending on the value of the subscript_type flag, return:
719 #define FUV_SUBSCRIPT_NONE 1 /* "@foo" */
720 #define FUV_SUBSCRIPT_ARRAY 2 /* "$foo[aindex]" */
721 #define FUV_SUBSCRIPT_HASH 3 /* "$foo{keyname}" */
722 #define FUV_SUBSCRIPT_WITHIN 4 /* "within @foo" */
725 S_varname(pTHX_ GV *gv, const char *gvtype, PADOFFSET targ,
726 SV* keyname, I32 aindex, int subscript_type)
731 SV * const name = sv_newmortal();
734 /* simulate gv_fullname4(), but add literal '^' for $^FOO names
735 * XXX get rid of all this if gv_fullnameX() ever supports this
739 HV *hv = GvSTASH(gv);
740 sv_setpv(name, gvtype);
743 else if (!(p=HvNAME_get(hv)))
745 if (strNE(p, "main")) {
747 sv_catpvn(name,"::", 2);
749 if (GvNAMELEN(gv)>= 1 &&
750 ((unsigned int)*GvNAME(gv)) <= 26)
752 Perl_sv_catpvf(aTHX_ name,"^%c", *GvNAME(gv) + 'A' - 1);
753 sv_catpvn(name,GvNAME(gv)+1,GvNAMELEN(gv)-1);
756 sv_catpvn(name,GvNAME(gv),GvNAMELEN(gv));
760 CV *cv = find_runcv(&u);
761 if (!cv || !CvPADLIST(cv))
763 av = (AV*)(*av_fetch(CvPADLIST(cv), 0, FALSE));
764 sv = *av_fetch(av, targ, FALSE);
765 /* SvLEN in a pad name is not to be trusted */
766 sv_setpv(name, SvPV_nolen_const(sv));
769 if (subscript_type == FUV_SUBSCRIPT_HASH) {
772 Perl_sv_catpvf(aTHX_ name, "{%s}",
773 pv_display(sv,SvPVX_const(keyname), SvCUR(keyname), 0, 32));
776 else if (subscript_type == FUV_SUBSCRIPT_ARRAY) {
778 Perl_sv_catpvf(aTHX_ name, "[%"IVdf"]", (IV)aindex);
780 else if (subscript_type == FUV_SUBSCRIPT_WITHIN)
781 sv_insert(name, 0, 0, "within ", 7);
788 =for apidoc find_uninit_var
790 Find the name of the undefined variable (if any) that caused the operator o
791 to issue a "Use of uninitialized value" warning.
792 If match is true, only return a name if it's value matches uninit_sv.
793 So roughly speaking, if a unary operator (such as OP_COS) generates a
794 warning, then following the direct child of the op may yield an
795 OP_PADSV or OP_GV that gives the name of the undefined variable. On the
796 other hand, with OP_ADD there are two branches to follow, so we only print
797 the variable name if we get an exact match.
799 The name is returned as a mortal SV.
801 Assumes that PL_op is the op that originally triggered the error, and that
802 PL_comppad/PL_curpad points to the currently executing pad.
808 S_find_uninit_var(pTHX_ OP* obase, SV* uninit_sv, bool match)
817 if (!obase || (match && (!uninit_sv || uninit_sv == &PL_sv_undef ||
818 uninit_sv == &PL_sv_placeholder)))
821 switch (obase->op_type) {
828 const bool pad = (obase->op_type == OP_PADAV || obase->op_type == OP_PADHV);
829 const bool hash = (obase->op_type == OP_PADHV || obase->op_type == OP_RV2HV);
832 int subscript_type = FUV_SUBSCRIPT_WITHIN;
834 if (pad) { /* @lex, %lex */
835 sv = PAD_SVl(obase->op_targ);
839 if (cUNOPx(obase)->op_first->op_type == OP_GV) {
840 /* @global, %global */
841 gv = cGVOPx_gv(cUNOPx(obase)->op_first);
844 sv = hash ? (SV*)GvHV(gv): (SV*)GvAV(gv);
846 else /* @{expr}, %{expr} */
847 return find_uninit_var(cUNOPx(obase)->op_first,
851 /* attempt to find a match within the aggregate */
853 keysv = S_find_hash_subscript(aTHX_ (HV*)sv, uninit_sv);
855 subscript_type = FUV_SUBSCRIPT_HASH;
858 index = S_find_array_subscript(aTHX_ (AV*)sv, uninit_sv);
860 subscript_type = FUV_SUBSCRIPT_ARRAY;
863 if (match && subscript_type == FUV_SUBSCRIPT_WITHIN)
866 return S_varname(aTHX_ gv, hash ? "%" : "@", obase->op_targ,
867 keysv, index, subscript_type);
871 if (match && PAD_SVl(obase->op_targ) != uninit_sv)
873 return S_varname(aTHX_ Nullgv, "$", obase->op_targ,
874 Nullsv, 0, FUV_SUBSCRIPT_NONE);
877 gv = cGVOPx_gv(obase);
878 if (!gv || (match && GvSV(gv) != uninit_sv))
880 return S_varname(aTHX_ gv, "$", 0, Nullsv, 0, FUV_SUBSCRIPT_NONE);
883 if (obase->op_flags & OPf_SPECIAL) { /* lexical array */
885 av = (AV*)PAD_SV(obase->op_targ);
886 if (!av || SvRMAGICAL(av))
888 svp = av_fetch(av, (I32)obase->op_private, FALSE);
889 if (!svp || *svp != uninit_sv)
892 return S_varname(aTHX_ Nullgv, "$", obase->op_targ,
893 Nullsv, (I32)obase->op_private, FUV_SUBSCRIPT_ARRAY);
896 gv = cGVOPx_gv(obase);
901 if (!av || SvRMAGICAL(av))
903 svp = av_fetch(av, (I32)obase->op_private, FALSE);
904 if (!svp || *svp != uninit_sv)
907 return S_varname(aTHX_ gv, "$", 0,
908 Nullsv, (I32)obase->op_private, FUV_SUBSCRIPT_ARRAY);
913 o = cUNOPx(obase)->op_first;
914 if (!o || o->op_type != OP_NULL ||
915 ! (o->op_targ == OP_AELEM || o->op_targ == OP_HELEM))
917 return find_uninit_var(cBINOPo->op_last, uninit_sv, match);
922 /* $a[uninit_expr] or $h{uninit_expr} */
923 return find_uninit_var(cBINOPx(obase)->op_last, uninit_sv, match);
926 o = cBINOPx(obase)->op_first;
927 kid = cBINOPx(obase)->op_last;
929 /* get the av or hv, and optionally the gv */
931 if (o->op_type == OP_PADAV || o->op_type == OP_PADHV) {
932 sv = PAD_SV(o->op_targ);
934 else if ((o->op_type == OP_RV2AV || o->op_type == OP_RV2HV)
935 && cUNOPo->op_first->op_type == OP_GV)
937 gv = cGVOPx_gv(cUNOPo->op_first);
940 sv = o->op_type == OP_RV2HV ? (SV*)GvHV(gv) : (SV*)GvAV(gv);
945 if (kid && kid->op_type == OP_CONST && SvOK(cSVOPx_sv(kid))) {
946 /* index is constant */
950 if (obase->op_type == OP_HELEM) {
951 HE* he = hv_fetch_ent((HV*)sv, cSVOPx_sv(kid), 0, 0);
952 if (!he || HeVAL(he) != uninit_sv)
956 svp = av_fetch((AV*)sv, SvIV(cSVOPx_sv(kid)), FALSE);
957 if (!svp || *svp != uninit_sv)
961 if (obase->op_type == OP_HELEM)
962 return S_varname(aTHX_ gv, "%", o->op_targ,
963 cSVOPx_sv(kid), 0, FUV_SUBSCRIPT_HASH);
965 return S_varname(aTHX_ gv, "@", o->op_targ, Nullsv,
966 SvIV(cSVOPx_sv(kid)), FUV_SUBSCRIPT_ARRAY);
970 /* index is an expression;
971 * attempt to find a match within the aggregate */
972 if (obase->op_type == OP_HELEM) {
973 SV *keysv = S_find_hash_subscript(aTHX_ (HV*)sv, uninit_sv);
975 return S_varname(aTHX_ gv, "%", o->op_targ,
976 keysv, 0, FUV_SUBSCRIPT_HASH);
979 const I32 index = S_find_array_subscript(aTHX_ (AV*)sv, uninit_sv);
981 return S_varname(aTHX_ gv, "@", o->op_targ,
982 Nullsv, index, FUV_SUBSCRIPT_ARRAY);
986 return S_varname(aTHX_ gv,
987 (o->op_type == OP_PADAV || o->op_type == OP_RV2AV)
989 o->op_targ, Nullsv, 0, FUV_SUBSCRIPT_WITHIN);
995 /* only examine RHS */
996 return find_uninit_var(cBINOPx(obase)->op_first, uninit_sv, match);
999 o = cUNOPx(obase)->op_first;
1000 if (o->op_type == OP_PUSHMARK)
1003 if (!o->op_sibling) {
1004 /* one-arg version of open is highly magical */
1006 if (o->op_type == OP_GV) { /* open FOO; */
1008 if (match && GvSV(gv) != uninit_sv)
1010 return S_varname(aTHX_ gv, "$", 0,
1011 Nullsv, 0, FUV_SUBSCRIPT_NONE);
1013 /* other possibilities not handled are:
1014 * open $x; or open my $x; should return '${*$x}'
1015 * open expr; should return '$'.expr ideally
1021 /* ops where $_ may be an implicit arg */
1025 if ( !(obase->op_flags & OPf_STACKED)) {
1026 if (uninit_sv == ((obase->op_private & OPpTARGET_MY)
1027 ? PAD_SVl(obase->op_targ)
1030 sv = sv_newmortal();
1031 sv_setpvn(sv, "$_", 2);
1039 /* skip filehandle as it can't produce 'undef' warning */
1040 o = cUNOPx(obase)->op_first;
1041 if ((obase->op_flags & OPf_STACKED) && o->op_type == OP_PUSHMARK)
1042 o = o->op_sibling->op_sibling;
1049 match = 1; /* XS or custom code could trigger random warnings */
1054 if (SvROK(PL_rs) && uninit_sv == SvRV(PL_rs))
1055 return sv_2mortal(newSVpv("${$/}", 0));
1060 if (!(obase->op_flags & OPf_KIDS))
1062 o = cUNOPx(obase)->op_first;
1068 /* if all except one arg are constant, or have no side-effects,
1069 * or are optimized away, then it's unambiguous */
1071 for (kid=o; kid; kid = kid->op_sibling) {
1073 ( (kid->op_type == OP_CONST && SvOK(cSVOPx_sv(kid)))
1074 || (kid->op_type == OP_NULL && ! (kid->op_flags & OPf_KIDS))
1075 || (kid->op_type == OP_PUSHMARK)
1079 if (o2) { /* more than one found */
1086 return find_uninit_var(o2, uninit_sv, match);
1090 sv = find_uninit_var(o, uninit_sv, 1);
1102 =for apidoc report_uninit
1104 Print appropriate "Use of uninitialized variable" warning
1110 Perl_report_uninit(pTHX_ SV* uninit_sv)
1113 SV* varname = Nullsv;
1115 varname = find_uninit_var(PL_op, uninit_sv,0);
1117 sv_insert(varname, 0, 0, " ", 1);
1119 Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
1120 varname ? SvPV_nolen_const(varname) : "",
1121 " in ", OP_DESC(PL_op));
1124 Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
1129 S_more_bodies (pTHX_ void **arena_root, void **root, size_t size)
1133 size_t count = PERL_ARENA_SIZE/size;
1134 New(0, start, count*size, char);
1135 *((void **) start) = *arena_root;
1136 *arena_root = (void *)start;
1138 end = start + (count-1) * size;
1140 /* The initial slot is used to link the arenas together, so it isn't to be
1141 linked into the list of ready-to-use bodies. */
1145 *root = (void *)start;
1147 while (start < end) {
1148 char *next = start + size;
1149 *(void**) start = (void *)next;
1152 *(void **)start = 0;
1157 /* grab a new thing from the free list, allocating more if necessary */
1160 S_new_body(pTHX_ void **arena_root, void **root, size_t size, size_t offset)
1164 xpv = *root ? *root : S_more_bodies(aTHX_ arena_root, root, size);
1165 *root = *(void**)xpv;
1167 return (void*)((char*)xpv - offset);
1170 /* return a thing to the free list */
1173 S_del_body(pTHX_ void *thing, void **root, size_t offset)
1175 void **real_thing = (void**)((char *)thing + offset);
1177 *real_thing = *root;
1178 *root = (void*)real_thing;
1182 /* Conventionally we simply malloc() a big block of memory, then divide it
1183 up into lots of the thing that we're allocating.
1185 This macro will expand to call to S_new_body. So for XPVBM (with ithreads),
1188 S_new_body(my_perl, (void**)&(my_perl->Ixpvbm_arenaroot),
1189 (void**)&(my_perl->Ixpvbm_root), sizeof(XPVBM), 0)
1192 #define new_body(TYPE,lctype) \
1193 S_new_body(aTHX_ (void**)&PL_ ## lctype ## _arenaroot, \
1194 (void**)&PL_ ## lctype ## _root, \
1198 /* But for some types, we cheat. The type starts with some members that are
1199 never accessed. So we allocate the substructure, starting at the first used
1200 member, then adjust the pointer back in memory by the size of the bit not
1201 allocated, so it's as if we allocated the full structure.
1202 (But things will all go boom if you write to the part that is "not there",
1203 because you'll be overwriting the last members of the preceding structure
1206 We calculate the correction using the STRUCT_OFFSET macro. For example, if
1207 xpv_allocated is the same structure as XPV then the two OFFSETs sum to zero,
1208 and the pointer is unchanged. If the allocated structure is smaller (no
1209 initial NV actually allocated) then the net effect is to subtract the size
1210 of the NV from the pointer, to return a new pointer as if an initial NV were
1213 This is the same trick as was used for NV and IV bodies. Ironically it
1214 doesn't need to be used for NV bodies any more, because NV is now at the
1215 start of the structure. IV bodies don't need it either, because they are
1216 no longer allocated. */
1218 #define new_body_allocated(TYPE,lctype,member) \
1219 S_new_body(aTHX_ (void**)&PL_ ## lctype ## _arenaroot, \
1220 (void**)&PL_ ## lctype ## _root, \
1221 sizeof(lctype ## _allocated), \
1222 STRUCT_OFFSET(TYPE, member) \
1223 - STRUCT_OFFSET(lctype ## _allocated, member))
1226 #define del_body(p,TYPE,lctype) \
1227 S_del_body(aTHX_ (void*)p, (void**)&PL_ ## lctype ## _root, 0)
1229 #define del_body_allocated(p,TYPE,lctype,member) \
1230 S_del_body(aTHX_ (void*)p, (void**)&PL_ ## lctype ## _root, \
1231 STRUCT_OFFSET(TYPE, member) \
1232 - STRUCT_OFFSET(lctype ## _allocated, member))
1234 #define my_safemalloc(s) (void*)safemalloc(s)
1235 #define my_safefree(p) safefree((char*)p)
1239 #define new_XNV() my_safemalloc(sizeof(XPVNV))
1240 #define del_XNV(p) my_safefree(p)
1242 #define new_XPV() my_safemalloc(sizeof(XPV))
1243 #define del_XPV(p) my_safefree(p)
1245 #define new_XPVIV() my_safemalloc(sizeof(XPVIV))
1246 #define del_XPVIV(p) my_safefree(p)
1248 #define new_XPVNV() my_safemalloc(sizeof(XPVNV))
1249 #define del_XPVNV(p) my_safefree(p)
1251 #define new_XPVCV() my_safemalloc(sizeof(XPVCV))
1252 #define del_XPVCV(p) my_safefree(p)
1254 #define new_XPVAV() my_safemalloc(sizeof(XPVAV))
1255 #define del_XPVAV(p) my_safefree(p)
1257 #define new_XPVHV() my_safemalloc(sizeof(XPVHV))
1258 #define del_XPVHV(p) my_safefree(p)
1260 #define new_XPVMG() my_safemalloc(sizeof(XPVMG))
1261 #define del_XPVMG(p) my_safefree(p)
1263 #define new_XPVGV() my_safemalloc(sizeof(XPVGV))
1264 #define del_XPVGV(p) my_safefree(p)
1266 #define new_XPVLV() my_safemalloc(sizeof(XPVLV))
1267 #define del_XPVLV(p) my_safefree(p)
1269 #define new_XPVBM() my_safemalloc(sizeof(XPVBM))
1270 #define del_XPVBM(p) my_safefree(p)
1274 #define new_XNV() new_body(NV, xnv)
1275 #define del_XNV(p) del_body(p, NV, xnv)
1277 #define new_XPV() new_body_allocated(XPV, xpv, xpv_cur)
1278 #define del_XPV(p) del_body_allocated(p, XPV, xpv, xpv_cur)
1280 #define new_XPVIV() new_body_allocated(XPVIV, xpviv, xpv_cur)
1281 #define del_XPVIV(p) del_body_allocated(p, XPVIV, xpviv, xpv_cur)
1283 #define new_XPVNV() new_body(XPVNV, xpvnv)
1284 #define del_XPVNV(p) del_body(p, XPVNV, xpvnv)
1286 #define new_XPVCV() new_body(XPVCV, xpvcv)
1287 #define del_XPVCV(p) del_body(p, XPVCV, xpvcv)
1289 #define new_XPVAV() new_body_allocated(XPVAV, xpvav, xav_fill)
1290 #define del_XPVAV(p) del_body_allocated(p, XPVAV, xpvav, xav_fill)
1292 #define new_XPVHV() new_body_allocated(XPVHV, xpvhv, xhv_fill)
1293 #define del_XPVHV(p) del_body_allocated(p, XPVHV, xpvhv, xhv_fill)
1295 #define new_XPVMG() new_body(XPVMG, xpvmg)
1296 #define del_XPVMG(p) del_body(p, XPVMG, xpvmg)
1298 #define new_XPVGV() new_body(XPVGV, xpvgv)
1299 #define del_XPVGV(p) del_body(p, XPVGV, xpvgv)
1301 #define new_XPVLV() new_body(XPVLV, xpvlv)
1302 #define del_XPVLV(p) del_body(p, XPVLV, xpvlv)
1304 #define new_XPVBM() new_body(XPVBM, xpvbm)
1305 #define del_XPVBM(p) del_body(p, XPVBM, xpvbm)
1309 #define new_XPVFM() my_safemalloc(sizeof(XPVFM))
1310 #define del_XPVFM(p) my_safefree(p)
1312 #define new_XPVIO() my_safemalloc(sizeof(XPVIO))
1313 #define del_XPVIO(p) my_safefree(p)
1316 =for apidoc sv_upgrade
1318 Upgrade an SV to a more complex form. Generally adds a new body type to the
1319 SV, then copies across as much information as possible from the old body.
1320 You generally want to use the C<SvUPGRADE> macro wrapper. See also C<svtype>.
1326 Perl_sv_upgrade(pTHX_ register SV *sv, U32 mt)
1336 void** old_body_arena;
1337 size_t old_body_offset;
1338 size_t old_body_length; /* Well, the length to copy. */
1340 bool zero_nv = TRUE;
1342 size_t new_body_length;
1343 size_t new_body_offset;
1344 void** new_body_arena;
1345 void** new_body_arenaroot;
1346 U32 old_type = SvTYPE(sv);
1348 if (mt != SVt_PV && SvIsCOW(sv)) {
1349 sv_force_normal_flags(sv, 0);
1352 if (SvTYPE(sv) == mt)
1355 if (SvTYPE(sv) > mt)
1356 Perl_croak(aTHX_ "sv_upgrade from type %d down to type %d",
1357 (int)SvTYPE(sv), (int)mt);
1367 old_body = SvANY(sv);
1369 old_body_offset = 0;
1370 old_body_length = 0;
1371 new_body_offset = 0;
1372 new_body_length = ~0;
1374 /* Copying structures onto other structures that have been neatly zeroed
1375 has a subtle gotcha. Consider XPVMG
1377 +------+------+------+------+------+-------+-------+
1378 | NV | CUR | LEN | IV | MAGIC | STASH |
1379 +------+------+------+------+------+-------+-------+
1380 0 4 8 12 16 20 24 28
1382 where NVs are aligned to 8 bytes, so that sizeof that structure is
1383 actually 32 bytes long, with 4 bytes of padding at the end:
1385 +------+------+------+------+------+-------+-------+------+
1386 | NV | CUR | LEN | IV | MAGIC | STASH | ??? |
1387 +------+------+------+------+------+-------+-------+------+
1388 0 4 8 12 16 20 24 28 32
1390 so what happens if you allocate memory for this structure:
1392 +------+------+------+------+------+-------+-------+------+------+...
1393 | NV | CUR | LEN | IV | MAGIC | STASH | GP | NAME |
1394 +------+------+------+------+------+-------+-------+------+------+...
1395 0 4 8 12 16 20 24 28 32 36
1397 zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
1398 expect, because you copy the area marked ??? onto GP. Now, ??? may have
1399 started out as zero once, but it's quite possible that it isn't. So now,
1400 rather than a nicely zeroed GP, you have it pointing somewhere random.
1403 (In fact, GP ends up pointing at a previous GP structure, because the
1404 principle cause of the padding in XPVMG getting garbage is a copy of
1405 sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob)
1407 So we are careful and work out the size of used parts of all the
1410 switch (SvTYPE(sv)) {
1417 else if (mt < SVt_PVIV)
1419 old_body_offset = STRUCT_OFFSET(XPVIV, xiv_iv);
1420 old_body_length = sizeof(IV);
1424 old_body_arena = (void **) &PL_xnv_root;
1425 old_body_length = sizeof(NV);
1432 pv = (char*)SvRV(sv);
1435 pv = SvPVX_mutable(sv);
1438 old_body_arena = (void **) &PL_xpv_root;
1439 old_body_offset = STRUCT_OFFSET(XPV, xpv_cur)
1440 - STRUCT_OFFSET(xpv_allocated, xpv_cur);
1441 old_body_length = STRUCT_OFFSET(XPV, xpv_len)
1442 + sizeof (((XPV*)SvANY(sv))->xpv_len)
1446 else if (mt == SVt_NV)
1450 pv = SvPVX_mutable(sv);
1454 old_body_arena = (void **) &PL_xpviv_root;
1455 old_body_offset = STRUCT_OFFSET(XPVIV, xpv_cur)
1456 - STRUCT_OFFSET(xpviv_allocated, xpv_cur);
1457 old_body_length = STRUCT_OFFSET(XPVIV, xiv_u)
1458 + sizeof (((XPVIV*)SvANY(sv))->xiv_u)
1462 pv = SvPVX_mutable(sv);
1467 old_body_arena = (void **) &PL_xpvnv_root;
1468 old_body_length = STRUCT_OFFSET(XPVNV, xiv_u)
1469 + sizeof (((XPVNV*)SvANY(sv))->xiv_u);
1473 /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1474 there's no way that it can be safely upgraded, because perl.c
1475 expects to Safefree(SvANY(PL_mess_sv)) */
1476 assert(sv != PL_mess_sv);
1477 /* This flag bit is used to mean other things in other scalar types.
1478 Given that it only has meaning inside the pad, it shouldn't be set
1479 on anything that can get upgraded. */
1480 assert((SvFLAGS(sv) & SVpad_TYPED) == 0);
1481 pv = SvPVX_mutable(sv);
1486 magic = SvMAGIC(sv);
1487 stash = SvSTASH(sv);
1488 old_body_arena = (void **) &PL_xpvmg_root;
1489 old_body_length = STRUCT_OFFSET(XPVMG, xmg_stash)
1490 + sizeof (((XPVMG*)SvANY(sv))->xmg_stash);
1494 Perl_croak(aTHX_ "Can't upgrade that kind of scalar");
1497 SvFLAGS(sv) &= ~SVTYPEMASK;
1502 Perl_croak(aTHX_ "Can't upgrade to undef");
1504 assert(old_type == SVt_NULL);
1505 SvANY(sv) = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
1509 assert(old_type == SVt_NULL);
1510 SvANY(sv) = new_XNV();
1514 assert(old_type == SVt_NULL);
1515 SvANY(sv) = &sv->sv_u.svu_rv;
1519 SvANY(sv) = new_XPVHV();
1522 HvTOTALKEYS(sv) = 0;
1524 /* Fall through... */
1527 SvANY(sv) = new_XPVAV();
1534 /* XXX? Only SVt_NULL is ever upgraded to AV or HV? */
1536 /* FIXME. Should be able to remove all this if()... if the above
1537 assertion is genuinely always true. */
1540 SvFLAGS(sv) &= ~SVf_OOK;
1543 SvPV_set(sv, (char*)0);
1544 SvMAGIC_set(sv, magic);
1545 SvSTASH_set(sv, stash);
1549 new_body = new_XPVIO();
1550 new_body_length = sizeof(XPVIO);
1553 new_body = new_XPVFM();
1554 new_body_length = sizeof(XPVFM);
1558 new_body_length = sizeof(XPVBM);
1559 new_body_arena = (void **) &PL_xpvbm_root;
1560 new_body_arenaroot = (void **) &PL_xpvbm_arenaroot;
1563 new_body_length = sizeof(XPVGV);
1564 new_body_arena = (void **) &PL_xpvgv_root;
1565 new_body_arenaroot = (void **) &PL_xpvgv_arenaroot;
1568 new_body_length = sizeof(XPVCV);
1569 new_body_arena = (void **) &PL_xpvcv_root;
1570 new_body_arenaroot = (void **) &PL_xpvcv_arenaroot;
1573 new_body_length = sizeof(XPVLV);
1574 new_body_arena = (void **) &PL_xpvlv_root;
1575 new_body_arenaroot = (void **) &PL_xpvlv_arenaroot;
1578 new_body_length = sizeof(XPVMG);
1579 new_body_arena = (void **) &PL_xpvmg_root;
1580 new_body_arenaroot = (void **) &PL_xpvmg_arenaroot;
1583 new_body_length = sizeof(XPVNV);
1584 new_body_arena = (void **) &PL_xpvnv_root;
1585 new_body_arenaroot = (void **) &PL_xpvnv_arenaroot;
1588 new_body_offset = STRUCT_OFFSET(XPVIV, xpv_cur)
1589 - STRUCT_OFFSET(xpviv_allocated, xpv_cur);
1590 new_body_length = sizeof(XPVIV) - new_body_offset;
1591 new_body_arena = (void **) &PL_xpviv_root;
1592 new_body_arenaroot = (void **) &PL_xpviv_arenaroot;
1593 /* XXX Is this still needed? Was it ever needed? Surely as there is
1594 no route from NV to PVIV, NOK can never be true */
1598 goto new_body_no_NV;
1600 new_body_offset = STRUCT_OFFSET(XPV, xpv_cur)
1601 - STRUCT_OFFSET(xpv_allocated, xpv_cur);
1602 new_body_length = sizeof(XPV) - new_body_offset;
1603 new_body_arena = (void **) &PL_xpv_root;
1604 new_body_arenaroot = (void **) &PL_xpv_arenaroot;
1606 /* PV and PVIV don't have an NV slot. */
1611 assert(new_body_length);
1613 new_body = S_new_body(aTHX_ new_body_arenaroot, new_body_arena,
1614 new_body_length, new_body_offset);
1616 /* We always allocated the full length item with PURIFY */
1617 new_body_length += new_body_offset;
1618 new_body_offset = 0;
1619 new_body = my_safemalloc(new_body_length);
1623 Zero(((char *)new_body) + new_body_offset, new_body_length, char);
1624 SvANY(sv) = new_body;
1626 if (old_body_length) {
1627 Copy((char *)old_body + old_body_offset,
1628 (char *)new_body + old_body_offset,
1629 old_body_length, char);
1632 /* FIXME - add a Configure test to determine if NV 0.0 is actually
1633 all bits zero. If it is, we can skip this initialisation. */
1638 IoPAGE_LEN(sv) = 60;
1639 if (old_type < SVt_RV)
1644 Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu", mt);
1648 if (old_body_arena) {
1650 my_safefree(old_body);
1652 S_del_body(aTHX_ old_body, old_body_arena, old_body_offset);
1658 =for apidoc sv_backoff
1660 Remove any string offset. You should normally use the C<SvOOK_off> macro
1667 Perl_sv_backoff(pTHX_ register SV *sv)
1670 assert(SvTYPE(sv) != SVt_PVHV);
1671 assert(SvTYPE(sv) != SVt_PVAV);
1673 const char *s = SvPVX_const(sv);
1674 SvLEN_set(sv, SvLEN(sv) + SvIVX(sv));
1675 SvPV_set(sv, SvPVX(sv) - SvIVX(sv));
1677 Move(s, SvPVX(sv), SvCUR(sv)+1, char);
1679 SvFLAGS(sv) &= ~SVf_OOK;
1686 Expands the character buffer in the SV. If necessary, uses C<sv_unref> and
1687 upgrades the SV to C<SVt_PV>. Returns a pointer to the character buffer.
1688 Use the C<SvGROW> wrapper instead.
1694 Perl_sv_grow(pTHX_ register SV *sv, register STRLEN newlen)
1698 #ifdef HAS_64K_LIMIT
1699 if (newlen >= 0x10000) {
1700 PerlIO_printf(Perl_debug_log,
1701 "Allocation too large: %"UVxf"\n", (UV)newlen);
1704 #endif /* HAS_64K_LIMIT */
1707 if (SvTYPE(sv) < SVt_PV) {
1708 sv_upgrade(sv, SVt_PV);
1709 s = SvPVX_mutable(sv);
1711 else if (SvOOK(sv)) { /* pv is offset? */
1713 s = SvPVX_mutable(sv);
1714 if (newlen > SvLEN(sv))
1715 newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1716 #ifdef HAS_64K_LIMIT
1717 if (newlen >= 0x10000)
1722 s = SvPVX_mutable(sv);
1724 if (newlen > SvLEN(sv)) { /* need more room? */
1725 newlen = PERL_STRLEN_ROUNDUP(newlen);
1726 if (SvLEN(sv) && s) {
1728 const STRLEN l = malloced_size((void*)SvPVX_const(sv));
1734 s = saferealloc(s, newlen);
1737 s = safemalloc(newlen);
1738 if (SvPVX_const(sv) && SvCUR(sv)) {
1739 Move(SvPVX_const(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1743 SvLEN_set(sv, newlen);
1749 =for apidoc sv_setiv
1751 Copies an integer into the given SV, upgrading first if necessary.
1752 Does not handle 'set' magic. See also C<sv_setiv_mg>.
1758 Perl_sv_setiv(pTHX_ register SV *sv, IV i)
1760 SV_CHECK_THINKFIRST_COW_DROP(sv);
1761 switch (SvTYPE(sv)) {
1763 sv_upgrade(sv, SVt_IV);
1766 sv_upgrade(sv, SVt_PVNV);
1770 sv_upgrade(sv, SVt_PVIV);
1779 Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1782 (void)SvIOK_only(sv); /* validate number */
1788 =for apidoc sv_setiv_mg
1790 Like C<sv_setiv>, but also handles 'set' magic.
1796 Perl_sv_setiv_mg(pTHX_ register SV *sv, IV i)
1803 =for apidoc sv_setuv
1805 Copies an unsigned integer into the given SV, upgrading first if necessary.
1806 Does not handle 'set' magic. See also C<sv_setuv_mg>.
1812 Perl_sv_setuv(pTHX_ register SV *sv, UV u)
1814 /* With these two if statements:
1815 u=1.49 s=0.52 cu=72.49 cs=10.64 scripts=270 tests=20865
1818 u=1.35 s=0.47 cu=73.45 cs=11.43 scripts=270 tests=20865
1820 If you wish to remove them, please benchmark to see what the effect is
1822 if (u <= (UV)IV_MAX) {
1823 sv_setiv(sv, (IV)u);
1832 =for apidoc sv_setuv_mg
1834 Like C<sv_setuv>, but also handles 'set' magic.
1840 Perl_sv_setuv_mg(pTHX_ register SV *sv, UV u)
1842 /* With these two if statements:
1843 u=1.49 s=0.52 cu=72.49 cs=10.64 scripts=270 tests=20865
1846 u=1.35 s=0.47 cu=73.45 cs=11.43 scripts=270 tests=20865
1848 If you wish to remove them, please benchmark to see what the effect is
1850 if (u <= (UV)IV_MAX) {
1851 sv_setiv(sv, (IV)u);
1861 =for apidoc sv_setnv
1863 Copies a double into the given SV, upgrading first if necessary.
1864 Does not handle 'set' magic. See also C<sv_setnv_mg>.
1870 Perl_sv_setnv(pTHX_ register SV *sv, NV num)
1872 SV_CHECK_THINKFIRST_COW_DROP(sv);
1873 switch (SvTYPE(sv)) {
1876 sv_upgrade(sv, SVt_NV);
1881 sv_upgrade(sv, SVt_PVNV);
1890 Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
1894 (void)SvNOK_only(sv); /* validate number */
1899 =for apidoc sv_setnv_mg
1901 Like C<sv_setnv>, but also handles 'set' magic.
1907 Perl_sv_setnv_mg(pTHX_ register SV *sv, NV num)
1913 /* Print an "isn't numeric" warning, using a cleaned-up,
1914 * printable version of the offending string
1918 S_not_a_number(pTHX_ SV *sv)
1925 dsv = sv_2mortal(newSVpv("", 0));
1926 pv = sv_uni_display(dsv, sv, 10, 0);
1929 char *limit = tmpbuf + sizeof(tmpbuf) - 8;
1930 /* each *s can expand to 4 chars + "...\0",
1931 i.e. need room for 8 chars */
1933 const char *s, *end;
1934 for (s = SvPVX_const(sv), end = s + SvCUR(sv); s < end && d < limit;
1937 if (ch & 128 && !isPRINT_LC(ch)) {
1946 else if (ch == '\r') {
1950 else if (ch == '\f') {
1954 else if (ch == '\\') {
1958 else if (ch == '\0') {
1962 else if (isPRINT_LC(ch))
1979 Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1980 "Argument \"%s\" isn't numeric in %s", pv,
1983 Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1984 "Argument \"%s\" isn't numeric", pv);
1988 =for apidoc looks_like_number
1990 Test if the content of an SV looks like a number (or is a number).
1991 C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1992 non-numeric warning), even if your atof() doesn't grok them.
1998 Perl_looks_like_number(pTHX_ SV *sv)
2000 register const char *sbegin;
2004 sbegin = SvPVX_const(sv);
2007 else if (SvPOKp(sv))
2008 sbegin = SvPV_const(sv, len);
2010 return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
2011 return grok_number(sbegin, len, NULL);
2014 /* Actually, ISO C leaves conversion of UV to IV undefined, but
2015 until proven guilty, assume that things are not that bad... */
2020 As 64 bit platforms often have an NV that doesn't preserve all bits of
2021 an IV (an assumption perl has been based on to date) it becomes necessary
2022 to remove the assumption that the NV always carries enough precision to
2023 recreate the IV whenever needed, and that the NV is the canonical form.
2024 Instead, IV/UV and NV need to be given equal rights. So as to not lose
2025 precision as a side effect of conversion (which would lead to insanity
2026 and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
2027 1) to distinguish between IV/UV/NV slots that have cached a valid
2028 conversion where precision was lost and IV/UV/NV slots that have a
2029 valid conversion which has lost no precision
2030 2) to ensure that if a numeric conversion to one form is requested that
2031 would lose precision, the precise conversion (or differently
2032 imprecise conversion) is also performed and cached, to prevent
2033 requests for different numeric formats on the same SV causing
2034 lossy conversion chains. (lossless conversion chains are perfectly
2039 SvIOKp is true if the IV slot contains a valid value
2040 SvIOK is true only if the IV value is accurate (UV if SvIOK_UV true)
2041 SvNOKp is true if the NV slot contains a valid value
2042 SvNOK is true only if the NV value is accurate
2045 while converting from PV to NV, check to see if converting that NV to an
2046 IV(or UV) would lose accuracy over a direct conversion from PV to
2047 IV(or UV). If it would, cache both conversions, return NV, but mark
2048 SV as IOK NOKp (ie not NOK).
2050 While converting from PV to IV, check to see if converting that IV to an
2051 NV would lose accuracy over a direct conversion from PV to NV. If it
2052 would, cache both conversions, flag similarly.
2054 Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
2055 correctly because if IV & NV were set NV *always* overruled.
2056 Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
2057 changes - now IV and NV together means that the two are interchangeable:
2058 SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
2060 The benefit of this is that operations such as pp_add know that if
2061 SvIOK is true for both left and right operands, then integer addition
2062 can be used instead of floating point (for cases where the result won't
2063 overflow). Before, floating point was always used, which could lead to
2064 loss of precision compared with integer addition.
2066 * making IV and NV equal status should make maths accurate on 64 bit
2068 * may speed up maths somewhat if pp_add and friends start to use
2069 integers when possible instead of fp. (Hopefully the overhead in
2070 looking for SvIOK and checking for overflow will not outweigh the
2071 fp to integer speedup)
2072 * will slow down integer operations (callers of SvIV) on "inaccurate"
2073 values, as the change from SvIOK to SvIOKp will cause a call into
2074 sv_2iv each time rather than a macro access direct to the IV slot
2075 * should speed up number->string conversion on integers as IV is
2076 favoured when IV and NV are equally accurate
2078 ####################################################################
2079 You had better be using SvIOK_notUV if you want an IV for arithmetic:
2080 SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
2081 On the other hand, SvUOK is true iff UV.
2082 ####################################################################
2084 Your mileage will vary depending your CPU's relative fp to integer
2088 #ifndef NV_PRESERVES_UV
2089 # define IS_NUMBER_UNDERFLOW_IV 1
2090 # define IS_NUMBER_UNDERFLOW_UV 2
2091 # define IS_NUMBER_IV_AND_UV 2
2092 # define IS_NUMBER_OVERFLOW_IV 4
2093 # define IS_NUMBER_OVERFLOW_UV 5
2095 /* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
2097 /* For sv_2nv these three cases are "SvNOK and don't bother casting" */
2099 S_sv_2iuv_non_preserve(pTHX_ register SV *sv, I32 numtype)
2101 DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_2iuv_non '%s', IV=0x%"UVxf" NV=%"NVgf" inttype=%"UVXf"\n", SvPVX_const(sv), SvIVX(sv), SvNVX(sv), (UV)numtype));
2102 if (SvNVX(sv) < (NV)IV_MIN) {
2103 (void)SvIOKp_on(sv);
2105 SvIV_set(sv, IV_MIN);
2106 return IS_NUMBER_UNDERFLOW_IV;
2108 if (SvNVX(sv) > (NV)UV_MAX) {
2109 (void)SvIOKp_on(sv);
2112 SvUV_set(sv, UV_MAX);
2113 return IS_NUMBER_OVERFLOW_UV;
2115 (void)SvIOKp_on(sv);
2117 /* Can't use strtol etc to convert this string. (See truth table in
2119 if (SvNVX(sv) <= (UV)IV_MAX) {
2120 SvIV_set(sv, I_V(SvNVX(sv)));
2121 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2122 SvIOK_on(sv); /* Integer is precise. NOK, IOK */
2124 /* Integer is imprecise. NOK, IOKp */
2126 return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
2129 SvUV_set(sv, U_V(SvNVX(sv)));
2130 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2131 if (SvUVX(sv) == UV_MAX) {
2132 /* As we know that NVs don't preserve UVs, UV_MAX cannot
2133 possibly be preserved by NV. Hence, it must be overflow.
2135 return IS_NUMBER_OVERFLOW_UV;
2137 SvIOK_on(sv); /* Integer is precise. NOK, UOK */
2139 /* Integer is imprecise. NOK, IOKp */
2141 return IS_NUMBER_OVERFLOW_IV;
2143 #endif /* !NV_PRESERVES_UV*/
2145 /* sv_2iv() is now a macro using Perl_sv_2iv_flags();
2146 * this function provided for binary compatibility only
2150 Perl_sv_2iv(pTHX_ register SV *sv)
2152 return sv_2iv_flags(sv, SV_GMAGIC);
2156 =for apidoc sv_2iv_flags
2158 Return the integer value of an SV, doing any necessary string
2159 conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2160 Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2166 Perl_sv_2iv_flags(pTHX_ register SV *sv, I32 flags)
2170 if (SvGMAGICAL(sv)) {
2171 if (flags & SV_GMAGIC)
2176 return I_V(SvNVX(sv));
2178 if (SvPOKp(sv) && SvLEN(sv))
2181 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2182 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2188 if (SvTHINKFIRST(sv)) {
2191 if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,numer)) &&
2192 (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv))))
2193 return SvIV(tmpstr);
2194 return PTR2IV(SvRV(sv));
2197 sv_force_normal_flags(sv, 0);
2199 if (SvREADONLY(sv) && !SvOK(sv)) {
2200 if (ckWARN(WARN_UNINITIALIZED))
2207 return (IV)(SvUVX(sv));
2214 /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
2215 * without also getting a cached IV/UV from it at the same time
2216 * (ie PV->NV conversion should detect loss of accuracy and cache
2217 * IV or UV at same time to avoid this. NWC */
2219 if (SvTYPE(sv) == SVt_NV)
2220 sv_upgrade(sv, SVt_PVNV);
2222 (void)SvIOKp_on(sv); /* Must do this first, to clear any SvOOK */
2223 /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
2224 certainly cast into the IV range at IV_MAX, whereas the correct
2225 answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
2227 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2228 SvIV_set(sv, I_V(SvNVX(sv)));
2229 if (SvNVX(sv) == (NV) SvIVX(sv)
2230 #ifndef NV_PRESERVES_UV
2231 && (((UV)1 << NV_PRESERVES_UV_BITS) >
2232 (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2233 /* Don't flag it as "accurately an integer" if the number
2234 came from a (by definition imprecise) NV operation, and
2235 we're outside the range of NV integer precision */
2238 SvIOK_on(sv); /* Can this go wrong with rounding? NWC */
2239 DEBUG_c(PerlIO_printf(Perl_debug_log,
2240 "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
2246 /* IV not precise. No need to convert from PV, as NV
2247 conversion would already have cached IV if it detected
2248 that PV->IV would be better than PV->NV->IV
2249 flags already correct - don't set public IOK. */
2250 DEBUG_c(PerlIO_printf(Perl_debug_log,
2251 "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
2256 /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2257 but the cast (NV)IV_MIN rounds to a the value less (more
2258 negative) than IV_MIN which happens to be equal to SvNVX ??
2259 Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2260 NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2261 (NV)UVX == NVX are both true, but the values differ. :-(
2262 Hopefully for 2s complement IV_MIN is something like
2263 0x8000000000000000 which will be exact. NWC */
2266 SvUV_set(sv, U_V(SvNVX(sv)));
2268 (SvNVX(sv) == (NV) SvUVX(sv))
2269 #ifndef NV_PRESERVES_UV
2270 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2271 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2272 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2273 /* Don't flag it as "accurately an integer" if the number
2274 came from a (by definition imprecise) NV operation, and
2275 we're outside the range of NV integer precision */
2281 DEBUG_c(PerlIO_printf(Perl_debug_log,
2282 "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
2286 return (IV)SvUVX(sv);
2289 else if (SvPOKp(sv) && SvLEN(sv)) {
2291 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2292 /* We want to avoid a possible problem when we cache an IV which
2293 may be later translated to an NV, and the resulting NV is not
2294 the same as the direct translation of the initial string
2295 (eg 123.456 can shortcut to the IV 123 with atol(), but we must
2296 be careful to ensure that the value with the .456 is around if the
2297 NV value is requested in the future).
2299 This means that if we cache such an IV, we need to cache the
2300 NV as well. Moreover, we trade speed for space, and do not
2301 cache the NV if we are sure it's not needed.
2304 /* SVt_PVNV is one higher than SVt_PVIV, hence this order */
2305 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2306 == IS_NUMBER_IN_UV) {
2307 /* It's definitely an integer, only upgrade to PVIV */
2308 if (SvTYPE(sv) < SVt_PVIV)
2309 sv_upgrade(sv, SVt_PVIV);
2311 } else if (SvTYPE(sv) < SVt_PVNV)
2312 sv_upgrade(sv, SVt_PVNV);
2314 /* If NV preserves UV then we only use the UV value if we know that
2315 we aren't going to call atof() below. If NVs don't preserve UVs
2316 then the value returned may have more precision than atof() will
2317 return, even though value isn't perfectly accurate. */
2318 if ((numtype & (IS_NUMBER_IN_UV
2319 #ifdef NV_PRESERVES_UV
2322 )) == IS_NUMBER_IN_UV) {
2323 /* This won't turn off the public IOK flag if it was set above */
2324 (void)SvIOKp_on(sv);
2326 if (!(numtype & IS_NUMBER_NEG)) {
2328 if (value <= (UV)IV_MAX) {
2329 SvIV_set(sv, (IV)value);
2331 SvUV_set(sv, value);
2335 /* 2s complement assumption */
2336 if (value <= (UV)IV_MIN) {
2337 SvIV_set(sv, -(IV)value);
2339 /* Too negative for an IV. This is a double upgrade, but
2340 I'm assuming it will be rare. */
2341 if (SvTYPE(sv) < SVt_PVNV)
2342 sv_upgrade(sv, SVt_PVNV);
2346 SvNV_set(sv, -(NV)value);
2347 SvIV_set(sv, IV_MIN);
2351 /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2352 will be in the previous block to set the IV slot, and the next
2353 block to set the NV slot. So no else here. */
2355 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2356 != IS_NUMBER_IN_UV) {
2357 /* It wasn't an (integer that doesn't overflow the UV). */
2358 SvNV_set(sv, Atof(SvPVX_const(sv)));
2360 if (! numtype && ckWARN(WARN_NUMERIC))
2363 #if defined(USE_LONG_DOUBLE)
2364 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" PERL_PRIgldbl ")\n",
2365 PTR2UV(sv), SvNVX(sv)));
2367 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"NVgf")\n",
2368 PTR2UV(sv), SvNVX(sv)));
2372 #ifdef NV_PRESERVES_UV
2373 (void)SvIOKp_on(sv);
2375 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2376 SvIV_set(sv, I_V(SvNVX(sv)));
2377 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2380 /* Integer is imprecise. NOK, IOKp */
2382 /* UV will not work better than IV */
2384 if (SvNVX(sv) > (NV)UV_MAX) {
2386 /* Integer is inaccurate. NOK, IOKp, is UV */
2387 SvUV_set(sv, UV_MAX);
2390 SvUV_set(sv, U_V(SvNVX(sv)));
2391 /* 0xFFFFFFFFFFFFFFFF not an issue in here */
2392 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2396 /* Integer is imprecise. NOK, IOKp, is UV */
2402 #else /* NV_PRESERVES_UV */
2403 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2404 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2405 /* The IV slot will have been set from value returned by
2406 grok_number above. The NV slot has just been set using
2409 assert (SvIOKp(sv));
2411 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2412 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2413 /* Small enough to preserve all bits. */
2414 (void)SvIOKp_on(sv);
2416 SvIV_set(sv, I_V(SvNVX(sv)));
2417 if ((NV)(SvIVX(sv)) == SvNVX(sv))
2419 /* Assumption: first non-preserved integer is < IV_MAX,
2420 this NV is in the preserved range, therefore: */
2421 if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2423 Perl_croak(aTHX_ "sv_2iv assumed (U_V(fabs((double)SvNVX(sv))) < (UV)IV_MAX) but SvNVX(sv)=%"NVgf" U_V is 0x%"UVxf", IV_MAX is 0x%"UVxf"\n", SvNVX(sv), U_V(SvNVX(sv)), (UV)IV_MAX);
2427 0 0 already failed to read UV.
2428 0 1 already failed to read UV.
2429 1 0 you won't get here in this case. IV/UV
2430 slot set, public IOK, Atof() unneeded.
2431 1 1 already read UV.
2432 so there's no point in sv_2iuv_non_preserve() attempting
2433 to use atol, strtol, strtoul etc. */
2434 if (sv_2iuv_non_preserve (sv, numtype)
2435 >= IS_NUMBER_OVERFLOW_IV)
2439 #endif /* NV_PRESERVES_UV */
2442 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP))
2444 if (SvTYPE(sv) < SVt_IV)
2445 /* Typically the caller expects that sv_any is not NULL now. */
2446 sv_upgrade(sv, SVt_IV);
2449 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2450 PTR2UV(sv),SvIVX(sv)));
2451 return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
2454 /* sv_2uv() is now a macro using Perl_sv_2uv_flags();
2455 * this function provided for binary compatibility only
2459 Perl_sv_2uv(pTHX_ register SV *sv)
2461 return sv_2uv_flags(sv, SV_GMAGIC);
2465 =for apidoc sv_2uv_flags
2467 Return the unsigned integer value of an SV, doing any necessary string
2468 conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2469 Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
2475 Perl_sv_2uv_flags(pTHX_ register SV *sv, I32 flags)
2479 if (SvGMAGICAL(sv)) {
2480 if (flags & SV_GMAGIC)
2485 return U_V(SvNVX(sv));
2486 if (SvPOKp(sv) && SvLEN(sv))
2489 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2490 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2496 if (SvTHINKFIRST(sv)) {
2499 if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,numer)) &&
2500 (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv))))
2501 return SvUV(tmpstr);
2502 return PTR2UV(SvRV(sv));
2505 sv_force_normal_flags(sv, 0);
2507 if (SvREADONLY(sv) && !SvOK(sv)) {
2508 if (ckWARN(WARN_UNINITIALIZED))
2518 return (UV)SvIVX(sv);
2522 /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
2523 * without also getting a cached IV/UV from it at the same time
2524 * (ie PV->NV conversion should detect loss of accuracy and cache
2525 * IV or UV at same time to avoid this. */
2526 /* IV-over-UV optimisation - choose to cache IV if possible */
2528 if (SvTYPE(sv) == SVt_NV)
2529 sv_upgrade(sv, SVt_PVNV);
2531 (void)SvIOKp_on(sv); /* Must do this first, to clear any SvOOK */
2532 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2533 SvIV_set(sv, I_V(SvNVX(sv)));
2534 if (SvNVX(sv) == (NV) SvIVX(sv)
2535 #ifndef NV_PRESERVES_UV
2536 && (((UV)1 << NV_PRESERVES_UV_BITS) >
2537 (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2538 /* Don't flag it as "accurately an integer" if the number
2539 came from a (by definition imprecise) NV operation, and
2540 we're outside the range of NV integer precision */
2543 SvIOK_on(sv); /* Can this go wrong with rounding? NWC */
2544 DEBUG_c(PerlIO_printf(Perl_debug_log,
2545 "0x%"UVxf" uv(%"NVgf" => %"IVdf") (precise)\n",
2551 /* IV not precise. No need to convert from PV, as NV
2552 conversion would already have cached IV if it detected
2553 that PV->IV would be better than PV->NV->IV
2554 flags already correct - don't set public IOK. */
2555 DEBUG_c(PerlIO_printf(Perl_debug_log,
2556 "0x%"UVxf" uv(%"NVgf" => %"IVdf") (imprecise)\n",
2561 /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2562 but the cast (NV)IV_MIN rounds to a the value less (more
2563 negative) than IV_MIN which happens to be equal to SvNVX ??
2564 Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2565 NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2566 (NV)UVX == NVX are both true, but the values differ. :-(
2567 Hopefully for 2s complement IV_MIN is something like
2568 0x8000000000000000 which will be exact. NWC */
2571 SvUV_set(sv, U_V(SvNVX(sv)));
2573 (SvNVX(sv) == (NV) SvUVX(sv))
2574 #ifndef NV_PRESERVES_UV
2575 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2576 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2577 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2578 /* Don't flag it as "accurately an integer" if the number
2579 came from a (by definition imprecise) NV operation, and
2580 we're outside the range of NV integer precision */
2585 DEBUG_c(PerlIO_printf(Perl_debug_log,
2586 "0x%"UVxf" 2uv(%"UVuf" => %"IVdf") (as unsigned)\n",
2592 else if (SvPOKp(sv) && SvLEN(sv)) {
2594 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2596 /* We want to avoid a possible problem when we cache a UV which
2597 may be later translated to an NV, and the resulting NV is not
2598 the translation of the initial data.
2600 This means that if we cache such a UV, we need to cache the
2601 NV as well. Moreover, we trade speed for space, and do not
2602 cache the NV if not needed.
2605 /* SVt_PVNV is one higher than SVt_PVIV, hence this order */
2606 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2607 == IS_NUMBER_IN_UV) {
2608 /* It's definitely an integer, only upgrade to PVIV */
2609 if (SvTYPE(sv) < SVt_PVIV)
2610 sv_upgrade(sv, SVt_PVIV);
2612 } else if (SvTYPE(sv) < SVt_PVNV)
2613 sv_upgrade(sv, SVt_PVNV);
2615 /* If NV preserves UV then we only use the UV value if we know that
2616 we aren't going to call atof() below. If NVs don't preserve UVs
2617 then the value returned may have more precision than atof() will
2618 return, even though it isn't accurate. */
2619 if ((numtype & (IS_NUMBER_IN_UV
2620 #ifdef NV_PRESERVES_UV
2623 )) == IS_NUMBER_IN_UV) {
2624 /* This won't turn off the public IOK flag if it was set above */
2625 (void)SvIOKp_on(sv);
2627 if (!(numtype & IS_NUMBER_NEG)) {
2629 if (value <= (UV)IV_MAX) {
2630 SvIV_set(sv, (IV)value);
2632 /* it didn't overflow, and it was positive. */
2633 SvUV_set(sv, value);
2637 /* 2s complement assumption */
2638 if (value <= (UV)IV_MIN) {
2639 SvIV_set(sv, -(IV)value);
2641 /* Too negative for an IV. This is a double upgrade, but
2642 I'm assuming it will be rare. */
2643 if (SvTYPE(sv) < SVt_PVNV)
2644 sv_upgrade(sv, SVt_PVNV);
2648 SvNV_set(sv, -(NV)value);
2649 SvIV_set(sv, IV_MIN);
2654 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2655 != IS_NUMBER_IN_UV) {
2656 /* It wasn't an integer, or it overflowed the UV. */
2657 SvNV_set(sv, Atof(SvPVX_const(sv)));
2659 if (! numtype && ckWARN(WARN_NUMERIC))
2662 #if defined(USE_LONG_DOUBLE)
2663 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%" PERL_PRIgldbl ")\n",
2664 PTR2UV(sv), SvNVX(sv)));
2666 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"NVgf")\n",
2667 PTR2UV(sv), SvNVX(sv)));
2670 #ifdef NV_PRESERVES_UV
2671 (void)SvIOKp_on(sv);
2673 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2674 SvIV_set(sv, I_V(SvNVX(sv)));
2675 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2678 /* Integer is imprecise. NOK, IOKp */
2680 /* UV will not work better than IV */
2682 if (SvNVX(sv) > (NV)UV_MAX) {
2684 /* Integer is inaccurate. NOK, IOKp, is UV */
2685 SvUV_set(sv, UV_MAX);
2688 SvUV_set(sv, U_V(SvNVX(sv)));
2689 /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2690 NV preservse UV so can do correct comparison. */
2691 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2695 /* Integer is imprecise. NOK, IOKp, is UV */
2700 #else /* NV_PRESERVES_UV */
2701 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2702 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2703 /* The UV slot will have been set from value returned by
2704 grok_number above. The NV slot has just been set using
2707 assert (SvIOKp(sv));
2709 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2710 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2711 /* Small enough to preserve all bits. */
2712 (void)SvIOKp_on(sv);
2714 SvIV_set(sv, I_V(SvNVX(sv)));
2715 if ((NV)(SvIVX(sv)) == SvNVX(sv))
2717 /* Assumption: first non-preserved integer is < IV_MAX,
2718 this NV is in the preserved range, therefore: */
2719 if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2721 Perl_croak(aTHX_ "sv_2uv assumed (U_V(fabs((double)SvNVX(sv))) < (UV)IV_MAX) but SvNVX(sv)=%"NVgf" U_V is 0x%"UVxf", IV_MAX is 0x%"UVxf"\n", SvNVX(sv), U_V(SvNVX(sv)), (UV)IV_MAX);
2724 sv_2iuv_non_preserve (sv, numtype);
2726 #endif /* NV_PRESERVES_UV */
2730 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2731 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2734 if (SvTYPE(sv) < SVt_IV)
2735 /* Typically the caller expects that sv_any is not NULL now. */
2736 sv_upgrade(sv, SVt_IV);
2740 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2741 PTR2UV(sv),SvUVX(sv)));
2742 return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
2748 Return the num value of an SV, doing any necessary string or integer
2749 conversion, magic etc. Normally used via the C<SvNV(sv)> and C<SvNVx(sv)>
2756 Perl_sv_2nv(pTHX_ register SV *sv)
2760 if (SvGMAGICAL(sv)) {
2764 if (SvPOKp(sv) && SvLEN(sv)) {
2765 if (ckWARN(WARN_NUMERIC) && !SvIOKp(sv) &&
2766 !grok_number(SvPVX_const(sv), SvCUR(sv), NULL))
2768 return Atof(SvPVX_const(sv));
2772 return (NV)SvUVX(sv);
2774 return (NV)SvIVX(sv);
2777 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2778 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2784 if (SvTHINKFIRST(sv)) {
2787 if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,numer)) &&
2788 (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv))))
2789 return SvNV(tmpstr);
2790 return PTR2NV(SvRV(sv));
2793 sv_force_normal_flags(sv, 0);
2795 if (SvREADONLY(sv) && !SvOK(sv)) {
2796 if (ckWARN(WARN_UNINITIALIZED))
2801 if (SvTYPE(sv) < SVt_NV) {
2802 if (SvTYPE(sv) == SVt_IV)
2803 sv_upgrade(sv, SVt_PVNV);
2805 sv_upgrade(sv, SVt_NV);
2806 #ifdef USE_LONG_DOUBLE
2808 STORE_NUMERIC_LOCAL_SET_STANDARD();
2809 PerlIO_printf(Perl_debug_log,
2810 "0x%"UVxf" num(%" PERL_PRIgldbl ")\n",
2811 PTR2UV(sv), SvNVX(sv));
2812 RESTORE_NUMERIC_LOCAL();
2816 STORE_NUMERIC_LOCAL_SET_STANDARD();
2817 PerlIO_printf(Perl_debug_log, "0x%"UVxf" num(%"NVgf")\n",
2818 PTR2UV(sv), SvNVX(sv));
2819 RESTORE_NUMERIC_LOCAL();
2823 else if (SvTYPE(sv) < SVt_PVNV)
2824 sv_upgrade(sv, SVt_PVNV);
2829 SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
2830 #ifdef NV_PRESERVES_UV
2833 /* Only set the public NV OK flag if this NV preserves the IV */
2834 /* Check it's not 0xFFFFFFFFFFFFFFFF */
2835 if (SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
2836 : (SvIVX(sv) == I_V(SvNVX(sv))))
2842 else if (SvPOKp(sv) && SvLEN(sv)) {
2844 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2845 if (ckWARN(WARN_NUMERIC) && !SvIOKp(sv) && !numtype)
2847 #ifdef NV_PRESERVES_UV
2848 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2849 == IS_NUMBER_IN_UV) {
2850 /* It's definitely an integer */
2851 SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
2853 SvNV_set(sv, Atof(SvPVX_const(sv)));
2856 SvNV_set(sv, Atof(SvPVX_const(sv)));
2857 /* Only set the public NV OK flag if this NV preserves the value in
2858 the PV at least as well as an IV/UV would.
2859 Not sure how to do this 100% reliably. */
2860 /* if that shift count is out of range then Configure's test is
2861 wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2863 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2864 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2865 SvNOK_on(sv); /* Definitely small enough to preserve all bits */
2866 } else if (!(numtype & IS_NUMBER_IN_UV)) {
2867 /* Can't use strtol etc to convert this string, so don't try.
2868 sv_2iv and sv_2uv will use the NV to convert, not the PV. */
2871 /* value has been set. It may not be precise. */
2872 if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2873 /* 2s complement assumption for (UV)IV_MIN */
2874 SvNOK_on(sv); /* Integer is too negative. */
2879 if (numtype & IS_NUMBER_NEG) {
2880 SvIV_set(sv, -(IV)value);
2881 } else if (value <= (UV)IV_MAX) {
2882 SvIV_set(sv, (IV)value);
2884 SvUV_set(sv, value);
2888 if (numtype & IS_NUMBER_NOT_INT) {
2889 /* I believe that even if the original PV had decimals,
2890 they are lost beyond the limit of the FP precision.
2891 However, neither is canonical, so both only get p
2892 flags. NWC, 2000/11/25 */
2893 /* Both already have p flags, so do nothing */
2895 const NV nv = SvNVX(sv);
2896 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2897 if (SvIVX(sv) == I_V(nv)) {
2902 /* It had no "." so it must be integer. */
2905 /* between IV_MAX and NV(UV_MAX).
2906 Could be slightly > UV_MAX */
2908 if (numtype & IS_NUMBER_NOT_INT) {
2909 /* UV and NV both imprecise. */
2911 const UV nv_as_uv = U_V(nv);
2913 if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2924 #endif /* NV_PRESERVES_UV */
2927 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP))
2929 if (SvTYPE(sv) < SVt_NV)
2930 /* Typically the caller expects that sv_any is not NULL now. */
2931 /* XXX Ilya implies that this is a bug in callers that assume this
2932 and ideally should be fixed. */
2933 sv_upgrade(sv, SVt_NV);
2936 #if defined(USE_LONG_DOUBLE)
2938 STORE_NUMERIC_LOCAL_SET_STANDARD();
2939 PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" PERL_PRIgldbl ")\n",
2940 PTR2UV(sv), SvNVX(sv));
2941 RESTORE_NUMERIC_LOCAL();
2945 STORE_NUMERIC_LOCAL_SET_STANDARD();
2946 PerlIO_printf(Perl_debug_log, "0x%"UVxf" 1nv(%"NVgf")\n",
2947 PTR2UV(sv), SvNVX(sv));
2948 RESTORE_NUMERIC_LOCAL();
2954 /* asIV(): extract an integer from the string value of an SV.
2955 * Caller must validate PVX */
2958 S_asIV(pTHX_ SV *sv)
2961 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2963 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2964 == IS_NUMBER_IN_UV) {
2965 /* It's definitely an integer */
2966 if (numtype & IS_NUMBER_NEG) {
2967 if (value < (UV)IV_MIN)
2970 if (value < (UV)IV_MAX)
2975 if (ckWARN(WARN_NUMERIC))
2978 return I_V(Atof(SvPVX_const(sv)));
2981 /* asUV(): extract an unsigned integer from the string value of an SV
2982 * Caller must validate PVX */
2985 S_asUV(pTHX_ SV *sv)
2988 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2990 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2991 == IS_NUMBER_IN_UV) {
2992 /* It's definitely an integer */
2993 if (!(numtype & IS_NUMBER_NEG))
2997 if (ckWARN(WARN_NUMERIC))
3000 return U_V(Atof(SvPVX_const(sv)));
3004 =for apidoc sv_2pv_nolen
3006 Like C<sv_2pv()>, but doesn't return the length too. You should usually
3007 use the macro wrapper C<SvPV_nolen(sv)> instead.
3012 Perl_sv_2pv_nolen(pTHX_ register SV *sv)
3014 return sv_2pv(sv, 0);
3017 /* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
3018 * UV as a string towards the end of buf, and return pointers to start and
3021 * We assume that buf is at least TYPE_CHARS(UV) long.
3025 uiv_2buf(char *buf, IV iv, UV uv, int is_uv, char **peob)
3027 char *ptr = buf + TYPE_CHARS(UV);
3041 *--ptr = '0' + (char)(uv % 10);
3049 /* sv_2pv() is now a macro using Perl_sv_2pv_flags();
3050 * this function provided for binary compatibility only
3054 Perl_sv_2pv(pTHX_ register SV *sv, STRLEN *lp)
3056 return sv_2pv_flags(sv, lp, SV_GMAGIC);
3060 =for apidoc sv_2pv_flags
3062 Returns a pointer to the string value of an SV, and sets *lp to its length.
3063 If flags includes SV_GMAGIC, does an mg_get() first. Coerces sv to a string
3065 Normally invoked via the C<SvPV_flags> macro. C<sv_2pv()> and C<sv_2pv_nomg>
3066 usually end up here too.
3072 Perl_sv_2pv_flags(pTHX_ register SV *sv, STRLEN *lp, I32 flags)
3077 char tbuf[64]; /* Must fit sprintf/Gconvert of longest IV/NV */
3078 char *tmpbuf = tbuf;
3085 if (SvGMAGICAL(sv)) {
3086 if (flags & SV_GMAGIC)
3091 if (flags & SV_MUTABLE_RETURN)
3092 return SvPVX_mutable(sv);
3093 if (flags & SV_CONST_RETURN)
3094 return (char *)SvPVX_const(sv);
3099 (void)sprintf(tmpbuf,"%"UVuf, (UV)SvUVX(sv));
3101 (void)sprintf(tmpbuf,"%"IVdf, (IV)SvIVX(sv));
3106 Gconvert(SvNVX(sv), NV_DIG, 0, tmpbuf);
3111 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
3112 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
3120 if (SvTHINKFIRST(sv)) {
3123 register const char *typestr;
3124 if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,string)) &&
3125 (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
3127 /* char *pv = lp ? SvPV(tmpstr, *lp) : SvPV_nolen(tmpstr); */
3130 if ((SvFLAGS(tmpstr) & (SVf_POK)) == SVf_POK) {
3131 if (flags & SV_CONST_RETURN) {
3132 pv = (char *) SvPVX_const(tmpstr);
3134 pv = (flags & SV_MUTABLE_RETURN)
3135 ? SvPVX_mutable(tmpstr) : SvPVX(tmpstr);
3138 *lp = SvCUR(tmpstr);
3140 pv = sv_2pv_flags(tmpstr, lp, flags);
3151 typestr = "NULLREF";
3155 switch (SvTYPE(sv)) {
3157 if ( ((SvFLAGS(sv) &
3158 (SVs_OBJECT|SVf_OK|SVs_GMG|SVs_SMG|SVs_RMG))
3159 == (SVs_OBJECT|SVs_SMG))
3160 && (mg = mg_find(sv, PERL_MAGIC_qr))) {
3161 const regexp *re = (regexp *)mg->mg_obj;
3164 const char *fptr = "msix";
3169 char need_newline = 0;
3170 U16 reganch = (U16)((re->reganch & PMf_COMPILETIME) >> 12);
3172 while((ch = *fptr++)) {
3174 reflags[left++] = ch;
3177 reflags[right--] = ch;
3182 reflags[left] = '-';
3186 mg->mg_len = re->prelen + 4 + left;
3188 * If /x was used, we have to worry about a regex
3189 * ending with a comment later being embedded
3190 * within another regex. If so, we don't want this
3191 * regex's "commentization" to leak out to the
3192 * right part of the enclosing regex, we must cap
3193 * it with a newline.
3195 * So, if /x was used, we scan backwards from the
3196 * end of the regex. If we find a '#' before we
3197 * find a newline, we need to add a newline
3198 * ourself. If we find a '\n' first (or if we
3199 * don't find '#' or '\n'), we don't need to add
3200 * anything. -jfriedl
3202 if (PMf_EXTENDED & re->reganch)
3204 const char *endptr = re->precomp + re->prelen;
3205 while (endptr >= re->precomp)
3207 const char c = *(endptr--);
3209 break; /* don't need another */
3211 /* we end while in a comment, so we
3213 mg->mg_len++; /* save space for it */
3214 need_newline = 1; /* note to add it */
3220 New(616, mg->mg_ptr, mg->mg_len + 1 + left, char);
3221 Copy("(?", mg->mg_ptr, 2, char);
3222 Copy(reflags, mg->mg_ptr+2, left, char);
3223 Copy(":", mg->mg_ptr+left+2, 1, char);
3224 Copy(re->precomp, mg->mg_ptr+3+left, re->prelen, char);
3226 mg->mg_ptr[mg->mg_len - 2] = '\n';
3227 mg->mg_ptr[mg->mg_len - 1] = ')';
3228 mg->mg_ptr[mg->mg_len] = 0;
3230 PL_reginterp_cnt += re->program[0].next_off;
3232 if (re->reganch & ROPT_UTF8)
3248 case SVt_PVBM: typestr = SvROK(sv) ? "REF" : "SCALAR"; break;
3249 case SVt_PVLV: typestr = SvROK(sv) ? "REF"
3250 /* tied lvalues should appear to be
3251 * scalars for backwards compatitbility */
3252 : (LvTYPE(sv) == 't' || LvTYPE(sv) == 'T')
3253 ? "SCALAR" : "LVALUE"; break;
3254 case SVt_PVAV: typestr = "ARRAY"; break;
3255 case SVt_PVHV: typestr = "HASH"; break;
3256 case SVt_PVCV: typestr = "CODE"; break;
3257 case SVt_PVGV: typestr = "GLOB"; break;
3258 case SVt_PVFM: typestr = "FORMAT"; break;
3259 case SVt_PVIO: typestr = "IO"; break;
3260 default: typestr = "UNKNOWN"; break;
3264 const char *name = HvNAME_get(SvSTASH(sv));
3265 Perl_sv_setpvf(aTHX_ tsv, "%s=%s(0x%"UVxf")",
3266 name ? name : "__ANON__" , typestr, PTR2UV(sv));
3269 Perl_sv_setpvf(aTHX_ tsv, "%s(0x%"UVxf")", typestr, PTR2UV(sv));
3273 *lp = strlen(typestr);
3274 return (char *)typestr;
3276 if (SvREADONLY(sv) && !SvOK(sv)) {
3277 if (ckWARN(WARN_UNINITIALIZED))
3284 if (SvIOK(sv) || ((SvIOKp(sv) && !SvNOKp(sv)))) {
3285 /* I'm assuming that if both IV and NV are equally valid then
3286 converting the IV is going to be more efficient */
3287 const U32 isIOK = SvIOK(sv);
3288 const U32 isUIOK = SvIsUV(sv);
3289 char buf[TYPE_CHARS(UV)];
3292 if (SvTYPE(sv) < SVt_PVIV)
3293 sv_upgrade(sv, SVt_PVIV);
3295 ptr = uiv_2buf(buf, 0, SvUVX(sv), 1, &ebuf);
3297 ptr = uiv_2buf(buf, SvIVX(sv), 0, 0, &ebuf);
3298 /* inlined from sv_setpvn */
3299 SvGROW_mutable(sv, (STRLEN)(ebuf - ptr + 1));
3300 Move(ptr,SvPVX_mutable(sv),ebuf - ptr,char);
3301 SvCUR_set(sv, ebuf - ptr);
3311 else if (SvNOKp(sv)) {
3312 if (SvTYPE(sv) < SVt_PVNV)
3313 sv_upgrade(sv, SVt_PVNV);
3314 /* The +20 is pure guesswork. Configure test needed. --jhi */
3315 s = SvGROW_mutable(sv, NV_DIG + 20);
3316 olderrno = errno; /* some Xenix systems wipe out errno here */
3318 if (SvNVX(sv) == 0.0)
3319 (void)strcpy(s,"0");
3323 Gconvert(SvNVX(sv), NV_DIG, 0, s);
3326 #ifdef FIXNEGATIVEZERO
3327 if (*s == '-' && s[1] == '0' && !s[2])
3337 if (ckWARN(WARN_UNINITIALIZED)
3338 && !PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP))
3342 if (SvTYPE(sv) < SVt_PV)
3343 /* Typically the caller expects that sv_any is not NULL now. */
3344 sv_upgrade(sv, SVt_PV);
3348 STRLEN len = s - SvPVX_const(sv);
3354 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
3355 PTR2UV(sv),SvPVX_const(sv)));
3356 if (flags & SV_CONST_RETURN)
3357 return (char *)SvPVX_const(sv);
3358 if (flags & SV_MUTABLE_RETURN)
3359 return SvPVX_mutable(sv);
3363 if (SvROK(sv)) { /* XXX Skip this when sv_pvn_force calls */
3364 /* Sneaky stuff here */
3368 tsv = newSVpv(tmpbuf, 0);
3381 t = SvPVX_const(tsv);
3386 len = strlen(tmpbuf);
3388 #ifdef FIXNEGATIVEZERO
3389 if (len == 2 && t[0] == '-' && t[1] == '0') {
3394 SvUPGRADE(sv, SVt_PV);
3397 s = SvGROW_mutable(sv, len + 1);
3400 return strcpy(s, t);
3405 =for apidoc sv_copypv
3407 Copies a stringified representation of the source SV into the
3408 destination SV. Automatically performs any necessary mg_get and
3409 coercion of numeric values into strings. Guaranteed to preserve
3410 UTF-8 flag even from overloaded objects. Similar in nature to
3411 sv_2pv[_flags] but operates directly on an SV instead of just the
3412 string. Mostly uses sv_2pv_flags to do its work, except when that
3413 would lose the UTF-8'ness of the PV.
3419 Perl_sv_copypv(pTHX_ SV *dsv, register SV *ssv)
3423 s = SvPV_const(ssv,len);
3424 sv_setpvn(dsv,s,len);
3432 =for apidoc sv_2pvbyte_nolen
3434 Return a pointer to the byte-encoded representation of the SV.
3435 May cause the SV to be downgraded from UTF-8 as a side-effect.
3437 Usually accessed via the C<SvPVbyte_nolen> macro.
3443 Perl_sv_2pvbyte_nolen(pTHX_ register SV *sv)
3445 return sv_2pvbyte(sv, 0);
3449 =for apidoc sv_2pvbyte
3451 Return a pointer to the byte-encoded representation of the SV, and set *lp
3452 to its length. May cause the SV to be downgraded from UTF-8 as a
3455 Usually accessed via the C<SvPVbyte> macro.
3461 Perl_sv_2pvbyte(pTHX_ register SV *sv, STRLEN *lp)
3463 sv_utf8_downgrade(sv,0);
3464 return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
3468 =for apidoc sv_2pvutf8_nolen
3470 Return a pointer to the UTF-8-encoded representation of the SV.
3471 May cause the SV to be upgraded to UTF-8 as a side-effect.
3473 Usually accessed via the C<SvPVutf8_nolen> macro.
3479 Perl_sv_2pvutf8_nolen(pTHX_ register SV *sv)
3481 return sv_2pvutf8(sv, 0);
3485 =for apidoc sv_2pvutf8
3487 Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
3488 to its length. May cause the SV to be upgraded to UTF-8 as a side-effect.
3490 Usually accessed via the C<SvPVutf8> macro.
3496 Perl_sv_2pvutf8(pTHX_ register SV *sv, STRLEN *lp)
3498 sv_utf8_upgrade(sv);
3499 return SvPV(sv,*lp);
3503 =for apidoc sv_2bool
3505 This function is only called on magical items, and is only used by
3506 sv_true() or its macro equivalent.
3512 Perl_sv_2bool(pTHX_ register SV *sv)
3521 if (SvAMAGIC(sv) && (tmpsv=AMG_CALLun(sv,bool_)) &&
3522 (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
3523 return (bool)SvTRUE(tmpsv);
3524 return SvRV(sv) != 0;
3527 register XPV* Xpvtmp;
3528 if ((Xpvtmp = (XPV*)SvANY(sv)) &&
3529 (*sv->sv_u.svu_pv > '0' ||
3530 Xpvtmp->xpv_cur > 1 ||
3531 (Xpvtmp->xpv_cur && *sv->sv_u.svu_pv != '0')))
3538 return SvIVX(sv) != 0;
3541 return SvNVX(sv) != 0.0;
3548 /* sv_utf8_upgrade() is now a macro using sv_utf8_upgrade_flags();
3549 * this function provided for binary compatibility only
3554 Perl_sv_utf8_upgrade(pTHX_ register SV *sv)
3556 return sv_utf8_upgrade_flags(sv, SV_GMAGIC);
3560 =for apidoc sv_utf8_upgrade
3562 Converts the PV of an SV to its UTF-8-encoded form.
3563 Forces the SV to string form if it is not already.
3564 Always sets the SvUTF8 flag to avoid future validity checks even
3565 if all the bytes have hibit clear.
3567 This is not as a general purpose byte encoding to Unicode interface:
3568 use the Encode extension for that.
3570 =for apidoc sv_utf8_upgrade_flags
3572 Converts the PV of an SV to its UTF-8-encoded form.
3573 Forces the SV to string form if it is not already.
3574 Always sets the SvUTF8 flag to avoid future validity checks even
3575 if all the bytes have hibit clear. If C<flags> has C<SV_GMAGIC> bit set,
3576 will C<mg_get> on C<sv> if appropriate, else not. C<sv_utf8_upgrade> and
3577 C<sv_utf8_upgrade_nomg> are implemented in terms of this function.
3579 This is not as a general purpose byte encoding to Unicode interface:
3580 use the Encode extension for that.
3586 Perl_sv_utf8_upgrade_flags(pTHX_ register SV *sv, I32 flags)
3588 if (sv == &PL_sv_undef)
3592 if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
3593 (void) sv_2pv_flags(sv,&len, flags);
3597 (void) SvPV_force(sv,len);
3606 sv_force_normal_flags(sv, 0);
3609 if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING))
3610 sv_recode_to_utf8(sv, PL_encoding);
3611 else { /* Assume Latin-1/EBCDIC */
3612 /* This function could be much more efficient if we
3613 * had a FLAG in SVs to signal if there are any hibit
3614 * chars in the PV. Given that there isn't such a flag
3615 * make the loop as fast as possible. */
3616 const U8 *s = (U8 *) SvPVX_const(sv);
3617 const U8 *e = (U8 *) SvEND(sv);
3623 if ((hibit = !NATIVE_IS_INVARIANT(ch)))
3627 STRLEN len = SvCUR(sv) + 1; /* Plus the \0 */
3628 U8 *recoded = bytes_to_utf8((U8*)s, &len);
3630 SvPV_free(sv); /* No longer using what was there before. */
3632 SvPV_set(sv, (char*)recoded);
3633 SvCUR_set(sv, len - 1);
3634 SvLEN_set(sv, len); /* No longer know the real size. */
3636 /* Mark as UTF-8 even if no hibit - saves scanning loop */
3643 =for apidoc sv_utf8_downgrade
3645 Attempts to convert the PV of an SV from characters to bytes.
3646 If the PV contains a character beyond byte, this conversion will fail;
3647 in this case, either returns false or, if C<fail_ok> is not
3650 This is not as a general purpose Unicode to byte encoding interface:
3651 use the Encode extension for that.
3657 Perl_sv_utf8_downgrade(pTHX_ register SV* sv, bool fail_ok)
3659 if (SvPOKp(sv) && SvUTF8(sv)) {
3665 sv_force_normal_flags(sv, 0);
3667 s = (U8 *) SvPV(sv, len);
3668 if (!utf8_to_bytes(s, &len)) {
3673 Perl_croak(aTHX_ "Wide character in %s",
3676 Perl_croak(aTHX_ "Wide character");
3687 =for apidoc sv_utf8_encode
3689 Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3690 flag off so that it looks like octets again.
3696 Perl_sv_utf8_encode(pTHX_ register SV *sv)
3698 (void) sv_utf8_upgrade(sv);
3700 sv_force_normal_flags(sv, 0);
3702 if (SvREADONLY(sv)) {
3703 Perl_croak(aTHX_ PL_no_modify);
3709 =for apidoc sv_utf8_decode
3711 If the PV of the SV is an octet sequence in UTF-8
3712 and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3713 so that it looks like a character. If the PV contains only single-byte
3714 characters, the C<SvUTF8> flag stays being off.
3715 Scans PV for validity and returns false if the PV is invalid UTF-8.
3721 Perl_sv_utf8_decode(pTHX_ register SV *sv)
3727 /* The octets may have got themselves encoded - get them back as
3730 if (!sv_utf8_downgrade(sv, TRUE))
3733 /* it is actually just a matter of turning the utf8 flag on, but
3734 * we want to make sure everything inside is valid utf8 first.
3736 c = (const U8 *) SvPVX_const(sv);
3737 if (!is_utf8_string(c, SvCUR(sv)+1))
3739 e = (const U8 *) SvEND(sv);
3742 if (!UTF8_IS_INVARIANT(ch)) {
3751 /* sv_setsv() is now a macro using Perl_sv_setsv_flags();
3752 * this function provided for binary compatibility only
3756 Perl_sv_setsv(pTHX_ SV *dstr, register SV *sstr)
3758 sv_setsv_flags(dstr, sstr, SV_GMAGIC);
3762 =for apidoc sv_setsv
3764 Copies the contents of the source SV C<ssv> into the destination SV
3765 C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3766 function if the source SV needs to be reused. Does not handle 'set' magic.
3767 Loosely speaking, it performs a copy-by-value, obliterating any previous
3768 content of the destination.
3770 You probably want to use one of the assortment of wrappers, such as
3771 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3772 C<SvSetMagicSV_nosteal>.
3774 =for apidoc sv_setsv_flags
3776 Copies the contents of the source SV C<ssv> into the destination SV
3777 C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3778 function if the source SV needs to be reused. Does not handle 'set' magic.
3779 Loosely speaking, it performs a copy-by-value, obliterating any previous
3780 content of the destination.
3781 If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
3782 C<ssv> if appropriate, else not. If the C<flags> parameter has the
3783 C<NOSTEAL> bit set then the buffers of temps will not be stolen. <sv_setsv>
3784 and C<sv_setsv_nomg> are implemented in terms of this function.
3786 You probably want to use one of the assortment of wrappers, such as
3787 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3788 C<SvSetMagicSV_nosteal>.
3790 This is the primary function for copying scalars, and most other
3791 copy-ish functions and macros use this underneath.
3797 Perl_sv_setsv_flags(pTHX_ SV *dstr, register SV *sstr, I32 flags)
3799 register U32 sflags;
3805 SV_CHECK_THINKFIRST_COW_DROP(dstr);
3807 sstr = &PL_sv_undef;
3808 stype = SvTYPE(sstr);
3809 dtype = SvTYPE(dstr);
3814 /* need to nuke the magic */
3816 SvRMAGICAL_off(dstr);
3819 /* There's a lot of redundancy below but we're going for speed here */
3824 if (dtype != SVt_PVGV) {
3825 (void)SvOK_off(dstr);
3833 sv_upgrade(dstr, SVt_IV);
3836 sv_upgrade(dstr, SVt_PVNV);
3840 sv_upgrade(dstr, SVt_PVIV);
3843 (void)SvIOK_only(dstr);
3844 SvIV_set(dstr, SvIVX(sstr));
3847 if (SvTAINTED(sstr))
3858 sv_upgrade(dstr, SVt_NV);
3863 sv_upgrade(dstr, SVt_PVNV);
3866 SvNV_set(dstr, SvNVX(sstr));
3867 (void)SvNOK_only(dstr);
3868 if (SvTAINTED(sstr))
3876 sv_upgrade(dstr, SVt_RV);
3877 else if (dtype == SVt_PVGV &&
3878 SvROK(sstr) && SvTYPE(SvRV(sstr)) == SVt_PVGV) {
3881 if (GvIMPORTED(dstr) != GVf_IMPORTED
3882 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3884 GvIMPORTED_on(dstr);
3893 #ifdef PERL_OLD_COPY_ON_WRITE
3894 if ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS) {
3895 if (dtype < SVt_PVIV)
3896 sv_upgrade(dstr, SVt_PVIV);
3903 sv_upgrade(dstr, SVt_PV);
3906 if (dtype < SVt_PVIV)
3907 sv_upgrade(dstr, SVt_PVIV);
3910 if (dtype < SVt_PVNV)
3911 sv_upgrade(dstr, SVt_PVNV);
3918 const char * const type = sv_reftype(sstr,0);
3920 Perl_croak(aTHX_ "Bizarre copy of %s in %s", type, OP_NAME(PL_op));
3922 Perl_croak(aTHX_ "Bizarre copy of %s", type);
3927 if (dtype <= SVt_PVGV) {
3929 if (dtype != SVt_PVGV) {
3930 const char * const name = GvNAME(sstr);
3931 const STRLEN len = GvNAMELEN(sstr);
3932 /* don't upgrade SVt_PVLV: it can hold a glob */
3933 if (dtype != SVt_PVLV)
3934 sv_upgrade(dstr, SVt_PVGV);
3935 sv_magic(dstr, dstr, PERL_MAGIC_glob, Nullch, 0);
3936 GvSTASH(dstr) = (HV*)SvREFCNT_inc(GvSTASH(sstr));
3937 GvNAME(dstr) = savepvn(name, len);
3938 GvNAMELEN(dstr) = len;
3939 SvFAKE_on(dstr); /* can coerce to non-glob */
3941 /* ahem, death to those who redefine active sort subs */
3942 else if (PL_curstackinfo->si_type == PERLSI_SORT
3943 && GvCV(dstr) && PL_sortcop == CvSTART(GvCV(dstr)))
3944 Perl_croak(aTHX_ "Can't redefine active sort subroutine %s",
3947 #ifdef GV_UNIQUE_CHECK
3948 if (GvUNIQUE((GV*)dstr)) {
3949 Perl_croak(aTHX_ PL_no_modify);
3953 (void)SvOK_off(dstr);
3954 GvINTRO_off(dstr); /* one-shot flag */
3956 GvGP(dstr) = gp_ref(GvGP(sstr));
3957 if (SvTAINTED(sstr))
3959 if (GvIMPORTED(dstr) != GVf_IMPORTED
3960 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3962 GvIMPORTED_on(dstr);
3970 if (SvGMAGICAL(sstr) && (flags & SV_GMAGIC)) {
3972 if ((int)SvTYPE(sstr) != stype) {
3973 stype = SvTYPE(sstr);
3974 if (stype == SVt_PVGV && dtype <= SVt_PVGV)
3978 if (stype == SVt_PVLV)
3979 SvUPGRADE(dstr, SVt_PVNV);
3981 SvUPGRADE(dstr, (U32)stype);
3984 sflags = SvFLAGS(sstr);
3986 if (sflags & SVf_ROK) {
3987 if (dtype >= SVt_PV) {
3988 if (dtype == SVt_PVGV) {
3989 SV *sref = SvREFCNT_inc(SvRV(sstr));
3991 const int intro = GvINTRO(dstr);
3993 #ifdef GV_UNIQUE_CHECK
3994 if (GvUNIQUE((GV*)dstr)) {
3995 Perl_croak(aTHX_ PL_no_modify);
4000 GvINTRO_off(dstr); /* one-shot flag */
4001 GvLINE(dstr) = CopLINE(PL_curcop);
4002 GvEGV(dstr) = (GV*)dstr;
4005 switch (SvTYPE(sref)) {
4008 SAVEGENERICSV(GvAV(dstr));
4010 dref = (SV*)GvAV(dstr);
4011 GvAV(dstr) = (AV*)sref;
4012 if (!GvIMPORTED_AV(dstr)
4013 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
4015 GvIMPORTED_AV_on(dstr);
4020 SAVEGENERICSV(GvHV(dstr));
4022 dref = (SV*)GvHV(dstr);
4023 GvHV(dstr) = (HV*)sref;
4024 if (!GvIMPORTED_HV(dstr)
4025 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
4027 GvIMPORTED_HV_on(dstr);
4032 if (GvCVGEN(dstr) && GvCV(dstr) != (CV*)sref) {
4033 SvREFCNT_dec(GvCV(dstr));
4034 GvCV(dstr) = Nullcv;
4035 GvCVGEN(dstr) = 0; /* Switch off cacheness. */
4036 PL_sub_generation++;
4038 SAVEGENERICSV(GvCV(dstr));
4041 dref = (SV*)GvCV(dstr);
4042 if (GvCV(dstr) != (CV*)sref) {
4043 CV* cv = GvCV(dstr);
4045 if (!GvCVGEN((GV*)dstr) &&
4046 (CvROOT(cv) || CvXSUB(cv)))
4048 /* ahem, death to those who redefine
4049 * active sort subs */
4050 if (PL_curstackinfo->si_type == PERLSI_SORT &&
4051 PL_sortcop == CvSTART(cv))
4053 "Can't redefine active sort subroutine %s",
4054 GvENAME((GV*)dstr));
4055 /* Redefining a sub - warning is mandatory if
4056 it was a const and its value changed. */
4057 if (ckWARN(WARN_REDEFINE)
4059 && (!CvCONST((CV*)sref)
4060 || sv_cmp(cv_const_sv(cv),
4061 cv_const_sv((CV*)sref)))))
4063 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
4065 ? "Constant subroutine %s::%s redefined"
4066 : "Subroutine %s::%s redefined",
4067 HvNAME_get(GvSTASH((GV*)dstr)),
4068 GvENAME((GV*)dstr));
4072 cv_ckproto(cv, (GV*)dstr,
4074 ? SvPVX_const(sref) : Nullch);
4076 GvCV(dstr) = (CV*)sref;
4077 GvCVGEN(dstr) = 0; /* Switch off cacheness. */
4078 GvASSUMECV_on(dstr);
4079 PL_sub_generation++;
4081 if (!GvIMPORTED_CV(dstr)
4082 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
4084 GvIMPORTED_CV_on(dstr);
4089 SAVEGENERICSV(GvIOp(dstr));
4091 dref = (SV*)GvIOp(dstr);
4092 GvIOp(dstr) = (IO*)sref;
4096 SAVEGENERICSV(GvFORM(dstr));
4098 dref = (SV*)GvFORM(dstr);
4099 GvFORM(dstr) = (CV*)sref;
4103 SAVEGENERICSV(GvSV(dstr));
4105 dref = (SV*)GvSV(dstr);
4107 if (!GvIMPORTED_SV(dstr)
4108 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
4110 GvIMPORTED_SV_on(dstr);
4116 if (SvTAINTED(sstr))
4120 if (SvPVX_const(dstr)) {
4126 (void)SvOK_off(dstr);
4127 SvRV_set(dstr, SvREFCNT_inc(SvRV(sstr)));
4129 if (sflags & SVp_NOK) {
4131 /* Only set the public OK flag if the source has public OK. */
4132 if (sflags & SVf_NOK)
4133 SvFLAGS(dstr) |= SVf_NOK;
4134 SvNV_set(dstr, SvNVX(sstr));
4136 if (sflags & SVp_IOK) {
4137 (void)SvIOKp_on(dstr);
4138 if (sflags & SVf_IOK)
4139 SvFLAGS(dstr) |= SVf_IOK;
4140 if (sflags & SVf_IVisUV)
4142 SvIV_set(dstr, SvIVX(sstr));
4144 if (SvAMAGIC(sstr)) {
4148 else if (sflags & SVp_POK) {
4152 * Check to see if we can just swipe the string. If so, it's a
4153 * possible small lose on short strings, but a big win on long ones.
4154 * It might even be a win on short strings if SvPVX_const(dstr)
4155 * has to be allocated and SvPVX_const(sstr) has to be freed.
4158 /* Whichever path we take through the next code, we want this true,
4159 and doing it now facilitates the COW check. */
4160 (void)SvPOK_only(dstr);
4163 /* We're not already COW */
4164 ((sflags & (SVf_FAKE | SVf_READONLY)) != (SVf_FAKE | SVf_READONLY)
4165 #ifndef PERL_OLD_COPY_ON_WRITE
4166 /* or we are, but dstr isn't a suitable target. */
4167 || (SvFLAGS(dstr) & CAN_COW_MASK) != CAN_COW_FLAGS
4172 (sflags & SVs_TEMP) && /* slated for free anyway? */
4173 !(sflags & SVf_OOK) && /* and not involved in OOK hack? */
4174 (!(flags & SV_NOSTEAL)) &&
4175 /* and we're allowed to steal temps */
4176 SvREFCNT(sstr) == 1 && /* and no other references to it? */
4177 SvLEN(sstr) && /* and really is a string */
4178 /* and won't be needed again, potentially */
4179 !(PL_op && PL_op->op_type == OP_AASSIGN))
4180 #ifdef PERL_OLD_COPY_ON_WRITE
4181 && !((sflags & CAN_COW_MASK) == CAN_COW_FLAGS
4182 && (SvFLAGS(dstr) & CAN_COW_MASK) == CAN_COW_FLAGS
4183 && SvTYPE(sstr) >= SVt_PVIV)
4186 /* Failed the swipe test, and it's not a shared hash key either.
4187 Have to copy the string. */
4188 STRLEN len = SvCUR(sstr);
4189 SvGROW(dstr, len + 1); /* inlined from sv_setpvn */
4190 Move(SvPVX_const(sstr),SvPVX(dstr),len,char);
4191 SvCUR_set(dstr, len);
4192 *SvEND(dstr) = '\0';
4194 /* If PERL_OLD_COPY_ON_WRITE is not defined, then isSwipe will always
4196 /* Either it's a shared hash key, or it's suitable for
4197 copy-on-write or we can swipe the string. */
4199 PerlIO_printf(Perl_debug_log, "Copy on write: sstr --> dstr\n");
4203 #ifdef PERL_OLD_COPY_ON_WRITE
4205 /* I believe I should acquire a global SV mutex if
4206 it's a COW sv (not a shared hash key) to stop
4207 it going un copy-on-write.
4208 If the source SV has gone un copy on write between up there
4209 and down here, then (assert() that) it is of the correct
4210 form to make it copy on write again */
4211 if ((sflags & (SVf_FAKE | SVf_READONLY))
4212 != (SVf_FAKE | SVf_READONLY)) {
4213 SvREADONLY_on(sstr);
4215 /* Make the source SV into a loop of 1.
4216 (about to become 2) */
4217 SV_COW_NEXT_SV_SET(sstr, sstr);
4221 /* Initial code is common. */
4222 if (SvPVX_const(dstr)) { /* we know that dtype >= SVt_PV */
4224 SvFLAGS(dstr) &= ~SVf_OOK;
4225 Safefree(SvPVX_const(dstr) - SvIVX(dstr));
4227 else if (SvLEN(dstr))
4228 Safefree(SvPVX_const(dstr));
4232 /* making another shared SV. */
4233 STRLEN cur = SvCUR(sstr);
4234 STRLEN len = SvLEN(sstr);
4235 #ifdef PERL_OLD_COPY_ON_WRITE
4237 assert (SvTYPE(dstr) >= SVt_PVIV);
4238 /* SvIsCOW_normal */
4239 /* splice us in between source and next-after-source. */
4240 SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4241 SV_COW_NEXT_SV_SET(sstr, dstr);
4242 SvPV_set(dstr, SvPVX_mutable(sstr));
4246 /* SvIsCOW_shared_hash */
4247 DEBUG_C(PerlIO_printf(Perl_debug_log,
4248 "Copy on write: Sharing hash\n"));
4250 assert (SvTYPE(dstr) >= SVt_PV);
4252 HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)))));
4254 SvLEN_set(dstr, len);
4255 SvCUR_set(dstr, cur);
4256 SvREADONLY_on(dstr);
4258 /* Relesase a global SV mutex. */
4261 { /* Passes the swipe test. */
4262 SvPV_set(dstr, SvPVX_mutable(sstr));
4263 SvLEN_set(dstr, SvLEN(sstr));
4264 SvCUR_set(dstr, SvCUR(sstr));
4267 (void)SvOK_off(sstr); /* NOTE: nukes most SvFLAGS on sstr */
4268 SvPV_set(sstr, Nullch);
4274 if (sflags & SVf_UTF8)
4276 if (sflags & SVp_NOK) {
4278 if (sflags & SVf_NOK)
4279 SvFLAGS(dstr) |= SVf_NOK;
4280 SvNV_set(dstr, SvNVX(sstr));
4282 if (sflags & SVp_IOK) {
4283 (void)SvIOKp_on(dstr);
4284 if (sflags & SVf_IOK)
4285 SvFLAGS(dstr) |= SVf_IOK;
4286 if (sflags & SVf_IVisUV)
4288 SvIV_set(dstr, SvIVX(sstr));
4291 MAGIC *smg = mg_find(sstr,PERL_MAGIC_vstring);
4292 sv_magic(dstr, NULL, PERL_MAGIC_vstring,
4293 smg->mg_ptr, smg->mg_len);
4294 SvRMAGICAL_on(dstr);
4297 else if (sflags & SVp_IOK) {
4298 if (sflags & SVf_IOK)
4299 (void)SvIOK_only(dstr);
4301 (void)SvOK_off(dstr);
4302 (void)SvIOKp_on(dstr);
4304 /* XXXX Do we want to set IsUV for IV(ROK)? Be extra safe... */
4305 if (sflags & SVf_IVisUV)
4307 SvIV_set(dstr, SvIVX(sstr));
4308 if (sflags & SVp_NOK) {
4309 if (sflags & SVf_NOK)
4310 (void)SvNOK_on(dstr);
4312 (void)SvNOKp_on(dstr);
4313 SvNV_set(dstr, SvNVX(sstr));
4316 else if (sflags & SVp_NOK) {
4317 if (sflags & SVf_NOK)
4318 (void)SvNOK_only(dstr);
4320 (void)SvOK_off(dstr);
4323 SvNV_set(dstr, SvNVX(sstr));
4326 if (dtype == SVt_PVGV) {
4327 if (ckWARN(WARN_MISC))
4328 Perl_warner(aTHX_ packWARN(WARN_MISC), "Undefined value assigned to typeglob");
4331 (void)SvOK_off(dstr);
4333 if (SvTAINTED(sstr))
4338 =for apidoc sv_setsv_mg
4340 Like C<sv_setsv>, but also handles 'set' magic.
4346 Perl_sv_setsv_mg(pTHX_ SV *dstr, register SV *sstr)
4348 sv_setsv(dstr,sstr);
4352 #ifdef PERL_OLD_COPY_ON_WRITE
4354 Perl_sv_setsv_cow(pTHX_ SV *dstr, SV *sstr)
4356 STRLEN cur = SvCUR(sstr);
4357 STRLEN len = SvLEN(sstr);
4358 register char *new_pv;
4361 PerlIO_printf(Perl_debug_log, "Fast copy on write: %p -> %p\n",
4369 if (SvTHINKFIRST(dstr))
4370 sv_force_normal_flags(dstr, SV_COW_DROP_PV);
4371 else if (SvPVX_const(dstr))
4372 Safefree(SvPVX_const(dstr));
4376 SvUPGRADE(dstr, SVt_PVIV);
4378 assert (SvPOK(sstr));
4379 assert (SvPOKp(sstr));
4380 assert (!SvIOK(sstr));
4381 assert (!SvIOKp(sstr));
4382 assert (!SvNOK(sstr));
4383 assert (!SvNOKp(sstr));
4385 if (SvIsCOW(sstr)) {
4387 if (SvLEN(sstr) == 0) {
4388 /* source is a COW shared hash key. */
4389 DEBUG_C(PerlIO_printf(Perl_debug_log,
4390 "Fast copy on write: Sharing hash\n"));
4391 new_pv = HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr))));
4394 SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4396 assert ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS);
4397 SvUPGRADE(sstr, SVt_PVIV);
4398 SvREADONLY_on(sstr);
4400 DEBUG_C(PerlIO_printf(Perl_debug_log,
4401 "Fast copy on write: Converting sstr to COW\n"));
4402 SV_COW_NEXT_SV_SET(dstr, sstr);
4404 SV_COW_NEXT_SV_SET(sstr, dstr);
4405 new_pv = SvPVX_mutable(sstr);
4408 SvPV_set(dstr, new_pv);
4409 SvFLAGS(dstr) = (SVt_PVIV|SVf_POK|SVp_POK|SVf_FAKE|SVf_READONLY);
4412 SvLEN_set(dstr, len);
4413 SvCUR_set(dstr, cur);
4422 =for apidoc sv_setpvn
4424 Copies a string into an SV. The C<len> parameter indicates the number of
4425 bytes to be copied. If the C<ptr> argument is NULL the SV will become
4426 undefined. Does not handle 'set' magic. See C<sv_setpvn_mg>.
4432 Perl_sv_setpvn(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
4434 register char *dptr;
4436 SV_CHECK_THINKFIRST_COW_DROP(sv);
4442 /* len is STRLEN which is unsigned, need to copy to signed */
4445 Perl_croak(aTHX_ "panic: sv_setpvn called with negative strlen");
4447 SvUPGRADE(sv, SVt_PV);
4449 dptr = SvGROW(sv, len + 1);
4450 Move(ptr,dptr,len,char);
4453 (void)SvPOK_only_UTF8(sv); /* validate pointer */
4458 =for apidoc sv_setpvn_mg
4460 Like C<sv_setpvn>, but also handles 'set' magic.
4466 Perl_sv_setpvn_mg(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
4468 sv_setpvn(sv,ptr,len);
4473 =for apidoc sv_setpv
4475 Copies a string into an SV. The string must be null-terminated. Does not
4476 handle 'set' magic. See C<sv_setpv_mg>.
4482 Perl_sv_setpv(pTHX_ register SV *sv, register const char *ptr)
4484 register STRLEN len;
4486 SV_CHECK_THINKFIRST_COW_DROP(sv);
4492 SvUPGRADE(sv, SVt_PV);
4494 SvGROW(sv, len + 1);
4495 Move(ptr,SvPVX(sv),len+1,char);
4497 (void)SvPOK_only_UTF8(sv); /* validate pointer */
4502 =for apidoc sv_setpv_mg
4504 Like C<sv_setpv>, but also handles 'set' magic.
4510 Perl_sv_setpv_mg(pTHX_ register SV *sv, register const char *ptr)
4517 =for apidoc sv_usepvn
4519 Tells an SV to use C<ptr> to find its string value. Normally the string is
4520 stored inside the SV but sv_usepvn allows the SV to use an outside string.
4521 The C<ptr> should point to memory that was allocated by C<malloc>. The
4522 string length, C<len>, must be supplied. This function will realloc the
4523 memory pointed to by C<ptr>, so that pointer should not be freed or used by
4524 the programmer after giving it to sv_usepvn. Does not handle 'set' magic.
4525 See C<sv_usepvn_mg>.
4531 Perl_sv_usepvn(pTHX_ register SV *sv, register char *ptr, register STRLEN len)
4534 SV_CHECK_THINKFIRST_COW_DROP(sv);
4535 SvUPGRADE(sv, SVt_PV);
4540 if (SvPVX_const(sv))
4543 allocate = PERL_STRLEN_ROUNDUP(len + 1);
4544 ptr = saferealloc (ptr, allocate);
4547 SvLEN_set(sv, allocate);
4549 (void)SvPOK_only_UTF8(sv); /* validate pointer */
4554 =for apidoc sv_usepvn_mg
4556 Like C<sv_usepvn>, but also handles 'set' magic.
4562 Perl_sv_usepvn_mg(pTHX_ register SV *sv, register char *ptr, register STRLEN len)
4564 sv_usepvn(sv,ptr,len);
4568 #ifdef PERL_OLD_COPY_ON_WRITE
4569 /* Need to do this *after* making the SV normal, as we need the buffer
4570 pointer to remain valid until after we've copied it. If we let go too early,
4571 another thread could invalidate it by unsharing last of the same hash key
4572 (which it can do by means other than releasing copy-on-write Svs)
4573 or by changing the other copy-on-write SVs in the loop. */
4575 S_sv_release_COW(pTHX_ register SV *sv, const char *pvx, STRLEN len, SV *after)
4577 if (len) { /* this SV was SvIsCOW_normal(sv) */
4578 /* we need to find the SV pointing to us. */
4579 SV *current = SV_COW_NEXT_SV(after);
4581 if (current == sv) {
4582 /* The SV we point to points back to us (there were only two of us
4584 Hence other SV is no longer copy on write either. */
4586 SvREADONLY_off(after);
4588 /* We need to follow the pointers around the loop. */
4590 while ((next = SV_COW_NEXT_SV(current)) != sv) {
4593 /* don't loop forever if the structure is bust, and we have
4594 a pointer into a closed loop. */
4595 assert (current != after);
4596 assert (SvPVX_const(current) == pvx);
4598 /* Make the SV before us point to the SV after us. */
4599 SV_COW_NEXT_SV_SET(current, after);
4602 unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4607 Perl_sv_release_IVX(pTHX_ register SV *sv)
4610 sv_force_normal_flags(sv, 0);
4616 =for apidoc sv_force_normal_flags
4618 Undo various types of fakery on an SV: if the PV is a shared string, make
4619 a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
4620 an xpvmg; if we're a copy-on-write scalar, this is the on-write time when
4621 we do the copy, and is also used locally. If C<SV_COW_DROP_PV> is set
4622 then a copy-on-write scalar drops its PV buffer (if any) and becomes
4623 SvPOK_off rather than making a copy. (Used where this scalar is about to be
4624 set to some other value.) In addition, the C<flags> parameter gets passed to
4625 C<sv_unref_flags()> when unrefing. C<sv_force_normal> calls this function
4626 with flags set to 0.
4632 Perl_sv_force_normal_flags(pTHX_ register SV *sv, U32 flags)
4634 #ifdef PERL_OLD_COPY_ON_WRITE
4635 if (SvREADONLY(sv)) {
4636 /* At this point I believe I should acquire a global SV mutex. */
4638 const char *pvx = SvPVX_const(sv);
4639 const STRLEN len = SvLEN(sv);
4640 const STRLEN cur = SvCUR(sv);
4641 SV * const next = SV_COW_NEXT_SV(sv); /* next COW sv in the loop. */
4643 PerlIO_printf(Perl_debug_log,
4644 "Copy on write: Force normal %ld\n",
4650 /* This SV doesn't own the buffer, so need to New() a new one: */
4651 SvPV_set(sv, (char*)0);
4653 if (flags & SV_COW_DROP_PV) {
4654 /* OK, so we don't need to copy our buffer. */
4657 SvGROW(sv, cur + 1);
4658 Move(pvx,SvPVX(sv),cur,char);
4662 sv_release_COW(sv, pvx, len, next);
4667 else if (IN_PERL_RUNTIME)
4668 Perl_croak(aTHX_ PL_no_modify);
4669 /* At this point I believe that I can drop the global SV mutex. */
4672 if (SvREADONLY(sv)) {
4674 const char *pvx = SvPVX_const(sv);
4675 const STRLEN len = SvCUR(sv);
4678 SvPV_set(sv, Nullch);
4680 SvGROW(sv, len + 1);
4681 Move(pvx,SvPVX_const(sv),len,char);
4683 unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4685 else if (IN_PERL_RUNTIME)
4686 Perl_croak(aTHX_ PL_no_modify);
4690 sv_unref_flags(sv, flags);
4691 else if (SvFAKE(sv) && SvTYPE(sv) == SVt_PVGV)
4696 =for apidoc sv_force_normal
4698 Undo various types of fakery on an SV: if the PV is a shared string, make
4699 a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
4700 an xpvmg. See also C<sv_force_normal_flags>.
4706 Perl_sv_force_normal(pTHX_ register SV *sv)
4708 sv_force_normal_flags(sv, 0);
4714 Efficient removal of characters from the beginning of the string buffer.
4715 SvPOK(sv) must be true and the C<ptr> must be a pointer to somewhere inside
4716 the string buffer. The C<ptr> becomes the first character of the adjusted
4717 string. Uses the "OOK hack".
4718 Beware: after this function returns, C<ptr> and SvPVX_const(sv) may no longer
4719 refer to the same chunk of data.
4725 Perl_sv_chop(pTHX_ register SV *sv, register const char *ptr)
4727 register STRLEN delta;
4728 if (!ptr || !SvPOKp(sv))
4730 delta = ptr - SvPVX_const(sv);
4731 SV_CHECK_THINKFIRST(sv);
4732 if (SvTYPE(sv) < SVt_PVIV)
4733 sv_upgrade(sv,SVt_PVIV);
4736 if (!SvLEN(sv)) { /* make copy of shared string */
4737 const char *pvx = SvPVX_const(sv);
4738 const STRLEN len = SvCUR(sv);
4739 SvGROW(sv, len + 1);
4740 Move(pvx,SvPVX_const(sv),len,char);
4744 /* Same SvOOK_on but SvOOK_on does a SvIOK_off
4745 and we do that anyway inside the SvNIOK_off
4747 SvFLAGS(sv) |= SVf_OOK;
4750 SvLEN_set(sv, SvLEN(sv) - delta);
4751 SvCUR_set(sv, SvCUR(sv) - delta);
4752 SvPV_set(sv, SvPVX(sv) + delta);
4753 SvIV_set(sv, SvIVX(sv) + delta);
4756 /* sv_catpvn() is now a macro using Perl_sv_catpvn_flags();
4757 * this function provided for binary compatibility only
4761 Perl_sv_catpvn(pTHX_ SV *dsv, const char* sstr, STRLEN slen)
4763 sv_catpvn_flags(dsv, sstr, slen, SV_GMAGIC);
4767 =for apidoc sv_catpvn
4769 Concatenates the string onto the end of the string which is in the SV. The
4770 C<len> indicates number of bytes to copy. If the SV has the UTF-8
4771 status set, then the bytes appended should be valid UTF-8.
4772 Handles 'get' magic, but not 'set' magic. See C<sv_catpvn_mg>.
4774 =for apidoc sv_catpvn_flags
4776 Concatenates the string onto the end of the string which is in the SV. The
4777 C<len> indicates number of bytes to copy. If the SV has the UTF-8
4778 status set, then the bytes appended should be valid UTF-8.
4779 If C<flags> has C<SV_GMAGIC> bit set, will C<mg_get> on C<dsv> if
4780 appropriate, else not. C<sv_catpvn> and C<sv_catpvn_nomg> are implemented
4781 in terms of this function.
4787 Perl_sv_catpvn_flags(pTHX_ register SV *dsv, register const char *sstr, register STRLEN slen, I32 flags)
4790 const char *dstr = SvPV_force_flags(dsv, dlen, flags);
4792 SvGROW(dsv, dlen + slen + 1);
4794 sstr = SvPVX_const(dsv);
4795 Move(sstr, SvPVX(dsv) + dlen, slen, char);
4796 SvCUR_set(dsv, SvCUR(dsv) + slen);
4798 (void)SvPOK_only_UTF8(dsv); /* validate pointer */
4803 =for apidoc sv_catpvn_mg
4805 Like C<sv_catpvn>, but also handles 'set' magic.
4811 Perl_sv_catpvn_mg(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
4813 sv_catpvn(sv,ptr,len);
4817 /* sv_catsv() is now a macro using Perl_sv_catsv_flags();
4818 * this function provided for binary compatibility only
4822 Perl_sv_catsv(pTHX_ SV *dstr, register SV *sstr)
4824 sv_catsv_flags(dstr, sstr, SV_GMAGIC);
4828 =for apidoc sv_catsv
4830 Concatenates the string from SV C<ssv> onto the end of the string in
4831 SV C<dsv>. Modifies C<dsv> but not C<ssv>. Handles 'get' magic, but
4832 not 'set' magic. See C<sv_catsv_mg>.
4834 =for apidoc sv_catsv_flags
4836 Concatenates the string from SV C<ssv> onto the end of the string in
4837 SV C<dsv>. Modifies C<dsv> but not C<ssv>. If C<flags> has C<SV_GMAGIC>
4838 bit set, will C<mg_get> on the SVs if appropriate, else not. C<sv_catsv>
4839 and C<sv_catsv_nomg> are implemented in terms of this function.
4844 Perl_sv_catsv_flags(pTHX_ SV *dsv, register SV *ssv, I32 flags)
4850 if ((spv = SvPV_const(ssv, slen))) {
4851 /* sutf8 and dutf8 were type bool, but under USE_ITHREADS,
4852 gcc version 2.95.2 20000220 (Debian GNU/Linux) for
4853 Linux xxx 2.2.17 on sparc64 with gcc -O2, we erroneously
4854 get dutf8 = 0x20000000, (i.e. SVf_UTF8) even though
4855 dsv->sv_flags doesn't have that bit set.
4856 Andy Dougherty 12 Oct 2001
4858 const I32 sutf8 = DO_UTF8(ssv);
4861 if (SvGMAGICAL(dsv) && (flags & SV_GMAGIC))
4863 dutf8 = DO_UTF8(dsv);
4865 if (dutf8 != sutf8) {
4867 /* Not modifying source SV, so taking a temporary copy. */
4868 SV* csv = sv_2mortal(newSVpvn(spv, slen));
4870 sv_utf8_upgrade(csv);
4871 spv = SvPV_const(csv, slen);
4874 sv_utf8_upgrade_nomg(dsv);
4876 sv_catpvn_nomg(dsv, spv, slen);
4881 =for apidoc sv_catsv_mg
4883 Like C<sv_catsv>, but also handles 'set' magic.
4889 Perl_sv_catsv_mg(pTHX_ SV *dsv, register SV *ssv)
4896 =for apidoc sv_catpv
4898 Concatenates the string onto the end of the string which is in the SV.
4899 If the SV has the UTF-8 status set, then the bytes appended should be
4900 valid UTF-8. Handles 'get' magic, but not 'set' magic. See C<sv_catpv_mg>.
4905 Perl_sv_catpv(pTHX_ register SV *sv, register const char *ptr)
4907 register STRLEN len;
4913 junk = SvPV_force(sv, tlen);
4915 SvGROW(sv, tlen + len + 1);
4917 ptr = SvPVX_const(sv);
4918 Move(ptr,SvPVX(sv)+tlen,len+1,char);
4919 SvCUR_set(sv, SvCUR(sv) + len);
4920 (void)SvPOK_only_UTF8(sv); /* validate pointer */
4925 =for apidoc sv_catpv_mg
4927 Like C<sv_catpv>, but also handles 'set' magic.
4933 Perl_sv_catpv_mg(pTHX_ register SV *sv, register const char *ptr)
4942 Create a new null SV, or if len > 0, create a new empty SVt_PV type SV
4943 with an initial PV allocation of len+1. Normally accessed via the C<NEWSV>
4950 Perl_newSV(pTHX_ STRLEN len)
4956 sv_upgrade(sv, SVt_PV);
4957 SvGROW(sv, len + 1);
4962 =for apidoc sv_magicext
4964 Adds magic to an SV, upgrading it if necessary. Applies the
4965 supplied vtable and returns a pointer to the magic added.
4967 Note that C<sv_magicext> will allow things that C<sv_magic> will not.
4968 In particular, you can add magic to SvREADONLY SVs, and add more than
4969 one instance of the same 'how'.
4971 If C<namlen> is greater than zero then a C<savepvn> I<copy> of C<name> is
4972 stored, if C<namlen> is zero then C<name> is stored as-is and - as another
4973 special case - if C<(name && namlen == HEf_SVKEY)> then C<name> is assumed
4974 to contain an C<SV*> and is stored as-is with its REFCNT incremented.
4976 (This is now used as a subroutine by C<sv_magic>.)
4981 Perl_sv_magicext(pTHX_ SV* sv, SV* obj, int how, const MGVTBL *vtable,
4982 const char* name, I32 namlen)
4986 if (SvTYPE(sv) < SVt_PVMG) {
4987 SvUPGRADE(sv, SVt_PVMG);
4989 Newz(702,mg, 1, MAGIC);
4990 mg->mg_moremagic = SvMAGIC(sv);
4991 SvMAGIC_set(sv, mg);
4993 /* Sometimes a magic contains a reference loop, where the sv and
4994 object refer to each other. To prevent a reference loop that
4995 would prevent such objects being freed, we look for such loops
4996 and if we find one we avoid incrementing the object refcount.
4998 Note we cannot do this to avoid self-tie loops as intervening RV must
4999 have its REFCNT incremented to keep it in existence.
5002 if (!obj || obj == sv ||
5003 how == PERL_MAGIC_arylen ||
5004 how == PERL_MAGIC_qr ||
5005 how == PERL_MAGIC_symtab ||
5006 (SvTYPE(obj) == SVt_PVGV &&
5007 (GvSV(obj) == sv || GvHV(obj) == (HV*)sv || GvAV(obj) == (AV*)sv ||
5008 GvCV(obj) == (CV*)sv || GvIOp(obj) == (IO*)sv ||
5009 GvFORM(obj) == (CV*)sv)))
5014 mg->mg_obj = SvREFCNT_inc(obj);
5015 mg->mg_flags |= MGf_REFCOUNTED;
5018 /* Normal self-ties simply pass a null object, and instead of
5019 using mg_obj directly, use the SvTIED_obj macro to produce a
5020 new RV as needed. For glob "self-ties", we are tieing the PVIO
5021 with an RV obj pointing to the glob containing the PVIO. In
5022 this case, to avoid a reference loop, we need to weaken the
5026 if (how == PERL_MAGIC_tiedscalar && SvTYPE(sv) == SVt_PVIO &&
5027 obj && SvROK(obj) && GvIO(SvRV(obj)) == (IO*)sv)
5033 mg->mg_len = namlen;
5036 mg->mg_ptr = savepvn(name, namlen);
5037 else if (namlen == HEf_SVKEY)
5038 mg->mg_ptr = (char*)SvREFCNT_inc((SV*)name);
5040 mg->mg_ptr = (char *) name;
5042 mg->mg_virtual = vtable;
5046 SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK|SVf_POK);
5051 =for apidoc sv_magic
5053 Adds magic to an SV. First upgrades C<sv> to type C<SVt_PVMG> if necessary,
5054 then adds a new magic item of type C<how> to the head of the magic list.
5056 See C<sv_magicext> (which C<sv_magic> now calls) for a description of the
5057 handling of the C<name> and C<namlen> arguments.
5059 You need to use C<sv_magicext> to add magic to SvREADONLY SVs and also
5060 to add more than one instance of the same 'how'.
5066 Perl_sv_magic(pTHX_ register SV *sv, SV *obj, int how, const char *name, I32 namlen)
5068 const MGVTBL *vtable = 0;
5071 #ifdef PERL_OLD_COPY_ON_WRITE
5073 sv_force_normal_flags(sv, 0);
5075 if (SvREADONLY(sv)) {
5077 && how != PERL_MAGIC_regex_global
5078 && how != PERL_MAGIC_bm
5079 && how != PERL_MAGIC_fm
5080 && how != PERL_MAGIC_sv
5081 && how != PERL_MAGIC_backref
5084 Perl_croak(aTHX_ PL_no_modify);
5087 if (SvMAGICAL(sv) || (how == PERL_MAGIC_taint && SvTYPE(sv) >= SVt_PVMG)) {
5088 if (SvMAGIC(sv) && (mg = mg_find(sv, how))) {
5089 /* sv_magic() refuses to add a magic of the same 'how' as an
5092 if (how == PERL_MAGIC_taint)
5100 vtable = &PL_vtbl_sv;
5102 case PERL_MAGIC_overload:
5103 vtable = &PL_vtbl_amagic;
5105 case PERL_MAGIC_overload_elem:
5106 vtable = &PL_vtbl_amagicelem;
5108 case PERL_MAGIC_overload_table:
5109 vtable = &PL_vtbl_ovrld;
5112 vtable = &PL_vtbl_bm;
5114 case PERL_MAGIC_regdata:
5115 vtable = &PL_vtbl_regdata;
5117 case PERL_MAGIC_regdatum:
5118 vtable = &PL_vtbl_regdatum;
5120 case PERL_MAGIC_env:
5121 vtable = &PL_vtbl_env;
5124 vtable = &PL_vtbl_fm;
5126 case PERL_MAGIC_envelem:
5127 vtable = &PL_vtbl_envelem;
5129 case PERL_MAGIC_regex_global:
5130 vtable = &PL_vtbl_mglob;
5132 case PERL_MAGIC_isa:
5133 vtable = &PL_vtbl_isa;
5135 case PERL_MAGIC_isaelem:
5136 vtable = &PL_vtbl_isaelem;
5138 case PERL_MAGIC_nkeys:
5139 vtable = &PL_vtbl_nkeys;
5141 case PERL_MAGIC_dbfile:
5144 case PERL_MAGIC_dbline:
5145 vtable = &PL_vtbl_dbline;
5147 #ifdef USE_LOCALE_COLLATE
5148 case PERL_MAGIC_collxfrm:
5149 vtable = &PL_vtbl_collxfrm;
5151 #endif /* USE_LOCALE_COLLATE */
5152 case PERL_MAGIC_tied:
5153 vtable = &PL_vtbl_pack;
5155 case PERL_MAGIC_tiedelem:
5156 case PERL_MAGIC_tiedscalar:
5157 vtable = &PL_vtbl_packelem;
5160 vtable = &PL_vtbl_regexp;
5162 case PERL_MAGIC_sig:
5163 vtable = &PL_vtbl_sig;
5165 case PERL_MAGIC_sigelem:
5166 vtable = &PL_vtbl_sigelem;
5168 case PERL_MAGIC_taint:
5169 vtable = &PL_vtbl_taint;
5171 case PERL_MAGIC_uvar:
5172 vtable = &PL_vtbl_uvar;
5174 case PERL_MAGIC_vec:
5175 vtable = &PL_vtbl_vec;
5177 case PERL_MAGIC_arylen_p:
5178 case PERL_MAGIC_rhash:
5179 case PERL_MAGIC_symtab:
5180 case PERL_MAGIC_vstring:
5183 case PERL_MAGIC_utf8:
5184 vtable = &PL_vtbl_utf8;
5186 case PERL_MAGIC_substr:
5187 vtable = &PL_vtbl_substr;
5189 case PERL_MAGIC_defelem:
5190 vtable = &PL_vtbl_defelem;
5192 case PERL_MAGIC_glob:
5193 vtable = &PL_vtbl_glob;
5195 case PERL_MAGIC_arylen:
5196 vtable = &PL_vtbl_arylen;
5198 case PERL_MAGIC_pos:
5199 vtable = &PL_vtbl_pos;
5201 case PERL_MAGIC_backref:
5202 vtable = &PL_vtbl_backref;
5204 case PERL_MAGIC_ext:
5205 /* Reserved for use by extensions not perl internals. */
5206 /* Useful for attaching extension internal data to perl vars. */
5207 /* Note that multiple extensions may clash if magical scalars */
5208 /* etc holding private data from one are passed to another. */
5211 Perl_croak(aTHX_ "Don't know how to handle magic of type \\%o", how);
5214 /* Rest of work is done else where */
5215 mg = sv_magicext(sv,obj,how,(MGVTBL*)vtable,name,namlen);
5218 case PERL_MAGIC_taint:
5221 case PERL_MAGIC_ext:
5222 case PERL_MAGIC_dbfile:
5229 =for apidoc sv_unmagic
5231 Removes all magic of type C<type> from an SV.
5237 Perl_sv_unmagic(pTHX_ SV *sv, int type)
5241 if (SvTYPE(sv) < SVt_PVMG || !SvMAGIC(sv))
5244 for (mg = *mgp; mg; mg = *mgp) {
5245 if (mg->mg_type == type) {
5246 const MGVTBL* const vtbl = mg->mg_virtual;
5247 *mgp = mg->mg_moremagic;
5248 if (vtbl && vtbl->svt_free)
5249 CALL_FPTR(vtbl->svt_free)(aTHX_ sv, mg);
5250 if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) {
5252 Safefree(mg->mg_ptr);
5253 else if (mg->mg_len == HEf_SVKEY)
5254 SvREFCNT_dec((SV*)mg->mg_ptr);
5255 else if (mg->mg_type == PERL_MAGIC_utf8 && mg->mg_ptr)
5256 Safefree(mg->mg_ptr);
5258 if (mg->mg_flags & MGf_REFCOUNTED)
5259 SvREFCNT_dec(mg->mg_obj);
5263 mgp = &mg->mg_moremagic;
5267 SvFLAGS(sv) |= (SvFLAGS(sv) & (SVp_NOK|SVp_POK)) >> PRIVSHIFT;
5274 =for apidoc sv_rvweaken
5276 Weaken a reference: set the C<SvWEAKREF> flag on this RV; give the
5277 referred-to SV C<PERL_MAGIC_backref> magic if it hasn't already; and
5278 push a back-reference to this RV onto the array of backreferences
5279 associated with that magic.
5285 Perl_sv_rvweaken(pTHX_ SV *sv)
5288 if (!SvOK(sv)) /* let undefs pass */
5291 Perl_croak(aTHX_ "Can't weaken a nonreference");
5292 else if (SvWEAKREF(sv)) {
5293 if (ckWARN(WARN_MISC))
5294 Perl_warner(aTHX_ packWARN(WARN_MISC), "Reference is already weak");
5298 sv_add_backref(tsv, sv);
5304 /* Give tsv backref magic if it hasn't already got it, then push a
5305 * back-reference to sv onto the array associated with the backref magic.
5309 S_sv_add_backref(pTHX_ SV *tsv, SV *sv)
5313 if (SvMAGICAL(tsv) && (mg = mg_find(tsv, PERL_MAGIC_backref)))
5314 av = (AV*)mg->mg_obj;
5317 sv_magic(tsv, (SV*)av, PERL_MAGIC_backref, NULL, 0);
5318 /* av now has a refcnt of 2, which avoids it getting freed
5319 * before us during global cleanup. The extra ref is removed
5320 * by magic_killbackrefs() when tsv is being freed */
5322 if (AvFILLp(av) >= AvMAX(av)) {
5324 SV **svp = AvARRAY(av);
5325 for (i = AvFILLp(av); i >= 0; i--)
5327 svp[i] = sv; /* reuse the slot */
5330 av_extend(av, AvFILLp(av)+1);
5332 AvARRAY(av)[++AvFILLp(av)] = sv; /* av_push() */
5335 /* delete a back-reference to ourselves from the backref magic associated
5336 * with the SV we point to.
5340 S_sv_del_backref(pTHX_ SV *sv)
5347 if (!SvMAGICAL(tsv) || !(mg = mg_find(tsv, PERL_MAGIC_backref)))
5348 Perl_croak(aTHX_ "panic: del_backref");
5349 av = (AV *)mg->mg_obj;
5351 for (i = AvFILLp(av); i >= 0; i--)
5352 if (svp[i] == sv) svp[i] = Nullsv;
5356 =for apidoc sv_insert
5358 Inserts a string at the specified offset/length within the SV. Similar to
5359 the Perl substr() function.
5365 Perl_sv_insert(pTHX_ SV *bigstr, STRLEN offset, STRLEN len, const char *little, STRLEN littlelen)
5369 register char *midend;
5370 register char *bigend;
5376 Perl_croak(aTHX_ "Can't modify non-existent substring");
5377 SvPV_force(bigstr, curlen);
5378 (void)SvPOK_only_UTF8(bigstr);
5379 if (offset + len > curlen) {
5380 SvGROW(bigstr, offset+len+1);
5381 Zero(SvPVX(bigstr)+curlen, offset+len-curlen, char);
5382 SvCUR_set(bigstr, offset+len);
5386 i = littlelen - len;
5387 if (i > 0) { /* string might grow */
5388 big = SvGROW(bigstr, SvCUR(bigstr) + i + 1);
5389 mid = big + offset + len;
5390 midend = bigend = big + SvCUR(bigstr);
5393 while (midend > mid) /* shove everything down */
5394 *--bigend = *--midend;
5395 Move(little,big+offset,littlelen,char);
5396 SvCUR_set(bigstr, SvCUR(bigstr) + i);
5401 Move(little,SvPVX(bigstr)+offset,len,char);
5406 big = SvPVX(bigstr);
5409 bigend = big + SvCUR(bigstr);
5411 if (midend > bigend)
5412 Perl_croak(aTHX_ "panic: sv_insert");
5414 if (mid - big > bigend - midend) { /* faster to shorten from end */
5416 Move(little, mid, littlelen,char);
5419 i = bigend - midend;
5421 Move(midend, mid, i,char);
5425 SvCUR_set(bigstr, mid - big);
5427 else if ((i = mid - big)) { /* faster from front */
5428 midend -= littlelen;
5430 sv_chop(bigstr,midend-i);
5435 Move(little, mid, littlelen,char);
5437 else if (littlelen) {
5438 midend -= littlelen;
5439 sv_chop(bigstr,midend);
5440 Move(little,midend,littlelen,char);
5443 sv_chop(bigstr,midend);
5449 =for apidoc sv_replace
5451 Make the first argument a copy of the second, then delete the original.
5452 The target SV physically takes over ownership of the body of the source SV
5453 and inherits its flags; however, the target keeps any magic it owns,
5454 and any magic in the source is discarded.
5455 Note that this is a rather specialist SV copying operation; most of the
5456 time you'll want to use C<sv_setsv> or one of its many macro front-ends.
5462 Perl_sv_replace(pTHX_ register SV *sv, register SV *nsv)
5464 const U32 refcnt = SvREFCNT(sv);
5465 SV_CHECK_THINKFIRST_COW_DROP(sv);
5466 if (SvREFCNT(nsv) != 1 && ckWARN_d(WARN_INTERNAL))
5467 Perl_warner(aTHX_ packWARN(WARN_INTERNAL), "Reference miscount in sv_replace()");
5468 if (SvMAGICAL(sv)) {
5472 sv_upgrade(nsv, SVt_PVMG);
5473 SvMAGIC_set(nsv, SvMAGIC(sv));
5474 SvFLAGS(nsv) |= SvMAGICAL(sv);
5476 SvMAGIC_set(sv, NULL);
5480 assert(!SvREFCNT(sv));
5481 #ifdef DEBUG_LEAKING_SCALARS
5482 sv->sv_flags = nsv->sv_flags;
5483 sv->sv_any = nsv->sv_any;
5484 sv->sv_refcnt = nsv->sv_refcnt;
5485 sv->sv_u = nsv->sv_u;
5487 StructCopy(nsv,sv,SV);
5489 /* Currently could join these into one piece of pointer arithmetic, but
5490 it would be unclear. */
5491 if(SvTYPE(sv) == SVt_IV)
5493 = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
5494 else if (SvTYPE(sv) == SVt_RV) {
5495 SvANY(sv) = &sv->sv_u.svu_rv;
5499 #ifdef PERL_OLD_COPY_ON_WRITE
5500 if (SvIsCOW_normal(nsv)) {
5501 /* We need to follow the pointers around the loop to make the
5502 previous SV point to sv, rather than nsv. */
5505 while ((next = SV_COW_NEXT_SV(current)) != nsv) {
5508 assert(SvPVX_const(current) == SvPVX_const(nsv));
5510 /* Make the SV before us point to the SV after us. */
5512 PerlIO_printf(Perl_debug_log, "previous is\n");
5514 PerlIO_printf(Perl_debug_log,
5515 "move it from 0x%"UVxf" to 0x%"UVxf"\n",
5516 (UV) SV_COW_NEXT_SV(current), (UV) sv);
5518 SV_COW_NEXT_SV_SET(current, sv);
5521 SvREFCNT(sv) = refcnt;
5522 SvFLAGS(nsv) |= SVTYPEMASK; /* Mark as freed */
5528 =for apidoc sv_clear
5530 Clear an SV: call any destructors, free up any memory used by the body,
5531 and free the body itself. The SV's head is I<not> freed, although
5532 its type is set to all 1's so that it won't inadvertently be assumed
5533 to be live during global destruction etc.
5534 This function should only be called when REFCNT is zero. Most of the time
5535 you'll want to call C<sv_free()> (or its macro wrapper C<SvREFCNT_dec>)
5542 Perl_sv_clear(pTHX_ register SV *sv)
5547 assert(SvREFCNT(sv) == 0);
5550 if (PL_defstash) { /* Still have a symbol table? */
5554 stash = SvSTASH(sv);
5555 destructor = StashHANDLER(stash,DESTROY);
5557 SV* tmpref = newRV(sv);
5558 SvREADONLY_on(tmpref); /* DESTROY() could be naughty */
5560 PUSHSTACKi(PERLSI_DESTROY);
5565 call_sv((SV*)destructor, G_DISCARD|G_EVAL|G_KEEPERR|G_VOID);
5571 if(SvREFCNT(tmpref) < 2) {
5572 /* tmpref is not kept alive! */
5574 SvRV_set(tmpref, NULL);
5577 SvREFCNT_dec(tmpref);
5579 } while (SvOBJECT(sv) && SvSTASH(sv) != stash);
5583 if (PL_in_clean_objs)
5584 Perl_croak(aTHX_ "DESTROY created new reference to dead object '%s'",
5586 /* DESTROY gave object new lease on life */
5592 SvREFCNT_dec(SvSTASH(sv)); /* possibly of changed persuasion */
5593 SvOBJECT_off(sv); /* Curse the object. */
5594 if (SvTYPE(sv) != SVt_PVIO)
5595 --PL_sv_objcount; /* XXX Might want something more general */
5598 if (SvTYPE(sv) >= SVt_PVMG) {
5601 if (SvTYPE(sv) == SVt_PVMG && SvFLAGS(sv) & SVpad_TYPED)
5602 SvREFCNT_dec(SvSTASH(sv));
5605 switch (SvTYPE(sv)) {
5608 IoIFP(sv) != PerlIO_stdin() &&
5609 IoIFP(sv) != PerlIO_stdout() &&
5610 IoIFP(sv) != PerlIO_stderr())
5612 io_close((IO*)sv, FALSE);
5614 if (IoDIRP(sv) && !(IoFLAGS(sv) & IOf_FAKE_DIRP))
5615 PerlDir_close(IoDIRP(sv));
5616 IoDIRP(sv) = (DIR*)NULL;
5617 Safefree(IoTOP_NAME(sv));
5618 Safefree(IoFMT_NAME(sv));
5619 Safefree(IoBOTTOM_NAME(sv));
5634 if (LvTYPE(sv) == 'T') { /* for tie: return HE to pool */
5635 SvREFCNT_dec(HeKEY_sv((HE*)LvTARG(sv)));
5636 HeNEXT((HE*)LvTARG(sv)) = PL_hv_fetch_ent_mh;
5637 PL_hv_fetch_ent_mh = (HE*)LvTARG(sv);
5639 else if (LvTYPE(sv) != 't') /* unless tie: unrefcnted fake SV** */
5640 SvREFCNT_dec(LvTARG(sv));
5644 Safefree(GvNAME(sv));
5645 /* cannot decrease stash refcount yet, as we might recursively delete
5646 ourselves when the refcnt drops to zero. Delay SvREFCNT_dec
5647 of stash until current sv is completely gone.
5648 -- JohnPC, 27 Mar 1998 */
5649 stash = GvSTASH(sv);
5655 /* Don't bother with SvOOK_off(sv); as we're only going to free it. */
5657 SvPV_set(sv, SvPVX_mutable(sv) - SvIVX(sv));
5658 /* Don't even bother with turning off the OOK flag. */
5667 SvREFCNT_dec(SvRV(sv));
5669 #ifdef PERL_OLD_COPY_ON_WRITE
5670 else if (SvPVX_const(sv)) {
5672 /* I believe I need to grab the global SV mutex here and
5673 then recheck the COW status. */
5675 PerlIO_printf(Perl_debug_log, "Copy on write: clear\n");
5678 sv_release_COW(sv, SvPVX_const(sv), SvLEN(sv),
5679 SV_COW_NEXT_SV(sv));
5680 /* And drop it here. */
5682 } else if (SvLEN(sv)) {
5683 Safefree(SvPVX_const(sv));
5687 else if (SvPVX_const(sv) && SvLEN(sv))
5688 Safefree(SvPVX_const(sv));
5689 else if (SvPVX_const(sv) && SvREADONLY(sv) && SvFAKE(sv)) {
5690 unshare_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sv)));
5703 switch (SvTYPE(sv)) {
5717 del_XPVIV(SvANY(sv));
5720 del_XPVNV(SvANY(sv));
5723 del_XPVMG(SvANY(sv));
5726 del_XPVLV(SvANY(sv));
5729 del_XPVAV(SvANY(sv));
5732 del_XPVHV(SvANY(sv));
5735 del_XPVCV(SvANY(sv));
5738 del_XPVGV(SvANY(sv));
5739 /* code duplication for increased performance. */
5740 SvFLAGS(sv) &= SVf_BREAK;
5741 SvFLAGS(sv) |= SVTYPEMASK;
5742 /* decrease refcount of the stash that owns this GV, if any */
5744 SvREFCNT_dec(stash);
5745 return; /* not break, SvFLAGS reset already happened */
5747 del_XPVBM(SvANY(sv));
5750 del_XPVFM(SvANY(sv));
5753 del_XPVIO(SvANY(sv));
5756 SvFLAGS(sv) &= SVf_BREAK;
5757 SvFLAGS(sv) |= SVTYPEMASK;
5761 =for apidoc sv_newref
5763 Increment an SV's reference count. Use the C<SvREFCNT_inc()> wrapper
5770 Perl_sv_newref(pTHX_ SV *sv)
5780 Decrement an SV's reference count, and if it drops to zero, call
5781 C<sv_clear> to invoke destructors and free up any memory used by
5782 the body; finally, deallocate the SV's head itself.
5783 Normally called via a wrapper macro C<SvREFCNT_dec>.
5789 Perl_sv_free(pTHX_ SV *sv)
5794 if (SvREFCNT(sv) == 0) {
5795 if (SvFLAGS(sv) & SVf_BREAK)
5796 /* this SV's refcnt has been artificially decremented to
5797 * trigger cleanup */
5799 if (PL_in_clean_all) /* All is fair */
5801 if (SvREADONLY(sv) && SvIMMORTAL(sv)) {
5802 /* make sure SvREFCNT(sv)==0 happens very seldom */
5803 SvREFCNT(sv) = (~(U32)0)/2;
5806 if (ckWARN_d(WARN_INTERNAL))
5807 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
5808 "Attempt to free unreferenced scalar: SV 0x%"UVxf
5809 pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
5812 if (--(SvREFCNT(sv)) > 0)
5814 Perl_sv_free2(aTHX_ sv);
5818 Perl_sv_free2(pTHX_ SV *sv)
5823 if (ckWARN_d(WARN_DEBUGGING))
5824 Perl_warner(aTHX_ packWARN(WARN_DEBUGGING),
5825 "Attempt to free temp prematurely: SV 0x%"UVxf
5826 pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
5830 if (SvREADONLY(sv) && SvIMMORTAL(sv)) {
5831 /* make sure SvREFCNT(sv)==0 happens very seldom */
5832 SvREFCNT(sv) = (~(U32)0)/2;
5843 Returns the length of the string in the SV. Handles magic and type
5844 coercion. See also C<SvCUR>, which gives raw access to the xpv_cur slot.
5850 Perl_sv_len(pTHX_ register SV *sv)
5858 len = mg_length(sv);
5860 (void)SvPV_const(sv, len);
5865 =for apidoc sv_len_utf8
5867 Returns the number of characters in the string in an SV, counting wide
5868 UTF-8 bytes as a single character. Handles magic and type coercion.
5874 * The length is cached in PERL_UTF8_magic, in the mg_len field. Also the
5875 * mg_ptr is used, by sv_pos_u2b(), see the comments of S_utf8_mg_pos_init().
5876 * (Note that the mg_len is not the length of the mg_ptr field.)
5881 Perl_sv_len_utf8(pTHX_ register SV *sv)
5887 return mg_length(sv);
5891 const U8 *s = (U8*)SvPV_const(sv, len);
5892 MAGIC *mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : 0;
5894 if (mg && mg->mg_len != -1 && (mg->mg_len > 0 || len == 0)) {
5896 #ifdef PERL_UTF8_CACHE_ASSERT
5897 assert(ulen == Perl_utf8_length(aTHX_ s, s + len));
5901 ulen = Perl_utf8_length(aTHX_ s, s + len);
5902 if (!mg && !SvREADONLY(sv)) {
5903 sv_magic(sv, 0, PERL_MAGIC_utf8, 0, 0);
5904 mg = mg_find(sv, PERL_MAGIC_utf8);
5914 /* S_utf8_mg_pos_init() is used to initialize the mg_ptr field of
5915 * a PERL_UTF8_magic. The mg_ptr is used to store the mapping
5916 * between UTF-8 and byte offsets. There are two (substr offset and substr
5917 * length, the i offset, PERL_MAGIC_UTF8_CACHESIZE) times two (UTF-8 offset
5918 * and byte offset) cache positions.
5920 * The mg_len field is used by sv_len_utf8(), see its comments.
5921 * Note that the mg_len is not the length of the mg_ptr field.
5925 S_utf8_mg_pos_init(pTHX_ SV *sv, MAGIC **mgp, STRLEN **cachep, I32 i,
5926 I32 offsetp, const U8 *s, const U8 *start)
5930 if (SvMAGICAL(sv) && !SvREADONLY(sv)) {
5932 *mgp = sv_magicext(sv, 0, PERL_MAGIC_utf8, (MGVTBL*)&PL_vtbl_utf8, 0, 0);
5936 *cachep = (STRLEN *) (*mgp)->mg_ptr;
5938 Newz(0, *cachep, PERL_MAGIC_UTF8_CACHESIZE * 2, STRLEN);
5939 (*mgp)->mg_ptr = (char *) *cachep;
5943 (*cachep)[i] = offsetp;
5944 (*cachep)[i+1] = s - start;
5952 * S_utf8_mg_pos() is used to query and update mg_ptr field of
5953 * a PERL_UTF8_magic. The mg_ptr is used to store the mapping
5954 * between UTF-8 and byte offsets. See also the comments of
5955 * S_utf8_mg_pos_init().
5959 S_utf8_mg_pos(pTHX_ SV *sv, MAGIC **mgp, STRLEN **cachep, I32 i, I32 *offsetp, I32 uoff, const U8 **sp, const U8 *start, const U8 *send)
5963 if (SvMAGICAL(sv) && !SvREADONLY(sv)) {
5965 *mgp = mg_find(sv, PERL_MAGIC_utf8);
5966 if (*mgp && (*mgp)->mg_ptr) {
5967 *cachep = (STRLEN *) (*mgp)->mg_ptr;
5968 ASSERT_UTF8_CACHE(*cachep);
5969 if ((*cachep)[i] == (STRLEN)uoff) /* An exact match. */
5971 else { /* We will skip to the right spot. */
5976 /* The assumption is that going backward is half
5977 * the speed of going forward (that's where the
5978 * 2 * backw in the below comes from). (The real
5979 * figure of course depends on the UTF-8 data.) */
5981 if ((*cachep)[i] > (STRLEN)uoff) {
5983 backw = (*cachep)[i] - (STRLEN)uoff;
5985 if (forw < 2 * backw)
5988 p = start + (*cachep)[i+1];
5990 /* Try this only for the substr offset (i == 0),
5991 * not for the substr length (i == 2). */
5992 else if (i == 0) { /* (*cachep)[i] < uoff */
5993 const STRLEN ulen = sv_len_utf8(sv);
5995 if ((STRLEN)uoff < ulen) {
5996 forw = (STRLEN)uoff - (*cachep)[i];
5997 backw = ulen - (STRLEN)uoff;
5999 if (forw < 2 * backw)
6000 p = start + (*cachep)[i+1];
6005 /* If the string is not long enough for uoff,
6006 * we could extend it, but not at this low a level. */
6010 if (forw < 2 * backw) {
6017 while (UTF8_IS_CONTINUATION(*p))
6022 /* Update the cache. */
6023 (*cachep)[i] = (STRLEN)uoff;
6024 (*cachep)[i+1] = p - start;
6026 /* Drop the stale "length" cache */
6035 if (found) { /* Setup the return values. */
6036 *offsetp = (*cachep)[i+1];
6037 *sp = start + *offsetp;
6040 *offsetp = send - start;
6042 else if (*sp < start) {
6048 #ifdef PERL_UTF8_CACHE_ASSERT
6053 while (n-- && s < send)
6057 assert(*offsetp == s - start);
6058 assert((*cachep)[0] == (STRLEN)uoff);
6059 assert((*cachep)[1] == *offsetp);
6061 ASSERT_UTF8_CACHE(*cachep);
6070 =for apidoc sv_pos_u2b
6072 Converts the value pointed to by offsetp from a count of UTF-8 chars from
6073 the start of the string, to a count of the equivalent number of bytes; if
6074 lenp is non-zero, it does the same to lenp, but this time starting from
6075 the offset, rather than from the start of the string. Handles magic and
6082 * sv_pos_u2b() uses, like sv_pos_b2u(), the mg_ptr of the potential
6083 * PERL_UTF8_magic of the sv to store the mapping between UTF-8 and
6084 * byte offsets. See also the comments of S_utf8_mg_pos().
6089 Perl_sv_pos_u2b(pTHX_ register SV *sv, I32* offsetp, I32* lenp)
6097 start = (U8*)SvPV_const(sv, len);
6101 const U8 *s = start;
6102 I32 uoffset = *offsetp;
6103 const U8 *send = s + len;
6107 if (utf8_mg_pos(sv, &mg, &cache, 0, offsetp, *offsetp, &s, start, send))
6109 if (!found && uoffset > 0) {
6110 while (s < send && uoffset--)
6114 if (utf8_mg_pos_init(sv, &mg, &cache, 0, *offsetp, s, start))
6116 *offsetp = s - start;
6121 if (utf8_mg_pos(sv, &mg, &cache, 2, lenp, *lenp, &s, start, send)) {
6125 if (!found && *lenp > 0) {
6128 while (s < send && ulen--)
6132 utf8_mg_pos_init(sv, &mg, &cache, 2, *lenp, s, start);
6136 ASSERT_UTF8_CACHE(cache);
6148 =for apidoc sv_pos_b2u
6150 Converts the value pointed to by offsetp from a count of bytes from the
6151 start of the string, to a count of the equivalent number of UTF-8 chars.
6152 Handles magic and type coercion.
6158 * sv_pos_b2u() uses, like sv_pos_u2b(), the mg_ptr of the potential
6159 * PERL_UTF8_magic of the sv to store the mapping between UTF-8 and
6160 * byte offsets. See also the comments of S_utf8_mg_pos().
6165 Perl_sv_pos_b2u(pTHX_ register SV* sv, I32* offsetp)
6173 s = (const U8*)SvPV_const(sv, len);
6174 if ((I32)len < *offsetp)
6175 Perl_croak(aTHX_ "panic: sv_pos_b2u: bad byte offset");
6177 const U8* send = s + *offsetp;
6179 STRLEN *cache = NULL;
6183 if (SvMAGICAL(sv) && !SvREADONLY(sv)) {
6184 mg = mg_find(sv, PERL_MAGIC_utf8);
6185 if (mg && mg->mg_ptr) {
6186 cache = (STRLEN *) mg->mg_ptr;
6187 if (cache[1] == (STRLEN)*offsetp) {
6188 /* An exact match. */
6189 *offsetp = cache[0];
6193 else if (cache[1] < (STRLEN)*offsetp) {
6194 /* We already know part of the way. */
6197 /* Let the below loop do the rest. */
6199 else { /* cache[1] > *offsetp */
6200 /* We already know all of the way, now we may
6201 * be able to walk back. The same assumption
6202 * is made as in S_utf8_mg_pos(), namely that
6203 * walking backward is twice slower than
6204 * walking forward. */
6205 STRLEN forw = *offsetp;
6206 STRLEN backw = cache[1] - *offsetp;
6208 if (!(forw < 2 * backw)) {
6209 const U8 *p = s + cache[1];
6216 while (UTF8_IS_CONTINUATION(*p)) {
6224 *offsetp = cache[0];
6226 /* Drop the stale "length" cache */
6234 ASSERT_UTF8_CACHE(cache);
6240 /* Call utf8n_to_uvchr() to validate the sequence
6241 * (unless a simple non-UTF character) */
6242 if (!UTF8_IS_INVARIANT(*s))
6243 utf8n_to_uvchr(s, UTF8SKIP(s), &n, 0);
6252 if (!SvREADONLY(sv)) {
6254 sv_magic(sv, 0, PERL_MAGIC_utf8, 0, 0);
6255 mg = mg_find(sv, PERL_MAGIC_utf8);
6260 Newz(0, cache, PERL_MAGIC_UTF8_CACHESIZE * 2, STRLEN);
6261 mg->mg_ptr = (char *) cache;
6266 cache[1] = *offsetp;
6267 /* Drop the stale "length" cache */
6280 Returns a boolean indicating whether the strings in the two SVs are
6281 identical. Is UTF-8 and 'use bytes' aware, handles get magic, and will
6282 coerce its args to strings if necessary.
6288 Perl_sv_eq(pTHX_ register SV *sv1, register SV *sv2)
6296 SV* svrecode = Nullsv;
6303 pv1 = SvPV_const(sv1, cur1);
6310 pv2 = SvPV_const(sv2, cur2);
6312 if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
6313 /* Differing utf8ness.
6314 * Do not UTF8size the comparands as a side-effect. */
6317 svrecode = newSVpvn(pv2, cur2);
6318 sv_recode_to_utf8(svrecode, PL_encoding);
6319 pv2 = SvPV_const(svrecode, cur2);
6322 svrecode = newSVpvn(pv1, cur1);
6323 sv_recode_to_utf8(svrecode, PL_encoding);
6324 pv1 = SvPV_const(svrecode, cur1);
6326 /* Now both are in UTF-8. */
6328 SvREFCNT_dec(svrecode);
6333 bool is_utf8 = TRUE;
6336 /* sv1 is the UTF-8 one,
6337 * if is equal it must be downgrade-able */
6338 char *pv = (char*)bytes_from_utf8((const U8*)pv1,
6344 /* sv2 is the UTF-8 one,
6345 * if is equal it must be downgrade-able */
6346 char *pv = (char *)bytes_from_utf8((const U8*)pv2,
6352 /* Downgrade not possible - cannot be eq */
6360 eq = (pv1 == pv2) || memEQ(pv1, pv2, cur1);
6363 SvREFCNT_dec(svrecode);
6374 Compares the strings in two SVs. Returns -1, 0, or 1 indicating whether the
6375 string in C<sv1> is less than, equal to, or greater than the string in
6376 C<sv2>. Is UTF-8 and 'use bytes' aware, handles get magic, and will
6377 coerce its args to strings if necessary. See also C<sv_cmp_locale>.
6383 Perl_sv_cmp(pTHX_ register SV *sv1, register SV *sv2)
6386 const char *pv1, *pv2;
6389 SV *svrecode = Nullsv;
6396 pv1 = SvPV_const(sv1, cur1);
6403 pv2 = SvPV_const(sv2, cur2);
6405 if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
6406 /* Differing utf8ness.
6407 * Do not UTF8size the comparands as a side-effect. */
6410 svrecode = newSVpvn(pv2, cur2);
6411 sv_recode_to_utf8(svrecode, PL_encoding);
6412 pv2 = SvPV_const(svrecode, cur2);
6415 pv2 = tpv = (char*)bytes_to_utf8((const U8*)pv2, &cur2);
6420 svrecode = newSVpvn(pv1, cur1);
6421 sv_recode_to_utf8(svrecode, PL_encoding);
6422 pv1 = SvPV_const(svrecode, cur1);
6425 pv1 = tpv = (char*)bytes_to_utf8((const U8*)pv1, &cur1);
6431 cmp = cur2 ? -1 : 0;
6435 const I32 retval = memcmp((const void*)pv1, (const void*)pv2, cur1 < cur2 ? cur1 : cur2);
6438 cmp = retval < 0 ? -1 : 1;
6439 } else if (cur1 == cur2) {
6442 cmp = cur1 < cur2 ? -1 : 1;
6447 SvREFCNT_dec(svrecode);
6456 =for apidoc sv_cmp_locale
6458 Compares the strings in two SVs in a locale-aware manner. Is UTF-8 and
6459 'use bytes' aware, handles get magic, and will coerce its args to strings
6460 if necessary. See also C<sv_cmp_locale>. See also C<sv_cmp>.
6466 Perl_sv_cmp_locale(pTHX_ register SV *sv1, register SV *sv2)
6468 #ifdef USE_LOCALE_COLLATE
6474 if (PL_collation_standard)
6478 pv1 = sv1 ? sv_collxfrm(sv1, &len1) : (char *) NULL;
6480 pv2 = sv2 ? sv_collxfrm(sv2, &len2) : (char *) NULL;
6482 if (!pv1 || !len1) {
6493 retval = memcmp((void*)pv1, (void*)pv2, len1 < len2 ? len1 : len2);
6496 return retval < 0 ? -1 : 1;
6499 * When the result of collation is equality, that doesn't mean
6500 * that there are no differences -- some locales exclude some
6501 * characters from consideration. So to avoid false equalities,
6502 * we use the raw string as a tiebreaker.
6508 #endif /* USE_LOCALE_COLLATE */
6510 return sv_cmp(sv1, sv2);
6514 #ifdef USE_LOCALE_COLLATE
6517 =for apidoc sv_collxfrm
6519 Add Collate Transform magic to an SV if it doesn't already have it.
6521 Any scalar variable may carry PERL_MAGIC_collxfrm magic that contains the
6522 scalar data of the variable, but transformed to such a format that a normal
6523 memory comparison can be used to compare the data according to the locale
6530 Perl_sv_collxfrm(pTHX_ SV *sv, STRLEN *nxp)
6534 mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_collxfrm) : (MAGIC *) NULL;
6535 if (!mg || !mg->mg_ptr || *(U32*)mg->mg_ptr != PL_collation_ix) {
6541 Safefree(mg->mg_ptr);
6542 s = SvPV_const(sv, len);
6543 if ((xf = mem_collxfrm(s, len, &xlen))) {
6544 if (SvREADONLY(sv)) {
6547 return xf + sizeof(PL_collation_ix);
6550 sv_magic(sv, 0, PERL_MAGIC_collxfrm, 0, 0);
6551 mg = mg_find(sv, PERL_MAGIC_collxfrm);
6564 if (mg && mg->mg_ptr) {
6566 return mg->mg_ptr + sizeof(PL_collation_ix);
6574 #endif /* USE_LOCALE_COLLATE */
6579 Get a line from the filehandle and store it into the SV, optionally
6580 appending to the currently-stored string.
6586 Perl_sv_gets(pTHX_ register SV *sv, register PerlIO *fp, I32 append)
6590 register STDCHAR rslast;
6591 register STDCHAR *bp;
6597 if (SvTHINKFIRST(sv))
6598 sv_force_normal_flags(sv, append ? 0 : SV_COW_DROP_PV);
6599 /* XXX. If you make this PVIV, then copy on write can copy scalars read
6601 However, perlbench says it's slower, because the existing swipe code
6602 is faster than copy on write.
6603 Swings and roundabouts. */
6604 SvUPGRADE(sv, SVt_PV);
6609 if (PerlIO_isutf8(fp)) {
6611 sv_utf8_upgrade_nomg(sv);
6612 sv_pos_u2b(sv,&append,0);
6614 } else if (SvUTF8(sv)) {
6615 SV *tsv = NEWSV(0,0);
6616 sv_gets(tsv, fp, 0);
6617 sv_utf8_upgrade_nomg(tsv);
6618 SvCUR_set(sv,append);
6621 goto return_string_or_null;
6626 if (PerlIO_isutf8(fp))
6629 if (IN_PERL_COMPILETIME) {
6630 /* we always read code in line mode */
6634 else if (RsSNARF(PL_rs)) {
6635 /* If it is a regular disk file use size from stat() as estimate
6636 of amount we are going to read - may result in malloc-ing
6637 more memory than we realy need if layers bellow reduce
6638 size we read (e.g. CRLF or a gzip layer)
6641 if (!PerlLIO_fstat(PerlIO_fileno(fp), &st) && S_ISREG(st.st_mode)) {
6642 const Off_t offset = PerlIO_tell(fp);
6643 if (offset != (Off_t) -1 && st.st_size + append > offset) {
6644 (void) SvGROW(sv, (STRLEN)((st.st_size - offset) + append + 1));
6650 else if (RsRECORD(PL_rs)) {
6654 /* Grab the size of the record we're getting */
6655 recsize = SvIV(SvRV(PL_rs));
6656 buffer = SvGROW(sv, (STRLEN)(recsize + append + 1)) + append;
6659 /* VMS wants read instead of fread, because fread doesn't respect */
6660 /* RMS record boundaries. This is not necessarily a good thing to be */
6661 /* doing, but we've got no other real choice - except avoid stdio
6662 as implementation - perhaps write a :vms layer ?
6664 bytesread = PerlLIO_read(PerlIO_fileno(fp), buffer, recsize);
6666 bytesread = PerlIO_read(fp, buffer, recsize);
6670 SvCUR_set(sv, bytesread += append);
6671 buffer[bytesread] = '\0';
6672 goto return_string_or_null;
6674 else if (RsPARA(PL_rs)) {
6680 /* Get $/ i.e. PL_rs into same encoding as stream wants */
6681 if (PerlIO_isutf8(fp)) {
6682 rsptr = SvPVutf8(PL_rs, rslen);
6685 if (SvUTF8(PL_rs)) {
6686 if (!sv_utf8_downgrade(PL_rs, TRUE)) {
6687 Perl_croak(aTHX_ "Wide character in $/");
6690 rsptr = SvPV_const(PL_rs, rslen);
6694 rslast = rslen ? rsptr[rslen - 1] : '\0';
6696 if (rspara) { /* have to do this both before and after */
6697 do { /* to make sure file boundaries work right */
6700 i = PerlIO_getc(fp);
6704 PerlIO_ungetc(fp,i);
6710 /* See if we know enough about I/O mechanism to cheat it ! */
6712 /* This used to be #ifdef test - it is made run-time test for ease
6713 of abstracting out stdio interface. One call should be cheap
6714 enough here - and may even be a macro allowing compile
6718 if (PerlIO_fast_gets(fp)) {
6721 * We're going to steal some values from the stdio struct
6722 * and put EVERYTHING in the innermost loop into registers.
6724 register STDCHAR *ptr;
6728 #if defined(VMS) && defined(PERLIO_IS_STDIO)
6729 /* An ungetc()d char is handled separately from the regular
6730 * buffer, so we getc() it back out and stuff it in the buffer.
6732 i = PerlIO_getc(fp);
6733 if (i == EOF) return 0;
6734 *(--((*fp)->_ptr)) = (unsigned char) i;
6738 /* Here is some breathtakingly efficient cheating */
6740 cnt = PerlIO_get_cnt(fp); /* get count into register */
6741 /* make sure we have the room */
6742 if ((I32)(SvLEN(sv) - append) <= cnt + 1) {
6743 /* Not room for all of it
6744 if we are looking for a separator and room for some
6746 if (rslen && cnt > 80 && (I32)SvLEN(sv) > append) {
6747 /* just process what we have room for */
6748 shortbuffered = cnt - SvLEN(sv) + append + 1;
6749 cnt -= shortbuffered;
6753 /* remember that cnt can be negative */
6754 SvGROW(sv, (STRLEN)(append + (cnt <= 0 ? 2 : (cnt + 1))));
6759 bp = (STDCHAR*)SvPVX_const(sv) + append; /* move these two too to registers */
6760 ptr = (STDCHAR*)PerlIO_get_ptr(fp);
6761 DEBUG_P(PerlIO_printf(Perl_debug_log,
6762 "Screamer: entering, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
6763 DEBUG_P(PerlIO_printf(Perl_debug_log,
6764 "Screamer: entering: PerlIO * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
6765 PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
6766 PTR2UV(PerlIO_has_base(fp) ? PerlIO_get_base(fp) : 0)));
6771 while (cnt > 0) { /* this | eat */
6773 if ((*bp++ = *ptr++) == rslast) /* really | dust */
6774 goto thats_all_folks; /* screams | sed :-) */
6778 Copy(ptr, bp, cnt, char); /* this | eat */
6779 bp += cnt; /* screams | dust */
6780 ptr += cnt; /* louder | sed :-) */
6785 if (shortbuffered) { /* oh well, must extend */
6786 cnt = shortbuffered;
6788 bpx = bp - (STDCHAR*)SvPVX_const(sv); /* box up before relocation */
6790 SvGROW(sv, SvLEN(sv) + append + cnt + 2);
6791 bp = (STDCHAR*)SvPVX_const(sv) + bpx; /* unbox after relocation */
6795 DEBUG_P(PerlIO_printf(Perl_debug_log,
6796 "Screamer: going to getc, ptr=%"UVuf", cnt=%ld\n",
6797 PTR2UV(ptr),(long)cnt));
6798 PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt); /* deregisterize cnt and ptr */
6800 DEBUG_P(PerlIO_printf(Perl_debug_log,
6801 "Screamer: pre: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
6802 PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
6803 PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
6805 /* This used to call 'filbuf' in stdio form, but as that behaves like
6806 getc when cnt <= 0 we use PerlIO_getc here to avoid introducing
6807 another abstraction. */
6808 i = PerlIO_getc(fp); /* get more characters */
6810 DEBUG_P(PerlIO_printf(Perl_debug_log,
6811 "Screamer: post: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
6812 PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
6813 PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
6815 cnt = PerlIO_get_cnt(fp);
6816 ptr = (STDCHAR*)PerlIO_get_ptr(fp); /* reregisterize cnt and ptr */
6817 DEBUG_P(PerlIO_printf(Perl_debug_log,
6818 "Screamer: after getc, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
6820 if (i == EOF) /* all done for ever? */
6821 goto thats_really_all_folks;
6823 bpx = bp - (STDCHAR*)SvPVX_const(sv); /* box up before relocation */
6825 SvGROW(sv, bpx + cnt + 2);
6826 bp = (STDCHAR*)SvPVX_const(sv) + bpx; /* unbox after relocation */
6828 *bp++ = (STDCHAR)i; /* store character from PerlIO_getc */
6830 if (rslen && (STDCHAR)i == rslast) /* all done for now? */
6831 goto thats_all_folks;
6835 if ((rslen > 1 && (STRLEN)(bp - (STDCHAR*)SvPVX_const(sv)) < rslen) ||
6836 memNE((char*)bp - rslen, rsptr, rslen))
6837 goto screamer; /* go back to the fray */
6838 thats_really_all_folks:
6840 cnt += shortbuffered;
6841 DEBUG_P(PerlIO_printf(Perl_debug_log,
6842 "Screamer: quitting, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
6843 PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt); /* put these back or we're in trouble */
6844 DEBUG_P(PerlIO_printf(Perl_debug_log,
6845 "Screamer: end: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
6846 PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
6847 PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
6849 SvCUR_set(sv, bp - (STDCHAR*)SvPVX_const(sv)); /* set length */
6850 DEBUG_P(PerlIO_printf(Perl_debug_log,
6851 "Screamer: done, len=%ld, string=|%.*s|\n",
6852 (long)SvCUR(sv),(int)SvCUR(sv),SvPVX_const(sv)));
6856 /*The big, slow, and stupid way. */
6857 #ifdef USE_HEAP_INSTEAD_OF_STACK /* Even slower way. */
6859 New(0, buf, 8192, STDCHAR);
6867 const register STDCHAR *bpe = buf + sizeof(buf);
6869 while ((i = PerlIO_getc(fp)) != EOF && (*bp++ = (STDCHAR)i) != rslast && bp < bpe)
6870 ; /* keep reading */
6874 cnt = PerlIO_read(fp,(char*)buf, sizeof(buf));
6875 /* Accomodate broken VAXC compiler, which applies U8 cast to
6876 * both args of ?: operator, causing EOF to change into 255
6879 i = (U8)buf[cnt - 1];
6885 cnt = 0; /* we do need to re-set the sv even when cnt <= 0 */
6887 sv_catpvn(sv, (char *) buf, cnt);
6889 sv_setpvn(sv, (char *) buf, cnt);
6891 if (i != EOF && /* joy */
6893 SvCUR(sv) < rslen ||
6894 memNE(SvPVX_const(sv) + SvCUR(sv) - rslen, rsptr, rslen)))
6898 * If we're reading from a TTY and we get a short read,
6899 * indicating that the user hit his EOF character, we need
6900 * to notice it now, because if we try to read from the TTY
6901 * again, the EOF condition will disappear.
6903 * The comparison of cnt to sizeof(buf) is an optimization
6904 * that prevents unnecessary calls to feof().
6908 if (!(cnt < sizeof(buf) && PerlIO_eof(fp)))
6912 #ifdef USE_HEAP_INSTEAD_OF_STACK
6917 if (rspara) { /* have to do this both before and after */
6918 while (i != EOF) { /* to make sure file boundaries work right */
6919 i = PerlIO_getc(fp);
6921 PerlIO_ungetc(fp,i);
6927 return_string_or_null:
6928 return (SvCUR(sv) - append) ? SvPVX(sv) : Nullch;
6934 Auto-increment of the value in the SV, doing string to numeric conversion
6935 if necessary. Handles 'get' magic.
6941 Perl_sv_inc(pTHX_ register SV *sv)
6950 if (SvTHINKFIRST(sv)) {
6952 sv_force_normal_flags(sv, 0);
6953 if (SvREADONLY(sv)) {
6954 if (IN_PERL_RUNTIME)
6955 Perl_croak(aTHX_ PL_no_modify);
6959 if (SvAMAGIC(sv) && AMG_CALLun(sv,inc))
6961 i = PTR2IV(SvRV(sv));
6966 flags = SvFLAGS(sv);
6967 if ((flags & (SVp_NOK|SVp_IOK)) == SVp_NOK) {
6968 /* It's (privately or publicly) a float, but not tested as an
6969 integer, so test it to see. */
6971 flags = SvFLAGS(sv);
6973 if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
6974 /* It's publicly an integer, or privately an integer-not-float */
6975 #ifdef PERL_PRESERVE_IVUV
6979 if (SvUVX(sv) == UV_MAX)
6980 sv_setnv(sv, UV_MAX_P1);
6982 (void)SvIOK_only_UV(sv);
6983 SvUV_set(sv, SvUVX(sv) + 1);
6985 if (SvIVX(sv) == IV_MAX)
6986 sv_setuv(sv, (UV)IV_MAX + 1);
6988 (void)SvIOK_only(sv);
6989 SvIV_set(sv, SvIVX(sv) + 1);
6994 if (flags & SVp_NOK) {
6995 (void)SvNOK_only(sv);
6996 SvNV_set(sv, SvNVX(sv) + 1.0);
7000 if (!(flags & SVp_POK) || !*SvPVX_const(sv)) {
7001 if ((flags & SVTYPEMASK) < SVt_PVIV)
7002 sv_upgrade(sv, ((flags & SVTYPEMASK) > SVt_IV ? SVt_PVIV : SVt_IV));
7003 (void)SvIOK_only(sv);
7008 while (isALPHA(*d)) d++;
7009 while (isDIGIT(*d)) d++;
7011 #ifdef PERL_PRESERVE_IVUV
7012 /* Got to punt this as an integer if needs be, but we don't issue
7013 warnings. Probably ought to make the sv_iv_please() that does
7014 the conversion if possible, and silently. */
7015 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), NULL);
7016 if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
7017 /* Need to try really hard to see if it's an integer.
7018 9.22337203685478e+18 is an integer.
7019 but "9.22337203685478e+18" + 0 is UV=9223372036854779904
7020 so $a="9.22337203685478e+18"; $a+0; $a++
7021 needs to be the same as $a="9.22337203685478e+18"; $a++
7028 /* sv_2iv *should* have made this an NV */
7029 if (flags & SVp_NOK) {
7030 (void)SvNOK_only(sv);
7031 SvNV_set(sv, SvNVX(sv) + 1.0);
7034 /* I don't think we can get here. Maybe I should assert this
7035 And if we do get here I suspect that sv_setnv will croak. NWC
7037 #if defined(USE_LONG_DOUBLE)
7038 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",
7039 SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
7041 DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_inc punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
7042 SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
7045 #endif /* PERL_PRESERVE_IVUV */
7046 sv_setnv(sv,Atof(SvPVX_const(sv)) + 1.0);
7050 while (d >= SvPVX_const(sv)) {
7058 /* MKS: The original code here died if letters weren't consecutive.
7059 * at least it didn't have to worry about non-C locales. The
7060 * new code assumes that ('z'-'a')==('Z'-'A'), letters are
7061 * arranged in order (although not consecutively) and that only
7062 * [A-Za-z] are accepted by isALPHA in the C locale.
7064 if (*d != 'z' && *d != 'Z') {
7065 do { ++*d; } while (!isALPHA(*d));
7068 *(d--) -= 'z' - 'a';
7073 *(d--) -= 'z' - 'a' + 1;
7077 /* oh,oh, the number grew */
7078 SvGROW(sv, SvCUR(sv) + 2);
7079 SvCUR_set(sv, SvCUR(sv) + 1);
7080 for (d = SvPVX(sv) + SvCUR(sv); d > SvPVX_const(sv); d--)
7091 Auto-decrement of the value in the SV, doing string to numeric conversion
7092 if necessary. Handles 'get' magic.
7098 Perl_sv_dec(pTHX_ register SV *sv)
7106 if (SvTHINKFIRST(sv)) {
7108 sv_force_normal_flags(sv, 0);
7109 if (SvREADONLY(sv)) {
7110 if (IN_PERL_RUNTIME)
7111 Perl_croak(aTHX_ PL_no_modify);
7115 if (SvAMAGIC(sv) && AMG_CALLun(sv,dec))
7117 i = PTR2IV(SvRV(sv));
7122 /* Unlike sv_inc we don't have to worry about string-never-numbers
7123 and keeping them magic. But we mustn't warn on punting */
7124 flags = SvFLAGS(sv);
7125 if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
7126 /* It's publicly an integer, or privately an integer-not-float */
7127 #ifdef PERL_PRESERVE_IVUV
7131 if (SvUVX(sv) == 0) {
7132 (void)SvIOK_only(sv);
7136 (void)SvIOK_only_UV(sv);
7137 SvUV_set(sv, SvUVX(sv) + 1);
7140 if (SvIVX(sv) == IV_MIN)
7141 sv_setnv(sv, (NV)IV_MIN - 1.0);
7143 (void)SvIOK_only(sv);
7144 SvIV_set(sv, SvIVX(sv) - 1);
7149 if (flags & SVp_NOK) {
7150 SvNV_set(sv, SvNVX(sv) - 1.0);
7151 (void)SvNOK_only(sv);
7154 if (!(flags & SVp_POK)) {
7155 if ((flags & SVTYPEMASK) < SVt_PVNV)
7156 sv_upgrade(sv, SVt_NV);
7158 (void)SvNOK_only(sv);
7161 #ifdef PERL_PRESERVE_IVUV
7163 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), NULL);
7164 if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
7165 /* Need to try really hard to see if it's an integer.
7166 9.22337203685478e+18 is an integer.
7167 but "9.22337203685478e+18" + 0 is UV=9223372036854779904
7168 so $a="9.22337203685478e+18"; $a+0; $a--
7169 needs to be the same as $a="9.22337203685478e+18"; $a--
7176 /* sv_2iv *should* have made this an NV */
7177 if (flags & SVp_NOK) {
7178 (void)SvNOK_only(sv);
7179 SvNV_set(sv, SvNVX(sv) - 1.0);
7182 /* I don't think we can get here. Maybe I should assert this
7183 And if we do get here I suspect that sv_setnv will croak. NWC
7185 #if defined(USE_LONG_DOUBLE)
7186 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",
7187 SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
7189 DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_dec punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
7190 SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
7194 #endif /* PERL_PRESERVE_IVUV */
7195 sv_setnv(sv,Atof(SvPVX_const(sv)) - 1.0); /* punt */
7199 =for apidoc sv_mortalcopy
7201 Creates a new SV which is a copy of the original SV (using C<sv_setsv>).
7202 The new SV is marked as mortal. It will be destroyed "soon", either by an
7203 explicit call to FREETMPS, or by an implicit call at places such as
7204 statement boundaries. See also C<sv_newmortal> and C<sv_2mortal>.
7209 /* Make a string that will exist for the duration of the expression
7210 * evaluation. Actually, it may have to last longer than that, but
7211 * hopefully we won't free it until it has been assigned to a
7212 * permanent location. */
7215 Perl_sv_mortalcopy(pTHX_ SV *oldstr)
7220 sv_setsv(sv,oldstr);
7222 PL_tmps_stack[++PL_tmps_ix] = sv;
7228 =for apidoc sv_newmortal
7230 Creates a new null SV which is mortal. The reference count of the SV is
7231 set to 1. It will be destroyed "soon", either by an explicit call to
7232 FREETMPS, or by an implicit call at places such as statement boundaries.
7233 See also C<sv_mortalcopy> and C<sv_2mortal>.
7239 Perl_sv_newmortal(pTHX)
7244 SvFLAGS(sv) = SVs_TEMP;
7246 PL_tmps_stack[++PL_tmps_ix] = sv;
7251 =for apidoc sv_2mortal
7253 Marks an existing SV as mortal. The SV will be destroyed "soon", either
7254 by an explicit call to FREETMPS, or by an implicit call at places such as
7255 statement boundaries. SvTEMP() is turned on which means that the SV's
7256 string buffer can be "stolen" if this SV is copied. See also C<sv_newmortal>
7257 and C<sv_mortalcopy>.
7263 Perl_sv_2mortal(pTHX_ register SV *sv)
7268 if (SvREADONLY(sv) && SvIMMORTAL(sv))
7271 PL_tmps_stack[++PL_tmps_ix] = sv;
7279 Creates a new SV and copies a string into it. The reference count for the
7280 SV is set to 1. If C<len> is zero, Perl will compute the length using
7281 strlen(). For efficiency, consider using C<newSVpvn> instead.
7287 Perl_newSVpv(pTHX_ const char *s, STRLEN len)
7292 sv_setpvn(sv,s,len ? len : strlen(s));
7297 =for apidoc newSVpvn
7299 Creates a new SV and copies a string into it. The reference count for the
7300 SV is set to 1. Note that if C<len> is zero, Perl will create a zero length
7301 string. You are responsible for ensuring that the source string is at least
7302 C<len> bytes long. If the C<s> argument is NULL the new SV will be undefined.
7308 Perl_newSVpvn(pTHX_ const char *s, STRLEN len)
7313 sv_setpvn(sv,s,len);
7319 =for apidoc newSVhek
7321 Creates a new SV from the hash key structure. It will generate scalars that
7322 point to the shared string table where possible. Returns a new (undefined)
7323 SV if the hek is NULL.
7329 Perl_newSVhek(pTHX_ const HEK *hek)
7338 if (HEK_LEN(hek) == HEf_SVKEY) {
7339 return newSVsv(*(SV**)HEK_KEY(hek));
7341 const int flags = HEK_FLAGS(hek);
7342 if (flags & HVhek_WASUTF8) {
7344 Andreas would like keys he put in as utf8 to come back as utf8
7346 STRLEN utf8_len = HEK_LEN(hek);
7347 U8 *as_utf8 = bytes_to_utf8 ((U8*)HEK_KEY(hek), &utf8_len);
7348 SV *sv = newSVpvn ((char*)as_utf8, utf8_len);
7351 Safefree (as_utf8); /* bytes_to_utf8() allocates a new string */
7353 } else if (flags & HVhek_REHASH) {
7354 /* We don't have a pointer to the hv, so we have to replicate the
7355 flag into every HEK. This hv is using custom a hasing
7356 algorithm. Hence we can't return a shared string scalar, as
7357 that would contain the (wrong) hash value, and might get passed
7358 into an hv routine with a regular hash */
7360 SV *sv = newSVpvn (HEK_KEY(hek), HEK_LEN(hek));
7365 /* This will be overwhelminly the most common case. */
7366 return newSVpvn_share(HEK_KEY(hek),
7367 (HEK_UTF8(hek) ? -HEK_LEN(hek) : HEK_LEN(hek)),
7373 =for apidoc newSVpvn_share
7375 Creates a new SV with its SvPVX_const pointing to a shared string in the string
7376 table. If the string does not already exist in the table, it is created
7377 first. Turns on READONLY and FAKE. The string's hash is stored in the UV
7378 slot of the SV; if the C<hash> parameter is non-zero, that value is used;
7379 otherwise the hash is computed. The idea here is that as the string table
7380 is used for shared hash keys these strings will have SvPVX_const == HeKEY and
7381 hash lookup will avoid string compare.
7387 Perl_newSVpvn_share(pTHX_ const char *src, I32 len, U32 hash)
7390 bool is_utf8 = FALSE;
7392 STRLEN tmplen = -len;
7394 /* See the note in hv.c:hv_fetch() --jhi */
7395 src = (char*)bytes_from_utf8((const U8*)src, &tmplen, &is_utf8);
7399 PERL_HASH(hash, src, len);
7401 sv_upgrade(sv, SVt_PV);
7402 SvPV_set(sv, sharepvn(src, is_utf8?-len:len, hash));
7414 #if defined(PERL_IMPLICIT_CONTEXT)
7416 /* pTHX_ magic can't cope with varargs, so this is a no-context
7417 * version of the main function, (which may itself be aliased to us).
7418 * Don't access this version directly.
7422 Perl_newSVpvf_nocontext(const char* pat, ...)
7427 va_start(args, pat);
7428 sv = vnewSVpvf(pat, &args);
7435 =for apidoc newSVpvf
7437 Creates a new SV and initializes it with the string formatted like
7444 Perl_newSVpvf(pTHX_ const char* pat, ...)
7448 va_start(args, pat);
7449 sv = vnewSVpvf(pat, &args);
7454 /* backend for newSVpvf() and newSVpvf_nocontext() */
7457 Perl_vnewSVpvf(pTHX_ const char* pat, va_list* args)
7461 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
7468 Creates a new SV and copies a floating point value into it.
7469 The reference count for the SV is set to 1.
7475 Perl_newSVnv(pTHX_ NV n)
7487 Creates a new SV and copies an integer into it. The reference count for the
7494 Perl_newSViv(pTHX_ IV i)
7506 Creates a new SV and copies an unsigned integer into it.
7507 The reference count for the SV is set to 1.
7513 Perl_newSVuv(pTHX_ UV u)
7523 =for apidoc newRV_noinc
7525 Creates an RV wrapper for an SV. The reference count for the original
7526 SV is B<not> incremented.
7532 Perl_newRV_noinc(pTHX_ SV *tmpRef)
7537 sv_upgrade(sv, SVt_RV);
7539 SvRV_set(sv, tmpRef);
7544 /* newRV_inc is the official function name to use now.
7545 * newRV_inc is in fact #defined to newRV in sv.h
7549 Perl_newRV(pTHX_ SV *tmpRef)
7551 return newRV_noinc(SvREFCNT_inc(tmpRef));
7557 Creates a new SV which is an exact duplicate of the original SV.
7564 Perl_newSVsv(pTHX_ register SV *old)
7570 if (SvTYPE(old) == SVTYPEMASK) {
7571 if (ckWARN_d(WARN_INTERNAL))
7572 Perl_warner(aTHX_ packWARN(WARN_INTERNAL), "semi-panic: attempt to dup freed string");
7576 /* SV_GMAGIC is the default for sv_setv()
7577 SV_NOSTEAL prevents TEMP buffers being, well, stolen, and saves games
7578 with SvTEMP_off and SvTEMP_on round a call to sv_setsv. */
7579 sv_setsv_flags(sv, old, SV_GMAGIC | SV_NOSTEAL);
7584 =for apidoc sv_reset
7586 Underlying implementation for the C<reset> Perl function.
7587 Note that the perl-level function is vaguely deprecated.
7593 Perl_sv_reset(pTHX_ register const char *s, HV *stash)
7596 char todo[PERL_UCHAR_MAX+1];
7601 if (!*s) { /* reset ?? searches */
7602 MAGIC *mg = mg_find((SV *)stash, PERL_MAGIC_symtab);
7604 PMOP *pm = (PMOP *) mg->mg_obj;
7606 pm->op_pmdynflags &= ~PMdf_USED;
7613 /* reset variables */
7615 if (!HvARRAY(stash))
7618 Zero(todo, 256, char);
7621 I32 i = (unsigned char)*s;
7625 max = (unsigned char)*s++;
7626 for ( ; i <= max; i++) {
7629 for (i = 0; i <= (I32) HvMAX(stash); i++) {
7631 for (entry = HvARRAY(stash)[i];
7633 entry = HeNEXT(entry))
7638 if (!todo[(U8)*HeKEY(entry)])
7640 gv = (GV*)HeVAL(entry);
7642 if (SvTHINKFIRST(sv)) {
7643 if (!SvREADONLY(sv) && SvROK(sv))
7648 if (SvTYPE(sv) >= SVt_PV) {
7650 if (SvPVX_const(sv) != Nullch)
7657 if (GvHV(gv) && !HvNAME_get(GvHV(gv))) {
7660 #ifdef USE_ENVIRON_ARRAY
7662 # ifdef USE_ITHREADS
7663 && PL_curinterp == aTHX
7667 environ[0] = Nullch;
7670 #endif /* !PERL_MICRO */
7680 Using various gambits, try to get an IO from an SV: the IO slot if its a
7681 GV; or the recursive result if we're an RV; or the IO slot of the symbol
7682 named after the PV if we're a string.
7688 Perl_sv_2io(pTHX_ SV *sv)
7693 switch (SvTYPE(sv)) {
7701 Perl_croak(aTHX_ "Bad filehandle: %s", GvNAME(gv));
7705 Perl_croak(aTHX_ PL_no_usym, "filehandle");
7707 return sv_2io(SvRV(sv));
7708 gv = gv_fetchsv(sv, FALSE, SVt_PVIO);
7714 Perl_croak(aTHX_ "Bad filehandle: %"SVf, sv);
7723 Using various gambits, try to get a CV from an SV; in addition, try if
7724 possible to set C<*st> and C<*gvp> to the stash and GV associated with it.
7730 Perl_sv_2cv(pTHX_ SV *sv, HV **st, GV **gvp, I32 lref)
7737 return *gvp = Nullgv, Nullcv;
7738 switch (SvTYPE(sv)) {
7757 SV **sp = &sv; /* Used in tryAMAGICunDEREF macro. */
7758 tryAMAGICunDEREF(to_cv);
7761 if (SvTYPE(sv) == SVt_PVCV) {
7770 Perl_croak(aTHX_ "Not a subroutine reference");
7775 gv = gv_fetchsv(sv, lref, SVt_PVCV);
7781 if (lref && !GvCVu(gv)) {
7784 tmpsv = NEWSV(704,0);
7785 gv_efullname3(tmpsv, gv, Nullch);
7786 /* XXX this is probably not what they think they're getting.
7787 * It has the same effect as "sub name;", i.e. just a forward
7789 newSUB(start_subparse(FALSE, 0),
7790 newSVOP(OP_CONST, 0, tmpsv),
7795 Perl_croak(aTHX_ "Unable to create sub named \"%"SVf"\"",
7805 Returns true if the SV has a true value by Perl's rules.
7806 Use the C<SvTRUE> macro instead, which may call C<sv_true()> or may
7807 instead use an in-line version.
7813 Perl_sv_true(pTHX_ register SV *sv)
7818 const register XPV* tXpv;
7819 if ((tXpv = (XPV*)SvANY(sv)) &&
7820 (tXpv->xpv_cur > 1 ||
7821 (tXpv->xpv_cur && *sv->sv_u.svu_pv != '0')))
7828 return SvIVX(sv) != 0;
7831 return SvNVX(sv) != 0.0;
7833 return sv_2bool(sv);
7841 A private implementation of the C<SvIVx> macro for compilers which can't
7842 cope with complex macro expressions. Always use the macro instead.
7848 Perl_sv_iv(pTHX_ register SV *sv)
7852 return (IV)SvUVX(sv);
7861 A private implementation of the C<SvUVx> macro for compilers which can't
7862 cope with complex macro expressions. Always use the macro instead.
7868 Perl_sv_uv(pTHX_ register SV *sv)
7873 return (UV)SvIVX(sv);
7881 A private implementation of the C<SvNVx> macro for compilers which can't
7882 cope with complex macro expressions. Always use the macro instead.
7888 Perl_sv_nv(pTHX_ register SV *sv)
7895 /* sv_pv() is now a macro using SvPV_nolen();
7896 * this function provided for binary compatibility only
7900 Perl_sv_pv(pTHX_ SV *sv)
7905 return sv_2pv(sv, 0);
7911 Use the C<SvPV_nolen> macro instead
7915 A private implementation of the C<SvPV> macro for compilers which can't
7916 cope with complex macro expressions. Always use the macro instead.
7922 Perl_sv_pvn(pTHX_ SV *sv, STRLEN *lp)
7928 return sv_2pv(sv, lp);
7933 Perl_sv_pvn_nomg(pTHX_ register SV *sv, STRLEN *lp)
7939 return sv_2pv_flags(sv, lp, 0);
7942 /* sv_pvn_force() is now a macro using Perl_sv_pvn_force_flags();
7943 * this function provided for binary compatibility only
7947 Perl_sv_pvn_force(pTHX_ SV *sv, STRLEN *lp)
7949 return sv_pvn_force_flags(sv, lp, SV_GMAGIC);
7953 =for apidoc sv_pvn_force
7955 Get a sensible string out of the SV somehow.
7956 A private implementation of the C<SvPV_force> macro for compilers which
7957 can't cope with complex macro expressions. Always use the macro instead.
7959 =for apidoc sv_pvn_force_flags
7961 Get a sensible string out of the SV somehow.
7962 If C<flags> has C<SV_GMAGIC> bit set, will C<mg_get> on C<sv> if
7963 appropriate, else not. C<sv_pvn_force> and C<sv_pvn_force_nomg> are
7964 implemented in terms of this function.
7965 You normally want to use the various wrapper macros instead: see
7966 C<SvPV_force> and C<SvPV_force_nomg>
7972 Perl_sv_pvn_force_flags(pTHX_ SV *sv, STRLEN *lp, I32 flags)
7975 if (SvTHINKFIRST(sv) && !SvROK(sv))
7976 sv_force_normal_flags(sv, 0);
7986 if (SvREADONLY(sv) && !(flags & SV_MUTABLE_RETURN)) {
7988 Perl_croak(aTHX_ "Can't coerce readonly %s to string in %s",
7989 sv_reftype(sv,0), OP_NAME(PL_op));
7991 Perl_croak(aTHX_ "Can't coerce readonly %s to string",
7994 if (SvTYPE(sv) > SVt_PVLV && SvTYPE(sv) != SVt_PVFM) {
7995 Perl_croak(aTHX_ "Can't coerce %s to string in %s", sv_reftype(sv,0),
7999 s = sv_2pv_flags(sv, &len, flags);
8003 if (s != SvPVX_const(sv)) { /* Almost, but not quite, sv_setpvn() */
8006 SvUPGRADE(sv, SVt_PV); /* Never FALSE */
8007 SvGROW(sv, len + 1);
8008 Move(s,SvPVX_const(sv),len,char);
8013 SvPOK_on(sv); /* validate pointer */
8015 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
8016 PTR2UV(sv),SvPVX_const(sv)));
8019 return SvPVX_mutable(sv);
8022 /* sv_pvbyte () is now a macro using Perl_sv_2pv_flags();
8023 * this function provided for binary compatibility only
8027 Perl_sv_pvbyte(pTHX_ SV *sv)
8029 sv_utf8_downgrade(sv,0);
8034 =for apidoc sv_pvbyte
8036 Use C<SvPVbyte_nolen> instead.
8038 =for apidoc sv_pvbyten
8040 A private implementation of the C<SvPVbyte> macro for compilers
8041 which can't cope with complex macro expressions. Always use the macro
8048 Perl_sv_pvbyten(pTHX_ SV *sv, STRLEN *lp)
8050 sv_utf8_downgrade(sv,0);
8051 return sv_pvn(sv,lp);
8055 =for apidoc sv_pvbyten_force
8057 A private implementation of the C<SvPVbytex_force> macro for compilers
8058 which can't cope with complex macro expressions. Always use the macro
8065 Perl_sv_pvbyten_force(pTHX_ SV *sv, STRLEN *lp)
8067 sv_pvn_force(sv,lp);
8068 sv_utf8_downgrade(sv,0);
8073 /* sv_pvutf8 () is now a macro using Perl_sv_2pv_flags();
8074 * this function provided for binary compatibility only
8078 Perl_sv_pvutf8(pTHX_ SV *sv)
8080 sv_utf8_upgrade(sv);
8085 =for apidoc sv_pvutf8
8087 Use the C<SvPVutf8_nolen> macro instead
8089 =for apidoc sv_pvutf8n
8091 A private implementation of the C<SvPVutf8> macro for compilers
8092 which can't cope with complex macro expressions. Always use the macro
8099 Perl_sv_pvutf8n(pTHX_ SV *sv, STRLEN *lp)
8101 sv_utf8_upgrade(sv);
8102 return sv_pvn(sv,lp);
8106 =for apidoc sv_pvutf8n_force
8108 A private implementation of the C<SvPVutf8_force> macro for compilers
8109 which can't cope with complex macro expressions. Always use the macro
8116 Perl_sv_pvutf8n_force(pTHX_ SV *sv, STRLEN *lp)
8118 sv_pvn_force(sv,lp);
8119 sv_utf8_upgrade(sv);
8125 =for apidoc sv_reftype
8127 Returns a string describing what the SV is a reference to.
8133 Perl_sv_reftype(pTHX_ const SV *sv, int ob)
8135 /* The fact that I don't need to downcast to char * everywhere, only in ?:
8136 inside return suggests a const propagation bug in g++. */
8137 if (ob && SvOBJECT(sv)) {
8138 char *name = HvNAME_get(SvSTASH(sv));
8139 return name ? name : (char *) "__ANON__";
8142 switch (SvTYPE(sv)) {
8159 case SVt_PVLV: return (char *) (SvROK(sv) ? "REF"
8160 /* tied lvalues should appear to be
8161 * scalars for backwards compatitbility */
8162 : (LvTYPE(sv) == 't' || LvTYPE(sv) == 'T')
8163 ? "SCALAR" : "LVALUE");
8164 case SVt_PVAV: return "ARRAY";
8165 case SVt_PVHV: return "HASH";
8166 case SVt_PVCV: return "CODE";
8167 case SVt_PVGV: return "GLOB";
8168 case SVt_PVFM: return "FORMAT";
8169 case SVt_PVIO: return "IO";
8170 default: return "UNKNOWN";
8176 =for apidoc sv_isobject
8178 Returns a boolean indicating whether the SV is an RV pointing to a blessed
8179 object. If the SV is not an RV, or if the object is not blessed, then this
8186 Perl_sv_isobject(pTHX_ SV *sv)
8203 Returns a boolean indicating whether the SV is blessed into the specified
8204 class. This does not check for subtypes; use C<sv_derived_from> to verify
8205 an inheritance relationship.
8211 Perl_sv_isa(pTHX_ SV *sv, const char *name)
8223 hvname = HvNAME_get(SvSTASH(sv));
8227 return strEQ(hvname, name);
8233 Creates a new SV for the RV, C<rv>, to point to. If C<rv> is not an RV then
8234 it will be upgraded to one. If C<classname> is non-null then the new SV will
8235 be blessed in the specified package. The new SV is returned and its
8236 reference count is 1.
8242 Perl_newSVrv(pTHX_ SV *rv, const char *classname)
8248 SV_CHECK_THINKFIRST_COW_DROP(rv);
8251 if (SvTYPE(rv) >= SVt_PVMG) {
8252 const U32 refcnt = SvREFCNT(rv);
8256 SvREFCNT(rv) = refcnt;
8259 if (SvTYPE(rv) < SVt_RV)
8260 sv_upgrade(rv, SVt_RV);
8261 else if (SvTYPE(rv) > SVt_RV) {
8272 HV* stash = gv_stashpv(classname, TRUE);
8273 (void)sv_bless(rv, stash);
8279 =for apidoc sv_setref_pv
8281 Copies a pointer into a new SV, optionally blessing the SV. The C<rv>
8282 argument will be upgraded to an RV. That RV will be modified to point to
8283 the new SV. If the C<pv> argument is NULL then C<PL_sv_undef> will be placed
8284 into the SV. The C<classname> argument indicates the package for the
8285 blessing. Set C<classname> to C<Nullch> to avoid the blessing. The new SV
8286 will have a reference count of 1, and the RV will be returned.
8288 Do not use with other Perl types such as HV, AV, SV, CV, because those
8289 objects will become corrupted by the pointer copy process.
8291 Note that C<sv_setref_pvn> copies the string while this copies the pointer.
8297 Perl_sv_setref_pv(pTHX_ SV *rv, const char *classname, void *pv)
8300 sv_setsv(rv, &PL_sv_undef);
8304 sv_setiv(newSVrv(rv,classname), PTR2IV(pv));
8309 =for apidoc sv_setref_iv
8311 Copies an integer into a new SV, optionally blessing the SV. The C<rv>
8312 argument will be upgraded to an RV. That RV will be modified to point to
8313 the new SV. The C<classname> argument indicates the package for the
8314 blessing. Set C<classname> to C<Nullch> to avoid the blessing. The new SV
8315 will have a reference count of 1, and the RV will be returned.
8321 Perl_sv_setref_iv(pTHX_ SV *rv, const char *classname, IV iv)
8323 sv_setiv(newSVrv(rv,classname), iv);
8328 =for apidoc sv_setref_uv
8330 Copies an unsigned integer into a new SV, optionally blessing the SV. The C<rv>
8331 argument will be upgraded to an RV. That RV will be modified to point to
8332 the new SV. The C<classname> argument indicates the package for the
8333 blessing. Set C<classname> to C<Nullch> to avoid the blessing. The new SV
8334 will have a reference count of 1, and the RV will be returned.
8340 Perl_sv_setref_uv(pTHX_ SV *rv, const char *classname, UV uv)
8342 sv_setuv(newSVrv(rv,classname), uv);
8347 =for apidoc sv_setref_nv
8349 Copies a double into a new SV, optionally blessing the SV. The C<rv>
8350 argument will be upgraded to an RV. That RV will be modified to point to
8351 the new SV. The C<classname> argument indicates the package for the
8352 blessing. Set C<classname> to C<Nullch> to avoid the blessing. The new SV
8353 will have a reference count of 1, and the RV will be returned.
8359 Perl_sv_setref_nv(pTHX_ SV *rv, const char *classname, NV nv)
8361 sv_setnv(newSVrv(rv,classname), nv);
8366 =for apidoc sv_setref_pvn
8368 Copies a string into a new SV, optionally blessing the SV. The length of the
8369 string must be specified with C<n>. The C<rv> argument will be upgraded to
8370 an RV. That RV will be modified to point to the new SV. The C<classname>
8371 argument indicates the package for the blessing. Set C<classname> to
8372 C<Nullch> to avoid the blessing. The new SV will have a reference count
8373 of 1, and the RV will be returned.
8375 Note that C<sv_setref_pv> copies the pointer while this copies the string.
8381 Perl_sv_setref_pvn(pTHX_ SV *rv, const char *classname, char *pv, STRLEN n)
8383 sv_setpvn(newSVrv(rv,classname), pv, n);
8388 =for apidoc sv_bless
8390 Blesses an SV into a specified package. The SV must be an RV. The package
8391 must be designated by its stash (see C<gv_stashpv()>). The reference count
8392 of the SV is unaffected.
8398 Perl_sv_bless(pTHX_ SV *sv, HV *stash)
8402 Perl_croak(aTHX_ "Can't bless non-reference value");
8404 if (SvFLAGS(tmpRef) & (SVs_OBJECT|SVf_READONLY)) {
8405 if (SvREADONLY(tmpRef))
8406 Perl_croak(aTHX_ PL_no_modify);
8407 if (SvOBJECT(tmpRef)) {
8408 if (SvTYPE(tmpRef) != SVt_PVIO)
8410 SvREFCNT_dec(SvSTASH(tmpRef));
8413 SvOBJECT_on(tmpRef);
8414 if (SvTYPE(tmpRef) != SVt_PVIO)
8416 SvUPGRADE(tmpRef, SVt_PVMG);
8417 SvSTASH_set(tmpRef, (HV*)SvREFCNT_inc(stash));
8424 if(SvSMAGICAL(tmpRef))
8425 if(mg_find(tmpRef, PERL_MAGIC_ext) || mg_find(tmpRef, PERL_MAGIC_uvar))
8433 /* Downgrades a PVGV to a PVMG.
8437 S_sv_unglob(pTHX_ SV *sv)
8441 assert(SvTYPE(sv) == SVt_PVGV);
8446 SvREFCNT_dec(GvSTASH(sv));
8447 GvSTASH(sv) = Nullhv;
8449 sv_unmagic(sv, PERL_MAGIC_glob);
8450 Safefree(GvNAME(sv));
8453 /* need to keep SvANY(sv) in the right arena */
8454 xpvmg = new_XPVMG();
8455 StructCopy(SvANY(sv), xpvmg, XPVMG);
8456 del_XPVGV(SvANY(sv));
8459 SvFLAGS(sv) &= ~SVTYPEMASK;
8460 SvFLAGS(sv) |= SVt_PVMG;
8464 =for apidoc sv_unref_flags
8466 Unsets the RV status of the SV, and decrements the reference count of
8467 whatever was being referenced by the RV. This can almost be thought of
8468 as a reversal of C<newSVrv>. The C<cflags> argument can contain
8469 C<SV_IMMEDIATE_UNREF> to force the reference count to be decremented
8470 (otherwise the decrementing is conditional on the reference count being
8471 different from one or the reference being a readonly SV).
8478 Perl_sv_unref_flags(pTHX_ SV *sv, U32 flags)
8482 if (SvWEAKREF(sv)) {
8490 /* You can't have a || SvREADONLY(rv) here, as $a = $$a, where $a was
8491 assigned to as BEGIN {$a = \"Foo"} will fail. */
8492 if (SvREFCNT(rv) != 1 || (flags & SV_IMMEDIATE_UNREF))
8494 else /* XXX Hack, but hard to make $a=$a->[1] work otherwise */
8495 sv_2mortal(rv); /* Schedule for freeing later */
8499 =for apidoc sv_unref
8501 Unsets the RV status of the SV, and decrements the reference count of
8502 whatever was being referenced by the RV. This can almost be thought of
8503 as a reversal of C<newSVrv>. This is C<sv_unref_flags> with the C<flag>
8504 being zero. See C<SvROK_off>.
8510 Perl_sv_unref(pTHX_ SV *sv)
8512 sv_unref_flags(sv, 0);
8516 =for apidoc sv_taint
8518 Taint an SV. Use C<SvTAINTED_on> instead.
8523 Perl_sv_taint(pTHX_ SV *sv)
8525 sv_magic((sv), Nullsv, PERL_MAGIC_taint, Nullch, 0);
8529 =for apidoc sv_untaint
8531 Untaint an SV. Use C<SvTAINTED_off> instead.
8536 Perl_sv_untaint(pTHX_ SV *sv)
8538 if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
8539 MAGIC *mg = mg_find(sv, PERL_MAGIC_taint);
8546 =for apidoc sv_tainted
8548 Test an SV for taintedness. Use C<SvTAINTED> instead.
8553 Perl_sv_tainted(pTHX_ SV *sv)
8555 if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
8556 MAGIC * const mg = mg_find(sv, PERL_MAGIC_taint);
8557 if (mg && ((mg->mg_len & 1) || ((mg->mg_len & 2) && mg->mg_obj == sv)))
8564 =for apidoc sv_setpviv
8566 Copies an integer into the given SV, also updating its string value.
8567 Does not handle 'set' magic. See C<sv_setpviv_mg>.
8573 Perl_sv_setpviv(pTHX_ SV *sv, IV iv)
8575 char buf[TYPE_CHARS(UV)];
8577 char *ptr = uiv_2buf(buf, iv, 0, 0, &ebuf);
8579 sv_setpvn(sv, ptr, ebuf - ptr);
8583 =for apidoc sv_setpviv_mg
8585 Like C<sv_setpviv>, but also handles 'set' magic.
8591 Perl_sv_setpviv_mg(pTHX_ SV *sv, IV iv)
8593 char buf[TYPE_CHARS(UV)];
8595 char *ptr = uiv_2buf(buf, iv, 0, 0, &ebuf);
8597 sv_setpvn(sv, ptr, ebuf - ptr);
8601 #if defined(PERL_IMPLICIT_CONTEXT)
8603 /* pTHX_ magic can't cope with varargs, so this is a no-context
8604 * version of the main function, (which may itself be aliased to us).
8605 * Don't access this version directly.
8609 Perl_sv_setpvf_nocontext(SV *sv, const char* pat, ...)
8613 va_start(args, pat);
8614 sv_vsetpvf(sv, pat, &args);
8618 /* pTHX_ magic can't cope with varargs, so this is a no-context
8619 * version of the main function, (which may itself be aliased to us).
8620 * Don't access this version directly.
8624 Perl_sv_setpvf_mg_nocontext(SV *sv, const char* pat, ...)
8628 va_start(args, pat);
8629 sv_vsetpvf_mg(sv, pat, &args);
8635 =for apidoc sv_setpvf
8637 Works like C<sv_catpvf> but copies the text into the SV instead of
8638 appending it. Does not handle 'set' magic. See C<sv_setpvf_mg>.
8644 Perl_sv_setpvf(pTHX_ SV *sv, const char* pat, ...)
8647 va_start(args, pat);
8648 sv_vsetpvf(sv, pat, &args);
8653 =for apidoc sv_vsetpvf
8655 Works like C<sv_vcatpvf> but copies the text into the SV instead of
8656 appending it. Does not handle 'set' magic. See C<sv_vsetpvf_mg>.
8658 Usually used via its frontend C<sv_setpvf>.
8664 Perl_sv_vsetpvf(pTHX_ SV *sv, const char* pat, va_list* args)
8666 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
8670 =for apidoc sv_setpvf_mg
8672 Like C<sv_setpvf>, but also handles 'set' magic.
8678 Perl_sv_setpvf_mg(pTHX_ SV *sv, const char* pat, ...)
8681 va_start(args, pat);
8682 sv_vsetpvf_mg(sv, pat, &args);
8687 =for apidoc sv_vsetpvf_mg
8689 Like C<sv_vsetpvf>, but also handles 'set' magic.
8691 Usually used via its frontend C<sv_setpvf_mg>.
8697 Perl_sv_vsetpvf_mg(pTHX_ SV *sv, const char* pat, va_list* args)
8699 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
8703 #if defined(PERL_IMPLICIT_CONTEXT)
8705 /* pTHX_ magic can't cope with varargs, so this is a no-context
8706 * version of the main function, (which may itself be aliased to us).
8707 * Don't access this version directly.
8711 Perl_sv_catpvf_nocontext(SV *sv, const char* pat, ...)
8715 va_start(args, pat);
8716 sv_vcatpvf(sv, pat, &args);
8720 /* pTHX_ magic can't cope with varargs, so this is a no-context
8721 * version of the main function, (which may itself be aliased to us).
8722 * Don't access this version directly.
8726 Perl_sv_catpvf_mg_nocontext(SV *sv, const char* pat, ...)
8730 va_start(args, pat);
8731 sv_vcatpvf_mg(sv, pat, &args);
8737 =for apidoc sv_catpvf
8739 Processes its arguments like C<sprintf> and appends the formatted
8740 output to an SV. If the appended data contains "wide" characters
8741 (including, but not limited to, SVs with a UTF-8 PV formatted with %s,
8742 and characters >255 formatted with %c), the original SV might get
8743 upgraded to UTF-8. Handles 'get' magic, but not 'set' magic. See
8744 C<sv_catpvf_mg>. If the original SV was UTF-8, the pattern should be
8745 valid UTF-8; if the original SV was bytes, the pattern should be too.
8750 Perl_sv_catpvf(pTHX_ SV *sv, const char* pat, ...)
8753 va_start(args, pat);
8754 sv_vcatpvf(sv, pat, &args);
8759 =for apidoc sv_vcatpvf
8761 Processes its arguments like C<vsprintf> and appends the formatted output
8762 to an SV. Does not handle 'set' magic. See C<sv_vcatpvf_mg>.
8764 Usually used via its frontend C<sv_catpvf>.
8770 Perl_sv_vcatpvf(pTHX_ SV *sv, const char* pat, va_list* args)
8772 sv_vcatpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
8776 =for apidoc sv_catpvf_mg
8778 Like C<sv_catpvf>, but also handles 'set' magic.
8784 Perl_sv_catpvf_mg(pTHX_ SV *sv, const char* pat, ...)
8787 va_start(args, pat);
8788 sv_vcatpvf_mg(sv, pat, &args);
8793 =for apidoc sv_vcatpvf_mg
8795 Like C<sv_vcatpvf>, but also handles 'set' magic.
8797 Usually used via its frontend C<sv_catpvf_mg>.
8803 Perl_sv_vcatpvf_mg(pTHX_ SV *sv, const char* pat, va_list* args)
8805 sv_vcatpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
8810 =for apidoc sv_vsetpvfn
8812 Works like C<sv_vcatpvfn> but copies the text into the SV instead of
8815 Usually used via one of its frontends C<sv_vsetpvf> and C<sv_vsetpvf_mg>.
8821 Perl_sv_vsetpvfn(pTHX_ SV *sv, const char *pat, STRLEN patlen, va_list *args, SV **svargs, I32 svmax, bool *maybe_tainted)
8823 sv_setpvn(sv, "", 0);
8824 sv_vcatpvfn(sv, pat, patlen, args, svargs, svmax, maybe_tainted);
8827 /* private function for use in sv_vcatpvfn via the EXPECT_NUMBER macro */
8830 S_expect_number(pTHX_ char** pattern)
8833 switch (**pattern) {
8834 case '1': case '2': case '3':
8835 case '4': case '5': case '6':
8836 case '7': case '8': case '9':
8837 while (isDIGIT(**pattern))
8838 var = var * 10 + (*(*pattern)++ - '0');
8842 #define EXPECT_NUMBER(pattern, var) (var = S_expect_number(aTHX_ &pattern))
8845 F0convert(NV nv, char *endbuf, STRLEN *len)
8847 const int neg = nv < 0;
8856 if (uv & 1 && uv == nv)
8857 uv--; /* Round to even */
8859 const unsigned dig = uv % 10;
8872 =for apidoc sv_vcatpvfn
8874 Processes its arguments like C<vsprintf> and appends the formatted output
8875 to an SV. Uses an array of SVs if the C style variable argument list is
8876 missing (NULL). When running with taint checks enabled, indicates via
8877 C<maybe_tainted> if results are untrustworthy (often due to the use of
8880 Usually used via one of its frontends C<sv_vcatpvf> and C<sv_vcatpvf_mg>.
8885 /* XXX maybe_tainted is never assigned to, so the doc above is lying. */
8888 Perl_sv_vcatpvfn(pTHX_ SV *sv, const char *pat, STRLEN patlen, va_list *args, SV **svargs, I32 svmax, bool *maybe_tainted)
8895 static const char nullstr[] = "(null)";
8897 bool has_utf8 = DO_UTF8(sv); /* has the result utf8? */
8898 const bool pat_utf8 = has_utf8; /* the pattern is in utf8? */
8900 /* Times 4: a decimal digit takes more than 3 binary digits.
8901 * NV_DIG: mantissa takes than many decimal digits.
8902 * Plus 32: Playing safe. */
8903 char ebuf[IV_DIG * 4 + NV_DIG + 32];
8904 /* large enough for "%#.#f" --chip */
8905 /* what about long double NVs? --jhi */
8907 /* no matter what, this is a string now */
8908 (void)SvPV_force(sv, origlen);
8910 /* special-case "", "%s", and "%-p" (SVf) */
8913 if (patlen == 2 && pat[0] == '%' && pat[1] == 's') {
8915 const char *s = va_arg(*args, char*);
8916 sv_catpv(sv, s ? s : nullstr);
8918 else if (svix < svmax) {
8919 sv_catsv(sv, *svargs);
8920 if (DO_UTF8(*svargs))
8925 if (patlen == 3 && pat[0] == '%' &&
8926 pat[1] == '-' && pat[2] == 'p') {
8928 argsv = va_arg(*args, SV*);
8929 sv_catsv(sv, argsv);
8936 #ifndef USE_LONG_DOUBLE
8937 /* special-case "%.<number>[gf]" */
8938 if ( patlen <= 5 && pat[0] == '%' && pat[1] == '.'
8939 && (pat[patlen-1] == 'g' || pat[patlen-1] == 'f') ) {
8940 unsigned digits = 0;
8944 while (*pp >= '0' && *pp <= '9')
8945 digits = 10 * digits + (*pp++ - '0');
8946 if (pp - pat == (int)patlen - 1) {
8950 nv = (NV)va_arg(*args, double);
8951 else if (svix < svmax)
8956 /* Add check for digits != 0 because it seems that some
8957 gconverts are buggy in this case, and we don't yet have
8958 a Configure test for this. */
8959 if (digits && digits < sizeof(ebuf) - NV_DIG - 10) {
8960 /* 0, point, slack */
8961 Gconvert(nv, (int)digits, 0, ebuf);
8963 if (*ebuf) /* May return an empty string for digits==0 */
8966 } else if (!digits) {
8969 if ((p = F0convert(nv, ebuf + sizeof ebuf, &l))) {
8970 sv_catpvn(sv, p, l);
8976 #endif /* !USE_LONG_DOUBLE */
8978 if (!args && svix < svmax && DO_UTF8(*svargs))
8981 patend = (char*)pat + patlen;
8982 for (p = (char*)pat; p < patend; p = q) {
8985 bool vectorize = FALSE;
8986 bool vectorarg = FALSE;
8987 bool vec_utf8 = FALSE;
8993 bool has_precis = FALSE;
8996 bool is_utf8 = FALSE; /* is this item utf8? */
8997 #ifdef HAS_LDBL_SPRINTF_BUG
8998 /* This is to try to fix a bug with irix/nonstop-ux/powerux and
8999 with sfio - Allen <allens@cpan.org> */
9000 bool fix_ldbl_sprintf_bug = FALSE;
9004 U8 utf8buf[UTF8_MAXBYTES+1];
9005 STRLEN esignlen = 0;
9007 const char *eptr = Nullch;
9010 const U8 *vecstr = Null(U8*);
9017 /* we need a long double target in case HAS_LONG_DOUBLE but
9020 #if defined(HAS_LONG_DOUBLE) && LONG_DOUBLESIZE > DOUBLESIZE
9028 const char *dotstr = ".";
9029 STRLEN dotstrlen = 1;
9030 I32 efix = 0; /* explicit format parameter index */
9031 I32 ewix = 0; /* explicit width index */
9032 I32 epix = 0; /* explicit precision index */
9033 I32 evix = 0; /* explicit vector index */
9034 bool asterisk = FALSE;
9036 /* echo everything up to the next format specification */
9037 for (q = p; q < patend && *q != '%'; ++q) ;
9039 if (has_utf8 && !pat_utf8)
9040 sv_catpvn_utf8_upgrade(sv, p, q - p, nsv);
9042 sv_catpvn(sv, p, q - p);
9049 We allow format specification elements in this order:
9050 \d+\$ explicit format parameter index
9052 v|\*(\d+\$)?v vector with optional (optionally specified) arg
9053 0 flag (as above): repeated to allow "v02"
9054 \d+|\*(\d+\$)? width using optional (optionally specified) arg
9055 \.(\d*|\*(\d+\$)?) precision using optional (optionally specified) arg
9057 [%bcdefginopsux_DFOUX] format (mandatory)
9059 if (EXPECT_NUMBER(q, width)) {
9100 if (EXPECT_NUMBER(q, ewix))
9109 if ((vectorarg = asterisk)) {
9121 EXPECT_NUMBER(q, width);
9126 vecsv = va_arg(*args, SV*);
9128 vecsv = (evix ? evix <= svmax : svix < svmax) ?
9129 svargs[evix ? evix-1 : svix++] : &PL_sv_undef;
9130 dotstr = SvPV_const(vecsv, dotstrlen);
9135 vecsv = va_arg(*args, SV*);
9136 vecstr = (U8*)SvPV_const(vecsv,veclen);
9137 vec_utf8 = DO_UTF8(vecsv);
9139 else if (efix ? efix <= svmax : svix < svmax) {
9140 vecsv = svargs[efix ? efix-1 : svix++];
9141 vecstr = (U8*)SvPV_const(vecsv,veclen);
9142 vec_utf8 = DO_UTF8(vecsv);
9143 /* if this is a version object, we need to return the
9144 * stringified representation (which the SvPVX_const has
9145 * already done for us), but not vectorize the args
9147 if ( *q == 'd' && sv_derived_from(vecsv,"version") )
9149 q++; /* skip past the rest of the %vd format */
9150 eptr = (const char *) vecstr;
9151 elen = strlen(eptr);
9164 i = va_arg(*args, int);
9166 i = (ewix ? ewix <= svmax : svix < svmax) ?
9167 SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
9169 width = (i < 0) ? -i : i;
9179 if (EXPECT_NUMBER(q, epix) && *q++ != '$')
9181 /* XXX: todo, support specified precision parameter */
9185 i = va_arg(*args, int);
9187 i = (ewix ? ewix <= svmax : svix < svmax)
9188 ? SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
9189 precis = (i < 0) ? 0 : i;
9194 precis = precis * 10 + (*q++ - '0');
9203 case 'I': /* Ix, I32x, and I64x */
9205 if (q[1] == '6' && q[2] == '4') {
9211 if (q[1] == '3' && q[2] == '2') {
9221 #if defined(HAS_QUAD) || defined(HAS_LONG_DOUBLE)
9232 #if defined(HAS_QUAD) || defined(HAS_LONG_DOUBLE)
9233 if (*(q + 1) == 'l') { /* lld, llf */
9258 argsv = (efix ? efix <= svmax : svix < svmax) ?
9259 svargs[efix ? efix-1 : svix++] : &PL_sv_undef;
9266 uv = (args && !vectorize) ? va_arg(*args, int) : SvIVx(argsv);
9268 (!UNI_IS_INVARIANT(uv) && SvUTF8(sv)))
9270 eptr = (char*)utf8buf;
9271 elen = uvchr_to_utf8((U8*)eptr, uv) - utf8buf;
9282 if (args && !vectorize) {
9283 eptr = va_arg(*args, char*);
9285 #ifdef MACOS_TRADITIONAL
9286 /* On MacOS, %#s format is used for Pascal strings */
9291 elen = strlen(eptr);
9293 eptr = (char *)nullstr;
9294 elen = sizeof nullstr - 1;
9298 eptr = SvPVx_const(argsv, elen);
9299 if (DO_UTF8(argsv)) {
9300 if (has_precis && precis < elen) {
9302 sv_pos_u2b(argsv, &p, 0); /* sticks at end */
9305 if (width) { /* fudge width (can't fudge elen) */
9306 width += elen - sv_len_utf8(argsv);
9314 if (has_precis && elen > precis)
9321 if (left && args) { /* SVf */
9330 argsv = va_arg(*args, SV*);
9331 eptr = SvPVx_const(argsv, elen);
9336 if (alt || vectorize)
9338 uv = PTR2UV(args ? va_arg(*args, void*) : argsv);
9356 uv = utf8n_to_uvchr(vecstr, veclen, &ulen,
9365 esignbuf[esignlen++] = plus;
9369 case 'h': iv = (short)va_arg(*args, int); break;
9370 case 'l': iv = va_arg(*args, long); break;
9371 case 'V': iv = va_arg(*args, IV); break;
9372 default: iv = va_arg(*args, int); break;
9374 case 'q': iv = va_arg(*args, Quad_t); break;
9379 IV tiv = SvIVx(argsv); /* work around GCC bug #13488 */
9381 case 'h': iv = (short)tiv; break;
9382 case 'l': iv = (long)tiv; break;
9384 default: iv = tiv; break;
9386 case 'q': iv = (Quad_t)tiv; break;
9390 if ( !vectorize ) /* we already set uv above */
9395 esignbuf[esignlen++] = plus;
9399 esignbuf[esignlen++] = '-';
9442 uv = utf8n_to_uvchr(vecstr, veclen, &ulen,
9453 case 'h': uv = (unsigned short)va_arg(*args, unsigned); break;
9454 case 'l': uv = va_arg(*args, unsigned long); break;
9455 case 'V': uv = va_arg(*args, UV); break;
9456 default: uv = va_arg(*args, unsigned); break;
9458 case 'q': uv = va_arg(*args, Uquad_t); break;
9463 UV tuv = SvUVx(argsv); /* work around GCC bug #13488 */
9465 case 'h': uv = (unsigned short)tuv; break;
9466 case 'l': uv = (unsigned long)tuv; break;
9468 default: uv = tuv; break;
9470 case 'q': uv = (Uquad_t)tuv; break;
9477 char *ptr = ebuf + sizeof ebuf;
9483 p = (char*)((c == 'X')
9484 ? "0123456789ABCDEF" : "0123456789abcdef");
9490 esignbuf[esignlen++] = '0';
9491 esignbuf[esignlen++] = c; /* 'x' or 'X' */
9499 if (alt && *ptr != '0')
9508 esignbuf[esignlen++] = '0';
9509 esignbuf[esignlen++] = 'b';
9512 default: /* it had better be ten or less */
9516 } while (uv /= base);
9519 elen = (ebuf + sizeof ebuf) - ptr;
9523 zeros = precis - elen;
9524 else if (precis == 0 && elen == 1 && *eptr == '0')
9530 /* FLOATING POINT */
9533 c = 'f'; /* maybe %F isn't supported here */
9539 /* This is evil, but floating point is even more evil */
9541 /* for SV-style calling, we can only get NV
9542 for C-style calling, we assume %f is double;
9543 for simplicity we allow any of %Lf, %llf, %qf for long double
9547 #if defined(USE_LONG_DOUBLE)
9551 /* [perl #20339] - we should accept and ignore %lf rather than die */
9555 #if defined(USE_LONG_DOUBLE)
9556 intsize = args ? 0 : 'q';
9560 #if defined(HAS_LONG_DOUBLE)
9569 /* now we need (long double) if intsize == 'q', else (double) */
9570 nv = (args && !vectorize) ?
9571 #if LONG_DOUBLESIZE > DOUBLESIZE
9573 va_arg(*args, long double) :
9574 va_arg(*args, double)
9576 va_arg(*args, double)
9582 if (c != 'e' && c != 'E') {
9584 /* FIXME: if HAS_LONG_DOUBLE but not USE_LONG_DOUBLE this
9585 will cast our (long double) to (double) */
9586 (void)Perl_frexp(nv, &i);
9587 if (i == PERL_INT_MIN)
9588 Perl_die(aTHX_ "panic: frexp");
9590 need = BIT_DIGITS(i);
9592 need += has_precis ? precis : 6; /* known default */
9597 #ifdef HAS_LDBL_SPRINTF_BUG
9598 /* This is to try to fix a bug with irix/nonstop-ux/powerux and
9599 with sfio - Allen <allens@cpan.org> */
9602 # define MY_DBL_MAX DBL_MAX
9603 # else /* XXX guessing! HUGE_VAL may be defined as infinity, so not using */
9604 # if DOUBLESIZE >= 8
9605 # define MY_DBL_MAX 1.7976931348623157E+308L
9607 # define MY_DBL_MAX 3.40282347E+38L
9611 # ifdef HAS_LDBL_SPRINTF_BUG_LESS1 /* only between -1L & 1L - Allen */
9612 # define MY_DBL_MAX_BUG 1L
9614 # define MY_DBL_MAX_BUG MY_DBL_MAX
9618 # define MY_DBL_MIN DBL_MIN
9619 # else /* XXX guessing! -Allen */
9620 # if DOUBLESIZE >= 8
9621 # define MY_DBL_MIN 2.2250738585072014E-308L
9623 # define MY_DBL_MIN 1.17549435E-38L
9627 if ((intsize == 'q') && (c == 'f') &&
9628 ((nv < MY_DBL_MAX_BUG) && (nv > -MY_DBL_MAX_BUG)) &&
9630 /* it's going to be short enough that
9631 * long double precision is not needed */
9633 if ((nv <= 0L) && (nv >= -0L))
9634 fix_ldbl_sprintf_bug = TRUE; /* 0 is 0 - easiest */
9636 /* would use Perl_fp_class as a double-check but not
9637 * functional on IRIX - see perl.h comments */
9639 if ((nv >= MY_DBL_MIN) || (nv <= -MY_DBL_MIN)) {
9640 /* It's within the range that a double can represent */
9641 #if defined(DBL_MAX) && !defined(DBL_MIN)
9642 if ((nv >= ((long double)1/DBL_MAX)) ||
9643 (nv <= (-(long double)1/DBL_MAX)))
9645 fix_ldbl_sprintf_bug = TRUE;
9648 if (fix_ldbl_sprintf_bug == TRUE) {
9658 # undef MY_DBL_MAX_BUG
9661 #endif /* HAS_LDBL_SPRINTF_BUG */
9663 need += 20; /* fudge factor */
9664 if (PL_efloatsize < need) {
9665 Safefree(PL_efloatbuf);
9666 PL_efloatsize = need + 20; /* more fudge */
9667 New(906, PL_efloatbuf, PL_efloatsize, char);
9668 PL_efloatbuf[0] = '\0';
9671 if ( !(width || left || plus || alt) && fill != '0'
9672 && has_precis && intsize != 'q' ) { /* Shortcuts */
9673 /* See earlier comment about buggy Gconvert when digits,
9675 if ( c == 'g' && precis) {
9676 Gconvert((NV)nv, (int)precis, 0, PL_efloatbuf);
9677 if (*PL_efloatbuf) /* May return an empty string for digits==0 */
9678 goto float_converted;
9679 } else if ( c == 'f' && !precis) {
9680 if ((eptr = F0convert(nv, ebuf + sizeof ebuf, &elen)))
9685 char *ptr = ebuf + sizeof ebuf;
9688 /* FIXME: what to do if HAS_LONG_DOUBLE but not PERL_PRIfldbl? */
9689 #if defined(HAS_LONG_DOUBLE) && defined(PERL_PRIfldbl)
9690 if (intsize == 'q') {
9691 /* Copy the one or more characters in a long double
9692 * format before the 'base' ([efgEFG]) character to
9693 * the format string. */
9694 static char const prifldbl[] = PERL_PRIfldbl;
9695 char const *p = prifldbl + sizeof(prifldbl) - 3;
9696 while (p >= prifldbl) { *--ptr = *p--; }
9701 do { *--ptr = '0' + (base % 10); } while (base /= 10);
9706 do { *--ptr = '0' + (base % 10); } while (base /= 10);
9718 /* No taint. Otherwise we are in the strange situation
9719 * where printf() taints but print($float) doesn't.
9721 #if defined(HAS_LONG_DOUBLE)
9723 (void)sprintf(PL_efloatbuf, ptr, nv);
9725 (void)sprintf(PL_efloatbuf, ptr, (double)nv);
9727 (void)sprintf(PL_efloatbuf, ptr, nv);
9731 eptr = PL_efloatbuf;
9732 elen = strlen(PL_efloatbuf);
9738 i = SvCUR(sv) - origlen;
9739 if (args && !vectorize) {
9741 case 'h': *(va_arg(*args, short*)) = i; break;
9742 default: *(va_arg(*args, int*)) = i; break;
9743 case 'l': *(va_arg(*args, long*)) = i; break;
9744 case 'V': *(va_arg(*args, IV*)) = i; break;
9746 case 'q': *(va_arg(*args, Quad_t*)) = i; break;
9751 sv_setuv_mg(argsv, (UV)i);
9753 continue; /* not "break" */
9759 if (!args && ckWARN(WARN_PRINTF) &&
9760 (PL_op->op_type == OP_PRTF || PL_op->op_type == OP_SPRINTF)) {
9761 SV *msg = sv_newmortal();
9762 Perl_sv_setpvf(aTHX_ msg, "Invalid conversion in %sprintf: ",
9763 (PL_op->op_type == OP_PRTF) ? "" : "s");
9766 Perl_sv_catpvf(aTHX_ msg,
9767 "\"%%%c\"", c & 0xFF);
9769 Perl_sv_catpvf(aTHX_ msg,
9770 "\"%%\\%03"UVof"\"",
9773 sv_catpv(msg, "end of string");
9774 Perl_warner(aTHX_ packWARN(WARN_PRINTF), "%"SVf, msg); /* yes, this is reentrant */
9777 /* output mangled stuff ... */
9783 /* ... right here, because formatting flags should not apply */
9784 SvGROW(sv, SvCUR(sv) + elen + 1);
9786 Copy(eptr, p, elen, char);
9789 SvCUR_set(sv, p - SvPVX_const(sv));
9791 continue; /* not "break" */
9794 /* calculate width before utf8_upgrade changes it */
9795 have = esignlen + zeros + elen;
9797 if (is_utf8 != has_utf8) {
9800 sv_utf8_upgrade(sv);
9803 SV *nsv = sv_2mortal(newSVpvn(eptr, elen));
9804 sv_utf8_upgrade(nsv);
9805 eptr = SvPVX_const(nsv);
9808 SvGROW(sv, SvCUR(sv) + elen + 1);
9813 need = (have > width ? have : width);
9816 SvGROW(sv, SvCUR(sv) + need + dotstrlen + 1);
9818 if (esignlen && fill == '0') {
9819 for (i = 0; i < (int)esignlen; i++)
9823 memset(p, fill, gap);
9826 if (esignlen && fill != '0') {
9827 for (i = 0; i < (int)esignlen; i++)
9831 for (i = zeros; i; i--)
9835 Copy(eptr, p, elen, char);
9839 memset(p, ' ', gap);
9844 Copy(dotstr, p, dotstrlen, char);
9848 vectorize = FALSE; /* done iterating over vecstr */
9855 SvCUR_set(sv, p - SvPVX_const(sv));
9863 /* =========================================================================
9865 =head1 Cloning an interpreter
9867 All the macros and functions in this section are for the private use of
9868 the main function, perl_clone().
9870 The foo_dup() functions make an exact copy of an existing foo thinngy.
9871 During the course of a cloning, a hash table is used to map old addresses
9872 to new addresses. The table is created and manipulated with the
9873 ptr_table_* functions.
9877 ============================================================================*/
9880 #if defined(USE_ITHREADS)
9882 #ifndef GpREFCNT_inc
9883 # define GpREFCNT_inc(gp) ((gp) ? (++(gp)->gp_refcnt, (gp)) : (GP*)NULL)
9887 #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
9888 #define av_dup(s,t) (AV*)sv_dup((SV*)s,t)
9889 #define av_dup_inc(s,t) (AV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9890 #define hv_dup(s,t) (HV*)sv_dup((SV*)s,t)
9891 #define hv_dup_inc(s,t) (HV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9892 #define cv_dup(s,t) (CV*)sv_dup((SV*)s,t)
9893 #define cv_dup_inc(s,t) (CV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9894 #define io_dup(s,t) (IO*)sv_dup((SV*)s,t)
9895 #define io_dup_inc(s,t) (IO*)SvREFCNT_inc(sv_dup((SV*)s,t))
9896 #define gv_dup(s,t) (GV*)sv_dup((SV*)s,t)
9897 #define gv_dup_inc(s,t) (GV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9898 #define SAVEPV(p) (p ? savepv(p) : Nullch)
9899 #define SAVEPVN(p,n) (p ? savepvn(p,n) : Nullch)
9902 /* Duplicate a regexp. Required reading: pregcomp() and pregfree() in
9903 regcomp.c. AMS 20010712 */
9906 Perl_re_dup(pTHX_ REGEXP *r, CLONE_PARAMS *param)
9911 struct reg_substr_datum *s;
9914 return (REGEXP *)NULL;
9916 if ((ret = (REGEXP *)ptr_table_fetch(PL_ptr_table, r)))
9919 len = r->offsets[0];
9920 npar = r->nparens+1;
9922 Newc(0, ret, sizeof(regexp) + (len+1)*sizeof(regnode), char, regexp);
9923 Copy(r->program, ret->program, len+1, regnode);
9925 New(0, ret->startp, npar, I32);
9926 Copy(r->startp, ret->startp, npar, I32);
9927 New(0, ret->endp, npar, I32);
9928 Copy(r->startp, ret->startp, npar, I32);
9930 New(0, ret->substrs, 1, struct reg_substr_data);
9931 for (s = ret->substrs->data, i = 0; i < 3; i++, s++) {
9932 s->min_offset = r->substrs->data[i].min_offset;
9933 s->max_offset = r->substrs->data[i].max_offset;
9934 s->substr = sv_dup_inc(r->substrs->data[i].substr, param);
9935 s->utf8_substr = sv_dup_inc(r->substrs->data[i].utf8_substr, param);
9938 ret->regstclass = NULL;
9941 const int count = r->data->count;
9943 Newc(0, d, sizeof(struct reg_data) + count*sizeof(void *),
9944 char, struct reg_data);
9945 New(0, d->what, count, U8);
9948 for (i = 0; i < count; i++) {
9949 d->what[i] = r->data->what[i];
9950 switch (d->what[i]) {
9951 /* legal options are one of: sfpont
9952 see also regcomp.h and pregfree() */
9954 d->data[i] = sv_dup_inc((SV *)r->data->data[i], param);
9957 d->data[i] = av_dup_inc((AV *)r->data->data[i], param);
9960 /* This is cheating. */
9961 New(0, d->data[i], 1, struct regnode_charclass_class);
9962 StructCopy(r->data->data[i], d->data[i],
9963 struct regnode_charclass_class);
9964 ret->regstclass = (regnode*)d->data[i];
9967 /* Compiled op trees are readonly, and can thus be
9968 shared without duplication. */
9970 d->data[i] = (void*)OpREFCNT_inc((OP*)r->data->data[i]);
9974 d->data[i] = r->data->data[i];
9977 d->data[i] = r->data->data[i];
9979 ((reg_trie_data*)d->data[i])->refcount++;
9983 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", r->data->what[i]);
9992 New(0, ret->offsets, 2*len+1, U32);
9993 Copy(r->offsets, ret->offsets, 2*len+1, U32);
9995 ret->precomp = SAVEPVN(r->precomp, r->prelen);
9996 ret->refcnt = r->refcnt;
9997 ret->minlen = r->minlen;
9998 ret->prelen = r->prelen;
9999 ret->nparens = r->nparens;
10000 ret->lastparen = r->lastparen;
10001 ret->lastcloseparen = r->lastcloseparen;
10002 ret->reganch = r->reganch;
10004 ret->sublen = r->sublen;
10006 if (RX_MATCH_COPIED(ret))
10007 ret->subbeg = SAVEPVN(r->subbeg, r->sublen);
10009 ret->subbeg = Nullch;
10010 #ifdef PERL_OLD_COPY_ON_WRITE
10011 ret->saved_copy = Nullsv;
10014 ptr_table_store(PL_ptr_table, r, ret);
10018 /* duplicate a file handle */
10021 Perl_fp_dup(pTHX_ PerlIO *fp, char type, CLONE_PARAMS *param)
10027 return (PerlIO*)NULL;
10029 /* look for it in the table first */
10030 ret = (PerlIO*)ptr_table_fetch(PL_ptr_table, fp);
10034 /* create anew and remember what it is */
10035 ret = PerlIO_fdupopen(aTHX_ fp, param, PERLIO_DUP_CLONE);
10036 ptr_table_store(PL_ptr_table, fp, ret);
10040 /* duplicate a directory handle */
10043 Perl_dirp_dup(pTHX_ DIR *dp)
10051 /* duplicate a typeglob */
10054 Perl_gp_dup(pTHX_ GP *gp, CLONE_PARAMS* param)
10059 /* look for it in the table first */
10060 ret = (GP*)ptr_table_fetch(PL_ptr_table, gp);
10064 /* create anew and remember what it is */
10065 Newz(0, ret, 1, GP);
10066 ptr_table_store(PL_ptr_table, gp, ret);
10069 ret->gp_refcnt = 0; /* must be before any other dups! */
10070 ret->gp_sv = sv_dup_inc(gp->gp_sv, param);
10071 ret->gp_io = io_dup_inc(gp->gp_io, param);
10072 ret->gp_form = cv_dup_inc(gp->gp_form, param);
10073 ret->gp_av = av_dup_inc(gp->gp_av, param);
10074 ret->gp_hv = hv_dup_inc(gp->gp_hv, param);
10075 ret->gp_egv = gv_dup(gp->gp_egv, param);/* GvEGV is not refcounted */
10076 ret->gp_cv = cv_dup_inc(gp->gp_cv, param);
10077 ret->gp_cvgen = gp->gp_cvgen;
10078 ret->gp_flags = gp->gp_flags;
10079 ret->gp_line = gp->gp_line;
10080 ret->gp_file = gp->gp_file; /* points to COP.cop_file */
10084 /* duplicate a chain of magic */
10087 Perl_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS* param)
10089 MAGIC *mgprev = (MAGIC*)NULL;
10092 return (MAGIC*)NULL;
10093 /* look for it in the table first */
10094 mgret = (MAGIC*)ptr_table_fetch(PL_ptr_table, mg);
10098 for (; mg; mg = mg->mg_moremagic) {
10100 Newz(0, nmg, 1, MAGIC);
10102 mgprev->mg_moremagic = nmg;
10105 nmg->mg_virtual = mg->mg_virtual; /* XXX copy dynamic vtable? */
10106 nmg->mg_private = mg->mg_private;
10107 nmg->mg_type = mg->mg_type;
10108 nmg->mg_flags = mg->mg_flags;
10109 if (mg->mg_type == PERL_MAGIC_qr) {
10110 nmg->mg_obj = (SV*)re_dup((REGEXP*)mg->mg_obj, param);
10112 else if(mg->mg_type == PERL_MAGIC_backref) {
10113 const AV * const av = (AV*) mg->mg_obj;
10116 (void)SvREFCNT_inc(nmg->mg_obj = (SV*)newAV());
10118 for (i = AvFILLp(av); i >= 0; i--) {
10119 if (!svp[i]) continue;
10120 av_push((AV*)nmg->mg_obj,sv_dup(svp[i],param));
10123 else if (mg->mg_type == PERL_MAGIC_symtab) {
10124 nmg->mg_obj = mg->mg_obj;
10127 nmg->mg_obj = (mg->mg_flags & MGf_REFCOUNTED)
10128 ? sv_dup_inc(mg->mg_obj, param)
10129 : sv_dup(mg->mg_obj, param);
10131 nmg->mg_len = mg->mg_len;
10132 nmg->mg_ptr = mg->mg_ptr; /* XXX random ptr? */
10133 if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) {
10134 if (mg->mg_len > 0) {
10135 nmg->mg_ptr = SAVEPVN(mg->mg_ptr, mg->mg_len);
10136 if (mg->mg_type == PERL_MAGIC_overload_table &&
10137 AMT_AMAGIC((AMT*)mg->mg_ptr))
10139 AMT *amtp = (AMT*)mg->mg_ptr;
10140 AMT *namtp = (AMT*)nmg->mg_ptr;
10142 for (i = 1; i < NofAMmeth; i++) {
10143 namtp->table[i] = cv_dup_inc(amtp->table[i], param);
10147 else if (mg->mg_len == HEf_SVKEY)
10148 nmg->mg_ptr = (char*)sv_dup_inc((SV*)mg->mg_ptr, param);
10150 if ((mg->mg_flags & MGf_DUP) && mg->mg_virtual && mg->mg_virtual->svt_dup) {
10151 CALL_FPTR(nmg->mg_virtual->svt_dup)(aTHX_ nmg, param);
10158 /* create a new pointer-mapping table */
10161 Perl_ptr_table_new(pTHX)
10164 Newz(0, tbl, 1, PTR_TBL_t);
10165 tbl->tbl_max = 511;
10166 tbl->tbl_items = 0;
10167 Newz(0, tbl->tbl_ary, tbl->tbl_max + 1, PTR_TBL_ENT_t*);
10172 # define PTR_TABLE_HASH(ptr) (PTR2UV(ptr) >> 3)
10174 # define PTR_TABLE_HASH(ptr) (PTR2UV(ptr) >> 2)
10177 #define new_pte() new_body(struct ptr_tbl_ent, pte)
10178 #define del_pte(p) del_body(p, struct ptr_tbl_ent, pte)
10180 /* map an existing pointer using a table */
10183 Perl_ptr_table_fetch(pTHX_ PTR_TBL_t *tbl, void *sv)
10185 PTR_TBL_ENT_t *tblent;
10186 const UV hash = PTR_TABLE_HASH(sv);
10188 tblent = tbl->tbl_ary[hash & tbl->tbl_max];
10189 for (; tblent; tblent = tblent->next) {
10190 if (tblent->oldval == sv)
10191 return tblent->newval;
10193 return (void*)NULL;
10196 /* add a new entry to a pointer-mapping table */
10199 Perl_ptr_table_store(pTHX_ PTR_TBL_t *tbl, void *oldv, void *newv)
10201 PTR_TBL_ENT_t *tblent, **otblent;
10202 /* XXX this may be pessimal on platforms where pointers aren't good
10203 * hash values e.g. if they grow faster in the most significant
10205 const UV hash = PTR_TABLE_HASH(oldv);
10209 otblent = &tbl->tbl_ary[hash & tbl->tbl_max];
10210 for (tblent = *otblent; tblent; empty=0, tblent = tblent->next) {
10211 if (tblent->oldval == oldv) {
10212 tblent->newval = newv;
10216 tblent = new_pte();
10217 tblent->oldval = oldv;
10218 tblent->newval = newv;
10219 tblent->next = *otblent;
10222 if (!empty && tbl->tbl_items > tbl->tbl_max)
10223 ptr_table_split(tbl);
10226 /* double the hash bucket size of an existing ptr table */
10229 Perl_ptr_table_split(pTHX_ PTR_TBL_t *tbl)
10231 PTR_TBL_ENT_t **ary = tbl->tbl_ary;
10232 const UV oldsize = tbl->tbl_max + 1;
10233 UV newsize = oldsize * 2;
10236 Renew(ary, newsize, PTR_TBL_ENT_t*);
10237 Zero(&ary[oldsize], newsize-oldsize, PTR_TBL_ENT_t*);
10238 tbl->tbl_max = --newsize;
10239 tbl->tbl_ary = ary;
10240 for (i=0; i < oldsize; i++, ary++) {
10241 PTR_TBL_ENT_t **curentp, **entp, *ent;
10244 curentp = ary + oldsize;
10245 for (entp = ary, ent = *ary; ent; ent = *entp) {
10246 if ((newsize & PTR_TABLE_HASH(ent->oldval)) != i) {
10248 ent->next = *curentp;
10258 /* remove all the entries from a ptr table */
10261 Perl_ptr_table_clear(pTHX_ PTR_TBL_t *tbl)
10263 register PTR_TBL_ENT_t **array;
10264 register PTR_TBL_ENT_t *entry;
10268 if (!tbl || !tbl->tbl_items) {
10272 array = tbl->tbl_ary;
10274 max = tbl->tbl_max;
10278 PTR_TBL_ENT_t *oentry = entry;
10279 entry = entry->next;
10283 if (++riter > max) {
10286 entry = array[riter];
10290 tbl->tbl_items = 0;
10293 /* clear and free a ptr table */
10296 Perl_ptr_table_free(pTHX_ PTR_TBL_t *tbl)
10301 ptr_table_clear(tbl);
10302 Safefree(tbl->tbl_ary);
10306 /* attempt to make everything in the typeglob readonly */
10309 S_gv_share(pTHX_ SV *sstr, CLONE_PARAMS *param)
10311 GV *gv = (GV*)sstr;
10312 SV *sv = ¶m->proto_perl->Isv_no; /* just need SvREADONLY-ness */
10314 if (GvIO(gv) || GvFORM(gv)) {
10315 GvUNIQUE_off(gv); /* GvIOs cannot be shared. nor can GvFORMs */
10317 else if (!GvCV(gv)) {
10318 GvCV(gv) = (CV*)sv;
10321 /* CvPADLISTs cannot be shared */
10322 if (!SvREADONLY(GvCV(gv)) && !CvXSUB(GvCV(gv))) {
10327 if (!GvUNIQUE(gv)) {
10329 PerlIO_printf(Perl_debug_log, "gv_share: unable to share %s::%s\n",
10330 HvNAME_get(GvSTASH(gv)), GvNAME(gv));
10336 * write attempts will die with
10337 * "Modification of a read-only value attempted"
10343 SvREADONLY_on(GvSV(gv));
10347 GvAV(gv) = (AV*)sv;
10350 SvREADONLY_on(GvAV(gv));
10354 GvHV(gv) = (HV*)sv;
10357 SvREADONLY_on(GvHV(gv));
10360 return sstr; /* he_dup() will SvREFCNT_inc() */
10363 /* duplicate an SV of any type (including AV, HV etc) */
10366 Perl_rvpv_dup(pTHX_ SV *dstr, SV *sstr, CLONE_PARAMS* param)
10369 SvRV_set(dstr, SvWEAKREF(sstr)
10370 ? sv_dup(SvRV(sstr), param)
10371 : sv_dup_inc(SvRV(sstr), param));
10374 else if (SvPVX_const(sstr)) {
10375 /* Has something there */
10377 /* Normal PV - clone whole allocated space */
10378 SvPV_set(dstr, SAVEPVN(SvPVX_const(sstr), SvLEN(sstr)-1));
10379 if (SvREADONLY(sstr) && SvFAKE(sstr)) {
10380 /* Not that normal - actually sstr is copy on write.
10381 But we are a true, independant SV, so: */
10382 SvREADONLY_off(dstr);
10387 /* Special case - not normally malloced for some reason */
10388 if ((SvREADONLY(sstr) && SvFAKE(sstr))) {
10389 /* A "shared" PV - clone it as "shared" PV */
10391 HEK_KEY(hek_dup(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)),
10395 /* Some other special case - random pointer */
10396 SvPV_set(dstr, SvPVX(sstr));
10401 /* Copy the Null */
10402 if (SvTYPE(dstr) == SVt_RV)
10403 SvRV_set(dstr, NULL);
10410 Perl_sv_dup(pTHX_ SV *sstr, CLONE_PARAMS* param)
10415 if (!sstr || SvTYPE(sstr) == SVTYPEMASK)
10417 /* look for it in the table first */
10418 dstr = (SV*)ptr_table_fetch(PL_ptr_table, sstr);
10422 if(param->flags & CLONEf_JOIN_IN) {
10423 /** We are joining here so we don't want do clone
10424 something that is bad **/
10425 const char *hvname;
10427 if(SvTYPE(sstr) == SVt_PVHV &&
10428 (hvname = HvNAME_get(sstr))) {
10429 /** don't clone stashes if they already exist **/
10430 HV* old_stash = gv_stashpv(hvname,0);
10431 return (SV*) old_stash;
10435 /* create anew and remember what it is */
10438 #ifdef DEBUG_LEAKING_SCALARS
10439 dstr->sv_debug_optype = sstr->sv_debug_optype;
10440 dstr->sv_debug_line = sstr->sv_debug_line;
10441 dstr->sv_debug_inpad = sstr->sv_debug_inpad;
10442 dstr->sv_debug_cloned = 1;
10444 dstr->sv_debug_file = savepv(sstr->sv_debug_file);
10446 dstr->sv_debug_file = savesharedpv(sstr->sv_debug_file);
10450 ptr_table_store(PL_ptr_table, sstr, dstr);
10453 SvFLAGS(dstr) = SvFLAGS(sstr);
10454 SvFLAGS(dstr) &= ~SVf_OOK; /* don't propagate OOK hack */
10455 SvREFCNT(dstr) = 0; /* must be before any other dups! */
10458 if (SvANY(sstr) && PL_watch_pvx && SvPVX_const(sstr) == PL_watch_pvx)
10459 PerlIO_printf(Perl_debug_log, "watch at %p hit, found string \"%s\"\n",
10460 PL_watch_pvx, SvPVX_const(sstr));
10463 /* don't clone objects whose class has asked us not to */
10464 if (SvOBJECT(sstr) && ! (SvFLAGS(SvSTASH(sstr)) & SVphv_CLONEABLE)) {
10465 SvFLAGS(dstr) &= ~SVTYPEMASK;
10466 SvOBJECT_off(dstr);
10470 switch (SvTYPE(sstr)) {
10472 SvANY(dstr) = NULL;
10475 SvANY(dstr) = (XPVIV*)((char*)&(dstr->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
10476 SvIV_set(dstr, SvIVX(sstr));
10479 SvANY(dstr) = new_XNV();
10480 SvNV_set(dstr, SvNVX(sstr));
10483 SvANY(dstr) = &(dstr->sv_u.svu_rv);
10484 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10487 SvANY(dstr) = new_XPV();
10488 SvCUR_set(dstr, SvCUR(sstr));
10489 SvLEN_set(dstr, SvLEN(sstr));
10490 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10493 SvANY(dstr) = new_XPVIV();
10494 SvCUR_set(dstr, SvCUR(sstr));
10495 SvLEN_set(dstr, SvLEN(sstr));
10496 SvIV_set(dstr, SvIVX(sstr));
10497 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10500 SvANY(dstr) = new_XPVNV();
10501 SvCUR_set(dstr, SvCUR(sstr));
10502 SvLEN_set(dstr, SvLEN(sstr));
10503 SvIV_set(dstr, SvIVX(sstr));
10504 SvNV_set(dstr, SvNVX(sstr));
10505 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10508 SvANY(dstr) = new_XPVMG();
10509 SvCUR_set(dstr, SvCUR(sstr));
10510 SvLEN_set(dstr, SvLEN(sstr));
10511 SvIV_set(dstr, SvIVX(sstr));
10512 SvNV_set(dstr, SvNVX(sstr));
10513 SvMAGIC_set(dstr, mg_dup(SvMAGIC(sstr), param));
10514 SvSTASH_set(dstr, hv_dup_inc(SvSTASH(sstr), param));
10515 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10518 SvANY(dstr) = new_XPVBM();
10519 SvCUR_set(dstr, SvCUR(sstr));
10520 SvLEN_set(dstr, SvLEN(sstr));
10521 SvIV_set(dstr, SvIVX(sstr));
10522 SvNV_set(dstr, SvNVX(sstr));
10523 SvMAGIC_set(dstr, mg_dup(SvMAGIC(sstr), param));
10524 SvSTASH_set(dstr, hv_dup_inc(SvSTASH(sstr), param));
10525 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10526 BmRARE(dstr) = BmRARE(sstr);
10527 BmUSEFUL(dstr) = BmUSEFUL(sstr);
10528 BmPREVIOUS(dstr)= BmPREVIOUS(sstr);
10531 SvANY(dstr) = new_XPVLV();
10532 SvCUR_set(dstr, SvCUR(sstr));
10533 SvLEN_set(dstr, SvLEN(sstr));
10534 SvIV_set(dstr, SvIVX(sstr));
10535 SvNV_set(dstr, SvNVX(sstr));
10536 SvMAGIC_set(dstr, mg_dup(SvMAGIC(sstr), param));
10537 SvSTASH_set(dstr, hv_dup_inc(SvSTASH(sstr), param));
10538 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10539 LvTARGOFF(dstr) = LvTARGOFF(sstr); /* XXX sometimes holds PMOP* when DEBUGGING */
10540 LvTARGLEN(dstr) = LvTARGLEN(sstr);
10541 if (LvTYPE(sstr) == 't') /* for tie: unrefcnted fake (SV**) */
10542 LvTARG(dstr) = dstr;
10543 else if (LvTYPE(sstr) == 'T') /* for tie: fake HE */
10544 LvTARG(dstr) = (SV*)he_dup((HE*)LvTARG(sstr), 0, param);
10546 LvTARG(dstr) = sv_dup_inc(LvTARG(sstr), param);
10547 LvTYPE(dstr) = LvTYPE(sstr);
10550 if (GvUNIQUE((GV*)sstr)) {
10552 if ((share = gv_share(sstr, param))) {
10555 ptr_table_store(PL_ptr_table, sstr, dstr);
10557 PerlIO_printf(Perl_debug_log, "sv_dup: sharing %s::%s\n",
10558 HvNAME_get(GvSTASH(share)), GvNAME(share));
10563 SvANY(dstr) = new_XPVGV();
10564 SvCUR_set(dstr, SvCUR(sstr));
10565 SvLEN_set(dstr, SvLEN(sstr));
10566 SvIV_set(dstr, SvIVX(sstr));
10567 SvNV_set(dstr, SvNVX(sstr));
10568 SvMAGIC_set(dstr, mg_dup(SvMAGIC(sstr), param));
10569 SvSTASH_set(dstr, hv_dup_inc(SvSTASH(sstr), param));
10570 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10571 GvNAMELEN(dstr) = GvNAMELEN(sstr);
10572 GvNAME(dstr) = SAVEPVN(GvNAME(sstr), GvNAMELEN(sstr));
10573 GvSTASH(dstr) = hv_dup_inc(GvSTASH(sstr), param);
10574 GvFLAGS(dstr) = GvFLAGS(sstr);
10575 GvGP(dstr) = gp_dup(GvGP(sstr), param);
10576 (void)GpREFCNT_inc(GvGP(dstr));
10579 SvANY(dstr) = new_XPVIO();
10580 SvCUR_set(dstr, SvCUR(sstr));
10581 SvLEN_set(dstr, SvLEN(sstr));
10582 SvIV_set(dstr, SvIVX(sstr));
10583 SvNV_set(dstr, SvNVX(sstr));
10584 SvMAGIC_set(dstr, mg_dup(SvMAGIC(sstr), param));
10585 SvSTASH_set(dstr, hv_dup_inc(SvSTASH(sstr), param));
10586 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10587 IoIFP(dstr) = fp_dup(IoIFP(sstr), IoTYPE(sstr), param);
10588 if (IoOFP(sstr) == IoIFP(sstr))
10589 IoOFP(dstr) = IoIFP(dstr);
10591 IoOFP(dstr) = fp_dup(IoOFP(sstr), IoTYPE(sstr), param);
10592 /* PL_rsfp_filters entries have fake IoDIRP() */
10593 if (IoDIRP(sstr) && !(IoFLAGS(sstr) & IOf_FAKE_DIRP))
10594 IoDIRP(dstr) = dirp_dup(IoDIRP(sstr));
10596 IoDIRP(dstr) = IoDIRP(sstr);
10597 IoLINES(dstr) = IoLINES(sstr);
10598 IoPAGE(dstr) = IoPAGE(sstr);
10599 IoPAGE_LEN(dstr) = IoPAGE_LEN(sstr);
10600 IoLINES_LEFT(dstr) = IoLINES_LEFT(sstr);
10601 if(IoFLAGS(sstr) & IOf_FAKE_DIRP) {
10602 /* I have no idea why fake dirp (rsfps)
10603 should be treaded differently but otherwise
10604 we end up with leaks -- sky*/
10605 IoTOP_GV(dstr) = gv_dup_inc(IoTOP_GV(sstr), param);
10606 IoFMT_GV(dstr) = gv_dup_inc(IoFMT_GV(sstr), param);
10607 IoBOTTOM_GV(dstr) = gv_dup_inc(IoBOTTOM_GV(sstr), param);
10609 IoTOP_GV(dstr) = gv_dup(IoTOP_GV(sstr), param);
10610 IoFMT_GV(dstr) = gv_dup(IoFMT_GV(sstr), param);
10611 IoBOTTOM_GV(dstr) = gv_dup(IoBOTTOM_GV(sstr), param);
10613 IoTOP_NAME(dstr) = SAVEPV(IoTOP_NAME(sstr));
10614 IoFMT_NAME(dstr) = SAVEPV(IoFMT_NAME(sstr));
10615 IoBOTTOM_NAME(dstr) = SAVEPV(IoBOTTOM_NAME(sstr));
10616 IoSUBPROCESS(dstr) = IoSUBPROCESS(sstr);
10617 IoTYPE(dstr) = IoTYPE(sstr);
10618 IoFLAGS(dstr) = IoFLAGS(sstr);
10621 SvANY(dstr) = new_XPVAV();
10622 SvCUR_set(dstr, SvCUR(sstr));
10623 SvLEN_set(dstr, SvLEN(sstr));
10624 SvMAGIC_set(dstr, mg_dup(SvMAGIC(sstr), param));
10625 SvSTASH_set(dstr, hv_dup_inc(SvSTASH(sstr), param));
10626 if (AvARRAY((AV*)sstr)) {
10627 SV **dst_ary, **src_ary;
10628 SSize_t items = AvFILLp((AV*)sstr) + 1;
10630 src_ary = AvARRAY((AV*)sstr);
10631 Newz(0, dst_ary, AvMAX((AV*)sstr)+1, SV*);
10632 ptr_table_store(PL_ptr_table, src_ary, dst_ary);
10633 SvPV_set(dstr, (char*)dst_ary);
10634 AvALLOC((AV*)dstr) = dst_ary;
10635 if (AvREAL((AV*)sstr)) {
10636 while (items-- > 0)
10637 *dst_ary++ = sv_dup_inc(*src_ary++, param);
10640 while (items-- > 0)
10641 *dst_ary++ = sv_dup(*src_ary++, param);
10643 items = AvMAX((AV*)sstr) - AvFILLp((AV*)sstr);
10644 while (items-- > 0) {
10645 *dst_ary++ = &PL_sv_undef;
10649 SvPV_set(dstr, Nullch);
10650 AvALLOC((AV*)dstr) = (SV**)NULL;
10654 SvANY(dstr) = new_XPVHV();
10655 SvCUR_set(dstr, SvCUR(sstr));
10656 SvLEN_set(dstr, SvLEN(sstr));
10657 HvTOTALKEYS(dstr) = HvTOTALKEYS(sstr);
10658 SvMAGIC_set(dstr, mg_dup(SvMAGIC(sstr), param));
10659 SvSTASH_set(dstr, hv_dup_inc(SvSTASH(sstr), param));
10663 if (HvARRAY((HV*)sstr)) {
10665 const bool sharekeys = !!HvSHAREKEYS(sstr);
10666 XPVHV * const dxhv = (XPVHV*)SvANY(dstr);
10667 XPVHV * const sxhv = (XPVHV*)SvANY(sstr);
10670 PERL_HV_ARRAY_ALLOC_BYTES(dxhv->xhv_max+1)
10671 + (SvOOK(sstr) ? sizeof(struct xpvhv_aux) : 0), char);
10672 HvARRAY(dstr) = (HE**)darray;
10673 while (i <= sxhv->xhv_max) {
10674 HE *source = HvARRAY(sstr)[i];
10676 = source ? he_dup(source, sharekeys, param) : 0;
10680 struct xpvhv_aux *saux = HvAUX(sstr);
10681 struct xpvhv_aux *daux = HvAUX(dstr);
10682 /* This flag isn't copied. */
10683 /* SvOOK_on(hv) attacks the IV flags. */
10684 SvFLAGS(dstr) |= SVf_OOK;
10686 hvname = saux->xhv_name;
10687 daux->xhv_name = hvname ? hek_dup(hvname, param) : hvname;
10689 daux->xhv_riter = saux->xhv_riter;
10690 daux->xhv_eiter = saux->xhv_eiter
10691 ? he_dup(saux->xhv_eiter, (bool)!!HvSHAREKEYS(sstr),
10696 SvPV_set(dstr, Nullch);
10698 /* Record stashes for possible cloning in Perl_clone(). */
10700 av_push(param->stashes, dstr);
10704 SvANY(dstr) = new_XPVFM();
10705 FmLINES(dstr) = FmLINES(sstr);
10709 SvANY(dstr) = new_XPVCV();
10711 SvCUR_set(dstr, SvCUR(sstr));
10712 SvLEN_set(dstr, SvLEN(sstr));
10713 SvIV_set(dstr, SvIVX(sstr));
10714 SvNV_set(dstr, SvNVX(sstr));
10715 SvMAGIC_set(dstr, mg_dup(SvMAGIC(sstr), param));
10716 SvSTASH_set(dstr, hv_dup_inc(SvSTASH(sstr), param));
10717 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
10718 CvSTASH(dstr) = hv_dup(CvSTASH(sstr), param); /* NOTE: not refcounted */
10719 CvSTART(dstr) = CvSTART(sstr);
10721 CvROOT(dstr) = OpREFCNT_inc(CvROOT(sstr));
10723 CvXSUB(dstr) = CvXSUB(sstr);
10724 CvXSUBANY(dstr) = CvXSUBANY(sstr);
10725 if (CvCONST(sstr)) {
10726 CvXSUBANY(dstr).any_ptr = GvUNIQUE(CvGV(sstr)) ?
10727 SvREFCNT_inc(CvXSUBANY(sstr).any_ptr) :
10728 sv_dup_inc((SV *)CvXSUBANY(sstr).any_ptr, param);
10730 /* don't dup if copying back - CvGV isn't refcounted, so the
10731 * duped GV may never be freed. A bit of a hack! DAPM */
10732 CvGV(dstr) = (param->flags & CLONEf_JOIN_IN) ?
10733 Nullgv : gv_dup(CvGV(sstr), param) ;
10734 if (param->flags & CLONEf_COPY_STACKS) {
10735 CvDEPTH(dstr) = CvDEPTH(sstr);
10739 PAD_DUP(CvPADLIST(dstr), CvPADLIST(sstr), param);
10740 CvOUTSIDE_SEQ(dstr) = CvOUTSIDE_SEQ(sstr);
10742 CvWEAKOUTSIDE(sstr)
10743 ? cv_dup( CvOUTSIDE(sstr), param)
10744 : cv_dup_inc(CvOUTSIDE(sstr), param);
10745 CvFLAGS(dstr) = CvFLAGS(sstr);
10746 CvFILE(dstr) = CvXSUB(sstr) ? CvFILE(sstr) : SAVEPV(CvFILE(sstr));
10749 Perl_croak(aTHX_ "Bizarre SvTYPE [%" IVdf "]", (IV)SvTYPE(sstr));
10753 if (SvOBJECT(dstr) && SvTYPE(dstr) != SVt_PVIO)
10759 /* duplicate a context */
10762 Perl_cx_dup(pTHX_ PERL_CONTEXT *cxs, I32 ix, I32 max, CLONE_PARAMS* param)
10764 PERL_CONTEXT *ncxs;
10767 return (PERL_CONTEXT*)NULL;
10769 /* look for it in the table first */
10770 ncxs = (PERL_CONTEXT*)ptr_table_fetch(PL_ptr_table, cxs);
10774 /* create anew and remember what it is */
10775 Newz(56, ncxs, max + 1, PERL_CONTEXT);
10776 ptr_table_store(PL_ptr_table, cxs, ncxs);
10779 PERL_CONTEXT *cx = &cxs[ix];
10780 PERL_CONTEXT *ncx = &ncxs[ix];
10781 ncx->cx_type = cx->cx_type;
10782 if (CxTYPE(cx) == CXt_SUBST) {
10783 Perl_croak(aTHX_ "Cloning substitution context is unimplemented");
10786 ncx->blk_oldsp = cx->blk_oldsp;
10787 ncx->blk_oldcop = cx->blk_oldcop;
10788 ncx->blk_oldmarksp = cx->blk_oldmarksp;
10789 ncx->blk_oldscopesp = cx->blk_oldscopesp;
10790 ncx->blk_oldpm = cx->blk_oldpm;
10791 ncx->blk_gimme = cx->blk_gimme;
10792 switch (CxTYPE(cx)) {
10794 ncx->blk_sub.cv = (cx->blk_sub.olddepth == 0
10795 ? cv_dup_inc(cx->blk_sub.cv, param)
10796 : cv_dup(cx->blk_sub.cv,param));
10797 ncx->blk_sub.argarray = (cx->blk_sub.hasargs
10798 ? av_dup_inc(cx->blk_sub.argarray, param)
10800 ncx->blk_sub.savearray = av_dup_inc(cx->blk_sub.savearray, param);
10801 ncx->blk_sub.olddepth = cx->blk_sub.olddepth;
10802 ncx->blk_sub.hasargs = cx->blk_sub.hasargs;
10803 ncx->blk_sub.lval = cx->blk_sub.lval;
10804 ncx->blk_sub.retop = cx->blk_sub.retop;
10807 ncx->blk_eval.old_in_eval = cx->blk_eval.old_in_eval;
10808 ncx->blk_eval.old_op_type = cx->blk_eval.old_op_type;
10809 ncx->blk_eval.old_namesv = sv_dup_inc(cx->blk_eval.old_namesv, param);
10810 ncx->blk_eval.old_eval_root = cx->blk_eval.old_eval_root;
10811 ncx->blk_eval.cur_text = sv_dup(cx->blk_eval.cur_text, param);
10812 ncx->blk_eval.retop = cx->blk_eval.retop;
10815 ncx->blk_loop.label = cx->blk_loop.label;
10816 ncx->blk_loop.resetsp = cx->blk_loop.resetsp;
10817 ncx->blk_loop.redo_op = cx->blk_loop.redo_op;
10818 ncx->blk_loop.next_op = cx->blk_loop.next_op;
10819 ncx->blk_loop.last_op = cx->blk_loop.last_op;
10820 ncx->blk_loop.iterdata = (CxPADLOOP(cx)
10821 ? cx->blk_loop.iterdata
10822 : gv_dup((GV*)cx->blk_loop.iterdata, param));
10823 ncx->blk_loop.oldcomppad
10824 = (PAD*)ptr_table_fetch(PL_ptr_table,
10825 cx->blk_loop.oldcomppad);
10826 ncx->blk_loop.itersave = sv_dup_inc(cx->blk_loop.itersave, param);
10827 ncx->blk_loop.iterlval = sv_dup_inc(cx->blk_loop.iterlval, param);
10828 ncx->blk_loop.iterary = av_dup_inc(cx->blk_loop.iterary, param);
10829 ncx->blk_loop.iterix = cx->blk_loop.iterix;
10830 ncx->blk_loop.itermax = cx->blk_loop.itermax;
10833 ncx->blk_sub.cv = cv_dup(cx->blk_sub.cv, param);
10834 ncx->blk_sub.gv = gv_dup(cx->blk_sub.gv, param);
10835 ncx->blk_sub.dfoutgv = gv_dup_inc(cx->blk_sub.dfoutgv, param);
10836 ncx->blk_sub.hasargs = cx->blk_sub.hasargs;
10837 ncx->blk_sub.retop = cx->blk_sub.retop;
10849 /* duplicate a stack info structure */
10852 Perl_si_dup(pTHX_ PERL_SI *si, CLONE_PARAMS* param)
10857 return (PERL_SI*)NULL;
10859 /* look for it in the table first */
10860 nsi = (PERL_SI*)ptr_table_fetch(PL_ptr_table, si);
10864 /* create anew and remember what it is */
10865 Newz(56, nsi, 1, PERL_SI);
10866 ptr_table_store(PL_ptr_table, si, nsi);
10868 nsi->si_stack = av_dup_inc(si->si_stack, param);
10869 nsi->si_cxix = si->si_cxix;
10870 nsi->si_cxmax = si->si_cxmax;
10871 nsi->si_cxstack = cx_dup(si->si_cxstack, si->si_cxix, si->si_cxmax, param);
10872 nsi->si_type = si->si_type;
10873 nsi->si_prev = si_dup(si->si_prev, param);
10874 nsi->si_next = si_dup(si->si_next, param);
10875 nsi->si_markoff = si->si_markoff;
10880 #define POPINT(ss,ix) ((ss)[--(ix)].any_i32)
10881 #define TOPINT(ss,ix) ((ss)[ix].any_i32)
10882 #define POPLONG(ss,ix) ((ss)[--(ix)].any_long)
10883 #define TOPLONG(ss,ix) ((ss)[ix].any_long)
10884 #define POPIV(ss,ix) ((ss)[--(ix)].any_iv)
10885 #define TOPIV(ss,ix) ((ss)[ix].any_iv)
10886 #define POPBOOL(ss,ix) ((ss)[--(ix)].any_bool)
10887 #define TOPBOOL(ss,ix) ((ss)[ix].any_bool)
10888 #define POPPTR(ss,ix) ((ss)[--(ix)].any_ptr)
10889 #define TOPPTR(ss,ix) ((ss)[ix].any_ptr)
10890 #define POPDPTR(ss,ix) ((ss)[--(ix)].any_dptr)
10891 #define TOPDPTR(ss,ix) ((ss)[ix].any_dptr)
10892 #define POPDXPTR(ss,ix) ((ss)[--(ix)].any_dxptr)
10893 #define TOPDXPTR(ss,ix) ((ss)[ix].any_dxptr)
10896 #define pv_dup_inc(p) SAVEPV(p)
10897 #define pv_dup(p) SAVEPV(p)
10898 #define svp_dup_inc(p,pp) any_dup(p,pp)
10900 /* map any object to the new equivent - either something in the
10901 * ptr table, or something in the interpreter structure
10905 Perl_any_dup(pTHX_ void *v, PerlInterpreter *proto_perl)
10910 return (void*)NULL;
10912 /* look for it in the table first */
10913 ret = ptr_table_fetch(PL_ptr_table, v);
10917 /* see if it is part of the interpreter structure */
10918 if (v >= (void*)proto_perl && v < (void*)(proto_perl+1))
10919 ret = (void*)(((char*)aTHX) + (((char*)v) - (char*)proto_perl));
10927 /* duplicate the save stack */
10930 Perl_ss_dup(pTHX_ PerlInterpreter *proto_perl, CLONE_PARAMS* param)
10932 ANY *ss = proto_perl->Tsavestack;
10933 I32 ix = proto_perl->Tsavestack_ix;
10934 I32 max = proto_perl->Tsavestack_max;
10946 void (*dptr) (void*);
10947 void (*dxptr) (pTHX_ void*);
10950 Newz(54, nss, max, ANY);
10953 I32 i = POPINT(ss,ix);
10954 TOPINT(nss,ix) = i;
10956 case SAVEt_ITEM: /* normal string */
10957 sv = (SV*)POPPTR(ss,ix);
10958 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10959 sv = (SV*)POPPTR(ss,ix);
10960 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10962 case SAVEt_SV: /* scalar reference */
10963 sv = (SV*)POPPTR(ss,ix);
10964 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10965 gv = (GV*)POPPTR(ss,ix);
10966 TOPPTR(nss,ix) = gv_dup_inc(gv, param);
10968 case SAVEt_GENERIC_PVREF: /* generic char* */
10969 c = (char*)POPPTR(ss,ix);
10970 TOPPTR(nss,ix) = pv_dup(c);
10971 ptr = POPPTR(ss,ix);
10972 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10974 case SAVEt_SHARED_PVREF: /* char* in shared space */
10975 c = (char*)POPPTR(ss,ix);
10976 TOPPTR(nss,ix) = savesharedpv(c);
10977 ptr = POPPTR(ss,ix);
10978 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10980 case SAVEt_GENERIC_SVREF: /* generic sv */
10981 case SAVEt_SVREF: /* scalar reference */
10982 sv = (SV*)POPPTR(ss,ix);
10983 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10984 ptr = POPPTR(ss,ix);
10985 TOPPTR(nss,ix) = svp_dup_inc((SV**)ptr, proto_perl);/* XXXXX */
10987 case SAVEt_AV: /* array reference */
10988 av = (AV*)POPPTR(ss,ix);
10989 TOPPTR(nss,ix) = av_dup_inc(av, param);
10990 gv = (GV*)POPPTR(ss,ix);
10991 TOPPTR(nss,ix) = gv_dup(gv, param);
10993 case SAVEt_HV: /* hash reference */
10994 hv = (HV*)POPPTR(ss,ix);
10995 TOPPTR(nss,ix) = hv_dup_inc(hv, param);
10996 gv = (GV*)POPPTR(ss,ix);
10997 TOPPTR(nss,ix) = gv_dup(gv, param);
10999 case SAVEt_INT: /* int reference */
11000 ptr = POPPTR(ss,ix);
11001 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11002 intval = (int)POPINT(ss,ix);
11003 TOPINT(nss,ix) = intval;
11005 case SAVEt_LONG: /* long reference */
11006 ptr = POPPTR(ss,ix);
11007 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11008 longval = (long)POPLONG(ss,ix);
11009 TOPLONG(nss,ix) = longval;
11011 case SAVEt_I32: /* I32 reference */
11012 case SAVEt_I16: /* I16 reference */
11013 case SAVEt_I8: /* I8 reference */
11014 ptr = POPPTR(ss,ix);
11015 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11017 TOPINT(nss,ix) = i;
11019 case SAVEt_IV: /* IV reference */
11020 ptr = POPPTR(ss,ix);
11021 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11023 TOPIV(nss,ix) = iv;
11025 case SAVEt_SPTR: /* SV* reference */
11026 ptr = POPPTR(ss,ix);
11027 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11028 sv = (SV*)POPPTR(ss,ix);
11029 TOPPTR(nss,ix) = sv_dup(sv, param);
11031 case SAVEt_VPTR: /* random* reference */
11032 ptr = POPPTR(ss,ix);
11033 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11034 ptr = POPPTR(ss,ix);
11035 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11037 case SAVEt_PPTR: /* char* reference */
11038 ptr = POPPTR(ss,ix);
11039 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11040 c = (char*)POPPTR(ss,ix);
11041 TOPPTR(nss,ix) = pv_dup(c);
11043 case SAVEt_HPTR: /* HV* reference */
11044 ptr = POPPTR(ss,ix);
11045 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11046 hv = (HV*)POPPTR(ss,ix);
11047 TOPPTR(nss,ix) = hv_dup(hv, param);
11049 case SAVEt_APTR: /* AV* reference */
11050 ptr = POPPTR(ss,ix);
11051 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11052 av = (AV*)POPPTR(ss,ix);
11053 TOPPTR(nss,ix) = av_dup(av, param);
11056 gv = (GV*)POPPTR(ss,ix);
11057 TOPPTR(nss,ix) = gv_dup(gv, param);
11059 case SAVEt_GP: /* scalar reference */
11060 gp = (GP*)POPPTR(ss,ix);
11061 TOPPTR(nss,ix) = gp = gp_dup(gp, param);
11062 (void)GpREFCNT_inc(gp);
11063 gv = (GV*)POPPTR(ss,ix);
11064 TOPPTR(nss,ix) = gv_dup_inc(gv, param);
11065 c = (char*)POPPTR(ss,ix);
11066 TOPPTR(nss,ix) = pv_dup(c);
11068 TOPIV(nss,ix) = iv;
11070 TOPIV(nss,ix) = iv;
11073 case SAVEt_MORTALIZESV:
11074 sv = (SV*)POPPTR(ss,ix);
11075 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
11078 ptr = POPPTR(ss,ix);
11079 if (ptr && (((OP*)ptr)->op_private & OPpREFCOUNTED)) {
11080 /* these are assumed to be refcounted properly */
11081 switch (((OP*)ptr)->op_type) {
11083 case OP_LEAVESUBLV:
11087 case OP_LEAVEWRITE:
11088 TOPPTR(nss,ix) = ptr;
11093 TOPPTR(nss,ix) = Nullop;
11098 TOPPTR(nss,ix) = Nullop;
11101 c = (char*)POPPTR(ss,ix);
11102 TOPPTR(nss,ix) = pv_dup_inc(c);
11104 case SAVEt_CLEARSV:
11105 longval = POPLONG(ss,ix);
11106 TOPLONG(nss,ix) = longval;
11109 hv = (HV*)POPPTR(ss,ix);
11110 TOPPTR(nss,ix) = hv_dup_inc(hv, param);
11111 c = (char*)POPPTR(ss,ix);
11112 TOPPTR(nss,ix) = pv_dup_inc(c);
11114 TOPINT(nss,ix) = i;
11116 case SAVEt_DESTRUCTOR:
11117 ptr = POPPTR(ss,ix);
11118 TOPPTR(nss,ix) = any_dup(ptr, proto_perl); /* XXX quite arbitrary */
11119 dptr = POPDPTR(ss,ix);
11120 TOPDPTR(nss,ix) = DPTR2FPTR(void (*)(void*),
11121 any_dup(FPTR2DPTR(void *, dptr),
11124 case SAVEt_DESTRUCTOR_X:
11125 ptr = POPPTR(ss,ix);
11126 TOPPTR(nss,ix) = any_dup(ptr, proto_perl); /* XXX quite arbitrary */
11127 dxptr = POPDXPTR(ss,ix);
11128 TOPDXPTR(nss,ix) = DPTR2FPTR(void (*)(pTHX_ void*),
11129 any_dup(FPTR2DPTR(void *, dxptr),
11132 case SAVEt_REGCONTEXT:
11135 TOPINT(nss,ix) = i;
11138 case SAVEt_STACK_POS: /* Position on Perl stack */
11140 TOPINT(nss,ix) = i;
11142 case SAVEt_AELEM: /* array element */
11143 sv = (SV*)POPPTR(ss,ix);
11144 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
11146 TOPINT(nss,ix) = i;
11147 av = (AV*)POPPTR(ss,ix);
11148 TOPPTR(nss,ix) = av_dup_inc(av, param);
11150 case SAVEt_HELEM: /* hash element */
11151 sv = (SV*)POPPTR(ss,ix);
11152 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
11153 sv = (SV*)POPPTR(ss,ix);
11154 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
11155 hv = (HV*)POPPTR(ss,ix);
11156 TOPPTR(nss,ix) = hv_dup_inc(hv, param);
11159 ptr = POPPTR(ss,ix);
11160 TOPPTR(nss,ix) = ptr;
11164 TOPINT(nss,ix) = i;
11166 case SAVEt_COMPPAD:
11167 av = (AV*)POPPTR(ss,ix);
11168 TOPPTR(nss,ix) = av_dup(av, param);
11171 longval = (long)POPLONG(ss,ix);
11172 TOPLONG(nss,ix) = longval;
11173 ptr = POPPTR(ss,ix);
11174 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11175 sv = (SV*)POPPTR(ss,ix);
11176 TOPPTR(nss,ix) = sv_dup(sv, param);
11179 ptr = POPPTR(ss,ix);
11180 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
11181 longval = (long)POPBOOL(ss,ix);
11182 TOPBOOL(nss,ix) = (bool)longval;
11184 case SAVEt_SET_SVFLAGS:
11186 TOPINT(nss,ix) = i;
11188 TOPINT(nss,ix) = i;
11189 sv = (SV*)POPPTR(ss,ix);
11190 TOPPTR(nss,ix) = sv_dup(sv, param);
11193 Perl_croak(aTHX_ "panic: ss_dup inconsistency");
11201 /* if sv is a stash, call $class->CLONE_SKIP(), and set the SVphv_CLONEABLE
11202 * flag to the result. This is done for each stash before cloning starts,
11203 * so we know which stashes want their objects cloned */
11206 do_mark_cloneable_stash(pTHX_ SV *sv)
11208 const HEK *hvname = HvNAME_HEK((HV*)sv);
11210 GV* cloner = gv_fetchmethod_autoload((HV*)sv, "CLONE_SKIP", 0);
11211 SvFLAGS(sv) |= SVphv_CLONEABLE; /* clone objects by default */
11212 if (cloner && GvCV(cloner)) {
11219 XPUSHs(sv_2mortal(newSVhek(hvname)));
11221 call_sv((SV*)GvCV(cloner), G_SCALAR);
11228 SvFLAGS(sv) &= ~SVphv_CLONEABLE;
11236 =for apidoc perl_clone
11238 Create and return a new interpreter by cloning the current one.
11240 perl_clone takes these flags as parameters:
11242 CLONEf_COPY_STACKS - is used to, well, copy the stacks also,
11243 without it we only clone the data and zero the stacks,
11244 with it we copy the stacks and the new perl interpreter is
11245 ready to run at the exact same point as the previous one.
11246 The pseudo-fork code uses COPY_STACKS while the
11247 threads->new doesn't.
11249 CLONEf_KEEP_PTR_TABLE
11250 perl_clone keeps a ptr_table with the pointer of the old
11251 variable as a key and the new variable as a value,
11252 this allows it to check if something has been cloned and not
11253 clone it again but rather just use the value and increase the
11254 refcount. If KEEP_PTR_TABLE is not set then perl_clone will kill
11255 the ptr_table using the function
11256 C<ptr_table_free(PL_ptr_table); PL_ptr_table = NULL;>,
11257 reason to keep it around is if you want to dup some of your own
11258 variable who are outside the graph perl scans, example of this
11259 code is in threads.xs create
11262 This is a win32 thing, it is ignored on unix, it tells perls
11263 win32host code (which is c++) to clone itself, this is needed on
11264 win32 if you want to run two threads at the same time,
11265 if you just want to do some stuff in a separate perl interpreter
11266 and then throw it away and return to the original one,
11267 you don't need to do anything.
11272 /* XXX the above needs expanding by someone who actually understands it ! */
11273 EXTERN_C PerlInterpreter *
11274 perl_clone_host(PerlInterpreter* proto_perl, UV flags);
11277 perl_clone(PerlInterpreter *proto_perl, UV flags)
11280 #ifdef PERL_IMPLICIT_SYS
11282 /* perlhost.h so we need to call into it
11283 to clone the host, CPerlHost should have a c interface, sky */
11285 if (flags & CLONEf_CLONE_HOST) {
11286 return perl_clone_host(proto_perl,flags);
11288 return perl_clone_using(proto_perl, flags,
11290 proto_perl->IMemShared,
11291 proto_perl->IMemParse,
11293 proto_perl->IStdIO,
11297 proto_perl->IProc);
11301 perl_clone_using(PerlInterpreter *proto_perl, UV flags,
11302 struct IPerlMem* ipM, struct IPerlMem* ipMS,
11303 struct IPerlMem* ipMP, struct IPerlEnv* ipE,
11304 struct IPerlStdIO* ipStd, struct IPerlLIO* ipLIO,
11305 struct IPerlDir* ipD, struct IPerlSock* ipS,
11306 struct IPerlProc* ipP)
11308 /* XXX many of the string copies here can be optimized if they're
11309 * constants; they need to be allocated as common memory and just
11310 * their pointers copied. */
11313 CLONE_PARAMS clone_params;
11314 CLONE_PARAMS* param = &clone_params;
11316 PerlInterpreter *my_perl = (PerlInterpreter*)(*ipM->pMalloc)(ipM, sizeof(PerlInterpreter));
11317 /* for each stash, determine whether its objects should be cloned */
11318 S_visit(proto_perl, do_mark_cloneable_stash, SVt_PVHV, SVTYPEMASK);
11319 PERL_SET_THX(my_perl);
11322 Poison(my_perl, 1, PerlInterpreter);
11324 PL_curcop = (COP *)Nullop;
11328 PL_savestack_ix = 0;
11329 PL_savestack_max = -1;
11330 PL_sig_pending = 0;
11331 Zero(&PL_debug_pad, 1, struct perl_debug_pad);
11332 # else /* !DEBUGGING */
11333 Zero(my_perl, 1, PerlInterpreter);
11334 # endif /* DEBUGGING */
11336 /* host pointers */
11338 PL_MemShared = ipMS;
11339 PL_MemParse = ipMP;
11346 #else /* !PERL_IMPLICIT_SYS */
11348 CLONE_PARAMS clone_params;
11349 CLONE_PARAMS* param = &clone_params;
11350 PerlInterpreter *my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
11351 /* for each stash, determine whether its objects should be cloned */
11352 S_visit(proto_perl, do_mark_cloneable_stash, SVt_PVHV, SVTYPEMASK);
11353 PERL_SET_THX(my_perl);
11356 Poison(my_perl, 1, PerlInterpreter);
11358 PL_curcop = (COP *)Nullop;
11362 PL_savestack_ix = 0;
11363 PL_savestack_max = -1;
11364 PL_sig_pending = 0;
11365 Zero(&PL_debug_pad, 1, struct perl_debug_pad);
11366 # else /* !DEBUGGING */
11367 Zero(my_perl, 1, PerlInterpreter);
11368 # endif /* DEBUGGING */
11369 #endif /* PERL_IMPLICIT_SYS */
11370 param->flags = flags;
11371 param->proto_perl = proto_perl;
11374 PL_xnv_arenaroot = NULL;
11375 PL_xnv_root = NULL;
11376 PL_xpv_arenaroot = NULL;
11377 PL_xpv_root = NULL;
11378 PL_xpviv_arenaroot = NULL;
11379 PL_xpviv_root = NULL;
11380 PL_xpvnv_arenaroot = NULL;
11381 PL_xpvnv_root = NULL;
11382 PL_xpvcv_arenaroot = NULL;
11383 PL_xpvcv_root = NULL;
11384 PL_xpvav_arenaroot = NULL;
11385 PL_xpvav_root = NULL;
11386 PL_xpvhv_arenaroot = NULL;
11387 PL_xpvhv_root = NULL;
11388 PL_xpvmg_arenaroot = NULL;
11389 PL_xpvmg_root = NULL;
11390 PL_xpvgv_arenaroot = NULL;
11391 PL_xpvgv_root = NULL;
11392 PL_xpvlv_arenaroot = NULL;
11393 PL_xpvlv_root = NULL;
11394 PL_xpvbm_arenaroot = NULL;
11395 PL_xpvbm_root = NULL;
11396 PL_he_arenaroot = NULL;
11398 #if defined(USE_ITHREADS)
11399 PL_pte_arenaroot = NULL;
11400 PL_pte_root = NULL;
11402 PL_nice_chunk = NULL;
11403 PL_nice_chunk_size = 0;
11405 PL_sv_objcount = 0;
11406 PL_sv_root = Nullsv;
11407 PL_sv_arenaroot = Nullsv;
11409 PL_debug = proto_perl->Idebug;
11411 PL_hash_seed = proto_perl->Ihash_seed;
11412 PL_rehash_seed = proto_perl->Irehash_seed;
11414 #ifdef USE_REENTRANT_API
11415 /* XXX: things like -Dm will segfault here in perlio, but doing
11416 * PERL_SET_CONTEXT(proto_perl);
11417 * breaks too many other things
11419 Perl_reentrant_init(aTHX);
11422 /* create SV map for pointer relocation */
11423 PL_ptr_table = ptr_table_new();
11425 /* initialize these special pointers as early as possible */
11426 SvANY(&PL_sv_undef) = NULL;
11427 SvREFCNT(&PL_sv_undef) = (~(U32)0)/2;
11428 SvFLAGS(&PL_sv_undef) = SVf_READONLY|SVt_NULL;
11429 ptr_table_store(PL_ptr_table, &proto_perl->Isv_undef, &PL_sv_undef);
11431 SvANY(&PL_sv_no) = new_XPVNV();
11432 SvREFCNT(&PL_sv_no) = (~(U32)0)/2;
11433 SvFLAGS(&PL_sv_no) = SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
11434 |SVp_POK|SVf_POK|SVf_READONLY|SVt_PVNV;
11435 SvPV_set(&PL_sv_no, SAVEPVN(PL_No, 0));
11436 SvCUR_set(&PL_sv_no, 0);
11437 SvLEN_set(&PL_sv_no, 1);
11438 SvIV_set(&PL_sv_no, 0);
11439 SvNV_set(&PL_sv_no, 0);
11440 ptr_table_store(PL_ptr_table, &proto_perl->Isv_no, &PL_sv_no);
11442 SvANY(&PL_sv_yes) = new_XPVNV();
11443 SvREFCNT(&PL_sv_yes) = (~(U32)0)/2;
11444 SvFLAGS(&PL_sv_yes) = SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
11445 |SVp_POK|SVf_POK|SVf_READONLY|SVt_PVNV;
11446 SvPV_set(&PL_sv_yes, SAVEPVN(PL_Yes, 1));
11447 SvCUR_set(&PL_sv_yes, 1);
11448 SvLEN_set(&PL_sv_yes, 2);
11449 SvIV_set(&PL_sv_yes, 1);
11450 SvNV_set(&PL_sv_yes, 1);
11451 ptr_table_store(PL_ptr_table, &proto_perl->Isv_yes, &PL_sv_yes);
11453 /* create (a non-shared!) shared string table */
11454 PL_strtab = newHV();
11455 HvSHAREKEYS_off(PL_strtab);
11456 hv_ksplit(PL_strtab, HvTOTALKEYS(proto_perl->Istrtab));
11457 ptr_table_store(PL_ptr_table, proto_perl->Istrtab, PL_strtab);
11459 PL_compiling = proto_perl->Icompiling;
11461 /* These two PVs will be free'd special way so must set them same way op.c does */
11462 PL_compiling.cop_stashpv = savesharedpv(PL_compiling.cop_stashpv);
11463 ptr_table_store(PL_ptr_table, proto_perl->Icompiling.cop_stashpv, PL_compiling.cop_stashpv);
11465 PL_compiling.cop_file = savesharedpv(PL_compiling.cop_file);
11466 ptr_table_store(PL_ptr_table, proto_perl->Icompiling.cop_file, PL_compiling.cop_file);
11468 ptr_table_store(PL_ptr_table, &proto_perl->Icompiling, &PL_compiling);
11469 if (!specialWARN(PL_compiling.cop_warnings))
11470 PL_compiling.cop_warnings = sv_dup_inc(PL_compiling.cop_warnings, param);
11471 if (!specialCopIO(PL_compiling.cop_io))
11472 PL_compiling.cop_io = sv_dup_inc(PL_compiling.cop_io, param);
11473 PL_curcop = (COP*)any_dup(proto_perl->Tcurcop, proto_perl);
11475 /* pseudo environmental stuff */
11476 PL_origargc = proto_perl->Iorigargc;
11477 PL_origargv = proto_perl->Iorigargv;
11479 param->stashes = newAV(); /* Setup array of objects to call clone on */
11481 #ifdef PERLIO_LAYERS
11482 /* Clone PerlIO tables as soon as we can handle general xx_dup() */
11483 PerlIO_clone(aTHX_ proto_perl, param);
11486 PL_envgv = gv_dup(proto_perl->Ienvgv, param);
11487 PL_incgv = gv_dup(proto_perl->Iincgv, param);
11488 PL_hintgv = gv_dup(proto_perl->Ihintgv, param);
11489 PL_origfilename = SAVEPV(proto_perl->Iorigfilename);
11490 PL_diehook = sv_dup_inc(proto_perl->Idiehook, param);
11491 PL_warnhook = sv_dup_inc(proto_perl->Iwarnhook, param);
11494 PL_minus_c = proto_perl->Iminus_c;
11495 PL_patchlevel = sv_dup_inc(proto_perl->Ipatchlevel, param);
11496 PL_localpatches = proto_perl->Ilocalpatches;
11497 PL_splitstr = proto_perl->Isplitstr;
11498 PL_preprocess = proto_perl->Ipreprocess;
11499 PL_minus_n = proto_perl->Iminus_n;
11500 PL_minus_p = proto_perl->Iminus_p;
11501 PL_minus_l = proto_perl->Iminus_l;
11502 PL_minus_a = proto_perl->Iminus_a;
11503 PL_minus_F = proto_perl->Iminus_F;
11504 PL_doswitches = proto_perl->Idoswitches;
11505 PL_dowarn = proto_perl->Idowarn;
11506 PL_doextract = proto_perl->Idoextract;
11507 PL_sawampersand = proto_perl->Isawampersand;
11508 PL_unsafe = proto_perl->Iunsafe;
11509 PL_inplace = SAVEPV(proto_perl->Iinplace);
11510 PL_e_script = sv_dup_inc(proto_perl->Ie_script, param);
11511 PL_perldb = proto_perl->Iperldb;
11512 PL_perl_destruct_level = proto_perl->Iperl_destruct_level;
11513 PL_exit_flags = proto_perl->Iexit_flags;
11515 /* magical thingies */
11516 /* XXX time(&PL_basetime) when asked for? */
11517 PL_basetime = proto_perl->Ibasetime;
11518 PL_formfeed = sv_dup(proto_perl->Iformfeed, param);
11520 PL_maxsysfd = proto_perl->Imaxsysfd;
11521 PL_multiline = proto_perl->Imultiline;
11522 PL_statusvalue = proto_perl->Istatusvalue;
11524 PL_statusvalue_vms = proto_perl->Istatusvalue_vms;
11526 PL_encoding = sv_dup(proto_perl->Iencoding, param);
11528 sv_setpvn(PERL_DEBUG_PAD(0), "", 0); /* For regex debugging. */
11529 sv_setpvn(PERL_DEBUG_PAD(1), "", 0); /* ext/re needs these */
11530 sv_setpvn(PERL_DEBUG_PAD(2), "", 0); /* even without DEBUGGING. */
11532 /* Clone the regex array */
11533 PL_regex_padav = newAV();
11535 const I32 len = av_len((AV*)proto_perl->Iregex_padav);
11536 SV** regexen = AvARRAY((AV*)proto_perl->Iregex_padav);
11538 av_push(PL_regex_padav,
11539 sv_dup_inc(regexen[0],param));
11540 for(i = 1; i <= len; i++) {
11541 if(SvREPADTMP(regexen[i])) {
11542 av_push(PL_regex_padav, sv_dup_inc(regexen[i], param));
11544 av_push(PL_regex_padav,
11546 newSViv(PTR2IV(re_dup(INT2PTR(REGEXP *,
11547 SvIVX(regexen[i])), param)))
11552 PL_regex_pad = AvARRAY(PL_regex_padav);
11554 /* shortcuts to various I/O objects */
11555 PL_stdingv = gv_dup(proto_perl->Istdingv, param);
11556 PL_stderrgv = gv_dup(proto_perl->Istderrgv, param);
11557 PL_defgv = gv_dup(proto_perl->Idefgv, param);
11558 PL_argvgv = gv_dup(proto_perl->Iargvgv, param);
11559 PL_argvoutgv = gv_dup(proto_perl->Iargvoutgv, param);
11560 PL_argvout_stack = av_dup_inc(proto_perl->Iargvout_stack, param);
11562 /* shortcuts to regexp stuff */
11563 PL_replgv = gv_dup(proto_perl->Ireplgv, param);
11565 /* shortcuts to misc objects */
11566 PL_errgv = gv_dup(proto_perl->Ierrgv, param);
11568 /* shortcuts to debugging objects */
11569 PL_DBgv = gv_dup(proto_perl->IDBgv, param);
11570 PL_DBline = gv_dup(proto_perl->IDBline, param);
11571 PL_DBsub = gv_dup(proto_perl->IDBsub, param);
11572 PL_DBsingle = sv_dup(proto_perl->IDBsingle, param);
11573 PL_DBtrace = sv_dup(proto_perl->IDBtrace, param);
11574 PL_DBsignal = sv_dup(proto_perl->IDBsignal, param);
11575 PL_DBassertion = sv_dup(proto_perl->IDBassertion, param);
11576 PL_lineary = av_dup(proto_perl->Ilineary, param);
11577 PL_dbargs = av_dup(proto_perl->Idbargs, param);
11579 /* symbol tables */
11580 PL_defstash = hv_dup_inc(proto_perl->Tdefstash, param);
11581 PL_curstash = hv_dup(proto_perl->Tcurstash, param);
11582 PL_debstash = hv_dup(proto_perl->Idebstash, param);
11583 PL_globalstash = hv_dup(proto_perl->Iglobalstash, param);
11584 PL_curstname = sv_dup_inc(proto_perl->Icurstname, param);
11586 PL_beginav = av_dup_inc(proto_perl->Ibeginav, param);
11587 PL_beginav_save = av_dup_inc(proto_perl->Ibeginav_save, param);
11588 PL_checkav_save = av_dup_inc(proto_perl->Icheckav_save, param);
11589 PL_endav = av_dup_inc(proto_perl->Iendav, param);
11590 PL_checkav = av_dup_inc(proto_perl->Icheckav, param);
11591 PL_initav = av_dup_inc(proto_perl->Iinitav, param);
11593 PL_sub_generation = proto_perl->Isub_generation;
11595 /* funky return mechanisms */
11596 PL_forkprocess = proto_perl->Iforkprocess;
11598 /* subprocess state */
11599 PL_fdpid = av_dup_inc(proto_perl->Ifdpid, param);
11601 /* internal state */
11602 PL_tainting = proto_perl->Itainting;
11603 PL_taint_warn = proto_perl->Itaint_warn;
11604 PL_maxo = proto_perl->Imaxo;
11605 if (proto_perl->Iop_mask)
11606 PL_op_mask = SAVEPVN(proto_perl->Iop_mask, PL_maxo);
11608 PL_op_mask = Nullch;
11609 /* PL_asserting = proto_perl->Iasserting; */
11611 /* current interpreter roots */
11612 PL_main_cv = cv_dup_inc(proto_perl->Imain_cv, param);
11613 PL_main_root = OpREFCNT_inc(proto_perl->Imain_root);
11614 PL_main_start = proto_perl->Imain_start;
11615 PL_eval_root = proto_perl->Ieval_root;
11616 PL_eval_start = proto_perl->Ieval_start;
11618 /* runtime control stuff */
11619 PL_curcopdb = (COP*)any_dup(proto_perl->Icurcopdb, proto_perl);
11620 PL_copline = proto_perl->Icopline;
11622 PL_filemode = proto_perl->Ifilemode;
11623 PL_lastfd = proto_perl->Ilastfd;
11624 PL_oldname = proto_perl->Ioldname; /* XXX not quite right */
11627 PL_gensym = proto_perl->Igensym;
11628 PL_preambled = proto_perl->Ipreambled;
11629 PL_preambleav = av_dup_inc(proto_perl->Ipreambleav, param);
11630 PL_laststatval = proto_perl->Ilaststatval;
11631 PL_laststype = proto_perl->Ilaststype;
11632 PL_mess_sv = Nullsv;
11634 PL_ors_sv = sv_dup_inc(proto_perl->Iors_sv, param);
11635 PL_ofmt = SAVEPV(proto_perl->Iofmt);
11637 /* interpreter atexit processing */
11638 PL_exitlistlen = proto_perl->Iexitlistlen;
11639 if (PL_exitlistlen) {
11640 New(0, PL_exitlist, PL_exitlistlen, PerlExitListEntry);
11641 Copy(proto_perl->Iexitlist, PL_exitlist, PL_exitlistlen, PerlExitListEntry);
11644 PL_exitlist = (PerlExitListEntry*)NULL;
11645 PL_modglobal = hv_dup_inc(proto_perl->Imodglobal, param);
11646 PL_custom_op_names = hv_dup_inc(proto_perl->Icustom_op_names,param);
11647 PL_custom_op_descs = hv_dup_inc(proto_perl->Icustom_op_descs,param);
11649 PL_profiledata = NULL;
11650 PL_rsfp = fp_dup(proto_perl->Irsfp, '<', param);
11651 /* PL_rsfp_filters entries have fake IoDIRP() */
11652 PL_rsfp_filters = av_dup_inc(proto_perl->Irsfp_filters, param);
11654 PL_compcv = cv_dup(proto_perl->Icompcv, param);
11656 PAD_CLONE_VARS(proto_perl, param);
11658 #ifdef HAVE_INTERP_INTERN
11659 sys_intern_dup(&proto_perl->Isys_intern, &PL_sys_intern);
11662 /* more statics moved here */
11663 PL_generation = proto_perl->Igeneration;
11664 PL_DBcv = cv_dup(proto_perl->IDBcv, param);
11666 PL_in_clean_objs = proto_perl->Iin_clean_objs;
11667 PL_in_clean_all = proto_perl->Iin_clean_all;
11669 PL_uid = proto_perl->Iuid;
11670 PL_euid = proto_perl->Ieuid;
11671 PL_gid = proto_perl->Igid;
11672 PL_egid = proto_perl->Iegid;
11673 PL_nomemok = proto_perl->Inomemok;
11674 PL_an = proto_perl->Ian;
11675 PL_evalseq = proto_perl->Ievalseq;
11676 PL_origenviron = proto_perl->Iorigenviron; /* XXX not quite right */
11677 PL_origalen = proto_perl->Iorigalen;
11678 PL_pidstatus = newHV(); /* XXX flag for cloning? */
11679 PL_osname = SAVEPV(proto_perl->Iosname);
11680 PL_sh_path_compat = proto_perl->Ish_path_compat; /* XXX never deallocated */
11681 PL_sighandlerp = proto_perl->Isighandlerp;
11684 PL_runops = proto_perl->Irunops;
11686 Copy(proto_perl->Itokenbuf, PL_tokenbuf, 256, char);
11689 PL_cshlen = proto_perl->Icshlen;
11690 PL_cshname = proto_perl->Icshname; /* XXX never deallocated */
11693 PL_lex_state = proto_perl->Ilex_state;
11694 PL_lex_defer = proto_perl->Ilex_defer;
11695 PL_lex_expect = proto_perl->Ilex_expect;
11696 PL_lex_formbrack = proto_perl->Ilex_formbrack;
11697 PL_lex_dojoin = proto_perl->Ilex_dojoin;
11698 PL_lex_starts = proto_perl->Ilex_starts;
11699 PL_lex_stuff = sv_dup_inc(proto_perl->Ilex_stuff, param);
11700 PL_lex_repl = sv_dup_inc(proto_perl->Ilex_repl, param);
11701 PL_lex_op = proto_perl->Ilex_op;
11702 PL_lex_inpat = proto_perl->Ilex_inpat;
11703 PL_lex_inwhat = proto_perl->Ilex_inwhat;
11704 PL_lex_brackets = proto_perl->Ilex_brackets;
11705 i = (PL_lex_brackets < 120 ? 120 : PL_lex_brackets);
11706 PL_lex_brackstack = SAVEPVN(proto_perl->Ilex_brackstack,i);
11707 PL_lex_casemods = proto_perl->Ilex_casemods;
11708 i = (PL_lex_casemods < 12 ? 12 : PL_lex_casemods);
11709 PL_lex_casestack = SAVEPVN(proto_perl->Ilex_casestack,i);
11711 Copy(proto_perl->Inextval, PL_nextval, 5, YYSTYPE);
11712 Copy(proto_perl->Inexttype, PL_nexttype, 5, I32);
11713 PL_nexttoke = proto_perl->Inexttoke;
11715 /* XXX This is probably masking the deeper issue of why
11716 * SvANY(proto_perl->Ilinestr) can be NULL at this point. For test case:
11717 * http://archive.develooper.com/perl5-porters%40perl.org/msg83298.html
11718 * (A little debugging with a watchpoint on it may help.)
11720 if (SvANY(proto_perl->Ilinestr)) {
11721 PL_linestr = sv_dup_inc(proto_perl->Ilinestr, param);
11722 i = proto_perl->Ibufptr - SvPVX_const(proto_perl->Ilinestr);
11723 PL_bufptr = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11724 i = proto_perl->Ioldbufptr - SvPVX_const(proto_perl->Ilinestr);
11725 PL_oldbufptr = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11726 i = proto_perl->Ioldoldbufptr - SvPVX_const(proto_perl->Ilinestr);
11727 PL_oldoldbufptr = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11728 i = proto_perl->Ilinestart - SvPVX_const(proto_perl->Ilinestr);
11729 PL_linestart = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11732 PL_linestr = NEWSV(65,79);
11733 sv_upgrade(PL_linestr,SVt_PVIV);
11734 sv_setpvn(PL_linestr,"",0);
11735 PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart = SvPVX(PL_linestr);
11737 PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
11738 PL_pending_ident = proto_perl->Ipending_ident;
11739 PL_sublex_info = proto_perl->Isublex_info; /* XXX not quite right */
11741 PL_expect = proto_perl->Iexpect;
11743 PL_multi_start = proto_perl->Imulti_start;
11744 PL_multi_end = proto_perl->Imulti_end;
11745 PL_multi_open = proto_perl->Imulti_open;
11746 PL_multi_close = proto_perl->Imulti_close;
11748 PL_error_count = proto_perl->Ierror_count;
11749 PL_subline = proto_perl->Isubline;
11750 PL_subname = sv_dup_inc(proto_perl->Isubname, param);
11752 /* XXX See comment on SvANY(proto_perl->Ilinestr) above */
11753 if (SvANY(proto_perl->Ilinestr)) {
11754 i = proto_perl->Ilast_uni - SvPVX_const(proto_perl->Ilinestr);
11755 PL_last_uni = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11756 i = proto_perl->Ilast_lop - SvPVX_const(proto_perl->Ilinestr);
11757 PL_last_lop = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
11758 PL_last_lop_op = proto_perl->Ilast_lop_op;
11761 PL_last_uni = SvPVX(PL_linestr);
11762 PL_last_lop = SvPVX(PL_linestr);
11763 PL_last_lop_op = 0;
11765 PL_in_my = proto_perl->Iin_my;
11766 PL_in_my_stash = hv_dup(proto_perl->Iin_my_stash, param);
11768 PL_cryptseen = proto_perl->Icryptseen;
11771 PL_hints = proto_perl->Ihints;
11773 PL_amagic_generation = proto_perl->Iamagic_generation;
11775 #ifdef USE_LOCALE_COLLATE
11776 PL_collation_ix = proto_perl->Icollation_ix;
11777 PL_collation_name = SAVEPV(proto_perl->Icollation_name);
11778 PL_collation_standard = proto_perl->Icollation_standard;
11779 PL_collxfrm_base = proto_perl->Icollxfrm_base;
11780 PL_collxfrm_mult = proto_perl->Icollxfrm_mult;
11781 #endif /* USE_LOCALE_COLLATE */
11783 #ifdef USE_LOCALE_NUMERIC
11784 PL_numeric_name = SAVEPV(proto_perl->Inumeric_name);
11785 PL_numeric_standard = proto_perl->Inumeric_standard;
11786 PL_numeric_local = proto_perl->Inumeric_local;
11787 PL_numeric_radix_sv = sv_dup_inc(proto_perl->Inumeric_radix_sv, param);
11788 #endif /* !USE_LOCALE_NUMERIC */
11790 /* utf8 character classes */
11791 PL_utf8_alnum = sv_dup_inc(proto_perl->Iutf8_alnum, param);
11792 PL_utf8_alnumc = sv_dup_inc(proto_perl->Iutf8_alnumc, param);
11793 PL_utf8_ascii = sv_dup_inc(proto_perl->Iutf8_ascii, param);
11794 PL_utf8_alpha = sv_dup_inc(proto_perl->Iutf8_alpha, param);
11795 PL_utf8_space = sv_dup_inc(proto_perl->Iutf8_space, param);
11796 PL_utf8_cntrl = sv_dup_inc(proto_perl->Iutf8_cntrl, param);
11797 PL_utf8_graph = sv_dup_inc(proto_perl->Iutf8_graph, param);
11798 PL_utf8_digit = sv_dup_inc(proto_perl->Iutf8_digit, param);
11799 PL_utf8_upper = sv_dup_inc(proto_perl->Iutf8_upper, param);
11800 PL_utf8_lower = sv_dup_inc(proto_perl->Iutf8_lower, param);
11801 PL_utf8_print = sv_dup_inc(proto_perl->Iutf8_print, param);
11802 PL_utf8_punct = sv_dup_inc(proto_perl->Iutf8_punct, param);
11803 PL_utf8_xdigit = sv_dup_inc(proto_perl->Iutf8_xdigit, param);
11804 PL_utf8_mark = sv_dup_inc(proto_perl->Iutf8_mark, param);
11805 PL_utf8_toupper = sv_dup_inc(proto_perl->Iutf8_toupper, param);
11806 PL_utf8_totitle = sv_dup_inc(proto_perl->Iutf8_totitle, param);
11807 PL_utf8_tolower = sv_dup_inc(proto_perl->Iutf8_tolower, param);
11808 PL_utf8_tofold = sv_dup_inc(proto_perl->Iutf8_tofold, param);
11809 PL_utf8_idstart = sv_dup_inc(proto_perl->Iutf8_idstart, param);
11810 PL_utf8_idcont = sv_dup_inc(proto_perl->Iutf8_idcont, param);
11812 /* Did the locale setup indicate UTF-8? */
11813 PL_utf8locale = proto_perl->Iutf8locale;
11814 /* Unicode features (see perlrun/-C) */
11815 PL_unicode = proto_perl->Iunicode;
11817 /* Pre-5.8 signals control */
11818 PL_signals = proto_perl->Isignals;
11820 /* times() ticks per second */
11821 PL_clocktick = proto_perl->Iclocktick;
11823 /* Recursion stopper for PerlIO_find_layer */
11824 PL_in_load_module = proto_perl->Iin_load_module;
11826 /* sort() routine */
11827 PL_sort_RealCmp = proto_perl->Isort_RealCmp;
11829 /* Not really needed/useful since the reenrant_retint is "volatile",
11830 * but do it for consistency's sake. */
11831 PL_reentrant_retint = proto_perl->Ireentrant_retint;
11833 /* Hooks to shared SVs and locks. */
11834 PL_sharehook = proto_perl->Isharehook;
11835 PL_lockhook = proto_perl->Ilockhook;
11836 PL_unlockhook = proto_perl->Iunlockhook;
11837 PL_threadhook = proto_perl->Ithreadhook;
11839 PL_runops_std = proto_perl->Irunops_std;
11840 PL_runops_dbg = proto_perl->Irunops_dbg;
11842 #ifdef THREADS_HAVE_PIDS
11843 PL_ppid = proto_perl->Ippid;
11847 PL_last_swash_hv = Nullhv; /* reinits on demand */
11848 PL_last_swash_klen = 0;
11849 PL_last_swash_key[0]= '\0';
11850 PL_last_swash_tmps = (U8*)NULL;
11851 PL_last_swash_slen = 0;
11853 PL_glob_index = proto_perl->Iglob_index;
11854 PL_srand_called = proto_perl->Isrand_called;
11855 PL_uudmap['M'] = 0; /* reinits on demand */
11856 PL_bitcount = Nullch; /* reinits on demand */
11858 if (proto_perl->Ipsig_pend) {
11859 Newz(0, PL_psig_pend, SIG_SIZE, int);
11862 PL_psig_pend = (int*)NULL;
11865 if (proto_perl->Ipsig_ptr) {
11866 Newz(0, PL_psig_ptr, SIG_SIZE, SV*);
11867 Newz(0, PL_psig_name, SIG_SIZE, SV*);
11868 for (i = 1; i < SIG_SIZE; i++) {
11869 PL_psig_ptr[i] = sv_dup_inc(proto_perl->Ipsig_ptr[i], param);
11870 PL_psig_name[i] = sv_dup_inc(proto_perl->Ipsig_name[i], param);
11874 PL_psig_ptr = (SV**)NULL;
11875 PL_psig_name = (SV**)NULL;
11878 /* thrdvar.h stuff */
11880 if (flags & CLONEf_COPY_STACKS) {
11881 /* next allocation will be PL_tmps_stack[PL_tmps_ix+1] */
11882 PL_tmps_ix = proto_perl->Ttmps_ix;
11883 PL_tmps_max = proto_perl->Ttmps_max;
11884 PL_tmps_floor = proto_perl->Ttmps_floor;
11885 Newz(50, PL_tmps_stack, PL_tmps_max, SV*);
11887 while (i <= PL_tmps_ix) {
11888 PL_tmps_stack[i] = sv_dup_inc(proto_perl->Ttmps_stack[i], param);
11892 /* next PUSHMARK() sets *(PL_markstack_ptr+1) */
11893 i = proto_perl->Tmarkstack_max - proto_perl->Tmarkstack;
11894 Newz(54, PL_markstack, i, I32);
11895 PL_markstack_max = PL_markstack + (proto_perl->Tmarkstack_max
11896 - proto_perl->Tmarkstack);
11897 PL_markstack_ptr = PL_markstack + (proto_perl->Tmarkstack_ptr
11898 - proto_perl->Tmarkstack);
11899 Copy(proto_perl->Tmarkstack, PL_markstack,
11900 PL_markstack_ptr - PL_markstack + 1, I32);
11902 /* next push_scope()/ENTER sets PL_scopestack[PL_scopestack_ix]
11903 * NOTE: unlike the others! */
11904 PL_scopestack_ix = proto_perl->Tscopestack_ix;
11905 PL_scopestack_max = proto_perl->Tscopestack_max;
11906 Newz(54, PL_scopestack, PL_scopestack_max, I32);
11907 Copy(proto_perl->Tscopestack, PL_scopestack, PL_scopestack_ix, I32);
11909 /* NOTE: si_dup() looks at PL_markstack */
11910 PL_curstackinfo = si_dup(proto_perl->Tcurstackinfo, param);
11912 /* PL_curstack = PL_curstackinfo->si_stack; */
11913 PL_curstack = av_dup(proto_perl->Tcurstack, param);
11914 PL_mainstack = av_dup(proto_perl->Tmainstack, param);
11916 /* next PUSHs() etc. set *(PL_stack_sp+1) */
11917 PL_stack_base = AvARRAY(PL_curstack);
11918 PL_stack_sp = PL_stack_base + (proto_perl->Tstack_sp
11919 - proto_perl->Tstack_base);
11920 PL_stack_max = PL_stack_base + AvMAX(PL_curstack);
11922 /* next SSPUSHFOO() sets PL_savestack[PL_savestack_ix]
11923 * NOTE: unlike the others! */
11924 PL_savestack_ix = proto_perl->Tsavestack_ix;
11925 PL_savestack_max = proto_perl->Tsavestack_max;
11926 /*Newz(54, PL_savestack, PL_savestack_max, ANY);*/
11927 PL_savestack = ss_dup(proto_perl, param);
11931 ENTER; /* perl_destruct() wants to LEAVE; */
11934 PL_start_env = proto_perl->Tstart_env; /* XXXXXX */
11935 PL_top_env = &PL_start_env;
11937 PL_op = proto_perl->Top;
11940 PL_Xpv = (XPV*)NULL;
11941 PL_na = proto_perl->Tna;
11943 PL_statbuf = proto_perl->Tstatbuf;
11944 PL_statcache = proto_perl->Tstatcache;
11945 PL_statgv = gv_dup(proto_perl->Tstatgv, param);
11946 PL_statname = sv_dup_inc(proto_perl->Tstatname, param);
11948 PL_timesbuf = proto_perl->Ttimesbuf;
11951 PL_tainted = proto_perl->Ttainted;
11952 PL_curpm = proto_perl->Tcurpm; /* XXX No PMOP ref count */
11953 PL_rs = sv_dup_inc(proto_perl->Trs, param);
11954 PL_last_in_gv = gv_dup(proto_perl->Tlast_in_gv, param);
11955 PL_ofs_sv = sv_dup_inc(proto_perl->Tofs_sv, param);
11956 PL_defoutgv = gv_dup_inc(proto_perl->Tdefoutgv, param);
11957 PL_chopset = proto_perl->Tchopset; /* XXX never deallocated */
11958 PL_toptarget = sv_dup_inc(proto_perl->Ttoptarget, param);
11959 PL_bodytarget = sv_dup_inc(proto_perl->Tbodytarget, param);
11960 PL_formtarget = sv_dup(proto_perl->Tformtarget, param);
11962 PL_restartop = proto_perl->Trestartop;
11963 PL_in_eval = proto_perl->Tin_eval;
11964 PL_delaymagic = proto_perl->Tdelaymagic;
11965 PL_dirty = proto_perl->Tdirty;
11966 PL_localizing = proto_perl->Tlocalizing;
11968 PL_errors = sv_dup_inc(proto_perl->Terrors, param);
11969 PL_hv_fetch_ent_mh = Nullhe;
11970 PL_modcount = proto_perl->Tmodcount;
11971 PL_lastgotoprobe = Nullop;
11972 PL_dumpindent = proto_perl->Tdumpindent;
11974 PL_sortcop = (OP*)any_dup(proto_perl->Tsortcop, proto_perl);
11975 PL_sortstash = hv_dup(proto_perl->Tsortstash, param);
11976 PL_firstgv = gv_dup(proto_perl->Tfirstgv, param);
11977 PL_secondgv = gv_dup(proto_perl->Tsecondgv, param);
11978 PL_sortcxix = proto_perl->Tsortcxix;
11979 PL_efloatbuf = Nullch; /* reinits on demand */
11980 PL_efloatsize = 0; /* reinits on demand */
11984 PL_screamfirst = NULL;
11985 PL_screamnext = NULL;
11986 PL_maxscream = -1; /* reinits on demand */
11987 PL_lastscream = Nullsv;
11989 PL_watchaddr = NULL;
11990 PL_watchok = Nullch;
11992 PL_regdummy = proto_perl->Tregdummy;
11993 PL_regprecomp = Nullch;
11996 PL_colorset = 0; /* reinits PL_colors[] */
11997 /*PL_colors[6] = {0,0,0,0,0,0};*/
11998 PL_reginput = Nullch;
11999 PL_regbol = Nullch;
12000 PL_regeol = Nullch;
12001 PL_regstartp = (I32*)NULL;
12002 PL_regendp = (I32*)NULL;
12003 PL_reglastparen = (U32*)NULL;
12004 PL_reglastcloseparen = (U32*)NULL;
12005 PL_regtill = Nullch;
12006 PL_reg_start_tmp = (char**)NULL;
12007 PL_reg_start_tmpl = 0;
12008 PL_regdata = (struct reg_data*)NULL;
12011 PL_reg_eval_set = 0;
12013 PL_regprogram = (regnode*)NULL;
12015 PL_regcc = (CURCUR*)NULL;
12016 PL_reg_call_cc = (struct re_cc_state*)NULL;
12017 PL_reg_re = (regexp*)NULL;
12018 PL_reg_ganch = Nullch;
12019 PL_reg_sv = Nullsv;
12020 PL_reg_match_utf8 = FALSE;
12021 PL_reg_magic = (MAGIC*)NULL;
12023 PL_reg_oldcurpm = (PMOP*)NULL;
12024 PL_reg_curpm = (PMOP*)NULL;
12025 PL_reg_oldsaved = Nullch;
12026 PL_reg_oldsavedlen = 0;
12027 #ifdef PERL_OLD_COPY_ON_WRITE
12030 PL_reg_maxiter = 0;
12031 PL_reg_leftiter = 0;
12032 PL_reg_poscache = Nullch;
12033 PL_reg_poscache_size= 0;
12035 /* RE engine - function pointers */
12036 PL_regcompp = proto_perl->Tregcompp;
12037 PL_regexecp = proto_perl->Tregexecp;
12038 PL_regint_start = proto_perl->Tregint_start;
12039 PL_regint_string = proto_perl->Tregint_string;
12040 PL_regfree = proto_perl->Tregfree;
12042 PL_reginterp_cnt = 0;
12043 PL_reg_starttry = 0;
12045 /* Pluggable optimizer */
12046 PL_peepp = proto_perl->Tpeepp;
12048 PL_stashcache = newHV();
12050 if (!(flags & CLONEf_KEEP_PTR_TABLE)) {
12051 ptr_table_free(PL_ptr_table);
12052 PL_ptr_table = NULL;
12055 /* Call the ->CLONE method, if it exists, for each of the stashes
12056 identified by sv_dup() above.
12058 while(av_len(param->stashes) != -1) {
12059 HV* stash = (HV*) av_shift(param->stashes);
12060 GV* cloner = gv_fetchmethod_autoload(stash, "CLONE", 0);
12061 if (cloner && GvCV(cloner)) {
12066 XPUSHs(sv_2mortal(newSVhek(HvNAME_HEK(stash))));
12068 call_sv((SV*)GvCV(cloner), G_DISCARD);
12074 SvREFCNT_dec(param->stashes);
12076 /* orphaned? eg threads->new inside BEGIN or use */
12077 if (PL_compcv && ! SvREFCNT(PL_compcv)) {
12078 (void)SvREFCNT_inc(PL_compcv);
12079 SAVEFREESV(PL_compcv);
12085 #endif /* USE_ITHREADS */
12088 =head1 Unicode Support
12090 =for apidoc sv_recode_to_utf8
12092 The encoding is assumed to be an Encode object, on entry the PV
12093 of the sv is assumed to be octets in that encoding, and the sv
12094 will be converted into Unicode (and UTF-8).
12096 If the sv already is UTF-8 (or if it is not POK), or if the encoding
12097 is not a reference, nothing is done to the sv. If the encoding is not
12098 an C<Encode::XS> Encoding object, bad things will happen.
12099 (See F<lib/encoding.pm> and L<Encode>).
12101 The PV of the sv is returned.
12106 Perl_sv_recode_to_utf8(pTHX_ SV *sv, SV *encoding)
12109 if (SvPOK(sv) && !SvUTF8(sv) && !IN_BYTES && SvROK(encoding)) {
12123 Passing sv_yes is wrong - it needs to be or'ed set of constants
12124 for Encode::XS, while UTf-8 decode (currently) assumes a true value means
12125 remove converted chars from source.
12127 Both will default the value - let them.
12129 XPUSHs(&PL_sv_yes);
12132 call_method("decode", G_SCALAR);
12136 s = SvPV_const(uni, len);
12137 if (s != SvPVX_const(sv)) {
12138 SvGROW(sv, len + 1);
12139 Move(s, SvPVX(sv), len + 1, char);
12140 SvCUR_set(sv, len);
12147 return SvPOKp(sv) ? SvPVX(sv) : NULL;
12151 =for apidoc sv_cat_decode
12153 The encoding is assumed to be an Encode object, the PV of the ssv is
12154 assumed to be octets in that encoding and decoding the input starts
12155 from the position which (PV + *offset) pointed to. The dsv will be
12156 concatenated the decoded UTF-8 string from ssv. Decoding will terminate
12157 when the string tstr appears in decoding output or the input ends on
12158 the PV of the ssv. The value which the offset points will be modified
12159 to the last input position on the ssv.
12161 Returns TRUE if the terminator was found, else returns FALSE.
12166 Perl_sv_cat_decode(pTHX_ SV *dsv, SV *encoding,
12167 SV *ssv, int *offset, char *tstr, int tlen)
12171 if (SvPOK(ssv) && SvPOK(dsv) && SvROK(encoding) && offset) {
12182 XPUSHs(offsv = sv_2mortal(newSViv(*offset)));
12183 XPUSHs(sv_2mortal(newSVpvn(tstr, tlen)));
12185 call_method("cat_decode", G_SCALAR);
12187 ret = SvTRUE(TOPs);
12188 *offset = SvIV(offsv);
12194 Perl_croak(aTHX_ "Invalid argument to sv_cat_decode");
12200 * c-indentation-style: bsd
12201 * c-basic-offset: 4
12202 * indent-tabs-mode: t
12205 * ex: set ts=8 sts=4 sw=4 noet: