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