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