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