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