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