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