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