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