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 */
50 # include <sys/select.h>
54 #ifdef USE_C_BACKTRACE
58 # undef USE_BFD /* BFD is useless in OS X. */
68 # include <execinfo.h>
72 #ifdef PERL_DEBUG_READONLY_COW
73 # include <sys/mman.h>
78 /* NOTE: Do not call the next three routines directly. Use the macros
79 * in handy.h, so that we can easily redefine everything to do tracking of
80 * allocated hunks back to the original New to track down any memory leaks.
81 * XXX This advice seems to be widely ignored :-( --AD August 1996.
84 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
85 # define ALWAYS_NEED_THX
88 #if defined(PERL_TRACK_MEMPOOL) && defined(PERL_DEBUG_READONLY_COW)
90 S_maybe_protect_rw(pTHX_ struct perl_memory_debug_header *header)
93 && mprotect(header, header->size, PROT_READ|PROT_WRITE))
94 Perl_warn(aTHX_ "mprotect for COW string %p %lu failed with %d",
95 header, header->size, errno);
99 S_maybe_protect_ro(pTHX_ struct perl_memory_debug_header *header)
102 && mprotect(header, header->size, PROT_READ))
103 Perl_warn(aTHX_ "mprotect RW for COW string %p %lu failed with %d",
104 header, header->size, errno);
106 # define maybe_protect_rw(foo) S_maybe_protect_rw(aTHX_ foo)
107 # define maybe_protect_ro(foo) S_maybe_protect_ro(aTHX_ foo)
109 # define maybe_protect_rw(foo) NOOP
110 # define maybe_protect_ro(foo) NOOP
113 #if defined(PERL_TRACK_MEMPOOL) || defined(PERL_DEBUG_READONLY_COW)
114 /* Use memory_debug_header */
116 # if (defined(PERL_POISON) && defined(PERL_TRACK_MEMPOOL)) \
117 || defined(PERL_DEBUG_READONLY_COW)
118 # define MDH_HAS_SIZE
122 /* paranoid version of system's malloc() */
125 Perl_safesysmalloc(MEM_SIZE size)
127 #ifdef ALWAYS_NEED_THX
131 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
133 if ((SSize_t)size < 0)
134 Perl_croak_nocontext("panic: malloc, size=%"UVuf, (UV) size);
136 if (!size) size = 1; /* malloc(0) is NASTY on our system */
137 #ifdef PERL_DEBUG_READONLY_COW
138 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
139 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
140 perror("mmap failed");
144 ptr = (Malloc_t)PerlMem_malloc(size?size:1);
146 PERL_ALLOC_CHECK(ptr);
149 struct perl_memory_debug_header *const header
150 = (struct perl_memory_debug_header *)ptr;
154 PoisonNew(((char *)ptr), size, char);
157 #ifdef PERL_TRACK_MEMPOOL
158 header->interpreter = aTHX;
159 /* Link us into the list. */
160 header->prev = &PL_memory_debug_header;
161 header->next = PL_memory_debug_header.next;
162 PL_memory_debug_header.next = header;
163 maybe_protect_rw(header->next);
164 header->next->prev = header;
165 maybe_protect_ro(header->next);
166 # ifdef PERL_DEBUG_READONLY_COW
167 header->readonly = 0;
173 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
174 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
178 #ifndef ALWAYS_NEED_THX
190 /* paranoid version of system's realloc() */
193 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
195 #ifdef ALWAYS_NEED_THX
199 #ifdef PERL_DEBUG_READONLY_COW
200 const MEM_SIZE oldsize = where
201 ? ((struct perl_memory_debug_header *)((char *)where - PERL_MEMORY_DEBUG_HEADER_SIZE))->size
204 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
205 Malloc_t PerlMem_realloc();
206 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
214 return safesysmalloc(size);
216 where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
217 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
219 struct perl_memory_debug_header *const header
220 = (struct perl_memory_debug_header *)where;
222 # ifdef PERL_TRACK_MEMPOOL
223 if (header->interpreter != aTHX) {
224 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
225 header->interpreter, aTHX);
227 assert(header->next->prev == header);
228 assert(header->prev->next == header);
230 if (header->size > size) {
231 const MEM_SIZE freed_up = header->size - size;
232 char *start_of_freed = ((char *)where) + size;
233 PoisonFree(start_of_freed, freed_up, char);
243 if ((SSize_t)size < 0)
244 Perl_croak_nocontext("panic: realloc, size=%"UVuf, (UV)size);
246 #ifdef PERL_DEBUG_READONLY_COW
247 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
248 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
249 perror("mmap failed");
252 Copy(where,ptr,oldsize < size ? oldsize : size,char);
253 if (munmap(where, oldsize)) {
254 perror("munmap failed");
258 ptr = (Malloc_t)PerlMem_realloc(where,size);
260 PERL_ALLOC_CHECK(ptr);
262 /* MUST do this fixup first, before doing ANYTHING else, as anything else
263 might allocate memory/free/move memory, and until we do the fixup, it
264 may well be chasing (and writing to) free memory. */
266 #ifdef PERL_TRACK_MEMPOOL
267 struct perl_memory_debug_header *const header
268 = (struct perl_memory_debug_header *)ptr;
271 if (header->size < size) {
272 const MEM_SIZE fresh = size - header->size;
273 char *start_of_fresh = ((char *)ptr) + size;
274 PoisonNew(start_of_fresh, fresh, char);
278 maybe_protect_rw(header->next);
279 header->next->prev = header;
280 maybe_protect_ro(header->next);
281 maybe_protect_rw(header->prev);
282 header->prev->next = header;
283 maybe_protect_ro(header->prev);
285 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
288 /* In particular, must do that fixup above before logging anything via
289 *printf(), as it can reallocate memory, which can cause SEGVs. */
291 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
292 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
299 #ifndef ALWAYS_NEED_THX
311 /* safe version of system's free() */
314 Perl_safesysfree(Malloc_t where)
316 #ifdef ALWAYS_NEED_THX
321 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
324 where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
326 struct perl_memory_debug_header *const header
327 = (struct perl_memory_debug_header *)where;
330 const MEM_SIZE size = header->size;
332 # ifdef PERL_TRACK_MEMPOOL
333 if (header->interpreter != aTHX) {
334 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
335 header->interpreter, aTHX);
338 Perl_croak_nocontext("panic: duplicate free");
341 Perl_croak_nocontext("panic: bad free, header->next==NULL");
342 if (header->next->prev != header || header->prev->next != header) {
343 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
344 "header=%p, ->prev->next=%p",
345 header->next->prev, header,
348 /* Unlink us from the chain. */
349 maybe_protect_rw(header->next);
350 header->next->prev = header->prev;
351 maybe_protect_ro(header->next);
352 maybe_protect_rw(header->prev);
353 header->prev->next = header->next;
354 maybe_protect_ro(header->prev);
355 maybe_protect_rw(header);
357 PoisonNew(where, size, char);
359 /* Trigger the duplicate free warning. */
362 # ifdef PERL_DEBUG_READONLY_COW
363 if (munmap(where, size)) {
364 perror("munmap failed");
370 #ifndef PERL_DEBUG_READONLY_COW
376 /* safe version of system's calloc() */
379 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
381 #ifdef ALWAYS_NEED_THX
385 #if defined(USE_MDH) || defined(DEBUGGING)
386 MEM_SIZE total_size = 0;
389 /* Even though calloc() for zero bytes is strange, be robust. */
390 if (size && (count <= MEM_SIZE_MAX / size)) {
391 #if defined(USE_MDH) || defined(DEBUGGING)
392 total_size = size * count;
398 if (PERL_MEMORY_DEBUG_HEADER_SIZE <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
399 total_size += PERL_MEMORY_DEBUG_HEADER_SIZE;
404 if ((SSize_t)size < 0 || (SSize_t)count < 0)
405 Perl_croak_nocontext("panic: calloc, size=%"UVuf", count=%"UVuf,
406 (UV)size, (UV)count);
408 #ifdef PERL_DEBUG_READONLY_COW
409 if ((ptr = mmap(0, total_size ? total_size : 1, PROT_READ|PROT_WRITE,
410 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
411 perror("mmap failed");
414 #elif defined(PERL_TRACK_MEMPOOL)
415 /* Have to use malloc() because we've added some space for our tracking
417 /* malloc(0) is non-portable. */
418 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
420 /* Use calloc() because it might save a memset() if the memory is fresh
421 and clean from the OS. */
423 ptr = (Malloc_t)PerlMem_calloc(count, size);
424 else /* calloc(0) is non-portable. */
425 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
427 PERL_ALLOC_CHECK(ptr);
428 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));
432 struct perl_memory_debug_header *const header
433 = (struct perl_memory_debug_header *)ptr;
435 # ifndef PERL_DEBUG_READONLY_COW
436 memset((void*)ptr, 0, total_size);
438 # ifdef PERL_TRACK_MEMPOOL
439 header->interpreter = aTHX;
440 /* Link us into the list. */
441 header->prev = &PL_memory_debug_header;
442 header->next = PL_memory_debug_header.next;
443 PL_memory_debug_header.next = header;
444 maybe_protect_rw(header->next);
445 header->next->prev = header;
446 maybe_protect_ro(header->next);
447 # ifdef PERL_DEBUG_READONLY_COW
448 header->readonly = 0;
452 header->size = total_size;
454 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
460 #ifndef ALWAYS_NEED_THX
469 /* These must be defined when not using Perl's malloc for binary
474 Malloc_t Perl_malloc (MEM_SIZE nbytes)
477 return (Malloc_t)PerlMem_malloc(nbytes);
480 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
483 return (Malloc_t)PerlMem_calloc(elements, size);
486 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
489 return (Malloc_t)PerlMem_realloc(where, nbytes);
492 Free_t Perl_mfree (Malloc_t where)
500 /* copy a string up to some (non-backslashed) delimiter, if any */
503 Perl_delimcpy(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen)
507 PERL_ARGS_ASSERT_DELIMCPY;
509 for (tolen = 0; from < fromend; from++, tolen++) {
511 if (from[1] != delim) {
518 else if (*from == delim)
529 /* return ptr to little string in big string, NULL if not found */
530 /* This routine was donated by Corey Satten. */
533 Perl_instr(const char *big, const char *little)
536 PERL_ARGS_ASSERT_INSTR;
538 /* libc prior to 4.6.27 (late 1994) did not work properly on a NULL
542 return strstr((char*)big, (char*)little);
545 /* same as instr but allow embedded nulls. The end pointers point to 1 beyond
546 * the final character desired to be checked */
549 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
551 PERL_ARGS_ASSERT_NINSTR;
555 const char first = *little;
557 bigend -= lend - little++;
559 while (big <= bigend) {
560 if (*big++ == first) {
561 for (x=big,s=little; s < lend; x++,s++) {
565 return (char*)(big-1);
572 /* reverse of the above--find last substring */
575 Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
578 const I32 first = *little;
579 const char * const littleend = lend;
581 PERL_ARGS_ASSERT_RNINSTR;
583 if (little >= littleend)
584 return (char*)bigend;
586 big = bigend - (littleend - little++);
587 while (big >= bigbeg) {
591 for (x=big+2,s=little; s < littleend; /**/ ) {
600 return (char*)(big+1);
605 /* As a space optimization, we do not compile tables for strings of length
606 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
607 special-cased in fbm_instr().
609 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
612 =head1 Miscellaneous Functions
614 =for apidoc fbm_compile
616 Analyses the string in order to make fast searches on it using fbm_instr()
617 -- the Boyer-Moore algorithm.
623 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
631 PERL_DEB( STRLEN rarest = 0 );
633 PERL_ARGS_ASSERT_FBM_COMPILE;
635 if (isGV_with_GP(sv) || SvROK(sv))
641 if (flags & FBMcf_TAIL) {
642 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
643 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
644 if (mg && mg->mg_len >= 0)
647 if (!SvPOK(sv) || SvNIOKp(sv))
648 s = (U8*)SvPV_force_mutable(sv, len);
649 else s = (U8 *)SvPV_mutable(sv, len);
650 if (len == 0) /* TAIL might be on a zero-length string. */
652 SvUPGRADE(sv, SVt_PVMG);
657 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
658 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
659 to call SvVALID_off() if the scalar was assigned to.
661 The comment itself (and "deeper magic" below) date back to
662 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
664 where the magic (presumably) was that the scalar had a BM table hidden
667 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
668 the table instead of the previous (somewhat hacky) approach of co-opting
669 the string buffer and storing it after the string. */
671 assert(!mg_find(sv, PERL_MAGIC_bm));
672 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
676 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
678 const U8 mlen = (len>255) ? 255 : (U8)len;
679 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
682 Newx(table, 256, U8);
683 memset((void*)table, mlen, 256);
684 mg->mg_ptr = (char *)table;
687 s += len - 1; /* last char */
690 if (table[*s] == mlen)
696 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
697 for (i = 0; i < len; i++) {
698 if (PL_freq[s[i]] < frequency) {
699 PERL_DEB( rarest = i );
700 frequency = PL_freq[s[i]];
703 BmUSEFUL(sv) = 100; /* Initial value */
704 if (flags & FBMcf_TAIL)
706 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
707 s[rarest], (UV)rarest));
710 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
711 /* If SvTAIL is actually due to \Z or \z, this gives false positives
715 =for apidoc fbm_instr
717 Returns the location of the SV in the string delimited by C<big> and
718 C<bigend>. It returns C<NULL> if the string can't be found. The C<sv>
719 does not have to be fbm_compiled, but the search will not be as fast
726 Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
730 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
731 STRLEN littlelen = l;
732 const I32 multiline = flags & FBMrf_MULTILINE;
734 PERL_ARGS_ASSERT_FBM_INSTR;
736 if ((STRLEN)(bigend - big) < littlelen) {
737 if ( SvTAIL(littlestr)
738 && ((STRLEN)(bigend - big) == littlelen - 1)
740 || (*big == *little &&
741 memEQ((char *)big, (char *)little, littlelen - 1))))
746 switch (littlelen) { /* Special cases for 0, 1 and 2 */
748 return (char*)big; /* Cannot be SvTAIL! */
750 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
751 /* Know that bigend != big. */
752 if (bigend[-1] == '\n')
753 return (char *)(bigend - 1);
754 return (char *) bigend;
762 if (SvTAIL(littlestr))
763 return (char *) bigend;
766 if (SvTAIL(littlestr) && !multiline) {
767 if (bigend[-1] == '\n' && bigend[-2] == *little)
768 return (char*)bigend - 2;
769 if (bigend[-1] == *little)
770 return (char*)bigend - 1;
774 /* This should be better than FBM if c1 == c2, and almost
775 as good otherwise: maybe better since we do less indirection.
776 And we save a lot of memory by caching no table. */
777 const unsigned char c1 = little[0];
778 const unsigned char c2 = little[1];
783 while (s <= bigend) {
793 goto check_1char_anchor;
804 goto check_1char_anchor;
807 while (s <= bigend) {
812 goto check_1char_anchor;
821 check_1char_anchor: /* One char and anchor! */
822 if (SvTAIL(littlestr) && (*bigend == *little))
823 return (char *)bigend; /* bigend is already decremented. */
826 break; /* Only lengths 0 1 and 2 have special-case code. */
829 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
830 s = bigend - littlelen;
831 if (s >= big && bigend[-1] == '\n' && *s == *little
832 /* Automatically of length > 2 */
833 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
835 return (char*)s; /* how sweet it is */
838 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
840 return (char*)s + 1; /* how sweet it is */
844 if (!SvVALID(littlestr)) {
845 char * const b = ninstr((char*)big,(char*)bigend,
846 (char*)little, (char*)little + littlelen);
848 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
849 /* Chop \n from littlestr: */
850 s = bigend - littlelen + 1;
852 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
862 if (littlelen > (STRLEN)(bigend - big))
866 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
867 const unsigned char *oldlittle;
871 --littlelen; /* Last char found by table lookup */
874 little += littlelen; /* last char */
877 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
881 if ((tmp = table[*s])) {
882 if ((s += tmp) < bigend)
886 else { /* less expensive than calling strncmp() */
887 unsigned char * const olds = s;
892 if (*--s == *--little)
894 s = olds + 1; /* here we pay the price for failure */
896 if (s < bigend) /* fake up continue to outer loop */
906 && memEQ((char *)(bigend - littlelen),
907 (char *)(oldlittle - littlelen), littlelen) )
908 return (char*)bigend - littlelen;
914 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
917 PERL_ARGS_ASSERT_SCREAMINSTR;
918 PERL_UNUSED_ARG(bigstr);
919 PERL_UNUSED_ARG(littlestr);
920 PERL_UNUSED_ARG(start_shift);
921 PERL_UNUSED_ARG(end_shift);
922 PERL_UNUSED_ARG(old_posp);
923 PERL_UNUSED_ARG(last);
925 /* This function must only ever be called on a scalar with study magic,
926 but those do not happen any more. */
927 Perl_croak(aTHX_ "panic: screaminstr");
928 NORETURN_FUNCTION_END;
934 Returns true if the leading len bytes of the strings s1 and s2 are the same
935 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
936 match themselves and their opposite case counterparts. Non-cased and non-ASCII
937 range bytes match only themselves.
944 Perl_foldEQ(const char *s1, const char *s2, I32 len)
946 const U8 *a = (const U8 *)s1;
947 const U8 *b = (const U8 *)s2;
949 PERL_ARGS_ASSERT_FOLDEQ;
954 if (*a != *b && *a != PL_fold[*b])
961 Perl_foldEQ_latin1(const char *s1, const char *s2, I32 len)
963 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
964 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
965 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
966 * does it check that the strings each have at least 'len' characters */
968 const U8 *a = (const U8 *)s1;
969 const U8 *b = (const U8 *)s2;
971 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
976 if (*a != *b && *a != PL_fold_latin1[*b]) {
985 =for apidoc foldEQ_locale
987 Returns true if the leading len bytes of the strings s1 and s2 are the same
988 case-insensitively in the current locale; false otherwise.
994 Perl_foldEQ_locale(const char *s1, const char *s2, I32 len)
997 const U8 *a = (const U8 *)s1;
998 const U8 *b = (const U8 *)s2;
1000 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
1005 if (*a != *b && *a != PL_fold_locale[*b])
1012 /* copy a string to a safe spot */
1015 =head1 Memory Management
1019 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1020 string which is a duplicate of C<pv>. The size of the string is
1021 determined by C<strlen()>, which means it may not contain embedded C<NUL>
1022 characters and must have a trailing C<NUL>. The memory allocated for the new
1023 string can be freed with the C<Safefree()> function.
1025 On some platforms, Windows for example, all allocated memory owned by a thread
1026 is deallocated when that thread ends. So if you need that not to happen, you
1027 need to use the shared memory functions, such as C<L</savesharedpv>>.
1033 Perl_savepv(pTHX_ const char *pv)
1035 PERL_UNUSED_CONTEXT;
1040 const STRLEN pvlen = strlen(pv)+1;
1041 Newx(newaddr, pvlen, char);
1042 return (char*)memcpy(newaddr, pv, pvlen);
1046 /* same thing but with a known length */
1051 Perl's version of what C<strndup()> would be if it existed. Returns a
1052 pointer to a newly allocated string which is a duplicate of the first
1053 C<len> bytes from C<pv>, plus a trailing
1054 C<NUL> byte. The memory allocated for
1055 the new string can be freed with the C<Safefree()> function.
1057 On some platforms, Windows for example, all allocated memory owned by a thread
1058 is deallocated when that thread ends. So if you need that not to happen, you
1059 need to use the shared memory functions, such as C<L</savesharedpvn>>.
1065 Perl_savepvn(pTHX_ const char *pv, I32 len)
1068 PERL_UNUSED_CONTEXT;
1072 Newx(newaddr,len+1,char);
1073 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1075 /* might not be null terminated */
1076 newaddr[len] = '\0';
1077 return (char *) CopyD(pv,newaddr,len,char);
1080 return (char *) ZeroD(newaddr,len+1,char);
1085 =for apidoc savesharedpv
1087 A version of C<savepv()> which allocates the duplicate string in memory
1088 which is shared between threads.
1093 Perl_savesharedpv(pTHX_ const char *pv)
1100 pvlen = strlen(pv)+1;
1101 newaddr = (char*)PerlMemShared_malloc(pvlen);
1105 return (char*)memcpy(newaddr, pv, pvlen);
1109 =for apidoc savesharedpvn
1111 A version of C<savepvn()> which allocates the duplicate string in memory
1112 which is shared between threads. (With the specific difference that a NULL
1113 pointer is not acceptable)
1118 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1120 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1122 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1127 newaddr[len] = '\0';
1128 return (char*)memcpy(newaddr, pv, len);
1132 =for apidoc savesvpv
1134 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1135 the passed in SV using C<SvPV()>
1137 On some platforms, Windows for example, all allocated memory owned by a thread
1138 is deallocated when that thread ends. So if you need that not to happen, you
1139 need to use the shared memory functions, such as C<L</savesharedsvpv>>.
1145 Perl_savesvpv(pTHX_ SV *sv)
1148 const char * const pv = SvPV_const(sv, len);
1151 PERL_ARGS_ASSERT_SAVESVPV;
1154 Newx(newaddr,len,char);
1155 return (char *) CopyD(pv,newaddr,len,char);
1159 =for apidoc savesharedsvpv
1161 A version of C<savesharedpv()> which allocates the duplicate string in
1162 memory which is shared between threads.
1168 Perl_savesharedsvpv(pTHX_ SV *sv)
1171 const char * const pv = SvPV_const(sv, len);
1173 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1175 return savesharedpvn(pv, len);
1178 /* the SV for Perl_form() and mess() is not kept in an arena */
1187 if (PL_phase != PERL_PHASE_DESTRUCT)
1188 return newSVpvs_flags("", SVs_TEMP);
1193 /* Create as PVMG now, to avoid any upgrading later */
1195 Newxz(any, 1, XPVMG);
1196 SvFLAGS(sv) = SVt_PVMG;
1197 SvANY(sv) = (void*)any;
1199 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1204 #if defined(PERL_IMPLICIT_CONTEXT)
1206 Perl_form_nocontext(const char* pat, ...)
1211 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1212 va_start(args, pat);
1213 retval = vform(pat, &args);
1217 #endif /* PERL_IMPLICIT_CONTEXT */
1220 =head1 Miscellaneous Functions
1223 Takes a sprintf-style format pattern and conventional
1224 (non-SV) arguments and returns the formatted string.
1226 (char *) Perl_form(pTHX_ const char* pat, ...)
1228 can be used any place a string (char *) is required:
1230 char * s = Perl_form("%d.%d",major,minor);
1232 Uses a single private buffer so if you want to format several strings you
1233 must explicitly copy the earlier strings away (and free the copies when you
1240 Perl_form(pTHX_ const char* pat, ...)
1244 PERL_ARGS_ASSERT_FORM;
1245 va_start(args, pat);
1246 retval = vform(pat, &args);
1252 Perl_vform(pTHX_ const char *pat, va_list *args)
1254 SV * const sv = mess_alloc();
1255 PERL_ARGS_ASSERT_VFORM;
1256 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1261 =for apidoc Am|SV *|mess|const char *pat|...
1263 Take a sprintf-style format pattern and argument list. These are used to
1264 generate a string message. If the message does not end with a newline,
1265 then it will be extended with some indication of the current location
1266 in the code, as described for L</mess_sv>.
1268 Normally, the resulting message is returned in a new mortal SV.
1269 During global destruction a single SV may be shared between uses of
1275 #if defined(PERL_IMPLICIT_CONTEXT)
1277 Perl_mess_nocontext(const char *pat, ...)
1282 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1283 va_start(args, pat);
1284 retval = vmess(pat, &args);
1288 #endif /* PERL_IMPLICIT_CONTEXT */
1291 Perl_mess(pTHX_ const char *pat, ...)
1295 PERL_ARGS_ASSERT_MESS;
1296 va_start(args, pat);
1297 retval = vmess(pat, &args);
1303 Perl_closest_cop(pTHX_ const COP *cop, const OP *o, const OP *curop,
1307 /* Look for curop starting from o. cop is the last COP we've seen. */
1308 /* opnext means that curop is actually the ->op_next of the op we are
1311 PERL_ARGS_ASSERT_CLOSEST_COP;
1313 if (!o || !curop || (
1314 opnext ? o->op_next == curop && o->op_type != OP_SCOPE : o == curop
1318 if (o->op_flags & OPf_KIDS) {
1320 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1323 /* If the OP_NEXTSTATE has been optimised away we can still use it
1324 * the get the file and line number. */
1326 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1327 cop = (const COP *)kid;
1329 /* Keep searching, and return when we've found something. */
1331 new_cop = closest_cop(cop, kid, curop, opnext);
1337 /* Nothing found. */
1343 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1345 Expands a message, intended for the user, to include an indication of
1346 the current location in the code, if the message does not already appear
1349 C<basemsg> is the initial message or object. If it is a reference, it
1350 will be used as-is and will be the result of this function. Otherwise it
1351 is used as a string, and if it already ends with a newline, it is taken
1352 to be complete, and the result of this function will be the same string.
1353 If the message does not end with a newline, then a segment such as C<at
1354 foo.pl line 37> will be appended, and possibly other clauses indicating
1355 the current state of execution. The resulting message will end with a
1358 Normally, the resulting message is returned in a new mortal SV.
1359 During global destruction a single SV may be shared between uses of this
1360 function. If C<consume> is true, then the function is permitted (but not
1361 required) to modify and return C<basemsg> instead of allocating a new SV.
1367 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1372 #if defined(USE_C_BACKTRACE) && defined(USE_C_BACKTRACE_ON_ERROR)
1376 /* The PERL_C_BACKTRACE_ON_WARN must be an integer of one or more. */
1377 if ((ws = PerlEnv_getenv("PERL_C_BACKTRACE_ON_ERROR")) &&
1378 (wi = atoi(ws)) > 0) {
1379 Perl_dump_c_backtrace(aTHX_ Perl_debug_log, wi, 1);
1384 PERL_ARGS_ASSERT_MESS_SV;
1386 if (SvROK(basemsg)) {
1392 sv_setsv(sv, basemsg);
1397 if (SvPOK(basemsg) && consume) {
1402 sv_copypv(sv, basemsg);
1405 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1407 * Try and find the file and line for PL_op. This will usually be
1408 * PL_curcop, but it might be a cop that has been optimised away. We
1409 * can try to find such a cop by searching through the optree starting
1410 * from the sibling of PL_curcop.
1414 closest_cop(PL_curcop, PL_curcop->op_sibling, PL_op, FALSE);
1419 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1420 OutCopFILE(cop), (IV)CopLINE(cop));
1421 /* Seems that GvIO() can be untrustworthy during global destruction. */
1422 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1423 && IoLINES(GvIOp(PL_last_in_gv)))
1426 const bool line_mode = (RsSIMPLE(PL_rs) &&
1427 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1428 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1429 SVfARG(PL_last_in_gv == PL_argvgv
1431 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1432 line_mode ? "line" : "chunk",
1433 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1435 if (PL_phase == PERL_PHASE_DESTRUCT)
1436 sv_catpvs(sv, " during global destruction");
1437 sv_catpvs(sv, ".\n");
1443 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1445 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1446 argument list. These are used to generate a string message. If the
1447 message does not end with a newline, then it will be extended with
1448 some indication of the current location in the code, as described for
1451 Normally, the resulting message is returned in a new mortal SV.
1452 During global destruction a single SV may be shared between uses of
1459 Perl_vmess(pTHX_ const char *pat, va_list *args)
1462 SV * const sv = mess_alloc();
1464 PERL_ARGS_ASSERT_VMESS;
1466 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1467 return mess_sv(sv, 1);
1471 Perl_write_to_stderr(pTHX_ SV* msv)
1477 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1479 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1480 && (io = GvIO(PL_stderrgv))
1481 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1482 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, SV_CONST(PRINT),
1483 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1485 PerlIO * const serr = Perl_error_log;
1487 do_print(msv, serr);
1488 (void)PerlIO_flush(serr);
1493 =head1 Warning and Dieing
1496 /* Common code used in dieing and warning */
1499 S_with_queued_errors(pTHX_ SV *ex)
1501 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1502 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1503 sv_catsv(PL_errors, ex);
1504 ex = sv_mortalcopy(PL_errors);
1505 SvCUR_set(PL_errors, 0);
1511 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1517 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1518 /* sv_2cv might call Perl_croak() or Perl_warner() */
1519 SV * const oldhook = *hook;
1527 cv = sv_2cv(oldhook, &stash, &gv, 0);
1529 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1539 exarg = newSVsv(ex);
1540 SvREADONLY_on(exarg);
1543 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1547 call_sv(MUTABLE_SV(cv), G_DISCARD);
1556 =for apidoc Am|OP *|die_sv|SV *baseex
1558 Behaves the same as L</croak_sv>, except for the return type.
1559 It should be used only where the C<OP *> return type is required.
1560 The function never actually returns.
1566 Perl_die_sv(pTHX_ SV *baseex)
1568 PERL_ARGS_ASSERT_DIE_SV;
1570 assert(0); /* NOTREACHED */
1571 NORETURN_FUNCTION_END;
1575 =for apidoc Am|OP *|die|const char *pat|...
1577 Behaves the same as L</croak>, except for the return type.
1578 It should be used only where the C<OP *> return type is required.
1579 The function never actually returns.
1584 #if defined(PERL_IMPLICIT_CONTEXT)
1586 Perl_die_nocontext(const char* pat, ...)
1590 va_start(args, pat);
1592 assert(0); /* NOTREACHED */
1594 NORETURN_FUNCTION_END;
1596 #endif /* PERL_IMPLICIT_CONTEXT */
1599 Perl_die(pTHX_ const char* pat, ...)
1602 va_start(args, pat);
1604 assert(0); /* NOTREACHED */
1606 NORETURN_FUNCTION_END;
1610 =for apidoc Am|void|croak_sv|SV *baseex
1612 This is an XS interface to Perl's C<die> function.
1614 C<baseex> is the error message or object. If it is a reference, it
1615 will be used as-is. Otherwise it is used as a string, and if it does
1616 not end with a newline then it will be extended with some indication of
1617 the current location in the code, as described for L</mess_sv>.
1619 The error message or object will be used as an exception, by default
1620 returning control to the nearest enclosing C<eval>, but subject to
1621 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1622 function never returns normally.
1624 To die with a simple string message, the L</croak> function may be
1631 Perl_croak_sv(pTHX_ SV *baseex)
1633 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1634 PERL_ARGS_ASSERT_CROAK_SV;
1635 invoke_exception_hook(ex, FALSE);
1640 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1642 This is an XS interface to Perl's C<die> function.
1644 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1645 argument list. These are used to generate a string message. If the
1646 message does not end with a newline, then it will be extended with
1647 some indication of the current location in the code, as described for
1650 The error message will be used as an exception, by default
1651 returning control to the nearest enclosing C<eval>, but subject to
1652 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1653 function never returns normally.
1655 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1656 (C<$@>) will be used as an error message or object instead of building an
1657 error message from arguments. If you want to throw a non-string object,
1658 or build an error message in an SV yourself, it is preferable to use
1659 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1665 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1667 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1668 invoke_exception_hook(ex, FALSE);
1673 =for apidoc Am|void|croak|const char *pat|...
1675 This is an XS interface to Perl's C<die> function.
1677 Take a sprintf-style format pattern and argument list. These are used to
1678 generate a string message. If the message does not end with a newline,
1679 then it will be extended with some indication of the current location
1680 in the code, as described for L</mess_sv>.
1682 The error message will be used as an exception, by default
1683 returning control to the nearest enclosing C<eval>, but subject to
1684 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1685 function never returns normally.
1687 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1688 (C<$@>) will be used as an error message or object instead of building an
1689 error message from arguments. If you want to throw a non-string object,
1690 or build an error message in an SV yourself, it is preferable to use
1691 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1696 #if defined(PERL_IMPLICIT_CONTEXT)
1698 Perl_croak_nocontext(const char *pat, ...)
1702 va_start(args, pat);
1704 assert(0); /* NOTREACHED */
1707 #endif /* PERL_IMPLICIT_CONTEXT */
1710 Perl_croak(pTHX_ const char *pat, ...)
1713 va_start(args, pat);
1715 assert(0); /* NOTREACHED */
1720 =for apidoc Am|void|croak_no_modify
1722 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1723 terser object code than using C<Perl_croak>. Less code used on exception code
1724 paths reduces CPU cache pressure.
1730 Perl_croak_no_modify(void)
1732 Perl_croak_nocontext( "%s", PL_no_modify);
1735 /* does not return, used in util.c perlio.c and win32.c
1736 This is typically called when malloc returns NULL.
1739 Perl_croak_no_mem(void)
1743 int fd = PerlIO_fileno(Perl_error_log);
1745 SETERRNO(EBADF,RMS_IFI);
1747 /* Can't use PerlIO to write as it allocates memory */
1748 PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, sizeof(PL_no_mem)-1));
1753 /* does not return, used only in POPSTACK */
1755 Perl_croak_popstack(void)
1758 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
1763 =for apidoc Am|void|warn_sv|SV *baseex
1765 This is an XS interface to Perl's C<warn> function.
1767 C<baseex> is the error message or object. If it is a reference, it
1768 will be used as-is. Otherwise it is used as a string, and if it does
1769 not end with a newline then it will be extended with some indication of
1770 the current location in the code, as described for L</mess_sv>.
1772 The error message or object will by default be written to standard error,
1773 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1775 To warn with a simple string message, the L</warn> function may be
1782 Perl_warn_sv(pTHX_ SV *baseex)
1784 SV *ex = mess_sv(baseex, 0);
1785 PERL_ARGS_ASSERT_WARN_SV;
1786 if (!invoke_exception_hook(ex, TRUE))
1787 write_to_stderr(ex);
1791 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1793 This is an XS interface to Perl's C<warn> function.
1795 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1796 argument list. These are used to generate a string message. If the
1797 message does not end with a newline, then it will be extended with
1798 some indication of the current location in the code, as described for
1801 The error message or object will by default be written to standard error,
1802 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1804 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1810 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1812 SV *ex = vmess(pat, args);
1813 PERL_ARGS_ASSERT_VWARN;
1814 if (!invoke_exception_hook(ex, TRUE))
1815 write_to_stderr(ex);
1819 =for apidoc Am|void|warn|const char *pat|...
1821 This is an XS interface to Perl's C<warn> function.
1823 Take a sprintf-style format pattern and argument list. These are used to
1824 generate a string message. If the message does not end with a newline,
1825 then it will be extended with some indication of the current location
1826 in the code, as described for L</mess_sv>.
1828 The error message or object will by default be written to standard error,
1829 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1831 Unlike with L</croak>, C<pat> is not permitted to be null.
1836 #if defined(PERL_IMPLICIT_CONTEXT)
1838 Perl_warn_nocontext(const char *pat, ...)
1842 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1843 va_start(args, pat);
1847 #endif /* PERL_IMPLICIT_CONTEXT */
1850 Perl_warn(pTHX_ const char *pat, ...)
1853 PERL_ARGS_ASSERT_WARN;
1854 va_start(args, pat);
1859 #if defined(PERL_IMPLICIT_CONTEXT)
1861 Perl_warner_nocontext(U32 err, const char *pat, ...)
1865 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1866 va_start(args, pat);
1867 vwarner(err, pat, &args);
1870 #endif /* PERL_IMPLICIT_CONTEXT */
1873 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1875 PERL_ARGS_ASSERT_CK_WARNER_D;
1877 if (Perl_ckwarn_d(aTHX_ err)) {
1879 va_start(args, pat);
1880 vwarner(err, pat, &args);
1886 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1888 PERL_ARGS_ASSERT_CK_WARNER;
1890 if (Perl_ckwarn(aTHX_ err)) {
1892 va_start(args, pat);
1893 vwarner(err, pat, &args);
1899 Perl_warner(pTHX_ U32 err, const char* pat,...)
1902 PERL_ARGS_ASSERT_WARNER;
1903 va_start(args, pat);
1904 vwarner(err, pat, &args);
1909 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1912 PERL_ARGS_ASSERT_VWARNER;
1913 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1914 SV * const msv = vmess(pat, args);
1916 invoke_exception_hook(msv, FALSE);
1920 Perl_vwarn(aTHX_ pat, args);
1924 /* implements the ckWARN? macros */
1927 Perl_ckwarn(pTHX_ U32 w)
1930 /* If lexical warnings have not been set, use $^W. */
1932 return PL_dowarn & G_WARN_ON;
1934 return ckwarn_common(w);
1937 /* implements the ckWARN?_d macro */
1940 Perl_ckwarn_d(pTHX_ U32 w)
1943 /* If lexical warnings have not been set then default classes warn. */
1947 return ckwarn_common(w);
1951 S_ckwarn_common(pTHX_ U32 w)
1953 if (PL_curcop->cop_warnings == pWARN_ALL)
1956 if (PL_curcop->cop_warnings == pWARN_NONE)
1959 /* Check the assumption that at least the first slot is non-zero. */
1960 assert(unpackWARN1(w));
1962 /* Check the assumption that it is valid to stop as soon as a zero slot is
1964 if (!unpackWARN2(w)) {
1965 assert(!unpackWARN3(w));
1966 assert(!unpackWARN4(w));
1967 } else if (!unpackWARN3(w)) {
1968 assert(!unpackWARN4(w));
1971 /* Right, dealt with all the special cases, which are implemented as non-
1972 pointers, so there is a pointer to a real warnings mask. */
1974 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1976 } while (w >>= WARNshift);
1981 /* Set buffer=NULL to get a new one. */
1983 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1985 const MEM_SIZE len_wanted =
1986 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
1987 PERL_UNUSED_CONTEXT;
1988 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1991 (specialWARN(buffer) ?
1992 PerlMemShared_malloc(len_wanted) :
1993 PerlMemShared_realloc(buffer, len_wanted));
1995 Copy(bits, (buffer + 1), size, char);
1996 if (size < WARNsize)
1997 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
2001 /* since we've already done strlen() for both nam and val
2002 * we can use that info to make things faster than
2003 * sprintf(s, "%s=%s", nam, val)
2005 #define my_setenv_format(s, nam, nlen, val, vlen) \
2006 Copy(nam, s, nlen, char); \
2008 Copy(val, s+(nlen+1), vlen, char); \
2009 *(s+(nlen+1+vlen)) = '\0'
2011 #ifdef USE_ENVIRON_ARRAY
2012 /* VMS' my_setenv() is in vms.c */
2013 #if !defined(WIN32) && !defined(NETWARE)
2015 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2019 /* only parent thread can modify process environment */
2020 if (PL_curinterp == aTHX)
2023 #ifndef PERL_USE_SAFE_PUTENV
2024 if (!PL_use_safe_putenv) {
2025 /* most putenv()s leak, so we manipulate environ directly */
2027 const I32 len = strlen(nam);
2030 /* where does it go? */
2031 for (i = 0; environ[i]; i++) {
2032 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
2036 if (environ == PL_origenviron) { /* need we copy environment? */
2042 while (environ[max])
2044 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2045 for (j=0; j<max; j++) { /* copy environment */
2046 const int len = strlen(environ[j]);
2047 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2048 Copy(environ[j], tmpenv[j], len+1, char);
2051 environ = tmpenv; /* tell exec where it is now */
2054 safesysfree(environ[i]);
2055 while (environ[i]) {
2056 environ[i] = environ[i+1];
2061 if (!environ[i]) { /* does not exist yet */
2062 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2063 environ[i+1] = NULL; /* make sure it's null terminated */
2066 safesysfree(environ[i]);
2070 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2071 /* all that work just for this */
2072 my_setenv_format(environ[i], nam, nlen, val, vlen);
2075 # if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__)
2076 # if defined(HAS_UNSETENV)
2078 (void)unsetenv(nam);
2080 (void)setenv(nam, val, 1);
2082 # else /* ! HAS_UNSETENV */
2083 (void)setenv(nam, val, 1);
2084 # endif /* HAS_UNSETENV */
2086 # if defined(HAS_UNSETENV)
2088 if (environ) /* old glibc can crash with null environ */
2089 (void)unsetenv(nam);
2091 const int nlen = strlen(nam);
2092 const int vlen = strlen(val);
2093 char * const new_env =
2094 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2095 my_setenv_format(new_env, nam, nlen, val, vlen);
2096 (void)putenv(new_env);
2098 # else /* ! HAS_UNSETENV */
2100 const int nlen = strlen(nam);
2106 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2107 /* all that work just for this */
2108 my_setenv_format(new_env, nam, nlen, val, vlen);
2109 (void)putenv(new_env);
2110 # endif /* HAS_UNSETENV */
2111 # endif /* __CYGWIN__ */
2112 #ifndef PERL_USE_SAFE_PUTENV
2118 #else /* WIN32 || NETWARE */
2121 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2125 const int nlen = strlen(nam);
2132 Newx(envstr, nlen+vlen+2, char);
2133 my_setenv_format(envstr, nam, nlen, val, vlen);
2134 (void)PerlEnv_putenv(envstr);
2138 #endif /* WIN32 || NETWARE */
2142 #ifdef UNLINK_ALL_VERSIONS
2144 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2148 PERL_ARGS_ASSERT_UNLNK;
2150 while (PerlLIO_unlink(f) >= 0)
2152 return retries ? 0 : -1;
2156 /* this is a drop-in replacement for bcopy() */
2157 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2159 Perl_my_bcopy(const char *from, char *to, I32 len)
2161 char * const retval = to;
2163 PERL_ARGS_ASSERT_MY_BCOPY;
2167 if (from - to >= 0) {
2175 *(--to) = *(--from);
2181 /* this is a drop-in replacement for memset() */
2184 Perl_my_memset(char *loc, I32 ch, I32 len)
2186 char * const retval = loc;
2188 PERL_ARGS_ASSERT_MY_MEMSET;
2198 /* this is a drop-in replacement for bzero() */
2199 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2201 Perl_my_bzero(char *loc, I32 len)
2203 char * const retval = loc;
2205 PERL_ARGS_ASSERT_MY_BZERO;
2215 /* this is a drop-in replacement for memcmp() */
2216 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2218 Perl_my_memcmp(const char *s1, const char *s2, I32 len)
2220 const U8 *a = (const U8 *)s1;
2221 const U8 *b = (const U8 *)s2;
2224 PERL_ARGS_ASSERT_MY_MEMCMP;
2229 if ((tmp = *a++ - *b++))
2234 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2237 /* This vsprintf replacement should generally never get used, since
2238 vsprintf was available in both System V and BSD 2.11. (There may
2239 be some cross-compilation or embedded set-ups where it is needed,
2242 If you encounter a problem in this function, it's probably a symptom
2243 that Configure failed to detect your system's vprintf() function.
2244 See the section on "item vsprintf" in the INSTALL file.
2246 This version may compile on systems with BSD-ish <stdio.h>,
2247 but probably won't on others.
2250 #ifdef USE_CHAR_VSPRINTF
2255 vsprintf(char *dest, const char *pat, void *args)
2259 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2260 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2261 FILE_cnt(&fakebuf) = 32767;
2263 /* These probably won't compile -- If you really need
2264 this, you'll have to figure out some other method. */
2265 fakebuf._ptr = dest;
2266 fakebuf._cnt = 32767;
2271 fakebuf._flag = _IOWRT|_IOSTRG;
2272 _doprnt(pat, args, &fakebuf); /* what a kludge */
2273 #if defined(STDIO_PTR_LVALUE)
2274 *(FILE_ptr(&fakebuf)++) = '\0';
2276 /* PerlIO has probably #defined away fputc, but we want it here. */
2278 # undef fputc /* XXX Should really restore it later */
2280 (void)fputc('\0', &fakebuf);
2282 #ifdef USE_CHAR_VSPRINTF
2285 return 0; /* perl doesn't use return value */
2289 #endif /* HAS_VPRINTF */
2292 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2294 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2303 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2305 PERL_FLUSHALL_FOR_CHILD;
2306 This = (*mode == 'w');
2310 taint_proper("Insecure %s%s", "EXEC");
2312 if (PerlProc_pipe(p) < 0)
2314 /* Try for another pipe pair for error return */
2315 if (PerlProc_pipe(pp) >= 0)
2317 while ((pid = PerlProc_fork()) < 0) {
2318 if (errno != EAGAIN) {
2319 PerlLIO_close(p[This]);
2320 PerlLIO_close(p[that]);
2322 PerlLIO_close(pp[0]);
2323 PerlLIO_close(pp[1]);
2327 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2336 /* Close parent's end of error status pipe (if any) */
2338 PerlLIO_close(pp[0]);
2339 #if defined(HAS_FCNTL) && defined(F_SETFD)
2340 /* Close error pipe automatically if exec works */
2341 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2345 /* Now dup our end of _the_ pipe to right position */
2346 if (p[THIS] != (*mode == 'r')) {
2347 PerlLIO_dup2(p[THIS], *mode == 'r');
2348 PerlLIO_close(p[THIS]);
2349 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2350 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2353 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2354 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2355 /* No automatic close - do it by hand */
2362 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2368 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2374 do_execfree(); /* free any memory malloced by child on fork */
2376 PerlLIO_close(pp[1]);
2377 /* Keep the lower of the two fd numbers */
2378 if (p[that] < p[This]) {
2379 PerlLIO_dup2(p[This], p[that]);
2380 PerlLIO_close(p[This]);
2384 PerlLIO_close(p[that]); /* close child's end of pipe */
2386 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2387 SvUPGRADE(sv,SVt_IV);
2389 PL_forkprocess = pid;
2390 /* If we managed to get status pipe check for exec fail */
2391 if (did_pipes && pid > 0) {
2396 while (n < sizeof(int)) {
2397 n1 = PerlLIO_read(pp[0],
2398 (void*)(((char*)&errkid)+n),
2404 PerlLIO_close(pp[0]);
2406 if (n) { /* Error */
2408 PerlLIO_close(p[This]);
2409 if (n != sizeof(int))
2410 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2412 pid2 = wait4pid(pid, &status, 0);
2413 } while (pid2 == -1 && errno == EINTR);
2414 errno = errkid; /* Propagate errno from kid */
2419 PerlLIO_close(pp[0]);
2420 return PerlIO_fdopen(p[This], mode);
2422 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2423 return my_syspopen4(aTHX_ NULL, mode, n, args);
2425 Perl_croak(aTHX_ "List form of piped open not implemented");
2426 return (PerlIO *) NULL;
2431 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2432 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2434 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2441 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2445 PERL_ARGS_ASSERT_MY_POPEN;
2447 PERL_FLUSHALL_FOR_CHILD;
2450 return my_syspopen(aTHX_ cmd,mode);
2453 This = (*mode == 'w');
2455 if (doexec && TAINTING_get) {
2457 taint_proper("Insecure %s%s", "EXEC");
2459 if (PerlProc_pipe(p) < 0)
2461 if (doexec && PerlProc_pipe(pp) >= 0)
2463 while ((pid = PerlProc_fork()) < 0) {
2464 if (errno != EAGAIN) {
2465 PerlLIO_close(p[This]);
2466 PerlLIO_close(p[that]);
2468 PerlLIO_close(pp[0]);
2469 PerlLIO_close(pp[1]);
2472 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2475 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2485 PerlLIO_close(pp[0]);
2486 #if defined(HAS_FCNTL) && defined(F_SETFD)
2487 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
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]);
2498 PerlLIO_close(p[THAT]);
2501 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2508 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2513 /* may or may not use the shell */
2514 do_exec3(cmd, pp[1], did_pipes);
2517 #endif /* defined OS2 */
2519 #ifdef PERLIO_USING_CRLF
2520 /* Since we circumvent IO layers when we manipulate low-level
2521 filedescriptors directly, need to manually switch to the
2522 default, binary, low-level mode; see PerlIOBuf_open(). */
2523 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2526 #ifdef PERL_USES_PL_PIDSTATUS
2527 hv_clear(PL_pidstatus); /* we have no children */
2533 do_execfree(); /* free any memory malloced by child on vfork */
2535 PerlLIO_close(pp[1]);
2536 if (p[that] < p[This]) {
2537 PerlLIO_dup2(p[This], p[that]);
2538 PerlLIO_close(p[This]);
2542 PerlLIO_close(p[that]);
2544 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2545 SvUPGRADE(sv,SVt_IV);
2547 PL_forkprocess = pid;
2548 if (did_pipes && pid > 0) {
2553 while (n < sizeof(int)) {
2554 n1 = PerlLIO_read(pp[0],
2555 (void*)(((char*)&errkid)+n),
2561 PerlLIO_close(pp[0]);
2563 if (n) { /* Error */
2565 PerlLIO_close(p[This]);
2566 if (n != sizeof(int))
2567 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2569 pid2 = wait4pid(pid, &status, 0);
2570 } while (pid2 == -1 && errno == EINTR);
2571 errno = errkid; /* Propagate errno from kid */
2576 PerlLIO_close(pp[0]);
2577 return PerlIO_fdopen(p[This], mode);
2581 FILE *djgpp_popen();
2583 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2585 PERL_FLUSHALL_FOR_CHILD;
2586 /* Call system's popen() to get a FILE *, then import it.
2587 used 0 for 2nd parameter to PerlIO_importFILE;
2590 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2593 #if defined(__LIBCATAMOUNT__)
2595 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2602 #endif /* !DOSISH */
2604 /* this is called in parent before the fork() */
2606 Perl_atfork_lock(void)
2609 #if defined(USE_ITHREADS)
2610 /* locks must be held in locking order (if any) */
2612 MUTEX_LOCK(&PL_perlio_mutex);
2615 MUTEX_LOCK(&PL_malloc_mutex);
2621 /* this is called in both parent and child after the fork() */
2623 Perl_atfork_unlock(void)
2626 #if defined(USE_ITHREADS)
2627 /* locks must be released in same order as in atfork_lock() */
2629 MUTEX_UNLOCK(&PL_perlio_mutex);
2632 MUTEX_UNLOCK(&PL_malloc_mutex);
2641 #if defined(HAS_FORK)
2643 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2648 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2649 * handlers elsewhere in the code */
2654 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2655 Perl_croak_nocontext("fork() not available");
2657 #endif /* HAS_FORK */
2662 dup2(int oldfd, int newfd)
2664 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2667 PerlLIO_close(newfd);
2668 return fcntl(oldfd, F_DUPFD, newfd);
2670 #define DUP2_MAX_FDS 256
2671 int fdtmp[DUP2_MAX_FDS];
2677 PerlLIO_close(newfd);
2678 /* good enough for low fd's... */
2679 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2680 if (fdx >= DUP2_MAX_FDS) {
2688 PerlLIO_close(fdtmp[--fdx]);
2695 #ifdef HAS_SIGACTION
2698 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2701 struct sigaction act, oact;
2704 /* only "parent" interpreter can diddle signals */
2705 if (PL_curinterp != aTHX)
2706 return (Sighandler_t) SIG_ERR;
2709 act.sa_handler = (void(*)(int))handler;
2710 sigemptyset(&act.sa_mask);
2713 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2714 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2716 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2717 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2718 act.sa_flags |= SA_NOCLDWAIT;
2720 if (sigaction(signo, &act, &oact) == -1)
2721 return (Sighandler_t) SIG_ERR;
2723 return (Sighandler_t) oact.sa_handler;
2727 Perl_rsignal_state(pTHX_ int signo)
2729 struct sigaction oact;
2730 PERL_UNUSED_CONTEXT;
2732 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2733 return (Sighandler_t) SIG_ERR;
2735 return (Sighandler_t) oact.sa_handler;
2739 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2742 struct sigaction act;
2744 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2747 /* only "parent" interpreter can diddle signals */
2748 if (PL_curinterp != aTHX)
2752 act.sa_handler = (void(*)(int))handler;
2753 sigemptyset(&act.sa_mask);
2756 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2757 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2759 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2760 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2761 act.sa_flags |= SA_NOCLDWAIT;
2763 return sigaction(signo, &act, save);
2767 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2771 /* only "parent" interpreter can diddle signals */
2772 if (PL_curinterp != aTHX)
2776 return sigaction(signo, save, (struct sigaction *)NULL);
2779 #else /* !HAS_SIGACTION */
2782 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2784 #if defined(USE_ITHREADS) && !defined(WIN32)
2785 /* only "parent" interpreter can diddle signals */
2786 if (PL_curinterp != aTHX)
2787 return (Sighandler_t) SIG_ERR;
2790 return PerlProc_signal(signo, handler);
2801 Perl_rsignal_state(pTHX_ int signo)
2804 Sighandler_t oldsig;
2806 #if defined(USE_ITHREADS) && !defined(WIN32)
2807 /* only "parent" interpreter can diddle signals */
2808 if (PL_curinterp != aTHX)
2809 return (Sighandler_t) SIG_ERR;
2813 oldsig = PerlProc_signal(signo, sig_trap);
2814 PerlProc_signal(signo, oldsig);
2816 PerlProc_kill(PerlProc_getpid(), signo);
2821 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2823 #if defined(USE_ITHREADS) && !defined(WIN32)
2824 /* only "parent" interpreter can diddle signals */
2825 if (PL_curinterp != aTHX)
2828 *save = PerlProc_signal(signo, handler);
2829 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2833 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2835 #if defined(USE_ITHREADS) && !defined(WIN32)
2836 /* only "parent" interpreter can diddle signals */
2837 if (PL_curinterp != aTHX)
2840 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2843 #endif /* !HAS_SIGACTION */
2844 #endif /* !PERL_MICRO */
2846 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2847 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2849 Perl_my_pclose(pTHX_ PerlIO *ptr)
2858 const int fd = PerlIO_fileno(ptr);
2861 svp = av_fetch(PL_fdpid,fd,TRUE);
2862 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2866 #if defined(USE_PERLIO)
2867 /* Find out whether the refcount is low enough for us to wait for the
2868 child proc without blocking. */
2869 should_wait = PerlIOUnix_refcnt(fd) == 1 && pid > 0;
2871 should_wait = pid > 0;
2875 if (pid == -1) { /* Opened by popen. */
2876 return my_syspclose(ptr);
2879 close_failed = (PerlIO_close(ptr) == EOF);
2881 if (should_wait) do {
2882 pid2 = wait4pid(pid, &status, 0);
2883 } while (pid2 == -1 && errno == EINTR);
2890 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
2895 #if defined(__LIBCATAMOUNT__)
2897 Perl_my_pclose(pTHX_ PerlIO *ptr)
2902 #endif /* !DOSISH */
2904 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
2906 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2910 PERL_ARGS_ASSERT_WAIT4PID;
2911 #ifdef PERL_USES_PL_PIDSTATUS
2913 /* PERL_USES_PL_PIDSTATUS is only defined when neither
2914 waitpid() nor wait4() is available, or on OS/2, which
2915 doesn't appear to support waiting for a progress group
2916 member, so we can only treat a 0 pid as an unknown child.
2923 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2924 pid, rather than a string form. */
2925 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2926 if (svp && *svp != &PL_sv_undef) {
2927 *statusp = SvIVX(*svp);
2928 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2936 hv_iterinit(PL_pidstatus);
2937 if ((entry = hv_iternext(PL_pidstatus))) {
2938 SV * const sv = hv_iterval(PL_pidstatus,entry);
2940 const char * const spid = hv_iterkey(entry,&len);
2942 assert (len == sizeof(Pid_t));
2943 memcpy((char *)&pid, spid, len);
2944 *statusp = SvIVX(sv);
2945 /* The hash iterator is currently on this entry, so simply
2946 calling hv_delete would trigger the lazy delete, which on
2947 aggregate does more work, beacuse next call to hv_iterinit()
2948 would spot the flag, and have to call the delete routine,
2949 while in the meantime any new entries can't re-use that
2951 hv_iterinit(PL_pidstatus);
2952 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2959 # ifdef HAS_WAITPID_RUNTIME
2960 if (!HAS_WAITPID_RUNTIME)
2963 result = PerlProc_waitpid(pid,statusp,flags);
2966 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2967 result = wait4(pid,statusp,flags,NULL);
2970 #ifdef PERL_USES_PL_PIDSTATUS
2971 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2976 Perl_croak(aTHX_ "Can't do waitpid with flags");
2978 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2979 pidgone(result,*statusp);
2985 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
2988 if (result < 0 && errno == EINTR) {
2990 errno = EINTR; /* reset in case a signal handler changed $! */
2994 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2996 #ifdef PERL_USES_PL_PIDSTATUS
2998 S_pidgone(pTHX_ Pid_t pid, int status)
3002 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3003 SvUPGRADE(sv,SVt_IV);
3004 SvIV_set(sv, status);
3012 int /* Cannot prototype with I32
3014 my_syspclose(PerlIO *ptr)
3017 Perl_my_pclose(pTHX_ PerlIO *ptr)
3020 /* Needs work for PerlIO ! */
3021 FILE * const f = PerlIO_findFILE(ptr);
3022 const I32 result = pclose(f);
3023 PerlIO_releaseFILE(ptr,f);
3031 Perl_my_pclose(pTHX_ PerlIO *ptr)
3033 /* Needs work for PerlIO ! */
3034 FILE * const f = PerlIO_findFILE(ptr);
3035 I32 result = djgpp_pclose(f);
3036 result = (result << 8) & 0xff00;
3037 PerlIO_releaseFILE(ptr,f);
3042 #define PERL_REPEATCPY_LINEAR 4
3044 Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
3046 PERL_ARGS_ASSERT_REPEATCPY;
3051 croak_memory_wrap();
3054 memset(to, *from, count);
3057 IV items, linear, half;
3059 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3060 for (items = 0; items < linear; ++items) {
3061 const char *q = from;
3063 for (todo = len; todo > 0; todo--)
3068 while (items <= half) {
3069 IV size = items * len;
3070 memcpy(p, to, size);
3076 memcpy(p, to, (count - items) * len);
3082 Perl_same_dirent(pTHX_ const char *a, const char *b)
3084 char *fa = strrchr(a,'/');
3085 char *fb = strrchr(b,'/');
3088 SV * const tmpsv = sv_newmortal();
3090 PERL_ARGS_ASSERT_SAME_DIRENT;
3103 sv_setpvs(tmpsv, ".");
3105 sv_setpvn(tmpsv, a, fa - a);
3106 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3109 sv_setpvs(tmpsv, ".");
3111 sv_setpvn(tmpsv, b, fb - b);
3112 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3114 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3115 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3117 #endif /* !HAS_RENAME */
3120 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3121 const char *const *const search_ext, I32 flags)
3124 const char *xfound = NULL;
3125 char *xfailed = NULL;
3126 char tmpbuf[MAXPATHLEN];
3131 #if defined(DOSISH) && !defined(OS2)
3132 # define SEARCH_EXTS ".bat", ".cmd", NULL
3133 # define MAX_EXT_LEN 4
3136 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3137 # define MAX_EXT_LEN 4
3140 # define SEARCH_EXTS ".pl", ".com", NULL
3141 # define MAX_EXT_LEN 4
3143 /* additional extensions to try in each dir if scriptname not found */
3145 static const char *const exts[] = { SEARCH_EXTS };
3146 const char *const *const ext = search_ext ? search_ext : exts;
3147 int extidx = 0, i = 0;
3148 const char *curext = NULL;
3150 PERL_UNUSED_ARG(search_ext);
3151 # define MAX_EXT_LEN 0
3154 PERL_ARGS_ASSERT_FIND_SCRIPT;
3157 * If dosearch is true and if scriptname does not contain path
3158 * delimiters, search the PATH for scriptname.
3160 * If SEARCH_EXTS is also defined, will look for each
3161 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3162 * while searching the PATH.
3164 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3165 * proceeds as follows:
3166 * If DOSISH or VMSISH:
3167 * + look for ./scriptname{,.foo,.bar}
3168 * + search the PATH for scriptname{,.foo,.bar}
3171 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3172 * this will not look in '.' if it's not in the PATH)
3177 # ifdef ALWAYS_DEFTYPES
3178 len = strlen(scriptname);
3179 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3180 int idx = 0, deftypes = 1;
3183 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3186 int idx = 0, deftypes = 1;
3189 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3191 /* The first time through, just add SEARCH_EXTS to whatever we
3192 * already have, so we can check for default file types. */
3194 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3200 if ((strlen(tmpbuf) + strlen(scriptname)
3201 + MAX_EXT_LEN) >= sizeof tmpbuf)
3202 continue; /* don't search dir with too-long name */
3203 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3207 if (strEQ(scriptname, "-"))
3209 if (dosearch) { /* Look in '.' first. */
3210 const char *cur = scriptname;
3212 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3214 if (strEQ(ext[i++],curext)) {
3215 extidx = -1; /* already has an ext */
3220 DEBUG_p(PerlIO_printf(Perl_debug_log,
3221 "Looking for %s\n",cur));
3222 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3223 && !S_ISDIR(PL_statbuf.st_mode)) {
3231 if (cur == scriptname) {
3232 len = strlen(scriptname);
3233 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3235 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3238 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3239 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3244 if (dosearch && !strchr(scriptname, '/')
3246 && !strchr(scriptname, '\\')
3248 && (s = PerlEnv_getenv("PATH")))
3252 bufend = s + strlen(s);
3253 while (s < bufend) {
3256 && *s != ';'; len++, s++) {
3257 if (len < sizeof tmpbuf)
3260 if (len < sizeof tmpbuf)
3263 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3269 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3270 continue; /* don't search dir with too-long name */
3273 && tmpbuf[len - 1] != '/'
3274 && tmpbuf[len - 1] != '\\'
3277 tmpbuf[len++] = '/';
3278 if (len == 2 && tmpbuf[0] == '.')
3280 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3284 len = strlen(tmpbuf);
3285 if (extidx > 0) /* reset after previous loop */
3289 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3290 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3291 if (S_ISDIR(PL_statbuf.st_mode)) {
3295 } while ( retval < 0 /* not there */
3296 && extidx>=0 && ext[extidx] /* try an extension? */
3297 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3302 if (S_ISREG(PL_statbuf.st_mode)
3303 && cando(S_IRUSR,TRUE,&PL_statbuf)
3304 #if !defined(DOSISH)
3305 && cando(S_IXUSR,TRUE,&PL_statbuf)
3309 xfound = tmpbuf; /* bingo! */
3313 xfailed = savepv(tmpbuf);
3316 if (!xfound && !seen_dot && !xfailed &&
3317 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3318 || S_ISDIR(PL_statbuf.st_mode)))
3320 seen_dot = 1; /* Disable message. */
3322 if (flags & 1) { /* do or die? */
3323 /* diag_listed_as: Can't execute %s */
3324 Perl_croak(aTHX_ "Can't %s %s%s%s",
3325 (xfailed ? "execute" : "find"),
3326 (xfailed ? xfailed : scriptname),
3327 (xfailed ? "" : " on PATH"),
3328 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3333 scriptname = xfound;
3335 return (scriptname ? savepv(scriptname) : NULL);
3338 #ifndef PERL_GET_CONTEXT_DEFINED
3341 Perl_get_context(void)
3344 #if defined(USE_ITHREADS)
3345 # ifdef OLD_PTHREADS_API
3347 int error = pthread_getspecific(PL_thr_key, &t)
3349 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3352 # ifdef I_MACH_CTHREADS
3353 return (void*)cthread_data(cthread_self());
3355 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3364 Perl_set_context(void *t)
3367 PERL_ARGS_ASSERT_SET_CONTEXT;
3368 #if defined(USE_ITHREADS)
3369 # ifdef I_MACH_CTHREADS
3370 cthread_set_data(cthread_self(), t);
3373 const int error = pthread_setspecific(PL_thr_key, t);
3375 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3383 #endif /* !PERL_GET_CONTEXT_DEFINED */
3385 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3394 Perl_get_op_names(pTHX)
3396 PERL_UNUSED_CONTEXT;
3397 return (char **)PL_op_name;
3401 Perl_get_op_descs(pTHX)
3403 PERL_UNUSED_CONTEXT;
3404 return (char **)PL_op_desc;
3408 Perl_get_no_modify(pTHX)
3410 PERL_UNUSED_CONTEXT;
3411 return PL_no_modify;
3415 Perl_get_opargs(pTHX)
3417 PERL_UNUSED_CONTEXT;
3418 return (U32 *)PL_opargs;
3422 Perl_get_ppaddr(pTHX)
3425 PERL_UNUSED_CONTEXT;
3426 return (PPADDR_t*)PL_ppaddr;
3429 #ifndef HAS_GETENV_LEN
3431 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3433 char * const env_trans = PerlEnv_getenv(env_elem);
3434 PERL_UNUSED_CONTEXT;
3435 PERL_ARGS_ASSERT_GETENV_LEN;
3437 *len = strlen(env_trans);
3444 Perl_get_vtbl(pTHX_ int vtbl_id)
3446 PERL_UNUSED_CONTEXT;
3448 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3449 ? NULL : PL_magic_vtables + vtbl_id;
3453 Perl_my_fflush_all(pTHX)
3455 #if defined(USE_PERLIO) || defined(FFLUSH_NULL)
3456 return PerlIO_flush(NULL);
3458 # if defined(HAS__FWALK)
3459 extern int fflush(FILE *);
3460 /* undocumented, unprototyped, but very useful BSDism */
3461 extern void _fwalk(int (*)(FILE *));
3465 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3467 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3468 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3470 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3471 open_max = sysconf(_SC_OPEN_MAX);
3474 open_max = FOPEN_MAX;
3477 open_max = OPEN_MAX;
3488 for (i = 0; i < open_max; i++)
3489 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3490 STDIO_STREAM_ARRAY[i]._file < open_max &&
3491 STDIO_STREAM_ARRAY[i]._flag)
3492 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3496 SETERRNO(EBADF,RMS_IFI);
3503 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3505 if (ckWARN(WARN_IO)) {
3507 = gv && (isGV_with_GP(gv))
3510 const char * const direction = have == '>' ? "out" : "in";
3512 if (name && HEK_LEN(name))
3513 Perl_warner(aTHX_ packWARN(WARN_IO),
3514 "Filehandle %"HEKf" opened only for %sput",
3515 HEKfARG(name), direction);
3517 Perl_warner(aTHX_ packWARN(WARN_IO),
3518 "Filehandle opened only for %sput", direction);
3523 Perl_report_evil_fh(pTHX_ const GV *gv)
3525 const IO *io = gv ? GvIO(gv) : NULL;
3526 const PERL_BITFIELD16 op = PL_op->op_type;
3530 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3532 warn_type = WARN_CLOSED;
3536 warn_type = WARN_UNOPENED;
3539 if (ckWARN(warn_type)) {
3541 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3542 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3543 const char * const pars =
3544 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3545 const char * const func =
3547 (op == OP_READLINE || op == OP_RCATLINE
3548 ? "readline" : /* "<HANDLE>" not nice */
3549 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3551 const char * const type =
3553 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3554 ? "socket" : "filehandle");
3555 const bool have_name = name && SvCUR(name);
3556 Perl_warner(aTHX_ packWARN(warn_type),
3557 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3558 have_name ? " " : "",
3559 SVfARG(have_name ? name : &PL_sv_no));
3560 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3562 aTHX_ packWARN(warn_type),
3563 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3564 func, pars, have_name ? " " : "",
3565 SVfARG(have_name ? name : &PL_sv_no)
3570 /* To workaround core dumps from the uninitialised tm_zone we get the
3571 * system to give us a reasonable struct to copy. This fix means that
3572 * strftime uses the tm_zone and tm_gmtoff values returned by
3573 * localtime(time()). That should give the desired result most of the
3574 * time. But probably not always!
3576 * This does not address tzname aspects of NETaa14816.
3581 # ifndef STRUCT_TM_HASZONE
3582 # define STRUCT_TM_HASZONE
3586 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3587 # ifndef HAS_TM_TM_ZONE
3588 # define HAS_TM_TM_ZONE
3593 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3595 #ifdef HAS_TM_TM_ZONE
3597 const struct tm* my_tm;
3598 PERL_ARGS_ASSERT_INIT_TM;
3600 my_tm = localtime(&now);
3602 Copy(my_tm, ptm, 1, struct tm);
3604 PERL_ARGS_ASSERT_INIT_TM;
3605 PERL_UNUSED_ARG(ptm);
3610 * mini_mktime - normalise struct tm values without the localtime()
3611 * semantics (and overhead) of mktime().
3614 Perl_mini_mktime(pTHX_ struct tm *ptm)
3618 int month, mday, year, jday;
3619 int odd_cent, odd_year;
3620 PERL_UNUSED_CONTEXT;
3622 PERL_ARGS_ASSERT_MINI_MKTIME;
3624 #define DAYS_PER_YEAR 365
3625 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3626 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3627 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3628 #define SECS_PER_HOUR (60*60)
3629 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3630 /* parentheses deliberately absent on these two, otherwise they don't work */
3631 #define MONTH_TO_DAYS 153/5
3632 #define DAYS_TO_MONTH 5/153
3633 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3634 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3635 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3636 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3639 * Year/day algorithm notes:
3641 * With a suitable offset for numeric value of the month, one can find
3642 * an offset into the year by considering months to have 30.6 (153/5) days,
3643 * using integer arithmetic (i.e., with truncation). To avoid too much
3644 * messing about with leap days, we consider January and February to be
3645 * the 13th and 14th month of the previous year. After that transformation,
3646 * we need the month index we use to be high by 1 from 'normal human' usage,
3647 * so the month index values we use run from 4 through 15.
3649 * Given that, and the rules for the Gregorian calendar (leap years are those
3650 * divisible by 4 unless also divisible by 100, when they must be divisible
3651 * by 400 instead), we can simply calculate the number of days since some
3652 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3653 * the days we derive from our month index, and adding in the day of the
3654 * month. The value used here is not adjusted for the actual origin which
3655 * it normally would use (1 January A.D. 1), since we're not exposing it.
3656 * We're only building the value so we can turn around and get the
3657 * normalised values for the year, month, day-of-month, and day-of-year.
3659 * For going backward, we need to bias the value we're using so that we find
3660 * the right year value. (Basically, we don't want the contribution of
3661 * March 1st to the number to apply while deriving the year). Having done
3662 * that, we 'count up' the contribution to the year number by accounting for
3663 * full quadracenturies (400-year periods) with their extra leap days, plus
3664 * the contribution from full centuries (to avoid counting in the lost leap
3665 * days), plus the contribution from full quad-years (to count in the normal
3666 * leap days), plus the leftover contribution from any non-leap years.
3667 * At this point, if we were working with an actual leap day, we'll have 0
3668 * days left over. This is also true for March 1st, however. So, we have
3669 * to special-case that result, and (earlier) keep track of the 'odd'
3670 * century and year contributions. If we got 4 extra centuries in a qcent,
3671 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3672 * Otherwise, we add back in the earlier bias we removed (the 123 from
3673 * figuring in March 1st), find the month index (integer division by 30.6),
3674 * and the remainder is the day-of-month. We then have to convert back to
3675 * 'real' months (including fixing January and February from being 14/15 in
3676 * the previous year to being in the proper year). After that, to get
3677 * tm_yday, we work with the normalised year and get a new yearday value for
3678 * January 1st, which we subtract from the yearday value we had earlier,
3679 * representing the date we've re-built. This is done from January 1
3680 * because tm_yday is 0-origin.
3682 * Since POSIX time routines are only guaranteed to work for times since the
3683 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3684 * applies Gregorian calendar rules even to dates before the 16th century
3685 * doesn't bother me. Besides, you'd need cultural context for a given
3686 * date to know whether it was Julian or Gregorian calendar, and that's
3687 * outside the scope for this routine. Since we convert back based on the
3688 * same rules we used to build the yearday, you'll only get strange results
3689 * for input which needed normalising, or for the 'odd' century years which
3690 * were leap years in the Julian calendar but not in the Gregorian one.
3691 * I can live with that.
3693 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3694 * that's still outside the scope for POSIX time manipulation, so I don't
3698 year = 1900 + ptm->tm_year;
3699 month = ptm->tm_mon;
3700 mday = ptm->tm_mday;
3706 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3707 yearday += month*MONTH_TO_DAYS + mday + jday;
3709 * Note that we don't know when leap-seconds were or will be,
3710 * so we have to trust the user if we get something which looks
3711 * like a sensible leap-second. Wild values for seconds will
3712 * be rationalised, however.
3714 if ((unsigned) ptm->tm_sec <= 60) {
3721 secs += 60 * ptm->tm_min;
3722 secs += SECS_PER_HOUR * ptm->tm_hour;
3724 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3725 /* got negative remainder, but need positive time */
3726 /* back off an extra day to compensate */
3727 yearday += (secs/SECS_PER_DAY)-1;
3728 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3731 yearday += (secs/SECS_PER_DAY);
3732 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3735 else if (secs >= SECS_PER_DAY) {
3736 yearday += (secs/SECS_PER_DAY);
3737 secs %= SECS_PER_DAY;
3739 ptm->tm_hour = secs/SECS_PER_HOUR;
3740 secs %= SECS_PER_HOUR;
3741 ptm->tm_min = secs/60;
3743 ptm->tm_sec += secs;
3744 /* done with time of day effects */
3746 * The algorithm for yearday has (so far) left it high by 428.
3747 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3748 * bias it by 123 while trying to figure out what year it
3749 * really represents. Even with this tweak, the reverse
3750 * translation fails for years before A.D. 0001.
3751 * It would still fail for Feb 29, but we catch that one below.
3753 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3754 yearday -= YEAR_ADJUST;
3755 year = (yearday / DAYS_PER_QCENT) * 400;
3756 yearday %= DAYS_PER_QCENT;
3757 odd_cent = yearday / DAYS_PER_CENT;
3758 year += odd_cent * 100;
3759 yearday %= DAYS_PER_CENT;
3760 year += (yearday / DAYS_PER_QYEAR) * 4;
3761 yearday %= DAYS_PER_QYEAR;
3762 odd_year = yearday / DAYS_PER_YEAR;
3764 yearday %= DAYS_PER_YEAR;
3765 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3770 yearday += YEAR_ADJUST; /* recover March 1st crock */
3771 month = yearday*DAYS_TO_MONTH;
3772 yearday -= month*MONTH_TO_DAYS;
3773 /* recover other leap-year adjustment */
3782 ptm->tm_year = year - 1900;
3784 ptm->tm_mday = yearday;
3785 ptm->tm_mon = month;
3789 ptm->tm_mon = month - 1;
3791 /* re-build yearday based on Jan 1 to get tm_yday */
3793 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3794 yearday += 14*MONTH_TO_DAYS + 1;
3795 ptm->tm_yday = jday - yearday;
3796 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3800 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)
3808 PERL_ARGS_ASSERT_MY_STRFTIME;
3810 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3813 mytm.tm_hour = hour;
3814 mytm.tm_mday = mday;
3816 mytm.tm_year = year;
3817 mytm.tm_wday = wday;
3818 mytm.tm_yday = yday;
3819 mytm.tm_isdst = isdst;
3821 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3822 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3827 #ifdef HAS_TM_TM_GMTOFF
3828 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3830 #ifdef HAS_TM_TM_ZONE
3831 mytm.tm_zone = mytm2.tm_zone;
3836 Newx(buf, buflen, char);
3838 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
3839 len = strftime(buf, buflen, fmt, &mytm);
3843 ** The following is needed to handle to the situation where
3844 ** tmpbuf overflows. Basically we want to allocate a buffer
3845 ** and try repeatedly. The reason why it is so complicated
3846 ** is that getting a return value of 0 from strftime can indicate
3847 ** one of the following:
3848 ** 1. buffer overflowed,
3849 ** 2. illegal conversion specifier, or
3850 ** 3. the format string specifies nothing to be returned(not
3851 ** an error). This could be because format is an empty string
3852 ** or it specifies %p that yields an empty string in some locale.
3853 ** If there is a better way to make it portable, go ahead by
3856 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3859 /* Possibly buf overflowed - try again with a bigger buf */
3860 const int fmtlen = strlen(fmt);
3861 int bufsize = fmtlen + buflen;
3863 Renew(buf, bufsize, char);
3866 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
3867 buflen = strftime(buf, bufsize, fmt, &mytm);
3870 if (buflen > 0 && buflen < bufsize)
3872 /* heuristic to prevent out-of-memory errors */
3873 if (bufsize > 100*fmtlen) {
3879 Renew(buf, bufsize, char);
3884 Perl_croak(aTHX_ "panic: no strftime");
3890 #define SV_CWD_RETURN_UNDEF \
3891 sv_setsv(sv, &PL_sv_undef); \
3894 #define SV_CWD_ISDOT(dp) \
3895 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3896 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3899 =head1 Miscellaneous Functions
3901 =for apidoc getcwd_sv
3903 Fill the sv with current working directory
3908 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3909 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3910 * getcwd(3) if available
3911 * Comments from the orignal:
3912 * This is a faster version of getcwd. It's also more dangerous
3913 * because you might chdir out of a directory that you can't chdir
3917 Perl_getcwd_sv(pTHX_ SV *sv)
3923 PERL_ARGS_ASSERT_GETCWD_SV;
3927 char buf[MAXPATHLEN];
3929 /* Some getcwd()s automatically allocate a buffer of the given
3930 * size from the heap if they are given a NULL buffer pointer.
3931 * The problem is that this behaviour is not portable. */
3932 if (getcwd(buf, sizeof(buf) - 1)) {
3937 sv_setsv(sv, &PL_sv_undef);
3945 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3949 SvUPGRADE(sv, SVt_PV);
3951 if (PerlLIO_lstat(".", &statbuf) < 0) {
3952 SV_CWD_RETURN_UNDEF;
3955 orig_cdev = statbuf.st_dev;
3956 orig_cino = statbuf.st_ino;
3966 if (PerlDir_chdir("..") < 0) {
3967 SV_CWD_RETURN_UNDEF;
3969 if (PerlLIO_stat(".", &statbuf) < 0) {
3970 SV_CWD_RETURN_UNDEF;
3973 cdev = statbuf.st_dev;
3974 cino = statbuf.st_ino;
3976 if (odev == cdev && oino == cino) {
3979 if (!(dir = PerlDir_open("."))) {
3980 SV_CWD_RETURN_UNDEF;
3983 while ((dp = PerlDir_read(dir)) != NULL) {
3985 namelen = dp->d_namlen;
3987 namelen = strlen(dp->d_name);
3990 if (SV_CWD_ISDOT(dp)) {
3994 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3995 SV_CWD_RETURN_UNDEF;
3998 tdev = statbuf.st_dev;
3999 tino = statbuf.st_ino;
4000 if (tino == oino && tdev == odev) {
4006 SV_CWD_RETURN_UNDEF;
4009 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4010 SV_CWD_RETURN_UNDEF;
4013 SvGROW(sv, pathlen + namelen + 1);
4017 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4020 /* prepend current directory to the front */
4022 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4023 pathlen += (namelen + 1);
4025 #ifdef VOID_CLOSEDIR
4028 if (PerlDir_close(dir) < 0) {
4029 SV_CWD_RETURN_UNDEF;
4035 SvCUR_set(sv, pathlen);
4039 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4040 SV_CWD_RETURN_UNDEF;
4043 if (PerlLIO_stat(".", &statbuf) < 0) {
4044 SV_CWD_RETURN_UNDEF;
4047 cdev = statbuf.st_dev;
4048 cino = statbuf.st_ino;
4050 if (cdev != orig_cdev || cino != orig_cino) {
4051 Perl_croak(aTHX_ "Unstable directory path, "
4052 "current directory changed unexpectedly");
4065 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4066 # define EMULATE_SOCKETPAIR_UDP
4069 #ifdef EMULATE_SOCKETPAIR_UDP
4071 S_socketpair_udp (int fd[2]) {
4073 /* Fake a datagram socketpair using UDP to localhost. */
4074 int sockets[2] = {-1, -1};
4075 struct sockaddr_in addresses[2];
4077 Sock_size_t size = sizeof(struct sockaddr_in);
4078 unsigned short port;
4081 memset(&addresses, 0, sizeof(addresses));
4084 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4085 if (sockets[i] == -1)
4086 goto tidy_up_and_fail;
4088 addresses[i].sin_family = AF_INET;
4089 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4090 addresses[i].sin_port = 0; /* kernel choses port. */
4091 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4092 sizeof(struct sockaddr_in)) == -1)
4093 goto tidy_up_and_fail;
4096 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4097 for each connect the other socket to it. */
4100 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4102 goto tidy_up_and_fail;
4103 if (size != sizeof(struct sockaddr_in))
4104 goto abort_tidy_up_and_fail;
4105 /* !1 is 0, !0 is 1 */
4106 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4107 sizeof(struct sockaddr_in)) == -1)
4108 goto tidy_up_and_fail;
4111 /* Now we have 2 sockets connected to each other. I don't trust some other
4112 process not to have already sent a packet to us (by random) so send
4113 a packet from each to the other. */
4116 /* I'm going to send my own port number. As a short.
4117 (Who knows if someone somewhere has sin_port as a bitfield and needs
4118 this routine. (I'm assuming crays have socketpair)) */
4119 port = addresses[i].sin_port;
4120 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4121 if (got != sizeof(port)) {
4123 goto tidy_up_and_fail;
4124 goto abort_tidy_up_and_fail;
4128 /* Packets sent. I don't trust them to have arrived though.
4129 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4130 connect to localhost will use a second kernel thread. In 2.6 the
4131 first thread running the connect() returns before the second completes,
4132 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4133 returns 0. Poor programs have tripped up. One poor program's authors'
4134 had a 50-1 reverse stock split. Not sure how connected these were.)
4135 So I don't trust someone not to have an unpredictable UDP stack.
4139 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4140 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4144 FD_SET((unsigned int)sockets[0], &rset);
4145 FD_SET((unsigned int)sockets[1], &rset);
4147 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4148 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4149 || !FD_ISSET(sockets[1], &rset)) {
4150 /* I hope this is portable and appropriate. */
4152 goto tidy_up_and_fail;
4153 goto abort_tidy_up_and_fail;
4157 /* And the paranoia department even now doesn't trust it to have arrive
4158 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4160 struct sockaddr_in readfrom;
4161 unsigned short buffer[2];
4166 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4167 sizeof(buffer), MSG_DONTWAIT,
4168 (struct sockaddr *) &readfrom, &size);
4170 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4172 (struct sockaddr *) &readfrom, &size);
4176 goto tidy_up_and_fail;
4177 if (got != sizeof(port)
4178 || size != sizeof(struct sockaddr_in)
4179 /* Check other socket sent us its port. */
4180 || buffer[0] != (unsigned short) addresses[!i].sin_port
4181 /* Check kernel says we got the datagram from that socket */
4182 || readfrom.sin_family != addresses[!i].sin_family
4183 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4184 || readfrom.sin_port != addresses[!i].sin_port)
4185 goto abort_tidy_up_and_fail;
4188 /* My caller (my_socketpair) has validated that this is non-NULL */
4191 /* I hereby declare this connection open. May God bless all who cross
4195 abort_tidy_up_and_fail:
4196 errno = ECONNABORTED;
4200 if (sockets[0] != -1)
4201 PerlLIO_close(sockets[0]);
4202 if (sockets[1] != -1)
4203 PerlLIO_close(sockets[1]);
4208 #endif /* EMULATE_SOCKETPAIR_UDP */
4210 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4212 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4213 /* Stevens says that family must be AF_LOCAL, protocol 0.
4214 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4219 struct sockaddr_in listen_addr;
4220 struct sockaddr_in connect_addr;
4225 || family != AF_UNIX
4228 errno = EAFNOSUPPORT;
4236 #ifdef EMULATE_SOCKETPAIR_UDP
4237 if (type == SOCK_DGRAM)
4238 return S_socketpair_udp(fd);
4241 aTHXa(PERL_GET_THX);
4242 listener = PerlSock_socket(AF_INET, type, 0);
4245 memset(&listen_addr, 0, sizeof(listen_addr));
4246 listen_addr.sin_family = AF_INET;
4247 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4248 listen_addr.sin_port = 0; /* kernel choses port. */
4249 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4250 sizeof(listen_addr)) == -1)
4251 goto tidy_up_and_fail;
4252 if (PerlSock_listen(listener, 1) == -1)
4253 goto tidy_up_and_fail;
4255 connector = PerlSock_socket(AF_INET, type, 0);
4256 if (connector == -1)
4257 goto tidy_up_and_fail;
4258 /* We want to find out the port number to connect to. */
4259 size = sizeof(connect_addr);
4260 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4262 goto tidy_up_and_fail;
4263 if (size != sizeof(connect_addr))
4264 goto abort_tidy_up_and_fail;
4265 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4266 sizeof(connect_addr)) == -1)
4267 goto tidy_up_and_fail;
4269 size = sizeof(listen_addr);
4270 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4273 goto tidy_up_and_fail;
4274 if (size != sizeof(listen_addr))
4275 goto abort_tidy_up_and_fail;
4276 PerlLIO_close(listener);
4277 /* Now check we are talking to ourself by matching port and host on the
4279 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4281 goto tidy_up_and_fail;
4282 if (size != sizeof(connect_addr)
4283 || listen_addr.sin_family != connect_addr.sin_family
4284 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4285 || listen_addr.sin_port != connect_addr.sin_port) {
4286 goto abort_tidy_up_and_fail;
4292 abort_tidy_up_and_fail:
4294 errno = ECONNABORTED; /* This would be the standard thing to do. */
4296 # ifdef ECONNREFUSED
4297 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4299 errno = ETIMEDOUT; /* Desperation time. */
4306 PerlLIO_close(listener);
4307 if (connector != -1)
4308 PerlLIO_close(connector);
4310 PerlLIO_close(acceptor);
4316 /* In any case have a stub so that there's code corresponding
4317 * to the my_socketpair in embed.fnc. */
4319 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4320 #ifdef HAS_SOCKETPAIR
4321 return socketpair(family, type, protocol, fd);
4330 =for apidoc sv_nosharing
4332 Dummy routine which "shares" an SV when there is no sharing module present.
4333 Or "locks" it. Or "unlocks" it. In other
4334 words, ignores its single SV argument.
4335 Exists to avoid test for a NULL function pointer and because it could
4336 potentially warn under some level of strict-ness.
4342 Perl_sv_nosharing(pTHX_ SV *sv)
4344 PERL_UNUSED_CONTEXT;
4345 PERL_UNUSED_ARG(sv);
4350 =for apidoc sv_destroyable
4352 Dummy routine which reports that object can be destroyed when there is no
4353 sharing module present. It ignores its single SV argument, and returns
4354 'true'. Exists to avoid test for a NULL function pointer and because it
4355 could potentially warn under some level of strict-ness.
4361 Perl_sv_destroyable(pTHX_ SV *sv)
4363 PERL_UNUSED_CONTEXT;
4364 PERL_UNUSED_ARG(sv);
4369 Perl_parse_unicode_opts(pTHX_ const char **popt)
4371 const char *p = *popt;
4374 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
4378 opt = (U32) atoi(p);
4381 if (*p && *p != '\n' && *p != '\r') {
4382 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4384 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4390 case PERL_UNICODE_STDIN:
4391 opt |= PERL_UNICODE_STDIN_FLAG; break;
4392 case PERL_UNICODE_STDOUT:
4393 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4394 case PERL_UNICODE_STDERR:
4395 opt |= PERL_UNICODE_STDERR_FLAG; break;
4396 case PERL_UNICODE_STD:
4397 opt |= PERL_UNICODE_STD_FLAG; break;
4398 case PERL_UNICODE_IN:
4399 opt |= PERL_UNICODE_IN_FLAG; break;
4400 case PERL_UNICODE_OUT:
4401 opt |= PERL_UNICODE_OUT_FLAG; break;
4402 case PERL_UNICODE_INOUT:
4403 opt |= PERL_UNICODE_INOUT_FLAG; break;
4404 case PERL_UNICODE_LOCALE:
4405 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4406 case PERL_UNICODE_ARGV:
4407 opt |= PERL_UNICODE_ARGV_FLAG; break;
4408 case PERL_UNICODE_UTF8CACHEASSERT:
4409 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
4411 if (*p != '\n' && *p != '\r') {
4412 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4415 "Unknown Unicode option letter '%c'", *p);
4422 opt = PERL_UNICODE_DEFAULT_FLAGS;
4424 the_end_of_the_opts_parser:
4426 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4427 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4428 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4436 # include <starlet.h>
4444 * This is really just a quick hack which grabs various garbage
4445 * values. It really should be a real hash algorithm which
4446 * spreads the effect of every input bit onto every output bit,
4447 * if someone who knows about such things would bother to write it.
4448 * Might be a good idea to add that function to CORE as well.
4449 * No numbers below come from careful analysis or anything here,
4450 * except they are primes and SEED_C1 > 1E6 to get a full-width
4451 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4452 * probably be bigger too.
4455 # define SEED_C1 1000003
4456 #define SEED_C4 73819
4458 # define SEED_C1 25747
4459 #define SEED_C4 20639
4463 #define SEED_C5 26107
4465 #ifndef PERL_NO_DEV_RANDOM
4470 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4471 * in 100-ns units, typically incremented ever 10 ms. */
4472 unsigned int when[2];
4474 # ifdef HAS_GETTIMEOFDAY
4475 struct timeval when;
4481 /* This test is an escape hatch, this symbol isn't set by Configure. */
4482 #ifndef PERL_NO_DEV_RANDOM
4483 #ifndef PERL_RANDOM_DEVICE
4484 /* /dev/random isn't used by default because reads from it will block
4485 * if there isn't enough entropy available. You can compile with
4486 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4487 * is enough real entropy to fill the seed. */
4488 # define PERL_RANDOM_DEVICE "/dev/urandom"
4490 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4492 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4501 _ckvmssts(sys$gettim(when));
4502 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4504 # ifdef HAS_GETTIMEOFDAY
4505 PerlProc_gettimeofday(&when,NULL);
4506 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4509 u = (U32)SEED_C1 * when;
4512 u += SEED_C3 * (U32)PerlProc_getpid();
4513 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4514 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4515 u += SEED_C5 * (U32)PTR2UV(&when);
4521 Perl_get_hash_seed(pTHX_ unsigned char * const seed_buffer)
4527 PERL_ARGS_ASSERT_GET_HASH_SEED;
4529 env_pv= PerlEnv_getenv("PERL_HASH_SEED");
4532 #ifndef USE_HASH_SEED_EXPLICIT
4534 /* ignore leading spaces */
4535 while (isSPACE(*env_pv))
4537 #ifdef USE_PERL_PERTURB_KEYS
4538 /* if they set it to "0" we disable key traversal randomization completely */
4539 if (strEQ(env_pv,"0")) {
4540 PL_hash_rand_bits_enabled= 0;
4542 /* otherwise switch to deterministic mode */
4543 PL_hash_rand_bits_enabled= 2;
4546 /* ignore a leading 0x... if it is there */
4547 if (env_pv[0] == '0' && env_pv[1] == 'x')
4550 for( i = 0; isXDIGIT(*env_pv) && i < PERL_HASH_SEED_BYTES; i++ ) {
4551 seed_buffer[i] = READ_XDIGIT(env_pv) << 4;
4552 if ( isXDIGIT(*env_pv)) {
4553 seed_buffer[i] |= READ_XDIGIT(env_pv);
4556 while (isSPACE(*env_pv))
4559 if (*env_pv && !isXDIGIT(*env_pv)) {
4560 Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n");
4562 /* should we check for unparsed crap? */
4563 /* should we warn about unused hex? */
4564 /* should we warn about insufficient hex? */
4569 (void)seedDrand01((Rand_seed_t)seed());
4571 for( i = 0; i < PERL_HASH_SEED_BYTES; i++ ) {
4572 seed_buffer[i] = (unsigned char)(Drand01() * (U8_MAX+1));
4575 #ifdef USE_PERL_PERTURB_KEYS
4576 { /* initialize PL_hash_rand_bits from the hash seed.
4577 * This value is highly volatile, it is updated every
4578 * hash insert, and is used as part of hash bucket chain
4579 * randomization and hash iterator randomization. */
4580 PL_hash_rand_bits= 0xbe49d17f; /* I just picked a number */
4581 for( i = 0; i < sizeof(UV) ; i++ ) {
4582 PL_hash_rand_bits += seed_buffer[i % PERL_HASH_SEED_BYTES];
4583 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,8);
4586 env_pv= PerlEnv_getenv("PERL_PERTURB_KEYS");
4588 if (strEQ(env_pv,"0") || strEQ(env_pv,"NO")) {
4589 PL_hash_rand_bits_enabled= 0;
4590 } else if (strEQ(env_pv,"1") || strEQ(env_pv,"RANDOM")) {
4591 PL_hash_rand_bits_enabled= 1;
4592 } else if (strEQ(env_pv,"2") || strEQ(env_pv,"DETERMINISTIC")) {
4593 PL_hash_rand_bits_enabled= 2;
4595 Perl_warn(aTHX_ "perl: warning: strange setting in '$ENV{PERL_PERTURB_KEYS}': '%s'\n", env_pv);
4601 #ifdef PERL_GLOBAL_STRUCT
4603 #define PERL_GLOBAL_STRUCT_INIT
4604 #include "opcode.h" /* the ppaddr and check */
4607 Perl_init_global_struct(pTHX)
4609 struct perl_vars *plvarsp = NULL;
4610 # ifdef PERL_GLOBAL_STRUCT
4611 const IV nppaddr = C_ARRAY_LENGTH(Gppaddr);
4612 const IV ncheck = C_ARRAY_LENGTH(Gcheck);
4613 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4614 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
4615 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
4619 plvarsp = PL_VarsPtr;
4620 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
4625 # define PERLVAR(prefix,var,type) /**/
4626 # define PERLVARA(prefix,var,n,type) /**/
4627 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
4628 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
4629 # include "perlvars.h"
4634 # ifdef PERL_GLOBAL_STRUCT
4637 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
4638 if (!plvarsp->Gppaddr)
4642 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
4643 if (!plvarsp->Gcheck)
4645 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
4646 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
4648 # ifdef PERL_SET_VARS
4649 PERL_SET_VARS(plvarsp);
4651 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4652 plvarsp->Gsv_placeholder.sv_flags = 0;
4653 memset(plvarsp->Ghash_seed, 0, sizeof(plvarsp->Ghash_seed));
4655 # undef PERL_GLOBAL_STRUCT_INIT
4660 #endif /* PERL_GLOBAL_STRUCT */
4662 #ifdef PERL_GLOBAL_STRUCT
4665 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
4667 int veto = plvarsp->Gveto_cleanup;
4669 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
4670 # ifdef PERL_GLOBAL_STRUCT
4671 # ifdef PERL_UNSET_VARS
4672 PERL_UNSET_VARS(plvarsp);
4676 free(plvarsp->Gppaddr);
4677 free(plvarsp->Gcheck);
4678 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4684 #endif /* PERL_GLOBAL_STRUCT */
4688 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
4689 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
4690 * given, and you supply your own implementation.
4692 * The default implementation reads a single env var, PERL_MEM_LOG,
4693 * expecting one or more of the following:
4695 * \d+ - fd fd to write to : must be 1st (atoi)
4696 * 'm' - memlog was PERL_MEM_LOG=1
4697 * 's' - svlog was PERL_SV_LOG=1
4698 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
4700 * This makes the logger controllable enough that it can reasonably be
4701 * added to the system perl.
4704 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
4705 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
4707 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
4709 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
4710 * writes to. In the default logger, this is settable at runtime.
4712 #ifndef PERL_MEM_LOG_FD
4713 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
4716 #ifndef PERL_MEM_LOG_NOIMPL
4718 # ifdef DEBUG_LEAKING_SCALARS
4719 # define SV_LOG_SERIAL_FMT " [%lu]"
4720 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
4722 # define SV_LOG_SERIAL_FMT
4723 # define _SV_LOG_SERIAL_ARG(sv)
4727 S_mem_log_common(enum mem_log_type mlt, const UV n,
4728 const UV typesize, const char *type_name, const SV *sv,
4729 Malloc_t oldalloc, Malloc_t newalloc,
4730 const char *filename, const int linenumber,
4731 const char *funcname)
4735 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
4737 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
4740 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
4742 /* We can't use SVs or PerlIO for obvious reasons,
4743 * so we'll use stdio and low-level IO instead. */
4744 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
4746 # ifdef HAS_GETTIMEOFDAY
4747 # define MEM_LOG_TIME_FMT "%10d.%06d: "
4748 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
4750 gettimeofday(&tv, 0);
4752 # define MEM_LOG_TIME_FMT "%10d: "
4753 # define MEM_LOG_TIME_ARG (int)when
4757 /* If there are other OS specific ways of hires time than
4758 * gettimeofday() (see ext/Time-HiRes), the easiest way is
4759 * probably that they would be used to fill in the struct
4763 int fd = atoi(pmlenv);
4765 fd = PERL_MEM_LOG_FD;
4767 if (strchr(pmlenv, 't')) {
4768 len = my_snprintf(buf, sizeof(buf),
4769 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
4770 PerlLIO_write(fd, buf, len);
4774 len = my_snprintf(buf, sizeof(buf),
4775 "alloc: %s:%d:%s: %"IVdf" %"UVuf
4776 " %s = %"IVdf": %"UVxf"\n",
4777 filename, linenumber, funcname, n, typesize,
4778 type_name, n * typesize, PTR2UV(newalloc));
4781 len = my_snprintf(buf, sizeof(buf),
4782 "realloc: %s:%d:%s: %"IVdf" %"UVuf
4783 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
4784 filename, linenumber, funcname, n, typesize,
4785 type_name, n * typesize, PTR2UV(oldalloc),
4789 len = my_snprintf(buf, sizeof(buf),
4790 "free: %s:%d:%s: %"UVxf"\n",
4791 filename, linenumber, funcname,
4796 len = my_snprintf(buf, sizeof(buf),
4797 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
4798 mlt == MLT_NEW_SV ? "new" : "del",
4799 filename, linenumber, funcname,
4800 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
4805 PerlLIO_write(fd, buf, len);
4809 #endif /* !PERL_MEM_LOG_NOIMPL */
4811 #ifndef PERL_MEM_LOG_NOIMPL
4813 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
4814 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
4816 /* this is suboptimal, but bug compatible. User is providing their
4817 own implementation, but is getting these functions anyway, and they
4818 do nothing. But _NOIMPL users should be able to cope or fix */
4820 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
4821 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
4825 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
4827 const char *filename, const int linenumber,
4828 const char *funcname)
4830 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
4831 NULL, NULL, newalloc,
4832 filename, linenumber, funcname);
4837 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
4838 Malloc_t oldalloc, Malloc_t newalloc,
4839 const char *filename, const int linenumber,
4840 const char *funcname)
4842 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
4843 NULL, oldalloc, newalloc,
4844 filename, linenumber, funcname);
4849 Perl_mem_log_free(Malloc_t oldalloc,
4850 const char *filename, const int linenumber,
4851 const char *funcname)
4853 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
4854 filename, linenumber, funcname);
4859 Perl_mem_log_new_sv(const SV *sv,
4860 const char *filename, const int linenumber,
4861 const char *funcname)
4863 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
4864 filename, linenumber, funcname);
4868 Perl_mem_log_del_sv(const SV *sv,
4869 const char *filename, const int linenumber,
4870 const char *funcname)
4872 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
4873 filename, linenumber, funcname);
4876 #endif /* PERL_MEM_LOG */
4879 =for apidoc my_sprintf
4881 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
4882 the length of the string written to the buffer. Only rare pre-ANSI systems
4883 need the wrapper function - usually this is a direct call to C<sprintf>.
4887 #ifndef SPRINTF_RETURNS_STRLEN
4889 Perl_my_sprintf(char *buffer, const char* pat, ...)
4892 PERL_ARGS_ASSERT_MY_SPRINTF;
4893 va_start(args, pat);
4894 vsprintf(buffer, pat, args);
4896 return strlen(buffer);
4901 =for apidoc my_snprintf
4903 The C library C<snprintf> functionality, if available and
4904 standards-compliant (uses C<vsnprintf>, actually). However, if the
4905 C<vsnprintf> is not available, will unfortunately use the unsafe
4906 C<vsprintf> which can overrun the buffer (there is an overrun check,
4907 but that may be too late). Consider using C<sv_vcatpvf> instead, or
4908 getting C<vsnprintf>.
4913 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
4917 PERL_ARGS_ASSERT_MY_SNPRINTF;
4918 va_start(ap, format);
4919 #ifdef HAS_VSNPRINTF
4920 retval = vsnprintf(buffer, len, format, ap);
4922 retval = vsprintf(buffer, format, ap);
4925 /* vsprintf() shows failure with < 0 */
4927 #ifdef HAS_VSNPRINTF
4928 /* vsnprintf() shows failure with >= len */
4930 (len > 0 && (Size_t)retval >= len)
4933 Perl_croak_nocontext("panic: my_snprintf buffer overflow");
4938 =for apidoc my_vsnprintf
4940 The C library C<vsnprintf> if available and standards-compliant.
4941 However, if if the C<vsnprintf> is not available, will unfortunately
4942 use the unsafe C<vsprintf> which can overrun the buffer (there is an
4943 overrun check, but that may be too late). Consider using
4944 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
4949 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
4955 PERL_ARGS_ASSERT_MY_VSNPRINTF;
4957 Perl_va_copy(ap, apc);
4958 # ifdef HAS_VSNPRINTF
4959 retval = vsnprintf(buffer, len, format, apc);
4961 retval = vsprintf(buffer, format, apc);
4965 # ifdef HAS_VSNPRINTF
4966 retval = vsnprintf(buffer, len, format, ap);
4968 retval = vsprintf(buffer, format, ap);
4970 #endif /* #ifdef NEED_VA_COPY */
4971 /* vsprintf() shows failure with < 0 */
4973 #ifdef HAS_VSNPRINTF
4974 /* vsnprintf() shows failure with >= len */
4976 (len > 0 && (Size_t)retval >= len)
4979 Perl_croak_nocontext("panic: my_vsnprintf buffer overflow");
4984 Perl_my_clearenv(pTHX)
4987 #if ! defined(PERL_MICRO)
4988 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
4990 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
4991 # if defined(USE_ENVIRON_ARRAY)
4992 # if defined(USE_ITHREADS)
4993 /* only the parent thread can clobber the process environment */
4994 if (PL_curinterp == aTHX)
4995 # endif /* USE_ITHREADS */
4997 # if ! defined(PERL_USE_SAFE_PUTENV)
4998 if ( !PL_use_safe_putenv) {
5000 if (environ == PL_origenviron)
5001 environ = (char**)safesysmalloc(sizeof(char*));
5003 for (i = 0; environ[i]; i++)
5004 (void)safesysfree(environ[i]);
5007 # else /* PERL_USE_SAFE_PUTENV */
5008 # if defined(HAS_CLEARENV)
5010 # elif defined(HAS_UNSETENV)
5011 int bsiz = 80; /* Most envvar names will be shorter than this. */
5012 char *buf = (char*)safesysmalloc(bsiz);
5013 while (*environ != NULL) {
5014 char *e = strchr(*environ, '=');
5015 int l = e ? e - *environ : (int)strlen(*environ);
5017 (void)safesysfree(buf);
5018 bsiz = l + 1; /* + 1 for the \0. */
5019 buf = (char*)safesysmalloc(bsiz);
5021 memcpy(buf, *environ, l);
5023 (void)unsetenv(buf);
5025 (void)safesysfree(buf);
5026 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5027 /* Just null environ and accept the leakage. */
5029 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5030 # endif /* ! PERL_USE_SAFE_PUTENV */
5032 # endif /* USE_ENVIRON_ARRAY */
5033 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5034 #endif /* PERL_MICRO */
5037 #ifdef PERL_IMPLICIT_CONTEXT
5039 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
5040 the global PL_my_cxt_index is incremented, and that value is assigned to
5041 that module's static my_cxt_index (who's address is passed as an arg).
5042 Then, for each interpreter this function is called for, it makes sure a
5043 void* slot is available to hang the static data off, by allocating or
5044 extending the interpreter's PL_my_cxt_list array */
5046 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
5048 Perl_my_cxt_init(pTHX_ int *index, size_t size)
5052 PERL_ARGS_ASSERT_MY_CXT_INIT;
5054 /* this module hasn't been allocated an index yet */
5055 #if defined(USE_ITHREADS)
5056 MUTEX_LOCK(&PL_my_ctx_mutex);
5058 *index = PL_my_cxt_index++;
5059 #if defined(USE_ITHREADS)
5060 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5064 /* make sure the array is big enough */
5065 if (PL_my_cxt_size <= *index) {
5066 if (PL_my_cxt_size) {
5067 while (PL_my_cxt_size <= *index)
5068 PL_my_cxt_size *= 2;
5069 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5072 PL_my_cxt_size = 16;
5073 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5076 /* newSV() allocates one more than needed */
5077 p = (void*)SvPVX(newSV(size-1));
5078 PL_my_cxt_list[*index] = p;
5079 Zero(p, size, char);
5083 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5086 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
5091 PERL_ARGS_ASSERT_MY_CXT_INDEX;
5093 for (index = 0; index < PL_my_cxt_index; index++) {
5094 const char *key = PL_my_cxt_keys[index];
5095 /* try direct pointer compare first - there are chances to success,
5096 * and it's much faster.
5098 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
5105 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
5111 PERL_ARGS_ASSERT_MY_CXT_INIT;
5113 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
5115 /* this module hasn't been allocated an index yet */
5116 #if defined(USE_ITHREADS)