more complete support for implicit thread/interpreter pointer,
[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 #define PERL_IN_UTIL_C
17 #include "perl.h"
18
19 #if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
20 #include <signal.h>
21 #endif
22
23 #ifndef SIG_ERR
24 # define SIG_ERR ((Sighandler_t) -1)
25 #endif
26
27 /* XXX If this causes problems, set i_unistd=undef in the hint file.  */
28 #ifdef I_UNISTD
29 #  include <unistd.h>
30 #endif
31
32 #ifdef I_VFORK
33 #  include <vfork.h>
34 #endif
35
36 /* Put this after #includes because fork and vfork prototypes may
37    conflict.
38 */
39 #ifndef HAS_VFORK
40 #   define vfork fork
41 #endif
42
43 #ifdef I_FCNTL
44 #  include <fcntl.h>
45 #endif
46 #ifdef I_SYS_FILE
47 #  include <sys/file.h>
48 #endif
49
50 #ifdef I_SYS_WAIT
51 #  include <sys/wait.h>
52 #endif
53
54 #define FLUSH
55
56 #ifdef LEAKTEST
57
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 Perl_safesysmalloc(pTHX_ 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         Perl_croak(aTHX_ "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 Perl_safesysrealloc(pTHX_ 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         Perl_croak(aTHX_ "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 Perl_safesysfree(pTHX_ 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 Perl_safesyscalloc(pTHX_ 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         Perl_croak(aTHX_ "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 Perl_safexmalloc(pTHX_ 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 Perl_safexrealloc(pTHX_ 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 Perl_safexfree(pTHX_ 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 Perl_safexcalloc(pTHX_ 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 S_xstat(pTHX_ 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 Perl_delimcpy(pTHX_ 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 Perl_instr(pTHX_ 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 Perl_ninstr(pTHX_ 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 Perl_rninstr(pTHX_ 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(pTHX_ 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(pTHX_ 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               Perl_croak(aTHX_ "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(pTHX_ 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(pTHX)
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(pTHX)
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(pTHX_ 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     new_ctype(curctype);
811 #endif /* USE_LOCALE_CTYPE */
812
813 #ifdef USE_LOCALE_COLLATE
814     new_collate(curcoll);
815 #endif /* USE_LOCALE_COLLATE */
816
817 #ifdef USE_LOCALE_NUMERIC
818     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(pTHX_ int printwarn)
829 {
830     return 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 Perl_mem_collxfrm(pTHX_ 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 #define FBM_TABLE_OFFSET 2      /* Number of bytes between EOS and table*/
893
894 /* As a space optimization, we do not compile tables for strings of length
895    0 and 1, and for strings of length 2 unless FBMcf_TAIL.  These are
896    special-cased in fbm_instr().
897
898    If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
899
900 void
901 Perl_fbm_compile(pTHX_ SV *sv, U32 flags /* not used yet */)
902 {
903     register U8 *s;
904     register U8 *table;
905     register U32 i;
906     STRLEN len;
907     I32 rarest = 0;
908     U32 frequency = 256;
909
910     if (flags & FBMcf_TAIL)
911         sv_catpvn(sv, "\n", 1);         /* Taken into account in fbm_instr() */
912     s = (U8*)SvPV_force(sv, len);
913     (void)SvUPGRADE(sv, SVt_PVBM);
914     if (len == 0)               /* TAIL might be on on a zero-length string. */
915         return;
916     if (len > 2) {
917         I32 mlen = len;
918         unsigned char *sb;
919
920         if (mlen > 255)
921             mlen = 255;
922         Sv_Grow(sv,len + 256 + FBM_TABLE_OFFSET);
923         table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
924         s = table - 1 - FBM_TABLE_OFFSET; /* Last char */
925         for (i = 0; i < 256; i++) {
926             table[i] = mlen;
927         }
928         table[-1] = flags;              /* Not used yet */
929         i = 0;
930         sb = s - mlen;
931         while (s >= sb) {
932             if (table[*s] == mlen)
933                 table[*s] = i;
934             s--, i++;
935         }
936     }
937     sv_magic(sv, Nullsv, 'B', Nullch, 0);       /* deep magic */
938     SvVALID_on(sv);
939
940     s = (unsigned char*)(SvPVX(sv));            /* deeper magic */
941     for (i = 0; i < len; i++) {
942         if (PL_freq[s[i]] < frequency) {
943             rarest = i;
944             frequency = PL_freq[s[i]];
945         }
946     }
947     BmRARE(sv) = s[rarest];
948     BmPREVIOUS(sv) = rarest;
949     BmUSEFUL(sv) = 100;                 /* Initial value */
950     if (flags & FBMcf_TAIL)
951         SvTAIL_on(sv);
952     DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",BmRARE(sv),BmPREVIOUS(sv)));
953 }
954
955 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
956 /* If SvTAIL is actually due to \Z or \z, this gives false positives
957    if multiline */
958
959 char *
960 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
961 {
962     register unsigned char *s;
963     STRLEN l;
964     register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
965     register STRLEN littlelen = l;
966     register I32 multiline = flags & FBMrf_MULTILINE;
967
968     if (bigend - big < littlelen) {
969       check_tail:
970         if ( SvTAIL(littlestr) 
971              && (bigend - big == littlelen - 1)
972              && (littlelen == 1 
973                  || *big == *little && memEQ(big, little, littlelen - 1)))
974             return (char*)big;
975         return Nullch;
976     }
977
978     if (littlelen <= 2) {               /* Special-cased */
979         register char c;
980
981         if (littlelen == 1) {
982             if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
983                 /* Know that bigend != big.  */
984                 if (bigend[-1] == '\n')
985                     return (char *)(bigend - 1);
986                 return (char *) bigend;
987             }
988             s = big;
989             while (s < bigend) {
990                 if (*s == *little)
991                     return (char *)s;
992                 s++;
993             }
994             if (SvTAIL(littlestr))
995                 return (char *) bigend;
996             return Nullch;
997         }
998         if (!littlelen)
999             return (char*)big;          /* Cannot be SvTAIL! */
1000
1001         /* littlelen is 2 */
1002         if (SvTAIL(littlestr) && !multiline) {
1003             if (bigend[-1] == '\n' && bigend[-2] == *little)
1004                 return (char*)bigend - 2;
1005             if (bigend[-1] == *little)
1006                 return (char*)bigend - 1;
1007             return Nullch;
1008         }
1009         {
1010             /* This should be better than FBM if c1 == c2, and almost
1011                as good otherwise: maybe better since we do less indirection.
1012                And we save a lot of memory by caching no table. */
1013             register unsigned char c1 = little[0];
1014             register unsigned char c2 = little[1];
1015
1016             s = big + 1;
1017             bigend--;
1018             if (c1 != c2) {
1019                 while (s <= bigend) {
1020                     if (s[0] == c2) {
1021                         if (s[-1] == c1)
1022                             return (char*)s - 1;
1023                         s += 2;
1024                         continue;
1025                     }
1026                   next_chars:
1027                     if (s[0] == c1) {
1028                         if (s == bigend)
1029                             goto check_1char_anchor;
1030                         if (s[1] == c2)
1031                             return (char*)s;
1032                         else {
1033                             s++;
1034                             goto next_chars;
1035                         }
1036                     }
1037                     else
1038                         s += 2;
1039                 }
1040                 goto check_1char_anchor;
1041             }
1042             /* Now c1 == c2 */
1043             while (s <= bigend) {
1044                 if (s[0] == c1) {
1045                     if (s[-1] == c1)
1046                         return (char*)s - 1;
1047                     if (s == bigend)
1048                         goto check_1char_anchor;
1049                     if (s[1] == c1)
1050                         return (char*)s;
1051                     s += 3;
1052                 }
1053                 else
1054                     s += 2;
1055             }
1056         }
1057       check_1char_anchor:               /* One char and anchor! */
1058         if (SvTAIL(littlestr) && (*bigend == *little))
1059             return (char *)bigend;      /* bigend is already decremented. */
1060         return Nullch;
1061     }
1062     if (SvTAIL(littlestr) && !multiline) {      /* tail anchored? */
1063         s = bigend - littlelen;
1064         if (s >= big
1065             && bigend[-1] == '\n' 
1066             && *s == *little 
1067             /* Automatically of length > 2 */
1068             && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1069             return (char*)s;            /* how sweet it is */
1070         if (s[1] == *little && memEQ((char*)s + 2,(char*)little + 1,
1071                                      littlelen - 2))
1072             return (char*)s + 1;        /* how sweet it is */
1073         return Nullch;
1074     }
1075     if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
1076         char *b = ninstr((char*)big,(char*)bigend,
1077                          (char*)little, (char*)little + littlelen);
1078
1079         if (!b && SvTAIL(littlestr)) {  /* Automatically multiline!  */
1080             /* Chop \n from littlestr: */
1081             s = bigend - littlelen + 1;
1082             if (*s == *little && memEQ((char*)s + 1, (char*)little + 1,
1083                                        littlelen - 2))
1084                 return (char*)s;
1085             return Nullch;
1086         }
1087         return b;
1088     }
1089     
1090     {   /* Do actual FBM.  */
1091         register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
1092         register unsigned char *oldlittle;
1093
1094         if (littlelen > bigend - big)
1095             return Nullch;
1096         --littlelen;                    /* Last char found by table lookup */
1097
1098         s = big + littlelen;
1099         little += littlelen;            /* last char */
1100         oldlittle = little;
1101         if (s < bigend) {
1102             register I32 tmp;
1103
1104           top2:
1105             /*SUPPRESS 560*/
1106             if (tmp = table[*s]) {
1107 #ifdef POINTERRIGOR
1108                 if (bigend - s > tmp) {
1109                     s += tmp;
1110                     goto top2;
1111                 }
1112                 s += tmp;
1113 #else
1114                 if ((s += tmp) < bigend)
1115                     goto top2;
1116 #endif
1117                 goto check_end;
1118             }
1119             else {              /* less expensive than calling strncmp() */
1120                 register unsigned char *olds = s;
1121
1122                 tmp = littlelen;
1123
1124                 while (tmp--) {
1125                     if (*--s == *--little)
1126                         continue;
1127                   differ:
1128                     s = olds + 1;       /* here we pay the price for failure */
1129                     little = oldlittle;
1130                     if (s < bigend)     /* fake up continue to outer loop */
1131                         goto top2;
1132                     goto check_end;
1133                 }
1134                 return (char *)s;
1135             }
1136         }
1137       check_end:
1138         if ( s == bigend && (table[-1] & FBMcf_TAIL)
1139              && memEQ(bigend - littlelen, oldlittle - littlelen, littlelen) )
1140             return (char*)bigend - littlelen;
1141         return Nullch;
1142     }
1143 }
1144
1145 /* start_shift, end_shift are positive quantities which give offsets
1146    of ends of some substring of bigstr.
1147    If `last' we want the last occurence.
1148    old_posp is the way of communication between consequent calls if
1149    the next call needs to find the . 
1150    The initial *old_posp should be -1.
1151
1152    Note that we take into account SvTAIL, so one can get extra
1153    optimizations if _ALL flag is set.
1154  */
1155
1156 /* If SvTAIL is actually due to \Z or \z, this gives false positives
1157    if PL_multiline.  In fact if !PL_multiline the autoritative answer
1158    is not supported yet. */
1159
1160 char *
1161 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
1162 {
1163     dTHR;
1164     register unsigned char *s, *x;
1165     register unsigned char *big;
1166     register I32 pos;
1167     register I32 previous;
1168     register I32 first;
1169     register unsigned char *little;
1170     register I32 stop_pos;
1171     register unsigned char *littleend;
1172     I32 found = 0;
1173
1174     if (*old_posp == -1
1175         ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
1176         : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
1177       cant_find:
1178         if ( BmRARE(littlestr) == '\n' 
1179              && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
1180             little = (unsigned char *)(SvPVX(littlestr));
1181             littleend = little + SvCUR(littlestr);
1182             first = *little++;
1183             goto check_tail;
1184         }
1185         return Nullch;
1186     }
1187
1188     little = (unsigned char *)(SvPVX(littlestr));
1189     littleend = little + SvCUR(littlestr);
1190     first = *little++;
1191     /* The value of pos we can start at: */
1192     previous = BmPREVIOUS(littlestr);
1193     big = (unsigned char *)(SvPVX(bigstr));
1194     /* The value of pos we can stop at: */
1195     stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
1196     if (previous + start_shift > stop_pos) {
1197         if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
1198             goto check_tail;
1199         return Nullch;
1200     }
1201     while (pos < previous + start_shift) {
1202         if (!(pos += PL_screamnext[pos]))
1203             goto cant_find;
1204     }
1205 #ifdef POINTERRIGOR
1206     do {
1207         if (pos >= stop_pos) break;
1208         if (big[pos-previous] != first)
1209             continue;
1210         for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
1211             if (*s++ != *x++) {
1212                 s--;
1213                 break;
1214             }
1215         }
1216         if (s == littleend) {
1217             *old_posp = pos;
1218             if (!last) return (char *)(big+pos-previous);
1219             found = 1;
1220         }
1221     } while ( pos += PL_screamnext[pos] );
1222     return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
1223 #else /* !POINTERRIGOR */
1224     big -= previous;
1225     do {
1226         if (pos >= stop_pos) break;
1227         if (big[pos] != first)
1228             continue;
1229         for (x=big+pos+1,s=little; s < littleend; /**/ ) {
1230             if (*s++ != *x++) {
1231                 s--;
1232                 break;
1233             }
1234         }
1235         if (s == littleend) {
1236             *old_posp = pos;
1237             if (!last) return (char *)(big+pos);
1238             found = 1;
1239         }
1240     } while ( pos += PL_screamnext[pos] );
1241     if (last && found) 
1242         return (char *)(big+(*old_posp));
1243 #endif /* POINTERRIGOR */
1244   check_tail:
1245     if (!SvTAIL(littlestr) || (end_shift > 0))
1246         return Nullch;
1247     /* Ignore the trailing "\n".  This code is not microoptimized */
1248     big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
1249     stop_pos = littleend - little;      /* Actual littlestr len */
1250     if (stop_pos == 0)
1251         return (char*)big;
1252     big -= stop_pos;
1253     if (*big == first
1254         && ((stop_pos == 1) || memEQ(big + 1, little, stop_pos - 1)))
1255         return (char*)big;
1256     return Nullch;
1257 }
1258
1259 I32
1260 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
1261 {
1262     register U8 *a = (U8 *)s1;
1263     register U8 *b = (U8 *)s2;
1264     while (len--) {
1265         if (*a != *b && *a != PL_fold[*b])
1266             return 1;
1267         a++,b++;
1268     }
1269     return 0;
1270 }
1271
1272 I32
1273 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
1274 {
1275     register U8 *a = (U8 *)s1;
1276     register U8 *b = (U8 *)s2;
1277     while (len--) {
1278         if (*a != *b && *a != PL_fold_locale[*b])
1279             return 1;
1280         a++,b++;
1281     }
1282     return 0;
1283 }
1284
1285 /* copy a string to a safe spot */
1286
1287 char *
1288 Perl_savepv(pTHX_ const char *sv)
1289 {
1290     register char *newaddr;
1291
1292     New(902,newaddr,strlen(sv)+1,char);
1293     (void)strcpy(newaddr,sv);
1294     return newaddr;
1295 }
1296
1297 /* same thing but with a known length */
1298
1299 char *
1300 Perl_savepvn(pTHX_ const char *sv, register I32 len)
1301 {
1302     register char *newaddr;
1303
1304     New(903,newaddr,len+1,char);
1305     Copy(sv,newaddr,len,char);          /* might not be null terminated */
1306     newaddr[len] = '\0';                /* is now */
1307     return newaddr;
1308 }
1309
1310 /* the SV for Perl_form() and mess() is not kept in an arena */
1311
1312 STATIC SV *
1313 S_mess_alloc(pTHX)
1314 {
1315     dTHR;
1316     SV *sv;
1317     XPVMG *any;
1318
1319     if (!PL_dirty)
1320         return sv_2mortal(newSVpvn("",0));
1321
1322     if (PL_mess_sv)
1323         return PL_mess_sv;
1324
1325     /* Create as PVMG now, to avoid any upgrading later */
1326     New(905, sv, 1, SV);
1327     Newz(905, any, 1, XPVMG);
1328     SvFLAGS(sv) = SVt_PVMG;
1329     SvANY(sv) = (void*)any;
1330     SvREFCNT(sv) = 1 << 30; /* practically infinite */
1331     PL_mess_sv = sv;
1332     return sv;
1333 }
1334
1335 #ifdef PERL_IMPLICIT_CONTEXT
1336 char *
1337 Perl_form_nocontext(const char* pat, ...)
1338 {
1339     dTHX;
1340     SV *sv = mess_alloc();
1341     va_list args;
1342     va_start(args, pat);
1343     sv_vsetpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*));
1344     va_end(args);
1345     return SvPVX(sv);
1346 }
1347 #endif
1348
1349 char *
1350 Perl_form(pTHX_ const char* pat, ...)
1351 {
1352     SV *sv = mess_alloc();
1353     va_list args;
1354     va_start(args, pat);
1355     sv_vsetpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*));
1356     va_end(args);
1357     return SvPVX(sv);
1358 }
1359
1360 SV *
1361 Perl_mess(pTHX_ const char *pat, va_list *args)
1362 {
1363     SV *sv = mess_alloc();
1364     static char dgd[] = " during global destruction.\n";
1365
1366     sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1367     if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1368         dTHR;
1369         if (PL_curcop->cop_line)
1370             Perl_sv_catpvf(aTHX_ sv, " at %_ line %ld",
1371                       GvSV(PL_curcop->cop_filegv), (long)PL_curcop->cop_line);
1372         if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1373             bool line_mode = (RsSIMPLE(PL_rs) &&
1374                               SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1375             Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %ld",
1376                       PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1377                       line_mode ? "line" : "chunk", 
1378                       (long)IoLINES(GvIOp(PL_last_in_gv)));
1379         }
1380         sv_catpv(sv, PL_dirty ? dgd : ".\n");
1381     }
1382     return sv;
1383 }
1384
1385 static OP *
1386 do_die(pTHX_ const char* pat, va_list *args)
1387 {
1388     dTHR;
1389     char *message;
1390     int was_in_eval = PL_in_eval;
1391     HV *stash;
1392     GV *gv;
1393     CV *cv;
1394     SV *msv;
1395     STRLEN msglen;
1396
1397     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1398                           "%p: die: curstack = %p, mainstack = %p\n",
1399                           thr, PL_curstack, PL_mainstack));
1400
1401     if (pat) {
1402         msv = mess(pat, args);
1403         message = SvPV(msv,msglen);
1404     }
1405     else {
1406         message = Nullch;
1407     }
1408
1409     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1410                           "%p: die: message = %s\ndiehook = %p\n",
1411                           thr, message, PL_diehook));
1412     if (PL_diehook) {
1413         /* sv_2cv might call Perl_croak() */
1414         SV *olddiehook = PL_diehook;
1415         ENTER;
1416         SAVESPTR(PL_diehook);
1417         PL_diehook = Nullsv;
1418         cv = sv_2cv(olddiehook, &stash, &gv, 0);
1419         LEAVE;
1420         if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1421             dSP;
1422             SV *msg;
1423
1424             ENTER;
1425             if (message) {
1426                 msg = newSVpvn(message, msglen);
1427                 SvREADONLY_on(msg);
1428                 SAVEFREESV(msg);
1429             }
1430             else {
1431                 msg = ERRSV;
1432             }
1433
1434             PUSHSTACKi(PERLSI_DIEHOOK);
1435             PUSHMARK(SP);
1436             XPUSHs(msg);
1437             PUTBACK;
1438             call_sv((SV*)cv, G_DISCARD);
1439             POPSTACK;
1440             LEAVE;
1441         }
1442     }
1443
1444     PL_restartop = die_where(message, msglen);
1445     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
1446           "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1447           thr, PL_restartop, was_in_eval, PL_top_env));
1448     if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1449         JMPENV_JUMP(3);
1450     return PL_restartop;
1451 }
1452
1453 #ifdef PERL_IMPLICIT_CONTEXT
1454 OP *
1455 Perl_die_nocontext(const char* pat, ...)
1456 {
1457     dTHX;
1458     OP *o;
1459     va_list args;
1460     va_start(args, pat);
1461     o = do_die(aTHX_ pat, &args);
1462     va_end(args);
1463     return o;
1464 }
1465 #endif
1466
1467 OP *
1468 Perl_die(pTHX_ const char* pat, ...)
1469 {
1470     OP *o;
1471     va_list args;
1472     va_start(args, pat);
1473     o = do_die(aTHX_ pat, &args);
1474     va_end(args);
1475     return o;
1476 }
1477
1478 STATIC void
1479 S_do_croak(pTHX_ const char* pat, va_list *args)
1480 {
1481     dTHR;
1482     char *message;
1483     HV *stash;
1484     GV *gv;
1485     CV *cv;
1486     SV *msv;
1487     STRLEN msglen;
1488
1489     msv = mess(pat, args);
1490     message = SvPV(msv,msglen);
1491     DEBUG_S(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
1492     if (PL_diehook) {
1493         /* sv_2cv might call Perl_croak() */
1494         SV *olddiehook = PL_diehook;
1495         ENTER;
1496         SAVESPTR(PL_diehook);
1497         PL_diehook = Nullsv;
1498         cv = sv_2cv(olddiehook, &stash, &gv, 0);
1499         LEAVE;
1500         if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1501             dSP;
1502             SV *msg;
1503
1504             ENTER;
1505             msg = newSVpvn(message, msglen);
1506             SvREADONLY_on(msg);
1507             SAVEFREESV(msg);
1508
1509             PUSHSTACKi(PERLSI_DIEHOOK);
1510             PUSHMARK(SP);
1511             XPUSHs(msg);
1512             PUTBACK;
1513             call_sv((SV*)cv, G_DISCARD);
1514             POPSTACK;
1515             LEAVE;
1516         }
1517     }
1518     if (PL_in_eval) {
1519         PL_restartop = die_where(message, msglen);
1520         JMPENV_JUMP(3);
1521     }
1522     {
1523 #ifdef USE_SFIO
1524         /* SFIO can really mess with your errno */
1525         int e = errno;
1526 #endif
1527         PerlIO_write(PerlIO_stderr(), message, msglen);
1528         (void)PerlIO_flush(PerlIO_stderr());
1529 #ifdef USE_SFIO
1530         errno = e;
1531 #endif
1532     }
1533     my_failure_exit();
1534 }
1535
1536 #ifdef PERL_IMPLICIT_CONTEXT
1537 void
1538 Perl_croak_nocontext(const char *pat, ...)
1539 {
1540     dTHX;
1541     va_list args;
1542     va_start(args, pat);
1543     do_croak(pat, &args);
1544     /* NOTREACHED */
1545     va_end(args);
1546 }
1547 #endif /* PERL_IMPLICIT_CONTEXT */
1548
1549 void
1550 Perl_croak(pTHX_ const char *pat, ...)
1551 {
1552     va_list args;
1553     va_start(args, pat);
1554     do_croak(pat, &args);
1555     /* NOTREACHED */
1556     va_end(args);
1557 }
1558
1559 STATIC void
1560 S_do_warn(pTHX_ const char* pat, va_list *args)
1561 {
1562     char *message;
1563     HV *stash;
1564     GV *gv;
1565     CV *cv;
1566     SV *msv;
1567     STRLEN msglen;
1568
1569     msv = mess(pat, args);
1570     message = SvPV(msv, msglen);
1571
1572     if (PL_warnhook) {
1573         /* sv_2cv might call Perl_warn() */
1574         dTHR;
1575         SV *oldwarnhook = PL_warnhook;
1576         ENTER;
1577         SAVESPTR(PL_warnhook);
1578         PL_warnhook = Nullsv;
1579         cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1580         LEAVE;
1581         if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1582             dSP;
1583             SV *msg;
1584
1585             ENTER;
1586             msg = newSVpvn(message, msglen);
1587             SvREADONLY_on(msg);
1588             SAVEFREESV(msg);
1589
1590             PUSHSTACKi(PERLSI_WARNHOOK);
1591             PUSHMARK(SP);
1592             XPUSHs(msg);
1593             PUTBACK;
1594             call_sv((SV*)cv, G_DISCARD);
1595             POPSTACK;
1596             LEAVE;
1597             return;
1598         }
1599     }
1600     PerlIO_write(PerlIO_stderr(), message, msglen);
1601 #ifdef LEAKTEST
1602     DEBUG_L(*message == '!' 
1603             ? (xstat(message[1]=='!'
1604                      ? (message[2]=='!' ? 2 : 1)
1605                      : 0)
1606                , 0)
1607             : 0);
1608 #endif
1609     (void)PerlIO_flush(PerlIO_stderr());
1610 }
1611
1612 #ifdef PERL_IMPLICIT_CONTEXT
1613 void
1614 Perl_warn_nocontext(const char *pat, ...)
1615 {
1616     dTHX;
1617     va_list args;
1618     va_start(args, pat);
1619     do_warn(pat, &args);
1620     va_end(args);
1621 }
1622 #endif /* PERL_IMPLICIT_CONTEXT */
1623
1624 void
1625 Perl_warn(pTHX_ const char *pat, ...)
1626 {
1627     va_list args;
1628     va_start(args, pat);
1629     do_warn(pat, &args);
1630     va_end(args);
1631 }
1632
1633 void
1634 Perl_warner(pTHX_ U32  err, const char* pat,...)
1635 {
1636     dTHR;
1637     va_list args;
1638     char *message;
1639     HV *stash;
1640     GV *gv;
1641     CV *cv;
1642     SV *msv;
1643     STRLEN msglen;
1644
1645     va_start(args, pat);
1646     msv = mess(pat, &args);
1647     message = SvPV(msv, msglen);
1648     va_end(args);
1649
1650     if (ckDEAD(err)) {
1651 #ifdef USE_THREADS
1652         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
1653 #endif /* USE_THREADS */
1654         if (PL_diehook) {
1655             /* sv_2cv might call Perl_croak() */
1656             SV *olddiehook = PL_diehook;
1657             ENTER;
1658             SAVESPTR(PL_diehook);
1659             PL_diehook = Nullsv;
1660             cv = sv_2cv(olddiehook, &stash, &gv, 0);
1661             LEAVE;
1662             if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1663                 dSP;
1664                 SV *msg;
1665  
1666                 ENTER;
1667                 msg = newSVpvn(message, msglen);
1668                 SvREADONLY_on(msg);
1669                 SAVEFREESV(msg);
1670  
1671                 PUSHMARK(sp);
1672                 XPUSHs(msg);
1673                 PUTBACK;
1674                 call_sv((SV*)cv, G_DISCARD);
1675  
1676                 LEAVE;
1677             }
1678         }
1679         if (PL_in_eval) {
1680             PL_restartop = die_where(message, msglen);
1681             JMPENV_JUMP(3);
1682         }
1683         PerlIO_write(PerlIO_stderr(), message, msglen);
1684         (void)PerlIO_flush(PerlIO_stderr());
1685         my_failure_exit();
1686
1687     }
1688     else {
1689         if (PL_warnhook) {
1690             /* sv_2cv might call Perl_warn() */
1691             dTHR;
1692             SV *oldwarnhook = PL_warnhook;
1693             ENTER;
1694             SAVESPTR(PL_warnhook);
1695             PL_warnhook = Nullsv;
1696             cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1697                 LEAVE;
1698             if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1699                 dSP;
1700                 SV *msg;
1701  
1702                 ENTER;
1703                 msg = newSVpvn(message, msglen);
1704                 SvREADONLY_on(msg);
1705                 SAVEFREESV(msg);
1706  
1707                 PUSHMARK(sp);
1708                 XPUSHs(msg);
1709                 PUTBACK;
1710                 call_sv((SV*)cv, G_DISCARD);
1711  
1712                 LEAVE;
1713                 return;
1714             }
1715         }
1716         PerlIO_write(PerlIO_stderr(), message, msglen);
1717 #ifdef LEAKTEST
1718         DEBUG_L(xstat());
1719 #endif
1720         (void)PerlIO_flush(PerlIO_stderr());
1721     }
1722 }
1723
1724 #ifndef VMS  /* VMS' my_setenv() is in VMS.c */
1725 #if !defined(WIN32) && !defined(CYGWIN32)
1726 void
1727 Perl_my_setenv(pTHX_ char *nam, char *val)
1728 {
1729 #ifndef PERL_USE_SAFE_PUTENV
1730     /* most putenv()s leak, so we manipulate environ directly */
1731     register I32 i=setenv_getix(nam);           /* where does it go? */
1732
1733     if (environ == PL_origenviron) {    /* need we copy environment? */
1734         I32 j;
1735         I32 max;
1736         char **tmpenv;
1737
1738         /*SUPPRESS 530*/
1739         for (max = i; environ[max]; max++) ;
1740         tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1741         for (j=0; j<max; j++) {         /* copy environment */
1742             tmpenv[j] = (char*)safesysmalloc((strlen(environ[j])+1)*sizeof(char));
1743             strcpy(tmpenv[j], environ[j]);
1744         }
1745         tmpenv[max] = Nullch;
1746         environ = tmpenv;               /* tell exec where it is now */
1747     }
1748     if (!val) {
1749         safesysfree(environ[i]);
1750         while (environ[i]) {
1751             environ[i] = environ[i+1];
1752             i++;
1753         }
1754         return;
1755     }
1756     if (!environ[i]) {                  /* does not exist yet */
1757         environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1758         environ[i+1] = Nullch;  /* make sure it's null terminated */
1759     }
1760     else
1761         safesysfree(environ[i]);
1762     environ[i] = (char*)safesysmalloc((strlen(nam)+strlen(val)+2) * sizeof(char));
1763
1764 #ifndef MSDOS
1765     (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
1766 #else
1767     /* MS-DOS requires environment variable names to be in uppercase */
1768     /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
1769      * some utilities and applications may break because they only look
1770      * for upper case strings. (Fixed strupr() bug here.)]
1771      */
1772     strcpy(environ[i],nam); strupr(environ[i]);
1773     (void)sprintf(environ[i] + strlen(nam),"=%s",val);
1774 #endif /* MSDOS */
1775
1776 #else   /* PERL_USE_SAFE_PUTENV */
1777     char *new_env;
1778
1779     new_env = (char*)safesysmalloc((strlen(nam) + strlen(val) + 2) * sizeof(char));
1780 #ifndef MSDOS
1781     (void)sprintf(new_env,"%s=%s",nam,val);/* all that work just for this */
1782 #else
1783     strcpy(new_env,nam); strupr(new_env);
1784     (void)sprintf(new_env + strlen(nam),"=%s",val);
1785 #endif
1786     (void)putenv(new_env);
1787 #endif  /* PERL_USE_SAFE_PUTENV */
1788 }
1789
1790 #else /* if WIN32 */
1791
1792 void
1793 Perl_my_setenv(pTHX_ char *nam,char *val)
1794 {
1795
1796 #ifdef USE_WIN32_RTL_ENV
1797
1798     register char *envstr;
1799     STRLEN namlen = strlen(nam);
1800     STRLEN vallen;
1801     char *oldstr = environ[setenv_getix(nam)];
1802
1803     /* putenv() has totally broken semantics in both the Borland
1804      * and Microsoft CRTLs.  They either store the passed pointer in
1805      * the environment without making a copy, or make a copy and don't
1806      * free it. And on top of that, they dont free() old entries that
1807      * are being replaced/deleted.  This means the caller must
1808      * free any old entries somehow, or we end up with a memory
1809      * leak every time my_setenv() is called.  One might think
1810      * one could directly manipulate environ[], like the UNIX code
1811      * above, but direct changes to environ are not allowed when
1812      * calling putenv(), since the RTLs maintain an internal
1813      * *copy* of environ[]. Bad, bad, *bad* stink.
1814      * GSAR 97-06-07
1815      */
1816
1817     if (!val) {
1818         if (!oldstr)
1819             return;
1820         val = "";
1821         vallen = 0;
1822     }
1823     else
1824         vallen = strlen(val);
1825     envstr = (char*)safesysmalloc((namlen + vallen + 3) * sizeof(char));
1826     (void)sprintf(envstr,"%s=%s",nam,val);
1827     (void)PerlEnv_putenv(envstr);
1828     if (oldstr)
1829         safesysfree(oldstr);
1830 #ifdef _MSC_VER
1831     safesysfree(envstr);        /* MSVCRT leaks without this */
1832 #endif
1833
1834 #else /* !USE_WIN32_RTL_ENV */
1835
1836     register char *envstr;
1837     STRLEN len = strlen(nam) + 3;
1838     if (!val) {
1839         val = "";
1840     }
1841     len += strlen(val);
1842     New(904, envstr, len, char);
1843     (void)sprintf(envstr,"%s=%s",nam,val);
1844     (void)PerlEnv_putenv(envstr);
1845     Safefree(envstr);
1846
1847 #endif
1848 }
1849
1850 #endif /* WIN32 */
1851
1852 I32
1853 Perl_setenv_getix(pTHX_ char *nam)
1854 {
1855     register I32 i, len = strlen(nam);
1856
1857     for (i = 0; environ[i]; i++) {
1858         if (
1859 #ifdef WIN32
1860             strnicmp(environ[i],nam,len) == 0
1861 #else
1862             strnEQ(environ[i],nam,len)
1863 #endif
1864             && environ[i][len] == '=')
1865             break;                      /* strnEQ must come first to avoid */
1866     }                                   /* potential SEGV's */
1867     return i;
1868 }
1869
1870 #endif /* !VMS */
1871
1872 #ifdef UNLINK_ALL_VERSIONS
1873 I32
1874 Perl_unlnk(pTHX_ char *f)       /* unlink all versions of a file */
1875 {
1876     I32 i;
1877
1878     for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1879     return i ? 0 : -1;
1880 }
1881 #endif
1882
1883 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
1884 char *
1885 Perl_my_bcopy(pTHX_ register const char *from,register char *to,register I32 len)
1886 {
1887     char *retval = to;
1888
1889     if (from - to >= 0) {
1890         while (len--)
1891             *to++ = *from++;
1892     }
1893     else {
1894         to += len;
1895         from += len;
1896         while (len--)
1897             *(--to) = *(--from);
1898     }
1899     return retval;
1900 }
1901 #endif
1902
1903 #ifndef HAS_MEMSET
1904 void *
1905 Perl_my_memset(pTHX_ register char *loc, register I32 ch, register I32 len)
1906 {
1907     char *retval = loc;
1908
1909     while (len--)
1910         *loc++ = ch;
1911     return retval;
1912 }
1913 #endif
1914
1915 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1916 char *
1917 Perl_my_bzero(pTHX_ register char *loc, register I32 len)
1918 {
1919     char *retval = loc;
1920
1921     while (len--)
1922         *loc++ = 0;
1923     return retval;
1924 }
1925 #endif
1926
1927 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1928 I32
1929 Perl_my_memcmp(pTHX_ const char *s1, const char *s2, register I32 len)
1930 {
1931     register U8 *a = (U8 *)s1;
1932     register U8 *b = (U8 *)s2;
1933     register I32 tmp;
1934
1935     while (len--) {
1936         if (tmp = *a++ - *b++)
1937             return tmp;
1938     }
1939     return 0;
1940 }
1941 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1942
1943 #ifndef HAS_VPRINTF
1944
1945 #ifdef USE_CHAR_VSPRINTF
1946 char *
1947 #else
1948 int
1949 #endif
1950 vsprintf(char *dest, const char *pat, char *args)
1951 {
1952     FILE fakebuf;
1953
1954     fakebuf._ptr = dest;
1955     fakebuf._cnt = 32767;
1956 #ifndef _IOSTRG
1957 #define _IOSTRG 0
1958 #endif
1959     fakebuf._flag = _IOWRT|_IOSTRG;
1960     _doprnt(pat, args, &fakebuf);       /* what a kludge */
1961     (void)putc('\0', &fakebuf);
1962 #ifdef USE_CHAR_VSPRINTF
1963     return(dest);
1964 #else
1965     return 0;           /* perl doesn't use return value */
1966 #endif
1967 }
1968
1969 #endif /* HAS_VPRINTF */
1970
1971 #ifdef MYSWAP
1972 #if BYTEORDER != 0x4321
1973 short
1974 Perl_my_swap(pTHX_ short s)
1975 {
1976 #if (BYTEORDER & 1) == 0
1977     short result;
1978
1979     result = ((s & 255) << 8) + ((s >> 8) & 255);
1980     return result;
1981 #else
1982     return s;
1983 #endif
1984 }
1985
1986 long
1987 Perl_my_htonl(pTHX_ long l)
1988 {
1989     union {
1990         long result;
1991         char c[sizeof(long)];
1992     } u;
1993
1994 #if BYTEORDER == 0x1234
1995     u.c[0] = (l >> 24) & 255;
1996     u.c[1] = (l >> 16) & 255;
1997     u.c[2] = (l >> 8) & 255;
1998     u.c[3] = l & 255;
1999     return u.result;
2000 #else
2001 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2002     Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2003 #else
2004     register I32 o;
2005     register I32 s;
2006
2007     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2008         u.c[o & 0xf] = (l >> s) & 255;
2009     }
2010     return u.result;
2011 #endif
2012 #endif
2013 }
2014
2015 long
2016 Perl_my_ntohl(pTHX_ long l)
2017 {
2018     union {
2019         long l;
2020         char c[sizeof(long)];
2021     } u;
2022
2023 #if BYTEORDER == 0x1234
2024     u.c[0] = (l >> 24) & 255;
2025     u.c[1] = (l >> 16) & 255;
2026     u.c[2] = (l >> 8) & 255;
2027     u.c[3] = l & 255;
2028     return u.l;
2029 #else
2030 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2031     Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2032 #else
2033     register I32 o;
2034     register I32 s;
2035
2036     u.l = l;
2037     l = 0;
2038     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2039         l |= (u.c[o & 0xf] & 255) << s;
2040     }
2041     return l;
2042 #endif
2043 #endif
2044 }
2045
2046 #endif /* BYTEORDER != 0x4321 */
2047 #endif /* MYSWAP */
2048
2049 /*
2050  * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2051  * If these functions are defined,
2052  * the BYTEORDER is neither 0x1234 nor 0x4321.
2053  * However, this is not assumed.
2054  * -DWS
2055  */
2056
2057 #define HTOV(name,type)                                         \
2058         type                                                    \
2059         name (register type n)                                  \
2060         {                                                       \
2061             union {                                             \
2062                 type value;                                     \
2063                 char c[sizeof(type)];                           \
2064             } u;                                                \
2065             register I32 i;                                     \
2066             register I32 s;                                     \
2067             for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) {  \
2068                 u.c[i] = (n >> s) & 0xFF;                       \
2069             }                                                   \
2070             return u.value;                                     \
2071         }
2072
2073 #define VTOH(name,type)                                         \
2074         type                                                    \
2075         name (register type n)                                  \
2076         {                                                       \
2077             union {                                             \
2078                 type value;                                     \
2079                 char c[sizeof(type)];                           \
2080             } u;                                                \
2081             register I32 i;                                     \
2082             register I32 s;                                     \
2083             u.value = n;                                        \
2084             n = 0;                                              \
2085             for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) {  \
2086                 n += (u.c[i] & 0xFF) << s;                      \
2087             }                                                   \
2088             return n;                                           \
2089         }
2090
2091 #if defined(HAS_HTOVS) && !defined(htovs)
2092 HTOV(htovs,short)
2093 #endif
2094 #if defined(HAS_HTOVL) && !defined(htovl)
2095 HTOV(htovl,long)
2096 #endif
2097 #if defined(HAS_VTOHS) && !defined(vtohs)
2098 VTOH(vtohs,short)
2099 #endif
2100 #if defined(HAS_VTOHL) && !defined(vtohl)
2101 VTOH(vtohl,long)
2102 #endif
2103
2104     /* VMS' my_popen() is in VMS.c, same with OS/2. */
2105 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM)
2106 PerlIO *
2107 Perl_my_popen(pTHX_ char *cmd, char *mode)
2108 {
2109     int p[2];
2110     register I32 This, that;
2111     register I32 pid;
2112     SV *sv;
2113     I32 doexec = strNE(cmd,"-");
2114     I32 did_pipes = 0;
2115     int pp[2];
2116
2117     PERL_FLUSHALL_FOR_CHILD;
2118 #ifdef OS2
2119     if (doexec) {
2120         return my_syspopen(cmd,mode);
2121     }
2122 #endif 
2123     This = (*mode == 'w');
2124     that = !This;
2125     if (doexec && PL_tainting) {
2126         taint_env();
2127         taint_proper("Insecure %s%s", "EXEC");
2128     }
2129     if (PerlProc_pipe(p) < 0)
2130         return Nullfp;
2131     if (doexec && PerlProc_pipe(pp) >= 0)
2132         did_pipes = 1;
2133     while ((pid = (doexec?vfork():fork())) < 0) {
2134         if (errno != EAGAIN) {
2135             PerlLIO_close(p[This]);
2136             if (did_pipes) {
2137                 PerlLIO_close(pp[0]);
2138                 PerlLIO_close(pp[1]);
2139             }
2140             if (!doexec)
2141                 Perl_croak(aTHX_ "Can't fork");
2142             return Nullfp;
2143         }
2144         sleep(5);
2145     }
2146     if (pid == 0) {
2147         GV* tmpgv;
2148
2149 #undef THIS
2150 #undef THAT
2151 #define THIS that
2152 #define THAT This
2153         PerlLIO_close(p[THAT]);
2154         if (did_pipes) {
2155             PerlLIO_close(pp[0]);
2156 #if defined(HAS_FCNTL) && defined(F_SETFD)
2157             fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2158 #endif
2159         }
2160         if (p[THIS] != (*mode == 'r')) {
2161             PerlLIO_dup2(p[THIS], *mode == 'r');
2162             PerlLIO_close(p[THIS]);
2163         }
2164 #ifndef OS2
2165         if (doexec) {
2166 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2167             int fd;
2168
2169 #ifndef NOFILE
2170 #define NOFILE 20
2171 #endif
2172             for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2173                 if (fd != pp[1])
2174                     PerlLIO_close(fd);
2175 #endif
2176             do_exec3(cmd,pp[1],did_pipes);      /* may or may not use the shell */
2177             PerlProc__exit(1);
2178         }
2179 #endif  /* defined OS2 */
2180         /*SUPPRESS 560*/
2181         if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
2182             sv_setiv(GvSV(tmpgv), (IV)getpid());
2183         PL_forkprocess = 0;
2184         hv_clear(PL_pidstatus); /* we have no children */
2185         return Nullfp;
2186 #undef THIS
2187 #undef THAT
2188     }
2189     do_execfree();      /* free any memory malloced by child on vfork */
2190     PerlLIO_close(p[that]);
2191     if (did_pipes)
2192         PerlLIO_close(pp[1]);
2193     if (p[that] < p[This]) {
2194         PerlLIO_dup2(p[This], p[that]);
2195         PerlLIO_close(p[This]);
2196         p[This] = p[that];
2197     }
2198     sv = *av_fetch(PL_fdpid,p[This],TRUE);
2199     (void)SvUPGRADE(sv,SVt_IV);
2200     SvIVX(sv) = pid;
2201     PL_forkprocess = pid;
2202     if (did_pipes && pid > 0) {
2203         int errkid;
2204         int n = 0, n1;
2205
2206         while (n < sizeof(int)) {
2207             n1 = PerlLIO_read(pp[0],
2208                               (void*)(((char*)&errkid)+n),
2209                               (sizeof(int)) - n);
2210             if (n1 <= 0)
2211                 break;
2212             n += n1;
2213         }
2214         if (n) {                        /* Error */
2215             if (n != sizeof(int))
2216                 Perl_croak(aTHX_ "panic: kid popen errno read");
2217             PerlLIO_close(pp[0]);
2218             errno = errkid;             /* Propagate errno from kid */
2219             return Nullfp;
2220         }
2221     }
2222     if (did_pipes)
2223          PerlLIO_close(pp[0]);
2224     return PerlIO_fdopen(p[This], mode);
2225 }
2226 #else
2227 #if defined(atarist) || defined(DJGPP)
2228 FILE *popen();
2229 PerlIO *
2230 Perl_my_popen(pTHX_ char *cmd, char *mode)
2231 {
2232     /* Needs work for PerlIO ! */
2233     /* used 0 for 2nd parameter to PerlIO-exportFILE; apparently not used */
2234     PERL_FLUSHALL_FOR_CHILD;
2235     return popen(PerlIO_exportFILE(cmd, 0), mode);
2236 }
2237 #endif
2238
2239 #endif /* !DOSISH */
2240
2241 #ifdef DUMP_FDS
2242 void
2243 Perl_dump_fds(pTHX_ char *s)
2244 {
2245     int fd;
2246     struct stat tmpstatbuf;
2247
2248     PerlIO_printf(PerlIO_stderr(),"%s", s);
2249     for (fd = 0; fd < 32; fd++) {
2250         if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2251             PerlIO_printf(PerlIO_stderr()," %d",fd);
2252     }
2253     PerlIO_printf(PerlIO_stderr(),"\n");
2254 }
2255 #endif  /* DUMP_FDS */
2256
2257 #ifndef HAS_DUP2
2258 int
2259 dup2(int oldfd, int newfd)
2260 {
2261 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2262     if (oldfd == newfd)
2263         return oldfd;
2264     PerlLIO_close(newfd);
2265     return fcntl(oldfd, F_DUPFD, newfd);
2266 #else
2267 #define DUP2_MAX_FDS 256
2268     int fdtmp[DUP2_MAX_FDS];
2269     I32 fdx = 0;
2270     int fd;
2271
2272     if (oldfd == newfd)
2273         return oldfd;
2274     PerlLIO_close(newfd);
2275     /* good enough for low fd's... */
2276     while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2277         if (fdx >= DUP2_MAX_FDS) {
2278             PerlLIO_close(fd);
2279             fd = -1;
2280             break;
2281         }
2282         fdtmp[fdx++] = fd;
2283     }
2284     while (fdx > 0)
2285         PerlLIO_close(fdtmp[--fdx]);
2286     return fd;
2287 #endif
2288 }
2289 #endif
2290
2291
2292 #ifdef HAS_SIGACTION
2293
2294 Sighandler_t
2295 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2296 {
2297     struct sigaction act, oact;
2298
2299     act.sa_handler = handler;
2300     sigemptyset(&act.sa_mask);
2301     act.sa_flags = 0;
2302 #ifdef SA_RESTART
2303     act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2304 #endif
2305 #ifdef SA_NOCLDWAIT
2306     if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2307         act.sa_flags |= SA_NOCLDWAIT;
2308 #endif
2309     if (sigaction(signo, &act, &oact) == -1)
2310         return SIG_ERR;
2311     else
2312         return oact.sa_handler;
2313 }
2314
2315 Sighandler_t
2316 Perl_rsignal_state(pTHX_ int signo)
2317 {
2318     struct sigaction oact;
2319
2320     if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2321         return SIG_ERR;
2322     else
2323         return oact.sa_handler;
2324 }
2325
2326 int
2327 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2328 {
2329     struct sigaction act;
2330
2331     act.sa_handler = handler;
2332     sigemptyset(&act.sa_mask);
2333     act.sa_flags = 0;
2334 #ifdef SA_RESTART
2335     act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2336 #endif
2337 #ifdef SA_NOCLDWAIT
2338     if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2339         act.sa_flags |= SA_NOCLDWAIT;
2340 #endif
2341     return sigaction(signo, &act, save);
2342 }
2343
2344 int
2345 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2346 {
2347     return sigaction(signo, save, (struct sigaction *)NULL);
2348 }
2349
2350 #else /* !HAS_SIGACTION */
2351
2352 Sighandler_t
2353 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2354 {
2355     return PerlProc_signal(signo, handler);
2356 }
2357
2358 static int sig_trapped;
2359
2360 static
2361 Signal_t
2362 sig_trap(int signo)
2363 {
2364     sig_trapped++;
2365 }
2366
2367 Sighandler_t
2368 Perl_rsignal_state(pTHX_ int signo)
2369 {
2370     Sighandler_t oldsig;
2371
2372     sig_trapped = 0;
2373     oldsig = PerlProc_signal(signo, sig_trap);
2374     PerlProc_signal(signo, oldsig);
2375     if (sig_trapped)
2376         PerlProc_kill(getpid(), signo);
2377     return oldsig;
2378 }
2379
2380 int
2381 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2382 {
2383     *save = PerlProc_signal(signo, handler);
2384     return (*save == SIG_ERR) ? -1 : 0;
2385 }
2386
2387 int
2388 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2389 {
2390     return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2391 }
2392
2393 #endif /* !HAS_SIGACTION */
2394
2395     /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2396 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM)
2397 I32
2398 Perl_my_pclose(pTHX_ PerlIO *ptr)
2399 {
2400     Sigsave_t hstat, istat, qstat;
2401     int status;
2402     SV **svp;
2403     int pid;
2404     int pid2;
2405     bool close_failed;
2406     int saved_errno;
2407 #ifdef VMS
2408     int saved_vaxc_errno;
2409 #endif
2410 #ifdef WIN32
2411     int saved_win32_errno;
2412 #endif
2413
2414     svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2415     pid = (int)SvIVX(*svp);
2416     SvREFCNT_dec(*svp);
2417     *svp = &PL_sv_undef;
2418 #ifdef OS2
2419     if (pid == -1) {                    /* Opened by popen. */
2420         return my_syspclose(ptr);
2421     }
2422 #endif 
2423     if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2424         saved_errno = errno;
2425 #ifdef VMS
2426         saved_vaxc_errno = vaxc$errno;
2427 #endif
2428 #ifdef WIN32
2429         saved_win32_errno = GetLastError();
2430 #endif
2431     }
2432 #ifdef UTS
2433     if(PerlProc_kill(pid, 0) < 0) { return(pid); }   /* HOM 12/23/91 */
2434 #endif
2435     rsignal_save(SIGHUP, SIG_IGN, &hstat);
2436     rsignal_save(SIGINT, SIG_IGN, &istat);
2437     rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2438     do {
2439         pid2 = wait4pid(pid, &status, 0);
2440     } while (pid2 == -1 && errno == EINTR);
2441     rsignal_restore(SIGHUP, &hstat);
2442     rsignal_restore(SIGINT, &istat);
2443     rsignal_restore(SIGQUIT, &qstat);
2444     if (close_failed) {
2445         SETERRNO(saved_errno, saved_vaxc_errno);
2446         return -1;
2447     }
2448     return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2449 }
2450 #endif /* !DOSISH */
2451
2452 #if  !defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(CYGWIN32)
2453 I32
2454 Perl_wait4pid(pTHX_ int pid, int *statusp, int flags)
2455 {
2456     SV *sv;
2457     SV** svp;
2458     char spid[TYPE_CHARS(int)];
2459
2460     if (!pid)
2461         return -1;
2462     if (pid > 0) {
2463         sprintf(spid, "%d", pid);
2464         svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2465         if (svp && *svp != &PL_sv_undef) {
2466             *statusp = SvIVX(*svp);
2467             (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2468             return pid;
2469         }
2470     }
2471     else {
2472         HE *entry;
2473
2474         hv_iterinit(PL_pidstatus);
2475         if (entry = hv_iternext(PL_pidstatus)) {
2476             pid = atoi(hv_iterkey(entry,(I32*)statusp));
2477             sv = hv_iterval(PL_pidstatus,entry);
2478             *statusp = SvIVX(sv);
2479             sprintf(spid, "%d", pid);
2480             (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2481             return pid;
2482         }
2483     }
2484 #ifdef HAS_WAITPID
2485 #  ifdef HAS_WAITPID_RUNTIME
2486     if (!HAS_WAITPID_RUNTIME)
2487         goto hard_way;
2488 #  endif
2489     return PerlProc_waitpid(pid,statusp,flags);
2490 #endif
2491 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2492     return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2493 #endif
2494 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2495   hard_way:
2496     {
2497         I32 result;
2498         if (flags)
2499             Perl_croak(aTHX_ "Can't do waitpid with flags");
2500         else {
2501             while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2502                 pidgone(result,*statusp);
2503             if (result < 0)
2504                 *statusp = -1;
2505         }
2506         return result;
2507     }
2508 #endif
2509 }
2510 #endif /* !DOSISH || OS2 || WIN32 */
2511
2512 void
2513 /*SUPPRESS 590*/
2514 Perl_pidgone(pTHX_ int pid, int status)
2515 {
2516     register SV *sv;
2517     char spid[TYPE_CHARS(int)];
2518
2519     sprintf(spid, "%d", pid);
2520     sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2521     (void)SvUPGRADE(sv,SVt_IV);
2522     SvIVX(sv) = status;
2523     return;
2524 }
2525
2526 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2527 int pclose();
2528 #ifdef HAS_FORK
2529 int                                     /* Cannot prototype with I32
2530                                            in os2ish.h. */
2531 my_syspclose(PerlIO *ptr)
2532 #else
2533 I32
2534 Perl_my_pclose(pTHX_ PerlIO *ptr)
2535 #endif 
2536 {
2537     /* Needs work for PerlIO ! */
2538     FILE *f = PerlIO_findFILE(ptr);
2539     I32 result = pclose(f);
2540     PerlIO_releaseFILE(ptr,f);
2541     return result;
2542 }
2543 #endif
2544
2545 void
2546 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2547 {
2548     register I32 todo;
2549     register const char *frombase = from;
2550
2551     if (len == 1) {
2552         register const char c = *from;
2553         while (count-- > 0)
2554             *to++ = c;
2555         return;
2556     }
2557     while (count-- > 0) {
2558         for (todo = len; todo > 0; todo--) {
2559             *to++ = *from++;
2560         }
2561         from = frombase;
2562     }
2563 }
2564
2565 U32
2566 Perl_cast_ulong(pTHX_ double f)
2567 {
2568     long along;
2569
2570 #if CASTFLAGS & 2
2571 #   define BIGDOUBLE 2147483648.0
2572     if (f >= BIGDOUBLE)
2573         return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2574 #endif
2575     if (f >= 0.0)
2576         return (unsigned long)f;
2577     along = (long)f;
2578     return (unsigned long)along;
2579 }
2580 # undef BIGDOUBLE
2581
2582 /* Unfortunately, on some systems the cast_uv() function doesn't
2583    work with the system-supplied definition of ULONG_MAX.  The
2584    comparison  (f >= ULONG_MAX) always comes out true.  It must be a
2585    problem with the compiler constant folding.
2586
2587    In any case, this workaround should be fine on any two's complement
2588    system.  If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2589    ccflags.
2590                --Andy Dougherty      <doughera@lafcol.lafayette.edu>
2591 */
2592
2593 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2594    of LONG_(MIN/MAX).
2595                            -- Kenneth Albanowski <kjahds@kjahds.com>
2596 */                                      
2597
2598 #ifndef MY_UV_MAX
2599 #  define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2600 #endif
2601
2602 I32
2603 Perl_cast_i32(pTHX_ double f)
2604 {
2605     if (f >= I32_MAX)
2606         return (I32) I32_MAX;
2607     if (f <= I32_MIN)
2608         return (I32) I32_MIN;
2609     return (I32) f;
2610 }
2611
2612 IV
2613 Perl_cast_iv(pTHX_ double f)
2614 {
2615     if (f >= IV_MAX) {
2616         UV uv;
2617         
2618         if (f >= (double)UV_MAX)
2619             return (IV) UV_MAX; 
2620         uv = (UV) f;
2621         return (IV)uv;
2622     }
2623     if (f <= IV_MIN)
2624         return (IV) IV_MIN;
2625     return (IV) f;
2626 }
2627
2628 UV
2629 Perl_cast_uv(pTHX_ double f)
2630 {
2631     if (f >= MY_UV_MAX)
2632         return (UV) MY_UV_MAX;
2633     if (f < 0) {
2634         IV iv;
2635         
2636         if (f < IV_MIN)
2637             return (UV)IV_MIN;
2638         iv = (IV) f;
2639         return (UV) iv;
2640     }
2641     return (UV) f;
2642 }
2643
2644 #ifndef HAS_RENAME
2645 I32
2646 Perl_same_dirent(pTHX_ char *a, char *b)
2647 {
2648     char *fa = strrchr(a,'/');
2649     char *fb = strrchr(b,'/');
2650     struct stat tmpstatbuf1;
2651     struct stat tmpstatbuf2;
2652     SV *tmpsv = sv_newmortal();
2653
2654     if (fa)
2655         fa++;
2656     else
2657         fa = a;
2658     if (fb)
2659         fb++;
2660     else
2661         fb = b;
2662     if (strNE(a,b))
2663         return FALSE;
2664     if (fa == a)
2665         sv_setpv(tmpsv, ".");
2666     else
2667         sv_setpvn(tmpsv, a, fa - a);
2668     if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2669         return FALSE;
2670     if (fb == b)
2671         sv_setpv(tmpsv, ".");
2672     else
2673         sv_setpvn(tmpsv, b, fb - b);
2674     if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2675         return FALSE;
2676     return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2677            tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2678 }
2679 #endif /* !HAS_RENAME */
2680
2681 UV
2682 Perl_scan_bin(pTHX_ char *start, I32 len, I32 *retlen)
2683 {
2684     register char *s = start;
2685     register UV retval = 0;
2686     bool overflowed = FALSE;
2687     while (len && *s >= '0' && *s <= '1') {
2688       register UV n = retval << 1;
2689       if (!overflowed && (n >> 1) != retval) {
2690           Perl_warn(aTHX_ "Integer overflow in binary number");
2691           overflowed = TRUE;
2692       }
2693       retval = n | (*s++ - '0');
2694       len--;
2695     }
2696     if (len && (*s >= '2' && *s <= '9')) {
2697       dTHR;
2698       if (ckWARN(WARN_UNSAFE))
2699           Perl_warner(aTHX_ WARN_UNSAFE, "Illegal binary digit '%c' ignored", *s);
2700     }
2701     *retlen = s - start;
2702     return retval;
2703 }
2704 UV
2705 Perl_scan_oct(pTHX_ char *start, I32 len, I32 *retlen)
2706 {
2707     register char *s = start;
2708     register UV retval = 0;
2709     bool overflowed = FALSE;
2710
2711     while (len && *s >= '0' && *s <= '7') {
2712         register UV n = retval << 3;
2713         if (!overflowed && (n >> 3) != retval) {
2714             Perl_warn(aTHX_ "Integer overflow in octal number");
2715             overflowed = TRUE;
2716         }
2717         retval = n | (*s++ - '0');
2718         len--;
2719     }
2720     if (len && (*s == '8' || *s == '9')) {
2721         dTHR;
2722         if (ckWARN(WARN_OCTAL))
2723             Perl_warner(aTHX_ WARN_OCTAL, "Illegal octal digit '%c' ignored", *s);
2724     }
2725     *retlen = s - start;
2726     return retval;
2727 }
2728
2729 UV
2730 Perl_scan_hex(pTHX_ char *start, I32 len, I32 *retlen)
2731 {
2732     register char *s = start;
2733     register UV retval = 0;
2734     bool overflowed = FALSE;
2735     char *tmp = s;
2736     register UV n;
2737
2738     while (len-- && *s) {
2739         tmp = strchr((char *) PL_hexdigit, *s++);
2740         if (!tmp) {
2741             if (*(s-1) == '_' || (*(s-1) == 'x' && retval == 0))
2742                 continue;
2743             else {
2744                 dTHR;
2745                 --s;
2746                 if (ckWARN(WARN_UNSAFE))
2747                     Perl_warner(aTHX_ WARN_UNSAFE,"Illegal hex digit '%c' ignored", *s);
2748                 break;
2749             }
2750         }
2751         n = retval << 4;
2752         if (!overflowed && (n >> 4) != retval) {
2753             Perl_warn(aTHX_ "Integer overflow in hex number");
2754             overflowed = TRUE;
2755         }
2756         retval = n | ((tmp - PL_hexdigit) & 15);
2757     }
2758     *retlen = s - start;
2759     return retval;
2760 }
2761
2762 char*
2763 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
2764 {
2765     dTHR;
2766     char *xfound = Nullch;
2767     char *xfailed = Nullch;
2768     char tmpbuf[MAXPATHLEN];
2769     register char *s;
2770     I32 len;
2771     int retval;
2772 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2773 #  define SEARCH_EXTS ".bat", ".cmd", NULL
2774 #  define MAX_EXT_LEN 4
2775 #endif
2776 #ifdef OS2
2777 #  define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2778 #  define MAX_EXT_LEN 4
2779 #endif
2780 #ifdef VMS
2781 #  define SEARCH_EXTS ".pl", ".com", NULL
2782 #  define MAX_EXT_LEN 4
2783 #endif
2784     /* additional extensions to try in each dir if scriptname not found */
2785 #ifdef SEARCH_EXTS
2786     char *exts[] = { SEARCH_EXTS };
2787     char **ext = search_ext ? search_ext : exts;
2788     int extidx = 0, i = 0;
2789     char *curext = Nullch;
2790 #else
2791 #  define MAX_EXT_LEN 0
2792 #endif
2793
2794     /*
2795      * If dosearch is true and if scriptname does not contain path
2796      * delimiters, search the PATH for scriptname.
2797      *
2798      * If SEARCH_EXTS is also defined, will look for each
2799      * scriptname{SEARCH_EXTS} whenever scriptname is not found
2800      * while searching the PATH.
2801      *
2802      * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2803      * proceeds as follows:
2804      *   If DOSISH or VMSISH:
2805      *     + look for ./scriptname{,.foo,.bar}
2806      *     + search the PATH for scriptname{,.foo,.bar}
2807      *
2808      *   If !DOSISH:
2809      *     + look *only* in the PATH for scriptname{,.foo,.bar} (note
2810      *       this will not look in '.' if it's not in the PATH)
2811      */
2812     tmpbuf[0] = '\0';
2813
2814 #ifdef VMS
2815 #  ifdef ALWAYS_DEFTYPES
2816     len = strlen(scriptname);
2817     if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2818         int hasdir, idx = 0, deftypes = 1;
2819         bool seen_dot = 1;
2820
2821         hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2822 #  else
2823     if (dosearch) {
2824         int hasdir, idx = 0, deftypes = 1;
2825         bool seen_dot = 1;
2826
2827         hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2828 #  endif
2829         /* The first time through, just add SEARCH_EXTS to whatever we
2830          * already have, so we can check for default file types. */
2831         while (deftypes ||
2832                (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2833         {
2834             if (deftypes) {
2835                 deftypes = 0;
2836                 *tmpbuf = '\0';
2837             }
2838             if ((strlen(tmpbuf) + strlen(scriptname)
2839                  + MAX_EXT_LEN) >= sizeof tmpbuf)
2840                 continue;       /* don't search dir with too-long name */
2841             strcat(tmpbuf, scriptname);
2842 #else  /* !VMS */
2843
2844 #ifdef DOSISH
2845     if (strEQ(scriptname, "-"))
2846         dosearch = 0;
2847     if (dosearch) {             /* Look in '.' first. */
2848         char *cur = scriptname;
2849 #ifdef SEARCH_EXTS
2850         if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2851             while (ext[i])
2852                 if (strEQ(ext[i++],curext)) {
2853                     extidx = -1;                /* already has an ext */
2854                     break;
2855                 }
2856         do {
2857 #endif
2858             DEBUG_p(PerlIO_printf(Perl_debug_log,
2859                                   "Looking for %s\n",cur));
2860             if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2861                 && !S_ISDIR(PL_statbuf.st_mode)) {
2862                 dosearch = 0;
2863                 scriptname = cur;
2864 #ifdef SEARCH_EXTS
2865                 break;
2866 #endif
2867             }
2868 #ifdef SEARCH_EXTS
2869             if (cur == scriptname) {
2870                 len = strlen(scriptname);
2871                 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2872                     break;
2873                 cur = strcpy(tmpbuf, scriptname);
2874             }
2875         } while (extidx >= 0 && ext[extidx]     /* try an extension? */
2876                  && strcpy(tmpbuf+len, ext[extidx++]));
2877 #endif
2878     }
2879 #endif
2880
2881     if (dosearch && !strchr(scriptname, '/')
2882 #ifdef DOSISH
2883                  && !strchr(scriptname, '\\')
2884 #endif
2885                  && (s = PerlEnv_getenv("PATH"))) {
2886         bool seen_dot = 0;
2887         
2888         PL_bufend = s + strlen(s);
2889         while (s < PL_bufend) {
2890 #if defined(atarist) || defined(DOSISH)
2891             for (len = 0; *s
2892 #  ifdef atarist
2893                     && *s != ','
2894 #  endif
2895                     && *s != ';'; len++, s++) {
2896                 if (len < sizeof tmpbuf)
2897                     tmpbuf[len] = *s;
2898             }
2899             if (len < sizeof tmpbuf)
2900                 tmpbuf[len] = '\0';
2901 #else  /* ! (atarist || DOSISH) */
2902             s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2903                         ':',
2904                         &len);
2905 #endif /* ! (atarist || DOSISH) */
2906             if (s < PL_bufend)
2907                 s++;
2908             if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2909                 continue;       /* don't search dir with too-long name */
2910             if (len
2911 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2912                 && tmpbuf[len - 1] != '/'
2913                 && tmpbuf[len - 1] != '\\'
2914 #endif
2915                )
2916                 tmpbuf[len++] = '/';
2917             if (len == 2 && tmpbuf[0] == '.')
2918                 seen_dot = 1;
2919             (void)strcpy(tmpbuf + len, scriptname);
2920 #endif  /* !VMS */
2921
2922 #ifdef SEARCH_EXTS
2923             len = strlen(tmpbuf);
2924             if (extidx > 0)     /* reset after previous loop */
2925                 extidx = 0;
2926             do {
2927 #endif
2928                 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2929                 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2930                 if (S_ISDIR(PL_statbuf.st_mode)) {
2931                     retval = -1;
2932                 }
2933 #ifdef SEARCH_EXTS
2934             } while (  retval < 0               /* not there */
2935                     && extidx>=0 && ext[extidx] /* try an extension? */
2936                     && strcpy(tmpbuf+len, ext[extidx++])
2937                 );
2938 #endif
2939             if (retval < 0)
2940                 continue;
2941             if (S_ISREG(PL_statbuf.st_mode)
2942                 && cando(S_IRUSR,TRUE,&PL_statbuf)
2943 #ifndef DOSISH
2944                 && cando(S_IXUSR,TRUE,&PL_statbuf)
2945 #endif
2946                 )
2947             {
2948                 xfound = tmpbuf;              /* bingo! */
2949                 break;
2950             }
2951             if (!xfailed)
2952                 xfailed = savepv(tmpbuf);
2953         }
2954 #ifndef DOSISH
2955         if (!xfound && !seen_dot && !xfailed &&
2956             (PerlLIO_stat(scriptname,&PL_statbuf) < 0 
2957              || S_ISDIR(PL_statbuf.st_mode)))
2958 #endif
2959             seen_dot = 1;                       /* Disable message. */
2960         if (!xfound) {
2961             if (flags & 1) {                    /* do or die? */
2962                 Perl_croak(aTHX_ "Can't %s %s%s%s",
2963                       (xfailed ? "execute" : "find"),
2964                       (xfailed ? xfailed : scriptname),
2965                       (xfailed ? "" : " on PATH"),
2966                       (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2967             }
2968             scriptname = Nullch;
2969         }
2970         if (xfailed)
2971             Safefree(xfailed);
2972         scriptname = xfound;
2973     }
2974     return (scriptname ? savepv(scriptname) : Nullch);
2975 }
2976
2977
2978 #ifdef USE_THREADS
2979 #ifdef FAKE_THREADS
2980 /* Very simplistic scheduler for now */
2981 void
2982 schedule(void)
2983 {
2984     thr = thr->i.next_run;
2985 }
2986
2987 void
2988 Perl_cond_init(pTHX_ perl_cond *cp)
2989 {
2990     *cp = 0;
2991 }
2992
2993 void
2994 Perl_cond_signal(pTHX_ perl_cond *cp)
2995 {
2996     perl_os_thread t;
2997     perl_cond cond = *cp;
2998     
2999     if (!cond)
3000         return;
3001     t = cond->thread;
3002     /* Insert t in the runnable queue just ahead of us */
3003     t->i.next_run = thr->i.next_run;
3004     thr->i.next_run->i.prev_run = t;
3005     t->i.prev_run = thr;
3006     thr->i.next_run = t;
3007     thr->i.wait_queue = 0;
3008     /* Remove from the wait queue */
3009     *cp = cond->next;
3010     Safefree(cond);
3011 }
3012
3013 void
3014 Perl_cond_broadcast(pTHX_ perl_cond *cp)
3015 {
3016     perl_os_thread t;
3017     perl_cond cond, cond_next;
3018     
3019     for (cond = *cp; cond; cond = cond_next) {
3020         t = cond->thread;
3021         /* Insert t in the runnable queue just ahead of us */
3022         t->i.next_run = thr->i.next_run;
3023         thr->i.next_run->i.prev_run = t;
3024         t->i.prev_run = thr;
3025         thr->i.next_run = t;
3026         thr->i.wait_queue = 0;
3027         /* Remove from the wait queue */
3028         cond_next = cond->next;
3029         Safefree(cond);
3030     }
3031     *cp = 0;
3032 }
3033
3034 void
3035 Perl_cond_wait(pTHX_ perl_cond *cp)
3036 {
3037     perl_cond cond;
3038
3039     if (thr->i.next_run == thr)
3040         Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3041     
3042     New(666, cond, 1, struct perl_wait_queue);
3043     cond->thread = thr;
3044     cond->next = *cp;
3045     *cp = cond;
3046     thr->i.wait_queue = cond;
3047     /* Remove ourselves from runnable queue */
3048     thr->i.next_run->i.prev_run = thr->i.prev_run;
3049     thr->i.prev_run->i.next_run = thr->i.next_run;
3050 }
3051 #endif /* FAKE_THREADS */
3052
3053 #ifdef PTHREAD_GETSPECIFIC_INT
3054 struct perl_thread *
3055 Perl_getTHR(pTHX)
3056 {
3057     pthread_addr_t t;
3058
3059     if (pthread_getspecific(PL_thr_key, &t))
3060         Perl_croak(aTHX_ "panic: pthread_getspecific");
3061     return (struct perl_thread *) t;
3062 }
3063 #endif
3064
3065 MAGIC *
3066 Perl_condpair_magic(pTHX_ SV *sv)
3067 {
3068     MAGIC *mg;
3069     
3070     SvUPGRADE(sv, SVt_PVMG);
3071     mg = mg_find(sv, 'm');
3072     if (!mg) {
3073         condpair_t *cp;
3074
3075         New(53, cp, 1, condpair_t);
3076         MUTEX_INIT(&cp->mutex);
3077         COND_INIT(&cp->owner_cond);
3078         COND_INIT(&cp->cond);
3079         cp->owner = 0;
3080         MUTEX_LOCK(&PL_cred_mutex);             /* XXX need separate mutex? */
3081         mg = mg_find(sv, 'm');
3082         if (mg) {
3083             /* someone else beat us to initialising it */
3084             MUTEX_UNLOCK(&PL_cred_mutex);       /* XXX need separate mutex? */
3085             MUTEX_DESTROY(&cp->mutex);
3086             COND_DESTROY(&cp->owner_cond);
3087             COND_DESTROY(&cp->cond);
3088             Safefree(cp);
3089         }
3090         else {
3091             sv_magic(sv, Nullsv, 'm', 0, 0);
3092             mg = SvMAGIC(sv);
3093             mg->mg_ptr = (char *)cp;
3094             mg->mg_len = sizeof(cp);
3095             MUTEX_UNLOCK(&PL_cred_mutex);       /* XXX need separate mutex? */
3096             DEBUG_S(WITH_THR(PerlIO_printf(PerlIO_stderr(),
3097                                            "%p: condpair_magic %p\n", thr, sv));)
3098         }
3099     }
3100     return mg;
3101 }
3102
3103 /*
3104  * Make a new perl thread structure using t as a prototype. Some of the
3105  * fields for the new thread are copied from the prototype thread, t,
3106  * so t should not be running in perl at the time this function is
3107  * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3108  * thread calling new_struct_thread) clearly satisfies this constraint.
3109  */
3110 struct perl_thread *
3111 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3112 {
3113 #ifndef PERL_IMPLICIT_CONTEXT
3114     struct perl_thread *thr;
3115 #endif
3116     SV *sv;
3117     SV **svp;
3118     I32 i;
3119
3120     sv = newSVpvn("", 0);
3121     SvGROW(sv, sizeof(struct perl_thread) + 1);
3122     SvCUR_set(sv, sizeof(struct perl_thread));
3123     thr = (Thread) SvPVX(sv);
3124 #ifdef DEBUGGING
3125     memset(thr, 0xab, sizeof(struct perl_thread));
3126     PL_markstack = 0;
3127     PL_scopestack = 0;
3128     PL_savestack = 0;
3129     PL_retstack = 0;
3130     PL_dirty = 0;
3131     PL_localizing = 0;
3132     Zero(&PL_hv_fetch_ent_mh, 1, HE);
3133 #else
3134     Zero(thr, 1, struct perl_thread);
3135 #endif
3136
3137     PL_protect = FUNC_NAME_TO_PTR(Perl_default_protect);
3138
3139     thr->oursv = sv;
3140     init_stacks();
3141
3142     PL_curcop = &PL_compiling;
3143     thr->cvcache = newHV();
3144     thr->threadsv = newAV();
3145     thr->specific = newAV();
3146     thr->errsv = newSVpvn("", 0);
3147     thr->errhv = newHV();
3148     thr->flags = THRf_R_JOINABLE;
3149     MUTEX_INIT(&thr->mutex);
3150
3151     /* top_env needs to be non-zero. It points to an area
3152        in which longjmp() stuff is stored, as C callstack
3153        info there at least is thread specific this has to
3154        be per-thread. Otherwise a 'die' in a thread gives
3155        that thread the C stack of last thread to do an eval {}!
3156        See comments in scope.h    
3157        Initialize top entry (as in perl.c for main thread)
3158      */
3159     PL_start_env.je_prev = NULL;
3160     PL_start_env.je_ret = -1;
3161     PL_start_env.je_mustcatch = TRUE;
3162     PL_top_env  = &PL_start_env;
3163
3164     PL_in_eval = EVAL_NULL;     /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR) */
3165     PL_restartop = 0;
3166
3167     PL_statname = NEWSV(66,0);
3168     PL_maxscream = -1;
3169     PL_regcompp = FUNC_NAME_TO_PTR(Perl_pregcomp);
3170     PL_regexecp = FUNC_NAME_TO_PTR(Perl_regexec_flags);
3171     PL_regindent = 0;
3172     PL_reginterp_cnt = 0;
3173     PL_lastscream = Nullsv;
3174     PL_screamfirst = 0;
3175     PL_screamnext = 0;
3176     PL_reg_start_tmp = 0;
3177     PL_reg_start_tmpl = 0;
3178
3179     /* parent thread's data needs to be locked while we make copy */
3180     MUTEX_LOCK(&t->mutex);
3181
3182     PL_protect = t->Tprotect;
3183
3184     PL_curcop = t->Tcurcop;       /* XXX As good a guess as any? */
3185     PL_defstash = t->Tdefstash;   /* XXX maybe these should */
3186     PL_curstash = t->Tcurstash;   /* always be set to main? */
3187
3188     PL_tainted = t->Ttainted;
3189     PL_curpm = t->Tcurpm;         /* XXX No PMOP ref count */
3190     PL_nrs = newSVsv(t->Tnrs);
3191     PL_rs = SvREFCNT_inc(PL_nrs);
3192     PL_last_in_gv = Nullgv;
3193     PL_ofslen = t->Tofslen;
3194     PL_ofs = savepvn(t->Tofs, PL_ofslen);
3195     PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3196     PL_chopset = t->Tchopset;
3197     PL_formtarget = newSVsv(t->Tformtarget);
3198     PL_bodytarget = newSVsv(t->Tbodytarget);
3199     PL_toptarget = newSVsv(t->Ttoptarget);
3200
3201     /* Initialise all per-thread SVs that the template thread used */
3202     svp = AvARRAY(t->threadsv);
3203     for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3204         if (*svp && *svp != &PL_sv_undef) {
3205             SV *sv = newSVsv(*svp);
3206             av_store(thr->threadsv, i, sv);
3207             sv_magic(sv, 0, 0, &PL_threadsv_names[i], 1);
3208             DEBUG_S(PerlIO_printf(PerlIO_stderr(),
3209                 "new_struct_thread: copied threadsv %d %p->%p\n",i, t, thr));
3210         }
3211     } 
3212     thr->threadsvp = AvARRAY(thr->threadsv);
3213
3214     MUTEX_LOCK(&PL_threads_mutex);
3215     PL_nthreads++;
3216     thr->tid = ++PL_threadnum;
3217     thr->next = t->next;
3218     thr->prev = t;
3219     t->next = thr;
3220     thr->next->prev = thr;
3221     MUTEX_UNLOCK(&PL_threads_mutex);
3222
3223     /* done copying parent's state */
3224     MUTEX_UNLOCK(&t->mutex);
3225
3226 #ifdef HAVE_THREAD_INTERN
3227     init_thread_intern(thr);
3228 #endif /* HAVE_THREAD_INTERN */
3229     return thr;
3230 }
3231 #endif /* USE_THREADS */
3232
3233 #ifdef HUGE_VAL
3234 /*
3235  * This hack is to force load of "huge" support from libm.a
3236  * So it is in perl for (say) POSIX to use. 
3237  * Needed for SunOS with Sun's 'acc' for example.
3238  */
3239 double 
3240 Perl_huge(void)
3241 {
3242  return HUGE_VAL;
3243 }
3244 #endif
3245
3246 #ifdef PERL_GLOBAL_STRUCT
3247 struct perl_vars *
3248 Perl_GetVars(pTHX)
3249 {
3250  return &PL_Vars;
3251 }
3252 #endif
3253
3254 char **
3255 Perl_get_op_names(pTHX)
3256 {
3257  return PL_op_name;
3258 }
3259
3260 char **
3261 Perl_get_op_descs(pTHX)
3262 {
3263  return PL_op_desc;
3264 }
3265
3266 char *
3267 Perl_get_no_modify(pTHX)
3268 {
3269  return (char*)PL_no_modify;
3270 }
3271
3272 U32 *
3273 Perl_get_opargs(pTHX)
3274 {
3275  return PL_opargs;
3276 }
3277
3278 #ifndef HAS_GETENV_LEN
3279 char *
3280 Perl_getenv_len(pTHX_ char *env_elem, unsigned long *len)
3281 {
3282     char *env_trans = PerlEnv_getenv(env_elem);
3283     if (env_trans)
3284         *len = strlen(env_trans);
3285     return env_trans;
3286 }
3287 #endif
3288
3289
3290 MGVTBL*
3291 Perl_get_vtbl(pTHX_ int vtbl_id)
3292 {
3293     MGVTBL* result = Null(MGVTBL*);
3294
3295     switch(vtbl_id) {
3296     case want_vtbl_sv:
3297         result = &PL_vtbl_sv;
3298         break;
3299     case want_vtbl_env:
3300         result = &PL_vtbl_env;
3301         break;
3302     case want_vtbl_envelem:
3303         result = &PL_vtbl_envelem;
3304         break;
3305     case want_vtbl_sig:
3306         result = &PL_vtbl_sig;
3307         break;
3308     case want_vtbl_sigelem:
3309         result = &PL_vtbl_sigelem;
3310         break;
3311     case want_vtbl_pack:
3312         result = &PL_vtbl_pack;
3313         break;
3314     case want_vtbl_packelem:
3315         result = &PL_vtbl_packelem;
3316         break;
3317     case want_vtbl_dbline:
3318         result = &PL_vtbl_dbline;
3319         break;
3320     case want_vtbl_isa:
3321         result = &PL_vtbl_isa;
3322         break;
3323     case want_vtbl_isaelem:
3324         result = &PL_vtbl_isaelem;
3325         break;
3326     case want_vtbl_arylen:
3327         result = &PL_vtbl_arylen;
3328         break;
3329     case want_vtbl_glob:
3330         result = &PL_vtbl_glob;
3331         break;
3332     case want_vtbl_mglob:
3333         result = &PL_vtbl_mglob;
3334         break;
3335     case want_vtbl_nkeys:
3336         result = &PL_vtbl_nkeys;
3337         break;
3338     case want_vtbl_taint:
3339         result = &PL_vtbl_taint;
3340         break;
3341     case want_vtbl_substr:
3342         result = &PL_vtbl_substr;
3343         break;
3344     case want_vtbl_vec:
3345         result = &PL_vtbl_vec;
3346         break;
3347     case want_vtbl_pos:
3348         result = &PL_vtbl_pos;
3349         break;
3350     case want_vtbl_bm:
3351         result = &PL_vtbl_bm;
3352         break;
3353     case want_vtbl_fm:
3354         result = &PL_vtbl_fm;
3355         break;
3356     case want_vtbl_uvar:
3357         result = &PL_vtbl_uvar;
3358         break;
3359 #ifdef USE_THREADS
3360     case want_vtbl_mutex:
3361         result = &PL_vtbl_mutex;
3362         break;
3363 #endif
3364     case want_vtbl_defelem:
3365         result = &PL_vtbl_defelem;
3366         break;
3367     case want_vtbl_regexp:
3368         result = &PL_vtbl_regexp;
3369         break;
3370     case want_vtbl_regdata:
3371         result = &PL_vtbl_regdata;
3372         break;
3373     case want_vtbl_regdatum:
3374         result = &PL_vtbl_regdatum;
3375         break;
3376 #ifdef USE_LOCALE_COLLATE
3377     case want_vtbl_collxfrm:
3378         result = &PL_vtbl_collxfrm;
3379         break;
3380 #endif
3381     case want_vtbl_amagic:
3382         result = &PL_vtbl_amagic;
3383         break;
3384     case want_vtbl_amagicelem:
3385         result = &PL_vtbl_amagicelem;
3386         break;
3387     case want_vtbl_backref:
3388         result = &PL_vtbl_backref;
3389         break;
3390     }
3391     return result;
3392 }
3393
3394 I32
3395 Perl_my_fflush_all(pTHX)
3396 {
3397 #ifdef FFLUSH_NULL
3398     return PerlIO_flush(NULL);
3399 #else
3400     long open_max = -1;
3401 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3402 #  ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3403     open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3404 #  else
3405 #  if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3406     open_max = sysconf(_SC_OPEN_MAX);
3407 #  else
3408 #   ifdef FOPEN_MAX
3409     open_max = FOPEN_MAX;
3410 #   else
3411 #    ifdef OPEN_MAX
3412     open_max = OPEN_MAX;
3413 #    else
3414 #     ifdef _NFILE
3415     open_max = _NFILE;
3416 #     endif
3417 #    endif
3418 #   endif
3419 #  endif
3420 #  endif
3421     if (open_max > 0) {
3422       long i;
3423       for (i = 0; i < open_max; i++)
3424             if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3425                 STDIO_STREAM_ARRAY[i]._file < open_max &&
3426                 STDIO_STREAM_ARRAY[i]._flag)
3427                 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3428       return 0;
3429     }
3430 # endif
3431     SETERRNO(EBADF,RMS$_IFI);
3432     return EOF;
3433 #endif
3434 }