This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Remove the unused new_X*V and del_X*V macros from sv.c
[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
889d28b2 928#if 2 *PTRSIZE <= IVSIZE
bd81e77b 929 /* 12 */
bc337e5c 930 { sizeof(XPVIV) - STRUCT_OFFSET(XPV, xpv_cur),
889d28b2
NC
931 copy_length(XPVIV, xiv_u) - STRUCT_OFFSET(XPV, xpv_cur),
932 + STRUCT_OFFSET(XPV, xpv_cur),
933 SVt_PVIV, FALSE, NONV, HASARENA,
934 FIT_ARENA(0, sizeof(XPVIV) - STRUCT_OFFSET(XPV, xpv_cur)) },
935 /* 12 */
936#else
937 { sizeof(XPVIV),
601dfd0a
NC
938 copy_length(XPVIV, xiv_u),
939 0,
69ba284b 940 SVt_PVIV, FALSE, NONV, HASARENA,
889d28b2
NC
941 FIT_ARENA(0, sizeof(XPVIV)) },
942#endif
d2a0f284 943
889d28b2
NC
944#if (2 *PTRSIZE <= IVSIZE) && (2 *PTRSIZE <= NVSIZE)
945 /* 20 */
bc337e5c 946 { sizeof(XPVNV) - STRUCT_OFFSET(XPV, xpv_cur),
889d28b2
NC
947 copy_length(XPVNV, xnv_u) - STRUCT_OFFSET(XPV, xpv_cur),
948 + STRUCT_OFFSET(XPV, xpv_cur),
949 SVt_PVNV, FALSE, HADNV, HASARENA,
950 FIT_ARENA(0, sizeof(XPVNV) - STRUCT_OFFSET(XPV, xpv_cur)) },
951#else
bd81e77b 952 /* 20 */
6e128786 953 { sizeof(XPVNV), copy_length(XPVNV, xnv_u), 0, SVt_PVNV, FALSE, HADNV,
d2a0f284 954 HASARENA, FIT_ARENA(0, sizeof(XPVNV)) },
889d28b2 955#endif
d2a0f284 956
bd81e77b 957 /* 28 */
6e128786 958 { sizeof(XPVMG), copy_length(XPVMG, xnv_u), 0, SVt_PVMG, FALSE, HADNV,
d2a0f284 959 HASARENA, FIT_ARENA(0, sizeof(XPVMG)) },
4df7f6af 960
288b8c02 961 /* something big */
601dfd0a
NC
962 { sizeof(regexp),
963 sizeof(regexp),
964 0,
08e44740 965 SVt_REGEXP, FALSE, NONV, HASARENA,
b6f60916 966 FIT_ARENA(0, sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur))
5c35adbb 967 },
4df7f6af 968
bd81e77b 969 /* 48 */
10666ae3 970 { sizeof(XPVGV), sizeof(XPVGV), 0, SVt_PVGV, TRUE, HADNV,
d2a0f284
JC
971 HASARENA, FIT_ARENA(0, sizeof(XPVGV)) },
972
bd81e77b 973 /* 64 */
10666ae3 974 { sizeof(XPVLV), sizeof(XPVLV), 0, SVt_PVLV, TRUE, HADNV,
d2a0f284
JC
975 HASARENA, FIT_ARENA(0, sizeof(XPVLV)) },
976
601dfd0a 977 { sizeof(XPVAV),
4f7003f5 978 copy_length(XPVAV, xav_alloc),
601dfd0a 979 0,
69ba284b 980 SVt_PVAV, TRUE, NONV, HASARENA,
601dfd0a 981 FIT_ARENA(0, sizeof(XPVAV)) },
d2a0f284 982
601dfd0a 983 { sizeof(XPVHV),
359164a0 984 copy_length(XPVHV, xhv_max),
601dfd0a 985 0,
69ba284b 986 SVt_PVHV, TRUE, NONV, HASARENA,
601dfd0a 987 FIT_ARENA(0, sizeof(XPVHV)) },
d2a0f284 988
c84c4652 989 /* 56 */
601dfd0a
NC
990 { sizeof(XPVCV),
991 sizeof(XPVCV),
992 0,
69ba284b 993 SVt_PVCV, TRUE, NONV, HASARENA,
601dfd0a 994 FIT_ARENA(0, sizeof(XPVCV)) },
69ba284b 995
601dfd0a
NC
996 { sizeof(XPVFM),
997 sizeof(XPVFM),
998 0,
69ba284b 999 SVt_PVFM, TRUE, NONV, NOARENA,
601dfd0a 1000 FIT_ARENA(20, sizeof(XPVFM)) },
d2a0f284
JC
1001
1002 /* XPVIO is 84 bytes, fits 48x */
601dfd0a
NC
1003 { sizeof(XPVIO),
1004 sizeof(XPVIO),
1005 0,
b6f60916 1006 SVt_PVIO, TRUE, NONV, HASARENA,
601dfd0a 1007 FIT_ARENA(24, sizeof(XPVIO)) },
bd81e77b 1008};
29489e7c 1009
bd81e77b 1010#define new_body_allocated(sv_type) \
d2a0f284 1011 (void *)((char *)S_new_body(aTHX_ sv_type) \
bd81e77b 1012 - bodies_by_type[sv_type].offset)
29489e7c 1013
bd81e77b
NC
1014#define del_body_allocated(p, sv_type) \
1015 del_body(p + bodies_by_type[sv_type].offset, &PL_body_roots[sv_type])
29489e7c 1016
29489e7c 1017
bd81e77b
NC
1018#define my_safemalloc(s) (void*)safemalloc(s)
1019#define my_safecalloc(s) (void*)safecalloc(s, 1)
1020#define my_safefree(p) safefree((char*)p)
29489e7c 1021
bd81e77b 1022#ifdef PURIFY
29489e7c 1023
bd81e77b 1024#define new_XNV() my_safemalloc(sizeof(XPVNV))
bd81e77b 1025#define new_XPVNV() my_safemalloc(sizeof(XPVNV))
bd81e77b 1026#define new_XPVMG() my_safemalloc(sizeof(XPVMG))
29489e7c 1027
bd81e77b 1028#define del_XPVGV(p) my_safefree(p)
29489e7c 1029
bd81e77b 1030#else /* !PURIFY */
29489e7c 1031
65ac1738 1032#define new_XNV() new_body_allocated(SVt_NV)
65ac1738 1033#define new_XPVNV() new_body_allocated(SVt_PVNV)
65ac1738 1034#define new_XPVMG() new_body_allocated(SVt_PVMG)
645c22ef 1035
65ac1738 1036#define del_XPVGV(p) del_body_allocated(p, SVt_PVGV)
1d7c1841 1037
bd81e77b 1038#endif /* PURIFY */
93e68bfb 1039
bd81e77b 1040/* no arena for you! */
93e68bfb 1041
bd81e77b 1042#define new_NOARENA(details) \
d2a0f284 1043 my_safemalloc((details)->body_size + (details)->offset)
bd81e77b 1044#define new_NOARENAZ(details) \
d2a0f284
JC
1045 my_safecalloc((details)->body_size + (details)->offset)
1046
1047STATIC void *
de37a194 1048S_more_bodies (pTHX_ const svtype sv_type)
d2a0f284
JC
1049{
1050 dVAR;
1051 void ** const root = &PL_body_roots[sv_type];
96a5add6 1052 const struct body_details * const bdp = &bodies_by_type[sv_type];
d2a0f284
JC
1053 const size_t body_size = bdp->body_size;
1054 char *start;
1055 const char *end;
d8fca402 1056 const size_t arena_size = Perl_malloc_good_size(bdp->arena_size);
0b2d3faa 1057#if defined(DEBUGGING) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
23e9d66c
NC
1058 static bool done_sanity_check;
1059
0b2d3faa
JH
1060 /* PERL_GLOBAL_STRUCT_PRIVATE cannot coexist with global
1061 * variables like done_sanity_check. */
10666ae3 1062 if (!done_sanity_check) {
ea471437 1063 unsigned int i = SVt_LAST;
10666ae3
NC
1064
1065 done_sanity_check = TRUE;
1066
1067 while (i--)
1068 assert (bodies_by_type[i].type == i);
1069 }
1070#endif
1071
23e9d66c
NC
1072 assert(bdp->arena_size);
1073
d8fca402 1074 start = (char*) Perl_get_arena(aTHX_ arena_size, sv_type);
d2a0f284 1075
d8fca402 1076 end = start + arena_size - 2 * body_size;
d2a0f284 1077
d2a0f284 1078 /* computed count doesnt reflect the 1st slot reservation */
d8fca402
NC
1079#if defined(MYMALLOC) || defined(HAS_MALLOC_GOOD_SIZE)
1080 DEBUG_m(PerlIO_printf(Perl_debug_log,
1081 "arena %p end %p arena-size %d (from %d) type %d "
1082 "size %d ct %d\n",
1083 (void*)start, (void*)end, (int)arena_size,
1084 (int)bdp->arena_size, sv_type, (int)body_size,
1085 (int)arena_size / (int)body_size));
1086#else
d2a0f284
JC
1087 DEBUG_m(PerlIO_printf(Perl_debug_log,
1088 "arena %p end %p arena-size %d type %d size %d ct %d\n",
6c9570dc 1089 (void*)start, (void*)end,
0e84aef4
JH
1090 (int)bdp->arena_size, sv_type, (int)body_size,
1091 (int)bdp->arena_size / (int)body_size));
d8fca402 1092#endif
d2a0f284
JC
1093 *root = (void *)start;
1094
d8fca402 1095 while (start <= end) {
d2a0f284
JC
1096 char * const next = start + body_size;
1097 *(void**) start = (void *)next;
1098 start = next;
1099 }
1100 *(void **)start = 0;
1101
1102 return *root;
1103}
1104
1105/* grab a new thing from the free list, allocating more if necessary.
1106 The inline version is used for speed in hot routines, and the
1107 function using it serves the rest (unless PURIFY).
1108*/
1109#define new_body_inline(xpv, sv_type) \
1110 STMT_START { \
1111 void ** const r3wt = &PL_body_roots[sv_type]; \
11b79775
DD
1112 xpv = (PTR_TBL_ENT_t*) (*((void **)(r3wt)) \
1113 ? *((void **)(r3wt)) : more_bodies(sv_type)); \
d2a0f284 1114 *(r3wt) = *(void**)(xpv); \
d2a0f284
JC
1115 } STMT_END
1116
1117#ifndef PURIFY
1118
1119STATIC void *
de37a194 1120S_new_body(pTHX_ const svtype sv_type)
d2a0f284
JC
1121{
1122 dVAR;
1123 void *xpv;
1124 new_body_inline(xpv, sv_type);
1125 return xpv;
1126}
1127
1128#endif
93e68bfb 1129
238b27b3
NC
1130static const struct body_details fake_rv =
1131 { 0, 0, 0, SVt_IV, FALSE, NONV, NOARENA, 0 };
1132
bd81e77b
NC
1133/*
1134=for apidoc sv_upgrade
93e68bfb 1135
bd81e77b
NC
1136Upgrade an SV to a more complex form. Generally adds a new body type to the
1137SV, then copies across as much information as possible from the old body.
1138You generally want to use the C<SvUPGRADE> macro wrapper. See also C<svtype>.
93e68bfb 1139
bd81e77b 1140=cut
93e68bfb 1141*/
93e68bfb 1142
bd81e77b 1143void
aad570aa 1144Perl_sv_upgrade(pTHX_ register SV *const sv, svtype new_type)
cac9b346 1145{
97aff369 1146 dVAR;
bd81e77b
NC
1147 void* old_body;
1148 void* new_body;
42d0e0b7 1149 const svtype old_type = SvTYPE(sv);
d2a0f284 1150 const struct body_details *new_type_details;
238b27b3 1151 const struct body_details *old_type_details
bd81e77b 1152 = bodies_by_type + old_type;
4df7f6af 1153 SV *referant = NULL;
cac9b346 1154
7918f24d
NC
1155 PERL_ARGS_ASSERT_SV_UPGRADE;
1156
1776cbe8
NC
1157 if (old_type == new_type)
1158 return;
1159
1160 /* This clause was purposefully added ahead of the early return above to
1161 the shared string hackery for (sort {$a <=> $b} keys %hash), with the
1162 inference by Nick I-S that it would fix other troublesome cases. See
1163 changes 7162, 7163 (f130fd4589cf5fbb24149cd4db4137c8326f49c1 and parent)
1164
1165 Given that shared hash key scalars are no longer PVIV, but PV, there is
1166 no longer need to unshare so as to free up the IVX slot for its proper
1167 purpose. So it's safe to move the early return earlier. */
1168
bd81e77b
NC
1169 if (new_type != SVt_PV && SvIsCOW(sv)) {
1170 sv_force_normal_flags(sv, 0);
1171 }
cac9b346 1172
bd81e77b 1173 old_body = SvANY(sv);
de042e1d 1174
bd81e77b
NC
1175 /* Copying structures onto other structures that have been neatly zeroed
1176 has a subtle gotcha. Consider XPVMG
cac9b346 1177
bd81e77b
NC
1178 +------+------+------+------+------+-------+-------+
1179 | NV | CUR | LEN | IV | MAGIC | STASH |
1180 +------+------+------+------+------+-------+-------+
1181 0 4 8 12 16 20 24 28
645c22ef 1182
bd81e77b
NC
1183 where NVs are aligned to 8 bytes, so that sizeof that structure is
1184 actually 32 bytes long, with 4 bytes of padding at the end:
08742458 1185
bd81e77b
NC
1186 +------+------+------+------+------+-------+-------+------+
1187 | NV | CUR | LEN | IV | MAGIC | STASH | ??? |
1188 +------+------+------+------+------+-------+-------+------+
1189 0 4 8 12 16 20 24 28 32
08742458 1190
bd81e77b 1191 so what happens if you allocate memory for this structure:
30f9da9e 1192
bd81e77b
NC
1193 +------+------+------+------+------+-------+-------+------+------+...
1194 | NV | CUR | LEN | IV | MAGIC | STASH | GP | NAME |
1195 +------+------+------+------+------+-------+-------+------+------+...
1196 0 4 8 12 16 20 24 28 32 36
bfc44f79 1197
bd81e77b
NC
1198 zero it, then copy sizeof(XPVMG) bytes on top of it? Not quite what you
1199 expect, because you copy the area marked ??? onto GP. Now, ??? may have
1200 started out as zero once, but it's quite possible that it isn't. So now,
1201 rather than a nicely zeroed GP, you have it pointing somewhere random.
1202 Bugs ensue.
bfc44f79 1203
bd81e77b
NC
1204 (In fact, GP ends up pointing at a previous GP structure, because the
1205 principle cause of the padding in XPVMG getting garbage is a copy of
6c9e42f7
NC
1206 sizeof(XPVMG) bytes from a XPVGV structure in sv_unglob. Right now
1207 this happens to be moot because XPVGV has been re-ordered, with GP
1208 no longer after STASH)
30f9da9e 1209
bd81e77b
NC
1210 So we are careful and work out the size of used parts of all the
1211 structures. */
bfc44f79 1212
bd81e77b
NC
1213 switch (old_type) {
1214 case SVt_NULL:
1215 break;
1216 case SVt_IV:
4df7f6af
NC
1217 if (SvROK(sv)) {
1218 referant = SvRV(sv);
238b27b3
NC
1219 old_type_details = &fake_rv;
1220 if (new_type == SVt_NV)
1221 new_type = SVt_PVNV;
4df7f6af
NC
1222 } else {
1223 if (new_type < SVt_PVIV) {
1224 new_type = (new_type == SVt_NV)
1225 ? SVt_PVNV : SVt_PVIV;
1226 }
bd81e77b
NC
1227 }
1228 break;
1229 case SVt_NV:
1230 if (new_type < SVt_PVNV) {
1231 new_type = SVt_PVNV;
bd81e77b
NC
1232 }
1233 break;
bd81e77b
NC
1234 case SVt_PV:
1235 assert(new_type > SVt_PV);
1236 assert(SVt_IV < SVt_PV);
1237 assert(SVt_NV < SVt_PV);
1238 break;
1239 case SVt_PVIV:
1240 break;
1241 case SVt_PVNV:
1242 break;
1243 case SVt_PVMG:
1244 /* Because the XPVMG of PL_mess_sv isn't allocated from the arena,
1245 there's no way that it can be safely upgraded, because perl.c
1246 expects to Safefree(SvANY(PL_mess_sv)) */
1247 assert(sv != PL_mess_sv);
1248 /* This flag bit is used to mean other things in other scalar types.
1249 Given that it only has meaning inside the pad, it shouldn't be set
1250 on anything that can get upgraded. */
00b1698f 1251 assert(!SvPAD_TYPED(sv));
bd81e77b
NC
1252 break;
1253 default:
1254 if (old_type_details->cant_upgrade)
c81225bc
NC
1255 Perl_croak(aTHX_ "Can't upgrade %s (%" UVuf ") to %" UVuf,
1256 sv_reftype(sv, 0), (UV) old_type, (UV) new_type);
bd81e77b 1257 }
3376de98
NC
1258
1259 if (old_type > new_type)
1260 Perl_croak(aTHX_ "sv_upgrade from type %d down to type %d",
1261 (int)old_type, (int)new_type);
1262
2fa1109b 1263 new_type_details = bodies_by_type + new_type;
645c22ef 1264
bd81e77b
NC
1265 SvFLAGS(sv) &= ~SVTYPEMASK;
1266 SvFLAGS(sv) |= new_type;
932e9ff9 1267
ab4416c0
NC
1268 /* This can't happen, as SVt_NULL is <= all values of new_type, so one of
1269 the return statements above will have triggered. */
1270 assert (new_type != SVt_NULL);
bd81e77b 1271 switch (new_type) {
bd81e77b
NC
1272 case SVt_IV:
1273 assert(old_type == SVt_NULL);
1274 SvANY(sv) = (XPVIV*)((char*)&(sv->sv_u.svu_iv) - STRUCT_OFFSET(XPVIV, xiv_iv));
1275 SvIV_set(sv, 0);
1276 return;
1277 case SVt_NV:
1278 assert(old_type == SVt_NULL);
1279 SvANY(sv) = new_XNV();
1280 SvNV_set(sv, 0);
1281 return;
bd81e77b 1282 case SVt_PVHV:
bd81e77b 1283 case SVt_PVAV:
d2a0f284 1284 assert(new_type_details->body_size);
c1ae03ae
NC
1285
1286#ifndef PURIFY
1287 assert(new_type_details->arena);
d2a0f284 1288 assert(new_type_details->arena_size);
c1ae03ae 1289 /* This points to the start of the allocated area. */
d2a0f284
JC
1290 new_body_inline(new_body, new_type);
1291 Zero(new_body, new_type_details->body_size, char);
c1ae03ae
NC
1292 new_body = ((char *)new_body) - new_type_details->offset;
1293#else
1294 /* We always allocated the full length item with PURIFY. To do this
1295 we fake things so that arena is false for all 16 types.. */
1296 new_body = new_NOARENAZ(new_type_details);
1297#endif
1298 SvANY(sv) = new_body;
1299 if (new_type == SVt_PVAV) {
1300 AvMAX(sv) = -1;
1301 AvFILLp(sv) = -1;
1302 AvREAL_only(sv);
64484faa 1303 if (old_type_details->body_size) {
ac572bf4
NC
1304 AvALLOC(sv) = 0;
1305 } else {
1306 /* It will have been zeroed when the new body was allocated.
1307 Lets not write to it, in case it confuses a write-back
1308 cache. */
1309 }
78ac7dd9
NC
1310 } else {
1311 assert(!SvOK(sv));
1312 SvOK_off(sv);
1313#ifndef NODEFAULT_SHAREKEYS
1314 HvSHAREKEYS_on(sv); /* key-sharing on by default */
1315#endif
1316 HvMAX(sv) = 7; /* (start with 8 buckets) */
c1ae03ae 1317 }
aeb18a1e 1318
bd81e77b
NC
1319 /* SVt_NULL isn't the only thing upgraded to AV or HV.
1320 The target created by newSVrv also is, and it can have magic.
1321 However, it never has SvPVX set.
1322 */
4df7f6af
NC
1323 if (old_type == SVt_IV) {
1324 assert(!SvROK(sv));
1325 } else if (old_type >= SVt_PV) {
bd81e77b
NC
1326 assert(SvPVX_const(sv) == 0);
1327 }
aeb18a1e 1328
bd81e77b 1329 if (old_type >= SVt_PVMG) {
e736a858 1330 SvMAGIC_set(sv, ((XPVMG*)old_body)->xmg_u.xmg_magic);
bd81e77b 1331 SvSTASH_set(sv, ((XPVMG*)old_body)->xmg_stash);
797c7171
NC
1332 } else {
1333 sv->sv_u.svu_array = NULL; /* or svu_hash */
bd81e77b
NC
1334 }
1335 break;
93e68bfb 1336
93e68bfb 1337
b9ad13ac
NC
1338 case SVt_REGEXP:
1339 /* This ensures that SvTHINKFIRST(sv) is true, and hence that
1340 sv_force_normal_flags(sv) is called. */
1341 SvFAKE_on(sv);
bd81e77b
NC
1342 case SVt_PVIV:
1343 /* XXX Is this still needed? Was it ever needed? Surely as there is
1344 no route from NV to PVIV, NOK can never be true */
1345 assert(!SvNOKp(sv));
1346 assert(!SvNOK(sv));
1347 case SVt_PVIO:
1348 case SVt_PVFM:
bd81e77b
NC
1349 case SVt_PVGV:
1350 case SVt_PVCV:
1351 case SVt_PVLV:
1352 case SVt_PVMG:
1353 case SVt_PVNV:
1354 case SVt_PV:
93e68bfb 1355
d2a0f284 1356 assert(new_type_details->body_size);
bd81e77b
NC
1357 /* We always allocated the full length item with PURIFY. To do this
1358 we fake things so that arena is false for all 16 types.. */
1359 if(new_type_details->arena) {
1360 /* This points to the start of the allocated area. */
d2a0f284
JC
1361 new_body_inline(new_body, new_type);
1362 Zero(new_body, new_type_details->body_size, char);
bd81e77b
NC
1363 new_body = ((char *)new_body) - new_type_details->offset;
1364 } else {
1365 new_body = new_NOARENAZ(new_type_details);
1366 }
1367 SvANY(sv) = new_body;
5e2fc214 1368
bd81e77b 1369 if (old_type_details->copy) {
f9ba3d20
NC
1370 /* There is now the potential for an upgrade from something without
1371 an offset (PVNV or PVMG) to something with one (PVCV, PVFM) */
1372 int offset = old_type_details->offset;
1373 int length = old_type_details->copy;
1374
1375 if (new_type_details->offset > old_type_details->offset) {
d4c19fe8 1376 const int difference
f9ba3d20
NC
1377 = new_type_details->offset - old_type_details->offset;
1378 offset += difference;
1379 length -= difference;
1380 }
1381 assert (length >= 0);
1382
1383 Copy((char *)old_body + offset, (char *)new_body + offset, length,
1384 char);
bd81e77b
NC
1385 }
1386
1387#ifndef NV_ZERO_IS_ALLBITS_ZERO
f2524eef 1388 /* If NV 0.0 is stores as all bits 0 then Zero() already creates a
e5ce394c
NC
1389 * correct 0.0 for us. Otherwise, if the old body didn't have an
1390 * NV slot, but the new one does, then we need to initialise the
1391 * freshly created NV slot with whatever the correct bit pattern is
1392 * for 0.0 */
e22a937e
NC
1393 if (old_type_details->zero_nv && !new_type_details->zero_nv
1394 && !isGV_with_GP(sv))
bd81e77b 1395 SvNV_set(sv, 0);
82048762 1396#endif
5e2fc214 1397
85dca89a
NC
1398 if (new_type == SVt_PVIO) {
1399 IO * const io = MUTABLE_IO(sv);
d963bf01 1400 GV *iogv = gv_fetchpvs("IO::File::", GV_ADD, SVt_PVHV);
85dca89a
NC
1401
1402 SvOBJECT_on(io);
1403 /* Clear the stashcache because a new IO could overrule a package
1404 name */
1405 hv_clear(PL_stashcache);
1406
85dca89a 1407 SvSTASH_set(io, MUTABLE_HV(SvREFCNT_inc(GvHV(iogv))));
f2524eef 1408 IoPAGE_LEN(sv) = 60;
85dca89a 1409 }
4df7f6af
NC
1410 if (old_type < SVt_PV) {
1411 /* referant will be NULL unless the old type was SVt_IV emulating
1412 SVt_RV */
1413 sv->sv_u.svu_rv = referant;
1414 }
bd81e77b
NC
1415 break;
1416 default:
afd78fd5
JH
1417 Perl_croak(aTHX_ "panic: sv_upgrade to unknown type %lu",
1418 (unsigned long)new_type);
bd81e77b 1419 }
73171d91 1420
db93c0c4 1421 if (old_type > SVt_IV) {
bd81e77b
NC
1422#ifdef PURIFY
1423 my_safefree(old_body);
1424#else
bc786448
GG
1425 /* Note that there is an assumption that all bodies of types that
1426 can be upgraded came from arenas. Only the more complex non-
1427 upgradable types are allowed to be directly malloc()ed. */
1428 assert(old_type_details->arena);
bd81e77b
NC
1429 del_body((void*)((char*)old_body + old_type_details->offset),
1430 &PL_body_roots[old_type]);
1431#endif
1432 }
1433}
73171d91 1434
bd81e77b
NC
1435/*
1436=for apidoc sv_backoff
73171d91 1437
bd81e77b
NC
1438Remove any string offset. You should normally use the C<SvOOK_off> macro
1439wrapper instead.
73171d91 1440
bd81e77b 1441=cut
73171d91
NC
1442*/
1443
bd81e77b 1444int
aad570aa 1445Perl_sv_backoff(pTHX_ register SV *const sv)
bd81e77b 1446{
69240efd 1447 STRLEN delta;
7a4bba22 1448 const char * const s = SvPVX_const(sv);
7918f24d
NC
1449
1450 PERL_ARGS_ASSERT_SV_BACKOFF;
96a5add6 1451 PERL_UNUSED_CONTEXT;
7918f24d 1452
bd81e77b
NC
1453 assert(SvOOK(sv));
1454 assert(SvTYPE(sv) != SVt_PVHV);
1455 assert(SvTYPE(sv) != SVt_PVAV);
7a4bba22 1456
69240efd
NC
1457 SvOOK_offset(sv, delta);
1458
7a4bba22
NC
1459 SvLEN_set(sv, SvLEN(sv) + delta);
1460 SvPV_set(sv, SvPVX(sv) - delta);
1461 Move(s, SvPVX(sv), SvCUR(sv)+1, char);
bd81e77b
NC
1462 SvFLAGS(sv) &= ~SVf_OOK;
1463 return 0;
1464}
73171d91 1465
bd81e77b
NC
1466/*
1467=for apidoc sv_grow
73171d91 1468
bd81e77b
NC
1469Expands the character buffer in the SV. If necessary, uses C<sv_unref> and
1470upgrades the SV to C<SVt_PV>. Returns a pointer to the character buffer.
1471Use the C<SvGROW> wrapper instead.
93e68bfb 1472
bd81e77b
NC
1473=cut
1474*/
93e68bfb 1475
bd81e77b 1476char *
aad570aa 1477Perl_sv_grow(pTHX_ register SV *const sv, register STRLEN newlen)
bd81e77b
NC
1478{
1479 register char *s;
93e68bfb 1480
7918f24d
NC
1481 PERL_ARGS_ASSERT_SV_GROW;
1482
5db06880
NC
1483 if (PL_madskills && newlen >= 0x100000) {
1484 PerlIO_printf(Perl_debug_log,
1485 "Allocation too large: %"UVxf"\n", (UV)newlen);
1486 }
bd81e77b
NC
1487#ifdef HAS_64K_LIMIT
1488 if (newlen >= 0x10000) {
1489 PerlIO_printf(Perl_debug_log,
1490 "Allocation too large: %"UVxf"\n", (UV)newlen);
1491 my_exit(1);
1492 }
1493#endif /* HAS_64K_LIMIT */
1494 if (SvROK(sv))
1495 sv_unref(sv);
1496 if (SvTYPE(sv) < SVt_PV) {
1497 sv_upgrade(sv, SVt_PV);
1498 s = SvPVX_mutable(sv);
1499 }
1500 else if (SvOOK(sv)) { /* pv is offset? */
1501 sv_backoff(sv);
1502 s = SvPVX_mutable(sv);
1503 if (newlen > SvLEN(sv))
1504 newlen += 10 * (newlen - SvCUR(sv)); /* avoid copy each time */
1505#ifdef HAS_64K_LIMIT
1506 if (newlen >= 0x10000)
1507 newlen = 0xFFFF;
1508#endif
1509 }
1510 else
1511 s = SvPVX_mutable(sv);
aeb18a1e 1512
bd81e77b 1513 if (newlen > SvLEN(sv)) { /* need more room? */
f1200559
WH
1514 STRLEN minlen = SvCUR(sv);
1515 minlen += (minlen >> PERL_STRLEN_EXPAND_SHIFT) + 10;
1516 if (newlen < minlen)
1517 newlen = minlen;
aedff202 1518#ifndef Perl_safesysmalloc_size
bd81e77b 1519 newlen = PERL_STRLEN_ROUNDUP(newlen);
bd81e77b 1520#endif
98653f18 1521 if (SvLEN(sv) && s) {
10edeb5d 1522 s = (char*)saferealloc(s, newlen);
bd81e77b
NC
1523 }
1524 else {
10edeb5d 1525 s = (char*)safemalloc(newlen);
bd81e77b
NC
1526 if (SvPVX_const(sv) && SvCUR(sv)) {
1527 Move(SvPVX_const(sv), s, (newlen < SvCUR(sv)) ? newlen : SvCUR(sv), char);
1528 }
1529 }
1530 SvPV_set(sv, s);
ca7c1a29 1531#ifdef Perl_safesysmalloc_size
98653f18
NC
1532 /* Do this here, do it once, do it right, and then we will never get
1533 called back into sv_grow() unless there really is some growing
1534 needed. */
ca7c1a29 1535 SvLEN_set(sv, Perl_safesysmalloc_size(s));
98653f18 1536#else
bd81e77b 1537 SvLEN_set(sv, newlen);
98653f18 1538#endif
bd81e77b
NC
1539 }
1540 return s;
1541}
aeb18a1e 1542
bd81e77b
NC
1543/*
1544=for apidoc sv_setiv
932e9ff9 1545
bd81e77b
NC
1546Copies an integer into the given SV, upgrading first if necessary.
1547Does not handle 'set' magic. See also C<sv_setiv_mg>.
463ee0b2 1548
bd81e77b
NC
1549=cut
1550*/
463ee0b2 1551
bd81e77b 1552void
aad570aa 1553Perl_sv_setiv(pTHX_ register SV *const sv, const IV i)
bd81e77b 1554{
97aff369 1555 dVAR;
7918f24d
NC
1556
1557 PERL_ARGS_ASSERT_SV_SETIV;
1558
bd81e77b
NC
1559 SV_CHECK_THINKFIRST_COW_DROP(sv);
1560 switch (SvTYPE(sv)) {
1561 case SVt_NULL:
bd81e77b 1562 case SVt_NV:
3376de98 1563 sv_upgrade(sv, SVt_IV);
bd81e77b 1564 break;
bd81e77b
NC
1565 case SVt_PV:
1566 sv_upgrade(sv, SVt_PVIV);
1567 break;
463ee0b2 1568
bd81e77b 1569 case SVt_PVGV:
6e592b3a
BM
1570 if (!isGV_with_GP(sv))
1571 break;
bd81e77b
NC
1572 case SVt_PVAV:
1573 case SVt_PVHV:
1574 case SVt_PVCV:
1575 case SVt_PVFM:
1576 case SVt_PVIO:
1577 Perl_croak(aTHX_ "Can't coerce %s to integer in %s", sv_reftype(sv,0),
1578 OP_DESC(PL_op));
42d0e0b7 1579 default: NOOP;
bd81e77b
NC
1580 }
1581 (void)SvIOK_only(sv); /* validate number */
1582 SvIV_set(sv, i);
1583 SvTAINT(sv);
1584}
932e9ff9 1585
bd81e77b
NC
1586/*
1587=for apidoc sv_setiv_mg
d33b2eba 1588
bd81e77b 1589Like C<sv_setiv>, but also handles 'set' magic.
1c846c1f 1590
bd81e77b
NC
1591=cut
1592*/
d33b2eba 1593
bd81e77b 1594void
aad570aa 1595Perl_sv_setiv_mg(pTHX_ register SV *const sv, const IV i)
bd81e77b 1596{
7918f24d
NC
1597 PERL_ARGS_ASSERT_SV_SETIV_MG;
1598
bd81e77b
NC
1599 sv_setiv(sv,i);
1600 SvSETMAGIC(sv);
1601}
727879eb 1602
bd81e77b
NC
1603/*
1604=for apidoc sv_setuv
d33b2eba 1605
bd81e77b
NC
1606Copies an unsigned integer into the given SV, upgrading first if necessary.
1607Does not handle 'set' magic. See also C<sv_setuv_mg>.
9b94d1dd 1608
bd81e77b
NC
1609=cut
1610*/
d33b2eba 1611
bd81e77b 1612void
aad570aa 1613Perl_sv_setuv(pTHX_ register SV *const sv, const UV u)
bd81e77b 1614{
7918f24d
NC
1615 PERL_ARGS_ASSERT_SV_SETUV;
1616
bd81e77b
NC
1617 /* With these two if statements:
1618 u=1.49 s=0.52 cu=72.49 cs=10.64 scripts=270 tests=20865
d33b2eba 1619
bd81e77b
NC
1620 without
1621 u=1.35 s=0.47 cu=73.45 cs=11.43 scripts=270 tests=20865
1c846c1f 1622
bd81e77b
NC
1623 If you wish to remove them, please benchmark to see what the effect is
1624 */
1625 if (u <= (UV)IV_MAX) {
1626 sv_setiv(sv, (IV)u);
1627 return;
1628 }
1629 sv_setiv(sv, 0);
1630 SvIsUV_on(sv);
1631 SvUV_set(sv, u);
1632}
d33b2eba 1633
bd81e77b
NC
1634/*
1635=for apidoc sv_setuv_mg
727879eb 1636
bd81e77b 1637Like C<sv_setuv>, but also handles 'set' magic.
9b94d1dd 1638
bd81e77b
NC
1639=cut
1640*/
5e2fc214 1641
bd81e77b 1642void
aad570aa 1643Perl_sv_setuv_mg(pTHX_ register SV *const sv, const UV u)
bd81e77b 1644{
7918f24d
NC
1645 PERL_ARGS_ASSERT_SV_SETUV_MG;
1646
bd81e77b
NC
1647 sv_setuv(sv,u);
1648 SvSETMAGIC(sv);
1649}
5e2fc214 1650
954c1994 1651/*
bd81e77b 1652=for apidoc sv_setnv
954c1994 1653
bd81e77b
NC
1654Copies a double into the given SV, upgrading first if necessary.
1655Does not handle 'set' magic. See also C<sv_setnv_mg>.
954c1994
GS
1656
1657=cut
1658*/
1659
63f97190 1660void
aad570aa 1661Perl_sv_setnv(pTHX_ register SV *const sv, const NV num)
79072805 1662{
97aff369 1663 dVAR;
7918f24d
NC
1664
1665 PERL_ARGS_ASSERT_SV_SETNV;
1666
bd81e77b
NC
1667 SV_CHECK_THINKFIRST_COW_DROP(sv);
1668 switch (SvTYPE(sv)) {
79072805 1669 case SVt_NULL:
79072805 1670 case SVt_IV:
bd81e77b 1671 sv_upgrade(sv, SVt_NV);
79072805
LW
1672 break;
1673 case SVt_PV:
79072805 1674 case SVt_PVIV:
bd81e77b 1675 sv_upgrade(sv, SVt_PVNV);
79072805 1676 break;
bd4b1eb5 1677
bd4b1eb5 1678 case SVt_PVGV:
6e592b3a
BM
1679 if (!isGV_with_GP(sv))
1680 break;
bd81e77b
NC
1681 case SVt_PVAV:
1682 case SVt_PVHV:
79072805 1683 case SVt_PVCV:
bd81e77b
NC
1684 case SVt_PVFM:
1685 case SVt_PVIO:
1686 Perl_croak(aTHX_ "Can't coerce %s to number in %s", sv_reftype(sv,0),
94bbb3f4 1687 OP_DESC(PL_op));
42d0e0b7 1688 default: NOOP;
2068cd4d 1689 }
bd81e77b
NC
1690 SvNV_set(sv, num);
1691 (void)SvNOK_only(sv); /* validate number */
1692 SvTAINT(sv);
79072805
LW
1693}
1694
645c22ef 1695/*
bd81e77b 1696=for apidoc sv_setnv_mg
645c22ef 1697
bd81e77b 1698Like C<sv_setnv>, but also handles 'set' magic.
645c22ef
DM
1699
1700=cut
1701*/
1702
bd81e77b 1703void
aad570aa 1704Perl_sv_setnv_mg(pTHX_ register SV *const sv, const NV num)
79072805 1705{
7918f24d
NC
1706 PERL_ARGS_ASSERT_SV_SETNV_MG;
1707
bd81e77b
NC
1708 sv_setnv(sv,num);
1709 SvSETMAGIC(sv);
79072805
LW
1710}
1711
bd81e77b
NC
1712/* Print an "isn't numeric" warning, using a cleaned-up,
1713 * printable version of the offending string
1714 */
954c1994 1715
bd81e77b 1716STATIC void
aad570aa 1717S_not_a_number(pTHX_ SV *const sv)
79072805 1718{
97aff369 1719 dVAR;
bd81e77b
NC
1720 SV *dsv;
1721 char tmpbuf[64];
1722 const char *pv;
94463019 1723
7918f24d
NC
1724 PERL_ARGS_ASSERT_NOT_A_NUMBER;
1725
94463019 1726 if (DO_UTF8(sv)) {
84bafc02 1727 dsv = newSVpvs_flags("", SVs_TEMP);
94463019
JH
1728 pv = sv_uni_display(dsv, sv, 10, 0);
1729 } else {
1730 char *d = tmpbuf;
551405c4 1731 const char * const limit = tmpbuf + sizeof(tmpbuf) - 8;
94463019
JH
1732 /* each *s can expand to 4 chars + "...\0",
1733 i.e. need room for 8 chars */
ecdeb87c 1734
00b6aa41
AL
1735 const char *s = SvPVX_const(sv);
1736 const char * const end = s + SvCUR(sv);
1737 for ( ; s < end && d < limit; s++ ) {
94463019
JH
1738 int ch = *s & 0xFF;
1739 if (ch & 128 && !isPRINT_LC(ch)) {
1740 *d++ = 'M';
1741 *d++ = '-';
1742 ch &= 127;
1743 }
1744 if (ch == '\n') {
1745 *d++ = '\\';
1746 *d++ = 'n';
1747 }
1748 else if (ch == '\r') {
1749 *d++ = '\\';
1750 *d++ = 'r';
1751 }
1752 else if (ch == '\f') {
1753 *d++ = '\\';
1754 *d++ = 'f';
1755 }
1756 else if (ch == '\\') {
1757 *d++ = '\\';
1758 *d++ = '\\';
1759 }
1760 else if (ch == '\0') {
1761 *d++ = '\\';
1762 *d++ = '0';
1763 }
1764 else if (isPRINT_LC(ch))
1765 *d++ = ch;
1766 else {
1767 *d++ = '^';
1768 *d++ = toCTRL(ch);
1769 }
1770 }
1771 if (s < end) {
1772 *d++ = '.';
1773 *d++ = '.';
1774 *d++ = '.';
1775 }
1776 *d = '\0';
1777 pv = tmpbuf;
a0d0e21e 1778 }
a0d0e21e 1779
533c011a 1780 if (PL_op)
9014280d 1781 Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
94463019
JH
1782 "Argument \"%s\" isn't numeric in %s", pv,
1783 OP_DESC(PL_op));
a0d0e21e 1784 else
9014280d 1785 Perl_warner(aTHX_ packWARN(WARN_NUMERIC),
94463019 1786 "Argument \"%s\" isn't numeric", pv);
a0d0e21e
LW
1787}
1788
c2988b20
NC
1789/*
1790=for apidoc looks_like_number
1791
645c22ef
DM
1792Test if the content of an SV looks like a number (or is a number).
1793C<Inf> and C<Infinity> are treated as numbers (so will not issue a
1794non-numeric warning), even if your atof() doesn't grok them.
c2988b20
NC
1795
1796=cut
1797*/
1798
1799I32
aad570aa 1800Perl_looks_like_number(pTHX_ SV *const sv)
c2988b20 1801{
a3b680e6 1802 register const char *sbegin;
c2988b20
NC
1803 STRLEN len;
1804
7918f24d
NC
1805 PERL_ARGS_ASSERT_LOOKS_LIKE_NUMBER;
1806
c2988b20 1807 if (SvPOK(sv)) {
3f7c398e 1808 sbegin = SvPVX_const(sv);
c2988b20
NC
1809 len = SvCUR(sv);
1810 }
1811 else if (SvPOKp(sv))
83003860 1812 sbegin = SvPV_const(sv, len);
c2988b20 1813 else
e0ab1c0e 1814 return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
c2988b20
NC
1815 return grok_number(sbegin, len, NULL);
1816}
25da4f38 1817
19f6321d
NC
1818STATIC bool
1819S_glob_2number(pTHX_ GV * const gv)
180488f8
NC
1820{
1821 const U32 wasfake = SvFLAGS(gv) & SVf_FAKE;
1822 SV *const buffer = sv_newmortal();
1823
7918f24d
NC
1824 PERL_ARGS_ASSERT_GLOB_2NUMBER;
1825
180488f8
NC
1826 /* FAKE globs can get coerced, so need to turn this off temporarily if it
1827 is on. */
1828 SvFAKE_off(gv);
1829 gv_efullname3(buffer, gv, "*");
1830 SvFLAGS(gv) |= wasfake;
1831
675c862f
AL
1832 /* We know that all GVs stringify to something that is not-a-number,
1833 so no need to test that. */
1834 if (ckWARN(WARN_NUMERIC))
1835 not_a_number(buffer);
1836 /* We just want something true to return, so that S_sv_2iuv_common
1837 can tail call us and return true. */
19f6321d 1838 return TRUE;
675c862f
AL
1839}
1840
25da4f38
IZ
1841/* Actually, ISO C leaves conversion of UV to IV undefined, but
1842 until proven guilty, assume that things are not that bad... */
1843
645c22ef
DM
1844/*
1845 NV_PRESERVES_UV:
1846
1847 As 64 bit platforms often have an NV that doesn't preserve all bits of
28e5dec8
JH
1848 an IV (an assumption perl has been based on to date) it becomes necessary
1849 to remove the assumption that the NV always carries enough precision to
1850 recreate the IV whenever needed, and that the NV is the canonical form.
1851 Instead, IV/UV and NV need to be given equal rights. So as to not lose
645c22ef 1852 precision as a side effect of conversion (which would lead to insanity
28e5dec8
JH
1853 and the dragon(s) in t/op/numconvert.t getting very angry) the intent is
1854 1) to distinguish between IV/UV/NV slots that have cached a valid
1855 conversion where precision was lost and IV/UV/NV slots that have a
1856 valid conversion which has lost no precision
645c22ef 1857 2) to ensure that if a numeric conversion to one form is requested that
28e5dec8
JH
1858 would lose precision, the precise conversion (or differently
1859 imprecise conversion) is also performed and cached, to prevent
1860 requests for different numeric formats on the same SV causing
1861 lossy conversion chains. (lossless conversion chains are perfectly
1862 acceptable (still))
1863
1864
1865 flags are used:
1866 SvIOKp is true if the IV slot contains a valid value
1867 SvIOK is true only if the IV value is accurate (UV if SvIOK_UV true)
1868 SvNOKp is true if the NV slot contains a valid value
1869 SvNOK is true only if the NV value is accurate
1870
1871 so
645c22ef 1872 while converting from PV to NV, check to see if converting that NV to an
28e5dec8
JH
1873 IV(or UV) would lose accuracy over a direct conversion from PV to
1874 IV(or UV). If it would, cache both conversions, return NV, but mark
1875 SV as IOK NOKp (ie not NOK).
1876
645c22ef 1877 While converting from PV to IV, check to see if converting that IV to an
28e5dec8
JH
1878 NV would lose accuracy over a direct conversion from PV to NV. If it
1879 would, cache both conversions, flag similarly.
1880
1881 Before, the SV value "3.2" could become NV=3.2 IV=3 NOK, IOK quite
1882 correctly because if IV & NV were set NV *always* overruled.
645c22ef
DM
1883 Now, "3.2" will become NV=3.2 IV=3 NOK, IOKp, because the flag's meaning
1884 changes - now IV and NV together means that the two are interchangeable:
28e5dec8 1885 SvIVX == (IV) SvNVX && SvNVX == (NV) SvIVX;
d460ef45 1886
645c22ef
DM
1887 The benefit of this is that operations such as pp_add know that if
1888 SvIOK is true for both left and right operands, then integer addition
1889 can be used instead of floating point (for cases where the result won't
1890 overflow). Before, floating point was always used, which could lead to
28e5dec8
JH
1891 loss of precision compared with integer addition.
1892
1893 * making IV and NV equal status should make maths accurate on 64 bit
1894 platforms
1895 * may speed up maths somewhat if pp_add and friends start to use
645c22ef 1896 integers when possible instead of fp. (Hopefully the overhead in
28e5dec8
JH
1897 looking for SvIOK and checking for overflow will not outweigh the
1898 fp to integer speedup)
1899 * will slow down integer operations (callers of SvIV) on "inaccurate"
1900 values, as the change from SvIOK to SvIOKp will cause a call into
1901 sv_2iv each time rather than a macro access direct to the IV slot
1902 * should speed up number->string conversion on integers as IV is
645c22ef 1903 favoured when IV and NV are equally accurate
28e5dec8
JH
1904
1905 ####################################################################
645c22ef
DM
1906 You had better be using SvIOK_notUV if you want an IV for arithmetic:
1907 SvIOK is true if (IV or UV), so you might be getting (IV)SvUV.
1908 On the other hand, SvUOK is true iff UV.
28e5dec8
JH
1909 ####################################################################
1910
645c22ef 1911 Your mileage will vary depending your CPU's relative fp to integer
28e5dec8
JH
1912 performance ratio.
1913*/
1914
1915#ifndef NV_PRESERVES_UV
645c22ef
DM
1916# define IS_NUMBER_UNDERFLOW_IV 1
1917# define IS_NUMBER_UNDERFLOW_UV 2
1918# define IS_NUMBER_IV_AND_UV 2
1919# define IS_NUMBER_OVERFLOW_IV 4
1920# define IS_NUMBER_OVERFLOW_UV 5
1921
1922/* sv_2iuv_non_preserve(): private routine for use by sv_2iv() and sv_2uv() */
28e5dec8
JH
1923
1924/* For sv_2nv these three cases are "SvNOK and don't bother casting" */
1925STATIC int
5de3775c 1926S_sv_2iuv_non_preserve(pTHX_ register SV *const sv
47031da6
NC
1927# ifdef DEBUGGING
1928 , I32 numtype
1929# endif
1930 )
28e5dec8 1931{
97aff369 1932 dVAR;
7918f24d
NC
1933
1934 PERL_ARGS_ASSERT_SV_2IUV_NON_PRESERVE;
1935
3f7c398e 1936 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
1937 if (SvNVX(sv) < (NV)IV_MIN) {
1938 (void)SvIOKp_on(sv);
1939 (void)SvNOK_on(sv);
45977657 1940 SvIV_set(sv, IV_MIN);
28e5dec8
JH
1941 return IS_NUMBER_UNDERFLOW_IV;
1942 }
1943 if (SvNVX(sv) > (NV)UV_MAX) {
1944 (void)SvIOKp_on(sv);
1945 (void)SvNOK_on(sv);
1946 SvIsUV_on(sv);
607fa7f2 1947 SvUV_set(sv, UV_MAX);
28e5dec8
JH
1948 return IS_NUMBER_OVERFLOW_UV;
1949 }
c2988b20
NC
1950 (void)SvIOKp_on(sv);
1951 (void)SvNOK_on(sv);
1952 /* Can't use strtol etc to convert this string. (See truth table in
1953 sv_2iv */
1954 if (SvNVX(sv) <= (UV)IV_MAX) {
45977657 1955 SvIV_set(sv, I_V(SvNVX(sv)));
c2988b20
NC
1956 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
1957 SvIOK_on(sv); /* Integer is precise. NOK, IOK */
1958 } else {
1959 /* Integer is imprecise. NOK, IOKp */
1960 }
1961 return SvNVX(sv) < 0 ? IS_NUMBER_UNDERFLOW_UV : IS_NUMBER_IV_AND_UV;
1962 }
1963 SvIsUV_on(sv);
607fa7f2 1964 SvUV_set(sv, U_V(SvNVX(sv)));
c2988b20
NC
1965 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
1966 if (SvUVX(sv) == UV_MAX) {
1967 /* As we know that NVs don't preserve UVs, UV_MAX cannot
1968 possibly be preserved by NV. Hence, it must be overflow.
1969 NOK, IOKp */
1970 return IS_NUMBER_OVERFLOW_UV;
1971 }
1972 SvIOK_on(sv); /* Integer is precise. NOK, UOK */
1973 } else {
1974 /* Integer is imprecise. NOK, IOKp */
28e5dec8 1975 }
c2988b20 1976 return IS_NUMBER_OVERFLOW_IV;
28e5dec8 1977}
645c22ef
DM
1978#endif /* !NV_PRESERVES_UV*/
1979
af359546 1980STATIC bool
7918f24d
NC
1981S_sv_2iuv_common(pTHX_ SV *const sv)
1982{
97aff369 1983 dVAR;
7918f24d
NC
1984
1985 PERL_ARGS_ASSERT_SV_2IUV_COMMON;
1986
af359546 1987 if (SvNOKp(sv)) {
28e5dec8
JH
1988 /* erm. not sure. *should* never get NOKp (without NOK) from sv_2nv
1989 * without also getting a cached IV/UV from it at the same time
1990 * (ie PV->NV conversion should detect loss of accuracy and cache
af359546
NC
1991 * IV or UV at same time to avoid this. */
1992 /* IV-over-UV optimisation - choose to cache IV if possible */
25da4f38
IZ
1993
1994 if (SvTYPE(sv) == SVt_NV)
1995 sv_upgrade(sv, SVt_PVNV);
1996
28e5dec8
JH
1997 (void)SvIOKp_on(sv); /* Must do this first, to clear any SvOOK */
1998 /* < not <= as for NV doesn't preserve UV, ((NV)IV_MAX+1) will almost
1999 certainly cast into the IV range at IV_MAX, whereas the correct
2000 answer is the UV IV_MAX +1. Hence < ensures that dodgy boundary
2001 cases go to UV */
cab190d4
JD
2002#if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
2003 if (Perl_isnan(SvNVX(sv))) {
2004 SvUV_set(sv, 0);
2005 SvIsUV_on(sv);
fdbe6d7c 2006 return FALSE;
cab190d4 2007 }
cab190d4 2008#endif
28e5dec8 2009 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
45977657 2010 SvIV_set(sv, I_V(SvNVX(sv)));
28e5dec8
JH
2011 if (SvNVX(sv) == (NV) SvIVX(sv)
2012#ifndef NV_PRESERVES_UV
2013 && (((UV)1 << NV_PRESERVES_UV_BITS) >
2014 (UV)(SvIVX(sv) > 0 ? SvIVX(sv) : -SvIVX(sv)))
2015 /* Don't flag it as "accurately an integer" if the number
2016 came from a (by definition imprecise) NV operation, and
2017 we're outside the range of NV integer precision */
2018#endif
2019 ) {
a43d94f2
NC
2020 if (SvNOK(sv))
2021 SvIOK_on(sv); /* Can this go wrong with rounding? NWC */
2022 else {
2023 /* scalar has trailing garbage, eg "42a" */
2024 }
28e5dec8 2025 DEBUG_c(PerlIO_printf(Perl_debug_log,
7234c960 2026 "0x%"UVxf" iv(%"NVgf" => %"IVdf") (precise)\n",
28e5dec8
JH
2027 PTR2UV(sv),
2028 SvNVX(sv),
2029 SvIVX(sv)));
2030
2031 } else {
2032 /* IV not precise. No need to convert from PV, as NV
2033 conversion would already have cached IV if it detected
2034 that PV->IV would be better than PV->NV->IV
2035 flags already correct - don't set public IOK. */
2036 DEBUG_c(PerlIO_printf(Perl_debug_log,
7234c960 2037 "0x%"UVxf" iv(%"NVgf" => %"IVdf") (imprecise)\n",
28e5dec8
JH
2038 PTR2UV(sv),
2039 SvNVX(sv),
2040 SvIVX(sv)));
2041 }
2042 /* Can the above go wrong if SvIVX == IV_MIN and SvNVX < IV_MIN,
2043 but the cast (NV)IV_MIN rounds to a the value less (more
2044 negative) than IV_MIN which happens to be equal to SvNVX ??
2045 Analogous to 0xFFFFFFFFFFFFFFFF rounding up to NV (2**64) and
2046 NV rounding back to 0xFFFFFFFFFFFFFFFF, so UVX == UV(NVX) and
2047 (NV)UVX == NVX are both true, but the values differ. :-(
2048 Hopefully for 2s complement IV_MIN is something like
2049 0x8000000000000000 which will be exact. NWC */
d460ef45 2050 }
25da4f38 2051 else {
607fa7f2 2052 SvUV_set(sv, U_V(SvNVX(sv)));
28e5dec8
JH
2053 if (
2054 (SvNVX(sv) == (NV) SvUVX(sv))
2055#ifndef NV_PRESERVES_UV
2056 /* Make sure it's not 0xFFFFFFFFFFFFFFFF */
2057 /*&& (SvUVX(sv) != UV_MAX) irrelevant with code below */
2058 && (((UV)1 << NV_PRESERVES_UV_BITS) > SvUVX(sv))
2059 /* Don't flag it as "accurately an integer" if the number
2060 came from a (by definition imprecise) NV operation, and
2061 we're outside the range of NV integer precision */
2062#endif
a43d94f2 2063 && SvNOK(sv)
28e5dec8
JH
2064 )
2065 SvIOK_on(sv);
25da4f38 2066 SvIsUV_on(sv);
1c846c1f 2067 DEBUG_c(PerlIO_printf(Perl_debug_log,
57def98f 2068 "0x%"UVxf" 2iv(%"UVuf" => %"IVdf") (as unsigned)\n",
56431972 2069 PTR2UV(sv),
57def98f
JH
2070 SvUVX(sv),
2071 SvUVX(sv)));
25da4f38 2072 }
748a9306
LW
2073 }
2074 else if (SvPOKp(sv) && SvLEN(sv)) {
c2988b20 2075 UV value;
504618e9 2076 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
af359546 2077 /* We want to avoid a possible problem when we cache an IV/ a UV which
25da4f38 2078 may be later translated to an NV, and the resulting NV is not
c2988b20
NC
2079 the same as the direct translation of the initial string
2080 (eg 123.456 can shortcut to the IV 123 with atol(), but we must
2081 be careful to ensure that the value with the .456 is around if the
2082 NV value is requested in the future).
1c846c1f 2083
af359546 2084 This means that if we cache such an IV/a UV, we need to cache the
25da4f38 2085 NV as well. Moreover, we trade speed for space, and do not
28e5dec8 2086 cache the NV if we are sure it's not needed.
25da4f38 2087 */
16b7a9a4 2088
c2988b20
NC
2089 /* SVt_PVNV is one higher than SVt_PVIV, hence this order */
2090 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2091 == IS_NUMBER_IN_UV) {
5e045b90 2092 /* It's definitely an integer, only upgrade to PVIV */
28e5dec8
JH
2093 if (SvTYPE(sv) < SVt_PVIV)
2094 sv_upgrade(sv, SVt_PVIV);
f7bbb42a 2095 (void)SvIOK_on(sv);
c2988b20
NC
2096 } else if (SvTYPE(sv) < SVt_PVNV)
2097 sv_upgrade(sv, SVt_PVNV);
28e5dec8 2098
f2524eef 2099 /* If NVs preserve UVs then we only use the UV value if we know that
c2988b20
NC
2100 we aren't going to call atof() below. If NVs don't preserve UVs
2101 then the value returned may have more precision than atof() will
2102 return, even though value isn't perfectly accurate. */
2103 if ((numtype & (IS_NUMBER_IN_UV
2104#ifdef NV_PRESERVES_UV
2105 | IS_NUMBER_NOT_INT
2106#endif
2107 )) == IS_NUMBER_IN_UV) {
2108 /* This won't turn off the public IOK flag if it was set above */
2109 (void)SvIOKp_on(sv);
2110
2111 if (!(numtype & IS_NUMBER_NEG)) {
2112 /* positive */;
2113 if (value <= (UV)IV_MAX) {
45977657 2114 SvIV_set(sv, (IV)value);
c2988b20 2115 } else {
af359546 2116 /* it didn't overflow, and it was positive. */
607fa7f2 2117 SvUV_set(sv, value);
c2988b20
NC
2118 SvIsUV_on(sv);
2119 }
2120 } else {
2121 /* 2s complement assumption */
2122 if (value <= (UV)IV_MIN) {
45977657 2123 SvIV_set(sv, -(IV)value);
c2988b20
NC
2124 } else {
2125 /* Too negative for an IV. This is a double upgrade, but
d1be9408 2126 I'm assuming it will be rare. */
c2988b20
NC
2127 if (SvTYPE(sv) < SVt_PVNV)
2128 sv_upgrade(sv, SVt_PVNV);
2129 SvNOK_on(sv);
2130 SvIOK_off(sv);
2131 SvIOKp_on(sv);
9d6ce603 2132 SvNV_set(sv, -(NV)value);
45977657 2133 SvIV_set(sv, IV_MIN);
c2988b20
NC
2134 }
2135 }
2136 }
2137 /* For !NV_PRESERVES_UV and IS_NUMBER_IN_UV and IS_NUMBER_NOT_INT we
2138 will be in the previous block to set the IV slot, and the next
2139 block to set the NV slot. So no else here. */
2140
2141 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2142 != IS_NUMBER_IN_UV) {
2143 /* It wasn't an (integer that doesn't overflow the UV). */
3f7c398e 2144 SvNV_set(sv, Atof(SvPVX_const(sv)));
28e5dec8 2145
c2988b20
NC
2146 if (! numtype && ckWARN(WARN_NUMERIC))
2147 not_a_number(sv);
28e5dec8 2148
65202027 2149#if defined(USE_LONG_DOUBLE)
c2988b20
NC
2150 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%" PERL_PRIgldbl ")\n",
2151 PTR2UV(sv), SvNVX(sv)));
65202027 2152#else
1779d84d 2153 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"NVgf")\n",
c2988b20 2154 PTR2UV(sv), SvNVX(sv)));
65202027 2155#endif
28e5dec8 2156
28e5dec8 2157#ifdef NV_PRESERVES_UV
af359546
NC
2158 (void)SvIOKp_on(sv);
2159 (void)SvNOK_on(sv);
2160 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2161 SvIV_set(sv, I_V(SvNVX(sv)));
2162 if ((NV)(SvIVX(sv)) == SvNVX(sv)) {
2163 SvIOK_on(sv);
2164 } else {
6f207bd3 2165 NOOP; /* Integer is imprecise. NOK, IOKp */
af359546
NC
2166 }
2167 /* UV will not work better than IV */
2168 } else {
2169 if (SvNVX(sv) > (NV)UV_MAX) {
2170 SvIsUV_on(sv);
2171 /* Integer is inaccurate. NOK, IOKp, is UV */
2172 SvUV_set(sv, UV_MAX);
af359546
NC
2173 } else {
2174 SvUV_set(sv, U_V(SvNVX(sv)));
2175 /* 0xFFFFFFFFFFFFFFFF not an issue in here, NVs
2176 NV preservse UV so can do correct comparison. */
2177 if ((NV)(SvUVX(sv)) == SvNVX(sv)) {
2178 SvIOK_on(sv);
af359546 2179 } else {
6f207bd3 2180 NOOP; /* Integer is imprecise. NOK, IOKp, is UV */
af359546
NC
2181 }
2182 }
4b0c9573 2183 SvIsUV_on(sv);
af359546 2184 }
28e5dec8 2185#else /* NV_PRESERVES_UV */
c2988b20
NC
2186 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2187 == (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT)) {
af359546 2188 /* The IV/UV slot will have been set from value returned by
c2988b20
NC
2189 grok_number above. The NV slot has just been set using
2190 Atof. */
560b0c46 2191 SvNOK_on(sv);
c2988b20
NC
2192 assert (SvIOKp(sv));
2193 } else {
2194 if (((UV)1 << NV_PRESERVES_UV_BITS) >
2195 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
2196 /* Small enough to preserve all bits. */
2197 (void)SvIOKp_on(sv);
2198 SvNOK_on(sv);
45977657 2199 SvIV_set(sv, I_V(SvNVX(sv)));
c2988b20
NC
2200 if ((NV)(SvIVX(sv)) == SvNVX(sv))
2201 SvIOK_on(sv);
2202 /* Assumption: first non-preserved integer is < IV_MAX,
2203 this NV is in the preserved range, therefore: */
2204 if (!(U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))
2205 < (UV)IV_MAX)) {
32fdb065 2206 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
2207 }
2208 } else {
2209 /* IN_UV NOT_INT
2210 0 0 already failed to read UV.
2211 0 1 already failed to read UV.
2212 1 0 you won't get here in this case. IV/UV
2213 slot set, public IOK, Atof() unneeded.
2214 1 1 already read UV.
2215 so there's no point in sv_2iuv_non_preserve() attempting
2216 to use atol, strtol, strtoul etc. */
47031da6 2217# ifdef DEBUGGING
40a17c4c 2218 sv_2iuv_non_preserve (sv, numtype);
47031da6
NC
2219# else
2220 sv_2iuv_non_preserve (sv);
2221# endif
c2988b20
NC
2222 }
2223 }
28e5dec8 2224#endif /* NV_PRESERVES_UV */
a43d94f2
NC
2225 /* It might be more code efficient to go through the entire logic above
2226 and conditionally set with SvIOKp_on() rather than SvIOK(), but it
2227 gets complex and potentially buggy, so more programmer efficient
2228 to do it this way, by turning off the public flags: */
2229 if (!numtype)
2230 SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
25da4f38 2231 }
af359546
NC
2232 }
2233 else {
675c862f 2234 if (isGV_with_GP(sv))
159b6efe 2235 return glob_2number(MUTABLE_GV(sv));
180488f8 2236
af359546
NC
2237 if (!(SvFLAGS(sv) & SVs_PADTMP)) {
2238 if (!PL_localizing && ckWARN(WARN_UNINITIALIZED))
2239 report_uninit(sv);
2240 }
25da4f38
IZ
2241 if (SvTYPE(sv) < SVt_IV)
2242 /* Typically the caller expects that sv_any is not NULL now. */
2243 sv_upgrade(sv, SVt_IV);
af359546
NC
2244 /* Return 0 from the caller. */
2245 return TRUE;
2246 }
2247 return FALSE;
2248}
2249
2250/*
2251=for apidoc sv_2iv_flags
2252
2253Return the integer value of an SV, doing any necessary string
2254conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2255Normally used via the C<SvIV(sv)> and C<SvIVx(sv)> macros.
2256
2257=cut
2258*/
2259
2260IV
5de3775c 2261Perl_sv_2iv_flags(pTHX_ register SV *const sv, const I32 flags)
af359546 2262{
97aff369 2263 dVAR;
af359546 2264 if (!sv)
a0d0e21e 2265 return 0;
cecf5685
NC
2266 if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2267 /* FBMs use the same flag bit as SVf_IVisUV, so must let them
50caf62e
NC
2268 cache IVs just in case. In practice it seems that they never
2269 actually anywhere accessible by user Perl code, let alone get used
2270 in anything other than a string context. */
af359546
NC
2271 if (flags & SV_GMAGIC)
2272 mg_get(sv);
2273 if (SvIOKp(sv))
2274 return SvIVX(sv);
2275 if (SvNOKp(sv)) {
2276 return I_V(SvNVX(sv));
2277 }
71c558c3
NC
2278 if (SvPOKp(sv) && SvLEN(sv)) {
2279 UV value;
2280 const int numtype
2281 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2282
2283 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2284 == IS_NUMBER_IN_UV) {
2285 /* It's definitely an integer */
2286 if (numtype & IS_NUMBER_NEG) {
2287 if (value < (UV)IV_MIN)
2288 return -(IV)value;
2289 } else {
2290 if (value < (UV)IV_MAX)
2291 return (IV)value;
2292 }
2293 }
2294 if (!numtype) {
2295 if (ckWARN(WARN_NUMERIC))
2296 not_a_number(sv);
2297 }
2298 return I_V(Atof(SvPVX_const(sv)));
2299 }
1c7ff15e
NC
2300 if (SvROK(sv)) {
2301 goto return_rok;
af359546 2302 }
1c7ff15e
NC
2303 assert(SvTYPE(sv) >= SVt_PVMG);
2304 /* This falls through to the report_uninit inside S_sv_2iuv_common. */
4cb1ec55 2305 } else if (SvTHINKFIRST(sv)) {
af359546 2306 if (SvROK(sv)) {
1c7ff15e 2307 return_rok:
af359546 2308 if (SvAMAGIC(sv)) {
aee036bb
DM
2309 SV * tmpstr;
2310 if (flags & SV_SKIP_OVERLOAD)
2311 return 0;
2312 tmpstr=AMG_CALLun(sv,numer);
af359546
NC
2313 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2314 return SvIV(tmpstr);
2315 }
2316 }
2317 return PTR2IV(SvRV(sv));
2318 }
2319 if (SvIsCOW(sv)) {
2320 sv_force_normal_flags(sv, 0);
2321 }
2322 if (SvREADONLY(sv) && !SvOK(sv)) {
2323 if (ckWARN(WARN_UNINITIALIZED))
2324 report_uninit(sv);
2325 return 0;
2326 }
2327 }
2328 if (!SvIOKp(sv)) {
2329 if (S_sv_2iuv_common(aTHX_ sv))
2330 return 0;
79072805 2331 }
1d7c1841
GS
2332 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2iv(%"IVdf")\n",
2333 PTR2UV(sv),SvIVX(sv)));
25da4f38 2334 return SvIsUV(sv) ? (IV)SvUVX(sv) : SvIVX(sv);
79072805
LW
2335}
2336
645c22ef 2337/*
891f9566 2338=for apidoc sv_2uv_flags
645c22ef
DM
2339
2340Return the unsigned integer value of an SV, doing any necessary string
891f9566
YST
2341conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2342Normally used via the C<SvUV(sv)> and C<SvUVx(sv)> macros.
645c22ef
DM
2343
2344=cut
2345*/
2346
ff68c719 2347UV
5de3775c 2348Perl_sv_2uv_flags(pTHX_ register SV *const sv, const I32 flags)
ff68c719 2349{
97aff369 2350 dVAR;
ff68c719 2351 if (!sv)
2352 return 0;
cecf5685
NC
2353 if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2354 /* FBMs use the same flag bit as SVf_IVisUV, so must let them
50caf62e 2355 cache IVs just in case. */
891f9566
YST
2356 if (flags & SV_GMAGIC)
2357 mg_get(sv);
ff68c719 2358 if (SvIOKp(sv))
2359 return SvUVX(sv);
2360 if (SvNOKp(sv))
2361 return U_V(SvNVX(sv));
71c558c3
NC
2362 if (SvPOKp(sv) && SvLEN(sv)) {
2363 UV value;
2364 const int numtype
2365 = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
2366
2367 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2368 == IS_NUMBER_IN_UV) {
2369 /* It's definitely an integer */
2370 if (!(numtype & IS_NUMBER_NEG))
2371 return value;
2372 }
2373 if (!numtype) {
2374 if (ckWARN(WARN_NUMERIC))
2375 not_a_number(sv);
2376 }
2377 return U_V(Atof(SvPVX_const(sv)));
2378 }
1c7ff15e
NC
2379 if (SvROK(sv)) {
2380 goto return_rok;
3fe9a6f1 2381 }
1c7ff15e
NC
2382 assert(SvTYPE(sv) >= SVt_PVMG);
2383 /* This falls through to the report_uninit inside S_sv_2iuv_common. */
4cb1ec55 2384 } else if (SvTHINKFIRST(sv)) {
ff68c719 2385 if (SvROK(sv)) {
1c7ff15e 2386 return_rok:
deb46114 2387 if (SvAMAGIC(sv)) {
aee036bb
DM
2388 SV *tmpstr;
2389 if (flags & SV_SKIP_OVERLOAD)
2390 return 0;
2391 tmpstr = AMG_CALLun(sv,numer);
deb46114
NC
2392 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2393 return SvUV(tmpstr);
2394 }
2395 }
2396 return PTR2UV(SvRV(sv));
ff68c719 2397 }
765f542d
NC
2398 if (SvIsCOW(sv)) {
2399 sv_force_normal_flags(sv, 0);
8a818333 2400 }
0336b60e 2401 if (SvREADONLY(sv) && !SvOK(sv)) {
0336b60e 2402 if (ckWARN(WARN_UNINITIALIZED))
29489e7c 2403 report_uninit(sv);
ff68c719 2404 return 0;
2405 }
2406 }
af359546
NC
2407 if (!SvIOKp(sv)) {
2408 if (S_sv_2iuv_common(aTHX_ sv))
2409 return 0;
ff68c719 2410 }
25da4f38 2411
1d7c1841
GS
2412 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2uv(%"UVuf")\n",
2413 PTR2UV(sv),SvUVX(sv)));
25da4f38 2414 return SvIsUV(sv) ? SvUVX(sv) : (UV)SvIVX(sv);
ff68c719 2415}
2416
645c22ef 2417/*
196007d1 2418=for apidoc sv_2nv_flags
645c22ef
DM
2419
2420Return the num value of an SV, doing any necessary string or integer
39d5de13
DM
2421conversion. If flags includes SV_GMAGIC, does an mg_get() first.
2422Normally used via the C<SvNV(sv)> and C<SvNVx(sv)> macros.
645c22ef
DM
2423
2424=cut
2425*/
2426
65202027 2427NV
39d5de13 2428Perl_sv_2nv_flags(pTHX_ register SV *const sv, const I32 flags)
79072805 2429{
97aff369 2430 dVAR;
79072805
LW
2431 if (!sv)
2432 return 0.0;
cecf5685
NC
2433 if (SvGMAGICAL(sv) || (SvTYPE(sv) == SVt_PVGV && SvVALID(sv))) {
2434 /* FBMs use the same flag bit as SVf_IVisUV, so must let them
50caf62e 2435 cache IVs just in case. */
39d5de13
DM
2436 if (flags & SV_GMAGIC)
2437 mg_get(sv);
463ee0b2
LW
2438 if (SvNOKp(sv))
2439 return SvNVX(sv);
0aa395f8 2440 if ((SvPOKp(sv) && SvLEN(sv)) && !SvIOKp(sv)) {
041457d9 2441 if (!SvIOKp(sv) && ckWARN(WARN_NUMERIC) &&
504618e9 2442 !grok_number(SvPVX_const(sv), SvCUR(sv), NULL))
a0d0e21e 2443 not_a_number(sv);
3f7c398e 2444 return Atof(SvPVX_const(sv));
a0d0e21e 2445 }
25da4f38 2446 if (SvIOKp(sv)) {
1c846c1f 2447 if (SvIsUV(sv))
65202027 2448 return (NV)SvUVX(sv);
25da4f38 2449 else
65202027 2450 return (NV)SvIVX(sv);
47a72cb8
NC
2451 }
2452 if (SvROK(sv)) {
2453 goto return_rok;
2454 }
2455 assert(SvTYPE(sv) >= SVt_PVMG);
2456 /* This falls through to the report_uninit near the end of the
2457 function. */
2458 } else if (SvTHINKFIRST(sv)) {
a0d0e21e 2459 if (SvROK(sv)) {
47a72cb8 2460 return_rok:
deb46114 2461 if (SvAMAGIC(sv)) {
aee036bb
DM
2462 SV *tmpstr;
2463 if (flags & SV_SKIP_OVERLOAD)
2464 return 0;
2465 tmpstr = AMG_CALLun(sv,numer);
deb46114
NC
2466 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2467 return SvNV(tmpstr);
2468 }
2469 }
2470 return PTR2NV(SvRV(sv));
a0d0e21e 2471 }
765f542d
NC
2472 if (SvIsCOW(sv)) {
2473 sv_force_normal_flags(sv, 0);
8a818333 2474 }
0336b60e 2475 if (SvREADONLY(sv) && !SvOK(sv)) {
599cee73 2476 if (ckWARN(WARN_UNINITIALIZED))
29489e7c 2477 report_uninit(sv);
ed6116ce
LW
2478 return 0.0;
2479 }
79072805
LW
2480 }
2481 if (SvTYPE(sv) < SVt_NV) {
7e25a7e9
NC
2482 /* The logic to use SVt_PVNV if necessary is in sv_upgrade. */
2483 sv_upgrade(sv, SVt_NV);
906f284f 2484#ifdef USE_LONG_DOUBLE
097ee67d 2485 DEBUG_c({
f93f4e46 2486 STORE_NUMERIC_LOCAL_SET_STANDARD();
1d7c1841
GS
2487 PerlIO_printf(Perl_debug_log,
2488 "0x%"UVxf" num(%" PERL_PRIgldbl ")\n",
2489 PTR2UV(sv), SvNVX(sv));
572bbb43
GS
2490 RESTORE_NUMERIC_LOCAL();
2491 });
65202027 2492#else
572bbb43 2493 DEBUG_c({
f93f4e46 2494 STORE_NUMERIC_LOCAL_SET_STANDARD();
1779d84d 2495 PerlIO_printf(Perl_debug_log, "0x%"UVxf" num(%"NVgf")\n",
1d7c1841 2496 PTR2UV(sv), SvNVX(sv));
097ee67d
JH
2497 RESTORE_NUMERIC_LOCAL();
2498 });
572bbb43 2499#endif
79072805
LW
2500 }
2501 else if (SvTYPE(sv) < SVt_PVNV)
2502 sv_upgrade(sv, SVt_PVNV);
59d8ce62
NC
2503 if (SvNOKp(sv)) {
2504 return SvNVX(sv);
61604483 2505 }
59d8ce62 2506 if (SvIOKp(sv)) {
9d6ce603 2507 SvNV_set(sv, SvIsUV(sv) ? (NV)SvUVX(sv) : (NV)SvIVX(sv));
28e5dec8 2508#ifdef NV_PRESERVES_UV
a43d94f2
NC
2509 if (SvIOK(sv))
2510 SvNOK_on(sv);
2511 else
2512 SvNOKp_on(sv);
28e5dec8
JH
2513#else
2514 /* Only set the public NV OK flag if this NV preserves the IV */
2515 /* Check it's not 0xFFFFFFFFFFFFFFFF */
a43d94f2
NC
2516 if (SvIOK(sv) &&
2517 SvIsUV(sv) ? ((SvUVX(sv) != UV_MAX)&&(SvUVX(sv) == U_V(SvNVX(sv))))
28e5dec8
JH
2518 : (SvIVX(sv) == I_V(SvNVX(sv))))
2519 SvNOK_on(sv);
2520 else
2521 SvNOKp_on(sv);
2522#endif
93a17b20 2523 }
748a9306 2524 else if (SvPOKp(sv) && SvLEN(sv)) {
c2988b20 2525 UV value;
3f7c398e 2526 const int numtype = grok_number(SvPVX_const(sv), SvCUR(sv), &value);
041457d9 2527 if (!SvIOKp(sv) && !numtype && ckWARN(WARN_NUMERIC))
a0d0e21e 2528 not_a_number(sv);
28e5dec8 2529#ifdef NV_PRESERVES_UV
c2988b20
NC
2530 if ((numtype & (IS_NUMBER_IN_UV | IS_NUMBER_NOT_INT))
2531 == IS_NUMBER_IN_UV) {
5e045b90 2532 /* It's definitely an integer */
9d6ce603 2533 SvNV_set(sv, (numtype & IS_NUMBER_NEG) ? -(NV)value : (NV)value);
c2988b20 2534 } else
3f7c398e 2535 SvNV_set(sv, Atof(SvPVX_const(sv)));
a43d94f2
NC
2536 if (numtype)
2537 SvNOK_on(sv);
2538 else
2539 SvNOKp_on(sv);
28e5dec8 2540#else
3f7c398e 2541 SvNV_set(sv, Atof(SvPVX_const(sv)));
28e5dec8
JH
2542 /* Only set the public NV OK flag if this NV preserves the value in
2543 the PV at least as well as an IV/UV would.
2544 Not sure how to do this 100% reliably. */
2545 /* if that shift count is out of range then Configure's test is
2546 wonky. We shouldn't be in here with NV_PRESERVES_UV_BITS ==
2547 UV_BITS */
2548 if (((UV)1 << NV_PRESERVES_UV_BITS) >
c2988b20 2549 U_V(SvNVX(sv) > 0 ? SvNVX(sv) : -SvNVX(sv))) {
28e5dec8 2550 SvNOK_on(sv); /* Definitely small enough to preserve all bits */
c2988b20
NC
2551 } else if (!(numtype & IS_NUMBER_IN_UV)) {
2552 /* Can't use strtol etc to convert this string, so don't try.
2553 sv_2iv and sv_2uv will use the NV to convert, not the PV. */
2554 SvNOK_on(sv);
2555 } else {
2556 /* value has been set. It may not be precise. */
2557 if ((numtype & IS_NUMBER_NEG) && (value > (UV)IV_MIN)) {
2558 /* 2s complement assumption for (UV)IV_MIN */
2559 SvNOK_on(sv); /* Integer is too negative. */
2560 } else {
2561 SvNOKp_on(sv);
2562 SvIOKp_on(sv);
6fa402ec 2563
c2988b20 2564 if (numtype & IS_NUMBER_NEG) {
45977657 2565 SvIV_set(sv, -(IV)value);
c2988b20 2566 } else if (value <= (UV)IV_MAX) {
45977657 2567 SvIV_set(sv, (IV)value);
c2988b20 2568 } else {
607fa7f2 2569 SvUV_set(sv, value);
c2988b20
NC
2570 SvIsUV_on(sv);
2571 }
2572
2573 if (numtype & IS_NUMBER_NOT_INT) {
2574 /* I believe that even if the original PV had decimals,
2575 they are lost beyond the limit of the FP precision.
2576 However, neither is canonical, so both only get p
2577 flags. NWC, 2000/11/25 */
2578 /* Both already have p flags, so do nothing */
2579 } else {
66a1b24b 2580 const NV nv = SvNVX(sv);
c2988b20
NC
2581 if (SvNVX(sv) < (NV)IV_MAX + 0.5) {
2582 if (SvIVX(sv) == I_V(nv)) {
2583 SvNOK_on(sv);
c2988b20 2584 } else {
c2988b20
NC
2585 /* It had no "." so it must be integer. */
2586 }
00b6aa41 2587 SvIOK_on(sv);
c2988b20
NC
2588 } else {
2589 /* between IV_MAX and NV(UV_MAX).
2590 Could be slightly > UV_MAX */
6fa402ec 2591
c2988b20
NC
2592 if (numtype & IS_NUMBER_NOT_INT) {
2593 /* UV and NV both imprecise. */
2594 } else {
66a1b24b 2595 const UV nv_as_uv = U_V(nv);
c2988b20
NC
2596
2597 if (value == nv_as_uv && SvUVX(sv) != UV_MAX) {
2598 SvNOK_on(sv);
c2988b20 2599 }
00b6aa41 2600 SvIOK_on(sv);
c2988b20
NC
2601 }
2602 }
2603 }
2604 }
2605 }
a43d94f2
NC
2606 /* It might be more code efficient to go through the entire logic above
2607 and conditionally set with SvNOKp_on() rather than SvNOK(), but it
2608 gets complex and potentially buggy, so more programmer efficient
2609 to do it this way, by turning off the public flags: */
2610 if (!numtype)
2611 SvFLAGS(sv) &= ~(SVf_IOK|SVf_NOK);
28e5dec8 2612#endif /* NV_PRESERVES_UV */
93a17b20 2613 }
79072805 2614 else {
f7877b28 2615 if (isGV_with_GP(sv)) {
159b6efe 2616 glob_2number(MUTABLE_GV(sv));
180488f8
NC
2617 return 0.0;
2618 }
2619
041457d9 2620 if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
29489e7c 2621 report_uninit(sv);
7e25a7e9
NC
2622 assert (SvTYPE(sv) >= SVt_NV);
2623 /* Typically the caller expects that sv_any is not NULL now. */
2624 /* XXX Ilya implies that this is a bug in callers that assume this
2625 and ideally should be fixed. */
a0d0e21e 2626 return 0.0;
79072805 2627 }
572bbb43 2628#if defined(USE_LONG_DOUBLE)
097ee67d 2629 DEBUG_c({
f93f4e46 2630 STORE_NUMERIC_LOCAL_SET_STANDARD();
1d7c1841
GS
2631 PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2nv(%" PERL_PRIgldbl ")\n",
2632 PTR2UV(sv), SvNVX(sv));
572bbb43
GS
2633 RESTORE_NUMERIC_LOCAL();
2634 });
65202027 2635#else
572bbb43 2636 DEBUG_c({
f93f4e46 2637 STORE_NUMERIC_LOCAL_SET_STANDARD();
1779d84d 2638 PerlIO_printf(Perl_debug_log, "0x%"UVxf" 1nv(%"NVgf")\n",
1d7c1841 2639 PTR2UV(sv), SvNVX(sv));
097ee67d
JH
2640 RESTORE_NUMERIC_LOCAL();
2641 });
572bbb43 2642#endif
463ee0b2 2643 return SvNVX(sv);
79072805
LW
2644}
2645
800401ee
JH
2646/*
2647=for apidoc sv_2num
2648
2649Return an SV with the numeric value of the source SV, doing any necessary
a196a5fa
JH
2650reference or overload conversion. You must use the C<SvNUM(sv)> macro to
2651access this function.
800401ee
JH
2652
2653=cut
2654*/
2655
2656SV *
5de3775c 2657Perl_sv_2num(pTHX_ register SV *const sv)
800401ee 2658{
7918f24d
NC
2659 PERL_ARGS_ASSERT_SV_2NUM;
2660
b9ee0594
RGS
2661 if (!SvROK(sv))
2662 return sv;
800401ee
JH
2663 if (SvAMAGIC(sv)) {
2664 SV * const tmpsv = AMG_CALLun(sv,numer);
a02ec77a 2665 TAINT_IF(tmpsv && SvTAINTED(tmpsv));
800401ee
JH
2666 if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
2667 return sv_2num(tmpsv);
2668 }
2669 return sv_2mortal(newSVuv(PTR2UV(SvRV(sv))));
2670}
2671
645c22ef
DM
2672/* uiv_2buf(): private routine for use by sv_2pv_flags(): print an IV or
2673 * UV as a string towards the end of buf, and return pointers to start and
2674 * end of it.
2675 *
2676 * We assume that buf is at least TYPE_CHARS(UV) long.
2677 */
2678
864dbfa3 2679static char *
5de3775c 2680S_uiv_2buf(char *const buf, const IV iv, UV uv, const int is_uv, char **const peob)
25da4f38 2681{
25da4f38 2682 char *ptr = buf + TYPE_CHARS(UV);
823a54a3 2683 char * const ebuf = ptr;
25da4f38 2684 int sign;
25da4f38 2685
7918f24d
NC
2686 PERL_ARGS_ASSERT_UIV_2BUF;
2687
25da4f38
IZ
2688 if (is_uv)
2689 sign = 0;
2690 else if (iv >= 0) {
2691 uv = iv;
2692 sign = 0;
2693 } else {
2694 uv = -iv;
2695 sign = 1;
2696 }
2697 do {
eb160463 2698 *--ptr = '0' + (char)(uv % 10);
25da4f38
IZ
2699 } while (uv /= 10);
2700 if (sign)
2701 *--ptr = '-';
2702 *peob = ebuf;
2703 return ptr;
2704}
2705
645c22ef
DM
2706/*
2707=for apidoc sv_2pv_flags
2708
ff276b08 2709Returns a pointer to the string value of an SV, and sets *lp to its length.
645c22ef
DM
2710If flags includes SV_GMAGIC, does an mg_get() first. Coerces sv to a string
2711if necessary.
2712Normally invoked via the C<SvPV_flags> macro. C<sv_2pv()> and C<sv_2pv_nomg>
2713usually end up here too.
2714
2715=cut
2716*/
2717
8d6d96c1 2718char *
5de3775c 2719Perl_sv_2pv_flags(pTHX_ register SV *const sv, STRLEN *const lp, const I32 flags)
8d6d96c1 2720{
97aff369 2721 dVAR;
79072805 2722 register char *s;
79072805 2723
463ee0b2 2724 if (!sv) {
cdb061a3
NC
2725 if (lp)
2726 *lp = 0;
73d840c0 2727 return (char *)"";
463ee0b2 2728 }
8990e307 2729 if (SvGMAGICAL(sv)) {
8d6d96c1
HS
2730 if (flags & SV_GMAGIC)
2731 mg_get(sv);
463ee0b2 2732 if (SvPOKp(sv)) {
cdb061a3
NC
2733 if (lp)
2734 *lp = SvCUR(sv);
10516c54
NC
2735 if (flags & SV_MUTABLE_RETURN)
2736 return SvPVX_mutable(sv);
4d84ee25
NC
2737 if (flags & SV_CONST_RETURN)
2738 return (char *)SvPVX_const(sv);
463ee0b2
LW
2739 return SvPVX(sv);
2740 }
75dfc8ec
NC
2741 if (SvIOKp(sv) || SvNOKp(sv)) {
2742 char tbuf[64]; /* Must fit sprintf/Gconvert of longest IV/NV */
75dfc8ec
NC
2743 STRLEN len;
2744
2745 if (SvIOKp(sv)) {
e80fed9d 2746 len = SvIsUV(sv)
d9fad198
JH
2747 ? my_snprintf(tbuf, sizeof(tbuf), "%"UVuf, (UV)SvUVX(sv))
2748 : my_snprintf(tbuf, sizeof(tbuf), "%"IVdf, (IV)SvIVX(sv));
75dfc8ec 2749 } else {
e8ada2d0
NC
2750 Gconvert(SvNVX(sv), NV_DIG, 0, tbuf);
2751 len = strlen(tbuf);
75dfc8ec 2752 }
b5b886f0
NC
2753 assert(!SvROK(sv));
2754 {
75dfc8ec
NC
2755 dVAR;
2756
2757#ifdef FIXNEGATIVEZERO
e8ada2d0
NC
2758 if (len == 2 && tbuf[0] == '-' && tbuf[1] == '0') {
2759 tbuf[0] = '0';
2760 tbuf[1] = 0;
75dfc8ec
NC
2761 len = 1;
2762 }
2763#endif
2764 SvUPGRADE(sv, SVt_PV);
2765 if (lp)
2766 *lp = len;
2767 s = SvGROW_mutable(sv, len + 1);
2768 SvCUR_set(sv, len);
2769 SvPOKp_on(sv);
10edeb5d 2770 return (char*)memcpy(s, tbuf, len + 1);
75dfc8ec 2771 }
463ee0b2 2772 }
1c7ff15e
NC
2773 if (SvROK(sv)) {
2774 goto return_rok;
2775 }
2776 assert(SvTYPE(sv) >= SVt_PVMG);
2777 /* This falls through to the report_uninit near the end of the
2778 function. */
2779 } else if (SvTHINKFIRST(sv)) {
ed6116ce 2780 if (SvROK(sv)) {
1c7ff15e 2781 return_rok:
deb46114 2782 if (SvAMAGIC(sv)) {
aee036bb
DM
2783 SV *tmpstr;
2784 if (flags & SV_SKIP_OVERLOAD)
2785 return NULL;
2786 tmpstr = AMG_CALLun(sv,string);
a02ec77a 2787 TAINT_IF(tmpstr && SvTAINTED(tmpstr));
deb46114
NC
2788 if (tmpstr && (!SvROK(tmpstr) || (SvRV(tmpstr) != SvRV(sv)))) {
2789 /* Unwrap this: */
2790 /* char *pv = lp ? SvPV(tmpstr, *lp) : SvPV_nolen(tmpstr);
2791 */
2792
2793 char *pv;
2794 if ((SvFLAGS(tmpstr) & (SVf_POK)) == SVf_POK) {
2795 if (flags & SV_CONST_RETURN) {
2796 pv = (char *) SvPVX_const(tmpstr);
2797 } else {
2798 pv = (flags & SV_MUTABLE_RETURN)
2799 ? SvPVX_mutable(tmpstr) : SvPVX(tmpstr);
2800 }
2801 if (lp)
2802 *lp = SvCUR(tmpstr);
50adf7d2 2803 } else {
deb46114 2804 pv = sv_2pv_flags(tmpstr, lp, flags);
50adf7d2 2805 }
deb46114
NC
2806 if (SvUTF8(tmpstr))
2807 SvUTF8_on(sv);
2808 else
2809 SvUTF8_off(sv);
2810 return pv;
50adf7d2 2811 }
deb46114
NC
2812 }
2813 {
fafee734
NC
2814 STRLEN len;
2815 char *retval;
2816 char *buffer;
d2c6dc5e 2817 SV *const referent = SvRV(sv);
d8eae41e
NC
2818
2819 if (!referent) {
fafee734
NC
2820 len = 7;
2821 retval = buffer = savepvn("NULLREF", len);
5c35adbb 2822 } else if (SvTYPE(referent) == SVt_REGEXP) {
d2c6dc5e 2823 REGEXP * const re = (REGEXP *)MUTABLE_PTR(referent);
67d2d14d
AB
2824 I32 seen_evals = 0;
2825
2826 assert(re);
2827
2828 /* If the regex is UTF-8 we want the containing scalar to
2829 have an UTF-8 flag too */
2830 if (RX_UTF8(re))
2831 SvUTF8_on(sv);
2832 else
2833 SvUTF8_off(sv);
2834
2835 if ((seen_evals = RX_SEEN_EVALS(re)))
2836 PL_reginterp_cnt += seen_evals;
2837
2838 if (lp)
2839 *lp = RX_WRAPLEN(re);
2840
2841 return RX_WRAPPED(re);
d8eae41e
NC
2842 } else {
2843 const char *const typestr = sv_reftype(referent, 0);
fafee734
NC
2844 const STRLEN typelen = strlen(typestr);
2845 UV addr = PTR2UV(referent);
2846 const char *stashname = NULL;
2847 STRLEN stashnamelen = 0; /* hush, gcc */
2848 const char *buffer_end;
d8eae41e 2849
d8eae41e 2850 if (SvOBJECT(referent)) {
fafee734
NC
2851 const HEK *const name = HvNAME_HEK(SvSTASH(referent));
2852
2853 if (name) {
2854 stashname = HEK_KEY(name);
2855 stashnamelen = HEK_LEN(name);
2856
2857 if (HEK_UTF8(name)) {
2858 SvUTF8_on(sv);
2859 } else {
2860 SvUTF8_off(sv);
2861 }
2862 } else {
2863 stashname = "__ANON__";
2864 stashnamelen = 8;
2865 }
2866 len = stashnamelen + 1 /* = */ + typelen + 3 /* (0x */
2867 + 2 * sizeof(UV) + 2 /* )\0 */;
2868 } else {
2869 len = typelen + 3 /* (0x */
2870 + 2 * sizeof(UV) + 2 /* )\0 */;
d8eae41e 2871 }
fafee734
NC
2872
2873 Newx(buffer, len, char);
2874 buffer_end = retval = buffer + len;
2875
2876 /* Working backwards */
2877 *--retval = '\0';
2878 *--retval = ')';
2879 do {
2880 *--retval = PL_hexdigit[addr & 15];
2881 } while (addr >>= 4);
2882 *--retval = 'x';
2883 *--retval = '0';
2884 *--retval = '(';
2885
2886 retval -= typelen;
2887 memcpy(retval, typestr, typelen);
2888
2889 if (stashname) {
2890 *--retval = '=';
2891 retval -= stashnamelen;
2892 memcpy(retval, stashname, stashnamelen);
2893 }
2894 /* retval may not neccesarily have reached the start of the
2895 buffer here. */
2896 assert (retval >= buffer);
2897
2898 len = buffer_end - retval - 1; /* -1 for that \0 */
c080367d 2899 }
042dae7a 2900 if (lp)
fafee734
NC
2901 *lp = len;
2902 SAVEFREEPV(buffer);
2903 return retval;
463ee0b2 2904 }
79072805 2905 }
0336b60e 2906 if (SvREADONLY(sv) && !SvOK(sv)) {
cdb061a3
NC
2907 if (lp)
2908 *lp = 0;
9f621bb0
NC
2909 if (flags & SV_UNDEF_RETURNS_NULL)
2910 return NULL;
2911 if (ckWARN(WARN_UNINITIALIZED))
2912 report_uninit(sv);
73d840c0 2913 return (char *)"";
79072805 2914 }
79072805 2915 }
28e5dec8
JH
2916 if (SvIOK(sv) || ((SvIOKp(sv) && !SvNOKp(sv)))) {
2917 /* I'm assuming that if both IV and NV are equally valid then
2918 converting the IV is going to be more efficient */
e1ec3a88 2919 const U32 isUIOK = SvIsUV(sv);
28e5dec8
JH
2920 char buf[TYPE_CHARS(UV)];
2921 char *ebuf, *ptr;
97a130b8 2922 STRLEN len;
28e5dec8
JH
2923
2924 if (SvTYPE(sv) < SVt_PVIV)
2925 sv_upgrade(sv, SVt_PVIV);
4ea1d550 2926 ptr = uiv_2buf(buf, SvIVX(sv), SvUVX(sv), isUIOK, &ebuf);
97a130b8 2927 len = ebuf - ptr;
5902b6a9 2928 /* inlined from sv_setpvn */
97a130b8
NC
2929 s = SvGROW_mutable(sv, len + 1);
2930 Move(ptr, s, len, char);
2931 s += len;
28e5dec8 2932 *s = '\0';
28e5dec8
JH
2933 }
2934 else if (SvNOKp(sv)) {
4ee39169 2935 dSAVE_ERRNO;
79072805
LW
2936 if (SvTYPE(sv) < SVt_PVNV)
2937 sv_upgrade(sv, SVt_PVNV);
1c846c1f 2938 /* The +20 is pure guesswork. Configure test needed. --jhi */
5902b6a9 2939 s = SvGROW_mutable(sv, NV_DIG + 20);
c81271c3 2940 /* some Xenix systems wipe out errno here */
79072805 2941#ifdef apollo
463ee0b2 2942 if (SvNVX(sv) == 0.0)
d1307786 2943 my_strlcpy(s, "0", SvLEN(sv));
79072805
LW
2944 else
2945#endif /*apollo*/
bbce6d69 2946 {
2d4389e4 2947 Gconvert(SvNVX(sv), NV_DIG, 0, s);
bbce6d69 2948 }
4ee39169 2949 RESTORE_ERRNO;
a0d0e21e 2950#ifdef FIXNEGATIVEZERO
20773dcd
NC
2951 if (*s == '-' && s[1] == '0' && !s[2]) {
2952 s[0] = '0';
2953 s[1] = 0;
2954 }
a0d0e21e 2955#endif
79072805
LW
2956 while (*s) s++;
2957#ifdef hcx
2958 if (s[-1] == '.')
46fc3d4c 2959 *--s = '\0';
79072805
LW
2960#endif
2961 }
79072805 2962 else {
8d1c3e26
NC
2963 if (isGV_with_GP(sv)) {
2964 GV *const gv = MUTABLE_GV(sv);
2965 const U32 wasfake = SvFLAGS(gv) & SVf_FAKE;
2966 SV *const buffer = sv_newmortal();
2967
2968 /* FAKE globs can get coerced, so need to turn this off temporarily
2969 if it is on. */
2970 SvFAKE_off(gv);
2971 gv_efullname3(buffer, gv, "*");
2972 SvFLAGS(gv) |= wasfake;
2973
1809c940
DM
2974 if (SvPOK(buffer)) {
2975 if (lp) {
2976 *lp = SvCUR(buffer);
2977 }
2978 return SvPVX(buffer);
2979 }
2980 else {
2981 if (lp)
2982 *lp = 0;
2983 return (char *)"";
8d1c3e26 2984 }
8d1c3e26 2985 }
180488f8 2986
cdb061a3 2987 if (lp)
00b6aa41 2988 *lp = 0;
9f621bb0
NC
2989 if (flags & SV_UNDEF_RETURNS_NULL)
2990 return NULL;
2991 if (!PL_localizing && !(SvFLAGS(sv) & SVs_PADTMP) && ckWARN(WARN_UNINITIALIZED))
2992 report_uninit(sv);
25da4f38
IZ
2993 if (SvTYPE(sv) < SVt_PV)
2994 /* Typically the caller expects that sv_any is not NULL now. */
2995 sv_upgrade(sv, SVt_PV);
73d840c0 2996 return (char *)"";
79072805 2997 }
cdb061a3 2998 {
823a54a3 2999 const STRLEN len = s - SvPVX_const(sv);
cdb061a3
NC
3000 if (lp)
3001 *lp = len;
3002 SvCUR_set(sv, len);
3003 }
79072805 3004 SvPOK_on(sv);
1d7c1841 3005 DEBUG_c(PerlIO_printf(Perl_debug_log, "0x%"UVxf" 2pv(%s)\n",
3f7c398e 3006 PTR2UV(sv),SvPVX_const(sv)));
4d84ee25
NC
3007 if (flags & SV_CONST_RETURN)
3008 return (char *)SvPVX_const(sv);
10516c54
NC
3009 if (flags & SV_MUTABLE_RETURN)
3010 return SvPVX_mutable(sv);
463ee0b2
LW
3011 return SvPVX(sv);
3012}
3013
645c22ef 3014/*
6050d10e
JP
3015=for apidoc sv_copypv
3016
3017Copies a stringified representation of the source SV into the
3018destination SV. Automatically performs any necessary mg_get and
54f0641b 3019coercion of numeric values into strings. Guaranteed to preserve
2575c402 3020UTF8 flag even from overloaded objects. Similar in nature to
54f0641b
NIS
3021sv_2pv[_flags] but operates directly on an SV instead of just the
3022string. Mostly uses sv_2pv_flags to do its work, except when that
6050d10e
JP
3023would lose the UTF-8'ness of the PV.
3024
3025=cut
3026*/
3027
3028void
5de3775c 3029Perl_sv_copypv(pTHX_ SV *const dsv, register SV *const ssv)
6050d10e 3030{
446eaa42 3031 STRLEN len;
53c1dcc0 3032 const char * const s = SvPV_const(ssv,len);
7918f24d
NC
3033
3034 PERL_ARGS_ASSERT_SV_COPYPV;
3035
cb50f42d 3036 sv_setpvn(dsv,s,len);
446eaa42 3037 if (SvUTF8(ssv))
cb50f42d 3038 SvUTF8_on(dsv);
446eaa42 3039 else
cb50f42d 3040 SvUTF8_off(dsv);
6050d10e
JP
3041}
3042
3043/*
645c22ef
DM
3044=for apidoc sv_2pvbyte
3045
3046Return a pointer to the byte-encoded representation of the SV, and set *lp
1e54db1a 3047to its length. May cause the SV to be downgraded from UTF-8 as a
645c22ef
DM
3048side-effect.
3049
3050Usually accessed via the C<SvPVbyte> macro.
3051
3052=cut
3053*/
3054
7340a771 3055char *
5de3775c 3056Perl_sv_2pvbyte(pTHX_ register SV *const sv, STRLEN *const lp)
7340a771 3057{
7918f24d
NC
3058 PERL_ARGS_ASSERT_SV_2PVBYTE;
3059
0875d2fe 3060 sv_utf8_downgrade(sv,0);
97972285 3061 return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
7340a771
GS
3062}
3063
645c22ef 3064/*
035cbb0e
RGS
3065=for apidoc sv_2pvutf8
3066
3067Return a pointer to the UTF-8-encoded representation of the SV, and set *lp
3068to its length. May cause the SV to be upgraded to UTF-8 as a side-effect.
3069
3070Usually accessed via the C<SvPVutf8> macro.
3071
3072=cut
3073*/
645c22ef 3074
7340a771 3075char *
7bc54cea 3076Perl_sv_2pvutf8(pTHX_ register SV *const sv, STRLEN *const lp)
7340a771 3077{
7918f24d
NC
3078 PERL_ARGS_ASSERT_SV_2PVUTF8;
3079
035cbb0e
RGS
3080 sv_utf8_upgrade(sv);
3081 return lp ? SvPV(sv,*lp) : SvPV_nolen(sv);
7340a771 3082}
1c846c1f 3083
7ee2227d 3084
645c22ef
DM
3085/*
3086=for apidoc sv_2bool
3087
3088This function is only called on magical items, and is only used by
8cf8f3d1 3089sv_true() or its macro equivalent.
645c22ef
DM
3090
3091=cut
3092*/
3093
463ee0b2 3094bool
7bc54cea 3095Perl_sv_2bool(pTHX_ register SV *const sv)
463ee0b2 3096{
97aff369 3097 dVAR;
7918f24d
NC
3098
3099 PERL_ARGS_ASSERT_SV_2BOOL;
3100
5b295bef 3101 SvGETMAGIC(sv);
463ee0b2 3102
a0d0e21e
LW
3103 if (!SvOK(sv))
3104 return 0;
3105 if (SvROK(sv)) {
fabdb6c0
AL
3106 if (SvAMAGIC(sv)) {
3107 SV * const tmpsv = AMG_CALLun(sv,bool_);
3108 if (tmpsv && (!SvROK(tmpsv) || (SvRV(tmpsv) != SvRV(sv))))
f2338a2e 3109 return cBOOL(SvTRUE(tmpsv));
fabdb6c0
AL
3110 }
3111 return SvRV(sv) != 0;
a0d0e21e 3112 }
463ee0b2 3113 if (SvPOKp(sv)) {
53c1dcc0
AL
3114 register XPV* const Xpvtmp = (XPV*)SvANY(sv);
3115 if (Xpvtmp &&
339049b0 3116 (*sv->sv_u.svu_pv > '0' ||
11343788 3117 Xpvtmp->xpv_cur > 1 ||
339049b0 3118 (Xpvtmp->xpv_cur && *sv->sv_u.svu_pv != '0')))
463ee0b2
LW
3119 return 1;
3120 else
3121 return 0;
3122 }
3123 else {
3124 if (SvIOKp(sv))
3125 return SvIVX(sv) != 0;
3126 else {
3127 if (SvNOKp(sv))
3128 return SvNVX(sv) != 0.0;
180488f8 3129 else {
f7877b28 3130 if (isGV_with_GP(sv))
180488f8
NC
3131 return TRUE;
3132 else
3133 return FALSE;
3134 }
463ee0b2
LW
3135 }
3136 }
79072805
LW
3137}
3138
c461cf8f
JH
3139/*
3140=for apidoc sv_utf8_upgrade
3141
78ea37eb 3142Converts the PV of an SV to its UTF-8-encoded form.
645c22ef 3143Forces the SV to string form if it is not already.
2bbc8d55 3144Will C<mg_get> on C<sv> if appropriate.
4411f3b6 3145Always sets the SvUTF8 flag to avoid future validity checks even
2bbc8d55
SP
3146if the whole string is the same in UTF-8 as not.
3147Returns the number of bytes in the converted string
c461cf8f 3148
13a6c0e0
JH
3149This is not as a general purpose byte encoding to Unicode interface:
3150use the Encode extension for that.
3151
fe749c9a
KW
3152=for apidoc sv_utf8_upgrade_nomg
3153
3154Like sv_utf8_upgrade, but doesn't do magic on C<sv>
3155
8d6d96c1
HS
3156=for apidoc sv_utf8_upgrade_flags
3157
78ea37eb 3158Converts the PV of an SV to its UTF-8-encoded form.
645c22ef 3159Forces the SV to string form if it is not already.
8d6d96c1 3160Always sets the SvUTF8 flag to avoid future validity checks even
2bbc8d55
SP
3161if all the bytes are invariant in UTF-8. If C<flags> has C<SV_GMAGIC> bit set,
3162will C<mg_get> on C<sv> if appropriate, else not.
3163Returns the number of bytes in the converted string
3164C<sv_utf8_upgrade> and
8d6d96c1
HS
3165C<sv_utf8_upgrade_nomg> are implemented in terms of this function.
3166
13a6c0e0
JH
3167This is not as a general purpose byte encoding to Unicode interface:
3168use the Encode extension for that.
3169
8d6d96c1 3170=cut
b3ab6785
KW
3171
3172The grow version is currently not externally documented. It adds a parameter,
3173extra, which is the number of unused bytes the string of 'sv' is guaranteed to
3174have free after it upon return. This allows the caller to reserve extra space
3175that it intends to fill, to avoid extra grows.
3176
3177Also externally undocumented for the moment is the flag SV_FORCE_UTF8_UPGRADE,
3178which can be used to tell this function to not first check to see if there are
3179any characters that are different in UTF-8 (variant characters) which would
3180force it to allocate a new string to sv, but to assume there are. Typically
3181this flag is used by a routine that has already parsed the string to find that
3182there are such characters, and passes this information on so that the work
3183doesn't have to be repeated.
3184
3185(One might think that the calling routine could pass in the position of the
3186first such variant, so it wouldn't have to be found again. But that is not the
3187case, because typically when the caller is likely to use this flag, it won't be
3188calling this routine unless it finds something that won't fit into a byte.
3189Otherwise it tries to not upgrade and just use bytes. But some things that
3190do fit into a byte are variants in utf8, and the caller may not have been
3191keeping track of these.)
3192
3193If the routine itself changes the string, it adds a trailing NUL. Such a NUL
3194isn't guaranteed due to having other routines do the work in some input cases,
3195or if the input is already flagged as being in utf8.
3196
3197The speed of this could perhaps be improved for many cases if someone wanted to
3198write a fast function that counts the number of variant characters in a string,
3199especially if it could return the position of the first one.
3200
8d6d96c1
HS
3201*/
3202
3203STRLEN
b3ab6785 3204Perl_sv_utf8_upgrade_flags_grow(pTHX_ register SV *const sv, const I32 flags, STRLEN extra)
8d6d96c1 3205{
97aff369 3206 dVAR;
7918f24d 3207
b3ab6785 3208 PERL_ARGS_ASSERT_SV_UTF8_UPGRADE_FLAGS_GROW;
7918f24d 3209
808c356f
RGS
3210 if (sv == &PL_sv_undef)
3211 return 0;
e0e62c2a
NIS
3212 if (!SvPOK(sv)) {
3213 STRLEN len = 0;
d52b7888
NC
3214 if (SvREADONLY(sv) && (SvPOKp(sv) || SvIOKp(sv) || SvNOKp(sv))) {
3215 (void) sv_2pv_flags(sv,&len, flags);
b3ab6785
KW
3216 if (SvUTF8(sv)) {
3217 if (extra) SvGROW(sv, SvCUR(sv) + extra);
d52b7888 3218 return len;
b3ab6785 3219 }
d52b7888
NC
3220 } else {
3221 (void) SvPV_force(sv,len);
3222 }
e0e62c2a 3223 }
4411f3b6 3224
f5cee72b 3225 if (SvUTF8(sv)) {
b3ab6785 3226 if (extra) SvGROW(sv, SvCUR(sv) + extra);
5fec3b1d 3227 return SvCUR(sv);
f5cee72b 3228 }
5fec3b1d 3229
765f542d
NC
3230 if (SvIsCOW(sv)) {
3231 sv_force_normal_flags(sv, 0);
db42d148
NIS
3232 }
3233
b3ab6785 3234 if (PL_encoding && !(flags & SV_UTF8_NO_ENCODING)) {
799ef3cb 3235 sv_recode_to_utf8(sv, PL_encoding);
b3ab6785
KW
3236 if (extra) SvGROW(sv, SvCUR(sv) + extra);
3237 return SvCUR(sv);
3238 }
3239
4e93345f
KW
3240 if (SvCUR(sv) == 0) {
3241 if (extra) SvGROW(sv, extra);
3242 } else { /* Assume Latin-1/EBCDIC */
c4e7c712 3243 /* This function could be much more efficient if we
2bbc8d55 3244 * had a FLAG in SVs to signal if there are any variant
c4e7c712 3245 * chars in the PV. Given that there isn't such a flag
b3ab6785
KW
3246 * make the loop as fast as possible (although there are certainly ways
3247 * to speed this up, eg. through vectorization) */
3248 U8 * s = (U8 *) SvPVX_const(sv);
3249 U8 * e = (U8 *) SvEND(sv);
3250 U8 *t = s;
3251 STRLEN two_byte_count = 0;
c4e7c712 3252
b3ab6785
KW
3253 if (flags & SV_FORCE_UTF8_UPGRADE) goto must_be_utf8;
3254
3255 /* See if really will need to convert to utf8. We mustn't rely on our
3256 * incoming SV being well formed and having a trailing '\0', as certain
3257 * code in pp_formline can send us partially built SVs. */
3258
c4e7c712 3259 while (t < e) {
53c1dcc0 3260 const U8 ch = *t++;
b3ab6785
KW
3261 if (NATIVE_IS_INVARIANT(ch)) continue;
3262
3263 t--; /* t already incremented; re-point to first variant */
3264 two_byte_count = 1;
3265 goto must_be_utf8;
c4e7c712 3266 }
b3ab6785
KW
3267
3268 /* utf8 conversion not needed because all are invariants. Mark as
3269 * UTF-8 even if no variant - saves scanning loop */
c4e7c712 3270 SvUTF8_on(sv);
b3ab6785
KW
3271 return SvCUR(sv);
3272
3273must_be_utf8:
3274
3275 /* Here, the string should be converted to utf8, either because of an
3276 * input flag (two_byte_count = 0), or because a character that
3277 * requires 2 bytes was found (two_byte_count = 1). t points either to
3278 * the beginning of the string (if we didn't examine anything), or to
3279 * the first variant. In either case, everything from s to t - 1 will
3280 * occupy only 1 byte each on output.
3281 *
3282 * There are two main ways to convert. One is to create a new string
3283 * and go through the input starting from the beginning, appending each
3284 * converted value onto the new string as we go along. It's probably
3285 * best to allocate enough space in the string for the worst possible
3286 * case rather than possibly running out of space and having to
3287 * reallocate and then copy what we've done so far. Since everything
3288 * from s to t - 1 is invariant, the destination can be initialized
3289 * with these using a fast memory copy
3290 *
3291 * The other way is to figure out exactly how big the string should be
3292 * by parsing the entire input. Then you don't have to make it big
3293 * enough to handle the worst possible case, and more importantly, if
3294 * the string you already have is large enough, you don't have to
3295 * allocate a new string, you can copy the last character in the input
3296 * string to the final position(s) that will be occupied by the
3297 * converted string and go backwards, stopping at t, since everything
3298 * before that is invariant.
3299 *
3300 * There are advantages and disadvantages to each method.
3301 *
3302 * In the first method, we can allocate a new string, do the memory
3303 * copy from the s to t - 1, and then proceed through the rest of the
3304 * string byte-by-byte.
3305 *
3306 * In the second method, we proceed through the rest of the input
3307 * string just calculating how big the converted string will be. Then
3308 * there are two cases:
3309 * 1) if the string has enough extra space to handle the converted
3310 * value. We go backwards through the string, converting until we
3311 * get to the position we are at now, and then stop. If this
3312 * position is far enough along in the string, this method is
3313 * faster than the other method. If the memory copy were the same
3314 * speed as the byte-by-byte loop, that position would be about
3315 * half-way, as at the half-way mark, parsing to the end and back
3316 * is one complete string's parse, the same amount as starting
3317 * over and going all the way through. Actually, it would be
3318 * somewhat less than half-way, as it's faster to just count bytes
3319 * than to also copy, and we don't have the overhead of allocating
3320 * a new string, changing the scalar to use it, and freeing the
3321 * existing one. But if the memory copy is fast, the break-even
3322 * point is somewhere after half way. The counting loop could be
3323 * sped up by vectorization, etc, to move the break-even point
3324 * further towards the beginning.
3325 * 2) if the string doesn't have enough space to handle the converted
3326 * value. A new string will have to be allocated, and one might
3327 * as well, given that, start from the beginning doing the first
3328 * method. We've spent extra time parsing the string and in
3329 * exchange all we've gotten is that we know precisely how big to
3330 * make the new one. Perl is more optimized for time than space,
3331 * so this case is a loser.
3332 * So what I've decided to do is not use the 2nd method unless it is
3333 * guaranteed that a new string won't have to be allocated, assuming
3334 * the worst case. I also decided not to put any more conditions on it
3335 * than this, for now. It seems likely that, since the worst case is
3336 * twice as big as the unknown portion of the string (plus 1), we won't
3337 * be guaranteed enough space, causing us to go to the first method,
3338 * unless the string is short, or the first variant character is near
3339 * the end of it. In either of these cases, it seems best to use the
3340 * 2nd method. The only circumstance I can think of where this would
3341 * be really slower is if the string had once had much more data in it
3342 * than it does now, but there is still a substantial amount in it */
3343
3344 {
3345 STRLEN invariant_head = t - s;
3346 STRLEN size = invariant_head + (e - t) * 2 + 1 + extra;
3347 if (SvLEN(sv) < size) {
3348
3349 /* Here, have decided to allocate a new string */
3350
3351 U8 *dst;
3352 U8 *d;
3353
3354 Newx(dst, size, U8);
3355
3356 /* If no known invariants at the beginning of the input string,
3357 * set so starts from there. Otherwise, can use memory copy to
3358 * get up to where we are now, and then start from here */
3359
3360 if (invariant_head <= 0) {
3361 d = dst;
3362 } else {
3363 Copy(s, dst, invariant_head, char);
3364 d = dst + invariant_head;
3365 }
3366
3367 while (t < e) {
3368 const UV uv = NATIVE8_TO_UNI(*t++);
3369 if (UNI_IS_INVARIANT(uv))
3370 *d++ = (U8)UNI_TO_NATIVE(uv);
3371 else {
3372 *d++ = (U8)UTF8_EIGHT_BIT_HI(uv);
3373 *d++ = (U8)UTF8_EIGHT_BIT_LO(uv);
3374 }
3375 }
3376 *d = '\0';
3377 SvPV_free(sv); /* No longer using pre-existing string */
3378 SvPV_set(sv, (char*)dst);
3379 SvCUR_set(sv, d - dst);
3380 SvLEN_set(sv, size);
3381 } else {
3382
3383 /* Here, have decided to get the exact size of the string.
3384 * Currently this happens only when we know that there is
3385 * guaranteed enough space to fit the converted string, so
3386 * don't have to worry about growing. If two_byte_count is 0,
3387 * then t points to the first byte of the string which hasn't
3388 * been examined yet. Otherwise two_byte_count is 1, and t
3389 * points to the first byte in the string that will expand to
3390 * two. Depending on this, start examining at t or 1 after t.
3391 * */
3392
3393 U8 *d = t + two_byte_count;
3394
3395
3396 /* Count up the remaining bytes that expand to two */
3397
3398 while (d < e) {
3399 const U8 chr = *d++;
3400 if (! NATIVE_IS_INVARIANT(chr)) two_byte_count++;
3401 }
3402
3403 /* The string will expand by just the number of bytes that
3404 * occupy two positions. But we are one afterwards because of
3405 * the increment just above. This is the place to put the
3406 * trailing NUL, and to set the length before we decrement */
3407
3408 d += two_byte_count;
3409 SvCUR_set(sv, d - s);
3410 *d-- = '\0';
3411
3412
3413 /* Having decremented d, it points to the position to put the
3414 * very last byte of the expanded string. Go backwards through
3415 * the string, copying and expanding as we go, stopping when we
3416 * get to the part that is invariant the rest of the way down */
3417
3418 e--;
3419 while (e >= t) {
3420 const U8 ch = NATIVE8_TO_UNI(*e--);
3421 if (UNI_IS_INVARIANT(ch)) {
3422 *d-- = UNI_TO_NATIVE(ch);
3423 } else {
3424 *d-- = (U8)UTF8_EIGHT_BIT_LO(ch);
3425 *d-- = (U8)UTF8_EIGHT_BIT_HI(ch);
3426 }
3427 }
3428 }
3429 }
560a288e 3430 }
b3ab6785
KW
3431
3432 /* Mark as UTF-8 even if no variant - saves scanning loop */
3433 SvUTF8_on(sv);
4411f3b6 3434 return SvCUR(sv);
560a288e
GS
3435}
3436
c461cf8f
JH
3437/*
3438=for apidoc sv_utf8_downgrade
3439
78ea37eb 3440Attempts to convert the PV of an SV from characters to bytes.
2bbc8d55
SP
3441If the PV contains a character that cannot fit
3442in a byte, this conversion will fail;
78ea37eb 3443in this case, either returns false or, if C<fail_ok> is not
c461cf8f
JH
3444true, croaks.
3445
13a6c0e0
JH
3446This is not as a general purpose Unicode to byte encoding interface:
3447use the Encode extension for that.
3448
c461cf8f
JH
3449=cut
3450*/
3451
560a288e 3452bool
7bc54cea 3453Perl_sv_utf8_downgrade(pTHX_ register SV *const sv, const bool fail_ok)
560a288e 3454{
97aff369 3455 dVAR;
7918f24d
NC
3456
3457 PERL_ARGS_ASSERT_SV_UTF8_DOWNGRADE;
3458
78ea37eb 3459 if (SvPOKp(sv) && SvUTF8(sv)) {
fa301091 3460 if (SvCUR(sv)) {
03cfe0ae 3461 U8 *s;
652088fc 3462 STRLEN len;
fa301091 3463
765f542d
NC
3464 if (SvIsCOW(sv)) {
3465 sv_force_normal_flags(sv, 0);
3466 }
03cfe0ae
NIS
3467 s = (U8 *) SvPV(sv, len);
3468 if (!utf8_to_bytes(s, &len)) {
fa301091
JH
3469 if (fail_ok)
3470 return FALSE;
3471 else {
3472 if (PL_op)
3473 Perl_croak(aTHX_ "Wide character in %s",
53e06cf0 3474 OP_DESC(PL_op));
fa301091
JH
3475 else
3476 Perl_croak(aTHX_ "Wide character");
3477 }
4b3603a4 3478 }
b162af07 3479 SvCUR_set(sv, len);
67e989fb 3480 }
560a288e 3481 }
ffebcc3e 3482 SvUTF8_off(sv);
560a288e
GS
3483 return TRUE;
3484}
3485
c461cf8f
JH
3486/*
3487=for apidoc sv_utf8_encode
3488
78ea37eb
TS
3489Converts the PV of an SV to UTF-8, but then turns the C<SvUTF8>
3490flag off so that it looks like octets again.
c461cf8f
JH
3491
3492=cut
3493*/
3494
560a288e 3495void
7bc54cea 3496Perl_sv_utf8_encode(pTHX_ register SV *const sv)
560a288e 3497{
7918f24d
NC
3498 PERL_ARGS_ASSERT_SV_UTF8_ENCODE;
3499
4c94c214
NC
3500 if (SvIsCOW(sv)) {
3501 sv_force_normal_flags(sv, 0);
3502 }
3503 if (SvREADONLY(sv)) {
6ad8f254 3504 Perl_croak_no_modify(aTHX);
4c94c214 3505 }
a5f5288a 3506 (void) sv_utf8_upgrade(sv);
560a288e
GS
3507 SvUTF8_off(sv);
3508}
3509
4411f3b6
NIS
3510/*
3511=for apidoc sv_utf8_decode
3512
78ea37eb
TS
3513If the PV of the SV is an octet sequence in UTF-8
3514and contains a multiple-byte character, the C<SvUTF8> flag is turned on
3515so that it looks like a character. If the PV contains only single-byte
3516characters, the C<SvUTF8> flag stays being off.
3517Scans PV for validity and returns false if the PV is invalid UTF-8.
4411f3b6
NIS
3518
3519=cut
3520*/
3521
560a288e 3522bool
7bc54cea 3523Perl_sv_utf8_decode(pTHX_ register SV *const sv)
560a288e 3524{
7918f24d
NC
3525 PERL_ARGS_ASSERT_SV_UTF8_DECODE;
3526
78ea37eb 3527 if (SvPOKp(sv)) {
93524f2b
NC
3528 const U8 *c;
3529 const U8 *e;
9cbac4c7 3530
645c22ef
DM
3531 /* The octets may have got themselves encoded - get them back as
3532 * bytes
3533 */
3534 if (!sv_utf8_downgrade(sv, TRUE))
560a288e
GS
3535 return FALSE;
3536
3537 /* it is actually just a matter of turning the utf8 flag on, but
3538 * we want to make sure everything inside is valid utf8 first.
3539 */
93524f2b 3540 c = (const U8 *) SvPVX_const(sv);
63cd0674 3541 if (!is_utf8_string(c, SvCUR(sv)+1))
67e989fb 3542 return FALSE;
93524f2b 3543 e = (const U8 *) SvEND(sv);
511c2ff0 3544 while (c < e) {
b64e5050 3545 const U8 ch = *c++;
c4d5f83a 3546 if (!UTF8_IS_INVARIANT(ch)) {
67e989fb
JH
3547 SvUTF8_on(sv);
3548 break;
3549 }
560a288e 3550 }
560a288e
GS
3551 }
3552 return TRUE;
3553}
3554
954c1994
GS
3555/*
3556=for apidoc sv_setsv
3557
645c22ef
DM
3558Copies the contents of the source SV C<ssv> into the destination SV
3559C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3560function if the source SV needs to be reused. Does not handle 'set' magic.
3561Loosely speaking, it performs a copy-by-value, obliterating any previous
3562content of the destination.
3563
3564You probably want to use one of the assortment of wrappers, such as
3565C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3566C<SvSetMagicSV_nosteal>.
3567
8d6d96c1
HS
3568=for apidoc sv_setsv_flags
3569
645c22ef
DM
3570Copies the contents of the source SV C<ssv> into the destination SV
3571C<dsv>. The source SV may be destroyed if it is mortal, so don't use this
3572function if the source SV needs to be reused. Does not handle 'set' magic.
3573Loosely speaking, it performs a copy-by-value, obliterating any previous
3574content of the destination.
3575If the C<flags> parameter has the C<SV_GMAGIC> bit set, will C<mg_get> on
5fcdf167
NC
3576C<ssv> if appropriate, else not. If the C<flags> parameter has the
3577C<NOSTEAL> bit set then the buffers of temps will not be stolen. <sv_setsv>
3578and C<sv_setsv_nomg> are implemented in terms of this function.
645c22ef
DM
3579
3580You probably want to use one of the assortment of wrappers, such as
3581C<SvSetSV>, C<SvSetSV_nosteal>, C<SvSetMagicSV> and
3582C<SvSetMagicSV_nosteal>.
3583
3584This is the primary function for copying scalars, and most other
3585copy-ish functions and macros use this underneath.
8d6d96c1
HS
3586
3587=cut
3588*/
3589
5d0301b7 3590static void
7bc54cea 3591S_glob_assign_glob(pTHX_ SV *const dstr, SV *const sstr, const int dtype)
5d0301b7 3592{
70cd14a1 3593 I32 mro_changes = 0; /* 1 = method, 2 = isa */
dd69841b 3594
7918f24d
NC
3595 PERL_ARGS_ASSERT_GLOB_ASSIGN_GLOB;
3596
5d0301b7
NC
3597 if (dtype != SVt_PVGV) {
3598 const char * const name = GvNAME(sstr);
3599 const STRLEN len = GvNAMELEN(sstr);
0d092c36 3600 {
f7877b28
NC
3601 if (dtype >= SVt_PV) {
3602 SvPV_free(dstr);
3603 SvPV_set(dstr, 0);
3604 SvLEN_set(dstr, 0);
3605 SvCUR_set(dstr, 0);
3606 }
0d092c36 3607 SvUPGRADE(dstr, SVt_PVGV);
dedf8e73 3608 (void)SvOK_off(dstr);
2e5b91de
NC
3609 /* FIXME - why are we doing this, then turning it off and on again
3610 below? */
3611 isGV_with_GP_on(dstr);
f7877b28 3612 }
5d0301b7
NC
3613 GvSTASH(dstr) = GvSTASH(sstr);
3614 if (GvSTASH(dstr))
daba3364 3615 Perl_sv_add_backref(aTHX_ MUTABLE_SV(GvSTASH(dstr)), dstr);
159b6efe 3616 gv_name_set(MUTABLE_GV(dstr), name, len, GV_ADD);
5d0301b7
NC
3617 SvFAKE_on(dstr); /* can coerce to non-glob */
3618 }
3619
159b6efe 3620 if(GvGP(MUTABLE_GV(sstr))) {
dd69841b
BB
3621 /* If source has method cache entry, clear it */
3622 if(GvCVGEN(sstr)) {
3623 SvREFCNT_dec(GvCV(sstr));
3624 GvCV(sstr) = NULL;
3625 GvCVGEN(sstr) = 0;
3626 }
3627 /* If source has a real method, then a method is
3628 going to change */
159b6efe 3629 else if(GvCV((const GV *)sstr)) {
70cd14a1 3630 mro_changes = 1;
dd69841b
BB
3631 }
3632 }
3633
3634 /* If dest already had a real method, that's a change as well */
159b6efe 3635 if(!mro_changes && GvGP(MUTABLE_GV(dstr)) && GvCVu((const GV *)dstr)) {
70cd14a1 3636 mro_changes = 1;
dd69841b
BB
3637 }
3638
159b6efe 3639 if(strEQ(GvNAME((const GV *)dstr),"ISA"))
70cd14a1
CB
3640 mro_changes = 2;
3641
159b6efe 3642 gp_free(MUTABLE_GV(dstr));
2e5b91de 3643 isGV_with_GP_off(dstr);
5d0301b7 3644 (void)SvOK_off(dstr);
2e5b91de 3645 isGV_with_GP_on(dstr);
dedf8e73 3646 GvINTRO_off(dstr); /* one-shot flag */
5d0301b7
NC
3647 GvGP(dstr) = gp_ref(GvGP(sstr));
3648 if (SvTAINTED(sstr))