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)) {
289 const SV * const sv = sva + 1;
290 const SV * const 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 const 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 void **arenaroots[] = {
529 (void**) &PL_xnv_arenaroot,
530 (void**) &PL_xpv_arenaroot,
531 (void**) &PL_xpviv_arenaroot,
532 (void**) &PL_xpvnv_arenaroot,
533 (void**) &PL_xpvcv_arenaroot,
534 (void**) &PL_xpvav_arenaroot,
535 (void**) &PL_xpvhv_arenaroot,
536 (void**) &PL_xpvmg_arenaroot,
537 (void**) &PL_xpvgv_arenaroot,
538 (void**) &PL_xpvlv_arenaroot,
539 (void**) &PL_xpvbm_arenaroot,
540 (void**) &PL_he_arenaroot,
541 #if defined(USE_ITHREADS)
542 (void**) &PL_pte_arenaroot,
547 (void**) &PL_xnv_root,
548 (void**) &PL_xpv_root,
549 (void**) &PL_xpviv_root,
550 (void**) &PL_xpvnv_root,
551 (void**) &PL_xpvcv_root,
552 (void**) &PL_xpvav_root,
553 (void**) &PL_xpvhv_root,
554 (void**) &PL_xpvmg_root,
555 (void**) &PL_xpvgv_root,
556 (void**) &PL_xpvlv_root,
557 (void**) &PL_xpvbm_root,
558 (void**) &PL_he_root,
559 #if defined(USE_ITHREADS)
560 (void**) &PL_pte_root,
565 /* Free arenas here, but be careful about fake ones. (We assume
566 contiguity of the fake ones with the corresponding real ones.) */
568 for (sva = PL_sv_arenaroot; sva; sva = svanext) {
569 svanext = (SV*) SvANY(sva);
570 while (svanext && SvFAKE(svanext))
571 svanext = (SV*) SvANY(svanext);
577 assert(sizeof(arenaroots) == sizeof(roots));
579 for (i=0; arenaroots[i]; i++) {
581 arena = *arenaroots[i];
582 for (; arena; arena = arenanext) {
583 arenanext = *(void **)arena;
591 Safefree(PL_nice_chunk);
592 PL_nice_chunk = Nullch;
593 PL_nice_chunk_size = 0;
598 /* ---------------------------------------------------------------------
600 * support functions for report_uninit()
603 /* the maxiumum size of array or hash where we will scan looking
604 * for the undefined element that triggered the warning */
606 #define FUV_MAX_SEARCH_SIZE 1000
608 /* Look for an entry in the hash whose value has the same SV as val;
609 * If so, return a mortal copy of the key. */
612 S_find_hash_subscript(pTHX_ HV *hv, SV* val)
618 if (!hv || SvMAGICAL(hv) || !HvARRAY(hv) ||
619 (HvTOTALKEYS(hv) > FUV_MAX_SEARCH_SIZE))
624 for (i=HvMAX(hv); i>0; i--) {
626 for (entry = array[i]; entry; entry = HeNEXT(entry)) {
627 if (HeVAL(entry) != val)
629 if ( HeVAL(entry) == &PL_sv_undef ||
630 HeVAL(entry) == &PL_sv_placeholder)
634 if (HeKLEN(entry) == HEf_SVKEY)
635 return sv_mortalcopy(HeKEY_sv(entry));
636 return sv_2mortal(newSVpvn(HeKEY(entry), HeKLEN(entry)));
642 /* Look for an entry in the array whose value has the same SV as val;
643 * If so, return the index, otherwise return -1. */
646 S_find_array_subscript(pTHX_ AV *av, SV* val)
650 if (!av || SvMAGICAL(av) || !AvARRAY(av) ||
651 (AvFILLp(av) > FUV_MAX_SEARCH_SIZE))
655 for (i=AvFILLp(av); i>=0; i--) {
656 if (svp[i] == val && svp[i] != &PL_sv_undef)
662 /* S_varname(): return the name of a variable, optionally with a subscript.
663 * If gv is non-zero, use the name of that global, along with gvtype (one
664 * of "$", "@", "%"); otherwise use the name of the lexical at pad offset
665 * targ. Depending on the value of the subscript_type flag, return:
668 #define FUV_SUBSCRIPT_NONE 1 /* "@foo" */
669 #define FUV_SUBSCRIPT_ARRAY 2 /* "$foo[aindex]" */
670 #define FUV_SUBSCRIPT_HASH 3 /* "$foo{keyname}" */
671 #define FUV_SUBSCRIPT_WITHIN 4 /* "within @foo" */
674 S_varname(pTHX_ GV *gv, const char *gvtype, PADOFFSET targ,
675 SV* keyname, I32 aindex, int subscript_type)
678 SV * const name = sv_newmortal();
681 /* simulate gv_fullname4(), but add literal '^' for $^FOO names
682 * XXX get rid of all this if gv_fullnameX() ever supports this
686 HV * const hv = GvSTASH(gv);
687 sv_setpv(name, gvtype);
690 else if (!(p=HvNAME_get(hv)))
692 if (strNE(p, "main")) {
694 sv_catpvn(name,"::", 2);
696 if (GvNAMELEN(gv)>= 1 &&
697 ((unsigned int)*GvNAME(gv)) <= 26)
699 Perl_sv_catpvf(aTHX_ name,"^%c", *GvNAME(gv) + 'A' - 1);
700 sv_catpvn(name,GvNAME(gv)+1,GvNAMELEN(gv)-1);
703 sv_catpvn(name,GvNAME(gv),GvNAMELEN(gv));
707 CV * const cv = find_runcv(&unused);
711 if (!cv || !CvPADLIST(cv))
713 av = (AV*)(*av_fetch(CvPADLIST(cv), 0, FALSE));
714 sv = *av_fetch(av, targ, FALSE);
715 /* SvLEN in a pad name is not to be trusted */
716 sv_setpv(name, SvPV_nolen_const(sv));
719 if (subscript_type == FUV_SUBSCRIPT_HASH) {
723 Perl_sv_catpvf(aTHX_ name, "{%s}",
724 pv_display(sv,SvPVX_const(keyname), SvCUR(keyname), 0, 32));
727 else if (subscript_type == FUV_SUBSCRIPT_ARRAY) {
729 Perl_sv_catpvf(aTHX_ name, "[%"IVdf"]", (IV)aindex);
731 else if (subscript_type == FUV_SUBSCRIPT_WITHIN)
732 sv_insert(name, 0, 0, "within ", 7);
739 =for apidoc find_uninit_var
741 Find the name of the undefined variable (if any) that caused the operator o
742 to issue a "Use of uninitialized value" warning.
743 If match is true, only return a name if it's value matches uninit_sv.
744 So roughly speaking, if a unary operator (such as OP_COS) generates a
745 warning, then following the direct child of the op may yield an
746 OP_PADSV or OP_GV that gives the name of the undefined variable. On the
747 other hand, with OP_ADD there are two branches to follow, so we only print
748 the variable name if we get an exact match.
750 The name is returned as a mortal SV.
752 Assumes that PL_op is the op that originally triggered the error, and that
753 PL_comppad/PL_curpad points to the currently executing pad.
759 S_find_uninit_var(pTHX_ OP* obase, SV* uninit_sv, bool match)
768 if (!obase || (match && (!uninit_sv || uninit_sv == &PL_sv_undef ||
769 uninit_sv == &PL_sv_placeholder)))
772 switch (obase->op_type) {
779 const bool pad = (obase->op_type == OP_PADAV || obase->op_type == OP_PADHV);
780 const bool hash = (obase->op_type == OP_PADHV || obase->op_type == OP_RV2HV);
783 int subscript_type = FUV_SUBSCRIPT_WITHIN;
785 if (pad) { /* @lex, %lex */
786 sv = PAD_SVl(obase->op_targ);
790 if (cUNOPx(obase)->op_first->op_type == OP_GV) {
791 /* @global, %global */
792 gv = cGVOPx_gv(cUNOPx(obase)->op_first);
795 sv = hash ? (SV*)GvHV(gv): (SV*)GvAV(gv);
797 else /* @{expr}, %{expr} */
798 return find_uninit_var(cUNOPx(obase)->op_first,
802 /* attempt to find a match within the aggregate */
804 keysv = S_find_hash_subscript(aTHX_ (HV*)sv, uninit_sv);
806 subscript_type = FUV_SUBSCRIPT_HASH;
809 index = S_find_array_subscript(aTHX_ (AV*)sv, uninit_sv);
811 subscript_type = FUV_SUBSCRIPT_ARRAY;
814 if (match && subscript_type == FUV_SUBSCRIPT_WITHIN)
817 return S_varname(aTHX_ gv, hash ? "%" : "@", obase->op_targ,
818 keysv, index, subscript_type);
822 if (match && PAD_SVl(obase->op_targ) != uninit_sv)
824 return S_varname(aTHX_ Nullgv, "$", obase->op_targ,
825 Nullsv, 0, FUV_SUBSCRIPT_NONE);
828 gv = cGVOPx_gv(obase);
829 if (!gv || (match && GvSV(gv) != uninit_sv))
831 return S_varname(aTHX_ gv, "$", 0, Nullsv, 0, FUV_SUBSCRIPT_NONE);
834 if (obase->op_flags & OPf_SPECIAL) { /* lexical array */
836 av = (AV*)PAD_SV(obase->op_targ);
837 if (!av || SvRMAGICAL(av))
839 svp = av_fetch(av, (I32)obase->op_private, FALSE);
840 if (!svp || *svp != uninit_sv)
843 return S_varname(aTHX_ Nullgv, "$", obase->op_targ,
844 Nullsv, (I32)obase->op_private, FUV_SUBSCRIPT_ARRAY);
847 gv = cGVOPx_gv(obase);
852 if (!av || SvRMAGICAL(av))
854 svp = av_fetch(av, (I32)obase->op_private, FALSE);
855 if (!svp || *svp != uninit_sv)
858 return S_varname(aTHX_ gv, "$", 0,
859 Nullsv, (I32)obase->op_private, FUV_SUBSCRIPT_ARRAY);
864 o = cUNOPx(obase)->op_first;
865 if (!o || o->op_type != OP_NULL ||
866 ! (o->op_targ == OP_AELEM || o->op_targ == OP_HELEM))
868 return find_uninit_var(cBINOPo->op_last, uninit_sv, match);
873 /* $a[uninit_expr] or $h{uninit_expr} */
874 return find_uninit_var(cBINOPx(obase)->op_last, uninit_sv, match);
877 o = cBINOPx(obase)->op_first;
878 kid = cBINOPx(obase)->op_last;
880 /* get the av or hv, and optionally the gv */
882 if (o->op_type == OP_PADAV || o->op_type == OP_PADHV) {
883 sv = PAD_SV(o->op_targ);
885 else if ((o->op_type == OP_RV2AV || o->op_type == OP_RV2HV)
886 && cUNOPo->op_first->op_type == OP_GV)
888 gv = cGVOPx_gv(cUNOPo->op_first);
891 sv = o->op_type == OP_RV2HV ? (SV*)GvHV(gv) : (SV*)GvAV(gv);
896 if (kid && kid->op_type == OP_CONST && SvOK(cSVOPx_sv(kid))) {
897 /* index is constant */
901 if (obase->op_type == OP_HELEM) {
902 HE* he = hv_fetch_ent((HV*)sv, cSVOPx_sv(kid), 0, 0);
903 if (!he || HeVAL(he) != uninit_sv)
907 svp = av_fetch((AV*)sv, SvIV(cSVOPx_sv(kid)), FALSE);
908 if (!svp || *svp != uninit_sv)
912 if (obase->op_type == OP_HELEM)
913 return S_varname(aTHX_ gv, "%", o->op_targ,
914 cSVOPx_sv(kid), 0, FUV_SUBSCRIPT_HASH);
916 return S_varname(aTHX_ gv, "@", o->op_targ, Nullsv,
917 SvIV(cSVOPx_sv(kid)), FUV_SUBSCRIPT_ARRAY);
921 /* index is an expression;
922 * attempt to find a match within the aggregate */
923 if (obase->op_type == OP_HELEM) {
924 SV * const keysv = S_find_hash_subscript(aTHX_ (HV*)sv, uninit_sv);
926 return S_varname(aTHX_ gv, "%", o->op_targ,
927 keysv, 0, FUV_SUBSCRIPT_HASH);
930 const I32 index = S_find_array_subscript(aTHX_ (AV*)sv, uninit_sv);
932 return S_varname(aTHX_ gv, "@", o->op_targ,
933 Nullsv, index, FUV_SUBSCRIPT_ARRAY);
937 return S_varname(aTHX_ gv,
938 (o->op_type == OP_PADAV || o->op_type == OP_RV2AV)
940 o->op_targ, Nullsv, 0, FUV_SUBSCRIPT_WITHIN);
946 /* only examine RHS */
947 return find_uninit_var(cBINOPx(obase)->op_first, uninit_sv, match);
950 o = cUNOPx(obase)->op_first;
951 if (o->op_type == OP_PUSHMARK)
954 if (!o->op_sibling) {
955 /* one-arg version of open is highly magical */
957 if (o->op_type == OP_GV) { /* open FOO; */
959 if (match && GvSV(gv) != uninit_sv)
961 return S_varname(aTHX_ gv, "$", 0,
962 Nullsv, 0, FUV_SUBSCRIPT_NONE);
964 /* other possibilities not handled are:
965 * open $x; or open my $x; should return '${*$x}'
966 * open expr; should return '$'.expr ideally
972 /* ops where $_ may be an implicit arg */
976 if ( !(obase->op_flags & OPf_STACKED)) {
977 if (uninit_sv == ((obase->op_private & OPpTARGET_MY)
978 ? PAD_SVl(obase->op_targ)
982 sv_setpvn(sv, "$_", 2);
990 /* skip filehandle as it can't produce 'undef' warning */
991 o = cUNOPx(obase)->op_first;
992 if ((obase->op_flags & OPf_STACKED) && o->op_type == OP_PUSHMARK)
993 o = o->op_sibling->op_sibling;
1000 match = 1; /* XS or custom code could trigger random warnings */
1005 if (SvROK(PL_rs) && uninit_sv == SvRV(PL_rs))
1006 return sv_2mortal(newSVpv("${$/}", 0));
1011 if (!(obase->op_flags & OPf_KIDS))
1013 o = cUNOPx(obase)->op_first;
1019 /* if all except one arg are constant, or have no side-effects,
1020 * or are optimized away, then it's unambiguous */
1022 for (kid=o; kid; kid = kid->op_sibling) {
1024 ( (kid->op_type == OP_CONST && SvOK(cSVOPx_sv(kid)))
1025 || (kid->op_type == OP_NULL && ! (kid->op_flags & OPf_KIDS))
1026 || (kid->op_type == OP_PUSHMARK)
1030 if (o2) { /* more than one found */
1037 return find_uninit_var(o2, uninit_sv, match);
1041 sv = find_uninit_var(o, uninit_sv, 1);
1053 =for apidoc report_uninit
1055 Print appropriate "Use of uninitialized variable" warning
1061 Perl_report_uninit(pTHX_ SV* uninit_sv)
1064 SV* varname = Nullsv;
1066 varname = find_uninit_var(PL_op, uninit_sv,0);
1068 sv_insert(varname, 0, 0, " ", 1);
1070 Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
1071 varname ? SvPV_nolen_const(varname) : "",
1072 " in ", OP_DESC(PL_op));
1075 Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
1080 S_more_bodies (pTHX_ void **arena_root, void **root, size_t size)
1084 const size_t count = PERL_ARENA_SIZE/size;
1085 New(0, start, count*size, char);
1086 *((void **) start) = *arena_root;
1087 *arena_root = (void *)start;
1089 end = start + (count-1) * size;
1091 /* The initial slot is used to link the arenas together, so it isn't to be
1092 linked into the list of ready-to-use bodies. */
1096 *root = (void *)start;
1098 while (start < end) {
1099 char * const next = start + size;
1100 *(void**) start = (void *)next;
1103 *(void **)start = 0;
1108 /* grab a new thing from the free list, allocating more if necessary */
1111 S_new_body(pTHX_ void **arena_root, void **root, size_t size)
1115 xpv = *root ? *root : S_more_bodies(aTHX_ arena_root, root, size);
1116 *root = *(void**)xpv;
1121 /* return a thing to the free list */
1123 #define del_body(thing, root) \
1126 *(void **)thing = *root; \
1127 *root = (void*)thing; \
1131 /* Conventionally we simply malloc() a big block of memory, then divide it
1132 up into lots of the thing that we're allocating.
1134 This macro will expand to call to S_new_body. So for XPVBM (with ithreads),
1137 S_new_body(my_perl, (void**)&(my_perl->Ixpvbm_arenaroot),
1138 (void**)&(my_perl->Ixpvbm_root), sizeof(XPVBM), 0)
1141 #define new_body(TYPE,lctype) \
1142 S_new_body(aTHX_ (void**)&PL_ ## lctype ## _arenaroot, \
1143 (void**)&PL_ ## lctype ## _root, \
1146 #define del_body_type(p,TYPE,lctype) \
1147 del_body((void*)p, (void**)&PL_ ## lctype ## _root)
1149 /* But for some types, we cheat. The type starts with some members that are
1150 never accessed. So we allocate the substructure, starting at the first used
1151 member, then adjust the pointer back in memory by the size of the bit not
1152 allocated, so it's as if we allocated the full structure.
1153 (But things will all go boom if you write to the part that is "not there",
1154 because you'll be overwriting the last members of the preceding structure
1157 We calculate the correction using the STRUCT_OFFSET macro. For example, if
1158 xpv_allocated is the same structure as XPV then the two OFFSETs sum to zero,
1159 and the pointer is unchanged. If the allocated structure is smaller (no
1160 initial NV actually allocated) then the net effect is to subtract the size
1161 of the NV from the pointer, to return a new pointer as if an initial NV were
1164 This is the same trick as was used for NV and IV bodies. Ironically it
1165 doesn't need to be used for NV bodies any more, because NV is now at the
1166 start of the structure. IV bodies don't need it either, because they are
1167 no longer allocated. */
1169 #define new_body_allocated(TYPE,lctype,member) \
1170 (void*)((char*)S_new_body(aTHX_ (void**)&PL_ ## lctype ## _arenaroot, \
1171 (void**)&PL_ ## lctype ## _root, \
1172 sizeof(lctype ## _allocated)) - \
1173 STRUCT_OFFSET(TYPE, member) \
1174 + STRUCT_OFFSET(lctype ## _allocated, member))
1177 #define del_body_allocated(p,TYPE,lctype,member) \
1178 del_body((void*)((char*)p + STRUCT_OFFSET(TYPE, member) \
1179 - STRUCT_OFFSET(lctype ## _allocated, member)), \
1180 (void**)&PL_ ## lctype ## _root)
1182 #define my_safemalloc(s) (void*)safemalloc(s)
1183 #define my_safefree(p) safefree((char*)p)
1187 #define new_XNV() my_safemalloc(sizeof(XPVNV))
1188 #define del_XNV(p) my_safefree(p)
1190 #define new_XPV() my_safemalloc(sizeof(XPV))
1191 #define del_XPV(p) my_safefree(p)
1193 #define new_XPVIV() my_safemalloc(sizeof(XPVIV))
1194 #define del_XPVIV(p) my_safefree(p)
1196 #define new_XPVNV() my_safemalloc(sizeof(XPVNV))
1197 #define del_XPVNV(p) my_safefree(p)
1199 #define new_XPVCV() my_safemalloc(sizeof(XPVCV))
1200 #define del_XPVCV(p) my_safefree(p)
1202 #define new_XPVAV() my_safemalloc(sizeof(XPVAV))
1203 #define del_XPVAV(p) my_safefree(p)
1205 #define new_XPVHV() my_safemalloc(sizeof(XPVHV))
1206 #define del_XPVHV(p) my_safefree(p)
1208 #define new_XPVMG() my_safemalloc(sizeof(XPVMG))
1209 #define del_XPVMG(p) my_safefree(p)
1211 #define new_XPVGV() my_safemalloc(sizeof(XPVGV))
1212 #define del_XPVGV(p) my_safefree(p)
1214 #define new_XPVLV() my_safemalloc(sizeof(XPVLV))
1215 #define del_XPVLV(p) my_safefree(p)
1217 #define new_XPVBM() my_safemalloc(sizeof(XPVBM))
1218 #define del_XPVBM(p) my_safefree(p)
1222 #define new_XNV() new_body(NV, xnv)
1223 #define del_XNV(p) del_body_type(p, NV, xnv)
1225 #define new_XPV() new_body_allocated(XPV, xpv, xpv_cur)
1226 #define del_XPV(p) del_body_allocated(p, XPV, xpv, xpv_cur)
1228 #define new_XPVIV() new_body_allocated(XPVIV, xpviv, xpv_cur)
1229 #define del_XPVIV(p) del_body_allocated(p, XPVIV, xpviv, xpv_cur)
1231 #define new_XPVNV() new_body(XPVNV, xpvnv)
1232 #define del_XPVNV(p) del_body_type(p, XPVNV, xpvnv)
1234 #define new_XPVCV() new_body(XPVCV, xpvcv)
1235 #define del_XPVCV(p) del_body_type(p, XPVCV, xpvcv)
1237 #define new_XPVAV() new_body_allocated(XPVAV, xpvav, xav_fill)
1238 #define del_XPVAV(p) del_body_allocated(p, XPVAV, xpvav, xav_fill)
1240 #define new_XPVHV() new_body_allocated(XPVHV, xpvhv, xhv_fill)
1241 #define del_XPVHV(p) del_body_allocated(p, XPVHV, xpvhv, xhv_fill)
1243 #define new_XPVMG() new_body(XPVMG, xpvmg)
1244 #define del_XPVMG(p) del_body_type(p, XPVMG, xpvmg)
1246 #define new_XPVGV() new_body(XPVGV, xpvgv)
1247 #define del_XPVGV(p) del_body_type(p, XPVGV, xpvgv)
1249 #define new_XPVLV() new_body(XPVLV, xpvlv)
1250 #define del_XPVLV(p) del_body_type(p, XPVLV, xpvlv)
1252 #define new_XPVBM() new_body(XPVBM, xpvbm)
1253 #define del_XPVBM(p) del_body_type(p, XPVBM, xpvbm)
1257 #define new_XPVFM() my_safemalloc(sizeof(XPVFM))
1258 #define del_XPVFM(p) my_safefree(p)
1260 #define new_XPVIO() my_safemalloc(sizeof(XPVIO))
1261 #define del_XPVIO(p) my_safefree(p)
1264 =for apidoc sv_upgrade
1266 Upgrade an SV to a more complex form. Generally adds a new body type to the
1267 SV, then copies across as much information as possible from the old body.
1268 You generally want to use the C<SvUPGRADE> macro wrapper. See also C<svtype>.
1274 Perl_sv_upgrade(pTHX_ register SV *sv, U32 mt)
1276 void** old_body_arena;
1277 size_t old_body_offset;
1278 size_t old_body_length; /* Well, the length to copy. */
1280 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1281 /* If NV 0.0 is store as all bits 0 then Zero() already creates a correct
1283 bool zero_nv = TRUE;
1286 size_t new_body_length;
1287 size_t new_body_offset;
1288 void** new_body_arena;
1289 void** new_body_arenaroot;
1290 const U32 old_type = SvTYPE(sv);
1292 if (mt != SVt_PV && SvIsCOW(sv)) {
1293 sv_force_normal_flags(sv, 0);
1296 if (SvTYPE(sv) == mt)
1299 if (SvTYPE(sv) > mt)
1300 Perl_croak(aTHX_ "sv_upgrade from type %d down to type %d",
1301 (int)SvTYPE(sv), (int)mt);
1304 old_body = SvANY(sv);
1306 old_body_offset = 0;
1307 old_body_length = 0;
1308 new_body_offset = 0;
1309 new_body_length = ~0;
1311 /* Copying structures onto other structures that have been neatly zeroed
1312 has a subtle gotcha. Consider XPVMG
1314 +------+------+------+------+------+-------+-------+
1315 | NV | CUR | LEN | IV | MAGIC | STASH |
1316 +------+------+------+------+------+-------+-------+
1317 0 4 8 12 16 20 24 28
1319 where NVs are aligned to 8 bytes, so that sizeof that structure is
1320 actually 32 bytes long, with 4 bytes of padding at the end:
1322 +------+------+------+------+------+-------+-------+------+
1323 | NV | CUR | LEN | IV | MAGIC | STASH | ??? |
1324 +------+------+------+------+------+-------+-------+------+
1325 0 4 8 12 16 20 24 28 32
1327 so what happens if you allocate memory for this structure:
1329 +------+------+------+------+------+-------+-------+------+------+...
1330 | NV | CUR | LEN | IV | MAGIC | STASH | GP | NAME |
1331 +------+------+------+------+------+-------+-------+------+------+...
1332 0 4 8 12 16 20 24 28 32 36
1334 zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
1335 expect, because you copy the area marked ??? onto GP. Now, ??? may have
1336 started out as zero once, but it's quite possible that it isn't. So now,
1337 rather than a nicely zeroed GP, you have it pointing somewhere random.
1340 (In fact, GP ends up pointing at a previous GP structure, because the
1341 principle cause of the padding in XPVMG getting garbage is a copy of
1342 sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob)
1344 So we are careful and work out the size of used parts of all the
1347 switch (SvTYPE(sv)) {
1353 else if (mt < SVt_PVIV)
1355 old_body_offset = STRUCT_OFFSET(XPVIV, xiv_iv);
1356 old_body_length = sizeof(IV);
1359 old_body_arena = (void **) &PL_xnv_root;
1360 old_body_length = sizeof(NV);
1361 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1370 old_body_arena = (void **) &PL_xpv_root;
1371 old_body_offset = STRUCT_OFFSET(XPV, xpv_cur)
1372 - STRUCT_OFFSET(xpv_allocated, xpv_cur);
1373 old_body_length = STRUCT_OFFSET(XPV, xpv_len)
1374 + sizeof (((XPV*)SvANY(sv))->xpv_len)
1378 else if (mt == SVt_NV)
1382 old_body_arena = (void **) &PL_xpviv_root;
1383 old_body_offset = STRUCT_OFFSET(XPVIV, xpv_cur)
1384 - STRUCT_OFFSET(xpviv_allocated, xpv_cur);
1385 old_body_length = STRUCT_OFFSET(XPVIV, xiv_u)
1386 + sizeof (((XPVIV*)SvANY(sv))->xiv_u)
1390 old_body_arena = (void **) &PL_xpvnv_root;
1391 old_body_length = STRUCT_OFFSET(XPVNV, xiv_u)
1392 + sizeof (((XPVNV*)SvANY(sv))->xiv_u);
1393 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1398 /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1399 there's no way that it can be safely upgraded, because perl.c
1400 expects to Safefree(SvANY(PL_mess_sv)) */
1401 assert(sv != PL_mess_sv);
1402 /* This flag bit is used to mean other things in other scalar types.
1403 Given that it only has meaning inside the pad, it shouldn't be set
1404 on anything that can get upgraded. */
1405 assert((SvFLAGS(sv) & SVpad_TYPED) == 0);
1406 old_body_arena = (void **) &PL_xpvmg_root;
1407 old_body_length = STRUCT_OFFSET(XPVMG, xmg_stash)
1408 + sizeof (((XPVMG*)SvANY(sv))->xmg_stash);
1409 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1414 Perl_croak(aTHX_ "Can't upgrade that kind of scalar");
1417 SvFLAGS(sv) &= ~SVTYPEMASK;
1422 Perl_croak(aTHX_ "Can't upgrade to undef");
1424 assert(old_type == SVt_NULL);
1425 SvANY(sv) = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
1429 assert(old_type == SVt_NULL);
1430 SvANY(sv) = new_XNV();
1434 assert(old_type == SVt_NULL);
1435 SvANY(sv) = &sv->sv_u.svu_rv;
1439 SvANY(sv) = new_XPVHV();
1442 HvTOTALKEYS(sv) = 0;
1447 SvANY(sv) = new_XPVAV();
1454 /* SVt_NULL isn't the only thing upgraded to AV or HV.
1455 The target created by newSVrv also is, and it can have magic.
1456 However, it never has SvPVX set.
1458 if (old_type >= SVt_RV) {
1459 assert(SvPVX_const(sv) == 0);
1462 /* Could put this in the else clause below, as PVMG must have SvPVX
1463 0 already (the assertion above) */
1464 SvPV_set(sv, (char*)0);
1466 if (old_type >= SVt_PVMG) {
1467 SvMAGIC_set(sv, ((XPVMG*)old_body)->xmg_magic);
1468 SvSTASH_set(sv, ((XPVMG*)old_body)->xmg_stash);
1476 new_body = new_XPVIO();
1477 new_body_length = sizeof(XPVIO);
1480 new_body = new_XPVFM();
1481 new_body_length = sizeof(XPVFM);
1485 new_body_length = sizeof(XPVBM);
1486 new_body_arena = (void **) &PL_xpvbm_root;
1487 new_body_arenaroot = (void **) &PL_xpvbm_arenaroot;
1490 new_body_length = sizeof(XPVGV);
1491 new_body_arena = (void **) &PL_xpvgv_root;
1492 new_body_arenaroot = (void **) &PL_xpvgv_arenaroot;
1495 new_body_length = sizeof(XPVCV);
1496 new_body_arena = (void **) &PL_xpvcv_root;
1497 new_body_arenaroot = (void **) &PL_xpvcv_arenaroot;
1500 new_body_length = sizeof(XPVLV);
1501 new_body_arena = (void **) &PL_xpvlv_root;
1502 new_body_arenaroot = (void **) &PL_xpvlv_arenaroot;
1505 new_body_length = sizeof(XPVMG);
1506 new_body_arena = (void **) &PL_xpvmg_root;
1507 new_body_arenaroot = (void **) &PL_xpvmg_arenaroot;
1510 new_body_length = sizeof(XPVNV);
1511 new_body_arena = (void **) &PL_xpvnv_root;
1512 new_body_arenaroot = (void **) &PL_xpvnv_arenaroot;
1515 new_body_offset = STRUCT_OFFSET(XPVIV, xpv_cur)
1516 - STRUCT_OFFSET(xpviv_allocated, xpv_cur);
1517 new_body_length = sizeof(XPVIV) - new_body_offset;
1518 new_body_arena = (void **) &PL_xpviv_root;
1519 new_body_arenaroot = (void **) &PL_xpviv_arenaroot;
1520 /* XXX Is this still needed? Was it ever needed? Surely as there is
1521 no route from NV to PVIV, NOK can never be true */
1525 goto new_body_no_NV;
1527 new_body_offset = STRUCT_OFFSET(XPV, xpv_cur)
1528 - STRUCT_OFFSET(xpv_allocated, xpv_cur);
1529 new_body_length = sizeof(XPV) - new_body_offset;
1530 new_body_arena = (void **) &PL_xpv_root;
1531 new_body_arenaroot = (void **) &PL_xpv_arenaroot;
1533 /* PV and PVIV don't have an NV slot. */
1534 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1539 assert(new_body_length);
1541 /* This points to the start of the allocated area. */
1542 new_body = S_new_body(aTHX_ new_body_arenaroot, new_body_arena,
1545 /* We always allocated the full length item with PURIFY */
1546 new_body_length += new_body_offset;
1547 new_body_offset = 0;
1548 new_body = my_safemalloc(new_body_length);
1552 Zero(new_body, new_body_length, char);
1553 new_body = ((char *)new_body) - new_body_offset;
1554 SvANY(sv) = new_body;
1556 if (old_body_length) {
1557 Copy((char *)old_body + old_body_offset,
1558 (char *)new_body + old_body_offset,
1559 old_body_length, char);
1562 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1568 IoPAGE_LEN(sv) = 60;
1569 if (old_type < SVt_RV)
1573 Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu", mt);
1577 if (old_body_arena) {
1579 my_safefree(old_body);
1581 del_body((void*)((char*)old_body + old_body_offset),
1588 =for apidoc sv_backoff
1590 Remove any string offset. You should normally use the C<SvOOK_off> macro
1597 Perl_sv_backoff(pTHX_ register SV *sv)
1600 assert(SvTYPE(sv) != SVt_PVHV);
1601 assert(SvTYPE(sv) != SVt_PVAV);
1603 const char * const s = SvPVX_const(sv);
1604 SvLEN_set(sv, SvLEN(sv) + SvIVX(sv));
1605 SvPV_set(sv, SvPVX(sv) - SvIVX(sv));
1607 Move(s, SvPVX(sv), SvCUR(sv)+1, char);
1609 SvFLAGS(sv) &= ~SVf_OOK;
1616 Expands the character buffer in the SV. If necessary, uses C<sv_unref> and
1617 upgrades the SV to C<SVt_PV>. Returns a pointer to the character buffer.
1618 Use the C<SvGROW> wrapper instead.
1624 Perl_sv_grow(pTHX_ register SV *sv, register STRLEN newlen)
1628 #ifdef HAS_64K_LIMIT
1629 if (newlen >= 0x10000) {
1630 PerlIO_printf(Perl_debug_log,
1631 "Allocation too large: %"UVxf"\n", (UV)newlen);
1634 #endif /* HAS_64K_LIMIT */
1637 if (SvTYPE(sv) < SVt_PV) {
1638 sv_upgrade(sv, SVt_PV);
1639 s = SvPVX_mutable(sv);
1641 else if (SvOOK(sv)) { /* pv is offset? */
1643 s = SvPVX_mutable(sv);
1644 if (newlen > SvLEN(sv))
1645 newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1646 #ifdef HAS_64K_LIMIT
1647 if (newlen >= 0x10000)
1652 s = SvPVX_mutable(sv);
1654 if (newlen > SvLEN(sv)) { /* need more room? */
1655 newlen = PERL_STRLEN_ROUNDUP(newlen);
1656 if (SvLEN(sv) && s) {
1658 const STRLEN l = malloced_size((void*)SvPVX_const(sv));
1664 s = saferealloc(s, newlen);
1667 s = safemalloc(newlen);
1668 if (SvPVX_const(sv) && SvCUR(sv)) {
1669 Move(SvPVX_const(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1673 SvLEN_set(sv, newlen);
1679 =for apidoc sv_setiv
1681 Copies an integer into the given SV, upgrading first if necessary.
1682 Does not handle 'set' magic. See also C<sv_setiv_mg>.
1688 Perl_sv_setiv(pTHX_ register SV *sv, IV i)
1690 SV_CHECK_THINKFIRST_COW_DROP(sv);
1691 switch (SvTYPE(sv)) {
1693 sv_upgrade(sv, SVt_IV);
1696 sv_upgrade(sv, SVt_PVNV);
1700 sv_upgrade(sv, SVt_PVIV);
1709 Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1712 (void)SvIOK_only(sv); /* validate number */
1718 =for apidoc sv_setiv_mg
1720 Like C<sv_setiv>, but also handles 'set' magic.
1726 Perl_sv_setiv_mg(pTHX_ register SV *sv, IV i)
1733 =for apidoc sv_setuv
1735 Copies an unsigned integer into the given SV, upgrading first if necessary.
1736 Does not handle 'set' magic. See also C<sv_setuv_mg>.
1742 Perl_sv_setuv(pTHX_ register SV *sv, UV u)
1744 /* With these two if statements:
1745 u=1.49 s=0.52 cu=72.49 cs=10.64 scripts=270 tests=20865
1748 u=1.35 s=0.47 cu=73.45 cs=11.43 scripts=270 tests=20865
1750 If you wish to remove them, please benchmark to see what the effect is
1752 if (u <= (UV)IV_MAX) {
1753 sv_setiv(sv, (IV)u);
1762 =for apidoc sv_setuv_mg
1764 Like C<sv_setuv>, but also handles 'set' magic.
1770 Perl_sv_setuv_mg(pTHX_ register SV *sv, UV u)
1772 /* With these two if statements:
1773 u=1.49 s=0.52 cu=72.49 cs=10.64 scripts=270 tests=20865
1776 u=1.35 s=0.47 cu=73.45 cs=11.43 scripts=270 tests=20865
1778 If you wish to remove them, please benchmark to see what the effect is
1780 if (u <= (UV)IV_MAX) {
1781 sv_setiv(sv, (IV)u);
1791 =for apidoc sv_setnv
1793 Copies a double into the given SV, upgrading first if necessary.
1794 Does not handle 'set' magic. See also C<sv_setnv_mg>.
1800 Perl_sv_setnv(pTHX_ register SV *sv, NV num)
1802 SV_CHECK_THINKFIRST_COW_DROP(sv);
1803 switch (SvTYPE(sv)) {
1806 sv_upgrade(sv, SVt_NV);
1811 sv_upgrade(sv, SVt_PVNV);
1820 Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
1824 (void)SvNOK_only(sv); /* validate number */
1829 =for apidoc sv_setnv_mg
1831 Like C<sv_setnv>, but also handles 'set' magic.
1837 Perl_sv_setnv_mg(pTHX_ register SV *sv, NV num)
1843 /* Print an "isn't numeric" warning, using a cleaned-up,
1844 * printable version of the offending string
1848 S_not_a_number(pTHX_ SV *sv)
1855 dsv = sv_2mortal(newSVpv("", 0));
1856 pv = sv_uni_display(dsv, sv, 10, 0);
1859 char *limit = tmpbuf + sizeof(tmpbuf) - 8;
1860 /* each *s can expand to 4 chars + "...\0",
1861 i.e. need room for 8 chars */
1863 const char *s, *end;
1864 for (s = SvPVX_const(sv), end = s + SvCUR(sv); s < end && d < limit;
1867 if (ch & 128 && !isPRINT_LC(ch)) {
1876 else if (ch == '\r') {
1880 else if (ch == '\f') {
1884 else if (ch == '\\') {
1888 else if (ch == '\0') {
1892 else if (isPRINT_LC(ch))
1909 Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1910 "Argument \"%s\" isn't numeric in %s", pv,
1913 Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1914 "Argument \"%s\" isn't numeric", pv);
1918 =for apidoc looks_like_number
1920 Test if the content of an SV looks like a number (or is a number).
1921 C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1922 non-numeric warning), even if your atof() doesn't grok them.
1928 Perl_looks_like_number(pTHX_ SV *sv)
1930 register const char *sbegin;
1934 sbegin = SvPVX_const(sv);
1937 else if (SvPOKp(sv))
1938 sbegin = SvPV_const(sv, len);
1940 return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
1941 return grok_number(sbegin, len, NULL);
1944 /* Actually, ISO C leaves conversion of UV to IV undefined, but
1945 until proven guilty, assume that things are not that bad... */
1950 As 64 bit platforms often have an NV that doesn't preserve all bits of
1951 an IV (an assumption perl has been based on to date) it becomes necessary
1952 to remove the assumption that the NV always carries enough precision to
1953 recreate the IV whenever needed, and that the NV is the canonical form.
1954 Instead, IV/UV and NV need to be given equal rights. So as to not lose
1955 precision as a side effect of conversion (which would lead to insanity
1956 and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1957 1) to distinguish between IV/UV/NV slots that have cached a valid
1958 conversion where precision was lost and IV/UV/NV slots that have a
1959 valid conversion which has lost no precision
1960 2) to ensure that if a numeric conversion to one form is requested that
1961 would lose precision, the precise conversion (or differently
1962 imprecise conversion) is also performed and cached, to prevent
1963 requests for different numeric formats on the same SV causing
1964 lossy conversion chains. (lossless conversion chains are perfectly
1969 SvIOKp is true if the IV slot contains a valid value
1970 SvIOK is true only if the IV value is accurate (UV if SvIOK_UV true)
1971 SvNOKp is true if the NV slot contains a valid value
1972 SvNOK is true only if the NV value is accurate
1975 while converting from PV to NV, check to see if converting that NV to an
1976 IV(or UV) would lose accuracy over a direct conversion from PV to
1977 IV(or UV). If it would, cache both conversions, return NV, but mark
1978 SV as IOK NOKp (ie not NOK).
1980 While converting from PV to IV, check to see if converting that IV to an
1981 NV would lose accuracy over a direct conversion from PV to NV. If it
1982 would, cache both conversions, flag similarly.
1984 Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1985 correctly because if IV & NV were set NV *always* overruled.
1986 Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1987 changes - now IV and NV together means that the two are interchangeable:
1988 SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
1990 The benefit of this is that operations such as pp_add know that if
1991 SvIOK is true for both left and right operands, then integer addition
1992 can be used instead of floating point (for cases where the result won't
1993 overflow). Before, floating point was always used, which could lead to
1994 loss of precision compared with integer addition.
1996 * making IV and NV equal status should make maths accurate on 64 bit
1998 * may speed up maths somewhat if pp_add and friends start to use
1999 integers when possible instead of fp. (Hopefully the overhead in
2000 looking for SvIOK and checking for overflow will not outweigh the
2001 fp to integer speedup)
2002 * will slow down integer operations (callers of SvIV) on "inaccurate"
2003 values, as the change from SvIOK to SvIOKp will cause a call into
2004 sv_2iv each time rather than a macro access direct to the IV slot
2005 * should speed up number->string conversion on integers as IV is
2006 favoured when IV and NV are equally accurate
2008 ####################################################################
2009 You had better be using SvIOK_notUV if you want an IV for arithmetic:
2010 SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
2011 On the other hand, SvUOK is true iff UV.
2012 ####################################################################
2014 Your mileage will vary depending your CPU's relative fp to integer
2018 #ifndef NV_PRESERVES_UV
2019 # define IS_NUMBER_UNDERFLOW_IV 1
2020 # define IS_NUMBER_UNDERFLOW_UV 2
2021 # define IS_NUMBER_IV_AND_UV 2
2022 # define IS_NUMBER_OVERFLOW_IV 4
2023 # define IS_NUMBER_OVERFLOW_UV 5
2025 /* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
2027 /* For sv_2nv these three cases are "SvNOK and don't bother casting" */
2029 S_sv_2iuv_non_preserve(pTHX_ register SV *sv, I32 numtype)
2031 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));
2032 if (SvNVX(sv) < (NV)IV_MIN) {
2033 (void)SvIOKp_on(sv);
2035 SvIV_set(sv, IV_MIN);
2036 return IS_NUMBER_UNDERFLOW_IV;
2038 if (SvNVX(sv) > (NV)UV_MAX) {
2039 (void)SvIOKp_on(sv);
2042 SvUV_set(sv, UV_MAX);
2043 return IS_NUMBER_OVERFLOW_UV;
2045 (void)SvIOKp_on(sv);
2047 /* Can't use strtol etc to convert this string. (See truth table in
2049 if (SvNVX(sv) <= (UV)IV_MAX) {
2050 SvIV_set(sv, I_V(SvNVX(sv)));
2051 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2052 SvIOK_on(sv); /* Integer is precise. NOK, IOK */
2054 /* Integer is imprecise. NOK, IOKp */
2056 return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
2059 SvUV_set(sv, U_V(SvNVX(sv)));
2060 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2061 if (SvUVX(sv) == UV_MAX) {
2062 /* As we know that NVs don't preserve UVs, UV_MAX cannot
2063 possibly be preserved by NV. Hence, it must be overflow.
2065 return IS_NUMBER_OVERFLOW_UV;
2067 SvIOK_on(sv); /* Integer is precise. NOK, UOK */
2069 /* Integer is imprecise. NOK, IOKp */
2071 return IS_NUMBER_OVERFLOW_IV;
2073 #endif /* !NV_PRESERVES_UV*/
2075 /* sv_2iv() is now a macro using Perl_sv_2iv_flags();
2076 * this function provided for binary compatibility only
2080 Perl_sv_2iv(pTHX_ register SV *sv)
2082 return sv_2iv_flags(sv, SV_GMAGIC);
2086 =for apidoc sv_2iv_flags
2088 Return the integer value of an SV, doing any necessary string
2089 conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2090 Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2096 Perl_sv_2iv_flags(pTHX_ register SV *sv, I32 flags)
2100 if (SvGMAGICAL(sv)) {
2101 if (flags & SV_GMAGIC)
2106 return I_V(SvNVX(sv));
2108 if (SvPOKp(sv) && SvLEN(sv))
2111 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2112 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2118 if (SvTHINKFIRST(sv)) {
2121 if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,numer)) &&
2122 (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv))))
2123 return SvIV(tmpstr);
2124 return PTR2IV(SvRV(sv));
2127 sv_force_normal_flags(sv, 0);
2129 if (SvREADONLY(sv) && !SvOK(sv)) {
2130 if (ckWARN(WARN_UNINITIALIZED))
2137 return (IV)(SvUVX(sv));
2144 /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
2145 * without also getting a cached IV/UV from it at the same time
2146 * (ie PV->NV conversion should detect loss of accuracy and cache
2147 * IV or UV at same time to avoid this. NWC */
2149 if (SvTYPE(sv) == SVt_NV)
2150 sv_upgrade(sv, SVt_PVNV);
2152 (void)SvIOKp_on(sv); /* Must do this first, to clear any SvOOK */
2153 /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
2154 certainly cast into the IV range at IV_MAX, whereas the correct
2155 answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
2157 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2158 SvIV_set(sv, I_V(SvNVX(sv)));
2159 if (SvNVX(sv) == (NV) SvIVX(sv)
2160 #ifndef NV_PRESERVES_UV
2161 && (((UV)1 << NV_PRESERVES_UV_BITS) >
2162 (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2163 /* Don't flag it as "accurately an integer" if the number
2164 came from a (by definition imprecise) NV operation, and
2165 we're outside the range of NV integer precision */
2168 SvIOK_on(sv); /* Can this go wrong with rounding? NWC */
2169 DEBUG_c(PerlIO_printf(Perl_debug_log,
2170 "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
2176 /* IV not precise. No need to convert from PV, as NV
2177 conversion would already have cached IV if it detected
2178 that PV->IV would be better than PV->NV->IV
2179 flags already correct - don't set public IOK. */
2180 DEBUG_c(PerlIO_printf(Perl_debug_log,
2181 "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
2186 /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2187 but the cast (NV)IV_MIN rounds to a the value less (more
2188 negative) than IV_MIN which happens to be equal to SvNVX ??
2189 Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2190 NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2191 (NV)UVX == NVX are both true, but the values differ. :-(
2192 Hopefully for 2s complement IV_MIN is something like
2193 0x8000000000000000 which will be exact. NWC */
2196 SvUV_set(sv, U_V(SvNVX(sv)));
2198 (SvNVX(sv) == (NV) SvUVX(sv))
2199 #ifndef NV_PRESERVES_UV
2200 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2201 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2202 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2203 /* Don't flag it as "accurately an integer" if the number
2204 came from a (by definition imprecise) NV operation, and
2205 we're outside the range of NV integer precision */
2211 DEBUG_c(PerlIO_printf(Perl_debug_log,
2212 "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
2216 return (IV)SvUVX(sv);
2219 else if (SvPOKp(sv) && SvLEN(sv)) {
2221 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2222 /* We want to avoid a possible problem when we cache an IV which
2223 may be later translated to an NV, and the resulting NV is not
2224 the same as the direct translation of the initial string
2225 (eg 123.456 can shortcut to the IV 123 with atol(), but we must
2226 be careful to ensure that the value with the .456 is around if the
2227 NV value is requested in the future).
2229 This means that if we cache such an IV, we need to cache the
2230 NV as well. Moreover, we trade speed for space, and do not
2231 cache the NV if we are sure it's not needed.
2234 /* SVt_PVNV is one higher than SVt_PVIV, hence this order */
2235 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2236 == IS_NUMBER_IN_UV) {
2237 /* It's definitely an integer, only upgrade to PVIV */
2238 if (SvTYPE(sv) < SVt_PVIV)
2239 sv_upgrade(sv, SVt_PVIV);
2241 } else if (SvTYPE(sv) < SVt_PVNV)
2242 sv_upgrade(sv, SVt_PVNV);
2244 /* If NV preserves UV then we only use the UV value if we know that
2245 we aren't going to call atof() below. If NVs don't preserve UVs
2246 then the value returned may have more precision than atof() will
2247 return, even though value isn't perfectly accurate. */
2248 if ((numtype & (IS_NUMBER_IN_UV
2249 #ifdef NV_PRESERVES_UV
2252 )) == IS_NUMBER_IN_UV) {
2253 /* This won't turn off the public IOK flag if it was set above */
2254 (void)SvIOKp_on(sv);
2256 if (!(numtype & IS_NUMBER_NEG)) {
2258 if (value <= (UV)IV_MAX) {
2259 SvIV_set(sv, (IV)value);
2261 SvUV_set(sv, value);
2265 /* 2s complement assumption */
2266 if (value <= (UV)IV_MIN) {
2267 SvIV_set(sv, -(IV)value);
2269 /* Too negative for an IV. This is a double upgrade, but
2270 I'm assuming it will be rare. */
2271 if (SvTYPE(sv) < SVt_PVNV)
2272 sv_upgrade(sv, SVt_PVNV);
2276 SvNV_set(sv, -(NV)value);
2277 SvIV_set(sv, IV_MIN);
2281 /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2282 will be in the previous block to set the IV slot, and the next
2283 block to set the NV slot. So no else here. */
2285 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2286 != IS_NUMBER_IN_UV) {
2287 /* It wasn't an (integer that doesn't overflow the UV). */
2288 SvNV_set(sv, Atof(SvPVX_const(sv)));
2290 if (! numtype && ckWARN(WARN_NUMERIC))
2293 #if defined(USE_LONG_DOUBLE)
2294 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" PERL_PRIgldbl ")\n",
2295 PTR2UV(sv), SvNVX(sv)));
2297 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"NVgf")\n",
2298 PTR2UV(sv), SvNVX(sv)));
2302 #ifdef NV_PRESERVES_UV
2303 (void)SvIOKp_on(sv);
2305 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2306 SvIV_set(sv, I_V(SvNVX(sv)));
2307 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2310 /* Integer is imprecise. NOK, IOKp */
2312 /* UV will not work better than IV */
2314 if (SvNVX(sv) > (NV)UV_MAX) {
2316 /* Integer is inaccurate. NOK, IOKp, is UV */
2317 SvUV_set(sv, UV_MAX);
2320 SvUV_set(sv, U_V(SvNVX(sv)));
2321 /* 0xFFFFFFFFFFFFFFFF not an issue in here */
2322 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2326 /* Integer is imprecise. NOK, IOKp, is UV */
2332 #else /* NV_PRESERVES_UV */
2333 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2334 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2335 /* The IV slot will have been set from value returned by
2336 grok_number above. The NV slot has just been set using
2339 assert (SvIOKp(sv));
2341 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2342 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2343 /* Small enough to preserve all bits. */
2344 (void)SvIOKp_on(sv);
2346 SvIV_set(sv, I_V(SvNVX(sv)));
2347 if ((NV)(SvIVX(sv)) == SvNVX(sv))
2349 /* Assumption: first non-preserved integer is < IV_MAX,
2350 this NV is in the preserved range, therefore: */
2351 if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2353 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);
2357 0 0 already failed to read UV.
2358 0 1 already failed to read UV.
2359 1 0 you won't get here in this case. IV/UV
2360 slot set, public IOK, Atof() unneeded.
2361 1 1 already read UV.
2362 so there's no point in sv_2iuv_non_preserve() attempting
2363 to use atol, strtol, strtoul etc. */
2364 if (sv_2iuv_non_preserve (sv, numtype)
2365 >= IS_NUMBER_OVERFLOW_IV)
2369 #endif /* NV_PRESERVES_UV */
2372 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP))
2374 if (SvTYPE(sv) < SVt_IV)
2375 /* Typically the caller expects that sv_any is not NULL now. */
2376 sv_upgrade(sv, SVt_IV);
2379 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2380 PTR2UV(sv),SvIVX(sv)));
2381 return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
2384 /* sv_2uv() is now a macro using Perl_sv_2uv_flags();
2385 * this function provided for binary compatibility only
2389 Perl_sv_2uv(pTHX_ register SV *sv)
2391 return sv_2uv_flags(sv, SV_GMAGIC);
2395 =for apidoc sv_2uv_flags
2397 Return the unsigned integer value of an SV, doing any necessary string
2398 conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2399 Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
2405 Perl_sv_2uv_flags(pTHX_ register SV *sv, I32 flags)
2409 if (SvGMAGICAL(sv)) {
2410 if (flags & SV_GMAGIC)
2415 return U_V(SvNVX(sv));
2416 if (SvPOKp(sv) && SvLEN(sv))
2419 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2420 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2426 if (SvTHINKFIRST(sv)) {
2429 if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,numer)) &&
2430 (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv))))
2431 return SvUV(tmpstr);
2432 return PTR2UV(SvRV(sv));
2435 sv_force_normal_flags(sv, 0);
2437 if (SvREADONLY(sv) && !SvOK(sv)) {
2438 if (ckWARN(WARN_UNINITIALIZED))
2448 return (UV)SvIVX(sv);
2452 /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
2453 * without also getting a cached IV/UV from it at the same time
2454 * (ie PV->NV conversion should detect loss of accuracy and cache
2455 * IV or UV at same time to avoid this. */
2456 /* IV-over-UV optimisation - choose to cache IV if possible */
2458 if (SvTYPE(sv) == SVt_NV)
2459 sv_upgrade(sv, SVt_PVNV);
2461 (void)SvIOKp_on(sv); /* Must do this first, to clear any SvOOK */
2462 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2463 SvIV_set(sv, I_V(SvNVX(sv)));
2464 if (SvNVX(sv) == (NV) SvIVX(sv)
2465 #ifndef NV_PRESERVES_UV
2466 && (((UV)1 << NV_PRESERVES_UV_BITS) >
2467 (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2468 /* Don't flag it as "accurately an integer" if the number
2469 came from a (by definition imprecise) NV operation, and
2470 we're outside the range of NV integer precision */
2473 SvIOK_on(sv); /* Can this go wrong with rounding? NWC */
2474 DEBUG_c(PerlIO_printf(Perl_debug_log,
2475 "0x%"UVxf" uv(%"NVgf" => %"IVdf") (precise)\n",
2481 /* IV not precise. No need to convert from PV, as NV
2482 conversion would already have cached IV if it detected
2483 that PV->IV would be better than PV->NV->IV
2484 flags already correct - don't set public IOK. */
2485 DEBUG_c(PerlIO_printf(Perl_debug_log,
2486 "0x%"UVxf" uv(%"NVgf" => %"IVdf") (imprecise)\n",
2491 /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2492 but the cast (NV)IV_MIN rounds to a the value less (more
2493 negative) than IV_MIN which happens to be equal to SvNVX ??
2494 Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2495 NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2496 (NV)UVX == NVX are both true, but the values differ. :-(
2497 Hopefully for 2s complement IV_MIN is something like
2498 0x8000000000000000 which will be exact. NWC */
2501 SvUV_set(sv, U_V(SvNVX(sv)));
2503 (SvNVX(sv) == (NV) SvUVX(sv))
2504 #ifndef NV_PRESERVES_UV
2505 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2506 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2507 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2508 /* Don't flag it as "accurately an integer" if the number
2509 came from a (by definition imprecise) NV operation, and
2510 we're outside the range of NV integer precision */
2515 DEBUG_c(PerlIO_printf(Perl_debug_log,
2516 "0x%"UVxf" 2uv(%"UVuf" => %"IVdf") (as unsigned)\n",
2522 else if (SvPOKp(sv) && SvLEN(sv)) {
2524 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2526 /* We want to avoid a possible problem when we cache a UV which
2527 may be later translated to an NV, and the resulting NV is not
2528 the translation of the initial data.
2530 This means that if we cache such a UV, we need to cache the
2531 NV as well. Moreover, we trade speed for space, and do not
2532 cache the NV if not needed.
2535 /* SVt_PVNV is one higher than SVt_PVIV, hence this order */
2536 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2537 == IS_NUMBER_IN_UV) {
2538 /* It's definitely an integer, only upgrade to PVIV */
2539 if (SvTYPE(sv) < SVt_PVIV)
2540 sv_upgrade(sv, SVt_PVIV);
2542 } else if (SvTYPE(sv) < SVt_PVNV)
2543 sv_upgrade(sv, SVt_PVNV);
2545 /* If NV preserves UV then we only use the UV value if we know that
2546 we aren't going to call atof() below. If NVs don't preserve UVs
2547 then the value returned may have more precision than atof() will
2548 return, even though it isn't accurate. */
2549 if ((numtype & (IS_NUMBER_IN_UV
2550 #ifdef NV_PRESERVES_UV
2553 )) == IS_NUMBER_IN_UV) {
2554 /* This won't turn off the public IOK flag if it was set above */
2555 (void)SvIOKp_on(sv);
2557 if (!(numtype & IS_NUMBER_NEG)) {
2559 if (value <= (UV)IV_MAX) {
2560 SvIV_set(sv, (IV)value);
2562 /* it didn't overflow, and it was positive. */
2563 SvUV_set(sv, value);
2567 /* 2s complement assumption */
2568 if (value <= (UV)IV_MIN) {
2569 SvIV_set(sv, -(IV)value);
2571 /* Too negative for an IV. This is a double upgrade, but
2572 I'm assuming it will be rare. */
2573 if (SvTYPE(sv) < SVt_PVNV)
2574 sv_upgrade(sv, SVt_PVNV);
2578 SvNV_set(sv, -(NV)value);
2579 SvIV_set(sv, IV_MIN);
2584 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2585 != IS_NUMBER_IN_UV) {
2586 /* It wasn't an integer, or it overflowed the UV. */
2587 SvNV_set(sv, Atof(SvPVX_const(sv)));
2589 if (! numtype && ckWARN(WARN_NUMERIC))
2592 #if defined(USE_LONG_DOUBLE)
2593 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%" PERL_PRIgldbl ")\n",
2594 PTR2UV(sv), SvNVX(sv)));
2596 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"NVgf")\n",
2597 PTR2UV(sv), SvNVX(sv)));
2600 #ifdef NV_PRESERVES_UV
2601 (void)SvIOKp_on(sv);
2603 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2604 SvIV_set(sv, I_V(SvNVX(sv)));
2605 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2608 /* Integer is imprecise. NOK, IOKp */
2610 /* UV will not work better than IV */
2612 if (SvNVX(sv) > (NV)UV_MAX) {
2614 /* Integer is inaccurate. NOK, IOKp, is UV */
2615 SvUV_set(sv, UV_MAX);
2618 SvUV_set(sv, U_V(SvNVX(sv)));
2619 /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2620 NV preservse UV so can do correct comparison. */
2621 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2625 /* Integer is imprecise. NOK, IOKp, is UV */
2630 #else /* NV_PRESERVES_UV */
2631 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2632 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2633 /* The UV slot will have been set from value returned by
2634 grok_number above. The NV slot has just been set using
2637 assert (SvIOKp(sv));
2639 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2640 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2641 /* Small enough to preserve all bits. */
2642 (void)SvIOKp_on(sv);
2644 SvIV_set(sv, I_V(SvNVX(sv)));
2645 if ((NV)(SvIVX(sv)) == SvNVX(sv))
2647 /* Assumption: first non-preserved integer is < IV_MAX,
2648 this NV is in the preserved range, therefore: */
2649 if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2651 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);
2654 sv_2iuv_non_preserve (sv, numtype);
2656 #endif /* NV_PRESERVES_UV */
2660 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2661 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2664 if (SvTYPE(sv) < SVt_IV)
2665 /* Typically the caller expects that sv_any is not NULL now. */
2666 sv_upgrade(sv, SVt_IV);
2670 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2671 PTR2UV(sv),SvUVX(sv)));
2672 return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
2678 Return the num value of an SV, doing any necessary string or integer
2679 conversion, magic etc. Normally used via the C<SvNV(sv)> and C<SvNVx(sv)>
2686 Perl_sv_2nv(pTHX_ register SV *sv)
2690 if (SvGMAGICAL(sv)) {
2694 if (SvPOKp(sv) && SvLEN(sv)) {
2695 if (ckWARN(WARN_NUMERIC) && !SvIOKp(sv) &&
2696 !grok_number(SvPVX_const(sv), SvCUR(sv), NULL))
2698 return Atof(SvPVX_const(sv));
2702 return (NV)SvUVX(sv);
2704 return (NV)SvIVX(sv);
2707 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2708 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
2714 if (SvTHINKFIRST(sv)) {
2717 if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,numer)) &&
2718 (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv))))
2719 return SvNV(tmpstr);
2720 return PTR2NV(SvRV(sv));
2723 sv_force_normal_flags(sv, 0);
2725 if (SvREADONLY(sv) && !SvOK(sv)) {
2726 if (ckWARN(WARN_UNINITIALIZED))
2731 if (SvTYPE(sv) < SVt_NV) {
2732 if (SvTYPE(sv) == SVt_IV)
2733 sv_upgrade(sv, SVt_PVNV);
2735 sv_upgrade(sv, SVt_NV);
2736 #ifdef USE_LONG_DOUBLE
2738 STORE_NUMERIC_LOCAL_SET_STANDARD();
2739 PerlIO_printf(Perl_debug_log,
2740 "0x%"UVxf" num(%" PERL_PRIgldbl ")\n",
2741 PTR2UV(sv), SvNVX(sv));
2742 RESTORE_NUMERIC_LOCAL();
2746 STORE_NUMERIC_LOCAL_SET_STANDARD();
2747 PerlIO_printf(Perl_debug_log, "0x%"UVxf" num(%"NVgf")\n",
2748 PTR2UV(sv), SvNVX(sv));
2749 RESTORE_NUMERIC_LOCAL();
2753 else if (SvTYPE(sv) < SVt_PVNV)
2754 sv_upgrade(sv, SVt_PVNV);
2759 SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
2760 #ifdef NV_PRESERVES_UV
2763 /* Only set the public NV OK flag if this NV preserves the IV */
2764 /* Check it's not 0xFFFFFFFFFFFFFFFF */
2765 if (SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
2766 : (SvIVX(sv) == I_V(SvNVX(sv))))
2772 else if (SvPOKp(sv) && SvLEN(sv)) {
2774 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2775 if (ckWARN(WARN_NUMERIC) && !SvIOKp(sv) && !numtype)
2777 #ifdef NV_PRESERVES_UV
2778 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2779 == IS_NUMBER_IN_UV) {
2780 /* It's definitely an integer */
2781 SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
2783 SvNV_set(sv, Atof(SvPVX_const(sv)));
2786 SvNV_set(sv, Atof(SvPVX_const(sv)));
2787 /* Only set the public NV OK flag if this NV preserves the value in
2788 the PV at least as well as an IV/UV would.
2789 Not sure how to do this 100% reliably. */
2790 /* if that shift count is out of range then Configure's test is
2791 wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2793 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2794 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2795 SvNOK_on(sv); /* Definitely small enough to preserve all bits */
2796 } else if (!(numtype & IS_NUMBER_IN_UV)) {
2797 /* Can't use strtol etc to convert this string, so don't try.
2798 sv_2iv and sv_2uv will use the NV to convert, not the PV. */
2801 /* value has been set. It may not be precise. */
2802 if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2803 /* 2s complement assumption for (UV)IV_MIN */
2804 SvNOK_on(sv); /* Integer is too negative. */
2809 if (numtype & IS_NUMBER_NEG) {
2810 SvIV_set(sv, -(IV)value);
2811 } else if (value <= (UV)IV_MAX) {
2812 SvIV_set(sv, (IV)value);
2814 SvUV_set(sv, value);
2818 if (numtype & IS_NUMBER_NOT_INT) {
2819 /* I believe that even if the original PV had decimals,
2820 they are lost beyond the limit of the FP precision.
2821 However, neither is canonical, so both only get p
2822 flags. NWC, 2000/11/25 */
2823 /* Both already have p flags, so do nothing */
2825 const NV nv = SvNVX(sv);
2826 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2827 if (SvIVX(sv) == I_V(nv)) {
2832 /* It had no "." so it must be integer. */
2835 /* between IV_MAX and NV(UV_MAX).
2836 Could be slightly > UV_MAX */
2838 if (numtype & IS_NUMBER_NOT_INT) {
2839 /* UV and NV both imprecise. */
2841 const UV nv_as_uv = U_V(nv);
2843 if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2854 #endif /* NV_PRESERVES_UV */
2857 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP))
2859 if (SvTYPE(sv) < SVt_NV)
2860 /* Typically the caller expects that sv_any is not NULL now. */
2861 /* XXX Ilya implies that this is a bug in callers that assume this
2862 and ideally should be fixed. */
2863 sv_upgrade(sv, SVt_NV);
2866 #if defined(USE_LONG_DOUBLE)
2868 STORE_NUMERIC_LOCAL_SET_STANDARD();
2869 PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" PERL_PRIgldbl ")\n",
2870 PTR2UV(sv), SvNVX(sv));
2871 RESTORE_NUMERIC_LOCAL();
2875 STORE_NUMERIC_LOCAL_SET_STANDARD();
2876 PerlIO_printf(Perl_debug_log, "0x%"UVxf" 1nv(%"NVgf")\n",
2877 PTR2UV(sv), SvNVX(sv));
2878 RESTORE_NUMERIC_LOCAL();
2884 /* asIV(): extract an integer from the string value of an SV.
2885 * Caller must validate PVX */
2888 S_asIV(pTHX_ SV *sv)
2891 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2893 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2894 == IS_NUMBER_IN_UV) {
2895 /* It's definitely an integer */
2896 if (numtype & IS_NUMBER_NEG) {
2897 if (value < (UV)IV_MIN)
2900 if (value < (UV)IV_MAX)
2905 if (ckWARN(WARN_NUMERIC))
2908 return I_V(Atof(SvPVX_const(sv)));
2911 /* asUV(): extract an unsigned integer from the string value of an SV
2912 * Caller must validate PVX */
2915 S_asUV(pTHX_ SV *sv)
2918 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2920 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2921 == IS_NUMBER_IN_UV) {
2922 /* It's definitely an integer */
2923 if (!(numtype & IS_NUMBER_NEG))
2927 if (ckWARN(WARN_NUMERIC))
2930 return U_V(Atof(SvPVX_const(sv)));
2934 =for apidoc sv_2pv_nolen
2936 Like C<sv_2pv()>, but doesn't return the length too. You should usually
2937 use the macro wrapper C<SvPV_nolen(sv)> instead.
2942 Perl_sv_2pv_nolen(pTHX_ register SV *sv)
2944 return sv_2pv(sv, 0);
2947 /* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2948 * UV as a string towards the end of buf, and return pointers to start and
2951 * We assume that buf is at least TYPE_CHARS(UV) long.
2955 uiv_2buf(char *buf, IV iv, UV uv, int is_uv, char **peob)
2957 char *ptr = buf + TYPE_CHARS(UV);
2971 *--ptr = '0' + (char)(uv % 10);
2979 /* sv_2pv() is now a macro using Perl_sv_2pv_flags();
2980 * this function provided for binary compatibility only
2984 Perl_sv_2pv(pTHX_ register SV *sv, STRLEN *lp)
2986 return sv_2pv_flags(sv, lp, SV_GMAGIC);
2990 =for apidoc sv_2pv_flags
2992 Returns a pointer to the string value of an SV, and sets *lp to its length.
2993 If flags includes SV_GMAGIC, does an mg_get() first. Coerces sv to a string
2995 Normally invoked via the C<SvPV_flags> macro. C<sv_2pv()> and C<sv_2pv_nomg>
2996 usually end up here too.
3002 Perl_sv_2pv_flags(pTHX_ register SV *sv, STRLEN *lp, I32 flags)
3007 char tbuf[64]; /* Must fit sprintf/Gconvert of longest IV/NV */
3008 char *tmpbuf = tbuf;
3015 if (SvGMAGICAL(sv)) {
3016 if (flags & SV_GMAGIC)
3021 if (flags & SV_MUTABLE_RETURN)
3022 return SvPVX_mutable(sv);
3023 if (flags & SV_CONST_RETURN)
3024 return (char *)SvPVX_const(sv);
3029 (void)sprintf(tmpbuf,"%"UVuf, (UV)SvUVX(sv));
3031 (void)sprintf(tmpbuf,"%"IVdf, (IV)SvIVX(sv));
3036 Gconvert(SvNVX(sv), NV_DIG, 0, tmpbuf);
3041 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
3042 if (ckWARN(WARN_UNINITIALIZED) && !PL_localizing)
3050 if (SvTHINKFIRST(sv)) {
3053 register const char *typestr;
3054 if (SvAMAGIC(sv) && (tmpstr=AMG_CALLun(sv,string)) &&
3055 (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
3057 /* char *pv = lp ? SvPV(tmpstr, *lp) : SvPV_nolen(tmpstr); */
3060 if ((SvFLAGS(tmpstr) & (SVf_POK)) == SVf_POK) {
3061 if (flags & SV_CONST_RETURN) {
3062 pv = (char *) SvPVX_const(tmpstr);
3064 pv = (flags & SV_MUTABLE_RETURN)
3065 ? SvPVX_mutable(tmpstr) : SvPVX(tmpstr);
3068 *lp = SvCUR(tmpstr);
3070 pv = sv_2pv_flags(tmpstr, lp, flags);
3081 typestr = "NULLREF";
3085 switch (SvTYPE(sv)) {
3087 if ( ((SvFLAGS(sv) &
3088 (SVs_OBJECT|SVf_OK|SVs_GMG|SVs_SMG|SVs_RMG))
3089 == (SVs_OBJECT|SVs_SMG))
3090 && (mg = mg_find(sv, PERL_MAGIC_qr))) {
3091 const regexp *re = (regexp *)mg->mg_obj;
3094 const char *fptr = "msix";
3099 char need_newline = 0;
3100 U16 reganch = (U16)((re->reganch & PMf_COMPILETIME) >> 12);
3102 while((ch = *fptr++)) {
3104 reflags[left++] = ch;
3107 reflags[right--] = ch;
3112 reflags[left] = '-';
3116 mg->mg_len = re->prelen + 4 + left;
3118 * If /x was used, we have to worry about a regex
3119 * ending with a comment later being embedded
3120 * within another regex. If so, we don't want this
3121 * regex's "commentization" to leak out to the
3122 * right part of the enclosing regex, we must cap
3123 * it with a newline.
3125 * So, if /x was used, we scan backwards from the
3126 * end of the regex. If we find a '#' before we
3127 * find a newline, we need to add a newline
3128 * ourself. If we find a '\n' first (or if we
3129 * don't find '#' or '\n'), we don't need to add
3130 * anything. -jfriedl
3132 if (PMf_EXTENDED & re->reganch)
3134 const char *endptr = re->precomp + re->prelen;
3135 while (endptr >= re->precomp)
3137 const char c = *(endptr--);
3139 break; /* don't need another */
3141 /* we end while in a comment, so we
3143 mg->mg_len++; /* save space for it */
3144 need_newline = 1; /* note to add it */
3150 New(616, mg->mg_ptr, mg->mg_len + 1 + left, char);
3151 Copy("(?", mg->mg_ptr, 2, char);
3152 Copy(reflags, mg->mg_ptr+2, left, char);
3153 Copy(":", mg->mg_ptr+left+2, 1, char);
3154 Copy(re->precomp, mg->mg_ptr+3+left, re->prelen, char);
3156 mg->mg_ptr[mg->mg_len - 2] = '\n';
3157 mg->mg_ptr[mg->mg_len - 1] = ')';
3158 mg->mg_ptr[mg->mg_len] = 0;
3160 PL_reginterp_cnt += re->program[0].next_off;
3162 if (re->reganch & ROPT_UTF8)
3178 case SVt_PVBM: typestr = SvROK(sv) ? "REF" : "SCALAR"; break;
3179 case SVt_PVLV: typestr = SvROK(sv) ? "REF"
3180 /* tied lvalues should appear to be
3181 * scalars for backwards compatitbility */
3182 : (LvTYPE(sv) == 't' || LvTYPE(sv) == 'T')
3183 ? "SCALAR" : "LVALUE"; break;
3184 case SVt_PVAV: typestr = "ARRAY"; break;
3185 case SVt_PVHV: typestr = "HASH"; break;
3186 case SVt_PVCV: typestr = "CODE"; break;
3187 case SVt_PVGV: typestr = "GLOB"; break;
3188 case SVt_PVFM: typestr = "FORMAT"; break;
3189 case SVt_PVIO: typestr = "IO"; break;
3190 default: typestr = "UNKNOWN"; break;
3194 const char *name = HvNAME_get(SvSTASH(sv));
3195 Perl_sv_setpvf(aTHX_ tsv, "%s=%s(0x%"UVxf")",
3196 name ? name : "__ANON__" , typestr, PTR2UV(sv));
3199 Perl_sv_setpvf(aTHX_ tsv, "%s(0x%"UVxf")", typestr, PTR2UV(sv));
3203 *lp = strlen(typestr);
3204 return (char *)typestr;
3206 if (SvREADONLY(sv) && !SvOK(sv)) {
3207 if (ckWARN(WARN_UNINITIALIZED))
3214 if (SvIOK(sv) || ((SvIOKp(sv) && !SvNOKp(sv)))) {
3215 /* I'm assuming that if both IV and NV are equally valid then
3216 converting the IV is going to be more efficient */
3217 const U32 isIOK = SvIOK(sv);
3218 const U32 isUIOK = SvIsUV(sv);
3219 char buf[TYPE_CHARS(UV)];
3222 if (SvTYPE(sv) < SVt_PVIV)
3223 sv_upgrade(sv, SVt_PVIV);
3225 ptr = uiv_2buf(buf, 0, SvUVX(sv), 1, &ebuf);
3227 ptr = uiv_2buf(buf, SvIVX(sv), 0, 0, &ebuf);
3228 /* inlined from sv_setpvn */
3229 SvGROW_mutable(sv, (STRLEN)(ebuf - ptr + 1));
3230 Move(ptr,SvPVX_mutable(sv),ebuf - ptr,char);
3231 SvCUR_set(sv, ebuf - ptr);
3241 else if (SvNOKp(sv)) {
3242 if (SvTYPE(sv) < SVt_PVNV)
3243 sv_upgrade(sv, SVt_PVNV);
3244 /* The +20 is pure guesswork. Configure test needed. --jhi */
3245 s = SvGROW_mutable(sv, NV_DIG + 20);
3246 olderrno = errno; /* some Xenix systems wipe out errno here */
3248 if (SvNVX(sv) == 0.0)
3249 (void)strcpy(s,"0");
3253 Gconvert(SvNVX(sv), NV_DIG, 0, s);
3256 #ifdef FIXNEGATIVEZERO
3257 if (*s == '-' && s[1] == '0' && !s[2])
3267 if (ckWARN(WARN_UNINITIALIZED)
3268 && !PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP))
3272 if (SvTYPE(sv) < SVt_PV)
3273 /* Typically the caller expects that sv_any is not NULL now. */
3274 sv_upgrade(sv, SVt_PV);
3278 STRLEN len = s - SvPVX_const(sv);
3284 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
3285 PTR2UV(sv),SvPVX_const(sv)));
3286 if (flags & SV_CONST_RETURN)
3287 return (char *)SvPVX_const(sv);
3288 if (flags & SV_MUTABLE_RETURN)
3289 return SvPVX_mutable(sv);
3293 if (SvROK(sv)) { /* XXX Skip this when sv_pvn_force calls */
3294 /* Sneaky stuff here */
3298 tsv = newSVpv(tmpbuf, 0);
3311 t = SvPVX_const(tsv);
3316 len = strlen(tmpbuf);
3318 #ifdef FIXNEGATIVEZERO
3319 if (len == 2 && t[0] == '-' && t[1] == '0') {
3324 SvUPGRADE(sv, SVt_PV);
3327 s = SvGROW_mutable(sv, len + 1);
3330 return strcpy(s, t);
3335 =for apidoc sv_copypv
3337 Copies a stringified representation of the source SV into the
3338 destination SV. Automatically performs any necessary mg_get and
3339 coercion of numeric values into strings. Guaranteed to preserve
3340 UTF-8 flag even from overloaded objects. Similar in nature to
3341 sv_2pv[_flags] but operates directly on an SV instead of just the
3342 string. Mostly uses sv_2pv_flags to do its work, except when that
3343 would lose the UTF-8'ness of the PV.
3349 Perl_sv_copypv(pTHX_ SV *dsv, register SV *ssv)
3352 const char * const s = SvPV_const(ssv,len);
3353 sv_setpvn(dsv,s,len);
3361 =for apidoc sv_2pvbyte_nolen
3363 Return a pointer to the byte-encoded representation of the SV.
3364 May cause the SV to be downgraded from UTF-8 as a side-effect.
3366 Usually accessed via the C<SvPVbyte_nolen> macro.
3372 Perl_sv_2pvbyte_nolen(pTHX_ register SV *sv)
3374 return sv_2pvbyte(sv, 0);
3378 =for apidoc sv_2pvbyte
3380 Return a pointer to the byte-encoded representation of the SV, and set *lp
3381 to its length. May cause the SV to be downgraded from UTF-8 as a
3384 Usually accessed via the C<SvPVbyte> macro.
3390 Perl_sv_2pvbyte(pTHX_ register SV *sv, STRLEN *lp)
3392 sv_utf8_downgrade(sv,0);
3393 return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
3397 =for apidoc sv_2pvutf8_nolen
3399 Return a pointer to the UTF-8-encoded representation of the SV.
3400 May cause the SV to be upgraded to UTF-8 as a side-effect.
3402 Usually accessed via the C<SvPVutf8_nolen> macro.
3408 Perl_sv_2pvutf8_nolen(pTHX_ register SV *sv)
3410 return sv_2pvutf8(sv, 0);
3414 =for apidoc sv_2pvutf8
3416 Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
3417 to its length. May cause the SV to be upgraded to UTF-8 as a side-effect.
3419 Usually accessed via the C<SvPVutf8> macro.
3425 Perl_sv_2pvutf8(pTHX_ register SV *sv, STRLEN *lp)
3427 sv_utf8_upgrade(sv);
3428 return SvPV(sv,*lp);
3432 =for apidoc sv_2bool
3434 This function is only called on magical items, and is only used by
3435 sv_true() or its macro equivalent.
3441 Perl_sv_2bool(pTHX_ register SV *sv)
3450 if (SvAMAGIC(sv) && (tmpsv=AMG_CALLun(sv,bool_)) &&
3451 (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
3452 return (bool)SvTRUE(tmpsv);
3453 return SvRV(sv) != 0;
3456 register XPV* const Xpvtmp = (XPV*)SvANY(sv);
3458 (*sv->sv_u.svu_pv > '0' ||
3459 Xpvtmp->xpv_cur > 1 ||
3460 (Xpvtmp->xpv_cur && *sv->sv_u.svu_pv != '0')))
3467 return SvIVX(sv) != 0;
3470 return SvNVX(sv) != 0.0;
3477 /* sv_utf8_upgrade() is now a macro using sv_utf8_upgrade_flags();
3478 * this function provided for binary compatibility only
3483 Perl_sv_utf8_upgrade(pTHX_ register SV *sv)
3485 return sv_utf8_upgrade_flags(sv, SV_GMAGIC);
3489 =for apidoc sv_utf8_upgrade
3491 Converts the PV of an SV to its UTF-8-encoded form.
3492 Forces the SV to string form if it is not already.
3493 Always sets the SvUTF8 flag to avoid future validity checks even
3494 if all the bytes have hibit clear.
3496 This is not as a general purpose byte encoding to Unicode interface:
3497 use the Encode extension for that.
3499 =for apidoc sv_utf8_upgrade_flags
3501 Converts the PV of an SV to its UTF-8-encoded form.
3502 Forces the SV to string form if it is not already.
3503 Always sets the SvUTF8 flag to avoid future validity checks even
3504 if all the bytes have hibit clear. If C<flags> has C<SV_GMAGIC> bit set,
3505 will C<mg_get> on C<sv> if appropriate, else not. C<sv_utf8_upgrade> and
3506 C<sv_utf8_upgrade_nomg> are implemented in terms of this function.
3508 This is not as a general purpose byte encoding to Unicode interface:
3509 use the Encode extension for that.
3515 Perl_sv_utf8_upgrade_flags(pTHX_ register SV *sv, I32 flags)
3517 if (sv == &PL_sv_undef)
3521 if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
3522 (void) sv_2pv_flags(sv,&len, flags);
3526 (void) SvPV_force(sv,len);
3535 sv_force_normal_flags(sv, 0);
3538 if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING))
3539 sv_recode_to_utf8(sv, PL_encoding);
3540 else { /* Assume Latin-1/EBCDIC */
3541 /* This function could be much more efficient if we
3542 * had a FLAG in SVs to signal if there are any hibit
3543 * chars in the PV. Given that there isn't such a flag
3544 * make the loop as fast as possible. */
3545 const U8 *s = (U8 *) SvPVX_const(sv);
3546 const U8 *e = (U8 *) SvEND(sv);
3552 if ((hibit = !NATIVE_IS_INVARIANT(ch)))
3556 STRLEN len = SvCUR(sv) + 1; /* Plus the \0 */
3557 U8 * const recoded = bytes_to_utf8((U8*)s, &len);
3559 SvPV_free(sv); /* No longer using what was there before. */
3561 SvPV_set(sv, (char*)recoded);
3562 SvCUR_set(sv, len - 1);
3563 SvLEN_set(sv, len); /* No longer know the real size. */
3565 /* Mark as UTF-8 even if no hibit - saves scanning loop */
3572 =for apidoc sv_utf8_downgrade
3574 Attempts to convert the PV of an SV from characters to bytes.
3575 If the PV contains a character beyond byte, this conversion will fail;
3576 in this case, either returns false or, if C<fail_ok> is not
3579 This is not as a general purpose Unicode to byte encoding interface:
3580 use the Encode extension for that.
3586 Perl_sv_utf8_downgrade(pTHX_ register SV* sv, bool fail_ok)
3588 if (SvPOKp(sv) && SvUTF8(sv)) {
3594 sv_force_normal_flags(sv, 0);
3596 s = (U8 *) SvPV(sv, len);
3597 if (!utf8_to_bytes(s, &len)) {
3602 Perl_croak(aTHX_ "Wide character in %s",
3605 Perl_croak(aTHX_ "Wide character");
3616 =for apidoc sv_utf8_encode
3618 Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3619 flag off so that it looks like octets again.
3625 Perl_sv_utf8_encode(pTHX_ register SV *sv)
3627 (void) sv_utf8_upgrade(sv);
3629 sv_force_normal_flags(sv, 0);
3631 if (SvREADONLY(sv)) {
3632 Perl_croak(aTHX_ PL_no_modify);
3638 =for apidoc sv_utf8_decode
3640 If the PV of the SV is an octet sequence in UTF-8
3641 and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3642 so that it looks like a character. If the PV contains only single-byte
3643 characters, the C<SvUTF8> flag stays being off.
3644 Scans PV for validity and returns false if the PV is invalid UTF-8.
3650 Perl_sv_utf8_decode(pTHX_ register SV *sv)
3656 /* The octets may have got themselves encoded - get them back as
3659 if (!sv_utf8_downgrade(sv, TRUE))
3662 /* it is actually just a matter of turning the utf8 flag on, but
3663 * we want to make sure everything inside is valid utf8 first.
3665 c = (const U8 *) SvPVX_const(sv);
3666 if (!is_utf8_string(c, SvCUR(sv)+1))
3668 e = (const U8 *) SvEND(sv);
3671 if (!UTF8_IS_INVARIANT(ch)) {
3680 /* sv_setsv() is now a macro using Perl_sv_setsv_flags();
3681 * this function provided for binary compatibility only
3685 Perl_sv_setsv(pTHX_ SV *dstr, register SV *sstr)
3687 sv_setsv_flags(dstr, sstr, SV_GMAGIC);
3691 =for apidoc sv_setsv
3693 Copies the contents of the source SV C<ssv> into the destination SV
3694 C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3695 function if the source SV needs to be reused. Does not handle 'set' magic.
3696 Loosely speaking, it performs a copy-by-value, obliterating any previous
3697 content of the destination.
3699 You probably want to use one of the assortment of wrappers, such as
3700 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3701 C<SvSetMagicSV_nosteal>.
3703 =for apidoc sv_setsv_flags
3705 Copies the contents of the source SV C<ssv> into the destination SV
3706 C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3707 function if the source SV needs to be reused. Does not handle 'set' magic.
3708 Loosely speaking, it performs a copy-by-value, obliterating any previous
3709 content of the destination.
3710 If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
3711 C<ssv> if appropriate, else not. If the C<flags> parameter has the
3712 C<NOSTEAL> bit set then the buffers of temps will not be stolen. <sv_setsv>
3713 and C<sv_setsv_nomg> are implemented in terms of this function.
3715 You probably want to use one of the assortment of wrappers, such as
3716 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3717 C<SvSetMagicSV_nosteal>.
3719 This is the primary function for copying scalars, and most other
3720 copy-ish functions and macros use this underneath.
3726 Perl_sv_setsv_flags(pTHX_ SV *dstr, register SV *sstr, I32 flags)
3728 register U32 sflags;
3734 SV_CHECK_THINKFIRST_COW_DROP(dstr);
3736 sstr = &PL_sv_undef;
3737 stype = SvTYPE(sstr);
3738 dtype = SvTYPE(dstr);
3743 /* need to nuke the magic */
3745 SvRMAGICAL_off(dstr);
3748 /* There's a lot of redundancy below but we're going for speed here */
3753 if (dtype != SVt_PVGV) {
3754 (void)SvOK_off(dstr);
3762 sv_upgrade(dstr, SVt_IV);
3765 sv_upgrade(dstr, SVt_PVNV);
3769 sv_upgrade(dstr, SVt_PVIV);
3772 (void)SvIOK_only(dstr);
3773 SvIV_set(dstr, SvIVX(sstr));
3776 if (SvTAINTED(sstr))
3787 sv_upgrade(dstr, SVt_NV);
3792 sv_upgrade(dstr, SVt_PVNV);
3795 SvNV_set(dstr, SvNVX(sstr));
3796 (void)SvNOK_only(dstr);
3797 if (SvTAINTED(sstr))
3805 sv_upgrade(dstr, SVt_RV);
3806 else if (dtype == SVt_PVGV &&
3807 SvROK(sstr) && SvTYPE(SvRV(sstr)) == SVt_PVGV) {
3810 if (GvIMPORTED(dstr) != GVf_IMPORTED
3811 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3813 GvIMPORTED_on(dstr);
3822 #ifdef PERL_OLD_COPY_ON_WRITE
3823 if ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS) {
3824 if (dtype < SVt_PVIV)
3825 sv_upgrade(dstr, SVt_PVIV);
3832 sv_upgrade(dstr, SVt_PV);
3835 if (dtype < SVt_PVIV)
3836 sv_upgrade(dstr, SVt_PVIV);
3839 if (dtype < SVt_PVNV)
3840 sv_upgrade(dstr, SVt_PVNV);
3847 const char * const type = sv_reftype(sstr,0);
3849 Perl_croak(aTHX_ "Bizarre copy of %s in %s", type, OP_NAME(PL_op));
3851 Perl_croak(aTHX_ "Bizarre copy of %s", type);
3856 if (dtype <= SVt_PVGV) {
3858 if (dtype != SVt_PVGV) {
3859 const char * const name = GvNAME(sstr);
3860 const STRLEN len = GvNAMELEN(sstr);
3861 /* don't upgrade SVt_PVLV: it can hold a glob */
3862 if (dtype != SVt_PVLV)
3863 sv_upgrade(dstr, SVt_PVGV);
3864 sv_magic(dstr, dstr, PERL_MAGIC_glob, Nullch, 0);
3865 GvSTASH(dstr) = (HV*)SvREFCNT_inc(GvSTASH(sstr));
3866 GvNAME(dstr) = savepvn(name, len);
3867 GvNAMELEN(dstr) = len;
3868 SvFAKE_on(dstr); /* can coerce to non-glob */
3870 /* ahem, death to those who redefine active sort subs */
3871 else if (PL_curstackinfo->si_type == PERLSI_SORT
3872 && GvCV(dstr) && PL_sortcop == CvSTART(GvCV(dstr)))
3873 Perl_croak(aTHX_ "Can't redefine active sort subroutine %s",
3876 #ifdef GV_UNIQUE_CHECK
3877 if (GvUNIQUE((GV*)dstr)) {
3878 Perl_croak(aTHX_ PL_no_modify);
3882 (void)SvOK_off(dstr);
3883 GvINTRO_off(dstr); /* one-shot flag */
3885 GvGP(dstr) = gp_ref(GvGP(sstr));
3886 if (SvTAINTED(sstr))
3888 if (GvIMPORTED(dstr) != GVf_IMPORTED
3889 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3891 GvIMPORTED_on(dstr);
3899 if (SvGMAGICAL(sstr) && (flags & SV_GMAGIC)) {
3901 if ((int)SvTYPE(sstr) != stype) {
3902 stype = SvTYPE(sstr);
3903 if (stype == SVt_PVGV && dtype <= SVt_PVGV)
3907 if (stype == SVt_PVLV)
3908 SvUPGRADE(dstr, SVt_PVNV);
3910 SvUPGRADE(dstr, (U32)stype);
3913 sflags = SvFLAGS(sstr);
3915 if (sflags & SVf_ROK) {
3916 if (dtype >= SVt_PV) {
3917 if (dtype == SVt_PVGV) {
3918 SV *sref = SvREFCNT_inc(SvRV(sstr));
3920 const int intro = GvINTRO(dstr);
3922 #ifdef GV_UNIQUE_CHECK
3923 if (GvUNIQUE((GV*)dstr)) {
3924 Perl_croak(aTHX_ PL_no_modify);
3929 GvINTRO_off(dstr); /* one-shot flag */
3930 GvLINE(dstr) = CopLINE(PL_curcop);
3931 GvEGV(dstr) = (GV*)dstr;
3934 switch (SvTYPE(sref)) {
3937 SAVEGENERICSV(GvAV(dstr));
3939 dref = (SV*)GvAV(dstr);
3940 GvAV(dstr) = (AV*)sref;
3941 if (!GvIMPORTED_AV(dstr)
3942 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3944 GvIMPORTED_AV_on(dstr);
3949 SAVEGENERICSV(GvHV(dstr));
3951 dref = (SV*)GvHV(dstr);
3952 GvHV(dstr) = (HV*)sref;
3953 if (!GvIMPORTED_HV(dstr)
3954 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3956 GvIMPORTED_HV_on(dstr);
3961 if (GvCVGEN(dstr) && GvCV(dstr) != (CV*)sref) {
3962 SvREFCNT_dec(GvCV(dstr));
3963 GvCV(dstr) = Nullcv;
3964 GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3965 PL_sub_generation++;
3967 SAVEGENERICSV(GvCV(dstr));
3970 dref = (SV*)GvCV(dstr);
3971 if (GvCV(dstr) != (CV*)sref) {
3972 CV* cv = GvCV(dstr);
3974 if (!GvCVGEN((GV*)dstr) &&
3975 (CvROOT(cv) || CvXSUB(cv)))
3977 /* ahem, death to those who redefine
3978 * active sort subs */
3979 if (PL_curstackinfo->si_type == PERLSI_SORT &&
3980 PL_sortcop == CvSTART(cv))
3982 "Can't redefine active sort subroutine %s",
3983 GvENAME((GV*)dstr));
3984 /* Redefining a sub - warning is mandatory if
3985 it was a const and its value changed. */
3986 if (ckWARN(WARN_REDEFINE)
3988 && (!CvCONST((CV*)sref)
3989 || sv_cmp(cv_const_sv(cv),
3990 cv_const_sv((CV*)sref)))))
3992 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
3994 ? "Constant subroutine %s::%s redefined"
3995 : "Subroutine %s::%s redefined",
3996 HvNAME_get(GvSTASH((GV*)dstr)),
3997 GvENAME((GV*)dstr));
4001 cv_ckproto(cv, (GV*)dstr,
4003 ? SvPVX_const(sref) : Nullch);
4005 GvCV(dstr) = (CV*)sref;
4006 GvCVGEN(dstr) = 0; /* Switch off cacheness. */
4007 GvASSUMECV_on(dstr);
4008 PL_sub_generation++;
4010 if (!GvIMPORTED_CV(dstr)
4011 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
4013 GvIMPORTED_CV_on(dstr);
4018 SAVEGENERICSV(GvIOp(dstr));
4020 dref = (SV*)GvIOp(dstr);
4021 GvIOp(dstr) = (IO*)sref;
4025 SAVEGENERICSV(GvFORM(dstr));
4027 dref = (SV*)GvFORM(dstr);
4028 GvFORM(dstr) = (CV*)sref;
4032 SAVEGENERICSV(GvSV(dstr));
4034 dref = (SV*)GvSV(dstr);
4036 if (!GvIMPORTED_SV(dstr)
4037 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
4039 GvIMPORTED_SV_on(dstr);
4045 if (SvTAINTED(sstr))
4049 if (SvPVX_const(dstr)) {
4055 (void)SvOK_off(dstr);
4056 SvRV_set(dstr, SvREFCNT_inc(SvRV(sstr)));
4058 if (sflags & SVp_NOK) {
4060 /* Only set the public OK flag if the source has public OK. */
4061 if (sflags & SVf_NOK)
4062 SvFLAGS(dstr) |= SVf_NOK;
4063 SvNV_set(dstr, SvNVX(sstr));
4065 if (sflags & SVp_IOK) {
4066 (void)SvIOKp_on(dstr);
4067 if (sflags & SVf_IOK)
4068 SvFLAGS(dstr) |= SVf_IOK;
4069 if (sflags & SVf_IVisUV)
4071 SvIV_set(dstr, SvIVX(sstr));
4073 if (SvAMAGIC(sstr)) {
4077 else if (sflags & SVp_POK) {
4081 * Check to see if we can just swipe the string. If so, it's a
4082 * possible small lose on short strings, but a big win on long ones.
4083 * It might even be a win on short strings if SvPVX_const(dstr)
4084 * has to be allocated and SvPVX_const(sstr) has to be freed.
4087 /* Whichever path we take through the next code, we want this true,
4088 and doing it now facilitates the COW check. */
4089 (void)SvPOK_only(dstr);
4092 /* We're not already COW */
4093 ((sflags & (SVf_FAKE | SVf_READONLY)) != (SVf_FAKE | SVf_READONLY)
4094 #ifndef PERL_OLD_COPY_ON_WRITE
4095 /* or we are, but dstr isn't a suitable target. */
4096 || (SvFLAGS(dstr) & CAN_COW_MASK) != CAN_COW_FLAGS
4101 (sflags & SVs_TEMP) && /* slated for free anyway? */
4102 !(sflags & SVf_OOK) && /* and not involved in OOK hack? */
4103 (!(flags & SV_NOSTEAL)) &&
4104 /* and we're allowed to steal temps */
4105 SvREFCNT(sstr) == 1 && /* and no other references to it? */
4106 SvLEN(sstr) && /* and really is a string */
4107 /* and won't be needed again, potentially */
4108 !(PL_op && PL_op->op_type == OP_AASSIGN))
4109 #ifdef PERL_OLD_COPY_ON_WRITE
4110 && !((sflags & CAN_COW_MASK) == CAN_COW_FLAGS
4111 && (SvFLAGS(dstr) & CAN_COW_MASK) == CAN_COW_FLAGS
4112 && SvTYPE(sstr) >= SVt_PVIV)
4115 /* Failed the swipe test, and it's not a shared hash key either.
4116 Have to copy the string. */
4117 STRLEN len = SvCUR(sstr);
4118 SvGROW(dstr, len + 1); /* inlined from sv_setpvn */
4119 Move(SvPVX_const(sstr),SvPVX(dstr),len,char);
4120 SvCUR_set(dstr, len);
4121 *SvEND(dstr) = '\0';
4123 /* If PERL_OLD_COPY_ON_WRITE is not defined, then isSwipe will always
4125 /* Either it's a shared hash key, or it's suitable for
4126 copy-on-write or we can swipe the string. */
4128 PerlIO_printf(Perl_debug_log, "Copy on write: sstr --> dstr\n");
4132 #ifdef PERL_OLD_COPY_ON_WRITE
4134 /* I believe I should acquire a global SV mutex if
4135 it's a COW sv (not a shared hash key) to stop
4136 it going un copy-on-write.
4137 If the source SV has gone un copy on write between up there
4138 and down here, then (assert() that) it is of the correct
4139 form to make it copy on write again */
4140 if ((sflags & (SVf_FAKE | SVf_READONLY))
4141 != (SVf_FAKE | SVf_READONLY)) {
4142 SvREADONLY_on(sstr);
4144 /* Make the source SV into a loop of 1.
4145 (about to become 2) */
4146 SV_COW_NEXT_SV_SET(sstr, sstr);
4150 /* Initial code is common. */
4151 if (SvPVX_const(dstr)) { /* we know that dtype >= SVt_PV */
4153 SvFLAGS(dstr) &= ~SVf_OOK;
4154 Safefree(SvPVX_const(dstr) - SvIVX(dstr));
4156 else if (SvLEN(dstr))
4157 Safefree(SvPVX_const(dstr));
4161 /* making another shared SV. */
4162 STRLEN cur = SvCUR(sstr);
4163 STRLEN len = SvLEN(sstr);
4164 #ifdef PERL_OLD_COPY_ON_WRITE
4166 assert (SvTYPE(dstr) >= SVt_PVIV);
4167 /* SvIsCOW_normal */
4168 /* splice us in between source and next-after-source. */
4169 SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4170 SV_COW_NEXT_SV_SET(sstr, dstr);
4171 SvPV_set(dstr, SvPVX_mutable(sstr));
4175 /* SvIsCOW_shared_hash */
4176 DEBUG_C(PerlIO_printf(Perl_debug_log,
4177 "Copy on write: Sharing hash\n"));
4179 assert (SvTYPE(dstr) >= SVt_PV);
4181 HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)))));
4183 SvLEN_set(dstr, len);
4184 SvCUR_set(dstr, cur);
4185 SvREADONLY_on(dstr);
4187 /* Relesase a global SV mutex. */
4190 { /* Passes the swipe test. */
4191 SvPV_set(dstr, SvPVX_mutable(sstr));
4192 SvLEN_set(dstr, SvLEN(sstr));
4193 SvCUR_set(dstr, SvCUR(sstr));
4196 (void)SvOK_off(sstr); /* NOTE: nukes most SvFLAGS on sstr */
4197 SvPV_set(sstr, Nullch);
4203 if (sflags & SVf_UTF8)
4205 if (sflags & SVp_NOK) {
4207 if (sflags & SVf_NOK)
4208 SvFLAGS(dstr) |= SVf_NOK;
4209 SvNV_set(dstr, SvNVX(sstr));
4211 if (sflags & SVp_IOK) {
4212 (void)SvIOKp_on(dstr);
4213 if (sflags & SVf_IOK)
4214 SvFLAGS(dstr) |= SVf_IOK;
4215 if (sflags & SVf_IVisUV)
4217 SvIV_set(dstr, SvIVX(sstr));
4220 MAGIC *smg = mg_find(sstr,PERL_MAGIC_vstring);
4221 sv_magic(dstr, NULL, PERL_MAGIC_vstring,
4222 smg->mg_ptr, smg->mg_len);
4223 SvRMAGICAL_on(dstr);
4226 else if (sflags & SVp_IOK) {
4227 if (sflags & SVf_IOK)
4228 (void)SvIOK_only(dstr);
4230 (void)SvOK_off(dstr);
4231 (void)SvIOKp_on(dstr);
4233 /* XXXX Do we want to set IsUV for IV(ROK)? Be extra safe... */
4234 if (sflags & SVf_IVisUV)
4236 SvIV_set(dstr, SvIVX(sstr));
4237 if (sflags & SVp_NOK) {
4238 if (sflags & SVf_NOK)
4239 (void)SvNOK_on(dstr);
4241 (void)SvNOKp_on(dstr);
4242 SvNV_set(dstr, SvNVX(sstr));
4245 else if (sflags & SVp_NOK) {
4246 if (sflags & SVf_NOK)
4247 (void)SvNOK_only(dstr);
4249 (void)SvOK_off(dstr);
4252 SvNV_set(dstr, SvNVX(sstr));
4255 if (dtype == SVt_PVGV) {
4256 if (ckWARN(WARN_MISC))
4257 Perl_warner(aTHX_ packWARN(WARN_MISC), "Undefined value assigned to typeglob");
4260 (void)SvOK_off(dstr);
4262 if (SvTAINTED(sstr))
4267 =for apidoc sv_setsv_mg
4269 Like C<sv_setsv>, but also handles 'set' magic.
4275 Perl_sv_setsv_mg(pTHX_ SV *dstr, register SV *sstr)
4277 sv_setsv(dstr,sstr);
4281 #ifdef PERL_OLD_COPY_ON_WRITE
4283 Perl_sv_setsv_cow(pTHX_ SV *dstr, SV *sstr)
4285 STRLEN cur = SvCUR(sstr);
4286 STRLEN len = SvLEN(sstr);
4287 register char *new_pv;
4290 PerlIO_printf(Perl_debug_log, "Fast copy on write: %p -> %p\n",
4298 if (SvTHINKFIRST(dstr))
4299 sv_force_normal_flags(dstr, SV_COW_DROP_PV);
4300 else if (SvPVX_const(dstr))
4301 Safefree(SvPVX_const(dstr));
4305 SvUPGRADE(dstr, SVt_PVIV);
4307 assert (SvPOK(sstr));
4308 assert (SvPOKp(sstr));
4309 assert (!SvIOK(sstr));
4310 assert (!SvIOKp(sstr));
4311 assert (!SvNOK(sstr));
4312 assert (!SvNOKp(sstr));
4314 if (SvIsCOW(sstr)) {
4316 if (SvLEN(sstr) == 0) {
4317 /* source is a COW shared hash key. */
4318 DEBUG_C(PerlIO_printf(Perl_debug_log,
4319 "Fast copy on write: Sharing hash\n"));
4320 new_pv = HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr))));
4323 SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
4325 assert ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS);
4326 SvUPGRADE(sstr, SVt_PVIV);
4327 SvREADONLY_on(sstr);
4329 DEBUG_C(PerlIO_printf(Perl_debug_log,
4330 "Fast copy on write: Converting sstr to COW\n"));
4331 SV_COW_NEXT_SV_SET(dstr, sstr);
4333 SV_COW_NEXT_SV_SET(sstr, dstr);
4334 new_pv = SvPVX_mutable(sstr);
4337 SvPV_set(dstr, new_pv);
4338 SvFLAGS(dstr) = (SVt_PVIV|SVf_POK|SVp_POK|SVf_FAKE|SVf_READONLY);
4341 SvLEN_set(dstr, len);
4342 SvCUR_set(dstr, cur);
4351 =for apidoc sv_setpvn
4353 Copies a string into an SV. The C<len> parameter indicates the number of
4354 bytes to be copied. If the C<ptr> argument is NULL the SV will become
4355 undefined. Does not handle 'set' magic. See C<sv_setpvn_mg>.
4361 Perl_sv_setpvn(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
4363 register char *dptr;
4365 SV_CHECK_THINKFIRST_COW_DROP(sv);
4371 /* len is STRLEN which is unsigned, need to copy to signed */
4374 Perl_croak(aTHX_ "panic: sv_setpvn called with negative strlen");
4376 SvUPGRADE(sv, SVt_PV);
4378 dptr = SvGROW(sv, len + 1);
4379 Move(ptr,dptr,len,char);
4382 (void)SvPOK_only_UTF8(sv); /* validate pointer */
4387 =for apidoc sv_setpvn_mg
4389 Like C<sv_setpvn>, but also handles 'set' magic.
4395 Perl_sv_setpvn_mg(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
4397 sv_setpvn(sv,ptr,len);
4402 =for apidoc sv_setpv
4404 Copies a string into an SV. The string must be null-terminated. Does not
4405 handle 'set' magic. See C<sv_setpv_mg>.
4411 Perl_sv_setpv(pTHX_ register SV *sv, register const char *ptr)
4413 register STRLEN len;
4415 SV_CHECK_THINKFIRST_COW_DROP(sv);
4421 SvUPGRADE(sv, SVt_PV);
4423 SvGROW(sv, len + 1);
4424 Move(ptr,SvPVX(sv),len+1,char);
4426 (void)SvPOK_only_UTF8(sv); /* validate pointer */
4431 =for apidoc sv_setpv_mg
4433 Like C<sv_setpv>, but also handles 'set' magic.
4439 Perl_sv_setpv_mg(pTHX_ register SV *sv, register const char *ptr)
4446 =for apidoc sv_usepvn
4448 Tells an SV to use C<ptr> to find its string value. Normally the string is
4449 stored inside the SV but sv_usepvn allows the SV to use an outside string.
4450 The C<ptr> should point to memory that was allocated by C<malloc>. The
4451 string length, C<len>, must be supplied. This function will realloc the
4452 memory pointed to by C<ptr>, so that pointer should not be freed or used by
4453 the programmer after giving it to sv_usepvn. Does not handle 'set' magic.
4454 See C<sv_usepvn_mg>.
4460 Perl_sv_usepvn(pTHX_ register SV *sv, register char *ptr, register STRLEN len)
4463 SV_CHECK_THINKFIRST_COW_DROP(sv);
4464 SvUPGRADE(sv, SVt_PV);
4469 if (SvPVX_const(sv))
4472 allocate = PERL_STRLEN_ROUNDUP(len + 1);
4473 ptr = saferealloc (ptr, allocate);
4476 SvLEN_set(sv, allocate);
4478 (void)SvPOK_only_UTF8(sv); /* validate pointer */
4483 =for apidoc sv_usepvn_mg
4485 Like C<sv_usepvn>, but also handles 'set' magic.
4491 Perl_sv_usepvn_mg(pTHX_ register SV *sv, register char *ptr, register STRLEN len)
4493 sv_usepvn(sv,ptr,len);
4497 #ifdef PERL_OLD_COPY_ON_WRITE
4498 /* Need to do this *after* making the SV normal, as we need the buffer
4499 pointer to remain valid until after we've copied it. If we let go too early,
4500 another thread could invalidate it by unsharing last of the same hash key
4501 (which it can do by means other than releasing copy-on-write Svs)
4502 or by changing the other copy-on-write SVs in the loop. */
4504 S_sv_release_COW(pTHX_ register SV *sv, const char *pvx, STRLEN len, SV *after)
4506 if (len) { /* this SV was SvIsCOW_normal(sv) */
4507 /* we need to find the SV pointing to us. */
4508 SV *current = SV_COW_NEXT_SV(after);
4510 if (current == sv) {
4511 /* The SV we point to points back to us (there were only two of us
4513 Hence other SV is no longer copy on write either. */
4515 SvREADONLY_off(after);
4517 /* We need to follow the pointers around the loop. */
4519 while ((next = SV_COW_NEXT_SV(current)) != sv) {
4522 /* don't loop forever if the structure is bust, and we have
4523 a pointer into a closed loop. */
4524 assert (current != after);
4525 assert (SvPVX_const(current) == pvx);
4527 /* Make the SV before us point to the SV after us. */
4528 SV_COW_NEXT_SV_SET(current, after);
4531 unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4536 Perl_sv_release_IVX(pTHX_ register SV *sv)
4539 sv_force_normal_flags(sv, 0);
4545 =for apidoc sv_force_normal_flags
4547 Undo various types of fakery on an SV: if the PV is a shared string, make
4548 a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
4549 an xpvmg; if we're a copy-on-write scalar, this is the on-write time when
4550 we do the copy, and is also used locally. If C<SV_COW_DROP_PV> is set
4551 then a copy-on-write scalar drops its PV buffer (if any) and becomes
4552 SvPOK_off rather than making a copy. (Used where this scalar is about to be
4553 set to some other value.) In addition, the C<flags> parameter gets passed to
4554 C<sv_unref_flags()> when unrefing. C<sv_force_normal> calls this function
4555 with flags set to 0.
4561 Perl_sv_force_normal_flags(pTHX_ register SV *sv, U32 flags)
4563 #ifdef PERL_OLD_COPY_ON_WRITE
4564 if (SvREADONLY(sv)) {
4565 /* At this point I believe I should acquire a global SV mutex. */
4567 const char *pvx = SvPVX_const(sv);
4568 const STRLEN len = SvLEN(sv);
4569 const STRLEN cur = SvCUR(sv);
4570 SV * const next = SV_COW_NEXT_SV(sv); /* next COW sv in the loop. */
4572 PerlIO_printf(Perl_debug_log,
4573 "Copy on write: Force normal %ld\n",
4579 /* This SV doesn't own the buffer, so need to New() a new one: */
4580 SvPV_set(sv, (char*)0);
4582 if (flags & SV_COW_DROP_PV) {
4583 /* OK, so we don't need to copy our buffer. */
4586 SvGROW(sv, cur + 1);
4587 Move(pvx,SvPVX(sv),cur,char);
4591 sv_release_COW(sv, pvx, len, next);
4596 else if (IN_PERL_RUNTIME)
4597 Perl_croak(aTHX_ PL_no_modify);
4598 /* At this point I believe that I can drop the global SV mutex. */
4601 if (SvREADONLY(sv)) {
4603 const char *pvx = SvPVX_const(sv);
4604 const STRLEN len = SvCUR(sv);
4607 SvPV_set(sv, Nullch);
4609 SvGROW(sv, len + 1);
4610 Move(pvx,SvPVX_const(sv),len,char);
4612 unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4614 else if (IN_PERL_RUNTIME)
4615 Perl_croak(aTHX_ PL_no_modify);
4619 sv_unref_flags(sv, flags);
4620 else if (SvFAKE(sv) && SvTYPE(sv) == SVt_PVGV)