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