bb82ad035e369da2c16bcfb1c8eb8312b910fb9d
[p5sagit/p5-mst-13.2.git] / util.c
1 /*    util.c
2  *
3  *    Copyright (c) 1991-1997, 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 #include "perl.h"
17
18 #if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
19 #include <signal.h>
20 #endif
21
22 #ifndef SIG_ERR
23 # define SIG_ERR ((Sighandler_t) -1)
24 #endif
25
26 /* XXX If this causes problems, set i_unistd=undef in the hint file.  */
27 #ifdef I_UNISTD
28 #  include <unistd.h>
29 #endif
30
31 #ifdef I_VFORK
32 #  include <vfork.h>
33 #endif
34
35 /* Put this after #includes because fork and vfork prototypes may
36    conflict.
37 */
38 #ifndef HAS_VFORK
39 #   define vfork fork
40 #endif
41
42 #ifdef I_FCNTL
43 #  include <fcntl.h>
44 #endif
45 #ifdef I_SYS_FILE
46 #  include <sys/file.h>
47 #endif
48
49 #ifdef I_SYS_WAIT
50 #  include <sys/wait.h>
51 #endif
52
53 #define FLUSH
54
55 #ifdef LEAKTEST
56 static void xstat _((void));
57 #endif
58
59 #ifndef MYMALLOC
60
61 /* paranoid version of malloc */
62
63 /* NOTE:  Do not call the next three routines directly.  Use the macros
64  * in handy.h, so that we can easily redefine everything to do tracking of
65  * allocated hunks back to the original New to track down any memory leaks.
66  * XXX This advice seems to be widely ignored :-(   --AD  August 1996.
67  */
68
69 Malloc_t
70 safemalloc(MEM_SIZE size)
71 {
72     Malloc_t ptr;
73 #ifdef HAS_64K_LIMIT
74         if (size > 0xffff) {
75                 PerlIO_printf(PerlIO_stderr(), "Allocation too large: %lx\n", size) FLUSH;
76                 my_exit(1);
77         }
78 #endif /* HAS_64K_LIMIT */
79 #ifdef DEBUGGING
80     if ((long)size < 0)
81         croak("panic: malloc");
82 #endif
83     ptr = malloc(size?size:1);  /* malloc(0) is NASTY on our system */
84 #if !(defined(I286) || defined(atarist))
85     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%x: (%05d) malloc %ld bytes\n",ptr,an++,(long)size));
86 #else
87     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) malloc %ld bytes\n",ptr,an++,(long)size));
88 #endif
89     if (ptr != Nullch)
90         return ptr;
91     else if (nomemok)
92         return Nullch;
93     else {
94         PerlIO_puts(PerlIO_stderr(),no_mem) FLUSH;
95         my_exit(1);
96         return Nullch;
97     }
98     /*NOTREACHED*/
99 }
100
101 /* paranoid version of realloc */
102
103 Malloc_t
104 saferealloc(Malloc_t where,MEM_SIZE size)
105 {
106     Malloc_t ptr;
107 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE)
108     Malloc_t realloc();
109 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
110
111 #ifdef HAS_64K_LIMIT 
112     if (size > 0xffff) {
113         PerlIO_printf(PerlIO_stderr(),
114                       "Reallocation too large: %lx\n", size) FLUSH;
115         my_exit(1);
116     }
117 #endif /* HAS_64K_LIMIT */
118     if (!where)
119         croak("Null realloc");
120 #ifdef DEBUGGING
121     if ((long)size < 0)
122         croak("panic: realloc");
123 #endif
124     ptr = realloc(where,size?size:1);   /* realloc(0) is NASTY on our system */
125
126 #if !(defined(I286) || defined(atarist))
127     DEBUG_m( {
128         PerlIO_printf(Perl_debug_log, "0x%x: (%05d) rfree\n",where,an++);
129         PerlIO_printf(Perl_debug_log, "0x%x: (%05d) realloc %ld bytes\n",ptr,an++,(long)size);
130     } )
131 #else
132     DEBUG_m( {
133         PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) rfree\n",where,an++);
134         PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) realloc %ld bytes\n",ptr,an++,(long)size);
135     } )
136 #endif
137
138     if (ptr != Nullch)
139         return ptr;
140     else if (nomemok)
141         return Nullch;
142     else {
143         PerlIO_puts(PerlIO_stderr(),no_mem) FLUSH;
144         my_exit(1);
145         return Nullch;
146     }
147     /*NOTREACHED*/
148 }
149
150 /* safe version of free */
151
152 Free_t
153 safefree(Malloc_t where)
154 {
155 #if !(defined(I286) || defined(atarist))
156     DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%x: (%05d) free\n",(char *) where,an++));
157 #else
158     DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) free\n",(char *) where,an++));
159 #endif
160     if (where) {
161         /*SUPPRESS 701*/
162         free(where);
163     }
164 }
165
166 /* safe version of calloc */
167
168 Malloc_t
169 safecalloc(MEM_SIZE count, MEM_SIZE size)
170 {
171     Malloc_t ptr;
172
173 #ifdef HAS_64K_LIMIT
174     if (size * count > 0xffff) {
175         PerlIO_printf(PerlIO_stderr(),
176                       "Allocation too large: %lx\n", size * count) FLUSH;
177         my_exit(1);
178     }
179 #endif /* HAS_64K_LIMIT */
180 #ifdef DEBUGGING
181     if ((long)size < 0 || (long)count < 0)
182         croak("panic: calloc");
183 #endif
184     size *= count;
185     ptr = malloc(size?size:1);  /* malloc(0) is NASTY on our system */
186 #if !(defined(I286) || defined(atarist))
187     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%x: (%05d) calloc %ld  x %ld bytes\n",ptr,an++,(long)count,(long)size));
188 #else
189     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) calloc %ld x %ld bytes\n",ptr,an++,(long)count,(long)size));
190 #endif
191     if (ptr != Nullch) {
192         memset((void*)ptr, 0, size);
193         return ptr;
194     }
195     else if (nomemok)
196         return Nullch;
197     else {
198         PerlIO_puts(PerlIO_stderr(),no_mem) FLUSH;
199         my_exit(1);
200         return Nullch;
201     }
202     /*NOTREACHED*/
203 }
204
205 #endif /* !MYMALLOC */
206
207 #ifdef LEAKTEST
208
209 #define ALIGN sizeof(long)
210
211 Malloc_t
212 safexmalloc(I32 x, MEM_SIZE size)
213 {
214     register Malloc_t where;
215
216     where = safemalloc(size + ALIGN);
217     xcount[x]++;
218     where[0] = x % 100;
219     where[1] = x / 100;
220     return where + ALIGN;
221 }
222
223 Malloc_t
224 safexrealloc(Malloc_t where, MEM_SIZE size)
225 {
226     register Malloc_t new = saferealloc(where - ALIGN, size + ALIGN);
227     return new + ALIGN;
228 }
229
230 void
231 safexfree(Malloc_t where)
232 {
233     I32 x;
234
235     if (!where)
236         return;
237     where -= ALIGN;
238     x = where[0] + 100 * where[1];
239     xcount[x]--;
240     safefree(where);
241 }
242
243 Malloc_t
244 safexcalloc(I32 x,MEM_SIZE count, MEM_SIZE size)
245 {
246     register Malloc_t where;
247
248     where = safexmalloc(x, size * count + ALIGN);
249     xcount[x]++;
250     memset((void*)where + ALIGN, 0, size * count);
251     where[0] = x % 100;
252     where[1] = x / 100;
253     return where + ALIGN;
254 }
255
256 static void
257 xstat(void)
258 {
259     register I32 i;
260
261     for (i = 0; i < MAXXCOUNT; i++) {
262         if (xcount[i] > lastxcount[i]) {
263             PerlIO_printf(PerlIO_stderr(),"%2d %2d\t%ld\n", i / 100, i % 100, xcount[i]);
264             lastxcount[i] = xcount[i];
265         }
266     }
267 }
268
269 #endif /* LEAKTEST */
270
271 /* copy a string up to some (non-backslashed) delimiter, if any */
272
273 char *
274 delimcpy(register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
275 {
276     register I32 tolen;
277     for (tolen = 0; from < fromend; from++, tolen++) {
278         if (*from == '\\') {
279             if (from[1] == delim)
280                 from++;
281             else {
282                 if (to < toend)
283                     *to++ = *from;
284                 tolen++;
285                 from++;
286             }
287         }
288         else if (*from == delim)
289             break;
290         if (to < toend)
291             *to++ = *from;
292     }
293     if (to < toend)
294         *to = '\0';
295     *retlen = tolen;
296     return from;
297 }
298
299 /* return ptr to little string in big string, NULL if not found */
300 /* This routine was donated by Corey Satten. */
301
302 char *
303 instr(register char *big, register char *little)
304 {
305     register char *s, *x;
306     register I32 first;
307
308     if (!little)
309         return big;
310     first = *little++;
311     if (!first)
312         return big;
313     while (*big) {
314         if (*big++ != first)
315             continue;
316         for (x=big,s=little; *s; /**/ ) {
317             if (!*x)
318                 return Nullch;
319             if (*s++ != *x++) {
320                 s--;
321                 break;
322             }
323         }
324         if (!*s)
325             return big-1;
326     }
327     return Nullch;
328 }
329
330 /* same as instr but allow embedded nulls */
331
332 char *
333 ninstr(register char *big, register char *bigend, char *little, char *lend)
334 {
335     register char *s, *x;
336     register I32 first = *little;
337     register char *littleend = lend;
338
339     if (!first && little >= littleend)
340         return big;
341     if (bigend - big < littleend - little)
342         return Nullch;
343     bigend -= littleend - little++;
344     while (big <= bigend) {
345         if (*big++ != first)
346             continue;
347         for (x=big,s=little; s < littleend; /**/ ) {
348             if (*s++ != *x++) {
349                 s--;
350                 break;
351             }
352         }
353         if (s >= littleend)
354             return big-1;
355     }
356     return Nullch;
357 }
358
359 /* reverse of the above--find last substring */
360
361 char *
362 rninstr(register char *big, char *bigend, char *little, char *lend)
363 {
364     register char *bigbeg;
365     register char *s, *x;
366     register I32 first = *little;
367     register char *littleend = lend;
368
369     if (!first && little >= littleend)
370         return bigend;
371     bigbeg = big;
372     big = bigend - (littleend - little++);
373     while (big >= bigbeg) {
374         if (*big-- != first)
375             continue;
376         for (x=big+2,s=little; s < littleend; /**/ ) {
377             if (*s++ != *x++) {
378                 s--;
379                 break;
380             }
381         }
382         if (s >= littleend)
383             return big+1;
384     }
385     return Nullch;
386 }
387
388 /*
389  * Set up for a new ctype locale.
390  */
391 void
392 perl_new_ctype(char *newctype)
393 {
394 #ifdef USE_LOCALE_CTYPE
395
396     int i;
397
398     for (i = 0; i < 256; i++) {
399         if (isUPPER_LC(i))
400             fold_locale[i] = toLOWER_LC(i);
401         else if (isLOWER_LC(i))
402             fold_locale[i] = toUPPER_LC(i);
403         else
404             fold_locale[i] = i;
405     }
406
407 #endif /* USE_LOCALE_CTYPE */
408 }
409
410 /*
411  * Set up for a new collation locale.
412  */
413 void
414 perl_new_collate(char *newcoll)
415 {
416 #ifdef USE_LOCALE_COLLATE
417
418     if (! newcoll) {
419         if (collation_name) {
420             ++collation_ix;
421             Safefree(collation_name);
422             collation_name = NULL;
423             collation_standard = TRUE;
424             collxfrm_base = 0;
425             collxfrm_mult = 2;
426         }
427         return;
428     }
429
430     if (! collation_name || strNE(collation_name, newcoll)) {
431         ++collation_ix;
432         Safefree(collation_name);
433         collation_name = savepv(newcoll);
434         collation_standard = (strEQ(newcoll, "C") || strEQ(newcoll, "POSIX"));
435
436         {
437           /*  2: at most so many chars ('a', 'b'). */
438           /* 50: surely no system expands a char more. */
439 #define XFRMBUFSIZE  (2 * 50)
440           char xbuf[XFRMBUFSIZE];
441           Size_t fa = strxfrm(xbuf, "a",  XFRMBUFSIZE);
442           Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
443           SSize_t mult = fb - fa;
444           if (mult < 1)
445               croak("strxfrm() gets absurd");
446           collxfrm_base = (fa > mult) ? (fa - mult) : 0;
447           collxfrm_mult = mult;
448         }
449     }
450
451 #endif /* USE_LOCALE_COLLATE */
452 }
453
454 /*
455  * Set up for a new numeric locale.
456  */
457 void
458 perl_new_numeric(char *newnum)
459 {
460 #ifdef USE_LOCALE_NUMERIC
461
462     if (! newnum) {
463         if (numeric_name) {
464             Safefree(numeric_name);
465             numeric_name = NULL;
466             numeric_standard = TRUE;
467             numeric_local = TRUE;
468         }
469         return;
470     }
471
472     if (! numeric_name || strNE(numeric_name, newnum)) {
473         Safefree(numeric_name);
474         numeric_name = savepv(newnum);
475         numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
476         numeric_local = TRUE;
477     }
478
479 #endif /* USE_LOCALE_NUMERIC */
480 }
481
482 void
483 perl_set_numeric_standard(void)
484 {
485 #ifdef USE_LOCALE_NUMERIC
486
487     if (! numeric_standard) {
488         setlocale(LC_NUMERIC, "C");
489         numeric_standard = TRUE;
490         numeric_local = FALSE;
491     }
492
493 #endif /* USE_LOCALE_NUMERIC */
494 }
495
496 void
497 perl_set_numeric_local(void)
498 {
499 #ifdef USE_LOCALE_NUMERIC
500
501     if (! numeric_local) {
502         setlocale(LC_NUMERIC, numeric_name);
503         numeric_standard = FALSE;
504         numeric_local = TRUE;
505     }
506
507 #endif /* USE_LOCALE_NUMERIC */
508 }
509
510
511 /*
512  * Initialize locale awareness.
513  */
514 int
515 perl_init_i18nl10n(int printwarn)
516 {
517     int ok = 1;
518     /* returns
519      *    1 = set ok or not applicable,
520      *    0 = fallback to C locale,
521      *   -1 = fallback to C locale failed
522      */
523
524 #ifdef USE_LOCALE
525
526 #ifdef USE_LOCALE_CTYPE
527     char *curctype   = NULL;
528 #endif /* USE_LOCALE_CTYPE */
529 #ifdef USE_LOCALE_COLLATE
530     char *curcoll    = NULL;
531 #endif /* USE_LOCALE_COLLATE */
532 #ifdef USE_LOCALE_NUMERIC
533     char *curnum     = NULL;
534 #endif /* USE_LOCALE_NUMERIC */
535     char *lc_all     = getenv("LC_ALL");
536     char *lang       = getenv("LANG");
537     bool setlocale_failure = FALSE;
538
539 #ifdef LOCALE_ENVIRON_REQUIRED
540
541     /*
542      * Ultrix setlocale(..., "") fails if there are no environment
543      * variables from which to get a locale name.
544      */
545
546     bool done = FALSE;
547
548 #ifdef LC_ALL
549     if (lang) {
550         if (setlocale(LC_ALL, ""))
551             done = TRUE;
552         else
553             setlocale_failure = TRUE;
554     }
555     if (!setlocale_failure)
556 #endif /* LC_ALL */
557     {
558 #ifdef USE_LOCALE_CTYPE
559         if (! (curctype = setlocale(LC_CTYPE,
560                                     (!done && (lang || getenv("LC_CTYPE")))
561                                     ? "" : Nullch)))
562             setlocale_failure = TRUE;
563 #endif /* USE_LOCALE_CTYPE */
564 #ifdef USE_LOCALE_COLLATE
565         if (! (curcoll = setlocale(LC_COLLATE,
566                                    (!done && (lang || getenv("LC_COLLATE")))
567                                    ? "" : Nullch)))
568             setlocale_failure = TRUE;
569 #endif /* USE_LOCALE_COLLATE */
570 #ifdef USE_LOCALE_NUMERIC
571         if (! (curnum = setlocale(LC_NUMERIC,
572                                   (!done && (lang || getenv("LC_NUMERIC")))
573                                   ? "" : Nullch)))
574             setlocale_failure = TRUE;
575 #endif /* USE_LOCALE_NUMERIC */
576     }
577
578 #else /* !LOCALE_ENVIRON_REQUIRED */
579
580 #ifdef LC_ALL
581
582     if (! setlocale(LC_ALL, ""))
583         setlocale_failure = TRUE;
584     else {
585 #ifdef USE_LOCALE_CTYPE
586         curctype = setlocale(LC_CTYPE, Nullch);
587 #endif /* USE_LOCALE_CTYPE */
588 #ifdef USE_LOCALE_COLLATE
589         curcoll = setlocale(LC_COLLATE, Nullch);
590 #endif /* USE_LOCALE_COLLATE */
591 #ifdef USE_LOCALE_NUMERIC
592         curnum = setlocale(LC_NUMERIC, Nullch);
593 #endif /* USE_LOCALE_NUMERIC */
594     }
595
596 #else /* !LC_ALL */
597
598 #ifdef USE_LOCALE_CTYPE
599     if (! (curctype = setlocale(LC_CTYPE, "")))
600         setlocale_failure = TRUE;
601 #endif /* USE_LOCALE_CTYPE */
602 #ifdef USE_LOCALE_COLLATE
603     if (! (curcoll = setlocale(LC_COLLATE, "")))
604         setlocale_failure = TRUE;
605 #endif /* USE_LOCALE_COLLATE */
606 #ifdef USE_LOCALE_NUMERIC
607     if (! (curnum = setlocale(LC_NUMERIC, "")))
608         setlocale_failure = TRUE;
609 #endif /* USE_LOCALE_NUMERIC */
610
611 #endif /* LC_ALL */
612
613 #endif /* !LOCALE_ENVIRON_REQUIRED */
614
615     if (setlocale_failure) {
616         char *p;
617         bool locwarn = (printwarn > 1 || 
618                         printwarn &&
619                         (!(p = getenv("PERL_BADLANG")) || atoi(p)));
620
621         if (locwarn) {
622 #ifdef LC_ALL
623   
624             PerlIO_printf(PerlIO_stderr(),
625                "perl: warning: Setting locale failed.\n");
626
627 #else /* !LC_ALL */
628   
629             PerlIO_printf(PerlIO_stderr(),
630                "perl: warning: Setting locale failed for the categories:\n\t");
631 #ifdef USE_LOCALE_CTYPE
632             if (! curctype)
633                 PerlIO_printf(PerlIO_stderr(), "LC_CTYPE ");
634 #endif /* USE_LOCALE_CTYPE */
635 #ifdef USE_LOCALE_COLLATE
636             if (! curcoll)
637                 PerlIO_printf(PerlIO_stderr(), "LC_COLLATE ");
638 #endif /* USE_LOCALE_COLLATE */
639 #ifdef USE_LOCALE_NUMERIC
640             if (! curnum)
641                 PerlIO_printf(PerlIO_stderr(), "LC_NUMERIC ");
642 #endif /* USE_LOCALE_NUMERIC */
643             PerlIO_printf(PerlIO_stderr(), "\n");
644
645 #endif /* LC_ALL */
646
647             PerlIO_printf(PerlIO_stderr(),
648                 "perl: warning: Please check that your locale settings:\n");
649
650             PerlIO_printf(PerlIO_stderr(),
651                           "\tLC_ALL = %c%s%c,\n",
652                           lc_all ? '"' : '(',
653                           lc_all ? lc_all : "unset",
654                           lc_all ? '"' : ')');
655
656             {
657               char **e;
658               for (e = environ; *e; e++) {
659                   if (strnEQ(*e, "LC_", 3)
660                         && strnNE(*e, "LC_ALL=", 7)
661                         && (p = strchr(*e, '=')))
662                       PerlIO_printf(PerlIO_stderr(), "\t%.*s = \"%s\",\n",
663                                     (int)(p - *e), *e, p + 1);
664               }
665             }
666
667             PerlIO_printf(PerlIO_stderr(),
668                           "\tLANG = %c%s%c\n",
669                           lang ? '"' : '(',
670                           lang ? lang : "unset",
671                           lang ? '"' : ')');
672
673             PerlIO_printf(PerlIO_stderr(),
674                           "    are supported and installed on your system.\n");
675         }
676
677 #ifdef LC_ALL
678
679         if (setlocale(LC_ALL, "C")) {
680             if (locwarn)
681                 PerlIO_printf(PerlIO_stderr(),
682       "perl: warning: Falling back to the standard locale (\"C\").\n");
683             ok = 0;
684         }
685         else {
686             if (locwarn)
687                 PerlIO_printf(PerlIO_stderr(),
688       "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
689             ok = -1;
690         }
691
692 #else /* ! LC_ALL */
693
694         if (0
695 #ifdef USE_LOCALE_CTYPE
696             || !(curctype || setlocale(LC_CTYPE, "C"))
697 #endif /* USE_LOCALE_CTYPE */
698 #ifdef USE_LOCALE_COLLATE
699             || !(curcoll || setlocale(LC_COLLATE, "C"))
700 #endif /* USE_LOCALE_COLLATE */
701 #ifdef USE_LOCALE_NUMERIC
702             || !(curnum || setlocale(LC_NUMERIC, "C"))
703 #endif /* USE_LOCALE_NUMERIC */
704             )
705         {
706             if (locwarn)
707                 PerlIO_printf(PerlIO_stderr(),
708       "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
709             ok = -1;
710         }
711
712 #endif /* ! LC_ALL */
713
714 #ifdef USE_LOCALE_CTYPE
715         curctype = setlocale(LC_CTYPE, Nullch);
716 #endif /* USE_LOCALE_CTYPE */
717 #ifdef USE_LOCALE_COLLATE
718         curcoll = setlocale(LC_COLLATE, Nullch);
719 #endif /* USE_LOCALE_COLLATE */
720 #ifdef USE_LOCALE_NUMERIC
721         curnum = setlocale(LC_NUMERIC, Nullch);
722 #endif /* USE_LOCALE_NUMERIC */
723     }
724
725 #ifdef USE_LOCALE_CTYPE
726     perl_new_ctype(curctype);
727 #endif /* USE_LOCALE_CTYPE */
728
729 #ifdef USE_LOCALE_COLLATE
730     perl_new_collate(curcoll);
731 #endif /* USE_LOCALE_COLLATE */
732
733 #ifdef USE_LOCALE_NUMERIC
734     perl_new_numeric(curnum);
735 #endif /* USE_LOCALE_NUMERIC */
736
737 #endif /* USE_LOCALE */
738
739     return ok;
740 }
741
742 /* Backwards compatibility. */
743 int
744 perl_init_i18nl14n(int printwarn)
745 {
746     return perl_init_i18nl10n(printwarn);
747 }
748
749 #ifdef USE_LOCALE_COLLATE
750
751 /*
752  * mem_collxfrm() is a bit like strxfrm() but with two important
753  * differences. First, it handles embedded NULs. Second, it allocates
754  * a bit more memory than needed for the transformed data itself.
755  * The real transformed data begins at offset sizeof(collationix).
756  * Please see sv_collxfrm() to see how this is used.
757  */
758 char *
759 mem_collxfrm(const char *s, STRLEN len, STRLEN *xlen)
760 {
761     char *xbuf;
762     STRLEN xalloc, xin, xout;
763
764     /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
765     /* the +1 is for the terminating NUL. */
766
767     xalloc = sizeof(collation_ix) + collxfrm_base + (collxfrm_mult * len) + 1;
768     New(171, xbuf, xalloc, char);
769     if (! xbuf)
770         goto bad;
771
772     *(U32*)xbuf = collation_ix;
773     xout = sizeof(collation_ix);
774     for (xin = 0; xin < len; ) {
775         SSize_t xused;
776
777         for (;;) {
778             xused = strxfrm(xbuf + xout, s + xin, xalloc - xout);
779             if (xused == -1)
780                 goto bad;
781             if (xused < xalloc - xout)
782                 break;
783             xalloc = (2 * xalloc) + 1;
784             Renew(xbuf, xalloc, char);
785             if (! xbuf)
786                 goto bad;
787         }
788
789         xin += strlen(s + xin) + 1;
790         xout += xused;
791
792         /* Embedded NULs are understood but silently skipped
793          * because they make no sense in locale collation. */
794     }
795
796     xbuf[xout] = '\0';
797     *xlen = xout - sizeof(collation_ix);
798     return xbuf;
799
800   bad:
801     Safefree(xbuf);
802     *xlen = 0;
803     return NULL;
804 }
805
806 #endif /* USE_LOCALE_COLLATE */
807
808 void
809 fbm_compile(SV *sv)
810 {
811     register unsigned char *s;
812     register unsigned char *table;
813     register U32 i;
814     register U32 len = SvCUR(sv);
815     I32 rarest = 0;
816     U32 frequency = 256;
817
818     sv_upgrade(sv, SVt_PVBM);
819     if (len > 255 || len == 0)  /* TAIL might be on on a zero-length string. */
820         return;                 /* can't have offsets that big */
821     if (len > 2) {
822         Sv_Grow(sv,len + 258);
823         table = (unsigned char*)(SvPVX(sv) + len + 1);
824         s = table - 2;
825         for (i = 0; i < 256; i++) {
826             table[i] = len;
827         }
828         i = 0;
829         while (s >= (unsigned char*)(SvPVX(sv)))
830             {
831                 if (table[*s] == len)
832                     table[*s] = i;
833                 s--,i++;
834             }
835     }
836     sv_magic(sv, Nullsv, 'B', Nullch, 0);       /* deep magic */
837     SvVALID_on(sv);
838
839     s = (unsigned char*)(SvPVX(sv));            /* deeper magic */
840     for (i = 0; i < len; i++) {
841         if (freq[s[i]] < frequency) {
842             rarest = i;
843             frequency = freq[s[i]];
844         }
845     }
846     BmRARE(sv) = s[rarest];
847     BmPREVIOUS(sv) = rarest;
848     DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",BmRARE(sv),BmPREVIOUS(sv)));
849 }
850
851 char *
852 fbm_instr(unsigned char *big, register unsigned char *bigend, SV *littlestr)
853 {
854     register unsigned char *s;
855     register I32 tmp;
856     register I32 littlelen;
857     register unsigned char *little;
858     register unsigned char *table;
859     register unsigned char *olds;
860     register unsigned char *oldlittle;
861
862     if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
863         STRLEN len;
864         char *l = SvPV(littlestr,len);
865         if (!len) {
866             if (SvTAIL(littlestr)) {    /* Can be only 0-len constant
867                                            substr => we can ignore SvVALID */
868                 if (multiline) {
869                     char *t = "\n";
870                     if ((s = (unsigned char*)ninstr((char*)big, (char*)bigend,
871                                                     t, t + len))) {
872                         return (char*)s;
873                     }
874                 }
875                 if (bigend > big && bigend[-1] == '\n')
876                     return (char *)(bigend - 1);
877                 else
878                     return (char *) bigend;
879             }
880             return (char*)big;
881         }
882         return ninstr((char*)big,(char*)bigend, l, l + len);
883     }
884
885     littlelen = SvCUR(littlestr);
886     if (SvTAIL(littlestr) && !multiline) {      /* tail anchored? */
887         if (littlelen > bigend - big)
888             return Nullch;
889         little = (unsigned char*)SvPVX(littlestr);
890         s = bigend - littlelen;
891         if (s > big
892             && bigend[-1] == '\n' 
893             && s[-1] == *little && memEQ((char*)s - 1,(char*)little,littlelen))
894             return (char*)s - 1;        /* how sweet it is */
895         else if (*s == *little && memEQ((char*)s,(char*)little,littlelen))
896             return (char*)s;            /* how sweet it is */
897         return Nullch;
898     }
899     if (littlelen <= 2) {
900         unsigned char c1 = (unsigned char)SvPVX(littlestr)[0];
901         unsigned char c2 = (unsigned char)SvPVX(littlestr)[1];
902         /* This may do extra comparisons if littlelen == 2, but this
903            should be hidden in the noise since we do less indirection. */
904         
905         s = big;
906         bigend -= littlelen;
907         while (s <= bigend) {
908             if (s[0] == c1 
909                 && (littlelen == 1 || s[1] == c2)
910                 && (!SvTAIL(littlestr)
911                     || s == bigend
912                     || s[littlelen] == '\n')) /* Automatically multiline */
913             {
914                 return (char*)s;
915             }
916             s++;
917         }
918         return Nullch;
919     }
920     table = (unsigned char*)(SvPVX(littlestr) + littlelen + 1);
921     if (--littlelen >= bigend - big)
922         return Nullch;
923     s = big + littlelen;
924     oldlittle = little = table - 2;
925     if (s < bigend) {
926       top2:
927         /*SUPPRESS 560*/
928         if (tmp = table[*s]) {
929 #ifdef POINTERRIGOR
930             if (bigend - s > tmp) {
931                 s += tmp;
932                 goto top2;
933             }
934 #else
935             if ((s += tmp) < bigend)
936                 goto top2;
937 #endif
938             return Nullch;
939         }
940         else {
941             tmp = littlelen;    /* less expensive than calling strncmp() */
942             olds = s;
943             while (tmp--) {
944                 if (*--s == *--little)
945                     continue;
946               differ:
947                 s = olds + 1;   /* here we pay the price for failure */
948                 little = oldlittle;
949                 if (s < bigend) /* fake up continue to outer loop */
950                     goto top2;
951                 return Nullch;
952             }
953             if (SvTAIL(littlestr)       /* automatically multiline */
954                 && olds + 1 != bigend
955                 && olds[1] != '\n') 
956                 goto differ;
957             return (char *)s;
958         }
959     }
960     return Nullch;
961 }
962
963 /* start_shift, end_shift are positive quantities which give offsets
964    of ends of some substring of bigstr.
965    If `last' we want the last occurence.
966    old_posp is the way of communication between consequent calls if
967    the next call needs to find the . 
968    The initial *old_posp should be -1.
969    Note that we do not take into account SvTAIL, so it may give wrong
970    positives if _ALL flag is set.
971  */
972
973 char *
974 screaminstr(SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
975 {
976     register unsigned char *s, *x;
977     register unsigned char *big;
978     register I32 pos;
979     register I32 previous;
980     register I32 first;
981     register unsigned char *little;
982     register I32 stop_pos;
983     register unsigned char *littleend;
984     I32 found = 0;
985
986     if (*old_posp == -1
987         ? (pos = screamfirst[BmRARE(littlestr)]) < 0
988         : (((pos = *old_posp), pos += screamnext[pos]) == 0))
989         return Nullch;
990     little = (unsigned char *)(SvPVX(littlestr));
991     littleend = little + SvCUR(littlestr);
992     first = *little++;
993     /* The value of pos we can start at: */
994     previous = BmPREVIOUS(littlestr);
995     big = (unsigned char *)(SvPVX(bigstr));
996     /* The value of pos we can stop at: */
997     stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
998     if (previous + start_shift > stop_pos) return Nullch;
999     while (pos < previous + start_shift) {
1000         if (!(pos += screamnext[pos]))
1001             return Nullch;
1002     }
1003 #ifdef POINTERRIGOR
1004     do {
1005         if (pos >= stop_pos) return Nullch;
1006         if (big[pos-previous] != first)
1007             continue;
1008         for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
1009             if (*s++ != *x++) {
1010                 s--;
1011                 break;
1012             }
1013         }
1014         if (s == littleend) {
1015             *old_posp = pos;
1016             if (!last) return (char *)(big+pos-previous);
1017             found = 1;
1018         }
1019     } while ( pos += screamnext[pos] );
1020     return (last && found) ? (char *)(big+(*old_posp)-previous) : Nullch;
1021 #else /* !POINTERRIGOR */
1022     big -= previous;
1023     do {
1024         if (pos >= stop_pos) return Nullch;
1025         if (big[pos] != first)
1026             continue;
1027         for (x=big+pos+1,s=little; s < littleend; /**/ ) {
1028             if (*s++ != *x++) {
1029                 s--;
1030                 break;
1031             }
1032         }
1033         if (s == littleend) {
1034             *old_posp = pos;
1035             if (!last) return (char *)(big+pos);
1036             found = 1;
1037         }
1038     } while ( pos += screamnext[pos] );
1039     return (last && found) ? (char *)(big+(*old_posp)) : Nullch;
1040 #endif /* POINTERRIGOR */
1041 }
1042
1043 I32
1044 ibcmp(char *s1, char *s2, register I32 len)
1045 {
1046     register U8 *a = (U8 *)s1;
1047     register U8 *b = (U8 *)s2;
1048     while (len--) {
1049         if (*a != *b && *a != fold[*b])
1050             return 1;
1051         a++,b++;
1052     }
1053     return 0;
1054 }
1055
1056 I32
1057 ibcmp_locale(char *s1, char *s2, register I32 len)
1058 {
1059     register U8 *a = (U8 *)s1;
1060     register U8 *b = (U8 *)s2;
1061     while (len--) {
1062         if (*a != *b && *a != fold_locale[*b])
1063             return 1;
1064         a++,b++;
1065     }
1066     return 0;
1067 }
1068
1069 /* copy a string to a safe spot */
1070
1071 char *
1072 savepv(char *sv)
1073 {
1074     register char *newaddr;
1075
1076     New(902,newaddr,strlen(sv)+1,char);
1077     (void)strcpy(newaddr,sv);
1078     return newaddr;
1079 }
1080
1081 /* same thing but with a known length */
1082
1083 char *
1084 savepvn(char *sv, register I32 len)
1085 {
1086     register char *newaddr;
1087
1088     New(903,newaddr,len+1,char);
1089     Copy(sv,newaddr,len,char);          /* might not be null terminated */
1090     newaddr[len] = '\0';                /* is now */
1091     return newaddr;
1092 }
1093
1094 /* the SV for form() and mess() is not kept in an arena */
1095
1096 static SV *
1097 mess_alloc(void)
1098 {
1099     SV *sv;
1100     XPVMG *any;
1101
1102     /* Create as PVMG now, to avoid any upgrading later */
1103     New(905, sv, 1, SV);
1104     Newz(905, any, 1, XPVMG);
1105     SvFLAGS(sv) = SVt_PVMG;
1106     SvANY(sv) = (void*)any;
1107     SvREFCNT(sv) = 1 << 30; /* practically infinite */
1108     return sv;
1109 }
1110
1111 #ifdef I_STDARG
1112 char *
1113 form(const char* pat, ...)
1114 #else
1115 /*VARARGS0*/
1116 char *
1117 form(pat, va_alist)
1118     const char *pat;
1119     va_dcl
1120 #endif
1121 {
1122     va_list args;
1123 #ifdef I_STDARG
1124     va_start(args, pat);
1125 #else
1126     va_start(args);
1127 #endif
1128     if (!mess_sv)
1129         mess_sv = mess_alloc();
1130     sv_vsetpvfn(mess_sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*));
1131     va_end(args);
1132     return SvPVX(mess_sv);
1133 }
1134
1135 char *
1136 mess(const char *pat, va_list *args)
1137 {
1138     SV *sv;
1139     static char dgd[] = " during global destruction.\n";
1140
1141     if (!mess_sv)
1142         mess_sv = mess_alloc();
1143     sv = mess_sv;
1144     sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1145     if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1146         dTHR;
1147         if (dirty)
1148             sv_catpv(sv, dgd);
1149         else {
1150             if (curcop->cop_line)
1151                 sv_catpvf(sv, " at %_ line %ld",
1152                           GvSV(curcop->cop_filegv), (long)curcop->cop_line);
1153             if (GvIO(last_in_gv) && IoLINES(GvIOp(last_in_gv))) {
1154                 bool line_mode = (RsSIMPLE(rs) &&
1155                                   SvLEN(rs) == 1 && *SvPVX(rs) == '\n');
1156                 sv_catpvf(sv, ", <%s> %s %ld",
1157                           last_in_gv == argvgv ? "" : GvNAME(last_in_gv),
1158                           line_mode ? "line" : "chunk", 
1159                           (long)IoLINES(GvIOp(last_in_gv)));
1160             }
1161             sv_catpv(sv, ".\n");
1162         }
1163     }
1164     return SvPVX(sv);
1165 }
1166
1167 #ifdef I_STDARG
1168 OP *
1169 die(const char* pat, ...)
1170 #else
1171 /*VARARGS0*/
1172 OP *
1173 die(pat, va_alist)
1174     const char *pat;
1175     va_dcl
1176 #endif
1177 {
1178     dTHR;
1179     va_list args;
1180     char *message;
1181     int was_in_eval = in_eval;
1182     HV *stash;
1183     GV *gv;
1184     CV *cv;
1185
1186 #ifdef USE_THREADS
1187     DEBUG_L(PerlIO_printf(PerlIO_stderr(),
1188                           "%p: die: curstack = %p, mainstack = %p\n",
1189                           thr, curstack, mainstack));
1190 #endif /* USE_THREADS */
1191     /* We have to switch back to mainstack or die_where may try to pop
1192      * the eval block from the wrong stack if die is being called from a
1193      * signal handler.  - dkindred@cs.cmu.edu */
1194     if (curstack != mainstack) {
1195         dSP;
1196         SWITCHSTACK(curstack, mainstack);
1197     }
1198
1199 #ifdef I_STDARG
1200     va_start(args, pat);
1201 #else
1202     va_start(args);
1203 #endif
1204     message = mess(pat, &args);
1205     va_end(args);
1206
1207 #ifdef USE_THREADS
1208     DEBUG_L(PerlIO_printf(PerlIO_stderr(),
1209                           "%p: die: message = %s\ndiehook = %p\n",
1210                           thr, message, diehook));
1211 #endif /* USE_THREADS */
1212     if (diehook) {
1213         /* sv_2cv might call croak() */
1214         SV *olddiehook = diehook;
1215         ENTER;
1216         SAVESPTR(diehook);
1217         diehook = Nullsv;
1218         cv = sv_2cv(olddiehook, &stash, &gv, 0);
1219         LEAVE;
1220         if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1221             dSP;
1222             SV *msg;
1223
1224             ENTER;
1225             msg = newSVpv(message, 0);
1226             SvREADONLY_on(msg);
1227             SAVEFREESV(msg);
1228
1229             PUSHMARK(sp);
1230             XPUSHs(msg);
1231             PUTBACK;
1232             perl_call_sv((SV*)cv, G_DISCARD);
1233
1234             LEAVE;
1235         }
1236     }
1237
1238     restartop = die_where(message);
1239 #ifdef USE_THREADS
1240     DEBUG_L(PerlIO_printf(PerlIO_stderr(),
1241           "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1242           thr, restartop, was_in_eval, top_env));
1243 #endif /* USE_THREADS */
1244     if ((!restartop && was_in_eval) || top_env->je_prev)
1245         JMPENV_JUMP(3);
1246     return restartop;
1247 }
1248
1249 #ifdef I_STDARG
1250 void
1251 croak(const char* pat, ...)
1252 #else
1253 /*VARARGS0*/
1254 void
1255 croak(pat, va_alist)
1256     char *pat;
1257     va_dcl
1258 #endif
1259 {
1260     dTHR;
1261     va_list args;
1262     char *message;
1263     HV *stash;
1264     GV *gv;
1265     CV *cv;
1266
1267 #ifdef I_STDARG
1268     va_start(args, pat);
1269 #else
1270     va_start(args);
1271 #endif
1272     message = mess(pat, &args);
1273     va_end(args);
1274 #ifdef USE_THREADS
1275     DEBUG_L(PerlIO_printf(PerlIO_stderr(), "croak: 0x%lx %s", (unsigned long) thr, message));
1276 #endif /* USE_THREADS */
1277     if (diehook) {
1278         /* sv_2cv might call croak() */
1279         SV *olddiehook = diehook;
1280         ENTER;
1281         SAVESPTR(diehook);
1282         diehook = Nullsv;
1283         cv = sv_2cv(olddiehook, &stash, &gv, 0);
1284         LEAVE;
1285         if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1286             dSP;
1287             SV *msg;
1288
1289             ENTER;
1290             msg = newSVpv(message, 0);
1291             SvREADONLY_on(msg);
1292             SAVEFREESV(msg);
1293
1294             PUSHMARK(sp);
1295             XPUSHs(msg);
1296             PUTBACK;
1297             perl_call_sv((SV*)cv, G_DISCARD);
1298
1299             LEAVE;
1300         }
1301     }
1302     if (in_eval) {
1303         restartop = die_where(message);
1304         JMPENV_JUMP(3);
1305     }
1306     PerlIO_puts(PerlIO_stderr(),message);
1307     (void)PerlIO_flush(PerlIO_stderr());
1308     my_failure_exit();
1309 }
1310
1311 void
1312 #ifdef I_STDARG
1313 warn(const char* pat,...)
1314 #else
1315 /*VARARGS0*/
1316 warn(pat,va_alist)
1317     const char *pat;
1318     va_dcl
1319 #endif
1320 {
1321     va_list args;
1322     char *message;
1323     HV *stash;
1324     GV *gv;
1325     CV *cv;
1326
1327 #ifdef I_STDARG
1328     va_start(args, pat);
1329 #else
1330     va_start(args);
1331 #endif
1332     message = mess(pat, &args);
1333     va_end(args);
1334
1335     if (warnhook) {
1336         /* sv_2cv might call warn() */
1337         dTHR;
1338         SV *oldwarnhook = warnhook;
1339         ENTER;
1340         SAVESPTR(warnhook);
1341         warnhook = Nullsv;
1342         cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1343         LEAVE;
1344         if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1345             dSP;
1346             SV *msg;
1347
1348             ENTER;
1349             msg = newSVpv(message, 0);
1350             SvREADONLY_on(msg);
1351             SAVEFREESV(msg);
1352
1353             PUSHMARK(sp);
1354             XPUSHs(msg);
1355             PUTBACK;
1356             perl_call_sv((SV*)cv, G_DISCARD);
1357
1358             LEAVE;
1359             return;
1360         }
1361     }
1362     PerlIO_puts(PerlIO_stderr(),message);
1363 #ifdef LEAKTEST
1364     DEBUG_L(xstat());
1365 #endif
1366     (void)PerlIO_flush(PerlIO_stderr());
1367 }
1368
1369 #ifndef VMS  /* VMS' my_setenv() is in VMS.c */
1370 #ifndef WIN32
1371 void
1372 my_setenv(char *nam, char *val)
1373 {
1374     register I32 i=setenv_getix(nam);           /* where does it go? */
1375
1376     if (environ == origenviron) {       /* need we copy environment? */
1377         I32 j;
1378         I32 max;
1379         char **tmpenv;
1380
1381         /*SUPPRESS 530*/
1382         for (max = i; environ[max]; max++) ;
1383         New(901,tmpenv, max+2, char*);
1384         for (j=0; j<max; j++)           /* copy environment */
1385             tmpenv[j] = savepv(environ[j]);
1386         tmpenv[max] = Nullch;
1387         environ = tmpenv;               /* tell exec where it is now */
1388     }
1389     if (!val) {
1390         Safefree(environ[i]);
1391         while (environ[i]) {
1392             environ[i] = environ[i+1];
1393             i++;
1394         }
1395         return;
1396     }
1397     if (!environ[i]) {                  /* does not exist yet */
1398         Renew(environ, i+2, char*);     /* just expand it a bit */
1399         environ[i+1] = Nullch;  /* make sure it's null terminated */
1400     }
1401     else
1402         Safefree(environ[i]);
1403     New(904, environ[i], strlen(nam) + strlen(val) + 2, char);
1404 #ifndef MSDOS
1405     (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
1406 #else
1407     /* MS-DOS requires environment variable names to be in uppercase */
1408     /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
1409      * some utilities and applications may break because they only look
1410      * for upper case strings. (Fixed strupr() bug here.)]
1411      */
1412     strcpy(environ[i],nam); strupr(environ[i]);
1413     (void)sprintf(environ[i] + strlen(nam),"=%s",val);
1414 #endif /* MSDOS */
1415 }
1416
1417 #else /* if WIN32 */
1418
1419 void
1420 my_setenv(char *nam,char *val)
1421 {
1422
1423 #ifdef USE_WIN32_RTL_ENV
1424
1425     register char *envstr;
1426     STRLEN namlen = strlen(nam);
1427     STRLEN vallen;
1428     char *oldstr = environ[setenv_getix(nam)];
1429
1430     /* putenv() has totally broken semantics in both the Borland
1431      * and Microsoft CRTLs.  They either store the passed pointer in
1432      * the environment without making a copy, or make a copy and don't
1433      * free it. And on top of that, they dont free() old entries that
1434      * are being replaced/deleted.  This means the caller must
1435      * free any old entries somehow, or we end up with a memory
1436      * leak every time my_setenv() is called.  One might think
1437      * one could directly manipulate environ[], like the UNIX code
1438      * above, but direct changes to environ are not allowed when
1439      * calling putenv(), since the RTLs maintain an internal
1440      * *copy* of environ[]. Bad, bad, *bad* stink.
1441      * GSAR 97-06-07
1442      */
1443
1444     if (!val) {
1445         if (!oldstr)
1446             return;
1447         val = "";
1448         vallen = 0;
1449     }
1450     else
1451         vallen = strlen(val);
1452     New(904, envstr, namlen + vallen + 3, char);
1453     (void)sprintf(envstr,"%s=%s",nam,val);
1454     (void)putenv(envstr);
1455     if (oldstr)
1456         Safefree(oldstr);
1457 #ifdef _MSC_VER
1458     Safefree(envstr);           /* MSVCRT leaks without this */
1459 #endif
1460
1461 #else /* !USE_WIN32_RTL_ENV */
1462
1463     /* The sane way to deal with the environment.
1464      * Has these advantages over putenv() & co.:
1465      *  * enables us to store a truly empty value in the
1466      *    environment (like in UNIX).
1467      *  * we don't have to deal with RTL globals, bugs and leaks.
1468      *  * Much faster.
1469      * Why you may want to enable USE_WIN32_RTL_ENV:
1470      *  * environ[] and RTL functions will not reflect changes,
1471      *    which might be an issue if extensions want to access
1472      *    the env. via RTL.  This cuts both ways, since RTL will
1473      *    not see changes made by extensions that call the Win32
1474      *    functions directly, either.
1475      * GSAR 97-06-07
1476      */
1477     SetEnvironmentVariable(nam,val);
1478
1479 #endif
1480 }
1481
1482 #endif /* WIN32 */
1483
1484 I32
1485 setenv_getix(char *nam)
1486 {
1487     register I32 i, len = strlen(nam);
1488
1489     for (i = 0; environ[i]; i++) {
1490         if (
1491 #ifdef WIN32
1492             strnicmp(environ[i],nam,len) == 0
1493 #else
1494             strnEQ(environ[i],nam,len)
1495 #endif
1496             && environ[i][len] == '=')
1497             break;                      /* strnEQ must come first to avoid */
1498     }                                   /* potential SEGV's */
1499     return i;
1500 }
1501
1502 #endif /* !VMS */
1503
1504 #ifdef UNLINK_ALL_VERSIONS
1505 I32
1506 unlnk(f)        /* unlink all versions of a file */
1507 char *f;
1508 {
1509     I32 i;
1510
1511     for (i = 0; unlink(f) >= 0; i++) ;
1512     return i ? 0 : -1;
1513 }
1514 #endif
1515
1516 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
1517 char *
1518 my_bcopy(register char *from,register char *to,register I32 len)
1519 {
1520     char *retval = to;
1521
1522     if (from - to >= 0) {
1523         while (len--)
1524             *to++ = *from++;
1525     }
1526     else {
1527         to += len;
1528         from += len;
1529         while (len--)
1530             *(--to) = *(--from);
1531     }
1532     return retval;
1533 }
1534 #endif
1535
1536 #ifndef HAS_MEMSET
1537 void *
1538 my_memset(loc,ch,len)
1539 register char *loc;
1540 register I32 ch;
1541 register I32 len;
1542 {
1543     char *retval = loc;
1544
1545     while (len--)
1546         *loc++ = ch;
1547     return retval;
1548 }
1549 #endif
1550
1551 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1552 char *
1553 my_bzero(loc,len)
1554 register char *loc;
1555 register I32 len;
1556 {
1557     char *retval = loc;
1558
1559     while (len--)
1560         *loc++ = 0;
1561     return retval;
1562 }
1563 #endif
1564
1565 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1566 I32
1567 my_memcmp(s1,s2,len)
1568 char *s1;
1569 char *s2;
1570 register I32 len;
1571 {
1572     register U8 *a = (U8 *)s1;
1573     register U8 *b = (U8 *)s2;
1574     register I32 tmp;
1575
1576     while (len--) {
1577         if (tmp = *a++ - *b++)
1578             return tmp;
1579     }
1580     return 0;
1581 }
1582 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1583
1584 #if defined(I_STDARG) || defined(I_VARARGS)
1585 #ifndef HAS_VPRINTF
1586
1587 #ifdef USE_CHAR_VSPRINTF
1588 char *
1589 #else
1590 int
1591 #endif
1592 vsprintf(dest, pat, args)
1593 char *dest;
1594 const char *pat;
1595 char *args;
1596 {
1597     FILE fakebuf;
1598
1599     fakebuf._ptr = dest;
1600     fakebuf._cnt = 32767;
1601 #ifndef _IOSTRG
1602 #define _IOSTRG 0
1603 #endif
1604     fakebuf._flag = _IOWRT|_IOSTRG;
1605     _doprnt(pat, args, &fakebuf);       /* what a kludge */
1606     (void)putc('\0', &fakebuf);
1607 #ifdef USE_CHAR_VSPRINTF
1608     return(dest);
1609 #else
1610     return 0;           /* perl doesn't use return value */
1611 #endif
1612 }
1613
1614 #endif /* HAS_VPRINTF */
1615 #endif /* I_VARARGS || I_STDARGS */
1616
1617 #ifdef MYSWAP
1618 #if BYTEORDER != 0x4321
1619 short
1620 #ifndef CAN_PROTOTYPE
1621 my_swap(s)
1622 short s;
1623 #else
1624 my_swap(short s)
1625 #endif
1626 {
1627 #if (BYTEORDER & 1) == 0
1628     short result;
1629
1630     result = ((s & 255) << 8) + ((s >> 8) & 255);
1631     return result;
1632 #else
1633     return s;
1634 #endif
1635 }
1636
1637 long
1638 #ifndef CAN_PROTOTYPE
1639 my_htonl(l)
1640 register long l;
1641 #else
1642 my_htonl(long l)
1643 #endif
1644 {
1645     union {
1646         long result;
1647         char c[sizeof(long)];
1648     } u;
1649
1650 #if BYTEORDER == 0x1234
1651     u.c[0] = (l >> 24) & 255;
1652     u.c[1] = (l >> 16) & 255;
1653     u.c[2] = (l >> 8) & 255;
1654     u.c[3] = l & 255;
1655     return u.result;
1656 #else
1657 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1658     croak("Unknown BYTEORDER\n");
1659 #else
1660     register I32 o;
1661     register I32 s;
1662
1663     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1664         u.c[o & 0xf] = (l >> s) & 255;
1665     }
1666     return u.result;
1667 #endif
1668 #endif
1669 }
1670
1671 long
1672 #ifndef CAN_PROTOTYPE
1673 my_ntohl(l)
1674 register long l;
1675 #else
1676 my_ntohl(long l)
1677 #endif
1678 {
1679     union {
1680         long l;
1681         char c[sizeof(long)];
1682     } u;
1683
1684 #if BYTEORDER == 0x1234
1685     u.c[0] = (l >> 24) & 255;
1686     u.c[1] = (l >> 16) & 255;
1687     u.c[2] = (l >> 8) & 255;
1688     u.c[3] = l & 255;
1689     return u.l;
1690 #else
1691 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1692     croak("Unknown BYTEORDER\n");
1693 #else
1694     register I32 o;
1695     register I32 s;
1696
1697     u.l = l;
1698     l = 0;
1699     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1700         l |= (u.c[o & 0xf] & 255) << s;
1701     }
1702     return l;
1703 #endif
1704 #endif
1705 }
1706
1707 #endif /* BYTEORDER != 0x4321 */
1708 #endif /* MYSWAP */
1709
1710 /*
1711  * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1712  * If these functions are defined,
1713  * the BYTEORDER is neither 0x1234 nor 0x4321.
1714  * However, this is not assumed.
1715  * -DWS
1716  */
1717
1718 #define HTOV(name,type)                                         \
1719         type                                                    \
1720         name (n)                                                \
1721         register type n;                                        \
1722         {                                                       \
1723             union {                                             \
1724                 type value;                                     \
1725                 char c[sizeof(type)];                           \
1726             } u;                                                \
1727             register I32 i;                                     \
1728             register I32 s;                                     \
1729             for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) {  \
1730                 u.c[i] = (n >> s) & 0xFF;                       \
1731             }                                                   \
1732             return u.value;                                     \
1733         }
1734
1735 #define VTOH(name,type)                                         \
1736         type                                                    \
1737         name (n)                                                \
1738         register type n;                                        \
1739         {                                                       \
1740             union {                                             \
1741                 type value;                                     \
1742                 char c[sizeof(type)];                           \
1743             } u;                                                \
1744             register I32 i;                                     \
1745             register I32 s;                                     \
1746             u.value = n;                                        \
1747             n = 0;                                              \
1748             for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) {  \
1749                 n += (u.c[i] & 0xFF) << s;                      \
1750             }                                                   \
1751             return n;                                           \
1752         }
1753
1754 #if defined(HAS_HTOVS) && !defined(htovs)
1755 HTOV(htovs,short)
1756 #endif
1757 #if defined(HAS_HTOVL) && !defined(htovl)
1758 HTOV(htovl,long)
1759 #endif
1760 #if defined(HAS_VTOHS) && !defined(vtohs)
1761 VTOH(vtohs,short)
1762 #endif
1763 #if defined(HAS_VTOHL) && !defined(vtohl)
1764 VTOH(vtohl,long)
1765 #endif
1766
1767     /* VMS' my_popen() is in VMS.c, same with OS/2. */
1768 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS)
1769 PerlIO *
1770 my_popen(char *cmd, char *mode)
1771 {
1772     int p[2];
1773     register I32 This, that;
1774     register I32 pid;
1775     SV *sv;
1776     I32 doexec = strNE(cmd,"-");
1777
1778 #ifdef OS2
1779     if (doexec) {
1780         return my_syspopen(cmd,mode);
1781     }
1782 #endif 
1783     if (pipe(p) < 0)
1784         return Nullfp;
1785     This = (*mode == 'w');
1786     that = !This;
1787     if (doexec && tainting) {
1788         taint_env();
1789         taint_proper("Insecure %s%s", "EXEC");
1790     }
1791     while ((pid = (doexec?vfork():fork())) < 0) {
1792         if (errno != EAGAIN) {
1793             close(p[This]);
1794             if (!doexec)
1795                 croak("Can't fork");
1796             return Nullfp;
1797         }
1798         sleep(5);
1799     }
1800     if (pid == 0) {
1801         GV* tmpgv;
1802
1803 #define THIS that
1804 #define THAT This
1805         close(p[THAT]);
1806         if (p[THIS] != (*mode == 'r')) {
1807             dup2(p[THIS], *mode == 'r');
1808             close(p[THIS]);
1809         }
1810         if (doexec) {
1811 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1812             int fd;
1813
1814 #ifndef NOFILE
1815 #define NOFILE 20
1816 #endif
1817             for (fd = maxsysfd + 1; fd < NOFILE; fd++)
1818                 close(fd);
1819 #endif
1820             do_exec(cmd);       /* may or may not use the shell */
1821             _exit(1);
1822         }
1823         /*SUPPRESS 560*/
1824         if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
1825             sv_setiv(GvSV(tmpgv), (IV)getpid());
1826         forkprocess = 0;
1827         hv_clear(pidstatus);    /* we have no children */
1828         return Nullfp;
1829 #undef THIS
1830 #undef THAT
1831     }
1832     do_execfree();      /* free any memory malloced by child on vfork */
1833     close(p[that]);
1834     if (p[that] < p[This]) {
1835         dup2(p[This], p[that]);
1836         close(p[This]);
1837         p[This] = p[that];
1838     }
1839     sv = *av_fetch(fdpid,p[This],TRUE);
1840     (void)SvUPGRADE(sv,SVt_IV);
1841     SvIVX(sv) = pid;
1842     forkprocess = pid;
1843     return PerlIO_fdopen(p[This], mode);
1844 }
1845 #else
1846 #if defined(atarist) || defined(DJGPP)
1847 FILE *popen();
1848 PerlIO *
1849 my_popen(cmd,mode)
1850 char    *cmd;
1851 char    *mode;
1852 {
1853     /* Needs work for PerlIO ! */
1854     /* used 0 for 2nd parameter to PerlIO-exportFILE; apparently not used */
1855     return popen(PerlIO_exportFILE(cmd, 0), mode);
1856 }
1857 #endif
1858
1859 #endif /* !DOSISH */
1860
1861 #ifdef DUMP_FDS
1862 dump_fds(s)
1863 char *s;
1864 {
1865     int fd;
1866     struct stat tmpstatbuf;
1867
1868     PerlIO_printf(PerlIO_stderr(),"%s", s);
1869     for (fd = 0; fd < 32; fd++) {
1870         if (Fstat(fd,&tmpstatbuf) >= 0)
1871             PerlIO_printf(PerlIO_stderr()," %d",fd);
1872     }
1873     PerlIO_printf(PerlIO_stderr(),"\n");
1874 }
1875 #endif
1876
1877 #ifndef HAS_DUP2
1878 int
1879 dup2(oldfd,newfd)
1880 int oldfd;
1881 int newfd;
1882 {
1883 #if defined(HAS_FCNTL) && defined(F_DUPFD)
1884     if (oldfd == newfd)
1885         return oldfd;
1886     close(newfd);
1887     return fcntl(oldfd, F_DUPFD, newfd);
1888 #else
1889 #define DUP2_MAX_FDS 256
1890     int fdtmp[DUP2_MAX_FDS];
1891     I32 fdx = 0;
1892     int fd;
1893
1894     if (oldfd == newfd)
1895         return oldfd;
1896     close(newfd);
1897     /* good enough for low fd's... */
1898     while ((fd = dup(oldfd)) != newfd && fd >= 0) {
1899         if (fdx >= DUP2_MAX_FDS) {
1900             close(fd);
1901             fd = -1;
1902             break;
1903         }
1904         fdtmp[fdx++] = fd;
1905     }
1906     while (fdx > 0)
1907         close(fdtmp[--fdx]);
1908     return fd;
1909 #endif
1910 }
1911 #endif
1912
1913
1914 #ifdef HAS_SIGACTION
1915
1916 Sighandler_t
1917 rsignal(int signo, Sighandler_t handler)
1918 {
1919     struct sigaction act, oact;
1920
1921     act.sa_handler = handler;
1922     sigemptyset(&act.sa_mask);
1923     act.sa_flags = 0;
1924 #ifdef SA_RESTART
1925     act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
1926 #endif
1927     if (sigaction(signo, &act, &oact) == -1)
1928         return SIG_ERR;
1929     else
1930         return oact.sa_handler;
1931 }
1932
1933 Sighandler_t
1934 rsignal_state(int signo)
1935 {
1936     struct sigaction oact;
1937
1938     if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
1939         return SIG_ERR;
1940     else
1941         return oact.sa_handler;
1942 }
1943
1944 int
1945 rsignal_save(int signo, Sighandler_t handler, Sigsave_t *save)
1946 {
1947     struct sigaction act;
1948
1949     act.sa_handler = handler;
1950     sigemptyset(&act.sa_mask);
1951     act.sa_flags = 0;
1952 #ifdef SA_RESTART
1953     act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
1954 #endif
1955     return sigaction(signo, &act, save);
1956 }
1957
1958 int
1959 rsignal_restore(int signo, Sigsave_t *save)
1960 {
1961     return sigaction(signo, save, (struct sigaction *)NULL);
1962 }
1963
1964 #else /* !HAS_SIGACTION */
1965
1966 Sighandler_t
1967 rsignal(int signo, Sighandler_t handler)
1968 {
1969     return signal(signo, handler);
1970 }
1971
1972 static int sig_trapped;
1973
1974 static
1975 Signal_t
1976 sig_trap(int signo)
1977 {
1978     sig_trapped++;
1979 }
1980
1981 Sighandler_t
1982 rsignal_state(int signo)
1983 {
1984     Sighandler_t oldsig;
1985
1986     sig_trapped = 0;
1987     oldsig = signal(signo, sig_trap);
1988     signal(signo, oldsig);
1989     if (sig_trapped)
1990         kill(getpid(), signo);
1991     return oldsig;
1992 }
1993
1994 int
1995 rsignal_save(int signo, Sighandler_t handler, Sigsave_t *save)
1996 {
1997     *save = signal(signo, handler);
1998     return (*save == SIG_ERR) ? -1 : 0;
1999 }
2000
2001 int
2002 rsignal_restore(int signo, Sigsave_t *save)
2003 {
2004     return (signal(signo, *save) == SIG_ERR) ? -1 : 0;
2005 }
2006
2007 #endif /* !HAS_SIGACTION */
2008
2009     /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2010 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS)
2011 I32
2012 my_pclose(FILE *ptr)
2013 {
2014     Sigsave_t hstat, istat, qstat;
2015     int status;
2016     SV **svp;
2017     int pid;
2018     bool close_failed;
2019     int saved_errno;
2020 #ifdef VMS
2021     int saved_vaxc_errno;
2022 #endif
2023 #ifdef WIN32
2024     int saved_win32_errno;
2025 #endif
2026
2027     svp = av_fetch(fdpid,PerlIO_fileno(ptr),TRUE);
2028     pid = (int)SvIVX(*svp);
2029     SvREFCNT_dec(*svp);
2030     *svp = &sv_undef;
2031 #ifdef OS2
2032     if (pid == -1) {                    /* Opened by popen. */
2033         return my_syspclose(ptr);
2034     }
2035 #endif 
2036     if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2037         saved_errno = errno;
2038 #ifdef VMS
2039         saved_vaxc_errno = vaxc$errno;
2040 #endif
2041 #ifdef WIN32
2042         saved_win32_errno = GetLastError();
2043 #endif
2044     }
2045 #ifdef UTS
2046     if(kill(pid, 0) < 0) { return(pid); }   /* HOM 12/23/91 */
2047 #endif
2048     rsignal_save(SIGHUP, SIG_IGN, &hstat);
2049     rsignal_save(SIGINT, SIG_IGN, &istat);
2050     rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2051     do {
2052         pid = wait4pid(pid, &status, 0);
2053     } while (pid == -1 && errno == EINTR);
2054     rsignal_restore(SIGHUP, &hstat);
2055     rsignal_restore(SIGINT, &istat);
2056     rsignal_restore(SIGQUIT, &qstat);
2057     if (close_failed) {
2058         SETERRNO(saved_errno, saved_vaxc_errno);
2059         return -1;
2060     }
2061     return(pid < 0 ? pid : status == 0 ? 0 : (errno = 0, status));
2062 }
2063 #endif /* !DOSISH */
2064
2065 #if  !defined(DOSISH) || defined(OS2) || defined(WIN32)
2066 I32
2067 wait4pid(int pid, int *statusp, int flags)
2068 {
2069     SV *sv;
2070     SV** svp;
2071     char spid[TYPE_CHARS(int)];
2072
2073     if (!pid)
2074         return -1;
2075     if (pid > 0) {
2076         sprintf(spid, "%d", pid);
2077         svp = hv_fetch(pidstatus,spid,strlen(spid),FALSE);
2078         if (svp && *svp != &sv_undef) {
2079             *statusp = SvIVX(*svp);
2080             (void)hv_delete(pidstatus,spid,strlen(spid),G_DISCARD);
2081             return pid;
2082         }
2083     }
2084     else {
2085         HE *entry;
2086
2087         hv_iterinit(pidstatus);
2088         if (entry = hv_iternext(pidstatus)) {
2089             pid = atoi(hv_iterkey(entry,(I32*)statusp));
2090             sv = hv_iterval(pidstatus,entry);
2091             *statusp = SvIVX(sv);
2092             sprintf(spid, "%d", pid);
2093             (void)hv_delete(pidstatus,spid,strlen(spid),G_DISCARD);
2094             return pid;
2095         }
2096     }
2097 #ifdef HAS_WAITPID
2098 #  ifdef HAS_WAITPID_RUNTIME
2099     if (!HAS_WAITPID_RUNTIME)
2100         goto hard_way;
2101 #  endif
2102     return waitpid(pid,statusp,flags);
2103 #endif
2104 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2105     return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2106 #endif
2107 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2108   hard_way:
2109     {
2110         I32 result;
2111         if (flags)
2112             croak("Can't do waitpid with flags");
2113         else {
2114             while ((result = wait(statusp)) != pid && pid > 0 && result >= 0)
2115                 pidgone(result,*statusp);
2116             if (result < 0)
2117                 *statusp = -1;
2118         }
2119         return result;
2120     }
2121 #endif
2122 }
2123 #endif /* !DOSISH || OS2 || WIN32 */
2124
2125 void
2126 /*SUPPRESS 590*/
2127 pidgone(int pid, int status)
2128 {
2129     register SV *sv;
2130     char spid[TYPE_CHARS(int)];
2131
2132     sprintf(spid, "%d", pid);
2133     sv = *hv_fetch(pidstatus,spid,strlen(spid),TRUE);
2134     (void)SvUPGRADE(sv,SVt_IV);
2135     SvIVX(sv) = status;
2136     return;
2137 }
2138
2139 #if defined(atarist) || defined(OS2) || defined(DJGPP)
2140 int pclose();
2141 #ifdef HAS_FORK
2142 int                                     /* Cannot prototype with I32
2143                                            in os2ish.h. */
2144 my_syspclose(ptr)
2145 #else
2146 I32
2147 my_pclose(ptr)
2148 #endif 
2149 PerlIO *ptr;
2150 {
2151     /* Needs work for PerlIO ! */
2152     FILE *f = PerlIO_findFILE(ptr);
2153     I32 result = pclose(f);
2154     PerlIO_releaseFILE(ptr,f);
2155     return result;
2156 }
2157 #endif
2158
2159 void
2160 repeatcpy(register char *to, register char *from, I32 len, register I32 count)
2161 {
2162     register I32 todo;
2163     register char *frombase = from;
2164
2165     if (len == 1) {
2166         todo = *from;
2167         while (count-- > 0)
2168             *to++ = todo;
2169         return;
2170     }
2171     while (count-- > 0) {
2172         for (todo = len; todo > 0; todo--) {
2173             *to++ = *from++;
2174         }
2175         from = frombase;
2176     }
2177 }
2178
2179 #ifndef CASTNEGFLOAT
2180 U32
2181 cast_ulong(f)
2182 double f;
2183 {
2184     long along;
2185
2186 #if CASTFLAGS & 2
2187 #   define BIGDOUBLE 2147483648.0
2188     if (f >= BIGDOUBLE)
2189         return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2190 #endif
2191     if (f >= 0.0)
2192         return (unsigned long)f;
2193     along = (long)f;
2194     return (unsigned long)along;
2195 }
2196 # undef BIGDOUBLE
2197 #endif
2198
2199 #ifndef CASTI32
2200
2201 /* Unfortunately, on some systems the cast_uv() function doesn't
2202    work with the system-supplied definition of ULONG_MAX.  The
2203    comparison  (f >= ULONG_MAX) always comes out true.  It must be a
2204    problem with the compiler constant folding.
2205
2206    In any case, this workaround should be fine on any two's complement
2207    system.  If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2208    ccflags.
2209                --Andy Dougherty      <doughera@lafcol.lafayette.edu>
2210 */
2211
2212 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2213    of LONG_(MIN/MAX).
2214                            -- Kenneth Albanowski <kjahds@kjahds.com>
2215 */                                      
2216
2217 #ifndef MY_UV_MAX
2218 #  define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2219 #endif
2220
2221 I32
2222 cast_i32(f)
2223 double f;
2224 {
2225     if (f >= I32_MAX)
2226         return (I32) I32_MAX;
2227     if (f <= I32_MIN)
2228         return (I32) I32_MIN;
2229     return (I32) f;
2230 }
2231
2232 IV
2233 cast_iv(f)
2234 double f;
2235 {
2236     if (f >= IV_MAX)
2237         return (IV) IV_MAX;
2238     if (f <= IV_MIN)
2239         return (IV) IV_MIN;
2240     return (IV) f;
2241 }
2242
2243 UV
2244 cast_uv(f)
2245 double f;
2246 {
2247     if (f >= MY_UV_MAX)
2248         return (UV) MY_UV_MAX;
2249     return (UV) f;
2250 }
2251
2252 #endif
2253
2254 #ifndef HAS_RENAME
2255 I32
2256 same_dirent(a,b)
2257 char *a;
2258 char *b;
2259 {
2260     char *fa = strrchr(a,'/');
2261     char *fb = strrchr(b,'/');
2262     struct stat tmpstatbuf1;
2263     struct stat tmpstatbuf2;
2264     SV *tmpsv = sv_newmortal();
2265
2266     if (fa)
2267         fa++;
2268     else
2269         fa = a;
2270     if (fb)
2271         fb++;
2272     else
2273         fb = b;
2274     if (strNE(a,b))
2275         return FALSE;
2276     if (fa == a)
2277         sv_setpv(tmpsv, ".");
2278     else
2279         sv_setpvn(tmpsv, a, fa - a);
2280     if (Stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2281         return FALSE;
2282     if (fb == b)
2283         sv_setpv(tmpsv, ".");
2284     else
2285         sv_setpvn(tmpsv, b, fb - b);
2286     if (Stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2287         return FALSE;
2288     return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2289            tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2290 }
2291 #endif /* !HAS_RENAME */
2292
2293 UV
2294 scan_oct(char *start, I32 len, I32 *retlen)
2295 {
2296     register char *s = start;
2297     register UV retval = 0;
2298     bool overflowed = FALSE;
2299
2300     while (len && *s >= '0' && *s <= '7') {
2301         register UV n = retval << 3;
2302         if (!overflowed && (n >> 3) != retval) {
2303             warn("Integer overflow in octal number");
2304             overflowed = TRUE;
2305         }
2306         retval = n | (*s++ - '0');
2307         len--;
2308     }
2309     if (dowarn && len && (*s == '8' || *s == '9'))
2310         warn("Illegal octal digit ignored");
2311     *retlen = s - start;
2312     return retval;
2313 }
2314
2315 UV
2316 scan_hex(char *start, I32 len, I32 *retlen)
2317 {
2318     register char *s = start;
2319     register UV retval = 0;
2320     bool overflowed = FALSE;
2321     char *tmp;
2322
2323     while (len-- && *s && (tmp = strchr((char *) hexdigit, *s))) {
2324         register UV n = retval << 4;
2325         if (!overflowed && (n >> 4) != retval) {
2326             warn("Integer overflow in hex number");
2327             overflowed = TRUE;
2328         }
2329         retval = n | ((tmp - hexdigit) & 15);
2330         s++;
2331     }
2332     *retlen = s - start;
2333     return retval;
2334 }
2335
2336 #ifdef USE_THREADS
2337 #ifdef FAKE_THREADS
2338 /* Very simplistic scheduler for now */
2339 void
2340 schedule(void)
2341 {
2342     thr = thr->i.next_run;
2343 }
2344
2345 void
2346 perl_cond_init(cp)
2347 perl_cond *cp;
2348 {
2349     *cp = 0;
2350 }
2351
2352 void
2353 perl_cond_signal(cp)
2354 perl_cond *cp;
2355 {
2356     perl_os_thread t;
2357     perl_cond cond = *cp;
2358     
2359     if (!cond)
2360         return;
2361     t = cond->thread;
2362     /* Insert t in the runnable queue just ahead of us */
2363     t->i.next_run = thr->i.next_run;
2364     thr->i.next_run->i.prev_run = t;
2365     t->i.prev_run = thr;
2366     thr->i.next_run = t;
2367     thr->i.wait_queue = 0;
2368     /* Remove from the wait queue */
2369     *cp = cond->next;
2370     Safefree(cond);
2371 }
2372
2373 void
2374 perl_cond_broadcast(cp)
2375 perl_cond *cp;
2376 {
2377     perl_os_thread t;
2378     perl_cond cond, cond_next;
2379     
2380     for (cond = *cp; cond; cond = cond_next) {
2381         t = cond->thread;
2382         /* Insert t in the runnable queue just ahead of us */
2383         t->i.next_run = thr->i.next_run;
2384         thr->i.next_run->i.prev_run = t;
2385         t->i.prev_run = thr;
2386         thr->i.next_run = t;
2387         thr->i.wait_queue = 0;
2388         /* Remove from the wait queue */
2389         cond_next = cond->next;
2390         Safefree(cond);
2391     }
2392     *cp = 0;
2393 }
2394
2395 void
2396 perl_cond_wait(cp)
2397 perl_cond *cp;
2398 {
2399     perl_cond cond;
2400
2401     if (thr->i.next_run == thr)
2402         croak("panic: perl_cond_wait called by last runnable thread");
2403     
2404     New(666, cond, 1, struct perl_wait_queue);
2405     cond->thread = thr;
2406     cond->next = *cp;
2407     *cp = cond;
2408     thr->i.wait_queue = cond;
2409     /* Remove ourselves from runnable queue */
2410     thr->i.next_run->i.prev_run = thr->i.prev_run;
2411     thr->i.prev_run->i.next_run = thr->i.next_run;
2412 }
2413 #endif /* FAKE_THREADS */
2414
2415 #ifdef OLD_PTHREADS_API
2416 struct perl_thread *
2417 getTHR _((void))
2418 {
2419     pthread_addr_t t;
2420
2421     if (pthread_getspecific(thr_key, &t))
2422         croak("panic: pthread_getspecific");
2423     return (struct perl_thread *) t;
2424 }
2425 #endif /* OLD_PTHREADS_API */
2426
2427 MAGIC *
2428 condpair_magic(SV *sv)
2429 {
2430     MAGIC *mg;
2431     
2432     SvUPGRADE(sv, SVt_PVMG);
2433     mg = mg_find(sv, 'm');
2434     if (!mg) {
2435         condpair_t *cp;
2436
2437         New(53, cp, 1, condpair_t);
2438         MUTEX_INIT(&cp->mutex);
2439         COND_INIT(&cp->owner_cond);
2440         COND_INIT(&cp->cond);
2441         cp->owner = 0;
2442         LOCK_SV_MUTEX;
2443         mg = mg_find(sv, 'm');
2444         if (mg) {
2445             /* someone else beat us to initialising it */
2446             UNLOCK_SV_MUTEX;
2447             MUTEX_DESTROY(&cp->mutex);
2448             COND_DESTROY(&cp->owner_cond);
2449             COND_DESTROY(&cp->cond);
2450             Safefree(cp);
2451         }
2452         else {
2453             sv_magic(sv, Nullsv, 'm', 0, 0);
2454             mg = SvMAGIC(sv);
2455             mg->mg_ptr = (char *)cp;
2456             mg->mg_len = sizeof(cp);
2457             UNLOCK_SV_MUTEX;
2458             DEBUG_L(WITH_THR(PerlIO_printf(PerlIO_stderr(),
2459                                            "%p: condpair_magic %p\n", thr, sv));)
2460         }
2461     }
2462     return mg;
2463 }
2464
2465 /*
2466  * Make a new perl thread structure using t as a prototype. Some of the
2467  * fields for the new thread are copied from the prototype thread, t,
2468  * so t should not be running in perl at the time this function is
2469  * called. The use by ext/Thread/Thread.xs in core perl (where t is the
2470  * thread calling new_struct_thread) clearly satisfies this constraint.
2471  */
2472 struct perl_thread *
2473 new_struct_thread(struct perl_thread *t)
2474 {
2475     struct perl_thread *thr;
2476     SV *sv;
2477     SV **svp;
2478     I32 i;
2479
2480     sv = newSVpv("", 0);
2481     SvGROW(sv, sizeof(struct perl_thread) + 1);
2482     SvCUR_set(sv, sizeof(struct perl_thread));
2483     thr = (Thread) SvPVX(sv);
2484     /* debug */
2485     memset(thr, 0xab, sizeof(struct perl_thread));
2486     markstack = 0;
2487     scopestack = 0;
2488     savestack = 0;
2489     retstack = 0;
2490     dirty = 0;
2491     localizing = 0;
2492     /* end debug */
2493
2494     thr->oursv = sv;
2495     init_stacks(ARGS);
2496
2497     curcop = &compiling;
2498     thr->cvcache = newHV();
2499     thr->threadsv = newAV();
2500     thr->specific = newAV();
2501     thr->errsv = newSVpv("", 0);
2502     thr->errhv = newHV();
2503     thr->flags = THRf_R_JOINABLE;
2504     MUTEX_INIT(&thr->mutex);
2505
2506     curcop = t->Tcurcop;       /* XXX As good a guess as any? */
2507     defstash = t->Tdefstash;   /* XXX maybe these should */
2508     curstash = t->Tcurstash;   /* always be set to main? */
2509
2510
2511     /* top_env needs to be non-zero. It points to an area
2512        in which longjmp() stuff is stored, as C callstack
2513        info there at least is thread specific this has to
2514        be per-thread. Otherwise a 'die' in a thread gives
2515        that thread the C stack of last thread to do an eval {}!
2516        See comments in scope.h    
2517        Initialize top entry (as in perl.c for main thread)
2518      */
2519     start_env.je_prev = NULL;
2520     start_env.je_ret = -1;
2521     start_env.je_mustcatch = TRUE;
2522     top_env  = &start_env;
2523
2524     in_eval = FALSE;
2525     restartop = 0;
2526
2527     tainted = t->Ttainted;
2528     curpm = t->Tcurpm;         /* XXX No PMOP ref count */
2529     nrs = newSVsv(t->Tnrs);
2530     rs = newSVsv(t->Trs);
2531     last_in_gv = (GV*)SvREFCNT_inc(t->Tlast_in_gv);
2532     ofslen = t->Tofslen;
2533     ofs = savepvn(t->Tofs, ofslen);
2534     defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
2535     chopset = t->Tchopset;
2536     formtarget = newSVsv(t->Tformtarget);
2537     bodytarget = newSVsv(t->Tbodytarget);
2538     toptarget = newSVsv(t->Ttoptarget);
2539     
2540     /* Initialise all per-thread SVs that the template thread used */
2541     svp = AvARRAY(t->threadsv);
2542     for (i = 0; i <= AvFILL(t->threadsv); i++, svp++) {
2543         if (*svp && *svp != &sv_undef) {
2544             SV *sv = newSVsv(*svp);
2545             av_store(thr->threadsv, i, sv);
2546             sv_magic(sv, 0, 0, &threadsv_names[i], 1);
2547             DEBUG_L(PerlIO_printf(PerlIO_stderr(),
2548                 "new_struct_thread: copied threadsv %d %p->%p\n",i, t, thr));
2549         }
2550     } 
2551     thr->threadsvp = AvARRAY(thr->threadsv);
2552
2553     MUTEX_LOCK(&threads_mutex);
2554     nthreads++;
2555     thr->tid = ++threadnum;
2556     thr->next = t->next;
2557     thr->prev = t;
2558     t->next = thr;
2559     thr->next->prev = thr;
2560     MUTEX_UNLOCK(&threads_mutex);
2561
2562 #ifdef HAVE_THREAD_INTERN
2563     init_thread_intern(thr);
2564 #endif /* HAVE_THREAD_INTERN */
2565     return thr;
2566 }
2567 #endif /* USE_THREADS */
2568
2569 #ifdef HUGE_VAL
2570 /*
2571  * This hack is to force load of "huge" support from libm.a
2572  * So it is in perl for (say) POSIX to use. 
2573  * Needed for SunOS with Sun's 'acc' for example.
2574  */
2575 double 
2576 Perl_huge(void)
2577 {
2578  return HUGE_VAL;
2579 }
2580 #endif
2581
2582 #ifdef PERL_GLOBAL_STRUCT
2583 struct perl_vars *
2584 Perl_GetVars(void)
2585 {
2586  return &Perl_Vars;
2587 }
2588 #endif
2589
2590 char **
2591 get_op_names(void)
2592 {
2593  return op_name;
2594 }
2595
2596 char **
2597 get_op_descs(void)
2598 {
2599  return op_desc;
2600 }