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