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