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 PERL_DEBUG_READONLY_COW
55 # include <sys/mman.h>
60 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
61 # define FD_CLOEXEC 1 /* NeXT needs this */
64 /* NOTE: Do not call the next three routines directly. Use the macros
65 * in handy.h, so that we can easily redefine everything to do tracking of
66 * allocated hunks back to the original New to track down any memory leaks.
67 * XXX This advice seems to be widely ignored :-( --AD August 1996.
70 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
71 # define ALWAYS_NEED_THX
74 #if defined(PERL_TRACK_MEMPOOL) && defined(PERL_DEBUG_READONLY_COW)
76 S_maybe_protect_rw(pTHX_ struct perl_memory_debug_header *header)
79 && mprotect(header, header->size, PROT_READ|PROT_WRITE))
80 Perl_warn(aTHX_ "mprotect for COW string %p %lu failed with %d",
81 header, header->size, errno);
85 S_maybe_protect_ro(pTHX_ struct perl_memory_debug_header *header)
88 && mprotect(header, header->size, PROT_READ))
89 Perl_warn(aTHX_ "mprotect RW for COW string %p %lu failed with %d",
90 header, header->size, errno);
92 # define maybe_protect_rw(foo) S_maybe_protect_rw(aTHX_ foo)
93 # define maybe_protect_ro(foo) S_maybe_protect_ro(aTHX_ foo)
95 # define maybe_protect_rw(foo) NOOP
96 # define maybe_protect_ro(foo) NOOP
99 #if defined(PERL_TRACK_MEMPOOL) || defined(PERL_DEBUG_READONLY_COW)
100 /* Use memory_debug_header */
102 # if (defined(PERL_POISON) && defined(PERL_TRACK_MEMPOOL)) \
103 || defined(PERL_DEBUG_READONLY_COW)
104 # define MDH_HAS_SIZE
108 /* paranoid version of system's malloc() */
111 Perl_safesysmalloc(MEM_SIZE size)
113 #ifdef ALWAYS_NEED_THX
117 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
119 if ((SSize_t)size < 0)
120 Perl_croak_nocontext("panic: malloc, size=%"UVuf, (UV) size);
122 if (!size) size = 1; /* malloc(0) is NASTY on our system */
123 #ifdef PERL_DEBUG_READONLY_COW
124 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
125 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
126 perror("mmap failed");
130 ptr = (Malloc_t)PerlMem_malloc(size?size:1);
132 PERL_ALLOC_CHECK(ptr);
135 struct perl_memory_debug_header *const header
136 = (struct perl_memory_debug_header *)ptr;
140 PoisonNew(((char *)ptr), size, char);
143 #ifdef PERL_TRACK_MEMPOOL
144 header->interpreter = aTHX;
145 /* Link us into the list. */
146 header->prev = &PL_memory_debug_header;
147 header->next = PL_memory_debug_header.next;
148 PL_memory_debug_header.next = header;
149 maybe_protect_rw(header->next);
150 header->next->prev = header;
151 maybe_protect_ro(header->next);
152 # ifdef PERL_DEBUG_READONLY_COW
153 header->readonly = 0;
159 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
160 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
164 #ifndef ALWAYS_NEED_THX
176 /* paranoid version of system's realloc() */
179 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
181 #ifdef ALWAYS_NEED_THX
185 #ifdef PERL_DEBUG_READONLY_COW
186 const MEM_SIZE oldsize = where
187 ? ((struct perl_memory_debug_header *)((char *)where - PERL_MEMORY_DEBUG_HEADER_SIZE))->size
190 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
191 Malloc_t PerlMem_realloc();
192 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
200 return safesysmalloc(size);
202 where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
203 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
205 struct perl_memory_debug_header *const header
206 = (struct perl_memory_debug_header *)where;
208 # ifdef PERL_TRACK_MEMPOOL
209 if (header->interpreter != aTHX) {
210 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
211 header->interpreter, aTHX);
213 assert(header->next->prev == header);
214 assert(header->prev->next == header);
216 if (header->size > size) {
217 const MEM_SIZE freed_up = header->size - size;
218 char *start_of_freed = ((char *)where) + size;
219 PoisonFree(start_of_freed, freed_up, char);
229 if ((SSize_t)size < 0)
230 Perl_croak_nocontext("panic: realloc, size=%"UVuf, (UV)size);
232 #ifdef PERL_DEBUG_READONLY_COW
233 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
234 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
235 perror("mmap failed");
238 Copy(where,ptr,oldsize < size ? oldsize : size,char);
239 if (munmap(where, oldsize)) {
240 perror("munmap failed");
244 ptr = (Malloc_t)PerlMem_realloc(where,size);
246 PERL_ALLOC_CHECK(ptr);
248 /* MUST do this fixup first, before doing ANYTHING else, as anything else
249 might allocate memory/free/move memory, and until we do the fixup, it
250 may well be chasing (and writing to) free memory. */
252 #ifdef PERL_TRACK_MEMPOOL
253 struct perl_memory_debug_header *const header
254 = (struct perl_memory_debug_header *)ptr;
257 if (header->size < size) {
258 const MEM_SIZE fresh = size - header->size;
259 char *start_of_fresh = ((char *)ptr) + size;
260 PoisonNew(start_of_fresh, fresh, char);
264 maybe_protect_rw(header->next);
265 header->next->prev = header;
266 maybe_protect_ro(header->next);
267 maybe_protect_rw(header->prev);
268 header->prev->next = header;
269 maybe_protect_ro(header->prev);
271 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
274 /* In particular, must do that fixup above before logging anything via
275 *printf(), as it can reallocate memory, which can cause SEGVs. */
277 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
278 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
285 #ifndef ALWAYS_NEED_THX
297 /* safe version of system's free() */
300 Perl_safesysfree(Malloc_t where)
302 #ifdef ALWAYS_NEED_THX
307 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
310 where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
312 struct perl_memory_debug_header *const header
313 = (struct perl_memory_debug_header *)where;
316 const MEM_SIZE size = header->size;
318 # ifdef PERL_TRACK_MEMPOOL
319 if (header->interpreter != aTHX) {
320 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
321 header->interpreter, aTHX);
324 Perl_croak_nocontext("panic: duplicate free");
327 Perl_croak_nocontext("panic: bad free, header->next==NULL");
328 if (header->next->prev != header || header->prev->next != header) {
329 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
330 "header=%p, ->prev->next=%p",
331 header->next->prev, header,
334 /* Unlink us from the chain. */
335 maybe_protect_rw(header->next);
336 header->next->prev = header->prev;
337 maybe_protect_ro(header->next);
338 maybe_protect_rw(header->prev);
339 header->prev->next = header->next;
340 maybe_protect_ro(header->prev);
341 maybe_protect_rw(header);
343 PoisonNew(where, size, char);
345 /* Trigger the duplicate free warning. */
348 # ifdef PERL_DEBUG_READONLY_COW
349 if (munmap(where, size)) {
350 perror("munmap failed");
356 #ifndef PERL_DEBUG_READONLY_COW
362 /* safe version of system's calloc() */
365 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
367 #ifdef ALWAYS_NEED_THX
371 #if defined(USE_MDH) || defined(DEBUGGING)
372 MEM_SIZE total_size = 0;
375 /* Even though calloc() for zero bytes is strange, be robust. */
376 if (size && (count <= MEM_SIZE_MAX / size)) {
377 #if defined(USE_MDH) || defined(DEBUGGING)
378 total_size = size * count;
384 if (PERL_MEMORY_DEBUG_HEADER_SIZE <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
385 total_size += PERL_MEMORY_DEBUG_HEADER_SIZE;
390 if ((SSize_t)size < 0 || (SSize_t)count < 0)
391 Perl_croak_nocontext("panic: calloc, size=%"UVuf", count=%"UVuf,
392 (UV)size, (UV)count);
394 #ifdef PERL_DEBUG_READONLY_COW
395 if ((ptr = mmap(0, total_size ? total_size : 1, PROT_READ|PROT_WRITE,
396 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
397 perror("mmap failed");
400 #elif defined(PERL_TRACK_MEMPOOL)
401 /* Have to use malloc() because we've added some space for our tracking
403 /* malloc(0) is non-portable. */
404 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
406 /* Use calloc() because it might save a memset() if the memory is fresh
407 and clean from the OS. */
409 ptr = (Malloc_t)PerlMem_calloc(count, size);
410 else /* calloc(0) is non-portable. */
411 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
413 PERL_ALLOC_CHECK(ptr);
414 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));
418 struct perl_memory_debug_header *const header
419 = (struct perl_memory_debug_header *)ptr;
421 # ifndef PERL_DEBUG_READONLY_COW
422 memset((void*)ptr, 0, total_size);
424 # ifdef PERL_TRACK_MEMPOOL
425 header->interpreter = aTHX;
426 /* Link us into the list. */
427 header->prev = &PL_memory_debug_header;
428 header->next = PL_memory_debug_header.next;
429 PL_memory_debug_header.next = header;
430 maybe_protect_rw(header->next);
431 header->next->prev = header;
432 maybe_protect_ro(header->next);
433 # ifdef PERL_DEBUG_READONLY_COW
434 header->readonly = 0;
438 header->size = total_size;
440 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
446 #ifndef ALWAYS_NEED_THX
455 /* These must be defined when not using Perl's malloc for binary
460 Malloc_t Perl_malloc (MEM_SIZE nbytes)
463 return (Malloc_t)PerlMem_malloc(nbytes);
466 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
469 return (Malloc_t)PerlMem_calloc(elements, size);
472 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
475 return (Malloc_t)PerlMem_realloc(where, nbytes);
478 Free_t Perl_mfree (Malloc_t where)
486 /* copy a string up to some (non-backslashed) delimiter, if any */
489 Perl_delimcpy(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen)
493 PERL_ARGS_ASSERT_DELIMCPY;
495 for (tolen = 0; from < fromend; from++, tolen++) {
497 if (from[1] != delim) {
504 else if (*from == delim)
515 /* return ptr to little string in big string, NULL if not found */
516 /* This routine was donated by Corey Satten. */
519 Perl_instr(const char *big, const char *little)
522 PERL_ARGS_ASSERT_INSTR;
524 /* libc prior to 4.6.27 (late 1994) did not work properly on a NULL
528 return strstr((char*)big, (char*)little);
531 /* same as instr but allow embedded nulls. The end pointers point to 1 beyond
532 * the final character desired to be checked */
535 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
537 PERL_ARGS_ASSERT_NINSTR;
541 const char first = *little;
543 bigend -= lend - little++;
545 while (big <= bigend) {
546 if (*big++ == first) {
547 for (x=big,s=little; s < lend; x++,s++) {
551 return (char*)(big-1);
558 /* reverse of the above--find last substring */
561 Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
564 const I32 first = *little;
565 const char * const littleend = lend;
567 PERL_ARGS_ASSERT_RNINSTR;
569 if (little >= littleend)
570 return (char*)bigend;
572 big = bigend - (littleend - little++);
573 while (big >= bigbeg) {
577 for (x=big+2,s=little; s < littleend; /**/ ) {
586 return (char*)(big+1);
591 /* As a space optimization, we do not compile tables for strings of length
592 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
593 special-cased in fbm_instr().
595 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
598 =head1 Miscellaneous Functions
600 =for apidoc fbm_compile
602 Analyses the string in order to make fast searches on it using fbm_instr()
603 -- the Boyer-Moore algorithm.
609 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
617 PERL_DEB( STRLEN rarest = 0 );
619 PERL_ARGS_ASSERT_FBM_COMPILE;
621 if (isGV_with_GP(sv) || SvROK(sv))
627 if (flags & FBMcf_TAIL) {
628 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
629 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
630 if (mg && mg->mg_len >= 0)
633 if (!SvPOK(sv) || SvNIOKp(sv))
634 s = (U8*)SvPV_force_mutable(sv, len);
635 else s = (U8 *)SvPV_mutable(sv, len);
636 if (len == 0) /* TAIL might be on a zero-length string. */
638 SvUPGRADE(sv, SVt_PVMG);
643 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
644 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
645 to call SvVALID_off() if the scalar was assigned to.
647 The comment itself (and "deeper magic" below) date back to
648 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
650 where the magic (presumably) was that the scalar had a BM table hidden
653 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
654 the table instead of the previous (somewhat hacky) approach of co-opting
655 the string buffer and storing it after the string. */
657 assert(!mg_find(sv, PERL_MAGIC_bm));
658 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
662 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
664 const U8 mlen = (len>255) ? 255 : (U8)len;
665 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
668 Newx(table, 256, U8);
669 memset((void*)table, mlen, 256);
670 mg->mg_ptr = (char *)table;
673 s += len - 1; /* last char */
676 if (table[*s] == mlen)
682 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
683 for (i = 0; i < len; i++) {
684 if (PL_freq[s[i]] < frequency) {
685 PERL_DEB( rarest = i );
686 frequency = PL_freq[s[i]];
689 BmUSEFUL(sv) = 100; /* Initial value */
690 if (flags & FBMcf_TAIL)
692 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
693 s[rarest], (UV)rarest));
696 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
697 /* If SvTAIL is actually due to \Z or \z, this gives false positives
701 =for apidoc fbm_instr
703 Returns the location of the SV in the string delimited by C<big> and
704 C<bigend>. It returns C<NULL> if the string can't be found. The C<sv>
705 does not have to be fbm_compiled, but the search will not be as fast
712 Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
716 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
717 STRLEN littlelen = l;
718 const I32 multiline = flags & FBMrf_MULTILINE;
720 PERL_ARGS_ASSERT_FBM_INSTR;
722 if ((STRLEN)(bigend - big) < littlelen) {
723 if ( SvTAIL(littlestr)
724 && ((STRLEN)(bigend - big) == littlelen - 1)
726 || (*big == *little &&
727 memEQ((char *)big, (char *)little, littlelen - 1))))
732 switch (littlelen) { /* Special cases for 0, 1 and 2 */
734 return (char*)big; /* Cannot be SvTAIL! */
736 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
737 /* Know that bigend != big. */
738 if (bigend[-1] == '\n')
739 return (char *)(bigend - 1);
740 return (char *) bigend;
748 if (SvTAIL(littlestr))
749 return (char *) bigend;
752 if (SvTAIL(littlestr) && !multiline) {
753 if (bigend[-1] == '\n' && bigend[-2] == *little)
754 return (char*)bigend - 2;
755 if (bigend[-1] == *little)
756 return (char*)bigend - 1;
760 /* This should be better than FBM if c1 == c2, and almost
761 as good otherwise: maybe better since we do less indirection.
762 And we save a lot of memory by caching no table. */
763 const unsigned char c1 = little[0];
764 const unsigned char c2 = little[1];
769 while (s <= bigend) {
779 goto check_1char_anchor;
790 goto check_1char_anchor;
793 while (s <= bigend) {
798 goto check_1char_anchor;
807 check_1char_anchor: /* One char and anchor! */
808 if (SvTAIL(littlestr) && (*bigend == *little))
809 return (char *)bigend; /* bigend is already decremented. */
812 break; /* Only lengths 0 1 and 2 have special-case code. */
815 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
816 s = bigend - littlelen;
817 if (s >= big && bigend[-1] == '\n' && *s == *little
818 /* Automatically of length > 2 */
819 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
821 return (char*)s; /* how sweet it is */
824 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
826 return (char*)s + 1; /* how sweet it is */
830 if (!SvVALID(littlestr)) {
831 char * const b = ninstr((char*)big,(char*)bigend,
832 (char*)little, (char*)little + littlelen);
834 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
835 /* Chop \n from littlestr: */
836 s = bigend - littlelen + 1;
838 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
848 if (littlelen > (STRLEN)(bigend - big))
852 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
853 const unsigned char *oldlittle;
857 --littlelen; /* Last char found by table lookup */
860 little += littlelen; /* last char */
863 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
867 if ((tmp = table[*s])) {
868 if ((s += tmp) < bigend)
872 else { /* less expensive than calling strncmp() */
873 unsigned char * const olds = s;
878 if (*--s == *--little)
880 s = olds + 1; /* here we pay the price for failure */
882 if (s < bigend) /* fake up continue to outer loop */
892 && memEQ((char *)(bigend - littlelen),
893 (char *)(oldlittle - littlelen), littlelen) )
894 return (char*)bigend - littlelen;
900 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
903 PERL_ARGS_ASSERT_SCREAMINSTR;
904 PERL_UNUSED_ARG(bigstr);
905 PERL_UNUSED_ARG(littlestr);
906 PERL_UNUSED_ARG(start_shift);
907 PERL_UNUSED_ARG(end_shift);
908 PERL_UNUSED_ARG(old_posp);
909 PERL_UNUSED_ARG(last);
911 /* This function must only ever be called on a scalar with study magic,
912 but those do not happen any more. */
913 Perl_croak(aTHX_ "panic: screaminstr");
920 Returns true if the leading len bytes of the strings s1 and s2 are the same
921 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
922 match themselves and their opposite case counterparts. Non-cased and non-ASCII
923 range bytes match only themselves.
930 Perl_foldEQ(const char *s1, const char *s2, I32 len)
932 const U8 *a = (const U8 *)s1;
933 const U8 *b = (const U8 *)s2;
935 PERL_ARGS_ASSERT_FOLDEQ;
940 if (*a != *b && *a != PL_fold[*b])
947 Perl_foldEQ_latin1(const char *s1, const char *s2, I32 len)
949 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
950 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
951 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
952 * does it check that the strings each have at least 'len' characters */
954 const U8 *a = (const U8 *)s1;
955 const U8 *b = (const U8 *)s2;
957 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
962 if (*a != *b && *a != PL_fold_latin1[*b]) {
971 =for apidoc foldEQ_locale
973 Returns true if the leading len bytes of the strings s1 and s2 are the same
974 case-insensitively in the current locale; false otherwise.
980 Perl_foldEQ_locale(const char *s1, const char *s2, I32 len)
983 const U8 *a = (const U8 *)s1;
984 const U8 *b = (const U8 *)s2;
986 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
991 if (*a != *b && *a != PL_fold_locale[*b])
998 /* copy a string to a safe spot */
1001 =head1 Memory Management
1005 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1006 string which is a duplicate of C<pv>. The size of the string is
1007 determined by C<strlen()>. The memory allocated for the new string can
1008 be freed with the C<Safefree()> function.
1010 On some platforms, Windows for example, all allocated memory owned by a thread
1011 is deallocated when that thread ends. So if you need that not to happen, you
1012 need to use the shared memory functions, such as C<L</savesharedpv>>.
1018 Perl_savepv(pTHX_ const char *pv)
1020 PERL_UNUSED_CONTEXT;
1025 const STRLEN pvlen = strlen(pv)+1;
1026 Newx(newaddr, pvlen, char);
1027 return (char*)memcpy(newaddr, pv, pvlen);
1031 /* same thing but with a known length */
1036 Perl's version of what C<strndup()> would be if it existed. Returns a
1037 pointer to a newly allocated string which is a duplicate of the first
1038 C<len> bytes from C<pv>, plus a trailing
1039 NUL byte. The memory allocated for
1040 the new string can be freed with the C<Safefree()> function.
1042 On some platforms, Windows for example, all allocated memory owned by a thread
1043 is deallocated when that thread ends. So if you need that not to happen, you
1044 need to use the shared memory functions, such as C<L</savesharedpvn>>.
1050 Perl_savepvn(pTHX_ const char *pv, I32 len)
1053 PERL_UNUSED_CONTEXT;
1057 Newx(newaddr,len+1,char);
1058 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1060 /* might not be null terminated */
1061 newaddr[len] = '\0';
1062 return (char *) CopyD(pv,newaddr,len,char);
1065 return (char *) ZeroD(newaddr,len+1,char);
1070 =for apidoc savesharedpv
1072 A version of C<savepv()> which allocates the duplicate string in memory
1073 which is shared between threads.
1078 Perl_savesharedpv(pTHX_ const char *pv)
1085 pvlen = strlen(pv)+1;
1086 newaddr = (char*)PerlMemShared_malloc(pvlen);
1090 return (char*)memcpy(newaddr, pv, pvlen);
1094 =for apidoc savesharedpvn
1096 A version of C<savepvn()> which allocates the duplicate string in memory
1097 which is shared between threads. (With the specific difference that a NULL
1098 pointer is not acceptable)
1103 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1105 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1107 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1112 newaddr[len] = '\0';
1113 return (char*)memcpy(newaddr, pv, len);
1117 =for apidoc savesvpv
1119 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1120 the passed in SV using C<SvPV()>
1122 On some platforms, Windows for example, all allocated memory owned by a thread
1123 is deallocated when that thread ends. So if you need that not to happen, you
1124 need to use the shared memory functions, such as C<L</savesharedsvpv>>.
1130 Perl_savesvpv(pTHX_ SV *sv)
1133 const char * const pv = SvPV_const(sv, len);
1136 PERL_ARGS_ASSERT_SAVESVPV;
1139 Newx(newaddr,len,char);
1140 return (char *) CopyD(pv,newaddr,len,char);
1144 =for apidoc savesharedsvpv
1146 A version of C<savesharedpv()> which allocates the duplicate string in
1147 memory which is shared between threads.
1153 Perl_savesharedsvpv(pTHX_ SV *sv)
1156 const char * const pv = SvPV_const(sv, len);
1158 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1160 return savesharedpvn(pv, len);
1163 /* the SV for Perl_form() and mess() is not kept in an arena */
1172 if (PL_phase != PERL_PHASE_DESTRUCT)
1173 return newSVpvs_flags("", SVs_TEMP);
1178 /* Create as PVMG now, to avoid any upgrading later */
1180 Newxz(any, 1, XPVMG);
1181 SvFLAGS(sv) = SVt_PVMG;
1182 SvANY(sv) = (void*)any;
1184 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1189 #if defined(PERL_IMPLICIT_CONTEXT)
1191 Perl_form_nocontext(const char* pat, ...)
1196 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1197 va_start(args, pat);
1198 retval = vform(pat, &args);
1202 #endif /* PERL_IMPLICIT_CONTEXT */
1205 =head1 Miscellaneous Functions
1208 Takes a sprintf-style format pattern and conventional
1209 (non-SV) arguments and returns the formatted string.
1211 (char *) Perl_form(pTHX_ const char* pat, ...)
1213 can be used any place a string (char *) is required:
1215 char * s = Perl_form("%d.%d",major,minor);
1217 Uses a single private buffer so if you want to format several strings you
1218 must explicitly copy the earlier strings away (and free the copies when you
1225 Perl_form(pTHX_ const char* pat, ...)
1229 PERL_ARGS_ASSERT_FORM;
1230 va_start(args, pat);
1231 retval = vform(pat, &args);
1237 Perl_vform(pTHX_ const char *pat, va_list *args)
1239 SV * const sv = mess_alloc();
1240 PERL_ARGS_ASSERT_VFORM;
1241 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1246 =for apidoc Am|SV *|mess|const char *pat|...
1248 Take a sprintf-style format pattern and argument list. These are used to
1249 generate a string message. If the message does not end with a newline,
1250 then it will be extended with some indication of the current location
1251 in the code, as described for L</mess_sv>.
1253 Normally, the resulting message is returned in a new mortal SV.
1254 During global destruction a single SV may be shared between uses of
1260 #if defined(PERL_IMPLICIT_CONTEXT)
1262 Perl_mess_nocontext(const char *pat, ...)
1267 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1268 va_start(args, pat);
1269 retval = vmess(pat, &args);
1273 #endif /* PERL_IMPLICIT_CONTEXT */
1276 Perl_mess(pTHX_ const char *pat, ...)
1280 PERL_ARGS_ASSERT_MESS;
1281 va_start(args, pat);
1282 retval = vmess(pat, &args);
1288 Perl_closest_cop(pTHX_ const COP *cop, const OP *o, const OP *curop,
1292 /* Look for curop starting from o. cop is the last COP we've seen. */
1293 /* opnext means that curop is actually the ->op_next of the op we are
1296 PERL_ARGS_ASSERT_CLOSEST_COP;
1298 if (!o || !curop || (
1299 opnext ? o->op_next == curop && o->op_type != OP_SCOPE : o == curop
1303 if (o->op_flags & OPf_KIDS) {
1305 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1308 /* If the OP_NEXTSTATE has been optimised away we can still use it
1309 * the get the file and line number. */
1311 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1312 cop = (const COP *)kid;
1314 /* Keep searching, and return when we've found something. */
1316 new_cop = closest_cop(cop, kid, curop, opnext);
1322 /* Nothing found. */
1328 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1330 Expands a message, intended for the user, to include an indication of
1331 the current location in the code, if the message does not already appear
1334 C<basemsg> is the initial message or object. If it is a reference, it
1335 will be used as-is and will be the result of this function. Otherwise it
1336 is used as a string, and if it already ends with a newline, it is taken
1337 to be complete, and the result of this function will be the same string.
1338 If the message does not end with a newline, then a segment such as C<at
1339 foo.pl line 37> will be appended, and possibly other clauses indicating
1340 the current state of execution. The resulting message will end with a
1343 Normally, the resulting message is returned in a new mortal SV.
1344 During global destruction a single SV may be shared between uses of this
1345 function. If C<consume> is true, then the function is permitted (but not
1346 required) to modify and return C<basemsg> instead of allocating a new SV.
1352 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1357 PERL_ARGS_ASSERT_MESS_SV;
1359 if (SvROK(basemsg)) {
1365 sv_setsv(sv, basemsg);
1370 if (SvPOK(basemsg) && consume) {
1375 sv_copypv(sv, basemsg);
1378 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1380 * Try and find the file and line for PL_op. This will usually be
1381 * PL_curcop, but it might be a cop that has been optimised away. We
1382 * can try to find such a cop by searching through the optree starting
1383 * from the sibling of PL_curcop.
1387 closest_cop(PL_curcop, PL_curcop->op_sibling, PL_op, FALSE);
1392 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1393 OutCopFILE(cop), (IV)CopLINE(cop));
1394 /* Seems that GvIO() can be untrustworthy during global destruction. */
1395 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1396 && IoLINES(GvIOp(PL_last_in_gv)))
1399 const bool line_mode = (RsSIMPLE(PL_rs) &&
1400 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1401 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1402 SVfARG(PL_last_in_gv == PL_argvgv
1404 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1405 line_mode ? "line" : "chunk",
1406 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1408 if (PL_phase == PERL_PHASE_DESTRUCT)
1409 sv_catpvs(sv, " during global destruction");
1410 sv_catpvs(sv, ".\n");
1416 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1418 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1419 argument list. These are used to generate a string message. If the
1420 message does not end with a newline, then it will be extended with
1421 some indication of the current location in the code, as described for
1424 Normally, the resulting message is returned in a new mortal SV.
1425 During global destruction a single SV may be shared between uses of
1432 Perl_vmess(pTHX_ const char *pat, va_list *args)
1435 SV * const sv = mess_alloc();
1437 PERL_ARGS_ASSERT_VMESS;
1439 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1440 return mess_sv(sv, 1);
1444 Perl_write_to_stderr(pTHX_ SV* msv)
1450 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1452 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1453 && (io = GvIO(PL_stderrgv))
1454 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1455 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, SV_CONST(PRINT),
1456 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1458 PerlIO * const serr = Perl_error_log;
1460 do_print(msv, serr);
1461 (void)PerlIO_flush(serr);
1466 =head1 Warning and Dieing
1469 /* Common code used in dieing and warning */
1472 S_with_queued_errors(pTHX_ SV *ex)
1474 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1475 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1476 sv_catsv(PL_errors, ex);
1477 ex = sv_mortalcopy(PL_errors);
1478 SvCUR_set(PL_errors, 0);
1484 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1490 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1491 /* sv_2cv might call Perl_croak() or Perl_warner() */
1492 SV * const oldhook = *hook;
1500 cv = sv_2cv(oldhook, &stash, &gv, 0);
1502 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1512 exarg = newSVsv(ex);
1513 SvREADONLY_on(exarg);
1516 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1520 call_sv(MUTABLE_SV(cv), G_DISCARD);
1529 =for apidoc Am|OP *|die_sv|SV *baseex
1531 Behaves the same as L</croak_sv>, except for the return type.
1532 It should be used only where the C<OP *> return type is required.
1533 The function never actually returns.
1539 Perl_die_sv(pTHX_ SV *baseex)
1541 PERL_ARGS_ASSERT_DIE_SV;
1543 assert(0); /* NOTREACHED */
1548 =for apidoc Am|OP *|die|const char *pat|...
1550 Behaves the same as L</croak>, except for the return type.
1551 It should be used only where the C<OP *> return type is required.
1552 The function never actually returns.
1557 #if defined(PERL_IMPLICIT_CONTEXT)
1559 Perl_die_nocontext(const char* pat, ...)
1563 va_start(args, pat);
1565 assert(0); /* NOTREACHED */
1569 #endif /* PERL_IMPLICIT_CONTEXT */
1572 Perl_die(pTHX_ const char* pat, ...)
1575 va_start(args, pat);
1577 assert(0); /* NOTREACHED */
1583 =for apidoc Am|void|croak_sv|SV *baseex
1585 This is an XS interface to Perl's C<die> function.
1587 C<baseex> is the error message or object. If it is a reference, it
1588 will be used as-is. Otherwise it is used as a string, and if it does
1589 not end with a newline then it will be extended with some indication of
1590 the current location in the code, as described for L</mess_sv>.
1592 The error message or object will be used as an exception, by default
1593 returning control to the nearest enclosing C<eval>, but subject to
1594 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1595 function never returns normally.
1597 To die with a simple string message, the L</croak> function may be
1604 Perl_croak_sv(pTHX_ SV *baseex)
1606 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1607 PERL_ARGS_ASSERT_CROAK_SV;
1608 invoke_exception_hook(ex, FALSE);
1613 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1615 This is an XS interface to Perl's C<die> function.
1617 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1618 argument list. These are used to generate a string message. If the
1619 message does not end with a newline, then it will be extended with
1620 some indication of the current location in the code, as described for
1623 The error message will be used as an exception, by default
1624 returning control to the nearest enclosing C<eval>, but subject to
1625 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1626 function never returns normally.
1628 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1629 (C<$@>) will be used as an error message or object instead of building an
1630 error message from arguments. If you want to throw a non-string object,
1631 or build an error message in an SV yourself, it is preferable to use
1632 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1638 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1640 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1641 invoke_exception_hook(ex, FALSE);
1646 =for apidoc Am|void|croak|const char *pat|...
1648 This is an XS interface to Perl's C<die> function.
1650 Take a sprintf-style format pattern and argument list. These are used to
1651 generate a string message. If the message does not end with a newline,
1652 then it will be extended with some indication of the current location
1653 in the code, as described for L</mess_sv>.
1655 The error message will be used as an exception, by default
1656 returning control to the nearest enclosing C<eval>, but subject to
1657 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1658 function never returns normally.
1660 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1661 (C<$@>) will be used as an error message or object instead of building an
1662 error message from arguments. If you want to throw a non-string object,
1663 or build an error message in an SV yourself, it is preferable to use
1664 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1669 #if defined(PERL_IMPLICIT_CONTEXT)
1671 Perl_croak_nocontext(const char *pat, ...)
1675 va_start(args, pat);
1677 assert(0); /* NOTREACHED */
1680 #endif /* PERL_IMPLICIT_CONTEXT */
1683 Perl_croak(pTHX_ const char *pat, ...)
1686 va_start(args, pat);
1688 assert(0); /* NOTREACHED */
1693 =for apidoc Am|void|croak_no_modify
1695 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1696 terser object code than using C<Perl_croak>. Less code used on exception code
1697 paths reduces CPU cache pressure.
1703 Perl_croak_no_modify(void)
1705 Perl_croak_nocontext( "%s", PL_no_modify);
1708 /* does not return, used in util.c perlio.c and win32.c
1709 This is typically called when malloc returns NULL.
1712 Perl_croak_no_mem(void)
1716 int fd = PerlIO_fileno(Perl_error_log);
1718 SETERRNO(EBADF,RMS_IFI);
1720 /* Can't use PerlIO to write as it allocates memory */
1721 int rc = PerlLIO_write(fd, PL_no_mem, sizeof(PL_no_mem)-1);
1722 /* silently ignore failures */
1723 PERL_UNUSED_VAR(rc);
1728 /* does not return, used only in POPSTACK */
1730 Perl_croak_popstack(void)
1733 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
1738 =for apidoc Am|void|warn_sv|SV *baseex
1740 This is an XS interface to Perl's C<warn> function.
1742 C<baseex> is the error message or object. If it is a reference, it
1743 will be used as-is. Otherwise it is used as a string, and if it does
1744 not end with a newline then it will be extended with some indication of
1745 the current location in the code, as described for L</mess_sv>.
1747 The error message or object will by default be written to standard error,
1748 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1750 To warn with a simple string message, the L</warn> function may be
1757 Perl_warn_sv(pTHX_ SV *baseex)
1759 SV *ex = mess_sv(baseex, 0);
1760 PERL_ARGS_ASSERT_WARN_SV;
1761 if (!invoke_exception_hook(ex, TRUE))
1762 write_to_stderr(ex);
1766 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1768 This is an XS interface to Perl's C<warn> function.
1770 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1771 argument list. These are used to generate a string message. If the
1772 message does not end with a newline, then it will be extended with
1773 some indication of the current location in the code, as described for
1776 The error message or object will by default be written to standard error,
1777 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1779 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1785 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1787 SV *ex = vmess(pat, args);
1788 PERL_ARGS_ASSERT_VWARN;
1789 if (!invoke_exception_hook(ex, TRUE))
1790 write_to_stderr(ex);
1794 =for apidoc Am|void|warn|const char *pat|...
1796 This is an XS interface to Perl's C<warn> function.
1798 Take a sprintf-style format pattern and argument list. These are used to
1799 generate a string message. If the message does not end with a newline,
1800 then it will be extended with some indication of the current location
1801 in the code, as described for L</mess_sv>.
1803 The error message or object will by default be written to standard error,
1804 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1806 Unlike with L</croak>, C<pat> is not permitted to be null.
1811 #if defined(PERL_IMPLICIT_CONTEXT)
1813 Perl_warn_nocontext(const char *pat, ...)
1817 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1818 va_start(args, pat);
1822 #endif /* PERL_IMPLICIT_CONTEXT */
1825 Perl_warn(pTHX_ const char *pat, ...)
1828 PERL_ARGS_ASSERT_WARN;
1829 va_start(args, pat);
1834 #if defined(PERL_IMPLICIT_CONTEXT)
1836 Perl_warner_nocontext(U32 err, const char *pat, ...)
1840 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1841 va_start(args, pat);
1842 vwarner(err, pat, &args);
1845 #endif /* PERL_IMPLICIT_CONTEXT */
1848 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1850 PERL_ARGS_ASSERT_CK_WARNER_D;
1852 if (Perl_ckwarn_d(aTHX_ err)) {
1854 va_start(args, pat);
1855 vwarner(err, pat, &args);
1861 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1863 PERL_ARGS_ASSERT_CK_WARNER;
1865 if (Perl_ckwarn(aTHX_ err)) {
1867 va_start(args, pat);
1868 vwarner(err, pat, &args);
1874 Perl_warner(pTHX_ U32 err, const char* pat,...)
1877 PERL_ARGS_ASSERT_WARNER;
1878 va_start(args, pat);
1879 vwarner(err, pat, &args);
1884 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1887 PERL_ARGS_ASSERT_VWARNER;
1888 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1889 SV * const msv = vmess(pat, args);
1891 invoke_exception_hook(msv, FALSE);
1895 Perl_vwarn(aTHX_ pat, args);
1899 /* implements the ckWARN? macros */
1902 Perl_ckwarn(pTHX_ U32 w)
1905 /* If lexical warnings have not been set, use $^W. */
1907 return PL_dowarn & G_WARN_ON;
1909 return ckwarn_common(w);
1912 /* implements the ckWARN?_d macro */
1915 Perl_ckwarn_d(pTHX_ U32 w)
1918 /* If lexical warnings have not been set then default classes warn. */
1922 return ckwarn_common(w);
1926 S_ckwarn_common(pTHX_ U32 w)
1928 if (PL_curcop->cop_warnings == pWARN_ALL)
1931 if (PL_curcop->cop_warnings == pWARN_NONE)
1934 /* Check the assumption that at least the first slot is non-zero. */
1935 assert(unpackWARN1(w));
1937 /* Check the assumption that it is valid to stop as soon as a zero slot is
1939 if (!unpackWARN2(w)) {
1940 assert(!unpackWARN3(w));
1941 assert(!unpackWARN4(w));
1942 } else if (!unpackWARN3(w)) {
1943 assert(!unpackWARN4(w));
1946 /* Right, dealt with all the special cases, which are implemented as non-
1947 pointers, so there is a pointer to a real warnings mask. */
1949 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1951 } while (w >>= WARNshift);
1956 /* Set buffer=NULL to get a new one. */
1958 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1960 const MEM_SIZE len_wanted =
1961 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
1962 PERL_UNUSED_CONTEXT;
1963 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1966 (specialWARN(buffer) ?
1967 PerlMemShared_malloc(len_wanted) :
1968 PerlMemShared_realloc(buffer, len_wanted));
1970 Copy(bits, (buffer + 1), size, char);
1971 if (size < WARNsize)
1972 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
1976 /* since we've already done strlen() for both nam and val
1977 * we can use that info to make things faster than
1978 * sprintf(s, "%s=%s", nam, val)
1980 #define my_setenv_format(s, nam, nlen, val, vlen) \
1981 Copy(nam, s, nlen, char); \
1983 Copy(val, s+(nlen+1), vlen, char); \
1984 *(s+(nlen+1+vlen)) = '\0'
1986 #ifdef USE_ENVIRON_ARRAY
1987 /* VMS' my_setenv() is in vms.c */
1988 #if !defined(WIN32) && !defined(NETWARE)
1990 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1994 /* only parent thread can modify process environment */
1995 if (PL_curinterp == aTHX)
1998 #ifndef PERL_USE_SAFE_PUTENV
1999 if (!PL_use_safe_putenv) {
2000 /* most putenv()s leak, so we manipulate environ directly */
2002 const I32 len = strlen(nam);
2005 /* where does it go? */
2006 for (i = 0; environ[i]; i++) {
2007 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
2011 if (environ == PL_origenviron) { /* need we copy environment? */
2017 while (environ[max])
2019 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2020 for (j=0; j<max; j++) { /* copy environment */
2021 const int len = strlen(environ[j]);
2022 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2023 Copy(environ[j], tmpenv[j], len+1, char);
2026 environ = tmpenv; /* tell exec where it is now */
2029 safesysfree(environ[i]);
2030 while (environ[i]) {
2031 environ[i] = environ[i+1];
2036 if (!environ[i]) { /* does not exist yet */
2037 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2038 environ[i+1] = NULL; /* make sure it's null terminated */
2041 safesysfree(environ[i]);
2045 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2046 /* all that work just for this */
2047 my_setenv_format(environ[i], nam, nlen, val, vlen);
2050 # if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__)
2051 # if defined(HAS_UNSETENV)
2053 (void)unsetenv(nam);
2055 (void)setenv(nam, val, 1);
2057 # else /* ! HAS_UNSETENV */
2058 (void)setenv(nam, val, 1);
2059 # endif /* HAS_UNSETENV */
2061 # if defined(HAS_UNSETENV)
2063 if (environ) /* old glibc can crash with null environ */
2064 (void)unsetenv(nam);
2066 const int nlen = strlen(nam);
2067 const int vlen = strlen(val);
2068 char * const new_env =
2069 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2070 my_setenv_format(new_env, nam, nlen, val, vlen);
2071 (void)putenv(new_env);
2073 # else /* ! HAS_UNSETENV */
2075 const int nlen = strlen(nam);
2081 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2082 /* all that work just for this */
2083 my_setenv_format(new_env, nam, nlen, val, vlen);
2084 (void)putenv(new_env);
2085 # endif /* HAS_UNSETENV */
2086 # endif /* __CYGWIN__ */
2087 #ifndef PERL_USE_SAFE_PUTENV
2093 #else /* WIN32 || NETWARE */
2096 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2100 const int nlen = strlen(nam);
2107 Newx(envstr, nlen+vlen+2, char);
2108 my_setenv_format(envstr, nam, nlen, val, vlen);
2109 (void)PerlEnv_putenv(envstr);
2113 #endif /* WIN32 || NETWARE */
2117 #ifdef UNLINK_ALL_VERSIONS
2119 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2123 PERL_ARGS_ASSERT_UNLNK;
2125 while (PerlLIO_unlink(f) >= 0)
2127 return retries ? 0 : -1;
2131 /* this is a drop-in replacement for bcopy() */
2132 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2134 Perl_my_bcopy(const char *from, char *to, I32 len)
2136 char * const retval = to;
2138 PERL_ARGS_ASSERT_MY_BCOPY;
2142 if (from - to >= 0) {
2150 *(--to) = *(--from);
2156 /* this is a drop-in replacement for memset() */
2159 Perl_my_memset(char *loc, I32 ch, I32 len)
2161 char * const retval = loc;
2163 PERL_ARGS_ASSERT_MY_MEMSET;
2173 /* this is a drop-in replacement for bzero() */
2174 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2176 Perl_my_bzero(char *loc, I32 len)
2178 char * const retval = loc;
2180 PERL_ARGS_ASSERT_MY_BZERO;
2190 /* this is a drop-in replacement for memcmp() */
2191 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2193 Perl_my_memcmp(const char *s1, const char *s2, I32 len)
2195 const U8 *a = (const U8 *)s1;
2196 const U8 *b = (const U8 *)s2;
2199 PERL_ARGS_ASSERT_MY_MEMCMP;
2204 if ((tmp = *a++ - *b++))
2209 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2212 /* This vsprintf replacement should generally never get used, since
2213 vsprintf was available in both System V and BSD 2.11. (There may
2214 be some cross-compilation or embedded set-ups where it is needed,
2217 If you encounter a problem in this function, it's probably a symptom
2218 that Configure failed to detect your system's vprintf() function.
2219 See the section on "item vsprintf" in the INSTALL file.
2221 This version may compile on systems with BSD-ish <stdio.h>,
2222 but probably won't on others.
2225 #ifdef USE_CHAR_VSPRINTF
2230 vsprintf(char *dest, const char *pat, void *args)
2234 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2235 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2236 FILE_cnt(&fakebuf) = 32767;
2238 /* These probably won't compile -- If you really need
2239 this, you'll have to figure out some other method. */
2240 fakebuf._ptr = dest;
2241 fakebuf._cnt = 32767;
2246 fakebuf._flag = _IOWRT|_IOSTRG;
2247 _doprnt(pat, args, &fakebuf); /* what a kludge */
2248 #if defined(STDIO_PTR_LVALUE)
2249 *(FILE_ptr(&fakebuf)++) = '\0';
2251 /* PerlIO has probably #defined away fputc, but we want it here. */
2253 # undef fputc /* XXX Should really restore it later */
2255 (void)fputc('\0', &fakebuf);
2257 #ifdef USE_CHAR_VSPRINTF
2260 return 0; /* perl doesn't use return value */
2264 #endif /* HAS_VPRINTF */
2267 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2269 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2278 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2280 PERL_FLUSHALL_FOR_CHILD;
2281 This = (*mode == 'w');
2285 taint_proper("Insecure %s%s", "EXEC");
2287 if (PerlProc_pipe(p) < 0)
2289 /* Try for another pipe pair for error return */
2290 if (PerlProc_pipe(pp) >= 0)
2292 while ((pid = PerlProc_fork()) < 0) {
2293 if (errno != EAGAIN) {
2294 PerlLIO_close(p[This]);
2295 PerlLIO_close(p[that]);
2297 PerlLIO_close(pp[0]);
2298 PerlLIO_close(pp[1]);
2302 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2311 /* Close parent's end of error status pipe (if any) */
2313 PerlLIO_close(pp[0]);
2314 #if defined(HAS_FCNTL) && defined(F_SETFD)
2315 /* Close error pipe automatically if exec works */
2316 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2320 /* Now dup our end of _the_ pipe to right position */
2321 if (p[THIS] != (*mode == 'r')) {
2322 PerlLIO_dup2(p[THIS], *mode == 'r');
2323 PerlLIO_close(p[THIS]);
2324 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2325 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2328 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2329 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2330 /* No automatic close - do it by hand */
2337 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2343 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2349 do_execfree(); /* free any memory malloced by child on fork */
2351 PerlLIO_close(pp[1]);
2352 /* Keep the lower of the two fd numbers */
2353 if (p[that] < p[This]) {
2354 PerlLIO_dup2(p[This], p[that]);
2355 PerlLIO_close(p[This]);
2359 PerlLIO_close(p[that]); /* close child's end of pipe */
2361 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2362 SvUPGRADE(sv,SVt_IV);
2364 PL_forkprocess = pid;
2365 /* If we managed to get status pipe check for exec fail */
2366 if (did_pipes && pid > 0) {
2371 while (n < sizeof(int)) {
2372 n1 = PerlLIO_read(pp[0],
2373 (void*)(((char*)&errkid)+n),
2379 PerlLIO_close(pp[0]);
2381 if (n) { /* Error */
2383 PerlLIO_close(p[This]);
2384 if (n != sizeof(int))
2385 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2387 pid2 = wait4pid(pid, &status, 0);
2388 } while (pid2 == -1 && errno == EINTR);
2389 errno = errkid; /* Propagate errno from kid */
2394 PerlLIO_close(pp[0]);
2395 return PerlIO_fdopen(p[This], mode);
2397 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2398 return my_syspopen4(aTHX_ NULL, mode, n, args);
2400 Perl_croak(aTHX_ "List form of piped open not implemented");
2401 return (PerlIO *) NULL;
2406 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2407 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2409 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2416 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2420 PERL_ARGS_ASSERT_MY_POPEN;
2422 PERL_FLUSHALL_FOR_CHILD;
2425 return my_syspopen(aTHX_ cmd,mode);
2428 This = (*mode == 'w');
2430 if (doexec && TAINTING_get) {
2432 taint_proper("Insecure %s%s", "EXEC");
2434 if (PerlProc_pipe(p) < 0)
2436 if (doexec && PerlProc_pipe(pp) >= 0)
2438 while ((pid = PerlProc_fork()) < 0) {
2439 if (errno != EAGAIN) {
2440 PerlLIO_close(p[This]);
2441 PerlLIO_close(p[that]);
2443 PerlLIO_close(pp[0]);
2444 PerlLIO_close(pp[1]);
2447 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2450 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2460 PerlLIO_close(pp[0]);
2461 #if defined(HAS_FCNTL) && defined(F_SETFD)
2462 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2466 if (p[THIS] != (*mode == 'r')) {
2467 PerlLIO_dup2(p[THIS], *mode == 'r');
2468 PerlLIO_close(p[THIS]);
2469 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2470 PerlLIO_close(p[THAT]);
2473 PerlLIO_close(p[THAT]);
2476 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2483 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2488 /* may or may not use the shell */
2489 do_exec3(cmd, pp[1], did_pipes);
2492 #endif /* defined OS2 */
2494 #ifdef PERLIO_USING_CRLF
2495 /* Since we circumvent IO layers when we manipulate low-level
2496 filedescriptors directly, need to manually switch to the
2497 default, binary, low-level mode; see PerlIOBuf_open(). */
2498 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2501 #ifdef PERL_USES_PL_PIDSTATUS
2502 hv_clear(PL_pidstatus); /* we have no children */
2508 do_execfree(); /* free any memory malloced by child on vfork */
2510 PerlLIO_close(pp[1]);
2511 if (p[that] < p[This]) {
2512 PerlLIO_dup2(p[This], p[that]);
2513 PerlLIO_close(p[This]);
2517 PerlLIO_close(p[that]);
2519 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2520 SvUPGRADE(sv,SVt_IV);
2522 PL_forkprocess = pid;
2523 if (did_pipes && pid > 0) {
2528 while (n < sizeof(int)) {
2529 n1 = PerlLIO_read(pp[0],
2530 (void*)(((char*)&errkid)+n),
2536 PerlLIO_close(pp[0]);
2538 if (n) { /* Error */
2540 PerlLIO_close(p[This]);
2541 if (n != sizeof(int))
2542 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2544 pid2 = wait4pid(pid, &status, 0);
2545 } while (pid2 == -1 && errno == EINTR);
2546 errno = errkid; /* Propagate errno from kid */
2551 PerlLIO_close(pp[0]);
2552 return PerlIO_fdopen(p[This], mode);
2556 FILE *djgpp_popen();
2558 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2560 PERL_FLUSHALL_FOR_CHILD;
2561 /* Call system's popen() to get a FILE *, then import it.
2562 used 0 for 2nd parameter to PerlIO_importFILE;
2565 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2568 #if defined(__LIBCATAMOUNT__)
2570 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2577 #endif /* !DOSISH */
2579 /* this is called in parent before the fork() */
2581 Perl_atfork_lock(void)
2584 #if defined(USE_ITHREADS)
2585 /* locks must be held in locking order (if any) */
2587 MUTEX_LOCK(&PL_perlio_mutex);
2590 MUTEX_LOCK(&PL_malloc_mutex);
2596 /* this is called in both parent and child after the fork() */
2598 Perl_atfork_unlock(void)
2601 #if defined(USE_ITHREADS)
2602 /* locks must be released in same order as in atfork_lock() */
2604 MUTEX_UNLOCK(&PL_perlio_mutex);
2607 MUTEX_UNLOCK(&PL_malloc_mutex);
2616 #if defined(HAS_FORK)
2618 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2623 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2624 * handlers elsewhere in the code */
2629 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2630 Perl_croak_nocontext("fork() not available");
2632 #endif /* HAS_FORK */
2637 dup2(int oldfd, int newfd)
2639 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2642 PerlLIO_close(newfd);
2643 return fcntl(oldfd, F_DUPFD, newfd);
2645 #define DUP2_MAX_FDS 256
2646 int fdtmp[DUP2_MAX_FDS];
2652 PerlLIO_close(newfd);
2653 /* good enough for low fd's... */
2654 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2655 if (fdx >= DUP2_MAX_FDS) {
2663 PerlLIO_close(fdtmp[--fdx]);
2670 #ifdef HAS_SIGACTION
2673 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2676 struct sigaction act, oact;
2679 /* only "parent" interpreter can diddle signals */
2680 if (PL_curinterp != aTHX)
2681 return (Sighandler_t) SIG_ERR;
2684 act.sa_handler = (void(*)(int))handler;
2685 sigemptyset(&act.sa_mask);
2688 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2689 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2691 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2692 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2693 act.sa_flags |= SA_NOCLDWAIT;
2695 if (sigaction(signo, &act, &oact) == -1)
2696 return (Sighandler_t) SIG_ERR;
2698 return (Sighandler_t) oact.sa_handler;
2702 Perl_rsignal_state(pTHX_ int signo)
2704 struct sigaction oact;
2705 PERL_UNUSED_CONTEXT;
2707 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2708 return (Sighandler_t) SIG_ERR;
2710 return (Sighandler_t) oact.sa_handler;
2714 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2717 struct sigaction act;
2719 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2722 /* only "parent" interpreter can diddle signals */
2723 if (PL_curinterp != aTHX)
2727 act.sa_handler = (void(*)(int))handler;
2728 sigemptyset(&act.sa_mask);
2731 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2732 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2734 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2735 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2736 act.sa_flags |= SA_NOCLDWAIT;
2738 return sigaction(signo, &act, save);
2742 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2746 /* only "parent" interpreter can diddle signals */
2747 if (PL_curinterp != aTHX)
2751 return sigaction(signo, save, (struct sigaction *)NULL);
2754 #else /* !HAS_SIGACTION */
2757 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2759 #if defined(USE_ITHREADS) && !defined(WIN32)
2760 /* only "parent" interpreter can diddle signals */
2761 if (PL_curinterp != aTHX)
2762 return (Sighandler_t) SIG_ERR;
2765 return PerlProc_signal(signo, handler);
2776 Perl_rsignal_state(pTHX_ int signo)
2779 Sighandler_t oldsig;
2781 #if defined(USE_ITHREADS) && !defined(WIN32)
2782 /* only "parent" interpreter can diddle signals */
2783 if (PL_curinterp != aTHX)
2784 return (Sighandler_t) SIG_ERR;
2788 oldsig = PerlProc_signal(signo, sig_trap);
2789 PerlProc_signal(signo, oldsig);
2791 PerlProc_kill(PerlProc_getpid(), signo);
2796 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2798 #if defined(USE_ITHREADS) && !defined(WIN32)
2799 /* only "parent" interpreter can diddle signals */
2800 if (PL_curinterp != aTHX)
2803 *save = PerlProc_signal(signo, handler);
2804 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2808 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2810 #if defined(USE_ITHREADS) && !defined(WIN32)
2811 /* only "parent" interpreter can diddle signals */
2812 if (PL_curinterp != aTHX)
2815 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2818 #endif /* !HAS_SIGACTION */
2819 #endif /* !PERL_MICRO */
2821 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2822 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2824 Perl_my_pclose(pTHX_ PerlIO *ptr)
2833 const int fd = PerlIO_fileno(ptr);
2836 svp = av_fetch(PL_fdpid,fd,TRUE);
2837 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2841 #if defined(USE_PERLIO)
2842 /* Find out whether the refcount is low enough for us to wait for the
2843 child proc without blocking. */
2844 should_wait = PerlIOUnix_refcnt(fd) == 1 && pid > 0;
2846 should_wait = pid > 0;
2850 if (pid == -1) { /* Opened by popen. */
2851 return my_syspclose(ptr);
2854 close_failed = (PerlIO_close(ptr) == EOF);
2856 if (should_wait) do {
2857 pid2 = wait4pid(pid, &status, 0);
2858 } while (pid2 == -1 && errno == EINTR);
2865 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
2870 #if defined(__LIBCATAMOUNT__)
2872 Perl_my_pclose(pTHX_ PerlIO *ptr)
2877 #endif /* !DOSISH */
2879 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
2881 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2885 PERL_ARGS_ASSERT_WAIT4PID;
2886 #ifdef PERL_USES_PL_PIDSTATUS
2888 /* PERL_USES_PL_PIDSTATUS is only defined when neither
2889 waitpid() nor wait4() is available, or on OS/2, which
2890 doesn't appear to support waiting for a progress group
2891 member, so we can only treat a 0 pid as an unknown child.
2898 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2899 pid, rather than a string form. */
2900 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2901 if (svp && *svp != &PL_sv_undef) {
2902 *statusp = SvIVX(*svp);
2903 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2911 hv_iterinit(PL_pidstatus);
2912 if ((entry = hv_iternext(PL_pidstatus))) {
2913 SV * const sv = hv_iterval(PL_pidstatus,entry);
2915 const char * const spid = hv_iterkey(entry,&len);
2917 assert (len == sizeof(Pid_t));
2918 memcpy((char *)&pid, spid, len);
2919 *statusp = SvIVX(sv);
2920 /* The hash iterator is currently on this entry, so simply
2921 calling hv_delete would trigger the lazy delete, which on
2922 aggregate does more work, beacuse next call to hv_iterinit()
2923 would spot the flag, and have to call the delete routine,
2924 while in the meantime any new entries can't re-use that
2926 hv_iterinit(PL_pidstatus);
2927 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2934 # ifdef HAS_WAITPID_RUNTIME
2935 if (!HAS_WAITPID_RUNTIME)
2938 result = PerlProc_waitpid(pid,statusp,flags);
2941 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2942 result = wait4(pid,statusp,flags,NULL);
2945 #ifdef PERL_USES_PL_PIDSTATUS
2946 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2951 Perl_croak(aTHX_ "Can't do waitpid with flags");
2953 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2954 pidgone(result,*statusp);
2960 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
2963 if (result < 0 && errno == EINTR) {
2965 errno = EINTR; /* reset in case a signal handler changed $! */
2969 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2971 #ifdef PERL_USES_PL_PIDSTATUS
2973 S_pidgone(pTHX_ Pid_t pid, int status)
2977 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
2978 SvUPGRADE(sv,SVt_IV);
2979 SvIV_set(sv, status);
2987 int /* Cannot prototype with I32
2989 my_syspclose(PerlIO *ptr)
2992 Perl_my_pclose(pTHX_ PerlIO *ptr)
2995 /* Needs work for PerlIO ! */
2996 FILE * const f = PerlIO_findFILE(ptr);
2997 const I32 result = pclose(f);
2998 PerlIO_releaseFILE(ptr,f);
3006 Perl_my_pclose(pTHX_ PerlIO *ptr)
3008 /* Needs work for PerlIO ! */
3009 FILE * const f = PerlIO_findFILE(ptr);
3010 I32 result = djgpp_pclose(f);
3011 result = (result << 8) & 0xff00;
3012 PerlIO_releaseFILE(ptr,f);
3017 #define PERL_REPEATCPY_LINEAR 4
3019 Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
3021 PERL_ARGS_ASSERT_REPEATCPY;
3026 croak_memory_wrap();
3029 memset(to, *from, count);
3032 IV items, linear, half;
3034 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3035 for (items = 0; items < linear; ++items) {
3036 const char *q = from;
3038 for (todo = len; todo > 0; todo--)
3043 while (items <= half) {
3044 IV size = items * len;
3045 memcpy(p, to, size);
3051 memcpy(p, to, (count - items) * len);
3057 Perl_same_dirent(pTHX_ const char *a, const char *b)
3059 char *fa = strrchr(a,'/');
3060 char *fb = strrchr(b,'/');
3063 SV * const tmpsv = sv_newmortal();
3065 PERL_ARGS_ASSERT_SAME_DIRENT;
3078 sv_setpvs(tmpsv, ".");
3080 sv_setpvn(tmpsv, a, fa - a);
3081 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3084 sv_setpvs(tmpsv, ".");
3086 sv_setpvn(tmpsv, b, fb - b);
3087 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3089 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3090 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3092 #endif /* !HAS_RENAME */
3095 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3096 const char *const *const search_ext, I32 flags)
3099 const char *xfound = NULL;
3100 char *xfailed = NULL;
3101 char tmpbuf[MAXPATHLEN];
3106 #if defined(DOSISH) && !defined(OS2)
3107 # define SEARCH_EXTS ".bat", ".cmd", NULL
3108 # define MAX_EXT_LEN 4
3111 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3112 # define MAX_EXT_LEN 4
3115 # define SEARCH_EXTS ".pl", ".com", NULL
3116 # define MAX_EXT_LEN 4
3118 /* additional extensions to try in each dir if scriptname not found */
3120 static const char *const exts[] = { SEARCH_EXTS };
3121 const char *const *const ext = search_ext ? search_ext : exts;
3122 int extidx = 0, i = 0;
3123 const char *curext = NULL;
3125 PERL_UNUSED_ARG(search_ext);
3126 # define MAX_EXT_LEN 0
3129 PERL_ARGS_ASSERT_FIND_SCRIPT;
3132 * If dosearch is true and if scriptname does not contain path
3133 * delimiters, search the PATH for scriptname.
3135 * If SEARCH_EXTS is also defined, will look for each
3136 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3137 * while searching the PATH.
3139 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3140 * proceeds as follows:
3141 * If DOSISH or VMSISH:
3142 * + look for ./scriptname{,.foo,.bar}
3143 * + search the PATH for scriptname{,.foo,.bar}
3146 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3147 * this will not look in '.' if it's not in the PATH)
3152 # ifdef ALWAYS_DEFTYPES
3153 len = strlen(scriptname);
3154 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3155 int idx = 0, deftypes = 1;
3158 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3161 int idx = 0, deftypes = 1;
3164 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3166 /* The first time through, just add SEARCH_EXTS to whatever we
3167 * already have, so we can check for default file types. */
3169 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3175 if ((strlen(tmpbuf) + strlen(scriptname)
3176 + MAX_EXT_LEN) >= sizeof tmpbuf)
3177 continue; /* don't search dir with too-long name */
3178 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3182 if (strEQ(scriptname, "-"))
3184 if (dosearch) { /* Look in '.' first. */
3185 const char *cur = scriptname;
3187 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3189 if (strEQ(ext[i++],curext)) {
3190 extidx = -1; /* already has an ext */
3195 DEBUG_p(PerlIO_printf(Perl_debug_log,
3196 "Looking for %s\n",cur));
3197 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3198 && !S_ISDIR(PL_statbuf.st_mode)) {
3206 if (cur == scriptname) {
3207 len = strlen(scriptname);
3208 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3210 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3213 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3214 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3219 if (dosearch && !strchr(scriptname, '/')
3221 && !strchr(scriptname, '\\')
3223 && (s = PerlEnv_getenv("PATH")))
3227 bufend = s + strlen(s);
3228 while (s < bufend) {
3231 && *s != ';'; len++, s++) {
3232 if (len < sizeof tmpbuf)
3235 if (len < sizeof tmpbuf)
3238 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3244 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3245 continue; /* don't search dir with too-long name */
3248 && tmpbuf[len - 1] != '/'
3249 && tmpbuf[len - 1] != '\\'
3252 tmpbuf[len++] = '/';
3253 if (len == 2 && tmpbuf[0] == '.')
3255 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3259 len = strlen(tmpbuf);
3260 if (extidx > 0) /* reset after previous loop */
3264 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3265 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3266 if (S_ISDIR(PL_statbuf.st_mode)) {
3270 } while ( retval < 0 /* not there */
3271 && extidx>=0 && ext[extidx] /* try an extension? */
3272 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3277 if (S_ISREG(PL_statbuf.st_mode)
3278 && cando(S_IRUSR,TRUE,&PL_statbuf)
3279 #if !defined(DOSISH)
3280 && cando(S_IXUSR,TRUE,&PL_statbuf)
3284 xfound = tmpbuf; /* bingo! */
3288 xfailed = savepv(tmpbuf);
3291 if (!xfound && !seen_dot && !xfailed &&
3292 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3293 || S_ISDIR(PL_statbuf.st_mode)))
3295 seen_dot = 1; /* Disable message. */
3297 if (flags & 1) { /* do or die? */
3298 /* diag_listed_as: Can't execute %s */
3299 Perl_croak(aTHX_ "Can't %s %s%s%s",
3300 (xfailed ? "execute" : "find"),
3301 (xfailed ? xfailed : scriptname),
3302 (xfailed ? "" : " on PATH"),
3303 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3308 scriptname = xfound;
3310 return (scriptname ? savepv(scriptname) : NULL);
3313 #ifndef PERL_GET_CONTEXT_DEFINED
3316 Perl_get_context(void)
3319 #if defined(USE_ITHREADS)
3320 # ifdef OLD_PTHREADS_API
3322 int error = pthread_getspecific(PL_thr_key, &t)
3324 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3327 # ifdef I_MACH_CTHREADS
3328 return (void*)cthread_data(cthread_self());
3330 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3339 Perl_set_context(void *t)
3342 PERL_ARGS_ASSERT_SET_CONTEXT;
3343 #if defined(USE_ITHREADS)
3344 # ifdef I_MACH_CTHREADS
3345 cthread_set_data(cthread_self(), t);
3348 const int error = pthread_setspecific(PL_thr_key, t);
3350 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3358 #endif /* !PERL_GET_CONTEXT_DEFINED */
3360 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3369 Perl_get_op_names(pTHX)
3371 PERL_UNUSED_CONTEXT;
3372 return (char **)PL_op_name;
3376 Perl_get_op_descs(pTHX)
3378 PERL_UNUSED_CONTEXT;
3379 return (char **)PL_op_desc;
3383 Perl_get_no_modify(pTHX)
3385 PERL_UNUSED_CONTEXT;
3386 return PL_no_modify;
3390 Perl_get_opargs(pTHX)
3392 PERL_UNUSED_CONTEXT;
3393 return (U32 *)PL_opargs;
3397 Perl_get_ppaddr(pTHX)
3400 PERL_UNUSED_CONTEXT;
3401 return (PPADDR_t*)PL_ppaddr;
3404 #ifndef HAS_GETENV_LEN
3406 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3408 char * const env_trans = PerlEnv_getenv(env_elem);
3409 PERL_UNUSED_CONTEXT;
3410 PERL_ARGS_ASSERT_GETENV_LEN;
3412 *len = strlen(env_trans);
3419 Perl_get_vtbl(pTHX_ int vtbl_id)
3421 PERL_UNUSED_CONTEXT;
3423 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3424 ? NULL : PL_magic_vtables + vtbl_id;
3428 Perl_my_fflush_all(pTHX)
3430 #if defined(USE_PERLIO) || defined(FFLUSH_NULL)
3431 return PerlIO_flush(NULL);
3433 # if defined(HAS__FWALK)
3434 extern int fflush(FILE *);
3435 /* undocumented, unprototyped, but very useful BSDism */
3436 extern void _fwalk(int (*)(FILE *));
3440 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3442 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3443 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3445 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3446 open_max = sysconf(_SC_OPEN_MAX);
3449 open_max = FOPEN_MAX;
3452 open_max = OPEN_MAX;
3463 for (i = 0; i < open_max; i++)
3464 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3465 STDIO_STREAM_ARRAY[i]._file < open_max &&
3466 STDIO_STREAM_ARRAY[i]._flag)
3467 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3471 SETERRNO(EBADF,RMS_IFI);
3478 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3480 if (ckWARN(WARN_IO)) {
3482 = gv && (isGV_with_GP(gv))
3485 const char * const direction = have == '>' ? "out" : "in";
3487 if (name && HEK_LEN(name))
3488 Perl_warner(aTHX_ packWARN(WARN_IO),
3489 "Filehandle %"HEKf" opened only for %sput",
3492 Perl_warner(aTHX_ packWARN(WARN_IO),
3493 "Filehandle opened only for %sput", direction);
3498 Perl_report_evil_fh(pTHX_ const GV *gv)
3500 const IO *io = gv ? GvIO(gv) : NULL;
3501 const PERL_BITFIELD16 op = PL_op->op_type;
3505 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3507 warn_type = WARN_CLOSED;
3511 warn_type = WARN_UNOPENED;
3514 if (ckWARN(warn_type)) {
3516 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3517 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3518 const char * const pars =
3519 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3520 const char * const func =
3522 (op == OP_READLINE || op == OP_RCATLINE
3523 ? "readline" : /* "<HANDLE>" not nice */
3524 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3526 const char * const type =
3528 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3529 ? "socket" : "filehandle");
3530 const bool have_name = name && SvCUR(name);
3531 Perl_warner(aTHX_ packWARN(warn_type),
3532 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3533 have_name ? " " : "",
3534 SVfARG(have_name ? name : &PL_sv_no));
3535 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3537 aTHX_ packWARN(warn_type),
3538 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3539 func, pars, have_name ? " " : "",
3540 SVfARG(have_name ? name : &PL_sv_no)
3545 /* To workaround core dumps from the uninitialised tm_zone we get the
3546 * system to give us a reasonable struct to copy. This fix means that
3547 * strftime uses the tm_zone and tm_gmtoff values returned by
3548 * localtime(time()). That should give the desired result most of the
3549 * time. But probably not always!
3551 * This does not address tzname aspects of NETaa14816.
3556 # ifndef STRUCT_TM_HASZONE
3557 # define STRUCT_TM_HASZONE
3561 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3562 # ifndef HAS_TM_TM_ZONE
3563 # define HAS_TM_TM_ZONE
3568 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3570 #ifdef HAS_TM_TM_ZONE
3572 const struct tm* my_tm;
3573 PERL_ARGS_ASSERT_INIT_TM;
3575 my_tm = localtime(&now);
3577 Copy(my_tm, ptm, 1, struct tm);
3579 PERL_ARGS_ASSERT_INIT_TM;
3580 PERL_UNUSED_ARG(ptm);
3585 * mini_mktime - normalise struct tm values without the localtime()
3586 * semantics (and overhead) of mktime().
3589 Perl_mini_mktime(pTHX_ struct tm *ptm)
3593 int month, mday, year, jday;
3594 int odd_cent, odd_year;
3595 PERL_UNUSED_CONTEXT;
3597 PERL_ARGS_ASSERT_MINI_MKTIME;
3599 #define DAYS_PER_YEAR 365
3600 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3601 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3602 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3603 #define SECS_PER_HOUR (60*60)
3604 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3605 /* parentheses deliberately absent on these two, otherwise they don't work */
3606 #define MONTH_TO_DAYS 153/5
3607 #define DAYS_TO_MONTH 5/153
3608 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3609 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3610 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3611 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3614 * Year/day algorithm notes:
3616 * With a suitable offset for numeric value of the month, one can find
3617 * an offset into the year by considering months to have 30.6 (153/5) days,
3618 * using integer arithmetic (i.e., with truncation). To avoid too much
3619 * messing about with leap days, we consider January and February to be
3620 * the 13th and 14th month of the previous year. After that transformation,
3621 * we need the month index we use to be high by 1 from 'normal human' usage,
3622 * so the month index values we use run from 4 through 15.
3624 * Given that, and the rules for the Gregorian calendar (leap years are those
3625 * divisible by 4 unless also divisible by 100, when they must be divisible
3626 * by 400 instead), we can simply calculate the number of days since some
3627 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3628 * the days we derive from our month index, and adding in the day of the
3629 * month. The value used here is not adjusted for the actual origin which
3630 * it normally would use (1 January A.D. 1), since we're not exposing it.
3631 * We're only building the value so we can turn around and get the
3632 * normalised values for the year, month, day-of-month, and day-of-year.
3634 * For going backward, we need to bias the value we're using so that we find
3635 * the right year value. (Basically, we don't want the contribution of
3636 * March 1st to the number to apply while deriving the year). Having done
3637 * that, we 'count up' the contribution to the year number by accounting for
3638 * full quadracenturies (400-year periods) with their extra leap days, plus
3639 * the contribution from full centuries (to avoid counting in the lost leap
3640 * days), plus the contribution from full quad-years (to count in the normal
3641 * leap days), plus the leftover contribution from any non-leap years.
3642 * At this point, if we were working with an actual leap day, we'll have 0
3643 * days left over. This is also true for March 1st, however. So, we have
3644 * to special-case that result, and (earlier) keep track of the 'odd'
3645 * century and year contributions. If we got 4 extra centuries in a qcent,
3646 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3647 * Otherwise, we add back in the earlier bias we removed (the 123 from
3648 * figuring in March 1st), find the month index (integer division by 30.6),
3649 * and the remainder is the day-of-month. We then have to convert back to
3650 * 'real' months (including fixing January and February from being 14/15 in
3651 * the previous year to being in the proper year). After that, to get
3652 * tm_yday, we work with the normalised year and get a new yearday value for
3653 * January 1st, which we subtract from the yearday value we had earlier,
3654 * representing the date we've re-built. This is done from January 1
3655 * because tm_yday is 0-origin.
3657 * Since POSIX time routines are only guaranteed to work for times since the
3658 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3659 * applies Gregorian calendar rules even to dates before the 16th century
3660 * doesn't bother me. Besides, you'd need cultural context for a given
3661 * date to know whether it was Julian or Gregorian calendar, and that's
3662 * outside the scope for this routine. Since we convert back based on the
3663 * same rules we used to build the yearday, you'll only get strange results
3664 * for input which needed normalising, or for the 'odd' century years which
3665 * were leap years in the Julian calendar but not in the Gregorian one.
3666 * I can live with that.
3668 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3669 * that's still outside the scope for POSIX time manipulation, so I don't
3673 year = 1900 + ptm->tm_year;
3674 month = ptm->tm_mon;
3675 mday = ptm->tm_mday;
3681 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3682 yearday += month*MONTH_TO_DAYS + mday + jday;
3684 * Note that we don't know when leap-seconds were or will be,
3685 * so we have to trust the user if we get something which looks
3686 * like a sensible leap-second. Wild values for seconds will
3687 * be rationalised, however.
3689 if ((unsigned) ptm->tm_sec <= 60) {
3696 secs += 60 * ptm->tm_min;
3697 secs += SECS_PER_HOUR * ptm->tm_hour;
3699 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3700 /* got negative remainder, but need positive time */
3701 /* back off an extra day to compensate */
3702 yearday += (secs/SECS_PER_DAY)-1;
3703 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3706 yearday += (secs/SECS_PER_DAY);
3707 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3710 else if (secs >= SECS_PER_DAY) {
3711 yearday += (secs/SECS_PER_DAY);
3712 secs %= SECS_PER_DAY;
3714 ptm->tm_hour = secs/SECS_PER_HOUR;
3715 secs %= SECS_PER_HOUR;
3716 ptm->tm_min = secs/60;
3718 ptm->tm_sec += secs;
3719 /* done with time of day effects */
3721 * The algorithm for yearday has (so far) left it high by 428.
3722 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3723 * bias it by 123 while trying to figure out what year it
3724 * really represents. Even with this tweak, the reverse
3725 * translation fails for years before A.D. 0001.
3726 * It would still fail for Feb 29, but we catch that one below.
3728 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3729 yearday -= YEAR_ADJUST;
3730 year = (yearday / DAYS_PER_QCENT) * 400;
3731 yearday %= DAYS_PER_QCENT;
3732 odd_cent = yearday / DAYS_PER_CENT;
3733 year += odd_cent * 100;
3734 yearday %= DAYS_PER_CENT;
3735 year += (yearday / DAYS_PER_QYEAR) * 4;
3736 yearday %= DAYS_PER_QYEAR;
3737 odd_year = yearday / DAYS_PER_YEAR;
3739 yearday %= DAYS_PER_YEAR;
3740 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3745 yearday += YEAR_ADJUST; /* recover March 1st crock */
3746 month = yearday*DAYS_TO_MONTH;
3747 yearday -= month*MONTH_TO_DAYS;
3748 /* recover other leap-year adjustment */
3757 ptm->tm_year = year - 1900;
3759 ptm->tm_mday = yearday;
3760 ptm->tm_mon = month;
3764 ptm->tm_mon = month - 1;
3766 /* re-build yearday based on Jan 1 to get tm_yday */
3768 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3769 yearday += 14*MONTH_TO_DAYS + 1;
3770 ptm->tm_yday = jday - yearday;
3771 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3775 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)
3783 PERL_ARGS_ASSERT_MY_STRFTIME;
3785 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3788 mytm.tm_hour = hour;
3789 mytm.tm_mday = mday;
3791 mytm.tm_year = year;
3792 mytm.tm_wday = wday;
3793 mytm.tm_yday = yday;
3794 mytm.tm_isdst = isdst;
3796 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3797 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3802 #ifdef HAS_TM_TM_GMTOFF
3803 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3805 #ifdef HAS_TM_TM_ZONE
3806 mytm.tm_zone = mytm2.tm_zone;
3811 Newx(buf, buflen, char);
3813 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
3814 len = strftime(buf, buflen, fmt, &mytm);
3818 ** The following is needed to handle to the situation where
3819 ** tmpbuf overflows. Basically we want to allocate a buffer
3820 ** and try repeatedly. The reason why it is so complicated
3821 ** is that getting a return value of 0 from strftime can indicate
3822 ** one of the following:
3823 ** 1. buffer overflowed,
3824 ** 2. illegal conversion specifier, or
3825 ** 3. the format string specifies nothing to be returned(not
3826 ** an error). This could be because format is an empty string
3827 ** or it specifies %p that yields an empty string in some locale.
3828 ** If there is a better way to make it portable, go ahead by
3831 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3834 /* Possibly buf overflowed - try again with a bigger buf */
3835 const int fmtlen = strlen(fmt);
3836 int bufsize = fmtlen + buflen;
3838 Renew(buf, bufsize, char);
3841 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
3842 buflen = strftime(buf, bufsize, fmt, &mytm);
3845 if (buflen > 0 && buflen < bufsize)
3847 /* heuristic to prevent out-of-memory errors */
3848 if (bufsize > 100*fmtlen) {
3854 Renew(buf, bufsize, char);
3859 Perl_croak(aTHX_ "panic: no strftime");
3865 #define SV_CWD_RETURN_UNDEF \
3866 sv_setsv(sv, &PL_sv_undef); \
3869 #define SV_CWD_ISDOT(dp) \
3870 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3871 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3874 =head1 Miscellaneous Functions
3876 =for apidoc getcwd_sv
3878 Fill the sv with current working directory
3883 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3884 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3885 * getcwd(3) if available
3886 * Comments from the orignal:
3887 * This is a faster version of getcwd. It's also more dangerous
3888 * because you might chdir out of a directory that you can't chdir
3892 Perl_getcwd_sv(pTHX_ SV *sv)
3898 PERL_ARGS_ASSERT_GETCWD_SV;
3902 char buf[MAXPATHLEN];
3904 /* Some getcwd()s automatically allocate a buffer of the given
3905 * size from the heap if they are given a NULL buffer pointer.
3906 * The problem is that this behaviour is not portable. */
3907 if (getcwd(buf, sizeof(buf) - 1)) {
3912 sv_setsv(sv, &PL_sv_undef);
3920 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3924 SvUPGRADE(sv, SVt_PV);
3926 if (PerlLIO_lstat(".", &statbuf) < 0) {
3927 SV_CWD_RETURN_UNDEF;
3930 orig_cdev = statbuf.st_dev;
3931 orig_cino = statbuf.st_ino;
3941 if (PerlDir_chdir("..") < 0) {
3942 SV_CWD_RETURN_UNDEF;
3944 if (PerlLIO_stat(".", &statbuf) < 0) {
3945 SV_CWD_RETURN_UNDEF;
3948 cdev = statbuf.st_dev;
3949 cino = statbuf.st_ino;
3951 if (odev == cdev && oino == cino) {
3954 if (!(dir = PerlDir_open("."))) {
3955 SV_CWD_RETURN_UNDEF;
3958 while ((dp = PerlDir_read(dir)) != NULL) {
3960 namelen = dp->d_namlen;
3962 namelen = strlen(dp->d_name);
3965 if (SV_CWD_ISDOT(dp)) {
3969 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3970 SV_CWD_RETURN_UNDEF;
3973 tdev = statbuf.st_dev;
3974 tino = statbuf.st_ino;
3975 if (tino == oino && tdev == odev) {
3981 SV_CWD_RETURN_UNDEF;
3984 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3985 SV_CWD_RETURN_UNDEF;
3988 SvGROW(sv, pathlen + namelen + 1);
3992 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3995 /* prepend current directory to the front */
3997 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3998 pathlen += (namelen + 1);
4000 #ifdef VOID_CLOSEDIR
4003 if (PerlDir_close(dir) < 0) {
4004 SV_CWD_RETURN_UNDEF;
4010 SvCUR_set(sv, pathlen);
4014 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4015 SV_CWD_RETURN_UNDEF;
4018 if (PerlLIO_stat(".", &statbuf) < 0) {
4019 SV_CWD_RETURN_UNDEF;
4022 cdev = statbuf.st_dev;
4023 cino = statbuf.st_ino;
4025 if (cdev != orig_cdev || cino != orig_cino) {
4026 Perl_croak(aTHX_ "Unstable directory path, "
4027 "current directory changed unexpectedly");
4040 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4041 # define EMULATE_SOCKETPAIR_UDP
4044 #ifdef EMULATE_SOCKETPAIR_UDP
4046 S_socketpair_udp (int fd[2]) {
4048 /* Fake a datagram socketpair using UDP to localhost. */
4049 int sockets[2] = {-1, -1};
4050 struct sockaddr_in addresses[2];
4052 Sock_size_t size = sizeof(struct sockaddr_in);
4053 unsigned short port;
4056 memset(&addresses, 0, sizeof(addresses));
4059 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4060 if (sockets[i] == -1)
4061 goto tidy_up_and_fail;
4063 addresses[i].sin_family = AF_INET;
4064 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4065 addresses[i].sin_port = 0; /* kernel choses port. */
4066 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4067 sizeof(struct sockaddr_in)) == -1)
4068 goto tidy_up_and_fail;
4071 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4072 for each connect the other socket to it. */
4075 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4077 goto tidy_up_and_fail;
4078 if (size != sizeof(struct sockaddr_in))
4079 goto abort_tidy_up_and_fail;
4080 /* !1 is 0, !0 is 1 */
4081 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4082 sizeof(struct sockaddr_in)) == -1)
4083 goto tidy_up_and_fail;
4086 /* Now we have 2 sockets connected to each other. I don't trust some other
4087 process not to have already sent a packet to us (by random) so send
4088 a packet from each to the other. */
4091 /* I'm going to send my own port number. As a short.
4092 (Who knows if someone somewhere has sin_port as a bitfield and needs
4093 this routine. (I'm assuming crays have socketpair)) */
4094 port = addresses[i].sin_port;
4095 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4096 if (got != sizeof(port)) {
4098 goto tidy_up_and_fail;
4099 goto abort_tidy_up_and_fail;
4103 /* Packets sent. I don't trust them to have arrived though.
4104 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4105 connect to localhost will use a second kernel thread. In 2.6 the
4106 first thread running the connect() returns before the second completes,
4107 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4108 returns 0. Poor programs have tripped up. One poor program's authors'
4109 had a 50-1 reverse stock split. Not sure how connected these were.)
4110 So I don't trust someone not to have an unpredictable UDP stack.
4114 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4115 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4119 FD_SET((unsigned int)sockets[0], &rset);
4120 FD_SET((unsigned int)sockets[1], &rset);
4122 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4123 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4124 || !FD_ISSET(sockets[1], &rset)) {
4125 /* I hope this is portable and appropriate. */
4127 goto tidy_up_and_fail;
4128 goto abort_tidy_up_and_fail;
4132 /* And the paranoia department even now doesn't trust it to have arrive
4133 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4135 struct sockaddr_in readfrom;
4136 unsigned short buffer[2];
4141 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4142 sizeof(buffer), MSG_DONTWAIT,
4143 (struct sockaddr *) &readfrom, &size);
4145 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4147 (struct sockaddr *) &readfrom, &size);
4151 goto tidy_up_and_fail;
4152 if (got != sizeof(port)
4153 || size != sizeof(struct sockaddr_in)
4154 /* Check other socket sent us its port. */
4155 || buffer[0] != (unsigned short) addresses[!i].sin_port
4156 /* Check kernel says we got the datagram from that socket */
4157 || readfrom.sin_family != addresses[!i].sin_family
4158 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4159 || readfrom.sin_port != addresses[!i].sin_port)
4160 goto abort_tidy_up_and_fail;
4163 /* My caller (my_socketpair) has validated that this is non-NULL */
4166 /* I hereby declare this connection open. May God bless all who cross
4170 abort_tidy_up_and_fail:
4171 errno = ECONNABORTED;
4175 if (sockets[0] != -1)
4176 PerlLIO_close(sockets[0]);
4177 if (sockets[1] != -1)
4178 PerlLIO_close(sockets[1]);
4183 #endif /* EMULATE_SOCKETPAIR_UDP */
4185 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4187 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4188 /* Stevens says that family must be AF_LOCAL, protocol 0.
4189 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4194 struct sockaddr_in listen_addr;
4195 struct sockaddr_in connect_addr;
4200 || family != AF_UNIX
4203 errno = EAFNOSUPPORT;
4211 #ifdef EMULATE_SOCKETPAIR_UDP
4212 if (type == SOCK_DGRAM)
4213 return S_socketpair_udp(fd);
4216 aTHXa(PERL_GET_THX);
4217 listener = PerlSock_socket(AF_INET, type, 0);
4220 memset(&listen_addr, 0, sizeof(listen_addr));
4221 listen_addr.sin_family = AF_INET;
4222 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4223 listen_addr.sin_port = 0; /* kernel choses port. */
4224 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4225 sizeof(listen_addr)) == -1)
4226 goto tidy_up_and_fail;
4227 if (PerlSock_listen(listener, 1) == -1)
4228 goto tidy_up_and_fail;
4230 connector = PerlSock_socket(AF_INET, type, 0);
4231 if (connector == -1)
4232 goto tidy_up_and_fail;
4233 /* We want to find out the port number to connect to. */
4234 size = sizeof(connect_addr);
4235 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4237 goto tidy_up_and_fail;
4238 if (size != sizeof(connect_addr))
4239 goto abort_tidy_up_and_fail;
4240 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4241 sizeof(connect_addr)) == -1)
4242 goto tidy_up_and_fail;
4244 size = sizeof(listen_addr);
4245 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4248 goto tidy_up_and_fail;
4249 if (size != sizeof(listen_addr))
4250 goto abort_tidy_up_and_fail;
4251 PerlLIO_close(listener);
4252 /* Now check we are talking to ourself by matching port and host on the
4254 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4256 goto tidy_up_and_fail;
4257 if (size != sizeof(connect_addr)
4258 || listen_addr.sin_family != connect_addr.sin_family
4259 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4260 || listen_addr.sin_port != connect_addr.sin_port) {
4261 goto abort_tidy_up_and_fail;
4267 abort_tidy_up_and_fail:
4269 errno = ECONNABORTED; /* This would be the standard thing to do. */
4271 # ifdef ECONNREFUSED
4272 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4274 errno = ETIMEDOUT; /* Desperation time. */
4281 PerlLIO_close(listener);
4282 if (connector != -1)
4283 PerlLIO_close(connector);
4285 PerlLIO_close(acceptor);
4291 /* In any case have a stub so that there's code corresponding
4292 * to the my_socketpair in embed.fnc. */
4294 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4295 #ifdef HAS_SOCKETPAIR
4296 return socketpair(family, type, protocol, fd);
4305 =for apidoc sv_nosharing
4307 Dummy routine which "shares" an SV when there is no sharing module present.
4308 Or "locks" it. Or "unlocks" it. In other
4309 words, ignores its single SV argument.
4310 Exists to avoid test for a NULL function pointer and because it could
4311 potentially warn under some level of strict-ness.
4317 Perl_sv_nosharing(pTHX_ SV *sv)
4319 PERL_UNUSED_CONTEXT;
4320 PERL_UNUSED_ARG(sv);
4325 =for apidoc sv_destroyable
4327 Dummy routine which reports that object can be destroyed when there is no
4328 sharing module present. It ignores its single SV argument, and returns
4329 'true'. Exists to avoid test for a NULL function pointer and because it
4330 could potentially warn under some level of strict-ness.
4336 Perl_sv_destroyable(pTHX_ SV *sv)
4338 PERL_UNUSED_CONTEXT;
4339 PERL_UNUSED_ARG(sv);
4344 Perl_parse_unicode_opts(pTHX_ const char **popt)
4346 const char *p = *popt;
4349 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
4353 opt = (U32) atoi(p);
4356 if (*p && *p != '\n' && *p != '\r') {
4357 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4359 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4365 case PERL_UNICODE_STDIN:
4366 opt |= PERL_UNICODE_STDIN_FLAG; break;
4367 case PERL_UNICODE_STDOUT:
4368 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4369 case PERL_UNICODE_STDERR:
4370 opt |= PERL_UNICODE_STDERR_FLAG; break;
4371 case PERL_UNICODE_STD:
4372 opt |= PERL_UNICODE_STD_FLAG; break;
4373 case PERL_UNICODE_IN:
4374 opt |= PERL_UNICODE_IN_FLAG; break;
4375 case PERL_UNICODE_OUT:
4376 opt |= PERL_UNICODE_OUT_FLAG; break;
4377 case PERL_UNICODE_INOUT:
4378 opt |= PERL_UNICODE_INOUT_FLAG; break;
4379 case PERL_UNICODE_LOCALE:
4380 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4381 case PERL_UNICODE_ARGV:
4382 opt |= PERL_UNICODE_ARGV_FLAG; break;
4383 case PERL_UNICODE_UTF8CACHEASSERT:
4384 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
4386 if (*p != '\n' && *p != '\r') {
4387 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4390 "Unknown Unicode option letter '%c'", *p);
4397 opt = PERL_UNICODE_DEFAULT_FLAGS;
4399 the_end_of_the_opts_parser:
4401 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4402 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4403 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4411 # include <starlet.h>
4419 * This is really just a quick hack which grabs various garbage
4420 * values. It really should be a real hash algorithm which
4421 * spreads the effect of every input bit onto every output bit,
4422 * if someone who knows about such things would bother to write it.
4423 * Might be a good idea to add that function to CORE as well.
4424 * No numbers below come from careful analysis or anything here,
4425 * except they are primes and SEED_C1 > 1E6 to get a full-width
4426 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4427 * probably be bigger too.
4430 # define SEED_C1 1000003
4431 #define SEED_C4 73819
4433 # define SEED_C1 25747
4434 #define SEED_C4 20639
4438 #define SEED_C5 26107
4440 #ifndef PERL_NO_DEV_RANDOM
4445 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4446 * in 100-ns units, typically incremented ever 10 ms. */
4447 unsigned int when[2];
4449 # ifdef HAS_GETTIMEOFDAY
4450 struct timeval when;
4456 /* This test is an escape hatch, this symbol isn't set by Configure. */
4457 #ifndef PERL_NO_DEV_RANDOM
4458 #ifndef PERL_RANDOM_DEVICE
4459 /* /dev/random isn't used by default because reads from it will block
4460 * if there isn't enough entropy available. You can compile with
4461 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4462 * is enough real entropy to fill the seed. */
4463 # define PERL_RANDOM_DEVICE "/dev/urandom"
4465 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4467 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4476 _ckvmssts(sys$gettim(when));
4477 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4479 # ifdef HAS_GETTIMEOFDAY
4480 PerlProc_gettimeofday(&when,NULL);
4481 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4484 u = (U32)SEED_C1 * when;
4487 u += SEED_C3 * (U32)PerlProc_getpid();
4488 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4489 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4490 u += SEED_C5 * (U32)PTR2UV(&when);
4496 Perl_get_hash_seed(pTHX_ unsigned char * const seed_buffer)
4502 PERL_ARGS_ASSERT_GET_HASH_SEED;
4504 env_pv= PerlEnv_getenv("PERL_HASH_SEED");
4507 #ifndef USE_HASH_SEED_EXPLICIT
4509 /* ignore leading spaces */
4510 while (isSPACE(*env_pv))
4512 #ifdef USE_PERL_PERTURB_KEYS
4513 /* if they set it to "0" we disable key traversal randomization completely */
4514 if (strEQ(env_pv,"0")) {
4515 PL_hash_rand_bits_enabled= 0;
4517 /* otherwise switch to deterministic mode */
4518 PL_hash_rand_bits_enabled= 2;
4521 /* ignore a leading 0x... if it is there */
4522 if (env_pv[0] == '0' && env_pv[1] == 'x')
4525 for( i = 0; isXDIGIT(*env_pv) && i < PERL_HASH_SEED_BYTES; i++ ) {
4526 seed_buffer[i] = READ_XDIGIT(env_pv) << 4;
4527 if ( isXDIGIT(*env_pv)) {
4528 seed_buffer[i] |= READ_XDIGIT(env_pv);
4531 while (isSPACE(*env_pv))
4534 if (*env_pv && !isXDIGIT(*env_pv)) {
4535 Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n");
4537 /* should we check for unparsed crap? */
4538 /* should we warn about unused hex? */
4539 /* should we warn about insufficient hex? */
4544 (void)seedDrand01((Rand_seed_t)seed());
4546 for( i = 0; i < PERL_HASH_SEED_BYTES; i++ ) {
4547 seed_buffer[i] = (unsigned char)(Drand01() * (U8_MAX+1));
4550 #ifdef USE_PERL_PERTURB_KEYS
4551 { /* initialize PL_hash_rand_bits from the hash seed.
4552 * This value is highly volatile, it is updated every
4553 * hash insert, and is used as part of hash bucket chain
4554 * randomization and hash iterator randomization. */
4555 PL_hash_rand_bits= 0xbe49d17f; /* I just picked a number */
4556 for( i = 0; i < sizeof(UV) ; i++ ) {
4557 PL_hash_rand_bits += seed_buffer[i % PERL_HASH_SEED_BYTES];
4558 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,8);
4561 env_pv= PerlEnv_getenv("PERL_PERTURB_KEYS");
4563 if (strEQ(env_pv,"0") || strEQ(env_pv,"NO")) {
4564 PL_hash_rand_bits_enabled= 0;
4565 } else if (strEQ(env_pv,"1") || strEQ(env_pv,"RANDOM")) {
4566 PL_hash_rand_bits_enabled= 1;
4567 } else if (strEQ(env_pv,"2") || strEQ(env_pv,"DETERMINISTIC")) {
4568 PL_hash_rand_bits_enabled= 2;
4570 Perl_warn(aTHX_ "perl: warning: strange setting in '$ENV{PERL_PERTURB_KEYS}': '%s'\n", env_pv);
4576 #ifdef PERL_GLOBAL_STRUCT
4578 #define PERL_GLOBAL_STRUCT_INIT
4579 #include "opcode.h" /* the ppaddr and check */
4582 Perl_init_global_struct(pTHX)
4584 struct perl_vars *plvarsp = NULL;
4585 # ifdef PERL_GLOBAL_STRUCT
4586 const IV nppaddr = C_ARRAY_LENGTH(Gppaddr);
4587 const IV ncheck = C_ARRAY_LENGTH(Gcheck);
4588 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4589 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
4590 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
4594 plvarsp = PL_VarsPtr;
4595 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
4600 # define PERLVAR(prefix,var,type) /**/
4601 # define PERLVARA(prefix,var,n,type) /**/
4602 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
4603 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
4604 # include "perlvars.h"
4609 # ifdef PERL_GLOBAL_STRUCT
4612 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
4613 if (!plvarsp->Gppaddr)
4617 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
4618 if (!plvarsp->Gcheck)
4620 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
4621 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
4623 # ifdef PERL_SET_VARS
4624 PERL_SET_VARS(plvarsp);
4626 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4627 plvarsp->Gsv_placeholder.sv_flags = 0;
4628 memset(plvarsp->Ghash_seed, 0, sizeof(plvarsp->Ghash_seed));
4630 # undef PERL_GLOBAL_STRUCT_INIT
4635 #endif /* PERL_GLOBAL_STRUCT */
4637 #ifdef PERL_GLOBAL_STRUCT
4640 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
4642 int veto = plvarsp->Gveto_cleanup;
4644 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
4645 # ifdef PERL_GLOBAL_STRUCT
4646 # ifdef PERL_UNSET_VARS
4647 PERL_UNSET_VARS(plvarsp);
4651 free(plvarsp->Gppaddr);
4652 free(plvarsp->Gcheck);
4653 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4659 #endif /* PERL_GLOBAL_STRUCT */
4663 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
4664 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
4665 * given, and you supply your own implementation.
4667 * The default implementation reads a single env var, PERL_MEM_LOG,
4668 * expecting one or more of the following:
4670 * \d+ - fd fd to write to : must be 1st (atoi)
4671 * 'm' - memlog was PERL_MEM_LOG=1
4672 * 's' - svlog was PERL_SV_LOG=1
4673 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
4675 * This makes the logger controllable enough that it can reasonably be
4676 * added to the system perl.
4679 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
4680 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
4682 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
4684 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
4685 * writes to. In the default logger, this is settable at runtime.
4687 #ifndef PERL_MEM_LOG_FD
4688 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
4691 #ifndef PERL_MEM_LOG_NOIMPL
4693 # ifdef DEBUG_LEAKING_SCALARS
4694 # define SV_LOG_SERIAL_FMT " [%lu]"
4695 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
4697 # define SV_LOG_SERIAL_FMT
4698 # define _SV_LOG_SERIAL_ARG(sv)
4702 S_mem_log_common(enum mem_log_type mlt, const UV n,
4703 const UV typesize, const char *type_name, const SV *sv,
4704 Malloc_t oldalloc, Malloc_t newalloc,
4705 const char *filename, const int linenumber,
4706 const char *funcname)
4710 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
4712 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
4715 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
4717 /* We can't use SVs or PerlIO for obvious reasons,
4718 * so we'll use stdio and low-level IO instead. */
4719 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
4721 # ifdef HAS_GETTIMEOFDAY
4722 # define MEM_LOG_TIME_FMT "%10d.%06d: "
4723 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
4725 gettimeofday(&tv, 0);
4727 # define MEM_LOG_TIME_FMT "%10d: "
4728 # define MEM_LOG_TIME_ARG (int)when
4732 /* If there are other OS specific ways of hires time than
4733 * gettimeofday() (see ext/Time-HiRes), the easiest way is
4734 * probably that they would be used to fill in the struct
4738 int fd = atoi(pmlenv);
4740 fd = PERL_MEM_LOG_FD;
4742 if (strchr(pmlenv, 't')) {
4743 len = my_snprintf(buf, sizeof(buf),
4744 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
4745 PerlLIO_write(fd, buf, len);
4749 len = my_snprintf(buf, sizeof(buf),
4750 "alloc: %s:%d:%s: %"IVdf" %"UVuf
4751 " %s = %"IVdf": %"UVxf"\n",
4752 filename, linenumber, funcname, n, typesize,
4753 type_name, n * typesize, PTR2UV(newalloc));
4756 len = my_snprintf(buf, sizeof(buf),
4757 "realloc: %s:%d:%s: %"IVdf" %"UVuf
4758 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
4759 filename, linenumber, funcname, n, typesize,
4760 type_name, n * typesize, PTR2UV(oldalloc),
4764 len = my_snprintf(buf, sizeof(buf),
4765 "free: %s:%d:%s: %"UVxf"\n",
4766 filename, linenumber, funcname,
4771 len = my_snprintf(buf, sizeof(buf),
4772 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
4773 mlt == MLT_NEW_SV ? "new" : "del",
4774 filename, linenumber, funcname,
4775 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
4780 PerlLIO_write(fd, buf, len);
4784 #endif /* !PERL_MEM_LOG_NOIMPL */
4786 #ifndef PERL_MEM_LOG_NOIMPL
4788 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
4789 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
4791 /* this is suboptimal, but bug compatible. User is providing their
4792 own implementation, but is getting these functions anyway, and they
4793 do nothing. But _NOIMPL users should be able to cope or fix */
4795 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
4796 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
4800 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
4802 const char *filename, const int linenumber,
4803 const char *funcname)
4805 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
4806 NULL, NULL, newalloc,
4807 filename, linenumber, funcname);
4812 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
4813 Malloc_t oldalloc, Malloc_t newalloc,
4814 const char *filename, const int linenumber,
4815 const char *funcname)
4817 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
4818 NULL, oldalloc, newalloc,
4819 filename, linenumber, funcname);
4824 Perl_mem_log_free(Malloc_t oldalloc,
4825 const char *filename, const int linenumber,
4826 const char *funcname)
4828 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
4829 filename, linenumber, funcname);
4834 Perl_mem_log_new_sv(const SV *sv,
4835 const char *filename, const int linenumber,
4836 const char *funcname)
4838 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
4839 filename, linenumber, funcname);
4843 Perl_mem_log_del_sv(const SV *sv,
4844 const char *filename, const int linenumber,
4845 const char *funcname)
4847 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
4848 filename, linenumber, funcname);
4851 #endif /* PERL_MEM_LOG */
4854 =for apidoc my_sprintf
4856 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
4857 the length of the string written to the buffer. Only rare pre-ANSI systems
4858 need the wrapper function - usually this is a direct call to C<sprintf>.
4862 #ifndef SPRINTF_RETURNS_STRLEN
4864 Perl_my_sprintf(char *buffer, const char* pat, ...)
4867 PERL_ARGS_ASSERT_MY_SPRINTF;
4868 va_start(args, pat);
4869 vsprintf(buffer, pat, args);
4871 return strlen(buffer);
4876 =for apidoc my_snprintf
4878 The C library C<snprintf> functionality, if available and
4879 standards-compliant (uses C<vsnprintf>, actually). However, if the
4880 C<vsnprintf> is not available, will unfortunately use the unsafe
4881 C<vsprintf> which can overrun the buffer (there is an overrun check,
4882 but that may be too late). Consider using C<sv_vcatpvf> instead, or
4883 getting C<vsnprintf>.
4888 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
4892 PERL_ARGS_ASSERT_MY_SNPRINTF;
4893 va_start(ap, format);
4894 #ifdef HAS_VSNPRINTF
4895 retval = vsnprintf(buffer, len, format, ap);
4897 retval = vsprintf(buffer, format, ap);
4900 /* vsprintf() shows failure with < 0 */
4902 #ifdef HAS_VSNPRINTF
4903 /* vsnprintf() shows failure with >= len */
4905 (len > 0 && (Size_t)retval >= len)
4908 Perl_croak_nocontext("panic: my_snprintf buffer overflow");
4913 =for apidoc my_vsnprintf
4915 The C library C<vsnprintf> if available and standards-compliant.
4916 However, if if the C<vsnprintf> is not available, will unfortunately
4917 use the unsafe C<vsprintf> which can overrun the buffer (there is an
4918 overrun check, but that may be too late). Consider using
4919 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
4924 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
4930 PERL_ARGS_ASSERT_MY_VSNPRINTF;
4932 Perl_va_copy(ap, apc);
4933 # ifdef HAS_VSNPRINTF
4934 retval = vsnprintf(buffer, len, format, apc);
4936 retval = vsprintf(buffer, format, apc);
4940 # ifdef HAS_VSNPRINTF
4941 retval = vsnprintf(buffer, len, format, ap);
4943 retval = vsprintf(buffer, format, ap);
4945 #endif /* #ifdef NEED_VA_COPY */
4946 /* vsprintf() shows failure with < 0 */
4948 #ifdef HAS_VSNPRINTF
4949 /* vsnprintf() shows failure with >= len */
4951 (len > 0 && (Size_t)retval >= len)
4954 Perl_croak_nocontext("panic: my_vsnprintf buffer overflow");
4959 Perl_my_clearenv(pTHX)
4962 #if ! defined(PERL_MICRO)
4963 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
4965 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
4966 # if defined(USE_ENVIRON_ARRAY)
4967 # if defined(USE_ITHREADS)
4968 /* only the parent thread can clobber the process environment */
4969 if (PL_curinterp == aTHX)
4970 # endif /* USE_ITHREADS */
4972 # if ! defined(PERL_USE_SAFE_PUTENV)
4973 if ( !PL_use_safe_putenv) {
4975 if (environ == PL_origenviron)
4976 environ = (char**)safesysmalloc(sizeof(char*));
4978 for (i = 0; environ[i]; i++)
4979 (void)safesysfree(environ[i]);
4982 # else /* PERL_USE_SAFE_PUTENV */
4983 # if defined(HAS_CLEARENV)
4985 # elif defined(HAS_UNSETENV)
4986 int bsiz = 80; /* Most envvar names will be shorter than this. */
4987 char *buf = (char*)safesysmalloc(bsiz);
4988 while (*environ != NULL) {
4989 char *e = strchr(*environ, '=');
4990 int l = e ? e - *environ : (int)strlen(*environ);
4992 (void)safesysfree(buf);
4993 bsiz = l + 1; /* + 1 for the \0. */
4994 buf = (char*)safesysmalloc(bsiz);
4996 memcpy(buf, *environ, l);
4998 (void)unsetenv(buf);
5000 (void)safesysfree(buf);
5001 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5002 /* Just null environ and accept the leakage. */
5004 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5005 # endif /* ! PERL_USE_SAFE_PUTENV */
5007 # endif /* USE_ENVIRON_ARRAY */
5008 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5009 #endif /* PERL_MICRO */
5012 #ifdef PERL_IMPLICIT_CONTEXT
5014 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
5015 the global PL_my_cxt_index is incremented, and that value is assigned to
5016 that module's static my_cxt_index (who's address is passed as an arg).
5017 Then, for each interpreter this function is called for, it makes sure a
5018 void* slot is available to hang the static data off, by allocating or
5019 extending the interpreter's PL_my_cxt_list array */
5021 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
5023 Perl_my_cxt_init(pTHX_ int *index, size_t size)
5027 PERL_ARGS_ASSERT_MY_CXT_INIT;
5029 /* this module hasn't been allocated an index yet */
5030 #if defined(USE_ITHREADS)
5031 MUTEX_LOCK(&PL_my_ctx_mutex);
5033 *index = PL_my_cxt_index++;
5034 #if defined(USE_ITHREADS)
5035 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5039 /* make sure the array is big enough */
5040 if (PL_my_cxt_size <= *index) {
5041 if (PL_my_cxt_size) {
5042 while (PL_my_cxt_size <= *index)
5043 PL_my_cxt_size *= 2;
5044 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5047 PL_my_cxt_size = 16;
5048 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5051 /* newSV() allocates one more than needed */
5052 p = (void*)SvPVX(newSV(size-1));
5053 PL_my_cxt_list[*index] = p;
5054 Zero(p, size, char);
5058 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5061 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
5066 PERL_ARGS_ASSERT_MY_CXT_INDEX;
5068 for (index = 0; index < PL_my_cxt_index; index++) {
5069 const char *key = PL_my_cxt_keys[index];
5070 /* try direct pointer compare first - there are chances to success,
5071 * and it's much faster.
5073 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
5080 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
5086 PERL_ARGS_ASSERT_MY_CXT_INIT;
5088 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
5090 /* this module hasn't been allocated an index yet */
5091 #if defined(USE_ITHREADS)
5092 MUTEX_LOCK(&PL_my_ctx_mutex);
5094 index = PL_my_cxt_index++;
5095 #if defined(USE_ITHREADS)
5096 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5100 /* make sure the array is big enough */
5101 if (PL_my_cxt_size <= index) {
5102 int old_size = PL_my_cxt_size;
5104 if (PL_my_cxt_size) {
5105 while (PL_my_cxt_size <= index)
5106 PL_my_cxt_size *= 2;
5107 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5108 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5111 PL_my_cxt_size = 16;
5112 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5113 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *