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