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