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
126 /* paranoid version of system's malloc() */
129 Perl_safesysmalloc(MEM_SIZE size)
131 #ifdef ALWAYS_NEED_THX
137 if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
139 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
142 if ((SSize_t)size < 0)
143 Perl_croak_nocontext("panic: malloc, size=%"UVuf, (UV) size);
145 if (!size) size = 1; /* malloc(0) is NASTY on our system */
146 #ifdef PERL_DEBUG_READONLY_COW
147 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
148 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
149 perror("mmap failed");
153 ptr = (Malloc_t)PerlMem_malloc(size?size:1);
155 PERL_ALLOC_CHECK(ptr);
158 struct perl_memory_debug_header *const header
159 = (struct perl_memory_debug_header *)ptr;
163 PoisonNew(((char *)ptr), size, char);
166 #ifdef PERL_TRACK_MEMPOOL
167 header->interpreter = aTHX;
168 /* Link us into the list. */
169 header->prev = &PL_memory_debug_header;
170 header->next = PL_memory_debug_header.next;
171 PL_memory_debug_header.next = header;
172 maybe_protect_rw(header->next);
173 header->next->prev = header;
174 maybe_protect_ro(header->next);
175 # ifdef PERL_DEBUG_READONLY_COW
176 header->readonly = 0;
182 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
183 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
191 #ifndef ALWAYS_NEED_THX
203 /* paranoid version of system's realloc() */
206 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
208 #ifdef ALWAYS_NEED_THX
212 #ifdef PERL_DEBUG_READONLY_COW
213 const MEM_SIZE oldsize = where
214 ? ((struct perl_memory_debug_header *)((char *)where - PERL_MEMORY_DEBUG_HEADER_SIZE))->size
217 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
218 Malloc_t PerlMem_realloc();
219 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
226 ptr = safesysmalloc(size);
230 where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
231 if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
233 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
235 struct perl_memory_debug_header *const header
236 = (struct perl_memory_debug_header *)where;
238 # ifdef PERL_TRACK_MEMPOOL
239 if (header->interpreter != aTHX) {
240 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
241 header->interpreter, aTHX);
243 assert(header->next->prev == header);
244 assert(header->prev->next == header);
246 if (header->size > size) {
247 const MEM_SIZE freed_up = header->size - size;
248 char *start_of_freed = ((char *)where) + size;
249 PoisonFree(start_of_freed, freed_up, char);
259 if ((SSize_t)size < 0)
260 Perl_croak_nocontext("panic: realloc, size=%"UVuf, (UV)size);
262 #ifdef PERL_DEBUG_READONLY_COW
263 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
264 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
265 perror("mmap failed");
268 Copy(where,ptr,oldsize < size ? oldsize : size,char);
269 if (munmap(where, oldsize)) {
270 perror("munmap failed");
274 ptr = (Malloc_t)PerlMem_realloc(where,size);
276 PERL_ALLOC_CHECK(ptr);
278 /* MUST do this fixup first, before doing ANYTHING else, as anything else
279 might allocate memory/free/move memory, and until we do the fixup, it
280 may well be chasing (and writing to) free memory. */
282 #ifdef PERL_TRACK_MEMPOOL
283 struct perl_memory_debug_header *const header
284 = (struct perl_memory_debug_header *)ptr;
287 if (header->size < size) {
288 const MEM_SIZE fresh = size - header->size;
289 char *start_of_fresh = ((char *)ptr) + size;
290 PoisonNew(start_of_fresh, fresh, char);
294 maybe_protect_rw(header->next);
295 header->next->prev = header;
296 maybe_protect_ro(header->next);
297 maybe_protect_rw(header->prev);
298 header->prev->next = header;
299 maybe_protect_ro(header->prev);
301 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
304 /* In particular, must do that fixup above before logging anything via
305 *printf(), as it can reallocate memory, which can cause SEGVs. */
307 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
308 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
315 #ifndef ALWAYS_NEED_THX
328 /* safe version of system's free() */
331 Perl_safesysfree(Malloc_t where)
333 #ifdef ALWAYS_NEED_THX
336 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
339 Malloc_t where_intrn = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
341 struct perl_memory_debug_header *const header
342 = (struct perl_memory_debug_header *)where_intrn;
345 const MEM_SIZE size = header->size;
347 # ifdef PERL_TRACK_MEMPOOL
348 if (header->interpreter != aTHX) {
349 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
350 header->interpreter, aTHX);
353 Perl_croak_nocontext("panic: duplicate free");
356 Perl_croak_nocontext("panic: bad free, header->next==NULL");
357 if (header->next->prev != header || header->prev->next != header) {
358 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
359 "header=%p, ->prev->next=%p",
360 header->next->prev, header,
363 /* Unlink us from the chain. */
364 maybe_protect_rw(header->next);
365 header->next->prev = header->prev;
366 maybe_protect_ro(header->next);
367 maybe_protect_rw(header->prev);
368 header->prev->next = header->next;
369 maybe_protect_ro(header->prev);
370 maybe_protect_rw(header);
372 PoisonNew(where_intrn, size, char);
374 /* Trigger the duplicate free warning. */
377 # ifdef PERL_DEBUG_READONLY_COW
378 if (munmap(where_intrn, size)) {
379 perror("munmap failed");
385 Malloc_t where_intrn = where;
387 #ifndef PERL_DEBUG_READONLY_COW
388 PerlMem_free(where_intrn);
393 /* safe version of system's calloc() */
396 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
398 #ifdef ALWAYS_NEED_THX
402 #if defined(USE_MDH) || defined(DEBUGGING)
403 MEM_SIZE total_size = 0;
406 /* Even though calloc() for zero bytes is strange, be robust. */
407 if (size && (count <= MEM_SIZE_MAX / size)) {
408 #if defined(USE_MDH) || defined(DEBUGGING)
409 total_size = size * count;
415 if (PERL_MEMORY_DEBUG_HEADER_SIZE <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
416 total_size += PERL_MEMORY_DEBUG_HEADER_SIZE;
421 if ((SSize_t)size < 0 || (SSize_t)count < 0)
422 Perl_croak_nocontext("panic: calloc, size=%"UVuf", count=%"UVuf,
423 (UV)size, (UV)count);
425 #ifdef PERL_DEBUG_READONLY_COW
426 if ((ptr = mmap(0, total_size ? total_size : 1, PROT_READ|PROT_WRITE,
427 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
428 perror("mmap failed");
431 #elif defined(PERL_TRACK_MEMPOOL)
432 /* Have to use malloc() because we've added some space for our tracking
434 /* malloc(0) is non-portable. */
435 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
437 /* Use calloc() because it might save a memset() if the memory is fresh
438 and clean from the OS. */
440 ptr = (Malloc_t)PerlMem_calloc(count, size);
441 else /* calloc(0) is non-portable. */
442 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
444 PERL_ALLOC_CHECK(ptr);
445 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)total_size));
449 struct perl_memory_debug_header *const header
450 = (struct perl_memory_debug_header *)ptr;
452 # ifndef PERL_DEBUG_READONLY_COW
453 memset((void*)ptr, 0, total_size);
455 # ifdef PERL_TRACK_MEMPOOL
456 header->interpreter = aTHX;
457 /* Link us into the list. */
458 header->prev = &PL_memory_debug_header;
459 header->next = PL_memory_debug_header.next;
460 PL_memory_debug_header.next = header;
461 maybe_protect_rw(header->next);
462 header->next->prev = header;
463 maybe_protect_ro(header->next);
464 # ifdef PERL_DEBUG_READONLY_COW
465 header->readonly = 0;
469 header->size = total_size;
471 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
477 #ifndef ALWAYS_NEED_THX
486 /* These must be defined when not using Perl's malloc for binary
491 Malloc_t Perl_malloc (MEM_SIZE nbytes)
493 #ifdef PERL_IMPLICIT_SYS
496 return (Malloc_t)PerlMem_malloc(nbytes);
499 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
501 #ifdef PERL_IMPLICIT_SYS
504 return (Malloc_t)PerlMem_calloc(elements, size);
507 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
509 #ifdef PERL_IMPLICIT_SYS
512 return (Malloc_t)PerlMem_realloc(where, nbytes);
515 Free_t Perl_mfree (Malloc_t where)
517 #ifdef PERL_IMPLICIT_SYS
525 /* copy a string up to some (non-backslashed) delimiter, if any */
528 Perl_delimcpy(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen)
532 PERL_ARGS_ASSERT_DELIMCPY;
534 for (tolen = 0; from < fromend; from++, tolen++) {
536 if (from[1] != delim) {
543 else if (*from == delim)
555 =head1 Miscellaneous Functions
557 =for apidoc Am|char *|ninstr|char * big|char * bigend|char * little|char * little_end
559 Find the first (leftmost) occurrence of a sequence of bytes within another
560 sequence. This is the Perl version of C<strstr()>, extended to handle
561 arbitrary sequences, potentially containing embedded C<NUL> characters (C<NUL>
562 is what the initial C<n> in the function name stands for; some systems have an
563 equivalent, C<memmem()>, but with a somewhat different API).
565 Another way of thinking about this function is finding a needle in a haystack.
566 C<big> points to the first byte in the haystack. C<big_end> points to one byte
567 beyond the final byte in the haystack. C<little> points to the first byte in
568 the needle. C<little_end> points to one byte beyond the final byte in the
569 needle. All the parameters must be non-C<NULL>.
571 The function returns C<NULL> if there is no occurrence of C<little> within
572 C<big>. If C<little> is the empty string, C<big> is returned.
574 Because this function operates at the byte level, and because of the inherent
575 characteristics of UTF-8 (or UTF-EBCDIC), it will work properly if both the
576 needle and the haystack are strings with the same UTF-8ness, but not if the
584 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
586 PERL_ARGS_ASSERT_NINSTR;
590 const char first = *little;
592 bigend -= lend - little++;
594 while (big <= bigend) {
595 if (*big++ == first) {
596 for (x=big,s=little; s < lend; x++,s++) {
600 return (char*)(big-1);
608 =head1 Miscellaneous Functions
610 =for apidoc Am|char *|rninstr|char * big|char * bigend|char * little|char * little_end
612 Like C<L</ninstr>>, but instead finds the final (rightmost) occurrence of a
613 sequence of bytes within another sequence, returning C<NULL> if there is no
621 Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
624 const I32 first = *little;
625 const char * const littleend = lend;
627 PERL_ARGS_ASSERT_RNINSTR;
629 if (little >= littleend)
630 return (char*)bigend;
632 big = bigend - (littleend - little++);
633 while (big >= bigbeg) {
637 for (x=big+2,s=little; s < littleend; /**/ ) {
646 return (char*)(big+1);
651 /* As a space optimization, we do not compile tables for strings of length
652 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
653 special-cased in fbm_instr().
655 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
658 =head1 Miscellaneous Functions
660 =for apidoc fbm_compile
662 Analyses the string in order to make fast searches on it using C<fbm_instr()>
663 -- the Boyer-Moore algorithm.
669 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
676 PERL_DEB( STRLEN rarest = 0 );
678 PERL_ARGS_ASSERT_FBM_COMPILE;
680 if (isGV_with_GP(sv) || SvROK(sv))
686 if (flags & FBMcf_TAIL) {
687 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
688 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
689 if (mg && mg->mg_len >= 0)
692 if (!SvPOK(sv) || SvNIOKp(sv))
693 s = (U8*)SvPV_force_mutable(sv, len);
694 else s = (U8 *)SvPV_mutable(sv, len);
695 if (len == 0) /* TAIL might be on a zero-length string. */
697 SvUPGRADE(sv, SVt_PVMG);
702 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
703 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
704 to call SvVALID_off() if the scalar was assigned to.
706 The comment itself (and "deeper magic" below) date back to
707 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
709 where the magic (presumably) was that the scalar had a BM table hidden
712 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
713 the table instead of the previous (somewhat hacky) approach of co-opting
714 the string buffer and storing it after the string. */
716 assert(!mg_find(sv, PERL_MAGIC_bm));
717 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
721 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
723 const U8 mlen = (len>255) ? 255 : (U8)len;
724 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
727 Newx(table, 256, U8);
728 memset((void*)table, mlen, 256);
729 mg->mg_ptr = (char *)table;
732 s += len - 1; /* last char */
735 if (table[*s] == mlen)
741 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
742 for (i = 0; i < len; i++) {
743 if (PL_freq[s[i]] < frequency) {
744 PERL_DEB( rarest = i );
745 frequency = PL_freq[s[i]];
748 BmUSEFUL(sv) = 100; /* Initial value */
749 if (flags & FBMcf_TAIL)
751 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
752 s[rarest], (UV)rarest));
757 =for apidoc fbm_instr
759 Returns the location of the SV in the string delimited by C<big> and
760 C<bigend> (C<bigend>) is the char following the last char).
761 It returns C<NULL> if the string can't be found. The C<sv>
762 does not have to be C<fbm_compiled>, but the search will not be as fast
767 If SvTAIL(littlestr) is true, a fake "\n" was appended to to the string
768 during FBM compilation due to FBMcf_TAIL in flags. It indicates that
769 the littlestr must be anchored to the end of bigstr (or to any \n if
772 E.g. The regex compiler would compile /abc/ to a littlestr of "abc",
773 while /abc$/ compiles to "abc\n" with SvTAIL() true.
775 A littlestr of "abc", !SvTAIL matches as /abc/;
776 a littlestr of "ab\n", SvTAIL matches as:
777 without FBMrf_MULTILINE: /ab\n?\z/
778 with FBMrf_MULTILINE: /ab\n/ || /ab\z/;
780 (According to Ilya from 1999; I don't know if this is still true, DAPM 2015):
781 "If SvTAIL is actually due to \Z or \z, this gives false positives
787 Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
791 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
792 STRLEN littlelen = l;
793 const I32 multiline = flags & FBMrf_MULTILINE;
795 PERL_ARGS_ASSERT_FBM_INSTR;
797 if ((STRLEN)(bigend - big) < littlelen) {
798 if ( SvTAIL(littlestr)
799 && ((STRLEN)(bigend - big) == littlelen - 1)
801 || (*big == *little &&
802 memEQ((char *)big, (char *)little, littlelen - 1))))
807 switch (littlelen) { /* Special cases for 0, 1 and 2 */
809 return (char*)big; /* Cannot be SvTAIL! */
812 if (SvTAIL(littlestr) && !multiline) /* Anchor only! */
813 /* [-1] is safe because we know that bigend != big. */
814 return (char *) (bigend - (bigend[-1] == '\n'));
816 s = (unsigned char *)memchr((void*)big, *little, bigend-big);
819 if (SvTAIL(littlestr))
820 return (char *) bigend;
824 if (SvTAIL(littlestr) && !multiline) {
825 /* a littlestr with SvTAIL must be of the form "X\n" (where X
826 * is a single char). It is anchored, and can only match
827 * "....X\n" or "....X" */
828 if (bigend[-2] == *little && bigend[-1] == '\n')
829 return (char*)bigend - 2;
830 if (bigend[-1] == *little)
831 return (char*)bigend - 1;
836 /* memchr() is likely to be very fast, possibly using whatever
837 * hardware support is available, such as checking a whole
838 * cache line in one instruction.
839 * So for a 2 char pattern, calling memchr() is likely to be
840 * faster than running FBM, or rolling our own. The previous
841 * version of this code was roll-your-own which typically
842 * only needed to read every 2nd char, which was good back in
843 * the day, but no longer.
845 unsigned char c1 = little[0];
846 unsigned char c2 = little[1];
848 /* *** for all this case, bigend points to the last char,
849 * not the trailing \0: this makes the conditions slightly
855 /* do a quick test for c1 before calling memchr();
856 * this avoids the expensive fn call overhead when
857 * there are lots of c1's */
858 if (LIKELY(*s != c1)) {
860 s = (unsigned char *)memchr((void*)s, c1, bigend - s);
867 /* failed; try searching for c2 this time; that way
868 * we don't go pathologically slow when the string
869 * consists mostly of c1's or vice versa.
874 s = (unsigned char *)memchr((void*)s, c2, bigend - s + 1);
882 /* c1, c2 the same */
892 s = (unsigned char *)memchr((void*)s, c1, bigend - s);
893 if (!s || s >= bigend)
900 /* failed to find 2 chars; try anchored match at end without
902 if (SvTAIL(littlestr) && bigend[0] == little[0])
903 return (char *)bigend;
908 break; /* Only lengths 0 1 and 2 have special-case code. */
911 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
912 s = bigend - littlelen;
913 if (s >= big && bigend[-1] == '\n' && *s == *little
914 /* Automatically of length > 2 */
915 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
917 return (char*)s; /* how sweet it is */
920 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
922 return (char*)s + 1; /* how sweet it is */
927 if (!SvVALID(littlestr)) {
928 /* not compiled; use Perl_ninstr() instead */
929 char * const b = ninstr((char*)big,(char*)bigend,
930 (char*)little, (char*)little + littlelen);
932 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
933 /* Chop \n from littlestr: */
934 s = bigend - littlelen + 1;
936 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
946 if (littlelen > (STRLEN)(bigend - big))
950 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
951 const unsigned char *oldlittle;
955 --littlelen; /* Last char found by table lookup */
958 little += littlelen; /* last char */
961 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
962 const unsigned char lastc = *little;
966 if ((tmp = table[*s])) {
967 /* *s != lastc; earliest position it could match now is
968 * tmp slots further on */
969 if ((s += tmp) >= bigend)
971 if (LIKELY(*s != lastc)) {
973 s = (unsigned char *)memchr((void*)s, lastc, bigend - s);
983 /* hand-rolled strncmp(): less expensive than calling the
984 * real function (maybe???) */
986 unsigned char * const olds = s;
991 if (*--s == *--little)
993 s = olds + 1; /* here we pay the price for failure */
995 if (s < bigend) /* fake up continue to outer loop */
1004 && SvTAIL(littlestr)
1005 && memEQ((char *)(bigend - littlelen),
1006 (char *)(oldlittle - littlelen), littlelen) )
1007 return (char*)bigend - littlelen;
1016 Returns true if the leading C<len> bytes of the strings C<s1> and C<s2> are the
1018 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
1019 match themselves and their opposite case counterparts. Non-cased and non-ASCII
1020 range bytes match only themselves.
1027 Perl_foldEQ(const char *s1, const char *s2, I32 len)
1029 const U8 *a = (const U8 *)s1;
1030 const U8 *b = (const U8 *)s2;
1032 PERL_ARGS_ASSERT_FOLDEQ;
1037 if (*a != *b && *a != PL_fold[*b])
1044 Perl_foldEQ_latin1(const char *s1, const char *s2, I32 len)
1046 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
1047 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
1048 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
1049 * does it check that the strings each have at least 'len' characters */
1051 const U8 *a = (const U8 *)s1;
1052 const U8 *b = (const U8 *)s2;
1054 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
1059 if (*a != *b && *a != PL_fold_latin1[*b]) {
1068 =for apidoc foldEQ_locale
1070 Returns true if the leading C<len> bytes of the strings C<s1> and C<s2> are the
1071 same case-insensitively in the current locale; false otherwise.
1077 Perl_foldEQ_locale(const char *s1, const char *s2, I32 len)
1080 const U8 *a = (const U8 *)s1;
1081 const U8 *b = (const U8 *)s2;
1083 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
1088 if (*a != *b && *a != PL_fold_locale[*b])
1095 /* copy a string to a safe spot */
1098 =head1 Memory Management
1102 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1103 string which is a duplicate of C<pv>. The size of the string is
1104 determined by C<strlen()>, which means it may not contain embedded C<NUL>
1105 characters and must have a trailing C<NUL>. The memory allocated for the new
1106 string can be freed with the C<Safefree()> function.
1108 On some platforms, Windows for example, all allocated memory owned by a thread
1109 is deallocated when that thread ends. So if you need that not to happen, you
1110 need to use the shared memory functions, such as C<L</savesharedpv>>.
1116 Perl_savepv(pTHX_ const char *pv)
1118 PERL_UNUSED_CONTEXT;
1123 const STRLEN pvlen = strlen(pv)+1;
1124 Newx(newaddr, pvlen, char);
1125 return (char*)memcpy(newaddr, pv, pvlen);
1129 /* same thing but with a known length */
1134 Perl's version of what C<strndup()> would be if it existed. Returns a
1135 pointer to a newly allocated string which is a duplicate of the first
1136 C<len> bytes from C<pv>, plus a trailing
1137 C<NUL> byte. The memory allocated for
1138 the new string can be freed with the C<Safefree()> function.
1140 On some platforms, Windows for example, all allocated memory owned by a thread
1141 is deallocated when that thread ends. So if you need that not to happen, you
1142 need to use the shared memory functions, such as C<L</savesharedpvn>>.
1148 Perl_savepvn(pTHX_ const char *pv, I32 len)
1151 PERL_UNUSED_CONTEXT;
1155 Newx(newaddr,len+1,char);
1156 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1158 /* might not be null terminated */
1159 newaddr[len] = '\0';
1160 return (char *) CopyD(pv,newaddr,len,char);
1163 return (char *) ZeroD(newaddr,len+1,char);
1168 =for apidoc savesharedpv
1170 A version of C<savepv()> which allocates the duplicate string in memory
1171 which is shared between threads.
1176 Perl_savesharedpv(pTHX_ const char *pv)
1181 PERL_UNUSED_CONTEXT;
1186 pvlen = strlen(pv)+1;
1187 newaddr = (char*)PerlMemShared_malloc(pvlen);
1191 return (char*)memcpy(newaddr, pv, pvlen);
1195 =for apidoc savesharedpvn
1197 A version of C<savepvn()> which allocates the duplicate string in memory
1198 which is shared between threads. (With the specific difference that a C<NULL>
1199 pointer is not acceptable)
1204 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1206 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1208 PERL_UNUSED_CONTEXT;
1209 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1214 newaddr[len] = '\0';
1215 return (char*)memcpy(newaddr, pv, len);
1219 =for apidoc savesvpv
1221 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1222 the passed in SV using C<SvPV()>
1224 On some platforms, Windows for example, all allocated memory owned by a thread
1225 is deallocated when that thread ends. So if you need that not to happen, you
1226 need to use the shared memory functions, such as C<L</savesharedsvpv>>.
1232 Perl_savesvpv(pTHX_ SV *sv)
1235 const char * const pv = SvPV_const(sv, len);
1238 PERL_ARGS_ASSERT_SAVESVPV;
1241 Newx(newaddr,len,char);
1242 return (char *) CopyD(pv,newaddr,len,char);
1246 =for apidoc savesharedsvpv
1248 A version of C<savesharedpv()> which allocates the duplicate string in
1249 memory which is shared between threads.
1255 Perl_savesharedsvpv(pTHX_ SV *sv)
1258 const char * const pv = SvPV_const(sv, len);
1260 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1262 return savesharedpvn(pv, len);
1265 /* the SV for Perl_form() and mess() is not kept in an arena */
1273 if (PL_phase != PERL_PHASE_DESTRUCT)
1274 return newSVpvs_flags("", SVs_TEMP);
1279 /* Create as PVMG now, to avoid any upgrading later */
1281 Newxz(any, 1, XPVMG);
1282 SvFLAGS(sv) = SVt_PVMG;
1283 SvANY(sv) = (void*)any;
1285 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1290 #if defined(PERL_IMPLICIT_CONTEXT)
1292 Perl_form_nocontext(const char* pat, ...)
1297 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1298 va_start(args, pat);
1299 retval = vform(pat, &args);
1303 #endif /* PERL_IMPLICIT_CONTEXT */
1306 =head1 Miscellaneous Functions
1309 Takes a sprintf-style format pattern and conventional
1310 (non-SV) arguments and returns the formatted string.
1312 (char *) Perl_form(pTHX_ const char* pat, ...)
1314 can be used any place a string (char *) is required:
1316 char * s = Perl_form("%d.%d",major,minor);
1318 Uses a single private buffer so if you want to format several strings you
1319 must explicitly copy the earlier strings away (and free the copies when you
1326 Perl_form(pTHX_ const char* pat, ...)
1330 PERL_ARGS_ASSERT_FORM;
1331 va_start(args, pat);
1332 retval = vform(pat, &args);
1338 Perl_vform(pTHX_ const char *pat, va_list *args)
1340 SV * const sv = mess_alloc();
1341 PERL_ARGS_ASSERT_VFORM;
1342 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1347 =for apidoc Am|SV *|mess|const char *pat|...
1349 Take a sprintf-style format pattern and argument list. These are used to
1350 generate a string message. If the message does not end with a newline,
1351 then it will be extended with some indication of the current location
1352 in the code, as described for L</mess_sv>.
1354 Normally, the resulting message is returned in a new mortal SV.
1355 During global destruction a single SV may be shared between uses of
1361 #if defined(PERL_IMPLICIT_CONTEXT)
1363 Perl_mess_nocontext(const char *pat, ...)
1368 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1369 va_start(args, pat);
1370 retval = vmess(pat, &args);
1374 #endif /* PERL_IMPLICIT_CONTEXT */
1377 Perl_mess(pTHX_ const char *pat, ...)
1381 PERL_ARGS_ASSERT_MESS;
1382 va_start(args, pat);
1383 retval = vmess(pat, &args);
1389 Perl_closest_cop(pTHX_ const COP *cop, const OP *o, const OP *curop,
1392 /* Look for curop starting from o. cop is the last COP we've seen. */
1393 /* opnext means that curop is actually the ->op_next of the op we are
1396 PERL_ARGS_ASSERT_CLOSEST_COP;
1398 if (!o || !curop || (
1399 opnext ? o->op_next == curop && o->op_type != OP_SCOPE : o == curop
1403 if (o->op_flags & OPf_KIDS) {
1405 for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
1408 /* If the OP_NEXTSTATE has been optimised away we can still use it
1409 * the get the file and line number. */
1411 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1412 cop = (const COP *)kid;
1414 /* Keep searching, and return when we've found something. */
1416 new_cop = closest_cop(cop, kid, curop, opnext);
1422 /* Nothing found. */
1428 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1430 Expands a message, intended for the user, to include an indication of
1431 the current location in the code, if the message does not already appear
1434 C<basemsg> is the initial message or object. If it is a reference, it
1435 will be used as-is and will be the result of this function. Otherwise it
1436 is used as a string, and if it already ends with a newline, it is taken
1437 to be complete, and the result of this function will be the same string.
1438 If the message does not end with a newline, then a segment such as C<at
1439 foo.pl line 37> will be appended, and possibly other clauses indicating
1440 the current state of execution. The resulting message will end with a
1443 Normally, the resulting message is returned in a new mortal SV.
1444 During global destruction a single SV may be shared between uses of this
1445 function. If C<consume> is true, then the function is permitted (but not
1446 required) to modify and return C<basemsg> instead of allocating a new SV.
1452 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1456 #if defined(USE_C_BACKTRACE) && defined(USE_C_BACKTRACE_ON_ERROR)
1460 /* The PERL_C_BACKTRACE_ON_WARN must be an integer of one or more. */
1461 if ((ws = PerlEnv_getenv("PERL_C_BACKTRACE_ON_ERROR"))
1462 && grok_atoUV(ws, &wi, NULL)
1463 && wi <= PERL_INT_MAX
1465 Perl_dump_c_backtrace(aTHX_ Perl_debug_log, (int)wi, 1);
1470 PERL_ARGS_ASSERT_MESS_SV;
1472 if (SvROK(basemsg)) {
1478 sv_setsv(sv, basemsg);
1483 if (SvPOK(basemsg) && consume) {
1488 sv_copypv(sv, basemsg);
1491 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1493 * Try and find the file and line for PL_op. This will usually be
1494 * PL_curcop, but it might be a cop that has been optimised away. We
1495 * can try to find such a cop by searching through the optree starting
1496 * from the sibling of PL_curcop.
1500 closest_cop(PL_curcop, OpSIBLING(PL_curcop), PL_op, FALSE);
1505 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1506 OutCopFILE(cop), (IV)CopLINE(cop));
1507 /* Seems that GvIO() can be untrustworthy during global destruction. */
1508 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1509 && IoLINES(GvIOp(PL_last_in_gv)))
1512 const bool line_mode = (RsSIMPLE(PL_rs) &&
1513 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1514 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1515 SVfARG(PL_last_in_gv == PL_argvgv
1517 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1518 line_mode ? "line" : "chunk",
1519 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1521 if (PL_phase == PERL_PHASE_DESTRUCT)
1522 sv_catpvs(sv, " during global destruction");
1523 sv_catpvs(sv, ".\n");
1529 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1531 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1532 argument list, respectively. These are used to generate a string message. If
1534 message does not end with a newline, then it will be extended with
1535 some indication of the current location in the code, as described for
1538 Normally, the resulting message is returned in a new mortal SV.
1539 During global destruction a single SV may be shared between uses of
1546 Perl_vmess(pTHX_ const char *pat, va_list *args)
1548 SV * const sv = mess_alloc();
1550 PERL_ARGS_ASSERT_VMESS;
1552 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1553 return mess_sv(sv, 1);
1557 Perl_write_to_stderr(pTHX_ SV* msv)
1562 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1564 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1565 && (io = GvIO(PL_stderrgv))
1566 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1567 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, SV_CONST(PRINT),
1568 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1570 PerlIO * const serr = Perl_error_log;
1572 do_print(msv, serr);
1573 (void)PerlIO_flush(serr);
1578 =head1 Warning and Dieing
1581 /* Common code used in dieing and warning */
1584 S_with_queued_errors(pTHX_ SV *ex)
1586 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1587 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1588 sv_catsv(PL_errors, ex);
1589 ex = sv_mortalcopy(PL_errors);
1590 SvCUR_set(PL_errors, 0);
1596 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1601 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1602 /* sv_2cv might call Perl_croak() or Perl_warner() */
1603 SV * const oldhook = *hook;
1611 cv = sv_2cv(oldhook, &stash, &gv, 0);
1613 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1623 exarg = newSVsv(ex);
1624 SvREADONLY_on(exarg);
1627 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1631 call_sv(MUTABLE_SV(cv), G_DISCARD);
1640 =for apidoc Am|OP *|die_sv|SV *baseex
1642 Behaves the same as L</croak_sv>, except for the return type.
1643 It should be used only where the C<OP *> return type is required.
1644 The function never actually returns.
1650 # pragma warning( push )
1651 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1652 __declspec(noreturn) has non-void return type */
1653 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1654 __declspec(noreturn) has a return statement */
1657 Perl_die_sv(pTHX_ SV *baseex)
1659 PERL_ARGS_ASSERT_DIE_SV;
1662 NORETURN_FUNCTION_END;
1665 # pragma warning( pop )
1669 =for apidoc Am|OP *|die|const char *pat|...
1671 Behaves the same as L</croak>, except for the return type.
1672 It should be used only where the C<OP *> return type is required.
1673 The function never actually returns.
1678 #if defined(PERL_IMPLICIT_CONTEXT)
1680 # pragma warning( push )
1681 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1682 __declspec(noreturn) has non-void return type */
1683 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1684 __declspec(noreturn) has a return statement */
1687 Perl_die_nocontext(const char* pat, ...)
1691 va_start(args, pat);
1693 NOT_REACHED; /* NOTREACHED */
1695 NORETURN_FUNCTION_END;
1698 # pragma warning( pop )
1700 #endif /* PERL_IMPLICIT_CONTEXT */
1703 # pragma warning( push )
1704 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1705 __declspec(noreturn) has non-void return type */
1706 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1707 __declspec(noreturn) has a return statement */
1710 Perl_die(pTHX_ const char* pat, ...)
1713 va_start(args, pat);
1715 NOT_REACHED; /* NOTREACHED */
1717 NORETURN_FUNCTION_END;
1720 # pragma warning( pop )
1724 =for apidoc Am|void|croak_sv|SV *baseex
1726 This is an XS interface to Perl's C<die> function.
1728 C<baseex> is the error message or object. If it is a reference, it
1729 will be used as-is. Otherwise it is used as a string, and if it does
1730 not end with a newline then it will be extended with some indication of
1731 the current location in the code, as described for L</mess_sv>.
1733 The error message or object will be used as an exception, by default
1734 returning control to the nearest enclosing C<eval>, but subject to
1735 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1736 function never returns normally.
1738 To die with a simple string message, the L</croak> function may be
1745 Perl_croak_sv(pTHX_ SV *baseex)
1747 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1748 PERL_ARGS_ASSERT_CROAK_SV;
1749 invoke_exception_hook(ex, FALSE);
1754 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1756 This is an XS interface to Perl's C<die> function.
1758 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1759 argument list. These are used to generate a string message. If the
1760 message does not end with a newline, then it will be extended with
1761 some indication of the current location in the code, as described for
1764 The error message will be used as an exception, by default
1765 returning control to the nearest enclosing C<eval>, but subject to
1766 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1767 function never returns normally.
1769 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1770 (C<$@>) will be used as an error message or object instead of building an
1771 error message from arguments. If you want to throw a non-string object,
1772 or build an error message in an SV yourself, it is preferable to use
1773 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1779 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1781 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1782 invoke_exception_hook(ex, FALSE);
1787 =for apidoc Am|void|croak|const char *pat|...
1789 This is an XS interface to Perl's C<die> function.
1791 Take a sprintf-style format pattern and argument list. These are used to
1792 generate a string message. If the message does not end with a newline,
1793 then it will be extended with some indication of the current location
1794 in the code, as described for L</mess_sv>.
1796 The error message will be used as an exception, by default
1797 returning control to the nearest enclosing C<eval>, but subject to
1798 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1799 function never returns normally.
1801 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1802 (C<$@>) will be used as an error message or object instead of building an
1803 error message from arguments. If you want to throw a non-string object,
1804 or build an error message in an SV yourself, it is preferable to use
1805 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1810 #if defined(PERL_IMPLICIT_CONTEXT)
1812 Perl_croak_nocontext(const char *pat, ...)
1816 va_start(args, pat);
1818 NOT_REACHED; /* NOTREACHED */
1821 #endif /* PERL_IMPLICIT_CONTEXT */
1824 Perl_croak(pTHX_ const char *pat, ...)
1827 va_start(args, pat);
1829 NOT_REACHED; /* NOTREACHED */
1834 =for apidoc Am|void|croak_no_modify
1836 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1837 terser object code than using C<Perl_croak>. Less code used on exception code
1838 paths reduces CPU cache pressure.
1844 Perl_croak_no_modify(void)
1846 Perl_croak_nocontext( "%s", PL_no_modify);
1849 /* does not return, used in util.c perlio.c and win32.c
1850 This is typically called when malloc returns NULL.
1853 Perl_croak_no_mem(void)
1857 int fd = PerlIO_fileno(Perl_error_log);
1859 SETERRNO(EBADF,RMS_IFI);
1861 /* Can't use PerlIO to write as it allocates memory */
1862 PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, sizeof(PL_no_mem)-1));
1867 /* does not return, used only in POPSTACK */
1869 Perl_croak_popstack(void)
1872 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
1877 =for apidoc Am|void|warn_sv|SV *baseex
1879 This is an XS interface to Perl's C<warn> function.
1881 C<baseex> is the error message or object. If it is a reference, it
1882 will be used as-is. Otherwise it is used as a string, and if it does
1883 not end with a newline then it will be extended with some indication of
1884 the current location in the code, as described for L</mess_sv>.
1886 The error message or object will by default be written to standard error,
1887 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1889 To warn with a simple string message, the L</warn> function may be
1896 Perl_warn_sv(pTHX_ SV *baseex)
1898 SV *ex = mess_sv(baseex, 0);
1899 PERL_ARGS_ASSERT_WARN_SV;
1900 if (!invoke_exception_hook(ex, TRUE))
1901 write_to_stderr(ex);
1905 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1907 This is an XS interface to Perl's C<warn> function.
1909 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1910 argument list. These are used to generate a string message. If the
1911 message does not end with a newline, then it will be extended with
1912 some indication of the current location in the code, as described for
1915 The error message or object will by default be written to standard error,
1916 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1918 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1924 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1926 SV *ex = vmess(pat, args);
1927 PERL_ARGS_ASSERT_VWARN;
1928 if (!invoke_exception_hook(ex, TRUE))
1929 write_to_stderr(ex);
1933 =for apidoc Am|void|warn|const char *pat|...
1935 This is an XS interface to Perl's C<warn> function.
1937 Take a sprintf-style format pattern and argument list. These are used to
1938 generate a string message. If the message does not end with a newline,
1939 then it will be extended with some indication of the current location
1940 in the code, as described for L</mess_sv>.
1942 The error message or object will by default be written to standard error,
1943 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1945 Unlike with L</croak>, C<pat> is not permitted to be null.
1950 #if defined(PERL_IMPLICIT_CONTEXT)
1952 Perl_warn_nocontext(const char *pat, ...)
1956 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1957 va_start(args, pat);
1961 #endif /* PERL_IMPLICIT_CONTEXT */
1964 Perl_warn(pTHX_ const char *pat, ...)
1967 PERL_ARGS_ASSERT_WARN;
1968 va_start(args, pat);
1973 #if defined(PERL_IMPLICIT_CONTEXT)
1975 Perl_warner_nocontext(U32 err, const char *pat, ...)
1979 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1980 va_start(args, pat);
1981 vwarner(err, pat, &args);
1984 #endif /* PERL_IMPLICIT_CONTEXT */
1987 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1989 PERL_ARGS_ASSERT_CK_WARNER_D;
1991 if (Perl_ckwarn_d(aTHX_ err)) {
1993 va_start(args, pat);
1994 vwarner(err, pat, &args);
2000 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
2002 PERL_ARGS_ASSERT_CK_WARNER;
2004 if (Perl_ckwarn(aTHX_ err)) {
2006 va_start(args, pat);
2007 vwarner(err, pat, &args);
2013 Perl_warner(pTHX_ U32 err, const char* pat,...)
2016 PERL_ARGS_ASSERT_WARNER;
2017 va_start(args, pat);
2018 vwarner(err, pat, &args);
2023 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
2026 PERL_ARGS_ASSERT_VWARNER;
2028 (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) &&
2029 !(PL_in_eval & EVAL_KEEPERR)
2031 SV * const msv = vmess(pat, args);
2033 if (PL_parser && PL_parser->error_count) {
2037 invoke_exception_hook(msv, FALSE);
2042 Perl_vwarn(aTHX_ pat, args);
2046 /* implements the ckWARN? macros */
2049 Perl_ckwarn(pTHX_ U32 w)
2051 /* If lexical warnings have not been set, use $^W. */
2053 return PL_dowarn & G_WARN_ON;
2055 return ckwarn_common(w);
2058 /* implements the ckWARN?_d macro */
2061 Perl_ckwarn_d(pTHX_ U32 w)
2063 /* If lexical warnings have not been set then default classes warn. */
2067 return ckwarn_common(w);
2071 S_ckwarn_common(pTHX_ U32 w)
2073 if (PL_curcop->cop_warnings == pWARN_ALL)
2076 if (PL_curcop->cop_warnings == pWARN_NONE)
2079 /* Check the assumption that at least the first slot is non-zero. */
2080 assert(unpackWARN1(w));
2082 /* Check the assumption that it is valid to stop as soon as a zero slot is
2084 if (!unpackWARN2(w)) {
2085 assert(!unpackWARN3(w));
2086 assert(!unpackWARN4(w));
2087 } else if (!unpackWARN3(w)) {
2088 assert(!unpackWARN4(w));
2091 /* Right, dealt with all the special cases, which are implemented as non-
2092 pointers, so there is a pointer to a real warnings mask. */
2094 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
2096 } while (w >>= WARNshift);
2101 /* Set buffer=NULL to get a new one. */
2103 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
2105 const MEM_SIZE len_wanted =
2106 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
2107 PERL_UNUSED_CONTEXT;
2108 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
2111 (specialWARN(buffer) ?
2112 PerlMemShared_malloc(len_wanted) :
2113 PerlMemShared_realloc(buffer, len_wanted));
2115 Copy(bits, (buffer + 1), size, char);
2116 if (size < WARNsize)
2117 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
2121 /* since we've already done strlen() for both nam and val
2122 * we can use that info to make things faster than
2123 * sprintf(s, "%s=%s", nam, val)
2125 #define my_setenv_format(s, nam, nlen, val, vlen) \
2126 Copy(nam, s, nlen, char); \
2128 Copy(val, s+(nlen+1), vlen, char); \
2129 *(s+(nlen+1+vlen)) = '\0'
2131 #ifdef USE_ENVIRON_ARRAY
2132 /* VMS' my_setenv() is in vms.c */
2133 #if !defined(WIN32) && !defined(NETWARE)
2135 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2139 amigaos4_obtain_environ(__FUNCTION__);
2142 /* only parent thread can modify process environment */
2143 if (PL_curinterp == aTHX)
2146 #ifndef PERL_USE_SAFE_PUTENV
2147 if (!PL_use_safe_putenv) {
2148 /* most putenv()s leak, so we manipulate environ directly */
2150 const I32 len = strlen(nam);
2153 /* where does it go? */
2154 for (i = 0; environ[i]; i++) {
2155 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
2159 if (environ == PL_origenviron) { /* need we copy environment? */
2165 while (environ[max])
2167 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2168 for (j=0; j<max; j++) { /* copy environment */
2169 const int len = strlen(environ[j]);
2170 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2171 Copy(environ[j], tmpenv[j], len+1, char);
2174 environ = tmpenv; /* tell exec where it is now */
2177 safesysfree(environ[i]);
2178 while (environ[i]) {
2179 environ[i] = environ[i+1];
2188 if (!environ[i]) { /* does not exist yet */
2189 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2190 environ[i+1] = NULL; /* make sure it's null terminated */
2193 safesysfree(environ[i]);
2197 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2198 /* all that work just for this */
2199 my_setenv_format(environ[i], nam, nlen, val, vlen);
2202 /* This next branch should only be called #if defined(HAS_SETENV), but
2203 Configure doesn't test for that yet. For Solaris, setenv() and unsetenv()
2204 were introduced in Solaris 9, so testing for HAS UNSETENV is sufficient.
2206 # if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__) || (defined(__sun) && defined(HAS_UNSETENV)) || defined(PERL_DARWIN)
2207 # if defined(HAS_UNSETENV)
2209 (void)unsetenv(nam);
2211 (void)setenv(nam, val, 1);
2213 # else /* ! HAS_UNSETENV */
2214 (void)setenv(nam, val, 1);
2215 # endif /* HAS_UNSETENV */
2217 # if defined(HAS_UNSETENV)
2219 if (environ) /* old glibc can crash with null environ */
2220 (void)unsetenv(nam);
2222 const int nlen = strlen(nam);
2223 const int vlen = strlen(val);
2224 char * const new_env =
2225 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2226 my_setenv_format(new_env, nam, nlen, val, vlen);
2227 (void)putenv(new_env);
2229 # else /* ! HAS_UNSETENV */
2231 const int nlen = strlen(nam);
2237 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2238 /* all that work just for this */
2239 my_setenv_format(new_env, nam, nlen, val, vlen);
2240 (void)putenv(new_env);
2241 # endif /* HAS_UNSETENV */
2242 # endif /* __CYGWIN__ */
2243 #ifndef PERL_USE_SAFE_PUTENV
2249 amigaos4_release_environ(__FUNCTION__);
2253 #else /* WIN32 || NETWARE */
2256 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2260 const int nlen = strlen(nam);
2267 Newx(envstr, nlen+vlen+2, char);
2268 my_setenv_format(envstr, nam, nlen, val, vlen);
2269 (void)PerlEnv_putenv(envstr);
2273 #endif /* WIN32 || NETWARE */
2277 #ifdef UNLINK_ALL_VERSIONS
2279 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2283 PERL_ARGS_ASSERT_UNLNK;
2285 while (PerlLIO_unlink(f) >= 0)
2287 return retries ? 0 : -1;
2291 /* this is a drop-in replacement for bcopy(), except for the return
2292 * value, which we need to be able to emulate memcpy() */
2293 #if !defined(HAS_MEMCPY) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY))
2295 Perl_my_bcopy(const void *vfrom, void *vto, size_t len)
2297 #if defined(HAS_BCOPY) && defined(HAS_SAFE_BCOPY)
2298 bcopy(vfrom, vto, len);
2300 const unsigned char *from = (const unsigned char *)vfrom;
2301 unsigned char *to = (unsigned char *)vto;
2303 PERL_ARGS_ASSERT_MY_BCOPY;
2305 if (from - to >= 0) {
2313 *(--to) = *(--from);
2321 /* this is a drop-in replacement for memset() */
2324 Perl_my_memset(void *vloc, int ch, size_t len)
2326 unsigned char *loc = (unsigned char *)vloc;
2328 PERL_ARGS_ASSERT_MY_MEMSET;
2336 /* this is a drop-in replacement for bzero() */
2337 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2339 Perl_my_bzero(void *vloc, size_t len)
2341 unsigned char *loc = (unsigned char *)vloc;
2343 PERL_ARGS_ASSERT_MY_BZERO;
2351 /* this is a drop-in replacement for memcmp() */
2352 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2354 Perl_my_memcmp(const void *vs1, const void *vs2, size_t len)
2356 const U8 *a = (const U8 *)vs1;
2357 const U8 *b = (const U8 *)vs2;
2360 PERL_ARGS_ASSERT_MY_MEMCMP;
2363 if ((tmp = *a++ - *b++))
2368 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2371 /* This vsprintf replacement should generally never get used, since
2372 vsprintf was available in both System V and BSD 2.11. (There may
2373 be some cross-compilation or embedded set-ups where it is needed,
2376 If you encounter a problem in this function, it's probably a symptom
2377 that Configure failed to detect your system's vprintf() function.
2378 See the section on "item vsprintf" in the INSTALL file.
2380 This version may compile on systems with BSD-ish <stdio.h>,
2381 but probably won't on others.
2384 #ifdef USE_CHAR_VSPRINTF
2389 vsprintf(char *dest, const char *pat, void *args)
2393 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2394 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2395 FILE_cnt(&fakebuf) = 32767;
2397 /* These probably won't compile -- If you really need
2398 this, you'll have to figure out some other method. */
2399 fakebuf._ptr = dest;
2400 fakebuf._cnt = 32767;
2405 fakebuf._flag = _IOWRT|_IOSTRG;
2406 _doprnt(pat, args, &fakebuf); /* what a kludge */
2407 #if defined(STDIO_PTR_LVALUE)
2408 *(FILE_ptr(&fakebuf)++) = '\0';
2410 /* PerlIO has probably #defined away fputc, but we want it here. */
2412 # undef fputc /* XXX Should really restore it later */
2414 (void)fputc('\0', &fakebuf);
2416 #ifdef USE_CHAR_VSPRINTF
2419 return 0; /* perl doesn't use return value */
2423 #endif /* HAS_VPRINTF */
2426 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2428 #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
2436 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2438 PERL_FLUSHALL_FOR_CHILD;
2439 This = (*mode == 'w');
2443 taint_proper("Insecure %s%s", "EXEC");
2445 if (PerlProc_pipe(p) < 0)
2447 /* Try for another pipe pair for error return */
2448 if (PerlProc_pipe(pp) >= 0)
2450 while ((pid = PerlProc_fork()) < 0) {
2451 if (errno != EAGAIN) {
2452 PerlLIO_close(p[This]);
2453 PerlLIO_close(p[that]);
2455 PerlLIO_close(pp[0]);
2456 PerlLIO_close(pp[1]);
2460 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2469 /* Close parent's end of error status pipe (if any) */
2471 PerlLIO_close(pp[0]);
2472 #if defined(HAS_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
2473 /* Close error pipe automatically if exec works */
2474 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2478 /* Now dup our end of _the_ pipe to right position */
2479 if (p[THIS] != (*mode == 'r')) {
2480 PerlLIO_dup2(p[THIS], *mode == 'r');
2481 PerlLIO_close(p[THIS]);
2482 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2483 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2486 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2487 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2488 /* No automatic close - do it by hand */
2495 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2501 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2507 do_execfree(); /* free any memory malloced by child on fork */
2509 PerlLIO_close(pp[1]);
2510 /* Keep the lower of the two fd numbers */
2511 if (p[that] < p[This]) {
2512 PerlLIO_dup2(p[This], p[that]);
2513 PerlLIO_close(p[This]);
2517 PerlLIO_close(p[that]); /* close child's end of pipe */
2519 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2520 SvUPGRADE(sv,SVt_IV);
2522 PL_forkprocess = pid;
2523 /* If we managed to get status pipe check for exec fail */
2524 if (did_pipes && pid > 0) {
2529 while (n < sizeof(int)) {
2530 n1 = PerlLIO_read(pp[0],
2531 (void*)(((char*)&errkid)+n),
2537 PerlLIO_close(pp[0]);
2539 if (n) { /* Error */
2541 PerlLIO_close(p[This]);
2542 if (n != sizeof(int))
2543 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2545 pid2 = wait4pid(pid, &status, 0);
2546 } while (pid2 == -1 && errno == EINTR);
2547 errno = errkid; /* Propagate errno from kid */
2552 PerlLIO_close(pp[0]);
2553 return PerlIO_fdopen(p[This], mode);
2555 # if defined(OS2) /* Same, without fork()ing and all extra overhead... */
2556 return my_syspopen4(aTHX_ NULL, mode, n, args);
2557 # elif defined(WIN32)
2558 return win32_popenlist(mode, n, args);
2560 Perl_croak(aTHX_ "List form of piped open not implemented");
2561 return (PerlIO *) NULL;
2566 /* VMS' my_popen() is in VMS.c, same with OS/2 and AmigaOS 4. */
2567 #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
2569 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2575 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2579 PERL_ARGS_ASSERT_MY_POPEN;
2581 PERL_FLUSHALL_FOR_CHILD;
2584 return my_syspopen(aTHX_ cmd,mode);
2587 This = (*mode == 'w');
2589 if (doexec && TAINTING_get) {
2591 taint_proper("Insecure %s%s", "EXEC");
2593 if (PerlProc_pipe(p) < 0)
2595 if (doexec && PerlProc_pipe(pp) >= 0)
2597 while ((pid = PerlProc_fork()) < 0) {
2598 if (errno != EAGAIN) {
2599 PerlLIO_close(p[This]);
2600 PerlLIO_close(p[that]);
2602 PerlLIO_close(pp[0]);
2603 PerlLIO_close(pp[1]);
2606 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2609 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2619 PerlLIO_close(pp[0]);
2620 #if defined(HAS_FCNTL) && defined(F_SETFD)
2621 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2625 if (p[THIS] != (*mode == 'r')) {
2626 PerlLIO_dup2(p[THIS], *mode == 'r');
2627 PerlLIO_close(p[THIS]);
2628 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2629 PerlLIO_close(p[THAT]);
2632 PerlLIO_close(p[THAT]);
2635 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2642 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2647 /* may or may not use the shell */
2648 do_exec3(cmd, pp[1], did_pipes);
2651 #endif /* defined OS2 */
2653 #ifdef PERLIO_USING_CRLF
2654 /* Since we circumvent IO layers when we manipulate low-level
2655 filedescriptors directly, need to manually switch to the
2656 default, binary, low-level mode; see PerlIOBuf_open(). */
2657 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2660 #ifdef PERL_USES_PL_PIDSTATUS
2661 hv_clear(PL_pidstatus); /* we have no children */
2667 do_execfree(); /* free any memory malloced by child on vfork */
2669 PerlLIO_close(pp[1]);
2670 if (p[that] < p[This]) {
2671 PerlLIO_dup2(p[This], p[that]);
2672 PerlLIO_close(p[This]);
2676 PerlLIO_close(p[that]);
2678 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2679 SvUPGRADE(sv,SVt_IV);
2681 PL_forkprocess = pid;
2682 if (did_pipes && pid > 0) {
2687 while (n < sizeof(int)) {
2688 n1 = PerlLIO_read(pp[0],
2689 (void*)(((char*)&errkid)+n),
2695 PerlLIO_close(pp[0]);
2697 if (n) { /* Error */
2699 PerlLIO_close(p[This]);
2700 if (n != sizeof(int))
2701 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2703 pid2 = wait4pid(pid, &status, 0);
2704 } while (pid2 == -1 && errno == EINTR);
2705 errno = errkid; /* Propagate errno from kid */
2710 PerlLIO_close(pp[0]);
2711 return PerlIO_fdopen(p[This], mode);
2715 FILE *djgpp_popen();
2717 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2719 PERL_FLUSHALL_FOR_CHILD;
2720 /* Call system's popen() to get a FILE *, then import it.
2721 used 0 for 2nd parameter to PerlIO_importFILE;
2724 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2727 #if defined(__LIBCATAMOUNT__)
2729 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2736 #endif /* !DOSISH */
2738 /* this is called in parent before the fork() */
2740 Perl_atfork_lock(void)
2741 #if defined(USE_ITHREADS)
2743 PERL_TSA_ACQUIRE(PL_perlio_mutex)
2746 PERL_TSA_ACQUIRE(PL_malloc_mutex)
2748 PERL_TSA_ACQUIRE(PL_op_mutex)
2751 #if defined(USE_ITHREADS)
2753 /* locks must be held in locking order (if any) */
2755 MUTEX_LOCK(&PL_perlio_mutex);
2758 MUTEX_LOCK(&PL_malloc_mutex);
2764 /* this is called in both parent and child after the fork() */
2766 Perl_atfork_unlock(void)
2767 #if defined(USE_ITHREADS)
2769 PERL_TSA_RELEASE(PL_perlio_mutex)
2772 PERL_TSA_RELEASE(PL_malloc_mutex)
2774 PERL_TSA_RELEASE(PL_op_mutex)
2777 #if defined(USE_ITHREADS)
2779 /* locks must be released in same order as in atfork_lock() */
2781 MUTEX_UNLOCK(&PL_perlio_mutex);
2784 MUTEX_UNLOCK(&PL_malloc_mutex);
2793 #if defined(HAS_FORK)
2795 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2800 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2801 * handlers elsewhere in the code */
2805 #elif defined(__amigaos4__)
2806 return amigaos_fork();
2808 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2809 Perl_croak_nocontext("fork() not available");
2811 #endif /* HAS_FORK */
2816 dup2(int oldfd, int newfd)
2818 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2821 PerlLIO_close(newfd);
2822 return fcntl(oldfd, F_DUPFD, newfd);
2824 #define DUP2_MAX_FDS 256
2825 int fdtmp[DUP2_MAX_FDS];
2831 PerlLIO_close(newfd);
2832 /* good enough for low fd's... */
2833 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2834 if (fdx >= DUP2_MAX_FDS) {
2842 PerlLIO_close(fdtmp[--fdx]);
2849 #ifdef HAS_SIGACTION
2852 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2854 struct sigaction act, oact;
2858 /* only "parent" interpreter can diddle signals */
2859 if (PL_curinterp != aTHX)
2860 return (Sighandler_t) SIG_ERR;
2863 act.sa_handler = (void(*)(int))handler;
2864 sigemptyset(&act.sa_mask);
2867 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2868 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2870 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2871 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2872 act.sa_flags |= SA_NOCLDWAIT;
2874 if (sigaction(signo, &act, &oact) == -1)
2875 return (Sighandler_t) SIG_ERR;
2877 return (Sighandler_t) oact.sa_handler;
2881 Perl_rsignal_state(pTHX_ int signo)
2883 struct sigaction oact;
2884 PERL_UNUSED_CONTEXT;
2886 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2887 return (Sighandler_t) SIG_ERR;
2889 return (Sighandler_t) oact.sa_handler;
2893 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2898 struct sigaction act;
2900 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2903 /* only "parent" interpreter can diddle signals */
2904 if (PL_curinterp != aTHX)
2908 act.sa_handler = (void(*)(int))handler;
2909 sigemptyset(&act.sa_mask);
2912 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2913 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2915 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2916 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2917 act.sa_flags |= SA_NOCLDWAIT;
2919 return sigaction(signo, &act, save);
2923 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2928 PERL_UNUSED_CONTEXT;
2930 /* only "parent" interpreter can diddle signals */
2931 if (PL_curinterp != aTHX)
2935 return sigaction(signo, save, (struct sigaction *)NULL);
2938 #else /* !HAS_SIGACTION */
2941 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2943 #if defined(USE_ITHREADS) && !defined(WIN32)
2944 /* only "parent" interpreter can diddle signals */
2945 if (PL_curinterp != aTHX)
2946 return (Sighandler_t) SIG_ERR;
2949 return PerlProc_signal(signo, handler);
2960 Perl_rsignal_state(pTHX_ int signo)
2963 Sighandler_t oldsig;
2965 #if defined(USE_ITHREADS) && !defined(WIN32)
2966 /* only "parent" interpreter can diddle signals */
2967 if (PL_curinterp != aTHX)
2968 return (Sighandler_t) SIG_ERR;
2972 oldsig = PerlProc_signal(signo, sig_trap);
2973 PerlProc_signal(signo, oldsig);
2975 PerlProc_kill(PerlProc_getpid(), signo);
2980 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2982 #if defined(USE_ITHREADS) && !defined(WIN32)
2983 /* only "parent" interpreter can diddle signals */
2984 if (PL_curinterp != aTHX)
2987 *save = PerlProc_signal(signo, handler);
2988 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2992 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2994 #if defined(USE_ITHREADS) && !defined(WIN32)
2995 /* only "parent" interpreter can diddle signals */
2996 if (PL_curinterp != aTHX)
2999 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3002 #endif /* !HAS_SIGACTION */
3003 #endif /* !PERL_MICRO */
3005 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3006 #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
3008 Perl_my_pclose(pTHX_ PerlIO *ptr)
3016 const int fd = PerlIO_fileno(ptr);
3019 svp = av_fetch(PL_fdpid,fd,TRUE);
3020 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3024 #if defined(USE_PERLIO)
3025 /* Find out whether the refcount is low enough for us to wait for the
3026 child proc without blocking. */
3027 should_wait = PerlIOUnix_refcnt(fd) == 1 && pid > 0;
3029 should_wait = pid > 0;
3033 if (pid == -1) { /* Opened by popen. */
3034 return my_syspclose(ptr);
3037 close_failed = (PerlIO_close(ptr) == EOF);
3039 if (should_wait) do {
3040 pid2 = wait4pid(pid, &status, 0);
3041 } while (pid2 == -1 && errno == EINTR);
3048 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3053 #if defined(__LIBCATAMOUNT__)
3055 Perl_my_pclose(pTHX_ PerlIO *ptr)
3060 #endif /* !DOSISH */
3062 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3064 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3067 PERL_ARGS_ASSERT_WAIT4PID;
3068 #ifdef PERL_USES_PL_PIDSTATUS
3070 /* PERL_USES_PL_PIDSTATUS is only defined when neither
3071 waitpid() nor wait4() is available, or on OS/2, which
3072 doesn't appear to support waiting for a progress group
3073 member, so we can only treat a 0 pid as an unknown child.
3080 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3081 pid, rather than a string form. */
3082 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3083 if (svp && *svp != &PL_sv_undef) {
3084 *statusp = SvIVX(*svp);
3085 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3093 hv_iterinit(PL_pidstatus);
3094 if ((entry = hv_iternext(PL_pidstatus))) {
3095 SV * const sv = hv_iterval(PL_pidstatus,entry);
3097 const char * const spid = hv_iterkey(entry,&len);
3099 assert (len == sizeof(Pid_t));
3100 memcpy((char *)&pid, spid, len);
3101 *statusp = SvIVX(sv);
3102 /* The hash iterator is currently on this entry, so simply
3103 calling hv_delete would trigger the lazy delete, which on
3104 aggregate does more work, because next call to hv_iterinit()
3105 would spot the flag, and have to call the delete routine,
3106 while in the meantime any new entries can't re-use that
3108 hv_iterinit(PL_pidstatus);
3109 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3116 # ifdef HAS_WAITPID_RUNTIME
3117 if (!HAS_WAITPID_RUNTIME)
3120 result = PerlProc_waitpid(pid,statusp,flags);
3123 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3124 result = wait4(pid,statusp,flags,NULL);
3127 #ifdef PERL_USES_PL_PIDSTATUS
3128 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3133 Perl_croak(aTHX_ "Can't do waitpid with flags");
3135 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3136 pidgone(result,*statusp);
3142 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3145 if (result < 0 && errno == EINTR) {
3147 errno = EINTR; /* reset in case a signal handler changed $! */
3151 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3153 #ifdef PERL_USES_PL_PIDSTATUS
3155 S_pidgone(pTHX_ Pid_t pid, int status)
3159 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3160 SvUPGRADE(sv,SVt_IV);
3161 SvIV_set(sv, status);
3169 int /* Cannot prototype with I32
3171 my_syspclose(PerlIO *ptr)
3174 Perl_my_pclose(pTHX_ PerlIO *ptr)
3177 /* Needs work for PerlIO ! */
3178 FILE * const f = PerlIO_findFILE(ptr);
3179 const I32 result = pclose(f);
3180 PerlIO_releaseFILE(ptr,f);
3188 Perl_my_pclose(pTHX_ PerlIO *ptr)
3190 /* Needs work for PerlIO ! */
3191 FILE * const f = PerlIO_findFILE(ptr);
3192 I32 result = djgpp_pclose(f);
3193 result = (result << 8) & 0xff00;
3194 PerlIO_releaseFILE(ptr,f);
3199 #define PERL_REPEATCPY_LINEAR 4
3201 Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
3203 PERL_ARGS_ASSERT_REPEATCPY;
3208 croak_memory_wrap();
3211 memset(to, *from, count);
3214 IV items, linear, half;
3216 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3217 for (items = 0; items < linear; ++items) {
3218 const char *q = from;
3220 for (todo = len; todo > 0; todo--)
3225 while (items <= half) {
3226 IV size = items * len;
3227 memcpy(p, to, size);
3233 memcpy(p, to, (count - items) * len);
3239 Perl_same_dirent(pTHX_ const char *a, const char *b)
3241 char *fa = strrchr(a,'/');
3242 char *fb = strrchr(b,'/');
3245 SV * const tmpsv = sv_newmortal();
3247 PERL_ARGS_ASSERT_SAME_DIRENT;
3260 sv_setpvs(tmpsv, ".");
3262 sv_setpvn(tmpsv, a, fa - a);
3263 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3266 sv_setpvs(tmpsv, ".");
3268 sv_setpvn(tmpsv, b, fb - b);
3269 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3271 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3272 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3274 #endif /* !HAS_RENAME */
3277 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3278 const char *const *const search_ext, I32 flags)
3280 const char *xfound = NULL;
3281 char *xfailed = NULL;
3282 char tmpbuf[MAXPATHLEN];
3287 #if defined(DOSISH) && !defined(OS2)
3288 # define SEARCH_EXTS ".bat", ".cmd", NULL
3289 # define MAX_EXT_LEN 4
3292 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3293 # define MAX_EXT_LEN 4
3296 # define SEARCH_EXTS ".pl", ".com", NULL
3297 # define MAX_EXT_LEN 4
3299 /* additional extensions to try in each dir if scriptname not found */
3301 static const char *const exts[] = { SEARCH_EXTS };
3302 const char *const *const ext = search_ext ? search_ext : exts;
3303 int extidx = 0, i = 0;
3304 const char *curext = NULL;
3306 PERL_UNUSED_ARG(search_ext);
3307 # define MAX_EXT_LEN 0
3310 PERL_ARGS_ASSERT_FIND_SCRIPT;
3313 * If dosearch is true and if scriptname does not contain path
3314 * delimiters, search the PATH for scriptname.
3316 * If SEARCH_EXTS is also defined, will look for each
3317 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3318 * while searching the PATH.
3320 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3321 * proceeds as follows:
3322 * If DOSISH or VMSISH:
3323 * + look for ./scriptname{,.foo,.bar}
3324 * + search the PATH for scriptname{,.foo,.bar}
3327 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3328 * this will not look in '.' if it's not in the PATH)
3333 # ifdef ALWAYS_DEFTYPES
3334 len = strlen(scriptname);
3335 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3336 int idx = 0, deftypes = 1;
3339 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3342 int idx = 0, deftypes = 1;
3345 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3347 /* The first time through, just add SEARCH_EXTS to whatever we
3348 * already have, so we can check for default file types. */
3350 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3357 if ((strlen(tmpbuf) + strlen(scriptname)
3358 + MAX_EXT_LEN) >= sizeof tmpbuf)
3359 continue; /* don't search dir with too-long name */
3360 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3364 if (strEQ(scriptname, "-"))
3366 if (dosearch) { /* Look in '.' first. */
3367 const char *cur = scriptname;
3369 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3371 if (strEQ(ext[i++],curext)) {
3372 extidx = -1; /* already has an ext */
3377 DEBUG_p(PerlIO_printf(Perl_debug_log,
3378 "Looking for %s\n",cur));
3381 if (PerlLIO_stat(cur,&statbuf) >= 0
3382 && !S_ISDIR(statbuf.st_mode)) {
3391 if (cur == scriptname) {
3392 len = strlen(scriptname);
3393 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3395 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3398 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3399 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3404 if (dosearch && !strchr(scriptname, '/')
3406 && !strchr(scriptname, '\\')
3408 && (s = PerlEnv_getenv("PATH")))
3412 bufend = s + strlen(s);
3413 while (s < bufend) {
3417 && *s != ';'; len++, s++) {
3418 if (len < sizeof tmpbuf)
3421 if (len < sizeof tmpbuf)
3424 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3430 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3431 continue; /* don't search dir with too-long name */
3434 && tmpbuf[len - 1] != '/'
3435 && tmpbuf[len - 1] != '\\'
3438 tmpbuf[len++] = '/';
3439 if (len == 2 && tmpbuf[0] == '.')
3441 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3445 len = strlen(tmpbuf);
3446 if (extidx > 0) /* reset after previous loop */
3450 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3451 retval = PerlLIO_stat(tmpbuf,&statbuf);
3452 if (S_ISDIR(statbuf.st_mode)) {
3456 } while ( retval < 0 /* not there */
3457 && extidx>=0 && ext[extidx] /* try an extension? */
3458 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3463 if (S_ISREG(statbuf.st_mode)
3464 && cando(S_IRUSR,TRUE,&statbuf)
3465 #if !defined(DOSISH)
3466 && cando(S_IXUSR,TRUE,&statbuf)
3470 xfound = tmpbuf; /* bingo! */
3474 xfailed = savepv(tmpbuf);
3479 if (!xfound && !seen_dot && !xfailed &&
3480 (PerlLIO_stat(scriptname,&statbuf) < 0
3481 || S_ISDIR(statbuf.st_mode)))
3483 seen_dot = 1; /* Disable message. */
3488 if (flags & 1) { /* do or die? */
3489 /* diag_listed_as: Can't execute %s */
3490 Perl_croak(aTHX_ "Can't %s %s%s%s",
3491 (xfailed ? "execute" : "find"),
3492 (xfailed ? xfailed : scriptname),
3493 (xfailed ? "" : " on PATH"),
3494 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3499 scriptname = xfound;
3501 return (scriptname ? savepv(scriptname) : NULL);
3504 #ifndef PERL_GET_CONTEXT_DEFINED
3507 Perl_get_context(void)
3509 #if defined(USE_ITHREADS)
3511 # ifdef OLD_PTHREADS_API
3513 int error = pthread_getspecific(PL_thr_key, &t)
3515 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3518 # ifdef I_MACH_CTHREADS
3519 return (void*)cthread_data(cthread_self());
3521 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3530 Perl_set_context(void *t)
3532 #if defined(USE_ITHREADS)
3535 PERL_ARGS_ASSERT_SET_CONTEXT;
3536 #if defined(USE_ITHREADS)
3537 # ifdef I_MACH_CTHREADS
3538 cthread_set_data(cthread_self(), t);
3541 const int error = pthread_setspecific(PL_thr_key, t);
3543 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3551 #endif /* !PERL_GET_CONTEXT_DEFINED */
3553 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3557 PERL_UNUSED_CONTEXT;
3563 Perl_get_op_names(pTHX)
3565 PERL_UNUSED_CONTEXT;
3566 return (char **)PL_op_name;
3570 Perl_get_op_descs(pTHX)
3572 PERL_UNUSED_CONTEXT;
3573 return (char **)PL_op_desc;
3577 Perl_get_no_modify(pTHX)
3579 PERL_UNUSED_CONTEXT;
3580 return PL_no_modify;
3584 Perl_get_opargs(pTHX)
3586 PERL_UNUSED_CONTEXT;
3587 return (U32 *)PL_opargs;
3591 Perl_get_ppaddr(pTHX)
3594 PERL_UNUSED_CONTEXT;
3595 return (PPADDR_t*)PL_ppaddr;
3598 #ifndef HAS_GETENV_LEN
3600 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3602 char * const env_trans = PerlEnv_getenv(env_elem);
3603 PERL_UNUSED_CONTEXT;
3604 PERL_ARGS_ASSERT_GETENV_LEN;
3606 *len = strlen(env_trans);
3613 Perl_get_vtbl(pTHX_ int vtbl_id)
3615 PERL_UNUSED_CONTEXT;
3617 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3618 ? NULL : (MGVTBL*)PL_magic_vtables + vtbl_id;
3622 Perl_my_fflush_all(pTHX)
3624 #if defined(USE_PERLIO) || defined(FFLUSH_NULL)
3625 return PerlIO_flush(NULL);
3627 # if defined(HAS__FWALK)
3628 extern int fflush(FILE *);
3629 /* undocumented, unprototyped, but very useful BSDism */
3630 extern void _fwalk(int (*)(FILE *));
3634 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3636 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3637 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3639 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3640 open_max = sysconf(_SC_OPEN_MAX);
3643 open_max = FOPEN_MAX;
3646 open_max = OPEN_MAX;
3657 for (i = 0; i < open_max; i++)
3658 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3659 STDIO_STREAM_ARRAY[i]._file < open_max &&
3660 STDIO_STREAM_ARRAY[i]._flag)
3661 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3665 SETERRNO(EBADF,RMS_IFI);
3672 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3674 if (ckWARN(WARN_IO)) {
3676 = gv && (isGV_with_GP(gv))
3679 const char * const direction = have == '>' ? "out" : "in";
3681 if (name && HEK_LEN(name))
3682 Perl_warner(aTHX_ packWARN(WARN_IO),
3683 "Filehandle %"HEKf" opened only for %sput",
3684 HEKfARG(name), direction);
3686 Perl_warner(aTHX_ packWARN(WARN_IO),
3687 "Filehandle opened only for %sput", direction);
3692 Perl_report_evil_fh(pTHX_ const GV *gv)
3694 const IO *io = gv ? GvIO(gv) : NULL;
3695 const PERL_BITFIELD16 op = PL_op->op_type;
3699 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3701 warn_type = WARN_CLOSED;
3705 warn_type = WARN_UNOPENED;
3708 if (ckWARN(warn_type)) {
3710 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3711 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3712 const char * const pars =
3713 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3714 const char * const func =
3716 (op == OP_READLINE || op == OP_RCATLINE
3717 ? "readline" : /* "<HANDLE>" not nice */
3718 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3720 const char * const type =
3722 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3723 ? "socket" : "filehandle");
3724 const bool have_name = name && SvCUR(name);
3725 Perl_warner(aTHX_ packWARN(warn_type),
3726 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3727 have_name ? " " : "",
3728 SVfARG(have_name ? name : &PL_sv_no));
3729 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3731 aTHX_ packWARN(warn_type),
3732 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3733 func, pars, have_name ? " " : "",
3734 SVfARG(have_name ? name : &PL_sv_no)
3739 /* To workaround core dumps from the uninitialised tm_zone we get the
3740 * system to give us a reasonable struct to copy. This fix means that
3741 * strftime uses the tm_zone and tm_gmtoff values returned by
3742 * localtime(time()). That should give the desired result most of the
3743 * time. But probably not always!
3745 * This does not address tzname aspects of NETaa14816.
3750 # ifndef STRUCT_TM_HASZONE
3751 # define STRUCT_TM_HASZONE
3755 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3756 # ifndef HAS_TM_TM_ZONE
3757 # define HAS_TM_TM_ZONE
3762 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3764 #ifdef HAS_TM_TM_ZONE
3766 const struct tm* my_tm;
3767 PERL_UNUSED_CONTEXT;
3768 PERL_ARGS_ASSERT_INIT_TM;
3770 my_tm = localtime(&now);
3772 Copy(my_tm, ptm, 1, struct tm);
3774 PERL_UNUSED_CONTEXT;
3775 PERL_ARGS_ASSERT_INIT_TM;
3776 PERL_UNUSED_ARG(ptm);
3781 * mini_mktime - normalise struct tm values without the localtime()
3782 * semantics (and overhead) of mktime().
3785 Perl_mini_mktime(struct tm *ptm)
3789 int month, mday, year, jday;
3790 int odd_cent, odd_year;
3792 PERL_ARGS_ASSERT_MINI_MKTIME;
3794 #define DAYS_PER_YEAR 365
3795 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3796 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3797 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3798 #define SECS_PER_HOUR (60*60)
3799 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3800 /* parentheses deliberately absent on these two, otherwise they don't work */
3801 #define MONTH_TO_DAYS 153/5
3802 #define DAYS_TO_MONTH 5/153
3803 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3804 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3805 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3806 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3809 * Year/day algorithm notes:
3811 * With a suitable offset for numeric value of the month, one can find
3812 * an offset into the year by considering months to have 30.6 (153/5) days,
3813 * using integer arithmetic (i.e., with truncation). To avoid too much
3814 * messing about with leap days, we consider January and February to be
3815 * the 13th and 14th month of the previous year. After that transformation,
3816 * we need the month index we use to be high by 1 from 'normal human' usage,
3817 * so the month index values we use run from 4 through 15.
3819 * Given that, and the rules for the Gregorian calendar (leap years are those
3820 * divisible by 4 unless also divisible by 100, when they must be divisible
3821 * by 400 instead), we can simply calculate the number of days since some
3822 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3823 * the days we derive from our month index, and adding in the day of the
3824 * month. The value used here is not adjusted for the actual origin which
3825 * it normally would use (1 January A.D. 1), since we're not exposing it.
3826 * We're only building the value so we can turn around and get the
3827 * normalised values for the year, month, day-of-month, and day-of-year.
3829 * For going backward, we need to bias the value we're using so that we find
3830 * the right year value. (Basically, we don't want the contribution of
3831 * March 1st to the number to apply while deriving the year). Having done
3832 * that, we 'count up' the contribution to the year number by accounting for
3833 * full quadracenturies (400-year periods) with their extra leap days, plus
3834 * the contribution from full centuries (to avoid counting in the lost leap
3835 * days), plus the contribution from full quad-years (to count in the normal
3836 * leap days), plus the leftover contribution from any non-leap years.
3837 * At this point, if we were working with an actual leap day, we'll have 0
3838 * days left over. This is also true for March 1st, however. So, we have
3839 * to special-case that result, and (earlier) keep track of the 'odd'
3840 * century and year contributions. If we got 4 extra centuries in a qcent,
3841 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3842 * Otherwise, we add back in the earlier bias we removed (the 123 from
3843 * figuring in March 1st), find the month index (integer division by 30.6),
3844 * and the remainder is the day-of-month. We then have to convert back to
3845 * 'real' months (including fixing January and February from being 14/15 in
3846 * the previous year to being in the proper year). After that, to get
3847 * tm_yday, we work with the normalised year and get a new yearday value for
3848 * January 1st, which we subtract from the yearday value we had earlier,
3849 * representing the date we've re-built. This is done from January 1
3850 * because tm_yday is 0-origin.
3852 * Since POSIX time routines are only guaranteed to work for times since the
3853 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3854 * applies Gregorian calendar rules even to dates before the 16th century
3855 * doesn't bother me. Besides, you'd need cultural context for a given
3856 * date to know whether it was Julian or Gregorian calendar, and that's
3857 * outside the scope for this routine. Since we convert back based on the
3858 * same rules we used to build the yearday, you'll only get strange results
3859 * for input which needed normalising, or for the 'odd' century years which
3860 * were leap years in the Julian calendar but not in the Gregorian one.
3861 * I can live with that.
3863 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3864 * that's still outside the scope for POSIX time manipulation, so I don't
3868 year = 1900 + ptm->tm_year;
3869 month = ptm->tm_mon;
3870 mday = ptm->tm_mday;
3876 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3877 yearday += month*MONTH_TO_DAYS + mday + jday;
3879 * Note that we don't know when leap-seconds were or will be,
3880 * so we have to trust the user if we get something which looks
3881 * like a sensible leap-second. Wild values for seconds will
3882 * be rationalised, however.
3884 if ((unsigned) ptm->tm_sec <= 60) {
3891 secs += 60 * ptm->tm_min;
3892 secs += SECS_PER_HOUR * ptm->tm_hour;
3894 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3895 /* got negative remainder, but need positive time */
3896 /* back off an extra day to compensate */
3897 yearday += (secs/SECS_PER_DAY)-1;
3898 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3901 yearday += (secs/SECS_PER_DAY);
3902 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3905 else if (secs >= SECS_PER_DAY) {
3906 yearday += (secs/SECS_PER_DAY);
3907 secs %= SECS_PER_DAY;
3909 ptm->tm_hour = secs/SECS_PER_HOUR;
3910 secs %= SECS_PER_HOUR;
3911 ptm->tm_min = secs/60;
3913 ptm->tm_sec += secs;
3914 /* done with time of day effects */
3916 * The algorithm for yearday has (so far) left it high by 428.
3917 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3918 * bias it by 123 while trying to figure out what year it
3919 * really represents. Even with this tweak, the reverse
3920 * translation fails for years before A.D. 0001.
3921 * It would still fail for Feb 29, but we catch that one below.
3923 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3924 yearday -= YEAR_ADJUST;
3925 year = (yearday / DAYS_PER_QCENT) * 400;
3926 yearday %= DAYS_PER_QCENT;
3927 odd_cent = yearday / DAYS_PER_CENT;
3928 year += odd_cent * 100;
3929 yearday %= DAYS_PER_CENT;
3930 year += (yearday / DAYS_PER_QYEAR) * 4;
3931 yearday %= DAYS_PER_QYEAR;
3932 odd_year = yearday / DAYS_PER_YEAR;
3934 yearday %= DAYS_PER_YEAR;
3935 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3940 yearday += YEAR_ADJUST; /* recover March 1st crock */
3941 month = yearday*DAYS_TO_MONTH;
3942 yearday -= month*MONTH_TO_DAYS;
3943 /* recover other leap-year adjustment */
3952 ptm->tm_year = year - 1900;
3954 ptm->tm_mday = yearday;
3955 ptm->tm_mon = month;
3959 ptm->tm_mon = month - 1;
3961 /* re-build yearday based on Jan 1 to get tm_yday */
3963 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3964 yearday += 14*MONTH_TO_DAYS + 1;
3965 ptm->tm_yday = jday - yearday;
3966 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3970 Perl_my_strftime(pTHX_ const char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3974 /* Note that yday and wday effectively are ignored by this function, as mini_mktime() overwrites them */
3981 PERL_ARGS_ASSERT_MY_STRFTIME;
3983 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3986 mytm.tm_hour = hour;
3987 mytm.tm_mday = mday;
3989 mytm.tm_year = year;
3990 mytm.tm_wday = wday;
3991 mytm.tm_yday = yday;
3992 mytm.tm_isdst = isdst;
3994 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3995 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4000 #ifdef HAS_TM_TM_GMTOFF
4001 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4003 #ifdef HAS_TM_TM_ZONE
4004 mytm.tm_zone = mytm2.tm_zone;
4009 Newx(buf, buflen, char);
4011 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
4012 len = strftime(buf, buflen, fmt, &mytm);
4016 ** The following is needed to handle to the situation where
4017 ** tmpbuf overflows. Basically we want to allocate a buffer
4018 ** and try repeatedly. The reason why it is so complicated
4019 ** is that getting a return value of 0 from strftime can indicate
4020 ** one of the following:
4021 ** 1. buffer overflowed,
4022 ** 2. illegal conversion specifier, or
4023 ** 3. the format string specifies nothing to be returned(not
4024 ** an error). This could be because format is an empty string
4025 ** or it specifies %p that yields an empty string in some locale.
4026 ** If there is a better way to make it portable, go ahead by
4029 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4032 /* Possibly buf overflowed - try again with a bigger buf */
4033 const int fmtlen = strlen(fmt);
4034 int bufsize = fmtlen + buflen;
4036 Renew(buf, bufsize, char);
4039 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
4040 buflen = strftime(buf, bufsize, fmt, &mytm);
4043 if (buflen > 0 && buflen < bufsize)
4045 /* heuristic to prevent out-of-memory errors */
4046 if (bufsize > 100*fmtlen) {
4052 Renew(buf, bufsize, char);
4057 Perl_croak(aTHX_ "panic: no strftime");
4063 #define SV_CWD_RETURN_UNDEF \
4064 sv_setsv(sv, &PL_sv_undef); \
4067 #define SV_CWD_ISDOT(dp) \
4068 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4069 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4072 =head1 Miscellaneous Functions
4074 =for apidoc getcwd_sv
4076 Fill C<sv> with current working directory
4081 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4082 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4083 * getcwd(3) if available
4084 * Comments from the original:
4085 * This is a faster version of getcwd. It's also more dangerous
4086 * because you might chdir out of a directory that you can't chdir
4090 Perl_getcwd_sv(pTHX_ SV *sv)
4095 PERL_ARGS_ASSERT_GETCWD_SV;
4099 char buf[MAXPATHLEN];
4101 /* Some getcwd()s automatically allocate a buffer of the given
4102 * size from the heap if they are given a NULL buffer pointer.
4103 * The problem is that this behaviour is not portable. */
4104 if (getcwd(buf, sizeof(buf) - 1)) {
4109 sv_setsv(sv, &PL_sv_undef);
4117 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4121 SvUPGRADE(sv, SVt_PV);
4123 if (PerlLIO_lstat(".", &statbuf) < 0) {
4124 SV_CWD_RETURN_UNDEF;
4127 orig_cdev = statbuf.st_dev;
4128 orig_cino = statbuf.st_ino;
4138 if (PerlDir_chdir("..") < 0) {
4139 SV_CWD_RETURN_UNDEF;
4141 if (PerlLIO_stat(".", &statbuf) < 0) {
4142 SV_CWD_RETURN_UNDEF;
4145 cdev = statbuf.st_dev;
4146 cino = statbuf.st_ino;
4148 if (odev == cdev && oino == cino) {
4151 if (!(dir = PerlDir_open("."))) {
4152 SV_CWD_RETURN_UNDEF;
4155 while ((dp = PerlDir_read(dir)) != NULL) {
4157 namelen = dp->d_namlen;
4159 namelen = strlen(dp->d_name);
4162 if (SV_CWD_ISDOT(dp)) {
4166 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4167 SV_CWD_RETURN_UNDEF;
4170 tdev = statbuf.st_dev;
4171 tino = statbuf.st_ino;
4172 if (tino == oino && tdev == odev) {
4178 SV_CWD_RETURN_UNDEF;
4181 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4182 SV_CWD_RETURN_UNDEF;
4185 SvGROW(sv, pathlen + namelen + 1);
4189 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4192 /* prepend current directory to the front */
4194 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4195 pathlen += (namelen + 1);
4197 #ifdef VOID_CLOSEDIR
4200 if (PerlDir_close(dir) < 0) {
4201 SV_CWD_RETURN_UNDEF;
4207 SvCUR_set(sv, pathlen);
4211 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4212 SV_CWD_RETURN_UNDEF;
4215 if (PerlLIO_stat(".", &statbuf) < 0) {
4216 SV_CWD_RETURN_UNDEF;
4219 cdev = statbuf.st_dev;
4220 cino = statbuf.st_ino;
4222 if (cdev != orig_cdev || cino != orig_cino) {
4223 Perl_croak(aTHX_ "Unstable directory path, "
4224 "current directory changed unexpectedly");
4237 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4238 # define EMULATE_SOCKETPAIR_UDP
4241 #ifdef EMULATE_SOCKETPAIR_UDP
4243 S_socketpair_udp (int fd[2]) {
4245 /* Fake a datagram socketpair using UDP to localhost. */
4246 int sockets[2] = {-1, -1};
4247 struct sockaddr_in addresses[2];
4249 Sock_size_t size = sizeof(struct sockaddr_in);
4250 unsigned short port;
4253 memset(&addresses, 0, sizeof(addresses));
4256 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4257 if (sockets[i] == -1)
4258 goto tidy_up_and_fail;
4260 addresses[i].sin_family = AF_INET;
4261 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4262 addresses[i].sin_port = 0; /* kernel choses port. */
4263 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4264 sizeof(struct sockaddr_in)) == -1)
4265 goto tidy_up_and_fail;
4268 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4269 for each connect the other socket to it. */
4272 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4274 goto tidy_up_and_fail;
4275 if (size != sizeof(struct sockaddr_in))
4276 goto abort_tidy_up_and_fail;
4277 /* !1 is 0, !0 is 1 */
4278 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4279 sizeof(struct sockaddr_in)) == -1)
4280 goto tidy_up_and_fail;
4283 /* Now we have 2 sockets connected to each other. I don't trust some other
4284 process not to have already sent a packet to us (by random) so send
4285 a packet from each to the other. */
4288 /* I'm going to send my own port number. As a short.
4289 (Who knows if someone somewhere has sin_port as a bitfield and needs
4290 this routine. (I'm assuming crays have socketpair)) */
4291 port = addresses[i].sin_port;
4292 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4293 if (got != sizeof(port)) {
4295 goto tidy_up_and_fail;
4296 goto abort_tidy_up_and_fail;
4300 /* Packets sent. I don't trust them to have arrived though.
4301 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4302 connect to localhost will use a second kernel thread. In 2.6 the
4303 first thread running the connect() returns before the second completes,
4304 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4305 returns 0. Poor programs have tripped up. One poor program's authors'
4306 had a 50-1 reverse stock split. Not sure how connected these were.)
4307 So I don't trust someone not to have an unpredictable UDP stack.
4311 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4312 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4316 FD_SET((unsigned int)sockets[0], &rset);
4317 FD_SET((unsigned int)sockets[1], &rset);
4319 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4320 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4321 || !FD_ISSET(sockets[1], &rset)) {
4322 /* I hope this is portable and appropriate. */
4324 goto tidy_up_and_fail;
4325 goto abort_tidy_up_and_fail;
4329 /* And the paranoia department even now doesn't trust it to have arrive
4330 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4332 struct sockaddr_in readfrom;
4333 unsigned short buffer[2];
4338 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4339 sizeof(buffer), MSG_DONTWAIT,
4340 (struct sockaddr *) &readfrom, &size);
4342 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4344 (struct sockaddr *) &readfrom, &size);
4348 goto tidy_up_and_fail;
4349 if (got != sizeof(port)
4350 || size != sizeof(struct sockaddr_in)
4351 /* Check other socket sent us its port. */
4352 || buffer[0] != (unsigned short) addresses[!i].sin_port
4353 /* Check kernel says we got the datagram from that socket */
4354 || readfrom.sin_family != addresses[!i].sin_family
4355 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4356 || readfrom.sin_port != addresses[!i].sin_port)
4357 goto abort_tidy_up_and_fail;
4360 /* My caller (my_socketpair) has validated that this is non-NULL */
4363 /* I hereby declare this connection open. May God bless all who cross
4367 abort_tidy_up_and_fail:
4368 errno = ECONNABORTED;
4372 if (sockets[0] != -1)
4373 PerlLIO_close(sockets[0]);
4374 if (sockets[1] != -1)
4375 PerlLIO_close(sockets[1]);
4380 #endif /* EMULATE_SOCKETPAIR_UDP */
4382 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4384 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4385 /* Stevens says that family must be AF_LOCAL, protocol 0.
4386 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4391 struct sockaddr_in listen_addr;
4392 struct sockaddr_in connect_addr;
4397 || family != AF_UNIX
4400 errno = EAFNOSUPPORT;
4408 #ifdef EMULATE_SOCKETPAIR_UDP
4409 if (type == SOCK_DGRAM)
4410 return S_socketpair_udp(fd);
4413 aTHXa(PERL_GET_THX);
4414 listener = PerlSock_socket(AF_INET, type, 0);
4417 memset(&listen_addr, 0, sizeof(listen_addr));
4418 listen_addr.sin_family = AF_INET;
4419 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4420 listen_addr.sin_port = 0; /* kernel choses port. */
4421 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4422 sizeof(listen_addr)) == -1)
4423 goto tidy_up_and_fail;
4424 if (PerlSock_listen(listener, 1) == -1)
4425 goto tidy_up_and_fail;
4427 connector = PerlSock_socket(AF_INET, type, 0);
4428 if (connector == -1)
4429 goto tidy_up_and_fail;
4430 /* We want to find out the port number to connect to. */
4431 size = sizeof(connect_addr);
4432 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4434 goto tidy_up_and_fail;
4435 if (size != sizeof(connect_addr))
4436 goto abort_tidy_up_and_fail;
4437 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4438 sizeof(connect_addr)) == -1)
4439 goto tidy_up_and_fail;
4441 size = sizeof(listen_addr);
4442 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4445 goto tidy_up_and_fail;
4446 if (size != sizeof(listen_addr))
4447 goto abort_tidy_up_and_fail;
4448 PerlLIO_close(listener);
4449 /* Now check we are talking to ourself by matching port and host on the
4451 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4453 goto tidy_up_and_fail;
4454 if (size != sizeof(connect_addr)
4455 || listen_addr.sin_family != connect_addr.sin_family
4456 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4457 || listen_addr.sin_port != connect_addr.sin_port) {
4458 goto abort_tidy_up_and_fail;
4464 abort_tidy_up_and_fail:
4466 errno = ECONNABORTED; /* This would be the standard thing to do. */
4468 # ifdef ECONNREFUSED
4469 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4471 errno = ETIMEDOUT; /* Desperation time. */
4478 PerlLIO_close(listener);
4479 if (connector != -1)
4480 PerlLIO_close(connector);
4482 PerlLIO_close(acceptor);
4488 /* In any case have a stub so that there's code corresponding
4489 * to the my_socketpair in embed.fnc. */
4491 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4492 #ifdef HAS_SOCKETPAIR
4493 return socketpair(family, type, protocol, fd);
4502 =for apidoc sv_nosharing
4504 Dummy routine which "shares" an SV when there is no sharing module present.
4505 Or "locks" it. Or "unlocks" it. In other
4506 words, ignores its single SV argument.
4507 Exists to avoid test for a C<NULL> function pointer and because it could
4508 potentially warn under some level of strict-ness.
4514 Perl_sv_nosharing(pTHX_ SV *sv)
4516 PERL_UNUSED_CONTEXT;
4517 PERL_UNUSED_ARG(sv);
4522 =for apidoc sv_destroyable
4524 Dummy routine which reports that object can be destroyed when there is no
4525 sharing module present. It ignores its single SV argument, and returns
4526 'true'. Exists to avoid test for a C<NULL> function pointer and because it
4527 could potentially warn under some level of strict-ness.
4533 Perl_sv_destroyable(pTHX_ SV *sv)
4535 PERL_UNUSED_CONTEXT;
4536 PERL_UNUSED_ARG(sv);
4541 Perl_parse_unicode_opts(pTHX_ const char **popt)
4543 const char *p = *popt;
4546 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
4552 if (grok_atoUV(p, &uv, &endptr) && uv <= U32_MAX) {
4555 if (p && *p && *p != '\n' && *p != '\r') {
4557 goto the_end_of_the_opts_parser;
4559 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4563 Perl_croak(aTHX_ "Invalid number '%s' for -C option.\n", p);
4569 case PERL_UNICODE_STDIN:
4570 opt |= PERL_UNICODE_STDIN_FLAG; break;
4571 case PERL_UNICODE_STDOUT:
4572 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4573 case PERL_UNICODE_STDERR:
4574 opt |= PERL_UNICODE_STDERR_FLAG; break;
4575 case PERL_UNICODE_STD:
4576 opt |= PERL_UNICODE_STD_FLAG; break;
4577 case PERL_UNICODE_IN:
4578 opt |= PERL_UNICODE_IN_FLAG; break;
4579 case PERL_UNICODE_OUT:
4580 opt |= PERL_UNICODE_OUT_FLAG; break;
4581 case PERL_UNICODE_INOUT:
4582 opt |= PERL_UNICODE_INOUT_FLAG; break;
4583 case PERL_UNICODE_LOCALE:
4584 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4585 case PERL_UNICODE_ARGV:
4586 opt |= PERL_UNICODE_ARGV_FLAG; break;
4587 case PERL_UNICODE_UTF8CACHEASSERT:
4588 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
4590 if (*p != '\n' && *p != '\r') {
4591 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4594 "Unknown Unicode option letter '%c'", *p);
4601 opt = PERL_UNICODE_DEFAULT_FLAGS;
4603 the_end_of_the_opts_parser:
4605 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4606 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4607 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4615 # include <starlet.h>
4622 * This is really just a quick hack which grabs various garbage
4623 * values. It really should be a real hash algorithm which
4624 * spreads the effect of every input bit onto every output bit,
4625 * if someone who knows about such things would bother to write it.
4626 * Might be a good idea to add that function to CORE as well.
4627 * No numbers below come from careful analysis or anything here,
4628 * except they are primes and SEED_C1 > 1E6 to get a full-width
4629 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4630 * probably be bigger too.
4633 # define SEED_C1 1000003
4634 #define SEED_C4 73819
4636 # define SEED_C1 25747
4637 #define SEED_C4 20639
4641 #define SEED_C5 26107
4643 #ifndef PERL_NO_DEV_RANDOM
4647 #ifdef HAS_GETTIMEOFDAY
4648 struct timeval when;
4653 /* This test is an escape hatch, this symbol isn't set by Configure. */
4654 #ifndef PERL_NO_DEV_RANDOM
4655 #ifndef PERL_RANDOM_DEVICE
4656 /* /dev/random isn't used by default because reads from it will block
4657 * if there isn't enough entropy available. You can compile with
4658 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4659 * is enough real entropy to fill the seed. */
4660 # ifdef __amigaos4__
4661 # define PERL_RANDOM_DEVICE "RANDOM:SIZE=4"
4663 # define PERL_RANDOM_DEVICE "/dev/urandom"
4666 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4668 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4676 #ifdef HAS_GETTIMEOFDAY
4677 PerlProc_gettimeofday(&when,NULL);
4678 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4681 u = (U32)SEED_C1 * when;
4683 u += SEED_C3 * (U32)PerlProc_getpid();
4684 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4685 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4686 u += SEED_C5 * (U32)PTR2UV(&when);
4692 Perl_get_hash_seed(pTHX_ unsigned char * const seed_buffer)
4697 PERL_ARGS_ASSERT_GET_HASH_SEED;
4699 env_pv= PerlEnv_getenv("PERL_HASH_SEED");
4702 #ifndef USE_HASH_SEED_EXPLICIT
4704 /* ignore leading spaces */
4705 while (isSPACE(*env_pv))
4707 #ifdef USE_PERL_PERTURB_KEYS
4708 /* if they set it to "0" we disable key traversal randomization completely */
4709 if (strEQ(env_pv,"0")) {
4710 PL_hash_rand_bits_enabled= 0;
4712 /* otherwise switch to deterministic mode */
4713 PL_hash_rand_bits_enabled= 2;
4716 /* ignore a leading 0x... if it is there */
4717 if (env_pv[0] == '0' && env_pv[1] == 'x')
4720 for( i = 0; isXDIGIT(*env_pv) && i < PERL_HASH_SEED_BYTES; i++ ) {
4721 seed_buffer[i] = READ_XDIGIT(env_pv) << 4;
4722 if ( isXDIGIT(*env_pv)) {
4723 seed_buffer[i] |= READ_XDIGIT(env_pv);
4726 while (isSPACE(*env_pv))
4729 if (*env_pv && !isXDIGIT(*env_pv)) {
4730 Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n");
4732 /* should we check for unparsed crap? */
4733 /* should we warn about unused hex? */
4734 /* should we warn about insufficient hex? */
4739 (void)seedDrand01((Rand_seed_t)seed());
4741 for( i = 0; i < PERL_HASH_SEED_BYTES; i++ ) {
4742 seed_buffer[i] = (unsigned char)(Drand01() * (U8_MAX+1));
4745 #ifdef USE_PERL_PERTURB_KEYS
4746 { /* initialize PL_hash_rand_bits from the hash seed.
4747 * This value is highly volatile, it is updated every
4748 * hash insert, and is used as part of hash bucket chain
4749 * randomization and hash iterator randomization. */
4750 PL_hash_rand_bits= 0xbe49d17f; /* I just picked a number */
4751 for( i = 0; i < sizeof(UV) ; i++ ) {
4752 PL_hash_rand_bits += seed_buffer[i % PERL_HASH_SEED_BYTES];
4753 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,8);
4756 env_pv= PerlEnv_getenv("PERL_PERTURB_KEYS");
4758 if (strEQ(env_pv,"0") || strEQ(env_pv,"NO")) {
4759 PL_hash_rand_bits_enabled= 0;
4760 } else if (strEQ(env_pv,"1") || strEQ(env_pv,"RANDOM")) {
4761 PL_hash_rand_bits_enabled= 1;
4762 } else if (strEQ(env_pv,"2") || strEQ(env_pv,"DETERMINISTIC")) {
4763 PL_hash_rand_bits_enabled= 2;
4765 Perl_warn(aTHX_ "perl: warning: strange setting in '$ENV{PERL_PERTURB_KEYS}': '%s'\n", env_pv);
4771 #ifdef PERL_GLOBAL_STRUCT
4773 #define PERL_GLOBAL_STRUCT_INIT
4774 #include "opcode.h" /* the ppaddr and check */
4777 Perl_init_global_struct(pTHX)
4779 struct perl_vars *plvarsp = NULL;
4780 # ifdef PERL_GLOBAL_STRUCT
4781 const IV nppaddr = C_ARRAY_LENGTH(Gppaddr);
4782 const IV ncheck = C_ARRAY_LENGTH(Gcheck);
4783 PERL_UNUSED_CONTEXT;
4784 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4785 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
4786 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
4790 plvarsp = PL_VarsPtr;
4791 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
4796 # define PERLVAR(prefix,var,type) /**/
4797 # define PERLVARA(prefix,var,n,type) /**/
4798 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
4799 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
4800 # include "perlvars.h"
4805 # ifdef PERL_GLOBAL_STRUCT
4808 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
4809 if (!plvarsp->Gppaddr)
4813 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
4814 if (!plvarsp->Gcheck)
4816 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
4817 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
4819 # ifdef PERL_SET_VARS
4820 PERL_SET_VARS(plvarsp);
4822 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4823 plvarsp->Gsv_placeholder.sv_flags = 0;
4824 memset(plvarsp->Ghash_seed, 0, sizeof(plvarsp->Ghash_seed));
4826 # undef PERL_GLOBAL_STRUCT_INIT
4831 #endif /* PERL_GLOBAL_STRUCT */
4833 #ifdef PERL_GLOBAL_STRUCT
4836 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
4838 int veto = plvarsp->Gveto_cleanup;
4840 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
4841 PERL_UNUSED_CONTEXT;
4842 # ifdef PERL_GLOBAL_STRUCT
4843 # ifdef PERL_UNSET_VARS
4844 PERL_UNSET_VARS(plvarsp);
4848 free(plvarsp->Gppaddr);
4849 free(plvarsp->Gcheck);
4850 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4856 #endif /* PERL_GLOBAL_STRUCT */
4860 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including
4861 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
4862 * given, and you supply your own implementation.
4864 * The default implementation reads a single env var, PERL_MEM_LOG,
4865 * expecting one or more of the following:
4867 * \d+ - fd fd to write to : must be 1st (grok_atoUV)
4868 * 'm' - memlog was PERL_MEM_LOG=1
4869 * 's' - svlog was PERL_SV_LOG=1
4870 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
4872 * This makes the logger controllable enough that it can reasonably be
4873 * added to the system perl.
4876 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
4877 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
4879 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
4881 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
4882 * writes to. In the default logger, this is settable at runtime.
4884 #ifndef PERL_MEM_LOG_FD
4885 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
4888 #ifndef PERL_MEM_LOG_NOIMPL
4890 # ifdef DEBUG_LEAKING_SCALARS
4891 # define SV_LOG_SERIAL_FMT " [%lu]"
4892 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
4894 # define SV_LOG_SERIAL_FMT
4895 # define _SV_LOG_SERIAL_ARG(sv)
4899 S_mem_log_common(enum mem_log_type mlt, const UV n,
4900 const UV typesize, const char *type_name, const SV *sv,
4901 Malloc_t oldalloc, Malloc_t newalloc,
4902 const char *filename, const int linenumber,
4903 const char *funcname)
4907 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
4909 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
4912 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
4914 /* We can't use SVs or PerlIO for obvious reasons,
4915 * so we'll use stdio and low-level IO instead. */
4916 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
4918 # ifdef HAS_GETTIMEOFDAY
4919 # define MEM_LOG_TIME_FMT "%10d.%06d: "
4920 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
4922 gettimeofday(&tv, 0);
4924 # define MEM_LOG_TIME_FMT "%10d: "
4925 # define MEM_LOG_TIME_ARG (int)when
4929 /* If there are other OS specific ways of hires time than
4930 * gettimeofday() (see dist/Time-HiRes), the easiest way is
4931 * probably that they would be used to fill in the struct
4938 if (grok_atoUV(pmlenv, &uv, &endptr) /* Ignore endptr. */
4939 && uv && uv <= PERL_INT_MAX
4943 fd = PERL_MEM_LOG_FD;
4946 if (strchr(pmlenv, 't')) {
4947 len = my_snprintf(buf, sizeof(buf),
4948 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
4949 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
4953 len = my_snprintf(buf, sizeof(buf),
4954 "alloc: %s:%d:%s: %"IVdf" %"UVuf
4955 " %s = %"IVdf": %"UVxf"\n",
4956 filename, linenumber, funcname, n, typesize,
4957 type_name, n * typesize, PTR2UV(newalloc));
4960 len = my_snprintf(buf, sizeof(buf),
4961 "realloc: %s:%d:%s: %"IVdf" %"UVuf
4962 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
4963 filename, linenumber, funcname, n, typesize,
4964 type_name, n * typesize, PTR2UV(oldalloc),
4968 len = my_snprintf(buf, sizeof(buf),
4969 "free: %s:%d:%s: %"UVxf"\n",
4970 filename, linenumber, funcname,
4975 len = my_snprintf(buf, sizeof(buf),
4976 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
4977 mlt == MLT_NEW_SV ? "new" : "del",
4978 filename, linenumber, funcname,
4979 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
4984 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
4988 #endif /* !PERL_MEM_LOG_NOIMPL */
4990 #ifndef PERL_MEM_LOG_NOIMPL
4992 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
4993 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
4995 /* this is suboptimal, but bug compatible. User is providing their
4996 own implementation, but is getting these functions anyway, and they
4997 do nothing. But _NOIMPL users should be able to cope or fix */
4999 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
5000 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
5004 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
5006 const char *filename, const int linenumber,
5007 const char *funcname)
5009 PERL_ARGS_ASSERT_MEM_LOG_ALLOC;
5011 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
5012 NULL, NULL, newalloc,
5013 filename, linenumber, funcname);
5018 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
5019 Malloc_t oldalloc, Malloc_t newalloc,
5020 const char *filename, const int linenumber,
5021 const char *funcname)
5023 PERL_ARGS_ASSERT_MEM_LOG_REALLOC;
5025 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
5026 NULL, oldalloc, newalloc,
5027 filename, linenumber, funcname);
5032 Perl_mem_log_free(Malloc_t oldalloc,
5033 const char *filename, const int linenumber,
5034 const char *funcname)
5036 PERL_ARGS_ASSERT_MEM_LOG_FREE;
5038 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
5039 filename, linenumber, funcname);
5044 Perl_mem_log_new_sv(const SV *sv,
5045 const char *filename, const int linenumber,
5046 const char *funcname)
5048 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
5049 filename, linenumber, funcname);
5053 Perl_mem_log_del_sv(const SV *sv,
5054 const char *filename, const int linenumber,
5055 const char *funcname)
5057 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
5058 filename, linenumber, funcname);
5061 #endif /* PERL_MEM_LOG */