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