This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
The TODO 'Tidy up global variables' can go, replaced with a second
[perl5.git] / util.c
CommitLineData
a0d0e21e 1/* util.c
a687059c 2 *
4bb101f2 3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
b94e2f88 4 * 2000, 2001, 2002, 2003, 2004, 2005, 2006, 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/*
12 * "Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content." --Gandalf
14 */
8d063cd8 15
166f8a29
DM
16/* This file contains assorted utility routines.
17 * Which is a polite way of saying any stuff that people couldn't think of
18 * a better place for. Amongst other things, it includes the warning and
19 * dieing stuff, plus wrappers for malloc code.
20 */
21
8d063cd8 22#include "EXTERN.h"
864dbfa3 23#define PERL_IN_UTIL_C
8d063cd8 24#include "perl.h"
62b28dd9 25
64ca3a65 26#ifndef PERL_MICRO
a687059c 27#include <signal.h>
36477c24
PP
28#ifndef SIG_ERR
29# define SIG_ERR ((Sighandler_t) -1)
30#endif
64ca3a65 31#endif
36477c24 32
172d2248
OS
33#ifdef __Lynx__
34/* Missing protos on LynxOS */
35int putenv(char *);
36#endif
37
ff68c719
PP
38#ifdef I_SYS_WAIT
39# include <sys/wait.h>
40#endif
41
868439a2
JH
42#ifdef HAS_SELECT
43# ifdef I_SYS_SELECT
44# include <sys/select.h>
45# endif
46#endif
47
8d063cd8 48#define FLUSH
8d063cd8 49
16cebae2
GS
50#if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
51# define FD_CLOEXEC 1 /* NeXT needs this */
52#endif
53
a687059c
LW
54/* NOTE: Do not call the next three routines directly. Use the macros
55 * in handy.h, so that we can easily redefine everything to do tracking of
56 * allocated hunks back to the original New to track down any memory leaks.
20cec16a 57 * XXX This advice seems to be widely ignored :-( --AD August 1996.
a687059c
LW
58 */
59
ca8d8976
NC
60static char *
61S_write_no_mem(pTHX)
62{
97aff369 63 dVAR;
ca8d8976
NC
64 /* Can't use PerlIO to write as it allocates memory */
65 PerlLIO_write(PerlIO_fileno(Perl_error_log),
66 PL_no_mem, strlen(PL_no_mem));
67 my_exit(1);
1f440eb2 68 NORETURN_FUNCTION_END;
ca8d8976
NC
69}
70
26fa51c3
AMS
71/* paranoid version of system's malloc() */
72
bd4080b3 73Malloc_t
4f63d024 74Perl_safesysmalloc(MEM_SIZE size)
8d063cd8 75{
54aff467 76 dTHX;
bd4080b3 77 Malloc_t ptr;
55497cff 78#ifdef HAS_64K_LIMIT
62b28dd9 79 if (size > 0xffff) {
bf49b057 80 PerlIO_printf(Perl_error_log,
16cebae2 81 "Allocation too large: %lx\n", size) FLUSH;
54aff467 82 my_exit(1);
62b28dd9 83 }
55497cff 84#endif /* HAS_64K_LIMIT */
e8dda941
JD
85#ifdef PERL_TRACK_MEMPOOL
86 size += sTHX;
87#endif
34de22dd
LW
88#ifdef DEBUGGING
89 if ((long)size < 0)
4f63d024 90 Perl_croak_nocontext("panic: malloc");
34de22dd 91#endif
12ae5dfc 92 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
da927450 93 PERL_ALLOC_CHECK(ptr);
97835f67 94 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
bd61b366 95 if (ptr != NULL) {
e8dda941 96#ifdef PERL_TRACK_MEMPOOL
731dcb42 97 ((struct perl_memory_debug_header *)ptr)->interpreter = aTHX;
cd1541b2
NC
98# ifdef PERL_POISON
99 ((struct perl_memory_debug_header *)ptr)->size = size;
100 ((struct perl_memory_debug_header *)ptr)->in_use = PERL_POISON_INUSE;
101# endif
e8dda941
JD
102 ptr = (Malloc_t)((char*)ptr+sTHX);
103#endif
8d063cd8 104 return ptr;
e8dda941 105}
3280af22 106 else if (PL_nomemok)
bd61b366 107 return NULL;
8d063cd8 108 else {
0bd48802 109 return write_no_mem();
8d063cd8
LW
110 }
111 /*NOTREACHED*/
112}
113
f2517201 114/* paranoid version of system's realloc() */
8d063cd8 115
bd4080b3 116Malloc_t
4f63d024 117Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
8d063cd8 118{
54aff467 119 dTHX;
bd4080b3 120 Malloc_t ptr;
9a34ef1d 121#if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
6ad3d225 122 Malloc_t PerlMem_realloc();
ecfc5424 123#endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
8d063cd8 124
a1d180c4 125#ifdef HAS_64K_LIMIT
5f05dabc 126 if (size > 0xffff) {
bf49b057 127 PerlIO_printf(Perl_error_log,
5f05dabc 128 "Reallocation too large: %lx\n", size) FLUSH;
54aff467 129 my_exit(1);
5f05dabc 130 }
55497cff 131#endif /* HAS_64K_LIMIT */
7614df0c 132 if (!size) {
f2517201 133 safesysfree(where);
7614df0c
JD
134 return NULL;
135 }
136
378cc40b 137 if (!where)
f2517201 138 return safesysmalloc(size);
e8dda941
JD
139#ifdef PERL_TRACK_MEMPOOL
140 where = (Malloc_t)((char*)where-sTHX);
141 size += sTHX;
731dcb42 142 if (((struct perl_memory_debug_header *)where)->interpreter != aTHX) {
e8dda941
JD
143 Perl_croak_nocontext("panic: realloc from wrong pool");
144 }
cd1541b2 145# ifdef PERL_POISON
2bee601c
NC
146 if (((struct perl_memory_debug_header *)where)->size > size) {
147 const MEM_SIZE freed_up =
148 ((struct perl_memory_debug_header *)where)->size - size;
149 char *start_of_freed = ((char *)where) + size;
150 Poison(start_of_freed, freed_up, char);
151 }
cd1541b2 152 ((struct perl_memory_debug_header *)where)->size = size;
cd1541b2 153# endif
e8dda941 154#endif
34de22dd
LW
155#ifdef DEBUGGING
156 if ((long)size < 0)
4f63d024 157 Perl_croak_nocontext("panic: realloc");
34de22dd 158#endif
12ae5dfc 159 ptr = (Malloc_t)PerlMem_realloc(where,size);
da927450 160 PERL_ALLOC_CHECK(ptr);
a1d180c4 161
97835f67
JH
162 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
163 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
79072805 164
bd61b366 165 if (ptr != NULL) {
e8dda941
JD
166#ifdef PERL_TRACK_MEMPOOL
167 ptr = (Malloc_t)((char*)ptr+sTHX);
168#endif
8d063cd8 169 return ptr;
e8dda941 170 }
3280af22 171 else if (PL_nomemok)
bd61b366 172 return NULL;
8d063cd8 173 else {
0bd48802 174 return write_no_mem();
8d063cd8
LW
175 }
176 /*NOTREACHED*/
177}
178
f2517201 179/* safe version of system's free() */
8d063cd8 180
54310121 181Free_t
4f63d024 182Perl_safesysfree(Malloc_t where)
8d063cd8 183{
e8dda941 184#if defined(PERL_IMPLICIT_SYS) || defined(PERL_TRACK_MEMPOOL)
54aff467 185 dTHX;
97aff369
JH
186#else
187 dVAR;
155aba94 188#endif
97835f67 189 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
378cc40b 190 if (where) {
e8dda941
JD
191#ifdef PERL_TRACK_MEMPOOL
192 where = (Malloc_t)((char*)where-sTHX);
731dcb42 193 if (((struct perl_memory_debug_header *)where)->interpreter != aTHX) {
e8dda941
JD
194 Perl_croak_nocontext("panic: free from wrong pool");
195 }
cd1541b2
NC
196# ifdef PERL_POISON
197 {
198 if (((struct perl_memory_debug_header *)where)->in_use
199 == PERL_POISON_FREE) {
200 Perl_croak_nocontext("panic: duplicate free");
201 }
202 if (((struct perl_memory_debug_header *)where)->in_use
203 != PERL_POISON_INUSE) {
204 Perl_croak_nocontext("panic: bad free ");
205 }
206 ((struct perl_memory_debug_header *)where)->in_use
207 = PERL_POISON_FREE;
208 }
209 Poison(where, ((struct perl_memory_debug_header *)where)->size, char);
210# endif
e8dda941 211#endif
6ad3d225 212 PerlMem_free(where);
378cc40b 213 }
8d063cd8
LW
214}
215
f2517201 216/* safe version of system's calloc() */
1050c9ca 217
bd4080b3 218Malloc_t
4f63d024 219Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
1050c9ca 220{
54aff467 221 dTHX;
bd4080b3 222 Malloc_t ptr;
1050c9ca 223
55497cff 224#ifdef HAS_64K_LIMIT
5f05dabc 225 if (size * count > 0xffff) {
bf49b057 226 PerlIO_printf(Perl_error_log,
5f05dabc 227 "Allocation too large: %lx\n", size * count) FLUSH;
54aff467 228 my_exit(1);
5f05dabc 229 }
55497cff 230#endif /* HAS_64K_LIMIT */
1050c9ca
PP
231#ifdef DEBUGGING
232 if ((long)size < 0 || (long)count < 0)
4f63d024 233 Perl_croak_nocontext("panic: calloc");
1050c9ca 234#endif
0b7c1c42 235 size *= count;
e8dda941
JD
236#ifdef PERL_TRACK_MEMPOOL
237 size += sTHX;
238#endif
12ae5dfc 239 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
da927450 240 PERL_ALLOC_CHECK(ptr);
97835f67 241 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)size));
bd61b366 242 if (ptr != NULL) {
1050c9ca 243 memset((void*)ptr, 0, size);
e8dda941 244#ifdef PERL_TRACK_MEMPOOL
731dcb42 245 ((struct perl_memory_debug_header *)ptr)->interpreter = aTHX;
cd1541b2
NC
246# ifdef PERL_POISON
247 ((struct perl_memory_debug_header *)ptr)->size = size;
248 ((struct perl_memory_debug_header *)ptr)->in_use = PERL_POISON_INUSE;
249# endif
e8dda941
JD
250 ptr = (Malloc_t)((char*)ptr+sTHX);
251#endif
1050c9ca
PP
252 return ptr;
253 }
3280af22 254 else if (PL_nomemok)
bd61b366 255 return NULL;
0bd48802 256 return write_no_mem();
1050c9ca
PP
257}
258
cae6d0e5
GS
259/* These must be defined when not using Perl's malloc for binary
260 * compatibility */
261
262#ifndef MYMALLOC
263
264Malloc_t Perl_malloc (MEM_SIZE nbytes)
265{
266 dTHXs;
077a72a9 267 return (Malloc_t)PerlMem_malloc(nbytes);
cae6d0e5
GS
268}
269
270Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
271{
272 dTHXs;
077a72a9 273 return (Malloc_t)PerlMem_calloc(elements, size);
cae6d0e5
GS
274}
275
276Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
277{
278 dTHXs;
077a72a9 279 return (Malloc_t)PerlMem_realloc(where, nbytes);
cae6d0e5
GS
280}
281
282Free_t Perl_mfree (Malloc_t where)
283{
284 dTHXs;
285 PerlMem_free(where);
286}
287
288#endif
289
8d063cd8
LW
290/* copy a string up to some (non-backslashed) delimiter, if any */
291
292char *
e1ec3a88 293Perl_delimcpy(pTHX_ register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
8d063cd8 294{
fc36a67e
PP
295 register I32 tolen;
296 for (tolen = 0; from < fromend; from++, tolen++) {
378cc40b
LW
297 if (*from == '\\') {
298 if (from[1] == delim)
299 from++;
fc36a67e
PP
300 else {
301 if (to < toend)
302 *to++ = *from;
303 tolen++;
304 from++;
305 }
378cc40b 306 }
bedebaa5 307 else if (*from == delim)
8d063cd8 308 break;
fc36a67e
PP
309 if (to < toend)
310 *to++ = *from;
8d063cd8 311 }
bedebaa5
CS
312 if (to < toend)
313 *to = '\0';
fc36a67e 314 *retlen = tolen;
73d840c0 315 return (char *)from;
8d063cd8
LW
316}
317
318/* return ptr to little string in big string, NULL if not found */
378cc40b 319/* This routine was donated by Corey Satten. */
8d063cd8
LW
320
321char *
864dbfa3 322Perl_instr(pTHX_ register const char *big, register const char *little)
378cc40b 323{
79072805 324 register I32 first;
378cc40b 325
a687059c 326 if (!little)
08105a92 327 return (char*)big;
a687059c 328 first = *little++;
378cc40b 329 if (!first)
08105a92 330 return (char*)big;
378cc40b 331 while (*big) {
66a1b24b 332 register const char *s, *x;
378cc40b
LW
333 if (*big++ != first)
334 continue;
335 for (x=big,s=little; *s; /**/ ) {
336 if (!*x)
bd61b366 337 return NULL;
4fc877ac 338 if (*s != *x)
378cc40b 339 break;
4fc877ac
AL
340 else {
341 s++;
342 x++;
378cc40b
LW
343 }
344 }
345 if (!*s)
08105a92 346 return (char*)(big-1);
378cc40b 347 }
bd61b366 348 return NULL;
378cc40b 349}
8d063cd8 350
a687059c
LW
351/* same as instr but allow embedded nulls */
352
353char *
4c8626be 354Perl_ninstr(pTHX_ const char *big, const char *bigend, const char *little, const char *lend)
8d063cd8 355{
4c8626be
GA
356 if (little >= lend)
357 return (char*)big;
358 {
359 char first = *little++;
360 const char *s, *x;
361 bigend -= lend - little;
362 OUTER:
363 while (big <= bigend) {
364 if (*big++ != first)
365 goto OUTER;
366 for (x=big,s=little; s < lend; x++,s++) {
367 if (*s != *x)
368 goto OUTER;
369 }
370 return (char*)(big-1);
371 }
378cc40b 372 }
bd61b366 373 return NULL;
a687059c
LW
374}
375
376/* reverse of the above--find last substring */
377
378char *
864dbfa3 379Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
a687059c 380{
08105a92 381 register const char *bigbeg;
e1ec3a88 382 register const I32 first = *little;
7452cf6a 383 register const char * const littleend = lend;
a687059c 384
260d78c9 385 if (little >= littleend)
08105a92 386 return (char*)bigend;
a687059c
LW
387 bigbeg = big;
388 big = bigend - (littleend - little++);
389 while (big >= bigbeg) {
66a1b24b 390 register const char *s, *x;
a687059c
LW
391 if (*big-- != first)
392 continue;
393 for (x=big+2,s=little; s < littleend; /**/ ) {
4fc877ac 394 if (*s != *x)
a687059c 395 break;
4fc877ac
AL
396 else {
397 x++;
398 s++;
a687059c
LW
399 }
400 }
401 if (s >= littleend)
08105a92 402 return (char*)(big+1);
378cc40b 403 }
bd61b366 404 return NULL;
378cc40b 405}
a687059c 406
cf93c79d
IZ
407#define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
408
409/* As a space optimization, we do not compile tables for strings of length
410 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
411 special-cased in fbm_instr().
412
413 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
414
954c1994 415/*
ccfc67b7
JH
416=head1 Miscellaneous Functions
417
954c1994
GS
418=for apidoc fbm_compile
419
420Analyses the string in order to make fast searches on it using fbm_instr()
421-- the Boyer-Moore algorithm.
422
423=cut
424*/
425
378cc40b 426void
7506f9c3 427Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
378cc40b 428{
97aff369 429 dVAR;
0d46e09a 430 register const U8 *s;
79072805 431 register U32 i;
0b71040e 432 STRLEN len;
79072805
LW
433 I32 rarest = 0;
434 U32 frequency = 256;
435
c517dc2b 436 if (flags & FBMcf_TAIL) {
890ce7af 437 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
396482e1 438 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
c517dc2b
JH
439 if (mg && mg->mg_len >= 0)
440 mg->mg_len++;
441 }
9cbe880b 442 s = (U8*)SvPV_force_mutable(sv, len);
862a34c6 443 SvUPGRADE(sv, SVt_PVBM);
d1be9408 444 if (len == 0) /* TAIL might be on a zero-length string. */
cf93c79d 445 return;
02128f11 446 if (len > 2) {
9cbe880b 447 const unsigned char *sb;
66a1b24b 448 const U8 mlen = (len>255) ? 255 : (U8)len;
890ce7af 449 register U8 *table;
cf93c79d 450
7506f9c3 451 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
9cbe880b 452 table = (unsigned char*)(SvPVX_mutable(sv) + len + FBM_TABLE_OFFSET);
7506f9c3
GS
453 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
454 memset((void*)table, mlen, 256);
455 table[-1] = (U8)flags;
02128f11 456 i = 0;
7506f9c3 457 sb = s - mlen + 1; /* first char (maybe) */
cf93c79d
IZ
458 while (s >= sb) {
459 if (table[*s] == mlen)
7506f9c3 460 table[*s] = (U8)i;
cf93c79d
IZ
461 s--, i++;
462 }
378cc40b 463 }
a0714e2c 464 sv_magic(sv, NULL, PERL_MAGIC_bm, NULL, 0); /* deep magic */
79072805 465 SvVALID_on(sv);
378cc40b 466
9cbe880b 467 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
bbce6d69 468 for (i = 0; i < len; i++) {
22c35a8c 469 if (PL_freq[s[i]] < frequency) {
bbce6d69 470 rarest = i;
22c35a8c 471 frequency = PL_freq[s[i]];
378cc40b
LW
472 }
473 }
79072805 474 BmRARE(sv) = s[rarest];
eb160463 475 BmPREVIOUS(sv) = (U16)rarest;
cf93c79d
IZ
476 BmUSEFUL(sv) = 100; /* Initial value */
477 if (flags & FBMcf_TAIL)
478 SvTAIL_on(sv);
7506f9c3
GS
479 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
480 BmRARE(sv),BmPREVIOUS(sv)));
378cc40b
LW
481}
482
cf93c79d
IZ
483/* If SvTAIL(littlestr), it has a fake '\n' at end. */
484/* If SvTAIL is actually due to \Z or \z, this gives false positives
485 if multiline */
486
954c1994
GS
487/*
488=for apidoc fbm_instr
489
490Returns the location of the SV in the string delimited by C<str> and
bd61b366 491C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
954c1994
GS
492does not have to be fbm_compiled, but the search will not be as fast
493then.
494
495=cut
496*/
497
378cc40b 498char *
864dbfa3 499Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
378cc40b 500{
a687059c 501 register unsigned char *s;
cf93c79d 502 STRLEN l;
9cbe880b
NC
503 register const unsigned char *little
504 = (const unsigned char *)SvPV_const(littlestr,l);
cf93c79d 505 register STRLEN littlelen = l;
e1ec3a88 506 register const I32 multiline = flags & FBMrf_MULTILINE;
cf93c79d 507
eb160463 508 if ((STRLEN)(bigend - big) < littlelen) {
a1d180c4 509 if ( SvTAIL(littlestr)
eb160463 510 && ((STRLEN)(bigend - big) == littlelen - 1)
a1d180c4 511 && (littlelen == 1
12ae5dfc 512 || (*big == *little &&
27da23d5 513 memEQ((char *)big, (char *)little, littlelen - 1))))
cf93c79d 514 return (char*)big;
bd61b366 515 return NULL;
cf93c79d 516 }
378cc40b 517
cf93c79d 518 if (littlelen <= 2) { /* Special-cased */
cf93c79d
IZ
519
520 if (littlelen == 1) {
521 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
522 /* Know that bigend != big. */
523 if (bigend[-1] == '\n')
524 return (char *)(bigend - 1);
525 return (char *) bigend;
526 }
527 s = big;
528 while (s < bigend) {
529 if (*s == *little)
530 return (char *)s;
531 s++;
532 }
533 if (SvTAIL(littlestr))
534 return (char *) bigend;
bd61b366 535 return NULL;
cf93c79d
IZ
536 }
537 if (!littlelen)
538 return (char*)big; /* Cannot be SvTAIL! */
539
540 /* littlelen is 2 */
541 if (SvTAIL(littlestr) && !multiline) {
542 if (bigend[-1] == '\n' && bigend[-2] == *little)
543 return (char*)bigend - 2;
544 if (bigend[-1] == *little)
545 return (char*)bigend - 1;
bd61b366 546 return NULL;
cf93c79d
IZ
547 }
548 {
549 /* This should be better than FBM if c1 == c2, and almost
550 as good otherwise: maybe better since we do less indirection.
551 And we save a lot of memory by caching no table. */
66a1b24b
AL
552 const unsigned char c1 = little[0];
553 const unsigned char c2 = little[1];
cf93c79d
IZ
554
555 s = big + 1;
556 bigend--;
557 if (c1 != c2) {
558 while (s <= bigend) {
559 if (s[0] == c2) {
560 if (s[-1] == c1)
561 return (char*)s - 1;
562 s += 2;
563 continue;
3fe6f2dc 564 }
cf93c79d
IZ
565 next_chars:
566 if (s[0] == c1) {
567 if (s == bigend)
568 goto check_1char_anchor;
569 if (s[1] == c2)
570 return (char*)s;
571 else {
572 s++;
573 goto next_chars;
574 }
575 }
576 else
577 s += 2;
578 }
579 goto check_1char_anchor;
580 }
581 /* Now c1 == c2 */
582 while (s <= bigend) {
583 if (s[0] == c1) {
584 if (s[-1] == c1)
585 return (char*)s - 1;
586 if (s == bigend)
587 goto check_1char_anchor;
588 if (s[1] == c1)
589 return (char*)s;
590 s += 3;
02128f11 591 }
c277df42 592 else
cf93c79d 593 s += 2;
c277df42 594 }
c277df42 595 }
cf93c79d
IZ
596 check_1char_anchor: /* One char and anchor! */
597 if (SvTAIL(littlestr) && (*bigend == *little))
598 return (char *)bigend; /* bigend is already decremented. */
bd61b366 599 return NULL;
d48672a2 600 }
cf93c79d 601 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
bbce6d69 602 s = bigend - littlelen;
a1d180c4 603 if (s >= big && bigend[-1] == '\n' && *s == *little
cf93c79d
IZ
604 /* Automatically of length > 2 */
605 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
7506f9c3 606 {
bbce6d69 607 return (char*)s; /* how sweet it is */
7506f9c3
GS
608 }
609 if (s[1] == *little
610 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
611 {
cf93c79d 612 return (char*)s + 1; /* how sweet it is */
7506f9c3 613 }
bd61b366 614 return NULL;
02128f11 615 }
cf93c79d 616 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
c4420975 617 char * const b = ninstr((char*)big,(char*)bigend,
cf93c79d
IZ
618 (char*)little, (char*)little + littlelen);
619
620 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
621 /* Chop \n from littlestr: */
622 s = bigend - littlelen + 1;
7506f9c3
GS
623 if (*s == *little
624 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
625 {
3fe6f2dc 626 return (char*)s;
7506f9c3 627 }
bd61b366 628 return NULL;
a687059c 629 }
cf93c79d 630 return b;
a687059c 631 }
a1d180c4 632
cf93c79d 633 { /* Do actual FBM. */
c4420975 634 register const unsigned char * const table = little + littlelen + FBM_TABLE_OFFSET;
0d46e09a 635 register const unsigned char *oldlittle;
cf93c79d 636
eb160463 637 if (littlelen > (STRLEN)(bigend - big))
bd61b366 638 return NULL;
cf93c79d
IZ
639 --littlelen; /* Last char found by table lookup */
640
641 s = big + littlelen;
642 little += littlelen; /* last char */
643 oldlittle = little;
644 if (s < bigend) {
645 register I32 tmp;
646
647 top2:
7506f9c3 648 if ((tmp = table[*s])) {
cf93c79d 649 if ((s += tmp) < bigend)
62b28dd9 650 goto top2;
cf93c79d
IZ
651 goto check_end;
652 }
653 else { /* less expensive than calling strncmp() */
66a1b24b 654 register unsigned char * const olds = s;
cf93c79d
IZ
655
656 tmp = littlelen;
657
658 while (tmp--) {
659 if (*--s == *--little)
660 continue;
cf93c79d
IZ
661 s = olds + 1; /* here we pay the price for failure */
662 little = oldlittle;
663 if (s < bigend) /* fake up continue to outer loop */
664 goto top2;
665 goto check_end;
666 }
667 return (char *)s;
a687059c 668 }
378cc40b 669 }
cf93c79d
IZ
670 check_end:
671 if ( s == bigend && (table[-1] & FBMcf_TAIL)
12ae5dfc
JH
672 && memEQ((char *)(bigend - littlelen),
673 (char *)(oldlittle - littlelen), littlelen) )
cf93c79d 674 return (char*)bigend - littlelen;
bd61b366 675 return NULL;
378cc40b 676 }
378cc40b
LW
677}
678
c277df42
IZ
679/* start_shift, end_shift are positive quantities which give offsets
680 of ends of some substring of bigstr.
a0288114 681 If "last" we want the last occurrence.
c277df42 682 old_posp is the way of communication between consequent calls if
a1d180c4 683 the next call needs to find the .
c277df42 684 The initial *old_posp should be -1.
cf93c79d
IZ
685
686 Note that we take into account SvTAIL, so one can get extra
687 optimizations if _ALL flag is set.
c277df42
IZ
688 */
689
cf93c79d 690/* If SvTAIL is actually due to \Z or \z, this gives false positives
26fa51c3 691 if PL_multiline. In fact if !PL_multiline the authoritative answer
cf93c79d
IZ
692 is not supported yet. */
693
378cc40b 694char *
864dbfa3 695Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
378cc40b 696{
97aff369 697 dVAR;
0d46e09a 698 register const unsigned char *big;
79072805
LW
699 register I32 pos;
700 register I32 previous;
701 register I32 first;
0d46e09a 702 register const unsigned char *little;
c277df42 703 register I32 stop_pos;
0d46e09a 704 register const unsigned char *littleend;
c277df42 705 I32 found = 0;
378cc40b 706
c277df42 707 if (*old_posp == -1
3280af22 708 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
cf93c79d
IZ
709 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
710 cant_find:
a1d180c4 711 if ( BmRARE(littlestr) == '\n'
cf93c79d 712 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
cfd0369c 713 little = (const unsigned char *)(SvPVX_const(littlestr));
cf93c79d
IZ
714 littleend = little + SvCUR(littlestr);
715 first = *little++;
716 goto check_tail;
717 }
bd61b366 718 return NULL;
cf93c79d
IZ
719 }
720
cfd0369c 721 little = (const unsigned char *)(SvPVX_const(littlestr));
79072805 722 littleend = little + SvCUR(littlestr);
378cc40b 723 first = *little++;
c277df42 724 /* The value of pos we can start at: */
79072805 725 previous = BmPREVIOUS(littlestr);
cfd0369c 726 big = (const unsigned char *)(SvPVX_const(bigstr));
c277df42
IZ
727 /* The value of pos we can stop at: */
728 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
cf93c79d 729 if (previous + start_shift > stop_pos) {
0fe87f7c
HS
730/*
731 stop_pos does not include SvTAIL in the count, so this check is incorrect
732 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
733*/
734#if 0
cf93c79d
IZ
735 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
736 goto check_tail;
0fe87f7c 737#endif
bd61b366 738 return NULL;
cf93c79d 739 }
c277df42 740 while (pos < previous + start_shift) {
3280af22 741 if (!(pos += PL_screamnext[pos]))
cf93c79d 742 goto cant_find;
378cc40b 743 }
de3bb511 744 big -= previous;
bbce6d69 745 do {
0d46e09a 746 register const unsigned char *s, *x;
ef64f398 747 if (pos >= stop_pos) break;
bbce6d69
PP
748 if (big[pos] != first)
749 continue;
750 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
bbce6d69
PP
751 if (*s++ != *x++) {
752 s--;
753 break;
378cc40b 754 }
bbce6d69 755 }
c277df42
IZ
756 if (s == littleend) {
757 *old_posp = pos;
758 if (!last) return (char *)(big+pos);
759 found = 1;
760 }
3280af22 761 } while ( pos += PL_screamnext[pos] );
a1d180c4 762 if (last && found)
cf93c79d 763 return (char *)(big+(*old_posp));
cf93c79d
IZ
764 check_tail:
765 if (!SvTAIL(littlestr) || (end_shift > 0))
bd61b366 766 return NULL;
cf93c79d 767 /* Ignore the trailing "\n". This code is not microoptimized */
cfd0369c 768 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
cf93c79d
IZ
769 stop_pos = littleend - little; /* Actual littlestr len */
770 if (stop_pos == 0)
771 return (char*)big;
772 big -= stop_pos;
773 if (*big == first
12ae5dfc
JH
774 && ((stop_pos == 1) ||
775 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
cf93c79d 776 return (char*)big;
bd61b366 777 return NULL;
8d063cd8
LW
778}
779
79072805 780I32
864dbfa3 781Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
79072805 782{
e1ec3a88
AL
783 register const U8 *a = (const U8 *)s1;
784 register const U8 *b = (const U8 *)s2;
79072805 785 while (len--) {
22c35a8c 786 if (*a != *b && *a != PL_fold[*b])
bbce6d69
PP
787 return 1;
788 a++,b++;
789 }
790 return 0;
791}
792
793I32
864dbfa3 794Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
bbce6d69 795{
27da23d5 796 dVAR;
e1ec3a88
AL
797 register const U8 *a = (const U8 *)s1;
798 register const U8 *b = (const U8 *)s2;
bbce6d69 799 while (len--) {
22c35a8c 800 if (*a != *b && *a != PL_fold_locale[*b])
bbce6d69
PP
801 return 1;
802 a++,b++;
79072805
LW
803 }
804 return 0;
805}
806
8d063cd8
LW
807/* copy a string to a safe spot */
808
954c1994 809/*
ccfc67b7
JH
810=head1 Memory Management
811
954c1994
GS
812=for apidoc savepv
813
61a925ed
AMS
814Perl's version of C<strdup()>. Returns a pointer to a newly allocated
815string which is a duplicate of C<pv>. The size of the string is
816determined by C<strlen()>. The memory allocated for the new string can
817be freed with the C<Safefree()> function.
954c1994
GS
818
819=cut
820*/
821
8d063cd8 822char *
efdfce31 823Perl_savepv(pTHX_ const char *pv)
8d063cd8 824{
e90e2364 825 if (!pv)
bd61b366 826 return NULL;
66a1b24b
AL
827 else {
828 char *newaddr;
829 const STRLEN pvlen = strlen(pv)+1;
a02a5408 830 Newx(newaddr,pvlen,char);
490a0e98 831 return memcpy(newaddr,pv,pvlen);
66a1b24b 832 }
e90e2364 833
8d063cd8
LW
834}
835
a687059c
LW
836/* same thing but with a known length */
837
954c1994
GS
838/*
839=for apidoc savepvn
840
61a925ed
AMS
841Perl's version of what C<strndup()> would be if it existed. Returns a
842pointer to a newly allocated string which is a duplicate of the first
843C<len> bytes from C<pv>. The memory allocated for the new string can be
844freed with the C<Safefree()> function.
954c1994
GS
845
846=cut
847*/
848
a687059c 849char *
efdfce31 850Perl_savepvn(pTHX_ const char *pv, register I32 len)
a687059c
LW
851{
852 register char *newaddr;
853
a02a5408 854 Newx(newaddr,len+1,char);
92110913 855 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
efdfce31 856 if (pv) {
e90e2364
NC
857 /* might not be null terminated */
858 newaddr[len] = '\0';
07409e01 859 return (char *) CopyD(pv,newaddr,len,char);
92110913
NIS
860 }
861 else {
07409e01 862 return (char *) ZeroD(newaddr,len+1,char);
92110913 863 }
a687059c
LW
864}
865
05ec9bb3
NIS
866/*
867=for apidoc savesharedpv
868
61a925ed
AMS
869A version of C<savepv()> which allocates the duplicate string in memory
870which is shared between threads.
05ec9bb3
NIS
871
872=cut
873*/
874char *
efdfce31 875Perl_savesharedpv(pTHX_ const char *pv)
05ec9bb3 876{
e90e2364 877 register char *newaddr;
490a0e98 878 STRLEN pvlen;
e90e2364 879 if (!pv)
bd61b366 880 return NULL;
e90e2364 881
490a0e98
NC
882 pvlen = strlen(pv)+1;
883 newaddr = (char*)PerlMemShared_malloc(pvlen);
e90e2364 884 if (!newaddr) {
0bd48802 885 return write_no_mem();
05ec9bb3 886 }
490a0e98 887 return memcpy(newaddr,pv,pvlen);
05ec9bb3
NIS
888}
889
2e0de35c
NC
890/*
891=for apidoc savesvpv
892
6832267f 893A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
2e0de35c
NC
894the passed in SV using C<SvPV()>
895
896=cut
897*/
898
899char *
900Perl_savesvpv(pTHX_ SV *sv)
901{
902 STRLEN len;
7452cf6a 903 const char * const pv = SvPV_const(sv, len);
2e0de35c
NC
904 register char *newaddr;
905
26866f99 906 ++len;
a02a5408 907 Newx(newaddr,len,char);
07409e01 908 return (char *) CopyD(pv,newaddr,len,char);
2e0de35c 909}
05ec9bb3
NIS
910
911
cea2e8a9 912/* the SV for Perl_form() and mess() is not kept in an arena */
fc36a67e 913
76e3520e 914STATIC SV *
cea2e8a9 915S_mess_alloc(pTHX)
fc36a67e 916{
97aff369 917 dVAR;
fc36a67e
PP
918 SV *sv;
919 XPVMG *any;
920
e72dc28c 921 if (!PL_dirty)
396482e1 922 return sv_2mortal(newSVpvs(""));
e72dc28c 923
0372dbb6
GS
924 if (PL_mess_sv)
925 return PL_mess_sv;
926
fc36a67e 927 /* Create as PVMG now, to avoid any upgrading later */
a02a5408
JC
928 Newx(sv, 1, SV);
929 Newxz(any, 1, XPVMG);
fc36a67e
PP
930 SvFLAGS(sv) = SVt_PVMG;
931 SvANY(sv) = (void*)any;
6136c704 932 SvPV_set(sv, NULL);
fc36a67e 933 SvREFCNT(sv) = 1 << 30; /* practically infinite */
e72dc28c 934 PL_mess_sv = sv;
fc36a67e
PP
935 return sv;
936}
937
c5be433b 938#if defined(PERL_IMPLICIT_CONTEXT)
cea2e8a9
GS
939char *
940Perl_form_nocontext(const char* pat, ...)
941{
942 dTHX;
c5be433b 943 char *retval;
cea2e8a9
GS
944 va_list args;
945 va_start(args, pat);
c5be433b 946 retval = vform(pat, &args);
cea2e8a9 947 va_end(args);
c5be433b 948 return retval;
cea2e8a9 949}
c5be433b 950#endif /* PERL_IMPLICIT_CONTEXT */
cea2e8a9 951
7c9e965c 952/*
ccfc67b7 953=head1 Miscellaneous Functions
7c9e965c
JP
954=for apidoc form
955
956Takes a sprintf-style format pattern and conventional
957(non-SV) arguments and returns the formatted string.
958
959 (char *) Perl_form(pTHX_ const char* pat, ...)
960
961can be used any place a string (char *) is required:
962
963 char * s = Perl_form("%d.%d",major,minor);
964
965Uses a single private buffer so if you want to format several strings you
966must explicitly copy the earlier strings away (and free the copies when you
967are done).
968
969=cut
970*/
971
8990e307 972char *
864dbfa3 973Perl_form(pTHX_ const char* pat, ...)
8990e307 974{
c5be433b 975 char *retval;
46fc3d4c 976 va_list args;
46fc3d4c 977 va_start(args, pat);
c5be433b 978 retval = vform(pat, &args);
46fc3d4c 979 va_end(args);
c5be433b
GS
980 return retval;
981}
982
983char *
984Perl_vform(pTHX_ const char *pat, va_list *args)
985{
2d03de9c 986 SV * const sv = mess_alloc();
c5be433b 987 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
e72dc28c 988 return SvPVX(sv);
46fc3d4c 989}
a687059c 990
5a844595
GS
991#if defined(PERL_IMPLICIT_CONTEXT)
992SV *
993Perl_mess_nocontext(const char *pat, ...)
994{
995 dTHX;
996 SV *retval;
997 va_list args;
998 va_start(args, pat);
999 retval = vmess(pat, &args);
1000 va_end(args);
1001 return retval;
1002}
1003#endif /* PERL_IMPLICIT_CONTEXT */
1004
06bf62c7 1005SV *
5a844595
GS
1006Perl_mess(pTHX_ const char *pat, ...)
1007{
1008 SV *retval;
1009 va_list args;
1010 va_start(args, pat);
1011 retval = vmess(pat, &args);
1012 va_end(args);
1013 return retval;
1014}
1015
ae7d165c 1016STATIC COP*
8772537c 1017S_closest_cop(pTHX_ COP *cop, const OP *o)
ae7d165c 1018{
97aff369 1019 dVAR;
ae7d165c
PJ
1020 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1021
fabdb6c0
AL
1022 if (!o || o == PL_op)
1023 return cop;
ae7d165c
PJ
1024
1025 if (o->op_flags & OPf_KIDS) {
1026 OP *kid;
fabdb6c0 1027 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
ae7d165c
PJ
1028 COP *new_cop;
1029
1030 /* If the OP_NEXTSTATE has been optimised away we can still use it
1031 * the get the file and line number. */
1032
1033 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1034 cop = (COP *)kid;
1035
1036 /* Keep searching, and return when we've found something. */
1037
1038 new_cop = closest_cop(cop, kid);
fabdb6c0
AL
1039 if (new_cop)
1040 return new_cop;
ae7d165c
PJ
1041 }
1042 }
1043
1044 /* Nothing found. */
1045
8772537c 1046 return Null(COP *);
ae7d165c
PJ
1047}
1048
5a844595
GS
1049SV *
1050Perl_vmess(pTHX_ const char *pat, va_list *args)
46fc3d4c 1051{
97aff369 1052 dVAR;
c4420975 1053 SV * const sv = mess_alloc();
27da23d5 1054 static const char dgd[] = " during global destruction.\n";
46fc3d4c 1055
fc36a67e 1056 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
46fc3d4c 1057 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
ae7d165c
PJ
1058
1059 /*
1060 * Try and find the file and line for PL_op. This will usually be
1061 * PL_curcop, but it might be a cop that has been optimised away. We
1062 * can try to find such a cop by searching through the optree starting
1063 * from the sibling of PL_curcop.
1064 */
1065
e1ec3a88 1066 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
ae7d165c
PJ
1067 if (!cop) cop = PL_curcop;
1068
1069 if (CopLINE(cop))
ed094faf 1070 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
3aed30dc 1071 OutCopFILE(cop), (IV)CopLINE(cop));
2035c5e8 1072 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
e1ec3a88 1073 const bool line_mode = (RsSIMPLE(PL_rs) &&
95a20fc0 1074 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
57def98f 1075 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
edc2eac3
JH
1076 PL_last_in_gv == PL_argvgv ?
1077 "" : GvNAME(PL_last_in_gv),
1078 line_mode ? "line" : "chunk",
1079 (IV)IoLINES(GvIOp(PL_last_in_gv)));
a687059c 1080 }
515f54a1 1081 sv_catpv(sv, PL_dirty ? dgd : ".\n");
a687059c 1082 }
06bf62c7 1083 return sv;
a687059c
LW
1084}
1085
7ff03255
SG
1086void
1087Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1088{
27da23d5 1089 dVAR;
7ff03255
SG
1090 IO *io;
1091 MAGIC *mg;
1092
1093 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1094 && (io = GvIO(PL_stderrgv))
1095 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1096 {
1097 dSP;
1098 ENTER;
1099 SAVETMPS;
1100
1101 save_re_context();
1102 SAVESPTR(PL_stderrgv);
a0714e2c 1103 PL_stderrgv = NULL;
7ff03255
SG
1104
1105 PUSHSTACKi(PERLSI_MAGIC);
1106
1107 PUSHMARK(SP);
1108 EXTEND(SP,2);
1109 PUSHs(SvTIED_obj((SV*)io, mg));
1110 PUSHs(sv_2mortal(newSVpvn(message, msglen)));
1111 PUTBACK;
1112 call_method("PRINT", G_SCALAR);
1113
1114 POPSTACK;
1115 FREETMPS;
1116 LEAVE;
1117 }
1118 else {
1119#ifdef USE_SFIO
1120 /* SFIO can really mess with your errno */
53c1dcc0 1121 const int e = errno;
7ff03255 1122#endif
53c1dcc0 1123 PerlIO * const serr = Perl_error_log;
7ff03255
SG
1124
1125 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1126 (void)PerlIO_flush(serr);
1127#ifdef USE_SFIO
1128 errno = e;
1129#endif
1130 }
1131}
1132
46d9c920 1133/* Common code used by vcroak, vdie, vwarn and vwarner */
3ab1ac99 1134
46d9c920
NC
1135STATIC bool
1136S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8, bool warn)
63315e18 1137{
97aff369 1138 dVAR;
63315e18
NC
1139 HV *stash;
1140 GV *gv;
1141 CV *cv;
46d9c920
NC
1142 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1143 /* sv_2cv might call Perl_croak() or Perl_warner() */
1144 SV * const oldhook = *hook;
1145
1146 assert(oldhook);
63315e18 1147
63315e18 1148 ENTER;
46d9c920
NC
1149 SAVESPTR(*hook);
1150 *hook = NULL;
1151 cv = sv_2cv(oldhook, &stash, &gv, 0);
63315e18
NC
1152 LEAVE;
1153 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1154 dSP;
1155 SV *msg;
1156
1157 ENTER;
1158 save_re_context();
46d9c920
NC
1159 if (warn) {
1160 SAVESPTR(*hook);
1161 *hook = NULL;
1162 }
1163 if (warn || message) {
63315e18
NC
1164 msg = newSVpvn(message, msglen);
1165 SvFLAGS(msg) |= utf8;
1166 SvREADONLY_on(msg);
1167 SAVEFREESV(msg);
1168 }
1169 else {
1170 msg = ERRSV;
1171 }
1172
46d9c920 1173 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
63315e18
NC
1174 PUSHMARK(SP);
1175 XPUSHs(msg);
1176 PUTBACK;
1177 call_sv((SV*)cv, G_DISCARD);
1178 POPSTACK;
1179 LEAVE;
46d9c920 1180 return TRUE;
63315e18 1181 }
46d9c920 1182 return FALSE;
63315e18
NC
1183}
1184
cfd0369c 1185STATIC const char *
e07360fa
AT
1186S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1187 I32* utf8)
1188{
1189 dVAR;
cfd0369c 1190 const char *message;
e07360fa
AT
1191
1192 if (pat) {
890ce7af 1193 SV * const msv = vmess(pat, args);
e07360fa
AT
1194 if (PL_errors && SvCUR(PL_errors)) {
1195 sv_catsv(PL_errors, msv);
cfd0369c 1196 message = SvPV_const(PL_errors, *msglen);
e07360fa
AT
1197 SvCUR_set(PL_errors, 0);
1198 }
1199 else
cfd0369c 1200 message = SvPV_const(msv,*msglen);
e07360fa
AT
1201 *utf8 = SvUTF8(msv);
1202 }
1203 else {
bd61b366 1204 message = NULL;
e07360fa
AT
1205 }
1206
1207 DEBUG_S(PerlIO_printf(Perl_debug_log,
1208 "%p: die/croak: message = %s\ndiehook = %p\n",
1209 thr, message, PL_diehook));
1210 if (PL_diehook) {
46d9c920 1211 S_vdie_common(aTHX_ message, *msglen, *utf8, FALSE);
e07360fa
AT
1212 }
1213 return message;
1214}
1215
c5be433b
GS
1216OP *
1217Perl_vdie(pTHX_ const char* pat, va_list *args)
36477c24 1218{
97aff369 1219 dVAR;
73d840c0 1220 const char *message;
e1ec3a88 1221 const int was_in_eval = PL_in_eval;
06bf62c7 1222 STRLEN msglen;
ff882698 1223 I32 utf8 = 0;
36477c24 1224
bf49b057 1225 DEBUG_S(PerlIO_printf(Perl_debug_log,
199100c8 1226 "%p: die: curstack = %p, mainstack = %p\n",
533c011a 1227 thr, PL_curstack, PL_mainstack));
36477c24 1228
890ce7af 1229 message = vdie_croak_common(pat, args, &msglen, &utf8);
36477c24 1230
06bf62c7 1231 PL_restartop = die_where(message, msglen);
ff882698 1232 SvFLAGS(ERRSV) |= utf8;
bf49b057 1233 DEBUG_S(PerlIO_printf(Perl_debug_log,
7c06b590 1234 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
533c011a 1235 thr, PL_restartop, was_in_eval, PL_top_env));
3280af22 1236 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
6224f72b 1237 JMPENV_JUMP(3);
3280af22 1238 return PL_restartop;
36477c24
PP
1239}
1240
c5be433b 1241#if defined(PERL_IMPLICIT_CONTEXT)
cea2e8a9
GS
1242OP *
1243Perl_die_nocontext(const char* pat, ...)
a687059c 1244{
cea2e8a9
GS
1245 dTHX;
1246 OP *o;
a687059c 1247 va_list args;
cea2e8a9 1248 va_start(args, pat);
c5be433b 1249 o = vdie(pat, &args);
cea2e8a9
GS
1250 va_end(args);
1251 return o;
1252}
c5be433b 1253#endif /* PERL_IMPLICIT_CONTEXT */
cea2e8a9
GS
1254
1255OP *
1256Perl_die(pTHX_ const char* pat, ...)
1257{
1258 OP *o;
1259 va_list args;
1260 va_start(args, pat);
c5be433b 1261 o = vdie(pat, &args);
cea2e8a9
GS
1262 va_end(args);
1263 return o;
1264}
1265
c5be433b
GS
1266void
1267Perl_vcroak(pTHX_ const char* pat, va_list *args)
cea2e8a9 1268{
97aff369 1269 dVAR;
73d840c0 1270 const char *message;
06bf62c7 1271 STRLEN msglen;
ff882698 1272 I32 utf8 = 0;
a687059c 1273
3ab1ac99 1274 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
5a844595 1275
3280af22 1276 if (PL_in_eval) {
06bf62c7 1277 PL_restartop = die_where(message, msglen);
ff882698 1278 SvFLAGS(ERRSV) |= utf8;
6224f72b 1279 JMPENV_JUMP(3);
a0d0e21e 1280 }
84414e3e 1281 else if (!message)
cfd0369c 1282 message = SvPVx_const(ERRSV, msglen);
84414e3e 1283
7ff03255 1284 write_to_stderr(message, msglen);
f86702cc 1285 my_failure_exit();
a687059c
LW
1286}
1287
c5be433b 1288#if defined(PERL_IMPLICIT_CONTEXT)
8990e307 1289void
cea2e8a9 1290Perl_croak_nocontext(const char *pat, ...)
a687059c 1291{
cea2e8a9 1292 dTHX;
a687059c 1293 va_list args;
cea2e8a9 1294 va_start(args, pat);
c5be433b 1295 vcroak(pat, &args);
cea2e8a9
GS
1296 /* NOTREACHED */
1297 va_end(args);
1298}
1299#endif /* PERL_IMPLICIT_CONTEXT */
1300
954c1994 1301/*
ccfc67b7
JH
1302=head1 Warning and Dieing
1303
954c1994
GS
1304=for apidoc croak
1305
9983fa3c 1306This is the XSUB-writer's interface to Perl's C<die> function.
966353fd
MF
1307Normally call this function the same way you call the C C<printf>
1308function. Calling C<croak> returns control directly to Perl,
1309sidestepping the normal C order of execution. See C<warn>.
9983fa3c
GS
1310
1311If you want to throw an exception object, assign the object to
bd61b366 1312C<$@> and then pass C<NULL> to croak():
9983fa3c
GS
1313
1314 errsv = get_sv("@", TRUE);
1315 sv_setsv(errsv, exception_object);
bd61b366 1316 croak(NULL);
954c1994
GS
1317
1318=cut
1319*/
1320
cea2e8a9
GS
1321void
1322Perl_croak(pTHX_ const char *pat, ...)
1323{
1324 va_list args;
1325 va_start(args, pat);
c5be433b 1326 vcroak(pat, &args);
cea2e8a9
GS
1327 /* NOTREACHED */
1328 va_end(args);
1329}
1330
c5be433b
GS
1331void
1332Perl_vwarn(pTHX_ const char* pat, va_list *args)
cea2e8a9 1333{
27da23d5 1334 dVAR;
06bf62c7 1335 STRLEN msglen;
53c1dcc0
AL
1336 SV * const msv = vmess(pat, args);
1337 const I32 utf8 = SvUTF8(msv);
1338 const char * const message = SvPV_const(msv, msglen);
a687059c 1339
3280af22 1340 if (PL_warnhook) {
46d9c920 1341 if (vdie_common(message, msglen, utf8, TRUE))
20cec16a 1342 return;
748a9306 1343 }
87582a92 1344
7ff03255 1345 write_to_stderr(message, msglen);
a687059c 1346}
8d063cd8 1347
c5be433b 1348#if defined(PERL_IMPLICIT_CONTEXT)
cea2e8a9
GS
1349void
1350Perl_warn_nocontext(const char *pat, ...)
1351{
1352 dTHX;
1353 va_list args;
1354 va_start(args, pat);
c5be433b 1355 vwarn(pat, &args);
cea2e8a9
GS
1356 va_end(args);
1357}
1358#endif /* PERL_IMPLICIT_CONTEXT */
1359
954c1994
GS
1360/*
1361=for apidoc warn
1362
966353fd
MF
1363This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1364function the same way you call the C C<printf> function. See C<croak>.
954c1994
GS
1365
1366=cut
1367*/
1368
cea2e8a9
GS
1369void
1370Perl_warn(pTHX_ const char *pat, ...)
1371{
1372 va_list args;
1373 va_start(args, pat);
c5be433b 1374 vwarn(pat, &args);
cea2e8a9
GS
1375 va_end(args);
1376}
1377
c5be433b
GS
1378#if defined(PERL_IMPLICIT_CONTEXT)
1379void
1380Perl_warner_nocontext(U32 err, const char *pat, ...)
1381{
27da23d5 1382 dTHX;
c5be433b
GS
1383 va_list args;
1384 va_start(args, pat);
1385 vwarner(err, pat, &args);
1386 va_end(args);
1387}
1388#endif /* PERL_IMPLICIT_CONTEXT */
1389
599cee73 1390void
864dbfa3 1391Perl_warner(pTHX_ U32 err, const char* pat,...)
599cee73
PM
1392{
1393 va_list args;
c5be433b
GS
1394 va_start(args, pat);
1395 vwarner(err, pat, &args);
1396 va_end(args);
1397}
1398
1399void
1400Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1401{
27da23d5 1402 dVAR;
d13b0d77 1403 if (ckDEAD(err)) {
a3b680e6 1404 SV * const msv = vmess(pat, args);
d13b0d77 1405 STRLEN msglen;
7452cf6a 1406 const char * const message = SvPV_const(msv, msglen);
a3b680e6 1407 const I32 utf8 = SvUTF8(msv);
599cee73 1408
3aed30dc 1409 if (PL_diehook) {
63315e18 1410 assert(message);
46d9c920 1411 S_vdie_common(aTHX_ message, msglen, utf8, FALSE);
3aed30dc
HS
1412 }
1413 if (PL_in_eval) {
1414 PL_restartop = die_where(message, msglen);
ff882698 1415 SvFLAGS(ERRSV) |= utf8;
3aed30dc
HS
1416 JMPENV_JUMP(3);
1417 }
7ff03255 1418 write_to_stderr(message, msglen);
3aed30dc 1419 my_failure_exit();
599cee73
PM
1420 }
1421 else {
d13b0d77 1422 Perl_vwarn(aTHX_ pat, args);
599cee73
PM
1423 }
1424}
1425
f54ba1c2
DM
1426/* implements the ckWARN? macros */
1427
1428bool
1429Perl_ckwarn(pTHX_ U32 w)
1430{
97aff369 1431 dVAR;
f54ba1c2
DM
1432 return
1433 (
1434 isLEXWARN_on
1435 && PL_curcop->cop_warnings != pWARN_NONE
1436 && (
1437 PL_curcop->cop_warnings == pWARN_ALL
1438 || isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1439 || (unpackWARN2(w) &&
1440 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1441 || (unpackWARN3(w) &&
1442 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1443 || (unpackWARN4(w) &&
1444 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1445 )
1446 )
1447 ||
1448 (
1449 isLEXWARN_off && PL_dowarn & G_WARN_ON
1450 )
1451 ;
1452}
1453
1454/* implements the ckWARN?_d macro */
1455
1456bool
1457Perl_ckwarn_d(pTHX_ U32 w)
1458{
97aff369 1459 dVAR;
f54ba1c2
DM
1460 return
1461 isLEXWARN_off
1462 || PL_curcop->cop_warnings == pWARN_ALL
1463 || (
1464 PL_curcop->cop_warnings != pWARN_NONE
1465 && (
1466 isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1467 || (unpackWARN2(w) &&
1468 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1469 || (unpackWARN3(w) &&
1470 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1471 || (unpackWARN4(w) &&
1472 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1473 )
1474 )
1475 ;
1476}
1477
1478
1479
e6587932
DM
1480/* since we've already done strlen() for both nam and val
1481 * we can use that info to make things faster than
1482 * sprintf(s, "%s=%s", nam, val)
1483 */
1484#define my_setenv_format(s, nam, nlen, val, vlen) \
1485 Copy(nam, s, nlen, char); \
1486 *(s+nlen) = '='; \
1487 Copy(val, s+(nlen+1), vlen, char); \
1488 *(s+(nlen+1+vlen)) = '\0'
1489
13b6e58c 1490#ifdef USE_ENVIRON_ARRAY
eccd403f 1491 /* VMS' my_setenv() is in vms.c */
2986a63f 1492#if !defined(WIN32) && !defined(NETWARE)
8d063cd8 1493void
e1ec3a88 1494Perl_my_setenv(pTHX_ const char *nam, const char *val)
8d063cd8 1495{
27da23d5 1496 dVAR;
4efc5df6
GS
1497#ifdef USE_ITHREADS
1498 /* only parent thread can modify process environment */
1499 if (PL_curinterp == aTHX)
1500#endif
1501 {
f2517201 1502#ifndef PERL_USE_SAFE_PUTENV
50acdf95 1503 if (!PL_use_safe_putenv) {
f2517201 1504 /* most putenv()s leak, so we manipulate environ directly */
79072805 1505 register I32 i=setenv_getix(nam); /* where does it go? */
e6587932 1506 int nlen, vlen;
8d063cd8 1507
3280af22 1508 if (environ == PL_origenviron) { /* need we copy environment? */
79072805
LW
1509 I32 j;
1510 I32 max;
fe14fcc3
LW
1511 char **tmpenv;
1512
1513 for (max = i; environ[max]; max++) ;
f2517201
GS
1514 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1515 for (j=0; j<max; j++) { /* copy environment */
e1ec3a88 1516 const int len = strlen(environ[j]);
3aed30dc
HS
1517 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1518 Copy(environ[j], tmpenv[j], len+1, char);
f2517201 1519 }
bd61b366 1520 tmpenv[max] = NULL;
fe14fcc3
LW
1521 environ = tmpenv; /* tell exec where it is now */
1522 }
a687059c 1523 if (!val) {
f2517201 1524 safesysfree(environ[i]);
a687059c
LW
1525 while (environ[i]) {
1526 environ[i] = environ[i+1];
1527 i++;
1528 }
1529 return;
1530 }
8d063cd8 1531 if (!environ[i]) { /* does not exist yet */
f2517201 1532 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
bd61b366 1533 environ[i+1] = NULL; /* make sure it's null terminated */
8d063cd8 1534 }
fe14fcc3 1535 else
f2517201 1536 safesysfree(environ[i]);
e6587932
DM
1537 nlen = strlen(nam);
1538 vlen = strlen(val);
f2517201 1539
e6587932
DM
1540 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1541 /* all that work just for this */
1542 my_setenv_format(environ[i], nam, nlen, val, vlen);
50acdf95
MS
1543 } else {
1544# endif
a0fd4948 1545# if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__)
88f5bc07
AB
1546# if defined(HAS_UNSETENV)
1547 if (val == NULL) {
1548 (void)unsetenv(nam);
1549 } else {
1550 (void)setenv(nam, val, 1);
1551 }
1552# else /* ! HAS_UNSETENV */
1553 (void)setenv(nam, val, 1);
1554# endif /* HAS_UNSETENV */
47dafe4d 1555# else
88f5bc07
AB
1556# if defined(HAS_UNSETENV)
1557 if (val == NULL) {
1558 (void)unsetenv(nam);
1559 } else {
c4420975
AL
1560 const int nlen = strlen(nam);
1561 const int vlen = strlen(val);
1562 char * const new_env =
88f5bc07
AB
1563 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1564 my_setenv_format(new_env, nam, nlen, val, vlen);
1565 (void)putenv(new_env);
1566 }
1567# else /* ! HAS_UNSETENV */
1568 char *new_env;
c4420975
AL
1569 const int nlen = strlen(nam);
1570 int vlen;
88f5bc07
AB
1571 if (!val) {
1572 val = "";
1573 }
1574 vlen = strlen(val);
1575 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1576 /* all that work just for this */
1577 my_setenv_format(new_env, nam, nlen, val, vlen);
1578 (void)putenv(new_env);
1579# endif /* HAS_UNSETENV */
47dafe4d 1580# endif /* __CYGWIN__ */
50acdf95
MS
1581#ifndef PERL_USE_SAFE_PUTENV
1582 }
1583#endif
4efc5df6 1584 }
8d063cd8
LW
1585}
1586
2986a63f 1587#else /* WIN32 || NETWARE */
68dc0745
PP
1588
1589void
72229eff 1590Perl_my_setenv(pTHX_ const char *nam, const char *val)
68dc0745 1591{
27da23d5 1592 dVAR;
ac5c734f 1593 register char *envstr;
e1ec3a88
AL
1594 const int nlen = strlen(nam);
1595 int vlen;
e6587932 1596
ac5c734f
GS
1597 if (!val) {
1598 val = "";
1599 }
e6587932 1600 vlen = strlen(val);
a02a5408 1601 Newx(envstr, nlen+vlen+2, char);
e6587932 1602 my_setenv_format(envstr, nam, nlen, val, vlen);
ac5c734f
GS
1603 (void)PerlEnv_putenv(envstr);
1604 Safefree(envstr);
3e3baf6d
TB
1605}
1606
2986a63f 1607#endif /* WIN32 || NETWARE */
3e3baf6d 1608
2f42fcb0 1609#ifndef PERL_MICRO
3e3baf6d 1610I32
e1ec3a88 1611Perl_setenv_getix(pTHX_ const char *nam)
3e3baf6d 1612{
53c1dcc0 1613 register I32 i;
0d46e09a 1614 register const I32 len = strlen(nam);
3e3baf6d
TB
1615
1616 for (i = 0; environ[i]; i++) {
1617 if (
1618#ifdef WIN32
1619 strnicmp(environ[i],nam,len) == 0
1620#else
1621 strnEQ(environ[i],nam,len)
1622#endif
1623 && environ[i][len] == '=')
1624 break; /* strnEQ must come first to avoid */
1625 } /* potential SEGV's */
1626 return i;
68dc0745 1627}
2f42fcb0 1628#endif /* !PERL_MICRO */
68dc0745 1629
ed79a026 1630#endif /* !VMS && !EPOC*/
378cc40b 1631
16d20bd9 1632#ifdef UNLINK_ALL_VERSIONS
79072805 1633I32
6e732051 1634Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
378cc40b 1635{
79072805 1636 I32 i;
378cc40b 1637
6ad3d225 1638 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
378cc40b
LW
1639 return i ? 0 : -1;
1640}
1641#endif
1642
7a3f2258 1643/* this is a drop-in replacement for bcopy() */
2253333f 1644#if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
378cc40b 1645char *
7a3f2258 1646Perl_my_bcopy(register const char *from,register char *to,register I32 len)
378cc40b 1647{
2d03de9c 1648 char * const retval = to;
378cc40b 1649
7c0587c8
LW
1650 if (from - to >= 0) {
1651 while (len--)
1652 *to++ = *from++;
1653 }
1654 else {
1655 to += len;
1656 from += len;
1657 while (len--)
faf8582f 1658 *(--to) = *(--from);
7c0587c8 1659 }
378cc40b
LW
1660 return retval;
1661}
ffed7fef 1662#endif
378cc40b 1663
7a3f2258 1664/* this is a drop-in replacement for memset() */
fc36a67e
PP
1665#ifndef HAS_MEMSET
1666void *
7a3f2258 1667Perl_my_memset(register char *loc, register I32 ch, register I32 len)
fc36a67e 1668{
2d03de9c 1669 char * const retval = loc;
fc36a67e
PP
1670
1671 while (len--)
1672 *loc++ = ch;
1673 return retval;
1674}
1675#endif
1676
7a3f2258 1677/* this is a drop-in replacement for bzero() */
7c0587c8 1678#if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
378cc40b 1679char *
7a3f2258 1680Perl_my_bzero(register char *loc, register I32 len)
378cc40b 1681{
2d03de9c 1682 char * const retval = loc;
378cc40b
LW
1683
1684 while (len--)
1685 *loc++ = 0;
1686 return retval;
1687}
1688#endif
7c0587c8 1689
7a3f2258 1690/* this is a drop-in replacement for memcmp() */
36477c24 1691#if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
79072805 1692I32
7a3f2258 1693Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
7c0587c8 1694{
e1ec3a88
AL
1695 register const U8 *a = (const U8 *)s1;
1696 register const U8 *b = (const U8 *)s2;
79072805 1697 register I32 tmp;
7c0587c8
LW
1698
1699 while (len--) {
27da23d5 1700 if ((tmp = *a++ - *b++))
7c0587c8
LW
1701 return tmp;
1702 }
1703 return 0;
1704}
36477c24 1705#endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
a687059c 1706
fe14fcc3 1707#ifndef HAS_VPRINTF
a687059c 1708
85e6fe83 1709#ifdef USE_CHAR_VSPRINTF
a687059c
LW
1710char *
1711#else
1712int
1713#endif
08105a92 1714vsprintf(char *dest, const char *pat, char *args)
a687059c
LW
1715{
1716 FILE fakebuf;
1717
1718 fakebuf._ptr = dest;
1719 fakebuf._cnt = 32767;
35c8bce7
LW
1720#ifndef _IOSTRG
1721#define _IOSTRG 0
1722#endif
a687059c
LW
1723 fakebuf._flag = _IOWRT|_IOSTRG;
1724 _doprnt(pat, args, &fakebuf); /* what a kludge */
1725 (void)putc('\0', &fakebuf);
85e6fe83 1726#ifdef USE_CHAR_VSPRINTF
a687059c
LW
1727 return(dest);
1728#else
1729 return 0; /* perl doesn't use return value */
1730#endif
1731}
1732
fe14fcc3 1733#endif /* HAS_VPRINTF */
a687059c
LW
1734
1735#ifdef MYSWAP
ffed7fef 1736#if BYTEORDER != 0x4321
a687059c 1737short
864dbfa3 1738Perl_my_swap(pTHX_ short s)
a687059c
LW
1739{
1740#if (BYTEORDER & 1) == 0
1741 short result;
1742
1743 result = ((s & 255) << 8) + ((s >> 8) & 255);
1744 return result;
1745#else
1746 return s;
1747#endif
1748}
1749
1750long
864dbfa3 1751Perl_my_htonl(pTHX_ long l)
a687059c
LW
1752{
1753 union {
1754 long result;
ffed7fef 1755 char c[sizeof(long)];
a687059c
LW
1756 } u;
1757
ffed7fef 1758#if BYTEORDER == 0x1234
a687059c
LW
1759 u.c[0] = (l >> 24) & 255;
1760 u.c[1] = (l >> 16) & 255;
1761 u.c[2] = (l >> 8) & 255;
1762 u.c[3] = l & 255;
1763 return u.result;
1764#else
ffed7fef 1765#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
cea2e8a9 1766 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
a687059c 1767#else
79072805
LW
1768 register I32 o;
1769 register I32 s;
a687059c 1770
ffed7fef
LW
1771 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1772 u.c[o & 0xf] = (l >> s) & 255;
a687059c
LW
1773 }
1774 return u.result;
1775#endif
1776#endif
1777}
1778
1779long
864dbfa3 1780Perl_my_ntohl(pTHX_ long l)
a687059c
LW
1781{
1782 union {
1783 long l;
ffed7fef 1784 char c[sizeof(long)];
a687059c
LW
1785 } u;
1786
ffed7fef 1787#if BYTEORDER == 0x1234
a687059c
LW
1788 u.c[0] = (l >> 24) & 255;
1789 u.c[1] = (l >> 16) & 255;
1790 u.c[2] = (l >> 8) & 255;
1791 u.c[3] = l & 255;
1792 return u.l;
1793#else
ffed7fef 1794#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
cea2e8a9 1795 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
a687059c 1796#else
79072805
LW
1797 register I32 o;
1798 register I32 s;
a687059c
LW
1799
1800 u.l = l;
1801 l = 0;
ffed7fef
LW
1802 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1803 l |= (u.c[o & 0xf] & 255) << s;
a687059c
LW
1804 }
1805 return l;
1806#endif
1807#endif
1808}
1809
ffed7fef 1810#endif /* BYTEORDER != 0x4321 */
988174c1
LW
1811#endif /* MYSWAP */
1812
1813/*
1814 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1815 * If these functions are defined,
1816 * the BYTEORDER is neither 0x1234 nor 0x4321.
1817 * However, this is not assumed.
1818 * -DWS
1819 */
1820
1109a392 1821#define HTOLE(name,type) \
988174c1 1822 type \
ba106d47 1823 name (register type n) \
988174c1
LW
1824 { \
1825 union { \
1826 type value; \
1827 char c[sizeof(type)]; \
1828 } u; \
79072805 1829 register I32 i; \
1109a392
MHM
1830 register I32 s = 0; \
1831 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
988174c1
LW
1832 u.c[i] = (n >> s) & 0xFF; \
1833 } \
1834 return u.value; \
1835 }
1836
1109a392 1837#define LETOH(name,type) \
988174c1 1838 type \
ba106d47 1839 name (register type n) \
988174c1
LW
1840 { \
1841 union { \
1842 type value; \
1843 char c[sizeof(type)]; \
1844 } u; \
79072805 1845 register I32 i; \
1109a392 1846 register I32 s = 0; \
988174c1
LW
1847 u.value = n; \
1848 n = 0; \
1109a392
MHM
1849 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1850 n |= ((type)(u.c[i] & 0xFF)) << s; \
988174c1
LW
1851 } \
1852 return n; \
1853 }
1854
1109a392
MHM
1855/*
1856 * Big-endian byte order functions.
1857 */
1858
1859#define HTOBE(name,type) \
1860 type \
1861 name (register type n) \
1862 { \
1863 union { \
1864 type value; \
1865 char c[sizeof(type)]; \
1866 } u; \
1867 register I32 i; \
1868 register I32 s = 8*(sizeof(u.c)-1); \
1869 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1870 u.c[i] = (n >> s) & 0xFF; \
1871 } \
1872 return u.value; \
1873 }
1874
1875#define BETOH(name,type) \
1876 type \
1877 name (register type n) \
1878 { \
1879 union { \
1880 type value; \
1881 char c[sizeof(type)]; \
1882 } u; \
1883 register I32 i; \
1884 register I32 s = 8*(sizeof(u.c)-1); \
1885 u.value = n; \
1886 n = 0; \
1887 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1888 n |= ((type)(u.c[i] & 0xFF)) << s; \
1889 } \
1890 return n; \
1891 }
1892
1893/*
1894 * If we just can't do it...
1895 */
1896
1897#define NOT_AVAIL(name,type) \
1898 type \
1899 name (register type n) \
1900 { \
1901 Perl_croak_nocontext(#name "() not available"); \
1902 return n; /* not reached */ \
1903 }
1904
1905
988174c1 1906#if defined(HAS_HTOVS) && !defined(htovs)
1109a392 1907HTOLE(htovs,short)
988174c1
LW
1908#endif
1909#if defined(HAS_HTOVL) && !defined(htovl)
1109a392 1910HTOLE(htovl,long)
988174c1
LW
1911#endif
1912#if defined(HAS_VTOHS) && !defined(vtohs)
1109a392 1913LETOH(vtohs,short)
988174c1
LW
1914#endif
1915#if defined(HAS_VTOHL) && !defined(vtohl)
1109a392
MHM
1916LETOH(vtohl,long)
1917#endif
1918
1919#ifdef PERL_NEED_MY_HTOLE16
1920# if U16SIZE == 2
1921HTOLE(Perl_my_htole16,U16)
1922# else
1923NOT_AVAIL(Perl_my_htole16,U16)
1924# endif
1925#endif
1926#ifdef PERL_NEED_MY_LETOH16
1927# if U16SIZE == 2
1928LETOH(Perl_my_letoh16,U16)
1929# else
1930NOT_AVAIL(Perl_my_letoh16,U16)
1931# endif
1932#endif
1933#ifdef PERL_NEED_MY_HTOBE16
1934# if U16SIZE == 2
1935HTOBE(Perl_my_htobe16,U16)
1936# else
1937NOT_AVAIL(Perl_my_htobe16,U16)
1938# endif
1939#endif
1940#ifdef PERL_NEED_MY_BETOH16
1941# if U16SIZE == 2
1942BETOH(Perl_my_betoh16,U16)
1943# else
1944NOT_AVAIL(Perl_my_betoh16,U16)
1945# endif
1946#endif
1947
1948#ifdef PERL_NEED_MY_HTOLE32
1949# if U32SIZE == 4
1950HTOLE(Perl_my_htole32,U32)
1951# else
1952NOT_AVAIL(Perl_my_htole32,U32)
1953# endif
1954#endif
1955#ifdef PERL_NEED_MY_LETOH32
1956# if U32SIZE == 4
1957LETOH(Perl_my_letoh32,U32)
1958# else
1959NOT_AVAIL(Perl_my_letoh32,U32)
1960# endif
1961#endif
1962#ifdef PERL_NEED_MY_HTOBE32
1963# if U32SIZE == 4
1964HTOBE(Perl_my_htobe32,U32)
1965# else
1966NOT_AVAIL(Perl_my_htobe32,U32)
1967# endif
1968#endif
1969#ifdef PERL_NEED_MY_BETOH32
1970# if U32SIZE == 4
1971BETOH(Perl_my_betoh32,U32)
1972# else
1973NOT_AVAIL(Perl_my_betoh32,U32)
1974# endif
1975#endif
1976
1977#ifdef PERL_NEED_MY_HTOLE64
1978# if U64SIZE == 8
1979HTOLE(Perl_my_htole64,U64)
1980# else
1981NOT_AVAIL(Perl_my_htole64,U64)
1982# endif
1983#endif
1984#ifdef PERL_NEED_MY_LETOH64
1985# if U64SIZE == 8
1986LETOH(Perl_my_letoh64,U64)
1987# else
1988NOT_AVAIL(Perl_my_letoh64,U64)
1989# endif
1990#endif
1991#ifdef PERL_NEED_MY_HTOBE64
1992# if U64SIZE == 8
1993HTOBE(Perl_my_htobe64,U64)
1994# else
1995NOT_AVAIL(Perl_my_htobe64,U64)
1996# endif
1997#endif
1998#ifdef PERL_NEED_MY_BETOH64
1999# if U64SIZE == 8
2000BETOH(Perl_my_betoh64,U64)
2001# else
2002NOT_AVAIL(Perl_my_betoh64,U64)
2003# endif
988174c1 2004#endif
a687059c 2005
1109a392
MHM
2006#ifdef PERL_NEED_MY_HTOLES
2007HTOLE(Perl_my_htoles,short)
2008#endif
2009#ifdef PERL_NEED_MY_LETOHS
2010LETOH(Perl_my_letohs,short)
2011#endif
2012#ifdef PERL_NEED_MY_HTOBES
2013HTOBE(Perl_my_htobes,short)
2014#endif
2015#ifdef PERL_NEED_MY_BETOHS
2016BETOH(Perl_my_betohs,short)
2017#endif
2018
2019#ifdef PERL_NEED_MY_HTOLEI
2020HTOLE(Perl_my_htolei,int)
2021#endif
2022#ifdef PERL_NEED_MY_LETOHI
2023LETOH(Perl_my_letohi,int)
2024#endif
2025#ifdef PERL_NEED_MY_HTOBEI
2026HTOBE(Perl_my_htobei,int)
2027#endif
2028#ifdef PERL_NEED_MY_BETOHI
2029BETOH(Perl_my_betohi,int)
2030#endif
2031
2032#ifdef PERL_NEED_MY_HTOLEL
2033HTOLE(Perl_my_htolel,long)
2034#endif
2035#ifdef PERL_NEED_MY_LETOHL
2036LETOH(Perl_my_letohl,long)
2037#endif
2038#ifdef PERL_NEED_MY_HTOBEL
2039HTOBE(Perl_my_htobel,long)
2040#endif
2041#ifdef PERL_NEED_MY_BETOHL
2042BETOH(Perl_my_betohl,long)
2043#endif
2044
2045void
2046Perl_my_swabn(void *ptr, int n)
2047{
2048 register char *s = (char *)ptr;
2049 register char *e = s + (n-1);
2050 register char tc;
2051
2052 for (n /= 2; n > 0; s++, e--, n--) {
2053 tc = *s;
2054 *s = *e;
2055 *e = tc;
2056 }
2057}
2058
4a7d1889
NIS
2059PerlIO *
2060Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
2061{
2986a63f 2062#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
97aff369 2063 dVAR;
1f852d0d
NIS
2064 int p[2];
2065 register I32 This, that;
2066 register Pid_t pid;
2067 SV *sv;
2068 I32 did_pipes = 0;
2069 int pp[2];
2070
2071 PERL_FLUSHALL_FOR_CHILD;
2072 This = (*mode == 'w');
2073 that = !This;
2074 if (PL_tainting) {
2075 taint_env();
2076 taint_proper("Insecure %s%s", "EXEC");
2077 }
2078 if (PerlProc_pipe(p) < 0)
2079 return Nullfp;
2080 /* Try for another pipe pair for error return */
2081 if (PerlProc_pipe(pp) >= 0)
2082 did_pipes = 1;
52e18b1f 2083 while ((pid = PerlProc_fork()) < 0) {
1f852d0d
NIS
2084 if (errno != EAGAIN) {
2085 PerlLIO_close(p[This]);
4e6dfe71 2086 PerlLIO_close(p[that]);
1f852d0d
NIS
2087 if (did_pipes) {
2088 PerlLIO_close(pp[0]);
2089 PerlLIO_close(pp[1]);
2090 }
2091 return Nullfp;
2092 }
2093 sleep(5);
2094 }
2095 if (pid == 0) {
2096 /* Child */
1f852d0d
NIS
2097#undef THIS
2098#undef THAT
2099#define THIS that
2100#define THAT This
1f852d0d
NIS
2101 /* Close parent's end of error status pipe (if any) */
2102 if (did_pipes) {
2103 PerlLIO_close(pp[0]);
2104#if defined(HAS_FCNTL) && defined(F_SETFD)
2105 /* Close error pipe automatically if exec works */
2106 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2107#endif
2108 }
2109 /* Now dup our end of _the_ pipe to right position */
2110 if (p[THIS] != (*mode == 'r')) {
2111 PerlLIO_dup2(p[THIS], *mode == 'r');
2112 PerlLIO_close(p[THIS]);
4e6dfe71
GS
2113 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2114 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
1f852d0d 2115 }
4e6dfe71
GS
2116 else
2117 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
1f852d0d
NIS
2118#if !defined(HAS_FCNTL) || !defined(F_SETFD)
2119 /* No automatic close - do it by hand */
b7953727
JH
2120# ifndef NOFILE
2121# define NOFILE 20
2122# endif
a080fe3d
NIS
2123 {
2124 int fd;
2125
2126 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
3aed30dc 2127 if (fd != pp[1])
a080fe3d
NIS
2128 PerlLIO_close(fd);
2129 }
1f852d0d
NIS
2130 }
2131#endif
a0714e2c 2132 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
1f852d0d
NIS
2133 PerlProc__exit(1);
2134#undef THIS
2135#undef THAT
2136 }
2137 /* Parent */
52e18b1f 2138 do_execfree(); /* free any memory malloced by child on fork */
1f852d0d
NIS
2139 if (did_pipes)
2140 PerlLIO_close(pp[1]);
2141 /* Keep the lower of the two fd numbers */
2142 if (p[that] < p[This]) {
2143 PerlLIO_dup2(p[This], p[that]);
2144 PerlLIO_close(p[This]);
2145 p[This] = p[that];
2146 }
4e6dfe71
GS
2147 else
2148 PerlLIO_close(p[that]); /* close child's end of pipe */
2149
1f852d0d
NIS
2150 LOCK_FDPID_MUTEX;
2151 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2152 UNLOCK_FDPID_MUTEX;
862a34c6 2153 SvUPGRADE(sv,SVt_IV);
45977657 2154 SvIV_set(sv, pid);
1f852d0d
NIS
2155 PL_forkprocess = pid;
2156 /* If we managed to get status pipe check for exec fail */
2157 if (did_pipes && pid > 0) {
2158 int errkid;
2159 int n = 0, n1;
2160
2161 while (n < sizeof(int)) {
2162 n1 = PerlLIO_read(pp[0],
2163 (void*)(((char*)&errkid)+n),
2164 (sizeof(int)) - n);
2165 if (n1 <= 0)
2166 break;
2167 n += n1;
2168 }
2169 PerlLIO_close(pp[0]);
2170 did_pipes = 0;
2171 if (n) { /* Error */
2172 int pid2, status;
8c51524e 2173 PerlLIO_close(p[This]);
1f852d0d
NIS
2174 if (n != sizeof(int))
2175 Perl_croak(aTHX_ "panic: kid popen errno read");
2176 do {
2177 pid2 = wait4pid(pid, &status, 0);
2178 } while (pid2 == -1 && errno == EINTR);
2179 errno = errkid; /* Propagate errno from kid */
2180 return Nullfp;
2181 }
2182 }
2183 if (did_pipes)
2184 PerlLIO_close(pp[0]);
2185 return PerlIO_fdopen(p[This], mode);
2186#else
4a7d1889
NIS
2187 Perl_croak(aTHX_ "List form of piped open not implemented");
2188 return (PerlIO *) NULL;
1f852d0d 2189#endif
4a7d1889
NIS
2190}
2191
5f05dabc 2192 /* VMS' my_popen() is in VMS.c, same with OS/2. */
cd39f2b6 2193#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
760ac839 2194PerlIO *
3dd43144 2195Perl_my_popen(pTHX_ const char *cmd, const char *mode)
a687059c 2196{
97aff369 2197 dVAR;
a687059c 2198 int p[2];
8ac85365 2199 register I32 This, that;
d8a83dd3 2200 register Pid_t pid;
79072805 2201 SV *sv;
bfce84ec 2202 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
e446cec8
IZ
2203 I32 did_pipes = 0;
2204 int pp[2];
a687059c 2205
45bc9206 2206 PERL_FLUSHALL_FOR_CHILD;
ddcf38b7
IZ
2207#ifdef OS2
2208 if (doexec) {
23da6c43 2209 return my_syspopen(aTHX_ cmd,mode);
ddcf38b7 2210 }
a1d180c4 2211#endif
8ac85365
NIS
2212 This = (*mode == 'w');
2213 that = !This;
3280af22 2214 if (doexec && PL_tainting) {
bbce6d69
PP
2215 taint_env();
2216 taint_proper("Insecure %s%s", "EXEC");
d48672a2 2217 }
c2267164
IZ
2218 if (PerlProc_pipe(p) < 0)
2219 return Nullfp;
e446cec8
IZ
2220 if (doexec && PerlProc_pipe(pp) >= 0)
2221 did_pipes = 1;
52e18b1f 2222 while ((pid = PerlProc_fork()) < 0) {
a687059c 2223 if (errno != EAGAIN) {
6ad3d225 2224 PerlLIO_close(p[This]);
b5ac89c3 2225 PerlLIO_close(p[that]);
e446cec8
IZ
2226 if (did_pipes) {
2227 PerlLIO_close(pp[0]);
2228 PerlLIO_close(pp[1]);
2229 }
a687059c 2230 if (!doexec)
cea2e8a9 2231 Perl_croak(aTHX_ "Can't fork");
a687059c
LW
2232 return Nullfp;
2233 }
2234 sleep(5);
2235 }
2236 if (pid == 0) {
79072805
LW
2237 GV* tmpgv;
2238
30ac6d9b
GS
2239#undef THIS
2240#undef THAT
a687059c 2241#define THIS that
8ac85365 2242#define THAT This
e446cec8
IZ
2243 if (did_pipes) {
2244 PerlLIO_close(pp[0]);
2245#if defined(HAS_FCNTL) && defined(F_SETFD)
2246 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2247#endif
2248 }
a687059c 2249 if (p[THIS] != (*mode == 'r')) {
6ad3d225
GS
2250 PerlLIO_dup2(p[THIS], *mode == 'r');
2251 PerlLIO_close(p[THIS]);
b5ac89c3
NIS
2252 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2253 PerlLIO_close(p[THAT]);
a687059c 2254 }
b5ac89c3
NIS
2255 else
2256 PerlLIO_close(p[THAT]);
4435c477 2257#ifndef OS2
a687059c 2258 if (doexec) {
a0d0e21e 2259#if !defined(HAS_FCNTL) || !defined(F_SETFD)
ae986130
LW
2260#ifndef NOFILE
2261#define NOFILE 20
2262#endif
a080fe3d 2263 {
3aed30dc 2264 int fd;
a080fe3d
NIS
2265
2266 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2267 if (fd != pp[1])
3aed30dc 2268 PerlLIO_close(fd);
a080fe3d 2269 }
ae986130 2270#endif
a080fe3d
NIS
2271 /* may or may not use the shell */
2272 do_exec3(cmd, pp[1], did_pipes);
6ad3d225 2273 PerlProc__exit(1);
a687059c 2274 }
4435c477 2275#endif /* defined OS2 */
fafc274c 2276 if ((tmpgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV))) {
4d76a344 2277 SvREADONLY_off(GvSV(tmpgv));
7766f137 2278 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
4d76a344
RGS
2279 SvREADONLY_on(GvSV(tmpgv));
2280 }
2281#ifdef THREADS_HAVE_PIDS
2282 PL_ppid = (IV)getppid();
2283#endif
3280af22 2284 PL_forkprocess = 0;
ca0c25f6 2285#ifdef PERL_USES_PL_PIDSTATUS
3280af22 2286 hv_clear(PL_pidstatus); /* we have no children */
ca0c25f6 2287#endif
a687059c
LW
2288 return Nullfp;
2289#undef THIS
2290#undef THAT
2291 }
b5ac89c3 2292 do_execfree(); /* free any memory malloced by child on vfork */
e446cec8
IZ
2293 if (did_pipes)
2294 PerlLIO_close(pp[1]);
8ac85365 2295 if (p[that] < p[This]) {
6ad3d225
GS
2296 PerlLIO_dup2(p[This], p[that]);
2297 PerlLIO_close(p[This]);
8ac85365 2298 p[This] = p[that];
62b28dd9 2299 }
b5ac89c3
NIS
2300 else
2301 PerlLIO_close(p[that]);
2302
4755096e 2303 LOCK_FDPID_MUTEX;
3280af22 2304 sv = *av_fetch(PL_fdpid,p[This],TRUE);
4755096e 2305 UNLOCK_FDPID_MUTEX;
862a34c6 2306 SvUPGRADE(sv,SVt_IV);
45977657 2307 SvIV_set(sv, pid);
3280af22 2308 PL_forkprocess = pid;
e446cec8
IZ
2309 if (did_pipes && pid > 0) {
2310 int errkid;
2311 int n = 0, n1;
2312
2313 while (n < sizeof(int)) {
2314 n1 = PerlLIO_read(pp[0],
2315 (void*)(((char*)&errkid)+n),
2316 (sizeof(int)) - n);
2317 if (n1 <= 0)
2318 break;
2319 n += n1;
2320 }
2f96c702
IZ
2321 PerlLIO_close(pp[0]);
2322 did_pipes = 0;
e446cec8 2323 if (n) { /* Error */
faa466a7 2324 int pid2, status;
8c51524e 2325 PerlLIO_close(p[This]);
e446cec8 2326 if (n != sizeof(int))
cea2e8a9 2327 Perl_croak(aTHX_ "panic: kid popen errno read");
faa466a7
RG
2328 do {
2329 pid2 = wait4pid(pid, &status, 0);
2330 } while (pid2 == -1 && errno == EINTR);
e446cec8
IZ
2331 errno = errkid; /* Propagate errno from kid */
2332 return Nullfp;
2333 }
2334 }
2335 if (did_pipes)
2336 PerlLIO_close(pp[0]);
8ac85365 2337 return PerlIO_fdopen(p[This], mode);
a687059c 2338}
7c0587c8 2339#else
85ca448a 2340#if defined(atarist) || defined(EPOC)
7c0587c8 2341FILE *popen();
760ac839 2342PerlIO *
864dbfa3 2343Perl_my_popen(pTHX_ char *cmd, char *mode)
7c0587c8 2344{
45bc9206 2345 PERL_FLUSHALL_FOR_CHILD;
a1d180c4
NIS
2346 /* Call system's popen() to get a FILE *, then import it.
2347 used 0 for 2nd parameter to PerlIO_importFILE;
2348 apparently not used
2349 */
2350 return PerlIO_importFILE(popen(cmd, mode), 0);
7c0587c8 2351}
2b96b0a5
JH
2352#else
2353#if defined(DJGPP)
2354FILE *djgpp_popen();
2355PerlIO *
2356Perl_my_popen(pTHX_ char *cmd, char *mode)
2357{
2358 PERL_FLUSHALL_FOR_CHILD;
2359 /* Call system's popen() to get a FILE *, then import it.
2360 used 0 for 2nd parameter to PerlIO_importFILE;
2361 apparently not used
2362 */
2363 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2364}
2365#endif
7c0587c8
LW
2366#endif
2367
2368#endif /* !DOSISH */
a687059c 2369
52e18b1f
GS
2370/* this is called in parent before the fork() */
2371void
2372Perl_atfork_lock(void)
2373{
27da23d5 2374 dVAR;
3db8f154 2375#if defined(USE_ITHREADS)
52e18b1f
GS
2376 /* locks must be held in locking order (if any) */
2377# ifdef MYMALLOC
2378 MUTEX_LOCK(&PL_malloc_mutex);
2379# endif
2380 OP_REFCNT_LOCK;
2381#endif
2382}
2383
2384/* this is called in both parent and child after the fork() */
2385void
2386Perl_atfork_unlock(void)
2387{
27da23d5 2388 dVAR;
3db8f154 2389#if defined(USE_ITHREADS)
52e18b1f
GS
2390 /* locks must be released in same order as in atfork_lock() */
2391# ifdef MYMALLOC
2392 MUTEX_UNLOCK(&PL_malloc_mutex);
2393# endif
2394 OP_REFCNT_UNLOCK;
2395#endif
2396}
2397
2398Pid_t
2399Perl_my_fork(void)
2400{
2401#if defined(HAS_FORK)
2402 Pid_t pid;
3db8f154 2403#if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
52e18b1f
GS
2404 atfork_lock();
2405 pid = fork();
2406 atfork_unlock();
2407#else
2408 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2409 * handlers elsewhere in the code */
2410 pid = fork();
2411#endif
2412 return pid;
2413#else
2414 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2415 Perl_croak_nocontext("fork() not available");
b961a566 2416 return 0;
52e18b1f
GS
2417#endif /* HAS_FORK */
2418}
2419
748a9306 2420#ifdef DUMP_FDS
35ff7856 2421void
864dbfa3 2422Perl_dump_fds(pTHX_ char *s)
ae986130
LW
2423{
2424 int fd;
c623ac67 2425 Stat_t tmpstatbuf;
ae986130 2426
bf49b057 2427 PerlIO_printf(Perl_debug_log,"%s", s);
ae986130 2428 for (fd = 0; fd < 32; fd++) {
6ad3d225 2429 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
bf49b057 2430 PerlIO_printf(Perl_debug_log," %d",fd);
ae986130 2431 }
bf49b057 2432 PerlIO_printf(Perl_debug_log,"\n");
27da23d5 2433 return;
ae986130 2434}
35ff7856 2435#endif /* DUMP_FDS */
ae986130 2436
fe14fcc3 2437#ifndef HAS_DUP2
fec02dd3 2438int
ba106d47 2439dup2(int oldfd, int newfd)
a687059c 2440{
a0d0e21e 2441#if defined(HAS_FCNTL) && defined(F_DUPFD)
fec02dd3
AD
2442 if (oldfd == newfd)
2443 return oldfd;
6ad3d225 2444 PerlLIO_close(newfd);
fec02dd3 2445 return fcntl(oldfd, F_DUPFD, newfd);
62b28dd9 2446#else
fc36a67e
PP
2447#define DUP2_MAX_FDS 256
2448 int fdtmp[DUP2_MAX_FDS];
79072805 2449 I32 fdx = 0;
ae986130
LW
2450 int fd;
2451
fe14fcc3 2452 if (oldfd == newfd)
fec02dd3 2453 return oldfd;
6ad3d225 2454 PerlLIO_close(newfd);
fc36a67e 2455 /* good enough for low fd's... */
6ad3d225 2456 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
fc36a67e 2457 if (fdx >= DUP2_MAX_FDS) {
6ad3d225 2458 PerlLIO_close(fd);
fc36a67e
PP
2459 fd = -1;
2460 break;
2461 }
ae986130 2462 fdtmp[fdx++] = fd;
fc36a67e 2463 }
ae986130 2464 while (fdx > 0)
6ad3d225 2465 PerlLIO_close(fdtmp[--fdx]);
fec02dd3 2466 return fd;
62b28dd9 2467#endif
a687059c
LW
2468}
2469#endif
2470
64ca3a65 2471#ifndef PERL_MICRO
ff68c719
PP
2472#ifdef HAS_SIGACTION
2473
abea2c45
HS
2474#ifdef MACOS_TRADITIONAL
2475/* We don't want restart behavior on MacOS */
2476#undef SA_RESTART
2477#endif
2478
ff68c719 2479Sighandler_t
864dbfa3 2480Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
ff68c719 2481{
27da23d5 2482 dVAR;
ff68c719
PP
2483 struct sigaction act, oact;
2484
a10b1e10
JH
2485#ifdef USE_ITHREADS
2486 /* only "parent" interpreter can diddle signals */
2487 if (PL_curinterp != aTHX)
8aad04aa 2488 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
2489#endif
2490
8aad04aa 2491 act.sa_handler = (void(*)(int))handler;
ff68c719
PP
2492 sigemptyset(&act.sa_mask);
2493 act.sa_flags = 0;
2494#ifdef SA_RESTART
4ffa73a3
JH
2495 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2496 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
0a8e0eff 2497#endif
358837b8 2498#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
8aad04aa 2499 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
85264bed
CS
2500 act.sa_flags |= SA_NOCLDWAIT;
2501#endif
ff68c719 2502 if (sigaction(signo, &act, &oact) == -1)
8aad04aa 2503 return (Sighandler_t) SIG_ERR;
ff68c719 2504 else
8aad04aa 2505 return (Sighandler_t) oact.sa_handler;
ff68c719
PP
2506}
2507
2508Sighandler_t
864dbfa3 2509Perl_rsignal_state(pTHX_ int signo)
ff68c719
PP
2510{
2511 struct sigaction oact;
2512
2513 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
8aad04aa 2514 return (Sighandler_t) SIG_ERR;
ff68c719 2515 else
8aad04aa 2516 return (Sighandler_t) oact.sa_handler;
ff68c719
PP
2517}
2518
2519int
864dbfa3 2520Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
ff68c719 2521{
27da23d5 2522 dVAR;
ff68c719
PP
2523 struct sigaction act;
2524
a10b1e10
JH
2525#ifdef USE_ITHREADS
2526 /* only "parent" interpreter can diddle signals */
2527 if (PL_curinterp != aTHX)
2528 return -1;
2529#endif
2530
8aad04aa 2531 act.sa_handler = (void(*)(int))handler;
ff68c719
PP
2532 sigemptyset(&act.sa_mask);
2533 act.sa_flags = 0;
2534#ifdef SA_RESTART
4ffa73a3
JH
2535 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2536 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
0a8e0eff 2537#endif
36b5d377 2538#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
8aad04aa 2539 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
85264bed
CS
2540 act.sa_flags |= SA_NOCLDWAIT;
2541#endif
ff68c719
PP
2542 return sigaction(signo, &act, save);
2543}
2544
2545int
864dbfa3 2546Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
ff68c719 2547{
27da23d5 2548 dVAR;
a10b1e10
JH
2549#ifdef USE_ITHREADS
2550 /* only "parent" interpreter can diddle signals */
2551 if (PL_curinterp != aTHX)
2552 return -1;
2553#endif
2554
ff68c719
PP
2555 return sigaction(signo, save, (struct sigaction *)NULL);
2556}
2557
2558#else /* !HAS_SIGACTION */
2559
2560Sighandler_t
864dbfa3 2561Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
ff68c719 2562{
39f1703b 2563#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
2564 /* only "parent" interpreter can diddle signals */
2565 if (PL_curinterp != aTHX)
8aad04aa 2566 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
2567#endif
2568
6ad3d225 2569 return PerlProc_signal(signo, handler);
ff68c719
PP
2570}
2571
fabdb6c0 2572static Signal_t
4e35701f 2573sig_trap(int signo)
ff68c719 2574{
27da23d5
JH
2575 dVAR;
2576 PL_sig_trapped++;
ff68c719
PP
2577}
2578
2579Sighandler_t
864dbfa3 2580Perl_rsignal_state(pTHX_ int signo)
ff68c719 2581{
27da23d5 2582 dVAR;
ff68c719
PP
2583 Sighandler_t oldsig;
2584
39f1703b 2585#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
2586 /* only "parent" interpreter can diddle signals */
2587 if (PL_curinterp != aTHX)
8aad04aa 2588 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
2589#endif
2590
27da23d5 2591 PL_sig_trapped = 0;
6ad3d225
GS
2592 oldsig = PerlProc_signal(signo, sig_trap);
2593 PerlProc_signal(signo, oldsig);
27da23d5 2594 if (PL_sig_trapped)
3aed30dc 2595 PerlProc_kill(PerlProc_getpid(), signo);
ff68c719
PP
2596 return oldsig;
2597}
2598
2599int
864dbfa3 2600Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
ff68c719 2601{
39f1703b 2602#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
2603 /* only "parent" interpreter can diddle signals */
2604 if (PL_curinterp != aTHX)
2605 return -1;
2606#endif
6ad3d225 2607 *save = PerlProc_signal(signo, handler);
8aad04aa 2608 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
ff68c719
PP
2609}
2610
2611int
864dbfa3 2612Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
ff68c719 2613{
39f1703b 2614#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
2615 /* only "parent" interpreter can diddle signals */
2616 if (PL_curinterp != aTHX)
2617 return -1;
2618#endif
8aad04aa 2619 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
ff68c719
PP
2620}
2621
2622#endif /* !HAS_SIGACTION */
64ca3a65 2623#endif /* !PERL_MICRO */
ff68c719 2624
5f05dabc 2625 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
cd39f2b6 2626#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
79072805 2627I32
864dbfa3 2628Perl_my_pclose(pTHX_ PerlIO *ptr)
a687059c 2629{
97aff369 2630 dVAR;
ff68c719 2631 Sigsave_t hstat, istat, qstat;
a687059c 2632 int status;
a0d0e21e 2633 SV **svp;
d8a83dd3
JH
2634 Pid_t pid;
2635 Pid_t pid2;
03136e13 2636 bool close_failed;
b7953727 2637 int saved_errno = 0;
22fae026
TM
2638#ifdef WIN32
2639 int saved_win32_errno;
2640#endif
a687059c 2641
4755096e 2642 LOCK_FDPID_MUTEX;
3280af22 2643 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
4755096e 2644 UNLOCK_FDPID_MUTEX;
25d92023 2645 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
a0d0e21e 2646 SvREFCNT_dec(*svp);
3280af22 2647 *svp = &PL_sv_undef;
ddcf38b7
IZ
2648#ifdef OS2
2649 if (pid == -1) { /* Opened by popen. */
2650 return my_syspclose(ptr);
2651 }
a1d180c4 2652#endif
03136e13
CS
2653 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2654 saved_errno = errno;
22fae026
TM
2655#ifdef WIN32
2656 saved_win32_errno = GetLastError();
2657#endif
03136e13 2658 }
7c0587c8 2659#ifdef UTS
6ad3d225 2660 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
7c0587c8 2661#endif
64ca3a65 2662#ifndef PERL_MICRO
8aad04aa
JH
2663 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
2664 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
2665 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
64ca3a65 2666#endif
748a9306 2667 do {
1d3434b8
GS
2668 pid2 = wait4pid(pid, &status, 0);
2669 } while (pid2 == -1 && errno == EINTR);
64ca3a65 2670#ifndef PERL_MICRO
ff68c719
PP
2671 rsignal_restore(SIGHUP, &hstat);
2672 rsignal_restore(SIGINT, &istat);
2673 rsignal_restore(SIGQUIT, &qstat);
64ca3a65 2674#endif
03136e13 2675 if (close_failed) {
ce6e1103 2676 SETERRNO(saved_errno, 0);
03136e13
CS
2677 return -1;
2678 }
1d3434b8 2679 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
20188a90 2680}
4633a7c4
LW
2681#endif /* !DOSISH */
2682
2986a63f 2683#if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
79072805 2684I32
d8a83dd3 2685Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
20188a90 2686{
97aff369 2687 dVAR;
27da23d5 2688 I32 result = 0;
b7953727
JH
2689 if (!pid)
2690 return -1;
ca0c25f6 2691#ifdef PERL_USES_PL_PIDSTATUS
b7953727 2692 {
3aed30dc 2693 if (pid > 0) {
12072db5
NC
2694 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2695 pid, rather than a string form. */
c4420975 2696 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3aed30dc
HS
2697 if (svp && *svp != &PL_sv_undef) {
2698 *statusp = SvIVX(*svp);
12072db5
NC
2699 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2700 G_DISCARD);
3aed30dc
HS
2701 return pid;
2702 }
2703 }
2704 else {
2705 HE *entry;
2706
2707 hv_iterinit(PL_pidstatus);
2708 if ((entry = hv_iternext(PL_pidstatus))) {
c4420975 2709 SV * const sv = hv_iterval(PL_pidstatus,entry);
7ea75b61 2710 I32 len;
0bcc34c2 2711 const char * const spid = hv_iterkey(entry,&len);
27da23d5 2712
12072db5
NC
2713 assert (len == sizeof(Pid_t));
2714 memcpy((char *)&pid, spid, len);
3aed30dc 2715 *statusp = SvIVX(sv);
7b9a3241
NC
2716 /* The hash iterator is currently on this entry, so simply
2717 calling hv_delete would trigger the lazy delete, which on
2718 aggregate does more work, beacuse next call to hv_iterinit()
2719 would spot the flag, and have to call the delete routine,
2720 while in the meantime any new entries can't re-use that
2721 memory. */
2722 hv_iterinit(PL_pidstatus);
7ea75b61 2723 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3aed30dc
HS
2724 return pid;
2725 }
20188a90
LW
2726 }
2727 }
68a29c53 2728#endif
79072805 2729#ifdef HAS_WAITPID
367f3c24
IZ
2730# ifdef HAS_WAITPID_RUNTIME
2731 if (!HAS_WAITPID_RUNTIME)
2732 goto hard_way;
2733# endif
cddd4526 2734 result = PerlProc_waitpid(pid,statusp,flags);
dfcfdb64 2735 goto finish;
367f3c24
IZ
2736#endif
2737#if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
cddd4526 2738 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
dfcfdb64 2739 goto finish;
367f3c24 2740#endif
ca0c25f6 2741#ifdef PERL_USES_PL_PIDSTATUS
27da23d5 2742#if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
367f3c24 2743 hard_way:
27da23d5 2744#endif
a0d0e21e 2745 {
a0d0e21e 2746 if (flags)
cea2e8a9 2747 Perl_croak(aTHX_ "Can't do waitpid with flags");
a0d0e21e 2748 else {
76e3520e 2749 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
a0d0e21e
LW
2750 pidgone(result,*statusp);
2751 if (result < 0)
2752 *statusp = -1;
2753 }
a687059c
LW
2754 }
2755#endif
27da23d5 2756#if defined(HAS_WAITPID) || defined(HAS_WAIT4)
dfcfdb64 2757 finish:
27da23d5 2758#endif
cddd4526
NIS
2759 if (result < 0 && errno == EINTR) {
2760 PERL_ASYNC_CHECK();
2761 }
2762 return result;
a687059c 2763}
2986a63f 2764#endif /* !DOSISH || OS2 || WIN32 || NETWARE */
a687059c 2765
ca0c25f6 2766#ifdef PERL_USES_PL_PIDSTATUS
7c0587c8 2767void
d8a83dd3 2768Perl_pidgone(pTHX_ Pid_t pid, int status)
a687059c 2769{
79072805 2770 register SV *sv;
a687059c 2771
12072db5 2772 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
862a34c6 2773 SvUPGRADE(sv,SVt_IV);
45977657 2774 SvIV_set(sv, status);
20188a90 2775 return;
a687059c 2776}
ca0c25f6 2777#endif
a687059c 2778
85ca448a 2779#if defined(atarist) || defined(OS2) || defined(EPOC)
7c0587c8 2780int pclose();
ddcf38b7
IZ
2781#ifdef HAS_FORK
2782int /* Cannot prototype with I32
2783 in os2ish.h. */
ba106d47 2784my_syspclose(PerlIO *ptr)
ddcf38b7 2785#else
79072805 2786I32
864dbfa3 2787Perl_my_pclose(pTHX_ PerlIO *ptr)
a1d180c4 2788#endif
a687059c 2789{
760ac839 2790 /* Needs work for PerlIO ! */
c4420975 2791 FILE * const f = PerlIO_findFILE(ptr);
7452cf6a 2792 const I32 result = pclose(f);
2b96b0a5
JH
2793 PerlIO_releaseFILE(ptr,f);
2794 return result;
2795}
2796#endif
2797
933fea7f 2798#if defined(DJGPP)
2b96b0a5
JH
2799int djgpp_pclose();
2800I32
2801Perl_my_pclose(pTHX_ PerlIO *ptr)
2802{
2803 /* Needs work for PerlIO ! */
c4420975 2804 FILE * const f = PerlIO_findFILE(ptr);
2b96b0a5 2805 I32 result = djgpp_pclose(f);
933fea7f 2806 result = (result << 8) & 0xff00;
760ac839
LW
2807 PerlIO_releaseFILE(ptr,f);
2808 return result;
a687059c 2809}
7c0587c8 2810#endif
9f68db38
LW
2811
2812void
864dbfa3 2813Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
9f68db38 2814{
79072805 2815 register I32 todo;
c4420975 2816 register const char * const frombase = from;
9f68db38
LW
2817
2818 if (len == 1) {
08105a92 2819 register const char c = *from;
9f68db38 2820 while (count-- > 0)
5926133d 2821 *to++ = c;
9f68db38
LW
2822 return;
2823 }
2824 while (count-- > 0) {
2825 for (todo = len; todo > 0; todo--) {
2826 *to++ = *from++;
2827 }
2828 from = frombase;
2829 }
2830}
0f85fab0 2831
fe14fcc3 2832#ifndef HAS_RENAME
79072805 2833I32
4373e329 2834Perl_same_dirent(pTHX_ const char *a, const char *b)
62b28dd9 2835{
93a17b20
LW
2836 char *fa = strrchr(a,'/');
2837 char *fb = strrchr(b,'/');
c623ac67
GS
2838 Stat_t tmpstatbuf1;
2839 Stat_t tmpstatbuf2;
c4420975 2840 SV * const tmpsv = sv_newmortal();
62b28dd9
LW
2841
2842 if (fa)
2843 fa++;
2844 else
2845 fa = a;
2846 if (fb)
2847 fb++;
2848 else
2849 fb = b;
2850 if (strNE(a,b))
2851 return FALSE;
2852 if (fa == a)
616d8c9c 2853 sv_setpvn(tmpsv, ".", 1);
62b28dd9 2854 else
46fc3d4c 2855 sv_setpvn(tmpsv, a, fa - a);
95a20fc0 2856 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
62b28dd9
LW
2857 return FALSE;
2858 if (fb == b)
616d8c9c 2859 sv_setpvn(tmpsv, ".", 1);
62b28dd9 2860 else
46fc3d4c 2861 sv_setpvn(tmpsv, b, fb - b);
95a20fc0 2862 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
62b28dd9
LW
2863 return FALSE;
2864 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2865 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2866}
fe14fcc3
LW
2867#endif /* !HAS_RENAME */
2868
491527d0 2869char*
7f315aed
NC
2870Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
2871 const char *const *const search_ext, I32 flags)
491527d0 2872{
97aff369 2873 dVAR;
bd61b366
SS
2874 const char *xfound = NULL;
2875 char *xfailed = NULL;
0f31cffe 2876 char tmpbuf[MAXPATHLEN];
491527d0 2877 register char *s;
5f74f29c 2878 I32 len = 0;
491527d0
GS
2879 int retval;
2880#if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2881# define SEARCH_EXTS ".bat", ".cmd", NULL
2882# define MAX_EXT_LEN 4
2883#endif
2884#ifdef OS2
2885# define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2886# define MAX_EXT_LEN 4
2887#endif
2888#ifdef VMS
2889# define SEARCH_EXTS ".pl", ".com", NULL
2890# define MAX_EXT_LEN 4
2891#endif
2892 /* additional extensions to try in each dir if scriptname not found */
2893#ifdef SEARCH_EXTS
0bcc34c2 2894 static const char *const exts[] = { SEARCH_EXTS };
7f315aed 2895 const char *const *const ext = search_ext ? search_ext : exts;
491527d0 2896 int extidx = 0, i = 0;
bd61b366 2897 const char *curext = NULL;
491527d0 2898#else
53c1dcc0 2899 PERL_UNUSED_ARG(search_ext);
491527d0
GS
2900# define MAX_EXT_LEN 0
2901#endif
2902
2903 /*
2904 * If dosearch is true and if scriptname does not contain path
2905 * delimiters, search the PATH for scriptname.
2906 *
2907 * If SEARCH_EXTS is also defined, will look for each
2908 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2909 * while searching the PATH.
2910 *
2911 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2912 * proceeds as follows:
2913 * If DOSISH or VMSISH:
2914 * + look for ./scriptname{,.foo,.bar}
2915 * + search the PATH for scriptname{,.foo,.bar}
2916 *
2917 * If !DOSISH:
2918 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2919 * this will not look in '.' if it's not in the PATH)
2920 */
84486fc6 2921 tmpbuf[0] = '\0';
491527d0
GS
2922
2923#ifdef VMS
2924# ifdef ALWAYS_DEFTYPES
2925 len = strlen(scriptname);
2926 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
c4420975 2927 int idx = 0, deftypes = 1;
491527d0
GS
2928 bool seen_dot = 1;
2929
bd61b366 2930 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
491527d0
GS
2931# else
2932 if (dosearch) {
c4420975 2933 int idx = 0, deftypes = 1;
491527d0
GS
2934 bool seen_dot = 1;
2935
bd61b366 2936 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
491527d0
GS
2937# endif
2938 /* The first time through, just add SEARCH_EXTS to whatever we
2939 * already have, so we can check for default file types. */
2940 while (deftypes ||
84486fc6 2941 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
491527d0
GS
2942 {
2943 if (deftypes) {
2944 deftypes = 0;
84486fc6 2945 *tmpbuf = '\0';
491527d0 2946 }
84486fc6
GS
2947 if ((strlen(tmpbuf) + strlen(scriptname)
2948 + MAX_EXT_LEN) >= sizeof tmpbuf)
491527d0 2949 continue; /* don't search dir with too-long name */
84486fc6 2950 strcat(tmpbuf, scriptname);
491527d0
GS
2951#else /* !VMS */
2952
2953#ifdef DOSISH
2954 if (strEQ(scriptname, "-"))
2955 dosearch = 0;
2956 if (dosearch) { /* Look in '.' first. */
fe2774ed 2957 const char *cur = scriptname;
491527d0
GS
2958#ifdef SEARCH_EXTS
2959 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2960 while (ext[i])
2961 if (strEQ(ext[i++],curext)) {
2962 extidx = -1; /* already has an ext */
2963 break;
2964 }
2965 do {
2966#endif
2967 DEBUG_p(PerlIO_printf(Perl_debug_log,
2968 "Looking for %s\n",cur));
017f25f1
IZ
2969 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2970 && !S_ISDIR(PL_statbuf.st_mode)) {
491527d0
GS
2971 dosearch = 0;
2972 scriptname = cur;
2973#ifdef SEARCH_EXTS
2974 break;
2975#endif
2976 }
2977#ifdef SEARCH_EXTS
2978 if (cur == scriptname) {
2979 len = strlen(scriptname);
84486fc6 2980 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
491527d0 2981 break;
490a0e98 2982 /* FIXME? Convert to memcpy */
84486fc6 2983 cur = strcpy(tmpbuf, scriptname);
491527d0
GS
2984 }
2985 } while (extidx >= 0 && ext[extidx] /* try an extension? */
84486fc6 2986 && strcpy(tmpbuf+len, ext[extidx++]));
491527d0
GS
2987#endif
2988 }
2989#endif
2990
cd39f2b6
JH
2991#ifdef MACOS_TRADITIONAL
2992 if (dosearch && !strchr(scriptname, ':') &&
2993 (s = PerlEnv_getenv("Commands")))
2994#else
491527d0
GS
2995 if (dosearch && !strchr(scriptname, '/')
2996#ifdef DOSISH
2997 && !strchr(scriptname, '\\')
2998#endif
cd39f2b6
JH
2999 && (s = PerlEnv_getenv("PATH")))
3000#endif
3001 {
491527d0 3002 bool seen_dot = 0;
92f0c265 3003
3280af22
NIS
3004 PL_bufend = s + strlen(s);
3005 while (s < PL_bufend) {
cd39f2b6
JH
3006#ifdef MACOS_TRADITIONAL
3007 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3008 ',',
3009 &len);
3010#else
491527d0
GS
3011#if defined(atarist) || defined(DOSISH)
3012 for (len = 0; *s
3013# ifdef atarist
3014 && *s != ','
3015# endif
3016 && *s != ';'; len++, s++) {
84486fc6
GS
3017 if (len < sizeof tmpbuf)
3018 tmpbuf[len] = *s;
491527d0 3019 }
84486fc6
GS
3020 if (len < sizeof tmpbuf)
3021 tmpbuf[len] = '\0';
491527d0 3022#else /* ! (atarist || DOSISH) */
3280af22 3023 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
491527d0
GS
3024 ':',
3025 &len);
3026#endif /* ! (atarist || DOSISH) */
cd39f2b6 3027#endif /* MACOS_TRADITIONAL */
3280af22 3028 if (s < PL_bufend)
491527d0 3029 s++;
84486fc6 3030 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
491527d0 3031 continue; /* don't search dir with too-long name */
cd39f2b6
JH
3032#ifdef MACOS_TRADITIONAL
3033 if (len && tmpbuf[len - 1] != ':')
3034 tmpbuf[len++] = ':';
3035#else
491527d0 3036 if (len
490a0e98 3037# if defined(atarist) || defined(__MINT__) || defined(DOSISH)
84486fc6
GS
3038 && tmpbuf[len - 1] != '/'
3039 && tmpbuf[len - 1] != '\\'
490a0e98 3040# endif
491527d0 3041 )
84486fc6
GS
3042 tmpbuf[len++] = '/';
3043 if (len == 2 && tmpbuf[0] == '.')
491527d0 3044 seen_dot = 1;
cd39f2b6 3045#endif
490a0e98
NC
3046 /* FIXME? Convert to memcpy by storing previous strlen(scriptname)
3047 */
84486fc6 3048 (void)strcpy(tmpbuf + len, scriptname);
491527d0
GS
3049#endif /* !VMS */
3050
3051#ifdef SEARCH_EXTS
84486fc6 3052 len = strlen(tmpbuf);
491527d0
GS
3053 if (extidx > 0) /* reset after previous loop */
3054 extidx = 0;
3055 do {
3056#endif
84486fc6 3057 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3280af22 3058 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
017f25f1
IZ
3059 if (S_ISDIR(PL_statbuf.st_mode)) {
3060 retval = -1;
3061 }
491527d0
GS
3062#ifdef SEARCH_EXTS
3063 } while ( retval < 0 /* not there */
3064 && extidx>=0 && ext[extidx] /* try an extension? */
84486fc6 3065 && strcpy(tmpbuf+len, ext[extidx++])
491527d0
GS
3066 );
3067#endif
3068 if (retval < 0)
3069 continue;
3280af22
NIS
3070 if (S_ISREG(PL_statbuf.st_mode)
3071 && cando(S_IRUSR,TRUE,&PL_statbuf)
73811745 3072#if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3280af22 3073 && cando(S_IXUSR,TRUE,&PL_statbuf)
491527d0
GS
3074#endif
3075 )
3076 {
3aed30dc 3077 xfound = tmpbuf; /* bingo! */
491527d0
GS
3078 break;
3079 }
3080 if (!xfailed)
84486fc6 3081 xfailed = savepv(tmpbuf);
491527d0
GS
3082 }
3083#ifndef DOSISH
017f25f1 3084 if (!xfound && !seen_dot && !xfailed &&
a1d180c4 3085 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
017f25f1 3086 || S_ISDIR(PL_statbuf.st_mode)))
491527d0
GS
3087#endif
3088 seen_dot = 1; /* Disable message. */
9ccb31f9
GS
3089 if (!xfound) {
3090 if (flags & 1) { /* do or die? */
3aed30dc 3091 Perl_croak(aTHX_ "Can't %s %s%s%s",
9ccb31f9
GS
3092 (xfailed ? "execute" : "find"),
3093 (xfailed ? xfailed : scriptname),
3094 (xfailed ? "" : " on PATH"),
3095 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3096 }
bd61b366 3097 scriptname = NULL;
9ccb31f9 3098 }
43c5f42d 3099 Safefree(xfailed);
491527d0
GS
3100 scriptname = xfound;
3101 }
bd61b366 3102 return (scriptname ? savepv(scriptname) : NULL);
491527d0
GS
3103}
3104
ba869deb
GS
3105#ifndef PERL_GET_CONTEXT_DEFINED
3106
3107void *
3108Perl_get_context(void)
3109{
27da23d5 3110 dVAR;
3db8f154 3111#if defined(USE_ITHREADS)
ba869deb
GS
3112# ifdef OLD_PTHREADS_API
3113 pthread_addr_t t;
3114 if (pthread_getspecific(PL_thr_key, &t))
3115 Perl_croak_nocontext("panic: pthread_getspecific");
3116 return (void*)t;
3117# else
bce813aa 3118# ifdef I_MACH_CTHREADS
8b8b35ab 3119 return (void*)cthread_data(cthread_self());
bce813aa 3120# else
8b8b35ab
JH
3121 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3122# endif
c44d3fdb 3123# endif
ba869deb
GS
3124#else
3125 return (void*)NULL;
3126#endif
3127}
3128
3129void
3130Perl_set_context(void *t)
3131{
8772537c 3132 dVAR;
3db8f154 3133#if defined(USE_ITHREADS)
c44d3fdb
GS
3134# ifdef I_MACH_CTHREADS
3135 cthread_set_data(cthread_self(), t);
3136# else
ba869deb
GS
3137 if (pthread_setspecific(PL_thr_key, t))
3138 Perl_croak_nocontext("panic: pthread_setspecific");
c44d3fdb 3139# endif
b464bac0 3140#else
8772537c 3141 PERL_UNUSED_ARG(t);
ba869deb
GS
3142#endif
3143}
3144
3145#endif /* !PERL_GET_CONTEXT_DEFINED */
491527d0 3146
27da23d5 3147#if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
22239a37 3148struct perl_vars *
864dbfa3 3149Perl_GetVars(pTHX)
22239a37 3150{
533c011a 3151 return &PL_Vars;
22239a37 3152}
31fb1209
NIS
3153#endif
3154
1cb0ed9b 3155char **
864dbfa3 3156Perl_get_op_names(pTHX)
31fb1209 3157{
27da23d5 3158 return (char **)PL_op_name;
31fb1209
NIS
3159}
3160
1cb0ed9b 3161char **
864dbfa3 3162Perl_get_op_descs(pTHX)
31fb1209 3163{
27da23d5 3164 return (char **)PL_op_desc;
31fb1209 3165}
9e6b2b00 3166
e1ec3a88 3167const char *
864dbfa3 3168Perl_get_no_modify(pTHX)
9e6b2b00 3169{
e1ec3a88 3170 return PL_no_modify;
9e6b2b00
GS
3171}
3172
3173U32 *
864dbfa3 3174Perl_get_opargs(pTHX)
9e6b2b00 3175{
27da23d5 3176 return (U32 *)PL_opargs;
9e6b2b00 3177}
51aa15f3 3178
0cb96387
GS
3179PPADDR_t*
3180Perl_get_ppaddr(pTHX)
3181{
27da23d5 3182 dVAR;
12ae5dfc 3183 return (PPADDR_t*)PL_ppaddr;
0cb96387
GS
3184}
3185
a6c40364
GS
3186#ifndef HAS_GETENV_LEN
3187char *
bf4acbe4 3188Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
a6c40364 3189{
8772537c 3190 char * const env_trans = PerlEnv_getenv(env_elem);
a6c40364
GS
3191 if (env_trans)
3192 *len = strlen(env_trans);
3193 return env_trans;
f675dbe5
CB
3194}
3195#endif
3196
dc9e4912
GS
3197
3198MGVTBL*
864dbfa3 3199Perl_get_vtbl(pTHX_ int vtbl_id)
dc9e4912 3200{
7452cf6a 3201 const MGVTBL* result;
dc9e4912
GS
3202
3203 switch(vtbl_id) {
3204 case want_vtbl_sv:
3205 result = &PL_vtbl_sv;
3206 break;
3207 case want_vtbl_env:
3208 result = &PL_vtbl_env;
3209 break;
3210 case want_vtbl_envelem:
3211 result = &PL_vtbl_envelem;
3212 break;
3213 case want_vtbl_sig:
3214 result = &PL_vtbl_sig;
3215 break;
3216 case want_vtbl_sigelem:
3217 result = &PL_vtbl_sigelem;
3218 break;
3219 case want_vtbl_pack:
3220 result = &PL_vtbl_pack;
3221 break;
3222 case want_vtbl_packelem:
3223 result = &PL_vtbl_packelem;
3224 break;
3225 case want_vtbl_dbline:
3226 result = &PL_vtbl_dbline;
3227 break;
3228 case want_vtbl_isa:
3229 result = &PL_vtbl_isa;
3230 break;
3231 case want_vtbl_isaelem:
3232 result = &PL_vtbl_isaelem;
3233 break;
3234 case want_vtbl_arylen:
3235 result = &PL_vtbl_arylen;
3236 break;
3237 case want_vtbl_glob:
3238 result = &PL_vtbl_glob;
3239 break;
3240 case want_vtbl_mglob:
3241 result = &PL_vtbl_mglob;
3242 break;
3243 case want_vtbl_nkeys:
3244 result = &PL_vtbl_nkeys;
3245 break;
3246 case want_vtbl_taint:
3247 result = &PL_vtbl_taint;
3248 break;
3249 case want_vtbl_substr:
3250 result = &PL_vtbl_substr;
3251 break;
3252 case want_vtbl_vec:
3253 result = &PL_vtbl_vec;
3254 break;
3255 case want_vtbl_pos:
3256 result = &PL_vtbl_pos;
3257 break;
3258 case want_vtbl_bm:
3259 result = &PL_vtbl_bm;
3260 break;
3261 case want_vtbl_fm:
3262 result = &PL_vtbl_fm;
3263 break;
3264 case want_vtbl_uvar:
3265 result = &PL_vtbl_uvar;
3266 break;
dc9e4912
GS
3267 case want_vtbl_defelem:
3268 result = &PL_vtbl_defelem;
3269 break;
3270 case want_vtbl_regexp:
3271 result = &PL_vtbl_regexp;
3272 break;
3273 case want_vtbl_regdata:
3274 result = &PL_vtbl_regdata;
3275 break;
3276 case want_vtbl_regdatum:
3277 result = &PL_vtbl_regdatum;
3278 break;
3c90161d 3279#ifdef USE_LOCALE_COLLATE
dc9e4912
GS
3280 case want_vtbl_collxfrm:
3281 result = &PL_vtbl_collxfrm;
3282 break;
3c90161d 3283#endif
dc9e4912
GS
3284 case want_vtbl_amagic:
3285 result = &PL_vtbl_amagic;
3286 break;
3287 case want_vtbl_amagicelem:
3288 result = &PL_vtbl_amagicelem;
3289 break;
810b8aa5
GS
3290 case want_vtbl_backref:
3291 result = &PL_vtbl_backref;
3292 break;
7e8c5dac
HS
3293 case want_vtbl_utf8:
3294 result = &PL_vtbl_utf8;
3295 break;
7452cf6a
AL
3296 default:
3297 result = Null(MGVTBL*);
3298 break;
dc9e4912 3299 }
27da23d5 3300 return (MGVTBL*)result;
dc9e4912
GS
3301}
3302
767df6a1 3303I32
864dbfa3 3304Perl_my_fflush_all(pTHX)
767df6a1 3305{
f800e14d 3306#if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
ce720889 3307 return PerlIO_flush(NULL);
767df6a1 3308#else
8fbdfb7c 3309# if defined(HAS__FWALK)
f13a2bc0 3310 extern int fflush(FILE *);
74cac757
JH
3311 /* undocumented, unprototyped, but very useful BSDism */
3312 extern void _fwalk(int (*)(FILE *));
8fbdfb7c 3313 _fwalk(&fflush);
74cac757 3314 return 0;
8fa7f367 3315# else
8fbdfb7c 3316# if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
8fa7f367 3317 long open_max = -1;
8fbdfb7c 3318# ifdef PERL_FFLUSH_ALL_FOPEN_MAX
d2201af2 3319 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
8fbdfb7c 3320# else
8fa7f367 3321# if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
767df6a1 3322 open_max = sysconf(_SC_OPEN_MAX);
8fa7f367
JH
3323# else
3324# ifdef FOPEN_MAX
74cac757 3325 open_max = FOPEN_MAX;
8fa7f367
JH
3326# else
3327# ifdef OPEN_MAX
74cac757 3328 open_max = OPEN_MAX;
8fa7f367
JH
3329# else
3330# ifdef _NFILE
d2201af2 3331 open_max = _NFILE;
8fa7f367
JH
3332# endif
3333# endif
74cac757 3334# endif
767df6a1
JH
3335# endif
3336# endif
767df6a1
JH
3337 if (open_max > 0) {
3338 long i;
3339 for (i = 0; i < open_max; i++)
d2201af2
AD
3340 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3341 STDIO_STREAM_ARRAY[i]._file < open_max &&
3342 STDIO_STREAM_ARRAY[i]._flag)
3343 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
767df6a1
JH
3344 return 0;
3345 }
8fbdfb7c 3346# endif
93189314 3347 SETERRNO(EBADF,RMS_IFI);
767df6a1 3348 return EOF;
74cac757 3349# endif
767df6a1
JH
3350#endif
3351}
097ee67d 3352
69282e91 3353void
e1ec3a88 3354Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
bc37a18f 3355{
b64e5050 3356 const char * const func =
66fc2fa5
JH
3357 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3358 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
bc37a18f 3359 PL_op_desc[op];
b64e5050
AL
3360 const char * const pars = OP_IS_FILETEST(op) ? "" : "()";
3361 const char * const type = OP_IS_SOCKET(op)
3aed30dc
HS
3362 || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3363 ? "socket" : "filehandle";
b64e5050 3364 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
66fc2fa5 3365
4c80c0b2 3366 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3aed30dc 3367 if (ckWARN(WARN_IO)) {
b64e5050 3368 const char * const direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3aed30dc
HS
3369 if (name && *name)
3370 Perl_warner(aTHX_ packWARN(WARN_IO),
3371 "Filehandle %s opened only for %sput",
fd322ea4 3372 name, direction);
3aed30dc
HS
3373 else
3374 Perl_warner(aTHX_ packWARN(WARN_IO),
fd322ea4 3375 "Filehandle opened only for %sput", direction);
3aed30dc 3376 }
2dd78f96
JH
3377 }
3378 else {
e1ec3a88 3379 const char *vile;
3aed30dc
HS
3380 I32 warn_type;
3381
3382 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3383 vile = "closed";
3384 warn_type = WARN_CLOSED;
3385 }
3386 else {
3387 vile = "unopened";
3388 warn_type = WARN_UNOPENED;
3389 }
3390
3391 if (ckWARN(warn_type)) {
3392 if (name && *name) {
3393 Perl_warner(aTHX_ packWARN(warn_type),
3394 "%s%s on %s %s %s", func, pars, vile, type, name);
3395 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3396 Perl_warner(
3397 aTHX_ packWARN(warn_type),
3398 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3399 func, pars, name
3400 );
3401 }
3402 else {
3403 Perl_warner(aTHX_ packWARN(warn_type),
3404 "%s%s on %s %s", func, pars, vile, type);
3405 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3406 Perl_warner(
3407 aTHX_ packWARN(warn_type),
3408 "\t(Are you trying to call %s%s on dirhandle?)\n",
3409 func, pars
3410 );
3411 }
3412 }
bc37a18f 3413 }
69282e91 3414}
a926ef6b
JH
3415
3416#ifdef EBCDIC
cbebf344
JH
3417/* in ASCII order, not that it matters */
3418static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3419
a926ef6b
JH
3420int
3421Perl_ebcdic_control(pTHX_ int ch)
3422{
3aed30dc 3423 if (ch > 'a') {
e1ec3a88 3424 const char *ctlp;
3aed30dc
HS
3425
3426 if (islower(ch))
3427 ch = toupper(ch);
3428
3429 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3430 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
a926ef6b 3431 }
3aed30dc
HS
3432
3433 if (ctlp == controllablechars)
3434 return('\177'); /* DEL */
3435 else
3436 return((unsigned char)(ctlp - controllablechars - 1));
3437 } else { /* Want uncontrol */
3438 if (ch == '\177' || ch == -1)
3439 return('?');
3440 else if (ch == '\157')
3441 return('\177');
3442 else if (ch == '\174')
3443 return('\000');
3444 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3445 return('\036');
3446 else if (ch == '\155')
3447 return('\037');
3448 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3449 return(controllablechars[ch+1]);
3450 else
3451 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3452 }
a926ef6b
JH
3453}
3454#endif
e72cf795 3455
f6adc668 3456/* To workaround core dumps from the uninitialised tm_zone we get the
e72cf795
JH
3457 * system to give us a reasonable struct to copy. This fix means that
3458 * strftime uses the tm_zone and tm_gmtoff values returned by
3459 * localtime(time()). That should give the desired result most of the
3460 * time. But probably not always!
3461 *
f6adc668
JH
3462 * This does not address tzname aspects of NETaa14816.
3463 *
e72cf795 3464 */
f6adc668 3465
e72cf795
JH
3466#ifdef HAS_GNULIBC
3467# ifndef STRUCT_TM_HASZONE
3468# define STRUCT_TM_HASZONE
3469# endif
3470#endif
3471
f6adc668
JH
3472#ifdef STRUCT_TM_HASZONE /* Backward compat */
3473# ifndef HAS_TM_TM_ZONE
3474# define HAS_TM_TM_ZONE
3475# endif
3476#endif
3477
e72cf795 3478void
f1208910 3479Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
e72cf795 3480{
f6adc668 3481#ifdef HAS_TM_TM_ZONE
e72cf795 3482 Time_t now;
1b6737cc 3483 const struct tm* my_tm;
e72cf795 3484 (void)time(&now);
82c57498 3485 my_tm = localtime(&now);
ca46b8ee
SP
3486 if (my_tm)
3487 Copy(my_tm, ptm, 1, struct tm);
1b6737cc
AL
3488#else
3489 PERL_UNUSED_ARG(ptm);
e72cf795
JH
3490#endif
3491}
3492
3493/*
3494 * mini_mktime - normalise struct tm values without the localtime()
3495 * semantics (and overhead) of mktime().
3496 */
3497void
f1208910 3498Perl_mini_mktime(pTHX_ struct tm *ptm)
e72cf795
JH
3499{
3500 int yearday;
3501 int secs;
3502 int month, mday, year, jday;
3503 int odd_cent, odd_year;
3504
3505#define DAYS_PER_YEAR 365
3506#define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3507#define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3508#define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3509#define SECS_PER_HOUR (60*60)
3510#define SECS_PER_DAY (24*SECS_PER_HOUR)
3511/* parentheses deliberately absent on these two, otherwise they don't work */
3512#define MONTH_TO_DAYS 153/5
3513#define DAYS_TO_MONTH 5/153
3514/* offset to bias by March (month 4) 1st between month/mday & year finding */
3515#define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3516/* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3517#define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3518
3519/*
3520 * Year/day algorithm notes:
3521 *
3522 * With a suitable offset for numeric value of the month, one can find
3523 * an offset into the year by considering months to have 30.6 (153/5) days,
3524 * using integer arithmetic (i.e., with truncation). To avoid too much
3525 * messing about with leap days, we consider January and February to be
3526 * the 13th and 14th month of the previous year. After that transformation,
3527 * we need the month index we use to be high by 1 from 'normal human' usage,
3528 * so the month index values we use run from 4 through 15.
3529 *
3530 * Given that, and the rules for the Gregorian calendar (leap years are those
3531 * divisible by 4 unless also divisible by 100, when they must be divisible
3532 * by 400 instead), we can simply calculate the number of days since some
3533 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3534 * the days we derive from our month index, and adding in the day of the
3535 * month. The value used here is not adjusted for the actual origin which
3536 * it normally would use (1 January A.D. 1), since we're not exposing it.
3537 * We're only building the value so we can turn around and get the
3538 * normalised values for the year, month, day-of-month, and day-of-year.
3539 *
3540 * For going backward, we need to bias the value we're using so that we find
3541 * the right year value. (Basically, we don't want the contribution of
3542 * March 1st to the number to apply while deriving the year). Having done
3543 * that, we 'count up' the contribution to the year number by accounting for
3544 * full quadracenturies (400-year periods) with their extra leap days, plus
3545 * the contribution from full centuries (to avoid counting in the lost leap
3546 * days), plus the contribution from full quad-years (to count in the normal
3547 * leap days), plus the leftover contribution from any non-leap years.
3548 * At this point, if we were working with an actual leap day, we'll have 0
3549 * days left over. This is also true for March 1st, however. So, we have
3550 * to special-case that result, and (earlier) keep track of the 'odd'
3551 * century and year contributions. If we got 4 extra centuries in a qcent,
3552 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3553 * Otherwise, we add back in the earlier bias we removed (the 123 from
3554 * figuring in March 1st), find the month index (integer division by 30.6),
3555 * and the remainder is the day-of-month. We then have to convert back to
3556 * 'real' months (including fixing January and February from being 14/15 in
3557 * the previous year to being in the proper year). After that, to get
3558 * tm_yday, we work with the normalised year and get a new yearday value for
3559 * January 1st, which we subtract from the yearday value we had earlier,
3560 * representing the date we've re-built. This is done from January 1
3561 * because tm_yday is 0-origin.
3562 *
3563 * Since POSIX time routines are only guaranteed to work for times since the
3564 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3565 * applies Gregorian calendar rules even to dates before the 16th century
3566 * doesn't bother me. Besides, you'd need cultural context for a given
3567 * date to know whether it was Julian or Gregorian calendar, and that's
3568 * outside the scope for this routine. Since we convert back based on the
3569 * same rules we used to build the yearday, you'll only get strange results
3570 * for input which needed normalising, or for the 'odd' century years which
3571 * were leap years in the Julian calander but not in the Gregorian one.
3572 * I can live with that.
3573 *
3574 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3575 * that's still outside the scope for POSIX time manipulation, so I don't
3576 * care.
3577 */
3578
3579 year = 1900 + ptm->tm_year;
3580 month = ptm->tm_mon;
3581 mday = ptm->tm_mday;
3582 /* allow given yday with no month & mday to dominate the result */
3583 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3584 month = 0;
3585 mday = 0;
3586 jday = 1 + ptm->tm_yday;
3587 }
3588 else {
3589 jday = 0;
3590 }
3591 if (month >= 2)
3592 month+=2;
3593 else
3594 month+=14, year--;
3595 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3596 yearday += month*MONTH_TO_DAYS + mday + jday;
3597 /*
3598 * Note that we don't know when leap-seconds were or will be,
3599 * so we have to trust the user if we get something which looks
3600 * like a sensible leap-second. Wild values for seconds will
3601 * be rationalised, however.
3602 */
3603 if ((unsigned) ptm->tm_sec <= 60) {
3604 secs = 0;
3605 }
3606 else {
3607 secs = ptm->tm_sec;
3608 ptm->tm_sec = 0;
3609 }
3610 secs += 60 * ptm->tm_min;
3611 secs += SECS_PER_HOUR * ptm->tm_hour;
3612 if (secs < 0) {
3613 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3614 /* got negative remainder, but need positive time */
3615 /* back off an extra day to compensate */
3616 yearday += (secs/SECS_PER_DAY)-1;
3617 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3618 }
3619 else {
3620 yearday += (secs/SECS_PER_DAY);
3621 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3622 }
3623 }
3624 else if (secs >= SECS_PER_DAY) {
3625 yearday += (secs/SECS_PER_DAY);
3626 secs %= SECS_PER_DAY;
3627 }
3628 ptm->tm_hour = secs/SECS_PER_HOUR;
3629 secs %= SECS_PER_HOUR;