3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 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 /* if adding more checks watch out for the following tests:
34 * t/op/index.t t/op/length.t t/op/pat.t t/op/substr.t
35 * lib/utf8.t lib/Unicode/Collate/t/index.t
38 # define ASSERT_UTF8_CACHE(cache) \
39 STMT_START { if (cache) { assert((cache)[0] <= (cache)[1]); \
40 assert((cache)[2] <= (cache)[3]); \
41 assert((cache)[3] <= (cache)[1]);} \
44 # define ASSERT_UTF8_CACHE(cache) NOOP
47 #ifdef PERL_OLD_COPY_ON_WRITE
48 #define SV_COW_NEXT_SV(sv) INT2PTR(SV *,SvUVX(sv))
49 #define SV_COW_NEXT_SV_SET(current,next) SvUV_set(current, PTR2UV(next))
50 /* This is a pessimistic view. Scalar must be purely a read-write PV to copy-
54 /* ============================================================================
56 =head1 Allocation and deallocation of SVs.
58 An SV (or AV, HV, etc.) is allocated in two parts: the head (struct
59 sv, av, hv...) contains type and reference count information, and for
60 many types, a pointer to the body (struct xrv, xpv, xpviv...), which
61 contains fields specific to each type. Some types store all they need
62 in the head, so don't have a body.
64 In all but the most memory-paranoid configuations (ex: PURIFY), heads
65 and bodies are allocated out of arenas, which by default are
66 approximately 4K chunks of memory parcelled up into N heads or bodies.
67 Sv-bodies are allocated by their sv-type, guaranteeing size
68 consistency needed to allocate safely from arrays.
70 For SV-heads, the first slot in each arena is reserved, and holds a
71 link to the next arena, some flags, and a note of the number of slots.
72 Snaked through each arena chain is a linked list of free items; when
73 this becomes empty, an extra arena is allocated and divided up into N
74 items which are threaded into the free list.
76 SV-bodies are similar, but they use arena-sets by default, which
77 separate the link and info from the arena itself, and reclaim the 1st
78 slot in the arena. SV-bodies are further described later.
80 The following global variables are associated with arenas:
82 PL_sv_arenaroot pointer to list of SV arenas
83 PL_sv_root pointer to list of free SV structures
85 PL_body_arenas head of linked-list of body arenas
86 PL_body_roots[] array of pointers to list of free bodies of svtype
87 arrays are indexed by the svtype needed
89 A few special SV heads are not allocated from an arena, but are
90 instead directly created in the interpreter structure, eg PL_sv_undef.
91 The size of arenas can be changed from the default by setting
92 PERL_ARENA_SIZE appropriately at compile time.
94 The SV arena serves the secondary purpose of allowing still-live SVs
95 to be located and destroyed during final cleanup.
97 At the lowest level, the macros new_SV() and del_SV() grab and free
98 an SV head. (If debugging with -DD, del_SV() calls the function S_del_sv()
99 to return the SV to the free list with error checking.) new_SV() calls
100 more_sv() / sv_add_arena() to add an extra arena if the free list is empty.
101 SVs in the free list have their SvTYPE field set to all ones.
103 At the time of very final cleanup, sv_free_arenas() is called from
104 perl_destruct() to physically free all the arenas allocated since the
105 start of the interpreter.
107 The function visit() scans the SV arenas list, and calls a specified
108 function for each SV it finds which is still live - ie which has an SvTYPE
109 other than all 1's, and a non-zero SvREFCNT. visit() is used by the
110 following functions (specified as [function that calls visit()] / [function
111 called by visit() for each SV]):
113 sv_report_used() / do_report_used()
114 dump all remaining SVs (debugging aid)
116 sv_clean_objs() / do_clean_objs(),do_clean_named_objs()
117 Attempt to free all objects pointed to by RVs,
118 and, unless DISABLE_DESTRUCTOR_KLUDGE is defined,
119 try to do the same for all objects indirectly
120 referenced by typeglobs too. Called once from
121 perl_destruct(), prior to calling sv_clean_all()
124 sv_clean_all() / do_clean_all()
125 SvREFCNT_dec(sv) each remaining SV, possibly
126 triggering an sv_free(). It also sets the
127 SVf_BREAK flag on the SV to indicate that the
128 refcnt has been artificially lowered, and thus
129 stopping sv_free() from giving spurious warnings
130 about SVs which unexpectedly have a refcnt
131 of zero. called repeatedly from perl_destruct()
132 until there are no SVs left.
134 =head2 Arena allocator API Summary
136 Private API to rest of sv.c
140 new_XIV(), del_XIV(),
141 new_XNV(), del_XNV(),
146 sv_report_used(), sv_clean_objs(), sv_clean_all(), sv_free_arenas()
150 ============================================================================ */
153 * "A time to plant, and a time to uproot what was planted..."
157 Perl_offer_nice_chunk(pTHX_ void *chunk, U32 chunk_size)
162 new_chunk = (void *)(chunk);
163 new_chunk_size = (chunk_size);
164 if (new_chunk_size > PL_nice_chunk_size) {
165 Safefree(PL_nice_chunk);
166 PL_nice_chunk = (char *) new_chunk;
167 PL_nice_chunk_size = new_chunk_size;
173 #ifdef DEBUG_LEAKING_SCALARS
174 # define FREE_SV_DEBUG_FILE(sv) Safefree((sv)->sv_debug_file)
176 # define FREE_SV_DEBUG_FILE(sv)
180 # define SvARENA_CHAIN(sv) ((sv)->sv_u.svu_rv)
181 /* Whilst I'd love to do this, it seems that things like to check on
183 # define POSION_SV_HEAD(sv) PoisonNew(sv, 1, struct STRUCT_SV)
185 # define POSION_SV_HEAD(sv) PoisonNew(&SvANY(sv), 1, void *), \
186 PoisonNew(&SvREFCNT(sv), 1, U32)
188 # define SvARENA_CHAIN(sv) SvANY(sv)
189 # define POSION_SV_HEAD(sv)
192 #define plant_SV(p) \
194 FREE_SV_DEBUG_FILE(p); \
196 SvARENA_CHAIN(p) = (void *)PL_sv_root; \
197 SvFLAGS(p) = SVTYPEMASK; \
202 #define uproot_SV(p) \
205 PL_sv_root = (SV*)SvARENA_CHAIN(p); \
210 /* make some more SVs by adding another arena */
219 sv_add_arena(PL_nice_chunk, PL_nice_chunk_size, 0);
220 PL_nice_chunk = NULL;
221 PL_nice_chunk_size = 0;
224 char *chunk; /* must use New here to match call to */
225 Newx(chunk,PERL_ARENA_SIZE,char); /* Safefree() in sv_free_arenas() */
226 sv_add_arena(chunk, PERL_ARENA_SIZE, 0);
232 /* new_SV(): return a new, empty SV head */
234 #ifdef DEBUG_LEAKING_SCALARS
235 /* provide a real function for a debugger to play with */
244 sv = S_more_sv(aTHX);
248 sv->sv_debug_optype = PL_op ? PL_op->op_type : 0;
249 sv->sv_debug_line = (U16) (PL_parser
250 ? PL_parser->copline == NOLINE
256 sv->sv_debug_inpad = 0;
257 sv->sv_debug_cloned = 0;
258 sv->sv_debug_file = PL_curcop ? savepv(CopFILE(PL_curcop)): NULL;
262 # define new_SV(p) (p)=S_new_SV(aTHX)
270 (p) = S_more_sv(aTHX); \
278 /* del_SV(): return an empty SV head to the free list */
291 S_del_sv(pTHX_ SV *p)
297 for (sva = PL_sv_arenaroot; sva; sva = (SV *) SvANY(sva)) {
298 const SV * const sv = sva + 1;
299 const SV * const svend = &sva[SvREFCNT(sva)];
300 if (p >= sv && p < svend) {
306 if (ckWARN_d(WARN_INTERNAL))
307 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
308 "Attempt to free non-arena SV: 0x%"UVxf
309 pTHX__FORMAT, PTR2UV(p) pTHX__VALUE);
316 #else /* ! DEBUGGING */
318 #define del_SV(p) plant_SV(p)
320 #endif /* DEBUGGING */
324 =head1 SV Manipulation Functions
326 =for apidoc sv_add_arena
328 Given a chunk of memory, link it to the head of the list of arenas,
329 and split it into a list of free SVs.
335 Perl_sv_add_arena(pTHX_ char *ptr, U32 size, U32 flags)
338 SV* const sva = (SV*)ptr;
342 /* The first SV in an arena isn't an SV. */
343 SvANY(sva) = (void *) PL_sv_arenaroot; /* ptr to next arena */
344 SvREFCNT(sva) = size / sizeof(SV); /* number of SV slots */
345 SvFLAGS(sva) = flags; /* FAKE if not to be freed */
347 PL_sv_arenaroot = sva;
348 PL_sv_root = sva + 1;
350 svend = &sva[SvREFCNT(sva) - 1];
353 SvARENA_CHAIN(sv) = (void *)(SV*)(sv + 1);
357 /* Must always set typemask because it's always checked in on cleanup
358 when the arenas are walked looking for objects. */
359 SvFLAGS(sv) = SVTYPEMASK;
362 SvARENA_CHAIN(sv) = 0;
366 SvFLAGS(sv) = SVTYPEMASK;
369 /* visit(): call the named function for each non-free SV in the arenas
370 * whose flags field matches the flags/mask args. */
373 S_visit(pTHX_ SVFUNC_t f, U32 flags, U32 mask)
379 for (sva = PL_sv_arenaroot; sva; sva = (SV*)SvANY(sva)) {
380 register const SV * const svend = &sva[SvREFCNT(sva)];
382 for (sv = sva + 1; sv < svend; ++sv) {
383 if (SvTYPE(sv) != SVTYPEMASK
384 && (sv->sv_flags & mask) == flags
397 /* called by sv_report_used() for each live SV */
400 do_report_used(pTHX_ SV *sv)
402 if (SvTYPE(sv) != SVTYPEMASK) {
403 PerlIO_printf(Perl_debug_log, "****\n");
410 =for apidoc sv_report_used
412 Dump the contents of all SVs not yet freed. (Debugging aid).
418 Perl_sv_report_used(pTHX)
421 visit(do_report_used, 0, 0);
427 /* called by sv_clean_objs() for each live SV */
430 do_clean_objs(pTHX_ SV *ref)
435 SV * const target = SvRV(ref);
436 if (SvOBJECT(target)) {
437 DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning object ref:\n "), sv_dump(ref)));
438 if (SvWEAKREF(ref)) {
439 sv_del_backref(target, ref);
445 SvREFCNT_dec(target);
450 /* XXX Might want to check arrays, etc. */
453 /* called by sv_clean_objs() for each live SV */
455 #ifndef DISABLE_DESTRUCTOR_KLUDGE
457 do_clean_named_objs(pTHX_ SV *sv)
460 assert(SvTYPE(sv) == SVt_PVGV);
461 assert(isGV_with_GP(sv));
464 #ifdef PERL_DONT_CREATE_GVSV
467 SvOBJECT(GvSV(sv))) ||
468 (GvAV(sv) && SvOBJECT(GvAV(sv))) ||
469 (GvHV(sv) && SvOBJECT(GvHV(sv))) ||
470 /* In certain rare cases GvIOp(sv) can be NULL, which would make SvOBJECT(GvIO(sv)) dereference NULL. */
471 (GvIO(sv) ? (SvFLAGS(GvIOp(sv)) & SVs_OBJECT) : 0) ||
472 (GvCV(sv) && SvOBJECT(GvCV(sv))) )
474 DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning named glob object:\n "), sv_dump(sv)));
475 SvFLAGS(sv) |= SVf_BREAK;
483 =for apidoc sv_clean_objs
485 Attempt to destroy all objects not yet freed
491 Perl_sv_clean_objs(pTHX)
494 PL_in_clean_objs = TRUE;
495 visit(do_clean_objs, SVf_ROK, SVf_ROK);
496 #ifndef DISABLE_DESTRUCTOR_KLUDGE
497 /* some barnacles may yet remain, clinging to typeglobs */
498 visit(do_clean_named_objs, SVt_PVGV|SVpgv_GP, SVTYPEMASK|SVp_POK|SVpgv_GP);
500 PL_in_clean_objs = FALSE;
503 /* called by sv_clean_all() for each live SV */
506 do_clean_all(pTHX_ SV *sv)
509 DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning loops: SV at 0x%"UVxf"\n", PTR2UV(sv)) ));
510 SvFLAGS(sv) |= SVf_BREAK;
515 =for apidoc sv_clean_all
517 Decrement the refcnt of each remaining SV, possibly triggering a
518 cleanup. This function may have to be called multiple times to free
519 SVs which are in complex self-referential hierarchies.
525 Perl_sv_clean_all(pTHX)
529 PL_in_clean_all = TRUE;
530 cleaned = visit(do_clean_all, 0,0);
531 PL_in_clean_all = FALSE;
536 ARENASETS: a meta-arena implementation which separates arena-info
537 into struct arena_set, which contains an array of struct
538 arena_descs, each holding info for a single arena. By separating
539 the meta-info from the arena, we recover the 1st slot, formerly
540 borrowed for list management. The arena_set is about the size of an
541 arena, avoiding the needless malloc overhead of a naive linked-list.
543 The cost is 1 arena-set malloc per ~320 arena-mallocs, + the unused
544 memory in the last arena-set (1/2 on average). In trade, we get
545 back the 1st slot in each arena (ie 1.7% of a CV-arena, less for
546 smaller types). The recovery of the wasted space allows use of
547 small arenas for large, rare body types, by changing array* fields
548 in body_details_by_type[] below.
551 char *arena; /* the raw storage, allocated aligned */
552 size_t size; /* its size ~4k typ */
553 U32 misc; /* type, and in future other things. */
558 /* Get the maximum number of elements in set[] such that struct arena_set
559 will fit within PERL_ARENA_SIZE, which is probably just under 4K, and
560 therefore likely to be 1 aligned memory page. */
562 #define ARENAS_PER_SET ((PERL_ARENA_SIZE - sizeof(struct arena_set*) \
563 - 2 * sizeof(int)) / sizeof (struct arena_desc))
566 struct arena_set* next;
567 unsigned int set_size; /* ie ARENAS_PER_SET */
568 unsigned int curr; /* index of next available arena-desc */
569 struct arena_desc set[ARENAS_PER_SET];
573 =for apidoc sv_free_arenas
575 Deallocate the memory used by all arenas. Note that all the individual SV
576 heads and bodies within the arenas must already have been freed.
581 Perl_sv_free_arenas(pTHX)
588 /* Free arenas here, but be careful about fake ones. (We assume
589 contiguity of the fake ones with the corresponding real ones.) */
591 for (sva = PL_sv_arenaroot; sva; sva = svanext) {
592 svanext = (SV*) SvANY(sva);
593 while (svanext && SvFAKE(svanext))
594 svanext = (SV*) SvANY(svanext);
601 struct arena_set *aroot = (struct arena_set*) PL_body_arenas;
604 struct arena_set *current = aroot;
607 assert(aroot->set[i].arena);
608 Safefree(aroot->set[i].arena);
616 i = PERL_ARENA_ROOTS_SIZE;
618 PL_body_roots[i] = 0;
620 Safefree(PL_nice_chunk);
621 PL_nice_chunk = NULL;
622 PL_nice_chunk_size = 0;
628 Here are mid-level routines that manage the allocation of bodies out
629 of the various arenas. There are 5 kinds of arenas:
631 1. SV-head arenas, which are discussed and handled above
632 2. regular body arenas
633 3. arenas for reduced-size bodies
635 5. pte arenas (thread related)
637 Arena types 2 & 3 are chained by body-type off an array of
638 arena-root pointers, which is indexed by svtype. Some of the
639 larger/less used body types are malloced singly, since a large
640 unused block of them is wasteful. Also, several svtypes dont have
641 bodies; the data fits into the sv-head itself. The arena-root
642 pointer thus has a few unused root-pointers (which may be hijacked
643 later for arena types 4,5)
645 3 differs from 2 as an optimization; some body types have several
646 unused fields in the front of the structure (which are kept in-place
647 for consistency). These bodies can be allocated in smaller chunks,
648 because the leading fields arent accessed. Pointers to such bodies
649 are decremented to point at the unused 'ghost' memory, knowing that
650 the pointers are used with offsets to the real memory.
652 HE, HEK arenas are managed separately, with separate code, but may
653 be merge-able later..
655 PTE arenas are not sv-bodies, but they share these mid-level
656 mechanics, so are considered here. The new mid-level mechanics rely
657 on the sv_type of the body being allocated, so we just reserve one
658 of the unused body-slots for PTEs, then use it in those (2) PTE
659 contexts below (line ~10k)
662 /* get_arena(size): this creates custom-sized arenas
663 TBD: export properly for hv.c: S_more_he().
666 Perl_get_arena(pTHX_ size_t arena_size, U32 misc)
669 struct arena_desc* adesc;
670 struct arena_set *aroot = (struct arena_set*) PL_body_arenas;
673 /* shouldnt need this
674 if (!arena_size) arena_size = PERL_ARENA_SIZE;
677 /* may need new arena-set to hold new arena */
678 if (!aroot || aroot->curr >= aroot->set_size) {
679 struct arena_set *newroot;
680 Newxz(newroot, 1, struct arena_set);
681 newroot->set_size = ARENAS_PER_SET;
682 newroot->next = aroot;
684 PL_body_arenas = (void *) newroot;
685 DEBUG_m(PerlIO_printf(Perl_debug_log, "new arenaset %p\n", (void*)aroot));
688 /* ok, now have arena-set with at least 1 empty/available arena-desc */
689 curr = aroot->curr++;
690 adesc = &(aroot->set[curr]);
691 assert(!adesc->arena);
693 Newx(adesc->arena, arena_size, char);
694 adesc->size = arena_size;
696 DEBUG_m(PerlIO_printf(Perl_debug_log, "arena %d added: %p size %"UVuf"\n",
697 curr, (void*)adesc->arena, (UV)arena_size));
703 /* return a thing to the free list */
705 #define del_body(thing, root) \
707 void ** const thing_copy = (void **)thing;\
708 *thing_copy = *root; \
709 *root = (void*)thing_copy; \
714 =head1 SV-Body Allocation
716 Allocation of SV-bodies is similar to SV-heads, differing as follows;
717 the allocation mechanism is used for many body types, so is somewhat
718 more complicated, it uses arena-sets, and has no need for still-live
721 At the outermost level, (new|del)_X*V macros return bodies of the
722 appropriate type. These macros call either (new|del)_body_type or
723 (new|del)_body_allocated macro pairs, depending on specifics of the
724 type. Most body types use the former pair, the latter pair is used to
725 allocate body types with "ghost fields".
727 "ghost fields" are fields that are unused in certain types, and
728 consequently dont need to actually exist. They are declared because
729 they're part of a "base type", which allows use of functions as
730 methods. The simplest examples are AVs and HVs, 2 aggregate types
731 which don't use the fields which support SCALAR semantics.
733 For these types, the arenas are carved up into *_allocated size
734 chunks, we thus avoid wasted memory for those unaccessed members.
735 When bodies are allocated, we adjust the pointer back in memory by the
736 size of the bit not allocated, so it's as if we allocated the full
737 structure. (But things will all go boom if you write to the part that
738 is "not there", because you'll be overwriting the last members of the
739 preceding structure in memory.)
741 We calculate the correction using the STRUCT_OFFSET macro. For
742 example, if xpv_allocated is the same structure as XPV then the two
743 OFFSETs sum to zero, and the pointer is unchanged. If the allocated
744 structure is smaller (no initial NV actually allocated) then the net
745 effect is to subtract the size of the NV from the pointer, to return a
746 new pointer as if an initial NV were actually allocated.
748 This is the same trick as was used for NV and IV bodies. Ironically it
749 doesn't need to be used for NV bodies any more, because NV is now at
750 the start of the structure. IV bodies don't need it either, because
751 they are no longer allocated.
753 In turn, the new_body_* allocators call S_new_body(), which invokes
754 new_body_inline macro, which takes a lock, and takes a body off the
755 linked list at PL_body_roots[sv_type], calling S_more_bodies() if
756 necessary to refresh an empty list. Then the lock is released, and
757 the body is returned.
759 S_more_bodies calls get_arena(), and carves it up into an array of N
760 bodies, which it strings into a linked list. It looks up arena-size
761 and body-size from the body_details table described below, thus
762 supporting the multiple body-types.
764 If PURIFY is defined, or PERL_ARENA_SIZE=0, arenas are not used, and
765 the (new|del)_X*V macros are mapped directly to malloc/free.
771 For each sv-type, struct body_details bodies_by_type[] carries
772 parameters which control these aspects of SV handling:
774 Arena_size determines whether arenas are used for this body type, and if
775 so, how big they are. PURIFY or PERL_ARENA_SIZE=0 set this field to
776 zero, forcing individual mallocs and frees.
778 Body_size determines how big a body is, and therefore how many fit into
779 each arena. Offset carries the body-pointer adjustment needed for
780 *_allocated body types, and is used in *_allocated macros.
782 But its main purpose is to parameterize info needed in
783 Perl_sv_upgrade(). The info here dramatically simplifies the function
784 vs the implementation in 5.8.7, making it table-driven. All fields
785 are used for this, except for arena_size.
787 For the sv-types that have no bodies, arenas are not used, so those
788 PL_body_roots[sv_type] are unused, and can be overloaded. In
789 something of a special case, SVt_NULL is borrowed for HE arenas;
790 PL_body_roots[HE_SVSLOT=SVt_NULL] is filled by S_more_he, but the
791 bodies_by_type[SVt_NULL] slot is not used, as the table is not
794 PTEs also use arenas, but are never seen in Perl_sv_upgrade. Nonetheless,
795 they get their own slot in bodies_by_type[PTE_SVSLOT =SVt_IV], so they can
796 just use the same allocation semantics. At first, PTEs were also
797 overloaded to a non-body sv-type, but this yielded hard-to-find malloc
798 bugs, so was simplified by claiming a new slot. This choice has no
799 consequence at this time.
803 struct body_details {
804 U8 body_size; /* Size to allocate */
805 U8 copy; /* Size of structure to copy (may be shorter) */
807 unsigned int type : 4; /* We have space for a sanity check. */
808 unsigned int cant_upgrade : 1; /* Cannot upgrade this type */
809 unsigned int zero_nv : 1; /* zero the NV when upgrading from this */
810 unsigned int arena : 1; /* Allocated from an arena */
811 size_t arena_size; /* Size of arena to allocate */
819 /* With -DPURFIY we allocate everything directly, and don't use arenas.
820 This seems a rather elegant way to simplify some of the code below. */
821 #define HASARENA FALSE
823 #define HASARENA TRUE
825 #define NOARENA FALSE
827 /* Size the arenas to exactly fit a given number of bodies. A count
828 of 0 fits the max number bodies into a PERL_ARENA_SIZE.block,
829 simplifying the default. If count > 0, the arena is sized to fit
830 only that many bodies, allowing arenas to be used for large, rare
831 bodies (XPVFM, XPVIO) without undue waste. The arena size is
832 limited by PERL_ARENA_SIZE, so we can safely oversize the
835 #define FIT_ARENA0(body_size) \
836 ((size_t)(PERL_ARENA_SIZE / body_size) * body_size)
837 #define FIT_ARENAn(count,body_size) \
838 ( count * body_size <= PERL_ARENA_SIZE) \
839 ? count * body_size \
840 : FIT_ARENA0 (body_size)
841 #define FIT_ARENA(count,body_size) \
843 ? FIT_ARENAn (count, body_size) \
844 : FIT_ARENA0 (body_size)
846 /* A macro to work out the offset needed to subtract from a pointer to (say)
853 to make its members accessible via a pointer to (say)
863 #define relative_STRUCT_OFFSET(longer, shorter, member) \
864 (STRUCT_OFFSET(shorter, member) - STRUCT_OFFSET(longer, member))
866 /* Calculate the length to copy. Specifically work out the length less any
867 final padding the compiler needed to add. See the comment in sv_upgrade
868 for why copying the padding proved to be a bug. */
870 #define copy_length(type, last_member) \
871 STRUCT_OFFSET(type, last_member) \
872 + sizeof (((type*)SvANY((SV*)0))->last_member)
874 static const struct body_details bodies_by_type[] = {
875 { sizeof(HE), 0, 0, SVt_NULL,
876 FALSE, NONV, NOARENA, FIT_ARENA(0, sizeof(HE)) },
878 /* The bind placeholder pretends to be an RV for now.
879 Also it's marked as "can't upgrade" to stop anyone using it before it's
881 { 0, 0, 0, SVt_BIND, TRUE, NONV, NOARENA, 0 },
883 /* IVs are in the head, so the allocation size is 0.
884 However, the slot is overloaded for PTEs. */
885 { sizeof(struct ptr_tbl_ent), /* This is used for PTEs. */
886 sizeof(IV), /* This is used to copy out the IV body. */
887 STRUCT_OFFSET(XPVIV, xiv_iv), SVt_IV, FALSE, NONV,
888 NOARENA /* IVS don't need an arena */,
889 /* But PTEs need to know the size of their arena */
890 FIT_ARENA(0, sizeof(struct ptr_tbl_ent))
893 /* 8 bytes on most ILP32 with IEEE doubles */
894 { sizeof(NV), sizeof(NV), 0, SVt_NV, FALSE, HADNV, HASARENA,
895 FIT_ARENA(0, sizeof(NV)) },
897 /* 8 bytes on most ILP32 with IEEE doubles */
898 { sizeof(xpv_allocated),
899 copy_length(XPV, xpv_len)
900 - relative_STRUCT_OFFSET(xpv_allocated, XPV, xpv_cur),
901 + relative_STRUCT_OFFSET(xpv_allocated, XPV, xpv_cur),
902 SVt_PV, FALSE, NONV, HASARENA, FIT_ARENA(0, sizeof(xpv_allocated)) },
905 { sizeof(xpviv_allocated),
906 copy_length(XPVIV, xiv_u)
907 - relative_STRUCT_OFFSET(xpviv_allocated, XPVIV, xpv_cur),
908 + relative_STRUCT_OFFSET(xpviv_allocated, XPVIV, xpv_cur),
909 SVt_PVIV, FALSE, NONV, HASARENA, FIT_ARENA(0, sizeof(xpviv_allocated)) },
912 { sizeof(XPVNV), copy_length(XPVNV, xiv_u), 0, SVt_PVNV, FALSE, HADNV,
913 HASARENA, FIT_ARENA(0, sizeof(XPVNV)) },
916 { sizeof(XPVMG), copy_length(XPVMG, xmg_stash), 0, SVt_PVMG, FALSE, HADNV,
917 HASARENA, FIT_ARENA(0, sizeof(XPVMG)) },
920 { sizeof(struct regexp_allocated), sizeof(struct regexp_allocated),
921 + relative_STRUCT_OFFSET(struct regexp_allocated, regexp, xpv_cur),
922 SVt_REGEXP, FALSE, NONV, HASARENA,
923 FIT_ARENA(0, sizeof(struct regexp_allocated))
927 { sizeof(XPVGV), sizeof(XPVGV), 0, SVt_PVGV, TRUE, HADNV,
928 HASARENA, FIT_ARENA(0, sizeof(XPVGV)) },
931 { sizeof(XPVLV), sizeof(XPVLV), 0, SVt_PVLV, TRUE, HADNV,
932 HASARENA, FIT_ARENA(0, sizeof(XPVLV)) },
934 { sizeof(xpvav_allocated),
935 copy_length(XPVAV, xmg_stash)
936 - relative_STRUCT_OFFSET(xpvav_allocated, XPVAV, xav_fill),
937 + relative_STRUCT_OFFSET(xpvav_allocated, XPVAV, xav_fill),
938 SVt_PVAV, TRUE, NONV, HASARENA, FIT_ARENA(0, sizeof(xpvav_allocated)) },
940 { sizeof(xpvhv_allocated),
941 copy_length(XPVHV, xmg_stash)
942 - relative_STRUCT_OFFSET(xpvhv_allocated, XPVHV, xhv_fill),
943 + relative_STRUCT_OFFSET(xpvhv_allocated, XPVHV, xhv_fill),
944 SVt_PVHV, TRUE, NONV, HASARENA, FIT_ARENA(0, sizeof(xpvhv_allocated)) },
947 { sizeof(xpvcv_allocated), sizeof(xpvcv_allocated),
948 + relative_STRUCT_OFFSET(xpvcv_allocated, XPVCV, xpv_cur),
949 SVt_PVCV, TRUE, NONV, HASARENA, FIT_ARENA(0, sizeof(xpvcv_allocated)) },
951 { sizeof(xpvfm_allocated), sizeof(xpvfm_allocated),
952 + relative_STRUCT_OFFSET(xpvfm_allocated, XPVFM, xpv_cur),
953 SVt_PVFM, TRUE, NONV, NOARENA, FIT_ARENA(20, sizeof(xpvfm_allocated)) },
955 /* XPVIO is 84 bytes, fits 48x */
956 { sizeof(XPVIO), sizeof(XPVIO), 0, SVt_PVIO, TRUE, HADNV,
957 HASARENA, FIT_ARENA(24, sizeof(XPVIO)) },
960 #define new_body_type(sv_type) \
961 (void *)((char *)S_new_body(aTHX_ sv_type))
963 #define del_body_type(p, sv_type) \
964 del_body(p, &PL_body_roots[sv_type])
967 #define new_body_allocated(sv_type) \
968 (void *)((char *)S_new_body(aTHX_ sv_type) \
969 - bodies_by_type[sv_type].offset)
971 #define del_body_allocated(p, sv_type) \
972 del_body(p + bodies_by_type[sv_type].offset, &PL_body_roots[sv_type])
975 #define my_safemalloc(s) (void*)safemalloc(s)
976 #define my_safecalloc(s) (void*)safecalloc(s, 1)
977 #define my_safefree(p) safefree((char*)p)
981 #define new_XNV() my_safemalloc(sizeof(XPVNV))
982 #define del_XNV(p) my_safefree(p)
984 #define new_XPVNV() my_safemalloc(sizeof(XPVNV))
985 #define del_XPVNV(p) my_safefree(p)
987 #define new_XPVAV() my_safemalloc(sizeof(XPVAV))
988 #define del_XPVAV(p) my_safefree(p)
990 #define new_XPVHV() my_safemalloc(sizeof(XPVHV))
991 #define del_XPVHV(p) my_safefree(p)
993 #define new_XPVMG() my_safemalloc(sizeof(XPVMG))
994 #define del_XPVMG(p) my_safefree(p)
996 #define new_XPVGV() my_safemalloc(sizeof(XPVGV))
997 #define del_XPVGV(p) my_safefree(p)
1001 #define new_XNV() new_body_type(SVt_NV)
1002 #define del_XNV(p) del_body_type(p, SVt_NV)
1004 #define new_XPVNV() new_body_type(SVt_PVNV)
1005 #define del_XPVNV(p) del_body_type(p, SVt_PVNV)
1007 #define new_XPVAV() new_body_allocated(SVt_PVAV)
1008 #define del_XPVAV(p) del_body_allocated(p, SVt_PVAV)
1010 #define new_XPVHV() new_body_allocated(SVt_PVHV)
1011 #define del_XPVHV(p) del_body_allocated(p, SVt_PVHV)
1013 #define new_XPVMG() new_body_type(SVt_PVMG)
1014 #define del_XPVMG(p) del_body_type(p, SVt_PVMG)
1016 #define new_XPVGV() new_body_type(SVt_PVGV)
1017 #define del_XPVGV(p) del_body_type(p, SVt_PVGV)
1021 /* no arena for you! */
1023 #define new_NOARENA(details) \
1024 my_safemalloc((details)->body_size + (details)->offset)
1025 #define new_NOARENAZ(details) \
1026 my_safecalloc((details)->body_size + (details)->offset)
1029 S_more_bodies (pTHX_ svtype sv_type)
1032 void ** const root = &PL_body_roots[sv_type];
1033 const struct body_details * const bdp = &bodies_by_type[sv_type];
1034 const size_t body_size = bdp->body_size;
1037 #if defined(DEBUGGING) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
1038 static bool done_sanity_check;
1040 /* PERL_GLOBAL_STRUCT_PRIVATE cannot coexist with global
1041 * variables like done_sanity_check. */
1042 if (!done_sanity_check) {
1043 unsigned int i = SVt_LAST;
1045 done_sanity_check = TRUE;
1048 assert (bodies_by_type[i].type == i);
1052 assert(bdp->arena_size);
1054 start = (char*) Perl_get_arena(aTHX_ bdp->arena_size, sv_type);
1056 end = start + bdp->arena_size - body_size;
1058 /* computed count doesnt reflect the 1st slot reservation */
1059 DEBUG_m(PerlIO_printf(Perl_debug_log,
1060 "arena %p end %p arena-size %d type %d size %d ct %d\n",
1061 (void*)start, (void*)end,
1062 (int)bdp->arena_size, sv_type, (int)body_size,
1063 (int)bdp->arena_size / (int)body_size));
1065 *root = (void *)start;
1067 while (start < end) {
1068 char * const next = start + body_size;
1069 *(void**) start = (void *)next;
1072 *(void **)start = 0;
1077 /* grab a new thing from the free list, allocating more if necessary.
1078 The inline version is used for speed in hot routines, and the
1079 function using it serves the rest (unless PURIFY).
1081 #define new_body_inline(xpv, sv_type) \
1083 void ** const r3wt = &PL_body_roots[sv_type]; \
1084 xpv = (PTR_TBL_ENT_t*) (*((void **)(r3wt)) \
1085 ? *((void **)(r3wt)) : more_bodies(sv_type)); \
1086 *(r3wt) = *(void**)(xpv); \
1092 S_new_body(pTHX_ svtype sv_type)
1096 new_body_inline(xpv, sv_type);
1102 static const struct body_details fake_rv =
1103 { 0, 0, 0, SVt_IV, FALSE, NONV, NOARENA, 0 };
1106 =for apidoc sv_upgrade
1108 Upgrade an SV to a more complex form. Generally adds a new body type to the
1109 SV, then copies across as much information as possible from the old body.
1110 You generally want to use the C<SvUPGRADE> macro wrapper. See also C<svtype>.
1116 Perl_sv_upgrade(pTHX_ register SV *sv, svtype new_type)
1121 const svtype old_type = SvTYPE(sv);
1122 const struct body_details *new_type_details;
1123 const struct body_details *old_type_details
1124 = bodies_by_type + old_type;
1125 SV *referant = NULL;
1127 if (new_type != SVt_PV && SvIsCOW(sv)) {
1128 sv_force_normal_flags(sv, 0);
1131 if (old_type == new_type)
1134 old_body = SvANY(sv);
1136 /* Copying structures onto other structures that have been neatly zeroed
1137 has a subtle gotcha. Consider XPVMG
1139 +------+------+------+------+------+-------+-------+
1140 | NV | CUR | LEN | IV | MAGIC | STASH |
1141 +------+------+------+------+------+-------+-------+
1142 0 4 8 12 16 20 24 28
1144 where NVs are aligned to 8 bytes, so that sizeof that structure is
1145 actually 32 bytes long, with 4 bytes of padding at the end:
1147 +------+------+------+------+------+-------+-------+------+
1148 | NV | CUR | LEN | IV | MAGIC | STASH | ??? |
1149 +------+------+------+------+------+-------+-------+------+
1150 0 4 8 12 16 20 24 28 32
1152 so what happens if you allocate memory for this structure:
1154 +------+------+------+------+------+-------+-------+------+------+...
1155 | NV | CUR | LEN | IV | MAGIC | STASH | GP | NAME |
1156 +------+------+------+------+------+-------+-------+------+------+...
1157 0 4 8 12 16 20 24 28 32 36
1159 zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
1160 expect, because you copy the area marked ??? onto GP. Now, ??? may have
1161 started out as zero once, but it's quite possible that it isn't. So now,
1162 rather than a nicely zeroed GP, you have it pointing somewhere random.
1165 (In fact, GP ends up pointing at a previous GP structure, because the
1166 principle cause of the padding in XPVMG getting garbage is a copy of
1167 sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob. Right now
1168 this happens to be moot because XPVGV has been re-ordered, with GP
1169 no longer after STASH)
1171 So we are careful and work out the size of used parts of all the
1179 referant = SvRV(sv);
1180 old_type_details = &fake_rv;
1181 if (new_type == SVt_NV)
1182 new_type = SVt_PVNV;
1184 if (new_type < SVt_PVIV) {
1185 new_type = (new_type == SVt_NV)
1186 ? SVt_PVNV : SVt_PVIV;
1191 if (new_type < SVt_PVNV) {
1192 new_type = SVt_PVNV;
1196 assert(new_type > SVt_PV);
1197 assert(SVt_IV < SVt_PV);
1198 assert(SVt_NV < SVt_PV);
1205 /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1206 there's no way that it can be safely upgraded, because perl.c
1207 expects to Safefree(SvANY(PL_mess_sv)) */
1208 assert(sv != PL_mess_sv);
1209 /* This flag bit is used to mean other things in other scalar types.
1210 Given that it only has meaning inside the pad, it shouldn't be set
1211 on anything that can get upgraded. */
1212 assert(!SvPAD_TYPED(sv));
1215 if (old_type_details->cant_upgrade)
1216 Perl_croak(aTHX_ "Can't upgrade %s (%" UVuf ") to %" UVuf,
1217 sv_reftype(sv, 0), (UV) old_type, (UV) new_type);
1220 if (old_type > new_type)
1221 Perl_croak(aTHX_ "sv_upgrade from type %d down to type %d",
1222 (int)old_type, (int)new_type);
1224 new_type_details = bodies_by_type + new_type;
1226 SvFLAGS(sv) &= ~SVTYPEMASK;
1227 SvFLAGS(sv) |= new_type;
1229 /* This can't happen, as SVt_NULL is <= all values of new_type, so one of
1230 the return statements above will have triggered. */
1231 assert (new_type != SVt_NULL);
1234 assert(old_type == SVt_NULL);
1235 SvANY(sv) = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
1239 assert(old_type == SVt_NULL);
1240 SvANY(sv) = new_XNV();
1245 assert(new_type_details->body_size);
1248 assert(new_type_details->arena);
1249 assert(new_type_details->arena_size);
1250 /* This points to the start of the allocated area. */
1251 new_body_inline(new_body, new_type);
1252 Zero(new_body, new_type_details->body_size, char);
1253 new_body = ((char *)new_body) - new_type_details->offset;
1255 /* We always allocated the full length item with PURIFY. To do this
1256 we fake things so that arena is false for all 16 types.. */
1257 new_body = new_NOARENAZ(new_type_details);
1259 SvANY(sv) = new_body;
1260 if (new_type == SVt_PVAV) {
1264 if (old_type_details->body_size) {
1267 /* It will have been zeroed when the new body was allocated.
1268 Lets not write to it, in case it confuses a write-back
1274 #ifndef NODEFAULT_SHAREKEYS
1275 HvSHAREKEYS_on(sv); /* key-sharing on by default */
1277 HvMAX(sv) = 7; /* (start with 8 buckets) */
1278 if (old_type_details->body_size) {
1281 /* It will have been zeroed when the new body was allocated.
1282 Lets not write to it, in case it confuses a write-back
1287 /* SVt_NULL isn't the only thing upgraded to AV or HV.
1288 The target created by newSVrv also is, and it can have magic.
1289 However, it never has SvPVX set.
1291 if (old_type == SVt_IV) {
1293 } else if (old_type >= SVt_PV) {
1294 assert(SvPVX_const(sv) == 0);
1297 if (old_type >= SVt_PVMG) {
1298 SvMAGIC_set(sv, ((XPVMG*)old_body)->xmg_u.xmg_magic);
1299 SvSTASH_set(sv, ((XPVMG*)old_body)->xmg_stash);
1301 sv->sv_u.svu_array = NULL; /* or svu_hash */
1307 /* XXX Is this still needed? Was it ever needed? Surely as there is
1308 no route from NV to PVIV, NOK can never be true */
1309 assert(!SvNOKp(sv));
1321 assert(new_type_details->body_size);
1322 /* We always allocated the full length item with PURIFY. To do this
1323 we fake things so that arena is false for all 16 types.. */
1324 if(new_type_details->arena) {
1325 /* This points to the start of the allocated area. */
1326 new_body_inline(new_body, new_type);
1327 Zero(new_body, new_type_details->body_size, char);
1328 new_body = ((char *)new_body) - new_type_details->offset;
1330 new_body = new_NOARENAZ(new_type_details);
1332 SvANY(sv) = new_body;
1334 if (old_type_details->copy) {
1335 /* There is now the potential for an upgrade from something without
1336 an offset (PVNV or PVMG) to something with one (PVCV, PVFM) */
1337 int offset = old_type_details->offset;
1338 int length = old_type_details->copy;
1340 if (new_type_details->offset > old_type_details->offset) {
1341 const int difference
1342 = new_type_details->offset - old_type_details->offset;
1343 offset += difference;
1344 length -= difference;
1346 assert (length >= 0);
1348 Copy((char *)old_body + offset, (char *)new_body + offset, length,
1352 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1353 /* If NV 0.0 is stores as all bits 0 then Zero() already creates a
1354 * correct 0.0 for us. Otherwise, if the old body didn't have an
1355 * NV slot, but the new one does, then we need to initialise the
1356 * freshly created NV slot with whatever the correct bit pattern is
1358 if (old_type_details->zero_nv && !new_type_details->zero_nv
1359 && !isGV_with_GP(sv))
1363 if (new_type == SVt_PVIO)
1364 IoPAGE_LEN(sv) = 60;
1365 if (old_type < SVt_PV) {
1366 /* referant will be NULL unless the old type was SVt_IV emulating
1368 sv->sv_u.svu_rv = referant;
1372 Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu",
1373 (unsigned long)new_type);
1376 if (old_type_details->arena) {
1377 /* If there was an old body, then we need to free it.
1378 Note that there is an assumption that all bodies of types that
1379 can be upgraded came from arenas. Only the more complex non-
1380 upgradable types are allowed to be directly malloc()ed. */
1382 my_safefree(old_body);
1384 del_body((void*)((char*)old_body + old_type_details->offset),
1385 &PL_body_roots[old_type]);
1391 =for apidoc sv_backoff
1393 Remove any string offset. You should normally use the C<SvOOK_off> macro
1400 Perl_sv_backoff(pTHX_ register SV *sv)
1403 const char * const s = SvPVX_const(sv);
1404 PERL_UNUSED_CONTEXT;
1406 assert(SvTYPE(sv) != SVt_PVHV);
1407 assert(SvTYPE(sv) != SVt_PVAV);
1409 SvOOK_offset(sv, delta);
1411 SvLEN_set(sv, SvLEN(sv) + delta);
1412 SvPV_set(sv, SvPVX(sv) - delta);
1413 Move(s, SvPVX(sv), SvCUR(sv)+1, char);
1414 SvFLAGS(sv) &= ~SVf_OOK;
1421 Expands the character buffer in the SV. If necessary, uses C<sv_unref> and
1422 upgrades the SV to C<SVt_PV>. Returns a pointer to the character buffer.
1423 Use the C<SvGROW> wrapper instead.
1429 Perl_sv_grow(pTHX_ register SV *sv, register STRLEN newlen)
1433 if (PL_madskills && newlen >= 0x100000) {
1434 PerlIO_printf(Perl_debug_log,
1435 "Allocation too large: %"UVxf"\n", (UV)newlen);
1437 #ifdef HAS_64K_LIMIT
1438 if (newlen >= 0x10000) {
1439 PerlIO_printf(Perl_debug_log,
1440 "Allocation too large: %"UVxf"\n", (UV)newlen);
1443 #endif /* HAS_64K_LIMIT */
1446 if (SvTYPE(sv) < SVt_PV) {
1447 sv_upgrade(sv, SVt_PV);
1448 s = SvPVX_mutable(sv);
1450 else if (SvOOK(sv)) { /* pv is offset? */
1452 s = SvPVX_mutable(sv);
1453 if (newlen > SvLEN(sv))
1454 newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1455 #ifdef HAS_64K_LIMIT
1456 if (newlen >= 0x10000)
1461 s = SvPVX_mutable(sv);
1463 if (newlen > SvLEN(sv)) { /* need more room? */
1464 newlen = PERL_STRLEN_ROUNDUP(newlen);
1465 if (SvLEN(sv) && s) {
1467 const STRLEN l = malloced_size((void*)SvPVX_const(sv));
1473 s = (char*)saferealloc(s, newlen);
1476 s = (char*)safemalloc(newlen);
1477 if (SvPVX_const(sv) && SvCUR(sv)) {
1478 Move(SvPVX_const(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1482 SvLEN_set(sv, newlen);
1488 =for apidoc sv_setiv
1490 Copies an integer into the given SV, upgrading first if necessary.
1491 Does not handle 'set' magic. See also C<sv_setiv_mg>.
1497 Perl_sv_setiv(pTHX_ register SV *sv, IV i)
1500 SV_CHECK_THINKFIRST_COW_DROP(sv);
1501 switch (SvTYPE(sv)) {
1504 sv_upgrade(sv, SVt_IV);
1507 sv_upgrade(sv, SVt_PVIV);
1516 Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1520 (void)SvIOK_only(sv); /* validate number */
1526 =for apidoc sv_setiv_mg
1528 Like C<sv_setiv>, but also handles 'set' magic.
1534 Perl_sv_setiv_mg(pTHX_ register SV *sv, IV i)
1541 =for apidoc sv_setuv
1543 Copies an unsigned integer into the given SV, upgrading first if necessary.
1544 Does not handle 'set' magic. See also C<sv_setuv_mg>.
1550 Perl_sv_setuv(pTHX_ register SV *sv, UV u)
1552 /* With these two if statements:
1553 u=1.49 s=0.52 cu=72.49 cs=10.64 scripts=270 tests=20865
1556 u=1.35 s=0.47 cu=73.45 cs=11.43 scripts=270 tests=20865
1558 If you wish to remove them, please benchmark to see what the effect is
1560 if (u <= (UV)IV_MAX) {
1561 sv_setiv(sv, (IV)u);
1570 =for apidoc sv_setuv_mg
1572 Like C<sv_setuv>, but also handles 'set' magic.
1578 Perl_sv_setuv_mg(pTHX_ register SV *sv, UV u)
1585 =for apidoc sv_setnv
1587 Copies a double into the given SV, upgrading first if necessary.
1588 Does not handle 'set' magic. See also C<sv_setnv_mg>.
1594 Perl_sv_setnv(pTHX_ register SV *sv, NV num)
1597 SV_CHECK_THINKFIRST_COW_DROP(sv);
1598 switch (SvTYPE(sv)) {
1601 sv_upgrade(sv, SVt_NV);
1605 sv_upgrade(sv, SVt_PVNV);
1614 Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
1619 (void)SvNOK_only(sv); /* validate number */
1624 =for apidoc sv_setnv_mg
1626 Like C<sv_setnv>, but also handles 'set' magic.
1632 Perl_sv_setnv_mg(pTHX_ register SV *sv, NV num)
1638 /* Print an "isn't numeric" warning, using a cleaned-up,
1639 * printable version of the offending string
1643 S_not_a_number(pTHX_ SV *sv)
1651 dsv = newSVpvs_flags("", SVs_TEMP);
1652 pv = sv_uni_display(dsv, sv, 10, 0);
1655 const char * const limit = tmpbuf + sizeof(tmpbuf) - 8;
1656 /* each *s can expand to 4 chars + "...\0",
1657 i.e. need room for 8 chars */
1659 const char *s = SvPVX_const(sv);
1660 const char * const end = s + SvCUR(sv);
1661 for ( ; s < end && d < limit; s++ ) {
1663 if (ch & 128 && !isPRINT_LC(ch)) {
1672 else if (ch == '\r') {
1676 else if (ch == '\f') {
1680 else if (ch == '\\') {
1684 else if (ch == '\0') {
1688 else if (isPRINT_LC(ch))
1705 Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1706 "Argument \"%s\" isn't numeric in %s", pv,
1709 Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1710 "Argument \"%s\" isn't numeric", pv);
1714 =for apidoc looks_like_number
1716 Test if the content of an SV looks like a number (or is a number).
1717 C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1718 non-numeric warning), even if your atof() doesn't grok them.
1724 Perl_looks_like_number(pTHX_ SV *sv)
1726 register const char *sbegin;
1730 sbegin = SvPVX_const(sv);
1733 else if (SvPOKp(sv))
1734 sbegin = SvPV_const(sv, len);
1736 return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
1737 return grok_number(sbegin, len, NULL);
1741 S_glob_2number(pTHX_ GV * const gv)
1743 const U32 wasfake = SvFLAGS(gv) & SVf_FAKE;
1744 SV *const buffer = sv_newmortal();
1746 /* FAKE globs can get coerced, so need to turn this off temporarily if it
1749 gv_efullname3(buffer, gv, "*");
1750 SvFLAGS(gv) |= wasfake;
1752 /* We know that all GVs stringify to something that is not-a-number,
1753 so no need to test that. */
1754 if (ckWARN(WARN_NUMERIC))
1755 not_a_number(buffer);
1756 /* We just want something true to return, so that S_sv_2iuv_common
1757 can tail call us and return true. */
1762 S_glob_2pv(pTHX_ GV * const gv, STRLEN * const len)
1764 const U32 wasfake = SvFLAGS(gv) & SVf_FAKE;
1765 SV *const buffer = sv_newmortal();
1767 /* FAKE globs can get coerced, so need to turn this off temporarily if it
1770 gv_efullname3(buffer, gv, "*");
1771 SvFLAGS(gv) |= wasfake;
1773 assert(SvPOK(buffer));
1775 *len = SvCUR(buffer);
1777 return SvPVX(buffer);
1780 /* Actually, ISO C leaves conversion of UV to IV undefined, but
1781 until proven guilty, assume that things are not that bad... */
1786 As 64 bit platforms often have an NV that doesn't preserve all bits of
1787 an IV (an assumption perl has been based on to date) it becomes necessary
1788 to remove the assumption that the NV always carries enough precision to
1789 recreate the IV whenever needed, and that the NV is the canonical form.
1790 Instead, IV/UV and NV need to be given equal rights. So as to not lose
1791 precision as a side effect of conversion (which would lead to insanity
1792 and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1793 1) to distinguish between IV/UV/NV slots that have cached a valid
1794 conversion where precision was lost and IV/UV/NV slots that have a
1795 valid conversion which has lost no precision
1796 2) to ensure that if a numeric conversion to one form is requested that
1797 would lose precision, the precise conversion (or differently
1798 imprecise conversion) is also performed and cached, to prevent
1799 requests for different numeric formats on the same SV causing
1800 lossy conversion chains. (lossless conversion chains are perfectly
1805 SvIOKp is true if the IV slot contains a valid value
1806 SvIOK is true only if the IV value is accurate (UV if SvIOK_UV true)
1807 SvNOKp is true if the NV slot contains a valid value
1808 SvNOK is true only if the NV value is accurate
1811 while converting from PV to NV, check to see if converting that NV to an
1812 IV(or UV) would lose accuracy over a direct conversion from PV to
1813 IV(or UV). If it would, cache both conversions, return NV, but mark
1814 SV as IOK NOKp (ie not NOK).
1816 While converting from PV to IV, check to see if converting that IV to an
1817 NV would lose accuracy over a direct conversion from PV to NV. If it
1818 would, cache both conversions, flag similarly.
1820 Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1821 correctly because if IV & NV were set NV *always* overruled.
1822 Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1823 changes - now IV and NV together means that the two are interchangeable:
1824 SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
1826 The benefit of this is that operations such as pp_add know that if
1827 SvIOK is true for both left and right operands, then integer addition
1828 can be used instead of floating point (for cases where the result won't
1829 overflow). Before, floating point was always used, which could lead to
1830 loss of precision compared with integer addition.
1832 * making IV and NV equal status should make maths accurate on 64 bit
1834 * may speed up maths somewhat if pp_add and friends start to use
1835 integers when possible instead of fp. (Hopefully the overhead in
1836 looking for SvIOK and checking for overflow will not outweigh the
1837 fp to integer speedup)
1838 * will slow down integer operations (callers of SvIV) on "inaccurate"
1839 values, as the change from SvIOK to SvIOKp will cause a call into
1840 sv_2iv each time rather than a macro access direct to the IV slot
1841 * should speed up number->string conversion on integers as IV is
1842 favoured when IV and NV are equally accurate
1844 ####################################################################
1845 You had better be using SvIOK_notUV if you want an IV for arithmetic:
1846 SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
1847 On the other hand, SvUOK is true iff UV.
1848 ####################################################################
1850 Your mileage will vary depending your CPU's relative fp to integer
1854 #ifndef NV_PRESERVES_UV
1855 # define IS_NUMBER_UNDERFLOW_IV 1
1856 # define IS_NUMBER_UNDERFLOW_UV 2
1857 # define IS_NUMBER_IV_AND_UV 2
1858 # define IS_NUMBER_OVERFLOW_IV 4
1859 # define IS_NUMBER_OVERFLOW_UV 5
1861 /* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
1863 /* For sv_2nv these three cases are "SvNOK and don't bother casting" */
1865 S_sv_2iuv_non_preserve(pTHX_ register SV *sv, I32 numtype)
1868 PERL_UNUSED_ARG(numtype); /* Used only under DEBUGGING? */
1869 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));
1870 if (SvNVX(sv) < (NV)IV_MIN) {
1871 (void)SvIOKp_on(sv);
1873 SvIV_set(sv, IV_MIN);
1874 return IS_NUMBER_UNDERFLOW_IV;
1876 if (SvNVX(sv) > (NV)UV_MAX) {
1877 (void)SvIOKp_on(sv);
1880 SvUV_set(sv, UV_MAX);
1881 return IS_NUMBER_OVERFLOW_UV;
1883 (void)SvIOKp_on(sv);
1885 /* Can't use strtol etc to convert this string. (See truth table in
1887 if (SvNVX(sv) <= (UV)IV_MAX) {
1888 SvIV_set(sv, I_V(SvNVX(sv)));
1889 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
1890 SvIOK_on(sv); /* Integer is precise. NOK, IOK */
1892 /* Integer is imprecise. NOK, IOKp */
1894 return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
1897 SvUV_set(sv, U_V(SvNVX(sv)));
1898 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
1899 if (SvUVX(sv) == UV_MAX) {
1900 /* As we know that NVs don't preserve UVs, UV_MAX cannot
1901 possibly be preserved by NV. Hence, it must be overflow.
1903 return IS_NUMBER_OVERFLOW_UV;
1905 SvIOK_on(sv); /* Integer is precise. NOK, UOK */
1907 /* Integer is imprecise. NOK, IOKp */
1909 return IS_NUMBER_OVERFLOW_IV;
1911 #endif /* !NV_PRESERVES_UV*/
1914 S_sv_2iuv_common(pTHX_ SV *sv) {
1917 /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
1918 * without also getting a cached IV/UV from it at the same time
1919 * (ie PV->NV conversion should detect loss of accuracy and cache
1920 * IV or UV at same time to avoid this. */
1921 /* IV-over-UV optimisation - choose to cache IV if possible */
1923 if (SvTYPE(sv) == SVt_NV)
1924 sv_upgrade(sv, SVt_PVNV);
1926 (void)SvIOKp_on(sv); /* Must do this first, to clear any SvOOK */
1927 /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
1928 certainly cast into the IV range at IV_MAX, whereas the correct
1929 answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
1931 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
1932 if (Perl_isnan(SvNVX(sv))) {
1938 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
1939 SvIV_set(sv, I_V(SvNVX(sv)));
1940 if (SvNVX(sv) == (NV) SvIVX(sv)
1941 #ifndef NV_PRESERVES_UV
1942 && (((UV)1 << NV_PRESERVES_UV_BITS) >
1943 (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
1944 /* Don't flag it as "accurately an integer" if the number
1945 came from a (by definition imprecise) NV operation, and
1946 we're outside the range of NV integer precision */
1950 SvIOK_on(sv); /* Can this go wrong with rounding? NWC */
1952 /* scalar has trailing garbage, eg "42a" */
1954 DEBUG_c(PerlIO_printf(Perl_debug_log,
1955 "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
1961 /* IV not precise. No need to convert from PV, as NV
1962 conversion would already have cached IV if it detected
1963 that PV->IV would be better than PV->NV->IV
1964 flags already correct - don't set public IOK. */
1965 DEBUG_c(PerlIO_printf(Perl_debug_log,
1966 "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
1971 /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
1972 but the cast (NV)IV_MIN rounds to a the value less (more
1973 negative) than IV_MIN which happens to be equal to SvNVX ??
1974 Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
1975 NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
1976 (NV)UVX == NVX are both true, but the values differ. :-(
1977 Hopefully for 2s complement IV_MIN is something like
1978 0x8000000000000000 which will be exact. NWC */
1981 SvUV_set(sv, U_V(SvNVX(sv)));
1983 (SvNVX(sv) == (NV) SvUVX(sv))
1984 #ifndef NV_PRESERVES_UV
1985 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
1986 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
1987 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
1988 /* Don't flag it as "accurately an integer" if the number
1989 came from a (by definition imprecise) NV operation, and
1990 we're outside the range of NV integer precision */
1996 DEBUG_c(PerlIO_printf(Perl_debug_log,
1997 "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
2003 else if (SvPOKp(sv) && SvLEN(sv)) {
2005 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2006 /* We want to avoid a possible problem when we cache an IV/ a UV which
2007 may be later translated to an NV, and the resulting NV is not
2008 the same as the direct translation of the initial string
2009 (eg 123.456 can shortcut to the IV 123 with atol(), but we must
2010 be careful to ensure that the value with the .456 is around if the
2011 NV value is requested in the future).
2013 This means that if we cache such an IV/a UV, we need to cache the
2014 NV as well. Moreover, we trade speed for space, and do not
2015 cache the NV if we are sure it's not needed.
2018 /* SVt_PVNV is one higher than SVt_PVIV, hence this order */
2019 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2020 == IS_NUMBER_IN_UV) {
2021 /* It's definitely an integer, only upgrade to PVIV */
2022 if (SvTYPE(sv) < SVt_PVIV)
2023 sv_upgrade(sv, SVt_PVIV);
2025 } else if (SvTYPE(sv) < SVt_PVNV)
2026 sv_upgrade(sv, SVt_PVNV);
2028 /* If NVs preserve UVs then we only use the UV value if we know that
2029 we aren't going to call atof() below. If NVs don't preserve UVs
2030 then the value returned may have more precision than atof() will
2031 return, even though value isn't perfectly accurate. */
2032 if ((numtype & (IS_NUMBER_IN_UV
2033 #ifdef NV_PRESERVES_UV
2036 )) == IS_NUMBER_IN_UV) {
2037 /* This won't turn off the public IOK flag if it was set above */
2038 (void)SvIOKp_on(sv);
2040 if (!(numtype & IS_NUMBER_NEG)) {
2042 if (value <= (UV)IV_MAX) {
2043 SvIV_set(sv, (IV)value);
2045 /* it didn't overflow, and it was positive. */
2046 SvUV_set(sv, value);
2050 /* 2s complement assumption */
2051 if (value <= (UV)IV_MIN) {
2052 SvIV_set(sv, -(IV)value);
2054 /* Too negative for an IV. This is a double upgrade, but
2055 I'm assuming it will be rare. */
2056 if (SvTYPE(sv) < SVt_PVNV)
2057 sv_upgrade(sv, SVt_PVNV);
2061 SvNV_set(sv, -(NV)value);
2062 SvIV_set(sv, IV_MIN);
2066 /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2067 will be in the previous block to set the IV slot, and the next
2068 block to set the NV slot. So no else here. */
2070 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2071 != IS_NUMBER_IN_UV) {
2072 /* It wasn't an (integer that doesn't overflow the UV). */
2073 SvNV_set(sv, Atof(SvPVX_const(sv)));
2075 if (! numtype && ckWARN(WARN_NUMERIC))
2078 #if defined(USE_LONG_DOUBLE)
2079 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" PERL_PRIgldbl ")\n",
2080 PTR2UV(sv), SvNVX(sv)));
2082 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"NVgf")\n",
2083 PTR2UV(sv), SvNVX(sv)));
2086 #ifdef NV_PRESERVES_UV
2087 (void)SvIOKp_on(sv);
2089 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2090 SvIV_set(sv, I_V(SvNVX(sv)));
2091 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2094 NOOP; /* Integer is imprecise. NOK, IOKp */
2096 /* UV will not work better than IV */
2098 if (SvNVX(sv) > (NV)UV_MAX) {
2100 /* Integer is inaccurate. NOK, IOKp, is UV */
2101 SvUV_set(sv, UV_MAX);
2103 SvUV_set(sv, U_V(SvNVX(sv)));
2104 /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2105 NV preservse UV so can do correct comparison. */
2106 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2109 NOOP; /* Integer is imprecise. NOK, IOKp, is UV */
2114 #else /* NV_PRESERVES_UV */
2115 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2116 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2117 /* The IV/UV slot will have been set from value returned by
2118 grok_number above. The NV slot has just been set using
2121 assert (SvIOKp(sv));
2123 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2124 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2125 /* Small enough to preserve all bits. */
2126 (void)SvIOKp_on(sv);
2128 SvIV_set(sv, I_V(SvNVX(sv)));
2129 if ((NV)(SvIVX(sv)) == SvNVX(sv))
2131 /* Assumption: first non-preserved integer is < IV_MAX,
2132 this NV is in the preserved range, therefore: */
2133 if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2135 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);
2139 0 0 already failed to read UV.
2140 0 1 already failed to read UV.
2141 1 0 you won't get here in this case. IV/UV
2142 slot set, public IOK, Atof() unneeded.
2143 1 1 already read UV.
2144 so there's no point in sv_2iuv_non_preserve() attempting
2145 to use atol, strtol, strtoul etc. */
2146 sv_2iuv_non_preserve (sv, numtype);
2149 #endif /* NV_PRESERVES_UV */
2150 /* It might be more code efficient to go through the entire logic above
2151 and conditionally set with SvIOKp_on() rather than SvIOK(), but it
2152 gets complex and potentially buggy, so more programmer efficient
2153 to do it this way, by turning off the public flags: */
2155 SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2159 if (isGV_with_GP(sv))
2160 return glob_2number((GV *)sv);
2162 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2163 if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2166 if (SvTYPE(sv) < SVt_IV)
2167 /* Typically the caller expects that sv_any is not NULL now. */
2168 sv_upgrade(sv, SVt_IV);
2169 /* Return 0 from the caller. */
2176 =for apidoc sv_2iv_flags
2178 Return the integer value of an SV, doing any necessary string
2179 conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2180 Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2186 Perl_sv_2iv_flags(pTHX_ register SV *sv, I32 flags)
2191 if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2192 /* FBMs use the same flag bit as SVf_IVisUV, so must let them
2193 cache IVs just in case. In practice it seems that they never
2194 actually anywhere accessible by user Perl code, let alone get used
2195 in anything other than a string context. */
2196 if (flags & SV_GMAGIC)
2201 return I_V(SvNVX(sv));
2203 if (SvPOKp(sv) && SvLEN(sv)) {
2206 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2208 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2209 == IS_NUMBER_IN_UV) {
2210 /* It's definitely an integer */
2211 if (numtype & IS_NUMBER_NEG) {
2212 if (value < (UV)IV_MIN)
2215 if (value < (UV)IV_MAX)
2220 if (ckWARN(WARN_NUMERIC))
2223 return I_V(Atof(SvPVX_const(sv)));
2228 assert(SvTYPE(sv) >= SVt_PVMG);
2229 /* This falls through to the report_uninit inside S_sv_2iuv_common. */
2230 } else if (SvTHINKFIRST(sv)) {
2234 SV * const tmpstr=AMG_CALLun(sv,numer);
2235 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2236 return SvIV(tmpstr);
2239 return PTR2IV(SvRV(sv));
2242 sv_force_normal_flags(sv, 0);
2244 if (SvREADONLY(sv) && !SvOK(sv)) {
2245 if (ckWARN(WARN_UNINITIALIZED))
2251 if (S_sv_2iuv_common(aTHX_ sv))
2254 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2255 PTR2UV(sv),SvIVX(sv)));
2256 return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
2260 =for apidoc sv_2uv_flags
2262 Return the unsigned integer value of an SV, doing any necessary string
2263 conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2264 Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
2270 Perl_sv_2uv_flags(pTHX_ register SV *sv, I32 flags)
2275 if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2276 /* FBMs use the same flag bit as SVf_IVisUV, so must let them
2277 cache IVs just in case. */
2278 if (flags & SV_GMAGIC)
2283 return U_V(SvNVX(sv));
2284 if (SvPOKp(sv) && SvLEN(sv)) {
2287 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2289 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2290 == IS_NUMBER_IN_UV) {
2291 /* It's definitely an integer */
2292 if (!(numtype & IS_NUMBER_NEG))
2296 if (ckWARN(WARN_NUMERIC))
2299 return U_V(Atof(SvPVX_const(sv)));
2304 assert(SvTYPE(sv) >= SVt_PVMG);
2305 /* This falls through to the report_uninit inside S_sv_2iuv_common. */
2306 } else if (SvTHINKFIRST(sv)) {
2310 SV *const tmpstr = AMG_CALLun(sv,numer);
2311 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2312 return SvUV(tmpstr);
2315 return PTR2UV(SvRV(sv));
2318 sv_force_normal_flags(sv, 0);
2320 if (SvREADONLY(sv) && !SvOK(sv)) {
2321 if (ckWARN(WARN_UNINITIALIZED))
2327 if (S_sv_2iuv_common(aTHX_ sv))
2331 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2332 PTR2UV(sv),SvUVX(sv)));
2333 return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
2339 Return the num value of an SV, doing any necessary string or integer
2340 conversion, magic etc. Normally used via the C<SvNV(sv)> and C<SvNVx(sv)>
2347 Perl_sv_2nv(pTHX_ register SV *sv)
2352 if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2353 /* FBMs use the same flag bit as SVf_IVisUV, so must let them
2354 cache IVs just in case. */
2358 if ((SvPOKp(sv) && SvLEN(sv)) && !SvIOKp(sv)) {
2359 if (!SvIOKp(sv) && ckWARN(WARN_NUMERIC) &&
2360 !grok_number(SvPVX_const(sv), SvCUR(sv), NULL))
2362 return Atof(SvPVX_const(sv));
2366 return (NV)SvUVX(sv);
2368 return (NV)SvIVX(sv);
2373 assert(SvTYPE(sv) >= SVt_PVMG);
2374 /* This falls through to the report_uninit near the end of the
2376 } else if (SvTHINKFIRST(sv)) {
2380 SV *const tmpstr = AMG_CALLun(sv,numer);
2381 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2382 return SvNV(tmpstr);
2385 return PTR2NV(SvRV(sv));
2388 sv_force_normal_flags(sv, 0);
2390 if (SvREADONLY(sv) && !SvOK(sv)) {
2391 if (ckWARN(WARN_UNINITIALIZED))
2396 if (SvTYPE(sv) < SVt_NV) {
2397 /* The logic to use SVt_PVNV if necessary is in sv_upgrade. */
2398 sv_upgrade(sv, SVt_NV);
2399 #ifdef USE_LONG_DOUBLE
2401 STORE_NUMERIC_LOCAL_SET_STANDARD();
2402 PerlIO_printf(Perl_debug_log,
2403 "0x%"UVxf" num(%" PERL_PRIgldbl ")\n",
2404 PTR2UV(sv), SvNVX(sv));
2405 RESTORE_NUMERIC_LOCAL();
2409 STORE_NUMERIC_LOCAL_SET_STANDARD();
2410 PerlIO_printf(Perl_debug_log, "0x%"UVxf" num(%"NVgf")\n",
2411 PTR2UV(sv), SvNVX(sv));
2412 RESTORE_NUMERIC_LOCAL();
2416 else if (SvTYPE(sv) < SVt_PVNV)
2417 sv_upgrade(sv, SVt_PVNV);
2422 SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
2423 #ifdef NV_PRESERVES_UV
2429 /* Only set the public NV OK flag if this NV preserves the IV */
2430 /* Check it's not 0xFFFFFFFFFFFFFFFF */
2432 SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
2433 : (SvIVX(sv) == I_V(SvNVX(sv))))
2439 else if (SvPOKp(sv) && SvLEN(sv)) {
2441 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2442 if (!SvIOKp(sv) && !numtype && ckWARN(WARN_NUMERIC))
2444 #ifdef NV_PRESERVES_UV
2445 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2446 == IS_NUMBER_IN_UV) {
2447 /* It's definitely an integer */
2448 SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
2450 SvNV_set(sv, Atof(SvPVX_const(sv)));
2456 SvNV_set(sv, Atof(SvPVX_const(sv)));
2457 /* Only set the public NV OK flag if this NV preserves the value in
2458 the PV at least as well as an IV/UV would.
2459 Not sure how to do this 100% reliably. */
2460 /* if that shift count is out of range then Configure's test is
2461 wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2463 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2464 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2465 SvNOK_on(sv); /* Definitely small enough to preserve all bits */
2466 } else if (!(numtype & IS_NUMBER_IN_UV)) {
2467 /* Can't use strtol etc to convert this string, so don't try.
2468 sv_2iv and sv_2uv will use the NV to convert, not the PV. */
2471 /* value has been set. It may not be precise. */
2472 if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2473 /* 2s complement assumption for (UV)IV_MIN */
2474 SvNOK_on(sv); /* Integer is too negative. */
2479 if (numtype & IS_NUMBER_NEG) {
2480 SvIV_set(sv, -(IV)value);
2481 } else if (value <= (UV)IV_MAX) {
2482 SvIV_set(sv, (IV)value);
2484 SvUV_set(sv, value);
2488 if (numtype & IS_NUMBER_NOT_INT) {
2489 /* I believe that even if the original PV had decimals,
2490 they are lost beyond the limit of the FP precision.
2491 However, neither is canonical, so both only get p
2492 flags. NWC, 2000/11/25 */
2493 /* Both already have p flags, so do nothing */
2495 const NV nv = SvNVX(sv);
2496 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2497 if (SvIVX(sv) == I_V(nv)) {
2500 /* It had no "." so it must be integer. */
2504 /* between IV_MAX and NV(UV_MAX).
2505 Could be slightly > UV_MAX */
2507 if (numtype & IS_NUMBER_NOT_INT) {
2508 /* UV and NV both imprecise. */
2510 const UV nv_as_uv = U_V(nv);
2512 if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2521 /* It might be more code efficient to go through the entire logic above
2522 and conditionally set with SvNOKp_on() rather than SvNOK(), but it
2523 gets complex and potentially buggy, so more programmer efficient
2524 to do it this way, by turning off the public flags: */
2526 SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
2527 #endif /* NV_PRESERVES_UV */
2530 if (isGV_with_GP(sv)) {
2531 glob_2number((GV *)sv);
2535 if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
2537 assert (SvTYPE(sv) >= SVt_NV);
2538 /* Typically the caller expects that sv_any is not NULL now. */
2539 /* XXX Ilya implies that this is a bug in callers that assume this
2540 and ideally should be fixed. */
2543 #if defined(USE_LONG_DOUBLE)
2545 STORE_NUMERIC_LOCAL_SET_STANDARD();
2546 PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" PERL_PRIgldbl ")\n",
2547 PTR2UV(sv), SvNVX(sv));
2548 RESTORE_NUMERIC_LOCAL();
2552 STORE_NUMERIC_LOCAL_SET_STANDARD();
2553 PerlIO_printf(Perl_debug_log, "0x%"UVxf" 1nv(%"NVgf")\n",
2554 PTR2UV(sv), SvNVX(sv));
2555 RESTORE_NUMERIC_LOCAL();
2564 Return an SV with the numeric value of the source SV, doing any necessary
2565 reference or overload conversion. You must use the C<SvNUM(sv)> macro to
2566 access this function.
2572 Perl_sv_2num(pTHX_ register SV *sv)
2577 SV * const tmpsv = AMG_CALLun(sv,numer);
2578 if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
2579 return sv_2num(tmpsv);
2581 return sv_2mortal(newSVuv(PTR2UV(SvRV(sv))));
2584 /* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2585 * UV as a string towards the end of buf, and return pointers to start and
2588 * We assume that buf is at least TYPE_CHARS(UV) long.
2592 S_uiv_2buf(char *buf, IV iv, UV uv, int is_uv, char **peob)
2594 char *ptr = buf + TYPE_CHARS(UV);
2595 char * const ebuf = ptr;
2608 *--ptr = '0' + (char)(uv % 10);
2617 =for apidoc sv_2pv_flags
2619 Returns a pointer to the string value of an SV, and sets *lp to its length.
2620 If flags includes SV_GMAGIC, does an mg_get() first. Coerces sv to a string
2622 Normally invoked via the C<SvPV_flags> macro. C<sv_2pv()> and C<sv_2pv_nomg>
2623 usually end up here too.
2629 Perl_sv_2pv_flags(pTHX_ register SV *sv, STRLEN *lp, I32 flags)
2639 if (SvGMAGICAL(sv)) {
2640 if (flags & SV_GMAGIC)
2645 if (flags & SV_MUTABLE_RETURN)
2646 return SvPVX_mutable(sv);
2647 if (flags & SV_CONST_RETURN)
2648 return (char *)SvPVX_const(sv);
2651 if (SvIOKp(sv) || SvNOKp(sv)) {
2652 char tbuf[64]; /* Must fit sprintf/Gconvert of longest IV/NV */
2657 ? my_snprintf(tbuf, sizeof(tbuf), "%"UVuf, (UV)SvUVX(sv))
2658 : my_snprintf(tbuf, sizeof(tbuf), "%"IVdf, (IV)SvIVX(sv));
2660 Gconvert(SvNVX(sv), NV_DIG, 0, tbuf);
2667 #ifdef FIXNEGATIVEZERO
2668 if (len == 2 && tbuf[0] == '-' && tbuf[1] == '0') {
2674 SvUPGRADE(sv, SVt_PV);
2677 s = SvGROW_mutable(sv, len + 1);
2680 return (char*)memcpy(s, tbuf, len + 1);
2686 assert(SvTYPE(sv) >= SVt_PVMG);
2687 /* This falls through to the report_uninit near the end of the
2689 } else if (SvTHINKFIRST(sv)) {
2693 SV *const tmpstr = AMG_CALLun(sv,string);
2694 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2696 /* char *pv = lp ? SvPV(tmpstr, *lp) : SvPV_nolen(tmpstr);
2700 if ((SvFLAGS(tmpstr) & (SVf_POK)) == SVf_POK) {
2701 if (flags & SV_CONST_RETURN) {
2702 pv = (char *) SvPVX_const(tmpstr);
2704 pv = (flags & SV_MUTABLE_RETURN)
2705 ? SvPVX_mutable(tmpstr) : SvPVX(tmpstr);
2708 *lp = SvCUR(tmpstr);
2710 pv = sv_2pv_flags(tmpstr, lp, flags);
2723 const SV *const referent = (SV*)SvRV(sv);
2727 retval = buffer = savepvn("NULLREF", len);
2728 } else if (SvTYPE(referent) == SVt_REGEXP) {
2729 const REGEXP * const re = (REGEXP *)referent;
2734 /* If the regex is UTF-8 we want the containing scalar to
2735 have an UTF-8 flag too */
2741 if ((seen_evals = RX_SEEN_EVALS(re)))
2742 PL_reginterp_cnt += seen_evals;
2745 *lp = RX_WRAPLEN(re);
2747 return RX_WRAPPED(re);
2749 const char *const typestr = sv_reftype(referent, 0);
2750 const STRLEN typelen = strlen(typestr);
2751 UV addr = PTR2UV(referent);
2752 const char *stashname = NULL;
2753 STRLEN stashnamelen = 0; /* hush, gcc */
2754 const char *buffer_end;
2756 if (SvOBJECT(referent)) {
2757 const HEK *const name = HvNAME_HEK(SvSTASH(referent));
2760 stashname = HEK_KEY(name);
2761 stashnamelen = HEK_LEN(name);
2763 if (HEK_UTF8(name)) {
2769 stashname = "__ANON__";
2772 len = stashnamelen + 1 /* = */ + typelen + 3 /* (0x */
2773 + 2 * sizeof(UV) + 2 /* )\0 */;
2775 len = typelen + 3 /* (0x */
2776 + 2 * sizeof(UV) + 2 /* )\0 */;
2779 Newx(buffer, len, char);
2780 buffer_end = retval = buffer + len;
2782 /* Working backwards */
2786 *--retval = PL_hexdigit[addr & 15];
2787 } while (addr >>= 4);
2793 memcpy(retval, typestr, typelen);
2797 retval -= stashnamelen;
2798 memcpy(retval, stashname, stashnamelen);
2800 /* retval may not neccesarily have reached the start of the
2802 assert (retval >= buffer);
2804 len = buffer_end - retval - 1; /* -1 for that \0 */
2812 if (SvREADONLY(sv) && !SvOK(sv)) {
2815 if (flags & SV_UNDEF_RETURNS_NULL)
2817 if (ckWARN(WARN_UNINITIALIZED))
2822 if (SvIOK(sv) || ((SvIOKp(sv) && !SvNOKp(sv)))) {
2823 /* I'm assuming that if both IV and NV are equally valid then
2824 converting the IV is going to be more efficient */
2825 const U32 isUIOK = SvIsUV(sv);
2826 char buf[TYPE_CHARS(UV)];
2830 if (SvTYPE(sv) < SVt_PVIV)
2831 sv_upgrade(sv, SVt_PVIV);
2832 ptr = uiv_2buf(buf, SvIVX(sv), SvUVX(sv), isUIOK, &ebuf);
2834 /* inlined from sv_setpvn */
2835 s = SvGROW_mutable(sv, len + 1);
2836 Move(ptr, s, len, char);
2840 else if (SvNOKp(sv)) {
2841 const int olderrno = errno;
2842 if (SvTYPE(sv) < SVt_PVNV)
2843 sv_upgrade(sv, SVt_PVNV);
2844 /* The +20 is pure guesswork. Configure test needed. --jhi */
2845 s = SvGROW_mutable(sv, NV_DIG + 20);
2846 /* some Xenix systems wipe out errno here */
2848 if (SvNVX(sv) == 0.0)
2849 my_strlcpy(s, "0", SvLEN(sv));
2853 Gconvert(SvNVX(sv), NV_DIG, 0, s);
2856 #ifdef FIXNEGATIVEZERO
2857 if (*s == '-' && s[1] == '0' && !s[2]) {
2869 if (isGV_with_GP(sv))
2870 return glob_2pv((GV *)sv, lp);
2874 if (flags & SV_UNDEF_RETURNS_NULL)
2876 if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
2878 if (SvTYPE(sv) < SVt_PV)
2879 /* Typically the caller expects that sv_any is not NULL now. */
2880 sv_upgrade(sv, SVt_PV);
2884 const STRLEN len = s - SvPVX_const(sv);
2890 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
2891 PTR2UV(sv),SvPVX_const(sv)));
2892 if (flags & SV_CONST_RETURN)
2893 return (char *)SvPVX_const(sv);
2894 if (flags & SV_MUTABLE_RETURN)
2895 return SvPVX_mutable(sv);
2900 =for apidoc sv_copypv
2902 Copies a stringified representation of the source SV into the
2903 destination SV. Automatically performs any necessary mg_get and
2904 coercion of numeric values into strings. Guaranteed to preserve
2905 UTF8 flag even from overloaded objects. Similar in nature to
2906 sv_2pv[_flags] but operates directly on an SV instead of just the
2907 string. Mostly uses sv_2pv_flags to do its work, except when that
2908 would lose the UTF-8'ness of the PV.
2914 Perl_sv_copypv(pTHX_ SV *dsv, register SV *ssv)
2917 const char * const s = SvPV_const(ssv,len);
2918 sv_setpvn(dsv,s,len);
2926 =for apidoc sv_2pvbyte
2928 Return a pointer to the byte-encoded representation of the SV, and set *lp
2929 to its length. May cause the SV to be downgraded from UTF-8 as a
2932 Usually accessed via the C<SvPVbyte> macro.
2938 Perl_sv_2pvbyte(pTHX_ register SV *sv, STRLEN *lp)
2940 sv_utf8_downgrade(sv,0);
2941 return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
2945 =for apidoc sv_2pvutf8
2947 Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
2948 to its length. May cause the SV to be upgraded to UTF-8 as a side-effect.
2950 Usually accessed via the C<SvPVutf8> macro.
2956 Perl_sv_2pvutf8(pTHX_ register SV *sv, STRLEN *lp)
2958 sv_utf8_upgrade(sv);
2959 return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
2964 =for apidoc sv_2bool
2966 This function is only called on magical items, and is only used by
2967 sv_true() or its macro equivalent.
2973 Perl_sv_2bool(pTHX_ register SV *sv)
2982 SV * const tmpsv = AMG_CALLun(sv,bool_);
2983 if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
2984 return (bool)SvTRUE(tmpsv);
2986 return SvRV(sv) != 0;
2989 register XPV* const Xpvtmp = (XPV*)SvANY(sv);
2991 (*sv->sv_u.svu_pv > '0' ||
2992 Xpvtmp->xpv_cur > 1 ||
2993 (Xpvtmp->xpv_cur && *sv->sv_u.svu_pv != '0')))
3000 return SvIVX(sv) != 0;
3003 return SvNVX(sv) != 0.0;
3005 if (isGV_with_GP(sv))
3015 =for apidoc sv_utf8_upgrade
3017 Converts the PV of an SV to its UTF-8-encoded form.
3018 Forces the SV to string form if it is not already.
3019 Always sets the SvUTF8 flag to avoid future validity checks even
3020 if all the bytes have hibit clear.
3022 This is not as a general purpose byte encoding to Unicode interface:
3023 use the Encode extension for that.
3025 =for apidoc sv_utf8_upgrade_flags
3027 Converts the PV of an SV to its UTF-8-encoded form.
3028 Forces the SV to string form if it is not already.
3029 Always sets the SvUTF8 flag to avoid future validity checks even
3030 if all the bytes have hibit clear. If C<flags> has C<SV_GMAGIC> bit set,
3031 will C<mg_get> on C<sv> if appropriate, else not. C<sv_utf8_upgrade> and
3032 C<sv_utf8_upgrade_nomg> are implemented in terms of this function.
3034 This is not as a general purpose byte encoding to Unicode interface:
3035 use the Encode extension for that.
3041 Perl_sv_utf8_upgrade_flags(pTHX_ register SV *sv, I32 flags)
3044 if (sv == &PL_sv_undef)
3048 if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
3049 (void) sv_2pv_flags(sv,&len, flags);
3053 (void) SvPV_force(sv,len);
3062 sv_force_normal_flags(sv, 0);
3065 if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING))
3066 sv_recode_to_utf8(sv, PL_encoding);
3067 else { /* Assume Latin-1/EBCDIC */
3068 /* This function could be much more efficient if we
3069 * had a FLAG in SVs to signal if there are any hibit
3070 * chars in the PV. Given that there isn't such a flag
3071 * make the loop as fast as possible. */
3072 const U8 * const s = (U8 *) SvPVX_const(sv);
3073 const U8 * const e = (U8 *) SvEND(sv);
3078 /* Check for hi bit */
3079 if (!NATIVE_IS_INVARIANT(ch)) {
3080 STRLEN len = SvCUR(sv) + 1; /* Plus the \0 */
3081 U8 * const recoded = bytes_to_utf8((U8*)s, &len);
3083 SvPV_free(sv); /* No longer using what was there before. */
3084 SvPV_set(sv, (char*)recoded);
3085 SvCUR_set(sv, len - 1);
3086 SvLEN_set(sv, len); /* No longer know the real size. */
3090 /* Mark as UTF-8 even if no hibit - saves scanning loop */
3097 =for apidoc sv_utf8_downgrade
3099 Attempts to convert the PV of an SV from characters to bytes.
3100 If the PV contains a character beyond byte, this conversion will fail;
3101 in this case, either returns false or, if C<fail_ok> is not
3104 This is not as a general purpose Unicode to byte encoding interface:
3105 use the Encode extension for that.
3111 Perl_sv_utf8_downgrade(pTHX_ register SV* sv, bool fail_ok)
3114 if (SvPOKp(sv) && SvUTF8(sv)) {
3120 sv_force_normal_flags(sv, 0);
3122 s = (U8 *) SvPV(sv, len);
3123 if (!utf8_to_bytes(s, &len)) {
3128 Perl_croak(aTHX_ "Wide character in %s",
3131 Perl_croak(aTHX_ "Wide character");
3142 =for apidoc sv_utf8_encode
3144 Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3145 flag off so that it looks like octets again.
3151 Perl_sv_utf8_encode(pTHX_ register SV *sv)
3154 sv_force_normal_flags(sv, 0);
3156 if (SvREADONLY(sv)) {
3157 Perl_croak(aTHX_ PL_no_modify);
3159 (void) sv_utf8_upgrade(sv);
3164 =for apidoc sv_utf8_decode
3166 If the PV of the SV is an octet sequence in UTF-8
3167 and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3168 so that it looks like a character. If the PV contains only single-byte
3169 characters, the C<SvUTF8> flag stays being off.
3170 Scans PV for validity and returns false if the PV is invalid UTF-8.
3176 Perl_sv_utf8_decode(pTHX_ register SV *sv)
3182 /* The octets may have got themselves encoded - get them back as
3185 if (!sv_utf8_downgrade(sv, TRUE))
3188 /* it is actually just a matter of turning the utf8 flag on, but
3189 * we want to make sure everything inside is valid utf8 first.
3191 c = (const U8 *) SvPVX_const(sv);
3192 if (!is_utf8_string(c, SvCUR(sv)+1))
3194 e = (const U8 *) SvEND(sv);
3197 if (!UTF8_IS_INVARIANT(ch)) {
3207 =for apidoc sv_setsv
3209 Copies the contents of the source SV C<ssv> into the destination SV
3210 C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3211 function if the source SV needs to be reused. Does not handle 'set' magic.
3212 Loosely speaking, it performs a copy-by-value, obliterating any previous
3213 content of the destination.
3215 You probably want to use one of the assortment of wrappers, such as
3216 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3217 C<SvSetMagicSV_nosteal>.
3219 =for apidoc sv_setsv_flags
3221 Copies the contents of the source SV C<ssv> into the destination SV
3222 C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3223 function if the source SV needs to be reused. Does not handle 'set' magic.
3224 Loosely speaking, it performs a copy-by-value, obliterating any previous
3225 content of the destination.
3226 If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
3227 C<ssv> if appropriate, else not. If the C<flags> parameter has the
3228 C<NOSTEAL> bit set then the buffers of temps will not be stolen. <sv_setsv>
3229 and C<sv_setsv_nomg> are implemented in terms of this function.
3231 You probably want to use one of the assortment of wrappers, such as
3232 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3233 C<SvSetMagicSV_nosteal>.
3235 This is the primary function for copying scalars, and most other
3236 copy-ish functions and macros use this underneath.
3242 S_glob_assign_glob(pTHX_ SV *dstr, SV *sstr, const int dtype)
3244 I32 mro_changes = 0; /* 1 = method, 2 = isa */
3246 if (dtype != SVt_PVGV) {
3247 const char * const name = GvNAME(sstr);
3248 const STRLEN len = GvNAMELEN(sstr);
3250 if (dtype >= SVt_PV) {
3256 SvUPGRADE(dstr, SVt_PVGV);
3257 (void)SvOK_off(dstr);
3258 /* FIXME - why are we doing this, then turning it off and on again
3260 isGV_with_GP_on(dstr);
3262 GvSTASH(dstr) = GvSTASH(sstr);
3264 Perl_sv_add_backref(aTHX_ (SV*)GvSTASH(dstr), dstr);
3265 gv_name_set((GV *)dstr, name, len, GV_ADD);
3266 SvFAKE_on(dstr); /* can coerce to non-glob */
3269 #ifdef GV_UNIQUE_CHECK
3270 if (GvUNIQUE((GV*)dstr)) {
3271 Perl_croak(aTHX_ PL_no_modify);
3275 if(GvGP((GV*)sstr)) {
3276 /* If source has method cache entry, clear it */
3278 SvREFCNT_dec(GvCV(sstr));
3282 /* If source has a real method, then a method is
3284 else if(GvCV((GV*)sstr)) {
3289 /* If dest already had a real method, that's a change as well */
3290 if(!mro_changes && GvGP((GV*)dstr) && GvCVu((GV*)dstr)) {
3294 if(strEQ(GvNAME((GV*)dstr),"ISA"))
3298 isGV_with_GP_off(dstr);
3299 (void)SvOK_off(dstr);
3300 isGV_with_GP_on(dstr);
3301 GvINTRO_off(dstr); /* one-shot flag */
3302 GvGP(dstr) = gp_ref(GvGP(sstr));
3303 if (SvTAINTED(sstr))
3305 if (GvIMPORTED(dstr) != GVf_IMPORTED
3306 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3308 GvIMPORTED_on(dstr);
3311 if(mro_changes == 2) mro_isa_changed_in(GvSTASH(dstr));
3312 else if(mro_changes) mro_method_changed_in(GvSTASH(dstr));
3317 S_glob_assign_ref(pTHX_ SV *dstr, SV *sstr) {
3318 SV * const sref = SvREFCNT_inc(SvRV(sstr));
3320 const int intro = GvINTRO(dstr);
3323 const U32 stype = SvTYPE(sref);
3326 #ifdef GV_UNIQUE_CHECK
3327 if (GvUNIQUE((GV*)dstr)) {
3328 Perl_croak(aTHX_ PL_no_modify);
3333 GvINTRO_off(dstr); /* one-shot flag */
3334 GvLINE(dstr) = CopLINE(PL_curcop);
3335 GvEGV(dstr) = (GV*)dstr;
3340 location = (SV **) &GvCV(dstr);
3341 import_flag = GVf_IMPORTED_CV;
3344 location = (SV **) &GvHV(dstr);
3345 import_flag = GVf_IMPORTED_HV;
3348 location = (SV **) &GvAV(dstr);
3349 import_flag = GVf_IMPORTED_AV;
3352 location = (SV **) &GvIOp(dstr);
3355 location = (SV **) &GvFORM(dstr);
3357 location = &GvSV(dstr);
3358 import_flag = GVf_IMPORTED_SV;
3361 if (stype == SVt_PVCV) {
3362 /*if (GvCVGEN(dstr) && (GvCV(dstr) != (CV*)sref || GvCVGEN(dstr))) {*/
3363 if (GvCVGEN(dstr)) {
3364 SvREFCNT_dec(GvCV(dstr));
3366 GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3369 SAVEGENERICSV(*location);
3373 if (stype == SVt_PVCV && (*location != sref || GvCVGEN(dstr))) {
3374 CV* const cv = (CV*)*location;
3376 if (!GvCVGEN((GV*)dstr) &&
3377 (CvROOT(cv) || CvXSUB(cv)))
3379 /* Redefining a sub - warning is mandatory if
3380 it was a const and its value changed. */
3381 if (CvCONST(cv) && CvCONST((CV*)sref)
3382 && cv_const_sv(cv) == cv_const_sv((CV*)sref)) {
3384 /* They are 2 constant subroutines generated from
3385 the same constant. This probably means that
3386 they are really the "same" proxy subroutine
3387 instantiated in 2 places. Most likely this is
3388 when a constant is exported twice. Don't warn.
3391 else if (ckWARN(WARN_REDEFINE)
3393 && (!CvCONST((CV*)sref)
3394 || sv_cmp(cv_const_sv(cv),
3395 cv_const_sv((CV*)sref))))) {
3396 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
3399 ? "Constant subroutine %s::%s redefined"
3400 : "Subroutine %s::%s redefined"),
3401 HvNAME_get(GvSTASH((GV*)dstr)),
3402 GvENAME((GV*)dstr));
3406 cv_ckproto_len(cv, (GV*)dstr,
3407 SvPOK(sref) ? SvPVX_const(sref) : NULL,
3408 SvPOK(sref) ? SvCUR(sref) : 0);
3410 GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3411 GvASSUMECV_on(dstr);
3412 if(GvSTASH(dstr)) mro_method_changed_in(GvSTASH(dstr)); /* sub foo { 1 } sub bar { 2 } *bar = \&foo */
3415 if (import_flag && !(GvFLAGS(dstr) & import_flag)
3416 && CopSTASH_ne(PL_curcop, GvSTASH(dstr))) {
3417 GvFLAGS(dstr) |= import_flag;
3422 if (SvTAINTED(sstr))
3428 Perl_sv_setsv_flags(pTHX_ SV *dstr, register SV *sstr, I32 flags)
3431 register U32 sflags;
3433 register svtype stype;
3438 if (SvIS_FREED(dstr)) {
3439 Perl_croak(aTHX_ "panic: attempt to copy value %" SVf
3440 " to a freed scalar %p", SVfARG(sstr), (void *)dstr);
3442 SV_CHECK_THINKFIRST_COW_DROP(dstr);
3444 sstr = &PL_sv_undef;
3445 if (SvIS_FREED(sstr)) {
3446 Perl_croak(aTHX_ "panic: attempt to copy freed scalar %p to %p",
3447 (void*)sstr, (void*)dstr);
3449 stype = SvTYPE(sstr);
3450 dtype = SvTYPE(dstr);
3452 (void)SvAMAGIC_off(dstr);
3455 /* need to nuke the magic */
3457 SvRMAGICAL_off(dstr);
3460 /* There's a lot of redundancy below but we're going for speed here */
3465 if (dtype != SVt_PVGV) {
3466 (void)SvOK_off(dstr);
3474 sv_upgrade(dstr, SVt_IV);
3478 sv_upgrade(dstr, SVt_PVIV);
3481 goto end_of_first_switch;
3483 (void)SvIOK_only(dstr);
3484 SvIV_set(dstr, SvIVX(sstr));
3487 /* SvTAINTED can only be true if the SV has taint magic, which in
3488 turn means that the SV type is PVMG (or greater). This is the
3489 case statement for SVt_IV, so this cannot be true (whatever gcov
3491 assert(!SvTAINTED(sstr));
3496 if (dtype < SVt_PV && dtype != SVt_IV)
3497 sv_upgrade(dstr, SVt_IV);
3505 sv_upgrade(dstr, SVt_NV);
3509 sv_upgrade(dstr, SVt_PVNV);
3512 goto end_of_first_switch;
3514 SvNV_set(dstr, SvNVX(sstr));
3515 (void)SvNOK_only(dstr);
3516 /* SvTAINTED can only be true if the SV has taint magic, which in
3517 turn means that the SV type is PVMG (or greater). This is the
3518 case statement for SVt_NV, so this cannot be true (whatever gcov
3520 assert(!SvTAINTED(sstr));
3526 #ifdef PERL_OLD_COPY_ON_WRITE
3527 if ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS) {
3528 if (dtype < SVt_PVIV)
3529 sv_upgrade(dstr, SVt_PVIV);
3537 sv_upgrade(dstr, SVt_PV);
3540 if (dtype < SVt_PVIV)
3541 sv_upgrade(dstr, SVt_PVIV);
3544 if (dtype < SVt_PVNV)
3545 sv_upgrade(dstr, SVt_PVNV);
3549 const char * const type = sv_reftype(sstr,0);
3551 Perl_croak(aTHX_ "Bizarre copy of %s in %s", type, OP_NAME(PL_op));
3553 Perl_croak(aTHX_ "Bizarre copy of %s", type);
3557 /* case SVt_BIND: */
3560 if (isGV_with_GP(sstr) && dtype <= SVt_PVGV) {
3561 glob_assign_glob(dstr, sstr, dtype);
3564 /* SvVALID means that this PVGV is playing at being an FBM. */
3568 if (SvGMAGICAL(sstr) && (flags & SV_GMAGIC)) {
3570 if (SvTYPE(sstr) != stype) {
3571 stype = SvTYPE(sstr);
3572 if (isGV_with_GP(sstr) && stype == SVt_PVGV && dtype <= SVt_PVGV) {
3573 glob_assign_glob(dstr, sstr, dtype);
3578 if (stype == SVt_PVLV)
3579 SvUPGRADE(dstr, SVt_PVNV);
3581 SvUPGRADE(dstr, (svtype)stype);
3583 end_of_first_switch:
3585 /* dstr may have been upgraded. */
3586 dtype = SvTYPE(dstr);
3587 sflags = SvFLAGS(sstr);
3589 if (dtype == SVt_PVCV || dtype == SVt_PVFM) {
3590 /* Assigning to a subroutine sets the prototype. */
3593 const char *const ptr = SvPV_const(sstr, len);
3595 SvGROW(dstr, len + 1);
3596 Copy(ptr, SvPVX(dstr), len + 1, char);
3597 SvCUR_set(dstr, len);
3599 SvFLAGS(dstr) |= sflags & SVf_UTF8;
3603 } else if (dtype == SVt_PVAV || dtype == SVt_PVHV) {
3604 const char * const type = sv_reftype(dstr,0);
3606 Perl_croak(aTHX_ "Cannot copy to %s in %s", type, OP_NAME(PL_op));
3608 Perl_croak(aTHX_ "Cannot copy to %s", type);
3609 } else if (sflags & SVf_ROK) {
3610 if (isGV_with_GP(dstr) && dtype == SVt_PVGV
3611 && SvTYPE(SvRV(sstr)) == SVt_PVGV) {
3614 if (GvIMPORTED(dstr) != GVf_IMPORTED
3615 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3617 GvIMPORTED_on(dstr);
3622 glob_assign_glob(dstr, sstr, dtype);
3626 if (dtype >= SVt_PV) {
3627 if (dtype == SVt_PVGV && isGV_with_GP(dstr)) {
3628 glob_assign_ref(dstr, sstr);
3631 if (SvPVX_const(dstr)) {
3637 (void)SvOK_off(dstr);
3638 SvRV_set(dstr, SvREFCNT_inc(SvRV(sstr)));
3639 SvFLAGS(dstr) |= sflags & SVf_ROK;
3640 assert(!(sflags & SVp_NOK));
3641 assert(!(sflags & SVp_IOK));
3642 assert(!(sflags & SVf_NOK));
3643 assert(!(sflags & SVf_IOK));
3645 else if (dtype == SVt_PVGV && isGV_with_GP(dstr)) {
3646 if (!(sflags & SVf_OK)) {
3647 if (ckWARN(WARN_MISC))
3648 Perl_warner(aTHX_ packWARN(WARN_MISC),
3649 "Undefined value assigned to typeglob");
3652 GV *gv = gv_fetchsv(sstr, GV_ADD, SVt_PVGV);
3653 if (dstr != (SV*)gv) {
3656 GvGP(dstr) = gp_ref(GvGP(gv));
3660 else if (sflags & SVp_POK) {
3664 * Check to see if we can just swipe the string. If so, it's a
3665 * possible small lose on short strings, but a big win on long ones.
3666 * It might even be a win on short strings if SvPVX_const(dstr)
3667 * has to be allocated and SvPVX_const(sstr) has to be freed.
3668 * Likewise if we can set up COW rather than doing an actual copy, we
3669 * drop to the else clause, as the swipe code and the COW setup code
3670 * have much in common.
3673 /* Whichever path we take through the next code, we want this true,
3674 and doing it now facilitates the COW check. */
3675 (void)SvPOK_only(dstr);
3678 /* If we're already COW then this clause is not true, and if COW
3679 is allowed then we drop down to the else and make dest COW
3680 with us. If caller hasn't said that we're allowed to COW
3681 shared hash keys then we don't do the COW setup, even if the
3682 source scalar is a shared hash key scalar. */
3683 (((flags & SV_COW_SHARED_HASH_KEYS)
3684 ? (sflags & (SVf_FAKE|SVf_READONLY)) != (SVf_FAKE|SVf_READONLY)
3685 : 1 /* If making a COW copy is forbidden then the behaviour we
3686 desire is as if the source SV isn't actually already
3687 COW, even if it is. So we act as if the source flags
3688 are not COW, rather than actually testing them. */
3690 #ifndef PERL_OLD_COPY_ON_WRITE
3691 /* The change that added SV_COW_SHARED_HASH_KEYS makes the logic
3692 when PERL_OLD_COPY_ON_WRITE is defined a little wrong.
3693 Conceptually PERL_OLD_COPY_ON_WRITE being defined should
3694 override SV_COW_SHARED_HASH_KEYS, because it means "always COW"
3695 but in turn, it's somewhat dead code, never expected to go
3696 live, but more kept as a placeholder on how to do it better
3697 in a newer implementation. */
3698 /* If we are COW and dstr is a suitable target then we drop down
3699 into the else and make dest a COW of us. */
3700 || (SvFLAGS(dstr) & CAN_COW_MASK) != CAN_COW_FLAGS
3705 (sflags & SVs_TEMP) && /* slated for free anyway? */
3706 !(sflags & SVf_OOK) && /* and not involved in OOK hack? */
3707 (!(flags & SV_NOSTEAL)) &&
3708 /* and we're allowed to steal temps */
3709 SvREFCNT(sstr) == 1 && /* and no other references to it? */
3710 SvLEN(sstr) && /* and really is a string */
3711 /* and won't be needed again, potentially */
3712 !(PL_op && PL_op->op_type == OP_AASSIGN))
3713 #ifdef PERL_OLD_COPY_ON_WRITE
3714 && ((flags & SV_COW_SHARED_HASH_KEYS)
3715 ? (!((sflags & CAN_COW_MASK) == CAN_COW_FLAGS
3716 && (SvFLAGS(dstr) & CAN_COW_MASK) == CAN_COW_FLAGS
3717 && SvTYPE(sstr) >= SVt_PVIV))
3721 /* Failed the swipe test, and it's not a shared hash key either.
3722 Have to copy the string. */
3723 STRLEN len = SvCUR(sstr);
3724 SvGROW(dstr, len + 1); /* inlined from sv_setpvn */
3725 Move(SvPVX_const(sstr),SvPVX(dstr),len,char);
3726 SvCUR_set(dstr, len);
3727 *SvEND(dstr) = '\0';
3729 /* If PERL_OLD_COPY_ON_WRITE is not defined, then isSwipe will always
3731 /* Either it's a shared hash key, or it's suitable for
3732 copy-on-write or we can swipe the string. */
3734 PerlIO_printf(Perl_debug_log, "Copy on write: sstr --> dstr\n");
3738 #ifdef PERL_OLD_COPY_ON_WRITE
3740 /* I believe I should acquire a global SV mutex if
3741 it's a COW sv (not a shared hash key) to stop
3742 it going un copy-on-write.
3743 If the source SV has gone un copy on write between up there
3744 and down here, then (assert() that) it is of the correct
3745 form to make it copy on write again */
3746 if ((sflags & (SVf_FAKE | SVf_READONLY))
3747 != (SVf_FAKE | SVf_READONLY)) {
3748 SvREADONLY_on(sstr);
3750 /* Make the source SV into a loop of 1.
3751 (about to become 2) */
3752 SV_COW_NEXT_SV_SET(sstr, sstr);
3756 /* Initial code is common. */
3757 if (SvPVX_const(dstr)) { /* we know that dtype >= SVt_PV */
3762 /* making another shared SV. */
3763 STRLEN cur = SvCUR(sstr);
3764 STRLEN len = SvLEN(sstr);
3765 #ifdef PERL_OLD_COPY_ON_WRITE
3767 assert (SvTYPE(dstr) >= SVt_PVIV);
3768 /* SvIsCOW_normal */
3769 /* splice us in between source and next-after-source. */
3770 SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
3771 SV_COW_NEXT_SV_SET(sstr, dstr);
3772 SvPV_set(dstr, SvPVX_mutable(sstr));
3776 /* SvIsCOW_shared_hash */
3777 DEBUG_C(PerlIO_printf(Perl_debug_log,
3778 "Copy on write: Sharing hash\n"));
3780 assert (SvTYPE(dstr) >= SVt_PV);
3782 HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr)))));
3784 SvLEN_set(dstr, len);
3785 SvCUR_set(dstr, cur);
3786 SvREADONLY_on(dstr);
3788 /* Relesase a global SV mutex. */
3791 { /* Passes the swipe test. */
3792 SvPV_set(dstr, SvPVX_mutable(sstr));
3793 SvLEN_set(dstr, SvLEN(sstr));
3794 SvCUR_set(dstr, SvCUR(sstr));
3797 (void)SvOK_off(sstr); /* NOTE: nukes most SvFLAGS on sstr */
3798 SvPV_set(sstr, NULL);
3804 if (sflags & SVp_NOK) {
3805 SvNV_set(dstr, SvNVX(sstr));
3807 if (sflags & SVp_IOK) {
3808 SvIV_set(dstr, SvIVX(sstr));
3809 /* Must do this otherwise some other overloaded use of 0x80000000
3810 gets confused. I guess SVpbm_VALID */
3811 if (sflags & SVf_IVisUV)
3814 SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_NOK|SVp_NOK|SVf_UTF8);
3816 const MAGIC * const smg = SvVSTRING_mg(sstr);
3818 sv_magic(dstr, NULL, PERL_MAGIC_vstring,
3819 smg->mg_ptr, smg->mg_len);
3820 SvRMAGICAL_on(dstr);
3824 else if (sflags & (SVp_IOK|SVp_NOK)) {
3825 (void)SvOK_off(dstr);
3826 SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_IVisUV|SVf_NOK|SVp_NOK);
3827 if (sflags & SVp_IOK) {
3828 /* XXXX Do we want to set IsUV for IV(ROK)? Be extra safe... */
3829 SvIV_set(dstr, SvIVX(sstr));
3831 if (sflags & SVp_NOK) {
3832 SvNV_set(dstr, SvNVX(sstr));
3836 if (isGV_with_GP(sstr)) {
3837 /* This stringification rule for globs is spread in 3 places.
3838 This feels bad. FIXME. */
3839 const U32 wasfake = sflags & SVf_FAKE;
3841 /* FAKE globs can get coerced, so need to turn this off
3842 temporarily if it is on. */
3844 gv_efullname3(dstr, (GV *)sstr, "*");
3845 SvFLAGS(sstr) |= wasfake;
3848 (void)SvOK_off(dstr);
3850 if (SvTAINTED(sstr))
3855 =for apidoc sv_setsv_mg
3857 Like C<sv_setsv>, but also handles 'set' magic.
3863 Perl_sv_setsv_mg(pTHX_ SV *dstr, register SV *sstr)
3865 sv_setsv(dstr,sstr);
3869 #ifdef PERL_OLD_COPY_ON_WRITE
3871 Perl_sv_setsv_cow(pTHX_ SV *dstr, SV *sstr)
3873 STRLEN cur = SvCUR(sstr);
3874 STRLEN len = SvLEN(sstr);
3875 register char *new_pv;
3878 PerlIO_printf(Perl_debug_log, "Fast copy on write: %p -> %p\n",
3879 (void*)sstr, (void*)dstr);
3886 if (SvTHINKFIRST(dstr))
3887 sv_force_normal_flags(dstr, SV_COW_DROP_PV);
3888 else if (SvPVX_const(dstr))
3889 Safefree(SvPVX_const(dstr));
3893 SvUPGRADE(dstr, SVt_PVIV);
3895 assert (SvPOK(sstr));
3896 assert (SvPOKp(sstr));
3897 assert (!SvIOK(sstr));
3898 assert (!SvIOKp(sstr));
3899 assert (!SvNOK(sstr));
3900 assert (!SvNOKp(sstr));
3902 if (SvIsCOW(sstr)) {
3904 if (SvLEN(sstr) == 0) {
3905 /* source is a COW shared hash key. */
3906 DEBUG_C(PerlIO_printf(Perl_debug_log,
3907 "Fast copy on write: Sharing hash\n"));
3908 new_pv = HEK_KEY(share_hek_hek(SvSHARED_HEK_FROM_PV(SvPVX_const(sstr))));
3911 SV_COW_NEXT_SV_SET(dstr, SV_COW_NEXT_SV(sstr));
3913 assert ((SvFLAGS(sstr) & CAN_COW_MASK) == CAN_COW_FLAGS);
3914 SvUPGRADE(sstr, SVt_PVIV);
3915 SvREADONLY_on(sstr);
3917 DEBUG_C(PerlIO_printf(Perl_debug_log,
3918 "Fast copy on write: Converting sstr to COW\n"));
3919 SV_COW_NEXT_SV_SET(dstr, sstr);
3921 SV_COW_NEXT_SV_SET(sstr, dstr);
3922 new_pv = SvPVX_mutable(sstr);
3925 SvPV_set(dstr, new_pv);
3926 SvFLAGS(dstr) = (SVt_PVIV|SVf_POK|SVp_POK|SVf_FAKE|SVf_READONLY);
3929 SvLEN_set(dstr, len);
3930 SvCUR_set(dstr, cur);
3939 =for apidoc sv_setpvn
3941 Copies a string into an SV. The C<len> parameter indicates the number of
3942 bytes to be copied. If the C<ptr> argument is NULL the SV will become
3943 undefined. Does not handle 'set' magic. See C<sv_setpvn_mg>.
3949 Perl_sv_setpvn(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
3952 register char *dptr;
3954 SV_CHECK_THINKFIRST_COW_DROP(sv);
3960 /* len is STRLEN which is unsigned, need to copy to signed */
3963 Perl_croak(aTHX_ "panic: sv_setpvn called with negative strlen");
3965 SvUPGRADE(sv, SVt_PV);
3967 dptr = SvGROW(sv, len + 1);
3968 Move(ptr,dptr,len,char);
3971 (void)SvPOK_only_UTF8(sv); /* validate pointer */
3976 =for apidoc sv_setpvn_mg
3978 Like C<sv_setpvn>, but also handles 'set' magic.
3984 Perl_sv_setpvn_mg(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
3986 sv_setpvn(sv,ptr,len);
3991 =for apidoc sv_setpv
3993 Copies a string into an SV. The string must be null-terminated. Does not
3994 handle 'set' magic. See C<sv_setpv_mg>.
4000 Perl_sv_setpv(pTHX_ register SV *sv, register const char *ptr)
4003 register STRLEN len;
4005 SV_CHECK_THINKFIRST_COW_DROP(sv);
4011 SvUPGRADE(sv, SVt_PV);
4013 SvGROW(sv, len + 1);
4014 Move(ptr,SvPVX(sv),len+1,char);
4016 (void)SvPOK_only_UTF8(sv); /* validate pointer */
4021 =for apidoc sv_setpv_mg
4023 Like C<sv_setpv>, but also handles 'set' magic.
4029 Perl_sv_setpv_mg(pTHX_ register SV *sv, register const char *ptr)
4036 =for apidoc sv_usepvn_flags
4038 Tells an SV to use C<ptr> to find its string value. Normally the
4039 string is stored inside the SV but sv_usepvn allows the SV to use an
4040 outside string. The C<ptr> should point to memory that was allocated
4041 by C<malloc>. The string length, C<len>, must be supplied. By default
4042 this function will realloc (i.e. move) the memory pointed to by C<ptr>,
4043 so that pointer should not be freed or used by the programmer after
4044 giving it to sv_usepvn, and neither should any pointers from "behind"
4045 that pointer (e.g. ptr + 1) be used.
4047 If C<flags> & SV_SMAGIC is true, will call SvSETMAGIC. If C<flags> &
4048 SV_HAS_TRAILING_NUL is true, then C<ptr[len]> must be NUL, and the realloc
4049 will be skipped. (i.e. the buffer is actually at least 1 byte longer than
4050 C<len>, and already meets the requirements for storing in C<SvPVX>)
4056 Perl_sv_usepvn_flags(pTHX_ SV *sv, char *ptr, STRLEN len, U32 flags)
4060 SV_CHECK_THINKFIRST_COW_DROP(sv);
4061 SvUPGRADE(sv, SVt_PV);
4064 if (flags & SV_SMAGIC)
4068 if (SvPVX_const(sv))
4072 if (flags & SV_HAS_TRAILING_NUL)
4073 assert(ptr[len] == '\0');
4076 allocate = (flags & SV_HAS_TRAILING_NUL)
4077 ? len + 1: PERL_STRLEN_ROUNDUP(len + 1);
4078 if (flags & SV_HAS_TRAILING_NUL) {
4079 /* It's long enough - do nothing.
4080 Specfically Perl_newCONSTSUB is relying on this. */
4083 /* Force a move to shake out bugs in callers. */
4084 char *new_ptr = (char*)safemalloc(allocate);
4085 Copy(ptr, new_ptr, len, char);
4086 PoisonFree(ptr,len,char);
4090 ptr = (char*) saferealloc (ptr, allocate);
4095 SvLEN_set(sv, allocate);
4096 if (!(flags & SV_HAS_TRAILING_NUL)) {
4099 (void)SvPOK_only_UTF8(sv); /* validate pointer */
4101 if (flags & SV_SMAGIC)
4105 #ifdef PERL_OLD_COPY_ON_WRITE
4106 /* Need to do this *after* making the SV normal, as we need the buffer
4107 pointer to remain valid until after we've copied it. If we let go too early,
4108 another thread could invalidate it by unsharing last of the same hash key
4109 (which it can do by means other than releasing copy-on-write Svs)
4110 or by changing the other copy-on-write SVs in the loop. */
4112 S_sv_release_COW(pTHX_ register SV *sv, const char *pvx, SV *after)
4114 { /* this SV was SvIsCOW_normal(sv) */
4115 /* we need to find the SV pointing to us. */
4116 SV *current = SV_COW_NEXT_SV(after);
4118 if (current == sv) {
4119 /* The SV we point to points back to us (there were only two of us
4121 Hence other SV is no longer copy on write either. */
4123 SvREADONLY_off(after);
4125 /* We need to follow the pointers around the loop. */
4127 while ((next = SV_COW_NEXT_SV(current)) != sv) {
4130 /* don't loop forever if the structure is bust, and we have
4131 a pointer into a closed loop. */
4132 assert (current != after);
4133 assert (SvPVX_const(current) == pvx);
4135 /* Make the SV before us point to the SV after us. */
4136 SV_COW_NEXT_SV_SET(current, after);
4142 =for apidoc sv_force_normal_flags
4144 Undo various types of fakery on an SV: if the PV is a shared string, make
4145 a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
4146 an xpvmg; if we're a copy-on-write scalar, this is the on-write time when
4147 we do the copy, and is also used locally. If C<SV_COW_DROP_PV> is set
4148 then a copy-on-write scalar drops its PV buffer (if any) and becomes
4149 SvPOK_off rather than making a copy. (Used where this scalar is about to be
4150 set to some other value.) In addition, the C<flags> parameter gets passed to
4151 C<sv_unref_flags()> when unrefing. C<sv_force_normal> calls this function
4152 with flags set to 0.
4158 Perl_sv_force_normal_flags(pTHX_ register SV *sv, U32 flags)
4161 #ifdef PERL_OLD_COPY_ON_WRITE
4162 if (SvREADONLY(sv)) {
4163 /* At this point I believe I should acquire a global SV mutex. */
4165 const char * const pvx = SvPVX_const(sv);
4166 const STRLEN len = SvLEN(sv);
4167 const STRLEN cur = SvCUR(sv);
4168 /* next COW sv in the loop. If len is 0 then this is a shared-hash
4169 key scalar, so we mustn't attempt to call SV_COW_NEXT_SV(), as
4170 we'll fail an assertion. */
4171 SV * const next = len ? SV_COW_NEXT_SV(sv) : 0;
4174 PerlIO_printf(Perl_debug_log,
4175 "Copy on write: Force normal %ld\n",
4181 /* This SV doesn't own the buffer, so need to Newx() a new one: */
4184 if (flags & SV_COW_DROP_PV) {
4185 /* OK, so we don't need to copy our buffer. */
4188 SvGROW(sv, cur + 1);
4189 Move(pvx,SvPVX(sv),cur,char);
4194 sv_release_COW(sv, pvx, next);
4196 unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4202 else if (IN_PERL_RUNTIME)
4203 Perl_croak(aTHX_ PL_no_modify);
4204 /* At this point I believe that I can drop the global SV mutex. */
4207 if (SvREADONLY(sv)) {
4209 const char * const pvx = SvPVX_const(sv);
4210 const STRLEN len = SvCUR(sv);
4215 SvGROW(sv, len + 1);
4216 Move(pvx,SvPVX(sv),len,char);
4218 unshare_hek(SvSHARED_HEK_FROM_PV(pvx));
4220 else if (IN_PERL_RUNTIME)
4221 Perl_croak(aTHX_ PL_no_modify);
4225 sv_unref_flags(sv, flags);
4226 else if (SvFAKE(sv) && SvTYPE(sv) == SVt_PVGV)
4233 Efficient removal of characters from the beginning of the string buffer.
4234 SvPOK(sv) must be true and the C<ptr> must be a pointer to somewhere inside
4235 the string buffer. The C<ptr> becomes the first character of the adjusted
4236 string. Uses the "OOK hack".
4237 Beware: after this function returns, C<ptr> and SvPVX_const(sv) may no longer
4238 refer to the same chunk of data.
4244 Perl_sv_chop(pTHX_ register SV *sv, register const char *ptr)
4250 const U8 *real_start;
4253 if (!ptr || !SvPOKp(sv))
4255 delta = ptr - SvPVX_const(sv);
4257 /* Nothing to do. */
4260 assert(ptr > SvPVX_const(sv));
4261 SV_CHECK_THINKFIRST(sv);
4264 if (!SvLEN(sv)) { /* make copy of shared string */
4265 const char *pvx = SvPVX_const(sv);
4266 const STRLEN len = SvCUR(sv);
4267 SvGROW(sv, len + 1);
4268 Move(pvx,SvPVX(sv),len,char);
4271 SvFLAGS(sv) |= SVf_OOK;
4274 SvOOK_offset(sv, old_delta);
4276 SvLEN_set(sv, SvLEN(sv) - delta);
4277 SvCUR_set(sv, SvCUR(sv) - delta);
4278 SvPV_set(sv, SvPVX(sv) + delta);
4280 p = (U8 *)SvPVX_const(sv);
4285 real_start = p - delta;
4289 if (delta < 0x100) {
4293 p -= sizeof(STRLEN);
4294 Copy((U8*)&delta, p, sizeof(STRLEN), U8);
4298 /* Fill the preceding buffer with sentinals to verify that no-one is
4300 while (p > real_start) {
4308 =for apidoc sv_catpvn
4310 Concatenates the string onto the end of the string which is in the SV. The
4311 C<len> indicates number of bytes to copy. If the SV has the UTF-8
4312 status set, then the bytes appended should be valid UTF-8.
4313 Handles 'get' magic, but not 'set' magic. See C<sv_catpvn_mg>.
4315 =for apidoc sv_catpvn_flags
4317 Concatenates the string onto the end of the string which is in the SV. The
4318 C<len> indicates number of bytes to copy. If the SV has the UTF-8
4319 status set, then the bytes appended should be valid UTF-8.
4320 If C<flags> has C<SV_GMAGIC> bit set, will C<mg_get> on C<dsv> if
4321 appropriate, else not. C<sv_catpvn> and C<sv_catpvn_nomg> are implemented
4322 in terms of this function.
4328 Perl_sv_catpvn_flags(pTHX_ register SV *dsv, register const char *sstr, register STRLEN slen, I32 flags)
4332 const char * const dstr = SvPV_force_flags(dsv, dlen, flags);
4334 SvGROW(dsv, dlen + slen + 1);
4336 sstr = SvPVX_const(dsv);
4337 Move(sstr, SvPVX(dsv) + dlen, slen, char);
4338 SvCUR_set(dsv, SvCUR(dsv) + slen);
4340 (void)SvPOK_only_UTF8(dsv); /* validate pointer */
4342 if (flags & SV_SMAGIC)
4347 =for apidoc sv_catsv
4349 Concatenates the string from SV C<ssv> onto the end of the string in
4350 SV C<dsv>. Modifies C<dsv> but not C<ssv>. Handles 'get' magic, but
4351 not 'set' magic. See C<sv_catsv_mg>.
4353 =for apidoc sv_catsv_flags
4355 Concatenates the string from SV C<ssv> onto the end of the string in
4356 SV C<dsv>. Modifies C<dsv> but not C<ssv>. If C<flags> has C<SV_GMAGIC>
4357 bit set, will C<mg_get> on the SVs if appropriate, else not. C<sv_catsv>
4358 and C<sv_catsv_nomg> are implemented in terms of this function.
4363 Perl_sv_catsv_flags(pTHX_ SV *dsv, register SV *ssv, I32 flags)
4368 const char *spv = SvPV_const(ssv, slen);
4370 /* sutf8 and dutf8 were type bool, but under USE_ITHREADS,
4371 gcc version 2.95.2 20000220 (Debian GNU/Linux) for
4372 Linux xxx 2.2.17 on sparc64 with gcc -O2, we erroneously
4373 get dutf8 = 0x20000000, (i.e. SVf_UTF8) even though
4374 dsv->sv_flags doesn't have that bit set.
4375 Andy Dougherty 12 Oct 2001
4377 const I32 sutf8 = DO_UTF8(ssv);
4380 if (SvGMAGICAL(dsv) && (flags & SV_GMAGIC))
4382 dutf8 = DO_UTF8(dsv);
4384 if (dutf8 != sutf8) {
4386 /* Not modifying source SV, so taking a temporary copy. */
4387 SV* const csv = newSVpvn_flags(spv, slen, SVs_TEMP);
4389 sv_utf8_upgrade(csv);
4390 spv = SvPV_const(csv, slen);
4393 sv_utf8_upgrade_nomg(dsv);
4395 sv_catpvn_nomg(dsv, spv, slen);
4398 if (flags & SV_SMAGIC)
4403 =for apidoc sv_catpv
4405 Concatenates the string onto the end of the string which is in the SV.
4406 If the SV has the UTF-8 status set, then the bytes appended should be
4407 valid UTF-8. Handles 'get' magic, but not 'set' magic. See C<sv_catpv_mg>.
4412 Perl_sv_catpv(pTHX_ register SV *sv, register const char *ptr)
4415 register STRLEN len;
4421 junk = SvPV_force(sv, tlen);
4423 SvGROW(sv, tlen + len + 1);
4425 ptr = SvPVX_const(sv);
4426 Move(ptr,SvPVX(sv)+tlen,len+1,char);
4427 SvCUR_set(sv, SvCUR(sv) + len);
4428 (void)SvPOK_only_UTF8(sv); /* validate pointer */
4433 =for apidoc sv_catpv_mg
4435 Like C<sv_catpv>, but also handles 'set' magic.
4441 Perl_sv_catpv_mg(pTHX_ register SV *sv, register const char *ptr)
4450 Creates a new SV. A non-zero C<len> parameter indicates the number of
4451 bytes of preallocated string space the SV should have. An extra byte for a
4452 trailing NUL is also reserved. (SvPOK is not set for the SV even if string
4453 space is allocated.) The reference count for the new SV is set to 1.
4455 In 5.9.3, newSV() replaces the older NEWSV() API, and drops the first
4456 parameter, I<x>, a debug aid which allowed callers to identify themselves.
4457 This aid has been superseded by a new build option, PERL_MEM_LOG (see
4458 L<perlhack/PERL_MEM_LOG>). The older API is still there for use in XS
4459 modules supporting older perls.
4465 Perl_newSV(pTHX_ STRLEN len)
4472 sv_upgrade(sv, SVt_PV);
4473 SvGROW(sv, len + 1);
4478 =for apidoc sv_magicext
4480 Adds magic to an SV, upgrading it if necessary. Applies the
4481 supplied vtable and returns a pointer to the magic added.
4483 Note that C<sv_magicext> will allow things that C<sv_magic> will not.
4484 In particular, you can add magic to SvREADONLY SVs, and add more than
4485 one instance of the same 'how'.
4487 If C<namlen> is greater than zero then a C<savepvn> I<copy> of C<name> is
4488 stored, if C<namlen> is zero then C<name> is stored as-is and - as another
4489 special case - if C<(name && namlen == HEf_SVKEY)> then C<name> is assumed
4490 to contain an C<SV*> and is stored as-is with its REFCNT incremented.
4492 (This is now used as a subroutine by C<sv_magic>.)
4497 Perl_sv_magicext(pTHX_ SV* sv, SV* obj, int how, const MGVTBL *vtable,
4498 const char* name, I32 namlen)
4503 SvUPGRADE(sv, SVt_PVMG);
4504 Newxz(mg, 1, MAGIC);
4505 mg->mg_moremagic = SvMAGIC(sv);
4506 SvMAGIC_set(sv, mg);
4508 /* Sometimes a magic contains a reference loop, where the sv and
4509 object refer to each other. To prevent a reference loop that
4510 would prevent such objects being freed, we look for such loops
4511 and if we find one we avoid incrementing the object refcount.
4513 Note we cannot do this to avoid self-tie loops as intervening RV must
4514 have its REFCNT incremented to keep it in existence.
4517 if (!obj || obj == sv ||
4518 how == PERL_MAGIC_arylen ||
4519 how == PERL_MAGIC_symtab ||
4520 (SvTYPE(obj) == SVt_PVGV &&
4521 (GvSV(obj) == sv || GvHV(obj) == (HV*)sv || GvAV(obj) == (AV*)sv ||
4522 GvCV(obj) == (CV*)sv || GvIOp(obj) == (IO*)sv ||
4523 GvFORM(obj) == (CV*)sv)))
4528 mg->mg_obj = SvREFCNT_inc_simple(obj);
4529 mg->mg_flags |= MGf_REFCOUNTED;
4532 /* Normal self-ties simply pass a null object, and instead of
4533 using mg_obj directly, use the SvTIED_obj macro to produce a
4534 new RV as needed. For glob "self-ties", we are tieing the PVIO
4535 with an RV obj pointing to the glob containing the PVIO. In
4536 this case, to avoid a reference loop, we need to weaken the
4540 if (how == PERL_MAGIC_tiedscalar && SvTYPE(sv) == SVt_PVIO &&
4541 obj && SvROK(obj) && GvIO(SvRV(obj)) == (IO*)sv)
4547 mg->mg_len = namlen;
4550 mg->mg_ptr = savepvn(name, namlen);
4551 else if (namlen == HEf_SVKEY)
4552 mg->mg_ptr = (char*)SvREFCNT_inc_simple_NN((SV*)name);
4554 mg->mg_ptr = (char *) name;
4556 mg->mg_virtual = (MGVTBL *) vtable;
4560 SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK|SVf_POK);
4565 =for apidoc sv_magic
4567 Adds magic to an SV. First upgrades C<sv> to type C<SVt_PVMG> if necessary,
4568 then adds a new magic item of type C<how> to the head of the magic list.
4570 See C<sv_magicext> (which C<sv_magic> now calls) for a description of the
4571 handling of the C<name> and C<namlen> arguments.
4573 You need to use C<sv_magicext> to add magic to SvREADONLY SVs and also
4574 to add more than one instance of the same 'how'.
4580 Perl_sv_magic(pTHX_ register SV *sv, SV *obj, int how, const char *name, I32 namlen)
4583 const MGVTBL *vtable;
4586 #ifdef PERL_OLD_COPY_ON_WRITE
4588 sv_force_normal_flags(sv, 0);
4590 if (SvREADONLY(sv)) {
4592 /* its okay to attach magic to shared strings; the subsequent
4593 * upgrade to PVMG will unshare the string */
4594 !(SvFAKE(sv) && SvTYPE(sv) < SVt_PVMG)
4597 && how != PERL_MAGIC_regex_global
4598 && how != PERL_MAGIC_bm
4599 && how != PERL_MAGIC_fm
4600 && how != PERL_MAGIC_sv
4601 && how != PERL_MAGIC_backref
4604 Perl_croak(aTHX_ PL_no_modify);
4607 if (SvMAGICAL(sv) || (how == PERL_MAGIC_taint && SvTYPE(sv) >= SVt_PVMG)) {
4608 if (SvMAGIC(sv) && (mg = mg_find(sv, how))) {
4609 /* sv_magic() refuses to add a magic of the same 'how' as an
4612 if (how == PERL_MAGIC_taint) {
4614 /* Any scalar which already had taint magic on which someone
4615 (erroneously?) did SvIOK_on() or similar will now be
4616 incorrectly sporting public "OK" flags. */
4617 SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK|SVf_POK);
4625 vtable = &PL_vtbl_sv;
4627 case PERL_MAGIC_overload:
4628 vtable = &PL_vtbl_amagic;
4630 case PERL_MAGIC_overload_elem:
4631 vtable = &PL_vtbl_amagicelem;
4633 case PERL_MAGIC_overload_table:
4634 vtable = &PL_vtbl_ovrld;
4637 vtable = &PL_vtbl_bm;
4639 case PERL_MAGIC_regdata:
4640 vtable = &PL_vtbl_regdata;
4642 case PERL_MAGIC_regdatum:
4643 vtable = &PL_vtbl_regdatum;
4645 case PERL_MAGIC_env:
4646 vtable = &PL_vtbl_env;
4649 vtable = &PL_vtbl_fm;
4651 case PERL_MAGIC_envelem:
4652 vtable = &PL_vtbl_envelem;
4654 case PERL_MAGIC_regex_global:
4655 vtable = &PL_vtbl_mglob;
4657 case PERL_MAGIC_isa:
4658 vtable = &PL_vtbl_isa;
4660 case PERL_MAGIC_isaelem:
4661 vtable = &PL_vtbl_isaelem;
4663 case PERL_MAGIC_nkeys:
4664 vtable = &PL_vtbl_nkeys;
4666 case PERL_MAGIC_dbfile:
4669 case PERL_MAGIC_dbline:
4670 vtable = &PL_vtbl_dbline;
4672 #ifdef USE_LOCALE_COLLATE
4673 case PERL_MAGIC_collxfrm:
4674 vtable = &PL_vtbl_collxfrm;
4676 #endif /* USE_LOCALE_COLLATE */
4677 case PERL_MAGIC_tied:
4678 vtable = &PL_vtbl_pack;
4680 case PERL_MAGIC_tiedelem:
4681 case PERL_MAGIC_tiedscalar:
4682 vtable = &PL_vtbl_packelem;
4685 vtable = &PL_vtbl_regexp;
4687 case PERL_MAGIC_hints:
4688 /* As this vtable is all NULL, we can reuse it. */
4689 case PERL_MAGIC_sig:
4690 vtable = &PL_vtbl_sig;
4692 case PERL_MAGIC_sigelem:
4693 vtable = &PL_vtbl_sigelem;
4695 case PERL_MAGIC_taint:
4696 vtable = &PL_vtbl_taint;
4698 case PERL_MAGIC_uvar:
4699 vtable = &PL_vtbl_uvar;
4701 case PERL_MAGIC_vec:
4702 vtable = &PL_vtbl_vec;
4704 case PERL_MAGIC_arylen_p:
4705 case PERL_MAGIC_rhash:
4706 case PERL_MAGIC_symtab:
4707 case PERL_MAGIC_vstring:
4710 case PERL_MAGIC_utf8:
4711 vtable = &PL_vtbl_utf8;
4713 case PERL_MAGIC_substr:
4714 vtable = &PL_vtbl_substr;
4716 case PERL_MAGIC_defelem:
4717 vtable = &PL_vtbl_defelem;
4719 case PERL_MAGIC_arylen:
4720 vtable = &PL_vtbl_arylen;
4722 case PERL_MAGIC_pos:
4723 vtable = &PL_vtbl_pos;
4725 case PERL_MAGIC_backref:
4726 vtable = &PL_vtbl_backref;
4728 case PERL_MAGIC_hintselem:
4729 vtable = &PL_vtbl_hintselem;
4731 case PERL_MAGIC_ext:
4732 /* Reserved for use by extensions not perl internals. */
4733 /* Useful for attaching extension internal data to perl vars. */
4734 /* Note that multiple extensions may clash if magical scalars */
4735 /* etc holding private data from one are passed to another. */
4739 Perl_croak(aTHX_ "Don't know how to handle magic of type \\%o", how);
4742 /* Rest of work is done else where */
4743 mg = sv_magicext(sv,obj,how,vtable,name,namlen);
4746 case PERL_MAGIC_taint:
4749 case PERL_MAGIC_ext:
4750 case PERL_MAGIC_dbfile:
4757 =for apidoc sv_unmagic
4759 Removes all magic of type C<type> from an SV.