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