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)
554 /* return ptr to little string in big string, NULL if not found */
555 /* This routine was donated by Corey Satten. */
558 Perl_instr(const char *big, const char *little)
561 PERL_ARGS_ASSERT_INSTR;
563 return strstr((char*)big, (char*)little);
567 =head1 Miscellaneous Functions
569 =for apidoc Am|char *|ninstr|char * big|char * bigend|char * little|char * little_end
571 Find the first (leftmost) occurrence of a sequence of bytes within another
572 sequence. This is the Perl version of C<strstr()>, extended to handle
573 arbitrary sequences, potentially containing embedded C<NUL> characters (C<NUL>
574 is what the initial C<n> in the function name stands for; some systems have an
575 equivalent, C<memmem()>, but with a somewhat different API).
577 Another way of thinking about this function is finding a needle in a haystack.
578 C<big> points to the first byte in the haystack. C<big_end> points to one byte
579 beyond the final byte in the haystack. C<little> points to the first byte in
580 the needle. C<little_end> points to one byte beyond the final byte in the
581 needle. All the parameters must be non-C<NULL>.
583 The function returns C<NULL> if there is no occurrence of C<little> within
584 C<big>. If C<little> is the empty string, C<big> is returned.
586 Because this function operates at the byte level, and because of the inherent
587 characteristics of UTF-8 (or UTF-EBCDIC), it will work properly if both the
588 needle and the haystack are strings with the same UTF-8ness, but not if the
596 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
598 PERL_ARGS_ASSERT_NINSTR;
602 const char first = *little;
604 bigend -= lend - little++;
606 while (big <= bigend) {
607 if (*big++ == first) {
608 for (x=big,s=little; s < lend; x++,s++) {
612 return (char*)(big-1);
620 =head1 Miscellaneous Functions
622 =for apidoc Am|char *|rninstr|char * big|char * bigend|char * little|char * little_end
624 Like C<L</ninstr>>, but instead finds the final (rightmost) occurrence of a
625 sequence of bytes within another sequence, returning C<NULL> if there is no
633 Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
636 const I32 first = *little;
637 const char * const littleend = lend;
639 PERL_ARGS_ASSERT_RNINSTR;
641 if (little >= littleend)
642 return (char*)bigend;
644 big = bigend - (littleend - little++);
645 while (big >= bigbeg) {
649 for (x=big+2,s=little; s < littleend; /**/ ) {
658 return (char*)(big+1);
663 /* As a space optimization, we do not compile tables for strings of length
664 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
665 special-cased in fbm_instr().
667 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
670 =head1 Miscellaneous Functions
672 =for apidoc fbm_compile
674 Analyses the string in order to make fast searches on it using C<fbm_instr()>
675 -- the Boyer-Moore algorithm.
681 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
688 PERL_DEB( STRLEN rarest = 0 );
690 PERL_ARGS_ASSERT_FBM_COMPILE;
692 if (isGV_with_GP(sv) || SvROK(sv))
698 if (flags & FBMcf_TAIL) {
699 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
700 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
701 if (mg && mg->mg_len >= 0)
704 if (!SvPOK(sv) || SvNIOKp(sv))
705 s = (U8*)SvPV_force_mutable(sv, len);
706 else s = (U8 *)SvPV_mutable(sv, len);
707 if (len == 0) /* TAIL might be on a zero-length string. */
709 SvUPGRADE(sv, SVt_PVMG);
714 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
715 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
716 to call SvVALID_off() if the scalar was assigned to.
718 The comment itself (and "deeper magic" below) date back to
719 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
721 where the magic (presumably) was that the scalar had a BM table hidden
724 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
725 the table instead of the previous (somewhat hacky) approach of co-opting
726 the string buffer and storing it after the string. */
728 assert(!mg_find(sv, PERL_MAGIC_bm));
729 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
733 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
735 const U8 mlen = (len>255) ? 255 : (U8)len;
736 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
739 Newx(table, 256, U8);
740 memset((void*)table, mlen, 256);
741 mg->mg_ptr = (char *)table;
744 s += len - 1; /* last char */
747 if (table[*s] == mlen)
753 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
754 for (i = 0; i < len; i++) {
755 if (PL_freq[s[i]] < frequency) {
756 PERL_DEB( rarest = i );
757 frequency = PL_freq[s[i]];
760 BmUSEFUL(sv) = 100; /* Initial value */
761 if (flags & FBMcf_TAIL)
763 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
764 s[rarest], (UV)rarest));
769 =for apidoc fbm_instr
771 Returns the location of the SV in the string delimited by C<big> and
772 C<bigend> (C<bigend>) is the char following the last char).
773 It returns C<NULL> if the string can't be found. The C<sv>
774 does not have to be C<fbm_compiled>, but the search will not be as fast
779 If SvTAIL(littlestr) is true, a fake "\n" was appended to to the string
780 during FBM compilation due to FBMcf_TAIL in flags. It indicates that
781 the littlestr must be anchored to the end of bigstr (or to any \n if
784 E.g. The regex compiler would compile /abc/ to a littlestr of "abc",
785 while /abc$/ compiles to "abc\n" with SvTAIL() true.
787 A littlestr of "abc", !SvTAIL matches as /abc/;
788 a littlestr of "ab\n", SvTAIL matches as:
789 without FBMrf_MULTILINE: /ab\n?\z/
790 with FBMrf_MULTILINE: /ab\n/ || /ab\z/;
792 (According to Ilya from 1999; I don't know if this is still true, DAPM 2015):
793 "If SvTAIL is actually due to \Z or \z, this gives false positives
799 Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
803 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
804 STRLEN littlelen = l;
805 const I32 multiline = flags & FBMrf_MULTILINE;
807 PERL_ARGS_ASSERT_FBM_INSTR;
809 if ((STRLEN)(bigend - big) < littlelen) {
810 if ( SvTAIL(littlestr)
811 && ((STRLEN)(bigend - big) == littlelen - 1)
813 || (*big == *little &&
814 memEQ((char *)big, (char *)little, littlelen - 1))))
819 switch (littlelen) { /* Special cases for 0, 1 and 2 */
821 return (char*)big; /* Cannot be SvTAIL! */
824 if (SvTAIL(littlestr) && !multiline) /* Anchor only! */
825 /* [-1] is safe because we know that bigend != big. */
826 return (char *) (bigend - (bigend[-1] == '\n'));
828 s = (unsigned char *)memchr((void*)big, *little, bigend-big);
831 if (SvTAIL(littlestr))
832 return (char *) bigend;
836 if (SvTAIL(littlestr) && !multiline) {
837 /* a littlestr with SvTAIL must be of the form "X\n" (where X
838 * is a single char). It is anchored, and can only match
839 * "....X\n" or "....X" */
840 if (bigend[-2] == *little && bigend[-1] == '\n')
841 return (char*)bigend - 2;
842 if (bigend[-1] == *little)
843 return (char*)bigend - 1;
848 /* memchr() is likely to be very fast, possibly using whatever
849 * hardware support is available, such as checking a whole
850 * cache line in one instruction.
851 * So for a 2 char pattern, calling memchr() is likely to be
852 * faster than running FBM, or rolling our own. The previous
853 * version of this code was roll-your-own which typically
854 * only needed to read every 2nd char, which was good back in
855 * the day, but no longer.
857 unsigned char c1 = little[0];
858 unsigned char c2 = little[1];
860 /* *** for all this case, bigend points to the last char,
861 * not the trailing \0: this makes the conditions slightly
867 /* do a quick test for c1 before calling memchr();
868 * this avoids the expensive fn call overhead when
869 * there are lots of c1's */
870 if (LIKELY(*s != c1)) {
872 s = (unsigned char *)memchr((void*)s, c1, bigend - s);
879 /* failed; try searching for c2 this time; that way
880 * we don't go pathologically slow when the string
881 * consists mostly of c1's or vice versa.
886 s = (unsigned char *)memchr((void*)s, c2, bigend - s + 1);
894 /* c1, c2 the same */
904 s = (unsigned char *)memchr((void*)s, c1, bigend - s);
905 if (!s || s >= bigend)
912 /* failed to find 2 chars; try anchored match at end without
914 if (SvTAIL(littlestr) && bigend[0] == little[0])
915 return (char *)bigend;
920 break; /* Only lengths 0 1 and 2 have special-case code. */
923 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
924 s = bigend - littlelen;
925 if (s >= big && bigend[-1] == '\n' && *s == *little
926 /* Automatically of length > 2 */
927 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
929 return (char*)s; /* how sweet it is */
932 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
934 return (char*)s + 1; /* how sweet it is */
939 if (!SvVALID(littlestr)) {
940 /* not compiled; use Perl_ninstr() instead */
941 char * const b = ninstr((char*)big,(char*)bigend,
942 (char*)little, (char*)little + littlelen);
944 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
945 /* Chop \n from littlestr: */
946 s = bigend - littlelen + 1;
948 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
958 if (littlelen > (STRLEN)(bigend - big))
962 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
963 const unsigned char *oldlittle;
967 --littlelen; /* Last char found by table lookup */
970 little += littlelen; /* last char */
973 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
974 const unsigned char lastc = *little;
978 if ((tmp = table[*s])) {
979 /* *s != lastc; earliest position it could match now is
980 * tmp slots further on */
981 if ((s += tmp) >= bigend)
983 if (LIKELY(*s != lastc)) {
985 s = (unsigned char *)memchr((void*)s, lastc, bigend - s);
995 /* hand-rolled strncmp(): less expensive than calling the
996 * real function (maybe???) */
998 unsigned char * const olds = s;
1003 if (*--s == *--little)
1005 s = olds + 1; /* here we pay the price for failure */
1007 if (s < bigend) /* fake up continue to outer loop */
1016 && SvTAIL(littlestr)
1017 && memEQ((char *)(bigend - littlelen),
1018 (char *)(oldlittle - littlelen), littlelen) )
1019 return (char*)bigend - littlelen;
1028 Returns true if the leading C<len> bytes of the strings C<s1> and C<s2> are the
1030 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
1031 match themselves and their opposite case counterparts. Non-cased and non-ASCII
1032 range bytes match only themselves.
1039 Perl_foldEQ(const char *s1, const char *s2, I32 len)
1041 const U8 *a = (const U8 *)s1;
1042 const U8 *b = (const U8 *)s2;
1044 PERL_ARGS_ASSERT_FOLDEQ;
1049 if (*a != *b && *a != PL_fold[*b])
1056 Perl_foldEQ_latin1(const char *s1, const char *s2, I32 len)
1058 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
1059 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
1060 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
1061 * does it check that the strings each have at least 'len' characters */
1063 const U8 *a = (const U8 *)s1;
1064 const U8 *b = (const U8 *)s2;
1066 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
1071 if (*a != *b && *a != PL_fold_latin1[*b]) {
1080 =for apidoc foldEQ_locale
1082 Returns true if the leading C<len> bytes of the strings C<s1> and C<s2> are the
1083 same case-insensitively in the current locale; false otherwise.
1089 Perl_foldEQ_locale(const char *s1, const char *s2, I32 len)
1092 const U8 *a = (const U8 *)s1;
1093 const U8 *b = (const U8 *)s2;
1095 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
1100 if (*a != *b && *a != PL_fold_locale[*b])
1107 /* copy a string to a safe spot */
1110 =head1 Memory Management
1114 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1115 string which is a duplicate of C<pv>. The size of the string is
1116 determined by C<strlen()>, which means it may not contain embedded C<NUL>
1117 characters and must have a trailing C<NUL>. The memory allocated for the new
1118 string can be freed with the C<Safefree()> function.
1120 On some platforms, Windows for example, all allocated memory owned by a thread
1121 is deallocated when that thread ends. So if you need that not to happen, you
1122 need to use the shared memory functions, such as C<L</savesharedpv>>.
1128 Perl_savepv(pTHX_ const char *pv)
1130 PERL_UNUSED_CONTEXT;
1135 const STRLEN pvlen = strlen(pv)+1;
1136 Newx(newaddr, pvlen, char);
1137 return (char*)memcpy(newaddr, pv, pvlen);
1141 /* same thing but with a known length */
1146 Perl's version of what C<strndup()> would be if it existed. Returns a
1147 pointer to a newly allocated string which is a duplicate of the first
1148 C<len> bytes from C<pv>, plus a trailing
1149 C<NUL> byte. The memory allocated for
1150 the new string can be freed with the C<Safefree()> function.
1152 On some platforms, Windows for example, all allocated memory owned by a thread
1153 is deallocated when that thread ends. So if you need that not to happen, you
1154 need to use the shared memory functions, such as C<L</savesharedpvn>>.
1160 Perl_savepvn(pTHX_ const char *pv, I32 len)
1163 PERL_UNUSED_CONTEXT;
1167 Newx(newaddr,len+1,char);
1168 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1170 /* might not be null terminated */
1171 newaddr[len] = '\0';
1172 return (char *) CopyD(pv,newaddr,len,char);
1175 return (char *) ZeroD(newaddr,len+1,char);
1180 =for apidoc savesharedpv
1182 A version of C<savepv()> which allocates the duplicate string in memory
1183 which is shared between threads.
1188 Perl_savesharedpv(pTHX_ const char *pv)
1193 PERL_UNUSED_CONTEXT;
1198 pvlen = strlen(pv)+1;
1199 newaddr = (char*)PerlMemShared_malloc(pvlen);
1203 return (char*)memcpy(newaddr, pv, pvlen);
1207 =for apidoc savesharedpvn
1209 A version of C<savepvn()> which allocates the duplicate string in memory
1210 which is shared between threads. (With the specific difference that a C<NULL>
1211 pointer is not acceptable)
1216 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1218 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1220 PERL_UNUSED_CONTEXT;
1221 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1226 newaddr[len] = '\0';
1227 return (char*)memcpy(newaddr, pv, len);
1231 =for apidoc savesvpv
1233 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1234 the passed in SV using C<SvPV()>
1236 On some platforms, Windows for example, all allocated memory owned by a thread
1237 is deallocated when that thread ends. So if you need that not to happen, you
1238 need to use the shared memory functions, such as C<L</savesharedsvpv>>.
1244 Perl_savesvpv(pTHX_ SV *sv)
1247 const char * const pv = SvPV_const(sv, len);
1250 PERL_ARGS_ASSERT_SAVESVPV;
1253 Newx(newaddr,len,char);
1254 return (char *) CopyD(pv,newaddr,len,char);
1258 =for apidoc savesharedsvpv
1260 A version of C<savesharedpv()> which allocates the duplicate string in
1261 memory which is shared between threads.
1267 Perl_savesharedsvpv(pTHX_ SV *sv)
1270 const char * const pv = SvPV_const(sv, len);
1272 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1274 return savesharedpvn(pv, len);
1277 /* the SV for Perl_form() and mess() is not kept in an arena */
1285 if (PL_phase != PERL_PHASE_DESTRUCT)
1286 return newSVpvs_flags("", SVs_TEMP);
1291 /* Create as PVMG now, to avoid any upgrading later */
1293 Newxz(any, 1, XPVMG);
1294 SvFLAGS(sv) = SVt_PVMG;
1295 SvANY(sv) = (void*)any;
1297 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1302 #if defined(PERL_IMPLICIT_CONTEXT)
1304 Perl_form_nocontext(const char* pat, ...)
1309 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1310 va_start(args, pat);
1311 retval = vform(pat, &args);
1315 #endif /* PERL_IMPLICIT_CONTEXT */
1318 =head1 Miscellaneous Functions
1321 Takes a sprintf-style format pattern and conventional
1322 (non-SV) arguments and returns the formatted string.
1324 (char *) Perl_form(pTHX_ const char* pat, ...)
1326 can be used any place a string (char *) is required:
1328 char * s = Perl_form("%d.%d",major,minor);
1330 Uses a single private buffer so if you want to format several strings you
1331 must explicitly copy the earlier strings away (and free the copies when you
1338 Perl_form(pTHX_ const char* pat, ...)
1342 PERL_ARGS_ASSERT_FORM;
1343 va_start(args, pat);
1344 retval = vform(pat, &args);
1350 Perl_vform(pTHX_ const char *pat, va_list *args)
1352 SV * const sv = mess_alloc();
1353 PERL_ARGS_ASSERT_VFORM;
1354 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1359 =for apidoc Am|SV *|mess|const char *pat|...
1361 Take a sprintf-style format pattern and argument list. These are used to
1362 generate a string message. If the message does not end with a newline,
1363 then it will be extended with some indication of the current location
1364 in the code, as described for L</mess_sv>.
1366 Normally, the resulting message is returned in a new mortal SV.
1367 During global destruction a single SV may be shared between uses of
1373 #if defined(PERL_IMPLICIT_CONTEXT)
1375 Perl_mess_nocontext(const char *pat, ...)
1380 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1381 va_start(args, pat);
1382 retval = vmess(pat, &args);
1386 #endif /* PERL_IMPLICIT_CONTEXT */
1389 Perl_mess(pTHX_ const char *pat, ...)
1393 PERL_ARGS_ASSERT_MESS;
1394 va_start(args, pat);
1395 retval = vmess(pat, &args);
1401 Perl_closest_cop(pTHX_ const COP *cop, const OP *o, const OP *curop,
1404 /* Look for curop starting from o. cop is the last COP we've seen. */
1405 /* opnext means that curop is actually the ->op_next of the op we are
1408 PERL_ARGS_ASSERT_CLOSEST_COP;
1410 if (!o || !curop || (
1411 opnext ? o->op_next == curop && o->op_type != OP_SCOPE : o == curop
1415 if (o->op_flags & OPf_KIDS) {
1417 for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
1420 /* If the OP_NEXTSTATE has been optimised away we can still use it
1421 * the get the file and line number. */
1423 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1424 cop = (const COP *)kid;
1426 /* Keep searching, and return when we've found something. */
1428 new_cop = closest_cop(cop, kid, curop, opnext);
1434 /* Nothing found. */
1440 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1442 Expands a message, intended for the user, to include an indication of
1443 the current location in the code, if the message does not already appear
1446 C<basemsg> is the initial message or object. If it is a reference, it
1447 will be used as-is and will be the result of this function. Otherwise it
1448 is used as a string, and if it already ends with a newline, it is taken
1449 to be complete, and the result of this function will be the same string.
1450 If the message does not end with a newline, then a segment such as C<at
1451 foo.pl line 37> will be appended, and possibly other clauses indicating
1452 the current state of execution. The resulting message will end with a
1455 Normally, the resulting message is returned in a new mortal SV.
1456 During global destruction a single SV may be shared between uses of this
1457 function. If C<consume> is true, then the function is permitted (but not
1458 required) to modify and return C<basemsg> instead of allocating a new SV.
1464 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1468 #if defined(USE_C_BACKTRACE) && defined(USE_C_BACKTRACE_ON_ERROR)
1472 /* The PERL_C_BACKTRACE_ON_WARN must be an integer of one or more. */
1473 if ((ws = PerlEnv_getenv("PERL_C_BACKTRACE_ON_ERROR"))
1474 && grok_atoUV(ws, &wi, NULL)
1475 && wi <= PERL_INT_MAX
1477 Perl_dump_c_backtrace(aTHX_ Perl_debug_log, (int)wi, 1);
1482 PERL_ARGS_ASSERT_MESS_SV;
1484 if (SvROK(basemsg)) {
1490 sv_setsv(sv, basemsg);
1495 if (SvPOK(basemsg) && consume) {
1500 sv_copypv(sv, basemsg);
1503 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1505 * Try and find the file and line for PL_op. This will usually be
1506 * PL_curcop, but it might be a cop that has been optimised away. We
1507 * can try to find such a cop by searching through the optree starting
1508 * from the sibling of PL_curcop.
1512 closest_cop(PL_curcop, OpSIBLING(PL_curcop), PL_op, FALSE);
1517 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1518 OutCopFILE(cop), (IV)CopLINE(cop));
1519 /* Seems that GvIO() can be untrustworthy during global destruction. */
1520 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1521 && IoLINES(GvIOp(PL_last_in_gv)))
1524 const bool line_mode = (RsSIMPLE(PL_rs) &&
1525 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1526 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1527 SVfARG(PL_last_in_gv == PL_argvgv
1529 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1530 line_mode ? "line" : "chunk",
1531 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1533 if (PL_phase == PERL_PHASE_DESTRUCT)
1534 sv_catpvs(sv, " during global destruction");
1535 sv_catpvs(sv, ".\n");
1541 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1543 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1544 argument list, respectively. These are used to generate a string message. If
1546 message does not end with a newline, then it will be extended with
1547 some indication of the current location in the code, as described for
1550 Normally, the resulting message is returned in a new mortal SV.
1551 During global destruction a single SV may be shared between uses of
1558 Perl_vmess(pTHX_ const char *pat, va_list *args)
1560 SV * const sv = mess_alloc();
1562 PERL_ARGS_ASSERT_VMESS;
1564 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1565 return mess_sv(sv, 1);
1569 Perl_write_to_stderr(pTHX_ SV* msv)
1574 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1576 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1577 && (io = GvIO(PL_stderrgv))
1578 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1579 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, SV_CONST(PRINT),
1580 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1582 PerlIO * const serr = Perl_error_log;
1584 do_print(msv, serr);
1585 (void)PerlIO_flush(serr);
1590 =head1 Warning and Dieing
1593 /* Common code used in dieing and warning */
1596 S_with_queued_errors(pTHX_ SV *ex)
1598 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1599 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1600 sv_catsv(PL_errors, ex);
1601 ex = sv_mortalcopy(PL_errors);
1602 SvCUR_set(PL_errors, 0);
1608 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1613 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1614 /* sv_2cv might call Perl_croak() or Perl_warner() */
1615 SV * const oldhook = *hook;
1623 cv = sv_2cv(oldhook, &stash, &gv, 0);
1625 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1635 exarg = newSVsv(ex);
1636 SvREADONLY_on(exarg);
1639 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1643 call_sv(MUTABLE_SV(cv), G_DISCARD);
1652 =for apidoc Am|OP *|die_sv|SV *baseex
1654 Behaves the same as L</croak_sv>, except for the return type.
1655 It should be used only where the C<OP *> return type is required.
1656 The function never actually returns.
1662 # pragma warning( push )
1663 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1664 __declspec(noreturn) has non-void return type */
1665 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1666 __declspec(noreturn) has a return statement */
1669 Perl_die_sv(pTHX_ SV *baseex)
1671 PERL_ARGS_ASSERT_DIE_SV;
1674 NORETURN_FUNCTION_END;
1677 # pragma warning( pop )
1681 =for apidoc Am|OP *|die|const char *pat|...
1683 Behaves the same as L</croak>, except for the return type.
1684 It should be used only where the C<OP *> return type is required.
1685 The function never actually returns.
1690 #if defined(PERL_IMPLICIT_CONTEXT)
1692 # pragma warning( push )
1693 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1694 __declspec(noreturn) has non-void return type */
1695 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1696 __declspec(noreturn) has a return statement */
1699 Perl_die_nocontext(const char* pat, ...)
1703 va_start(args, pat);
1705 NOT_REACHED; /* NOTREACHED */
1707 NORETURN_FUNCTION_END;
1710 # pragma warning( pop )
1712 #endif /* PERL_IMPLICIT_CONTEXT */
1715 # pragma warning( push )
1716 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1717 __declspec(noreturn) has non-void return type */
1718 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1719 __declspec(noreturn) has a return statement */
1722 Perl_die(pTHX_ const char* pat, ...)
1725 va_start(args, pat);
1727 NOT_REACHED; /* NOTREACHED */
1729 NORETURN_FUNCTION_END;
1732 # pragma warning( pop )
1736 =for apidoc Am|void|croak_sv|SV *baseex
1738 This is an XS interface to Perl's C<die> function.
1740 C<baseex> is the error message or object. If it is a reference, it
1741 will be used as-is. Otherwise it is used as a string, and if it does
1742 not end with a newline then it will be extended with some indication of
1743 the current location in the code, as described for L</mess_sv>.
1745 The error message or object will be used as an exception, by default
1746 returning control to the nearest enclosing C<eval>, but subject to
1747 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1748 function never returns normally.
1750 To die with a simple string message, the L</croak> function may be
1757 Perl_croak_sv(pTHX_ SV *baseex)
1759 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1760 PERL_ARGS_ASSERT_CROAK_SV;
1761 invoke_exception_hook(ex, FALSE);
1766 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1768 This is an XS interface to Perl's C<die> function.
1770 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1771 argument list. These are used to generate a string message. If the
1772 message does not end with a newline, then it will be extended with
1773 some indication of the current location in the code, as described for
1776 The error message will be used as an exception, by default
1777 returning control to the nearest enclosing C<eval>, but subject to
1778 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1779 function never returns normally.
1781 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1782 (C<$@>) will be used as an error message or object instead of building an
1783 error message from arguments. If you want to throw a non-string object,
1784 or build an error message in an SV yourself, it is preferable to use
1785 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1791 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1793 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1794 invoke_exception_hook(ex, FALSE);
1799 =for apidoc Am|void|croak|const char *pat|...
1801 This is an XS interface to Perl's C<die> function.
1803 Take a sprintf-style format pattern and argument list. These are used to
1804 generate a string message. If the message does not end with a newline,
1805 then it will be extended with some indication of the current location
1806 in the code, as described for L</mess_sv>.
1808 The error message will be used as an exception, by default
1809 returning control to the nearest enclosing C<eval>, but subject to
1810 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1811 function never returns normally.
1813 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1814 (C<$@>) will be used as an error message or object instead of building an
1815 error message from arguments. If you want to throw a non-string object,
1816 or build an error message in an SV yourself, it is preferable to use
1817 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1822 #if defined(PERL_IMPLICIT_CONTEXT)
1824 Perl_croak_nocontext(const char *pat, ...)
1828 va_start(args, pat);
1830 NOT_REACHED; /* NOTREACHED */
1833 #endif /* PERL_IMPLICIT_CONTEXT */
1836 Perl_croak(pTHX_ const char *pat, ...)
1839 va_start(args, pat);
1841 NOT_REACHED; /* NOTREACHED */
1846 =for apidoc Am|void|croak_no_modify
1848 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1849 terser object code than using C<Perl_croak>. Less code used on exception code
1850 paths reduces CPU cache pressure.
1856 Perl_croak_no_modify(void)
1858 Perl_croak_nocontext( "%s", PL_no_modify);
1861 /* does not return, used in util.c perlio.c and win32.c
1862 This is typically called when malloc returns NULL.
1865 Perl_croak_no_mem(void)
1869 int fd = PerlIO_fileno(Perl_error_log);
1871 SETERRNO(EBADF,RMS_IFI);
1873 /* Can't use PerlIO to write as it allocates memory */
1874 PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, sizeof(PL_no_mem)-1));
1879 /* does not return, used only in POPSTACK */
1881 Perl_croak_popstack(void)
1884 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
1889 =for apidoc Am|void|warn_sv|SV *baseex
1891 This is an XS interface to Perl's C<warn> function.
1893 C<baseex> is the error message or object. If it is a reference, it
1894 will be used as-is. Otherwise it is used as a string, and if it does
1895 not end with a newline then it will be extended with some indication of
1896 the current location in the code, as described for L</mess_sv>.
1898 The error message or object will by default be written to standard error,
1899 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1901 To warn with a simple string message, the L</warn> function may be
1908 Perl_warn_sv(pTHX_ SV *baseex)
1910 SV *ex = mess_sv(baseex, 0);
1911 PERL_ARGS_ASSERT_WARN_SV;
1912 if (!invoke_exception_hook(ex, TRUE))
1913 write_to_stderr(ex);
1917 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1919 This is an XS interface to Perl's C<warn> function.
1921 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1922 argument list. These are used to generate a string message. If the
1923 message does not end with a newline, then it will be extended with
1924 some indication of the current location in the code, as described for
1927 The error message or object will by default be written to standard error,
1928 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1930 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1936 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1938 SV *ex = vmess(pat, args);
1939 PERL_ARGS_ASSERT_VWARN;
1940 if (!invoke_exception_hook(ex, TRUE))
1941 write_to_stderr(ex);
1945 =for apidoc Am|void|warn|const char *pat|...
1947 This is an XS interface to Perl's C<warn> function.
1949 Take a sprintf-style format pattern and argument list. These are used to
1950 generate a string message. If the message does not end with a newline,
1951 then it will be extended with some indication of the current location
1952 in the code, as described for L</mess_sv>.
1954 The error message or object will by default be written to standard error,
1955 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1957 Unlike with L</croak>, C<pat> is not permitted to be null.
1962 #if defined(PERL_IMPLICIT_CONTEXT)
1964 Perl_warn_nocontext(const char *pat, ...)
1968 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1969 va_start(args, pat);
1973 #endif /* PERL_IMPLICIT_CONTEXT */
1976 Perl_warn(pTHX_ const char *pat, ...)
1979 PERL_ARGS_ASSERT_WARN;
1980 va_start(args, pat);
1985 #if defined(PERL_IMPLICIT_CONTEXT)
1987 Perl_warner_nocontext(U32 err, const char *pat, ...)
1991 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1992 va_start(args, pat);
1993 vwarner(err, pat, &args);
1996 #endif /* PERL_IMPLICIT_CONTEXT */
1999 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
2001 PERL_ARGS_ASSERT_CK_WARNER_D;
2003 if (Perl_ckwarn_d(aTHX_ err)) {
2005 va_start(args, pat);
2006 vwarner(err, pat, &args);
2012 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
2014 PERL_ARGS_ASSERT_CK_WARNER;
2016 if (Perl_ckwarn(aTHX_ err)) {
2018 va_start(args, pat);
2019 vwarner(err, pat, &args);
2025 Perl_warner(pTHX_ U32 err, const char* pat,...)
2028 PERL_ARGS_ASSERT_WARNER;
2029 va_start(args, pat);
2030 vwarner(err, pat, &args);
2035 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
2038 PERL_ARGS_ASSERT_VWARNER;
2040 (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) &&
2041 !(PL_in_eval & EVAL_KEEPERR)
2043 SV * const msv = vmess(pat, args);
2045 if (PL_parser && PL_parser->error_count) {
2049 invoke_exception_hook(msv, FALSE);
2054 Perl_vwarn(aTHX_ pat, args);
2058 /* implements the ckWARN? macros */
2061 Perl_ckwarn(pTHX_ U32 w)
2063 /* If lexical warnings have not been set, use $^W. */
2065 return PL_dowarn & G_WARN_ON;
2067 return ckwarn_common(w);
2070 /* implements the ckWARN?_d macro */
2073 Perl_ckwarn_d(pTHX_ U32 w)
2075 /* If lexical warnings have not been set then default classes warn. */
2079 return ckwarn_common(w);
2083 S_ckwarn_common(pTHX_ U32 w)
2085 if (PL_curcop->cop_warnings == pWARN_ALL)
2088 if (PL_curcop->cop_warnings == pWARN_NONE)
2091 /* Check the assumption that at least the first slot is non-zero. */
2092 assert(unpackWARN1(w));
2094 /* Check the assumption that it is valid to stop as soon as a zero slot is
2096 if (!unpackWARN2(w)) {
2097 assert(!unpackWARN3(w));
2098 assert(!unpackWARN4(w));
2099 } else if (!unpackWARN3(w)) {
2100 assert(!unpackWARN4(w));
2103 /* Right, dealt with all the special cases, which are implemented as non-
2104 pointers, so there is a pointer to a real warnings mask. */
2106 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
2108 } while (w >>= WARNshift);
2113 /* Set buffer=NULL to get a new one. */
2115 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
2117 const MEM_SIZE len_wanted =
2118 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
2119 PERL_UNUSED_CONTEXT;
2120 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
2123 (specialWARN(buffer) ?
2124 PerlMemShared_malloc(len_wanted) :
2125 PerlMemShared_realloc(buffer, len_wanted));
2127 Copy(bits, (buffer + 1), size, char);
2128 if (size < WARNsize)
2129 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
2133 /* since we've already done strlen() for both nam and val
2134 * we can use that info to make things faster than
2135 * sprintf(s, "%s=%s", nam, val)
2137 #define my_setenv_format(s, nam, nlen, val, vlen) \
2138 Copy(nam, s, nlen, char); \
2140 Copy(val, s+(nlen+1), vlen, char); \
2141 *(s+(nlen+1+vlen)) = '\0'
2143 #ifdef USE_ENVIRON_ARRAY
2144 /* VMS' my_setenv() is in vms.c */
2145 #if !defined(WIN32) && !defined(NETWARE)
2147 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2151 amigaos4_obtain_environ(__FUNCTION__);
2154 /* only parent thread can modify process environment */
2155 if (PL_curinterp == aTHX)
2158 #ifndef PERL_USE_SAFE_PUTENV
2159 if (!PL_use_safe_putenv) {
2160 /* most putenv()s leak, so we manipulate environ directly */
2162 const I32 len = strlen(nam);
2165 /* where does it go? */
2166 for (i = 0; environ[i]; i++) {
2167 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
2171 if (environ == PL_origenviron) { /* need we copy environment? */
2177 while (environ[max])
2179 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2180 for (j=0; j<max; j++) { /* copy environment */
2181 const int len = strlen(environ[j]);
2182 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2183 Copy(environ[j], tmpenv[j], len+1, char);
2186 environ = tmpenv; /* tell exec where it is now */
2189 safesysfree(environ[i]);
2190 while (environ[i]) {
2191 environ[i] = environ[i+1];
2200 if (!environ[i]) { /* does not exist yet */
2201 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2202 environ[i+1] = NULL; /* make sure it's null terminated */
2205 safesysfree(environ[i]);
2209 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2210 /* all that work just for this */
2211 my_setenv_format(environ[i], nam, nlen, val, vlen);
2214 /* This next branch should only be called #if defined(HAS_SETENV), but
2215 Configure doesn't test for that yet. For Solaris, setenv() and unsetenv()
2216 were introduced in Solaris 9, so testing for HAS UNSETENV is sufficient.
2218 # if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__) || (defined(__sun) && defined(HAS_UNSETENV)) || defined(PERL_DARWIN)
2219 # if defined(HAS_UNSETENV)
2221 (void)unsetenv(nam);
2223 (void)setenv(nam, val, 1);
2225 # else /* ! HAS_UNSETENV */
2226 (void)setenv(nam, val, 1);
2227 # endif /* HAS_UNSETENV */
2229 # if defined(HAS_UNSETENV)
2231 if (environ) /* old glibc can crash with null environ */
2232 (void)unsetenv(nam);
2234 const int nlen = strlen(nam);
2235 const int vlen = strlen(val);
2236 char * const new_env =
2237 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2238 my_setenv_format(new_env, nam, nlen, val, vlen);
2239 (void)putenv(new_env);
2241 # else /* ! HAS_UNSETENV */
2243 const int nlen = strlen(nam);
2249 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2250 /* all that work just for this */
2251 my_setenv_format(new_env, nam, nlen, val, vlen);
2252 (void)putenv(new_env);
2253 # endif /* HAS_UNSETENV */
2254 # endif /* __CYGWIN__ */
2255 #ifndef PERL_USE_SAFE_PUTENV
2261 amigaos4_release_environ(__FUNCTION__);
2265 #else /* WIN32 || NETWARE */
2268 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2272 const int nlen = strlen(nam);
2279 Newx(envstr, nlen+vlen+2, char);
2280 my_setenv_format(envstr, nam, nlen, val, vlen);
2281 (void)PerlEnv_putenv(envstr);
2285 #endif /* WIN32 || NETWARE */
2289 #ifdef UNLINK_ALL_VERSIONS
2291 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2295 PERL_ARGS_ASSERT_UNLNK;
2297 while (PerlLIO_unlink(f) >= 0)
2299 return retries ? 0 : -1;
2303 /* this is a drop-in replacement for bcopy(), except for the return
2304 * value, which we need to be able to emulate memcpy() */
2305 #if !defined(HAS_MEMCPY) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY))
2307 Perl_my_bcopy(const void *vfrom, void *vto, size_t len)
2309 #if defined(HAS_BCOPY) && defined(HAS_SAFE_BCOPY)
2310 bcopy(vfrom, vto, len);
2312 const unsigned char *from = (const unsigned char *)vfrom;
2313 unsigned char *to = (unsigned char *)vto;
2315 PERL_ARGS_ASSERT_MY_BCOPY;
2317 if (from - to >= 0) {
2325 *(--to) = *(--from);
2333 /* this is a drop-in replacement for memset() */
2336 Perl_my_memset(void *vloc, int ch, size_t len)
2338 unsigned char *loc = (unsigned char *)vloc;
2340 PERL_ARGS_ASSERT_MY_MEMSET;
2348 /* this is a drop-in replacement for bzero() */
2349 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2351 Perl_my_bzero(void *vloc, size_t len)
2353 unsigned char *loc = (unsigned char *)vloc;
2355 PERL_ARGS_ASSERT_MY_BZERO;
2363 /* this is a drop-in replacement for memcmp() */
2364 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2366 Perl_my_memcmp(const void *vs1, const void *vs2, size_t len)
2368 const U8 *a = (const U8 *)vs1;
2369 const U8 *b = (const U8 *)vs2;
2372 PERL_ARGS_ASSERT_MY_MEMCMP;
2375 if ((tmp = *a++ - *b++))
2380 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2383 /* This vsprintf replacement should generally never get used, since
2384 vsprintf was available in both System V and BSD 2.11. (There may
2385 be some cross-compilation or embedded set-ups where it is needed,
2388 If you encounter a problem in this function, it's probably a symptom
2389 that Configure failed to detect your system's vprintf() function.
2390 See the section on "item vsprintf" in the INSTALL file.
2392 This version may compile on systems with BSD-ish <stdio.h>,
2393 but probably won't on others.
2396 #ifdef USE_CHAR_VSPRINTF
2401 vsprintf(char *dest, const char *pat, void *args)
2405 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2406 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2407 FILE_cnt(&fakebuf) = 32767;
2409 /* These probably won't compile -- If you really need
2410 this, you'll have to figure out some other method. */
2411 fakebuf._ptr = dest;
2412 fakebuf._cnt = 32767;
2417 fakebuf._flag = _IOWRT|_IOSTRG;
2418 _doprnt(pat, args, &fakebuf); /* what a kludge */
2419 #if defined(STDIO_PTR_LVALUE)
2420 *(FILE_ptr(&fakebuf)++) = '\0';
2422 /* PerlIO has probably #defined away fputc, but we want it here. */
2424 # undef fputc /* XXX Should really restore it later */
2426 (void)fputc('\0', &fakebuf);
2428 #ifdef USE_CHAR_VSPRINTF
2431 return 0; /* perl doesn't use return value */
2435 #endif /* HAS_VPRINTF */
2438 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2440 #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
2448 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2450 PERL_FLUSHALL_FOR_CHILD;
2451 This = (*mode == 'w');
2455 taint_proper("Insecure %s%s", "EXEC");
2457 if (PerlProc_pipe(p) < 0)
2459 /* Try for another pipe pair for error return */
2460 if (PerlProc_pipe(pp) >= 0)
2462 while ((pid = PerlProc_fork()) < 0) {
2463 if (errno != EAGAIN) {
2464 PerlLIO_close(p[This]);
2465 PerlLIO_close(p[that]);
2467 PerlLIO_close(pp[0]);
2468 PerlLIO_close(pp[1]);
2472 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2481 /* Close parent's end of error status pipe (if any) */
2483 PerlLIO_close(pp[0]);
2484 #if defined(HAS_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
2485 /* Close error pipe automatically if exec works */
2486 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2490 /* Now dup our end of _the_ pipe to right position */
2491 if (p[THIS] != (*mode == 'r')) {
2492 PerlLIO_dup2(p[THIS], *mode == 'r');
2493 PerlLIO_close(p[THIS]);
2494 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2495 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2498 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2499 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2500 /* No automatic close - do it by hand */
2507 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2513 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2519 do_execfree(); /* free any memory malloced by child on fork */
2521 PerlLIO_close(pp[1]);
2522 /* Keep the lower of the two fd numbers */
2523 if (p[that] < p[This]) {
2524 PerlLIO_dup2(p[This], p[that]);
2525 PerlLIO_close(p[This]);
2529 PerlLIO_close(p[that]); /* close child's end of pipe */
2531 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2532 SvUPGRADE(sv,SVt_IV);
2534 PL_forkprocess = pid;
2535 /* If we managed to get status pipe check for exec fail */
2536 if (did_pipes && pid > 0) {
2541 while (n < sizeof(int)) {
2542 n1 = PerlLIO_read(pp[0],
2543 (void*)(((char*)&errkid)+n),
2549 PerlLIO_close(pp[0]);
2551 if (n) { /* Error */
2553 PerlLIO_close(p[This]);
2554 if (n != sizeof(int))
2555 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2557 pid2 = wait4pid(pid, &status, 0);
2558 } while (pid2 == -1 && errno == EINTR);
2559 errno = errkid; /* Propagate errno from kid */
2564 PerlLIO_close(pp[0]);
2565 return PerlIO_fdopen(p[This], mode);
2567 # if defined(OS2) /* Same, without fork()ing and all extra overhead... */
2568 return my_syspopen4(aTHX_ NULL, mode, n, args);
2569 # elif defined(WIN32)
2570 return win32_popenlist(mode, n, args);
2572 Perl_croak(aTHX_ "List form of piped open not implemented");
2573 return (PerlIO *) NULL;
2578 /* VMS' my_popen() is in VMS.c, same with OS/2 and AmigaOS 4. */
2579 #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
2581 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2587 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2591 PERL_ARGS_ASSERT_MY_POPEN;
2593 PERL_FLUSHALL_FOR_CHILD;
2596 return my_syspopen(aTHX_ cmd,mode);
2599 This = (*mode == 'w');
2601 if (doexec && TAINTING_get) {
2603 taint_proper("Insecure %s%s", "EXEC");
2605 if (PerlProc_pipe(p) < 0)
2607 if (doexec && PerlProc_pipe(pp) >= 0)
2609 while ((pid = PerlProc_fork()) < 0) {
2610 if (errno != EAGAIN) {
2611 PerlLIO_close(p[This]);
2612 PerlLIO_close(p[that]);
2614 PerlLIO_close(pp[0]);
2615 PerlLIO_close(pp[1]);
2618 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2621 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2631 PerlLIO_close(pp[0]);
2632 #if defined(HAS_FCNTL) && defined(F_SETFD)
2633 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2637 if (p[THIS] != (*mode == 'r')) {
2638 PerlLIO_dup2(p[THIS], *mode == 'r');
2639 PerlLIO_close(p[THIS]);
2640 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2641 PerlLIO_close(p[THAT]);
2644 PerlLIO_close(p[THAT]);
2647 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2654 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2659 /* may or may not use the shell */
2660 do_exec3(cmd, pp[1], did_pipes);
2663 #endif /* defined OS2 */
2665 #ifdef PERLIO_USING_CRLF
2666 /* Since we circumvent IO layers when we manipulate low-level
2667 filedescriptors directly, need to manually switch to the
2668 default, binary, low-level mode; see PerlIOBuf_open(). */
2669 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2672 #ifdef PERL_USES_PL_PIDSTATUS
2673 hv_clear(PL_pidstatus); /* we have no children */
2679 do_execfree(); /* free any memory malloced by child on vfork */
2681 PerlLIO_close(pp[1]);
2682 if (p[that] < p[This]) {
2683 PerlLIO_dup2(p[This], p[that]);
2684 PerlLIO_close(p[This]);
2688 PerlLIO_close(p[that]);
2690 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2691 SvUPGRADE(sv,SVt_IV);
2693 PL_forkprocess = pid;
2694 if (did_pipes && pid > 0) {
2699 while (n < sizeof(int)) {
2700 n1 = PerlLIO_read(pp[0],
2701 (void*)(((char*)&errkid)+n),
2707 PerlLIO_close(pp[0]);
2709 if (n) { /* Error */
2711 PerlLIO_close(p[This]);
2712 if (n != sizeof(int))
2713 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2715 pid2 = wait4pid(pid, &status, 0);
2716 } while (pid2 == -1 && errno == EINTR);
2717 errno = errkid; /* Propagate errno from kid */
2722 PerlLIO_close(pp[0]);
2723 return PerlIO_fdopen(p[This], mode);
2727 FILE *djgpp_popen();
2729 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2731 PERL_FLUSHALL_FOR_CHILD;
2732 /* Call system's popen() to get a FILE *, then import it.
2733 used 0 for 2nd parameter to PerlIO_importFILE;
2736 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2739 #if defined(__LIBCATAMOUNT__)
2741 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2748 #endif /* !DOSISH */
2750 /* this is called in parent before the fork() */
2752 Perl_atfork_lock(void)
2753 #if defined(USE_ITHREADS)
2755 PERL_TSA_ACQUIRE(PL_perlio_mutex)
2758 PERL_TSA_ACQUIRE(PL_malloc_mutex)
2760 PERL_TSA_ACQUIRE(PL_op_mutex)
2763 #if defined(USE_ITHREADS)
2765 /* locks must be held in locking order (if any) */
2767 MUTEX_LOCK(&PL_perlio_mutex);
2770 MUTEX_LOCK(&PL_malloc_mutex);
2776 /* this is called in both parent and child after the fork() */
2778 Perl_atfork_unlock(void)
2779 #if defined(USE_ITHREADS)
2781 PERL_TSA_RELEASE(PL_perlio_mutex)
2784 PERL_TSA_RELEASE(PL_malloc_mutex)
2786 PERL_TSA_RELEASE(PL_op_mutex)
2789 #if defined(USE_ITHREADS)
2791 /* locks must be released in same order as in atfork_lock() */
2793 MUTEX_UNLOCK(&PL_perlio_mutex);
2796 MUTEX_UNLOCK(&PL_malloc_mutex);
2805 #if defined(HAS_FORK)
2807 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2812 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2813 * handlers elsewhere in the code */
2817 #elif defined(__amigaos4__)
2818 return amigaos_fork();
2820 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2821 Perl_croak_nocontext("fork() not available");
2823 #endif /* HAS_FORK */
2828 dup2(int oldfd, int newfd)
2830 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2833 PerlLIO_close(newfd);
2834 return fcntl(oldfd, F_DUPFD, newfd);
2836 #define DUP2_MAX_FDS 256
2837 int fdtmp[DUP2_MAX_FDS];
2843 PerlLIO_close(newfd);
2844 /* good enough for low fd's... */
2845 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2846 if (fdx >= DUP2_MAX_FDS) {
2854 PerlLIO_close(fdtmp[--fdx]);
2861 #ifdef HAS_SIGACTION
2864 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2866 struct sigaction act, oact;
2870 /* only "parent" interpreter can diddle signals */
2871 if (PL_curinterp != aTHX)
2872 return (Sighandler_t) SIG_ERR;
2875 act.sa_handler = (void(*)(int))handler;
2876 sigemptyset(&act.sa_mask);
2879 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2880 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2882 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2883 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2884 act.sa_flags |= SA_NOCLDWAIT;
2886 if (sigaction(signo, &act, &oact) == -1)
2887 return (Sighandler_t) SIG_ERR;
2889 return (Sighandler_t) oact.sa_handler;
2893 Perl_rsignal_state(pTHX_ int signo)
2895 struct sigaction oact;
2896 PERL_UNUSED_CONTEXT;
2898 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2899 return (Sighandler_t) SIG_ERR;
2901 return (Sighandler_t) oact.sa_handler;
2905 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2910 struct sigaction act;
2912 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2915 /* only "parent" interpreter can diddle signals */
2916 if (PL_curinterp != aTHX)
2920 act.sa_handler = (void(*)(int))handler;
2921 sigemptyset(&act.sa_mask);
2924 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2925 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2927 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2928 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2929 act.sa_flags |= SA_NOCLDWAIT;
2931 return sigaction(signo, &act, save);
2935 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2940 PERL_UNUSED_CONTEXT;
2942 /* only "parent" interpreter can diddle signals */
2943 if (PL_curinterp != aTHX)
2947 return sigaction(signo, save, (struct sigaction *)NULL);
2950 #else /* !HAS_SIGACTION */
2953 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2955 #if defined(USE_ITHREADS) && !defined(WIN32)
2956 /* only "parent" interpreter can diddle signals */
2957 if (PL_curinterp != aTHX)
2958 return (Sighandler_t) SIG_ERR;
2961 return PerlProc_signal(signo, handler);
2972 Perl_rsignal_state(pTHX_ int signo)
2975 Sighandler_t oldsig;
2977 #if defined(USE_ITHREADS) && !defined(WIN32)
2978 /* only "parent" interpreter can diddle signals */
2979 if (PL_curinterp != aTHX)
2980 return (Sighandler_t) SIG_ERR;
2984 oldsig = PerlProc_signal(signo, sig_trap);
2985 PerlProc_signal(signo, oldsig);
2987 PerlProc_kill(PerlProc_getpid(), signo);
2992 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2994 #if defined(USE_ITHREADS) && !defined(WIN32)
2995 /* only "parent" interpreter can diddle signals */
2996 if (PL_curinterp != aTHX)
2999 *save = PerlProc_signal(signo, handler);
3000 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3004 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3006 #if defined(USE_ITHREADS) && !defined(WIN32)
3007 /* only "parent" interpreter can diddle signals */
3008 if (PL_curinterp != aTHX)
3011 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3014 #endif /* !HAS_SIGACTION */
3015 #endif /* !PERL_MICRO */
3017 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3018 #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
3020 Perl_my_pclose(pTHX_ PerlIO *ptr)
3028 const int fd = PerlIO_fileno(ptr);
3031 svp = av_fetch(PL_fdpid,fd,TRUE);
3032 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3036 #if defined(USE_PERLIO)
3037 /* Find out whether the refcount is low enough for us to wait for the
3038 child proc without blocking. */
3039 should_wait = PerlIOUnix_refcnt(fd) == 1 && pid > 0;
3041 should_wait = pid > 0;
3045 if (pid == -1) { /* Opened by popen. */
3046 return my_syspclose(ptr);
3049 close_failed = (PerlIO_close(ptr) == EOF);
3051 if (should_wait) do {
3052 pid2 = wait4pid(pid, &status, 0);
3053 } while (pid2 == -1 && errno == EINTR);
3060 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3065 #if defined(__LIBCATAMOUNT__)
3067 Perl_my_pclose(pTHX_ PerlIO *ptr)
3072 #endif /* !DOSISH */
3074 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3076 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3079 PERL_ARGS_ASSERT_WAIT4PID;
3080 #ifdef PERL_USES_PL_PIDSTATUS
3082 /* PERL_USES_PL_PIDSTATUS is only defined when neither
3083 waitpid() nor wait4() is available, or on OS/2, which
3084 doesn't appear to support waiting for a progress group
3085 member, so we can only treat a 0 pid as an unknown child.
3092 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3093 pid, rather than a string form. */
3094 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3095 if (svp && *svp != &PL_sv_undef) {
3096 *statusp = SvIVX(*svp);
3097 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3105 hv_iterinit(PL_pidstatus);
3106 if ((entry = hv_iternext(PL_pidstatus))) {
3107 SV * const sv = hv_iterval(PL_pidstatus,entry);
3109 const char * const spid = hv_iterkey(entry,&len);
3111 assert (len == sizeof(Pid_t));
3112 memcpy((char *)&pid, spid, len);
3113 *statusp = SvIVX(sv);
3114 /* The hash iterator is currently on this entry, so simply
3115 calling hv_delete would trigger the lazy delete, which on
3116 aggregate does more work, because next call to hv_iterinit()
3117 would spot the flag, and have to call the delete routine,
3118 while in the meantime any new entries can't re-use that
3120 hv_iterinit(PL_pidstatus);
3121 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3128 # ifdef HAS_WAITPID_RUNTIME
3129 if (!HAS_WAITPID_RUNTIME)
3132 result = PerlProc_waitpid(pid,statusp,flags);
3135 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3136 result = wait4(pid,statusp,flags,NULL);
3139 #ifdef PERL_USES_PL_PIDSTATUS
3140 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3145 Perl_croak(aTHX_ "Can't do waitpid with flags");
3147 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3148 pidgone(result,*statusp);
3154 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3157 if (result < 0 && errno == EINTR) {
3159 errno = EINTR; /* reset in case a signal handler changed $! */
3163 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3165 #ifdef PERL_USES_PL_PIDSTATUS
3167 S_pidgone(pTHX_ Pid_t pid, int status)
3171 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3172 SvUPGRADE(sv,SVt_IV);
3173 SvIV_set(sv, status);
3181 int /* Cannot prototype with I32
3183 my_syspclose(PerlIO *ptr)
3186 Perl_my_pclose(pTHX_ PerlIO *ptr)
3189 /* Needs work for PerlIO ! */
3190 FILE * const f = PerlIO_findFILE(ptr);
3191 const I32 result = pclose(f);
3192 PerlIO_releaseFILE(ptr,f);
3200 Perl_my_pclose(pTHX_ PerlIO *ptr)
3202 /* Needs work for PerlIO ! */
3203 FILE * const f = PerlIO_findFILE(ptr);
3204 I32 result = djgpp_pclose(f);
3205 result = (result << 8) & 0xff00;
3206 PerlIO_releaseFILE(ptr,f);
3211 #define PERL_REPEATCPY_LINEAR 4
3213 Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
3215 PERL_ARGS_ASSERT_REPEATCPY;
3220 croak_memory_wrap();
3223 memset(to, *from, count);
3226 IV items, linear, half;
3228 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3229 for (items = 0; items < linear; ++items) {
3230 const char *q = from;
3232 for (todo = len; todo > 0; todo--)
3237 while (items <= half) {
3238 IV size = items * len;
3239 memcpy(p, to, size);
3245 memcpy(p, to, (count - items) * len);
3251 Perl_same_dirent(pTHX_ const char *a, const char *b)
3253 char *fa = strrchr(a,'/');
3254 char *fb = strrchr(b,'/');
3257 SV * const tmpsv = sv_newmortal();
3259 PERL_ARGS_ASSERT_SAME_DIRENT;
3272 sv_setpvs(tmpsv, ".");
3274 sv_setpvn(tmpsv, a, fa - a);
3275 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3278 sv_setpvs(tmpsv, ".");
3280 sv_setpvn(tmpsv, b, fb - b);
3281 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3283 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3284 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3286 #endif /* !HAS_RENAME */
3289 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3290 const char *const *const search_ext, I32 flags)
3292 const char *xfound = NULL;
3293 char *xfailed = NULL;
3294 char tmpbuf[MAXPATHLEN];
3299 #if defined(DOSISH) && !defined(OS2)
3300 # define SEARCH_EXTS ".bat", ".cmd", NULL
3301 # define MAX_EXT_LEN 4
3304 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3305 # define MAX_EXT_LEN 4
3308 # define SEARCH_EXTS ".pl", ".com", NULL
3309 # define MAX_EXT_LEN 4
3311 /* additional extensions to try in each dir if scriptname not found */
3313 static const char *const exts[] = { SEARCH_EXTS };
3314 const char *const *const ext = search_ext ? search_ext : exts;
3315 int extidx = 0, i = 0;
3316 const char *curext = NULL;
3318 PERL_UNUSED_ARG(search_ext);
3319 # define MAX_EXT_LEN 0
3322 PERL_ARGS_ASSERT_FIND_SCRIPT;
3325 * If dosearch is true and if scriptname does not contain path
3326 * delimiters, search the PATH for scriptname.
3328 * If SEARCH_EXTS is also defined, will look for each
3329 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3330 * while searching the PATH.
3332 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3333 * proceeds as follows:
3334 * If DOSISH or VMSISH:
3335 * + look for ./scriptname{,.foo,.bar}
3336 * + search the PATH for scriptname{,.foo,.bar}
3339 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3340 * this will not look in '.' if it's not in the PATH)
3345 # ifdef ALWAYS_DEFTYPES
3346 len = strlen(scriptname);
3347 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3348 int idx = 0, deftypes = 1;
3351 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3354 int idx = 0, deftypes = 1;
3357 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3359 /* The first time through, just add SEARCH_EXTS to whatever we
3360 * already have, so we can check for default file types. */
3362 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3369 if ((strlen(tmpbuf) + strlen(scriptname)
3370 + MAX_EXT_LEN) >= sizeof tmpbuf)
3371 continue; /* don't search dir with too-long name */
3372 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3376 if (strEQ(scriptname, "-"))
3378 if (dosearch) { /* Look in '.' first. */
3379 const char *cur = scriptname;
3381 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3383 if (strEQ(ext[i++],curext)) {
3384 extidx = -1; /* already has an ext */
3389 DEBUG_p(PerlIO_printf(Perl_debug_log,
3390 "Looking for %s\n",cur));
3393 if (PerlLIO_stat(cur,&statbuf) >= 0
3394 && !S_ISDIR(statbuf.st_mode)) {
3403 if (cur == scriptname) {
3404 len = strlen(scriptname);
3405 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3407 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3410 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3411 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3416 if (dosearch && !strchr(scriptname, '/')
3418 && !strchr(scriptname, '\\')
3420 && (s = PerlEnv_getenv("PATH")))
3424 bufend = s + strlen(s);
3425 while (s < bufend) {
3429 && *s != ';'; len++, s++) {
3430 if (len < sizeof tmpbuf)
3433 if (len < sizeof tmpbuf)
3436 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3442 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3443 continue; /* don't search dir with too-long name */
3446 && tmpbuf[len - 1] != '/'
3447 && tmpbuf[len - 1] != '\\'
3450 tmpbuf[len++] = '/';
3451 if (len == 2 && tmpbuf[0] == '.')
3453 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3457 len = strlen(tmpbuf);
3458 if (extidx > 0) /* reset after previous loop */
3462 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3463 retval = PerlLIO_stat(tmpbuf,&statbuf);
3464 if (S_ISDIR(statbuf.st_mode)) {
3468 } while ( retval < 0 /* not there */
3469 && extidx>=0 && ext[extidx] /* try an extension? */
3470 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3475 if (S_ISREG(statbuf.st_mode)
3476 && cando(S_IRUSR,TRUE,&statbuf)
3477 #if !defined(DOSISH)
3478 && cando(S_IXUSR,TRUE,&statbuf)
3482 xfound = tmpbuf; /* bingo! */
3486 xfailed = savepv(tmpbuf);
3491 if (!xfound && !seen_dot && !xfailed &&
3492 (PerlLIO_stat(scriptname,&statbuf) < 0
3493 || S_ISDIR(statbuf.st_mode)))
3495 seen_dot = 1; /* Disable message. */
3500 if (flags & 1) { /* do or die? */
3501 /* diag_listed_as: Can't execute %s */
3502 Perl_croak(aTHX_ "Can't %s %s%s%s",
3503 (xfailed ? "execute" : "find"),
3504 (xfailed ? xfailed : scriptname),
3505 (xfailed ? "" : " on PATH"),
3506 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3511 scriptname = xfound;
3513 return (scriptname ? savepv(scriptname) : NULL);
3516 #ifndef PERL_GET_CONTEXT_DEFINED
3519 Perl_get_context(void)
3521 #if defined(USE_ITHREADS)
3523 # ifdef OLD_PTHREADS_API
3525 int error = pthread_getspecific(PL_thr_key, &t)
3527 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3530 # ifdef I_MACH_CTHREADS
3531 return (void*)cthread_data(cthread_self());
3533 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3542 Perl_set_context(void *t)
3544 #if defined(USE_ITHREADS)
3547 PERL_ARGS_ASSERT_SET_CONTEXT;
3548 #if defined(USE_ITHREADS)
3549 # ifdef I_MACH_CTHREADS
3550 cthread_set_data(cthread_self(), t);
3553 const int error = pthread_setspecific(PL_thr_key, t);
3555 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3563 #endif /* !PERL_GET_CONTEXT_DEFINED */
3565 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3569 PERL_UNUSED_CONTEXT;
3575 Perl_get_op_names(pTHX)
3577 PERL_UNUSED_CONTEXT;
3578 return (char **)PL_op_name;
3582 Perl_get_op_descs(pTHX)
3584 PERL_UNUSED_CONTEXT;
3585 return (char **)PL_op_desc;
3589 Perl_get_no_modify(pTHX)
3591 PERL_UNUSED_CONTEXT;
3592 return PL_no_modify;
3596 Perl_get_opargs(pTHX)
3598 PERL_UNUSED_CONTEXT;
3599 return (U32 *)PL_opargs;
3603 Perl_get_ppaddr(pTHX)
3606 PERL_UNUSED_CONTEXT;
3607 return (PPADDR_t*)PL_ppaddr;
3610 #ifndef HAS_GETENV_LEN
3612 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3614 char * const env_trans = PerlEnv_getenv(env_elem);
3615 PERL_UNUSED_CONTEXT;
3616 PERL_ARGS_ASSERT_GETENV_LEN;
3618 *len = strlen(env_trans);
3625 Perl_get_vtbl(pTHX_ int vtbl_id)
3627 PERL_UNUSED_CONTEXT;
3629 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3630 ? NULL : (MGVTBL*)PL_magic_vtables + vtbl_id;
3634 Perl_my_fflush_all(pTHX)
3636 #if defined(USE_PERLIO) || defined(FFLUSH_NULL)
3637 return PerlIO_flush(NULL);
3639 # if defined(HAS__FWALK)
3640 extern int fflush(FILE *);
3641 /* undocumented, unprototyped, but very useful BSDism */
3642 extern void _fwalk(int (*)(FILE *));
3646 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3648 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3649 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3651 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3652 open_max = sysconf(_SC_OPEN_MAX);
3655 open_max = FOPEN_MAX;
3658 open_max = OPEN_MAX;
3669 for (i = 0; i < open_max; i++)
3670 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3671 STDIO_STREAM_ARRAY[i]._file < open_max &&
3672 STDIO_STREAM_ARRAY[i]._flag)
3673 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3677 SETERRNO(EBADF,RMS_IFI);
3684 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3686 if (ckWARN(WARN_IO)) {
3688 = gv && (isGV_with_GP(gv))
3691 const char * const direction = have == '>' ? "out" : "in";
3693 if (name && HEK_LEN(name))
3694 Perl_warner(aTHX_ packWARN(WARN_IO),
3695 "Filehandle %"HEKf" opened only for %sput",
3696 HEKfARG(name), direction);
3698 Perl_warner(aTHX_ packWARN(WARN_IO),
3699 "Filehandle opened only for %sput", direction);
3704 Perl_report_evil_fh(pTHX_ const GV *gv)
3706 const IO *io = gv ? GvIO(gv) : NULL;
3707 const PERL_BITFIELD16 op = PL_op->op_type;
3711 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3713 warn_type = WARN_CLOSED;
3717 warn_type = WARN_UNOPENED;
3720 if (ckWARN(warn_type)) {
3722 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3723 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3724 const char * const pars =
3725 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3726 const char * const func =
3728 (op == OP_READLINE || op == OP_RCATLINE
3729 ? "readline" : /* "<HANDLE>" not nice */
3730 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3732 const char * const type =
3734 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3735 ? "socket" : "filehandle");
3736 const bool have_name = name && SvCUR(name);
3737 Perl_warner(aTHX_ packWARN(warn_type),
3738 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3739 have_name ? " " : "",
3740 SVfARG(have_name ? name : &PL_sv_no));
3741 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3743 aTHX_ packWARN(warn_type),
3744 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3745 func, pars, have_name ? " " : "",
3746 SVfARG(have_name ? name : &PL_sv_no)
3751 /* To workaround core dumps from the uninitialised tm_zone we get the
3752 * system to give us a reasonable struct to copy. This fix means that
3753 * strftime uses the tm_zone and tm_gmtoff values returned by
3754 * localtime(time()). That should give the desired result most of the
3755 * time. But probably not always!
3757 * This does not address tzname aspects of NETaa14816.
3762 # ifndef STRUCT_TM_HASZONE
3763 # define STRUCT_TM_HASZONE
3767 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3768 # ifndef HAS_TM_TM_ZONE
3769 # define HAS_TM_TM_ZONE
3774 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3776 #ifdef HAS_TM_TM_ZONE
3778 const struct tm* my_tm;
3779 PERL_UNUSED_CONTEXT;
3780 PERL_ARGS_ASSERT_INIT_TM;
3782 my_tm = localtime(&now);
3784 Copy(my_tm, ptm, 1, struct tm);
3786 PERL_UNUSED_CONTEXT;
3787 PERL_ARGS_ASSERT_INIT_TM;
3788 PERL_UNUSED_ARG(ptm);
3793 * mini_mktime - normalise struct tm values without the localtime()
3794 * semantics (and overhead) of mktime().
3797 Perl_mini_mktime(struct tm *ptm)
3801 int month, mday, year, jday;
3802 int odd_cent, odd_year;
3804 PERL_ARGS_ASSERT_MINI_MKTIME;
3806 #define DAYS_PER_YEAR 365
3807 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3808 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3809 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3810 #define SECS_PER_HOUR (60*60)
3811 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3812 /* parentheses deliberately absent on these two, otherwise they don't work */
3813 #define MONTH_TO_DAYS 153/5
3814 #define DAYS_TO_MONTH 5/153
3815 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3816 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3817 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3818 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3821 * Year/day algorithm notes:
3823 * With a suitable offset for numeric value of the month, one can find
3824 * an offset into the year by considering months to have 30.6 (153/5) days,
3825 * using integer arithmetic (i.e., with truncation). To avoid too much
3826 * messing about with leap days, we consider January and February to be
3827 * the 13th and 14th month of the previous year. After that transformation,
3828 * we need the month index we use to be high by 1 from 'normal human' usage,
3829 * so the month index values we use run from 4 through 15.
3831 * Given that, and the rules for the Gregorian calendar (leap years are those
3832 * divisible by 4 unless also divisible by 100, when they must be divisible
3833 * by 400 instead), we can simply calculate the number of days since some
3834 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3835 * the days we derive from our month index, and adding in the day of the
3836 * month. The value used here is not adjusted for the actual origin which
3837 * it normally would use (1 January A.D. 1), since we're not exposing it.
3838 * We're only building the value so we can turn around and get the
3839 * normalised values for the year, month, day-of-month, and day-of-year.
3841 * For going backward, we need to bias the value we're using so that we find
3842 * the right year value. (Basically, we don't want the contribution of
3843 * March 1st to the number to apply while deriving the year). Having done
3844 * that, we 'count up' the contribution to the year number by accounting for
3845 * full quadracenturies (400-year periods) with their extra leap days, plus
3846 * the contribution from full centuries (to avoid counting in the lost leap
3847 * days), plus the contribution from full quad-years (to count in the normal
3848 * leap days), plus the leftover contribution from any non-leap years.
3849 * At this point, if we were working with an actual leap day, we'll have 0
3850 * days left over. This is also true for March 1st, however. So, we have
3851 * to special-case that result, and (earlier) keep track of the 'odd'
3852 * century and year contributions. If we got 4 extra centuries in a qcent,
3853 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3854 * Otherwise, we add back in the earlier bias we removed (the 123 from
3855 * figuring in March 1st), find the month index (integer division by 30.6),
3856 * and the remainder is the day-of-month. We then have to convert back to
3857 * 'real' months (including fixing January and February from being 14/15 in
3858 * the previous year to being in the proper year). After that, to get
3859 * tm_yday, we work with the normalised year and get a new yearday value for
3860 * January 1st, which we subtract from the yearday value we had earlier,
3861 * representing the date we've re-built. This is done from January 1
3862 * because tm_yday is 0-origin.
3864 * Since POSIX time routines are only guaranteed to work for times since the
3865 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3866 * applies Gregorian calendar rules even to dates before the 16th century
3867 * doesn't bother me. Besides, you'd need cultural context for a given
3868 * date to know whether it was Julian or Gregorian calendar, and that's
3869 * outside the scope for this routine. Since we convert back based on the
3870 * same rules we used to build the yearday, you'll only get strange results
3871 * for input which needed normalising, or for the 'odd' century years which
3872 * were leap years in the Julian calendar but not in the Gregorian one.
3873 * I can live with that.
3875 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3876 * that's still outside the scope for POSIX time manipulation, so I don't
3880 year = 1900 + ptm->tm_year;
3881 month = ptm->tm_mon;
3882 mday = ptm->tm_mday;
3888 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3889 yearday += month*MONTH_TO_DAYS + mday + jday;
3891 * Note that we don't know when leap-seconds were or will be,
3892 * so we have to trust the user if we get something which looks
3893 * like a sensible leap-second. Wild values for seconds will
3894 * be rationalised, however.
3896 if ((unsigned) ptm->tm_sec <= 60) {
3903 secs += 60 * ptm->tm_min;
3904 secs += SECS_PER_HOUR * ptm->tm_hour;
3906 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3907 /* got negative remainder, but need positive time */
3908 /* back off an extra day to compensate */
3909 yearday += (secs/SECS_PER_DAY)-1;
3910 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3913 yearday += (secs/SECS_PER_DAY);
3914 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3917 else if (secs >= SECS_PER_DAY) {
3918 yearday += (secs/SECS_PER_DAY);
3919 secs %= SECS_PER_DAY;
3921 ptm->tm_hour = secs/SECS_PER_HOUR;
3922 secs %= SECS_PER_HOUR;
3923 ptm->tm_min = secs/60;
3925 ptm->tm_sec += secs;
3926 /* done with time of day effects */
3928 * The algorithm for yearday has (so far) left it high by 428.
3929 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3930 * bias it by 123 while trying to figure out what year it
3931 * really represents. Even with this tweak, the reverse
3932 * translation fails for years before A.D. 0001.
3933 * It would still fail for Feb 29, but we catch that one below.
3935 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3936 yearday -= YEAR_ADJUST;
3937 year = (yearday / DAYS_PER_QCENT) * 400;
3938 yearday %= DAYS_PER_QCENT;
3939 odd_cent = yearday / DAYS_PER_CENT;
3940 year += odd_cent * 100;
3941 yearday %= DAYS_PER_CENT;
3942 year += (yearday / DAYS_PER_QYEAR) * 4;
3943 yearday %= DAYS_PER_QYEAR;
3944 odd_year = yearday / DAYS_PER_YEAR;
3946 yearday %= DAYS_PER_YEAR;
3947 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3952 yearday += YEAR_ADJUST; /* recover March 1st crock */
3953 month = yearday*DAYS_TO_MONTH;
3954 yearday -= month*MONTH_TO_DAYS;
3955 /* recover other leap-year adjustment */
3964 ptm->tm_year = year - 1900;
3966 ptm->tm_mday = yearday;
3967 ptm->tm_mon = month;
3971 ptm->tm_mon = month - 1;
3973 /* re-build yearday based on Jan 1 to get tm_yday */
3975 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3976 yearday += 14*MONTH_TO_DAYS + 1;
3977 ptm->tm_yday = jday - yearday;
3978 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3982 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)
3986 /* Note that yday and wday effectively are ignored by this function, as mini_mktime() overwrites them */
3993 PERL_ARGS_ASSERT_MY_STRFTIME;
3995 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3998 mytm.tm_hour = hour;
3999 mytm.tm_mday = mday;
4001 mytm.tm_year = year;
4002 mytm.tm_wday = wday;
4003 mytm.tm_yday = yday;
4004 mytm.tm_isdst = isdst;
4006 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4007 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4012 #ifdef HAS_TM_TM_GMTOFF
4013 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4015 #ifdef HAS_TM_TM_ZONE
4016 mytm.tm_zone = mytm2.tm_zone;
4021 Newx(buf, buflen, char);
4023 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
4024 len = strftime(buf, buflen, fmt, &mytm);
4028 ** The following is needed to handle to the situation where
4029 ** tmpbuf overflows. Basically we want to allocate a buffer
4030 ** and try repeatedly. The reason why it is so complicated
4031 ** is that getting a return value of 0 from strftime can indicate
4032 ** one of the following:
4033 ** 1. buffer overflowed,
4034 ** 2. illegal conversion specifier, or
4035 ** 3. the format string specifies nothing to be returned(not
4036 ** an error). This could be because format is an empty string
4037 ** or it specifies %p that yields an empty string in some locale.
4038 ** If there is a better way to make it portable, go ahead by
4041 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4044 /* Possibly buf overflowed - try again with a bigger buf */
4045 const int fmtlen = strlen(fmt);
4046 int bufsize = fmtlen + buflen;
4048 Renew(buf, bufsize, char);
4051 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
4052 buflen = strftime(buf, bufsize, fmt, &mytm);
4055 if (buflen > 0 && buflen < bufsize)
4057 /* heuristic to prevent out-of-memory errors */
4058 if (bufsize > 100*fmtlen) {
4064 Renew(buf, bufsize, char);
4069 Perl_croak(aTHX_ "panic: no strftime");
4075 #define SV_CWD_RETURN_UNDEF \
4076 sv_setsv(sv, &PL_sv_undef); \
4079 #define SV_CWD_ISDOT(dp) \
4080 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4081 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4084 =head1 Miscellaneous Functions
4086 =for apidoc getcwd_sv
4088 Fill C<sv> with current working directory
4093 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4094 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4095 * getcwd(3) if available
4096 * Comments from the original:
4097 * This is a faster version of getcwd. It's also more dangerous
4098 * because you might chdir out of a directory that you can't chdir
4102 Perl_getcwd_sv(pTHX_ SV *sv)
4107 PERL_ARGS_ASSERT_GETCWD_SV;
4111 char buf[MAXPATHLEN];
4113 /* Some getcwd()s automatically allocate a buffer of the given
4114 * size from the heap if they are given a NULL buffer pointer.
4115 * The problem is that this behaviour is not portable. */
4116 if (getcwd(buf, sizeof(buf) - 1)) {
4121 sv_setsv(sv, &PL_sv_undef);
4129 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4133 SvUPGRADE(sv, SVt_PV);
4135 if (PerlLIO_lstat(".", &statbuf) < 0) {
4136 SV_CWD_RETURN_UNDEF;
4139 orig_cdev = statbuf.st_dev;
4140 orig_cino = statbuf.st_ino;
4150 if (PerlDir_chdir("..") < 0) {
4151 SV_CWD_RETURN_UNDEF;
4153 if (PerlLIO_stat(".", &statbuf) < 0) {
4154 SV_CWD_RETURN_UNDEF;
4157 cdev = statbuf.st_dev;
4158 cino = statbuf.st_ino;
4160 if (odev == cdev && oino == cino) {
4163 if (!(dir = PerlDir_open("."))) {
4164 SV_CWD_RETURN_UNDEF;
4167 while ((dp = PerlDir_read(dir)) != NULL) {
4169 namelen = dp->d_namlen;
4171 namelen = strlen(dp->d_name);
4174 if (SV_CWD_ISDOT(dp)) {
4178 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4179 SV_CWD_RETURN_UNDEF;
4182 tdev = statbuf.st_dev;
4183 tino = statbuf.st_ino;
4184 if (tino == oino && tdev == odev) {
4190 SV_CWD_RETURN_UNDEF;
4193 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4194 SV_CWD_RETURN_UNDEF;
4197 SvGROW(sv, pathlen + namelen + 1);
4201 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4204 /* prepend current directory to the front */
4206 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4207 pathlen += (namelen + 1);
4209 #ifdef VOID_CLOSEDIR
4212 if (PerlDir_close(dir) < 0) {
4213 SV_CWD_RETURN_UNDEF;
4219 SvCUR_set(sv, pathlen);
4223 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4224 SV_CWD_RETURN_UNDEF;
4227 if (PerlLIO_stat(".", &statbuf) < 0) {
4228 SV_CWD_RETURN_UNDEF;
4231 cdev = statbuf.st_dev;
4232 cino = statbuf.st_ino;
4234 if (cdev != orig_cdev || cino != orig_cino) {
4235 Perl_croak(aTHX_ "Unstable directory path, "
4236 "current directory changed unexpectedly");
4249 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4250 # define EMULATE_SOCKETPAIR_UDP
4253 #ifdef EMULATE_SOCKETPAIR_UDP
4255 S_socketpair_udp (int fd[2]) {
4257 /* Fake a datagram socketpair using UDP to localhost. */
4258 int sockets[2] = {-1, -1};
4259 struct sockaddr_in addresses[2];
4261 Sock_size_t size = sizeof(struct sockaddr_in);
4262 unsigned short port;
4265 memset(&addresses, 0, sizeof(addresses));
4268 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4269 if (sockets[i] == -1)
4270 goto tidy_up_and_fail;
4272 addresses[i].sin_family = AF_INET;
4273 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4274 addresses[i].sin_port = 0; /* kernel choses port. */
4275 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4276 sizeof(struct sockaddr_in)) == -1)
4277 goto tidy_up_and_fail;
4280 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4281 for each connect the other socket to it. */
4284 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4286 goto tidy_up_and_fail;
4287 if (size != sizeof(struct sockaddr_in))
4288 goto abort_tidy_up_and_fail;
4289 /* !1 is 0, !0 is 1 */
4290 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4291 sizeof(struct sockaddr_in)) == -1)
4292 goto tidy_up_and_fail;
4295 /* Now we have 2 sockets connected to each other. I don't trust some other
4296 process not to have already sent a packet to us (by random) so send
4297 a packet from each to the other. */
4300 /* I'm going to send my own port number. As a short.
4301 (Who knows if someone somewhere has sin_port as a bitfield and needs
4302 this routine. (I'm assuming crays have socketpair)) */
4303 port = addresses[i].sin_port;
4304 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4305 if (got != sizeof(port)) {
4307 goto tidy_up_and_fail;
4308 goto abort_tidy_up_and_fail;
4312 /* Packets sent. I don't trust them to have arrived though.
4313 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4314 connect to localhost will use a second kernel thread. In 2.6 the
4315 first thread running the connect() returns before the second completes,
4316 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4317 returns 0. Poor programs have tripped up. One poor program's authors'
4318 had a 50-1 reverse stock split. Not sure how connected these were.)
4319 So I don't trust someone not to have an unpredictable UDP stack.
4323 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4324 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4328 FD_SET((unsigned int)sockets[0], &rset);
4329 FD_SET((unsigned int)sockets[1], &rset);
4331 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4332 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4333 || !FD_ISSET(sockets[1], &rset)) {
4334 /* I hope this is portable and appropriate. */
4336 goto tidy_up_and_fail;
4337 goto abort_tidy_up_and_fail;
4341 /* And the paranoia department even now doesn't trust it to have arrive
4342 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4344 struct sockaddr_in readfrom;
4345 unsigned short buffer[2];
4350 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4351 sizeof(buffer), MSG_DONTWAIT,
4352 (struct sockaddr *) &readfrom, &size);
4354 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4356 (struct sockaddr *) &readfrom, &size);
4360 goto tidy_up_and_fail;
4361 if (got != sizeof(port)
4362 || size != sizeof(struct sockaddr_in)
4363 /* Check other socket sent us its port. */
4364 || buffer[0] != (unsigned short) addresses[!i].sin_port
4365 /* Check kernel says we got the datagram from that socket */
4366 || readfrom.sin_family != addresses[!i].sin_family
4367 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4368 || readfrom.sin_port != addresses[!i].sin_port)
4369 goto abort_tidy_up_and_fail;
4372 /* My caller (my_socketpair) has validated that this is non-NULL */
4375 /* I hereby declare this connection open. May God bless all who cross
4379 abort_tidy_up_and_fail:
4380 errno = ECONNABORTED;
4384 if (sockets[0] != -1)
4385 PerlLIO_close(sockets[0]);
4386 if (sockets[1] != -1)
4387 PerlLIO_close(sockets[1]);
4392 #endif /* EMULATE_SOCKETPAIR_UDP */
4394 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4396 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4397 /* Stevens says that family must be AF_LOCAL, protocol 0.
4398 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4403 struct sockaddr_in listen_addr;
4404 struct sockaddr_in connect_addr;
4409 || family != AF_UNIX
4412 errno = EAFNOSUPPORT;
4420 #ifdef EMULATE_SOCKETPAIR_UDP
4421 if (type == SOCK_DGRAM)
4422 return S_socketpair_udp(fd);
4425 aTHXa(PERL_GET_THX);
4426 listener = PerlSock_socket(AF_INET, type, 0);
4429 memset(&listen_addr, 0, sizeof(listen_addr));
4430 listen_addr.sin_family = AF_INET;
4431 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4432 listen_addr.sin_port = 0; /* kernel choses port. */
4433 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4434 sizeof(listen_addr)) == -1)
4435 goto tidy_up_and_fail;
4436 if (PerlSock_listen(listener, 1) == -1)
4437 goto tidy_up_and_fail;
4439 connector = PerlSock_socket(AF_INET, type, 0);
4440 if (connector == -1)
4441 goto tidy_up_and_fail;
4442 /* We want to find out the port number to connect to. */
4443 size = sizeof(connect_addr);
4444 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4446 goto tidy_up_and_fail;
4447 if (size != sizeof(connect_addr))
4448 goto abort_tidy_up_and_fail;
4449 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4450 sizeof(connect_addr)) == -1)
4451 goto tidy_up_and_fail;
4453 size = sizeof(listen_addr);
4454 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4457 goto tidy_up_and_fail;
4458 if (size != sizeof(listen_addr))
4459 goto abort_tidy_up_and_fail;
4460 PerlLIO_close(listener);
4461 /* Now check we are talking to ourself by matching port and host on the
4463 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4465 goto tidy_up_and_fail;
4466 if (size != sizeof(connect_addr)
4467 || listen_addr.sin_family != connect_addr.sin_family
4468 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4469 || listen_addr.sin_port != connect_addr.sin_port) {
4470 goto abort_tidy_up_and_fail;
4476 abort_tidy_up_and_fail:
4478 errno = ECONNABORTED; /* This would be the standard thing to do. */
4480 # ifdef ECONNREFUSED
4481 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4483 errno = ETIMEDOUT; /* Desperation time. */
4490 PerlLIO_close(listener);
4491 if (connector != -1)
4492 PerlLIO_close(connector);
4494 PerlLIO_close(acceptor);
4500 /* In any case have a stub so that there's code corresponding
4501 * to the my_socketpair in embed.fnc. */
4503 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4504 #ifdef HAS_SOCKETPAIR
4505 return socketpair(family, type, protocol, fd);
4514 =for apidoc sv_nosharing
4516 Dummy routine which "shares" an SV when there is no sharing module present.
4517 Or "locks" it. Or "unlocks" it. In other
4518 words, ignores its single SV argument.
4519 Exists to avoid test for a C<NULL> function pointer and because it could
4520 potentially warn under some level of strict-ness.
4526 Perl_sv_nosharing(pTHX_ SV *sv)
4528 PERL_UNUSED_CONTEXT;
4529 PERL_UNUSED_ARG(sv);
4534 =for apidoc sv_destroyable
4536 Dummy routine which reports that object can be destroyed when there is no
4537 sharing module present. It ignores its single SV argument, and returns
4538 'true'. Exists to avoid test for a C<NULL> function pointer and because it
4539 could potentially warn under some level of strict-ness.
4545 Perl_sv_destroyable(pTHX_ SV *sv)
4547 PERL_UNUSED_CONTEXT;
4548 PERL_UNUSED_ARG(sv);
4553 Perl_parse_unicode_opts(pTHX_ const char **popt)
4555 const char *p = *popt;
4558 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
4564 if (grok_atoUV(p, &uv, &endptr) && uv <= U32_MAX) {
4567 if (p && *p && *p != '\n' && *p != '\r') {
4569 goto the_end_of_the_opts_parser;
4571 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4575 Perl_croak(aTHX_ "Invalid number '%s' for -C option.\n", p);
4581 case PERL_UNICODE_STDIN:
4582 opt |= PERL_UNICODE_STDIN_FLAG; break;
4583 case PERL_UNICODE_STDOUT:
4584 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4585 case PERL_UNICODE_STDERR:
4586 opt |= PERL_UNICODE_STDERR_FLAG; break;
4587 case PERL_UNICODE_STD:
4588 opt |= PERL_UNICODE_STD_FLAG; break;
4589 case PERL_UNICODE_IN:
4590 opt |= PERL_UNICODE_IN_FLAG; break;
4591 case PERL_UNICODE_OUT:
4592 opt |= PERL_UNICODE_OUT_FLAG; break;
4593 case PERL_UNICODE_INOUT:
4594 opt |= PERL_UNICODE_INOUT_FLAG; break;
4595 case PERL_UNICODE_LOCALE:
4596 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4597 case PERL_UNICODE_ARGV:
4598 opt |= PERL_UNICODE_ARGV_FLAG; break;
4599 case PERL_UNICODE_UTF8CACHEASSERT:
4600 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
4602 if (*p != '\n' && *p != '\r') {
4603 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4606 "Unknown Unicode option letter '%c'", *p);
4613 opt = PERL_UNICODE_DEFAULT_FLAGS;
4615 the_end_of_the_opts_parser:
4617 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4618 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4619 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4627 # include <starlet.h>
4634 * This is really just a quick hack which grabs various garbage
4635 * values. It really should be a real hash algorithm which
4636 * spreads the effect of every input bit onto every output bit,
4637 * if someone who knows about such things would bother to write it.
4638 * Might be a good idea to add that function to CORE as well.
4639 * No numbers below come from careful analysis or anything here,
4640 * except they are primes and SEED_C1 > 1E6 to get a full-width
4641 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4642 * probably be bigger too.
4645 # define SEED_C1 1000003
4646 #define SEED_C4 73819
4648 # define SEED_C1 25747
4649 #define SEED_C4 20639
4653 #define SEED_C5 26107
4655 #ifndef PERL_NO_DEV_RANDOM
4659 #ifdef HAS_GETTIMEOFDAY
4660 struct timeval when;
4665 /* This test is an escape hatch, this symbol isn't set by Configure. */
4666 #ifndef PERL_NO_DEV_RANDOM
4667 #ifndef PERL_RANDOM_DEVICE
4668 /* /dev/random isn't used by default because reads from it will block
4669 * if there isn't enough entropy available. You can compile with
4670 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4671 * is enough real entropy to fill the seed. */
4672 # ifdef __amigaos4__
4673 # define PERL_RANDOM_DEVICE "RANDOM:SIZE=4"
4675 # define PERL_RANDOM_DEVICE "/dev/urandom"
4678 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4680 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4688 #ifdef HAS_GETTIMEOFDAY
4689 PerlProc_gettimeofday(&when,NULL);
4690 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4693 u = (U32)SEED_C1 * when;
4695 u += SEED_C3 * (U32)PerlProc_getpid();
4696 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4697 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4698 u += SEED_C5 * (U32)PTR2UV(&when);
4704 Perl_get_hash_seed(pTHX_ unsigned char * const seed_buffer)
4709 PERL_ARGS_ASSERT_GET_HASH_SEED;
4711 env_pv= PerlEnv_getenv("PERL_HASH_SEED");
4714 #ifndef USE_HASH_SEED_EXPLICIT
4716 /* ignore leading spaces */
4717 while (isSPACE(*env_pv))
4719 #ifdef USE_PERL_PERTURB_KEYS
4720 /* if they set it to "0" we disable key traversal randomization completely */
4721 if (strEQ(env_pv,"0")) {
4722 PL_hash_rand_bits_enabled= 0;
4724 /* otherwise switch to deterministic mode */
4725 PL_hash_rand_bits_enabled= 2;
4728 /* ignore a leading 0x... if it is there */
4729 if (env_pv[0] == '0' && env_pv[1] == 'x')
4732 for( i = 0; isXDIGIT(*env_pv) && i < PERL_HASH_SEED_BYTES; i++ ) {
4733 seed_buffer[i] = READ_XDIGIT(env_pv) << 4;
4734 if ( isXDIGIT(*env_pv)) {
4735 seed_buffer[i] |= READ_XDIGIT(env_pv);
4738 while (isSPACE(*env_pv))
4741 if (*env_pv && !isXDIGIT(*env_pv)) {
4742 Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n");
4744 /* should we check for unparsed crap? */
4745 /* should we warn about unused hex? */
4746 /* should we warn about insufficient hex? */
4751 (void)seedDrand01((Rand_seed_t)seed());
4753 for( i = 0; i < PERL_HASH_SEED_BYTES; i++ ) {
4754 seed_buffer[i] = (unsigned char)(Drand01() * (U8_MAX+1));
4757 #ifdef USE_PERL_PERTURB_KEYS
4758 { /* initialize PL_hash_rand_bits from the hash seed.
4759 * This value is highly volatile, it is updated every
4760 * hash insert, and is used as part of hash bucket chain
4761 * randomization and hash iterator randomization. */
4762 PL_hash_rand_bits= 0xbe49d17f; /* I just picked a number */
4763 for( i = 0; i < sizeof(UV) ; i++ ) {
4764 PL_hash_rand_bits += seed_buffer[i % PERL_HASH_SEED_BYTES];
4765 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,8);
4768 env_pv= PerlEnv_getenv("PERL_PERTURB_KEYS");
4770 if (strEQ(env_pv,"0") || strEQ(env_pv,"NO")) {
4771 PL_hash_rand_bits_enabled= 0;
4772 } else if (strEQ(env_pv,"1") || strEQ(env_pv,"RANDOM")) {
4773 PL_hash_rand_bits_enabled= 1;
4774 } else if (strEQ(env_pv,"2") || strEQ(env_pv,"DETERMINISTIC")) {
4775 PL_hash_rand_bits_enabled= 2;
4777 Perl_warn(aTHX_ "perl: warning: strange setting in '$ENV{PERL_PERTURB_KEYS}': '%s'\n", env_pv);
4783 #ifdef PERL_GLOBAL_STRUCT
4785 #define PERL_GLOBAL_STRUCT_INIT
4786 #include "opcode.h" /* the ppaddr and check */
4789 Perl_init_global_struct(pTHX)
4791 struct perl_vars *plvarsp = NULL;
4792 # ifdef PERL_GLOBAL_STRUCT
4793 const IV nppaddr = C_ARRAY_LENGTH(Gppaddr);
4794 const IV ncheck = C_ARRAY_LENGTH(Gcheck);
4795 PERL_UNUSED_CONTEXT;
4796 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4797 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
4798 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
4802 plvarsp = PL_VarsPtr;
4803 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
4808 # define PERLVAR(prefix,var,type) /**/
4809 # define PERLVARA(prefix,var,n,type) /**/
4810 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
4811 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
4812 # include "perlvars.h"
4817 # ifdef PERL_GLOBAL_STRUCT
4820 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
4821 if (!plvarsp->Gppaddr)
4825 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
4826 if (!plvarsp->Gcheck)
4828 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
4829 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
4831 # ifdef PERL_SET_VARS
4832 PERL_SET_VARS(plvarsp);
4834 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4835 plvarsp->Gsv_placeholder.sv_flags = 0;
4836 memset(plvarsp->Ghash_seed, 0, sizeof(plvarsp->Ghash_seed));
4838 # undef PERL_GLOBAL_STRUCT_INIT
4843 #endif /* PERL_GLOBAL_STRUCT */
4845 #ifdef PERL_GLOBAL_STRUCT
4848 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
4850 int veto = plvarsp->Gveto_cleanup;
4852 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
4853 PERL_UNUSED_CONTEXT;
4854 # ifdef PERL_GLOBAL_STRUCT
4855 # ifdef PERL_UNSET_VARS
4856 PERL_UNSET_VARS(plvarsp);
4860 free(plvarsp->Gppaddr);
4861 free(plvarsp->Gcheck);
4862 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4868 #endif /* PERL_GLOBAL_STRUCT */
4872 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including
4873 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
4874 * given, and you supply your own implementation.
4876 * The default implementation reads a single env var, PERL_MEM_LOG,
4877 * expecting one or more of the following:
4879 * \d+ - fd fd to write to : must be 1st (grok_atoUV)
4880 * 'm' - memlog was PERL_MEM_LOG=1
4881 * 's' - svlog was PERL_SV_LOG=1
4882 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
4884 * This makes the logger controllable enough that it can reasonably be
4885 * added to the system perl.
4888 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
4889 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
4891 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
4893 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
4894 * writes to. In the default logger, this is settable at runtime.
4896 #ifndef PERL_MEM_LOG_FD
4897 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
4900 #ifndef PERL_MEM_LOG_NOIMPL
4902 # ifdef DEBUG_LEAKING_SCALARS
4903 # define SV_LOG_SERIAL_FMT " [%lu]"
4904 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
4906 # define SV_LOG_SERIAL_FMT
4907 # define _SV_LOG_SERIAL_ARG(sv)
4911 S_mem_log_common(enum mem_log_type mlt, const UV n,
4912 const UV typesize, const char *type_name, const SV *sv,
4913 Malloc_t oldalloc, Malloc_t newalloc,
4914 const char *filename, const int linenumber,
4915 const char *funcname)
4919 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
4921 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
4924 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
4926 /* We can't use SVs or PerlIO for obvious reasons,
4927 * so we'll use stdio and low-level IO instead. */
4928 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
4930 # ifdef HAS_GETTIMEOFDAY
4931 # define MEM_LOG_TIME_FMT "%10d.%06d: "
4932 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
4934 gettimeofday(&tv, 0);
4936 # define MEM_LOG_TIME_FMT "%10d: "
4937 # define MEM_LOG_TIME_ARG (int)when
4941 /* If there are other OS specific ways of hires time than
4942 * gettimeofday() (see dist/Time-HiRes), the easiest way is
4943 * probably that they would be used to fill in the struct
4950 if (grok_atoUV(pmlenv, &uv, &endptr) /* Ignore endptr. */
4951 && uv && uv <= PERL_INT_MAX
4955 fd = PERL_MEM_LOG_FD;
4958 if (strchr(pmlenv, 't')) {
4959 len = my_snprintf(buf, sizeof(buf),
4960 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
4961 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
4965 len = my_snprintf(buf, sizeof(buf),
4966 "alloc: %s:%d:%s: %"IVdf" %"UVuf
4967 " %s = %"IVdf": %"UVxf"\n",
4968 filename, linenumber, funcname, n, typesize,
4969 type_name, n * typesize, PTR2UV(newalloc));
4972 len = my_snprintf(buf, sizeof(buf),
4973 "realloc: %s:%d:%s: %"IVdf" %"UVuf
4974 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
4975 filename, linenumber, funcname, n, typesize,
4976 type_name, n * typesize, PTR2UV(oldalloc),
4980 len = my_snprintf(buf, sizeof(buf),
4981 "free: %s:%d:%s: %"UVxf"\n",
4982 filename, linenumber, funcname,
4987 len = my_snprintf(buf, sizeof(buf),
4988 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
4989 mlt == MLT_NEW_SV ? "new" : "del",
4990 filename, linenumber, funcname,
4991 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
4996 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
5000 #endif /* !PERL_MEM_LOG_NOIMPL */
5002 #ifndef PERL_MEM_LOG_NOIMPL
5004 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
5005 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
5007 /* this is suboptimal, but bug compatible. User is providing their
5008 own implementation, but is getting these functions anyway, and they
5009 do nothing. But _NOIMPL users should be able to cope or fix */
5011 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
5012 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
5016 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
5018 const char *filename, const int linenumber,
5019 const char *funcname)
5021 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
5022 NULL, NULL, newalloc,
5023 filename, linenumber, funcname);
5028 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
5029 Malloc_t oldalloc, Malloc_t newalloc,
5030 const char *filename, const int linenumber,
5031 const char *funcname)
5033 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
5034 NULL, oldalloc, newalloc,
5035 filename, linenumber, funcname);
5040 Perl_mem_log_free(Malloc_t oldalloc,
5041 const char *filename, const int linenumber,
5042 const char *funcname)
5044 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
5045 filename, linenumber, funcname);
5050 Perl_mem_log_new_sv(const SV *sv,
5051 const char *filename, const int linenumber,
5052 const char *funcname)
5054 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
5055 filename, linenumber, funcname);
5059 Perl_mem_log_del_sv(const SV *sv,
5060 const char *filename, const int linenumber,
5061 const char *funcname)
5063 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
5064 filename, linenumber, funcname);
5067 #endif /* PERL_MEM_LOG */
5070 =for apidoc my_sprintf
5072 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5073 the length of the string written to the buffer. Only rare pre-ANSI systems
5074 need the wrapper function - usually this is a direct call to C<sprintf>.
5078 #ifndef SPRINTF_RETURNS_STRLEN
5080 Perl_my_sprintf(char *buffer, const char* pat, ...)
5083 PERL_ARGS_ASSERT_MY_SPRINTF;
5084 va_start(args, pat);