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