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