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