3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, 2006, 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 /* ============================================================================
49 =head1 Allocation and deallocation of SVs.
51 An SV (or AV, HV, etc.) is allocated in two parts: the head (struct
52 sv, av, hv...) contains type and reference count information, and for
53 many types, a pointer to the body (struct xrv, xpv, xpviv...), which
54 contains fields specific to each type. Some types store all they need
55 in the head, so don't have a body.
57 In all but the most memory-paranoid configuations (ex: PURIFY), heads
58 and bodies are allocated out of arenas, which by default are
59 approximately 4K chunks of memory parcelled up into N heads or bodies.
60 Sv-bodies are allocated by their sv-type, guaranteeing size
61 consistency needed to allocate safely from arrays.
63 For SV-heads, the first slot in each arena is reserved, and holds a
64 link to the next arena, some flags, and a note of the number of slots.
65 Snaked through each arena chain is a linked list of free items; when
66 this becomes empty, an extra arena is allocated and divided up into N
67 items which are threaded into the free list.
69 SV-bodies are similar, but they use arena-sets by default, which
70 separate the link and info from the arena itself, and reclaim the 1st
71 slot in the arena. SV-bodies are further described later.
73 The following global variables are associated with arenas:
75 PL_sv_arenaroot pointer to list of SV arenas
76 PL_sv_root pointer to list of free SV structures
78 PL_body_arenas head of linked-list of body arenas
79 PL_body_roots[] array of pointers to list of free bodies of svtype
80 arrays are indexed by the svtype needed
82 A few special SV heads are not allocated from an arena, but are
83 instead directly created in the interpreter structure, eg PL_sv_undef.
84 The size of arenas can be changed from the default by setting
85 PERL_ARENA_SIZE appropriately at compile time.
87 The SV arena serves the secondary purpose of allowing still-live SVs
88 to be located and destroyed during final cleanup.
90 At the lowest level, the macros new_SV() and del_SV() grab and free
91 an SV head. (If debugging with -DD, del_SV() calls the function S_del_sv()
92 to return the SV to the free list with error checking.) new_SV() calls
93 more_sv() / sv_add_arena() to add an extra arena if the free list is empty.
94 SVs in the free list have their SvTYPE field set to all ones.
96 At the time of very final cleanup, sv_free_arenas() is called from
97 perl_destruct() to physically free all the arenas allocated since the
98 start of the interpreter.
100 Manipulation of any of the PL_*root pointers is protected by enclosing
101 LOCK_SV_MUTEX; ... UNLOCK_SV_MUTEX calls which should Do the Right Thing
102 if 5005 threads are enabled.
104 The function visit() scans the SV arenas list, and calls a specified
105 function for each SV it finds which is still live - ie which has an SvTYPE
106 other than all 1's, and a non-zero SvREFCNT. visit() is used by the
107 following functions (specified as [function that calls visit()] / [function
108 called by visit() for each SV]):
110 sv_report_used() / do_report_used()
111 dump all remaining SVs (debugging aid)
113 sv_clean_objs() / do_clean_objs(),do_clean_named_objs()
114 Attempt to free all objects pointed to by RVs,
115 and, unless DISABLE_DESTRUCTOR_KLUDGE is defined,
116 try to do the same for all objects indirectly
117 referenced by typeglobs too. Called once from
118 perl_destruct(), prior to calling sv_clean_all()
121 sv_clean_all() / do_clean_all()
122 SvREFCNT_dec(sv) each remaining SV, possibly
123 triggering an sv_free(). It also sets the
124 SVf_BREAK flag on the SV to indicate that the
125 refcnt has been artificially lowered, and thus
126 stopping sv_free() from giving spurious warnings
127 about SVs which unexpectedly have a refcnt
128 of zero. called repeatedly from perl_destruct()
129 until there are no SVs left.
131 =head2 Arena allocator API Summary
133 Private API to rest of sv.c
137 new_XIV(), del_XIV(),
138 new_XNV(), del_XNV(),
143 sv_report_used(), sv_clean_objs(), sv_clean_all(), sv_free_arenas()
147 ============================================================================ */
150 * "A time to plant, and a time to uproot what was planted..."
154 * nice_chunk and nice_chunk size need to be set
155 * and queried under the protection of sv_mutex for 5005 threads
158 Perl_offer_nice_chunk(pTHX_ void *chunk, U32 chunk_size)
163 new_chunk = (void *)(chunk);
164 new_chunk_size = (chunk_size);
165 if (new_chunk_size > PL_nice_chunk_size) {
166 Safefree(PL_nice_chunk);
167 PL_nice_chunk = (char *) new_chunk;
168 PL_nice_chunk_size = new_chunk_size;
175 #define plant_SV(p) \
177 SvANY(p) = (void *)PL_sv_root; \
178 SvFLAGS(p) = SVTYPEMASK; \
183 /* sv_mutex must be held while calling uproot_SV() for 5005 threads */
184 #define uproot_SV(p) \
187 PL_sv_root = (SV*)SvANY(p); \
192 /* make some more SVs by adding another arena */
194 /* sv_mutex must be held while calling more_sv() for 5005 threads */
201 sv_add_arena(PL_nice_chunk, PL_nice_chunk_size, 0);
202 PL_nice_chunk = NULL;
203 PL_nice_chunk_size = 0;
206 char *chunk; /* must use New here to match call to */
207 Newx(chunk,PERL_ARENA_SIZE,char); /* Safefree() in sv_free_arenas() */
208 sv_add_arena(chunk, PERL_ARENA_SIZE, 0);
214 /* new_SV(): return a new, empty SV head */
216 #ifdef DEBUG_LEAKING_SCALARS
217 /* provide a real function for a debugger to play with */
227 sv = S_more_sv(aTHX);
234 # define new_SV(p) (p)=S_new_SV(aTHX)
243 (p) = S_more_sv(aTHX); \
252 /* del_SV(): return an empty SV head to the free list */
267 S_del_sv(pTHX_ SV *p)
272 for (sva = PL_sv_arenaroot; sva; sva = (SV *) SvANY(sva)) {
273 const SV * const sv = sva + 1;
274 const SV * const svend = &sva[SvREFCNT(sva)];
275 if (p >= sv && p < svend) {
281 if (ckWARN_d(WARN_INTERNAL))
282 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
283 "Attempt to free non-arena SV: 0x%"UVxf
284 pTHX__FORMAT, PTR2UV(p) pTHX__VALUE);
291 #else /* ! DEBUGGING */
293 #define del_SV(p) plant_SV(p)
295 #endif /* DEBUGGING */
299 =head1 SV Manipulation Functions
301 =for apidoc sv_add_arena
303 Given a chunk of memory, link it to the head of the list of arenas,
304 and split it into a list of free SVs.
310 Perl_sv_add_arena(pTHX_ char *ptr, U32 size, U32 flags)
312 SV* const sva = (SV*)ptr;
316 /* The first SV in an arena isn't an SV. */
317 SvANY(sva) = (void *) PL_sv_arenaroot; /* ptr to next arena */
318 SvREFCNT(sva) = size / sizeof(SV); /* number of SV slots */
319 SvFLAGS(sva) = flags; /* FAKE if not to be freed */
321 PL_sv_arenaroot = sva;
322 PL_sv_root = sva + 1;
324 svend = &sva[SvREFCNT(sva) - 1];
327 SvANY(sv) = (void *)(SV*)(sv + 1);
331 /* Must always set typemask because it's awlays checked in on cleanup
332 when the arenas are walked looking for objects. */
333 SvFLAGS(sv) = SVTYPEMASK;
340 SvFLAGS(sv) = SVTYPEMASK;
343 /* visit(): call the named function for each non-free SV in the arenas
344 * whose flags field matches the flags/mask args. */
347 S_visit(pTHX_ SVFUNC_t f, U32 flags, U32 mask)
352 for (sva = PL_sv_arenaroot; sva; sva = (SV*)SvANY(sva)) {
353 register const SV * const svend = &sva[SvREFCNT(sva)];
355 for (sv = sva + 1; sv < svend; ++sv) {
356 if (SvTYPE(sv) != SVTYPEMASK
357 && (sv->sv_flags & mask) == flags
370 /* called by sv_report_used() for each live SV */
373 do_report_used(pTHX_ SV *sv)
375 if (SvTYPE(sv) != SVTYPEMASK) {
376 PerlIO_printf(Perl_debug_log, "****\n");
383 =for apidoc sv_report_used
385 Dump the contents of all SVs not yet freed. (Debugging aid).
391 Perl_sv_report_used(pTHX)
394 visit(do_report_used, 0, 0);
400 /* called by sv_clean_objs() for each live SV */
403 do_clean_objs(pTHX_ SV *sv)
407 if (SvROK(sv) && SvOBJECT(rv = SvRV(sv))) {
408 DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning object ref:\n "), sv_dump(sv)));
420 /* XXX Might want to check arrays, etc. */
423 /* called by sv_clean_objs() for each live SV */
425 #ifndef DISABLE_DESTRUCTOR_KLUDGE
427 do_clean_named_objs(pTHX_ SV *sv)
429 if (SvTYPE(sv) == SVt_PVGV && GvGP(sv)) {
431 #ifdef PERL_DONT_CREATE_GVSV
434 SvOBJECT(GvSV(sv))) ||
435 (GvAV(sv) && SvOBJECT(GvAV(sv))) ||
436 (GvHV(sv) && SvOBJECT(GvHV(sv))) ||
437 (GvIO(sv) && SvOBJECT(GvIO(sv))) ||
438 (GvCV(sv) && SvOBJECT(GvCV(sv))) )
440 DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning named glob object:\n "), sv_dump(sv)));
441 SvFLAGS(sv) |= SVf_BREAK;
449 =for apidoc sv_clean_objs
451 Attempt to destroy all objects not yet freed
457 Perl_sv_clean_objs(pTHX)
459 PL_in_clean_objs = TRUE;
460 visit(do_clean_objs, SVf_ROK, SVf_ROK);
461 #ifndef DISABLE_DESTRUCTOR_KLUDGE
462 /* some barnacles may yet remain, clinging to typeglobs */
463 visit(do_clean_named_objs, SVt_PVGV, SVTYPEMASK);
465 PL_in_clean_objs = FALSE;
468 /* called by sv_clean_all() for each live SV */
471 do_clean_all(pTHX_ SV *sv)
473 DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning loops: SV at 0x%"UVxf"\n", PTR2UV(sv)) ));
474 SvFLAGS(sv) |= SVf_BREAK;
479 =for apidoc sv_clean_all
481 Decrement the refcnt of each remaining SV, possibly triggering a
482 cleanup. This function may have to be called multiple times to free
483 SVs which are in complex self-referential hierarchies.
489 Perl_sv_clean_all(pTHX)
492 PL_in_clean_all = TRUE;
493 cleaned = visit(do_clean_all, 0,0);
494 PL_in_clean_all = FALSE;
499 ARENASETS: a meta-arena implementation which separates arena-info
500 into struct arena_set, which contains an array of struct
501 arena_descs, each holding info for a single arena. By separating
502 the meta-info from the arena, we recover the 1st slot, formerly
503 borrowed for list management. The arena_set is about the size of an
504 arena, avoiding the needless malloc overhead of a naive linked-list.
506 The cost is 1 arena-set malloc per ~320 arena-mallocs, + the unused
507 memory in the last arena-set (1/2 on average). In trade, we get
508 back the 1st slot in each arena (ie 1.7% of a CV-arena, less for
509 smaller types). The recovery of the wasted space allows use of
510 small arenas for large, rare body types,
513 char *arena; /* the raw storage, allocated aligned */
514 size_t size; /* its size ~4k typ */
515 U32 misc; /* type, and in future other things. */
520 /* Get the maximum number of elements in set[] such that struct arena_set
521 will fit within PERL_ARENA_SIZE, which is probabably just under 4K, and
522 therefore likely to be 1 aligned memory page. */
524 #define ARENAS_PER_SET ((PERL_ARENA_SIZE - sizeof(struct arena_set*) \
525 - 2 * sizeof(int)) / sizeof (struct arena_desc))
528 struct arena_set* next;
529 unsigned int set_size; /* ie ARENAS_PER_SET */
530 unsigned int curr; /* index of next available arena-desc */
531 struct arena_desc set[ARENAS_PER_SET];
535 =for apidoc sv_free_arenas
537 Deallocate the memory used by all arenas. Note that all the individual SV
538 heads and bodies within the arenas must already have been freed.
543 Perl_sv_free_arenas(pTHX)
549 /* Free arenas here, but be careful about fake ones. (We assume
550 contiguity of the fake ones with the corresponding real ones.) */
552 for (sva = PL_sv_arenaroot; sva; sva = svanext) {
553 svanext = (SV*) SvANY(sva);
554 while (svanext && SvFAKE(svanext))
555 svanext = (SV*) SvANY(svanext);
562 struct arena_set *aroot = (struct arena_set*) PL_body_arenas;
565 struct arena_set *current = aroot;
568 assert(aroot->set[i].arena);
569 Safefree(aroot->set[i].arena);
577 i = PERL_ARENA_ROOTS_SIZE;
579 PL_body_roots[i] = 0;
581 Safefree(PL_nice_chunk);
582 PL_nice_chunk = NULL;
583 PL_nice_chunk_size = 0;
589 =for apidoc report_uninit
591 Print appropriate "Use of uninitialized variable" warning
597 Perl_report_uninit(pTHX)
600 Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit,
601 " in ", OP_DESC(PL_op));
603 Perl_warner(aTHX_ packWARN(WARN_UNINITIALIZED), PL_warn_uninit, "", "");
607 Here are mid-level routines that manage the allocation of bodies out
608 of the various arenas. There are 5 kinds of arenas:
610 1. SV-head arenas, which are discussed and handled above
611 2. regular body arenas
612 3. arenas for reduced-size bodies
614 5. pte arenas (thread related)
616 Arena types 2 & 3 are chained by body-type off an array of
617 arena-root pointers, which is indexed by svtype. Some of the
618 larger/less used body types are malloced singly, since a large
619 unused block of them is wasteful. Also, several svtypes dont have
620 bodies; the data fits into the sv-head itself. The arena-root
621 pointer thus has a few unused root-pointers (which may be hijacked
622 later for arena types 4,5)
624 3 differs from 2 as an optimization; some body types have several
625 unused fields in the front of the structure (which are kept in-place
626 for consistency). These bodies can be allocated in smaller chunks,
627 because the leading fields arent accessed. Pointers to such bodies
628 are decremented to point at the unused 'ghost' memory, knowing that
629 the pointers are used with offsets to the real memory.
631 HE, HEK arenas are managed separately, with separate code, but may
632 be merge-able later..
634 PTE arenas are not sv-bodies, but they share these mid-level
635 mechanics, so are considered here. The new mid-level mechanics rely
636 on the sv_type of the body being allocated, so we just reserve one
637 of the unused body-slots for PTEs, then use it in those (2) PTE
638 contexts below (line ~10k)
641 /* get_arena(size): this creates custom-sized arenas
642 TBD: export properly for hv.c: S_more_he().
645 Perl_get_arena(pTHX_ size_t arena_size, U32 misc)
647 struct arena_desc* adesc;
648 struct arena_set *aroot = (struct arena_set*) PL_body_arenas;
651 /* shouldnt need this
652 if (!arena_size) arena_size = PERL_ARENA_SIZE;
655 /* may need new arena-set to hold new arena */
656 if (!aroot || aroot->curr >= aroot->set_size) {
657 struct arena_set *newroot;
658 Newxz(newroot, 1, struct arena_set);
659 newroot->set_size = ARENAS_PER_SET;
660 newroot->next = aroot;
662 PL_body_arenas = (void *) newroot;
663 DEBUG_m(PerlIO_printf(Perl_debug_log, "new arenaset %p\n", aroot));
666 /* ok, now have arena-set with at least 1 empty/available arena-desc */
667 curr = aroot->curr++;
668 adesc = &(aroot->set[curr]);
669 assert(!adesc->arena);
671 Newx(adesc->arena, arena_size, char);
672 adesc->size = arena_size;
674 DEBUG_m(PerlIO_printf(Perl_debug_log, "arena %d added: %p size %d\n",
675 curr, adesc->arena, arena_size));
681 /* return a thing to the free list */
683 #define del_body(thing, root) \
685 void ** const thing_copy = (void **)thing;\
687 *thing_copy = *root; \
688 *root = (void*)thing_copy; \
694 =head1 SV-Body Allocation
696 Allocation of SV-bodies is similar to SV-heads, differing as follows;
697 the allocation mechanism is used for many body types, so is somewhat
698 more complicated, it uses arena-sets, and has no need for still-live
701 At the outermost level, (new|del)_X*V macros return bodies of the
702 appropriate type. These macros call either (new|del)_body_type or
703 (new|del)_body_allocated macro pairs, depending on specifics of the
704 type. Most body types use the former pair, the latter pair is used to
705 allocate body types with "ghost fields".
707 "ghost fields" are fields that are unused in certain types, and
708 consequently dont need to actually exist. They are declared because
709 they're part of a "base type", which allows use of functions as
710 methods. The simplest examples are AVs and HVs, 2 aggregate types
711 which don't use the fields which support SCALAR semantics.
713 For these types, the arenas are carved up into *_allocated size
714 chunks, we thus avoid wasted memory for those unaccessed members.
715 When bodies are allocated, we adjust the pointer back in memory by the
716 size of the bit not allocated, so it's as if we allocated the full
717 structure. (But things will all go boom if you write to the part that
718 is "not there", because you'll be overwriting the last members of the
719 preceding structure in memory.)
721 We calculate the correction using the STRUCT_OFFSET macro. For
722 example, if xpv_allocated is the same structure as XPV then the two
723 OFFSETs sum to zero, and the pointer is unchanged. If the allocated
724 structure is smaller (no initial NV actually allocated) then the net
725 effect is to subtract the size of the NV from the pointer, to return a
726 new pointer as if an initial NV were actually allocated.
728 This is the same trick as was used for NV and IV bodies. Ironically it
729 doesn't need to be used for NV bodies any more, because NV is now at
730 the start of the structure. IV bodies don't need it either, because
731 they are no longer allocated.
733 In turn, the new_body_* allocators call S_new_body(), which invokes
734 new_body_inline macro, which takes a lock, and takes a body off the
735 linked list at PL_body_roots[sv_type], calling S_more_bodies() if
736 necessary to refresh an empty list. Then the lock is released, and
737 the body is returned.
739 S_more_bodies calls get_arena(), and carves it up into an array of N
740 bodies, which it strings into a linked list. It looks up arena-size
741 and body-size from the body_details table described below, thus
742 supporting the multiple body-types.
744 If PURIFY is defined, or PERL_ARENA_SIZE=0, arenas are not used, and
745 the (new|del)_X*V macros are mapped directly to malloc/free.
751 For each sv-type, struct body_details bodies_by_type[] carries
752 parameters which control these aspects of SV handling:
754 Arena_size determines whether arenas are used for this body type, and if
755 so, how big they are. PURIFY or PERL_ARENA_SIZE=0 set this field to
756 zero, forcing individual mallocs and frees.
758 Body_size determines how big a body is, and therefore how many fit into
759 each arena. Offset carries the body-pointer adjustment needed for
760 *_allocated body types, and is used in *_allocated macros.
762 But its main purpose is to parameterize info needed in
763 Perl_sv_upgrade(). The info here dramatically simplifies the function
764 vs the implementation in 5.8.7, making it table-driven. All fields
765 are used for this, except for arena_size.
767 For the sv-types that have no bodies, arenas are not used, so those
768 PL_body_roots[sv_type] are unused, and can be overloaded. In
769 something of a special case, SVt_NULL is borrowed for HE arenas;
770 PL_body_roots[SVt_NULL] is filled by S_more_he, but the
771 bodies_by_type[SVt_NULL] slot is not used, as the table is not
774 PTEs also use arenas, but are never seen in Perl_sv_upgrade.
775 Nonetheless, they get their own slot in bodies_by_type[SVt_NULL], so
776 they can just use the same allocation semantics. At first, PTEs were
777 also overloaded to a non-body sv-type, but this yielded hard-to-find
778 malloc bugs, so was simplified by claiming a new slot. This choice
779 has no consequence at this time.
783 struct body_details {
784 U8 body_size; /* Size to allocate */
785 U8 copy; /* Size of structure to copy (may be shorter) */
787 unsigned int type : 4; /* We have space for a sanity check. */
788 unsigned int cant_upgrade : 1; /* Cannot upgrade this type */
789 unsigned int zero_nv : 1; /* zero the NV when upgrading from this */
790 unsigned int arena : 1; /* Allocated from an arena */
791 size_t arena_size; /* Size of arena to allocate */
799 /* With -DPURFIY we allocate everything directly, and don't use arenas.
800 This seems a rather elegant way to simplify some of the code below. */
801 #define HASARENA FALSE
803 #define HASARENA TRUE
805 #define NOARENA FALSE
807 /* Size the arenas to exactly fit a given number of bodies. A count
808 of 0 fits the max number bodies into a PERL_ARENA_SIZE.block,
809 simplifying the default. If count > 0, the arena is sized to fit
810 only that many bodies, allowing arenas to be used for large, rare
811 bodies (XPVFM, XPVIO) without undue waste. The arena size is
812 limited by PERL_ARENA_SIZE, so we can safely oversize the
815 #define FIT_ARENA0(body_size) \
816 ((size_t)(PERL_ARENA_SIZE / body_size) * body_size)
817 #define FIT_ARENAn(count,body_size) \
818 ( count * body_size <= PERL_ARENA_SIZE) \
819 ? count * body_size \
820 : FIT_ARENA0 (body_size)
821 #define FIT_ARENA(count,body_size) \
823 ? FIT_ARENAn (count, body_size) \
824 : FIT_ARENA0 (body_size)
826 /* A macro to work out the offset needed to subtract from a pointer to (say)
833 to make its members accessible via a pointer to (say)
843 #define relative_STRUCT_OFFSET(longer, shorter, member) \
844 (STRUCT_OFFSET(shorter, member) - STRUCT_OFFSET(longer, member))
846 /* Calculate the length to copy. Specifically work out the length less any
847 final padding the compiler needed to add. See the comment in sv_upgrade
848 for why copying the padding proved to be a bug. */
850 #define copy_length(type, last_member) \
851 STRUCT_OFFSET(type, last_member) \
852 + sizeof (((type*)SvANY((SV*)0))->last_member)
854 static const struct body_details bodies_by_type[] = {
855 {0, 0, 0, SVt_NULL, FALSE, NONV, NOARENA, 0},
857 { sizeof(xiv_allocated), sizeof(IV),
858 + relative_STRUCT_OFFSET(xiv_allocated, XPVIV, xiv_iv),
859 SVt_IV, FALSE, NONV, HASARENA, FIT_ARENA(0, sizeof(xiv_allocated))},
861 /* 8 bytes on most ILP32 with IEEE doubles */
862 { sizeof(xnv_allocated), sizeof(NV),
863 + relative_STRUCT_OFFSET(xnv_allocated, XPVNV, xnv_nv),
864 SVt_NV, FALSE, HADNV, HASARENA, FIT_ARENA(0, sizeof(xnv_allocated))},
866 { sizeof(XRV), sizeof(XRV), 0, SVt_RV, FALSE, NONV, HASARENA,
867 FIT_ARENA(0, sizeof(XRV))},
869 { sizeof(xpv_allocated),
870 copy_length(XPV, xpv_len)
871 - relative_STRUCT_OFFSET(xpv_allocated, XPV, xpv_cur),
872 + relative_STRUCT_OFFSET(xpv_allocated, XPV, xpv_cur),
873 SVt_PV, FALSE, NONV, HASARENA, FIT_ARENA(0, sizeof(xpv_allocated)) },
875 { sizeof(xpviv_allocated),
876 copy_length(XPVIV, xiv_iv)
877 - relative_STRUCT_OFFSET(xpviv_allocated, XPVIV, xpv_cur),
878 + relative_STRUCT_OFFSET(xpviv_allocated, XPVIV, xpv_cur),
879 SVt_PVIV, FALSE, NONV, HASARENA, FIT_ARENA(0, sizeof(xpviv_allocated)) },
881 { sizeof(XPVNV), copy_length(XPVNV, xnv_nv), 0, SVt_PVNV, FALSE, HADNV,
882 HASARENA, FIT_ARENA(0, sizeof(XPVNV)) },
884 { sizeof(XPVMG), copy_length(XPVMG, xmg_stash), 0, SVt_PVMG, FALSE, HADNV,
885 HASARENA, FIT_ARENA(0, sizeof(XPVMG)) },
887 { sizeof(XPVBM), sizeof(XPVBM), 0, SVt_PVBM, TRUE, HADNV,
888 HASARENA, FIT_ARENA(0, sizeof(XPVBM)) },
890 { sizeof(XPVLV), sizeof(XPVLV), 0, SVt_PVLV, TRUE, HADNV,
891 HASARENA, FIT_ARENA(0, sizeof(XPVLV)) },
893 { sizeof(xpvav_allocated),
894 sizeof(xpvav_allocated)
895 - relative_STRUCT_OFFSET(xpvav_allocated, XPVAV, xav_fill),
896 + relative_STRUCT_OFFSET(xpvav_allocated, XPVAV, xav_fill),
897 SVt_PVAV, TRUE, HADNV, HASARENA, FIT_ARENA(0, sizeof(xpvav_allocated)) },
899 { sizeof(xpvhv_allocated),
900 sizeof(xpvhv_allocated)
901 - relative_STRUCT_OFFSET(xpvhv_allocated, XPVHV, xhv_fill),
902 + relative_STRUCT_OFFSET(xpvhv_allocated, XPVHV, xhv_fill),
903 SVt_PVHV, TRUE, HADNV, HASARENA, FIT_ARENA(0, sizeof(xpvhv_allocated)) },
905 { sizeof(XPVCV), sizeof(XPVCV), 0, SVt_PVCV, TRUE, HADNV,
906 HASARENA, FIT_ARENA(0, sizeof(XPVCV)) },
908 { sizeof(XPVGV), sizeof(XPVGV), 0, SVt_PVGV, TRUE, HADNV,
909 HASARENA, FIT_ARENA(0, sizeof(XPVGV)) },
911 { sizeof(XPVFM), sizeof(XPVFM), 0, SVt_PVFM, TRUE, HADNV,
912 HASARENA, FIT_ARENA(20, sizeof(XPVFM)) },
914 { sizeof(XPVIO), sizeof(XPVIO), 0, SVt_PVIO, TRUE, HADNV,
915 HASARENA, FIT_ARENA(24, sizeof(XPVIO)) },
917 /* These two are the 17th and 18th entries in the array, so beyond the
918 all the regular SV types. */
919 { sizeof(struct ptr_tbl_ent), /* This is used for PTEs. */
920 0, 0, 0, FALSE, NONV, NOARENA,
921 FIT_ARENA(0, sizeof(struct ptr_tbl_ent))
924 { sizeof(HE), 0, 0, 0, FALSE, NONV, NOARENA,
925 FIT_ARENA(0, sizeof(HE)) }
928 #define new_body_type(sv_type) \
929 (void *)((char *)S_new_body(aTHX_ sv_type))
931 #define del_body_type(p, sv_type) \
932 del_body(p, &PL_body_roots[sv_type])
935 #define new_body_allocated(sv_type) \
936 (void *)((char *)S_new_body(aTHX_ sv_type) \
937 - bodies_by_type[sv_type].offset)
939 #define del_body_allocated(p, sv_type) \
940 del_body(p + bodies_by_type[sv_type].offset, &PL_body_roots[sv_type])
943 #define my_safemalloc(s) (void*)safemalloc(s)
944 #define my_safecalloc(s) (void*)safecalloc(s, 1)
945 #define my_safefree(p) safefree((char*)p)
947 typedef struct xpviv XIV;
948 typedef struct xpvnv XNV;
952 #define new_XIV() my_safemalloc(sizeof(XPVIV))
953 #define del_XIV(p) my_safefree(p)
955 #define new_XNV() my_safemalloc(sizeof(XPVNV))
956 #define del_XNV(p) my_safefree(p)
958 #define new_XRV() my_safemalloc(sizeof(XRV))
959 #define del_XRV(p) my_safefree(p)
961 #define new_XPVNV() my_safemalloc(sizeof(XPVNV))
962 #define del_XPVNV(p) my_safefree(p)
964 #define new_XPVAV() my_safemalloc(sizeof(XPVAV))
965 #define del_XPVAV(p) my_safefree(p)
967 #define new_XPVHV() my_safemalloc(sizeof(XPVHV))
968 #define del_XPVHV(p) my_safefree(p)
970 #define new_XPVMG() my_safemalloc(sizeof(XPVMG))
971 #define del_XPVMG(p) my_safefree(p)
973 #define new_XPVGV() my_safemalloc(sizeof(XPVGV))
974 #define del_XPVGV(p) my_safefree(p)
978 #define new_XIV() new_body_allocated(SVt_IV)
979 #define del_XIV(p) del_body_allocated(p, SVt_IV)
981 #define new_XNV() new_body_allocated(SVt_NV)
982 #define del_XNV(p) del_body_allocated(p, SVt_NV)
984 #define new_XRV() new_body_type(SVt_RV)
985 #define del_XRV(p) del_body_type(SVt_RV)
987 #define new_XPVNV() new_body_type(SVt_PVNV)
988 #define del_XPVNV(p) del_body_type(p, SVt_PVNV)
990 #define new_XPVAV() new_body_allocated(SVt_PVAV)
991 #define del_XPVAV(p) del_body_allocated(p, SVt_PVAV)
993 #define new_XPVHV() new_body_allocated(SVt_PVHV)
994 #define del_XPVHV(p) del_body_allocated(p, SVt_PVHV)
996 #define new_XPVMG() new_body_type(SVt_PVMG)
997 #define del_XPVMG(p) del_body_type(p, SVt_PVMG)
999 #define new_XPVGV() new_body_type(SVt_PVGV)
1000 #define del_XPVGV(p) del_body_type(p, SVt_PVGV)
1004 /* no arena for you! */
1006 #define new_NOARENA(details) \
1007 my_safemalloc((details)->body_size + (details)->offset)
1008 #define new_NOARENAZ(details) \
1009 my_safecalloc((details)->body_size + (details)->offset)
1012 S_more_bodies (pTHX_ svtype sv_type)
1014 void ** const root = &PL_body_roots[sv_type];
1015 const struct body_details * const bdp = &bodies_by_type[sv_type];
1016 const size_t body_size = bdp->body_size;
1019 #if defined DEBUGGING
1020 static bool done_sanity_check;
1022 /* PERL_GLOBAL_STRUCT_PRIVATE cannot coexist with global
1023 * variables like done_sanity_check. */
1024 assert(bdp->arena_size);
1026 if (!done_sanity_check) {
1027 unsigned int i = SVt_LAST;
1029 done_sanity_check = TRUE;
1032 assert (bodies_by_type[i].type == i);
1036 assert(bdp->arena_size);
1038 start = (char*) Perl_get_arena(aTHX_ bdp->arena_size, sv_type);
1040 end = start + bdp->arena_size - body_size;
1042 /* computed count doesnt reflect the 1st slot reservation */
1043 DEBUG_m(PerlIO_printf(Perl_debug_log,
1044 "arena %p end %p arena-size %d type %d size %d ct %d\n",
1046 (int)bdp->arena_size, sv_type, (int)body_size,
1047 (int)bdp->arena_size / (int)body_size));
1049 *root = (void *)start;
1051 while (start < end) {
1052 char * const next = start + body_size;
1053 *(void**) start = (void *)next;
1056 *(void **)start = 0;
1061 /* grab a new thing from the free list, allocating more if necessary.
1062 The inline version is used for speed in hot routines, and the
1063 function using it serves the rest (unless PURIFY).
1065 #define new_body_inline(xpv, sv_type) \
1067 void ** const r3wt = &PL_body_roots[sv_type]; \
1069 xpv = (PTR_TBL_ENT_t*) (*((void **)(r3wt)) \
1070 ? *((void **)(r3wt)) : more_bodies(sv_type)); \
1071 *(r3wt) = *(void**)(xpv); \
1078 S_new_body(pTHX_ svtype sv_type)
1081 new_body_inline(xpv, sv_type);
1088 =for apidoc sv_upgrade
1090 Upgrade an SV to a more complex form. Generally adds a new body type to the
1091 SV, then copies across as much information as possible from the old body.
1092 You generally want to use the C<SvUPGRADE> macro wrapper. See also C<svtype>.
1098 Perl_sv_upgrade(pTHX_ register SV *sv, U32 new_type)
1102 const U32 old_type = SvTYPE(sv);
1103 const struct body_details *new_type_details;
1104 const struct body_details *const old_type_details
1105 = bodies_by_type + old_type;
1107 if (new_type != SVt_PV && SvIsCOW(sv)) {
1108 sv_force_normal_flags(sv, 0);
1111 if (old_type == new_type)
1114 old_body = SvANY(sv);
1116 /* Copying structures onto other structures that have been neatly zeroed
1117 has a subtle gotcha. Consider XPVMG
1119 +------+------+------+------+------+-------+-------+
1120 | NV | CUR | LEN | IV | MAGIC | STASH |
1121 +------+------+------+------+------+-------+-------+
1122 0 4 8 12 16 20 24 28
1124 where NVs are aligned to 8 bytes, so that sizeof that structure is
1125 actually 32 bytes long, with 4 bytes of padding at the end:
1127 +------+------+------+------+------+-------+-------+------+
1128 | NV | CUR | LEN | IV | MAGIC | STASH | ??? |
1129 +------+------+------+------+------+-------+-------+------+
1130 0 4 8 12 16 20 24 28 32
1132 so what happens if you allocate memory for this structure:
1134 +------+------+------+------+------+-------+-------+------+------+...
1135 | NV | CUR | LEN | IV | MAGIC | STASH | GP | NAME |
1136 +------+------+------+------+------+-------+-------+------+------+...
1137 0 4 8 12 16 20 24 28 32 36
1139 zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
1140 expect, because you copy the area marked ??? onto GP. Now, ??? may have
1141 started out as zero once, but it's quite possible that it isn't. So now,
1142 rather than a nicely zeroed GP, you have it pointing somewhere random.
1145 (In fact, GP ends up pointing at a previous GP structure, because the
1146 principle cause of the padding in XPVMG getting garbage is a copy of
1147 sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob)
1149 So we are careful and work out the size of used parts of all the
1156 if (new_type < SVt_PVIV) {
1157 new_type = (new_type == SVt_NV)
1158 ? SVt_PVNV : SVt_PVIV;
1163 if (new_type < SVt_PVNV) {
1164 new_type = SVt_PVNV;
1168 if (new_type == SVt_IV)
1169 new_type = SVt_PVIV;
1170 else if (new_type == SVt_NV)
1171 new_type = SVt_PVNV;
1174 if (new_type == SVt_IV)
1175 new_type = SVt_PVIV;
1176 else if (new_type == SVt_NV)
1177 new_type = SVt_PVNV;
1180 if (new_type == SVt_NV)
1181 new_type = SVt_PVNV;
1186 /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1187 there's no way that it can be safely upgraded, because perl.c
1188 expects to Safefree(SvANY(PL_mess_sv)) */
1189 assert(sv != PL_mess_sv);
1190 /* This flag bit is used to mean other things in other scalar types.
1191 Given that it only has meaning inside the pad, it shouldn't be set
1192 on anything that can get upgraded. */
1193 assert(!SvPAD_TYPED(sv));
1196 if (old_type_details->cant_upgrade)
1197 Perl_croak(aTHX_ "Can't upgrade %s (%" UVuf ") to %" UVuf,
1198 sv_reftype(sv, 0), (UV) old_type, (UV) new_type);
1200 new_type_details = bodies_by_type + new_type;
1202 if (old_type > new_type) {
1206 SvFLAGS(sv) &= ~SVTYPEMASK;
1207 SvFLAGS(sv) |= new_type;
1209 /* This can't happen, as SVt_NULL is <= all values of new_type, so one of
1210 the return statements above will have triggered. */
1211 assert (new_type != SVt_NULL);
1214 assert(old_type == SVt_NULL);
1215 SvANY(sv) = new_XIV();
1219 assert(old_type == SVt_NULL);
1220 SvANY(sv) = new_XNV();
1224 assert(old_type == SVt_NULL);
1225 SvANY(sv) = new_XRV();
1230 assert(new_type_details->body_size);
1233 assert(new_type_details->arena);
1234 assert(new_type_details->arena_size);
1235 /* This points to the start of the allocated area. */
1236 new_body_inline(new_body, new_type);
1237 Zero(new_body, new_type_details->body_size, char);
1238 new_body = ((char *)new_body) - new_type_details->offset;
1240 /* We always allocated the full length item with PURIFY. To do this
1241 we fake things so that arena is false for all 16 types.. */
1242 new_body = new_NOARENAZ(new_type_details);
1244 SvANY(sv) = new_body;
1245 if (new_type == SVt_PVAV) {
1248 AvFLAGS(sv) = AVf_REAL;
1251 /* SVt_NULL isn't the only thing upgraded to AV or HV.
1252 The target created by newSVrv also is, and it can have magic.
1253 However, it never has SvPVX set.
1255 if (old_type >= SVt_RV && ((XPV*)old_body)->xpv_pv) {
1256 char *pv = ((XPV*)old_body)->xpv_pv;
1257 if (old_type >= SVt_PV) {
1259 pv -= ((XPVIV*)old_body)->xiv_iv;
1263 /* RV shouldn't be pointing at anything, but just in case. */
1265 SvREFCNT_dec((SV*)pv);
1270 if (old_type >= SVt_PVMG) {
1271 SvMAGIC_set(sv, ((XPVMG*)old_body)->xmg_magic);
1272 SvSTASH_set(sv, ((XPVMG*)old_body)->xmg_stash);
1278 /* XXX Is this still needed? Was it ever needed? Surely as there is
1279 no route from NV to PVIV, NOK can never be true */
1280 assert(!SvNOKp(sv));
1292 assert(new_type_details->body_size);
1293 /* We always allocated the full length item with PURIFY. To do this
1294 we fake things so that arena is false for all 16 types.. */
1295 if(new_type_details->arena) {
1296 /* This points to the start of the allocated area. */
1297 new_body_inline(new_body, new_type);
1298 Zero(new_body, new_type_details->body_size, char);
1299 new_body = ((char *)new_body) - new_type_details->offset;
1301 new_body = new_NOARENAZ(new_type_details);
1303 SvANY(sv) = new_body;
1305 if (old_type_details->copy) {
1306 Copy((char *)old_body + old_type_details->offset,
1307 (char *)new_body + old_type_details->offset,
1308 old_type_details->copy, char);
1311 #ifndef NV_ZERO_IS_ALLBITS_ZERO
1312 /* If NV 0.0 is stores as all bits 0 then Zero() already creates a
1313 * correct 0.0 for us. Otherwise, if the old body didn't have an
1314 * NV slot, but the new one does, then we need to initialise the
1315 * freshly created NV slot with whatever the correct bit pattern is
1317 if (old_type_details->zero_nv && !bodies_by_type[new_type].zero_nv)
1321 if (new_type == SVt_PVIO)
1322 IoPAGE_LEN(sv) = 60;
1325 Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu",
1326 (unsigned long)new_type);
1329 if (old_type_details->arena) {
1330 /* If there was an old body, then we need to free it.
1331 Note that there is an assumption that all bodies of types that
1332 can be upgraded came from arenas. Only the more complex non-
1333 upgradable types are allowed to be directly malloc()ed. */
1335 my_safefree(old_body);
1337 del_body((void*)((char*)old_body + old_type_details->offset),
1338 &PL_body_roots[old_type]);
1345 =for apidoc sv_backoff
1347 Remove any string offset. You should normally use the C<SvOOK_off> macro
1354 Perl_sv_backoff(pTHX_ register SV *sv)
1356 PERL_UNUSED_CONTEXT;
1359 const char * const s = SvPVX_const(sv);
1360 SvLEN_set(sv, SvLEN(sv) + SvIVX(sv));
1361 SvPV_set(sv, SvPVX(sv) - SvIVX(sv));
1363 Move(s, SvPVX(sv), SvCUR(sv)+1, char);
1365 SvFLAGS(sv) &= ~SVf_OOK;
1372 Expands the character buffer in the SV. If necessary, uses C<sv_unref> and
1373 upgrades the SV to C<SVt_PV>. Returns a pointer to the character buffer.
1374 Use the C<SvGROW> wrapper instead.
1380 Perl_sv_grow(pTHX_ register SV *sv, register STRLEN newlen)
1386 #ifdef HAS_64K_LIMIT
1387 if (newlen >= 0x10000) {
1388 PerlIO_printf(Perl_debug_log,
1389 "Allocation too large: %"UVxf"\n", (UV)newlen);
1392 #endif /* HAS_64K_LIMIT */
1395 if (SvTYPE(sv) < SVt_PV) {
1396 sv_upgrade(sv, SVt_PV);
1397 s = SvPVX_mutable(sv);
1399 else if (SvOOK(sv)) { /* pv is offset? */
1401 s = SvPVX_mutable(sv);
1402 if (newlen > SvLEN(sv))
1403 newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1404 #ifdef HAS_64K_LIMIT
1405 if (newlen >= 0x10000)
1410 s = SvPVX_mutable(sv);
1412 if (newlen > SvLEN(sv)) { /* need more room? */
1413 newlen = PERL_STRLEN_ROUNDUP(newlen);
1414 if (SvLEN(sv) && s) {
1416 const STRLEN l = malloced_size((void*)SvPVX_const(sv));
1422 s = (char*)saferealloc(s, newlen);
1425 /* sv_force_normal_flags() must not try to unshare the new
1426 PVX we allocate below. AMS 20010713 */
1427 if (SvREADONLY(sv) && SvFAKE(sv)) {
1431 s = (char*)safemalloc(newlen);
1432 if (SvPVX_const(sv) && SvCUR(sv)) {
1433 Move(SvPVX_const(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1437 SvLEN_set(sv, newlen);
1443 =for apidoc sv_setiv
1445 Copies an integer into the given SV, upgrading first if necessary.
1446 Does not handle 'set' magic. See also C<sv_setiv_mg>.
1452 Perl_sv_setiv(pTHX_ register SV *sv, IV i)
1454 SV_CHECK_THINKFIRST(sv);
1455 switch (SvTYPE(sv)) {
1457 sv_upgrade(sv, SVt_IV);
1460 sv_upgrade(sv, SVt_PVNV);
1464 sv_upgrade(sv, SVt_PVIV);
1473 Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1477 (void)SvIOK_only(sv); /* validate number */
1483 =for apidoc sv_setiv_mg
1485 Like C<sv_setiv>, but also handles 'set' magic.
1491 Perl_sv_setiv_mg(pTHX_ register SV *sv, IV i)
1498 =for apidoc sv_setuv
1500 Copies an unsigned integer into the given SV, upgrading first if necessary.
1501 Does not handle 'set' magic. See also C<sv_setuv_mg>.
1507 Perl_sv_setuv(pTHX_ register SV *sv, UV u)
1509 /* With these two if statements:
1510 u=1.49 s=0.52 cu=72.49 cs=10.64 scripts=270 tests=20865
1513 u=1.35 s=0.47 cu=73.45 cs=11.43 scripts=270 tests=20865
1515 If you wish to remove them, please benchmark to see what the effect is
1517 if (u <= (UV)IV_MAX) {
1518 sv_setiv(sv, (IV)u);
1527 =for apidoc sv_setuv_mg
1529 Like C<sv_setuv>, but also handles 'set' magic.
1535 Perl_sv_setuv_mg(pTHX_ register SV *sv, UV u)
1542 =for apidoc sv_setnv
1544 Copies a double into the given SV, upgrading first if necessary.
1545 Does not handle 'set' magic. See also C<sv_setnv_mg>.
1551 Perl_sv_setnv(pTHX_ register SV *sv, NV num)
1553 SV_CHECK_THINKFIRST(sv);
1554 switch (SvTYPE(sv)) {
1557 sv_upgrade(sv, SVt_NV);
1562 sv_upgrade(sv, SVt_PVNV);
1571 Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
1576 (void)SvNOK_only(sv); /* validate number */
1581 =for apidoc sv_setnv_mg
1583 Like C<sv_setnv>, but also handles 'set' magic.
1589 Perl_sv_setnv_mg(pTHX_ register SV *sv, NV num)
1595 /* Print an "isn't numeric" warning, using a cleaned-up,
1596 * printable version of the offending string
1600 S_not_a_number(pTHX_ SV *sv)
1607 dsv = sv_2mortal(newSVpvs(""));
1608 pv = sv_uni_display(dsv, sv, 10, 0);
1611 const char * const limit = tmpbuf + sizeof(tmpbuf) - 8;
1612 /* each *s can expand to 4 chars + "...\0",
1613 i.e. need room for 8 chars */
1615 const char *s = SvPVX_const(sv);
1616 const char * const end = s + SvCUR(sv);
1617 for ( ; s < end && d < limit; s++ ) {
1619 if (ch & 128 && !isPRINT_LC(ch)) {
1628 else if (ch == '\r') {
1632 else if (ch == '\f') {
1636 else if (ch == '\\') {
1640 else if (ch == '\0') {
1644 else if (isPRINT_LC(ch))
1661 Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1662 "Argument \"%s\" isn't numeric in %s", pv,
1665 Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
1666 "Argument \"%s\" isn't numeric", pv);
1670 =for apidoc looks_like_number
1672 Test if the content of an SV looks like a number (or is a number).
1673 C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1674 non-numeric warning), even if your atof() doesn't grok them.
1680 Perl_looks_like_number(pTHX_ SV *sv)
1682 register const char *sbegin;
1686 sbegin = SvPVX_const(sv);
1689 else if (SvPOKp(sv))
1690 sbegin = SvPV_const(sv, len);
1692 return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
1693 return grok_number(sbegin, len, NULL);
1696 /* Actually, ISO C leaves conversion of UV to IV undefined, but
1697 until proven guilty, assume that things are not that bad... */
1702 As 64 bit platforms often have an NV that doesn't preserve all bits of
1703 an IV (an assumption perl has been based on to date) it becomes necessary
1704 to remove the assumption that the NV always carries enough precision to
1705 recreate the IV whenever needed, and that the NV is the canonical form.
1706 Instead, IV/UV and NV need to be given equal rights. So as to not lose
1707 precision as a side effect of conversion (which would lead to insanity
1708 and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1709 1) to distinguish between IV/UV/NV slots that have cached a valid
1710 conversion where precision was lost and IV/UV/NV slots that have a
1711 valid conversion which has lost no precision
1712 2) to ensure that if a numeric conversion to one form is requested that
1713 would lose precision, the precise conversion (or differently
1714 imprecise conversion) is also performed and cached, to prevent
1715 requests for different numeric formats on the same SV causing
1716 lossy conversion chains. (lossless conversion chains are perfectly
1721 SvIOKp is true if the IV slot contains a valid value
1722 SvIOK is true only if the IV value is accurate (UV if SvIOK_UV true)
1723 SvNOKp is true if the NV slot contains a valid value
1724 SvNOK is true only if the NV value is accurate
1727 while converting from PV to NV, check to see if converting that NV to an
1728 IV(or UV) would lose accuracy over a direct conversion from PV to
1729 IV(or UV). If it would, cache both conversions, return NV, but mark
1730 SV as IOK NOKp (ie not NOK).
1732 While converting from PV to IV, check to see if converting that IV to an
1733 NV would lose accuracy over a direct conversion from PV to NV. If it
1734 would, cache both conversions, flag similarly.
1736 Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1737 correctly because if IV & NV were set NV *always* overruled.
1738 Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1739 changes - now IV and NV together means that the two are interchangeable:
1740 SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
1742 The benefit of this is that operations such as pp_add know that if
1743 SvIOK is true for both left and right operands, then integer addition
1744 can be used instead of floating point (for cases where the result won't
1745 overflow). Before, floating point was always used, which could lead to
1746 loss of precision compared with integer addition.
1748 * making IV and NV equal status should make maths accurate on 64 bit
1750 * may speed up maths somewhat if pp_add and friends start to use
1751 integers when possible instead of fp. (Hopefully the overhead in
1752 looking for SvIOK and checking for overflow will not outweigh the
1753 fp to integer speedup)
1754 * will slow down integer operations (callers of SvIV) on "inaccurate"
1755 values, as the change from SvIOK to SvIOKp will cause a call into
1756 sv_2iv each time rather than a macro access direct to the IV slot
1757 * should speed up number->string conversion on integers as IV is
1758 favoured when IV and NV are equally accurate
1760 ####################################################################
1761 You had better be using SvIOK_notUV if you want an IV for arithmetic:
1762 SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
1763 On the other hand, SvUOK is true iff UV.
1764 ####################################################################
1766 Your mileage will vary depending your CPU's relative fp to integer
1770 #ifndef NV_PRESERVES_UV
1771 # define IS_NUMBER_UNDERFLOW_IV 1
1772 # define IS_NUMBER_UNDERFLOW_UV 2
1773 # define IS_NUMBER_IV_AND_UV 2
1774 # define IS_NUMBER_OVERFLOW_IV 4
1775 # define IS_NUMBER_OVERFLOW_UV 5
1777 /* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
1779 /* For sv_2nv these three cases are "SvNOK and don't bother casting" */
1781 S_sv_2iuv_non_preserve(pTHX_ register SV *sv, I32 numtype)
1783 PERL_UNUSED_ARG(numtype); /* Used only under DEBUGGING? */
1784 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));
1785 if (SvNVX(sv) < (NV)IV_MIN) {
1786 (void)SvIOKp_on(sv);
1788 SvIV_set(sv, IV_MIN);
1789 return IS_NUMBER_UNDERFLOW_IV;
1791 if (SvNVX(sv) > (NV)UV_MAX) {
1792 (void)SvIOKp_on(sv);
1795 SvUV_set(sv, UV_MAX);
1796 return IS_NUMBER_OVERFLOW_UV;
1798 (void)SvIOKp_on(sv);
1800 /* Can't use strtol etc to convert this string. (See truth table in
1802 if (SvNVX(sv) <= (UV)IV_MAX) {
1803 SvIV_set(sv, I_V(SvNVX(sv)));
1804 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
1805 SvIOK_on(sv); /* Integer is precise. NOK, IOK */
1807 /* Integer is imprecise. NOK, IOKp */
1809 return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
1812 SvUV_set(sv, U_V(SvNVX(sv)));
1813 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
1814 if (SvUVX(sv) == UV_MAX) {
1815 /* As we know that NVs don't preserve UVs, UV_MAX cannot
1816 possibly be preserved by NV. Hence, it must be overflow.
1818 return IS_NUMBER_OVERFLOW_UV;
1820 SvIOK_on(sv); /* Integer is precise. NOK, UOK */
1822 /* Integer is imprecise. NOK, IOKp */
1824 return IS_NUMBER_OVERFLOW_IV;
1826 #endif /* !NV_PRESERVES_UV*/
1829 S_sv_2iuv_common(pTHX_ SV *sv) {
1831 /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
1832 * without also getting a cached IV/UV from it at the same time
1833 * (ie PV->NV conversion should detect loss of accuracy and cache
1834 * IV or UV at same time to avoid this. */
1835 /* IV-over-UV optimisation - choose to cache IV if possible */
1837 if (SvTYPE(sv) == SVt_NV)
1838 sv_upgrade(sv, SVt_PVNV);
1840 (void)SvIOKp_on(sv); /* Must do this first, to clear any SvOOK */
1841 /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
1842 certainly cast into the IV range at IV_MAX, whereas the correct
1843 answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
1845 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
1846 if (Perl_isnan(SvNVX(sv))) {
1852 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
1853 SvIV_set(sv, I_V(SvNVX(sv)));
1854 if (SvNVX(sv) == (NV) SvIVX(sv)
1855 #ifndef NV_PRESERVES_UV
1856 && (((UV)1 << NV_PRESERVES_UV_BITS) >
1857 (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
1858 /* Don't flag it as "accurately an integer" if the number
1859 came from a (by definition imprecise) NV operation, and
1860 we're outside the range of NV integer precision */
1863 SvIOK_on(sv); /* Can this go wrong with rounding? NWC */
1864 DEBUG_c(PerlIO_printf(Perl_debug_log,
1865 "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
1871 /* IV not precise. No need to convert from PV, as NV
1872 conversion would already have cached IV if it detected
1873 that PV->IV would be better than PV->NV->IV
1874 flags already correct - don't set public IOK. */
1875 DEBUG_c(PerlIO_printf(Perl_debug_log,
1876 "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
1881 /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
1882 but the cast (NV)IV_MIN rounds to a the value less (more
1883 negative) than IV_MIN which happens to be equal to SvNVX ??
1884 Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
1885 NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
1886 (NV)UVX == NVX are both true, but the values differ. :-(
1887 Hopefully for 2s complement IV_MIN is something like
1888 0x8000000000000000 which will be exact. NWC */
1891 SvUV_set(sv, U_V(SvNVX(sv)));
1893 (SvNVX(sv) == (NV) SvUVX(sv))
1894 #ifndef NV_PRESERVES_UV
1895 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
1896 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
1897 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
1898 /* Don't flag it as "accurately an integer" if the number
1899 came from a (by definition imprecise) NV operation, and
1900 we're outside the range of NV integer precision */
1905 DEBUG_c(PerlIO_printf(Perl_debug_log,
1906 "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
1912 else if (SvPOKp(sv) && SvLEN(sv)) {
1914 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
1915 /* We want to avoid a possible problem when we cache an IV/ a UV which
1916 may be later translated to an NV, and the resulting NV is not
1917 the same as the direct translation of the initial string
1918 (eg 123.456 can shortcut to the IV 123 with atol(), but we must
1919 be careful to ensure that the value with the .456 is around if the
1920 NV value is requested in the future).
1922 This means that if we cache such an IV/a UV, we need to cache the
1923 NV as well. Moreover, we trade speed for space, and do not
1924 cache the NV if we are sure it's not needed.
1927 /* SVt_PVNV is one higher than SVt_PVIV, hence this order */
1928 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
1929 == IS_NUMBER_IN_UV) {
1930 /* It's definitely an integer, only upgrade to PVIV */
1931 if (SvTYPE(sv) < SVt_PVIV)
1932 sv_upgrade(sv, SVt_PVIV);
1934 } else if (SvTYPE(sv) < SVt_PVNV)
1935 sv_upgrade(sv, SVt_PVNV);
1937 /* If NVs preserve UVs then we only use the UV value if we know that
1938 we aren't going to call atof() below. If NVs don't preserve UVs
1939 then the value returned may have more precision than atof() will
1940 return, even though value isn't perfectly accurate. */
1941 if ((numtype & (IS_NUMBER_IN_UV
1942 #ifdef NV_PRESERVES_UV
1945 )) == IS_NUMBER_IN_UV) {
1946 /* This won't turn off the public IOK flag if it was set above */
1947 (void)SvIOKp_on(sv);
1949 if (!(numtype & IS_NUMBER_NEG)) {
1951 if (value <= (UV)IV_MAX) {
1952 SvIV_set(sv, (IV)value);
1954 /* it didn't overflow, and it was positive. */
1955 SvUV_set(sv, value);
1959 /* 2s complement assumption */
1960 if (value <= (UV)IV_MIN) {
1961 SvIV_set(sv, -(IV)value);
1963 /* Too negative for an IV. This is a double upgrade, but
1964 I'm assuming it will be rare. */
1965 if (SvTYPE(sv) < SVt_PVNV)
1966 sv_upgrade(sv, SVt_PVNV);
1970 SvNV_set(sv, -(NV)value);
1971 SvIV_set(sv, IV_MIN);
1975 /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
1976 will be in the previous block to set the IV slot, and the next
1977 block to set the NV slot. So no else here. */
1979 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
1980 != IS_NUMBER_IN_UV) {
1981 /* It wasn't an (integer that doesn't overflow the UV). */
1982 SvNV_set(sv, Atof(SvPVX_const(sv)));
1984 if (! numtype && ckWARN(WARN_NUMERIC))
1987 #if defined(USE_LONG_DOUBLE)
1988 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" PERL_PRIgldbl ")\n",
1989 PTR2UV(sv), SvNVX(sv)));
1991 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"NVgf")\n",
1992 PTR2UV(sv), SvNVX(sv)));
1995 #ifdef NV_PRESERVES_UV
1996 (void)SvIOKp_on(sv);
1998 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
1999 SvIV_set(sv, I_V(SvNVX(sv)));
2000 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2003 NOOP; /* Integer is imprecise. NOK, IOKp */
2005 /* UV will not work better than IV */
2007 if (SvNVX(sv) > (NV)UV_MAX) {
2009 /* Integer is inaccurate. NOK, IOKp, is UV */
2010 SvUV_set(sv, UV_MAX);
2012 SvUV_set(sv, U_V(SvNVX(sv)));
2013 /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2014 NV preservse UV so can do correct comparison. */
2015 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2018 NOOP; /* Integer is imprecise. NOK, IOKp, is UV */
2023 #else /* NV_PRESERVES_UV */
2024 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2025 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
2026 /* The IV/UV slot will have been set from value returned by
2027 grok_number above. The NV slot has just been set using
2030 assert (SvIOKp(sv));
2032 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2033 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2034 /* Small enough to preserve all bits. */
2035 (void)SvIOKp_on(sv);
2037 SvIV_set(sv, I_V(SvNVX(sv)));
2038 if ((NV)(SvIVX(sv)) == SvNVX(sv))
2040 /* Assumption: first non-preserved integer is < IV_MAX,
2041 this NV is in the preserved range, therefore: */
2042 if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2044 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);
2048 0 0 already failed to read UV.
2049 0 1 already failed to read UV.
2050 1 0 you won't get here in this case. IV/UV
2051 slot set, public IOK, Atof() unneeded.
2052 1 1 already read UV.
2053 so there's no point in sv_2iuv_non_preserve() attempting
2054 to use atol, strtol, strtoul etc. */
2055 sv_2iuv_non_preserve (sv, numtype);
2058 #endif /* NV_PRESERVES_UV */
2062 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2063 if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2066 if (SvTYPE(sv) < SVt_IV)
2067 /* Typically the caller expects that sv_any is not NULL now. */
2068 sv_upgrade(sv, SVt_IV);
2069 /* Return 0 from the caller. */
2076 =for apidoc sv_2iv_flags
2078 Return the integer value of an SV, doing any necessary string
2079 conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2080 Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2086 Perl_sv_2iv_flags(pTHX_ register SV *sv, I32 flags)
2090 if (SvGMAGICAL(sv) || SvTYPE(sv) == SVt_PVBM) {
2091 /* PVBMs use the same flag bit as SVf_IVisUV, so must let them
2092 cache IVs just in case. In practice it seems that they never
2093 actually anywhere accessible by user Perl code, let alone get used
2094 in anything other than a string context. */
2095 if (flags & SV_GMAGIC)
2100 return I_V(SvNVX(sv));
2102 if (SvPOKp(sv) && SvLEN(sv)) {
2105 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2107 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2108 == IS_NUMBER_IN_UV) {
2109 /* It's definitely an integer */
2110 if (numtype & IS_NUMBER_NEG) {
2111 if (value < (UV)IV_MIN)
2114 if (value < (UV)IV_MAX)
2119 if (ckWARN(WARN_NUMERIC))
2122 return I_V(Atof(SvPVX_const(sv)));
2127 assert(SvTYPE(sv) >= SVt_PVMG);
2128 /* This falls through to the report_uninit inside S_sv_2iuv_common. */
2129 } else if (SvTHINKFIRST(sv)) {
2133 SV * const tmpstr=AMG_CALLun(sv,numer);
2134 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2135 return SvIV(tmpstr);
2138 return PTR2IV(SvRV(sv));
2141 sv_force_normal_flags(sv, 0);
2143 if (SvREADONLY(sv) && !SvOK(sv)) {
2144 if (ckWARN(WARN_UNINITIALIZED))
2150 if (S_sv_2iuv_common(aTHX_ sv))
2153 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2154 PTR2UV(sv),SvIVX(sv)));
2155 return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
2159 =for apidoc sv_2uv_flags
2161 Return the unsigned integer value of an SV, doing any necessary string
2162 conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2163 Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
2169 Perl_sv_2uv_flags(pTHX_ register SV *sv, I32 flags)
2173 if (SvGMAGICAL(sv) || SvTYPE(sv) == SVt_PVBM) {
2174 /* PVBMs use the same flag bit as SVf_IVisUV, so must let them
2175 cache IVs just in case. */
2176 if (flags & SV_GMAGIC)
2181 return U_V(SvNVX(sv));
2182 if (SvPOKp(sv) && SvLEN(sv)) {
2185 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2187 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2188 == IS_NUMBER_IN_UV) {
2189 /* It's definitely an integer */
2190 if (!(numtype & IS_NUMBER_NEG))
2194 if (ckWARN(WARN_NUMERIC))
2197 return U_V(Atof(SvPVX_const(sv)));
2202 assert(SvTYPE(sv) >= SVt_PVMG);
2203 /* This falls through to the report_uninit inside S_sv_2iuv_common. */
2204 } else if (SvTHINKFIRST(sv)) {
2208 SV *const tmpstr = AMG_CALLun(sv,numer);
2209 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2210 return SvUV(tmpstr);
2213 return PTR2UV(SvRV(sv));
2215 if (SvREADONLY(sv) && SvFAKE(sv)) {
2216 sv_force_normal(sv);
2218 if (SvREADONLY(sv) && !SvOK(sv)) {
2219 if (ckWARN(WARN_UNINITIALIZED))
2225 if (S_sv_2iuv_common(aTHX_ sv))
2229 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2230 PTR2UV(sv),SvUVX(sv)));
2231 return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
2237 Return the num value of an SV, doing any necessary string or integer
2238 conversion, magic etc. Normally used via the C<SvNV(sv)> and C<SvNVx(sv)>
2245 Perl_sv_2nv(pTHX_ register SV *sv)
2249 if (SvGMAGICAL(sv) || SvTYPE(sv) == SVt_PVBM) {
2250 /* PVBMs use the same flag bit as SVf_IVisUV, so must let them
2251 cache IVs just in case. */
2255 if (SvPOKp(sv) && SvLEN(sv)) {
2256 if (!SvIOKp(sv) && ckWARN(WARN_NUMERIC) &&
2257 !grok_number(SvPVX_const(sv), SvCUR(sv), NULL))
2259 return Atof(SvPVX_const(sv));
2263 return (NV)SvUVX(sv);
2265 return (NV)SvIVX(sv);
2270 assert(SvTYPE(sv) >= SVt_PVMG);
2271 /* This falls through to the report_uninit near the end of the
2273 } else if (SvTHINKFIRST(sv)) {
2277 SV *const tmpstr = AMG_CALLun(sv,numer);
2278 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2279 return SvNV(tmpstr);
2282 return PTR2NV(SvRV(sv));
2284 if (SvREADONLY(sv) && SvFAKE(sv)) {
2285 sv_force_normal(sv);
2287 if (SvREADONLY(sv) && !SvOK(sv)) {
2288 if (ckWARN(WARN_UNINITIALIZED))
2293 if (SvTYPE(sv) < SVt_NV) {
2294 /* The logic to use SVt_PVNV if necessary is in sv_upgrade. */
2295 sv_upgrade(sv, SVt_NV);
2296 #ifdef USE_LONG_DOUBLE
2298 STORE_NUMERIC_LOCAL_SET_STANDARD();
2299 PerlIO_printf(Perl_debug_log,
2300 "0x%"UVxf" num(%" PERL_PRIgldbl ")\n",
2301 PTR2UV(sv), SvNVX(sv));
2302 RESTORE_NUMERIC_LOCAL();
2306 STORE_NUMERIC_LOCAL_SET_STANDARD();
2307 PerlIO_printf(Perl_debug_log, "0x%"UVxf" num(%"NVgf")\n",
2308 PTR2UV(sv), SvNVX(sv));
2309 RESTORE_NUMERIC_LOCAL();
2313 else if (SvTYPE(sv) < SVt_PVNV)
2314 sv_upgrade(sv, SVt_PVNV);
2319 SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
2320 #ifdef NV_PRESERVES_UV
2323 /* Only set the public NV OK flag if this NV preserves the IV */
2324 /* Check it's not 0xFFFFFFFFFFFFFFFF */
2325 if (SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
2326 : (SvIVX(sv) == I_V(SvNVX(sv))))
2332 else if (SvPOKp(sv) && SvLEN(sv)) {
2334 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2335 if (!SvIOKp(sv) && !numtype && ckWARN(WARN_NUMERIC))
2337 #ifdef NV_PRESERVES_UV
2338 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2339 == IS_NUMBER_IN_UV) {
2340 /* It's definitely an integer */
2341 SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
2343 SvNV_set(sv, Atof(SvPVX_const(sv)));
2346 SvNV_set(sv, Atof(SvPVX_const(sv)));
2347 /* Only set the public NV OK flag if this NV preserves the value in
2348 the PV at least as well as an IV/UV would.
2349 Not sure how to do this 100% reliably. */
2350 /* if that shift count is out of range then Configure's test is
2351 wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2353 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2354 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2355 SvNOK_on(sv); /* Definitely small enough to preserve all bits */
2356 } else if (!(numtype & IS_NUMBER_IN_UV)) {
2357 /* Can't use strtol etc to convert this string, so don't try.
2358 sv_2iv and sv_2uv will use the NV to convert, not the PV. */
2361 /* value has been set. It may not be precise. */
2362 if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2363 /* 2s complement assumption for (UV)IV_MIN */
2364 SvNOK_on(sv); /* Integer is too negative. */
2369 if (numtype & IS_NUMBER_NEG) {
2370 SvIV_set(sv, -(IV)value);
2371 } else if (value <= (UV)IV_MAX) {
2372 SvIV_set(sv, (IV)value);
2374 SvUV_set(sv, value);
2378 if (numtype & IS_NUMBER_NOT_INT) {
2379 /* I believe that even if the original PV had decimals,
2380 they are lost beyond the limit of the FP precision.
2381 However, neither is canonical, so both only get p
2382 flags. NWC, 2000/11/25 */
2383 /* Both already have p flags, so do nothing */
2385 const NV nv = SvNVX(sv);
2386 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2387 if (SvIVX(sv) == I_V(nv)) {
2390 /* It had no "." so it must be integer. */
2394 /* between IV_MAX and NV(UV_MAX).
2395 Could be slightly > UV_MAX */
2397 if (numtype & IS_NUMBER_NOT_INT) {
2398 /* UV and NV both imprecise. */
2400 const UV nv_as_uv = U_V(nv);
2402 if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2411 #endif /* NV_PRESERVES_UV */
2414 if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
2416 assert (SvTYPE(sv) >= SVt_NV);
2417 /* Typically the caller expects that sv_any is not NULL now. */
2418 /* XXX Ilya implies that this is a bug in callers that assume this
2419 and ideally should be fixed. */
2422 #if defined(USE_LONG_DOUBLE)
2424 STORE_NUMERIC_LOCAL_SET_STANDARD();
2425 PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" PERL_PRIgldbl ")\n",
2426 PTR2UV(sv), SvNVX(sv));
2427 RESTORE_NUMERIC_LOCAL();
2431 STORE_NUMERIC_LOCAL_SET_STANDARD();
2432 PerlIO_printf(Perl_debug_log, "0x%"UVxf" 1nv(%"NVgf")\n",
2433 PTR2UV(sv), SvNVX(sv));
2434 RESTORE_NUMERIC_LOCAL();
2440 /* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2441 * UV as a string towards the end of buf, and return pointers to start and
2444 * We assume that buf is at least TYPE_CHARS(UV) long.
2448 S_uiv_2buf(char *buf, IV iv, UV uv, int is_uv, char **peob)
2450 char *ptr = buf + TYPE_CHARS(UV);
2451 char * const ebuf = ptr;
2464 *--ptr = '0' + (char)(uv % 10);
2472 /* stringify_regexp(): private routine for use by sv_2pv_flags(): converts
2473 * a regexp to its stringified form.
2477 S_stringify_regexp(pTHX_ SV *sv, MAGIC *mg, STRLEN *lp) {
2478 const regexp * const re = (regexp *)mg->mg_obj;
2481 const char *fptr = "msix";
2486 bool need_newline = 0;
2487 U16 reganch = (U16)((re->reganch & PMf_COMPILETIME) >> 12);
2489 while((ch = *fptr++)) {
2491 reflags[left++] = ch;
2494 reflags[right--] = ch;
2499 reflags[left] = '-';
2503 mg->mg_len = re->prelen + 4 + left;
2505 * If /x was used, we have to worry about a regex ending with a
2506 * comment later being embedded within another regex. If so, we don't
2507 * want this regex's "commentization" to leak out to the right part of
2508 * the enclosing regex, we must cap it with a newline.
2510 * So, if /x was used, we scan backwards from the end of the regex. If
2511 * we find a '#' before we find a newline, we need to add a newline
2512 * ourself. If we find a '\n' first (or if we don't find '#' or '\n'),
2513 * we don't need to add anything. -jfriedl
2515 if (PMf_EXTENDED & re->reganch) {
2516 const char *endptr = re->precomp + re->prelen;
2517 while (endptr >= re->precomp) {
2518 const char c = *(endptr--);
2520 break; /* don't need another */
2522 /* we end while in a comment, so we need a newline */
2523 mg->mg_len++; /* save space for it */
2524 need_newline = 1; /* note to add it */
2530 Newx(mg->mg_ptr, mg->mg_len + 1 + left, char);
2531 mg->mg_ptr[0] = '(';
2532 mg->mg_ptr[1] = '?';
2533 Copy(reflags, mg->mg_ptr+2, left, char);
2534 *(mg->mg_ptr+left+2) = ':';
2535 Copy(re->precomp, mg->mg_ptr+3+left, re->prelen, char);
2537 mg->mg_ptr[mg->mg_len - 2] = '\n';
2538 mg->mg_ptr[mg->mg_len - 1] = ')';
2539 mg->mg_ptr[mg->mg_len] = 0;
2541 PL_reginterp_cnt += re->program[0].next_off;
2543 if (re->reganch & ROPT_UTF8)
2553 =for apidoc sv_2pv_flags
2555 Returns a pointer to the string value of an SV, and sets *lp to its length.
2556 If flags includes SV_GMAGIC, does an mg_get() first. Coerces sv to a string
2558 Normally invoked via the C<SvPV_flags> macro. C<sv_2pv()> and C<sv_2pv_nomg>
2559 usually end up here too.
2565 Perl_sv_2pv_flags(pTHX_ register SV *sv, STRLEN *lp, I32 flags)
2574 if (SvGMAGICAL(sv)) {
2575 if (flags & SV_GMAGIC)
2580 if (flags & SV_MUTABLE_RETURN)
2581 return SvPVX_mutable(sv);
2582 if (flags & SV_CONST_RETURN)
2583 return (char *)SvPVX_const(sv);
2586 if (SvIOKp(sv) || SvNOKp(sv)) {
2587 char tbuf[64]; /* Must fit sprintf/Gconvert of longest IV/NV */
2592 ? my_snprintf(tbuf, sizeof(tbuf), "%"UVuf, (UV)SvUVX(sv))
2593 : my_snprintf(tbuf, sizeof(tbuf), "%"IVdf, (IV)SvIVX(sv));
2595 Gconvert(SvNVX(sv), NV_DIG, 0, tbuf);
2601 #ifdef FIXNEGATIVEZERO
2602 if (len == 2 && tbuf[0] == '-' && tbuf[1] == '0') {
2608 SvUPGRADE(sv, SVt_PV);
2611 s = SvGROW_mutable(sv, len + 1);
2614 return (char*)memcpy(s, tbuf, len + 1);
2620 assert(SvTYPE(sv) >= SVt_PVMG);
2621 /* This falls through to the report_uninit near the end of the
2623 } else if (SvTHINKFIRST(sv)) {
2627 SV *const tmpstr = AMG_CALLun(sv,string);
2628 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2630 /* char *pv = lp ? SvPV(tmpstr, *lp) : SvPV_nolen(tmpstr);
2634 if ((SvFLAGS(tmpstr) & (SVf_POK)) == SVf_POK) {
2635 if (flags & SV_CONST_RETURN) {
2636 pv = (char *) SvPVX_const(tmpstr);
2638 pv = (flags & SV_MUTABLE_RETURN)
2639 ? SvPVX_mutable(tmpstr) : SvPVX(tmpstr);
2642 *lp = SvCUR(tmpstr);
2644 pv = sv_2pv_flags(tmpstr, lp, flags);
2658 const SV *const referent = (SV*)SvRV(sv);
2662 retval = buffer = savepvn("NULLREF", len);
2663 } else if (SvTYPE(referent) == SVt_PVMG
2664 && ((SvFLAGS(referent) &
2665 (SVs_OBJECT|SVf_OK|SVs_GMG|SVs_SMG|SVs_RMG))
2666 == (SVs_OBJECT|SVs_SMG))
2667 && (mg = mg_find((SV *) referent, PERL_MAGIC_qr))) {
2668 return stringify_regexp(sv, mg, lp);
2670 const char *const typestr = sv_reftype((SV *) referent, 0);
2671 const STRLEN typelen = strlen(typestr);
2672 UV addr = PTR2UV(referent);
2673 const char *stashname = NULL;
2674 STRLEN stashnamelen = 0; /* hush, gcc */
2675 const char *buffer_end;
2677 if (SvOBJECT(referent)) {
2678 stashname = HvNAME_get(SvSTASH(referent));
2681 stashnamelen = strlen(stashname);
2684 stashname = "__ANON__";
2687 len = stashnamelen + 1 /* = */ + typelen + 3 /* (0x */
2688 + 2 * sizeof(UV) + 2 /* )\0 */;
2690 len = typelen + 3 /* (0x */
2691 + 2 * sizeof(UV) + 2 /* )\0 */;
2694 Newx(buffer, len, char);
2695 buffer_end = retval = buffer + len;
2697 /* Working backwards */
2701 *--retval = PL_hexdigit[addr & 15];
2702 } while (addr >>= 4);
2708 memcpy(retval, typestr, typelen);
2712 retval -= stashnamelen;
2713 memcpy(retval, stashname, stashnamelen);
2715 /* retval may not neccesarily have reached the start of the
2717 assert (retval >= buffer);
2719 len = buffer_end - retval - 1; /* -1 for that \0 */
2727 if (SvREADONLY(sv) && !SvOK(sv)) {
2728 if (ckWARN(WARN_UNINITIALIZED))
2735 if (SvIOK(sv) || ((SvIOKp(sv) && !SvNOKp(sv)))) {
2736 /* I'm assuming that if both IV and NV are equally valid then
2737 converting the IV is going to be more efficient */
2738 const U32 isUIOK = SvIsUV(sv);
2739 char buf[TYPE_CHARS(UV)];
2742 if (SvTYPE(sv) < SVt_PVIV)
2743 sv_upgrade(sv, SVt_PVIV);
2744 ptr = uiv_2buf(buf, SvIVX(sv), SvUVX(sv), isUIOK, &ebuf);
2745 /* inlined from sv_setpvn */
2746 SvGROW_mutable(sv, (STRLEN)(ebuf - ptr + 1));
2747 Move(ptr,SvPVX_mutable(sv),ebuf - ptr,char);
2748 SvCUR_set(sv, ebuf - ptr);
2752 else if (SvNOKp(sv)) {
2753 const int olderrno = errno;
2754 if (SvTYPE(sv) < SVt_PVNV)
2755 sv_upgrade(sv, SVt_PVNV);
2756 /* The +20 is pure guesswork. Configure test needed. --jhi */
2757 s = SvGROW_mutable(sv, NV_DIG + 20);
2758 /* some Xenix systems wipe out errno here */
2760 if (SvNVX(sv) == 0.0)
2761 my_strlcpy(s, "0", SvLEN(sv));
2765 Gconvert(SvNVX(sv), NV_DIG, 0, s);
2768 #ifdef FIXNEGATIVEZERO
2769 if (*s == '-' && s[1] == '0' && !s[2])
2770 my_strlcpy(s, "0", SvLEN(s));
2779 if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
2783 if (SvTYPE(sv) < SVt_PV)
2784 /* Typically the caller expects that sv_any is not NULL now. */
2785 sv_upgrade(sv, SVt_PV);
2789 const STRLEN len = s - SvPVX_const(sv);
2795 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
2796 PTR2UV(sv),SvPVX_const(sv)));
2797 if (flags & SV_CONST_RETURN)
2798 return (char *)SvPVX_const(sv);
2799 if (flags & SV_MUTABLE_RETURN)
2800 return SvPVX_mutable(sv);
2805 =for apidoc sv_copypv
2807 Copies a stringified representation of the source SV into the
2808 destination SV. Automatically performs any necessary mg_get and
2809 coercion of numeric values into strings. Guaranteed to preserve
2810 UTF-8 flag even from overloaded objects. Similar in nature to
2811 sv_2pv[_flags] but operates directly on an SV instead of just the
2812 string. Mostly uses sv_2pv_flags to do its work, except when that
2813 would lose the UTF-8'ness of the PV.
2819 Perl_sv_copypv(pTHX_ SV *dsv, register SV *ssv)
2822 const char * const s = SvPV_const(ssv,len);
2823 sv_setpvn(dsv,s,len);
2831 =for apidoc sv_2pvbyte
2833 Return a pointer to the byte-encoded representation of the SV, and set *lp
2834 to its length. May cause the SV to be downgraded from UTF-8 as a
2837 Usually accessed via the C<SvPVbyte> macro.
2843 Perl_sv_2pvbyte(pTHX_ register SV *sv, STRLEN *lp)
2845 sv_utf8_downgrade(sv,0);
2846 return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
2850 =for apidoc sv_2pvutf8
2852 Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
2853 to its length. May cause the SV to be upgraded to UTF-8 as a side-effect.
2855 Usually accessed via the C<SvPVutf8> macro.
2861 Perl_sv_2pvutf8(pTHX_ register SV *sv, STRLEN *lp)
2863 sv_utf8_upgrade(sv);
2864 return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
2869 =for apidoc sv_2bool
2871 This function is only called on magical items, and is only used by
2872 sv_true() or its macro equivalent.
2878 Perl_sv_2bool(pTHX_ register SV *sv)
2886 SV * const tmpsv = AMG_CALLun(sv,bool_);
2887 if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
2888 return (bool)SvTRUE(tmpsv);
2890 return SvRV(sv) != 0;
2893 register XPV* const Xpvtmp = (XPV*)SvANY(sv);
2895 (*Xpvtmp->xpv_pv > '0' ||
2896 Xpvtmp->xpv_cur > 1 ||
2897 (Xpvtmp->xpv_cur && *Xpvtmp->xpv_pv != '0')))
2904 return SvIVX(sv) != 0;
2907 return SvNVX(sv) != 0.0;
2915 =for apidoc sv_utf8_upgrade
2917 Converts the PV of an SV to its UTF-8-encoded form.
2918 Forces the SV to string form if it is not already.
2919 Always sets the SvUTF8 flag to avoid future validity checks even
2920 if all the bytes have hibit clear.
2922 This is not as a general purpose byte encoding to Unicode interface:
2923 use the Encode extension for that.
2925 =for apidoc sv_utf8_upgrade_flags
2927 Converts the PV of an SV to its UTF-8-encoded form.
2928 Forces the SV to string form if it is not already.
2929 Always sets the SvUTF8 flag to avoid future validity checks even
2930 if all the bytes have hibit clear. If C<flags> has C<SV_GMAGIC> bit set,
2931 will C<mg_get> on C<sv> if appropriate, else not. C<sv_utf8_upgrade> and
2932 C<sv_utf8_upgrade_nomg> are implemented in terms of this function.
2934 This is not as a general purpose byte encoding to Unicode interface:
2935 use the Encode extension for that.
2941 Perl_sv_utf8_upgrade_flags(pTHX_ register SV *sv, I32 flags)
2943 if (sv == &PL_sv_undef)
2947 if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
2948 (void) sv_2pv_flags(sv,&len, flags);
2952 (void) SvPV_force(sv,len);
2960 if (SvREADONLY(sv) && SvFAKE(sv)) {
2961 sv_force_normal(sv);
2964 if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING))
2965 sv_recode_to_utf8(sv, PL_encoding);
2966 else { /* Assume Latin-1/EBCDIC */
2967 /* This function could be much more efficient if we
2968 * had a FLAG in SVs to signal if there are any hibit
2969 * chars in the PV. Given that there isn't such a flag
2970 * make the loop as fast as possible. */
2971 const U8 * const s = (U8 *) SvPVX_const(sv);
2972 const U8 * const e = (U8 *) SvEND(sv);
2977 /* Check for hi bit */
2978 if (!NATIVE_IS_INVARIANT(ch)) {
2979 STRLEN len = SvCUR(sv) + 1; /* Plus the \0 */
2980 U8 * const recoded = bytes_to_utf8((U8*)s, &len);
2982 SvPV_free(sv); /* No longer using what was there before. */
2983 SvPV_set(sv, (char*)recoded);
2984 SvCUR_set(sv, len - 1);
2985 SvLEN_set(sv, len); /* No longer know the real size. */
2989 /* Mark as UTF-8 even if no hibit - saves scanning loop */
2996 =for apidoc sv_utf8_downgrade
2998 Attempts to convert the PV of an SV from characters to bytes.
2999 If the PV contains a character beyond byte, this conversion will fail;
3000 in this case, either returns false or, if C<fail_ok> is not
3003 This is not as a general purpose Unicode to byte encoding interface:
3004 use the Encode extension for that.
3010 Perl_sv_utf8_downgrade(pTHX_ register SV* sv, bool fail_ok)
3012 if (SvPOKp(sv) && SvUTF8(sv)) {
3017 if (SvREADONLY(sv) && SvFAKE(sv))
3018 sv_force_normal(sv);
3019 s = (U8 *) SvPV(sv, len);
3020 if (!utf8_to_bytes(s, &len)) {
3025 Perl_croak(aTHX_ "Wide character in %s",
3028 Perl_croak(aTHX_ "Wide character");
3039 =for apidoc sv_utf8_encode
3041 Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3042 flag off so that it looks like octets again.
3048 Perl_sv_utf8_encode(pTHX_ register SV *sv)
3051 sv_force_normal_flags(sv, 0);
3053 if (SvREADONLY(sv)) {
3054 Perl_croak(aTHX_ PL_no_modify);
3056 (void) sv_utf8_upgrade(sv);
3061 =for apidoc sv_utf8_decode
3063 If the PV of the SV is an octet sequence in UTF-8
3064 and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3065 so that it looks like a character. If the PV contains only single-byte
3066 characters, the C<SvUTF8> flag stays being off.
3067 Scans PV for validity and returns false if the PV is invalid UTF-8.
3073 Perl_sv_utf8_decode(pTHX_ register SV *sv)
3079 /* The octets may have got themselves encoded - get them back as
3082 if (!sv_utf8_downgrade(sv, TRUE))
3085 /* it is actually just a matter of turning the utf8 flag on, but
3086 * we want to make sure everything inside is valid utf8 first.
3088 c = (const U8 *) SvPVX_const(sv);
3089 if (!is_utf8_string((U8 *)c, SvCUR(sv)+1))
3091 e = (const U8 *) SvEND(sv);
3094 if (!UTF8_IS_INVARIANT(ch)) {
3104 =for apidoc sv_setsv
3106 Copies the contents of the source SV C<ssv> into the destination SV
3107 C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3108 function if the source SV needs to be reused. Does not handle 'set' magic.
3109 Loosely speaking, it performs a copy-by-value, obliterating any previous
3110 content of the destination.
3112 You probably want to use one of the assortment of wrappers, such as
3113 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3114 C<SvSetMagicSV_nosteal>.
3116 =for apidoc sv_setsv_flags
3118 Copies the contents of the source SV C<ssv> into the destination SV
3119 C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3120 function if the source SV needs to be reused. Does not handle 'set' magic.
3121 Loosely speaking, it performs a copy-by-value, obliterating any previous
3122 content of the destination.
3123 If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
3124 C<ssv> if appropriate, else not. If the C<flags> parameter has the
3125 C<NOSTEAL> bit set then the buffers of temps will not be stolen. <sv_setsv>
3126 and C<sv_setsv_nomg> are implemented in terms of this function.
3128 You probably want to use one of the assortment of wrappers, such as
3129 C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3130 C<SvSetMagicSV_nosteal>.
3132 This is the primary function for copying scalars, and most other
3133 copy-ish functions and macros use this underneath.
3139 S_glob_assign_glob(pTHX_ SV *dstr, SV *sstr, const int dtype)
3141 if (dtype != SVt_PVGV) {
3142 const char * const name = GvNAME(sstr);
3143 const STRLEN len = GvNAMELEN(sstr);
3144 sv_upgrade(dstr, SVt_PVGV);
3145 sv_magic(dstr, dstr, PERL_MAGIC_glob, Nullch, 0);
3146 GvSTASH(dstr) = (HV*)SvREFCNT_inc(GvSTASH(sstr));
3147 gv_name_set((GV *)dstr, name, len, GV_ADD);
3148 SvFAKE_on(dstr); /* can coerce to non-glob */
3151 #ifdef GV_UNIQUE_CHECK
3152 if (GvUNIQUE((GV*)dstr)) {
3153 Perl_croak(aTHX_ PL_no_modify);
3157 (void)SvOK_off(dstr);
3158 GvINTRO_off(dstr); /* one-shot flag */
3160 GvGP(dstr) = gp_ref(GvGP(sstr));
3161 if (SvTAINTED(sstr))
3163 if (GvIMPORTED(dstr) != GVf_IMPORTED
3164 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3166 GvIMPORTED_on(dstr);
3173 S_glob_assign_ref(pTHX_ SV *dstr, SV *sstr) {
3174 SV * const sref = SvREFCNT_inc(SvRV(sstr));
3176 const int intro = GvINTRO(dstr);
3179 const U32 stype = SvTYPE(sref);
3182 #ifdef GV_UNIQUE_CHECK
3183 if (GvUNIQUE((GV*)dstr)) {
3184 Perl_croak(aTHX_ PL_no_modify);
3189 GvINTRO_off(dstr); /* one-shot flag */
3190 GvLINE(dstr) = CopLINE(PL_curcop);
3191 GvEGV(dstr) = (GV*)dstr;
3196 location = (SV **) &GvCV(dstr);
3197 import_flag = GVf_IMPORTED_CV;
3200 location = (SV **) &GvHV(dstr);
3201 import_flag = GVf_IMPORTED_HV;
3204 location = (SV **) &GvAV(dstr);
3205 import_flag = GVf_IMPORTED_AV;
3208 location = (SV **) &GvIOp(dstr);
3211 location = (SV **) &GvFORM(dstr);
3213 location = &GvSV(dstr);
3214 import_flag = GVf_IMPORTED_SV;
3217 if (stype == SVt_PVCV) {
3218 if (GvCVGEN(dstr) && GvCV(dstr) != (CV*)sref) {
3219 SvREFCNT_dec(GvCV(dstr));
3221 GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3222 PL_sub_generation++;
3225 SAVEGENERICSV(*location);
3229 if (stype == SVt_PVCV && *location != sref) {
3230 CV* const cv = (CV*)*location;
3232 if (!GvCVGEN((GV*)dstr) &&
3233 (CvROOT(cv) || CvXSUB(cv)))
3235 /* Redefining a sub - warning is mandatory if
3236 it was a const and its value changed. */
3237 if (CvCONST(cv) && CvCONST((CV*)sref)
3238 && cv_const_sv(cv) == cv_const_sv((CV*)sref)) {
3240 /* They are 2 constant subroutines generated from
3241 the same constant. This probably means that
3242 they are really the "same" proxy subroutine
3243 instantiated in 2 places. Most likely this is
3244 when a constant is exported twice. Don't warn.
3247 else if (ckWARN(WARN_REDEFINE)
3249 && (!CvCONST((CV*)sref)
3250 || sv_cmp(cv_const_sv(cv),
3251 cv_const_sv((CV*)sref))))) {
3252 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
3255 ? "Constant subroutine %s::%s redefined"
3256 : "Subroutine %s::%s redefined"),
3257 HvNAME_get(GvSTASH((GV*)dstr)),
3258 GvENAME((GV*)dstr));
3262 cv_ckproto_len(cv, (GV*)dstr,
3264 ? (char *) SvPVX_const(sref) : NULL,
3265 SvPOK(sref) ? SvCUR(sref) : 0);
3267 GvCVGEN(dstr) = 0; /* Switch off cacheness. */
3268 GvASSUMECV_on(dstr);
3269 PL_sub_generation++;
3272 if (import_flag && !(GvFLAGS(dstr) & import_flag)
3273 && CopSTASH_ne(PL_curcop, GvSTASH(dstr))) {
3274 GvFLAGS(dstr) |= import_flag;
3280 if (SvTAINTED(sstr))
3286 Perl_sv_setsv_flags(pTHX_ SV *dstr, register SV *sstr, I32 flags)
3288 register U32 sflags;
3290 register svtype stype;
3295 if (SvIS_FREED(dstr)) {
3296 Perl_croak(aTHX_ "panic: attempt to copy value %" SVf
3297 " to a freed scalar %p", sstr, dstr);
3299 SV_CHECK_THINKFIRST(dstr);
3301 sstr = &PL_sv_undef;
3302 if (SvIS_FREED(sstr)) {
3303 Perl_croak(aTHX_ "panic: attempt to copy freed scalar %p to %p", sstr,
3306 stype = SvTYPE(sstr);
3307 dtype = SvTYPE(dstr);
3312 /* need to nuke the magic */
3314 SvRMAGICAL_off(dstr);
3317 /* There's a lot of redundancy below but we're going for speed here */
3322 if (dtype != SVt_PVGV) {
3323 (void)SvOK_off(dstr);
3331 sv_upgrade(dstr, SVt_IV);
3336 sv_upgrade(dstr, SVt_PVIV);
3339 (void)SvIOK_only(dstr);
3340 SvIV_set(dstr, SvIVX(sstr));
3343 /* SvTAINTED can only be true if the SV has taint magic, which in
3344 turn means that the SV type is PVMG (or greater). This is the
3345 case statement for SVt_IV, so this cannot be true (whatever gcov
3356 sv_upgrade(dstr, SVt_NV);
3361 sv_upgrade(dstr, SVt_PVNV);
3364 SvNV_set(dstr, SvNVX(sstr));
3365 (void)SvNOK_only(dstr);
3366 /* SvTAINTED can only be true if the SV has taint magic, which in
3367 turn means that the SV type is PVMG (or greater). This is the
3368 case statement for SVt_NV, so this cannot be true (whatever gcov
3376 sv_upgrade(dstr, SVt_RV);
3381 sv_upgrade(dstr, SVt_PV);
3384 if (dtype < SVt_PVIV)
3385 sv_upgrade(dstr, SVt_PVIV);
3388 if (dtype < SVt_PVNV)
3389 sv_upgrade(dstr, SVt_PVNV);
3393 const char * const type = sv_reftype(sstr,0);
3395 Perl_croak(aTHX_ "Bizarre copy of %s in %s", type, OP_NAME(PL_op));
3397 Perl_croak(aTHX_ "Bizarre copy of %s", type);
3402 if (dtype <= SVt_PVGV) {
3403 glob_assign_glob(dstr, sstr, dtype);
3411 if (SvGMAGICAL(sstr) && (flags & SV_GMAGIC)) {
3413 if (SvTYPE(sstr) != stype) {
3414 stype = SvTYPE(sstr);
3415 if (stype == SVt_PVGV && dtype <= SVt_PVGV) {
3416 glob_assign_glob(dstr, sstr, dtype);
3421 if (stype == SVt_PVLV)
3422 (void)SvUPGRADE(dstr, SVt_PVNV);
3424 (void)SvUPGRADE(dstr, (U32)stype);
3427 /* dstr may have been upgraded. */
3428 dtype = SvTYPE(dstr);
3429 sflags = SvFLAGS(sstr);
3431 if (sflags & SVf_ROK) {
3432 if (dtype == SVt_PVGV && SvTYPE(SvRV(sstr)) == SVt_PVGV) {
3435 if (GvIMPORTED(dstr) != GVf_IMPORTED
3436 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3438 GvIMPORTED_on(dstr);
3443 glob_assign_glob(dstr, sstr, dtype);
3447 if (dtype >= SVt_PV) {
3448 if (dtype == SVt_PVGV) {
3449 glob_assign_ref(dstr, sstr);
3452 if (SvPVX_const(dstr)) {
3458 (void)SvOK_off(dstr);
3459 SvRV_set(dstr, SvREFCNT_inc(SvRV(sstr)));
3460 SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_NOK|SVp_NOK|SVf_ROK
3462 if (sflags & SVp_NOK) {
3463 SvNV_set(dstr, SvNVX(sstr));
3465 if (sflags & SVp_IOK) {
3466 /* Must do this otherwise some other overloaded use of 0x80000000
3467 gets confused. Probably SVprv_WEAKREF */
3468 if (sflags & SVf_IVisUV)
3470 SvIV_set(dstr, SvIVX(sstr));
3473 else if (sflags & SVp_POK) {
3476 * Check to see if we can just swipe the string. If so, it's a
3477 * possible small lose on short strings, but a big win on long ones.
3478 * It might even be a win on short strings if SvPVX_const(dstr)
3479 * has to be allocated and SvPVX_const(sstr) has to be freed.
3482 if (SvTEMP(sstr) && /* slated for free anyway? */
3483 SvREFCNT(sstr) == 1 && /* and no other references to it? */
3484 (!(flags & SV_NOSTEAL)) && /* and we're allowed to steal temps */
3485 !(sflags & SVf_OOK) && /* and not involved in OOK hack? */
3486 SvLEN(sstr) && /* and really is a string */
3487 /* and won't be needed again, potentially */
3488 !(PL_op && PL_op->op_type == OP_AASSIGN))
3490 if (SvPVX_const(dstr)) { /* we know that dtype >= SVt_PV */
3493 (void)SvPOK_only(dstr);
3494 SvPV_set(dstr, SvPVX(sstr));
3495 SvLEN_set(dstr, SvLEN(sstr));
3496 SvCUR_set(dstr, SvCUR(sstr));
3499 (void)SvOK_off(sstr); /* NOTE: nukes most SvFLAGS on sstr */
3500 SvPV_set(sstr, NULL);
3505 else { /* have to copy actual string */
3506 STRLEN len = SvCUR(sstr);
3507 SvGROW(dstr, len + 1); /* inlined from sv_setpvn */
3508 Move(SvPVX_const(sstr),SvPVX(dstr),len,char);
3509 SvCUR_set(dstr, len);
3510 *SvEND(dstr) = '\0';
3511 (void)SvPOK_only(dstr);
3513 if (sflags & SVp_NOK) {
3514 SvNV_set(dstr, SvNVX(sstr));
3516 if (sflags & SVp_IOK) {
3518 SvIV_set(dstr, SvIVX(sstr));
3519 /* Must do this otherwise some other overloaded use of 0x80000000
3520 gets confused. I guess SVpbm_VALID */
3521 if (sflags & SVf_IVisUV)
3524 SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_NOK|SVp_NOK|SVf_UTF8);
3526 const MAGIC * const smg = SvVSTRING_mg(sstr);
3528 sv_magic(dstr, NULL, PERL_MAGIC_vstring,
3529 smg->mg_ptr, smg->mg_len);
3530 SvRMAGICAL_on(dstr);
3534 else if (sflags & (SVp_IOK|SVp_NOK)) {
3535 (void)SvOK_off(dstr);
3536 SvFLAGS(dstr) |= sflags & (SVf_IOK|SVp_IOK|SVf_IVisUV|SVf_NOK|SVp_NOK);
3537 if (sflags & SVp_IOK) {
3538 /* XXXX Do we want to set IsUV for IV(ROK)? Be extra safe... */
3539 SvIV_set(dstr, SvIVX(sstr));
3541 if (sflags & SVp_NOK) {
3542 SvNV_set(dstr, SvNVX(sstr));
3546 if (dtype == SVt_PVGV) {
3547 if (ckWARN(WARN_MISC))
3548 Perl_warner(aTHX_ packWARN(WARN_MISC), "Undefined value assigned to typeglob");
3551 (void)SvOK_off(dstr);
3553 if (SvTAINTED(sstr))
3558 =for apidoc sv_setsv_mg
3560 Like C<sv_setsv>, but also handles 'set' magic.
3566 Perl_sv_setsv_mg(pTHX_ SV *dstr, register SV *sstr)
3568 sv_setsv(dstr,sstr);
3573 =for apidoc sv_setpvn
3575 Copies a string into an SV. The C<len> parameter indicates the number of
3576 bytes to be copied. If the C<ptr> argument is NULL the SV will become
3577 undefined. Does not handle 'set' magic. See C<sv_setpvn_mg>.
3583 Perl_sv_setpvn(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
3585 register char *dptr;
3587 SV_CHECK_THINKFIRST(sv);
3593 /* len is STRLEN which is unsigned, need to copy to signed */
3596 Perl_croak(aTHX_ "panic: sv_setpvn called with negative strlen");
3598 (void)SvUPGRADE(sv, SVt_PV);
3600 dptr = SvGROW(sv, len + 1);
3601 Move(ptr,dptr,len,char);
3604 (void)SvPOK_only_UTF8(sv); /* validate pointer */
3609 =for apidoc sv_setpvn_mg
3611 Like C<sv_setpvn>, but also handles 'set' magic.
3617 Perl_sv_setpvn_mg(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
3619 sv_setpvn(sv,ptr,len);
3624 =for apidoc sv_setpv
3626 Copies a string into an SV. The string must be null-terminated. Does not
3627 handle 'set' magic. See C<sv_setpv_mg>.
3633 Perl_sv_setpv(pTHX_ register SV *sv, register const char *ptr)
3635 register STRLEN len;
3637 SV_CHECK_THINKFIRST(sv);
3643 (void)SvUPGRADE(sv, SVt_PV);
3645 SvGROW(sv, len + 1);
3646 Move(ptr,SvPVX(sv),len+1,char);
3648 (void)SvPOK_only_UTF8(sv); /* validate pointer */
3653 =for apidoc sv_setpv_mg
3655 Like C<sv_setpv>, but also handles 'set' magic.
3661 Perl_sv_setpv_mg(pTHX_ register SV *sv, register const char *ptr)
3668 =for apidoc sv_usepvn_flags
3670 Tells an SV to use C<ptr> to find its string value. Normally the
3671 string is stored inside the SV but sv_usepvn allows the SV to use an
3672 outside string. The C<ptr> should point to memory that was allocated
3673 by C<malloc>. The string length, C<len>, must be supplied. By default
3674 this function will realloc (i.e. move) the memory pointed to by C<ptr>,
3675 so that pointer should not be freed or used by the programmer after
3676 giving it to sv_usepvn, and neither should any pointers from "behind"
3677 that pointer (e.g. ptr + 1) be used.
3679 If C<flags> & SV_SMAGIC is true, will call SvSETMAGIC. If C<flags> &
3680 SV_HAS_TRAILING_NUL is true, then C<ptr[len]> must be NUL, and the realloc
3681 will be skipped. (i.e. the buffer is actually at least 1 byte longer than
3682 C<len>, and already meets the requirements for storing in C<SvPVX>)
3688 Perl_sv_usepvn_flags(pTHX_ SV *sv, char *ptr, STRLEN len, U32 flags)
3691 SV_CHECK_THINKFIRST(sv);
3692 (void)SvUPGRADE(sv, SVt_PV);
3695 if (flags & SV_SMAGIC)
3699 if (SvPVX_const(sv))
3703 if (flags & SV_HAS_TRAILING_NUL)
3704 assert(ptr[len] == '\0');
3707 allocate = (flags & SV_HAS_TRAILING_NUL)
3708 ? len + 1: PERL_STRLEN_ROUNDUP(len + 1);
3709 if (flags & SV_HAS_TRAILING_NUL) {
3710 /* It's long enough - do nothing.
3711 Specfically Perl_newCONSTSUB is relying on this. */
3713 ptr = (char*) saferealloc (ptr, allocate);
3717 SvLEN_set(sv, allocate);
3718 if (!(flags & SV_HAS_TRAILING_NUL)) {
3721 (void)SvPOK_only_UTF8(sv); /* validate pointer */
3723 if (flags & SV_SMAGIC)
3728 =for apidoc sv_force_normal_flags
3730 Undo various types of fakery on an SV: if the PV is a shared string, make
3731 a private copy; if we're a ref, stop refing; if we're a glob, downgrade to
3732 an xpvmg. The C<flags> parameter gets passed to C<sv_unref_flags()>
3733 when unrefing. C<sv_force_normal> calls this function with flags set to 0.
3739 Perl_sv_force_normal_flags(pTHX_ register SV *sv, U32 flags)
3741 if (SvREADONLY(sv)) {
3743 const char * const pvx = SvPVX_const(sv);
3744 const STRLEN len = SvCUR(sv);
3745 const U32 hash = SvSHARED_HASH(sv);
3748 SvGROW(sv, len + 1);
3749 Move(pvx,SvPVX(sv),len,char);
3751 unsharepvn(pvx, SvUTF8(sv) ? -(I32)len : len, hash);
3753 else if (IN_PERL_RUNTIME)
3754 Perl_croak(aTHX_ PL_no_modify);
3757 sv_unref_flags(sv, flags);
3758 else if (SvFAKE(sv) && SvTYPE(sv) == SVt_PVGV)
3765 Efficient removal of characters from the beginning of the string buffer.
3766 SvPOK(sv) must be true and the C<ptr> must be a pointer to somewhere inside
3767 the string buffer. The C<ptr> becomes the first character of the adjusted
3768 string. Uses the "OOK hack".
3769 Beware: after this function returns, C<ptr> and SvPVX_const(sv) may no longer
3770 refer to the same chunk of data.
3776 Perl_sv_chop(pTHX_ register SV *sv, register char *ptr)
3778 register STRLEN delta;
3779 if (!ptr || !SvPOKp(sv))
3781 delta = ptr - SvPVX_const(sv);
3782 SV_CHECK_THINKFIRST(sv);
3783 if (SvTYPE(sv) < SVt_PVIV)
3784 sv_upgrade(sv,SVt_PVIV);
3787 if (!SvLEN(sv)) { /* make copy of shared string */
3788 const char *pvx = SvPVX_const(sv);
3789 const STRLEN len = SvCUR(sv);
3790 SvGROW(sv, len + 1);
3791 Move(pvx,SvPVX(sv),len,char);
3795 /* Same SvOOK_on but SvOOK_on does a SvIOK_off
3796 and we do that anyway inside the SvNIOK_off
3798 SvFLAGS(sv) |= SVf_OOK;
3801 SvLEN_set(sv, SvLEN(sv) - delta);
3802 SvCUR_set(sv, SvCUR(sv) - delta);
3803 SvPV_set(sv, SvPVX(sv) + delta);
3804 SvIV_set(sv, SvIVX(sv) + delta);
3808 =for apidoc sv_catpvn
3810 Concatenates the string onto the end of the string which is in the SV. The
3811 C<len> indicates number of bytes to copy. If the SV has the UTF-8
3812 status set, then the bytes appended should be valid UTF-8.
3813 Handles 'get' magic, but not 'set' magic. See C<sv_catpvn_mg>.
3815 =for apidoc sv_catpvn_flags
3817 Concatenates the string onto the end of the string which is in the SV. The
3818 C<len> indicates number of bytes to copy. If the SV has the UTF-8
3819 status set, then the bytes appended should be valid UTF-8.
3820 If C<flags> has C<SV_GMAGIC> bit set, will C<mg_get> on C<dsv> if
3821 appropriate, else not. C<sv_catpvn> and C<sv_catpvn_nomg> are implemented
3822 in terms of this function.
3828 Perl_sv_catpvn_flags(pTHX_ register SV *dsv, register const char *sstr, register STRLEN slen, I32 flags)
3831 const char * const dstr = SvPV_force_flags(dsv, dlen, flags);
3833 SvGROW(dsv, dlen + slen + 1);
3835 sstr = SvPVX_const(dsv);
3836 Move(sstr, SvPVX(dsv) + dlen, slen, char);
3837 SvCUR_set(dsv, SvCUR(dsv) + slen);
3839 (void)SvPOK_only_UTF8(dsv); /* validate pointer */
3841 if (flags & SV_SMAGIC)
3846 =for apidoc sv_catsv
3848 Concatenates the string from SV C<ssv> onto the end of the string in
3849 SV C<dsv>. Modifies C<dsv> but not C<ssv>. Handles 'get' magic, but
3850 not 'set' magic. See C<sv_catsv_mg>.
3852 =for apidoc sv_catsv_flags
3854 Concatenates the string from SV C<ssv> onto the end of the string in
3855 SV C<dsv>. Modifies C<dsv> but not C<ssv>. If C<flags> has C<SV_GMAGIC>
3856 bit set, will C<mg_get> on the SVs if appropriate, else not. C<sv_catsv>
3857 and C<sv_catsv_nomg> are implemented in terms of this function.
3862 Perl_sv_catsv_flags(pTHX_ SV *dsv, register SV *ssv, I32 flags)
3866 const char *spv = SvPV_const(ssv, slen);
3868 /* sutf8 and dutf8 were type bool, but under USE_ITHREADS,
3869 gcc version 2.95.2 20000220 (Debian GNU/Linux) for
3870 Linux xxx 2.2.17 on sparc64 with gcc -O2, we erroneously
3871 get dutf8 = 0x20000000, (i.e. SVf_UTF8) even though
3872 dsv->sv_flags doesn't have that bit set.
3873 Andy Dougherty 12 Oct 2001
3875 const I32 sutf8 = DO_UTF8(ssv);
3878 if (SvGMAGICAL(dsv) && (flags & SV_GMAGIC))
3880 dutf8 = DO_UTF8(dsv);
3882 if (dutf8 != sutf8) {
3884 /* Not modifying source SV, so taking a temporary copy. */
3885 SV* const csv = sv_2mortal(newSVpvn(spv, slen));
3887 sv_utf8_upgrade(csv);
3888 spv = SvPV_const(csv, slen);
3891 sv_utf8_upgrade_nomg(dsv);
3893 sv_catpvn_nomg(dsv, spv, slen);
3896 if (flags & SV_SMAGIC)
3901 =for apidoc sv_catpv
3903 Concatenates the string onto the end of the string which is in the SV.
3904 If the SV has the UTF-8 status set, then the bytes appended should be
3905 valid UTF-8. Handles 'get' magic, but not 'set' magic. See C<sv_catpv_mg>.
3910 Perl_sv_catpv(pTHX_ register SV *sv, register const char *ptr)
3912 register STRLEN len;
3918 junk = SvPV_force(sv, tlen);
3920 SvGROW(sv, tlen + len + 1);
3922 ptr = SvPVX_const(sv);
3923 Move(ptr,SvPVX(sv)+tlen,len+1,char);
3924 SvCUR_set(sv, SvCUR(sv) + len);
3925 (void)SvPOK_only_UTF8(sv); /* validate pointer */
3930 =for apidoc sv_catpv_mg
3932 Like C<sv_catpv>, but also handles 'set' magic.
3938 Perl_sv_catpv_mg(pTHX_ register SV *sv, register const char *ptr)
3947 Creates a new SV. A non-zero C<len> parameter indicates the number of
3948 bytes of preallocated string space the SV should have. An extra byte for a
3949 trailing NUL is also reserved. (SvPOK is not set for the SV even if string
3950 space is allocated.) The reference count for the new SV is set to 1.
3952 In 5.9.3, newSV() replaces the older NEWSV() API, and drops the first
3953 parameter, I<x>, a debug aid which allowed callers to identify themselves.
3954 This aid has been superseded by a new build option, PERL_MEM_LOG (see
3955 L<perlhack/PERL_MEM_LOG>). The older API is still there for use in XS
3956 modules supporting older perls.
3962 Perl_newSV(pTHX_ STRLEN len)
3968 sv_upgrade(sv, SVt_PV);
3969 SvGROW(sv, len + 1);
3974 =for apidoc sv_magicext
3976 Adds magic to an SV, upgrading it if necessary. Applies the
3977 supplied vtable and returns a pointer to the magic added.
3979 Note that C<sv_magicext> will allow things that C<sv_magic> will not.
3980 In particular, you can add magic to SvREADONLY SVs, and add more than
3981 one instance of the same 'how'.
3983 If C<namlen> is greater than zero then a C<savepvn> I<copy> of C<name> is
3984 stored, if C<namlen> is zero then C<name> is stored as-is and - as another
3985 special case - if C<(name && namlen == HEf_SVKEY)> then C<name> is assumed
3986 to contain an C<SV*> and is stored as-is with its REFCNT incremented.
3988 (This is now used as a subroutine by C<sv_magic>.)
3993 Perl_sv_magicext(pTHX_ SV* sv, SV* obj, int how, MGVTBL *vtable,
3994 const char* name, I32 namlen)
3998 if (SvTYPE(sv) < SVt_PVMG) {
3999 (void)SvUPGRADE(sv, SVt_PVMG);
4001 Newxz(mg, 1, MAGIC);
4002 mg->mg_moremagic = SvMAGIC(sv);
4003 SvMAGIC_set(sv, mg);
4005 /* Sometimes a magic contains a reference loop, where the sv and
4006 object refer to each other. To prevent a reference loop that
4007 would prevent such objects being freed, we look for such loops
4008 and if we find one we avoid incrementing the object refcount.
4010 Note we cannot do this to avoid self-tie loops as intervening RV must
4011 have its REFCNT incremented to keep it in existence.
4014 if (!obj || obj == sv ||
4015 how == PERL_MAGIC_arylen ||
4016 how == PERL_MAGIC_qr ||
4017 (SvTYPE(obj) == SVt_PVGV &&
4018 (GvSV(obj) == sv || GvHV(obj) == (HV*)sv || GvAV(obj) == (AV*)sv ||
4019 GvCV(obj) == (CV*)sv || GvIOp(obj) == (IO*)sv ||
4020 GvFORM(obj) == (CV*)sv)))
4025 mg->mg_obj = SvREFCNT_inc_simple(obj);
4026 mg->mg_flags |= MGf_REFCOUNTED;
4029 /* Normal self-ties simply pass a null object, and instead of
4030 using mg_obj directly, use the SvTIED_obj macro to produce a
4031 new RV as needed. For glob "self-ties", we are tieing the PVIO
4032 with an RV obj pointing to the glob containing the PVIO. In
4033 this case, to avoid a reference loop, we need to weaken the
4037 if (how == PERL_MAGIC_tiedscalar && SvTYPE(sv) == SVt_PVIO &&
4038 obj && SvROK(obj) && GvIO(SvRV(obj)) == (IO*)sv)
4044 mg->mg_len = namlen;
4047 mg->mg_ptr = savepvn(name, namlen);
4048 else if (namlen == HEf_SVKEY)
4049 mg->mg_ptr = (char*)SvREFCNT_inc_simple_NN((SV*)name);
4051 mg->mg_ptr = (char *) name;
4053 mg->mg_virtual = vtable;
4057 SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK|SVf_POK);
4062 =for apidoc sv_magic
4064 Adds magic to an SV. First upgrades C<sv> to type C<SVt_PVMG> if necessary,
4065 then adds a new magic item of type C<how> to the head of the magic list.
4067 See C<sv_magicext> (which C<sv_magic> now calls) for a description of the
4068 handling of the C<name> and C<namlen> arguments.
4070 You need to use C<sv_magicext> to add magic to SvREADONLY SVs and also
4071 to add more than one instance of the same 'how'.
4077 Perl_sv_magic(pTHX_ register SV *sv, SV *obj, int how, const char *name, I32 namlen)
4082 if (SvREADONLY(sv)) {
4084 /* its okay to attach magic to shared strings; the subsequent
4085 * upgrade to PVMG will unshare the string */
4086 !(SvFAKE(sv) && SvTYPE(sv) < SVt_PVMG)
4089 && how != PERL_MAGIC_regex_global
4090 && how != PERL_MAGIC_bm
4091 && how != PERL_MAGIC_fm
4092 && how != PERL_MAGIC_sv
4093 && how != PERL_MAGIC_backref
4096 Perl_croak(aTHX_ PL_no_modify);
4099 if (SvMAGICAL(sv) || (how == PERL_MAGIC_taint && SvTYPE(sv) >= SVt_PVMG)) {
4100 if (SvMAGIC(sv) && (mg = mg_find(sv, how))) {
4101 /* sv_magic() refuses to add a magic of the same 'how' as an
4104 if (how == PERL_MAGIC_taint) {
4106 /* Any scalar which already had taint magic on which someone
4107 (erroneously?) did SvIOK_on() or similar will now be
4108 incorrectly sporting public "OK" flags. */
4109 SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK|SVf_POK);
4117 vtable = &PL_vtbl_sv;
4119 case PERL_MAGIC_overload:
4120 vtable = &PL_vtbl_amagic;
4122 case PERL_MAGIC_overload_elem:
4123 vtable = &PL_vtbl_amagicelem;
4125 case PERL_MAGIC_overload_table:
4126 vtable = &PL_vtbl_ovrld;
4129 vtable = &PL_vtbl_bm;
4131 case PERL_MAGIC_regdata:
4132 vtable = &PL_vtbl_regdata;
4134 case PERL_MAGIC_regdatum:
4135 vtable = &PL_vtbl_regdatum;
4137 case PERL_MAGIC_env:
4138 vtable = &PL_vtbl_env;
4141 vtable = &PL_vtbl_fm;
4143 case PERL_MAGIC_envelem:
4144 vtable = &PL_vtbl_envelem;
4146 case PERL_MAGIC_regex_global:
4147 vtable = &PL_vtbl_mglob;
4149 case PERL_MAGIC_isa:
4150 vtable = &PL_vtbl_isa;
4152 case PERL_MAGIC_isaelem:
4153 vtable = &PL_vtbl_isaelem;
4155 case PERL_MAGIC_nkeys:
4156 vtable = &PL_vtbl_nkeys;
4158 case PERL_MAGIC_dbfile:
4161 case PERL_MAGIC_dbline:
4162 vtable = &PL_vtbl_dbline;
4164 #ifdef USE_5005THREADS
4165 case PERL_MAGIC_mutex:
4166 vtable = &PL_vtbl_mutex;
4168 #endif /* USE_5005THREADS */
4169 #ifdef USE_LOCALE_COLLATE
4170 case PERL_MAGIC_collxfrm:
4171 vtable = &PL_vtbl_collxfrm;
4173 #endif /* USE_LOCALE_COLLATE */
4174 case PERL_MAGIC_tied:
4175 vtable = &PL_vtbl_pack;
4177 case PERL_MAGIC_tiedelem:
4178 case PERL_MAGIC_tiedscalar:
4179 vtable = &PL_vtbl_packelem;
4182 vtable = &PL_vtbl_regexp;
4184 case PERL_MAGIC_sig:
4185 vtable = &PL_vtbl_sig;
4187 case PERL_MAGIC_sigelem:
4188 vtable = &PL_vtbl_sigelem;
4190 case PERL_MAGIC_taint:
4191 vtable = &PL_vtbl_taint;
4193 case PERL_MAGIC_uvar:
4194 vtable = &PL_vtbl_uvar;
4196 case PERL_MAGIC_vec:
4197 vtable = &PL_vtbl_vec;
4199 case PERL_MAGIC_vstring:
4202 case PERL_MAGIC_utf8:
4203 vtable = &PL_vtbl_utf8;
4205 case PERL_MAGIC_substr:
4206 vtable = &PL_vtbl_substr;
4208 case PERL_MAGIC_defelem:
4209 vtable = &PL_vtbl_defelem;
4211 case PERL_MAGIC_glob:
4212 vtable = &PL_vtbl_glob;
4214 case PERL_MAGIC_arylen:
4215 vtable = &PL_vtbl_arylen;
4217 case PERL_MAGIC_pos:
4218 vtable = &PL_vtbl_pos;
4220 case PERL_MAGIC_backref:
4221 vtable = &PL_vtbl_backref;
4223 case PERL_MAGIC_ext:
4224 /* Reserved for use by extensions not perl internals. */
4225 /* Useful for attaching extension internal data to perl vars. */
4226 /* Note that multiple extensions may clash if magical scalars */
4227 /* etc holding private data from one are passed to another. */
4231 Perl_croak(aTHX_ "Don't know how to handle magic of type \\%o", how);
4234 /* Rest of work is done else where */
4235 mg = sv_magicext(sv,obj,how,(MGVTBL*)vtable,name,namlen);
4238 case PERL_MAGIC_taint:
4241 case PERL_MAGIC_ext:
4242 case PERL_MAGIC_dbfile:
4249 =for apidoc sv_unmagic
4251 Removes all magic of type C<type> from an SV.
4257 Perl_sv_unmagic(pTHX_ SV *sv, int type)
4261 if (SvTYPE(sv) < SVt_PVMG || !SvMAGIC(sv))
4264 for (mg = *mgp; mg; mg = *mgp) {
4265 if (mg->mg_type == type) {
4266 const MGVTBL* const vtbl = mg->mg_virtual;
4267 *mgp = mg->mg_moremagic;
4268 if (vtbl && vtbl->svt_free)
4269 CALL_FPTR(vtbl->svt_free)(aTHX_ sv, mg);
4270 if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) {
4272 Safefree(mg->mg_ptr);
4273 else if (mg->mg_len == HEf_SVKEY)
4274 SvREFCNT_dec((SV*)mg->mg_ptr);
4275 else if (mg->mg_type == PERL_MAGIC_utf8)
4276 Safefree(mg->mg_ptr);
4278 if (mg->mg_flags & MGf_REFCOUNTED)
4279 SvREFCNT_dec(mg->mg_obj);
4283 mgp = &mg->mg_moremagic;
4287 SvFLAGS(sv) |= (SvFLAGS(sv) & (SVp_NOK|SVp_POK)) >> PRIVSHIFT;
4294 =for apidoc sv_rvweaken
4296 Weaken a reference: set the C<SvWEAKREF> flag on this RV; give the
4297 referred-to SV C<PERL_MAGIC_backref> magic if it hasn't already; and
4298 push a back-reference to this RV onto the array of backreferences
4299 associated with that magic.
4305 Perl_sv_rvweaken(pTHX_ SV *sv)
4308 if (!SvOK(sv)) /* let undefs pass */
4311 Perl_croak(aTHX_ "Can't weaken a nonreference");
4312 else if (SvWEAKREF(sv)) {
4313 if (ckWARN(WARN_MISC))
4314 Perl_warner(aTHX_ packWARN(WARN_MISC), "Reference is already weak");
4318 sv_add_backref(tsv, sv);
4324 /* Give tsv backref magic if it hasn't already got it, then push a
4325 * back-reference to sv onto the array associated with the backref magic.
4329 S_sv_add_backref(pTHX_ SV *tsv, SV *sv)
4333 if (SvMAGICAL(tsv) && (mg = mg_find(tsv, PERL_MAGIC_backref)))
4334 av = (AV*)mg->mg_obj;
4338 sv_magic(tsv, (SV*)av, PERL_MAGIC_backref, NULL, 0);
4339 /* av now has a refcnt of 2, which avoids it getting freed
4340 * before us during global cleanup. The extra ref is removed
4341 * by magic_killbackrefs() when tsv is being freed */
4343 if (AvFILLp(av) >= AvMAX(av)) {
4344 av_extend(av, AvFILLp(av)+1);
4346 AvARRAY(av)[++AvFILLp(av)] = sv; /* av_push() */
4349 /* delete a back-reference to ourselves from the backref magic associated
4350 * with the SV we point to.
4354 S_sv_del_backref(pTHX_ SV *sv)
4359 SV * const tsv = SvRV(sv);
4361 if (!SvMAGICAL(tsv) || !(mg = mg_find(tsv, PERL_MAGIC_backref)))
4362 Perl_croak(aTHX_ "panic: del_backref");
4363 av = (AV *)mg->mg_obj;
4365 /* We shouldn't be in here more than once, but for paranoia reasons lets
4367 for (i = AvFILLp(av); i >= 0; i--) {
4369 const SSize_t fill = AvFILLp(av);
4371 /* We weren't the last entry.
4372 An unordered list has this property that you can take the
4373 last element off the end to fill the hole, and it's still
4374 an unordered list :-)
4379 AvFILLp(av) = fill - 1;
4385 =for apidoc sv_insert
4387 Inserts a string at the specified offset/length within the SV. Similar to
4388 the Perl substr() function.
4394 Perl_sv_insert(pTHX_ SV *bigstr, STRLEN offset, STRLEN len, char *little, STRLEN littlelen)
4398 register char *midend;
4399 register char *bigend;
4405 Perl_croak(aTHX_ "Can't modify non-existent substring");
4406 SvPV_force(bigstr, curlen);
4407 (void)SvPOK_only_UTF8(bigstr);
4408 if (offset + len > curlen) {
4409 SvGROW(bigstr, offset+len+1);
4410 Zero(SvPVX(bigstr)+curlen, offset+len-curlen, char);
4411 SvCUR_set(bigstr, offset+len);
4415 i = littlelen - len;
4416 if (i > 0) { /* string might grow */
4417 big = SvGROW(bigstr, SvCUR(bigstr) + i + 1);
4418 mid = big + offset + len;
4419 midend = bigend = big + SvCUR(bigstr);
4422 while (midend > mid) /* shove everything down */
4423 *--bigend = *--midend;
4424 Move(little,big+offset,littlelen,char);
4425 SvCUR_set(bigstr, SvCUR(bigstr) + i);
4430 Move(little,SvPVX(bigstr)+offset,len,char);
4435 big = SvPVX(bigstr);
4438 bigend = big + SvCUR(bigstr);
4440 if (midend > bigend)
4441 Perl_croak(aTHX_ "panic: sv_insert");
4443 if (mid - big > bigend - midend) { /* faster to shorten from end */
4445 Move(little, mid, littlelen,char);
4448 i = bigend - midend;
4450 Move(midend, mid, i,char);
4454 SvCUR_set(bigstr, mid - big);
4456 else if ((i = mid - big)) { /* faster from front */
4457 midend -= littlelen;
4459 sv_chop(bigstr,midend-i);
4464 Move(little, mid, littlelen,char);
4466 else if (littlelen) {
4467 midend -= littlelen;
4468 sv_chop(bigstr,midend);
4469 Move(little,midend,littlelen,char);
4472 sv_chop(bigstr,midend);
4478 =for apidoc sv_replace
4480 Make the first argument a copy of the second, then delete the original.
4481 The target SV physically takes over ownership of the body of the source SV
4482 and inherits its flags; however, the target keeps any magic it owns,
4483 and any magic in the source is discarded.
4484 Note that this is a rather specialist SV copying operation; most of the
4485 time you'll want to use C<sv_setsv> or one of its many macro front-ends.
4491 Perl_sv_replace(pTHX_ register SV *sv, register SV *nsv)
4493 const U32 refcnt = SvREFCNT(sv);
4494 SV_CHECK_THINKFIRST(sv);
4495 if (SvREFCNT(nsv) != 1 && ckWARN_d(WARN_INTERNAL))
4496 Perl_warner(aTHX_ packWARN(WARN_INTERNAL), "Reference miscount in sv_replace()");
4497 if (SvMAGICAL(sv)) {
4501 sv_upgrade(nsv, SVt_PVMG);
4502 SvMAGIC_set(nsv, SvMAGIC(sv));
4503 SvFLAGS(nsv) |= SvMAGICAL(sv);
4505 SvMAGIC_set(sv, NULL);
4509 assert(!SvREFCNT(sv));
4510 StructCopy(nsv,sv,SV);
4511 SvREFCNT(sv) = refcnt;
4512 SvFLAGS(nsv) |= SVTYPEMASK; /* Mark as freed */
4518 =for apidoc sv_clear
4520 Clear an SV: call any destructors, free up any memory used by the body,
4521 and free the body itself. The SV's head is I<not> freed, although
4522 its type is set to all 1's so that it won't inadvertently be assumed
4523 to be live during global destruction etc.
4524 This function should only be called when REFCNT is zero. Most of the time
4525 you'll want to call C<sv_free()> (or its macro wrapper C<SvREFCNT_dec>)
4532 Perl_sv_clear(pTHX_ register SV *sv)
4535 const U32 type = SvTYPE(sv);
4536 const struct body_details *const sv_type_details
4537 = bodies_by_type + type;
4540 assert(SvREFCNT(sv) == 0);
4542 if (type < SVt_IV) {
4547 if (PL_defstash) { /* Still have a symbol table? */
4551 stash = SvSTASH(sv);
4552 destructor = StashHANDLER(stash,DESTROY);
4554 SV* const tmpref = newRV(sv);
4555 SvREADONLY_on(tmpref); /* DESTROY() could be naughty */
4557 PUSHSTACKi(PERLSI_DESTROY);
4562 call_sv((SV*)destructor, G_DISCARD|G_EVAL|G_KEEPERR|G_VOID);
4568 if(SvREFCNT(tmpref) < 2) {
4569 /* tmpref is not kept alive! */
4571 SvRV_set(tmpref, NULL);
4574 SvREFCNT_dec(tmpref);
4576 } while (SvOBJECT(sv) && SvSTASH(sv) != stash);
4580 if (PL_in_clean_objs)
4581 Perl_croak(aTHX_ "DESTROY created new reference to dead object '%s'",
4583 /* DESTROY gave object new lease on life */
4589 SvREFCNT_dec(SvSTASH(sv)); /* possibly of changed persuasion */
4590 SvOBJECT_off(sv); /* Curse the object. */
4591 if (type != SVt_PVIO)
4592 --PL_sv_objcount; /* XXX Might want something more general */
4595 if (type >= SVt_PVMG) {
4598 if (type == SVt_PVMG && SvPAD_TYPED(sv))
4599 SvREFCNT_dec(SvSTASH(sv));
4605 IoIFP(sv) != PerlIO_stdin() &&
4606 IoIFP(sv) != PerlIO_stdout() &&
4607 IoIFP(sv) != PerlIO_stderr())
4609 io_close((IO*)sv, FALSE);
4611 if (IoDIRP(sv) && !(IoFLAGS(sv) & IOf_FAKE_DIRP))
4612 PerlDir_close(IoDIRP(sv));
4613 IoDIRP(sv) = (DIR*)NULL;
4614 Safefree(IoTOP_NAME(sv));
4615 Safefree(IoFMT_NAME(sv));
4616 Safefree(IoBOTTOM_NAME(sv));
4631 if (LvTYPE(sv) == 'T') { /* for tie: return HE to pool */
4632 SvREFCNT_dec(HeKEY_sv((HE*)LvTARG(sv)));
4633 HeNEXT((HE*)LvTARG(sv)) = PL_hv_fetch_ent_mh;
4634 PL_hv_fetch_ent_mh = (HE*)LvTARG(sv);
4636 else if (LvTYPE(sv) != 't') /* unless tie: unrefcnted fake SV** */
4637 SvREFCNT_dec(LvTARG(sv));
4641 Safefree(GvNAME(sv));
4642 /* cannot decrease stash refcount yet, as we might recursively delete
4643 ourselves when the refcnt drops to zero. Delay SvREFCNT_dec
4644 of stash until current sv is completely gone.
4645 -- JohnPC, 27 Mar 1998 */
4646 stash = GvSTASH(sv);
4651 /* Don't bother with SvOOK_off(sv); as we're only going to free it. */
4653 SvPV_set(sv, SvPVX_mutable(sv) - SvIVX(sv));
4654 /* Don't even bother with turning off the OOK flag. */
4662 SvREFCNT_dec(SvRV(sv));
4664 else if (SvPVX_const(sv) && SvLEN(sv))
4665 Safefree(SvPVX_mutable(sv));
4666 else if (SvPVX_const(sv) && SvREADONLY(sv) && SvFAKE(sv)) {
4667 unsharepvn(SvPVX_const(sv),
4668 SvUTF8(sv) ? -(I32)SvCUR(sv) : SvCUR(sv),
4678 SvFLAGS(sv) &= SVf_BREAK;
4679 SvFLAGS(sv) |= SVTYPEMASK;
4681 if (sv_type_details->arena) {
4682 del_body(((char *)SvANY(sv) + sv_type_details->offset),
4683 &PL_body_roots[type]);
4685 else if (sv_type_details->body_size) {
4686 my_safefree(SvANY(sv));
4689 /* decrease refcount of the stash that owns this GV, if any */
4691 SvREFCNT_dec(stash);
4696 =for apidoc sv_newref
4698 Increment an SV's reference count. Use the C<SvREFCNT_inc()> wrapper
4705 Perl_sv_newref(pTHX_ SV *sv)
4707 PERL_UNUSED_CONTEXT;
4709 ATOMIC_INC(SvREFCNT(sv));
4716 Decrement an SV's reference count, and if it drops to zero, call
4717 C<sv_clear> to invoke destructors and free up any memory used by
4718 the body; finally, deallocate the SV's head itself.
4719 Normally called via a wrapper macro C<SvREFCNT_dec>.
4725 Perl_sv_free(pTHX_ SV *sv)
4727 int refcount_is_zero;
4731 if (SvREFCNT(sv) == 0) {
4732 if (SvFLAGS(sv) & SVf_BREAK)
4733 /* this SV's refcnt has been artificially decremented to
4734 * trigger cleanup */
4736 if (PL_in_clean_all) /* All is fair */
4738 if (SvREADONLY(sv) && SvIMMORTAL(sv)) {
4739 /* make sure SvREFCNT(sv)==0 happens very seldom */
4740 SvREFCNT(sv) = (~(U32)0)/2;
4743 if (ckWARN_d(WARN_INTERNAL)) {
4744 Perl_warner(aTHX_ packWARN(WARN_INTERNAL),
4745 "Attempt to free unreferenced scalar: SV 0x%"UVxf
4746 pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
4747 #ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
4748 Perl_dump_sv_child(aTHX_ sv);
4753 ATOMIC_DEC_AND_TEST(refcount_is_zero, SvREFCNT(sv));
4754 if (!refcount_is_zero)
4758 if (ckWARN_d(WARN_DEBUGGING))
4759 Perl_warner(aTHX_ packWARN(WARN_DEBUGGING),
4760 "Attempt to free temp prematurely: SV 0x%"UVxf
4761 pTHX__FORMAT, PTR2UV(sv) pTHX__VALUE);
4765 if (SvREADONLY(sv) && SvIMMORTAL(sv)) {
4766 /* make sure SvREFCNT(sv)==0 happens very seldom */
4767 SvREFCNT(sv) = (~(U32)0)/2;
4778 Returns the length of the string in the SV. Handles magic and type
4779 coercion. See also C<SvCUR>, which gives raw access to the xpv_cur slot.
4785 Perl_sv_len(pTHX_ register SV *sv)
4793 len = mg_length(sv);
4795 (void)SvPV_const(sv, len);
4800 =for apidoc sv_len_utf8
4802 Returns the number of characters in the string in an SV, counting wide
4803 UTF-8 bytes as a single character. Handles magic and type coercion.
4809 * The length is cached in PERL_UTF8_magic, in the mg_len field. Also the
4810 * mg_ptr is used, by sv_pos_u2b() and sv_pos_b2u() - see the comments below.
4811 * (Note that the mg_len is not the length of the mg_ptr field.
4812 * This allows the cache to store the character length of the string without
4813 * needing to malloc() extra storage to attach to the mg_ptr.)
4818 Perl_sv_len_utf8(pTHX_ register SV *sv)
4824 return mg_length(sv);
4828 const U8 *s = (U8*)SvPV_const(sv, len);
4832 MAGIC *mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : 0;
4834 if (mg && mg->mg_len != -1) {
4836 if (PL_utf8cache < 0) {
4837 const STRLEN real = Perl_utf8_length(aTHX_ (U8 *)s,
4840 /* Need to turn the assertions off otherwise we may
4841 recurse infinitely while printing error messages.
4843 SAVEI8(PL_utf8cache);
4845 Perl_croak(aTHX_ "panic: sv_len_utf8 cache %"UVuf
4846 " real %"UVuf" for %"SVf,
4847 (UV) ulen, (UV) real, (void*)sv);
4852 ulen = Perl_utf8_length(aTHX_ (U8 *)s, (U8 *)s + len);
4853 if (!SvREADONLY(sv)) {
4855 mg = sv_magicext(sv, 0, PERL_MAGIC_utf8,
4856 &PL_vtbl_utf8, 0, 0);
4864 return Perl_utf8_length(aTHX_ (U8 *)s, (U8 *)s + len);
4868 /* Walk forwards to find the byte corresponding to the passed in UTF-8
4871 S_sv_pos_u2b_forwards(const U8 *const start, const U8 *const send,
4874 const U8 *s = start;
4876 while (s < send && uoffset--)
4879 /* This is the existing behaviour. Possibly it should be a croak, as
4880 it's actually a bounds error */
4886 /* Given the length of the string in both bytes and UTF-8 characters, decide
4887 whether to walk forwards or backwards to find the byte corresponding to
4888 the passed in UTF-8 offset. */
4890 S_sv_pos_u2b_midway(const U8 *const start, const U8 *send,
4891 STRLEN uoffset, STRLEN uend)
4893 STRLEN backw = uend - uoffset;
4894 if (uoffset < 2 * backw) {
4895 /* The assumption is that going forwards is twice the speed of going
4896 forward (that's where the 2 * backw comes from).
4897 (The real figure of course depends on the UTF-8 data.) */
4898 return sv_pos_u2b_forwards(start, send, uoffset);
4903 while (UTF8_IS_CONTINUATION(*send))
4906 return send - start;
4909 /* For the string representation of the given scalar, find the byte
4910 corresponding to the passed in UTF-8 offset. uoffset0 and boffset0
4911 give another position in the string, *before* the sought offset, which
4912 (which is always true, as 0, 0 is a valid pair of positions), which should
4913 help reduce the amount of linear searching.
4914 If *mgp is non-NULL, it should point to the UTF-8 cache magic, which
4915 will be used to reduce the amount of linear searching. The cache will be
4916 created if necessary, and the found value offered to it for update. */
4918 S_sv_pos_u2b_cached(pTHX_ SV *sv, MAGIC **mgp, const U8 *const start,
4919 const U8 *const send, STRLEN uoffset,
4920 STRLEN uoffset0, STRLEN boffset0) {
4921 STRLEN boffset = 0; /* Actually always set, but let's keep gcc happy. */
4924 assert (uoffset >= uoffset0);
4926 if (SvMAGICAL(sv) && !SvREADONLY(sv) && PL_utf8cache
4927 && (*mgp || (*mgp = mg_find(sv, PERL_MAGIC_utf8)))) {
4928 if ((*mgp)->mg_ptr) {
4929 STRLEN *cache = (STRLEN *) (*mgp)->mg_ptr;
4930 if (cache[0] == uoffset) {
4931 /* An exact match. */
4934 if (cache[2] == uoffset) {
4935 /* An exact match. */
4939 if (cache[0] < uoffset) {
4940 /* The cache already knows part of the way. */
4941 if (cache[0] > uoffset0) {
4942 /* The cache knows more than the passed in pair */
4943 uoffset0 = cache[0];
4944 boffset0 = cache[1];
4946 if ((*mgp)->mg_len != -1) {
4947 /* And we know the end too. */
4949 + sv_pos_u2b_midway(start + boffset0, send,
4951 (*mgp)->mg_len - uoffset0);
4954 + sv_pos_u2b_forwards(start + boffset0,
4955 send, uoffset - uoffset0);
4958 else if (cache[2] < uoffset) {
4959 /* We're between the two cache entries. */
4960 if (cache[2] > uoffset0) {
4961 /* and the cache knows more than the passed in pair */
4962 uoffset0 = cache[2];
4963 boffset0 = cache[3];
4967 + sv_pos_u2b_midway(start + boffset0,
4970 cache[0] - uoffset0);
4973 + sv_pos_u2b_midway(start + boffset0,
4976 cache[2] - uoffset0);
4980 else if ((*mgp)->mg_len != -1) {
4981 /* If we can take advantage of a passed in offset, do so. */
4982 /* In fact, offset0 is either 0, or less than offset, so don't
4983 need to worry about the other possibility. */
4985 + sv_pos_u2b_midway(start + boffset0, send,
4987 (*mgp)->mg_len - uoffset0);
4992 if (!found || PL_utf8cache < 0) {
4993 const STRLEN real_boffset
4994 = boffset0 + sv_pos_u2b_forwards(start + boffset0,
4995 send, uoffset - uoffset0);
4997 if (found && PL_utf8cache < 0) {
4998 if (real_boffset != boffset) {
4999 /* Need to turn the assertions off otherwise we may recurse
5000 infinitely while printing error messages. */
5001 SAVEI8(PL_utf8cache);
5003 Perl_croak(aTHX_ "panic: sv_pos_u2b_cache cache %"UVuf
5004 " real %"UVuf" for %"SVf,
5005 (UV) boffset, (UV) real_boffset, (void*)sv);
5008 boffset = real_boffset;
5011 S_utf8_mg_pos_cache_update(aTHX_ sv, mgp, boffset, uoffset, send - start);
5017 =for apidoc sv_pos_u2b
5019 Converts the value pointed to by offsetp from a count of UTF-8 chars from
5020 the start of the string, to a count of the equivalent number of bytes; if
5021 lenp is non-zero, it does the same to lenp, but this time starting from
5022 the offset, rather than from the start of the string. Handles magic and
5029 * sv_pos_u2b() uses, like sv_pos_b2u(), the mg_ptr of the potential
5030 * PERL_UTF8_magic of the sv to store the mapping between UTF-8 and
5031 * byte offsets. See also the comments of S_utf8_mg_pos_cache_update().
5036 Perl_sv_pos_u2b(pTHX_ register SV *sv, I32* offsetp, I32* lenp)
5044 start = (U8*)SvPV_const(sv, len);
5046 STRLEN uoffset = (STRLEN) *offsetp;
5047 const U8 * const send = start + len;
5049 const STRLEN boffset = sv_pos_u2b_cached(sv, &mg, start, send,
5052 *offsetp = (I32) boffset;
5055 /* Convert the relative offset to absolute. */
5056 const STRLEN uoffset2 = uoffset + (STRLEN) *lenp;
5057 const STRLEN boffset2
5058 = sv_pos_u2b_cached(sv, &mg, start, send, uoffset2,
5059 uoffset, boffset) - boffset;
5072 /* Create and update the UTF8 magic offset cache, with the proffered utf8/
5073 byte length pairing. The (byte) length of the total SV is passed in too,
5074 as blen, because for some (more esoteric) SVs, the call to SvPV_const()
5075 may not have updated SvCUR, so we can't rely on reading it directly.
5077 The proffered utf8/byte length pairing isn't used if the cache already has
5078 two pairs, and swapping either for the proffered pair would increase the
5079 RMS of the intervals between known byte offsets.
5081 The cache itself consists of 4 STRLEN values
5082 0: larger UTF-8 offset
5083 1: corresponding byte offset
5084 2: smaller UTF-8 offset
5085 3: corresponding byte offset
5087 Unused cache pairs have the value 0, 0.
5088 Keeping the cache "backwards" means that the invariant of
5089 cache[0] >= cache[2] is maintained even with empty slots, which means that
5090 the code that uses it doesn't need to worry if only 1 entry has actually
5091 been set to non-zero. It also makes the "position beyond the end of the
5092 cache" logic much simpler, as the first slot is always the one to start
5096 S_utf8_mg_pos_cache_update(pTHX_ SV *sv, MAGIC **mgp, STRLEN byte, STRLEN utf8,
5104 *mgp = sv_magicext(sv, 0, PERL_MAGIC_utf8, (MGVTBL*)&PL_vtbl_utf8, 0,
5106 (*mgp)->mg_len = -1;
5110 if (!(cache = (STRLEN *)(*mgp)->mg_ptr)) {
5111 Newxz(cache, PERL_MAGIC_UTF8_CACHESIZE * 2, STRLEN);
5112 (*mgp)->mg_ptr = (char *) cache;
5116 if (PL_utf8cache < 0) {
5117 const U8 *start = (const U8 *) SvPVX_const(sv);
5118 const STRLEN realutf8 = utf8_length((U8 *)start, (U8 *)start + byte);
5120 if (realutf8 != utf8) {
5121 /* Need to turn the assertions off otherwise we may recurse
5122 infinitely while printing error messages. */
5123 SAVEI8(PL_utf8cache);
5125 Perl_croak(aTHX_ "panic: utf8_mg_pos_cache_update cache %"UVuf
5126 " real %"UVuf" for %"SVf, (UV) utf8, (UV) realutf8, (void*)sv);
5130 /* Cache is held with the later position first, to simplify the code
5131 that deals with unbounded ends. */
5133 ASSERT_UTF8_CACHE(cache);
5134 if (cache[1] == 0) {
5135 /* Cache is totally empty */
5138 } else if (cache[3] == 0) {
5139 if (byte > cache[1]) {
5140 /* New one is larger, so goes first. */
5141 cache[2] = cache[0];
5142 cache[3] = cache[1];
5150 #define THREEWAY_SQUARE(a,b,c,d) \
5151 ((float)((d) - (c))) * ((float)((d) - (c))) \
5152 + ((float)((c) - (b))) * ((float)((c) - (b))) \
5153 + ((float)((b) - (a))) * ((float)((b) - (a)))
5155 /* Cache has 2 slots in use, and we know three potential pairs.
5156 Keep the two that give the lowest RMS distance. Do the
5157 calcualation in bytes simply because we always know the byte
5158 length. squareroot has the same ordering as the positive value,
5159 so don't bother with the actual square root. */
5160 const float existing = THREEWAY_SQUARE(0, cache[3], cache[1], blen);
5161 if (byte > cache[1]) {
5162 /* New position is after the existing pair of pairs. */
5163 const float keep_earlier
5164 = THREEWAY_SQUARE(0, cache[3], byte, blen);
5165 const float keep_later
5166 = THREEWAY_SQUARE(0, cache[1], byte, blen);
5168 if (keep_later < keep_earlier) {
5169 if (keep_later < existing) {
5170 cache[2] = cache[0];
5171 cache[3] = cache[1];
5177 if (keep_earlier < existing) {
5183 else if (byte > cache[3]) {
5184 /* New position is between the existing pair of pairs. */
5185 const float keep_earlier
5186 = THREEWAY_SQUARE(0, cache[3], byte, blen);
5187 const float keep_later
5188 = THREEWAY_SQUARE(0, byte, cache[1], blen);
5190 if (keep_later < keep_earlier) {
5191 if (keep_later < existing) {
5197 if (keep_earlier < existing) {
5204 /* New position is before the existing pair of pairs. */
5205 const float keep_earlier
5206 = THREEWAY_SQUARE(0, byte, cache[3], blen);
5207 const float keep_later
5208 = THREEWAY_SQUARE(0, byte, cache[1], blen);
5210 if (keep_later < keep_earlier) {
5211 if (keep_later < existing) {
5217 if (keep_earlier < existing) {
5218 cache[0] = cache[2];
5219 cache[1] = cache[3];
5226 ASSERT_UTF8_CACHE(cache);
5229 /* We already know all of the way, now we may be able to walk back. The same
5230 assumption is made as in S_sv_pos_u2b_midway(), namely that walking
5231 backward is half the speed of walking forward. */
5233 S_sv_pos_b2u_midway(pTHX_ const U8 *s, const U8 *const target, const U8 *end,
5236 const STRLEN forw = target - s;
5237 STRLEN backw = end - target;
5239 if (forw < 2 * backw) {
5240 return utf8_length((U8 *)s, (U8 *)target);
5243 while (end > target) {
5245 while (UTF8_IS_CONTINUATION(*end)) {
5254 =for apidoc sv_pos_b2u
5256 Converts the value pointed to by offsetp from a count of bytes from the
5257 start of the string, to a count of the equivalent number of UTF-8 chars.
5258 Handles magic and type coercion.
5264 * sv_pos_b2u() uses, like sv_pos_u2b(), the mg_ptr of the potential
5265 * PERL_UTF8_magic of the sv to store the mapping between UTF-8 and
5270 Perl_sv_pos_b2u(pTHX_ register SV* sv, I32* offsetp)
5273 const STRLEN byte = *offsetp;
5274 STRLEN len = 0; /* Actually always set, but let's keep gcc happy. */
5283 s = (const U8*)SvPV_const(sv, blen);
5286 Perl_croak(aTHX_ "panic: sv_pos_b2u: bad byte offset");
5290 if (SvMAGICAL(sv) && !SvREADONLY(sv) && PL_utf8cache
5291 && (mg = mg_find(sv, PERL_MAGIC_utf8))) {
5293 STRLEN * const cache = (STRLEN *) mg->mg_ptr;
5294 if (cache[1] == byte) {
5295 /* An exact match. */
5296 *offsetp = cache[0];
5299 if (cache[3] == byte) {
5300 /* An exact match. */
5301 *offsetp = cache[2];
5305 if (cache[1] < byte) {
5306 /* We already know part of the way. */
5307 if (mg->mg_len != -1) {
5308 /* Actually, we know the end too. */
5310 + S_sv_pos_b2u_midway(aTHX_ s + cache[1], send,
5311 s + blen, mg->mg_len - cache[0]);
5313 len = cache[0] + utf8_length((U8 *)s + cache[1],
5317 else if (cache[3] < byte) {
5318 /* We're between the two cached pairs, so we do the calculation
5319 offset by the byte/utf-8 positions for the earlier pair,
5320 then add the utf-8 characters from the string start to
5322 len = S_sv_pos_b2u_midway(aTHX_ s + cache[3], send,
5323 s + cache[1], cache[0] - cache[2])
5327 else { /* cache[3] > byte */
5328 len = S_sv_pos_b2u_midway(aTHX_ s, send, s + cache[3],
5332 ASSERT_UTF8_CACHE(cache);
5334 } else if (mg->mg_len != -1) {
5335 len = S_sv_pos_b2u_midway(aTHX_ s, send, s + blen, mg->mg_len);
5339 if (!found || PL_utf8cache < 0) {
5340 const STRLEN real_len = utf8_length((U8 *)s, (U8 *)send);
5342 if (found && PL_utf8cache < 0) {
5343 if (len != real_len) {
5344 /* Need to turn the assertions off otherwise we may recurse
5345 infinitely while printing error messages. */
5346 SAVEI8(PL_utf8cache);
5348 Perl_croak(aTHX_ "panic: sv_pos_b2u cache %"UVuf
5349 " real %"UVuf" for %"SVf,
5350 (UV) len, (UV) real_len, (void*)sv);
5357 S_utf8_mg_pos_cache_update(aTHX_ sv, &mg, byte, len, blen);
5363 Returns a boolean indicating whether the strings in the two SVs are
5364 identical. Is UTF-8 and 'use bytes' aware, handles get magic, and will
5365 coerce its args to strings if necessary.
5371 Perl_sv_eq(pTHX_ register SV *sv1, register SV *sv2)
5379 SV* svrecode = NULL;
5386 /* if pv1 and pv2 are the same, second SvPV_const call may
5387 * invalidate pv1, so we may need to make a copy */
5388 if (sv1 == sv2 && (SvTHINKFIRST(sv1) || SvGMAGICAL(sv1))) {
5389 pv1 = SvPV_const(sv1, cur1);
5390 sv1 = sv_2mortal(newSVpvn(pv1, cur1));
5391 if (SvUTF8(sv2)) SvUTF8_on(sv1);
5393 pv1 = SvPV_const(sv1, cur1);
5401 pv2 = SvPV_const(sv2, cur2);
5403 if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
5404 /* Differing utf8ness.
5405 * Do not UTF8size the comparands as a side-effect. */
5408 svrecode = newSVpvn(pv2, cur2);
5409 sv_recode_to_utf8(svrecode, PL_encoding);
5410 pv2 = SvPV_const(svrecode, cur2);
5413 svrecode = newSVpvn(pv1, cur1);
5414 sv_recode_to_utf8(svrecode, PL_encoding);
5415 pv1 = SvPV_const(svrecode, cur1);
5417 /* Now both are in UTF-8. */
5419 SvREFCNT_dec(svrecode);
5424 bool is_utf8 = TRUE;
5427 /* sv1 is the UTF-8 one,
5428 * if is equal it must be downgrade-able */
5429 char * const pv = (char*)bytes_from_utf8((U8*)pv1,
5435 /* sv2 is the UTF-8 one,
5436 * if is equal it must be downgrade-able */
5437 char * const pv = (char *)bytes_from_utf8((U8*)pv2,
5443 /* Downgrade not possible - cannot be eq */
5451 eq = memEQ(pv1, pv2, cur1);
5453 SvREFCNT_dec(svrecode);
5463 Compares the strings in two SVs. Returns -1, 0, or 1 indicating whether the
5464 string in C<sv1> is less than, equal to, or greater than the string in
5465 C<sv2>. Is UTF-8 and 'use bytes' aware, handles get magic, and will
5466 coerce its args to strings if necessary. See also C<sv_cmp_locale>.
5472 Perl_sv_cmp(pTHX_ register SV *sv1, register SV *sv2)
5475 const char *pv1, *pv2;
5478 SV *svrecode = NULL;
5485 pv1 = SvPV_const(sv1, cur1);
5492 pv2 = SvPV_const(sv2, cur2);
5494 if (cur1 && cur2 && SvUTF8(sv1) != SvUTF8(sv2) && !IN_BYTES) {
5495 /* Differing utf8ness.
5496 * Do not UTF8size the comparands as a side-effect. */
5499 svrecode = newSVpvn(pv2, cur2);
5500 sv_recode_to_utf8(svrecode, PL_encoding);
5501 pv2 = SvPV_const(svrecode, cur2);
5504 pv2 = tpv = (char*)bytes_to_utf8((U8*)pv2, &cur2);
5509 svrecode = newSVpvn(pv1, cur1);
5510 sv_recode_to_utf8(svrecode, PL_encoding);
5511 pv1 = SvPV_const(svrecode, cur1);
5514 pv1 = tpv = (char*)bytes_to_utf8((U8*)pv1, &cur1);
5520 cmp = cur2 ? -1 : 0;
5524 const I32 retval = memcmp((const void*)pv1, (const void*)pv2, cur1 < cur2 ? cur1 : cur2);
5527 cmp = retval < 0 ? -1 : 1;
5528 } else if (cur1 == cur2) {
5531 cmp = cur1 < cur2 ? -1 : 1;
5535 SvREFCNT_dec(svrecode);
5543 =for apidoc sv_cmp_locale
5545 Compares the strings in two SVs in a locale-aware manner. Is UTF-8 and
5546 'use bytes' aware, handles get magic, and will coerce its args to strings
5547 if necessary. See also C<sv_cmp_locale>. See also C<sv_cmp>.
5553 Perl_sv_cmp_locale(pTHX_ register SV *sv1, register SV *sv2)
5555 #ifdef USE_LOCALE_COLLATE
5561 if (PL_collation_standard)
5565 pv1 = sv1 ? sv_collxfrm(sv1, &len1) : (char *) NULL;
5567 pv2 = sv2 ? sv_collxfrm(sv2, &len2) : (char *) NULL;
5569 if (!pv1 || !len1) {
5580 retval = memcmp((void*)pv1, (void*)pv2, len1 < len2 ? len1 : len2);
5583 return retval < 0 ? -1 : 1;
5586 * When the result of collation is equality, that doesn't mean
5587 * that there are no differences -- some locales exclude some
5588 * characters from consideration. So to avoid false equalities,
5589 * we use the raw string as a tiebreaker.
5595 #endif /* USE_LOCALE_COLLATE */
5597 return sv_cmp(sv1, sv2);
5601 #ifdef USE_LOCALE_COLLATE
5604 =for apidoc sv_collxfrm
5606 Add Collate Transform magic to an SV if it doesn't already have it.
5608 Any scalar variable may carry PERL_MAGIC_collxfrm magic that contains the
5609 scalar data of the variable, but transformed to such a format that a normal
5610 memory comparison can be used to compare the data according to the locale
5617 Perl_sv_collxfrm(pTHX_ SV *sv, STRLEN *nxp)
5621 mg = SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_collxfrm) : (MAGIC *) NULL;
5622 if (!mg || !mg->mg_ptr || *(U32*)mg->mg_ptr != PL_collation_ix) {
5628 Safefree(mg->mg_ptr);
5629 s = SvPV_const(sv, len);
5630 if ((xf = mem_collxfrm(s, len, &xlen))) {
5631 if (SvREADONLY(sv)) {
5634 return xf + sizeof(PL_collation_ix);
5637 #ifdef PERL_OLD_COPY_ON_WRITE
5639 sv_force_normal_flags(sv, 0);
5641 mg = sv_magicext(sv, 0, PERL_MAGIC_collxfrm, &PL_vtbl_collxfrm,
5655 if (mg && mg->mg_ptr) {
5657 return mg->mg_ptr + sizeof(PL_collation_ix);
5665 #endif /* USE_LOCALE_COLLATE */
5670 Get a line from the filehandle and store it into the SV, optionally
5671 appending to the currently-stored string.
5677 Perl_sv_gets(pTHX_ register SV *sv, register PerlIO *fp, I32 append)
5681 register STDCHAR rslast;
5682 register STDCHAR *bp;
5687 if (SvTHINKFIRST(sv))
5688 sv_force_normal_flags(sv, append ? 0 : SV_COW_DROP_PV);
5689 /* XXX. If you make this PVIV, then copy on write can copy scalars read
5691 However, perlbench says it's slower, because the existing swipe code
5692 is faster than copy on write.
5693 Swings and roundabouts. */
5694 (void)SvUPGRADE(sv, SVt_PV);
5699 if (PerlIO_isutf8(fp)) {
5701 sv_utf8_upgrade_nomg(sv);
5702 sv_pos_u2b(sv,&append,0);
5704 } else if (SvUTF8(sv)) {
5705 SV * const tsv = newSV(0);
5706 sv_gets(tsv, fp, 0);
5707 sv_utf8_upgrade_nomg(tsv);
5708 SvCUR_set(sv,append);
5711 goto return_string_or_null;
5716 if (PerlIO_isutf8(fp))
5719 if (IN_PERL_COMPILETIME) {
5720 /* we always read code in line mode */
5724 else if (RsSNARF(PL_rs)) {
5725 /* If it is a regular disk file use size from stat() as estimate
5726 of amount we are going to read -- may result in mallocing
5727 more memory than we really need if the layers below reduce
5728 the size we read (e.g. CRLF or a gzip layer).
5731 if (!PerlLIO_fstat(PerlIO_fileno(fp), &st) && S_ISREG(st.st_mode)) {
5732 const Off_t offset = PerlIO_tell(fp);
5733 if (offset != (Off_t) -1 && st.st_size + append > offset) {
5734 (void) SvGROW(sv, (STRLEN)((st.st_size - offset) + append + 1));
5740 else if (RsRECORD(PL_rs)) {
5745 /* Grab the size of the record we're getting */
5746 recsize = SvUV(SvRV(PL_rs)); /* RsRECORD() guarantees > 0. */
5747 buffer = SvGROW(sv, (STRLEN)(recsize + append + 1)) + append;
5750 /* VMS wants read instead of fread, because fread doesn't respect */
5751 /* RMS record boundaries. This is not necessarily a good thing to be */
5752 /* doing, but we've got no other real choice - except avoid stdio
5753 as implementation - perhaps write a :vms layer ?
5755 bytesread = PerlLIO_read(PerlIO_fileno(fp), buffer, recsize);
5757 bytesread = PerlIO_read(fp, buffer, recsize);
5761 SvCUR_set(sv, bytesread += append);
5762 buffer[bytesread] = '\0';
5763 goto return_string_or_null;
5765 else if (RsPARA(PL_rs)) {
5771 /* Get $/ i.e. PL_rs into same encoding as stream wants */
5772 if (PerlIO_isutf8(fp)) {
5773 rsptr = SvPVutf8(PL_rs, rslen);
5776 if (SvUTF8(PL_rs)) {
5777 if (!sv_utf8_downgrade(PL_rs, TRUE)) {
5778 Perl_croak(aTHX_ "Wide character in $/");
5781 rsptr = SvPV_const(PL_rs, rslen);
5785 rslast = rslen ? rsptr[rslen - 1] : '\0';
5787 if (rspara) { /* have to do this both before and after */
5788 do { /* to make sure file boundaries work right */
5791 i = PerlIO_getc(fp);
5795 PerlIO_ungetc(fp,i);
5801 /* See if we know enough about I/O mechanism to cheat it ! */
5803 /* This used to be #ifdef test - it is made run-time test for ease
5804 of abstracting out stdio interface. One call should be cheap
5805 enough here - and may even be a macro allowing compile
5809 if (PerlIO_fast_gets(fp)) {
5812 * We're going to steal some values from the stdio struct
5813 * and put EVERYTHING in the innermost loop into registers.
5815 register STDCHAR *ptr;
5819 #if defined(VMS) && defined(PERLIO_IS_STDIO)
5820 /* An ungetc()d char is handled separately from the regular
5821 * buffer, so we getc() it back out and stuff it in the buffer.
5823 i = PerlIO_getc(fp);
5824 if (i == EOF) return 0;
5825 *(--((*fp)->_ptr)) = (unsigned char) i;
5829 /* Here is some breathtakingly efficient cheating */
5831 cnt = PerlIO_get_cnt(fp); /* get count into register */
5832 /* make sure we have the room */
5833 if ((I32)(SvLEN(sv) - append) <= cnt + 1) {
5834 /* Not room for all of it
5835 if we are looking for a separator and room for some
5837 if (rslen && cnt > 80 && (I32)SvLEN(sv) > append) {
5838 /* just process what we have room for */
5839 shortbuffered = cnt - SvLEN(sv) + append + 1;
5840 cnt -= shortbuffered;
5844 /* remember that cnt can be negative */
5845 SvGROW(sv, (STRLEN)(append + (cnt <= 0 ? 2 : (cnt + 1))));
5850 bp = (STDCHAR*)SvPVX_const(sv) + append; /* move these two too to registers */
5851 ptr = (STDCHAR*)PerlIO_get_ptr(fp);
5852 DEBUG_P(PerlIO_printf(Perl_debug_log,
5853 "Screamer: entering, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
5854 DEBUG_P(PerlIO_printf(Perl_debug_log,
5855 "Screamer: entering: PerlIO * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
5856 PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
5857 PTR2UV(PerlIO_has_base(fp) ? PerlIO_get_base(fp) : 0)));
5862 while (cnt > 0) { /* this | eat */
5864 if ((*bp++ = *ptr++) == rslast) /* really | dust */
5865 goto thats_all_folks; /* screams | sed :-) */
5869 Copy(ptr, bp, cnt, char); /* this | eat */
5870 bp += cnt; /* screams | dust */
5871 ptr += cnt; /* louder | sed :-) */
5876 if (shortbuffered) { /* oh well, must extend */
5877 cnt = shortbuffered;
5879 bpx = bp - (STDCHAR*)SvPVX_const(sv); /* box up before relocation */
5881 SvGROW(sv, SvLEN(sv) + append + cnt + 2);
5882 bp = (STDCHAR*)SvPVX_const(sv) + bpx; /* unbox after relocation */
5886 DEBUG_P(PerlIO_printf(Perl_debug_log,
5887 "Screamer: going to getc, ptr=%"UVuf", cnt=%ld\n",
5888 PTR2UV(ptr),(long)cnt));
5889 PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt); /* deregisterize cnt and ptr */
5891 DEBUG_P(PerlIO_printf(Perl_debug_log,
5892 "Screamer: pre: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
5893 PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
5894 PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
5896 /* This used to call 'filbuf' in stdio form, but as that behaves like
5897 getc when cnt <= 0 we use PerlIO_getc here to avoid introducing
5898 another abstraction. */
5899 i = PerlIO_getc(fp); /* get more characters */
5901 DEBUG_P(PerlIO_printf(Perl_debug_log,
5902 "Screamer: post: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
5903 PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
5904 PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
5906 cnt = PerlIO_get_cnt(fp);
5907 ptr = (STDCHAR*)PerlIO_get_ptr(fp); /* reregisterize cnt and ptr */
5908 DEBUG_P(PerlIO_printf(Perl_debug_log,
5909 "Screamer: after getc, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
5911 if (i == EOF) /* all done for ever? */
5912 goto thats_really_all_folks;
5914 bpx = bp - (STDCHAR*)SvPVX_const(sv); /* box up before relocation */
5916 SvGROW(sv, bpx + cnt + 2);
5917 bp = (STDCHAR*)SvPVX_const(sv) + bpx; /* unbox after relocation */
5919 *bp++ = (STDCHAR)i; /* store character from PerlIO_getc */
5921 if (rslen && (STDCHAR)i == rslast) /* all done for now? */
5922 goto thats_all_folks;
5926 if ((rslen > 1 && (STRLEN)(bp - (STDCHAR*)SvPVX_const(sv)) < rslen) ||
5927 memNE((char*)bp - rslen, rsptr, rslen))
5928 goto screamer; /* go back to the fray */
5929 thats_really_all_folks:
5931 cnt += shortbuffered;
5932 DEBUG_P(PerlIO_printf(Perl_debug_log,
5933 "Screamer: quitting, ptr=%"UVuf", cnt=%ld\n",PTR2UV(ptr),(long)cnt));
5934 PerlIO_set_ptrcnt(fp, (STDCHAR*)ptr, cnt); /* put these back or we're in trouble */
5935 DEBUG_P(PerlIO_printf(Perl_debug_log,
5936 "Screamer: end: FILE * thinks ptr=%"UVuf", cnt=%ld, base=%"UVuf"\n",
5937 PTR2UV(PerlIO_get_ptr(fp)), (long)PerlIO_get_cnt(fp),
5938 PTR2UV(PerlIO_has_base (fp) ? PerlIO_get_base(fp) : 0)));
5940 SvCUR_set(sv, bp - (STDCHAR*)SvPVX_const(sv)); /* set length */
5941 DEBUG_P(PerlIO_printf(Perl_debug_log,
5942 "Screamer: done, len=%ld, string=|%.*s|\n",
5943 (long)SvCUR(sv),(int)SvCUR(sv),SvPVX_const(sv)));
5947 /*The big, slow, and stupid way. */
5948 #ifdef USE_HEAP_INSTEAD_OF_STACK /* Even slower way. */
5949 STDCHAR *buf = NULL;
5950 Newx(buf, 8192, STDCHAR);
5958 register const STDCHAR * const bpe = buf + sizeof(buf);
5960 while ((i = PerlIO_getc(fp)) != EOF && (*bp++ = (STDCHAR)i) != rslast && bp < bpe)
5961 ; /* keep reading */
5965 cnt = PerlIO_read(fp,(char*)buf, sizeof(buf));
5966 /* Accomodate broken VAXC compiler, which applies U8 cast to
5967 * both args of ?: operator, causing EOF to change into 255
5970 i = (U8)buf[cnt - 1];
5976 cnt = 0; /* we do need to re-set the sv even when cnt <= 0 */
5978 sv_catpvn(sv, (char *) buf, cnt);
5980 sv_setpvn(sv, (char *) buf, cnt);
5982 if (i != EOF && /* joy */
5984 SvCUR(sv) < rslen ||
5985 memNE(SvPVX_const(sv) + SvCUR(sv) - rslen, rsptr, rslen)))
5989 * If we're reading from a TTY and we get a short read,
5990 * indicating that the user hit his EOF character, we need
5991 * to notice it now, because if we try to read from the TTY
5992 * again, the EOF condition will disappear.
5994 * The comparison of cnt to sizeof(buf) is an optimization
5995 * that prevents unnecessary calls to feof().
5999 if (!(cnt < (I32)sizeof(buf) && PerlIO_eof(fp)))
6003 #ifdef USE_HEAP_INSTEAD_OF_STACK
6008 if (rspara) { /* have to do this both before and after */
6009 while (i != EOF) { /* to make sure file boundaries work right */
6010 i = PerlIO_getc(fp);
6012 PerlIO_ungetc(fp,i);
6018 return_string_or_null:
6019 return (SvCUR(sv) - append) ? SvPVX(sv) : NULL;
6025 Auto-increment of the value in the SV, doing string to numeric conversion
6026 if necessary. Handles 'get' magic.
6032 Perl_sv_inc(pTHX_ register SV *sv)
6040 if (SvTHINKFIRST(sv)) {
6041 if (SvREADONLY(sv) && SvFAKE(sv))
6042 sv_force_normal(sv);
6043 if (SvREADONLY(sv)) {
6044 if (IN_PERL_RUNTIME)
6045 Perl_croak(aTHX_ PL_no_modify);
6049 if (SvAMAGIC(sv) && AMG_CALLun(sv,inc))
6051 i = PTR2IV(SvRV(sv));
6056 flags = SvFLAGS(sv);
6057 if ((flags & (SVp_NOK|SVp_IOK)) == SVp_NOK) {
6058 /* It's (privately or publicly) a float, but not tested as an
6059 integer, so test it to see. */
6061 flags = SvFLAGS(sv);
6063 if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
6064 /* It's publicly an integer, or privately an integer-not-float */
6065 #ifdef PERL_PRESERVE_IVUV
6069 if (SvUVX(sv) == UV_MAX)
6070 sv_setnv(sv, UV_MAX_P1);
6072 (void)SvIOK_only_UV(sv);
6073 SvUV_set(sv, SvUVX(sv) + 1);
6075 if (SvIVX(sv) == IV_MAX)
6076 sv_setuv(sv, (UV)IV_MAX + 1);
6078 (void)SvIOK_only(sv);
6079 SvIV_set(sv, SvIVX(sv) + 1);
6084 if (flags & SVp_NOK) {
6085 (void)SvNOK_only(sv);
6086 SvNV_set(sv, SvNVX(sv) + 1.0);
6090 if (!(flags & SVp_POK) || !*SvPVX_const(sv)) {
6091 if ((flags & SVTYPEMASK) < SVt_PVIV)
6092 sv_upgrade(sv, ((flags & SVTYPEMASK) > SVt_IV ? SVt_PVIV : SVt_IV));
6093 (void)SvIOK_only(sv);
6098 while (isALPHA(*d)) d++;
6099 while (isDIGIT(*d)) d++;
6101 #ifdef PERL_PRESERVE_IVUV
6102 /* Got to punt this as an integer if needs be, but we don't issue
6103 warnings. Probably ought to make the sv_iv_please() that does
6104 the conversion if possible, and silently. */
6105 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), NULL);
6106 if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
6107 /* Need to try really hard to see if it's an integer.
6108 9.22337203685478e+18 is an integer.
6109 but "9.22337203685478e+18" + 0 is UV=9223372036854779904
6110 so $a="9.22337203685478e+18"; $a+0; $a++
6111 needs to be the same as $a="9.22337203685478e+18"; $a++
6118 /* sv_2iv *should* have made this an NV */
6119 if (flags & SVp_NOK) {
6120 (void)SvNOK_only(sv);
6121 SvNV_set(sv, SvNVX(sv) + 1.0);
6124 /* I don't think we can get here. Maybe I should assert this
6125 And if we do get here I suspect that sv_setnv will croak. NWC
6127 #if defined(USE_LONG_DOUBLE)
6128 DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_inc punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"PERL_PRIgldbl"\n",
6129 SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
6131 DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_inc punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
6132 SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
6135 #endif /* PERL_PRESERVE_IVUV */
6136 sv_setnv(sv,Atof(SvPVX_const(sv)) + 1.0);
6140 while (d >= SvPVX_const(sv)) {
6148 /* MKS: The original code here died if letters weren't consecutive.
6149 * at least it didn't have to worry about non-C locales. The
6150 * new code assumes that ('z'-'a')==('Z'-'A'), letters are
6151 * arranged in order (although not consecutively) and that only
6152 * [A-Za-z] are accepted by isALPHA in the C locale.
6154 if (*d != 'z' && *d != 'Z') {
6155 do { ++*d; } while (!isALPHA(*d));
6158 *(d--) -= 'z' - 'a';
6163 *(d--) -= 'z' - 'a' + 1;
6167 /* oh,oh, the number grew */
6168 SvGROW(sv, SvCUR(sv) + 2);
6169 SvCUR_set(sv, SvCUR(sv) + 1);
6170 for (d = SvPVX(sv) + SvCUR(sv); d > SvPVX_const(sv); d--)
6181 Auto-decrement of the value in the SV, doing string to numeric conversion
6182 if necessary. Handles 'get' magic.
6188 Perl_sv_dec(pTHX_ register SV *sv)
6195 if (SvTHINKFIRST(sv)) {
6196 if (SvREADONLY(sv) && SvFAKE(sv))
6197 sv_force_normal(sv);
6198 if (SvREADONLY(sv)) {
6199 if (IN_PERL_RUNTIME)
6200 Perl_croak(aTHX_ PL_no_modify);
6204 if (SvAMAGIC(sv) && AMG_CALLun(sv,dec))
6206 i = PTR2IV(SvRV(sv));
6211 /* Unlike sv_inc we don't have to worry about string-never-numbers
6212 and keeping them magic. But we mustn't warn on punting */
6213 flags = SvFLAGS(sv);
6214 if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
6215 /* It's publicly an integer, or privately an integer-not-float */
6216 #ifdef PERL_PRESERVE_IVUV
6220 if (SvUVX(sv) == 0) {
6221 (void)SvIOK_only(sv);
6225 (void)SvIOK_only_UV(sv);
6226 SvUV_set(sv, SvUVX(sv) - 1);
6229 if (SvIVX(sv) == IV_MIN)
6230 sv_setnv(sv, (NV)IV_MIN - 1.0);
6232 (void)SvIOK_only(sv);
6233 SvIV_set(sv, SvIVX(sv) - 1);
6238 if (flags & SVp_NOK) {
6239 SvNV_set(sv, SvNVX(sv) - 1.0);
6240 (void)SvNOK_only(sv);
6243 if (!(flags & SVp_POK)) {
6244 if ((flags & SVTYPEMASK) < SVt_PVIV)
6245 sv_upgrade(sv, ((flags & SVTYPEMASK) > SVt_IV) ? SVt_PVIV : SVt_IV);
6247 (void)SvIOK_only(sv);
6250 #ifdef PERL_PRESERVE_IVUV
6252 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), NULL);
6253 if (numtype && !(numtype & IS_NUMBER_INFINITY)) {
6254 /* Need to try really hard to see if it's an integer.
6255 9.22337203685478e+18 is an integer.
6256 but "9.22337203685478e+18" + 0 is UV=9223372036854779904
6257 so $a="9.22337203685478e+18"; $a+0; $a--
6258 needs to be the same as $a="9.22337203685478e+18"; $a--
6265 /* sv_2iv *should* have made this an NV */
6266 if (flags & SVp_NOK) {
6267 (void)SvNOK_only(sv);
6268 SvNV_set(sv, SvNVX(sv) - 1.0);
6271 /* I don't think we can get here. Maybe I should assert this
6272 And if we do get here I suspect that sv_setnv will croak. NWC
6274 #if defined(USE_LONG_DOUBLE)
6275 DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_dec punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"PERL_PRIgldbl"\n",
6276 SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
6278 DEBUG_c(PerlIO_printf(Perl_debug_log,"sv_dec punt failed to convert '%s' to IOK or NOKp, UV=0x%"UVxf" NV=%"NVgf"\n",
6279 SvPVX_const(sv), SvIVX(sv), SvNVX(sv)));
6283 #endif /* PERL_PRESERVE_IVUV */
6284 sv_setnv(sv,Atof(SvPVX_const(sv)) - 1.0); /* punt */
6288 =for apidoc sv_mortalcopy
6290 Creates a new SV which is a copy of the original SV (using C<sv_setsv>).
6291 The new SV is marked as mortal. It will be destroyed "soon", either by an
6292 explicit call to FREETMPS, or by an implicit call at places such as
6293 statement boundaries. See also C<sv_newmortal> and C<sv_2mortal>.
6298 /* Make a string that will exist for the duration of the expression
6299 * evaluation. Actually, it may have to last longer than that, but
6300 * hopefully we won't free it until it has been assigned to a
6301 * permanent location. */
6304 Perl_sv_mortalcopy(pTHX_ SV *oldstr)
6309 sv_setsv(sv,oldstr);
6311 PL_tmps_stack[++PL_tmps_ix] = sv;
6317 =for apidoc sv_newmortal
6319 Creates a new null SV which is mortal. The reference count of the SV is
6320 set to 1. It will be destroyed "soon", either by an explicit call to
6321 FREETMPS, or by an implicit call at places such as statement boundaries.
6322 See also C<sv_mortalcopy> and C<sv_2mortal>.
6328 Perl_sv_newmortal(pTHX)
6333 SvFLAGS(sv) = SVs_TEMP;
6335 PL_tmps_stack[++PL_tmps_ix] = sv;
6340 =for apidoc sv_2mortal
6342 Marks an existing SV as mortal. The SV will be destroyed "soon", either
6343 by an explicit call to FREETMPS, or by an implicit call at places such as
6344 statement boundaries. SvTEMP() is turned on which means that the SV's
6345 string buffer can be "stolen" if this SV is copied. See also C<sv_newmortal>
6346 and C<sv_mortalcopy>.
6352 Perl_sv_2mortal(pTHX_ register SV *sv)
6356 if (SvREADONLY(sv) && SvIMMORTAL(sv))
6359 PL_tmps_stack[++PL_tmps_ix] = sv;
6367 Creates a new SV and copies a string into it. The reference count for the
6368 SV is set to 1. If C<len> is zero, Perl will compute the length using
6369 strlen(). For efficiency, consider using C<newSVpvn> instead.
6375 Perl_newSVpv(pTHX_ const char *s, STRLEN len)
6380 sv_setpvn(sv, s, len || s == NULL ? len : strlen(s));
6385 =for apidoc newSVpvn
6387 Creates a new SV and copies a string into it. The reference count for the
6388 SV is set to 1. Note that if C<len> is zero, Perl will create a zero length
6389 string. You are responsible for ensuring that the source string is at least
6390 C<len> bytes long. If the C<s> argument is NULL the new SV will be undefined.
6396 Perl_newSVpvn(pTHX_ const char *s, STRLEN len)
6401 sv_setpvn(sv,s,len);
6407 =for apidoc newSVhek
6409 Creates a new SV from the hash key structure. It will generate scalars that
6410 point to the shared string table where possible. Returns a new (undefined)
6411 SV if the hek is NULL.
6417 Perl_newSVhek(pTHX_ const HEK *hek)
6426 if (HEK_LEN(hek) == HEf_SVKEY) {
6427 return newSVsv(*(SV**)HEK_KEY(hek));
6429 const int flags = HEK_FLAGS(hek);
6430 if (flags & HVhek_WASUTF8) {
6432 Andreas would like keys he put in as utf8 to come back as utf8
6434 STRLEN utf8_len = HEK_LEN(hek);
6435 const U8 *as_utf8 = bytes_to_utf8 ((U8*)HEK_KEY(hek), &utf8_len);
6436 SV * const sv = newSVpvn ((const char*)as_utf8, utf8_len);
6439 Safefree (as_utf8); /* bytes_to_utf8() allocates a new string */
6441 } else if (flags & (HVhek_REHASH|HVhek_UNSHARED)) {
6442 /* We don't have a pointer to the hv, so we have to replicate the
6443 flag into every HEK. This hv is using custom a hasing
6444 algorithm. Hence we can't return a shared string scalar, as
6445 that would contain the (wrong) hash value, and might get passed
6446 into an hv routine with a regular hash.
6447 Similarly, a hash that isn't using shared hash keys has to have
6448 the flag in every key so that we know not to try to call
6449 share_hek_kek on it. */
6451 SV * const sv = newSVpvn (HEK_KEY(hek), HEK_LEN(hek));
6456 /* This will be overwhelminly the most common case. */
6457 return newSVpvn_share(HEK_KEY(hek),
6458 (HEK_UTF8(hek) ? -HEK_LEN(hek) : HEK_LEN(hek)),
6464 =for apidoc newSVpvn_share
6466 Creates a new SV with its SvPVX_const pointing to a shared string in the string
6467 table. If the string does not already exist in the table, it is created
6468 first. Turns on READONLY and FAKE. The string's hash is stored in the UV
6469 slot of the SV; if the C<hash> parameter is non-zero, that value is used;
6470 otherwise the hash is computed. The idea here is that as the string table
6471 is used for shared hash keys these strings will have SvPVX_const == HeKEY and
6472 hash lookup will avoid string compare.
6478 Perl_newSVpvn_share(pTHX_ const char *src, I32 len, U32 hash)
6481 bool is_utf8 = FALSE;
6482 const char *const orig_src = src;
6485 STRLEN tmplen = -len;
6487 /* See the note in hv.c:hv_fetch() --jhi */
6488 src = (char*)bytes_from_utf8((U8*)src, &tmplen, &is_utf8);
6492 PERL_HASH(hash, src, len);
6494 sv_upgrade(sv, SVt_PVIV);
6495 SvPV_set(sv, sharepvn(src, is_utf8?-len:len, hash));
6504 if (src != orig_src)
6510 #if defined(PERL_IMPLICIT_CONTEXT)
6512 /* pTHX_ magic can't cope with varargs, so this is a no-context
6513 * version of the main function, (which may itself be aliased to us).
6514 * Don't access this version directly.
6518 Perl_newSVpvf_nocontext(const char* pat, ...)
6523 va_start(args, pat);
6524 sv = vnewSVpvf(pat, &args);
6531 =for apidoc newSVpvf
6533 Creates a new SV and initializes it with the string formatted like
6540 Perl_newSVpvf(pTHX_ const char* pat, ...)
6544 va_start(args, pat);
6545 sv = vnewSVpvf(pat, &args);
6550 /* backend for newSVpvf() and newSVpvf_nocontext() */
6553 Perl_vnewSVpvf(pTHX_ const char* pat, va_list* args)
6557 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
6564 Creates a new SV and copies a floating point value into it.
6565 The reference count for the SV is set to 1.
6571 Perl_newSVnv(pTHX_ NV n)
6583 Creates a new SV and copies an integer into it. The reference count for the
6590 Perl_newSViv(pTHX_ IV i)
6602 Creates a new SV and copies an unsigned integer into it.
6603 The reference count for the SV is set to 1.
6609 Perl_newSVuv(pTHX_ UV u)
6619 =for apidoc newRV_noinc
6621 Creates an RV wrapper for an SV. The reference count for the original
6622 SV is B<not> incremented.
6628 Perl_newRV_noinc(pTHX_ SV *tmpRef)
6633 sv_upgrade(sv, SVt_RV);
6635 SvRV_set(sv, tmpRef);
6640 /* newRV_inc is the official function name to use now.
6641 * newRV_inc is in fact #defined to newRV in sv.h
6645 Perl_newRV(pTHX_ SV *sv)
6647 return newRV_noinc(SvREFCNT_inc_simple_NN(sv));
6653 Creates a new SV which is an exact duplicate of the original SV.
6660 Perl_newSVsv(pTHX_ register SV *old)
6666 if (SvTYPE(old) == SVTYPEMASK) {
6667 if (ckWARN_d(WARN_INTERNAL))
6668 Perl_warner(aTHX_ packWARN(WARN_INTERNAL), "semi-panic: attempt to dup freed string");
6672 /* SV_GMAGIC is the default for sv_setv()
6673 SV_NOSTEAL prevents TEMP buffers being, well, stolen, and saves games
6674 with SvTEMP_off and SvTEMP_on round a call to sv_setsv. */
6675 sv_setsv_flags(sv, old, SV_GMAGIC | SV_NOSTEAL);
6680 =for apidoc sv_reset
6682 Underlying implementation for the C<reset> Perl function.
6683 Note that the perl-level function is vaguely deprecated.
6689 Perl_sv_reset(pTHX_ register char *s, HV *stash)
6692 char todo[PERL_UCHAR_MAX+1];
6697 if (!*s) { /* reset ?? searches */
6698 for (pm = HvPMROOT(stash); pm; pm = pm->op_pmnext) {
6699 pm->op_pmdynflags &= ~PMdf_USED;
6704 /* reset variables */
6706 if (!HvARRAY(stash))
6709 Zero(todo, 256, char);
6712 I32 i = (unsigned char)*s;
6716 max = (unsigned char)*s++;
6717 for ( ; i <= max; i++) {
6720 for (i = 0; i <= (I32) HvMAX(stash); i++) {
6722 for (entry = HvARRAY(stash)[i];
6724 entry = HeNEXT(entry))
6729 if (!todo[(U8)*HeKEY(entry)])
6731 gv = (GV*)HeVAL(entry);
6734 if (SvTHINKFIRST(sv)) {
6735 if (!SvREADONLY(sv) && SvROK(sv))
6737 /* XXX Is this continue a bug? Why should THINKFIRST
6738 exempt us from resetting arrays and hashes? */
6742 if (SvTYPE(sv) >= SVt_PV) {
6744 if (SvPVX_const(sv) != NULL)
6752 if (GvHV(gv) && !HvNAME_get(GvHV(gv))) {
6754 Perl_die(aTHX_ "Can't reset %%ENV on this system");
6757 # if defined(USE_ENVIRON_ARRAY)
6760 # endif /* USE_ENVIRON_ARRAY */
6771 Using various gambits, try to get an IO from an SV: the IO slot if its a
6772 GV; or the recursive result if we're an RV; or the IO slot of the symbol
6773 named after the PV if we're a string.
6779 Perl_sv_2io(pTHX_ SV *sv)
6784 switch (SvTYPE(sv)) {
6792 Perl_croak(aTHX_ "Bad filehandle: %s", GvNAME(gv));
6796 Perl_croak(aTHX_ PL_no_usym, "filehandle");
6798 return sv_2io(SvRV(sv));
6799 gv = gv_fetchsv(sv, 0, SVt_PVIO);
6805 Perl_croak(aTHX_ "Bad filehandle: %"SVf, (void*)sv);
6814 Using various gambits, try to get a CV from an SV; in addition, try if
6815 possible to set C<*st> and C<*gvp> to the stash and GV associated with it.
6816 The flags in C<lref> are passed to sv_fetchsv.
6822 Perl_sv_2cv(pTHX_ SV *sv, HV **st, GV **gvp, I32 lref)
6832 switch (SvTYPE(sv)) {
6851 SV * const *sp = &sv; /* Used in tryAMAGICunDEREF macro. */
6852 tryAMAGICunDEREF(to_cv);
6855 if (SvTYPE(sv) == SVt_PVCV) {
6864 Perl_croak(aTHX_ "Not a subroutine reference");
6869 gv = gv_fetchsv(sv, lref, SVt_PVCV);
6875 /* Some flags to gv_fetchsv mean don't really create the GV */
6876 if (SvTYPE(gv) != SVt_PVGV) {
6882 if (lref && !GvCVu(gv)) {
6886 gv_efullname3(tmpsv, gv, NULL);
6887 /* XXX this is probably not what they think they're getting.
6888 * It has the same effect as "sub name;", i.e. just a forward
6890 newSUB(start_subparse(FALSE, 0),
6891 newSVOP(OP_CONST, 0, tmpsv),
6895 Perl_croak(aTHX_ "Unable to create sub named \"%"SVf"\"",
6905 Returns true if the SV has a true value by Perl's rules.
6906 Use the C<SvTRUE> macro instead, which may call C<sv_true()> or may
6907 instead use an in-line version.
6913 Perl_sv_true(pTHX_ register SV *sv)
6918 register const XPV* const tXpv = (XPV*)SvANY(sv);
6920 (tXpv->xpv_cur > 1 ||
6921 (tXpv->xpv_cur && *tXpv->xpv_pv != '0')))
6928 return SvIVX(sv) != 0;
6931 return SvNVX(sv) != 0.0;
6933 return sv_2bool(sv);
6939 =for apidoc sv_pvn_force
6941 Get a sensible string out of the SV somehow.
6942 A private implementation of the C<SvPV_force> macro for compilers which
6943 can't cope with complex macro expressions. Always use the macro instead.
6945 =for apidoc sv_pvn_force_flags
6947 Get a sensible string out of the SV somehow.
6948 If C<flags> has C<SV_GMAGIC> bit set, will C<mg_get> on C<sv> if
6949 appropriate, else not. C<sv_pvn_force> and C<sv_pvn_force_nomg> are
6950 implemented in terms of this function.
6951 You normally want to use the various wrapper macros instead: see
6952 C<SvPV_force> and C<SvPV_force_nomg>
6958 Perl_sv_pvn_force_flags(pTHX_ SV *sv, STRLEN *lp, I32 flags)
6961 if (SvTHINKFIRST(sv) && !SvROK(sv))
6962 sv_force_normal(sv);
6972 if (SvREADONLY(sv) && !(flags & SV_MUTABLE_RETURN)) {
6973 const char * const ref = sv_reftype(sv,0);
6975 Perl_croak(aTHX_ "Can't coerce readonly %s to string in %s",
6976 ref, OP_NAME(PL_op));
6978 Perl_croak(aTHX_ "Can't coerce readonly %s to string", ref);
6980 if (SvTYPE(sv) > SVt_PVLV && SvTYPE(sv) != SVt_PVFM)
6981 Perl_croak(aTHX_ "Can't coerce %s to string in %s", sv_reftype(sv,0),
6983 s = sv_2pv_flags(sv, &len, flags);
6987 if (s != SvPVX_const(sv)) { /* Almost, but not quite, sv_setpvn() */
6990 (void)SvUPGRADE(sv, SVt_PV); /* Never FALSE */
6991 SvGROW(sv, len + 1);
6992 Move(s,SvPVX(sv),len,char);
6997 SvPOK_on(sv); /* validate pointer */
6999 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
7000 PTR2UV(sv),SvPVX_const(sv)));
7003 return SvPVX_mutable(sv);
7007 =for apidoc sv_pvbyten_force
7009 The backend for the C<SvPVbytex_force> macro. Always use the macro instead.
7015 Perl_sv_pvbyten_force(pTHX_ SV *sv, STRLEN *lp)
7017 sv_pvn_force(sv,lp);
7018 sv_utf8_downgrade(sv,0);
7024 =for apidoc sv_pvutf8n_force
7026 The backend for the C<SvPVutf8x_force> macro. Always use the macro instead.
7032 Perl_sv_pvutf8n_force(pTHX_ SV *sv, STRLEN *lp)
7034 sv_pvn_force(sv,lp);
7035 sv_utf8_upgrade(sv);
7041 =for apidoc sv_reftype
7043 Returns a string describing what the SV is a reference to.
7049 Perl_sv_reftype(pTHX_ SV *sv, int ob)
7051 /* The fact that I don't need to downcast to char * everywhere, only in ?:
7052 inside return suggests a const propagation bug in g++. */
7053 if (ob && SvOBJECT(sv)) {
7054 char * const name = HvNAME_get(SvSTASH(sv));
7055 return name ? name : (char *) "__ANON__";
7058 switch (SvTYPE(sv)) {
7073 case SVt_PVLV: return (char *) (SvROK(sv) ? "REF"
7074 /* tied lvalues should appear to be
7075 * scalars for backwards compatitbility */
7076 : (LvTYPE(sv) == 't' || LvTYPE(sv) == 'T')
7077 ? "SCALAR" : "LVALUE");
7078 case SVt_PVAV: return "ARRAY";
7079 case SVt_PVHV: return "HASH";
7080 case SVt_PVCV: return "CODE";
7081 case SVt_PVGV: return "GLOB";
7082 case SVt_PVFM: return "FORMAT";
7083 case SVt_PVIO: return "IO";
7084 default: return "UNKNOWN";
7090 =for apidoc sv_isobject
7092 Returns a boolean indicating whether the SV is an RV pointing to a blessed
7093 object. If the SV is not an RV, or if the object is not blessed, then this
7100 Perl_sv_isobject(pTHX_ SV *sv)
7116 Returns a boolean indicating whether the SV is blessed into the specified
7117 class. This does not check for subtypes; use C<sv_derived_from> to verify
7118 an inheritance relationship.
7124 Perl_sv_isa(pTHX_ SV *sv, const char *name)
7135 hvname = HvNAME_get(SvSTASH(sv));
7139 return strEQ(hvname, name);
7145 Creates a new SV for the RV, C<rv>, to point to. If C<rv> is not an RV then
7146 it will be upgraded to one. If C<classname> is non-null then the new SV will
7147 be blessed in the specified package. The new SV is returned and its
7148 reference count is 1.
7154 Perl_newSVrv(pTHX_ SV *rv, const char *classname)
7160 SV_CHECK_THINKFIRST(rv);
7163 if (SvTYPE(rv) >= SVt_PVMG) {
7164 const U32 refcnt = SvREFCNT(rv);
7168 SvREFCNT(rv) = refcnt;
7170 sv_upgrade(rv, SVt_RV);
7171 } else if (SvROK(rv)) {
7172 SvREFCNT_dec(SvRV(rv));
7173 } else if (SvTYPE(rv) < SVt_RV)
7174 sv_upgrade(rv, SVt_RV);
7175 else if (SvTYPE(rv) > SVt_RV) {
7186 HV* const stash = gv_stashpv(classname, TRUE);
7187 (void)sv_bless(rv, stash);
7193 =for apidoc sv_setref_pv
7195 Copies a pointer into a new SV, optionally blessing the SV. The C<rv>
7196 argument will be upgraded to an RV. That RV will be modified to point to
7197 the new SV. If the C<pv> argument is NULL then C<PL_sv_undef> will be placed
7198 into the SV. The C<classname> argument indicates the package for the
7199 blessing. Set C<classname> to C<NULL> to avoid the blessing. The new SV
7200 will have a reference count of 1, and the RV will be returned.
7202 Do not use with other Perl types such as HV, AV, SV, CV, because those
7203 objects will become corrupted by the pointer copy process.
7205 Note that C<sv_setref_pvn> copies the string while this copies the pointer.
7211 Perl_sv_setref_pv(pTHX_ SV *rv, const char *classname, void *pv)
7214 sv_setsv(rv, &PL_sv_undef);
7218 sv_setiv(newSVrv(rv,classname), PTR2IV(pv));
7223 =for apidoc sv_setref_iv
7225 Copies an integer into a new SV, optionally blessing the SV. The C<rv>
7226 argument will be upgraded to an RV. That RV will be modified to point to
7227 the new SV. The C<classname> argument indicates the package for the
7228 blessing. Set C<classname> to C<NULL> to avoid the blessing. The new SV
7229 will have a reference count of 1, and the RV will be returned.
7235 Perl_sv_setref_iv(pTHX_ SV *rv, const char *classname, IV iv)
7237 sv_setiv(newSVrv(rv,classname), iv);
7242 =for apidoc sv_setref_uv
7244 Copies an unsigned integer into a new SV, optionally blessing the SV. The C<rv>
7245 argument will be upgraded to an RV. That RV will be modified to point to
7246 the new SV. The C<classname> argument indicates the package for the
7247 blessing. Set C<classname> to C<NULL> to avoid the blessing. The new SV
7248 will have a reference count of 1, and the RV will be returned.
7254 Perl_sv_setref_uv(pTHX_ SV *rv, const char *classname, UV uv)
7256 sv_setuv(newSVrv(rv,classname), uv);
7261 =for apidoc sv_setref_nv
7263 Copies a double into a new SV, optionally blessing the SV. The C<rv>
7264 argument will be upgraded to an RV. That RV will be modified to point to
7265 the new SV. The C<classname> argument indicates the package for the
7266 blessing. Set C<classname> to C<NULL> to avoid the blessing. The new SV
7267 will have a reference count of 1, and the RV will be returned.
7273 Perl_sv_setref_nv(pTHX_ SV *rv, const char *classname, NV nv)
7275 sv_setnv(newSVrv(rv,classname), nv);
7280 =for apidoc sv_setref_pvn
7282 Copies a string into a new SV, optionally blessing the SV. The length of the
7283 string must be specified with C<n>. The C<rv> argument will be upgraded to
7284 an RV. That RV will be modified to point to the new SV. The C<classname>
7285 argument indicates the package for the blessing. Set C<classname> to
7286 C<NULL> to avoid the blessing. The new SV will have a reference count
7287 of 1, and the RV will be returned.
7289 Note that C<sv_setref_pv> copies the pointer while this copies the string.
7295 Perl_sv_setref_pvn(pTHX_ SV *rv, const char *classname, char *pv, STRLEN n)
7297 sv_setpvn(newSVrv(rv,classname), pv, n);
7301 /* This is a hack to cope with reblessing from class with overloading magic to
7302 one without (or the other way). Search for every reference pointing to the
7303 object. Can't use S_visit() because we would need to pass a parameter to
7306 S_reset_amagic(pTHX_ SV *rv, const bool on) {
7307 /* It is assumed that you've already turned magic on/off on rv */
7309 SV *const target = SvRV(rv);
7310 /* Less 1 for the reference we've already dealt with. */
7311 U32 how_many = SvREFCNT(target) - 1;
7314 if (SvMAGICAL(target) && (mg = mg_find(target, PERL_MAGIC_backref))) {
7315 /* Back referneces also need to be found, but aren't part of the
7316 target's reference count. */
7317 how_many += 1 + av_len((AV*)mg->mg_obj);
7321 /* There was only 1 reference to this object. */
7325 for (sva = PL_sv_arenaroot; sva; sva = (SV*)SvANY(sva)) {
7326 register const SV * const svend = &sva[SvREFCNT(sva)];
7328 for (sv = sva + 1; sv < svend; ++sv) {
7329 if (SvTYPE(sv) != SVTYPEMASK
7330 && (sv->sv_flags & SVf_ROK) == SVf_ROK
7332 && SvRV(sv) == target
7338 if (--how_many == 0) {
7339 /* We have found them all. */
7348 =for apidoc sv_bless
7350 Blesses an SV into a specified package. The SV must be an RV. The package
7351 must be designated by its stash (see C<gv_stashpv()>). The reference count
7352 of the SV is unaffected.
7358 Perl_sv_bless(pTHX_ SV *sv, HV *stash)
7362 Perl_croak(aTHX_ "Can't bless non-reference value");
7364 if (SvFLAGS(tmpRef) & (SVs_OBJECT|SVf_READONLY)) {
7365 if (SvREADONLY(tmpRef))
7366 Perl_croak(aTHX_ PL_no_modify);
7367 if (SvOBJECT(tmpRef)) {
7368 if (SvTYPE(tmpRef) != SVt_PVIO)
7370 SvREFCNT_dec(SvSTASH(tmpRef));
7373 SvOBJECT_on(tmpRef);
7374 if (SvTYPE(tmpRef) != SVt_PVIO)
7376 (void)SvUPGRADE(tmpRef, SVt_PVMG);
7377 SvSTASH_set(tmpRef, (HV*)SvREFCNT_inc_simple(stash));
7379 if (Gv_AMG(stash)) {
7380 if (!SvAMAGIC(sv)) {
7382 S_reset_amagic(aTHX_ sv, TRUE);
7387 S_reset_amagic(aTHX_ sv, FALSE);
7391 if(SvSMAGICAL(tmpRef))
7392 if(mg_find(tmpRef, PERL_MAGIC_ext) || mg_find(tmpRef, PERL_MAGIC_uvar))
7400 /* Downgrades a PVGV to a PVMG.
7404 S_sv_unglob(pTHX_ SV *sv)
7408 assert(SvTYPE(sv) == SVt_PVGV);
7413 SvREFCNT_dec(GvSTASH(sv));
7416 sv_unmagic(sv, PERL_MAGIC_glob);
7417 Safefree(GvNAME(sv));
7420 /* need to keep SvANY(sv) in the right arena */
7421 xpvmg = new_XPVMG();
7422 StructCopy(SvANY(sv), xpvmg, XPVMG);
7423 del_XPVGV(SvANY(sv));
7426 SvFLAGS(sv) &= ~SVTYPEMASK;
7427 SvFLAGS(sv) |= SVt_PVMG;
7431 =for apidoc sv_unref_flags
7433 Unsets the RV status of the SV, and decrements the reference count of
7434 whatever was being referenced by the RV. This can almost be thought of
7435 as a reversal of C<newSVrv>. The C<cflags> argument can contain
7436 C<SV_IMMEDIATE_UNREF> to force the reference count to be decremented
7437 (otherwise the decrementing is conditional on the reference count being
7438 different from one or the reference being a readonly SV).
7445 Perl_sv_unref_flags(pTHX_ SV *sv, U32 flags)
7447 SV const * rv = SvRV(sv);
7449 if (SvWEAKREF(sv)) {
7457 /* You can't have a || SvREADONLY(rv) here, as $a = $$a, where $a was
7458 assigned to as BEGIN {$a = \"Foo"} will fail. */
7459 if (SvREFCNT(rv) != 1 || (flags & SV_IMMEDIATE_UNREF))
7461 else /* XXX Hack, but hard to make $a=$a->[1] work otherwise */
7462 sv_2mortal((SV *)rv); /* Schedule for freeing later */
7466 =for apidoc sv_untaint
7468 Untaint an SV. Use C<SvTAINTED_off> instead.
7473 Perl_sv_untaint(pTHX_ SV *sv)
7475 if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
7476 MAGIC * const mg = mg_find(sv, PERL_MAGIC_taint);
7483 =for apidoc sv_tainted
7485 Test an SV for taintedness. Use C<SvTAINTED> instead.
7490 Perl_sv_tainted(pTHX_ SV *sv)
7492 if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
7493 const MAGIC * const mg = mg_find(sv, PERL_MAGIC_taint);
7494 if (mg && (mg->mg_len & 1) )
7501 =for apidoc sv_setpviv
7503 Copies an integer into the given SV, also updating its string value.
7504 Does not handle 'set' magic. See C<sv_setpviv_mg>.
7510 Perl_sv_setpviv(pTHX_ SV *sv, IV iv)
7512 char buf[TYPE_CHARS(UV)];
7514 char * const ptr = uiv_2buf(buf, iv, 0, 0, &ebuf);
7516 sv_setpvn(sv, ptr, ebuf - ptr);
7520 =for apidoc sv_setpviv_mg
7522 Like C<sv_setpviv>, but also handles 'set' magic.
7528 Perl_sv_setpviv_mg(pTHX_ SV *sv, IV iv)
7534 #if defined(PERL_IMPLICIT_CONTEXT)
7536 /* pTHX_ magic can't cope with varargs, so this is a no-context
7537 * version of the main function, (which may itself be aliased to us).
7538 * Don't access this version directly.
7542 Perl_sv_setpvf_nocontext(SV *sv, const char* pat, ...)
7546 va_start(args, pat);
7547 sv_vsetpvf(sv, pat, &args);
7551 /* pTHX_ magic can't cope with varargs, so this is a no-context
7552 * version of the main function, (which may itself be aliased to us).
7553 * Don't access this version directly.
7557 Perl_sv_setpvf_mg_nocontext(SV *sv, const char* pat, ...)
7561 va_start(args, pat);
7562 sv_vsetpvf_mg(sv, pat, &args);
7568 =for apidoc sv_setpvf
7570 Works like C<sv_catpvf> but copies the text into the SV instead of
7571 appending it. Does not handle 'set' magic. See C<sv_setpvf_mg>.
7577 Perl_sv_setpvf(pTHX_ SV *sv, const char* pat, ...)
7580 va_start(args, pat);
7581 sv_vsetpvf(sv, pat, &args);
7586 =for apidoc sv_vsetpvf
7588 Works like C<sv_vcatpvf> but copies the text into the SV instead of
7589 appending it. Does not handle 'set' magic. See C<sv_vsetpvf_mg>.
7591 Usually used via its frontend C<sv_setpvf>.
7597 Perl_sv_vsetpvf(pTHX_ SV *sv, const char* pat, va_list* args)
7599 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
7603 =for apidoc sv_setpvf_mg
7605 Like C<sv_setpvf>, but also handles 'set' magic.
7611 Perl_sv_setpvf_mg(pTHX_ SV *sv, const char* pat, ...)
7614 va_start(args, pat);
7615 sv_vsetpvf_mg(sv, pat, &args);
7620 =for apidoc sv_vsetpvf_mg
7622 Like C<sv_vsetpvf>, but also handles 'set' magic.
7624 Usually used via its frontend C<sv_setpvf_mg>.
7630 Perl_sv_vsetpvf_mg(pTHX_ SV *sv, const char* pat, va_list* args)
7632 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
7636 #if defined(PERL_IMPLICIT_CONTEXT)
7638 /* pTHX_ magic can't cope with varargs, so this is a no-context
7639 * version of the main function, (which may itself be aliased to us).
7640 * Don't access this version directly.
7644 Perl_sv_catpvf_nocontext(SV *sv, const char* pat, ...)
7648 va_start(args, pat);
7649 sv_vcatpvf(sv, pat, &args);
7653 /* pTHX_ magic can't cope with varargs, so this is a no-context
7654 * version of the main function, (which may itself be aliased to us).
7655 * Don't access this version directly.
7659 Perl_sv_catpvf_mg_nocontext(SV *sv, const char* pat, ...)
7663 va_start(args, pat);
7664 sv_vcatpvf_mg(sv, pat, &args);
7670 =for apidoc sv_catpvf
7672 Processes its arguments like C<sprintf> and appends the formatted
7673 output to an SV. If the appended data contains "wide" characters
7674 (including, but not limited to, SVs with a UTF-8 PV formatted with %s,
7675 and characters >255 formatted with %c), the original SV might get
7676 upgraded to UTF-8. Handles 'get' magic, but not 'set' magic. See
7677 C<sv_catpvf_mg>. If the original SV was UTF-8, the pattern should be
7678 valid UTF-8; if the original SV was bytes, the pattern should be too.
7683 Perl_sv_catpvf(pTHX_ SV *sv, const char* pat, ...)
7686 va_start(args, pat);
7687 sv_vcatpvf(sv, pat, &args);
7692 =for apidoc sv_vcatpvf
7694 Processes its arguments like C<vsprintf> and appends the formatted output
7695 to an SV. Does not handle 'set' magic. See C<sv_vcatpvf_mg>.
7697 Usually used via its frontend C<sv_catpvf>.
7703 Perl_sv_vcatpvf(pTHX_ SV *sv, const char* pat, va_list* args)
7705 sv_vcatpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
7709 =for apidoc sv_catpvf_mg
7711 Like C<sv_catpvf>, but also handles 'set' magic.
7717 Perl_sv_catpvf_mg(pTHX_ SV *sv, const char* pat, ...)
7720 va_start(args, pat);
7721 sv_vcatpvf_mg(sv, pat, &args);
7726 =for apidoc sv_vcatpvf_mg
7728 Like C<sv_vcatpvf>, but also handles 'set' magic.
7730 Usually used via its frontend C<sv_catpvf_mg>.
7736 Perl_sv_vcatpvf_mg(pTHX_ SV *sv, const char* pat, va_list* args)
7738 sv_vcatpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
7743 =for apidoc sv_vsetpvfn
7745 Works like C<sv_vcatpvfn> but copies the text into the SV instead of
7748 Usually used via one of its frontends C<sv_vsetpvf> and C<sv_vsetpvf_mg>.
7754 Perl_sv_vsetpvfn(pTHX_ SV *sv, const char *pat, STRLEN patlen, va_list *args, SV **svargs, I32 svmax, bool *maybe_tainted)
7756 sv_setpvn(sv, "", 0);
7757 sv_vcatpvfn(sv, pat, patlen, args, svargs, svmax, maybe_tainted);
7761 S_expect_number(pTHX_ char** pattern)
7764 switch (**pattern) {
7765 case '1': case '2': case '3':
7766 case '4': case '5': case '6':
7767 case '7': case '8': case '9':
7768 var = *(*pattern)++ - '0';
7769 while (isDIGIT(**pattern)) {
7770 const I32 tmp = var * 10 + (*(*pattern)++ - '0');
7772 Perl_croak(aTHX_ "Integer overflow in format string for %s", (PL_op ? OP_NAME(PL_op) : "sv_vcatpvfn"));
7780 S_F0convert(NV nv, char *endbuf, STRLEN *len)
7782 const int neg = nv < 0;
7791 if (uv & 1 && uv == nv)
7792 uv--; /* Round to even */
7794 const unsigned dig = uv % 10;
7807 =for apidoc sv_vcatpvfn
7809 Processes its arguments like C<vsprintf> and appends the formatted output
7810 to an SV. Uses an array of SVs if the C style variable argument list is
7811 missing (NULL). When running with taint checks enabled, indicates via
7812 C<maybe_tainted> if results are untrustworthy (often due to the use of
7815 XXX Except that it maybe_tainted is never assigned to.
7817 Usually used via one of its frontends C<sv_vcatpvf> and C<sv_vcatpvf_mg>.
7822 /* XXX maybe_tainted is never assigned to, so the doc above is lying. */
7825 Perl_sv_vcatpvfn(pTHX_ SV *sv, const char *pat, STRLEN patlen, va_list *args, SV **svargs, I32 svmax, bool *maybe_tainted)
7832 static const char nullstr[] = "(null)";
7834 bool has_utf8 = DO_UTF8(sv); /* has the result utf8? */
7835 const bool pat_utf8 = has_utf8; /* the pattern is in utf8? */
7837 /* Times 4: a decimal digit takes more than 3 binary digits.
7838 * NV_DIG: mantissa takes than many decimal digits.
7839 * Plus 32: Playing safe. */
7840 char ebuf[IV_DIG * 4 + NV_DIG + 32];
7841 /* large enough for "%#.#f" --chip */
7842 /* what about long double NVs? --jhi */
7844 PERL_UNUSED_ARG(maybe_tainted);
7846 /* no matter what, this is a string now */
7847 (void)SvPV_force(sv, origlen);
7849 /* special-case "", "%s", and "%_" */
7852 if (patlen == 2 && pat[0] == '%') {
7856 const char * const s = va_arg(*args, char*);
7857 sv_catpv(sv, s ? s : nullstr);
7859 else if (svix < svmax) {
7860 sv_catsv(sv, *svargs);
7865 argsv = va_arg(*args, SV*);
7866 sv_catsv(sv, argsv);
7869 /* See comment on '_' below */
7874 #ifndef USE_LONG_DOUBLE
7875 /* special-case "%.<number>[gf]" */
7876 if ( !args && patlen <= 5 && pat[0] == '%' && pat[1] == '.'
7877 && (pat[patlen-1] == 'g' || pat[patlen-1] == 'f') ) {
7878 unsigned digits = 0;
7882 while (*pp >= '0' && *pp <= '9')
7883 digits = 10 * digits + (*pp++ - '0');
7884 if (pp - pat == (int)patlen - 1) {
7892 /* Add check for digits != 0 because it seems that some
7893 gconverts are buggy in this case, and we don't yet have
7894 a Configure test for this. */
7895 if (digits && digits < sizeof(ebuf) - NV_DIG - 10) {
7896 /* 0, point, slack */
7897 Gconvert(nv, (int)digits, 0, ebuf);
7899 if (*ebuf) /* May return an empty string for digits==0 */
7902 } else if (!digits) {
7905 if ((p = F0convert(nv, ebuf + sizeof ebuf, &l))) {
7906 sv_catpvn(sv, p, l);
7912 #endif /* !USE_LONG_DOUBLE */
7914 if (!args && svix < svmax && DO_UTF8(*svargs))
7917 patend = (char*)pat + patlen;
7918 for (p = (char*)pat; p < patend; p = q) {
7921 bool vectorize = FALSE;
7922 bool vectorarg = FALSE;
7923 bool vec_utf8 = FALSE;
7929 bool has_precis = FALSE;
7931 const I32 osvix = svix;
7932 bool is_utf8 = FALSE; /* is this item utf8? */
7933 #ifdef HAS_LDBL_SPRINTF_BUG
7934 /* This is to try to fix a bug with irix/nonstop-ux/powerux and
7935 with sfio - Allen <allens@cpan.org> */
7936 bool fix_ldbl_sprintf_bug = FALSE;
7940 U8 utf8buf[UTF8_MAXBYTES+1];
7941 STRLEN esignlen = 0;
7943 const char *eptr = NULL;
7946 const U8 *vecstr = NULL;
7953 /* we need a long double target in case HAS_LONG_DOUBLE but
7956 #if defined(HAS_LONG_DOUBLE) && LONG_DOUBLESIZE > DOUBLESIZE
7964 const char *dotstr = ".";
7965 STRLEN dotstrlen = 1;
7966 I32 efix = 0; /* explicit format parameter index */
7967 I32 ewix = 0; /* explicit width index */
7968 I32 epix = 0; /* explicit precision index */
7969 I32 evix = 0; /* explicit vector index */
7970 bool asterisk = FALSE;
7972 /* echo everything up to the next format specification */
7973 for (q = p; q < patend && *q != '%'; ++q) ;
7975 if (has_utf8 && !pat_utf8)
7976 sv_catpvn_utf8_upgrade(sv, p, q - p, nsv);
7978 sv_catpvn(sv, p, q - p);
7985 We allow format specification elements in this order:
7986 \d+\$ explicit format parameter index
7988 v|\*(\d+\$)?v vector with optional (optionally specified) arg
7989 0 flag (as above): repeated to allow "v02"
7990 \d+|\*(\d+\$)? width using optional (optionally specified) arg
7991 \.(\d*|\*(\d+\$)?) precision using optional (optionally specified) arg
7993 [%bcdefginopsux_DFOUX] format (mandatory)
7995 if ( (width = expect_number(&q)) ) {
8010 if (plus == '+' && *q == ' ') /* '+' over ' ' */
8039 if ( (ewix = expect_number(&q)) )
8048 if ((vectorarg = asterisk)) {
8061 width = expect_number(&q);
8065 if ((*q == 'p') && left) {
8066 vectorize = (width == 1);
8072 vecsv = va_arg(*args, SV*);
8074 vecsv = (evix > 0 && evix <= svmax)
8075 ? svargs[evix-1] : &PL_sv_undef;
8077 vecsv = svix < svmax ? svargs[svix++] : &PL_sv_undef;
8079 dotstr = SvPV_const(vecsv, dotstrlen);
8080 /* Keep the DO_UTF8 test *after* the SvPV call, else things go
8081 bad with tied or overloaded values that return UTF8. */
8084 else if (has_utf8) {
8085 vecsv = sv_mortalcopy(vecsv);
8086 sv_utf8_upgrade(vecsv);
8087 dotstr = SvPV_const(vecsv, dotstrlen);
8092 vecsv = va_arg(*args, SV*);
8093 vecstr = (U8*)SvPV_const(vecsv,veclen);
8094 vec_utf8 = DO_UTF8(vecsv);
8096 else if (efix ? (efix > 0 && efix <= svmax) : svix < svmax) {
8097 vecsv = svargs[efix ? efix-1 : svix++];
8098 vecstr = (U8*)SvPV_const(vecsv,veclen);
8099 vec_utf8 = DO_UTF8(vecsv);
8102 vecsv = &PL_sv_undef;
8110 i = va_arg(*args, int);
8112 i = (ewix ? ewix <= svmax : svix < svmax) ?
8113 SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
8115 width = (i < 0) ? -i : i;
8125 if ( ((epix = expect_number(&q))) && (*q++ != '$') )
8127 /* XXX: todo, support specified precision parameter */
8131 i = va_arg(*args, int);
8133 i = (ewix ? ewix <= svmax : svix < svmax)
8134 ? SvIVx(svargs[ewix ? ewix-1 : svix++]) : 0;
8136 has_precis = !(i < 0);
8141 precis = precis * 10 + (*q++ - '0');
8150 case 'I': /* Ix, I32x, and I64x */
8152 if (q[1] == '6' && q[2] == '4') {
8158 if (q[1] == '3' && q[2] == '2') {
8168 #if defined(HAS_QUAD) || defined(HAS_LONG_DOUBLE)
8179 #if defined(HAS_QUAD) || defined(HAS_LONG_DOUBLE)
8180 if (*(q + 1) == 'l') { /* lld, llf */
8206 if (!vectorize && !args) {
8208 const I32 i = efix-1;
8209 argsv = (i >= 0 && i < svmax) ? svargs[i] : &PL_sv_undef;
8211 argsv = (svix >= 0 && svix < svmax)
8212 ? svargs[svix++] : &PL_sv_undef;
8223 uv = (args) ? va_arg(*args, int) : SvIVx(argsv);
8225 (!UNI_IS_INVARIANT(uv) && SvUTF8(sv)))
8227 eptr = (char*)utf8buf;
8228 elen = uvchr_to_utf8((U8*)eptr, uv) - utf8buf;
8242 eptr = va_arg(*args, char*);
8244 #ifdef MACOS_TRADITIONAL
8245 /* On MacOS, %#s format is used for Pascal strings */
8250 elen = strlen(eptr);
8252 eptr = (char *)nullstr;
8253 elen = sizeof nullstr - 1;
8257 eptr = SvPVx_const(argsv, elen);
8258 if (DO_UTF8(argsv)) {
8259 I32 old_precis = precis;
8260 if (has_precis && precis < elen) {
8262 sv_pos_u2b(argsv, &p, 0); /* sticks at end */
8265 if (width) { /* fudge width (can't fudge elen) */
8266 if (has_precis && precis < elen)
8267 width += precis - old_precis;
8269 width += elen - sv_len_utf8(argsv);
8281 * The "%_" hack might have to be changed someday,
8282 * if ISO or ANSI decide to use '_' for something.
8283 * So we keep it hidden from users' code.
8285 if (!args || vectorize)
8287 argsv = va_arg(*args, SV*);
8288 eptr = SvPVx(argsv, elen);
8293 if (has_precis && elen > precis)
8304 goto format_sv; /* %-p -> %_ */
8307 goto format_vd; /* %-1p -> %vd */
8312 goto format_sv; /* %-Np -> %.N_ */
8315 if (alt || vectorize)
8317 uv = PTR2UV(args ? va_arg(*args, void*) : argsv);
8338 uv = utf8n_to_uvchr((U8 *)vecstr, veclen, &ulen,
8347 esignbuf[esignlen++] = plus;
8351 case 'h': iv = (short)va_arg(*args, int); break;
8352 case 'l': iv = va_arg(*args, long); break;
8353 case 'V': iv = va_arg(*args, IV); break;
8354 default: iv = va_arg(*args, int); break;
8356 case 'q': iv = va_arg(*args, Quad_t); break;
8361 IV tiv = SvIVx(argsv); /* work around GCC bug #13488 */
8363 case 'h': iv = (short)tiv; break;
8364 case 'l': iv = (long)tiv; break;
8366 default: iv = tiv; break;
8368 case 'q': iv = (Quad_t)tiv; break;
8372 if ( !vectorize ) /* we already set uv above */
8377 esignbuf[esignlen++] = plus;
8381 esignbuf[esignlen++] = '-';
8424 uv = utf8n_to_uvchr((U8 *)vecstr, veclen, &ulen,
8435 case 'h': uv = (unsigned short)va_arg(*args, unsigned); break;
8436 case 'l': uv = va_arg(*args, unsigned long); break;
8437 case 'V': uv = va_arg(*args, UV); break;
8438 default: uv = va_arg(*args, unsigned); break;
8440 case 'q': uv = va_arg(*args, Uquad_t); break;
8445 UV tuv = SvUVx(argsv); /* work around GCC bug #13488 */
8447 case 'h': uv = (unsigned short)tuv; break;
8448 case 'l': uv = (unsigned long)tuv; break;
8450 default: uv = tuv; break;
8452 case 'q': uv = (Uquad_t)tuv; break;
8459 char *ptr = ebuf + sizeof ebuf;
8460 bool tempalt = uv ? alt : FALSE; /* Vectors can't change alt */
8466 p = (char *)((c == 'X') ? PL_hexdigit + 16 : PL_hexdigit);
8472 esignbuf[esignlen++] = '0';
8473 esignbuf[esignlen++] = c; /* 'x' or 'X' */
8481 if (alt && *ptr != '0')
8490 esignbuf[esignlen++] = '0';
8491 esignbuf[esignlen++] = 'b';
8494 default: /* it had better be ten or less */
8495 #if defined(PERL_Y2KWARN)
8496 if (ckWARN(WARN_Y2K)) {
8498 const char *const s = SvPV_const(sv,n);
8499 if (n >= 2 && s[n-2] == '1' && s[n-1] == '9'
8500 && (n == 2 || !isDIGIT(s[n-3])))
8502 Perl_warner(aTHX_ packWARN(WARN_Y2K),
8503 "Possible Y2K bug: %%%c %s",
8504 c, "format string following '19'");
8511 } while (uv /= base);
8514 elen = (ebuf + sizeof ebuf) - ptr;
8518 zeros = precis - elen;
8519 else if (precis == 0 && elen == 1 && *eptr == '0'
8520 && !(base == 8 && alt)) /* "%#.0o" prints "0" */
8523 /* a precision nullifies the 0 flag. */
8530 /* FLOATING POINT */
8533 c = 'f'; /* maybe %F isn't supported here */
8541 /* This is evil, but floating point is even more evil */
8543 /* for SV-style calling, we can only get NV
8544 for C-style calling, we assume %f is double;
8545 for simplicity we allow any of %Lf, %llf, %qf for long double
8549 #if defined(USE_LONG_DOUBLE)
8553 /* [perl #20339] - we should accept and ignore %lf rather than die */
8557 #if defined(USE_LONG_DOUBLE)
8558 intsize = args ? 0 : 'q';
8562 #if defined(HAS_LONG_DOUBLE)
8571 /* now we need (long double) if intsize == 'q', else (double) */
8573 #if LONG_DOUBLESIZE > DOUBLESIZE
8575 va_arg(*args, long double) :
8576 va_arg(*args, double)
8578 va_arg(*args, double)
8583 if (c != 'e' && c != 'E') {
8585 /* FIXME: if HAS_LONG_DOUBLE but not USE_LONG_DOUBLE this
8586 will cast our (long double) to (double) */
8587 (void)Perl_frexp(nv, &i);
8588 if (i == PERL_INT_MIN)
8589 Perl_die(aTHX_ "panic: frexp");
8591 need = BIT_DIGITS(i);
8593 need += has_precis ? precis : 6; /* known default */
8598 #ifdef HAS_LDBL_SPRINTF_BUG
8599 /* This is to try to fix a bug with irix/nonstop-ux/powerux and
8600 with sfio - Allen <allens@cpan.org> */
8603 # define MY_DBL_MAX DBL_MAX
8604 # else /* XXX guessing! HUGE_VAL may be defined as infinity, so not using */
8605 # if DOUBLESIZE >= 8
8606 # define MY_DBL_MAX 1.7976931348623157E+308L
8608 # define MY_DBL_MAX 3.40282347E+38L
8612 # ifdef HAS_LDBL_SPRINTF_BUG_LESS1 /* only between -1L & 1L - Allen */
8613 # define MY_DBL_MAX_BUG 1L
8615 # define MY_DBL_MAX_BUG MY_DBL_MAX
8619 # define MY_DBL_MIN DBL_MIN
8620 # else /* XXX guessing! -Allen */
8621 # if DOUBLESIZE >= 8
8622 # define MY_DBL_MIN 2.2250738585072014E-308L
8624 # define MY_DBL_MIN 1.17549435E-38L
8628 if ((intsize == 'q') && (c == 'f') &&
8629 ((nv < MY_DBL_MAX_BUG) && (nv > -MY_DBL_MAX_BUG)) &&
8631 /* it's going to be short enough that
8632 * long double precision is not needed */
8634 if ((nv <= 0L) && (nv >= -0L))
8635 fix_ldbl_sprintf_bug = TRUE; /* 0 is 0 - easiest */
8637 /* would use Perl_fp_class as a double-check but not
8638 * functional on IRIX - see perl.h comments */
8640 if ((nv >= MY_DBL_MIN) || (nv <= -MY_DBL_MIN)) {
8641 /* It's within the range that a double can represent */
8642 #if defined(DBL_MAX) && !defined(DBL_MIN)
8643 if ((nv >= ((long double)1/DBL_MAX)) ||
8644 (nv <= (-(long double)1/DBL_MAX)))
8646 fix_ldbl_sprintf_bug = TRUE;
8649 if (fix_ldbl_sprintf_bug == TRUE) {
8659 # undef MY_DBL_MAX_BUG
8662 #endif /* HAS_LDBL_SPRINTF_BUG */
8664 need += 20; /* fudge factor */
8665 if (PL_efloatsize < need) {
8666 Safefree(PL_efloatbuf);
8667 PL_efloatsize = need + 20; /* more fudge */
8668 Newx(PL_efloatbuf, PL_efloatsize, char);
8669 PL_efloatbuf[0] = '\0';
8672 if ( !(width || left || plus || alt) && fill != '0'
8673 && has_precis && intsize != 'q' ) { /* Shortcuts */
8674 /* See earlier comment about buggy Gconvert when digits,
8676 if ( c == 'g' && precis) {
8677 Gconvert((NV)nv, (int)precis, 0, PL_efloatbuf);
8678 /* May return an empty string for digits==0 */
8679 if (*PL_efloatbuf) {
8680 elen = strlen(PL_efloatbuf);
8681 goto float_converted;
8683 } else if ( c == 'f' && !precis) {
8684 if ((eptr = F0convert(nv, ebuf + sizeof ebuf, &elen)))
8689 char *ptr = ebuf + sizeof ebuf;
8692 /* FIXME: what to do if HAS_LONG_DOUBLE but not PERL_PRIfldbl? */
8693 #if defined(HAS_LONG_DOUBLE) && defined(PERL_PRIfldbl)
8694 if (intsize == 'q') {
8695 /* Copy the one or more characters in a long double
8696 * format before the 'base' ([efgEFG]) character to
8697 * the format string. */
8698 static char const prifldbl[] = PERL_PRIfldbl;
8699 char const *p = prifldbl + sizeof(prifldbl) - 3;
8700 while (p >= prifldbl) { *--ptr = *p--; }
8705 do { *--ptr = '0' + (base % 10); } while (base /= 10);
8710 do { *--ptr = '0' + (base % 10); } while (base /= 10);
8722 /* No taint. Otherwise we are in the strange situation
8723 * where printf() taints but print($float) doesn't.
8725 #if defined(HAS_LONG_DOUBLE)
8726 elen = ((intsize == 'q')
8727 ? my_snprintf(PL_efloatbuf, PL_efloatsize, ptr, nv)
8728 : my_snprintf(PL_efloatbuf, PL_efloatsize, ptr, (double)nv));
8730 elen = my_sprintf(PL_efloatbuf, ptr, nv);
8734 eptr = PL_efloatbuf;
8742 i = SvCUR(sv) - origlen;
8745 case 'h': *(va_arg(*args, short*)) = i; break;
8746 default: *(va_arg(*args, int*)) = i; break;
8747 case 'l': *(va_arg(*args, long*)) = i; break;
8748 case 'V': *(va_arg(*args, IV*)) = i; break;
8750 case 'q': *(va_arg(*args, Quad_t*)) = i; break;
8755 sv_setuv_mg(argsv, (UV)i);
8756 continue; /* not "break" */
8763 && (PL_op->op_type == OP_PRTF || PL_op->op_type == OP_SPRINTF)
8764 && ckWARN(WARN_PRINTF))
8766 SV * const msg = sv_newmortal();
8767 Perl_sv_setpvf(aTHX_ msg, "Invalid conversion in %sprintf: ",
8768 (PL_op->op_type == OP_PRTF) ? "" : "s");
8771 Perl_sv_catpvf(aTHX_ msg,
8772 "\"%%%c\"", c & 0xFF);
8774 Perl_sv_catpvf(aTHX_ msg,
8775 "\"%%\\%03"UVof"\"",
8778 sv_catpvs(msg, "end of string");
8779 Perl_warner(aTHX_ packWARN(WARN_PRINTF), "%"SVf, (void*)msg); /* yes, this is reentrant */
8782 /* output mangled stuff ... */
8788 /* ... right here, because formatting flags should not apply */
8789 SvGROW(sv, SvCUR(sv) + elen + 1);
8791 Copy(eptr, p, elen, char);
8794 SvCUR_set(sv, p - SvPVX_const(sv));
8796 continue; /* not "break" */
8799 if (is_utf8 != has_utf8) {
8802 sv_utf8_upgrade(sv);
8805 const STRLEN old_elen = elen;
8806 SV * const nsv = sv_2mortal(newSVpvn(eptr, elen));
8807 sv_utf8_upgrade(nsv);
8808 eptr = SvPVX_const(nsv);
8811 if (width) { /* fudge width (can't fudge elen) */
8812 width += elen - old_elen;
8818 have = esignlen + zeros + elen;
8820 Perl_croak_nocontext(PL_memory_wrap);
8822 if (is_utf8 != has_utf8) {
8825 sv_utf8_upgrade(sv);
8828 SV * const nsv = sv_2mortal(newSVpvn(eptr, elen));
8829 sv_utf8_upgrade(nsv);
8830 eptr = SvPVX_const(nsv);
8833 SvGROW(sv, SvCUR(sv) + elen + 1);
8837 /* Use memchr() instead of strchr(), as eptr is not guaranteed */
8838 /* to point to a null-terminated string. */
8839 if (left && ckWARN(WARN_PRINTF) && memchr(eptr, '\n', elen) &&
8840 (PL_op->op_type == OP_PRTF || PL_op->op_type == OP_SPRINTF))
8841 Perl_warner(aTHX_ packWARN(WARN_PRINTF),
8842 "Newline in left-justified string for %sprintf",
8843 (PL_op->op_type == OP_PRTF) ? "" : "s");
8845 need = (have > width ? have : width);
8848 if (need >= (((STRLEN)~0) - SvCUR(sv) - dotstrlen - 1))
8849 Perl_croak_nocontext(PL_memory_wrap);
8850 SvGROW(sv, SvCUR(sv) + need + dotstrlen + 1);
8852 if (esignlen && fill == '0') {
8854 for (i = 0; i < (int)esignlen; i++)
8858 memset(p, fill, gap);
8861 if (esignlen && fill != '0') {
8863 for (i = 0; i < (int)esignlen; i++)
8868 for (i = zeros; i; i--)
8872 Copy(eptr, p, elen, char);
8876 memset(p, ' ', gap);
8881 Copy(dotstr, p, dotstrlen, char);
8885 vectorize = FALSE; /* done iterating over vecstr */
8892 SvCUR_set(sv, p - SvPVX_const(sv));
8900 /* =========================================================================
8902 =head1 Cloning an interpreter
8904 All the macros and functions in this section are for the private use of
8905 the main function, perl_clone().
8907 The foo_dup() functions make an exact copy of an existing foo thinngy.
8908 During the course of a cloning, a hash table is used to map old addresses
8909 to new addresses. The table is created and manipulated with the
8910 ptr_table_* functions.
8914 ============================================================================*/
8917 #if defined(USE_ITHREADS)
8919 #if defined(USE_5005THREADS)
8920 # include "error: USE_5005THREADS and USE_ITHREADS are incompatible"
8923 #ifndef GpREFCNT_inc
8924 # define GpREFCNT_inc(gp) ((gp) ? (++(gp)->gp_refcnt, (gp)) : (GP*)NULL)
8928 /* Certain cases in Perl_ss_dup have been merged, by relying on the fact
8929 that currently av_dup, gv_dup and hv_dup are the same as sv_dup.
8930 If this changes, please unmerge ss_dup. */
8931 #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
8932 #define sv_dup_inc_NN(s,t) SvREFCNT_inc_NN(sv_dup(s,t))
8933 #define av_dup(s,t) (AV*)sv_dup((SV*)s,t)
8934 #define av_dup_inc(s,t) (AV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8935 #define hv_dup(s,t) (HV*)sv_dup((SV*)s,t)
8936 #define hv_dup_inc(s,t) (HV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8937 #define cv_dup(s,t) (CV*)sv_dup((SV*)s,t)
8938 #define cv_dup_inc(s,t) (CV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8939 #define io_dup(s,t) (IO*)sv_dup((SV*)s,t)
8940 #define io_dup_inc(s,t) (IO*)SvREFCNT_inc(sv_dup((SV*)s,t))
8941 #define gv_dup(s,t) (GV*)sv_dup((SV*)s,t)
8942 #define gv_dup_inc(s,t) (GV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8943 #define SAVEPV(p) ((p) ? savepv(p) : NULL)
8944 #define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
8947 /* Duplicate a regexp. Required reading: pregcomp() and pregfree() in
8948 regcomp.c. AMS 20010712 */
8951 Perl_re_dup(pTHX_ REGEXP *r, CLONE_PARAMS *param)
8955 struct reg_substr_datum *s;
8958 return (REGEXP *)NULL;
8960 if ((ret = (REGEXP *)ptr_table_fetch(PL_ptr_table, r)))
8963 len = r->offsets[0];
8964 npar = r->nparens+1;
8966 Newxc(ret, sizeof(regexp) + (len+1)*sizeof(regnode), char, regexp);
8967 Copy(r->program, ret->program, len+1, regnode);
8969 Newx(ret->startp, npar, I32);
8970 Copy(r->startp, ret->startp, npar, I32);
8971 Newx(ret->endp, npar, I32);
8972 Copy(r->startp, ret->startp, npar, I32);
8974 Newx(ret->substrs, 1, struct reg_substr_data);
8975 for (s = ret->substrs->data, i = 0; i < 3; i++, s++) {
8976 s->min_offset = r->substrs->data[i].min_offset;
8977 s->max_offset = r->substrs->data[i].max_offset;
8978 s->substr = sv_dup_inc(r->substrs->data[i].substr, param);
8979 s->utf8_substr = sv_dup_inc(r->substrs->data[i].utf8_substr, param);
8982 ret->regstclass = NULL;
8985 const int count = r->data->count;
8988 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
8989 char, struct reg_data);
8990 Newx(d->what, count, U8);
8993 for (i = 0; i < count; i++) {
8994 d->what[i] = r->data->what[i];
8995 switch (d->what[i]) {
8997 d->data[i] = sv_dup_inc((SV *)r->data->data[i], param);
9000 d->data[i] = av_dup_inc((AV *)r->data->data[i], param);
9003 /* This is cheating. */
9004 Newx(d->data[i], 1, struct regnode_charclass_class);
9005 StructCopy(r->data->data[i], d->data[i],
9006 struct regnode_charclass_class);
9007 ret->regstclass = (regnode*)d->data[i];
9010 /* Compiled op trees are readonly, and can thus be
9011 shared without duplication. */
9013 d->data[i] = (void*)OpREFCNT_inc((OP*)r->data->data[i]);
9017 d->data[i] = r->data->data[i];
9027 Newx(ret->offsets, 2*len+1, U32);
9028 Copy(r->offsets, ret->offsets, 2*len+1, U32);
9030 ret->precomp = SAVEPVN(r->precomp, r->prelen);
9031 ret->refcnt = r->refcnt;
9032 ret->minlen = r->minlen;
9033 ret->prelen = r->prelen;
9034 ret->nparens = r->nparens;
9035 ret->lastparen = r->lastparen;
9036 ret->lastcloseparen = r->lastcloseparen;
9037 ret->reganch = r->reganch;
9039 ret->sublen = r->sublen;
9041 if (RX_MATCH_COPIED(ret))
9042 ret->subbeg = SAVEPVN(r->subbeg, r->sublen);
9046 ptr_table_store(PL_ptr_table, r, ret);
9050 /* duplicate a file handle */
9053 Perl_fp_dup(pTHX_ PerlIO *fp, char type, CLONE_PARAMS *param)
9057 PERL_UNUSED_ARG(type);
9060 return (PerlIO*)NULL;
9062 /* look for it in the table first */
9063 ret = (PerlIO*)ptr_table_fetch(PL_ptr_table, fp);
9067 /* create anew and remember what it is */
9068 ret = PerlIO_fdupopen(aTHX_ fp, param, PERLIO_DUP_CLONE);
9069 ptr_table_store(PL_ptr_table, fp, ret);
9073 /* duplicate a directory handle */
9076 Perl_dirp_dup(pTHX_ DIR *dp)
9078 PERL_UNUSED_CONTEXT;
9085 /* duplicate a typeglob */
9088 Perl_gp_dup(pTHX_ GP *gp, CLONE_PARAMS* param)
9094 /* look for it in the table first */
9095 ret = (GP*)ptr_table_fetch(PL_ptr_table, gp);
9099 /* create anew and remember what it is */
9101 ptr_table_store(PL_ptr_table, gp, ret);
9104 ret->gp_refcnt = 0; /* must be before any other dups! */
9105 ret->gp_sv = sv_dup_inc(gp->gp_sv, param);
9106 ret->gp_io = io_dup_inc(gp->gp_io, param);
9107 ret->gp_form = cv_dup_inc(gp->gp_form, param);
9108 ret->gp_av = av_dup_inc(gp->gp_av, param);
9109 ret->gp_hv = hv_dup_inc(gp->gp_hv, param);
9110 ret->gp_egv = gv_dup(gp->gp_egv, param);/* GvEGV is not refcounted */
9111 ret->gp_cv = cv_dup_inc(gp->gp_cv, param);
9112 ret->gp_cvgen = gp->gp_cvgen;
9113 ret->gp_flags = gp->gp_flags;
9114 ret->gp_line = gp->gp_line;
9115 ret->gp_file = gp->gp_file; /* points to COP.cop_file */
9119 /* duplicate a chain of magic */
9122 Perl_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS* param)
9124 MAGIC *mgprev = (MAGIC*)NULL;
9127 return (MAGIC*)NULL;
9128 /* look for it in the table first */
9129 mgret = (MAGIC*)ptr_table_fetch(PL_ptr_table, mg);
9133 for (; mg; mg = mg->mg_moremagic) {
9135 Newxz(nmg, 1, MAGIC);
9137 mgprev->mg_moremagic = nmg;
9140 nmg->mg_virtual = mg->mg_virtual; /* XXX copy dynamic vtable? */
9141 nmg->mg_private = mg->mg_private;
9142 nmg->mg_type = mg->mg_type;
9143 nmg->mg_flags = mg->mg_flags;
9144 if (mg->mg_type == PERL_MAGIC_qr) {
9145 nmg->mg_obj = (SV*)re_dup((REGEXP*)mg->mg_obj, param);
9147 else if(mg->mg_type == PERL_MAGIC_backref) {
9148 /* The backref AV has its reference count deliberately bumped by
9150 nmg->mg_obj = SvREFCNT_inc(av_dup_inc((AV*) mg->mg_obj, param));
9153 nmg->mg_obj = (mg->mg_flags & MGf_REFCOUNTED)
9154 ? sv_dup_inc(mg->mg_obj, param)
9155 : sv_dup(mg->mg_obj, param);
9157 nmg->mg_len = mg->mg_len;
9158 nmg->mg_ptr = mg->mg_ptr; /* XXX random ptr? */
9159 if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) {
9160 if (mg->mg_len > 0) {
9161 nmg->mg_ptr = SAVEPVN(mg->mg_ptr, mg->mg_len);
9162 if (mg->mg_type == PERL_MAGIC_overload_table &&
9163 AMT_AMAGIC((AMT*)mg->mg_ptr))
9165 const AMT * const amtp = (AMT*)mg->mg_ptr;
9166 AMT * const namtp = (AMT*)nmg->mg_ptr;
9168 for (i = 1; i < NofAMmeth; i++) {
9169 namtp->table[i] = cv_dup_inc(amtp->table[i], param);
9173 else if (mg->mg_len == HEf_SVKEY)
9174 nmg->mg_ptr = (char*)sv_dup_inc((SV*)mg->mg_ptr, param);
9176 if ((mg->mg_flags & MGf_DUP) && mg->mg_virtual && mg->mg_virtual->svt_dup) {
9177 CALL_FPTR(nmg->mg_virtual->svt_dup)(aTHX_ nmg, param);
9184 /* create a new pointer-mapping table */
9187 Perl_ptr_table_new(pTHX)
9190 PERL_UNUSED_CONTEXT;
9192 Newxz(tbl, 1, PTR_TBL_t);
9195 Newxz(tbl->tbl_ary, tbl->tbl_max + 1, PTR_TBL_ENT_t*);
9199 #define PTR_TABLE_HASH(ptr) \
9200 ((PTR2UV(ptr) >> 3) ^ (PTR2UV(ptr) >> (3 + 7)) ^ (PTR2UV(ptr) >> (3 + 17)))
9203 we use the PTE_SVSLOT 'reservation' made above, both here (in the
9204 following define) and at call to new_body_inline made below in
9205 Perl_ptr_table_store()
9208 #define del_pte(p) del_body_type(p, PTE_SVSLOT)
9210 /* map an existing pointer using a table */
9212 STATIC PTR_TBL_ENT_t *
9213 S_ptr_table_find(PTR_TBL_t *tbl, const void *sv) {
9214 PTR_TBL_ENT_t *tblent;
9215 const UV hash = PTR_TABLE_HASH(sv);
9217 tblent = tbl->tbl_ary[hash & tbl->tbl_max];
9218 for (; tblent; tblent = tblent->next) {
9219 if (tblent->oldval == sv)
9226 Perl_ptr_table_fetch(pTHX_ PTR_TBL_t *tbl, void *sv)
9228 PTR_TBL_ENT_t const *const tblent = ptr_table_find(tbl, (const void *)sv);
9229 PERL_UNUSED_CONTEXT;
9230 return tblent ? tblent->newval : NULL;
9233 /* add a new entry to a pointer-mapping table */
9236 Perl_ptr_table_store(pTHX_ PTR_TBL_t *tbl, void *oldsv, void *newsv)
9238 PTR_TBL_ENT_t *tblent = ptr_table_find(tbl, (const void *)oldsv);
9239 PERL_UNUSED_CONTEXT;
9242 tblent->newval = newsv;
9244 const UV entry = PTR_TABLE_HASH(oldsv) & tbl->tbl_max;
9246 new_body_inline(tblent, PTE_SVSLOT);
9248 tblent->oldval = oldsv;
9249 tblent->newval = newsv;
9250 tblent->next = tbl->tbl_ary[entry];
9251 tbl->tbl_ary[entry] = tblent;
9253 if (tblent->next && tbl->tbl_items > tbl->tbl_max)
9254 ptr_table_split(tbl);
9258 /* double the hash bucket size of an existing ptr table */
9261 Perl_ptr_table_split(pTHX_ PTR_TBL_t *tbl)
9263 PTR_TBL_ENT_t **ary = tbl->tbl_ary;
9264 const UV oldsize = tbl->tbl_max + 1;
9265 UV newsize = oldsize * 2;
9267 PERL_UNUSED_CONTEXT;
9269 Renew(ary, newsize, PTR_TBL_ENT_t*);
9270 Zero(&ary[oldsize], newsize-oldsize, PTR_TBL_ENT_t*);
9271 tbl->tbl_max = --newsize;
9273 for (i=0; i < oldsize; i++, ary++) {
9274 PTR_TBL_ENT_t **curentp, **entp, *ent;
9277 curentp = ary + oldsize;
9278 for (entp = ary, ent = *ary; ent; ent = *entp) {
9279 if ((newsize & PTR_TABLE_HASH(ent->oldval)) != i) {
9281 ent->next = *curentp;
9291 /* remove all the entries from a ptr table */
9294 Perl_ptr_table_clear(pTHX_ PTR_TBL_t *tbl)
9296 if (tbl && tbl->tbl_items) {
9297 register PTR_TBL_ENT_t * const * const array = tbl->tbl_ary;
9298 UV riter = tbl->tbl_max;
9301 PTR_TBL_ENT_t *entry = array[riter];
9304 PTR_TBL_ENT_t * const oentry = entry;
9305 entry = entry->next;
9314 /* clear and free a ptr table */
9317 Perl_ptr_table_free(pTHX_ PTR_TBL_t *tbl)
9322 ptr_table_clear(tbl);
9323 Safefree(tbl->tbl_ary);
9333 Perl_rvpv_dup(pTHX_ SV *dstr, SV *sstr, CLONE_PARAMS* param)
9336 SvRV_set(dstr, SvWEAKREF(sstr)
9337 ? sv_dup(SvRV(sstr), param)
9338 : sv_dup_inc(SvRV(sstr), param));
9341 else if (SvPVX_const(sstr)) {
9342 /* Has something there */
9344 /* Normal PV - clone whole allocated space */
9345 SvPV_set(dstr, SAVEPVN(SvPVX_const(sstr), SvLEN(sstr)-1));
9348 /* Special case - not normally malloced for some reason */
9349 if (SvREADONLY(sstr) && SvFAKE(sstr)) {
9350 /* A "shared" PV - clone it as unshared string */
9351 if(SvPADTMP(sstr)) {
9352 /* However, some of them live in the pad
9353 and they should not have these flags
9356 SvPV_set(dstr, sharepvn(SvPVX_const(sstr), SvCUR(sstr),
9358 SvUV_set(dstr, SvUVX(sstr));
9361 SvPV_set(dstr, SAVEPVN(SvPVX_const(sstr), SvCUR(sstr)));
9363 SvREADONLY_off(dstr);
9367 /* Some other special case - random pointer */
9368 SvPV_set(dstr, SvPVX(sstr));
9374 if (SvTYPE(dstr) == SVt_RV)
9375 SvRV_set(dstr, NULL);
9377 SvPV_set(dstr, NULL);
9381 /* duplicate an SV of any type (including AV, HV etc) */
9384 Perl_sv_dup(pTHX_ SV *sstr, CLONE_PARAMS* param)
9388 if (!sstr || SvTYPE(sstr) == SVTYPEMASK)
9390 /* look for it in the table first */
9391 dstr = (SV*)ptr_table_fetch(PL_ptr_table, sstr);
9395 if(param->flags & CLONEf_JOIN_IN) {
9396 /** We are joining here so we don't want do clone
9397 something that is bad **/
9398 if (SvTYPE(sstr) == SVt_PVHV) {
9399 const char * const hvname = HvNAME_get(sstr);
9401 /** don't clone stashes if they already exist **/
9402 return (SV*)gv_stashpv(hvname,0);
9406 /* create anew and remember what it is */
9408 ptr_table_store(PL_ptr_table, sstr, dstr);
9411 SvFLAGS(dstr) = SvFLAGS(sstr);
9412 SvFLAGS(dstr) &= ~SVf_OOK; /* don't propagate OOK hack */
9413 SvREFCNT(dstr) = 0; /* must be before any other dups! */
9416 if (SvANY(sstr) && PL_watch_pvx && SvPVX_const(sstr) == PL_watch_pvx)
9417 PerlIO_printf(Perl_debug_log, "watch at %p hit, found string \"%s\"\n",
9418 PL_watch_pvx, SvPVX_const(sstr));
9421 /* don't clone objects whose class has asked us not to */
9422 if (SvOBJECT(sstr) && ! (SvFLAGS(SvSTASH(sstr)) & SVphv_CLONEABLE)) {
9423 SvFLAGS(dstr) &= ~SVTYPEMASK;
9428 switch (SvTYPE(sstr)) {
9436 /* These are all the types that need simple bodies allocating. */
9438 const svtype sv_type = SvTYPE(sstr);
9439 const struct body_details *const sv_type_details
9440 = bodies_by_type + sv_type;
9442 assert(sv_type_details->body_size);
9444 assert(sv_type_details->arena);
9445 new_body_inline(new_body, sv_type);
9446 new_body = (void*)((char*)new_body - sv_type_details->offset);
9448 assert(!sv_type_details->arena);
9449 new_body = new_NOARENA(sv_type_details);
9453 SvANY(dstr) = new_body;
9455 if (sv_type == SVt_RV) {
9456 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
9459 Copy(((char*)SvANY(sstr)) + sv_type_details->offset,
9460 ((char*)SvANY(dstr)) + sv_type_details->offset,
9461 sv_type_details->copy, char);
9463 Copy(((char*)SvANY(sstr)),
9464 ((char*)SvANY(dstr)),
9465 sv_type_details->body_size + sv_type_details->offset, char);
9472 /* These are all the types that need complex bodies allocating. */
9474 const svtype sv_type = SvTYPE(sstr);
9475 const struct body_details *const sv_type_details
9476 = bodies_by_type + sv_type;
9480 Perl_croak(aTHX_ "Bizarre SvTYPE [%" IVdf "]", (IV)SvTYPE(sstr));
9484 if (GvUNIQUE((GV*)sstr)) {
9485 NOOP; /* Do sharing here, and fall through */
9498 assert(sv_type_details->body_size);
9499 if (sv_type_details->arena) {
9500 new_body_inline(new_body, sv_type);
9502 = (void*)((char*)new_body - sv_type_details->offset);
9504 new_body = new_NOARENA(sv_type_details);
9508 SvANY(dstr) = new_body;
9511 Copy(((char*)SvANY(sstr)) + sv_type_details->offset,
9512 ((char*)SvANY(dstr)) + sv_type_details->offset,
9513 sv_type_details->copy, char);
9515 Copy(((char*)SvANY(sstr)),
9516 ((char*)SvANY(dstr)),
9517 sv_type_details->body_size + sv_type_details->offset, char);
9520 if (sv_type != SVt_PVAV && sv_type != SVt_PVHV)
9521 Perl_rvpv_dup(aTHX_ dstr, sstr, param);
9523 /* The Copy above means that all the source (unduplicated) pointers
9524 are now in the destination. We can check the flags and the
9525 pointers in either, but it's possible that there's less cache
9526 missing by always going for the destination.
9527 FIXME - instrument and check that assumption */
9528 if (sv_type >= SVt_PVMG) {
9530 SvMAGIC_set(dstr, mg_dup(SvMAGIC(dstr), param));
9532 SvSTASH_set(dstr, hv_dup_inc(SvSTASH(dstr), param));
9535 /* The cast silences a GCC warning about unhandled types. */
9536 switch ((int)sv_type) {
9548 /* XXX LvTARGOFF sometimes holds PMOP* when DEBUGGING */
9549 if (LvTYPE(dstr) == 't') /* for tie: unrefcnted fake (SV**) */
9550 LvTARG(dstr) = dstr;
9551 else if (LvTYPE(dstr) == 'T') /* for tie: fake HE */
9552 LvTARG(dstr) = (SV*)he_dup((HE*)LvTARG(dstr), 0, param);
9554 LvTARG(dstr) = sv_dup_inc(LvTARG(dstr), param);
9557 GvXPVGV(dstr)->xgv_name = SAVEPVN(GvNAME(dstr), GvNAMELEN(dstr));
9559 GvSTASH(dstr) = hv_dup_inc(GvSTASH(dstr), param);
9560 GvGP(dstr) = gp_dup(GvGP(dstr), param);
9561 (void)GpREFCNT_inc(GvGP(dstr));
9564 IoIFP(dstr) = fp_dup(IoIFP(dstr), IoTYPE(dstr), param);
9565 if (IoOFP(dstr) == IoIFP(sstr))
9566 IoOFP(dstr) = IoIFP(dstr);
9568 IoOFP(dstr) = fp_dup(IoOFP(dstr), IoTYPE(dstr), param);
9569 /* PL_rsfp_filters entries have fake IoDIRP() */
9570 if(IoFLAGS(dstr) & IOf_FAKE_DIRP) {
9571 /* I have no idea why fake dirp (rsfps)
9572 should be treated differently but otherwise
9573 we end up with leaks -- sky*/
9574 IoTOP_GV(dstr) = gv_dup_inc(IoTOP_GV(dstr), param);
9575 IoFMT_GV(dstr) = gv_dup_inc(IoFMT_GV(dstr), param);
9576 IoBOTTOM_GV(dstr) = gv_dup_inc(IoBOTTOM_GV(dstr), param);
9578 IoTOP_GV(dstr) = gv_dup(IoTOP_GV(dstr), param);
9579 IoFMT_GV(dstr) = gv_dup(IoFMT_GV(dstr), param);
9580 IoBOTTOM_GV(dstr) = gv_dup(IoBOTTOM_GV(dstr), param);
9582 IoDIRP(dstr) = dirp_dup(IoDIRP(dstr));
9585 /* IoDIRP(dstr) is already a copy of IoDIRP(sstr) */
9588 IoTOP_NAME(dstr) = SAVEPV(IoTOP_NAME(dstr));
9589 IoFMT_NAME(dstr) = SAVEPV(IoFMT_NAME(dstr));
9590 IoBOTTOM_NAME(dstr) = SAVEPV(IoBOTTOM_NAME(dstr));
9593 if (AvARRAY((AV*)sstr)) {
9594 SV **dst_ary, **src_ary;
9595 SSize_t items = AvFILLp((AV*)sstr) + 1;
9597 src_ary = AvARRAY((AV*)sstr);
9598 Newz(0, dst_ary, AvMAX((AV*)sstr)+1, SV*);
9599 ptr_table_store(PL_ptr_table, src_ary, dst_ary);
9600 SvPV_set(dstr, (char*)dst_ary);
9601 AvALLOC((AV*)dstr) = dst_ary;
9602 if (AvREAL((AV*)sstr)) {
9604 *dst_ary++ = sv_dup_inc(*src_ary++, param);
9608 *dst_ary++ = sv_dup(*src_ary++, param);
9610 items = AvMAX((AV*)sstr) - AvFILLp((AV*)sstr);
9611 while (items-- > 0) {
9612 *dst_ary++ = &PL_sv_undef;
9616 SvPV_set(dstr, NULL);
9617 AvALLOC((AV*)dstr) = (SV**)NULL;
9619 AvARYLEN((AV*)dstr) = sv_dup_inc(AvARYLEN((AV*)sstr), param);
9622 if (HvARRAY((HV*)sstr)) {
9623 bool sharekeys = !!HvSHAREKEYS(sstr);
9625 XPVHV *dxhv = (XPVHV*)SvANY(dstr);
9626 XPVHV *sxhv = (XPVHV*)SvANY(sstr);
9627 Newx(dxhv->xhv_array,
9628 PERL_HV_ARRAY_ALLOC_BYTES(dxhv->xhv_max+1), char);
9629 while (i <= sxhv->xhv_max) {
9630 HE *source = HvARRAY(sstr)[i];
9632 = source ? he_dup(source, sharekeys, param) : 0;
9635 dxhv->xhv_eiter = he_dup(sxhv->xhv_eiter,
9636 (bool)!!HvSHAREKEYS(sstr), param);
9639 SvPV_set(dstr, NULL);
9640 HvEITER_set((HV*)dstr, (HE*)NULL);
9642 /* HvPMROOT is a plain assignment, not a clone. Bug? */
9643 HvNAME((HV*)dstr) = SAVEPV(HvNAME((HV*)sstr));
9644 /* Record stashes for possible cloning in Perl_clone(). */
9645 if(HvNAME((HV*)dstr))
9646 av_push(param->stashes, dstr);
9650 /* NOTE: not refcounted */
9651 CvSTASH(dstr) = hv_dup(CvSTASH(dstr), param);
9653 CvROOT(dstr) = OpREFCNT_inc(CvROOT(dstr));
9655 if (CvCONST(dstr) && CvISXSUB(dstr)) {
9656 CvXSUBANY(dstr).any_ptr = GvUNIQUE(CvGV(dstr)) ?
9657 SvREFCNT_inc(CvXSUBANY(dstr).any_ptr) :
9658 sv_dup_inc((SV *)CvXSUBANY(dstr).any_ptr, param);
9660 /* don't dup if copying back - CvGV isn't refcounted, so the
9661 * duped GV may never be freed. A bit of a hack! DAPM */
9662 CvGV(dstr) = (param->flags & CLONEf_JOIN_IN) ?
9663 NULL : gv_dup(CvGV(dstr), param) ;
9664 if (!(param->flags & CLONEf_COPY_STACKS)) {
9667 PAD_DUP(CvPADLIST(dstr), CvPADLIST(sstr), param);
9670 ? cv_dup( CvOUTSIDE(dstr), param)
9671 : cv_dup_inc(CvOUTSIDE(dstr), param);
9672 if (!CvISXSUB(dstr))
9673 CvFILE(dstr) = SAVEPV(CvFILE(dstr));
9679 if (SvOBJECT(dstr) && SvTYPE(dstr) != SVt_PVIO)
9685 /* duplicate a context */
9688 Perl_cx_dup(pTHX_ PERL_CONTEXT *cxs, I32 ix, I32 max, CLONE_PARAMS* param)
9693 return (PERL_CONTEXT*)NULL;
9695 /* look for it in the table first */
9696 ncxs = (PERL_CONTEXT*)ptr_table_fetch(PL_ptr_table, cxs);
9700 /* create anew and remember what it is */
9701 Newxz(ncxs, max + 1, PERL_CONTEXT);
9702 ptr_table_store(PL_ptr_table, cxs, ncxs);
9705 PERL_CONTEXT * const cx = &cxs[ix];
9706 PERL_CONTEXT * const ncx = &ncxs[ix];
9707 ncx->cx_type = cx->cx_type;
9708 if (CxTYPE(cx) == CXt_SUBST) {
9709 Perl_croak(aTHX_ "Cloning substitution context is unimplemented");
9712 ncx->blk_oldsp = cx->blk_oldsp;
9713 ncx->blk_oldcop = cx->blk_oldcop;
9714 ncx->blk_oldretsp = cx->blk_oldretsp;
9715 ncx->blk_oldmarksp = cx->blk_oldmarksp;
9716 ncx->blk_oldscopesp = cx->blk_oldscopesp;
9717 ncx->blk_oldpm = cx->blk_oldpm;
9718 ncx->blk_gimme = cx->blk_gimme;
9719 switch (CxTYPE(cx)) {
9721 ncx->blk_sub.cv = (cx->blk_sub.olddepth == 0
9722 ? cv_dup_inc(cx->blk_sub.cv, param)
9723 : cv_dup(cx->blk_sub.cv,param));
9724 ncx->blk_sub.argarray = (cx->blk_sub.hasargs
9725 ? av_dup_inc(cx->blk_sub.argarray, param)
9727 ncx->blk_sub.savearray = av_dup_inc(cx->blk_sub.savearray, param);
9728 ncx->blk_sub.olddepth = cx->blk_sub.olddepth;
9729 ncx->blk_sub.hasargs = cx->blk_sub.hasargs;
9730 ncx->blk_sub.lval = cx->blk_sub.lval;
9731 ncx->blk_sub.oldcomppad = (PAD*)ptr_table_fetch(PL_ptr_table,
9732 cx->blk_sub.oldcomppad);
9735 ncx->blk_eval.old_in_eval = cx->blk_eval.old_in_eval;
9736 ncx->blk_eval.old_op_type = cx->blk_eval.old_op_type;
9737 ncx->blk_eval.old_namesv = sv_dup_inc(cx->blk_eval.old_namesv, param);
9738 ncx->blk_eval.old_eval_root = cx->blk_eval.old_eval_root;
9739 ncx->blk_eval.cur_text = sv_dup(cx->blk_eval.cur_text, param);
9742 ncx->blk_loop.label = cx->blk_loop.label;
9743 ncx->blk_loop.resetsp = cx->blk_loop.resetsp;
9744 ncx->blk_loop.redo_op = cx->blk_loop.redo_op;
9745 ncx->blk_loop.next_op = cx->blk_loop.next_op;
9746 ncx->blk_loop.last_op = cx->blk_loop.last_op;
9747 ncx->blk_loop.iterdata = (CxPADLOOP(cx)
9748 ? cx->blk_loop.iterdata
9749 : gv_dup((GV*)cx->blk_loop.iterdata, param));
9750 ncx->blk_loop.oldcomppad
9751 = (PAD*)ptr_table_fetch(PL_ptr_table,
9752 cx->blk_loop.oldcomppad);
9753 ncx->blk_loop.itersave = sv_dup_inc(cx->blk_loop.itersave, param);
9754 ncx->blk_loop.iterlval = sv_dup_inc(cx->blk_loop.iterlval, param);
9755 ncx->blk_loop.iterary = av_dup_inc(cx->blk_loop.iterary, param);
9756 ncx->blk_loop.iterix = cx->blk_loop.iterix;
9757 ncx->blk_loop.itermax = cx->blk_loop.itermax;
9760 ncx->blk_sub.cv = cv_dup(cx->blk_sub.cv, param);
9761 ncx->blk_sub.gv = gv_dup(cx->blk_sub.gv, param);
9762 ncx->blk_sub.dfoutgv = gv_dup_inc(cx->blk_sub.dfoutgv, param);
9763 ncx->blk_sub.hasargs = cx->blk_sub.hasargs;
9775 /* duplicate a stack info structure */
9778 Perl_si_dup(pTHX_ PERL_SI *si, CLONE_PARAMS* param)
9783 return (PERL_SI*)NULL;
9785 /* look for it in the table first */
9786 nsi = (PERL_SI*)ptr_table_fetch(PL_ptr_table, si);
9790 /* create anew and remember what it is */
9791 Newxz(nsi, 1, PERL_SI);
9792 ptr_table_store(PL_ptr_table, si, nsi);
9794 nsi->si_stack = av_dup_inc(si->si_stack, param);
9795 nsi->si_cxix = si->si_cxix;
9796 nsi->si_cxmax = si->si_cxmax;
9797 nsi->si_cxstack = cx_dup(si->si_cxstack, si->si_cxix, si->si_cxmax, param);
9798 nsi->si_type = si->si_type;
9799 nsi->si_prev = si_dup(si->si_prev, param);
9800 nsi->si_next = si_dup(si->si_next, param);
9801 nsi->si_markoff = si->si_markoff;
9806 #define POPINT(ss,ix) ((ss)[--(ix)].any_i32)
9807 #define TOPINT(ss,ix) ((ss)[ix].any_i32)
9808 #define POPLONG(ss,ix) ((ss)[--(ix)].any_long)
9809 #define TOPLONG(ss,ix) ((ss)[ix].any_long)
9810 #define POPIV(ss,ix) ((ss)[--(ix)].any_iv)
9811 #define TOPIV(ss,ix) ((ss)[ix].any_iv)
9812 #define POPBOOL(ss,ix) ((ss)[--(ix)].any_bool)
9813 #define TOPBOOL(ss,ix) ((ss)[ix].any_bool)
9814 #define POPPTR(ss,ix) ((ss)[--(ix)].any_ptr)
9815 #define TOPPTR(ss,ix) ((ss)[ix].any_ptr)
9816 #define POPDPTR(ss,ix) ((ss)[--(ix)].any_dptr)
9817 #define TOPDPTR(ss,ix) ((ss)[ix].any_dptr)
9818 #define POPDXPTR(ss,ix) ((ss)[--(ix)].any_dxptr)
9819 #define TOPDXPTR(ss,ix) ((ss)[ix].any_dxptr)
9822 #define pv_dup_inc(p) SAVEPV(p)
9823 #define pv_dup(p) SAVEPV(p)
9824 #define svp_dup_inc(p,pp) any_dup(p,pp)
9826 /* map any object to the new equivent - either something in the
9827 * ptr table, or something in the interpreter structure
9831 Perl_any_dup(pTHX_ void *v, PerlInterpreter *proto_perl)
9838 /* look for it in the table first */
9839 ret = ptr_table_fetch(PL_ptr_table, v);
9843 /* see if it is part of the interpreter structure */
9844 if (v >= (void*)proto_perl && v < (void*)(proto_perl+1))
9845 ret = (void*)(((char*)aTHX) + (((char*)v) - (char*)proto_perl));
9853 /* duplicate the save stack */
9856 Perl_ss_dup(pTHX_ PerlInterpreter *proto_perl, CLONE_PARAMS* param)
9858 ANY * const ss = proto_perl->Tsavestack;
9859 const I32 max = proto_perl->Tsavestack_max;
9860 I32 ix = proto_perl->Tsavestack_ix;
9873 void (*dptr) (void*);
9874 void (*dxptr) (pTHX_ void*);
9876 Newxz(nss, max, ANY);
9879 const I32 type = POPINT(ss,ix);
9880 TOPINT(nss,ix) = type;
9882 case SAVEt_HELEM: /* hash element */
9883 sv = (SV*)POPPTR(ss,ix);
9884 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
9886 case SAVEt_ITEM: /* normal string */
9887 case SAVEt_SV: /* scalar reference */
9888 sv = (SV*)POPPTR(ss,ix);
9889 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
9892 case SAVEt_MORTALIZESV:
9893 sv = (SV*)POPPTR(ss,ix);
9894 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
9896 case SAVEt_GENERIC_PVREF: /* generic char* */
9897 c = (char*)POPPTR(ss,ix);
9898 TOPPTR(nss,ix) = pv_dup(c);
9899 ptr = POPPTR(ss,ix);
9900 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
9902 case SAVEt_SHARED_PVREF: /* char* in shared space */
9903 c = (char*)POPPTR(ss,ix);
9904 TOPPTR(nss,ix) = savesharedpv(c);
9905 ptr = POPPTR(ss,ix);
9906 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
9908 case SAVEt_GENERIC_SVREF: /* generic sv */
9909 case SAVEt_SVREF: /* scalar reference */
9910 sv = (SV*)POPPTR(ss,ix);
9911 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
9912 ptr = POPPTR(ss,ix);
9913 TOPPTR(nss,ix) = svp_dup_inc((SV**)ptr, proto_perl);/* XXXXX */
9915 case SAVEt_HV: /* hash reference */
9916 case SAVEt_AV: /* array reference */
9917 sv = (SV*) POPPTR(ss,ix);
9918 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
9922 sv = (SV*) POPPTR(ss,ix);
9923 TOPPTR(nss,ix) = sv_dup(sv, param);
9925 case SAVEt_INT: /* int reference */
9926 ptr = POPPTR(ss,ix);
9927 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
9928 intval = (int)POPINT(ss,ix);
9929 TOPINT(nss,ix) = intval;
9931 case SAVEt_LONG: /* long reference */
9932 ptr = POPPTR(ss,ix);
9933 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
9936 longval = (long)POPLONG(ss,ix);
9937 TOPLONG(nss,ix) = longval;
9939 case SAVEt_I32: /* I32 reference */
9940 case SAVEt_I16: /* I16 reference */
9941 case SAVEt_I8: /* I8 reference */
9942 case SAVEt_COP_ARYBASE: /* call CopARYBASE_set */
9943 ptr = POPPTR(ss,ix);
9944 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
9948 case SAVEt_IV: /* IV reference */
9949 ptr = POPPTR(ss,ix);
9950 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
9954 case SAVEt_HPTR: /* HV* reference */
9955 case SAVEt_APTR: /* AV* reference */
9956 case SAVEt_SPTR: /* SV* reference */
9957 ptr = POPPTR(ss,ix);
9958 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
9959 sv = (SV*)POPPTR(ss,ix);
9960 TOPPTR(nss,ix) = sv_dup(sv, param);
9962 case SAVEt_VPTR: /* random* reference */
9963 ptr = POPPTR(ss,ix);
9964 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
9965 ptr = POPPTR(ss,ix);
9966 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
9968 case SAVEt_PPTR: /* char* reference */
9969 ptr = POPPTR(ss,ix);
9970 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
9971 c = (char*)POPPTR(ss,ix);
9972 TOPPTR(nss,ix) = pv_dup(c);
9974 case SAVEt_GP_OLD: /* scalar reference */
9975 case SAVEt_GP_NEW: /* scalar reference */
9976 gp = (GP*)POPPTR(ss,ix);
9977 TOPPTR(nss,ix) = gp = gp_dup(gp, param);
9978 (void)GpREFCNT_inc(gp);
9979 gv = (GV*)POPPTR(ss,ix);
9980 TOPPTR(nss,ix) = gv_dup_inc(gv, param);
9981 if (type == SAVEt_GP_OLD) {
9982 c = (char*)POPPTR(ss,ix);
9983 TOPPTR(nss,ix) = pv_dup(c);
9991 ptr = POPPTR(ss,ix);
9992 if (ptr && (((OP*)ptr)->op_private & OPpREFCOUNTED)) {
9993 /* these are assumed to be refcounted properly */
9995 switch (((OP*)ptr)->op_type) {
10001 case OP_LEAVEWRITE:
10002 TOPPTR(nss,ix) = ptr;
10009 TOPPTR(nss,ix) = NULL;
10014 TOPPTR(nss,ix) = NULL;
10017 c = (char*)POPPTR(ss,ix);
10018 TOPPTR(nss,ix) = pv_dup_inc(c);
10021 hv = (HV*)POPPTR(ss,ix);
10022 TOPPTR(nss,ix) = hv_dup_inc(hv, param);
10023 c = (char*)POPPTR(ss,ix);
10024 TOPPTR(nss,ix) = pv_dup_inc(c);
10026 case SAVEt_STACK_POS: /* Position on Perl stack */
10028 TOPINT(nss,ix) = i;
10030 case SAVEt_DESTRUCTOR:
10031 ptr = POPPTR(ss,ix);
10032 TOPPTR(nss,ix) = any_dup(ptr, proto_perl); /* XXX quite arbitrary */
10033 dptr = POPDPTR(ss,ix);
10034 TOPDPTR(nss,ix) = DPTR2FPTR(void (*)(void*),
10035 any_dup(FPTR2DPTR(void *, dptr),
10038 case SAVEt_DESTRUCTOR_X:
10039 ptr = POPPTR(ss,ix);
10040 TOPPTR(nss,ix) = any_dup(ptr, proto_perl); /* XXX quite arbitrary */
10041 dxptr = POPDXPTR(ss,ix);
10042 TOPDXPTR(nss,ix) = DPTR2FPTR(void (*)(pTHX_ void*),
10043 any_dup(FPTR2DPTR(void *, dxptr),
10046 case SAVEt_REGCONTEXT:
10049 TOPINT(nss,ix) = i;
10052 case SAVEt_AELEM: /* array element */
10053 sv = (SV*)POPPTR(ss,ix);
10054 TOPPTR(nss,ix) = sv_dup_inc(sv, param);
10056 TOPINT(nss,ix) = i;
10057 av = (AV*)POPPTR(ss,ix);
10058 TOPPTR(nss,ix) = av_dup_inc(av, param);
10061 ptr = POPPTR(ss,ix);
10062 TOPPTR(nss,ix) = ptr;
10066 TOPINT(nss,ix) = i;
10069 longval = (long)POPLONG(ss,ix);
10070 TOPLONG(nss,ix) = longval;
10071 ptr = POPPTR(ss,ix);
10072 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10073 sv = (SV*)POPPTR(ss,ix);
10074 TOPPTR(nss,ix) = sv_dup(sv, param);
10077 ptr = POPPTR(ss,ix);
10078 TOPPTR(nss,ix) = any_dup(ptr, proto_perl);
10079 longval = (long)POPBOOL(ss,ix);
10080 TOPBOOL(nss,ix) = (bool)longval;
10082 case SAVEt_RE_STATE:
10084 const struct re_save_state *const old_state
10085 = (struct re_save_state *)
10086 (ss + ix - SAVESTACK_ALLOC_FOR_RE_SAVE_STATE);
10087 struct re_save_state *const new_state
10088 = (struct re_save_state *)
10089 (nss + ix - SAVESTACK_ALLOC_FOR_RE_SAVE_STATE);
10091 Copy(old_state, new_state, 1, struct re_save_state);
10092 ix -= SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
10094 new_state->re_state_bostr
10095 = pv_dup(old_state->re_state_bostr);
10096 new_state->re_state_reginput
10097 = pv_dup(old_state->re_state_reginput);
10098 new_state->re_state_regbol
10099 = pv_dup(old_state->re_state_regbol);
10100 new_state->re_state_regeol
10101 = pv_dup(old_state->re_state_regeol);
10102 new_state->re_state_regstartp
10103 = (I32*) any_dup(old_state->re_state_regstartp, proto_perl);
10104 new_state->re_state_regendp
10105 = (I32*) any_dup(old_state->re_state_regendp, proto_perl);
10106 new_state->re_state_reglastparen
10107 = (U32*) any_dup(old_state->re_state_reglastparen,
10109 new_state->re_state_reglastcloseparen
10110 = (U32*)any_dup(old_state->re_state_reglastcloseparen,
10112 new_state->re_state_regtill
10113 = pv_dup(old_state->re_state_regtill);
10114 /* XXX This just has to be broken. The old save_re_context
10115 code did SAVEGENERICPV(PL_reg_start_tmp);
10116 PL_reg_start_tmp is char **.
10117 Look above to what the dup code does for
10118 SAVEt_GENERIC_PVREF
10119 It can never have worked.
10120 So this is merely a faithful copy of the exiting bug: */
10121 new_state->re_state_reg_start_tmp
10122 = (char **) pv_dup((char *)
10123 old_state->re_state_reg_start_tmp);
10124 /* I assume that it only ever "worked" because no-one called
10125 (pseudo)fork while the regexp engine had re-entered itself.
10127 new_state->re_state_reg_call_cc
10128 = any_dup(old_state->re_state_reg_call_cc, proto_perl);
10129 new_state->re_state_reg_re
10130 = any_dup(old_state->re_state_reg_re, proto_perl);
10131 new_state->re_state_reg_ganch
10132 = pv_dup(old_state->re_state_reg_ganch);
10133 new_state->re_state_reg_sv
10134 = sv_dup(old_state->re_state_reg_sv, param);
10135 #ifdef PERL_OLD_COPY_ON_WRITE
10136 new_state->re_state_nrs
10137 = sv_dup(old_state->re_state_nrs, param);
10139 new_state->re_state_reg_magic
10140 = (MAGIC*) any_dup(old_state->re_state_reg_magic,
10142 new_state->re_state_reg_oldcurpm
10143 = (PMOP*) any_dup(old_state->re_state_reg_oldcurpm,
10145 new_state->re_state_reg_curpm
10146 = (PMOP*) any_dup(old_state->re_state_reg_curpm,
10148 new_state->re_state_reg_oldsaved
10149 = pv_dup(old_state->re_state_reg_oldsaved);
10150 new_state->re_state_reg_poscache
10151 = pv_dup(old_state->re_state_reg_poscache);
10152 new_state->re_state_reg_starttry
10153 = pv_dup(old_state->re_state_reg_starttry);
10158 "panic: ss_dup inconsistency (%"IVdf")", (IV) type);
10166 /* if sv is a stash, call $class->CLONE_SKIP(), and set the SVphv_CLONEABLE
10167 * flag to the result. This is done for each stash before cloning starts,
10168 * so we know which stashes want their objects cloned */
10171 do_mark_cloneable_stash(pTHX_ SV *sv)
10173 const char *const hvname = HvNAME_get((HV*)sv);
10175 GV* const cloner = gv_fetchmethod_autoload((HV*)sv, "CLONE_SKIP", 0);
10176 SvFLAGS(sv) |= SVphv_CLONEABLE; /* clone objects by default */
10177 if (cloner && GvCV(cloner)) {
10184 XPUSHs(sv_2mortal(newSVpv(hvname, 0)));
10186 call_sv((SV*)GvCV(cloner), G_SCALAR);
10193 SvFLAGS(sv) &= ~SVphv_CLONEABLE;
10201 =for apidoc perl_clone
10203 Create and return a new interpreter by cloning the current one.
10205 perl_clone takes these flags as parameters:
10207 CLONEf_COPY_STACKS - is used to, well, copy the stacks also,
10208 without it we only clone the data and zero the stacks,
10209 with it we copy the stacks and the new perl interpreter is
10210 ready to run at the exact same point as the previous one.
10211 The pseudo-fork code uses COPY_STACKS while the
10212 threads->new doesn't.
10214 CLONEf_KEEP_PTR_TABLE
10215 perl_clone keeps a ptr_table with the pointer of the old
10216 variable as a key and the new variable as a value,
10217 this allows it to check if something has been cloned and not
10218 clone it again but rather just use the value and increase the
10219 refcount. If KEEP_PTR_TABLE is not set then perl_clone will kill
10220 the ptr_table using the function
10221 C<ptr_table_free(PL_ptr_table); PL_ptr_table = NULL;>,
10222 reason to keep it around is if you want to dup some of your own
10223 variable who are outside the graph perl scans, example of this
10224 code is in threads.xs create
10227 This is a win32 thing, it is ignored on unix, it tells perls
10228 win32host code (which is c++) to clone itself, this is needed on
10229 win32 if you want to run two threads at the same time,
10230 if you just want to do some stuff in a separate perl interpreter
10231 and then throw it away and return to the original one,
10232 you don't need to do anything.
10237 /* XXX the above needs expanding by someone who actually understands it ! */
10238 EXTERN_C PerlInterpreter *
10239 perl_clone_host(PerlInterpreter* proto_perl, UV flags);
10242 perl_clone(PerlInterpreter *proto_perl, UV flags)
10244 #ifdef PERL_IMPLICIT_SYS
10246 /* perlhost.h so we need to call into it
10247 to clone the host, CPerlHost should have a c interface, sky */
10249 if (flags & CLONEf_CLONE_HOST) {
10250 return perl_clone_host(proto_perl,flags);
10252 return perl_clone_using(proto_perl, flags,
10254 proto_perl->IMemShared,
10255 proto_perl->IMemParse,
10257 proto_perl->IStdIO,
10261 proto_perl->IProc);
10265 perl_clone_using(PerlInterpreter *proto_perl, UV flags,
10266 struct IPerlMem* ipM, struct IPerlMem* ipMS,
10267 struct IPerlMem* ipMP, struct IPerlEnv* ipE,
10268 struct IPerlStdIO* ipStd, struct IPerlLIO* ipLIO,
10269 struct IPerlDir* ipD, struct IPerlSock* ipS,
10270 struct IPerlProc* ipP)
10272 /* XXX many of the string copies here can be optimized if they're
10273 * constants; they need to be allocated as common memory and just
10274 * their pointers copied. */
10277 CLONE_PARAMS clone_params;
10278 CLONE_PARAMS* const param = &clone_params;
10280 PerlInterpreter * const my_perl = (PerlInterpreter*)(*ipM->pMalloc)(ipM, sizeof(PerlInterpreter));
10281 /* for each stash, determine whether its objects should be cloned */
10282 S_visit(proto_perl, do_mark_cloneable_stash, SVt_PVHV, SVTYPEMASK);
10283 PERL_SET_THX(my_perl);
10286 Poison(my_perl, 1, PerlInterpreter);
10292 PL_savestack_ix = 0;
10293 PL_savestack_max = -1;
10295 PL_sig_pending = 0;
10296 Zero(&PL_debug_pad, 1, struct perl_debug_pad);
10297 # else /* !DEBUGGING */
10298 Zero(my_perl, 1, PerlInterpreter);
10299 # endif /* DEBUGGING */
10301 /* host pointers */
10303 PL_MemShared = ipMS;
10304 PL_MemParse = ipMP;
10311 #else /* !PERL_IMPLICIT_SYS */
10313 CLONE_PARAMS clone_params;
10314 CLONE_PARAMS* param = &clone_params;
10315 PerlInterpreter * const my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
10316 /* for each stash, determine whether its objects should be cloned */
10317 S_visit(proto_perl, do_mark_cloneable_stash, SVt_PVHV, SVTYPEMASK);
10318 PERL_SET_THX(my_perl);
10321 Poison(my_perl, 1, PerlInterpreter);
10327 PL_savestack_ix = 0;
10328 PL_savestack_max = -1;
10330 PL_sig_pending = 0;
10331 Zero(&PL_debug_pad, 1, struct perl_debug_pad);
10332 # else /* !DEBUGGING */
10333 Zero(my_perl, 1, PerlInterpreter);
10334 # endif /* DEBUGGING */
10335 #endif /* PERL_IMPLICIT_SYS */
10336 param->flags = flags;
10337 param->proto_perl = proto_perl;
10339 INIT_TRACK_MEMPOOL(my_perl->Imemory_debug_header, my_perl);
10342 PL_body_arenas = NULL;
10343 Zero(&PL_body_roots, 1, PL_body_roots);
10345 /* old arena roots */
10346 PL_xiv_arenaroot = NULL;
10347 PL_xiv_root = NULL;
10348 PL_xnv_arenaroot = NULL;
10349 PL_xnv_root = NULL;
10350 PL_xrv_arenaroot = NULL;
10351 PL_xrv_root = NULL;
10352 PL_xpv_arenaroot = NULL;
10353 PL_xpv_root = NULL;
10354 PL_xpviv_arenaroot = NULL;
10355 PL_xpviv_root = NULL;
10356 PL_xpvnv_arenaroot = NULL;
10357 PL_xpvnv_root = NULL;
10358 PL_xpvcv_arenaroot = NULL;
10359 PL_xpvcv_root = NULL;
10360 PL_xpvav_arenaroot = NULL;
10361 PL_xpvav_root = NULL;
10362 PL_xpvhv_arenaroot = NULL;
10363 PL_xpvhv_root = NULL;
10364 PL_xpvmg_arenaroot = NULL;
10365 PL_xpvmg_root = NULL;
10366 PL_xpvlv_arenaroot = NULL;
10367 PL_xpvlv_root = NULL;
10368 PL_xpvbm_arenaroot = NULL;
10369 PL_xpvbm_root = NULL;
10370 PL_nice_chunk = NULL;
10371 PL_nice_chunk_size = 0;
10373 PL_sv_objcount = 0;
10375 PL_sv_arenaroot = NULL;
10377 PL_debug = proto_perl->Idebug;
10379 PL_hash_seed = proto_perl->Ihash_seed;
10380 PL_rehash_seed = proto_perl->Irehash_seed;
10382 #ifdef USE_REENTRANT_API
10383 /* XXX: things like -Dm will segfault here in perlio, but doing
10384 * PERL_SET_CONTEXT(proto_perl);
10385 * breaks too many other things
10387 Perl_reentrant_init(aTHX);
10390 /* create SV map for pointer relocation */
10391 PL_ptr_table = ptr_table_new();
10393 /* initialize these special pointers as early as possible */
10394 SvANY(&PL_sv_undef) = NULL;
10395 SvREFCNT(&PL_sv_undef) = (~(U32)0)/2;
10396 SvFLAGS(&PL_sv_undef) = SVf_READONLY|SVt_NULL;
10397 ptr_table_store(PL_ptr_table, &proto_perl->Isv_undef, &PL_sv_undef);
10399 SvANY(&PL_sv_no) = new_XPVNV();
10400 SvREFCNT(&PL_sv_no) = (~(U32)0)/2;
10401 SvFLAGS(&PL_sv_no) = SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
10402 |SVp_POK|SVf_POK|SVf_READONLY|SVt_PVNV;
10403 SvPV_set(&PL_sv_no, savepvn(PL_No, 0));
10404 SvCUR_set(&PL_sv_no, 0);
10405 SvLEN_set(&PL_sv_no, 1);
10406 SvIV_set(&PL_sv_no, 0);
10407 SvNV_set(&PL_sv_no, 0);
10408 ptr_table_store(PL_ptr_table, &proto_perl->Isv_no, &PL_sv_no);
10410 SvANY(&PL_sv_yes) = new_XPVNV();
10411 SvREFCNT(&PL_sv_yes) = (~(U32)0)/2;
10412 SvFLAGS(&PL_sv_yes) = SVp_IOK|SVf_IOK|SVp_NOK|SVf_NOK
10413 |SVp_POK|SVf_POK|SVf_READONLY|SVt_PVNV;
10414 SvPV_set(&PL_sv_yes, savepvn(PL_Yes, 1));
10415 SvCUR_set(&PL_sv_yes, 1);
10416 SvLEN_set(&PL_sv_yes, 2);
10417 SvIV_set(&PL_sv_yes, 1);
10418 SvNV_set(&PL_sv_yes, 1);
10419 ptr_table_store(PL_ptr_table, &proto_perl->Isv_yes, &PL_sv_yes);
10421 /* create (a non-shared!) shared string table */
10422 PL_strtab = newHV();
10423 HvSHAREKEYS_off(PL_strtab);
10424 hv_ksplit(PL_strtab, HvTOTALKEYS(proto_perl->Istrtab));
10425 ptr_table_store(PL_ptr_table, proto_perl->Istrtab, PL_strtab);
10427 PL_compiling = proto_perl->Icompiling;
10429 /* These two PVs will be free'd special way so must set them same way op.c does */
10430 PL_compiling.cop_stashpv = savesharedpv(PL_compiling.cop_stashpv);
10431 ptr_table_store(PL_ptr_table, proto_perl->Icompiling.cop_stashpv, PL_compiling.cop_stashpv);
10433 PL_compiling.cop_file = savesharedpv(PL_compiling.cop_file);
10434 ptr_table_store(PL_ptr_table, proto_perl->Icompiling.cop_file, PL_compiling.cop_file);
10436 ptr_table_store(PL_ptr_table, &proto_perl->Icompiling, &PL_compiling);
10437 if (!specialWARN(PL_compiling.cop_warnings))
10438 PL_compiling.cop_warnings = sv_dup_inc(PL_compiling.cop_warnings, param);
10439 if (!specialCopIO(PL_compiling.cop_io))
10440 PL_compiling.cop_io = sv_dup_inc(PL_compiling.cop_io, param);
10441 PL_curcop = (COP*)any_dup(proto_perl->Tcurcop, proto_perl);
10443 /* pseudo environmental stuff */
10444 PL_origargc = proto_perl->Iorigargc;
10445 PL_origargv = proto_perl->Iorigargv;
10447 param->stashes = newAV(); /* Setup array of objects to call clone on */
10449 #ifdef PERLIO_LAYERS
10450 /* Clone PerlIO tables as soon as we can handle general xx_dup() */
10451 PerlIO_clone(aTHX_ proto_perl, param);
10454 PL_envgv = gv_dup(proto_perl->Ienvgv, param);
10455 PL_incgv = gv_dup(proto_perl->Iincgv, param);
10456 PL_hintgv = gv_dup(proto_perl->Ihintgv, param);
10457 PL_origfilename = SAVEPV(proto_perl->Iorigfilename);
10458 PL_diehook = sv_dup_inc(proto_perl->Idiehook, param);
10459 PL_warnhook = sv_dup_inc(proto_perl->Iwarnhook, param);
10462 PL_minus_c = proto_perl->Iminus_c;
10463 PL_patchlevel = sv_dup_inc(proto_perl->Ipatchlevel, param);
10464 PL_localpatches = proto_perl->Ilocalpatches;
10465 PL_splitstr = proto_perl->Isplitstr;
10466 PL_preprocess = proto_perl->Ipreprocess;
10467 PL_minus_n = proto_perl->Iminus_n;
10468 PL_minus_p = proto_perl->Iminus_p;
10469 PL_minus_l = proto_perl->Iminus_l;
10470 PL_minus_a = proto_perl->Iminus_a;
10471 PL_minus_F = proto_perl->Iminus_F;
10472 PL_doswitches = proto_perl->Idoswitches;
10473 PL_dowarn = proto_perl->Idowarn;
10474 PL_doextract = proto_perl->Idoextract;
10475 PL_sawampersand = proto_perl->Isawampersand;
10476 PL_unsafe = proto_perl->Iunsafe;
10477 PL_inplace = SAVEPV(proto_perl->Iinplace);
10478 PL_e_script = sv_dup_inc(proto_perl->Ie_script, param);
10479 PL_perldb = proto_perl->Iperldb;
10480 PL_perl_destruct_level = proto_perl->Iperl_destruct_level;
10481 PL_exit_flags = proto_perl->Iexit_flags;
10483 /* magical thingies */
10484 /* XXX time(&PL_basetime) when asked for? */
10485 PL_basetime = proto_perl->Ibasetime;
10486 PL_formfeed = sv_dup(proto_perl->Iformfeed, param);
10488 PL_maxsysfd = proto_perl->Imaxsysfd;
10489 PL_multiline = proto_perl->Imultiline;
10490 PL_statusvalue = proto_perl->Istatusvalue;
10492 PL_statusvalue_vms = proto_perl->Istatusvalue_vms;
10494 PL_statusvalue_posix = proto_perl->Istatusvalue_posix;
10496 PL_encoding = sv_dup(proto_perl->Iencoding, param);
10498 sv_setpvn(PERL_DEBUG_PAD(0), "", 0); /* For regex debugging. */
10499 sv_setpvn(PERL_DEBUG_PAD(1), "", 0); /* ext/re needs these */
10500 sv_setpvn(PERL_DEBUG_PAD(2), "", 0); /* even without DEBUGGING. */
10502 /* Clone the regex array */
10503 PL_regex_padav = newAV();
10505 const I32 len = av_len((AV*)proto_perl->Iregex_padav);
10506 SV* const * const regexen = AvARRAY((AV*)proto_perl->Iregex_padav);
10508 av_push(PL_regex_padav, sv_dup_inc_NN(regexen[0],param));
10509 for(i = 1; i <= len; i++) {
10510 const SV * const regex = regexen[i];
10513 ? sv_dup_inc((SV *)regex, param)
10515 newSViv(PTR2IV(re_dup(
10516 INT2PTR(REGEXP *, SvIVX(regex)), param))))
10518 av_push(PL_regex_padav, sv);
10521 PL_regex_pad = AvARRAY(PL_regex_padav);
10523 /* shortcuts to various I/O objects */
10524 PL_stdingv = gv_dup(proto_perl->Istdingv, param);
10525 PL_stderrgv = gv_dup(proto_perl->Istderrgv, param);
10526 PL_defgv = gv_dup(proto_perl->Idefgv, param);
10527 PL_argvgv = gv_dup(proto_perl->Iargvgv, param);
10528 PL_argvoutgv = gv_dup(proto_perl->Iargvoutgv, param);
10529 PL_argvout_stack = av_dup_inc(proto_perl->Iargvout_stack, param);
10531 /* shortcuts to regexp stuff */
10532 PL_replgv = gv_dup(proto_perl->Ireplgv, param);
10534 /* shortcuts to misc objects */
10535 PL_errgv = gv_dup(proto_perl->Ierrgv, param);
10537 /* shortcuts to debugging objects */
10538 PL_DBgv = gv_dup(proto_perl->IDBgv, param);
10539 PL_DBline = gv_dup(proto_perl->IDBline, param);
10540 PL_DBsub = gv_dup(proto_perl->IDBsub, param);
10541 PL_DBsingle = sv_dup(proto_perl->IDBsingle, param);
10542 PL_DBtrace = sv_dup(proto_perl->IDBtrace, param);
10543 PL_DBsignal = sv_dup(proto_perl->IDBsignal, param);
10544 PL_lineary = av_dup(proto_perl->Ilineary, param);
10545 PL_dbargs = av_dup(proto_perl->Idbargs, param);
10547 /* symbol tables */
10548 PL_defstash = hv_dup_inc(proto_perl->Tdefstash, param);
10549 PL_curstash = hv_dup(proto_perl->Tcurstash, param);
10550 PL_nullstash = hv_dup(proto_perl->Inullstash, param);
10551 PL_debstash = hv_dup(proto_perl->Idebstash, param);
10552 PL_globalstash = hv_dup(proto_perl->Iglobalstash, param);
10553 PL_curstname = sv_dup_inc(proto_perl->Icurstname, param);
10555 PL_beginav = av_dup_inc(proto_perl->Ibeginav, param);
10556 PL_beginav_save = av_dup_inc(proto_perl->Ibeginav_save, param);
10557 PL_checkav_save = av_dup_inc(proto_perl->Icheckav_save, param);
10558 PL_endav = av_dup_inc(proto_perl->Iendav, param);
10559 PL_checkav = av_dup_inc(proto_perl->Icheckav, param);
10560 PL_initav = av_dup_inc(proto_perl->Iinitav, param);
10562 PL_sub_generation = proto_perl->Isub_generation;
10564 /* funky return mechanisms */
10565 PL_forkprocess = proto_perl->Iforkprocess;
10567 /* subprocess state */
10568 PL_fdpid = av_dup_inc(proto_perl->Ifdpid, param);
10570 /* internal state */
10571 PL_tainting = proto_perl->Itainting;
10572 PL_taint_warn = proto_perl->Itaint_warn;
10573 PL_maxo = proto_perl->Imaxo;
10574 if (proto_perl->Iop_mask)
10575 PL_op_mask = SAVEPVN(proto_perl->Iop_mask, PL_maxo);
10579 /* current interpreter roots */
10580 PL_main_cv = cv_dup_inc(proto_perl->Imain_cv, param);
10582 PL_main_root = OpREFCNT_inc(proto_perl->Imain_root);
10584 PL_main_start = proto_perl->Imain_start;
10585 PL_eval_root = proto_perl->Ieval_root;
10586 PL_eval_start = proto_perl->Ieval_start;
10588 /* runtime control stuff */
10589 PL_curcopdb = (COP*)any_dup(proto_perl->Icurcopdb, proto_perl);
10590 PL_copline = proto_perl->Icopline;
10592 PL_filemode = proto_perl->Ifilemode;
10593 PL_lastfd = proto_perl->Ilastfd;
10594 PL_oldname = proto_perl->Ioldname; /* XXX not quite right */
10597 PL_gensym = proto_perl->Igensym;
10598 PL_preambled = proto_perl->Ipreambled;
10599 PL_preambleav = av_dup_inc(proto_perl->Ipreambleav, param);
10600 PL_laststatval = proto_perl->Ilaststatval;
10601 PL_laststype = proto_perl->Ilaststype;
10604 PL_ors_sv = sv_dup_inc(proto_perl->Iors_sv, param);
10605 PL_ofmt = SAVEPV(proto_perl->Iofmt);
10607 /* interpreter atexit processing */
10608 PL_exitlistlen = proto_perl->Iexitlistlen;
10609 if (PL_exitlistlen) {
10610 Newx(PL_exitlist, PL_exitlistlen, PerlExitListEntry);
10611 Copy(proto_perl->Iexitlist, PL_exitlist, PL_exitlistlen, PerlExitListEntry);
10614 PL_exitlist = (PerlExitListEntry*)NULL;
10615 PL_modglobal = hv_dup_inc(proto_perl->Imodglobal, param);
10616 PL_custom_op_names = hv_dup_inc(proto_perl->Icustom_op_names,param);
10617 PL_custom_op_descs = hv_dup_inc(proto_perl->Icustom_op_descs,param);
10619 PL_profiledata = NULL;
10620 PL_rsfp = fp_dup(proto_perl->Irsfp, '<', param);
10621 /* PL_rsfp_filters entries have fake IoDIRP() */
10622 PL_rsfp_filters = av_dup_inc(proto_perl->Irsfp_filters, param);
10624 PL_compcv = cv_dup(proto_perl->Icompcv, param);
10626 PAD_CLONE_VARS(proto_perl, param);
10628 #ifdef HAVE_INTERP_INTERN
10629 sys_intern_dup(&proto_perl->Isys_intern, &PL_sys_intern);
10632 /* more statics moved here */
10633 PL_generation = proto_perl->Igeneration;
10634 PL_DBcv = cv_dup(proto_perl->IDBcv, param);
10636 PL_in_clean_objs = proto_perl->Iin_clean_objs;
10637 PL_in_clean_all = proto_perl->Iin_clean_all;
10639 PL_uid = proto_perl->Iuid;
10640 PL_euid = proto_perl->Ieuid;
10641 PL_gid = proto_perl->Igid;
10642 PL_egid = proto_perl->Iegid;
10643 PL_nomemok = proto_perl->Inomemok;
10644 PL_an = proto_perl->Ian;
10645 PL_op_seqmax = proto_perl->Iop_seqmax;
10646 PL_evalseq = proto_perl->Ievalseq;
10647 PL_origenviron = proto_perl->Iorigenviron; /* XXX not quite right */
10648 PL_origalen = proto_perl->Iorigalen;
10649 PL_pidstatus = newHV(); /* XXX flag for cloning? */
10650 PL_osname = SAVEPV(proto_perl->Iosname);
10651 PL_sh_path_compat = proto_perl->Ish_path_compat; /* XXX never deallocated */
10652 PL_sighandlerp = proto_perl->Isighandlerp;
10655 PL_runops = proto_perl->Irunops;
10657 Copy(proto_perl->Itokenbuf, PL_tokenbuf, 256, char);
10660 PL_cshlen = proto_perl->Icshlen;
10661 PL_cshname = proto_perl->Icshname; /* XXX never deallocated */
10664 PL_lex_state = proto_perl->Ilex_state;
10665 PL_lex_defer = proto_perl->Ilex_defer;
10666 PL_lex_expect = proto_perl->Ilex_expect;
10667 PL_lex_formbrack = proto_perl->Ilex_formbrack;
10668 PL_lex_dojoin = proto_perl->Ilex_dojoin;
10669 PL_lex_starts = proto_perl->Ilex_starts;
10670 PL_lex_stuff = sv_dup_inc(proto_perl->Ilex_stuff, param);
10671 PL_lex_repl = sv_dup_inc(proto_perl->Ilex_repl, param);
10672 PL_lex_op = proto_perl->Ilex_op;
10673 PL_lex_inpat = proto_perl->Ilex_inpat;
10674 PL_lex_inwhat = proto_perl->Ilex_inwhat;
10675 PL_lex_brackets = proto_perl->Ilex_brackets;
10676 i = (PL_lex_brackets < 120 ? 120 : PL_lex_brackets);
10677 PL_lex_brackstack = SAVEPVN(proto_perl->Ilex_brackstack,i);
10678 PL_lex_casemods = proto_perl->Ilex_casemods;
10679 i = (PL_lex_casemods < 12 ? 12 : PL_lex_casemods);
10680 PL_lex_casestack = SAVEPVN(proto_perl->Ilex_casestack,i);
10682 Copy(proto_perl->Inextval, PL_nextval, 5, YYSTYPE);
10683 Copy(proto_perl->Inexttype, PL_nexttype, 5, I32);
10684 PL_nexttoke = proto_perl->Inexttoke;
10686 PL_linestr = sv_dup_inc(proto_perl->Ilinestr, param);
10687 i = proto_perl->Ibufptr - SvPVX_const(proto_perl->Ilinestr);
10688 PL_bufptr = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
10689 i = proto_perl->Ioldbufptr - SvPVX_const(proto_perl->Ilinestr);
10690 PL_oldbufptr = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
10691 i = proto_perl->Ioldoldbufptr - SvPVX_const(proto_perl->Ilinestr);
10692 PL_oldoldbufptr = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
10693 i = proto_perl->Ilinestart - SvPVX_const(proto_perl->Ilinestr);
10694 PL_linestart = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
10695 PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
10696 PL_pending_ident = proto_perl->Ipending_ident;
10697 PL_sublex_info = proto_perl->Isublex_info; /* XXX not quite right */
10699 PL_expect = proto_perl->Iexpect;
10701 PL_multi_start = proto_perl->Imulti_start;
10702 PL_multi_end = proto_perl->Imulti_end;
10703 PL_multi_open = proto_perl->Imulti_open;
10704 PL_multi_close = proto_perl->Imulti_close;
10706 PL_error_count = proto_perl->Ierror_count;
10707 PL_subline = proto_perl->Isubline;
10708 PL_subname = sv_dup_inc(proto_perl->Isubname, param);
10710 i = proto_perl->Ilast_uni - SvPVX_const(proto_perl->Ilinestr);
10711 PL_last_uni = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
10712 i = proto_perl->Ilast_lop - SvPVX_const(proto_perl->Ilinestr);
10713 PL_last_lop = SvPVX(PL_linestr) + (i < 0 ? 0 : i);
10714 PL_last_lop_op = proto_perl->Ilast_lop_op;
10715 PL_in_my = proto_perl->Iin_my;
10716 PL_in_my_stash = hv_dup(proto_perl->Iin_my_stash, param);
10718 PL_cryptseen = proto_perl->Icryptseen;
10721 PL_hints = proto_perl->Ihints;
10723 PL_amagic_generation = proto_perl->Iamagic_generation;
10725 #ifdef USE_LOCALE_COLLATE
10726 PL_collation_ix = proto_perl->Icollation_ix;
10727 PL_collation_name = SAVEPV(proto_perl->Icollation_name);
10728 PL_collation_standard = proto_perl->Icollation_standard;
10729 PL_collxfrm_base = proto_perl->Icollxfrm_base;
10730 PL_collxfrm_mult = proto_perl->Icollxfrm_mult;
10731 #endif /* USE_LOCALE_COLLATE */
10733 #ifdef USE_LOCALE_NUMERIC
10734 PL_numeric_name = SAVEPV(proto_perl->Inumeric_name);
10735 PL_numeric_standard = proto_perl->Inumeric_standard;
10736 PL_numeric_local = proto_perl->Inumeric_local;
10737 PL_numeric_radix_sv = sv_dup_inc(proto_perl->Inumeric_radix_sv, param);
10738 #endif /* !USE_LOCALE_NUMERIC */
10740 /* utf8 character classes */
10741 PL_utf8_alnum = sv_dup_inc(proto_perl->Iutf8_alnum, param);
10742 PL_utf8_alnumc = sv_dup_inc(proto_perl->Iutf8_alnumc, param);
10743 PL_utf8_ascii = sv_dup_inc(proto_perl->Iutf8_ascii, param);
10744 PL_utf8_alpha = sv_dup_inc(proto_perl->Iutf8_alpha, param);
10745 PL_utf8_space = sv_dup_inc(proto_perl->Iutf8_space, param);
10746 PL_utf8_cntrl = sv_dup_inc(proto_perl->Iutf8_cntrl, param);
10747 PL_utf8_graph = sv_dup_inc(proto_perl->Iutf8_graph, param);
10748 PL_utf8_digit = sv_dup_inc(proto_perl->Iutf8_digit, param);
10749 PL_utf8_upper = sv_dup_inc(proto_perl->Iutf8_upper, param);
10750 PL_utf8_lower = sv_dup_inc(proto_perl->Iutf8_lower, param);
10751 PL_utf8_print = sv_dup_inc(proto_perl->Iutf8_print, param);
10752 PL_utf8_punct = sv_dup_inc(proto_perl->Iutf8_punct, param);
10753 PL_utf8_xdigit = sv_dup_inc(proto_perl->Iutf8_xdigit, param);
10754 PL_utf8_mark = sv_dup_inc(proto_perl->Iutf8_mark, param);
10755 PL_utf8_toupper = sv_dup_inc(proto_perl->Iutf8_toupper, param);
10756 PL_utf8_totitle = sv_dup_inc(proto_perl->Iutf8_totitle, param);
10757 PL_utf8_tolower = sv_dup_inc(proto_perl->Iutf8_tolower, param);
10758 PL_utf8_tofold = sv_dup_inc(proto_perl->Iutf8_tofold, param);
10759 PL_utf8_idstart = sv_dup_inc(proto_perl->Iutf8_idstart, param);
10760 PL_utf8_idcont = sv_dup_inc(proto_perl->Iutf8_idcont, param);
10762 /* Did the locale setup indicate UTF-8? */
10763 PL_utf8locale = proto_perl->Iutf8locale;
10764 /* Unicode features (see perlrun/-C) */
10765 PL_unicode = proto_perl->Iunicode;
10767 /* Pre-5.8 signals control */
10768 PL_signals = proto_perl->Isignals;
10770 /* times() ticks per second */
10771 PL_clocktick = proto_perl->Iclocktick;
10773 /* Recursion stopper for PerlIO_find_layer */
10774 PL_in_load_module = proto_perl->Iin_load_module;
10776 /* sort() routine */
10777 PL_sort_RealCmp = proto_perl->Isort_RealCmp;
10779 /* Not really needed/useful since the reenrant_retint is "volatile",
10780 * but do it for consistency's sake. */
10781 PL_reentrant_retint = proto_perl->Ireentrant_retint;
10783 /* Hooks to shared SVs and locks. */
10784 PL_sharehook = proto_perl->Isharehook;
10785 PL_lockhook = proto_perl->Ilockhook;
10786 PL_unlockhook = proto_perl->Iunlockhook;
10787 PL_threadhook = proto_perl->Ithreadhook;
10789 PL_runops_std = proto_perl->Irunops_std;
10790 PL_runops_dbg = proto_perl->Irunops_dbg;
10792 #ifdef THREADS_HAVE_PIDS
10793 PL_ppid = proto_perl->Ippid;
10797 PL_last_swash_hv = NULL; /* reinits on demand */
10798 PL_last_swash_klen = 0;
10799 PL_last_swash_key[0]= '\0';
10800 PL_last_swash_tmps = (U8*)NULL;
10801 PL_last_swash_slen = 0;
10803 /* perly.c globals */
10804 PL_yydebug = proto_perl->Iyydebug;
10805 PL_yynerrs = proto_perl->Iyynerrs;
10806 PL_yyerrflag = proto_perl->Iyyerrflag;
10807 PL_yychar = proto_perl->Iyychar;
10808 PL_yyval = proto_perl->Iyyval;
10809 PL_yylval = proto_perl->Iyylval;
10811 PL_glob_index = proto_perl->Iglob_index;
10812 PL_srand_called = proto_perl->Isrand_called;
10813 PL_uudmap[(U32) 'M'] = 0; /* reinits on demand */
10814 PL_bitcount = NULL; /* reinits on demand */
10816 if (proto_perl->Ipsig_pend) {
10817 Newxz(PL_psig_pend, SIG_SIZE, int);
10820 PL_psig_pend = (int*)NULL;
10823 if (proto_perl->Ipsig_ptr) {
10824 Newxz(PL_psig_ptr, SIG_SIZE, SV*);
10825 Newxz(PL_psig_name, SIG_SIZE, SV*);
10826 for (i = 1; i < SIG_SIZE; i++) {
10827 PL_psig_ptr[i] = sv_dup_inc(proto_perl->Ipsig_ptr[i], param);
10828 PL_psig_name[i] = sv_dup_inc(proto_perl->Ipsig_name[i], param);
10832 PL_psig_ptr = (SV**)NULL;
10833 PL_psig_name = (SV**)NULL;
10836 /* thrdvar.h stuff */
10838 if (flags & CLONEf_COPY_STACKS) {
10839 /* next allocation will be PL_tmps_stack[PL_tmps_ix+1] */
10840 PL_tmps_ix = proto_perl->Ttmps_ix;
10841 PL_tmps_max = proto_perl->Ttmps_max;
10842 PL_tmps_floor = proto_perl->Ttmps_floor;
10843 Newxz(PL_tmps_stack, PL_tmps_max, SV*);
10845 while (i <= PL_tmps_ix) {
10846 PL_tmps_stack[i] = sv_dup_inc(proto_perl->Ttmps_stack[i], param);
10850 /* next PUSHMARK() sets *(PL_markstack_ptr+1) */
10851 i = proto_perl->Tmarkstack_max - proto_perl->Tmarkstack;
10852 Newxz(PL_markstack, i, I32);
10853 PL_markstack_max = PL_markstack + (proto_perl->Tmarkstack_max
10854 - proto_perl->Tmarkstack);
10855 PL_markstack_ptr = PL_markstack + (proto_perl->Tmarkstack_ptr
10856 - proto_perl->Tmarkstack);
10857 Copy(proto_perl->Tmarkstack, PL_markstack,
10858 PL_markstack_ptr - PL_markstack + 1, I32);
10860 /* next push_scope()/ENTER sets PL_scopestack[PL_scopestack_ix]
10861 * NOTE: unlike the others! */
10862 PL_scopestack_ix = proto_perl->Tscopestack_ix;
10863 PL_scopestack_max = proto_perl->Tscopestack_max;
10864 Newxz(PL_scopestack, PL_scopestack_max, I32);
10865 Copy(proto_perl->Tscopestack, PL_scopestack, PL_scopestack_ix, I32);
10867 /* next push_return() sets PL_retstack[PL_retstack_ix]
10868 * NOTE: unlike the others! */
10869 PL_retstack_ix = proto_perl->Tretstack_ix;
10870 PL_retstack_max = proto_perl->Tretstack_max;
10871 Newz(54, PL_retstack, PL_retstack_max, OP*);
10872 Copy(proto_perl->Tretstack, PL_retstack, PL_retstack_ix, OP*);
10874 /* NOTE: si_dup() looks at PL_markstack */
10875 PL_curstackinfo = si_dup(proto_perl->Tcurstackinfo, param);
10877 /* PL_curstack = PL_curstackinfo->si_stack; */
10878 PL_curstack = av_dup(proto_perl->Tcurstack, param);
10879 PL_mainstack = av_dup(proto_perl->Tmainstack, param);
10881 /* next PUSHs() etc. set *(PL_stack_sp+1) */
10882 PL_stack_base = AvARRAY(PL_curstack);
10883 PL_stack_sp = PL_stack_base + (proto_perl->Tstack_sp
10884 - proto_perl->Tstack_base);
10885 PL_stack_max = PL_stack_base + AvMAX(PL_curstack);
10887 /* next SSPUSHFOO() sets PL_savestack[PL_savestack_ix]
10888 * NOTE: unlike the others! */
10889 PL_savestack_ix = proto_perl->Tsavestack_ix;
10890 PL_savestack_max = proto_perl->Tsavestack_max;
10891 /*Newxz(PL_savestack, PL_savestack_max, ANY);*/
10892 PL_savestack = ss_dup(proto_perl, param);
10896 ENTER; /* perl_destruct() wants to LEAVE; */
10898 /* although we're not duplicating the tmps stack, we should still
10899 * add entries for any SVs on the tmps stack that got cloned by a
10900 * non-refcount means (eg a temp in @_); otherwise they will be
10903 for (i = 0; i<= proto_perl->Ttmps_ix; i++) {
10904 SV * const nsv = (SV*)ptr_table_fetch(PL_ptr_table,
10905 proto_perl->Ttmps_stack[i]);
10906 if (nsv && !SvREFCNT(nsv)) {
10908 PL_tmps_stack[++PL_tmps_ix] = SvREFCNT_inc_simple(nsv);
10913 PL_start_env = proto_perl->Tstart_env; /* XXXXXX */
10914 PL_top_env = &PL_start_env;
10916 PL_op = proto_perl->Top;
10919 PL_Xpv = (XPV*)NULL;
10920 PL_na = proto_perl->Tna;
10922 PL_statbuf = proto_perl->Tstatbuf;
10923 PL_statcache = proto_perl->Tstatcache;
10924 PL_statgv = gv_dup(proto_perl->Tstatgv, param);
10925 PL_statname = sv_dup_inc(proto_perl->Tstatname, param);
10927 PL_timesbuf = proto_perl->Ttimesbuf;
10930 PL_tainted = proto_perl->Ttainted;
10931 PL_curpm = proto_perl->Tcurpm; /* XXX No PMOP ref count */
10932 PL_rs = sv_dup_inc(proto_perl->Trs, param);
10933 PL_last_in_gv = gv_dup(proto_perl->Tlast_in_gv, param);
10934 PL_ofs_sv = sv_dup_inc(proto_perl->Tofs_sv, param);
10935 PL_defoutgv = gv_dup_inc(proto_perl->Tdefoutgv, param);
10936 PL_chopset = proto_perl->Tchopset; /* XXX never deallocated */
10937 PL_toptarget = sv_dup_inc(proto_perl->Ttoptarget, param);
10938 PL_bodytarget = sv_dup_inc(proto_perl->Tbodytarget, param);
10939 PL_formtarget = sv_dup(proto_perl->Tformtarget, param);
10941 PL_restartop = proto_perl->Trestartop;
10942 PL_in_eval = proto_perl->Tin_eval;
10943 PL_delaymagic = proto_perl->Tdelaymagic;
10944 PL_dirty = proto_perl->Tdirty;
10945 PL_localizing = proto_perl->Tlocalizing;
10947 #ifdef PERL_FLEXIBLE_EXCEPTIONS
10948 PL_protect = proto_perl->Tprotect;
10950 PL_errors = sv_dup_inc(proto_perl->Terrors, param);
10951 PL_hv_fetch_ent_mh = NULL;
10952 PL_modcount = proto_perl->Tmodcount;
10953 PL_lastgotoprobe = NULL;
10954 PL_dumpindent = proto_perl->Tdumpindent;
10956 PL_sortcop = (OP*)any_dup(proto_perl->Tsortcop, proto_perl);
10957 PL_sortstash = hv_dup(proto_perl->Tsortstash, param);
10958 PL_firstgv = gv_dup(proto_perl->Tfirstgv, param);
10959 PL_secondgv = gv_dup(proto_perl->Tsecondgv, param);
10960 PL_efloatbuf = NULL; /* reinits on demand */
10961 PL_efloatsize = 0; /* reinits on demand */
10965 PL_screamfirst = NULL;
10966 PL_screamnext = NULL;
10967 PL_maxscream = -1; /* reinits on demand */
10968 PL_lastscream = NULL;
10970 PL_watchaddr = NULL;
10973 PL_regdummy = proto_perl->Tregdummy;
10974 PL_regcomp_parse = Nullch;
10975 PL_regxend = Nullch;
10976 PL_regcode = (regnode*)NULL;
10979 PL_regprecomp = NULL;
10984 PL_seen_zerolen = 0;
10986 PL_regcomp_rx = (regexp*)NULL;
10988 PL_colorset = 0; /* reinits PL_colors[] */
10989 /*PL_colors[6] = {0,0,0,0,0,0};*/
10990 PL_reg_whilem_seen = 0;
10991 PL_reginput = NULL;
10994 PL_regstartp = (I32*)NULL;
10995 PL_regendp = (I32*)NULL;
10996 PL_reglastparen = (U32*)NULL;
10997 PL_reglastcloseparen = (U32*)NULL;
10999 PL_reg_start_tmp = (char**)NULL;
11000 PL_reg_start_tmpl = 0;
11001 PL_regdata = (struct reg_data*)NULL;
11004 PL_reg_eval_set = 0;
11006 PL_regprogram = (regnode*)NULL;
11008 PL_regcc = (CURCUR*)NULL;
11009 PL_reg_call_cc = (struct re_cc_state*)NULL;
11010 PL_reg_re = (regexp*)NULL;
11011 PL_reg_ganch = NULL;
11013 PL_reg_match_utf8 = FALSE;
11014 PL_reg_magic = (MAGIC*)NULL;
11016 PL_reg_oldcurpm = (PMOP*)NULL;
11017 PL_reg_curpm = (PMOP*)NULL;
11018 PL_reg_oldsaved = NULL;
11019 PL_reg_oldsavedlen = 0;
11020 PL_reg_maxiter = 0;
11021 PL_reg_leftiter = 0;
11022 PL_reg_poscache = NULL;
11023 PL_reg_poscache_size= 0;
11025 /* RE engine - function pointers */
11026 PL_regcompp = proto_perl->Tregcompp;
11027 PL_regexecp = proto_perl->Tregexecp;
11028 PL_regint_start = proto_perl->Tregint_start;
11029 PL_regint_string = proto_perl->Tregint_string;
11030 PL_regfree = proto_perl->Tregfree;
11032 PL_reginterp_cnt = 0;
11033 PL_reg_starttry = 0;
11035 /* Pluggable optimizer */
11036 PL_peepp = proto_perl->Tpeepp;
11038 PL_stashcache = newHV();
11040 if (!(flags & CLONEf_KEEP_PTR_TABLE)) {
11041 ptr_table_free(PL_ptr_table);
11042 PL_ptr_table = NULL;
11045 /* Call the ->CLONE method, if it exists, for each of the stashes
11046 identified by sv_dup() above.
11048 while(av_len(param->stashes) != -1) {
11049 HV* const stash = (HV*) av_shift(param->stashes);
11050 GV* const cloner = gv_fetchmethod_autoload(stash, "CLONE", 0);
11051 if (cloner && GvCV(cloner)) {
11056 XPUSHs(sv_2mortal(newSVpv(HvNAME_get(stash), 0)));
11058 call_sv((SV*)GvCV(cloner), G_DISCARD);
11064 SvREFCNT_dec(param->stashes);
11066 /* orphaned? eg threads->new inside BEGIN or use */
11067 if (PL_compcv && ! SvREFCNT(PL_compcv)) {
11068 SvREFCNT_inc_simple_void(PL_compcv);
11069 SAVEFREESV(PL_compcv);
11075 #endif /* USE_ITHREADS */
11078 =head1 Unicode Support
11080 =for apidoc sv_recode_to_utf8
11082 The encoding is assumed to be an Encode object, on entry the PV
11083 of the sv is assumed to be octets in that encoding, and the sv
11084 will be converted into Unicode (and UTF-8).
11086 If the sv already is UTF-8 (or if it is not POK), or if the encoding
11087 is not a reference, nothing is done to the sv. If the encoding is not
11088 an C<Encode::XS> Encoding object, bad things will happen.
11089 (See F<lib/encoding.pm> and L<Encode>).
11091 The PV of the sv is returned.
11096 Perl_sv_recode_to_utf8(pTHX_ SV *sv, SV *encoding)
11098 if (SvPOK(sv) && !SvUTF8(sv) && !IN_BYTES && SvROK(encoding)) {
11112 Passing sv_yes is wrong - it needs to be or'ed set of constants
11113 for Encode::XS, while UTf-8 decode (currently) assumes a true value means
11114 remove converted chars from source.
11116 Both will default the value - let them.
11118 XPUSHs(&PL_sv_yes);
11121 call_method("decode", G_SCALAR);
11125 s = SvPV_const(uni, len);
11126 if (s != SvPVX_const(sv)) {
11127 SvGROW(sv, len + 1);
11128 Move(s, SvPVX(sv), len + 1, char);
11129 SvCUR_set(sv, len);
11136 return SvPOKp(sv) ? SvPVX(sv) : NULL;
11140 =for apidoc sv_cat_decode
11142 The encoding is assumed to be an Encode object, the PV of the ssv is
11143 assumed to be octets in that encoding and decoding the input starts
11144 from the position which (PV + *offset) pointed to. The dsv will be
11145 concatenated the decoded UTF-8 string from ssv. Decoding will terminate
11146 when the string tstr appears in decoding output or the input ends on
11147 the PV of the ssv. The value which the offset points will be modified
11148 to the last input position on the ssv.
11150 Returns TRUE if the terminator was found, else returns FALSE.
11155 Perl_sv_cat_decode(pTHX_ SV *dsv, SV *encoding,
11156 SV *ssv, int *offset, char *tstr, int tlen)
11159 if (SvPOK(ssv) && SvPOK(dsv) && SvROK(encoding) && offset) {
11170 XPUSHs(offsv = sv_2mortal(newSViv(*offset)));
11171 XPUSHs(sv_2mortal(newSVpvn(tstr, tlen)));
11173 call_method("cat_decode", G_SCALAR);
11175 ret = SvTRUE(TOPs);
11176 *offset = SvIV(offsv);
11182 Perl_croak(aTHX_ "Invalid argument to sv_cat_decode");
11188 * c-indentation-style: bsd
11189 * c-basic-offset: 4
11190 * indent-tabs-mode: t
11193 * ex: set ts=8 sts=4 sw=4 noet: