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
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.
12 * 'Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content.' --Gandalf to Pippin
15 * [p.598 of _The Lord of the Rings_, III/xi: "The PalantÃr"]
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.
25 #define PERL_IN_UTIL_C
29 #if defined(USE_PERLIO)
30 #include "perliol.h" /* For PerlIOUnix_refcnt */
36 # define SIG_ERR ((Sighandler_t) -1)
44 /* Missing protos on LynxOS */
49 # include "amigaos4/amigaio.h"
54 # include <sys/select.h>
58 #ifdef USE_C_BACKTRACE
62 # undef USE_BFD /* BFD is useless in OS X. */
72 # include <execinfo.h>
76 #ifdef PERL_DEBUG_READONLY_COW
77 # include <sys/mman.h>
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.
88 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
89 # define ALWAYS_NEED_THX
92 #if defined(PERL_TRACK_MEMPOOL) && defined(PERL_DEBUG_READONLY_COW)
94 S_maybe_protect_rw(pTHX_ struct perl_memory_debug_header *header)
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);
103 S_maybe_protect_ro(pTHX_ struct perl_memory_debug_header *header)
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);
110 # define maybe_protect_rw(foo) S_maybe_protect_rw(aTHX_ foo)
111 # define maybe_protect_ro(foo) S_maybe_protect_ro(aTHX_ foo)
113 # define maybe_protect_rw(foo) NOOP
114 # define maybe_protect_ro(foo) NOOP
117 #if defined(PERL_TRACK_MEMPOOL) || defined(PERL_DEBUG_READONLY_COW)
118 /* Use memory_debug_header */
120 # if (defined(PERL_POISON) && defined(PERL_TRACK_MEMPOOL)) \
121 || defined(PERL_DEBUG_READONLY_COW)
122 # define MDH_HAS_SIZE
127 =for apidoc_section $memory
128 =for apidoc safesysmalloc
129 Paranoid version of system's malloc()
135 Perl_safesysmalloc(MEM_SIZE size)
137 #ifdef ALWAYS_NEED_THX
144 if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
146 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
149 if ((SSize_t)size < 0)
150 Perl_croak_nocontext("panic: malloc, size=%" UVuf, (UV) size);
152 if (!size) size = 1; /* malloc(0) is NASTY on our system */
154 #ifdef PERL_DEBUG_READONLY_COW
155 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
156 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
157 perror("mmap failed");
161 ptr = (Malloc_t)PerlMem_malloc(size);
163 PERL_ALLOC_CHECK(ptr);
166 struct perl_memory_debug_header *const header
167 = (struct perl_memory_debug_header *)ptr;
171 PoisonNew(((char *)ptr), size, char);
174 #ifdef PERL_TRACK_MEMPOOL
175 header->interpreter = aTHX;
176 /* Link us into the list. */
177 header->prev = &PL_memory_debug_header;
178 header->next = PL_memory_debug_header.next;
179 PL_memory_debug_header.next = header;
180 maybe_protect_rw(header->next);
181 header->next->prev = header;
182 maybe_protect_ro(header->next);
183 # ifdef PERL_DEBUG_READONLY_COW
184 header->readonly = 0;
190 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
191 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
193 /* malloc() can modify errno() even on success, but since someone
194 writing perl code doesn't have any control over when perl calls
195 malloc() we need to hide that.
204 #ifndef ALWAYS_NEED_THX
217 =for apidoc safesysrealloc
218 Paranoid version of system's realloc()
224 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
226 #ifdef ALWAYS_NEED_THX
230 #ifdef PERL_DEBUG_READONLY_COW
231 const MEM_SIZE oldsize = where
232 ? ((struct perl_memory_debug_header *)((char *)where - PERL_MEMORY_DEBUG_HEADER_SIZE))->size
241 ptr = safesysmalloc(size);
246 where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
247 if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
249 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
251 struct perl_memory_debug_header *const header
252 = (struct perl_memory_debug_header *)where;
254 # ifdef PERL_TRACK_MEMPOOL
255 if (header->interpreter != aTHX) {
256 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
257 header->interpreter, aTHX);
259 assert(header->next->prev == header);
260 assert(header->prev->next == header);
262 if (header->size > size) {
263 const MEM_SIZE freed_up = header->size - size;
264 char *start_of_freed = ((char *)where) + size;
265 PoisonFree(start_of_freed, freed_up, char);
275 if ((SSize_t)size < 0)
276 Perl_croak_nocontext("panic: realloc, size=%" UVuf, (UV)size);
278 #ifdef PERL_DEBUG_READONLY_COW
279 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
280 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
281 perror("mmap failed");
284 Copy(where,ptr,oldsize < size ? oldsize : size,char);
285 if (munmap(where, oldsize)) {
286 perror("munmap failed");
290 ptr = (Malloc_t)PerlMem_realloc(where,size);
292 PERL_ALLOC_CHECK(ptr);
294 /* MUST do this fixup first, before doing ANYTHING else, as anything else
295 might allocate memory/free/move memory, and until we do the fixup, it
296 may well be chasing (and writing to) free memory. */
298 #ifdef PERL_TRACK_MEMPOOL
299 struct perl_memory_debug_header *const header
300 = (struct perl_memory_debug_header *)ptr;
303 if (header->size < size) {
304 const MEM_SIZE fresh = size - header->size;
305 char *start_of_fresh = ((char *)ptr) + size;
306 PoisonNew(start_of_fresh, fresh, char);
310 maybe_protect_rw(header->next);
311 header->next->prev = header;
312 maybe_protect_ro(header->next);
313 maybe_protect_rw(header->prev);
314 header->prev->next = header;
315 maybe_protect_ro(header->prev);
317 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
319 /* realloc() can modify errno() even on success, but since someone
320 writing perl code doesn't have any control over when perl calls
321 realloc() we need to hide that.
326 /* In particular, must do that fixup above before logging anything via
327 *printf(), as it can reallocate memory, which can cause SEGVs. */
329 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
330 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
337 #ifndef ALWAYS_NEED_THX
351 =for apidoc safesysfree
352 Safe version of system's free()
358 Perl_safesysfree(Malloc_t where)
360 #ifdef ALWAYS_NEED_THX
363 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
366 Malloc_t where_intrn = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
368 struct perl_memory_debug_header *const header
369 = (struct perl_memory_debug_header *)where_intrn;
372 const MEM_SIZE size = header->size;
374 # ifdef PERL_TRACK_MEMPOOL
375 if (header->interpreter != aTHX) {
376 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
377 header->interpreter, aTHX);
380 Perl_croak_nocontext("panic: duplicate free");
383 Perl_croak_nocontext("panic: bad free, header->next==NULL");
384 if (header->next->prev != header || header->prev->next != header) {
385 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
386 "header=%p, ->prev->next=%p",
387 header->next->prev, header,
390 /* Unlink us from the chain. */
391 maybe_protect_rw(header->next);
392 header->next->prev = header->prev;
393 maybe_protect_ro(header->next);
394 maybe_protect_rw(header->prev);
395 header->prev->next = header->next;
396 maybe_protect_ro(header->prev);
397 maybe_protect_rw(header);
399 PoisonNew(where_intrn, size, char);
401 /* Trigger the duplicate free warning. */
404 # ifdef PERL_DEBUG_READONLY_COW
405 if (munmap(where_intrn, size)) {
406 perror("munmap failed");
412 Malloc_t where_intrn = where;
414 #ifndef PERL_DEBUG_READONLY_COW
415 PerlMem_free(where_intrn);
421 =for apidoc safesyscalloc
422 Safe version of system's calloc()
428 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
430 #ifdef ALWAYS_NEED_THX
434 #if defined(USE_MDH) || defined(DEBUGGING)
435 MEM_SIZE total_size = 0;
438 /* Even though calloc() for zero bytes is strange, be robust. */
439 if (size && (count <= MEM_SIZE_MAX / size)) {
440 #if defined(USE_MDH) || defined(DEBUGGING)
441 total_size = size * count;
447 if (PERL_MEMORY_DEBUG_HEADER_SIZE <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
448 total_size += PERL_MEMORY_DEBUG_HEADER_SIZE;
453 if ((SSize_t)size < 0 || (SSize_t)count < 0)
454 Perl_croak_nocontext("panic: calloc, size=%" UVuf ", count=%" UVuf,
455 (UV)size, (UV)count);
457 #ifdef PERL_DEBUG_READONLY_COW
458 if ((ptr = mmap(0, total_size ? total_size : 1, PROT_READ|PROT_WRITE,
459 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
460 perror("mmap failed");
463 #elif defined(PERL_TRACK_MEMPOOL)
464 /* Have to use malloc() because we've added some space for our tracking
466 /* malloc(0) is non-portable. */
467 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
469 /* Use calloc() because it might save a memset() if the memory is fresh
470 and clean from the OS. */
472 ptr = (Malloc_t)PerlMem_calloc(count, size);
473 else /* calloc(0) is non-portable. */
474 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
476 PERL_ALLOC_CHECK(ptr);
477 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));
481 struct perl_memory_debug_header *const header
482 = (struct perl_memory_debug_header *)ptr;
484 # ifndef PERL_DEBUG_READONLY_COW
485 memset((void*)ptr, 0, total_size);
487 # ifdef PERL_TRACK_MEMPOOL
488 header->interpreter = aTHX;
489 /* Link us into the list. */
490 header->prev = &PL_memory_debug_header;
491 header->next = PL_memory_debug_header.next;
492 PL_memory_debug_header.next = header;
493 maybe_protect_rw(header->next);
494 header->next->prev = header;
495 maybe_protect_ro(header->next);
496 # ifdef PERL_DEBUG_READONLY_COW
497 header->readonly = 0;
501 header->size = total_size;
503 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
509 #ifndef ALWAYS_NEED_THX
518 /* These must be defined when not using Perl's malloc for binary
523 Malloc_t Perl_malloc (MEM_SIZE nbytes)
525 #ifdef PERL_IMPLICIT_SYS
528 return (Malloc_t)PerlMem_malloc(nbytes);
531 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
533 #ifdef PERL_IMPLICIT_SYS
536 return (Malloc_t)PerlMem_calloc(elements, size);
539 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
541 #ifdef PERL_IMPLICIT_SYS
544 return (Malloc_t)PerlMem_realloc(where, nbytes);
547 Free_t Perl_mfree (Malloc_t where)
549 #ifdef PERL_IMPLICIT_SYS
557 /* This is the value stored in *retlen in the two delimcpy routines below when
558 * there wasn't enough room in the destination to store everything it was asked
559 * to. The value is deliberately very large so that hopefully if code uses it
560 * unquestioninly to access memory, it will likely segfault. And it is small
561 * enough that if the caller does some arithmetic on it before accessing, it
562 * won't overflow into a small legal number. */
563 #define DELIMCPY_OUT_OF_BOUNDS_RET I32_MAX
566 =for apidoc_section $string
567 =for apidoc delimcpy_no_escape
569 Copy a source buffer to a destination buffer, stopping at (but not including)
570 the first occurrence in the source of the delimiter byte, C<delim>. The source
571 is the bytes between S<C<from> and C<from_end> - 1>. Similarly, the dest is
572 C<to> up to C<to_end>.
574 The number of bytes copied is written to C<*retlen>.
576 Returns the position of C<delim> in the C<from> buffer, but if there is no
577 such occurrence before C<from_end>, then C<from_end> is returned, and the entire
578 buffer S<C<from> .. C<from_end> - 1> is copied.
580 If there is room in the destination available after the copy, an extra
581 terminating safety C<NUL> byte is appended (not included in the returned
584 The error case is if the destination buffer is not large enough to accommodate
585 everything that should be copied. In this situation, a value larger than
586 S<C<to_end> - C<to>> is written to C<*retlen>, and as much of the source as
587 fits will be written to the destination. Not having room for the safety C<NUL>
588 is not considered an error.
593 Perl_delimcpy_no_escape(char *to, const char *to_end,
594 const char *from, const char *from_end,
595 const int delim, I32 *retlen)
597 const char * delim_pos;
598 Ptrdiff_t from_len = from_end - from;
599 Ptrdiff_t to_len = to_end - to;
602 PERL_ARGS_ASSERT_DELIMCPY_NO_ESCAPE;
604 assert(from_len >= 0);
607 /* Look for the first delimiter in the source */
608 delim_pos = (const char *) memchr(from, delim, from_len);
610 /* Copy up to where the delimiter was found, or the entire buffer if not
612 copy_len = (delim_pos) ? delim_pos - from : from_len;
614 /* If not enough room, copy as much as can fit, and set error return */
615 if (copy_len > to_len) {
616 Copy(from, to, to_len, char);
617 *retlen = DELIMCPY_OUT_OF_BOUNDS_RET;
620 Copy(from, to, copy_len, char);
622 /* If there is extra space available, add a trailing NUL */
623 if (copy_len < to_len) {
630 return (char *) from + copy_len;
636 Copy a source buffer to a destination buffer, stopping at (but not including)
637 the first occurrence in the source of an unescaped (defined below) delimiter
638 byte, C<delim>. The source is the bytes between S<C<from> and C<from_end> -
639 1>. Similarly, the dest is C<to> up to C<to_end>.
641 The number of bytes copied is written to C<*retlen>.
643 Returns the position of the first uncopied C<delim> in the C<from> buffer, but
644 if there is no such occurrence before C<from_end>, then C<from_end> is returned,
645 and the entire buffer S<C<from> .. C<from_end> - 1> is copied.
647 If there is room in the destination available after the copy, an extra
648 terminating safety C<NUL> byte is appended (not included in the returned
651 The error case is if the destination buffer is not large enough to accommodate
652 everything that should be copied. In this situation, a value larger than
653 S<C<to_end> - C<to>> is written to C<*retlen>, and as much of the source as
654 fits will be written to the destination. Not having room for the safety C<NUL>
655 is not considered an error.
657 In the following examples, let C<x> be the delimiter, and C<0> represent a C<NUL>
658 byte (B<NOT> the digit C<0>). Then we would have
663 provided the destination buffer is at least 4 bytes long.
665 An escaped delimiter is one which is immediately preceded by a single
666 backslash. Escaped delimiters are copied, and the copy continues past the
667 delimiter; the backslash is not copied:
672 (provided the destination buffer is at least 8 bytes long).
674 It's actually somewhat more complicated than that. A sequence of any odd number
675 of backslashes escapes the following delimiter, and the copy continues with
676 exactly one of the backslashes stripped.
680 abc\\\xdef abc\\xdef0
681 abc\\\\\xdef abc\\\\xdef0
683 (as always, if the destination is large enough)
685 An even number of preceding backslashes does not escape the delimiter, so that
686 the copy stops just before it, and includes all the backslashes (no stripping;
687 zero is considered even):
698 Perl_delimcpy(char *to, const char *to_end,
699 const char *from, const char *from_end,
700 const int delim, I32 *retlen)
702 const char * const orig_to = to;
703 Ptrdiff_t copy_len = 0;
704 bool stopped_early = FALSE; /* Ran out of room to copy to */
706 PERL_ARGS_ASSERT_DELIMCPY;
707 assert(from_end >= from);
708 assert(to_end >= to);
710 /* Don't use the loop for the trivial case of the first character being the
711 * delimiter; otherwise would have to worry inside the loop about backing
712 * up before the start of 'from' */
713 if (LIKELY(from_end > from && *from != delim)) {
714 while ((copy_len = from_end - from) > 0) {
715 const char * backslash_pos;
716 const char * delim_pos;
718 /* Look for the next delimiter in the remaining portion of the
719 * source. A loop invariant is that we already know that the copy
720 * should include *from; this comes from the conditional before the
721 * loop, and how we set things up at the end of each iteration */
722 delim_pos = (const char *) memchr(from + 1, delim, copy_len - 1);
724 /* If didn't find it, done looking; set up so copies all of the
727 copy_len = from_end - from;
731 /* Look for a backslash immediately before the delimiter */
732 backslash_pos = delim_pos - 1;
734 /* If the delimiter is not escaped, this ends the copy */
735 if (*backslash_pos != '\\') {
736 copy_len = delim_pos - from;
740 /* Here there is a backslash just before the delimiter, but it
741 * could be the final backslash in a sequence of them. Backup to
742 * find the first one in it. */
746 while (backslash_pos >= from && *backslash_pos == '\\');
748 /* If the number of backslashes is even, they just escape one
749 * another, leaving the delimiter unescaped, and stopping the copy.
751 if (! ((delim_pos - (backslash_pos + 1)) & 1)) {
752 copy_len = delim_pos - from; /* even, copy up to delimiter */
756 /* Here is odd, so the delimiter is escaped. We will try to copy
757 * all but the final backslash in the sequence */
758 copy_len = delim_pos - 1 - from;
760 /* Do the copy, but not beyond the end of the destination */
761 if (copy_len >= to_end - to) {
762 Copy(from, to, to_end - to, char);
763 stopped_early = TRUE;
764 to = (char *) to_end;
767 Copy(from, to, copy_len, char);
771 /* Set up so next iteration will include the delimiter */
776 /* Here, have found the final segment to copy. Copy that, but not beyond
777 * the size of the destination. If not enough room, copy as much as can
778 * fit, and set error return */
779 if (stopped_early || copy_len > to_end - to) {
780 Copy(from, to, to_end - to, char);
781 *retlen = DELIMCPY_OUT_OF_BOUNDS_RET;
784 Copy(from, to, copy_len, char);
788 /* If there is extra space available, add a trailing NUL */
793 *retlen = to - orig_to;
796 return (char *) from + copy_len;
802 Find the first (leftmost) occurrence of a sequence of bytes within another
803 sequence. This is the Perl version of C<strstr()>, extended to handle
804 arbitrary sequences, potentially containing embedded C<NUL> characters (C<NUL>
805 is what the initial C<n> in the function name stands for; some systems have an
806 equivalent, C<memmem()>, but with a somewhat different API).
808 Another way of thinking about this function is finding a needle in a haystack.
809 C<big> points to the first byte in the haystack. C<big_end> points to one byte
810 beyond the final byte in the haystack. C<little> points to the first byte in
811 the needle. C<little_end> points to one byte beyond the final byte in the
812 needle. All the parameters must be non-C<NULL>.
814 The function returns C<NULL> if there is no occurrence of C<little> within
815 C<big>. If C<little> is the empty string, C<big> is returned.
817 Because this function operates at the byte level, and because of the inherent
818 characteristics of UTF-8 (or UTF-EBCDIC), it will work properly if both the
819 needle and the haystack are strings with the same UTF-8ness, but not if the
827 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
829 PERL_ARGS_ASSERT_NINSTR;
832 return ninstr(big, bigend, little, lend);
835 if (little >= lend) {
839 const U8 first = *little;
842 /* No match can start closer to the end of the haystack than the length
844 bigend -= lend - little;
845 little++; /* Look for 'first', then the remainder is in here */
846 lsize = lend - little;
848 while (big <= bigend) {
849 big = (char *) memchr((U8 *) big, first, bigend - big + 1);
850 if (big == NULL || big > bigend) {
854 if (memEQ(big + 1, little, lsize)) {
870 Like C<L</ninstr>>, but instead finds the final (rightmost) occurrence of a
871 sequence of bytes within another sequence, returning C<NULL> if there is no
879 Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
881 const Ptrdiff_t little_len = lend - little;
882 const Ptrdiff_t big_len = bigend - big;
884 PERL_ARGS_ASSERT_RNINSTR;
886 /* A non-existent needle trivially matches the rightmost possible position
888 if (UNLIKELY(little_len <= 0)) {
889 return (char*)bigend;
892 /* If the needle is larger than the haystack, the needle can't possibly fit
893 * inside the haystack. */
894 if (UNLIKELY(little_len > big_len)) {
898 /* Special case length 1 needles. It's trivial if we have memrchr();
899 * and otherwise we just do a per-byte search backwards.
901 * XXX When we don't have memrchr, we could use something like
902 * S_find_next_masked( or S_find_span_end() to do per-word searches */
903 if (little_len == 1) {
904 const char final = *little;
908 return (char *) memrchr(big, final, big_len);
910 const char * cur = bigend - 1;
916 } while (--cur >= big);
922 else { /* Below, the needle is longer than a single byte */
924 /* We search backwards in the haystack for the final character of the
925 * needle. Each time one is found, we see if the characters just
926 * before it in the haystack match the rest of the needle. */
927 const char final = *(lend - 1);
929 /* What matches consists of 'little_len'-1 characters, then the final
931 const Size_t prefix_len = little_len - 1;
933 /* If the final character in the needle is any closer than this to the
934 * left edge, there wouldn't be enough room for all of it to fit in the
936 const char * const left_fence = big + prefix_len;
938 /* Start at the right edge */
939 char * cur = (char *) bigend;
941 /* memrchr() makes the search easy (and fast); otherwise, look
942 * backwards byte-by-byte. */
947 cur = (char *) memrchr(left_fence, final, cur - left_fence);
954 if (cur < left_fence) {
958 while (*cur != final);
961 /* Here, we know that *cur is 'final'; see if the preceding bytes
962 * of the needle also match the corresponding haystack bytes */
963 if memEQ(cur - prefix_len, little, prefix_len) {
964 return cur - prefix_len;
966 } while (cur > left_fence);
972 /* As a space optimization, we do not compile tables for strings of length
973 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
974 special-cased in fbm_instr().
976 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
980 =for apidoc fbm_compile
982 Analyzes the string in order to make fast searches on it using C<fbm_instr()>
983 -- the Boyer-Moore algorithm.
989 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
996 PERL_ARGS_ASSERT_FBM_COMPILE;
998 if (isGV_with_GP(sv) || SvROK(sv))
1004 if (flags & FBMcf_TAIL) {
1005 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
1006 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
1007 if (mg && mg->mg_len >= 0)
1010 if (!SvPOK(sv) || SvNIOKp(sv))
1011 s = (U8*)SvPV_force_mutable(sv, len);
1012 else s = (U8 *)SvPV_mutable(sv, len);
1013 if (len == 0) /* TAIL might be on a zero-length string. */
1015 SvUPGRADE(sv, SVt_PVMG);
1019 /* add PERL_MAGIC_bm magic holding the FBM lookup table */
1021 assert(!mg_find(sv, PERL_MAGIC_bm));
1022 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
1026 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
1028 const U8 mlen = (len>255) ? 255 : (U8)len;
1029 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
1032 Newx(table, 256, U8);
1033 memset((void*)table, mlen, 256);
1034 mg->mg_ptr = (char *)table;
1037 s += len - 1; /* last char */
1040 if (table[*s] == mlen)
1046 BmUSEFUL(sv) = 100; /* Initial value */
1047 ((XPVNV*)SvANY(sv))->xnv_u.xnv_bm_tail = cBOOL(flags & FBMcf_TAIL);
1052 =for apidoc fbm_instr
1054 Returns the location of the SV in the string delimited by C<big> and
1055 C<bigend> (C<bigend>) is the char following the last char).
1056 It returns C<NULL> if the string can't be found. The C<sv>
1057 does not have to be C<fbm_compiled>, but the search will not be as fast
1062 If SvTAIL(littlestr) is true, a fake "\n" was appended to the string
1063 during FBM compilation due to FBMcf_TAIL in flags. It indicates that
1064 the littlestr must be anchored to the end of bigstr (or to any \n if
1067 E.g. The regex compiler would compile /abc/ to a littlestr of "abc",
1068 while /abc$/ compiles to "abc\n" with SvTAIL() true.
1070 A littlestr of "abc", !SvTAIL matches as /abc/;
1071 a littlestr of "ab\n", SvTAIL matches as:
1072 without FBMrf_MULTILINE: /ab\n?\z/
1073 with FBMrf_MULTILINE: /ab\n/ || /ab\z/;
1075 (According to Ilya from 1999; I don't know if this is still true, DAPM 2015):
1076 "If SvTAIL is actually due to \Z or \z, this gives false positives
1082 Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
1086 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
1087 STRLEN littlelen = l;
1088 const I32 multiline = flags & FBMrf_MULTILINE;
1089 bool valid = SvVALID(littlestr);
1090 bool tail = valid ? cBOOL(SvTAIL(littlestr)) : FALSE;
1092 PERL_ARGS_ASSERT_FBM_INSTR;
1094 assert(bigend >= big);
1096 if ((STRLEN)(bigend - big) < littlelen) {
1098 && ((STRLEN)(bigend - big) == littlelen - 1)
1100 || (*big == *little &&
1101 memEQ((char *)big, (char *)little, littlelen - 1))))
1106 switch (littlelen) { /* Special cases for 0, 1 and 2 */
1108 return (char*)big; /* Cannot be SvTAIL! */
1111 if (tail && !multiline) /* Anchor only! */
1112 /* [-1] is safe because we know that bigend != big. */
1113 return (char *) (bigend - (bigend[-1] == '\n'));
1115 s = (unsigned char *)memchr((void*)big, *little, bigend-big);
1119 return (char *) bigend;
1123 if (tail && !multiline) {
1124 /* a littlestr with SvTAIL must be of the form "X\n" (where X
1125 * is a single char). It is anchored, and can only match
1126 * "....X\n" or "....X" */
1127 if (bigend[-2] == *little && bigend[-1] == '\n')
1128 return (char*)bigend - 2;
1129 if (bigend[-1] == *little)
1130 return (char*)bigend - 1;
1135 /* memchr() is likely to be very fast, possibly using whatever
1136 * hardware support is available, such as checking a whole
1137 * cache line in one instruction.
1138 * So for a 2 char pattern, calling memchr() is likely to be
1139 * faster than running FBM, or rolling our own. The previous
1140 * version of this code was roll-your-own which typically
1141 * only needed to read every 2nd char, which was good back in
1142 * the day, but no longer.
1144 unsigned char c1 = little[0];
1145 unsigned char c2 = little[1];
1147 /* *** for all this case, bigend points to the last char,
1148 * not the trailing \0: this makes the conditions slightly
1153 while (s < bigend) {
1154 /* do a quick test for c1 before calling memchr();
1155 * this avoids the expensive fn call overhead when
1156 * there are lots of c1's */
1157 if (LIKELY(*s != c1)) {
1159 s = (unsigned char *)memchr((void*)s, c1, bigend - s);
1166 /* failed; try searching for c2 this time; that way
1167 * we don't go pathologically slow when the string
1168 * consists mostly of c1's or vice versa.
1173 s = (unsigned char *)memchr((void*)s, c2, bigend - s + 1);
1177 return (char*)s - 1;
1181 /* c1, c2 the same */
1182 while (s < bigend) {
1191 s = (unsigned char *)memchr((void*)s, c1, bigend - s);
1192 if (!s || s >= bigend)
1199 /* failed to find 2 chars; try anchored match at end without
1201 if (tail && bigend[0] == little[0])
1202 return (char *)bigend;
1207 break; /* Only lengths 0 1 and 2 have special-case code. */
1210 if (tail && !multiline) { /* tail anchored? */
1211 s = bigend - littlelen;
1212 if (s >= big && bigend[-1] == '\n' && *s == *little
1213 /* Automatically of length > 2 */
1214 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1216 return (char*)s; /* how sweet it is */
1219 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
1221 return (char*)s + 1; /* how sweet it is */
1227 /* not compiled; use Perl_ninstr() instead */
1228 char * const b = ninstr((char*)big,(char*)bigend,
1229 (char*)little, (char*)little + littlelen);
1231 assert(!tail); /* valid => FBM; tail only set on SvVALID SVs */
1235 /* Do actual FBM. */
1236 if (littlelen > (STRLEN)(bigend - big))
1240 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
1241 const unsigned char *oldlittle;
1245 --littlelen; /* Last char found by table lookup */
1247 s = big + littlelen;
1248 little += littlelen; /* last char */
1251 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
1252 const unsigned char lastc = *little;
1256 if ((tmp = table[*s])) {
1257 /* *s != lastc; earliest position it could match now is
1258 * tmp slots further on */
1259 if ((s += tmp) >= bigend)
1261 if (LIKELY(*s != lastc)) {
1263 s = (unsigned char *)memchr((void*)s, lastc, bigend - s);
1273 /* hand-rolled strncmp(): less expensive than calling the
1274 * real function (maybe???) */
1276 unsigned char * const olds = s;
1281 if (*--s == *--little)
1283 s = olds + 1; /* here we pay the price for failure */
1285 if (s < bigend) /* fake up continue to outer loop */
1295 && memEQ((char *)(bigend - littlelen),
1296 (char *)(oldlittle - littlelen), littlelen) )
1297 return (char*)bigend - littlelen;
1303 Perl_cntrl_to_mnemonic(const U8 c)
1305 /* Returns the mnemonic string that represents character 'c', if one
1306 * exists; NULL otherwise. The only ones that exist for the purposes of
1307 * this routine are a few control characters */
1310 case '\a': return "\\a";
1311 case '\b': return "\\b";
1312 case ESC_NATIVE: return "\\e";
1313 case '\f': return "\\f";
1314 case '\n': return "\\n";
1315 case '\r': return "\\r";
1316 case '\t': return "\\t";
1322 /* copy a string to a safe spot */
1325 =for apidoc_section $string
1328 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1329 string which is a duplicate of C<pv>. The size of the string is
1330 determined by C<strlen()>, which means it may not contain embedded C<NUL>
1331 characters and must have a trailing C<NUL>. To prevent memory leaks, the
1332 memory allocated for the new string needs to be freed when no longer needed.
1333 This can be done with the C<L</Safefree>> function, or
1334 L<C<SAVEFREEPV>|perlguts/SAVEFREEPV(p)>.
1336 On some platforms, Windows for example, all allocated memory owned by a thread
1337 is deallocated when that thread ends. So if you need that not to happen, you
1338 need to use the shared memory functions, such as C<L</savesharedpv>>.
1344 Perl_savepv(pTHX_ const char *pv)
1346 PERL_UNUSED_CONTEXT;
1351 const STRLEN pvlen = strlen(pv)+1;
1352 Newx(newaddr, pvlen, char);
1353 return (char*)memcpy(newaddr, pv, pvlen);
1357 /* same thing but with a known length */
1362 Perl's version of what C<strndup()> would be if it existed. Returns a
1363 pointer to a newly allocated string which is a duplicate of the first
1364 C<len> bytes from C<pv>, plus a trailing
1365 C<NUL> byte. The memory allocated for
1366 the new string can be freed with the C<Safefree()> function.
1368 On some platforms, Windows for example, all allocated memory owned by a thread
1369 is deallocated when that thread ends. So if you need that not to happen, you
1370 need to use the shared memory functions, such as C<L</savesharedpvn>>.
1376 Perl_savepvn(pTHX_ const char *pv, Size_t len)
1379 PERL_UNUSED_CONTEXT;
1381 Newx(newaddr,len+1,char);
1382 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1384 /* might not be null terminated */
1385 newaddr[len] = '\0';
1386 return (char *) CopyD(pv,newaddr,len,char);
1389 return (char *) ZeroD(newaddr,len+1,char);
1394 =for apidoc savesharedpv
1396 A version of C<savepv()> which allocates the duplicate string in memory
1397 which is shared between threads.
1402 Perl_savesharedpv(pTHX_ const char *pv)
1407 PERL_UNUSED_CONTEXT;
1412 pvlen = strlen(pv)+1;
1413 newaddr = (char*)PerlMemShared_malloc(pvlen);
1417 return (char*)memcpy(newaddr, pv, pvlen);
1421 =for apidoc savesharedpvn
1423 A version of C<savepvn()> which allocates the duplicate string in memory
1424 which is shared between threads. (With the specific difference that a C<NULL>
1425 pointer is not acceptable)
1430 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1432 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1434 PERL_UNUSED_CONTEXT;
1435 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1440 newaddr[len] = '\0';
1441 return (char*)memcpy(newaddr, pv, len);
1445 =for apidoc savesvpv
1447 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1448 the passed in SV using C<SvPV()>
1450 On some platforms, Windows for example, all allocated memory owned by a thread
1451 is deallocated when that thread ends. So if you need that not to happen, you
1452 need to use the shared memory functions, such as C<L</savesharedsvpv>>.
1458 Perl_savesvpv(pTHX_ SV *sv)
1461 const char * const pv = SvPV_const(sv, len);
1464 PERL_ARGS_ASSERT_SAVESVPV;
1467 Newx(newaddr,len,char);
1468 return (char *) CopyD(pv,newaddr,len,char);
1472 =for apidoc savesharedsvpv
1474 A version of C<savesharedpv()> which allocates the duplicate string in
1475 memory which is shared between threads.
1481 Perl_savesharedsvpv(pTHX_ SV *sv)
1484 const char * const pv = SvPV_const(sv, len);
1486 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1488 return savesharedpvn(pv, len);
1491 /* the SV for Perl_form() and mess() is not kept in an arena */
1499 if (PL_phase != PERL_PHASE_DESTRUCT)
1500 return newSVpvs_flags("", SVs_TEMP);
1505 /* Create as PVMG now, to avoid any upgrading later */
1507 Newxz(any, 1, XPVMG);
1508 SvFLAGS(sv) = SVt_PVMG;
1509 SvANY(sv) = (void*)any;
1511 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1516 #if defined(MULTIPLICITY)
1518 Perl_form_nocontext(const char* pat, ...)
1523 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1524 va_start(args, pat);
1525 retval = vform(pat, &args);
1529 #endif /* MULTIPLICITY */
1532 =for apidoc_section $display
1534 =for apidoc_item form_nocontext
1536 These take a sprintf-style format pattern and conventional
1537 (non-SV) arguments and return the formatted string.
1539 (char *) Perl_form(pTHX_ const char* pat, ...)
1541 can be used any place a string (char *) is required:
1543 char * s = Perl_form("%d.%d",major,minor);
1545 They use a single (per-thread) private buffer so if you want to format several
1546 strings you must explicitly copy the earlier strings away (and free the copies
1549 The two forms differ only in that C<form_nocontext> does not take a thread
1550 context (C<aTHX>) parameter, so is used in situations where the caller doesn't
1551 already have the thread context.
1554 Like C<L</form>> but but the arguments are an encapsulated argument list.
1560 Perl_form(pTHX_ const char* pat, ...)
1564 PERL_ARGS_ASSERT_FORM;
1565 va_start(args, pat);
1566 retval = vform(pat, &args);
1572 Perl_vform(pTHX_ const char *pat, va_list *args)
1574 SV * const sv = mess_alloc();
1575 PERL_ARGS_ASSERT_VFORM;
1576 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1582 =for apidoc_item mess_nocontext
1584 These take a sprintf-style format pattern and argument list, which are used to
1585 generate a string message. If the message does not end with a newline, then it
1586 will be extended with some indication of the current location in the code, as
1587 described for C<L</mess_sv>>.
1589 Normally, the resulting message is returned in a new mortal SV.
1590 But during global destruction a single SV may be shared between uses of
1593 The two forms differ only in that C<mess_nocontext> does not take a thread
1594 context (C<aTHX>) parameter, so is used in situations where the caller doesn't
1595 already have the thread context.
1600 #if defined(MULTIPLICITY)
1602 Perl_mess_nocontext(const char *pat, ...)
1607 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1608 va_start(args, pat);
1609 retval = vmess(pat, &args);
1613 #endif /* MULTIPLICITY */
1616 Perl_mess(pTHX_ const char *pat, ...)
1620 PERL_ARGS_ASSERT_MESS;
1621 va_start(args, pat);
1622 retval = vmess(pat, &args);
1628 Perl_closest_cop(pTHX_ const COP *cop, const OP *o, const OP *curop,
1631 /* Look for curop starting from o. cop is the last COP we've seen. */
1632 /* opnext means that curop is actually the ->op_next of the op we are
1635 PERL_ARGS_ASSERT_CLOSEST_COP;
1637 if (!o || !curop || (
1638 opnext ? o->op_next == curop && o->op_type != OP_SCOPE : o == curop
1642 if (o->op_flags & OPf_KIDS) {
1644 for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
1647 /* If the OP_NEXTSTATE has been optimised away we can still use it
1648 * the get the file and line number. */
1650 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1651 cop = (const COP *)kid;
1653 /* Keep searching, and return when we've found something. */
1655 new_cop = closest_cop(cop, kid, curop, opnext);
1661 /* Nothing found. */
1669 Expands a message, intended for the user, to include an indication of
1670 the current location in the code, if the message does not already appear
1673 C<basemsg> is the initial message or object. If it is a reference, it
1674 will be used as-is and will be the result of this function. Otherwise it
1675 is used as a string, and if it already ends with a newline, it is taken
1676 to be complete, and the result of this function will be the same string.
1677 If the message does not end with a newline, then a segment such as C<at
1678 foo.pl line 37> will be appended, and possibly other clauses indicating
1679 the current state of execution. The resulting message will end with a
1682 Normally, the resulting message is returned in a new mortal SV.
1683 During global destruction a single SV may be shared between uses of this
1684 function. If C<consume> is true, then the function is permitted (but not
1685 required) to modify and return C<basemsg> instead of allocating a new SV.
1691 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1695 #if defined(USE_C_BACKTRACE) && defined(USE_C_BACKTRACE_ON_ERROR)
1699 /* The PERL_C_BACKTRACE_ON_WARN must be an integer of one or more. */
1700 if ((ws = PerlEnv_getenv("PERL_C_BACKTRACE_ON_ERROR"))
1701 && grok_atoUV(ws, &wi, NULL)
1702 && wi <= PERL_INT_MAX
1704 Perl_dump_c_backtrace(aTHX_ Perl_debug_log, (int)wi, 1);
1709 PERL_ARGS_ASSERT_MESS_SV;
1711 if (SvROK(basemsg)) {
1717 sv_setsv(sv, basemsg);
1722 if (SvPOK(basemsg) && consume) {
1727 sv_copypv(sv, basemsg);
1730 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1732 * Try and find the file and line for PL_op. This will usually be
1733 * PL_curcop, but it might be a cop that has been optimised away. We
1734 * can try to find such a cop by searching through the optree starting
1735 * from the sibling of PL_curcop.
1740 closest_cop(PL_curcop, OpSIBLING(PL_curcop), PL_op, FALSE);
1745 Perl_sv_catpvf(aTHX_ sv, " at %s line %" IVdf,
1746 OutCopFILE(cop), (IV)CopLINE(cop));
1749 /* Seems that GvIO() can be untrustworthy during global destruction. */
1750 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1751 && IoLINES(GvIOp(PL_last_in_gv)))
1754 const bool line_mode = (RsSIMPLE(PL_rs) &&
1755 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1756 Perl_sv_catpvf(aTHX_ sv, ", <%" SVf "> %s %" IVdf,
1757 SVfARG(PL_last_in_gv == PL_argvgv
1759 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1760 line_mode ? "line" : "chunk",
1761 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1763 if (PL_phase == PERL_PHASE_DESTRUCT)
1764 sv_catpvs(sv, " during global destruction");
1765 sv_catpvs(sv, ".\n");
1773 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1774 argument list, respectively. These are used to generate a string message. If
1776 message does not end with a newline, then it will be extended with
1777 some indication of the current location in the code, as described for
1780 Normally, the resulting message is returned in a new mortal SV.
1781 During global destruction a single SV may be shared between uses of
1788 Perl_vmess(pTHX_ const char *pat, va_list *args)
1790 SV * const sv = mess_alloc();
1792 PERL_ARGS_ASSERT_VMESS;
1794 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1795 return mess_sv(sv, 1);
1799 Perl_write_to_stderr(pTHX_ SV* msv)
1804 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1806 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1807 && (io = GvIO(PL_stderrgv))
1808 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1809 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, SV_CONST(PRINT),
1810 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1812 PerlIO * const serr = Perl_error_log;
1814 do_print(msv, serr);
1815 (void)PerlIO_flush(serr);
1820 =for apidoc_section $warning
1823 /* Common code used in dieing and warning */
1826 S_with_queued_errors(pTHX_ SV *ex)
1828 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1829 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1830 sv_catsv(PL_errors, ex);
1831 ex = sv_mortalcopy(PL_errors);
1832 SvCUR_set(PL_errors, 0);
1838 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1843 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1844 /* sv_2cv might call Perl_croak() or Perl_warner() */
1845 SV * const oldhook = *hook;
1847 if (!oldhook || oldhook == PERL_WARNHOOK_FATAL)
1853 cv = sv_2cv(oldhook, &stash, &gv, 0);
1855 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1865 exarg = newSVsv(ex);
1866 SvREADONLY_on(exarg);
1869 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1873 call_sv(MUTABLE_SV(cv), G_DISCARD);
1883 =for apidoc_item die_nocontext
1885 These ehave the same as L</croak_sv>, except for the return type.
1886 It should be used only where the C<OP *> return type is required.
1887 The functions never actually return.
1889 The two forms differ only in that C<die_nocontext> does not take a thread
1890 context (C<aTHX>) parameter, so is used in situations where the caller doesn't
1891 already have the thread context.
1896 /* silence __declspec(noreturn) warnings */
1897 MSVC_DIAG_IGNORE(4646 4645)
1899 Perl_die_sv(pTHX_ SV *baseex)
1901 PERL_ARGS_ASSERT_DIE_SV;
1904 NORETURN_FUNCTION_END;
1911 Behaves the same as L</croak>, except for the return type.
1912 It should be used only where the C<OP *> return type is required.
1913 The function never actually returns.
1918 #if defined(MULTIPLICITY)
1920 /* silence __declspec(noreturn) warnings */
1921 MSVC_DIAG_IGNORE(4646 4645)
1923 Perl_die_nocontext(const char* pat, ...)
1927 va_start(args, pat);
1929 NOT_REACHED; /* NOTREACHED */
1931 NORETURN_FUNCTION_END;
1935 #endif /* MULTIPLICITY */
1937 /* silence __declspec(noreturn) warnings */
1938 MSVC_DIAG_IGNORE(4646 4645)
1940 Perl_die(pTHX_ const char* pat, ...)
1943 va_start(args, pat);
1945 NOT_REACHED; /* NOTREACHED */
1947 NORETURN_FUNCTION_END;
1952 =for apidoc croak_sv
1954 This is an XS interface to Perl's C<die> function.
1956 C<baseex> is the error message or object. If it is a reference, it
1957 will be used as-is. Otherwise it is used as a string, and if it does
1958 not end with a newline then it will be extended with some indication of
1959 the current location in the code, as described for L</mess_sv>.
1961 The error message or object will be used as an exception, by default
1962 returning control to the nearest enclosing C<eval>, but subject to
1963 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1964 function never returns normally.
1966 To die with a simple string message, the L</croak> function may be
1973 Perl_croak_sv(pTHX_ SV *baseex)
1975 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1976 PERL_ARGS_ASSERT_CROAK_SV;
1977 invoke_exception_hook(ex, FALSE);
1984 This is an XS interface to Perl's C<die> function.
1986 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1987 argument list. These are used to generate a string message. If the
1988 message does not end with a newline, then it will be extended with
1989 some indication of the current location in the code, as described for
1992 The error message will be used as an exception, by default
1993 returning control to the nearest enclosing C<eval>, but subject to
1994 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1995 function never returns normally.
1997 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1998 (C<$@>) will be used as an error message or object instead of building an
1999 error message from arguments. If you want to throw a non-string object,
2000 or build an error message in an SV yourself, it is preferable to use
2001 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
2007 Perl_vcroak(pTHX_ const char* pat, va_list *args)
2009 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
2010 invoke_exception_hook(ex, FALSE);
2016 =for apidoc_item croak_nocontext
2018 These are XS interfaces to Perl's C<die> function.
2020 They take a sprintf-style format pattern and argument list, which are used to
2021 generate a string message. If the message does not end with a newline, then it
2022 will be extended with some indication of the current location in the code, as
2023 described for C<L</mess_sv>>.
2025 The error message will be used as an exception, by default
2026 returning control to the nearest enclosing C<eval>, but subject to
2027 modification by a C<$SIG{__DIE__}> handler. In any case, these croak
2028 functions never return normally.
2030 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
2031 (C<$@>) will be used as an error message or object instead of building an
2032 error message from arguments. If you want to throw a non-string object,
2033 or build an error message in an SV yourself, it is preferable to use
2034 the C<L</croak_sv>> function, which does not involve clobbering C<ERRSV>.
2036 The two forms differ only in that C<croak_nocontext> does not take a thread
2037 context (C<aTHX>) parameter. It is usually preferred as it takes up fewer
2038 bytes of code than plain C<Perl_croak>, and time is rarely a critical resource
2039 when you are about to throw an exception.
2044 #if defined(MULTIPLICITY)
2046 Perl_croak_nocontext(const char *pat, ...)
2050 va_start(args, pat);
2052 NOT_REACHED; /* NOTREACHED */
2055 #endif /* MULTIPLICITY */
2057 /* saves machine code for a common noreturn idiom typically used in Newx*() */
2058 GCC_DIAG_IGNORE_DECL(-Wunused-function);
2060 Perl_croak_memory_wrap(void)
2062 Perl_croak_nocontext("%s",PL_memory_wrap);
2064 GCC_DIAG_RESTORE_DECL;
2067 Perl_croak(pTHX_ const char *pat, ...)
2070 va_start(args, pat);
2072 NOT_REACHED; /* NOTREACHED */
2077 =for apidoc croak_no_modify
2079 This encapsulates a common reason for dying, generating terser object code than
2080 using the generic C<Perl_croak>. It is exactly equivalent to
2081 C<Perl_croak(aTHX_ "%s", PL_no_modify)> (which expands to something like
2082 "Modification of a read-only value attempted").
2084 Less code used on exception code paths reduces CPU cache pressure.
2090 Perl_croak_no_modify(void)
2092 Perl_croak_nocontext( "%s", PL_no_modify);
2095 /* does not return, used in util.c perlio.c and win32.c
2096 This is typically called when malloc returns NULL.
2099 Perl_croak_no_mem(void)
2103 int fd = PerlIO_fileno(Perl_error_log);
2105 SETERRNO(EBADF,RMS_IFI);
2107 /* Can't use PerlIO to write as it allocates memory */
2108 PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, sizeof(PL_no_mem)-1));
2113 /* does not return, used only in POPSTACK */
2115 Perl_croak_popstack(void)
2118 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
2125 This is an XS interface to Perl's C<warn> function.
2127 C<baseex> is the error message or object. If it is a reference, it
2128 will be used as-is. Otherwise it is used as a string, and if it does
2129 not end with a newline then it will be extended with some indication of
2130 the current location in the code, as described for L</mess_sv>.
2132 The error message or object will by default be written to standard error,
2133 but this is subject to modification by a C<$SIG{__WARN__}> handler.
2135 To warn with a simple string message, the L</warn> function may be
2142 Perl_warn_sv(pTHX_ SV *baseex)
2144 SV *ex = mess_sv(baseex, 0);
2145 PERL_ARGS_ASSERT_WARN_SV;
2146 if (!invoke_exception_hook(ex, TRUE))
2147 write_to_stderr(ex);
2153 This is an XS interface to Perl's C<warn> function.
2155 This is like C<L</warn>>, but C<args> are an encapsulated
2158 Unlike with L</vcroak>, C<pat> is not permitted to be null.
2164 Perl_vwarn(pTHX_ const char* pat, va_list *args)
2166 SV *ex = vmess(pat, args);
2167 PERL_ARGS_ASSERT_VWARN;
2168 if (!invoke_exception_hook(ex, TRUE))
2169 write_to_stderr(ex);
2174 =for apidoc_item warn_nocontext
2176 These are XS interfaces to Perl's C<warn> function.
2178 They take a sprintf-style format pattern and argument list, which are used to
2179 generate a string message. If the message does not end with a newline, then it
2180 will be extended with some indication of the current location in the code, as
2181 described for C<L</mess_sv>>.
2183 The error message or object will by default be written to standard error,
2184 but this is subject to modification by a C<$SIG{__WARN__}> handler.
2186 Unlike with C<L</croak>>, C<pat> is not permitted to be null.
2188 The two forms differ only in that C<warn_nocontext> does not take a thread
2189 context (C<aTHX>) parameter, so is used in situations where the caller doesn't
2190 already have the thread context.
2195 #if defined(MULTIPLICITY)
2197 Perl_warn_nocontext(const char *pat, ...)
2201 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
2202 va_start(args, pat);
2206 #endif /* MULTIPLICITY */
2209 Perl_warn(pTHX_ const char *pat, ...)
2212 PERL_ARGS_ASSERT_WARN;
2213 va_start(args, pat);
2220 =for apidoc_item warner_nocontext
2222 These output a warning of the specified category (or categories) given by
2223 C<err>, using the sprintf-style format pattern C<pat>, and argument list.
2225 C<err> must be one of the C<L</packWARN>>, C<packWARN2>, C<packWARN3>,
2226 C<packWARN4> macros populated with the appropriate number of warning
2227 categories. If any of the warning categories they specify is fatal, a fatal
2228 exception is thrown.
2230 In any event a message is generated by the pattern and arguments. If the
2231 message does not end with a newline, then it will be extended with some
2232 indication of the current location in the code, as described for L</mess_sv>.
2234 The error message or object will by default be written to standard error,
2235 but this is subject to modification by a C<$SIG{__WARN__}> handler.
2237 C<pat> is not permitted to be null.
2239 The two forms differ only in that C<warner_nocontext> does not take a thread
2240 context (C<aTHX>) parameter, so is used in situations where the caller doesn't
2241 already have the thread context.
2243 These functions differ from the similarly named C<L</warn>> functions, in that
2244 the latter are for XS code to unconditionally display a warning, whereas these
2245 are for code that may be compiling a perl program, and does extra checking to
2246 see if the warning should be fatal.
2248 =for apidoc ck_warner
2249 =for apidoc_item ck_warner_d
2250 If none of the warning categories given by C<err> are enabled, do nothing;
2251 otherwise call C<L</warner>> or C<L</warner_nocontext>> with the passed-in
2254 C<err> must be one of the C<L</packWARN>>, C<packWARN2>, C<packWARN3>,
2255 C<packWARN4> macros populated with the appropriate number of warning
2258 The two forms differ only in that C<ck_warner_d> should be used if warnings for
2259 any of the categories are by default enabled.
2262 This is like C<L</warner>>, but C<args> are an encapsulated argument list.
2267 #if defined(MULTIPLICITY)
2269 Perl_warner_nocontext(U32 err, const char *pat, ...)
2273 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
2274 va_start(args, pat);
2275 vwarner(err, pat, &args);
2278 #endif /* MULTIPLICITY */
2281 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
2283 PERL_ARGS_ASSERT_CK_WARNER_D;
2285 if (Perl_ckwarn_d(aTHX_ err)) {
2287 va_start(args, pat);
2288 vwarner(err, pat, &args);
2294 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
2296 PERL_ARGS_ASSERT_CK_WARNER;
2298 if (Perl_ckwarn(aTHX_ err)) {
2300 va_start(args, pat);
2301 vwarner(err, pat, &args);
2307 Perl_warner(pTHX_ U32 err, const char* pat,...)
2310 PERL_ARGS_ASSERT_WARNER;
2311 va_start(args, pat);
2312 vwarner(err, pat, &args);
2317 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
2319 PERL_ARGS_ASSERT_VWARNER;
2321 (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) &&
2322 !(PL_in_eval & EVAL_KEEPERR)
2324 SV * const msv = vmess(pat, args);
2326 if (PL_parser && PL_parser->error_count) {
2330 invoke_exception_hook(msv, FALSE);
2335 Perl_vwarn(aTHX_ pat, args);
2339 /* implements the ckWARN? macros */
2342 Perl_ckwarn(pTHX_ U32 w)
2344 /* If lexical warnings have not been set, use $^W. */
2346 return PL_dowarn & G_WARN_ON;
2348 return ckwarn_common(w);
2351 /* implements the ckWARN?_d macro */
2354 Perl_ckwarn_d(pTHX_ U32 w)
2356 /* If lexical warnings have not been set then default classes warn. */
2360 return ckwarn_common(w);
2364 S_ckwarn_common(pTHX_ U32 w)
2366 if (PL_curcop->cop_warnings == pWARN_ALL)
2369 if (PL_curcop->cop_warnings == pWARN_NONE)
2372 /* Check the assumption that at least the first slot is non-zero. */
2373 assert(unpackWARN1(w));
2375 /* Check the assumption that it is valid to stop as soon as a zero slot is
2377 if (!unpackWARN2(w)) {
2378 assert(!unpackWARN3(w));
2379 assert(!unpackWARN4(w));
2380 } else if (!unpackWARN3(w)) {
2381 assert(!unpackWARN4(w));
2384 /* Right, dealt with all the special cases, which are implemented as non-
2385 pointers, so there is a pointer to a real warnings mask. */
2387 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
2389 } while (w >>= WARNshift);
2394 /* Set buffer=NULL to get a new one. */
2396 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
2398 const MEM_SIZE len_wanted =
2399 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
2400 PERL_UNUSED_CONTEXT;
2401 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
2404 (specialWARN(buffer) ?
2405 PerlMemShared_malloc(len_wanted) :
2406 PerlMemShared_realloc(buffer, len_wanted));
2408 Copy(bits, (buffer + 1), size, char);
2409 if (size < WARNsize)
2410 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
2414 /* since we've already done strlen() for both nam and val
2415 * we can use that info to make things faster than
2416 * sprintf(s, "%s=%s", nam, val)
2418 #define my_setenv_format(s, nam, nlen, val, vlen) \
2419 Copy(nam, s, nlen, char); \
2421 Copy(val, s+(nlen+1), vlen, char); \
2422 *(s+(nlen+1+vlen)) = '\0'
2426 #ifdef USE_ENVIRON_ARRAY
2427 /* NB: VMS' my_setenv() is in vms.c */
2429 /* Configure doesn't test for HAS_SETENV yet, so decide based on platform.
2430 * For Solaris, setenv() and unsetenv() were introduced in Solaris 9, so
2431 * testing for HAS UNSETENV is sufficient.
2433 # if defined(__CYGWIN__)|| defined(__riscos__) || (defined(__sun) && defined(HAS_UNSETENV)) || defined(PERL_DARWIN)
2434 # define MY_HAS_SETENV
2437 /* small wrapper for use by Perl_my_setenv that mallocs, or reallocs if
2438 * 'current' is non-null, with up to three sizes that are added together.
2439 * It handles integer overflow.
2441 # ifndef MY_HAS_SETENV
2443 S_env_alloc(void *current, Size_t l1, Size_t l2, Size_t l3, Size_t size)
2446 Size_t sl, l = l1 + l2;
2458 ? safesysrealloc(current, sl)
2459 : safesysmalloc(sl);
2464 croak_memory_wrap();
2469 # if !defined(WIN32)
2472 =for apidoc_section $utility
2473 =for apidoc my_setenv
2475 A wrapper for the C library L<setenv(3)>. Don't use the latter, as the perl
2476 version has desirable safeguards
2482 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2484 # ifdef __amigaos4__
2485 amigaos4_obtain_environ(__FUNCTION__);
2488 # ifdef USE_ITHREADS
2489 /* only parent thread can modify process environment, so no need to use a
2491 if (PL_curinterp == aTHX)
2495 # ifndef PERL_USE_SAFE_PUTENV
2496 if (!PL_use_safe_putenv) {
2497 /* most putenv()s leak, so we manipulate environ directly */
2499 Size_t vlen, nlen = strlen(nam);
2501 /* where does it go? */
2502 for (i = 0; environ[i]; i++) {
2503 if (strnEQ(environ[i], nam, nlen) && environ[i][nlen] == '=')
2507 if (environ == PL_origenviron) { /* need we copy environment? */
2512 while (environ[max])
2515 /* XXX shouldn't that be max+1 rather than max+2 ??? - DAPM */
2516 tmpenv = (char**)S_env_alloc(NULL, max, 2, 0, sizeof(char*));
2518 for (j=0; j<max; j++) { /* copy environment */
2519 const Size_t len = strlen(environ[j]);
2520 tmpenv[j] = S_env_alloc(NULL, len, 1, 0, 1);
2521 Copy(environ[j], tmpenv[j], len+1, char);
2525 environ = tmpenv; /* tell exec where it is now */
2529 safesysfree(environ[i]);
2530 while (environ[i]) {
2531 environ[i] = environ[i+1];
2534 # ifdef __amigaos4__
2541 if (!environ[i]) { /* does not exist yet */
2542 environ = (char**)S_env_alloc(environ, i, 2, 0, sizeof(char*));
2543 environ[i+1] = NULL; /* make sure it's null terminated */
2546 safesysfree(environ[i]);
2550 environ[i] = S_env_alloc(NULL, nlen, vlen, 2, 1);
2551 /* all that work just for this */
2552 my_setenv_format(environ[i], nam, nlen, val, vlen);
2556 # endif /* !PERL_USE_SAFE_PUTENV */
2558 # ifdef MY_HAS_SETENV
2559 # if defined(HAS_UNSETENV)
2561 (void)unsetenv(nam);
2563 (void)setenv(nam, val, 1);
2565 # else /* ! HAS_UNSETENV */
2566 (void)setenv(nam, val, 1);
2567 # endif /* HAS_UNSETENV */
2569 # elif defined(HAS_UNSETENV)
2572 if (environ) /* old glibc can crash with null environ */
2573 (void)unsetenv(nam);
2575 const Size_t nlen = strlen(nam);
2576 const Size_t vlen = strlen(val);
2577 char * const new_env = S_env_alloc(NULL, nlen, vlen, 2, 1);
2578 my_setenv_format(new_env, nam, nlen, val, vlen);
2579 (void)putenv(new_env);
2582 # else /* ! HAS_UNSETENV */
2585 const Size_t nlen = strlen(nam);
2591 new_env = S_env_alloc(NULL, nlen, vlen, 2, 1);
2592 /* all that work just for this */
2593 my_setenv_format(new_env, nam, nlen, val, vlen);
2594 (void)putenv(new_env);
2596 # endif /* MY_HAS_SETENV */
2598 # ifndef PERL_USE_SAFE_PUTENV
2603 # ifdef __amigaos4__
2605 amigaos4_release_environ(__FUNCTION__);
2612 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2615 const Size_t nlen = strlen(nam);
2622 envstr = S_env_alloc(NULL, nlen, vlen, 2, 1);
2623 my_setenv_format(envstr, nam, nlen, val, vlen);
2624 (void)PerlEnv_putenv(envstr);
2625 safesysfree(envstr);
2630 #endif /* USE_ENVIRON_ARRAY */
2635 #ifdef UNLINK_ALL_VERSIONS
2637 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2641 PERL_ARGS_ASSERT_UNLNK;
2643 while (PerlLIO_unlink(f) >= 0)
2645 return retries ? 0 : -1;
2650 #if (__CHARSET_LIB == 1)
2651 static int chgfdccsid(int fd, unsigned short ccsid)
2654 memset(&attr, 0, sizeof(attr));
2655 attr.att_filetagchg = 1;
2656 attr.att_filetag.ft_ccsid = ccsid;
2657 if (ccsid != FT_BINARY) {
2658 attr.att_filetag.ft_txtflag = 1;
2660 return __fchattr(fd, &attr, sizeof(attr));
2666 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2668 #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(OS2) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
2676 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2678 PERL_FLUSHALL_FOR_CHILD;
2679 This = (*mode == 'w');
2683 taint_proper("Insecure %s%s", "EXEC");
2685 if (PerlProc_pipe_cloexec(p) < 0)
2687 /* Try for another pipe pair for error return */
2688 if (PerlProc_pipe_cloexec(pp) >= 0)
2690 while ((pid = PerlProc_fork()) < 0) {
2691 if (errno != EAGAIN) {
2692 PerlLIO_close(p[This]);
2693 PerlLIO_close(p[that]);
2695 PerlLIO_close(pp[0]);
2696 PerlLIO_close(pp[1]);
2700 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2709 /* Close parent's end of error status pipe (if any) */
2711 PerlLIO_close(pp[0]);
2713 #if (__CHARSET_LIB == 1)
2714 chgfdccsid(p[THIS], 819);
2715 chgfdccsid(p[THAT], 819);
2718 /* Now dup our end of _the_ pipe to right position */
2719 if (p[THIS] != (*mode == 'r')) {
2720 PerlLIO_dup2(p[THIS], *mode == 'r');
2721 PerlLIO_close(p[THIS]);
2722 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2723 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2726 setfd_cloexec_or_inhexec_by_sysfdness(p[THIS]);
2727 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2729 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2730 /* No automatic close - do it by hand */
2737 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2743 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2750 PerlLIO_close(pp[1]);
2751 /* Keep the lower of the two fd numbers */
2752 if (p[that] < p[This]) {
2753 PerlLIO_dup2_cloexec(p[This], p[that]);
2754 PerlLIO_close(p[This]);
2758 PerlLIO_close(p[that]); /* close child's end of pipe */
2760 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2761 SvUPGRADE(sv,SVt_IV);
2763 PL_forkprocess = pid;
2764 /* If we managed to get status pipe check for exec fail */
2765 if (did_pipes && pid > 0) {
2767 unsigned read_total = 0;
2769 while (read_total < sizeof(int)) {
2770 const SSize_t n1 = PerlLIO_read(pp[0],
2771 (void*)(((char*)&errkid)+read_total),
2772 (sizeof(int)) - read_total);
2777 PerlLIO_close(pp[0]);
2779 if (read_total) { /* Error */
2781 PerlLIO_close(p[This]);
2782 if (read_total != sizeof(int))
2783 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", read_total);
2785 pid2 = wait4pid(pid, &status, 0);
2786 } while (pid2 == -1 && errno == EINTR);
2787 errno = errkid; /* Propagate errno from kid */
2792 PerlLIO_close(pp[0]);
2794 #if (__CHARSET_LIB == 1)
2795 PerlIO* io = PerlIO_fdopen(p[This], mode);
2797 chgfdccsid(p[This], 819);
2801 return PerlIO_fdopen(p[This], mode);
2804 return PerlIO_fdopen(p[This], mode);
2808 # if defined(OS2) /* Same, without fork()ing and all extra overhead... */
2809 return my_syspopen4(aTHX_ NULL, mode, n, args);
2810 # elif defined(WIN32)
2811 return win32_popenlist(mode, n, args);
2813 Perl_croak(aTHX_ "List form of piped open not implemented");
2814 return (PerlIO *) NULL;
2819 /* VMS' my_popen() is in VMS.c, same with OS/2 and AmigaOS 4. */
2820 #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
2822 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2828 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2832 PERL_ARGS_ASSERT_MY_POPEN;
2834 PERL_FLUSHALL_FOR_CHILD;
2837 return my_syspopen(aTHX_ cmd,mode);
2840 This = (*mode == 'w');
2842 if (doexec && TAINTING_get) {
2844 taint_proper("Insecure %s%s", "EXEC");
2846 if (PerlProc_pipe_cloexec(p) < 0)
2848 if (doexec && PerlProc_pipe_cloexec(pp) >= 0)
2850 while ((pid = PerlProc_fork()) < 0) {
2851 if (errno != EAGAIN) {
2852 PerlLIO_close(p[This]);
2853 PerlLIO_close(p[that]);
2855 PerlLIO_close(pp[0]);
2856 PerlLIO_close(pp[1]);
2859 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2862 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2872 PerlLIO_close(pp[0]);
2874 #if (__CHARSET_LIB == 1)
2875 chgfdccsid(p[THIS], 819);
2876 chgfdccsid(p[THAT], 819);
2879 if (p[THIS] != (*mode == 'r')) {
2880 PerlLIO_dup2(p[THIS], *mode == 'r');
2881 PerlLIO_close(p[THIS]);
2882 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2883 PerlLIO_close(p[THAT]);
2886 setfd_cloexec_or_inhexec_by_sysfdness(p[THIS]);
2887 PerlLIO_close(p[THAT]);
2891 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2898 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2903 /* may or may not use the shell */
2904 do_exec3(cmd, pp[1], did_pipes);
2907 #endif /* defined OS2 */
2909 #ifdef PERLIO_USING_CRLF
2910 /* Since we circumvent IO layers when we manipulate low-level
2911 filedescriptors directly, need to manually switch to the
2912 default, binary, low-level mode; see PerlIOBuf_open(). */
2913 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2916 #ifdef PERL_USES_PL_PIDSTATUS
2917 hv_clear(PL_pidstatus); /* we have no children */
2924 PerlLIO_close(pp[1]);
2925 if (p[that] < p[This]) {
2926 PerlLIO_dup2_cloexec(p[This], p[that]);
2927 PerlLIO_close(p[This]);
2931 PerlLIO_close(p[that]);
2933 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2934 SvUPGRADE(sv,SVt_IV);
2936 PL_forkprocess = pid;
2937 if (did_pipes && pid > 0) {
2941 while (n < sizeof(int)) {
2942 const SSize_t n1 = PerlLIO_read(pp[0],
2943 (void*)(((char*)&errkid)+n),
2949 PerlLIO_close(pp[0]);
2951 if (n) { /* Error */
2953 PerlLIO_close(p[This]);
2954 if (n != sizeof(int))
2955 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2957 pid2 = wait4pid(pid, &status, 0);
2958 } while (pid2 == -1 && errno == EINTR);
2959 errno = errkid; /* Propagate errno from kid */
2964 PerlLIO_close(pp[0]);
2966 #if (__CHARSET_LIB == 1)
2967 PerlIO* io = PerlIO_fdopen(p[This], mode);
2969 chgfdccsid(p[This], 819);
2973 return PerlIO_fdopen(p[This], mode);
2976 return PerlIO_fdopen(p[This], mode);
2979 #elif defined(__LIBCATAMOUNT__)
2981 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2986 #endif /* !DOSISH */
2988 /* this is called in parent before the fork() */
2990 Perl_atfork_lock(void)
2991 #if defined(USE_ITHREADS)
2993 PERL_TSA_ACQUIRE(PL_perlio_mutex)
2996 PERL_TSA_ACQUIRE(PL_malloc_mutex)
2998 PERL_TSA_ACQUIRE(PL_op_mutex)
3001 #if defined(USE_ITHREADS)
3002 /* locks must be held in locking order (if any) */
3004 MUTEX_LOCK(&PL_perlio_mutex);
3007 MUTEX_LOCK(&PL_malloc_mutex);
3013 /* this is called in both parent and child after the fork() */
3015 Perl_atfork_unlock(void)
3016 #if defined(USE_ITHREADS)
3018 PERL_TSA_RELEASE(PL_perlio_mutex)
3021 PERL_TSA_RELEASE(PL_malloc_mutex)
3023 PERL_TSA_RELEASE(PL_op_mutex)
3026 #if defined(USE_ITHREADS)
3027 /* locks must be released in same order as in atfork_lock() */
3029 MUTEX_UNLOCK(&PL_perlio_mutex);
3032 MUTEX_UNLOCK(&PL_malloc_mutex);
3041 #if defined(HAS_FORK)
3043 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
3048 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
3049 * handlers elsewhere in the code */
3053 #elif defined(__amigaos4__)
3054 return amigaos_fork();
3056 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
3057 Perl_croak_nocontext("fork() not available");
3059 #endif /* HAS_FORK */
3064 dup2(int oldfd, int newfd)
3066 #if defined(HAS_FCNTL) && defined(F_DUPFD)
3069 PerlLIO_close(newfd);
3070 return fcntl(oldfd, F_DUPFD, newfd);
3072 #define DUP2_MAX_FDS 256
3073 int fdtmp[DUP2_MAX_FDS];
3079 PerlLIO_close(newfd);
3080 /* good enough for low fd's... */
3081 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
3082 if (fdx >= DUP2_MAX_FDS) {
3090 PerlLIO_close(fdtmp[--fdx]);
3097 #ifdef HAS_SIGACTION
3100 =for apidoc_section $signals
3103 A wrapper for the C library L<signal(2)>. Don't use the latter, as the Perl
3104 version knows things that interact with the rest of the perl interpreter.
3110 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3112 struct sigaction act, oact;
3115 /* only "parent" interpreter can diddle signals */
3116 if (PL_curinterp != aTHX)
3117 return (Sighandler_t) SIG_ERR;
3120 act.sa_handler = handler;
3121 sigemptyset(&act.sa_mask);
3124 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3125 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
3127 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3128 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3129 act.sa_flags |= SA_NOCLDWAIT;
3131 if (sigaction(signo, &act, &oact) == -1)
3132 return (Sighandler_t) SIG_ERR;
3134 return (Sighandler_t) oact.sa_handler;
3138 Perl_rsignal_state(pTHX_ int signo)
3140 struct sigaction oact;
3141 PERL_UNUSED_CONTEXT;
3143 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
3144 return (Sighandler_t) SIG_ERR;
3146 return (Sighandler_t) oact.sa_handler;
3150 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3152 struct sigaction act;
3154 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
3157 /* only "parent" interpreter can diddle signals */
3158 if (PL_curinterp != aTHX)
3162 act.sa_handler = handler;
3163 sigemptyset(&act.sa_mask);
3166 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3167 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
3169 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3170 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3171 act.sa_flags |= SA_NOCLDWAIT;
3173 return sigaction(signo, &act, save);
3177 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3179 PERL_UNUSED_CONTEXT;
3181 /* only "parent" interpreter can diddle signals */
3182 if (PL_curinterp != aTHX)
3186 return sigaction(signo, save, (struct sigaction *)NULL);
3189 #else /* !HAS_SIGACTION */
3192 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3194 #if defined(USE_ITHREADS) && !defined(WIN32)
3195 /* only "parent" interpreter can diddle signals */
3196 if (PL_curinterp != aTHX)
3197 return (Sighandler_t) SIG_ERR;
3200 return PerlProc_signal(signo, handler);
3210 Perl_rsignal_state(pTHX_ int signo)
3212 Sighandler_t oldsig;
3214 #if defined(USE_ITHREADS) && !defined(WIN32)
3215 /* only "parent" interpreter can diddle signals */
3216 if (PL_curinterp != aTHX)
3217 return (Sighandler_t) SIG_ERR;
3221 oldsig = PerlProc_signal(signo, sig_trap);
3222 PerlProc_signal(signo, oldsig);
3224 PerlProc_kill(PerlProc_getpid(), signo);
3229 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3231 #if defined(USE_ITHREADS) && !defined(WIN32)
3232 /* only "parent" interpreter can diddle signals */
3233 if (PL_curinterp != aTHX)
3236 *save = PerlProc_signal(signo, handler);
3237 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3241 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3243 #if defined(USE_ITHREADS) && !defined(WIN32)
3244 /* only "parent" interpreter can diddle signals */
3245 if (PL_curinterp != aTHX)
3248 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3251 #endif /* !HAS_SIGACTION */
3252 #endif /* !PERL_MICRO */
3254 /* VMS' my_pclose() is in VMS.c */
3255 #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
3257 Perl_my_pclose(pTHX_ PerlIO *ptr)
3265 const int fd = PerlIO_fileno(ptr);
3268 svp = av_fetch(PL_fdpid, fd, FALSE);
3270 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3277 #if defined(USE_PERLIO)
3278 /* Find out whether the refcount is low enough for us to wait for the
3279 child proc without blocking. */
3280 should_wait = PerlIOUnix_refcnt(fd) == 1 && pid > 0;
3282 should_wait = pid > 0;
3286 if (pid == -2) { /* Opened by popen. */
3287 return my_syspclose(ptr);
3290 close_failed = (PerlIO_close(ptr) == EOF);
3292 if (should_wait) do {
3293 pid2 = wait4pid(pid, &status, 0);
3294 } while (pid2 == -1 && errno == EINTR);
3301 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3305 #elif defined(__LIBCATAMOUNT__)
3307 Perl_my_pclose(pTHX_ PerlIO *ptr)
3311 #endif /* !DOSISH */
3313 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32)) && !defined(__LIBCATAMOUNT__)
3315 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3318 PERL_ARGS_ASSERT_WAIT4PID;
3319 #ifdef PERL_USES_PL_PIDSTATUS
3321 /* PERL_USES_PL_PIDSTATUS is only defined when neither
3322 waitpid() nor wait4() is available, or on OS/2, which
3323 doesn't appear to support waiting for a progress group
3324 member, so we can only treat a 0 pid as an unknown child.
3331 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3332 pid, rather than a string form. */
3333 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3334 if (svp && *svp != &PL_sv_undef) {
3335 *statusp = SvIVX(*svp);
3336 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3344 hv_iterinit(PL_pidstatus);
3345 if ((entry = hv_iternext(PL_pidstatus))) {
3346 SV * const sv = hv_iterval(PL_pidstatus,entry);
3348 const char * const spid = hv_iterkey(entry,&len);
3350 assert (len == sizeof(Pid_t));
3351 memcpy((char *)&pid, spid, len);
3352 *statusp = SvIVX(sv);
3353 /* The hash iterator is currently on this entry, so simply
3354 calling hv_delete would trigger the lazy delete, which on
3355 aggregate does more work, because next call to hv_iterinit()
3356 would spot the flag, and have to call the delete routine,
3357 while in the meantime any new entries can't re-use that
3359 hv_iterinit(PL_pidstatus);
3360 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3367 # ifdef HAS_WAITPID_RUNTIME
3368 if (!HAS_WAITPID_RUNTIME)
3371 result = PerlProc_waitpid(pid,statusp,flags);
3374 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3375 result = wait4(pid,statusp,flags,NULL);
3378 #ifdef PERL_USES_PL_PIDSTATUS
3379 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3384 Perl_croak(aTHX_ "Can't do waitpid with flags");
3386 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3387 pidgone(result,*statusp);
3393 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3396 if (result < 0 && errno == EINTR) {
3398 errno = EINTR; /* reset in case a signal handler changed $! */
3402 #endif /* !DOSISH || OS2 || WIN32 */
3404 #ifdef PERL_USES_PL_PIDSTATUS
3406 S_pidgone(pTHX_ Pid_t pid, int status)
3410 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3411 SvUPGRADE(sv,SVt_IV);
3412 SvIV_set(sv, status);
3420 int /* Cannot prototype with I32
3422 my_syspclose(PerlIO *ptr)
3425 Perl_my_pclose(pTHX_ PerlIO *ptr)
3428 /* Needs work for PerlIO ! */
3429 FILE * const f = PerlIO_findFILE(ptr);
3430 const I32 result = pclose(f);
3431 PerlIO_releaseFILE(ptr,f);
3436 #define PERL_REPEATCPY_LINEAR 4
3438 Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
3440 PERL_ARGS_ASSERT_REPEATCPY;
3445 croak_memory_wrap();
3448 memset(to, *from, count);
3451 IV items, linear, half;
3453 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3454 for (items = 0; items < linear; ++items) {
3455 const char *q = from;
3457 for (todo = len; todo > 0; todo--)
3462 while (items <= half) {
3463 IV size = items * len;
3464 memcpy(p, to, size);
3470 memcpy(p, to, (count - items) * len);
3476 Perl_same_dirent(pTHX_ const char *a, const char *b)
3478 char *fa = strrchr(a,'/');
3479 char *fb = strrchr(b,'/');
3482 SV * const tmpsv = sv_newmortal();
3484 PERL_ARGS_ASSERT_SAME_DIRENT;
3497 sv_setpvs(tmpsv, ".");
3499 sv_setpvn(tmpsv, a, fa - a);
3500 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3503 sv_setpvs(tmpsv, ".");
3505 sv_setpvn(tmpsv, b, fb - b);
3506 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3508 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3509 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3511 #endif /* !HAS_RENAME */
3514 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3515 const char *const *const search_ext, I32 flags)
3517 const char *xfound = NULL;
3518 char *xfailed = NULL;
3519 char tmpbuf[MAXPATHLEN];
3524 #if defined(DOSISH) && !defined(OS2)
3525 # define SEARCH_EXTS ".bat", ".cmd", NULL
3526 # define MAX_EXT_LEN 4
3529 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3530 # define MAX_EXT_LEN 4
3533 # define SEARCH_EXTS ".pl", ".com", NULL
3534 # define MAX_EXT_LEN 4
3536 /* additional extensions to try in each dir if scriptname not found */
3538 static const char *const exts[] = { SEARCH_EXTS };
3539 const char *const *const ext = search_ext ? search_ext : exts;
3540 int extidx = 0, i = 0;
3541 const char *curext = NULL;
3543 PERL_UNUSED_ARG(search_ext);
3544 # define MAX_EXT_LEN 0
3547 PERL_ARGS_ASSERT_FIND_SCRIPT;
3550 * If dosearch is true and if scriptname does not contain path
3551 * delimiters, search the PATH for scriptname.
3553 * If SEARCH_EXTS is also defined, will look for each
3554 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3555 * while searching the PATH.
3557 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3558 * proceeds as follows:
3559 * If DOSISH or VMSISH:
3560 * + look for ./scriptname{,.foo,.bar}
3561 * + search the PATH for scriptname{,.foo,.bar}
3564 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3565 * this will not look in '.' if it's not in the PATH)
3570 # ifdef ALWAYS_DEFTYPES
3571 len = strlen(scriptname);
3572 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3573 int idx = 0, deftypes = 1;
3576 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3579 int idx = 0, deftypes = 1;
3582 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3584 /* The first time through, just add SEARCH_EXTS to whatever we
3585 * already have, so we can check for default file types. */
3587 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3594 if ((strlen(tmpbuf) + strlen(scriptname)
3595 + MAX_EXT_LEN) >= sizeof tmpbuf)
3596 continue; /* don't search dir with too-long name */
3597 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3601 if (strEQ(scriptname, "-"))
3603 if (dosearch) { /* Look in '.' first. */
3604 const char *cur = scriptname;
3606 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3608 if (strEQ(ext[i++],curext)) {
3609 extidx = -1; /* already has an ext */
3614 DEBUG_p(PerlIO_printf(Perl_debug_log,
3615 "Looking for %s\n",cur));
3618 if (PerlLIO_stat(cur,&statbuf) >= 0
3619 && !S_ISDIR(statbuf.st_mode)) {
3628 if (cur == scriptname) {
3629 len = strlen(scriptname);
3630 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3632 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3635 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3636 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3641 if (dosearch && !strchr(scriptname, '/')
3643 && !strchr(scriptname, '\\')
3645 && (s = PerlEnv_getenv("PATH")))
3649 bufend = s + strlen(s);
3650 while (s < bufend) {
3654 && *s != ';'; len++, s++) {
3655 if (len < sizeof tmpbuf)
3658 if (len < sizeof tmpbuf)
3661 s = delimcpy_no_escape(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3666 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3667 continue; /* don't search dir with too-long name */
3670 && tmpbuf[len - 1] != '/'
3671 && tmpbuf[len - 1] != '\\'
3674 tmpbuf[len++] = '/';
3675 if (len == 2 && tmpbuf[0] == '.')
3677 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3681 len = strlen(tmpbuf);
3682 if (extidx > 0) /* reset after previous loop */
3686 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3687 retval = PerlLIO_stat(tmpbuf,&statbuf);
3688 if (S_ISDIR(statbuf.st_mode)) {
3692 } while ( retval < 0 /* not there */
3693 && extidx>=0 && ext[extidx] /* try an extension? */
3694 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3699 if (S_ISREG(statbuf.st_mode)
3700 && cando(S_IRUSR,TRUE,&statbuf)
3701 #if !defined(DOSISH)
3702 && cando(S_IXUSR,TRUE,&statbuf)
3706 xfound = tmpbuf; /* bingo! */
3710 xfailed = savepv(tmpbuf);
3715 if (!xfound && !seen_dot && !xfailed &&
3716 (PerlLIO_stat(scriptname,&statbuf) < 0
3717 || S_ISDIR(statbuf.st_mode)))
3719 seen_dot = 1; /* Disable message. */
3724 if (flags & 1) { /* do or die? */
3725 /* diag_listed_as: Can't execute %s */
3726 Perl_croak(aTHX_ "Can't %s %s%s%s",
3727 (xfailed ? "execute" : "find"),
3728 (xfailed ? xfailed : scriptname),
3729 (xfailed ? "" : " on PATH"),
3730 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3735 scriptname = xfound;
3737 return (scriptname ? savepv(scriptname) : NULL);
3740 #ifndef PERL_GET_CONTEXT_DEFINED
3743 Perl_get_context(void)
3745 #if defined(USE_ITHREADS)
3746 # ifdef OLD_PTHREADS_API
3748 int error = pthread_getspecific(PL_thr_key, &t);
3750 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3752 # elif defined(I_MACH_CTHREADS)
3753 return (void*)cthread_data(cthread_self());
3755 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3763 Perl_set_context(void *t)
3765 PERL_ARGS_ASSERT_SET_CONTEXT;
3766 #if defined(USE_ITHREADS)
3767 # ifdef PERL_USE_THREAD_LOCAL
3768 PL_current_context = t;
3770 # ifdef I_MACH_CTHREADS
3771 cthread_set_data(cthread_self(), t);
3773 /* We set thread-specific value always, as C++ code has to read it with
3774 * pthreads, beacuse the declaration syntax for thread local storage for C11
3775 * is incompatible with C++, meaning that we can't expose the thread local
3776 * variable to C++ code. */
3778 const int error = pthread_setspecific(PL_thr_key, t);
3780 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3788 #endif /* !PERL_GET_CONTEXT_DEFINED */
3791 Perl_get_op_names(pTHX)
3793 PERL_UNUSED_CONTEXT;
3794 return (char **)PL_op_name;
3798 Perl_get_op_descs(pTHX)
3800 PERL_UNUSED_CONTEXT;
3801 return (char **)PL_op_desc;
3805 Perl_get_no_modify(pTHX)
3807 PERL_UNUSED_CONTEXT;
3808 return PL_no_modify;
3812 Perl_get_opargs(pTHX)
3814 PERL_UNUSED_CONTEXT;
3815 return (U32 *)PL_opargs;
3819 Perl_get_ppaddr(pTHX)
3821 PERL_UNUSED_CONTEXT;
3822 return (PPADDR_t*)PL_ppaddr;
3825 #ifndef HAS_GETENV_LEN
3827 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3829 char * const env_trans = PerlEnv_getenv(env_elem);
3830 PERL_UNUSED_CONTEXT;
3831 PERL_ARGS_ASSERT_GETENV_LEN;
3833 *len = strlen(env_trans);
3840 Perl_get_vtbl(pTHX_ int vtbl_id)
3842 PERL_UNUSED_CONTEXT;
3844 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3845 ? NULL : (MGVTBL*)PL_magic_vtables + vtbl_id;
3849 Perl_my_fflush_all(pTHX)
3851 #if defined(USE_PERLIO) || defined(FFLUSH_NULL)
3852 return PerlIO_flush(NULL);
3854 # if defined(HAS__FWALK)
3855 extern int fflush(FILE *);
3856 /* undocumented, unprototyped, but very useful BSDism */
3857 extern void _fwalk(int (*)(FILE *));
3861 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3863 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3864 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3865 # elif defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3866 open_max = sysconf(_SC_OPEN_MAX);
3867 # elif defined(FOPEN_MAX)
3868 open_max = FOPEN_MAX;
3869 # elif defined(OPEN_MAX)
3870 open_max = OPEN_MAX;
3871 # elif defined(_NFILE)
3876 for (i = 0; i < open_max; i++)
3877 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3878 STDIO_STREAM_ARRAY[i]._file < open_max &&
3879 STDIO_STREAM_ARRAY[i]._flag)
3880 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3884 SETERRNO(EBADF,RMS_IFI);
3891 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3893 if (ckWARN(WARN_IO)) {
3895 = gv && (isGV_with_GP(gv))
3898 const char * const direction = have == '>' ? "out" : "in";
3900 if (name && HEK_LEN(name))
3901 Perl_warner(aTHX_ packWARN(WARN_IO),
3902 "Filehandle %" HEKf " opened only for %sput",
3903 HEKfARG(name), direction);
3905 Perl_warner(aTHX_ packWARN(WARN_IO),
3906 "Filehandle opened only for %sput", direction);
3911 Perl_report_evil_fh(pTHX_ const GV *gv)
3913 const IO *io = gv ? GvIO(gv) : NULL;
3914 const PERL_BITFIELD16 op = PL_op->op_type;
3918 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3920 warn_type = WARN_CLOSED;
3924 warn_type = WARN_UNOPENED;
3927 if (ckWARN(warn_type)) {
3929 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3930 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3931 const char * const pars =
3932 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3933 const char * const func =
3935 (op == OP_READLINE || op == OP_RCATLINE
3936 ? "readline" : /* "<HANDLE>" not nice */
3937 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3939 const char * const type =
3941 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3942 ? "socket" : "filehandle");
3943 const bool have_name = name && SvCUR(name);
3944 Perl_warner(aTHX_ packWARN(warn_type),
3945 "%s%s on %s %s%s%" SVf, func, pars, vile, type,
3946 have_name ? " " : "",
3947 SVfARG(have_name ? name : &PL_sv_no));
3948 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3950 aTHX_ packWARN(warn_type),
3951 "\t(Are you trying to call %s%s on dirhandle%s%" SVf "?)\n",
3952 func, pars, have_name ? " " : "",
3953 SVfARG(have_name ? name : &PL_sv_no)
3958 /* To workaround core dumps from the uninitialised tm_zone we get the
3959 * system to give us a reasonable struct to copy. This fix means that
3960 * strftime uses the tm_zone and tm_gmtoff values returned by
3961 * localtime(time()). That should give the desired result most of the
3962 * time. But probably not always!
3964 * This does not address tzname aspects of NETaa14816.
3969 # ifndef STRUCT_TM_HASZONE
3970 # define STRUCT_TM_HASZONE
3974 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3975 # ifndef HAS_TM_TM_ZONE
3976 # define HAS_TM_TM_ZONE
3981 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3983 #ifdef HAS_TM_TM_ZONE
3985 const struct tm* my_tm;
3986 PERL_UNUSED_CONTEXT;
3987 PERL_ARGS_ASSERT_INIT_TM;
3989 ENV_LOCALE_READ_LOCK;
3990 my_tm = localtime(&now);
3992 Copy(my_tm, ptm, 1, struct tm);
3993 ENV_LOCALE_READ_UNLOCK;
3995 PERL_UNUSED_CONTEXT;
3996 PERL_ARGS_ASSERT_INIT_TM;
3997 PERL_UNUSED_ARG(ptm);
4002 =for apidoc_section $time
4003 =for apidoc mini_mktime
4004 normalise S<C<struct tm>> values without the localtime() semantics (and
4005 overhead) of mktime().
4010 Perl_mini_mktime(struct tm *ptm)
4014 int month, mday, year, jday;
4015 int odd_cent, odd_year;
4017 PERL_ARGS_ASSERT_MINI_MKTIME;
4019 #define DAYS_PER_YEAR 365
4020 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
4021 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
4022 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
4023 #define SECS_PER_HOUR (60*60)
4024 #define SECS_PER_DAY (24*SECS_PER_HOUR)
4025 /* parentheses deliberately absent on these two, otherwise they don't work */
4026 #define MONTH_TO_DAYS 153/5
4027 #define DAYS_TO_MONTH 5/153
4028 /* offset to bias by March (month 4) 1st between month/mday & year finding */
4029 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
4030 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
4031 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
4034 * Year/day algorithm notes:
4036 * With a suitable offset for numeric value of the month, one can find
4037 * an offset into the year by considering months to have 30.6 (153/5) days,
4038 * using integer arithmetic (i.e., with truncation). To avoid too much
4039 * messing about with leap days, we consider January and February to be
4040 * the 13th and 14th month of the previous year. After that transformation,
4041 * we need the month index we use to be high by 1 from 'normal human' usage,
4042 * so the month index values we use run from 4 through 15.
4044 * Given that, and the rules for the Gregorian calendar (leap years are those
4045 * divisible by 4 unless also divisible by 100, when they must be divisible
4046 * by 400 instead), we can simply calculate the number of days since some
4047 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
4048 * the days we derive from our month index, and adding in the day of the
4049 * month. The value used here is not adjusted for the actual origin which
4050 * it normally would use (1 January A.D. 1), since we're not exposing it.
4051 * We're only building the value so we can turn around and get the
4052 * normalised values for the year, month, day-of-month, and day-of-year.
4054 * For going backward, we need to bias the value we're using so that we find
4055 * the right year value. (Basically, we don't want the contribution of
4056 * March 1st to the number to apply while deriving the year). Having done
4057 * that, we 'count up' the contribution to the year number by accounting for
4058 * full quadracenturies (400-year periods) with their extra leap days, plus
4059 * the contribution from full centuries (to avoid counting in the lost leap
4060 * days), plus the contribution from full quad-years (to count in the normal
4061 * leap days), plus the leftover contribution from any non-leap years.
4062 * At this point, if we were working with an actual leap day, we'll have 0
4063 * days left over. This is also true for March 1st, however. So, we have
4064 * to special-case that result, and (earlier) keep track of the 'odd'
4065 * century and year contributions. If we got 4 extra centuries in a qcent,
4066 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
4067 * Otherwise, we add back in the earlier bias we removed (the 123 from
4068 * figuring in March 1st), find the month index (integer division by 30.6),
4069 * and the remainder is the day-of-month. We then have to convert back to
4070 * 'real' months (including fixing January and February from being 14/15 in
4071 * the previous year to being in the proper year). After that, to get
4072 * tm_yday, we work with the normalised year and get a new yearday value for
4073 * January 1st, which we subtract from the yearday value we had earlier,
4074 * representing the date we've re-built. This is done from January 1
4075 * because tm_yday is 0-origin.
4077 * Since POSIX time routines are only guaranteed to work for times since the
4078 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
4079 * applies Gregorian calendar rules even to dates before the 16th century
4080 * doesn't bother me. Besides, you'd need cultural context for a given
4081 * date to know whether it was Julian or Gregorian calendar, and that's
4082 * outside the scope for this routine. Since we convert back based on the
4083 * same rules we used to build the yearday, you'll only get strange results
4084 * for input which needed normalising, or for the 'odd' century years which
4085 * were leap years in the Julian calendar but not in the Gregorian one.
4086 * I can live with that.
4088 * This algorithm also fails to handle years before A.D. 1 gracefully, but
4089 * that's still outside the scope for POSIX time manipulation, so I don't
4095 year = 1900 + ptm->tm_year;
4096 month = ptm->tm_mon;
4097 mday = ptm->tm_mday;
4103 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4104 yearday += month*MONTH_TO_DAYS + mday + jday;
4106 * Note that we don't know when leap-seconds were or will be,
4107 * so we have to trust the user if we get something which looks
4108 * like a sensible leap-second. Wild values for seconds will
4109 * be rationalised, however.
4111 if ((unsigned) ptm->tm_sec <= 60) {
4118 secs += 60 * ptm->tm_min;
4119 secs += SECS_PER_HOUR * ptm->tm_hour;
4121 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4122 /* got negative remainder, but need positive time */
4123 /* back off an extra day to compensate */
4124 yearday += (secs/SECS_PER_DAY)-1;
4125 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4128 yearday += (secs/SECS_PER_DAY);
4129 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4132 else if (secs >= SECS_PER_DAY) {
4133 yearday += (secs/SECS_PER_DAY);
4134 secs %= SECS_PER_DAY;
4136 ptm->tm_hour = secs/SECS_PER_HOUR;
4137 secs %= SECS_PER_HOUR;
4138 ptm->tm_min = secs/60;
4140 ptm->tm_sec += secs;
4141 /* done with time of day effects */
4143 * The algorithm for yearday has (so far) left it high by 428.
4144 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4145 * bias it by 123 while trying to figure out what year it
4146 * really represents. Even with this tweak, the reverse
4147 * translation fails for years before A.D. 0001.
4148 * It would still fail for Feb 29, but we catch that one below.
4150 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
4151 yearday -= YEAR_ADJUST;
4152 year = (yearday / DAYS_PER_QCENT) * 400;
4153 yearday %= DAYS_PER_QCENT;
4154 odd_cent = yearday / DAYS_PER_CENT;
4155 year += odd_cent * 100;
4156 yearday %= DAYS_PER_CENT;
4157 year += (yearday / DAYS_PER_QYEAR) * 4;
4158 yearday %= DAYS_PER_QYEAR;
4159 odd_year = yearday / DAYS_PER_YEAR;
4161 yearday %= DAYS_PER_YEAR;
4162 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4167 yearday += YEAR_ADJUST; /* recover March 1st crock */
4168 month = yearday*DAYS_TO_MONTH;
4169 yearday -= month*MONTH_TO_DAYS;
4170 /* recover other leap-year adjustment */
4179 ptm->tm_year = year - 1900;
4181 ptm->tm_mday = yearday;
4182 ptm->tm_mon = month;
4186 ptm->tm_mon = month - 1;
4188 /* re-build yearday based on Jan 1 to get tm_yday */
4190 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4191 yearday += 14*MONTH_TO_DAYS + 1;
4192 ptm->tm_yday = jday - yearday;
4193 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4197 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)
4202 =for apidoc_section $time
4203 =for apidoc my_strftime
4204 strftime(), but with a different API so that the return value is a pointer
4205 to the formatted result (which MUST be arranged to be FREED BY THE
4206 CALLER). This allows this function to increase the buffer size as needed,
4207 so that the caller doesn't have to worry about that.
4209 Note that yday and wday effectively are ignored by this function, as
4210 mini_mktime() overwrites them
4212 Also note that this is always executed in the underlying locale of the program,
4213 giving localized results.
4223 PERL_ARGS_ASSERT_MY_STRFTIME;
4225 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4228 mytm.tm_hour = hour;
4229 mytm.tm_mday = mday;
4231 mytm.tm_year = year;
4232 mytm.tm_wday = wday;
4233 mytm.tm_yday = yday;
4234 mytm.tm_isdst = isdst;
4236 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4237 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4242 #ifdef HAS_TM_TM_GMTOFF
4243 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4245 #ifdef HAS_TM_TM_ZONE
4246 mytm.tm_zone = mytm2.tm_zone;
4251 Newx(buf, buflen, char);
4253 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* fmt checked by caller */
4255 len = strftime(buf, buflen, fmt, &mytm);
4257 GCC_DIAG_RESTORE_STMT;
4260 ** The following is needed to handle the situation where
4261 ** tmpbuf overflows. Basically we want to allocate a buffer
4262 ** and try repeatedly, until it's large enough. The reason why it is so
4263 ** complicated ** is that getting a return value of 0 from strftime can
4264 ** indicate one of the following:
4265 ** 1. buffer overflowed,
4266 ** 2. illegal conversion specifier, or
4267 ** 3. the format string specifies nothing to be returned (which isn't an
4268 ** an error). This could be because the format is an empty string
4269 ** or it specifies %p which yields an empty string in some locales.
4270 ** If there is a better way to make it portable, go ahead by
4273 if (inRANGE(len, 1, buflen - 1) || (len == 0 && *fmt == '\0'))
4276 /* Possibly buf overflowed - try again with a bigger buf */
4277 const int fmtlen = strlen(fmt);
4278 int bufsize = fmtlen + buflen;
4280 Renew(buf, bufsize, char);
4283 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* fmt checked by caller */
4284 buflen = strftime(buf, bufsize, fmt, &mytm);
4285 GCC_DIAG_RESTORE_STMT;
4287 if (inRANGE(buflen, 1, bufsize - 1))
4289 /* heuristic to prevent out-of-memory errors */
4290 if (bufsize > 100*fmtlen) {
4292 /* "%p" can legally return nothing, assume that was the case if we
4293 * can't make the buffer large enough to get a non-zero return. For
4294 * any other formats, assume it is an error (probably it is an illegal
4295 * conversion specifier.) */
4296 if (strEQ(fmt, "%p")) {
4297 Renew(buf, 1, char);
4307 Renew(buf, bufsize, char);
4312 Perl_croak(aTHX_ "panic: no strftime");
4318 #define SV_CWD_RETURN_UNDEF \
4322 #define SV_CWD_ISDOT(dp) \
4323 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4324 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4327 =for apidoc_section $utility
4329 =for apidoc getcwd_sv
4331 Fill C<sv> with current working directory
4336 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4337 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4338 * getcwd(3) if available
4339 * Comments from the original:
4340 * This is a faster version of getcwd. It's also more dangerous
4341 * because you might chdir out of a directory that you can't chdir
4345 Perl_getcwd_sv(pTHX_ SV *sv)
4350 PERL_ARGS_ASSERT_GETCWD_SV;
4354 char buf[MAXPATHLEN];
4356 /* Some getcwd()s automatically allocate a buffer of the given
4357 * size from the heap if they are given a NULL buffer pointer.
4358 * The problem is that this behaviour is not portable. */
4359 if (getcwd(buf, sizeof(buf) - 1)) {
4364 SV_CWD_RETURN_UNDEF;
4371 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4375 SvUPGRADE(sv, SVt_PV);
4377 if (PerlLIO_lstat(".", &statbuf) < 0) {
4378 SV_CWD_RETURN_UNDEF;
4381 orig_cdev = statbuf.st_dev;
4382 orig_cino = statbuf.st_ino;
4392 if (PerlDir_chdir("..") < 0) {
4393 SV_CWD_RETURN_UNDEF;
4395 if (PerlLIO_stat(".", &statbuf) < 0) {
4396 SV_CWD_RETURN_UNDEF;
4399 cdev = statbuf.st_dev;
4400 cino = statbuf.st_ino;
4402 if (odev == cdev && oino == cino) {
4405 if (!(dir = PerlDir_open("."))) {
4406 SV_CWD_RETURN_UNDEF;
4409 while ((dp = PerlDir_read(dir)) != NULL) {
4411 namelen = dp->d_namlen;
4413 namelen = strlen(dp->d_name);
4416 if (SV_CWD_ISDOT(dp)) {
4420 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4421 SV_CWD_RETURN_UNDEF;
4424 tdev = statbuf.st_dev;
4425 tino = statbuf.st_ino;
4426 if (tino == oino && tdev == odev) {
4432 SV_CWD_RETURN_UNDEF;
4435 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4436 SV_CWD_RETURN_UNDEF;
4439 SvGROW(sv, pathlen + namelen + 1);
4443 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4446 /* prepend current directory to the front */
4448 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4449 pathlen += (namelen + 1);
4451 #ifdef VOID_CLOSEDIR
4454 if (PerlDir_close(dir) < 0) {
4455 SV_CWD_RETURN_UNDEF;
4461 SvCUR_set(sv, pathlen);
4465 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4466 SV_CWD_RETURN_UNDEF;
4469 if (PerlLIO_stat(".", &statbuf) < 0) {
4470 SV_CWD_RETURN_UNDEF;
4473 cdev = statbuf.st_dev;
4474 cino = statbuf.st_ino;
4476 if (cdev != orig_cdev || cino != orig_cino) {
4477 Perl_croak(aTHX_ "Unstable directory path, "
4478 "current directory changed unexpectedly");
4491 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4492 # define EMULATE_SOCKETPAIR_UDP
4495 #ifdef EMULATE_SOCKETPAIR_UDP
4497 S_socketpair_udp (int fd[2]) {
4499 /* Fake a datagram socketpair using UDP to localhost. */
4500 int sockets[2] = {-1, -1};
4501 struct sockaddr_in addresses[2];
4503 Sock_size_t size = sizeof(struct sockaddr_in);
4504 unsigned short port;
4507 memset(&addresses, 0, sizeof(addresses));
4510 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4511 if (sockets[i] == -1)
4512 goto tidy_up_and_fail;
4514 addresses[i].sin_family = AF_INET;
4515 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4516 addresses[i].sin_port = 0; /* kernel choses port. */
4517 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4518 sizeof(struct sockaddr_in)) == -1)
4519 goto tidy_up_and_fail;
4522 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4523 for each connect the other socket to it. */
4526 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4528 goto tidy_up_and_fail;
4529 if (size != sizeof(struct sockaddr_in))
4530 goto abort_tidy_up_and_fail;
4531 /* !1 is 0, !0 is 1 */
4532 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4533 sizeof(struct sockaddr_in)) == -1)
4534 goto tidy_up_and_fail;
4537 /* Now we have 2 sockets connected to each other. I don't trust some other
4538 process not to have already sent a packet to us (by random) so send
4539 a packet from each to the other. */
4542 /* I'm going to send my own port number. As a short.
4543 (Who knows if someone somewhere has sin_port as a bitfield and needs
4544 this routine. (I'm assuming crays have socketpair)) */
4545 port = addresses[i].sin_port;
4546 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4547 if (got != sizeof(port)) {
4549 goto tidy_up_and_fail;
4550 goto abort_tidy_up_and_fail;
4554 /* Packets sent. I don't trust them to have arrived though.
4555 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4556 connect to localhost will use a second kernel thread. In 2.6 the
4557 first thread running the connect() returns before the second completes,
4558 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4559 returns 0. Poor programs have tripped up. One poor program's authors'
4560 had a 50-1 reverse stock split. Not sure how connected these were.)
4561 So I don't trust someone not to have an unpredictable UDP stack.
4565 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4566 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4570 FD_SET((unsigned int)sockets[0], &rset);
4571 FD_SET((unsigned int)sockets[1], &rset);
4573 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4574 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4575 || !FD_ISSET(sockets[1], &rset)) {
4576 /* I hope this is portable and appropriate. */
4578 goto tidy_up_and_fail;
4579 goto abort_tidy_up_and_fail;
4583 /* And the paranoia department even now doesn't trust it to have arrive
4584 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4586 struct sockaddr_in readfrom;
4587 unsigned short buffer[2];
4592 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4593 sizeof(buffer), MSG_DONTWAIT,
4594 (struct sockaddr *) &readfrom, &size);
4596 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4598 (struct sockaddr *) &readfrom, &size);
4602 goto tidy_up_and_fail;
4603 if (got != sizeof(port)
4604 || size != sizeof(struct sockaddr_in)
4605 /* Check other socket sent us its port. */
4606 || buffer[0] != (unsigned short) addresses[!i].sin_port
4607 /* Check kernel says we got the datagram from that socket */
4608 || readfrom.sin_family != addresses[!i].sin_family
4609 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4610 || readfrom.sin_port != addresses[!i].sin_port)
4611 goto abort_tidy_up_and_fail;
4614 /* My caller (my_socketpair) has validated that this is non-NULL */
4617 /* I hereby declare this connection open. May God bless all who cross
4621 abort_tidy_up_and_fail:
4622 errno = ECONNABORTED;
4626 if (sockets[0] != -1)
4627 PerlLIO_close(sockets[0]);
4628 if (sockets[1] != -1)
4629 PerlLIO_close(sockets[1]);
4634 #endif /* EMULATE_SOCKETPAIR_UDP */
4636 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4638 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4639 /* Stevens says that family must be AF_LOCAL, protocol 0.
4640 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4645 struct sockaddr_in listen_addr;
4646 struct sockaddr_in connect_addr;
4651 || family != AF_UNIX
4654 errno = EAFNOSUPPORT;
4663 type &= ~SOCK_CLOEXEC;
4666 #ifdef EMULATE_SOCKETPAIR_UDP
4667 if (type == SOCK_DGRAM)
4668 return S_socketpair_udp(fd);
4671 aTHXa(PERL_GET_THX);
4672 listener = PerlSock_socket(AF_INET, type, 0);
4675 memset(&listen_addr, 0, sizeof(listen_addr));
4676 listen_addr.sin_family = AF_INET;
4677 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4678 listen_addr.sin_port = 0; /* kernel choses port. */
4679 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4680 sizeof(listen_addr)) == -1)
4681 goto tidy_up_and_fail;
4682 if (PerlSock_listen(listener, 1) == -1)
4683 goto tidy_up_and_fail;
4685 connector = PerlSock_socket(AF_INET, type, 0);
4686 if (connector == -1)
4687 goto tidy_up_and_fail;
4688 /* We want to find out the port number to connect to. */
4689 size = sizeof(connect_addr);
4690 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4692 goto tidy_up_and_fail;
4693 if (size != sizeof(connect_addr))
4694 goto abort_tidy_up_and_fail;
4695 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4696 sizeof(connect_addr)) == -1)
4697 goto tidy_up_and_fail;
4699 size = sizeof(listen_addr);
4700 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4703 goto tidy_up_and_fail;
4704 if (size != sizeof(listen_addr))
4705 goto abort_tidy_up_and_fail;
4706 PerlLIO_close(listener);
4707 /* Now check we are talking to ourself by matching port and host on the
4709 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4711 goto tidy_up_and_fail;
4712 if (size != sizeof(connect_addr)
4713 || listen_addr.sin_family != connect_addr.sin_family
4714 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4715 || listen_addr.sin_port != connect_addr.sin_port) {
4716 goto abort_tidy_up_and_fail;
4722 abort_tidy_up_and_fail:
4724 errno = ECONNABORTED; /* This would be the standard thing to do. */
4725 #elif defined(ECONNREFUSED)
4726 errno = ECONNREFUSED; /* some OSes might not have ECONNABORTED. */
4728 errno = ETIMEDOUT; /* Desperation time. */
4734 PerlLIO_close(listener);
4735 if (connector != -1)
4736 PerlLIO_close(connector);
4738 PerlLIO_close(acceptor);
4744 /* In any case have a stub so that there's code corresponding
4745 * to the my_socketpair in embed.fnc. */
4747 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4748 #ifdef HAS_SOCKETPAIR
4749 return socketpair(family, type, protocol, fd);
4758 =for apidoc sv_nosharing
4760 Dummy routine which "shares" an SV when there is no sharing module present.
4761 Or "locks" it. Or "unlocks" it. In other
4762 words, ignores its single SV argument.
4763 Exists to avoid test for a C<NULL> function pointer and because it could
4764 potentially warn under some level of strict-ness.
4770 Perl_sv_nosharing(pTHX_ SV *sv)
4772 PERL_UNUSED_CONTEXT;
4773 PERL_UNUSED_ARG(sv);
4778 =for apidoc sv_destroyable
4780 Dummy routine which reports that object can be destroyed when there is no
4781 sharing module present. It ignores its single SV argument, and returns
4782 'true'. Exists to avoid test for a C<NULL> function pointer and because it
4783 could potentially warn under some level of strict-ness.
4789 Perl_sv_destroyable(pTHX_ SV *sv)
4791 PERL_UNUSED_CONTEXT;
4792 PERL_UNUSED_ARG(sv);
4797 Perl_parse_unicode_opts(pTHX_ const char **popt)
4799 const char *p = *popt;
4802 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
4806 const char* endptr = p + strlen(p);
4808 if (grok_atoUV(p, &uv, &endptr) && uv <= U32_MAX) {
4811 if (p && *p && *p != '\n' && *p != '\r') {
4813 goto the_end_of_the_opts_parser;
4815 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4819 Perl_croak(aTHX_ "Invalid number '%s' for -C option.\n", p);
4825 case PERL_UNICODE_STDIN:
4826 opt |= PERL_UNICODE_STDIN_FLAG; break;
4827 case PERL_UNICODE_STDOUT:
4828 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4829 case PERL_UNICODE_STDERR:
4830 opt |= PERL_UNICODE_STDERR_FLAG; break;
4831 case PERL_UNICODE_STD:
4832 opt |= PERL_UNICODE_STD_FLAG; break;
4833 case PERL_UNICODE_IN:
4834 opt |= PERL_UNICODE_IN_FLAG; break;
4835 case PERL_UNICODE_OUT:
4836 opt |= PERL_UNICODE_OUT_FLAG; break;
4837 case PERL_UNICODE_INOUT:
4838 opt |= PERL_UNICODE_INOUT_FLAG; break;
4839 case PERL_UNICODE_LOCALE:
4840 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4841 case PERL_UNICODE_ARGV:
4842 opt |= PERL_UNICODE_ARGV_FLAG; break;
4843 case PERL_UNICODE_UTF8CACHEASSERT:
4844 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
4846 if (*p != '\n' && *p != '\r') {
4847 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4850 "Unknown Unicode option letter '%c'", *p);
4857 opt = PERL_UNICODE_DEFAULT_FLAGS;
4859 the_end_of_the_opts_parser:
4861 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4862 Perl_croak(aTHX_ "Unknown Unicode option value %" UVuf,
4863 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4871 # include <starlet.h>
4878 * This is really just a quick hack which grabs various garbage
4879 * values. It really should be a real hash algorithm which
4880 * spreads the effect of every input bit onto every output bit,
4881 * if someone who knows about such things would bother to write it.
4882 * Might be a good idea to add that function to CORE as well.
4883 * No numbers below come from careful analysis or anything here,
4884 * except they are primes and SEED_C1 > 1E6 to get a full-width
4885 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4886 * probably be bigger too.
4889 # define SEED_C1 1000003
4890 #define SEED_C4 73819
4892 # define SEED_C1 25747
4893 #define SEED_C4 20639
4897 #define SEED_C5 26107
4899 #ifndef PERL_NO_DEV_RANDOM
4903 #ifdef HAS_GETTIMEOFDAY
4904 struct timeval when;
4909 /* This test is an escape hatch, this symbol isn't set by Configure. */
4910 #ifndef PERL_NO_DEV_RANDOM
4911 #ifndef PERL_RANDOM_DEVICE
4912 /* /dev/random isn't used by default because reads from it will block
4913 * if there isn't enough entropy available. You can compile with
4914 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4915 * is enough real entropy to fill the seed. */
4916 # ifdef __amigaos4__
4917 # define PERL_RANDOM_DEVICE "RANDOM:SIZE=4"
4919 # define PERL_RANDOM_DEVICE "/dev/urandom"
4922 fd = PerlLIO_open_cloexec(PERL_RANDOM_DEVICE, 0);
4924 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4932 #ifdef HAS_GETTIMEOFDAY
4933 PerlProc_gettimeofday(&when,NULL);
4934 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4937 u = (U32)SEED_C1 * when;
4939 u += SEED_C3 * (U32)PerlProc_getpid();
4940 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4941 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4942 u += SEED_C5 * (U32)PTR2UV(&when);
4948 Perl_get_hash_seed(pTHX_ unsigned char * const seed_buffer)
4950 #ifndef NO_PERL_HASH_ENV
4955 PERL_ARGS_ASSERT_GET_HASH_SEED;
4957 #ifndef NO_PERL_HASH_ENV
4958 env_pv= PerlEnv_getenv("PERL_HASH_SEED");
4962 /* ignore leading spaces */
4963 while (isSPACE(*env_pv))
4965 # ifdef USE_PERL_PERTURB_KEYS
4966 /* if they set it to "0" we disable key traversal randomization completely */
4967 if (strEQ(env_pv,"0")) {
4968 PL_hash_rand_bits_enabled= 0;
4970 /* otherwise switch to deterministic mode */
4971 PL_hash_rand_bits_enabled= 2;
4974 /* ignore a leading 0x... if it is there */
4975 if (env_pv[0] == '0' && env_pv[1] == 'x')
4978 for( i = 0; isXDIGIT(*env_pv) && i < PERL_HASH_SEED_BYTES; i++ ) {
4979 seed_buffer[i] = READ_XDIGIT(env_pv) << 4;
4980 if ( isXDIGIT(*env_pv)) {
4981 seed_buffer[i] |= READ_XDIGIT(env_pv);
4984 while (isSPACE(*env_pv))
4987 if (*env_pv && !isXDIGIT(*env_pv)) {
4988 Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n");
4990 /* should we check for unparsed crap? */
4991 /* should we warn about unused hex? */
4992 /* should we warn about insufficient hex? */
4995 #endif /* NO_PERL_HASH_ENV */
4997 for( i = 0; i < PERL_HASH_SEED_BYTES; i++ ) {
4998 seed_buffer[i] = (unsigned char)(Perl_internal_drand48() * (U8_MAX+1));
5001 #ifdef USE_PERL_PERTURB_KEYS
5002 { /* initialize PL_hash_rand_bits from the hash seed.
5003 * This value is highly volatile, it is updated every
5004 * hash insert, and is used as part of hash bucket chain
5005 * randomization and hash iterator randomization. */
5006 PL_hash_rand_bits= 0xbe49d17f; /* I just picked a number */
5007 for( i = 0; i < sizeof(UV) ; i++ ) {
5008 PL_hash_rand_bits += seed_buffer[i % PERL_HASH_SEED_BYTES];
5009 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,8);
5012 # ifndef NO_PERL_HASH_ENV
5013 env_pv= PerlEnv_getenv("PERL_PERTURB_KEYS");
5015 if (strEQ(env_pv,"0") || strEQ(env_pv,"NO")) {
5016 PL_hash_rand_bits_enabled= 0;
5017 } else if (strEQ(env_pv,"1") || strEQ(env_pv,"RANDOM")) {
5018 PL_hash_rand_bits_enabled= 1;
5019 } else if (strEQ(env_pv,"2") || strEQ(env_pv,"DETERMINISTIC")) {
5020 PL_hash_rand_bits_enabled= 2;
5022 Perl_warn(aTHX_ "perl: warning: strange setting in '$ENV{PERL_PERTURB_KEYS}': '%s'\n", env_pv);
5031 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including
5032 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
5033 * given, and you supply your own implementation.
5035 * The default implementation reads a single env var, PERL_MEM_LOG,
5036 * expecting one or more of the following:
5038 * \d+ - fd fd to write to : must be 1st (grok_atoUV)
5039 * 'm' - memlog was PERL_MEM_LOG=1
5040 * 's' - svlog was PERL_SV_LOG=1
5041 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
5043 * This makes the logger controllable enough that it can reasonably be
5044 * added to the system perl.
5047 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
5048 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5050 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5052 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
5053 * writes to. In the default logger, this is settable at runtime.
5055 #ifndef PERL_MEM_LOG_FD
5056 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5059 #ifndef PERL_MEM_LOG_NOIMPL
5061 # ifdef DEBUG_LEAKING_SCALARS
5062 # define SV_LOG_SERIAL_FMT " [%lu]"
5063 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
5065 # define SV_LOG_SERIAL_FMT
5066 # define _SV_LOG_SERIAL_ARG(sv)
5070 S_mem_log_common(enum mem_log_type mlt, const UV n,
5071 const UV typesize, const char *type_name, const SV *sv,
5072 Malloc_t oldalloc, Malloc_t newalloc,
5073 const char *filename, const int linenumber,
5074 const char *funcname)
5079 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
5081 PL_mem_log[0] |= 0x2; /* Flag that the call is from this code */
5082 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
5083 PL_mem_log[0] &= ~0x2;
5086 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
5088 /* We can't use SVs or PerlIO for obvious reasons,
5089 * so we'll use stdio and low-level IO instead. */
5090 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5092 # ifdef HAS_GETTIMEOFDAY
5093 # define MEM_LOG_TIME_FMT "%10d.%06d: "
5094 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
5096 gettimeofday(&tv, 0);
5098 # define MEM_LOG_TIME_FMT "%10d: "
5099 # define MEM_LOG_TIME_ARG (int)when
5103 /* If there are other OS specific ways of hires time than
5104 * gettimeofday() (see dist/Time-HiRes), the easiest way is
5105 * probably that they would be used to fill in the struct
5109 const char* endptr = pmlenv + strlen(pmlenv);
5112 if (grok_atoUV(pmlenv, &uv, &endptr) /* Ignore endptr. */
5113 && uv && uv <= PERL_INT_MAX
5117 fd = PERL_MEM_LOG_FD;
5120 if (strchr(pmlenv, 't')) {
5121 len = my_snprintf(buf, sizeof(buf),
5122 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
5123 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
5127 len = my_snprintf(buf, sizeof(buf),
5128 "alloc: %s:%d:%s: %" IVdf " %" UVuf
5129 " %s = %" IVdf ": %" UVxf "\n",
5130 filename, linenumber, funcname, n, typesize,
5131 type_name, n * typesize, PTR2UV(newalloc));
5134 len = my_snprintf(buf, sizeof(buf),
5135 "realloc: %s:%d:%s: %" IVdf " %" UVuf
5136 " %s = %" IVdf ": %" UVxf " -> %" UVxf "\n",
5137 filename, linenumber, funcname, n, typesize,
5138 type_name, n * typesize, PTR2UV(oldalloc),
5142 len = my_snprintf(buf, sizeof(buf),
5143 "free: %s:%d:%s: %" UVxf "\n",
5144 filename, linenumber, funcname,
5149 len = my_snprintf(buf, sizeof(buf),
5150 "%s_SV: %s:%d:%s: %" UVxf SV_LOG_SERIAL_FMT "\n",
5151 mlt == MLT_NEW_SV ? "new" : "del",
5152 filename, linenumber, funcname,
5153 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
5158 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
5162 #endif /* !PERL_MEM_LOG_NOIMPL */
5164 #ifndef PERL_MEM_LOG_NOIMPL
5166 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
5167 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
5169 /* this is suboptimal, but bug compatible. User is providing their
5170 own implementation, but is getting these functions anyway, and they
5171 do nothing. But _NOIMPL users should be able to cope or fix */
5173 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
5174 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
5178 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
5180 const char *filename, const int linenumber,
5181 const char *funcname)
5183 PERL_ARGS_ASSERT_MEM_LOG_ALLOC;
5185 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
5186 NULL, NULL, newalloc,
5187 filename, linenumber, funcname);
5192 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
5193 Malloc_t oldalloc, Malloc_t newalloc,
5194 const char *filename, const int linenumber,
5195 const char *funcname)
5197 PERL_ARGS_ASSERT_MEM_LOG_REALLOC;
5199 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
5200 NULL, oldalloc, newalloc,
5201 filename, linenumber, funcname);
5206 Perl_mem_log_free(Malloc_t oldalloc,
5207 const char *filename, const int linenumber,
5208 const char *funcname)
5210 PERL_ARGS_ASSERT_MEM_LOG_FREE;
5212 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
5213 filename, linenumber, funcname);
5218 Perl_mem_log_new_sv(const SV *sv,
5219 const char *filename, const int linenumber,
5220 const char *funcname)
5222 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
5223 filename, linenumber, funcname);
5227 Perl_mem_log_del_sv(const SV *sv,
5228 const char *filename, const int linenumber,
5229 const char *funcname)
5231 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
5232 filename, linenumber, funcname);
5235 #endif /* PERL_MEM_LOG */
5238 =for apidoc_section $string
5239 =for apidoc quadmath_format_valid
5241 C<quadmath_snprintf()> is very strict about its C<format> string and will
5242 fail, returning -1, if the format is invalid. It accepts exactly
5245 C<quadmath_format_valid()> checks that the intended single spec looks
5246 sane: begins with C<%>, has only one C<%>, ends with C<[efgaEFGA]>,
5247 and has C<Q> before it. This is not a full "printf syntax check",
5250 Returns true if it is valid, false if not.
5252 See also L</quadmath_format_needed>.
5258 Perl_quadmath_format_valid(const char* format)
5262 PERL_ARGS_ASSERT_QUADMATH_FORMAT_VALID;
5264 if (format[0] != '%' || strchr(format + 1, '%'))
5266 len = strlen(format);
5267 /* minimum length three: %Qg */
5268 if (len < 3 || memCHRs("efgaEFGA", format[len - 1]) == NULL)
5270 if (format[len - 2] != 'Q')
5277 =for apidoc quadmath_format_needed
5279 C<quadmath_format_needed()> returns true if the C<format> string seems to
5280 contain at least one non-Q-prefixed C<%[efgaEFGA]> format specifier,
5281 or returns false otherwise.
5283 The format specifier detection is not complete printf-syntax detection,
5284 but it should catch most common cases.
5286 If true is returned, those arguments B<should> in theory be processed
5287 with C<quadmath_snprintf()>, but in case there is more than one such
5288 format specifier (see L</quadmath_format_valid>), and if there is
5289 anything else beyond that one (even just a single byte), they
5290 B<cannot> be processed because C<quadmath_snprintf()> is very strict,
5291 accepting only one format spec, and nothing else.
5292 In this case, the code should probably fail.
5298 Perl_quadmath_format_needed(const char* format)
5300 const char *p = format;
5303 PERL_ARGS_ASSERT_QUADMATH_FORMAT_NEEDED;
5305 while ((q = strchr(p, '%'))) {
5307 if (*q == '+') /* plus */
5309 if (*q == '#') /* alt */
5311 if (*q == '*') /* width */
5315 while (isDIGIT(*q)) q++;
5318 if (*q == '.' && (q[1] == '*' || isDIGIT(q[1]))) { /* prec */
5323 while (isDIGIT(*q)) q++;
5325 if (memCHRs("efgaEFGA", *q)) /* Would have needed 'Q' in front. */
5334 =for apidoc my_snprintf
5336 The C library C<snprintf> functionality, if available and
5337 standards-compliant (uses C<vsnprintf>, actually). However, if the
5338 C<vsnprintf> is not available, will unfortunately use the unsafe
5339 C<vsprintf> which can overrun the buffer (there is an overrun check,
5340 but that may be too late). Consider using C<sv_vcatpvf> instead, or
5341 getting C<vsnprintf>.
5346 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
5350 PERL_ARGS_ASSERT_MY_SNPRINTF;
5351 #ifndef HAS_VSNPRINTF
5352 PERL_UNUSED_VAR(len);
5354 va_start(ap, format);
5357 bool quadmath_valid = FALSE;
5358 if (quadmath_format_valid(format)) {
5359 /* If the format looked promising, use it as quadmath. */
5360 retval = quadmath_snprintf(buffer, len, format, va_arg(ap, NV));
5362 Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", format);
5364 quadmath_valid = TRUE;
5366 /* quadmath_format_single() will return false for example for
5367 * "foo = %g", or simply "%g". We could handle the %g by
5368 * using quadmath for the NV args. More complex cases of
5369 * course exist: "foo = %g, bar = %g", or "foo=%Qg" (otherwise
5370 * quadmath-valid but has stuff in front).
5372 * Handling the "Q-less" cases right would require walking
5373 * through the va_list and rewriting the format, calling
5374 * quadmath for the NVs, building a new va_list, and then
5375 * letting vsnprintf/vsprintf to take care of the other
5376 * arguments. This may be doable.
5378 * We do not attempt that now. But for paranoia, we here try
5379 * to detect some common (but not all) cases where the
5380 * "Q-less" %[efgaEFGA] formats are present, and die if
5381 * detected. This doesn't fix the problem, but it stops the
5382 * vsnprintf/vsprintf pulling doubles off the va_list when
5383 * __float128 NVs should be pulled off instead.
5385 * If quadmath_format_needed() returns false, we are reasonably
5386 * certain that we can call vnsprintf() or vsprintf() safely. */
5387 if (!quadmath_valid && quadmath_format_needed(format))
5388 Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", format);
5393 #ifdef HAS_VSNPRINTF
5394 retval = vsnprintf(buffer, len, format, ap);
5396 retval = vsprintf(buffer, format, ap);
5399 /* vsprintf() shows failure with < 0 */
5401 #ifdef HAS_VSNPRINTF
5402 /* vsnprintf() shows failure with >= len */
5404 (len > 0 && (Size_t)retval >= len)
5407 Perl_croak_nocontext("panic: my_snprintf buffer overflow");
5412 =for apidoc my_vsnprintf
5414 The C library C<vsnprintf> if available and standards-compliant.
5415 However, if the C<vsnprintf> is not available, will unfortunately
5416 use the unsafe C<vsprintf> which can overrun the buffer (there is an
5417 overrun check, but that may be too late). Consider using
5418 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
5423 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
5426 PERL_UNUSED_ARG(buffer);
5427 PERL_UNUSED_ARG(len);
5428 PERL_UNUSED_ARG(format);
5429 /* the cast is to avoid gcc -Wsizeof-array-argument complaining */
5430 PERL_UNUSED_ARG((void*)ap);
5431 Perl_croak_nocontext("panic: my_vsnprintf not available with quadmath");
5438 PERL_ARGS_ASSERT_MY_VSNPRINTF;
5439 Perl_va_copy(ap, apc);
5440 # ifdef HAS_VSNPRINTF
5441 retval = vsnprintf(buffer, len, format, apc);
5443 PERL_UNUSED_ARG(len);
5444 retval = vsprintf(buffer, format, apc);
5448 # ifdef HAS_VSNPRINTF
5449 retval = vsnprintf(buffer, len, format, ap);
5451 PERL_UNUSED_ARG(len);
5452 retval = vsprintf(buffer, format, ap);
5454 #endif /* #ifdef NEED_VA_COPY */
5455 /* vsprintf() shows failure with < 0 */
5457 #ifdef HAS_VSNPRINTF
5458 /* vsnprintf() shows failure with >= len */
5460 (len > 0 && (Size_t)retval >= len)
5463 Perl_croak_nocontext("panic: my_vsnprintf buffer overflow");
5469 Perl_my_clearenv(pTHX)
5471 #if ! defined(PERL_MICRO)
5472 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5474 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5475 # if defined(USE_ENVIRON_ARRAY)
5476 # if defined(USE_ITHREADS)
5477 /* only the parent thread can clobber the process environment, so no need
5479 if (PL_curinterp == aTHX)
5480 # endif /* USE_ITHREADS */
5482 # if ! defined(PERL_USE_SAFE_PUTENV)
5483 if ( !PL_use_safe_putenv) {
5485 if (environ == PL_origenviron)
5486 environ = (char**)safesysmalloc(sizeof(char*));
5488 for (i = 0; environ[i]; i++)
5489 (void)safesysfree(environ[i]);
5492 # else /* PERL_USE_SAFE_PUTENV */
5493 # if defined(HAS_CLEARENV)
5495 # elif defined(HAS_UNSETENV)
5496 int bsiz = 80; /* Most envvar names will be shorter than this. */
5497 char *buf = (char*)safesysmalloc(bsiz);
5498 while (*environ != NULL) {
5499 char *e = strchr(*environ, '=');
5500 int l = e ? e - *environ : (int)strlen(*environ);
5502 (void)safesysfree(buf);
5503 bsiz = l + 1; /* + 1 for the \0. */
5504 buf = (char*)safesysmalloc(bsiz);
5506 memcpy(buf, *environ, l);
5508 (void)unsetenv(buf);
5510 (void)safesysfree(buf);
5511 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5512 /* Just null environ and accept the leakage. */
5514 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5515 # endif /* ! PERL_USE_SAFE_PUTENV */
5517 # endif /* USE_ENVIRON_ARRAY */
5518 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5519 #endif /* PERL_MICRO */
5525 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
5526 the global PL_my_cxt_index is incremented, and that value is assigned to
5527 that module's static my_cxt_index (who's address is passed as an arg).
5528 Then, for each interpreter this function is called for, it makes sure a
5529 void* slot is available to hang the static data off, by allocating or
5530 extending the interpreter's PL_my_cxt_list array */
5533 Perl_my_cxt_init(pTHX_ int *indexp, size_t size)
5538 PERL_ARGS_ASSERT_MY_CXT_INIT;
5541 /* do initial check without locking.
5542 * -1: not allocated or another thread currently allocating
5543 * other: already allocated by another thread
5546 MUTEX_LOCK(&PL_my_ctx_mutex);
5547 /*now a stricter check with locking */
5550 /* this module hasn't been allocated an index yet */
5551 *indexp = PL_my_cxt_index++;
5553 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5556 /* make sure the array is big enough */
5557 if (PL_my_cxt_size <= index) {
5558 if (PL_my_cxt_size) {
5559 IV new_size = PL_my_cxt_size;
5560 while (new_size <= index)
5562 Renew(PL_my_cxt_list, new_size, void *);
5563 PL_my_cxt_size = new_size;
5566 PL_my_cxt_size = 16;
5567 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5570 /* newSV() allocates one more than needed */
5571 p = (void*)SvPVX(newSV(size-1));
5572 PL_my_cxt_list[index] = p;
5573 Zero(p, size, char);
5577 #endif /* MULTIPLICITY */
5580 /* Perl_xs_handshake():
5581 implement the various XS_*_BOOTCHECK macros, which are added to .c
5582 files by ExtUtils::ParseXS, to check that the perl the module was built
5583 with is binary compatible with the running perl.
5586 Perl_xs_handshake(U32 key, void * v_my_perl, const char * file,
5587 [U32 items, U32 ax], [char * api_version], [char * xs_version])
5589 The meaning of the varargs is determined the U32 key arg (which is not
5590 a format string). The fields of key are assembled by using HS_KEY().
5592 Under PERL_IMPLICIT_CONTEX, the v_my_perl arg is of type
5593 "PerlInterpreter *" and represents the callers context; otherwise it is
5594 of type "CV *", and is the boot xsub's CV.
5596 v_my_perl will catch where a threaded future perl526.dll calling IO.dll
5597 for example, and IO.dll was linked with threaded perl524.dll, and both
5598 perl526.dll and perl524.dll are in %PATH and the Win32 DLL loader
5599 successfully can load IO.dll into the process but simultaneously it
5600 loaded an interpreter of a different version into the process, and XS
5601 code will naturally pass SV*s created by perl524.dll for perl526.dll to
5602 use through perl526.dll's my_perl->Istack_base.
5604 v_my_perl cannot be the first arg, since then 'key' will be out of
5605 place in a threaded vs non-threaded mixup; and analyzing the key
5606 number's bitfields won't reveal the problem, since it will be a valid
5607 key (unthreaded perl) on interp side, but croak will report the XS mod's
5608 key as gibberish (it is really a my_perl ptr) (threaded XS mod); or if
5609 it's a threaded perl and an unthreaded XS module, threaded perl will
5610 look at an uninit C stack or an uninit register to get 'key'
5611 (remember that it assumes that the 1st arg is the interp cxt).
5613 'file' is the source filename of the caller.
5617 Perl_xs_handshake(const U32 key, void * v_my_perl, const char * file, ...)
5623 const char *stage = "first";
5631 PERL_ARGS_ASSERT_XS_HANDSHAKE;
5632 va_start(args, file);
5634 got = INT2PTR(void*, (UV)(key & HSm_KEY_MATCH));
5635 need = (void *)(HS_KEY(FALSE, FALSE, "", "") & HSm_KEY_MATCH);
5636 if (UNLIKELY(got != need))
5638 /* try to catch where a 2nd threaded perl interp DLL is loaded into a process
5639 by a XS DLL compiled against the wrong interl DLL b/c of bad @INC, and the
5640 2nd threaded perl interp DLL never initialized its TLS/PERL_SYS_INIT3 so
5641 dTHX call from 2nd interp DLL can't return the my_perl that pp_entersub
5642 passed to the XS DLL */
5644 xs_interp = (tTHX)v_my_perl;
5648 /* try to catch where an unthreaded perl interp DLL (for ex. perl522.dll) is
5649 loaded into a process by a XS DLL built by an unthreaded perl522.dll perl,
5650 but the DynaLoder/Perl that started the process and loaded the XS DLL is
5651 unthreaded perl524.dll, since unthreadeds don't pass my_perl (a unique *)
5652 through pp_entersub, use a unique value (which is a pointer to PL_stack_sp's
5653 location in the unthreaded perl binary) stored in CV * to figure out if this
5654 Perl_xs_handshake was called by the same pp_entersub */
5655 cv = (CV*)v_my_perl;
5656 xs_spp = (SV***)CvHSCXT(cv);
5658 need = &PL_stack_sp;
5661 if(UNLIKELY(got != need)) {
5662 bad_handshake:/* recycle branch and string from above */
5663 if(got != (void *)HSf_NOCHK)
5664 noperl_die("%s: loadable library and perl binaries are mismatched"
5665 " (got %s handshake key %p, needed %p)\n",
5666 file, stage, got, need);
5669 if(key & HSf_SETXSUBFN) { /* this might be called from a module bootstrap */
5670 SAVEPPTR(PL_xsubfilename);/* which was require'd from a XSUB BEGIN */
5671 PL_xsubfilename = file; /* so the old name must be restored for
5672 additional XSUBs to register themselves */
5673 /* XSUBs can't be perl lang/perl5db.pl debugged
5674 if (PERLDB_LINE_OR_SAVESRC)
5675 (void)gv_fetchfile(file); */
5678 if(key & HSf_POPMARK) {
5680 { SV **mark = PL_stack_base + ax++;
5682 items = (I32)(SP - MARK);
5686 items = va_arg(args, U32);
5687 ax = va_arg(args, U32);
5691 assert(HS_GETAPIVERLEN(key) <= UCHAR_MAX);
5692 if((apiverlen = HS_GETAPIVERLEN(key))) {
5693 char * api_p = va_arg(args, char*);
5694 if(apiverlen != sizeof("v" PERL_API_VERSION_STRING)-1
5695 || memNE(api_p, "v" PERL_API_VERSION_STRING,
5696 sizeof("v" PERL_API_VERSION_STRING)-1))
5697 Perl_croak_nocontext("Perl API version %s of %" SVf " does not match %s",
5698 api_p, SVfARG(PL_stack_base[ax + 0]),
5699 "v" PERL_API_VERSION_STRING);
5704 assert(HS_GETXSVERLEN(key) <= UCHAR_MAX && HS_GETXSVERLEN(key) <= HS_APIVERLEN_MAX);
5705 if((xsverlen = HS_GETXSVERLEN(key)))
5706 S_xs_version_bootcheck(aTHX_
5707 items, ax, va_arg(args, char*), xsverlen);
5715 S_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
5719 const char *vn = NULL;
5720 SV *const module = PL_stack_base[ax];
5722 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
5724 if (items >= 2) /* version supplied as bootstrap arg */
5725 sv = PL_stack_base[ax + 1];
5727 /* XXX GV_ADDWARN */
5729 sv = get_sv(Perl_form(aTHX_ "%" SVf "::%s", SVfARG(module), vn), 0);
5730 if (!sv || !SvOK(sv)) {
5732 sv = get_sv(Perl_form(aTHX_ "%" SVf "::%s", SVfARG(module), vn), 0);
5736 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
5737 SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version")
5738 ? sv : sv_2mortal(new_version(sv));
5739 xssv = upg_version(xssv, 0);
5740 if ( vcmp(pmsv,xssv) ) {
5741 SV *string = vstringify(xssv);
5742 SV *xpt = Perl_newSVpvf(aTHX_ "%" SVf " object version %" SVf
5743 " does not match ", SVfARG(module), SVfARG(string));
5745 SvREFCNT_dec(string);
5746 string = vstringify(pmsv);
5749 Perl_sv_catpvf(aTHX_ xpt, "$%" SVf "::%s %" SVf, SVfARG(module), vn,
5752 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %" SVf, SVfARG(string));
5754 SvREFCNT_dec(string);
5756 Perl_sv_2mortal(aTHX_ xpt);
5757 Perl_croak_sv(aTHX_ xpt);
5763 =for apidoc my_strlcat
5765 The C library C<strlcat> if available, or a Perl implementation of it.
5766 This operates on C C<NUL>-terminated strings.
5768 C<my_strlcat()> appends string C<src> to the end of C<dst>. It will append at
5769 most S<C<size - strlen(dst) - 1>> characters. It will then C<NUL>-terminate,
5770 unless C<size> is 0 or the original C<dst> string was longer than C<size> (in
5771 practice this should not happen as it means that either C<size> is incorrect or
5772 that C<dst> is not a proper C<NUL>-terminated string).
5774 Note that C<size> is the full size of the destination buffer and
5775 the result is guaranteed to be C<NUL>-terminated if there is room. Note that
5776 room for the C<NUL> should be included in C<size>.
5778 The return value is the total length that C<dst> would have if C<size> is
5779 sufficiently large. Thus it is the initial length of C<dst> plus the length of
5780 C<src>. If C<size> is smaller than the return, the excess was not appended.
5784 Description stolen from http://man.openbsd.org/strlcat.3
5788 Perl_my_strlcat(char *dst, const char *src, Size_t size)
5790 Size_t used, length, copy;
5793 length = strlen(src);
5794 if (size > 0 && used < size - 1) {
5795 copy = (length >= size - used) ? size - used - 1 : length;
5796 memcpy(dst + used, src, copy);
5797 dst[used + copy] = '\0';
5799 return used + length;
5805 =for apidoc my_strlcpy
5807 The C library C<strlcpy> if available, or a Perl implementation of it.
5808 This operates on C C<NUL>-terminated strings.
5810 C<my_strlcpy()> copies up to S<C<size - 1>> characters from the string C<src>
5811 to C<dst>, C<NUL>-terminating the result if C<size> is not 0.
5813 The return value is the total length C<src> would be if the copy completely
5814 succeeded. If it is larger than C<size>, the excess was not copied.
5818 Description stolen from http://man.openbsd.org/strlcpy.3
5822 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
5824 Size_t length, copy;
5826 length = strlen(src);
5828 copy = (length >= size) ? size - 1 : length;
5829 memcpy(dst, src, copy);
5836 PERL_STATIC_INLINE bool
5837 S_gv_has_usable_name(pTHX_ GV *gv)
5841 && HvENAME(GvSTASH(gv))
5842 && (gvp = (GV **)hv_fetchhek(
5843 GvSTASH(gv), GvNAME_HEK(gv), 0
5849 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
5851 SV * const dbsv = GvSVn(PL_DBsub);
5852 const bool save_taint = TAINT_get;
5854 /* When we are called from pp_goto (svp is null),
5855 * we do not care about using dbsv to call CV;
5856 * it's for informational purposes only.
5859 PERL_ARGS_ASSERT_GET_DB_SUB;
5863 if (!PERLDB_SUB_NN) {
5866 if (!svp && !CvLEXICAL(cv)) {
5867 gv_efullname3(dbsv, gv, NULL);
5869 else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED)) || CvLEXICAL(cv)
5870 || strEQ(GvNAME(gv), "END")
5871 || ( /* Could be imported, and old sub redefined. */
5872 (GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv))
5874 !( (SvTYPE(*svp) == SVt_PVGV)
5875 && (GvCV((const GV *)*svp) == cv)
5876 /* Use GV from the stack as a fallback. */
5877 && S_gv_has_usable_name(aTHX_ gv = (GV *)*svp)
5881 /* GV is potentially non-unique, or contain different CV. */
5882 SV * const tmp = newRV(MUTABLE_SV(cv));
5883 sv_setsv(dbsv, tmp);
5887 sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv)));
5888 sv_catpvs(dbsv, "::");
5889 sv_cathek(dbsv, GvNAME_HEK(gv));
5893 const int type = SvTYPE(dbsv);
5894 if (type < SVt_PVIV && type != SVt_IV)
5895 sv_upgrade(dbsv, SVt_PVIV);
5896 (void)SvIOK_on(dbsv);
5897 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
5900 TAINT_IF(save_taint);
5901 #ifdef NO_TAINT_SUPPORT
5902 PERL_UNUSED_VAR(save_taint);
5907 Perl_my_dirfd(DIR * dir) {
5909 /* Most dirfd implementations have problems when passed NULL. */
5914 #elif defined(HAS_DIR_DD_FD)
5917 Perl_croak_nocontext(PL_no_func, "dirfd");
5918 NOT_REACHED; /* NOTREACHED */
5923 #if !defined(HAS_MKOSTEMP) || !defined(HAS_MKSTEMP)
5925 #define TEMP_FILE_CH "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789"
5926 #define TEMP_FILE_CH_COUNT (sizeof(TEMP_FILE_CH)-1)
5929 S_my_mkostemp(char *templte, int flags) {
5931 STRLEN len = strlen(templte);
5935 int delete_on_close = flags & O_VMS_DELETEONCLOSE;
5937 flags &= ~O_VMS_DELETEONCLOSE;
5941 templte[len-1] != 'X' || templte[len-2] != 'X' || templte[len-3] != 'X' ||
5942 templte[len-4] != 'X' || templte[len-5] != 'X' || templte[len-6] != 'X') {
5943 SETERRNO(EINVAL, LIB_INVARG);
5949 for (i = 1; i <= 6; ++i) {
5950 templte[len-i] = TEMP_FILE_CH[(int)(Perl_internal_drand48() * TEMP_FILE_CH_COUNT)];
5953 if (delete_on_close) {
5954 fd = open(templte, O_RDWR | O_CREAT | O_EXCL | flags, 0600, "fop=dlt");
5959 fd = PerlLIO_open3(templte, O_RDWR | O_CREAT | O_EXCL | flags, 0600);
5961 } while (fd == -1 && errno == EEXIST && ++attempts <= 100);
5968 #ifndef HAS_MKOSTEMP
5970 Perl_my_mkostemp(char *templte, int flags)
5972 PERL_ARGS_ASSERT_MY_MKOSTEMP;
5973 return S_my_mkostemp(templte, flags);
5979 Perl_my_mkstemp(char *templte)
5981 PERL_ARGS_ASSERT_MY_MKSTEMP;
5982 return S_my_mkostemp(templte, 0);
5987 Perl_get_re_arg(pTHX_ SV *sv) {
5993 sv = MUTABLE_SV(SvRV(sv));
5994 if (SvTYPE(sv) == SVt_REGEXP)
5995 return (REGEXP*) sv;
6002 * This code is derived from drand48() implementation from FreeBSD,
6003 * found in lib/libc/gen/_rand48.c.
6005 * The U64 implementation is original, based on the POSIX
6006 * specification for drand48().
6010 * Copyright (c) 1993 Martin Birgmeier
6011 * All rights reserved.
6013 * You may redistribute unmodified or modified versions of this source
6014 * code provided that the above copyright notice and this and the
6015 * following conditions are retained.
6017 * This software is provided ``as is'', and comes with no warranties
6018 * of any kind. I shall in no event be liable for anything that happens
6019 * to anyone/anything when using this software.
6022 #define FREEBSD_DRAND48_SEED_0 (0x330e)
6024 #ifdef PERL_DRAND48_QUAD
6026 #define DRAND48_MULT UINT64_C(0x5deece66d)
6027 #define DRAND48_ADD 0xb
6028 #define DRAND48_MASK UINT64_C(0xffffffffffff)
6032 #define FREEBSD_DRAND48_SEED_1 (0xabcd)
6033 #define FREEBSD_DRAND48_SEED_2 (0x1234)
6034 #define FREEBSD_DRAND48_MULT_0 (0xe66d)
6035 #define FREEBSD_DRAND48_MULT_1 (0xdeec)
6036 #define FREEBSD_DRAND48_MULT_2 (0x0005)
6037 #define FREEBSD_DRAND48_ADD (0x000b)
6039 const unsigned short _rand48_mult[3] = {
6040 FREEBSD_DRAND48_MULT_0,
6041 FREEBSD_DRAND48_MULT_1,
6042 FREEBSD_DRAND48_MULT_2
6044 const unsigned short _rand48_add = FREEBSD_DRAND48_ADD;
6049 Perl_drand48_init_r(perl_drand48_t *random_state, U32 seed)
6051 PERL_ARGS_ASSERT_DRAND48_INIT_R;
6053 #ifdef PERL_DRAND48_QUAD
6054 *random_state = FREEBSD_DRAND48_SEED_0 + ((U64)seed << 16);
6056 random_state->seed[0] = FREEBSD_DRAND48_SEED_0;
6057 random_state->seed[1] = (U16) seed;
6058 random_state->seed[2] = (U16) (seed >> 16);
6063 Perl_drand48_r(perl_drand48_t *random_state)
6065 PERL_ARGS_ASSERT_DRAND48_R;
6067 #ifdef PERL_DRAND48_QUAD
6068 *random_state = (*random_state * DRAND48_MULT + DRAND48_ADD)
6071 return ldexp((double)*random_state, -48);
6077 accu = (U32) _rand48_mult[0] * (U32) random_state->seed[0]
6078 + (U32) _rand48_add;
6079 temp[0] = (U16) accu; /* lower 16 bits */
6080 accu >>= sizeof(U16) * 8;
6081 accu += (U32) _rand48_mult[0] * (U32) random_state->seed[1]
6082 + (U32) _rand48_mult[1] * (U32) random_state->seed[0];
6083 temp[1] = (U16) accu; /* middle 16 bits */
6084 accu >>= sizeof(U16) * 8;
6085 accu += _rand48_mult[0] * random_state->seed[2]
6086 + _rand48_mult[1] * random_state->seed[1]
6087 + _rand48_mult[2] * random_state->seed[0];
6088 random_state->seed[0] = temp[0];
6089 random_state->seed[1] = temp[1];
6090 random_state->seed[2] = (U16) accu;
6092 return ldexp((double) random_state->seed[0], -48) +
6093 ldexp((double) random_state->seed[1], -32) +
6094 ldexp((double) random_state->seed[2], -16);
6099 #ifdef USE_C_BACKTRACE
6101 /* Possibly move all this USE_C_BACKTRACE code into a new file. */
6106 /* abfd is the BFD handle. */
6108 /* bfd_syms is the BFD symbol table. */
6110 /* bfd_text is handle to the the ".text" section of the object file. */
6112 /* Since opening the executable and scanning its symbols is quite
6113 * heavy operation, we remember the filename we used the last time,
6114 * and do the opening and scanning only if the filename changes.
6115 * This removes most (but not all) open+scan cycles. */
6116 const char* fname_prev;
6119 /* Given a dl_info, update the BFD context if necessary. */
6120 static void bfd_update(bfd_context* ctx, Dl_info* dl_info)
6122 /* BFD open and scan only if the filename changed. */
6123 if (ctx->fname_prev == NULL ||
6124 strNE(dl_info->dli_fname, ctx->fname_prev)) {
6126 bfd_close(ctx->abfd);
6128 ctx->abfd = bfd_openr(dl_info->dli_fname, 0);
6130 if (bfd_check_format(ctx->abfd, bfd_object)) {
6131 IV symbol_size = bfd_get_symtab_upper_bound(ctx->abfd);
6132 if (symbol_size > 0) {
6133 Safefree(ctx->bfd_syms);
6134 Newx(ctx->bfd_syms, symbol_size, asymbol*);
6136 bfd_get_section_by_name(ctx->abfd, ".text");
6144 ctx->fname_prev = dl_info->dli_fname;
6148 /* Given a raw frame, try to symbolize it and store
6149 * symbol information (source file, line number) away. */
6150 static void bfd_symbolize(bfd_context* ctx,
6153 STRLEN* symbol_name_size,
6155 STRLEN* source_name_size,
6156 STRLEN* source_line)
6158 *symbol_name = NULL;
6159 *symbol_name_size = 0;
6161 IV offset = PTR2IV(raw_frame) - PTR2IV(ctx->bfd_text->vma);
6163 bfd_canonicalize_symtab(ctx->abfd, ctx->bfd_syms) > 0) {
6166 unsigned int line = 0;
6167 if (bfd_find_nearest_line(ctx->abfd, ctx->bfd_text,
6168 ctx->bfd_syms, offset,
6169 &file, &func, &line) &&
6170 file && func && line > 0) {
6171 /* Size and copy the source file, use only
6172 * the basename of the source file.
6174 * NOTE: the basenames are fine for the
6175 * Perl source files, but may not always
6176 * be the best idea for XS files. */
6177 const char *p, *b = NULL;
6178 /* Look for the last slash. */
6179 for (p = file; *p; p++) {
6183 if (b == NULL || *b == 0) {
6186 *source_name_size = p - b + 1;
6187 Newx(*source_name, *source_name_size + 1, char);
6188 Copy(b, *source_name, *source_name_size + 1, char);
6190 *symbol_name_size = strlen(func);
6191 Newx(*symbol_name, *symbol_name_size + 1, char);
6192 Copy(func, *symbol_name, *symbol_name_size + 1, char);
6194 *source_line = line;
6200 #endif /* #ifdef USE_BFD */
6204 /* OS X has no public API for for 'symbolicating' (Apple official term)
6205 * stack addresses to {function_name, source_file, line_number}.
6206 * Good news: there is command line utility atos(1) which does that.
6207 * Bad news 1: it's a command line utility.
6208 * Bad news 2: one needs to have the Developer Tools installed.
6209 * Bad news 3: in newer releases it needs to be run as 'xcrun atos'.
6211 * To recap: we need to open a pipe for reading for a utility which
6212 * might not exist, or exists in different locations, and then parse
6213 * the output. And since this is all for a low-level API, we cannot
6214 * use high-level stuff. Thanks, Apple. */
6217 /* tool is set to the absolute pathname of the tool to use:
6220 /* format is set to a printf format string used for building
6221 * the external command to run. */
6223 /* unavail is set if e.g. xcrun cannot be found, or something
6224 * else happens that makes getting the backtrace dubious. Note,
6225 * however, that the context isn't persistent, the next call to
6226 * get_c_backtrace() will start from scratch. */
6228 /* fname is the current object file name. */
6230 /* object_base_addr is the base address of the shared object. */
6231 void* object_base_addr;
6234 /* Given |dl_info|, updates the context. If the context has been
6235 * marked unavailable, return immediately. If not but the tool has
6236 * not been set, set it to either "xcrun atos" or "atos" (also set the
6237 * format to use for creating commands for piping), or if neither is
6238 * unavailable (one needs the Developer Tools installed), mark the context
6239 * an unavailable. Finally, update the filename (object name),
6240 * and its base address. */
6242 static void atos_update(atos_context* ctx,
6247 if (ctx->tool == NULL) {
6248 const char* tools[] = {
6252 const char* formats[] = {
6253 "/usr/bin/xcrun atos -o '%s' -l %08x %08x 2>&1",
6254 "/usr/bin/atos -d -o '%s' -l %08x %08x 2>&1"
6258 for (i = 0; i < C_ARRAY_LENGTH(tools); i++) {
6259 if (stat(tools[i], &st) == 0 && S_ISREG(st.st_mode)) {
6260 ctx->tool = tools[i];
6261 ctx->format = formats[i];
6265 if (ctx->tool == NULL) {
6266 ctx->unavail = TRUE;
6270 if (ctx->fname == NULL ||
6271 strNE(dl_info->dli_fname, ctx->fname)) {
6272 ctx->fname = dl_info->dli_fname;
6273 ctx->object_base_addr = dl_info->dli_fbase;
6277 /* Given an output buffer end |p| and its |start|, matches
6278 * for the atos output, extracting the source code location
6279 * and returning non-NULL if possible, returning NULL otherwise. */
6280 static const char* atos_parse(const char* p,
6282 STRLEN* source_name_size,
6283 STRLEN* source_line) {
6284 /* atos() output is something like:
6285 * perl_parse (in miniperl) (perl.c:2314)\n\n".
6286 * We cannot use Perl regular expressions, because we need to
6287 * stay low-level. Therefore here we have a rolled-out version
6288 * of a state machine which matches _backwards_from_the_end_ and
6289 * if there's a success, returns the starts of the filename,
6290 * also setting the filename size and the source line number.
6291 * The matched regular expression is roughly "\(.*:\d+\)\s*$" */
6292 const char* source_number_start;
6293 const char* source_name_end;
6294 const char* source_line_end = start;
6295 const char* close_paren;
6298 /* Skip trailing whitespace. */
6299 while (p > start && isSPACE(*p)) p--;
6300 /* Now we should be at the close paren. */
6301 if (p == start || *p != ')')
6305 /* Now we should be in the line number. */
6306 if (p == start || !isDIGIT(*p))
6308 /* Skip over the digits. */
6309 while (p > start && isDIGIT(*p))
6311 /* Now we should be at the colon. */
6312 if (p == start || *p != ':')
6314 source_number_start = p + 1;
6315 source_name_end = p; /* Just beyond the end. */
6317 /* Look for the open paren. */
6318 while (p > start && *p != '(')
6323 *source_name_size = source_name_end - p;
6324 if (grok_atoUV(source_number_start, &uv, &source_line_end)
6325 && source_line_end == close_paren
6326 && uv <= PERL_INT_MAX
6328 *source_line = (STRLEN)uv;
6334 /* Given a raw frame, read a pipe from the symbolicator (that's the
6335 * technical term) atos, reads the result, and parses the source code
6336 * location. We must stay low-level, so we use snprintf(), pipe(),
6337 * and fread(), and then also parse the output ourselves. */
6338 static void atos_symbolize(atos_context* ctx,
6341 STRLEN* source_name_size,
6342 STRLEN* source_line)
6350 /* Simple security measure: if there's any funny business with
6351 * the object name (used as "-o '%s'" ), leave since at least
6352 * partially the user controls it. */
6353 for (p = ctx->fname; *p; p++) {
6354 if (*p == '\'' || isCNTRL(*p)) {
6355 ctx->unavail = TRUE;
6359 cnt = snprintf(cmd, sizeof(cmd), ctx->format,
6360 ctx->fname, ctx->object_base_addr, raw_frame);
6361 if (cnt < sizeof(cmd)) {
6362 /* Undo nostdio.h #defines that disable stdio.
6363 * This is somewhat naughty, but is used elsewhere
6364 * in the core, and affects only OS X. */
6369 FILE* fp = popen(cmd, "r");
6370 /* At the moment we open a new pipe for each stack frame.
6371 * This is naturally somewhat slow, but hopefully generating
6372 * stack traces is never going to in a performance critical path.
6374 * We could play tricks with atos by batching the stack
6375 * addresses to be resolved: atos can either take multiple
6376 * addresses from the command line, or read addresses from
6377 * a file (though the mess of creating temporary files would
6378 * probably negate much of any possible speedup).
6380 * Normally there are only two objects present in the backtrace:
6381 * perl itself, and the libdyld.dylib. (Note that the object
6382 * filenames contain the full pathname, so perl may not always
6383 * be in the same place.) Whenever the object in the
6384 * backtrace changes, the base address also changes.
6386 * The problem with batching the addresses, though, would be
6387 * matching the results with the addresses: the parsing of
6388 * the results is already painful enough with a single address. */
6391 UV cnt = fread(out, 1, sizeof(out), fp);
6392 if (cnt < sizeof(out)) {
6393 const char* p = atos_parse(out + cnt - 1, out,
6398 *source_name_size, char);
6399 Copy(p, *source_name,
6400 *source_name_size, char);
6408 #endif /* #ifdef PERL_DARWIN */
6411 =for apidoc_section $debugging
6412 =for apidoc get_c_backtrace
6414 Collects the backtrace (aka "stacktrace") into a single linear
6415 malloced buffer, which the caller B<must> C<Perl_free_c_backtrace()>.
6417 Scans the frames back by S<C<depth + skip>>, then drops the C<skip> innermost,
6418 returning at most C<depth> frames.
6424 Perl_get_c_backtrace(pTHX_ int depth, int skip)
6426 /* Note that here we must stay as low-level as possible: Newx(),
6427 * Copy(), Safefree(); since we may be called from anywhere,
6428 * so we should avoid higher level constructs like SVs or AVs.
6430 * Since we are using safesysmalloc() via Newx(), don't try
6431 * getting backtrace() there, unless you like deep recursion. */
6433 /* Currently only implemented with backtrace() and dladdr(),
6434 * for other platforms NULL is returned. */
6436 #if defined(HAS_BACKTRACE) && defined(HAS_DLADDR)
6437 /* backtrace() is available via <execinfo.h> in glibc and in most
6438 * modern BSDs; dladdr() is available via <dlfcn.h>. */
6440 /* We try fetching this many frames total, but then discard
6441 * the |skip| first ones. For the remaining ones we will try
6442 * retrieving more information with dladdr(). */
6443 int try_depth = skip + depth;
6445 /* The addresses (program counters) returned by backtrace(). */
6448 /* Retrieved with dladdr() from the addresses returned by backtrace(). */
6451 /* Sizes _including_ the terminating \0 of the object name
6452 * and symbol name strings. */
6453 STRLEN* object_name_sizes;
6454 STRLEN* symbol_name_sizes;
6457 /* The symbol names comes either from dli_sname,
6458 * or if using BFD, they can come from BFD. */
6459 char** symbol_names;
6462 /* The source code location information. Dug out with e.g. BFD. */
6463 char** source_names;
6464 STRLEN* source_name_sizes;
6465 STRLEN* source_lines;
6467 Perl_c_backtrace* bt = NULL; /* This is what will be returned. */
6468 int got_depth; /* How many frames were returned from backtrace(). */
6469 UV frame_count = 0; /* How many frames we return. */
6470 UV total_bytes = 0; /* The size of the whole returned backtrace. */
6473 bfd_context bfd_ctx;
6476 atos_context atos_ctx;
6479 /* Here are probably possibilities for optimizing. We could for
6480 * example have a struct that contains most of these and then
6481 * allocate |try_depth| of them, saving a bunch of malloc calls.
6482 * Note, however, that |frames| could not be part of that struct
6483 * because backtrace() will want an array of just them. Also be
6484 * careful about the name strings. */
6485 Newx(raw_frames, try_depth, void*);
6486 Newx(dl_infos, try_depth, Dl_info);
6487 Newx(object_name_sizes, try_depth, STRLEN);
6488 Newx(symbol_name_sizes, try_depth, STRLEN);
6489 Newx(source_names, try_depth, char*);
6490 Newx(source_name_sizes, try_depth, STRLEN);
6491 Newx(source_lines, try_depth, STRLEN);
6493 Newx(symbol_names, try_depth, char*);
6496 /* Get the raw frames. */
6497 got_depth = (int)backtrace(raw_frames, try_depth);
6499 /* We use dladdr() instead of backtrace_symbols() because we want
6500 * the full details instead of opaque strings. This is useful for
6501 * two reasons: () the details are needed for further symbolic
6502 * digging, for example in OS X (2) by having the details we fully
6503 * control the output, which in turn is useful when more platforms
6504 * are added: we can keep out output "portable". */
6506 /* We want a single linear allocation, which can then be freed
6507 * with a single swoop. We will do the usual trick of first
6508 * walking over the structure and seeing how much we need to
6509 * allocate, then allocating, and then walking over the structure
6510 * the second time and populating it. */
6512 /* First we must compute the total size of the buffer. */
6513 total_bytes = sizeof(Perl_c_backtrace_header);
6514 if (got_depth > skip) {
6517 bfd_init(); /* Is this safe to call multiple times? */
6518 Zero(&bfd_ctx, 1, bfd_context);
6521 Zero(&atos_ctx, 1, atos_context);
6523 for (i = skip; i < try_depth; i++) {
6524 Dl_info* dl_info = &dl_infos[i];
6526 object_name_sizes[i] = 0;
6527 source_names[i] = NULL;
6528 source_name_sizes[i] = 0;
6529 source_lines[i] = 0;
6531 /* Yes, zero from dladdr() is failure. */
6532 if (dladdr(raw_frames[i], dl_info)) {
6533 total_bytes += sizeof(Perl_c_backtrace_frame);
6535 object_name_sizes[i] =
6536 dl_info->dli_fname ? strlen(dl_info->dli_fname) : 0;
6537 symbol_name_sizes[i] =
6538 dl_info->dli_sname ? strlen(dl_info->dli_sname) : 0;
6540 bfd_update(&bfd_ctx, dl_info);
6541 bfd_symbolize(&bfd_ctx, raw_frames[i],
6543 &symbol_name_sizes[i],
6545 &source_name_sizes[i],
6549 atos_update(&atos_ctx, dl_info);
6550 atos_symbolize(&atos_ctx,
6553 &source_name_sizes[i],
6557 /* Plus ones for the terminating \0. */
6558 total_bytes += object_name_sizes[i] + 1;
6559 total_bytes += symbol_name_sizes[i] + 1;
6560 total_bytes += source_name_sizes[i] + 1;
6568 Safefree(bfd_ctx.bfd_syms);
6572 /* Now we can allocate and populate the result buffer. */
6573 Newxc(bt, total_bytes, char, Perl_c_backtrace);
6574 Zero(bt, total_bytes, char);
6575 bt->header.frame_count = frame_count;
6576 bt->header.total_bytes = total_bytes;
6577 if (frame_count > 0) {
6578 Perl_c_backtrace_frame* frame = bt->frame_info;
6579 char* name_base = (char *)(frame + frame_count);
6580 char* name_curr = name_base; /* Outputting the name strings here. */
6582 for (i = skip; i < skip + frame_count; i++) {
6583 Dl_info* dl_info = &dl_infos[i];
6585 frame->addr = raw_frames[i];
6586 frame->object_base_addr = dl_info->dli_fbase;
6587 frame->symbol_addr = dl_info->dli_saddr;
6589 /* Copies a string, including the \0, and advances the name_curr.
6590 * Also copies the start and the size to the frame. */
6591 #define PERL_C_BACKTRACE_STRCPY(frame, doffset, src, dsize, size) \
6593 Copy(src, name_curr, size, char); \
6594 frame->doffset = name_curr - (char*)bt; \
6595 frame->dsize = size; \
6596 name_curr += size; \
6599 PERL_C_BACKTRACE_STRCPY(frame, object_name_offset,
6601 object_name_size, object_name_sizes[i]);
6604 PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
6606 symbol_name_size, symbol_name_sizes[i]);
6607 Safefree(symbol_names[i]);
6609 PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
6611 symbol_name_size, symbol_name_sizes[i]);
6614 PERL_C_BACKTRACE_STRCPY(frame, source_name_offset,
6616 source_name_size, source_name_sizes[i]);
6617 Safefree(source_names[i]);
6619 #undef PERL_C_BACKTRACE_STRCPY
6621 frame->source_line_number = source_lines[i];
6625 assert(total_bytes ==
6626 (UV)(sizeof(Perl_c_backtrace_header) +
6627 frame_count * sizeof(Perl_c_backtrace_frame) +
6628 name_curr - name_base));
6631 Safefree(symbol_names);
6633 bfd_close(bfd_ctx.abfd);
6636 Safefree(source_lines);
6637 Safefree(source_name_sizes);
6638 Safefree(source_names);
6639 Safefree(symbol_name_sizes);
6640 Safefree(object_name_sizes);
6641 /* Assuming the strings returned by dladdr() are pointers
6642 * to read-only static memory (the object file), so that
6643 * they do not need freeing (and cannot be). */
6645 Safefree(raw_frames);
6648 PERL_UNUSED_ARG(depth);
6649 PERL_UNUSED_ARG(skip);
6655 =for apidoc free_c_backtrace
6657 Deallocates a backtrace received from get_c_backtrace.
6663 =for apidoc get_c_backtrace_dump
6665 Returns a SV containing a dump of C<depth> frames of the call stack, skipping
6666 the C<skip> innermost ones. C<depth> of 20 is usually enough.
6668 The appended output looks like:
6671 1 10e004812:0082 Perl_croak util.c:1716 /usr/bin/perl
6672 2 10df8d6d2:1d72 perl_parse perl.c:3975 /usr/bin/perl
6675 The fields are tab-separated. The first column is the depth (zero
6676 being the innermost non-skipped frame). In the hex:offset, the hex is
6677 where the program counter was in C<S_parse_body>, and the :offset (might
6678 be missing) tells how much inside the C<S_parse_body> the program counter was.
6680 The C<util.c:1716> is the source code file and line number.
6682 The F</usr/bin/perl> is obvious (hopefully).
6684 Unknowns are C<"-">. Unknowns can happen unfortunately quite easily:
6685 if the platform doesn't support retrieving the information;
6686 if the binary is missing the debug information;
6687 if the optimizer has transformed the code by for example inlining.
6693 Perl_get_c_backtrace_dump(pTHX_ int depth, int skip)
6695 Perl_c_backtrace* bt;
6697 bt = get_c_backtrace(depth, skip + 1 /* Hide ourselves. */);
6699 Perl_c_backtrace_frame* frame;
6700 SV* dsv = newSVpvs("");
6702 for (i = 0, frame = bt->frame_info;
6703 i < bt->header.frame_count; i++, frame++) {
6704 Perl_sv_catpvf(aTHX_ dsv, "%d", (int)i);
6705 Perl_sv_catpvf(aTHX_ dsv, "\t%p", frame->addr ? frame->addr : "-");
6706 /* Symbol (function) names might disappear without debug info.
6708 * The source code location might disappear in case of the
6709 * optimizer inlining or otherwise rearranging the code. */
6710 if (frame->symbol_addr) {
6711 Perl_sv_catpvf(aTHX_ dsv, ":%04x",
6713 ((char*)frame->addr - (char*)frame->symbol_addr));
6715 Perl_sv_catpvf(aTHX_ dsv, "\t%s",
6716 frame->symbol_name_size &&
6717 frame->symbol_name_offset ?
6718 (char*)bt + frame->symbol_name_offset : "-");
6719 if (frame->source_name_size &&
6720 frame->source_name_offset &&
6721 frame->source_line_number) {
6722 Perl_sv_catpvf(aTHX_ dsv, "\t%s:%" UVuf,
6723 (char*)bt + frame->source_name_offset,
6724 (UV)frame->source_line_number);
6726 Perl_sv_catpvf(aTHX_ dsv, "\t-");
6728 Perl_sv_catpvf(aTHX_ dsv, "\t%s",
6729 frame->object_name_size &&
6730 frame->object_name_offset ?
6731 (char*)bt + frame->object_name_offset : "-");
6732 /* The frame->object_base_addr is not output,
6733 * but it is used for symbolizing/symbolicating. */
6734 sv_catpvs(dsv, "\n");
6737 Perl_free_c_backtrace(bt);
6746 =for apidoc dump_c_backtrace
6748 Dumps the C backtrace to the given C<fp>.
6750 Returns true if a backtrace could be retrieved, false if not.
6756 Perl_dump_c_backtrace(pTHX_ PerlIO* fp, int depth, int skip)
6760 PERL_ARGS_ASSERT_DUMP_C_BACKTRACE;
6762 sv = Perl_get_c_backtrace_dump(aTHX_ depth, skip);
6765 PerlIO_printf(fp, "%s", SvPV_nolen(sv));
6771 #endif /* #ifdef USE_C_BACKTRACE */
6773 #if defined(USE_ITHREADS) && defined(I_PTHREAD)
6775 /* pthread_mutex_t and perl_mutex are typedef equivalent
6776 * so casting the pointers is fine. */
6778 int perl_tsa_mutex_lock(perl_mutex* mutex)
6780 return pthread_mutex_lock((pthread_mutex_t *) mutex);
6783 int perl_tsa_mutex_unlock(perl_mutex* mutex)
6785 return pthread_mutex_unlock((pthread_mutex_t *) mutex);
6788 int perl_tsa_mutex_destroy(perl_mutex* mutex)
6790 return pthread_mutex_destroy((pthread_mutex_t *) mutex);
6797 /* log a sub call or return */
6800 Perl_dtrace_probe_call(pTHX_ CV *cv, bool is_call)
6808 PERL_ARGS_ASSERT_DTRACE_PROBE_CALL;
6811 HEK *hek = CvNAME_HEK(cv);
6812 func = HEK_KEY(hek);
6818 start = (const COP *)CvSTART(cv);
6819 file = CopFILE(start);
6820 line = CopLINE(start);
6821 stash = CopSTASHPV(start);
6824 PERL_SUB_ENTRY(func, file, line, stash);
6827 PERL_SUB_RETURN(func, file, line, stash);
6832 /* log a require file loading/loaded */
6835 Perl_dtrace_probe_load(pTHX_ const char *name, bool is_loading)
6837 PERL_ARGS_ASSERT_DTRACE_PROBE_LOAD;
6840 PERL_LOADING_FILE(name);
6843 PERL_LOADED_FILE(name);
6848 /* log an op execution */
6851 Perl_dtrace_probe_op(pTHX_ const OP *op)
6853 PERL_ARGS_ASSERT_DTRACE_PROBE_OP;
6855 PERL_OP_ENTRY(OP_NAME(op));
6859 /* log a compile/run phase change */
6862 Perl_dtrace_probe_phase(pTHX_ enum perl_phase phase)
6864 const char *ph_old = PL_phase_names[PL_phase];
6865 const char *ph_new = PL_phase_names[phase];
6867 PERL_PHASE_CHANGE(ph_new, ph_old);
6873 * ex: set ts=8 sts=4 sw=4 et: