This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Get rid of the following gcc format warnings by simplifying the
[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));
e8dda941
JD
95 if (ptr != Nullch) {
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)
7c0587c8 107 return Nullch;
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
e8dda941
JD
165 if (ptr != Nullch) {
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)
7c0587c8 172 return Nullch;
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));
1050c9ca
PP
242 if (ptr != Nullch) {
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)
1050c9ca 255 return Nullch;
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)
337 return Nullch;
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
LW
347 }
348 return Nullch;
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 }
a687059c
LW
373 return Nullch;
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 }
a687059c 404 return Nullch;
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 }
14befaf4 464 sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 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
491C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
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
IZ
514 return (char*)big;
515 return Nullch;
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;
535 return Nullch;
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;
546 return Nullch;
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. */
599 return Nullch;
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 }
02128f11
IZ
614 return Nullch;
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 }
cf93c79d 628 return Nullch;
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))
cf93c79d
IZ
638 return Nullch;
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
IZ
674 return (char*)bigend - littlelen;
675 return Nullch;
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 }
378cc40b 718 return Nullch;
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
cf93c79d
IZ
738 return Nullch;
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))
766 return Nullch;
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
IZ
776 return (char*)big;
777 return Nullch;
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
NC
825 if (!pv)
826 return Nullch;
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
NC
879 if (!pv)
880 return Nullch;
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);
1103 PL_stderrgv = Nullgv;
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
3ab1ac99
NC
1133/* Common code used by vcroak, vdie and vwarner */
1134
e07360fa 1135STATIC void
63315e18
NC
1136S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8)
1137{
97aff369 1138 dVAR;
63315e18
NC
1139 HV *stash;
1140 GV *gv;
1141 CV *cv;
1142 /* sv_2cv might call Perl_croak() */
890ce7af 1143 SV * const olddiehook = PL_diehook;
63315e18
NC
1144
1145 assert(PL_diehook);
1146 ENTER;
1147 SAVESPTR(PL_diehook);
1148 PL_diehook = Nullsv;
1149 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1150 LEAVE;
1151 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1152 dSP;
1153 SV *msg;
1154
1155 ENTER;
1156 save_re_context();
1157 if (message) {
1158 msg = newSVpvn(message, msglen);
1159 SvFLAGS(msg) |= utf8;
1160 SvREADONLY_on(msg);
1161 SAVEFREESV(msg);
1162 }
1163 else {
1164 msg = ERRSV;
1165 }
1166
1167 PUSHSTACKi(PERLSI_DIEHOOK);
1168 PUSHMARK(SP);
1169 XPUSHs(msg);
1170 PUTBACK;
1171 call_sv((SV*)cv, G_DISCARD);
1172 POPSTACK;
1173 LEAVE;
1174 }
1175}
1176
cfd0369c 1177STATIC const char *
e07360fa
AT
1178S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1179 I32* utf8)
1180{
1181 dVAR;
cfd0369c 1182 const char *message;
e07360fa
AT
1183
1184 if (pat) {
890ce7af 1185 SV * const msv = vmess(pat, args);
e07360fa
AT
1186 if (PL_errors && SvCUR(PL_errors)) {
1187 sv_catsv(PL_errors, msv);
cfd0369c 1188 message = SvPV_const(PL_errors, *msglen);
e07360fa
AT
1189 SvCUR_set(PL_errors, 0);
1190 }
1191 else
cfd0369c 1192 message = SvPV_const(msv,*msglen);
e07360fa
AT
1193 *utf8 = SvUTF8(msv);
1194 }
1195 else {
1196 message = Nullch;
1197 }
1198
1199 DEBUG_S(PerlIO_printf(Perl_debug_log,
1200 "%p: die/croak: message = %s\ndiehook = %p\n",
1201 thr, message, PL_diehook));
1202 if (PL_diehook) {
1203 S_vdie_common(aTHX_ message, *msglen, *utf8);
1204 }
1205 return message;
1206}
1207
c5be433b
GS
1208OP *
1209Perl_vdie(pTHX_ const char* pat, va_list *args)
36477c24 1210{
97aff369 1211 dVAR;
73d840c0 1212 const char *message;
e1ec3a88 1213 const int was_in_eval = PL_in_eval;
06bf62c7 1214 STRLEN msglen;
ff882698 1215 I32 utf8 = 0;
36477c24 1216
bf49b057 1217 DEBUG_S(PerlIO_printf(Perl_debug_log,
199100c8 1218 "%p: die: curstack = %p, mainstack = %p\n",
533c011a 1219 thr, PL_curstack, PL_mainstack));
36477c24 1220
890ce7af 1221 message = vdie_croak_common(pat, args, &msglen, &utf8);
36477c24 1222
06bf62c7 1223 PL_restartop = die_where(message, msglen);
ff882698 1224 SvFLAGS(ERRSV) |= utf8;
bf49b057 1225 DEBUG_S(PerlIO_printf(Perl_debug_log,
7c06b590 1226 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
533c011a 1227 thr, PL_restartop, was_in_eval, PL_top_env));
3280af22 1228 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
6224f72b 1229 JMPENV_JUMP(3);
3280af22 1230 return PL_restartop;
36477c24
PP
1231}
1232
c5be433b 1233#if defined(PERL_IMPLICIT_CONTEXT)
cea2e8a9
GS
1234OP *
1235Perl_die_nocontext(const char* pat, ...)
a687059c 1236{
cea2e8a9
GS
1237 dTHX;
1238 OP *o;
a687059c 1239 va_list args;
cea2e8a9 1240 va_start(args, pat);
c5be433b 1241 o = vdie(pat, &args);
cea2e8a9
GS
1242 va_end(args);
1243 return o;
1244}
c5be433b 1245#endif /* PERL_IMPLICIT_CONTEXT */
cea2e8a9
GS
1246
1247OP *
1248Perl_die(pTHX_ const char* pat, ...)
1249{
1250 OP *o;
1251 va_list args;
1252 va_start(args, pat);
c5be433b 1253 o = vdie(pat, &args);
cea2e8a9
GS
1254 va_end(args);
1255 return o;
1256}
1257
c5be433b
GS
1258void
1259Perl_vcroak(pTHX_ const char* pat, va_list *args)
cea2e8a9 1260{
97aff369 1261 dVAR;
73d840c0 1262 const char *message;
06bf62c7 1263 STRLEN msglen;
ff882698 1264 I32 utf8 = 0;
a687059c 1265
3ab1ac99 1266 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
5a844595 1267
3280af22 1268 if (PL_in_eval) {
06bf62c7 1269 PL_restartop = die_where(message, msglen);
ff882698 1270 SvFLAGS(ERRSV) |= utf8;
6224f72b 1271 JMPENV_JUMP(3);
a0d0e21e 1272 }
84414e3e 1273 else if (!message)
cfd0369c 1274 message = SvPVx_const(ERRSV, msglen);
84414e3e 1275
7ff03255 1276 write_to_stderr(message, msglen);
f86702cc 1277 my_failure_exit();
a687059c
LW
1278}
1279
c5be433b 1280#if defined(PERL_IMPLICIT_CONTEXT)
8990e307 1281void
cea2e8a9 1282Perl_croak_nocontext(const char *pat, ...)
a687059c 1283{
cea2e8a9 1284 dTHX;
a687059c 1285 va_list args;
cea2e8a9 1286 va_start(args, pat);
c5be433b 1287 vcroak(pat, &args);
cea2e8a9
GS
1288 /* NOTREACHED */
1289 va_end(args);
1290}
1291#endif /* PERL_IMPLICIT_CONTEXT */
1292
954c1994 1293/*
ccfc67b7
JH
1294=head1 Warning and Dieing
1295
954c1994
GS
1296=for apidoc croak
1297
9983fa3c 1298This is the XSUB-writer's interface to Perl's C<die> function.
966353fd
MF
1299Normally call this function the same way you call the C C<printf>
1300function. Calling C<croak> returns control directly to Perl,
1301sidestepping the normal C order of execution. See C<warn>.
9983fa3c
GS
1302
1303If you want to throw an exception object, assign the object to
1304C<$@> and then pass C<Nullch> to croak():
1305
1306 errsv = get_sv("@", TRUE);
1307 sv_setsv(errsv, exception_object);
1308 croak(Nullch);
954c1994
GS
1309
1310=cut
1311*/
1312
cea2e8a9
GS
1313void
1314Perl_croak(pTHX_ const char *pat, ...)
1315{
1316 va_list args;
1317 va_start(args, pat);
c5be433b 1318 vcroak(pat, &args);
cea2e8a9
GS
1319 /* NOTREACHED */
1320 va_end(args);
1321}
1322
c5be433b
GS
1323void
1324Perl_vwarn(pTHX_ const char* pat, va_list *args)
cea2e8a9 1325{
27da23d5 1326 dVAR;
06bf62c7 1327 STRLEN msglen;
53c1dcc0
AL
1328 SV * const msv = vmess(pat, args);
1329 const I32 utf8 = SvUTF8(msv);
1330 const char * const message = SvPV_const(msv, msglen);
a687059c 1331
3280af22 1332 if (PL_warnhook) {
cea2e8a9 1333 /* sv_2cv might call Perl_warn() */
53c1dcc0
AL
1334 SV * const oldwarnhook = PL_warnhook;
1335 CV * cv;
1336 HV * stash;
1337 GV * gv;
1338
1738f5c4 1339 ENTER;
3280af22
NIS
1340 SAVESPTR(PL_warnhook);
1341 PL_warnhook = Nullsv;
20cec16a 1342 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1738f5c4
CS
1343 LEAVE;
1344 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
20cec16a 1345 dSP;
774d564b
PP
1346 SV *msg;
1347
1348 ENTER;
c5be5b4d
DM
1349 SAVESPTR(PL_warnhook);
1350 PL_warnhook = Nullsv;
3a1f2dc9 1351 save_re_context();
06bf62c7 1352 msg = newSVpvn(message, msglen);
ff882698 1353 SvFLAGS(msg) |= utf8;
774d564b
PP
1354 SvREADONLY_on(msg);
1355 SAVEFREESV(msg);
1356
e788e7d3 1357 PUSHSTACKi(PERLSI_WARNHOOK);
924508f0 1358 PUSHMARK(SP);
774d564b 1359 XPUSHs(msg);
20cec16a 1360 PUTBACK;
864dbfa3 1361 call_sv((SV*)cv, G_DISCARD);
d3acc0f7 1362 POPSTACK;
774d564b 1363 LEAVE;
20cec16a
PP
1364 return;
1365 }
748a9306 1366 }
87582a92 1367
7ff03255 1368 write_to_stderr(message, msglen);
a687059c 1369}
8d063cd8 1370
c5be433b 1371#if defined(PERL_IMPLICIT_CONTEXT)
cea2e8a9
GS
1372void
1373Perl_warn_nocontext(const char *pat, ...)
1374{
1375 dTHX;
1376 va_list args;
1377 va_start(args, pat);
c5be433b 1378 vwarn(pat, &args);
cea2e8a9
GS
1379 va_end(args);
1380}
1381#endif /* PERL_IMPLICIT_CONTEXT */
1382
954c1994
GS
1383/*
1384=for apidoc warn
1385
966353fd
MF
1386This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1387function the same way you call the C C<printf> function. See C<croak>.
954c1994
GS
1388
1389=cut
1390*/
1391
cea2e8a9
GS
1392void
1393Perl_warn(pTHX_ const char *pat, ...)
1394{
1395 va_list args;
1396 va_start(args, pat);
c5be433b 1397 vwarn(pat, &args);
cea2e8a9
GS
1398 va_end(args);
1399}
1400
c5be433b
GS
1401#if defined(PERL_IMPLICIT_CONTEXT)
1402void
1403Perl_warner_nocontext(U32 err, const char *pat, ...)
1404{
27da23d5 1405 dTHX;
c5be433b
GS
1406 va_list args;
1407 va_start(args, pat);
1408 vwarner(err, pat, &args);
1409 va_end(args);
1410}
1411#endif /* PERL_IMPLICIT_CONTEXT */
1412
599cee73 1413void
864dbfa3 1414Perl_warner(pTHX_ U32 err, const char* pat,...)
599cee73
PM
1415{
1416 va_list args;
c5be433b
GS
1417 va_start(args, pat);
1418 vwarner(err, pat, &args);
1419 va_end(args);
1420}
1421
1422void
1423Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1424{
27da23d5 1425 dVAR;
d13b0d77 1426 if (ckDEAD(err)) {
a3b680e6 1427 SV * const msv = vmess(pat, args);
d13b0d77 1428 STRLEN msglen;
7452cf6a 1429 const char * const message = SvPV_const(msv, msglen);
a3b680e6 1430 const I32 utf8 = SvUTF8(msv);
599cee73 1431
3aed30dc 1432 if (PL_diehook) {
63315e18
NC
1433 assert(message);
1434 S_vdie_common(aTHX_ message, msglen, utf8);
3aed30dc
HS
1435 }
1436 if (PL_in_eval) {
1437 PL_restartop = die_where(message, msglen);
ff882698 1438 SvFLAGS(ERRSV) |= utf8;
3aed30dc
HS
1439 JMPENV_JUMP(3);
1440 }
7ff03255 1441 write_to_stderr(message, msglen);
3aed30dc 1442 my_failure_exit();
599cee73
PM
1443 }
1444 else {
d13b0d77 1445 Perl_vwarn(aTHX_ pat, args);
599cee73
PM
1446 }
1447}
1448
f54ba1c2
DM
1449/* implements the ckWARN? macros */
1450
1451bool
1452Perl_ckwarn(pTHX_ U32 w)
1453{
97aff369 1454 dVAR;
f54ba1c2
DM
1455 return
1456 (
1457 isLEXWARN_on
1458 && PL_curcop->cop_warnings != pWARN_NONE
1459 && (
1460 PL_curcop->cop_warnings == pWARN_ALL
1461 || isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1462 || (unpackWARN2(w) &&
1463 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1464 || (unpackWARN3(w) &&
1465 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1466 || (unpackWARN4(w) &&
1467 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1468 )
1469 )
1470 ||
1471 (
1472 isLEXWARN_off && PL_dowarn & G_WARN_ON
1473 )
1474 ;
1475}
1476
1477/* implements the ckWARN?_d macro */
1478
1479bool
1480Perl_ckwarn_d(pTHX_ U32 w)
1481{
97aff369 1482 dVAR;
f54ba1c2
DM
1483 return
1484 isLEXWARN_off
1485 || PL_curcop->cop_warnings == pWARN_ALL
1486 || (
1487 PL_curcop->cop_warnings != pWARN_NONE
1488 && (
1489 isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1490 || (unpackWARN2(w) &&
1491 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1492 || (unpackWARN3(w) &&
1493 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1494 || (unpackWARN4(w) &&
1495 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1496 )
1497 )
1498 ;
1499}
1500
1501
1502
e6587932
DM
1503/* since we've already done strlen() for both nam and val
1504 * we can use that info to make things faster than
1505 * sprintf(s, "%s=%s", nam, val)
1506 */
1507#define my_setenv_format(s, nam, nlen, val, vlen) \
1508 Copy(nam, s, nlen, char); \
1509 *(s+nlen) = '='; \
1510 Copy(val, s+(nlen+1), vlen, char); \
1511 *(s+(nlen+1+vlen)) = '\0'
1512
13b6e58c 1513#ifdef USE_ENVIRON_ARRAY
eccd403f 1514 /* VMS' my_setenv() is in vms.c */
2986a63f 1515#if !defined(WIN32) && !defined(NETWARE)
8d063cd8 1516void
e1ec3a88 1517Perl_my_setenv(pTHX_ const char *nam, const char *val)
8d063cd8 1518{
27da23d5 1519 dVAR;
4efc5df6
GS
1520#ifdef USE_ITHREADS
1521 /* only parent thread can modify process environment */
1522 if (PL_curinterp == aTHX)
1523#endif
1524 {
f2517201 1525#ifndef PERL_USE_SAFE_PUTENV
50acdf95 1526 if (!PL_use_safe_putenv) {
f2517201 1527 /* most putenv()s leak, so we manipulate environ directly */
79072805 1528 register I32 i=setenv_getix(nam); /* where does it go? */
e6587932 1529 int nlen, vlen;
8d063cd8 1530
3280af22 1531 if (environ == PL_origenviron) { /* need we copy environment? */
79072805
LW
1532 I32 j;
1533 I32 max;
fe14fcc3
LW
1534 char **tmpenv;
1535
1536 for (max = i; environ[max]; max++) ;
f2517201
GS
1537 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1538 for (j=0; j<max; j++) { /* copy environment */
e1ec3a88 1539 const int len = strlen(environ[j]);
3aed30dc
HS
1540 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1541 Copy(environ[j], tmpenv[j], len+1, char);
f2517201 1542 }
fe14fcc3
LW
1543 tmpenv[max] = Nullch;
1544 environ = tmpenv; /* tell exec where it is now */
1545 }
a687059c 1546 if (!val) {
f2517201 1547 safesysfree(environ[i]);
a687059c
LW
1548 while (environ[i]) {
1549 environ[i] = environ[i+1];
1550 i++;
1551 }
1552 return;
1553 }
8d063cd8 1554 if (!environ[i]) { /* does not exist yet */
f2517201 1555 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
8d063cd8
LW
1556 environ[i+1] = Nullch; /* make sure it's null terminated */
1557 }
fe14fcc3 1558 else
f2517201 1559 safesysfree(environ[i]);
e6587932
DM
1560 nlen = strlen(nam);
1561 vlen = strlen(val);
f2517201 1562
e6587932
DM
1563 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1564 /* all that work just for this */
1565 my_setenv_format(environ[i], nam, nlen, val, vlen);
50acdf95
MS
1566 } else {
1567# endif
a0fd4948 1568# if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__)
88f5bc07
AB
1569# if defined(HAS_UNSETENV)
1570 if (val == NULL) {
1571 (void)unsetenv(nam);
1572 } else {
1573 (void)setenv(nam, val, 1);
1574 }
1575# else /* ! HAS_UNSETENV */
1576 (void)setenv(nam, val, 1);
1577# endif /* HAS_UNSETENV */
47dafe4d 1578# else
88f5bc07
AB
1579# if defined(HAS_UNSETENV)
1580 if (val == NULL) {
1581 (void)unsetenv(nam);
1582 } else {
c4420975
AL
1583 const int nlen = strlen(nam);
1584 const int vlen = strlen(val);
1585 char * const new_env =
88f5bc07
AB
1586 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1587 my_setenv_format(new_env, nam, nlen, val, vlen);
1588 (void)putenv(new_env);
1589 }
1590# else /* ! HAS_UNSETENV */
1591 char *new_env;
c4420975
AL
1592 const int nlen = strlen(nam);
1593 int vlen;
88f5bc07
AB
1594 if (!val) {
1595 val = "";
1596 }
1597 vlen = strlen(val);
1598 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1599 /* all that work just for this */
1600 my_setenv_format(new_env, nam, nlen, val, vlen);
1601 (void)putenv(new_env);
1602# endif /* HAS_UNSETENV */
47dafe4d 1603# endif /* __CYGWIN__ */
50acdf95
MS
1604#ifndef PERL_USE_SAFE_PUTENV
1605 }
1606#endif
4efc5df6 1607 }
8d063cd8
LW
1608}
1609
2986a63f 1610#else /* WIN32 || NETWARE */
68dc0745
PP
1611
1612void
72229eff 1613Perl_my_setenv(pTHX_ const char *nam, const char *val)
68dc0745 1614{
27da23d5 1615 dVAR;
ac5c734f 1616 register char *envstr;
e1ec3a88
AL
1617 const int nlen = strlen(nam);
1618 int vlen;
e6587932 1619
ac5c734f
GS
1620 if (!val) {
1621 val = "";
1622 }
e6587932 1623 vlen = strlen(val);
a02a5408 1624 Newx(envstr, nlen+vlen+2, char);
e6587932 1625 my_setenv_format(envstr, nam, nlen, val, vlen);
ac5c734f
GS
1626 (void)PerlEnv_putenv(envstr);
1627 Safefree(envstr);
3e3baf6d
TB
1628}
1629
2986a63f 1630#endif /* WIN32 || NETWARE */
3e3baf6d 1631
2f42fcb0 1632#ifndef PERL_MICRO
3e3baf6d 1633I32
e1ec3a88 1634Perl_setenv_getix(pTHX_ const char *nam)
3e3baf6d 1635{
53c1dcc0 1636 register I32 i;
0d46e09a 1637 register const I32 len = strlen(nam);
3e3baf6d
TB
1638
1639 for (i = 0; environ[i]; i++) {
1640 if (
1641#ifdef WIN32
1642 strnicmp(environ[i],nam,len) == 0
1643#else
1644 strnEQ(environ[i],nam,len)
1645#endif
1646 && environ[i][len] == '=')
1647 break; /* strnEQ must come first to avoid */
1648 } /* potential SEGV's */
1649 return i;
68dc0745 1650}
2f42fcb0 1651#endif /* !PERL_MICRO */
68dc0745 1652
ed79a026 1653#endif /* !VMS && !EPOC*/
378cc40b 1654
16d20bd9 1655#ifdef UNLINK_ALL_VERSIONS
79072805 1656I32
6e732051 1657Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
378cc40b 1658{
79072805 1659 I32 i;
378cc40b 1660
6ad3d225 1661 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
378cc40b
LW
1662 return i ? 0 : -1;
1663}
1664#endif
1665
7a3f2258 1666/* this is a drop-in replacement for bcopy() */
2253333f 1667#if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
378cc40b 1668char *
7a3f2258 1669Perl_my_bcopy(register const char *from,register char *to,register I32 len)
378cc40b 1670{
2d03de9c 1671 char * const retval = to;
378cc40b 1672
7c0587c8
LW
1673 if (from - to >= 0) {
1674 while (len--)
1675 *to++ = *from++;
1676 }
1677 else {
1678 to += len;
1679 from += len;
1680 while (len--)
faf8582f 1681 *(--to) = *(--from);
7c0587c8 1682 }
378cc40b
LW
1683 return retval;
1684}
ffed7fef 1685#endif
378cc40b 1686
7a3f2258 1687/* this is a drop-in replacement for memset() */
fc36a67e
PP
1688#ifndef HAS_MEMSET
1689void *
7a3f2258 1690Perl_my_memset(register char *loc, register I32 ch, register I32 len)
fc36a67e 1691{
2d03de9c 1692 char * const retval = loc;
fc36a67e
PP
1693
1694 while (len--)
1695 *loc++ = ch;
1696 return retval;
1697}
1698#endif
1699
7a3f2258 1700/* this is a drop-in replacement for bzero() */
7c0587c8 1701#if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
378cc40b 1702char *
7a3f2258 1703Perl_my_bzero(register char *loc, register I32 len)
378cc40b 1704{
2d03de9c 1705 char * const retval = loc;
378cc40b
LW
1706
1707 while (len--)
1708 *loc++ = 0;
1709 return retval;
1710}
1711#endif
7c0587c8 1712
7a3f2258 1713/* this is a drop-in replacement for memcmp() */
36477c24 1714#if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
79072805 1715I32
7a3f2258 1716Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
7c0587c8 1717{
e1ec3a88
AL
1718 register const U8 *a = (const U8 *)s1;
1719 register const U8 *b = (const U8 *)s2;
79072805 1720 register I32 tmp;
7c0587c8
LW
1721
1722 while (len--) {
27da23d5 1723 if ((tmp = *a++ - *b++))
7c0587c8
LW
1724 return tmp;
1725 }
1726 return 0;
1727}
36477c24 1728#endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
a687059c 1729
fe14fcc3 1730#ifndef HAS_VPRINTF
a687059c 1731
85e6fe83 1732#ifdef USE_CHAR_VSPRINTF
a687059c
LW
1733char *
1734#else
1735int
1736#endif
08105a92 1737vsprintf(char *dest, const char *pat, char *args)
a687059c
LW
1738{
1739 FILE fakebuf;
1740
1741 fakebuf._ptr = dest;
1742 fakebuf._cnt = 32767;
35c8bce7
LW
1743#ifndef _IOSTRG
1744#define _IOSTRG 0
1745#endif
a687059c
LW
1746 fakebuf._flag = _IOWRT|_IOSTRG;
1747 _doprnt(pat, args, &fakebuf); /* what a kludge */
1748 (void)putc('\0', &fakebuf);
85e6fe83 1749#ifdef USE_CHAR_VSPRINTF
a687059c
LW
1750 return(dest);
1751#else
1752 return 0; /* perl doesn't use return value */
1753#endif
1754}
1755
fe14fcc3 1756#endif /* HAS_VPRINTF */
a687059c
LW
1757
1758#ifdef MYSWAP
ffed7fef 1759#if BYTEORDER != 0x4321
a687059c 1760short
864dbfa3 1761Perl_my_swap(pTHX_ short s)
a687059c
LW
1762{
1763#if (BYTEORDER & 1) == 0
1764 short result;
1765
1766 result = ((s & 255) << 8) + ((s >> 8) & 255);
1767 return result;
1768#else
1769 return s;
1770#endif
1771}
1772
1773long
864dbfa3 1774Perl_my_htonl(pTHX_ long l)
a687059c
LW
1775{
1776 union {
1777 long result;
ffed7fef 1778 char c[sizeof(long)];
a687059c
LW
1779 } u;
1780
ffed7fef 1781#if BYTEORDER == 0x1234
a687059c
LW
1782 u.c[0] = (l >> 24) & 255;
1783 u.c[1] = (l >> 16) & 255;
1784 u.c[2] = (l >> 8) & 255;
1785 u.c[3] = l & 255;
1786 return u.result;
1787#else
ffed7fef 1788#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
cea2e8a9 1789 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
a687059c 1790#else
79072805
LW
1791 register I32 o;
1792 register I32 s;
a687059c 1793
ffed7fef
LW
1794 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1795 u.c[o & 0xf] = (l >> s) & 255;
a687059c
LW
1796 }
1797 return u.result;
1798#endif
1799#endif
1800}
1801
1802long
864dbfa3 1803Perl_my_ntohl(pTHX_ long l)
a687059c
LW
1804{
1805 union {
1806 long l;
ffed7fef 1807 char c[sizeof(long)];
a687059c
LW
1808 } u;
1809
ffed7fef 1810#if BYTEORDER == 0x1234
a687059c
LW
1811 u.c[0] = (l >> 24) & 255;
1812 u.c[1] = (l >> 16) & 255;
1813 u.c[2] = (l >> 8) & 255;
1814 u.c[3] = l & 255;
1815 return u.l;
1816#else
ffed7fef 1817#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
cea2e8a9 1818 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
a687059c 1819#else
79072805
LW
1820 register I32 o;
1821 register I32 s;
a687059c
LW
1822
1823 u.l = l;
1824 l = 0;
ffed7fef
LW
1825 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1826 l |= (u.c[o & 0xf] & 255) << s;
a687059c
LW
1827 }
1828 return l;
1829#endif
1830#endif
1831}
1832
ffed7fef 1833#endif /* BYTEORDER != 0x4321 */
988174c1
LW
1834#endif /* MYSWAP */
1835
1836/*
1837 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1838 * If these functions are defined,
1839 * the BYTEORDER is neither 0x1234 nor 0x4321.
1840 * However, this is not assumed.
1841 * -DWS
1842 */
1843
1109a392 1844#define HTOLE(name,type) \
988174c1 1845 type \
ba106d47 1846 name (register type n) \
988174c1
LW
1847 { \
1848 union { \
1849 type value; \
1850 char c[sizeof(type)]; \
1851 } u; \
79072805 1852 register I32 i; \
1109a392
MHM
1853 register I32 s = 0; \
1854 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
988174c1
LW
1855 u.c[i] = (n >> s) & 0xFF; \
1856 } \
1857 return u.value; \
1858 }
1859
1109a392 1860#define LETOH(name,type) \
988174c1 1861 type \
ba106d47 1862 name (register type n) \
988174c1
LW
1863 { \
1864 union { \
1865 type value; \
1866 char c[sizeof(type)]; \
1867 } u; \
79072805 1868 register I32 i; \
1109a392 1869 register I32 s = 0; \
988174c1
LW
1870 u.value = n; \
1871 n = 0; \
1109a392
MHM
1872 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1873 n |= ((type)(u.c[i] & 0xFF)) << s; \
988174c1
LW
1874 } \
1875 return n; \
1876 }
1877
1109a392
MHM
1878/*
1879 * Big-endian byte order functions.
1880 */
1881
1882#define HTOBE(name,type) \
1883 type \
1884 name (register type n) \
1885 { \
1886 union { \
1887 type value; \
1888 char c[sizeof(type)]; \
1889 } u; \
1890 register I32 i; \
1891 register I32 s = 8*(sizeof(u.c)-1); \
1892 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1893 u.c[i] = (n >> s) & 0xFF; \
1894 } \
1895 return u.value; \
1896 }
1897
1898#define BETOH(name,type) \
1899 type \
1900 name (register type n) \
1901 { \
1902 union { \
1903 type value; \
1904 char c[sizeof(type)]; \
1905 } u; \
1906 register I32 i; \
1907 register I32 s = 8*(sizeof(u.c)-1); \
1908 u.value = n; \
1909 n = 0; \
1910 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1911 n |= ((type)(u.c[i] & 0xFF)) << s; \
1912 } \
1913 return n; \
1914 }
1915
1916/*
1917 * If we just can't do it...
1918 */
1919
1920#define NOT_AVAIL(name,type) \
1921 type \
1922 name (register type n) \
1923 { \
1924 Perl_croak_nocontext(#name "() not available"); \
1925 return n; /* not reached */ \
1926 }
1927
1928
988174c1 1929#if defined(HAS_HTOVS) && !defined(htovs)
1109a392 1930HTOLE(htovs,short)
988174c1
LW
1931#endif
1932#if defined(HAS_HTOVL) && !defined(htovl)
1109a392 1933HTOLE(htovl,long)
988174c1
LW
1934#endif
1935#if defined(HAS_VTOHS) && !defined(vtohs)
1109a392 1936LETOH(vtohs,short)
988174c1
LW
1937#endif
1938#if defined(HAS_VTOHL) && !defined(vtohl)
1109a392
MHM
1939LETOH(vtohl,long)
1940#endif
1941
1942#ifdef PERL_NEED_MY_HTOLE16
1943# if U16SIZE == 2
1944HTOLE(Perl_my_htole16,U16)
1945# else
1946NOT_AVAIL(Perl_my_htole16,U16)
1947# endif
1948#endif
1949#ifdef PERL_NEED_MY_LETOH16
1950# if U16SIZE == 2
1951LETOH(Perl_my_letoh16,U16)
1952# else
1953NOT_AVAIL(Perl_my_letoh16,U16)
1954# endif
1955#endif
1956#ifdef PERL_NEED_MY_HTOBE16
1957# if U16SIZE == 2
1958HTOBE(Perl_my_htobe16,U16)
1959# else
1960NOT_AVAIL(Perl_my_htobe16,U16)
1961# endif
1962#endif
1963#ifdef PERL_NEED_MY_BETOH16
1964# if U16SIZE == 2
1965BETOH(Perl_my_betoh16,U16)
1966# else
1967NOT_AVAIL(Perl_my_betoh16,U16)
1968# endif
1969#endif
1970
1971#ifdef PERL_NEED_MY_HTOLE32
1972# if U32SIZE == 4
1973HTOLE(Perl_my_htole32,U32)
1974# else
1975NOT_AVAIL(Perl_my_htole32,U32)
1976# endif
1977#endif
1978#ifdef PERL_NEED_MY_LETOH32
1979# if U32SIZE == 4
1980LETOH(Perl_my_letoh32,U32)
1981# else
1982NOT_AVAIL(Perl_my_letoh32,U32)
1983# endif
1984#endif
1985#ifdef PERL_NEED_MY_HTOBE32
1986# if U32SIZE == 4
1987HTOBE(Perl_my_htobe32,U32)
1988# else
1989NOT_AVAIL(Perl_my_htobe32,U32)
1990# endif
1991#endif
1992#ifdef PERL_NEED_MY_BETOH32
1993# if U32SIZE == 4
1994BETOH(Perl_my_betoh32,U32)
1995# else
1996NOT_AVAIL(Perl_my_betoh32,U32)
1997# endif
1998#endif
1999
2000#ifdef PERL_NEED_MY_HTOLE64
2001# if U64SIZE == 8
2002HTOLE(Perl_my_htole64,U64)
2003# else
2004NOT_AVAIL(Perl_my_htole64,U64)
2005# endif
2006#endif
2007#ifdef PERL_NEED_MY_LETOH64
2008# if U64SIZE == 8
2009LETOH(Perl_my_letoh64,U64)
2010# else
2011NOT_AVAIL(Perl_my_letoh64,U64)
2012# endif
2013#endif
2014#ifdef PERL_NEED_MY_HTOBE64
2015# if U64SIZE == 8
2016HTOBE(Perl_my_htobe64,U64)
2017# else
2018NOT_AVAIL(Perl_my_htobe64,U64)
2019# endif
2020#endif
2021#ifdef PERL_NEED_MY_BETOH64
2022# if U64SIZE == 8
2023BETOH(Perl_my_betoh64,U64)
2024# else
2025NOT_AVAIL(Perl_my_betoh64,U64)
2026# endif
988174c1 2027#endif
a687059c 2028
1109a392
MHM
2029#ifdef PERL_NEED_MY_HTOLES
2030HTOLE(Perl_my_htoles,short)
2031#endif
2032#ifdef PERL_NEED_MY_LETOHS
2033LETOH(Perl_my_letohs,short)
2034#endif
2035#ifdef PERL_NEED_MY_HTOBES
2036HTOBE(Perl_my_htobes,short)
2037#endif
2038#ifdef PERL_NEED_MY_BETOHS
2039BETOH(Perl_my_betohs,short)
2040#endif
2041
2042#ifdef PERL_NEED_MY_HTOLEI
2043HTOLE(Perl_my_htolei,int)
2044#endif
2045#ifdef PERL_NEED_MY_LETOHI
2046LETOH(Perl_my_letohi,int)
2047#endif
2048#ifdef PERL_NEED_MY_HTOBEI
2049HTOBE(Perl_my_htobei,int)
2050#endif
2051#ifdef PERL_NEED_MY_BETOHI
2052BETOH(Perl_my_betohi,int)
2053#endif
2054
2055#ifdef PERL_NEED_MY_HTOLEL
2056HTOLE(Perl_my_htolel,long)
2057#endif
2058#ifdef PERL_NEED_MY_LETOHL
2059LETOH(Perl_my_letohl,long)
2060#endif
2061#ifdef PERL_NEED_MY_HTOBEL
2062HTOBE(Perl_my_htobel,long)
2063#endif
2064#ifdef PERL_NEED_MY_BETOHL
2065BETOH(Perl_my_betohl,long)
2066#endif
2067
2068void
2069Perl_my_swabn(void *ptr, int n)
2070{
2071 register char *s = (char *)ptr;
2072 register char *e = s + (n-1);
2073 register char tc;
2074
2075 for (n /= 2; n > 0; s++, e--, n--) {
2076 tc = *s;
2077 *s = *e;
2078 *e = tc;
2079 }
2080}
2081
4a7d1889
NIS
2082PerlIO *
2083Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
2084{
2986a63f 2085#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
97aff369 2086 dVAR;
1f852d0d
NIS
2087 int p[2];
2088 register I32 This, that;
2089 register Pid_t pid;
2090 SV *sv;
2091 I32 did_pipes = 0;
2092 int pp[2];
2093
2094 PERL_FLUSHALL_FOR_CHILD;
2095 This = (*mode == 'w');
2096 that = !This;
2097 if (PL_tainting) {
2098 taint_env();
2099 taint_proper("Insecure %s%s", "EXEC");
2100 }
2101 if (PerlProc_pipe(p) < 0)
2102 return Nullfp;
2103 /* Try for another pipe pair for error return */
2104 if (PerlProc_pipe(pp) >= 0)
2105 did_pipes = 1;
52e18b1f 2106 while ((pid = PerlProc_fork()) < 0) {
1f852d0d
NIS
2107 if (errno != EAGAIN) {
2108 PerlLIO_close(p[This]);
4e6dfe71 2109 PerlLIO_close(p[that]);
1f852d0d
NIS
2110 if (did_pipes) {
2111 PerlLIO_close(pp[0]);
2112 PerlLIO_close(pp[1]);
2113 }
2114 return Nullfp;
2115 }
2116 sleep(5);
2117 }
2118 if (pid == 0) {
2119 /* Child */
1f852d0d
NIS
2120#undef THIS
2121#undef THAT
2122#define THIS that
2123#define THAT This
1f852d0d
NIS
2124 /* Close parent's end of error status pipe (if any) */
2125 if (did_pipes) {
2126 PerlLIO_close(pp[0]);
2127#if defined(HAS_FCNTL) && defined(F_SETFD)
2128 /* Close error pipe automatically if exec works */
2129 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2130#endif
2131 }
2132 /* Now dup our end of _the_ pipe to right position */
2133 if (p[THIS] != (*mode == 'r')) {
2134 PerlLIO_dup2(p[THIS], *mode == 'r');
2135 PerlLIO_close(p[THIS]);
4e6dfe71
GS
2136 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2137 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
1f852d0d 2138 }
4e6dfe71
GS
2139 else
2140 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
1f852d0d
NIS
2141#if !defined(HAS_FCNTL) || !defined(F_SETFD)
2142 /* No automatic close - do it by hand */
b7953727
JH
2143# ifndef NOFILE
2144# define NOFILE 20
2145# endif
a080fe3d
NIS
2146 {
2147 int fd;
2148
2149 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
3aed30dc 2150 if (fd != pp[1])
a080fe3d
NIS
2151 PerlLIO_close(fd);
2152 }
1f852d0d
NIS
2153 }
2154#endif
2155 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
2156 PerlProc__exit(1);
2157#undef THIS
2158#undef THAT
2159 }
2160 /* Parent */
52e18b1f 2161 do_execfree(); /* free any memory malloced by child on fork */
1f852d0d
NIS
2162 if (did_pipes)
2163 PerlLIO_close(pp[1]);
2164 /* Keep the lower of the two fd numbers */
2165 if (p[that] < p[This]) {
2166 PerlLIO_dup2(p[This], p[that]);
2167 PerlLIO_close(p[This]);
2168 p[This] = p[that];
2169 }
4e6dfe71
GS
2170 else
2171 PerlLIO_close(p[that]); /* close child's end of pipe */
2172
1f852d0d
NIS
2173 LOCK_FDPID_MUTEX;
2174 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2175 UNLOCK_FDPID_MUTEX;
862a34c6 2176 SvUPGRADE(sv,SVt_IV);
45977657 2177 SvIV_set(sv, pid);
1f852d0d
NIS
2178 PL_forkprocess = pid;
2179 /* If we managed to get status pipe check for exec fail */
2180 if (did_pipes && pid > 0) {
2181 int errkid;
2182 int n = 0, n1;
2183
2184 while (n < sizeof(int)) {
2185 n1 = PerlLIO_read(pp[0],
2186 (void*)(((char*)&errkid)+n),
2187 (sizeof(int)) - n);
2188 if (n1 <= 0)
2189 break;
2190 n += n1;
2191 }
2192 PerlLIO_close(pp[0]);
2193 did_pipes = 0;
2194 if (n) { /* Error */
2195 int pid2, status;
8c51524e 2196 PerlLIO_close(p[This]);
1f852d0d
NIS
2197 if (n != sizeof(int))
2198 Perl_croak(aTHX_ "panic: kid popen errno read");
2199 do {
2200 pid2 = wait4pid(pid, &status, 0);
2201 } while (pid2 == -1 && errno == EINTR);
2202 errno = errkid; /* Propagate errno from kid */
2203 return Nullfp;
2204 }
2205 }
2206 if (did_pipes)
2207 PerlLIO_close(pp[0]);
2208 return PerlIO_fdopen(p[This], mode);
2209#else
4a7d1889
NIS
2210 Perl_croak(aTHX_ "List form of piped open not implemented");
2211 return (PerlIO *) NULL;
1f852d0d 2212#endif
4a7d1889
NIS
2213}
2214
5f05dabc 2215 /* VMS' my_popen() is in VMS.c, same with OS/2. */
cd39f2b6 2216#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
760ac839 2217PerlIO *
3dd43144 2218Perl_my_popen(pTHX_ const char *cmd, const char *mode)
a687059c 2219{
97aff369 2220 dVAR;
a687059c 2221 int p[2];
8ac85365 2222 register I32 This, that;
d8a83dd3 2223 register Pid_t pid;
79072805 2224 SV *sv;
bfce84ec 2225 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
e446cec8
IZ
2226 I32 did_pipes = 0;
2227 int pp[2];
a687059c 2228
45bc9206 2229 PERL_FLUSHALL_FOR_CHILD;
ddcf38b7
IZ
2230#ifdef OS2
2231 if (doexec) {
23da6c43 2232 return my_syspopen(aTHX_ cmd,mode);
ddcf38b7 2233 }
a1d180c4 2234#endif
8ac85365
NIS
2235 This = (*mode == 'w');
2236 that = !This;
3280af22 2237 if (doexec && PL_tainting) {
bbce6d69
PP
2238 taint_env();
2239 taint_proper("Insecure %s%s", "EXEC");
d48672a2 2240 }
c2267164
IZ
2241 if (PerlProc_pipe(p) < 0)
2242 return Nullfp;
e446cec8
IZ
2243 if (doexec && PerlProc_pipe(pp) >= 0)
2244 did_pipes = 1;
52e18b1f 2245 while ((pid = PerlProc_fork()) < 0) {
a687059c 2246 if (errno != EAGAIN) {
6ad3d225 2247 PerlLIO_close(p[This]);
b5ac89c3 2248 PerlLIO_close(p[that]);
e446cec8
IZ
2249 if (did_pipes) {
2250 PerlLIO_close(pp[0]);
2251 PerlLIO_close(pp[1]);
2252 }
a687059c 2253 if (!doexec)
cea2e8a9 2254 Perl_croak(aTHX_ "Can't fork");
a687059c
LW
2255 return Nullfp;
2256 }
2257 sleep(5);
2258 }
2259 if (pid == 0) {
79072805
LW
2260 GV* tmpgv;
2261
30ac6d9b
GS
2262#undef THIS
2263#undef THAT
a687059c 2264#define THIS that
8ac85365 2265#define THAT This
e446cec8
IZ
2266 if (did_pipes) {
2267 PerlLIO_close(pp[0]);
2268#if defined(HAS_FCNTL) && defined(F_SETFD)
2269 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2270#endif
2271 }
a687059c 2272 if (p[THIS] != (*mode == 'r')) {
6ad3d225
GS
2273 PerlLIO_dup2(p[THIS], *mode == 'r');
2274 PerlLIO_close(p[THIS]);
b5ac89c3
NIS
2275 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2276 PerlLIO_close(p[THAT]);
a687059c 2277 }
b5ac89c3
NIS
2278 else
2279 PerlLIO_close(p[THAT]);
4435c477 2280#ifndef OS2
a687059c 2281 if (doexec) {
a0d0e21e 2282#if !defined(HAS_FCNTL) || !defined(F_SETFD)
ae986130
LW
2283#ifndef NOFILE
2284#define NOFILE 20
2285#endif
a080fe3d 2286 {
3aed30dc 2287 int fd;
a080fe3d
NIS
2288
2289 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2290 if (fd != pp[1])
3aed30dc 2291 PerlLIO_close(fd);
a080fe3d 2292 }
ae986130 2293#endif
a080fe3d
NIS
2294 /* may or may not use the shell */
2295 do_exec3(cmd, pp[1], did_pipes);
6ad3d225 2296 PerlProc__exit(1);
a687059c 2297 }
4435c477 2298#endif /* defined OS2 */
306196c3 2299 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
4d76a344 2300 SvREADONLY_off(GvSV(tmpgv));
7766f137 2301 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
4d76a344
RGS
2302 SvREADONLY_on(GvSV(tmpgv));
2303 }
2304#ifdef THREADS_HAVE_PIDS
2305 PL_ppid = (IV)getppid();
2306#endif
3280af22 2307 PL_forkprocess = 0;
ca0c25f6 2308#ifdef PERL_USES_PL_PIDSTATUS
3280af22 2309 hv_clear(PL_pidstatus); /* we have no children */
ca0c25f6 2310#endif
a687059c
LW
2311 return Nullfp;
2312#undef THIS
2313#undef THAT
2314 }
b5ac89c3 2315 do_execfree(); /* free any memory malloced by child on vfork */
e446cec8
IZ
2316 if (did_pipes)
2317 PerlLIO_close(pp[1]);
8ac85365 2318 if (p[that] < p[This]) {
6ad3d225
GS
2319 PerlLIO_dup2(p[This], p[that]);
2320 PerlLIO_close(p[This]);
8ac85365 2321 p[This] = p[that];
62b28dd9 2322 }
b5ac89c3
NIS
2323 else
2324 PerlLIO_close(p[that]);
2325
4755096e 2326 LOCK_FDPID_MUTEX;
3280af22 2327 sv = *av_fetch(PL_fdpid,p[This],TRUE);
4755096e 2328 UNLOCK_FDPID_MUTEX;
862a34c6 2329 SvUPGRADE(sv,SVt_IV);
45977657 2330 SvIV_set(sv, pid);
3280af22 2331 PL_forkprocess = pid;
e446cec8
IZ
2332 if (did_pipes && pid > 0) {
2333 int errkid;
2334 int n = 0, n1;
2335
2336 while (n < sizeof(int)) {
2337 n1 = PerlLIO_read(pp[0],
2338 (void*)(((char*)&errkid)+n),
2339 (sizeof(int)) - n);
2340 if (n1 <= 0)
2341 break;
2342 n += n1;
2343 }
2f96c702
IZ
2344 PerlLIO_close(pp[0]);
2345 did_pipes = 0;
e446cec8 2346 if (n) { /* Error */
faa466a7 2347 int pid2, status;
8c51524e 2348 PerlLIO_close(p[This]);
e446cec8 2349 if (n != sizeof(int))
cea2e8a9 2350 Perl_croak(aTHX_ "panic: kid popen errno read");
faa466a7
RG
2351 do {
2352 pid2 = wait4pid(pid, &status, 0);
2353 } while (pid2 == -1 && errno == EINTR);
e446cec8
IZ
2354 errno = errkid; /* Propagate errno from kid */
2355 return Nullfp;
2356 }
2357 }
2358 if (did_pipes)
2359 PerlLIO_close(pp[0]);
8ac85365 2360 return PerlIO_fdopen(p[This], mode);
a687059c 2361}
7c0587c8 2362#else
85ca448a 2363#if defined(atarist) || defined(EPOC)
7c0587c8 2364FILE *popen();
760ac839 2365PerlIO *
864dbfa3 2366Perl_my_popen(pTHX_ char *cmd, char *mode)
7c0587c8 2367{
45bc9206 2368 PERL_FLUSHALL_FOR_CHILD;
a1d180c4
NIS
2369 /* Call system's popen() to get a FILE *, then import it.
2370 used 0 for 2nd parameter to PerlIO_importFILE;
2371 apparently not used
2372 */
2373 return PerlIO_importFILE(popen(cmd, mode), 0);
7c0587c8 2374}
2b96b0a5
JH
2375#else
2376#if defined(DJGPP)
2377FILE *djgpp_popen();
2378PerlIO *
2379Perl_my_popen(pTHX_ char *cmd, char *mode)
2380{
2381 PERL_FLUSHALL_FOR_CHILD;
2382 /* Call system's popen() to get a FILE *, then import it.
2383 used 0 for 2nd parameter to PerlIO_importFILE;
2384 apparently not used
2385 */
2386 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2387}
2388#endif
7c0587c8
LW
2389#endif
2390
2391#endif /* !DOSISH */
a687059c 2392
52e18b1f
GS
2393/* this is called in parent before the fork() */
2394void
2395Perl_atfork_lock(void)
2396{
27da23d5 2397 dVAR;
3db8f154 2398#if defined(USE_ITHREADS)
52e18b1f
GS
2399 /* locks must be held in locking order (if any) */
2400# ifdef MYMALLOC
2401 MUTEX_LOCK(&PL_malloc_mutex);
2402# endif
2403 OP_REFCNT_LOCK;
2404#endif
2405}
2406
2407/* this is called in both parent and child after the fork() */
2408void
2409Perl_atfork_unlock(void)
2410{
27da23d5 2411 dVAR;
3db8f154 2412#if defined(USE_ITHREADS)
52e18b1f
GS
2413 /* locks must be released in same order as in atfork_lock() */
2414# ifdef MYMALLOC
2415 MUTEX_UNLOCK(&PL_malloc_mutex);
2416# endif
2417 OP_REFCNT_UNLOCK;
2418#endif
2419}
2420
2421Pid_t
2422Perl_my_fork(void)
2423{
2424#if defined(HAS_FORK)
2425 Pid_t pid;
3db8f154 2426#if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
52e18b1f
GS
2427 atfork_lock();
2428 pid = fork();
2429 atfork_unlock();
2430#else
2431 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2432 * handlers elsewhere in the code */
2433 pid = fork();
2434#endif
2435 return pid;
2436#else
2437 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2438 Perl_croak_nocontext("fork() not available");
b961a566 2439 return 0;
52e18b1f
GS
2440#endif /* HAS_FORK */
2441}
2442
748a9306 2443#ifdef DUMP_FDS
35ff7856 2444void
864dbfa3 2445Perl_dump_fds(pTHX_ char *s)
ae986130
LW
2446{
2447 int fd;
c623ac67 2448 Stat_t tmpstatbuf;
ae986130 2449
bf49b057 2450 PerlIO_printf(Perl_debug_log,"%s", s);
ae986130 2451 for (fd = 0; fd < 32; fd++) {
6ad3d225 2452 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
bf49b057 2453 PerlIO_printf(Perl_debug_log," %d",fd);
ae986130 2454 }
bf49b057 2455 PerlIO_printf(Perl_debug_log,"\n");
27da23d5 2456 return;
ae986130 2457}
35ff7856 2458#endif /* DUMP_FDS */
ae986130 2459
fe14fcc3 2460#ifndef HAS_DUP2
fec02dd3 2461int
ba106d47 2462dup2(int oldfd, int newfd)
a687059c 2463{
a0d0e21e 2464#if defined(HAS_FCNTL) && defined(F_DUPFD)
fec02dd3
AD
2465 if (oldfd == newfd)
2466 return oldfd;
6ad3d225 2467 PerlLIO_close(newfd);
fec02dd3 2468 return fcntl(oldfd, F_DUPFD, newfd);
62b28dd9 2469#else
fc36a67e
PP
2470#define DUP2_MAX_FDS 256
2471 int fdtmp[DUP2_MAX_FDS];
79072805 2472 I32 fdx = 0;
ae986130
LW
2473 int fd;
2474
fe14fcc3 2475 if (oldfd == newfd)
fec02dd3 2476 return oldfd;
6ad3d225 2477 PerlLIO_close(newfd);
fc36a67e 2478 /* good enough for low fd's... */
6ad3d225 2479 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
fc36a67e 2480 if (fdx >= DUP2_MAX_FDS) {
6ad3d225 2481 PerlLIO_close(fd);
fc36a67e
PP
2482 fd = -1;
2483 break;
2484 }
ae986130 2485 fdtmp[fdx++] = fd;
fc36a67e 2486 }
ae986130 2487 while (fdx > 0)
6ad3d225 2488 PerlLIO_close(fdtmp[--fdx]);
fec02dd3 2489 return fd;
62b28dd9 2490#endif
a687059c
LW
2491}
2492#endif
2493
64ca3a65 2494#ifndef PERL_MICRO
ff68c719
PP
2495#ifdef HAS_SIGACTION
2496
abea2c45
HS
2497#ifdef MACOS_TRADITIONAL
2498/* We don't want restart behavior on MacOS */
2499#undef SA_RESTART
2500#endif
2501
ff68c719 2502Sighandler_t
864dbfa3 2503Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
ff68c719 2504{
27da23d5 2505 dVAR;
ff68c719
PP
2506 struct sigaction act, oact;
2507
a10b1e10
JH
2508#ifdef USE_ITHREADS
2509 /* only "parent" interpreter can diddle signals */
2510 if (PL_curinterp != aTHX)
8aad04aa 2511 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
2512#endif
2513
8aad04aa 2514 act.sa_handler = (void(*)(int))handler;
ff68c719
PP
2515 sigemptyset(&act.sa_mask);
2516 act.sa_flags = 0;
2517#ifdef SA_RESTART
4ffa73a3
JH
2518 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2519 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
0a8e0eff 2520#endif
358837b8 2521#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
8aad04aa 2522 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
85264bed
CS
2523 act.sa_flags |= SA_NOCLDWAIT;
2524#endif
ff68c719 2525 if (sigaction(signo, &act, &oact) == -1)
8aad04aa 2526 return (Sighandler_t) SIG_ERR;
ff68c719 2527 else
8aad04aa 2528 return (Sighandler_t) oact.sa_handler;
ff68c719
PP
2529}
2530
2531Sighandler_t
864dbfa3 2532Perl_rsignal_state(pTHX_ int signo)
ff68c719
PP
2533{
2534 struct sigaction oact;
2535
2536 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
8aad04aa 2537 return (Sighandler_t) SIG_ERR;
ff68c719 2538 else
8aad04aa 2539 return (Sighandler_t) oact.sa_handler;
ff68c719
PP
2540}
2541
2542int
864dbfa3 2543Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
ff68c719 2544{
27da23d5 2545 dVAR;
ff68c719
PP
2546 struct sigaction act;
2547
a10b1e10
JH
2548#ifdef USE_ITHREADS
2549 /* only "parent" interpreter can diddle signals */
2550 if (PL_curinterp != aTHX)
2551 return -1;
2552#endif
2553
8aad04aa 2554 act.sa_handler = (void(*)(int))handler;
ff68c719
PP
2555 sigemptyset(&act.sa_mask);
2556 act.sa_flags = 0;
2557#ifdef SA_RESTART
4ffa73a3
JH
2558 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2559 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
0a8e0eff 2560#endif
36b5d377 2561#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
8aad04aa 2562 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
85264bed
CS
2563 act.sa_flags |= SA_NOCLDWAIT;
2564#endif
ff68c719
PP
2565 return sigaction(signo, &act, save);
2566}
2567
2568int
864dbfa3 2569Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
ff68c719 2570{
27da23d5 2571 dVAR;
a10b1e10
JH
2572#ifdef USE_ITHREADS
2573 /* only "parent" interpreter can diddle signals */
2574 if (PL_curinterp != aTHX)
2575 return -1;
2576#endif
2577
ff68c719
PP
2578 return sigaction(signo, save, (struct sigaction *)NULL);
2579}
2580
2581#else /* !HAS_SIGACTION */
2582
2583Sighandler_t
864dbfa3 2584Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
ff68c719 2585{
39f1703b 2586#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
2587 /* only "parent" interpreter can diddle signals */
2588 if (PL_curinterp != aTHX)
8aad04aa 2589 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
2590#endif
2591
6ad3d225 2592 return PerlProc_signal(signo, handler);
ff68c719
PP
2593}
2594
fabdb6c0 2595static Signal_t
4e35701f 2596sig_trap(int signo)
ff68c719 2597{
27da23d5
JH
2598 dVAR;
2599 PL_sig_trapped++;
ff68c719
PP
2600}
2601
2602Sighandler_t
864dbfa3 2603Perl_rsignal_state(pTHX_ int signo)
ff68c719 2604{
27da23d5 2605 dVAR;
ff68c719
PP
2606 Sighandler_t oldsig;
2607
39f1703b 2608#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
2609 /* only "parent" interpreter can diddle signals */
2610 if (PL_curinterp != aTHX)
8aad04aa 2611 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
2612#endif
2613
27da23d5 2614 PL_sig_trapped = 0;
6ad3d225
GS
2615 oldsig = PerlProc_signal(signo, sig_trap);
2616 PerlProc_signal(signo, oldsig);
27da23d5 2617 if (PL_sig_trapped)
3aed30dc 2618 PerlProc_kill(PerlProc_getpid(), signo);
ff68c719
PP
2619 return oldsig;
2620}
2621
2622int
864dbfa3 2623Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
ff68c719 2624{
39f1703b 2625#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
2626 /* only "parent" interpreter can diddle signals */
2627 if (PL_curinterp != aTHX)
2628 return -1;
2629#endif
6ad3d225 2630 *save = PerlProc_signal(signo, handler);
8aad04aa 2631 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
ff68c719
PP
2632}
2633
2634int
864dbfa3 2635Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
ff68c719 2636{
39f1703b 2637#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
2638 /* only "parent" interpreter can diddle signals */
2639 if (PL_curinterp != aTHX)
2640 return -1;
2641#endif
8aad04aa 2642 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
ff68c719
PP
2643}
2644
2645#endif /* !HAS_SIGACTION */
64ca3a65 2646#endif /* !PERL_MICRO */
ff68c719 2647
5f05dabc 2648 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
cd39f2b6 2649#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
79072805 2650I32
864dbfa3 2651Perl_my_pclose(pTHX_ PerlIO *ptr)
a687059c 2652{
97aff369 2653 dVAR;
ff68c719 2654 Sigsave_t hstat, istat, qstat;
a687059c 2655 int status;
a0d0e21e 2656 SV **svp;
d8a83dd3
JH
2657 Pid_t pid;
2658 Pid_t pid2;
03136e13 2659 bool close_failed;
b7953727 2660 int saved_errno = 0;
22fae026
TM
2661#ifdef WIN32
2662 int saved_win32_errno;
2663#endif
a687059c 2664
4755096e 2665 LOCK_FDPID_MUTEX;
3280af22 2666 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
4755096e 2667 UNLOCK_FDPID_MUTEX;
25d92023 2668 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
a0d0e21e 2669 SvREFCNT_dec(*svp);
3280af22 2670 *svp = &PL_sv_undef;
ddcf38b7
IZ
2671#ifdef OS2
2672 if (pid == -1) { /* Opened by popen. */
2673 return my_syspclose(ptr);
2674 }
a1d180c4 2675#endif
03136e13
CS
2676 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2677 saved_errno = errno;
22fae026
TM
2678#ifdef WIN32
2679 saved_win32_errno = GetLastError();
2680#endif
03136e13 2681 }
7c0587c8 2682#ifdef UTS
6ad3d225 2683 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
7c0587c8 2684#endif
64ca3a65 2685#ifndef PERL_MICRO
8aad04aa
JH
2686 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
2687 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
2688 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
64ca3a65 2689#endif
748a9306 2690 do {
1d3434b8
GS
2691 pid2 = wait4pid(pid, &status, 0);
2692 } while (pid2 == -1 && errno == EINTR);
64ca3a65 2693#ifndef PERL_MICRO
ff68c719
PP
2694 rsignal_restore(SIGHUP, &hstat);
2695 rsignal_restore(SIGINT, &istat);
2696 rsignal_restore(SIGQUIT, &qstat);
64ca3a65 2697#endif
03136e13 2698 if (close_failed) {
ce6e1103 2699 SETERRNO(saved_errno, 0);
03136e13
CS
2700 return -1;
2701 }
1d3434b8 2702 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
20188a90 2703}
4633a7c4
LW
2704#endif /* !DOSISH */
2705
2986a63f 2706#if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
79072805 2707I32
d8a83dd3 2708Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
20188a90 2709{
97aff369 2710 dVAR;
27da23d5 2711 I32 result = 0;
b7953727
JH
2712 if (!pid)
2713 return -1;
ca0c25f6 2714#ifdef PERL_USES_PL_PIDSTATUS
b7953727 2715 {
3aed30dc 2716 if (pid > 0) {
12072db5
NC
2717 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2718 pid, rather than a string form. */
c4420975 2719 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3aed30dc
HS
2720 if (svp && *svp != &PL_sv_undef) {
2721 *statusp = SvIVX(*svp);
12072db5
NC
2722 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2723 G_DISCARD);
3aed30dc
HS
2724 return pid;
2725 }
2726 }
2727 else {
2728 HE *entry;
2729
2730 hv_iterinit(PL_pidstatus);
2731 if ((entry = hv_iternext(PL_pidstatus))) {
c4420975 2732 SV * const sv = hv_iterval(PL_pidstatus,entry);
7ea75b61 2733 I32 len;
0bcc34c2 2734 const char * const spid = hv_iterkey(entry,&len);
27da23d5 2735
12072db5
NC
2736 assert (len == sizeof(Pid_t));
2737 memcpy((char *)&pid, spid, len);
3aed30dc 2738 *statusp = SvIVX(sv);
7b9a3241
NC
2739 /* The hash iterator is currently on this entry, so simply
2740 calling hv_delete would trigger the lazy delete, which on
2741 aggregate does more work, beacuse next call to hv_iterinit()
2742 would spot the flag, and have to call the delete routine,
2743 while in the meantime any new entries can't re-use that
2744 memory. */
2745 hv_iterinit(PL_pidstatus);
7ea75b61 2746 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3aed30dc
HS
2747 return pid;
2748 }
20188a90
LW
2749 }
2750 }
68a29c53 2751#endif
79072805 2752#ifdef HAS_WAITPID
367f3c24
IZ
2753# ifdef HAS_WAITPID_RUNTIME
2754 if (!HAS_WAITPID_RUNTIME)
2755 goto hard_way;
2756# endif
cddd4526 2757 result = PerlProc_waitpid(pid,statusp,flags);
dfcfdb64 2758 goto finish;
367f3c24
IZ
2759#endif
2760#if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
cddd4526 2761 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
dfcfdb64 2762 goto finish;
367f3c24 2763#endif
ca0c25f6 2764#ifdef PERL_USES_PL_PIDSTATUS
27da23d5 2765#if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
367f3c24 2766 hard_way:
27da23d5 2767#endif
a0d0e21e 2768 {
a0d0e21e 2769 if (flags)
cea2e8a9 2770 Perl_croak(aTHX_ "Can't do waitpid with flags");
a0d0e21e 2771 else {
76e3520e 2772 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
a0d0e21e
LW
2773 pidgone(result,*statusp);
2774 if (result < 0)
2775 *statusp = -1;
2776 }
a687059c
LW
2777 }
2778#endif
27da23d5 2779#if defined(HAS_WAITPID) || defined(HAS_WAIT4)
dfcfdb64 2780 finish:
27da23d5 2781#endif
cddd4526
NIS
2782 if (result < 0 && errno == EINTR) {
2783 PERL_ASYNC_CHECK();
2784 }
2785 return result;
a687059c 2786}
2986a63f 2787#endif /* !DOSISH || OS2 || WIN32 || NETWARE */
a687059c 2788
ca0c25f6 2789#ifdef PERL_USES_PL_PIDSTATUS
7c0587c8 2790void
d8a83dd3 2791Perl_pidgone(pTHX_ Pid_t pid, int status)
a687059c 2792{
79072805 2793 register SV *sv;
a687059c 2794
12072db5 2795 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
862a34c6 2796 SvUPGRADE(sv,SVt_IV);
45977657 2797 SvIV_set(sv, status);
20188a90 2798 return;
a687059c 2799}
ca0c25f6 2800#endif
a687059c 2801
85ca448a 2802#if defined(atarist) || defined(OS2) || defined(EPOC)
7c0587c8 2803int pclose();
ddcf38b7
IZ
2804#ifdef HAS_FORK
2805int /* Cannot prototype with I32
2806 in os2ish.h. */
ba106d47 2807my_syspclose(PerlIO *ptr)
ddcf38b7 2808#else
79072805 2809I32
864dbfa3 2810Perl_my_pclose(pTHX_ PerlIO *ptr)
a1d180c4 2811#endif
a687059c 2812{
760ac839 2813 /* Needs work for PerlIO ! */
c4420975 2814 FILE * const f = PerlIO_findFILE(ptr);
7452cf6a 2815 const I32 result = pclose(f);
2b96b0a5
JH
2816 PerlIO_releaseFILE(ptr,f);
2817 return result;
2818}
2819#endif
2820
933fea7f 2821#if defined(DJGPP)
2b96b0a5
JH
2822int djgpp_pclose();
2823I32
2824Perl_my_pclose(pTHX_ PerlIO *ptr)
2825{
2826 /* Needs work for PerlIO ! */
c4420975 2827 FILE * const f = PerlIO_findFILE(ptr);
2b96b0a5 2828 I32 result = djgpp_pclose(f);
933fea7f 2829 result = (result << 8) & 0xff00;
760ac839
LW
2830 PerlIO_releaseFILE(ptr,f);
2831 return result;
a687059c 2832}
7c0587c8 2833#endif
9f68db38
LW
2834
2835void
864dbfa3 2836Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
9f68db38 2837{
79072805 2838 register I32 todo;
c4420975 2839 register const char * const frombase = from;
9f68db38
LW
2840
2841 if (len == 1) {
08105a92 2842 register const char c = *from;
9f68db38 2843 while (count-- > 0)
5926133d 2844 *to++ = c;
9f68db38
LW
2845 return;
2846 }
2847 while (count-- > 0) {
2848 for (todo = len; todo > 0; todo--) {
2849 *to++ = *from++;
2850 }
2851 from = frombase;
2852 }
2853}
0f85fab0 2854
fe14fcc3 2855#ifndef HAS_RENAME
79072805 2856I32
4373e329 2857Perl_same_dirent(pTHX_ const char *a, const char *b)
62b28dd9 2858{
93a17b20
LW
2859 char *fa = strrchr(a,'/');
2860 char *fb = strrchr(b,'/');
c623ac67
GS
2861 Stat_t tmpstatbuf1;
2862 Stat_t tmpstatbuf2;
c4420975 2863 SV * const tmpsv = sv_newmortal();
62b28dd9
LW
2864
2865 if (fa)
2866 fa++;
2867 else
2868 fa = a;
2869 if (fb)
2870 fb++;
2871 else
2872 fb = b;
2873 if (strNE(a,b))
2874 return FALSE;
2875 if (fa == a)
616d8c9c 2876 sv_setpvn(tmpsv, ".", 1);
62b28dd9 2877 else
46fc3d4c 2878 sv_setpvn(tmpsv, a, fa - a);
95a20fc0 2879 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
62b28dd9
LW
2880 return FALSE;
2881 if (fb == b)
616d8c9c 2882 sv_setpvn(tmpsv, ".", 1);
62b28dd9 2883 else
46fc3d4c 2884 sv_setpvn(tmpsv, b, fb - b);
95a20fc0 2885 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
62b28dd9
LW
2886 return FALSE;
2887 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2888 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2889}
fe14fcc3
LW
2890#endif /* !HAS_RENAME */
2891
491527d0 2892char*
7f315aed
NC
2893Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
2894 const char *const *const search_ext, I32 flags)
491527d0 2895{
97aff369 2896 dVAR;
e1ec3a88 2897 const char *xfound = Nullch;
491527d0 2898 char *xfailed = Nullch;
0f31cffe 2899 char tmpbuf[MAXPATHLEN];
491527d0 2900 register char *s;
5f74f29c 2901 I32 len = 0;
491527d0
GS
2902 int retval;
2903#if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2904# define SEARCH_EXTS ".bat", ".cmd", NULL
2905# define MAX_EXT_LEN 4
2906#endif
2907#ifdef OS2
2908# define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2909# define MAX_EXT_LEN 4
2910#endif
2911#ifdef VMS
2912# define SEARCH_EXTS ".pl", ".com", NULL
2913# define MAX_EXT_LEN 4
2914#endif
2915 /* additional extensions to try in each dir if scriptname not found */
2916#ifdef SEARCH_EXTS
0bcc34c2 2917 static const char *const exts[] = { SEARCH_EXTS };
7f315aed 2918 const char *const *const ext = search_ext ? search_ext : exts;
491527d0 2919 int extidx = 0, i = 0;
e1ec3a88 2920 const char *curext = Nullch;
491527d0 2921#else
53c1dcc0 2922 PERL_UNUSED_ARG(search_ext);
491527d0
GS
2923# define MAX_EXT_LEN 0
2924#endif
2925
2926 /*
2927 * If dosearch is true and if scriptname does not contain path
2928 * delimiters, search the PATH for scriptname.
2929 *
2930 * If SEARCH_EXTS is also defined, will look for each
2931 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2932 * while searching the PATH.
2933 *
2934 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2935 * proceeds as follows:
2936 * If DOSISH or VMSISH:
2937 * + look for ./scriptname{,.foo,.bar}
2938 * + search the PATH for scriptname{,.foo,.bar}
2939 *
2940 * If !DOSISH:
2941 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2942 * this will not look in '.' if it's not in the PATH)
2943 */
84486fc6 2944 tmpbuf[0] = '\0';
491527d0
GS
2945
2946#ifdef VMS
2947# ifdef ALWAYS_DEFTYPES
2948 len = strlen(scriptname);
2949 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
c4420975 2950 int idx = 0, deftypes = 1;
491527d0
GS
2951 bool seen_dot = 1;
2952
c4420975 2953 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch);
491527d0
GS
2954# else
2955 if (dosearch) {
c4420975 2956 int idx = 0, deftypes = 1;
491527d0
GS
2957 bool seen_dot = 1;
2958
c4420975 2959 const int hasdir = (strpbrk(scriptname,":[</") != Nullch);
491527d0
GS
2960# endif
2961 /* The first time through, just add SEARCH_EXTS to whatever we
2962 * already have, so we can check for default file types. */
2963 while (deftypes ||
84486fc6 2964 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
491527d0
GS
2965 {
2966 if (deftypes) {
2967 deftypes = 0;
84486fc6 2968 *tmpbuf = '\0';
491527d0 2969 }
84486fc6
GS
2970 if ((strlen(tmpbuf) + strlen(scriptname)
2971 + MAX_EXT_LEN) >= sizeof tmpbuf)
491527d0 2972 continue; /* don't search dir with too-long name */
84486fc6 2973 strcat(tmpbuf, scriptname);
491527d0
GS
2974#else /* !VMS */
2975
2976#ifdef DOSISH
2977 if (strEQ(scriptname, "-"))
2978 dosearch = 0;
2979 if (dosearch) { /* Look in '.' first. */
fe2774ed 2980 const char *cur = scriptname;
491527d0
GS
2981#ifdef SEARCH_EXTS
2982 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2983 while (ext[i])
2984 if (strEQ(ext[i++],curext)) {
2985 extidx = -1; /* already has an ext */
2986 break;
2987 }
2988 do {
2989#endif
2990 DEBUG_p(PerlIO_printf(Perl_debug_log,
2991 "Looking for %s\n",cur));
017f25f1
IZ
2992 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2993 && !S_ISDIR(PL_statbuf.st_mode)) {
491527d0
GS
2994 dosearch = 0;
2995 scriptname = cur;
2996#ifdef SEARCH_EXTS
2997 break;
2998#endif
2999 }
3000#ifdef SEARCH_EXTS
3001 if (cur == scriptname) {
3002 len = strlen(scriptname);
84486fc6 3003 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
491527d0 3004 break;
490a0e98 3005 /* FIXME? Convert to memcpy */
84486fc6 3006 cur = strcpy(tmpbuf, scriptname);
491527d0
GS
3007 }
3008 } while (extidx >= 0 && ext[extidx] /* try an extension? */
84486fc6 3009 && strcpy(tmpbuf+len, ext[extidx++]));
491527d0
GS
3010#endif
3011 }
3012#endif
3013
cd39f2b6
JH
3014#ifdef MACOS_TRADITIONAL
3015 if (dosearch && !strchr(scriptname, ':') &&
3016 (s = PerlEnv_getenv("Commands")))
3017#else
491527d0
GS
3018 if (dosearch && !strchr(scriptname, '/')
3019#ifdef DOSISH
3020 && !strchr(scriptname, '\\')
3021#endif
cd39f2b6
JH
3022 && (s = PerlEnv_getenv("PATH")))
3023#endif
3024 {
491527d0 3025 bool seen_dot = 0;
92f0c265 3026
3280af22
NIS
3027 PL_bufend = s + strlen(s);
3028 while (s < PL_bufend) {
cd39f2b6
JH
3029#ifdef MACOS_TRADITIONAL
3030 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3031 ',',
3032 &len);
3033#else
491527d0
GS
3034#if defined(atarist) || defined(DOSISH)
3035 for (len = 0; *s
3036# ifdef atarist
3037 && *s != ','
3038# endif
3039 && *s != ';'; len++, s++) {
84486fc6
GS
3040 if (len < sizeof tmpbuf)
3041 tmpbuf[len] = *s;
491527d0 3042 }
84486fc6
GS
3043 if (len < sizeof tmpbuf)
3044 tmpbuf[len] = '\0';
491527d0 3045#else /* ! (atarist || DOSISH) */
3280af22 3046 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
491527d0
GS
3047 ':',
3048 &len);
3049#endif /* ! (atarist || DOSISH) */
cd39f2b6 3050#endif /* MACOS_TRADITIONAL */
3280af22 3051 if (s < PL_bufend)
491527d0 3052 s++;
84486fc6 3053 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
491527d0 3054 continue; /* don't search dir with too-long name */
cd39f2b6
JH
3055#ifdef MACOS_TRADITIONAL
3056 if (len && tmpbuf[len - 1] != ':')
3057 tmpbuf[len++] = ':';
3058#else
491527d0 3059 if (len
490a0e98 3060# if defined(atarist) || defined(__MINT__) || defined(DOSISH)
84486fc6
GS
3061 && tmpbuf[len - 1] != '/'
3062 && tmpbuf[len - 1] != '\\'
490a0e98 3063# endif
491527d0 3064 )
84486fc6
GS
3065 tmpbuf[len++] = '/';
3066 if (len == 2 && tmpbuf[0] == '.')
491527d0 3067 seen_dot = 1;
cd39f2b6 3068#endif
490a0e98
NC
3069 /* FIXME? Convert to memcpy by storing previous strlen(scriptname)
3070 */
84486fc6 3071 (void)strcpy(tmpbuf + len, scriptname);
491527d0
GS
3072#endif /* !VMS */
3073
3074#ifdef SEARCH_EXTS
84486fc6 3075 len = strlen(tmpbuf);
491527d0
GS
3076 if (extidx > 0) /* reset after previous loop */
3077 extidx = 0;
3078 do {
3079#endif
84486fc6 3080 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3280af22 3081 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
017f25f1
IZ
3082 if (S_ISDIR(PL_statbuf.st_mode)) {
3083 retval = -1;
3084 }
491527d0
GS
3085#ifdef SEARCH_EXTS
3086 } while ( retval < 0 /* not there */
3087 && extidx>=0 && ext[extidx] /* try an extension? */
84486fc6 3088 && strcpy(tmpbuf+len, ext[extidx++])
491527d0
GS
3089 );
3090#endif
3091 if (retval < 0)
3092 continue;
3280af22
NIS
3093 if (S_ISREG(PL_statbuf.st_mode)
3094 && cando(S_IRUSR,TRUE,&PL_statbuf)
73811745 3095#if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3280af22 3096 && cando(S_IXUSR,TRUE,&PL_statbuf)
491527d0
GS
3097#endif
3098 )
3099 {
3aed30dc 3100 xfound = tmpbuf; /* bingo! */
491527d0
GS
3101 break;
3102 }
3103 if (!xfailed)
84486fc6 3104 xfailed = savepv(tmpbuf);
491527d0
GS
3105 }
3106#ifndef DOSISH
017f25f1 3107 if (!xfound && !seen_dot && !xfailed &&
a1d180c4 3108 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
017f25f1 3109 || S_ISDIR(PL_statbuf.st_mode)))
491527d0
GS
3110#endif
3111 seen_dot = 1; /* Disable message. */
9ccb31f9
GS
3112 if (!xfound) {
3113 if (flags & 1) { /* do or die? */
3aed30dc 3114 Perl_croak(aTHX_ "Can't %s %s%s%s",
9ccb31f9
GS
3115 (xfailed ? "execute" : "find"),
3116 (xfailed ? xfailed : scriptname),
3117 (xfailed ? "" : " on PATH"),
3118 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3119 }
3120 scriptname = Nullch;
3121 }
43c5f42d 3122 Safefree(xfailed);
491527d0
GS
3123 scriptname = xfound;
3124 }
9ccb31f9 3125 return (scriptname ? savepv(scriptname) : Nullch);
491527d0
GS
3126}
3127
ba869deb
GS
3128#ifndef PERL_GET_CONTEXT_DEFINED
3129
3130void *
3131Perl_get_context(void)
3132{
27da23d5 3133 dVAR;
3db8f154 3134#if defined(USE_ITHREADS)
ba869deb
GS
3135# ifdef OLD_PTHREADS_API
3136 pthread_addr_t t;
3137 if (pthread_getspecific(PL_thr_key, &t))
3138 Perl_croak_nocontext("panic: pthread_getspecific");
3139 return (void*)t;
3140# else
bce813aa 3141# ifdef I_MACH_CTHREADS
8b8b35ab 3142 return (void*)cthread_data(cthread_self());
bce813aa 3143# else
8b8b35ab
JH
3144 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3145# endif
c44d3fdb 3146# endif
ba869deb
GS
3147#else
3148 return (void*)NULL;
3149#endif
3150}
3151
3152void
3153Perl_set_context(void *t)
3154{
8772537c 3155 dVAR;
3db8f154 3156#if defined(USE_ITHREADS)
c44d3fdb
GS
3157# ifdef I_MACH_CTHREADS
3158 cthread_set_data(cthread_self(), t);
3159# else
ba869deb
GS
3160 if (pthread_setspecific(PL_thr_key, t))
3161 Perl_croak_nocontext("panic: pthread_setspecific");
c44d3fdb 3162# endif
b464bac0 3163#else
8772537c 3164 PERL_UNUSED_ARG(t);
ba869deb
GS
3165#endif
3166}
3167
3168#endif /* !PERL_GET_CONTEXT_DEFINED */
491527d0 3169
27da23d5 3170#if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
22239a37 3171struct perl_vars *
864dbfa3 3172Perl_GetVars(pTHX)
22239a37 3173{
533c011a 3174 return &PL_Vars;
22239a37 3175}
31fb1209
NIS
3176#endif
3177
1cb0ed9b 3178char **
864dbfa3 3179Perl_get_op_names(pTHX)
31fb1209 3180{
27da23d5 3181 return (char **)PL_op_name;
31fb1209
NIS
3182}
3183
1cb0ed9b 3184char **
864dbfa3 3185Perl_get_op_descs(pTHX)
31fb1209 3186{
27da23d5 3187 return (char **)PL_op_desc;
31fb1209 3188}
9e6b2b00 3189
e1ec3a88 3190const char *
864dbfa3 3191Perl_get_no_modify(pTHX)
9e6b2b00 3192{
e1ec3a88 3193 return PL_no_modify;
9e6b2b00
GS
3194}
3195
3196U32 *
864dbfa3 3197Perl_get_opargs(pTHX)
9e6b2b00 3198{
27da23d5 3199 return (U32 *)PL_opargs;
9e6b2b00 3200}
51aa15f3 3201
0cb96387
GS
3202PPADDR_t*
3203Perl_get_ppaddr(pTHX)
3204{
27da23d5 3205 dVAR;
12ae5dfc 3206 return (PPADDR_t*)PL_ppaddr;
0cb96387
GS
3207}
3208
a6c40364
GS
3209#ifndef HAS_GETENV_LEN
3210char *
bf4acbe4 3211Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
a6c40364 3212{
8772537c 3213 char * const env_trans = PerlEnv_getenv(env_elem);
a6c40364
GS
3214 if (env_trans)
3215 *len = strlen(env_trans);
3216 return env_trans;
f675dbe5
CB
3217}
3218#endif
3219
dc9e4912
GS
3220
3221MGVTBL*
864dbfa3 3222Perl_get_vtbl(pTHX_ int vtbl_id)
dc9e4912 3223{
7452cf6a 3224 const MGVTBL* result;
dc9e4912
GS
3225
3226 switch(vtbl_id) {
3227 case want_vtbl_sv:
3228 result = &PL_vtbl_sv;
3229 break;
3230 case want_vtbl_env:
3231 result = &PL_vtbl_env;
3232 break;
3233 case want_vtbl_envelem:
3234 result = &PL_vtbl_envelem;
3235 break;
3236 case want_vtbl_sig:
3237 result = &PL_vtbl_sig;
3238 break;
3239 case want_vtbl_sigelem:
3240 result = &PL_vtbl_sigelem;
3241 break;
3242 case want_vtbl_pack:
3243 result = &PL_vtbl_pack;
3244 break;
3245 case want_vtbl_packelem:
3246 result = &PL_vtbl_packelem;
3247 break;
3248 case want_vtbl_dbline:
3249 result = &PL_vtbl_dbline;
3250 break;
3251 case want_vtbl_isa:
3252 result = &PL_vtbl_isa;
3253 break;
3254 case want_vtbl_isaelem:
3255 result = &PL_vtbl_isaelem;
3256 break;
3257 case want_vtbl_arylen:
3258 result = &PL_vtbl_arylen;
3259 break;
3260 case want_vtbl_glob:
3261 result = &PL_vtbl_glob;
3262 break;
3263 case want_vtbl_mglob:
3264 result = &PL_vtbl_mglob;
3265 break;
3266 case want_vtbl_nkeys:
3267 result = &PL_vtbl_nkeys;
3268 break;
3269 case want_vtbl_taint:
3270 result = &PL_vtbl_taint;
3271 break;
3272 case want_vtbl_substr:
3273 result = &PL_vtbl_substr;
3274 break;
3275 case want_vtbl_vec:
3276 result = &PL_vtbl_vec;
3277 break;
3278 case want_vtbl_pos:
3279 result = &PL_vtbl_pos;
3280 break;
3281 case want_vtbl_bm:
3282 result = &PL_vtbl_bm;
3283 break;
3284 case want_vtbl_fm:
3285 result = &PL_vtbl_fm;
3286 break;
3287 case want_vtbl_uvar:
3288 result = &PL_vtbl_uvar;
3289 break;
dc9e4912
GS
3290 case want_vtbl_defelem:
3291 result = &PL_vtbl_defelem;
3292 break;
3293 case want_vtbl_regexp:
3294 result = &PL_vtbl_regexp;
3295 break;
3296 case want_vtbl_regdata:
3297 result = &PL_vtbl_regdata;
3298 break;
3299 case want_vtbl_regdatum:
3300 result = &PL_vtbl_regdatum;
3301 break;
3c90161d 3302#ifdef USE_LOCALE_COLLATE
dc9e4912
GS
3303 case want_vtbl_collxfrm:
3304 result = &PL_vtbl_collxfrm;
3305 break;
3c90161d 3306#endif
dc9e4912
GS
3307 case want_vtbl_amagic:
3308 result = &PL_vtbl_amagic;
3309 break;
3310 case want_vtbl_amagicelem:
3311 result = &PL_vtbl_amagicelem;
3312 break;
810b8aa5
GS
3313 case want_vtbl_backref:
3314 result = &PL_vtbl_backref;
3315 break;
7e8c5dac
HS
3316 case want_vtbl_utf8:
3317 result = &PL_vtbl_utf8;
3318 break;
7452cf6a
AL
3319 default:
3320 result = Null(MGVTBL*);
3321 break;
dc9e4912 3322 }
27da23d5 3323 return (MGVTBL*)result;
dc9e4912
GS
3324}
3325
767df6a1 3326I32
864dbfa3 3327Perl_my_fflush_all(pTHX)
767df6a1 3328{
f800e14d 3329#if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
ce720889 3330 return PerlIO_flush(NULL);
767df6a1 3331#else
8fbdfb7c 3332# if defined(HAS__FWALK)
f13a2bc0 3333 extern int fflush(FILE *);
74cac757
JH
3334 /* undocumented, unprototyped, but very useful BSDism */
3335 extern void _fwalk(int (*)(FILE *));
8fbdfb7c 3336 _fwalk(&fflush);
74cac757 3337 return 0;
8fa7f367 3338# else
8fbdfb7c 3339# if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
8fa7f367 3340 long open_max = -1;
8fbdfb7c 3341# ifdef PERL_FFLUSH_ALL_FOPEN_MAX
d2201af2 3342 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
8fbdfb7c 3343# else
8fa7f367 3344# if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
767df6a1 3345 open_max = sysconf(_SC_OPEN_MAX);
8fa7f367
JH
3346# else
3347# ifdef FOPEN_MAX
74cac757 3348 open_max = FOPEN_MAX;
8fa7f367
JH
3349# else
3350# ifdef OPEN_MAX
74cac757 3351 open_max = OPEN_MAX;
8fa7f367
JH
3352# else
3353# ifdef _NFILE
d2201af2 3354 open_max = _NFILE;
8fa7f367
JH
3355# endif
3356# endif
74cac757 3357# endif
767df6a1
JH
3358# endif
3359# endif
767df6a1
JH
3360 if (open_max > 0) {
3361 long i;
3362 for (i = 0; i < open_max; i++)
d2201af2
AD
3363 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3364 STDIO_STREAM_ARRAY[i]._file < open_max &&
3365 STDIO_STREAM_ARRAY[i]._flag)
3366 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
767df6a1
JH
3367 return 0;
3368 }
8fbdfb7c 3369# endif
93189314 3370 SETERRNO(EBADF,RMS_IFI);
767df6a1 3371 return EOF;
74cac757 3372# endif
767df6a1
JH
3373#endif
3374}
097ee67d 3375
69282e91 3376void
e1ec3a88 3377Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
bc37a18f 3378{
b64e5050 3379 const char * const func =
66fc2fa5
JH
3380 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3381 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
bc37a18f 3382 PL_op_desc[op];
b64e5050
AL
3383 const char * const pars = OP_IS_FILETEST(op) ? "" : "()";
3384 const char * const type = OP_IS_SOCKET(op)
3aed30dc
HS
3385 || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3386 ? "socket" : "filehandle";
b64e5050 3387 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
66fc2fa5 3388
4c80c0b2 3389 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3aed30dc 3390 if (ckWARN(WARN_IO)) {
b64e5050 3391 const char * const direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3aed30dc
HS
3392 if (name && *name)
3393 Perl_warner(aTHX_ packWARN(WARN_IO),
3394 "Filehandle %s opened only for %sput",
fd322ea4 3395 name, direction);
3aed30dc
HS
3396 else
3397 Perl_warner(aTHX_ packWARN(WARN_IO),
fd322ea4 3398 "Filehandle opened only for %sput", direction);
3aed30dc 3399 }
2dd78f96
JH
3400 }
3401 else {
e1ec3a88 3402 const char *vile;
3aed30dc
HS
3403 I32 warn_type;
3404
3405 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3406 vile = "closed";
3407 warn_type = WARN_CLOSED;
3408 }
3409 else {
3410 vile = "unopened";
3411 warn_type = WARN_UNOPENED;
3412 }
3413
3414 if (ckWARN(warn_type)) {
3415 if (name && *name) {
3416 Perl_warner(aTHX_ packWARN(warn_type),
3417 "%s%s on %s %s %s", func, pars, vile, type, name);
3418 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3419 Perl_warner(
3420 aTHX_ packWARN(warn_type),
3421 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3422 func, pars, name
3423 );
3424 }
3425 else {
3426 Perl_warner(aTHX_ packWARN(warn_type),
3427 "%s%s on %s %s", func, pars, vile, type);
3428 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3429 Perl_warner(
3430 aTHX_ packWARN(warn_type),
3431 "\t(Are you trying to call %s%s on dirhandle?)\n",
3432 func, pars
3433 );
3434 }
3435 }
bc37a18f 3436 }
69282e91 3437}
a926ef6b
JH
3438
3439#ifdef EBCDIC
cbebf344
JH
3440/* in ASCII order, not that it matters */
3441static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3442
a926ef6b
JH
3443int
3444Perl_ebcdic_control(pTHX_ int ch)
3445{
3aed30dc 3446 if (ch > 'a') {
e1ec3a88 3447 const char *ctlp;
3aed30dc
HS
3448
3449 if (islower(ch))
3450 ch = toupper(ch);
3451
3452 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3453 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
a926ef6b 3454 }
3aed30dc
HS
3455
3456 if (ctlp == controllablechars)
3457 return('\177'); /* DEL */
3458 else
3459 return((unsigned char)(ctlp - controllablechars - 1));
3460 } else { /* Want uncontrol */
3461 if (ch == '\177' || ch == -1)
3462 return('?');
3463 else if (ch == '\157')
3464 return('\177');
3465 else if (ch == '\174')
3466 return('\000');
3467 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3468 return('\036');
3469 else if (ch == '\155')
3470 return('\037');
3471 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3472 return(controllablechars[ch+1]);
3473 else
3474 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3475 }
a926ef6b
JH
3476}
3477#endif
e72cf795 3478
f6adc668 3479/* To workaround core dumps from the uninitialised tm_zone we get the
e72cf795
JH
3480 * system to give us a reasonable struct to copy. This fix means that
3481 * strftime uses the tm_zone and tm_gmtoff values returned by
3482 * localtime(time()). That should give the desired result most of the
3483 * time. But probably not always!
3484 *
f6adc668
JH
3485 * This does not address tzname aspects of NETaa14816.
3486 *
e72cf795 3487 */
f6adc668 3488
e72cf795
JH
3489#ifdef HAS_GNULIBC
3490# ifndef STRUCT_TM_HASZONE
3491# define STRUCT_TM_HASZONE
3492# endif
3493#endif
3494
f6adc668
JH
3495#ifdef STRUCT_TM_HASZONE /* Backward compat */
3496# ifndef HAS_TM_TM_ZONE
3497# define HAS_TM_TM_ZONE
3498# endif
3499#endif
3500
e72cf795 3501void
f1208910 3502Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
e72cf795 3503{
f6adc668 3504#ifdef HAS_TM_TM_ZONE
e72cf795 3505 Time_t now;
1b6737cc 3506 const struct tm* my_tm;
e72cf795 3507 (void)time(&now);
82c57498 3508 my_tm = localtime(&now);
ca46b8ee
SP
3509 if (my_tm)
3510 Copy(my_tm, ptm, 1, struct tm);
1b6737cc
AL
3511#else
3512 PERL_UNUSED_ARG(ptm);
e72cf795
JH
3513#endif
3514}
3515
3516/*
3517 * mini_mktime - normalise struct tm values without the localtime()
3518 * semantics (and overhead) of mktime().
3519 */
3520void
f1208910 3521Perl_mini_mktime(pTHX_ struct tm *ptm)
e72cf795
JH
3522{
3523 int yearday;
3524 int secs;
3525 int month, mday, year, jday;
3526 int odd_cent, odd_year;
3527
3528#define DAYS_PER_YEAR 365
3529#define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3530#define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3531#define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3532#define SECS_PER_HOUR (60*60)
3533#define SECS_PER_DAY (24*SECS_PER_HOUR)
3534/* parentheses deliberately absent on these two, otherwise they don't work */
3535#define MONTH_TO_DAYS 153/5
3536#define DAYS_TO_MONTH 5/153
3537/* offset to bias by March (month 4) 1st between month/mday & year finding */
3538#define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3539/* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3540#define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3541
3542/*
3543 * Year/day algorithm notes:
3544 *
3545 * With a suitable offset for numeric value of the month, one can find
3546 * an offset into the year by considering months to have 30.6 (153/5) days,
3547 * using integer arithmetic (i.e., with truncation). To avoid too much
3548 * messing about with leap days, we consider January and February to be
3549 * the 13th and 14th month of the previous year. After that transformation,
3550 * we need the month index we use to be high by 1 from 'normal human' usage,
3551 * so the month index values we use run from 4 through 15.
3552 *
3553 * Given that, and the rules for the Gregorian calendar (leap years are those
3554 * divisible by 4 unless also divisible by 100, when they must be divisible
3555 * by 400 instead), we can simply calculate the number of days since some
3556 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3557 * the days we derive from our month index, and adding in the day of the
3558 * month. The value used here is not adjusted for the actual origin which
3559 * it normally would use (1 January A.D. 1), since we're not exposing it.
3560 * We're only building the value so we can turn around and get the
3561 * normalised values for the year, month, day-of-month, and day-of-year.
3562 *
3563 * For going backward, we need to bias the value we're using so that we find
3564 * the right year value. (Basically, we don't want the contribution of
3565 * March 1st to the number to apply while deriving the year). Having done
3566 * that, we 'count up' the contribution to the year number by accounting for
3567 * full quadracenturies (400-year periods) with their extra leap days, plus
3568 * the contribution from full centuries (to avoid counting in the lost leap
3569 * days), plus the contribution from full quad-years (to count in the normal
3570 * leap days), plus the leftover contribution from any non-leap years.
3571 * At this point, if we were working with an actual leap day, we'll have 0
3572 * days left over. This is also true for March 1st, however. So, we have
3573 * to special-case that result, and (earlier) keep track of the 'odd'
3574 * century and year contributions. If we got 4 extra centuries in a qcent,
3575 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3576 * Otherwise, we add back in the earlier bias we removed (the 123 from
3577 * figuring in March 1st), find the month index (integer division by 30.6),
3578 * and the remainder is the day-of-month. We then have to convert back to
3579 * 'real' months (including fixing January and February from being 14/15 in
3580 * the previous year to being in the proper year). After that, to get
3581 * tm_yday, we work with the normalised year and get a new yearday value for
3582 * January 1st, which we subtract from the yearday value we had earlier,
3583 * representing the date we've re-built. This is done from January 1
3584 * because tm_yday is 0-origin.
3585 *
3586 * Since POSIX time routines are only guaranteed to work for times since the
3587 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3588 * applies Gregorian calendar rules even to dates before the 16th century
3589 * doesn't bother me. Besides, you'd need cultural context for a given
3590 * date to know whether it was Julian or Gregorian calendar, and that's
3591 * outside the scope for this routine. Since we convert back based on the
3592 * same rules we used to build the yearday, you'll only get strange results
3593 * for input which needed normalising, or for the 'odd' century years which
3594 * were leap years in the Julian calander but not in the Gregorian one.
3595 * I can live with that.
3596 *
3597 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3598 * that's still outside the scope for POSIX time manipulation, so I don't
3599 * care.
3600 */
3601
3602 year = 1900 + ptm->tm_year;
3603 month = ptm->tm_mon;
3604 mday = ptm->tm_mday;
3605 /* allow given yday with no month & mday to dominate the result */
3606 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3607 month = 0;
3608 mday = 0;
3609 jday = 1 + ptm->tm_yday;
3610 }
3611 else {
3612 jday = 0;
3613 }
3614 if (month >= 2)
3615 month+=2;
3616 else
3617 month+=14, year--;
3618 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3619 yearday += month*MONTH_TO_DAYS + mday + jday;
3620 /*
3621 * Note that we don't know when leap-seconds were or will be,
3622 * so we have to trust the user if we get something which looks
3623 * like a sensible leap-second. Wild values for seconds will
3624 * be rationalised, however.
3625 */
3626 if ((unsigned) ptm->tm_sec <= 60) {
3627 secs = 0;
3628 }
3629 else {
3630 secs = ptm->tm_sec;
3631 ptm->tm_sec = 0;
3632 }
3633 secs += 60 * ptm->tm_min;
3634 secs += SECS_PER_HOUR * ptm->tm_hour;
3635 if (secs < 0) {
3636 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3637 /* got negative remainder, but need positive time */
3638 /* back off an extra day to compensate */
3639 yearday += (secs/SECS_PER_DAY)-1;
3640 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3641 }
3642 else {
3643 yearday += (secs/SECS_PER_DAY);
3644 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3645 }
3646 }
3647 else if (secs >= SECS_PER_DAY) {
3648 yearday += (secs/SECS_PER_DAY);
3649 secs %= SECS_PER_DAY;
3650 }
3651 ptm->tm_hour = secs/SECS_PER_HOUR;
3652 secs %= SECS_PER_HOUR;
3653 ptm->tm_min = secs/60;
3654 secs %= 60;
3655 ptm->tm_sec += secs;
3656 /* done with time of day effe