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