This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Store C<study>'s data as U32s, instead of I32s.
[perl5.git] / util.c
1 /*    util.c
2  *
3  *    Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4  *    2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  * 'Very useful, no doubt, that was to Saruman; yet it seems that he was
13  *  not content.'                                    --Gandalf to Pippin
14  *
15  *     [p.598 of _The Lord of the Rings_, III/xi: "The Palantír"]
16  */
17
18 /* This file contains assorted utility routines.
19  * Which is a polite way of saying any stuff that people couldn't think of
20  * a better place for. Amongst other things, it includes the warning and
21  * dieing stuff, plus wrappers for malloc code.
22  */
23
24 #include "EXTERN.h"
25 #define PERL_IN_UTIL_C
26 #include "perl.h"
27
28 #ifdef USE_PERLIO
29 #include "perliol.h" /* For PerlIOUnix_refcnt */
30 #endif
31
32 #ifndef PERL_MICRO
33 #include <signal.h>
34 #ifndef SIG_ERR
35 # define SIG_ERR ((Sighandler_t) -1)
36 #endif
37 #endif
38
39 #ifdef __Lynx__
40 /* Missing protos on LynxOS */
41 int putenv(char *);
42 #endif
43
44 #ifdef I_SYS_WAIT
45 #  include <sys/wait.h>
46 #endif
47
48 #ifdef HAS_SELECT
49 # ifdef I_SYS_SELECT
50 #  include <sys/select.h>
51 # endif
52 #endif
53
54 #define FLUSH
55
56 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
57 #  define FD_CLOEXEC 1                  /* NeXT needs this */
58 #endif
59
60 /* NOTE:  Do not call the next three routines directly.  Use the macros
61  * in handy.h, so that we can easily redefine everything to do tracking of
62  * allocated hunks back to the original New to track down any memory leaks.
63  * XXX This advice seems to be widely ignored :-(   --AD  August 1996.
64  */
65
66 static char *
67 S_write_no_mem(pTHX)
68 {
69     dVAR;
70     /* Can't use PerlIO to write as it allocates memory */
71     PerlLIO_write(PerlIO_fileno(Perl_error_log),
72                   PL_no_mem, strlen(PL_no_mem));
73     my_exit(1);
74     NORETURN_FUNCTION_END;
75 }
76
77 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
78 #  define ALWAYS_NEED_THX
79 #endif
80
81 /* paranoid version of system's malloc() */
82
83 Malloc_t
84 Perl_safesysmalloc(MEM_SIZE size)
85 {
86 #ifdef ALWAYS_NEED_THX
87     dTHX;
88 #endif
89     Malloc_t ptr;
90 #ifdef HAS_64K_LIMIT
91         if (size > 0xffff) {
92             PerlIO_printf(Perl_error_log,
93                           "Allocation too large: %lx\n", size) FLUSH;
94             my_exit(1);
95         }
96 #endif /* HAS_64K_LIMIT */
97 #ifdef PERL_TRACK_MEMPOOL
98     size += sTHX;
99 #endif
100 #ifdef DEBUGGING
101     if ((long)size < 0)
102         Perl_croak_nocontext("panic: malloc");
103 #endif
104     ptr = (Malloc_t)PerlMem_malloc(size?size:1);        /* malloc(0) is NASTY on our system */
105     PERL_ALLOC_CHECK(ptr);
106     if (ptr != NULL) {
107 #ifdef PERL_TRACK_MEMPOOL
108         struct perl_memory_debug_header *const header
109             = (struct perl_memory_debug_header *)ptr;
110 #endif
111
112 #ifdef PERL_POISON
113         PoisonNew(((char *)ptr), size, char);
114 #endif
115
116 #ifdef PERL_TRACK_MEMPOOL
117         header->interpreter = aTHX;
118         /* Link us into the list.  */
119         header->prev = &PL_memory_debug_header;
120         header->next = PL_memory_debug_header.next;
121         PL_memory_debug_header.next = header;
122         header->next->prev = header;
123 #  ifdef PERL_POISON
124         header->size = size;
125 #  endif
126         ptr = (Malloc_t)((char*)ptr+sTHX);
127 #endif
128         DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
129         return ptr;
130 }
131     else {
132 #ifndef ALWAYS_NEED_THX
133         dTHX;
134 #endif
135         if (PL_nomemok)
136             return NULL;
137         else {
138             return write_no_mem();
139         }
140     }
141     /*NOTREACHED*/
142 }
143
144 /* paranoid version of system's realloc() */
145
146 Malloc_t
147 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
148 {
149 #ifdef ALWAYS_NEED_THX
150     dTHX;
151 #endif
152     Malloc_t ptr;
153 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
154     Malloc_t PerlMem_realloc();
155 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
156
157 #ifdef HAS_64K_LIMIT
158     if (size > 0xffff) {
159         PerlIO_printf(Perl_error_log,
160                       "Reallocation too large: %lx\n", size) FLUSH;
161         my_exit(1);
162     }
163 #endif /* HAS_64K_LIMIT */
164     if (!size) {
165         safesysfree(where);
166         return NULL;
167     }
168
169     if (!where)
170         return safesysmalloc(size);
171 #ifdef PERL_TRACK_MEMPOOL
172     where = (Malloc_t)((char*)where-sTHX);
173     size += sTHX;
174     {
175         struct perl_memory_debug_header *const header
176             = (struct perl_memory_debug_header *)where;
177
178         if (header->interpreter != aTHX) {
179             Perl_croak_nocontext("panic: realloc from wrong pool");
180         }
181         assert(header->next->prev == header);
182         assert(header->prev->next == header);
183 #  ifdef PERL_POISON
184         if (header->size > size) {
185             const MEM_SIZE freed_up = header->size - size;
186             char *start_of_freed = ((char *)where) + size;
187             PoisonFree(start_of_freed, freed_up, char);
188         }
189         header->size = size;
190 #  endif
191     }
192 #endif
193 #ifdef DEBUGGING
194     if ((long)size < 0)
195         Perl_croak_nocontext("panic: realloc");
196 #endif
197     ptr = (Malloc_t)PerlMem_realloc(where,size);
198     PERL_ALLOC_CHECK(ptr);
199
200     /* MUST do this fixup first, before doing ANYTHING else, as anything else
201        might allocate memory/free/move memory, and until we do the fixup, it
202        may well be chasing (and writing to) free memory.  */
203 #ifdef PERL_TRACK_MEMPOOL
204     if (ptr != NULL) {
205         struct perl_memory_debug_header *const header
206             = (struct perl_memory_debug_header *)ptr;
207
208 #  ifdef PERL_POISON
209         if (header->size < size) {
210             const MEM_SIZE fresh = size - header->size;
211             char *start_of_fresh = ((char *)ptr) + size;
212             PoisonNew(start_of_fresh, fresh, char);
213         }
214 #  endif
215
216         header->next->prev = header;
217         header->prev->next = header;
218
219         ptr = (Malloc_t)((char*)ptr+sTHX);
220     }
221 #endif
222
223     /* In particular, must do that fixup above before logging anything via
224      *printf(), as it can reallocate memory, which can cause SEGVs.  */
225
226     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
227     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
228
229
230     if (ptr != NULL) {
231         return ptr;
232     }
233     else {
234 #ifndef ALWAYS_NEED_THX
235         dTHX;
236 #endif
237         if (PL_nomemok)
238             return NULL;
239         else {
240             return write_no_mem();
241         }
242     }
243     /*NOTREACHED*/
244 }
245
246 /* safe version of system's free() */
247
248 Free_t
249 Perl_safesysfree(Malloc_t where)
250 {
251 #ifdef ALWAYS_NEED_THX
252     dTHX;
253 #else
254     dVAR;
255 #endif
256     DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
257     if (where) {
258 #ifdef PERL_TRACK_MEMPOOL
259         where = (Malloc_t)((char*)where-sTHX);
260         {
261             struct perl_memory_debug_header *const header
262                 = (struct perl_memory_debug_header *)where;
263
264             if (header->interpreter != aTHX) {
265                 Perl_croak_nocontext("panic: free from wrong pool");
266             }
267             if (!header->prev) {
268                 Perl_croak_nocontext("panic: duplicate free");
269             }
270             if (!(header->next) || header->next->prev != header
271                 || header->prev->next != header) {
272                 Perl_croak_nocontext("panic: bad free");
273             }
274             /* Unlink us from the chain.  */
275             header->next->prev = header->prev;
276             header->prev->next = header->next;
277 #  ifdef PERL_POISON
278             PoisonNew(where, header->size, char);
279 #  endif
280             /* Trigger the duplicate free warning.  */
281             header->next = NULL;
282         }
283 #endif
284         PerlMem_free(where);
285     }
286 }
287
288 /* safe version of system's calloc() */
289
290 Malloc_t
291 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
292 {
293 #ifdef ALWAYS_NEED_THX
294     dTHX;
295 #endif
296     Malloc_t ptr;
297 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
298     MEM_SIZE total_size = 0;
299 #endif
300
301     /* Even though calloc() for zero bytes is strange, be robust. */
302     if (size && (count <= MEM_SIZE_MAX / size)) {
303 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
304         total_size = size * count;
305 #endif
306     }
307     else
308         Perl_croak_nocontext("%s", PL_memory_wrap);
309 #ifdef PERL_TRACK_MEMPOOL
310     if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
311         total_size += sTHX;
312     else
313         Perl_croak_nocontext("%s", PL_memory_wrap);
314 #endif
315 #ifdef HAS_64K_LIMIT
316     if (total_size > 0xffff) {
317         PerlIO_printf(Perl_error_log,
318                       "Allocation too large: %lx\n", total_size) FLUSH;
319         my_exit(1);
320     }
321 #endif /* HAS_64K_LIMIT */
322 #ifdef DEBUGGING
323     if ((long)size < 0 || (long)count < 0)
324         Perl_croak_nocontext("panic: calloc");
325 #endif
326 #ifdef PERL_TRACK_MEMPOOL
327     /* Have to use malloc() because we've added some space for our tracking
328        header.  */
329     /* malloc(0) is non-portable. */
330     ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
331 #else
332     /* Use calloc() because it might save a memset() if the memory is fresh
333        and clean from the OS.  */
334     if (count && size)
335         ptr = (Malloc_t)PerlMem_calloc(count, size);
336     else /* calloc(0) is non-portable. */
337         ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
338 #endif
339     PERL_ALLOC_CHECK(ptr);
340     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)total_size));
341     if (ptr != NULL) {
342 #ifdef PERL_TRACK_MEMPOOL
343         {
344             struct perl_memory_debug_header *const header
345                 = (struct perl_memory_debug_header *)ptr;
346
347             memset((void*)ptr, 0, total_size);
348             header->interpreter = aTHX;
349             /* Link us into the list.  */
350             header->prev = &PL_memory_debug_header;
351             header->next = PL_memory_debug_header.next;
352             PL_memory_debug_header.next = header;
353             header->next->prev = header;
354 #  ifdef PERL_POISON
355             header->size = total_size;
356 #  endif
357             ptr = (Malloc_t)((char*)ptr+sTHX);
358         }
359 #endif
360         return ptr;
361     }
362     else {
363 #ifndef ALWAYS_NEED_THX
364         dTHX;
365 #endif
366         if (PL_nomemok)
367             return NULL;
368         return write_no_mem();
369     }
370 }
371
372 /* These must be defined when not using Perl's malloc for binary
373  * compatibility */
374
375 #ifndef MYMALLOC
376
377 Malloc_t Perl_malloc (MEM_SIZE nbytes)
378 {
379     dTHXs;
380     return (Malloc_t)PerlMem_malloc(nbytes);
381 }
382
383 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
384 {
385     dTHXs;
386     return (Malloc_t)PerlMem_calloc(elements, size);
387 }
388
389 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
390 {
391     dTHXs;
392     return (Malloc_t)PerlMem_realloc(where, nbytes);
393 }
394
395 Free_t   Perl_mfree (Malloc_t where)
396 {
397     dTHXs;
398     PerlMem_free(where);
399 }
400
401 #endif
402
403 /* copy a string up to some (non-backslashed) delimiter, if any */
404
405 char *
406 Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
407 {
408     register I32 tolen;
409
410     PERL_ARGS_ASSERT_DELIMCPY;
411
412     for (tolen = 0; from < fromend; from++, tolen++) {
413         if (*from == '\\') {
414             if (from[1] != delim) {
415                 if (to < toend)
416                     *to++ = *from;
417                 tolen++;
418             }
419             from++;
420         }
421         else if (*from == delim)
422             break;
423         if (to < toend)
424             *to++ = *from;
425     }
426     if (to < toend)
427         *to = '\0';
428     *retlen = tolen;
429     return (char *)from;
430 }
431
432 /* return ptr to little string in big string, NULL if not found */
433 /* This routine was donated by Corey Satten. */
434
435 char *
436 Perl_instr(register const char *big, register const char *little)
437 {
438     register I32 first;
439
440     PERL_ARGS_ASSERT_INSTR;
441
442     if (!little)
443         return (char*)big;
444     first = *little++;
445     if (!first)
446         return (char*)big;
447     while (*big) {
448         register const char *s, *x;
449         if (*big++ != first)
450             continue;
451         for (x=big,s=little; *s; /**/ ) {
452             if (!*x)
453                 return NULL;
454             if (*s != *x)
455                 break;
456             else {
457                 s++;
458                 x++;
459             }
460         }
461         if (!*s)
462             return (char*)(big-1);
463     }
464     return NULL;
465 }
466
467 /* same as instr but allow embedded nulls */
468
469 char *
470 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
471 {
472     PERL_ARGS_ASSERT_NINSTR;
473     if (little >= lend)
474         return (char*)big;
475     {
476         const char first = *little;
477         const char *s, *x;
478         bigend -= lend - little++;
479     OUTER:
480         while (big <= bigend) {
481             if (*big++ == first) {
482                 for (x=big,s=little; s < lend; x++,s++) {
483                     if (*s != *x)
484                         goto OUTER;
485                 }
486                 return (char*)(big-1);
487             }
488         }
489     }
490     return NULL;
491 }
492
493 /* reverse of the above--find last substring */
494
495 char *
496 Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
497 {
498     register const char *bigbeg;
499     register const I32 first = *little;
500     register const char * const littleend = lend;
501
502     PERL_ARGS_ASSERT_RNINSTR;
503
504     if (little >= littleend)
505         return (char*)bigend;
506     bigbeg = big;
507     big = bigend - (littleend - little++);
508     while (big >= bigbeg) {
509         register const char *s, *x;
510         if (*big-- != first)
511             continue;
512         for (x=big+2,s=little; s < littleend; /**/ ) {
513             if (*s != *x)
514                 break;
515             else {
516                 x++;
517                 s++;
518             }
519         }
520         if (s >= littleend)
521             return (char*)(big+1);
522     }
523     return NULL;
524 }
525
526 /* As a space optimization, we do not compile tables for strings of length
527    0 and 1, and for strings of length 2 unless FBMcf_TAIL.  These are
528    special-cased in fbm_instr().
529
530    If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
531
532 /*
533 =head1 Miscellaneous Functions
534
535 =for apidoc fbm_compile
536
537 Analyses the string in order to make fast searches on it using fbm_instr()
538 -- the Boyer-Moore algorithm.
539
540 =cut
541 */
542
543 void
544 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
545 {
546     dVAR;
547     register const U8 *s;
548     STRLEN i;
549     STRLEN len;
550     STRLEN rarest = 0;
551     U32 frequency = 256;
552     MAGIC *mg;
553
554     PERL_ARGS_ASSERT_FBM_COMPILE;
555
556     /* Refuse to fbm_compile a studied scalar, as this gives more flexibility in
557        SV flag usage.  No real-world code would ever end up using a studied
558        scalar as a compile-time second argument to index, so this isn't a real
559        pessimisation.  */
560     if (SvSCREAM(sv))
561         return;
562
563     if (SvVALID(sv))
564         return;
565
566     if (flags & FBMcf_TAIL) {
567         MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
568         sv_catpvs(sv, "\n");            /* Taken into account in fbm_instr() */
569         if (mg && mg->mg_len >= 0)
570             mg->mg_len++;
571     }
572     s = (U8*)SvPV_force_mutable(sv, len);
573     if (len == 0)               /* TAIL might be on a zero-length string. */
574         return;
575     SvUPGRADE(sv, SVt_PVMG);
576     SvIOK_off(sv);
577     SvNOK_off(sv);
578     SvVALID_on(sv);
579
580     /* "deep magic", the comment used to add. The use of MAGIC itself isn't
581        really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
582        to call SvVALID_off() if the scalar was assigned to.
583
584        The comment itself (and "deeper magic" below) date back to
585        378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
586        str->str_pok |= 2;
587        where the magic (presumably) was that the scalar had a BM table hidden
588        inside itself.
589
590        As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
591        the table instead of the previous (somewhat hacky) approach of co-opting
592        the string buffer and storing it after the string.  */
593
594     assert(!mg_find(sv, PERL_MAGIC_bm));
595     mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
596     assert(mg);
597
598     if (len > 2) {
599         /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
600            the BM table.  */
601         const U8 mlen = (len>255) ? 255 : (U8)len;
602         const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
603         register U8 *table;
604
605         Newx(table, 256, U8);
606         memset((void*)table, mlen, 256);
607         mg->mg_ptr = (char *)table;
608         mg->mg_len = 256;
609
610         s += len - 1; /* last char */
611         i = 0;
612         while (s >= sb) {
613             if (table[*s] == mlen)
614                 table[*s] = (U8)i;
615             s--, i++;
616         }
617     }
618
619     s = (const unsigned char*)(SvPVX_const(sv));        /* deeper magic */
620     for (i = 0; i < len; i++) {
621         if (PL_freq[s[i]] < frequency) {
622             rarest = i;
623             frequency = PL_freq[s[i]];
624         }
625     }
626     BmRARE(sv) = s[rarest];
627     BmPREVIOUS(sv) = rarest;
628     BmUSEFUL(sv) = 100;                 /* Initial value */
629     if (flags & FBMcf_TAIL)
630         SvTAIL_on(sv);
631     DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
632                           BmRARE(sv), BmPREVIOUS(sv)));
633 }
634
635 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
636 /* If SvTAIL is actually due to \Z or \z, this gives false positives
637    if multiline */
638
639 /*
640 =for apidoc fbm_instr
641
642 Returns the location of the SV in the string delimited by C<str> and
643 C<strend>.  It returns C<NULL> if the string can't be found.  The C<sv>
644 does not have to be fbm_compiled, but the search will not be as fast
645 then.
646
647 =cut
648 */
649
650 char *
651 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
652 {
653     register unsigned char *s;
654     STRLEN l;
655     register const unsigned char *little
656         = (const unsigned char *)SvPV_const(littlestr,l);
657     register STRLEN littlelen = l;
658     register const I32 multiline = flags & FBMrf_MULTILINE;
659
660     PERL_ARGS_ASSERT_FBM_INSTR;
661
662     if ((STRLEN)(bigend - big) < littlelen) {
663         if ( SvTAIL(littlestr)
664              && ((STRLEN)(bigend - big) == littlelen - 1)
665              && (littlelen == 1
666                  || (*big == *little &&
667                      memEQ((char *)big, (char *)little, littlelen - 1))))
668             return (char*)big;
669         return NULL;
670     }
671
672     switch (littlelen) { /* Special cases for 0, 1 and 2  */
673     case 0:
674         return (char*)big;              /* Cannot be SvTAIL! */
675     case 1:
676             if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
677                 /* Know that bigend != big.  */
678                 if (bigend[-1] == '\n')
679                     return (char *)(bigend - 1);
680                 return (char *) bigend;
681             }
682             s = big;
683             while (s < bigend) {
684                 if (*s == *little)
685                     return (char *)s;
686                 s++;
687             }
688             if (SvTAIL(littlestr))
689                 return (char *) bigend;
690             return NULL;
691     case 2:
692         if (SvTAIL(littlestr) && !multiline) {
693             if (bigend[-1] == '\n' && bigend[-2] == *little)
694                 return (char*)bigend - 2;
695             if (bigend[-1] == *little)
696                 return (char*)bigend - 1;
697             return NULL;
698         }
699         {
700             /* This should be better than FBM if c1 == c2, and almost
701                as good otherwise: maybe better since we do less indirection.
702                And we save a lot of memory by caching no table. */
703             const unsigned char c1 = little[0];
704             const unsigned char c2 = little[1];
705
706             s = big + 1;
707             bigend--;
708             if (c1 != c2) {
709                 while (s <= bigend) {
710                     if (s[0] == c2) {
711                         if (s[-1] == c1)
712                             return (char*)s - 1;
713                         s += 2;
714                         continue;
715                     }
716                   next_chars:
717                     if (s[0] == c1) {
718                         if (s == bigend)
719                             goto check_1char_anchor;
720                         if (s[1] == c2)
721                             return (char*)s;
722                         else {
723                             s++;
724                             goto next_chars;
725                         }
726                     }
727                     else
728                         s += 2;
729                 }
730                 goto check_1char_anchor;
731             }
732             /* Now c1 == c2 */
733             while (s <= bigend) {
734                 if (s[0] == c1) {
735                     if (s[-1] == c1)
736                         return (char*)s - 1;
737                     if (s == bigend)
738                         goto check_1char_anchor;
739                     if (s[1] == c1)
740                         return (char*)s;
741                     s += 3;
742                 }
743                 else
744                     s += 2;
745             }
746         }
747       check_1char_anchor:               /* One char and anchor! */
748         if (SvTAIL(littlestr) && (*bigend == *little))
749             return (char *)bigend;      /* bigend is already decremented. */
750         return NULL;
751     default:
752         break; /* Only lengths 0 1 and 2 have special-case code.  */
753     }
754
755     if (SvTAIL(littlestr) && !multiline) {      /* tail anchored? */
756         s = bigend - littlelen;
757         if (s >= big && bigend[-1] == '\n' && *s == *little
758             /* Automatically of length > 2 */
759             && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
760         {
761             return (char*)s;            /* how sweet it is */
762         }
763         if (s[1] == *little
764             && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
765         {
766             return (char*)s + 1;        /* how sweet it is */
767         }
768         return NULL;
769     }
770     if (!SvVALID(littlestr)) {
771         char * const b = ninstr((char*)big,(char*)bigend,
772                          (char*)little, (char*)little + littlelen);
773
774         if (!b && SvTAIL(littlestr)) {  /* Automatically multiline!  */
775             /* Chop \n from littlestr: */
776             s = bigend - littlelen + 1;
777             if (*s == *little
778                 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
779             {
780                 return (char*)s;
781             }
782             return NULL;
783         }
784         return b;
785     }
786
787     /* Do actual FBM.  */
788     if (littlelen > (STRLEN)(bigend - big))
789         return NULL;
790
791     {
792         const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
793         const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
794         register const unsigned char *oldlittle;
795
796         --littlelen;                    /* Last char found by table lookup */
797
798         s = big + littlelen;
799         little += littlelen;            /* last char */
800         oldlittle = little;
801         if (s < bigend) {
802             register I32 tmp;
803
804           top2:
805             if ((tmp = table[*s])) {
806                 if ((s += tmp) < bigend)
807                     goto top2;
808                 goto check_end;
809             }
810             else {              /* less expensive than calling strncmp() */
811                 register unsigned char * const olds = s;
812
813                 tmp = littlelen;
814
815                 while (tmp--) {
816                     if (*--s == *--little)
817                         continue;
818                     s = olds + 1;       /* here we pay the price for failure */
819                     little = oldlittle;
820                     if (s < bigend)     /* fake up continue to outer loop */
821                         goto top2;
822                     goto check_end;
823                 }
824                 return (char *)s;
825             }
826         }
827       check_end:
828         if ( s == bigend
829              && SvTAIL(littlestr)
830              && memEQ((char *)(bigend - littlelen),
831                       (char *)(oldlittle - littlelen), littlelen) )
832             return (char*)bigend - littlelen;
833         return NULL;
834     }
835 }
836
837 /* start_shift, end_shift are positive quantities which give offsets
838    of ends of some substring of bigstr.
839    If "last" we want the last occurrence.
840    old_posp is the way of communication between consequent calls if
841    the next call needs to find the .
842    The initial *old_posp should be -1.
843
844    Note that we take into account SvTAIL, so one can get extra
845    optimizations if _ALL flag is set.
846  */
847
848 /* If SvTAIL is actually due to \Z or \z, this gives false positives
849    if PL_multiline.  In fact if !PL_multiline the authoritative answer
850    is not supported yet. */
851
852 char *
853 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
854 {
855     dVAR;
856     register const unsigned char *big;
857     U32 pos;
858     register I32 previous;
859     register I32 first;
860     register const unsigned char *little;
861     register I32 stop_pos;
862     register const unsigned char *littleend;
863     bool found = FALSE;
864     const MAGIC * mg;
865     U32 *screamfirst;
866     U32 *screamnext;
867     U32 const nope = ~0;
868
869     PERL_ARGS_ASSERT_SCREAMINSTR;
870
871     assert(SvMAGICAL(bigstr));
872     mg = mg_find(bigstr, PERL_MAGIC_study);
873     assert(mg);
874     assert(SvTYPE(littlestr) == SVt_PVMG);
875     assert(SvVALID(littlestr));
876
877     screamfirst = (U32 *)mg->mg_ptr;
878     screamnext = screamfirst + 256;
879
880     pos = *old_posp == -1
881         ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
882     if (pos == nope) {
883       cant_find:
884         if ( BmRARE(littlestr) == '\n'
885              && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
886             little = (const unsigned char *)(SvPVX_const(littlestr));
887             littleend = little + SvCUR(littlestr);
888             first = *little++;
889             goto check_tail;
890         }
891         return NULL;
892     }
893
894     little = (const unsigned char *)(SvPVX_const(littlestr));
895     littleend = little + SvCUR(littlestr);
896     first = *little++;
897     /* The value of pos we can start at: */
898     previous = BmPREVIOUS(littlestr);
899     big = (const unsigned char *)(SvPVX_const(bigstr));
900     /* The value of pos we can stop at: */
901     stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
902     if (previous + start_shift > stop_pos) {
903 /*
904   stop_pos does not include SvTAIL in the count, so this check is incorrect
905   (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
906 */
907 #if 0
908         if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
909             goto check_tail;
910 #endif
911         return NULL;
912     }
913     while ((I32)pos < previous + start_shift) {
914         pos = screamnext[pos];
915         if (pos == nope)
916             goto cant_find;
917     }
918     big -= previous;
919     do {
920         if ((I32)pos >= stop_pos) break;
921         if (big[pos] == first) {
922             const unsigned char *s = little;
923             const unsigned char *x = big + pos + 1;
924             while (s < littleend) {
925                 if (*s != *x++)
926                     break;
927                 ++s;
928             }
929             if (s == littleend) {
930                 *old_posp = (I32)pos;
931                 if (!last) return (char *)(big+pos);
932                 found = TRUE;
933             }
934         }
935         pos = screamnext[pos];
936     } while (pos != nope);
937     if (last && found)
938         return (char *)(big+(*old_posp));
939   check_tail:
940     if (!SvTAIL(littlestr) || (end_shift > 0))
941         return NULL;
942     /* Ignore the trailing "\n".  This code is not microoptimized */
943     big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
944     stop_pos = littleend - little;      /* Actual littlestr len */
945     if (stop_pos == 0)
946         return (char*)big;
947     big -= stop_pos;
948     if (*big == first
949         && ((stop_pos == 1) ||
950             memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
951         return (char*)big;
952     return NULL;
953 }
954
955 /*
956 =for apidoc foldEQ
957
958 Returns true if the leading len bytes of the strings s1 and s2 are the same
959 case-insensitively; false otherwise.  Uppercase and lowercase ASCII range bytes
960 match themselves and their opposite case counterparts.  Non-cased and non-ASCII
961 range bytes match only themselves.
962
963 =cut
964 */
965
966
967 I32
968 Perl_foldEQ(const char *s1, const char *s2, register I32 len)
969 {
970     register const U8 *a = (const U8 *)s1;
971     register const U8 *b = (const U8 *)s2;
972
973     PERL_ARGS_ASSERT_FOLDEQ;
974
975     while (len--) {
976         if (*a != *b && *a != PL_fold[*b])
977             return 0;
978         a++,b++;
979     }
980     return 1;
981 }
982 I32
983 Perl_foldEQ_latin1(const char *s1, const char *s2, register I32 len)
984 {
985     /* Compare non-utf8 using Unicode (Latin1) semantics.  Does not work on
986      * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
987      * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these.  Nor
988      * does it check that the strings each have at least 'len' characters */
989
990     register const U8 *a = (const U8 *)s1;
991     register const U8 *b = (const U8 *)s2;
992
993     PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
994
995     while (len--) {
996         if (*a != *b && *a != PL_fold_latin1[*b]) {
997             return 0;
998         }
999         a++, b++;
1000     }
1001     return 1;
1002 }
1003
1004 /*
1005 =for apidoc foldEQ_locale
1006
1007 Returns true if the leading len bytes of the strings s1 and s2 are the same
1008 case-insensitively in the current locale; false otherwise.
1009
1010 =cut
1011 */
1012
1013 I32
1014 Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
1015 {
1016     dVAR;
1017     register const U8 *a = (const U8 *)s1;
1018     register const U8 *b = (const U8 *)s2;
1019
1020     PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
1021
1022     while (len--) {
1023         if (*a != *b && *a != PL_fold_locale[*b])
1024             return 0;
1025         a++,b++;
1026     }
1027     return 1;
1028 }
1029
1030 /* copy a string to a safe spot */
1031
1032 /*
1033 =head1 Memory Management
1034
1035 =for apidoc savepv
1036
1037 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1038 string which is a duplicate of C<pv>. The size of the string is
1039 determined by C<strlen()>. The memory allocated for the new string can
1040 be freed with the C<Safefree()> function.
1041
1042 =cut
1043 */
1044
1045 char *
1046 Perl_savepv(pTHX_ const char *pv)
1047 {
1048     PERL_UNUSED_CONTEXT;
1049     if (!pv)
1050         return NULL;
1051     else {
1052         char *newaddr;
1053         const STRLEN pvlen = strlen(pv)+1;
1054         Newx(newaddr, pvlen, char);
1055         return (char*)memcpy(newaddr, pv, pvlen);
1056     }
1057 }
1058
1059 /* same thing but with a known length */
1060
1061 /*
1062 =for apidoc savepvn
1063
1064 Perl's version of what C<strndup()> would be if it existed. Returns a
1065 pointer to a newly allocated string which is a duplicate of the first
1066 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
1067 the new string can be freed with the C<Safefree()> function.
1068
1069 =cut
1070 */
1071
1072 char *
1073 Perl_savepvn(pTHX_ const char *pv, register I32 len)
1074 {
1075     register char *newaddr;
1076     PERL_UNUSED_CONTEXT;
1077
1078     Newx(newaddr,len+1,char);
1079     /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1080     if (pv) {
1081         /* might not be null terminated */
1082         newaddr[len] = '\0';
1083         return (char *) CopyD(pv,newaddr,len,char);
1084     }
1085     else {
1086         return (char *) ZeroD(newaddr,len+1,char);
1087     }
1088 }
1089
1090 /*
1091 =for apidoc savesharedpv
1092
1093 A version of C<savepv()> which allocates the duplicate string in memory
1094 which is shared between threads.
1095
1096 =cut
1097 */
1098 char *
1099 Perl_savesharedpv(pTHX_ const char *pv)
1100 {
1101     register char *newaddr;
1102     STRLEN pvlen;
1103     if (!pv)
1104         return NULL;
1105
1106     pvlen = strlen(pv)+1;
1107     newaddr = (char*)PerlMemShared_malloc(pvlen);
1108     if (!newaddr) {
1109         return write_no_mem();
1110     }
1111     return (char*)memcpy(newaddr, pv, pvlen);
1112 }
1113
1114 /*
1115 =for apidoc savesharedpvn
1116
1117 A version of C<savepvn()> which allocates the duplicate string in memory
1118 which is shared between threads. (With the specific difference that a NULL
1119 pointer is not acceptable)
1120
1121 =cut
1122 */
1123 char *
1124 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1125 {
1126     char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1127
1128     PERL_ARGS_ASSERT_SAVESHAREDPVN;
1129
1130     if (!newaddr) {
1131         return write_no_mem();
1132     }
1133     newaddr[len] = '\0';
1134     return (char*)memcpy(newaddr, pv, len);
1135 }
1136
1137 /*
1138 =for apidoc savesvpv
1139
1140 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1141 the passed in SV using C<SvPV()>
1142
1143 =cut
1144 */
1145
1146 char *
1147 Perl_savesvpv(pTHX_ SV *sv)
1148 {
1149     STRLEN len;
1150     const char * const pv = SvPV_const(sv, len);
1151     register char *newaddr;
1152
1153     PERL_ARGS_ASSERT_SAVESVPV;
1154
1155     ++len;
1156     Newx(newaddr,len,char);
1157     return (char *) CopyD(pv,newaddr,len,char);
1158 }
1159
1160 /*
1161 =for apidoc savesharedsvpv
1162
1163 A version of C<savesharedpv()> which allocates the duplicate string in
1164 memory which is shared between threads.
1165
1166 =cut
1167 */
1168
1169 char *
1170 Perl_savesharedsvpv(pTHX_ SV *sv)
1171 {
1172     STRLEN len;
1173     const char * const pv = SvPV_const(sv, len);
1174
1175     PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1176
1177     return savesharedpvn(pv, len);
1178 }
1179
1180 /* the SV for Perl_form() and mess() is not kept in an arena */
1181
1182 STATIC SV *
1183 S_mess_alloc(pTHX)
1184 {
1185     dVAR;
1186     SV *sv;
1187     XPVMG *any;
1188
1189     if (PL_phase != PERL_PHASE_DESTRUCT)
1190         return newSVpvs_flags("", SVs_TEMP);
1191
1192     if (PL_mess_sv)
1193         return PL_mess_sv;
1194
1195     /* Create as PVMG now, to avoid any upgrading later */
1196     Newx(sv, 1, SV);
1197     Newxz(any, 1, XPVMG);
1198     SvFLAGS(sv) = SVt_PVMG;
1199     SvANY(sv) = (void*)any;
1200     SvPV_set(sv, NULL);
1201     SvREFCNT(sv) = 1 << 30; /* practically infinite */
1202     PL_mess_sv = sv;
1203     return sv;
1204 }
1205
1206 #if defined(PERL_IMPLICIT_CONTEXT)
1207 char *
1208 Perl_form_nocontext(const char* pat, ...)
1209 {
1210     dTHX;
1211     char *retval;
1212     va_list args;
1213     PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1214     va_start(args, pat);
1215     retval = vform(pat, &args);
1216     va_end(args);
1217     return retval;
1218 }
1219 #endif /* PERL_IMPLICIT_CONTEXT */
1220
1221 /*
1222 =head1 Miscellaneous Functions
1223 =for apidoc form
1224
1225 Takes a sprintf-style format pattern and conventional
1226 (non-SV) arguments and returns the formatted string.
1227
1228     (char *) Perl_form(pTHX_ const char* pat, ...)
1229
1230 can be used any place a string (char *) is required:
1231
1232     char * s = Perl_form("%d.%d",major,minor);
1233
1234 Uses a single private buffer so if you want to format several strings you
1235 must explicitly copy the earlier strings away (and free the copies when you
1236 are done).
1237
1238 =cut
1239 */
1240
1241 char *
1242 Perl_form(pTHX_ const char* pat, ...)
1243 {
1244     char *retval;
1245     va_list args;
1246     PERL_ARGS_ASSERT_FORM;
1247     va_start(args, pat);
1248     retval = vform(pat, &args);
1249     va_end(args);
1250     return retval;
1251 }
1252
1253 char *
1254 Perl_vform(pTHX_ const char *pat, va_list *args)
1255 {
1256     SV * const sv = mess_alloc();
1257     PERL_ARGS_ASSERT_VFORM;
1258     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1259     return SvPVX(sv);
1260 }
1261
1262 /*
1263 =for apidoc Am|SV *|mess|const char *pat|...
1264
1265 Take a sprintf-style format pattern and argument list.  These are used to
1266 generate a string message.  If the message does not end with a newline,
1267 then it will be extended with some indication of the current location
1268 in the code, as described for L</mess_sv>.
1269
1270 Normally, the resulting message is returned in a new mortal SV.
1271 During global destruction a single SV may be shared between uses of
1272 this function.
1273
1274 =cut
1275 */
1276
1277 #if defined(PERL_IMPLICIT_CONTEXT)
1278 SV *
1279 Perl_mess_nocontext(const char *pat, ...)
1280 {
1281     dTHX;
1282     SV *retval;
1283     va_list args;
1284     PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1285     va_start(args, pat);
1286     retval = vmess(pat, &args);
1287     va_end(args);
1288     return retval;
1289 }
1290 #endif /* PERL_IMPLICIT_CONTEXT */
1291
1292 SV *
1293 Perl_mess(pTHX_ const char *pat, ...)
1294 {
1295     SV *retval;
1296     va_list args;
1297     PERL_ARGS_ASSERT_MESS;
1298     va_start(args, pat);
1299     retval = vmess(pat, &args);
1300     va_end(args);
1301     return retval;
1302 }
1303
1304 STATIC const COP*
1305 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1306 {
1307     dVAR;
1308     /* Look for PL_op starting from o.  cop is the last COP we've seen. */
1309
1310     PERL_ARGS_ASSERT_CLOSEST_COP;
1311
1312     if (!o || o == PL_op)
1313         return cop;
1314
1315     if (o->op_flags & OPf_KIDS) {
1316         const OP *kid;
1317         for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1318             const COP *new_cop;
1319
1320             /* If the OP_NEXTSTATE has been optimised away we can still use it
1321              * the get the file and line number. */
1322
1323             if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1324                 cop = (const COP *)kid;
1325
1326             /* Keep searching, and return when we've found something. */
1327
1328             new_cop = closest_cop(cop, kid);
1329             if (new_cop)
1330                 return new_cop;
1331         }
1332     }
1333
1334     /* Nothing found. */
1335
1336     return NULL;
1337 }
1338
1339 /*
1340 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1341
1342 Expands a message, intended for the user, to include an indication of
1343 the current location in the code, if the message does not already appear
1344 to be complete.
1345
1346 C<basemsg> is the initial message or object.  If it is a reference, it
1347 will be used as-is and will be the result of this function.  Otherwise it
1348 is used as a string, and if it already ends with a newline, it is taken
1349 to be complete, and the result of this function will be the same string.
1350 If the message does not end with a newline, then a segment such as C<at
1351 foo.pl line 37> will be appended, and possibly other clauses indicating
1352 the current state of execution.  The resulting message will end with a
1353 dot and a newline.
1354
1355 Normally, the resulting message is returned in a new mortal SV.
1356 During global destruction a single SV may be shared between uses of this
1357 function.  If C<consume> is true, then the function is permitted (but not
1358 required) to modify and return C<basemsg> instead of allocating a new SV.
1359
1360 =cut
1361 */
1362
1363 SV *
1364 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1365 {
1366     dVAR;
1367     SV *sv;
1368
1369     PERL_ARGS_ASSERT_MESS_SV;
1370
1371     if (SvROK(basemsg)) {
1372         if (consume) {
1373             sv = basemsg;
1374         }
1375         else {
1376             sv = mess_alloc();
1377             sv_setsv(sv, basemsg);
1378         }
1379         return sv;
1380     }
1381
1382     if (SvPOK(basemsg) && consume) {
1383         sv = basemsg;
1384     }
1385     else {
1386         sv = mess_alloc();
1387         sv_copypv(sv, basemsg);
1388     }
1389
1390     if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1391         /*
1392          * Try and find the file and line for PL_op.  This will usually be
1393          * PL_curcop, but it might be a cop that has been optimised away.  We
1394          * can try to find such a cop by searching through the optree starting
1395          * from the sibling of PL_curcop.
1396          */
1397
1398         const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1399         if (!cop)
1400             cop = PL_curcop;
1401
1402         if (CopLINE(cop))
1403             Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1404             OutCopFILE(cop), (IV)CopLINE(cop));
1405         /* Seems that GvIO() can be untrustworthy during global destruction. */
1406         if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1407                 && IoLINES(GvIOp(PL_last_in_gv)))
1408         {
1409             const bool line_mode = (RsSIMPLE(PL_rs) &&
1410                               SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1411             Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1412                            PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1413                            line_mode ? "line" : "chunk",
1414                            (IV)IoLINES(GvIOp(PL_last_in_gv)));
1415         }
1416         if (PL_phase == PERL_PHASE_DESTRUCT)
1417             sv_catpvs(sv, " during global destruction");
1418         sv_catpvs(sv, ".\n");
1419     }
1420     return sv;
1421 }
1422
1423 /*
1424 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1425
1426 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1427 argument list.  These are used to generate a string message.  If the
1428 message does not end with a newline, then it will be extended with
1429 some indication of the current location in the code, as described for
1430 L</mess_sv>.
1431
1432 Normally, the resulting message is returned in a new mortal SV.
1433 During global destruction a single SV may be shared between uses of
1434 this function.
1435
1436 =cut
1437 */
1438
1439 SV *
1440 Perl_vmess(pTHX_ const char *pat, va_list *args)
1441 {
1442     dVAR;
1443     SV * const sv = mess_alloc();
1444
1445     PERL_ARGS_ASSERT_VMESS;
1446
1447     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1448     return mess_sv(sv, 1);
1449 }
1450
1451 void
1452 Perl_write_to_stderr(pTHX_ SV* msv)
1453 {
1454     dVAR;
1455     IO *io;
1456     MAGIC *mg;
1457
1458     PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1459
1460     if (PL_stderrgv && SvREFCNT(PL_stderrgv) 
1461         && (io = GvIO(PL_stderrgv))
1462         && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar))) 
1463         Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1464                             G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1465     else {
1466 #ifdef USE_SFIO
1467         /* SFIO can really mess with your errno */
1468         dSAVED_ERRNO;
1469 #endif
1470         PerlIO * const serr = Perl_error_log;
1471
1472         do_print(msv, serr);
1473         (void)PerlIO_flush(serr);
1474 #ifdef USE_SFIO
1475         RESTORE_ERRNO;
1476 #endif
1477     }
1478 }
1479
1480 /*
1481 =head1 Warning and Dieing
1482 */
1483
1484 /* Common code used in dieing and warning */
1485
1486 STATIC SV *
1487 S_with_queued_errors(pTHX_ SV *ex)
1488 {
1489     PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1490     if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1491         sv_catsv(PL_errors, ex);
1492         ex = sv_mortalcopy(PL_errors);
1493         SvCUR_set(PL_errors, 0);
1494     }
1495     return ex;
1496 }
1497
1498 STATIC bool
1499 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1500 {
1501     dVAR;
1502     HV *stash;
1503     GV *gv;
1504     CV *cv;
1505     SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1506     /* sv_2cv might call Perl_croak() or Perl_warner() */
1507     SV * const oldhook = *hook;
1508
1509     if (!oldhook)
1510         return FALSE;
1511
1512     ENTER;
1513     SAVESPTR(*hook);
1514     *hook = NULL;
1515     cv = sv_2cv(oldhook, &stash, &gv, 0);
1516     LEAVE;
1517     if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1518         dSP;
1519         SV *exarg;
1520
1521         ENTER;
1522         save_re_context();
1523         if (warn) {
1524             SAVESPTR(*hook);
1525             *hook = NULL;
1526         }
1527         exarg = newSVsv(ex);
1528         SvREADONLY_on(exarg);
1529         SAVEFREESV(exarg);
1530
1531         PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1532         PUSHMARK(SP);
1533         XPUSHs(exarg);
1534         PUTBACK;
1535         call_sv(MUTABLE_SV(cv), G_DISCARD);
1536         POPSTACK;
1537         LEAVE;
1538         return TRUE;
1539     }
1540     return FALSE;
1541 }
1542
1543 /*
1544 =for apidoc Am|OP *|die_sv|SV *baseex
1545
1546 Behaves the same as L</croak_sv>, except for the return type.
1547 It should be used only where the C<OP *> return type is required.
1548 The function never actually returns.
1549
1550 =cut
1551 */
1552
1553 OP *
1554 Perl_die_sv(pTHX_ SV *baseex)
1555 {
1556     PERL_ARGS_ASSERT_DIE_SV;
1557     croak_sv(baseex);
1558     /* NOTREACHED */
1559     return NULL;
1560 }
1561
1562 /*
1563 =for apidoc Am|OP *|die|const char *pat|...
1564
1565 Behaves the same as L</croak>, except for the return type.
1566 It should be used only where the C<OP *> return type is required.
1567 The function never actually returns.
1568
1569 =cut
1570 */
1571
1572 #if defined(PERL_IMPLICIT_CONTEXT)
1573 OP *
1574 Perl_die_nocontext(const char* pat, ...)
1575 {
1576     dTHX;
1577     va_list args;
1578     va_start(args, pat);
1579     vcroak(pat, &args);
1580     /* NOTREACHED */
1581     va_end(args);
1582     return NULL;
1583 }
1584 #endif /* PERL_IMPLICIT_CONTEXT */
1585
1586 OP *
1587 Perl_die(pTHX_ const char* pat, ...)
1588 {
1589     va_list args;
1590     va_start(args, pat);
1591     vcroak(pat, &args);
1592     /* NOTREACHED */
1593     va_end(args);
1594     return NULL;
1595 }
1596
1597 /*
1598 =for apidoc Am|void|croak_sv|SV *baseex
1599
1600 This is an XS interface to Perl's C<die> function.
1601
1602 C<baseex> is the error message or object.  If it is a reference, it
1603 will be used as-is.  Otherwise it is used as a string, and if it does
1604 not end with a newline then it will be extended with some indication of
1605 the current location in the code, as described for L</mess_sv>.
1606
1607 The error message or object will be used as an exception, by default
1608 returning control to the nearest enclosing C<eval>, but subject to
1609 modification by a C<$SIG{__DIE__}> handler.  In any case, the C<croak_sv>
1610 function never returns normally.
1611
1612 To die with a simple string message, the L</croak> function may be
1613 more convenient.
1614
1615 =cut
1616 */
1617
1618 void
1619 Perl_croak_sv(pTHX_ SV *baseex)
1620 {
1621     SV *ex = with_queued_errors(mess_sv(baseex, 0));
1622     PERL_ARGS_ASSERT_CROAK_SV;
1623     invoke_exception_hook(ex, FALSE);
1624     die_unwind(ex);
1625 }
1626
1627 /*
1628 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1629
1630 This is an XS interface to Perl's C<die> function.
1631
1632 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1633 argument list.  These are used to generate a string message.  If the
1634 message does not end with a newline, then it will be extended with
1635 some indication of the current location in the code, as described for
1636 L</mess_sv>.
1637
1638 The error message will be used as an exception, by default
1639 returning control to the nearest enclosing C<eval>, but subject to
1640 modification by a C<$SIG{__DIE__}> handler.  In any case, the C<croak>
1641 function never returns normally.
1642
1643 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1644 (C<$@>) will be used as an error message or object instead of building an
1645 error message from arguments.  If you want to throw a non-string object,
1646 or build an error message in an SV yourself, it is preferable to use
1647 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1648
1649 =cut
1650 */
1651
1652 void
1653 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1654 {
1655     SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1656     invoke_exception_hook(ex, FALSE);
1657     die_unwind(ex);
1658 }
1659
1660 /*
1661 =for apidoc Am|void|croak|const char *pat|...
1662
1663 This is an XS interface to Perl's C<die> function.
1664
1665 Take a sprintf-style format pattern and argument list.  These are used to
1666 generate a string message.  If the message does not end with a newline,
1667 then it will be extended with some indication of the current location
1668 in the code, as described for L</mess_sv>.
1669
1670 The error message will be used as an exception, by default
1671 returning control to the nearest enclosing C<eval>, but subject to
1672 modification by a C<$SIG{__DIE__}> handler.  In any case, the C<croak>
1673 function never returns normally.
1674
1675 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1676 (C<$@>) will be used as an error message or object instead of building an
1677 error message from arguments.  If you want to throw a non-string object,
1678 or build an error message in an SV yourself, it is preferable to use
1679 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1680
1681 =cut
1682 */
1683
1684 #if defined(PERL_IMPLICIT_CONTEXT)
1685 void
1686 Perl_croak_nocontext(const char *pat, ...)
1687 {
1688     dTHX;
1689     va_list args;
1690     va_start(args, pat);
1691     vcroak(pat, &args);
1692     /* NOTREACHED */
1693     va_end(args);
1694 }
1695 #endif /* PERL_IMPLICIT_CONTEXT */
1696
1697 void
1698 Perl_croak(pTHX_ const char *pat, ...)
1699 {
1700     va_list args;
1701     va_start(args, pat);
1702     vcroak(pat, &args);
1703     /* NOTREACHED */
1704     va_end(args);
1705 }
1706
1707 /*
1708 =for apidoc Am|void|croak_no_modify
1709
1710 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1711 terser object code than using C<Perl_croak>. Less code used on exception code
1712 paths reduces CPU cache pressure.
1713
1714 =cut
1715 */
1716
1717 void
1718 Perl_croak_no_modify(pTHX)
1719 {
1720     Perl_croak(aTHX_ "%s", PL_no_modify);
1721 }
1722
1723 /*
1724 =for apidoc Am|void|warn_sv|SV *baseex
1725
1726 This is an XS interface to Perl's C<warn> function.
1727
1728 C<baseex> is the error message or object.  If it is a reference, it
1729 will be used as-is.  Otherwise it is used as a string, and if it does
1730 not end with a newline then it will be extended with some indication of
1731 the current location in the code, as described for L</mess_sv>.
1732
1733 The error message or object will by default be written to standard error,
1734 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1735
1736 To warn with a simple string message, the L</warn> function may be
1737 more convenient.
1738
1739 =cut
1740 */
1741
1742 void
1743 Perl_warn_sv(pTHX_ SV *baseex)
1744 {
1745     SV *ex = mess_sv(baseex, 0);
1746     PERL_ARGS_ASSERT_WARN_SV;
1747     if (!invoke_exception_hook(ex, TRUE))
1748         write_to_stderr(ex);
1749 }
1750
1751 /*
1752 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1753
1754 This is an XS interface to Perl's C<warn> function.
1755
1756 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1757 argument list.  These are used to generate a string message.  If the
1758 message does not end with a newline, then it will be extended with
1759 some indication of the current location in the code, as described for
1760 L</mess_sv>.
1761
1762 The error message or object will by default be written to standard error,
1763 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1764
1765 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1766
1767 =cut
1768 */
1769
1770 void
1771 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1772 {
1773     SV *ex = vmess(pat, args);
1774     PERL_ARGS_ASSERT_VWARN;
1775     if (!invoke_exception_hook(ex, TRUE))
1776         write_to_stderr(ex);
1777 }
1778
1779 /*
1780 =for apidoc Am|void|warn|const char *pat|...
1781
1782 This is an XS interface to Perl's C<warn> function.
1783
1784 Take a sprintf-style format pattern and argument list.  These are used to
1785 generate a string message.  If the message does not end with a newline,
1786 then it will be extended with some indication of the current location
1787 in the code, as described for L</mess_sv>.
1788
1789 The error message or object will by default be written to standard error,
1790 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1791
1792 Unlike with L</croak>, C<pat> is not permitted to be null.
1793
1794 =cut
1795 */
1796
1797 #if defined(PERL_IMPLICIT_CONTEXT)
1798 void
1799 Perl_warn_nocontext(const char *pat, ...)
1800 {
1801     dTHX;
1802     va_list args;
1803     PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1804     va_start(args, pat);
1805     vwarn(pat, &args);
1806     va_end(args);
1807 }
1808 #endif /* PERL_IMPLICIT_CONTEXT */
1809
1810 void
1811 Perl_warn(pTHX_ const char *pat, ...)
1812 {
1813     va_list args;
1814     PERL_ARGS_ASSERT_WARN;
1815     va_start(args, pat);
1816     vwarn(pat, &args);
1817     va_end(args);
1818 }
1819
1820 #if defined(PERL_IMPLICIT_CONTEXT)
1821 void
1822 Perl_warner_nocontext(U32 err, const char *pat, ...)
1823 {
1824     dTHX; 
1825     va_list args;
1826     PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1827     va_start(args, pat);
1828     vwarner(err, pat, &args);
1829     va_end(args);
1830 }
1831 #endif /* PERL_IMPLICIT_CONTEXT */
1832
1833 void
1834 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1835 {
1836     PERL_ARGS_ASSERT_CK_WARNER_D;
1837
1838     if (Perl_ckwarn_d(aTHX_ err)) {
1839         va_list args;
1840         va_start(args, pat);
1841         vwarner(err, pat, &args);
1842         va_end(args);
1843     }
1844 }
1845
1846 void
1847 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1848 {
1849     PERL_ARGS_ASSERT_CK_WARNER;
1850
1851     if (Perl_ckwarn(aTHX_ err)) {
1852         va_list args;
1853         va_start(args, pat);
1854         vwarner(err, pat, &args);
1855         va_end(args);
1856     }
1857 }
1858
1859 void
1860 Perl_warner(pTHX_ U32  err, const char* pat,...)
1861 {
1862     va_list args;
1863     PERL_ARGS_ASSERT_WARNER;
1864     va_start(args, pat);
1865     vwarner(err, pat, &args);
1866     va_end(args);
1867 }
1868
1869 void
1870 Perl_vwarner(pTHX_ U32  err, const char* pat, va_list* args)
1871 {
1872     dVAR;
1873     PERL_ARGS_ASSERT_VWARNER;
1874     if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1875         SV * const msv = vmess(pat, args);
1876
1877         invoke_exception_hook(msv, FALSE);
1878         die_unwind(msv);
1879     }
1880     else {
1881         Perl_vwarn(aTHX_ pat, args);
1882     }
1883 }
1884
1885 /* implements the ckWARN? macros */
1886
1887 bool
1888 Perl_ckwarn(pTHX_ U32 w)
1889 {
1890     dVAR;
1891     /* If lexical warnings have not been set, use $^W.  */
1892     if (isLEXWARN_off)
1893         return PL_dowarn & G_WARN_ON;
1894
1895     return ckwarn_common(w);
1896 }
1897
1898 /* implements the ckWARN?_d macro */
1899
1900 bool
1901 Perl_ckwarn_d(pTHX_ U32 w)
1902 {
1903     dVAR;
1904     /* If lexical warnings have not been set then default classes warn.  */
1905     if (isLEXWARN_off)
1906         return TRUE;
1907
1908     return ckwarn_common(w);
1909 }
1910
1911 static bool
1912 S_ckwarn_common(pTHX_ U32 w)
1913 {
1914     if (PL_curcop->cop_warnings == pWARN_ALL)
1915         return TRUE;
1916
1917     if (PL_curcop->cop_warnings == pWARN_NONE)
1918         return FALSE;
1919
1920     /* Check the assumption that at least the first slot is non-zero.  */
1921     assert(unpackWARN1(w));
1922
1923     /* Check the assumption that it is valid to stop as soon as a zero slot is
1924        seen.  */
1925     if (!unpackWARN2(w)) {
1926         assert(!unpackWARN3(w));
1927         assert(!unpackWARN4(w));
1928     } else if (!unpackWARN3(w)) {
1929         assert(!unpackWARN4(w));
1930     }
1931         
1932     /* Right, dealt with all the special cases, which are implemented as non-
1933        pointers, so there is a pointer to a real warnings mask.  */
1934     do {
1935         if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1936             return TRUE;
1937     } while (w >>= WARNshift);
1938
1939     return FALSE;
1940 }
1941
1942 /* Set buffer=NULL to get a new one.  */
1943 STRLEN *
1944 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1945                            STRLEN size) {
1946     const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
1947     PERL_UNUSED_CONTEXT;
1948     PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1949
1950     buffer = (STRLEN*)
1951         (specialWARN(buffer) ?
1952          PerlMemShared_malloc(len_wanted) :
1953          PerlMemShared_realloc(buffer, len_wanted));
1954     buffer[0] = size;
1955     Copy(bits, (buffer + 1), size, char);
1956     return buffer;
1957 }
1958
1959 /* since we've already done strlen() for both nam and val
1960  * we can use that info to make things faster than
1961  * sprintf(s, "%s=%s", nam, val)
1962  */
1963 #define my_setenv_format(s, nam, nlen, val, vlen) \
1964    Copy(nam, s, nlen, char); \
1965    *(s+nlen) = '='; \
1966    Copy(val, s+(nlen+1), vlen, char); \
1967    *(s+(nlen+1+vlen)) = '\0'
1968
1969 #ifdef USE_ENVIRON_ARRAY
1970        /* VMS' my_setenv() is in vms.c */
1971 #if !defined(WIN32) && !defined(NETWARE)
1972 void
1973 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1974 {
1975   dVAR;
1976 #ifdef USE_ITHREADS
1977   /* only parent thread can modify process environment */
1978   if (PL_curinterp == aTHX)
1979 #endif
1980   {
1981 #ifndef PERL_USE_SAFE_PUTENV
1982     if (!PL_use_safe_putenv) {
1983     /* most putenv()s leak, so we manipulate environ directly */
1984     register I32 i;
1985     register const I32 len = strlen(nam);
1986     int nlen, vlen;
1987
1988     /* where does it go? */
1989     for (i = 0; environ[i]; i++) {
1990         if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1991             break;
1992     }
1993
1994     if (environ == PL_origenviron) {   /* need we copy environment? */
1995        I32 j;
1996        I32 max;
1997        char **tmpenv;
1998
1999        max = i;
2000        while (environ[max])
2001            max++;
2002        tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2003        for (j=0; j<max; j++) {         /* copy environment */
2004            const int len = strlen(environ[j]);
2005            tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2006            Copy(environ[j], tmpenv[j], len+1, char);
2007        }
2008        tmpenv[max] = NULL;
2009        environ = tmpenv;               /* tell exec where it is now */
2010     }
2011     if (!val) {
2012        safesysfree(environ[i]);
2013        while (environ[i]) {
2014            environ[i] = environ[i+1];
2015            i++;
2016         }
2017        return;
2018     }
2019     if (!environ[i]) {                 /* does not exist yet */
2020        environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2021        environ[i+1] = NULL;    /* make sure it's null terminated */
2022     }
2023     else
2024        safesysfree(environ[i]);
2025        nlen = strlen(nam);
2026        vlen = strlen(val);
2027
2028        environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2029        /* all that work just for this */
2030        my_setenv_format(environ[i], nam, nlen, val, vlen);
2031     } else {
2032 # endif
2033 #   if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
2034 #       if defined(HAS_UNSETENV)
2035         if (val == NULL) {
2036             (void)unsetenv(nam);
2037         } else {
2038             (void)setenv(nam, val, 1);
2039         }
2040 #       else /* ! HAS_UNSETENV */
2041         (void)setenv(nam, val, 1);
2042 #       endif /* HAS_UNSETENV */
2043 #   else
2044 #       if defined(HAS_UNSETENV)
2045         if (val == NULL) {
2046             (void)unsetenv(nam);
2047         } else {
2048             const int nlen = strlen(nam);
2049             const int vlen = strlen(val);
2050             char * const new_env =
2051                 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2052             my_setenv_format(new_env, nam, nlen, val, vlen);
2053             (void)putenv(new_env);
2054         }
2055 #       else /* ! HAS_UNSETENV */
2056         char *new_env;
2057         const int nlen = strlen(nam);
2058         int vlen;
2059         if (!val) {
2060            val = "";
2061         }
2062         vlen = strlen(val);
2063         new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2064         /* all that work just for this */
2065         my_setenv_format(new_env, nam, nlen, val, vlen);
2066         (void)putenv(new_env);
2067 #       endif /* HAS_UNSETENV */
2068 #   endif /* __CYGWIN__ */
2069 #ifndef PERL_USE_SAFE_PUTENV
2070     }
2071 #endif
2072   }
2073 }
2074
2075 #else /* WIN32 || NETWARE */
2076
2077 void
2078 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2079 {
2080     dVAR;
2081     register char *envstr;
2082     const int nlen = strlen(nam);
2083     int vlen;
2084
2085     if (!val) {
2086        val = "";
2087     }
2088     vlen = strlen(val);
2089     Newx(envstr, nlen+vlen+2, char);
2090     my_setenv_format(envstr, nam, nlen, val, vlen);
2091     (void)PerlEnv_putenv(envstr);
2092     Safefree(envstr);
2093 }
2094
2095 #endif /* WIN32 || NETWARE */
2096
2097 #endif /* !VMS && !EPOC*/
2098
2099 #ifdef UNLINK_ALL_VERSIONS
2100 I32
2101 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2102 {
2103     I32 retries = 0;
2104
2105     PERL_ARGS_ASSERT_UNLNK;
2106
2107     while (PerlLIO_unlink(f) >= 0)
2108         retries++;
2109     return retries ? 0 : -1;
2110 }
2111 #endif
2112
2113 /* this is a drop-in replacement for bcopy() */
2114 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2115 char *
2116 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2117 {
2118     char * const retval = to;
2119
2120     PERL_ARGS_ASSERT_MY_BCOPY;
2121
2122     if (from - to >= 0) {
2123         while (len--)
2124             *to++ = *from++;
2125     }
2126     else {
2127         to += len;
2128         from += len;
2129         while (len--)
2130             *(--to) = *(--from);
2131     }
2132     return retval;
2133 }
2134 #endif
2135
2136 /* this is a drop-in replacement for memset() */
2137 #ifndef HAS_MEMSET
2138 void *
2139 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2140 {
2141     char * const retval = loc;
2142
2143     PERL_ARGS_ASSERT_MY_MEMSET;
2144
2145     while (len--)
2146         *loc++ = ch;
2147     return retval;
2148 }
2149 #endif
2150
2151 /* this is a drop-in replacement for bzero() */
2152 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2153 char *
2154 Perl_my_bzero(register char *loc, register I32 len)
2155 {
2156     char * const retval = loc;
2157
2158     PERL_ARGS_ASSERT_MY_BZERO;
2159
2160     while (len--)
2161         *loc++ = 0;
2162     return retval;
2163 }
2164 #endif
2165
2166 /* this is a drop-in replacement for memcmp() */
2167 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2168 I32
2169 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2170 {
2171     register const U8 *a = (const U8 *)s1;
2172     register const U8 *b = (const U8 *)s2;
2173     register I32 tmp;
2174
2175     PERL_ARGS_ASSERT_MY_MEMCMP;
2176
2177     while (len--) {
2178         if ((tmp = *a++ - *b++))
2179             return tmp;
2180     }
2181     return 0;
2182 }
2183 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2184
2185 #ifndef HAS_VPRINTF
2186 /* This vsprintf replacement should generally never get used, since
2187    vsprintf was available in both System V and BSD 2.11.  (There may
2188    be some cross-compilation or embedded set-ups where it is needed,
2189    however.)
2190
2191    If you encounter a problem in this function, it's probably a symptom
2192    that Configure failed to detect your system's vprintf() function.
2193    See the section on "item vsprintf" in the INSTALL file.
2194
2195    This version may compile on systems with BSD-ish <stdio.h>,
2196    but probably won't on others.
2197 */
2198
2199 #ifdef USE_CHAR_VSPRINTF
2200 char *
2201 #else
2202 int
2203 #endif
2204 vsprintf(char *dest, const char *pat, void *args)
2205 {
2206     FILE fakebuf;
2207
2208 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2209     FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2210     FILE_cnt(&fakebuf) = 32767;
2211 #else
2212     /* These probably won't compile -- If you really need
2213        this, you'll have to figure out some other method. */
2214     fakebuf._ptr = dest;
2215     fakebuf._cnt = 32767;
2216 #endif
2217 #ifndef _IOSTRG
2218 #define _IOSTRG 0
2219 #endif
2220     fakebuf._flag = _IOWRT|_IOSTRG;
2221     _doprnt(pat, args, &fakebuf);       /* what a kludge */
2222 #if defined(STDIO_PTR_LVALUE)
2223     *(FILE_ptr(&fakebuf)++) = '\0';
2224 #else
2225     /* PerlIO has probably #defined away fputc, but we want it here. */
2226 #  ifdef fputc
2227 #    undef fputc  /* XXX Should really restore it later */
2228 #  endif
2229     (void)fputc('\0', &fakebuf);
2230 #endif
2231 #ifdef USE_CHAR_VSPRINTF
2232     return(dest);
2233 #else
2234     return 0;           /* perl doesn't use return value */
2235 #endif
2236 }
2237
2238 #endif /* HAS_VPRINTF */
2239
2240 #ifdef MYSWAP
2241 #if BYTEORDER != 0x4321
2242 short
2243 Perl_my_swap(pTHX_ short s)
2244 {
2245 #if (BYTEORDER & 1) == 0
2246     short result;
2247
2248     result = ((s & 255) << 8) + ((s >> 8) & 255);
2249     return result;
2250 #else
2251     return s;
2252 #endif
2253 }
2254
2255 long
2256 Perl_my_htonl(pTHX_ long l)
2257 {
2258     union {
2259         long result;
2260         char c[sizeof(long)];
2261     } u;
2262
2263 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2264 #if BYTEORDER == 0x12345678
2265     u.result = 0; 
2266 #endif 
2267     u.c[0] = (l >> 24) & 255;
2268     u.c[1] = (l >> 16) & 255;
2269     u.c[2] = (l >> 8) & 255;
2270     u.c[3] = l & 255;
2271     return u.result;
2272 #else
2273 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2274     Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2275 #else
2276     register I32 o;
2277     register I32 s;
2278
2279     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2280         u.c[o & 0xf] = (l >> s) & 255;
2281     }
2282     return u.result;
2283 #endif
2284 #endif
2285 }
2286
2287 long
2288 Perl_my_ntohl(pTHX_ long l)
2289 {
2290     union {
2291         long l;
2292         char c[sizeof(long)];
2293     } u;
2294
2295 #if BYTEORDER == 0x1234
2296     u.c[0] = (l >> 24) & 255;
2297     u.c[1] = (l >> 16) & 255;
2298     u.c[2] = (l >> 8) & 255;
2299     u.c[3] = l & 255;
2300     return u.l;
2301 #else
2302 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2303     Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2304 #else
2305     register I32 o;
2306     register I32 s;
2307
2308     u.l = l;
2309     l = 0;
2310     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2311         l |= (u.c[o & 0xf] & 255) << s;
2312     }
2313     return l;
2314 #endif
2315 #endif
2316 }
2317
2318 #endif /* BYTEORDER != 0x4321 */
2319 #endif /* MYSWAP */
2320
2321 /*
2322  * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2323  * If these functions are defined,
2324  * the BYTEORDER is neither 0x1234 nor 0x4321.
2325  * However, this is not assumed.
2326  * -DWS
2327  */
2328
2329 #define HTOLE(name,type)                                        \
2330         type                                                    \
2331         name (register type n)                                  \
2332         {                                                       \
2333             union {                                             \
2334                 type value;                                     \
2335                 char c[sizeof(type)];                           \
2336             } u;                                                \
2337             register U32 i;                                     \
2338             register U32 s = 0;                                 \
2339             for (i = 0; i < sizeof(u.c); i++, s += 8) {         \
2340                 u.c[i] = (n >> s) & 0xFF;                       \
2341             }                                                   \
2342             return u.value;                                     \
2343         }
2344
2345 #define LETOH(name,type)                                        \
2346         type                                                    \
2347         name (register type n)                                  \
2348         {                                                       \
2349             union {                                             \
2350                 type value;                                     \
2351                 char c[sizeof(type)];                           \
2352             } u;                                                \
2353             register U32 i;                                     \
2354             register U32 s = 0;                                 \
2355             u.value = n;                                        \
2356             n = 0;                                              \
2357             for (i = 0; i < sizeof(u.c); i++, s += 8) {         \
2358                 n |= ((type)(u.c[i] & 0xFF)) << s;              \
2359             }                                                   \
2360             return n;                                           \
2361         }
2362
2363 /*
2364  * Big-endian byte order functions.
2365  */
2366
2367 #define HTOBE(name,type)                                        \
2368         type                                                    \
2369         name (register type n)                                  \
2370         {                                                       \
2371             union {                                             \
2372                 type value;                                     \
2373                 char c[sizeof(type)];                           \
2374             } u;                                                \
2375             register U32 i;                                     \
2376             register U32 s = 8*(sizeof(u.c)-1);                 \
2377             for (i = 0; i < sizeof(u.c); i++, s -= 8) {         \
2378                 u.c[i] = (n >> s) & 0xFF;                       \
2379             }                                                   \
2380             return u.value;                                     \
2381         }
2382
2383 #define BETOH(name,type)                                        \
2384         type                                                    \
2385         name (register type n)                                  \
2386         {                                                       \
2387             union {                                             \
2388                 type value;                                     \
2389                 char c[sizeof(type)];                           \
2390             } u;                                                \
2391             register U32 i;                                     \
2392             register U32 s = 8*(sizeof(u.c)-1);                 \
2393             u.value = n;                                        \
2394             n = 0;                                              \
2395             for (i = 0; i < sizeof(u.c); i++, s -= 8) {         \
2396                 n |= ((type)(u.c[i] & 0xFF)) << s;              \
2397             }                                                   \
2398             return n;                                           \
2399         }
2400
2401 /*
2402  * If we just can't do it...
2403  */
2404
2405 #define NOT_AVAIL(name,type)                                    \
2406         type                                                    \
2407         name (register type n)                                  \
2408         {                                                       \
2409             Perl_croak_nocontext(#name "() not available");     \
2410             return n; /* not reached */                         \
2411         }
2412
2413
2414 #if defined(HAS_HTOVS) && !defined(htovs)
2415 HTOLE(htovs,short)
2416 #endif
2417 #if defined(HAS_HTOVL) && !defined(htovl)
2418 HTOLE(htovl,long)
2419 #endif
2420 #if defined(HAS_VTOHS) && !defined(vtohs)
2421 LETOH(vtohs,short)
2422 #endif
2423 #if defined(HAS_VTOHL) && !defined(vtohl)
2424 LETOH(vtohl,long)
2425 #endif
2426
2427 #ifdef PERL_NEED_MY_HTOLE16
2428 # if U16SIZE == 2
2429 HTOLE(Perl_my_htole16,U16)
2430 # else
2431 NOT_AVAIL(Perl_my_htole16,U16)
2432 # endif
2433 #endif
2434 #ifdef PERL_NEED_MY_LETOH16
2435 # if U16SIZE == 2
2436 LETOH(Perl_my_letoh16,U16)
2437 # else
2438 NOT_AVAIL(Perl_my_letoh16,U16)
2439 # endif
2440 #endif
2441 #ifdef PERL_NEED_MY_HTOBE16
2442 # if U16SIZE == 2
2443 HTOBE(Perl_my_htobe16,U16)
2444 # else
2445 NOT_AVAIL(Perl_my_htobe16,U16)
2446 # endif
2447 #endif
2448 #ifdef PERL_NEED_MY_BETOH16
2449 # if U16SIZE == 2
2450 BETOH(Perl_my_betoh16,U16)
2451 # else
2452 NOT_AVAIL(Perl_my_betoh16,U16)
2453 # endif
2454 #endif
2455
2456 #ifdef PERL_NEED_MY_HTOLE32
2457 # if U32SIZE == 4
2458 HTOLE(Perl_my_htole32,U32)
2459 # else
2460 NOT_AVAIL(Perl_my_htole32,U32)
2461 # endif
2462 #endif
2463 #ifdef PERL_NEED_MY_LETOH32
2464 # if U32SIZE == 4
2465 LETOH(Perl_my_letoh32,U32)
2466 # else
2467 NOT_AVAIL(Perl_my_letoh32,U32)
2468 # endif
2469 #endif
2470 #ifdef PERL_NEED_MY_HTOBE32
2471 # if U32SIZE == 4
2472 HTOBE(Perl_my_htobe32,U32)
2473 # else
2474 NOT_AVAIL(Perl_my_htobe32,U32)
2475 # endif
2476 #endif
2477 #ifdef PERL_NEED_MY_BETOH32
2478 # if U32SIZE == 4
2479 BETOH(Perl_my_betoh32,U32)
2480 # else
2481 NOT_AVAIL(Perl_my_betoh32,U32)
2482 # endif
2483 #endif
2484
2485 #ifdef PERL_NEED_MY_HTOLE64
2486 # if U64SIZE == 8
2487 HTOLE(Perl_my_htole64,U64)
2488 # else
2489 NOT_AVAIL(Perl_my_htole64,U64)
2490 # endif
2491 #endif
2492 #ifdef PERL_NEED_MY_LETOH64
2493 # if U64SIZE == 8
2494 LETOH(Perl_my_letoh64,U64)
2495 # else
2496 NOT_AVAIL(Perl_my_letoh64,U64)
2497 # endif
2498 #endif
2499 #ifdef PERL_NEED_MY_HTOBE64
2500 # if U64SIZE == 8
2501 HTOBE(Perl_my_htobe64,U64)
2502 # else
2503 NOT_AVAIL(Perl_my_htobe64,U64)
2504 # endif
2505 #endif
2506 #ifdef PERL_NEED_MY_BETOH64
2507 # if U64SIZE == 8
2508 BETOH(Perl_my_betoh64,U64)
2509 # else
2510 NOT_AVAIL(Perl_my_betoh64,U64)
2511 # endif
2512 #endif
2513
2514 #ifdef PERL_NEED_MY_HTOLES
2515 HTOLE(Perl_my_htoles,short)
2516 #endif
2517 #ifdef PERL_NEED_MY_LETOHS
2518 LETOH(Perl_my_letohs,short)
2519 #endif
2520 #ifdef PERL_NEED_MY_HTOBES
2521 HTOBE(Perl_my_htobes,short)
2522 #endif
2523 #ifdef PERL_NEED_MY_BETOHS
2524 BETOH(Perl_my_betohs,short)
2525 #endif
2526
2527 #ifdef PERL_NEED_MY_HTOLEI
2528 HTOLE(Perl_my_htolei,int)
2529 #endif
2530 #ifdef PERL_NEED_MY_LETOHI
2531 LETOH(Perl_my_letohi,int)
2532 #endif
2533 #ifdef PERL_NEED_MY_HTOBEI
2534 HTOBE(Perl_my_htobei,int)
2535 #endif
2536 #ifdef PERL_NEED_MY_BETOHI
2537 BETOH(Perl_my_betohi,int)
2538 #endif
2539
2540 #ifdef PERL_NEED_MY_HTOLEL
2541 HTOLE(Perl_my_htolel,long)
2542 #endif
2543 #ifdef PERL_NEED_MY_LETOHL
2544 LETOH(Perl_my_letohl,long)
2545 #endif
2546 #ifdef PERL_NEED_MY_HTOBEL
2547 HTOBE(Perl_my_htobel,long)
2548 #endif
2549 #ifdef PERL_NEED_MY_BETOHL
2550 BETOH(Perl_my_betohl,long)
2551 #endif
2552
2553 void
2554 Perl_my_swabn(void *ptr, int n)
2555 {
2556     register char *s = (char *)ptr;
2557     register char *e = s + (n-1);
2558     register char tc;
2559
2560     PERL_ARGS_ASSERT_MY_SWABN;
2561
2562     for (n /= 2; n > 0; s++, e--, n--) {
2563       tc = *s;
2564       *s = *e;
2565       *e = tc;
2566     }
2567 }
2568
2569 PerlIO *
2570 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2571 {
2572 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2573     dVAR;
2574     int p[2];
2575     register I32 This, that;
2576     register Pid_t pid;
2577     SV *sv;
2578     I32 did_pipes = 0;
2579     int pp[2];
2580
2581     PERL_ARGS_ASSERT_MY_POPEN_LIST;
2582
2583     PERL_FLUSHALL_FOR_CHILD;
2584     This = (*mode == 'w');
2585     that = !This;
2586     if (PL_tainting) {
2587         taint_env();
2588         taint_proper("Insecure %s%s", "EXEC");
2589     }
2590     if (PerlProc_pipe(p) < 0)
2591         return NULL;
2592     /* Try for another pipe pair for error return */
2593     if (PerlProc_pipe(pp) >= 0)
2594         did_pipes = 1;
2595     while ((pid = PerlProc_fork()) < 0) {
2596         if (errno != EAGAIN) {
2597             PerlLIO_close(p[This]);
2598             PerlLIO_close(p[that]);
2599             if (did_pipes) {
2600                 PerlLIO_close(pp[0]);
2601                 PerlLIO_close(pp[1]);
2602             }
2603             return NULL;
2604         }
2605         Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2606         sleep(5);
2607     }
2608     if (pid == 0) {
2609         /* Child */
2610 #undef THIS
2611 #undef THAT
2612 #define THIS that
2613 #define THAT This
2614         /* Close parent's end of error status pipe (if any) */
2615         if (did_pipes) {
2616             PerlLIO_close(pp[0]);
2617 #if defined(HAS_FCNTL) && defined(F_SETFD)
2618             /* Close error pipe automatically if exec works */
2619             fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2620 #endif
2621         }
2622         /* Now dup our end of _the_ pipe to right position */
2623         if (p[THIS] != (*mode == 'r')) {
2624             PerlLIO_dup2(p[THIS], *mode == 'r');
2625             PerlLIO_close(p[THIS]);
2626             if (p[THAT] != (*mode == 'r'))      /* if dup2() didn't close it */
2627                 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2628         }
2629         else
2630             PerlLIO_close(p[THAT]);     /* close parent's end of _the_ pipe */
2631 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2632         /* No automatic close - do it by hand */
2633 #  ifndef NOFILE
2634 #  define NOFILE 20
2635 #  endif
2636         {
2637             int fd;
2638
2639             for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2640                 if (fd != pp[1])
2641                     PerlLIO_close(fd);
2642             }
2643         }
2644 #endif
2645         do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2646         PerlProc__exit(1);
2647 #undef THIS
2648 #undef THAT
2649     }
2650     /* Parent */
2651     do_execfree();      /* free any memory malloced by child on fork */
2652     if (did_pipes)
2653         PerlLIO_close(pp[1]);
2654     /* Keep the lower of the two fd numbers */
2655     if (p[that] < p[This]) {
2656         PerlLIO_dup2(p[This], p[that]);
2657         PerlLIO_close(p[This]);
2658         p[This] = p[that];
2659     }
2660     else
2661         PerlLIO_close(p[that]);         /* close child's end of pipe */
2662
2663     sv = *av_fetch(PL_fdpid,p[This],TRUE);
2664     SvUPGRADE(sv,SVt_IV);
2665     SvIV_set(sv, pid);
2666     PL_forkprocess = pid;
2667     /* If we managed to get status pipe check for exec fail */
2668     if (did_pipes && pid > 0) {
2669         int errkid;
2670         unsigned n = 0;
2671         SSize_t n1;
2672
2673         while (n < sizeof(int)) {
2674             n1 = PerlLIO_read(pp[0],
2675                               (void*)(((char*)&errkid)+n),
2676                               (sizeof(int)) - n);
2677             if (n1 <= 0)
2678                 break;
2679             n += n1;
2680         }
2681         PerlLIO_close(pp[0]);
2682         did_pipes = 0;
2683         if (n) {                        /* Error */
2684             int pid2, status;
2685             PerlLIO_close(p[This]);
2686             if (n != sizeof(int))
2687                 Perl_croak(aTHX_ "panic: kid popen errno read");
2688             do {
2689                 pid2 = wait4pid(pid, &status, 0);
2690             } while (pid2 == -1 && errno == EINTR);
2691             errno = errkid;             /* Propagate errno from kid */
2692             return NULL;
2693         }
2694     }
2695     if (did_pipes)
2696          PerlLIO_close(pp[0]);
2697     return PerlIO_fdopen(p[This], mode);
2698 #else
2699 #  ifdef OS2    /* Same, without fork()ing and all extra overhead... */
2700     return my_syspopen4(aTHX_ NULL, mode, n, args);
2701 #  else
2702     Perl_croak(aTHX_ "List form of piped open not implemented");
2703     return (PerlIO *) NULL;
2704 #  endif
2705 #endif
2706 }
2707
2708     /* VMS' my_popen() is in VMS.c, same with OS/2. */
2709 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
2710 PerlIO *
2711 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2712 {
2713     dVAR;
2714     int p[2];
2715     register I32 This, that;
2716     register Pid_t pid;
2717     SV *sv;
2718     const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2719     I32 did_pipes = 0;
2720     int pp[2];
2721
2722     PERL_ARGS_ASSERT_MY_POPEN;
2723
2724     PERL_FLUSHALL_FOR_CHILD;
2725 #ifdef OS2
2726     if (doexec) {
2727         return my_syspopen(aTHX_ cmd,mode);
2728     }
2729 #endif
2730     This = (*mode == 'w');
2731     that = !This;
2732     if (doexec && PL_tainting) {
2733         taint_env();
2734         taint_proper("Insecure %s%s", "EXEC");
2735     }
2736     if (PerlProc_pipe(p) < 0)
2737         return NULL;
2738     if (doexec && PerlProc_pipe(pp) >= 0)
2739         did_pipes = 1;
2740     while ((pid = PerlProc_fork()) < 0) {
2741         if (errno != EAGAIN) {
2742             PerlLIO_close(p[This]);
2743             PerlLIO_close(p[that]);
2744             if (did_pipes) {
2745                 PerlLIO_close(pp[0]);
2746                 PerlLIO_close(pp[1]);
2747             }
2748             if (!doexec)
2749                 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2750             return NULL;
2751         }
2752         Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2753         sleep(5);
2754     }
2755     if (pid == 0) {
2756
2757 #undef THIS
2758 #undef THAT
2759 #define THIS that
2760 #define THAT This
2761         if (did_pipes) {
2762             PerlLIO_close(pp[0]);
2763 #if defined(HAS_FCNTL) && defined(F_SETFD)
2764             fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2765 #endif
2766         }
2767         if (p[THIS] != (*mode == 'r')) {
2768             PerlLIO_dup2(p[THIS], *mode == 'r');
2769             PerlLIO_close(p[THIS]);
2770             if (p[THAT] != (*mode == 'r'))      /* if dup2() didn't close it */
2771                 PerlLIO_close(p[THAT]);
2772         }
2773         else
2774             PerlLIO_close(p[THAT]);
2775 #ifndef OS2
2776         if (doexec) {
2777 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2778 #ifndef NOFILE
2779 #define NOFILE 20
2780 #endif
2781             {
2782                 int fd;
2783
2784                 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2785                     if (fd != pp[1])
2786                         PerlLIO_close(fd);
2787             }
2788 #endif
2789             /* may or may not use the shell */
2790             do_exec3(cmd, pp[1], did_pipes);
2791             PerlProc__exit(1);
2792         }
2793 #endif  /* defined OS2 */
2794
2795 #ifdef PERLIO_USING_CRLF
2796    /* Since we circumvent IO layers when we manipulate low-level
2797       filedescriptors directly, need to manually switch to the
2798       default, binary, low-level mode; see PerlIOBuf_open(). */
2799    PerlLIO_setmode((*mode == 'r'), O_BINARY);
2800 #endif 
2801 #ifdef THREADS_HAVE_PIDS
2802         PL_ppid = (IV)getppid();
2803 #endif
2804         PL_forkprocess = 0;
2805 #ifdef PERL_USES_PL_PIDSTATUS
2806         hv_clear(PL_pidstatus); /* we have no children */
2807 #endif
2808         return NULL;
2809 #undef THIS
2810 #undef THAT
2811     }
2812     do_execfree();      /* free any memory malloced by child on vfork */
2813     if (did_pipes)
2814         PerlLIO_close(pp[1]);
2815     if (p[that] < p[This]) {
2816         PerlLIO_dup2(p[This], p[that]);
2817         PerlLIO_close(p[This]);
2818         p[This] = p[that];
2819     }
2820     else
2821         PerlLIO_close(p[that]);
2822
2823     sv = *av_fetch(PL_fdpid,p[This],TRUE);
2824     SvUPGRADE(sv,SVt_IV);
2825     SvIV_set(sv, pid);
2826     PL_forkprocess = pid;
2827     if (did_pipes && pid > 0) {
2828         int errkid;
2829         unsigned n = 0;
2830         SSize_t n1;
2831
2832         while (n < sizeof(int)) {
2833             n1 = PerlLIO_read(pp[0],
2834                               (void*)(((char*)&errkid)+n),
2835                               (sizeof(int)) - n);
2836             if (n1 <= 0)
2837                 break;
2838             n += n1;
2839         }
2840         PerlLIO_close(pp[0]);
2841         did_pipes = 0;
2842         if (n) {                        /* Error */
2843             int pid2, status;
2844             PerlLIO_close(p[This]);
2845             if (n != sizeof(int))
2846                 Perl_croak(aTHX_ "panic: kid popen errno read");
2847             do {
2848                 pid2 = wait4pid(pid, &status, 0);
2849             } while (pid2 == -1 && errno == EINTR);
2850             errno = errkid;             /* Propagate errno from kid */
2851             return NULL;
2852         }
2853     }
2854     if (did_pipes)
2855          PerlLIO_close(pp[0]);
2856     return PerlIO_fdopen(p[This], mode);
2857 }
2858 #else
2859 #if defined(atarist) || defined(EPOC)
2860 FILE *popen();
2861 PerlIO *
2862 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2863 {
2864     PERL_ARGS_ASSERT_MY_POPEN;
2865     PERL_FLUSHALL_FOR_CHILD;
2866     /* Call system's popen() to get a FILE *, then import it.
2867        used 0 for 2nd parameter to PerlIO_importFILE;
2868        apparently not used
2869     */
2870     return PerlIO_importFILE(popen(cmd, mode), 0);
2871 }
2872 #else
2873 #if defined(DJGPP)
2874 FILE *djgpp_popen();
2875 PerlIO *
2876 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2877 {
2878     PERL_FLUSHALL_FOR_CHILD;
2879     /* Call system's popen() to get a FILE *, then import it.
2880        used 0 for 2nd parameter to PerlIO_importFILE;
2881        apparently not used
2882     */
2883     return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2884 }
2885 #else
2886 #if defined(__LIBCATAMOUNT__)
2887 PerlIO *
2888 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2889 {
2890     return NULL;
2891 }
2892 #endif
2893 #endif
2894 #endif
2895
2896 #endif /* !DOSISH */
2897
2898 /* this is called in parent before the fork() */
2899 void
2900 Perl_atfork_lock(void)
2901 {
2902    dVAR;
2903 #if defined(USE_ITHREADS)
2904     /* locks must be held in locking order (if any) */
2905 #  ifdef MYMALLOC
2906     MUTEX_LOCK(&PL_malloc_mutex);
2907 #  endif
2908     OP_REFCNT_LOCK;
2909 #endif
2910 }
2911
2912 /* this is called in both parent and child after the fork() */
2913 void
2914 Perl_atfork_unlock(void)
2915 {
2916     dVAR;
2917 #if defined(USE_ITHREADS)
2918     /* locks must be released in same order as in atfork_lock() */
2919 #  ifdef MYMALLOC
2920     MUTEX_UNLOCK(&PL_malloc_mutex);
2921 #  endif
2922     OP_REFCNT_UNLOCK;
2923 #endif
2924 }
2925
2926 Pid_t
2927 Perl_my_fork(void)
2928 {
2929 #if defined(HAS_FORK)
2930     Pid_t pid;
2931 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2932     atfork_lock();
2933     pid = fork();
2934     atfork_unlock();
2935 #else
2936     /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2937      * handlers elsewhere in the code */
2938     pid = fork();
2939 #endif
2940     return pid;
2941 #else
2942     /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2943     Perl_croak_nocontext("fork() not available");
2944     return 0;
2945 #endif /* HAS_FORK */
2946 }
2947
2948 #ifdef DUMP_FDS
2949 void
2950 Perl_dump_fds(pTHX_ const char *const s)
2951 {
2952     int fd;
2953     Stat_t tmpstatbuf;
2954
2955     PERL_ARGS_ASSERT_DUMP_FDS;
2956
2957     PerlIO_printf(Perl_debug_log,"%s", s);
2958     for (fd = 0; fd < 32; fd++) {
2959         if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2960             PerlIO_printf(Perl_debug_log," %d",fd);
2961     }
2962     PerlIO_printf(Perl_debug_log,"\n");
2963     return;
2964 }
2965 #endif  /* DUMP_FDS */
2966
2967 #ifndef HAS_DUP2
2968 int
2969 dup2(int oldfd, int newfd)
2970 {
2971 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2972     if (oldfd == newfd)
2973         return oldfd;
2974     PerlLIO_close(newfd);
2975     return fcntl(oldfd, F_DUPFD, newfd);
2976 #else
2977 #define DUP2_MAX_FDS 256
2978     int fdtmp[DUP2_MAX_FDS];
2979     I32 fdx = 0;
2980     int fd;
2981
2982     if (oldfd == newfd)
2983         return oldfd;
2984     PerlLIO_close(newfd);
2985     /* good enough for low fd's... */
2986     while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2987         if (fdx >= DUP2_MAX_FDS) {
2988             PerlLIO_close(fd);
2989             fd = -1;
2990             break;
2991         }
2992         fdtmp[fdx++] = fd;
2993     }
2994     while (fdx > 0)
2995         PerlLIO_close(fdtmp[--fdx]);
2996     return fd;
2997 #endif
2998 }
2999 #endif
3000
3001 #ifndef PERL_MICRO
3002 #ifdef HAS_SIGACTION
3003
3004 Sighandler_t
3005 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3006 {
3007     dVAR;
3008     struct sigaction act, oact;
3009
3010 #ifdef USE_ITHREADS
3011     /* only "parent" interpreter can diddle signals */
3012     if (PL_curinterp != aTHX)
3013         return (Sighandler_t) SIG_ERR;
3014 #endif
3015
3016     act.sa_handler = (void(*)(int))handler;
3017     sigemptyset(&act.sa_mask);
3018     act.sa_flags = 0;
3019 #ifdef SA_RESTART
3020     if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3021         act.sa_flags |= SA_RESTART;     /* SVR4, 4.3+BSD */
3022 #endif
3023 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3024     if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3025         act.sa_flags |= SA_NOCLDWAIT;
3026 #endif
3027     if (sigaction(signo, &act, &oact) == -1)
3028         return (Sighandler_t) SIG_ERR;
3029     else
3030         return (Sighandler_t) oact.sa_handler;
3031 }
3032
3033 Sighandler_t
3034 Perl_rsignal_state(pTHX_ int signo)
3035 {
3036     struct sigaction oact;
3037     PERL_UNUSED_CONTEXT;
3038
3039     if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
3040         return (Sighandler_t) SIG_ERR;
3041     else
3042         return (Sighandler_t) oact.sa_handler;
3043 }
3044
3045 int
3046 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3047 {
3048     dVAR;
3049     struct sigaction act;
3050
3051     PERL_ARGS_ASSERT_RSIGNAL_SAVE;
3052
3053 #ifdef USE_ITHREADS
3054     /* only "parent" interpreter can diddle signals */
3055     if (PL_curinterp != aTHX)
3056         return -1;
3057 #endif
3058
3059     act.sa_handler = (void(*)(int))handler;
3060     sigemptyset(&act.sa_mask);
3061     act.sa_flags = 0;
3062 #ifdef SA_RESTART
3063     if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3064         act.sa_flags |= SA_RESTART;     /* SVR4, 4.3+BSD */
3065 #endif
3066 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3067     if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3068         act.sa_flags |= SA_NOCLDWAIT;
3069 #endif
3070     return sigaction(signo, &act, save);
3071 }
3072
3073 int
3074 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3075 {
3076     dVAR;
3077 #ifdef USE_ITHREADS
3078     /* only "parent" interpreter can diddle signals */
3079     if (PL_curinterp != aTHX)
3080         return -1;
3081 #endif
3082
3083     return sigaction(signo, save, (struct sigaction *)NULL);
3084 }
3085
3086 #else /* !HAS_SIGACTION */
3087
3088 Sighandler_t
3089 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3090 {
3091 #if defined(USE_ITHREADS) && !defined(WIN32)
3092     /* only "parent" interpreter can diddle signals */
3093     if (PL_curinterp != aTHX)
3094         return (Sighandler_t) SIG_ERR;
3095 #endif
3096
3097     return PerlProc_signal(signo, handler);
3098 }
3099
3100 static Signal_t
3101 sig_trap(int signo)
3102 {
3103     dVAR;
3104     PL_sig_trapped++;
3105 }
3106
3107 Sighandler_t
3108 Perl_rsignal_state(pTHX_ int signo)
3109 {
3110     dVAR;
3111     Sighandler_t oldsig;
3112
3113 #if defined(USE_ITHREADS) && !defined(WIN32)
3114     /* only "parent" interpreter can diddle signals */
3115     if (PL_curinterp != aTHX)
3116         return (Sighandler_t) SIG_ERR;
3117 #endif
3118
3119     PL_sig_trapped = 0;
3120     oldsig = PerlProc_signal(signo, sig_trap);
3121     PerlProc_signal(signo, oldsig);
3122     if (PL_sig_trapped)
3123         PerlProc_kill(PerlProc_getpid(), signo);
3124     return oldsig;
3125 }
3126
3127 int
3128 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3129 {
3130 #if defined(USE_ITHREADS) && !defined(WIN32)
3131     /* only "parent" interpreter can diddle signals */
3132     if (PL_curinterp != aTHX)
3133         return -1;
3134 #endif
3135     *save = PerlProc_signal(signo, handler);
3136     return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3137 }
3138
3139 int
3140 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3141 {
3142 #if defined(USE_ITHREADS) && !defined(WIN32)
3143     /* only "parent" interpreter can diddle signals */
3144     if (PL_curinterp != aTHX)
3145         return -1;
3146 #endif
3147     return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3148 }
3149
3150 #endif /* !HAS_SIGACTION */
3151 #endif /* !PERL_MICRO */
3152
3153     /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3154 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
3155 I32
3156 Perl_my_pclose(pTHX_ PerlIO *ptr)
3157 {
3158     dVAR;
3159     Sigsave_t hstat, istat, qstat;
3160     int status;
3161     SV **svp;
3162     Pid_t pid;
3163     Pid_t pid2 = 0;
3164     bool close_failed;
3165     dSAVEDERRNO;
3166     const int fd = PerlIO_fileno(ptr);
3167
3168 #ifdef USE_PERLIO
3169     /* Find out whether the refcount is low enough for us to wait for the
3170        child proc without blocking. */
3171     const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
3172 #else
3173     const bool should_wait = 1;
3174 #endif
3175
3176     svp = av_fetch(PL_fdpid,fd,TRUE);
3177     pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3178     SvREFCNT_dec(*svp);
3179     *svp = &PL_sv_undef;
3180 #ifdef OS2
3181     if (pid == -1) {                    /* Opened by popen. */
3182         return my_syspclose(ptr);
3183     }
3184 #endif
3185     close_failed = (PerlIO_close(ptr) == EOF);
3186     SAVE_ERRNO;
3187 #ifdef UTS
3188     if(PerlProc_kill(pid, 0) < 0) { return(pid); }   /* HOM 12/23/91 */
3189 #endif
3190 #ifndef PERL_MICRO
3191     rsignal_save(SIGHUP,  (Sighandler_t) SIG_IGN, &hstat);
3192     rsignal_save(SIGINT,  (Sighandler_t) SIG_IGN, &istat);
3193     rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3194 #endif
3195     if (should_wait) do {
3196         pid2 = wait4pid(pid, &status, 0);
3197     } while (pid2 == -1 && errno == EINTR);
3198 #ifndef PERL_MICRO
3199     rsignal_restore(SIGHUP, &hstat);
3200     rsignal_restore(SIGINT, &istat);
3201     rsignal_restore(SIGQUIT, &qstat);
3202 #endif
3203     if (close_failed) {
3204         RESTORE_ERRNO;
3205         return -1;
3206     }
3207     return(
3208       should_wait
3209        ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3210        : 0
3211     );
3212 }
3213 #else
3214 #if defined(__LIBCATAMOUNT__)
3215 I32
3216 Perl_my_pclose(pTHX_ PerlIO *ptr)
3217 {
3218     return -1;
3219 }
3220 #endif
3221 #endif /* !DOSISH */
3222
3223 #if  (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3224 I32
3225 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3226 {
3227     dVAR;
3228     I32 result = 0;
3229     PERL_ARGS_ASSERT_WAIT4PID;
3230     if (!pid)
3231         return -1;
3232 #ifdef PERL_USES_PL_PIDSTATUS
3233     {
3234         if (pid > 0) {
3235             /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3236                pid, rather than a string form.  */
3237             SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3238             if (svp && *svp != &PL_sv_undef) {
3239                 *statusp = SvIVX(*svp);
3240                 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3241                                 G_DISCARD);
3242                 return pid;
3243             }
3244         }
3245         else {
3246             HE *entry;
3247
3248             hv_iterinit(PL_pidstatus);
3249             if ((entry = hv_iternext(PL_pidstatus))) {
3250                 SV * const sv = hv_iterval(PL_pidstatus,entry);
3251                 I32 len;
3252                 const char * const spid = hv_iterkey(entry,&len);
3253
3254                 assert (len == sizeof(Pid_t));
3255                 memcpy((char *)&pid, spid, len);
3256                 *statusp = SvIVX(sv);
3257                 /* The hash iterator is currently on this entry, so simply
3258                    calling hv_delete would trigger the lazy delete, which on
3259                    aggregate does more work, beacuse next call to hv_iterinit()
3260                    would spot the flag, and have to call the delete routine,
3261                    while in the meantime any new entries can't re-use that
3262                    memory.  */
3263                 hv_iterinit(PL_pidstatus);
3264                 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3265                 return pid;
3266             }
3267         }
3268     }
3269 #endif
3270 #ifdef HAS_WAITPID
3271 #  ifdef HAS_WAITPID_RUNTIME
3272     if (!HAS_WAITPID_RUNTIME)
3273         goto hard_way;
3274 #  endif
3275     result = PerlProc_waitpid(pid,statusp,flags);
3276     goto finish;
3277 #endif
3278 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3279     result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3280     goto finish;
3281 #endif
3282 #ifdef PERL_USES_PL_PIDSTATUS
3283 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3284   hard_way:
3285 #endif
3286     {
3287         if (flags)
3288             Perl_croak(aTHX_ "Can't do waitpid with flags");
3289         else {
3290             while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3291                 pidgone(result,*statusp);
3292             if (result < 0)
3293                 *statusp = -1;
3294         }
3295     }
3296 #endif
3297 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3298   finish:
3299 #endif
3300     if (result < 0 && errno == EINTR) {
3301         PERL_ASYNC_CHECK();
3302         errno = EINTR; /* reset in case a signal handler changed $! */
3303     }
3304     return result;
3305 }
3306 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3307
3308 #ifdef PERL_USES_PL_PIDSTATUS
3309 void
3310 S_pidgone(pTHX_ Pid_t pid, int status)
3311 {
3312     register SV *sv;
3313
3314     sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3315     SvUPGRADE(sv,SVt_IV);
3316     SvIV_set(sv, status);
3317     return;
3318 }
3319 #endif
3320
3321 #if defined(atarist) || defined(OS2) || defined(EPOC)
3322 int pclose();
3323 #ifdef HAS_FORK
3324 int                                     /* Cannot prototype with I32
3325                                            in os2ish.h. */
3326 my_syspclose(PerlIO *ptr)
3327 #else
3328 I32
3329 Perl_my_pclose(pTHX_ PerlIO *ptr)
3330 #endif
3331 {
3332     /* Needs work for PerlIO ! */
3333     FILE * const f = PerlIO_findFILE(ptr);
3334     const I32 result = pclose(f);
3335     PerlIO_releaseFILE(ptr,f);
3336     return result;
3337 }
3338 #endif
3339
3340 #if defined(DJGPP)
3341 int djgpp_pclose();
3342 I32
3343 Perl_my_pclose(pTHX_ PerlIO *ptr)
3344 {
3345     /* Needs work for PerlIO ! */
3346     FILE * const f = PerlIO_findFILE(ptr);
3347     I32 result = djgpp_pclose(f);
3348     result = (result << 8) & 0xff00;
3349     PerlIO_releaseFILE(ptr,f);
3350     return result;
3351 }
3352 #endif
3353
3354 #define PERL_REPEATCPY_LINEAR 4
3355 void
3356 Perl_repeatcpy(register char *to, register const char *from, I32 len, register I32 count)
3357 {
3358     PERL_ARGS_ASSERT_REPEATCPY;
3359
3360     if (len == 1)
3361         memset(to, *from, count);
3362     else if (count) {
3363         register char *p = to;
3364         I32 items, linear, half;
3365
3366         linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3367         for (items = 0; items < linear; ++items) {
3368             register const char *q = from;
3369             I32 todo;
3370             for (todo = len; todo > 0; todo--)
3371                 *p++ = *q++;
3372         }
3373
3374         half = count / 2;
3375         while (items <= half) {
3376             I32 size = items * len;
3377             memcpy(p, to, size);
3378             p     += size;
3379             items *= 2;
3380         }
3381
3382         if (count > items)
3383             memcpy(p, to, (count - items) * len);
3384     }
3385 }
3386
3387 #ifndef HAS_RENAME
3388 I32
3389 Perl_same_dirent(pTHX_ const char *a, const char *b)
3390 {
3391     char *fa = strrchr(a,'/');
3392     char *fb = strrchr(b,'/');
3393     Stat_t tmpstatbuf1;
3394     Stat_t tmpstatbuf2;
3395     SV * const tmpsv = sv_newmortal();
3396
3397     PERL_ARGS_ASSERT_SAME_DIRENT;
3398
3399     if (fa)
3400         fa++;
3401     else
3402         fa = a;
3403     if (fb)
3404         fb++;
3405     else
3406         fb = b;
3407     if (strNE(a,b))
3408         return FALSE;
3409     if (fa == a)
3410         sv_setpvs(tmpsv, ".");
3411     else
3412         sv_setpvn(tmpsv, a, fa - a);
3413     if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3414         return FALSE;
3415     if (fb == b)
3416         sv_setpvs(tmpsv, ".");
3417     else
3418         sv_setpvn(tmpsv, b, fb - b);
3419     if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3420         return FALSE;
3421     return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3422            tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3423 }
3424 #endif /* !HAS_RENAME */
3425
3426 char*
3427 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3428                  const char *const *const search_ext, I32 flags)
3429 {
3430     dVAR;
3431     const char *xfound = NULL;
3432     char *xfailed = NULL;
3433     char tmpbuf[MAXPATHLEN];
3434     register char *s;
3435     I32 len = 0;
3436     int retval;
3437     char *bufend;
3438 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3439 #  define SEARCH_EXTS ".bat", ".cmd", NULL
3440 #  define MAX_EXT_LEN 4
3441 #endif
3442 #ifdef OS2
3443 #  define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3444 #  define MAX_EXT_LEN 4
3445 #endif
3446 #ifdef VMS
3447 #  define SEARCH_EXTS ".pl", ".com", NULL
3448 #  define MAX_EXT_LEN 4
3449 #endif
3450     /* additional extensions to try in each dir if scriptname not found */
3451 #ifdef SEARCH_EXTS
3452     static const char *const exts[] = { SEARCH_EXTS };
3453     const char *const *const ext = search_ext ? search_ext : exts;
3454     int extidx = 0, i = 0;
3455     const char *curext = NULL;
3456 #else
3457     PERL_UNUSED_ARG(search_ext);
3458 #  define MAX_EXT_LEN 0
3459 #endif
3460
3461     PERL_ARGS_ASSERT_FIND_SCRIPT;
3462
3463     /*
3464      * If dosearch is true and if scriptname does not contain path
3465      * delimiters, search the PATH for scriptname.
3466      *
3467      * If SEARCH_EXTS is also defined, will look for each
3468      * scriptname{SEARCH_EXTS} whenever scriptname is not found
3469      * while searching the PATH.
3470      *
3471      * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3472      * proceeds as follows:
3473      *   If DOSISH or VMSISH:
3474      *     + look for ./scriptname{,.foo,.bar}
3475      *     + search the PATH for scriptname{,.foo,.bar}
3476      *
3477      *   If !DOSISH:
3478      *     + look *only* in the PATH for scriptname{,.foo,.bar} (note
3479      *       this will not look in '.' if it's not in the PATH)
3480      */
3481     tmpbuf[0] = '\0';
3482
3483 #ifdef VMS
3484 #  ifdef ALWAYS_DEFTYPES
3485     len = strlen(scriptname);
3486     if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3487         int idx = 0, deftypes = 1;
3488         bool seen_dot = 1;
3489
3490         const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3491 #  else
3492     if (dosearch) {
3493         int idx = 0, deftypes = 1;
3494         bool seen_dot = 1;
3495
3496         const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3497 #  endif
3498         /* The first time through, just add SEARCH_EXTS to whatever we
3499          * already have, so we can check for default file types. */
3500         while (deftypes ||
3501                (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3502         {
3503             if (deftypes) {
3504                 deftypes = 0;
3505                 *tmpbuf = '\0';
3506             }
3507             if ((strlen(tmpbuf) + strlen(scriptname)
3508                  + MAX_EXT_LEN) >= sizeof tmpbuf)
3509                 continue;       /* don't search dir with too-long name */
3510             my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3511 #else  /* !VMS */
3512
3513 #ifdef DOSISH
3514     if (strEQ(scriptname, "-"))
3515         dosearch = 0;
3516     if (dosearch) {             /* Look in '.' first. */
3517         const char *cur = scriptname;
3518 #ifdef SEARCH_EXTS
3519         if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3520             while (ext[i])
3521                 if (strEQ(ext[i++],curext)) {
3522                     extidx = -1;                /* already has an ext */
3523                     break;
3524                 }
3525         do {
3526 #endif
3527             DEBUG_p(PerlIO_printf(Perl_debug_log,
3528                                   "Looking for %s\n",cur));
3529             if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3530                 && !S_ISDIR(PL_statbuf.st_mode)) {
3531                 dosearch = 0;
3532                 scriptname = cur;
3533 #ifdef SEARCH_EXTS
3534                 break;
3535 #endif
3536             }
3537 #ifdef SEARCH_EXTS
3538             if (cur == scriptname) {
3539                 len = strlen(scriptname);
3540                 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3541                     break;
3542                 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3543                 cur = tmpbuf;
3544             }
3545         } while (extidx >= 0 && ext[extidx]     /* try an extension? */
3546                  && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3547 #endif
3548     }
3549 #endif
3550
3551     if (dosearch && !strchr(scriptname, '/')
3552 #ifdef DOSISH
3553                  && !strchr(scriptname, '\\')
3554 #endif
3555                  && (s = PerlEnv_getenv("PATH")))
3556     {
3557         bool seen_dot = 0;
3558
3559         bufend = s + strlen(s);
3560         while (s < bufend) {
3561 #if defined(atarist) || defined(DOSISH)
3562             for (len = 0; *s
3563 #  ifdef atarist
3564                     && *s != ','
3565 #  endif
3566                     && *s != ';'; len++, s++) {
3567                 if (len < sizeof tmpbuf)
3568                     tmpbuf[len] = *s;
3569             }
3570             if (len < sizeof tmpbuf)
3571                 tmpbuf[len] = '\0';
3572 #else  /* ! (atarist || DOSISH) */
3573             s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3574                         ':',
3575                         &len);
3576 #endif /* ! (atarist || DOSISH) */
3577             if (s < bufend)
3578                 s++;
3579             if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3580                 continue;       /* don't search dir with too-long name */
3581             if (len
3582 #  if defined(atarist) || defined(DOSISH)
3583                 && tmpbuf[len - 1] != '/'
3584                 && tmpbuf[len - 1] != '\\'
3585 #  endif
3586                )
3587                 tmpbuf[len++] = '/';
3588             if (len == 2 && tmpbuf[0] == '.')
3589                 seen_dot = 1;
3590             (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3591 #endif  /* !VMS */
3592
3593 #ifdef SEARCH_EXTS
3594             len = strlen(tmpbuf);
3595             if (extidx > 0)     /* reset after previous loop */
3596                 extidx = 0;
3597             do {
3598 #endif
3599                 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3600                 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3601                 if (S_ISDIR(PL_statbuf.st_mode)) {
3602                     retval = -1;
3603                 }
3604 #ifdef SEARCH_EXTS
3605             } while (  retval < 0               /* not there */
3606                     && extidx>=0 && ext[extidx] /* try an extension? */
3607                     && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3608                 );
3609 #endif
3610             if (retval < 0)
3611                 continue;
3612             if (S_ISREG(PL_statbuf.st_mode)
3613                 && cando(S_IRUSR,TRUE,&PL_statbuf)
3614 #if !defined(DOSISH)
3615                 && cando(S_IXUSR,TRUE,&PL_statbuf)
3616 #endif
3617                 )
3618             {
3619                 xfound = tmpbuf;                /* bingo! */
3620                 break;
3621             }
3622             if (!xfailed)
3623                 xfailed = savepv(tmpbuf);
3624         }
3625 #ifndef DOSISH
3626         if (!xfound && !seen_dot && !xfailed &&
3627             (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3628              || S_ISDIR(PL_statbuf.st_mode)))
3629 #endif
3630             seen_dot = 1;                       /* Disable message. */
3631         if (!xfound) {
3632             if (flags & 1) {                    /* do or die? */
3633                 Perl_croak(aTHX_ "Can't %s %s%s%s",
3634                       (xfailed ? "execute" : "find"),
3635                       (xfailed ? xfailed : scriptname),
3636                       (xfailed ? "" : " on PATH"),
3637                       (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3638             }
3639             scriptname = NULL;
3640         }
3641         Safefree(xfailed);
3642         scriptname = xfound;
3643     }
3644     return (scriptname ? savepv(scriptname) : NULL);
3645 }
3646
3647 #ifndef PERL_GET_CONTEXT_DEFINED
3648
3649 void *
3650 Perl_get_context(void)
3651 {
3652     dVAR;
3653 #if defined(USE_ITHREADS)
3654 #  ifdef OLD_PTHREADS_API
3655     pthread_addr_t t;
3656     if (pthread_getspecific(PL_thr_key, &t))
3657         Perl_croak_nocontext("panic: pthread_getspecific");
3658     return (void*)t;
3659 #  else
3660 #    ifdef I_MACH_CTHREADS
3661     return (void*)cthread_data(cthread_self());
3662 #    else
3663     return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3664 #    endif
3665 #  endif
3666 #else
3667     return (void*)NULL;
3668 #endif
3669 }
3670
3671 void
3672 Perl_set_context(void *t)
3673 {
3674     dVAR;
3675     PERL_ARGS_ASSERT_SET_CONTEXT;
3676 #if defined(USE_ITHREADS)
3677 #  ifdef I_MACH_CTHREADS
3678     cthread_set_data(cthread_self(), t);
3679 #  else
3680     if (pthread_setspecific(PL_thr_key, t))
3681         Perl_croak_nocontext("panic: pthread_setspecific");
3682 #  endif
3683 #else
3684     PERL_UNUSED_ARG(t);
3685 #endif
3686 }
3687
3688 #endif /* !PERL_GET_CONTEXT_DEFINED */
3689
3690 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3691 struct perl_vars *
3692 Perl_GetVars(pTHX)
3693 {
3694  return &PL_Vars;
3695 }
3696 #endif
3697
3698 char **
3699 Perl_get_op_names(pTHX)
3700 {
3701     PERL_UNUSED_CONTEXT;
3702     return (char **)PL_op_name;
3703 }
3704
3705 char **
3706 Perl_get_op_descs(pTHX)
3707 {
3708     PERL_UNUSED_CONTEXT;
3709     return (char **)PL_op_desc;
3710 }
3711
3712 const char *
3713 Perl_get_no_modify(pTHX)
3714 {
3715     PERL_UNUSED_CONTEXT;
3716     return PL_no_modify;
3717 }
3718
3719 U32 *
3720 Perl_get_opargs(pTHX)
3721 {
3722     PERL_UNUSED_CONTEXT;
3723     return (U32 *)PL_opargs;
3724 }
3725
3726 PPADDR_t*
3727 Perl_get_ppaddr(pTHX)
3728 {
3729     dVAR;
3730     PERL_UNUSED_CONTEXT;
3731     return (PPADDR_t*)PL_ppaddr;
3732 }
3733
3734 #ifndef HAS_GETENV_LEN
3735 char *
3736 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3737 {
3738     char * const env_trans = PerlEnv_getenv(env_elem);
3739     PERL_UNUSED_CONTEXT;
3740     PERL_ARGS_ASSERT_GETENV_LEN;
3741     if (env_trans)
3742         *len = strlen(env_trans);
3743     return env_trans;
3744 }
3745 #endif
3746
3747
3748 MGVTBL*
3749 Perl_get_vtbl(pTHX_ int vtbl_id)
3750 {
3751     PERL_UNUSED_CONTEXT;
3752
3753     return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3754         ? NULL : PL_magic_vtables + vtbl_id;
3755 }
3756
3757 I32
3758 Perl_my_fflush_all(pTHX)
3759 {
3760 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3761     return PerlIO_flush(NULL);
3762 #else
3763 # if defined(HAS__FWALK)
3764     extern int fflush(FILE *);
3765     /* undocumented, unprototyped, but very useful BSDism */
3766     extern void _fwalk(int (*)(FILE *));
3767     _fwalk(&fflush);
3768     return 0;
3769 # else
3770 #  if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3771     long open_max = -1;
3772 #   ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3773     open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3774 #   else
3775 #    if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3776     open_max = sysconf(_SC_OPEN_MAX);
3777 #     else
3778 #      ifdef FOPEN_MAX
3779     open_max = FOPEN_MAX;
3780 #      else
3781 #       ifdef OPEN_MAX
3782     open_max = OPEN_MAX;
3783 #       else
3784 #        ifdef _NFILE
3785     open_max = _NFILE;
3786 #        endif
3787 #       endif
3788 #      endif
3789 #     endif
3790 #    endif
3791     if (open_max > 0) {
3792       long i;
3793       for (i = 0; i < open_max; i++)
3794             if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3795                 STDIO_STREAM_ARRAY[i]._file < open_max &&
3796                 STDIO_STREAM_ARRAY[i]._flag)
3797                 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3798       return 0;
3799     }
3800 #  endif
3801     SETERRNO(EBADF,RMS_IFI);
3802     return EOF;
3803 # endif
3804 #endif
3805 }
3806
3807 void
3808 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3809 {
3810     if (ckWARN(WARN_IO)) {
3811         const char * const name
3812             = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3813         const char * const direction = have == '>' ? "out" : "in";
3814
3815         if (name && *name)
3816             Perl_warner(aTHX_ packWARN(WARN_IO),
3817                         "Filehandle %s opened only for %sput",
3818                         name, direction);
3819         else
3820             Perl_warner(aTHX_ packWARN(WARN_IO),
3821                         "Filehandle opened only for %sput", direction);
3822     }
3823 }
3824
3825 void
3826 Perl_report_evil_fh(pTHX_ const GV *gv)
3827 {
3828     const IO *io = gv ? GvIO(gv) : NULL;
3829     const PERL_BITFIELD16 op = PL_op->op_type;
3830     const char *vile;
3831     I32 warn_type;
3832
3833     if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3834         vile = "closed";
3835         warn_type = WARN_CLOSED;
3836     }
3837     else {
3838         vile = "unopened";
3839         warn_type = WARN_UNOPENED;
3840     }
3841
3842     if (ckWARN(warn_type)) {
3843         const char * const name
3844             = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3845         const char * const pars =
3846             (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3847         const char * const func =
3848             (const char *)
3849             (op == OP_READLINE   ? "readline"  :        /* "<HANDLE>" not nice */
3850              op == OP_LEAVEWRITE ? "write" :            /* "write exit" not nice */
3851              PL_op_desc[op]);
3852         const char * const type =
3853             (const char *)
3854             (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3855              ? "socket" : "filehandle");
3856         if (name && *name) {
3857             Perl_warner(aTHX_ packWARN(warn_type),
3858                         "%s%s on %s %s %s", func, pars, vile, type, name);
3859             if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3860                 Perl_warner(
3861                             aTHX_ packWARN(warn_type),
3862                             "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3863                             func, pars, name
3864                             );
3865         }
3866         else {
3867             Perl_warner(aTHX_ packWARN(warn_type),
3868                         "%s%s on %s %s", func, pars, vile, type);
3869             if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3870                 Perl_warner(
3871                             aTHX_ packWARN(warn_type),
3872                             "\t(Are you trying to call %s%s on dirhandle?)\n",
3873                             func, pars
3874                             );
3875         }
3876     }
3877 }
3878
3879 /* To workaround core dumps from the uninitialised tm_zone we get the
3880  * system to give us a reasonable struct to copy.  This fix means that
3881  * strftime uses the tm_zone and tm_gmtoff values returned by
3882  * localtime(time()). That should give the desired result most of the
3883  * time. But probably not always!
3884  *
3885  * This does not address tzname aspects of NETaa14816.
3886  *
3887  */
3888
3889 #ifdef HAS_GNULIBC
3890 # ifndef STRUCT_TM_HASZONE
3891 #    define STRUCT_TM_HASZONE
3892 # endif
3893 #endif
3894
3895 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3896 # ifndef HAS_TM_TM_ZONE
3897 #    define HAS_TM_TM_ZONE
3898 # endif
3899 #endif
3900
3901 void
3902 Perl_init_tm(pTHX_ struct tm *ptm)      /* see mktime, strftime and asctime */
3903 {
3904 #ifdef HAS_TM_TM_ZONE
3905     Time_t now;
3906     const struct tm* my_tm;
3907     PERL_ARGS_ASSERT_INIT_TM;
3908     (void)time(&now);
3909     my_tm = localtime(&now);
3910     if (my_tm)
3911         Copy(my_tm, ptm, 1, struct tm);
3912 #else
3913     PERL_ARGS_ASSERT_INIT_TM;
3914     PERL_UNUSED_ARG(ptm);
3915 #endif
3916 }
3917
3918 /*
3919  * mini_mktime - normalise struct tm values without the localtime()
3920  * semantics (and overhead) of mktime().
3921  */
3922 void
3923 Perl_mini_mktime(pTHX_ struct tm *ptm)
3924 {
3925     int yearday;
3926     int secs;
3927     int month, mday, year, jday;
3928     int odd_cent, odd_year;
3929     PERL_UNUSED_CONTEXT;
3930
3931     PERL_ARGS_ASSERT_MINI_MKTIME;
3932
3933 #define DAYS_PER_YEAR   365
3934 #define DAYS_PER_QYEAR  (4*DAYS_PER_YEAR+1)
3935 #define DAYS_PER_CENT   (25*DAYS_PER_QYEAR-1)
3936 #define DAYS_PER_QCENT  (4*DAYS_PER_CENT+1)
3937 #define SECS_PER_HOUR   (60*60)
3938 #define SECS_PER_DAY    (24*SECS_PER_HOUR)
3939 /* parentheses deliberately absent on these two, otherwise they don't work */
3940 #define MONTH_TO_DAYS   153/5
3941 #define DAYS_TO_MONTH   5/153
3942 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3943 #define YEAR_ADJUST     (4*MONTH_TO_DAYS+1)
3944 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3945 #define WEEKDAY_BIAS    6       /* (1+6)%7 makes Sunday 0 again */
3946
3947 /*
3948  * Year/day algorithm notes:
3949  *
3950  * With a suitable offset for numeric value of the month, one can find
3951  * an offset into the year by considering months to have 30.6 (153/5) days,
3952  * using integer arithmetic (i.e., with truncation).  To avoid too much
3953  * messing about with leap days, we consider January and February to be
3954  * the 13th and 14th month of the previous year.  After that transformation,
3955  * we need the month index we use to be high by 1 from 'normal human' usage,
3956  * so the month index values we use run from 4 through 15.
3957  *
3958  * Given that, and the rules for the Gregorian calendar (leap years are those
3959  * divisible by 4 unless also divisible by 100, when they must be divisible
3960  * by 400 instead), we can simply calculate the number of days since some
3961  * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3962  * the days we derive from our month index, and adding in the day of the
3963  * month.  The value used here is not adjusted for the actual origin which
3964  * it normally would use (1 January A.D. 1), since we're not exposing it.
3965  * We're only building the value so we can turn around and get the
3966  * normalised values for the year, month, day-of-month, and day-of-year.
3967  *
3968  * For going backward, we need to bias the value we're using so that we find
3969  * the right year value.  (Basically, we don't want the contribution of
3970  * March 1st to the number to apply while deriving the year).  Having done
3971  * that, we 'count up' the contribution to the year number by accounting for
3972  * full quadracenturies (400-year periods) with their extra leap days, plus
3973  * the contribution from full centuries (to avoid counting in the lost leap
3974  * days), plus the contribution from full quad-years (to count in the normal
3975  * leap days), plus the leftover contribution from any non-leap years.
3976  * At this point, if we were working with an actual leap day, we'll have 0
3977  * days left over.  This is also true for March 1st, however.  So, we have
3978  * to special-case that result, and (earlier) keep track of the 'odd'
3979  * century and year contributions.  If we got 4 extra centuries in a qcent,
3980  * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3981  * Otherwise, we add back in the earlier bias we removed (the 123 from
3982  * figuring in March 1st), find the month index (integer division by 30.6),
3983  * and the remainder is the day-of-month.  We then have to convert back to
3984  * 'real' months (including fixing January and February from being 14/15 in
3985  * the previous year to being in the proper year).  After that, to get
3986  * tm_yday, we work with the normalised year and get a new yearday value for
3987  * January 1st, which we subtract from the yearday value we had earlier,
3988  * representing the date we've re-built.  This is done from January 1
3989  * because tm_yday is 0-origin.
3990  *
3991  * Since POSIX time routines are only guaranteed to work for times since the
3992  * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3993  * applies Gregorian calendar rules even to dates before the 16th century
3994  * doesn't bother me.  Besides, you'd need cultural context for a given
3995  * date to know whether it was Julian or Gregorian calendar, and that's
3996  * outside the scope for this routine.  Since we convert back based on the
3997  * same rules we used to build the yearday, you'll only get strange results
3998  * for input which needed normalising, or for the 'odd' century years which
3999  * were leap years in the Julian calendar but not in the Gregorian one.
4000  * I can live with that.
4001  *
4002  * This algorithm also fails to handle years before A.D. 1 gracefully, but
4003  * that's still outside the scope for POSIX time manipulation, so I don't
4004  * care.
4005  */
4006
4007     year = 1900 + ptm->tm_year;
4008     month = ptm->tm_mon;
4009     mday = ptm->tm_mday;
4010     /* allow given yday with no month & mday to dominate the result */
4011     if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
4012         month = 0;
4013         mday = 0;
4014         jday = 1 + ptm->tm_yday;
4015     }
4016     else {
4017         jday = 0;
4018     }
4019     if (month >= 2)
4020         month+=2;
4021     else
4022         month+=14, year--;
4023     yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4024     yearday += month*MONTH_TO_DAYS + mday + jday;
4025     /*
4026      * Note that we don't know when leap-seconds were or will be,
4027      * so we have to trust the user if we get something which looks
4028      * like a sensible leap-second.  Wild values for seconds will
4029      * be rationalised, however.
4030      */
4031     if ((unsigned) ptm->tm_sec <= 60) {
4032         secs = 0;
4033     }
4034     else {
4035         secs = ptm->tm_sec;
4036         ptm->tm_sec = 0;
4037     }
4038     secs += 60 * ptm->tm_min;
4039     secs += SECS_PER_HOUR * ptm->tm_hour;
4040     if (secs < 0) {
4041         if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4042             /* got negative remainder, but need positive time */
4043             /* back off an extra day to compensate */
4044             yearday += (secs/SECS_PER_DAY)-1;
4045             secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4046         }
4047         else {
4048             yearday += (secs/SECS_PER_DAY);
4049             secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4050         }
4051     }
4052     else if (secs >= SECS_PER_DAY) {
4053         yearday += (secs/SECS_PER_DAY);
4054         secs %= SECS_PER_DAY;
4055     }
4056     ptm->tm_hour = secs/SECS_PER_HOUR;
4057     secs %= SECS_PER_HOUR;
4058     ptm->tm_min = secs/60;
4059     secs %= 60;
4060     ptm->tm_sec += secs;
4061     /* done with time of day effects */
4062     /*
4063      * The algorithm for yearday has (so far) left it high by 428.
4064      * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4065      * bias it by 123 while trying to figure out what year it
4066      * really represents.  Even with this tweak, the reverse
4067      * translation fails for years before A.D. 0001.
4068      * It would still fail for Feb 29, but we catch that one below.
4069      */
4070     jday = yearday;     /* save for later fixup vis-a-vis Jan 1 */
4071     yearday -= YEAR_ADJUST;
4072     year = (yearday / DAYS_PER_QCENT) * 400;
4073     yearday %= DAYS_PER_QCENT;
4074     odd_cent = yearday / DAYS_PER_CENT;
4075     year += odd_cent * 100;
4076     yearday %= DAYS_PER_CENT;
4077     year += (yearday / DAYS_PER_QYEAR) * 4;
4078     yearday %= DAYS_PER_QYEAR;
4079     odd_year = yearday / DAYS_PER_YEAR;
4080     year += odd_year;
4081     yearday %= DAYS_PER_YEAR;
4082     if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4083         month = 1;
4084         yearday = 29;
4085     }
4086     else {
4087         yearday += YEAR_ADJUST; /* recover March 1st crock */
4088         month = yearday*DAYS_TO_MONTH;
4089         yearday -= month*MONTH_TO_DAYS;
4090         /* recover other leap-year adjustment */
4091         if (month > 13) {
4092             month-=14;
4093             year++;
4094         }
4095         else {
4096             month-=2;
4097         }
4098     }
4099     ptm->tm_year = year - 1900;
4100     if (yearday) {
4101       ptm->tm_mday = yearday;
4102       ptm->tm_mon = month;
4103     }
4104     else {
4105       ptm->tm_mday = 31;
4106       ptm->tm_mon = month - 1;
4107     }
4108     /* re-build yearday based on Jan 1 to get tm_yday */
4109     year--;
4110     yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4111     yearday += 14*MONTH_TO_DAYS + 1;
4112     ptm->tm_yday = jday - yearday;
4113     /* fix tm_wday if not overridden by caller */
4114     if ((unsigned)ptm->tm_wday > 6)
4115         ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4116 }
4117
4118 char *
4119 Perl_my_strftime(pTHX_ const char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
4120 {
4121 #ifdef HAS_STRFTIME
4122   char *buf;
4123   int buflen;
4124   struct tm mytm;
4125   int len;
4126
4127   PERL_ARGS_ASSERT_MY_STRFTIME;
4128
4129   init_tm(&mytm);       /* XXX workaround - see init_tm() above */
4130   mytm.tm_sec = sec;
4131   mytm.tm_min = min;
4132   mytm.tm_hour = hour;
4133   mytm.tm_mday = mday;
4134   mytm.tm_mon = mon;
4135   mytm.tm_year = year;
4136   mytm.tm_wday = wday;
4137   mytm.tm_yday = yday;
4138   mytm.tm_isdst = isdst;
4139   mini_mktime(&mytm);
4140   /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4141 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4142   STMT_START {
4143     struct tm mytm2;
4144     mytm2 = mytm;
4145     mktime(&mytm2);
4146 #ifdef HAS_TM_TM_GMTOFF
4147     mytm.tm_gmtoff = mytm2.tm_gmtoff;
4148 #endif
4149 #ifdef HAS_TM_TM_ZONE
4150     mytm.tm_zone = mytm2.tm_zone;
4151 #endif
4152   } STMT_END;
4153 #endif
4154   buflen = 64;
4155   Newx(buf, buflen, char);
4156   len = strftime(buf, buflen, fmt, &mytm);
4157   /*
4158   ** The following is needed to handle to the situation where
4159   ** tmpbuf overflows.  Basically we want to allocate a buffer
4160   ** and try repeatedly.  The reason why it is so complicated
4161   ** is that getting a return value of 0 from strftime can indicate
4162   ** one of the following:
4163   ** 1. buffer overflowed,
4164   ** 2. illegal conversion specifier, or
4165   ** 3. the format string specifies nothing to be returned(not
4166   **      an error).  This could be because format is an empty string
4167   **    or it specifies %p that yields an empty string in some locale.
4168   ** If there is a better way to make it portable, go ahead by
4169   ** all means.
4170   */
4171   if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4172     return buf;
4173   else {
4174     /* Possibly buf overflowed - try again with a bigger buf */
4175     const int fmtlen = strlen(fmt);
4176     int bufsize = fmtlen + buflen;
4177
4178     Renew(buf, bufsize, char);
4179     while (buf) {
4180       buflen = strftime(buf, bufsize, fmt, &mytm);
4181       if (buflen > 0 && buflen < bufsize)
4182         break;
4183       /* heuristic to prevent out-of-memory errors */
4184       if (bufsize > 100*fmtlen) {
4185         Safefree(buf);
4186         buf = NULL;
4187         break;
4188       }
4189       bufsize *= 2;
4190       Renew(buf, bufsize, char);
4191     }
4192     return buf;
4193   }
4194 #else
4195   Perl_croak(aTHX_ "panic: no strftime");
4196   return NULL;
4197 #endif
4198 }
4199
4200
4201 #define SV_CWD_RETURN_UNDEF \
4202 sv_setsv(sv, &PL_sv_undef); \
4203 return FALSE
4204
4205 #define SV_CWD_ISDOT(dp) \
4206     (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4207         (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4208
4209 /*
4210 =head1 Miscellaneous Functions
4211
4212 =for apidoc getcwd_sv
4213
4214 Fill the sv with current working directory
4215
4216 =cut
4217 */
4218
4219 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4220  * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4221  * getcwd(3) if available
4222  * Comments from the orignal:
4223  *     This is a faster version of getcwd.  It's also more dangerous
4224  *     because you might chdir out of a directory that you can't chdir
4225  *     back into. */
4226
4227 int
4228 Perl_getcwd_sv(pTHX_ register SV *sv)
4229 {
4230 #ifndef PERL_MICRO
4231     dVAR;
4232 #ifndef INCOMPLETE_TAINTS
4233     SvTAINTED_on(sv);
4234 #endif
4235
4236     PERL_ARGS_ASSERT_GETCWD_SV;
4237
4238 #ifdef HAS_GETCWD
4239     {
4240         char buf[MAXPATHLEN];
4241
4242         /* Some getcwd()s automatically allocate a buffer of the given
4243          * size from the heap if they are given a NULL buffer pointer.
4244          * The problem is that this behaviour is not portable. */
4245         if (getcwd(buf, sizeof(buf) - 1)) {
4246             sv_setpv(sv, buf);
4247             return TRUE;
4248         }
4249         else {
4250             sv_setsv(sv, &PL_sv_undef);
4251             return FALSE;
4252         }
4253     }
4254
4255 #else
4256
4257     Stat_t statbuf;
4258     int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4259     int pathlen=0;
4260     Direntry_t *dp;
4261
4262     SvUPGRADE(sv, SVt_PV);
4263
4264     if (PerlLIO_lstat(".", &statbuf) < 0) {
4265         SV_CWD_RETURN_UNDEF;
4266     }
4267
4268     orig_cdev = statbuf.st_dev;
4269     orig_cino = statbuf.st_ino;
4270     cdev = orig_cdev;
4271     cino = orig_cino;
4272
4273     for (;;) {
4274         DIR *dir;
4275         int namelen;
4276         odev = cdev;
4277         oino = cino;
4278
4279         if (PerlDir_chdir("..") < 0) {
4280             SV_CWD_RETURN_UNDEF;
4281         }
4282         if (PerlLIO_stat(".", &statbuf) < 0) {
4283             SV_CWD_RETURN_UNDEF;
4284         }
4285
4286         cdev = statbuf.st_dev;
4287         cino = statbuf.st_ino;
4288
4289         if (odev == cdev && oino == cino) {
4290             break;
4291         }
4292         if (!(dir = PerlDir_open("."))) {
4293             SV_CWD_RETURN_UNDEF;
4294         }
4295
4296         while ((dp = PerlDir_read(dir)) != NULL) {
4297 #ifdef DIRNAMLEN
4298             namelen = dp->d_namlen;
4299 #else
4300             namelen = strlen(dp->d_name);
4301 #endif
4302             /* skip . and .. */
4303             if (SV_CWD_ISDOT(dp)) {
4304                 continue;
4305             }
4306
4307             if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4308                 SV_CWD_RETURN_UNDEF;
4309             }
4310
4311             tdev = statbuf.st_dev;
4312             tino = statbuf.st_ino;
4313             if (tino == oino && tdev == odev) {
4314                 break;
4315             }
4316         }
4317
4318         if (!dp) {
4319             SV_CWD_RETURN_UNDEF;
4320         }
4321
4322         if (pathlen + namelen + 1 >= MAXPATHLEN) {
4323             SV_CWD_RETURN_UNDEF;
4324         }
4325
4326         SvGROW(sv, pathlen + namelen + 1);
4327
4328         if (pathlen) {
4329             /* shift down */
4330             Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4331         }
4332
4333         /* prepend current directory to the front */
4334         *SvPVX(sv) = '/';
4335         Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4336         pathlen += (namelen + 1);
4337
4338 #ifdef VOID_CLOSEDIR
4339         PerlDir_close(dir);
4340 #else
4341         if (PerlDir_close(dir) < 0) {
4342             SV_CWD_RETURN_UNDEF;
4343         }
4344 #endif
4345     }
4346
4347     if (pathlen) {
4348         SvCUR_set(sv, pathlen);
4349         *SvEND(sv) = '\0';
4350         SvPOK_only(sv);
4351
4352         if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4353             SV_CWD_RETURN_UNDEF;
4354         }
4355     }
4356     if (PerlLIO_stat(".", &statbuf) < 0) {
4357         SV_CWD_RETURN_UNDEF;
4358     }
4359
4360     cdev = statbuf.st_dev;
4361     cino = statbuf.st_ino;
4362
4363     if (cdev != orig_cdev || cino != orig_cino) {
4364         Perl_croak(aTHX_ "Unstable directory path, "
4365                    "current directory changed unexpectedly");
4366     }
4367
4368     return TRUE;
4369 #endif
4370
4371 #else
4372     return FALSE;
4373 #endif
4374 }
4375
4376 #define VERSION_MAX 0x7FFFFFFF
4377
4378 /*
4379 =for apidoc prescan_version
4380
4381 Validate that a given string can be parsed as a version object, but doesn't
4382 actually perform the parsing.  Can use either strict or lax validation rules.
4383 Can optionally set a number of hint variables to save the parsing code
4384 some time when tokenizing.
4385
4386 =cut
4387 */
4388 const char *
4389 Perl_prescan_version(pTHX_ const char *s, bool strict,
4390                      const char **errstr,
4391                      bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4392     bool qv = (sqv ? *sqv : FALSE);
4393     int width = 3;
4394     int saw_decimal = 0;
4395     bool alpha = FALSE;
4396     const char *d = s;
4397
4398     PERL_ARGS_ASSERT_PRESCAN_VERSION;
4399
4400     if (qv && isDIGIT(*d))
4401         goto dotted_decimal_version;
4402
4403     if (*d == 'v') { /* explicit v-string */
4404         d++;
4405         if (isDIGIT(*d)) {
4406             qv = TRUE;
4407         }
4408         else { /* degenerate v-string */
4409             /* requires v1.2.3 */
4410             BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4411         }
4412
4413 dotted_decimal_version:
4414         if (strict && d[0] == '0' && isDIGIT(d[1])) {
4415             /* no leading zeros allowed */
4416             BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4417         }
4418
4419         while (isDIGIT(*d))     /* integer part */
4420             d++;
4421
4422         if (*d == '.')
4423         {
4424             saw_decimal++;
4425             d++;                /* decimal point */
4426         }
4427         else
4428         {
4429             if (strict) {
4430                 /* require v1.2.3 */
4431                 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4432             }
4433             else {
4434                 goto version_prescan_finish;
4435             }
4436         }
4437
4438         {
4439             int i = 0;
4440             int j = 0;
4441             while (isDIGIT(*d)) {       /* just keep reading */
4442                 i++;
4443                 while (isDIGIT(*d)) {
4444                     d++; j++;
4445                     /* maximum 3 digits between decimal */
4446                     if (strict && j > 3) {
4447                         BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4448                     }
4449                 }
4450                 if (*d == '_') {
4451                     if (strict) {
4452                         BADVERSION(s,errstr,"Invalid version format (no underscores)");
4453                     }
4454                     if ( alpha ) {
4455                         BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4456                     }
4457                     d++;
4458                     alpha = TRUE;
4459                 }
4460                 else if (*d == '.') {
4461                     if (alpha) {
4462                         BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4463                     }
4464                     saw_decimal++;
4465                     d++;
4466                 }
4467                 else if (!isDIGIT(*d)) {
4468                     break;
4469                 }
4470                 j = 0;
4471             }
4472
4473             if (strict && i < 2) {
4474                 /* requires v1.2.3 */
4475                 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4476             }
4477         }
4478     }                                   /* end if dotted-decimal */
4479     else
4480     {                                   /* decimal versions */
4481         /* special strict case for leading '.' or '0' */
4482         if (strict) {
4483             if (*d == '.') {
4484                 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4485             }
4486             if (*d == '0' && isDIGIT(d[1])) {
4487                 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4488             }
4489         }
4490
4491         /* consume all of the integer part */
4492         while (isDIGIT(*d))
4493             d++;
4494
4495         /* look for a fractional part */
4496         if (*d == '.') {
4497             /* we found it, so consume it */
4498             saw_decimal++;
4499             d++;
4500         }
4501         else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4502             if ( d == s ) {
4503                 /* found nothing */
4504                 BADVERSION(s,errstr,"Invalid version format (version required)");
4505             }
4506             /* found just an integer */
4507             goto version_prescan_finish;
4508         }
4509         else if ( *d == '-') {
4510                 BADVERSION(s,errstr,"Invalid version format (negative version number)");                
4511         }
4512         else if ( d == s ) {
4513             /* didn't find either integer or period */
4514             BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4515         }
4516         else if (*d == '_') {
4517             /* underscore can't come after integer part */
4518             if (strict) {
4519                 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4520             }
4521             else if (isDIGIT(d[1])) {
4522                 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4523             }
4524             else {
4525                 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4526             }
4527         }
4528         else {
4529             /* anything else after integer part is just invalid data */
4530             BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4531         }
4532
4533         /* scan the fractional part after the decimal point*/
4534
4535         if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4536                 /* strict or lax-but-not-the-end */
4537                 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4538         }
4539
4540         while (isDIGIT(*d)) {
4541             d++;
4542             if (*d == '.' && isDIGIT(d[-1])) {
4543                 if (alpha) {
4544                     BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4545                 }
4546                 if (strict) {
4547                     BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4548                 }
4549                 d = (char *)s;          /* start all over again */
4550                 qv = TRUE;
4551                 goto dotted_decimal_version;
4552             }
4553             if (*d == '_') {
4554                 if (strict) {
4555                     BADVERSION(s,errstr,"Invalid version format (no underscores)");
4556                 }
4557                 if ( alpha ) {
4558                     BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4559                 }
4560                 if ( ! isDIGIT(d[1]) ) {
4561                     BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4562                 }
4563                 d++;
4564                 alpha = TRUE;
4565             }
4566         }
4567     }
4568
4569 version_prescan_finish:
4570     while (isSPACE(*d))
4571         d++;
4572
4573     if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4574         /* trailing non-numeric data */
4575         BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4576     }
4577
4578     if (sqv)
4579         *sqv = qv;
4580     if (swidth)
4581         *swidth = width;
4582     if (ssaw_decimal)
4583         *ssaw_decimal = saw_decimal;
4584     if (salpha)
4585         *salpha = alpha;
4586     return d;
4587 }
4588
4589 /*
4590 =for apidoc scan_version
4591
4592 Returns a pointer to the next character after the parsed
4593 version string, as well as upgrading the passed in SV to
4594 an RV.
4595
4596 Function must be called with an already existing SV like
4597
4598     sv = newSV(0);
4599     s = scan_version(s, SV *sv, bool qv);
4600
4601 Performs some preprocessing to the string to ensure that
4602 it has the correct characteristics of a version.  Flags the
4603 object if it contains an underscore (which denotes this
4604 is an alpha version).  The boolean qv denotes that the version
4605 should be interpreted as if it had multiple decimals, even if
4606 it doesn't.
4607
4608 =cut
4609 */
4610
4611 const char *
4612 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4613 {
4614     const char *start;
4615     const char *pos;
4616     const char *last;
4617     const char *errstr = NULL;
4618     int saw_decimal = 0;
4619     int width = 3;
4620     bool alpha = FALSE;
4621     bool vinf = FALSE;
4622     AV * const av = newAV();
4623     SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4624
4625     PERL_ARGS_ASSERT_SCAN_VERSION;
4626
4627     (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4628
4629 #ifndef NODEFAULT_SHAREKEYS
4630     HvSHAREKEYS_on(hv);         /* key-sharing on by default */
4631 #endif
4632
4633     while (isSPACE(*s)) /* leading whitespace is OK */
4634         s++;
4635
4636     last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4637     if (errstr) {
4638         /* "undef" is a special case and not an error */
4639         if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4640             Perl_croak(aTHX_ "%s", errstr);
4641         }
4642     }
4643
4644     start = s;
4645     if (*s == 'v')
4646         s++;
4647     pos = s;
4648
4649     if ( qv )
4650         (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4651     if ( alpha )
4652         (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4653     if ( !qv && width < 3 )
4654         (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4655     
4656     while (isDIGIT(*pos))
4657         pos++;
4658     if (!isALPHA(*pos)) {
4659         I32 rev;
4660
4661         for (;;) {
4662             rev = 0;
4663             {
4664                 /* this is atoi() that delimits on underscores */
4665                 const char *end = pos;
4666                 I32 mult = 1;
4667                 I32 orev;
4668
4669                 /* the following if() will only be true after the decimal
4670                  * point of a version originally created with a bare
4671                  * floating point number, i.e. not quoted in any way
4672                  */
4673                 if ( !qv && s > start && saw_decimal == 1 ) {
4674                     mult *= 100;
4675                     while ( s < end ) {
4676                         orev = rev;
4677                         rev += (*s - '0') * mult;
4678                         mult /= 10;
4679                         if (   (PERL_ABS(orev) > PERL_ABS(rev)) 
4680                             || (PERL_ABS(rev) > VERSION_MAX )) {
4681                             Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW), 
4682                                            "Integer overflow in version %d",VERSION_MAX);
4683                             s = end - 1;
4684                             rev = VERSION_MAX;
4685                             vinf = 1;
4686                         }
4687                         s++;
4688                         if ( *s == '_' )
4689                             s++;
4690                     }
4691                 }
4692                 else {
4693                     while (--end >= s) {
4694                         orev = rev;
4695                         rev += (*end - '0') * mult;
4696                         mult *= 10;
4697                         if (   (PERL_ABS(orev) > PERL_ABS(rev)) 
4698                             || (PERL_ABS(rev) > VERSION_MAX )) {
4699                             Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW), 
4700                                            "Integer overflow in version");
4701                             end = s - 1;
4702                             rev = VERSION_MAX;
4703                             vinf = 1;
4704                         }
4705                     }
4706                 } 
4707             }
4708
4709             /* Append revision */
4710             av_push(av, newSViv(rev));
4711             if ( vinf ) {
4712                 s = last;
4713                 break;
4714             }
4715             else if ( *pos == '.' )
4716                 s = ++pos;
4717             else if ( *pos == '_' && isDIGIT(pos[1]) )
4718                 s = ++pos;
4719             else if ( *pos == ',' && isDIGIT(pos[1]) )
4720                 s = ++pos;
4721             else if ( isDIGIT(*pos) )
4722                 s = pos;
4723             else {
4724                 s = pos;
4725                 break;
4726             }
4727             if ( qv ) {
4728                 while ( isDIGIT(*pos) )
4729                     pos++;
4730             }
4731             else {
4732                 int digits = 0;
4733                 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4734                     if ( *pos != '_' )
4735                         digits++;
4736                     pos++;
4737                 }
4738             }
4739         }
4740     }
4741     if ( qv ) { /* quoted versions always get at least three terms*/
4742         I32 len = av_len(av);
4743         /* This for loop appears to trigger a compiler bug on OS X, as it
4744            loops infinitely. Yes, len is negative. No, it makes no sense.
4745            Compiler in question is:
4746            gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4747            for ( len = 2 - len; len > 0; len-- )
4748            av_push(MUTABLE_AV(sv), newSViv(0));
4749         */
4750         len = 2 - len;
4751         while (len-- > 0)
4752             av_push(av, newSViv(0));
4753     }
4754
4755     /* need to save off the current version string for later */
4756     if ( vinf ) {
4757         SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4758         (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4759         (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4760     }
4761     else if ( s > start ) {
4762         SV * orig = newSVpvn(start,s-start);
4763         if ( qv && saw_decimal == 1 && *start != 'v' ) {
4764             /* need to insert a v to be consistent */
4765             sv_insert(orig, 0, 0, "v", 1);
4766         }
4767         (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4768     }
4769     else {
4770         (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4771         av_push(av, newSViv(0));
4772     }
4773
4774     /* And finally, store the AV in the hash */
4775     (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4776
4777     /* fix RT#19517 - special case 'undef' as string */
4778     if ( *s == 'u' && strEQ(s,"undef") ) {
4779         s += 5;
4780     }
4781
4782     return s;
4783 }
4784
4785 /*
4786 =for apidoc new_version
4787
4788 Returns a new version object based on the passed in SV:
4789
4790     SV *sv = new_version(SV *ver);
4791
4792 Does not alter the passed in ver SV.  See "upg_version" if you
4793 want to upgrade the SV.
4794
4795 =cut
4796 */
4797
4798 SV *
4799 Perl_new_version(pTHX_ SV *ver)
4800 {
4801     dVAR;
4802     SV * const rv = newSV(0);
4803     PERL_ARGS_ASSERT_NEW_VERSION;
4804     if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4805     {
4806         I32 key;
4807         AV * const av = newAV();
4808         AV *sav;
4809         /* This will get reblessed later if a derived class*/
4810         SV * const hv = newSVrv(rv, "version"); 
4811         (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4812 #ifndef NODEFAULT_SHAREKEYS
4813         HvSHAREKEYS_on(hv);         /* key-sharing on by default */
4814 #endif
4815
4816         if ( SvROK(ver) )
4817             ver = SvRV(ver);
4818
4819         /* Begin copying all of the elements */
4820         if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4821             (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4822
4823         if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4824             (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4825         
4826         if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4827         {
4828             const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4829             (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4830         }
4831
4832         if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4833         {
4834             SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4835             (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4836         }
4837
4838         sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4839         /* This will get reblessed later if a derived class*/
4840         for ( key = 0; key <= av_len(sav); key++ )
4841         {
4842             const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4843             av_push(av, newSViv(rev));
4844         }
4845
4846         (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4847         return rv;
4848     }
4849 #ifdef SvVOK
4850     {
4851         const MAGIC* const mg = SvVSTRING_mg(ver);
4852         if ( mg ) { /* already a v-string */
4853             const STRLEN len = mg->mg_len;
4854             char * const version = savepvn( (const char*)mg->mg_ptr, len);
4855             sv_setpvn(rv,version,len);
4856             /* this is for consistency with the pure Perl class */
4857             if ( isDIGIT(*version) )
4858                 sv_insert(rv, 0, 0, "v", 1);
4859             Safefree(version);
4860         }
4861         else {
4862 #endif
4863         sv_setsv(rv,ver); /* make a duplicate */
4864 #ifdef SvVOK
4865         }
4866     }
4867 #endif
4868     return upg_version(rv, FALSE);
4869 }
4870
4871 /*
4872 =for apidoc upg_version
4873
4874 In-place upgrade of the supplied SV to a version object.
4875
4876     SV *sv = upg_version(SV *sv, bool qv);
4877
4878 Returns a pointer to the upgraded SV.  Set the boolean qv if you want
4879 to force this SV to be interpreted as an "extended" version.
4880
4881 =cut
4882 */
4883
4884 SV *
4885 Perl_upg_version(pTHX_ SV *ver, bool qv)
4886 {
4887     const char *version, *s;
4888 #ifdef SvVOK
4889     const MAGIC *mg;
4890 #endif
4891
4892     PERL_ARGS_ASSERT_UPG_VERSION;
4893
4894     if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4895     {
4896         /* may get too much accuracy */ 
4897         char tbuf[64];
4898 #ifdef USE_LOCALE_NUMERIC
4899         char *loc = setlocale(LC_NUMERIC, "C");
4900 #endif
4901         STRLEN len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4902 #ifdef USE_LOCALE_NUMERIC
4903         setlocale(LC_NUMERIC, loc);
4904 #endif
4905         while (tbuf[len-1] == '0' && len > 0) len--;
4906         if ( tbuf[len-1] == '.' ) len--; /* eat the trailing decimal */
4907         version = savepvn(tbuf, len);
4908     }
4909 #ifdef SvVOK
4910     else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4911         version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4912         qv = TRUE;
4913     }
4914 #endif
4915     else /* must be a string or something like a string */
4916     {
4917         STRLEN len;
4918         version = savepv(SvPV(ver,len));
4919 #ifndef SvVOK
4920 #  if PERL_VERSION > 5
4921         /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4922         if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
4923             /* may be a v-string */
4924             char *testv = (char *)version;
4925             STRLEN tlen = len;
4926             for (tlen=0; tlen < len; tlen++, testv++) {
4927                 /* if one of the characters is non-text assume v-string */
4928                 if (testv[0] < ' ') {
4929                     SV * const nsv = sv_newmortal();
4930                     const char *nver;
4931                     const char *pos;
4932                     int saw_decimal = 0;
4933                     sv_setpvf(nsv,"v%vd",ver);
4934                     pos = nver = savepv(SvPV_nolen(nsv));
4935
4936                     /* scan the resulting formatted string */
4937                     pos++; /* skip the leading 'v' */
4938                     while ( *pos == '.' || isDIGIT(*pos) ) {
4939                         if ( *pos == '.' )
4940                             saw_decimal++ ;
4941                         pos++;
4942                     }
4943
4944                     /* is definitely a v-string */
4945                     if ( saw_decimal >= 2 ) {   
4946                         Safefree(version);
4947                         version = nver;
4948                     }
4949                     break;
4950                 }
4951             }
4952         }
4953 #  endif
4954 #endif
4955     }
4956
4957     s = scan_version(version, ver, qv);
4958     if ( *s != '\0' ) 
4959         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), 
4960                        "Version string '%s' contains invalid data; "
4961                        "ignoring: '%s'", version, s);
4962     Safefree(version);
4963     return ver;
4964 }
4965
4966 /*
4967 =for apidoc vverify
4968
4969 Validates that the SV contains valid internal structure for a version object.
4970 It may be passed either the version object (RV) or the hash itself (HV).  If
4971 the structure is valid, it returns the HV.  If the structure is invalid,
4972 it returns NULL.
4973
4974     SV *hv = vverify(sv);
4975
4976 Note that it only confirms the bare minimum structure (so as not to get
4977 confused by derived classes which may contain additional hash entries):
4978
4979 =over 4
4980
4981 =item * The SV is an HV or a reference to an HV
4982
4983 =item * The hash contains a "version" key
4984
4985 =item * The "version" key has a reference to an AV as its value
4986
4987 =back
4988
4989 =cut
4990 */
4991
4992 SV *
4993 Perl_vverify(pTHX_ SV *vs)
4994 {
4995     SV *sv;
4996
4997     PERL_ARGS_ASSERT_VVERIFY;
4998
4999     if ( SvROK(vs) )
5000         vs = SvRV(vs);
5001
5002     /* see if the appropriate elements exist */
5003     if ( SvTYPE(vs) == SVt_PVHV
5004          && hv_exists(MUTABLE_HV(vs), "version", 7)
5005          && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
5006          && SvTYPE(sv) == SVt_PVAV )
5007         return vs;
5008     else
5009         return NULL;
5010 }
5011
5012 /*
5013 =for apidoc vnumify
5014
5015 Accepts a version object and returns the normalized floating
5016 point representation.  Call like:
5017
5018     sv = vnumify(rv);
5019
5020 NOTE: you can pass either the object directly or the SV
5021 contained within the RV.
5022
5023 The SV returned has a refcount of 1.
5024
5025 =cut
5026 */
5027
5028 SV *
5029 Perl_vnumify(pTHX_ SV *vs)
5030 {
5031     I32 i, len, digit;
5032     int width;
5033     bool alpha = FALSE;
5034     SV *sv;
5035     AV *av;
5036
5037     PERL_ARGS_ASSERT_VNUMIFY;