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