This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Integrate:
[perl5.git] / util.c
1 /*    util.c
2  *
3  *    Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4  *    2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  * "Very useful, no doubt, that was to Saruman; yet it seems that he was
13  * not content."  --Gandalf
14  */
15
16 /* This file contains assorted utility routines.
17  * Which is a polite way of saying any stuff that people couldn't think of
18  * a better place for. Amongst other things, it includes the warning and
19  * dieing stuff, plus wrappers for malloc code.
20  */
21
22 #include "EXTERN.h"
23 #define PERL_IN_UTIL_C
24 #include "perl.h"
25
26 #ifndef PERL_MICRO
27 #include <signal.h>
28 #ifndef SIG_ERR
29 # define SIG_ERR ((Sighandler_t) -1)
30 #endif
31 #endif
32
33 #ifdef __Lynx__
34 /* Missing protos on LynxOS */
35 int putenv(char *);
36 #endif
37
38 #ifdef I_SYS_WAIT
39 #  include <sys/wait.h>
40 #endif
41
42 #ifdef HAS_SELECT
43 # ifdef I_SYS_SELECT
44 #  include <sys/select.h>
45 # endif
46 #endif
47
48 #define FLUSH
49
50 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
51 #  define FD_CLOEXEC 1                  /* NeXT needs this */
52 #endif
53
54 /* NOTE:  Do not call the next three routines directly.  Use the macros
55  * in handy.h, so that we can easily redefine everything to do tracking of
56  * allocated hunks back to the original New to track down any memory leaks.
57  * XXX This advice seems to be widely ignored :-(   --AD  August 1996.
58  */
59
60 /* paranoid version of system's malloc() */
61
62 Malloc_t
63 Perl_safesysmalloc(MEM_SIZE size)
64 {
65     dTHX;
66     Malloc_t ptr;
67 #ifdef HAS_64K_LIMIT
68         if (size > 0xffff) {
69             PerlIO_printf(Perl_error_log,
70                           "Allocation too large: %lx\n", size) FLUSH;
71             my_exit(1);
72         }
73 #endif /* HAS_64K_LIMIT */
74 #ifdef DEBUGGING
75     if ((long)size < 0)
76         Perl_croak_nocontext("panic: malloc");
77 #endif
78     ptr = (Malloc_t)PerlMem_malloc(size?size:1);        /* malloc(0) is NASTY on our system */
79     PERL_ALLOC_CHECK(ptr);
80     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
81     if (ptr != Nullch)
82         return ptr;
83     else if (PL_nomemok)
84         return Nullch;
85     else {
86         /* Can't use PerlIO to write as it allocates memory */
87         PerlLIO_write(PerlIO_fileno(Perl_error_log),
88                       PL_no_mem, strlen(PL_no_mem));
89         my_exit(1);
90         return Nullch;
91     }
92     /*NOTREACHED*/
93 }
94
95 /* paranoid version of system's realloc() */
96
97 Malloc_t
98 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
99 {
100     dTHX;
101     Malloc_t ptr;
102 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
103     Malloc_t PerlMem_realloc();
104 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
105
106 #ifdef HAS_64K_LIMIT
107     if (size > 0xffff) {
108         PerlIO_printf(Perl_error_log,
109                       "Reallocation too large: %lx\n", size) FLUSH;
110         my_exit(1);
111     }
112 #endif /* HAS_64K_LIMIT */
113     if (!size) {
114         safesysfree(where);
115         return NULL;
116     }
117
118     if (!where)
119         return safesysmalloc(size);
120 #ifdef DEBUGGING
121     if ((long)size < 0)
122         Perl_croak_nocontext("panic: realloc");
123 #endif
124     ptr = (Malloc_t)PerlMem_realloc(where,size);
125     PERL_ALLOC_CHECK(ptr);
126
127     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
128     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
129
130     if (ptr != Nullch)
131         return ptr;
132     else if (PL_nomemok)
133         return Nullch;
134     else {
135         /* Can't use PerlIO to write as it allocates memory */
136         PerlLIO_write(PerlIO_fileno(Perl_error_log),
137                       PL_no_mem, strlen(PL_no_mem));
138         my_exit(1);
139         return Nullch;
140     }
141     /*NOTREACHED*/
142 }
143
144 /* safe version of system's free() */
145
146 Free_t
147 Perl_safesysfree(Malloc_t where)
148 {
149 #ifdef PERL_IMPLICIT_SYS
150     dTHX;
151 #endif
152     DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
153     if (where) {
154         /*SUPPRESS 701*/
155         PerlMem_free(where);
156     }
157 }
158
159 /* safe version of system's calloc() */
160
161 Malloc_t
162 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
163 {
164     dTHX;
165     Malloc_t ptr;
166
167 #ifdef HAS_64K_LIMIT
168     if (size * count > 0xffff) {
169         PerlIO_printf(Perl_error_log,
170                       "Allocation too large: %lx\n", size * count) FLUSH;
171         my_exit(1);
172     }
173 #endif /* HAS_64K_LIMIT */
174 #ifdef DEBUGGING
175     if ((long)size < 0 || (long)count < 0)
176         Perl_croak_nocontext("panic: calloc");
177 #endif
178     size *= count;
179     ptr = (Malloc_t)PerlMem_malloc(size?size:1);        /* malloc(0) is NASTY on our system */
180     PERL_ALLOC_CHECK(ptr);
181     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)size));
182     if (ptr != Nullch) {
183         memset((void*)ptr, 0, size);
184         return ptr;
185     }
186     else if (PL_nomemok)
187         return Nullch;
188     else {
189         /* Can't use PerlIO to write as it allocates memory */
190         PerlLIO_write(PerlIO_fileno(Perl_error_log),
191                       PL_no_mem, strlen(PL_no_mem));
192         my_exit(1);
193         return Nullch;
194     }
195     /*NOTREACHED*/
196 }
197
198 /* These must be defined when not using Perl's malloc for binary
199  * compatibility */
200
201 #ifndef MYMALLOC
202
203 Malloc_t Perl_malloc (MEM_SIZE nbytes)
204 {
205     dTHXs;
206     return (Malloc_t)PerlMem_malloc(nbytes);
207 }
208
209 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
210 {
211     dTHXs;
212     return (Malloc_t)PerlMem_calloc(elements, size);
213 }
214
215 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
216 {
217     dTHXs;
218     return (Malloc_t)PerlMem_realloc(where, nbytes);
219 }
220
221 Free_t   Perl_mfree (Malloc_t where)
222 {
223     dTHXs;
224     PerlMem_free(where);
225 }
226
227 #endif
228
229 /* copy a string up to some (non-backslashed) delimiter, if any */
230
231 char *
232 Perl_delimcpy(pTHX_ register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
233 {
234     register I32 tolen;
235     for (tolen = 0; from < fromend; from++, tolen++) {
236         if (*from == '\\') {
237             if (from[1] == delim)
238                 from++;
239             else {
240                 if (to < toend)
241                     *to++ = *from;
242                 tolen++;
243                 from++;
244             }
245         }
246         else if (*from == delim)
247             break;
248         if (to < toend)
249             *to++ = *from;
250     }
251     if (to < toend)
252         *to = '\0';
253     *retlen = tolen;
254     return (char *)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 Perl_instr(pTHX_ register const char *big, register const char *little)
262 {
263     register const char *s, *x;
264     register I32 first;
265
266     if (!little)
267         return (char*)big;
268     first = *little++;
269     if (!first)
270         return (char*)big;
271     while (*big) {
272         if (*big++ != first)
273             continue;
274         for (x=big,s=little; *s; /**/ ) {
275             if (!*x)
276                 return Nullch;
277             if (*s++ != *x++) {
278                 s--;
279                 break;
280             }
281         }
282         if (!*s)
283             return (char*)(big-1);
284     }
285     return Nullch;
286 }
287
288 /* same as instr but allow embedded nulls */
289
290 char *
291 Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
292 {
293     register const char *s, *x;
294     register const I32 first = *little;
295     register const char *littleend = lend;
296
297     if (!first && little >= littleend)
298         return (char*)big;
299     if (bigend - big < littleend - little)
300         return Nullch;
301     bigend -= littleend - little++;
302     while (big <= bigend) {
303         if (*big++ != first)
304             continue;
305         for (x=big,s=little; s < littleend; /**/ ) {
306             if (*s++ != *x++) {
307                 s--;
308                 break;
309             }
310         }
311         if (s >= littleend)
312             return (char*)(big-1);
313     }
314     return Nullch;
315 }
316
317 /* reverse of the above--find last substring */
318
319 char *
320 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
321 {
322     register const char *bigbeg;
323     register const char *s, *x;
324     register const I32 first = *little;
325     register const char *littleend = lend;
326
327     if (!first && little >= littleend)
328         return (char*)bigend;
329     bigbeg = big;
330     big = bigend - (littleend - little++);
331     while (big >= bigbeg) {
332         if (*big-- != first)
333             continue;
334         for (x=big+2,s=little; s < littleend; /**/ ) {
335             if (*s++ != *x++) {
336                 s--;
337                 break;
338             }
339         }
340         if (s >= littleend)
341             return (char*)(big+1);
342     }
343     return Nullch;
344 }
345
346 #define FBM_TABLE_OFFSET 2      /* Number of bytes between EOS and table*/
347
348 /* As a space optimization, we do not compile tables for strings of length
349    0 and 1, and for strings of length 2 unless FBMcf_TAIL.  These are
350    special-cased in fbm_instr().
351
352    If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
353
354 /*
355 =head1 Miscellaneous Functions
356
357 =for apidoc fbm_compile
358
359 Analyses the string in order to make fast searches on it using fbm_instr()
360 -- the Boyer-Moore algorithm.
361
362 =cut
363 */
364
365 void
366 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
367 {
368     const register U8 *s;
369     register U8 *table;
370     register U32 i;
371     STRLEN len;
372     I32 rarest = 0;
373     U32 frequency = 256;
374
375     if (flags & FBMcf_TAIL) {
376         MAGIC *mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
377         sv_catpvn(sv, "\n", 1);         /* Taken into account in fbm_instr() */
378         if (mg && mg->mg_len >= 0)
379             mg->mg_len++;
380     }
381     s = (U8*)SvPV_force_mutable(sv, len);
382     (void)SvUPGRADE(sv, SVt_PVBM);
383     if (len == 0)               /* TAIL might be on a zero-length string. */
384         return;
385     if (len > 2) {
386         U8 mlen;
387         const unsigned char *sb;
388
389         if (len > 255)
390             mlen = 255;
391         else
392             mlen = (U8)len;
393         Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
394         table = (unsigned char*)(SvPVX_mutable(sv) + len + FBM_TABLE_OFFSET);
395         s = table - 1 - FBM_TABLE_OFFSET;       /* last char */
396         memset((void*)table, mlen, 256);
397         table[-1] = (U8)flags;
398         i = 0;
399         sb = s - mlen + 1;                      /* first char (maybe) */
400         while (s >= sb) {
401             if (table[*s] == mlen)
402                 table[*s] = (U8)i;
403             s--, i++;
404         }
405     }
406     sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 0);     /* deep magic */
407     SvVALID_on(sv);
408
409     s = (const unsigned char*)(SvPVX_const(sv));        /* deeper magic */
410     for (i = 0; i < len; i++) {
411         if (PL_freq[s[i]] < frequency) {
412             rarest = i;
413             frequency = PL_freq[s[i]];
414         }
415     }
416     BmRARE(sv) = s[rarest];
417     BmPREVIOUS(sv) = (U16)rarest;
418     BmUSEFUL(sv) = 100;                 /* Initial value */
419     if (flags & FBMcf_TAIL)
420         SvTAIL_on(sv);
421     DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
422                           BmRARE(sv),BmPREVIOUS(sv)));
423 }
424
425 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
426 /* If SvTAIL is actually due to \Z or \z, this gives false positives
427    if multiline */
428
429 /*
430 =for apidoc fbm_instr
431
432 Returns the location of the SV in the string delimited by C<str> and
433 C<strend>.  It returns C<Nullch> if the string can't be found.  The C<sv>
434 does not have to be fbm_compiled, but the search will not be as fast
435 then.
436
437 =cut
438 */
439
440 char *
441 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
442 {
443     register unsigned char *s;
444     STRLEN l;
445     register const unsigned char *little
446         = (const unsigned char *)SvPV_const(littlestr,l);
447     register STRLEN littlelen = l;
448     register const I32 multiline = flags & FBMrf_MULTILINE;
449
450     if ((STRLEN)(bigend - big) < littlelen) {
451         if ( SvTAIL(littlestr)
452              && ((STRLEN)(bigend - big) == littlelen - 1)
453              && (littlelen == 1
454                  || (*big == *little &&
455                      memEQ(big, little, littlelen - 1))))
456             return (char*)big;
457         return Nullch;
458     }
459
460     if (littlelen <= 2) {               /* Special-cased */
461
462         if (littlelen == 1) {
463             if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
464                 /* Know that bigend != big.  */
465                 if (bigend[-1] == '\n')
466                     return (char *)(bigend - 1);
467                 return (char *) bigend;
468             }
469             s = big;
470             while (s < bigend) {
471                 if (*s == *little)
472                     return (char *)s;
473                 s++;
474             }
475             if (SvTAIL(littlestr))
476                 return (char *) bigend;
477             return Nullch;
478         }
479         if (!littlelen)
480             return (char*)big;          /* Cannot be SvTAIL! */
481
482         /* littlelen is 2 */
483         if (SvTAIL(littlestr) && !multiline) {
484             if (bigend[-1] == '\n' && bigend[-2] == *little)
485                 return (char*)bigend - 2;
486             if (bigend[-1] == *little)
487                 return (char*)bigend - 1;
488             return Nullch;
489         }
490         {
491             /* This should be better than FBM if c1 == c2, and almost
492                as good otherwise: maybe better since we do less indirection.
493                And we save a lot of memory by caching no table. */
494             register unsigned char c1 = little[0];
495             register unsigned char c2 = little[1];
496
497             s = big + 1;
498             bigend--;
499             if (c1 != c2) {
500                 while (s <= bigend) {
501                     if (s[0] == c2) {
502                         if (s[-1] == c1)
503                             return (char*)s - 1;
504                         s += 2;
505                         continue;
506                     }
507                   next_chars:
508                     if (s[0] == c1) {
509                         if (s == bigend)
510                             goto check_1char_anchor;
511                         if (s[1] == c2)
512                             return (char*)s;
513                         else {
514                             s++;
515                             goto next_chars;
516                         }
517                     }
518                     else
519                         s += 2;
520                 }
521                 goto check_1char_anchor;
522             }
523             /* Now c1 == c2 */
524             while (s <= bigend) {
525                 if (s[0] == c1) {
526                     if (s[-1] == c1)
527                         return (char*)s - 1;
528                     if (s == bigend)
529                         goto check_1char_anchor;
530                     if (s[1] == c1)
531                         return (char*)s;
532                     s += 3;
533                 }
534                 else
535                     s += 2;
536             }
537         }
538       check_1char_anchor:               /* One char and anchor! */
539         if (SvTAIL(littlestr) && (*bigend == *little))
540             return (char *)bigend;      /* bigend is already decremented. */
541         return Nullch;
542     }
543     if (SvTAIL(littlestr) && !multiline) {      /* tail anchored? */
544         s = bigend - littlelen;
545         if (s >= big && bigend[-1] == '\n' && *s == *little
546             /* Automatically of length > 2 */
547             && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
548         {
549             return (char*)s;            /* how sweet it is */
550         }
551         if (s[1] == *little
552             && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
553         {
554             return (char*)s + 1;        /* how sweet it is */
555         }
556         return Nullch;
557     }
558     if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
559         char *b = ninstr((char*)big,(char*)bigend,
560                          (char*)little, (char*)little + littlelen);
561
562         if (!b && SvTAIL(littlestr)) {  /* Automatically multiline!  */
563             /* Chop \n from littlestr: */
564             s = bigend - littlelen + 1;
565             if (*s == *little
566                 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
567             {
568                 return (char*)s;
569             }
570             return Nullch;
571         }
572         return b;
573     }
574
575     {   /* Do actual FBM.  */
576         register const unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
577         const register unsigned char *oldlittle;
578
579         if (littlelen > (STRLEN)(bigend - big))
580             return Nullch;
581         --littlelen;                    /* Last char found by table lookup */
582
583         s = big + littlelen;
584         little += littlelen;            /* last char */
585         oldlittle = little;
586         if (s < bigend) {
587             register I32 tmp;
588
589           top2:
590             /*SUPPRESS 560*/
591             if ((tmp = table[*s])) {
592                 if ((s += tmp) < bigend)
593                     goto top2;
594                 goto check_end;
595             }
596             else {              /* less expensive than calling strncmp() */
597                 register unsigned char *olds = s;
598
599                 tmp = littlelen;
600
601                 while (tmp--) {
602                     if (*--s == *--little)
603                         continue;
604                     s = olds + 1;       /* here we pay the price for failure */
605                     little = oldlittle;
606                     if (s < bigend)     /* fake up continue to outer loop */
607                         goto top2;
608                     goto check_end;
609                 }
610                 return (char *)s;
611             }
612         }
613       check_end:
614         if ( s == bigend && (table[-1] & FBMcf_TAIL)
615              && memEQ((char *)(bigend - littlelen),
616                       (char *)(oldlittle - littlelen), littlelen) )
617             return (char*)bigend - littlelen;
618         return Nullch;
619     }
620 }
621
622 /* start_shift, end_shift are positive quantities which give offsets
623    of ends of some substring of bigstr.
624    If "last" we want the last occurrence.
625    old_posp is the way of communication between consequent calls if
626    the next call needs to find the .
627    The initial *old_posp should be -1.
628
629    Note that we take into account SvTAIL, so one can get extra
630    optimizations if _ALL flag is set.
631  */
632
633 /* If SvTAIL is actually due to \Z or \z, this gives false positives
634    if PL_multiline.  In fact if !PL_multiline the authoritative answer
635    is not supported yet. */
636
637 char *
638 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
639 {
640     register unsigned char *s, *x;
641     register unsigned char *big;
642     register I32 pos;
643     register I32 previous;
644     register I32 first;
645     register unsigned char *little;
646     register I32 stop_pos;
647     register unsigned char *littleend;
648     I32 found = 0;
649
650     if (*old_posp == -1
651         ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
652         : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
653       cant_find:
654         if ( BmRARE(littlestr) == '\n'
655              && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
656             little = (unsigned char *)(SvPVX(littlestr));
657             littleend = little + SvCUR(littlestr);
658             first = *little++;
659             goto check_tail;
660         }
661         return Nullch;
662     }
663
664     little = (unsigned char *)(SvPVX(littlestr));
665     littleend = little + SvCUR(littlestr);
666     first = *little++;
667     /* The value of pos we can start at: */
668     previous = BmPREVIOUS(littlestr);
669     big = (unsigned char *)(SvPVX(bigstr));
670     /* The value of pos we can stop at: */
671     stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
672     if (previous + start_shift > stop_pos) {
673 /*
674   stop_pos does not include SvTAIL in the count, so this check is incorrect
675   (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
676 */
677 #if 0
678         if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
679             goto check_tail;
680 #endif
681         return Nullch;
682     }
683     while (pos < previous + start_shift) {
684         if (!(pos += PL_screamnext[pos]))
685             goto cant_find;
686     }
687     big -= previous;
688     do {
689         if (pos >= stop_pos) break;
690         if (big[pos] != first)
691             continue;
692         for (x=big+pos+1,s=little; s < littleend; /**/ ) {
693             if (*s++ != *x++) {
694                 s--;
695                 break;
696             }
697         }
698         if (s == littleend) {
699             *old_posp = pos;
700             if (!last) return (char *)(big+pos);
701             found = 1;
702         }
703     } while ( pos += PL_screamnext[pos] );
704     if (last && found)
705         return (char *)(big+(*old_posp));
706   check_tail:
707     if (!SvTAIL(littlestr) || (end_shift > 0))
708         return Nullch;
709     /* Ignore the trailing "\n".  This code is not microoptimized */
710     big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
711     stop_pos = littleend - little;      /* Actual littlestr len */
712     if (stop_pos == 0)
713         return (char*)big;
714     big -= stop_pos;
715     if (*big == first
716         && ((stop_pos == 1) ||
717             memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
718         return (char*)big;
719     return Nullch;
720 }
721
722 I32
723 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
724 {
725     register const U8 *a = (const U8 *)s1;
726     register const U8 *b = (const U8 *)s2;
727     while (len--) {
728         if (*a != *b && *a != PL_fold[*b])
729             return 1;
730         a++,b++;
731     }
732     return 0;
733 }
734
735 I32
736 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
737 {
738     register const U8 *a = (const U8 *)s1;
739     register const U8 *b = (const U8 *)s2;
740     while (len--) {
741         if (*a != *b && *a != PL_fold_locale[*b])
742             return 1;
743         a++,b++;
744     }
745     return 0;
746 }
747
748 /* copy a string to a safe spot */
749
750 /*
751 =head1 Memory Management
752
753 =for apidoc savepv
754
755 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
756 string which is a duplicate of C<pv>. The size of the string is
757 determined by C<strlen()>. The memory allocated for the new string can
758 be freed with the C<Safefree()> function.
759
760 =cut
761 */
762
763 char *
764 Perl_savepv(pTHX_ const char *pv)
765 {
766     register char *newaddr;
767 #ifdef PERL_MALLOC_WRAP
768     STRLEN pvlen;
769 #endif
770     if (!pv)
771         return Nullch;
772
773 #ifdef PERL_MALLOC_WRAP
774     pvlen = strlen(pv)+1;
775     New(902,newaddr,pvlen,char);
776 #else
777     New(902,newaddr,strlen(pv)+1,char);
778 #endif
779     return strcpy(newaddr,pv);
780 }
781
782 /* same thing but with a known length */
783
784 /*
785 =for apidoc savepvn
786
787 Perl's version of what C<strndup()> would be if it existed. Returns a
788 pointer to a newly allocated string which is a duplicate of the first
789 C<len> bytes from C<pv>. The memory allocated for the new string can be
790 freed with the C<Safefree()> function.
791
792 =cut
793 */
794
795 char *
796 Perl_savepvn(pTHX_ const char *pv, register I32 len)
797 {
798     register char *newaddr;
799
800     New(903,newaddr,len+1,char);
801     /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
802     if (pv) {
803         /* might not be null terminated */
804         newaddr[len] = '\0';
805         return (char *) CopyD(pv,newaddr,len,char);
806     }
807     else {
808         return (char *) ZeroD(newaddr,len+1,char);
809     }
810 }
811
812 /*
813 =for apidoc savesharedpv
814
815 A version of C<savepv()> which allocates the duplicate string in memory
816 which is shared between threads.
817
818 =cut
819 */
820 char *
821 Perl_savesharedpv(pTHX_ const char *pv)
822 {
823     register char *newaddr;
824     if (!pv)
825         return Nullch;
826
827     newaddr = (char*)PerlMemShared_malloc(strlen(pv)+1);
828     if (!newaddr) {
829         PerlLIO_write(PerlIO_fileno(Perl_error_log),
830                       PL_no_mem, strlen(PL_no_mem));
831         my_exit(1);
832     }
833     return strcpy(newaddr,pv);
834 }
835
836 /*
837 =for apidoc savesvpv
838
839 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
840 the passed in SV using C<SvPV()>
841
842 =cut
843 */
844
845 char *
846 Perl_savesvpv(pTHX_ SV *sv)
847 {
848     STRLEN len;
849     const char *pv = SvPV(sv, len);
850     register char *newaddr;
851
852     ++len;
853     New(903,newaddr,len,char);
854     return (char *) CopyD(pv,newaddr,len,char);
855 }
856
857
858 /* the SV for Perl_form() and mess() is not kept in an arena */
859
860 STATIC SV *
861 S_mess_alloc(pTHX)
862 {
863     SV *sv;
864     XPVMG *any;
865
866     if (!PL_dirty)
867         return sv_2mortal(newSVpvn("",0));
868
869     if (PL_mess_sv)
870         return PL_mess_sv;
871
872     /* Create as PVMG now, to avoid any upgrading later */
873     New(905, sv, 1, SV);
874     Newz(905, any, 1, XPVMG);
875     SvFLAGS(sv) = SVt_PVMG;
876     SvANY(sv) = (void*)any;
877     SvREFCNT(sv) = 1 << 30; /* practically infinite */
878     PL_mess_sv = sv;
879     return sv;
880 }
881
882 #if defined(PERL_IMPLICIT_CONTEXT)
883 char *
884 Perl_form_nocontext(const char* pat, ...)
885 {
886     dTHX;
887     char *retval;
888     va_list args;
889     va_start(args, pat);
890     retval = vform(pat, &args);
891     va_end(args);
892     return retval;
893 }
894 #endif /* PERL_IMPLICIT_CONTEXT */
895
896 /*
897 =head1 Miscellaneous Functions
898 =for apidoc form
899
900 Takes a sprintf-style format pattern and conventional
901 (non-SV) arguments and returns the formatted string.
902
903     (char *) Perl_form(pTHX_ const char* pat, ...)
904
905 can be used any place a string (char *) is required:
906
907     char * s = Perl_form("%d.%d",major,minor);
908
909 Uses a single private buffer so if you want to format several strings you
910 must explicitly copy the earlier strings away (and free the copies when you
911 are done).
912
913 =cut
914 */
915
916 char *
917 Perl_form(pTHX_ const char* pat, ...)
918 {
919     char *retval;
920     va_list args;
921     va_start(args, pat);
922     retval = vform(pat, &args);
923     va_end(args);
924     return retval;
925 }
926
927 char *
928 Perl_vform(pTHX_ const char *pat, va_list *args)
929 {
930     SV *sv = mess_alloc();
931     sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
932     return SvPVX(sv);
933 }
934
935 #if defined(PERL_IMPLICIT_CONTEXT)
936 SV *
937 Perl_mess_nocontext(const char *pat, ...)
938 {
939     dTHX;
940     SV *retval;
941     va_list args;
942     va_start(args, pat);
943     retval = vmess(pat, &args);
944     va_end(args);
945     return retval;
946 }
947 #endif /* PERL_IMPLICIT_CONTEXT */
948
949 SV *
950 Perl_mess(pTHX_ const char *pat, ...)
951 {
952     SV *retval;
953     va_list args;
954     va_start(args, pat);
955     retval = vmess(pat, &args);
956     va_end(args);
957     return retval;
958 }
959
960 STATIC COP*
961 S_closest_cop(pTHX_ COP *cop, OP *o)
962 {
963     /* Look for PL_op starting from o.  cop is the last COP we've seen. */
964
965     if (!o || o == PL_op) return cop;
966
967     if (o->op_flags & OPf_KIDS) {
968         OP *kid;
969         for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
970         {
971             COP *new_cop;
972
973             /* If the OP_NEXTSTATE has been optimised away we can still use it
974              * the get the file and line number. */
975
976             if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
977                 cop = (COP *)kid;
978
979             /* Keep searching, and return when we've found something. */
980
981             new_cop = closest_cop(cop, kid);
982             if (new_cop) return new_cop;
983         }
984     }
985
986     /* Nothing found. */
987
988     return 0;
989 }
990
991 SV *
992 Perl_vmess(pTHX_ const char *pat, va_list *args)
993 {
994     SV *sv = mess_alloc();
995     static char dgd[] = " during global destruction.\n";
996
997     sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
998     if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
999
1000         /*
1001          * Try and find the file and line for PL_op.  This will usually be
1002          * PL_curcop, but it might be a cop that has been optimised away.  We
1003          * can try to find such a cop by searching through the optree starting
1004          * from the sibling of PL_curcop.
1005          */
1006
1007         const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1008         if (!cop) cop = PL_curcop;
1009
1010         if (CopLINE(cop))
1011             Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1012             OutCopFILE(cop), (IV)CopLINE(cop));
1013         if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1014             const bool line_mode = (RsSIMPLE(PL_rs) &&
1015                               SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1016             Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1017                            PL_last_in_gv == PL_argvgv ?
1018                            "" : GvNAME(PL_last_in_gv),
1019                            line_mode ? "line" : "chunk",
1020                            (IV)IoLINES(GvIOp(PL_last_in_gv)));
1021         }
1022 #ifdef USE_5005THREADS
1023         if (thr->tid)
1024             Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1025 #endif
1026         sv_catpv(sv, PL_dirty ? dgd : ".\n");
1027     }
1028     return sv;
1029 }
1030
1031 void
1032 Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1033 {
1034     IO *io;
1035     MAGIC *mg;
1036
1037     if (PL_stderrgv && SvREFCNT(PL_stderrgv) 
1038         && (io = GvIO(PL_stderrgv))
1039         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar))) 
1040     {
1041         dSP;
1042         ENTER;
1043         SAVETMPS;
1044
1045         save_re_context();
1046         SAVESPTR(PL_stderrgv);
1047         PL_stderrgv = Nullgv;
1048
1049         PUSHSTACKi(PERLSI_MAGIC);
1050
1051         PUSHMARK(SP);
1052         EXTEND(SP,2);
1053         PUSHs(SvTIED_obj((SV*)io, mg));
1054         PUSHs(sv_2mortal(newSVpvn(message, msglen)));
1055         PUTBACK;
1056         call_method("PRINT", G_SCALAR);
1057
1058         POPSTACK;
1059         FREETMPS;
1060         LEAVE;
1061     }
1062     else {
1063 #ifdef USE_SFIO
1064         /* SFIO can really mess with your errno */
1065         int e = errno;
1066 #endif
1067         PerlIO *serr = Perl_error_log;
1068
1069         PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1070         (void)PerlIO_flush(serr);
1071 #ifdef USE_SFIO
1072         errno = e;
1073 #endif
1074     }
1075 }
1076
1077 /* Common code used by vcroak, vdie and vwarner  */
1078
1079 /* Whilst this should really be STATIC, it was not in 5.8.7, hence something
1080    may have linked against it.  */
1081 void
1082 S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8)
1083 {
1084     HV *stash;
1085     GV *gv;
1086     CV *cv;
1087     /* sv_2cv might call Perl_croak() */
1088     SV *olddiehook = PL_diehook;
1089
1090     assert(PL_diehook);
1091     ENTER;
1092     SAVESPTR(PL_diehook);
1093     PL_diehook = Nullsv;
1094     cv = sv_2cv(olddiehook, &stash, &gv, 0);
1095     LEAVE;
1096     if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1097         dSP;
1098         SV *msg;
1099
1100         ENTER;
1101         save_re_context();
1102         if (message) {
1103             msg = newSVpvn(message, msglen);
1104             SvFLAGS(msg) |= utf8;
1105             SvREADONLY_on(msg);
1106             SAVEFREESV(msg);
1107         }
1108         else {
1109             msg = ERRSV;
1110         }
1111
1112         PUSHSTACKi(PERLSI_DIEHOOK);
1113         PUSHMARK(SP);
1114         XPUSHs(msg);
1115         PUTBACK;
1116         call_sv((SV*)cv, G_DISCARD);
1117         POPSTACK;
1118         LEAVE;
1119     }
1120 }
1121
1122 /* Whilst this should really be STATIC, it was not in 5.8.7, hence something
1123    may have linked against it.  */
1124 char *
1125 S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1126                     I32* utf8)
1127 {
1128     char *message;
1129
1130     if (pat) {
1131         SV *msv = vmess(pat, args);
1132         if (PL_errors && SvCUR(PL_errors)) {
1133             sv_catsv(PL_errors, msv);
1134             message = SvPV(PL_errors, *msglen);
1135             SvCUR_set(PL_errors, 0);
1136         }
1137         else
1138             message = SvPV(msv,*msglen);
1139         *utf8 = SvUTF8(msv);
1140     }
1141     else {
1142         message = Nullch;
1143     }
1144
1145     DEBUG_S(PerlIO_printf(Perl_debug_log,
1146                           "%p: die/croak: message = %s\ndiehook = %p\n",
1147                           thr, message, PL_diehook));
1148     if (PL_diehook) {
1149         S_vdie_common(aTHX_ message, *msglen, *utf8);
1150     }
1151     return message;
1152 }
1153
1154 OP *
1155 Perl_vdie(pTHX_ const char* pat, va_list *args)
1156 {
1157     const char *message;
1158     const int was_in_eval = PL_in_eval;
1159     STRLEN msglen;
1160     I32 utf8 = 0;
1161
1162     DEBUG_S(PerlIO_printf(Perl_debug_log,
1163                           "%p: die: curstack = %p, mainstack = %p\n",
1164                           thr, PL_curstack, PL_mainstack));
1165
1166     message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1167
1168     PL_restartop = die_where(message, msglen);
1169     SvFLAGS(ERRSV) |= utf8;
1170     DEBUG_S(PerlIO_printf(Perl_debug_log,
1171           "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1172           thr, PL_restartop, was_in_eval, PL_top_env));
1173     if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1174         JMPENV_JUMP(3);
1175     return PL_restartop;
1176 }
1177
1178 #if defined(PERL_IMPLICIT_CONTEXT)
1179 OP *
1180 Perl_die_nocontext(const char* pat, ...)
1181 {
1182     dTHX;
1183     OP *o;
1184     va_list args;
1185     va_start(args, pat);
1186     o = vdie(pat, &args);
1187     va_end(args);
1188     return o;
1189 }
1190 #endif /* PERL_IMPLICIT_CONTEXT */
1191
1192 OP *
1193 Perl_die(pTHX_ const char* pat, ...)
1194 {
1195     OP *o;
1196     va_list args;
1197     va_start(args, pat);
1198     o = vdie(pat, &args);
1199     va_end(args);
1200     return o;
1201 }
1202
1203 void
1204 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1205 {
1206     const char *message;
1207     STRLEN msglen;
1208     I32 utf8 = 0;
1209
1210     message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1211
1212     if (PL_in_eval) {
1213         PL_restartop = die_where(message, msglen);
1214         SvFLAGS(ERRSV) |= utf8;
1215         JMPENV_JUMP(3);
1216     }
1217     else if (!message)
1218         message = SvPVx(ERRSV, msglen);
1219
1220     write_to_stderr(message, msglen);
1221     my_failure_exit();
1222 }
1223
1224 #if defined(PERL_IMPLICIT_CONTEXT)
1225 void
1226 Perl_croak_nocontext(const char *pat, ...)
1227 {
1228     dTHX;
1229     va_list args;
1230     va_start(args, pat);
1231     vcroak(pat, &args);
1232     /* NOTREACHED */
1233     va_end(args);
1234 }
1235 #endif /* PERL_IMPLICIT_CONTEXT */
1236
1237 /*
1238 =head1 Warning and Dieing
1239
1240 =for apidoc croak
1241
1242 This is the XSUB-writer's interface to Perl's C<die> function.
1243 Normally call this function the same way you call the C C<printf>
1244 function.  Calling C<croak> returns control directly to Perl,
1245 sidestepping the normal C order of execution. See C<warn>.
1246
1247 If you want to throw an exception object, assign the object to
1248 C<$@> and then pass C<Nullch> to croak():
1249
1250    errsv = get_sv("@", TRUE);
1251    sv_setsv(errsv, exception_object);
1252    croak(Nullch);
1253
1254 =cut
1255 */
1256
1257 void
1258 Perl_croak(pTHX_ const char *pat, ...)
1259 {
1260     va_list args;
1261     va_start(args, pat);
1262     vcroak(pat, &args);
1263     /* NOTREACHED */
1264     va_end(args);
1265 }
1266
1267 void
1268 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1269 {
1270     char *message;
1271     HV *stash;
1272     GV *gv;
1273     CV *cv;
1274     SV *msv;
1275     STRLEN msglen;
1276     I32 utf8 = 0;
1277
1278     msv = vmess(pat, args);
1279     utf8 = SvUTF8(msv);
1280     message = SvPV(msv, msglen);
1281
1282     if (PL_warnhook) {
1283         /* sv_2cv might call Perl_warn() */
1284         SV *oldwarnhook = PL_warnhook;
1285         ENTER;
1286         SAVESPTR(PL_warnhook);
1287         PL_warnhook = Nullsv;
1288         cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1289         LEAVE;
1290         if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1291             dSP;
1292             SV *msg;
1293
1294             ENTER;
1295             save_re_context();
1296             msg = newSVpvn(message, msglen);
1297             SvFLAGS(msg) |= utf8;
1298             SvREADONLY_on(msg);
1299             SAVEFREESV(msg);
1300
1301             PUSHSTACKi(PERLSI_WARNHOOK);
1302             PUSHMARK(SP);
1303             XPUSHs(msg);
1304             PUTBACK;
1305             call_sv((SV*)cv, G_DISCARD);
1306             POPSTACK;
1307             LEAVE;
1308             return;
1309         }
1310     }
1311
1312     write_to_stderr(message, msglen);
1313 }
1314
1315 #if defined(PERL_IMPLICIT_CONTEXT)
1316 void
1317 Perl_warn_nocontext(const char *pat, ...)
1318 {
1319     dTHX;
1320     va_list args;
1321     va_start(args, pat);
1322     vwarn(pat, &args);
1323     va_end(args);
1324 }
1325 #endif /* PERL_IMPLICIT_CONTEXT */
1326
1327 /*
1328 =for apidoc warn
1329
1330 This is the XSUB-writer's interface to Perl's C<warn> function.  Call this
1331 function the same way you call the C C<printf> function.  See C<croak>.
1332
1333 =cut
1334 */
1335
1336 void
1337 Perl_warn(pTHX_ const char *pat, ...)
1338 {
1339     va_list args;
1340     va_start(args, pat);
1341     vwarn(pat, &args);
1342     va_end(args);
1343 }
1344
1345 #if defined(PERL_IMPLICIT_CONTEXT)
1346 void
1347 Perl_warner_nocontext(U32 err, const char *pat, ...)
1348 {
1349     dTHX;
1350     va_list args;
1351     va_start(args, pat);
1352     vwarner(err, pat, &args);
1353     va_end(args);
1354 }
1355 #endif /* PERL_IMPLICIT_CONTEXT */
1356
1357 void
1358 Perl_warner(pTHX_ U32  err, const char* pat,...)
1359 {
1360     va_list args;
1361     va_start(args, pat);
1362     vwarner(err, pat, &args);
1363     va_end(args);
1364 }
1365
1366 void
1367 Perl_vwarner(pTHX_ U32  err, const char* pat, va_list* args)
1368 {
1369     if (ckDEAD(err)) {
1370         SV * const msv = vmess(pat, args);
1371         STRLEN msglen;
1372         const char *message = SvPV(msv, msglen);
1373         const I32 utf8 = SvUTF8(msv);
1374
1375 #ifdef USE_5005THREADS
1376         DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1377 #endif /* USE_5005THREADS */
1378         if (PL_diehook) {
1379             assert(message);
1380             S_vdie_common(aTHX_ message, msglen, utf8);
1381         }
1382         if (PL_in_eval) {
1383             PL_restartop = die_where(message, msglen);
1384             SvFLAGS(ERRSV) |= utf8;
1385             JMPENV_JUMP(3);
1386         }
1387         write_to_stderr(message, msglen);
1388         my_failure_exit();
1389     }
1390     else {
1391         Perl_vwarn(aTHX_ pat, args);
1392     }
1393 }
1394
1395 /* since we've already done strlen() for both nam and val
1396  * we can use that info to make things faster than
1397  * sprintf(s, "%s=%s", nam, val)
1398  */
1399 #define my_setenv_format(s, nam, nlen, val, vlen) \
1400    Copy(nam, s, nlen, char); \
1401    *(s+nlen) = '='; \
1402    Copy(val, s+(nlen+1), vlen, char); \
1403    *(s+(nlen+1+vlen)) = '\0'
1404
1405 #ifdef USE_ENVIRON_ARRAY
1406        /* VMS' my_setenv() is in vms.c */
1407 #if !defined(WIN32) && !defined(NETWARE)
1408 void
1409 Perl_my_setenv(pTHX_ char *nam, char *val)
1410 {
1411 #ifdef USE_ITHREADS
1412   /* only parent thread can modify process environment */
1413   if (PL_curinterp == aTHX)
1414 #endif
1415   {
1416 #ifndef PERL_USE_SAFE_PUTENV
1417     if (!PL_use_safe_putenv) {
1418     /* most putenv()s leak, so we manipulate environ directly */
1419     register I32 i=setenv_getix(nam);           /* where does it go? */
1420     int nlen, vlen;
1421
1422     if (environ == PL_origenviron) {    /* need we copy environment? */
1423         I32 j;
1424         I32 max;
1425         char **tmpenv;
1426
1427         /*SUPPRESS 530*/
1428         for (max = i; environ[max]; max++) ;
1429         tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1430         for (j=0; j<max; j++) {         /* copy environment */
1431             const int len = strlen(environ[j]);
1432             tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1433             Copy(environ[j], tmpenv[j], len+1, char);
1434         }
1435         tmpenv[max] = Nullch;
1436         environ = tmpenv;               /* tell exec where it is now */
1437     }
1438     if (!val) {
1439         safesysfree(environ[i]);
1440         while (environ[i]) {
1441             environ[i] = environ[i+1];
1442             i++;
1443         }
1444         return;
1445     }
1446     if (!environ[i]) {                  /* does not exist yet */
1447         environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1448         environ[i+1] = Nullch;  /* make sure it's null terminated */
1449     }
1450     else
1451         safesysfree(environ[i]);
1452     nlen = strlen(nam);
1453     vlen = strlen(val);
1454
1455     environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1456     /* all that work just for this */
1457     my_setenv_format(environ[i], nam, nlen, val, vlen);
1458     } else {
1459 # endif
1460 #   if defined(__CYGWIN__) || defined( EPOC)
1461     setenv(nam, val, 1);
1462 #   else
1463     char *new_env;
1464     int nlen = strlen(nam), vlen;
1465     if (!val) {
1466         val = "";
1467     }
1468     vlen = strlen(val);
1469     new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1470     /* all that work just for this */
1471     my_setenv_format(new_env, nam, nlen, val, vlen);
1472     (void)putenv(new_env);
1473 #   endif /* __CYGWIN__ */
1474 #ifndef PERL_USE_SAFE_PUTENV
1475     }
1476 #endif
1477   }
1478 }
1479
1480 #else /* WIN32 || NETWARE */
1481
1482 void
1483 Perl_my_setenv(pTHX_ const char *nam, char *val)
1484 {
1485     register char *envstr;
1486     const int nlen = strlen(nam);
1487     int vlen;
1488
1489     if (!val) {
1490         val = "";
1491     }
1492     vlen = strlen(val);
1493     New(904, envstr, nlen+vlen+2, char);
1494     my_setenv_format(envstr, nam, nlen, val, vlen);
1495     (void)PerlEnv_putenv(envstr);
1496     Safefree(envstr);
1497 }
1498
1499 #endif /* WIN32 || NETWARE */
1500
1501 #ifndef PERL_MICRO
1502 I32
1503 Perl_setenv_getix(pTHX_ char *nam)
1504 {
1505     register I32 i, len = strlen(nam);
1506
1507     for (i = 0; environ[i]; i++) {
1508         if (
1509 #ifdef WIN32
1510             strnicmp(environ[i],nam,len) == 0
1511 #else
1512             strnEQ(environ[i],nam,len)
1513 #endif
1514             && environ[i][len] == '=')
1515             break;                      /* strnEQ must come first to avoid */
1516     }                                   /* potential SEGV's */
1517     return i;
1518 }
1519 #endif /* !PERL_MICRO */
1520
1521 #endif /* !VMS && !EPOC*/
1522
1523 #ifdef UNLINK_ALL_VERSIONS
1524 I32
1525 Perl_unlnk(pTHX_ char *f)       /* unlink all versions of a file */
1526 {
1527     I32 i;
1528
1529     for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1530     return i ? 0 : -1;
1531 }
1532 #endif
1533
1534 /* this is a drop-in replacement for bcopy() */
1535 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1536 char *
1537 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1538 {
1539     char *retval = to;
1540
1541     if (from - to >= 0) {
1542         while (len--)
1543             *to++ = *from++;
1544     }
1545     else {
1546         to += len;
1547         from += len;
1548         while (len--)
1549             *(--to) = *(--from);
1550     }
1551     return retval;
1552 }
1553 #endif
1554
1555 /* this is a drop-in replacement for memset() */
1556 #ifndef HAS_MEMSET
1557 void *
1558 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1559 {
1560     char *retval = loc;
1561
1562     while (len--)
1563         *loc++ = ch;
1564     return retval;
1565 }
1566 #endif
1567
1568 /* this is a drop-in replacement for bzero() */
1569 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1570 char *
1571 Perl_my_bzero(register char *loc, register I32 len)
1572 {
1573     char *retval = loc;
1574
1575     while (len--)
1576         *loc++ = 0;
1577     return retval;
1578 }
1579 #endif
1580
1581 /* this is a drop-in replacement for memcmp() */
1582 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1583 I32
1584 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1585 {
1586     register const U8 *a = (const U8 *)s1;
1587     register const U8 *b = (const U8 *)s2;
1588     register I32 tmp;
1589
1590     while (len--) {
1591         if (tmp = *a++ - *b++)
1592             return tmp;
1593     }
1594     return 0;
1595 }
1596 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1597
1598 #ifndef HAS_VPRINTF
1599
1600 #ifdef USE_CHAR_VSPRINTF
1601 char *
1602 #else
1603 int
1604 #endif
1605 vsprintf(char *dest, const char *pat, char *args)
1606 {
1607     FILE fakebuf;
1608
1609     fakebuf._ptr = dest;
1610     fakebuf._cnt = 32767;
1611 #ifndef _IOSTRG
1612 #define _IOSTRG 0
1613 #endif
1614     fakebuf._flag = _IOWRT|_IOSTRG;
1615     _doprnt(pat, args, &fakebuf);       /* what a kludge */
1616     (void)putc('\0', &fakebuf);
1617 #ifdef USE_CHAR_VSPRINTF
1618     return(dest);
1619 #else
1620     return 0;           /* perl doesn't use return value */
1621 #endif
1622 }
1623
1624 #endif /* HAS_VPRINTF */
1625
1626 #ifdef MYSWAP
1627 #if BYTEORDER != 0x4321
1628 short
1629 Perl_my_swap(pTHX_ short s)
1630 {
1631 #if (BYTEORDER & 1) == 0
1632     short result;
1633
1634     result = ((s & 255) << 8) + ((s >> 8) & 255);
1635     return result;
1636 #else
1637     return s;
1638 #endif
1639 }
1640
1641 long
1642 Perl_my_htonl(pTHX_ long l)
1643 {
1644     union {
1645         long result;
1646         char c[sizeof(long)];
1647     } u;
1648
1649 #if BYTEORDER == 0x1234
1650     u.c[0] = (l >> 24) & 255;
1651     u.c[1] = (l >> 16) & 255;
1652     u.c[2] = (l >> 8) & 255;
1653     u.c[3] = l & 255;
1654     return u.result;
1655 #else
1656 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1657     Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1658 #else
1659     register I32 o;
1660     register I32 s;
1661
1662     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1663         u.c[o & 0xf] = (l >> s) & 255;
1664     }
1665     return u.result;
1666 #endif
1667 #endif
1668 }
1669
1670 long
1671 Perl_my_ntohl(pTHX_ long l)
1672 {
1673     union {
1674         long l;
1675         char c[sizeof(long)];
1676     } u;
1677
1678 #if BYTEORDER == 0x1234
1679     u.c[0] = (l >> 24) & 255;
1680     u.c[1] = (l >> 16) & 255;
1681     u.c[2] = (l >> 8) & 255;
1682     u.c[3] = l & 255;
1683     return u.l;
1684 #else
1685 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1686     Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1687 #else
1688     register I32 o;
1689     register I32 s;
1690
1691     u.l = l;
1692     l = 0;
1693     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1694         l |= (u.c[o & 0xf] & 255) << s;
1695     }
1696     return l;
1697 #endif
1698 #endif
1699 }
1700
1701 #endif /* BYTEORDER != 0x4321 */
1702 #endif /* MYSWAP */
1703
1704 /*
1705  * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1706  * If these functions are defined,
1707  * the BYTEORDER is neither 0x1234 nor 0x4321.
1708  * However, this is not assumed.
1709  * -DWS
1710  */
1711
1712 #define HTOLE(name,type)                                        \
1713         type                                                    \
1714         name (register type n)                                  \
1715         {                                                       \
1716             union {                                             \
1717                 type value;                                     \
1718                 char c[sizeof(type)];                           \
1719             } u;                                                \
1720             register I32 i;                                     \
1721             register I32 s = 0;                                 \
1722             for (i = 0; i < sizeof(u.c); i++, s += 8) {         \
1723                 u.c[i] = (n >> s) & 0xFF;                       \
1724             }                                                   \
1725             return u.value;                                     \
1726         }
1727
1728 #define LETOH(name,type)                                        \
1729         type                                                    \
1730         name (register type n)                                  \
1731         {                                                       \
1732             union {                                             \
1733                 type value;                                     \
1734                 char c[sizeof(type)];                           \
1735             } u;                                                \
1736             register I32 i;                                     \
1737             register I32 s = 0;                                 \
1738             u.value = n;                                        \
1739             n = 0;                                              \
1740             for (i = 0; i < sizeof(u.c); i++, s += 8) {         \
1741                 n |= ((type)(u.c[i] & 0xFF)) << s;              \
1742             }                                                   \
1743             return n;                                           \
1744         }
1745
1746 /*
1747  * Big-endian byte order functions.
1748  */
1749
1750 #define HTOBE(name,type)                                        \
1751         type                                                    \
1752         name (register type n)                                  \
1753         {                                                       \
1754             union {                                             \
1755                 type value;                                     \
1756                 char c[sizeof(type)];                           \
1757             } u;                                                \
1758             register I32 i;                                     \
1759             register I32 s = 8*(sizeof(u.c)-1);                 \
1760             for (i = 0; i < sizeof(u.c); i++, s -= 8) {         \
1761                 u.c[i] = (n >> s) & 0xFF;                       \
1762             }                                                   \
1763             return u.value;                                     \
1764         }
1765
1766 #define BETOH(name,type)                                        \
1767         type                                                    \
1768         name (register type n)                                  \
1769         {                                                       \
1770             union {                                             \
1771                 type value;                                     \
1772                 char c[sizeof(type)];                           \
1773             } u;                                                \
1774             register I32 i;                                     \
1775             register I32 s = 8*(sizeof(u.c)-1);                 \
1776             u.value = n;                                        \
1777             n = 0;                                              \
1778             for (i = 0; i < sizeof(u.c); i++, s -= 8) {         \
1779                 n |= ((type)(u.c[i] & 0xFF)) << s;              \
1780             }                                                   \
1781             return n;                                           \
1782         }
1783
1784 /*
1785  * If we just can't do it...
1786  */
1787
1788 #define NOT_AVAIL(name,type)                                    \
1789         type                                                    \
1790         name (register type n)                                  \
1791         {                                                       \
1792             Perl_croak_nocontext(#name "() not available");     \
1793             return n; /* not reached */                         \
1794         }
1795
1796
1797 #if defined(HAS_HTOVS) && !defined(htovs)
1798 HTOLE(htovs,short)
1799 #endif
1800 #if defined(HAS_HTOVL) && !defined(htovl)
1801 HTOLE(htovl,long)
1802 #endif
1803 #if defined(HAS_VTOHS) && !defined(vtohs)
1804 LETOH(vtohs,short)
1805 #endif
1806 #if defined(HAS_VTOHL) && !defined(vtohl)
1807 LETOH(vtohl,long)
1808 #endif
1809
1810 #ifdef PERL_NEED_MY_HTOLE16
1811 # if U16SIZE == 2
1812 HTOLE(Perl_my_htole16,U16)
1813 # else
1814 NOT_AVAIL(Perl_my_htole16,U16)
1815 # endif
1816 #endif
1817 #ifdef PERL_NEED_MY_LETOH16
1818 # if U16SIZE == 2
1819 LETOH(Perl_my_letoh16,U16)
1820 # else
1821 NOT_AVAIL(Perl_my_letoh16,U16)
1822 # endif
1823 #endif
1824 #ifdef PERL_NEED_MY_HTOBE16
1825 # if U16SIZE == 2
1826 HTOBE(Perl_my_htobe16,U16)
1827 # else
1828 NOT_AVAIL(Perl_my_htobe16,U16)
1829 # endif
1830 #endif
1831 #ifdef PERL_NEED_MY_BETOH16
1832 # if U16SIZE == 2
1833 BETOH(Perl_my_betoh16,U16)
1834 # else
1835 NOT_AVAIL(Perl_my_betoh16,U16)
1836 # endif
1837 #endif
1838
1839 #ifdef PERL_NEED_MY_HTOLE32
1840 # if U32SIZE == 4
1841 HTOLE(Perl_my_htole32,U32)
1842 # else
1843 NOT_AVAIL(Perl_my_htole32,U32)
1844 # endif
1845 #endif
1846 #ifdef PERL_NEED_MY_LETOH32
1847 # if U32SIZE == 4
1848 LETOH(Perl_my_letoh32,U32)
1849 # else
1850 NOT_AVAIL(Perl_my_letoh32,U32)
1851 # endif
1852 #endif
1853 #ifdef PERL_NEED_MY_HTOBE32
1854 # if U32SIZE == 4
1855 HTOBE(Perl_my_htobe32,U32)
1856 # else
1857 NOT_AVAIL(Perl_my_htobe32,U32)
1858 # endif
1859 #endif
1860 #ifdef PERL_NEED_MY_BETOH32
1861 # if U32SIZE == 4
1862 BETOH(Perl_my_betoh32,U32)
1863 # else
1864 NOT_AVAIL(Perl_my_betoh32,U32)
1865 # endif
1866 #endif
1867
1868 #ifdef PERL_NEED_MY_HTOLE64
1869 # if U64SIZE == 8
1870 HTOLE(Perl_my_htole64,U64)
1871 # else
1872 NOT_AVAIL(Perl_my_htole64,U64)
1873 # endif
1874 #endif
1875 #ifdef PERL_NEED_MY_LETOH64
1876 # if U64SIZE == 8
1877 LETOH(Perl_my_letoh64,U64)
1878 # else
1879 NOT_AVAIL(Perl_my_letoh64,U64)
1880 # endif
1881 #endif
1882 #ifdef PERL_NEED_MY_HTOBE64
1883 # if U64SIZE == 8
1884 HTOBE(Perl_my_htobe64,U64)
1885 # else
1886 NOT_AVAIL(Perl_my_htobe64,U64)
1887 # endif
1888 #endif
1889 #ifdef PERL_NEED_MY_BETOH64
1890 # if U64SIZE == 8
1891 BETOH(Perl_my_betoh64,U64)
1892 # else
1893 NOT_AVAIL(Perl_my_betoh64,U64)
1894 # endif
1895 #endif
1896
1897 #ifdef PERL_NEED_MY_HTOLES
1898 HTOLE(Perl_my_htoles,short)
1899 #endif
1900 #ifdef PERL_NEED_MY_LETOHS
1901 LETOH(Perl_my_letohs,short)
1902 #endif
1903 #ifdef PERL_NEED_MY_HTOBES
1904 HTOBE(Perl_my_htobes,short)
1905 #endif
1906 #ifdef PERL_NEED_MY_BETOHS
1907 BETOH(Perl_my_betohs,short)
1908 #endif
1909
1910 #ifdef PERL_NEED_MY_HTOLEI
1911 HTOLE(Perl_my_htolei,int)
1912 #endif
1913 #ifdef PERL_NEED_MY_LETOHI
1914 LETOH(Perl_my_letohi,int)
1915 #endif
1916 #ifdef PERL_NEED_MY_HTOBEI
1917 HTOBE(Perl_my_htobei,int)
1918 #endif
1919 #ifdef PERL_NEED_MY_BETOHI
1920 BETOH(Perl_my_betohi,int)
1921 #endif
1922
1923 #ifdef PERL_NEED_MY_HTOLEL
1924 HTOLE(Perl_my_htolel,long)
1925 #endif
1926 #ifdef PERL_NEED_MY_LETOHL
1927 LETOH(Perl_my_letohl,long)
1928 #endif
1929 #ifdef PERL_NEED_MY_HTOBEL
1930 HTOBE(Perl_my_htobel,long)
1931 #endif
1932 #ifdef PERL_NEED_MY_BETOHL
1933 BETOH(Perl_my_betohl,long)
1934 #endif
1935
1936 void
1937 Perl_my_swabn(void *ptr, int n)
1938 {
1939     register char *s = (char *)ptr;
1940     register char *e = s + (n-1);
1941     register char tc;
1942
1943     for (n /= 2; n > 0; s++, e--, n--) {
1944       tc = *s;
1945       *s = *e;
1946       *e = tc;
1947     }
1948 }
1949
1950 PerlIO *
1951 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
1952 {
1953 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
1954     int p[2];
1955     register I32 This, that;
1956     register Pid_t pid;
1957     SV *sv;
1958     I32 did_pipes = 0;
1959     int pp[2];
1960
1961     PERL_FLUSHALL_FOR_CHILD;
1962     This = (*mode == 'w');
1963     that = !This;
1964     if (PL_tainting) {
1965         taint_env();
1966         taint_proper("Insecure %s%s", "EXEC");
1967     }
1968     if (PerlProc_pipe(p) < 0)
1969         return Nullfp;
1970     /* Try for another pipe pair for error return */
1971     if (PerlProc_pipe(pp) >= 0)
1972         did_pipes = 1;
1973     while ((pid = PerlProc_fork()) < 0) {
1974         if (errno != EAGAIN) {
1975             PerlLIO_close(p[This]);
1976             PerlLIO_close(p[that]);
1977             if (did_pipes) {
1978                 PerlLIO_close(pp[0]);
1979                 PerlLIO_close(pp[1]);
1980             }
1981             return Nullfp;
1982         }
1983         sleep(5);
1984     }
1985     if (pid == 0) {
1986         /* Child */
1987 #undef THIS
1988 #undef THAT
1989 #define THIS that
1990 #define THAT This
1991         /* Close parent's end of error status pipe (if any) */
1992         if (did_pipes) {
1993             PerlLIO_close(pp[0]);
1994 #if defined(HAS_FCNTL) && defined(F_SETFD)
1995             /* Close error pipe automatically if exec works */
1996             fcntl(pp[1], F_SETFD, FD_CLOEXEC);
1997 #endif
1998         }
1999         /* Now dup our end of _the_ pipe to right position */
2000         if (p[THIS] != (*mode == 'r')) {
2001             PerlLIO_dup2(p[THIS], *mode == 'r');
2002             PerlLIO_close(p[THIS]);
2003             if (p[THAT] != (*mode == 'r'))      /* if dup2() didn't close it */
2004                 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2005         }
2006         else
2007             PerlLIO_close(p[THAT]);     /* close parent's end of _the_ pipe */
2008 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2009         /* No automatic close - do it by hand */
2010 #  ifndef NOFILE
2011 #  define NOFILE 20
2012 #  endif
2013         {
2014             int fd;
2015
2016             for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2017                 if (fd != pp[1])
2018                     PerlLIO_close(fd);
2019             }
2020         }
2021 #endif
2022         do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
2023         PerlProc__exit(1);
2024 #undef THIS
2025 #undef THAT
2026     }
2027     /* Parent */
2028     do_execfree();      /* free any memory malloced by child on fork */
2029     if (did_pipes)
2030         PerlLIO_close(pp[1]);
2031     /* Keep the lower of the two fd numbers */
2032     if (p[that] < p[This]) {
2033         PerlLIO_dup2(p[This], p[that]);
2034         PerlLIO_close(p[This]);
2035         p[This] = p[that];
2036     }
2037     else
2038         PerlLIO_close(p[that]);         /* close child's end of pipe */
2039
2040     LOCK_FDPID_MUTEX;
2041     sv = *av_fetch(PL_fdpid,p[This],TRUE);
2042     UNLOCK_FDPID_MUTEX;
2043     (void)SvUPGRADE(sv,SVt_IV);
2044     SvIV_set(sv, pid);
2045     PL_forkprocess = pid;
2046     /* If we managed to get status pipe check for exec fail */
2047     if (did_pipes && pid > 0) {
2048         int errkid;
2049         int n = 0, n1;
2050
2051         while (n < sizeof(int)) {
2052             n1 = PerlLIO_read(pp[0],
2053                               (void*)(((char*)&errkid)+n),
2054                               (sizeof(int)) - n);
2055             if (n1 <= 0)
2056                 break;
2057             n += n1;
2058         }
2059         PerlLIO_close(pp[0]);
2060         did_pipes = 0;
2061         if (n) {                        /* Error */
2062             int pid2, status;
2063             PerlLIO_close(p[This]);
2064             if (n != sizeof(int))
2065                 Perl_croak(aTHX_ "panic: kid popen errno read");
2066             do {
2067                 pid2 = wait4pid(pid, &status, 0);
2068             } while (pid2 == -1 && errno == EINTR);
2069             errno = errkid;             /* Propagate errno from kid */
2070             return Nullfp;
2071         }
2072     }
2073     if (did_pipes)
2074          PerlLIO_close(pp[0]);
2075     return PerlIO_fdopen(p[This], mode);
2076 #else
2077     Perl_croak(aTHX_ "List form of piped open not implemented");
2078     return (PerlIO *) NULL;
2079 #endif
2080 }
2081
2082     /* VMS' my_popen() is in VMS.c, same with OS/2. */
2083 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2084 PerlIO *
2085 Perl_my_popen(pTHX_ char *cmd, char *mode)
2086 {
2087     int p[2];
2088     register I32 This, that;
2089     register Pid_t pid;
2090     SV *sv;
2091     I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2092     I32 did_pipes = 0;
2093     int pp[2];
2094
2095     PERL_FLUSHALL_FOR_CHILD;
2096 #ifdef OS2
2097     if (doexec) {
2098         return my_syspopen(aTHX_ cmd,mode);
2099     }
2100 #endif
2101     This = (*mode == 'w');
2102     that = !This;
2103     if (doexec && PL_tainting) {
2104         taint_env();
2105         taint_proper("Insecure %s%s", "EXEC");
2106     }
2107     if (PerlProc_pipe(p) < 0)
2108         return Nullfp;
2109     if (doexec && PerlProc_pipe(pp) >= 0)
2110         did_pipes = 1;
2111     while ((pid = PerlProc_fork()) < 0) {
2112         if (errno != EAGAIN) {
2113             PerlLIO_close(p[This]);
2114             PerlLIO_close(p[that]);
2115             if (did_pipes) {
2116                 PerlLIO_close(pp[0]);
2117                 PerlLIO_close(pp[1]);
2118             }
2119             if (!doexec)
2120                 Perl_croak(aTHX_ "Can't fork");
2121             return Nullfp;
2122         }
2123         sleep(5);
2124     }
2125     if (pid == 0) {
2126         GV* tmpgv;
2127
2128 #undef THIS
2129 #undef THAT
2130 #define THIS that
2131 #define THAT This
2132         if (did_pipes) {
2133             PerlLIO_close(pp[0]);
2134 #if defined(HAS_FCNTL) && defined(F_SETFD)
2135             fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2136 #endif
2137         }
2138         if (p[THIS] != (*mode == 'r')) {
2139             PerlLIO_dup2(p[THIS], *mode == 'r');
2140             PerlLIO_close(p[THIS]);
2141             if (p[THAT] != (*mode == 'r'))      /* if dup2() didn't close it */
2142                 PerlLIO_close(p[THAT]);
2143         }
2144         else
2145             PerlLIO_close(p[THAT]);
2146 #ifndef OS2
2147         if (doexec) {
2148 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2149             int fd;
2150
2151 #ifndef NOFILE
2152 #define NOFILE 20
2153 #endif
2154             {
2155                 int fd;
2156
2157                 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2158                     if (fd != pp[1])
2159                         PerlLIO_close(fd);
2160             }
2161 #endif
2162             /* may or may not use the shell */
2163             do_exec3(cmd, pp[1], did_pipes);
2164             PerlProc__exit(1);
2165         }
2166 #endif  /* defined OS2 */
2167         /*SUPPRESS 560*/
2168         if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
2169             SvREADONLY_off(GvSV(tmpgv));
2170             sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2171             SvREADONLY_on(GvSV(tmpgv));
2172         }
2173 #ifdef THREADS_HAVE_PIDS
2174         PL_ppid = (IV)getppid();
2175 #endif
2176         PL_forkprocess = 0;
2177         hv_clear(PL_pidstatus); /* we have no children */
2178         return Nullfp;
2179 #undef THIS
2180 #undef THAT
2181     }
2182     do_execfree();      /* free any memory malloced by child on vfork */
2183     if (did_pipes)
2184         PerlLIO_close(pp[1]);
2185     if (p[that] < p[This]) {
2186         PerlLIO_dup2(p[This], p[that]);
2187         PerlLIO_close(p[This]);
2188         p[This] = p[that];
2189     }
2190     else
2191         PerlLIO_close(p[that]);
2192
2193     LOCK_FDPID_MUTEX;
2194     sv = *av_fetch(PL_fdpid,p[This],TRUE);
2195     UNLOCK_FDPID_MUTEX;
2196     (void)SvUPGRADE(sv,SVt_IV);
2197     SvIV_set(sv, pid);
2198     PL_forkprocess = pid;
2199     if (did_pipes && pid > 0) {
2200         int errkid;
2201         int n = 0, n1;
2202
2203         while (n < sizeof(int)) {
2204             n1 = PerlLIO_read(pp[0],
2205                               (void*)(((char*)&errkid)+n),
2206                               (sizeof(int)) - n);
2207             if (n1 <= 0)
2208                 break;
2209             n += n1;
2210         }
2211         PerlLIO_close(pp[0]);
2212         did_pipes = 0;
2213         if (n) {                        /* Error */
2214             int pid2, status;
2215             PerlLIO_close(p[This]);
2216             if (n != sizeof(int))
2217                 Perl_croak(aTHX_ "panic: kid popen errno read");
2218             do {
2219                 pid2 = wait4pid(pid, &status, 0);
2220             } while (pid2 == -1 && errno == EINTR);
2221             errno = errkid;             /* Propagate errno from kid */
2222             return Nullfp;
2223         }
2224     }
2225     if (did_pipes)
2226          PerlLIO_close(pp[0]);
2227     return PerlIO_fdopen(p[This], mode);
2228 }
2229 #else
2230 #if defined(atarist) || defined(EPOC)
2231 FILE *popen();
2232 PerlIO *
2233 Perl_my_popen(pTHX_ char *cmd, char *mode)
2234 {
2235     PERL_FLUSHALL_FOR_CHILD;
2236     /* Call system's popen() to get a FILE *, then import it.
2237        used 0 for 2nd parameter to PerlIO_importFILE;
2238        apparently not used
2239     */
2240     return PerlIO_importFILE(popen(cmd, mode), 0);
2241 }
2242 #else
2243 #if defined(DJGPP)
2244 FILE *djgpp_popen();
2245 PerlIO *
2246 Perl_my_popen(pTHX_ char *cmd, char *mode)
2247 {
2248     PERL_FLUSHALL_FOR_CHILD;
2249     /* Call system's popen() to get a FILE *, then import it.
2250        used 0 for 2nd parameter to PerlIO_importFILE;
2251        apparently not used
2252     */
2253     return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2254 }
2255 #endif
2256 #endif
2257
2258 #endif /* !DOSISH */
2259
2260 /* this is called in parent before the fork() */
2261 void
2262 Perl_atfork_lock(void)
2263 {
2264 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2265     /* locks must be held in locking order (if any) */
2266 #  ifdef MYMALLOC
2267     MUTEX_LOCK(&PL_malloc_mutex);
2268 #  endif
2269     OP_REFCNT_LOCK;
2270 #endif
2271 }
2272
2273 /* this is called in both parent and child after the fork() */
2274 void
2275 Perl_atfork_unlock(void)
2276 {
2277 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2278     /* locks must be released in same order as in atfork_lock() */
2279 #  ifdef MYMALLOC
2280     MUTEX_UNLOCK(&PL_malloc_mutex);
2281 #  endif
2282     OP_REFCNT_UNLOCK;
2283 #endif
2284 }
2285
2286 Pid_t
2287 Perl_my_fork(void)
2288 {
2289 #if defined(HAS_FORK)
2290     Pid_t pid;
2291 #if (defined(USE_5005THREADS) || defined(USE_ITHREADS)) && !defined(HAS_PTHREAD_ATFORK)
2292     atfork_lock();
2293     pid = fork();
2294     atfork_unlock();
2295 #else
2296     /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2297      * handlers elsewhere in the code */
2298     pid = fork();
2299 #endif
2300     return pid;
2301 #else
2302     /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2303     Perl_croak_nocontext("fork() not available");
2304     return 0;
2305 #endif /* HAS_FORK */
2306 }
2307
2308 #ifdef DUMP_FDS
2309 void
2310 Perl_dump_fds(pTHX_ char *s)
2311 {
2312     int fd;
2313     Stat_t tmpstatbuf;
2314
2315     PerlIO_printf(Perl_debug_log,"%s", s);
2316     for (fd = 0; fd < 32; fd++) {
2317         if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2318             PerlIO_printf(Perl_debug_log," %d",fd);
2319     }
2320     PerlIO_printf(Perl_debug_log,"\n");
2321 }
2322 #endif  /* DUMP_FDS */
2323
2324 #ifndef HAS_DUP2
2325 int
2326 dup2(int oldfd, int newfd)
2327 {
2328 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2329     if (oldfd == newfd)
2330         return oldfd;
2331     PerlLIO_close(newfd);
2332     return fcntl(oldfd, F_DUPFD, newfd);
2333 #else
2334 #define DUP2_MAX_FDS 256
2335     int fdtmp[DUP2_MAX_FDS];
2336     I32 fdx = 0;
2337     int fd;
2338
2339     if (oldfd == newfd)
2340         return oldfd;
2341     PerlLIO_close(newfd);
2342     /* good enough for low fd's... */
2343     while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2344         if (fdx >= DUP2_MAX_FDS) {
2345             PerlLIO_close(fd);
2346             fd = -1;
2347             break;
2348         }
2349         fdtmp[fdx++] = fd;
2350     }
2351     while (fdx > 0)
2352         PerlLIO_close(fdtmp[--fdx]);
2353     return fd;
2354 #endif
2355 }
2356 #endif
2357
2358 #ifndef PERL_MICRO
2359 #ifdef HAS_SIGACTION
2360
2361 #ifdef MACOS_TRADITIONAL
2362 /* We don't want restart behavior on MacOS */
2363 #undef SA_RESTART
2364 #endif
2365
2366 Sighandler_t
2367 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2368 {
2369     struct sigaction act, oact;
2370
2371 #ifdef USE_ITHREADS
2372     /* only "parent" interpreter can diddle signals */
2373     if (PL_curinterp != aTHX)
2374         return SIG_ERR;
2375 #endif
2376
2377     act.sa_handler = handler;
2378     sigemptyset(&act.sa_mask);
2379     act.sa_flags = 0;
2380 #ifdef SA_RESTART
2381     if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2382         act.sa_flags |= SA_RESTART;     /* SVR4, 4.3+BSD */
2383 #endif
2384 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2385     if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2386         act.sa_flags |= SA_NOCLDWAIT;
2387 #endif
2388     if (sigaction(signo, &act, &oact) == -1)
2389         return SIG_ERR;
2390     else
2391         return oact.sa_handler;
2392 }
2393
2394 Sighandler_t
2395 Perl_rsignal_state(pTHX_ int signo)
2396 {
2397     struct sigaction oact;
2398
2399     if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2400         return SIG_ERR;
2401     else
2402         return oact.sa_handler;
2403 }
2404
2405 int
2406 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2407 {
2408     struct sigaction act;
2409
2410 #ifdef USE_ITHREADS
2411     /* only "parent" interpreter can diddle signals */
2412     if (PL_curinterp != aTHX)
2413         return -1;
2414 #endif
2415
2416     act.sa_handler = handler;
2417     sigemptyset(&act.sa_mask);
2418     act.sa_flags = 0;
2419 #ifdef SA_RESTART
2420     if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2421         act.sa_flags |= SA_RESTART;     /* SVR4, 4.3+BSD */
2422 #endif
2423 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2424     if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2425         act.sa_flags |= SA_NOCLDWAIT;
2426 #endif
2427     return sigaction(signo, &act, save);
2428 }
2429
2430 int
2431 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2432 {
2433 #ifdef USE_ITHREADS
2434     /* only "parent" interpreter can diddle signals */
2435     if (PL_curinterp != aTHX)
2436         return -1;
2437 #endif
2438
2439     return sigaction(signo, save, (struct sigaction *)NULL);
2440 }
2441
2442 #else /* !HAS_SIGACTION */
2443
2444 Sighandler_t
2445 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2446 {
2447 #if defined(USE_ITHREADS) && !defined(WIN32)
2448     /* only "parent" interpreter can diddle signals */
2449     if (PL_curinterp != aTHX)
2450         return SIG_ERR;
2451 #endif
2452
2453     return PerlProc_signal(signo, handler);
2454 }
2455
2456 static int sig_trapped; /* XXX signals are process-wide anyway, so we
2457                            ignore the implications of this for threading */
2458
2459 static
2460 Signal_t
2461 sig_trap(int signo)
2462 {
2463     sig_trapped++;
2464 }
2465
2466 Sighandler_t
2467 Perl_rsignal_state(pTHX_ int signo)
2468 {
2469     Sighandler_t oldsig;
2470
2471 #if defined(USE_ITHREADS) && !defined(WIN32)
2472     /* only "parent" interpreter can diddle signals */
2473     if (PL_curinterp != aTHX)
2474         return SIG_ERR;
2475 #endif
2476
2477     sig_trapped = 0;
2478     oldsig = PerlProc_signal(signo, sig_trap);
2479     PerlProc_signal(signo, oldsig);
2480     if (sig_trapped)
2481         PerlProc_kill(PerlProc_getpid(), signo);
2482     return oldsig;
2483 }
2484
2485 int
2486 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2487 {
2488 #if defined(USE_ITHREADS) && !defined(WIN32)
2489     /* only "parent" interpreter can diddle signals */
2490     if (PL_curinterp != aTHX)
2491         return -1;
2492 #endif
2493     *save = PerlProc_signal(signo, handler);
2494     return (*save == SIG_ERR) ? -1 : 0;
2495 }
2496
2497 int
2498 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2499 {
2500 #if defined(USE_ITHREADS) && !defined(WIN32)
2501     /* only "parent" interpreter can diddle signals */
2502     if (PL_curinterp != aTHX)
2503         return -1;
2504 #endif
2505     return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2506 }
2507
2508 #endif /* !HAS_SIGACTION */
2509 #endif /* !PERL_MICRO */
2510
2511     /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2512 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2513 I32
2514 Perl_my_pclose(pTHX_ PerlIO *ptr)
2515 {
2516     Sigsave_t hstat, istat, qstat;
2517     int status;
2518     SV **svp;
2519     Pid_t pid;
2520     Pid_t pid2;
2521     bool close_failed;
2522     int saved_errno = 0;
2523 #ifdef VMS
2524     int saved_vaxc_errno;
2525 #endif
2526 #ifdef WIN32
2527     int saved_win32_errno;
2528 #endif
2529
2530     LOCK_FDPID_MUTEX;
2531     svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2532     UNLOCK_FDPID_MUTEX;
2533     pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2534     SvREFCNT_dec(*svp);
2535     *svp = &PL_sv_undef;
2536 #ifdef OS2
2537     if (pid == -1) {                    /* Opened by popen. */
2538         return my_syspclose(ptr);
2539     }
2540 #endif
2541     if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2542         saved_errno = errno;
2543 #ifdef VMS
2544         saved_vaxc_errno = vaxc$errno;
2545 #endif
2546 #ifdef WIN32
2547         saved_win32_errno = GetLastError();
2548 #endif
2549     }
2550 #ifdef UTS
2551     if(PerlProc_kill(pid, 0) < 0) { return(pid); }   /* HOM 12/23/91 */
2552 #endif
2553 #ifndef PERL_MICRO
2554     rsignal_save(SIGHUP, SIG_IGN, &hstat);
2555     rsignal_save(SIGINT, SIG_IGN, &istat);
2556     rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2557 #endif
2558     do {
2559         pid2 = wait4pid(pid, &status, 0);
2560     } while (pid2 == -1 && errno == EINTR);
2561 #ifndef PERL_MICRO
2562     rsignal_restore(SIGHUP, &hstat);
2563     rsignal_restore(SIGINT, &istat);
2564     rsignal_restore(SIGQUIT, &qstat);
2565 #endif
2566     if (close_failed) {
2567         SETERRNO(saved_errno, saved_vaxc_errno);
2568         return -1;
2569     }
2570     return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2571 }
2572 #endif /* !DOSISH */
2573
2574 #if  (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2575 I32
2576 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2577 {
2578     I32 result;
2579     if (!pid)
2580         return -1;
2581 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2582     {
2583         SV *sv;
2584         SV** svp;
2585         char spid[TYPE_CHARS(IV)];
2586
2587         if (pid > 0) {
2588             sprintf(spid, "%"IVdf, (IV)pid);
2589             svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2590             if (svp && *svp != &PL_sv_undef) {
2591                 *statusp = SvIVX(*svp);
2592                 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2593                 return pid;
2594             }
2595         }
2596         else {
2597             HE *entry;
2598
2599             hv_iterinit(PL_pidstatus);
2600             if ((entry = hv_iternext(PL_pidstatus))) {
2601                 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2602                 sv = hv_iterval(PL_pidstatus,entry);
2603                 *statusp = SvIVX(sv);
2604                 sprintf(spid, "%"IVdf, (IV)pid);
2605                 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2606                 return pid;
2607             }
2608         }
2609     }
2610 #endif
2611 #ifdef HAS_WAITPID
2612 #  ifdef HAS_WAITPID_RUNTIME
2613     if (!HAS_WAITPID_RUNTIME)
2614         goto hard_way;
2615 #  endif
2616     result = PerlProc_waitpid(pid,statusp,flags);
2617     goto finish;
2618 #endif
2619 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2620     result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2621     goto finish;
2622 #endif
2623 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2624   hard_way:
2625     {
2626         if (flags)
2627             Perl_croak(aTHX_ "Can't do waitpid with flags");
2628         else {
2629             while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2630                 pidgone(result,*statusp);
2631             if (result < 0)
2632                 *statusp = -1;
2633         }
2634     }
2635 #endif
2636   finish:
2637     if (result < 0 && errno == EINTR) {
2638         PERL_ASYNC_CHECK();
2639     }
2640     return result;
2641 }
2642 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2643
2644 void
2645 /*SUPPRESS 590*/
2646 Perl_pidgone(pTHX_ Pid_t pid, int status)
2647 {
2648     register SV *sv;
2649     char spid[TYPE_CHARS(IV)];
2650
2651     sprintf(spid, "%"IVdf, (IV)pid);
2652     sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2653     (void)SvUPGRADE(sv,SVt_IV);
2654     SvIV_set(sv, status);
2655     return;
2656 }
2657
2658 #if defined(atarist) || defined(OS2) || defined(EPOC)
2659 int pclose();
2660 #ifdef HAS_FORK
2661 int                                     /* Cannot prototype with I32
2662                                            in os2ish.h. */
2663 my_syspclose(PerlIO *ptr)
2664 #else
2665 I32
2666 Perl_my_pclose(pTHX_ PerlIO *ptr)
2667 #endif
2668 {
2669     /* Needs work for PerlIO ! */
2670     FILE *f = PerlIO_findFILE(ptr);
2671     I32 result = pclose(f);
2672     PerlIO_releaseFILE(ptr,f);
2673     return result;
2674 }
2675 #endif
2676
2677 #if defined(DJGPP)
2678 int djgpp_pclose();
2679 I32
2680 Perl_my_pclose(pTHX_ PerlIO *ptr)
2681 {
2682     /* Needs work for PerlIO ! */
2683     FILE *f = PerlIO_findFILE(ptr);
2684     I32 result = djgpp_pclose(f);
2685     result = (result << 8) & 0xff00;
2686     PerlIO_releaseFILE(ptr,f);
2687     return result;
2688 }
2689 #endif
2690
2691 void
2692 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2693 {
2694     register I32 todo;
2695     register const char *frombase = from;
2696
2697     if (len == 1) {
2698         register const char c = *from;
2699         while (count-- > 0)
2700             *to++ = c;
2701         return;
2702     }
2703     while (count-- > 0) {
2704         for (todo = len; todo > 0; todo--) {
2705             *to++ = *from++;
2706         }
2707         from = frombase;
2708     }
2709 }
2710
2711 #ifndef HAS_RENAME
2712 I32
2713 Perl_same_dirent(pTHX_ char *a, char *b)
2714 {
2715     char *fa = strrchr(a,'/');
2716     char *fb = strrchr(b,'/');
2717     Stat_t tmpstatbuf1;
2718     Stat_t tmpstatbuf2;
2719     SV *tmpsv = sv_newmortal();
2720
2721     if (fa)
2722         fa++;
2723     else
2724         fa = a;
2725     if (fb)
2726         fb++;
2727     else
2728         fb = b;
2729     if (strNE(a,b))
2730         return FALSE;
2731     if (fa == a)
2732         sv_setpvn(tmpsv, ".", 1);
2733     else
2734         sv_setpvn(tmpsv, a, fa - a);
2735     if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
2736         return FALSE;
2737     if (fb == b)
2738         sv_setpvn(tmpsv, ".", 1);
2739     else
2740         sv_setpvn(tmpsv, b, fb - b);
2741     if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
2742         return FALSE;
2743     return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2744            tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2745 }
2746 #endif /* !HAS_RENAME */
2747
2748 char*
2749 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
2750 {
2751     const char *xfound = Nullch;
2752     char *xfailed = Nullch;
2753     char tmpbuf[MAXPATHLEN];
2754     register char *s;
2755     I32 len = 0;
2756     int retval;
2757 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2758 #  define SEARCH_EXTS ".bat", ".cmd", NULL
2759 #  define MAX_EXT_LEN 4
2760 #endif
2761 #ifdef OS2
2762 #  define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2763 #  define MAX_EXT_LEN 4
2764 #endif
2765 #ifdef VMS
2766 #  define SEARCH_EXTS ".pl", ".com", NULL
2767 #  define MAX_EXT_LEN 4
2768 #endif
2769     /* additional extensions to try in each dir if scriptname not found */
2770 #ifdef SEARCH_EXTS
2771     const char *exts[] = { SEARCH_EXTS };
2772     const char **ext = search_ext ? search_ext : exts;
2773     int extidx = 0, i = 0;
2774     const char *curext = Nullch;
2775 #else
2776     (void)search_ext;
2777 #  define MAX_EXT_LEN 0
2778 #endif
2779
2780     /*
2781      * If dosearch is true and if scriptname does not contain path
2782      * delimiters, search the PATH for scriptname.
2783      *
2784      * If SEARCH_EXTS is also defined, will look for each
2785      * scriptname{SEARCH_EXTS} whenever scriptname is not found
2786      * while searching the PATH.
2787      *
2788      * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2789      * proceeds as follows:
2790      *   If DOSISH or VMSISH:
2791      *     + look for ./scriptname{,.foo,.bar}
2792      *     + search the PATH for scriptname{,.foo,.bar}
2793      *
2794      *   If !DOSISH:
2795      *     + look *only* in the PATH for scriptname{,.foo,.bar} (note
2796      *       this will not look in '.' if it's not in the PATH)
2797      */
2798     tmpbuf[0] = '\0';
2799
2800 #ifdef VMS
2801 #  ifdef ALWAYS_DEFTYPES
2802     len = strlen(scriptname);
2803     if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2804         int hasdir, idx = 0, deftypes = 1;
2805         bool seen_dot = 1;
2806
2807         hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2808 #  else
2809     if (dosearch) {
2810         int hasdir, idx = 0, deftypes = 1;
2811         bool seen_dot = 1;
2812
2813         hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2814 #  endif
2815         /* The first time through, just add SEARCH_EXTS to whatever we
2816          * already have, so we can check for default file types. */
2817         while (deftypes ||
2818                (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2819         {
2820             if (deftypes) {
2821                 deftypes = 0;
2822                 *tmpbuf = '\0';
2823             }
2824             if ((strlen(tmpbuf) + strlen(scriptname)
2825                  + MAX_EXT_LEN) >= sizeof tmpbuf)
2826                 continue;       /* don't search dir with too-long name */
2827             strcat(tmpbuf, scriptname);
2828 #else  /* !VMS */
2829
2830 #ifdef DOSISH
2831     if (strEQ(scriptname, "-"))
2832         dosearch = 0;
2833     if (dosearch) {             /* Look in '.' first. */
2834         char *cur = scriptname;
2835 #ifdef SEARCH_EXTS
2836         if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2837             while (ext[i])
2838                 if (strEQ(ext[i++],curext)) {
2839                     extidx = -1;                /* already has an ext */
2840                     break;
2841                 }
2842         do {
2843 #endif
2844             DEBUG_p(PerlIO_printf(Perl_debug_log,
2845                                   "Looking for %s\n",cur));
2846             if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2847                 && !S_ISDIR(PL_statbuf.st_mode)) {
2848                 dosearch = 0;
2849                 scriptname = cur;
2850 #ifdef SEARCH_EXTS
2851                 break;
2852 #endif
2853             }
2854 #ifdef SEARCH_EXTS
2855             if (cur == scriptname) {
2856                 len = strlen(scriptname);
2857                 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2858                     break;
2859                 cur = strcpy(tmpbuf, scriptname);
2860             }
2861         } while (extidx >= 0 && ext[extidx]     /* try an extension? */
2862                  && strcpy(tmpbuf+len, ext[extidx++]));
2863 #endif
2864     }
2865 #endif
2866
2867 #ifdef MACOS_TRADITIONAL
2868     if (dosearch && !strchr(scriptname, ':') &&
2869         (s = PerlEnv_getenv("Commands")))
2870 #else
2871     if (dosearch && !strchr(scriptname, '/')
2872 #ifdef DOSISH
2873                  && !strchr(scriptname, '\\')
2874 #endif
2875                  && (s = PerlEnv_getenv("PATH")))
2876 #endif
2877     {
2878         bool seen_dot = 0;
2879         
2880         PL_bufend = s + strlen(s);
2881         while (s < PL_bufend) {
2882 #ifdef MACOS_TRADITIONAL
2883             s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2884                         ',',
2885                         &len);
2886 #else
2887 #if defined(atarist) || defined(DOSISH)
2888             for (len = 0; *s
2889 #  ifdef atarist
2890                     && *s != ','
2891 #  endif
2892                     && *s != ';'; len++, s++) {
2893                 if (len < sizeof tmpbuf)
2894                     tmpbuf[len] = *s;
2895             }
2896             if (len < sizeof tmpbuf)
2897                 tmpbuf[len] = '\0';
2898 #else  /* ! (atarist || DOSISH) */
2899             s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2900                         ':',
2901                         &len);
2902 #endif /* ! (atarist || DOSISH) */
2903 #endif /* MACOS_TRADITIONAL */
2904             if (s < PL_bufend)
2905                 s++;
2906             if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2907                 continue;       /* don't search dir with too-long name */
2908 #ifdef MACOS_TRADITIONAL
2909             if (len && tmpbuf[len - 1] != ':')
2910                 tmpbuf[len++] = ':';
2911 #else
2912             if (len
2913 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2914                 && tmpbuf[len - 1] != '/'
2915                 && tmpbuf[len - 1] != '\\'
2916 #endif
2917                )
2918                 tmpbuf[len++] = '/';
2919             if (len == 2 && tmpbuf[0] == '.')
2920                 seen_dot = 1;
2921 #endif
2922             (void)strcpy(tmpbuf + len, scriptname);
2923 #endif  /* !VMS */
2924
2925 #ifdef SEARCH_EXTS
2926             len = strlen(tmpbuf);
2927             if (extidx > 0)     /* reset after previous loop */
2928                 extidx = 0;
2929             do {
2930 #endif
2931                 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2932                 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2933                 if (S_ISDIR(PL_statbuf.st_mode)) {
2934                     retval = -1;
2935                 }
2936 #ifdef SEARCH_EXTS
2937             } while (  retval < 0               /* not there */
2938                     && extidx>=0 && ext[extidx] /* try an extension? */
2939                     && strcpy(tmpbuf+len, ext[extidx++])
2940                 );
2941 #endif
2942             if (retval < 0)
2943                 continue;
2944             if (S_ISREG(PL_statbuf.st_mode)
2945                 && cando(S_IRUSR,TRUE,&PL_statbuf)
2946 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
2947                 && cando(S_IXUSR,TRUE,&PL_statbuf)
2948 #endif
2949                 )
2950             {
2951                 xfound = tmpbuf;                /* bingo! */
2952                 break;
2953             }
2954             if (!xfailed)
2955                 xfailed = savepv(tmpbuf);
2956         }
2957 #ifndef DOSISH
2958         if (!xfound && !seen_dot && !xfailed &&
2959             (PerlLIO_stat(scriptname,&PL_statbuf) < 0
2960              || S_ISDIR(PL_statbuf.st_mode)))
2961 #endif
2962             seen_dot = 1;                       /* Disable message. */
2963         if (!xfound) {
2964             if (flags & 1) {                    /* do or die? */
2965                 Perl_croak(aTHX_ "Can't %s %s%s%s",
2966                       (xfailed ? "execute" : "find"),
2967                       (xfailed ? xfailed : scriptname),
2968                       (xfailed ? "" : " on PATH"),
2969                       (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2970             }
2971             scriptname = Nullch;
2972         }
2973         if (xfailed)
2974             Safefree(xfailed);
2975         scriptname = xfound;
2976     }
2977     return (scriptname ? savepv(scriptname) : Nullch);
2978 }
2979
2980 #ifndef PERL_GET_CONTEXT_DEFINED
2981
2982 void *
2983 Perl_get_context(void)
2984 {
2985 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2986 #  ifdef OLD_PTHREADS_API
2987     pthread_addr_t t;
2988     if (pthread_getspecific(PL_thr_key, &t))
2989         Perl_croak_nocontext("panic: pthread_getspecific");
2990     return (void*)t;
2991 #  else
2992 #    ifdef I_MACH_CTHREADS
2993     return (void*)cthread_data(cthread_self());
2994 #    else
2995     return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
2996 #    endif
2997 #  endif
2998 #else
2999     return (void*)NULL;
3000 #endif
3001 }
3002
3003 void
3004 Perl_set_context(void *t)
3005 {
3006 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
3007 #  ifdef I_MACH_CTHREADS
3008     cthread_set_data(cthread_self(), t);
3009 #  else
3010     if (pthread_setspecific(PL_thr_key, t))
3011         Perl_croak_nocontext("panic: pthread_setspecific");
3012 #  endif
3013 #else
3014     (void)t;
3015 #endif
3016 }
3017
3018 #endif /* !PERL_GET_CONTEXT_DEFINED */
3019
3020 #ifdef USE_5005THREADS
3021
3022 #ifdef FAKE_THREADS
3023 /* Very simplistic scheduler for now */
3024 void
3025 schedule(void)
3026 {
3027     thr = thr->i.next_run;
3028 }
3029
3030 void
3031 Perl_cond_init(pTHX_ perl_cond *cp)
3032 {
3033     *cp = 0;
3034 }
3035
3036 void
3037 Perl_cond_signal(pTHX_ perl_cond *cp)
3038 {
3039     perl_os_thread t;
3040     perl_cond cond = *cp;
3041
3042     if (!cond)
3043         return;
3044     t = cond->thread;
3045     /* Insert t in the runnable queue just ahead of us */
3046     t->i.next_run = thr->i.next_run;
3047     thr->i.next_run->i.prev_run = t;
3048     t->i.prev_run = thr;
3049     thr->i.next_run = t;
3050     thr->i.wait_queue = 0;
3051     /* Remove from the wait queue */
3052     *cp = cond->next;
3053     Safefree(cond);
3054 }
3055
3056 void
3057 Perl_cond_broadcast(pTHX_ perl_cond *cp)
3058 {
3059     perl_os_thread t;
3060     perl_cond cond, cond_next;
3061
3062     for (cond = *cp; cond; cond = cond_next) {
3063         t = cond->thread;
3064         /* Insert t in the runnable queue just ahead of us */
3065         t->i.next_run = thr->i.next_run;
3066         thr->i.next_run->i.prev_run = t;
3067         t->i.prev_run = thr;
3068         thr->i.next_run = t;
3069         thr->i.wait_queue = 0;
3070         /* Remove from the wait queue */
3071         cond_next = cond->next;
3072         Safefree(cond);
3073     }
3074     *cp = 0;
3075 }
3076
3077 void
3078 Perl_cond_wait(pTHX_ perl_cond *cp)
3079 {
3080     perl_cond cond;
3081
3082     if (thr->i.next_run == thr)
3083         Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3084
3085     New(666, cond, 1, struct perl_wait_queue);
3086     cond->thread = thr;
3087     cond->next = *cp;
3088     *cp = cond;
3089     thr->i.wait_queue = cond;
3090     /* Remove ourselves from runnable queue */
3091     thr->i.next_run->i.prev_run = thr->i.prev_run;
3092     thr->i.prev_run->i.next_run = thr->i.next_run;
3093 }
3094 #endif /* FAKE_THREADS */
3095
3096 MAGIC *
3097 Perl_condpair_magic(pTHX_ SV *sv)
3098 {
3099     MAGIC *mg;
3100
3101     (void)SvUPGRADE(sv, SVt_PVMG);
3102     mg = mg_find(sv, PERL_MAGIC_mutex);
3103     if (!mg) {
3104         condpair_t *cp;
3105
3106         New(53, cp, 1, condpair_t);
3107         MUTEX_INIT(&cp->mutex);
3108         COND_INIT(&cp->owner_cond);
3109         COND_INIT(&cp->cond);
3110         cp->owner = 0;
3111         LOCK_CRED_MUTEX;                /* XXX need separate mutex? */
3112         mg = mg_find(sv, PERL_MAGIC_mutex);
3113         if (mg) {
3114             /* someone else beat us to initialising it */
3115             UNLOCK_CRED_MUTEX;          /* XXX need separate mutex? */
3116             MUTEX_DESTROY(&cp->mutex);
3117             COND_DESTROY(&cp->owner_cond);
3118             COND_DESTROY(&cp->cond);
3119             Safefree(cp);
3120         }
3121         else {
3122             sv_magic(sv, Nullsv, PERL_MAGIC_mutex, 0, 0);
3123             mg = SvMAGIC(sv);
3124             mg->mg_ptr = (char *)cp;
3125             mg->mg_len = sizeof(cp);
3126             UNLOCK_CRED_MUTEX;          /* XXX need separate mutex? */
3127             DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
3128                                            "%p: condpair_magic %p\n", thr, sv)));
3129         }
3130     }
3131     return mg;
3132 }
3133
3134 SV *
3135 Perl_sv_lock(pTHX_ SV *osv)
3136 {
3137     MAGIC *mg;
3138     SV *sv = osv;
3139
3140     LOCK_SV_LOCK_MUTEX;
3141     if (SvROK(sv)) {
3142         sv = SvRV(sv);
3143     }
3144
3145     mg = condpair_magic(sv);
3146     MUTEX_LOCK(MgMUTEXP(mg));
3147     if (MgOWNER(mg) == thr)
3148         MUTEX_UNLOCK(MgMUTEXP(mg));
3149     else {
3150         while (MgOWNER(mg))
3151             COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
3152         MgOWNER(mg) = thr;
3153         DEBUG_S(PerlIO_printf(Perl_debug_log,
3154                               "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
3155                               PTR2UV(thr), PTR2UV(sv)));
3156         MUTEX_UNLOCK(MgMUTEXP(mg));
3157         SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
3158     }
3159     UNLOCK_SV_LOCK_MUTEX;
3160     return sv;
3161 }
3162
3163 /*
3164  * Make a new perl thread structure using t as a prototype. Some of the
3165  * fields for the new thread are copied from the prototype thread, t,
3166  * so t should not be running in perl at the time this function is
3167  * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3168  * thread calling new_struct_thread) clearly satisfies this constraint.
3169  */
3170 struct perl_thread *
3171 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3172 {
3173 #if !defined(PERL_IMPLICIT_CONTEXT)
3174     struct perl_thread *thr;
3175 #endif
3176     SV *sv;
3177     SV **svp;
3178     I32 i;
3179
3180     sv = newSVpvn("", 0);
3181     SvGROW(sv, sizeof(struct perl_thread) + 1);
3182     SvCUR_set(sv, sizeof(struct perl_thread));
3183     thr = (Thread) SvPVX(sv);
3184 #ifdef DEBUGGING
3185     Poison(thr, 1, struct perl_thread);
3186     PL_markstack = 0;
3187     PL_scopestack = 0;
3188     PL_savestack = 0;
3189     PL_retstack = 0;
3190     PL_dirty = 0;
3191     PL_localizing = 0;
3192     Zero(&PL_hv_fetch_ent_mh, 1, HE);
3193     PL_efloatbuf = (char*)NULL;
3194     PL_efloatsize = 0;
3195 #else
3196     Zero(thr, 1, struct perl_thread);
3197 #endif
3198
3199     thr->oursv = sv;
3200     init_stacks();
3201
3202     PL_curcop = &PL_compiling;
3203     thr->interp = t->interp;
3204     thr->cvcache = newHV();
3205     thr->threadsv = newAV();
3206     thr->specific = newAV();
3207     thr->errsv = newSVpvn("", 0);
3208     thr->flags = THRf_R_JOINABLE;
3209     thr->thr_done = 0;
3210     MUTEX_INIT(&thr->mutex);
3211
3212     JMPENV_BOOTSTRAP;
3213
3214     PL_in_eval = EVAL_NULL;     /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
3215     PL_restartop = 0;
3216
3217     PL_statname = NEWSV(66,0);
3218     PL_errors = newSVpvn("", 0);
3219     PL_maxscream = -1;
3220     PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3221     PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3222     PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3223     PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3224     PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3225     PL_regindent = 0;
3226     PL_reginterp_cnt = 0;
3227     PL_lastscream = Nullsv;
3228     PL_screamfirst = 0;
3229     PL_screamnext = 0;
3230     PL_reg_start_tmp = 0;
3231     PL_reg_start_tmpl = 0;
3232     PL_reg_poscache = Nullch;
3233
3234     PL_peepp = MEMBER_TO_FPTR(Perl_peep);
3235
3236     /* parent thread's data needs to be locked while we make copy */
3237     MUTEX_LOCK(&t->mutex);
3238
3239 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3240     PL_protect = t->Tprotect;
3241 #endif
3242
3243     PL_curcop = t->Tcurcop;       /* XXX As good a guess as any? */
3244     PL_defstash = t->Tdefstash;   /* XXX maybe these should */
3245     PL_curstash = t->Tcurstash;   /* always be set to main? */
3246
3247     PL_tainted = t->Ttainted;
3248     PL_curpm = t->Tcurpm;       /* XXX No PMOP ref count */
3249     PL_rs = newSVsv(t->Trs);
3250     PL_last_in_gv = Nullgv;
3251     PL_ofs_sv = t->Tofs_sv ? SvREFCNT_inc(PL_ofs_sv) : Nullsv;
3252     PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3253     PL_chopset = t->Tchopset;
3254     PL_bodytarget = newSVsv(t->Tbodytarget);
3255     PL_toptarget = newSVsv(t->Ttoptarget);
3256     if (t->Tformtarget == t->Ttoptarget)
3257         PL_formtarget = PL_toptarget;
3258     else
3259         PL_formtarget = PL_bodytarget;
3260     PL_watchaddr = 0; /* XXX */
3261     PL_watchok = 0; /* XXX */
3262     PL_comppad = 0;
3263     PL_curpad = 0;
3264
3265     /* Initialise all per-thread SVs that the template thread used */
3266     svp = AvARRAY(t->threadsv);
3267     for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3268         if (*svp && *svp != &PL_sv_undef) {
3269             SV *sv = newSVsv(*svp);
3270             av_store(thr->threadsv, i, sv);
3271             sv_magic(sv, 0, PERL_MAGIC_sv, &PL_threadsv_names[i], 1);
3272             DEBUG_S(PerlIO_printf(Perl_debug_log,
3273                 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
3274                                   (IV)i, t, thr));
3275         }
3276     }
3277     thr->threadsvp = AvARRAY(thr->threadsv);
3278
3279     MUTEX_LOCK(&PL_threads_mutex);
3280     PL_nthreads++;
3281     thr->tid = ++PL_threadnum;
3282     thr->next = t->next;
3283     thr->prev = t;
3284     t->next = thr;
3285     thr->next->prev = thr;
3286     MUTEX_UNLOCK(&PL_threads_mutex);
3287
3288     /* done copying parent's state */
3289     MUTEX_UNLOCK(&t->mutex);
3290
3291 #ifdef HAVE_THREAD_INTERN
3292     Perl_init_thread_intern(thr);
3293 #endif /* HAVE_THREAD_INTERN */
3294     return thr;
3295 }
3296 #endif /* USE_5005THREADS */
3297
3298 #ifdef PERL_GLOBAL_STRUCT
3299 struct perl_vars *
3300 Perl_GetVars(pTHX)
3301 {
3302  return &PL_Vars;
3303 }
3304 #endif
3305
3306 char **
3307 Perl_get_op_names(pTHX)
3308 {
3309  return PL_op_name;
3310 }
3311
3312 char **
3313 Perl_get_op_descs(pTHX)
3314 {
3315  return PL_op_desc;
3316 }
3317
3318 char *
3319 Perl_get_no_modify(pTHX)
3320 {
3321  return PL_no_modify;
3322 }
3323
3324 U32 *
3325 Perl_get_opargs(pTHX)
3326 {
3327  return PL_opargs;
3328 }
3329
3330 PPADDR_t*
3331 Perl_get_ppaddr(pTHX)
3332 {
3333  return (PPADDR_t*)PL_ppaddr;
3334 }
3335
3336 #ifndef HAS_GETENV_LEN
3337 char *
3338 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3339 {
3340     char *env_trans = PerlEnv_getenv(env_elem);
3341     if (env_trans)
3342         *len = strlen(env_trans);
3343     return env_trans;
3344 }
3345 #endif
3346
3347
3348 MGVTBL*
3349 Perl_get_vtbl(pTHX_ int vtbl_id)
3350 {
3351     MGVTBL* result = Null(MGVTBL*);
3352
3353     switch(vtbl_id) {
3354     case want_vtbl_sv:
3355         result = &PL_vtbl_sv;
3356         break;
3357     case want_vtbl_env:
3358         result = &PL_vtbl_env;
3359         break;
3360     case want_vtbl_envelem:
3361         result = &PL_vtbl_envelem;
3362         break;
3363     case want_vtbl_sig:
3364         result = &PL_vtbl_sig;
3365         break;
3366     case want_vtbl_sigelem:
3367         result = &PL_vtbl_sigelem;
3368         break;
3369     case want_vtbl_pack:
3370         result = &PL_vtbl_pack;
3371         break;
3372     case want_vtbl_packelem:
3373         result = &PL_vtbl_packelem;
3374         break;
3375     case want_vtbl_dbline:
3376         result = &PL_vtbl_dbline;
3377         break;
3378     case want_vtbl_isa:
3379         result = &PL_vtbl_isa;
3380         break;
3381     case want_vtbl_isaelem:
3382         result = &PL_vtbl_isaelem;
3383         break;
3384     case want_vtbl_arylen:
3385         result = &PL_vtbl_arylen;
3386         break;
3387     case want_vtbl_glob:
3388         result = &PL_vtbl_glob;
3389         break;
3390     case want_vtbl_mglob:
3391         result = &PL_vtbl_mglob;
3392         break;
3393     case want_vtbl_nkeys:
3394         result = &PL_vtbl_nkeys;
3395         break;
3396     case want_vtbl_taint:
3397         result = &PL_vtbl_taint;
3398         break;
3399     case want_vtbl_substr:
3400         result = &PL_vtbl_substr;
3401         break;
3402     case want_vtbl_vec:
3403         result = &PL_vtbl_vec;
3404         break;
3405     case want_vtbl_pos:
3406         result = &PL_vtbl_pos;
3407         break;
3408     case want_vtbl_bm:
3409         result = &PL_vtbl_bm;
3410         break;
3411     case want_vtbl_fm:
3412         result = &PL_vtbl_fm;
3413         break;
3414     case want_vtbl_uvar:
3415         result = &PL_vtbl_uvar;
3416         break;
3417 #ifdef USE_5005THREADS
3418     case want_vtbl_mutex:
3419         result = &PL_vtbl_mutex;
3420         break;
3421 #endif
3422     case want_vtbl_defelem:
3423         result = &PL_vtbl_defelem;
3424         break;
3425     case want_vtbl_regexp:
3426         result = &PL_vtbl_regexp;
3427         break;
3428     case want_vtbl_regdata:
3429         result = &PL_vtbl_regdata;
3430         break;
3431     case want_vtbl_regdatum:
3432         result = &PL_vtbl_regdatum;
3433         break;
3434 #ifdef USE_LOCALE_COLLATE
3435     case want_vtbl_collxfrm:
3436         result = &PL_vtbl_collxfrm;
3437         break;
3438 #endif
3439     case want_vtbl_amagic:
3440         result = &PL_vtbl_amagic;
3441         break;
3442     case want_vtbl_amagicelem:
3443         result = &PL_vtbl_amagicelem;
3444         break;
3445     case want_vtbl_backref:
3446         result = &PL_vtbl_backref;
3447         break;
3448     case want_vtbl_utf8:
3449         result = &PL_vtbl_utf8;
3450         break;
3451     }
3452     return result;
3453 }
3454
3455 I32
3456 Perl_my_fflush_all(pTHX)
3457 {
3458 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3459     return PerlIO_flush(NULL);
3460 #else
3461 # if defined(HAS__FWALK)
3462     extern int fflush(FILE *);
3463     /* undocumented, unprototyped, but very useful BSDism */
3464     extern void _fwalk(int (*)(FILE *));
3465     _fwalk(&fflush);
3466     return 0;
3467 # else
3468 #  if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3469     long open_max = -1;
3470 #   ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3471     open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3472 #   else
3473 #    if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3474     open_max = sysconf(_SC_OPEN_MAX);
3475 #     else
3476 #      ifdef FOPEN_MAX
3477     open_max = FOPEN_MAX;
3478 #      else
3479 #       ifdef OPEN_MAX
3480     open_max = OPEN_MAX;
3481 #       else
3482 #        ifdef _NFILE
3483     open_max = _NFILE;
3484 #        endif
3485 #       endif
3486 #      endif
3487 #     endif
3488 #    endif
3489     if (open_max > 0) {
3490       long i;
3491       for (i = 0; i < open_max; i++)
3492             if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3493                 STDIO_STREAM_ARRAY[i]._file < open_max &&
3494                 STDIO_STREAM_ARRAY[i]._flag)
3495                 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3496       return 0;
3497     }
3498 #  endif
3499     SETERRNO(EBADF,RMS_IFI);
3500     return EOF;
3501 # endif
3502 #endif
3503 }
3504
3505 void
3506 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3507 {
3508     const char *func =
3509         op == OP_READLINE   ? "readline"  :     /* "<HANDLE>" not nice */
3510         op == OP_LEAVEWRITE ? "write" :         /* "write exit" not nice */
3511         PL_op_desc[op];
3512     const char *pars = OP_IS_FILETEST(op) ? "" : "()";
3513     const char *type = OP_IS_SOCKET(op)
3514             || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3515                 ?  "socket" : "filehandle";
3516     const char *name = NULL;
3517
3518     if (gv && isGV(gv)) {
3519         name = GvENAME(gv);
3520     }
3521
3522     if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3523         if (ckWARN(WARN_IO)) {
3524             const char *direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3525             if (name && *name)
3526                 Perl_warner(aTHX_ packWARN(WARN_IO),
3527                             "Filehandle %s opened only for %sput",
3528                             name, direction);
3529             else
3530                 Perl_warner(aTHX_ packWARN(WARN_IO),
3531                             "Filehandle opened only for %sput", direction);
3532         }
3533     }
3534     else {
3535         const char *vile;
3536         I32   warn_type;
3537
3538         if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3539             vile = "closed";
3540             warn_type = WARN_CLOSED;
3541         }
3542         else {
3543             vile = "unopened";
3544             warn_type = WARN_UNOPENED;
3545         }
3546
3547         if (ckWARN(warn_type)) {
3548             if (name && *name) {
3549                 Perl_warner(aTHX_ packWARN(warn_type),
3550                             "%s%s on %s %s %s", func, pars, vile, type, name);
3551                 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3552                     Perl_warner(
3553                         aTHX_ packWARN(warn_type),
3554                         "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3555                         func, pars, name
3556                     );
3557             }
3558             else {
3559                 Perl_warner(aTHX_ packWARN(warn_type),
3560                             "%s%s on %s %s", func, pars, vile, type);
3561                 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3562                     Perl_warner(
3563                         aTHX_ packWARN(warn_type),
3564                         "\t(Are you trying to call %s%s on dirhandle?)\n",
3565                         func, pars
3566                     );
3567             }
3568         }
3569     }
3570 }
3571
3572 #ifdef EBCDIC
3573 /* in ASCII order, not that it matters */
3574 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3575
3576 int
3577 Perl_ebcdic_control(pTHX_ int ch)
3578 {
3579     if (ch > 'a') {
3580         const char *ctlp;
3581
3582         if (islower(ch))
3583             ch = toupper(ch);
3584
3585         if ((ctlp = strchr(controllablechars, ch)) == 0) {
3586             Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3587         }
3588
3589         if (ctlp == controllablechars)
3590             return('\177'); /* DEL */
3591         else
3592             return((unsigned char)(ctlp - controllablechars - 1));
3593     } else { /* Want uncontrol */
3594         if (ch == '\177' || ch == -1)
3595             return('?');
3596         else if (ch == '\157')
3597             return('\177');
3598         else if (ch == '\174')
3599             return('\000');
3600         else if (ch == '^')    /* '\137' in 1047, '\260' in 819 */
3601             return('\036');
3602         else if (ch == '\155')
3603             return('\037');
3604         else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3605             return(controllablechars[ch+1]);
3606         else
3607             Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3608     }
3609 }
3610 #endif
3611
3612 /* To workaround core dumps from the uninitialised tm_zone we get the
3613  * system to give us a reasonable struct to copy.  This fix means that
3614  * strftime uses the tm_zone and tm_gmtoff values returned by
3615  * localtime(time()). That should give the desired result most of the
3616  * time. But probably not always!
3617  *
3618  * This does not address tzname aspects of NETaa14816.
3619  *
3620  */
3621
3622 #ifdef HAS_GNULIBC
3623 # ifndef STRUCT_TM_HASZONE
3624 #    define STRUCT_TM_HASZONE
3625 # endif
3626 #endif
3627
3628 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3629 # ifndef HAS_TM_TM_ZONE
3630 #    define HAS_TM_TM_ZONE
3631 # endif
3632 #endif
3633
3634 void
3635 Perl_init_tm(pTHX_ struct tm *ptm)      /* see mktime, strftime and asctime */
3636 {
3637 #ifdef HAS_TM_TM_ZONE
3638     Time_t now;
3639     struct tm* my_tm;
3640     (void)time(&now);
3641     my_tm = localtime(&now);
3642     if (my_tm)
3643         Copy(my_tm, ptm, 1, struct tm);
3644 #endif
3645 }
3646
3647 /*
3648  * mini_mktime - normalise struct tm values without the localtime()
3649  * semantics (and overhead) of mktime().
3650  */
3651 void
3652 Perl_mini_mktime(pTHX_ struct tm *ptm)
3653 {
3654     int yearday;
3655     int secs;
3656     int month, mday, year, jday;
3657     int odd_cent, odd_year;
3658
3659 #define DAYS_PER_YEAR   365
3660 #define DAYS_PER_QYEAR  (4*DAYS_PER_YEAR+1)
3661 #define DAYS_PER_CENT   (25*DAYS_PER_QYEAR-1)
3662 #define DAYS_PER_QCENT  (4*DAYS_PER_CENT+1)
3663 #define SECS_PER_HOUR   (60*60)
3664 #define SECS_PER_DAY    (24*SECS_PER_HOUR)
3665 /* parentheses deliberately absent on these two, otherwise they don't work */
3666 #define MONTH_TO_DAYS   153/5
3667 #define DAYS_TO_MONTH   5/153
3668 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3669 #define YEAR_ADJUST     (4*MONTH_TO_DAYS+1)
3670 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3671 #define WEEKDAY_BIAS    6       /* (1+6)%7 makes Sunday 0 again */
3672
3673 /*
3674  * Year/day algorithm notes:
3675  *
3676  * With a suitable offset for numeric value of the month, one can find
3677  * an offset into the year by considering months to have 30.6 (153/5) days,
3678  * using integer arithmetic (i.e., with truncation).  To avoid too much
3679  * messing about with leap days, we consider January and February to be
3680  * the 13th and 14th month of the previous year.  After that transformation,
3681  * we need the month index we use to be high by 1 from 'normal human' usage,
3682  * so the month index values we use run from 4 through 15.
3683  *
3684  * Given that, and the rules for the Gregorian calendar (leap years are those
3685  * divisible by 4 unless also divisible by 100, when they must be divisible
3686  * by 400 instead), we can simply calculate the number of days since some
3687  * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3688  * the days we derive from our month index, and adding in the day of the
3689  * month.  The value used here is not adjusted for the actual origin which
3690  * it normally would use (1 January A.D. 1), since we're not exposing it.
3691  * We're only building the value so we can turn around and get the
3692  * normalised values for the year, month, day-of-month, and day-of-year.
3693  *
3694  * For going backward, we need to bias the value we're using so that we find
3695  * the right year value.  (Basically, we don't want the contribution of
3696  * March 1st to the number to apply while deriving the year).  Having done
3697  * that, we 'count up' the contribution to the year number by accounting for
3698  * full quadracenturies (400-year periods) with their extra leap days, plus
3699  * the contribution from full centuries (to avoid counting in the lost leap
3700  * days), plus the contribution from full quad-years (to count in the normal
3701  * leap days), plus the leftover contribution from any non-leap years.
3702  * At this point, if we were working with an actual leap day, we'll have 0
3703  * days left over.  This is also true for March 1st, however.  So, we have
3704  * to special-case that result, and (earlier) keep track of the 'odd'
3705  * century and year contributions.  If we got 4 extra centuries in a qcent,
3706  * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3707  * Otherwise, we add back in the earlier bias we removed (the 123 from
3708  * figuring in March 1st), find the month index (integer division by 30.6),
3709  * and the remainder is the day-of-month.  We then have to convert back to
3710  * 'real' months (including fixing January and February from being 14/15 in
3711  * the previous year to being in the proper year).  After that, to get
3712  * tm_yday, we work with the normalised year and get a new yearday value for
3713  * January 1st, which we subtract from the yearday value we had earlier,
3714  * representing the date we've re-built.  This is done from January 1
3715  * because tm_yday is 0-origin.
3716  *
3717  * Since POSIX time routines are only guaranteed to work for times since the
3718  * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3719  * applies Gregorian calendar rules even to dates before the 16th century
3720  * doesn't bother me.  Besides, you'd need cultural context for a given
3721  * date to know whether it was Julian or Gregorian calendar, and that's
3722  * outside the scope for this routine.  Since we convert back based on the
3723  * same rules we used to build the yearday, you'll only get strange results
3724  * for input which needed normalising, or for the 'odd' century years which
3725  * were leap years in the Julian calander but not in the Gregorian one.
3726  * I can live with that.
3727  *
3728  * This algorithm also fails to handle years before A.D. 1 gracefully, but
3729  * that's still outside the scope for POSIX time manipulation, so I don't
3730  * care.
3731  */
3732
3733     year = 1900 + ptm->tm_year;
3734     month = ptm->tm_mon;
3735     mday = ptm->tm_mday;
3736     /* allow given yday with no month & mday to dominate the result */
3737     if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3738         month = 0;
3739         mday = 0;
3740         jday = 1 + ptm->tm_yday;
3741     }
3742     else {
3743         jday = 0;
3744     }
3745     if (month >= 2)
3746         month+=2;
3747     else
3748         month+=14, year--;
3749     yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3750     yearday += month*MONTH_TO_DAYS + mday + jday;
3751     /*
3752      * Note that we don't know when leap-seconds were or will be,
3753      * so we have to trust the user if we get something which looks
3754      * like a sensible leap-second.  Wild values for seconds will
3755      * be rationalised, however.
3756      */
3757     if ((unsigned) ptm->tm_sec <= 60) {
3758         secs = 0;
3759     }
3760     else {
3761         secs = ptm->tm_sec;
3762         ptm->tm_sec = 0;
3763     }
3764     secs += 60 * ptm->tm_min;
3765     secs += SECS_PER_HOUR * ptm->tm_hour;
3766     if (secs < 0) {
3767         if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3768             /* got negative remainder, but need positive time */
3769             /* back off an extra day to compensate */
3770             yearday += (secs/SECS_PER_DAY)-1;
3771             secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3772         }
3773         else {
3774             yearday += (secs/SECS_PER_DAY);
3775             secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3776         }
3777     }
3778     else if (secs >= SECS_PER_DAY) {
3779         yearday += (secs/SECS_PER_DAY);
3780         secs %= SECS_PER_DAY;
3781     }
3782     ptm->tm_hour = secs/SECS_PER_HOUR;
3783     secs %= SECS_PER_HOUR;
3784     ptm->tm_min = secs/60;
3785     secs %= 60;
3786     ptm->tm_sec += secs;
3787     /* done with time of day effects */
3788     /*
3789      * The algorithm for yearday has (so far) left it high by 428.
3790      * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3791      * bias it by 123 while trying to figure out what year it
3792      * really represents.  Even with this tweak, the reverse
3793      * translation fails for years before A.D. 0001.
3794      * It would still fail for Feb 29, but we catch that one below.
3795      */
3796     jday = yearday;     /* save for later fixup vis-a-vis Jan 1 */
3797     yearday -= YEAR_ADJUST;
3798     year = (yearday / DAYS_PER_QCENT) * 400;
3799     yearday %= DAYS_PER_QCENT;
3800     odd_cent = yearday / DAYS_PER_CENT;
3801     year += odd_cent * 100;
3802     yearday %= DAYS_PER_CENT;
3803     year += (yearday / DAYS_PER_QYEAR) * 4;
3804     yearday %= DAYS_PER_QYEAR;
3805     odd_year = yearday / DAYS_PER_YEAR;
3806     year += odd_year;
3807     yearday %= DAYS_PER_YEAR;
3808     if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3809         month = 1;
3810         yearday = 29;
3811     }
3812     else {
3813         yearday += YEAR_ADJUST; /* recover March 1st crock */
3814         month = yearday*DAYS_TO_MONTH;
3815         yearday -= month*MONTH_TO_DAYS;
3816         /* recover other leap-year adjustment */
3817         if (month > 13) {
3818             month-=14;
3819             year++;
3820         }
3821         else {
3822             month-=2;
3823         }
3824     }
3825     ptm->tm_year = year - 1900;
3826     if (yearday) {
3827       ptm->tm_mday = yearday;
3828       ptm->tm_mon = month;
3829     }
3830     else {
3831       ptm->tm_mday = 31;
3832       ptm->tm_mon = month - 1;
3833     }
3834     /* re-build yearday based on Jan 1 to get tm_yday */
3835     year--;
3836     yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3837     yearday += 14*MONTH_TO_DAYS + 1;
3838     ptm->tm_yday = jday - yearday;
3839     /* fix tm_wday if not overridden by caller */
3840     if ((unsigned)ptm->tm_wday > 6)
3841         ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3842 }
3843
3844 char *
3845 Perl_my_strftime(pTHX_ char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3846 {
3847 #ifdef HAS_STRFTIME
3848   char *buf;
3849   int buflen;
3850   struct tm mytm;
3851   int len;
3852
3853   init_tm(&mytm);       /* XXX workaround - see init_tm() above */
3854   mytm.tm_sec = sec;
3855   mytm.tm_min = min;
3856   mytm.tm_hour = hour;
3857   mytm.tm_mday = mday;
3858   mytm.tm_mon = mon;
3859   mytm.tm_year = year;
3860   mytm.tm_wday = wday;
3861   mytm.tm_yday = yday;
3862   mytm.tm_isdst = isdst;
3863   mini_mktime(&mytm);
3864   /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3865 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3866   STMT_START {
3867     struct tm mytm2;
3868     mytm2 = mytm;
3869     mktime(&mytm2);
3870 #ifdef HAS_TM_TM_GMTOFF
3871     mytm.tm_gmtoff = mytm2.tm_gmtoff;
3872 #endif
3873 #ifdef HAS_TM_TM_ZONE
3874     mytm.tm_zone = mytm2.tm_zone;
3875 #endif
3876   } STMT_END;
3877 #endif
3878   buflen = 64;
3879   New(0, buf, buflen, char);
3880   len = strftime(buf, buflen, fmt, &mytm);
3881   /*
3882   ** The following is needed to handle to the situation where
3883   ** tmpbuf overflows.  Basically we want to allocate a buffer
3884   ** and try repeatedly.  The reason why it is so complicated
3885   ** is that getting a return value of 0 from strftime can indicate
3886   ** one of the following:
3887   ** 1. buffer overflowed,
3888   ** 2. illegal conversion specifier, or
3889   ** 3. the format string specifies nothing to be returned(not
3890   **      an error).  This could be because format is an empty string
3891   **    or it specifies %p that yields an empty string in some locale.
3892   ** If there is a better way to make it portable, go ahead by
3893   ** all means.
3894   */
3895   if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3896     return buf;
3897   else {
3898     /* Possibly buf overflowed - try again with a bigger buf */
3899     const int fmtlen = strlen(fmt);
3900     const int bufsize = fmtlen + buflen;
3901
3902     New(0, buf, bufsize, char);
3903     while (buf) {
3904       buflen = strftime(buf, bufsize, fmt, &mytm);
3905       if (buflen > 0 && buflen < bufsize)
3906         break;
3907       /* heuristic to prevent out-of-memory errors */
3908       if (bufsize > 100*fmtlen) {
3909         Safefree(buf);
3910         buf = NULL;
3911         break;
3912       }
3913       Renew(buf, bufsize*2, char);
3914     }
3915     return buf;
3916   }
3917 #else
3918   Perl_croak(aTHX_ "panic: no strftime");
3919 #endif
3920 }
3921
3922
3923 #define SV_CWD_RETURN_UNDEF \
3924 sv_setsv(sv, &PL_sv_undef); \
3925 return FALSE
3926
3927 #define SV_CWD_ISDOT(dp) \
3928     (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3929         (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3930
3931 /*
3932 =head1 Miscellaneous Functions
3933
3934 =for apidoc getcwd_sv
3935
3936 Fill the sv with current working directory
3937
3938 =cut
3939 */
3940
3941 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3942  * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3943  * getcwd(3) if available
3944  * Comments from the orignal:
3945  *     This is a faster version of getcwd.  It's also more dangerous
3946  *     because you might chdir out of a directory that you can't chdir
3947  *     back into. */
3948
3949 int
3950 Perl_getcwd_sv(pTHX_ register SV *sv)
3951 {
3952 #ifndef PERL_MICRO
3953
3954 #ifndef INCOMPLETE_TAINTS
3955     SvTAINTED_on(sv);
3956 #endif
3957
3958 #ifdef HAS_GETCWD
3959     {
3960         char buf[MAXPATHLEN];
3961
3962         /* Some getcwd()s automatically allocate a buffer of the given
3963          * size from the heap if they are given a NULL buffer pointer.
3964          * The problem is that this behaviour is not portable. */
3965         if (getcwd(buf, sizeof(buf) - 1)) {
3966             sv_setpvn(sv, buf, strlen(buf));
3967             return TRUE;
3968         }
3969         else {
3970             sv_setsv(sv, &PL_sv_undef);
3971             return FALSE;
3972         }
3973     }
3974
3975 #else
3976
3977     Stat_t statbuf;
3978     int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3979     int pathlen=0;
3980     Direntry_t *dp;
3981
3982     (void)SvUPGRADE(sv, SVt_PV);
3983
3984     if (PerlLIO_lstat(".", &statbuf) < 0) {
3985         SV_CWD_RETURN_UNDEF;
3986     }
3987
3988     orig_cdev = statbuf.st_dev;
3989     orig_cino = statbuf.st_ino;
3990     cdev = orig_cdev;
3991     cino = orig_cino;
3992
3993     for (;;) {
3994         DIR *dir;
3995         odev = cdev;
3996         oino = cino;
3997
3998         if (PerlDir_chdir("..") < 0) {
3999             SV_CWD_RETURN_UNDEF;
4000         }
4001         if (PerlLIO_stat(".", &statbuf) < 0) {
4002             SV_CWD_RETURN_UNDEF;
4003         }
4004
4005         cdev = statbuf.st_dev;
4006         cino = statbuf.st_ino;
4007
4008         if (odev == cdev && oino == cino) {
4009             break;
4010         }
4011         if (!(dir = PerlDir_open("."))) {
4012             SV_CWD_RETURN_UNDEF;
4013         }
4014
4015         while ((dp = PerlDir_read(dir)) != NULL) {
4016 #ifdef DIRNAMLEN
4017             const int namelen = dp->d_namlen;
4018 #else
4019             const int namelen = strlen(dp->d_name);
4020 #endif
4021             /* skip . and .. */
4022             if (SV_CWD_ISDOT(dp)) {
4023                 continue;
4024             }
4025
4026             if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4027                 SV_CWD_RETURN_UNDEF;
4028             }
4029
4030             tdev = statbuf.st_dev;
4031             tino = statbuf.st_ino;
4032             if (tino == oino && tdev == odev) {
4033                 break;
4034             }
4035         }
4036
4037         if (!dp) {
4038             SV_CWD_RETURN_UNDEF;
4039         }
4040
4041         if (pathlen + namelen + 1 >= MAXPATHLEN) {
4042             SV_CWD_RETURN_UNDEF;
4043         }
4044
4045         SvGROW(sv, pathlen + namelen + 1);
4046
4047         if (pathlen) {
4048             /* shift down */
4049             Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4050         }
4051
4052         /* prepend current directory to the front */
4053         *SvPVX(sv) = '/';
4054         Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4055         pathlen += (namelen + 1);
4056
4057 #ifdef VOID_CLOSEDIR
4058         PerlDir_close(dir);
4059 #else
4060         if (PerlDir_close(dir) < 0) {
4061             SV_CWD_RETURN_UNDEF;
4062         }
4063 #endif
4064     }
4065
4066     if (pathlen) {
4067         SvCUR_set(sv, pathlen);
4068         *SvEND(sv) = '\0';
4069         SvPOK_only(sv);
4070
4071         if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4072             SV_CWD_RETURN_UNDEF;
4073         }
4074     }
4075     if (PerlLIO_stat(".", &statbuf) < 0) {
4076         SV_CWD_RETURN_UNDEF;
4077     }
4078
4079     cdev = statbuf.st_dev;
4080     cino = statbuf.st_ino;
4081
4082     if (cdev != orig_cdev || cino != orig_cino) {
4083         Perl_croak(aTHX_ "Unstable directory path, "
4084                    "current directory changed unexpectedly");
4085     }
4086
4087     return TRUE;
4088 #endif
4089
4090 #else
4091     return FALSE;
4092 #endif
4093 }
4094
4095 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4096 #   define EMULATE_SOCKETPAIR_UDP
4097 #endif
4098
4099 #ifdef EMULATE_SOCKETPAIR_UDP
4100 static int
4101 S_socketpair_udp (int fd[2]) {
4102     dTHX;
4103     /* Fake a datagram socketpair using UDP to localhost.  */
4104     int sockets[2] = {-1, -1};
4105     struct sockaddr_in addresses[2];
4106     int i;
4107     Sock_size_t size = sizeof(struct sockaddr_in);
4108     unsigned short port;
4109     int got;
4110
4111     memset(&addresses, 0, sizeof(addresses));
4112     i = 1;
4113     do {
4114         sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4115         if (sockets[i] == -1)
4116             goto tidy_up_and_fail;
4117
4118         addresses[i].sin_family = AF_INET;
4119         addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4120         addresses[i].sin_port = 0;      /* kernel choses port.  */
4121         if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4122                 sizeof(struct sockaddr_in)) == -1)
4123             goto tidy_up_and_fail;
4124     } while (i--);
4125
4126     /* Now have 2 UDP sockets. Find out which port each is connected to, and
4127        for each connect the other socket to it.  */
4128     i = 1;
4129     do {
4130         if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4131                 &size) == -1)
4132             goto tidy_up_and_fail;
4133         if (size != sizeof(struct sockaddr_in))
4134             goto abort_tidy_up_and_fail;
4135         /* !1 is 0, !0 is 1 */
4136         if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4137                 sizeof(struct sockaddr_in)) == -1)
4138             goto tidy_up_and_fail;
4139     } while (i--);
4140
4141     /* Now we have 2 sockets connected to each other. I don't trust some other
4142        process not to have already sent a packet to us (by random) so send
4143        a packet from each to the other.  */
4144     i = 1;
4145     do {
4146         /* I'm going to send my own port number.  As a short.
4147            (Who knows if someone somewhere has sin_port as a bitfield and needs
4148            this routine. (I'm assuming crays have socketpair)) */
4149         port = addresses[i].sin_port;
4150         got = PerlLIO_write(sockets[i], &port, sizeof(port));
4151         if (got != sizeof(port)) {
4152             if (got == -1)
4153                 goto tidy_up_and_fail;
4154             goto abort_tidy_up_and_fail;
4155         }
4156     } while (i--);
4157
4158     /* Packets sent. I don't trust them to have arrived though.
4159        (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4160        connect to localhost will use a second kernel thread. In 2.6 the
4161        first thread running the connect() returns before the second completes,
4162        so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4163        returns 0. Poor programs have tripped up. One poor program's authors'
4164        had a 50-1 reverse stock split. Not sure how connected these were.)
4165        So I don't trust someone not to have an unpredictable UDP stack.
4166     */
4167
4168     {
4169         struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4170         int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4171         fd_set rset;
4172
4173         FD_ZERO(&rset);
4174         FD_SET(sockets[0], &rset);
4175         FD_SET(sockets[1], &rset);
4176
4177         got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4178         if (got != 2 || !FD_ISSET(sockets[0], &rset)
4179                 || !FD_ISSET(sockets[1], &rset)) {
4180             /* I hope this is portable and appropriate.  */
4181             if (got == -1)
4182                 goto tidy_up_and_fail;
4183             goto abort_tidy_up_and_fail;
4184         }
4185     }
4186
4187     /* And the paranoia department even now doesn't trust it to have arrive
4188        (hence MSG_DONTWAIT). Or that what arrives was sent by us.  */
4189     {
4190         struct sockaddr_in readfrom;
4191         unsigned short buffer[2];
4192
4193         i = 1;
4194         do {
4195 #ifdef MSG_DONTWAIT
4196             got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4197                     sizeof(buffer), MSG_DONTWAIT,
4198                     (struct sockaddr *) &readfrom, &size);
4199 #else
4200             got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4201                     sizeof(buffer), 0,
4202                     (struct sockaddr *) &readfrom, &size);
4203 #endif
4204
4205             if (got == -1)
4206                 goto tidy_up_and_fail;
4207             if (got != sizeof(port)
4208                     || size != sizeof(struct sockaddr_in)
4209                     /* Check other socket sent us its port.  */
4210                     || buffer[0] != (unsigned short) addresses[!i].sin_port
4211                     /* Check kernel says we got the datagram from that socket */
4212                     || readfrom.sin_family != addresses[!i].sin_family
4213                     || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4214                     || readfrom.sin_port != addresses[!i].sin_port)
4215                 goto abort_tidy_up_and_fail;
4216         } while (i--);
4217     }
4218     /* My caller (my_socketpair) has validated that this is non-NULL  */
4219     fd[0] = sockets[0];
4220     fd[1] = sockets[1];
4221     /* I hereby declare this connection open.  May God bless all who cross
4222        her.  */
4223     return 0;
4224
4225   abort_tidy_up_and_fail:
4226     errno = ECONNABORTED;
4227   tidy_up_and_fail:
4228     {
4229         const int save_errno = errno;
4230         if (sockets[0] != -1)
4231             PerlLIO_close(sockets[0]);
4232         if (sockets[1] != -1)
4233             PerlLIO_close(sockets[1]);
4234         errno = save_errno;
4235         return -1;
4236     }
4237 }
4238 #endif /*  EMULATE_SOCKETPAIR_UDP */
4239
4240 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4241 int
4242 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4243     /* Stevens says that family must be AF_LOCAL, protocol 0.
4244        I'm going to enforce that, then ignore it, and use TCP (or UDP).  */
4245     dTHX;
4246     int listener = -1;
4247     int connector = -1;
4248     int acceptor = -1;
4249     struct sockaddr_in listen_addr;
4250     struct sockaddr_in connect_addr;
4251     Sock_size_t size;
4252
4253     if (protocol
4254 #ifdef AF_UNIX
4255         || family != AF_UNIX
4256 #endif
4257     ) {
4258         errno = EAFNOSUPPORT;
4259         return -1;
4260     }
4261     if (!fd) {
4262         errno = EINVAL;
4263         return -1;
4264     }
4265
4266 #ifdef EMULATE_SOCKETPAIR_UDP
4267     if (type == SOCK_DGRAM)
4268         return S_socketpair_udp(fd);
4269 #endif
4270
4271     listener = PerlSock_socket(AF_INET, type, 0);
4272     if (listener == -1)
4273         return -1;
4274     memset(&listen_addr, 0, sizeof(listen_addr));
4275     listen_addr.sin_family = AF_INET;
4276     listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4277     listen_addr.sin_port = 0;   /* kernel choses port.  */
4278     if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4279             sizeof(listen_addr)) == -1)
4280         goto tidy_up_and_fail;
4281     if (PerlSock_listen(listener, 1) == -1)
4282         goto tidy_up_and_fail;
4283
4284     connector = PerlSock_socket(AF_INET, type, 0);
4285     if (connector == -1)
4286         goto tidy_up_and_fail;
4287     /* We want to find out the port number to connect to.  */
4288     size = sizeof(connect_addr);
4289     if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4290             &size) == -1)
4291         goto tidy_up_and_fail;
4292     if (size != sizeof(connect_addr))
4293         goto abort_tidy_up_and_fail;
4294     if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4295             sizeof(connect_addr)) == -1)
4296         goto tidy_up_and_fail;
4297
4298     size = sizeof(listen_addr);
4299     acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4300             &size);
4301     if (acceptor == -1)
4302         goto tidy_up_and_fail;
4303     if (size != sizeof(listen_addr))
4304         goto abort_tidy_up_and_fail;
4305     PerlLIO_close(listener);
4306     /* Now check we are talking to ourself by matching port and host on the
4307        two sockets.  */
4308     if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4309             &size) == -1)
4310         goto tidy_up_and_fail;
4311     if (size != sizeof(connect_addr)
4312             || listen_addr.sin_family != connect_addr.sin_family
4313             || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4314             || listen_addr.sin_port != connect_addr.sin_port) {
4315         goto abort_tidy_up_and_fail;
4316     }
4317     fd[0] = connector;
4318     fd[1] = acceptor;
4319     return 0;
4320
4321   abort_tidy_up_and_fail:
4322   errno = ECONNABORTED; /* I hope this is portable and appropriate.  */
4323   tidy_up_and_fail:
4324     {
4325         int save_errno = errno;
4326         if (listener != -1)
4327             PerlLIO_close(listener);
4328         if (connector != -1)
4329             PerlLIO_close(connector);
4330         if (acceptor != -1)
4331             PerlLIO_close(acceptor);
4332         errno = save_errno;
4333         return -1;
4334     }
4335 }
4336 #else
4337 /* In any case have a stub so that there's code corresponding
4338  * to the my_socketpair in global.sym. */
4339 int
4340 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4341 #ifdef HAS_SOCKETPAIR
4342     return socketpair(family, type, protocol, fd);
4343 #else
4344     return -1;
4345 #endif
4346 }
4347 #endif
4348
4349 /*
4350
4351 =for apidoc sv_nosharing
4352
4353 Dummy routine which "shares" an SV when there is no sharing module present.
4354 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4355 some level of strict-ness.
4356
4357 =cut
4358 */
4359
4360 void
4361 Perl_sv_nosharing(pTHX_ SV *sv)
4362 {
4363     (void)sv;
4364 }
4365
4366 /*
4367 =for apidoc sv_nolocking
4368
4369 Dummy routine which "locks" an SV when there is no locking module present.
4370 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4371 some level of strict-ness.
4372
4373 =cut
4374 */
4375
4376 void
4377 Perl_sv_nolocking(pTHX_ SV *sv)
4378 {
4379     (void)sv;
4380 }
4381
4382
4383 /*
4384 =for apidoc sv_nounlocking
4385
4386 Dummy routine which "unlocks" an SV when there is no locking module present.
4387 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4388 some level of strict-ness.
4389
4390 =cut
4391 */
4392
4393 void
4394 Perl_sv_nounlocking(pTHX_ SV *sv)
4395 {
4396     (void)sv;
4397 }
4398
4399 U32
4400 Perl_parse_unicode_opts(pTHX_ char **popt)
4401 {
4402   const char *p = *popt;
4403   U32 opt = 0;
4404
4405   if (*p) {
4406        if (isDIGIT(*p)) {
4407             opt = (U32) atoi(p);
4408             while (isDIGIT(*p)) p++;
4409             if (*p && *p != '\n' && *p != '\r')
4410                  Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4411        }
4412        else {
4413             for (; *p; p++) {
4414                  switch (*p) {
4415                  case PERL_UNICODE_STDIN:
4416                       opt |= PERL_UNICODE_STDIN_FLAG;   break;
4417                  case PERL_UNICODE_STDOUT:
4418                       opt |= PERL_UNICODE_STDOUT_FLAG;  break;
4419                  case PERL_UNICODE_STDERR:
4420                       opt |= PERL_UNICODE_STDERR_FLAG;  break;
4421                  case PERL_UNICODE_STD:
4422                       opt |= PERL_UNICODE_STD_FLAG;     break;
4423                  case PERL_UNICODE_IN:
4424                       opt |= PERL_UNICODE_IN_FLAG;      break;
4425                  case PERL_UNICODE_OUT:
4426                       opt |= PERL_UNICODE_OUT_FLAG;     break;
4427                  case PERL_UNICODE_INOUT:
4428                       opt |= PERL_UNICODE_INOUT_FLAG;   break;
4429                  case PERL_UNICODE_LOCALE:
4430                       opt |= PERL_UNICODE_LOCALE_FLAG;  break;
4431                  case PERL_UNICODE_ARGV:
4432                       opt |= PERL_UNICODE_ARGV_FLAG;    break;
4433                  default:
4434                       if (*p != '\n' && *p != '\r')
4435                           Perl_croak(aTHX_
4436                                      "Unknown Unicode option letter '%c'", *p);
4437                  }
4438             }
4439        }
4440   }
4441   else
4442        opt = PERL_UNICODE_DEFAULT_FLAGS;
4443
4444   if (opt & ~PERL_UNICODE_ALL_FLAGS)
4445        Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4446                   (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4447
4448   *popt = p;
4449
4450   return opt;
4451 }
4452
4453 U32
4454 Perl_seed(pTHX)
4455 {
4456     /*
4457      * This is really just a quick hack which grabs various garbage
4458      * values.  It really should be a real hash algorithm which
4459      * spreads the effect of every input bit onto every output bit,
4460      * if someone who knows about such things would bother to write it.
4461      * Might be a good idea to add that function to CORE as well.
4462      * No numbers below come from careful analysis or anything here,
4463      * except they are primes and SEED_C1 > 1E6 to get a full-width
4464      * value from (tv_sec * SEED_C1 + tv_usec).  The multipliers should
4465      * probably be bigger too.
4466      */
4467 #if RANDBITS > 16
4468 #  define SEED_C1       1000003
4469 #define   SEED_C4       73819
4470 #else
4471 #  define SEED_C1       25747
4472 #define   SEED_C4       20639
4473 #endif
4474 #define   SEED_C2       3
4475 #define   SEED_C3       269
4476 #define   SEED_C5       26107
4477
4478 #ifndef PERL_NO_DEV_RANDOM
4479     int fd;
4480 #endif
4481     U32 u;
4482 #ifdef VMS
4483 #  include <starlet.h>
4484     /* when[] = (low 32 bits, high 32 bits) of time since epoch
4485      * in 100-ns units, typically incremented ever 10 ms.        */
4486     unsigned int when[2];
4487 #else
4488 #  ifdef HAS_GETTIMEOFDAY
4489     struct timeval when;
4490 #  else
4491     Time_t when;
4492 #  endif
4493 #endif
4494
4495 /* This test is an escape hatch, this symbol isn't set by Configure. */
4496 #ifndef PERL_NO_DEV_RANDOM
4497 #ifndef PERL_RANDOM_DEVICE
4498    /* /dev/random isn't used by default because reads from it will block
4499     * if there isn't enough entropy available.  You can compile with
4500     * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4501     * is enough real entropy to fill the seed. */
4502 #  define PERL_RANDOM_DEVICE "/dev/urandom"
4503 #endif
4504     fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4505     if (fd != -1) {
4506         if (PerlLIO_read(fd, &u, sizeof u) != sizeof u)
4507             u = 0;
4508         PerlLIO_close(fd);
4509         if (u)
4510             return u;
4511     }
4512 #endif
4513
4514 #ifdef VMS
4515     _ckvmssts(sys$gettim(when));
4516     u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4517 #else
4518 #  ifdef HAS_GETTIMEOFDAY
4519     PerlProc_gettimeofday(&when,NULL);
4520     u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4521 #  else
4522     (void)time(&when);
4523     u = (U32)SEED_C1 * when;
4524 #  endif
4525 #endif
4526     u += SEED_C3 * (U32)PerlProc_getpid();
4527     u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4528 #ifndef PLAN9           /* XXX Plan9 assembler chokes on this; fix needed  */
4529     u += SEED_C5 * (U32)PTR2UV(&when);
4530 #endif
4531     return u;
4532 }
4533
4534 UV
4535 Perl_get_hash_seed(pTHX)
4536 {
4537      const char *s = PerlEnv_getenv("PERL_HASH_SEED");
4538      UV myseed = 0;
4539
4540      if (s)
4541           while (isSPACE(*s)) s++;
4542      if (s && isDIGIT(*s))
4543           myseed = (UV)Atoul(s);
4544      else
4545 #ifdef USE_HASH_SEED_EXPLICIT
4546      if (s)
4547 #endif
4548      {
4549           /* Compute a random seed */
4550           (void)seedDrand01((Rand_seed_t)seed());
4551           myseed = (UV)(Drand01() * (NV)UV_MAX);
4552 #if RANDBITS < (UVSIZE * 8)
4553           /* Since there are not enough randbits to to reach all
4554            * the bits of a UV, the low bits might need extra
4555            * help.  Sum in another random number that will
4556            * fill in the low bits. */
4557           myseed +=
4558                (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
4559 #endif /* RANDBITS < (UVSIZE * 8) */
4560           if (myseed == 0) { /* Superparanoia. */
4561               myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
4562               if (myseed == 0)
4563                   Perl_croak(aTHX_ "Your random numbers are not that random");
4564           }
4565      }
4566      PL_rehash_seed_set = TRUE;
4567
4568      return myseed;
4569 }
4570 /*
4571  * Local variables:
4572  * c-indentation-style: bsd
4573  * c-basic-offset: 4
4574  * indent-tabs-mode: t
4575  * End:
4576  *
4577  * ex: set ts=8 sts=4 sw=4 noet:
4578  */