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