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