This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
-DL and PERL_DEBUG_MSTATS unravelled
[perl5.git] / util.c
CommitLineData
a0d0e21e 1/* util.c
a687059c 2 *
9607fc9c 3 * Copyright (c) 1991-1997, 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"
8d063cd8 16#include "perl.h"
31da6858 17#include "perlmem.h"
62b28dd9 18
6eb13c3b 19#if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
a687059c 20#include <signal.h>
62b28dd9 21#endif
a687059c 22
36477c24 23#ifndef SIG_ERR
24# define SIG_ERR ((Sighandler_t) -1)
25#endif
26
bd4080b3 27/* XXX If this causes problems, set i_unistd=undef in the hint file. */
85e6fe83 28#ifdef I_UNISTD
8990e307
LW
29# include <unistd.h>
30#endif
31
a687059c
LW
32#ifdef I_VFORK
33# include <vfork.h>
34#endif
35
94b6baf5
AD
36/* Put this after #includes because fork and vfork prototypes may
37 conflict.
38*/
39#ifndef HAS_VFORK
40# define vfork fork
41#endif
42
fe14fcc3
LW
43#ifdef I_FCNTL
44# include <fcntl.h>
45#endif
46#ifdef I_SYS_FILE
47# include <sys/file.h>
48#endif
49
ff68c719 50#ifdef I_SYS_WAIT
51# include <sys/wait.h>
52#endif
53
8d063cd8 54#define FLUSH
8d063cd8 55
a0d0e21e 56#ifdef LEAKTEST
a0d0e21e 57
8c52afec
IZ
58static void xstat _((int));
59long xcount[MAXXCOUNT];
60long lastxcount[MAXXCOUNT];
61long xycount[MAXXCOUNT][MAXYCOUNT];
62long lastxycount[MAXXCOUNT][MAXYCOUNT];
63
a0d0e21e 64#endif
a863c7d1 65
55497cff 66#ifndef MYMALLOC
de3bb511 67
8d063cd8
LW
68/* paranoid version of malloc */
69
a687059c
LW
70/* NOTE: Do not call the next three routines directly. Use the macros
71 * in handy.h, so that we can easily redefine everything to do tracking of
72 * allocated hunks back to the original New to track down any memory leaks.
20cec16a 73 * XXX This advice seems to be widely ignored :-( --AD August 1996.
a687059c
LW
74 */
75
bd4080b3 76Malloc_t
f0f333f4 77safemalloc(MEM_SIZE size)
8d063cd8 78{
bd4080b3 79 Malloc_t ptr;
55497cff 80#ifdef HAS_64K_LIMIT
62b28dd9 81 if (size > 0xffff) {
760ac839 82 PerlIO_printf(PerlIO_stderr(), "Allocation too large: %lx\n", size) FLUSH;
79072805 83 my_exit(1);
62b28dd9 84 }
55497cff 85#endif /* HAS_64K_LIMIT */
34de22dd
LW
86#ifdef DEBUGGING
87 if ((long)size < 0)
463ee0b2 88 croak("panic: malloc");
34de22dd 89#endif
6ad3d225 90 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
79072805 91#if !(defined(I286) || defined(atarist))
760ac839 92 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%x: (%05d) malloc %ld bytes\n",ptr,an++,(long)size));
79072805 93#else
760ac839 94 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) malloc %ld bytes\n",ptr,an++,(long)size));
8d063cd8
LW
95#endif
96 if (ptr != Nullch)
97 return ptr;
7c0587c8
LW
98 else if (nomemok)
99 return Nullch;
8d063cd8 100 else {
760ac839 101 PerlIO_puts(PerlIO_stderr(),no_mem) FLUSH;
79072805 102 my_exit(1);
4e35701f 103 return Nullch;
8d063cd8
LW
104 }
105 /*NOTREACHED*/
106}
107
108/* paranoid version of realloc */
109
bd4080b3 110Malloc_t
f0f333f4 111saferealloc(Malloc_t where,MEM_SIZE size)
8d063cd8 112{
bd4080b3 113 Malloc_t ptr;
ecfc5424 114#if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE)
6ad3d225 115 Malloc_t PerlMem_realloc();
ecfc5424 116#endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
8d063cd8 117
55497cff 118#ifdef HAS_64K_LIMIT
5f05dabc 119 if (size > 0xffff) {
120 PerlIO_printf(PerlIO_stderr(),
121 "Reallocation too large: %lx\n", size) FLUSH;
122 my_exit(1);
123 }
55497cff 124#endif /* HAS_64K_LIMIT */
378cc40b 125 if (!where)
463ee0b2 126 croak("Null realloc");
34de22dd
LW
127#ifdef DEBUGGING
128 if ((long)size < 0)
463ee0b2 129 croak("panic: realloc");
34de22dd 130#endif
6ad3d225 131 ptr = PerlMem_realloc(where,size?size:1); /* realloc(0) is NASTY on our system */
79072805
LW
132
133#if !(defined(I286) || defined(atarist))
134 DEBUG_m( {
760ac839
LW
135 PerlIO_printf(Perl_debug_log, "0x%x: (%05d) rfree\n",where,an++);
136 PerlIO_printf(Perl_debug_log, "0x%x: (%05d) realloc %ld bytes\n",ptr,an++,(long)size);
79072805
LW
137 } )
138#else
139 DEBUG_m( {
760ac839
LW
140 PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) rfree\n",where,an++);
141 PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) realloc %ld bytes\n",ptr,an++,(long)size);
79072805 142 } )
8d063cd8 143#endif
79072805 144
8d063cd8
LW
145 if (ptr != Nullch)
146 return ptr;
7c0587c8
LW
147 else if (nomemok)
148 return Nullch;
8d063cd8 149 else {
760ac839 150 PerlIO_puts(PerlIO_stderr(),no_mem) FLUSH;
79072805 151 my_exit(1);
4e35701f 152 return Nullch;
8d063cd8
LW
153 }
154 /*NOTREACHED*/
155}
156
157/* safe version of free */
158
54310121 159Free_t
f0f333f4 160safefree(Malloc_t where)
8d063cd8 161{
79072805 162#if !(defined(I286) || defined(atarist))
f0f333f4 163 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%x: (%05d) free\n",(char *) where,an++));
79072805 164#else
f0f333f4 165 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) free\n",(char *) where,an++));
8d063cd8 166#endif
378cc40b 167 if (where) {
de3bb511 168 /*SUPPRESS 701*/
6ad3d225 169 PerlMem_free(where);
378cc40b 170 }
8d063cd8
LW
171}
172
1050c9ca 173/* safe version of calloc */
174
bd4080b3 175Malloc_t
f0f333f4 176safecalloc(MEM_SIZE count, MEM_SIZE size)
1050c9ca 177{
bd4080b3 178 Malloc_t ptr;
1050c9ca 179
55497cff 180#ifdef HAS_64K_LIMIT
5f05dabc 181 if (size * count > 0xffff) {
182 PerlIO_printf(PerlIO_stderr(),
183 "Allocation too large: %lx\n", size * count) FLUSH;
184 my_exit(1);
185 }
55497cff 186#endif /* HAS_64K_LIMIT */
1050c9ca 187#ifdef DEBUGGING
188 if ((long)size < 0 || (long)count < 0)
189 croak("panic: calloc");
190#endif
0b7c1c42 191 size *= count;
6ad3d225 192 ptr = PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
1050c9ca 193#if !(defined(I286) || defined(atarist))
fb73857a 194 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%x: (%05d) calloc %ld x %ld bytes\n",ptr,an++,(long)count,(long)size));
1050c9ca 195#else
fb73857a 196 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) calloc %ld x %ld bytes\n",ptr,an++,(long)count,(long)size));
1050c9ca 197#endif
1050c9ca 198 if (ptr != Nullch) {
199 memset((void*)ptr, 0, size);
200 return ptr;
201 }
202 else if (nomemok)
203 return Nullch;
204 else {
760ac839 205 PerlIO_puts(PerlIO_stderr(),no_mem) FLUSH;
1050c9ca 206 my_exit(1);
4e35701f 207 return Nullch;
1050c9ca 208 }
209 /*NOTREACHED*/
210}
211
55497cff 212#endif /* !MYMALLOC */
de3bb511 213
a687059c
LW
214#ifdef LEAKTEST
215
8c52afec
IZ
216struct mem_test_strut {
217 union {
218 long type;
219 char c[2];
220 } u;
221 long size;
222};
223
224# define ALIGN sizeof(struct mem_test_strut)
225
226# define sizeof_chunk(ch) (((struct mem_test_strut*) (ch))->size)
227# define typeof_chunk(ch) \
228 (((struct mem_test_strut*) (ch))->u.c[0] + ((struct mem_test_strut*) (ch))->u.c[1]*100)
229# define set_typeof_chunk(ch,t) \
230 (((struct mem_test_strut*) (ch))->u.c[0] = t % 100, ((struct mem_test_strut*) (ch))->u.c[1] = t / 100)
231#define SIZE_TO_Y(size) ( (size) > MAXY_SIZE \
232 ? MAXYCOUNT - 1 \
233 : ( (size) > 40 \
234 ? ((size) - 1)/8 + 5 \
235 : ((size) - 1)/4))
8d063cd8 236
bd4080b3 237Malloc_t
f0f333f4 238safexmalloc(I32 x, MEM_SIZE size)
8d063cd8 239{
8c52afec 240 register char* where = (char*)safemalloc(size + ALIGN);
8d063cd8 241
8c52afec
IZ
242 xcount[x] += size;
243 xycount[x][SIZE_TO_Y(size)]++;
244 set_typeof_chunk(where, x);
245 sizeof_chunk(where) = size;
246 return (Malloc_t)(where + ALIGN);
8d063cd8 247}
8d063cd8 248
bd4080b3 249Malloc_t
8c52afec 250safexrealloc(Malloc_t wh, MEM_SIZE size)
a687059c 251{
8c52afec
IZ
252 char *where = (char*)wh;
253
254 if (!wh)
255 return safexmalloc(0,size);
256
257 {
258 MEM_SIZE old = sizeof_chunk(where - ALIGN);
259 int t = typeof_chunk(where - ALIGN);
260 register char* new = (char*)saferealloc(where - ALIGN, size + ALIGN);
261
262 xycount[t][SIZE_TO_Y(old)]--;
263 xycount[t][SIZE_TO_Y(size)]++;
264 xcount[t] += size - old;
265 sizeof_chunk(new) = size;
266 return (Malloc_t)(new + ALIGN);
267 }
a687059c
LW
268}
269
270void
8c52afec 271safexfree(Malloc_t wh)
a687059c 272{
79072805 273 I32 x;
8c52afec
IZ
274 char *where = (char*)wh;
275 MEM_SIZE size;
276
a687059c
LW
277 if (!where)
278 return;
279 where -= ALIGN;
8c52afec 280 size = sizeof_chunk(where);
a687059c 281 x = where[0] + 100 * where[1];
8c52afec
IZ
282 xcount[x] -= size;
283 xycount[x][SIZE_TO_Y(size)]--;
a687059c
LW
284 safefree(where);
285}
286
bd4080b3 287Malloc_t
f0f333f4 288safexcalloc(I32 x,MEM_SIZE count, MEM_SIZE size)
1050c9ca 289{
8c52afec
IZ
290 register char * where = (char*)safexmalloc(x, size * count + ALIGN);
291 xcount[x] += size;
292 xycount[x][SIZE_TO_Y(size)]++;
293 memset((void*)(where + ALIGN), 0, size * count);
294 set_typeof_chunk(where, x);
295 sizeof_chunk(where) = size;
296 return (Malloc_t)(where + ALIGN);
1050c9ca 297}
298
7c0587c8 299static void
8c52afec 300xstat(int flag)
8d063cd8 301{
8c52afec
IZ
302 register I32 i, j, total = 0;
303 I32 subtot[MAXYCOUNT];
8d063cd8 304
8c52afec
IZ
305 for (j = 0; j < MAXYCOUNT; j++) {
306 subtot[j] = 0;
307 }
308
309 PerlIO_printf(PerlIO_stderr(), " Id subtot 4 8 12 16 20 24 28 32 36 40 48 56 64 72 80 80+\n", total);
a687059c 310 for (i = 0; i < MAXXCOUNT; i++) {
8c52afec
IZ
311 total += xcount[i];
312 for (j = 0; j < MAXYCOUNT; j++) {
313 subtot[j] += xycount[i][j];
314 }
315 if (flag == 0
316 ? xcount[i] /* Have something */
317 : (flag == 2
318 ? xcount[i] != lastxcount[i] /* Changed */
319 : xcount[i] > lastxcount[i])) { /* Growed */
320 PerlIO_printf(PerlIO_stderr(),"%2d %02d %7ld ", i / 100, i % 100,
321 flag == 2 ? xcount[i] - lastxcount[i] : xcount[i]);
a687059c 322 lastxcount[i] = xcount[i];
8c52afec
IZ
323 for (j = 0; j < MAXYCOUNT; j++) {
324 if ( flag == 0
325 ? xycount[i][j] /* Have something */
326 : (flag == 2
327 ? xycount[i][j] != lastxycount[i][j] /* Changed */
328 : xycount[i][j] > lastxycount[i][j])) { /* Growed */
329 PerlIO_printf(PerlIO_stderr(),"%3ld ",
330 flag == 2
331 ? xycount[i][j] - lastxycount[i][j]
332 : xycount[i][j]);
333 lastxycount[i][j] = xycount[i][j];
334 } else {
335 PerlIO_printf(PerlIO_stderr(), " . ", xycount[i][j]);
336 }
337 }
338 PerlIO_printf(PerlIO_stderr(), "\n");
339 }
340 }
341 if (flag != 2) {
342 PerlIO_printf(PerlIO_stderr(), "Total %7ld ", total);
343 for (j = 0; j < MAXYCOUNT; j++) {
344 if (subtot[j]) {
345 PerlIO_printf(PerlIO_stderr(), "%3ld ", subtot[j]);
346 } else {
347 PerlIO_printf(PerlIO_stderr(), " . ");
348 }
8d063cd8 349 }
8c52afec 350 PerlIO_printf(PerlIO_stderr(), "\n");
8d063cd8 351 }
8d063cd8 352}
a687059c
LW
353
354#endif /* LEAKTEST */
8d063cd8
LW
355
356/* copy a string up to some (non-backslashed) delimiter, if any */
357
358char *
8ac85365 359delimcpy(register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
8d063cd8 360{
fc36a67e 361 register I32 tolen;
362 for (tolen = 0; from < fromend; from++, tolen++) {
378cc40b
LW
363 if (*from == '\\') {
364 if (from[1] == delim)
365 from++;
fc36a67e 366 else {
367 if (to < toend)
368 *to++ = *from;
369 tolen++;
370 from++;
371 }
378cc40b 372 }
bedebaa5 373 else if (*from == delim)
8d063cd8 374 break;
fc36a67e 375 if (to < toend)
376 *to++ = *from;
8d063cd8 377 }
bedebaa5
CS
378 if (to < toend)
379 *to = '\0';
fc36a67e 380 *retlen = tolen;
8d063cd8
LW
381 return from;
382}
383
384/* return ptr to little string in big string, NULL if not found */
378cc40b 385/* This routine was donated by Corey Satten. */
8d063cd8
LW
386
387char *
8ac85365 388instr(register char *big, register char *little)
378cc40b
LW
389{
390 register char *s, *x;
79072805 391 register I32 first;
378cc40b 392
a687059c
LW
393 if (!little)
394 return big;
395 first = *little++;
378cc40b
LW
396 if (!first)
397 return big;
398 while (*big) {
399 if (*big++ != first)
400 continue;
401 for (x=big,s=little; *s; /**/ ) {
402 if (!*x)
403 return Nullch;
404 if (*s++ != *x++) {
405 s--;
406 break;
407 }
408 }
409 if (!*s)
410 return big-1;
411 }
412 return Nullch;
413}
8d063cd8 414
a687059c
LW
415/* same as instr but allow embedded nulls */
416
417char *
8ac85365 418ninstr(register char *big, register char *bigend, char *little, char *lend)
8d063cd8 419{
a687059c 420 register char *s, *x;
79072805 421 register I32 first = *little;
a687059c 422 register char *littleend = lend;
378cc40b 423
a0d0e21e 424 if (!first && little >= littleend)
a687059c 425 return big;
de3bb511
LW
426 if (bigend - big < littleend - little)
427 return Nullch;
a687059c
LW
428 bigend -= littleend - little++;
429 while (big <= bigend) {
430 if (*big++ != first)
431 continue;
432 for (x=big,s=little; s < littleend; /**/ ) {
433 if (*s++ != *x++) {
434 s--;
435 break;
436 }
437 }
438 if (s >= littleend)
439 return big-1;
378cc40b 440 }
a687059c
LW
441 return Nullch;
442}
443
444/* reverse of the above--find last substring */
445
446char *
8ac85365 447rninstr(register char *big, char *bigend, char *little, char *lend)
a687059c
LW
448{
449 register char *bigbeg;
450 register char *s, *x;
79072805 451 register I32 first = *little;
a687059c
LW
452 register char *littleend = lend;
453
a0d0e21e 454 if (!first && little >= littleend)
a687059c
LW
455 return bigend;
456 bigbeg = big;
457 big = bigend - (littleend - little++);
458 while (big >= bigbeg) {
459 if (*big-- != first)
460 continue;
461 for (x=big+2,s=little; s < littleend; /**/ ) {
462 if (*s++ != *x++) {
463 s--;
464 break;
465 }
466 }
467 if (s >= littleend)
468 return big+1;
378cc40b 469 }
a687059c 470 return Nullch;
378cc40b 471}
a687059c 472
bbce6d69 473/*
474 * Set up for a new ctype locale.
475 */
55497cff 476void
8ac85365 477perl_new_ctype(char *newctype)
ef7eada9 478{
36477c24 479#ifdef USE_LOCALE_CTYPE
480
bbce6d69 481 int i;
ef7eada9 482
bbce6d69 483 for (i = 0; i < 256; i++) {
484 if (isUPPER_LC(i))
485 fold_locale[i] = toLOWER_LC(i);
486 else if (isLOWER_LC(i))
487 fold_locale[i] = toUPPER_LC(i);
488 else
489 fold_locale[i] = i;
490 }
bbce6d69 491
36477c24 492#endif /* USE_LOCALE_CTYPE */
493}
bbce6d69 494
495/*
496 * Set up for a new collation locale.
497 */
498void
8ac85365 499perl_new_collate(char *newcoll)
bbce6d69 500{
36477c24 501#ifdef USE_LOCALE_COLLATE
502
bbce6d69 503 if (! newcoll) {
504 if (collation_name) {
505 ++collation_ix;
506 Safefree(collation_name);
507 collation_name = NULL;
508 collation_standard = TRUE;
bbce6d69 509 collxfrm_base = 0;
510 collxfrm_mult = 2;
bbce6d69 511 }
512 return;
513 }
514
515 if (! collation_name || strNE(collation_name, newcoll)) {
516 ++collation_ix;
517 Safefree(collation_name);
518 collation_name = savepv(newcoll);
ff68c719 519 collation_standard = (strEQ(newcoll, "C") || strEQ(newcoll, "POSIX"));
bbce6d69 520
bbce6d69 521 {
522 /* 2: at most so many chars ('a', 'b'). */
523 /* 50: surely no system expands a char more. */
524#define XFRMBUFSIZE (2 * 50)
525 char xbuf[XFRMBUFSIZE];
526 Size_t fa = strxfrm(xbuf, "a", XFRMBUFSIZE);
527 Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
528 SSize_t mult = fb - fa;
529 if (mult < 1)
530 croak("strxfrm() gets absurd");
531 collxfrm_base = (fa > mult) ? (fa - mult) : 0;
532 collxfrm_mult = mult;
533 }
bbce6d69 534 }
bbce6d69 535
36477c24 536#endif /* USE_LOCALE_COLLATE */
537}
bbce6d69 538
539/*
540 * Set up for a new numeric locale.
541 */
542void
8ac85365 543perl_new_numeric(char *newnum)
bbce6d69 544{
36477c24 545#ifdef USE_LOCALE_NUMERIC
546
bbce6d69 547 if (! newnum) {
548 if (numeric_name) {
549 Safefree(numeric_name);
550 numeric_name = NULL;
551 numeric_standard = TRUE;
552 numeric_local = TRUE;
553 }
554 return;
555 }
556
557 if (! numeric_name || strNE(numeric_name, newnum)) {
558 Safefree(numeric_name);
559 numeric_name = savepv(newnum);
ff68c719 560 numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
bbce6d69 561 numeric_local = TRUE;
562 }
36477c24 563
564#endif /* USE_LOCALE_NUMERIC */
bbce6d69 565}
566
567void
8ac85365 568perl_set_numeric_standard(void)
bbce6d69 569{
5f05dabc 570#ifdef USE_LOCALE_NUMERIC
571
bbce6d69 572 if (! numeric_standard) {
573 setlocale(LC_NUMERIC, "C");
574 numeric_standard = TRUE;
575 numeric_local = FALSE;
576 }
5f05dabc 577
578#endif /* USE_LOCALE_NUMERIC */
bbce6d69 579}
580
581void
8ac85365 582perl_set_numeric_local(void)
bbce6d69 583{
5f05dabc 584#ifdef USE_LOCALE_NUMERIC
585
bbce6d69 586 if (! numeric_local) {
587 setlocale(LC_NUMERIC, numeric_name);
588 numeric_standard = FALSE;
589 numeric_local = TRUE;
590 }
bbce6d69 591
36477c24 592#endif /* USE_LOCALE_NUMERIC */
5f05dabc 593}
36477c24 594
bbce6d69 595
36477c24 596/*
597 * Initialize locale awareness.
598 */
f0c5b223 599int
8ac85365 600perl_init_i18nl10n(int printwarn)
f0c5b223
TB
601{
602 int ok = 1;
603 /* returns
604 * 1 = set ok or not applicable,
605 * 0 = fallback to C locale,
606 * -1 = fallback to C locale failed
607 */
bbce6d69 608
36477c24 609#ifdef USE_LOCALE
bbce6d69 610
36477c24 611#ifdef USE_LOCALE_CTYPE
bbce6d69 612 char *curctype = NULL;
36477c24 613#endif /* USE_LOCALE_CTYPE */
614#ifdef USE_LOCALE_COLLATE
bbce6d69 615 char *curcoll = NULL;
36477c24 616#endif /* USE_LOCALE_COLLATE */
617#ifdef USE_LOCALE_NUMERIC
bbce6d69 618 char *curnum = NULL;
36477c24 619#endif /* USE_LOCALE_NUMERIC */
76e3520e
GS
620 char *lc_all = PerlEnv_getenv("LC_ALL");
621 char *lang = PerlEnv_getenv("LANG");
bbce6d69 622 bool setlocale_failure = FALSE;
f0c5b223 623
02b32252
CS
624#ifdef LOCALE_ENVIRON_REQUIRED
625
626 /*
627 * Ultrix setlocale(..., "") fails if there are no environment
628 * variables from which to get a locale name.
629 */
630
631 bool done = FALSE;
632
633#ifdef LC_ALL
634 if (lang) {
635 if (setlocale(LC_ALL, ""))
636 done = TRUE;
637 else
638 setlocale_failure = TRUE;
639 }
640 if (!setlocale_failure)
641#endif /* LC_ALL */
642 {
643#ifdef USE_LOCALE_CTYPE
644 if (! (curctype = setlocale(LC_CTYPE,
76e3520e 645 (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
02b32252
CS
646 ? "" : Nullch)))
647 setlocale_failure = TRUE;
648#endif /* USE_LOCALE_CTYPE */
649#ifdef USE_LOCALE_COLLATE
650 if (! (curcoll = setlocale(LC_COLLATE,
76e3520e 651 (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
02b32252
CS
652 ? "" : Nullch)))
653 setlocale_failure = TRUE;
654#endif /* USE_LOCALE_COLLATE */
655#ifdef USE_LOCALE_NUMERIC
656 if (! (curnum = setlocale(LC_NUMERIC,
76e3520e 657 (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
02b32252
CS
658 ? "" : Nullch)))
659 setlocale_failure = TRUE;
660#endif /* USE_LOCALE_NUMERIC */
661 }
662
663#else /* !LOCALE_ENVIRON_REQUIRED */
664
bbce6d69 665#ifdef LC_ALL
5f05dabc 666
bbce6d69 667 if (! setlocale(LC_ALL, ""))
668 setlocale_failure = TRUE;
5f05dabc 669 else {
670#ifdef USE_LOCALE_CTYPE
671 curctype = setlocale(LC_CTYPE, Nullch);
672#endif /* USE_LOCALE_CTYPE */
673#ifdef USE_LOCALE_COLLATE
674 curcoll = setlocale(LC_COLLATE, Nullch);
675#endif /* USE_LOCALE_COLLATE */
676#ifdef USE_LOCALE_NUMERIC
677 curnum = setlocale(LC_NUMERIC, Nullch);
678#endif /* USE_LOCALE_NUMERIC */
679 }
680
681#else /* !LC_ALL */
bbce6d69 682
36477c24 683#ifdef USE_LOCALE_CTYPE
5f05dabc 684 if (! (curctype = setlocale(LC_CTYPE, "")))
bbce6d69 685 setlocale_failure = TRUE;
36477c24 686#endif /* USE_LOCALE_CTYPE */
687#ifdef USE_LOCALE_COLLATE
5f05dabc 688 if (! (curcoll = setlocale(LC_COLLATE, "")))
bbce6d69 689 setlocale_failure = TRUE;
36477c24 690#endif /* USE_LOCALE_COLLATE */
691#ifdef USE_LOCALE_NUMERIC
5f05dabc 692 if (! (curnum = setlocale(LC_NUMERIC, "")))
bbce6d69 693 setlocale_failure = TRUE;
36477c24 694#endif /* USE_LOCALE_NUMERIC */
bbce6d69 695
5f05dabc 696#endif /* LC_ALL */
697
02b32252
CS
698#endif /* !LOCALE_ENVIRON_REQUIRED */
699
5f05dabc 700 if (setlocale_failure) {
701 char *p;
702 bool locwarn = (printwarn > 1 ||
703 printwarn &&
76e3520e 704 (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p)));
20cec16a 705
5f05dabc 706 if (locwarn) {
707#ifdef LC_ALL
708
709 PerlIO_printf(PerlIO_stderr(),
710 "perl: warning: Setting locale failed.\n");
711
712#else /* !LC_ALL */
713
ef7eada9 714 PerlIO_printf(PerlIO_stderr(),
bbce6d69 715 "perl: warning: Setting locale failed for the categories:\n\t");
36477c24 716#ifdef USE_LOCALE_CTYPE
bbce6d69 717 if (! curctype)
5f05dabc 718 PerlIO_printf(PerlIO_stderr(), "LC_CTYPE ");
36477c24 719#endif /* USE_LOCALE_CTYPE */
720#ifdef USE_LOCALE_COLLATE
bbce6d69 721 if (! curcoll)
5f05dabc 722 PerlIO_printf(PerlIO_stderr(), "LC_COLLATE ");
36477c24 723#endif /* USE_LOCALE_COLLATE */
724#ifdef USE_LOCALE_NUMERIC
bbce6d69 725 if (! curnum)
5f05dabc 726 PerlIO_printf(PerlIO_stderr(), "LC_NUMERIC ");
36477c24 727#endif /* USE_LOCALE_NUMERIC */
bbce6d69 728 PerlIO_printf(PerlIO_stderr(), "\n");
729
5f05dabc 730#endif /* LC_ALL */
731
760ac839 732 PerlIO_printf(PerlIO_stderr(),
bbce6d69 733 "perl: warning: Please check that your locale settings:\n");
ef7eada9
JH
734
735 PerlIO_printf(PerlIO_stderr(),
bbce6d69 736 "\tLC_ALL = %c%s%c,\n",
737 lc_all ? '"' : '(',
738 lc_all ? lc_all : "unset",
739 lc_all ? '"' : ')');
5f05dabc 740
741 {
742 char **e;
743 for (e = environ; *e; e++) {
744 if (strnEQ(*e, "LC_", 3)
745 && strnNE(*e, "LC_ALL=", 7)
746 && (p = strchr(*e, '=')))
747 PerlIO_printf(PerlIO_stderr(), "\t%.*s = \"%s\",\n",
fb73857a 748 (int)(p - *e), *e, p + 1);
5f05dabc 749 }
750 }
751
ef7eada9 752 PerlIO_printf(PerlIO_stderr(),
bbce6d69 753 "\tLANG = %c%s%c\n",
5f05dabc 754 lang ? '"' : '(',
bbce6d69 755 lang ? lang : "unset",
756 lang ? '"' : ')');
ef7eada9 757
bbce6d69 758 PerlIO_printf(PerlIO_stderr(),
759 " are supported and installed on your system.\n");
5f05dabc 760 }
ef7eada9 761
5f05dabc 762#ifdef LC_ALL
763
764 if (setlocale(LC_ALL, "C")) {
765 if (locwarn)
766 PerlIO_printf(PerlIO_stderr(),
767 "perl: warning: Falling back to the standard locale (\"C\").\n");
bbce6d69 768 ok = 0;
ef7eada9 769 }
5f05dabc 770 else {
771 if (locwarn)
772 PerlIO_printf(PerlIO_stderr(),
773 "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
774 ok = -1;
775 }
bbce6d69 776
5f05dabc 777#else /* ! LC_ALL */
778
779 if (0
36477c24 780#ifdef USE_LOCALE_CTYPE
5f05dabc 781 || !(curctype || setlocale(LC_CTYPE, "C"))
36477c24 782#endif /* USE_LOCALE_CTYPE */
783#ifdef USE_LOCALE_COLLATE
5f05dabc 784 || !(curcoll || setlocale(LC_COLLATE, "C"))
36477c24 785#endif /* USE_LOCALE_COLLATE */
786#ifdef USE_LOCALE_NUMERIC
5f05dabc 787 || !(curnum || setlocale(LC_NUMERIC, "C"))
36477c24 788#endif /* USE_LOCALE_NUMERIC */
5f05dabc 789 )
790 {
791 if (locwarn)
bbce6d69 792 PerlIO_printf(PerlIO_stderr(),
5f05dabc 793 "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
794 ok = -1;
bbce6d69 795 }
5f05dabc 796
bbce6d69 797#endif /* ! LC_ALL */
5f05dabc 798
799#ifdef USE_LOCALE_CTYPE
800 curctype = setlocale(LC_CTYPE, Nullch);
801#endif /* USE_LOCALE_CTYPE */
802#ifdef USE_LOCALE_COLLATE
803 curcoll = setlocale(LC_COLLATE, Nullch);
804#endif /* USE_LOCALE_COLLATE */
805#ifdef USE_LOCALE_NUMERIC
806 curnum = setlocale(LC_NUMERIC, Nullch);
807#endif /* USE_LOCALE_NUMERIC */
ef7eada9
JH
808 }
809
36477c24 810#ifdef USE_LOCALE_CTYPE
bbce6d69 811 perl_new_ctype(curctype);
36477c24 812#endif /* USE_LOCALE_CTYPE */
bbce6d69 813
36477c24 814#ifdef USE_LOCALE_COLLATE
bbce6d69 815 perl_new_collate(curcoll);
36477c24 816#endif /* USE_LOCALE_COLLATE */
bbce6d69 817
36477c24 818#ifdef USE_LOCALE_NUMERIC
bbce6d69 819 perl_new_numeric(curnum);
36477c24 820#endif /* USE_LOCALE_NUMERIC */
ef7eada9 821
36477c24 822#endif /* USE_LOCALE */
ef7eada9 823
f0c5b223
TB
824 return ok;
825}
826
bbce6d69 827/* Backwards compatibility. */
828int
8ac85365 829perl_init_i18nl14n(int printwarn)
bbce6d69 830{
5f05dabc 831 return perl_init_i18nl10n(printwarn);
bbce6d69 832}
ef7eada9 833
36477c24 834#ifdef USE_LOCALE_COLLATE
ef7eada9 835
bbce6d69 836/*
837 * mem_collxfrm() is a bit like strxfrm() but with two important
838 * differences. First, it handles embedded NULs. Second, it allocates
839 * a bit more memory than needed for the transformed data itself.
840 * The real transformed data begins at offset sizeof(collationix).
841 * Please see sv_collxfrm() to see how this is used.
842 */
843char *
8ac85365 844mem_collxfrm(const char *s, STRLEN len, STRLEN *xlen)
bbce6d69 845{
846 char *xbuf;
76e3520e 847 STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
bbce6d69 848
849 /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
850 /* the +1 is for the terminating NUL. */
851
76e3520e
GS
852 xAlloc = sizeof(collation_ix) + collxfrm_base + (collxfrm_mult * len) + 1;
853 New(171, xbuf, xAlloc, char);
bbce6d69 854 if (! xbuf)
855 goto bad;
856
857 *(U32*)xbuf = collation_ix;
858 xout = sizeof(collation_ix);
859 for (xin = 0; xin < len; ) {
860 SSize_t xused;
861
862 for (;;) {
76e3520e 863 xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
bbce6d69 864 if (xused == -1)
865 goto bad;
76e3520e 866 if (xused < xAlloc - xout)
bbce6d69 867 break;
76e3520e
GS
868 xAlloc = (2 * xAlloc) + 1;
869 Renew(xbuf, xAlloc, char);
bbce6d69 870 if (! xbuf)
871 goto bad;
872 }
ef7eada9 873
bbce6d69 874 xin += strlen(s + xin) + 1;
875 xout += xused;
876
877 /* Embedded NULs are understood but silently skipped
878 * because they make no sense in locale collation. */
879 }
ef7eada9 880
bbce6d69 881 xbuf[xout] = '\0';
882 *xlen = xout - sizeof(collation_ix);
883 return xbuf;
884
885 bad:
886 Safefree(xbuf);
887 *xlen = 0;
888 return NULL;
ef7eada9
JH
889}
890
36477c24 891#endif /* USE_LOCALE_COLLATE */
bbce6d69 892
378cc40b 893void
2779dcf1 894fbm_compile(SV *sv, U32 flags /* not used yet */)
378cc40b 895{
a687059c
LW
896 register unsigned char *s;
897 register unsigned char *table;
79072805
LW
898 register U32 i;
899 register U32 len = SvCUR(sv);
900 I32 rarest = 0;
901 U32 frequency = 256;
902
c277df42
IZ
903 sv_upgrade(sv, SVt_PVBM);
904 if (len > 255 || len == 0) /* TAIL might be on on a zero-length string. */
748a9306 905 return; /* can't have offsets that big */
02128f11
IZ
906 if (len > 2) {
907 Sv_Grow(sv,len + 258);
908 table = (unsigned char*)(SvPVX(sv) + len + 1);
909 s = table - 2;
910 for (i = 0; i < 256; i++) {
911 table[i] = len;
912 }
913 i = 0;
914 while (s >= (unsigned char*)(SvPVX(sv)))
915 {
916 if (table[*s] == len)
917 table[*s] = i;
918 s--,i++;
919 }
378cc40b 920 }
bbce6d69 921 sv_magic(sv, Nullsv, 'B', Nullch, 0); /* deep magic */
79072805 922 SvVALID_on(sv);
378cc40b 923
463ee0b2 924 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
bbce6d69 925 for (i = 0; i < len; i++) {
926 if (freq[s[i]] < frequency) {
927 rarest = i;
928 frequency = freq[s[i]];
378cc40b
LW
929 }
930 }
79072805
LW
931 BmRARE(sv) = s[rarest];
932 BmPREVIOUS(sv) = rarest;
760ac839 933 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",BmRARE(sv),BmPREVIOUS(sv)));
378cc40b
LW
934}
935
378cc40b 936char *
8ac85365 937fbm_instr(unsigned char *big, register unsigned char *bigend, SV *littlestr)
378cc40b 938{
a687059c 939 register unsigned char *s;
79072805
LW
940 register I32 tmp;
941 register I32 littlelen;
a687059c
LW
942 register unsigned char *little;
943 register unsigned char *table;
944 register unsigned char *olds;
945 register unsigned char *oldlittle;
378cc40b 946
79072805 947 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
a0d0e21e
LW
948 STRLEN len;
949 char *l = SvPV(littlestr,len);
c277df42 950 if (!len) {
02128f11
IZ
951 if (SvTAIL(littlestr)) { /* Can be only 0-len constant
952 substr => we can ignore SvVALID */
953 if (multiline) {
954 char *t = "\n";
3fe6f2dc
MB
955 if ((s = (unsigned char*)ninstr((char*)big, (char*)bigend,
956 t, t + len))) {
957 return (char*)s;
958 }
02128f11 959 }
c277df42 960 if (bigend > big && bigend[-1] == '\n')
161b471a 961 return (char *)(bigend - 1);
c277df42 962 else
161b471a 963 return (char *) bigend;
c277df42 964 }
d48672a2 965 return (char*)big;
c277df42 966 }
a0d0e21e 967 return ninstr((char*)big,(char*)bigend, l, l + len);
d48672a2 968 }
378cc40b 969
79072805
LW
970 littlelen = SvCUR(littlestr);
971 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
0f85fab0
LW
972 if (littlelen > bigend - big)
973 return Nullch;
463ee0b2 974 little = (unsigned char*)SvPVX(littlestr);
bbce6d69 975 s = bigend - littlelen;
02128f11
IZ
976 if (s > big
977 && bigend[-1] == '\n'
978 && s[-1] == *little && memEQ((char*)s - 1,(char*)little,littlelen))
979 return (char*)s - 1; /* how sweet it is */
980 else if (*s == *little && memEQ((char*)s,(char*)little,littlelen))
bbce6d69 981 return (char*)s; /* how sweet it is */
02128f11
IZ
982 return Nullch;
983 }
984 if (littlelen <= 2) {
985 unsigned char c1 = (unsigned char)SvPVX(littlestr)[0];
986 unsigned char c2 = (unsigned char)SvPVX(littlestr)[1];
987 /* This may do extra comparisons if littlelen == 2, but this
988 should be hidden in the noise since we do less indirection. */
989
990 s = big;
991 bigend -= littlelen;
992 while (s <= bigend) {
993 if (s[0] == c1
994 && (littlelen == 1 || s[1] == c2)
995 && (!SvTAIL(littlestr)
996 || s == bigend
997 || s[littlelen] == '\n')) /* Automatically multiline */
3fe6f2dc
MB
998 {
999 return (char*)s;
1000 }
02128f11 1001 s++;
a687059c 1002 }
bbce6d69 1003 return Nullch;
a687059c 1004 }
463ee0b2 1005 table = (unsigned char*)(SvPVX(littlestr) + littlelen + 1);
62b28dd9
LW
1006 if (--littlelen >= bigend - big)
1007 return Nullch;
1008 s = big + littlelen;
a687059c 1009 oldlittle = little = table - 2;
bbce6d69 1010 if (s < bigend) {
1011 top2:
1012 /*SUPPRESS 560*/
1013 if (tmp = table[*s]) {
62b28dd9 1014#ifdef POINTERRIGOR
bbce6d69 1015 if (bigend - s > tmp) {
1016 s += tmp;
1017 goto top2;
1018 }
62b28dd9 1019#else
bbce6d69 1020 if ((s += tmp) < bigend)
1021 goto top2;
62b28dd9 1022#endif
bbce6d69 1023 return Nullch;
a687059c 1024 }
bbce6d69 1025 else {
1026 tmp = littlelen; /* less expensive than calling strncmp() */
1027 olds = s;
1028 while (tmp--) {
1029 if (*--s == *--little)
1030 continue;
c277df42 1031 differ:
bbce6d69 1032 s = olds + 1; /* here we pay the price for failure */
1033 little = oldlittle;
1034 if (s < bigend) /* fake up continue to outer loop */
62b28dd9 1035 goto top2;
62b28dd9 1036 return Nullch;
a687059c 1037 }
c277df42
IZ
1038 if (SvTAIL(littlestr) /* automatically multiline */
1039 && olds + 1 != bigend
1040 && olds[1] != '\n')
1041 goto differ;
bbce6d69 1042 return (char *)s;
378cc40b
LW
1043 }
1044 }
1045 return Nullch;
1046}
1047
c277df42
IZ
1048/* start_shift, end_shift are positive quantities which give offsets
1049 of ends of some substring of bigstr.
1050 If `last' we want the last occurence.
1051 old_posp is the way of communication between consequent calls if
1052 the next call needs to find the .
1053 The initial *old_posp should be -1.
1054 Note that we do not take into account SvTAIL, so it may give wrong
1055 positives if _ALL flag is set.
1056 */
1057
378cc40b 1058char *
c277df42 1059screaminstr(SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
378cc40b 1060{
a687059c
LW
1061 register unsigned char *s, *x;
1062 register unsigned char *big;
79072805
LW
1063 register I32 pos;
1064 register I32 previous;
1065 register I32 first;
a687059c 1066 register unsigned char *little;
c277df42 1067 register I32 stop_pos;
a687059c 1068 register unsigned char *littleend;
c277df42 1069 I32 found = 0;
378cc40b 1070
c277df42
IZ
1071 if (*old_posp == -1
1072 ? (pos = screamfirst[BmRARE(littlestr)]) < 0
1073 : (((pos = *old_posp), pos += screamnext[pos]) == 0))
378cc40b 1074 return Nullch;
463ee0b2 1075 little = (unsigned char *)(SvPVX(littlestr));
79072805 1076 littleend = little + SvCUR(littlestr);
378cc40b 1077 first = *little++;
c277df42 1078 /* The value of pos we can start at: */
79072805 1079 previous = BmPREVIOUS(littlestr);
463ee0b2 1080 big = (unsigned char *)(SvPVX(bigstr));
c277df42
IZ
1081 /* The value of pos we can stop at: */
1082 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
1083 if (previous + start_shift > stop_pos) return Nullch;
1084 while (pos < previous + start_shift) {
378cc40b
LW
1085 if (!(pos += screamnext[pos]))
1086 return Nullch;
1087 }
de3bb511 1088#ifdef POINTERRIGOR
bbce6d69 1089 do {
c277df42 1090 if (pos >= stop_pos) return Nullch;
bbce6d69 1091 if (big[pos-previous] != first)
1092 continue;
1093 for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
bbce6d69 1094 if (*s++ != *x++) {
1095 s--;
1096 break;
de3bb511 1097 }
bbce6d69 1098 }
c277df42
IZ
1099 if (s == littleend) {
1100 *old_posp = pos;
1101 if (!last) return (char *)(big+pos-previous);
1102 found = 1;
1103 }
bbce6d69 1104 } while ( pos += screamnext[pos] );
c277df42 1105 return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
de3bb511
LW
1106#else /* !POINTERRIGOR */
1107 big -= previous;
bbce6d69 1108 do {
c277df42 1109 if (pos >= stop_pos) return Nullch;
bbce6d69 1110 if (big[pos] != first)
1111 continue;
1112 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
bbce6d69 1113 if (*s++ != *x++) {
1114 s--;
1115 break;
378cc40b 1116 }
bbce6d69 1117 }
c277df42
IZ
1118 if (s == littleend) {
1119 *old_posp = pos;
1120 if (!last) return (char *)(big+pos);
1121 found = 1;
1122 }
bbce6d69 1123 } while ( pos += screamnext[pos] );
c277df42 1124 return (last && found) ? (char *)(big+(*old_posp)) : Nullch;
de3bb511 1125#endif /* POINTERRIGOR */
8d063cd8
LW
1126}
1127
79072805 1128I32
8ac85365 1129ibcmp(char *s1, char *s2, register I32 len)
79072805 1130{
bbce6d69 1131 register U8 *a = (U8 *)s1;
1132 register U8 *b = (U8 *)s2;
79072805 1133 while (len--) {
bbce6d69 1134 if (*a != *b && *a != fold[*b])
1135 return 1;
1136 a++,b++;
1137 }
1138 return 0;
1139}
1140
1141I32
8ac85365 1142ibcmp_locale(char *s1, char *s2, register I32 len)
bbce6d69 1143{
1144 register U8 *a = (U8 *)s1;
1145 register U8 *b = (U8 *)s2;
1146 while (len--) {
1147 if (*a != *b && *a != fold_locale[*b])
1148 return 1;
1149 a++,b++;
79072805
LW
1150 }
1151 return 0;
1152}
1153
8d063cd8
LW
1154/* copy a string to a safe spot */
1155
1156char *
8ac85365 1157savepv(char *sv)
8d063cd8 1158{
a687059c 1159 register char *newaddr;
8d063cd8 1160
79072805
LW
1161 New(902,newaddr,strlen(sv)+1,char);
1162 (void)strcpy(newaddr,sv);
8d063cd8
LW
1163 return newaddr;
1164}
1165
a687059c
LW
1166/* same thing but with a known length */
1167
1168char *
8ac85365 1169savepvn(char *sv, register I32 len)
a687059c
LW
1170{
1171 register char *newaddr;
1172
1173 New(903,newaddr,len+1,char);
79072805 1174 Copy(sv,newaddr,len,char); /* might not be null terminated */
a687059c
LW
1175 newaddr[len] = '\0'; /* is now */
1176 return newaddr;
1177}
1178
fc36a67e 1179/* the SV for form() and mess() is not kept in an arena */
1180
76e3520e 1181STATIC SV *
8ac85365 1182mess_alloc(void)
fc36a67e 1183{
1184 SV *sv;
1185 XPVMG *any;
1186
1187 /* Create as PVMG now, to avoid any upgrading later */
1188 New(905, sv, 1, SV);
1189 Newz(905, any, 1, XPVMG);
1190 SvFLAGS(sv) = SVt_PVMG;
1191 SvANY(sv) = (void*)any;
1192 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1193 return sv;
1194}
1195
8990e307 1196char *
46fc3d4c 1197form(const char* pat, ...)
8990e307 1198{
46fc3d4c 1199 va_list args;
46fc3d4c 1200 va_start(args, pat);
fc36a67e 1201 if (!mess_sv)
1202 mess_sv = mess_alloc();
1203 sv_vsetpvfn(mess_sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*));
46fc3d4c 1204 va_end(args);
fc36a67e 1205 return SvPVX(mess_sv);
46fc3d4c 1206}
a687059c 1207
46fc3d4c 1208char *
8ac85365 1209mess(const char *pat, va_list *args)
46fc3d4c 1210{
1211 SV *sv;
1212 static char dgd[] = " during global destruction.\n";
1213
46fc3d4c 1214 if (!mess_sv)
fc36a67e 1215 mess_sv = mess_alloc();
46fc3d4c 1216 sv = mess_sv;
fc36a67e 1217 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
46fc3d4c 1218 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
e858de61 1219 dTHR;
2304df62 1220 if (dirty)
46fc3d4c 1221 sv_catpv(sv, dgd);
2304df62 1222 else {
46fc3d4c 1223 if (curcop->cop_line)
fc36a67e 1224 sv_catpvf(sv, " at %_ line %ld",
46fc3d4c 1225 GvSV(curcop->cop_filegv), (long)curcop->cop_line);
c07a80fd 1226 if (GvIO(last_in_gv) && IoLINES(GvIOp(last_in_gv))) {
1227 bool line_mode = (RsSIMPLE(rs) &&
1228 SvLEN(rs) == 1 && *SvPVX(rs) == '\n');
46fc3d4c 1229 sv_catpvf(sv, ", <%s> %s %ld",
1230 last_in_gv == argvgv ? "" : GvNAME(last_in_gv),
1231 line_mode ? "line" : "chunk",
1232 (long)IoLINES(GvIOp(last_in_gv)));
2304df62 1233 }
46fc3d4c 1234 sv_catpv(sv, ".\n");
a687059c 1235 }
a687059c 1236 }
46fc3d4c 1237 return SvPVX(sv);
a687059c
LW
1238}
1239
36477c24 1240OP *
71be2cbc 1241die(const char* pat, ...)
36477c24 1242{
5dc0d613 1243 dTHR;
36477c24 1244 va_list args;
1245 char *message;
36477c24 1246 int was_in_eval = in_eval;
1247 HV *stash;
1248 GV *gv;
1249 CV *cv;
1250
57d3b86d 1251#ifdef USE_THREADS
199100c8
MB
1252 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
1253 "%p: die: curstack = %p, mainstack = %p\n",
1254 thr, curstack, mainstack));
57d3b86d 1255#endif /* USE_THREADS */
36477c24 1256
36477c24 1257 va_start(args, pat);
4e6ea2c3 1258 message = pat ? mess(pat, &args) : Nullch;
36477c24 1259 va_end(args);
1260
57d3b86d 1261#ifdef USE_THREADS
199100c8
MB
1262 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
1263 "%p: die: message = %s\ndiehook = %p\n",
1264 thr, message, diehook));
57d3b86d 1265#endif /* USE_THREADS */
1738f5c4
CS
1266 if (diehook) {
1267 /* sv_2cv might call croak() */
1268 SV *olddiehook = diehook;
1269 ENTER;
1270 SAVESPTR(diehook);
1271 diehook = Nullsv;
1272 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1273 LEAVE;
1274 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1275 dSP;
774d564b 1276 SV *msg;
1277
1278 ENTER;
4e6ea2c3
GS
1279 if(message) {
1280 msg = newSVpv(message, 0);
1281 SvREADONLY_on(msg);
1282 SAVEFREESV(msg);
1283 }
1284 else {
1285 msg = ERRSV;
1286 }
1738f5c4 1287
8931a351 1288 PUSHSTACK(SI_DIEHOOK);
924508f0 1289 PUSHMARK(SP);
1738f5c4
CS
1290 XPUSHs(msg);
1291 PUTBACK;
1292 perl_call_sv((SV*)cv, G_DISCARD);
8931a351 1293 POPSTACK();
774d564b 1294 LEAVE;
1738f5c4 1295 }
36477c24 1296 }
1297
1298 restartop = die_where(message);
57d3b86d 1299#ifdef USE_THREADS
d9f997d7 1300 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
7c06b590
GS
1301 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1302 thr, restartop, was_in_eval, top_env));
57d3b86d 1303#endif /* USE_THREADS */
7c06b590 1304 if ((!restartop && was_in_eval) || top_env->je_prev)
54310121 1305 JMPENV_JUMP(3);
36477c24 1306 return restartop;
1307}
1308
79072805 1309void
71be2cbc 1310croak(const char* pat, ...)
a687059c 1311{
11343788 1312 dTHR;
a687059c 1313 va_list args;
de3bb511 1314 char *message;
748a9306
LW
1315 HV *stash;
1316 GV *gv;
1317 CV *cv;
a687059c 1318
8990e307 1319 va_start(args, pat);
2304df62 1320 message = mess(pat, &args);
a687059c 1321 va_end(args);
11343788 1322#ifdef USE_THREADS
d9f997d7 1323 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
11343788 1324#endif /* USE_THREADS */
20cec16a 1325 if (diehook) {
1738f5c4 1326 /* sv_2cv might call croak() */
20cec16a 1327 SV *olddiehook = diehook;
1738f5c4
CS
1328 ENTER;
1329 SAVESPTR(diehook);
1330 diehook = Nullsv;
20cec16a 1331 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1738f5c4
CS
1332 LEAVE;
1333 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
20cec16a 1334 dSP;
774d564b 1335 SV *msg;
1336
1337 ENTER;
1338 msg = newSVpv(message, 0);
1339 SvREADONLY_on(msg);
1340 SAVEFREESV(msg);
20cec16a 1341
8931a351 1342 PUSHSTACK(SI_DIEHOOK);
924508f0 1343 PUSHMARK(SP);
1738f5c4 1344 XPUSHs(msg);
20cec16a 1345 PUTBACK;
1346 perl_call_sv((SV*)cv, G_DISCARD);
8931a351 1347 POPSTACK();
774d564b 1348 LEAVE;
20cec16a 1349 }
748a9306 1350 }
a0d0e21e
LW
1351 if (in_eval) {
1352 restartop = die_where(message);
54310121 1353 JMPENV_JUMP(3);
a0d0e21e 1354 }
760ac839
LW
1355 PerlIO_puts(PerlIO_stderr(),message);
1356 (void)PerlIO_flush(PerlIO_stderr());
f86702cc 1357 my_failure_exit();
a687059c
LW
1358}
1359
8990e307 1360void
71be2cbc 1361warn(const char* pat,...)
a687059c
LW
1362{
1363 va_list args;
de3bb511 1364 char *message;
748a9306
LW
1365 HV *stash;
1366 GV *gv;
1367 CV *cv;
a687059c 1368
8990e307 1369 va_start(args, pat);
2304df62 1370 message = mess(pat, &args);
a687059c
LW
1371 va_end(args);
1372
20cec16a 1373 if (warnhook) {
1738f5c4 1374 /* sv_2cv might call warn() */
11343788 1375 dTHR;
20cec16a 1376 SV *oldwarnhook = warnhook;
1738f5c4
CS
1377 ENTER;
1378 SAVESPTR(warnhook);
1379 warnhook = Nullsv;
20cec16a 1380 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1738f5c4
CS
1381 LEAVE;
1382 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
20cec16a 1383 dSP;
774d564b 1384 SV *msg;
1385
1386 ENTER;
1387 msg = newSVpv(message, 0);
1388 SvREADONLY_on(msg);
1389 SAVEFREESV(msg);
1390
8931a351 1391 PUSHSTACK(SI_WARNHOOK);
924508f0 1392 PUSHMARK(SP);
774d564b 1393 XPUSHs(msg);
20cec16a 1394 PUTBACK;
1395 perl_call_sv((SV*)cv, G_DISCARD);
8931a351 1396 POPSTACK();
774d564b 1397 LEAVE;
20cec16a 1398 return;
1399 }
748a9306 1400 }
20cec16a 1401 PerlIO_puts(PerlIO_stderr(),message);
a687059c 1402#ifdef LEAKTEST
8c52afec
IZ
1403 DEBUG_L(*message == '!'
1404 ? (xstat(message[1]=='!'
1405 ? (message[2]=='!' ? 2 : 1)
1406 : 0)
1407 , 0)
1408 : 0);
a687059c 1409#endif
20cec16a 1410 (void)PerlIO_flush(PerlIO_stderr());
a687059c 1411}
8d063cd8 1412
a0d0e21e 1413#ifndef VMS /* VMS' my_setenv() is in VMS.c */
3e3baf6d 1414#ifndef WIN32
8d063cd8 1415void
8ac85365 1416my_setenv(char *nam, char *val)
8d063cd8 1417{
79072805 1418 register I32 i=setenv_getix(nam); /* where does it go? */
8d063cd8 1419
fe14fcc3 1420 if (environ == origenviron) { /* need we copy environment? */
79072805
LW
1421 I32 j;
1422 I32 max;
fe14fcc3
LW
1423 char **tmpenv;
1424
de3bb511 1425 /*SUPPRESS 530*/
fe14fcc3
LW
1426 for (max = i; environ[max]; max++) ;
1427 New(901,tmpenv, max+2, char*);
1428 for (j=0; j<max; j++) /* copy environment */
a0d0e21e 1429 tmpenv[j] = savepv(environ[j]);
fe14fcc3
LW
1430 tmpenv[max] = Nullch;
1431 environ = tmpenv; /* tell exec where it is now */
1432 }
a687059c 1433 if (!val) {
e5ebf479 1434 Safefree(environ[i]);
a687059c
LW
1435 while (environ[i]) {
1436 environ[i] = environ[i+1];
1437 i++;
1438 }
1439 return;
1440 }
8d063cd8 1441 if (!environ[i]) { /* does not exist yet */
fe14fcc3 1442 Renew(environ, i+2, char*); /* just expand it a bit */
8d063cd8
LW
1443 environ[i+1] = Nullch; /* make sure it's null terminated */
1444 }
fe14fcc3
LW
1445 else
1446 Safefree(environ[i]);
a687059c 1447 New(904, environ[i], strlen(nam) + strlen(val) + 2, char);
62b28dd9 1448#ifndef MSDOS
a687059c 1449 (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
62b28dd9
LW
1450#else
1451 /* MS-DOS requires environment variable names to be in uppercase */
fe14fcc3
LW
1452 /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
1453 * some utilities and applications may break because they only look
1454 * for upper case strings. (Fixed strupr() bug here.)]
1455 */
1456 strcpy(environ[i],nam); strupr(environ[i]);
62b28dd9
LW
1457 (void)sprintf(environ[i] + strlen(nam),"=%s",val);
1458#endif /* MSDOS */
8d063cd8
LW
1459}
1460
3e3baf6d 1461#else /* if WIN32 */
68dc0745 1462
1463void
4e35701f 1464my_setenv(char *nam,char *val)
68dc0745 1465{
3e3baf6d
TB
1466
1467#ifdef USE_WIN32_RTL_ENV
1468
68dc0745 1469 register char *envstr;
1470 STRLEN namlen = strlen(nam);
3e3baf6d
TB
1471 STRLEN vallen;
1472 char *oldstr = environ[setenv_getix(nam)];
1473
1474 /* putenv() has totally broken semantics in both the Borland
1475 * and Microsoft CRTLs. They either store the passed pointer in
1476 * the environment without making a copy, or make a copy and don't
1477 * free it. And on top of that, they dont free() old entries that
1478 * are being replaced/deleted. This means the caller must
1479 * free any old entries somehow, or we end up with a memory
1480 * leak every time my_setenv() is called. One might think
1481 * one could directly manipulate environ[], like the UNIX code
1482 * above, but direct changes to environ are not allowed when
1483 * calling putenv(), since the RTLs maintain an internal
1484 * *copy* of environ[]. Bad, bad, *bad* stink.
1485 * GSAR 97-06-07
1486 */
68dc0745 1487
3e3baf6d
TB
1488 if (!val) {
1489 if (!oldstr)
1490 return;
1491 val = "";
1492 vallen = 0;
1493 }
1494 else
1495 vallen = strlen(val);
fc36a67e 1496 New(904, envstr, namlen + vallen + 3, char);
68dc0745 1497 (void)sprintf(envstr,"%s=%s",nam,val);
76e3520e 1498 (void)PerlEnv_putenv(envstr);
3e3baf6d
TB
1499 if (oldstr)
1500 Safefree(oldstr);
1501#ifdef _MSC_VER
1502 Safefree(envstr); /* MSVCRT leaks without this */
1503#endif
1504
1505#else /* !USE_WIN32_RTL_ENV */
1506
1507 /* The sane way to deal with the environment.
1508 * Has these advantages over putenv() & co.:
1509 * * enables us to store a truly empty value in the
1510 * environment (like in UNIX).
1511 * * we don't have to deal with RTL globals, bugs and leaks.
1512 * * Much faster.
1513 * Why you may want to enable USE_WIN32_RTL_ENV:
1514 * * environ[] and RTL functions will not reflect changes,
1515 * which might be an issue if extensions want to access
1516 * the env. via RTL. This cuts both ways, since RTL will
1517 * not see changes made by extensions that call the Win32
1518 * functions directly, either.
1519 * GSAR 97-06-07
1520 */
1521 SetEnvironmentVariable(nam,val);
1522
1523#endif
1524}
1525
1526#endif /* WIN32 */
1527
1528I32
8ac85365 1529setenv_getix(char *nam)
3e3baf6d
TB
1530{
1531 register I32 i, len = strlen(nam);
1532
1533 for (i = 0; environ[i]; i++) {
1534 if (
1535#ifdef WIN32
1536 strnicmp(environ[i],nam,len) == 0
1537#else
1538 strnEQ(environ[i],nam,len)
1539#endif
1540 && environ[i][len] == '=')
1541 break; /* strnEQ must come first to avoid */
1542 } /* potential SEGV's */
1543 return i;
68dc0745 1544}
1545
a0d0e21e 1546#endif /* !VMS */
378cc40b 1547
16d20bd9 1548#ifdef UNLINK_ALL_VERSIONS
79072805 1549I32
378cc40b
LW
1550unlnk(f) /* unlink all versions of a file */
1551char *f;
1552{
79072805 1553 I32 i;
378cc40b 1554
6ad3d225 1555 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
378cc40b
LW
1556 return i ? 0 : -1;
1557}
1558#endif
1559
85e6fe83 1560#if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
378cc40b 1561char *
4e35701f 1562my_bcopy(register char *from,register char *to,register I32 len)
378cc40b
LW
1563{
1564 char *retval = to;
1565
7c0587c8
LW
1566 if (from - to >= 0) {
1567 while (len--)
1568 *to++ = *from++;
1569 }
1570 else {
1571 to += len;
1572 from += len;
1573 while (len--)
faf8582f 1574 *(--to) = *(--from);
7c0587c8 1575 }
378cc40b
LW
1576 return retval;
1577}
ffed7fef 1578#endif
378cc40b 1579
fc36a67e 1580#ifndef HAS_MEMSET
1581void *
1582my_memset(loc,ch,len)
1583register char *loc;
1584register I32 ch;
1585register I32 len;
1586{
1587 char *retval = loc;
1588
1589 while (len--)
1590 *loc++ = ch;
1591 return retval;
1592}
1593#endif
1594
7c0587c8 1595#if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
378cc40b 1596char *
7c0587c8 1597my_bzero(loc,len)
378cc40b 1598register char *loc;
79072805 1599register I32 len;
378cc40b
LW
1600{
1601 char *retval = loc;
1602
1603 while (len--)
1604 *loc++ = 0;
1605 return retval;
1606}
1607#endif
7c0587c8 1608
36477c24 1609#if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
79072805 1610I32
7c0587c8 1611my_memcmp(s1,s2,len)
36477c24 1612char *s1;
1613char *s2;
79072805 1614register I32 len;
7c0587c8 1615{
36477c24 1616 register U8 *a = (U8 *)s1;
1617 register U8 *b = (U8 *)s2;
79072805 1618 register I32 tmp;
7c0587c8
LW
1619
1620 while (len--) {
36477c24 1621 if (tmp = *a++ - *b++)
7c0587c8
LW
1622 return tmp;
1623 }
1624 return 0;
1625}
36477c24 1626#endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
a687059c 1627
fe14fcc3 1628#ifndef HAS_VPRINTF
a687059c 1629
85e6fe83 1630#ifdef USE_CHAR_VSPRINTF
a687059c
LW
1631char *
1632#else
1633int
1634#endif
1635vsprintf(dest, pat, args)
71be2cbc 1636char *dest;
1637const char *pat;
1638char *args;
a687059c
LW
1639{
1640 FILE fakebuf;
1641
1642 fakebuf._ptr = dest;
1643 fakebuf._cnt = 32767;
35c8bce7
LW
1644#ifndef _IOSTRG
1645#define _IOSTRG 0
1646#endif
a687059c
LW
1647 fakebuf._flag = _IOWRT|_IOSTRG;
1648 _doprnt(pat, args, &fakebuf); /* what a kludge */
1649 (void)putc('\0', &fakebuf);
85e6fe83 1650#ifdef USE_CHAR_VSPRINTF
a687059c
LW
1651 return(dest);
1652#else
1653 return 0; /* perl doesn't use return value */
1654#endif
1655}
1656
fe14fcc3 1657#endif /* HAS_VPRINTF */
a687059c
LW
1658
1659#ifdef MYSWAP
ffed7fef 1660#if BYTEORDER != 0x4321
a687059c 1661short
748a9306 1662my_swap(short s)
a687059c
LW
1663{
1664#if (BYTEORDER & 1) == 0
1665 short result;
1666
1667 result = ((s & 255) << 8) + ((s >> 8) & 255);
1668 return result;
1669#else
1670 return s;
1671#endif
1672}
1673
1674long
748a9306 1675my_htonl(long l)
a687059c
LW
1676{
1677 union {
1678 long result;
ffed7fef 1679 char c[sizeof(long)];
a687059c
LW
1680 } u;
1681
ffed7fef 1682#if BYTEORDER == 0x1234
a687059c
LW
1683 u.c[0] = (l >> 24) & 255;
1684 u.c[1] = (l >> 16) & 255;
1685 u.c[2] = (l >> 8) & 255;
1686 u.c[3] = l & 255;
1687 return u.result;
1688#else
ffed7fef 1689#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
463ee0b2 1690 croak("Unknown BYTEORDER\n");
a687059c 1691#else
79072805
LW
1692 register I32 o;
1693 register I32 s;
a687059c 1694
ffed7fef
LW
1695 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1696 u.c[o & 0xf] = (l >> s) & 255;
a687059c
LW
1697 }
1698 return u.result;
1699#endif
1700#endif
1701}
1702
1703long
748a9306 1704my_ntohl(long l)
a687059c
LW
1705{
1706 union {
1707 long l;
ffed7fef 1708 char c[sizeof(long)];
a687059c
LW
1709 } u;
1710
ffed7fef 1711#if BYTEORDER == 0x1234
a687059c
LW
1712 u.c[0] = (l >> 24) & 255;
1713 u.c[1] = (l >> 16) & 255;
1714 u.c[2] = (l >> 8) & 255;
1715 u.c[3] = l & 255;
1716 return u.l;
1717#else
ffed7fef 1718#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
463ee0b2 1719 croak("Unknown BYTEORDER\n");
a687059c 1720#else
79072805
LW
1721 register I32 o;
1722 register I32 s;
a687059c
LW
1723
1724 u.l = l;
1725 l = 0;
ffed7fef
LW
1726 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1727 l |= (u.c[o & 0xf] & 255) << s;
a687059c
LW
1728 }
1729 return l;
1730#endif
1731#endif
1732}
1733
ffed7fef 1734#endif /* BYTEORDER != 0x4321 */
988174c1
LW
1735#endif /* MYSWAP */
1736
1737/*
1738 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1739 * If these functions are defined,
1740 * the BYTEORDER is neither 0x1234 nor 0x4321.
1741 * However, this is not assumed.
1742 * -DWS
1743 */
1744
1745#define HTOV(name,type) \
1746 type \
1747 name (n) \
1748 register type n; \
1749 { \
1750 union { \
1751 type value; \
1752 char c[sizeof(type)]; \
1753 } u; \
79072805
LW
1754 register I32 i; \
1755 register I32 s; \
988174c1
LW
1756 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1757 u.c[i] = (n >> s) & 0xFF; \
1758 } \
1759 return u.value; \
1760 }
1761
1762#define VTOH(name,type) \
1763 type \
1764 name (n) \
1765 register type n; \
1766 { \
1767 union { \
1768 type value; \
1769 char c[sizeof(type)]; \
1770 } u; \
79072805
LW
1771 register I32 i; \
1772 register I32 s; \
988174c1
LW
1773 u.value = n; \
1774 n = 0; \
1775 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1776 n += (u.c[i] & 0xFF) << s; \
1777 } \
1778 return n; \
1779 }
1780
1781#if defined(HAS_HTOVS) && !defined(htovs)
1782HTOV(htovs,short)
1783#endif
1784#if defined(HAS_HTOVL) && !defined(htovl)
1785HTOV(htovl,long)
1786#endif
1787#if defined(HAS_VTOHS) && !defined(vtohs)
1788VTOH(vtohs,short)
1789#endif
1790#if defined(HAS_VTOHL) && !defined(vtohl)
1791VTOH(vtohl,long)
1792#endif
a687059c 1793
5f05dabc 1794 /* VMS' my_popen() is in VMS.c, same with OS/2. */
1795#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS)
760ac839 1796PerlIO *
8ac85365 1797my_popen(char *cmd, char *mode)
a687059c
LW
1798{
1799 int p[2];
8ac85365 1800 register I32 This, that;
79072805
LW
1801 register I32 pid;
1802 SV *sv;
1738f5c4 1803 I32 doexec = strNE(cmd,"-");
a687059c 1804
ddcf38b7
IZ
1805#ifdef OS2
1806 if (doexec) {
1807 return my_syspopen(cmd,mode);
1808 }
1809#endif
8ac85365
NIS
1810 This = (*mode == 'w');
1811 that = !This;
bbce6d69 1812 if (doexec && tainting) {
1813 taint_env();
1814 taint_proper("Insecure %s%s", "EXEC");
d48672a2 1815 }
c2267164
IZ
1816 if (PerlProc_pipe(p) < 0)
1817 return Nullfp;
a687059c
LW
1818 while ((pid = (doexec?vfork():fork())) < 0) {
1819 if (errno != EAGAIN) {
6ad3d225 1820 PerlLIO_close(p[This]);
a687059c 1821 if (!doexec)
463ee0b2 1822 croak("Can't fork");
a687059c
LW
1823 return Nullfp;
1824 }
1825 sleep(5);
1826 }
1827 if (pid == 0) {
79072805
LW
1828 GV* tmpgv;
1829
30ac6d9b
GS
1830#undef THIS
1831#undef THAT
a687059c 1832#define THIS that
8ac85365 1833#define THAT This
6ad3d225 1834 PerlLIO_close(p[THAT]);
a687059c 1835 if (p[THIS] != (*mode == 'r')) {
6ad3d225
GS
1836 PerlLIO_dup2(p[THIS], *mode == 'r');
1837 PerlLIO_close(p[THIS]);
a687059c
LW
1838 }
1839 if (doexec) {
a0d0e21e 1840#if !defined(HAS_FCNTL) || !defined(F_SETFD)
ae986130
LW
1841 int fd;
1842
1843#ifndef NOFILE
1844#define NOFILE 20
1845#endif
d48672a2 1846 for (fd = maxsysfd + 1; fd < NOFILE; fd++)
6ad3d225 1847 PerlLIO_close(fd);
ae986130 1848#endif
a687059c 1849 do_exec(cmd); /* may or may not use the shell */
6ad3d225 1850 PerlProc__exit(1);
a687059c 1851 }
de3bb511 1852 /*SUPPRESS 560*/
85e6fe83 1853 if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
1e422769 1854 sv_setiv(GvSV(tmpgv), (IV)getpid());
9f68db38 1855 forkprocess = 0;
463ee0b2 1856 hv_clear(pidstatus); /* we have no children */
a687059c
LW
1857 return Nullfp;
1858#undef THIS
1859#undef THAT
1860 }
62b28dd9 1861 do_execfree(); /* free any memory malloced by child on vfork */
6ad3d225 1862 PerlLIO_close(p[that]);
8ac85365 1863 if (p[that] < p[This]) {
6ad3d225
GS
1864 PerlLIO_dup2(p[This], p[that]);
1865 PerlLIO_close(p[This]);
8ac85365 1866 p[This] = p[that];
62b28dd9 1867 }
8ac85365 1868 sv = *av_fetch(fdpid,p[This],TRUE);
a0d0e21e 1869 (void)SvUPGRADE(sv,SVt_IV);
463ee0b2 1870 SvIVX(sv) = pid;
a687059c 1871 forkprocess = pid;
8ac85365 1872 return PerlIO_fdopen(p[This], mode);
a687059c 1873}
7c0587c8 1874#else
55497cff 1875#if defined(atarist) || defined(DJGPP)
7c0587c8 1876FILE *popen();
760ac839 1877PerlIO *
79072805 1878my_popen(cmd,mode)
7c0587c8
LW
1879char *cmd;
1880char *mode;
1881{
760ac839 1882 /* Needs work for PerlIO ! */
55497cff 1883 /* used 0 for 2nd parameter to PerlIO-exportFILE; apparently not used */
1884 return popen(PerlIO_exportFILE(cmd, 0), mode);
7c0587c8
LW
1885}
1886#endif
1887
1888#endif /* !DOSISH */
a687059c 1889
748a9306 1890#ifdef DUMP_FDS
35ff7856
GS
1891void
1892dump_fds(char *s)
ae986130
LW
1893{
1894 int fd;
1895 struct stat tmpstatbuf;
1896
760ac839 1897 PerlIO_printf(PerlIO_stderr(),"%s", s);
ae986130 1898 for (fd = 0; fd < 32; fd++) {
6ad3d225 1899 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
760ac839 1900 PerlIO_printf(PerlIO_stderr()," %d",fd);
ae986130 1901 }
760ac839 1902 PerlIO_printf(PerlIO_stderr(),"\n");
ae986130 1903}
35ff7856 1904#endif /* DUMP_FDS */
ae986130 1905
fe14fcc3 1906#ifndef HAS_DUP2
fec02dd3 1907int
a687059c
LW
1908dup2(oldfd,newfd)
1909int oldfd;
1910int newfd;
1911{
a0d0e21e 1912#if defined(HAS_FCNTL) && defined(F_DUPFD)
fec02dd3
AD
1913 if (oldfd == newfd)
1914 return oldfd;
6ad3d225 1915 PerlLIO_close(newfd);
fec02dd3 1916 return fcntl(oldfd, F_DUPFD, newfd);
62b28dd9 1917#else
fc36a67e 1918#define DUP2_MAX_FDS 256
1919 int fdtmp[DUP2_MAX_FDS];
79072805 1920 I32 fdx = 0;
ae986130
LW
1921 int fd;
1922
fe14fcc3 1923 if (oldfd == newfd)
fec02dd3 1924 return oldfd;
6ad3d225 1925 PerlLIO_close(newfd);
fc36a67e 1926 /* good enough for low fd's... */
6ad3d225 1927 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
fc36a67e 1928 if (fdx >= DUP2_MAX_FDS) {
6ad3d225 1929 PerlLIO_close(fd);
fc36a67e 1930 fd = -1;
1931 break;
1932 }
ae986130 1933 fdtmp[fdx++] = fd;
fc36a67e 1934 }
ae986130 1935 while (fdx > 0)
6ad3d225 1936 PerlLIO_close(fdtmp[--fdx]);
fec02dd3 1937 return fd;
62b28dd9 1938#endif
a687059c
LW
1939}
1940#endif
1941
ff68c719 1942
1943#ifdef HAS_SIGACTION
1944
1945Sighandler_t
8ac85365 1946rsignal(int signo, Sighandler_t handler)
ff68c719 1947{
1948 struct sigaction act, oact;
1949
1950 act.sa_handler = handler;
1951 sigemptyset(&act.sa_mask);
1952 act.sa_flags = 0;
1953#ifdef SA_RESTART
1954 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
1955#endif
1956 if (sigaction(signo, &act, &oact) == -1)
36477c24 1957 return SIG_ERR;
ff68c719 1958 else
36477c24 1959 return oact.sa_handler;
ff68c719 1960}
1961
1962Sighandler_t
8ac85365 1963rsignal_state(int signo)
ff68c719 1964{
1965 struct sigaction oact;
1966
1967 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
1968 return SIG_ERR;
1969 else
1970 return oact.sa_handler;
1971}
1972
1973int
8ac85365 1974rsignal_save(int signo, Sighandler_t handler, Sigsave_t *save)
ff68c719 1975{
1976 struct sigaction act;
1977
1978 act.sa_handler = handler;
1979 sigemptyset(&act.sa_mask);
1980 act.sa_flags = 0;
1981#ifdef SA_RESTART
1982 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
1983#endif
1984 return sigaction(signo, &act, save);
1985}
1986
1987int
8ac85365 1988rsignal_restore(int signo, Sigsave_t *save)
ff68c719 1989{
1990 return sigaction(signo, save, (struct sigaction *)NULL);
1991}
1992
1993#else /* !HAS_SIGACTION */
1994
1995Sighandler_t
4e35701f 1996rsignal(int signo, Sighandler_t handler)
ff68c719 1997{
6ad3d225 1998 return PerlProc_signal(signo, handler);
ff68c719 1999}
2000
2001static int sig_trapped;
2002
2003static
2004Signal_t
4e35701f 2005sig_trap(int signo)
ff68c719 2006{
2007 sig_trapped++;
2008}
2009
2010Sighandler_t
4e35701f 2011rsignal_state(int signo)
ff68c719 2012{
2013 Sighandler_t oldsig;
2014
2015 sig_trapped = 0;
6ad3d225
GS
2016 oldsig = PerlProc_signal(signo, sig_trap);
2017 PerlProc_signal(signo, oldsig);
ff68c719 2018 if (sig_trapped)
6ad3d225 2019 PerlProc_kill(getpid(), signo);
ff68c719 2020 return oldsig;
2021}
2022
2023int
4e35701f 2024rsignal_save(int signo, Sighandler_t handler, Sigsave_t *save)
ff68c719 2025{
6ad3d225 2026 *save = PerlProc_signal(signo, handler);
ff68c719 2027 return (*save == SIG_ERR) ? -1 : 0;
2028}
2029
2030int
4e35701f 2031rsignal_restore(int signo, Sigsave_t *save)
ff68c719 2032{
6ad3d225 2033 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
ff68c719 2034}
2035
2036#endif /* !HAS_SIGACTION */
2037
5f05dabc 2038 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2039#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS)
79072805 2040I32
6acef3b7 2041my_pclose(PerlIO *ptr)
a687059c 2042{
ff68c719 2043 Sigsave_t hstat, istat, qstat;
a687059c 2044 int status;
a0d0e21e 2045 SV **svp;
20188a90 2046 int pid;
1d3434b8 2047 int pid2;
03136e13
CS
2048 bool close_failed;
2049 int saved_errno;
2050#ifdef VMS
2051 int saved_vaxc_errno;
2052#endif
22fae026
TM
2053#ifdef WIN32
2054 int saved_win32_errno;
2055#endif
a687059c 2056
760ac839 2057 svp = av_fetch(fdpid,PerlIO_fileno(ptr),TRUE);
748a9306 2058 pid = (int)SvIVX(*svp);
a0d0e21e
LW
2059 SvREFCNT_dec(*svp);
2060 *svp = &sv_undef;
ddcf38b7
IZ
2061#ifdef OS2
2062 if (pid == -1) { /* Opened by popen. */
2063 return my_syspclose(ptr);
2064 }
2065#endif
03136e13
CS
2066 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2067 saved_errno = errno;
2068#ifdef VMS
2069 saved_vaxc_errno = vaxc$errno;
2070#endif
22fae026
TM
2071#ifdef WIN32
2072 saved_win32_errno = GetLastError();
2073#endif
03136e13 2074 }
7c0587c8 2075#ifdef UTS
6ad3d225 2076 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
7c0587c8 2077#endif
ff68c719 2078 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2079 rsignal_save(SIGINT, SIG_IGN, &istat);
2080 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
748a9306 2081 do {
1d3434b8
GS
2082 pid2 = wait4pid(pid, &status, 0);
2083 } while (pid2 == -1 && errno == EINTR);
ff68c719 2084 rsignal_restore(SIGHUP, &hstat);
2085 rsignal_restore(SIGINT, &istat);
2086 rsignal_restore(SIGQUIT, &qstat);
03136e13
CS
2087 if (close_failed) {
2088 SETERRNO(saved_errno, saved_vaxc_errno);
2089 return -1;
2090 }
1d3434b8 2091 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
20188a90 2092}
4633a7c4
LW
2093#endif /* !DOSISH */
2094
2d7a9237 2095#if !defined(DOSISH) || defined(OS2) || defined(WIN32)
79072805 2096I32
8ac85365 2097wait4pid(int pid, int *statusp, int flags)
20188a90 2098{
79072805
LW
2099 SV *sv;
2100 SV** svp;
fc36a67e 2101 char spid[TYPE_CHARS(int)];
20188a90
LW
2102
2103 if (!pid)
2104 return -1;
20188a90
LW
2105 if (pid > 0) {
2106 sprintf(spid, "%d", pid);
79072805
LW
2107 svp = hv_fetch(pidstatus,spid,strlen(spid),FALSE);
2108 if (svp && *svp != &sv_undef) {
463ee0b2 2109 *statusp = SvIVX(*svp);
748a9306 2110 (void)hv_delete(pidstatus,spid,strlen(spid),G_DISCARD);
20188a90
LW
2111 return pid;
2112 }
2113 }
2114 else {
79072805 2115 HE *entry;
20188a90 2116
79072805
LW
2117 hv_iterinit(pidstatus);
2118 if (entry = hv_iternext(pidstatus)) {
a0d0e21e 2119 pid = atoi(hv_iterkey(entry,(I32*)statusp));
79072805 2120 sv = hv_iterval(pidstatus,entry);
463ee0b2 2121 *statusp = SvIVX(sv);
20188a90 2122 sprintf(spid, "%d", pid);
748a9306 2123 (void)hv_delete(pidstatus,spid,strlen(spid),G_DISCARD);
20188a90
LW
2124 return pid;
2125 }
2126 }
79072805 2127#ifdef HAS_WAITPID
367f3c24
IZ
2128# ifdef HAS_WAITPID_RUNTIME
2129 if (!HAS_WAITPID_RUNTIME)
2130 goto hard_way;
2131# endif
79072805 2132 return waitpid(pid,statusp,flags);
367f3c24
IZ
2133#endif
2134#if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
a0d0e21e 2135 return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
367f3c24
IZ
2136#endif
2137#if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2138 hard_way:
a0d0e21e
LW
2139 {
2140 I32 result;
2141 if (flags)
2142 croak("Can't do waitpid with flags");
2143 else {
76e3520e 2144 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
a0d0e21e
LW
2145 pidgone(result,*statusp);
2146 if (result < 0)
2147 *statusp = -1;
2148 }
2149 return result;
a687059c
LW
2150 }
2151#endif
a687059c 2152}
2d7a9237 2153#endif /* !DOSISH || OS2 || WIN32 */
a687059c 2154
7c0587c8 2155void
de3bb511 2156/*SUPPRESS 590*/
8ac85365 2157pidgone(int pid, int status)
a687059c 2158{
79072805 2159 register SV *sv;
fc36a67e 2160 char spid[TYPE_CHARS(int)];
a687059c 2161
20188a90 2162 sprintf(spid, "%d", pid);
79072805 2163 sv = *hv_fetch(pidstatus,spid,strlen(spid),TRUE);
a0d0e21e 2164 (void)SvUPGRADE(sv,SVt_IV);
463ee0b2 2165 SvIVX(sv) = status;
20188a90 2166 return;
a687059c
LW
2167}
2168
55497cff 2169#if defined(atarist) || defined(OS2) || defined(DJGPP)
7c0587c8 2170int pclose();
ddcf38b7
IZ
2171#ifdef HAS_FORK
2172int /* Cannot prototype with I32
2173 in os2ish.h. */
2174my_syspclose(ptr)
2175#else
79072805
LW
2176I32
2177my_pclose(ptr)
ddcf38b7 2178#endif
760ac839 2179PerlIO *ptr;
a687059c 2180{
760ac839
LW
2181 /* Needs work for PerlIO ! */
2182 FILE *f = PerlIO_findFILE(ptr);
2183 I32 result = pclose(f);
2184 PerlIO_releaseFILE(ptr,f);
2185 return result;
a687059c 2186}
7c0587c8 2187#endif
9f68db38
LW
2188
2189void
8ac85365 2190repeatcpy(register char *to, register char *from, I32 len, register I32 count)
9f68db38 2191{
79072805 2192 register I32 todo;
9f68db38
LW
2193 register char *frombase = from;
2194
2195 if (len == 1) {
2196 todo = *from;
2197 while (count-- > 0)
2198 *to++ = todo;
2199 return;
2200 }
2201 while (count-- > 0) {
2202 for (todo = len; todo > 0; todo--) {
2203 *to++ = *from++;
2204 }
2205 from = frombase;
2206 }
2207}
0f85fab0
LW
2208
2209#ifndef CASTNEGFLOAT
463ee0b2 2210U32
79072805 2211cast_ulong(f)
0f85fab0
LW
2212double f;
2213{
2214 long along;
2215
27e2fb84 2216#if CASTFLAGS & 2
34de22dd
LW
2217# define BIGDOUBLE 2147483648.0
2218 if (f >= BIGDOUBLE)
2219 return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2220#endif
0f85fab0
LW
2221 if (f >= 0.0)
2222 return (unsigned long)f;
2223 along = (long)f;
2224 return (unsigned long)along;
2225}
ed6116ce
LW
2226# undef BIGDOUBLE
2227#endif
2228
2229#ifndef CASTI32
5d94fbed 2230
5d94fbed
AD
2231/* Unfortunately, on some systems the cast_uv() function doesn't
2232 work with the system-supplied definition of ULONG_MAX. The
2233 comparison (f >= ULONG_MAX) always comes out true. It must be a
2234 problem with the compiler constant folding.
2235
2236 In any case, this workaround should be fine on any two's complement
2237 system. If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2238 ccflags.
2239 --Andy Dougherty <doughera@lafcol.lafayette.edu>
2240*/
1eb770ff 2241
2242/* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2243 of LONG_(MIN/MAX).
2244 -- Kenneth Albanowski <kjahds@kjahds.com>
2245*/
2246
20cec16a 2247#ifndef MY_UV_MAX
2248# define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
5d94fbed
AD
2249#endif
2250
ed6116ce
LW
2251I32
2252cast_i32(f)
2253double f;
2254{
20cec16a 2255 if (f >= I32_MAX)
2256 return (I32) I32_MAX;
2257 if (f <= I32_MIN)
2258 return (I32) I32_MIN;
ed6116ce
LW
2259 return (I32) f;
2260}
a0d0e21e
LW
2261
2262IV
2263cast_iv(f)
2264double f;
2265{
20cec16a 2266 if (f >= IV_MAX)
2267 return (IV) IV_MAX;
2268 if (f <= IV_MIN)
2269 return (IV) IV_MIN;
a0d0e21e
LW
2270 return (IV) f;
2271}
5d94fbed
AD
2272
2273UV
2274cast_uv(f)
2275double f;
2276{
20cec16a 2277 if (f >= MY_UV_MAX)
2278 return (UV) MY_UV_MAX;
5d94fbed
AD
2279 return (UV) f;
2280}
2281
0f85fab0 2282#endif
62b28dd9 2283
fe14fcc3 2284#ifndef HAS_RENAME
79072805 2285I32
62b28dd9
LW
2286same_dirent(a,b)
2287char *a;
2288char *b;
2289{
93a17b20
LW
2290 char *fa = strrchr(a,'/');
2291 char *fb = strrchr(b,'/');
62b28dd9
LW
2292 struct stat tmpstatbuf1;
2293 struct stat tmpstatbuf2;
46fc3d4c 2294 SV *tmpsv = sv_newmortal();
62b28dd9
LW
2295
2296 if (fa)
2297 fa++;
2298 else
2299 fa = a;
2300 if (fb)
2301 fb++;
2302 else
2303 fb = b;
2304 if (strNE(a,b))
2305 return FALSE;
2306 if (fa == a)
46fc3d4c 2307 sv_setpv(tmpsv, ".");
62b28dd9 2308 else
46fc3d4c 2309 sv_setpvn(tmpsv, a, fa - a);
c6ed36e1 2310 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
62b28dd9
LW
2311 return FALSE;
2312 if (fb == b)
46fc3d4c 2313 sv_setpv(tmpsv, ".");
62b28dd9 2314 else
46fc3d4c 2315 sv_setpvn(tmpsv, b, fb - b);
c6ed36e1 2316 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
62b28dd9
LW
2317 return FALSE;
2318 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2319 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2320}
fe14fcc3
LW
2321#endif /* !HAS_RENAME */
2322
55497cff 2323UV
8ac85365 2324scan_oct(char *start, I32 len, I32 *retlen)
fe14fcc3
LW
2325{
2326 register char *s = start;
55497cff 2327 register UV retval = 0;
2328 bool overflowed = FALSE;
fe14fcc3 2329
748a9306 2330 while (len && *s >= '0' && *s <= '7') {
55497cff 2331 register UV n = retval << 3;
2332 if (!overflowed && (n >> 3) != retval) {
2333 warn("Integer overflow in octal number");
2334 overflowed = TRUE;
2335 }
2336 retval = n | (*s++ - '0');
748a9306 2337 len--;
fe14fcc3 2338 }
748a9306
LW
2339 if (dowarn && len && (*s == '8' || *s == '9'))
2340 warn("Illegal octal digit ignored");
fe14fcc3
LW
2341 *retlen = s - start;
2342 return retval;
2343}
2344
71be2cbc 2345UV
8ac85365 2346scan_hex(char *start, I32 len, I32 *retlen)
fe14fcc3
LW
2347{
2348 register char *s = start;
55497cff 2349 register UV retval = 0;
2350 bool overflowed = FALSE;
6ff81951 2351 char *tmp = s;
fe14fcc3 2352
4e35701f 2353 while (len-- && *s && (tmp = strchr((char *) hexdigit, *s))) {
55497cff 2354 register UV n = retval << 4;
2355 if (!overflowed && (n >> 4) != retval) {
2356 warn("Integer overflow in hex number");
2357 overflowed = TRUE;
2358 }
4e35701f 2359 retval = n | ((tmp - hexdigit) & 15);
fe14fcc3
LW
2360 s++;
2361 }
6ff81951
GS
2362 if (dowarn && !tmp) {
2363 warn("Illegal hex digit ignored");
2364 }
fe14fcc3
LW
2365 *retlen = s - start;
2366 return retval;
2367}
760ac839 2368
491527d0
GS
2369char*
2370find_script(char *scriptname, bool dosearch, char **search_ext, I32 flags)
2371{
2372 dTHR;
2373 char *xfound = Nullch;
2374 char *xfailed = Nullch;
2375 register char *s;
2376 I32 len;
2377 int retval;
2378#if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2379# define SEARCH_EXTS ".bat", ".cmd", NULL
2380# define MAX_EXT_LEN 4
2381#endif
2382#ifdef OS2
2383# define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2384# define MAX_EXT_LEN 4
2385#endif
2386#ifdef VMS
2387# define SEARCH_EXTS ".pl", ".com", NULL
2388# define MAX_EXT_LEN 4
2389#endif
2390 /* additional extensions to try in each dir if scriptname not found */
2391#ifdef SEARCH_EXTS
2392 char *exts[] = { SEARCH_EXTS };
2393 char **ext = search_ext ? search_ext : exts;
2394 int extidx = 0, i = 0;
2395 char *curext = Nullch;
2396#else
2397# define MAX_EXT_LEN 0
2398#endif
2399
2400 /*
2401 * If dosearch is true and if scriptname does not contain path
2402 * delimiters, search the PATH for scriptname.
2403 *
2404 * If SEARCH_EXTS is also defined, will look for each
2405 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2406 * while searching the PATH.
2407 *
2408 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2409 * proceeds as follows:
2410 * If DOSISH or VMSISH:
2411 * + look for ./scriptname{,.foo,.bar}
2412 * + search the PATH for scriptname{,.foo,.bar}
2413 *
2414 * If !DOSISH:
2415 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2416 * this will not look in '.' if it's not in the PATH)
2417 */
2418
2419#ifdef VMS
2420# ifdef ALWAYS_DEFTYPES
2421 len = strlen(scriptname);
2422 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2423 int hasdir, idx = 0, deftypes = 1;
2424 bool seen_dot = 1;
2425
2426 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2427# else
2428 if (dosearch) {
2429 int hasdir, idx = 0, deftypes = 1;
2430 bool seen_dot = 1;
2431
2432 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2433# endif
2434 /* The first time through, just add SEARCH_EXTS to whatever we
2435 * already have, so we can check for default file types. */
2436 while (deftypes ||
2437 (!hasdir && my_trnlnm("DCL$PATH",tokenbuf,idx++)) )
2438 {
2439 if (deftypes) {
2440 deftypes = 0;
2441 *tokenbuf = '\0';
2442 }
2443 if ((strlen(tokenbuf) + strlen(scriptname)
2444 + MAX_EXT_LEN) >= sizeof tokenbuf)
2445 continue; /* don't search dir with too-long name */
2446 strcat(tokenbuf, scriptname);
2447#else /* !VMS */
2448
2449#ifdef DOSISH
2450 if (strEQ(scriptname, "-"))
2451 dosearch = 0;
2452 if (dosearch) { /* Look in '.' first. */
2453 char *cur = scriptname;
2454#ifdef SEARCH_EXTS
2455 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2456 while (ext[i])
2457 if (strEQ(ext[i++],curext)) {
2458 extidx = -1; /* already has an ext */
2459 break;
2460 }
2461 do {
2462#endif
2463 DEBUG_p(PerlIO_printf(Perl_debug_log,
2464 "Looking for %s\n",cur));
2465 if (PerlLIO_stat(cur,&statbuf) >= 0) {
2466 dosearch = 0;
2467 scriptname = cur;
2468#ifdef SEARCH_EXTS
2469 break;
2470#endif
2471 }
2472#ifdef SEARCH_EXTS
2473 if (cur == scriptname) {
2474 len = strlen(scriptname);
2475 if (len+MAX_EXT_LEN+1 >= sizeof(tokenbuf))
2476 break;
2477 cur = strcpy(tokenbuf, scriptname);
2478 }
2479 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2480 && strcpy(tokenbuf+len, ext[extidx++]));
2481#endif
2482 }
2483#endif
2484
2485 if (dosearch && !strchr(scriptname, '/')
2486#ifdef DOSISH
2487 && !strchr(scriptname, '\\')
2488#endif
2489 && (s = PerlEnv_getenv("PATH"))) {
2490 bool seen_dot = 0;
2491
2492 bufend = s + strlen(s);
2493 while (s < bufend) {
2494#if defined(atarist) || defined(DOSISH)
2495 for (len = 0; *s
2496# ifdef atarist
2497 && *s != ','
2498# endif
2499 && *s != ';'; len++, s++) {
2500 if (len < sizeof tokenbuf)
2501 tokenbuf[len] = *s;
2502 }
2503 if (len < sizeof tokenbuf)
2504 tokenbuf[len] = '\0';
2505#else /* ! (atarist || DOSISH) */
2506 s = delimcpy(tokenbuf, tokenbuf + sizeof tokenbuf, s, bufend,
2507 ':',
2508 &len);
2509#endif /* ! (atarist || DOSISH) */
2510 if (s < bufend)
2511 s++;
2512 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tokenbuf)
2513 continue; /* don't search dir with too-long name */
2514 if (len
2515#if defined(atarist) || defined(DOSISH)
2516 && tokenbuf[len - 1] != '/'
2517 && tokenbuf[len - 1] != '\\'
2518#endif
2519 )
2520 tokenbuf[len++] = '/';
2521 if (len == 2 && tokenbuf[0] == '.')
2522 seen_dot = 1;
2523 (void)strcpy(tokenbuf + len, scriptname);
2524#endif /* !VMS */
2525
2526#ifdef SEARCH_EXTS
2527 len = strlen(tokenbuf);
2528 if (extidx > 0) /* reset after previous loop */
2529 extidx = 0;
2530 do {
2531#endif
2532 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tokenbuf));
2533 retval = PerlLIO_stat(tokenbuf,&statbuf);
2534#ifdef SEARCH_EXTS
2535 } while ( retval < 0 /* not there */
2536 && extidx>=0 && ext[extidx] /* try an extension? */
2537 && strcpy(tokenbuf+len, ext[extidx++])
2538 );
2539#endif
2540 if (retval < 0)
2541 continue;
2542 if (S_ISREG(statbuf.st_mode)
2543 && cando(S_IRUSR,TRUE,&statbuf)
2544#ifndef DOSISH
2545 && cando(S_IXUSR,TRUE,&statbuf)
2546#endif
2547 )
2548 {
2549 xfound = tokenbuf; /* bingo! */
2550 break;
2551 }
2552 if (!xfailed)
2553 xfailed = savepv(tokenbuf);
2554 }
2555#ifndef DOSISH
2556 if (!xfound && !seen_dot && !xfailed && (PerlLIO_stat(scriptname,&statbuf) < 0))
2557#endif
2558 seen_dot = 1; /* Disable message. */
2559 if (!xfound)
2560 scriptname = NULL;
2561/* croak("Can't %s %s%s%s",
2562 (xfailed ? "execute" : "find"),
2563 (xfailed ? xfailed : scriptname),
2564 (xfailed ? "" : " on PATH"),
2565 (xfailed || seen_dot) ? "" : ", '.' not in PATH"); */
2566 if (xfailed)
2567 Safefree(xfailed);
2568 scriptname = xfound;
2569 }
2570 return scriptname;
2571}
2572
2573
11343788 2574#ifdef USE_THREADS
12ca11f6
MB
2575#ifdef FAKE_THREADS
2576/* Very simplistic scheduler for now */
2577void
2578schedule(void)
2579{
c7848ba1 2580 thr = thr->i.next_run;
12ca11f6
MB
2581}
2582
2583void
2584perl_cond_init(cp)
2585perl_cond *cp;
2586{
2587 *cp = 0;
2588}
2589
2590void
2591perl_cond_signal(cp)
2592perl_cond *cp;
2593{
51dd5992 2594 perl_os_thread t;
12ca11f6
MB
2595 perl_cond cond = *cp;
2596
2597 if (!cond)
2598 return;
2599 t = cond->thread;
2600 /* Insert t in the runnable queue just ahead of us */
c7848ba1
MB
2601 t->i.next_run = thr->i.next_run;
2602 thr->i.next_run->i.prev_run = t;
2603 t->i.prev_run = thr;
2604 thr->i.next_run = t;
2605 thr->i.wait_queue = 0;
12ca11f6
MB
2606 /* Remove from the wait queue */
2607 *cp = cond->next;
2608 Safefree(cond);
2609}
2610
2611void
2612perl_cond_broadcast(cp)
2613perl_cond *cp;
2614{
51dd5992 2615 perl_os_thread t;
12ca11f6
MB
2616 perl_cond cond, cond_next;
2617
2618 for (cond = *cp; cond; cond = cond_next) {
2619 t = cond->thread;
2620 /* Insert t in the runnable queue just ahead of us */
c7848ba1
MB
2621 t->i.next_run = thr->i.next_run;
2622 thr->i.next_run->i.prev_run = t;
2623 t->i.prev_run = thr;
2624 thr->i.next_run = t;
2625 thr->i.wait_queue = 0;
12ca11f6
MB
2626 /* Remove from the wait queue */
2627 cond_next = cond->next;
2628 Safefree(cond);
2629 }
2630 *cp = 0;
2631}
2632
2633void
2634perl_cond_wait(cp)
2635perl_cond *cp;
2636{
2637 perl_cond cond;
2638
c7848ba1 2639 if (thr->i.next_run == thr)
12ca11f6
MB
2640 croak("panic: perl_cond_wait called by last runnable thread");
2641
0f15f207 2642 New(666, cond, 1, struct perl_wait_queue);
12ca11f6
MB
2643 cond->thread = thr;
2644 cond->next = *cp;
2645 *cp = cond;
c7848ba1 2646 thr->i.wait_queue = cond;
12ca11f6 2647 /* Remove ourselves from runnable queue */
c7848ba1
MB
2648 thr->i.next_run->i.prev_run = thr->i.prev_run;
2649 thr->i.prev_run->i.next_run = thr->i.next_run;
12ca11f6
MB
2650}
2651#endif /* FAKE_THREADS */
2652
11343788 2653#ifdef OLD_PTHREADS_API
52e1cb5e 2654struct perl_thread *
11343788
MB
2655getTHR _((void))
2656{
2657 pthread_addr_t t;
2658
2659 if (pthread_getspecific(thr_key, &t))
2660 croak("panic: pthread_getspecific");
52e1cb5e 2661 return (struct perl_thread *) t;
11343788
MB
2662}
2663#endif /* OLD_PTHREADS_API */
f93b4edd
MB
2664
2665MAGIC *
8ac85365 2666condpair_magic(SV *sv)
f93b4edd
MB
2667{
2668 MAGIC *mg;
2669
2670 SvUPGRADE(sv, SVt_PVMG);
2671 mg = mg_find(sv, 'm');
2672 if (!mg) {
2673 condpair_t *cp;
2674
2675 New(53, cp, 1, condpair_t);
2676 MUTEX_INIT(&cp->mutex);
2677 COND_INIT(&cp->owner_cond);
2678 COND_INIT(&cp->cond);
2679 cp->owner = 0;
940cb80d 2680 LOCK_SV_MUTEX;
f93b4edd
MB
2681 mg = mg_find(sv, 'm');
2682 if (mg) {
2683 /* someone else beat us to initialising it */
940cb80d 2684 UNLOCK_SV_MUTEX;
f93b4edd
MB
2685 MUTEX_DESTROY(&cp->mutex);
2686 COND_DESTROY(&cp->owner_cond);
2687 COND_DESTROY(&cp->cond);
2688 Safefree(cp);
2689 }
2690 else {
2691 sv_magic(sv, Nullsv, 'm', 0, 0);
2692 mg = SvMAGIC(sv);
2693 mg->mg_ptr = (char *)cp;
565764a8 2694 mg->mg_len = sizeof(cp);
940cb80d 2695 UNLOCK_SV_MUTEX;
bc1f4c86 2696 DEBUG_L(WITH_THR(PerlIO_printf(PerlIO_stderr(),
c7848ba1 2697 "%p: condpair_magic %p\n", thr, sv));)
f93b4edd
MB
2698 }
2699 }
2700 return mg;
2701}
a863c7d1
MB
2702
2703/*
199100c8
MB
2704 * Make a new perl thread structure using t as a prototype. Some of the
2705 * fields for the new thread are copied from the prototype thread, t,
2706 * so t should not be running in perl at the time this function is
2707 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
2708 * thread calling new_struct_thread) clearly satisfies this constraint.
a863c7d1 2709 */
52e1cb5e
JH
2710struct perl_thread *
2711new_struct_thread(struct perl_thread *t)
a863c7d1 2712{
52e1cb5e 2713 struct perl_thread *thr;
a863c7d1 2714 SV *sv;
199100c8
MB
2715 SV **svp;
2716 I32 i;
2717
2718 sv = newSVpv("", 0);
52e1cb5e
JH
2719 SvGROW(sv, sizeof(struct perl_thread) + 1);
2720 SvCUR_set(sv, sizeof(struct perl_thread));
199100c8 2721 thr = (Thread) SvPVX(sv);
199100c8 2722 /* debug */
52e1cb5e 2723 memset(thr, 0xab, sizeof(struct perl_thread));
199100c8
MB
2724 markstack = 0;
2725 scopestack = 0;
2726 savestack = 0;
2727 retstack = 0;
2728 dirty = 0;
2729 localizing = 0;
2730 /* end debug */
2731
2732 thr->oursv = sv;
d55594ae 2733 init_stacks(ARGS);
a863c7d1 2734
a863c7d1 2735 curcop = &compiling;
199100c8 2736 thr->cvcache = newHV();
54b9620d 2737 thr->threadsv = newAV();
a863c7d1 2738 thr->specific = newAV();
38a03e6e
MB
2739 thr->errsv = newSVpv("", 0);
2740 thr->errhv = newHV();
a863c7d1
MB
2741 thr->flags = THRf_R_JOINABLE;
2742 MUTEX_INIT(&thr->mutex);
199100c8
MB
2743
2744 curcop = t->Tcurcop; /* XXX As good a guess as any? */
2745 defstash = t->Tdefstash; /* XXX maybe these should */
2746 curstash = t->Tcurstash; /* always be set to main? */
d55594ae
GS
2747
2748
2749 /* top_env needs to be non-zero. It points to an area
2750 in which longjmp() stuff is stored, as C callstack
2751 info there at least is thread specific this has to
2752 be per-thread. Otherwise a 'die' in a thread gives
2753 that thread the C stack of last thread to do an eval {}!
2754 See comments in scope.h
2755 Initialize top entry (as in perl.c for main thread)
2756 */
2757 start_env.je_prev = NULL;
2758 start_env.je_ret = -1;
2759 start_env.je_mustcatch = TRUE;
2760 top_env = &start_env;
2761
199100c8
MB
2762 in_eval = FALSE;
2763 restartop = 0;
2764
2765 tainted = t->Ttainted;
2766 curpm = t->Tcurpm; /* XXX No PMOP ref count */
2767 nrs = newSVsv(t->Tnrs);
2768 rs = newSVsv(t->Trs);
2769 last_in_gv = (GV*)SvREFCNT_inc(t->Tlast_in_gv);
2770 ofslen = t->Tofslen;
2771 ofs = savepvn(t->Tofs, ofslen);
2772 defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
2773 chopset = t->Tchopset;
2774 formtarget = newSVsv(t->Tformtarget);
2775 bodytarget = newSVsv(t->Tbodytarget);
2776 toptarget = newSVsv(t->Ttoptarget);
2777
54b9620d
MB
2778 /* Initialise all per-thread SVs that the template thread used */
2779 svp = AvARRAY(t->threadsv);
93965878 2780 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
199100c8
MB
2781 if (*svp && *svp != &sv_undef) {
2782 SV *sv = newSVsv(*svp);
54b9620d
MB
2783 av_store(thr->threadsv, i, sv);
2784 sv_magic(sv, 0, 0, &threadsv_names[i], 1);
199100c8 2785 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
54b9620d 2786 "new_struct_thread: copied threadsv %d %p->%p\n",i, t, thr));
199100c8
MB
2787 }
2788 }
940cb80d 2789 thr->threadsvp = AvARRAY(thr->threadsv);
199100c8 2790
a863c7d1
MB
2791 MUTEX_LOCK(&threads_mutex);
2792 nthreads++;
199100c8
MB
2793 thr->tid = ++threadnum;
2794 thr->next = t->next;
2795 thr->prev = t;
2796 t->next = thr;
2797 thr->next->prev = thr;
a863c7d1
MB
2798 MUTEX_UNLOCK(&threads_mutex);
2799
2800#ifdef HAVE_THREAD_INTERN
2801 init_thread_intern(thr);
a863c7d1 2802#endif /* HAVE_THREAD_INTERN */
a863c7d1
MB
2803 return thr;
2804}
11343788 2805#endif /* USE_THREADS */
760ac839
LW
2806
2807#ifdef HUGE_VAL
2808/*
2809 * This hack is to force load of "huge" support from libm.a
2810 * So it is in perl for (say) POSIX to use.
2811 * Needed for SunOS with Sun's 'acc' for example.
2812 */
2813double
8ac85365 2814Perl_huge(void)
760ac839
LW
2815{
2816 return HUGE_VAL;
2817}
2818#endif
4e35701f 2819
22239a37
NIS
2820#ifdef PERL_GLOBAL_STRUCT
2821struct perl_vars *
2822Perl_GetVars(void)
2823{
2824 return &Perl_Vars;
2825}
31fb1209
NIS
2826#endif
2827
2828char **
2829get_op_names(void)
2830{
2831 return op_name;
2832}
2833
2834char **
2835get_op_descs(void)
2836{
2837 return op_desc;
2838}
9e6b2b00
GS
2839
2840char *
2841get_no_modify(void)
2842{
2843 return (char*)no_modify;
2844}
2845
2846U32 *
2847get_opargs(void)
2848{
2849 return opargs;
2850}
51aa15f3
GS
2851
2852
2853SV **
2854get_specialsv_list(void)
2855{
2856 return specialsv_list;
2857}