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