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