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