866e598bf657a59e5e6c825c7ed9d99b8c44541a
[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;
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, U32 flags /* not used yet */)
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
1277 #ifdef I_STDARG
1278     va_start(args, pat);
1279 #else
1280     va_start(args);
1281 #endif
1282     message = mess(pat, &args);
1283     va_end(args);
1284
1285 #ifdef USE_THREADS
1286     DEBUG_L(PerlIO_printf(PerlIO_stderr(),
1287                           "%p: die: message = %s\ndiehook = %p\n",
1288                           thr, message, diehook));
1289 #endif /* USE_THREADS */
1290     if (diehook) {
1291         /* sv_2cv might call croak() */
1292         SV *olddiehook = diehook;
1293         ENTER;
1294         SAVESPTR(diehook);
1295         diehook = Nullsv;
1296         cv = sv_2cv(olddiehook, &stash, &gv, 0);
1297         LEAVE;
1298         if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1299             dSP;
1300             SV *msg;
1301
1302             ENTER;
1303             msg = newSVpv(message, 0);
1304             SvREADONLY_on(msg);
1305             SAVEFREESV(msg);
1306
1307             PUSHSTACK(SI_DIEHOOK);
1308             PUSHMARK(SP);
1309             XPUSHs(msg);
1310             PUTBACK;
1311             perl_call_sv((SV*)cv, G_DISCARD);
1312             POPSTACK();
1313             LEAVE;
1314         }
1315     }
1316
1317     restartop = die_where(message);
1318 #ifdef USE_THREADS
1319     DEBUG_L(PerlIO_printf(PerlIO_stderr(),
1320           "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1321           thr, restartop, was_in_eval, top_env));
1322 #endif /* USE_THREADS */
1323     if ((!restartop && was_in_eval) || top_env->je_prev)
1324         JMPENV_JUMP(3);
1325     return restartop;
1326 }
1327
1328 #ifdef I_STDARG
1329 void
1330 croak(const char* pat, ...)
1331 #else
1332 /*VARARGS0*/
1333 void
1334 croak(pat, va_alist)
1335     char *pat;
1336     va_dcl
1337 #endif
1338 {
1339     dTHR;
1340     va_list args;
1341     char *message;
1342     HV *stash;
1343     GV *gv;
1344     CV *cv;
1345
1346 #ifdef I_STDARG
1347     va_start(args, pat);
1348 #else
1349     va_start(args);
1350 #endif
1351     message = mess(pat, &args);
1352     va_end(args);
1353 #ifdef USE_THREADS
1354     DEBUG_L(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
1355 #endif /* USE_THREADS */
1356     if (diehook) {
1357         /* sv_2cv might call croak() */
1358         SV *olddiehook = diehook;
1359         ENTER;
1360         SAVESPTR(diehook);
1361         diehook = Nullsv;
1362         cv = sv_2cv(olddiehook, &stash, &gv, 0);
1363         LEAVE;
1364         if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1365             dSP;
1366             SV *msg;
1367
1368             ENTER;
1369             msg = newSVpv(message, 0);
1370             SvREADONLY_on(msg);
1371             SAVEFREESV(msg);
1372
1373             PUSHSTACK(SI_DIEHOOK);
1374             PUSHMARK(SP);
1375             XPUSHs(msg);
1376             PUTBACK;
1377             perl_call_sv((SV*)cv, G_DISCARD);
1378             POPSTACK();
1379             LEAVE;
1380         }
1381     }
1382     if (in_eval) {
1383         restartop = die_where(message);
1384         JMPENV_JUMP(3);
1385     }
1386     PerlIO_puts(PerlIO_stderr(),message);
1387     (void)PerlIO_flush(PerlIO_stderr());
1388     my_failure_exit();
1389 }
1390
1391 void
1392 #ifdef I_STDARG
1393 warn(const char* pat,...)
1394 #else
1395 /*VARARGS0*/
1396 warn(pat,va_alist)
1397     const char *pat;
1398     va_dcl
1399 #endif
1400 {
1401     va_list args;
1402     char *message;
1403     HV *stash;
1404     GV *gv;
1405     CV *cv;
1406
1407 #ifdef I_STDARG
1408     va_start(args, pat);
1409 #else
1410     va_start(args);
1411 #endif
1412     message = mess(pat, &args);
1413     va_end(args);
1414
1415     if (warnhook) {
1416         /* sv_2cv might call warn() */
1417         dTHR;
1418         SV *oldwarnhook = warnhook;
1419         ENTER;
1420         SAVESPTR(warnhook);
1421         warnhook = Nullsv;
1422         cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1423         LEAVE;
1424         if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1425             dSP;
1426             SV *msg;
1427
1428             ENTER;
1429             msg = newSVpv(message, 0);
1430             SvREADONLY_on(msg);
1431             SAVEFREESV(msg);
1432
1433             PUSHSTACK(SI_WARNHOOK);
1434             PUSHMARK(SP);
1435             XPUSHs(msg);
1436             PUTBACK;
1437             perl_call_sv((SV*)cv, G_DISCARD);
1438             POPSTACK();
1439             LEAVE;
1440             return;
1441         }
1442     }
1443     PerlIO_puts(PerlIO_stderr(),message);
1444 #ifdef LEAKTEST
1445     DEBUG_L(*message == '!' 
1446             ? (xstat(message[1]=='!'
1447                      ? (message[2]=='!' ? 2 : 1)
1448                      : 0)
1449                , 0)
1450             : 0);
1451 #endif
1452     (void)PerlIO_flush(PerlIO_stderr());
1453 }
1454
1455 #ifndef VMS  /* VMS' my_setenv() is in VMS.c */
1456 #ifndef WIN32
1457 void
1458 my_setenv(char *nam, char *val)
1459 {
1460     register I32 i=setenv_getix(nam);           /* where does it go? */
1461
1462     if (environ == origenviron) {       /* need we copy environment? */
1463         I32 j;
1464         I32 max;
1465         char **tmpenv;
1466
1467         /*SUPPRESS 530*/
1468         for (max = i; environ[max]; max++) ;
1469         New(901,tmpenv, max+2, char*);
1470         for (j=0; j<max; j++)           /* copy environment */
1471             tmpenv[j] = savepv(environ[j]);
1472         tmpenv[max] = Nullch;
1473         environ = tmpenv;               /* tell exec where it is now */
1474     }
1475     if (!val) {
1476         Safefree(environ[i]);
1477         while (environ[i]) {
1478             environ[i] = environ[i+1];
1479             i++;
1480         }
1481         return;
1482     }
1483     if (!environ[i]) {                  /* does not exist yet */
1484         Renew(environ, i+2, char*);     /* just expand it a bit */
1485         environ[i+1] = Nullch;  /* make sure it's null terminated */
1486     }
1487     else
1488         Safefree(environ[i]);
1489     New(904, environ[i], strlen(nam) + strlen(val) + 2, char);
1490 #ifndef MSDOS
1491     (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
1492 #else
1493     /* MS-DOS requires environment variable names to be in uppercase */
1494     /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
1495      * some utilities and applications may break because they only look
1496      * for upper case strings. (Fixed strupr() bug here.)]
1497      */
1498     strcpy(environ[i],nam); strupr(environ[i]);
1499     (void)sprintf(environ[i] + strlen(nam),"=%s",val);
1500 #endif /* MSDOS */
1501 }
1502
1503 #else /* if WIN32 */
1504
1505 void
1506 my_setenv(char *nam,char *val)
1507 {
1508
1509 #ifdef USE_WIN32_RTL_ENV
1510
1511     register char *envstr;
1512     STRLEN namlen = strlen(nam);
1513     STRLEN vallen;
1514     char *oldstr = environ[setenv_getix(nam)];
1515
1516     /* putenv() has totally broken semantics in both the Borland
1517      * and Microsoft CRTLs.  They either store the passed pointer in
1518      * the environment without making a copy, or make a copy and don't
1519      * free it. And on top of that, they dont free() old entries that
1520      * are being replaced/deleted.  This means the caller must
1521      * free any old entries somehow, or we end up with a memory
1522      * leak every time my_setenv() is called.  One might think
1523      * one could directly manipulate environ[], like the UNIX code
1524      * above, but direct changes to environ are not allowed when
1525      * calling putenv(), since the RTLs maintain an internal
1526      * *copy* of environ[]. Bad, bad, *bad* stink.
1527      * GSAR 97-06-07
1528      */
1529
1530     if (!val) {
1531         if (!oldstr)
1532             return;
1533         val = "";
1534         vallen = 0;
1535     }
1536     else
1537         vallen = strlen(val);
1538     New(904, envstr, namlen + vallen + 3, char);
1539     (void)sprintf(envstr,"%s=%s",nam,val);
1540     (void)PerlEnv_putenv(envstr);
1541     if (oldstr)
1542         Safefree(oldstr);
1543 #ifdef _MSC_VER
1544     Safefree(envstr);           /* MSVCRT leaks without this */
1545 #endif
1546
1547 #else /* !USE_WIN32_RTL_ENV */
1548
1549     /* The sane way to deal with the environment.
1550      * Has these advantages over putenv() & co.:
1551      *  * enables us to store a truly empty value in the
1552      *    environment (like in UNIX).
1553      *  * we don't have to deal with RTL globals, bugs and leaks.
1554      *  * Much faster.
1555      * Why you may want to enable USE_WIN32_RTL_ENV:
1556      *  * environ[] and RTL functions will not reflect changes,
1557      *    which might be an issue if extensions want to access
1558      *    the env. via RTL.  This cuts both ways, since RTL will
1559      *    not see changes made by extensions that call the Win32
1560      *    functions directly, either.
1561      * GSAR 97-06-07
1562      */
1563     SetEnvironmentVariable(nam,val);
1564
1565 #endif
1566 }
1567
1568 #endif /* WIN32 */
1569
1570 I32
1571 setenv_getix(char *nam)
1572 {
1573     register I32 i, len = strlen(nam);
1574
1575     for (i = 0; environ[i]; i++) {
1576         if (
1577 #ifdef WIN32
1578             strnicmp(environ[i],nam,len) == 0
1579 #else
1580             strnEQ(environ[i],nam,len)
1581 #endif
1582             && environ[i][len] == '=')
1583             break;                      /* strnEQ must come first to avoid */
1584     }                                   /* potential SEGV's */
1585     return i;
1586 }
1587
1588 #endif /* !VMS */
1589
1590 #ifdef UNLINK_ALL_VERSIONS
1591 I32
1592 unlnk(f)        /* unlink all versions of a file */
1593 char *f;
1594 {
1595     I32 i;
1596
1597     for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1598     return i ? 0 : -1;
1599 }
1600 #endif
1601
1602 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
1603 char *
1604 my_bcopy(register char *from,register char *to,register I32 len)
1605 {
1606     char *retval = to;
1607
1608     if (from - to >= 0) {
1609         while (len--)
1610             *to++ = *from++;
1611     }
1612     else {
1613         to += len;
1614         from += len;
1615         while (len--)
1616             *(--to) = *(--from);
1617     }
1618     return retval;
1619 }
1620 #endif
1621
1622 #ifndef HAS_MEMSET
1623 void *
1624 my_memset(loc,ch,len)
1625 register char *loc;
1626 register I32 ch;
1627 register I32 len;
1628 {
1629     char *retval = loc;
1630
1631     while (len--)
1632         *loc++ = ch;
1633     return retval;
1634 }
1635 #endif
1636
1637 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1638 char *
1639 my_bzero(loc,len)
1640 register char *loc;
1641 register I32 len;
1642 {
1643     char *retval = loc;
1644
1645     while (len--)
1646         *loc++ = 0;
1647     return retval;
1648 }
1649 #endif
1650
1651 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1652 I32
1653 my_memcmp(s1,s2,len)
1654 char *s1;
1655 char *s2;
1656 register I32 len;
1657 {
1658     register U8 *a = (U8 *)s1;
1659     register U8 *b = (U8 *)s2;
1660     register I32 tmp;
1661
1662     while (len--) {
1663         if (tmp = *a++ - *b++)
1664             return tmp;
1665     }
1666     return 0;
1667 }
1668 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1669
1670 #if defined(I_STDARG) || defined(I_VARARGS)
1671 #ifndef HAS_VPRINTF
1672
1673 #ifdef USE_CHAR_VSPRINTF
1674 char *
1675 #else
1676 int
1677 #endif
1678 vsprintf(dest, pat, args)
1679 char *dest;
1680 const char *pat;
1681 char *args;
1682 {
1683     FILE fakebuf;
1684
1685     fakebuf._ptr = dest;
1686     fakebuf._cnt = 32767;
1687 #ifndef _IOSTRG
1688 #define _IOSTRG 0
1689 #endif
1690     fakebuf._flag = _IOWRT|_IOSTRG;
1691     _doprnt(pat, args, &fakebuf);       /* what a kludge */
1692     (void)putc('\0', &fakebuf);
1693 #ifdef USE_CHAR_VSPRINTF
1694     return(dest);
1695 #else
1696     return 0;           /* perl doesn't use return value */
1697 #endif
1698 }
1699
1700 #endif /* HAS_VPRINTF */
1701 #endif /* I_VARARGS || I_STDARGS */
1702
1703 #ifdef MYSWAP
1704 #if BYTEORDER != 0x4321
1705 short
1706 my_swap(short s)
1707 {
1708 #if (BYTEORDER & 1) == 0
1709     short result;
1710
1711     result = ((s & 255) << 8) + ((s >> 8) & 255);
1712     return result;
1713 #else
1714     return s;
1715 #endif
1716 }
1717
1718 long
1719 my_htonl(long l)
1720 {
1721     union {
1722         long result;
1723         char c[sizeof(long)];
1724     } u;
1725
1726 #if BYTEORDER == 0x1234
1727     u.c[0] = (l >> 24) & 255;
1728     u.c[1] = (l >> 16) & 255;
1729     u.c[2] = (l >> 8) & 255;
1730     u.c[3] = l & 255;
1731     return u.result;
1732 #else
1733 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1734     croak("Unknown BYTEORDER\n");
1735 #else
1736     register I32 o;
1737     register I32 s;
1738
1739     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1740         u.c[o & 0xf] = (l >> s) & 255;
1741     }
1742     return u.result;
1743 #endif
1744 #endif
1745 }
1746
1747 long
1748 my_ntohl(long l)
1749 {
1750     union {
1751         long l;
1752         char c[sizeof(long)];
1753     } u;
1754
1755 #if BYTEORDER == 0x1234
1756     u.c[0] = (l >> 24) & 255;
1757     u.c[1] = (l >> 16) & 255;
1758     u.c[2] = (l >> 8) & 255;
1759     u.c[3] = l & 255;
1760     return u.l;
1761 #else
1762 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1763     croak("Unknown BYTEORDER\n");
1764 #else
1765     register I32 o;
1766     register I32 s;
1767
1768     u.l = l;
1769     l = 0;
1770     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1771         l |= (u.c[o & 0xf] & 255) << s;
1772     }
1773     return l;
1774 #endif
1775 #endif
1776 }
1777
1778 #endif /* BYTEORDER != 0x4321 */
1779 #endif /* MYSWAP */
1780
1781 /*
1782  * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1783  * If these functions are defined,
1784  * the BYTEORDER is neither 0x1234 nor 0x4321.
1785  * However, this is not assumed.
1786  * -DWS
1787  */
1788
1789 #define HTOV(name,type)                                         \
1790         type                                                    \
1791         name (n)                                                \
1792         register type n;                                        \
1793         {                                                       \
1794             union {                                             \
1795                 type value;                                     \
1796                 char c[sizeof(type)];                           \
1797             } u;                                                \
1798             register I32 i;                                     \
1799             register I32 s;                                     \
1800             for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) {  \
1801                 u.c[i] = (n >> s) & 0xFF;                       \
1802             }                                                   \
1803             return u.value;                                     \
1804         }
1805
1806 #define VTOH(name,type)                                         \
1807         type                                                    \
1808         name (n)                                                \
1809         register type n;                                        \
1810         {                                                       \
1811             union {                                             \
1812                 type value;                                     \
1813                 char c[sizeof(type)];                           \
1814             } u;                                                \
1815             register I32 i;                                     \
1816             register I32 s;                                     \
1817             u.value = n;                                        \
1818             n = 0;                                              \
1819             for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) {  \
1820                 n += (u.c[i] & 0xFF) << s;                      \
1821             }                                                   \
1822             return n;                                           \
1823         }
1824
1825 #if defined(HAS_HTOVS) && !defined(htovs)
1826 HTOV(htovs,short)
1827 #endif
1828 #if defined(HAS_HTOVL) && !defined(htovl)
1829 HTOV(htovl,long)
1830 #endif
1831 #if defined(HAS_VTOHS) && !defined(vtohs)
1832 VTOH(vtohs,short)
1833 #endif
1834 #if defined(HAS_VTOHL) && !defined(vtohl)
1835 VTOH(vtohl,long)
1836 #endif
1837
1838 int
1839 do_binmode(PerlIO *fp, int iotype, int flag)
1840 {
1841     if (flag != TRUE)
1842         croak("panic: unsetting binmode"); /* Not implemented yet */
1843 #ifdef DOSISH
1844 #ifdef atarist
1845     if (!PerlIO_flush(fp) && (fp->_flag |= _IOBIN))
1846         return 1;
1847     else
1848         return 0;
1849 #else
1850     if (PerlLIO_setmode(PerlIO_fileno(fp), OP_BINARY) != -1) {
1851 #if defined(WIN32) && defined(__BORLANDC__)
1852         /* The translation mode of the stream is maintained independent
1853          * of the translation mode of the fd in the Borland RTL (heavy
1854          * digging through their runtime sources reveal).  User has to
1855          * set the mode explicitly for the stream (though they don't
1856          * document this anywhere). GSAR 97-5-24
1857          */
1858         PerlIO_seek(fp,0L,0);
1859         fp->flags |= _F_BIN;
1860 #endif
1861         return 1;
1862     }
1863     else
1864         return 0;
1865 #endif
1866 #else
1867 #if defined(USEMYBINMODE)
1868     if (my_binmode(fp,iotype) != NULL)
1869         return 1;
1870     else
1871         return 0;
1872 #else
1873     return 1;
1874 #endif
1875 #endif
1876 }
1877
1878     /* VMS' my_popen() is in VMS.c, same with OS/2. */
1879 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS)
1880 PerlIO *
1881 my_popen(char *cmd, char *mode)
1882 {
1883     int p[2];
1884     register I32 This, that;
1885     register I32 pid;
1886     SV *sv;
1887     I32 doexec = strNE(cmd,"-");
1888
1889 #ifdef OS2
1890     if (doexec) {
1891         return my_syspopen(cmd,mode);
1892     }
1893 #endif 
1894     This = (*mode == 'w');
1895     that = !This;
1896     if (doexec && tainting) {
1897         taint_env();
1898         taint_proper("Insecure %s%s", "EXEC");
1899     }
1900     if (PerlProc_pipe(p) < 0)
1901         return Nullfp;
1902     while ((pid = (doexec?vfork():fork())) < 0) {
1903         if (errno != EAGAIN) {
1904             PerlLIO_close(p[This]);
1905             if (!doexec)
1906                 croak("Can't fork");
1907             return Nullfp;
1908         }
1909         sleep(5);
1910     }
1911     if (pid == 0) {
1912         GV* tmpgv;
1913
1914 #define THIS that
1915 #define THAT This
1916         PerlLIO_close(p[THAT]);
1917         if (p[THIS] != (*mode == 'r')) {
1918             PerlLIO_dup2(p[THIS], *mode == 'r');
1919             PerlLIO_close(p[THIS]);
1920         }
1921         if (doexec) {
1922 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1923             int fd;
1924
1925 #ifndef NOFILE
1926 #define NOFILE 20
1927 #endif
1928             for (fd = maxsysfd + 1; fd < NOFILE; fd++)
1929                 PerlLIO_close(fd);
1930 #endif
1931             do_exec(cmd);       /* may or may not use the shell */
1932             PerlProc__exit(1);
1933         }
1934         /*SUPPRESS 560*/
1935         if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
1936             sv_setiv(GvSV(tmpgv), (IV)getpid());
1937         forkprocess = 0;
1938         hv_clear(pidstatus);    /* we have no children */
1939         return Nullfp;
1940 #undef THIS
1941 #undef THAT
1942     }
1943     do_execfree();      /* free any memory malloced by child on vfork */
1944     PerlLIO_close(p[that]);
1945     if (p[that] < p[This]) {
1946         PerlLIO_dup2(p[This], p[that]);
1947         PerlLIO_close(p[This]);
1948         p[This] = p[that];
1949     }
1950     sv = *av_fetch(fdpid,p[This],TRUE);
1951     (void)SvUPGRADE(sv,SVt_IV);
1952     SvIVX(sv) = pid;
1953     forkprocess = pid;
1954     return PerlIO_fdopen(p[This], mode);
1955 }
1956 #else
1957 #if defined(atarist) || defined(DJGPP)
1958 FILE *popen();
1959 PerlIO *
1960 my_popen(cmd,mode)
1961 char    *cmd;
1962 char    *mode;
1963 {
1964     /* Needs work for PerlIO ! */
1965     /* used 0 for 2nd parameter to PerlIO-exportFILE; apparently not used */
1966     return popen(PerlIO_exportFILE(cmd, 0), mode);
1967 }
1968 #endif
1969
1970 #endif /* !DOSISH */
1971
1972 #ifdef DUMP_FDS
1973 dump_fds(s)
1974 char *s;
1975 {
1976     int fd;
1977     struct stat tmpstatbuf;
1978
1979     PerlIO_printf(PerlIO_stderr(),"%s", s);
1980     for (fd = 0; fd < 32; fd++) {
1981         if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
1982             PerlIO_printf(PerlIO_stderr()," %d",fd);
1983     }
1984     PerlIO_printf(PerlIO_stderr(),"\n");
1985 }
1986 #endif
1987
1988 #ifndef HAS_DUP2
1989 int
1990 dup2(oldfd,newfd)
1991 int oldfd;
1992 int newfd;
1993 {
1994 #if defined(HAS_FCNTL) && defined(F_DUPFD)
1995     if (oldfd == newfd)
1996         return oldfd;
1997     PerlLIO_close(newfd);
1998     return fcntl(oldfd, F_DUPFD, newfd);
1999 #else
2000 #define DUP2_MAX_FDS 256
2001     int fdtmp[DUP2_MAX_FDS];
2002     I32 fdx = 0;
2003     int fd;
2004
2005     if (oldfd == newfd)
2006         return oldfd;
2007     PerlLIO_close(newfd);
2008     /* good enough for low fd's... */
2009     while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2010         if (fdx >= DUP2_MAX_FDS) {
2011             PerlLIO_close(fd);
2012             fd = -1;
2013             break;
2014         }
2015         fdtmp[fdx++] = fd;
2016     }
2017     while (fdx > 0)
2018         PerlLIO_close(fdtmp[--fdx]);
2019     return fd;
2020 #endif
2021 }
2022 #endif
2023
2024
2025 #ifdef HAS_SIGACTION
2026
2027 Sighandler_t
2028 rsignal(int signo, Sighandler_t handler)
2029 {
2030     struct sigaction act, oact;
2031
2032     act.sa_handler = handler;
2033     sigemptyset(&act.sa_mask);
2034     act.sa_flags = 0;
2035 #ifdef SA_RESTART
2036     act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2037 #endif
2038     if (sigaction(signo, &act, &oact) == -1)
2039         return SIG_ERR;
2040     else
2041         return oact.sa_handler;
2042 }
2043
2044 Sighandler_t
2045 rsignal_state(int signo)
2046 {
2047     struct sigaction oact;
2048
2049     if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2050         return SIG_ERR;
2051     else
2052         return oact.sa_handler;
2053 }
2054
2055 int
2056 rsignal_save(int signo, Sighandler_t handler, Sigsave_t *save)
2057 {
2058     struct sigaction act;
2059
2060     act.sa_handler = handler;
2061     sigemptyset(&act.sa_mask);
2062     act.sa_flags = 0;
2063 #ifdef SA_RESTART
2064     act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2065 #endif
2066     return sigaction(signo, &act, save);
2067 }
2068
2069 int
2070 rsignal_restore(int signo, Sigsave_t *save)
2071 {
2072     return sigaction(signo, save, (struct sigaction *)NULL);
2073 }
2074
2075 #else /* !HAS_SIGACTION */
2076
2077 Sighandler_t
2078 rsignal(int signo, Sighandler_t handler)
2079 {
2080     return PerlProc_signal(signo, handler);
2081 }
2082
2083 static int sig_trapped;
2084
2085 static
2086 Signal_t
2087 sig_trap(int signo)
2088 {
2089     sig_trapped++;
2090 }
2091
2092 Sighandler_t
2093 rsignal_state(int signo)
2094 {
2095     Sighandler_t oldsig;
2096
2097     sig_trapped = 0;
2098     oldsig = PerlProc_signal(signo, sig_trap);
2099     PerlProc_signal(signo, oldsig);
2100     if (sig_trapped)
2101         PerlProc_kill(getpid(), signo);
2102     return oldsig;
2103 }
2104
2105 int
2106 rsignal_save(int signo, Sighandler_t handler, Sigsave_t *save)
2107 {
2108     *save = PerlProc_signal(signo, handler);
2109     return (*save == SIG_ERR) ? -1 : 0;
2110 }
2111
2112 int
2113 rsignal_restore(int signo, Sigsave_t *save)
2114 {
2115     return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2116 }
2117
2118 #endif /* !HAS_SIGACTION */
2119
2120     /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2121 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS)
2122 I32
2123 my_pclose(PerlIO *ptr)
2124 {
2125     Sigsave_t hstat, istat, qstat;
2126     int status;
2127     SV **svp;
2128     int pid;
2129     bool close_failed;
2130     int saved_errno;
2131 #ifdef VMS
2132     int saved_vaxc_errno;
2133 #endif
2134 #ifdef WIN32
2135     int saved_win32_errno;
2136 #endif
2137
2138     svp = av_fetch(fdpid,PerlIO_fileno(ptr),TRUE);
2139     pid = (int)SvIVX(*svp);
2140     SvREFCNT_dec(*svp);
2141     *svp = &sv_undef;
2142 #ifdef OS2
2143     if (pid == -1) {                    /* Opened by popen. */
2144         return my_syspclose(ptr);
2145     }
2146 #endif 
2147     if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2148         saved_errno = errno;
2149 #ifdef VMS
2150         saved_vaxc_errno = vaxc$errno;
2151 #endif
2152 #ifdef WIN32
2153         saved_win32_errno = GetLastError();
2154 #endif
2155     }
2156 #ifdef UTS
2157     if(PerlProc_kill(pid, 0) < 0) { return(pid); }   /* HOM 12/23/91 */
2158 #endif
2159     rsignal_save(SIGHUP, SIG_IGN, &hstat);
2160     rsignal_save(SIGINT, SIG_IGN, &istat);
2161     rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2162     do {
2163         pid = wait4pid(pid, &status, 0);
2164     } while (pid == -1 && errno == EINTR);
2165     rsignal_restore(SIGHUP, &hstat);
2166     rsignal_restore(SIGINT, &istat);
2167     rsignal_restore(SIGQUIT, &qstat);
2168     if (close_failed) {
2169         SETERRNO(saved_errno, saved_vaxc_errno);
2170         return -1;
2171     }
2172     return(pid < 0 ? pid : status == 0 ? 0 : (errno = 0, status));
2173 }
2174 #endif /* !DOSISH */
2175
2176 #if  !defined(DOSISH) || defined(OS2) || defined(WIN32)
2177 I32
2178 wait4pid(int pid, int *statusp, int flags)
2179 {
2180     SV *sv;
2181     SV** svp;
2182     char spid[TYPE_CHARS(int)];
2183
2184     if (!pid)
2185         return -1;
2186     if (pid > 0) {
2187         sprintf(spid, "%d", pid);
2188         svp = hv_fetch(pidstatus,spid,strlen(spid),FALSE);
2189         if (svp && *svp != &sv_undef) {
2190             *statusp = SvIVX(*svp);
2191             (void)hv_delete(pidstatus,spid,strlen(spid),G_DISCARD);
2192             return pid;
2193         }
2194     }
2195     else {
2196         HE *entry;
2197
2198         hv_iterinit(pidstatus);
2199         if (entry = hv_iternext(pidstatus)) {
2200             pid = atoi(hv_iterkey(entry,(I32*)statusp));
2201             sv = hv_iterval(pidstatus,entry);
2202             *statusp = SvIVX(sv);
2203             sprintf(spid, "%d", pid);
2204             (void)hv_delete(pidstatus,spid,strlen(spid),G_DISCARD);
2205             return pid;
2206         }
2207     }
2208 #ifdef HAS_WAITPID
2209 #  ifdef HAS_WAITPID_RUNTIME
2210     if (!HAS_WAITPID_RUNTIME)
2211         goto hard_way;
2212 #  endif
2213     return waitpid(pid,statusp,flags);
2214 #endif
2215 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2216     return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2217 #endif
2218 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2219   hard_way:
2220     {
2221         I32 result;
2222         if (flags)
2223             croak("Can't do waitpid with flags");
2224         else {
2225             while ((result = wait(statusp)) != pid && pid > 0 && result >= 0)
2226                 pidgone(result,*statusp);
2227             if (result < 0)
2228                 *statusp = -1;
2229         }
2230         return result;
2231     }
2232 #endif
2233 }
2234 #endif /* !DOSISH || OS2 || WIN32 */
2235
2236 void
2237 /*SUPPRESS 590*/
2238 pidgone(int pid, int status)
2239 {
2240     register SV *sv;
2241     char spid[TYPE_CHARS(int)];
2242
2243     sprintf(spid, "%d", pid);
2244     sv = *hv_fetch(pidstatus,spid,strlen(spid),TRUE);
2245     (void)SvUPGRADE(sv,SVt_IV);
2246     SvIVX(sv) = status;
2247     return;
2248 }
2249
2250 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2251 int pclose();
2252 #ifdef HAS_FORK
2253 int                                     /* Cannot prototype with I32
2254                                            in os2ish.h. */
2255 my_syspclose(ptr)
2256 #else
2257 I32
2258 my_pclose(ptr)
2259 #endif 
2260 PerlIO *ptr;
2261 {
2262     /* Needs work for PerlIO ! */
2263     FILE *f = PerlIO_findFILE(ptr);
2264     I32 result = pclose(f);
2265     PerlIO_releaseFILE(ptr,f);
2266     return result;
2267 }
2268 #endif
2269
2270 void
2271 repeatcpy(register char *to, register char *from, I32 len, register I32 count)
2272 {
2273     register I32 todo;
2274     register char *frombase = from;
2275
2276     if (len == 1) {
2277         todo = *from;
2278         while (count-- > 0)
2279             *to++ = todo;
2280         return;
2281     }
2282     while (count-- > 0) {
2283         for (todo = len; todo > 0; todo--) {
2284             *to++ = *from++;
2285         }
2286         from = frombase;
2287     }
2288 }
2289
2290 #ifndef CASTNEGFLOAT
2291 U32
2292 cast_ulong(f)
2293 double f;
2294 {
2295     long along;
2296
2297 #if CASTFLAGS & 2
2298 #   define BIGDOUBLE 2147483648.0
2299     if (f >= BIGDOUBLE)
2300         return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2301 #endif
2302     if (f >= 0.0)
2303         return (unsigned long)f;
2304     along = (long)f;
2305     return (unsigned long)along;
2306 }
2307 # undef BIGDOUBLE
2308 #endif
2309
2310 #ifndef CASTI32
2311
2312 /* Unfortunately, on some systems the cast_uv() function doesn't
2313    work with the system-supplied definition of ULONG_MAX.  The
2314    comparison  (f >= ULONG_MAX) always comes out true.  It must be a
2315    problem with the compiler constant folding.
2316
2317    In any case, this workaround should be fine on any two's complement
2318    system.  If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2319    ccflags.
2320                --Andy Dougherty      <doughera@lafcol.lafayette.edu>
2321 */
2322
2323 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2324    of LONG_(MIN/MAX).
2325                            -- Kenneth Albanowski <kjahds@kjahds.com>
2326 */                                      
2327
2328 #ifndef MY_UV_MAX
2329 #  define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2330 #endif
2331
2332 I32
2333 cast_i32(f)
2334 double f;
2335 {
2336     if (f >= I32_MAX)
2337         return (I32) I32_MAX;
2338     if (f <= I32_MIN)
2339         return (I32) I32_MIN;
2340     return (I32) f;
2341 }
2342
2343 IV
2344 cast_iv(f)
2345 double f;
2346 {
2347     if (f >= IV_MAX)
2348         return (IV) IV_MAX;
2349     if (f <= IV_MIN)
2350         return (IV) IV_MIN;
2351     return (IV) f;
2352 }
2353
2354 UV
2355 cast_uv(f)
2356 double f;
2357 {
2358     if (f >= MY_UV_MAX)
2359         return (UV) MY_UV_MAX;
2360     return (UV) f;
2361 }
2362
2363 #endif
2364
2365 #ifndef HAS_RENAME
2366 I32
2367 same_dirent(a,b)
2368 char *a;
2369 char *b;
2370 {
2371     char *fa = strrchr(a,'/');
2372     char *fb = strrchr(b,'/');
2373     struct stat tmpstatbuf1;
2374     struct stat tmpstatbuf2;
2375     SV *tmpsv = sv_newmortal();
2376
2377     if (fa)
2378         fa++;
2379     else
2380         fa = a;
2381     if (fb)
2382         fb++;
2383     else
2384         fb = b;
2385     if (strNE(a,b))
2386         return FALSE;
2387     if (fa == a)
2388         sv_setpv(tmpsv, ".");
2389     else
2390         sv_setpvn(tmpsv, a, fa - a);
2391     if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2392         return FALSE;
2393     if (fb == b)
2394         sv_setpv(tmpsv, ".");
2395     else
2396         sv_setpvn(tmpsv, b, fb - b);
2397     if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2398         return FALSE;
2399     return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2400            tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2401 }
2402 #endif /* !HAS_RENAME */
2403
2404 UV
2405 scan_oct(char *start, I32 len, I32 *retlen)
2406 {
2407     register char *s = start;
2408     register UV retval = 0;
2409     bool overflowed = FALSE;
2410
2411     while (len && *s >= '0' && *s <= '7') {
2412         register UV n = retval << 3;
2413         if (!overflowed && (n >> 3) != retval) {
2414             warn("Integer overflow in octal number");
2415             overflowed = TRUE;
2416         }
2417         retval = n | (*s++ - '0');
2418         len--;
2419     }
2420     if (dowarn && len && (*s == '8' || *s == '9'))
2421         warn("Illegal octal digit ignored");
2422     *retlen = s - start;
2423     return retval;
2424 }
2425
2426 UV
2427 scan_hex(char *start, I32 len, I32 *retlen)
2428 {
2429     register char *s = start;
2430     register UV retval = 0;
2431     bool overflowed = FALSE;
2432     char *tmp;
2433
2434     while (len-- && *s && (tmp = strchr((char *) hexdigit, *s))) {
2435         register UV n = retval << 4;
2436         if (!overflowed && (n >> 4) != retval) {
2437             warn("Integer overflow in hex number");
2438             overflowed = TRUE;
2439         }
2440         retval = n | ((tmp - hexdigit) & 15);
2441         s++;
2442     }
2443     *retlen = s - start;
2444     return retval;
2445 }
2446
2447 char*
2448 find_script(char *scriptname, bool dosearch, char **search_ext, I32 flags)
2449 {
2450     dTHR;
2451     char *xfound = Nullch;
2452     char *xfailed = Nullch;
2453     register char *s;
2454     I32 len;
2455     int retval;
2456 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2457 #  define SEARCH_EXTS ".bat", ".cmd", NULL
2458 #  define MAX_EXT_LEN 4
2459 #endif
2460 #ifdef OS2
2461 #  define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2462 #  define MAX_EXT_LEN 4
2463 #endif
2464 #ifdef VMS
2465 #  define SEARCH_EXTS ".pl", ".com", NULL
2466 #  define MAX_EXT_LEN 4
2467 #endif
2468     /* additional extensions to try in each dir if scriptname not found */
2469 #ifdef SEARCH_EXTS
2470     char *exts[] = { SEARCH_EXTS };
2471     char **ext = search_ext ? search_ext : exts;
2472     int extidx = 0, i = 0;
2473     char *curext = Nullch;
2474 #else
2475 #  define MAX_EXT_LEN 0
2476 #endif
2477
2478     /*
2479      * If dosearch is true and if scriptname does not contain path
2480      * delimiters, search the PATH for scriptname.
2481      *
2482      * If SEARCH_EXTS is also defined, will look for each
2483      * scriptname{SEARCH_EXTS} whenever scriptname is not found
2484      * while searching the PATH.
2485      *
2486      * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2487      * proceeds as follows:
2488      *   If DOSISH or VMSISH:
2489      *     + look for ./scriptname{,.foo,.bar}
2490      *     + search the PATH for scriptname{,.foo,.bar}
2491      *
2492      *   If !DOSISH:
2493      *     + look *only* in the PATH for scriptname{,.foo,.bar} (note
2494      *       this will not look in '.' if it's not in the PATH)
2495      */
2496
2497 #ifdef VMS
2498 #  ifdef ALWAYS_DEFTYPES
2499     len = strlen(scriptname);
2500     if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2501         int hasdir, idx = 0, deftypes = 1;
2502         bool seen_dot = 1;
2503
2504         hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2505 #  else
2506     if (dosearch) {
2507         int hasdir, idx = 0, deftypes = 1;
2508         bool seen_dot = 1;
2509
2510         hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2511 #  endif
2512         /* The first time through, just add SEARCH_EXTS to whatever we
2513          * already have, so we can check for default file types. */
2514         while (deftypes ||
2515                (!hasdir && my_trnlnm("DCL$PATH",tokenbuf,idx++)) )
2516         {
2517             if (deftypes) {
2518                 deftypes = 0;
2519                 *tokenbuf = '\0';
2520             }
2521             if ((strlen(tokenbuf) + strlen(scriptname)
2522                  + MAX_EXT_LEN) >= sizeof tokenbuf)
2523                 continue;       /* don't search dir with too-long name */
2524             strcat(tokenbuf, scriptname);
2525 #else  /* !VMS */
2526
2527 #ifdef DOSISH
2528     if (strEQ(scriptname, "-"))
2529         dosearch = 0;
2530     if (dosearch) {             /* Look in '.' first. */
2531         char *cur = scriptname;
2532 #ifdef SEARCH_EXTS
2533         if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2534             while (ext[i])
2535                 if (strEQ(ext[i++],curext)) {
2536                     extidx = -1;                /* already has an ext */
2537                     break;
2538                 }
2539         do {
2540 #endif
2541             DEBUG_p(PerlIO_printf(Perl_debug_log,
2542                                   "Looking for %s\n",cur));
2543             if (PerlLIO_stat(cur,&statbuf) >= 0) {
2544                 dosearch = 0;
2545                 scriptname = cur;
2546 #ifdef SEARCH_EXTS
2547                 break;
2548 #endif
2549             }
2550 #ifdef SEARCH_EXTS
2551             if (cur == scriptname) {
2552                 len = strlen(scriptname);
2553                 if (len+MAX_EXT_LEN+1 >= sizeof(tokenbuf))
2554                     break;
2555                 cur = strcpy(tokenbuf, scriptname);
2556             }
2557         } while (extidx >= 0 && ext[extidx]     /* try an extension? */
2558                  && strcpy(tokenbuf+len, ext[extidx++]));
2559 #endif
2560     }
2561 #endif
2562
2563     if (dosearch && !strchr(scriptname, '/')
2564 #ifdef DOSISH
2565                  && !strchr(scriptname, '\\')
2566 #endif
2567                  && (s = PerlEnv_getenv("PATH"))) {
2568         bool seen_dot = 0;
2569         
2570         bufend = s + strlen(s);
2571         while (s < bufend) {
2572 #if defined(atarist) || defined(DOSISH)
2573             for (len = 0; *s
2574 #  ifdef atarist
2575                     && *s != ','
2576 #  endif
2577                     && *s != ';'; len++, s++) {
2578                 if (len < sizeof tokenbuf)
2579                     tokenbuf[len] = *s;
2580             }
2581             if (len < sizeof tokenbuf)
2582                 tokenbuf[len] = '\0';
2583 #else  /* ! (atarist || DOSISH) */
2584             s = delimcpy(tokenbuf, tokenbuf + sizeof tokenbuf, s, bufend,
2585                         ':',
2586                         &len);
2587 #endif /* ! (atarist || DOSISH) */
2588             if (s < bufend)
2589                 s++;
2590             if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tokenbuf)
2591                 continue;       /* don't search dir with too-long name */
2592             if (len
2593 #if defined(atarist) || defined(DOSISH)
2594                 && tokenbuf[len - 1] != '/'
2595                 && tokenbuf[len - 1] != '\\'
2596 #endif
2597                )
2598                 tokenbuf[len++] = '/';
2599             if (len == 2 && tokenbuf[0] == '.')
2600                 seen_dot = 1;
2601             (void)strcpy(tokenbuf + len, scriptname);
2602 #endif  /* !VMS */
2603
2604 #ifdef SEARCH_EXTS
2605             len = strlen(tokenbuf);
2606             if (extidx > 0)     /* reset after previous loop */
2607                 extidx = 0;
2608             do {
2609 #endif
2610                 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tokenbuf));
2611                 retval = PerlLIO_stat(tokenbuf,&statbuf);
2612 #ifdef SEARCH_EXTS
2613             } while (  retval < 0               /* not there */
2614                     && extidx>=0 && ext[extidx] /* try an extension? */
2615                     && strcpy(tokenbuf+len, ext[extidx++])
2616                 );
2617 #endif
2618             if (retval < 0)
2619                 continue;
2620             if (S_ISREG(statbuf.st_mode)
2621                 && cando(S_IRUSR,TRUE,&statbuf)
2622 #ifndef DOSISH
2623                 && cando(S_IXUSR,TRUE,&statbuf)
2624 #endif
2625                 )
2626             {
2627                 xfound = tokenbuf;              /* bingo! */
2628                 break;
2629             }
2630             if (!xfailed)
2631                 xfailed = savepv(tokenbuf);
2632         }
2633 #ifndef DOSISH
2634         if (!xfound && !seen_dot && !xfailed && (PerlLIO_stat(scriptname,&statbuf) < 0))
2635 #endif
2636             seen_dot = 1;                       /* Disable message. */
2637         if (!xfound) 
2638             scriptname = NULL;
2639 /*          croak("Can't %s %s%s%s",
2640                   (xfailed ? "execute" : "find"),
2641                   (xfailed ? xfailed : scriptname),
2642                   (xfailed ? "" : " on PATH"),
2643                   (xfailed || seen_dot) ? "" : ", '.' not in PATH"); */
2644         if (xfailed)
2645             Safefree(xfailed);
2646         scriptname = xfound;
2647     }
2648     return scriptname;
2649 }
2650
2651
2652 #ifdef USE_THREADS
2653 #ifdef FAKE_THREADS
2654 /* Very simplistic scheduler for now */
2655 void
2656 schedule(void)
2657 {
2658     thr = thr->i.next_run;
2659 }
2660
2661 void
2662 perl_cond_init(cp)
2663 perl_cond *cp;
2664 {
2665     *cp = 0;
2666 }
2667
2668 void
2669 perl_cond_signal(cp)
2670 perl_cond *cp;
2671 {
2672     perl_os_thread t;
2673     perl_cond cond = *cp;
2674     
2675     if (!cond)
2676         return;
2677     t = cond->thread;
2678     /* Insert t in the runnable queue just ahead of us */
2679     t->i.next_run = thr->i.next_run;
2680     thr->i.next_run->i.prev_run = t;
2681     t->i.prev_run = thr;
2682     thr->i.next_run = t;
2683     thr->i.wait_queue = 0;
2684     /* Remove from the wait queue */
2685     *cp = cond->next;
2686     Safefree(cond);
2687 }
2688
2689 void
2690 perl_cond_broadcast(cp)
2691 perl_cond *cp;
2692 {
2693     perl_os_thread t;
2694     perl_cond cond, cond_next;
2695     
2696     for (cond = *cp; cond; cond = cond_next) {
2697         t = cond->thread;
2698         /* Insert t in the runnable queue just ahead of us */
2699         t->i.next_run = thr->i.next_run;
2700         thr->i.next_run->i.prev_run = t;
2701         t->i.prev_run = thr;
2702         thr->i.next_run = t;
2703         thr->i.wait_queue = 0;
2704         /* Remove from the wait queue */
2705         cond_next = cond->next;
2706         Safefree(cond);
2707     }
2708     *cp = 0;
2709 }
2710
2711 void
2712 perl_cond_wait(cp)
2713 perl_cond *cp;
2714 {
2715     perl_cond cond;
2716
2717     if (thr->i.next_run == thr)
2718         croak("panic: perl_cond_wait called by last runnable thread");
2719     
2720     New(666, cond, 1, struct perl_wait_queue);
2721     cond->thread = thr;
2722     cond->next = *cp;
2723     *cp = cond;
2724     thr->i.wait_queue = cond;
2725     /* Remove ourselves from runnable queue */
2726     thr->i.next_run->i.prev_run = thr->i.prev_run;
2727     thr->i.prev_run->i.next_run = thr->i.next_run;
2728 }
2729 #endif /* FAKE_THREADS */
2730
2731 #ifdef OLD_PTHREADS_API
2732 struct perl_thread *
2733 getTHR _((void))
2734 {
2735     pthread_addr_t t;
2736
2737     if (pthread_getspecific(thr_key, &t))
2738         croak("panic: pthread_getspecific");
2739     return (struct perl_thread *) t;
2740 }
2741 #endif /* OLD_PTHREADS_API */
2742
2743 MAGIC *
2744 condpair_magic(SV *sv)
2745 {
2746     MAGIC *mg;
2747     
2748     SvUPGRADE(sv, SVt_PVMG);
2749     mg = mg_find(sv, 'm');
2750     if (!mg) {
2751         condpair_t *cp;
2752
2753         New(53, cp, 1, condpair_t);
2754         MUTEX_INIT(&cp->mutex);
2755         COND_INIT(&cp->owner_cond);
2756         COND_INIT(&cp->cond);
2757         cp->owner = 0;
2758         LOCK_SV_MUTEX;
2759         mg = mg_find(sv, 'm');
2760         if (mg) {
2761             /* someone else beat us to initialising it */
2762             UNLOCK_SV_MUTEX;
2763             MUTEX_DESTROY(&cp->mutex);
2764             COND_DESTROY(&cp->owner_cond);
2765             COND_DESTROY(&cp->cond);
2766             Safefree(cp);
2767         }
2768         else {
2769             sv_magic(sv, Nullsv, 'm', 0, 0);
2770             mg = SvMAGIC(sv);
2771             mg->mg_ptr = (char *)cp;
2772             mg->mg_len = sizeof(cp);
2773             UNLOCK_SV_MUTEX;
2774             DEBUG_L(WITH_THR(PerlIO_printf(PerlIO_stderr(),
2775                                            "%p: condpair_magic %p\n", thr, sv));)
2776         }
2777     }
2778     return mg;
2779 }
2780
2781 /*
2782  * Make a new perl thread structure using t as a prototype. Some of the
2783  * fields for the new thread are copied from the prototype thread, t,
2784  * so t should not be running in perl at the time this function is
2785  * called. The use by ext/Thread/Thread.xs in core perl (where t is the
2786  * thread calling new_struct_thread) clearly satisfies this constraint.
2787  */
2788 struct perl_thread *
2789 new_struct_thread(struct perl_thread *t)
2790 {
2791     struct perl_thread *thr;
2792     SV *sv;
2793     SV **svp;
2794     I32 i;
2795
2796     sv = newSVpv("", 0);
2797     SvGROW(sv, sizeof(struct perl_thread) + 1);
2798     SvCUR_set(sv, sizeof(struct perl_thread));
2799     thr = (Thread) SvPVX(sv);
2800     /* debug */
2801     memset(thr, 0xab, sizeof(struct perl_thread));
2802     markstack = 0;
2803     scopestack = 0;
2804     savestack = 0;
2805     retstack = 0;
2806     dirty = 0;
2807     localizing = 0;
2808     /* end debug */
2809
2810     thr->oursv = sv;
2811     init_stacks(ARGS);
2812
2813     curcop = &compiling;
2814     thr->cvcache = newHV();
2815     thr->threadsv = newAV();
2816     thr->specific = newAV();
2817     thr->errsv = newSVpv("", 0);
2818     thr->errhv = newHV();
2819     thr->flags = THRf_R_JOINABLE;
2820     MUTEX_INIT(&thr->mutex);
2821
2822     curcop = t->Tcurcop;       /* XXX As good a guess as any? */
2823     defstash = t->Tdefstash;   /* XXX maybe these should */
2824     curstash = t->Tcurstash;   /* always be set to main? */
2825
2826
2827     /* top_env needs to be non-zero. It points to an area
2828        in which longjmp() stuff is stored, as C callstack
2829        info there at least is thread specific this has to
2830        be per-thread. Otherwise a 'die' in a thread gives
2831        that thread the C stack of last thread to do an eval {}!
2832        See comments in scope.h    
2833        Initialize top entry (as in perl.c for main thread)
2834      */
2835     start_env.je_prev = NULL;
2836     start_env.je_ret = -1;
2837     start_env.je_mustcatch = TRUE;
2838     top_env  = &start_env;
2839
2840     in_eval = FALSE;
2841     restartop = 0;
2842
2843     tainted = t->Ttainted;
2844     curpm = t->Tcurpm;         /* XXX No PMOP ref count */
2845     nrs = newSVsv(t->Tnrs);
2846     rs = newSVsv(t->Trs);
2847     last_in_gv = (GV*)SvREFCNT_inc(t->Tlast_in_gv);
2848     ofslen = t->Tofslen;
2849     ofs = savepvn(t->Tofs, ofslen);
2850     defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
2851     chopset = t->Tchopset;
2852     formtarget = newSVsv(t->Tformtarget);
2853     bodytarget = newSVsv(t->Tbodytarget);
2854     toptarget = newSVsv(t->Ttoptarget);
2855     
2856     /* Initialise all per-thread SVs that the template thread used */
2857     svp = AvARRAY(t->threadsv);
2858     for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
2859         if (*svp && *svp != &sv_undef) {
2860             SV *sv = newSVsv(*svp);
2861             av_store(thr->threadsv, i, sv);
2862             sv_magic(sv, 0, 0, &threadsv_names[i], 1);
2863             DEBUG_L(PerlIO_printf(PerlIO_stderr(),
2864                 "new_struct_thread: copied threadsv %d %p->%p\n",i, t, thr));
2865         }
2866     } 
2867     thr->threadsvp = AvARRAY(thr->threadsv);
2868
2869     MUTEX_LOCK(&threads_mutex);
2870     nthreads++;
2871     thr->tid = ++threadnum;
2872     thr->next = t->next;
2873     thr->prev = t;
2874     t->next = thr;
2875     thr->next->prev = thr;
2876     MUTEX_UNLOCK(&threads_mutex);
2877
2878 #ifdef HAVE_THREAD_INTERN
2879     init_thread_intern(thr);
2880 #endif /* HAVE_THREAD_INTERN */
2881     return thr;
2882 }
2883 #endif /* USE_THREADS */
2884
2885 #ifdef HUGE_VAL
2886 /*
2887  * This hack is to force load of "huge" support from libm.a
2888  * So it is in perl for (say) POSIX to use. 
2889  * Needed for SunOS with Sun's 'acc' for example.
2890  */
2891 double 
2892 Perl_huge(void)
2893 {
2894  return HUGE_VAL;
2895 }
2896 #endif
2897
2898 #ifdef PERL_GLOBAL_STRUCT
2899 struct perl_vars *
2900 Perl_GetVars(void)
2901 {
2902  return &Perl_Vars;
2903 }
2904 #endif
2905
2906 char **
2907 get_op_names(void)
2908 {
2909  return op_name;
2910 }
2911
2912 char **
2913 get_op_descs(void)
2914 {
2915  return op_desc;
2916 }