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