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