This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
8ce3d325e1d4b1596913c5371445113d2867fbab
[perl5.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 /* Omit this -- it causes too much grief on mixed systems.
23 #ifdef I_UNISTD
24 #  include <unistd.h>
25 #endif
26 */
27
28 #ifdef I_VFORK
29 #  include <vfork.h>
30 #endif
31
32 #ifdef I_LIMITS  /* Needed for cast_xxx() functions below. */
33 #  include <limits.h>
34 #endif
35
36 /* Put this after #includes because fork and vfork prototypes may
37    conflict.
38 */
39 #ifndef HAS_VFORK
40 #   define vfork fork
41 #endif
42
43 #ifdef I_FCNTL
44 #  include <fcntl.h>
45 #endif
46 #ifdef I_SYS_FILE
47 #  include <sys/file.h>
48 #endif
49
50 #define FLUSH
51
52 #ifdef LEAKTEST
53 static void xstat _((void));
54 #endif
55
56 #ifndef safemalloc
57
58 /* paranoid version of malloc */
59
60 /* NOTE:  Do not call the next three routines directly.  Use the macros
61  * in handy.h, so that we can easily redefine everything to do tracking of
62  * allocated hunks back to the original New to track down any memory leaks.
63  */
64
65 char *
66 safemalloc(size)
67 #ifdef MSDOS
68 unsigned long size;
69 #else
70 MEM_SIZE size;
71 #endif /* MSDOS */
72 {
73     char  *ptr;
74 #ifdef MSDOS
75         if (size > 0xffff) {
76                 fprintf(stderr, "Allocation too large: %lx\n", size) FLUSH;
77                 my_exit(1);
78         }
79 #endif /* MSDOS */
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(fprintf(stderr,"0x%x: (%05d) malloc %ld bytes\n",ptr,an++,(long)size));
87 #else
88     DEBUG_m(fprintf(stderr,"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         fputs(no_mem,stderr) FLUSH;
96         my_exit(1);
97     }
98     /*NOTREACHED*/
99 }
100
101 /* paranoid version of realloc */
102
103 char *
104 saferealloc(where,size)
105 char *where;
106 #ifndef MSDOS
107 MEM_SIZE size;
108 #else
109 unsigned long size;
110 #endif /* MSDOS */
111 {
112     char *ptr;
113 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE)
114     char *realloc();
115 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
116
117 #ifdef MSDOS
118         if (size > 0xffff) {
119                 fprintf(stderr, "Reallocation too large: %lx\n", size) FLUSH;
120                 my_exit(1);
121         }
122 #endif /* MSDOS */
123     if (!where)
124         croak("Null realloc");
125 #ifdef DEBUGGING
126     if ((long)size < 0)
127         croak("panic: realloc");
128 #endif
129     ptr = realloc(where,size?size:1);   /* realloc(0) is NASTY on our system */
130
131 #if !(defined(I286) || defined(atarist))
132     DEBUG_m( {
133         fprintf(stderr,"0x%x: (%05d) rfree\n",where,an++);
134         fprintf(stderr,"0x%x: (%05d) realloc %ld bytes\n",ptr,an++,(long)size);
135     } )
136 #else
137     DEBUG_m( {
138         fprintf(stderr,"0x%lx: (%05d) rfree\n",where,an++);
139         fprintf(stderr,"0x%lx: (%05d) realloc %ld bytes\n",ptr,an++,(long)size);
140     } )
141 #endif
142
143     if (ptr != Nullch)
144         return ptr;
145     else if (nomemok)
146         return Nullch;
147     else {
148         fputs(no_mem,stderr) FLUSH;
149         my_exit(1);
150     }
151     /*NOTREACHED*/
152 }
153
154 /* safe version of free */
155
156 void
157 safefree(where)
158 char *where;
159 {
160 #if !(defined(I286) || defined(atarist))
161     DEBUG_m( fprintf(stderr,"0x%x: (%05d) free\n",where,an++));
162 #else
163     DEBUG_m( fprintf(stderr,"0x%lx: (%05d) free\n",where,an++));
164 #endif
165     if (where) {
166         /*SUPPRESS 701*/
167         free(where);
168     }
169 }
170
171 #endif /* !safemalloc */
172
173 #ifdef LEAKTEST
174
175 #define ALIGN sizeof(long)
176
177 char *
178 safexmalloc(x,size)
179 I32 x;
180 MEM_SIZE size;
181 {
182     register char *where;
183
184     where = safemalloc(size + ALIGN);
185     xcount[x]++;
186     where[0] = x % 100;
187     where[1] = x / 100;
188     return where + ALIGN;
189 }
190
191 char *
192 safexrealloc(where,size)
193 char *where;
194 MEM_SIZE size;
195 {
196     register char *new = saferealloc(where - ALIGN, size + ALIGN);
197     return new + ALIGN;
198 }
199
200 void
201 safexfree(where)
202 char *where;
203 {
204     I32 x;
205
206     if (!where)
207         return;
208     where -= ALIGN;
209     x = where[0] + 100 * where[1];
210     xcount[x]--;
211     safefree(where);
212 }
213
214 static void
215 xstat()
216 {
217     register I32 i;
218
219     for (i = 0; i < MAXXCOUNT; i++) {
220         if (xcount[i] > lastxcount[i]) {
221             fprintf(stderr,"%2d %2d\t%ld\n", i / 100, i % 100, xcount[i]);
222             lastxcount[i] = xcount[i];
223         }
224     }
225 }
226
227 #endif /* LEAKTEST */
228
229 /* copy a string up to some (non-backslashed) delimiter, if any */
230
231 char *
232 cpytill(to,from,fromend,delim,retlen)
233 register char *to;
234 register char *from;
235 register char *fromend;
236 register int delim;
237 I32 *retlen;
238 {
239     char *origto = to;
240
241     for (; from < fromend; from++,to++) {
242         if (*from == '\\') {
243             if (from[1] == delim)
244                 from++;
245             else if (from[1] == '\\')
246                 *to++ = *from++;
247         }
248         else if (*from == delim)
249             break;
250         *to = *from;
251     }
252     *to = '\0';
253     *retlen = to - origto;
254     return from;
255 }
256
257 /* return ptr to little string in big string, NULL if not found */
258 /* This routine was donated by Corey Satten. */
259
260 char *
261 instr(big, little)
262 register char *big;
263 register char *little;
264 {
265     register char *s, *x;
266     register I32 first;
267
268     if (!little)
269         return big;
270     first = *little++;
271     if (!first)
272         return big;
273     while (*big) {
274         if (*big++ != first)
275             continue;
276         for (x=big,s=little; *s; /**/ ) {
277             if (!*x)
278                 return Nullch;
279             if (*s++ != *x++) {
280                 s--;
281                 break;
282             }
283         }
284         if (!*s)
285             return big-1;
286     }
287     return Nullch;
288 }
289
290 /* same as instr but allow embedded nulls */
291
292 char *
293 ninstr(big, bigend, little, lend)
294 register char *big;
295 register char *bigend;
296 char *little;
297 char *lend;
298 {
299     register char *s, *x;
300     register I32 first = *little;
301     register char *littleend = lend;
302
303     if (!first && little >= littleend)
304         return big;
305     if (bigend - big < littleend - little)
306         return Nullch;
307     bigend -= littleend - little++;
308     while (big <= bigend) {
309         if (*big++ != first)
310             continue;
311         for (x=big,s=little; s < littleend; /**/ ) {
312             if (*s++ != *x++) {
313                 s--;
314                 break;
315             }
316         }
317         if (s >= littleend)
318             return big-1;
319     }
320     return Nullch;
321 }
322
323 /* reverse of the above--find last substring */
324
325 char *
326 rninstr(big, bigend, little, lend)
327 register char *big;
328 char *bigend;
329 char *little;
330 char *lend;
331 {
332     register char *bigbeg;
333     register char *s, *x;
334     register I32 first = *little;
335     register char *littleend = lend;
336
337     if (!first && little >= littleend)
338         return bigend;
339     bigbeg = big;
340     big = bigend - (littleend - little++);
341     while (big >= bigbeg) {
342         if (*big-- != first)
343             continue;
344         for (x=big+2,s=little; s < littleend; /**/ ) {
345             if (*s++ != *x++) {
346                 s--;
347                 break;
348             }
349         }
350         if (s >= littleend)
351             return big+1;
352     }
353     return Nullch;
354 }
355
356 /* Initialize locale (and the fold[] array).*/
357 int
358 perl_init_i18nl14n(printwarn)   
359     int printwarn;
360 {
361     int ok = 1;
362     /* returns
363      *    1 = set ok or not applicable,
364      *    0 = fallback to C locale,
365      *   -1 = fallback to C locale failed
366      */
367 #if defined(HAS_SETLOCALE) && defined(LC_CTYPE)
368     char * lang     = getenv("LANG");
369     char * lc_all   = getenv("LC_ALL");
370     char * lc_ctype = getenv("LC_CTYPE");
371     int i;
372
373     if (setlocale(LC_CTYPE, "") == NULL && (lc_all || lc_ctype || lang)) {
374         if (printwarn) {
375             fprintf(stderr, "warning: setlocale(LC_CTYPE, \"\") failed.\n");
376             fprintf(stderr,
377               "warning: LC_ALL = \"%s\", LC_CTYPE = \"%s\", LANG = \"%s\",\n",
378               lc_all   ? lc_all   : "(null)",
379               lc_ctype ? lc_ctype : "(null)",
380               lang     ? lang     : "(null)"
381               );
382             fprintf(stderr, "warning: falling back to the \"C\" locale.\n");
383         }
384         ok = 0;
385         if (setlocale(LC_CTYPE, "C") == NULL)
386             ok = -1;
387     }
388
389     for (i = 0; i < 256; i++) {
390         if (isUPPER(i)) fold[i] = toLOWER(i);
391         else if (isLOWER(i)) fold[i] = toUPPER(i);
392         else fold[i] = i;
393     }
394 #endif
395     return ok;
396 }
397
398 void
399 fbm_compile(sv, iflag)
400 SV *sv;
401 I32 iflag;
402 {
403     register unsigned char *s;
404     register unsigned char *table;
405     register U32 i;
406     register U32 len = SvCUR(sv);
407     I32 rarest = 0;
408     U32 frequency = 256;
409
410     if (len > 255)
411         return;                 /* can't have offsets that big */
412     Sv_Grow(sv,len+258);
413     table = (unsigned char*)(SvPVX(sv) + len + 1);
414     s = table - 2;
415     for (i = 0; i < 256; i++) {
416         table[i] = len;
417     }
418     i = 0;
419     while (s >= (unsigned char*)(SvPVX(sv)))
420     {
421         if (table[*s] == len) {
422 #ifndef pdp11
423             if (iflag)
424                 table[*s] = table[fold[*s]] = i;
425 #else
426             if (iflag) {
427                 I32 j;
428                 j = fold[*s];
429                 table[j] = i;
430                 table[*s] = i;
431             }
432 #endif /* pdp11 */
433             else
434                 table[*s] = i;
435         }
436         s--,i++;
437     }
438     sv_upgrade(sv, SVt_PVBM);
439     sv_magic(sv, Nullsv, 'B', Nullch, 0);                       /* deep magic */
440     SvVALID_on(sv);
441
442     s = (unsigned char*)(SvPVX(sv));            /* deeper magic */
443     if (iflag) {
444         register U32 tmp, foldtmp;
445         SvCASEFOLD_on(sv);
446         for (i = 0; i < len; i++) {
447             tmp=freq[s[i]];
448             foldtmp=freq[fold[s[i]]];
449             if (tmp < frequency && foldtmp < frequency) {
450                 rarest = i;
451                 /* choose most frequent among the two */
452                 frequency = (tmp > foldtmp) ? tmp : foldtmp;
453             }
454         }
455     }
456     else {
457         for (i = 0; i < len; i++) {
458             if (freq[s[i]] < frequency) {
459                 rarest = i;
460                 frequency = freq[s[i]];
461             }
462         }
463     }
464     BmRARE(sv) = s[rarest];
465     BmPREVIOUS(sv) = rarest;
466     DEBUG_r(fprintf(stderr,"rarest char %c at %d\n",BmRARE(sv),BmPREVIOUS(sv)));
467 }
468
469 char *
470 fbm_instr(big, bigend, littlestr)
471 unsigned char *big;
472 register unsigned char *bigend;
473 SV *littlestr;
474 {
475     register unsigned char *s;
476     register I32 tmp;
477     register I32 littlelen;
478     register unsigned char *little;
479     register unsigned char *table;
480     register unsigned char *olds;
481     register unsigned char *oldlittle;
482
483     if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
484         STRLEN len;
485         char *l = SvPV(littlestr,len);
486         if (!len)
487             return (char*)big;
488         return ninstr((char*)big,(char*)bigend, l, l + len);
489     }
490
491     littlelen = SvCUR(littlestr);
492     if (SvTAIL(littlestr) && !multiline) {      /* tail anchored? */
493         if (littlelen > bigend - big)
494             return Nullch;
495         little = (unsigned char*)SvPVX(littlestr);
496         if (SvCASEFOLD(littlestr)) {    /* oops, fake it */
497             big = bigend - littlelen;           /* just start near end */
498             if (bigend[-1] == '\n' && little[littlelen-1] != '\n')
499                 big--;
500         }
501         else {
502             s = bigend - littlelen;
503             if (*s == *little && bcmp((char*)s,(char*)little,littlelen)==0)
504                 return (char*)s;                /* how sweet it is */
505             else if (bigend[-1] == '\n' && little[littlelen-1] != '\n'
506               && s > big) {
507                     s--;
508                 if (*s == *little && bcmp((char*)s,(char*)little,littlelen)==0)
509                     return (char*)s;
510             }
511             return Nullch;
512         }
513     }
514     table = (unsigned char*)(SvPVX(littlestr) + littlelen + 1);
515     if (--littlelen >= bigend - big)
516         return Nullch;
517     s = big + littlelen;
518     oldlittle = little = table - 2;
519     if (SvCASEFOLD(littlestr)) {        /* case insensitive? */
520         if (s < bigend) {
521           top1:
522             /*SUPPRESS 560*/
523             if (tmp = table[*s]) {
524 #ifdef POINTERRIGOR
525                 if (bigend - s > tmp) {
526                     s += tmp;
527                     goto top1;
528                 }
529 #else
530                 if ((s += tmp) < bigend)
531                     goto top1;
532 #endif
533                 return Nullch;
534             }
535             else {
536                 tmp = littlelen;        /* less expensive than calling strncmp() */
537                 olds = s;
538                 while (tmp--) {
539                     if (*--s == *--little || fold[*s] == *little)
540                         continue;
541                     s = olds + 1;       /* here we pay the price for failure */
542                     little = oldlittle;
543                     if (s < bigend)     /* fake up continue to outer loop */
544                         goto top1;
545                     return Nullch;
546                 }
547                 return (char *)s;
548             }
549         }
550     }
551     else {
552         if (s < bigend) {
553           top2:
554             /*SUPPRESS 560*/
555             if (tmp = table[*s]) {
556 #ifdef POINTERRIGOR
557                 if (bigend - s > tmp) {
558                     s += tmp;
559                     goto top2;
560                 }
561 #else
562                 if ((s += tmp) < bigend)
563                     goto top2;
564 #endif
565                 return Nullch;
566             }
567             else {
568                 tmp = littlelen;        /* less expensive than calling strncmp() */
569                 olds = s;
570                 while (tmp--) {
571                     if (*--s == *--little)
572                         continue;
573                     s = olds + 1;       /* here we pay the price for failure */
574                     little = oldlittle;
575                     if (s < bigend)     /* fake up continue to outer loop */
576                         goto top2;
577                     return Nullch;
578                 }
579                 return (char *)s;
580             }
581         }
582     }
583     return Nullch;
584 }
585
586 char *
587 screaminstr(bigstr, littlestr)
588 SV *bigstr;
589 SV *littlestr;
590 {
591     register unsigned char *s, *x;
592     register unsigned char *big;
593     register I32 pos;
594     register I32 previous;
595     register I32 first;
596     register unsigned char *little;
597     register unsigned char *bigend;
598     register unsigned char *littleend;
599
600     if ((pos = screamfirst[BmRARE(littlestr)]) < 0) 
601         return Nullch;
602     little = (unsigned char *)(SvPVX(littlestr));
603     littleend = little + SvCUR(littlestr);
604     first = *little++;
605     previous = BmPREVIOUS(littlestr);
606     big = (unsigned char *)(SvPVX(bigstr));
607     bigend = big + SvCUR(bigstr);
608     while (pos < previous) {
609         if (!(pos += screamnext[pos]))
610             return Nullch;
611     }
612 #ifdef POINTERRIGOR
613     if (SvCASEFOLD(littlestr)) {        /* case insignificant? */
614         do {
615             if (big[pos-previous] != first && big[pos-previous] != fold[first])
616                 continue;
617             for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
618                 if (x >= bigend)
619                     return Nullch;
620                 if (*s++ != *x++ && fold[*(s-1)] != *(x-1)) {
621                     s--;
622                     break;
623                 }
624             }
625             if (s == littleend)
626                 return (char *)(big+pos-previous);
627         } while (
628                 pos += screamnext[pos]  /* does this goof up anywhere? */
629             );
630     }
631     else {
632         do {
633             if (big[pos-previous] != first)
634                 continue;
635             for (x=big+pos+1-previous,s=little; s < littleend; /**/ ) {
636                 if (x >= bigend)
637                     return Nullch;
638                 if (*s++ != *x++) {
639                     s--;
640                     break;
641                 }
642             }
643             if (s == littleend)
644                 return (char *)(big+pos-previous);
645         } while ( pos += screamnext[pos] );
646     }
647 #else /* !POINTERRIGOR */
648     big -= previous;
649     if (SvCASEFOLD(littlestr)) {        /* case insignificant? */
650         do {
651             if (big[pos] != first && big[pos] != fold[first])
652                 continue;
653             for (x=big+pos+1,s=little; s < littleend; /**/ ) {
654                 if (x >= bigend)
655                     return Nullch;
656                 if (*s++ != *x++ && fold[*(s-1)] != *(x-1)) {
657                     s--;
658                     break;
659                 }
660             }
661             if (s == littleend)
662                 return (char *)(big+pos);
663         } while (
664                 pos += screamnext[pos]  /* does this goof up anywhere? */
665             );
666     }
667     else {
668         do {
669             if (big[pos] != first)
670                 continue;
671             for (x=big+pos+1,s=little; s < littleend; /**/ ) {
672                 if (x >= bigend)
673                     return Nullch;
674                 if (*s++ != *x++) {
675                     s--;
676                     break;
677                 }
678             }
679             if (s == littleend)
680                 return (char *)(big+pos);
681         } while (
682                 pos += screamnext[pos]
683             );
684     }
685 #endif /* POINTERRIGOR */
686     return Nullch;
687 }
688
689 I32
690 ibcmp(a,b,len)
691 register U8 *a;
692 register U8 *b;
693 register I32 len;
694 {
695     while (len--) {
696         if (*a == *b) {
697             a++,b++;
698             continue;
699         }
700         if (fold[*a++] == *b++)
701             continue;
702         return 1;
703     }
704     return 0;
705 }
706
707 /* copy a string to a safe spot */
708
709 char *
710 savepv(sv)
711 char *sv;
712 {
713     register char *newaddr;
714
715     New(902,newaddr,strlen(sv)+1,char);
716     (void)strcpy(newaddr,sv);
717     return newaddr;
718 }
719
720 /* same thing but with a known length */
721
722 char *
723 savepvn(sv, len)
724 char *sv;
725 register I32 len;
726 {
727     register char *newaddr;
728
729     New(903,newaddr,len+1,char);
730     Copy(sv,newaddr,len,char);          /* might not be null terminated */
731     newaddr[len] = '\0';                /* is now */
732     return newaddr;
733 }
734
735 #if !defined(I_STDARG) && !defined(I_VARARGS)
736
737 /*
738  * Fallback on the old hackers way of doing varargs
739  */
740
741 /*VARARGS1*/
742 char *
743 mess(pat,a1,a2,a3,a4)
744 char *pat;
745 long a1, a2, a3, a4;
746 {
747     char *s;
748     char *s_start;
749     I32 usermess = strEQ(pat,"%s");
750     SV *tmpstr;
751
752     s = s_start = buf;
753     if (usermess) {
754         tmpstr = sv_newmortal();
755         sv_setpv(tmpstr, (char*)a1);
756         *s++ = SvPVX(tmpstr)[SvCUR(tmpstr)-1];
757     }
758     else {
759         (void)sprintf(s,pat,a1,a2,a3,a4);
760         s += strlen(s);
761     }
762
763     if (s[-1] != '\n') {
764         if (dirty)
765             strcpy(s, " during global destruction.\n");
766         else {
767             if (curcop->cop_line) {
768                 (void)sprintf(s," at %s line %ld",
769                   SvPVX(GvSV(curcop->cop_filegv)), (long)curcop->cop_line);
770                 s += strlen(s);
771             }
772             if (GvIO(last_in_gv) &&
773                 IoLINES(GvIOp(last_in_gv)) ) {
774                 (void)sprintf(s,", <%s> %s %ld",
775                   last_in_gv == argvgv ? "" : GvENAME(last_in_gv),
776                   strEQ(rs,"\n") ? "line" : "chunk", 
777                   (long)IoLINES(GvIOp(last_in_gv)));
778                 s += strlen(s);
779             }
780             (void)strcpy(s,".\n");
781             s += 2;
782         }
783         if (usermess)
784             sv_catpv(tmpstr,buf+1);
785     }
786
787     if (s - s_start >= sizeof(buf)) {   /* Ooops! */
788         if (usermess)
789             fputs(SvPVX(tmpstr), stderr);
790         else
791             fputs(buf, stderr);
792         fputs("panic: message overflow - memory corrupted!\n",stderr);
793         my_exit(1);
794     }
795     if (usermess)
796         return SvPVX(tmpstr);
797     else
798         return buf;
799 }
800
801 /*VARARGS1*/
802 void croak(pat,a1,a2,a3,a4)
803 char *pat;
804 long a1, a2, a3, a4;
805 {
806     char *tmps;
807     char *message;
808     HV *stash;
809     GV *gv;
810     CV *cv;
811
812     message = mess(pat,a1,a2,a3,a4);
813     if (diehook && (cv = sv_2cv(diehook, &stash, &gv, 0)) && !CvDEPTH(cv)) {
814         dSP;
815
816         PUSHMARK(sp);
817         EXTEND(sp, 1);
818         PUSHs(sv_2mortal(newSVpv(message,0)));
819         PUTBACK;
820         perl_call_sv((SV*)cv, G_DISCARD);
821     }
822     if (in_eval) {
823         restartop = die_where(message);
824         longjmp(top_env, 3);
825     }
826     fputs(message,stderr);
827     (void)fflush(stderr);
828     if (e_fp) {
829 #ifdef DOSISH
830         fclose(e_fp);
831 #endif
832         (void)UNLINK(e_tmpname);
833     }
834     statusvalue = SHIFTSTATUS(statusvalue);
835 #ifdef VMS
836     my_exit((U32)vaxc$errno?vaxc$errno:errno?errno:statusvalue?statusvalue:SS$_ABORT);
837 #else
838     my_exit((U32)((errno&255)?errno:((statusvalue&255)?statusvalue:255)));
839 #endif
840 }
841
842 /*VARARGS1*/
843 void warn(pat,a1,a2,a3,a4)
844 char *pat;
845 long a1, a2, a3, a4;
846 {
847     char *message;
848     SV *sv;
849     HV *stash;
850     GV *gv;
851     CV *cv;
852
853     message = mess(pat,a1,a2,a3,a4);
854     if (warnhook && (cv = sv_2cv(warnhook, &stash, &gv, 0)) && !CvDEPTH(cv)) {
855         dSP;
856
857         PUSHMARK(sp);
858         EXTEND(sp, 1);
859         PUSHs(sv_2mortal(newSVpv(message,0)));
860         PUTBACK;
861         perl_call_sv((SV*)cv, G_DISCARD);
862     }
863     else {
864         fputs(message,stderr);
865 #ifdef LEAKTEST
866         DEBUG_L(xstat());
867 #endif
868         (void)fflush(stderr);
869     }
870 }
871
872 #else /* !defined(I_STDARG) && !defined(I_VARARGS) */
873
874 #ifdef I_STDARG
875 char *
876 mess(char *pat, va_list *args)
877 #else
878 /*VARARGS0*/
879 char *
880 mess(pat, args)
881     char *pat;
882     va_list *args;
883 #endif
884 {
885     char *s;
886     char *s_start;
887     SV *tmpstr;
888     I32 usermess;
889 #ifndef HAS_VPRINTF
890 #ifdef USE_CHAR_VSPRINTF
891     char *vsprintf();
892 #else
893     I32 vsprintf();
894 #endif
895 #endif
896
897     s = s_start = buf;
898     usermess = strEQ(pat, "%s");
899     if (usermess) {
900         tmpstr = sv_newmortal();
901         sv_setpv(tmpstr, va_arg(*args, char *));
902         *s++ = SvPVX(tmpstr)[SvCUR(tmpstr)-1];
903     }
904     else {
905         (void) vsprintf(s,pat,*args);
906         s += strlen(s);
907     }
908     va_end(*args);
909
910     if (s[-1] != '\n') {
911         if (dirty)
912             strcpy(s, " during global destruction.\n");
913         else {
914             if (curcop->cop_line) {
915                 (void)sprintf(s," at %s line %ld",
916                   SvPVX(GvSV(curcop->cop_filegv)), (long)curcop->cop_line);
917                 s += strlen(s);
918             }
919             if (GvIO(last_in_gv) && IoLINES(GvIOp(last_in_gv))) {
920                 bool line_mode = (RsSIMPLE(rs) &&
921                                   SvLEN(rs) == 1 && *SvPVX(rs) == '\n');
922                 (void)sprintf(s,", <%s> %s %ld",
923                   last_in_gv == argvgv ? "" : GvNAME(last_in_gv),
924                   line_mode ? "line" : "chunk", 
925                   (long)IoLINES(GvIOp(last_in_gv)));
926                 s += strlen(s);
927             }
928             (void)strcpy(s,".\n");
929             s += 2;
930         }
931         if (usermess)
932             sv_catpv(tmpstr,buf+1);
933     }
934
935     if (s - s_start >= sizeof(buf)) {   /* Ooops! */
936         if (usermess)
937             fputs(SvPVX(tmpstr), stderr);
938         else
939             fputs(buf, stderr);
940         fputs("panic: message overflow - memory corrupted!\n",stderr);
941         my_exit(1);
942     }
943     if (usermess)
944         return SvPVX(tmpstr);
945     else
946         return buf;
947 }
948
949 #ifdef I_STDARG
950 void
951 croak(char* pat, ...)
952 #else
953 /*VARARGS0*/
954 void
955 croak(pat, va_alist)
956     char *pat;
957     va_dcl
958 #endif
959 {
960     va_list args;
961     char *message;
962     HV *stash;
963     GV *gv;
964     CV *cv;
965
966 #ifdef I_STDARG
967     va_start(args, pat);
968 #else
969     va_start(args);
970 #endif
971     message = mess(pat, &args);
972     va_end(args);
973     if (diehook && (cv = sv_2cv(diehook, &stash, &gv, 0)) && !CvDEPTH(cv)) {
974         dSP;
975
976         PUSHMARK(sp);
977         EXTEND(sp, 1);
978         PUSHs(sv_2mortal(newSVpv(message,0)));
979         PUTBACK;
980         perl_call_sv((SV*)cv, G_DISCARD);
981     }
982     if (in_eval) {
983         restartop = die_where(message);
984         longjmp(top_env, 3);
985     }
986     fputs(message,stderr);
987     (void)fflush(stderr);
988     if (e_fp) {
989 #ifdef DOSISH
990         fclose(e_fp);
991 #endif
992         (void)UNLINK(e_tmpname);
993     }
994     statusvalue = SHIFTSTATUS(statusvalue);
995 #ifdef VMS
996     my_exit((U32)(vaxc$errno?vaxc$errno:(statusvalue?statusvalue:44)));
997 #else
998     my_exit((U32)((errno&255)?errno:((statusvalue&255)?statusvalue:255)));
999 #endif
1000 }
1001
1002 void
1003 #ifdef I_STDARG
1004 warn(char* pat,...)
1005 #else
1006 /*VARARGS0*/
1007 warn(pat,va_alist)
1008     char *pat;
1009     va_dcl
1010 #endif
1011 {
1012     va_list args;
1013     char *message;
1014     HV *stash;
1015     GV *gv;
1016     CV *cv;
1017
1018 #ifdef I_STDARG
1019     va_start(args, pat);
1020 #else
1021     va_start(args);
1022 #endif
1023     message = mess(pat, &args);
1024     va_end(args);
1025
1026     if (warnhook && (cv = sv_2cv(warnhook, &stash, &gv, 0)) && !CvDEPTH(cv)) {
1027         dSP;
1028
1029         PUSHMARK(sp);
1030         EXTEND(sp, 1);
1031         PUSHs(sv_2mortal(newSVpv(message,0)));
1032         PUTBACK;
1033         perl_call_sv((SV*)cv, G_DISCARD);
1034     }
1035     else {
1036         fputs(message,stderr);
1037 #ifdef LEAKTEST
1038         DEBUG_L(xstat());
1039 #endif
1040         (void)fflush(stderr);
1041     }
1042 }
1043 #endif /* !defined(I_STDARG) && !defined(I_VARARGS) */
1044
1045 #ifndef VMS  /* VMS' my_setenv() is in VMS.c */
1046 void
1047 my_setenv(nam,val)
1048 char *nam, *val;
1049 {
1050     register I32 i=setenv_getix(nam);           /* where does it go? */
1051
1052     if (environ == origenviron) {       /* need we copy environment? */
1053         I32 j;
1054         I32 max;
1055         char **tmpenv;
1056
1057         /*SUPPRESS 530*/
1058         for (max = i; environ[max]; max++) ;
1059         New(901,tmpenv, max+2, char*);
1060         for (j=0; j<max; j++)           /* copy environment */
1061             tmpenv[j] = savepv(environ[j]);
1062         tmpenv[max] = Nullch;
1063         environ = tmpenv;               /* tell exec where it is now */
1064     }
1065     if (!val) {
1066         while (environ[i]) {
1067             environ[i] = environ[i+1];
1068             i++;
1069         }
1070         return;
1071     }
1072     if (!environ[i]) {                  /* does not exist yet */
1073         Renew(environ, i+2, char*);     /* just expand it a bit */
1074         environ[i+1] = Nullch;  /* make sure it's null terminated */
1075     }
1076     else
1077         Safefree(environ[i]);
1078     New(904, environ[i], strlen(nam) + strlen(val) + 2, char);
1079 #ifndef MSDOS
1080     (void)sprintf(environ[i],"%s=%s",nam,val);/* all that work just for this */
1081 #else
1082     /* MS-DOS requires environment variable names to be in uppercase */
1083     /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
1084      * some utilities and applications may break because they only look
1085      * for upper case strings. (Fixed strupr() bug here.)]
1086      */
1087     strcpy(environ[i],nam); strupr(environ[i]);
1088     (void)sprintf(environ[i] + strlen(nam),"=%s",val);
1089 #endif /* MSDOS */
1090 }
1091
1092 I32
1093 setenv_getix(nam)
1094 char *nam;
1095 {
1096     register I32 i, len = strlen(nam);
1097
1098     for (i = 0; environ[i]; i++) {
1099         if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1100             break;                      /* strnEQ must come first to avoid */
1101     }                                   /* potential SEGV's */
1102     return i;
1103 }
1104 #endif /* !VMS */
1105
1106 #ifdef UNLINK_ALL_VERSIONS
1107 I32
1108 unlnk(f)        /* unlink all versions of a file */
1109 char *f;
1110 {
1111     I32 i;
1112
1113     for (i = 0; unlink(f) >= 0; i++) ;
1114     return i ? 0 : -1;
1115 }
1116 #endif
1117
1118 #if !defined(HAS_BCOPY) || !defined(HAS_SAFE_BCOPY)
1119 char *
1120 my_bcopy(from,to,len)
1121 register char *from;
1122 register char *to;
1123 register I32 len;
1124 {
1125     char *retval = to;
1126
1127     if (from - to >= 0) {
1128         while (len--)
1129             *to++ = *from++;
1130     }
1131     else {
1132         to += len;
1133         from += len;
1134         while (len--)
1135             *(--to) = *(--from);
1136     }
1137     return retval;
1138 }
1139 #endif
1140
1141 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1142 char *
1143 my_bzero(loc,len)
1144 register char *loc;
1145 register I32 len;
1146 {
1147     char *retval = loc;
1148
1149     while (len--)
1150         *loc++ = 0;
1151     return retval;
1152 }
1153 #endif
1154
1155 #ifndef HAS_MEMCMP
1156 I32
1157 my_memcmp(s1,s2,len)
1158 register unsigned char *s1;
1159 register unsigned char *s2;
1160 register I32 len;
1161 {
1162     register I32 tmp;
1163
1164     while (len--) {
1165         if (tmp = *s1++ - *s2++)
1166             return tmp;
1167     }
1168     return 0;
1169 }
1170 #endif /* HAS_MEMCMP */
1171
1172 #if defined(I_STDARG) || defined(I_VARARGS)
1173 #ifndef HAS_VPRINTF
1174
1175 #ifdef USE_CHAR_VSPRINTF
1176 char *
1177 #else
1178 int
1179 #endif
1180 vsprintf(dest, pat, args)
1181 char *dest, *pat, *args;
1182 {
1183     FILE fakebuf;
1184
1185     fakebuf._ptr = dest;
1186     fakebuf._cnt = 32767;
1187 #ifndef _IOSTRG
1188 #define _IOSTRG 0
1189 #endif
1190     fakebuf._flag = _IOWRT|_IOSTRG;
1191     _doprnt(pat, args, &fakebuf);       /* what a kludge */
1192     (void)putc('\0', &fakebuf);
1193 #ifdef USE_CHAR_VSPRINTF
1194     return(dest);
1195 #else
1196     return 0;           /* perl doesn't use return value */
1197 #endif
1198 }
1199
1200 int
1201 vfprintf(fd, pat, args)
1202 FILE *fd;
1203 char *pat, *args;
1204 {
1205     _doprnt(pat, args, fd);
1206     return 0;           /* wrong, but perl doesn't use the return value */
1207 }
1208 #endif /* HAS_VPRINTF */
1209 #endif /* I_VARARGS || I_STDARGS */
1210
1211 #ifdef MYSWAP
1212 #if BYTEORDER != 0x4321
1213 short
1214 #ifndef CAN_PROTOTYPE
1215 my_swap(s)
1216 short s;
1217 #else
1218 my_swap(short s)
1219 #endif
1220 {
1221 #if (BYTEORDER & 1) == 0
1222     short result;
1223
1224     result = ((s & 255) << 8) + ((s >> 8) & 255);
1225     return result;
1226 #else
1227     return s;
1228 #endif
1229 }
1230
1231 long
1232 #ifndef CAN_PROTOTYPE
1233 my_htonl(l)
1234 register long l;
1235 #else
1236 my_htonl(long l)
1237 #endif
1238 {
1239     union {
1240         long result;
1241         char c[sizeof(long)];
1242     } u;
1243
1244 #if BYTEORDER == 0x1234
1245     u.c[0] = (l >> 24) & 255;
1246     u.c[1] = (l >> 16) & 255;
1247     u.c[2] = (l >> 8) & 255;
1248     u.c[3] = l & 255;
1249     return u.result;
1250 #else
1251 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1252     croak("Unknown BYTEORDER\n");
1253 #else
1254     register I32 o;
1255     register I32 s;
1256
1257     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1258         u.c[o & 0xf] = (l >> s) & 255;
1259     }
1260     return u.result;
1261 #endif
1262 #endif
1263 }
1264
1265 long
1266 #ifndef CAN_PROTOTYPE
1267 my_ntohl(l)
1268 register long l;
1269 #else
1270 my_ntohl(long l)
1271 #endif
1272 {
1273     union {
1274         long l;
1275         char c[sizeof(long)];
1276     } u;
1277
1278 #if BYTEORDER == 0x1234
1279     u.c[0] = (l >> 24) & 255;
1280     u.c[1] = (l >> 16) & 255;
1281     u.c[2] = (l >> 8) & 255;
1282     u.c[3] = l & 255;
1283     return u.l;
1284 #else
1285 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1286     croak("Unknown BYTEORDER\n");
1287 #else
1288     register I32 o;
1289     register I32 s;
1290
1291     u.l = l;
1292     l = 0;
1293     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1294         l |= (u.c[o & 0xf] & 255) << s;
1295     }
1296     return l;
1297 #endif
1298 #endif
1299 }
1300
1301 #endif /* BYTEORDER != 0x4321 */
1302 #endif /* MYSWAP */
1303
1304 /*
1305  * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1306  * If these functions are defined,
1307  * the BYTEORDER is neither 0x1234 nor 0x4321.
1308  * However, this is not assumed.
1309  * -DWS
1310  */
1311
1312 #define HTOV(name,type)                                         \
1313         type                                                    \
1314         name (n)                                                \
1315         register type n;                                        \
1316         {                                                       \
1317             union {                                             \
1318                 type value;                                     \
1319                 char c[sizeof(type)];                           \
1320             } u;                                                \
1321             register I32 i;                                     \
1322             register I32 s;                                     \
1323             for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) {  \
1324                 u.c[i] = (n >> s) & 0xFF;                       \
1325             }                                                   \
1326             return u.value;                                     \
1327         }
1328
1329 #define VTOH(name,type)                                         \
1330         type                                                    \
1331         name (n)                                                \
1332         register type n;                                        \
1333         {                                                       \
1334             union {                                             \
1335                 type value;                                     \
1336                 char c[sizeof(type)];                           \
1337             } u;                                                \
1338             register I32 i;                                     \
1339             register I32 s;                                     \
1340             u.value = n;                                        \
1341             n = 0;                                              \
1342             for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) {  \
1343                 n += (u.c[i] & 0xFF) << s;                      \
1344             }                                                   \
1345             return n;                                           \
1346         }
1347
1348 #if defined(HAS_HTOVS) && !defined(htovs)
1349 HTOV(htovs,short)
1350 #endif
1351 #if defined(HAS_HTOVL) && !defined(htovl)
1352 HTOV(htovl,long)
1353 #endif
1354 #if defined(HAS_VTOHS) && !defined(vtohs)
1355 VTOH(vtohs,short)
1356 #endif
1357 #if defined(HAS_VTOHL) && !defined(vtohl)
1358 VTOH(vtohl,long)
1359 #endif
1360
1361 #if  !defined(DOSISH) && !defined(VMS)  /* VMS' my_popen() is in
1362                                            VMS.c, same with OS/2. */
1363 FILE *
1364 my_popen(cmd,mode)
1365 char    *cmd;
1366 char    *mode;
1367 {
1368     int p[2];
1369     register I32 this, that;
1370     register I32 pid;
1371     SV *sv;
1372     I32 doexec = strNE(cmd,"-");
1373
1374     if (pipe(p) < 0)
1375         return Nullfp;
1376     this = (*mode == 'w');
1377     that = !this;
1378     if (tainting) {
1379         if (doexec) {
1380             taint_env();
1381             taint_proper("Insecure %s%s", "EXEC");
1382         }
1383     }
1384     while ((pid = (doexec?vfork():fork())) < 0) {
1385         if (errno != EAGAIN) {
1386             close(p[this]);
1387             if (!doexec)
1388                 croak("Can't fork");
1389             return Nullfp;
1390         }
1391         sleep(5);
1392     }
1393     if (pid == 0) {
1394         GV* tmpgv;
1395
1396 #define THIS that
1397 #define THAT this
1398         close(p[THAT]);
1399         if (p[THIS] != (*mode == 'r')) {
1400             dup2(p[THIS], *mode == 'r');
1401             close(p[THIS]);
1402         }
1403         if (doexec) {
1404 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1405             int fd;
1406
1407 #ifndef NOFILE
1408 #define NOFILE 20
1409 #endif
1410             for (fd = maxsysfd + 1; fd < NOFILE; fd++)
1411                 close(fd);
1412 #endif
1413             do_exec(cmd);       /* may or may not use the shell */
1414             _exit(1);
1415         }
1416         /*SUPPRESS 560*/
1417         if (tmpgv = gv_fetchpv("$",TRUE, SVt_PV))
1418             sv_setiv(GvSV(tmpgv),(I32)getpid());
1419         forkprocess = 0;
1420         hv_clear(pidstatus);    /* we have no children */
1421         return Nullfp;
1422 #undef THIS
1423 #undef THAT
1424     }
1425     do_execfree();      /* free any memory malloced by child on vfork */
1426     close(p[that]);
1427     if (p[that] < p[this]) {
1428         dup2(p[this], p[that]);
1429         close(p[this]);
1430         p[this] = p[that];
1431     }
1432     sv = *av_fetch(fdpid,p[this],TRUE);
1433     (void)SvUPGRADE(sv,SVt_IV);
1434     SvIVX(sv) = pid;
1435     forkprocess = pid;
1436     return fdopen(p[this], mode);
1437 }
1438 #else
1439 #if defined(atarist)
1440 FILE *popen();
1441 FILE *
1442 my_popen(cmd,mode)
1443 char    *cmd;
1444 char    *mode;
1445 {
1446     return popen(cmd, mode);
1447 }
1448 #endif
1449
1450 #endif /* !DOSISH */
1451
1452 #ifdef DUMP_FDS
1453 dump_fds(s)
1454 char *s;
1455 {
1456     int fd;
1457     struct stat tmpstatbuf;
1458
1459     fprintf(stderr,"%s", s);
1460     for (fd = 0; fd < 32; fd++) {
1461         if (Fstat(fd,&tmpstatbuf) >= 0)
1462             fprintf(stderr," %d",fd);
1463     }
1464     fprintf(stderr,"\n");
1465 }
1466 #endif
1467
1468 #ifndef HAS_DUP2
1469 int
1470 dup2(oldfd,newfd)
1471 int oldfd;
1472 int newfd;
1473 {
1474 #if defined(HAS_FCNTL) && defined(F_DUPFD)
1475     if (oldfd == newfd)
1476         return oldfd;
1477     close(newfd);
1478     return fcntl(oldfd, F_DUPFD, newfd);
1479 #else
1480     int fdtmp[256];
1481     I32 fdx = 0;
1482     int fd;
1483
1484     if (oldfd == newfd)
1485         return oldfd;
1486     close(newfd);
1487     while ((fd = dup(oldfd)) != newfd && fd >= 0) /* good enough for low fd's */
1488         fdtmp[fdx++] = fd;
1489     while (fdx > 0)
1490         close(fdtmp[--fdx]);
1491     return fd;
1492 #endif
1493 }
1494 #endif
1495
1496 #if  !defined(DOSISH) && !defined(VMS)  /* VMS' my_popen() is in VMS.c */
1497 I32
1498 my_pclose(ptr)
1499 FILE *ptr;
1500 {
1501     Signal_t (*hstat)(), (*istat)(), (*qstat)();
1502     int status;
1503     SV **svp;
1504     int pid;
1505
1506     svp = av_fetch(fdpid,fileno(ptr),TRUE);
1507     pid = (int)SvIVX(*svp);
1508     SvREFCNT_dec(*svp);
1509     *svp = &sv_undef;
1510     fclose(ptr);
1511 #ifdef UTS
1512     if(kill(pid, 0) < 0) { return(pid); }   /* HOM 12/23/91 */
1513 #endif
1514     hstat = signal(SIGHUP, SIG_IGN);
1515     istat = signal(SIGINT, SIG_IGN);
1516     qstat = signal(SIGQUIT, SIG_IGN);
1517     do {
1518         pid = wait4pid(pid, &status, 0);
1519     } while (pid == -1 && errno == EINTR);
1520     signal(SIGHUP, hstat);
1521     signal(SIGINT, istat);
1522     signal(SIGQUIT, qstat);
1523     return(pid < 0 ? pid : status);
1524 }
1525 #endif /* !DOSISH */
1526
1527 #if  !defined(DOSISH) || defined(OS2)
1528 I32
1529 wait4pid(pid,statusp,flags)
1530 int pid;
1531 int *statusp;
1532 int flags;
1533 {
1534     SV *sv;
1535     SV** svp;
1536     char spid[16];
1537
1538     if (!pid)
1539         return -1;
1540     if (pid > 0) {
1541         sprintf(spid, "%d", pid);
1542         svp = hv_fetch(pidstatus,spid,strlen(spid),FALSE);
1543         if (svp && *svp != &sv_undef) {
1544             *statusp = SvIVX(*svp);
1545             (void)hv_delete(pidstatus,spid,strlen(spid),G_DISCARD);
1546             return pid;
1547         }
1548     }
1549     else {
1550         HE *entry;
1551
1552         hv_iterinit(pidstatus);
1553         if (entry = hv_iternext(pidstatus)) {
1554             pid = atoi(hv_iterkey(entry,(I32*)statusp));
1555             sv = hv_iterval(pidstatus,entry);
1556             *statusp = SvIVX(sv);
1557             sprintf(spid, "%d", pid);
1558             (void)hv_delete(pidstatus,spid,strlen(spid),G_DISCARD);
1559             return pid;
1560         }
1561     }
1562 #ifdef HAS_WAITPID
1563     return waitpid(pid,statusp,flags);
1564 #else
1565 #ifdef HAS_WAIT4
1566     return wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
1567 #else
1568     {
1569         I32 result;
1570         if (flags)
1571             croak("Can't do waitpid with flags");
1572         else {
1573             while ((result = wait(statusp)) != pid && pid > 0 && result >= 0)
1574                 pidgone(result,*statusp);
1575             if (result < 0)
1576                 *statusp = -1;
1577         }
1578         return result;
1579     }
1580 #endif
1581 #endif
1582 }
1583 #endif /* !DOSISH */
1584
1585 void
1586 /*SUPPRESS 590*/
1587 pidgone(pid,status)
1588 int pid;
1589 int status;
1590 {
1591     register SV *sv;
1592     char spid[16];
1593
1594     sprintf(spid, "%d", pid);
1595     sv = *hv_fetch(pidstatus,spid,strlen(spid),TRUE);
1596     (void)SvUPGRADE(sv,SVt_IV);
1597     SvIVX(sv) = status;
1598     return;
1599 }
1600
1601 #if defined(atarist) || defined(OS2)
1602 int pclose();
1603 I32
1604 my_pclose(ptr)
1605 FILE *ptr;
1606 {
1607     return pclose(ptr);
1608 }
1609 #endif
1610
1611 void
1612 repeatcpy(to,from,len,count)
1613 register char *to;
1614 register char *from;
1615 I32 len;
1616 register I32 count;
1617 {
1618     register I32 todo;
1619     register char *frombase = from;
1620
1621     if (len == 1) {
1622         todo = *from;
1623         while (count-- > 0)
1624             *to++ = todo;
1625         return;
1626     }
1627     while (count-- > 0) {
1628         for (todo = len; todo > 0; todo--) {
1629             *to++ = *from++;
1630         }
1631         from = frombase;
1632     }
1633 }
1634
1635 #ifndef CASTNEGFLOAT
1636 U32
1637 cast_ulong(f)
1638 double f;
1639 {
1640     long along;
1641
1642 #if CASTFLAGS & 2
1643 #   define BIGDOUBLE 2147483648.0
1644     if (f >= BIGDOUBLE)
1645         return (unsigned long)(f-(long)(f/BIGDOUBLE)*BIGDOUBLE)|0x80000000;
1646 #endif
1647     if (f >= 0.0)
1648         return (unsigned long)f;
1649     along = (long)f;
1650     return (unsigned long)along;
1651 }
1652 # undef BIGDOUBLE
1653 #endif
1654
1655 #ifndef CASTI32
1656
1657 /* Look for MAX and MIN integral values.  If we can't find them,
1658    we'll use 32-bit two's complement defaults.
1659 */
1660 #ifndef LONG_MAX
1661 #  ifdef MAXLONG    /* Often used in <values.h> */
1662 #    define LONG_MAX MAXLONG
1663 #  else
1664 #    define LONG_MAX        2147483647L
1665 #  endif
1666 #endif
1667
1668 #ifndef LONG_MIN
1669 #    define LONG_MIN        (-LONG_MAX - 1)
1670 #endif
1671
1672 #ifndef ULONG_MAX
1673 #  ifdef MAXULONG 
1674 #    define LONG_MAX MAXULONG
1675 #  else
1676 #    define ULONG_MAX       4294967295L
1677 #  endif
1678 #endif
1679
1680 /* Unfortunately, on some systems the cast_uv() function doesn't
1681    work with the system-supplied definition of ULONG_MAX.  The
1682    comparison  (f >= ULONG_MAX) always comes out true.  It must be a
1683    problem with the compiler constant folding.
1684
1685    In any case, this workaround should be fine on any two's complement
1686    system.  If it's not, supply a '-DMY_ULONG_MAX=whatever' in your
1687    ccflags.
1688                --Andy Dougherty      <doughera@lafcol.lafayette.edu>
1689 */
1690 #ifndef MY_ULONG_MAX
1691 #  define MY_ULONG_MAX ((UV)LONG_MAX * (UV)2 + (UV)1)
1692 #endif
1693
1694 I32
1695 cast_i32(f)
1696 double f;
1697 {
1698     if (f >= LONG_MAX)
1699         return (I32) LONG_MAX;
1700     if (f <= LONG_MIN)
1701         return (I32) LONG_MIN;
1702     return (I32) f;
1703 }
1704
1705 IV
1706 cast_iv(f)
1707 double f;
1708 {
1709     if (f >= LONG_MAX)
1710         return (IV) LONG_MAX;
1711     if (f <= LONG_MIN)
1712         return (IV) LONG_MIN;
1713     return (IV) f;
1714 }
1715
1716 UV
1717 cast_uv(f)
1718 double f;
1719 {
1720     if (f >= MY_ULONG_MAX)
1721         return (UV) MY_ULONG_MAX;
1722     return (UV) f;
1723 }
1724
1725 #endif
1726
1727 #ifndef HAS_RENAME
1728 I32
1729 same_dirent(a,b)
1730 char *a;
1731 char *b;
1732 {
1733     char *fa = strrchr(a,'/');
1734     char *fb = strrchr(b,'/');
1735     struct stat tmpstatbuf1;
1736     struct stat tmpstatbuf2;
1737 #ifndef MAXPATHLEN
1738 #define MAXPATHLEN 1024
1739 #endif
1740     char tmpbuf[MAXPATHLEN+1];
1741
1742     if (fa)
1743         fa++;
1744     else
1745         fa = a;
1746     if (fb)
1747         fb++;
1748     else
1749         fb = b;
1750     if (strNE(a,b))
1751         return FALSE;
1752     if (fa == a)
1753         strcpy(tmpbuf,".");
1754     else
1755         strncpy(tmpbuf, a, fa - a);
1756     if (Stat(tmpbuf, &tmpstatbuf1) < 0)
1757         return FALSE;
1758     if (fb == b)
1759         strcpy(tmpbuf,".");
1760     else
1761         strncpy(tmpbuf, b, fb - b);
1762     if (Stat(tmpbuf, &tmpstatbuf2) < 0)
1763         return FALSE;
1764     return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
1765            tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
1766 }
1767 #endif /* !HAS_RENAME */
1768
1769 unsigned long
1770 scan_oct(start, len, retlen)
1771 char *start;
1772 I32 len;
1773 I32 *retlen;
1774 {
1775     register char *s = start;
1776     register unsigned long retval = 0;
1777
1778     while (len && *s >= '0' && *s <= '7') {
1779         retval <<= 3;
1780         retval |= *s++ - '0';
1781         len--;
1782     }
1783     if (dowarn && len && (*s == '8' || *s == '9'))
1784         warn("Illegal octal digit ignored");
1785     *retlen = s - start;
1786     return retval;
1787 }
1788
1789 unsigned long
1790 scan_hex(start, len, retlen)
1791 char *start;
1792 I32 len;
1793 I32 *retlen;
1794 {
1795     register char *s = start;
1796     register unsigned long retval = 0;
1797     char *tmp;
1798
1799     while (len-- && *s && (tmp = strchr(hexdigit, *s))) {
1800         retval <<= 4;
1801         retval |= (tmp - hexdigit) & 15;
1802         s++;
1803     }
1804     *retlen = s - start;
1805     return retval;
1806 }