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