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