[inseparable changes from patch from perl5.003_12 to perl5.003_13]
[p5sagit/p5-mst-13.2.git] / util.c
1 /*    util.c
2  *
3  *    Copyright (c) 1991-1994, Larry Wall
4  *
5  *    You may distribute under the terms of either the GNU General Public
6  *    License or the Artistic License, as specified in the README file.
7  *
8  */
9
10 /*
11  * "Very useful, no doubt, that was to Saruman; yet it seems that he was
12  * not content."  --Gandalf
13  */
14
15 #include "EXTERN.h"
16 #include "perl.h"
17
18 #if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
19 #include <signal.h>
20 #endif
21
22 #ifndef SIG_ERR
23 # define SIG_ERR ((Sighandler_t) -1)
24 #endif
25
26 /* XXX If this causes problems, set i_unistd=undef in the hint file.  */
27 #ifdef I_UNISTD
28 #  include <unistd.h>
29 #endif
30
31 #ifdef I_VFORK
32 #  include <vfork.h>
33 #endif
34
35 /* Put this after #includes because fork and vfork prototypes may
36    conflict.
37 */
38 #ifndef HAS_VFORK
39 #   define vfork fork
40 #endif
41
42 #ifdef I_FCNTL
43 #  include <fcntl.h>
44 #endif
45 #ifdef I_SYS_FILE
46 #  include <sys/file.h>
47 #endif
48
49 #ifdef I_SYS_WAIT
50 #  include <sys/wait.h>
51 #endif
52
53 #define FLUSH
54
55 #ifdef LEAKTEST
56 static void xstat _((void));
57 #endif
58
59 #ifndef MYMALLOC
60
61 /* paranoid version of malloc */
62
63 /* NOTE:  Do not call the next three routines directly.  Use the macros
64  * in handy.h, so that we can easily redefine everything to do tracking of
65  * allocated hunks back to the original New to track down any memory leaks.
66  * XXX This advice seems to be widely ignored :-(   --AD  August 1996.
67  */
68
69 Malloc_t
70 safemalloc(size)
71 MEM_SIZE size;
72 {
73     Malloc_t ptr;
74 #ifdef HAS_64K_LIMIT
75         if (size > 0xffff) {
76                 PerlIO_printf(PerlIO_stderr(), "Allocation too large: %lx\n", size) FLUSH;
77                 my_exit(1);
78         }
79 #endif /* HAS_64K_LIMIT */
80 #ifdef DEBUGGING
81     if ((long)size < 0)
82         croak("panic: malloc");
83 #endif
84     ptr = malloc(size?size:1);  /* malloc(0) is NASTY on our system */
85 #if !(defined(I286) || defined(atarist))
86     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%x: (%05d) malloc %ld bytes\n",ptr,an++,(long)size));
87 #else
88     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) malloc %ld bytes\n",ptr,an++,(long)size));
89 #endif
90     if (ptr != Nullch)
91         return ptr;
92     else if (nomemok)
93         return Nullch;
94     else {
95         PerlIO_puts(PerlIO_stderr(),no_mem) FLUSH;
96         my_exit(1);
97     }
98     /*NOTREACHED*/
99 }
100
101 /* paranoid version of realloc */
102
103 Malloc_t
104 saferealloc(where,size)
105 Malloc_t where;
106 MEM_SIZE size;
107 {
108     Malloc_t ptr;
109 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE)
110     Malloc_t realloc();
111 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
112
113 #ifdef HAS_64K_LIMIT 
114     if (size > 0xffff) {
115         PerlIO_printf(PerlIO_stderr(),
116                       "Reallocation too large: %lx\n", size) FLUSH;
117         my_exit(1);
118     }
119 #endif /* HAS_64K_LIMIT */
120     if (!where)
121         croak("Null realloc");
122 #ifdef DEBUGGING
123     if ((long)size < 0)
124         croak("panic: realloc");
125 #endif
126     ptr = realloc(where,size?size:1);   /* realloc(0) is NASTY on our system */
127
128 #if !(defined(I286) || defined(atarist))
129     DEBUG_m( {
130         PerlIO_printf(Perl_debug_log, "0x%x: (%05d) rfree\n",where,an++);
131         PerlIO_printf(Perl_debug_log, "0x%x: (%05d) realloc %ld bytes\n",ptr,an++,(long)size);
132     } )
133 #else
134     DEBUG_m( {
135         PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) rfree\n",where,an++);
136         PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) realloc %ld bytes\n",ptr,an++,(long)size);
137     } )
138 #endif
139
140     if (ptr != Nullch)
141         return ptr;
142     else if (nomemok)
143         return Nullch;
144     else {
145         PerlIO_puts(PerlIO_stderr(),no_mem) FLUSH;
146         my_exit(1);
147     }
148     /*NOTREACHED*/
149 }
150
151 /* safe version of free */
152
153 void
154 safefree(where)
155 Malloc_t where;
156 {
157 #if !(defined(I286) || defined(atarist))
158     DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%x: (%05d) free\n",where,an++));
159 #else
160     DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) free\n",where,an++));
161 #endif
162     if (where) {
163         /*SUPPRESS 701*/
164         free(where);
165     }
166 }
167
168 /* safe version of calloc */
169
170 Malloc_t
171 safecalloc(count, size)
172 MEM_SIZE count;
173 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 #if !(defined(I286) || defined(atarist))
189     DEBUG_m(PerlIO_printf(PerlIO_stderr(), "0x%x: (%05d) calloc %ld  x %ld bytes\n",ptr,an++,(long)count,(long)size));
190 #else
191     DEBUG_m(PerlIO_printf(PerlIO_stderr(), "0x%lx: (%05d) calloc %ld x %ld bytes\n",ptr,an++,(long)count,(long)size));
192 #endif
193     size *= count;
194     ptr = malloc(size?size:1);  /* malloc(0) is NASTY on our system */
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     }
205     /*NOTREACHED*/
206 }
207
208 #endif /* !MYMALLOC */
209
210 #ifdef LEAKTEST
211
212 #define ALIGN sizeof(long)
213
214 Malloc_t
215 safexmalloc(x,size)
216 I32 x;
217 MEM_SIZE size;
218 {
219     register Malloc_t where;
220
221     where = safemalloc(size + ALIGN);
222     xcount[x]++;
223     where[0] = x % 100;
224     where[1] = x / 100;
225     return where + ALIGN;
226 }
227
228 Malloc_t
229 safexrealloc(where,size)
230 Malloc_t where;
231 MEM_SIZE size;
232 {
233     register Malloc_t new = saferealloc(where - ALIGN, size + ALIGN);
234     return new + ALIGN;
235 }
236
237 void
238 safexfree(where)
239 Malloc_t where;
240 {
241     I32 x;
242
243     if (!where)
244         return;
245     where -= ALIGN;
246     x = where[0] + 100 * where[1];
247     xcount[x]--;
248     safefree(where);
249 }
250
251 Malloc_t
252 safexcalloc(x,count,size)
253 I32 x;
254 MEM_SIZE count;
255 MEM_SIZE size;
256 {
257     register Malloc_t where;
258
259     where = safexmalloc(x, size * count + ALIGN);
260     xcount[x]++;
261     memset((void*)where + ALIGN, 0, size * count);
262     where[0] = x % 100;
263     where[1] = x / 100;
264     return where + ALIGN;
265 }
266
267 static void
268 xstat()
269 {
270     register I32 i;
271
272     for (i = 0; i < MAXXCOUNT; i++) {
273         if (xcount[i] > lastxcount[i]) {
274             PerlIO_printf(PerlIO_stderr(),"%2d %2d\t%ld\n", i / 100, i % 100, xcount[i]);
275             lastxcount[i] = xcount[i];
276         }
277     }
278 }
279
280 #endif /* LEAKTEST */
281
282 /* copy a string up to some (non-backslashed) delimiter, if any */
283
284 char *
285 cpytill(to,from,fromend,delim,retlen)
286 register char *to;
287 register char *from;
288 register char *fromend;
289 register int delim;
290 I32 *retlen;
291 {
292     char *origto = to;
293
294     for (; from < fromend; from++,to++) {
295         if (*from == '\\') {
296             if (from[1] == delim)
297                 from++;
298             else if (from[1] == '\\')
299                 *to++ = *from++;
300         }
301         else if (*from == delim)
302             break;
303         *to = *from;
304     }
305     *to = '\0';
306     *retlen = to - origto;
307     return from;
308 }
309
310 /* return ptr to little string in big string, NULL if not found */
311 /* This routine was donated by Corey Satten. */
312
313 char *
314 instr(big, little)
315 register char *big;
316 register char *little;
317 {
318     register char *s, *x;
319     register I32 first;
320
321     if (!little)
322         return big;
323     first = *little++;
324     if (!first)
325         return big;
326     while (*big) {
327         if (*big++ != first)
328             continue;
329         for (x=big,s=little; *s; /**/ ) {
330             if (!*x)
331                 return Nullch;
332             if (*s++ != *x++) {
333                 s--;
334                 break;
335             }
336         }
337         if (!*s)
338             return big-1;
339     }
340     return Nullch;
341 }
342
343 /* same as instr but allow embedded nulls */
344
345 char *
346 ninstr(big, bigend, little, lend)
347 register char *big;
348 register char *bigend;
349 char *little;
350 char *lend;
351 {
352     register char *s, *x;
353     register I32 first = *little;
354     register char *littleend = lend;
355
356     if (!first && little >= littleend)
357         return big;
358     if (bigend - big < littleend - little)
359         return Nullch;
360     bigend -= littleend - little++;
361     while (big <= bigend) {
362         if (*big++ != first)
363             continue;
364         for (x=big,s=little; s < littleend; /**/ ) {
365             if (*s++ != *x++) {
366                 s--;
367                 break;
368             }
369         }
370         if (s >= littleend)
371             return big-1;
372     }
373     return Nullch;
374 }
375
376 /* reverse of the above--find last substring */
377
378 char *
379 rninstr(big, bigend, little, lend)
380 register char *big;
381 char *bigend;
382 char *little;
383 char *lend;
384 {
385     register char *bigbeg;
386     register char *s, *x;
387     register I32 first = *little;
388     register char *littleend = lend;
389
390     if (!first && little >= littleend)
391         return bigend;
392     bigbeg = big;
393     big = bigend - (littleend - little++);
394     while (big >= bigbeg) {
395         if (*big-- != first)
396             continue;
397         for (x=big+2,s=little; s < littleend; /**/ ) {
398             if (*s++ != *x++) {
399                 s--;
400                 break;
401             }
402         }
403         if (s >= littleend)
404             return big+1;
405     }
406     return Nullch;
407 }
408
409 /*
410  * Set up for a new ctype locale.
411  */
412 void
413 perl_new_ctype(newctype)
414     char *newctype;
415 {
416 #ifdef USE_LOCALE_CTYPE
417
418     int i;
419
420     for (i = 0; i < 256; i++) {
421         if (isUPPER_LC(i))
422             fold_locale[i] = toLOWER_LC(i);
423         else if (isLOWER_LC(i))
424             fold_locale[i] = toUPPER_LC(i);
425         else
426             fold_locale[i] = i;
427     }
428
429 #endif /* USE_LOCALE_CTYPE */
430 }
431
432 /*
433  * Set up for a new collation locale.
434  */
435 void
436 perl_new_collate(newcoll)
437     char *newcoll;
438 {
439 #ifdef USE_LOCALE_COLLATE
440
441     if (! newcoll) {
442         if (collation_name) {
443             ++collation_ix;
444             Safefree(collation_name);
445             collation_name = NULL;
446             collation_standard = TRUE;
447             collxfrm_base = 0;
448             collxfrm_mult = 2;
449         }
450         return;
451     }
452
453     if (! collation_name || strNE(collation_name, newcoll)) {
454         ++collation_ix;
455         Safefree(collation_name);
456         collation_name = savepv(newcoll);
457         collation_standard = (strEQ(newcoll, "C") || strEQ(newcoll, "POSIX"));
458
459         {
460           /*  2: at most so many chars ('a', 'b'). */
461           /* 50: surely no system expands a char more. */
462 #define XFRMBUFSIZE  (2 * 50)
463           char xbuf[XFRMBUFSIZE];
464           Size_t fa = strxfrm(xbuf, "a",  XFRMBUFSIZE);
465           Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
466           SSize_t mult = fb - fa;
467           if (mult < 1)
468               croak("strxfrm() gets absurd");
469           collxfrm_base = (fa > mult) ? (fa - mult) : 0;
470           collxfrm_mult = mult;
471         }
472     }
473
474 #endif /* USE_LOCALE_COLLATE */
475 }
476
477 /*
478  * Set up for a new numeric locale.
479  */
480 void
481 perl_new_numeric(newnum)
482     char *newnum;
483 {
484 #ifdef USE_LOCALE_NUMERIC
485
486     if (! newnum) {
487         if (numeric_name) {
488             Safefree(numeric_name);
489             numeric_name = NULL;
490             numeric_standard = TRUE;
491             numeric_local = TRUE;
492         }
493         return;
494     }
495
496     if (! numeric_name || strNE(numeric_name, newnum)) {
497         Safefree(numeric_name);
498         numeric_name = savepv(newnum);
499         numeric_standard = (strEQ(newnum, "C") || strEQ(newnum, "POSIX"));
500         numeric_local = TRUE;
501     }
502
503 #endif /* USE_LOCALE_NUMERIC */
504 }
505
506 void
507 perl_set_numeric_standard()
508 {
509 #ifdef USE_LOCALE_NUMERIC
510
511     if (! numeric_standard) {
512         setlocale(LC_NUMERIC, "C");
513         numeric_standard = TRUE;
514         numeric_local = FALSE;
515     }
516
517 #endif /* USE_LOCALE_NUMERIC */
518 }
519
520 void
521 perl_set_numeric_local()
522 {
523 #ifdef USE_LOCALE_NUMERIC
524
525     if (! numeric_local) {
526         setlocale(LC_NUMERIC, numeric_name);
527         numeric_standard = FALSE;
528         numeric_local = TRUE;
529     }
530
531 #endif /* USE_LOCALE_NUMERIC */
532 }
533
534
535 /*
536  * Initialize locale awareness.
537  */
538 int
539 perl_init_i18nl10n(printwarn)   
540     int printwarn;
541 {
542     int ok = 1;
543     /* returns
544      *    1 = set ok or not applicable,
545      *    0 = fallback to C locale,
546      *   -1 = fallback to C locale failed
547      */
548
549 #ifdef USE_LOCALE
550
551 #ifdef LC_ALL
552     char *lc_all     = getenv("LC_ALL");
553 #endif /* LC_ALL */
554 #ifdef USE_LOCALE_CTYPE
555     char *lc_ctype   = getenv("LC_CTYPE");
556     char *curctype   = NULL;
557 #endif /* USE_LOCALE_CTYPE */
558 #ifdef USE_LOCALE_COLLATE
559     char *lc_collate = getenv("LC_COLLATE");
560     char *curcoll    = NULL;
561 #endif /* USE_LOCALE_COLLATE */
562 #ifdef USE_LOCALE_NUMERIC
563     char *lc_numeric = getenv("LC_NUMERIC");
564     char *curnum     = NULL;
565 #endif /* USE_LOCALE_NUMERIC */
566     char *lang       = getenv("LANG");
567     bool setlocale_failure = FALSE;
568
569 #ifdef LC_ALL
570
571     if (! setlocale(LC_ALL, ""))
572         setlocale_failure = TRUE;
573     else {
574 #ifdef USE_LOCALE_CTYPE
575         curctype = setlocale(LC_CTYPE, Nullch);
576 #endif /* USE_LOCALE_CTYPE */
577 #ifdef USE_LOCALE_COLLATE
578         curcoll = setlocale(LC_COLLATE, Nullch);
579 #endif /* USE_LOCALE_COLLATE */
580 #ifdef USE_LOCALE_NUMERIC
581         curnum = setlocale(LC_NUMERIC, Nullch);
582 #endif /* USE_LOCALE_NUMERIC */
583     }
584
585 #else /* !LC_ALL */
586
587 #ifdef USE_LOCALE_CTYPE
588     if (! (curctype = setlocale(LC_CTYPE, "")))
589         setlocale_failure = TRUE;
590 #endif /* USE_LOCALE_CTYPE */
591 #ifdef USE_LOCALE_COLLATE
592     if (! (curcoll = setlocale(LC_COLLATE, "")))
593         setlocale_failure = TRUE;
594 #endif /* USE_LOCALE_COLLATE */
595 #ifdef USE_LOCALE_NUMERIC
596     if (! (curnum = setlocale(LC_NUMERIC, "")))
597         setlocale_failure = TRUE;
598 #endif /* USE_LOCALE_NUMERIC */
599
600 #endif /* LC_ALL */
601
602     if (setlocale_failure) {
603         char *p;
604         bool locwarn = (printwarn > 1 || 
605                         printwarn &&
606                         (!(p = getenv("PERL_BADLANG")) || atoi(p)));
607
608         if (locwarn) {
609 #ifdef LC_ALL
610   
611             PerlIO_printf(PerlIO_stderr(),
612                "perl: warning: Setting locale failed.\n");
613
614 #else /* !LC_ALL */
615   
616             PerlIO_printf(PerlIO_stderr(),
617                "perl: warning: Setting locale failed for the categories:\n\t");
618 #ifdef USE_LOCALE_CTYPE
619             if (! curctype)
620                 PerlIO_printf(PerlIO_stderr(), "LC_CTYPE ");
621 #endif /* USE_LOCALE_CTYPE */
622 #ifdef USE_LOCALE_COLLATE
623             if (! curcoll)
624                 PerlIO_printf(PerlIO_stderr(), "LC_COLLATE ");
625 #endif /* USE_LOCALE_COLLATE */
626 #ifdef USE_LOCALE_NUMERIC
627             if (! curnum)
628                 PerlIO_printf(PerlIO_stderr(), "LC_NUMERIC ");
629 #endif /* USE_LOCALE_NUMERIC */
630             PerlIO_printf(PerlIO_stderr(), "\n");
631
632 #endif /* LC_ALL */
633
634             PerlIO_printf(PerlIO_stderr(),
635                 "perl: warning: Please check that your locale settings:\n");
636
637 #ifdef LC_ALL
638             PerlIO_printf(PerlIO_stderr(),
639                           "\tLC_ALL = %c%s%c,\n",
640                           lc_all ? '"' : '(',
641                           lc_all ? lc_all : "unset",
642                           lc_all ? '"' : ')');
643 #endif /* LC_ALL */
644
645             {
646               char **e;
647               for (e = environ; *e; e++) {
648                   if (strnEQ(*e, "LC_", 3)
649                         && strnNE(*e, "LC_ALL=", 7)
650                         && (p = strchr(*e, '=')))
651                       PerlIO_printf(PerlIO_stderr(), "\t%.*s = \"%s\",\n",
652                                     (p - *e), *e, p + 1);
653               }
654             }
655
656             PerlIO_printf(PerlIO_stderr(),
657                           "\tLANG = %c%s%c\n",
658                           lang ? '"' : '(',
659                           lang ? lang : "unset",
660                           lang ? '"' : ')');
661
662             PerlIO_printf(PerlIO_stderr(),
663                           "    are supported and installed on your system.\n");
664         }
665
666 #ifdef LC_ALL
667
668         if (setlocale(LC_ALL, "C")) {
669             if (locwarn)
670                 PerlIO_printf(PerlIO_stderr(),
671       "perl: warning: Falling back to the standard locale (\"C\").\n");
672             ok = 0;
673         }
674         else {
675             if (locwarn)
676                 PerlIO_printf(PerlIO_stderr(),
677       "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
678             ok = -1;
679         }
680
681 #else /* ! LC_ALL */
682
683         if (0
684 #ifdef USE_LOCALE_CTYPE
685             || !(curctype || setlocale(LC_CTYPE, "C"))
686 #endif /* USE_LOCALE_CTYPE */
687 #ifdef USE_LOCALE_COLLATE
688             || !(curcoll || setlocale(LC_COLLATE, "C"))
689 #endif /* USE_LOCALE_COLLATE */
690 #ifdef USE_LOCALE_NUMERIC
691             || !(curnum || setlocale(LC_NUMERIC, "C"))
692 #endif /* USE_LOCALE_NUMERIC */
693             )
694         {
695             if (locwarn)
696                 PerlIO_printf(PerlIO_stderr(),
697       "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
698             ok = -1;
699         }
700
701 #endif /* ! LC_ALL */
702
703 #ifdef USE_LOCALE_CTYPE
704         curctype = setlocale(LC_CTYPE, Nullch);
705 #endif /* USE_LOCALE_CTYPE */
706 #ifdef USE_LOCALE_COLLATE
707         curcoll = setlocale(LC_COLLATE, Nullch);
708 #endif /* USE_LOCALE_COLLATE */
709 #ifdef USE_LOCALE_NUMERIC
710         curnum = setlocale(LC_NUMERIC, Nullch);
711 #endif /* USE_LOCALE_NUMERIC */
712     }
713
714 #ifdef USE_LOCALE_CTYPE
715     perl_new_ctype(curctype);
716 #endif /* USE_LOCALE_CTYPE */
717
718 #ifdef USE_LOCALE_COLLATE
719     perl_new_collate(curcoll);
720 #endif /* USE_LOCALE_COLLATE */
721
722 #ifdef USE_LOCALE_NUMERIC
723     perl_new_numeric(curnum);
724 #endif /* USE_LOCALE_NUMERIC */
725
726 #endif /* USE_LOCALE */
727
728     return ok;
729 }
730
731 /* Backwards compatibility. */
732 int
733 perl_init_i18nl14n(printwarn)   
734     int printwarn;
735 {
736     return perl_init_i18nl10n(printwarn);
737 }
738
739 #ifdef USE_LOCALE_COLLATE
740
741 /*
742  * mem_collxfrm() is a bit like strxfrm() but with two important
743  * differences. First, it handles embedded NULs. Second, it allocates
744  * a bit more memory than needed for the transformed data itself.
745  * The real transformed data begins at offset sizeof(collationix).
746  * Please see sv_collxfrm() to see how this is used.
747  */
748 char *
749 mem_collxfrm(s, len, xlen)
750      const char *s;
751      STRLEN len;
752      STRLEN *xlen;
753 {
754     char *xbuf;
755     STRLEN xalloc, xin, xout;
756
757     /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
758     /* the +1 is for the terminating NUL. */
759
760     xalloc = sizeof(collation_ix) + collxfrm_base + (collxfrm_mult * len) + 1;
761     New(171, xbuf, xalloc, char);
762     if (! xbuf)
763         goto bad;
764
765     *(U32*)xbuf = collation_ix;
766     xout = sizeof(collation_ix);
767     for (xin = 0; xin < len; ) {
768         SSize_t xused;
769
770         for (;;) {
771             xused = strxfrm(xbuf + xout, s + xin, xalloc - xout);
772             if (xused == -1)
773                 goto bad;
774             if (xused < xalloc - xout)
775                 break;
776             xalloc = (2 * xalloc) + 1;
777             Renew(xbuf, xalloc, char);
778             if (! xbuf)
779                 goto bad;
780         }
781
782         xin += strlen(s + xin) + 1;
783         xout += xused;
784
785         /* Embedded NULs are understood but silently skipped
786          * because they make no sense in locale collation. */
787     }
788
789     xbuf[xout] = '\0';
790     *xlen = xout - sizeof(collation_ix);
791     return xbuf;
792
793   bad:
794     Safefree(xbuf);
795     *xlen = 0;
796     return NULL;
797 }
798
799 #endif /* USE_LOCALE_COLLATE */
800
801 void
802 fbm_compile(sv)
803 SV *sv;
804 {
805     register unsigned char *s;
806     register unsigned char *table;
807     register U32 i;
808     register U32 len = SvCUR(sv);
809     I32 rarest = 0;
810     U32 frequency = 256;
811
812     if (len > 255)
813         return;                 /* can't have offsets that big */
814     Sv_Grow(sv,len+258);
815     table = (unsigned char*)(SvPVX(sv) + len + 1);
816     s = table - 2;
817     for (i = 0; i < 256; i++) {
818         table[i] = len;
819     }
820     i = 0;
821     while (s >= (unsigned char*)(SvPVX(sv)))
822     {
823         if (table[*s] == len)
824             table[*s] = i;
825         s--,i++;
826     }
827     sv_upgrade(sv, SVt_PVBM);
828     sv_magic(sv, Nullsv, 'B', Nullch, 0);       /* deep magic */
829     SvVALID_on(sv);
830
831     s = (unsigned char*)(SvPVX(sv));            /* deeper magic */
832     for (i = 0; i < len; i++) {
833         if (freq[s[i]] < frequency) {
834             rarest = i;
835             frequency = freq[s[i]];
836         }
837     }
838     BmRARE(sv) = s[rarest];
839     BmPREVIOUS(sv) = rarest;
840     DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",BmRARE(sv),BmPREVIOUS(sv)));
841 }
842
843 char *
844 fbm_instr(big, bigend, littlestr)
845 unsigned char *big;
846 register unsigned char *bigend;
847 SV *littlestr;
848 {
849     register unsigned char *s;
850     register I32 tmp;
851     register I32 littlelen;
852     register unsigned char *little;
853     register unsigned char *table;
854     register unsigned char *olds;
855     register unsigned char *oldlittle;
856
857     if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
858         STRLEN len;
859         char *l = SvPV(littlestr,len);
860         if (!len)
861             return (char*)big;
862         return ninstr((char*)big,(char*)bigend, l, l + len);
863     }
864
865     littlelen = SvCUR(littlestr);
866     if (SvTAIL(littlestr) && !multiline) {      /* tail anchored? */
867         if (littlelen > bigend - big)
868             return Nullch;
869         little = (unsigned char*)SvPVX(littlestr);
870         s = bigend - littlelen;
871         if (*s == *little && memEQ((char*)s,(char*)little,littlelen))
872             return (char*)s;            /* how sweet it is */
873         else if (bigend[-1] == '\n' && little[littlelen-1] != '\n'
874                  && s > big) {
875             s--;
876             if (*s == *little && memEQ((char*)s,(char*)little,littlelen))
877                 return (char*)s;
878         }
879         return Nullch;
880     }
881     table = (unsigned char*)(SvPVX(littlestr) + littlelen + 1);
882     if (--littlelen >= bigend - big)
883         return Nullch;
884     s = big + littlelen;
885     oldlittle = little = table - 2;
886     if (s < bigend) {
887       top2:
888         /*SUPPRESS 560*/
889         if (tmp = table[*s]) {
890 #ifdef POINTERRIGOR
891             if (bigend - s > tmp) {
892                 s += tmp;
893                 goto top2;
894             }
895 #else
896             if ((s += tmp) < bigend)
897                 goto top2;
898 #endif
899             return Nullch;
900         }
901         else {
902             tmp = littlelen;    /* less expensive than calling strncmp() */
903             olds = s;
904             while (tmp--) {
905                 if (*--s == *--little)
906                     continue;
907                 s = olds + 1;   /* here we pay the price for failure */
908                 little = oldlittle;
909                 if (s < bigend) /* fake up continue to outer loop */
910                     goto top2;
911                 return Nullch;
912             }
913             return (char *)s;
914         }
915     }
916     return Nullch;
917 }
918
919 char *
920 screaminstr(bigstr, littlestr)
921 SV *bigstr;
922 SV *littlestr;
923 {
924     register unsigned char *s, *x;
925     register unsigned char *big;
926     register I32 pos;
927     register I32 previous;
928     register I32 first;
929     register unsigned char *little;
930     register unsigned char *bigend;
931     register unsigned char *littleend;
932
933     if ((pos = screamfirst[BmRARE(littlestr)]) < 0) 
934         return Nullch;
935     little = (unsigned char *)(SvPVX(littlestr));
936     littleend = little + SvCUR(littlestr);
937     first = *little++;
938     previous = BmPREVIOUS(littlestr);
939     big = (unsigned char *)(SvPVX(bigstr));
940     bigend = big + SvCUR(bigstr);
941     while (pos < previous) {
942         if (!(pos += screamnext[pos]))
943             return Nullch;
944     }
945 #ifdef POINTERRIGOR
946     do {
947         if (big[pos-previous] != first)
948             continue;
949         for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
950             if (x >= bigend)
951                 return Nullch;
952             if (*s++ != *x++) {
953                 s--;
954                 break;
955             }
956         }
957         if (s == littleend)
958             return (char *)(big+pos-previous);
959     } while ( pos += screamnext[pos] );
960 #else /* !POINTERRIGOR */
961     big -= previous;
962     do {
963         if (big[pos] != first)
964             continue;
965         for (x=big+pos+1,s=little; s < littleend; /**/ ) {
966             if (x >= bigend)
967                 return Nullch;
968             if (*s++ != *x++) {
969                 s--;
970                 break;
971             }
972         }
973         if (s == littleend)
974             return (char *)(big+pos);
975     } while ( pos += screamnext[pos] );
976 #endif /* POINTERRIGOR */
977     return Nullch;
978 }
979
980 I32
981 ibcmp(s1, s2, len)
982 char *s1, *s2;
983 register I32 len;
984 {
985     register U8 *a = (U8 *)s1;
986     register U8 *b = (U8 *)s2;
987     while (len--) {
988         if (*a != *b && *a != fold[*b])
989             return 1;
990         a++,b++;
991     }
992     return 0;
993 }
994
995 I32
996 ibcmp_locale(s1, s2, len)
997 char *s1, *s2;
998 register I32 len;
999 {
1000     register U8 *a = (U8 *)s1;
1001     register U8 *b = (U8 *)s2;
1002     while (len--) {
1003         if (*a != *b && *a != fold_locale[*b])
1004             return 1;
1005         a++,b++;
1006     }
1007     return 0;
1008 }
1009
1010 /* copy a string to a safe spot */
1011
1012 char *
1013 savepv(sv)
1014 char *sv;
1015 {
1016     register char *newaddr;
1017
1018     New(902,newaddr,strlen(sv)+1,char);
1019     (void)strcpy(newaddr,sv);
1020     return newaddr;
1021 }
1022
1023 /* same thing but with a known length */
1024
1025 char *
1026 savepvn(sv, len)
1027 char *sv;
1028 register I32 len;
1029 {
1030     register char *newaddr;
1031
1032     New(903,newaddr,len+1,char);
1033     Copy(sv,newaddr,len,char);          /* might not be null terminated */
1034     newaddr[len] = '\0';                /* is now */
1035     return newaddr;
1036 }
1037
1038 #ifdef I_STDARG
1039 char *
1040 mess(char *pat, va_list *args)
1041 #else
1042 /*VARARGS0*/
1043 char *
1044 mess(pat, args)
1045     char *pat;
1046     va_list *args;
1047 #endif
1048 {
1049     char *s;
1050     char *s_start;
1051     SV *tmpstr;
1052     I32 usermess;
1053 #ifndef HAS_VPRINTF
1054 #ifdef USE_CHAR_VSPRINTF
1055     char *vsprintf();
1056 #else
1057     I32 vsprintf();
1058 #endif
1059 #endif
1060
1061     s = s_start = buf;
1062     usermess = strEQ(pat, "%s");
1063     if (usermess) {
1064         tmpstr = sv_newmortal();
1065         sv_setpv(tmpstr, va_arg(*args, char *));
1066         *s++ = SvPVX(tmpstr)[SvCUR(tmpstr)-1];
1067     }
1068     else {
1069         (void) vsprintf(s,pat,*args);
1070         s += strlen(s);
1071     }
1072     va_end(*args);
1073
1074     if (!(s > s_start && s[-1] == '\n')) {
1075         if (dirty)
1076             strcpy(s, " during global destruction.\n");
1077         else {
1078             if (curcop->cop_line) {
1079                 (void)sprintf(s," at %s line %ld",
1080                   SvPVX(GvSV(curcop->cop_filegv)), (long)curcop->cop_line);
1081                 s += strlen(s);
1082             }
1083             if (GvIO(last_in_gv) && IoLINES(GvIOp(last_in_gv))) {
1084                 bool line_mode = (RsSIMPLE(rs) &&
1085                                   SvLEN(rs) == 1 && *SvPVX(rs) == '\n');
1086                 (void)sprintf(s,", <%s> %s %ld",
1087                   last_in_gv == argvgv ? "" : GvNAME(last_in_gv),
1088                   line_mode ? "line" : "chunk", 
1089                   (long)IoLINES(GvIOp(last_in_gv)));
1090                 s += strlen(s);
1091             }
1092             (void)strcpy(s,".\n");
1093             s += 2;
1094         }
1095         if (usermess)
1096             sv_catpv(tmpstr,buf+1);
1097     }
1098
1099     if (s - s_start >= sizeof(buf)) {   /* Ooops! */
1100         if (usermess)
1101             PerlIO_puts(PerlIO_stderr(), SvPVX(tmpstr));
1102         else
1103             PerlIO_puts(PerlIO_stderr(), buf);
1104         PerlIO_puts(PerlIO_stderr(), "panic: message overflow - memory corrupted!\n");
1105         my_exit(1);
1106     }
1107     if (usermess)
1108         return SvPVX(tmpstr);
1109     else
1110         return buf;
1111 }
1112
1113 #ifdef I_STDARG
1114 OP *
1115 die(char* pat, ...)
1116 #else
1117 /*VARARGS0*/
1118 OP *
1119 die(pat, va_alist)
1120     char *pat;
1121     va_dcl
1122 #endif
1123 {
1124     va_list args;
1125     char *message;
1126     int oldrunlevel = runlevel;
1127     int was_in_eval = in_eval;
1128     HV *stash;
1129     GV *gv;
1130     CV *cv;
1131
1132     /* We have to switch back to mainstack or die_where may try to pop
1133      * the eval block from the wrong stack if die is being called from a
1134      * signal handler.  - dkindred@cs.cmu.edu */
1135     if (curstack != mainstack) {
1136         dSP;
1137         SWITCHSTACK(curstack, mainstack);
1138     }
1139
1140 #ifdef I_STDARG
1141     va_start(args, pat);
1142 #else
1143     va_start(args);
1144 #endif
1145     message = mess(pat, &args);
1146     va_end(args);
1147
1148     if (diehook && (cv = sv_2cv(diehook, &stash, &gv, 0)) && !CvDEPTH(cv)) {
1149         dSP;
1150         SV *msg = sv_2mortal(newSVpv(message, 0));
1151
1152         PUSHMARK(sp);
1153         EXTEND(sp, 1);
1154         PUSHs(msg);
1155         PUTBACK;
1156         perl_call_sv((SV*)cv, G_DISCARD);
1157
1158         /* It's okay for the __DIE__ hook to modify the message. */
1159         message = SvPV(msg, na);
1160     }
1161
1162     restartop = die_where(message);
1163     if ((!restartop && was_in_eval) || oldrunlevel > 1)
1164         Siglongjmp(top_env, 3);
1165     return restartop;
1166 }
1167
1168 #ifdef I_STDARG
1169 void
1170 croak(char* pat, ...)
1171 #else
1172 /*VARARGS0*/
1173 void
1174 croak(pat, va_alist)
1175     char *pat;
1176     va_dcl
1177 #endif
1178 {
1179     va_list args;
1180     char *message;
1181     HV *stash;
1182     GV *gv;
1183     CV *cv;
1184
1185 #ifdef I_STDARG
1186     va_start(args, pat);
1187 #else
1188     va_start(args);
1189 #endif
1190     message = mess(pat, &args);
1191     va_end(args);
1192     if (diehook) {
1193         SV *olddiehook = diehook;
1194         diehook = Nullsv;                 /* sv_2cv might call croak() */
1195         cv = sv_2cv(olddiehook, &stash, &gv, 0);
1196         diehook = olddiehook;
1197         if (cv && !CvDEPTH(cv)) {
1198             dSP;
1199             SV *msg = sv_2mortal(newSVpv(message, 0));
1200
1201             PUSHMARK(sp);
1202             EXTEND(sp, 1);
1203             PUSHs(msg);
1204             PUTBACK;
1205             perl_call_sv((SV*)cv, G_DISCARD);
1206
1207             /* It's okay for the __DIE__ hook to modify the message. */
1208             message = SvPV(msg, na);
1209         }
1210     }
1211     if (in_eval) {
1212         restartop = die_where(message);
1213         Siglongjmp(top_env, 3);
1214     }
1215     PerlIO_puts(PerlIO_stderr(),message);
1216     (void)PerlIO_flush(PerlIO_stderr());
1217     if (e_tmpname) {
1218         if (e_fp) {
1219             PerlIO_close(e_fp);
1220             e_fp = Nullfp;
1221         }
1222         (void)UNLINK(e_tmpname);
1223         Safefree(e_tmpname);
1224         e_tmpname = Nullch;
1225     }
1226     statusvalue = SHIFTSTATUS(statusvalue);
1227 #ifdef VMS
1228     my_exit((U32)(vaxc$errno?vaxc$errno:(statusvalue?statusvalue:44)));
1229 #else
1230     my_exit((U32)((errno&255)?errno:((statusvalue&255)?statusvalue:255)));
1231 #endif
1232 }
1233
1234 void
1235 #ifdef I_STDARG
1236 warn(char* pat,...)
1237 #else
1238 /*VARARGS0*/
1239 warn(pat,va_alist)
1240     char *pat;
1241     va_dcl
1242 #endif
1243 {
1244     va_list args;
1245     char *message;
1246     HV *stash;
1247     GV *gv;
1248     CV *cv;
1249
1250 #ifdef I_STDARG
1251     va_start(args, pat);
1252 #else
1253     va_start(args);
1254 #endif
1255     message = mess(pat, &args);
1256     va_end(args);
1257
1258     if (warnhook) {
1259         SV *oldwarnhook = warnhook;
1260         warnhook = Nullsv;      /* sv_2cv might end up calling warn() */
1261         cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1262         warnhook = oldwarnhook;
1263         if (cv && !CvDEPTH(cv)) {
1264             dSP;
1265
1266             PUSHMARK(sp);
1267             EXTEND(sp, 1);
1268             PUSHs(sv_2mortal(newSVpv(message,0)));
1269             PUTBACK;
1270             perl_call_sv((SV*)cv, G_DISCARD);
1271             return;
1272         }
1273     }
1274     PerlIO_puts(PerlIO_stderr(),message);
1275 #ifdef LEAKTEST
1276     DEBUG_L(xstat());
1277 #endif
1278     (void)PerlIO_flush(PerlIO_stderr());
1279 }
1280
1281 #ifndef VMS  /* VMS' my_setenv() is in VMS.c */
1282 void
1283 my_setenv(nam,val)
1284 char *nam, *val;
1285 {
1286     register I32 i=setenv_getix(nam);           /* where does it go? */
1287
1288     if (environ == origenviron) {       /* need we copy environment? */
1289         I32 j;
1290         I32 max;
1291         char **tmpenv;
1292
1293         /*SUPPRESS 530*/
1294         for (max = i; environ[max]; max++) ;
1295         New(901,tmpenv, max+2, char*);
1296         for (j=0; j<max; j++)           /* copy environment */
1297             tmpenv[j] = savepv(environ[j]);
1298         tmpenv[max] = Nullch;
1299         environ = tmpenv;               /* tell exec where it is now */
1300     }
1301     if (!val) {
1302         while (environ[i]) {
1303             environ[i] = environ[i+1];
1304             i++;
1305         }
1306         return;
1307     }
1308     if (!environ[i]) {                  /* does not exist yet */
1309         Renew(environ, i+2, char*);     /* just expand it a bit */
1310         environ[i+1] = Nullch;  /* make sure it's null terminated */
1311     }
1312     else
1313         Safefree(environ[i]);
1314     New(904, environ[i], strlen(nam) + strlen(val) + 2, char);
1315 #ifndef MSDOS
1316     (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
1317 #else
1318     /* MS-DOS requires environment variable names to be in uppercase */
1319     /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
1320      * some utilities and applications may break because they only look
1321      * for upper case strings. (Fixed strupr() bug here.)]
1322      */
1323     strcpy(environ[i],nam); strupr(environ[i]);
1324     (void)sprintf(environ[i] + strlen(nam),"=%s",val);
1325 #endif /* MSDOS */
1326 }
1327
1328 I32
1329 setenv_getix(nam)
1330 char *nam;
1331 {
1332     register I32 i, len = strlen(nam);
1333
1334     for (i = 0; environ[i]; i++) {
1335         if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1336             break;                      /* strnEQ must come first to avoid */
1337     }                                   /* potential SEGV's */
1338     return i;
1339 }
1340 #endif /* !VMS */
1341
1342 #ifdef UNLINK_ALL_VERSIONS
1343 I32
1344 unlnk(f)        /* unlink all versions of a file */
1345 char *f;
1346 {
1347     I32 i;
1348
1349     for (i = 0; unlink(f) >= 0; i++) ;
1350     return i ? 0 : -1;
1351 }
1352 #endif
1353
1354 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
1355 char *
1356 my_bcopy(from,to,len)
1357 register char *from;
1358 register char *to;
1359 register I32 len;
1360 {
1361     char *retval = to;
1362
1363     if (from - to >= 0) {
1364         while (len--)
1365             *to++ = *from++;
1366     }
1367     else {
1368         to += len;
1369         from += len;
1370         while (len--)
1371             *(--to) = *(--from);
1372     }
1373     return retval;
1374 }
1375 #endif
1376
1377 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1378 char *
1379 my_bzero(loc,len)
1380 register char *loc;
1381 register I32 len;
1382 {
1383     char *retval = loc;
1384
1385     while (len--)
1386         *loc++ = 0;
1387     return retval;
1388 }
1389 #endif
1390
1391 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1392 I32
1393 my_memcmp(s1,s2,len)
1394 char *s1;
1395 char *s2;
1396 register I32 len;
1397 {
1398     register U8 *a = (U8 *)s1;
1399     register U8 *b = (U8 *)s2;
1400     register I32 tmp;
1401
1402     while (len--) {
1403         if (tmp = *a++ - *b++)
1404             return tmp;
1405     }
1406     return 0;
1407 }
1408 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1409
1410 #if defined(I_STDARG) || defined(I_VARARGS)
1411 #ifndef HAS_VPRINTF
1412
1413 #ifdef USE_CHAR_VSPRINTF
1414 char *
1415 #else
1416 int
1417 #endif
1418 vsprintf(dest, pat, args)
1419 char *dest, *pat, *args;
1420 {
1421     FILE fakebuf;
1422
1423     fakebuf._ptr = dest;
1424     fakebuf._cnt = 32767;
1425 #ifndef _IOSTRG
1426 #define _IOSTRG 0
1427 #endif
1428     fakebuf._flag = _IOWRT|_IOSTRG;
1429     _doprnt(pat, args, &fakebuf);       /* what a kludge */
1430     (void)putc('\0', &fakebuf);
1431 #ifdef USE_CHAR_VSPRINTF
1432     return(dest);
1433 #else
1434     return 0;           /* perl doesn't use return value */
1435 #endif
1436 }
1437
1438 #endif /* HAS_VPRINTF */
1439 #endif /* I_VARARGS || I_STDARGS */
1440
1441 #ifdef MYSWAP
1442 #if BYTEORDER != 0x4321
1443 short
1444 #ifndef CAN_PROTOTYPE
1445 my_swap(s)
1446 short s;
1447 #else
1448 my_swap(short s)
1449 #endif
1450 {
1451 #if (BYTEORDER & 1) == 0
1452     short result;
1453
1454     result = ((s & 255) << 8) + ((s >> 8) & 255);
1455     return result;
1456 #else
1457     return s;
1458 #endif
1459 }
1460
1461 long
1462 #ifndef CAN_PROTOTYPE
1463 my_htonl(l)
1464 register long l;
1465 #else
1466 my_htonl(long l)
1467 #endif
1468 {
1469     union {
1470         long result;
1471         char c[sizeof(long)];
1472     } u;
1473
1474 #if BYTEORDER == 0x1234
1475     u.c[0] = (l >> 24) & 255;
1476     u.c[1] = (l >> 16) & 255;
1477     u.c[2] = (l >> 8) & 255;
1478     u.c[3] = l & 255;
1479     return u.result;
1480 #else
1481 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1482     croak("Unknown BYTEORDER\n");
1483 #else
1484     register I32 o;
1485     register I32 s;
1486
1487     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1488         u.c[o & 0xf] = (l >> s) & 255;
1489     }
1490     return u.result;
1491 #endif
1492 #endif
1493 }
1494
1495 long
1496 #ifndef CAN_PROTOTYPE
1497 my_ntohl(l)
1498 register long l;
1499 #else
1500 my_ntohl(long l)
1501 #endif
1502 {
1503     union {
1504         long l;
1505         char c[sizeof(long)];
1506     } u;
1507
1508 #if BYTEORDER == 0x1234
1509     u.c[0] = (l >> 24) & 255;
1510     u.c[1] = (l >> 16) & 255;
1511     u.c[2] = (l >> 8) & 255;
1512     u.c[3] = l & 255;
1513     return u.l;
1514 #else
1515 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1516     croak("Unknown BYTEORDER\n");
1517 #else
1518     register I32 o;
1519     register I32 s;
1520
1521     u.l = l;
1522     l = 0;
1523     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1524         l |= (u.c[o & 0xf] & 255) << s;
1525     }
1526     return l;
1527 #endif
1528 #endif
1529 }
1530
1531 #endif /* BYTEORDER != 0x4321 */
1532 #endif /* MYSWAP */
1533
1534 /*
1535  * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1536  * If these functions are defined,
1537  * the BYTEORDER is neither 0x1234 nor 0x4321.
1538  * However, this is not assumed.
1539  * -DWS
1540  */
1541
1542 #define HTOV(name,type)                                         \
1543         type                                                    \
1544         name (n)                                                \
1545         register type n;                                        \
1546         {                                                       \
1547             union {                                             \
1548                 type value;                                     \
1549                 char c[sizeof(type)];                           \
1550             } u;                                                \
1551             register I32 i;                                     \
1552             register I32 s;                                     \
1553             for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) {  \
1554                 u.c[i] = (n >> s) & 0xFF;                       \
1555             }                                                   \
1556             return u.value;                                     \
1557         }
1558
1559 #define VTOH(name,type)                                         \
1560         type                                                    \
1561         name (n)                                                \
1562         register type n;                                        \
1563         {                                                       \
1564             union {                                             \
1565                 type value;                                     \
1566                 char c[sizeof(type)];                           \
1567             } u;                                                \
1568             register I32 i;                                     \
1569             register I32 s;                                     \
1570             u.value = n;                                        \
1571             n = 0;                                              \
1572             for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) {  \
1573                 n += (u.c[i] & 0xFF) << s;                      \
1574             }                                                   \
1575             return n;                                           \
1576         }
1577
1578 #if defined(HAS_HTOVS) && !defined(htovs)
1579 HTOV(htovs,short)
1580 #endif
1581 #if defined(HAS_HTOVL) && !defined(htovl)
1582 HTOV(htovl,long)
1583 #endif
1584 #if defined(HAS_VTOHS) && !defined(vtohs)
1585 VTOH(vtohs,short)
1586 #endif
1587 #if defined(HAS_VTOHL) && !defined(vtohl)
1588 VTOH(vtohl,long)
1589 #endif
1590
1591     /* VMS' my_popen() is in VMS.c, same with OS/2. */
1592 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS)
1593 PerlIO *
1594 my_popen(cmd,mode)
1595 char    *cmd;
1596 char    *mode;
1597 {
1598     int p[2];
1599     register I32 this, that;
1600     register I32 pid;
1601     SV *sv;
1602     I32 doexec =
1603 #ifdef AMIGAOS
1604         1;
1605 #else
1606         strNE(cmd,"-");
1607 #endif
1608
1609 #ifdef OS2
1610     if (doexec) {
1611         return my_syspopen(cmd,mode);
1612     }
1613 #endif 
1614     if (pipe(p) < 0)
1615         return Nullfp;
1616     this = (*mode == 'w');
1617     that = !this;
1618     if (doexec && tainting) {
1619         taint_env();
1620         taint_proper("Insecure %s%s", "EXEC");
1621     }
1622     while ((pid = (doexec?vfork():fork())) < 0) {
1623         if (errno != EAGAIN) {
1624             close(p[this]);
1625             if (!doexec)
1626                 croak("Can't fork");
1627             return Nullfp;
1628         }
1629         sleep(5);
1630     }
1631     if (pid == 0) {
1632         GV* tmpgv;
1633
1634 #define THIS that
1635 #define THAT this
1636         close(p[THAT]);
1637         if (p[THIS] != (*mode == 'r')) {
1638             dup2(p[THIS], *mode == 'r');
1639             close(p[THIS]);
1640         }
1641         if (doexec) {
1642 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1643             int fd;
1644
1645 #ifndef NOFILE
1646 #define NOFILE 20
1647 #endif
1648             for (fd = maxsysfd + 1; fd < NOFILE; fd++)
1649                 close(fd);
1650 #endif
1651             do_exec(cmd);       /* may or may not use the shell */
1652             _exit(1);
1653         }
1654         /*SUPPRESS 560*/
1655         if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
1656             sv_setiv(GvSV(tmpgv),(I32)getpid());
1657         forkprocess = 0;
1658         hv_clear(pidstatus);    /* we have no children */
1659         return Nullfp;
1660 #undef THIS
1661 #undef THAT
1662     }
1663     do_execfree();      /* free any memory malloced by child on vfork */
1664     close(p[that]);
1665     if (p[that] < p[this]) {
1666         dup2(p[this], p[that]);
1667         close(p[this]);
1668         p[this] = p[that];
1669     }
1670     sv = *av_fetch(fdpid,p[this],TRUE);
1671     (void)SvUPGRADE(sv,SVt_IV);
1672     SvIVX(sv) = pid;
1673     forkprocess = pid;
1674     return PerlIO_fdopen(p[this], mode);
1675 }
1676 #else
1677 #if defined(atarist) || defined(DJGPP)
1678 FILE *popen();
1679 PerlIO *
1680 my_popen(cmd,mode)
1681 char    *cmd;
1682 char    *mode;
1683 {
1684     /* Needs work for PerlIO ! */
1685     /* used 0 for 2nd parameter to PerlIO-exportFILE; apparently not used */
1686     return popen(PerlIO_exportFILE(cmd, 0), mode);
1687 }
1688 #endif
1689
1690 #endif /* !DOSISH */
1691
1692 #ifdef DUMP_FDS
1693 dump_fds(s)
1694 char *s;
1695 {
1696     int fd;
1697     struct stat tmpstatbuf;
1698
1699     PerlIO_printf(PerlIO_stderr(),"%s", s);
1700     for (fd = 0; fd < 32; fd++) {
1701         if (Fstat(fd,&tmpstatbuf) >= 0)
1702             PerlIO_printf(PerlIO_stderr()," %d",fd);
1703     }
1704     PerlIO_printf(PerlIO_stderr(),"\n");
1705 }
1706 #endif
1707
1708 #ifndef HAS_DUP2
1709 int
1710 dup2(oldfd,newfd)
1711 int oldfd;
1712 int newfd;
1713 {
1714 #if defined(HAS_FCNTL) && defined(F_DUPFD)
1715     if (oldfd == newfd)
1716         return oldfd;
1717     close(newfd);
1718     return fcntl(oldfd, F_DUPFD, newfd);
1719 #else
1720     int fdtmp[256];
1721     I32 fdx = 0;
1722     int fd;
1723
1724     if (oldfd == newfd)
1725         return oldfd;
1726     close(newfd);
1727     while ((fd = dup(oldfd)) != newfd && fd >= 0) /* good enough for low fd's */
1728         fdtmp[fdx++] = fd;
1729     while (fdx > 0)
1730         close(fdtmp[--fdx]);
1731     return fd;
1732 #endif
1733 }
1734 #endif
1735
1736
1737 #ifdef HAS_SIGACTION
1738
1739 Sighandler_t
1740 rsignal(signo, handler)
1741 int signo;
1742 Sighandler_t handler;
1743 {
1744     struct sigaction act, oact;
1745
1746     act.sa_handler = handler;
1747     sigemptyset(&act.sa_mask);
1748     act.sa_flags = 0;
1749 #ifdef SA_RESTART
1750     act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
1751 #endif
1752     if (sigaction(signo, &act, &oact) == -1)
1753         return SIG_ERR;
1754     else
1755         return oact.sa_handler;
1756 }
1757
1758 Sighandler_t
1759 rsignal_state(signo)
1760 int signo;
1761 {
1762     struct sigaction oact;
1763
1764     if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
1765         return SIG_ERR;
1766     else
1767         return oact.sa_handler;
1768 }
1769
1770 int
1771 rsignal_save(signo, handler, save)
1772 int signo;
1773 Sighandler_t handler;
1774 Sigsave_t *save;
1775 {
1776     struct sigaction act;
1777
1778     act.sa_handler = handler;
1779     sigemptyset(&act.sa_mask);
1780     act.sa_flags = 0;
1781 #ifdef SA_RESTART
1782     act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
1783 #endif
1784     return sigaction(signo, &act, save);
1785 }
1786
1787 int
1788 rsignal_restore(signo, save)
1789 int signo;
1790 Sigsave_t *save;
1791 {
1792     return sigaction(signo, save, (struct sigaction *)NULL);
1793 }
1794
1795 #else /* !HAS_SIGACTION */
1796
1797 Sighandler_t
1798 rsignal(signo, handler)
1799 int signo;
1800 Sighandler_t handler;
1801 {
1802     return signal(signo, handler);
1803 }
1804
1805 static int sig_trapped;
1806
1807 static
1808 Signal_t
1809 sig_trap(signo)
1810 int signo;
1811 {
1812     sig_trapped++;
1813 }
1814
1815 Sighandler_t
1816 rsignal_state(signo)
1817 int signo;
1818 {
1819     Sighandler_t oldsig;
1820
1821     sig_trapped = 0;
1822     oldsig = signal(signo, sig_trap);
1823     signal(signo, oldsig);
1824     if (sig_trapped)
1825         kill(getpid(), signo);
1826     return oldsig;
1827 }
1828
1829 int
1830 rsignal_save(signo, handler, save)
1831 int signo;
1832 Sighandler_t handler;
1833 Sigsave_t *save;
1834 {
1835     *save = signal(signo, handler);
1836     return (*save == SIG_ERR) ? -1 : 0;
1837 }
1838
1839 int
1840 rsignal_restore(signo, save)
1841 int signo;
1842 Sigsave_t *save;
1843 {
1844     return (signal(signo, *save) == SIG_ERR) ? -1 : 0;
1845 }
1846
1847 #endif /* !HAS_SIGACTION */
1848
1849     /* VMS' my_pclose() is in VMS.c; same with OS/2 */
1850 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS)
1851 I32
1852 my_pclose(ptr)
1853 PerlIO *ptr;
1854 {
1855     Sigsave_t hstat, istat, qstat;
1856     int status;
1857     SV **svp;
1858     int pid;
1859
1860     svp = av_fetch(fdpid,PerlIO_fileno(ptr),TRUE);
1861     pid = (int)SvIVX(*svp);
1862     SvREFCNT_dec(*svp);
1863     *svp = &sv_undef;
1864 #ifdef OS2
1865     if (pid == -1) {                    /* Opened by popen. */
1866         return my_syspclose(ptr);
1867     }
1868 #endif 
1869     PerlIO_close(ptr);
1870 #ifdef UTS
1871     if(kill(pid, 0) < 0) { return(pid); }   /* HOM 12/23/91 */
1872 #endif
1873     rsignal_save(SIGHUP, SIG_IGN, &hstat);
1874     rsignal_save(SIGINT, SIG_IGN, &istat);
1875     rsignal_save(SIGQUIT, SIG_IGN, &qstat);
1876     do {
1877         pid = wait4pid(pid, &status, 0);
1878     } while (pid == -1 && errno == EINTR);
1879     rsignal_restore(SIGHUP, &hstat);
1880     rsignal_restore(SIGINT, &istat);
1881     rsignal_restore(SIGQUIT, &qstat);
1882     return(pid < 0 ? pid : status);
1883 }
1884 #endif /* !DOSISH */
1885
1886 #if  !defined(DOSISH) || defined(OS2)
1887 I32
1888 wait4pid(pid,statusp,flags)
1889 int pid;
1890 int *statusp;
1891 int flags;
1892 {
1893     SV *sv;
1894     SV** svp;
1895     char spid[16];
1896
1897     if (!pid)
1898         return -1;
1899     if (pid > 0) {
1900         sprintf(spid, "%d", pid);
1901         svp = hv_fetch(pidstatus,spid,strlen(spid),FALSE);
1902         if (svp && *svp != &sv_undef) {
1903             *statusp = SvIVX(*svp);
1904             (void)hv_delete(pidstatus,spid,strlen(spid),G_DISCARD);
1905             return pid;
1906         }
1907     }
1908     else {
1909         HE *entry;
1910
1911         hv_iterinit(pidstatus);
1912         if (entry = hv_iternext(pidstatus)) {
1913             pid = atoi(hv_iterkey(entry,(I32*)statusp));
1914             sv = hv_iterval(pidstatus,entry);
1915             *statusp = SvIVX(sv);
1916             sprintf(spid, "%d", pid);
1917             (void)hv_delete(pidstatus,spid,strlen(spid),G_DISCARD);
1918             return pid;
1919         }
1920     }
1921 #ifdef HAS_WAITPID
1922     return waitpid(pid,statusp,flags);
1923 #else
1924 #ifdef HAS_WAIT4
1925     return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
1926 #else
1927     {
1928         I32 result;
1929         if (flags)
1930             croak("Can't do waitpid with flags");
1931         else {
1932             while ((result = wait(statusp)) != pid && pid > 0 && result >= 0)
1933                 pidgone(result,*statusp);
1934             if (result < 0)
1935                 *statusp = -1;
1936         }
1937         return result;
1938     }
1939 #endif
1940 #endif
1941 }
1942 #endif /* !DOSISH */
1943
1944 void
1945 /*SUPPRESS 590*/
1946 pidgone(pid,status)
1947 int pid;
1948 int status;
1949 {
1950     register SV *sv;
1951     char spid[16];
1952
1953     sprintf(spid, "%d", pid);
1954     sv = *hv_fetch(pidstatus,spid,strlen(spid),TRUE);
1955     (void)SvUPGRADE(sv,SVt_IV);
1956     SvIVX(sv) = status;
1957     return;
1958 }
1959
1960 #if defined(atarist) || defined(OS2) || defined(DJGPP)
1961 int pclose();
1962 #ifdef HAS_FORK
1963 int                                     /* Cannot prototype with I32
1964                                            in os2ish.h. */
1965 my_syspclose(ptr)
1966 #else
1967 I32
1968 my_pclose(ptr)
1969 #endif 
1970 PerlIO *ptr;
1971 {
1972     /* Needs work for PerlIO ! */
1973     FILE *f = PerlIO_findFILE(ptr);
1974     I32 result = pclose(f);
1975     PerlIO_releaseFILE(ptr,f);
1976     return result;
1977 }
1978 #endif
1979
1980 void
1981 repeatcpy(to,from,len,count)
1982 register char *to;
1983 register char *from;
1984 I32 len;
1985 register I32 count;
1986 {
1987     register I32 todo;
1988     register char *frombase = from;
1989
1990     if (len == 1) {
1991         todo = *from;
1992         while (count-- > 0)
1993             *to++ = todo;
1994         return;
1995     }
1996     while (count-- > 0) {
1997         for (todo = len; todo > 0; todo--) {
1998             *to++ = *from++;
1999         }
2000         from = frombase;
2001     }
2002 }
2003
2004 #ifndef CASTNEGFLOAT
2005 U32
2006 cast_ulong(f)
2007 double f;
2008 {
2009     long along;
2010
2011 #if CASTFLAGS & 2
2012 #   define BIGDOUBLE 2147483648.0
2013     if (f >= BIGDOUBLE)
2014         return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
2015 #endif
2016     if (f >= 0.0)
2017         return (unsigned long)f;
2018     along = (long)f;
2019     return (unsigned long)along;
2020 }
2021 # undef BIGDOUBLE
2022 #endif
2023
2024 #ifndef CASTI32
2025
2026 /* Unfortunately, on some systems the cast_uv() function doesn't
2027    work with the system-supplied definition of ULONG_MAX.  The
2028    comparison  (f >= ULONG_MAX) always comes out true.  It must be a
2029    problem with the compiler constant folding.
2030
2031    In any case, this workaround should be fine on any two's complement
2032    system.  If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
2033    ccflags.
2034                --Andy Dougherty      <doughera@lafcol.lafayette.edu>
2035 */
2036
2037 /* Code modified to prefer proper named type ranges, I32, IV, or UV, instead
2038    of LONG_(MIN/MAX).
2039                            -- Kenneth Albanowski <kjahds@kjahds.com>
2040 */                                      
2041
2042 #ifndef MY_UV_MAX
2043 #  define MY_UV_MAX ((UV)IV_MAX * (UV)2 + (UV)1)
2044 #endif
2045
2046 I32
2047 cast_i32(f)
2048 double f;
2049 {
2050     if (f >= I32_MAX)
2051         return (I32) I32_MAX;
2052     if (f <= I32_MIN)
2053         return (I32) I32_MIN;
2054     return (I32) f;
2055 }
2056
2057 IV
2058 cast_iv(f)
2059 double f;
2060 {
2061     if (f >= IV_MAX)
2062         return (IV) IV_MAX;
2063     if (f <= IV_MIN)
2064         return (IV) IV_MIN;
2065     return (IV) f;
2066 }
2067
2068 UV
2069 cast_uv(f)
2070 double f;
2071 {
2072     if (f >= MY_UV_MAX)
2073         return (UV) MY_UV_MAX;
2074     return (UV) f;
2075 }
2076
2077 #endif
2078
2079 #ifndef HAS_RENAME
2080 I32
2081 same_dirent(a,b)
2082 char *a;
2083 char *b;
2084 {
2085     char *fa = strrchr(a,'/');
2086     char *fb = strrchr(b,'/');
2087     struct stat tmpstatbuf1;
2088     struct stat tmpstatbuf2;
2089 #ifndef MAXPATHLEN
2090 #define MAXPATHLEN 1024
2091 #endif
2092     char tmpbuf[MAXPATHLEN+1];
2093
2094     if (fa)
2095         fa++;
2096     else
2097         fa = a;
2098     if (fb)
2099         fb++;
2100     else
2101         fb = b;
2102     if (strNE(a,b))
2103         return FALSE;
2104     if (fa == a)
2105         strcpy(tmpbuf,".");
2106     else
2107         strncpy(tmpbuf, a, fa - a);
2108     if (Stat(tmpbuf, &tmpstatbuf1) < 0)
2109         return FALSE;
2110     if (fb == b)
2111         strcpy(tmpbuf,".");
2112     else
2113         strncpy(tmpbuf, b, fb - b);
2114     if (Stat(tmpbuf, &tmpstatbuf2) < 0)
2115         return FALSE;
2116     return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2117            tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2118 }
2119 #endif /* !HAS_RENAME */
2120
2121 UV
2122 scan_oct(start, len, retlen)
2123 char *start;
2124 I32 len;
2125 I32 *retlen;
2126 {
2127     register char *s = start;
2128     register UV retval = 0;
2129     bool overflowed = FALSE;
2130
2131     while (len && *s >= '0' && *s <= '7') {
2132         register UV n = retval << 3;
2133         if (!overflowed && (n >> 3) != retval) {
2134             warn("Integer overflow in octal number");
2135             overflowed = TRUE;
2136         }
2137         retval = n | (*s++ - '0');
2138         len--;
2139     }
2140     if (dowarn && len && (*s == '8' || *s == '9'))
2141         warn("Illegal octal digit ignored");
2142     *retlen = s - start;
2143     return retval;
2144 }
2145
2146 unsigned long
2147 scan_hex(start, len, retlen)
2148 char *start;
2149 I32 len;
2150 I32 *retlen;
2151 {
2152     register char *s = start;
2153     register UV retval = 0;
2154     bool overflowed = FALSE;
2155     char *tmp;
2156
2157     while (len-- && *s && (tmp = strchr(hexdigit, *s))) {
2158         register UV n = retval << 4;
2159         if (!overflowed && (n >> 4) != retval) {
2160             warn("Integer overflow in hex number");
2161             overflowed = TRUE;
2162         }
2163         retval = n | (tmp - hexdigit) & 15;
2164         s++;
2165     }
2166     *retlen = s - start;
2167     return retval;
2168 }
2169
2170
2171 #ifdef HUGE_VAL
2172 /*
2173  * This hack is to force load of "huge" support from libm.a
2174  * So it is in perl for (say) POSIX to use. 
2175  * Needed for SunOS with Sun's 'acc' for example.
2176  */
2177 double 
2178 Perl_huge()
2179 {
2180  return HUGE_VAL;
2181 }
2182 #endif