This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
new perldelta
[perl5.git] / util.c
CommitLineData
a0d0e21e 1/* util.c
a687059c 2 *
1129b882
NC
3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
a687059c 5 *
d48672a2
LW
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
8d063cd8 8 *
8d063cd8 9 */
a0d0e21e
LW
10
11/*
4ac71550
TC
12 * 'Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content.' --Gandalf to Pippin
14 *
cdad3b53 15 * [p.598 of _The Lord of the Rings_, III/xi: "The Palantír"]
a0d0e21e 16 */
8d063cd8 17
166f8a29
DM
18/* This file contains assorted utility routines.
19 * Which is a polite way of saying any stuff that people couldn't think of
20 * a better place for. Amongst other things, it includes the warning and
21 * dieing stuff, plus wrappers for malloc code.
22 */
23
8d063cd8 24#include "EXTERN.h"
864dbfa3 25#define PERL_IN_UTIL_C
8d063cd8 26#include "perl.h"
62b28dd9 27
6f408c34 28#ifdef USE_PERLIO
2e0cfa16 29#include "perliol.h" /* For PerlIOUnix_refcnt */
6f408c34 30#endif
2e0cfa16 31
64ca3a65 32#ifndef PERL_MICRO
a687059c 33#include <signal.h>
36477c24 34#ifndef SIG_ERR
35# define SIG_ERR ((Sighandler_t) -1)
36#endif
64ca3a65 37#endif
36477c24 38
172d2248
OS
39#ifdef __Lynx__
40/* Missing protos on LynxOS */
41int putenv(char *);
42#endif
43
868439a2
JH
44#ifdef HAS_SELECT
45# ifdef I_SYS_SELECT
46# include <sys/select.h>
47# endif
48#endif
49
8d063cd8 50#define FLUSH
8d063cd8 51
16cebae2
GS
52#if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
53# define FD_CLOEXEC 1 /* NeXT needs this */
54#endif
55
a687059c
LW
56/* NOTE: Do not call the next three routines directly. Use the macros
57 * in handy.h, so that we can easily redefine everything to do tracking of
58 * allocated hunks back to the original New to track down any memory leaks.
20cec16a 59 * XXX This advice seems to be widely ignored :-( --AD August 1996.
a687059c
LW
60 */
61
ca8d8976
NC
62static char *
63S_write_no_mem(pTHX)
64{
97aff369 65 dVAR;
ca8d8976
NC
66 /* Can't use PerlIO to write as it allocates memory */
67 PerlLIO_write(PerlIO_fileno(Perl_error_log),
68 PL_no_mem, strlen(PL_no_mem));
69 my_exit(1);
1f440eb2 70 NORETURN_FUNCTION_END;
ca8d8976
NC
71}
72
79a92154 73#if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
1f4d2d4e
NC
74# define ALWAYS_NEED_THX
75#endif
76
26fa51c3
AMS
77/* paranoid version of system's malloc() */
78
bd4080b3 79Malloc_t
4f63d024 80Perl_safesysmalloc(MEM_SIZE size)
8d063cd8 81{
1f4d2d4e 82#ifdef ALWAYS_NEED_THX
54aff467 83 dTHX;
0cb20dae 84#endif
bd4080b3 85 Malloc_t ptr;
55497cff 86#ifdef HAS_64K_LIMIT
62b28dd9 87 if (size > 0xffff) {
bf49b057 88 PerlIO_printf(Perl_error_log,
16cebae2 89 "Allocation too large: %lx\n", size) FLUSH;
54aff467 90 my_exit(1);
62b28dd9 91 }
55497cff 92#endif /* HAS_64K_LIMIT */
e8dda941
JD
93#ifdef PERL_TRACK_MEMPOOL
94 size += sTHX;
95#endif
34de22dd 96#ifdef DEBUGGING
03c5309f 97 if ((SSize_t)size < 0)
5637ef5b 98 Perl_croak_nocontext("panic: malloc, size=%"UVuf, (UV) size);
34de22dd 99#endif
12ae5dfc 100 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
da927450 101 PERL_ALLOC_CHECK(ptr);
bd61b366 102 if (ptr != NULL) {
e8dda941 103#ifdef PERL_TRACK_MEMPOOL
7cb608b5
NC
104 struct perl_memory_debug_header *const header
105 = (struct perl_memory_debug_header *)ptr;
9a083ecf
NC
106#endif
107
108#ifdef PERL_POISON
7e337ee0 109 PoisonNew(((char *)ptr), size, char);
9a083ecf 110#endif
7cb608b5 111
9a083ecf 112#ifdef PERL_TRACK_MEMPOOL
7cb608b5
NC
113 header->interpreter = aTHX;
114 /* Link us into the list. */
115 header->prev = &PL_memory_debug_header;
116 header->next = PL_memory_debug_header.next;
117 PL_memory_debug_header.next = header;
118 header->next->prev = header;
cd1541b2 119# ifdef PERL_POISON
7cb608b5 120 header->size = size;
cd1541b2 121# endif
e8dda941
JD
122 ptr = (Malloc_t)((char*)ptr+sTHX);
123#endif
5dfff8f3 124 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
8d063cd8 125 return ptr;
e8dda941 126}
8d063cd8 127 else {
1f4d2d4e 128#ifndef ALWAYS_NEED_THX
0cb20dae
NC
129 dTHX;
130#endif
131 if (PL_nomemok)
132 return NULL;
133 else {
134 return write_no_mem();
135 }
8d063cd8
LW
136 }
137 /*NOTREACHED*/
138}
139
f2517201 140/* paranoid version of system's realloc() */
8d063cd8 141
bd4080b3 142Malloc_t
4f63d024 143Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
8d063cd8 144{
1f4d2d4e 145#ifdef ALWAYS_NEED_THX
54aff467 146 dTHX;
0cb20dae 147#endif
bd4080b3 148 Malloc_t ptr;
9a34ef1d 149#if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
6ad3d225 150 Malloc_t PerlMem_realloc();
ecfc5424 151#endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
8d063cd8 152
a1d180c4 153#ifdef HAS_64K_LIMIT
5f05dabc 154 if (size > 0xffff) {
bf49b057 155 PerlIO_printf(Perl_error_log,
5f05dabc 156 "Reallocation too large: %lx\n", size) FLUSH;
54aff467 157 my_exit(1);
5f05dabc 158 }
55497cff 159#endif /* HAS_64K_LIMIT */
7614df0c 160 if (!size) {
f2517201 161 safesysfree(where);
7614df0c
JD
162 return NULL;
163 }
164
378cc40b 165 if (!where)
f2517201 166 return safesysmalloc(size);
e8dda941
JD
167#ifdef PERL_TRACK_MEMPOOL
168 where = (Malloc_t)((char*)where-sTHX);
169 size += sTHX;
7cb608b5
NC
170 {
171 struct perl_memory_debug_header *const header
172 = (struct perl_memory_debug_header *)where;
173
174 if (header->interpreter != aTHX) {
5637ef5b
NC
175 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
176 header->interpreter, aTHX);
7cb608b5
NC
177 }
178 assert(header->next->prev == header);
179 assert(header->prev->next == header);
cd1541b2 180# ifdef PERL_POISON
7cb608b5
NC
181 if (header->size > size) {
182 const MEM_SIZE freed_up = header->size - size;
183 char *start_of_freed = ((char *)where) + size;
7e337ee0 184 PoisonFree(start_of_freed, freed_up, char);
7cb608b5
NC
185 }
186 header->size = size;
cd1541b2 187# endif
7cb608b5 188 }
e8dda941 189#endif
34de22dd 190#ifdef DEBUGGING
03c5309f 191 if ((SSize_t)size < 0)
5637ef5b 192 Perl_croak_nocontext("panic: realloc, size=%"UVuf, (UV)size);
34de22dd 193#endif
12ae5dfc 194 ptr = (Malloc_t)PerlMem_realloc(where,size);
da927450 195 PERL_ALLOC_CHECK(ptr);
a1d180c4 196
4fd0a9b8
NC
197 /* MUST do this fixup first, before doing ANYTHING else, as anything else
198 might allocate memory/free/move memory, and until we do the fixup, it
199 may well be chasing (and writing to) free memory. */
e8dda941 200#ifdef PERL_TRACK_MEMPOOL
4fd0a9b8 201 if (ptr != NULL) {
7cb608b5
NC
202 struct perl_memory_debug_header *const header
203 = (struct perl_memory_debug_header *)ptr;
204
9a083ecf
NC
205# ifdef PERL_POISON
206 if (header->size < size) {
207 const MEM_SIZE fresh = size - header->size;
208 char *start_of_fresh = ((char *)ptr) + size;
7e337ee0 209 PoisonNew(start_of_fresh, fresh, char);
9a083ecf
NC
210 }
211# endif
212
7cb608b5
NC
213 header->next->prev = header;
214 header->prev->next = header;
215
e8dda941 216 ptr = (Malloc_t)((char*)ptr+sTHX);
4fd0a9b8 217 }
e8dda941 218#endif
4fd0a9b8
NC
219
220 /* In particular, must do that fixup above before logging anything via
221 *printf(), as it can reallocate memory, which can cause SEGVs. */
222
223 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
224 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
225
226
227 if (ptr != NULL) {
8d063cd8 228 return ptr;
e8dda941 229 }
8d063cd8 230 else {
1f4d2d4e 231#ifndef ALWAYS_NEED_THX
0cb20dae
NC
232 dTHX;
233#endif
234 if (PL_nomemok)
235 return NULL;
236 else {
237 return write_no_mem();
238 }
8d063cd8
LW
239 }
240 /*NOTREACHED*/
241}
242
f2517201 243/* safe version of system's free() */
8d063cd8 244
54310121 245Free_t
4f63d024 246Perl_safesysfree(Malloc_t where)
8d063cd8 247{
79a92154 248#ifdef ALWAYS_NEED_THX
54aff467 249 dTHX;
97aff369
JH
250#else
251 dVAR;
155aba94 252#endif
97835f67 253 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
378cc40b 254 if (where) {
e8dda941
JD
255#ifdef PERL_TRACK_MEMPOOL
256 where = (Malloc_t)((char*)where-sTHX);
cd1541b2 257 {
7cb608b5
NC
258 struct perl_memory_debug_header *const header
259 = (struct perl_memory_debug_header *)where;
260
261 if (header->interpreter != aTHX) {
5637ef5b
NC
262 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
263 header->interpreter, aTHX);
7cb608b5
NC
264 }
265 if (!header->prev) {
cd1541b2
NC
266 Perl_croak_nocontext("panic: duplicate free");
267 }
5637ef5b
NC
268 if (!(header->next))
269 Perl_croak_nocontext("panic: bad free, header->next==NULL");
270 if (header->next->prev != header || header->prev->next != header) {
271 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
272 "header=%p, ->prev->next=%p",
273 header->next->prev, header,
274 header->prev->next);
cd1541b2 275 }
7cb608b5
NC
276 /* Unlink us from the chain. */
277 header->next->prev = header->prev;
278 header->prev->next = header->next;
279# ifdef PERL_POISON
7e337ee0 280 PoisonNew(where, header->size, char);
cd1541b2 281# endif
7cb608b5
NC
282 /* Trigger the duplicate free warning. */
283 header->next = NULL;
284 }
e8dda941 285#endif
6ad3d225 286 PerlMem_free(where);
378cc40b 287 }
8d063cd8
LW
288}
289
f2517201 290/* safe version of system's calloc() */
1050c9ca 291
bd4080b3 292Malloc_t
4f63d024 293Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
1050c9ca 294{
1f4d2d4e 295#ifdef ALWAYS_NEED_THX
54aff467 296 dTHX;
0cb20dae 297#endif
bd4080b3 298 Malloc_t ptr;
4b1123b9 299#if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
ad7244db 300 MEM_SIZE total_size = 0;
4b1123b9 301#endif
1050c9ca 302
ad7244db 303 /* Even though calloc() for zero bytes is strange, be robust. */
4b1123b9
NC
304 if (size && (count <= MEM_SIZE_MAX / size)) {
305#if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
ad7244db 306 total_size = size * count;
4b1123b9
NC
307#endif
308 }
ad7244db 309 else
f1f66076 310 Perl_croak_nocontext("%s", PL_memory_wrap);
ad7244db 311#ifdef PERL_TRACK_MEMPOOL
19a94d75 312 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
ad7244db
JH
313 total_size += sTHX;
314 else
f1f66076 315 Perl_croak_nocontext("%s", PL_memory_wrap);
ad7244db 316#endif
55497cff 317#ifdef HAS_64K_LIMIT
e1a95402 318 if (total_size > 0xffff) {
bf49b057 319 PerlIO_printf(Perl_error_log,
e1a95402 320 "Allocation too large: %lx\n", total_size) FLUSH;
54aff467 321 my_exit(1);
5f05dabc 322 }
55497cff 323#endif /* HAS_64K_LIMIT */
1050c9ca 324#ifdef DEBUGGING
03c5309f 325 if ((SSize_t)size < 0 || (SSize_t)count < 0)
5637ef5b
NC
326 Perl_croak_nocontext("panic: calloc, size=%"UVuf", count=%"UVuf,
327 (UV)size, (UV)count);
1050c9ca 328#endif
e8dda941 329#ifdef PERL_TRACK_MEMPOOL
e1a95402
NC
330 /* Have to use malloc() because we've added some space for our tracking
331 header. */
ad7244db
JH
332 /* malloc(0) is non-portable. */
333 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
e1a95402
NC
334#else
335 /* Use calloc() because it might save a memset() if the memory is fresh
336 and clean from the OS. */
ad7244db
JH
337 if (count && size)
338 ptr = (Malloc_t)PerlMem_calloc(count, size);
339 else /* calloc(0) is non-portable. */
340 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
e8dda941 341#endif
da927450 342 PERL_ALLOC_CHECK(ptr);
e1a95402 343 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)total_size));
bd61b366 344 if (ptr != NULL) {
e8dda941 345#ifdef PERL_TRACK_MEMPOOL
7cb608b5
NC
346 {
347 struct perl_memory_debug_header *const header
348 = (struct perl_memory_debug_header *)ptr;
349
e1a95402 350 memset((void*)ptr, 0, total_size);
7cb608b5
NC
351 header->interpreter = aTHX;
352 /* Link us into the list. */
353 header->prev = &PL_memory_debug_header;
354 header->next = PL_memory_debug_header.next;
355 PL_memory_debug_header.next = header;
356 header->next->prev = header;
cd1541b2 357# ifdef PERL_POISON
e1a95402 358 header->size = total_size;
cd1541b2 359# endif
7cb608b5
NC
360 ptr = (Malloc_t)((char*)ptr+sTHX);
361 }
e8dda941 362#endif
1050c9ca 363 return ptr;
364 }
0cb20dae 365 else {
1f4d2d4e 366#ifndef ALWAYS_NEED_THX
0cb20dae
NC
367 dTHX;
368#endif
369 if (PL_nomemok)
370 return NULL;
371 return write_no_mem();
372 }
1050c9ca 373}
374
cae6d0e5
GS
375/* These must be defined when not using Perl's malloc for binary
376 * compatibility */
377
378#ifndef MYMALLOC
379
380Malloc_t Perl_malloc (MEM_SIZE nbytes)
381{
382 dTHXs;
077a72a9 383 return (Malloc_t)PerlMem_malloc(nbytes);
cae6d0e5
GS
384}
385
386Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
387{
388 dTHXs;
077a72a9 389 return (Malloc_t)PerlMem_calloc(elements, size);
cae6d0e5
GS
390}
391
392Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
393{
394 dTHXs;
077a72a9 395 return (Malloc_t)PerlMem_realloc(where, nbytes);
cae6d0e5
GS
396}
397
398Free_t Perl_mfree (Malloc_t where)
399{
400 dTHXs;
401 PerlMem_free(where);
402}
403
404#endif
405
8d063cd8
LW
406/* copy a string up to some (non-backslashed) delimiter, if any */
407
408char *
04c9e624 409Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
8d063cd8 410{
fc36a67e 411 register I32 tolen;
35da51f7 412
7918f24d
NC
413 PERL_ARGS_ASSERT_DELIMCPY;
414
fc36a67e 415 for (tolen = 0; from < fromend; from++, tolen++) {
378cc40b 416 if (*from == '\\') {
35da51f7 417 if (from[1] != delim) {
fc36a67e 418 if (to < toend)
419 *to++ = *from;
420 tolen++;
fc36a67e 421 }
35da51f7 422 from++;
378cc40b 423 }
bedebaa5 424 else if (*from == delim)
8d063cd8 425 break;
fc36a67e 426 if (to < toend)
427 *to++ = *from;
8d063cd8 428 }
bedebaa5
CS
429 if (to < toend)
430 *to = '\0';
fc36a67e 431 *retlen = tolen;
73d840c0 432 return (char *)from;
8d063cd8
LW
433}
434
435/* return ptr to little string in big string, NULL if not found */
378cc40b 436/* This routine was donated by Corey Satten. */
8d063cd8
LW
437
438char *
04c9e624 439Perl_instr(register const char *big, register const char *little)
378cc40b 440{
79072805 441 register I32 first;
378cc40b 442
7918f24d
NC
443 PERL_ARGS_ASSERT_INSTR;
444
a687059c 445 if (!little)
08105a92 446 return (char*)big;
a687059c 447 first = *little++;
378cc40b 448 if (!first)
08105a92 449 return (char*)big;
378cc40b 450 while (*big) {
66a1b24b 451 register const char *s, *x;
378cc40b
LW
452 if (*big++ != first)
453 continue;
454 for (x=big,s=little; *s; /**/ ) {
455 if (!*x)
bd61b366 456 return NULL;
4fc877ac 457 if (*s != *x)
378cc40b 458 break;
4fc877ac
AL
459 else {
460 s++;
461 x++;
378cc40b
LW
462 }
463 }
464 if (!*s)
08105a92 465 return (char*)(big-1);
378cc40b 466 }
bd61b366 467 return NULL;
378cc40b 468}
8d063cd8 469
e057d092
KW
470/* same as instr but allow embedded nulls. The end pointers point to 1 beyond
471 * the final character desired to be checked */
a687059c
LW
472
473char *
04c9e624 474Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
8d063cd8 475{
7918f24d 476 PERL_ARGS_ASSERT_NINSTR;
4c8626be
GA
477 if (little >= lend)
478 return (char*)big;
479 {
8ba22ff4 480 const char first = *little;
4c8626be 481 const char *s, *x;
8ba22ff4 482 bigend -= lend - little++;
4c8626be
GA
483 OUTER:
484 while (big <= bigend) {
b0ca24ee
JH
485 if (*big++ == first) {
486 for (x=big,s=little; s < lend; x++,s++) {
487 if (*s != *x)
488 goto OUTER;
489 }
490 return (char*)(big-1);
4c8626be 491 }
4c8626be 492 }
378cc40b 493 }
bd61b366 494 return NULL;
a687059c
LW
495}
496
497/* reverse of the above--find last substring */
498
499char *
04c9e624 500Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
a687059c 501{
08105a92 502 register const char *bigbeg;
e1ec3a88 503 register const I32 first = *little;
7452cf6a 504 register const char * const littleend = lend;
a687059c 505
7918f24d
NC
506 PERL_ARGS_ASSERT_RNINSTR;
507
260d78c9 508 if (little >= littleend)
08105a92 509 return (char*)bigend;
a687059c
LW
510 bigbeg = big;
511 big = bigend - (littleend - little++);
512 while (big >= bigbeg) {
66a1b24b 513 register const char *s, *x;
a687059c
LW
514 if (*big-- != first)
515 continue;
516 for (x=big+2,s=little; s < littleend; /**/ ) {
4fc877ac 517 if (*s != *x)
a687059c 518 break;
4fc877ac
AL
519 else {
520 x++;
521 s++;
a687059c
LW
522 }
523 }
524 if (s >= littleend)
08105a92 525 return (char*)(big+1);
378cc40b 526 }
bd61b366 527 return NULL;
378cc40b 528}
a687059c 529
cf93c79d
IZ
530/* As a space optimization, we do not compile tables for strings of length
531 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
532 special-cased in fbm_instr().
533
534 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
535
954c1994 536/*
ccfc67b7
JH
537=head1 Miscellaneous Functions
538
954c1994
GS
539=for apidoc fbm_compile
540
541Analyses the string in order to make fast searches on it using fbm_instr()
542-- the Boyer-Moore algorithm.
543
544=cut
545*/
546
378cc40b 547void
7506f9c3 548Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
378cc40b 549{
97aff369 550 dVAR;
0d46e09a 551 register const U8 *s;
ea725ce6 552 STRLEN i;
0b71040e 553 STRLEN len;
ea725ce6 554 STRLEN rarest = 0;
79072805 555 U32 frequency = 256;
2bda37ba 556 MAGIC *mg;
79072805 557
7918f24d
NC
558 PERL_ARGS_ASSERT_FBM_COMPILE;
559
4265b45d
NC
560 /* Refuse to fbm_compile a studied scalar, as this gives more flexibility in
561 SV flag usage. No real-world code would ever end up using a studied
562 scalar as a compile-time second argument to index, so this isn't a real
563 pessimisation. */
564 if (SvSCREAM(sv))
565 return;
566
9402563a
NC
567 if (SvVALID(sv))
568 return;
569
c517dc2b 570 if (flags & FBMcf_TAIL) {
890ce7af 571 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
396482e1 572 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
c517dc2b
JH
573 if (mg && mg->mg_len >= 0)
574 mg->mg_len++;
575 }
9cbe880b 576 s = (U8*)SvPV_force_mutable(sv, len);
d1be9408 577 if (len == 0) /* TAIL might be on a zero-length string. */
cf93c79d 578 return;
c13a5c80 579 SvUPGRADE(sv, SVt_PVMG);
78d0cf80 580 SvIOK_off(sv);
8eeaf79a
NC
581 SvNOK_off(sv);
582 SvVALID_on(sv);
2bda37ba
NC
583
584 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
585 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
586 to call SvVALID_off() if the scalar was assigned to.
587
588 The comment itself (and "deeper magic" below) date back to
589 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
590 str->str_pok |= 2;
591 where the magic (presumably) was that the scalar had a BM table hidden
592 inside itself.
593
594 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
595 the table instead of the previous (somewhat hacky) approach of co-opting
596 the string buffer and storing it after the string. */
597
598 assert(!mg_find(sv, PERL_MAGIC_bm));
599 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
600 assert(mg);
601
02128f11 602 if (len > 2) {
21aeb718
NC
603 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
604 the BM table. */
66a1b24b 605 const U8 mlen = (len>255) ? 255 : (U8)len;
2bda37ba 606 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
890ce7af 607 register U8 *table;
cf93c79d 608
2bda37ba 609 Newx(table, 256, U8);
7506f9c3 610 memset((void*)table, mlen, 256);
2bda37ba
NC
611 mg->mg_ptr = (char *)table;
612 mg->mg_len = 256;
613
614 s += len - 1; /* last char */
02128f11 615 i = 0;
cf93c79d
IZ
616 while (s >= sb) {
617 if (table[*s] == mlen)
7506f9c3 618 table[*s] = (U8)i;
cf93c79d
IZ
619 s--, i++;
620 }
378cc40b 621 }
378cc40b 622
9cbe880b 623 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
bbce6d69 624 for (i = 0; i < len; i++) {
22c35a8c 625 if (PL_freq[s[i]] < frequency) {
bbce6d69 626 rarest = i;
22c35a8c 627 frequency = PL_freq[s[i]];
378cc40b
LW
628 }
629 }
79072805 630 BmRARE(sv) = s[rarest];
44a10c71 631 BmPREVIOUS(sv) = rarest;
cf93c79d
IZ
632 BmUSEFUL(sv) = 100; /* Initial value */
633 if (flags & FBMcf_TAIL)
634 SvTAIL_on(sv);
ea725ce6
NC
635 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
636 BmRARE(sv), BmPREVIOUS(sv)));
378cc40b
LW
637}
638
cf93c79d
IZ
639/* If SvTAIL(littlestr), it has a fake '\n' at end. */
640/* If SvTAIL is actually due to \Z or \z, this gives false positives
641 if multiline */
642
954c1994
GS
643/*
644=for apidoc fbm_instr
645
646Returns the location of the SV in the string delimited by C<str> and
bd61b366 647C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
954c1994
GS
648does not have to be fbm_compiled, but the search will not be as fast
649then.
650
651=cut
652*/
653
378cc40b 654char *
864dbfa3 655Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
378cc40b 656{
a687059c 657 register unsigned char *s;
cf93c79d 658 STRLEN l;
9cbe880b
NC
659 register const unsigned char *little
660 = (const unsigned char *)SvPV_const(littlestr,l);
cf93c79d 661 register STRLEN littlelen = l;
e1ec3a88 662 register const I32 multiline = flags & FBMrf_MULTILINE;
cf93c79d 663
7918f24d
NC
664 PERL_ARGS_ASSERT_FBM_INSTR;
665
eb160463 666 if ((STRLEN)(bigend - big) < littlelen) {
a1d180c4 667 if ( SvTAIL(littlestr)
eb160463 668 && ((STRLEN)(bigend - big) == littlelen - 1)
a1d180c4 669 && (littlelen == 1
12ae5dfc 670 || (*big == *little &&
27da23d5 671 memEQ((char *)big, (char *)little, littlelen - 1))))
cf93c79d 672 return (char*)big;
bd61b366 673 return NULL;
cf93c79d 674 }
378cc40b 675
21aeb718
NC
676 switch (littlelen) { /* Special cases for 0, 1 and 2 */
677 case 0:
678 return (char*)big; /* Cannot be SvTAIL! */
679 case 1:
cf93c79d
IZ
680 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
681 /* Know that bigend != big. */
682 if (bigend[-1] == '\n')
683 return (char *)(bigend - 1);
684 return (char *) bigend;
685 }
686 s = big;
687 while (s < bigend) {
688 if (*s == *little)
689 return (char *)s;
690 s++;
691 }
692 if (SvTAIL(littlestr))
693 return (char *) bigend;
bd61b366 694 return NULL;
21aeb718 695 case 2:
cf93c79d
IZ
696 if (SvTAIL(littlestr) && !multiline) {
697 if (bigend[-1] == '\n' && bigend[-2] == *little)
698 return (char*)bigend - 2;
699 if (bigend[-1] == *little)
700 return (char*)bigend - 1;
bd61b366 701 return NULL;
cf93c79d
IZ
702 }
703 {
704 /* This should be better than FBM if c1 == c2, and almost
705 as good otherwise: maybe better since we do less indirection.
706 And we save a lot of memory by caching no table. */
66a1b24b
AL
707 const unsigned char c1 = little[0];
708 const unsigned char c2 = little[1];
cf93c79d
IZ
709
710 s = big + 1;
711 bigend--;
712 if (c1 != c2) {
713 while (s <= bigend) {
714 if (s[0] == c2) {
715 if (s[-1] == c1)
716 return (char*)s - 1;
717 s += 2;
718 continue;
3fe6f2dc 719 }
cf93c79d
IZ
720 next_chars:
721 if (s[0] == c1) {
722 if (s == bigend)
723 goto check_1char_anchor;
724 if (s[1] == c2)
725 return (char*)s;
726 else {
727 s++;
728 goto next_chars;
729 }
730 }
731 else
732 s += 2;
733 }
734 goto check_1char_anchor;
735 }
736 /* Now c1 == c2 */
737 while (s <= bigend) {
738 if (s[0] == c1) {
739 if (s[-1] == c1)
740 return (char*)s - 1;
741 if (s == bigend)
742 goto check_1char_anchor;
743 if (s[1] == c1)
744 return (char*)s;
745 s += 3;
02128f11 746 }
c277df42 747 else
cf93c79d 748 s += 2;
c277df42 749 }
c277df42 750 }
cf93c79d
IZ
751 check_1char_anchor: /* One char and anchor! */
752 if (SvTAIL(littlestr) && (*bigend == *little))
753 return (char *)bigend; /* bigend is already decremented. */
bd61b366 754 return NULL;
21aeb718
NC
755 default:
756 break; /* Only lengths 0 1 and 2 have special-case code. */
d48672a2 757 }
21aeb718 758
cf93c79d 759 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
bbce6d69 760 s = bigend - littlelen;
a1d180c4 761 if (s >= big && bigend[-1] == '\n' && *s == *little
cf93c79d
IZ
762 /* Automatically of length > 2 */
763 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
7506f9c3 764 {
bbce6d69 765 return (char*)s; /* how sweet it is */
7506f9c3
GS
766 }
767 if (s[1] == *little
768 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
769 {
cf93c79d 770 return (char*)s + 1; /* how sweet it is */
7506f9c3 771 }
bd61b366 772 return NULL;
02128f11 773 }
cecf5685 774 if (!SvVALID(littlestr)) {
c4420975 775 char * const b = ninstr((char*)big,(char*)bigend,
cf93c79d
IZ
776 (char*)little, (char*)little + littlelen);
777
778 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
779 /* Chop \n from littlestr: */
780 s = bigend - littlelen + 1;
7506f9c3
GS
781 if (*s == *little
782 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
783 {
3fe6f2dc 784 return (char*)s;
7506f9c3 785 }
bd61b366 786 return NULL;
a687059c 787 }
cf93c79d 788 return b;
a687059c 789 }
a1d180c4 790
3566a07d
NC
791 /* Do actual FBM. */
792 if (littlelen > (STRLEN)(bigend - big))
793 return NULL;
794
795 {
2bda37ba
NC
796 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
797 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
0d46e09a 798 register const unsigned char *oldlittle;
cf93c79d 799
cf93c79d
IZ
800 --littlelen; /* Last char found by table lookup */
801
802 s = big + littlelen;
803 little += littlelen; /* last char */
804 oldlittle = little;
805 if (s < bigend) {
806 register I32 tmp;
807
808 top2:
7506f9c3 809 if ((tmp = table[*s])) {
cf93c79d 810 if ((s += tmp) < bigend)
62b28dd9 811 goto top2;
cf93c79d
IZ
812 goto check_end;
813 }
814 else { /* less expensive than calling strncmp() */
66a1b24b 815 register unsigned char * const olds = s;
cf93c79d
IZ
816
817 tmp = littlelen;
818
819 while (tmp--) {
820 if (*--s == *--little)
821 continue;
cf93c79d
IZ
822 s = olds + 1; /* here we pay the price for failure */
823 little = oldlittle;
824 if (s < bigend) /* fake up continue to outer loop */
825 goto top2;
826 goto check_end;
827 }
828 return (char *)s;
a687059c 829 }
378cc40b 830 }
cf93c79d 831 check_end:
c8029a41 832 if ( s == bigend
cffe132d 833 && SvTAIL(littlestr)
12ae5dfc
JH
834 && memEQ((char *)(bigend - littlelen),
835 (char *)(oldlittle - littlelen), littlelen) )
cf93c79d 836 return (char*)bigend - littlelen;
bd61b366 837 return NULL;
378cc40b 838 }
378cc40b
LW
839}
840
c277df42
IZ
841/* start_shift, end_shift are positive quantities which give offsets
842 of ends of some substring of bigstr.
a0288114 843 If "last" we want the last occurrence.
c277df42 844 old_posp is the way of communication between consequent calls if
a1d180c4 845 the next call needs to find the .
c277df42 846 The initial *old_posp should be -1.
cf93c79d
IZ
847
848 Note that we take into account SvTAIL, so one can get extra
849 optimizations if _ALL flag is set.
c277df42
IZ
850 */
851
cf93c79d 852/* If SvTAIL is actually due to \Z or \z, this gives false positives
26fa51c3 853 if PL_multiline. In fact if !PL_multiline the authoritative answer
cf93c79d
IZ
854 is not supported yet. */
855
378cc40b 856char *
864dbfa3 857Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
378cc40b 858{
97aff369 859 dVAR;
0d46e09a 860 register const unsigned char *big;
72de20cd 861 U32 pos = 0; /* hush a gcc warning */
79072805
LW
862 register I32 previous;
863 register I32 first;
0d46e09a 864 register const unsigned char *little;
c277df42 865 register I32 stop_pos;
0d46e09a 866 register const unsigned char *littleend;
378b4d0f 867 bool found = FALSE;
4185c919 868 const MAGIC * mg;
72de20cd
NC
869 const void *screamnext_raw = NULL; /* hush a gcc warning */
870 bool cant_find = FALSE; /* hush a gcc warning */
378cc40b 871
7918f24d
NC
872 PERL_ARGS_ASSERT_SCREAMINSTR;
873
4185c919
NC
874 assert(SvMAGICAL(bigstr));
875 mg = mg_find(bigstr, PERL_MAGIC_study);
876 assert(mg);
c13a5c80 877 assert(SvTYPE(littlestr) == SVt_PVMG);
cecf5685 878 assert(SvVALID(littlestr));
d372c834 879
72de20cd
NC
880 if (mg->mg_private == 1) {
881 const U8 *const screamfirst = (U8 *)mg->mg_ptr;
882 const U8 *const screamnext = screamfirst + 256;
4185c919 883
72de20cd
NC
884 screamnext_raw = (const void *)screamnext;
885
886 pos = *old_posp == -1
887 ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
888 cant_find = pos == (U8)~0;
889 } else if (mg->mg_private == 2) {
890 const U16 *const screamfirst = (U16 *)mg->mg_ptr;
891 const U16 *const screamnext = screamfirst + 256;
892
893 screamnext_raw = (const void *)screamnext;
894
895 pos = *old_posp == -1
896 ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
897 cant_find = pos == (U16)~0;
898 } else if (mg->mg_private == 4) {
899 const U32 *const screamfirst = (U32 *)mg->mg_ptr;
900 const U32 *const screamnext = screamfirst + 256;
901
902 screamnext_raw = (const void *)screamnext;
903
904 pos = *old_posp == -1
905 ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
906 cant_find = pos == (U32)~0;
907 } else
908 Perl_croak(aTHX_ "panic: unknown study size %u", mg->mg_private);
909
910 if (cant_find) {
cf93c79d 911 cant_find:
a1d180c4 912 if ( BmRARE(littlestr) == '\n'
85c508c3 913 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
cfd0369c 914 little = (const unsigned char *)(SvPVX_const(littlestr));
cf93c79d
IZ
915 littleend = little + SvCUR(littlestr);
916 first = *little++;
917 goto check_tail;
918 }
bd61b366 919 return NULL;
cf93c79d
IZ
920 }
921
cfd0369c 922 little = (const unsigned char *)(SvPVX_const(littlestr));
79072805 923 littleend = little + SvCUR(littlestr);
378cc40b 924 first = *little++;
c277df42 925 /* The value of pos we can start at: */
79072805 926 previous = BmPREVIOUS(littlestr);
cfd0369c 927 big = (const unsigned char *)(SvPVX_const(bigstr));
c277df42
IZ
928 /* The value of pos we can stop at: */
929 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
cf93c79d 930 if (previous + start_shift > stop_pos) {
0fe87f7c
HS
931/*
932 stop_pos does not include SvTAIL in the count, so this check is incorrect
933 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
934*/
935#if 0
cf93c79d
IZ
936 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
937 goto check_tail;
0fe87f7c 938#endif
bd61b366 939 return NULL;
cf93c79d 940 }
72de20cd
NC
941 if (mg->mg_private == 1) {
942 const U8 *const screamnext = (const U8 *const) screamnext_raw;
943 while ((I32)pos < previous + start_shift) {
944 pos = screamnext[pos];
945 if (pos == (U8)~0)
946 goto cant_find;
947 }
948 } else if (mg->mg_private == 2) {
949 const U16 *const screamnext = (const U16 *const) screamnext_raw;
950 while ((I32)pos < previous + start_shift) {
951 pos = screamnext[pos];
952 if (pos == (U16)~0)
953 goto cant_find;
954 }
955 } else if (mg->mg_private == 4) {
956 const U32 *const screamnext = (const U32 *const) screamnext_raw;
957 while ((I32)pos < previous + start_shift) {
958 pos = screamnext[pos];
959 if (pos == (U32)~0)
960 goto cant_find;
961 }
378cc40b 962 }
de3bb511 963 big -= previous;
72de20cd 964 while (1) {
b606cf7f 965 if ((I32)pos >= stop_pos) break;
56e9eeb1 966 if (big[pos] == first) {
378b4d0f
NC
967 const unsigned char *s = little;
968 const unsigned char *x = big + pos + 1;
969 while (s < littleend) {
970 if (*s != *x++)
56e9eeb1 971 break;
378b4d0f 972 ++s;
56e9eeb1
NC
973 }
974 if (s == littleend) {
b606cf7f 975 *old_posp = (I32)pos;
56e9eeb1 976 if (!last) return (char *)(big+pos);
378b4d0f 977 found = TRUE;
378cc40b 978 }
bbce6d69 979 }
72de20cd
NC
980 if (mg->mg_private == 1) {
981 pos = ((const U8 *const)screamnext_raw)[pos];
982 if (pos == (U8)~0)
983 break;
984 } else if (mg->mg_private == 2) {
985 pos = ((const U16 *const)screamnext_raw)[pos];
986 if (pos == (U16)~0)
987 break;
988 } else if (mg->mg_private == 4) {
989 pos = ((const U32 *const)screamnext_raw)[pos];
990 if (pos == (U32)~0)
991 break;
992 }
993 };
a1d180c4 994 if (last && found)
cf93c79d 995 return (char *)(big+(*old_posp));
cf93c79d
IZ
996 check_tail:
997 if (!SvTAIL(littlestr) || (end_shift > 0))
bd61b366 998 return NULL;
cf93c79d 999 /* Ignore the trailing "\n". This code is not microoptimized */
cfd0369c 1000 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
cf93c79d
IZ
1001 stop_pos = littleend - little; /* Actual littlestr len */
1002 if (stop_pos == 0)
1003 return (char*)big;
1004 big -= stop_pos;
1005 if (*big == first
12ae5dfc
JH
1006 && ((stop_pos == 1) ||
1007 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
cf93c79d 1008 return (char*)big;
bd61b366 1009 return NULL;
8d063cd8
LW
1010}
1011
e6226b18
KW
1012/*
1013=for apidoc foldEQ
1014
1015Returns true if the leading len bytes of the strings s1 and s2 are the same
1016case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
1017match themselves and their opposite case counterparts. Non-cased and non-ASCII
1018range bytes match only themselves.
1019
1020=cut
1021*/
1022
1023
79072805 1024I32
e6226b18 1025Perl_foldEQ(const char *s1, const char *s2, register I32 len)
79072805 1026{
e1ec3a88
AL
1027 register const U8 *a = (const U8 *)s1;
1028 register const U8 *b = (const U8 *)s2;
96a5add6 1029
e6226b18 1030 PERL_ARGS_ASSERT_FOLDEQ;
7918f24d 1031
79072805 1032 while (len--) {
22c35a8c 1033 if (*a != *b && *a != PL_fold[*b])
e6226b18 1034 return 0;
bbce6d69 1035 a++,b++;
1036 }
e6226b18 1037 return 1;
bbce6d69 1038}
1b9f127b
KW
1039I32
1040Perl_foldEQ_latin1(const char *s1, const char *s2, register I32 len)
1041{
1042 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
1043 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
1044 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
1045 * does it check that the strings each have at least 'len' characters */
1046
1047 register const U8 *a = (const U8 *)s1;
1048 register const U8 *b = (const U8 *)s2;
1049
1050 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
1051
1052 while (len--) {
1053 if (*a != *b && *a != PL_fold_latin1[*b]) {
1054 return 0;
1055 }
1056 a++, b++;
1057 }
1058 return 1;
1059}
bbce6d69 1060
e6226b18
KW
1061/*
1062=for apidoc foldEQ_locale
1063
1064Returns true if the leading len bytes of the strings s1 and s2 are the same
1065case-insensitively in the current locale; false otherwise.
1066
1067=cut
1068*/
1069
bbce6d69 1070I32
e6226b18 1071Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
bbce6d69 1072{
27da23d5 1073 dVAR;
e1ec3a88
AL
1074 register const U8 *a = (const U8 *)s1;
1075 register const U8 *b = (const U8 *)s2;
96a5add6 1076
e6226b18 1077 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
7918f24d 1078
bbce6d69 1079 while (len--) {
22c35a8c 1080 if (*a != *b && *a != PL_fold_locale[*b])
e6226b18 1081 return 0;
bbce6d69 1082 a++,b++;
79072805 1083 }
e6226b18 1084 return 1;
79072805
LW
1085}
1086
8d063cd8
LW
1087/* copy a string to a safe spot */
1088
954c1994 1089/*
ccfc67b7
JH
1090=head1 Memory Management
1091
954c1994
GS
1092=for apidoc savepv
1093
61a925ed
AMS
1094Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1095string which is a duplicate of C<pv>. The size of the string is
1096determined by C<strlen()>. The memory allocated for the new string can
1097be freed with the C<Safefree()> function.
954c1994
GS
1098
1099=cut
1100*/
1101
8d063cd8 1102char *
efdfce31 1103Perl_savepv(pTHX_ const char *pv)
8d063cd8 1104{
96a5add6 1105 PERL_UNUSED_CONTEXT;
e90e2364 1106 if (!pv)
bd61b366 1107 return NULL;
66a1b24b
AL
1108 else {
1109 char *newaddr;
1110 const STRLEN pvlen = strlen(pv)+1;
10edeb5d
JH
1111 Newx(newaddr, pvlen, char);
1112 return (char*)memcpy(newaddr, pv, pvlen);
66a1b24b 1113 }
8d063cd8
LW
1114}
1115
a687059c
LW
1116/* same thing but with a known length */
1117
954c1994
GS
1118/*
1119=for apidoc savepvn
1120
61a925ed
AMS
1121Perl's version of what C<strndup()> would be if it existed. Returns a
1122pointer to a newly allocated string which is a duplicate of the first
cbf82dd0
NC
1123C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
1124the new string can be freed with the C<Safefree()> function.
954c1994
GS
1125
1126=cut
1127*/
1128
a687059c 1129char *
efdfce31 1130Perl_savepvn(pTHX_ const char *pv, register I32 len)
a687059c
LW
1131{
1132 register char *newaddr;
96a5add6 1133 PERL_UNUSED_CONTEXT;
a687059c 1134
a02a5408 1135 Newx(newaddr,len+1,char);
92110913 1136 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
efdfce31 1137 if (pv) {
e90e2364
NC
1138 /* might not be null terminated */
1139 newaddr[len] = '\0';
07409e01 1140 return (char *) CopyD(pv,newaddr,len,char);
92110913
NIS
1141 }
1142 else {
07409e01 1143 return (char *) ZeroD(newaddr,len+1,char);
92110913 1144 }
a687059c
LW
1145}
1146
05ec9bb3
NIS
1147/*
1148=for apidoc savesharedpv
1149
61a925ed
AMS
1150A version of C<savepv()> which allocates the duplicate string in memory
1151which is shared between threads.
05ec9bb3
NIS
1152
1153=cut
1154*/
1155char *
efdfce31 1156Perl_savesharedpv(pTHX_ const char *pv)
05ec9bb3 1157{
e90e2364 1158 register char *newaddr;
490a0e98 1159 STRLEN pvlen;
e90e2364 1160 if (!pv)
bd61b366 1161 return NULL;
e90e2364 1162
490a0e98
NC
1163 pvlen = strlen(pv)+1;
1164 newaddr = (char*)PerlMemShared_malloc(pvlen);
e90e2364 1165 if (!newaddr) {
0bd48802 1166 return write_no_mem();
05ec9bb3 1167 }
10edeb5d 1168 return (char*)memcpy(newaddr, pv, pvlen);
05ec9bb3
NIS
1169}
1170
2e0de35c 1171/*
d9095cec
NC
1172=for apidoc savesharedpvn
1173
1174A version of C<savepvn()> which allocates the duplicate string in memory
1175which is shared between threads. (With the specific difference that a NULL
1176pointer is not acceptable)
1177
1178=cut
1179*/
1180char *
1181Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1182{
1183 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
7918f24d 1184
6379d4a9 1185 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
7918f24d 1186
d9095cec
NC
1187 if (!newaddr) {
1188 return write_no_mem();
1189 }
1190 newaddr[len] = '\0';
1191 return (char*)memcpy(newaddr, pv, len);
1192}
1193
1194/*
2e0de35c
NC
1195=for apidoc savesvpv
1196
6832267f 1197A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
2e0de35c
NC
1198the passed in SV using C<SvPV()>
1199
1200=cut
1201*/
1202
1203char *
1204Perl_savesvpv(pTHX_ SV *sv)
1205{
1206 STRLEN len;
7452cf6a 1207 const char * const pv = SvPV_const(sv, len);
2e0de35c
NC
1208 register char *newaddr;
1209
7918f24d
NC
1210 PERL_ARGS_ASSERT_SAVESVPV;
1211
26866f99 1212 ++len;
a02a5408 1213 Newx(newaddr,len,char);
07409e01 1214 return (char *) CopyD(pv,newaddr,len,char);
2e0de35c 1215}
05ec9bb3 1216
9dcc53ea
Z
1217/*
1218=for apidoc savesharedsvpv
1219
1220A version of C<savesharedpv()> which allocates the duplicate string in
1221memory which is shared between threads.
1222
1223=cut
1224*/
1225
1226char *
1227Perl_savesharedsvpv(pTHX_ SV *sv)
1228{
1229 STRLEN len;
1230 const char * const pv = SvPV_const(sv, len);
1231
1232 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1233
1234 return savesharedpvn(pv, len);
1235}
05ec9bb3 1236
cea2e8a9 1237/* the SV for Perl_form() and mess() is not kept in an arena */
fc36a67e 1238
76e3520e 1239STATIC SV *
cea2e8a9 1240S_mess_alloc(pTHX)
fc36a67e 1241{
97aff369 1242 dVAR;
fc36a67e 1243 SV *sv;
1244 XPVMG *any;
1245
627364f1 1246 if (PL_phase != PERL_PHASE_DESTRUCT)
84bafc02 1247 return newSVpvs_flags("", SVs_TEMP);
e72dc28c 1248
0372dbb6
GS
1249 if (PL_mess_sv)
1250 return PL_mess_sv;
1251
fc36a67e 1252 /* Create as PVMG now, to avoid any upgrading later */
a02a5408
JC
1253 Newx(sv, 1, SV);
1254 Newxz(any, 1, XPVMG);
fc36a67e 1255 SvFLAGS(sv) = SVt_PVMG;
1256 SvANY(sv) = (void*)any;
6136c704 1257 SvPV_set(sv, NULL);
fc36a67e 1258 SvREFCNT(sv) = 1 << 30; /* practically infinite */
e72dc28c 1259 PL_mess_sv = sv;
fc36a67e 1260 return sv;
1261}
1262
c5be433b 1263#if defined(PERL_IMPLICIT_CONTEXT)
cea2e8a9
GS
1264char *
1265Perl_form_nocontext(const char* pat, ...)
1266{
1267 dTHX;
c5be433b 1268 char *retval;
cea2e8a9 1269 va_list args;
7918f24d 1270 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
cea2e8a9 1271 va_start(args, pat);
c5be433b 1272 retval = vform(pat, &args);
cea2e8a9 1273 va_end(args);
c5be433b 1274 return retval;
cea2e8a9 1275}
c5be433b 1276#endif /* PERL_IMPLICIT_CONTEXT */
cea2e8a9 1277
7c9e965c 1278/*
ccfc67b7 1279=head1 Miscellaneous Functions
7c9e965c
JP
1280=for apidoc form
1281
1282Takes a sprintf-style format pattern and conventional
1283(non-SV) arguments and returns the formatted string.
1284
1285 (char *) Perl_form(pTHX_ const char* pat, ...)
1286
1287can be used any place a string (char *) is required:
1288
1289 char * s = Perl_form("%d.%d",major,minor);
1290
1291Uses a single private buffer so if you want to format several strings you
1292must explicitly copy the earlier strings away (and free the copies when you
1293are done).
1294
1295=cut
1296*/
1297
8990e307 1298char *
864dbfa3 1299Perl_form(pTHX_ const char* pat, ...)
8990e307 1300{
c5be433b 1301 char *retval;
46fc3d4c 1302 va_list args;
7918f24d 1303 PERL_ARGS_ASSERT_FORM;
46fc3d4c 1304 va_start(args, pat);
c5be433b 1305 retval = vform(pat, &args);
46fc3d4c 1306 va_end(args);
c5be433b
GS
1307 return retval;
1308}
1309
1310char *
1311Perl_vform(pTHX_ const char *pat, va_list *args)
1312{
2d03de9c 1313 SV * const sv = mess_alloc();
7918f24d 1314 PERL_ARGS_ASSERT_VFORM;
4608196e 1315 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
e72dc28c 1316 return SvPVX(sv);
46fc3d4c 1317}
a687059c 1318
c5df3096
Z
1319/*
1320=for apidoc Am|SV *|mess|const char *pat|...
1321
1322Take a sprintf-style format pattern and argument list. These are used to
1323generate a string message. If the message does not end with a newline,
1324then it will be extended with some indication of the current location
1325in the code, as described for L</mess_sv>.
1326
1327Normally, the resulting message is returned in a new mortal SV.
1328During global destruction a single SV may be shared between uses of
1329this function.
1330
1331=cut
1332*/
1333
5a844595
GS
1334#if defined(PERL_IMPLICIT_CONTEXT)
1335SV *
1336Perl_mess_nocontext(const char *pat, ...)
1337{
1338 dTHX;
1339 SV *retval;
1340 va_list args;
7918f24d 1341 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
5a844595
GS
1342 va_start(args, pat);
1343 retval = vmess(pat, &args);
1344 va_end(args);
1345 return retval;
1346}
1347#endif /* PERL_IMPLICIT_CONTEXT */
1348
06bf62c7 1349SV *
5a844595
GS
1350Perl_mess(pTHX_ const char *pat, ...)
1351{
1352 SV *retval;
1353 va_list args;
7918f24d 1354 PERL_ARGS_ASSERT_MESS;
5a844595
GS
1355 va_start(args, pat);
1356 retval = vmess(pat, &args);
1357 va_end(args);
1358 return retval;
1359}
1360
5f66b61c
AL
1361STATIC const COP*
1362S_closest_cop(pTHX_ const COP *cop, const OP *o)
ae7d165c 1363{
97aff369 1364 dVAR;
ae7d165c
PJ
1365 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1366
7918f24d
NC
1367 PERL_ARGS_ASSERT_CLOSEST_COP;
1368
fabdb6c0
AL
1369 if (!o || o == PL_op)
1370 return cop;
ae7d165c
PJ
1371
1372 if (o->op_flags & OPf_KIDS) {
5f66b61c 1373 const OP *kid;
fabdb6c0 1374 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
5f66b61c 1375 const COP *new_cop;
ae7d165c
PJ
1376
1377 /* If the OP_NEXTSTATE has been optimised away we can still use it
1378 * the get the file and line number. */
1379
1380 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
5f66b61c 1381 cop = (const COP *)kid;
ae7d165c
PJ
1382
1383 /* Keep searching, and return when we've found something. */
1384
1385 new_cop = closest_cop(cop, kid);
fabdb6c0
AL
1386 if (new_cop)
1387 return new_cop;
ae7d165c
PJ
1388 }
1389 }
1390
1391 /* Nothing found. */
1392
5f66b61c 1393 return NULL;
ae7d165c
PJ
1394}
1395
c5df3096
Z
1396/*
1397=for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1398
1399Expands a message, intended for the user, to include an indication of
1400the current location in the code, if the message does not already appear
1401to be complete.
1402
1403C<basemsg> is the initial message or object. If it is a reference, it
1404will be used as-is and will be the result of this function. Otherwise it
1405is used as a string, and if it already ends with a newline, it is taken
1406to be complete, and the result of this function will be the same string.
1407If the message does not end with a newline, then a segment such as C<at
1408foo.pl line 37> will be appended, and possibly other clauses indicating
1409the current state of execution. The resulting message will end with a
1410dot and a newline.
1411
1412Normally, the resulting message is returned in a new mortal SV.
1413During global destruction a single SV may be shared between uses of this
1414function. If C<consume> is true, then the function is permitted (but not
1415required) to modify and return C<basemsg> instead of allocating a new SV.
1416
1417=cut
1418*/
1419
5a844595 1420SV *
c5df3096 1421Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
46fc3d4c 1422{
97aff369 1423 dVAR;
c5df3096 1424 SV *sv;
46fc3d4c 1425
c5df3096
Z
1426 PERL_ARGS_ASSERT_MESS_SV;
1427
1428 if (SvROK(basemsg)) {
1429 if (consume) {
1430 sv = basemsg;
1431 }
1432 else {
1433 sv = mess_alloc();
1434 sv_setsv(sv, basemsg);
1435 }
1436 return sv;
1437 }
1438
1439 if (SvPOK(basemsg) && consume) {
1440 sv = basemsg;
1441 }
1442 else {
1443 sv = mess_alloc();
1444 sv_copypv(sv, basemsg);
1445 }
7918f24d 1446
46fc3d4c 1447 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
ae7d165c
PJ
1448 /*
1449 * Try and find the file and line for PL_op. This will usually be
1450 * PL_curcop, but it might be a cop that has been optimised away. We
1451 * can try to find such a cop by searching through the optree starting
1452 * from the sibling of PL_curcop.
1453 */
1454
e1ec3a88 1455 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
5f66b61c
AL
1456 if (!cop)
1457 cop = PL_curcop;
ae7d165c
PJ
1458
1459 if (CopLINE(cop))
ed094faf 1460 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
3aed30dc 1461 OutCopFILE(cop), (IV)CopLINE(cop));
191f87d5
DH
1462 /* Seems that GvIO() can be untrustworthy during global destruction. */
1463 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1464 && IoLINES(GvIOp(PL_last_in_gv)))
1465 {
e1ec3a88 1466 const bool line_mode = (RsSIMPLE(PL_rs) &&
95a20fc0 1467 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
3b46b707
BF
1468 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1469 SVfARG(PL_last_in_gv == PL_argvgv
1470 ? &PL_sv_no
1471 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
edc2eac3
JH
1472 line_mode ? "line" : "chunk",
1473 (IV)IoLINES(GvIOp(PL_last_in_gv)));
a687059c 1474 }
627364f1 1475 if (PL_phase == PERL_PHASE_DESTRUCT)
5f66b61c
AL
1476 sv_catpvs(sv, " during global destruction");
1477 sv_catpvs(sv, ".\n");
a687059c 1478 }
06bf62c7 1479 return sv;
a687059c
LW
1480}
1481
c5df3096
Z
1482/*
1483=for apidoc Am|SV *|vmess|const char *pat|va_list *args
1484
1485C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1486argument list. These are used to generate a string message. If the
1487message does not end with a newline, then it will be extended with
1488some indication of the current location in the code, as described for
1489L</mess_sv>.
1490
1491Normally, the resulting message is returned in a new mortal SV.
1492During global destruction a single SV may be shared between uses of
1493this function.
1494
1495=cut
1496*/
1497
1498SV *
1499Perl_vmess(pTHX_ const char *pat, va_list *args)
1500{
1501 dVAR;
1502 SV * const sv = mess_alloc();
1503
1504 PERL_ARGS_ASSERT_VMESS;
1505
1506 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1507 return mess_sv(sv, 1);
1508}
1509
7ff03255 1510void
7d0994e0 1511Perl_write_to_stderr(pTHX_ SV* msv)
7ff03255 1512{
27da23d5 1513 dVAR;
7ff03255
SG
1514 IO *io;
1515 MAGIC *mg;
1516
7918f24d
NC
1517 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1518
7ff03255
SG
1519 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1520 && (io = GvIO(PL_stderrgv))
daba3364 1521 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
d1d7a15d
NC
1522 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1523 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
7ff03255
SG
1524 else {
1525#ifdef USE_SFIO
1526 /* SFIO can really mess with your errno */
4ee39169 1527 dSAVED_ERRNO;
7ff03255 1528#endif
53c1dcc0 1529 PerlIO * const serr = Perl_error_log;
7ff03255 1530
83c55556 1531 do_print(msv, serr);
7ff03255
SG
1532 (void)PerlIO_flush(serr);
1533#ifdef USE_SFIO
4ee39169 1534 RESTORE_ERRNO;
7ff03255
SG
1535#endif
1536 }
1537}
1538
c5df3096
Z
1539/*
1540=head1 Warning and Dieing
1541*/
1542
1543/* Common code used in dieing and warning */
1544
1545STATIC SV *
1546S_with_queued_errors(pTHX_ SV *ex)
1547{
1548 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1549 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1550 sv_catsv(PL_errors, ex);
1551 ex = sv_mortalcopy(PL_errors);
1552 SvCUR_set(PL_errors, 0);
1553 }
1554 return ex;
1555}
3ab1ac99 1556
46d9c920 1557STATIC bool
c5df3096 1558S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
63315e18 1559{
97aff369 1560 dVAR;
63315e18
NC
1561 HV *stash;
1562 GV *gv;
1563 CV *cv;
46d9c920
NC
1564 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1565 /* sv_2cv might call Perl_croak() or Perl_warner() */
1566 SV * const oldhook = *hook;
1567
c5df3096
Z
1568 if (!oldhook)
1569 return FALSE;
63315e18 1570
63315e18 1571 ENTER;
46d9c920
NC
1572 SAVESPTR(*hook);
1573 *hook = NULL;
1574 cv = sv_2cv(oldhook, &stash, &gv, 0);
63315e18
NC
1575 LEAVE;
1576 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1577 dSP;
c5df3096 1578 SV *exarg;
63315e18
NC
1579
1580 ENTER;
1581 save_re_context();
46d9c920
NC
1582 if (warn) {
1583 SAVESPTR(*hook);
1584 *hook = NULL;
1585 }
c5df3096
Z
1586 exarg = newSVsv(ex);
1587 SvREADONLY_on(exarg);
1588 SAVEFREESV(exarg);
63315e18 1589
46d9c920 1590 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
63315e18 1591 PUSHMARK(SP);
c5df3096 1592 XPUSHs(exarg);
63315e18 1593 PUTBACK;
daba3364 1594 call_sv(MUTABLE_SV(cv), G_DISCARD);
63315e18
NC
1595 POPSTACK;
1596 LEAVE;
46d9c920 1597 return TRUE;
63315e18 1598 }
46d9c920 1599 return FALSE;
63315e18
NC
1600}
1601
c5df3096
Z
1602/*
1603=for apidoc Am|OP *|die_sv|SV *baseex
e07360fa 1604
c5df3096
Z
1605Behaves the same as L</croak_sv>, except for the return type.
1606It should be used only where the C<OP *> return type is required.
1607The function never actually returns.
e07360fa 1608
c5df3096
Z
1609=cut
1610*/
e07360fa 1611
c5df3096
Z
1612OP *
1613Perl_die_sv(pTHX_ SV *baseex)
36477c24 1614{
c5df3096
Z
1615 PERL_ARGS_ASSERT_DIE_SV;
1616 croak_sv(baseex);
ad09800f
GG
1617 /* NOTREACHED */
1618 return NULL;
36477c24 1619}
1620
c5df3096
Z
1621/*
1622=for apidoc Am|OP *|die|const char *pat|...
1623
1624Behaves the same as L</croak>, except for the return type.
1625It should be used only where the C<OP *> return type is required.
1626The function never actually returns.
1627
1628=cut
1629*/
1630
c5be433b 1631#if defined(PERL_IMPLICIT_CONTEXT)
cea2e8a9
GS
1632OP *
1633Perl_die_nocontext(const char* pat, ...)
a687059c 1634{
cea2e8a9 1635 dTHX;
a687059c 1636 va_list args;
cea2e8a9 1637 va_start(args, pat);
c5df3096
Z
1638 vcroak(pat, &args);
1639 /* NOTREACHED */
cea2e8a9 1640 va_end(args);
c5df3096 1641 return NULL;
cea2e8a9 1642}
c5be433b 1643#endif /* PERL_IMPLICIT_CONTEXT */
cea2e8a9
GS
1644
1645OP *
1646Perl_die(pTHX_ const char* pat, ...)
1647{
cea2e8a9
GS
1648 va_list args;
1649 va_start(args, pat);
c5df3096
Z
1650 vcroak(pat, &args);
1651 /* NOTREACHED */
cea2e8a9 1652 va_end(args);
c5df3096 1653 return NULL;
cea2e8a9
GS
1654}
1655
c5df3096
Z
1656/*
1657=for apidoc Am|void|croak_sv|SV *baseex
1658
1659This is an XS interface to Perl's C<die> function.
1660
1661C<baseex> is the error message or object. If it is a reference, it
1662will be used as-is. Otherwise it is used as a string, and if it does
1663not end with a newline then it will be extended with some indication of
1664the current location in the code, as described for L</mess_sv>.
1665
1666The error message or object will be used as an exception, by default
1667returning control to the nearest enclosing C<eval>, but subject to
1668modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1669function never returns normally.
1670
1671To die with a simple string message, the L</croak> function may be
1672more convenient.
1673
1674=cut
1675*/
1676
c5be433b 1677void
c5df3096 1678Perl_croak_sv(pTHX_ SV *baseex)
cea2e8a9 1679{
c5df3096
Z
1680 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1681 PERL_ARGS_ASSERT_CROAK_SV;
1682 invoke_exception_hook(ex, FALSE);
1683 die_unwind(ex);
1684}
1685
1686/*
1687=for apidoc Am|void|vcroak|const char *pat|va_list *args
1688
1689This is an XS interface to Perl's C<die> function.
1690
1691C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1692argument list. These are used to generate a string message. If the
1693message does not end with a newline, then it will be extended with
1694some indication of the current location in the code, as described for
1695L</mess_sv>.
1696
1697The error message will be used as an exception, by default
1698returning control to the nearest enclosing C<eval>, but subject to
1699modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1700function never returns normally.
a687059c 1701
c5df3096
Z
1702For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1703(C<$@>) will be used as an error message or object instead of building an
1704error message from arguments. If you want to throw a non-string object,
1705or build an error message in an SV yourself, it is preferable to use
1706the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
5a844595 1707
c5df3096
Z
1708=cut
1709*/
1710
1711void
1712Perl_vcroak(pTHX_ const char* pat, va_list *args)
1713{
1714 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1715 invoke_exception_hook(ex, FALSE);
1716 die_unwind(ex);
a687059c
LW
1717}
1718
c5df3096
Z
1719/*
1720=for apidoc Am|void|croak|const char *pat|...
1721
1722This is an XS interface to Perl's C<die> function.
1723
1724Take a sprintf-style format pattern and argument list. These are used to
1725generate a string message. If the message does not end with a newline,
1726then it will be extended with some indication of the current location
1727in the code, as described for L</mess_sv>.
1728
1729The error message will be used as an exception, by default
1730returning control to the nearest enclosing C<eval>, but subject to
1731modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1732function never returns normally.
1733
1734For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1735(C<$@>) will be used as an error message or object instead of building an
1736error message from arguments. If you want to throw a non-string object,
1737or build an error message in an SV yourself, it is preferable to use
1738the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1739
1740=cut
1741*/
1742
c5be433b 1743#if defined(PERL_IMPLICIT_CONTEXT)
8990e307 1744void
cea2e8a9 1745Perl_croak_nocontext(const char *pat, ...)
a687059c 1746{
cea2e8a9 1747 dTHX;
a687059c 1748 va_list args;
cea2e8a9 1749 va_start(args, pat);
c5be433b 1750 vcroak(pat, &args);
cea2e8a9
GS
1751 /* NOTREACHED */
1752 va_end(args);
1753}
1754#endif /* PERL_IMPLICIT_CONTEXT */
1755
c5df3096
Z
1756void
1757Perl_croak(pTHX_ const char *pat, ...)
1758{
1759 va_list args;
1760 va_start(args, pat);
1761 vcroak(pat, &args);
1762 /* NOTREACHED */
1763 va_end(args);
1764}
1765
954c1994 1766/*
6ad8f254
NC
1767=for apidoc Am|void|croak_no_modify
1768
1769Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1770terser object code than using C<Perl_croak>. Less code used on exception code
1771paths reduces CPU cache pressure.
1772
d8e47b5c 1773=cut
6ad8f254
NC
1774*/
1775
1776void
1777Perl_croak_no_modify(pTHX)
1778{
1779 Perl_croak(aTHX_ "%s", PL_no_modify);
1780}
1781
1782/*
c5df3096 1783=for apidoc Am|void|warn_sv|SV *baseex
ccfc67b7 1784
c5df3096 1785This is an XS interface to Perl's C<warn> function.
954c1994 1786
c5df3096
Z
1787C<baseex> is the error message or object. If it is a reference, it
1788will be used as-is. Otherwise it is used as a string, and if it does
1789not end with a newline then it will be extended with some indication of
1790the current location in the code, as described for L</mess_sv>.
9983fa3c 1791
c5df3096
Z
1792The error message or object will by default be written to standard error,
1793but this is subject to modification by a C<$SIG{__WARN__}> handler.
9983fa3c 1794
c5df3096
Z
1795To warn with a simple string message, the L</warn> function may be
1796more convenient.
954c1994
GS
1797
1798=cut
1799*/
1800
cea2e8a9 1801void
c5df3096 1802Perl_warn_sv(pTHX_ SV *baseex)
cea2e8a9 1803{
c5df3096
Z
1804 SV *ex = mess_sv(baseex, 0);
1805 PERL_ARGS_ASSERT_WARN_SV;
1806 if (!invoke_exception_hook(ex, TRUE))
1807 write_to_stderr(ex);
cea2e8a9
GS
1808}
1809
c5df3096
Z
1810/*
1811=for apidoc Am|void|vwarn|const char *pat|va_list *args
1812
1813This is an XS interface to Perl's C<warn> function.
1814
1815C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1816argument list. These are used to generate a string message. If the
1817message does not end with a newline, then it will be extended with
1818some indication of the current location in the code, as described for
1819L</mess_sv>.
1820
1821The error message or object will by default be written to standard error,
1822but this is subject to modification by a C<$SIG{__WARN__}> handler.
1823
1824Unlike with L</vcroak>, C<pat> is not permitted to be null.
1825
1826=cut
1827*/
1828
c5be433b
GS
1829void
1830Perl_vwarn(pTHX_ const char* pat, va_list *args)
cea2e8a9 1831{
c5df3096 1832 SV *ex = vmess(pat, args);
7918f24d 1833 PERL_ARGS_ASSERT_VWARN;
c5df3096
Z
1834 if (!invoke_exception_hook(ex, TRUE))
1835 write_to_stderr(ex);
1836}
7918f24d 1837
c5df3096
Z
1838/*
1839=for apidoc Am|void|warn|const char *pat|...
87582a92 1840
c5df3096
Z
1841This is an XS interface to Perl's C<warn> function.
1842
1843Take a sprintf-style format pattern and argument list. These are used to
1844generate a string message. If the message does not end with a newline,
1845then it will be extended with some indication of the current location
1846in the code, as described for L</mess_sv>.
1847
1848The error message or object will by default be written to standard error,
1849but this is subject to modification by a C<$SIG{__WARN__}> handler.
1850
1851Unlike with L</croak>, C<pat> is not permitted to be null.
1852
1853=cut
1854*/
8d063cd8 1855
c5be433b 1856#if defined(PERL_IMPLICIT_CONTEXT)
cea2e8a9
GS
1857void
1858Perl_warn_nocontext(const char *pat, ...)
1859{
1860 dTHX;
1861 va_list args;
7918f24d 1862 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
cea2e8a9 1863 va_start(args, pat);
c5be433b 1864 vwarn(pat, &args);
cea2e8a9
GS
1865 va_end(args);
1866}
1867#endif /* PERL_IMPLICIT_CONTEXT */
1868
1869void
1870Perl_warn(pTHX_ const char *pat, ...)
1871{
1872 va_list args;
7918f24d 1873 PERL_ARGS_ASSERT_WARN;
cea2e8a9 1874 va_start(args, pat);
c5be433b 1875 vwarn(pat, &args);
cea2e8a9
GS
1876 va_end(args);
1877}
1878
c5be433b
GS
1879#if defined(PERL_IMPLICIT_CONTEXT)
1880void
1881Perl_warner_nocontext(U32 err, const char *pat, ...)
1882{
27da23d5 1883 dTHX;
c5be433b 1884 va_list args;
7918f24d 1885 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
c5be433b
GS
1886 va_start(args, pat);
1887 vwarner(err, pat, &args);
1888 va_end(args);
1889}
1890#endif /* PERL_IMPLICIT_CONTEXT */
1891
599cee73 1892void
9b387841
NC
1893Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1894{
1895 PERL_ARGS_ASSERT_CK_WARNER_D;
1896
1897 if (Perl_ckwarn_d(aTHX_ err)) {
1898 va_list args;
1899 va_start(args, pat);
1900 vwarner(err, pat, &args);
1901 va_end(args);
1902 }
1903}
1904
1905void
a2a5de95
NC
1906Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1907{
1908 PERL_ARGS_ASSERT_CK_WARNER;
1909
1910 if (Perl_ckwarn(aTHX_ err)) {
1911 va_list args;
1912 va_start(args, pat);
1913 vwarner(err, pat, &args);
1914 va_end(args);
1915 }
1916}
1917
1918void
864dbfa3 1919Perl_warner(pTHX_ U32 err, const char* pat,...)
599cee73
PM
1920{
1921 va_list args;
7918f24d 1922 PERL_ARGS_ASSERT_WARNER;
c5be433b
GS
1923 va_start(args, pat);
1924 vwarner(err, pat, &args);
1925 va_end(args);
1926}
1927
1928void
1929Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1930{
27da23d5 1931 dVAR;
7918f24d 1932 PERL_ARGS_ASSERT_VWARNER;
5f2d9966 1933 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
a3b680e6 1934 SV * const msv = vmess(pat, args);
599cee73 1935
c5df3096
Z
1936 invoke_exception_hook(msv, FALSE);
1937 die_unwind(msv);
599cee73
PM
1938 }
1939 else {
d13b0d77 1940 Perl_vwarn(aTHX_ pat, args);
599cee73
PM
1941 }
1942}
1943
f54ba1c2
DM
1944/* implements the ckWARN? macros */
1945
1946bool
1947Perl_ckwarn(pTHX_ U32 w)
1948{
97aff369 1949 dVAR;
ad287e37
NC
1950 /* If lexical warnings have not been set, use $^W. */
1951 if (isLEXWARN_off)
1952 return PL_dowarn & G_WARN_ON;
1953
26c7b074 1954 return ckwarn_common(w);
f54ba1c2
DM
1955}
1956
1957/* implements the ckWARN?_d macro */
1958
1959bool
1960Perl_ckwarn_d(pTHX_ U32 w)
1961{
97aff369 1962 dVAR;
ad287e37
NC
1963 /* If lexical warnings have not been set then default classes warn. */
1964 if (isLEXWARN_off)
1965 return TRUE;
1966
26c7b074
NC
1967 return ckwarn_common(w);
1968}
1969
1970static bool
1971S_ckwarn_common(pTHX_ U32 w)
1972{
ad287e37
NC
1973 if (PL_curcop->cop_warnings == pWARN_ALL)
1974 return TRUE;
1975
1976 if (PL_curcop->cop_warnings == pWARN_NONE)
1977 return FALSE;
1978
98fe6610
NC
1979 /* Check the assumption that at least the first slot is non-zero. */
1980 assert(unpackWARN1(w));
1981
1982 /* Check the assumption that it is valid to stop as soon as a zero slot is
1983 seen. */
1984 if (!unpackWARN2(w)) {
1985 assert(!unpackWARN3(w));
1986 assert(!unpackWARN4(w));
1987 } else if (!unpackWARN3(w)) {
1988 assert(!unpackWARN4(w));
1989 }
1990
26c7b074
NC
1991 /* Right, dealt with all the special cases, which are implemented as non-
1992 pointers, so there is a pointer to a real warnings mask. */
98fe6610
NC
1993 do {
1994 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1995 return TRUE;
1996 } while (w >>= WARNshift);
1997
1998 return FALSE;
f54ba1c2
DM
1999}
2000
72dc9ed5
NC
2001/* Set buffer=NULL to get a new one. */
2002STRLEN *
8ee4cf24 2003Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
72dc9ed5 2004 STRLEN size) {
5af88345
FC
2005 const MEM_SIZE len_wanted =
2006 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
35da51f7 2007 PERL_UNUSED_CONTEXT;
7918f24d 2008 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
72dc9ed5 2009
10edeb5d
JH
2010 buffer = (STRLEN*)
2011 (specialWARN(buffer) ?
2012 PerlMemShared_malloc(len_wanted) :
2013 PerlMemShared_realloc(buffer, len_wanted));
72dc9ed5
NC
2014 buffer[0] = size;
2015 Copy(bits, (buffer + 1), size, char);
5af88345
FC
2016 if (size < WARNsize)
2017 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
72dc9ed5
NC
2018 return buffer;
2019}
f54ba1c2 2020
e6587932
DM
2021/* since we've already done strlen() for both nam and val
2022 * we can use that info to make things faster than
2023 * sprintf(s, "%s=%s", nam, val)
2024 */
2025#define my_setenv_format(s, nam, nlen, val, vlen) \
2026 Copy(nam, s, nlen, char); \
2027 *(s+nlen) = '='; \
2028 Copy(val, s+(nlen+1), vlen, char); \
2029 *(s+(nlen+1+vlen)) = '\0'
2030
c5d12488
JH
2031#ifdef USE_ENVIRON_ARRAY
2032 /* VMS' my_setenv() is in vms.c */
2033#if !defined(WIN32) && !defined(NETWARE)
8d063cd8 2034void
e1ec3a88 2035Perl_my_setenv(pTHX_ const char *nam, const char *val)
8d063cd8 2036{
27da23d5 2037 dVAR;
4efc5df6
GS
2038#ifdef USE_ITHREADS
2039 /* only parent thread can modify process environment */
2040 if (PL_curinterp == aTHX)
2041#endif
2042 {
f2517201 2043#ifndef PERL_USE_SAFE_PUTENV
50acdf95 2044 if (!PL_use_safe_putenv) {
c5d12488 2045 /* most putenv()s leak, so we manipulate environ directly */
3a9222be
JH
2046 register I32 i;
2047 register const I32 len = strlen(nam);
c5d12488
JH
2048 int nlen, vlen;
2049
3a9222be
JH
2050 /* where does it go? */
2051 for (i = 0; environ[i]; i++) {
2052 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
2053 break;
2054 }
2055
c5d12488
JH
2056 if (environ == PL_origenviron) { /* need we copy environment? */
2057 I32 j;
2058 I32 max;
2059 char **tmpenv;
2060
2061 max = i;
2062 while (environ[max])
2063 max++;
2064 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2065 for (j=0; j<max; j++) { /* copy environment */
2066 const int len = strlen(environ[j]);
2067 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2068 Copy(environ[j], tmpenv[j], len+1, char);
2069 }
2070 tmpenv[max] = NULL;
2071 environ = tmpenv; /* tell exec where it is now */
2072 }
2073 if (!val) {
2074 safesysfree(environ[i]);
2075 while (environ[i]) {
2076 environ[i] = environ[i+1];
2077 i++;
a687059c 2078 }
c5d12488
JH
2079 return;
2080 }
2081 if (!environ[i]) { /* does not exist yet */
2082 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2083 environ[i+1] = NULL; /* make sure it's null terminated */
2084 }
2085 else
2086 safesysfree(environ[i]);
2087 nlen = strlen(nam);
2088 vlen = strlen(val);
2089
2090 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2091 /* all that work just for this */
2092 my_setenv_format(environ[i], nam, nlen, val, vlen);
50acdf95 2093 } else {
c5d12488 2094# endif
7ee146b1 2095# if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
88f5bc07
AB
2096# if defined(HAS_UNSETENV)
2097 if (val == NULL) {
2098 (void)unsetenv(nam);
2099 } else {
2100 (void)setenv(nam, val, 1);
2101 }
2102# else /* ! HAS_UNSETENV */
2103 (void)setenv(nam, val, 1);
2104# endif /* HAS_UNSETENV */
47dafe4d 2105# else
88f5bc07
AB
2106# if defined(HAS_UNSETENV)
2107 if (val == NULL) {
2108 (void)unsetenv(nam);
2109 } else {
c4420975
AL
2110 const int nlen = strlen(nam);
2111 const int vlen = strlen(val);
2112 char * const new_env =
88f5bc07
AB
2113 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2114 my_setenv_format(new_env, nam, nlen, val, vlen);
2115 (void)putenv(new_env);
2116 }
2117# else /* ! HAS_UNSETENV */
2118 char *new_env;
c4420975
AL
2119 const int nlen = strlen(nam);
2120 int vlen;
88f5bc07
AB
2121 if (!val) {
2122 val = "";
2123 }
2124 vlen = strlen(val);
2125 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2126 /* all that work just for this */
2127 my_setenv_format(new_env, nam, nlen, val, vlen);
2128 (void)putenv(new_env);
2129# endif /* HAS_UNSETENV */
47dafe4d 2130# endif /* __CYGWIN__ */
50acdf95
MS
2131#ifndef PERL_USE_SAFE_PUTENV
2132 }
2133#endif
4efc5df6 2134 }
8d063cd8
LW
2135}
2136
c5d12488 2137#else /* WIN32 || NETWARE */
68dc0745 2138
2139void
72229eff 2140Perl_my_setenv(pTHX_ const char *nam, const char *val)
68dc0745 2141{
27da23d5 2142 dVAR;
c5d12488
JH
2143 register char *envstr;
2144 const int nlen = strlen(nam);
2145 int vlen;
e6587932 2146
c5d12488
JH
2147 if (!val) {
2148 val = "";
ac5c734f 2149 }
c5d12488
JH
2150 vlen = strlen(val);
2151 Newx(envstr, nlen+vlen+2, char);
2152 my_setenv_format(envstr, nam, nlen, val, vlen);
2153 (void)PerlEnv_putenv(envstr);
2154 Safefree(envstr);
3e3baf6d
TB
2155}
2156
c5d12488 2157#endif /* WIN32 || NETWARE */
3e3baf6d 2158
c5d12488 2159#endif /* !VMS && !EPOC*/
378cc40b 2160
16d20bd9 2161#ifdef UNLINK_ALL_VERSIONS
79072805 2162I32
6e732051 2163Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
378cc40b 2164{
35da51f7 2165 I32 retries = 0;
378cc40b 2166
7918f24d
NC
2167 PERL_ARGS_ASSERT_UNLNK;
2168
35da51f7
AL
2169 while (PerlLIO_unlink(f) >= 0)
2170 retries++;
2171 return retries ? 0 : -1;
378cc40b
LW
2172}
2173#endif
2174
7a3f2258 2175/* this is a drop-in replacement for bcopy() */
2253333f 2176#if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
378cc40b 2177char *
7a3f2258 2178Perl_my_bcopy(register const char *from,register char *to,register I32 len)
378cc40b 2179{
2d03de9c 2180 char * const retval = to;
378cc40b 2181
7918f24d
NC
2182 PERL_ARGS_ASSERT_MY_BCOPY;
2183
7c0587c8
LW
2184 if (from - to >= 0) {
2185 while (len--)
2186 *to++ = *from++;
2187 }
2188 else {
2189 to += len;
2190 from += len;
2191 while (len--)
faf8582f 2192 *(--to) = *(--from);
7c0587c8 2193 }
378cc40b
LW
2194 return retval;
2195}
ffed7fef 2196#endif
378cc40b 2197
7a3f2258 2198/* this is a drop-in replacement for memset() */
fc36a67e 2199#ifndef HAS_MEMSET
2200void *
7a3f2258 2201Perl_my_memset(register char *loc, register I32 ch, register I32 len)
fc36a67e 2202{
2d03de9c 2203 char * const retval = loc;
fc36a67e 2204
7918f24d
NC
2205 PERL_ARGS_ASSERT_MY_MEMSET;
2206
fc36a67e 2207 while (len--)
2208 *loc++ = ch;
2209 return retval;
2210}
2211#endif
2212
7a3f2258 2213/* this is a drop-in replacement for bzero() */
7c0587c8 2214#if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
378cc40b 2215char *
7a3f2258 2216Perl_my_bzero(register char *loc, register I32 len)
378cc40b 2217{
2d03de9c 2218 char * const retval = loc;
378cc40b 2219
7918f24d
NC
2220 PERL_ARGS_ASSERT_MY_BZERO;
2221
378cc40b
LW
2222 while (len--)
2223 *loc++ = 0;
2224 return retval;
2225}
2226#endif
7c0587c8 2227
7a3f2258 2228/* this is a drop-in replacement for memcmp() */
36477c24 2229#if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
79072805 2230I32
7a3f2258 2231Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
7c0587c8 2232{
e1ec3a88
AL
2233 register const U8 *a = (const U8 *)s1;
2234 register const U8 *b = (const U8 *)s2;
79072805 2235 register I32 tmp;
7c0587c8 2236
7918f24d
NC
2237 PERL_ARGS_ASSERT_MY_MEMCMP;
2238
7c0587c8 2239 while (len--) {
27da23d5 2240 if ((tmp = *a++ - *b++))
7c0587c8
LW
2241 return tmp;
2242 }
2243 return 0;
2244}
36477c24 2245#endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
a687059c 2246
fe14fcc3 2247#ifndef HAS_VPRINTF
d05d9be5
AD
2248/* This vsprintf replacement should generally never get used, since
2249 vsprintf was available in both System V and BSD 2.11. (There may
2250 be some cross-compilation or embedded set-ups where it is needed,
2251 however.)
2252
2253 If you encounter a problem in this function, it's probably a symptom
2254 that Configure failed to detect your system's vprintf() function.
2255 See the section on "item vsprintf" in the INSTALL file.
2256
2257 This version may compile on systems with BSD-ish <stdio.h>,
2258 but probably won't on others.
2259*/
a687059c 2260
85e6fe83 2261#ifdef USE_CHAR_VSPRINTF
a687059c
LW
2262char *
2263#else
2264int
2265#endif
d05d9be5 2266vsprintf(char *dest, const char *pat, void *args)
a687059c
LW
2267{
2268 FILE fakebuf;
2269
d05d9be5
AD
2270#if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2271 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2272 FILE_cnt(&fakebuf) = 32767;
2273#else
2274 /* These probably won't compile -- If you really need
2275 this, you'll have to figure out some other method. */
a687059c
LW
2276 fakebuf._ptr = dest;
2277 fakebuf._cnt = 32767;
d05d9be5 2278#endif
35c8bce7
LW
2279#ifndef _IOSTRG
2280#define _IOSTRG 0
2281#endif
a687059c
LW
2282 fakebuf._flag = _IOWRT|_IOSTRG;
2283 _doprnt(pat, args, &fakebuf); /* what a kludge */
d05d9be5
AD
2284#if defined(STDIO_PTR_LVALUE)
2285 *(FILE_ptr(&fakebuf)++) = '\0';
2286#else
2287 /* PerlIO has probably #defined away fputc, but we want it here. */
2288# ifdef fputc
2289# undef fputc /* XXX Should really restore it later */
2290# endif
2291 (void)fputc('\0', &fakebuf);
2292#endif
85e6fe83 2293#ifdef USE_CHAR_VSPRINTF
a687059c
LW
2294 return(dest);
2295#else
2296 return 0; /* perl doesn't use return value */
2297#endif
2298}
2299
fe14fcc3 2300#endif /* HAS_VPRINTF */
a687059c
LW
2301
2302#ifdef MYSWAP
ffed7fef 2303#if BYTEORDER != 0x4321
a687059c 2304short
864dbfa3 2305Perl_my_swap(pTHX_ short s)
a687059c
LW
2306{
2307#if (BYTEORDER & 1) == 0
2308 short result;
2309
2310 result = ((s & 255) << 8) + ((s >> 8) & 255);
2311 return result;
2312#else
2313 return s;
2314#endif
2315}
2316
2317long
864dbfa3 2318Perl_my_htonl(pTHX_ long l)
a687059c
LW
2319{
2320 union {
2321 long result;
ffed7fef 2322 char c[sizeof(long)];
a687059c
LW
2323 } u;
2324
cef6ea9d
JH
2325#if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2326#if BYTEORDER == 0x12345678
2327 u.result = 0;
2328#endif
a687059c
LW
2329 u.c[0] = (l >> 24) & 255;
2330 u.c[1] = (l >> 16) & 255;
2331 u.c[2] = (l >> 8) & 255;
2332 u.c[3] = l & 255;
2333 return u.result;
2334#else
ffed7fef 2335#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
cea2e8a9 2336 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
a687059c 2337#else
79072805
LW
2338 register I32 o;
2339 register I32 s;
a687059c 2340
ffed7fef
LW
2341 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2342 u.c[o & 0xf] = (l >> s) & 255;
a687059c
LW
2343 }
2344 return u.result;
2345#endif
2346#endif
2347}
2348
2349long
864dbfa3 2350Perl_my_ntohl(pTHX_ long l)
a687059c
LW
2351{
2352 union {
2353 long l;
ffed7fef 2354 char c[sizeof(long)];
a687059c
LW
2355 } u;
2356
ffed7fef 2357#if BYTEORDER == 0x1234
a687059c
LW
2358 u.c[0] = (l >> 24) & 255;
2359 u.c[1] = (l >> 16) & 255;
2360 u.c[2] = (l >> 8) & 255;
2361 u.c[3] = l & 255;
2362 return u.l;
2363#else
ffed7fef 2364#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
cea2e8a9 2365 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
a687059c 2366#else
79072805
LW
2367 register I32 o;
2368 register I32 s;
a687059c
LW
2369
2370 u.l = l;
2371 l = 0;
ffed7fef
LW
2372 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2373 l |= (u.c[o & 0xf] & 255) << s;
a687059c
LW
2374 }
2375 return l;
2376#endif
2377#endif
2378}
2379
ffed7fef 2380#endif /* BYTEORDER != 0x4321 */
988174c1
LW
2381#endif /* MYSWAP */
2382
2383/*
2384 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2385 * If these functions are defined,
2386 * the BYTEORDER is neither 0x1234 nor 0x4321.
2387 * However, this is not assumed.
2388 * -DWS
2389 */
2390
1109a392 2391#define HTOLE(name,type) \
988174c1 2392 type \
ba106d47 2393 name (register type n) \
988174c1
LW
2394 { \
2395 union { \
2396 type value; \
2397 char c[sizeof(type)]; \
2398 } u; \
bb7a0f54
MHM
2399 register U32 i; \
2400 register U32 s = 0; \
1109a392 2401 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
988174c1
LW
2402 u.c[i] = (n >> s) & 0xFF; \
2403 } \
2404 return u.value; \
2405 }
2406
1109a392 2407#define LETOH(name,type) \
988174c1 2408 type \
ba106d47 2409 name (register type n) \
988174c1
LW
2410 { \
2411 union { \
2412 type value; \
2413 char c[sizeof(type)]; \
2414 } u; \
bb7a0f54
MHM
2415 register U32 i; \
2416 register U32 s = 0; \
988174c1
LW
2417 u.value = n; \
2418 n = 0; \
1109a392
MHM
2419 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2420 n |= ((type)(u.c[i] & 0xFF)) << s; \
988174c1
LW
2421 } \
2422 return n; \
2423 }
2424
1109a392
MHM
2425/*
2426 * Big-endian byte order functions.
2427 */
2428
2429#define HTOBE(name,type) \
2430 type \
2431 name (register type n) \
2432 { \
2433 union { \
2434 type value; \
2435 char c[sizeof(type)]; \
2436 } u; \
bb7a0f54
MHM
2437 register U32 i; \
2438 register U32 s = 8*(sizeof(u.c)-1); \
1109a392
MHM
2439 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2440 u.c[i] = (n >> s) & 0xFF; \
2441 } \
2442 return u.value; \
2443 }
2444
2445#define BETOH(name,type) \
2446 type \
2447 name (register type n) \
2448 { \
2449 union { \
2450 type value; \
2451 char c[sizeof(type)]; \
2452 } u; \
bb7a0f54
MHM
2453 register U32 i; \
2454 register U32 s = 8*(sizeof(u.c)-1); \
1109a392
MHM
2455 u.value = n; \
2456 n = 0; \
2457 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2458 n |= ((type)(u.c[i] & 0xFF)) << s; \
2459 } \
2460 return n; \
2461 }
2462
2463/*
2464 * If we just can't do it...
2465 */
2466
2467#define NOT_AVAIL(name,type) \
2468 type \
2469 name (register type n) \
2470 { \
2471 Perl_croak_nocontext(#name "() not available"); \
2472 return n; /* not reached */ \
2473 }
2474
2475
988174c1 2476#if defined(HAS_HTOVS) && !defined(htovs)
1109a392 2477HTOLE(htovs,short)
988174c1
LW
2478#endif
2479#if defined(HAS_HTOVL) && !defined(htovl)
1109a392 2480HTOLE(htovl,long)
988174c1
LW
2481#endif
2482#if defined(HAS_VTOHS) && !defined(vtohs)
1109a392 2483LETOH(vtohs,short)
988174c1
LW
2484#endif
2485#if defined(HAS_VTOHL) && !defined(vtohl)
1109a392
MHM
2486LETOH(vtohl,long)
2487#endif
2488
2489#ifdef PERL_NEED_MY_HTOLE16
2490# if U16SIZE == 2
2491HTOLE(Perl_my_htole16,U16)
2492# else
2493NOT_AVAIL(Perl_my_htole16,U16)
2494# endif
2495#endif
2496#ifdef PERL_NEED_MY_LETOH16
2497# if U16SIZE == 2
2498LETOH(Perl_my_letoh16,U16)
2499# else
2500NOT_AVAIL(Perl_my_letoh16,U16)
2501# endif
2502#endif
2503#ifdef PERL_NEED_MY_HTOBE16
2504# if U16SIZE == 2
2505HTOBE(Perl_my_htobe16,U16)
2506# else
2507NOT_AVAIL(Perl_my_htobe16,U16)
2508# endif
2509#endif
2510#ifdef PERL_NEED_MY_BETOH16
2511# if U16SIZE == 2
2512BETOH(Perl_my_betoh16,U16)
2513# else
2514NOT_AVAIL(Perl_my_betoh16,U16)
2515# endif
2516#endif
2517
2518#ifdef PERL_NEED_MY_HTOLE32
2519# if U32SIZE == 4
2520HTOLE(Perl_my_htole32,U32)
2521# else
2522NOT_AVAIL(Perl_my_htole32,U32)
2523# endif
2524#endif
2525#ifdef PERL_NEED_MY_LETOH32
2526# if U32SIZE == 4
2527LETOH(Perl_my_letoh32,U32)
2528# else
2529NOT_AVAIL(Perl_my_letoh32,U32)
2530# endif
2531#endif
2532#ifdef PERL_NEED_MY_HTOBE32
2533# if U32SIZE == 4
2534HTOBE(Perl_my_htobe32,U32)
2535# else
2536NOT_AVAIL(Perl_my_htobe32,U32)
2537# endif
2538#endif
2539#ifdef PERL_NEED_MY_BETOH32
2540# if U32SIZE == 4
2541BETOH(Perl_my_betoh32,U32)
2542# else
2543NOT_AVAIL(Perl_my_betoh32,U32)
2544# endif
2545#endif
2546
2547#ifdef PERL_NEED_MY_HTOLE64
2548# if U64SIZE == 8
2549HTOLE(Perl_my_htole64,U64)
2550# else
2551NOT_AVAIL(Perl_my_htole64,U64)
2552# endif
2553#endif
2554#ifdef PERL_NEED_MY_LETOH64
2555# if U64SIZE == 8
2556LETOH(Perl_my_letoh64,U64)
2557# else
2558NOT_AVAIL(Perl_my_letoh64,U64)
2559# endif
2560#endif
2561#ifdef PERL_NEED_MY_HTOBE64
2562# if U64SIZE == 8
2563HTOBE(Perl_my_htobe64,U64)
2564# else
2565NOT_AVAIL(Perl_my_htobe64,U64)
2566# endif
2567#endif
2568#ifdef PERL_NEED_MY_BETOH64
2569# if U64SIZE == 8
2570BETOH(Perl_my_betoh64,U64)
2571# else
2572NOT_AVAIL(Perl_my_betoh64,U64)
2573# endif
988174c1 2574#endif
a687059c 2575
1109a392
MHM
2576#ifdef PERL_NEED_MY_HTOLES
2577HTOLE(Perl_my_htoles,short)
2578#endif
2579#ifdef PERL_NEED_MY_LETOHS
2580LETOH(Perl_my_letohs,short)
2581#endif
2582#ifdef PERL_NEED_MY_HTOBES
2583HTOBE(Perl_my_htobes,short)
2584#endif
2585#ifdef PERL_NEED_MY_BETOHS
2586BETOH(Perl_my_betohs,short)
2587#endif
2588
2589#ifdef PERL_NEED_MY_HTOLEI
2590HTOLE(Perl_my_htolei,int)
2591#endif
2592#ifdef PERL_NEED_MY_LETOHI
2593LETOH(Perl_my_letohi,int)
2594#endif
2595#ifdef PERL_NEED_MY_HTOBEI
2596HTOBE(Perl_my_htobei,int)
2597#endif
2598#ifdef PERL_NEED_MY_BETOHI
2599BETOH(Perl_my_betohi,int)
2600#endif
2601
2602#ifdef PERL_NEED_MY_HTOLEL
2603HTOLE(Perl_my_htolel,long)
2604#endif
2605#ifdef PERL_NEED_MY_LETOHL
2606LETOH(Perl_my_letohl,long)
2607#endif
2608#ifdef PERL_NEED_MY_HTOBEL
2609HTOBE(Perl_my_htobel,long)
2610#endif
2611#ifdef PERL_NEED_MY_BETOHL
2612BETOH(Perl_my_betohl,long)
2613#endif
2614
2615void
2616Perl_my_swabn(void *ptr, int n)
2617{
2618 register char *s = (char *)ptr;
2619 register char *e = s + (n-1);
2620 register char tc;
2621
7918f24d
NC
2622 PERL_ARGS_ASSERT_MY_SWABN;
2623
1109a392
MHM
2624 for (n /= 2; n > 0; s++, e--, n--) {
2625 tc = *s;
2626 *s = *e;
2627 *e = tc;
2628 }
2629}
2630
4a7d1889 2631PerlIO *
c9289b7b 2632Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
4a7d1889 2633{
e37778c2 2634#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
97aff369 2635 dVAR;
1f852d0d
NIS
2636 int p[2];
2637 register I32 This, that;
2638 register Pid_t pid;
2639 SV *sv;
2640 I32 did_pipes = 0;
2641 int pp[2];
2642
7918f24d
NC
2643 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2644
1f852d0d
NIS
2645 PERL_FLUSHALL_FOR_CHILD;
2646 This = (*mode == 'w');
2647 that = !This;
2648 if (PL_tainting) {
2649 taint_env();
2650 taint_proper("Insecure %s%s", "EXEC");
2651 }
2652 if (PerlProc_pipe(p) < 0)
4608196e 2653 return NULL;
1f852d0d
NIS
2654 /* Try for another pipe pair for error return */
2655 if (PerlProc_pipe(pp) >= 0)
2656 did_pipes = 1;
52e18b1f 2657 while ((pid = PerlProc_fork()) < 0) {
1f852d0d
NIS
2658 if (errno != EAGAIN) {
2659 PerlLIO_close(p[This]);
4e6dfe71 2660 PerlLIO_close(p[that]);
1f852d0d
NIS
2661 if (did_pipes) {
2662 PerlLIO_close(pp[0]);
2663 PerlLIO_close(pp[1]);
2664 }
4608196e 2665 return NULL;
1f852d0d 2666 }
a2a5de95 2667 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
1f852d0d
NIS
2668 sleep(5);
2669 }
2670 if (pid == 0) {
2671 /* Child */
1f852d0d
NIS
2672#undef THIS
2673#undef THAT
2674#define THIS that
2675#define THAT This
1f852d0d
NIS
2676 /* Close parent's end of error status pipe (if any) */
2677 if (did_pipes) {
2678 PerlLIO_close(pp[0]);
2679#if defined(HAS_FCNTL) && defined(F_SETFD)
2680 /* Close error pipe automatically if exec works */
2681 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2682#endif
2683 }
2684 /* Now dup our end of _the_ pipe to right position */
2685 if (p[THIS] != (*mode == 'r')) {
2686 PerlLIO_dup2(p[THIS], *mode == 'r');
2687 PerlLIO_close(p[THIS]);
4e6dfe71
GS
2688 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2689 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
1f852d0d 2690 }
4e6dfe71
GS
2691 else
2692 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
1f852d0d
NIS
2693#if !defined(HAS_FCNTL) || !defined(F_SETFD)
2694 /* No automatic close - do it by hand */
b7953727
JH
2695# ifndef NOFILE
2696# define NOFILE 20
2697# endif
a080fe3d
NIS
2698 {
2699 int fd;
2700
2701 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
3aed30dc 2702 if (fd != pp[1])
a080fe3d
NIS
2703 PerlLIO_close(fd);
2704 }
1f852d0d
NIS
2705 }
2706#endif
a0714e2c 2707 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
1f852d0d
NIS
2708 PerlProc__exit(1);
2709#undef THIS
2710#undef THAT
2711 }
2712 /* Parent */
52e18b1f 2713 do_execfree(); /* free any memory malloced by child on fork */
1f852d0d
NIS
2714 if (did_pipes)
2715 PerlLIO_close(pp[1]);
2716 /* Keep the lower of the two fd numbers */
2717 if (p[that] < p[This]) {
2718 PerlLIO_dup2(p[This], p[that]);
2719 PerlLIO_close(p[This]);
2720 p[This] = p[that];
2721 }
4e6dfe71
GS
2722 else
2723 PerlLIO_close(p[that]); /* close child's end of pipe */
2724
1f852d0d 2725 sv = *av_fetch(PL_fdpid,p[This],TRUE);
862a34c6 2726 SvUPGRADE(sv,SVt_IV);
45977657 2727 SvIV_set(sv, pid);
1f852d0d
NIS
2728 PL_forkprocess = pid;
2729 /* If we managed to get status pipe check for exec fail */
2730 if (did_pipes && pid > 0) {
2731 int errkid;
bb7a0f54
MHM
2732 unsigned n = 0;
2733 SSize_t n1;
1f852d0d
NIS
2734
2735 while (n < sizeof(int)) {
2736 n1 = PerlLIO_read(pp[0],
2737 (void*)(((char*)&errkid)+n),
2738 (sizeof(int)) - n);
2739 if (n1 <= 0)
2740 break;
2741 n += n1;
2742 }
2743 PerlLIO_close(pp[0]);
2744 did_pipes = 0;
2745 if (n) { /* Error */
2746 int pid2, status;
8c51524e 2747 PerlLIO_close(p[This]);
1f852d0d 2748 if (n != sizeof(int))
5637ef5b 2749 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
1f852d0d
NIS
2750 do {
2751 pid2 = wait4pid(pid, &status, 0);
2752 } while (pid2 == -1 && errno == EINTR);
2753 errno = errkid; /* Propagate errno from kid */
4608196e 2754 return NULL;
1f852d0d
NIS
2755 }
2756 }
2757 if (did_pipes)
2758 PerlLIO_close(pp[0]);
2759 return PerlIO_fdopen(p[This], mode);
2760#else
9d419b5f 2761# ifdef OS2 /* Same, without fork()ing and all extra overhead... */
4e205ed6 2762 return my_syspopen4(aTHX_ NULL, mode, n, args);
9d419b5f 2763# else
4a7d1889
NIS
2764 Perl_croak(aTHX_ "List form of piped open not implemented");
2765 return (PerlIO *) NULL;
9d419b5f 2766# endif
1f852d0d 2767#endif
4a7d1889
NIS
2768}
2769
5f05dabc 2770 /* VMS' my_popen() is in VMS.c, same with OS/2. */
e37778c2 2771#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
760ac839 2772PerlIO *
3dd43144 2773Perl_my_popen(pTHX_ const char *cmd, const char *mode)
a687059c 2774{
97aff369 2775 dVAR;
a687059c 2776 int p[2];
8ac85365 2777 register I32 This, that;
d8a83dd3 2778 register Pid_t pid;
79072805 2779 SV *sv;
bfce84ec 2780 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
e446cec8
IZ
2781 I32 did_pipes = 0;
2782 int pp[2];
a687059c 2783
7918f24d
NC
2784 PERL_ARGS_ASSERT_MY_POPEN;
2785
45bc9206 2786 PERL_FLUSHALL_FOR_CHILD;
ddcf38b7
IZ
2787#ifdef OS2
2788 if (doexec) {
23da6c43 2789 return my_syspopen(aTHX_ cmd,mode);
ddcf38b7 2790 }
a1d180c4 2791#endif
8ac85365
NIS
2792 This = (*mode == 'w');
2793 that = !This;
3280af22 2794 if (doexec && PL_tainting) {
bbce6d69 2795 taint_env();
2796 taint_proper("Insecure %s%s", "EXEC");
d48672a2 2797 }
c2267164 2798 if (PerlProc_pipe(p) < 0)
4608196e 2799 return NULL;
e446cec8
IZ
2800 if (doexec && PerlProc_pipe(pp) >= 0)
2801 did_pipes = 1;
52e18b1f 2802 while ((pid = PerlProc_fork()) < 0) {
a687059c 2803 if (errno != EAGAIN) {
6ad3d225 2804 PerlLIO_close(p[This]);
b5ac89c3 2805 PerlLIO_close(p[that]);
e446cec8
IZ
2806 if (did_pipes) {
2807 PerlLIO_close(pp[0]);
2808 PerlLIO_close(pp[1]);
2809 }
a687059c 2810 if (!doexec)
b3647a36 2811 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
4608196e 2812 return NULL;
a687059c 2813 }
a2a5de95 2814 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
a687059c
LW
2815 sleep(5);
2816 }
2817 if (pid == 0) {
79072805 2818
30ac6d9b
GS
2819#undef THIS
2820#undef THAT
a687059c 2821#define THIS that
8ac85365 2822#define THAT This
e446cec8
IZ
2823 if (did_pipes) {
2824 PerlLIO_close(pp[0]);
2825#if defined(HAS_FCNTL) && defined(F_SETFD)
2826 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2827#endif
2828 }
a687059c 2829 if (p[THIS] != (*mode == 'r')) {
6ad3d225
GS
2830 PerlLIO_dup2(p[THIS], *mode == 'r');
2831 PerlLIO_close(p[THIS]);
b5ac89c3
NIS
2832 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2833 PerlLIO_close(p[THAT]);
a687059c 2834 }
b5ac89c3
NIS
2835 else
2836 PerlLIO_close(p[THAT]);
4435c477 2837#ifndef OS2
a687059c 2838 if (doexec) {
a0d0e21e 2839#if !defined(HAS_FCNTL) || !defined(F_SETFD)
ae986130
LW
2840#ifndef NOFILE
2841#define NOFILE 20
2842#endif
a080fe3d 2843 {
3aed30dc 2844 int fd;
a080fe3d
NIS
2845
2846 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2847 if (fd != pp[1])
3aed30dc 2848 PerlLIO_close(fd);
a080fe3d 2849 }
ae986130 2850#endif
a080fe3d
NIS
2851 /* may or may not use the shell */
2852 do_exec3(cmd, pp[1], did_pipes);
6ad3d225 2853 PerlProc__exit(1);
a687059c 2854 }
4435c477 2855#endif /* defined OS2 */
713cef20
IZ
2856
2857#ifdef PERLIO_USING_CRLF
2858 /* Since we circumvent IO layers when we manipulate low-level
2859 filedescriptors directly, need to manually switch to the
2860 default, binary, low-level mode; see PerlIOBuf_open(). */
2861 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2862#endif
3280af22 2863 PL_forkprocess = 0;
ca0c25f6 2864#ifdef PERL_USES_PL_PIDSTATUS
3280af22 2865 hv_clear(PL_pidstatus); /* we have no children */
ca0c25f6 2866#endif
4608196e 2867 return NULL;
a687059c
LW
2868#undef THIS
2869#undef THAT
2870 }
b5ac89c3 2871 do_execfree(); /* free any memory malloced by child on vfork */
e446cec8
IZ
2872 if (did_pipes)
2873 PerlLIO_close(pp[1]);
8ac85365 2874 if (p[that] < p[This]) {
6ad3d225
GS
2875 PerlLIO_dup2(p[This], p[that]);
2876 PerlLIO_close(p[This]);
8ac85365 2877 p[This] = p[that];
62b28dd9 2878 }
b5ac89c3
NIS
2879 else
2880 PerlLIO_close(p[that]);
2881
3280af22 2882 sv = *av_fetch(PL_fdpid,p[This],TRUE);
862a34c6 2883 SvUPGRADE(sv,SVt_IV);
45977657 2884 SvIV_set(sv, pid);
3280af22 2885 PL_forkprocess = pid;
e446cec8
IZ
2886 if (did_pipes && pid > 0) {
2887 int errkid;
bb7a0f54
MHM
2888 unsigned n = 0;
2889 SSize_t n1;
e446cec8
IZ
2890
2891 while (n < sizeof(int)) {
2892 n1 = PerlLIO_read(pp[0],
2893 (void*)(((char*)&errkid)+n),
2894 (sizeof(int)) - n);
2895 if (n1 <= 0)
2896 break;
2897 n += n1;
2898 }
2f96c702
IZ
2899 PerlLIO_close(pp[0]);
2900 did_pipes = 0;
e446cec8 2901 if (n) { /* Error */
faa466a7 2902 int pid2, status;
8c51524e 2903 PerlLIO_close(p[This]);
e446cec8 2904 if (n != sizeof(int))
5637ef5b 2905 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
faa466a7
RG
2906 do {
2907 pid2 = wait4pid(pid, &status, 0);
2908 } while (pid2 == -1 && errno == EINTR);
e446cec8 2909 errno = errkid; /* Propagate errno from kid */
4608196e 2910 return NULL;
e446cec8
IZ
2911 }
2912 }
2913 if (did_pipes)
2914 PerlLIO_close(pp[0]);
8ac85365 2915 return PerlIO_fdopen(p[This], mode);
a687059c 2916}
7c0587c8 2917#else
85ca448a 2918#if defined(atarist) || defined(EPOC)
7c0587c8 2919FILE *popen();
760ac839 2920PerlIO *
cef6ea9d 2921Perl_my_popen(pTHX_ const char *cmd, const char *mode)
7c0587c8 2922{
7918f24d 2923 PERL_ARGS_ASSERT_MY_POPEN;
45bc9206 2924 PERL_FLUSHALL_FOR_CHILD;
a1d180c4
NIS
2925 /* Call system's popen() to get a FILE *, then import it.
2926 used 0 for 2nd parameter to PerlIO_importFILE;
2927 apparently not used
2928 */
2929 return PerlIO_importFILE(popen(cmd, mode), 0);
7c0587c8 2930}
2b96b0a5
JH
2931#else
2932#if defined(DJGPP)
2933FILE *djgpp_popen();
2934PerlIO *
cef6ea9d 2935Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2b96b0a5
JH
2936{
2937 PERL_FLUSHALL_FOR_CHILD;
2938 /* Call system's popen() to get a FILE *, then import it.
2939 used 0 for 2nd parameter to PerlIO_importFILE;
2940 apparently not used
2941 */
2942 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2943}
9c12f1e5
RGS
2944#else
2945#if defined(__LIBCATAMOUNT__)
2946PerlIO *
2947Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2948{
2949 return NULL;
2950}
2951#endif
2b96b0a5 2952#endif
7c0587c8
LW
2953#endif
2954
2955#endif /* !DOSISH */
a687059c 2956
52e18b1f
GS
2957/* this is called in parent before the fork() */
2958void
2959Perl_atfork_lock(void)
2960{
27da23d5 2961 dVAR;
3db8f154 2962#if defined(USE_ITHREADS)
52e18b1f
GS
2963 /* locks must be held in locking order (if any) */
2964# ifdef MYMALLOC
2965 MUTEX_LOCK(&PL_malloc_mutex);
2966# endif
2967 OP_REFCNT_LOCK;
2968#endif
2969}
2970
2971/* this is called in both parent and child after the fork() */
2972void
2973Perl_atfork_unlock(void)
2974{
27da23d5 2975 dVAR;
3db8f154 2976#if defined(USE_ITHREADS)
52e18b1f
GS
2977 /* locks must be released in same order as in atfork_lock() */
2978# ifdef MYMALLOC
2979 MUTEX_UNLOCK(&PL_malloc_mutex);
2980# endif
2981 OP_REFCNT_UNLOCK;
2982#endif
2983}
2984
2985Pid_t
2986Perl_my_fork(void)
2987{
2988#if defined(HAS_FORK)
2989 Pid_t pid;
3db8f154 2990#if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
52e18b1f
GS
2991 atfork_lock();
2992 pid = fork();
2993 atfork_unlock();
2994#else
2995 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2996 * handlers elsewhere in the code */
2997 pid = fork();
2998#endif
2999 return pid;
3000#else
3001 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
3002 Perl_croak_nocontext("fork() not available");
b961a566 3003 return 0;
52e18b1f
GS
3004#endif /* HAS_FORK */
3005}
3006
748a9306 3007#ifdef DUMP_FDS
35ff7856 3008void
c9289b7b 3009Perl_dump_fds(pTHX_ const char *const s)
ae986130
LW
3010{
3011 int fd;
c623ac67 3012 Stat_t tmpstatbuf;
ae986130 3013
7918f24d
NC
3014 PERL_ARGS_ASSERT_DUMP_FDS;
3015
bf49b057 3016 PerlIO_printf(Perl_debug_log,"%s", s);
ae986130 3017 for (fd = 0; fd < 32; fd++) {
6ad3d225 3018 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
bf49b057 3019 PerlIO_printf(Perl_debug_log," %d",fd);
ae986130 3020 }
bf49b057 3021 PerlIO_printf(Perl_debug_log,"\n");
27da23d5 3022 return;
ae986130 3023}
35ff7856 3024#endif /* DUMP_FDS */
ae986130 3025
fe14fcc3 3026#ifndef HAS_DUP2
fec02dd3 3027int
ba106d47 3028dup2(int oldfd, int newfd)
a687059c 3029{
a0d0e21e 3030#if defined(HAS_FCNTL) && defined(F_DUPFD)
fec02dd3
AD
3031 if (oldfd == newfd)
3032 return oldfd;
6ad3d225 3033 PerlLIO_close(newfd);
fec02dd3 3034 return fcntl(oldfd, F_DUPFD, newfd);
62b28dd9 3035#else
fc36a67e 3036#define DUP2_MAX_FDS 256
3037 int fdtmp[DUP2_MAX_FDS];
79072805 3038 I32 fdx = 0;
ae986130
LW
3039 int fd;
3040
fe14fcc3 3041 if (oldfd == newfd)
fec02dd3 3042 return oldfd;
6ad3d225 3043 PerlLIO_close(newfd);
fc36a67e 3044 /* good enough for low fd's... */
6ad3d225 3045 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
fc36a67e 3046 if (fdx >= DUP2_MAX_FDS) {
6ad3d225 3047 PerlLIO_close(fd);
fc36a67e 3048 fd = -1;
3049 break;
3050 }
ae986130 3051 fdtmp[fdx++] = fd;
fc36a67e 3052 }
ae986130 3053 while (fdx > 0)
6ad3d225 3054 PerlLIO_close(fdtmp[--fdx]);
fec02dd3 3055 return fd;
62b28dd9 3056#endif
a687059c
LW
3057}
3058#endif
3059
64ca3a65 3060#ifndef PERL_MICRO
ff68c719 3061#ifdef HAS_SIGACTION
3062
3063Sighandler_t
864dbfa3 3064Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
ff68c719 3065{
27da23d5 3066 dVAR;
ff68c719 3067 struct sigaction act, oact;
3068
a10b1e10
JH
3069#ifdef USE_ITHREADS
3070 /* only "parent" interpreter can diddle signals */
3071 if (PL_curinterp != aTHX)
8aad04aa 3072 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
3073#endif
3074
8aad04aa 3075 act.sa_handler = (void(*)(int))handler;
ff68c719 3076 sigemptyset(&act.sa_mask);
3077 act.sa_flags = 0;
3078#ifdef SA_RESTART
4ffa73a3
JH
3079 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3080 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
0a8e0eff 3081#endif
358837b8 3082#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
8aad04aa 3083 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
85264bed
CS
3084 act.sa_flags |= SA_NOCLDWAIT;
3085#endif
ff68c719 3086 if (sigaction(signo, &act, &oact) == -1)
8aad04aa 3087 return (Sighandler_t) SIG_ERR;
ff68c719 3088 else
8aad04aa 3089 return (Sighandler_t) oact.sa_handler;
ff68c719 3090}
3091
3092Sighandler_t
864dbfa3 3093Perl_rsignal_state(pTHX_ int signo)
ff68c719 3094{
3095 struct sigaction oact;
96a5add6 3096 PERL_UNUSED_CONTEXT;
ff68c719 3097
3098 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
8aad04aa 3099 return (Sighandler_t) SIG_ERR;
ff68c719 3100 else
8aad04aa 3101 return (Sighandler_t) oact.sa_handler;
ff68c719 3102}
3103
3104int
864dbfa3 3105Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
ff68c719 3106{
27da23d5 3107 dVAR;
ff68c719 3108 struct sigaction act;
3109
7918f24d
NC
3110 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
3111
a10b1e10
JH
3112#ifdef USE_ITHREADS
3113 /* only "parent" interpreter can diddle signals */
3114 if (PL_curinterp != aTHX)
3115 return -1;
3116#endif
3117
8aad04aa 3118 act.sa_handler = (void(*)(int))handler;
ff68c719 3119 sigemptyset(&act.sa_mask);
3120 act.sa_flags = 0;
3121#ifdef SA_RESTART
4ffa73a3
JH
3122 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3123 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
0a8e0eff 3124#endif
36b5d377 3125#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
8aad04aa 3126 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
85264bed
CS
3127 act.sa_flags |= SA_NOCLDWAIT;
3128#endif
ff68c719 3129 return sigaction(signo, &act, save);
3130}
3131
3132int
864dbfa3 3133Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
ff68c719 3134{
27da23d5 3135 dVAR;
a10b1e10
JH
3136#ifdef USE_ITHREADS
3137 /* only "parent" interpreter can diddle signals */
3138 if (PL_curinterp != aTHX)
3139 return -1;
3140#endif
3141
ff68c719 3142 return sigaction(signo, save, (struct sigaction *)NULL);
3143}
3144
3145#else /* !HAS_SIGACTION */
3146
3147Sighandler_t
864dbfa3 3148Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
ff68c719 3149{
39f1703b 3150#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
3151 /* only "parent" interpreter can diddle signals */
3152 if (PL_curinterp != aTHX)
8aad04aa 3153 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
3154#endif
3155
6ad3d225 3156 return PerlProc_signal(signo, handler);
ff68c719 3157}
3158
fabdb6c0 3159static Signal_t
4e35701f 3160sig_trap(int signo)
ff68c719 3161{
27da23d5
JH
3162 dVAR;
3163 PL_sig_trapped++;
ff68c719 3164}
3165
3166Sighandler_t
864dbfa3 3167Perl_rsignal_state(pTHX_ int signo)
ff68c719 3168{
27da23d5 3169 dVAR;
ff68c719 3170 Sighandler_t oldsig;
3171
39f1703b 3172#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
3173 /* only "parent" interpreter can diddle signals */
3174 if (PL_curinterp != aTHX)
8aad04aa 3175 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
3176#endif
3177
27da23d5 3178 PL_sig_trapped = 0;
6ad3d225
GS
3179 oldsig = PerlProc_signal(signo, sig_trap);
3180 PerlProc_signal(signo, oldsig);
27da23d5 3181 if (PL_sig_trapped)
3aed30dc 3182 PerlProc_kill(PerlProc_getpid(), signo);
ff68c719 3183 return oldsig;
3184}
3185
3186int
864dbfa3 3187Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
ff68c719 3188{
39f1703b 3189#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
3190 /* only "parent" interpreter can diddle signals */
3191 if (PL_curinterp != aTHX)
3192 return -1;
3193#endif
6ad3d225 3194 *save = PerlProc_signal(signo, handler);
8aad04aa 3195 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
ff68c719 3196}
3197
3198int
864dbfa3 3199Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
ff68c719 3200{
39f1703b 3201#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
3202 /* only "parent" interpreter can diddle signals */
3203 if (PL_curinterp != aTHX)
3204 return -1;
3205#endif
8aad04aa 3206 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
ff68c719 3207}
3208
3209#endif /* !HAS_SIGACTION */
64ca3a65 3210#endif /* !PERL_MICRO */
ff68c719 3211
5f05dabc 3212 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
e37778c2 3213#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
79072805 3214I32
864dbfa3 3215Perl_my_pclose(pTHX_ PerlIO *ptr)
a687059c 3216{
97aff369 3217 dVAR;
ff68c719 3218 Sigsave_t hstat, istat, qstat;
a687059c 3219 int status;
a0d0e21e 3220 SV **svp;
d8a83dd3 3221 Pid_t pid;
2e0cfa16 3222 Pid_t pid2 = 0;
03136e13 3223 bool close_failed;
4ee39169 3224 dSAVEDERRNO;
2e0cfa16
FC
3225 const int fd = PerlIO_fileno(ptr);
3226
b6ae43b7 3227#ifdef USE_PERLIO
2e0cfa16
FC
3228 /* Find out whether the refcount is low enough for us to wait for the
3229 child proc without blocking. */
3230 const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
b6ae43b7
NC
3231#else
3232 const bool should_wait = 1;
3233#endif
a687059c 3234
2e0cfa16 3235 svp = av_fetch(PL_fdpid,fd,TRUE);
25d92023 3236 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
a0d0e21e 3237 SvREFCNT_dec(*svp);
3280af22 3238 *svp = &PL_sv_undef;
ddcf38b7
IZ
3239#ifdef OS2
3240 if (pid == -1) { /* Opened by popen. */
3241 return my_syspclose(ptr);
3242 }
a1d180c4 3243#endif
f1618b10
CS
3244 close_failed = (PerlIO_close(ptr) == EOF);
3245 SAVE_ERRNO;
7c0587c8 3246#ifdef UTS
6ad3d225 3247 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
7c0587c8 3248#endif
64ca3a65 3249#ifndef PERL_MICRO
8aad04aa
JH
3250 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3251 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3252 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
64ca3a65 3253#endif
2e0cfa16 3254 if (should_wait) do {
1d3434b8
GS
3255 pid2 = wait4pid(pid, &status, 0);
3256 } while (pid2 == -1 && errno == EINTR);
64ca3a65 3257#ifndef PERL_MICRO
ff68c719 3258 rsignal_restore(SIGHUP, &hstat);
3259 rsignal_restore(SIGINT, &istat);
3260 rsignal_restore(SIGQUIT, &qstat);
64ca3a65 3261#endif
03136e13 3262 if (close_failed) {
4ee39169 3263 RESTORE_ERRNO;
03136e13
CS
3264 return -1;
3265 }
2e0cfa16
FC
3266 return(
3267 should_wait
3268 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3269 : 0
3270 );
20188a90 3271}
9c12f1e5
RGS
3272#else
3273#if defined(__LIBCATAMOUNT__)
3274I32
3275Perl_my_pclose(pTHX_ PerlIO *ptr)
3276{
3277 return -1;
3278}
3279#endif
4633a7c4
LW
3280#endif /* !DOSISH */
3281
e37778c2 3282#if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
79072805 3283I32
d8a83dd3 3284Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
20188a90 3285{
97aff369 3286 dVAR;
27da23d5 3287 I32 result = 0;
7918f24d 3288 PERL_ARGS_ASSERT_WAIT4PID;
b7953727
JH
3289 if (!pid)
3290 return -1;
ca0c25f6 3291#ifdef PERL_USES_PL_PIDSTATUS
b7953727 3292 {
3aed30dc 3293 if (pid > 0) {
12072db5
NC
3294 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3295 pid, rather than a string form. */
c4420975 3296 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3aed30dc
HS
3297 if (svp && *svp != &PL_sv_undef) {
3298 *statusp = SvIVX(*svp);
12072db5
NC
3299 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3300 G_DISCARD);
3aed30dc
HS
3301 return pid;
3302 }
3303 }
3304 else {
3305 HE *entry;
3306
3307 hv_iterinit(PL_pidstatus);
3308 if ((entry = hv_iternext(PL_pidstatus))) {
c4420975 3309 SV * const sv = hv_iterval(PL_pidstatus,entry);
7ea75b61 3310 I32 len;
0bcc34c2 3311 const char * const spid = hv_iterkey(entry,&len);
27da23d5 3312
12072db5
NC
3313 assert (len == sizeof(Pid_t));
3314 memcpy((char *)&pid, spid, len);
3aed30dc 3315 *statusp = SvIVX(sv);
7b9a3241
NC
3316 /* The hash iterator is currently on this entry, so simply
3317 calling hv_delete would trigger the lazy delete, which on
3318 aggregate does more work, beacuse next call to hv_iterinit()
3319 would spot the flag, and have to call the delete routine,
3320 while in the meantime any new entries can't re-use that
3321 memory. */
3322 hv_iterinit(PL_pidstatus);
7ea75b61 3323 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3aed30dc
HS
3324 return pid;
3325 }
20188a90
LW
3326 }
3327 }
68a29c53 3328#endif
79072805 3329#ifdef HAS_WAITPID
367f3c24
IZ
3330# ifdef HAS_WAITPID_RUNTIME
3331 if (!HAS_WAITPID_RUNTIME)
3332 goto hard_way;
3333# endif
cddd4526 3334 result = PerlProc_waitpid(pid,statusp,flags);
dfcfdb64 3335 goto finish;
367f3c24
IZ
3336#endif
3337#if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
4608196e 3338 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
dfcfdb64 3339 goto finish;
367f3c24 3340#endif
ca0c25f6 3341#ifdef PERL_USES_PL_PIDSTATUS
27da23d5 3342#if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
367f3c24 3343 hard_way:
27da23d5 3344#endif
a0d0e21e 3345 {
a0d0e21e 3346 if (flags)
cea2e8a9 3347 Perl_croak(aTHX_ "Can't do waitpid with flags");
a0d0e21e 3348 else {
76e3520e 3349 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
a0d0e21e
LW
3350 pidgone(result,*statusp);
3351 if (result < 0)
3352 *statusp = -1;
3353 }
a687059c
LW
3354 }
3355#endif
27da23d5 3356#if defined(HAS_WAITPID) || defined(HAS_WAIT4)
dfcfdb64 3357 finish:
27da23d5 3358#endif
cddd4526
NIS
3359 if (result < 0 && errno == EINTR) {
3360 PERL_ASYNC_CHECK();
48dbb59e 3361 errno = EINTR; /* reset in case a signal handler changed $! */
cddd4526
NIS
3362 }
3363 return result;
a687059c 3364}
2986a63f 3365#endif /* !DOSISH || OS2 || WIN32 || NETWARE */
a687059c 3366
ca0c25f6 3367#ifdef PERL_USES_PL_PIDSTATUS
7c0587c8 3368void
ed4173ef 3369S_pidgone(pTHX_ Pid_t pid, int status)
a687059c 3370{
79072805 3371 register SV *sv;
a687059c 3372
12072db5 3373 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
862a34c6 3374 SvUPGRADE(sv,SVt_IV);
45977657 3375 SvIV_set(sv, status);
20188a90 3376 return;
a687059c 3377}
ca0c25f6 3378#endif
a687059c 3379
85ca448a 3380#if defined(atarist) || defined(OS2) || defined(EPOC)
7c0587c8 3381int pclose();
ddcf38b7
IZ
3382#ifdef HAS_FORK
3383int /* Cannot prototype with I32
3384 in os2ish.h. */
ba106d47 3385my_syspclose(PerlIO *ptr)
ddcf38b7 3386#else
79072805 3387I32
864dbfa3 3388Perl_my_pclose(pTHX_ PerlIO *ptr)
a1d180c4 3389#endif
a687059c 3390{
760ac839 3391 /* Needs work for PerlIO ! */
c4420975 3392 FILE * const f = PerlIO_findFILE(ptr);
7452cf6a 3393 const I32 result = pclose(f);
2b96b0a5
JH
3394 PerlIO_releaseFILE(ptr,f);
3395 return result;
3396}
3397#endif
3398
933fea7f 3399#if defined(DJGPP)
2b96b0a5
JH
3400int djgpp_pclose();
3401I32
3402Perl_my_pclose(pTHX_ PerlIO *ptr)
3403{
3404 /* Needs work for PerlIO ! */
c4420975 3405 FILE * const f = PerlIO_findFILE(ptr);
2b96b0a5 3406 I32 result = djgpp_pclose(f);
933fea7f 3407 result = (result << 8) & 0xff00;
760ac839
LW
3408 PerlIO_releaseFILE(ptr,f);
3409 return result;
a687059c 3410}
7c0587c8 3411#endif
9f68db38 3412
16fa5c11 3413#define PERL_REPEATCPY_LINEAR 4
9f68db38 3414void
26e1303d 3415Perl_repeatcpy(register char *to, register const char *from, I32 len, register IV count)
9f68db38 3416{
7918f24d
NC
3417 PERL_ARGS_ASSERT_REPEATCPY;
3418
16fa5c11
VP
3419 if (len == 1)
3420 memset(to, *from, count);
3421 else if (count) {
3422 register char *p = to;
26e1303d 3423 IV items, linear, half;
16fa5c11
VP
3424
3425 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3426 for (items = 0; items < linear; ++items) {
3427 register const char *q = from;
26e1303d 3428 IV todo;
16fa5c11
VP
3429 for (todo = len; todo > 0; todo--)
3430 *p++ = *q++;
3431 }
3432
3433 half = count / 2;
3434 while (items <= half) {
26e1303d 3435 IV size = items * len;
16fa5c11
VP
3436 memcpy(p, to, size);
3437 p += size;
3438 items *= 2;
9f68db38 3439 }
16fa5c11
VP
3440
3441 if (count > items)
3442 memcpy(p, to, (count - items) * len);
9f68db38
LW
3443 }
3444}
0f85fab0 3445
fe14fcc3 3446#ifndef HAS_RENAME
79072805 3447I32
4373e329 3448Perl_same_dirent(pTHX_ const char *a, const char *b)
62b28dd9 3449{
93a17b20
LW
3450 char *fa = strrchr(a,'/');
3451 char *fb = strrchr(b,'/');
c623ac67
GS
3452 Stat_t tmpstatbuf1;
3453 Stat_t tmpstatbuf2;
c4420975 3454 SV * const tmpsv = sv_newmortal();
62b28dd9 3455
7918f24d
NC
3456 PERL_ARGS_ASSERT_SAME_DIRENT;
3457
62b28dd9
LW
3458 if (fa)
3459 fa++;
3460 else
3461 fa = a;
3462 if (fb)
3463 fb++;
3464 else
3465 fb = b;
3466 if (strNE(a,b))
3467 return FALSE;
3468 if (fa == a)
76f68e9b 3469 sv_setpvs(tmpsv, ".");
62b28dd9 3470 else
46fc3d4c 3471 sv_setpvn(tmpsv, a, fa - a);
95a20fc0 3472 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
62b28dd9
LW
3473 return FALSE;
3474 if (fb == b)
76f68e9b 3475 sv_setpvs(tmpsv, ".");
62b28dd9 3476 else
46fc3d4c 3477 sv_setpvn(tmpsv, b, fb - b);
95a20fc0 3478 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
62b28dd9
LW
3479 return FALSE;
3480 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3481 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3482}
fe14fcc3
LW
3483#endif /* !HAS_RENAME */
3484
491527d0 3485char*
7f315aed
NC
3486Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3487 const char *const *const search_ext, I32 flags)
491527d0 3488{
97aff369 3489 dVAR;
bd61b366
SS
3490 const char *xfound = NULL;
3491 char *xfailed = NULL;
0f31cffe 3492 char tmpbuf[MAXPATHLEN];
491527d0 3493 register char *s;
5f74f29c 3494 I32 len = 0;
491527d0 3495 int retval;
39a02377 3496 char *bufend;
491527d0
GS
3497#if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3498# define SEARCH_EXTS ".bat", ".cmd", NULL
3499# define MAX_EXT_LEN 4
3500#endif
3501#ifdef OS2
3502# define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3503# define MAX_EXT_LEN 4
3504#endif
3505#ifdef VMS
3506# define SEARCH_EXTS ".pl", ".com", NULL
3507# define MAX_EXT_LEN 4
3508#endif
3509 /* additional extensions to try in each dir if scriptname not found */
3510#ifdef SEARCH_EXTS
0bcc34c2 3511 static const char *const exts[] = { SEARCH_EXTS };
7f315aed 3512 const char *const *const ext = search_ext ? search_ext : exts;
491527d0 3513 int extidx = 0, i = 0;
bd61b366 3514 const char *curext = NULL;
491527d0 3515#else
53c1dcc0 3516 PERL_UNUSED_ARG(search_ext);
491527d0
GS
3517# define MAX_EXT_LEN 0
3518#endif
3519
7918f24d
NC
3520 PERL_ARGS_ASSERT_FIND_SCRIPT;
3521
491527d0
GS
3522 /*
3523 * If dosearch is true and if scriptname does not contain path
3524 * delimiters, search the PATH for scriptname.
3525 *
3526 * If SEARCH_EXTS is also defined, will look for each
3527 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3528 * while searching the PATH.
3529 *
3530 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3531 * proceeds as follows:
3532 * If DOSISH or VMSISH:
3533 * + look for ./scriptname{,.foo,.bar}
3534 * + search the PATH for scriptname{,.foo,.bar}
3535 *
3536 * If !DOSISH:
3537 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3538 * this will not look in '.' if it's not in the PATH)
3539 */
84486fc6 3540 tmpbuf[0] = '\0';
491527d0
GS
3541
3542#ifdef VMS
3543# ifdef ALWAYS_DEFTYPES
3544 len = strlen(scriptname);
3545 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
c4420975 3546 int idx = 0, deftypes = 1;
491527d0
GS
3547 bool seen_dot = 1;
3548
bd61b366 3549 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
491527d0
GS
3550# else
3551 if (dosearch) {
c4420975 3552 int idx = 0, deftypes = 1;
491527d0
GS
3553 bool seen_dot = 1;
3554
bd61b366 3555 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
491527d0
GS
3556# endif
3557 /* The first time through, just add SEARCH_EXTS to whatever we
3558 * already have, so we can check for default file types. */
3559 while (deftypes ||
84486fc6 3560 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
491527d0
GS
3561 {
3562 if (deftypes) {
3563 deftypes = 0;
84486fc6 3564 *tmpbuf = '\0';
491527d0 3565 }
84486fc6
GS
3566 if ((strlen(tmpbuf) + strlen(scriptname)
3567 + MAX_EXT_LEN) >= sizeof tmpbuf)
491527d0 3568 continue; /* don't search dir with too-long name */
6fca0082 3569 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
491527d0
GS
3570#else /* !VMS */
3571
3572#ifdef DOSISH
3573 if (strEQ(scriptname, "-"))
3574 dosearch = 0;
3575 if (dosearch) { /* Look in '.' first. */
fe2774ed 3576 const char *cur = scriptname;
491527d0
GS
3577#ifdef SEARCH_EXTS
3578 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3579 while (ext[i])
3580 if (strEQ(ext[i++],curext)) {
3581 extidx = -1; /* already has an ext */
3582 break;
3583 }
3584 do {
3585#endif
3586 DEBUG_p(PerlIO_printf(Perl_debug_log,
3587 "Looking for %s\n",cur));
017f25f1
IZ
3588 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3589 && !S_ISDIR(PL_statbuf.st_mode)) {
491527d0
GS
3590 dosearch = 0;
3591 scriptname = cur;
3592#ifdef SEARCH_EXTS
3593 break;
3594#endif
3595 }
3596#ifdef SEARCH_EXTS
3597 if (cur == scriptname) {
3598 len = strlen(scriptname);
84486fc6 3599 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
491527d0 3600 break;
9e4425f7
SH
3601 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3602 cur = tmpbuf;
491527d0
GS
3603 }
3604 } while (extidx >= 0 && ext[extidx] /* try an extension? */
6fca0082 3605 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
491527d0
GS
3606#endif
3607 }
3608#endif
3609
3610 if (dosearch && !strchr(scriptname, '/')
3611#ifdef DOSISH
3612 && !strchr(scriptname, '\\')
3613#endif
cd39f2b6 3614 && (s = PerlEnv_getenv("PATH")))
cd39f2b6 3615 {
491527d0 3616 bool seen_dot = 0;
92f0c265 3617
39a02377
DM
3618 bufend = s + strlen(s);
3619 while (s < bufend) {
491527d0
GS
3620#if defined(atarist) || defined(DOSISH)
3621 for (len = 0; *s
3622# ifdef atarist
3623 && *s != ','
3624# endif
3625 && *s != ';'; len++, s++) {
84486fc6
GS
3626 if (len < sizeof tmpbuf)
3627 tmpbuf[len] = *s;
491527d0 3628 }
84486fc6
GS
3629 if (len < sizeof tmpbuf)
3630 tmpbuf[len] = '\0';
491527d0 3631#else /* ! (atarist || DOSISH) */
39a02377 3632 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
491527d0
GS
3633 ':',
3634 &len);
3635#endif /* ! (atarist || DOSISH) */
39a02377 3636 if (s < bufend)
491527d0 3637 s++;
84486fc6 3638 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
491527d0
GS
3639 continue; /* don't search dir with too-long name */
3640 if (len
cd86ed9d 3641# if defined(atarist) || defined(DOSISH)
84486fc6
GS
3642 && tmpbuf[len - 1] != '/'
3643 && tmpbuf[len - 1] != '\\'
490a0e98 3644# endif
491527d0 3645 )
84486fc6
GS
3646 tmpbuf[len++] = '/';
3647 if (len == 2 && tmpbuf[0] == '.')
491527d0 3648 seen_dot = 1;
28f0d0ec 3649 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
491527d0
GS
3650#endif /* !VMS */
3651
3652#ifdef SEARCH_EXTS
84486fc6 3653 len = strlen(tmpbuf);
491527d0
GS
3654 if (extidx > 0) /* reset after previous loop */
3655 extidx = 0;
3656 do {
3657#endif
84486fc6 3658 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3280af22 3659 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
017f25f1
IZ
3660 if (S_ISDIR(PL_statbuf.st_mode)) {
3661 retval = -1;
3662 }
491527d0
GS
3663#ifdef SEARCH_EXTS
3664 } while ( retval < 0 /* not there */
3665 && extidx>=0 && ext[extidx] /* try an extension? */
6fca0082 3666 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
491527d0
GS
3667 );
3668#endif
3669 if (retval < 0)
3670 continue;
3280af22
NIS
3671 if (S_ISREG(PL_statbuf.st_mode)
3672 && cando(S_IRUSR,TRUE,&PL_statbuf)
e37778c2 3673#if !defined(DOSISH)
3280af22 3674 && cando(S_IXUSR,TRUE,&PL_statbuf)
491527d0
GS
3675#endif
3676 )
3677 {
3aed30dc 3678 xfound = tmpbuf; /* bingo! */
491527d0
GS
3679 break;
3680 }
3681 if (!xfailed)
84486fc6 3682 xfailed = savepv(tmpbuf);
491527d0
GS
3683 }
3684#ifndef DOSISH
017f25f1 3685 if (!xfound && !seen_dot && !xfailed &&
a1d180c4 3686 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
017f25f1 3687 || S_ISDIR(PL_statbuf.st_mode)))
491527d0
GS
3688#endif
3689 seen_dot = 1; /* Disable message. */
9ccb31f9
GS
3690 if (!xfound) {
3691 if (flags & 1) { /* do or die? */
6ad282c7 3692 /* diag_listed_as: Can't execute %s */
3aed30dc 3693 Perl_croak(aTHX_ "Can't %s %s%s%s",
9ccb31f9
GS
3694 (xfailed ? "execute" : "find"),
3695 (xfailed ? xfailed : scriptname),
3696 (xfailed ? "" : " on PATH"),
3697 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3698 }
bd61b366 3699 scriptname = NULL;
9ccb31f9 3700 }
43c5f42d 3701 Safefree(xfailed);
491527d0
GS
3702 scriptname = xfound;
3703 }
bd61b366 3704 return (scriptname ? savepv(scriptname) : NULL);
491527d0
GS
3705}
3706
ba869deb
GS
3707#ifndef PERL_GET_CONTEXT_DEFINED
3708
3709void *
3710Perl_get_context(void)
3711{
27da23d5 3712 dVAR;
3db8f154 3713#if defined(USE_ITHREADS)
ba869deb
GS
3714# ifdef OLD_PTHREADS_API
3715 pthread_addr_t t;
5637ef5b
NC
3716 int error = pthread_getspecific(PL_thr_key, &t)
3717 if (error)
3718 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
ba869deb
GS
3719 return (void*)t;
3720# else
bce813aa 3721# ifdef I_MACH_CTHREADS
8b8b35ab 3722 return (void*)cthread_data(cthread_self());
bce813aa 3723# else
8b8b35ab
JH
3724 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3725# endif
c44d3fdb 3726# endif
ba869deb
GS
3727#else
3728 return (void*)NULL;
3729#endif
3730}
3731
3732void
3733Perl_set_context(void *t)
3734{
8772537c 3735 dVAR;
7918f24d 3736 PERL_ARGS_ASSERT_SET_CONTEXT;
3db8f154 3737#if defined(USE_ITHREADS)
c44d3fdb
GS
3738# ifdef I_MACH_CTHREADS
3739 cthread_set_data(cthread_self(), t);
3740# else
5637ef5b
NC
3741 {
3742 const int error = pthread_setspecific(PL_thr_key, t);
3743 if (error)
3744 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3745 }
c44d3fdb 3746# endif
b464bac0 3747#else
8772537c 3748 PERL_UNUSED_ARG(t);
ba869deb
GS
3749#endif
3750}
3751
3752#endif /* !PERL_GET_CONTEXT_DEFINED */
491527d0 3753
27da23d5 3754#if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
22239a37 3755struct perl_vars *
864dbfa3 3756Perl_GetVars(pTHX)
22239a37 3757{
533c011a 3758 return &PL_Vars;
22239a37 3759}
31fb1209
NIS
3760#endif
3761
1cb0ed9b 3762char **
864dbfa3 3763Perl_get_op_names(pTHX)
31fb1209 3764{
96a5add6
AL
3765 PERL_UNUSED_CONTEXT;
3766 return (char **)PL_op_name;
31fb1209
NIS
3767}
3768
1cb0ed9b 3769char **
864dbfa3 3770Perl_get_op_descs(pTHX)
31fb1209 3771{
96a5add6
AL
3772 PERL_UNUSED_CONTEXT;
3773 return (char **)PL_op_desc;
31fb1209 3774}
9e6b2b00 3775
e1ec3a88 3776const char *
864dbfa3 3777Perl_get_no_modify(pTHX)
9e6b2b00 3778{
96a5add6
AL
3779 PERL_UNUSED_CONTEXT;
3780 return PL_no_modify;
9e6b2b00
GS
3781}
3782
3783U32 *
864dbfa3 3784Perl_get_opargs(pTHX)
9e6b2b00 3785{
96a5add6
AL
3786 PERL_UNUSED_CONTEXT;
3787 return (U32 *)PL_opargs;
9e6b2b00 3788}
51aa15f3 3789
0cb96387
GS
3790PPADDR_t*
3791Perl_get_ppaddr(pTHX)
3792{
96a5add6
AL
3793 dVAR;
3794 PERL_UNUSED_CONTEXT;
3795 return (PPADDR_t*)PL_ppaddr;
0cb96387
GS
3796}
3797
a6c40364
GS
3798#ifndef HAS_GETENV_LEN
3799char *
bf4acbe4 3800Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
a6c40364 3801{
8772537c 3802 char * const env_trans = PerlEnv_getenv(env_elem);
96a5add6 3803 PERL_UNUSED_CONTEXT;
7918f24d 3804 PERL_ARGS_ASSERT_GETENV_LEN;
a6c40364
GS
3805 if (env_trans)
3806 *len = strlen(env_trans);
3807 return env_trans;
f675dbe5
CB
3808}
3809#endif
3810
dc9e4912
GS
3811
3812MGVTBL*
864dbfa3 3813Perl_get_vtbl(pTHX_ int vtbl_id)
dc9e4912 3814{
96a5add6 3815 PERL_UNUSED_CONTEXT;
dc9e4912 3816
c7fdacb9
NC
3817 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3818 ? NULL : PL_magic_vtables + vtbl_id;
dc9e4912
GS
3819}
3820
767df6a1 3821I32
864dbfa3 3822Perl_my_fflush_all(pTHX)
767df6a1 3823{
f800e14d 3824#if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
ce720889 3825 return PerlIO_flush(NULL);
767df6a1 3826#else
8fbdfb7c 3827# if defined(HAS__FWALK)
f13a2bc0 3828 extern int fflush(FILE *);
74cac757
JH
3829 /* undocumented, unprototyped, but very useful BSDism */
3830 extern void _fwalk(int (*)(FILE *));
8fbdfb7c 3831 _fwalk(&fflush);
74cac757 3832 return 0;
8fa7f367 3833# else
8fbdfb7c 3834# if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
8fa7f367 3835 long open_max = -1;
8fbdfb7c 3836# ifdef PERL_FFLUSH_ALL_FOPEN_MAX
d2201af2 3837 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
8fbdfb7c 3838# else
8fa7f367 3839# if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
767df6a1 3840 open_max = sysconf(_SC_OPEN_MAX);
8fa7f367
JH
3841# else
3842# ifdef FOPEN_MAX
74cac757 3843 open_max = FOPEN_MAX;
8fa7f367
JH
3844# else
3845# ifdef OPEN_MAX
74cac757 3846 open_max = OPEN_MAX;
8fa7f367
JH
3847# else
3848# ifdef _NFILE
d2201af2 3849 open_max = _NFILE;
8fa7f367
JH
3850# endif
3851# endif
74cac757 3852# endif
767df6a1
JH
3853# endif
3854# endif
767df6a1
JH
3855 if (open_max > 0) {
3856 long i;
3857 for (i = 0; i < open_max; i++)
d2201af2
AD
3858 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3859 STDIO_STREAM_ARRAY[i]._file < open_max &&
3860 STDIO_STREAM_ARRAY[i]._flag)
3861 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
767df6a1
JH
3862 return 0;
3863 }
8fbdfb7c 3864# endif
93189314 3865 SETERRNO(EBADF,RMS_IFI);
767df6a1 3866 return EOF;
74cac757 3867# endif
767df6a1
JH
3868#endif
3869}
097ee67d 3870
69282e91 3871void
45219de6 3872Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
a5390457
NC
3873{
3874 if (ckWARN(WARN_IO)) {
3b46b707
BF
3875 SV * const name
3876 = gv && (isGV(gv) || isGV_with_GP(gv))
3877 ? sv_2mortal(newSVhek(GvENAME_HEK((gv))))
3878 : NULL;
a5390457
NC
3879 const char * const direction = have == '>' ? "out" : "in";
3880
3b46b707 3881 if (name && SvPOK(name) && *SvPV_nolen(name))
a5390457 3882 Perl_warner(aTHX_ packWARN(WARN_IO),
3b46b707 3883 "Filehandle %"SVf" opened only for %sput",
a5390457
NC
3884 name, direction);
3885 else
3886 Perl_warner(aTHX_ packWARN(WARN_IO),
3887 "Filehandle opened only for %sput", direction);
3888 }
3889}
3890
3891void
831e4cc3 3892Perl_report_evil_fh(pTHX_ const GV *gv)
bc37a18f 3893{
65820a28 3894 const IO *io = gv ? GvIO(gv) : NULL;
831e4cc3 3895 const PERL_BITFIELD16 op = PL_op->op_type;
a5390457
NC
3896 const char *vile;
3897 I32 warn_type;
3898
65820a28 3899 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
a5390457
NC
3900 vile = "closed";
3901 warn_type = WARN_CLOSED;
2dd78f96
JH
3902 }
3903 else {
a5390457
NC
3904 vile = "unopened";
3905 warn_type = WARN_UNOPENED;
3906 }
3907
3908 if (ckWARN(warn_type)) {
3b46b707
BF
3909 SV * const name
3910 = gv && (isGV(gv) || isGV_with_GP(gv)) && GvENAMELEN(gv) ?
3911 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
a5390457
NC
3912 const char * const pars =
3913 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3914 const char * const func =
3915 (const char *)
3916 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3917 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
a5390457
NC
3918 PL_op_desc[op]);
3919 const char * const type =
3920 (const char *)
65820a28 3921 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
a5390457 3922 ? "socket" : "filehandle");
65d99836
FC
3923 const bool have_name = name && SvPOK(name) && *SvPV_nolen(name);
3924 Perl_warner(aTHX_ packWARN(warn_type),
3925 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3926 have_name ? " " : "",
3927 SVfARG(have_name ? name : &PL_sv_no));
3928 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
a5390457
NC
3929 Perl_warner(
3930 aTHX_ packWARN(warn_type),
65d99836
FC
3931 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3932 func, pars, have_name ? " " : "",
3933 SVfARG(have_name ? name : &PL_sv_no)
a5390457 3934 );
bc37a18f 3935 }
69282e91 3936}
a926ef6b 3937
f6adc668 3938/* To workaround core dumps from the uninitialised tm_zone we get the
e72cf795
JH
3939 * system to give us a reasonable struct to copy. This fix means that
3940 * strftime uses the tm_zone and tm_gmtoff values returned by
3941 * localtime(time()). That should give the desired result most of the
3942 * time. But probably not always!
3943 *
f6adc668
JH
3944 * This does not address tzname aspects of NETaa14816.
3945 *
e72cf795 3946 */
f6adc668 3947
e72cf795
JH
3948#ifdef HAS_GNULIBC
3949# ifndef STRUCT_TM_HASZONE
3950# define STRUCT_TM_HASZONE
3951# endif
3952#endif
3953
f6adc668
JH
3954#ifdef STRUCT_TM_HASZONE /* Backward compat */
3955# ifndef HAS_TM_TM_ZONE
3956# define HAS_TM_TM_ZONE
3957# endif
3958#endif
3959
e72cf795 3960void
f1208910 3961Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
e72cf795 3962{
f6adc668 3963#ifdef HAS_TM_TM_ZONE
e72cf795 3964 Time_t now;
1b6737cc 3965 const struct tm* my_tm;
7918f24d 3966 PERL_ARGS_ASSERT_INIT_TM;
e72cf795 3967 (void)time(&now);
82c57498 3968 my_tm = localtime(&now);
ca46b8ee
SP
3969 if (my_tm)
3970 Copy(my_tm, ptm, 1, struct tm);
1b6737cc 3971#else
7918f24d 3972 PERL_ARGS_ASSERT_INIT_TM;
1b6737cc 3973 PERL_UNUSED_ARG(ptm);
e72cf795
JH
3974#endif
3975}
3976
3977/*
3978 * mini_mktime - normalise struct tm values without the localtime()
3979 * semantics (and overhead) of mktime().
3980 */
3981void
f1208910 3982Perl_mini_mktime(pTHX_ struct tm *ptm)
e72cf795
JH
3983{
3984 int yearday;
3985 int secs;
3986 int month, mday, year, jday;
3987 int odd_cent, odd_year;
96a5add6 3988 PERL_UNUSED_CONTEXT;
e72cf795 3989
7918f24d
NC
3990 PERL_ARGS_ASSERT_MINI_MKTIME;
3991
e72cf795
JH
3992#define DAYS_PER_YEAR 365
3993#define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3994#define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3995#define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3996#define SECS_PER_HOUR (60*60)
3997#define SECS_PER_DAY (24*SECS_PER_HOUR)
3998/* parentheses deliberately absent on these two, otherwise they don't work */
3999#define MONTH_TO_DAYS 153/5
4000#define DAYS_TO_MONTH 5/153
4001/* offset to bias by March (month 4) 1st between month/mday & year finding */
4002#define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
4003/* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
4004#define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
4005
4006/*
4007 * Year/day algorithm notes:
4008 *
4009 * With a suitable offset for numeric value of the month, one can find
4010 * an offset into the year by considering months to have 30.6 (153/5) days,
4011 * using integer arithmetic (i.e., with truncation). To avoid too much
4012 * messing about with leap days, we consider January and February to be
4013 * the 13th and 14th month of the previous year. After that transformation,
4014 * we need the month index we use to be high by 1 from 'normal human' usage,
4015 * so the month index values we use run from 4 through 15.
4016 *
4017 * Given that, and the rules for the Gregorian calendar (leap years are those
4018 * divisible by 4 unless also divisible by 100, when they must be divisible
4019 * by 400 instead), we can simply calculate the number of days since some
4020 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
4021 * the days we derive from our month index, and adding in the day of the
4022 * month. The value used here is not adjusted for the actual origin which
4023 * it normally would use (1 January A.D. 1), since we're not exposing it.
4024 * We're only building the value so we can turn around and get the
4025 * normalised values for the year, month, day-of-month, and day-of-year.
4026 *
4027 * For going backward, we need to bias the value we're using so that we find
4028 * the right year value. (Basically, we don't want the contribution of
4029 * March 1st to the number to apply while deriving the year). Having done
4030 * that, we 'count up' the contribution to the year number by accounting for
4031 * full quadracenturies (400-year periods) with their extra leap days, plus
4032 * the contribution from full centuries (to avoid counting in the lost leap
4033 * days), plus the contribution from full quad-years (to count in the normal
4034 * leap days), plus the leftover contribution from any non-leap years.
4035 * At this point, if we were working with an actual leap day, we'll have 0
4036 * days left over. This is also true for March 1st, however. So, we have
4037 * to special-case that result, and (earlier) keep track of the 'odd'
4038 * century and year contributions. If we got 4 extra centuries in a qcent,
4039 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
4040 * Otherwise, we add back in the earlier bias we removed (the 123 from
4041 * figuring in March 1st), find the month index (integer division by 30.6),
4042 * and the remainder is the day-of-month. We then have to convert back to
4043 * 'real' months (including fixing January and February from being 14/15 in
4044 * the previous year to being in the proper year). After that, to get
4045 * tm_yday, we work with the normalised year and get a new yearday value for
4046 * January 1st, which we subtract from the yearday value we had earlier,
4047 * representing the date we've re-built. This is done from January 1
4048 * because tm_yday is 0-origin.
4049 *
4050 * Since POSIX time routines are only guaranteed to work for times since the
4051 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
4052 * applies Gregorian calendar rules even to dates before the 16th century
4053 * doesn't bother me. Besides, you'd need cultural context for a given
4054 * date to know whether it was Julian or Gregorian calendar, and that's
4055 * outside the scope for this routine. Since we convert back based on the
4056 * same rules we used to build the yearday, you'll only get strange results
4057 * for input which needed normalising, or for the 'odd' century years which
486ec47a 4058 * were leap years in the Julian calendar but not in the Gregorian one.
e72cf795
JH
4059 * I can live with that.
4060 *
4061 * This algorithm also fails to handle years before A.D. 1 gracefully, but
4062 * that's still outside the scope for POSIX time manipulation, so I don't
4063 * care.
4064 */
4065
4066 year = 1900 + ptm->tm_year;
4067 month = ptm->tm_mon;
4068 mday = ptm->tm_mday;
4069 /* allow given yday with no month & mday to dominate the result */
4070 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
4071 month = 0;
4072 mday = 0;
4073 jday = 1 + ptm->tm_yday;
4074 }
4075 else {
4076 jday = 0;
4077 }
4078 if (month >= 2)
4079 month+=2;
4080 else
4081 month+=14, year--;
4082 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4083 yearday += month*MONTH_TO_DAYS + mday + jday;
4084 /*
4085 * Note that we don't know when leap-seconds were or will be,
4086 * so we have to trust the user if we get something which looks
4087 * like a sensible leap-second. Wild values for seconds will
4088 * be rationalised, however.
4089 */
4090 if ((unsigned) ptm->tm_sec <= 60) {
4091 secs = 0;
4092 }
4093 else {
4094 secs = ptm->tm_sec;
4095 ptm->tm_sec = 0;
4096 }
4097 secs += 60 * ptm->tm_min;
4098 secs += SECS_PER_HOUR * ptm->tm_hour;
4099 if (secs < 0) {
4100 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4101 /* got negative remainder, but need positive time */
4102 /* back off an extra day to compensate */
4103 yearday += (secs/SECS_PER_DAY)-1;
4104 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4105 }
4106 else {
4107 yearday += (secs/SECS_PER_DAY);
4108 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4109 }
4110 }
4111 else if (secs >= SECS_PER_DAY) {
4112 yearday += (secs/SECS_PER_DAY);
4113 secs %= SECS_PER_DAY;
4114 }
4115 ptm->tm_hour = secs/SECS_PER_HOUR;
4116 secs %= SECS_PER_HOUR;
4117 ptm->tm_min = secs/60;
4118 secs %= 60;
4119 ptm->tm_sec += secs;
4120 /* done with time of day effects */
4121 /*
4122 * The algorithm for yearday has (so far) left it high by 428.
4123 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4124 * bias it by 123 while trying to figure out what year it
4125 * really represents. Even with this tweak, the reverse
4126 * translation fails for years before A.D. 0001.
4127 * It would still fail for Feb 29, but we catch that one below.
4128 */
4129 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
4130 yearday -= YEAR_ADJUST;
4131 year = (yearday / DAYS_PER_QCENT) * 400;
4132 yearday %= DAYS_PER_QCENT;
4133 odd_cent = yearday / DAYS_PER_CENT;
4134 year += odd_cent * 100;
4135 yearday %= DAYS_PER_CENT;
4136 year += (yearday / DAYS_PER_QYEAR) * 4;
4137 yearday %= DAYS_PER_QYEAR;
4138 odd_year = yearday / DAYS_PER_YEAR;
4139 year += odd_year;
4140 yearday %= DAYS_PER_YEAR;
4141 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4142 month = 1;
4143 yearday = 29;
4144 }
4145 else {
4146 yearday += YEAR_ADJUST; /* recover March 1st crock */
4147 month = yearday*DAYS_TO_MONTH;
4148 yearday -= month*MONTH_TO_DAYS;
4149 /* recover other leap-year adjustment */
4150 if (month > 13) {
4151 month-=14;
4152 year++;
4153 }
4154 else {
4155 month-=2;
4156 }
4157 }
4158 ptm->tm_year = year - 1900;
4159 if (yearday) {
4160 ptm->tm_mday = yearday;
4161 ptm->tm_mon = month;
4162 }
4163 else {
4164 ptm->tm_mday = 31;
4165 ptm->tm_mon = month - 1;
4166 }
4167 /* re-build yearday based on Jan 1 to get tm_yday */
4168 year--;
4169 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4170 yearday += 14*MONTH_TO_DAYS + 1;
4171 ptm->tm_yday = jday - yearday;
4172 /* fix tm_wday if not overridden by caller */
4173 if ((unsigned)ptm->tm_wday > 6)
4174 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4175}
b3c85772
JH
4176
4177char *
e1ec3a88 4178Perl_my_strftime(pTHX_ const char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
b3c85772
JH
4179{
4180#ifdef HAS_STRFTIME
4181 char *buf;
4182 int buflen;
4183 struct tm mytm;
4184 int len;
4185
7918f24d
NC
4186 PERL_ARGS_ASSERT_MY_STRFTIME;
4187
b3c85772
JH
4188 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4189 mytm.tm_sec = sec;
4190 mytm.tm_min = min;
4191 mytm.tm_hour = hour;
4192 mytm.tm_mday = mday;
4193 mytm.tm_mon = mon;
4194 mytm.tm_year = year;
4195 mytm.tm_wday = wday;
4196 mytm.tm_yday = yday;
4197 mytm.tm_isdst = isdst;
4198 mini_mktime(&mytm);
c473feec
SR
4199 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4200#if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4201 STMT_START {
4202 struct tm mytm2;
4203 mytm2 = mytm;
4204 mktime(&mytm2);
4205#ifdef HAS_TM_TM_GMTOFF
4206 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4207#endif
4208#ifdef HAS_TM_TM_ZONE
4209 mytm.tm_zone = mytm2.tm_zone;
4210#endif
4211 } STMT_END;
4212#endif
b3c85772 4213 buflen = 64;
a02a5408 4214 Newx(buf, buflen, char);
b3c85772
JH
4215 len = strftime(buf, buflen, fmt, &mytm);
4216 /*
877f6a72 4217 ** The following is needed to handle to the situation where
b3c85772
JH
4218 ** tmpbuf overflows. Basically we want to allocate a buffer
4219 ** and try repeatedly. The reason why it is so complicated
4220 ** is that getting a return value of 0 from strftime can indicate
4221 ** one of the following:
4222 ** 1. buffer overflowed,
4223 ** 2. illegal conversion specifier, or
4224 ** 3. the format string specifies nothing to be returned(not
4225 ** an error). This could be because format is an empty string
4226 ** or it specifies %p that yields an empty string in some locale.
4227 ** If there is a better way to make it portable, go ahead by
4228 ** all means.
4229 */
4230 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4231 return buf;
4232 else {
4233 /* Possibly buf overflowed - try again with a bigger buf */
e1ec3a88 4234 const int fmtlen = strlen(fmt);
7743c307 4235 int bufsize = fmtlen + buflen;
877f6a72 4236
c4bc4aaa 4237 Renew(buf, bufsize, char);
b3c85772
JH
4238 while (buf) {
4239 buflen = strftime(buf, bufsize, fmt, &mytm);
4240 if (buflen > 0 && buflen < bufsize)
4241 break;
4242 /* heuristic to prevent out-of-memory errors */
4243 if (bufsize > 100*fmtlen) {
4244 Safefree(buf);
4245 buf = NULL;
4246 break;
4247 }
7743c307
SH
4248 bufsize *= 2;
4249 Renew(buf, bufsize, char);
b3c85772
JH
4250 }
4251 return buf;
4252 }
4253#else
4254 Perl_croak(aTHX_ "panic: no strftime");
27da23d5 4255 return NULL;
b3c85772
JH
4256#endif
4257}
4258
877f6a72
NIS
4259
4260#define SV_CWD_RETURN_UNDEF \
4261sv_setsv(sv, &PL_sv_undef); \
4262return FALSE
4263
4264#define SV_CWD_ISDOT(dp) \
4265 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3aed30dc 4266 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
877f6a72
NIS
4267
4268/*
ccfc67b7
JH
4269=head1 Miscellaneous Functions
4270
89423764 4271=for apidoc getcwd_sv
877f6a72
NIS
4272
4273Fill the sv with current working directory
4274
4275=cut
4276*/
4277
4278/* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4279 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4280 * getcwd(3) if available
4281 * Comments from the orignal:
4282 * This is a faster version of getcwd. It's also more dangerous
4283 * because you might chdir out of a directory that you can't chdir
4284 * back into. */
4285
877f6a72 4286int
89423764 4287Perl_getcwd_sv(pTHX_ register SV *sv)
877f6a72
NIS
4288{
4289#ifndef PERL_MICRO
97aff369 4290 dVAR;
ea715489
JH
4291#ifndef INCOMPLETE_TAINTS
4292 SvTAINTED_on(sv);
4293#endif
4294
7918f24d
NC
4295 PERL_ARGS_ASSERT_GETCWD_SV;
4296
8f95b30d
JH
4297#ifdef HAS_GETCWD
4298 {
60e110a8
DM
4299 char buf[MAXPATHLEN];
4300
3aed30dc 4301 /* Some getcwd()s automatically allocate a buffer of the given
60e110a8
DM
4302 * size from the heap if they are given a NULL buffer pointer.
4303 * The problem is that this behaviour is not portable. */
3aed30dc 4304 if (getcwd(buf, sizeof(buf) - 1)) {
42d9b98d 4305 sv_setpv(sv, buf);
3aed30dc
HS
4306 return TRUE;
4307 }
4308 else {
4309 sv_setsv(sv, &PL_sv_undef);
4310 return FALSE;
4311 }
8f95b30d
JH
4312 }
4313
4314#else
4315
c623ac67 4316 Stat_t statbuf;
877f6a72 4317 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4373e329 4318 int pathlen=0;
877f6a72 4319 Direntry_t *dp;
877f6a72 4320
862a34c6 4321 SvUPGRADE(sv, SVt_PV);
877f6a72 4322
877f6a72 4323 if (PerlLIO_lstat(".", &statbuf) < 0) {
3aed30dc 4324 SV_CWD_RETURN_UNDEF;
877f6a72
NIS
4325 }
4326
4327 orig_cdev = statbuf.st_dev;
4328 orig_cino = statbuf.st_ino;
4329 cdev = orig_cdev;
4330 cino = orig_cino;
4331
4332 for (;;) {
4373e329 4333 DIR *dir;
f56ed502 4334 int namelen;
3aed30dc
HS
4335 odev = cdev;
4336 oino = cino;
4337
4338 if (PerlDir_chdir("..") < 0) {
4339 SV_CWD_RETURN_UNDEF;
4340 }
4341 if (PerlLIO_stat(".", &statbuf) < 0) {
4342 SV_CWD_RETURN_UNDEF;
4343 }
4344
4345 cdev = statbuf.st_dev;
4346 cino = statbuf.st_ino;
4347
4348 if (odev == cdev && oino == cino) {
4349 break;
4350 }
4351 if (!(dir = PerlDir_open("."))) {
4352 SV_CWD_RETURN_UNDEF;
4353 }
4354
4355 while ((dp = PerlDir_read(dir)) != NULL) {
877f6a72 4356#ifdef DIRNAMLEN
f56ed502 4357 namelen = dp->d_namlen;
877f6a72 4358#else
f56ed502 4359 namelen = strlen(dp->d_name);
877f6a72 4360#endif
3aed30dc
HS
4361 /* skip . and .. */
4362 if (SV_CWD_ISDOT(dp)) {
4363 continue;
4364 }
4365
4366 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4367 SV_CWD_RETURN_UNDEF;
4368 }
4369
4370 tdev = statbuf.st_dev;
4371 tino = statbuf.st_ino;
4372 if (tino == oino && tdev == odev) {
4373 break;
4374 }
cb5953d6
JH
4375 }
4376
3aed30dc
HS
4377 if (!dp) {
4378 SV_CWD_RETURN_UNDEF;
4379 }
4380
4381 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4382 SV_CWD_RETURN_UNDEF;
4383 }
877f6a72 4384
3aed30dc
HS
4385 SvGROW(sv, pathlen + namelen + 1);
4386
4387 if (pathlen) {
4388 /* shift down */
95a20fc0 4389 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3aed30dc 4390 }
877f6a72 4391
3aed30dc
HS
4392 /* prepend current directory to the front */
4393 *SvPVX(sv) = '/';
4394 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4395 pathlen += (namelen + 1);
877f6a72
NIS
4396
4397#ifdef VOID_CLOSEDIR
3aed30dc 4398 PerlDir_close(dir);
877f6a72 4399#else
3aed30dc
HS
4400 if (PerlDir_close(dir) < 0) {
4401 SV_CWD_RETURN_UNDEF;
4402 }
877f6a72
NIS
4403#endif
4404 }
4405
60e110a8 4406 if (pathlen) {
3aed30dc
HS
4407 SvCUR_set(sv, pathlen);
4408 *SvEND(sv) = '\0';
4409 SvPOK_only(sv);
877f6a72 4410
95a20fc0 4411 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
3aed30dc
HS
4412 SV_CWD_RETURN_UNDEF;
4413 }
877f6a72
NIS
4414 }
4415 if (PerlLIO_stat(".", &statbuf) < 0) {
3aed30dc 4416 SV_CWD_RETURN_UNDEF;
877f6a72
NIS
4417 }
4418
4419 cdev = statbuf.st_dev;
4420 cino = statbuf.st_ino;
4421
4422 if (cdev != orig_cdev || cino != orig_cino) {
3aed30dc
HS
4423 Perl_croak(aTHX_ "Unstable directory path, "
4424 "current directory changed unexpectedly");
877f6a72 4425 }
877f6a72
NIS
4426
4427 return TRUE;
793b8d8e
JH
4428#endif
4429
877f6a72
NIS
4430#else
4431 return FALSE;
4432#endif
4433}
4434
c812d146 4435#define VERSION_MAX 0x7FFFFFFF
91152fc1 4436
22f16304
RU
4437/*
4438=for apidoc prescan_version
4439
d54f8cf7
JP
4440Validate that a given string can be parsed as a version object, but doesn't
4441actually perform the parsing. Can use either strict or lax validation rules.
4442Can optionally set a number of hint variables to save the parsing code
4443some time when tokenizing.
4444
22f16304
RU
4445=cut
4446*/
91152fc1
DG
4447const char *
4448Perl_prescan_version(pTHX_ const char *s, bool strict,
4449 const char **errstr,
4450 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4451 bool qv = (sqv ? *sqv : FALSE);
4452 int width = 3;
4453 int saw_decimal = 0;
4454 bool alpha = FALSE;
4455 const char *d = s;
4456
4457 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4458
4459 if (qv && isDIGIT(*d))
4460 goto dotted_decimal_version;
4461
4462 if (*d == 'v') { /* explicit v-string */
4463 d++;
4464 if (isDIGIT(*d)) {
4465 qv = TRUE;
4466 }
4467 else { /* degenerate v-string */
4468 /* requires v1.2.3 */
4469 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4470 }
4471
4472dotted_decimal_version:
4473 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4474 /* no leading zeros allowed */
4475 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4476 }
4477
4478 while (isDIGIT(*d)) /* integer part */
4479 d++;
4480
4481 if (*d == '.')
4482 {
4483 saw_decimal++;
4484 d++; /* decimal point */
4485 }
4486 else
4487 {
4488 if (strict) {
4489 /* require v1.2.3 */
4490 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4491 }
4492 else {
4493 goto version_prescan_finish;
4494 }
4495 }
4496
4497 {
4498 int i = 0;
4499 int j = 0;
4500 while (isDIGIT(*d)) { /* just keep reading */
4501 i++;
4502 while (isDIGIT(*d)) {
4503 d++; j++;
4504 /* maximum 3 digits between decimal */
4505 if (strict && j > 3) {
4506 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4507 }
4508 }
4509 if (*d == '_') {
4510 if (strict) {
4511 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4512 }
4513 if ( alpha ) {
4514 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4515 }
4516 d++;
4517 alpha = TRUE;
4518 }
4519 else if (*d == '.') {
4520 if (alpha) {
4521 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4522 }
4523 saw_decimal++;
4524 d++;
4525 }
4526 else if (!isDIGIT(*d)) {
4527 break;
4528 }
4529 j = 0;
4530 }
4531
4532 if (strict && i < 2) {
4533 /* requires v1.2.3 */
4534 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4535 }
4536 }
4537 } /* end if dotted-decimal */
4538 else
4539 { /* decimal versions */
4540 /* special strict case for leading '.' or '0' */
4541 if (strict) {
4542 if (*d == '.') {
4543 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4544 }
4545 if (*d == '0' && isDIGIT(d[1])) {
4546 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4547 }
4548 }
4549
c8c8e589
JP
4550 /* and we never support negative versions */
4551 if ( *d == '-') {
8c72d156 4552 BADVERSION(s,errstr,"Invalid version format (negative version number)");
c8c8e589
JP
4553 }
4554
91152fc1
DG
4555 /* consume all of the integer part */
4556 while (isDIGIT(*d))
4557 d++;
4558
4559 /* look for a fractional part */
4560 if (*d == '.') {
4561 /* we found it, so consume it */
4562 saw_decimal++;
4563 d++;
4564 }
4e4da3ac 4565 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
91152fc1
DG
4566 if ( d == s ) {
4567 /* found nothing */
4568 BADVERSION(s,errstr,"Invalid version format (version required)");
4569 }
4570 /* found just an integer */
4571 goto version_prescan_finish;
4572 }
4573 else if ( d == s ) {
4574 /* didn't find either integer or period */
4575 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4576 }
4577 else if (*d == '_') {
4578 /* underscore can't come after integer part */
4579 if (strict) {
4580 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4581 }
4582 else if (isDIGIT(d[1])) {
4583 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4584 }
4585 else {
4586 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4587 }
4588 }
4589 else {
4590 /* anything else after integer part is just invalid data */
4591 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4592 }
4593
4594 /* scan the fractional part after the decimal point*/
4595
4e4da3ac 4596 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
91152fc1
DG
4597 /* strict or lax-but-not-the-end */
4598 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4599 }
4600
4601 while (isDIGIT(*d)) {
4602 d++;
4603 if (*d == '.' && isDIGIT(d[-1])) {
4604 if (alpha) {
4605 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4606 }
4607 if (strict) {
4608 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4609 }
4610 d = (char *)s; /* start all over again */
4611 qv = TRUE;
4612 goto dotted_decimal_version;
4613 }
4614 if (*d == '_') {
4615 if (strict) {
4616 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4617 }
4618 if ( alpha ) {
4619 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4620 }
4621 if ( ! isDIGIT(d[1]) ) {
4622 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4623 }
4624 d++;
4625 alpha = TRUE;
4626 }
4627 }
4628 }
4629
4630version_prescan_finish:
4631 while (isSPACE(*d))
4632 d++;
4633
4e4da3ac 4634 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
91152fc1
DG
4635 /* trailing non-numeric data */
4636 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4637 }
4638
4639 if (sqv)
4640 *sqv = qv;
4641 if (swidth)
4642 *swidth = width;
4643 if (ssaw_decimal)
4644 *ssaw_decimal = saw_decimal;
4645 if (salpha)
4646 *salpha = alpha;
4647 return d;
4648}
4649
f4758303 4650/*
b0f01acb
JP
4651=for apidoc scan_version
4652
4653Returns a pointer to the next character after the parsed
4654version string, as well as upgrading the passed in SV to
4655an RV.
4656
4657Function must be called with an already existing SV like
4658
137d6fc0 4659 sv = newSV(0);
abc25d8c 4660 s = scan_version(s, SV *sv, bool qv);
b0f01acb
JP
4661
4662Performs some preprocessing to the string to ensure that
4663it has the correct characteristics of a version. Flags the
4664object if it contains an underscore (which denotes this
abc25d8c 4665is an alpha version). The boolean qv denotes that the version
137d6fc0
JP
4666should be interpreted as if it had multiple decimals, even if
4667it doesn't.
b0f01acb
JP
4668
4669=cut
4670*/
4671
9137345a 4672const char *
e1ec3a88 4673Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
b0f01acb 4674{
e0218a61 4675 const char *start;
9137345a
JP
4676 const char *pos;
4677 const char *last;
91152fc1
DG
4678 const char *errstr = NULL;
4679 int saw_decimal = 0;
9137345a 4680 int width = 3;
91152fc1 4681 bool alpha = FALSE;
c812d146 4682 bool vinf = FALSE;
7452cf6a
AL
4683 AV * const av = newAV();
4684 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
7918f24d
NC
4685
4686 PERL_ARGS_ASSERT_SCAN_VERSION;
4687
9137345a 4688 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
cb5772bb 4689
91152fc1
DG
4690#ifndef NODEFAULT_SHAREKEYS
4691 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4692#endif
4693
e0218a61
JP
4694 while (isSPACE(*s)) /* leading whitespace is OK */
4695 s++;
4696
91152fc1
DG
4697 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4698 if (errstr) {
4699 /* "undef" is a special case and not an error */
4700 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4701 Perl_croak(aTHX_ "%s", errstr);
46314c13 4702 }
ad63d80f 4703 }
ad63d80f 4704
91152fc1
DG
4705 start = s;
4706 if (*s == 'v')
4707 s++;
9137345a
JP
4708 pos = s;
4709
4710 if ( qv )
ef8f7699 4711 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
cb5772bb 4712 if ( alpha )
ef8f7699 4713 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
9137345a 4714 if ( !qv && width < 3 )
ef8f7699 4715 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
9137345a 4716
ad63d80f 4717 while (isDIGIT(*pos))
46314c13 4718 pos++;
ad63d80f
JP
4719 if (!isALPHA(*pos)) {
4720 I32 rev;
4721
ad63d80f
JP
4722 for (;;) {
4723 rev = 0;
4724 {
129318bd 4725 /* this is atoi() that delimits on underscores */
9137345a 4726 const char *end = pos;
129318bd 4727 I32 mult = 1;
c812d146 4728 I32 orev;
9137345a 4729
129318bd
JP
4730 /* the following if() will only be true after the decimal
4731 * point of a version originally created with a bare
4732 * floating point number, i.e. not quoted in any way
4733 */
91152fc1 4734 if ( !qv && s > start && saw_decimal == 1 ) {
c76df65e 4735 mult *= 100;
129318bd 4736 while ( s < end ) {
c812d146 4737 orev = rev;
129318bd
JP
4738 rev += (*s - '0') * mult;
4739 mult /= 10;
c812d146
JP
4740 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4741 || (PERL_ABS(rev) > VERSION_MAX )) {
a2a5de95
NC
4742 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4743 "Integer overflow in version %d",VERSION_MAX);
c812d146
JP
4744 s = end - 1;
4745 rev = VERSION_MAX;
4746 vinf = 1;
4747 }
129318bd 4748 s++;
9137345a
JP
4749 if ( *s == '_' )
4750 s++;
129318bd
JP
4751 }
4752 }
4753 else {
4754 while (--end >= s) {
c812d146 4755 orev = rev;
129318bd
JP
4756 rev += (*end - '0') * mult;
4757 mult *= 10;
c812d146
JP
4758 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4759 || (PERL_ABS(rev) > VERSION_MAX )) {
a2a5de95
NC
4760 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4761 "Integer overflow in version");
c812d146
JP
4762 end = s - 1;
4763 rev = VERSION_MAX;
4764 vinf = 1;
4765 }
129318bd
JP
4766 }
4767 }
4768 }
9137345a 4769
129318bd 4770 /* Append revision */
9137345a 4771 av_push(av, newSViv(rev));
c812d146
JP
4772 if ( vinf ) {
4773 s = last;
4774 break;
4775 }
4776 else if ( *pos == '.' )
9137345a
JP
4777 s = ++pos;
4778 else if ( *pos == '_' && isDIGIT(pos[1]) )
ad63d80f 4779 s = ++pos;
f941e658
JP
4780 else if ( *pos == ',' && isDIGIT(pos[1]) )
4781 s = ++pos;
ad63d80f
JP
4782 else if ( isDIGIT(*pos) )
4783 s = pos;
b0f01acb 4784 else {
ad63d80f
JP
4785 s = pos;
4786 break;
4787 }
9137345a
JP
4788 if ( qv ) {
4789 while ( isDIGIT(*pos) )
4790 pos++;
4791 }
4792 else {
4793 int digits = 0;
4794 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4795 if ( *pos != '_' )
4796 digits++;
4797 pos++;
4798 }
b0f01acb
JP
4799 }
4800 }
4801 }
9137345a
JP
4802 if ( qv ) { /* quoted versions always get at least three terms*/
4803 I32 len = av_len(av);
4edfc503
NC
4804 /* This for loop appears to trigger a compiler bug on OS X, as it
4805 loops infinitely. Yes, len is negative. No, it makes no sense.
4806 Compiler in question is:
4807 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4808 for ( len = 2 - len; len > 0; len-- )
502c6561 4809 av_push(MUTABLE_AV(sv), newSViv(0));
4edfc503
NC
4810 */
4811 len = 2 - len;
4812 while (len-- > 0)
9137345a 4813 av_push(av, newSViv(0));
b9381830 4814 }
9137345a 4815
8cb289bd 4816 /* need to save off the current version string for later */
c812d146
JP
4817 if ( vinf ) {
4818 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
ef8f7699
NC
4819 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4820 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
c812d146
JP
4821 }
4822 else if ( s > start ) {
8cb289bd 4823 SV * orig = newSVpvn(start,s-start);
91152fc1 4824 if ( qv && saw_decimal == 1 && *start != 'v' ) {
8cb289bd
RGS
4825 /* need to insert a v to be consistent */
4826 sv_insert(orig, 0, 0, "v", 1);
4827 }
ef8f7699 4828 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
8cb289bd
RGS
4829 }
4830 else {
76f68e9b 4831 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
9137345a 4832 av_push(av, newSViv(0));
8cb289bd
RGS
4833 }
4834
4835 /* And finally, store the AV in the hash */
daba3364 4836 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
9137345a 4837
92dcf8ce
JP
4838 /* fix RT#19517 - special case 'undef' as string */
4839 if ( *s == 'u' && strEQ(s,"undef") ) {
4840 s += 5;
4841 }
4842
9137345a 4843 return s;
b0f01acb
JP
4844}
4845
4846/*
4847=for apidoc new_version
4848
4849Returns a new version object based on the passed in SV:
4850
4851 SV *sv = new_version(SV *ver);
4852
4853Does not alter the passed in ver SV. See "upg_version" if you
4854want to upgrade the SV.
4855
4856=cut
4857*/
4858
4859SV *
4860Perl_new_version(pTHX_ SV *ver)
4861{
97aff369 4862 dVAR;
2d03de9c 4863 SV * const rv = newSV(0);
7918f24d 4864 PERL_ARGS_ASSERT_NEW_VERSION;
573a19fb 4865 if ( sv_isobject(ver) && sv_derived_from(ver, "version") )
bc4eb4d6 4866 /* can just copy directly */
d7aa5382
JP
4867 {
4868 I32 key;
53c1dcc0 4869 AV * const av = newAV();
9137345a
JP
4870 AV *sav;
4871 /* This will get reblessed later if a derived class*/
e0218a61 4872 SV * const hv = newSVrv(rv, "version");
9137345a 4873 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
91152fc1
DG
4874#ifndef NODEFAULT_SHAREKEYS
4875 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4876#endif
9137345a
JP
4877
4878 if ( SvROK(ver) )
4879 ver = SvRV(ver);
4880
4881 /* Begin copying all of the elements */
ef8f7699
NC
4882 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4883 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
9137345a 4884
ef8f7699
NC
4885 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4886 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
9137345a 4887
ef8f7699 4888 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
d7aa5382 4889 {
ef8f7699
NC
4890 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4891 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
d7aa5382 4892 }
9137345a 4893
ef8f7699 4894 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
8cb289bd 4895 {
ef8f7699
NC
4896 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4897 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
8cb289bd
RGS
4898 }
4899
502c6561 4900 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
9137345a
JP
4901 /* This will get reblessed later if a derived class*/
4902 for ( key = 0; key <= av_len(sav); key++ )
4903 {
4904 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4905 av_push(av, newSViv(rev));
4906 }
4907
daba3364 4908 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
d7aa5382
JP
4909 return rv;
4910 }
ad63d80f 4911#ifdef SvVOK
4f2da183 4912 {
3c21775b 4913 const MAGIC* const mg = SvVSTRING_mg(ver);
4f2da183
NC
4914 if ( mg ) { /* already a v-string */
4915 const STRLEN len = mg->mg_len;
4916 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4917 sv_setpvn(rv,version,len);
8cb289bd 4918 /* this is for consistency with the pure Perl class */
91152fc1 4919 if ( isDIGIT(*version) )
8cb289bd 4920 sv_insert(rv, 0, 0, "v", 1);
4f2da183
NC
4921 Safefree(version);
4922 }
4923 else {
ad63d80f 4924#endif
4f2da183 4925 sv_setsv(rv,ver); /* make a duplicate */
137d6fc0 4926#ifdef SvVOK
4f2da183 4927 }
26ec6fc3 4928 }
137d6fc0 4929#endif
ac0e6a2f 4930 return upg_version(rv, FALSE);
b0f01acb
JP
4931}
4932
4933/*
4934=for apidoc upg_version
4935
4936In-place upgrade of the supplied SV to a version object.
4937
ac0e6a2f 4938 SV *sv = upg_version(SV *sv, bool qv);
b0f01acb 4939
ac0e6a2f
RGS
4940Returns a pointer to the upgraded SV. Set the boolean qv if you want
4941to force this SV to be interpreted as an "extended" version.
b0f01acb
JP
4942
4943=cut
4944*/
4945
4946SV *
ac0e6a2f 4947Perl_upg_version(pTHX_ SV *ver, bool qv)
b0f01acb 4948{
cd57dc11 4949 const char *version, *s;
4f2da183
NC
4950#ifdef SvVOK
4951 const MAGIC *mg;
4952#endif
137d6fc0 4953
7918f24d
NC
4954 PERL_ARGS_ASSERT_UPG_VERSION;
4955
ac0e6a2f 4956 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
137d6fc0 4957 {
909d3787
KW
4958 STRLEN len;
4959
ac0e6a2f 4960 /* may get too much accuracy */
137d6fc0 4961 char tbuf[64];
78e230ae
FC
4962 SV *sv = SvNVX(ver) > 10e50 ? newSV(64) : 0;
4963 char *buf;
b5b5a8f0 4964#ifdef USE_LOCALE_NUMERIC
909d3787
KW
4965 char *loc = savepv(setlocale(LC_NUMERIC, NULL));
4966 setlocale(LC_NUMERIC, "C");
b5b5a8f0 4967#endif
78e230ae 4968 if (sv) {
d29d0fd4 4969 Perl_sv_setpvf(aTHX_ sv, "%.9"NVff, SvNVX(ver));
78e230ae
FC
4970 buf = SvPV(sv, len);
4971 }
4972 else {
4973 len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4974 buf = tbuf;
4975 }
b5b5a8f0
RGS
4976#ifdef USE_LOCALE_NUMERIC
4977 setlocale(LC_NUMERIC, loc);
909d3787 4978 Safefree(loc);
b5b5a8f0 4979#endif
78e230ae
FC
4980 while (buf[len-1] == '0' && len > 0) len--;
4981 if ( buf[len-1] == '.' ) len--; /* eat the trailing decimal */
4982 version = savepvn(buf, len);
4983 SvREFCNT_dec(sv);
137d6fc0 4984 }
ad63d80f 4985#ifdef SvVOK
666cce26 4986 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
ad63d80f 4987 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
91152fc1 4988 qv = TRUE;
b0f01acb 4989 }
ad63d80f 4990#endif
137d6fc0
JP
4991 else /* must be a string or something like a string */
4992 {
ac0e6a2f
RGS
4993 STRLEN len;
4994 version = savepv(SvPV(ver,len));
4995#ifndef SvVOK
4996# if PERL_VERSION > 5
4997 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
d54f8cf7 4998 if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
ac0e6a2f 4999 /* may be a v-string */
d54f8cf7
JP
5000 char *testv = (char *)version;
5001 STRLEN tlen = len;
5002 for (tlen=0; tlen < len; tlen++, testv++) {
5003 /* if one of the characters is non-text assume v-string */
5004 if (testv[0] < ' ') {
5005 SV * const nsv = sv_newmortal();
5006 const char *nver;
5007 const char *pos;
5008 int saw_decimal = 0;
5009 sv_setpvf(nsv,"v%vd",ver);
5010 pos = nver = savepv(SvPV_nolen(nsv));
5011
5012 /* scan the resulting formatted string */
5013 pos++; /* skip the leading 'v' */
5014 while ( *pos == '.' || isDIGIT(*pos) ) {
5015 if ( *pos == '.' )
5016 saw_decimal++ ;
5017 pos++;
5018 }
ac0e6a2f 5019
d54f8cf7
JP
5020 /* is definitely a v-string */
5021 if ( saw_decimal >= 2 ) {
5022 Safefree(version);
5023 version = nver;
5024 }
5025 break;
5026 }
ac0e6a2f
RGS
5027 }
5028 }
5029# endif
5030#endif
137d6fc0 5031 }
92dcf8ce 5032
cd57dc11 5033 s = scan_version(version, ver, qv);
808ee47e 5034 if ( *s != '\0' )
a2a5de95
NC
5035 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
5036 "Version string '%s' contains invalid data; "
5037 "ignoring: '%s'", version, s);
137d6fc0 5038 Safefree(version);
ad63d80f 5039 return ver;
b0f01acb
JP
5040}
5041
e0218a61
JP
5042/*
5043=for apidoc vverify
5044
5de8bffd
DG
5045Validates that the SV contains valid internal structure for a version object.
5046It may be passed either the version object (RV) or the hash itself (HV). If
5047the structure is valid, it returns the HV. If the structure is invalid,
5048it returns NULL.
e0218a61 5049
5de8bffd 5050 SV *hv = vverify(sv);
e0218a61
JP
5051
5052Note that it only confirms the bare minimum structure (so as not to get
5053confused by derived classes which may contain additional hash entries):
5054
5055=over 4
5056
5de8bffd 5057=item * The SV is an HV or a reference to an HV
e0218a61
JP
5058
5059=item * The hash contains a "version" key
5060
5de8bffd 5061=item * The "version" key has a reference to an AV as its value
e0218a61
JP
5062
5063=back
5064
5065=cut
5066*/
5067
5de8bffd 5068SV *
e0218a61
JP
5069Perl_vverify(pTHX_ SV *vs)
5070{
5071 SV *sv;
7918f24d
NC
5072
5073 PERL_ARGS_ASSERT_VVERIFY;
5074
e0218a61
JP
5075 if ( SvROK(vs) )
5076 vs = SvRV(vs);
5077
5078 /* see if the appropriate elements exist */
5079 if ( SvTYPE(vs) == SVt_PVHV
ef8f7699
NC
5080 && hv_exists(MUTABLE_HV(vs), "version", 7)
5081 && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
e0218a61 5082 && SvTYPE(sv) == SVt_PVAV )
5de8bffd 5083 return vs;
e0218a61 5084 else
5de8bffd 5085 return NULL;
e0218a61 5086}
b0f01acb
JP
5087
5088/*
5089=for apidoc vnumify
5090
ad63d80f
JP
5091Accepts a version object and returns the normalized floating
5092point representation. Call like:
b0f01acb 5093
ad63d80f 5094 sv = vnumify(rv);
b0f01acb 5095
ad63d80f
JP
5096NOTE: you can pass either the object directly or the SV
5097contained within the RV.
b0f01acb 5098
0f8e99e6
FC
5099The SV returned has a refcount of 1.
5100
b0f01acb
JP
5101=cut
5102*/
5103
5104SV *
ad63d80f 5105Perl_vnumify(pTHX_ SV *vs)
b0f01acb 5106{
ad63d80f 5107 I32 i, len, digit;
9137345a
JP
5108 int width;
5109 bool alpha = FALSE;
cb4a3036 5110 SV *sv;
9137345a 5111 AV *av;
7918f24d
NC
5112
5113 PERL_ARGS_ASSERT_VNUMIFY;
5114
5de8bffd
DG
5115 /* extract the HV from the object */
5116 vs = vverify(vs);
5117 if ( ! vs )
e0218a61
JP
5118 Perl_croak(aTHX_ "Invalid version object");
5119
9137345a 5120 /* see if various flags exist */
ef8f7699 5121 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
9137345a 5122 alpha = TRUE;
ef8f7699
NC
5123 if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
5124 width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
9137345a
JP
5125 else
5126 width = 3;
5127
5128
5129 /* attempt to retrieve the version array */
502c6561 5130 if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
cb4a3036 5131 return newSVpvs("0");
9137345a
JP
5132 }
5133
5134 len = av_len(av);
46314c13
JP
5135 if ( len == -1 )
5136 {
cb4a3036 5137 return newSVpvs("0");
46314c13 5138 }
9137345a
JP
5139
5140 digit = SvIV(*av_fetch(av, 0, 0));
cb4a3036 5141 sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
13f8f398 5142 for ( i = 1 ; i < len ; i++ )
b0f01acb 5143 {
9137345a
JP
5144 digit = SvIV(*av_fetch(av, i, 0));
5145 if ( width < 3 ) {
43eaf59d 5146 const int denom = (width == 2 ? 10 : 100);
53c1dcc0 5147 const div_t term = div((int)PERL_ABS(digit),denom);
261fcdab 5148 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
9137345a
JP
5149 }
5150 else {
261fcdab 5151 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
9137345a 5152 }
b0f01acb 5153 }
13f8f398
JP
5154
5155 if ( len > 0 )
5156 {
9137345a
JP
5157 digit = SvIV(*av_fetch(av, len, 0));
5158 if ( alpha && width == 3 ) /* alpha version */
396482e1 5159 sv_catpvs(sv,"_");
261fcdab 5160 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
13f8f398 5161 }
e0218a61 5162 else /* len == 0 */
13f8f398 5163 {
396482e1 5164 sv_catpvs(sv, "000");
13f8f398 5165 }
b0f01acb
JP
5166 return sv;
5167}
5168
5169/*
b9381830 5170=for apidoc vnormal
b0f01acb 5171
ad63d80f
JP
5172Accepts a version object and returns the normalized string
5173representation. Call like:
b0f01acb 5174
b9381830 5175 sv = vnormal(rv);
b0f01acb 5176
ad63d80f
JP
5177NOTE: you can pass either the object directly or the SV
5178contained within the RV.
b0f01acb 5179
0f8e99e6
FC
5180The SV returned has a refcount of 1.
5181
b0f01acb
JP
5182=cut
5183*/
5184
5185SV *
b9381830 5186Perl_vnormal(pTHX_ SV *vs)
b0f01acb 5187{
ad63d80f 5188 I32 i, len, digit;
9137345a 5189 bool alpha = FALSE;
cb4a3036 5190 SV *sv;
9137345a 5191 AV *av;
7918f24d
NC
5192
5193 PERL_ARGS_ASSERT_VNORMAL;
5194
5de8bffd
DG
5195 /* extract the HV from the object */
5196 vs = vverify(vs);
5197 if ( ! vs )
e0218a61
JP
5198 Perl_croak(aTHX_ "Invalid version object");
5199
ef8f7699 5200 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
9137345a 5201 alpha = TRUE;
502c6561 5202 av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)));
9137345a
JP
5203
5204 len = av_len(av);
e0218a61
JP
5205 if ( len == -1 )
5206 {
cb4a3036 5207 return newSVpvs("");
46314c13 5208 }
9137345a 5209 digit = SvIV(*av_fetch(av, 0, 0));
cb4a3036 5210 sv = Perl_newSVpvf(aTHX_ "v%"IVdf, (IV)digit);
cb5772bb 5211 for ( i = 1 ; i < len ; i++ ) {
9137345a 5212 digit = SvIV(*av_fetch(av, i, 0));
261fcdab 5213 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
9137345a
JP
5214 }
5215
e0218a61
JP
5216 if ( len > 0 )
5217 {
9137345a
JP
5218 /* handle last digit specially */
5219 digit = SvIV(*av_fetch(av, len, 0));
5220 if ( alpha )
261fcdab 5221 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
ad63d80f 5222 else
261fcdab 5223 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
b0f01acb 5224 }
9137345a 5225
137d6fc0
JP
5226 if ( len <= 2 ) { /* short version, must be at least three */
5227 for ( len = 2 - len; len != 0; len-- )
396482e1 5228 sv_catpvs(sv,".0");
137d6fc0 5229 }
b0f01acb 5230 return sv;
9137345a 5231}
b0f01acb 5232
ad63d80f 5233/*
b9381830
JP
5234=for apidoc vstringify
5235
5236In order to maintain maximum compatibility with earlier versions
5237of Perl, this function will return either the floating point
5238notation or the multiple dotted notation, depending on whether
0f8e99e6
FC
5239the original version contained 1 or more dots, respectively.
5240
5241The SV returned has a refcount of 1.
b9381830
JP
5242
5243=cut
5244*/
5245
5246SV *
5247Perl_vstringify(pTHX_ SV *vs)
5248{
7918f24d
NC
5249 PERL_ARGS_ASSERT_VSTRINGIFY;
5250
5de8bffd
DG
5251 /* extract the HV from the object */
5252 vs = vverify(vs);
5253 if ( ! vs )
e0218a61
JP
5254 Perl_croak(aTHX_ "Invalid version object");
5255
ef8f7699 5256 if (hv_exists(MUTABLE_HV(vs), "original", sizeof("original") - 1)) {
219bf418 5257 SV *pv;
ef8f7699 5258 pv = *hv_fetchs(MUTABLE_HV(vs), "original", FALSE);
219bf418
RGS
5259 if ( SvPOK(pv) )
5260 return newSVsv(pv);
5261 else
5262 return &PL_sv_undef;
5263 }
5264 else {
ef8f7699 5265 if ( hv_exists(MUTABLE_HV(vs), "qv", 2) )
219bf418
RGS
5266 return vnormal(vs);
5267 else
5268 return vnumify(vs);
5269 }
b9381830
JP
5270}
5271
5272/*
ad63d80f
JP
5273=for apidoc vcmp
5274
5275Version object aware cmp. Both operands must already have been
5276converted into version objects.
5277
5278=cut
5279*/
5280
5281int
9137345a 5282Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
ad63d80f
JP
5283{
5284 I32 i,l,m,r,retval;
9137345a
JP
5285 bool lalpha = FALSE;
5286 bool ralpha = FALSE;
5287 I32 left = 0;
5288 I32 right = 0;
5289 AV *lav, *rav;
7918f24d
NC
5290
5291 PERL_ARGS_ASSERT_VCMP;
5292
5de8bffd
DG
5293 /* extract the HVs from the objects */
5294 lhv = vverify(lhv);
5295 rhv = vverify(rhv);
5296 if ( ! ( lhv && rhv ) )
e0218a61
JP
5297 Perl_croak(aTHX_ "Invalid version object");
5298
9137345a 5299 /* get the left hand term */
502c6561 5300 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(lhv), "version", FALSE)));
ef8f7699 5301 if ( hv_exists(MUTABLE_HV(lhv), "alpha", 5 ) )
9137345a
JP
5302 lalpha = TRUE;
5303
5304 /* and the right hand term */
502c6561 5305 rav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rhv), "version", FALSE)));
ef8f7699 5306 if ( hv_exists(MUTABLE_HV(rhv), "alpha", 5 ) )
9137345a
JP
5307 ralpha = TRUE;
5308
5309 l = av_len(lav);
5310 r = av_len(rav);
ad63d80f
JP
5311 m = l < r ? l : r;
5312 retval = 0;
5313 i = 0;
5314 while ( i <= m && retval == 0 )
5315 {
9137345a
JP
5316 left = SvIV(*av_fetch(lav,i,0));
5317 right = SvIV(*av_fetch(rav,i,0));
5318 if ( left < right )
ad63d80f 5319 retval = -1;
9137345a 5320 if ( left > right )
ad63d80f
JP
5321 retval = +1;
5322 i++;
5323 }
5324
9137345a
JP
5325 /* tiebreaker for alpha with identical terms */
5326 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
5327 {
5328 if ( lalpha && !ralpha )
5329 {
5330 retval = -1;
5331 }
5332 else if ( ralpha && !lalpha)
5333 {
5334 retval = +1;
5335 }
5336 }
5337
137d6fc0 5338 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
129318bd 5339 {
137d6fc0 5340 if ( l < r )
129318bd 5341 {
137d6fc0
JP
5342 while ( i <= r && retval == 0 )
5343 {
9137345a 5344 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
137d6fc0
JP
5345 retval = -1; /* not a match after all */
5346 i++;
5347 }
5348 }
5349 else
5350 {
5351 while ( i <= l && retval == 0 )
5352 {
9137345a 5353 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
137d6fc0
JP
5354 retval = +1; /* not a match after all */
5355 i++;
5356 }
129318bd
JP
5357 }
5358 }
ad63d80f
JP
5359 return retval;
5360}
5361
c95c94b1 5362#if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
2bc69dc4
NIS
5363# define EMULATE_SOCKETPAIR_UDP
5364#endif
5365
5366#ifdef EMULATE_SOCKETPAIR_UDP
02fc2eee
NC
5367static int
5368S_socketpair_udp (int fd[2]) {
e10bb1e9 5369 dTHX;
02fc2eee
NC
5370 /* Fake a datagram socketpair using UDP to localhost. */
5371 int sockets[2] = {-1, -1};
5372 struct sockaddr_in addresses[2];
5373 int i;
3aed30dc 5374 Sock_size_t size = sizeof(struct sockaddr_in);
ae92b34e 5375 unsigned short port;
02fc2eee
NC
5376 int got;
5377
3aed30dc 5378 memset(&addresses, 0, sizeof(addresses));
02fc2eee
NC
5379 i = 1;
5380 do {
3aed30dc
HS
5381 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
5382 if (sockets[i] == -1)
5383 goto tidy_up_and_fail;
5384
5385 addresses[i].sin_family = AF_INET;
5386 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5387 addresses[i].sin_port = 0; /* kernel choses port. */
5388 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
5389 sizeof(struct sockaddr_in)) == -1)
5390 goto tidy_up_and_fail;
02fc2eee
NC
5391 } while (i--);
5392
5393 /* Now have 2 UDP sockets. Find out which port each is connected to, and
5394 for each connect the other socket to it. */
5395 i = 1;
5396 do {
3aed30dc
HS
5397 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
5398 &size) == -1)
5399 goto tidy_up_and_fail;
5400 if (size != sizeof(struct sockaddr_in))
5401 goto abort_tidy_up_and_fail;
5402 /* !1 is 0, !0 is 1 */
5403 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
5404 sizeof(struct sockaddr_in)) == -1)
5405 goto tidy_up_and_fail;
02fc2eee
NC
5406 } while (i--);
5407
5408 /* Now we have 2 sockets connected to each other. I don't trust some other
5409 process not to have already sent a packet to us (by random) so send
5410 a packet from each to the other. */
5411 i = 1;
5412 do {
3aed30dc
HS
5413 /* I'm going to send my own port number. As a short.
5414 (Who knows if someone somewhere has sin_port as a bitfield and needs
5415 this routine. (I'm assuming crays have socketpair)) */
5416 port = addresses[i].sin_port;
5417 got = PerlLIO_write(sockets[i], &port, sizeof(port));
5418 if (got != sizeof(port)) {
5419 if (got == -1)
5420 goto tidy_up_and_fail;
5421 goto abort_tidy_up_and_fail;
5422 }
02fc2eee
NC
5423 } while (i--);
5424
5425 /* Packets sent. I don't trust them to have arrived though.
5426 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
5427 connect to localhost will use a second kernel thread. In 2.6 the
5428 first thread running the connect() returns before the second completes,
5429 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
5430 returns 0. Poor programs have tripped up. One poor program's authors'
5431 had a 50-1 reverse stock split. Not sure how connected these were.)
5432 So I don't trust someone not to have an unpredictable UDP stack.
5433 */
5434
5435 {
3aed30dc
HS
5436 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
5437 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
5438 fd_set rset;
5439
5440 FD_ZERO(&rset);
ea407a0c
NC
5441 FD_SET((unsigned int)sockets[0], &rset);
5442 FD_SET((unsigned int)sockets[1], &rset);
3aed30dc
HS
5443
5444 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
5445 if (got != 2 || !FD_ISSET(sockets[0], &rset)
5446 || !FD_ISSET(sockets[1], &rset)) {
5447 /* I hope this is portable and appropriate. */
5448 if (got == -1)
5449 goto tidy_up_and_fail;
5450 goto abort_tidy_up_and_fail;
5451 }
02fc2eee 5452 }
f4758303 5453
02fc2eee
NC
5454 /* And the paranoia department even now doesn't trust it to have arrive
5455 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
5456 {
3aed30dc
HS
5457 struct sockaddr_in readfrom;
5458 unsigned short buffer[2];
02fc2eee 5459
3aed30dc
HS
5460 i = 1;
5461 do {
02fc2eee 5462#ifdef MSG_DONTWAIT
3aed30dc
HS
5463 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5464 sizeof(buffer), MSG_DONTWAIT,
5465 (struct sockaddr *) &readfrom, &size);
02fc2eee 5466#else
3aed30dc
HS
5467 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5468 sizeof(buffer), 0,
5469 (struct sockaddr *) &readfrom, &size);
e10bb1e9 5470#endif
02fc2eee 5471
3aed30dc
HS
5472 if (got == -1)
5473 goto tidy_up_and_fail;
5474 if (got != sizeof(port)
5475 || size != sizeof(struct sockaddr_in)
5476 /* Check other socket sent us its port. */
5477 || buffer[0] != (unsigned short) addresses[!i].sin_port
5478 /* Check kernel says we got the datagram from that socket */
5479 || readfrom.sin_family != addresses[!i].sin_family
5480 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
5481 || readfrom.sin_port != addresses[!i].sin_port)
5482 goto abort_tidy_up_and_fail;
5483 } while (i--);
02fc2eee
NC
5484 }
5485 /* My caller (my_socketpair) has validated that this is non-NULL */
5486 fd[0] = sockets[0];
5487 fd[1] = sockets[1];
5488 /* I hereby declare this connection open. May God bless all who cross
5489 her. */
5490 return 0;
5491
5492 abort_tidy_up_and_fail:
5493 errno = ECONNABORTED;
5494 tidy_up_and_fail:
5495 {
4ee39169 5496 dSAVE_ERRNO;
3aed30dc
HS
5497 if (sockets[0] != -1)
5498 PerlLIO_close(sockets[0]);
5499 if (sockets[1] != -1)
5500 PerlLIO_close(sockets[1]);
4ee39169 5501 RESTORE_ERRNO;
3aed30dc 5502 return -1;
02fc2eee
NC
5503 }
5504}
85ca448a 5505#endif /* EMULATE_SOCKETPAIR_UDP */
02fc2eee 5506
b5ac89c3 5507#if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
02fc2eee
NC
5508int
5509Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5510 /* Stevens says that family must be AF_LOCAL, protocol 0.
2948e0bd 5511 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
e10bb1e9 5512 dTHX;
02fc2eee
NC
5513 int listener = -1;
5514 int connector = -1;
5515 int acceptor = -1;
5516 struct sockaddr_in listen_addr;
5517 struct sockaddr_in connect_addr;
5518 Sock_size_t size;
5519
50458334
JH
5520 if (protocol
5521#ifdef AF_UNIX
5522 || family != AF_UNIX
5523#endif
3aed30dc
HS
5524 ) {
5525 errno = EAFNOSUPPORT;
5526 return -1;
02fc2eee 5527 }
2948e0bd 5528 if (!fd) {
3aed30dc
HS
5529 errno = EINVAL;
5530 return -1;
2948e0bd 5531 }
02fc2eee 5532
2bc69dc4 5533#ifdef EMULATE_SOCKETPAIR_UDP
02fc2eee 5534 if (type == SOCK_DGRAM)
3aed30dc 5535 return S_socketpair_udp(fd);
2bc69dc4 5536#endif
02fc2eee 5537
3aed30dc 5538 listener = PerlSock_socket(AF_INET, type, 0);
02fc2eee 5539 if (listener == -1)
3aed30dc
HS
5540 return -1;
5541 memset(&listen_addr, 0, sizeof(listen_addr));
02fc2eee 5542 listen_addr.sin_family = AF_INET;
3aed30dc 5543 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
02fc2eee 5544 listen_addr.sin_port = 0; /* kernel choses port. */
3aed30dc
HS
5545 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5546 sizeof(listen_addr)) == -1)
5547 goto tidy_up_and_fail;
e10bb1e9 5548 if (PerlSock_listen(listener, 1) == -1)
3aed30dc 5549 goto tidy_up_and_fail;
02fc2eee 5550
3aed30dc 5551 connector = PerlSock_socket(AF_INET, type, 0);
02fc2eee 5552 if (connector == -1)
3aed30dc 5553 goto tidy_up_and_fail;
02fc2eee 5554 /* We want to find out the port number to connect to. */
3aed30dc
HS
5555 size = sizeof(connect_addr);
5556 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5557 &size) == -1)
5558 goto tidy_up_and_fail;
5559 if (size != sizeof(connect_addr))
5560 goto abort_tidy_up_and_fail;
e10bb1e9 5561 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
3aed30dc
HS
5562 sizeof(connect_addr)) == -1)
5563 goto tidy_up_and_fail;
02fc2eee 5564
3aed30dc
HS
5565 size = sizeof(listen_addr);
5566 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5567 &size);
02fc2eee 5568 if (acceptor == -1)
3aed30dc
HS
5569 goto tidy_up_and_fail;
5570 if (size != sizeof(listen_addr))
5571 goto abort_tidy_up_and_fail;
5572 PerlLIO_close(listener);
02fc2eee
NC
5573 /* Now check we are talking to ourself by matching port and host on the
5574 two sockets. */
3aed30dc
HS
5575 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5576 &size) == -1)
5577 goto tidy_up_and_fail;
5578 if (size != sizeof(connect_addr)
5579 || listen_addr.sin_family != connect_addr.sin_family
5580 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5581 || listen_addr.sin_port != connect_addr.sin_port) {
5582 goto abort_tidy_up_and_fail;
02fc2eee
NC
5583 }
5584 fd[0] = connector;
5585 fd[1] = acceptor;
5586 return 0;
5587
5588 abort_tidy_up_and_fail:
27da23d5
JH
5589#ifdef ECONNABORTED
5590 errno = ECONNABORTED; /* This would be the standard thing to do. */
5591#else
5592# ifdef ECONNREFUSED
5593 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5594# else
5595 errno = ETIMEDOUT; /* Desperation time. */
5596# endif
5597#endif
02fc2eee
NC
5598 tidy_up_and_fail:
5599 {
4ee39169 5600 dSAVE_ERRNO;
3aed30dc
HS
5601 if (listener != -1)
5602 PerlLIO_close(listener);
5603 if (connector != -1)
5604 PerlLIO_close(connector);
5605 if (acceptor != -1)
5606 PerlLIO_close(acceptor);
4ee39169 5607 RESTORE_ERRNO;
3aed30dc 5608 return -1;
02fc2eee
NC
5609 }
5610}
85ca448a 5611#else
48ea76d1 5612/* In any case have a stub so that there's code corresponding
d500e60d 5613 * to the my_socketpair in embed.fnc. */
48ea76d1
JH
5614int
5615Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
daf16542 5616#ifdef HAS_SOCKETPAIR
48ea76d1 5617 return socketpair(family, type, protocol, fd);
daf16542
JH
5618#else
5619 return -1;
5620#endif
48ea76d1
JH
5621}
5622#endif
5623
68795e93
NIS
5624/*
5625
5626=for apidoc sv_nosharing
5627
5628Dummy routine which "shares" an SV when there is no sharing module present.
d5b2b27b
NC
5629Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5630Exists to avoid test for a NULL function pointer and because it could
5631potentially warn under some level of strict-ness.
68795e93
NIS
5632
5633=cut
5634*/
5635
5636void
5637Perl_sv_nosharing(pTHX_ SV *sv)
5638{
96a5add6 5639 PERL_UNUSED_CONTEXT;
53c1dcc0 5640 PERL_UNUSED_ARG(sv);
68795e93
NIS
5641}
5642
eba16661
JH
5643/*
5644
5645=for apidoc sv_destroyable
5646
5647Dummy routine which reports that object can be destroyed when there is no
5648sharing module present. It ignores its single SV argument, and returns
5649'true'. Exists to avoid test for a NULL function pointer and because it
5650could potentially warn under some level of strict-ness.
5651
5652=cut
5653*/
5654
5655bool
5656Perl_sv_destroyable(pTHX_ SV *sv)
5657{
5658 PERL_UNUSED_CONTEXT;
5659 PERL_UNUSED_ARG(sv);
5660 return TRUE;
5661}
5662
a05d7ebb 5663U32
e1ec3a88 5664Perl_parse_unicode_opts(pTHX_ const char **popt)
a05d7ebb 5665{
e1ec3a88 5666 const char *p = *popt;
a05d7ebb
JH
5667 U32 opt = 0;
5668
7918f24d
NC
5669 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5670
a05d7ebb
JH
5671 if (*p) {
5672 if (isDIGIT(*p)) {
5673 opt = (U32) atoi(p);
35da51f7
AL
5674 while (isDIGIT(*p))
5675 p++;
d4a59e54
FC
5676 if (*p && *p != '\n' && *p != '\r') {
5677 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5678 else
a05d7ebb 5679 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
d4a59e54 5680 }
a05d7ebb
JH
5681 }
5682 else {
5683 for (; *p; p++) {
5684 switch (*p) {
5685 case PERL_UNICODE_STDIN:
5686 opt |= PERL_UNICODE_STDIN_FLAG; break;
5687 case PERL_UNICODE_STDOUT:
5688 opt |= PERL_UNICODE_STDOUT_FLAG; break;
5689 case PERL_UNICODE_STDERR:
5690 opt |= PERL_UNICODE_STDERR_FLAG; break;
5691 case PERL_UNICODE_STD:
5692 opt |= PERL_UNICODE_STD_FLAG; break;
5693 case PERL_UNICODE_IN:
5694 opt |= PERL_UNICODE_IN_FLAG; break;
5695 case PERL_UNICODE_OUT:
5696 opt |= PERL_UNICODE_OUT_FLAG; break;
5697 case PERL_UNICODE_INOUT:
5698 opt |= PERL_UNICODE_INOUT_FLAG; break;
5699 case PERL_UNICODE_LOCALE:
5700 opt |= PERL_UNICODE_LOCALE_FLAG; break;
5701 case PERL_UNICODE_ARGV:
5702 opt |= PERL_UNICODE_ARGV_FLAG; break;
5a22a2bb
NC
5703 case PERL_UNICODE_UTF8CACHEASSERT:
5704 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
a05d7ebb 5705 default:
d4a59e54
FC
5706 if (*p != '\n' && *p != '\r') {
5707 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5708 else
7c91f477
JH
5709 Perl_croak(aTHX_
5710 "Unknown Unicode option letter '%c'", *p);
d4a59e54 5711 }
a05d7ebb
JH
5712 }
5713 }
5714 }
5715 }
5716 else
5717 opt = PERL_UNICODE_DEFAULT_FLAGS;
5718
d4a59e54
FC
5719 the_end_of_the_opts_parser:
5720
a05d7ebb 5721 if (opt & ~PERL_UNICODE_ALL_FLAGS)
06e66572 5722 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
a05d7ebb
JH
5723 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5724
5725 *popt = p;
5726
5727 return opt;
5728}
5729
25bbd826
CB
5730#ifdef VMS
5731# include <starlet.h>
5732#endif
5733
132efe8b
JH
5734U32
5735Perl_seed(pTHX)
5736{
97aff369 5737 dVAR;
132efe8b
JH
5738 /*
5739 * This is really just a quick hack which grabs various garbage
5740 * values. It really should be a real hash algorithm which
5741 * spreads the effect of every input bit onto every output bit,
5742 * if someone who knows about such things would bother to write it.
5743 * Might be a good idea to add that function to CORE as well.
5744 * No numbers below come from careful analysis or anything here,
5745 * except they are primes and SEED_C1 > 1E6 to get a full-width
5746 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5747 * probably be bigger too.
5748 */
5749#if RANDBITS > 16
5750# define SEED_C1 1000003
5751#define SEED_C4 73819
5752#else
5753# define SEED_C1 25747
5754#define SEED_C4 20639
5755#endif
5756#define SEED_C2 3
5757#define SEED_C3 269
5758#define SEED_C5 26107
5759
5760#ifndef PERL_NO_DEV_RANDOM
5761 int fd;
5762#endif
5763 U32 u;
5764#ifdef VMS
132efe8b
JH
5765 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5766 * in 100-ns units, typically incremented ever 10 ms. */
5767 unsigned int when[2];
5768#else
5769# ifdef HAS_GETTIMEOFDAY
5770 struct timeval when;
5771# else
5772 Time_t when;
5773# endif
5774#endif
5775
5776/* This test is an escape hatch, this symbol isn't set by Configure. */
5777#ifndef PERL_NO_DEV_RANDOM
5778#ifndef PERL_RANDOM_DEVICE
5779 /* /dev/random isn't used by default because reads from it will block
5780 * if there isn't enough entropy available. You can compile with
5781 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5782 * is enough real entropy to fill the seed. */
5783# define PERL_RANDOM_DEVICE "/dev/urandom"
5784#endif
5785 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5786 if (fd != -1) {
27da23d5 5787 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
132efe8b
JH
5788 u = 0;
5789 PerlLIO_close(fd);
5790 if (u)
5791 return u;
5792 }
5793#endif
5794
5795#ifdef VMS
5796 _ckvmssts(sys$gettim(when));
5797 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5798#else
5799# ifdef HAS_GETTIMEOFDAY
5800 PerlProc_gettimeofday(&when,NULL);
5801 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5802# else
5803 (void)time(&when);
5804 u = (U32)SEED_C1 * when;
5805# endif
5806#endif
5807 u += SEED_C3 * (U32)PerlProc_getpid();
5808 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5809#ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5810 u += SEED_C5 * (U32)PTR2UV(&when);
5811#endif
5812 return u;
5813}
5814
bed60192 5815UV
a783c5f4 5816Perl_get_hash_seed(pTHX)
bed60192 5817{
97aff369 5818 dVAR;
e1ec3a88 5819 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
bed60192
JH
5820 UV myseed = 0;
5821
5822 if (s)
35da51f7
AL
5823 while (isSPACE(*s))
5824 s++;
bed60192
JH
5825 if (s && isDIGIT(*s))
5826 myseed = (UV)Atoul(s);
5827 else
5828#ifdef USE_HASH_SEED_EXPLICIT
5829 if (s)
5830#endif
5831 {
5832 /* Compute a random seed */
5833 (void)seedDrand01((Rand_seed_t)seed());
bed60192
JH
5834 myseed = (UV)(Drand01() * (NV)UV_MAX);
5835#if RANDBITS < (UVSIZE * 8)
5836 /* Since there are not enough randbits to to reach all
5837 * the bits of a UV, the low bits might need extra
5838 * help. Sum in another random number that will
5839 * fill in the low bits. */
5840 myseed +=
fa58a56f 5841 (UV)(Drand01() * (NV)((((UV)1) << ((UVSIZE * 8 - RANDBITS))) - 1));
bed60192 5842#endif /* RANDBITS < (UVSIZE * 8) */
6cfd5ea7
JH
5843 if (myseed == 0) { /* Superparanoia. */
5844 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5845 if (myseed == 0)
5846 Perl_croak(aTHX_ "Your random numbers are not that random");
5847 }
bed60192 5848 }
008fb0c0 5849 PL_rehash_seed_set = TRUE;
bed60192
JH
5850
5851 return myseed;
5852}
27da23d5 5853
ed221c57
AL
5854#ifdef USE_ITHREADS
5855bool
5856Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5857{
aa33328e
BF
5858 const char * stashpv = CopSTASHPV(c);
5859 const char * name = HvNAME_get(hv);
6379d4a9
FC
5860 const bool utf8 = CopSTASH_len(c) < 0;
5861 const I32 len = utf8 ? -CopSTASH_len(c) : CopSTASH_len(c);
96a5add6 5862 PERL_UNUSED_CONTEXT;
7918f24d 5863 PERL_ARGS_ASSERT_STASHPV_HVNAME_MATCH;
ed221c57 5864
6852b003
FC
5865 if (!stashpv || !name)
5866 return stashpv == name;
707475cd 5867 if ( !HvNAMEUTF8(hv) != !utf8 ) {
6379d4a9 5868 if (utf8) {
aa33328e 5869 return (bytes_cmp_utf8(
6379d4a9 5870 (const U8*)stashpv, len,
aa33328e
BF
5871 (const U8*)name, HEK_LEN(HvNAME_HEK(hv))) == 0);
5872 } else {
5873 return (bytes_cmp_utf8(
5874 (const U8*)name, HEK_LEN(HvNAME_HEK(hv)),
6379d4a9 5875 (const U8*)stashpv, len) == 0);
aa33328e
BF
5876 }
5877 }
5878 else
5879 return (stashpv == name
6379d4a9 5880 || (HEK_LEN(HvNAME_HEK(hv)) == len
f374360c 5881 && memEQ(stashpv, name, len)));
68403e65 5882 /*NOTREACHED*/
ed221c57
AL
5883 return FALSE;
5884}
5885#endif
5886
5887
27da23d5
JH
5888#ifdef PERL_GLOBAL_STRUCT
5889
bae1192d
JH
5890#define PERL_GLOBAL_STRUCT_INIT
5891#include "opcode.h" /* the ppaddr and check */
5892
27da23d5
JH
5893struct perl_vars *
5894Perl_init_global_struct(pTHX)
5895{
5896 struct perl_vars *plvarsp = NULL;
bae1192d 5897# ifdef PERL_GLOBAL_STRUCT
7452cf6a
AL
5898 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5899 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
27da23d5
JH
5900# ifdef PERL_GLOBAL_STRUCT_PRIVATE
5901 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5902 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5903 if (!plvarsp)
5904 exit(1);
5905# else
5906 plvarsp = PL_VarsPtr;
5907# endif /* PERL_GLOBAL_STRUCT_PRIVATE */
aadb217d
JH
5908# undef PERLVAR
5909# undef PERLVARA
5910# undef PERLVARI
5911# undef PERLVARIC
115ff745
NC
5912# define PERLVAR(prefix,var,type) /**/
5913# define PERLVARA(prefix,var,n,type) /**/
5914# define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
5915# define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
27da23d5
JH
5916# include "perlvars.h"
5917# undef PERLVAR
5918# undef PERLVARA
5919# undef PERLVARI
5920# undef PERLVARIC
27da23d5 5921# ifdef PERL_GLOBAL_STRUCT
bae1192d
JH
5922 plvarsp->Gppaddr =
5923 (Perl_ppaddr_t*)
5924 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
27da23d5
JH
5925 if (!plvarsp->Gppaddr)
5926 exit(1);
bae1192d
JH
5927 plvarsp->Gcheck =
5928 (Perl_check_t*)
5929 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
27da23d5
JH
5930 if (!plvarsp->Gcheck)
5931 exit(1);
5932 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5933 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5934# endif
5935# ifdef PERL_SET_VARS
5936 PERL_SET_VARS(plvarsp);
5937# endif
bae1192d
JH
5938# undef PERL_GLOBAL_STRUCT_INIT
5939# endif
27da23d5
JH
5940 return plvarsp;
5941}
5942
5943#endif /* PERL_GLOBAL_STRUCT */
5944
5945#ifdef PERL_GLOBAL_STRUCT
5946
5947void
5948Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5949{
7918f24d 5950 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
bae1192d 5951# ifdef PERL_GLOBAL_STRUCT
27da23d5
JH
5952# ifdef PERL_UNSET_VARS
5953 PERL_UNSET_VARS(plvarsp);
5954# endif
5955 free(plvarsp->Gppaddr);
5956 free(plvarsp->Gcheck);
bae1192d 5957# ifdef PERL_GLOBAL_STRUCT_PRIVATE
27da23d5 5958 free(plvarsp);
bae1192d
JH
5959# endif
5960# endif
27da23d5
JH
5961}
5962
5963#endif /* PERL_GLOBAL_STRUCT */
5964
fe4f188c
JH
5965#ifdef PERL_MEM_LOG
5966
1cd8acb5 5967/* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
73d1d973
JC
5968 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
5969 * given, and you supply your own implementation.
65ceff02 5970 *
2e5b5004 5971 * The default implementation reads a single env var, PERL_MEM_LOG,
1cd8acb5
JC
5972 * expecting one or more of the following:
5973 *
5974 * \d+ - fd fd to write to : must be 1st (atoi)
2e5b5004 5975 * 'm' - memlog was PERL_MEM_LOG=1
1cd8acb5
JC
5976 * 's' - svlog was PERL_SV_LOG=1
5977 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
0b0ab801 5978 *
1cd8acb5
JC
5979 * This makes the logger controllable enough that it can reasonably be
5980 * added to the system perl.
65ceff02
JH
5981 */
5982
1cd8acb5 5983/* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
65ceff02
JH
5984 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5985 */
e352bcff
JH
5986#define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5987
1cd8acb5
JC
5988/* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
5989 * writes to. In the default logger, this is settable at runtime.
65ceff02
JH
5990 */
5991#ifndef PERL_MEM_LOG_FD
5992# define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5993#endif
5994
73d1d973 5995#ifndef PERL_MEM_LOG_NOIMPL
d7a2c63c
MHM
5996
5997# ifdef DEBUG_LEAKING_SCALARS
5998# define SV_LOG_SERIAL_FMT " [%lu]"
5999# define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
6000# else
6001# define SV_LOG_SERIAL_FMT
6002# define _SV_LOG_SERIAL_ARG(sv)
6003# endif
6004
0b0ab801 6005static void
73d1d973
JC
6006S_mem_log_common(enum mem_log_type mlt, const UV n,
6007 const UV typesize, const char *type_name, const SV *sv,
6008 Malloc_t oldalloc, Malloc_t newalloc,
6009 const char *filename, const int linenumber,
6010 const char *funcname)
0b0ab801 6011{
1cd8acb5 6012 const char *pmlenv;
4ca7bcef 6013
1cd8acb5 6014 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
4ca7bcef 6015
1cd8acb5
JC
6016 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
6017 if (!pmlenv)
6018 return;
6019 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
65ceff02
JH
6020 {
6021 /* We can't use SVs or PerlIO for obvious reasons,
6022 * so we'll use stdio and low-level IO instead. */
6023 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
1cd8acb5 6024
5b692037 6025# ifdef HAS_GETTIMEOFDAY
0b0ab801
MHM
6026# define MEM_LOG_TIME_FMT "%10d.%06d: "
6027# define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
6028 struct timeval tv;
65ceff02 6029 gettimeofday(&tv, 0);
0b0ab801
MHM
6030# else
6031# define MEM_LOG_TIME_FMT "%10d: "
6032# define MEM_LOG_TIME_ARG (int)when
6033 Time_t when;
6034 (void)time(&when);
5b692037
JH
6035# endif
6036 /* If there are other OS specific ways of hires time than
40d04ec4 6037 * gettimeofday() (see ext/Time-HiRes), the easiest way is
5b692037
JH
6038 * probably that they would be used to fill in the struct
6039 * timeval. */
65ceff02 6040 {
0b0ab801 6041 STRLEN len;
1cd8acb5
JC
6042 int fd = atoi(pmlenv);
6043 if (!fd)
6044 fd = PERL_MEM_LOG_FD;
0b0ab801 6045
1cd8acb5 6046 if (strchr(pmlenv, 't')) {
0b0ab801
MHM
6047 len = my_snprintf(buf, sizeof(buf),
6048 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
6049 PerlLIO_write(fd, buf, len);
6050 }
0b0ab801
MHM
6051 switch (mlt) {
6052 case MLT_ALLOC:
6053 len = my_snprintf(buf, sizeof(buf),
6054 "alloc: %s:%d:%s: %"IVdf" %"UVuf
6055 " %s = %"IVdf": %"UVxf"\n",
6056 filename, linenumber, funcname, n, typesize,
bef8a128 6057 type_name, n * typesize, PTR2UV(newalloc));
0b0ab801
MHM
6058 break;
6059 case MLT_REALLOC:
6060 len = my_snprintf(buf, sizeof(buf),
6061 "realloc: %s:%d:%s: %"IVdf" %"UVuf
6062 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
6063 filename, linenumber, funcname, n, typesize,
bef8a128 6064 type_name, n * typesize, PTR2UV(oldalloc),
0b0ab801
MHM
6065 PTR2UV(newalloc));
6066 break;
6067 case MLT_FREE:
6068 len = my_snprintf(buf, sizeof(buf),
6069 "free: %s:%d:%s: %"UVxf"\n",
6070 filename, linenumber, funcname,
6071 PTR2UV(oldalloc));
6072 break;
d7a2c63c
MHM
6073 case MLT_NEW_SV:
6074 case MLT_DEL_SV:
6075 len = my_snprintf(buf, sizeof(buf),
6076 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
6077 mlt == MLT_NEW_SV ? "new" : "del",
6078 filename, linenumber, funcname,
6079 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
6080 break;
73d1d973
JC
6081 default:
6082 len = 0;
0b0ab801
MHM
6083 }
6084 PerlLIO_write(fd, buf, len);
65ceff02
JH
6085 }
6086 }
0b0ab801 6087}
73d1d973
JC
6088#endif /* !PERL_MEM_LOG_NOIMPL */
6089
6090#ifndef PERL_MEM_LOG_NOIMPL
6091# define \
6092 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
6093 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
6094#else
6095/* this is suboptimal, but bug compatible. User is providing their
486ec47a 6096 own implementation, but is getting these functions anyway, and they
73d1d973
JC
6097 do nothing. But _NOIMPL users should be able to cope or fix */
6098# define \
6099 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
6100 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
0b0ab801
MHM
6101#endif
6102
6103Malloc_t
73d1d973
JC
6104Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
6105 Malloc_t newalloc,
6106 const char *filename, const int linenumber,
6107 const char *funcname)
6108{
6109 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
6110 NULL, NULL, newalloc,
6111 filename, linenumber, funcname);
fe4f188c
JH
6112 return newalloc;
6113}
6114
6115Malloc_t
73d1d973
JC
6116Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
6117 Malloc_t oldalloc, Malloc_t newalloc,
6118 const char *filename, const int linenumber,
6119 const char *funcname)
6120{
6121 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
6122 NULL, oldalloc, newalloc,
6123 filename, linenumber, funcname);
fe4f188c
JH
6124 return newalloc;
6125}
6126
6127Malloc_t
73d1d973
JC
6128Perl_mem_log_free(Malloc_t oldalloc,
6129 const char *filename, const int linenumber,
6130 const char *funcname)
fe4f188c 6131{
73d1d973
JC
6132 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
6133 filename, linenumber, funcname);
fe4f188c
JH
6134 return oldalloc;
6135}
6136
d7a2c63c 6137void
73d1d973
JC
6138Perl_mem_log_new_sv(const SV *sv,
6139 const char *filename, const int linenumber,
6140 const char *funcname)
d7a2c63c 6141{
73d1d973
JC
6142 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
6143 filename, linenumber, funcname);
d7a2c63c
MHM
6144}
6145
6146void
73d1d973
JC
6147Perl_mem_log_del_sv(const SV *sv,
6148 const char *filename, const int linenumber,
6149 const char *funcname)
d7a2c63c 6150{
73d1d973
JC
6151 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
6152 filename, linenumber, funcname);
d7a2c63c
MHM
6153}
6154
fe4f188c
JH
6155#endif /* PERL_MEM_LOG */
6156
66610fdd 6157/*
ce582cee
NC
6158=for apidoc my_sprintf
6159
6160The C library C<sprintf>, wrapped if necessary, to ensure that it will return
6161the length of the string written to the buffer. Only rare pre-ANSI systems
6162need the wrapper function - usually this is a direct call to C<sprintf>.
6163
6164=cut
6165*/
6166#ifndef SPRINTF_RETURNS_STRLEN
6167int
6168Perl_my_sprintf(char *buffer, const char* pat, ...)
6169{
6170 va_list args;
7918f24d 6171 PERL_ARGS_ASSERT_MY_SPRINTF;
ce582cee
NC
6172 va_start(args, pat);
6173 vsprintf(buffer, pat, args);
6174 va_end(args);
6175 return strlen(buffer);
6176}
6177#endif
6178
d9fad198
JH
6179/*
6180=for apidoc my_snprintf
6181
6182The C library C<snprintf> functionality, if available and
5b692037 6183standards-compliant (uses C<vsnprintf>, actually). However, if the
d9fad198 6184C<vsnprintf> is not available, will unfortunately use the unsafe
5b692037
JH
6185C<vsprintf> which can overrun the buffer (there is an overrun check,
6186but that may be too late). Consider using C<sv_vcatpvf> instead, or
6187getting C<vsnprintf>.
d9fad198
JH
6188
6189=cut
6190*/
6191int
6192Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
d9fad198
JH
6193{
6194 dTHX;
6195 int retval;
6196 va_list ap;
7918f24d 6197 PERL_ARGS_ASSERT_MY_SNPRINTF;
d9fad198 6198 va_start(ap, format);
5b692037 6199#ifdef HAS_VSNPRINTF
d9fad198
JH
6200 retval = vsnprintf(buffer, len, format, ap);
6201#else
6202 retval = vsprintf(buffer, format, ap);
6203#endif
6204 va_end(ap);
7dac5c64
RB
6205 /* vsprintf() shows failure with < 0 */
6206 if (retval < 0
6207#ifdef HAS_VSNPRINTF
6208 /* vsnprintf() shows failure with >= len */
6209 ||
6210 (len > 0 && (Size_t)retval >= len)
6211#endif
6212 )
5b692037 6213 Perl_croak(aTHX_ "panic: my_snprintf buffer overflow");
d9fad198
JH
6214 return retval;
6215}
6216
6217/*
6218=for apidoc my_vsnprintf
6219
5b692037
JH
6220The C library C<vsnprintf> if available and standards-compliant.
6221However, if if the C<vsnprintf> is not available, will unfortunately
6222use the unsafe C<vsprintf> which can overrun the buffer (there is an
6223overrun check, but that may be too late). Consider using
6224C<sv_vcatpvf> instead, or getting C<vsnprintf>.
d9fad198
JH
6225
6226=cut
6227*/
6228int
6229Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
d9fad198
JH
6230{
6231 dTHX;
6232 int retval;
d9fad198
JH
6233#ifdef NEED_VA_COPY
6234 va_list apc;
7918f24d
NC
6235
6236 PERL_ARGS_ASSERT_MY_VSNPRINTF;
6237
239fec62 6238 Perl_va_copy(ap, apc);
5b692037 6239# ifdef HAS_VSNPRINTF
d9fad198
JH
6240 retval = vsnprintf(buffer, len, format, apc);
6241# else
6242 retval = vsprintf(buffer, format, apc);
6243# endif
6244#else
5b692037 6245# ifdef HAS_VSNPRINTF
d9fad198
JH
6246 retval = vsnprintf(buffer, len, format, ap);
6247# else
6248 retval = vsprintf(buffer, format, ap);
6249# endif
5b692037 6250#endif /* #ifdef NEED_VA_COPY */
7dac5c64
RB
6251 /* vsprintf() shows failure with < 0 */
6252 if (retval < 0
6253#ifdef HAS_VSNPRINTF
6254 /* vsnprintf() shows failure with >= len */
6255 ||
6256 (len > 0 && (Size_t)retval >= len)
6257#endif
6258 )
5b692037 6259 Perl_croak(aTHX_ "panic: my_vsnprintf buffer overflow");
d9fad198
JH
6260 return retval;
6261}
6262
b0269e46
AB
6263void
6264Perl_my_clearenv(pTHX)
6265{
6266 dVAR;
6267#if ! defined(PERL_MICRO)
6268# if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
6269 PerlEnv_clearenv();
6270# else /* ! (PERL_IMPLICIT_SYS || WIN32) */
6271# if defined(USE_ENVIRON_ARRAY)
6272# if defined(USE_ITHREADS)
6273 /* only the parent thread can clobber the process environment */
6274 if (PL_curinterp == aTHX)
6275# endif /* USE_ITHREADS */
6276 {
6277# if ! defined(PERL_USE_SAFE_PUTENV)
6278 if ( !PL_use_safe_putenv) {
6279 I32 i;
6280 if (environ == PL_origenviron)
6281 environ = (char**)safesysmalloc(sizeof(char*));
6282 else
6283 for (i = 0; environ[i]; i++)
6284 (void)safesysfree(environ[i]);
6285 }
6286 environ[0] = NULL;
6287# else /* PERL_USE_SAFE_PUTENV */
6288# if defined(HAS_CLEARENV)
6289 (void)clearenv();
6290# elif defined(HAS_UNSETENV)
6291 int bsiz = 80; /* Most envvar names will be shorter than this. */
d1307786
JH
6292 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
6293 char *buf = (char*)safesysmalloc(bufsiz);
b0269e46
AB
6294 while (*environ != NULL) {
6295 char *e = strchr(*environ, '=');
b57a0404 6296 int l = e ? e - *environ : (int)strlen(*environ);
b0269e46
AB
6297 if (bsiz < l + 1) {
6298 (void)safesysfree(buf);
1bdfa2de 6299 bsiz = l + 1; /* + 1 for the \0. */
d1307786 6300 buf = (char*)safesysmalloc(bufsiz);
b0269e46 6301 }
82d8bb49
NC
6302 memcpy(buf, *environ, l);
6303 buf[l] = '\0';
b0269e46
AB
6304 (void)unsetenv(buf);
6305 }
6306 (void)safesysfree(buf);
6307# else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
6308 /* Just null environ and accept the leakage. */
6309 *environ = NULL;
6310# endif /* HAS_CLEARENV || HAS_UNSETENV */
6311# endif /* ! PERL_USE_SAFE_PUTENV */
6312 }
6313# endif /* USE_ENVIRON_ARRAY */
6314# endif /* PERL_IMPLICIT_SYS || WIN32 */
6315#endif /* PERL_MICRO */
6316}
6317
f16dd614
DM
6318#ifdef PERL_IMPLICIT_CONTEXT
6319
53d44271 6320/* Implements the MY_CXT_INIT macro. The first time a module is loaded,
f16dd614
DM
6321the global PL_my_cxt_index is incremented, and that value is assigned to
6322that module's static my_cxt_index (who's address is passed as an arg).
6323Then, for each interpreter this function is called for, it makes sure a
6324void* slot is available to hang the static data off, by allocating or
6325extending the interpreter's PL_my_cxt_list array */
6326
53d44271 6327#ifndef PERL_GLOBAL_STRUCT_PRIVATE
f16dd614
DM
6328void *
6329Perl_my_cxt_init(pTHX_ int *index, size_t size)
6330{
97aff369 6331 dVAR;
f16dd614 6332 void *p;
7918f24d 6333 PERL_ARGS_ASSERT_MY_CXT_INIT;
f16dd614
DM
6334 if (*index == -1) {
6335 /* this module hasn't been allocated an index yet */
8703a9a4 6336#if defined(USE_ITHREADS)
f16dd614 6337 MUTEX_LOCK(&PL_my_ctx_mutex);
8703a9a4 6338#endif
f16dd614 6339 *index = PL_my_cxt_index++;
8703a9a4 6340#if defined(USE_ITHREADS)
f16dd614 6341 MUTEX_UNLOCK(&PL_my_ctx_mutex);
8703a9a4 6342#endif
f16dd614
DM
6343 }
6344
6345 /* make sure the array is big enough */
4c901e72
DM
6346 if (PL_my_cxt_size <= *index) {
6347 if (PL_my_cxt_size) {
6348 while (PL_my_cxt_size <= *index)
f16dd614
DM
6349 PL_my_cxt_size *= 2;
6350 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6351 }
6352 else {
6353 PL_my_cxt_size = 16;
6354 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6355 }
6356 }
6357 /* newSV() allocates one more than needed */
6358 p = (void*)SvPVX(newSV(size-1));
6359 PL_my_cxt_list[*index] = p;
6360 Zero(p, size, char);
6361 return p;
6362}
53d44271
JH
6363
6364#else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6365
6366int
6367Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
6368{
6369 dVAR;
6370 int index;
6371
7918f24d
NC
6372 PERL_ARGS_ASSERT_MY_CXT_INDEX;
6373
53d44271
JH
6374 for (index = 0; index < PL_my_cxt_index; index++) {
6375 const char *key = PL_my_cxt_keys[index];
6376 /* try direct pointer compare first - there are chances to success,
6377 * and it's much faster.
6378 */
6379 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
6380 return index;
6381 }
6382 return -1;
6383}
6384
6385void *
6386Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
6387{
6388 dVAR;
6389 void *p;
6390 int index;
6391
7918f24d
NC
6392 PERL_ARGS_ASSERT_MY_CXT_INIT;
6393
53d44271
JH
6394 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
6395 if (index == -1) {
6396 /* this module hasn't been allocated an index yet */
8703a9a4 6397#if defined(USE_ITHREADS)
53d44271 6398 MUTEX_LOCK(&PL_my_ctx_mutex);
8703a9a4 6399#endif
53d44271 6400 index = PL_my_cxt_index++;
8703a9a4 6401#if defined(USE_ITHREADS)
53d44271 6402 MUTEX_UNLOCK(&PL_my_ctx_mutex);
8703a9a4 6403#endif
53d44271
JH
6404 }
6405
6406 /* make sure the array is big enough */
6407 if (PL_my_cxt_size <= index) {
6408 int old_size = PL_my_cxt_size;
6409 int i;
6410 if (PL_my_cxt_size) {
6411 while (PL_my_cxt_size <= index)
6412 PL_my_cxt_size *= 2;
6413 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6414 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6415 }
6416 else {
6417 PL_my_cxt_size = 16;
6418 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6419 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6420 }
6421 for (i = old_size; i < PL_my_cxt_size; i++) {
6422 PL_my_cxt_keys[i] = 0;
6423 PL_my_cxt_list[i] = 0;
6424 }
6425 }
6426 PL_my_cxt_keys[index] = my_cxt_key;
6427 /* newSV() allocates one more than needed */
6428 p = (void*)SvPVX(newSV(size-1));
6429 PL_my_cxt_list[index] = p;
6430 Zero(p, size, char);
6431 return p;
6432}
6433#endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6434#endif /* PERL_IMPLICIT_CONTEXT */
f16dd614 6435
e9b067d9
NC
6436void
6437Perl_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
6438 STRLEN xs_len)
6439{
6440 SV *sv;
6441 const char *vn = NULL;
a2f871a2 6442 SV *const module = PL_stack_base[ax];
e9b067d9
NC
6443
6444 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
6445
6446 if (items >= 2) /* version supplied as bootstrap arg */
6447 sv = PL_stack_base[ax + 1];
6448 else {
6449 /* XXX GV_ADDWARN */
a2f871a2
NC
6450 vn = "XS_VERSION";
6451 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6452 if (!sv || !SvOK(sv)) {
6453 vn = "VERSION";
6454 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6455 }
e9b067d9
NC
6456 }
6457 if (sv) {
f9cc56fa 6458 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
573a19fb 6459 SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version")
f9cc56fa 6460 ? sv : sv_2mortal(new_version(sv));
e9b067d9
NC
6461 xssv = upg_version(xssv, 0);
6462 if ( vcmp(pmsv,xssv) ) {
a2f871a2
NC
6463 SV *string = vstringify(xssv);
6464 SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
6465 " does not match ", module, string);
6466
6467 SvREFCNT_dec(string);
6468 string = vstringify(pmsv);
6469
6470 if (vn) {
6471 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, module, vn,
6472 string);
6473 } else {
6474 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, string);
6475 }
6476 SvREFCNT_dec(string);
6477
e9b067d9 6478 Perl_sv_2mortal(aTHX_ xpt);
e9b067d9 6479 Perl_croak_sv(aTHX_ xpt);
f9cc56fa 6480 }
e9b067d9
NC
6481 }
6482}
6483
379a8907
NC
6484void
6485Perl_xs_apiversion_bootcheck(pTHX_ SV *module, const char *api_p,
6486 STRLEN api_len)
6487{
6488 SV *xpt = NULL;
8a280620
NC
6489 SV *compver = Perl_newSVpvn_flags(aTHX_ api_p, api_len, SVs_TEMP);
6490 SV *runver;
379a8907
NC
6491
6492 PERL_ARGS_ASSERT_XS_APIVERSION_BOOTCHECK;
6493
8a280620 6494 /* This might croak */
379a8907 6495 compver = upg_version(compver, 0);
8a280620
NC
6496 /* This should never croak */
6497 runver = new_version(PL_apiversion);
379a8907 6498 if (vcmp(compver, runver)) {
8a280620
NC
6499 SV *compver_string = vstringify(compver);
6500 SV *runver_string = vstringify(runver);
379a8907 6501 xpt = Perl_newSVpvf(aTHX_ "Perl API version %"SVf
8a280620
NC
6502 " of %"SVf" does not match %"SVf,
6503 compver_string, module, runver_string);
379a8907 6504 Perl_sv_2mortal(aTHX_ xpt);
8a280620
NC
6505
6506 SvREFCNT_dec(compver_string);
6507 SvREFCNT_dec(runver_string);
379a8907 6508 }
379a8907
NC
6509 SvREFCNT_dec(runver);
6510 if (xpt)
6511 Perl_croak_sv(aTHX_ xpt);
6512}
6513
a6cc4119
SP
6514#ifndef HAS_STRLCAT
6515Size_t
6516Perl_my_strlcat(char *dst, const char *src, Size_t size)
6517{
6518 Size_t used, length, copy;
6519
6520 used = strlen(dst);
6521 length = strlen(src);
6522 if (size > 0 && used < size - 1) {
6523 copy = (length >= size - used) ? size - used - 1 : length;
6524 memcpy(dst + used, src, copy);
6525 dst[used + copy] = '\0';
6526 }
6527 return used + length;
6528}
6529#endif
6530
6531#ifndef HAS_STRLCPY
6532Size_t
6533Perl_my_strlcpy(char *dst, const char *src, Size_t size)
6534{
6535 Size_t length, copy;
6536
6537 length = strlen(src);
6538 if (size > 0) {
6539 copy = (length >= size) ? size - 1 : length;
6540 memcpy(dst, src, copy);
6541 dst[copy] = '\0';
6542 }
6543 return length;
6544}
6545#endif
6546
17dd9954
JH
6547#if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
6548/* VC7 or 7.1, building with pre-VC7 runtime libraries. */
6549long _ftol( double ); /* Defined by VC6 C libs. */
6550long _ftol2( double dblSource ) { return _ftol( dblSource ); }
6551#endif
6552
a7999c08
FC
6553PERL_STATIC_INLINE bool
6554S_gv_has_usable_name(pTHX_ GV *gv)
6555{
6556 GV **gvp;
6557 return GvSTASH(gv)
6558 && HvENAME(GvSTASH(gv))
6559 && (gvp = (GV **)hv_fetch(
6560 GvSTASH(gv), GvNAME(gv),
6561 GvNAMEUTF8(gv) ? -GvNAMELEN(gv) : GvNAMELEN(gv), 0
6562 ))
6563 && *gvp == gv;
6564}
6565
c51f309c
NC
6566void
6567Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
6568{
6569 dVAR;
6570 SV * const dbsv = GvSVn(PL_DBsub);
07004ebb
DM
6571 const bool save_taint = PL_tainted;
6572
107c452c
FC
6573 /* When we are called from pp_goto (svp is null),
6574 * we do not care about using dbsv to call CV;
c51f309c
NC
6575 * it's for informational purposes only.
6576 */
6577
7918f24d
NC
6578 PERL_ARGS_ASSERT_GET_DB_SUB;
6579
07004ebb 6580 PL_tainted = FALSE;
c51f309c
NC
6581 save_item(dbsv);
6582 if (!PERLDB_SUB_NN) {
be1cc451 6583 GV *gv = CvGV(cv);
c51f309c 6584
7d8b4ed3
FC
6585 if (!svp) {
6586 gv_efullname3(dbsv, gv, NULL);
6587 }
6588 else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
c51f309c 6589 || strEQ(GvNAME(gv), "END")
a7999c08
FC
6590 || ( /* Could be imported, and old sub redefined. */
6591 (GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv))
6592 &&
159b6efe 6593 !( (SvTYPE(*svp) == SVt_PVGV)
be1cc451 6594 && (GvCV((const GV *)*svp) == cv)
a7999c08 6595 /* Use GV from the stack as a fallback. */
4aaab439 6596 && S_gv_has_usable_name(aTHX_ gv = (GV *)*svp)
be1cc451
FC
6597 )
6598 )
7d8b4ed3 6599 ) {
c51f309c 6600 /* GV is potentially non-unique, or contain different CV. */
daba3364 6601 SV * const tmp = newRV(MUTABLE_SV(cv));
c51f309c
NC
6602 sv_setsv(dbsv, tmp);
6603 SvREFCNT_dec(tmp);
6604 }
6605 else {
a7999c08
FC
6606 sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv)));
6607 sv_catpvs(dbsv, "::");
6608 sv_catpvn_flags(
6609 dbsv, GvNAME(gv), GvNAMELEN(gv),
6610 GvNAMEUTF8(gv) ? SV_CATUTF8 : SV_CATBYTES
6611 );
c51f309c
NC
6612 }
6613 }
6614 else {
6615 const int type = SvTYPE(dbsv);
6616 if (type < SVt_PVIV && type != SVt_IV)
6617 sv_upgrade(dbsv, SVt_PVIV);
6618 (void)SvIOK_on(dbsv);
6619 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
6620 }
07004ebb 6621 TAINT_IF(save_taint);
c51f309c
NC
6622}
6623
3497a01f 6624int
08ea85eb 6625Perl_my_dirfd(pTHX_ DIR * dir) {
3497a01f
SP
6626
6627 /* Most dirfd implementations have problems when passed NULL. */
6628 if(!dir)
6629 return -1;
6630#ifdef HAS_DIRFD
6631 return dirfd(dir);
6632#elif defined(HAS_DIR_DD_FD)
6633 return dir->dd_fd;
6634#else
6635 Perl_die(aTHX_ PL_no_func, "dirfd");
6636 /* NOT REACHED */
6637 return 0;
6638#endif
6639}
6640
f7e71195
AB
6641REGEXP *
6642Perl_get_re_arg(pTHX_ SV *sv) {
f7e71195
AB
6643
6644 if (sv) {
6645 if (SvMAGICAL(sv))
6646 mg_get(sv);
df052ff8
BM
6647 if (SvROK(sv))
6648 sv = MUTABLE_SV(SvRV(sv));
6649 if (SvTYPE(sv) == SVt_REGEXP)
6650 return (REGEXP*) sv;
f7e71195
AB
6651 }
6652
6653 return NULL;
6654}
6655
ce582cee 6656/*
66610fdd
RGS
6657 * Local variables:
6658 * c-indentation-style: bsd
6659 * c-basic-offset: 4
6660 * indent-tabs-mode: t
6661 * End:
6662 *
37442d52
RGS
6663 * ex: set ts=8 sts=4 sw=4 noet:
6664 */