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