This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Correct the size calculations for FIT_ARENA for SVt_REGEXP.
[perl5.git] / sv.c
CommitLineData
a0d0e21e 1/* sv.c
79072805 2 *
1129b882 3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
83706693
RGS
4 * 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 by Larry Wall
5 * and others
79072805
LW
6 *
7 * You may distribute under the terms of either the GNU General Public
8 * License or the Artistic License, as specified in the README file.
9 *
4ac71550
TC
10 */
11
12/*
13 * 'I wonder what the Entish is for "yes" and "no",' he thought.
14 * --Pippin
15 *
16 * [p.480 of _The Lord of the Rings_, III/iv: "Treebeard"]
17 */
18
19/*
645c22ef
DM
20 *
21 *
5e045b90
AMS
22 * This file contains the code that creates, manipulates and destroys
23 * scalar values (SVs). The other types (AV, HV, GV, etc.) reuse the
24 * structure of an SV, so their creation and destruction is handled
25 * here; higher-level functions are in av.c, hv.c, and so on. Opcode
26 * level functions (eg. substr, split, join) for each of the types are
27 * in the pp*.c files.
79072805
LW
28 */
29
30#include "EXTERN.h"
864dbfa3 31#define PERL_IN_SV_C
79072805 32#include "perl.h"
d2f185dc 33#include "regcomp.h"
79072805 34
51371543 35#define FCALL *f
2c5424a7 36
2f8ed50e
OS
37#ifdef __Lynx__
38/* Missing proto on LynxOS */
39 char *gconvert(double, int, int, char *);
40#endif
41
e23c8137 42#ifdef PERL_UTF8_CACHE_ASSERT
ab455f60 43/* if adding more checks watch out for the following tests:
e23c8137
JH
44 * t/op/index.t t/op/length.t t/op/pat.t t/op/substr.t
45 * lib/utf8.t lib/Unicode/Collate/t/index.t
46 * --jhi
47 */
6f207bd3 48# define ASSERT_UTF8_CACHE(cache) \
ab455f60
NC
49 STMT_START { if (cache) { assert((cache)[0] <= (cache)[1]); \
50 assert((cache)[2] <= (cache)[3]); \
51 assert((cache)[3] <= (cache)[1]);} \
52 } STMT_END
e23c8137 53#else
6f207bd3 54# define ASSERT_UTF8_CACHE(cache) NOOP
e23c8137
JH
55#endif
56
f8c7b90f 57#ifdef PERL_OLD_COPY_ON_WRITE
765f542d 58#define SV_COW_NEXT_SV(sv) INT2PTR(SV *,SvUVX(sv))
607fa7f2 59#define SV_COW_NEXT_SV_SET(current,next) SvUV_set(current, PTR2UV(next))
b5ccf5f2 60/* This is a pessimistic view. Scalar must be purely a read-write PV to copy-
765f542d 61 on-write. */
765f542d 62#endif
645c22ef
DM
63
64/* ============================================================================
65
66=head1 Allocation and deallocation of SVs.
67
d2a0f284
JC
68An SV (or AV, HV, etc.) is allocated in two parts: the head (struct
69sv, av, hv...) contains type and reference count information, and for
70many types, a pointer to the body (struct xrv, xpv, xpviv...), which
71contains fields specific to each type. Some types store all they need
72in the head, so don't have a body.
73
74In all but the most memory-paranoid configuations (ex: PURIFY), heads
75and bodies are allocated out of arenas, which by default are
76approximately 4K chunks of memory parcelled up into N heads or bodies.
93e68bfb
JC
77Sv-bodies are allocated by their sv-type, guaranteeing size
78consistency needed to allocate safely from arrays.
79
d2a0f284
JC
80For SV-heads, the first slot in each arena is reserved, and holds a
81link to the next arena, some flags, and a note of the number of slots.
82Snaked through each arena chain is a linked list of free items; when
83this becomes empty, an extra arena is allocated and divided up into N
84items which are threaded into the free list.
85
86SV-bodies are similar, but they use arena-sets by default, which
87separate the link and info from the arena itself, and reclaim the 1st
88slot in the arena. SV-bodies are further described later.
645c22ef
DM
89
90The following global variables are associated with arenas:
91
92 PL_sv_arenaroot pointer to list of SV arenas
93 PL_sv_root pointer to list of free SV structures
94
d2a0f284
JC
95 PL_body_arenas head of linked-list of body arenas
96 PL_body_roots[] array of pointers to list of free bodies of svtype
97 arrays are indexed by the svtype needed
93e68bfb 98
d2a0f284
JC
99A few special SV heads are not allocated from an arena, but are
100instead directly created in the interpreter structure, eg PL_sv_undef.
93e68bfb
JC
101The size of arenas can be changed from the default by setting
102PERL_ARENA_SIZE appropriately at compile time.
645c22ef
DM
103
104The SV arena serves the secondary purpose of allowing still-live SVs
105to be located and destroyed during final cleanup.
106
107At the lowest level, the macros new_SV() and del_SV() grab and free
108an SV head. (If debugging with -DD, del_SV() calls the function S_del_sv()
109to return the SV to the free list with error checking.) new_SV() calls
110more_sv() / sv_add_arena() to add an extra arena if the free list is empty.
111SVs in the free list have their SvTYPE field set to all ones.
112
ff276b08 113At the time of very final cleanup, sv_free_arenas() is called from
645c22ef 114perl_destruct() to physically free all the arenas allocated since the
6a93a7e5 115start of the interpreter.
645c22ef 116
645c22ef
DM
117The function visit() scans the SV arenas list, and calls a specified
118function for each SV it finds which is still live - ie which has an SvTYPE
119other than all 1's, and a non-zero SvREFCNT. visit() is used by the
120following functions (specified as [function that calls visit()] / [function
121called by visit() for each SV]):
122
123 sv_report_used() / do_report_used()
f2524eef 124 dump all remaining SVs (debugging aid)
645c22ef
DM
125
126 sv_clean_objs() / do_clean_objs(),do_clean_named_objs()
127 Attempt to free all objects pointed to by RVs,
128 and, unless DISABLE_DESTRUCTOR_KLUDGE is defined,
129 try to do the same for all objects indirectly
130 referenced by typeglobs too. Called once from
131 perl_destruct(), prior to calling sv_clean_all()
132 below.
133
134 sv_clean_all() / do_clean_all()
135 SvREFCNT_dec(sv) each remaining SV, possibly
136 triggering an sv_free(). It also sets the
137 SVf_BREAK flag on the SV to indicate that the
138 refcnt has been artificially lowered, and thus
139 stopping sv_free() from giving spurious warnings
140 about SVs which unexpectedly have a refcnt
141 of zero. called repeatedly from perl_destruct()
142 until there are no SVs left.
143
93e68bfb 144=head2 Arena allocator API Summary
645c22ef
DM
145
146Private API to rest of sv.c
147
148 new_SV(), del_SV(),
149
df0f0429 150 new_XPVNV(), del_XPVGV(),
645c22ef
DM
151 etc
152
153Public API:
154
8cf8f3d1 155 sv_report_used(), sv_clean_objs(), sv_clean_all(), sv_free_arenas()
645c22ef 156
645c22ef
DM
157=cut
158
3e8320cc 159 * ========================================================================= */
645c22ef 160
4561caa4
CS
161/*
162 * "A time to plant, and a time to uproot what was planted..."
163 */
164
77354fb4 165void
de37a194 166Perl_offer_nice_chunk(pTHX_ void *const chunk, const U32 chunk_size)
77354fb4 167{
97aff369 168 dVAR;
77354fb4
NC
169 void *new_chunk;
170 U32 new_chunk_size;
7918f24d
NC
171
172 PERL_ARGS_ASSERT_OFFER_NICE_CHUNK;
173
77354fb4
NC
174 new_chunk = (void *)(chunk);
175 new_chunk_size = (chunk_size);
176 if (new_chunk_size > PL_nice_chunk_size) {
177 Safefree(PL_nice_chunk);
178 PL_nice_chunk = (char *) new_chunk;
179 PL_nice_chunk_size = new_chunk_size;
180 } else {
181 Safefree(chunk);
182 }
77354fb4 183}
cac9b346 184
d7a2c63c
MHM
185#ifdef PERL_MEM_LOG
186# define MEM_LOG_NEW_SV(sv, file, line, func) \
187 Perl_mem_log_new_sv(sv, file, line, func)
188# define MEM_LOG_DEL_SV(sv, file, line, func) \
189 Perl_mem_log_del_sv(sv, file, line, func)
190#else
191# define MEM_LOG_NEW_SV(sv, file, line, func) NOOP
192# define MEM_LOG_DEL_SV(sv, file, line, func) NOOP
193#endif
194
fd0854ff 195#ifdef DEBUG_LEAKING_SCALARS
22162ca8 196# define FREE_SV_DEBUG_FILE(sv) Safefree((sv)->sv_debug_file)
d7a2c63c
MHM
197# define DEBUG_SV_SERIAL(sv) \
198 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) del_SV\n", \
199 PTR2UV(sv), (long)(sv)->sv_debug_serial))
fd0854ff
DM
200#else
201# define FREE_SV_DEBUG_FILE(sv)
d7a2c63c 202# define DEBUG_SV_SERIAL(sv) NOOP
fd0854ff
DM
203#endif
204
48614a46
NC
205#ifdef PERL_POISON
206# define SvARENA_CHAIN(sv) ((sv)->sv_u.svu_rv)
daba3364 207# define SvARENA_CHAIN_SET(sv,val) (sv)->sv_u.svu_rv = MUTABLE_SV((val))
48614a46
NC
208/* Whilst I'd love to do this, it seems that things like to check on
209 unreferenced scalars
7e337ee0 210# define POSION_SV_HEAD(sv) PoisonNew(sv, 1, struct STRUCT_SV)
48614a46 211*/
7e337ee0
JH
212# define POSION_SV_HEAD(sv) PoisonNew(&SvANY(sv), 1, void *), \
213 PoisonNew(&SvREFCNT(sv), 1, U32)
48614a46
NC
214#else
215# define SvARENA_CHAIN(sv) SvANY(sv)
3eef1deb 216# define SvARENA_CHAIN_SET(sv,val) SvANY(sv) = (void *)(val)
48614a46
NC
217# define POSION_SV_HEAD(sv)
218#endif
219
990198f0
DM
220/* Mark an SV head as unused, and add to free list.
221 *
222 * If SVf_BREAK is set, skip adding it to the free list, as this SV had
223 * its refcount artificially decremented during global destruction, so
224 * there may be dangling pointers to it. The last thing we want in that
225 * case is for it to be reused. */
226
053fc874
GS
227#define plant_SV(p) \
228 STMT_START { \
990198f0 229 const U32 old_flags = SvFLAGS(p); \
d7a2c63c
MHM
230 MEM_LOG_DEL_SV(p, __FILE__, __LINE__, FUNCTION__); \
231 DEBUG_SV_SERIAL(p); \
fd0854ff 232 FREE_SV_DEBUG_FILE(p); \
48614a46 233 POSION_SV_HEAD(p); \
053fc874 234 SvFLAGS(p) = SVTYPEMASK; \
990198f0 235 if (!(old_flags & SVf_BREAK)) { \
3eef1deb 236 SvARENA_CHAIN_SET(p, PL_sv_root); \
990198f0
DM
237 PL_sv_root = (p); \
238 } \
053fc874
GS
239 --PL_sv_count; \
240 } STMT_END
a0d0e21e 241
053fc874
GS
242#define uproot_SV(p) \
243 STMT_START { \
244 (p) = PL_sv_root; \
daba3364 245 PL_sv_root = MUTABLE_SV(SvARENA_CHAIN(p)); \
053fc874
GS
246 ++PL_sv_count; \
247 } STMT_END
248
645c22ef 249
cac9b346
NC
250/* make some more SVs by adding another arena */
251
cac9b346
NC
252STATIC SV*
253S_more_sv(pTHX)
254{
97aff369 255 dVAR;
cac9b346
NC
256 SV* sv;
257
258 if (PL_nice_chunk) {
259 sv_add_arena(PL_nice_chunk, PL_nice_chunk_size, 0);
bd61b366 260 PL_nice_chunk = NULL;
cac9b346
NC
261 PL_nice_chunk_size = 0;
262 }
263 else {
264 char *chunk; /* must use New here to match call to */
d2a0f284 265 Newx(chunk,PERL_ARENA_SIZE,char); /* Safefree() in sv_free_arenas() */
2e7ed132 266 sv_add_arena(chunk, PERL_ARENA_SIZE, 0);
cac9b346
NC
267 }
268 uproot_SV(sv);
269 return sv;
270}
271
645c22ef
DM
272/* new_SV(): return a new, empty SV head */
273
eba0f806
DM
274#ifdef DEBUG_LEAKING_SCALARS
275/* provide a real function for a debugger to play with */
276STATIC SV*
d7a2c63c 277S_new_SV(pTHX_ const char *file, int line, const char *func)
eba0f806
DM
278{
279 SV* sv;
280
eba0f806
DM
281 if (PL_sv_root)
282 uproot_SV(sv);
283 else
cac9b346 284 sv = S_more_sv(aTHX);
eba0f806
DM
285 SvANY(sv) = 0;
286 SvREFCNT(sv) = 1;
287 SvFLAGS(sv) = 0;
fd0854ff 288 sv->sv_debug_optype = PL_op ? PL_op->op_type : 0;
e385c3bf
DM
289 sv->sv_debug_line = (U16) (PL_parser && PL_parser->copline != NOLINE
290 ? PL_parser->copline
291 : PL_curcop
f24aceb1
DM
292 ? CopLINE(PL_curcop)
293 : 0
e385c3bf 294 );
fd0854ff 295 sv->sv_debug_inpad = 0;
cd676548 296 sv->sv_debug_parent = NULL;
fd0854ff 297 sv->sv_debug_file = PL_curcop ? savepv(CopFILE(PL_curcop)): NULL;
d7a2c63c
MHM
298
299 sv->sv_debug_serial = PL_sv_serial++;
300
301 MEM_LOG_NEW_SV(sv, file, line, func);
302 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) new_SV (from %s:%d [%s])\n",
303 PTR2UV(sv), (long)sv->sv_debug_serial, file, line, func));
304
eba0f806
DM
305 return sv;
306}
d7a2c63c 307# define new_SV(p) (p)=S_new_SV(aTHX_ __FILE__, __LINE__, FUNCTION__)
eba0f806
DM
308
309#else
310# define new_SV(p) \
053fc874 311 STMT_START { \
053fc874
GS
312 if (PL_sv_root) \
313 uproot_SV(p); \
314 else \
cac9b346 315 (p) = S_more_sv(aTHX); \
053fc874
GS
316 SvANY(p) = 0; \
317 SvREFCNT(p) = 1; \
318 SvFLAGS(p) = 0; \
d7a2c63c 319 MEM_LOG_NEW_SV(p, __FILE__, __LINE__, FUNCTION__); \
053fc874 320 } STMT_END
eba0f806 321#endif
463ee0b2 322
645c22ef
DM
323
324/* del_SV(): return an empty SV head to the free list */
325
a0d0e21e 326#ifdef DEBUGGING
4561caa4 327
053fc874
GS
328#define del_SV(p) \
329 STMT_START { \
aea4f609 330 if (DEBUG_D_TEST) \
053fc874
GS
331 del_sv(p); \
332 else \
333 plant_SV(p); \
053fc874 334 } STMT_END
a0d0e21e 335
76e3520e 336STATIC void
cea2e8a9 337S_del_sv(pTHX_ SV *p)
463ee0b2 338{
97aff369 339 dVAR;
7918f24d
NC
340
341 PERL_ARGS_ASSERT_DEL_SV;
342
aea4f609 343 if (DEBUG_D_TEST) {
4633a7c4 344 SV* sva;
a3b680e6 345 bool ok = 0;
daba3364 346 for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
53c1dcc0
AL
347 const SV * const sv = sva + 1;
348 const SV * const svend = &sva[SvREFCNT(sva)];
c0ff570e 349 if (p >= sv && p < svend) {
a0d0e21e 350 ok = 1;
c0ff570e
NC
351 break;
352 }
a0d0e21e
LW
353 }
354 if (!ok) {
9b387841
NC
355 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
356 "Attempt to free non-arena SV: 0x%"UVxf
357 pTHX__FORMAT, PTR2UV(p) pTHX__VALUE);
a0d0e21e
LW
358 return;
359 }
360 }
4561caa4 361 plant_SV(p);
463ee0b2 362}
a0d0e21e 363
4561caa4
CS
364#else /* ! DEBUGGING */
365
366#define del_SV(p) plant_SV(p)
367
368#endif /* DEBUGGING */
463ee0b2 369
645c22ef
DM
370
371/*
ccfc67b7
JH
372=head1 SV Manipulation Functions
373
645c22ef
DM
374=for apidoc sv_add_arena
375
376Given a chunk of memory, link it to the head of the list of arenas,
377and split it into a list of free SVs.
378
379=cut
380*/
381
d2bd4e7f
NC
382static void
383S_sv_add_arena(pTHX_ char *const ptr, const U32 size, const U32 flags)
463ee0b2 384{
97aff369 385 dVAR;
daba3364 386 SV *const sva = MUTABLE_SV(ptr);
463ee0b2
LW
387 register SV* sv;
388 register SV* svend;
4633a7c4 389
7918f24d
NC
390 PERL_ARGS_ASSERT_SV_ADD_ARENA;
391
4633a7c4 392 /* The first SV in an arena isn't an SV. */
3280af22 393 SvANY(sva) = (void *) PL_sv_arenaroot; /* ptr to next arena */
4633a7c4
LW
394 SvREFCNT(sva) = size / sizeof(SV); /* number of SV slots */
395 SvFLAGS(sva) = flags; /* FAKE if not to be freed */
396
3280af22
NIS
397 PL_sv_arenaroot = sva;
398 PL_sv_root = sva + 1;
4633a7c4
LW
399
400 svend = &sva[SvREFCNT(sva) - 1];
401 sv = sva + 1;
463ee0b2 402 while (sv < svend) {
3eef1deb 403 SvARENA_CHAIN_SET(sv, (sv + 1));
03e36789 404#ifdef DEBUGGING
978b032e 405 SvREFCNT(sv) = 0;
03e36789 406#endif
4b69cbe3 407 /* Must always set typemask because it's always checked in on cleanup
03e36789 408 when the arenas are walked looking for objects. */
8990e307 409 SvFLAGS(sv) = SVTYPEMASK;
463ee0b2
LW
410 sv++;
411 }
3eef1deb 412 SvARENA_CHAIN_SET(sv, 0);
03e36789
NC
413#ifdef DEBUGGING
414 SvREFCNT(sv) = 0;
415#endif
4633a7c4
LW
416 SvFLAGS(sv) = SVTYPEMASK;
417}
418
055972dc
DM
419/* visit(): call the named function for each non-free SV in the arenas
420 * whose flags field matches the flags/mask args. */
645c22ef 421
5226ed68 422STATIC I32
de37a194 423S_visit(pTHX_ SVFUNC_t f, const U32 flags, const U32 mask)
8990e307 424{
97aff369 425 dVAR;
4633a7c4 426 SV* sva;
5226ed68 427 I32 visited = 0;
8990e307 428
7918f24d
NC
429 PERL_ARGS_ASSERT_VISIT;
430
daba3364 431 for (sva = PL_sv_arenaroot; sva; sva = MUTABLE_SV(SvANY(sva))) {
53c1dcc0 432 register const SV * const svend = &sva[SvREFCNT(sva)];
a3b680e6 433 register SV* sv;
4561caa4 434 for (sv = sva + 1; sv < svend; ++sv) {
055972dc
DM
435 if (SvTYPE(sv) != SVTYPEMASK
436 && (sv->sv_flags & mask) == flags
437 && SvREFCNT(sv))
438 {
acfe0abc 439 (FCALL)(aTHX_ sv);
5226ed68
JH
440 ++visited;
441 }
8990e307
LW
442 }
443 }
5226ed68 444 return visited;
8990e307
LW
445}
446
758a08c3
JH
447#ifdef DEBUGGING
448
645c22ef
DM
449/* called by sv_report_used() for each live SV */
450
451static void
5fa45a31 452do_report_used(pTHX_ SV *const sv)
645c22ef
DM
453{
454 if (SvTYPE(sv) != SVTYPEMASK) {
455 PerlIO_printf(Perl_debug_log, "****\n");
456 sv_dump(sv);
457 }
458}
758a08c3 459#endif
645c22ef
DM
460
461/*
462=for apidoc sv_report_used
463
464Dump the contents of all SVs not yet freed. (Debugging aid).
465
466=cut
467*/
468
8990e307 469void
864dbfa3 470Perl_sv_report_used(pTHX)
4561caa4 471{
ff270d3a 472#ifdef DEBUGGING
055972dc 473 visit(do_report_used, 0, 0);
96a5add6
AL
474#else
475 PERL_UNUSED_CONTEXT;
ff270d3a 476#endif
4561caa4
CS
477}
478
645c22ef
DM
479/* called by sv_clean_objs() for each live SV */
480
481static void
de37a194 482do_clean_objs(pTHX_ SV *const ref)
645c22ef 483{
97aff369 484 dVAR;
ea724faa
NC
485 assert (SvROK(ref));
486 {
823a54a3
AL
487 SV * const target = SvRV(ref);
488 if (SvOBJECT(target)) {
489 DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning object ref:\n "), sv_dump(ref)));
490 if (SvWEAKREF(ref)) {
491 sv_del_backref(target, ref);
492 SvWEAKREF_off(ref);
493 SvRV_set(ref, NULL);
494 } else {
495 SvROK_off(ref);
496 SvRV_set(ref, NULL);
497 SvREFCNT_dec(target);
498 }
645c22ef
DM
499 }
500 }
501
502 /* XXX Might want to check arrays, etc. */
503}
504
505/* called by sv_clean_objs() for each live SV */
506
507#ifndef DISABLE_DESTRUCTOR_KLUDGE
508static void
f30de749 509do_clean_named_objs(pTHX_ SV *const sv)
645c22ef 510{
97aff369 511 dVAR;
ea724faa 512 assert(SvTYPE(sv) == SVt_PVGV);
d011219a
NC
513 assert(isGV_with_GP(sv));
514 if (GvGP(sv)) {
c69033f2
NC
515 if ((
516#ifdef PERL_DONT_CREATE_GVSV
517 GvSV(sv) &&
518#endif
519 SvOBJECT(GvSV(sv))) ||
645c22ef
DM
520 (GvAV(sv) && SvOBJECT(GvAV(sv))) ||
521 (GvHV(sv) && SvOBJECT(GvHV(sv))) ||
9c12f1e5
RGS
522 /* In certain rare cases GvIOp(sv) can be NULL, which would make SvOBJECT(GvIO(sv)) dereference NULL. */
523 (GvIO(sv) ? (SvFLAGS(GvIOp(sv)) & SVs_OBJECT) : 0) ||
645c22ef
DM
524 (GvCV(sv) && SvOBJECT(GvCV(sv))) )
525 {
526 DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning named glob object:\n "), sv_dump(sv)));
ec5f3c78 527 SvFLAGS(sv) |= SVf_BREAK;
645c22ef
DM
528 SvREFCNT_dec(sv);
529 }
530 }
531}
532#endif
533
534/*
535=for apidoc sv_clean_objs
536
537Attempt to destroy all objects not yet freed
538
539=cut
540*/
541
4561caa4 542void
864dbfa3 543Perl_sv_clean_objs(pTHX)
4561caa4 544{
97aff369 545 dVAR;
3280af22 546 PL_in_clean_objs = TRUE;
055972dc 547 visit(do_clean_objs, SVf_ROK, SVf_ROK);
4561caa4 548#ifndef DISABLE_DESTRUCTOR_KLUDGE
2d0f3c12 549 /* some barnacles may yet remain, clinging to typeglobs */
d011219a 550 visit(do_clean_named_objs, SVt_PVGV|SVpgv_GP, SVTYPEMASK|SVp_POK|SVpgv_GP);
4561caa4 551#endif
3280af22 552 PL_in_clean_objs = FALSE;
4561caa4
CS
553}
554
645c22ef
DM
555/* called by sv_clean_all() for each live SV */
556
557static void
de37a194 558do_clean_all(pTHX_ SV *const sv)
645c22ef 559{
97aff369 560 dVAR;
daba3364 561 if (sv == (const SV *) PL_fdpid || sv == (const SV *)PL_strtab) {
cddfcddc 562 /* don't clean pid table and strtab */
d17ea597 563 return;
cddfcddc 564 }
645c22ef
DM
565 DEBUG_D((PerlIO_printf(Perl_debug_log, "Cleaning loops: SV at 0x%"UVxf"\n", PTR2UV(sv)) ));
566 SvFLAGS(sv) |= SVf_BREAK;
567 SvREFCNT_dec(sv);
568}
569
570/*
571=for apidoc sv_clean_all
572
573Decrement the refcnt of each remaining SV, possibly triggering a
574cleanup. This function may have to be called multiple times to free
ff276b08 575SVs which are in complex self-referential hierarchies.
645c22ef
DM
576
577=cut
578*/
579
5226ed68 580I32
864dbfa3 581Perl_sv_clean_all(pTHX)
8990e307 582{
97aff369 583 dVAR;
5226ed68 584 I32 cleaned;
3280af22 585 PL_in_clean_all = TRUE;
055972dc 586 cleaned = visit(do_clean_all, 0,0);
3280af22 587 PL_in_clean_all = FALSE;
5226ed68 588 return cleaned;
8990e307 589}
463ee0b2 590
5e258f8c
JC
591/*
592 ARENASETS: a meta-arena implementation which separates arena-info
593 into struct arena_set, which contains an array of struct
594 arena_descs, each holding info for a single arena. By separating
595 the meta-info from the arena, we recover the 1st slot, formerly
596 borrowed for list management. The arena_set is about the size of an
39244528 597 arena, avoiding the needless malloc overhead of a naive linked-list.
5e258f8c
JC
598
599 The cost is 1 arena-set malloc per ~320 arena-mallocs, + the unused
600 memory in the last arena-set (1/2 on average). In trade, we get
601 back the 1st slot in each arena (ie 1.7% of a CV-arena, less for
d2a0f284 602 smaller types). The recovery of the wasted space allows use of
e15dad31
JC
603 small arenas for large, rare body types, by changing array* fields
604 in body_details_by_type[] below.
5e258f8c 605*/
5e258f8c 606struct arena_desc {
398c677b
NC
607 char *arena; /* the raw storage, allocated aligned */
608 size_t size; /* its size ~4k typ */
e5973ed5 609 svtype utype; /* bodytype stored in arena */
5e258f8c
JC
610};
611
e6148039
NC
612struct arena_set;
613
614/* Get the maximum number of elements in set[] such that struct arena_set
e15dad31 615 will fit within PERL_ARENA_SIZE, which is probably just under 4K, and
e6148039
NC
616 therefore likely to be 1 aligned memory page. */
617
618#define ARENAS_PER_SET ((PERL_ARENA_SIZE - sizeof(struct arena_set*) \
619 - 2 * sizeof(int)) / sizeof (struct arena_desc))
5e258f8c
JC
620
621struct arena_set {
622 struct arena_set* next;
0a848332
NC
623 unsigned int set_size; /* ie ARENAS_PER_SET */
624 unsigned int curr; /* index of next available arena-desc */
5e258f8c
JC
625 struct arena_desc set[ARENAS_PER_SET];
626};
627
645c22ef
DM
628/*
629=for apidoc sv_free_arenas
630
631Deallocate the memory used by all arenas. Note that all the individual SV
632heads and bodies within the arenas must already have been freed.
633
634=cut
635*/
4633a7c4 636void
864dbfa3 637Perl_sv_free_arenas(pTHX)
4633a7c4 638{
97aff369 639 dVAR;
4633a7c4
LW
640 SV* sva;
641 SV* svanext;
0a848332 642 unsigned int i;
4633a7c4
LW
643
644 /* Free arenas here, but be careful about fake ones. (We assume
645 contiguity of the fake ones with the corresponding real ones.) */
646
3280af22 647 for (sva = PL_sv_arenaroot; sva; sva = svanext) {
daba3364 648 svanext = MUTABLE_SV(SvANY(sva));
4633a7c4 649 while (svanext && SvFAKE(svanext))
daba3364 650 svanext = MUTABLE_SV(SvANY(svanext));
4633a7c4
LW
651
652 if (!SvFAKE(sva))
1df70142 653 Safefree(sva);
4633a7c4 654 }
93e68bfb 655
5e258f8c 656 {
0a848332
NC
657 struct arena_set *aroot = (struct arena_set*) PL_body_arenas;
658
659 while (aroot) {
660 struct arena_set *current = aroot;
661 i = aroot->curr;
662 while (i--) {
5e258f8c
JC
663 assert(aroot->set[i].arena);
664 Safefree(aroot->set[i].arena);
665 }
0a848332
NC
666 aroot = aroot->next;
667 Safefree(current);
5e258f8c
JC
668 }
669 }
dc8220bf 670 PL_body_arenas = 0;
fdda85ca 671
0a848332
NC
672 i = PERL_ARENA_ROOTS_SIZE;
673 while (i--)
93e68bfb 674 PL_body_roots[i] = 0;
93e68bfb 675
43c5f42d 676 Safefree(PL_nice_chunk);
bd61b366 677 PL_nice_chunk = NULL;
3280af22
NIS
678 PL_nice_chunk_size = 0;
679 PL_sv_arenaroot = 0;
680 PL_sv_root = 0;
4633a7c4
LW
681}
682
bd81e77b
NC
683/*
684 Here are mid-level routines that manage the allocation of bodies out
685 of the various arenas. There are 5 kinds of arenas:
29489e7c 686
bd81e77b
NC
687 1. SV-head arenas, which are discussed and handled above
688 2. regular body arenas
689 3. arenas for reduced-size bodies
690 4. Hash-Entry arenas
29489e7c 691
bd81e77b
NC
692 Arena types 2 & 3 are chained by body-type off an array of
693 arena-root pointers, which is indexed by svtype. Some of the
694 larger/less used body types are malloced singly, since a large
695 unused block of them is wasteful. Also, several svtypes dont have
696 bodies; the data fits into the sv-head itself. The arena-root
697 pointer thus has a few unused root-pointers (which may be hijacked
698 later for arena types 4,5)
29489e7c 699
bd81e77b
NC
700 3 differs from 2 as an optimization; some body types have several
701 unused fields in the front of the structure (which are kept in-place
702 for consistency). These bodies can be allocated in smaller chunks,
703 because the leading fields arent accessed. Pointers to such bodies
704 are decremented to point at the unused 'ghost' memory, knowing that
705 the pointers are used with offsets to the real memory.
29489e7c 706
bd81e77b
NC
707 HE, HEK arenas are managed separately, with separate code, but may
708 be merge-able later..
bd81e77b
NC
709*/
710
bd26d9a3 711/* get_arena(size): this creates custom-sized arenas
5e258f8c
JC
712 TBD: export properly for hv.c: S_more_he().
713*/
714void*
e5973ed5 715Perl_get_arena(pTHX_ const size_t arena_size, const svtype bodytype)
5e258f8c 716{
7a89be66 717 dVAR;
5e258f8c 718 struct arena_desc* adesc;
39244528 719 struct arena_set *aroot = (struct arena_set*) PL_body_arenas;
0a848332 720 unsigned int curr;
5e258f8c 721
476a1e16
JC
722 /* shouldnt need this
723 if (!arena_size) arena_size = PERL_ARENA_SIZE;
724 */
5e258f8c
JC
725
726 /* may need new arena-set to hold new arena */
39244528
NC
727 if (!aroot || aroot->curr >= aroot->set_size) {
728 struct arena_set *newroot;
5e258f8c
JC
729 Newxz(newroot, 1, struct arena_set);
730 newroot->set_size = ARENAS_PER_SET;
39244528
NC
731 newroot->next = aroot;
732 aroot = newroot;
733 PL_body_arenas = (void *) newroot;
52944de8 734 DEBUG_m(PerlIO_printf(Perl_debug_log, "new arenaset %p\n", (void*)aroot));
5e258f8c
JC
735 }
736
737 /* ok, now have arena-set with at least 1 empty/available arena-desc */
39244528
NC
738 curr = aroot->curr++;
739 adesc = &(aroot->set[curr]);
5e258f8c
JC
740 assert(!adesc->arena);
741
89086707 742 Newx(adesc->arena, arena_size, char);
5e258f8c 743 adesc->size = arena_size;
e5973ed5 744 adesc->utype = bodytype;
d67b3c53
JH
745 DEBUG_m(PerlIO_printf(Perl_debug_log, "arena %d added: %p size %"UVuf"\n",
746 curr, (void*)adesc->arena, (UV)arena_size));
5e258f8c
JC
747
748 return adesc->arena;
5e258f8c
JC
749}
750
53c1dcc0 751
bd81e77b 752/* return a thing to the free list */
29489e7c 753
bd81e77b
NC
754#define del_body(thing, root) \
755 STMT_START { \
00b6aa41 756 void ** const thing_copy = (void **)thing;\
bd81e77b
NC
757 *thing_copy = *root; \
758 *root = (void*)thing_copy; \
bd81e77b 759 } STMT_END
29489e7c 760
bd81e77b 761/*
d2a0f284
JC
762
763=head1 SV-Body Allocation
764
765Allocation of SV-bodies is similar to SV-heads, differing as follows;
766the allocation mechanism is used for many body types, so is somewhat
767more complicated, it uses arena-sets, and has no need for still-live
768SV detection.
769
770At the outermost level, (new|del)_X*V macros return bodies of the
771appropriate type. These macros call either (new|del)_body_type or
772(new|del)_body_allocated macro pairs, depending on specifics of the
773type. Most body types use the former pair, the latter pair is used to
774allocate body types with "ghost fields".
775
776"ghost fields" are fields that are unused in certain types, and
69ba284b 777consequently don't need to actually exist. They are declared because
d2a0f284
JC
778they're part of a "base type", which allows use of functions as
779methods. The simplest examples are AVs and HVs, 2 aggregate types
780which don't use the fields which support SCALAR semantics.
781
69ba284b 782For these types, the arenas are carved up into appropriately sized
d2a0f284
JC
783chunks, we thus avoid wasted memory for those unaccessed members.
784When bodies are allocated, we adjust the pointer back in memory by the
69ba284b 785size of the part not allocated, so it's as if we allocated the full
d2a0f284
JC
786structure. (But things will all go boom if you write to the part that
787is "not there", because you'll be overwriting the last members of the
788preceding structure in memory.)
789
69ba284b
NC
790We calculate the correction using the STRUCT_OFFSET macro on the first
791member present. If the allocated structure is smaller (no initial NV
792actually allocated) then the net effect is to subtract the size of the NV
793from the pointer, to return a new pointer as if an initial NV were actually
794allocated. (We were using structures named *_allocated for this, but
795this turned out to be a subtle bug, because a structure without an NV
796could have a lower alignment constraint, but the compiler is allowed to
797optimised accesses based on the alignment constraint of the actual pointer
798to the full structure, for example, using a single 64 bit load instruction
799because it "knows" that two adjacent 32 bit members will be 8-byte aligned.)
d2a0f284
JC
800
801This is the same trick as was used for NV and IV bodies. Ironically it
802doesn't need to be used for NV bodies any more, because NV is now at
803the start of the structure. IV bodies don't need it either, because
804they are no longer allocated.
805
806In turn, the new_body_* allocators call S_new_body(), which invokes
807new_body_inline macro, which takes a lock, and takes a body off the
808linked list at PL_body_roots[sv_type], calling S_more_bodies() if
809necessary to refresh an empty list. Then the lock is released, and
810the body is returned.
811
812S_more_bodies calls get_arena(), and carves it up into an array of N
813bodies, which it strings into a linked list. It looks up arena-size
814and body-size from the body_details table described below, thus
815supporting the multiple body-types.
816
817If PURIFY is defined, or PERL_ARENA_SIZE=0, arenas are not used, and
818the (new|del)_X*V macros are mapped directly to malloc/free.
819
820*/
821
822/*
823
824For each sv-type, struct body_details bodies_by_type[] carries
825parameters which control these aspects of SV handling:
826
827Arena_size determines whether arenas are used for this body type, and if
828so, how big they are. PURIFY or PERL_ARENA_SIZE=0 set this field to
829zero, forcing individual mallocs and frees.
830
831Body_size determines how big a body is, and therefore how many fit into
832each arena. Offset carries the body-pointer adjustment needed for
69ba284b 833"ghost fields", and is used in *_allocated macros.
d2a0f284
JC
834
835But its main purpose is to parameterize info needed in
836Perl_sv_upgrade(). The info here dramatically simplifies the function
69ba284b 837vs the implementation in 5.8.8, making it table-driven. All fields
d2a0f284
JC
838are used for this, except for arena_size.
839
840For the sv-types that have no bodies, arenas are not used, so those
841PL_body_roots[sv_type] are unused, and can be overloaded. In
842something of a special case, SVt_NULL is borrowed for HE arenas;
c6f8b1d0 843PL_body_roots[HE_SVSLOT=SVt_NULL] is filled by S_more_he, but the
d2a0f284 844bodies_by_type[SVt_NULL] slot is not used, as the table is not
c6f8b1d0 845available in hv.c.
d2a0f284 846
29489e7c
DM
847*/
848
bd81e77b 849struct body_details {
0fb58b32 850 U8 body_size; /* Size to allocate */
10666ae3 851 U8 copy; /* Size of structure to copy (may be shorter) */
0fb58b32 852 U8 offset;
10666ae3
NC
853 unsigned int type : 4; /* We have space for a sanity check. */
854 unsigned int cant_upgrade : 1; /* Cannot upgrade this type */
855 unsigned int zero_nv : 1; /* zero the NV when upgrading from this */
856 unsigned int arena : 1; /* Allocated from an arena */
857 size_t arena_size; /* Size of arena to allocate */
bd81e77b 858};
29489e7c 859
bd81e77b
NC
860#define HADNV FALSE
861#define NONV TRUE
29489e7c 862
d2a0f284 863
bd81e77b
NC
864#ifdef PURIFY
865/* With -DPURFIY we allocate everything directly, and don't use arenas.
866 This seems a rather elegant way to simplify some of the code below. */
867#define HASARENA FALSE
868#else
869#define HASARENA TRUE
870#endif
871#define NOARENA FALSE
29489e7c 872
d2a0f284
JC
873/* Size the arenas to exactly fit a given number of bodies. A count
874 of 0 fits the max number bodies into a PERL_ARENA_SIZE.block,
875 simplifying the default. If count > 0, the arena is sized to fit
876 only that many bodies, allowing arenas to be used for large, rare
877 bodies (XPVFM, XPVIO) without undue waste. The arena size is
878 limited by PERL_ARENA_SIZE, so we can safely oversize the
879 declarations.
880 */
95db5f15
MB
881#define FIT_ARENA0(body_size) \
882 ((size_t)(PERL_ARENA_SIZE / body_size) * body_size)
883#define FIT_ARENAn(count,body_size) \
884 ( count * body_size <= PERL_ARENA_SIZE) \
885 ? count * body_size \
886 : FIT_ARENA0 (body_size)
887#define FIT_ARENA(count,body_size) \
888 count \
889 ? FIT_ARENAn (count, body_size) \
890 : FIT_ARENA0 (body_size)
d2a0f284 891
bd81e77b
NC
892/* Calculate the length to copy. Specifically work out the length less any
893 final padding the compiler needed to add. See the comment in sv_upgrade
894 for why copying the padding proved to be a bug. */
29489e7c 895
bd81e77b
NC
896#define copy_length(type, last_member) \
897 STRUCT_OFFSET(type, last_member) \
daba3364 898 + sizeof (((type*)SvANY((const SV *)0))->last_member)
29489e7c 899
bd81e77b 900static const struct body_details bodies_by_type[] = {
10666ae3
NC
901 { sizeof(HE), 0, 0, SVt_NULL,
902 FALSE, NONV, NOARENA, FIT_ARENA(0, sizeof(HE)) },
d2a0f284 903
1cb9cd50 904 /* The bind placeholder pretends to be an RV for now.
c6f8b1d0 905 Also it's marked as "can't upgrade" to stop anyone using it before it's
1cb9cd50
NC
906 implemented. */
907 { 0, 0, 0, SVt_BIND, TRUE, NONV, NOARENA, 0 },
908
db93c0c4
NC
909 /* IVs are in the head, so the allocation size is 0. */
910 { 0,
d2a0f284 911 sizeof(IV), /* This is used to copy out the IV body. */
10666ae3 912 STRUCT_OFFSET(XPVIV, xiv_iv), SVt_IV, FALSE, NONV,
db93c0c4 913 NOARENA /* IVS don't need an arena */, 0
d2a0f284
JC
914 },
915
bd81e77b 916 /* 8 bytes on most ILP32 with IEEE doubles */
6e128786
NC
917 { sizeof(NV), sizeof(NV),
918 STRUCT_OFFSET(XPVNV, xnv_u),
919 SVt_NV, FALSE, HADNV, HASARENA, FIT_ARENA(0, sizeof(NV)) },
d2a0f284 920
bd81e77b 921 /* 8 bytes on most ILP32 with IEEE doubles */
bc337e5c 922 { sizeof(XPV) - STRUCT_OFFSET(XPV, xpv_cur),
889d28b2
NC
923 copy_length(XPV, xpv_len) - STRUCT_OFFSET(XPV, xpv_cur),
924 + STRUCT_OFFSET(XPV, xpv_cur),
69ba284b 925 SVt_PV, FALSE, NONV, HASARENA,
889d28b2 926 FIT_ARENA(0, sizeof(XPV) - STRUCT_OFFSET(XPV, xpv_cur)) },
d2a0f284 927
bd81e77b 928 /* 12 */
bc337e5c 929 { sizeof(XPVIV) - STRUCT_OFFSET(XPV, xpv_cur),
889d28b2
NC
930 copy_length(XPVIV, xiv_u) - STRUCT_OFFSET(XPV, xpv_cur),
931 + STRUCT_OFFSET(XPV, xpv_cur),
932 SVt_PVIV, FALSE, NONV, HASARENA,
933 FIT_ARENA(0, sizeof(XPVIV) - STRUCT_OFFSET(XPV, xpv_cur)) },
d2a0f284 934
889d28b2 935 /* 20 */
bc337e5c 936 { sizeof(XPVNV) - STRUCT_OFFSET(XPV, xpv_cur),
889d28b2
NC
937 copy_length(XPVNV, xnv_u) - STRUCT_OFFSET(XPV, xpv_cur),
938 + STRUCT_OFFSET(XPV, xpv_cur),
939 SVt_PVNV, FALSE, HADNV, HASARENA,
940 FIT_ARENA(0, sizeof(XPVNV) - STRUCT_OFFSET(XPV, xpv_cur)) },
d2a0f284 941
bd81e77b 942 /* 28 */
6e128786 943 { sizeof(XPVMG), copy_length(XPVMG, xnv_u), 0, SVt_PVMG, FALSE, HADNV,
d2a0f284 944 HASARENA, FIT_ARENA(0, sizeof(XPVMG)) },
4df7f6af 945
288b8c02 946 /* something big */
601dfd0a
NC
947 { sizeof(regexp),
948 sizeof(regexp),
949 0,
08e44740 950 SVt_REGEXP, FALSE, NONV, HASARENA,
eaeb1e7f 951 FIT_ARENA(0, sizeof(regexp))
5c35adbb 952 },
4df7f6af 953
bd81e77b 954 /* 48 */
10666ae3 955 { sizeof(XPVGV), sizeof(XPVGV), 0, SVt_PVGV, TRUE, HADNV,
d2a0f284
JC
956 HASARENA, FIT_ARENA(0, sizeof(XPVGV)) },
957
bd81e77b 958 /* 64 */
10666ae3 959 { sizeof(XPVLV), sizeof(XPVLV), 0, SVt_PVLV, TRUE, HADNV,
d2a0f284
JC
960 HASARENA, FIT_ARENA(0, sizeof(XPVLV)) },
961
601dfd0a 962 { sizeof(XPVAV),
4f7003f5 963 copy_length(XPVAV, xav_alloc),
601dfd0a 964 0,
69ba284b 965 SVt_PVAV, TRUE, NONV, HASARENA,
601dfd0a 966 FIT_ARENA(0, sizeof(XPVAV)) },
d2a0f284 967
601dfd0a 968 { sizeof(XPVHV),
359164a0 969 copy_length(XPVHV, xhv_max),
601dfd0a 970 0,
69ba284b 971 SVt_PVHV, TRUE, NONV, HASARENA,
601dfd0a 972 FIT_ARENA(0, sizeof(XPVHV)) },
d2a0f284 973
c84c4652 974 /* 56 */
601dfd0a
NC
975 { sizeof(XPVCV),
976 sizeof(XPVCV),
977 0,
69ba284b 978 SVt_PVCV, TRUE, NONV, HASARENA,
601dfd0a 979 FIT_ARENA(0, sizeof(XPVCV)) },
69ba284b 980
601dfd0a
NC
981 { sizeof(XPVFM),
982 sizeof(XPVFM),
983 0,
69ba284b 984 SVt_PVFM, TRUE, NONV, NOARENA,
601dfd0a 985 FIT_ARENA(20, sizeof(XPVFM)) },
d2a0f284
JC
986
987 /* XPVIO is 84 bytes, fits 48x */
601dfd0a
NC
988 { sizeof(XPVIO),
989 sizeof(XPVIO),
990 0,
b6f60916 991 SVt_PVIO, TRUE, NONV, HASARENA,
601dfd0a 992 FIT_ARENA(24, sizeof(XPVIO)) },
bd81e77b 993};
29489e7c 994
bd81e77b 995#define new_body_allocated(sv_type) \
d2a0f284 996 (void *)((char *)S_new_body(aTHX_ sv_type) \
bd81e77b 997 - bodies_by_type[sv_type].offset)
29489e7c 998
bd81e77b
NC
999#define del_body_allocated(p, sv_type) \
1000 del_body(p + bodies_by_type[sv_type].offset, &PL_body_roots[sv_type])
29489e7c 1001
bd81e77b 1002#ifdef PURIFY
29489e7c 1003
beeec492
NC
1004#define new_XNV() safemalloc(sizeof(XPVNV))
1005#define new_XPVNV() safemalloc(sizeof(XPVNV))
1006#define new_XPVMG() safemalloc(sizeof(XPVMG))
29489e7c 1007
beeec492 1008#define del_XPVGV(p) safefree(p)
29489e7c 1009
bd81e77b 1010#else /* !PURIFY */
29489e7c 1011
65ac1738 1012#define new_XNV() new_body_allocated(SVt_NV)
65ac1738 1013#define new_XPVNV() new_body_allocated(SVt_PVNV)
65ac1738 1014#define new_XPVMG() new_body_allocated(SVt_PVMG)
645c22ef 1015
65ac1738 1016#define del_XPVGV(p) del_body_allocated(p, SVt_PVGV)
1d7c1841 1017
bd81e77b 1018#endif /* PURIFY */
93e68bfb 1019
bd81e77b 1020/* no arena for you! */
93e68bfb 1021
bd81e77b 1022#define new_NOARENA(details) \
beeec492 1023 safemalloc((details)->body_size + (details)->offset)
bd81e77b 1024#define new_NOARENAZ(details) \
beeec492 1025 safecalloc((details)->body_size + (details)->offset, 1)
d2a0f284
JC
1026
1027STATIC void *
de37a194 1028S_more_bodies (pTHX_ const svtype sv_type)
d2a0f284
JC
1029{
1030 dVAR;
1031 void ** const root = &PL_body_roots[sv_type];
96a5add6 1032 const struct body_details * const bdp = &bodies_by_type[sv_type];
d2a0f284
JC
1033 const size_t body_size = bdp->body_size;
1034 char *start;
1035 const char *end;
d8fca402 1036 const size_t arena_size = Perl_malloc_good_size(bdp->arena_size);
0b2d3faa 1037#if defined(DEBUGGING) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
23e9d66c
NC
1038 static bool done_sanity_check;
1039
0b2d3faa
JH
1040 /* PERL_GLOBAL_STRUCT_PRIVATE cannot coexist with global
1041 * variables like done_sanity_check. */
10666ae3 1042 if (!done_sanity_check) {
ea471437 1043 unsigned int i = SVt_LAST;
10666ae3
NC
1044
1045 done_sanity_check = TRUE;
1046
1047 while (i--)
1048 assert (bodies_by_type[i].type == i);
1049 }
1050#endif
1051
23e9d66c
NC
1052 assert(bdp->arena_size);
1053
d8fca402 1054 start = (char*) Perl_get_arena(aTHX_ arena_size, sv_type);
d2a0f284 1055
d8fca402 1056 end = start + arena_size - 2 * body_size;
d2a0f284 1057
d2a0f284 1058 /* computed count doesnt reflect the 1st slot reservation */
d8fca402
NC
1059#if defined(MYMALLOC) || defined(HAS_MALLOC_GOOD_SIZE)
1060 DEBUG_m(PerlIO_printf(Perl_debug_log,
1061 "arena %p end %p arena-size %d (from %d) type %d "
1062 "size %d ct %d\n",
1063 (void*)start, (void*)end, (int)arena_size,
1064 (int)bdp->arena_size, sv_type, (int)body_size,
1065 (int)arena_size / (int)body_size));
1066#else
d2a0f284
JC
1067 DEBUG_m(PerlIO_printf(Perl_debug_log,
1068 "arena %p end %p arena-size %d type %d size %d ct %d\n",
6c9570dc 1069 (void*)start, (void*)end,
0e84aef4
JH
1070 (int)bdp->arena_size, sv_type, (int)body_size,
1071 (int)bdp->arena_size / (int)body_size));
d8fca402 1072#endif
d2a0f284
JC
1073 *root = (void *)start;
1074
d8fca402 1075 while (start <= end) {
d2a0f284
JC
1076 char * const next = start + body_size;
1077 *(void**) start = (void *)next;
1078 start = next;
1079 }
1080 *(void **)start = 0;
1081
1082 return *root;
1083}
1084
1085/* grab a new thing from the free list, allocating more if necessary.
1086 The inline version is used for speed in hot routines, and the
1087 function using it serves the rest (unless PURIFY).
1088*/
1089#define new_body_inline(xpv, sv_type) \
1090 STMT_START { \
1091 void ** const r3wt = &PL_body_roots[sv_type]; \
11b79775
DD
1092 xpv = (PTR_TBL_ENT_t*) (*((void **)(r3wt)) \
1093 ? *((void **)(r3wt)) : more_bodies(sv_type)); \
d2a0f284 1094 *(r3wt) = *(void**)(xpv); \
d2a0f284
JC
1095 } STMT_END
1096
1097#ifndef PURIFY
1098
1099STATIC void *
de37a194 1100S_new_body(pTHX_ const svtype sv_type)
d2a0f284
JC
1101{
1102 dVAR;
1103 void *xpv;
1104 new_body_inline(xpv, sv_type);
1105 return xpv;
1106}
1107
1108#endif
93e68bfb 1109
238b27b3
NC
1110static const struct body_details fake_rv =
1111 { 0, 0, 0, SVt_IV, FALSE, NONV, NOARENA, 0 };
1112
bd81e77b
NC
1113/*
1114=for apidoc sv_upgrade
93e68bfb 1115
bd81e77b
NC
1116Upgrade an SV to a more complex form. Generally adds a new body type to the
1117SV, then copies across as much information as possible from the old body.
1118You generally want to use the C<SvUPGRADE> macro wrapper. See also C<svtype>.
93e68bfb 1119
bd81e77b 1120=cut
93e68bfb 1121*/
93e68bfb 1122
bd81e77b 1123void
aad570aa 1124Perl_sv_upgrade(pTHX_ register SV *const sv, svtype new_type)
cac9b346 1125{
97aff369 1126 dVAR;
bd81e77b
NC
1127 void* old_body;
1128 void* new_body;
42d0e0b7 1129 const svtype old_type = SvTYPE(sv);
d2a0f284 1130 const struct body_details *new_type_details;
238b27b3 1131 const struct body_details *old_type_details
bd81e77b 1132 = bodies_by_type + old_type;
4df7f6af 1133 SV *referant = NULL;
cac9b346 1134
7918f24d
NC
1135 PERL_ARGS_ASSERT_SV_UPGRADE;
1136
1776cbe8
NC
1137 if (old_type == new_type)
1138 return;
1139
1140 /* This clause was purposefully added ahead of the early return above to
1141 the shared string hackery for (sort {$a <=> $b} keys %hash), with the
1142 inference by Nick I-S that it would fix other troublesome cases. See
1143 changes 7162, 7163 (f130fd4589cf5fbb24149cd4db4137c8326f49c1 and parent)
1144
1145 Given that shared hash key scalars are no longer PVIV, but PV, there is
1146 no longer need to unshare so as to free up the IVX slot for its proper
1147 purpose. So it's safe to move the early return earlier. */
1148
bd81e77b
NC
1149 if (new_type != SVt_PV && SvIsCOW(sv)) {
1150 sv_force_normal_flags(sv, 0);
1151 }
cac9b346 1152
bd81e77b 1153 old_body = SvANY(sv);
de042e1d 1154
bd81e77b
NC
1155 /* Copying structures onto other structures that have been neatly zeroed
1156 has a subtle gotcha. Consider XPVMG
cac9b346 1157
bd81e77b
NC
1158 +------+------+------+------+------+-------+-------+
1159 | NV | CUR | LEN | IV | MAGIC | STASH |
1160 +------+------+------+------+------+-------+-------+
1161 0 4 8 12 16 20 24 28
645c22ef 1162
bd81e77b
NC
1163 where NVs are aligned to 8 bytes, so that sizeof that structure is
1164 actually 32 bytes long, with 4 bytes of padding at the end:
08742458 1165
bd81e77b
NC
1166 +------+------+------+------+------+-------+-------+------+
1167 | NV | CUR | LEN | IV | MAGIC | STASH | ??? |
1168 +------+------+------+------+------+-------+-------+------+
1169 0 4 8 12 16 20 24 28 32
08742458 1170
bd81e77b 1171 so what happens if you allocate memory for this structure:
30f9da9e 1172
bd81e77b
NC
1173 +------+------+------+------+------+-------+-------+------+------+...
1174 | NV | CUR | LEN | IV | MAGIC | STASH | GP | NAME |
1175 +------+------+------+------+------+-------+-------+------+------+...
1176 0 4 8 12 16 20 24 28 32 36
bfc44f79 1177
bd81e77b
NC
1178 zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
1179 expect, because you copy the area marked ??? onto GP. Now, ??? may have
1180 started out as zero once, but it's quite possible that it isn't. So now,
1181 rather than a nicely zeroed GP, you have it pointing somewhere random.
1182 Bugs ensue.
bfc44f79 1183
bd81e77b
NC
1184 (In fact, GP ends up pointing at a previous GP structure, because the
1185 principle cause of the padding in XPVMG getting garbage is a copy of
6c9e42f7
NC
1186 sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob. Right now
1187 this happens to be moot because XPVGV has been re-ordered, with GP
1188 no longer after STASH)
30f9da9e 1189
bd81e77b
NC
1190 So we are careful and work out the size of used parts of all the
1191 structures. */
bfc44f79 1192
bd81e77b
NC
1193 switch (old_type) {
1194 case SVt_NULL:
1195 break;
1196 case SVt_IV:
4df7f6af
NC
1197 if (SvROK(sv)) {
1198 referant = SvRV(sv);
238b27b3
NC
1199 old_type_details = &fake_rv;
1200 if (new_type == SVt_NV)
1201 new_type = SVt_PVNV;
4df7f6af
NC
1202 } else {
1203 if (new_type < SVt_PVIV) {
1204 new_type = (new_type == SVt_NV)
1205 ? SVt_PVNV : SVt_PVIV;
1206 }
bd81e77b
NC
1207 }
1208 break;
1209 case SVt_NV:
1210 if (new_type < SVt_PVNV) {
1211 new_type = SVt_PVNV;
bd81e77b
NC
1212 }
1213 break;
bd81e77b
NC
1214 case SVt_PV:
1215 assert(new_type > SVt_PV);
1216 assert(SVt_IV < SVt_PV);
1217 assert(SVt_NV < SVt_PV);
1218 break;
1219 case SVt_PVIV:
1220 break;
1221 case SVt_PVNV:
1222 break;
1223 case SVt_PVMG:
1224 /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1225 there's no way that it can be safely upgraded, because perl.c
1226 expects to Safefree(SvANY(PL_mess_sv)) */
1227 assert(sv != PL_mess_sv);
1228 /* This flag bit is used to mean other things in other scalar types.
1229 Given that it only has meaning inside the pad, it shouldn't be set
1230 on anything that can get upgraded. */
00b1698f 1231 assert(!SvPAD_TYPED(sv));
bd81e77b
NC
1232 break;
1233 default:
1234 if (old_type_details->cant_upgrade)
c81225bc
NC
1235 Perl_croak(aTHX_ "Can't upgrade %s (%" UVuf ") to %" UVuf,
1236 sv_reftype(sv, 0), (UV) old_type, (UV) new_type);
bd81e77b 1237 }
3376de98
NC
1238
1239 if (old_type > new_type)
1240 Perl_croak(aTHX_ "sv_upgrade from type %d down to type %d",
1241 (int)old_type, (int)new_type);
1242
2fa1109b 1243 new_type_details = bodies_by_type + new_type;
645c22ef 1244
bd81e77b
NC
1245 SvFLAGS(sv) &= ~SVTYPEMASK;
1246 SvFLAGS(sv) |= new_type;
932e9ff9 1247
ab4416c0
NC
1248 /* This can't happen, as SVt_NULL is <= all values of new_type, so one of
1249 the return statements above will have triggered. */
1250 assert (new_type != SVt_NULL);
bd81e77b 1251 switch (new_type) {
bd81e77b
NC
1252 case SVt_IV:
1253 assert(old_type == SVt_NULL);
1254 SvANY(sv) = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
1255 SvIV_set(sv, 0);
1256 return;
1257 case SVt_NV:
1258 assert(old_type == SVt_NULL);
1259 SvANY(sv) = new_XNV();
1260 SvNV_set(sv, 0);
1261 return;
bd81e77b 1262 case SVt_PVHV:
bd81e77b 1263 case SVt_PVAV:
d2a0f284 1264 assert(new_type_details->body_size);
c1ae03ae
NC
1265
1266#ifndef PURIFY
1267 assert(new_type_details->arena);
d2a0f284 1268 assert(new_type_details->arena_size);
c1ae03ae 1269 /* This points to the start of the allocated area. */
d2a0f284
JC
1270 new_body_inline(new_body, new_type);
1271 Zero(new_body, new_type_details->body_size, char);
c1ae03ae
NC
1272 new_body = ((char *)new_body) - new_type_details->offset;
1273#else
1274 /* We always allocated the full length item with PURIFY. To do this
1275 we fake things so that arena is false for all 16 types.. */
1276 new_body = new_NOARENAZ(new_type_details);
1277#endif
1278 SvANY(sv) = new_body;
1279 if (new_type == SVt_PVAV) {
1280 AvMAX(sv) = -1;
1281 AvFILLp(sv) = -1;
1282 AvREAL_only(sv);
64484faa 1283 if (old_type_details->body_size) {
ac572bf4
NC
1284 AvALLOC(sv) = 0;
1285 } else {
1286 /* It will have been zeroed when the new body was allocated.
1287 Lets not write to it, in case it confuses a write-back
1288 cache. */
1289 }
78ac7dd9
NC
1290 } else {
1291 assert(!SvOK(sv));
1292 SvOK_off(sv);
1293#ifndef NODEFAULT_SHAREKEYS
1294 HvSHAREKEYS_on(sv); /* key-sharing on by default */
1295#endif
1296 HvMAX(sv) = 7; /* (start with 8 buckets) */
c1ae03ae 1297 }
aeb18a1e 1298
bd81e77b
NC
1299 /* SVt_NULL isn't the only thing upgraded to AV or HV.
1300 The target created by newSVrv also is, and it can have magic.
1301 However, it never has SvPVX set.
1302 */
4df7f6af
NC
1303 if (old_type == SVt_IV) {
1304 assert(!SvROK(sv));
1305 } else if (old_type >= SVt_PV) {
bd81e77b
NC
1306 assert(SvPVX_const(sv) == 0);
1307 }
aeb18a1e 1308
bd81e77b 1309 if (old_type >= SVt_PVMG) {
e736a858 1310 SvMAGIC_set(sv, ((XPVMG*)old_body)->xmg_u.xmg_magic);
bd81e77b 1311 SvSTASH_set(sv, ((XPVMG*)old_body)->xmg_stash);
797c7171
NC
1312 } else {
1313 sv->sv_u.svu_array = NULL; /* or svu_hash */
bd81e77b
NC
1314 }
1315 break;
93e68bfb 1316
93e68bfb 1317
b9ad13ac
NC
1318 case SVt_REGEXP:
1319 /* This ensures that SvTHINKFIRST(sv) is true, and hence that
1320 sv_force_normal_flags(sv) is called. */
1321 SvFAKE_on(sv);
bd81e77b
NC
1322 case SVt_PVIV:
1323 /* XXX Is this still needed? Was it ever needed? Surely as there is
1324 no route from NV to PVIV, NOK can never be true */
1325 assert(!SvNOKp(sv));
1326 assert(!SvNOK(sv));
1327 case SVt_PVIO:
1328 case SVt_PVFM:
bd81e77b
NC
1329 case SVt_PVGV:
1330 case SVt_PVCV:
1331 case SVt_PVLV:
1332 case SVt_PVMG:
1333 case SVt_PVNV:
1334 case SVt_PV:
93e68bfb 1335
d2a0f284 1336 assert(new_type_details->body_size);
bd81e77b
NC
1337 /* We always allocated the full length item with PURIFY. To do this
1338 we fake things so that arena is false for all 16 types.. */
1339 if(new_type_details->arena) {
1340 /* This points to the start of the allocated area. */
d2a0f284
JC
1341 new_body_inline(new_body, new_type);
1342 Zero(new_body, new_type_details->body_size, char);
bd81e77b
NC
1343 new_body = ((char *)new_body) - new_type_details->offset;
1344 } else {
1345 new_body = new_NOARENAZ(new_type_details);
1346 }
1347 SvANY(sv) = new_body;
5e2fc214 1348
bd81e77b 1349 if (old_type_details->copy) {
f9ba3d20
NC
1350 /* There is now the potential for an upgrade from something without
1351 an offset (PVNV or PVMG) to something with one (PVCV, PVFM) */
1352 int offset = old_type_details->offset;
1353 int length = old_type_details->copy;
1354
1355 if (new_type_details->offset > old_type_details->offset) {
d4c19fe8 1356 const int difference
f9ba3d20
NC
1357 = new_type_details->offset - old_type_details->offset;
1358 offset += difference;
1359 length -= difference;
1360 }
1361 assert (length >= 0);
1362
1363 Copy((char *)old_body + offset, (char *)new_body + offset, length,
1364 char);
bd81e77b
NC
1365 }
1366
1367#ifndef NV_ZERO_IS_ALLBITS_ZERO
f2524eef 1368 /* If NV 0.0 is stores as all bits 0 then Zero() already creates a
e5ce394c
NC
1369 * correct 0.0 for us. Otherwise, if the old body didn't have an
1370 * NV slot, but the new one does, then we need to initialise the
1371 * freshly created NV slot with whatever the correct bit pattern is
1372 * for 0.0 */
e22a937e
NC
1373 if (old_type_details->zero_nv && !new_type_details->zero_nv
1374 && !isGV_with_GP(sv))
bd81e77b 1375 SvNV_set(sv, 0);
82048762 1376#endif
5e2fc214 1377
85dca89a
NC
1378 if (new_type == SVt_PVIO) {
1379 IO * const io = MUTABLE_IO(sv);
d963bf01 1380 GV *iogv = gv_fetchpvs("IO::File::", GV_ADD, SVt_PVHV);
85dca89a
NC
1381
1382 SvOBJECT_on(io);
1383 /* Clear the stashcache because a new IO could overrule a package
1384 name */
1385 hv_clear(PL_stashcache);
1386
85dca89a 1387 SvSTASH_set(io, MUTABLE_HV(SvREFCNT_inc(GvHV(iogv))));
f2524eef 1388 IoPAGE_LEN(sv) = 60;
85dca89a 1389 }
4df7f6af
NC
1390 if (old_type < SVt_PV) {
1391 /* referant will be NULL unless the old type was SVt_IV emulating
1392 SVt_RV */
1393 sv->sv_u.svu_rv = referant;
1394 }
bd81e77b
NC
1395 break;
1396 default:
afd78fd5
JH
1397 Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu",
1398 (unsigned long)new_type);
bd81e77b 1399 }
73171d91 1400
db93c0c4 1401 if (old_type > SVt_IV) {
bd81e77b 1402#ifdef PURIFY
beeec492 1403 safefree(old_body);
bd81e77b 1404#else
bc786448
GG
1405 /* Note that there is an assumption that all bodies of types that
1406 can be upgraded came from arenas. Only the more complex non-
1407 upgradable types are allowed to be directly malloc()ed. */
1408 assert(old_type_details->arena);
bd81e77b
NC
1409 del_body((void*)((char*)old_body + old_type_details->offset),
1410 &PL_body_roots[old_type]);
1411#endif
1412 }
1413}
73171d91 1414
bd81e77b
NC
1415/*
1416=for apidoc sv_backoff
73171d91 1417
bd81e77b
NC
1418Remove any string offset. You should normally use the C<SvOOK_off> macro
1419wrapper instead.
73171d91 1420
bd81e77b 1421=cut
73171d91
NC
1422*/
1423
bd81e77b 1424int
aad570aa 1425Perl_sv_backoff(pTHX_ register SV *const sv)
bd81e77b 1426{
69240efd 1427 STRLEN delta;
7a4bba22 1428 const char * const s = SvPVX_const(sv);
7918f24d
NC
1429
1430 PERL_ARGS_ASSERT_SV_BACKOFF;
96a5add6 1431 PERL_UNUSED_CONTEXT;
7918f24d 1432
bd81e77b
NC
1433 assert(SvOOK(sv));
1434 assert(SvTYPE(sv) != SVt_PVHV);
1435 assert(SvTYPE(sv) != SVt_PVAV);
7a4bba22 1436
69240efd
NC
1437 SvOOK_offset(sv, delta);
1438
7a4bba22
NC
1439 SvLEN_set(sv, SvLEN(sv) + delta);
1440 SvPV_set(sv, SvPVX(sv) - delta);
1441 Move(s, SvPVX(sv), SvCUR(sv)+1, char);
bd81e77b
NC
1442 SvFLAGS(sv) &= ~SVf_OOK;
1443 return 0;
1444}
73171d91 1445
bd81e77b
NC
1446/*
1447=for apidoc sv_grow
73171d91 1448
bd81e77b
NC
1449Expands the character buffer in the SV. If necessary, uses C<sv_unref> and
1450upgrades the SV to C<SVt_PV>. Returns a pointer to the character buffer.
1451Use the C<SvGROW> wrapper instead.
93e68bfb 1452
bd81e77b
NC
1453=cut
1454*/
93e68bfb 1455
bd81e77b 1456char *
aad570aa 1457Perl_sv_grow(pTHX_ register SV *const sv, register STRLEN newlen)
bd81e77b
NC
1458{
1459 register char *s;
93e68bfb 1460
7918f24d
NC
1461 PERL_ARGS_ASSERT_SV_GROW;
1462
5db06880
NC
1463 if (PL_madskills && newlen >= 0x100000) {
1464 PerlIO_printf(Perl_debug_log,
1465 "Allocation too large: %"UVxf"\n", (UV)newlen);
1466 }
bd81e77b
NC
1467#ifdef HAS_64K_LIMIT
1468 if (newlen >= 0x10000) {
1469 PerlIO_printf(Perl_debug_log,
1470 "Allocation too large: %"UVxf"\n", (UV)newlen);
1471 my_exit(1);
1472 }
1473#endif /* HAS_64K_LIMIT */
1474 if (SvROK(sv))
1475 sv_unref(sv);
1476 if (SvTYPE(sv) < SVt_PV) {
1477 sv_upgrade(sv, SVt_PV);
1478 s = SvPVX_mutable(sv);
1479 }
1480 else if (SvOOK(sv)) { /* pv is offset? */
1481 sv_backoff(sv);
1482 s = SvPVX_mutable(sv);
1483 if (newlen > SvLEN(sv))
1484 newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1485#ifdef HAS_64K_LIMIT
1486 if (newlen >= 0x10000)
1487 newlen = 0xFFFF;
1488#endif
1489 }
1490 else
1491 s = SvPVX_mutable(sv);
aeb18a1e 1492
bd81e77b 1493 if (newlen > SvLEN(sv)) { /* need more room? */
f1200559
WH
1494 STRLEN minlen = SvCUR(sv);
1495 minlen += (minlen >> PERL_STRLEN_EXPAND_SHIFT) + 10;
1496 if (newlen < minlen)
1497 newlen = minlen;
aedff202 1498#ifndef Perl_safesysmalloc_size
bd81e77b 1499 newlen = PERL_STRLEN_ROUNDUP(newlen);
bd81e77b 1500#endif
98653f18 1501 if (SvLEN(sv) && s) {
10edeb5d 1502 s = (char*)saferealloc(s, newlen);
bd81e77b
NC
1503 }
1504 else {
10edeb5d 1505 s = (char*)safemalloc(newlen);
bd81e77b
NC
1506 if (SvPVX_const(sv) && SvCUR(sv)) {
1507 Move(SvPVX_const(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1508 }
1509 }
1510 SvPV_set(sv, s);
ca7c1a29 1511#ifdef Perl_safesysmalloc_size
98653f18
NC
1512 /* Do this here, do it once, do it right, and then we will never get
1513 called back into sv_grow() unless there really is some growing
1514 needed. */
ca7c1a29 1515 SvLEN_set(sv, Perl_safesysmalloc_size(s));
98653f18 1516#else
bd81e77b 1517 SvLEN_set(sv, newlen);
98653f18 1518#endif
bd81e77b
NC
1519 }
1520 return s;
1521}
aeb18a1e 1522
bd81e77b
NC
1523/*
1524=for apidoc sv_setiv
932e9ff9 1525
bd81e77b
NC
1526Copies an integer into the given SV, upgrading first if necessary.
1527Does not handle 'set' magic. See also C<sv_setiv_mg>.
463ee0b2 1528
bd81e77b
NC
1529=cut
1530*/
463ee0b2 1531
bd81e77b 1532void
aad570aa 1533Perl_sv_setiv(pTHX_ register SV *const sv, const IV i)
bd81e77b 1534{
97aff369 1535 dVAR;
7918f24d
NC
1536
1537 PERL_ARGS_ASSERT_SV_SETIV;
1538
bd81e77b
NC
1539 SV_CHECK_THINKFIRST_COW_DROP(sv);
1540 switch (SvTYPE(sv)) {
1541 case SVt_NULL:
bd81e77b 1542 case SVt_NV:
3376de98 1543 sv_upgrade(sv, SVt_IV);
bd81e77b 1544 break;
bd81e77b
NC
1545 case SVt_PV:
1546 sv_upgrade(sv, SVt_PVIV);
1547 break;
463ee0b2 1548
bd81e77b 1549 case SVt_PVGV:
6e592b3a
BM
1550 if (!isGV_with_GP(sv))
1551 break;
bd81e77b
NC
1552 case SVt_PVAV:
1553 case SVt_PVHV:
1554 case SVt_PVCV:
1555 case SVt_PVFM:
1556 case SVt_PVIO:
1557 Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1558 OP_DESC(PL_op));
42d0e0b7 1559 default: NOOP;
bd81e77b
NC
1560 }
1561 (void)SvIOK_only(sv); /* validate number */
1562 SvIV_set(sv, i);
1563 SvTAINT(sv);
1564}
932e9ff9 1565
bd81e77b
NC
1566/*
1567=for apidoc sv_setiv_mg
d33b2eba 1568
bd81e77b 1569Like C<sv_setiv>, but also handles 'set' magic.
1c846c1f 1570
bd81e77b
NC
1571=cut
1572*/
d33b2eba 1573
bd81e77b 1574void
aad570aa 1575Perl_sv_setiv_mg(pTHX_ register SV *const sv, const IV i)
bd81e77b 1576{
7918f24d
NC
1577 PERL_ARGS_ASSERT_SV_SETIV_MG;
1578
bd81e77b
NC
1579 sv_setiv(sv,i);
1580 SvSETMAGIC(sv);
1581}
727879eb 1582
bd81e77b
NC
1583/*
1584=for apidoc sv_setuv
d33b2eba 1585
bd81e77b
NC
1586Copies an unsigned integer into the given SV, upgrading first if necessary.
1587Does not handle 'set' magic. See also C<sv_setuv_mg>.
9b94d1dd 1588
bd81e77b
NC
1589=cut
1590*/
d33b2eba 1591
bd81e77b 1592void
aad570aa 1593Perl_sv_setuv(pTHX_ register SV *const sv, const UV u)
bd81e77b 1594{
7918f24d
NC
1595 PERL_ARGS_ASSERT_SV_SETUV;
1596
bd81e77b
NC
1597 /* With these two if statements:
1598 u=1.49 s=0.52 cu=72.49 cs=10.64 scripts=270 tests=20865
d33b2eba 1599
bd81e77b
NC
1600 without
1601 u=1.35 s=0.47 cu=73.45 cs=11.43 scripts=270 tests=20865
1c846c1f 1602
bd81e77b
NC
1603 If you wish to remove them, please benchmark to see what the effect is
1604 */
1605 if (u <= (UV)IV_MAX) {
1606 sv_setiv(sv, (IV)u);
1607 return;
1608 }
1609 sv_setiv(sv, 0);
1610 SvIsUV_on(sv);
1611 SvUV_set(sv, u);
1612}
d33b2eba 1613
bd81e77b
NC
1614/*
1615=for apidoc sv_setuv_mg
727879eb 1616
bd81e77b 1617Like C<sv_setuv>, but also handles 'set' magic.
9b94d1dd 1618
bd81e77b
NC
1619=cut
1620*/
5e2fc214 1621
bd81e77b 1622void
aad570aa 1623Perl_sv_setuv_mg(pTHX_ register SV *const sv, const UV u)
bd81e77b 1624{
7918f24d
NC
1625 PERL_ARGS_ASSERT_SV_SETUV_MG;
1626
bd81e77b
NC
1627 sv_setuv(sv,u);
1628 SvSETMAGIC(sv);
1629}
5e2fc214 1630
954c1994 1631/*
bd81e77b 1632=for apidoc sv_setnv
954c1994 1633
bd81e77b
NC
1634Copies a double into the given SV, upgrading first if necessary.
1635Does not handle 'set' magic. See also C<sv_setnv_mg>.
954c1994
GS
1636
1637=cut
1638*/
1639
63f97190 1640void
aad570aa 1641Perl_sv_setnv(pTHX_ register SV *const sv, const NV num)
79072805 1642{
97aff369 1643 dVAR;
7918f24d
NC
1644
1645 PERL_ARGS_ASSERT_SV_SETNV;
1646
bd81e77b
NC
1647 SV_CHECK_THINKFIRST_COW_DROP(sv);
1648 switch (SvTYPE(sv)) {
79072805 1649 case SVt_NULL:
79072805 1650 case SVt_IV:
bd81e77b 1651 sv_upgrade(sv, SVt_NV);
79072805
LW
1652 break;
1653 case SVt_PV:
79072805 1654 case SVt_PVIV:
bd81e77b 1655 sv_upgrade(sv, SVt_PVNV);
79072805 1656 break;
bd4b1eb5 1657
bd4b1eb5 1658 case SVt_PVGV:
6e592b3a
BM
1659 if (!isGV_with_GP(sv))
1660 break;
bd81e77b
NC
1661 case SVt_PVAV:
1662 case SVt_PVHV:
79072805 1663 case SVt_PVCV:
bd81e77b
NC
1664 case SVt_PVFM:
1665 case SVt_PVIO:
1666 Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
94bbb3f4 1667 OP_DESC(PL_op));
42d0e0b7 1668 default: NOOP;
2068cd4d 1669 }
bd81e77b
NC
1670 SvNV_set(sv, num);
1671 (void)SvNOK_only(sv); /* validate number */
1672 SvTAINT(sv);
79072805
LW
1673}
1674
645c22ef 1675/*
bd81e77b 1676=for apidoc sv_setnv_mg
645c22ef 1677
bd81e77b 1678Like C<sv_setnv>, but also handles 'set' magic.
645c22ef
DM
1679
1680=cut
1681*/
1682
bd81e77b 1683void
aad570aa 1684Perl_sv_setnv_mg(pTHX_ register SV *const sv, const NV num)
79072805 1685{
7918f24d
NC
1686 PERL_ARGS_ASSERT_SV_SETNV_MG;
1687
bd81e77b
NC
1688 sv_setnv(sv,num);
1689 SvSETMAGIC(sv);
79072805
LW
1690}
1691
bd81e77b
NC
1692/* Print an "isn't numeric" warning, using a cleaned-up,
1693 * printable version of the offending string
1694 */
954c1994 1695
bd81e77b 1696STATIC void
aad570aa 1697S_not_a_number(pTHX_ SV *const sv)
79072805 1698{
97aff369 1699 dVAR;
bd81e77b
NC
1700 SV *dsv;
1701 char tmpbuf[64];
1702 const char *pv;
94463019 1703
7918f24d
NC
1704 PERL_ARGS_ASSERT_NOT_A_NUMBER;
1705
94463019 1706 if (DO_UTF8(sv)) {
84bafc02 1707 dsv = newSVpvs_flags("", SVs_TEMP);
94463019
JH
1708 pv = sv_uni_display(dsv, sv, 10, 0);
1709 } else {
1710 char *d = tmpbuf;
551405c4 1711 const char * const limit = tmpbuf + sizeof(tmpbuf) - 8;
94463019
JH
1712 /* each *s can expand to 4 chars + "...\0",
1713 i.e. need room for 8 chars */
ecdeb87c 1714
00b6aa41
AL
1715 const char *s = SvPVX_const(sv);
1716 const char * const end = s + SvCUR(sv);
1717 for ( ; s < end && d < limit; s++ ) {
94463019
JH
1718 int ch = *s & 0xFF;
1719 if (ch & 128 && !isPRINT_LC(ch)) {
1720 *d++ = 'M';
1721 *d++ = '-';
1722 ch &= 127;
1723 }
1724 if (ch == '\n') {
1725 *d++ = '\\';
1726 *d++ = 'n';
1727 }
1728 else if (ch == '\r') {
1729 *d++ = '\\';
1730 *d++ = 'r';
1731 }
1732 else if (ch == '\f') {
1733 *d++ = '\\';
1734 *d++ = 'f';
1735 }
1736 else if (ch == '\\') {
1737 *d++ = '\\';
1738 *d++ = '\\';
1739 }
1740 else if (ch == '\0') {
1741 *d++ = '\\';
1742 *d++ = '0';
1743 }
1744 else if (isPRINT_LC(ch))
1745 *d++ = ch;
1746 else {
1747 *d++ = '^';
1748 *d++ = toCTRL(ch);
1749 }
1750 }
1751 if (s < end) {
1752 *d++ = '.';
1753 *d++ = '.';
1754 *d++ = '.';
1755 }
1756 *d = '\0';
1757 pv = tmpbuf;
a0d0e21e 1758 }
a0d0e21e 1759
533c011a 1760 if (PL_op)
9014280d 1761 Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
94463019
JH
1762 "Argument \"%s\" isn't numeric in %s", pv,
1763 OP_DESC(PL_op));
a0d0e21e 1764 else
9014280d 1765 Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
94463019 1766 "Argument \"%s\" isn't numeric", pv);
a0d0e21e
LW
1767}
1768
c2988b20
NC
1769/*
1770=for apidoc looks_like_number
1771
645c22ef
DM
1772Test if the content of an SV looks like a number (or is a number).
1773C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1774non-numeric warning), even if your atof() doesn't grok them.
c2988b20
NC
1775
1776=cut
1777*/
1778
1779I32
aad570aa 1780Perl_looks_like_number(pTHX_ SV *const sv)
c2988b20 1781{
a3b680e6 1782 register const char *sbegin;
c2988b20
NC
1783 STRLEN len;
1784
7918f24d
NC
1785 PERL_ARGS_ASSERT_LOOKS_LIKE_NUMBER;
1786
c2988b20 1787 if (SvPOK(sv)) {
3f7c398e 1788 sbegin = SvPVX_const(sv);
c2988b20
NC
1789 len = SvCUR(sv);
1790 }
1791 else if (SvPOKp(sv))
83003860 1792 sbegin = SvPV_const(sv, len);
c2988b20 1793 else
e0ab1c0e 1794 return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
c2988b20
NC
1795 return grok_number(sbegin, len, NULL);
1796}
25da4f38 1797
19f6321d
NC
1798STATIC bool
1799S_glob_2number(pTHX_ GV * const gv)
180488f8
NC
1800{
1801 const U32 wasfake = SvFLAGS(gv) & SVf_FAKE;
1802 SV *const buffer = sv_newmortal();
1803
7918f24d
NC
1804 PERL_ARGS_ASSERT_GLOB_2NUMBER;
1805
180488f8
NC
1806 /* FAKE globs can get coerced, so need to turn this off temporarily if it
1807 is on. */
1808 SvFAKE_off(gv);
1809 gv_efullname3(buffer, gv, "*");
1810 SvFLAGS(gv) |= wasfake;
1811
675c862f
AL
1812 /* We know that all GVs stringify to something that is not-a-number,
1813 so no need to test that. */
1814 if (ckWARN(WARN_NUMERIC))
1815 not_a_number(buffer);
1816 /* We just want something true to return, so that S_sv_2iuv_common
1817 can tail call us and return true. */
19f6321d 1818 return TRUE;
675c862f
AL
1819}
1820
25da4f38
IZ
1821/* Actually, ISO C leaves conversion of UV to IV undefined, but
1822 until proven guilty, assume that things are not that bad... */
1823
645c22ef
DM
1824/*
1825 NV_PRESERVES_UV:
1826
1827 As 64 bit platforms often have an NV that doesn't preserve all bits of
28e5dec8
JH
1828 an IV (an assumption perl has been based on to date) it becomes necessary
1829 to remove the assumption that the NV always carries enough precision to
1830 recreate the IV whenever needed, and that the NV is the canonical form.
1831 Instead, IV/UV and NV need to be given equal rights. So as to not lose
645c22ef 1832 precision as a side effect of conversion (which would lead to insanity
28e5dec8
JH
1833 and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1834 1) to distinguish between IV/UV/NV slots that have cached a valid
1835 conversion where precision was lost and IV/UV/NV slots that have a
1836 valid conversion which has lost no precision
645c22ef 1837 2) to ensure that if a numeric conversion to one form is requested that
28e5dec8
JH
1838 would lose precision, the precise conversion (or differently
1839 imprecise conversion) is also performed and cached, to prevent
1840 requests for different numeric formats on the same SV causing
1841 lossy conversion chains. (lossless conversion chains are perfectly
1842 acceptable (still))
1843
1844
1845 flags are used:
1846 SvIOKp is true if the IV slot contains a valid value
1847 SvIOK is true only if the IV value is accurate (UV if SvIOK_UV true)
1848 SvNOKp is true if the NV slot contains a valid value
1849 SvNOK is true only if the NV value is accurate
1850
1851 so
645c22ef 1852 while converting from PV to NV, check to see if converting that NV to an
28e5dec8
JH
1853 IV(or UV) would lose accuracy over a direct conversion from PV to
1854 IV(or UV). If it would, cache both conversions, return NV, but mark
1855 SV as IOK NOKp (ie not NOK).
1856
645c22ef 1857 While converting from PV to IV, check to see if converting that IV to an
28e5dec8
JH
1858 NV would lose accuracy over a direct conversion from PV to NV. If it
1859 would, cache both conversions, flag similarly.
1860
1861 Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1862 correctly because if IV & NV were set NV *always* overruled.
645c22ef
DM
1863 Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1864 changes - now IV and NV together means that the two are interchangeable:
28e5dec8 1865 SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
d460ef45 1866
645c22ef
DM
1867 The benefit of this is that operations such as pp_add know that if
1868 SvIOK is true for both left and right operands, then integer addition
1869 can be used instead of floating point (for cases where the result won't
1870 overflow). Before, floating point was always used, which could lead to
28e5dec8
JH
1871 loss of precision compared with integer addition.
1872
1873 * making IV and NV equal status should make maths accurate on 64 bit
1874 platforms
1875 * may speed up maths somewhat if pp_add and friends start to use
645c22ef 1876 integers when possible instead of fp. (Hopefully the overhead in
28e5dec8
JH
1877 looking for SvIOK and checking for overflow will not outweigh the
1878 fp to integer speedup)
1879 * will slow down integer operations (callers of SvIV) on "inaccurate"
1880 values, as the change from SvIOK to SvIOKp will cause a call into
1881 sv_2iv each time rather than a macro access direct to the IV slot
1882 * should speed up number->string conversion on integers as IV is
645c22ef 1883 favoured when IV and NV are equally accurate
28e5dec8
JH
1884
1885 ####################################################################
645c22ef
DM
1886 You had better be using SvIOK_notUV if you want an IV for arithmetic:
1887 SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
1888 On the other hand, SvUOK is true iff UV.
28e5dec8
JH
1889 ####################################################################
1890
645c22ef 1891 Your mileage will vary depending your CPU's relative fp to integer
28e5dec8
JH
1892 performance ratio.
1893*/
1894
1895#ifndef NV_PRESERVES_UV
645c22ef
DM
1896# define IS_NUMBER_UNDERFLOW_IV 1
1897# define IS_NUMBER_UNDERFLOW_UV 2
1898# define IS_NUMBER_IV_AND_UV 2
1899# define IS_NUMBER_OVERFLOW_IV 4
1900# define IS_NUMBER_OVERFLOW_UV 5
1901
1902/* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
28e5dec8
JH
1903
1904/* For sv_2nv these three cases are "SvNOK and don't bother casting" */
1905STATIC int
5de3775c 1906S_sv_2iuv_non_preserve(pTHX_ register SV *const sv
47031da6
NC
1907# ifdef DEBUGGING
1908 , I32 numtype
1909# endif
1910 )
28e5dec8 1911{
97aff369 1912 dVAR;
7918f24d
NC
1913
1914 PERL_ARGS_ASSERT_SV_2IUV_NON_PRESERVE;
1915
3f7c398e 1916 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));
28e5dec8
JH
1917 if (SvNVX(sv) < (NV)IV_MIN) {
1918 (void)SvIOKp_on(sv);
1919 (void)SvNOK_on(sv);
45977657 1920 SvIV_set(sv, IV_MIN);
28e5dec8
JH
1921 return IS_NUMBER_UNDERFLOW_IV;
1922 }
1923 if (SvNVX(sv) > (NV)UV_MAX) {
1924 (void)SvIOKp_on(sv);
1925 (void)SvNOK_on(sv);
1926 SvIsUV_on(sv);
607fa7f2 1927 SvUV_set(sv, UV_MAX);
28e5dec8
JH
1928 return IS_NUMBER_OVERFLOW_UV;
1929 }
c2988b20
NC
1930 (void)SvIOKp_on(sv);
1931 (void)SvNOK_on(sv);
1932 /* Can't use strtol etc to convert this string. (See truth table in
1933 sv_2iv */
1934 if (SvNVX(sv) <= (UV)IV_MAX) {
45977657 1935 SvIV_set(sv, I_V(SvNVX(sv)));
c2988b20
NC
1936 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
1937 SvIOK_on(sv); /* Integer is precise. NOK, IOK */
1938 } else {
1939 /* Integer is imprecise. NOK, IOKp */
1940 }
1941 return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
1942 }
1943 SvIsUV_on(sv);
607fa7f2 1944 SvUV_set(sv, U_V(SvNVX(sv)));
c2988b20
NC
1945 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
1946 if (SvUVX(sv) == UV_MAX) {
1947 /* As we know that NVs don't preserve UVs, UV_MAX cannot
1948 possibly be preserved by NV. Hence, it must be overflow.
1949 NOK, IOKp */
1950 return IS_NUMBER_OVERFLOW_UV;
1951 }
1952 SvIOK_on(sv); /* Integer is precise. NOK, UOK */
1953 } else {
1954 /* Integer is imprecise. NOK, IOKp */
28e5dec8 1955 }
c2988b20 1956 return IS_NUMBER_OVERFLOW_IV;
28e5dec8 1957}
645c22ef
DM
1958#endif /* !NV_PRESERVES_UV*/
1959
af359546 1960STATIC bool
7918f24d
NC
1961S_sv_2iuv_common(pTHX_ SV *const sv)
1962{
97aff369 1963 dVAR;
7918f24d
NC
1964
1965 PERL_ARGS_ASSERT_SV_2IUV_COMMON;
1966
af359546 1967 if (SvNOKp(sv)) {
28e5dec8
JH
1968 /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
1969 * without also getting a cached IV/UV from it at the same time
1970 * (ie PV->NV conversion should detect loss of accuracy and cache
af359546
NC
1971 * IV or UV at same time to avoid this. */
1972 /* IV-over-UV optimisation - choose to cache IV if possible */
25da4f38
IZ
1973
1974 if (SvTYPE(sv) == SVt_NV)
1975 sv_upgrade(sv, SVt_PVNV);
1976
28e5dec8
JH
1977 (void)SvIOKp_on(sv); /* Must do this first, to clear any SvOOK */
1978 /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
1979 certainly cast into the IV range at IV_MAX, whereas the correct
1980 answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
1981 cases go to UV */
cab190d4
JD
1982#if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
1983 if (Perl_isnan(SvNVX(sv))) {
1984 SvUV_set(sv, 0);
1985 SvIsUV_on(sv);
fdbe6d7c 1986 return FALSE;
cab190d4 1987 }
cab190d4 1988#endif
28e5dec8 1989 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
45977657 1990 SvIV_set(sv, I_V(SvNVX(sv)));
28e5dec8
JH
1991 if (SvNVX(sv) == (NV) SvIVX(sv)
1992#ifndef NV_PRESERVES_UV
1993 && (((UV)1 << NV_PRESERVES_UV_BITS) >
1994 (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
1995 /* Don't flag it as "accurately an integer" if the number
1996 came from a (by definition imprecise) NV operation, and
1997 we're outside the range of NV integer precision */
1998#endif
1999 ) {
a43d94f2
NC
2000 if (SvNOK(sv))
2001 SvIOK_on(sv); /* Can this go wrong with rounding? NWC */
2002 else {
2003 /* scalar has trailing garbage, eg "42a" */
2004 }
28e5dec8 2005 DEBUG_c(PerlIO_printf(Perl_debug_log,
7234c960 2006 "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
28e5dec8
JH
2007 PTR2UV(sv),
2008 SvNVX(sv),
2009 SvIVX(sv)));
2010
2011 } else {
2012 /* IV not precise. No need to convert from PV, as NV
2013 conversion would already have cached IV if it detected
2014 that PV->IV would be better than PV->NV->IV
2015 flags already correct - don't set public IOK. */
2016 DEBUG_c(PerlIO_printf(Perl_debug_log,
7234c960 2017 "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
28e5dec8
JH
2018 PTR2UV(sv),
2019 SvNVX(sv),
2020 SvIVX(sv)));
2021 }
2022 /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2023 but the cast (NV)IV_MIN rounds to a the value less (more
2024 negative) than IV_MIN which happens to be equal to SvNVX ??
2025 Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2026 NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2027 (NV)UVX == NVX are both true, but the values differ. :-(
2028 Hopefully for 2s complement IV_MIN is something like
2029 0x8000000000000000 which will be exact. NWC */
d460ef45 2030 }
25da4f38 2031 else {
607fa7f2 2032 SvUV_set(sv, U_V(SvNVX(sv)));
28e5dec8
JH
2033 if (
2034 (SvNVX(sv) == (NV) SvUVX(sv))
2035#ifndef NV_PRESERVES_UV
2036 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2037 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2038 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2039 /* Don't flag it as "accurately an integer" if the number
2040 came from a (by definition imprecise) NV operation, and
2041 we're outside the range of NV integer precision */
2042#endif
a43d94f2 2043 && SvNOK(sv)
28e5dec8
JH
2044 )
2045 SvIOK_on(sv);
25da4f38 2046 SvIsUV_on(sv);
1c846c1f 2047 DEBUG_c(PerlIO_printf(Perl_debug_log,
57def98f 2048 "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
56431972 2049 PTR2UV(sv),
57def98f
JH
2050 SvUVX(sv),
2051 SvUVX(sv)));
25da4f38 2052 }
748a9306
LW
2053 }
2054 else if (SvPOKp(sv) && SvLEN(sv)) {
c2988b20 2055 UV value;
504618e9 2056 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
af359546 2057 /* We want to avoid a possible problem when we cache an IV/ a UV which
25da4f38 2058 may be later translated to an NV, and the resulting NV is not
c2988b20
NC
2059 the same as the direct translation of the initial string
2060 (eg 123.456 can shortcut to the IV 123 with atol(), but we must
2061 be careful to ensure that the value with the .456 is around if the
2062 NV value is requested in the future).
1c846c1f 2063
af359546 2064 This means that if we cache such an IV/a UV, we need to cache the
25da4f38 2065 NV as well. Moreover, we trade speed for space, and do not
28e5dec8 2066 cache the NV if we are sure it's not needed.
25da4f38 2067 */
16b7a9a4 2068
c2988b20
NC
2069 /* SVt_PVNV is one higher than SVt_PVIV, hence this order */
2070 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2071 == IS_NUMBER_IN_UV) {
5e045b90 2072 /* It's definitely an integer, only upgrade to PVIV */
28e5dec8
JH
2073 if (SvTYPE(sv) < SVt_PVIV)
2074 sv_upgrade(sv, SVt_PVIV);
f7bbb42a 2075 (void)SvIOK_on(sv);
c2988b20
NC
2076 } else if (SvTYPE(sv) < SVt_PVNV)
2077 sv_upgrade(sv, SVt_PVNV);
28e5dec8 2078
f2524eef 2079 /* If NVs preserve UVs then we only use the UV value if we know that
c2988b20
NC
2080 we aren't going to call atof() below. If NVs don't preserve UVs
2081 then the value returned may have more precision than atof() will
2082 return, even though value isn't perfectly accurate. */
2083 if ((numtype & (IS_NUMBER_IN_UV
2084#ifdef NV_PRESERVES_UV
2085 | IS_NUMBER_NOT_INT
2086#endif
2087 )) == IS_NUMBER_IN_UV) {
2088 /* This won't turn off the public IOK flag if it was set above */
2089 (void)SvIOKp_on(sv);
2090
2091 if (!(numtype & IS_NUMBER_NEG)) {
2092 /* positive */;
2093 if (value <= (UV)IV_MAX) {
45977657 2094 SvIV_set(sv, (IV)value);
c2988b20 2095 } else {
af359546 2096 /* it didn't overflow, and it was positive. */
607fa7f2 2097 SvUV_set(sv, value);
c2988b20
NC
2098 SvIsUV_on(sv);
2099 }
2100 } else {
2101 /* 2s complement assumption */
2102 if (value <= (UV)IV_MIN) {
45977657 2103 SvIV_set(sv, -(IV)value);
c2988b20
NC
2104 } else {
2105 /* Too negative for an IV. This is a double upgrade, but
d1be9408 2106 I'm assuming it will be rare. */
c2988b20
NC
2107 if (SvTYPE(sv) < SVt_PVNV)
2108 sv_upgrade(sv, SVt_PVNV);
2109 SvNOK_on(sv);
2110 SvIOK_off(sv);
2111 SvIOKp_on(sv);
9d6ce603 2112 SvNV_set(sv, -(NV)value);
45977657 2113 SvIV_set(sv, IV_MIN);
c2988b20
NC
2114 }
2115 }
2116 }
2117 /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2118 will be in the previous block to set the IV slot, and the next
2119 block to set the NV slot. So no else here. */
2120
2121 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2122 != IS_NUMBER_IN_UV) {
2123 /* It wasn't an (integer that doesn't overflow the UV). */
3f7c398e 2124 SvNV_set(sv, Atof(SvPVX_const(sv)));
28e5dec8 2125
c2988b20
NC
2126 if (! numtype && ckWARN(WARN_NUMERIC))
2127 not_a_number(sv);
28e5dec8 2128
65202027 2129#if defined(USE_LONG_DOUBLE)
c2988b20
NC
2130 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" PERL_PRIgldbl ")\n",
2131 PTR2UV(sv), SvNVX(sv)));
65202027 2132#else
1779d84d 2133 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"NVgf")\n",
c2988b20 2134 PTR2UV(sv), SvNVX(sv)));
65202027 2135#endif
28e5dec8 2136
28e5dec8 2137#ifdef NV_PRESERVES_UV
af359546
NC
2138 (void)SvIOKp_on(sv);
2139 (void)SvNOK_on(sv);
2140 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2141 SvIV_set(sv, I_V(SvNVX(sv)));
2142 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2143 SvIOK_on(sv);
2144 } else {
6f207bd3 2145 NOOP; /* Integer is imprecise. NOK, IOKp */
af359546
NC
2146 }
2147 /* UV will not work better than IV */
2148 } else {
2149 if (SvNVX(sv) > (NV)UV_MAX) {
2150 SvIsUV_on(sv);
2151 /* Integer is inaccurate. NOK, IOKp, is UV */
2152 SvUV_set(sv, UV_MAX);
af359546
NC
2153 } else {
2154 SvUV_set(sv, U_V(SvNVX(sv)));
2155 /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2156 NV preservse UV so can do correct comparison. */
2157 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2158 SvIOK_on(sv);
af359546 2159 } else {
6f207bd3 2160 NOOP; /* Integer is imprecise. NOK, IOKp, is UV */
af359546
NC
2161 }
2162 }
4b0c9573 2163 SvIsUV_on(sv);
af359546 2164 }
28e5dec8 2165#else /* NV_PRESERVES_UV */
c2988b20
NC
2166 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2167 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
af359546 2168 /* The IV/UV slot will have been set from value returned by
c2988b20
NC
2169 grok_number above. The NV slot has just been set using
2170 Atof. */
560b0c46 2171 SvNOK_on(sv);
c2988b20
NC
2172 assert (SvIOKp(sv));
2173 } else {
2174 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2175 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2176 /* Small enough to preserve all bits. */
2177 (void)SvIOKp_on(sv);
2178 SvNOK_on(sv);
45977657 2179 SvIV_set(sv, I_V(SvNVX(sv)));
c2988b20
NC
2180 if ((NV)(SvIVX(sv)) == SvNVX(sv))
2181 SvIOK_on(sv);
2182 /* Assumption: first non-preserved integer is < IV_MAX,
2183 this NV is in the preserved range, therefore: */
2184 if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2185 < (UV)IV_MAX)) {
32fdb065 2186 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);
c2988b20
NC
2187 }
2188 } else {
2189 /* IN_UV NOT_INT
2190 0 0 already failed to read UV.
2191 0 1 already failed to read UV.
2192 1 0 you won't get here in this case. IV/UV
2193 slot set, public IOK, Atof() unneeded.
2194 1 1 already read UV.
2195 so there's no point in sv_2iuv_non_preserve() attempting
2196 to use atol, strtol, strtoul etc. */
47031da6 2197# ifdef DEBUGGING
40a17c4c 2198 sv_2iuv_non_preserve (sv, numtype);
47031da6
NC
2199# else
2200 sv_2iuv_non_preserve (sv);
2201# endif
c2988b20
NC
2202 }
2203 }
28e5dec8 2204#endif /* NV_PRESERVES_UV */
a43d94f2
NC
2205 /* It might be more code efficient to go through the entire logic above
2206 and conditionally set with SvIOKp_on() rather than SvIOK(), but it
2207 gets complex and potentially buggy, so more programmer efficient
2208 to do it this way, by turning off the public flags: */
2209 if (!numtype)
2210 SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
25da4f38 2211 }
af359546
NC
2212 }
2213 else {
675c862f 2214 if (isGV_with_GP(sv))
159b6efe 2215 return glob_2number(MUTABLE_GV(sv));
180488f8 2216
af359546
NC
2217 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2218 if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2219 report_uninit(sv);
2220 }
25da4f38
IZ
2221 if (SvTYPE(sv) < SVt_IV)
2222 /* Typically the caller expects that sv_any is not NULL now. */
2223 sv_upgrade(sv, SVt_IV);
af359546
NC
2224 /* Return 0 from the caller. */
2225 return TRUE;
2226 }
2227 return FALSE;
2228}
2229
2230/*
2231=for apidoc sv_2iv_flags
2232
2233Return the integer value of an SV, doing any necessary string
2234conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2235Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2236
2237=cut
2238*/
2239
2240IV
5de3775c 2241Perl_sv_2iv_flags(pTHX_ register SV *const sv, const I32 flags)
af359546 2242{
97aff369 2243 dVAR;
af359546 2244 if (!sv)
a0d0e21e 2245 return 0;
cecf5685
NC
2246 if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2247 /* FBMs use the same flag bit as SVf_IVisUV, so must let them
50caf62e
NC
2248 cache IVs just in case. In practice it seems that they never
2249 actually anywhere accessible by user Perl code, let alone get used
2250 in anything other than a string context. */
af359546
NC
2251 if (flags & SV_GMAGIC)
2252 mg_get(sv);
2253 if (SvIOKp(sv))
2254 return SvIVX(sv);
2255 if (SvNOKp(sv)) {
2256 return I_V(SvNVX(sv));
2257 }
71c558c3
NC
2258 if (SvPOKp(sv) && SvLEN(sv)) {
2259 UV value;
2260 const int numtype
2261 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2262
2263 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2264 == IS_NUMBER_IN_UV) {
2265 /* It's definitely an integer */
2266 if (numtype & IS_NUMBER_NEG) {
2267 if (value < (UV)IV_MIN)
2268 return -(IV)value;
2269 } else {
2270 if (value < (UV)IV_MAX)
2271 return (IV)value;
2272 }
2273 }
2274 if (!numtype) {
2275 if (ckWARN(WARN_NUMERIC))
2276 not_a_number(sv);
2277 }
2278 return I_V(Atof(SvPVX_const(sv)));
2279 }
1c7ff15e
NC
2280 if (SvROK(sv)) {
2281 goto return_rok;
af359546 2282 }
1c7ff15e
NC
2283 assert(SvTYPE(sv) >= SVt_PVMG);
2284 /* This falls through to the report_uninit inside S_sv_2iuv_common. */
4cb1ec55 2285 } else if (SvTHINKFIRST(sv)) {
af359546 2286 if (SvROK(sv)) {
1c7ff15e 2287 return_rok:
af359546 2288 if (SvAMAGIC(sv)) {
aee036bb
DM
2289 SV * tmpstr;
2290 if (flags & SV_SKIP_OVERLOAD)
2291 return 0;
2292 tmpstr=AMG_CALLun(sv,numer);
af359546
NC
2293 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2294 return SvIV(tmpstr);
2295 }
2296 }
2297 return PTR2IV(SvRV(sv));
2298 }
2299 if (SvIsCOW(sv)) {
2300 sv_force_normal_flags(sv, 0);
2301 }
2302 if (SvREADONLY(sv) && !SvOK(sv)) {
2303 if (ckWARN(WARN_UNINITIALIZED))
2304 report_uninit(sv);
2305 return 0;
2306 }
2307 }
2308 if (!SvIOKp(sv)) {
2309 if (S_sv_2iuv_common(aTHX_ sv))
2310 return 0;
79072805 2311 }
1d7c1841
GS
2312 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2313 PTR2UV(sv),SvIVX(sv)));
25da4f38 2314 return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
79072805
LW
2315}
2316
645c22ef 2317/*
891f9566 2318=for apidoc sv_2uv_flags
645c22ef
DM
2319
2320Return the unsigned integer value of an SV, doing any necessary string
891f9566
YST
2321conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2322Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
645c22ef
DM
2323
2324=cut
2325*/
2326
ff68c719 2327UV
5de3775c 2328Perl_sv_2uv_flags(pTHX_ register SV *const sv, const I32 flags)
ff68c719 2329{
97aff369 2330 dVAR;
ff68c719 2331 if (!sv)
2332 return 0;
cecf5685
NC
2333 if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2334 /* FBMs use the same flag bit as SVf_IVisUV, so must let them
50caf62e 2335 cache IVs just in case. */
891f9566
YST
2336 if (flags & SV_GMAGIC)
2337 mg_get(sv);
ff68c719 2338 if (SvIOKp(sv))
2339 return SvUVX(sv);
2340 if (SvNOKp(sv))
2341 return U_V(SvNVX(sv));
71c558c3
NC
2342 if (SvPOKp(sv) && SvLEN(sv)) {
2343 UV value;
2344 const int numtype
2345 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2346
2347 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2348 == IS_NUMBER_IN_UV) {
2349 /* It's definitely an integer */
2350 if (!(numtype & IS_NUMBER_NEG))
2351 return value;
2352 }
2353 if (!numtype) {
2354 if (ckWARN(WARN_NUMERIC))
2355 not_a_number(sv);
2356 }
2357 return U_V(Atof(SvPVX_const(sv)));
2358 }
1c7ff15e
NC
2359 if (SvROK(sv)) {
2360 goto return_rok;
3fe9a6f1 2361 }
1c7ff15e
NC
2362 assert(SvTYPE(sv) >= SVt_PVMG);
2363 /* This falls through to the report_uninit inside S_sv_2iuv_common. */
4cb1ec55 2364 } else if (SvTHINKFIRST(sv)) {
ff68c719 2365 if (SvROK(sv)) {
1c7ff15e 2366 return_rok:
deb46114 2367 if (SvAMAGIC(sv)) {
aee036bb
DM
2368 SV *tmpstr;
2369 if (flags & SV_SKIP_OVERLOAD)
2370 return 0;
2371 tmpstr = AMG_CALLun(sv,numer);
deb46114
NC
2372 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2373 return SvUV(tmpstr);
2374 }
2375 }
2376 return PTR2UV(SvRV(sv));
ff68c719 2377 }
765f542d
NC
2378 if (SvIsCOW(sv)) {
2379 sv_force_normal_flags(sv, 0);
8a818333 2380 }
0336b60e 2381 if (SvREADONLY(sv) && !SvOK(sv)) {
0336b60e 2382 if (ckWARN(WARN_UNINITIALIZED))
29489e7c 2383 report_uninit(sv);
ff68c719 2384 return 0;
2385 }
2386 }
af359546
NC
2387 if (!SvIOKp(sv)) {
2388 if (S_sv_2iuv_common(aTHX_ sv))
2389 return 0;
ff68c719 2390 }
25da4f38 2391
1d7c1841
GS
2392 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2393 PTR2UV(sv),SvUVX(sv)));
25da4f38 2394 return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
ff68c719 2395}
2396
645c22ef 2397/*
196007d1 2398=for apidoc sv_2nv_flags
645c22ef
DM
2399
2400Return the num value of an SV, doing any necessary string or integer
39d5de13
DM
2401conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2402Normally used via the C<SvNV(sv)> and C<SvNVx(sv)> macros.
645c22ef
DM
2403
2404=cut
2405*/
2406
65202027 2407NV
39d5de13 2408Perl_sv_2nv_flags(pTHX_ register SV *const sv, const I32 flags)
79072805 2409{
97aff369 2410 dVAR;
79072805
LW
2411 if (!sv)
2412 return 0.0;
cecf5685
NC
2413 if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2414 /* FBMs use the same flag bit as SVf_IVisUV, so must let them
50caf62e 2415 cache IVs just in case. */
39d5de13
DM
2416 if (flags & SV_GMAGIC)
2417 mg_get(sv);
463ee0b2
LW
2418 if (SvNOKp(sv))
2419 return SvNVX(sv);
0aa395f8 2420 if ((SvPOKp(sv) && SvLEN(sv)) && !SvIOKp(sv)) {
041457d9 2421 if (!SvIOKp(sv) && ckWARN(WARN_NUMERIC) &&
504618e9 2422 !grok_number(SvPVX_const(sv), SvCUR(sv), NULL))
a0d0e21e 2423 not_a_number(sv);
3f7c398e 2424 return Atof(SvPVX_const(sv));
a0d0e21e 2425 }
25da4f38 2426 if (SvIOKp(sv)) {
1c846c1f 2427 if (SvIsUV(sv))
65202027 2428 return (NV)SvUVX(sv);
25da4f38 2429 else
65202027 2430 return (NV)SvIVX(sv);
47a72cb8
NC
2431 }
2432 if (SvROK(sv)) {
2433 goto return_rok;
2434 }
2435 assert(SvTYPE(sv) >= SVt_PVMG);
2436 /* This falls through to the report_uninit near the end of the
2437 function. */
2438 } else if (SvTHINKFIRST(sv)) {
a0d0e21e 2439 if (SvROK(sv)) {
47a72cb8 2440 return_rok:
deb46114 2441 if (SvAMAGIC(sv)) {
aee036bb
DM
2442 SV *tmpstr;
2443 if (flags & SV_SKIP_OVERLOAD)
2444 return 0;
2445 tmpstr = AMG_CALLun(sv,numer);
deb46114
NC
2446 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2447 return SvNV(tmpstr);
2448 }
2449 }
2450 return PTR2NV(SvRV(sv));
a0d0e21e 2451 }
765f542d
NC
2452 if (SvIsCOW(sv)) {
2453 sv_force_normal_flags(sv, 0);
8a818333 2454 }
0336b60e 2455 if (SvREADONLY(sv) && !SvOK(sv)) {
599cee73 2456 if (ckWARN(WARN_UNINITIALIZED))
29489e7c 2457 report_uninit(sv);
ed6116ce
LW
2458 return 0.0;
2459 }
79072805
LW
2460 }
2461 if (SvTYPE(sv) < SVt_NV) {
7e25a7e9
NC
2462 /* The logic to use SVt_PVNV if necessary is in sv_upgrade. */
2463 sv_upgrade(sv, SVt_NV);
906f284f 2464#ifdef USE_LONG_DOUBLE
097ee67d 2465 DEBUG_c({
f93f4e46 2466 STORE_NUMERIC_LOCAL_SET_STANDARD();
1d7c1841
GS
2467 PerlIO_printf(Perl_debug_log,
2468 "0x%"UVxf" num(%" PERL_PRIgldbl ")\n",
2469 PTR2UV(sv), SvNVX(sv));
572bbb43
GS
2470 RESTORE_NUMERIC_LOCAL();
2471 });
65202027 2472#else
572bbb43 2473 DEBUG_c({
f93f4e46 2474 STORE_NUMERIC_LOCAL_SET_STANDARD();
1779d84d 2475 PerlIO_printf(Perl_debug_log, "0x%"UVxf" num(%"NVgf")\n",
1d7c1841 2476 PTR2UV(sv), SvNVX(sv));
097ee67d
JH
2477 RESTORE_NUMERIC_LOCAL();
2478 });
572bbb43 2479#endif
79072805
LW
2480 }
2481 else if (SvTYPE(sv) < SVt_PVNV)
2482 sv_upgrade(sv, SVt_PVNV);
59d8ce62
NC
2483 if (SvNOKp(sv)) {
2484 return SvNVX(sv);
61604483 2485 }
59d8ce62 2486 if (SvIOKp(sv)) {
9d6ce603 2487 SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
28e5dec8 2488#ifdef NV_PRESERVES_UV
a43d94f2
NC
2489 if (SvIOK(sv))
2490 SvNOK_on(sv);
2491 else
2492 SvNOKp_on(sv);
28e5dec8
JH
2493#else
2494 /* Only set the public NV OK flag if this NV preserves the IV */
2495 /* Check it's not 0xFFFFFFFFFFFFFFFF */
a43d94f2
NC
2496 if (SvIOK(sv) &&
2497 SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
28e5dec8
JH
2498 : (SvIVX(sv) == I_V(SvNVX(sv))))
2499 SvNOK_on(sv);
2500 else
2501 SvNOKp_on(sv);
2502#endif
93a17b20 2503 }
748a9306 2504 else if (SvPOKp(sv) && SvLEN(sv)) {
c2988b20 2505 UV value;
3f7c398e 2506 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
041457d9 2507 if (!SvIOKp(sv) && !numtype && ckWARN(WARN_NUMERIC))
a0d0e21e 2508 not_a_number(sv);
28e5dec8 2509#ifdef NV_PRESERVES_UV
c2988b20
NC
2510 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2511 == IS_NUMBER_IN_UV) {
5e045b90 2512 /* It's definitely an integer */
9d6ce603 2513 SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
c2988b20 2514 } else
3f7c398e 2515 SvNV_set(sv, Atof(SvPVX_const(sv)));
a43d94f2
NC
2516 if (numtype)
2517 SvNOK_on(sv);
2518 else
2519 SvNOKp_on(sv);
28e5dec8 2520#else
3f7c398e 2521 SvNV_set(sv, Atof(SvPVX_const(sv)));
28e5dec8
JH
2522 /* Only set the public NV OK flag if this NV preserves the value in
2523 the PV at least as well as an IV/UV would.
2524 Not sure how to do this 100% reliably. */
2525 /* if that shift count is out of range then Configure's test is
2526 wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2527 UV_BITS */
2528 if (((UV)1 << NV_PRESERVES_UV_BITS) >
c2988b20 2529 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
28e5dec8 2530 SvNOK_on(sv); /* Definitely small enough to preserve all bits */
c2988b20
NC
2531 } else if (!(numtype & IS_NUMBER_IN_UV)) {
2532 /* Can't use strtol etc to convert this string, so don't try.
2533 sv_2iv and sv_2uv will use the NV to convert, not the PV. */
2534 SvNOK_on(sv);
2535 } else {
2536 /* value has been set. It may not be precise. */
2537 if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2538 /* 2s complement assumption for (UV)IV_MIN */
2539 SvNOK_on(sv); /* Integer is too negative. */
2540 } else {
2541 SvNOKp_on(sv);
2542 SvIOKp_on(sv);
6fa402ec 2543
c2988b20 2544 if (numtype & IS_NUMBER_NEG) {
45977657 2545 SvIV_set(sv, -(IV)value);
c2988b20 2546 } else if (value <= (UV)IV_MAX) {
45977657 2547 SvIV_set(sv, (IV)value);
c2988b20 2548 } else {
607fa7f2 2549 SvUV_set(sv, value);
c2988b20
NC
2550 SvIsUV_on(sv);
2551 }
2552
2553 if (numtype & IS_NUMBER_NOT_INT) {
2554 /* I believe that even if the original PV had decimals,
2555 they are lost beyond the limit of the FP precision.
2556 However, neither is canonical, so both only get p
2557 flags. NWC, 2000/11/25 */
2558 /* Both already have p flags, so do nothing */
2559 } else {
66a1b24b 2560 const NV nv = SvNVX(sv);
c2988b20
NC
2561 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2562 if (SvIVX(sv) == I_V(nv)) {
2563 SvNOK_on(sv);
c2988b20 2564 } else {
c2988b20
NC
2565 /* It had no "." so it must be integer. */
2566 }
00b6aa41 2567 SvIOK_on(sv);
c2988b20
NC
2568 } else {
2569 /* between IV_MAX and NV(UV_MAX).
2570 Could be slightly > UV_MAX */
6fa402ec 2571
c2988b20
NC
2572 if (numtype & IS_NUMBER_NOT_INT) {
2573 /* UV and NV both imprecise. */
2574 } else {
66a1b24b 2575 const UV nv_as_uv = U_V(nv);
c2988b20
NC
2576
2577 if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2578 SvNOK_on(sv);
c2988b20 2579 }
00b6aa41 2580 SvIOK_on(sv);
c2988b20
NC
2581 }
2582 }
2583 }
2584 }
2585 }
a43d94f2
NC
2586 /* It might be more code efficient to go through the entire logic above
2587 and conditionally set with SvNOKp_on() rather than SvNOK(), but it
2588 gets complex and potentially buggy, so more programmer efficient
2589 to do it this way, by turning off the public flags: */
2590 if (!numtype)
2591 SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
28e5dec8 2592#endif /* NV_PRESERVES_UV */
93a17b20 2593 }
79072805 2594 else {
f7877b28 2595 if (isGV_with_GP(sv)) {
159b6efe 2596 glob_2number(MUTABLE_GV(sv));
180488f8
NC
2597 return 0.0;
2598 }
2599
041457d9 2600 if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
29489e7c 2601 report_uninit(sv);
7e25a7e9
NC
2602 assert (SvTYPE(sv) >= SVt_NV);
2603 /* Typically the caller expects that sv_any is not NULL now. */
2604 /* XXX Ilya implies that this is a bug in callers that assume this
2605 and ideally should be fixed. */
a0d0e21e 2606 return 0.0;
79072805 2607 }
572bbb43 2608#if defined(USE_LONG_DOUBLE)
097ee67d 2609 DEBUG_c({
f93f4e46 2610 STORE_NUMERIC_LOCAL_SET_STANDARD();
1d7c1841
GS
2611 PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" PERL_PRIgldbl ")\n",
2612 PTR2UV(sv), SvNVX(sv));
572bbb43
GS
2613 RESTORE_NUMERIC_LOCAL();
2614 });
65202027 2615#else
572bbb43 2616 DEBUG_c({
f93f4e46 2617 STORE_NUMERIC_LOCAL_SET_STANDARD();
1779d84d 2618 PerlIO_printf(Perl_debug_log, "0x%"UVxf" 1nv(%"NVgf")\n",
1d7c1841 2619 PTR2UV(sv), SvNVX(sv));
097ee67d
JH
2620 RESTORE_NUMERIC_LOCAL();
2621 });
572bbb43 2622#endif
463ee0b2 2623 return SvNVX(sv);
79072805
LW
2624}
2625
800401ee
JH
2626/*
2627=for apidoc sv_2num
2628
2629Return an SV with the numeric value of the source SV, doing any necessary
a196a5fa
JH
2630reference or overload conversion. You must use the C<SvNUM(sv)> macro to
2631access this function.
800401ee
JH
2632
2633=cut
2634*/
2635
2636SV *
5de3775c 2637Perl_sv_2num(pTHX_ register SV *const sv)
800401ee 2638{
7918f24d
NC
2639 PERL_ARGS_ASSERT_SV_2NUM;
2640
b9ee0594
RGS
2641 if (!SvROK(sv))
2642 return sv;
800401ee
JH
2643 if (SvAMAGIC(sv)) {
2644 SV * const tmpsv = AMG_CALLun(sv,numer);
a02ec77a 2645 TAINT_IF(tmpsv && SvTAINTED(tmpsv));
800401ee
JH
2646 if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
2647 return sv_2num(tmpsv);
2648 }
2649 return sv_2mortal(newSVuv(PTR2UV(SvRV(sv))));
2650}
2651
645c22ef
DM
2652/* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2653 * UV as a string towards the end of buf, and return pointers to start and
2654 * end of it.
2655 *
2656 * We assume that buf is at least TYPE_CHARS(UV) long.
2657 */
2658
864dbfa3 2659static char *
5de3775c 2660S_uiv_2buf(char *const buf, const IV iv, UV uv, const int is_uv, char **const peob)
25da4f38 2661{
25da4f38 2662 char *ptr = buf + TYPE_CHARS(UV);
823a54a3 2663 char * const ebuf = ptr;
25da4f38 2664 int sign;
25da4f38 2665
7918f24d
NC
2666 PERL_ARGS_ASSERT_UIV_2BUF;
2667
25da4f38
IZ
2668 if (is_uv)
2669 sign = 0;
2670 else if (iv >= 0) {
2671 uv = iv;
2672 sign = 0;
2673 } else {
2674 uv = -iv;
2675 sign = 1;
2676 }
2677 do {
eb160463 2678 *--ptr = '0' + (char)(uv % 10);
25da4f38
IZ
2679 } while (uv /= 10);
2680 if (sign)
2681 *--ptr = '-';
2682 *peob = ebuf;
2683 return ptr;
2684}
2685
645c22ef
DM
2686/*
2687=for apidoc sv_2pv_flags
2688
ff276b08 2689Returns a pointer to the string value of an SV, and sets *lp to its length.
645c22ef
DM
2690If flags includes SV_GMAGIC, does an mg_get() first. Coerces sv to a string
2691if necessary.
2692Normally invoked via the C<SvPV_flags> macro. C<sv_2pv()> and C<sv_2pv_nomg>
2693usually end up here too.
2694
2695=cut
2696*/
2697
8d6d96c1 2698char *
5de3775c 2699Perl_sv_2pv_flags(pTHX_ register SV *const sv, STRLEN *const lp, const I32 flags)
8d6d96c1 2700{
97aff369 2701 dVAR;
79072805 2702 register char *s;
79072805 2703
463ee0b2 2704 if (!sv) {
cdb061a3
NC
2705 if (lp)
2706 *lp = 0;
73d840c0 2707 return (char *)"";
463ee0b2 2708 }
8990e307 2709 if (SvGMAGICAL(sv)) {
8d6d96c1
HS
2710 if (flags & SV_GMAGIC)
2711 mg_get(sv);
463ee0b2 2712 if (SvPOKp(sv)) {
cdb061a3
NC
2713 if (lp)
2714 *lp = SvCUR(sv);
10516c54
NC
2715 if (flags & SV_MUTABLE_RETURN)
2716 return SvPVX_mutable(sv);
4d84ee25
NC
2717 if (flags & SV_CONST_RETURN)
2718 return (char *)SvPVX_const(sv);
463ee0b2
LW
2719 return SvPVX(sv);
2720 }
75dfc8ec
NC
2721 if (SvIOKp(sv) || SvNOKp(sv)) {
2722 char tbuf[64]; /* Must fit sprintf/Gconvert of longest IV/NV */
75dfc8ec
NC
2723 STRLEN len;
2724
2725 if (SvIOKp(sv)) {
e80fed9d 2726 len = SvIsUV(sv)
d9fad198
JH
2727 ? my_snprintf(tbuf, sizeof(tbuf), "%"UVuf, (UV)SvUVX(sv))
2728 : my_snprintf(tbuf, sizeof(tbuf), "%"IVdf, (IV)SvIVX(sv));
75dfc8ec 2729 } else {
e8ada2d0
NC
2730 Gconvert(SvNVX(sv), NV_DIG, 0, tbuf);
2731 len = strlen(tbuf);
75dfc8ec 2732 }
b5b886f0
NC
2733 assert(!SvROK(sv));
2734 {
75dfc8ec
NC
2735 dVAR;
2736
2737#ifdef FIXNEGATIVEZERO
e8ada2d0
NC
2738 if (len == 2 && tbuf[0] == '-' && tbuf[1] == '0') {
2739 tbuf[0] = '0';
2740 tbuf[1] = 0;
75dfc8ec
NC
2741 len = 1;
2742 }
2743#endif
2744 SvUPGRADE(sv, SVt_PV);
2745 if (lp)
2746 *lp = len;
2747 s = SvGROW_mutable(sv, len + 1);
2748 SvCUR_set(sv, len);
2749 SvPOKp_on(sv);
10edeb5d 2750 return (char*)memcpy(s, tbuf, len + 1);
75dfc8ec 2751 }
463ee0b2 2752 }
1c7ff15e
NC
2753 if (SvROK(sv)) {
2754 goto return_rok;
2755 }
2756 assert(SvTYPE(sv) >= SVt_PVMG);
2757 /* This falls through to the report_uninit near the end of the
2758 function. */
2759 } else if (SvTHINKFIRST(sv)) {
ed6116ce 2760 if (SvROK(sv)) {
1c7ff15e 2761 return_rok:
deb46114 2762 if (SvAMAGIC(sv)) {
aee036bb
DM
2763 SV *tmpstr;
2764 if (flags & SV_SKIP_OVERLOAD)
2765 return NULL;
2766 tmpstr = AMG_CALLun(sv,string);
a02ec77a 2767 TAINT_IF(tmpstr && SvTAINTED(tmpstr));
deb46114
NC
2768 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2769 /* Unwrap this: */
2770 /* char *pv = lp ? SvPV(tmpstr, *lp) : SvPV_nolen(tmpstr);
2771 */
2772
2773 char *pv;
2774 if ((SvFLAGS(tmpstr) & (SVf_POK)) == SVf_POK) {
2775 if (flags & SV_CONST_RETURN) {
2776 pv = (char *) SvPVX_const(tmpstr);
2777 } else {
2778 pv = (flags & SV_MUTABLE_RETURN)
2779 ? SvPVX_mutable(tmpstr) : SvPVX(tmpstr);
2780 }
2781 if (lp)
2782 *lp = SvCUR(tmpstr);
50adf7d2 2783 } else {
deb46114 2784 pv = sv_2pv_flags(tmpstr, lp, flags);
50adf7d2 2785 }
deb46114
NC
2786 if (SvUTF8(tmpstr))
2787 SvUTF8_on(sv);
2788 else
2789 SvUTF8_off(sv);
2790 return pv;
50adf7d2 2791 }
deb46114
NC
2792 }
2793 {
fafee734
NC
2794 STRLEN len;
2795 char *retval;
2796 char *buffer;
d2c6dc5e 2797 SV *const referent = SvRV(sv);
d8eae41e
NC
2798
2799 if (!referent) {
fafee734
NC
2800 len = 7;
2801 retval = buffer = savepvn("NULLREF", len);
5c35adbb 2802 } else if (SvTYPE(referent) == SVt_REGEXP) {
d2c6dc5e 2803 REGEXP * const re = (REGEXP *)MUTABLE_PTR(referent);
67d2d14d
AB
2804 I32 seen_evals = 0;
2805
2806 assert(re);
2807
2808 /* If the regex is UTF-8 we want the containing scalar to
2809 have an UTF-8 flag too */
2810 if (RX_UTF8(re))
2811 SvUTF8_on(sv);
2812 else
2813 SvUTF8_off(sv);
2814
2815 if ((seen_evals = RX_SEEN_EVALS(re)))
2816 PL_reginterp_cnt += seen_evals;
2817
2818 if (lp)
2819 *lp = RX_WRAPLEN(re);
2820
2821 return RX_WRAPPED(re);
d8eae41e
NC
2822 } else {
2823 const char *const typestr = sv_reftype(referent, 0);
fafee734
NC
2824 const STRLEN typelen = strlen(typestr);
2825 UV addr = PTR2UV(referent);
2826 const char *stashname = NULL;
2827 STRLEN stashnamelen = 0; /* hush, gcc */
2828 const char *buffer_end;
d8eae41e 2829
d8eae41e 2830 if (SvOBJECT(referent)) {
fafee734
NC
2831 const HEK *const name = HvNAME_HEK(SvSTASH(referent));
2832
2833 if (name) {
2834 stashname = HEK_KEY(name);
2835 stashnamelen = HEK_LEN(name);
2836
2837 if (HEK_UTF8(name)) {
2838 SvUTF8_on(sv);
2839 } else {
2840 SvUTF8_off(sv);
2841 }
2842 } else {
2843 stashname = "__ANON__";
2844 stashnamelen = 8;
2845 }
2846 len = stashnamelen + 1 /* = */ + typelen + 3 /* (0x */
2847 + 2 * sizeof(UV) + 2 /* )\0 */;
2848 } else {
2849 len = typelen + 3 /* (0x */
2850 + 2 * sizeof(UV) + 2 /* )\0 */;
d8eae41e 2851 }
fafee734
NC
2852
2853 Newx(buffer, len, char);
2854 buffer_end = retval = buffer + len;
2855
2856 /* Working backwards */
2857 *--retval = '\0';
2858 *--retval = ')';
2859 do {
2860 *--retval = PL_hexdigit[addr & 15];
2861 } while (addr >>= 4);
2862 *--retval = 'x';
2863 *--retval = '0';
2864 *--retval = '(';
2865
2866 retval -= typelen;
2867 memcpy(retval, typestr, typelen);
2868
2869 if (stashname) {
2870 *--retval = '=';
2871 retval -= stashnamelen;
2872 memcpy(retval, stashname, stashnamelen);
2873 }
2874 /* retval may not neccesarily have reached the start of the
2875 buffer here. */
2876 assert (retval >= buffer);
2877
2878 len = buffer_end - retval - 1; /* -1 for that \0 */
c080367d 2879 }
042dae7a 2880 if (lp)
fafee734
NC
2881 *lp = len;
2882 SAVEFREEPV(buffer);
2883 return retval;
463ee0b2 2884 }
79072805 2885 }
0336b60e 2886 if (SvREADONLY(sv) && !SvOK(sv)) {
cdb061a3
NC
2887 if (lp)
2888 *lp = 0;
9f621bb0
NC
2889 if (flags & SV_UNDEF_RETURNS_NULL)
2890 return NULL;
2891 if (ckWARN(WARN_UNINITIALIZED))
2892 report_uninit(sv);
73d840c0 2893 return (char *)"";
79072805 2894 }
79072805 2895 }
28e5dec8
JH
2896 if (SvIOK(sv) || ((SvIOKp(sv) && !SvNOKp(sv)))) {
2897 /* I'm assuming that if both IV and NV are equally valid then
2898 converting the IV is going to be more efficient */
e1ec3a88 2899 const U32 isUIOK = SvIsUV(sv);
28e5dec8
JH
2900 char buf[TYPE_CHARS(UV)];
2901 char *ebuf, *ptr;
97a130b8 2902 STRLEN len;
28e5dec8
JH
2903
2904 if (SvTYPE(sv) < SVt_PVIV)
2905 sv_upgrade(sv, SVt_PVIV);
4ea1d550 2906 ptr = uiv_2buf(buf, SvIVX(sv), SvUVX(sv), isUIOK, &ebuf);
97a130b8 2907 len = ebuf - ptr;
5902b6a9 2908 /* inlined from sv_setpvn */
97a130b8
NC
2909 s = SvGROW_mutable(sv, len + 1);
2910 Move(ptr, s, len, char);
2911 s += len;
28e5dec8 2912 *s = '\0';
28e5dec8
JH
2913 }
2914 else if (SvNOKp(sv)) {
4ee39169 2915 dSAVE_ERRNO;
79072805
LW
2916 if (SvTYPE(sv) < SVt_PVNV)
2917 sv_upgrade(sv, SVt_PVNV);
1c846c1f 2918 /* The +20 is pure guesswork. Configure test needed. --jhi */
5902b6a9 2919 s = SvGROW_mutable(sv, NV_DIG + 20);
c81271c3 2920 /* some Xenix systems wipe out errno here */
79072805 2921#ifdef apollo
463ee0b2 2922 if (SvNVX(sv) == 0.0)
d1307786 2923 my_strlcpy(s, "0", SvLEN(sv));
79072805
LW
2924 else
2925#endif /*apollo*/
bbce6d69 2926 {
2d4389e4 2927 Gconvert(SvNVX(sv), NV_DIG, 0, s);
bbce6d69 2928 }
4ee39169 2929 RESTORE_ERRNO;
a0d0e21e 2930#ifdef FIXNEGATIVEZERO
20773dcd
NC
2931 if (*s == '-' && s[1] == '0' && !s[2]) {
2932 s[0] = '0';
2933 s[1] = 0;
2934 }
a0d0e21e 2935#endif
79072805
LW
2936 while (*s) s++;
2937#ifdef hcx
2938 if (s[-1] == '.')
46fc3d4c 2939 *--s = '\0';
79072805
LW
2940#endif
2941 }
79072805 2942 else {
8d1c3e26
NC
2943 if (isGV_with_GP(sv)) {
2944 GV *const gv = MUTABLE_GV(sv);
2945 const U32 wasfake = SvFLAGS(gv) & SVf_FAKE;
2946 SV *const buffer = sv_newmortal();
2947
2948 /* FAKE globs can get coerced, so need to turn this off temporarily
2949 if it is on. */
2950 SvFAKE_off(gv);
2951 gv_efullname3(buffer, gv, "*");
2952 SvFLAGS(gv) |= wasfake;
2953
1809c940
DM
2954 if (SvPOK(buffer)) {
2955 if (lp) {
2956 *lp = SvCUR(buffer);
2957 }
2958 return SvPVX(buffer);
2959 }
2960 else {
2961 if (lp)
2962 *lp = 0;
2963 return (char *)"";
8d1c3e26 2964 }
8d1c3e26 2965 }
180488f8 2966
cdb061a3 2967 if (lp)
00b6aa41 2968 *lp = 0;
9f621bb0
NC
2969 if (flags & SV_UNDEF_RETURNS_NULL)
2970 return NULL;
2971 if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
2972 report_uninit(sv);
25da4f38
IZ
2973 if (SvTYPE(sv) < SVt_PV)
2974 /* Typically the caller expects that sv_any is not NULL now. */
2975 sv_upgrade(sv, SVt_PV);
73d840c0 2976 return (char *)"";
79072805 2977 }
cdb061a3 2978 {
823a54a3 2979 const STRLEN len = s - SvPVX_const(sv);
cdb061a3
NC
2980 if (lp)
2981 *lp = len;
2982 SvCUR_set(sv, len);
2983 }
79072805 2984 SvPOK_on(sv);
1d7c1841 2985 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
3f7c398e 2986 PTR2UV(sv),SvPVX_const(sv)));
4d84ee25
NC
2987 if (flags & SV_CONST_RETURN)
2988 return (char *)SvPVX_const(sv);
10516c54
NC
2989 if (flags & SV_MUTABLE_RETURN)
2990 return SvPVX_mutable(sv);
463ee0b2
LW
2991 return SvPVX(sv);
2992}
2993
645c22ef 2994/*
6050d10e
JP
2995=for apidoc sv_copypv
2996
2997Copies a stringified representation of the source SV into the
2998destination SV. Automatically performs any necessary mg_get and
54f0641b 2999coercion of numeric values into strings. Guaranteed to preserve
2575c402 3000UTF8 flag even from overloaded objects. Similar in nature to
54f0641b
NIS
3001sv_2pv[_flags] but operates directly on an SV instead of just the
3002string. Mostly uses sv_2pv_flags to do its work, except when that
6050d10e
JP
3003would lose the UTF-8'ness of the PV.
3004
3005=cut
3006*/
3007
3008void
5de3775c 3009Perl_sv_copypv(pTHX_ SV *const dsv, register SV *const ssv)
6050d10e 3010{
446eaa42 3011 STRLEN len;
53c1dcc0 3012 const char * const s = SvPV_const(ssv,len);
7918f24d
NC
3013
3014 PERL_ARGS_ASSERT_SV_COPYPV;
3015
cb50f42d 3016 sv_setpvn(dsv,s,len);
446eaa42 3017 if (SvUTF8(ssv))
cb50f42d 3018 SvUTF8_on(dsv);
446eaa42 3019 else
cb50f42d 3020 SvUTF8_off(dsv);
6050d10e
JP
3021}
3022
3023/*
645c22ef
DM
3024=for apidoc sv_2pvbyte
3025
3026Return a pointer to the byte-encoded representation of the SV, and set *lp
1e54db1a 3027to its length. May cause the SV to be downgraded from UTF-8 as a
645c22ef
DM
3028side-effect.
3029
3030Usually accessed via the C<SvPVbyte> macro.
3031
3032=cut
3033*/
3034
7340a771 3035char *
5de3775c 3036Perl_sv_2pvbyte(pTHX_ register SV *const sv, STRLEN *const lp)
7340a771 3037{
7918f24d
NC
3038 PERL_ARGS_ASSERT_SV_2PVBYTE;
3039
0875d2fe 3040 sv_utf8_downgrade(sv,0);
97972285 3041 return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
7340a771
GS
3042}
3043
645c22ef 3044/*
035cbb0e
RGS
3045=for apidoc sv_2pvutf8
3046
3047Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
3048to its length. May cause the SV to be upgraded to UTF-8 as a side-effect.
3049
3050Usually accessed via the C<SvPVutf8> macro.
3051
3052=cut
3053*/
645c22ef 3054
7340a771 3055char *
7bc54cea 3056Perl_sv_2pvutf8(pTHX_ register SV *const sv, STRLEN *const lp)
7340a771 3057{
7918f24d
NC
3058 PERL_ARGS_ASSERT_SV_2PVUTF8;
3059
035cbb0e
RGS
3060 sv_utf8_upgrade(sv);
3061 return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
7340a771 3062}
1c846c1f 3063
7ee2227d 3064
645c22ef
DM
3065/*
3066=for apidoc sv_2bool
3067
3068This function is only called on magical items, and is only used by
8cf8f3d1 3069sv_true() or its macro equivalent.
645c22ef
DM
3070
3071=cut
3072*/
3073
463ee0b2 3074bool
7bc54cea 3075Perl_sv_2bool(pTHX_ register SV *const sv)
463ee0b2 3076{
97aff369 3077 dVAR;
7918f24d
NC
3078
3079 PERL_ARGS_ASSERT_SV_2BOOL;
3080
5b295bef 3081 SvGETMAGIC(sv);
463ee0b2 3082
a0d0e21e
LW
3083 if (!SvOK(sv))
3084 return 0;
3085 if (SvROK(sv)) {
fabdb6c0
AL
3086 if (SvAMAGIC(sv)) {
3087 SV * const tmpsv = AMG_CALLun(sv,bool_);
3088 if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
f2338a2e 3089 return cBOOL(SvTRUE(tmpsv));
fabdb6c0
AL
3090 }
3091 return SvRV(sv) != 0;
a0d0e21e 3092 }
463ee0b2 3093 if (SvPOKp(sv)) {
53c1dcc0
AL
3094 register XPV* const Xpvtmp = (XPV*)SvANY(sv);
3095 if (Xpvtmp &&
339049b0 3096 (*sv->sv_u.svu_pv > '0' ||
11343788 3097 Xpvtmp->xpv_cur > 1 ||
339049b0 3098 (Xpvtmp->xpv_cur && *sv->sv_u.svu_pv != '0')))
463ee0b2
LW
3099 return 1;
3100 else
3101 return 0;
3102 }
3103 else {
3104 if (SvIOKp(sv))
3105 return SvIVX(sv) != 0;
3106 else {
3107 if (SvNOKp(sv))
3108 return SvNVX(sv) != 0.0;
180488f8 3109 else {
f7877b28 3110 if (isGV_with_GP(sv))
180488f8
NC
3111 return TRUE;
3112 else
3113 return FALSE;
3114 }
463ee0b2
LW
3115 }
3116 }
79072805
LW
3117}
3118
c461cf8f
JH
3119/*
3120=for apidoc sv_utf8_upgrade
3121
78ea37eb 3122Converts the PV of an SV to its UTF-8-encoded form.
645c22ef 3123Forces the SV to string form if it is not already.
2bbc8d55 3124Will C<mg_get> on C<sv> if appropriate.
4411f3b6 3125Always sets the SvUTF8 flag to avoid future validity checks even
2bbc8d55
SP
3126if the whole string is the same in UTF-8 as not.
3127Returns the number of bytes in the converted string
c461cf8f 3128
13a6c0e0
JH
3129This is not as a general purpose byte encoding to Unicode interface:
3130use the Encode extension for that.
3131
fe749c9a
KW
3132=for apidoc sv_utf8_upgrade_nomg
3133
3134Like sv_utf8_upgrade, but doesn't do magic on C<sv>
3135
8d6d96c1
HS
3136=for apidoc sv_utf8_upgrade_flags
3137
78ea37eb 3138Converts the PV of an SV to its UTF-8-encoded form.
645c22ef 3139Forces the SV to string form if it is not already.
8d6d96c1 3140Always sets the SvUTF8 flag to avoid future validity checks even
2bbc8d55
SP
3141if all the bytes are invariant in UTF-8. If C<flags> has C<SV_GMAGIC> bit set,
3142will C<mg_get> on C<sv> if appropriate, else not.
3143Returns the number of bytes in the converted string
3144C<sv_utf8_upgrade> and
8d6d96c1
HS
3145C<sv_utf8_upgrade_nomg> are implemented in terms of this function.
3146
13a6c0e0
JH
3147This is not as a general purpose byte encoding to Unicode interface:
3148use the Encode extension for that.
3149
8d6d96c1 3150=cut
b3ab6785
KW
3151
3152The grow version is currently not externally documented. It adds a parameter,
3153extra, which is the number of unused bytes the string of 'sv' is guaranteed to
3154have free after it upon return. This allows the caller to reserve extra space
3155that it intends to fill, to avoid extra grows.
3156
3157Also externally undocumented for the moment is the flag SV_FORCE_UTF8_UPGRADE,
3158which can be used to tell this function to not first check to see if there are
3159any characters that are different in UTF-8 (variant characters) which would
3160force it to allocate a new string to sv, but to assume there are. Typically
3161this flag is used by a routine that has already parsed the string to find that
3162there are such characters, and passes this information on so that the work
3163doesn't have to be repeated.
3164
3165(One might think that the calling routine could pass in the position of the
3166first such variant, so it wouldn't have to be found again. But that is not the
3167case, because typically when the caller is likely to use this flag, it won't be
3168calling this routine unless it finds something that won't fit into a byte.
3169Otherwise it tries to not upgrade and just use bytes. But some things that
3170do fit into a byte are variants in utf8, and the caller may not have been
3171keeping track of these.)
3172
3173If the routine itself changes the string, it adds a trailing NUL. Such a NUL
3174isn't guaranteed due to having other routines do the work in some input cases,
3175or if the input is already flagged as being in utf8.
3176
3177The speed of this could perhaps be improved for many cases if someone wanted to
3178write a fast function that counts the number of variant characters in a string,
3179especially if it could return the position of the first one.
3180
8d6d96c1
HS
3181*/
3182
3183STRLEN
b3ab6785 3184Perl_sv_utf8_upgrade_flags_grow(pTHX_ register SV *const sv, const I32 flags, STRLEN extra)
8d6d96c1 3185{
97aff369 3186 dVAR;
7918f24d 3187
b3ab6785 3188 PERL_ARGS_ASSERT_SV_UTF8_UPGRADE_FLAGS_GROW;
7918f24d 3189
808c356f
RGS
3190 if (sv == &PL_sv_undef)
3191 return 0;
e0e62c2a
NIS
3192 if (!SvPOK(sv)) {
3193 STRLEN len = 0;
d52b7888
NC
3194 if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
3195 (void) sv_2pv_flags(sv,&len, flags);
b3ab6785
KW
3196 if (SvUTF8(sv)) {
3197 if (extra) SvGROW(sv, SvCUR(sv) + extra);
d52b7888 3198 return len;
b3ab6785 3199 }
d52b7888
NC
3200 } else {
3201 (void) SvPV_force(sv,len);
3202 }
e0e62c2a 3203 }
4411f3b6 3204
f5cee72b 3205 if (SvUTF8(sv)) {
b3ab6785 3206 if (extra) SvGROW(sv, SvCUR(sv) + extra);
5fec3b1d 3207 return SvCUR(sv);
f5cee72b 3208 }
5fec3b1d 3209
765f542d
NC
3210 if (SvIsCOW(sv)) {
3211 sv_force_normal_flags(sv, 0);
db42d148
NIS
3212 }
3213
b3ab6785 3214 if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING)) {
799ef3cb 3215 sv_recode_to_utf8(sv, PL_encoding);
b3ab6785
KW
3216 if (extra) SvGROW(sv, SvCUR(sv) + extra);
3217 return SvCUR(sv);
3218 }
3219
4e93345f
KW
3220 if (SvCUR(sv) == 0) {
3221 if (extra) SvGROW(sv, extra);
3222 } else { /* Assume Latin-1/EBCDIC */
c4e7c712 3223 /* This function could be much more efficient if we
2bbc8d55 3224 * had a FLAG in SVs to signal if there are any variant
c4e7c712 3225 * chars in the PV. Given that there isn't such a flag
b3ab6785
KW
3226 * make the loop as fast as possible (although there are certainly ways
3227 * to speed this up, eg. through vectorization) */
3228 U8 * s = (U8 *) SvPVX_const(sv);
3229 U8 * e = (U8 *) SvEND(sv);
3230 U8 *t = s;
3231 STRLEN two_byte_count = 0;
c4e7c712 3232
b3ab6785
KW
3233 if (flags & SV_FORCE_UTF8_UPGRADE) goto must_be_utf8;
3234
3235 /* See if really will need to convert to utf8. We mustn't rely on our
3236 * incoming SV being well formed and having a trailing '\0', as certain
3237 * code in pp_formline can send us partially built SVs. */
3238
c4e7c712 3239 while (t < e) {
53c1dcc0 3240 const U8 ch = *t++;
b3ab6785
KW
3241 if (NATIVE_IS_INVARIANT(ch)) continue;
3242
3243 t--; /* t already incremented; re-point to first variant */
3244 two_byte_count = 1;
3245 goto must_be_utf8;
c4e7c712 3246 }
b3ab6785
KW
3247
3248 /* utf8 conversion not needed because all are invariants. Mark as
3249 * UTF-8 even if no variant - saves scanning loop */
c4e7c712 3250 SvUTF8_on(sv);
b3ab6785
KW
3251 return SvCUR(sv);
3252
3253must_be_utf8:
3254
3255 /* Here, the string should be converted to utf8, either because of an
3256 * input flag (two_byte_count = 0), or because a character that
3257 * requires 2 bytes was found (two_byte_count = 1). t points either to
3258 * the beginning of the string (if we didn't examine anything), or to
3259 * the first variant. In either case, everything from s to t - 1 will
3260 * occupy only 1 byte each on output.
3261 *
3262 * There are two main ways to convert. One is to create a new string
3263 * and go through the input starting from the beginning, appending each
3264 * converted value onto the new string as we go along. It's probably
3265 * best to allocate enough space in the string for the worst possible
3266 * case rather than possibly running out of space and having to
3267 * reallocate and then copy what we've done so far. Since everything
3268 * from s to t - 1 is invariant, the destination can be initialized
3269 * with these using a fast memory copy
3270 *
3271 * The other way is to figure out exactly how big the string should be
3272 * by parsing the entire input. Then you don't have to make it big
3273 * enough to handle the worst possible case, and more importantly, if
3274 * the string you already have is large enough, you don't have to
3275 * allocate a new string, you can copy the last character in the input
3276 * string to the final position(s) that will be occupied by the
3277 * converted string and go backwards, stopping at t, since everything
3278 * before that is invariant.
3279 *
3280 * There are advantages and disadvantages to each method.
3281 *
3282 * In the first method, we can allocate a new string, do the memory
3283 * copy from the s to t - 1, and then proceed through the rest of the
3284 * string byte-by-byte.
3285 *
3286 * In the second method, we proceed through the rest of the input
3287 * string just calculating how big the converted string will be. Then
3288 * there are two cases:
3289 * 1) if the string has enough extra space to handle the converted
3290 * value. We go backwards through the string, converting until we
3291 * get to the position we are at now, and then stop. If this
3292 * position is far enough along in the string, this method is
3293 * faster than the other method. If the memory copy were the same
3294 * speed as the byte-by-byte loop, that position would be about
3295 * half-way, as at the half-way mark, parsing to the end and back
3296 * is one complete string's parse, the same amount as starting
3297 * over and going all the way through. Actually, it would be
3298 * somewhat less than half-way, as it's faster to just count bytes
3299 * than to also copy, and we don't have the overhead of allocating
3300 * a new string, changing the scalar to use it, and freeing the
3301 * existing one. But if the memory copy is fast, the break-even
3302 * point is somewhere after half way. The counting loop could be
3303 * sped up by vectorization, etc, to move the break-even point
3304 * further towards the beginning.
3305 * 2) if the string doesn't have enough space to handle the converted
3306 * value. A new string will have to be allocated, and one might
3307 * as well, given that, start from the beginning doing the first
3308 * method. We've spent extra time parsing the string and in
3309 * exchange all we've gotten is that we know precisely how big to
3310 * make the new one. Perl is more optimized for time than space,
3311 * so this case is a loser.
3312 * So what I've decided to do is not use the 2nd method unless it is
3313 * guaranteed that a new string won't have to be allocated, assuming
3314 * the worst case. I also decided not to put any more conditions on it
3315 * than this, for now. It seems likely that, since the worst case is
3316 * twice as big as the unknown portion of the string (plus 1), we won't
3317 * be guaranteed enough space, causing us to go to the first method,
3318 * unless the string is short, or the first variant character is near
3319 * the end of it. In either of these cases, it seems best to use the
3320 * 2nd method. The only circumstance I can think of where this would
3321 * be really slower is if the string had once had much more data in it
3322 * than it does now, but there is still a substantial amount in it */
3323
3324 {
3325 STRLEN invariant_head = t - s;
3326 STRLEN size = invariant_head + (e - t) * 2 + 1 + extra;
3327 if (SvLEN(sv) < size) {
3328
3329 /* Here, have decided to allocate a new string */
3330
3331 U8 *dst;
3332 U8 *d;
3333
3334 Newx(dst, size, U8);
3335
3336 /* If no known invariants at the beginning of the input string,
3337 * set so starts from there. Otherwise, can use memory copy to
3338 * get up to where we are now, and then start from here */
3339
3340 if (invariant_head <= 0) {
3341 d = dst;
3342 } else {
3343 Copy(s, dst, invariant_head, char);
3344 d = dst + invariant_head;
3345 }
3346
3347 while (t < e) {
3348 const UV uv = NATIVE8_TO_UNI(*t++);
3349 if (UNI_IS_INVARIANT(uv))
3350 *d++ = (U8)UNI_TO_NATIVE(uv);
3351 else {
3352 *d++ = (U8)UTF8_EIGHT_BIT_HI(uv);
3353 *d++ = (U8)UTF8_EIGHT_BIT_LO(uv);
3354 }
3355 }
3356 *d = '\0';
3357 SvPV_free(sv); /* No longer using pre-existing string */
3358 SvPV_set(sv, (char*)dst);
3359 SvCUR_set(sv, d - dst);
3360 SvLEN_set(sv, size);
3361 } else {
3362
3363 /* Here, have decided to get the exact size of the string.
3364 * Currently this happens only when we know that there is
3365 * guaranteed enough space to fit the converted string, so
3366 * don't have to worry about growing. If two_byte_count is 0,
3367 * then t points to the first byte of the string which hasn't
3368 * been examined yet. Otherwise two_byte_count is 1, and t
3369 * points to the first byte in the string that will expand to
3370 * two. Depending on this, start examining at t or 1 after t.
3371 * */
3372
3373 U8 *d = t + two_byte_count;
3374
3375
3376 /* Count up the remaining bytes that expand to two */
3377
3378 while (d < e) {
3379 const U8 chr = *d++;
3380 if (! NATIVE_IS_INVARIANT(chr)) two_byte_count++;
3381 }
3382
3383 /* The string will expand by just the number of bytes that
3384 * occupy two positions. But we are one afterwards because of
3385 * the increment just above. This is the place to put the
3386 * trailing NUL, and to set the length before we decrement */
3387
3388 d += two_byte_count;
3389 SvCUR_set(sv, d - s);
3390 *d-- = '\0';
3391
3392
3393 /* Having decremented d, it points to the position to put the
3394 * very last byte of the expanded string. Go backwards through
3395 * the string, copying and expanding as we go, stopping when we
3396 * get to the part that is invariant the rest of the way down */
3397
3398 e--;
3399 while (e >= t) {
3400 const U8 ch = NATIVE8_TO_UNI(*e--);
3401 if (UNI_IS_INVARIANT(ch)) {
3402 *d-- = UNI_TO_NATIVE(ch);
3403 } else {
3404 *d-- = (U8)UTF8_EIGHT_BIT_LO(ch);
3405 *d-- = (U8)UTF8_EIGHT_BIT_HI(ch);
3406 }
3407 }
3408 }
3409 }
560a288e 3410 }
b3ab6785
KW
3411
3412 /* Mark as UTF-8 even if no variant - saves scanning loop */
3413 SvUTF8_on(sv);
4411f3b6 3414 return SvCUR(sv);
560a288e
GS
3415}
3416
c461cf8f
JH
3417/*
3418=for apidoc sv_utf8_downgrade
3419
78ea37eb 3420Attempts to convert the PV of an SV from characters to bytes.
2bbc8d55
SP
3421If the PV contains a character that cannot fit
3422in a byte, this conversion will fail;
78ea37eb 3423in this case, either returns false or, if C<fail_ok> is not
c461cf8f
JH
3424true, croaks.
3425
13a6c0e0
JH
3426This is not as a general purpose Unicode to byte encoding interface:
3427use the Encode extension for that.
3428
c461cf8f
JH
3429=cut
3430*/
3431
560a288e 3432bool
7bc54cea 3433Perl_sv_utf8_downgrade(pTHX_ register SV *const sv, const bool fail_ok)
560a288e 3434{
97aff369 3435 dVAR;
7918f24d
NC
3436
3437 PERL_ARGS_ASSERT_SV_UTF8_DOWNGRADE;
3438
78ea37eb 3439 if (SvPOKp(sv) && SvUTF8(sv)) {
fa301091 3440 if (SvCUR(sv)) {
03cfe0ae 3441 U8 *s;
652088fc 3442 STRLEN len;
fa301091 3443
765f542d
NC
3444 if (SvIsCOW(sv)) {
3445 sv_force_normal_flags(sv, 0);
3446 }
03cfe0ae
NIS
3447 s = (U8 *) SvPV(sv, len);
3448 if (!utf8_to_bytes(s, &len)) {
fa301091
JH
3449 if (fail_ok)
3450 return FALSE;
3451 else {
3452 if (PL_op)
3453 Perl_croak(aTHX_ "Wide character in %s",
53e06cf0 3454 OP_DESC(PL_op));
fa301091
JH
3455 else
3456 Perl_croak(aTHX_ "Wide character");
3457 }
4b3603a4 3458 }
b162af07 3459 SvCUR_set(sv, len);
67e989fb 3460 }
560a288e 3461 }
ffebcc3e 3462 SvUTF8_off(sv);
560a288e
GS
3463 return TRUE;
3464}
3465
c461cf8f
JH
3466/*
3467=for apidoc sv_utf8_encode
3468
78ea37eb
TS
3469Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3470flag off so that it looks like octets again.
c461cf8f
JH
3471
3472=cut
3473*/
3474
560a288e 3475void
7bc54cea 3476Perl_sv_utf8_encode(pTHX_ register SV *const sv)
560a288e 3477{
7918f24d
NC
3478 PERL_ARGS_ASSERT_SV_UTF8_ENCODE;
3479
4c94c214
NC
3480 if (SvIsCOW(sv)) {
3481 sv_force_normal_flags(sv, 0);
3482 }
3483 if (SvREADONLY(sv)) {
6ad8f254 3484 Perl_croak_no_modify(aTHX);
4c94c214 3485 }
a5f5288a 3486 (void) sv_utf8_upgrade(sv);
560a288e
GS
3487 SvUTF8_off(sv);
3488}
3489
4411f3b6
NIS
3490/*
3491=for apidoc sv_utf8_decode
3492
78ea37eb
TS
3493If the PV of the SV is an octet sequence in UTF-8
3494and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3495so that it looks like a character. If the PV contains only single-byte
3496characters, the C<SvUTF8> flag stays being off.
3497Scans PV for validity and returns false if the PV is invalid UTF-8.
4411f3b6
NIS
3498
3499=cut
3500*/
3501
560a288e 3502bool
7bc54cea 3503Perl_sv_utf8_decode(pTHX_ register SV *const sv)
560a288e 3504{
7918f24d
NC
3505 PERL_ARGS_ASSERT_SV_UTF8_DECODE;
3506
78ea37eb 3507 if (SvPOKp(sv)) {
93524f2b
NC
3508 const U8 *c;
3509 const U8 *e;
9cbac4c7 3510
645c22ef
DM
3511 /* The octets may have got themselves encoded - get them back as
3512 * bytes
3513 */
3514 if (!sv_utf8_downgrade(sv, TRUE))
560a288e
GS
3515 return FALSE;
3516
3517 /* it is actually just a matter of turning the utf8 flag on, but
3518 * we want to make sure everything inside is valid utf8 first.
3519 */
93524f2b 3520 c = (const U8 *) SvPVX_const(sv);
63cd0674 3521 if (!is_utf8_string(c, SvCUR(sv)+1))
67e989fb 3522 return FALSE;
93524f2b 3523 e = (const U8 *) SvEND(sv);
511c2ff0 3524 while (c < e) {
b64e5050 3525 const U8 ch = *c++;
c4d5f83a 3526 if (!UTF8_IS_INVARIANT(ch)) {
67e989fb
JH
3527 SvUTF8_on(sv);
3528 break;
3529 }
560a288e 3530 }
560a288e
GS
3531 }
3532 return TRUE;
3533}
3534
954c1994
GS
3535/*
3536=for apidoc sv_setsv
3537
645c22ef
DM
3538Copies the contents of the source SV C<ssv> into the destination SV
3539C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3540function if the source SV needs to be reused. Does not handle 'set' magic.
3541Loosely speaking, it performs a copy-by-value, obliterating any previous
3542content of the destination.
3543
3544You probably want to use one of the assortment of wrappers, such as
3545C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3546C<SvSetMagicSV_nosteal>.
3547
8d6d96c1
HS
3548=for apidoc sv_setsv_flags
3549
645c22ef
DM
3550Copies the contents of the source SV C<ssv> into the destination SV
3551C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3552function if the source SV needs to be reused. Does not handle 'set' magic.
3553Loosely speaking, it performs a copy-by-value, obliterating any previous
3554content of the destination.
3555If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
5fcdf167
NC
3556C<ssv> if appropriate, else not. If the C<flags> parameter has the
3557C<NOSTEAL> bit set then the buffers of temps will not be stolen. <sv_setsv>
3558and C<sv_setsv_nomg> are implemented in terms of this function.
645c22ef
DM
3559
3560You probably want to use one of the assortment of wrappers, such as
3561C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3562C<SvSetMagicSV_nosteal>.
3563
3564This is the primary function for copying scalars, and most other
3565copy-ish functions and macros use this underneath.
8d6d96c1
HS
3566
3567=cut
3568*/
3569
5d0301b7 3570static void
7bc54cea 3571S_glob_assign_glob(pTHX_ SV *const dstr, SV *const sstr, const int dtype)
5d0301b7 3572{
70cd14a1 3573 I32 mro_changes = 0; /* 1 = method, 2 = isa */
dd69841b 3574
7918f24d
NC
3575 PERL_ARGS_ASSERT_GLOB_ASSIGN_GLOB;
3576
5d0301b7
NC
3577 if (dtype != SVt_PVGV) {
3578 const char * const name = GvNAME(sstr);
3579 const STRLEN len = GvNAMELEN(sstr);
0d092c36 3580 {
f7877b28
NC
3581 if (dtype >= SVt_PV) {
3582 SvPV_free(dstr);
3583 SvPV_set(dstr, 0);
3584 SvLEN_set(dstr, 0);
3585 SvCUR_set(dstr, 0);
3586 }
0d092c36 3587 SvUPGRADE(dstr, SVt_PVGV);
dedf8e73 3588 (void)SvOK_off(dstr);
2e5b91de
NC
3589 /* FIXME - why are we doing this, then turning it off and on again
3590 below? */
3591 isGV_with_GP_on(dstr);
f7877b28 3592 }
5d0301b7
NC
3593 GvSTASH(dstr) = GvSTASH(sstr);
3594 if (GvSTASH(dstr))
daba3364 3595 Perl_sv_add_backref(aTHX_ MUTABLE_SV(GvSTASH(dstr)), dstr);
159b6efe 3596 gv_name_set(MUTABLE_GV(dstr), name, len, GV_ADD);
5d0301b7
NC
3597 SvFAKE_on(dstr); /* can coerce to non-glob */
3598 }
3599
159b6efe 3600 if(GvGP(MUTABLE_GV(sstr))) {
dd69841b
BB
3601 /* If source has method cache entry, clear it */
3602 if(GvCVGEN(sstr)) {
3603 SvREFCNT_dec(GvCV(sstr));
3604 GvCV(sstr) = NULL;
3605 GvCVGEN(sstr) = 0;
3606 }
3607 /* If source has a real method, then a method is
3608 going to change */
159b6efe 3609 else if(GvCV((const GV *)sstr)) {
70cd14a1 3610 mro_changes = 1;
dd69841b
BB
3611 }
3612 }
3613
3614 /* If dest already had a real method, that's a change as well */
159b6efe 3615 if(!mro_changes && GvGP(MUTABLE_GV(dstr)) && GvCVu((const GV *)dstr)) {
70cd14a1 3616 mro_changes = 1;
dd69841b
BB
3617 }
3618
159b6efe 3619 if(strEQ(GvNAME((const GV *)dstr),"ISA"))
70cd14a1
CB
3620 mro_changes = 2;
3621
159b6efe 3622 gp_free(MUTABLE_GV(dstr));
2e5b91de 3623 isGV_with_GP_off(dstr);
5d0301b7 3624 (void)SvOK_off(dstr);
2e5b91de 3625 isGV_with_GP_on(dstr);
dedf8e73 3626 GvINTRO_off(dstr); /* one-shot flag */
5d0301b7
NC
3627 GvGP(dstr) = gp_ref(GvGP(sstr));
3628 if (SvTAINTED(sstr))
3629 SvTAINT(dstr);
3630 if (GvIMPORTED(dstr) != GVf_IMPORTED
3631 && CopSTASH_ne(PL_curcop, GvSTASH(dstr)))
3632 {
3633 GvIMPORTED_on(dstr);
3634 }
3635 GvMULTI_on(dstr);
70cd14a1
CB
3636 if(mro_changes == 2) mro_isa_changed_in(GvSTASH(dstr));
3637 else if(mro_changes) mro_method_changed_in(GvSTASH(dstr));
5d0301b7
NC
3638 return;
3639}
3640
b8473700 3641static void
7bc54cea 3642S_glob_assign_ref(pTHX_ SV *const dstr, SV *const sstr)
7918f24d 3643{
b8473700
NC
3644 SV * const sref = SvREFCNT_inc(SvRV(sstr));
3645 SV *dref = NULL;
3646 const int intro = GvINTRO(dstr);
2440974c 3647 SV **location;
3386d083 3648 U8 import_flag = 0;
27242d61
NC
3649 const U32 stype = SvTYPE(sref);