This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
In overload::ov_method, use ‘no overloading’
[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 HAS_SELECT
45 # ifdef I_SYS_SELECT
46 #  include <sys/select.h>
47 # endif
48 #endif
49
50 #define FLUSH
51
52 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
53 #  define FD_CLOEXEC 1                  /* NeXT needs this */
54 #endif
55
56 /* NOTE:  Do not call the next three routines directly.  Use the macros
57  * in handy.h, so that we can easily redefine everything to do tracking of
58  * allocated hunks back to the original New to track down any memory leaks.
59  * XXX This advice seems to be widely ignored :-(   --AD  August 1996.
60  */
61
62 static char *
63 S_write_no_mem(pTHX)
64 {
65     dVAR;
66     /* Can't use PerlIO to write as it allocates memory */
67     PerlLIO_write(PerlIO_fileno(Perl_error_log),
68                   PL_no_mem, strlen(PL_no_mem));
69     my_exit(1);
70     NORETURN_FUNCTION_END;
71 }
72
73 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
74 #  define ALWAYS_NEED_THX
75 #endif
76
77 /* paranoid version of system's malloc() */
78
79 Malloc_t
80 Perl_safesysmalloc(MEM_SIZE size)
81 {
82 #ifdef ALWAYS_NEED_THX
83     dTHX;
84 #endif
85     Malloc_t ptr;
86 #ifdef HAS_64K_LIMIT
87         if (size > 0xffff) {
88             PerlIO_printf(Perl_error_log,
89                           "Allocation too large: %lx\n", size) FLUSH;
90             my_exit(1);
91         }
92 #endif /* HAS_64K_LIMIT */
93 #ifdef PERL_TRACK_MEMPOOL
94     size += sTHX;
95 #endif
96 #ifdef DEBUGGING
97     if ((SSize_t)size < 0)
98         Perl_croak_nocontext("panic: malloc, size=%"UVuf, (UV) size);
99 #endif
100     ptr = (Malloc_t)PerlMem_malloc(size?size:1);        /* malloc(0) is NASTY on our system */
101     PERL_ALLOC_CHECK(ptr);
102     if (ptr != NULL) {
103 #ifdef PERL_TRACK_MEMPOOL
104         struct perl_memory_debug_header *const header
105             = (struct perl_memory_debug_header *)ptr;
106 #endif
107
108 #ifdef PERL_POISON
109         PoisonNew(((char *)ptr), size, char);
110 #endif
111
112 #ifdef PERL_TRACK_MEMPOOL
113         header->interpreter = aTHX;
114         /* Link us into the list.  */
115         header->prev = &PL_memory_debug_header;
116         header->next = PL_memory_debug_header.next;
117         PL_memory_debug_header.next = header;
118         header->next->prev = header;
119 #  ifdef PERL_POISON
120         header->size = size;
121 #  endif
122         ptr = (Malloc_t)((char*)ptr+sTHX);
123 #endif
124         DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
125         return ptr;
126 }
127     else {
128 #ifndef ALWAYS_NEED_THX
129         dTHX;
130 #endif
131         if (PL_nomemok)
132             return NULL;
133         else {
134             return write_no_mem();
135         }
136     }
137     /*NOTREACHED*/
138 }
139
140 /* paranoid version of system's realloc() */
141
142 Malloc_t
143 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
144 {
145 #ifdef ALWAYS_NEED_THX
146     dTHX;
147 #endif
148     Malloc_t ptr;
149 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
150     Malloc_t PerlMem_realloc();
151 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
152
153 #ifdef HAS_64K_LIMIT
154     if (size > 0xffff) {
155         PerlIO_printf(Perl_error_log,
156                       "Reallocation too large: %lx\n", size) FLUSH;
157         my_exit(1);
158     }
159 #endif /* HAS_64K_LIMIT */
160     if (!size) {
161         safesysfree(where);
162         return NULL;
163     }
164
165     if (!where)
166         return safesysmalloc(size);
167 #ifdef PERL_TRACK_MEMPOOL
168     where = (Malloc_t)((char*)where-sTHX);
169     size += sTHX;
170     {
171         struct perl_memory_debug_header *const header
172             = (struct perl_memory_debug_header *)where;
173
174         if (header->interpreter != aTHX) {
175             Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
176                                  header->interpreter, aTHX);
177         }
178         assert(header->next->prev == header);
179         assert(header->prev->next == header);
180 #  ifdef PERL_POISON
181         if (header->size > size) {
182             const MEM_SIZE freed_up = header->size - size;
183             char *start_of_freed = ((char *)where) + size;
184             PoisonFree(start_of_freed, freed_up, char);
185         }
186         header->size = size;
187 #  endif
188     }
189 #endif
190 #ifdef DEBUGGING
191     if ((SSize_t)size < 0)
192         Perl_croak_nocontext("panic: realloc, size=%"UVuf, (UV)size);
193 #endif
194     ptr = (Malloc_t)PerlMem_realloc(where,size);
195     PERL_ALLOC_CHECK(ptr);
196
197     /* MUST do this fixup first, before doing ANYTHING else, as anything else
198        might allocate memory/free/move memory, and until we do the fixup, it
199        may well be chasing (and writing to) free memory.  */
200 #ifdef PERL_TRACK_MEMPOOL
201     if (ptr != NULL) {
202         struct perl_memory_debug_header *const header
203             = (struct perl_memory_debug_header *)ptr;
204
205 #  ifdef PERL_POISON
206         if (header->size < size) {
207             const MEM_SIZE fresh = size - header->size;
208             char *start_of_fresh = ((char *)ptr) + size;
209             PoisonNew(start_of_fresh, fresh, char);
210         }
211 #  endif
212
213         header->next->prev = header;
214         header->prev->next = header;
215
216         ptr = (Malloc_t)((char*)ptr+sTHX);
217     }
218 #endif
219
220     /* In particular, must do that fixup above before logging anything via
221      *printf(), as it can reallocate memory, which can cause SEGVs.  */
222
223     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
224     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
225
226
227     if (ptr != NULL) {
228         return ptr;
229     }
230     else {
231 #ifndef ALWAYS_NEED_THX
232         dTHX;
233 #endif
234         if (PL_nomemok)
235             return NULL;
236         else {
237             return write_no_mem();
238         }
239     }
240     /*NOTREACHED*/
241 }
242
243 /* safe version of system's free() */
244
245 Free_t
246 Perl_safesysfree(Malloc_t where)
247 {
248 #ifdef ALWAYS_NEED_THX
249     dTHX;
250 #else
251     dVAR;
252 #endif
253     DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
254     if (where) {
255 #ifdef PERL_TRACK_MEMPOOL
256         where = (Malloc_t)((char*)where-sTHX);
257         {
258             struct perl_memory_debug_header *const header
259                 = (struct perl_memory_debug_header *)where;
260
261             if (header->interpreter != aTHX) {
262                 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
263                                      header->interpreter, aTHX);
264             }
265             if (!header->prev) {
266                 Perl_croak_nocontext("panic: duplicate free");
267             }
268             if (!(header->next))
269                 Perl_croak_nocontext("panic: bad free, header->next==NULL");
270             if (header->next->prev != header || header->prev->next != header) {
271                 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
272                                      "header=%p, ->prev->next=%p",
273                                      header->next->prev, header,
274                                      header->prev->next);
275             }
276             /* Unlink us from the chain.  */
277             header->next->prev = header->prev;
278             header->prev->next = header->next;
279 #  ifdef PERL_POISON
280             PoisonNew(where, header->size, char);
281 #  endif
282             /* Trigger the duplicate free warning.  */
283             header->next = NULL;
284         }
285 #endif
286         PerlMem_free(where);
287     }
288 }
289
290 /* safe version of system's calloc() */
291
292 Malloc_t
293 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
294 {
295 #ifdef ALWAYS_NEED_THX
296     dTHX;
297 #endif
298     Malloc_t ptr;
299 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
300     MEM_SIZE total_size = 0;
301 #endif
302
303     /* Even though calloc() for zero bytes is strange, be robust. */
304     if (size && (count <= MEM_SIZE_MAX / size)) {
305 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
306         total_size = size * count;
307 #endif
308     }
309     else
310         Perl_croak_nocontext("%s", PL_memory_wrap);
311 #ifdef PERL_TRACK_MEMPOOL
312     if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
313         total_size += sTHX;
314     else
315         Perl_croak_nocontext("%s", PL_memory_wrap);
316 #endif
317 #ifdef HAS_64K_LIMIT
318     if (total_size > 0xffff) {
319         PerlIO_printf(Perl_error_log,
320                       "Allocation too large: %lx\n", total_size) FLUSH;
321         my_exit(1);
322     }
323 #endif /* HAS_64K_LIMIT */
324 #ifdef DEBUGGING
325     if ((SSize_t)size < 0 || (SSize_t)count < 0)
326         Perl_croak_nocontext("panic: calloc, size=%"UVuf", count=%"UVuf,
327                              (UV)size, (UV)count);
328 #endif
329 #ifdef PERL_TRACK_MEMPOOL
330     /* Have to use malloc() because we've added some space for our tracking
331        header.  */
332     /* malloc(0) is non-portable. */
333     ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
334 #else
335     /* Use calloc() because it might save a memset() if the memory is fresh
336        and clean from the OS.  */
337     if (count && size)
338         ptr = (Malloc_t)PerlMem_calloc(count, size);
339     else /* calloc(0) is non-portable. */
340         ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
341 #endif
342     PERL_ALLOC_CHECK(ptr);
343     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));
344     if (ptr != NULL) {
345 #ifdef PERL_TRACK_MEMPOOL
346         {
347             struct perl_memory_debug_header *const header
348                 = (struct perl_memory_debug_header *)ptr;
349
350             memset((void*)ptr, 0, total_size);
351             header->interpreter = aTHX;
352             /* Link us into the list.  */
353             header->prev = &PL_memory_debug_header;
354             header->next = PL_memory_debug_header.next;
355             PL_memory_debug_header.next = header;
356             header->next->prev = header;
357 #  ifdef PERL_POISON
358             header->size = total_size;
359 #  endif
360             ptr = (Malloc_t)((char*)ptr+sTHX);
361         }
362 #endif
363         return ptr;
364     }
365     else {
366 #ifndef ALWAYS_NEED_THX
367         dTHX;
368 #endif
369         if (PL_nomemok)
370             return NULL;
371         return write_no_mem();
372     }
373 }
374
375 /* These must be defined when not using Perl's malloc for binary
376  * compatibility */
377
378 #ifndef MYMALLOC
379
380 Malloc_t Perl_malloc (MEM_SIZE nbytes)
381 {
382     dTHXs;
383     return (Malloc_t)PerlMem_malloc(nbytes);
384 }
385
386 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
387 {
388     dTHXs;
389     return (Malloc_t)PerlMem_calloc(elements, size);
390 }
391
392 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
393 {
394     dTHXs;
395     return (Malloc_t)PerlMem_realloc(where, nbytes);
396 }
397
398 Free_t   Perl_mfree (Malloc_t where)
399 {
400     dTHXs;
401     PerlMem_free(where);
402 }
403
404 #endif
405
406 /* copy a string up to some (non-backslashed) delimiter, if any */
407
408 char *
409 Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
410 {
411     register I32 tolen;
412
413     PERL_ARGS_ASSERT_DELIMCPY;
414
415     for (tolen = 0; from < fromend; from++, tolen++) {
416         if (*from == '\\') {
417             if (from[1] != delim) {
418                 if (to < toend)
419                     *to++ = *from;
420                 tolen++;
421             }
422             from++;
423         }
424         else if (*from == delim)
425             break;
426         if (to < toend)
427             *to++ = *from;
428     }
429     if (to < toend)
430         *to = '\0';
431     *retlen = tolen;
432     return (char *)from;
433 }
434
435 /* return ptr to little string in big string, NULL if not found */
436 /* This routine was donated by Corey Satten. */
437
438 char *
439 Perl_instr(register const char *big, register const char *little)
440 {
441     register I32 first;
442
443     PERL_ARGS_ASSERT_INSTR;
444
445     if (!little)
446         return (char*)big;
447     first = *little++;
448     if (!first)
449         return (char*)big;
450     while (*big) {
451         register const char *s, *x;
452         if (*big++ != first)
453             continue;
454         for (x=big,s=little; *s; /**/ ) {
455             if (!*x)
456                 return NULL;
457             if (*s != *x)
458                 break;
459             else {
460                 s++;
461                 x++;
462             }
463         }
464         if (!*s)
465             return (char*)(big-1);
466     }
467     return NULL;
468 }
469
470 /* same as instr but allow embedded nulls */
471
472 char *
473 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
474 {
475     PERL_ARGS_ASSERT_NINSTR;
476     if (little >= lend)
477         return (char*)big;
478     {
479         const char first = *little;
480         const char *s, *x;
481         bigend -= lend - little++;
482     OUTER:
483         while (big <= bigend) {
484             if (*big++ == first) {
485                 for (x=big,s=little; s < lend; x++,s++) {
486                     if (*s != *x)
487                         goto OUTER;
488                 }
489                 return (char*)(big-1);
490             }
491         }
492     }
493     return NULL;
494 }
495
496 /* reverse of the above--find last substring */
497
498 char *
499 Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
500 {
501     register const char *bigbeg;
502     register const I32 first = *little;
503     register const char * const littleend = lend;
504
505     PERL_ARGS_ASSERT_RNINSTR;
506
507     if (little >= littleend)
508         return (char*)bigend;
509     bigbeg = big;
510     big = bigend - (littleend - little++);
511     while (big >= bigbeg) {
512         register const char *s, *x;
513         if (*big-- != first)
514             continue;
515         for (x=big+2,s=little; s < littleend; /**/ ) {
516             if (*s != *x)
517                 break;
518             else {
519                 x++;
520                 s++;
521             }
522         }
523         if (s >= littleend)
524             return (char*)(big+1);
525     }
526     return NULL;
527 }
528
529 /* As a space optimization, we do not compile tables for strings of length
530    0 and 1, and for strings of length 2 unless FBMcf_TAIL.  These are
531    special-cased in fbm_instr().
532
533    If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
534
535 /*
536 =head1 Miscellaneous Functions
537
538 =for apidoc fbm_compile
539
540 Analyses the string in order to make fast searches on it using fbm_instr()
541 -- the Boyer-Moore algorithm.
542
543 =cut
544 */
545
546 void
547 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
548 {
549     dVAR;
550     register const U8 *s;
551     STRLEN i;
552     STRLEN len;
553     STRLEN rarest = 0;
554     U32 frequency = 256;
555     MAGIC *mg;
556
557     PERL_ARGS_ASSERT_FBM_COMPILE;
558
559     /* Refuse to fbm_compile a studied scalar, as this gives more flexibility in
560        SV flag usage.  No real-world code would ever end up using a studied
561        scalar as a compile-time second argument to index, so this isn't a real
562        pessimisation.  */
563     if (SvSCREAM(sv))
564         return;
565
566     if (SvVALID(sv))
567         return;
568
569     if (flags & FBMcf_TAIL) {
570         MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
571         sv_catpvs(sv, "\n");            /* Taken into account in fbm_instr() */
572         if (mg && mg->mg_len >= 0)
573             mg->mg_len++;
574     }
575     s = (U8*)SvPV_force_mutable(sv, len);
576     if (len == 0)               /* TAIL might be on a zero-length string. */
577         return;
578     SvUPGRADE(sv, SVt_PVMG);
579     SvIOK_off(sv);
580     SvNOK_off(sv);
581     SvVALID_on(sv);
582
583     /* "deep magic", the comment used to add. The use of MAGIC itself isn't
584        really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
585        to call SvVALID_off() if the scalar was assigned to.
586
587        The comment itself (and "deeper magic" below) date back to
588        378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
589        str->str_pok |= 2;
590        where the magic (presumably) was that the scalar had a BM table hidden
591        inside itself.
592
593        As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
594        the table instead of the previous (somewhat hacky) approach of co-opting
595        the string buffer and storing it after the string.  */
596
597     assert(!mg_find(sv, PERL_MAGIC_bm));
598     mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
599     assert(mg);
600
601     if (len > 2) {
602         /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
603            the BM table.  */
604         const U8 mlen = (len>255) ? 255 : (U8)len;
605         const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
606         register U8 *table;
607
608         Newx(table, 256, U8);
609         memset((void*)table, mlen, 256);
610         mg->mg_ptr = (char *)table;
611         mg->mg_len = 256;
612
613         s += len - 1; /* last char */
614         i = 0;
615         while (s >= sb) {
616             if (table[*s] == mlen)
617                 table[*s] = (U8)i;
618             s--, i++;
619         }
620     }
621
622     s = (const unsigned char*)(SvPVX_const(sv));        /* deeper magic */
623     for (i = 0; i < len; i++) {
624         if (PL_freq[s[i]] < frequency) {
625             rarest = i;
626             frequency = PL_freq[s[i]];
627         }
628     }
629     BmRARE(sv) = s[rarest];
630     BmPREVIOUS(sv) = rarest;
631     BmUSEFUL(sv) = 100;                 /* Initial value */
632     if (flags & FBMcf_TAIL)
633         SvTAIL_on(sv);
634     DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
635                           BmRARE(sv), BmPREVIOUS(sv)));
636 }
637
638 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
639 /* If SvTAIL is actually due to \Z or \z, this gives false positives
640    if multiline */
641
642 /*
643 =for apidoc fbm_instr
644
645 Returns the location of the SV in the string delimited by C<str> and
646 C<strend>.  It returns C<NULL> if the string can't be found.  The C<sv>
647 does not have to be fbm_compiled, but the search will not be as fast
648 then.
649
650 =cut
651 */
652
653 char *
654 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
655 {
656     register unsigned char *s;
657     STRLEN l;
658     register const unsigned char *little
659         = (const unsigned char *)SvPV_const(littlestr,l);
660     register STRLEN littlelen = l;
661     register const I32 multiline = flags & FBMrf_MULTILINE;
662
663     PERL_ARGS_ASSERT_FBM_INSTR;
664
665     if ((STRLEN)(bigend - big) < littlelen) {
666         if ( SvTAIL(littlestr)
667              && ((STRLEN)(bigend - big) == littlelen - 1)
668              && (littlelen == 1
669                  || (*big == *little &&
670                      memEQ((char *)big, (char *)little, littlelen - 1))))
671             return (char*)big;
672         return NULL;
673     }
674
675     switch (littlelen) { /* Special cases for 0, 1 and 2  */
676     case 0:
677         return (char*)big;              /* Cannot be SvTAIL! */
678     case 1:
679             if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
680                 /* Know that bigend != big.  */
681                 if (bigend[-1] == '\n')
682                     return (char *)(bigend - 1);
683                 return (char *) bigend;
684             }
685             s = big;
686             while (s < bigend) {
687                 if (*s == *little)
688                     return (char *)s;
689                 s++;
690             }
691             if (SvTAIL(littlestr))
692                 return (char *) bigend;
693             return NULL;
694     case 2:
695         if (SvTAIL(littlestr) && !multiline) {
696             if (bigend[-1] == '\n' && bigend[-2] == *little)
697                 return (char*)bigend - 2;
698             if (bigend[-1] == *little)
699                 return (char*)bigend - 1;
700             return NULL;
701         }
702         {
703             /* This should be better than FBM if c1 == c2, and almost
704                as good otherwise: maybe better since we do less indirection.
705                And we save a lot of memory by caching no table. */
706             const unsigned char c1 = little[0];
707             const unsigned char c2 = little[1];
708
709             s = big + 1;
710             bigend--;
711             if (c1 != c2) {
712                 while (s <= bigend) {
713                     if (s[0] == c2) {
714                         if (s[-1] == c1)
715                             return (char*)s - 1;
716                         s += 2;
717                         continue;
718                     }
719                   next_chars:
720                     if (s[0] == c1) {
721                         if (s == bigend)
722                             goto check_1char_anchor;
723                         if (s[1] == c2)
724                             return (char*)s;
725                         else {
726                             s++;
727                             goto next_chars;
728                         }
729                     }
730                     else
731                         s += 2;
732                 }
733                 goto check_1char_anchor;
734             }
735             /* Now c1 == c2 */
736             while (s <= bigend) {
737                 if (s[0] == c1) {
738                     if (s[-1] == c1)
739                         return (char*)s - 1;
740                     if (s == bigend)
741                         goto check_1char_anchor;
742                     if (s[1] == c1)
743                         return (char*)s;
744                     s += 3;
745                 }
746                 else
747                     s += 2;
748             }
749         }
750       check_1char_anchor:               /* One char and anchor! */
751         if (SvTAIL(littlestr) && (*bigend == *little))
752             return (char *)bigend;      /* bigend is already decremented. */
753         return NULL;
754     default:
755         break; /* Only lengths 0 1 and 2 have special-case code.  */
756     }
757
758     if (SvTAIL(littlestr) && !multiline) {      /* tail anchored? */
759         s = bigend - littlelen;
760         if (s >= big && bigend[-1] == '\n' && *s == *little
761             /* Automatically of length > 2 */
762             && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
763         {
764             return (char*)s;            /* how sweet it is */
765         }
766         if (s[1] == *little
767             && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
768         {
769             return (char*)s + 1;        /* how sweet it is */
770         }
771         return NULL;
772     }
773     if (!SvVALID(littlestr)) {
774         char * const b = ninstr((char*)big,(char*)bigend,
775                          (char*)little, (char*)little + littlelen);
776
777         if (!b && SvTAIL(littlestr)) {  /* Automatically multiline!  */
778             /* Chop \n from littlestr: */
779             s = bigend - littlelen + 1;
780             if (*s == *little
781                 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
782             {
783                 return (char*)s;
784             }
785             return NULL;
786         }
787         return b;
788     }
789
790     /* Do actual FBM.  */
791     if (littlelen > (STRLEN)(bigend - big))
792         return NULL;
793
794     {
795         const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
796         const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
797         register const unsigned char *oldlittle;
798
799         --littlelen;                    /* Last char found by table lookup */
800
801         s = big + littlelen;
802         little += littlelen;            /* last char */
803         oldlittle = little;
804         if (s < bigend) {
805             register I32 tmp;
806
807           top2:
808             if ((tmp = table[*s])) {
809                 if ((s += tmp) < bigend)
810                     goto top2;
811                 goto check_end;
812             }
813             else {              /* less expensive than calling strncmp() */
814                 register unsigned char * const olds = s;
815
816                 tmp = littlelen;
817
818                 while (tmp--) {
819                     if (*--s == *--little)
820                         continue;
821                     s = olds + 1;       /* here we pay the price for failure */
822                     little = oldlittle;
823                     if (s < bigend)     /* fake up continue to outer loop */
824                         goto top2;
825                     goto check_end;
826                 }
827                 return (char *)s;
828             }
829         }
830       check_end:
831         if ( s == bigend
832              && SvTAIL(littlestr)
833              && memEQ((char *)(bigend - littlelen),
834                       (char *)(oldlittle - littlelen), littlelen) )
835             return (char*)bigend - littlelen;
836         return NULL;
837     }
838 }
839
840 /* start_shift, end_shift are positive quantities which give offsets
841    of ends of some substring of bigstr.
842    If "last" we want the last occurrence.
843    old_posp is the way of communication between consequent calls if
844    the next call needs to find the .
845    The initial *old_posp should be -1.
846
847    Note that we take into account SvTAIL, so one can get extra
848    optimizations if _ALL flag is set.
849  */
850
851 /* If SvTAIL is actually due to \Z or \z, this gives false positives
852    if PL_multiline.  In fact if !PL_multiline the authoritative answer
853    is not supported yet. */
854
855 char *
856 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
857 {
858     dVAR;
859     register const unsigned char *big;
860     U32 pos = 0; /* hush a gcc warning */
861     register I32 previous;
862     register I32 first;
863     register const unsigned char *little;
864     register I32 stop_pos;
865     register const unsigned char *littleend;
866     bool found = FALSE;
867     const MAGIC * mg;
868     const void *screamnext_raw = NULL; /* hush a gcc warning */
869     bool cant_find = FALSE; /* hush a gcc warning */
870
871     PERL_ARGS_ASSERT_SCREAMINSTR;
872
873     assert(SvMAGICAL(bigstr));
874     mg = mg_find(bigstr, PERL_MAGIC_study);
875     assert(mg);
876     assert(SvTYPE(littlestr) == SVt_PVMG);
877     assert(SvVALID(littlestr));
878
879     if (mg->mg_private == 1) {
880         const U8 *const screamfirst = (U8 *)mg->mg_ptr;
881         const U8 *const screamnext = screamfirst + 256;
882
883         screamnext_raw = (const void *)screamnext;
884
885         pos = *old_posp == -1
886             ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
887         cant_find = pos == (U8)~0;
888     } else if (mg->mg_private == 2) {
889         const U16 *const screamfirst = (U16 *)mg->mg_ptr;
890         const U16 *const screamnext = screamfirst + 256;
891
892         screamnext_raw = (const void *)screamnext;
893
894         pos = *old_posp == -1
895             ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
896         cant_find = pos == (U16)~0;
897     } else if (mg->mg_private == 4) {
898         const U32 *const screamfirst = (U32 *)mg->mg_ptr;
899         const U32 *const screamnext = screamfirst + 256;
900
901         screamnext_raw = (const void *)screamnext;
902
903         pos = *old_posp == -1
904             ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
905         cant_find = pos == (U32)~0;
906     } else
907         Perl_croak(aTHX_ "panic: unknown study size %u", mg->mg_private);
908
909     if (cant_find) {
910       cant_find:
911         if ( BmRARE(littlestr) == '\n'
912              && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
913             little = (const unsigned char *)(SvPVX_const(littlestr));
914             littleend = little + SvCUR(littlestr);
915             first = *little++;
916             goto check_tail;
917         }
918         return NULL;
919     }
920
921     little = (const unsigned char *)(SvPVX_const(littlestr));
922     littleend = little + SvCUR(littlestr);
923     first = *little++;
924     /* The value of pos we can start at: */
925     previous = BmPREVIOUS(littlestr);
926     big = (const unsigned char *)(SvPVX_const(bigstr));
927     /* The value of pos we can stop at: */
928     stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
929     if (previous + start_shift > stop_pos) {
930 /*
931   stop_pos does not include SvTAIL in the count, so this check is incorrect
932   (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
933 */
934 #if 0
935         if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
936             goto check_tail;
937 #endif
938         return NULL;
939     }
940     if (mg->mg_private == 1) {
941         const U8 *const screamnext = (const U8 *const) screamnext_raw;
942         while ((I32)pos < previous + start_shift) {
943             pos = screamnext[pos];
944             if (pos == (U8)~0)
945                 goto cant_find;
946         }
947     } else if (mg->mg_private == 2) {
948         const U16 *const screamnext = (const U16 *const) screamnext_raw;
949         while ((I32)pos < previous + start_shift) {
950             pos = screamnext[pos];
951             if (pos == (U16)~0)
952                 goto cant_find;
953         }
954     } else if (mg->mg_private == 4) {
955         const U32 *const screamnext = (const U32 *const) screamnext_raw;
956         while ((I32)pos < previous + start_shift) {
957             pos = screamnext[pos];
958             if (pos == (U32)~0)
959                 goto cant_find;
960         }
961     }
962     big -= previous;
963     while (1) {
964         if ((I32)pos >= stop_pos) break;
965         if (big[pos] == first) {
966             const unsigned char *s = little;
967             const unsigned char *x = big + pos + 1;
968             while (s < littleend) {
969                 if (*s != *x++)
970                     break;
971                 ++s;
972             }
973             if (s == littleend) {
974                 *old_posp = (I32)pos;
975                 if (!last) return (char *)(big+pos);
976                 found = TRUE;
977             }
978         }
979         if (mg->mg_private == 1) {
980             pos = ((const U8 *const)screamnext_raw)[pos];
981             if (pos == (U8)~0)
982                 break;
983         } else if (mg->mg_private == 2) {
984             pos = ((const U16 *const)screamnext_raw)[pos];
985             if (pos == (U16)~0)
986                 break;
987         } else if (mg->mg_private == 4) {
988             pos = ((const U32 *const)screamnext_raw)[pos];
989             if (pos == (U32)~0)
990                 break;
991         }
992     };
993     if (last && found)
994         return (char *)(big+(*old_posp));
995   check_tail:
996     if (!SvTAIL(littlestr) || (end_shift > 0))
997         return NULL;
998     /* Ignore the trailing "\n".  This code is not microoptimized */
999     big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
1000     stop_pos = littleend - little;      /* Actual littlestr len */
1001     if (stop_pos == 0)
1002         return (char*)big;
1003     big -= stop_pos;
1004     if (*big == first
1005         && ((stop_pos == 1) ||
1006             memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
1007         return (char*)big;
1008     return NULL;
1009 }
1010
1011 /*
1012 =for apidoc foldEQ
1013
1014 Returns true if the leading len bytes of the strings s1 and s2 are the same
1015 case-insensitively; false otherwise.  Uppercase and lowercase ASCII range bytes
1016 match themselves and their opposite case counterparts.  Non-cased and non-ASCII
1017 range bytes match only themselves.
1018
1019 =cut
1020 */
1021
1022
1023 I32
1024 Perl_foldEQ(const char *s1, const char *s2, register I32 len)
1025 {
1026     register const U8 *a = (const U8 *)s1;
1027     register const U8 *b = (const U8 *)s2;
1028
1029     PERL_ARGS_ASSERT_FOLDEQ;
1030
1031     while (len--) {
1032         if (*a != *b && *a != PL_fold[*b])
1033             return 0;
1034         a++,b++;
1035     }
1036     return 1;
1037 }
1038 I32
1039 Perl_foldEQ_latin1(const char *s1, const char *s2, register I32 len)
1040 {
1041     /* Compare non-utf8 using Unicode (Latin1) semantics.  Does not work on
1042      * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
1043      * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these.  Nor
1044      * does it check that the strings each have at least 'len' characters */
1045
1046     register const U8 *a = (const U8 *)s1;
1047     register const U8 *b = (const U8 *)s2;
1048
1049     PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
1050
1051     while (len--) {
1052         if (*a != *b && *a != PL_fold_latin1[*b]) {
1053             return 0;
1054         }
1055         a++, b++;
1056     }
1057     return 1;
1058 }
1059
1060 /*
1061 =for apidoc foldEQ_locale
1062
1063 Returns true if the leading len bytes of the strings s1 and s2 are the same
1064 case-insensitively in the current locale; false otherwise.
1065
1066 =cut
1067 */
1068
1069 I32
1070 Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
1071 {
1072     dVAR;
1073     register const U8 *a = (const U8 *)s1;
1074     register const U8 *b = (const U8 *)s2;
1075
1076     PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
1077
1078     while (len--) {
1079         if (*a != *b && *a != PL_fold_locale[*b])
1080             return 0;
1081         a++,b++;
1082     }
1083     return 1;
1084 }
1085
1086 /* copy a string to a safe spot */
1087
1088 /*
1089 =head1 Memory Management
1090
1091 =for apidoc savepv
1092
1093 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1094 string which is a duplicate of C<pv>. The size of the string is
1095 determined by C<strlen()>. The memory allocated for the new string can
1096 be freed with the C<Safefree()> function.
1097
1098 =cut
1099 */
1100
1101 char *
1102 Perl_savepv(pTHX_ const char *pv)
1103 {
1104     PERL_UNUSED_CONTEXT;
1105     if (!pv)
1106         return NULL;
1107     else {
1108         char *newaddr;
1109         const STRLEN pvlen = strlen(pv)+1;
1110         Newx(newaddr, pvlen, char);
1111         return (char*)memcpy(newaddr, pv, pvlen);
1112     }
1113 }
1114
1115 /* same thing but with a known length */
1116
1117 /*
1118 =for apidoc savepvn
1119
1120 Perl's version of what C<strndup()> would be if it existed. Returns a
1121 pointer to a newly allocated string which is a duplicate of the first
1122 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
1123 the new string can be freed with the C<Safefree()> function.
1124
1125 =cut
1126 */
1127
1128 char *
1129 Perl_savepvn(pTHX_ const char *pv, register I32 len)
1130 {
1131     register char *newaddr;
1132     PERL_UNUSED_CONTEXT;
1133
1134     Newx(newaddr,len+1,char);
1135     /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1136     if (pv) {
1137         /* might not be null terminated */
1138         newaddr[len] = '\0';
1139         return (char *) CopyD(pv,newaddr,len,char);
1140     }
1141     else {
1142         return (char *) ZeroD(newaddr,len+1,char);
1143     }
1144 }
1145
1146 /*
1147 =for apidoc savesharedpv
1148
1149 A version of C<savepv()> which allocates the duplicate string in memory
1150 which is shared between threads.
1151
1152 =cut
1153 */
1154 char *
1155 Perl_savesharedpv(pTHX_ const char *pv)
1156 {
1157     register char *newaddr;
1158     STRLEN pvlen;
1159     if (!pv)
1160         return NULL;
1161
1162     pvlen = strlen(pv)+1;
1163     newaddr = (char*)PerlMemShared_malloc(pvlen);
1164     if (!newaddr) {
1165         return write_no_mem();
1166     }
1167     return (char*)memcpy(newaddr, pv, pvlen);
1168 }
1169
1170 /*
1171 =for apidoc savesharedpvn
1172
1173 A version of C<savepvn()> which allocates the duplicate string in memory
1174 which is shared between threads. (With the specific difference that a NULL
1175 pointer is not acceptable)
1176
1177 =cut
1178 */
1179 char *
1180 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1181 {
1182     char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1183
1184     PERL_ARGS_ASSERT_SAVESHAREDPVN;
1185
1186     if (!newaddr) {
1187         return write_no_mem();
1188     }
1189     newaddr[len] = '\0';
1190     return (char*)memcpy(newaddr, pv, len);
1191 }
1192
1193 /*
1194 =for apidoc savesvpv
1195
1196 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1197 the passed in SV using C<SvPV()>
1198
1199 =cut
1200 */
1201
1202 char *
1203 Perl_savesvpv(pTHX_ SV *sv)
1204 {
1205     STRLEN len;
1206     const char * const pv = SvPV_const(sv, len);
1207     register char *newaddr;
1208
1209     PERL_ARGS_ASSERT_SAVESVPV;
1210
1211     ++len;
1212     Newx(newaddr,len,char);
1213     return (char *) CopyD(pv,newaddr,len,char);
1214 }
1215
1216 /*
1217 =for apidoc savesharedsvpv
1218
1219 A version of C<savesharedpv()> which allocates the duplicate string in
1220 memory which is shared between threads.
1221
1222 =cut
1223 */
1224
1225 char *
1226 Perl_savesharedsvpv(pTHX_ SV *sv)
1227 {
1228     STRLEN len;
1229     const char * const pv = SvPV_const(sv, len);
1230
1231     PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1232
1233     return savesharedpvn(pv, len);
1234 }
1235
1236 /* the SV for Perl_form() and mess() is not kept in an arena */
1237
1238 STATIC SV *
1239 S_mess_alloc(pTHX)
1240 {
1241     dVAR;
1242     SV *sv;
1243     XPVMG *any;
1244
1245     if (PL_phase != PERL_PHASE_DESTRUCT)
1246         return newSVpvs_flags("", SVs_TEMP);
1247
1248     if (PL_mess_sv)
1249         return PL_mess_sv;
1250
1251     /* Create as PVMG now, to avoid any upgrading later */
1252     Newx(sv, 1, SV);
1253     Newxz(any, 1, XPVMG);
1254     SvFLAGS(sv) = SVt_PVMG;
1255     SvANY(sv) = (void*)any;
1256     SvPV_set(sv, NULL);
1257     SvREFCNT(sv) = 1 << 30; /* practically infinite */
1258     PL_mess_sv = sv;
1259     return sv;
1260 }
1261
1262 #if defined(PERL_IMPLICIT_CONTEXT)
1263 char *
1264 Perl_form_nocontext(const char* pat, ...)
1265 {
1266     dTHX;
1267     char *retval;
1268     va_list args;
1269     PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1270     va_start(args, pat);
1271     retval = vform(pat, &args);
1272     va_end(args);
1273     return retval;
1274 }
1275 #endif /* PERL_IMPLICIT_CONTEXT */
1276
1277 /*
1278 =head1 Miscellaneous Functions
1279 =for apidoc form
1280
1281 Takes a sprintf-style format pattern and conventional
1282 (non-SV) arguments and returns the formatted string.
1283
1284     (char *) Perl_form(pTHX_ const char* pat, ...)
1285
1286 can be used any place a string (char *) is required:
1287
1288     char * s = Perl_form("%d.%d",major,minor);
1289
1290 Uses a single private buffer so if you want to format several strings you
1291 must explicitly copy the earlier strings away (and free the copies when you
1292 are done).
1293
1294 =cut
1295 */
1296
1297 char *
1298 Perl_form(pTHX_ const char* pat, ...)
1299 {
1300     char *retval;
1301     va_list args;
1302     PERL_ARGS_ASSERT_FORM;
1303     va_start(args, pat);
1304     retval = vform(pat, &args);
1305     va_end(args);
1306     return retval;
1307 }
1308
1309 char *
1310 Perl_vform(pTHX_ const char *pat, va_list *args)
1311 {
1312     SV * const sv = mess_alloc();
1313     PERL_ARGS_ASSERT_VFORM;
1314     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1315     return SvPVX(sv);
1316 }
1317
1318 /*
1319 =for apidoc Am|SV *|mess|const char *pat|...
1320
1321 Take a sprintf-style format pattern and argument list.  These are used to
1322 generate a string message.  If the message does not end with a newline,
1323 then it will be extended with some indication of the current location
1324 in the code, as described for L</mess_sv>.
1325
1326 Normally, the resulting message is returned in a new mortal SV.
1327 During global destruction a single SV may be shared between uses of
1328 this function.
1329
1330 =cut
1331 */
1332
1333 #if defined(PERL_IMPLICIT_CONTEXT)
1334 SV *
1335 Perl_mess_nocontext(const char *pat, ...)
1336 {
1337     dTHX;
1338     SV *retval;
1339     va_list args;
1340     PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1341     va_start(args, pat);
1342     retval = vmess(pat, &args);
1343     va_end(args);
1344     return retval;
1345 }
1346 #endif /* PERL_IMPLICIT_CONTEXT */
1347
1348 SV *
1349 Perl_mess(pTHX_ const char *pat, ...)
1350 {
1351     SV *retval;
1352     va_list args;
1353     PERL_ARGS_ASSERT_MESS;
1354     va_start(args, pat);
1355     retval = vmess(pat, &args);
1356     va_end(args);
1357     return retval;
1358 }
1359
1360 STATIC const COP*
1361 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1362 {
1363     dVAR;
1364     /* Look for PL_op starting from o.  cop is the last COP we've seen. */
1365
1366     PERL_ARGS_ASSERT_CLOSEST_COP;
1367
1368     if (!o || o == PL_op)
1369         return cop;
1370
1371     if (o->op_flags & OPf_KIDS) {
1372         const OP *kid;
1373         for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1374             const COP *new_cop;
1375
1376             /* If the OP_NEXTSTATE has been optimised away we can still use it
1377              * the get the file and line number. */
1378
1379             if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1380                 cop = (const COP *)kid;
1381
1382             /* Keep searching, and return when we've found something. */
1383
1384             new_cop = closest_cop(cop, kid);
1385             if (new_cop)
1386                 return new_cop;
1387         }
1388     }
1389
1390     /* Nothing found. */
1391
1392     return NULL;
1393 }
1394
1395 /*
1396 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1397
1398 Expands a message, intended for the user, to include an indication of
1399 the current location in the code, if the message does not already appear
1400 to be complete.
1401
1402 C<basemsg> is the initial message or object.  If it is a reference, it
1403 will be used as-is and will be the result of this function.  Otherwise it
1404 is used as a string, and if it already ends with a newline, it is taken
1405 to be complete, and the result of this function will be the same string.
1406 If the message does not end with a newline, then a segment such as C<at
1407 foo.pl line 37> will be appended, and possibly other clauses indicating
1408 the current state of execution.  The resulting message will end with a
1409 dot and a newline.
1410
1411 Normally, the resulting message is returned in a new mortal SV.
1412 During global destruction a single SV may be shared between uses of this
1413 function.  If C<consume> is true, then the function is permitted (but not
1414 required) to modify and return C<basemsg> instead of allocating a new SV.
1415
1416 =cut
1417 */
1418
1419 SV *
1420 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1421 {
1422     dVAR;
1423     SV *sv;
1424
1425     PERL_ARGS_ASSERT_MESS_SV;
1426
1427     if (SvROK(basemsg)) {
1428         if (consume) {
1429             sv = basemsg;
1430         }
1431         else {
1432             sv = mess_alloc();
1433             sv_setsv(sv, basemsg);
1434         }
1435         return sv;
1436     }
1437
1438     if (SvPOK(basemsg) && consume) {
1439         sv = basemsg;
1440     }
1441     else {
1442         sv = mess_alloc();
1443         sv_copypv(sv, basemsg);
1444     }
1445
1446     if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1447         /*
1448          * Try and find the file and line for PL_op.  This will usually be
1449          * PL_curcop, but it might be a cop that has been optimised away.  We
1450          * can try to find such a cop by searching through the optree starting
1451          * from the sibling of PL_curcop.
1452          */
1453
1454         const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1455         if (!cop)
1456             cop = PL_curcop;
1457
1458         if (CopLINE(cop))
1459             Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1460             OutCopFILE(cop), (IV)CopLINE(cop));
1461         /* Seems that GvIO() can be untrustworthy during global destruction. */
1462         if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1463                 && IoLINES(GvIOp(PL_last_in_gv)))
1464         {
1465             const bool line_mode = (RsSIMPLE(PL_rs) &&
1466                               SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1467             Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1468                            SVfARG(PL_last_in_gv == PL_argvgv
1469                                  ? &PL_sv_no
1470                                  : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1471                            line_mode ? "line" : "chunk",
1472                            (IV)IoLINES(GvIOp(PL_last_in_gv)));
1473         }
1474         if (PL_phase == PERL_PHASE_DESTRUCT)
1475             sv_catpvs(sv, " during global destruction");
1476         sv_catpvs(sv, ".\n");
1477     }
1478     return sv;
1479 }
1480
1481 /*
1482 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1483
1484 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1485 argument list.  These are used to generate a string message.  If the
1486 message does not end with a newline, then it will be extended with
1487 some indication of the current location in the code, as described for
1488 L</mess_sv>.
1489
1490 Normally, the resulting message is returned in a new mortal SV.
1491 During global destruction a single SV may be shared between uses of
1492 this function.
1493
1494 =cut
1495 */
1496
1497 SV *
1498 Perl_vmess(pTHX_ const char *pat, va_list *args)
1499 {
1500     dVAR;
1501     SV * const sv = mess_alloc();
1502
1503     PERL_ARGS_ASSERT_VMESS;
1504
1505     sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1506     return mess_sv(sv, 1);
1507 }
1508
1509 void
1510 Perl_write_to_stderr(pTHX_ SV* msv)
1511 {
1512     dVAR;
1513     IO *io;
1514     MAGIC *mg;
1515
1516     PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1517
1518     if (PL_stderrgv && SvREFCNT(PL_stderrgv) 
1519         && (io = GvIO(PL_stderrgv))
1520         && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar))) 
1521         Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1522                             G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1523     else {
1524 #ifdef USE_SFIO
1525         /* SFIO can really mess with your errno */
1526         dSAVED_ERRNO;
1527 #endif
1528         PerlIO * const serr = Perl_error_log;
1529
1530         do_print(msv, serr);
1531         (void)PerlIO_flush(serr);
1532 #ifdef USE_SFIO
1533         RESTORE_ERRNO;
1534 #endif
1535     }
1536 }
1537
1538 /*
1539 =head1 Warning and Dieing
1540 */
1541
1542 /* Common code used in dieing and warning */
1543
1544 STATIC SV *
1545 S_with_queued_errors(pTHX_ SV *ex)
1546 {
1547     PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1548     if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1549         sv_catsv(PL_errors, ex);
1550         ex = sv_mortalcopy(PL_errors);
1551         SvCUR_set(PL_errors, 0);
1552     }
1553     return ex;
1554 }
1555
1556 STATIC bool
1557 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1558 {
1559     dVAR;
1560     HV *stash;
1561     GV *gv;
1562     CV *cv;
1563     SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1564     /* sv_2cv might call Perl_croak() or Perl_warner() */
1565     SV * const oldhook = *hook;
1566
1567     if (!oldhook)
1568         return FALSE;
1569
1570     ENTER;
1571     SAVESPTR(*hook);
1572     *hook = NULL;
1573     cv = sv_2cv(oldhook, &stash, &gv, 0);
1574     LEAVE;
1575     if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1576         dSP;
1577         SV *exarg;
1578
1579         ENTER;
1580         save_re_context();
1581         if (warn) {
1582             SAVESPTR(*hook);
1583             *hook = NULL;
1584         }
1585         exarg = newSVsv(ex);
1586         SvREADONLY_on(exarg);
1587         SAVEFREESV(exarg);
1588
1589         PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1590         PUSHMARK(SP);
1591         XPUSHs(exarg);
1592         PUTBACK;
1593         call_sv(MUTABLE_SV(cv), G_DISCARD);
1594         POPSTACK;
1595         LEAVE;
1596         return TRUE;
1597     }
1598     return FALSE;
1599 }
1600
1601 /*
1602 =for apidoc Am|OP *|die_sv|SV *baseex
1603
1604 Behaves the same as L</croak_sv>, except for the return type.
1605 It should be used only where the C<OP *> return type is required.
1606 The function never actually returns.
1607
1608 =cut
1609 */
1610
1611 OP *
1612 Perl_die_sv(pTHX_ SV *baseex)
1613 {
1614     PERL_ARGS_ASSERT_DIE_SV;
1615     croak_sv(baseex);
1616     /* NOTREACHED */
1617     return NULL;
1618 }
1619
1620 /*
1621 =for apidoc Am|OP *|die|const char *pat|...
1622
1623 Behaves the same as L</croak>, except for the return type.
1624 It should be used only where the C<OP *> return type is required.
1625 The function never actually returns.
1626
1627 =cut
1628 */
1629
1630 #if defined(PERL_IMPLICIT_CONTEXT)
1631 OP *
1632 Perl_die_nocontext(const char* pat, ...)
1633 {
1634     dTHX;
1635     va_list args;
1636     va_start(args, pat);
1637     vcroak(pat, &args);
1638     /* NOTREACHED */
1639     va_end(args);
1640     return NULL;
1641 }
1642 #endif /* PERL_IMPLICIT_CONTEXT */
1643
1644 OP *
1645 Perl_die(pTHX_ const char* pat, ...)
1646 {
1647     va_list args;
1648     va_start(args, pat);
1649     vcroak(pat, &args);
1650     /* NOTREACHED */
1651     va_end(args);
1652     return NULL;
1653 }
1654
1655 /*
1656 =for apidoc Am|void|croak_sv|SV *baseex
1657
1658 This is an XS interface to Perl's C<die> function.
1659
1660 C<baseex> is the error message or object.  If it is a reference, it
1661 will be used as-is.  Otherwise it is used as a string, and if it does
1662 not end with a newline then it will be extended with some indication of
1663 the current location in the code, as described for L</mess_sv>.
1664
1665 The error message or object will be used as an exception, by default
1666 returning control to the nearest enclosing C<eval>, but subject to
1667 modification by a C<$SIG{__DIE__}> handler.  In any case, the C<croak_sv>
1668 function never returns normally.
1669
1670 To die with a simple string message, the L</croak> function may be
1671 more convenient.
1672
1673 =cut
1674 */
1675
1676 void
1677 Perl_croak_sv(pTHX_ SV *baseex)
1678 {
1679     SV *ex = with_queued_errors(mess_sv(baseex, 0));
1680     PERL_ARGS_ASSERT_CROAK_SV;
1681     invoke_exception_hook(ex, FALSE);
1682     die_unwind(ex);
1683 }
1684
1685 /*
1686 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1687
1688 This is an XS interface to Perl's C<die> function.
1689
1690 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1691 argument list.  These are used to generate a string message.  If the
1692 message does not end with a newline, then it will be extended with
1693 some indication of the current location in the code, as described for
1694 L</mess_sv>.
1695
1696 The error message will be used as an exception, by default
1697 returning control to the nearest enclosing C<eval>, but subject to
1698 modification by a C<$SIG{__DIE__}> handler.  In any case, the C<croak>
1699 function never returns normally.
1700
1701 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1702 (C<$@>) will be used as an error message or object instead of building an
1703 error message from arguments.  If you want to throw a non-string object,
1704 or build an error message in an SV yourself, it is preferable to use
1705 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1706
1707 =cut
1708 */
1709
1710 void
1711 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1712 {
1713     SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1714     invoke_exception_hook(ex, FALSE);
1715     die_unwind(ex);
1716 }
1717
1718 /*
1719 =for apidoc Am|void|croak|const char *pat|...
1720
1721 This is an XS interface to Perl's C<die> function.
1722
1723 Take a sprintf-style format pattern and argument list.  These are used to
1724 generate a string message.  If the message does not end with a newline,
1725 then it will be extended with some indication of the current location
1726 in the code, as described for L</mess_sv>.
1727
1728 The error message will be used as an exception, by default
1729 returning control to the nearest enclosing C<eval>, but subject to
1730 modification by a C<$SIG{__DIE__}> handler.  In any case, the C<croak>
1731 function never returns normally.
1732
1733 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1734 (C<$@>) will be used as an error message or object instead of building an
1735 error message from arguments.  If you want to throw a non-string object,
1736 or build an error message in an SV yourself, it is preferable to use
1737 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1738
1739 =cut
1740 */
1741
1742 #if defined(PERL_IMPLICIT_CONTEXT)
1743 void
1744 Perl_croak_nocontext(const char *pat, ...)
1745 {
1746     dTHX;
1747     va_list args;
1748     va_start(args, pat);
1749     vcroak(pat, &args);
1750     /* NOTREACHED */
1751     va_end(args);
1752 }
1753 #endif /* PERL_IMPLICIT_CONTEXT */
1754
1755 void
1756 Perl_croak(pTHX_ const char *pat, ...)
1757 {
1758     va_list args;
1759     va_start(args, pat);
1760     vcroak(pat, &args);
1761     /* NOTREACHED */
1762     va_end(args);
1763 }
1764
1765 /*
1766 =for apidoc Am|void|croak_no_modify
1767
1768 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1769 terser object code than using C<Perl_croak>. Less code used on exception code
1770 paths reduces CPU cache pressure.
1771
1772 =cut
1773 */
1774
1775 void
1776 Perl_croak_no_modify(pTHX)
1777 {
1778     Perl_croak(aTHX_ "%s", PL_no_modify);
1779 }
1780
1781 /*
1782 =for apidoc Am|void|warn_sv|SV *baseex
1783
1784 This is an XS interface to Perl's C<warn> function.
1785
1786 C<baseex> is the error message or object.  If it is a reference, it
1787 will be used as-is.  Otherwise it is used as a string, and if it does
1788 not end with a newline then it will be extended with some indication of
1789 the current location in the code, as described for L</mess_sv>.
1790
1791 The error message or object will by default be written to standard error,
1792 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1793
1794 To warn with a simple string message, the L</warn> function may be
1795 more convenient.
1796
1797 =cut
1798 */
1799
1800 void
1801 Perl_warn_sv(pTHX_ SV *baseex)
1802 {
1803     SV *ex = mess_sv(baseex, 0);
1804     PERL_ARGS_ASSERT_WARN_SV;
1805     if (!invoke_exception_hook(ex, TRUE))
1806         write_to_stderr(ex);
1807 }
1808
1809 /*
1810 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1811
1812 This is an XS interface to Perl's C<warn> function.
1813
1814 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1815 argument list.  These are used to generate a string message.  If the
1816 message does not end with a newline, then it will be extended with
1817 some indication of the current location in the code, as described for
1818 L</mess_sv>.
1819
1820 The error message or object will by default be written to standard error,
1821 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1822
1823 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1824
1825 =cut
1826 */
1827
1828 void
1829 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1830 {
1831     SV *ex = vmess(pat, args);
1832     PERL_ARGS_ASSERT_VWARN;
1833     if (!invoke_exception_hook(ex, TRUE))
1834         write_to_stderr(ex);
1835 }
1836
1837 /*
1838 =for apidoc Am|void|warn|const char *pat|...
1839
1840 This is an XS interface to Perl's C<warn> function.
1841
1842 Take a sprintf-style format pattern and argument list.  These are used to
1843 generate a string message.  If the message does not end with a newline,
1844 then it will be extended with some indication of the current location
1845 in the code, as described for L</mess_sv>.
1846
1847 The error message or object will by default be written to standard error,
1848 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1849
1850 Unlike with L</croak>, C<pat> is not permitted to be null.
1851
1852 =cut
1853 */
1854
1855 #if defined(PERL_IMPLICIT_CONTEXT)
1856 void
1857 Perl_warn_nocontext(const char *pat, ...)
1858 {
1859     dTHX;
1860     va_list args;
1861     PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1862     va_start(args, pat);
1863     vwarn(pat, &args);
1864     va_end(args);
1865 }
1866 #endif /* PERL_IMPLICIT_CONTEXT */
1867
1868 void
1869 Perl_warn(pTHX_ const char *pat, ...)
1870 {
1871     va_list args;
1872     PERL_ARGS_ASSERT_WARN;
1873     va_start(args, pat);
1874     vwarn(pat, &args);
1875     va_end(args);
1876 }
1877
1878 #if defined(PERL_IMPLICIT_CONTEXT)
1879 void
1880 Perl_warner_nocontext(U32 err, const char *pat, ...)
1881 {
1882     dTHX; 
1883     va_list args;
1884     PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1885     va_start(args, pat);
1886     vwarner(err, pat, &args);
1887     va_end(args);
1888 }
1889 #endif /* PERL_IMPLICIT_CONTEXT */
1890
1891 void
1892 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1893 {
1894     PERL_ARGS_ASSERT_CK_WARNER_D;
1895
1896     if (Perl_ckwarn_d(aTHX_ err)) {
1897         va_list args;
1898         va_start(args, pat);
1899         vwarner(err, pat, &args);
1900         va_end(args);
1901     }
1902 }
1903
1904 void
1905 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1906 {
1907     PERL_ARGS_ASSERT_CK_WARNER;
1908
1909     if (Perl_ckwarn(aTHX_ err)) {
1910         va_list args;
1911         va_start(args, pat);
1912         vwarner(err, pat, &args);
1913         va_end(args);
1914     }
1915 }
1916
1917 void
1918 Perl_warner(pTHX_ U32  err, const char* pat,...)
1919 {
1920     va_list args;
1921     PERL_ARGS_ASSERT_WARNER;
1922     va_start(args, pat);
1923     vwarner(err, pat, &args);
1924     va_end(args);
1925 }
1926
1927 void
1928 Perl_vwarner(pTHX_ U32  err, const char* pat, va_list* args)
1929 {
1930     dVAR;
1931     PERL_ARGS_ASSERT_VWARNER;
1932     if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1933         SV * const msv = vmess(pat, args);
1934
1935         invoke_exception_hook(msv, FALSE);
1936         die_unwind(msv);
1937     }
1938     else {
1939         Perl_vwarn(aTHX_ pat, args);
1940     }
1941 }
1942
1943 /* implements the ckWARN? macros */
1944
1945 bool
1946 Perl_ckwarn(pTHX_ U32 w)
1947 {
1948     dVAR;
1949     /* If lexical warnings have not been set, use $^W.  */
1950     if (isLEXWARN_off)
1951         return PL_dowarn & G_WARN_ON;
1952
1953     return ckwarn_common(w);
1954 }
1955
1956 /* implements the ckWARN?_d macro */
1957
1958 bool
1959 Perl_ckwarn_d(pTHX_ U32 w)
1960 {
1961     dVAR;
1962     /* If lexical warnings have not been set then default classes warn.  */
1963     if (isLEXWARN_off)
1964         return TRUE;
1965
1966     return ckwarn_common(w);
1967 }
1968
1969 static bool
1970 S_ckwarn_common(pTHX_ U32 w)
1971 {
1972     if (PL_curcop->cop_warnings == pWARN_ALL)
1973         return TRUE;
1974
1975     if (PL_curcop->cop_warnings == pWARN_NONE)
1976         return FALSE;
1977
1978     /* Check the assumption that at least the first slot is non-zero.  */
1979     assert(unpackWARN1(w));
1980
1981     /* Check the assumption that it is valid to stop as soon as a zero slot is
1982        seen.  */
1983     if (!unpackWARN2(w)) {
1984         assert(!unpackWARN3(w));
1985         assert(!unpackWARN4(w));
1986     } else if (!unpackWARN3(w)) {
1987         assert(!unpackWARN4(w));
1988     }
1989         
1990     /* Right, dealt with all the special cases, which are implemented as non-
1991        pointers, so there is a pointer to a real warnings mask.  */
1992     do {
1993         if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1994             return TRUE;
1995     } while (w >>= WARNshift);
1996
1997     return FALSE;
1998 }
1999
2000 /* Set buffer=NULL to get a new one.  */
2001 STRLEN *
2002 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
2003                            STRLEN size) {
2004     const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
2005     PERL_UNUSED_CONTEXT;
2006     PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
2007
2008     buffer = (STRLEN*)
2009         (specialWARN(buffer) ?
2010          PerlMemShared_malloc(len_wanted) :
2011          PerlMemShared_realloc(buffer, len_wanted));
2012     buffer[0] = size;
2013     Copy(bits, (buffer + 1), size, char);
2014     return buffer;
2015 }
2016
2017 /* since we've already done strlen() for both nam and val
2018  * we can use that info to make things faster than
2019  * sprintf(s, "%s=%s", nam, val)
2020  */
2021 #define my_setenv_format(s, nam, nlen, val, vlen) \
2022    Copy(nam, s, nlen, char); \
2023    *(s+nlen) = '='; \
2024    Copy(val, s+(nlen+1), vlen, char); \
2025    *(s+(nlen+1+vlen)) = '\0'
2026
2027 #ifdef USE_ENVIRON_ARRAY
2028        /* VMS' my_setenv() is in vms.c */
2029 #if !defined(WIN32) && !defined(NETWARE)
2030 void
2031 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2032 {
2033   dVAR;
2034 #ifdef USE_ITHREADS
2035   /* only parent thread can modify process environment */
2036   if (PL_curinterp == aTHX)
2037 #endif
2038   {
2039 #ifndef PERL_USE_SAFE_PUTENV
2040     if (!PL_use_safe_putenv) {
2041     /* most putenv()s leak, so we manipulate environ directly */
2042     register I32 i;
2043     register const I32 len = strlen(nam);
2044     int nlen, vlen;
2045
2046     /* where does it go? */
2047     for (i = 0; environ[i]; i++) {
2048         if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
2049             break;
2050     }
2051
2052     if (environ == PL_origenviron) {   /* need we copy environment? */
2053        I32 j;
2054        I32 max;
2055        char **tmpenv;
2056
2057        max = i;
2058        while (environ[max])
2059            max++;
2060        tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2061        for (j=0; j<max; j++) {         /* copy environment */
2062            const int len = strlen(environ[j]);
2063            tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2064            Copy(environ[j], tmpenv[j], len+1, char);
2065        }
2066        tmpenv[max] = NULL;
2067        environ = tmpenv;               /* tell exec where it is now */
2068     }
2069     if (!val) {
2070        safesysfree(environ[i]);
2071        while (environ[i]) {
2072            environ[i] = environ[i+1];
2073            i++;
2074         }
2075        return;
2076     }
2077     if (!environ[i]) {                 /* does not exist yet */
2078        environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2079        environ[i+1] = NULL;    /* make sure it's null terminated */
2080     }
2081     else
2082        safesysfree(environ[i]);
2083        nlen = strlen(nam);
2084        vlen = strlen(val);
2085
2086        environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2087        /* all that work just for this */
2088        my_setenv_format(environ[i], nam, nlen, val, vlen);
2089     } else {
2090 # endif
2091 #   if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
2092 #       if defined(HAS_UNSETENV)
2093         if (val == NULL) {
2094             (void)unsetenv(nam);
2095         } else {
2096             (void)setenv(nam, val, 1);
2097         }
2098 #       else /* ! HAS_UNSETENV */
2099         (void)setenv(nam, val, 1);
2100 #       endif /* HAS_UNSETENV */
2101 #   else
2102 #       if defined(HAS_UNSETENV)
2103         if (val == NULL) {
2104             (void)unsetenv(nam);
2105         } else {
2106             const int nlen = strlen(nam);
2107             const int vlen = strlen(val);
2108             char * const new_env =
2109                 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2110             my_setenv_format(new_env, nam, nlen, val, vlen);
2111             (void)putenv(new_env);
2112         }
2113 #       else /* ! HAS_UNSETENV */
2114         char *new_env;
2115         const int nlen = strlen(nam);
2116         int vlen;
2117         if (!val) {
2118            val = "";
2119         }
2120         vlen = strlen(val);
2121         new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2122         /* all that work just for this */
2123         my_setenv_format(new_env, nam, nlen, val, vlen);
2124         (void)putenv(new_env);
2125 #       endif /* HAS_UNSETENV */
2126 #   endif /* __CYGWIN__ */
2127 #ifndef PERL_USE_SAFE_PUTENV
2128     }
2129 #endif
2130   }
2131 }
2132
2133 #else /* WIN32 || NETWARE */
2134
2135 void
2136 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2137 {
2138     dVAR;
2139     register char *envstr;
2140     const int nlen = strlen(nam);
2141     int vlen;
2142
2143     if (!val) {
2144        val = "";
2145     }
2146     vlen = strlen(val);
2147     Newx(envstr, nlen+vlen+2, char);
2148     my_setenv_format(envstr, nam, nlen, val, vlen);
2149     (void)PerlEnv_putenv(envstr);
2150     Safefree(envstr);
2151 }
2152
2153 #endif /* WIN32 || NETWARE */
2154
2155 #endif /* !VMS && !EPOC*/
2156
2157 #ifdef UNLINK_ALL_VERSIONS
2158 I32
2159 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2160 {
2161     I32 retries = 0;
2162
2163     PERL_ARGS_ASSERT_UNLNK;
2164
2165     while (PerlLIO_unlink(f) >= 0)
2166         retries++;
2167     return retries ? 0 : -1;
2168 }
2169 #endif
2170
2171 /* this is a drop-in replacement for bcopy() */
2172 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2173 char *
2174 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2175 {
2176     char * const retval = to;
2177
2178     PERL_ARGS_ASSERT_MY_BCOPY;
2179
2180     if (from - to >= 0) {
2181         while (len--)
2182             *to++ = *from++;
2183     }
2184     else {
2185         to += len;
2186         from += len;
2187         while (len--)
2188             *(--to) = *(--from);
2189     }
2190     return retval;
2191 }
2192 #endif
2193
2194 /* this is a drop-in replacement for memset() */
2195 #ifndef HAS_MEMSET
2196 void *
2197 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2198 {
2199     char * const retval = loc;
2200
2201     PERL_ARGS_ASSERT_MY_MEMSET;
2202
2203     while (len--)
2204         *loc++ = ch;
2205     return retval;
2206 }
2207 #endif
2208
2209 /* this is a drop-in replacement for bzero() */
2210 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2211 char *
2212 Perl_my_bzero(register char *loc, register I32 len)
2213 {
2214     char * const retval = loc;
2215
2216     PERL_ARGS_ASSERT_MY_BZERO;
2217
2218     while (len--)
2219         *loc++ = 0;
2220     return retval;
2221 }
2222 #endif
2223
2224 /* this is a drop-in replacement for memcmp() */
2225 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2226 I32
2227 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2228 {
2229     register const U8 *a = (const U8 *)s1;
2230     register const U8 *b = (const U8 *)s2;
2231     register I32 tmp;
2232
2233     PERL_ARGS_ASSERT_MY_MEMCMP;
2234
2235     while (len--) {
2236         if ((tmp = *a++ - *b++))
2237             return tmp;
2238     }
2239     return 0;
2240 }
2241 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2242
2243 #ifndef HAS_VPRINTF
2244 /* This vsprintf replacement should generally never get used, since
2245    vsprintf was available in both System V and BSD 2.11.  (There may
2246    be some cross-compilation or embedded set-ups where it is needed,
2247    however.)
2248
2249    If you encounter a problem in this function, it's probably a symptom
2250    that Configure failed to detect your system's vprintf() function.
2251    See the section on "item vsprintf" in the INSTALL file.
2252
2253    This version may compile on systems with BSD-ish <stdio.h>,
2254    but probably won't on others.
2255 */
2256
2257 #ifdef USE_CHAR_VSPRINTF
2258 char *
2259 #else
2260 int
2261 #endif
2262 vsprintf(char *dest, const char *pat, void *args)
2263 {
2264     FILE fakebuf;
2265
2266 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2267     FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2268     FILE_cnt(&fakebuf) = 32767;
2269 #else
2270     /* These probably won't compile -- If you really need
2271        this, you'll have to figure out some other method. */
2272     fakebuf._ptr = dest;
2273     fakebuf._cnt = 32767;
2274 #endif
2275 #ifndef _IOSTRG
2276 #define _IOSTRG 0
2277 #endif
2278     fakebuf._flag = _IOWRT|_IOSTRG;
2279     _doprnt(pat, args, &fakebuf);       /* what a kludge */
2280 #if defined(STDIO_PTR_LVALUE)
2281     *(FILE_ptr(&fakebuf)++) = '\0';
2282 #else
2283     /* PerlIO has probably #defined away fputc, but we want it here. */
2284 #  ifdef fputc
2285 #    undef fputc  /* XXX Should really restore it later */
2286 #  endif
2287     (void)fputc('\0', &fakebuf);
2288 #endif
2289 #ifdef USE_CHAR_VSPRINTF
2290     return(dest);
2291 #else
2292     return 0;           /* perl doesn't use return value */
2293 #endif
2294 }
2295
2296 #endif /* HAS_VPRINTF */
2297
2298 #ifdef MYSWAP
2299 #if BYTEORDER != 0x4321
2300 short
2301 Perl_my_swap(pTHX_ short s)
2302 {
2303 #if (BYTEORDER & 1) == 0
2304     short result;
2305
2306     result = ((s & 255) << 8) + ((s >> 8) & 255);
2307     return result;
2308 #else
2309     return s;
2310 #endif
2311 }
2312
2313 long
2314 Perl_my_htonl(pTHX_ long l)
2315 {
2316     union {
2317         long result;
2318         char c[sizeof(long)];
2319     } u;
2320
2321 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2322 #if BYTEORDER == 0x12345678
2323     u.result = 0; 
2324 #endif 
2325     u.c[0] = (l >> 24) & 255;
2326     u.c[1] = (l >> 16) & 255;
2327     u.c[2] = (l >> 8) & 255;
2328     u.c[3] = l & 255;
2329     return u.result;
2330 #else
2331 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2332     Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2333 #else
2334     register I32 o;
2335     register I32 s;
2336
2337     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2338         u.c[o & 0xf] = (l >> s) & 255;
2339     }
2340     return u.result;
2341 #endif
2342 #endif
2343 }
2344
2345 long
2346 Perl_my_ntohl(pTHX_ long l)
2347 {
2348     union {
2349         long l;
2350         char c[sizeof(long)];
2351     } u;
2352
2353 #if BYTEORDER == 0x1234
2354     u.c[0] = (l >> 24) & 255;
2355     u.c[1] = (l >> 16) & 255;
2356     u.c[2] = (l >> 8) & 255;
2357     u.c[3] = l & 255;
2358     return u.l;
2359 #else
2360 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2361     Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2362 #else
2363     register I32 o;
2364     register I32 s;
2365
2366     u.l = l;
2367     l = 0;
2368     for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2369         l |= (u.c[o & 0xf] & 255) << s;
2370     }
2371     return l;
2372 #endif
2373 #endif
2374 }
2375
2376 #endif /* BYTEORDER != 0x4321 */
2377 #endif /* MYSWAP */
2378
2379 /*
2380  * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2381  * If these functions are defined,
2382  * the BYTEORDER is neither 0x1234 nor 0x4321.
2383  * However, this is not assumed.
2384  * -DWS
2385  */
2386
2387 #define HTOLE(name,type)                                        \
2388         type                                                    \
2389         name (register type n)                                  \
2390         {                                                       \
2391             union {                                             \
2392                 type value;                                     \
2393                 char c[sizeof(type)];                           \
2394             } u;                                                \
2395             register U32 i;                                     \
2396             register U32 s = 0;                                 \
2397             for (i = 0; i < sizeof(u.c); i++, s += 8) {         \
2398                 u.c[i] = (n >> s) & 0xFF;                       \
2399             }                                                   \
2400             return u.value;                                     \
2401         }
2402
2403 #define LETOH(name,type)                                        \
2404         type                                                    \
2405         name (register type n)                                  \
2406         {                                                       \
2407             union {                                             \
2408                 type value;                                     \
2409                 char c[sizeof(type)];                           \
2410             } u;                                                \
2411             register U32 i;                                     \
2412             register U32 s = 0;                                 \
2413             u.value = n;                                        \
2414             n = 0;                                              \
2415             for (i = 0; i < sizeof(u.c); i++, s += 8) {         \
2416                 n |= ((type)(u.c[i] & 0xFF)) << s;              \
2417             }                                                   \
2418             return n;                                           \
2419         }
2420
2421 /*
2422  * Big-endian byte order functions.
2423  */
2424
2425 #define HTOBE(name,type)                                        \
2426         type                                                    \
2427         name (register type n)                                  \
2428         {                                                       \
2429             union {                                             \
2430                 type value;                                     \
2431                 char c[sizeof(type)];                           \
2432             } u;                                                \
2433             register U32 i;                                     \
2434             register U32 s = 8*(sizeof(u.c)-1);                 \
2435             for (i = 0; i < sizeof(u.c); i++, s -= 8) {         \
2436                 u.c[i] = (n >> s) & 0xFF;                       \
2437             }                                                   \
2438             return u.value;                                     \
2439         }
2440
2441 #define BETOH(name,type)                                        \
2442         type                                                    \
2443         name (register type n)                                  \
2444         {                                                       \
2445             union {                                             \
2446                 type value;                                     \
2447                 char c[sizeof(type)];                           \
2448             } u;                                                \
2449             register U32 i;                                     \
2450             register U32 s = 8*(sizeof(u.c)-1);                 \
2451             u.value = n;                                        \
2452             n = 0;                                              \
2453             for (i = 0; i < sizeof(u.c); i++, s -= 8) {         \
2454                 n |= ((type)(u.c[i] & 0xFF)) << s;              \
2455             }                                                   \
2456             return n;                                           \
2457         }
2458
2459 /*
2460  * If we just can't do it...
2461  */
2462
2463 #define NOT_AVAIL(name,type)                                    \
2464         type                                                    \
2465         name (register type n)                                  \
2466         {                                                       \
2467             Perl_croak_nocontext(#name "() not available");     \
2468             return n; /* not reached */                         \
2469         }
2470
2471
2472 #if defined(HAS_HTOVS) && !defined(htovs)
2473 HTOLE(htovs,short)
2474 #endif
2475 #if defined(HAS_HTOVL) && !defined(htovl)
2476 HTOLE(htovl,long)
2477 #endif
2478 #if defined(HAS_VTOHS) && !defined(vtohs)
2479 LETOH(vtohs,short)
2480 #endif
2481 #if defined(HAS_VTOHL) && !defined(vtohl)
2482 LETOH(vtohl,long)
2483 #endif
2484
2485 #ifdef PERL_NEED_MY_HTOLE16
2486 # if U16SIZE == 2
2487 HTOLE(Perl_my_htole16,U16)
2488 # else
2489 NOT_AVAIL(Perl_my_htole16,U16)
2490 # endif
2491 #endif
2492 #ifdef PERL_NEED_MY_LETOH16
2493 # if U16SIZE == 2
2494 LETOH(Perl_my_letoh16,U16)
2495 # else
2496 NOT_AVAIL(Perl_my_letoh16,U16)
2497 # endif
2498 #endif
2499 #ifdef PERL_NEED_MY_HTOBE16
2500 # if U16SIZE == 2
2501 HTOBE(Perl_my_htobe16,U16)
2502 # else
2503 NOT_AVAIL(Perl_my_htobe16,U16)
2504 # endif
2505 #endif
2506 #ifdef PERL_NEED_MY_BETOH16
2507 # if U16SIZE == 2
2508 BETOH(Perl_my_betoh16,U16)
2509 # else
2510 NOT_AVAIL(Perl_my_betoh16,U16)
2511 # endif
2512 #endif
2513
2514 #ifdef PERL_NEED_MY_HTOLE32
2515 # if U32SIZE == 4
2516 HTOLE(Perl_my_htole32,U32)
2517 # else
2518 NOT_AVAIL(Perl_my_htole32,U32)
2519 # endif
2520 #endif
2521 #ifdef PERL_NEED_MY_LETOH32
2522 # if U32SIZE == 4
2523 LETOH(Perl_my_letoh32,U32)
2524 # else
2525 NOT_AVAIL(Perl_my_letoh32,U32)
2526 # endif
2527 #endif
2528 #ifdef PERL_NEED_MY_HTOBE32
2529 # if U32SIZE == 4
2530 HTOBE(Perl_my_htobe32,U32)
2531 # else
2532 NOT_AVAIL(Perl_my_htobe32,U32)
2533 # endif
2534 #endif
2535 #ifdef PERL_NEED_MY_BETOH32
2536 # if U32SIZE == 4
2537 BETOH(Perl_my_betoh32,U32)
2538 # else
2539 NOT_AVAIL(Perl_my_betoh32,U32)
2540 # endif
2541 #endif
2542
2543 #ifdef PERL_NEED_MY_HTOLE64
2544 # if U64SIZE == 8
2545 HTOLE(Perl_my_htole64,U64)
2546 # else
2547 NOT_AVAIL(Perl_my_htole64,U64)
2548 # endif
2549 #endif
2550 #ifdef PERL_NEED_MY_LETOH64
2551 # if U64SIZE == 8
2552 LETOH(Perl_my_letoh64,U64)
2553 # else
2554 NOT_AVAIL(Perl_my_letoh64,U64)
2555 # endif
2556 #endif
2557 #ifdef PERL_NEED_MY_HTOBE64
2558 # if U64SIZE == 8
2559 HTOBE(Perl_my_htobe64,U64)
2560 # else
2561 NOT_AVAIL(Perl_my_htobe64,U64)
2562 # endif
2563 #endif
2564 #ifdef PERL_NEED_MY_BETOH64
2565 # if U64SIZE == 8
2566 BETOH(Perl_my_betoh64,U64)
2567 # else
2568 NOT_AVAIL(Perl_my_betoh64,U64)
2569 # endif
2570 #endif
2571
2572 #ifdef PERL_NEED_MY_HTOLES
2573 HTOLE(Perl_my_htoles,short)
2574 #endif
2575 #ifdef PERL_NEED_MY_LETOHS
2576 LETOH(Perl_my_letohs,short)
2577 #endif
2578 #ifdef PERL_NEED_MY_HTOBES
2579 HTOBE(Perl_my_htobes,short)
2580 #endif
2581 #ifdef PERL_NEED_MY_BETOHS
2582 BETOH(Perl_my_betohs,short)
2583 #endif
2584
2585 #ifdef PERL_NEED_MY_HTOLEI
2586 HTOLE(Perl_my_htolei,int)
2587 #endif
2588 #ifdef PERL_NEED_MY_LETOHI
2589 LETOH(Perl_my_letohi,int)
2590 #endif
2591 #ifdef PERL_NEED_MY_HTOBEI
2592 HTOBE(Perl_my_htobei,int)
2593 #endif
2594 #ifdef PERL_NEED_MY_BETOHI
2595 BETOH(Perl_my_betohi,int)
2596 #endif
2597
2598 #ifdef PERL_NEED_MY_HTOLEL
2599 HTOLE(Perl_my_htolel,long)
2600 #endif
2601 #ifdef PERL_NEED_MY_LETOHL
2602 LETOH(Perl_my_letohl,long)
2603 #endif
2604 #ifdef PERL_NEED_MY_HTOBEL
2605 HTOBE(Perl_my_htobel,long)
2606 #endif
2607 #ifdef PERL_NEED_MY_BETOHL
2608 BETOH(Perl_my_betohl,long)
2609 #endif
2610
2611 void
2612 Perl_my_swabn(void *ptr, int n)
2613 {
2614     register char *s = (char *)ptr;
2615     register char *e = s + (n-1);
2616     register char tc;
2617
2618     PERL_ARGS_ASSERT_MY_SWABN;
2619
2620     for (n /= 2; n > 0; s++, e--, n--) {
2621       tc = *s;
2622       *s = *e;
2623       *e = tc;
2624     }
2625 }
2626
2627 PerlIO *
2628 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2629 {
2630 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2631     dVAR;
2632     int p[2];
2633     register I32 This, that;
2634     register Pid_t pid;
2635     SV *sv;
2636     I32 did_pipes = 0;
2637     int pp[2];
2638
2639     PERL_ARGS_ASSERT_MY_POPEN_LIST;
2640
2641     PERL_FLUSHALL_FOR_CHILD;
2642     This = (*mode == 'w');
2643     that = !This;
2644     if (PL_tainting) {
2645         taint_env();
2646         taint_proper("Insecure %s%s", "EXEC");
2647     }
2648     if (PerlProc_pipe(p) < 0)
2649         return NULL;
2650     /* Try for another pipe pair for error return */
2651     if (PerlProc_pipe(pp) >= 0)
2652         did_pipes = 1;
2653     while ((pid = PerlProc_fork()) < 0) {
2654         if (errno != EAGAIN) {
2655             PerlLIO_close(p[This]);
2656             PerlLIO_close(p[that]);
2657             if (did_pipes) {
2658                 PerlLIO_close(pp[0]);
2659                 PerlLIO_close(pp[1]);
2660             }
2661             return NULL;
2662         }
2663         Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2664         sleep(5);
2665     }
2666     if (pid == 0) {
2667         /* Child */
2668 #undef THIS
2669 #undef THAT
2670 #define THIS that
2671 #define THAT This
2672         /* Close parent's end of error status pipe (if any) */
2673         if (did_pipes) {
2674             PerlLIO_close(pp[0]);
2675 #if defined(HAS_FCNTL) && defined(F_SETFD)
2676             /* Close error pipe automatically if exec works */
2677             fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2678 #endif
2679         }
2680         /* Now dup our end of _the_ pipe to right position */
2681         if (p[THIS] != (*mode == 'r')) {
2682             PerlLIO_dup2(p[THIS], *mode == 'r');
2683             PerlLIO_close(p[THIS]);
2684             if (p[THAT] != (*mode == 'r'))      /* if dup2() didn't close it */
2685                 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2686         }
2687         else
2688             PerlLIO_close(p[THAT]);     /* close parent's end of _the_ pipe */
2689 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2690         /* No automatic close - do it by hand */
2691 #  ifndef NOFILE
2692 #  define NOFILE 20
2693 #  endif
2694         {
2695             int fd;
2696
2697             for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2698                 if (fd != pp[1])
2699                     PerlLIO_close(fd);
2700             }
2701         }
2702 #endif
2703         do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2704         PerlProc__exit(1);
2705 #undef THIS
2706 #undef THAT
2707     }
2708     /* Parent */
2709     do_execfree();      /* free any memory malloced by child on fork */
2710     if (did_pipes)
2711         PerlLIO_close(pp[1]);
2712     /* Keep the lower of the two fd numbers */
2713     if (p[that] < p[This]) {
2714         PerlLIO_dup2(p[This], p[that]);
2715         PerlLIO_close(p[This]);
2716         p[This] = p[that];
2717     }
2718     else
2719         PerlLIO_close(p[that]);         /* close child's end of pipe */
2720
2721     sv = *av_fetch(PL_fdpid,p[This],TRUE);
2722     SvUPGRADE(sv,SVt_IV);
2723     SvIV_set(sv, pid);
2724     PL_forkprocess = pid;
2725     /* If we managed to get status pipe check for exec fail */
2726     if (did_pipes && pid > 0) {
2727         int errkid;
2728         unsigned n = 0;
2729         SSize_t n1;
2730
2731         while (n < sizeof(int)) {
2732             n1 = PerlLIO_read(pp[0],
2733                               (void*)(((char*)&errkid)+n),
2734                               (sizeof(int)) - n);
2735             if (n1 <= 0)
2736                 break;
2737             n += n1;
2738         }
2739         PerlLIO_close(pp[0]);
2740         did_pipes = 0;
2741         if (n) {                        /* Error */
2742             int pid2, status;
2743             PerlLIO_close(p[This]);
2744             if (n != sizeof(int))
2745                 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2746             do {
2747                 pid2 = wait4pid(pid, &status, 0);
2748             } while (pid2 == -1 && errno == EINTR);
2749             errno = errkid;             /* Propagate errno from kid */
2750             return NULL;
2751         }
2752     }
2753     if (did_pipes)
2754          PerlLIO_close(pp[0]);
2755     return PerlIO_fdopen(p[This], mode);
2756 #else
2757 #  ifdef OS2    /* Same, without fork()ing and all extra overhead... */
2758     return my_syspopen4(aTHX_ NULL, mode, n, args);
2759 #  else
2760     Perl_croak(aTHX_ "List form of piped open not implemented");
2761     return (PerlIO *) NULL;
2762 #  endif
2763 #endif
2764 }
2765
2766     /* VMS' my_popen() is in VMS.c, same with OS/2. */
2767 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
2768 PerlIO *
2769 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2770 {
2771     dVAR;
2772     int p[2];
2773     register I32 This, that;
2774     register Pid_t pid;
2775     SV *sv;
2776     const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2777     I32 did_pipes = 0;
2778     int pp[2];
2779
2780     PERL_ARGS_ASSERT_MY_POPEN;
2781
2782     PERL_FLUSHALL_FOR_CHILD;
2783 #ifdef OS2
2784     if (doexec) {
2785         return my_syspopen(aTHX_ cmd,mode);
2786     }
2787 #endif
2788     This = (*mode == 'w');
2789     that = !This;
2790     if (doexec && PL_tainting) {
2791         taint_env();
2792         taint_proper("Insecure %s%s", "EXEC");
2793     }
2794     if (PerlProc_pipe(p) < 0)
2795         return NULL;
2796     if (doexec && PerlProc_pipe(pp) >= 0)
2797         did_pipes = 1;
2798     while ((pid = PerlProc_fork()) < 0) {
2799         if (errno != EAGAIN) {
2800             PerlLIO_close(p[This]);
2801             PerlLIO_close(p[that]);
2802             if (did_pipes) {
2803                 PerlLIO_close(pp[0]);
2804                 PerlLIO_close(pp[1]);
2805             }
2806             if (!doexec)
2807                 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2808             return NULL;
2809         }
2810         Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2811         sleep(5);
2812     }
2813     if (pid == 0) {
2814
2815 #undef THIS
2816 #undef THAT
2817 #define THIS that
2818 #define THAT This
2819         if (did_pipes) {
2820             PerlLIO_close(pp[0]);
2821 #if defined(HAS_FCNTL) && defined(F_SETFD)
2822             fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2823 #endif
2824         }
2825         if (p[THIS] != (*mode == 'r')) {
2826             PerlLIO_dup2(p[THIS], *mode == 'r');
2827             PerlLIO_close(p[THIS]);
2828             if (p[THAT] != (*mode == 'r'))      /* if dup2() didn't close it */
2829                 PerlLIO_close(p[THAT]);
2830         }
2831         else
2832             PerlLIO_close(p[THAT]);
2833 #ifndef OS2
2834         if (doexec) {
2835 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2836 #ifndef NOFILE
2837 #define NOFILE 20
2838 #endif
2839             {
2840                 int fd;
2841
2842                 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2843                     if (fd != pp[1])
2844                         PerlLIO_close(fd);
2845             }
2846 #endif
2847             /* may or may not use the shell */
2848             do_exec3(cmd, pp[1], did_pipes);
2849             PerlProc__exit(1);
2850         }
2851 #endif  /* defined OS2 */
2852
2853 #ifdef PERLIO_USING_CRLF
2854    /* Since we circumvent IO layers when we manipulate low-level
2855       filedescriptors directly, need to manually switch to the
2856       default, binary, low-level mode; see PerlIOBuf_open(). */
2857    PerlLIO_setmode((*mode == 'r'), O_BINARY);
2858 #endif 
2859 #ifdef THREADS_HAVE_PIDS
2860         PL_ppid = (IV)getppid();
2861 #endif
2862         PL_forkprocess = 0;
2863 #ifdef PERL_USES_PL_PIDSTATUS
2864         hv_clear(PL_pidstatus); /* we have no children */
2865 #endif
2866         return NULL;
2867 #undef THIS
2868 #undef THAT
2869     }
2870     do_execfree();      /* free any memory malloced by child on vfork */
2871     if (did_pipes)
2872         PerlLIO_close(pp[1]);
2873     if (p[that] < p[This]) {
2874         PerlLIO_dup2(p[This], p[that]);
2875         PerlLIO_close(p[This]);
2876         p[This] = p[that];
2877     }
2878     else
2879         PerlLIO_close(p[that]);
2880
2881     sv = *av_fetch(PL_fdpid,p[This],TRUE);
2882     SvUPGRADE(sv,SVt_IV);
2883     SvIV_set(sv, pid);
2884     PL_forkprocess = pid;
2885     if (did_pipes && pid > 0) {
2886         int errkid;
2887         unsigned n = 0;
2888         SSize_t n1;
2889
2890         while (n < sizeof(int)) {
2891             n1 = PerlLIO_read(pp[0],
2892                               (void*)(((char*)&errkid)+n),
2893                               (sizeof(int)) - n);
2894             if (n1 <= 0)
2895                 break;
2896             n += n1;
2897         }
2898         PerlLIO_close(pp[0]);
2899         did_pipes = 0;
2900         if (n) {                        /* Error */
2901             int pid2, status;
2902             PerlLIO_close(p[This]);
2903             if (n != sizeof(int))
2904                 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2905             do {
2906                 pid2 = wait4pid(pid, &status, 0);
2907             } while (pid2 == -1 && errno == EINTR);
2908             errno = errkid;             /* Propagate errno from kid */
2909             return NULL;
2910         }
2911     }
2912     if (did_pipes)
2913          PerlLIO_close(pp[0]);
2914     return PerlIO_fdopen(p[This], mode);
2915 }
2916 #else
2917 #if defined(atarist) || defined(EPOC)
2918 FILE *popen();
2919 PerlIO *
2920 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2921 {
2922     PERL_ARGS_ASSERT_MY_POPEN;
2923     PERL_FLUSHALL_FOR_CHILD;
2924     /* Call system's popen() to get a FILE *, then import it.
2925        used 0 for 2nd parameter to PerlIO_importFILE;
2926        apparently not used
2927     */
2928     return PerlIO_importFILE(popen(cmd, mode), 0);
2929 }
2930 #else
2931 #if defined(DJGPP)
2932 FILE *djgpp_popen();
2933 PerlIO *
2934 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2935 {
2936     PERL_FLUSHALL_FOR_CHILD;
2937     /* Call system's popen() to get a FILE *, then import it.
2938        used 0 for 2nd parameter to PerlIO_importFILE;
2939        apparently not used
2940     */
2941     return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2942 }
2943 #else
2944 #if defined(__LIBCATAMOUNT__)
2945 PerlIO *
2946 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2947 {
2948     return NULL;
2949 }
2950 #endif
2951 #endif
2952 #endif
2953
2954 #endif /* !DOSISH */
2955
2956 /* this is called in parent before the fork() */
2957 void
2958 Perl_atfork_lock(void)
2959 {
2960    dVAR;
2961 #if defined(USE_ITHREADS)
2962     /* locks must be held in locking order (if any) */
2963 #  ifdef MYMALLOC
2964     MUTEX_LOCK(&PL_malloc_mutex);
2965 #  endif
2966     OP_REFCNT_LOCK;
2967 #endif
2968 }
2969
2970 /* this is called in both parent and child after the fork() */
2971 void
2972 Perl_atfork_unlock(void)
2973 {
2974     dVAR;
2975 #if defined(USE_ITHREADS)
2976     /* locks must be released in same order as in atfork_lock() */
2977 #  ifdef MYMALLOC
2978     MUTEX_UNLOCK(&PL_malloc_mutex);
2979 #  endif
2980     OP_REFCNT_UNLOCK;
2981 #endif
2982 }
2983
2984 Pid_t
2985 Perl_my_fork(void)
2986 {
2987 #if defined(HAS_FORK)
2988     Pid_t pid;
2989 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2990     atfork_lock();
2991     pid = fork();
2992     atfork_unlock();
2993 #else
2994     /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2995      * handlers elsewhere in the code */
2996     pid = fork();
2997 #endif
2998     return pid;
2999 #else
3000     /* this "canna happen" since nothing should be calling here if !HAS_FORK */
3001     Perl_croak_nocontext("fork() not available");
3002     return 0;
3003 #endif /* HAS_FORK */
3004 }
3005
3006 #ifdef DUMP_FDS
3007 void
3008 Perl_dump_fds(pTHX_ const char *const s)
3009 {
3010     int fd;
3011     Stat_t tmpstatbuf;
3012
3013     PERL_ARGS_ASSERT_DUMP_FDS;
3014
3015     PerlIO_printf(Perl_debug_log,"%s", s);
3016     for (fd = 0; fd < 32; fd++) {
3017         if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
3018             PerlIO_printf(Perl_debug_log," %d",fd);
3019     }
3020     PerlIO_printf(Perl_debug_log,"\n");
3021     return;
3022 }
3023 #endif  /* DUMP_FDS */
3024
3025 #ifndef HAS_DUP2
3026 int
3027 dup2(int oldfd, int newfd)
3028 {
3029 #if defined(HAS_FCNTL) && defined(F_DUPFD)
3030     if (oldfd == newfd)
3031         return oldfd;
3032     PerlLIO_close(newfd);
3033     return fcntl(oldfd, F_DUPFD, newfd);
3034 #else
3035 #define DUP2_MAX_FDS 256
3036     int fdtmp[DUP2_MAX_FDS];
3037     I32 fdx = 0;
3038     int fd;
3039
3040     if (oldfd == newfd)
3041         return oldfd;
3042     PerlLIO_close(newfd);
3043     /* good enough for low fd's... */
3044     while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
3045         if (fdx >= DUP2_MAX_FDS) {
3046             PerlLIO_close(fd);
3047             fd = -1;
3048             break;
3049         }
3050         fdtmp[fdx++] = fd;
3051     }
3052     while (fdx > 0)
3053         PerlLIO_close(fdtmp[--fdx]);
3054     return fd;
3055 #endif
3056 }
3057 #endif
3058
3059 #ifndef PERL_MICRO
3060 #ifdef HAS_SIGACTION
3061
3062 Sighandler_t
3063 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3064 {
3065     dVAR;
3066     struct sigaction act, oact;
3067
3068 #ifdef USE_ITHREADS
3069     /* only "parent" interpreter can diddle signals */
3070     if (PL_curinterp != aTHX)
3071         return (Sighandler_t) SIG_ERR;
3072 #endif
3073
3074     act.sa_handler = (void(*)(int))handler;
3075     sigemptyset(&act.sa_mask);
3076     act.sa_flags = 0;
3077 #ifdef SA_RESTART
3078     if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3079         act.sa_flags |= SA_RESTART;     /* SVR4, 4.3+BSD */
3080 #endif
3081 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3082     if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3083         act.sa_flags |= SA_NOCLDWAIT;
3084 #endif
3085     if (sigaction(signo, &act, &oact) == -1)
3086         return (Sighandler_t) SIG_ERR;
3087     else
3088         return (Sighandler_t) oact.sa_handler;
3089 }
3090
3091 Sighandler_t
3092 Perl_rsignal_state(pTHX_ int signo)
3093 {
3094     struct sigaction oact;
3095     PERL_UNUSED_CONTEXT;
3096
3097     if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
3098         return (Sighandler_t) SIG_ERR;
3099     else
3100         return (Sighandler_t) oact.sa_handler;
3101 }
3102
3103 int
3104 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3105 {
3106     dVAR;
3107     struct sigaction act;
3108
3109     PERL_ARGS_ASSERT_RSIGNAL_SAVE;
3110
3111 #ifdef USE_ITHREADS
3112     /* only "parent" interpreter can diddle signals */
3113     if (PL_curinterp != aTHX)
3114         return -1;
3115 #endif
3116
3117     act.sa_handler = (void(*)(int))handler;
3118     sigemptyset(&act.sa_mask);
3119     act.sa_flags = 0;
3120 #ifdef SA_RESTART
3121     if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3122         act.sa_flags |= SA_RESTART;     /* SVR4, 4.3+BSD */
3123 #endif
3124 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3125     if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3126         act.sa_flags |= SA_NOCLDWAIT;
3127 #endif
3128     return sigaction(signo, &act, save);
3129 }
3130
3131 int
3132 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3133 {
3134     dVAR;
3135 #ifdef USE_ITHREADS
3136     /* only "parent" interpreter can diddle signals */
3137     if (PL_curinterp != aTHX)
3138         return -1;
3139 #endif
3140
3141     return sigaction(signo, save, (struct sigaction *)NULL);
3142 }
3143
3144 #else /* !HAS_SIGACTION */
3145
3146 Sighandler_t
3147 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3148 {
3149 #if defined(USE_ITHREADS) && !defined(WIN32)
3150     /* only "parent" interpreter can diddle signals */
3151     if (PL_curinterp != aTHX)
3152         return (Sighandler_t) SIG_ERR;
3153 #endif
3154
3155     return PerlProc_signal(signo, handler);
3156 }
3157
3158 static Signal_t
3159 sig_trap(int signo)
3160 {
3161     dVAR;
3162     PL_sig_trapped++;
3163 }
3164
3165 Sighandler_t
3166 Perl_rsignal_state(pTHX_ int signo)
3167 {
3168     dVAR;
3169     Sighandler_t oldsig;
3170
3171 #if defined(USE_ITHREADS) && !defined(WIN32)
3172     /* only "parent" interpreter can diddle signals */
3173     if (PL_curinterp != aTHX)
3174         return (Sighandler_t) SIG_ERR;
3175 #endif
3176
3177     PL_sig_trapped = 0;
3178     oldsig = PerlProc_signal(signo, sig_trap);
3179     PerlProc_signal(signo, oldsig);
3180     if (PL_sig_trapped)
3181         PerlProc_kill(PerlProc_getpid(), signo);
3182     return oldsig;
3183 }
3184
3185 int
3186 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3187 {
3188 #if defined(USE_ITHREADS) && !defined(WIN32)
3189     /* only "parent" interpreter can diddle signals */
3190     if (PL_curinterp != aTHX)
3191         return -1;
3192 #endif
3193     *save = PerlProc_signal(signo, handler);
3194     return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3195 }
3196
3197 int
3198 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3199 {
3200 #if defined(USE_ITHREADS) && !defined(WIN32)
3201     /* only "parent" interpreter can diddle signals */
3202     if (PL_curinterp != aTHX)
3203         return -1;
3204 #endif
3205     return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3206 }
3207
3208 #endif /* !HAS_SIGACTION */
3209 #endif /* !PERL_MICRO */
3210
3211     /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3212 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
3213 I32
3214 Perl_my_pclose(pTHX_ PerlIO *ptr)
3215 {
3216     dVAR;
3217     Sigsave_t hstat, istat, qstat;
3218     int status;
3219     SV **svp;
3220     Pid_t pid;
3221     Pid_t pid2 = 0;
3222     bool close_failed;
3223     dSAVEDERRNO;
3224     const int fd = PerlIO_fileno(ptr);
3225
3226 #ifdef USE_PERLIO
3227     /* Find out whether the refcount is low enough for us to wait for the
3228        child proc without blocking. */
3229     const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
3230 #else
3231     const bool should_wait = 1;
3232 #endif
3233
3234     svp = av_fetch(PL_fdpid,fd,TRUE);
3235     pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3236     SvREFCNT_dec(*svp);
3237     *svp = &PL_sv_undef;
3238 #ifdef OS2
3239     if (pid == -1) {                    /* Opened by popen. */
3240         return my_syspclose(ptr);
3241     }
3242 #endif
3243     close_failed = (PerlIO_close(ptr) == EOF);
3244     SAVE_ERRNO;
3245 #ifdef UTS
3246     if(PerlProc_kill(pid, 0) < 0) { return(pid); }   /* HOM 12/23/91 */
3247 #endif
3248 #ifndef PERL_MICRO
3249     rsignal_save(SIGHUP,  (Sighandler_t) SIG_IGN, &hstat);
3250     rsignal_save(SIGINT,  (Sighandler_t) SIG_IGN, &istat);
3251     rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3252 #endif
3253     if (should_wait) do {
3254         pid2 = wait4pid(pid, &status, 0);
3255     } while (pid2 == -1 && errno == EINTR);
3256 #ifndef PERL_MICRO
3257     rsignal_restore(SIGHUP, &hstat);
3258     rsignal_restore(SIGINT, &istat);
3259     rsignal_restore(SIGQUIT, &qstat);
3260 #endif
3261     if (close_failed) {
3262         RESTORE_ERRNO;
3263         return -1;
3264     }
3265     return(
3266       should_wait
3267        ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3268        : 0
3269     );
3270 }
3271 #else
3272 #if defined(__LIBCATAMOUNT__)
3273 I32
3274 Perl_my_pclose(pTHX_ PerlIO *ptr)
3275 {
3276     return -1;
3277 }
3278 #endif
3279 #endif /* !DOSISH */
3280
3281 #if  (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3282 I32
3283 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3284 {
3285     dVAR;
3286     I32 result = 0;
3287     PERL_ARGS_ASSERT_WAIT4PID;
3288     if (!pid)
3289         return -1;
3290 #ifdef PERL_USES_PL_PIDSTATUS
3291     {
3292         if (pid > 0) {
3293             /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3294                pid, rather than a string form.  */
3295             SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3296             if (svp && *svp != &PL_sv_undef) {
3297                 *statusp = SvIVX(*svp);
3298                 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3299                                 G_DISCARD);
3300                 return pid;
3301             }
3302         }
3303         else {
3304             HE *entry;
3305
3306             hv_iterinit(PL_pidstatus);
3307             if ((entry = hv_iternext(PL_pidstatus))) {
3308                 SV * const sv = hv_iterval(PL_pidstatus,entry);
3309                 I32 len;
3310                 const char * const spid = hv_iterkey(entry,&len);
3311
3312                 assert (len == sizeof(Pid_t));
3313                 memcpy((char *)&pid, spid, len);
3314                 *statusp = SvIVX(sv);
3315                 /* The hash iterator is currently on this entry, so simply
3316                    calling hv_delete would trigger the lazy delete, which on
3317                    aggregate does more work, beacuse next call to hv_iterinit()
3318                    would spot the flag, and have to call the delete routine,
3319                    while in the meantime any new entries can't re-use that
3320                    memory.  */
3321                 hv_iterinit(PL_pidstatus);
3322                 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3323                 return pid;
3324             }
3325         }
3326     }
3327 #endif
3328 #ifdef HAS_WAITPID
3329 #  ifdef HAS_WAITPID_RUNTIME
3330     if (!HAS_WAITPID_RUNTIME)
3331         goto hard_way;
3332 #  endif
3333     result = PerlProc_waitpid(pid,statusp,flags);
3334     goto finish;
3335 #endif
3336 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3337     result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3338     goto finish;
3339 #endif
3340 #ifdef PERL_USES_PL_PIDSTATUS
3341 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3342   hard_way:
3343 #endif
3344     {
3345         if (flags)
3346             Perl_croak(aTHX_ "Can't do waitpid with flags");
3347         else {
3348             while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3349                 pidgone(result,*statusp);
3350             if (result < 0)
3351                 *statusp = -1;
3352         }
3353     }
3354 #endif
3355 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3356   finish:
3357 #endif
3358     if (result < 0 && errno == EINTR) {
3359         PERL_ASYNC_CHECK();
3360         errno = EINTR; /* reset in case a signal handler changed $! */
3361     }
3362     return result;
3363 }
3364 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3365
3366 #ifdef PERL_USES_PL_PIDSTATUS
3367 void
3368 S_pidgone(pTHX_ Pid_t pid, int status)
3369 {
3370     register SV *sv;
3371
3372     sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3373     SvUPGRADE(sv,SVt_IV);
3374     SvIV_set(sv, status);
3375     return;
3376 }
3377 #endif
3378
3379 #if defined(atarist) || defined(OS2) || defined(EPOC)
3380 int pclose();
3381 #ifdef HAS_FORK
3382 int                                     /* Cannot prototype with I32
3383                                            in os2ish.h. */
3384 my_syspclose(PerlIO *ptr)
3385 #else
3386 I32
3387 Perl_my_pclose(pTHX_ PerlIO *ptr)
3388 #endif
3389 {
3390     /* Needs work for PerlIO ! */
3391     FILE * const f = PerlIO_findFILE(ptr);
3392     const I32 result = pclose(f);
3393     PerlIO_releaseFILE(ptr,f);
3394     return result;
3395 }
3396 #endif
3397
3398 #if defined(DJGPP)
3399 int djgpp_pclose();
3400 I32
3401 Perl_my_pclose(pTHX_ PerlIO *ptr)
3402 {
3403     /* Needs work for PerlIO ! */
3404     FILE * const f = PerlIO_findFILE(ptr);
3405     I32 result = djgpp_pclose(f);
3406     result = (result << 8) & 0xff00;
3407     PerlIO_releaseFILE(ptr,f);
3408     return result;
3409 }
3410 #endif
3411
3412 #define PERL_REPEATCPY_LINEAR 4
3413 void
3414 Perl_repeatcpy(register char *to, register const char *from, I32 len, register IV count)
3415 {
3416     PERL_ARGS_ASSERT_REPEATCPY;
3417
3418     if (len == 1)
3419         memset(to, *from, count);
3420     else if (count) {
3421         register char *p = to;
3422         IV items, linear, half;
3423
3424         linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3425         for (items = 0; items < linear; ++items) {
3426             register const char *q = from;
3427             IV todo;
3428             for (todo = len; todo > 0; todo--)
3429                 *p++ = *q++;
3430         }
3431
3432         half = count / 2;
3433         while (items <= half) {
3434             IV size = items * len;
3435             memcpy(p, to, size);
3436             p     += size;
3437             items *= 2;
3438         }
3439
3440         if (count > items)
3441             memcpy(p, to, (count - items) * len);
3442     }
3443 }
3444
3445 #ifndef HAS_RENAME
3446 I32
3447 Perl_same_dirent(pTHX_ const char *a, const char *b)
3448 {
3449     char *fa = strrchr(a,'/');
3450     char *fb = strrchr(b,'/');
3451     Stat_t tmpstatbuf1;
3452     Stat_t tmpstatbuf2;
3453     SV * const tmpsv = sv_newmortal();
3454
3455     PERL_ARGS_ASSERT_SAME_DIRENT;
3456
3457     if (fa)
3458         fa++;
3459     else
3460         fa = a;
3461     if (fb)
3462         fb++;
3463     else
3464         fb = b;
3465     if (strNE(a,b))
3466         return FALSE;
3467     if (fa == a)
3468         sv_setpvs(tmpsv, ".");
3469     else
3470         sv_setpvn(tmpsv, a, fa - a);
3471     if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3472         return FALSE;
3473     if (fb == b)
3474         sv_setpvs(tmpsv, ".");
3475     else
3476         sv_setpvn(tmpsv, b, fb - b);
3477     if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3478         return FALSE;
3479     return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3480            tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3481 }
3482 #endif /* !HAS_RENAME */
3483
3484 char*
3485 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3486                  const char *const *const search_ext, I32 flags)
3487 {
3488     dVAR;
3489     const char *xfound = NULL;
3490     char *xfailed = NULL;
3491     char tmpbuf[MAXPATHLEN];
3492     register char *s;
3493     I32 len = 0;
3494     int retval;
3495     char *bufend;
3496 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3497 #  define SEARCH_EXTS ".bat", ".cmd", NULL
3498 #  define MAX_EXT_LEN 4
3499 #endif
3500 #ifdef OS2
3501 #  define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3502 #  define MAX_EXT_LEN 4
3503 #endif
3504 #ifdef VMS
3505 #  define SEARCH_EXTS ".pl", ".com", NULL
3506 #  define MAX_EXT_LEN 4
3507 #endif
3508     /* additional extensions to try in each dir if scriptname not found */
3509 #ifdef SEARCH_EXTS
3510     static const char *const exts[] = { SEARCH_EXTS };
3511     const char *const *const ext = search_ext ? search_ext : exts;
3512     int extidx = 0, i = 0;
3513     const char *curext = NULL;
3514 #else
3515     PERL_UNUSED_ARG(search_ext);
3516 #  define MAX_EXT_LEN 0
3517 #endif
3518
3519     PERL_ARGS_ASSERT_FIND_SCRIPT;
3520
3521     /*
3522      * If dosearch is true and if scriptname does not contain path
3523      * delimiters, search the PATH for scriptname.
3524      *
3525      * If SEARCH_EXTS is also defined, will look for each
3526      * scriptname{SEARCH_EXTS} whenever scriptname is not found
3527      * while searching the PATH.
3528      *
3529      * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3530      * proceeds as follows:
3531      *   If DOSISH or VMSISH:
3532      *     + look for ./scriptname{,.foo,.bar}
3533      *     + search the PATH for scriptname{,.foo,.bar}
3534      *
3535      *   If !DOSISH:
3536      *     + look *only* in the PATH for scriptname{,.foo,.bar} (note
3537      *       this will not look in '.' if it's not in the PATH)
3538      */
3539     tmpbuf[0] = '\0';
3540
3541 #ifdef VMS
3542 #  ifdef ALWAYS_DEFTYPES
3543     len = strlen(scriptname);
3544     if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3545         int idx = 0, deftypes = 1;
3546         bool seen_dot = 1;
3547
3548         const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3549 #  else
3550     if (dosearch) {
3551         int idx = 0, deftypes = 1;
3552         bool seen_dot = 1;
3553
3554         const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3555 #  endif
3556         /* The first time through, just add SEARCH_EXTS to whatever we
3557          * already have, so we can check for default file types. */
3558         while (deftypes ||
3559                (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3560         {
3561             if (deftypes) {
3562                 deftypes = 0;
3563                 *tmpbuf = '\0';
3564             }
3565             if ((strlen(tmpbuf) + strlen(scriptname)
3566                  + MAX_EXT_LEN) >= sizeof tmpbuf)
3567                 continue;       /* don't search dir with too-long name */
3568             my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3569 #else  /* !VMS */
3570
3571 #ifdef DOSISH
3572     if (strEQ(scriptname, "-"))
3573         dosearch = 0;
3574     if (dosearch) {             /* Look in '.' first. */
3575         const char *cur = scriptname;
3576 #ifdef SEARCH_EXTS
3577         if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3578             while (ext[i])
3579                 if (strEQ(ext[i++],curext)) {
3580                     extidx = -1;                /* already has an ext */
3581                     break;
3582                 }
3583         do {
3584 #endif
3585             DEBUG_p(PerlIO_printf(Perl_debug_log,
3586                                   "Looking for %s\n",cur));
3587             if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3588                 && !S_ISDIR(PL_statbuf.st_mode)) {
3589                 dosearch = 0;
3590                 scriptname = cur;
3591 #ifdef SEARCH_EXTS
3592                 break;
3593 #endif
3594             }
3595 #ifdef SEARCH_EXTS
3596             if (cur == scriptname) {
3597                 len = strlen(scriptname);
3598                 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3599                     break;
3600                 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3601                 cur = tmpbuf;
3602             }
3603         } while (extidx >= 0 && ext[extidx]     /* try an extension? */
3604                  && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3605 #endif
3606     }
3607 #endif
3608
3609     if (dosearch && !strchr(scriptname, '/')
3610 #ifdef DOSISH
3611                  && !strchr(scriptname, '\\')
3612 #endif
3613                  && (s = PerlEnv_getenv("PATH")))
3614     {
3615         bool seen_dot = 0;
3616
3617         bufend = s + strlen(s);
3618         while (s < bufend) {
3619 #if defined(atarist) || defined(DOSISH)
3620             for (len = 0; *s
3621 #  ifdef atarist
3622                     && *s != ','
3623 #  endif
3624                     && *s != ';'; len++, s++) {
3625                 if (len < sizeof tmpbuf)
3626                     tmpbuf[len] = *s;
3627             }
3628             if (len < sizeof tmpbuf)
3629                 tmpbuf[len] = '\0';
3630 #else  /* ! (atarist || DOSISH) */
3631             s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3632                         ':',
3633                         &len);
3634 #endif /* ! (atarist || DOSISH) */
3635             if (s < bufend)
3636                 s++;
3637             if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3638                 continue;       /* don't search dir with too-long name */
3639             if (len
3640 #  if defined(atarist) || defined(DOSISH)
3641                 && tmpbuf[len - 1] != '/'
3642                 && tmpbuf[len - 1] != '\\'
3643 #  endif
3644                )
3645                 tmpbuf[len++] = '/';
3646             if (len == 2 && tmpbuf[0] == '.')
3647                 seen_dot = 1;
3648             (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3649 #endif  /* !VMS */
3650
3651 #ifdef SEARCH_EXTS
3652             len = strlen(tmpbuf);
3653             if (extidx > 0)     /* reset after previous loop */
3654                 extidx = 0;
3655             do {
3656 #endif
3657                 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3658                 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3659                 if (S_ISDIR(PL_statbuf.st_mode)) {
3660                     retval = -1;
3661                 }
3662 #ifdef SEARCH_EXTS
3663             } while (  retval < 0               /* not there */
3664                     && extidx>=0 && ext[extidx] /* try an extension? */
3665                     && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3666                 );
3667 #endif
3668             if (retval < 0)
3669                 continue;
3670             if (S_ISREG(PL_statbuf.st_mode)
3671                 && cando(S_IRUSR,TRUE,&PL_statbuf)
3672 #if !defined(DOSISH)
3673                 && cando(S_IXUSR,TRUE,&PL_statbuf)
3674 #endif
3675                 )
3676             {
3677                 xfound = tmpbuf;                /* bingo! */
3678                 break;
3679             }
3680             if (!xfailed)
3681                 xfailed = savepv(tmpbuf);
3682         }
3683 #ifndef DOSISH
3684         if (!xfound && !seen_dot && !xfailed &&
3685             (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3686              || S_ISDIR(PL_statbuf.st_mode)))
3687 #endif
3688             seen_dot = 1;                       /* Disable message. */
3689         if (!xfound) {
3690             if (flags & 1) {                    /* do or die? */
3691                 /* diag_listed_as: Can't execute %s */
3692                 Perl_croak(aTHX_ "Can't %s %s%s%s",
3693                       (xfailed ? "execute" : "find"),
3694                       (xfailed ? xfailed : scriptname),
3695                       (xfailed ? "" : " on PATH"),
3696                       (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3697             }
3698             scriptname = NULL;
3699         }
3700         Safefree(xfailed);
3701         scriptname = xfound;
3702     }
3703     return (scriptname ? savepv(scriptname) : NULL);
3704 }
3705
3706 #ifndef PERL_GET_CONTEXT_DEFINED
3707
3708 void *
3709 Perl_get_context(void)
3710 {
3711     dVAR;
3712 #if defined(USE_ITHREADS)
3713 #  ifdef OLD_PTHREADS_API
3714     pthread_addr_t t;
3715     int error = pthread_getspecific(PL_thr_key, &t)
3716     if (error)
3717         Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3718     return (void*)t;
3719 #  else
3720 #    ifdef I_MACH_CTHREADS
3721     return (void*)cthread_data(cthread_self());
3722 #    else
3723     return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3724 #    endif
3725 #  endif
3726 #else
3727     return (void*)NULL;
3728 #endif
3729 }
3730
3731 void
3732 Perl_set_context(void *t)
3733 {
3734     dVAR;
3735     PERL_ARGS_ASSERT_SET_CONTEXT;
3736 #if defined(USE_ITHREADS)
3737 #  ifdef I_MACH_CTHREADS
3738     cthread_set_data(cthread_self(), t);
3739 #  else
3740     {
3741         const int error = pthread_setspecific(PL_thr_key, t);
3742         if (error)
3743             Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3744     }
3745 #  endif
3746 #else
3747     PERL_UNUSED_ARG(t);
3748 #endif
3749 }
3750
3751 #endif /* !PERL_GET_CONTEXT_DEFINED */
3752
3753 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3754 struct perl_vars *
3755 Perl_GetVars(pTHX)
3756 {
3757  return &PL_Vars;
3758 }
3759 #endif
3760
3761 char **
3762 Perl_get_op_names(pTHX)
3763 {
3764     PERL_UNUSED_CONTEXT;
3765     return (char **)PL_op_name;
3766 }
3767
3768 char **
3769 Perl_get_op_descs(pTHX)
3770 {
3771     PERL_UNUSED_CONTEXT;
3772     return (char **)PL_op_desc;
3773 }
3774
3775 const char *
3776 Perl_get_no_modify(pTHX)
3777 {
3778     PERL_UNUSED_CONTEXT;
3779     return PL_no_modify;
3780 }
3781
3782 U32 *
3783 Perl_get_opargs(pTHX)
3784 {
3785     PERL_UNUSED_CONTEXT;
3786     return (U32 *)PL_opargs;
3787 }
3788
3789 PPADDR_t*
3790 Perl_get_ppaddr(pTHX)
3791 {
3792     dVAR;
3793     PERL_UNUSED_CONTEXT;
3794     return (PPADDR_t*)PL_ppaddr;
3795 }
3796
3797 #ifndef HAS_GETENV_LEN
3798 char *
3799 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3800 {
3801     char * const env_trans = PerlEnv_getenv(env_elem);
3802     PERL_UNUSED_CONTEXT;
3803     PERL_ARGS_ASSERT_GETENV_LEN;
3804     if (env_trans)
3805         *len = strlen(env_trans);
3806     return env_trans;
3807 }
3808 #endif
3809
3810
3811 MGVTBL*
3812 Perl_get_vtbl(pTHX_ int vtbl_id)
3813 {
3814     PERL_UNUSED_CONTEXT;
3815
3816     return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3817         ? NULL : PL_magic_vtables + vtbl_id;
3818 }
3819
3820 I32
3821 Perl_my_fflush_all(pTHX)
3822 {
3823 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3824     return PerlIO_flush(NULL);
3825 #else
3826 # if defined(HAS__FWALK)
3827     extern int fflush(FILE *);
3828     /* undocumented, unprototyped, but very useful BSDism */
3829     extern void _fwalk(int (*)(FILE *));
3830     _fwalk(&fflush);
3831     return 0;
3832 # else
3833 #  if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3834     long open_max = -1;
3835 #   ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3836     open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3837 #   else
3838 #    if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3839     open_max = sysconf(_SC_OPEN_MAX);
3840 #     else
3841 #      ifdef FOPEN_MAX
3842     open_max = FOPEN_MAX;
3843 #      else
3844 #       ifdef OPEN_MAX
3845     open_max = OPEN_MAX;
3846 #       else
3847 #        ifdef _NFILE
3848     open_max = _NFILE;
3849 #        endif
3850 #       endif
3851 #      endif
3852 #     endif
3853 #    endif
3854     if (open_max > 0) {
3855       long i;
3856       for (i = 0; i < open_max; i++)
3857             if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3858                 STDIO_STREAM_ARRAY[i]._file < open_max &&
3859                 STDIO_STREAM_ARRAY[i]._flag)
3860                 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3861       return 0;
3862     }
3863 #  endif
3864     SETERRNO(EBADF,RMS_IFI);
3865     return EOF;
3866 # endif
3867 #endif
3868 }
3869
3870 void
3871 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3872 {
3873     if (ckWARN(WARN_IO)) {
3874         SV * const name
3875            = gv && (isGV(gv) || isGV_with_GP(gv))
3876                 ? sv_2mortal(newSVhek(GvENAME_HEK((gv))))
3877                 : NULL;
3878         const char * const direction = have == '>' ? "out" : "in";
3879
3880         if (name && SvPOK(name) && *SvPV_nolen(name))
3881             Perl_warner(aTHX_ packWARN(WARN_IO),
3882                         "Filehandle %"SVf" opened only for %sput",
3883                         name, direction);
3884         else
3885             Perl_warner(aTHX_ packWARN(WARN_IO),
3886                         "Filehandle opened only for %sput", direction);
3887     }
3888 }
3889
3890 void
3891 Perl_report_evil_fh(pTHX_ const GV *gv)
3892 {
3893     const IO *io = gv ? GvIO(gv) : NULL;
3894     const PERL_BITFIELD16 op = PL_op->op_type;
3895     const char *vile;
3896     I32 warn_type;
3897
3898     if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3899         vile = "closed";
3900         warn_type = WARN_CLOSED;
3901     }
3902     else {
3903         vile = "unopened";
3904         warn_type = WARN_UNOPENED;
3905     }
3906
3907     if (ckWARN(warn_type)) {
3908         SV * const name
3909             = gv && (isGV(gv) || isGV_with_GP(gv)) && GvENAMELEN(gv) ?
3910                                      sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3911         const char * const pars =
3912             (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3913         const char * const func =
3914             (const char *)
3915             (op == OP_READLINE   ? "readline"  :        /* "<HANDLE>" not nice */
3916              op == OP_LEAVEWRITE ? "write" :            /* "write exit" not nice */
3917              PL_op_desc[op]);
3918         const char * const type =
3919             (const char *)
3920             (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3921              ? "socket" : "filehandle");
3922         const bool have_name = name && SvPOK(name) && *SvPV_nolen(name);
3923         Perl_warner(aTHX_ packWARN(warn_type),
3924                    "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3925                     have_name ? " " : "",
3926                     SVfARG(have_name ? name : &PL_sv_no));
3927         if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3928                 Perl_warner(
3929                             aTHX_ packWARN(warn_type),
3930                         "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3931                         func, pars, have_name ? " " : "",
3932                         SVfARG(have_name ? name : &PL_sv_no)
3933                             );
3934     }
3935 }
3936
3937 /* To workaround core dumps from the uninitialised tm_zone we get the
3938  * system to give us a reasonable struct to copy.  This fix means that
3939  * strftime uses the tm_zone and tm_gmtoff values returned by
3940  * localtime(time()). That should give the desired result most of the
3941  * time. But probably not always!
3942  *
3943  * This does not address tzname aspects of NETaa14816.
3944  *
3945  */
3946
3947 #ifdef HAS_GNULIBC
3948 # ifndef STRUCT_TM_HASZONE
3949 #    define STRUCT_TM_HASZONE
3950 # endif
3951 #endif
3952
3953 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3954 # ifndef HAS_TM_TM_ZONE
3955 #    define HAS_TM_TM_ZONE
3956 # endif
3957 #endif
3958
3959 void
3960 Perl_init_tm(pTHX_ struct tm *ptm)      /* see mktime, strftime and asctime */
3961 {
3962 #ifdef HAS_TM_TM_ZONE
3963     Time_t now;
3964     const struct tm* my_tm;
3965     PERL_ARGS_ASSERT_INIT_TM;
3966     (void)time(&now);
3967     my_tm = localtime(&now);
3968     if (my_tm)
3969         Copy(my_tm, ptm, 1, struct tm);
3970 #else
3971     PERL_ARGS_ASSERT_INIT_TM;
3972     PERL_UNUSED_ARG(ptm);
3973 #endif
3974 }
3975
3976 /*
3977  * mini_mktime - normalise struct tm values without the localtime()
3978  * semantics (and overhead) of mktime().
3979  */
3980 void
3981 Perl_mini_mktime(pTHX_ struct tm *ptm)
3982 {
3983     int yearday;
3984     int secs;
3985     int month, mday, year, jday;
3986     int odd_cent, odd_year;
3987     PERL_UNUSED_CONTEXT;
3988
3989     PERL_ARGS_ASSERT_MINI_MKTIME;
3990
3991 #define DAYS_PER_YEAR   365
3992 #define DAYS_PER_QYEAR  (4*DAYS_PER_YEAR+1)
3993 #define DAYS_PER_CENT   (25*DAYS_PER_QYEAR-1)
3994 #define DAYS_PER_QCENT  (4*DAYS_PER_CENT+1)
3995 #define SECS_PER_HOUR   (60*60)
3996 #define SECS_PER_DAY    (24*SECS_PER_HOUR)
3997 /* parentheses deliberately absent on these two, otherwise they don't work */
3998 #define MONTH_TO_DAYS   153/5
3999 #define DAYS_TO_MONTH   5/153
4000 /* offset to bias by March (month 4) 1st between month/mday & year finding */
4001 #define YEAR_ADJUST     (4*MONTH_TO_DAYS+1)
4002 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
4003 #define WEEKDAY_BIAS    6       /* (1+6)%7 makes Sunday 0 again */
4004
4005 /*
4006  * Year/day algorithm notes:
4007  *
4008  * With a suitable offset for numeric value of the month, one can find
4009  * an offset into the year by considering months to have 30.6 (153/5) days,
4010  * using integer arithmetic (i.e., with truncation).  To avoid too much
4011  * messing about with leap days, we consider January and February to be
4012  * the 13th and 14th month of the previous year.  After that transformation,
4013  * we need the month index we use to be high by 1 from 'normal human' usage,
4014  * so the month index values we use run from 4 through 15.
4015  *
4016  * Given that, and the rules for the Gregorian calendar (leap years are those
4017  * divisible by 4 unless also divisible by 100, when they must be divisible
4018  * by 400 instead), we can simply calculate the number of days since some
4019  * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
4020  * the days we derive from our month index, and adding in the day of the
4021  * month.  The value used here is not adjusted for the actual origin which
4022  * it normally would use (1 January A.D. 1), since we're not exposing it.
4023  * We're only building the value so we can turn around and get the
4024  * normalised values for the year, month, day-of-month, and day-of-year.
4025  *
4026  * For going backward, we need to bias the value we're using so that we find
4027  * the right year value.  (Basically, we don't want the contribution of
4028  * March 1st to the number to apply while deriving the year).  Having done
4029  * that, we 'count up' the contribution to the year number by accounting for
4030  * full quadracenturies (400-year periods) with their extra leap days, plus
4031  * the contribution from full centuries (to avoid counting in the lost leap
4032  * days), plus the contribution from full quad-years (to count in the normal
4033  * leap days), plus the leftover contribution from any non-leap years.
4034  * At this point, if we were working with an actual leap day, we'll have 0
4035  * days left over.  This is also true for March 1st, however.  So, we have
4036  * to special-case that result, and (earlier) keep track of the 'odd'
4037  * century and year contributions.  If we got 4 extra centuries in a qcent,
4038  * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
4039  * Otherwise, we add back in the earlier bias we removed (the 123 from
4040  * figuring in March 1st), find the month index (integer division by 30.6),
4041  * and the remainder is the day-of-month.  We then have to convert back to
4042  * 'real' months (including fixing January and February from being 14/15 in
4043  * the previous year to being in the proper year).  After that, to get
4044  * tm_yday, we work with the normalised year and get a new yearday value for
4045  * January 1st, which we subtract from the yearday value we had earlier,
4046  * representing the date we've re-built.  This is done from January 1
4047  * because tm_yday is 0-origin.
4048  *
4049  * Since POSIX time routines are only guaranteed to work for times since the
4050  * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
4051  * applies Gregorian calendar rules even to dates before the 16th century
4052  * doesn't bother me.  Besides, you'd need cultural context for a given
4053  * date to know whether it was Julian or Gregorian calendar, and that's
4054  * outside the scope for this routine.  Since we convert back based on the
4055  * same rules we used to build the yearday, you'll only get strange results
4056  * for input which needed normalising, or for the 'odd' century years which
4057  * were leap years in the Julian calendar but not in the Gregorian one.
4058  * I can live with that.
4059  *
4060  * This algorithm also fails to handle years before A.D. 1 gracefully, but
4061  * that's still outside the scope for POSIX time manipulation, so I don't
4062  * care.
4063  */
4064
4065     year = 1900 + ptm->tm_year;
4066     month = ptm->tm_mon;
4067     mday = ptm->tm_mday;
4068     /* allow given yday with no month & mday to dominate the result */
4069     if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
4070         month = 0;
4071         mday = 0;
4072         jday = 1 + ptm->tm_yday;
4073     }
4074     else {
4075         jday = 0;
4076     }
4077     if (month >= 2)
4078         month+=2;
4079     else
4080         month+=14, year--;
4081     yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4082     yearday += month*MONTH_TO_DAYS + mday + jday;
4083     /*
4084      * Note that we don't know when leap-seconds were or will be,
4085      * so we have to trust the user if we get something which looks
4086      * like a sensible leap-second.  Wild values for seconds will
4087      * be rationalised, however.
4088      */
4089     if ((unsigned) ptm->tm_sec <= 60) {
4090         secs = 0;
4091     }
4092     else {
4093         secs = ptm->tm_sec;
4094         ptm->tm_sec = 0;
4095     }
4096     secs += 60 * ptm->tm_min;
4097     secs += SECS_PER_HOUR * ptm->tm_hour;
4098     if (secs < 0) {
4099         if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4100             /* got negative remainder, but need positive time */
4101             /* back off an extra day to compensate */
4102             yearday += (secs/SECS_PER_DAY)-1;
4103             secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4104         }
4105         else {
4106             yearday += (secs/SECS_PER_DAY);
4107             secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4108         }
4109     }
4110     else if (secs >= SECS_PER_DAY) {
4111         yearday += (secs/SECS_PER_DAY);
4112         secs %= SECS_PER_DAY;
4113     }
4114     ptm->tm_hour = secs/SECS_PER_HOUR;
4115     secs %= SECS_PER_HOUR;
4116     ptm->tm_min = secs/60;
4117     secs %= 60;
4118     ptm->tm_sec += secs;
4119     /* done with time of day effects */
4120     /*
4121      * The algorithm for yearday has (so far) left it high by 428.
4122      * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4123      * bias it by 123 while trying to figure out what year it
4124      * really represents.  Even with this tweak, the reverse
4125      * translation fails for years before A.D. 0001.
4126      * It would still fail for Feb 29, but we catch that one below.
4127      */
4128     jday = yearday;     /* save for later fixup vis-a-vis Jan 1 */
4129     yearday -= YEAR_ADJUST;
4130     year = (yearday / DAYS_PER_QCENT) * 400;
4131     yearday %= DAYS_PER_QCENT;
4132     odd_cent = yearday / DAYS_PER_CENT;
4133     year += odd_cent * 100;
4134     yearday %= DAYS_PER_CENT;
4135     year += (yearday / DAYS_PER_QYEAR) * 4;
4136     yearday %= DAYS_PER_QYEAR;
4137     odd_year = yearday / DAYS_PER_YEAR;
4138     year += odd_year;
4139     yearday %= DAYS_PER_YEAR;
4140     if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4141         month = 1;
4142         yearday = 29;
4143     }
4144     else {
4145         yearday += YEAR_ADJUST; /* recover March 1st crock */
4146         month = yearday*DAYS_TO_MONTH;
4147         yearday -= month*MONTH_TO_DAYS;
4148         /* recover other leap-year adjustment */
4149         if (month > 13) {
4150             month-=14;
4151             year++;
4152         }
4153         else {
4154             month-=2;
4155         }
4156     }
4157     ptm->tm_year = year - 1900;
4158     if (yearday) {
4159       ptm->tm_mday = yearday;
4160       ptm->tm_mon = month;
4161     }
4162     else {
4163       ptm->tm_mday = 31;
4164       ptm->tm_mon = month - 1;
4165     }
4166     /* re-build yearday based on Jan 1 to get tm_yday */
4167     year--;
4168     yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4169     yearday += 14*MONTH_TO_DAYS + 1;
4170     ptm->tm_yday = jday - yearday;
4171     /* fix tm_wday if not overridden by caller */
4172     if ((unsigned)ptm->tm_wday > 6)
4173         ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4174 }
4175
4176 char *
4177 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)
4178 {
4179 #ifdef HAS_STRFTIME
4180   char *buf;
4181   int buflen;
4182   struct tm mytm;
4183   int len;
4184
4185   PERL_ARGS_ASSERT_MY_STRFTIME;
4186
4187   init_tm(&mytm);       /* XXX workaround - see init_tm() above */
4188   mytm.tm_sec = sec;
4189   mytm.tm_min = min;
4190   mytm.tm_hour = hour;
4191   mytm.tm_mday = mday;
4192   mytm.tm_mon = mon;
4193   mytm.tm_year = year;
4194   mytm.tm_wday = wday;
4195   mytm.tm_yday = yday;
4196   mytm.tm_isdst = isdst;
4197   mini_mktime(&mytm);
4198   /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4199 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4200   STMT_START {
4201     struct tm mytm2;
4202     mytm2 = mytm;
4203     mktime(&mytm2);
4204 #ifdef HAS_TM_TM_GMTOFF
4205     mytm.tm_gmtoff = mytm2.tm_gmtoff;
4206 #endif
4207 #ifdef HAS_TM_TM_ZONE
4208     mytm.tm_zone = mytm2.tm_zone;
4209 #endif
4210   } STMT_END;
4211 #endif
4212   buflen = 64;
4213   Newx(buf, buflen, char);
4214   len = strftime(buf, buflen, fmt, &mytm);
4215   /*
4216   ** The following is needed to handle to the situation where
4217   ** tmpbuf overflows.  Basically we want to allocate a buffer
4218   ** and try repeatedly.  The reason why it is so complicated
4219   ** is that getting a return value of 0 from strftime can indicate
4220   ** one of the following:
4221   ** 1. buffer overflowed,
4222   ** 2. illegal conversion specifier, or
4223   ** 3. the format string specifies nothing to be returned(not
4224   **      an error).  This could be because format is an empty string
4225   **    or it specifies %p that yields an empty string in some locale.
4226   ** If there is a better way to make it portable, go ahead by
4227   ** all means.
4228   */
4229   if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4230     return buf;
4231   else {
4232     /* Possibly buf overflowed - try again with a bigger buf */
4233     const int fmtlen = strlen(fmt);
4234     int bufsize = fmtlen + buflen;
4235
4236     Renew(buf, bufsize, char);
4237     while (buf) {
4238       buflen = strftime(buf, bufsize, fmt, &mytm);
4239       if (buflen > 0 && buflen < bufsize)
4240         break;
4241       /* heuristic to prevent out-of-memory errors */
4242       if (bufsize > 100*fmtlen) {
4243         Safefree(buf);
4244         buf = NULL;
4245         break;
4246       }
4247       bufsize *= 2;
4248       Renew(buf, bufsize, char);
4249     }
4250     return buf;
4251   }
4252 #else
4253   Perl_croak(aTHX_ "panic: no strftime");
4254   return NULL;
4255 #endif
4256 }
4257
4258
4259 #define SV_CWD_RETURN_UNDEF \
4260 sv_setsv(sv, &PL_sv_undef); \
4261 return FALSE
4262
4263 #define SV_CWD_ISDOT(dp) \
4264     (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4265         (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4266
4267 /*
4268 =head1 Miscellaneous Functions
4269
4270 =for apidoc getcwd_sv
4271
4272 Fill the sv with current working directory
4273
4274 =cut
4275 */
4276
4277 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4278  * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4279  * getcwd(3) if available
4280  * Comments from the orignal:
4281  *     This is a faster version of getcwd.  It's also more dangerous
4282  *     because you might chdir out of a directory that you can't chdir
4283  *     back into. */
4284
4285 int
4286 Perl_getcwd_sv(pTHX_ register SV *sv)
4287 {
4288 #ifndef PERL_MICRO
4289     dVAR;
4290 #ifndef INCOMPLETE_TAINTS
4291     SvTAINTED_on(sv);
4292 #endif
4293
4294     PERL_ARGS_ASSERT_GETCWD_SV;
4295
4296 #ifdef HAS_GETCWD
4297     {
4298         char buf[MAXPATHLEN];
4299
4300         /* Some getcwd()s automatically allocate a buffer of the given
4301          * size from the heap if they are given a NULL buffer pointer.
4302          * The problem is that this behaviour is not portable. */
4303         if (getcwd(buf, sizeof(buf) - 1)) {
4304             sv_setpv(sv, buf);
4305             return TRUE;
4306         }
4307         else {
4308             sv_setsv(sv, &PL_sv_undef);
4309             return FALSE;
4310         }
4311     }
4312
4313 #else
4314
4315     Stat_t statbuf;
4316     int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4317     int pathlen=0;
4318     Direntry_t *dp;
4319
4320     SvUPGRADE(sv, SVt_PV);
4321
4322     if (PerlLIO_lstat(".", &statbuf) < 0) {
4323         SV_CWD_RETURN_UNDEF;
4324     }
4325
4326     orig_cdev = statbuf.st_dev;
4327     orig_cino = statbuf.st_ino;
4328     cdev = orig_cdev;
4329     cino = orig_cino;
4330
4331     for (;;) {
4332         DIR *dir;
4333         int namelen;
4334         odev = cdev;
4335         oino = cino;
4336
4337         if (PerlDir_chdir("..") < 0) {
4338             SV_CWD_RETURN_UNDEF;
4339         }
4340         if (PerlLIO_stat(".", &statbuf) < 0) {
4341             SV_CWD_RETURN_UNDEF;
4342         }
4343
4344         cdev = statbuf.st_dev;
4345         cino = statbuf.st_ino;
4346
4347         if (odev == cdev && oino == cino) {
4348             break;
4349         }
4350         if (!(dir = PerlDir_open("."))) {
4351             SV_CWD_RETURN_UNDEF;
4352         }
4353
4354         while ((dp = PerlDir_read(dir)) != NULL) {
4355 #ifdef DIRNAMLEN
4356             namelen = dp->d_namlen;
4357 #else
4358             namelen = strlen(dp->d_name);
4359 #endif
4360             /* skip . and .. */
4361             if (SV_CWD_ISDOT(dp)) {
4362                 continue;
4363             }
4364
4365             if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4366                 SV_CWD_RETURN_UNDEF;
4367             }
4368
4369             tdev = statbuf.st_dev;
4370             tino = statbuf.st_ino;
4371             if (tino == oino && tdev == odev) {
4372                 break;
4373             }
4374         }
4375
4376         if (!dp) {
4377             SV_CWD_RETURN_UNDEF;
4378         }
4379
4380         if (pathlen + namelen + 1 >= MAXPATHLEN) {
4381             SV_CWD_RETURN_UNDEF;
4382         }
4383
4384         SvGROW(sv, pathlen + namelen + 1);
4385
4386         if (pathlen) {
4387             /* shift down */
4388             Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4389         }
4390
4391         /* prepend current directory to the front */
4392         *SvPVX(sv) = '/';
4393         Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4394         pathlen += (namelen + 1);
4395
4396 #ifdef VOID_CLOSEDIR
4397         PerlDir_close(dir);
4398 #else
4399         if (PerlDir_close(dir) < 0) {
4400             SV_CWD_RETURN_UNDEF;
4401         }
4402 #endif
4403     }
4404
4405     if (pathlen) {
4406         SvCUR_set(sv, pathlen);
4407         *SvEND(sv) = '\0';
4408         SvPOK_only(sv);
4409
4410         if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4411             SV_CWD_RETURN_UNDEF;
4412         }
4413     }
4414     if (PerlLIO_stat(".", &statbuf) < 0) {
4415         SV_CWD_RETURN_UNDEF;
4416     }
4417
4418     cdev = statbuf.st_dev;
4419     cino = statbuf.st_ino;
4420
4421     if (cdev != orig_cdev || cino != orig_cino) {
4422         Perl_croak(aTHX_ "Unstable directory path, "
4423                    "current directory changed unexpectedly");
4424     }
4425
4426     return TRUE;
4427 #endif
4428
4429 #else
4430     return FALSE;
4431 #endif
4432 }
4433
4434 #define VERSION_MAX 0x7FFFFFFF
4435
4436 /*
4437 =for apidoc prescan_version
4438
4439 Validate that a given string can be parsed as a version object, but doesn't
4440 actually perform the parsing.  Can use either strict or lax validation rules.
4441 Can optionally set a number of hint variables to save the parsing code
4442 some time when tokenizing.
4443
4444 =cut
4445 */
4446 const char *
4447 Perl_prescan_version(pTHX_ const char *s, bool strict,
4448                      const char **errstr,
4449                      bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4450     bool qv = (sqv ? *sqv : FALSE);
4451     int width = 3;
4452     int saw_decimal = 0;
4453     bool alpha = FALSE;
4454     const char *d = s;
4455
4456     PERL_ARGS_ASSERT_PRESCAN_VERSION;
4457
4458     if (qv && isDIGIT(*d))
4459         goto dotted_decimal_version;
4460
4461     if (*d == 'v') { /* explicit v-string */
4462         d++;
4463         if (isDIGIT(*d)) {
4464             qv = TRUE;
4465         }
4466         else { /* degenerate v-string */
4467             /* requires v1.2.3 */
4468             BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4469         }
4470
4471 dotted_decimal_version:
4472         if (strict && d[0] == '0' && isDIGIT(d[1])) {
4473             /* no leading zeros allowed */
4474             BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4475         }
4476
4477         while (isDIGIT(*d))     /* integer part */
4478             d++;
4479
4480         if (*d == '.')
4481         {
4482             saw_decimal++;
4483             d++;                /* decimal point */
4484         }
4485         else
4486         {
4487             if (strict) {
4488                 /* require v1.2.3 */
4489                 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4490             }
4491             else {
4492                 goto version_prescan_finish;
4493             }
4494         }
4495
4496         {
4497             int i = 0;
4498             int j = 0;
4499             while (isDIGIT(*d)) {       /* just keep reading */
4500                 i++;
4501                 while (isDIGIT(*d)) {
4502                     d++; j++;
4503                     /* maximum 3 digits between decimal */
4504                     if (strict && j > 3) {
4505                         BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4506                     }
4507                 }
4508                 if (*d == '_') {
4509                     if (strict) {
4510                         BADVERSION(s,errstr,"Invalid version format (no underscores)");
4511                     }
4512                     if ( alpha ) {
4513                         BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4514                     }
4515                     d++;
4516                     alpha = TRUE;
4517                 }
4518                 else if (*d == '.') {
4519                     if (alpha) {
4520                         BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4521                     }
4522                     saw_decimal++;
4523                     d++;
4524                 }
4525                 else if (!isDIGIT(*d)) {
4526                     break;
4527                 }
4528                 j = 0;
4529             }
4530
4531             if (strict && i < 2) {
4532                 /* requires v1.2.3 */
4533                 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4534             }
4535         }
4536     }                                   /* end if dotted-decimal */
4537     else
4538     {                                   /* decimal versions */
4539         /* special strict case for leading '.' or '0' */
4540         if (strict) {
4541             if (*d == '.') {
4542                 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4543             }
4544             if (*d == '0' && isDIGIT(d[1])) {
4545                 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4546             }
4547         }
4548
4549         /* and we never support negative versions */
4550         if ( *d == '-') {
4551                 BADVERSION(s,errstr,"Invalid version format (negative version number)");                
4552         }
4553
4554         /* consume all of the integer part */
4555         while (isDIGIT(*d))
4556             d++;
4557
4558         /* look for a fractional part */
4559         if (*d == '.') {
4560             /* we found it, so consume it */
4561             saw_decimal++;
4562             d++;
4563         }
4564         else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4565             if ( d == s ) {
4566                 /* found nothing */
4567                 BADVERSION(s,errstr,"Invalid version format (version required)");
4568             }
4569             /* found just an integer */
4570             goto version_prescan_finish;
4571         }
4572         else if ( d == s ) {
4573             /* didn't find either integer or period */
4574             BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4575         }
4576         else if (*d == '_') {
4577             /* underscore can't come after integer part */
4578             if (strict) {
4579                 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4580             }
4581             else if (isDIGIT(d[1])) {
4582                 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4583             }
4584             else {
4585                 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4586             }
4587         }
4588         else {
4589             /* anything else after integer part is just invalid data */
4590             BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4591         }
4592
4593         /* scan the fractional part after the decimal point*/
4594
4595         if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4596                 /* strict or lax-but-not-the-end */
4597                 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4598         }
4599
4600         while (isDIGIT(*d)) {
4601             d++;
4602             if (*d == '.' && isDIGIT(d[-1])) {
4603                 if (alpha) {
4604                     BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4605                 }
4606                 if (strict) {
4607                     BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4608                 }
4609                 d = (char *)s;          /* start all over again */
4610                 qv = TRUE;
4611                 goto dotted_decimal_version;
4612             }
4613             if (*d == '_') {
4614                 if (strict) {
4615                     BADVERSION(s,errstr,"Invalid version format (no underscores)");
4616                 }
4617                 if ( alpha ) {
4618                     BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4619                 }
4620                 if ( ! isDIGIT(d[1]) ) {
4621                     BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4622                 }
4623                 d++;
4624                 alpha = TRUE;
4625             }
4626         }
4627     }
4628
4629 version_prescan_finish:
4630     while (isSPACE(*d))
4631         d++;
4632
4633     if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4634         /* trailing non-numeric data */
4635         BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4636     }
4637
4638     if (sqv)
4639         *sqv = qv;
4640     if (swidth)
4641         *swidth = width;
4642     if (ssaw_decimal)
4643         *ssaw_decimal = saw_decimal;
4644     if (salpha)
4645         *salpha = alpha;
4646     return d;
4647 }
4648
4649 /*
4650 =for apidoc scan_version
4651
4652 Returns a pointer to the next character after the parsed
4653 version string, as well as upgrading the passed in SV to
4654 an RV.
4655
4656 Function must be called with an already existing SV like
4657
4658     sv = newSV(0);
4659     s = scan_version(s, SV *sv, bool qv);
4660
4661 Performs some preprocessing to the string to ensure that
4662 it has the correct characteristics of a version.  Flags the
4663 object if it contains an underscore (which denotes this
4664 is an alpha version).  The boolean qv denotes that the version
4665 should be interpreted as if it had multiple decimals, even if
4666 it doesn't.
4667
4668 =cut
4669 */
4670
4671 const char *
4672 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4673 {
4674     const char *start;
4675     const char *pos;
4676     const char *last;
4677     const char *errstr = NULL;
4678     int saw_decimal = 0;
4679     int width = 3;
4680     bool alpha = FALSE;
4681     bool vinf = FALSE;
4682     AV * const av = newAV();
4683     SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4684
4685     PERL_ARGS_ASSERT_SCAN_VERSION;
4686
4687     (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4688
4689 #ifndef NODEFAULT_SHAREKEYS
4690     HvSHAREKEYS_on(hv);         /* key-sharing on by default */
4691 #endif
4692
4693     while (isSPACE(*s)) /* leading whitespace is OK */
4694         s++;
4695
4696     last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4697     if (errstr) {
4698         /* "undef" is a special case and not an error */
4699         if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4700             Perl_croak(aTHX_ "%s", errstr);
4701         }
4702     }
4703
4704     start = s;
4705     if (*s == 'v')
4706         s++;
4707     pos = s;
4708
4709     if ( qv )
4710         (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4711     if ( alpha )
4712         (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4713     if ( !qv && width < 3 )
4714         (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4715     
4716     while (isDIGIT(*pos))
4717         pos++;
4718     if (!isALPHA(*pos)) {
4719         I32 rev;
4720
4721         for (;;) {
4722             rev = 0;
4723             {
4724                 /* this is atoi() that delimits on underscores */
4725                 const char *end = pos;
4726                 I32 mult = 1;
4727                 I32 orev;
4728
4729                 /* the following if() will only be true after the decimal
4730                  * point of a version originally created with a bare
4731                  * floating point number, i.e. not quoted in any way
4732                  */
4733                 if ( !qv && s > start && saw_decimal == 1 ) {
4734                     mult *= 100;
4735                     while ( s < end ) {
4736                         orev = rev;
4737                         rev += (*s - '0') * mult;
4738                         mult /= 10;
4739                         if (   (PERL_ABS(orev) > PERL_ABS(rev)) 
4740                             || (PERL_ABS(rev) > VERSION_MAX )) {
4741                             Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW), 
4742                                            "Integer overflow in version %d",VERSION_MAX);
4743                             s = end - 1;
4744                             rev = VERSION_MAX;
4745                             vinf = 1;
4746                         }
4747                         s++;
4748                         if ( *s == '_' )
4749                             s++;
4750                     }
4751                 }
4752                 else {
4753                     while (--end >= s) {
4754                         orev = rev;
4755                         rev += (*end - '0') * mult;
4756                         mult *= 10;
4757                         if (   (PERL_ABS(orev) > PERL_ABS(rev)) 
4758                             || (PERL_ABS(rev) > VERSION_MAX )) {
4759                             Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW), 
4760                                            "Integer overflow in version");
4761                             end = s - 1;
4762                             rev = VERSION_MAX;
4763                             vinf = 1;
4764                         }
4765                     }
4766                 } 
4767             }
4768
4769             /* Append revision */
4770             av_push(av, newSViv(rev));
4771             if ( vinf ) {
4772                 s = last;
4773                 break;
4774             }
4775             else if ( *pos == '.' )
4776                 s = ++pos;
4777             else if ( *pos == '_' && isDIGIT(pos[1]) )
4778                 s = ++pos;
4779             else if ( *pos == ',' && isDIGIT(pos[1]) )
4780                 s = ++pos;
4781             else if ( isDIGIT(*pos) )
4782                 s = pos;
4783             else {
4784                 s = pos;
4785                 break;
4786             }
4787             if ( qv ) {
4788                 while ( isDIGIT(*pos) )
4789                     pos++;
4790             }
4791             else {
4792                 int digits = 0;
4793                 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4794                     if ( *pos != '_' )
4795                         digits++;
4796                     pos++;
4797                 }
4798             }
4799         }
4800     }
4801     if ( qv ) { /* quoted versions always get at least three terms*/
4802         I32 len = av_len(av);
4803         /* This for loop appears to trigger a compiler bug on OS X, as it
4804            loops infinitely. Yes, len is negative. No, it makes no sense.
4805            Compiler in question is:
4806            gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4807            for ( len = 2 - len; len > 0; len-- )
4808            av_push(MUTABLE_AV(sv), newSViv(0));
4809         */
4810         len = 2 - len;
4811         while (len-- > 0)
4812             av_push(av, newSViv(0));
4813     }
4814
4815     /* need to save off the current version string for later */
4816     if ( vinf ) {
4817         SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4818         (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4819         (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4820     }
4821     else if ( s > start ) {
4822         SV * orig = newSVpvn(start,s-start);
4823         if ( qv && saw_decimal == 1 && *start != 'v' ) {
4824             /* need to insert a v to be consistent */
4825             sv_insert(orig, 0, 0, "v", 1);
4826         }
4827         (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4828     }
4829     else {
4830         (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4831         av_push(av, newSViv(0));
4832     }
4833
4834     /* And finally, store the AV in the hash */
4835     (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4836
4837     /* fix RT#19517 - special case 'undef' as string */
4838     if ( *s == 'u' && strEQ(s,"undef") ) {
4839         s += 5;
4840     }
4841
4842     return s;
4843 }
4844
4845 /*
4846 =for apidoc new_version
4847
4848 Returns a new version object based on the passed in SV:
4849
4850     SV *sv = new_version(SV *ver);
4851
4852 Does not alter the passed in ver SV.  See "upg_version" if you
4853 want to upgrade the SV.
4854
4855 =cut
4856 */
4857
4858 SV *
4859 Perl_new_version(pTHX_ SV *ver)
4860 {
4861     dVAR;
4862     SV * const rv = newSV(0);
4863     PERL_ARGS_ASSERT_NEW_VERSION;
4864     if ( sv_isobject(ver) && sv_derived_from(ver, "version") )
4865          /* can just copy directly */
4866     {
4867         I32 key;
4868         AV * const av = newAV();
4869         AV *sav;
4870         /* This will get reblessed later if a derived class*/
4871         SV * const hv = newSVrv(rv, "version"); 
4872         (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4873 #ifndef NODEFAULT_SHAREKEYS
4874         HvSHAREKEYS_on(hv);         /* key-sharing on by default */
4875 #endif
4876
4877         if ( SvROK(ver) )
4878             ver = SvRV(ver);
4879
4880         /* Begin copying all of the elements */
4881         if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4882             (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4883
4884         if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4885             (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4886         
4887         if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4888         {
4889             const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4890             (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4891         }
4892
4893         if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4894         {
4895             SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4896             (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4897         }
4898
4899         sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4900         /* This will get reblessed later if a derived class*/
4901         for ( key = 0; key <= av_len(sav); key++ )
4902         {
4903             const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4904             av_push(av, newSViv(rev));
4905         }
4906
4907         (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4908         return rv;
4909     }
4910 #ifdef SvVOK
4911     {
4912         const MAGIC* const mg = SvVSTRING_mg(ver);
4913         if ( mg ) { /* already a v-string */
4914             const STRLEN len = mg->mg_len;
4915             char * const version = savepvn( (const char*)mg->mg_ptr, len);
4916             sv_setpvn(rv,version,len);
4917             /* this is for consistency with the pure Perl class */
4918             if ( isDIGIT(*version) )
4919                 sv_insert(rv, 0, 0, "v", 1);
4920             Safefree(version);
4921         }
4922         else {
4923 #endif
4924         sv_setsv(rv,ver); /* make a duplicate */
4925 #ifdef SvVOK
4926         }
4927     }
4928 #endif
4929     return upg_version(rv, FALSE);
4930 }
4931
4932 /*
4933 =for apidoc upg_version
4934
4935 In-place upgrade of the supplied SV to a version object.
4936
4937     SV *sv = upg_version(SV *sv, bool qv);
4938
4939 Returns a pointer to the upgraded SV.  Set the boolean qv if you want
4940 to force this SV to be interpreted as an "extended" version.
4941
4942 =cut
4943 */
4944
4945 SV *
4946 Perl_upg_version(pTHX_ SV *ver, bool qv)
4947 {
4948     const char *version, *s;
4949 #ifdef SvVOK
4950     const MAGIC *mg;
4951 #endif
4952
4953     PERL_ARGS_ASSERT_UPG_VERSION;
4954
4955     if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4956     {
4957         STRLEN len;
4958
4959         /* may get too much accuracy */ 
4960         char tbuf[64];
4961 #ifdef USE_LOCALE_NUMERIC
4962         char *loc = savepv(setlocale(LC_NUMERIC, NULL));
4963         setlocale(LC_NUMERIC, "C");
4964 #endif
4965         len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4966 #ifdef USE_LOCALE_NUMERIC
4967         setlocale(LC_NUMERIC, loc);
4968         Safefree(loc);
4969 #endif
4970         while (tbuf[len-1] == '0' && len > 0) len--;
4971         if ( tbuf[len-1] == '.' ) len--; /* eat the trailing decimal */
4972         version = savepvn(tbuf, len);
4973     }
4974 #ifdef SvVOK
4975     else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4976         version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4977         qv = TRUE;
4978     }
4979 #endif
4980     else /* must be a string or something like a string */
4981     {
4982         STRLEN len;
4983         version = savepv(SvPV(ver,len));
4984 #ifndef SvVOK
4985 #  if PERL_VERSION > 5
4986         /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4987         if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
4988             /* may be a v-string */
4989             char *testv = (char *)version;
4990             STRLEN tlen = len;
4991             for (tlen=0; tlen < len; tlen++, testv++) {
4992                 /* if one of the characters is non-text assume v-string */
4993                 if (testv[0] < ' ') {
4994                     SV * const nsv = sv_newmortal();
4995                     const char *nver;
4996                     const char *pos;
4997                     int saw_decimal = 0;
4998                     sv_setpvf(nsv,"v%vd",ver);
4999                     pos = nver = savepv(SvPV_nolen(nsv));
5000
5001                     /* scan the resulting formatted string */
5002                     pos++; /* skip the leading 'v' */
5003                     while ( *pos == '.' || isDIGIT(*pos) ) {
5004                         if ( *pos == '.' )
5005                             saw_decimal++ ;
5006                         pos++;
5007                     }
5008
5009                     /* is definitely a v-string */
5010                     if ( saw_decimal >= 2 ) {   
5011                         Safefree(version);
5012                         version = nver;
5013                     }
5014                     break;
5015                 }
5016             }
5017         }
5018 #  endif
5019 #endif
5020     }
5021
5022     s = scan_version(version, ver, qv);
5023     if ( *s != '\0' ) 
5024         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), 
5025                        "Version string '%s' contains invalid data; "
5026                        "ignoring: '%s'", version, s);
5027     Safefree(version);
5028     return ver;
5029 }
5030
5031 /*
5032 =for apidoc vverify
5033
5034 Validates that the SV contains valid internal structure for a version object.
5035 It may be passed either the version object (RV) or the hash itself (HV).  If
5036 the structure is valid, it returns the HV.  If the structure is invalid,
5037 it returns NULL.
5038
5039     SV *hv = vverify(sv);
5040
5041 Note that it only confirms the bare minimum structure (so as not to get
5042 confused by derived classes which may contain additional hash entries):
5043
5044 =over 4
5045
5046 =item * The SV is an HV or a reference to an HV
5047
5048 =item * The hash contains a "version" key
5049
5050 =item * The "version" key has a reference to an AV as its value
5051
5052 =back
5053
5054 =cut
5055 */
5056
5057 SV *
5058 Perl_vverify(pTHX_ SV *vs)
5059 {
5060     SV *sv;
5061
5062     PERL_ARGS_ASSERT_VVERIFY;
5063
5064     if ( SvROK(vs) )
5065         vs = SvRV(vs);
5066
5067     /* see if the appropriate elements exist */
5068     if ( SvTYPE(vs) == SVt_PVHV
5069          && hv_exists(MUTABLE_HV(vs), "version", 7)
5070          && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
5071          && SvTYPE(sv) == SVt_PVAV )
5072         return vs;
5073     else
5074         return NULL;
5075 }
5076
5077 /*
5078 =for apidoc vnumify
5079
5080 Accepts a version object and returns the normalized floating
5081 point representation.  Call like:
5082
5083     sv = vnumify(rv);
5084
5085 NOTE: you can pass either the object directly or the SV
5086 contained within the RV.
5087
5088 The SV returned has a refcount of 1.
5089
5090 =cut
5091 */
5092
5093 SV *
5094 Perl_vnumify(pTHX_ SV *vs)
5095 {
5096     I32 i, len, digit;
5097     int width;
5098     bool alpha = FALSE;
5099     SV *sv;
5100     AV *av;
5101
5102     PERL_ARGS_ASSERT_VNUMIFY;
5103
5104     /* extract the HV from the object */
5105     vs = vverify(vs);
5106     if ( ! vs )
5107         Perl_croak(aTHX_ "Invalid version object");
5108
5109     /* see if various flags exist */
5110     if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5111         alpha = TRUE;
5112     if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
5113         width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
5114     else
5115         width = 3;
5116
5117
5118     /* attempt to retrieve the version array */
5119     if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
5120         return newSVpvs("0");
5121     }
5122
5123     len = av_len(av);
5124     if ( len == -1 )
5125     {
5126         return newSVpvs("0");
5127     }
5128
5129     digit = SvIV(*av_fetch(av, 0, 0));
5130     sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
5131     for ( i = 1 ; i < len ; i++ )
5132     {
5133         digit = SvIV(*av_fetch(av, i, 0));
5134         if ( width < 3 ) {
5135             const int denom = (width == 2 ? 10 : 100);
5136             const div_t term = div((int)PERL_ABS(digit),denom);
5137             Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
5138         }
5139         else {
5140             Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5141         }
5142     }
5143
5144     if ( len > 0 )
5145     {
5146         digit = SvIV(*av_fetch(av, len, 0));
5147         if ( alpha && width == 3 ) /* alpha version */
5148             sv_catpvs(sv,"_");
5149         Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5150     }
5151     else /* len == 0 */
5152     {
5153         sv_catpvs(sv, "000");
5154     }
5155     return sv;
5156 }
5157
5158 /*
5159 =for apidoc vnormal
5160
5161 Accepts a version object and returns the normalized string
5162 representation.  Call like:
5163
5164     sv = vnormal(rv);
5165
5166 NOTE: you can pass either the object directly or the SV
5167 contained within the RV.
5168
5169 The SV returned has a refcount of 1.
5170
5171 =cut
5172 */
5173
5174 SV *
5175 Perl_vnormal(pTHX_ SV *vs)
5176 {
5177     I32 i, len, digit;
5178     bool alpha = FALSE;
5179     SV *sv;
5180     AV *av;
5181
5182     PERL_ARGS_ASSERT_VNORMAL;
5183
5184     /* extract the HV from the object */
5185     vs = vverify(vs);
5186     if ( ! vs )
5187         Perl_croak(aTHX_ "Invalid version object");
5188
5189     if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5190         alpha = TRUE;
5191     av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)));
5192
5193     len = av_len(av);
5194     if ( len == -1 )
5195     {
5196         return newSVpvs("");
5197     }
5198     digit = SvIV(*av_fetch(av, 0, 0));
5199     sv = Perl_newSVpvf(aTHX_ "v%"IVdf, (IV)digit);
5200     for ( i = 1 ; i < len ; i++ ) {
5201         digit = SvIV(*av_fetch(av, i, 0));
5202         Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5203     }
5204
5205     if ( len > 0 )
5206     {
5207         /* handle last digit specially */
5208         digit = SvIV(*av_fetch(av, len, 0));
5209         if ( alpha )
5210             Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
5211         else
5212             Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5213     }
5214
5215     if ( len <= 2 ) { /* short version, must be at least three */
5216         for ( len = 2 - len; len != 0; len-- )
5217             sv_catpvs(sv,".0");
5218     }
5219     return sv;
5220 }
5221
5222 /*
5223 =for apidoc vstringify
5224
5225 In order to maintain maximum compatibility with earlier versions
5226 of Perl, this function will return either the floating point
5227 notation or the multiple dotted notation, depending on whether
5228 the original version contained 1 or more dots, respectively.
5229
5230 The SV returned has a refcount of 1.
5231
5232 =cut
5233 */
5234
5235 SV *
5236 Perl_vstringify(pTHX_ SV *vs)
5237 {
5238     PERL_ARGS_ASSERT_VSTRINGIFY;
5239
5240     /* extract the HV from the object */
5241     vs = vverify(vs);
5242     if ( ! vs )
5243         Perl_croak(aTHX_ "Invalid version object");
5244
5245     if (hv_exists(MUTABLE_HV(vs), "original",  sizeof("original") - 1)) {
5246         SV *pv;
5247         pv = *hv_fetchs(MUTABLE_HV(vs), "original", FALSE);
5248         if ( SvPOK(pv) )
5249             return newSVsv(pv);
5250         else
5251             return &PL_sv_undef;
5252     }
5253     else {
5254         if ( hv_exists(MUTABLE_HV(vs), "qv", 2) )
5255             return vnormal(vs);
5256         else
5257             return vnumify(vs);
5258     }
5259 }
5260
5261 /*
5262 =for apidoc vcmp
5263
5264 Version object aware cmp.  Both operands must already have been 
5265 converted into version objects.
5266
5267 =cut
5268 */
5269
5270 int
5271 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
5272 {
5273     I32 i,l,m,r,retval;
5274     bool lalpha = FALSE;
5275     bool ralpha = FALSE;
5276     I32 left = 0;
5277     I32 right = 0;
5278     AV *lav, *rav;
5279
5280     PERL_ARGS_ASSERT_VCMP;
5281
5282     /* extract the HVs from the objects */
5283     lhv = vverify(lhv);
5284     rhv = vverify(rhv);
5285     if ( ! ( lhv && rhv ) )
5286         Perl_croak(aTHX_ "Invalid version object");
5287
5288     /* get the left hand term */
5289     lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(lhv), "version", FALSE)));
5290     if ( hv_exists(MUTABLE_HV(lhv), "alpha", 5 ) )
5291         lalpha = TRUE;
5292
5293     /* and the right hand term */
5294     rav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rhv), "version", FALSE)));
5295     if ( hv_exists(MUTABLE_HV(rhv), "alpha", 5 ) )
5296         ralpha = TRUE;
5297
5298     l = av_len(lav);
5299     r = av_len(rav);
5300     m = l < r ? l : r;
5301     retval = 0;
5302     i = 0;
5303     while ( i <= m && retval == 0 )
5304     {
5305         left  = SvIV(*av_fetch(lav,i,0));
5306         right = SvIV(*av_fetch(rav,i,0));
5307         if ( left < right  )
5308             retval = -1;
5309         if ( left > right )
5310             retval = +1;
5311         i++;
5312     }
5313
5314     /* tiebreaker for alpha with identical terms */
5315     if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
5316     {
5317         if ( lalpha && !ralpha )
5318         {
5319             retval = -1;
5320         }
5321         else if ( ralpha && !lalpha)
5322         {
5323             retval = +1;
5324         }
5325     }
5326
5327     if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
5328     {
5329         if ( l < r )
5330         {
5331             while ( i <= r && retval == 0 )
5332             {
5333                 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
5334                     retval = -1; /* not a match after all */
5335                 i++;
5336             }
5337         }
5338         else
5339         {
5340             while ( i <= l && retval == 0 )
5341             {
5342                 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
5343                     retval = +1; /* not a match after all */
5344                 i++;
5345             }
5346         }
5347     }
5348     return retval;
5349 }
5350
5351 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
5352 #   define EMULATE_SOCKETPAIR_UDP
5353 #endif
5354
5355 #ifdef EMULATE_SOCKETPAIR_UDP
5356 static int
5357 S_socketpair_udp (int fd[2]) {
5358     dTHX;
5359     /* Fake a datagram socketpair using UDP to localhost.  */
5360     int sockets[2] = {-1, -1};
5361     struct sockaddr_in addresses[2];
5362     int i;
5363     Sock_size_t size = sizeof(struct sockaddr_in);
5364     unsigned short port;
5365     int got;
5366
5367     memset(&addresses, 0, sizeof(addresses));
5368     i = 1;
5369     do {
5370         sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
5371         if (sockets[i] == -1)
5372             goto tidy_up_and_fail;
5373
5374         addresses[i].sin_family = AF_INET;
5375         addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5376         addresses[i].sin_port = 0;      /* kernel choses port.  */
5377         if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
5378                 sizeof(struct sockaddr_in)) == -1)
5379             goto tidy_up_and_fail;
5380     } while (i--);
5381
5382     /* Now have 2 UDP sockets. Find out which port each is connected to, and
5383        for each connect the other socket to it.  */
5384     i = 1;
5385     do {
5386         if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
5387                 &size) == -1)
5388             goto tidy_up_and_fail;
5389         if (size != sizeof(struct sockaddr_in))
5390             goto abort_tidy_up_and_fail;
5391         /* !1 is 0, !0 is 1 */
5392         if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
5393                 sizeof(struct sockaddr_in)) == -1)
5394             goto tidy_up_and_fail;
5395     } while (i--);
5396
5397     /* Now we have 2 sockets connected to each other. I don't trust some other
5398        process not to have already sent a packet to us (by random) so send
5399        a packet from each to the other.  */
5400     i = 1;
5401     do {
5402         /* I'm going to send my own port number.  As a short.
5403            (Who knows if someone somewhere has sin_port as a bitfield and needs
5404            this routine. (I'm assuming crays have socketpair)) */
5405         port = addresses[i].sin_port;
5406         got = PerlLIO_write(sockets[i], &port, sizeof(port));
5407         if (got != sizeof(port)) {
5408             if (got == -1)
5409                 goto tidy_up_and_fail;
5410             goto abort_tidy_up_and_fail;
5411         }
5412     } while (i--);
5413
5414     /* Packets sent. I don't trust them to have arrived though.
5415        (As I understand it Solaris TCP stack is multithreaded. Non-blocking
5416        connect to localhost will use a second kernel thread. In 2.6 the
5417        first thread running the connect() returns before the second completes,
5418        so EINPROGRESS> In 2.7 the improved stack is faster and connect()
5419        returns 0. Poor programs have tripped up. One poor program's authors'
5420        had a 50-1 reverse stock split. Not sure how connected these were.)
5421        So I don't trust someone not to have an unpredictable UDP stack.
5422     */
5423
5424     {
5425         struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
5426         int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
5427         fd_set rset;
5428
5429         FD_ZERO(&rset);
5430         FD_SET((unsigned int)sockets[0], &rset);
5431         FD_SET((unsigned int)sockets[1], &rset);
5432
5433         got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
5434         if (got != 2 || !FD_ISSET(sockets[0], &rset)
5435                 || !FD_ISSET(sockets[1], &rset)) {
5436             /* I hope this is portable and appropriate.  */
5437             if (got == -1)
5438                 goto tidy_up_and_fail;
5439             goto abort_tidy_up_and_fail;
5440         }
5441     }
5442
5443     /* And the paranoia department even now doesn't trust it to have arrive
5444        (hence MSG_DONTWAIT). Or that what arrives was sent by us.  */
5445     {
5446         struct sockaddr_in readfrom;
5447         unsigned short buffer[2];
5448
5449         i = 1;
5450         do {
5451 #ifdef MSG_DONTWAIT
5452             got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5453                     sizeof(buffer), MSG_DONTWAIT,
5454                     (struct sockaddr *) &readfrom, &size);
5455 #else
5456             got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5457                     sizeof(buffer), 0,
5458                     (struct sockaddr *) &readfrom, &size);
5459 #endif
5460
5461             if (got == -1)
5462                 goto tidy_up_and_fail;
5463             if (got != sizeof(port)
5464                     || size != sizeof(struct sockaddr_in)
5465                     /* Check other socket sent us its port.  */
5466                     || buffer[0] != (unsigned short) addresses[!i].sin_port
5467                     /* Check kernel says we got the datagram from that socket */
5468                     || readfrom.sin_family != addresses[!i].sin_family
5469                     || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
5470                     || readfrom.sin_port != addresses[!i].sin_port)
5471                 goto abort_tidy_up_and_fail;
5472         } while (i--);
5473     }
5474     /* My caller (my_socketpair) has validated that this is non-NULL  */
5475     fd[0] = sockets[0];
5476     fd[1] = sockets[1];
5477     /* I hereby declare this connection open.  May God bless all who cross
5478        her.  */
5479     return 0;
5480
5481   abort_tidy_up_and_fail:
5482     errno = ECONNABORTED;
5483   tidy_up_and_fail:
5484     {
5485         dSAVE_ERRNO;
5486         if (sockets[0] != -1)
5487             PerlLIO_close(sockets[0]);
5488         if (sockets[1] != -1)
5489             PerlLIO_close(sockets[1]);
5490         RESTORE_ERRNO;
5491         return -1;
5492     }
5493 }
5494 #endif /*  EMULATE_SOCKETPAIR_UDP */
5495
5496 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
5497 int
5498 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5499     /* Stevens says that family must be AF_LOCAL, protocol 0.
5500        I'm going to enforce that, then ignore it, and use TCP (or UDP).  */
5501     dTHX;
5502     int listener = -1;
5503     int connector = -1;
5504     int acceptor = -1;
5505     struct sockaddr_in listen_addr;
5506     struct sockaddr_in connect_addr;
5507     Sock_size_t size;
5508
5509     if (protocol
5510 #ifdef AF_UNIX
5511         || family != AF_UNIX
5512 #endif
5513     ) {
5514         errno = EAFNOSUPPORT;
5515         return -1;
5516     }
5517     if (!fd) {
5518         errno = EINVAL;
5519         return -1;
5520     }
5521
5522 #ifdef EMULATE_SOCKETPAIR_UDP
5523     if (type == SOCK_DGRAM)
5524         return S_socketpair_udp(fd);
5525 #endif
5526
5527     listener = PerlSock_socket(AF_INET, type, 0);
5528     if (listener == -1)
5529         return -1;
5530     memset(&listen_addr, 0, sizeof(listen_addr));
5531     listen_addr.sin_family = AF_INET;
5532     listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5533     listen_addr.sin_port = 0;   /* kernel choses port.  */
5534     if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5535             sizeof(listen_addr)) == -1)
5536         goto tidy_up_and_fail;
5537     if (PerlSock_listen(listener, 1) == -1)
5538         goto tidy_up_and_fail;
5539
5540     connector = PerlSock_socket(AF_INET, type, 0);
5541     if (connector == -1)
5542         goto tidy_up_and_fail;
5543     /* We want to find out the port number to connect to.  */
5544     size = sizeof(connect_addr);
5545     if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5546             &size) == -1)
5547         goto tidy_up_and_fail;
5548     if (size != sizeof(connect_addr))
5549         goto abort_tidy_up_and_fail;
5550     if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
5551             sizeof(connect_addr)) == -1)
5552         goto tidy_up_and_fail;
5553
5554     size = sizeof(listen_addr);
5555     acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5556             &size);
5557     if (acceptor == -1)
5558         goto tidy_up_and_fail;
5559     if (size != sizeof(listen_addr))
5560         goto abort_tidy_up_and_fail;
5561     PerlLIO_close(listener);
5562     /* Now check we are talking to ourself by matching port and host on the
5563        two sockets.  */
5564     if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5565             &size) == -1)
5566         goto tidy_up_and_fail;
5567     if (size != sizeof(connect_addr)
5568             || listen_addr.sin_family != connect_addr.sin_family
5569             || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5570             || listen_addr.sin_port != connect_addr.sin_port) {
5571         goto abort_tidy_up_and_fail;
5572     }
5573     fd[0] = connector;
5574     fd[1] = acceptor;
5575     return 0;
5576
5577   abort_tidy_up_and_fail:
5578 #ifdef ECONNABORTED
5579   errno = ECONNABORTED; /* This would be the standard thing to do. */
5580 #else
5581 #  ifdef ECONNREFUSED
5582   errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5583 #  else
5584   errno = ETIMEDOUT;    /* Desperation time. */
5585 #  endif
5586 #endif
5587   tidy_up_and_fail:
5588     {
5589         dSAVE_ERRNO;
5590         if (listener != -1)
5591             PerlLIO_close(listener);
5592         if (connector != -1)
5593             PerlLIO_close(connector);
5594         if (acceptor != -1)
5595             PerlLIO_close(acceptor);
5596         RESTORE_ERRNO;
5597         return -1;
5598     }
5599 }
5600 #else
5601 /* In any case have a stub so that there's code corresponding
5602  * to the my_socketpair in embed.fnc. */
5603 int
5604 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5605 #ifdef HAS_SOCKETPAIR
5606     return socketpair(family, type, protocol, fd);
5607 #else
5608     return -1;
5609 #endif
5610 }
5611 #endif
5612
5613 /*
5614
5615 =for apidoc sv_nosharing
5616
5617 Dummy routine which "shares" an SV when there is no sharing module present.
5618 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5619 Exists to avoid test for a NULL function pointer and because it could
5620 potentially warn under some level of strict-ness.
5621
5622 =cut
5623 */
5624
5625 void
5626 Perl_sv_nosharing(pTHX_ SV *sv)
5627 {
5628     PERL_UNUSED_CONTEXT;
5629     PERL_UNUSED_ARG(sv);
5630 }
5631
5632 /*
5633
5634 =for apidoc sv_destroyable
5635
5636 Dummy routine which reports that object can be destroyed when there is no
5637 sharing module present.  It ignores its single SV argument, and returns
5638 'true'.  Exists to avoid test for a NULL function pointer and because it
5639 could potentially warn under some level of strict-ness.
5640
5641 =cut
5642 */
5643
5644 bool
5645 Perl_sv_destroyable(pTHX_ SV *sv)
5646 {
5647     PERL_UNUSED_CONTEXT;
5648     PERL_UNUSED_ARG(sv);
5649     return TRUE;
5650 }
5651
5652 U32
5653 Perl_parse_unicode_opts(pTHX_ const char **popt)
5654 {
5655   const char *p = *popt;
5656   U32 opt = 0;
5657
5658   PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5659
5660   if (*p) {
5661        if (isDIGIT(*p)) {
5662             opt = (U32) atoi(p);
5663             while (isDIGIT(*p))
5664                 p++;
5665             if (*p && *p != '\n' && *p != '\r') {
5666              if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5667              else
5668                  Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
5669             }
5670        }
5671        else {
5672             for (; *p; p++) {
5673                  switch (*p) {
5674                  case PERL_UNICODE_STDIN:
5675                       opt |= PERL_UNICODE_STDIN_FLAG;   break;
5676                  case PERL_UNICODE_STDOUT:
5677                       opt |= PERL_UNICODE_STDOUT_FLAG;  break;
5678                  case PERL_UNICODE_STDERR:
5679                       opt |= PERL_UNICODE_STDERR_FLAG;  break;
5680                  case PERL_UNICODE_STD:
5681                       opt |= PERL_UNICODE_STD_FLAG;     break;
5682                  case PERL_UNICODE_IN:
5683                       opt |= PERL_UNICODE_IN_FLAG;      break;
5684                  case PERL_UNICODE_OUT:
5685                       opt |= PERL_UNICODE_OUT_FLAG;     break;
5686                  case PERL_UNICODE_INOUT:
5687                       opt |= PERL_UNICODE_INOUT_FLAG;   break;
5688                  case PERL_UNICODE_LOCALE:
5689                       opt |= PERL_UNICODE_LOCALE_FLAG;  break;
5690                  case PERL_UNICODE_ARGV:
5691                       opt |= PERL_UNICODE_ARGV_FLAG;    break;
5692                  case PERL_UNICODE_UTF8CACHEASSERT:
5693                       opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
5694                  default:
5695                       if (*p != '\n' && *p != '\r') {
5696                         if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5697                         else
5698                           Perl_croak(aTHX_
5699                                      "Unknown Unicode option letter '%c'", *p);
5700                       }
5701                  }
5702             }
5703        }
5704   }
5705   else
5706        opt = PERL_UNICODE_DEFAULT_FLAGS;
5707
5708   the_end_of_the_opts_parser:
5709
5710   if (opt & ~PERL_UNICODE_ALL_FLAGS)
5711        Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
5712                   (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5713
5714   *popt = p;
5715
5716   return opt;
5717 }
5718
5719 U32
5720 Perl_seed(pTHX)
5721 {
5722     dVAR;
5723     /*
5724      * This is really just a quick hack which grabs various garbage
5725      * values.  It really should be a real hash algorithm which
5726      * spreads the effect of every input bit onto every output bit,
5727      * if someone who knows about such things would bother to write it.
5728      * Might be a good idea to add that function to CORE as well.
5729      * No numbers below come from careful analysis or anything here,
5730      * except they are primes and SEED_C1 > 1E6 to get a full-width
5731      * value from (tv_sec * SEED_C1 + tv_usec).  The multipliers should
5732      * probably be bigger too.
5733      */
5734 #if RANDBITS > 16
5735 #  define SEED_C1       1000003
5736 #define   SEED_C4       73819
5737 #else
5738 #  define SEED_C1       25747
5739 #define   SEED_C4       20639
5740 #endif
5741 #define   SEED_C2       3
5742 #define   SEED_C3       269
5743 #define   SEED_C5       26107
5744
5745 #ifndef PERL_NO_DEV_RANDOM
5746     int fd;
5747 #endif
5748     U32 u;
5749 #ifdef VMS
5750 #  include <starlet.h>
5751     /* when[] = (low 32 bits, high 32 bits) of time since epoch
5752      * in 100-ns units, typically incremented ever 10 ms.        */
5753     unsigned int when[2];
5754 #else
5755 #  ifdef HAS_GETTIMEOFDAY
5756     struct timeval when;
5757 #  else
5758     Time_t when;
5759 #  endif
5760 #endif
5761
5762 /* This test is an escape hatch, this symbol isn't set by Configure. */
5763 #ifndef PERL_NO_DEV_RANDOM
5764 #ifndef PERL_RANDOM_DEVICE
5765    /* /dev/random isn't used by default because reads from it will block
5766     * if there isn't enough entropy available.  You can compile with
5767     * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5768     * is enough real entropy to fill the seed. */
5769 #  define PERL_RANDOM_DEVICE "/dev/urandom"
5770 #endif
5771     fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5772     if (fd != -1) {
5773         if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5774             u = 0;
5775         PerlLIO_close(fd);
5776         if (u)
5777             return u;
5778     }
5779 #endif
5780
5781 #ifdef VMS
5782     _ckvmssts(sys$gettim(when));
5783     u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5784 #else
5785 #  ifdef HAS_GETTIMEOFDAY
5786     PerlProc_gettimeofday(&when,NULL);
5787     u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5788 #  else
5789     (void)time(&when);
5790     u = (U32)SEED_C1 * when;
5791 #  endif
5792 #endif
5793     u += SEED_C3 * (U32)PerlProc_getpid();
5794     u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5795 #ifndef PLAN9           /* XXX Plan9 assembler chokes on this; fix needed  */
5796     u += SEED_C5 * (U32)PTR2UV(&when);
5797 #endif
5798     return u;
5799 }
5800
5801 UV
5802 Perl_get_hash_seed(pTHX)
5803 {
5804     dVAR;
5805      const char *s = PerlEnv_getenv("PERL_HASH_SEED");
5806      UV myseed = 0;
5807
5808      if (s)
5809         while (isSPACE(*s))
5810             s++;
5811      if (s && isDIGIT(*s))
5812           myseed = (UV)Atoul(s);
5813      else
5814 #ifdef USE_HASH_SEED_EXPLICIT
5815      if (s)
5816 #endif
5817      {
5818           /* Compute a random seed */
5819           (void)seedDrand01((Rand_seed_t)seed());
5820           myseed = (UV)(Drand01() * (NV)UV_MAX);
5821 #if RANDBITS < (UVSIZE * 8)
5822           /* Since there are not enough randbits to to reach all
5823            * the bits of a UV, the low bits might need extra
5824            * help.  Sum in another random number that will
5825            * fill in the low bits. */
5826           myseed +=
5827                (UV)(Drand01() * (NV)((((UV)1) << ((UVSIZE * 8 - RANDBITS))) - 1));
5828 #endif /* RANDBITS < (UVSIZE * 8) */
5829           if (myseed == 0) { /* Superparanoia. */
5830               myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5831               if (myseed == 0)
5832                   Perl_croak(aTHX_ "Your random numbers are not that random");
5833           }
5834      }
5835      PL_rehash_seed_set = TRUE;
5836
5837      return myseed;
5838 }
5839
5840 #ifdef USE_ITHREADS
5841 bool
5842 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5843 {
5844     const char * stashpv = CopSTASHPV(c);
5845     const char * name    = HvNAME_get(hv);
5846     PERL_UNUSED_CONTEXT;
5847     PERL_ARGS_ASSERT_STASHPV_HVNAME_MATCH;
5848
5849     if (!stashpv || !name)
5850         return stashpv == name;
5851     if ( HvNAMEUTF8(hv) && !(CopSTASH_flags(c) & SVf_UTF8 ? 1 : 0) ) {
5852         if (CopSTASH_flags(c) & SVf_UTF8) {
5853             return (bytes_cmp_utf8(
5854                         (const U8*)stashpv, strlen(stashpv),
5855                         (const U8*)name, HEK_LEN(HvNAME_HEK(hv))) == 0);
5856         } else {
5857             return (bytes_cmp_utf8(
5858                         (const U8*)name, HEK_LEN(HvNAME_HEK(hv)),
5859                         (const U8*)stashpv, strlen(stashpv)) == 0);
5860         }
5861     }
5862     else
5863         return (stashpv == name
5864                     || strEQ(stashpv, name));
5865     /*NOTREACHED*/
5866     return FALSE;
5867 }
5868 #endif
5869
5870
5871 #ifdef PERL_GLOBAL_STRUCT
5872
5873 #define PERL_GLOBAL_STRUCT_INIT
5874 #include "opcode.h" /* the ppaddr and check */
5875
5876 struct perl_vars *
5877 Perl_init_global_struct(pTHX)
5878 {
5879     struct perl_vars *plvarsp = NULL;
5880 # ifdef PERL_GLOBAL_STRUCT
5881     const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5882     const IV ncheck  = sizeof(Gcheck) /sizeof(Perl_check_t);
5883 #  ifdef PERL_GLOBAL_STRUCT_PRIVATE
5884     /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5885     plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5886     if (!plvarsp)
5887         exit(1);
5888 #  else
5889     plvarsp = PL_VarsPtr;
5890 #  endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5891 #  undef PERLVAR
5892 #  undef PERLVARA
5893 #  undef PERLVARI
5894 #  undef PERLVARIC
5895 #  define PERLVAR(prefix,var,type) /**/
5896 #  define PERLVARA(prefix,var,n,type) /**/
5897 #  define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
5898 #  define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
5899 #  include "perlvars.h"
5900 #  undef PERLVAR
5901 #  undef PERLVARA
5902 #  undef PERLVARI
5903 #  undef PERLVARIC
5904 #  ifdef PERL_GLOBAL_STRUCT
5905     plvarsp->Gppaddr =
5906         (Perl_ppaddr_t*)
5907         PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5908     if (!plvarsp->Gppaddr)
5909         exit(1);
5910     plvarsp->Gcheck  =
5911         (Perl_check_t*)
5912         PerlMem_malloc(ncheck  * sizeof(Perl_check_t));
5913     if (!plvarsp->Gcheck)
5914         exit(1);
5915     Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t); 
5916     Copy(Gcheck,  plvarsp->Gcheck,  ncheck,  Perl_check_t); 
5917 #  endif
5918 #  ifdef PERL_SET_VARS
5919     PERL_SET_VARS(plvarsp);
5920 #  endif
5921 # undef PERL_GLOBAL_STRUCT_INIT
5922 # endif
5923     return plvarsp;
5924 }
5925
5926 #endif /* PERL_GLOBAL_STRUCT */
5927
5928 #ifdef PERL_GLOBAL_STRUCT
5929
5930 void
5931 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5932 {
5933     PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
5934 # ifdef PERL_GLOBAL_STRUCT
5935 #  ifdef PERL_UNSET_VARS
5936     PERL_UNSET_VARS(plvarsp);
5937 #  endif
5938     free(plvarsp->Gppaddr);
5939     free(plvarsp->Gcheck);
5940 #  ifdef PERL_GLOBAL_STRUCT_PRIVATE
5941     free(plvarsp);
5942 #  endif
5943 # endif
5944 }
5945
5946 #endif /* PERL_GLOBAL_STRUCT */
5947
5948 #ifdef PERL_MEM_LOG
5949
5950 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
5951  * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
5952  * given, and you supply your own implementation.
5953  *
5954  * The default implementation reads a single env var, PERL_MEM_LOG,
5955  * expecting one or more of the following:
5956  *
5957  *    \d+ - fd          fd to write to          : must be 1st (atoi)
5958  *    'm' - memlog      was PERL_MEM_LOG=1
5959  *    's' - svlog       was PERL_SV_LOG=1
5960  *    't' - timestamp   was PERL_MEM_LOG_TIMESTAMP=1
5961  *
5962  * This makes the logger controllable enough that it can reasonably be
5963  * added to the system perl.
5964  */
5965
5966 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
5967  * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5968  */
5969 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5970
5971 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
5972  * writes to.  In the default logger, this is settable at runtime.
5973  */
5974 #ifndef PERL_MEM_LOG_FD
5975 #  define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5976 #endif
5977
5978 #ifndef PERL_MEM_LOG_NOIMPL
5979
5980 # ifdef DEBUG_LEAKING_SCALARS
5981 #   define SV_LOG_SERIAL_FMT        " [%lu]"
5982 #   define _SV_LOG_SERIAL_ARG(sv)   , (unsigned long) (sv)->sv_debug_serial
5983 # else
5984 #   define SV_LOG_SERIAL_FMT
5985 #   define _SV_LOG_SERIAL_ARG(sv)
5986 # endif
5987
5988 static void
5989 S_mem_log_common(enum mem_log_type mlt, const UV n, 
5990                  const UV typesize, const char *type_name, const SV *sv,
5991                  Malloc_t oldalloc, Malloc_t newalloc,
5992                  const char *filename, const int linenumber,
5993                  const char *funcname)
5994 {
5995     const char *pmlenv;
5996
5997     PERL_ARGS_ASSERT_MEM_LOG_COMMON;
5998
5999     pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
6000     if (!pmlenv)
6001         return;
6002     if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
6003     {
6004         /* We can't use SVs or PerlIO for obvious reasons,
6005          * so we'll use stdio and low-level IO instead. */
6006         char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
6007
6008 #   ifdef HAS_GETTIMEOFDAY
6009 #     define MEM_LOG_TIME_FMT   "%10d.%06d: "
6010 #     define MEM_LOG_TIME_ARG   (int)tv.tv_sec, (int)tv.tv_usec
6011         struct timeval tv;
6012         gettimeofday(&tv, 0);
6013 #   else
6014 #     define MEM_LOG_TIME_FMT   "%10d: "
6015 #     define MEM_LOG_TIME_ARG   (int)when
6016         Time_t when;
6017         (void)time(&when);
6018 #   endif
6019         /* If there are other OS specific ways of hires time than
6020          * gettimeofday() (see ext/Time-HiRes), the easiest way is
6021          * probably that they would be used to fill in the struct
6022          * timeval. */
6023         {
6024             STRLEN len;
6025             int fd = atoi(pmlenv);
6026             if (!fd)
6027                 fd = PERL_MEM_LOG_FD;
6028
6029             if (strchr(pmlenv, 't')) {
6030                 len = my_snprintf(buf, sizeof(buf),
6031                                 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
6032                 PerlLIO_write(fd, buf, len);
6033             }
6034             switch (mlt) {
6035             case MLT_ALLOC:
6036                 len = my_snprintf(buf, sizeof(buf),
6037                         "alloc: %s:%d:%s: %"IVdf" %"UVuf
6038                         " %s = %"IVdf": %"UVxf"\n",
6039                         filename, linenumber, funcname, n, typesize,
6040                         type_name, n * typesize, PTR2UV(newalloc));
6041                 break;
6042             case MLT_REALLOC:
6043                 len = my_snprintf(buf, sizeof(buf),
6044                         "realloc: %s:%d:%s: %"IVdf" %"UVuf
6045                         " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
6046                         filename, linenumber, funcname, n, typesize,
6047                         type_name, n * typesize, PTR2UV(oldalloc),
6048                         PTR2UV(newalloc));
6049                 break;
6050             case MLT_FREE:
6051                 len = my_snprintf(buf, sizeof(buf),
6052                         "free: %s:%d:%s: %"UVxf"\n",
6053                         filename, linenumber, funcname,
6054                         PTR2UV(oldalloc));
6055                 break;
6056             case MLT_NEW_SV:
6057             case MLT_DEL_SV:
6058                 len = my_snprintf(buf, sizeof(buf),
6059                         "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
6060                         mlt == MLT_NEW_SV ? "new" : "del",
6061                         filename, linenumber, funcname,
6062                         PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
6063                 break;
6064             default:
6065                 len = 0;
6066             }
6067             PerlLIO_write(fd, buf, len);
6068         }
6069     }
6070 }
6071 #endif /* !PERL_MEM_LOG_NOIMPL */
6072
6073 #ifndef PERL_MEM_LOG_NOIMPL
6074 # define \
6075     mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
6076     mem_log_common   (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
6077 #else
6078 /* this is suboptimal, but bug compatible.  User is providing their
6079    own implementation, but is getting these functions anyway, and they
6080    do nothing. But _NOIMPL users should be able to cope or fix */
6081 # define \
6082     mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
6083     /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
6084 #endif
6085
6086 Malloc_t
6087 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
6088                    Malloc_t newalloc, 
6089                    const char *filename, const int linenumber,
6090                    const char *funcname)
6091 {
6092     mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
6093                       NULL, NULL, newalloc,
6094                       filename, linenumber, funcname);
6095     return newalloc;
6096 }
6097
6098 Malloc_t
6099 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
6100                      Malloc_t oldalloc, Malloc_t newalloc, 
6101                      const char *filename, const int linenumber, 
6102                      const char *funcname)
6103 {
6104     mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
6105                       NULL, oldalloc, newalloc, 
6106                       filename, linenumber, funcname);
6107     return newalloc;
6108 }
6109
6110 Malloc_t
6111 Perl_mem_log_free(Malloc_t oldalloc, 
6112                   const char *filename, const int linenumber, 
6113                   const char *funcname)
6114 {
6115     mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL, 
6116                       filename, linenumber, funcname);
6117     return oldalloc;
6118 }
6119
6120 void
6121 Perl_mem_log_new_sv(const SV *sv, 
6122                     const char *filename, const int linenumber,
6123                     const char *funcname)
6124 {
6125     mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
6126                       filename, linenumber, funcname);
6127 }
6128
6129 void
6130 Perl_mem_log_del_sv(const SV *sv,
6131                     const char *filename, const int linenumber, 
6132                     const char *funcname)
6133 {
6134     mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL, 
6135                       filename, linenumber, funcname);
6136 }
6137
6138 #endif /* PERL_MEM_LOG */
6139
6140 /*
6141 =for apidoc my_sprintf
6142
6143 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
6144 the length of the string written to the buffer. Only rare pre-ANSI systems
6145 need the wrapper function - usually this is a direct call to C<sprintf>.
6146
6147 =cut
6148 */
6149 #ifndef SPRINTF_RETURNS_STRLEN
6150 int
6151 Perl_my_sprintf(char *buffer, const char* pat, ...)
6152 {
6153     va_list args;
6154     PERL_ARGS_ASSERT_MY_SPRINTF;
6155     va_start(args, pat);
6156     vsprintf(buffer, pat, args);
6157     va_end(args);
6158     return strlen(buffer);
6159 }
6160 #endif
6161
6162 /*
6163 =for apidoc my_snprintf
6164
6165 The C library C<snprintf> functionality, if available and
6166 standards-compliant (uses C<vsnprintf>, actually).  However, if the
6167 C<vsnprintf> is not available, will unfortunately use the unsafe
6168 C<vsprintf> which can overrun the buffer (there is an overrun check,
6169 but that may be too late).  Consider using C<sv_vcatpvf> instead, or
6170 getting C<vsnprintf>.
6171
6172 =cut
6173 */
6174 int
6175 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
6176 {
6177     dTHX;
6178     int retval;
6179     va_list ap;
6180     PERL_ARGS_ASSERT_MY_SNPRINTF;
6181     va_start(ap, format);
6182 #ifdef HAS_VSNPRINTF
6183     retval = vsnprintf(buffer, len, format, ap);
6184 #else
6185     retval = vsprintf(buffer, format, ap);
6186 #endif
6187     va_end(ap);
6188     /* vsprintf() shows failure with < 0 */
6189     if (retval < 0
6190 #ifdef HAS_VSNPRINTF
6191     /* vsnprintf() shows failure with >= len */
6192         ||
6193         (len > 0 && (Size_t)retval >= len) 
6194 #endif
6195     )
6196         Perl_croak(aTHX_ "panic: my_snprintf buffer overflow");
6197     return retval;
6198 }
6199
6200 /*
6201 =for apidoc my_vsnprintf
6202
6203 The C library C<vsnprintf> if available and standards-compliant.
6204 However, if if the C<vsnprintf> is not available, will unfortunately
6205 use the unsafe C<vsprintf> which can overrun the buffer (there is an
6206 overrun check, but that may be too late).  Consider using
6207 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
6208
6209 =cut
6210 */
6211 int
6212 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
6213 {
6214     dTHX;
6215     int retval;
6216 #ifdef NEED_VA_COPY
6217     va_list apc;
6218
6219     PERL_ARGS_ASSERT_MY_VSNPRINTF;
6220
6221     Perl_va_copy(ap, apc);
6222 # ifdef HAS_VSNPRINTF
6223     retval = vsnprintf(buffer, len, format, apc);
6224 # else
6225     retval = vsprintf(buffer, format, apc);
6226 # endif
6227 #else
6228 # ifdef HAS_VSNPRINTF
6229     retval = vsnprintf(buffer, len, format, ap);
6230 # else
6231     retval = vsprintf(buffer, format, ap);
6232 # endif
6233 #endif /* #ifdef NEED_VA_COPY */
6234     /* vsprintf() shows failure with < 0 */
6235     if (retval < 0
6236 #ifdef HAS_VSNPRINTF
6237     /* vsnprintf() shows failure with >= len */
6238         ||
6239         (len > 0 && (Size_t)retval >= len) 
6240 #endif
6241     )
6242         Perl_croak(aTHX_ "panic: my_vsnprintf buffer overflow");
6243     return retval;
6244 }
6245
6246 void
6247 Perl_my_clearenv(pTHX)
6248 {
6249     dVAR;
6250 #if ! defined(PERL_MICRO)
6251 #  if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
6252     PerlEnv_clearenv();
6253 #  else /* ! (PERL_IMPLICIT_SYS || WIN32) */
6254 #    if defined(USE_ENVIRON_ARRAY)
6255 #      if defined(USE_ITHREADS)
6256     /* only the parent thread can clobber the process environment */
6257     if (PL_curinterp == aTHX)
6258 #      endif /* USE_ITHREADS */
6259     {
6260 #      if ! defined(PERL_USE_SAFE_PUTENV)
6261     if ( !PL_use_safe_putenv) {
6262       I32 i;
6263       if (environ == PL_origenviron)
6264         environ = (char**)safesysmalloc(sizeof(char*));
6265       else
6266         for (i = 0; environ[i]; i++)
6267           (void)safesysfree(environ[i]);
6268     }
6269     environ[0] = NULL;
6270 #      else /* PERL_USE_SAFE_PUTENV */
6271 #        if defined(HAS_CLEARENV)
6272     (void)clearenv();
6273 #        elif defined(HAS_UNSETENV)
6274     int bsiz = 80; /* Most envvar names will be shorter than this. */
6275     int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
6276     char *buf = (char*)safesysmalloc(bufsiz);
6277     while (*environ != NULL) {
6278       char *e = strchr(*environ, '=');
6279       int l = e ? e - *environ : (int)strlen(*environ);
6280       if (bsiz < l + 1) {
6281         (void)safesysfree(buf);
6282         bsiz = l + 1; /* + 1 for the \0. */
6283         buf = (char*)safesysmalloc(bufsiz);
6284       } 
6285       memcpy(buf, *environ, l);
6286       buf[l] = '\0';
6287       (void)unsetenv(buf);
6288     }
6289     (void)safesysfree(buf);
6290 #        else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
6291     /* Just null environ and accept the leakage. */
6292     *environ = NULL;
6293 #        endif /* HAS_CLEARENV || HAS_UNSETENV */
6294 #      endif /* ! PERL_USE_SAFE_PUTENV */
6295     }
6296 #    endif /* USE_ENVIRON_ARRAY */
6297 #  endif /* PERL_IMPLICIT_SYS || WIN32 */
6298 #endif /* PERL_MICRO */
6299 }
6300
6301 #ifdef PERL_IMPLICIT_CONTEXT
6302
6303 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
6304 the global PL_my_cxt_index is incremented, and that value is assigned to
6305 that module's static my_cxt_index (who's address is passed as an arg).
6306 Then, for each interpreter this function is called for, it makes sure a
6307 void* slot is available to hang the static data off, by allocating or
6308 extending the interpreter's PL_my_cxt_list array */
6309
6310 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
6311 void *
6312 Perl_my_cxt_init(pTHX_ int *index, size_t size)
6313 {
6314     dVAR;
6315     void *p;
6316     PERL_ARGS_ASSERT_MY_CXT_INIT;
6317     if (*index == -1) {
6318         /* this module hasn't been allocated an index yet */
6319 #if defined(USE_ITHREADS)
6320         MUTEX_LOCK(&PL_my_ctx_mutex);
6321 #endif
6322         *index = PL_my_cxt_index++;
6323 #if defined(USE_ITHREADS)
6324         MUTEX_UNLOCK(&PL_my_ctx_mutex);
6325 #endif
6326     }
6327     
6328     /* make sure the array is big enough */
6329     if (PL_my_cxt_size <= *index) {
6330         if (PL_my_cxt_size) {
6331             while (PL_my_cxt_size <= *index)
6332                 PL_my_cxt_size *= 2;
6333             Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6334         }
6335         else {
6336             PL_my_cxt_size = 16;
6337             Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6338         }
6339     }
6340     /* newSV() allocates one more than needed */
6341     p = (void*)SvPVX(newSV(size-1));
6342     PL_my_cxt_list[*index] = p;
6343     Zero(p, size, char);
6344     return p;
6345 }
6346
6347 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6348
6349 int
6350 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
6351 {
6352     dVAR;
6353     int index;
6354
6355     PERL_ARGS_ASSERT_MY_CXT_INDEX;
6356
6357     for (index = 0; index < PL_my_cxt_index; index++) {
6358         const char *key = PL_my_cxt_keys[index];
6359         /* try direct pointer compare first - there are chances to success,
6360          * and it's much faster.
6361          */
6362         if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
6363             return index;
6364     }
6365     return -1;
6366 }
6367
6368 void *
6369 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
6370 {
6371     dVAR;
6372     void *p;
6373     int index;
6374
6375     PERL_ARGS_ASSERT_MY_CXT_INIT;
6376
6377     index = Perl_my_cxt_index(aTHX_ my_cxt_key);
6378     if (index == -1) {
6379         /* this module hasn't been allocated an index yet */
6380 #if defined(USE_ITHREADS)
6381         MUTEX_LOCK(&PL_my_ctx_mutex);
6382 #endif
6383         index = PL_my_cxt_index++;
6384 #if defined(USE_ITHREADS)
6385         MUTEX_UNLOCK(&PL_my_ctx_mutex);
6386 #endif
6387     }
6388
6389     /* make sure the array is big enough */
6390     if (PL_my_cxt_size <= index) {
6391         int old_size = PL_my_cxt_size;
6392         int i;
6393         if (PL_my_cxt_size) {
6394             while (PL_my_cxt_size <= index)
6395                 PL_my_cxt_size *= 2;
6396             Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6397             Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6398         }
6399         else {
6400             PL_my_cxt_size = 16;
6401             Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6402             Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6403         }
6404         for (i = old_size; i < PL_my_cxt_size; i++) {
6405             PL_my_cxt_keys[i] = 0;
6406             PL_my_cxt_list[i] = 0;
6407         }
6408     }
6409     PL_my_cxt_keys[index] = my_cxt_key;
6410     /* newSV() allocates one more than needed */
6411     p = (void*)SvPVX(newSV(size-1));
6412     PL_my_cxt_list[index] = p;
6413     Zero(p, size, char);
6414     return p;
6415 }
6416 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6417 #endif /* PERL_IMPLICIT_CONTEXT */
6418
6419 void
6420 Perl_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
6421                           STRLEN xs_len)
6422 {
6423     SV *sv;
6424     const char *vn = NULL;
6425     SV *const module = PL_stack_base[ax];
6426
6427     PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
6428
6429     if (items >= 2)      /* version supplied as bootstrap arg */
6430         sv = PL_stack_base[ax + 1];
6431     else {
6432         /* XXX GV_ADDWARN */
6433         vn = "XS_VERSION";
6434         sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6435         if (!sv || !SvOK(sv)) {
6436             vn = "VERSION";
6437             sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6438         }
6439     }
6440     if (sv) {
6441         SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
6442         SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version")
6443             ? sv : sv_2mortal(new_version(sv));
6444         xssv = upg_version(xssv, 0);
6445         if ( vcmp(pmsv,xssv) ) {
6446             SV *string = vstringify(xssv);
6447             SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
6448                                     " does not match ", module, string);
6449
6450             SvREFCNT_dec(string);
6451             string = vstringify(pmsv);
6452
6453             if (vn) {
6454                 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, module, vn,
6455                                string);
6456             } else {
6457                 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, string);
6458             }
6459             SvREFCNT_dec(string);
6460
6461             Perl_sv_2mortal(aTHX_ xpt);
6462             Perl_croak_sv(aTHX_ xpt);
6463         }
6464     }
6465 }
6466
6467 void
6468 Perl_xs_apiversion_bootcheck(pTHX_ SV *module, const char *api_p,
6469                              STRLEN api_len)
6470 {
6471     SV *xpt = NULL;
6472     SV *compver = Perl_newSVpvn_flags(aTHX_ api_p, api_len, SVs_TEMP);
6473     SV *runver;
6474
6475     PERL_ARGS_ASSERT_XS_APIVERSION_BOOTCHECK;
6476
6477     /* This might croak  */
6478     compver = upg_version(compver, 0);
6479     /* This should never croak */
6480     runver = new_version(PL_apiversion);
6481     if (vcmp(compver, runver)) {
6482         SV *compver_string = vstringify(compver);
6483         SV *runver_string = vstringify(runver);
6484         xpt = Perl_newSVpvf(aTHX_ "Perl API version %"SVf
6485                             " of %"SVf" does not match %"SVf,
6486                             compver_string, module, runver_string);
6487         Perl_sv_2mortal(aTHX_ xpt);
6488
6489         SvREFCNT_dec(compver_string);
6490         SvREFCNT_dec(runver_string);
6491     }
6492     SvREFCNT_dec(runver);
6493     if (xpt)
6494         Perl_croak_sv(aTHX_ xpt);
6495 }
6496
6497 #ifndef HAS_STRLCAT
6498 Size_t
6499 Perl_my_strlcat(char *dst, const char *src, Size_t size)
6500 {
6501     Size_t used, length, copy;
6502
6503     used = strlen(dst);
6504     length = strlen(src);
6505     if (size > 0 && used < size - 1) {
6506         copy = (length >= size - used) ? size - used - 1 : length;
6507         memcpy(dst + used, src, copy);
6508         dst[used + copy] = '\0';
6509     }
6510     return used + length;
6511 }
6512 #endif
6513
6514 #ifndef HAS_STRLCPY
6515 Size_t
6516 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
6517 {
6518     Size_t length, copy;
6519
6520     length = strlen(src);
6521     if (size > 0) {
6522         copy = (length >= size) ? size - 1 : length;
6523         memcpy(dst, src, copy);
6524         dst[copy] = '\0';
6525     }
6526     return length;
6527 }
6528 #endif
6529
6530 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
6531 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
6532 long _ftol( double ); /* Defined by VC6 C libs. */
6533 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
6534 #endif
6535
6536 PERL_STATIC_INLINE bool
6537 S_gv_has_usable_name(pTHX_ GV *gv)
6538 {
6539     GV **gvp;
6540     return GvSTASH(gv)
6541         && HvENAME(GvSTASH(gv))
6542         && (gvp = (GV **)hv_fetch(
6543                         GvSTASH(gv), GvNAME(gv),
6544                         GvNAMEUTF8(gv) ? -GvNAMELEN(gv) : GvNAMELEN(gv), 0
6545            ))
6546         && *gvp == gv;
6547 }
6548
6549 void
6550 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
6551 {
6552     dVAR;
6553     SV * const dbsv = GvSVn(PL_DBsub);
6554     const bool save_taint = PL_tainted;
6555
6556     /* When we are called from pp_goto (svp is null),
6557      * we do not care about using dbsv to call CV;
6558      * it's for informational purposes only.
6559      */
6560
6561     PERL_ARGS_ASSERT_GET_DB_SUB;
6562
6563     PL_tainted = FALSE;
6564     save_item(dbsv);
6565     if (!PERLDB_SUB_NN) {
6566         GV *gv = CvGV(cv);
6567
6568         if (!svp) {
6569             gv_efullname3(dbsv, gv, NULL);
6570         }
6571         else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
6572              || strEQ(GvNAME(gv), "END")
6573              || ( /* Could be imported, and old sub redefined. */
6574                  (GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv))
6575                  &&
6576                  !( (SvTYPE(*svp) == SVt_PVGV)
6577                     && (GvCV((const GV *)*svp) == cv)
6578                     /* Use GV from the stack as a fallback. */
6579                     && S_gv_has_usable_name(aTHX_ gv = (GV *)*svp) 
6580                   )
6581                 )
6582         ) {
6583             /* GV is potentially non-unique, or contain different CV. */
6584             SV * const tmp = newRV(MUTABLE_SV(cv));
6585             sv_setsv(dbsv, tmp);
6586             SvREFCNT_dec(tmp);
6587         }
6588         else {
6589             sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv)));
6590             sv_catpvs(dbsv, "::");
6591             sv_catpvn_flags(
6592               dbsv, GvNAME(gv), GvNAMELEN(gv),
6593               GvNAMEUTF8(gv) ? SV_CATUTF8 : SV_CATBYTES
6594             );
6595         }
6596     }
6597     else {
6598         const int type = SvTYPE(dbsv);
6599         if (type < SVt_PVIV && type != SVt_IV)
6600             sv_upgrade(dbsv, SVt_PVIV);
6601         (void)SvIOK_on(dbsv);
6602         SvIV_set(dbsv, PTR2IV(cv));     /* Do it the quickest way  */
6603     }
6604     TAINT_IF(save_taint);
6605 }
6606
6607 int
6608 Perl_my_dirfd(pTHX_ DIR * dir) {
6609
6610     /* Most dirfd implementations have problems when passed NULL. */
6611     if(!dir)
6612         return -1;
6613 #ifdef HAS_DIRFD
6614     return dirfd(dir);
6615 #elif defined(HAS_DIR_DD_FD)
6616     return dir->dd_fd;
6617 #else
6618     Perl_die(aTHX_ PL_no_func, "dirfd");
6619    /* NOT REACHED */
6620     return 0;
6621 #endif 
6622 }
6623
6624 REGEXP *
6625 Perl_get_re_arg(pTHX_ SV *sv) {
6626
6627     if (sv) {
6628         if (SvMAGICAL(sv))
6629             mg_get(sv);
6630         if (SvROK(sv))
6631             sv = MUTABLE_SV(SvRV(sv));
6632         if (SvTYPE(sv) == SVt_REGEXP)
6633             return (REGEXP*) sv;
6634     }
6635  
6636     return NULL;
6637 }
6638
6639 /*
6640  * Local variables:
6641  * c-indentation-style: bsd
6642  * c-basic-offset: 4
6643  * indent-tabs-mode: t
6644  * End:
6645  *
6646  * ex: set ts=8 sts=4 sw=4 noet:
6647  */