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