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