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
30 #include "perliol.h" /* For PerlIOUnix_refcnt */
36 # define SIG_ERR ((Sighandler_t) -1)
41 /* Missing protos on LynxOS */
47 # include <sys/select.h>
53 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
54 # define FD_CLOEXEC 1 /* NeXT needs this */
57 /* NOTE: Do not call the next three routines directly. Use the macros
58 * in handy.h, so that we can easily redefine everything to do tracking of
59 * allocated hunks back to the original New to track down any memory leaks.
60 * XXX This advice seems to be widely ignored :-( --AD August 1996.
63 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
64 # define ALWAYS_NEED_THX
67 /* paranoid version of system's malloc() */
70 Perl_safesysmalloc(MEM_SIZE size)
72 #ifdef ALWAYS_NEED_THX
78 PerlIO_printf(Perl_error_log,
79 "Allocation too large: %lx\n", size) FLUSH;
82 #endif /* HAS_64K_LIMIT */
83 #ifdef PERL_TRACK_MEMPOOL
87 if ((SSize_t)size < 0)
88 Perl_croak_nocontext("panic: malloc, size=%"UVuf, (UV) size);
90 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
91 PERL_ALLOC_CHECK(ptr);
93 #ifdef PERL_TRACK_MEMPOOL
94 struct perl_memory_debug_header *const header
95 = (struct perl_memory_debug_header *)ptr;
99 PoisonNew(((char *)ptr), size, char);
102 #ifdef PERL_TRACK_MEMPOOL
103 header->interpreter = aTHX;
104 /* Link us into the list. */
105 header->prev = &PL_memory_debug_header;
106 header->next = PL_memory_debug_header.next;
107 PL_memory_debug_header.next = header;
108 header->next->prev = header;
112 ptr = (Malloc_t)((char*)ptr+sTHX);
114 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
118 #ifndef ALWAYS_NEED_THX
130 /* paranoid version of system's realloc() */
133 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
135 #ifdef ALWAYS_NEED_THX
139 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
140 Malloc_t PerlMem_realloc();
141 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
145 PerlIO_printf(Perl_error_log,
146 "Reallocation too large: %lx\n", size) FLUSH;
149 #endif /* HAS_64K_LIMIT */
156 return safesysmalloc(size);
157 #ifdef PERL_TRACK_MEMPOOL
158 where = (Malloc_t)((char*)where-sTHX);
161 struct perl_memory_debug_header *const header
162 = (struct perl_memory_debug_header *)where;
164 if (header->interpreter != aTHX) {
165 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
166 header->interpreter, aTHX);
168 assert(header->next->prev == header);
169 assert(header->prev->next == header);
171 if (header->size > size) {
172 const MEM_SIZE freed_up = header->size - size;
173 char *start_of_freed = ((char *)where) + size;
174 PoisonFree(start_of_freed, freed_up, char);
181 if ((SSize_t)size < 0)
182 Perl_croak_nocontext("panic: realloc, size=%"UVuf, (UV)size);
184 ptr = (Malloc_t)PerlMem_realloc(where,size);
185 PERL_ALLOC_CHECK(ptr);
187 /* MUST do this fixup first, before doing ANYTHING else, as anything else
188 might allocate memory/free/move memory, and until we do the fixup, it
189 may well be chasing (and writing to) free memory. */
190 #ifdef PERL_TRACK_MEMPOOL
192 struct perl_memory_debug_header *const header
193 = (struct perl_memory_debug_header *)ptr;
196 if (header->size < size) {
197 const MEM_SIZE fresh = size - header->size;
198 char *start_of_fresh = ((char *)ptr) + size;
199 PoisonNew(start_of_fresh, fresh, char);
203 header->next->prev = header;
204 header->prev->next = header;
206 ptr = (Malloc_t)((char*)ptr+sTHX);
210 /* In particular, must do that fixup above before logging anything via
211 *printf(), as it can reallocate memory, which can cause SEGVs. */
213 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
214 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
221 #ifndef ALWAYS_NEED_THX
233 /* safe version of system's free() */
236 Perl_safesysfree(Malloc_t where)
238 #ifdef ALWAYS_NEED_THX
243 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
245 #ifdef PERL_TRACK_MEMPOOL
246 where = (Malloc_t)((char*)where-sTHX);
248 struct perl_memory_debug_header *const header
249 = (struct perl_memory_debug_header *)where;
251 if (header->interpreter != aTHX) {
252 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
253 header->interpreter, aTHX);
256 Perl_croak_nocontext("panic: duplicate free");
259 Perl_croak_nocontext("panic: bad free, header->next==NULL");
260 if (header->next->prev != header || header->prev->next != header) {
261 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
262 "header=%p, ->prev->next=%p",
263 header->next->prev, header,
266 /* Unlink us from the chain. */
267 header->next->prev = header->prev;
268 header->prev->next = header->next;
270 PoisonNew(where, header->size, char);
272 /* Trigger the duplicate free warning. */
280 /* safe version of system's calloc() */
283 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
285 #ifdef ALWAYS_NEED_THX
289 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
290 MEM_SIZE total_size = 0;
293 /* Even though calloc() for zero bytes is strange, be robust. */
294 if (size && (count <= MEM_SIZE_MAX / size)) {
295 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
296 total_size = size * count;
301 #ifdef PERL_TRACK_MEMPOOL
302 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
308 if (total_size > 0xffff) {
309 PerlIO_printf(Perl_error_log,
310 "Allocation too large: %lx\n", total_size) FLUSH;
313 #endif /* HAS_64K_LIMIT */
315 if ((SSize_t)size < 0 || (SSize_t)count < 0)
316 Perl_croak_nocontext("panic: calloc, size=%"UVuf", count=%"UVuf,
317 (UV)size, (UV)count);
319 #ifdef PERL_TRACK_MEMPOOL
320 /* Have to use malloc() because we've added some space for our tracking
322 /* malloc(0) is non-portable. */
323 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
325 /* Use calloc() because it might save a memset() if the memory is fresh
326 and clean from the OS. */
328 ptr = (Malloc_t)PerlMem_calloc(count, size);
329 else /* calloc(0) is non-portable. */
330 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
332 PERL_ALLOC_CHECK(ptr);
333 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));
335 #ifdef PERL_TRACK_MEMPOOL
337 struct perl_memory_debug_header *const header
338 = (struct perl_memory_debug_header *)ptr;
340 memset((void*)ptr, 0, total_size);
341 header->interpreter = aTHX;
342 /* Link us into the list. */
343 header->prev = &PL_memory_debug_header;
344 header->next = PL_memory_debug_header.next;
345 PL_memory_debug_header.next = header;
346 header->next->prev = header;
348 header->size = total_size;
350 ptr = (Malloc_t)((char*)ptr+sTHX);
356 #ifndef ALWAYS_NEED_THX
365 /* These must be defined when not using Perl's malloc for binary
370 Malloc_t Perl_malloc (MEM_SIZE nbytes)
373 return (Malloc_t)PerlMem_malloc(nbytes);
376 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
379 return (Malloc_t)PerlMem_calloc(elements, size);
382 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
385 return (Malloc_t)PerlMem_realloc(where, nbytes);
388 Free_t Perl_mfree (Malloc_t where)
396 /* copy a string up to some (non-backslashed) delimiter, if any */
399 Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
403 PERL_ARGS_ASSERT_DELIMCPY;
405 for (tolen = 0; from < fromend; from++, tolen++) {
407 if (from[1] != delim) {
414 else if (*from == delim)
425 /* return ptr to little string in big string, NULL if not found */
426 /* This routine was donated by Corey Satten. */
429 Perl_instr(register const char *big, register const char *little)
433 PERL_ARGS_ASSERT_INSTR;
444 for (x=big,s=little; *s; /**/ ) {
455 return (char*)(big-1);
460 /* same as instr but allow embedded nulls. The end pointers point to 1 beyond
461 * the final character desired to be checked */
464 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
466 PERL_ARGS_ASSERT_NINSTR;
470 const char first = *little;
472 bigend -= lend - little++;
474 while (big <= bigend) {
475 if (*big++ == first) {
476 for (x=big,s=little; s < lend; x++,s++) {
480 return (char*)(big-1);
487 /* reverse of the above--find last substring */
490 Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
493 const I32 first = *little;
494 const char * const littleend = lend;
496 PERL_ARGS_ASSERT_RNINSTR;
498 if (little >= littleend)
499 return (char*)bigend;
501 big = bigend - (littleend - little++);
502 while (big >= bigbeg) {
506 for (x=big+2,s=little; s < littleend; /**/ ) {
515 return (char*)(big+1);
520 /* As a space optimization, we do not compile tables for strings of length
521 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
522 special-cased in fbm_instr().
524 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
527 =head1 Miscellaneous Functions
529 =for apidoc fbm_compile
531 Analyses the string in order to make fast searches on it using fbm_instr()
532 -- the Boyer-Moore algorithm.
538 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
548 PERL_ARGS_ASSERT_FBM_COMPILE;
550 if (isGV_with_GP(sv))
556 if (flags & FBMcf_TAIL) {
557 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
558 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
559 if (mg && mg->mg_len >= 0)
562 s = (U8*)SvPV_force_mutable(sv, len);
563 if (len == 0) /* TAIL might be on a zero-length string. */
565 SvUPGRADE(sv, SVt_PVMG);
570 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
571 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
572 to call SvVALID_off() if the scalar was assigned to.
574 The comment itself (and "deeper magic" below) date back to
575 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
577 where the magic (presumably) was that the scalar had a BM table hidden
580 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
581 the table instead of the previous (somewhat hacky) approach of co-opting
582 the string buffer and storing it after the string. */
584 assert(!mg_find(sv, PERL_MAGIC_bm));
585 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
589 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
591 const U8 mlen = (len>255) ? 255 : (U8)len;
592 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
595 Newx(table, 256, U8);
596 memset((void*)table, mlen, 256);
597 mg->mg_ptr = (char *)table;
600 s += len - 1; /* last char */
603 if (table[*s] == mlen)
609 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
610 for (i = 0; i < len; i++) {
611 if (PL_freq[s[i]] < frequency) {
613 frequency = PL_freq[s[i]];
616 BmRARE(sv) = s[rarest];
617 BmPREVIOUS(sv) = rarest;
618 BmUSEFUL(sv) = 100; /* Initial value */
619 if (flags & FBMcf_TAIL)
621 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
622 BmRARE(sv), BmPREVIOUS(sv)));
625 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
626 /* If SvTAIL is actually due to \Z or \z, this gives false positives
630 =for apidoc fbm_instr
632 Returns the location of the SV in the string delimited by C<big> and
633 C<bigend>. It returns C<NULL> if the string can't be found. The C<sv>
634 does not have to be fbm_compiled, but the search will not be as fast
641 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
645 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
646 STRLEN littlelen = l;
647 const I32 multiline = flags & FBMrf_MULTILINE;
649 PERL_ARGS_ASSERT_FBM_INSTR;
651 if ((STRLEN)(bigend - big) < littlelen) {
652 if ( SvTAIL(littlestr)
653 && ((STRLEN)(bigend - big) == littlelen - 1)
655 || (*big == *little &&
656 memEQ((char *)big, (char *)little, littlelen - 1))))
661 switch (littlelen) { /* Special cases for 0, 1 and 2 */
663 return (char*)big; /* Cannot be SvTAIL! */
665 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
666 /* Know that bigend != big. */
667 if (bigend[-1] == '\n')
668 return (char *)(bigend - 1);
669 return (char *) bigend;
677 if (SvTAIL(littlestr))
678 return (char *) bigend;
681 if (SvTAIL(littlestr) && !multiline) {
682 if (bigend[-1] == '\n' && bigend[-2] == *little)
683 return (char*)bigend - 2;
684 if (bigend[-1] == *little)
685 return (char*)bigend - 1;
689 /* This should be better than FBM if c1 == c2, and almost
690 as good otherwise: maybe better since we do less indirection.
691 And we save a lot of memory by caching no table. */
692 const unsigned char c1 = little[0];
693 const unsigned char c2 = little[1];
698 while (s <= bigend) {
708 goto check_1char_anchor;
719 goto check_1char_anchor;
722 while (s <= bigend) {
727 goto check_1char_anchor;
736 check_1char_anchor: /* One char and anchor! */
737 if (SvTAIL(littlestr) && (*bigend == *little))
738 return (char *)bigend; /* bigend is already decremented. */
741 break; /* Only lengths 0 1 and 2 have special-case code. */
744 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
745 s = bigend - littlelen;
746 if (s >= big && bigend[-1] == '\n' && *s == *little
747 /* Automatically of length > 2 */
748 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
750 return (char*)s; /* how sweet it is */
753 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
755 return (char*)s + 1; /* how sweet it is */
759 if (!SvVALID(littlestr)) {
760 char * const b = ninstr((char*)big,(char*)bigend,
761 (char*)little, (char*)little + littlelen);
763 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
764 /* Chop \n from littlestr: */
765 s = bigend - littlelen + 1;
767 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
777 if (littlelen > (STRLEN)(bigend - big))
781 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
782 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
783 const unsigned char *oldlittle;
785 --littlelen; /* Last char found by table lookup */
788 little += littlelen; /* last char */
794 if ((tmp = table[*s])) {
795 if ((s += tmp) < bigend)
799 else { /* less expensive than calling strncmp() */
800 unsigned char * const olds = s;
805 if (*--s == *--little)
807 s = olds + 1; /* here we pay the price for failure */
809 if (s < bigend) /* fake up continue to outer loop */
819 && memEQ((char *)(bigend - littlelen),
820 (char *)(oldlittle - littlelen), littlelen) )
821 return (char*)bigend - littlelen;
827 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
830 PERL_ARGS_ASSERT_SCREAMINSTR;
831 PERL_UNUSED_ARG(bigstr);
832 PERL_UNUSED_ARG(littlestr);
833 PERL_UNUSED_ARG(start_shift);
834 PERL_UNUSED_ARG(end_shift);
835 PERL_UNUSED_ARG(old_posp);
836 PERL_UNUSED_ARG(last);
838 /* This function must only ever be called on a scalar with study magic,
839 but those do not happen any more. */
840 Perl_croak(aTHX_ "panic: screaminstr");
847 Returns true if the leading len bytes of the strings s1 and s2 are the same
848 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
849 match themselves and their opposite case counterparts. Non-cased and non-ASCII
850 range bytes match only themselves.
857 Perl_foldEQ(const char *s1, const char *s2, register I32 len)
859 const U8 *a = (const U8 *)s1;
860 const U8 *b = (const U8 *)s2;
862 PERL_ARGS_ASSERT_FOLDEQ;
867 if (*a != *b && *a != PL_fold[*b])
874 Perl_foldEQ_latin1(const char *s1, const char *s2, register I32 len)
876 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
877 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
878 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
879 * does it check that the strings each have at least 'len' characters */
881 const U8 *a = (const U8 *)s1;
882 const U8 *b = (const U8 *)s2;
884 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
889 if (*a != *b && *a != PL_fold_latin1[*b]) {
898 =for apidoc foldEQ_locale
900 Returns true if the leading len bytes of the strings s1 and s2 are the same
901 case-insensitively in the current locale; false otherwise.
907 Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
910 const U8 *a = (const U8 *)s1;
911 const U8 *b = (const U8 *)s2;
913 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
918 if (*a != *b && *a != PL_fold_locale[*b])
925 /* copy a string to a safe spot */
928 =head1 Memory Management
932 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
933 string which is a duplicate of C<pv>. The size of the string is
934 determined by C<strlen()>. The memory allocated for the new string can
935 be freed with the C<Safefree()> function.
941 Perl_savepv(pTHX_ const char *pv)
948 const STRLEN pvlen = strlen(pv)+1;
949 Newx(newaddr, pvlen, char);
950 return (char*)memcpy(newaddr, pv, pvlen);
954 /* same thing but with a known length */
959 Perl's version of what C<strndup()> would be if it existed. Returns a
960 pointer to a newly allocated string which is a duplicate of the first
961 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
962 the new string can be freed with the C<Safefree()> function.
968 Perl_savepvn(pTHX_ const char *pv, register I32 len)
975 Newx(newaddr,len+1,char);
976 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
978 /* might not be null terminated */
980 return (char *) CopyD(pv,newaddr,len,char);
983 return (char *) ZeroD(newaddr,len+1,char);
988 =for apidoc savesharedpv
990 A version of C<savepv()> which allocates the duplicate string in memory
991 which is shared between threads.
996 Perl_savesharedpv(pTHX_ const char *pv)
1003 pvlen = strlen(pv)+1;
1004 newaddr = (char*)PerlMemShared_malloc(pvlen);
1008 return (char*)memcpy(newaddr, pv, pvlen);
1012 =for apidoc savesharedpvn
1014 A version of C<savepvn()> which allocates the duplicate string in memory
1015 which is shared between threads. (With the specific difference that a NULL
1016 pointer is not acceptable)
1021 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1023 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1025 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1030 newaddr[len] = '\0';
1031 return (char*)memcpy(newaddr, pv, len);
1035 =for apidoc savesvpv
1037 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1038 the passed in SV using C<SvPV()>
1044 Perl_savesvpv(pTHX_ SV *sv)
1047 const char * const pv = SvPV_const(sv, len);
1050 PERL_ARGS_ASSERT_SAVESVPV;
1053 Newx(newaddr,len,char);
1054 return (char *) CopyD(pv,newaddr,len,char);
1058 =for apidoc savesharedsvpv
1060 A version of C<savesharedpv()> which allocates the duplicate string in
1061 memory which is shared between threads.
1067 Perl_savesharedsvpv(pTHX_ SV *sv)
1070 const char * const pv = SvPV_const(sv, len);
1072 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1074 return savesharedpvn(pv, len);
1077 /* the SV for Perl_form() and mess() is not kept in an arena */
1086 if (PL_phase != PERL_PHASE_DESTRUCT)
1087 return newSVpvs_flags("", SVs_TEMP);
1092 /* Create as PVMG now, to avoid any upgrading later */
1094 Newxz(any, 1, XPVMG);
1095 SvFLAGS(sv) = SVt_PVMG;
1096 SvANY(sv) = (void*)any;
1098 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1103 #if defined(PERL_IMPLICIT_CONTEXT)
1105 Perl_form_nocontext(const char* pat, ...)
1110 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1111 va_start(args, pat);
1112 retval = vform(pat, &args);
1116 #endif /* PERL_IMPLICIT_CONTEXT */
1119 =head1 Miscellaneous Functions
1122 Takes a sprintf-style format pattern and conventional
1123 (non-SV) arguments and returns the formatted string.
1125 (char *) Perl_form(pTHX_ const char* pat, ...)
1127 can be used any place a string (char *) is required:
1129 char * s = Perl_form("%d.%d",major,minor);
1131 Uses a single private buffer so if you want to format several strings you
1132 must explicitly copy the earlier strings away (and free the copies when you
1139 Perl_form(pTHX_ const char* pat, ...)
1143 PERL_ARGS_ASSERT_FORM;
1144 va_start(args, pat);
1145 retval = vform(pat, &args);
1151 Perl_vform(pTHX_ const char *pat, va_list *args)
1153 SV * const sv = mess_alloc();
1154 PERL_ARGS_ASSERT_VFORM;
1155 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1160 =for apidoc Am|SV *|mess|const char *pat|...
1162 Take a sprintf-style format pattern and argument list. These are used to
1163 generate a string message. If the message does not end with a newline,
1164 then it will be extended with some indication of the current location
1165 in the code, as described for L</mess_sv>.
1167 Normally, the resulting message is returned in a new mortal SV.
1168 During global destruction a single SV may be shared between uses of
1174 #if defined(PERL_IMPLICIT_CONTEXT)
1176 Perl_mess_nocontext(const char *pat, ...)
1181 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1182 va_start(args, pat);
1183 retval = vmess(pat, &args);
1187 #endif /* PERL_IMPLICIT_CONTEXT */
1190 Perl_mess(pTHX_ const char *pat, ...)
1194 PERL_ARGS_ASSERT_MESS;
1195 va_start(args, pat);
1196 retval = vmess(pat, &args);
1202 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1205 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1207 PERL_ARGS_ASSERT_CLOSEST_COP;
1209 if (!o || o == PL_op)
1212 if (o->op_flags & OPf_KIDS) {
1214 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1217 /* If the OP_NEXTSTATE has been optimised away we can still use it
1218 * the get the file and line number. */
1220 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1221 cop = (const COP *)kid;
1223 /* Keep searching, and return when we've found something. */
1225 new_cop = closest_cop(cop, kid);
1231 /* Nothing found. */
1237 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1239 Expands a message, intended for the user, to include an indication of
1240 the current location in the code, if the message does not already appear
1243 C<basemsg> is the initial message or object. If it is a reference, it
1244 will be used as-is and will be the result of this function. Otherwise it
1245 is used as a string, and if it already ends with a newline, it is taken
1246 to be complete, and the result of this function will be the same string.
1247 If the message does not end with a newline, then a segment such as C<at
1248 foo.pl line 37> will be appended, and possibly other clauses indicating
1249 the current state of execution. The resulting message will end with a
1252 Normally, the resulting message is returned in a new mortal SV.
1253 During global destruction a single SV may be shared between uses of this
1254 function. If C<consume> is true, then the function is permitted (but not
1255 required) to modify and return C<basemsg> instead of allocating a new SV.
1261 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1266 PERL_ARGS_ASSERT_MESS_SV;
1268 if (SvROK(basemsg)) {
1274 sv_setsv(sv, basemsg);
1279 if (SvPOK(basemsg) && consume) {
1284 sv_copypv(sv, basemsg);
1287 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1289 * Try and find the file and line for PL_op. This will usually be
1290 * PL_curcop, but it might be a cop that has been optimised away. We
1291 * can try to find such a cop by searching through the optree starting
1292 * from the sibling of PL_curcop.
1295 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1300 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1301 OutCopFILE(cop), (IV)CopLINE(cop));
1302 /* Seems that GvIO() can be untrustworthy during global destruction. */
1303 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1304 && IoLINES(GvIOp(PL_last_in_gv)))
1307 const bool line_mode = (RsSIMPLE(PL_rs) &&
1308 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1309 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1310 SVfARG(PL_last_in_gv == PL_argvgv
1312 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1313 line_mode ? "line" : "chunk",
1314 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1316 if (PL_phase == PERL_PHASE_DESTRUCT)
1317 sv_catpvs(sv, " during global destruction");
1318 sv_catpvs(sv, ".\n");
1324 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1326 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1327 argument list. These are used to generate a string message. If the
1328 message does not end with a newline, then it will be extended with
1329 some indication of the current location in the code, as described for
1332 Normally, the resulting message is returned in a new mortal SV.
1333 During global destruction a single SV may be shared between uses of
1340 Perl_vmess(pTHX_ const char *pat, va_list *args)
1343 SV * const sv = mess_alloc();
1345 PERL_ARGS_ASSERT_VMESS;
1347 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1348 return mess_sv(sv, 1);
1352 Perl_write_to_stderr(pTHX_ SV* msv)
1358 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1360 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1361 && (io = GvIO(PL_stderrgv))
1362 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1363 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1364 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1367 /* SFIO can really mess with your errno */
1370 PerlIO * const serr = Perl_error_log;
1372 do_print(msv, serr);
1373 (void)PerlIO_flush(serr);
1381 =head1 Warning and Dieing
1384 /* Common code used in dieing and warning */
1387 S_with_queued_errors(pTHX_ SV *ex)
1389 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1390 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1391 sv_catsv(PL_errors, ex);
1392 ex = sv_mortalcopy(PL_errors);
1393 SvCUR_set(PL_errors, 0);
1399 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1405 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1406 /* sv_2cv might call Perl_croak() or Perl_warner() */
1407 SV * const oldhook = *hook;
1415 cv = sv_2cv(oldhook, &stash, &gv, 0);
1417 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1427 exarg = newSVsv(ex);
1428 SvREADONLY_on(exarg);
1431 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1435 call_sv(MUTABLE_SV(cv), G_DISCARD);
1444 =for apidoc Am|OP *|die_sv|SV *baseex
1446 Behaves the same as L</croak_sv>, except for the return type.
1447 It should be used only where the C<OP *> return type is required.
1448 The function never actually returns.
1454 Perl_die_sv(pTHX_ SV *baseex)
1456 PERL_ARGS_ASSERT_DIE_SV;
1458 assert(0); /* NOTREACHED */
1463 =for apidoc Am|OP *|die|const char *pat|...
1465 Behaves the same as L</croak>, except for the return type.
1466 It should be used only where the C<OP *> return type is required.
1467 The function never actually returns.
1472 #if defined(PERL_IMPLICIT_CONTEXT)
1474 Perl_die_nocontext(const char* pat, ...)
1478 va_start(args, pat);
1480 assert(0); /* NOTREACHED */
1484 #endif /* PERL_IMPLICIT_CONTEXT */
1487 Perl_die(pTHX_ const char* pat, ...)
1490 va_start(args, pat);
1492 assert(0); /* NOTREACHED */
1498 =for apidoc Am|void|croak_sv|SV *baseex
1500 This is an XS interface to Perl's C<die> function.
1502 C<baseex> is the error message or object. If it is a reference, it
1503 will be used as-is. Otherwise it is used as a string, and if it does
1504 not end with a newline then it will be extended with some indication of
1505 the current location in the code, as described for L</mess_sv>.
1507 The error message or object will be used as an exception, by default
1508 returning control to the nearest enclosing C<eval>, but subject to
1509 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1510 function never returns normally.
1512 To die with a simple string message, the L</croak> function may be
1519 Perl_croak_sv(pTHX_ SV *baseex)
1521 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1522 PERL_ARGS_ASSERT_CROAK_SV;
1523 invoke_exception_hook(ex, FALSE);
1528 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1530 This is an XS interface to Perl's C<die> function.
1532 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1533 argument list. These are used to generate a string message. If the
1534 message does not end with a newline, then it will be extended with
1535 some indication of the current location in the code, as described for
1538 The error message will be used as an exception, by default
1539 returning control to the nearest enclosing C<eval>, but subject to
1540 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1541 function never returns normally.
1543 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1544 (C<$@>) will be used as an error message or object instead of building an
1545 error message from arguments. If you want to throw a non-string object,
1546 or build an error message in an SV yourself, it is preferable to use
1547 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1553 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1555 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1556 invoke_exception_hook(ex, FALSE);
1561 =for apidoc Am|void|croak|const char *pat|...
1563 This is an XS interface to Perl's C<die> function.
1565 Take a sprintf-style format pattern and argument list. These are used to
1566 generate a string message. If the message does not end with a newline,
1567 then it will be extended with some indication of the current location
1568 in the code, as described for L</mess_sv>.
1570 The error message will be used as an exception, by default
1571 returning control to the nearest enclosing C<eval>, but subject to
1572 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1573 function never returns normally.
1575 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1576 (C<$@>) will be used as an error message or object instead of building an
1577 error message from arguments. If you want to throw a non-string object,
1578 or build an error message in an SV yourself, it is preferable to use
1579 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1584 #if defined(PERL_IMPLICIT_CONTEXT)
1586 Perl_croak_nocontext(const char *pat, ...)
1590 va_start(args, pat);
1592 assert(0); /* NOTREACHED */
1595 #endif /* PERL_IMPLICIT_CONTEXT */
1598 Perl_croak(pTHX_ const char *pat, ...)
1601 va_start(args, pat);
1603 assert(0); /* NOTREACHED */
1608 =for apidoc Am|void|croak_no_modify
1610 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1611 terser object code than using C<Perl_croak>. Less code used on exception code
1612 paths reduces CPU cache pressure.
1618 Perl_croak_no_modify()
1620 Perl_croak_nocontext( "%s", PL_no_modify);
1623 /* does not return, used in util.c perlio.c and win32.c
1624 This is typically called when malloc returns NULL.
1631 /* Can't use PerlIO to write as it allocates memory */
1632 PerlLIO_write(PerlIO_fileno(Perl_error_log),
1633 PL_no_mem, sizeof(PL_no_mem)-1);
1638 =for apidoc Am|void|warn_sv|SV *baseex
1640 This is an XS interface to Perl's C<warn> function.
1642 C<baseex> is the error message or object. If it is a reference, it
1643 will be used as-is. Otherwise it is used as a string, and if it does
1644 not end with a newline then it will be extended with some indication of
1645 the current location in the code, as described for L</mess_sv>.
1647 The error message or object will by default be written to standard error,
1648 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1650 To warn with a simple string message, the L</warn> function may be
1657 Perl_warn_sv(pTHX_ SV *baseex)
1659 SV *ex = mess_sv(baseex, 0);
1660 PERL_ARGS_ASSERT_WARN_SV;
1661 if (!invoke_exception_hook(ex, TRUE))
1662 write_to_stderr(ex);
1666 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1668 This is an XS interface to Perl's C<warn> function.
1670 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1671 argument list. These are used to generate a string message. If the
1672 message does not end with a newline, then it will be extended with
1673 some indication of the current location in the code, as described for
1676 The error message or object will by default be written to standard error,
1677 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1679 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1685 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1687 SV *ex = vmess(pat, args);
1688 PERL_ARGS_ASSERT_VWARN;
1689 if (!invoke_exception_hook(ex, TRUE))
1690 write_to_stderr(ex);
1694 =for apidoc Am|void|warn|const char *pat|...
1696 This is an XS interface to Perl's C<warn> function.
1698 Take a sprintf-style format pattern and argument list. These are used to
1699 generate a string message. If the message does not end with a newline,
1700 then it will be extended with some indication of the current location
1701 in the code, as described for L</mess_sv>.
1703 The error message or object will by default be written to standard error,
1704 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1706 Unlike with L</croak>, C<pat> is not permitted to be null.
1711 #if defined(PERL_IMPLICIT_CONTEXT)
1713 Perl_warn_nocontext(const char *pat, ...)
1717 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1718 va_start(args, pat);
1722 #endif /* PERL_IMPLICIT_CONTEXT */
1725 Perl_warn(pTHX_ const char *pat, ...)
1728 PERL_ARGS_ASSERT_WARN;
1729 va_start(args, pat);
1734 #if defined(PERL_IMPLICIT_CONTEXT)
1736 Perl_warner_nocontext(U32 err, const char *pat, ...)
1740 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1741 va_start(args, pat);
1742 vwarner(err, pat, &args);
1745 #endif /* PERL_IMPLICIT_CONTEXT */
1748 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1750 PERL_ARGS_ASSERT_CK_WARNER_D;
1752 if (Perl_ckwarn_d(aTHX_ err)) {
1754 va_start(args, pat);
1755 vwarner(err, pat, &args);
1761 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1763 PERL_ARGS_ASSERT_CK_WARNER;
1765 if (Perl_ckwarn(aTHX_ err)) {
1767 va_start(args, pat);
1768 vwarner(err, pat, &args);
1774 Perl_warner(pTHX_ U32 err, const char* pat,...)
1777 PERL_ARGS_ASSERT_WARNER;
1778 va_start(args, pat);
1779 vwarner(err, pat, &args);
1784 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1787 PERL_ARGS_ASSERT_VWARNER;
1788 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1789 SV * const msv = vmess(pat, args);
1791 invoke_exception_hook(msv, FALSE);
1795 Perl_vwarn(aTHX_ pat, args);
1799 /* implements the ckWARN? macros */
1802 Perl_ckwarn(pTHX_ U32 w)
1805 /* If lexical warnings have not been set, use $^W. */
1807 return PL_dowarn & G_WARN_ON;
1809 return ckwarn_common(w);
1812 /* implements the ckWARN?_d macro */
1815 Perl_ckwarn_d(pTHX_ U32 w)
1818 /* If lexical warnings have not been set then default classes warn. */
1822 return ckwarn_common(w);
1826 S_ckwarn_common(pTHX_ U32 w)
1828 if (PL_curcop->cop_warnings == pWARN_ALL)
1831 if (PL_curcop->cop_warnings == pWARN_NONE)
1834 /* Check the assumption that at least the first slot is non-zero. */
1835 assert(unpackWARN1(w));
1837 /* Check the assumption that it is valid to stop as soon as a zero slot is
1839 if (!unpackWARN2(w)) {
1840 assert(!unpackWARN3(w));
1841 assert(!unpackWARN4(w));
1842 } else if (!unpackWARN3(w)) {
1843 assert(!unpackWARN4(w));
1846 /* Right, dealt with all the special cases, which are implemented as non-
1847 pointers, so there is a pointer to a real warnings mask. */
1849 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1851 } while (w >>= WARNshift);
1856 /* Set buffer=NULL to get a new one. */
1858 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1860 const MEM_SIZE len_wanted =
1861 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
1862 PERL_UNUSED_CONTEXT;
1863 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1866 (specialWARN(buffer) ?
1867 PerlMemShared_malloc(len_wanted) :
1868 PerlMemShared_realloc(buffer, len_wanted));
1870 Copy(bits, (buffer + 1), size, char);
1871 if (size < WARNsize)
1872 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
1876 /* since we've already done strlen() for both nam and val
1877 * we can use that info to make things faster than
1878 * sprintf(s, "%s=%s", nam, val)
1880 #define my_setenv_format(s, nam, nlen, val, vlen) \
1881 Copy(nam, s, nlen, char); \
1883 Copy(val, s+(nlen+1), vlen, char); \
1884 *(s+(nlen+1+vlen)) = '\0'
1886 #ifdef USE_ENVIRON_ARRAY
1887 /* VMS' my_setenv() is in vms.c */
1888 #if !defined(WIN32) && !defined(NETWARE)
1890 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1894 /* only parent thread can modify process environment */
1895 if (PL_curinterp == aTHX)
1898 #ifndef PERL_USE_SAFE_PUTENV
1899 if (!PL_use_safe_putenv) {
1900 /* most putenv()s leak, so we manipulate environ directly */
1902 const I32 len = strlen(nam);
1905 /* where does it go? */
1906 for (i = 0; environ[i]; i++) {
1907 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1911 if (environ == PL_origenviron) { /* need we copy environment? */
1917 while (environ[max])
1919 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1920 for (j=0; j<max; j++) { /* copy environment */
1921 const int len = strlen(environ[j]);
1922 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1923 Copy(environ[j], tmpenv[j], len+1, char);
1926 environ = tmpenv; /* tell exec where it is now */
1929 safesysfree(environ[i]);
1930 while (environ[i]) {
1931 environ[i] = environ[i+1];
1936 if (!environ[i]) { /* does not exist yet */
1937 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1938 environ[i+1] = NULL; /* make sure it's null terminated */
1941 safesysfree(environ[i]);
1945 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1946 /* all that work just for this */
1947 my_setenv_format(environ[i], nam, nlen, val, vlen);
1950 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
1951 # if defined(HAS_UNSETENV)
1953 (void)unsetenv(nam);
1955 (void)setenv(nam, val, 1);
1957 # else /* ! HAS_UNSETENV */
1958 (void)setenv(nam, val, 1);
1959 # endif /* HAS_UNSETENV */
1961 # if defined(HAS_UNSETENV)
1963 (void)unsetenv(nam);
1965 const int nlen = strlen(nam);
1966 const int vlen = strlen(val);
1967 char * const new_env =
1968 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1969 my_setenv_format(new_env, nam, nlen, val, vlen);
1970 (void)putenv(new_env);
1972 # else /* ! HAS_UNSETENV */
1974 const int nlen = strlen(nam);
1980 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1981 /* all that work just for this */
1982 my_setenv_format(new_env, nam, nlen, val, vlen);
1983 (void)putenv(new_env);
1984 # endif /* HAS_UNSETENV */
1985 # endif /* __CYGWIN__ */
1986 #ifndef PERL_USE_SAFE_PUTENV
1992 #else /* WIN32 || NETWARE */
1995 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1999 const int nlen = strlen(nam);
2006 Newx(envstr, nlen+vlen+2, char);
2007 my_setenv_format(envstr, nam, nlen, val, vlen);
2008 (void)PerlEnv_putenv(envstr);
2012 #endif /* WIN32 || NETWARE */
2014 #endif /* !VMS && !EPOC*/
2016 #ifdef UNLINK_ALL_VERSIONS
2018 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2022 PERL_ARGS_ASSERT_UNLNK;
2024 while (PerlLIO_unlink(f) >= 0)
2026 return retries ? 0 : -1;
2030 /* this is a drop-in replacement for bcopy() */
2031 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2033 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2035 char * const retval = to;
2037 PERL_ARGS_ASSERT_MY_BCOPY;
2041 if (from - to >= 0) {
2049 *(--to) = *(--from);
2055 /* this is a drop-in replacement for memset() */
2058 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2060 char * const retval = loc;
2062 PERL_ARGS_ASSERT_MY_MEMSET;
2072 /* this is a drop-in replacement for bzero() */
2073 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2075 Perl_my_bzero(register char *loc, register I32 len)
2077 char * const retval = loc;
2079 PERL_ARGS_ASSERT_MY_BZERO;
2089 /* this is a drop-in replacement for memcmp() */
2090 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2092 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2094 const U8 *a = (const U8 *)s1;
2095 const U8 *b = (const U8 *)s2;
2098 PERL_ARGS_ASSERT_MY_MEMCMP;
2103 if ((tmp = *a++ - *b++))
2108 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2111 /* This vsprintf replacement should generally never get used, since
2112 vsprintf was available in both System V and BSD 2.11. (There may
2113 be some cross-compilation or embedded set-ups where it is needed,
2116 If you encounter a problem in this function, it's probably a symptom
2117 that Configure failed to detect your system's vprintf() function.
2118 See the section on "item vsprintf" in the INSTALL file.
2120 This version may compile on systems with BSD-ish <stdio.h>,
2121 but probably won't on others.
2124 #ifdef USE_CHAR_VSPRINTF
2129 vsprintf(char *dest, const char *pat, void *args)
2133 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2134 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2135 FILE_cnt(&fakebuf) = 32767;
2137 /* These probably won't compile -- If you really need
2138 this, you'll have to figure out some other method. */
2139 fakebuf._ptr = dest;
2140 fakebuf._cnt = 32767;
2145 fakebuf._flag = _IOWRT|_IOSTRG;
2146 _doprnt(pat, args, &fakebuf); /* what a kludge */
2147 #if defined(STDIO_PTR_LVALUE)
2148 *(FILE_ptr(&fakebuf)++) = '\0';
2150 /* PerlIO has probably #defined away fputc, but we want it here. */
2152 # undef fputc /* XXX Should really restore it later */
2154 (void)fputc('\0', &fakebuf);
2156 #ifdef USE_CHAR_VSPRINTF
2159 return 0; /* perl doesn't use return value */
2163 #endif /* HAS_VPRINTF */
2166 #if BYTEORDER != 0x4321
2168 Perl_my_swap(pTHX_ short s)
2170 #if (BYTEORDER & 1) == 0
2173 result = ((s & 255) << 8) + ((s >> 8) & 255);
2181 Perl_my_htonl(pTHX_ long l)
2185 char c[sizeof(long)];
2188 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2189 #if BYTEORDER == 0x12345678
2192 u.c[0] = (l >> 24) & 255;
2193 u.c[1] = (l >> 16) & 255;
2194 u.c[2] = (l >> 8) & 255;
2198 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2199 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2204 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2205 u.c[o & 0xf] = (l >> s) & 255;
2213 Perl_my_ntohl(pTHX_ long l)
2217 char c[sizeof(long)];
2220 #if BYTEORDER == 0x1234
2221 u.c[0] = (l >> 24) & 255;
2222 u.c[1] = (l >> 16) & 255;
2223 u.c[2] = (l >> 8) & 255;
2227 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2228 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2235 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2236 l |= (u.c[o & 0xf] & 255) << s;
2243 #endif /* BYTEORDER != 0x4321 */
2247 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2248 * If these functions are defined,
2249 * the BYTEORDER is neither 0x1234 nor 0x4321.
2250 * However, this is not assumed.
2254 #define HTOLE(name,type) \
2256 name (register type n) \
2260 char c[sizeof(type)]; \
2264 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2265 u.c[i] = (n >> s) & 0xFF; \
2270 #define LETOH(name,type) \
2272 name (register type n) \
2276 char c[sizeof(type)]; \
2282 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2283 n |= ((type)(u.c[i] & 0xFF)) << s; \
2289 * Big-endian byte order functions.
2292 #define HTOBE(name,type) \
2294 name (register type n) \
2298 char c[sizeof(type)]; \
2301 U32 s = 8*(sizeof(u.c)-1); \
2302 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2303 u.c[i] = (n >> s) & 0xFF; \
2308 #define BETOH(name,type) \
2310 name (register type n) \
2314 char c[sizeof(type)]; \
2317 U32 s = 8*(sizeof(u.c)-1); \
2320 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2321 n |= ((type)(u.c[i] & 0xFF)) << s; \
2327 * If we just can't do it...
2330 #define NOT_AVAIL(name,type) \
2332 name (register type n) \
2334 Perl_croak_nocontext(#name "() not available"); \
2335 return n; /* not reached */ \
2339 #if defined(HAS_HTOVS) && !defined(htovs)
2342 #if defined(HAS_HTOVL) && !defined(htovl)
2345 #if defined(HAS_VTOHS) && !defined(vtohs)
2348 #if defined(HAS_VTOHL) && !defined(vtohl)
2352 #ifdef PERL_NEED_MY_HTOLE16
2354 HTOLE(Perl_my_htole16,U16)
2356 NOT_AVAIL(Perl_my_htole16,U16)
2359 #ifdef PERL_NEED_MY_LETOH16
2361 LETOH(Perl_my_letoh16,U16)
2363 NOT_AVAIL(Perl_my_letoh16,U16)
2366 #ifdef PERL_NEED_MY_HTOBE16
2368 HTOBE(Perl_my_htobe16,U16)
2370 NOT_AVAIL(Perl_my_htobe16,U16)
2373 #ifdef PERL_NEED_MY_BETOH16
2375 BETOH(Perl_my_betoh16,U16)
2377 NOT_AVAIL(Perl_my_betoh16,U16)
2381 #ifdef PERL_NEED_MY_HTOLE32
2383 HTOLE(Perl_my_htole32,U32)
2385 NOT_AVAIL(Perl_my_htole32,U32)
2388 #ifdef PERL_NEED_MY_LETOH32
2390 LETOH(Perl_my_letoh32,U32)
2392 NOT_AVAIL(Perl_my_letoh32,U32)
2395 #ifdef PERL_NEED_MY_HTOBE32
2397 HTOBE(Perl_my_htobe32,U32)
2399 NOT_AVAIL(Perl_my_htobe32,U32)
2402 #ifdef PERL_NEED_MY_BETOH32
2404 BETOH(Perl_my_betoh32,U32)
2406 NOT_AVAIL(Perl_my_betoh32,U32)
2410 #ifdef PERL_NEED_MY_HTOLE64
2412 HTOLE(Perl_my_htole64,U64)
2414 NOT_AVAIL(Perl_my_htole64,U64)
2417 #ifdef PERL_NEED_MY_LETOH64
2419 LETOH(Perl_my_letoh64,U64)
2421 NOT_AVAIL(Perl_my_letoh64,U64)
2424 #ifdef PERL_NEED_MY_HTOBE64
2426 HTOBE(Perl_my_htobe64,U64)
2428 NOT_AVAIL(Perl_my_htobe64,U64)
2431 #ifdef PERL_NEED_MY_BETOH64
2433 BETOH(Perl_my_betoh64,U64)
2435 NOT_AVAIL(Perl_my_betoh64,U64)
2439 #ifdef PERL_NEED_MY_HTOLES
2440 HTOLE(Perl_my_htoles,short)
2442 #ifdef PERL_NEED_MY_LETOHS
2443 LETOH(Perl_my_letohs,short)
2445 #ifdef PERL_NEED_MY_HTOBES
2446 HTOBE(Perl_my_htobes,short)
2448 #ifdef PERL_NEED_MY_BETOHS
2449 BETOH(Perl_my_betohs,short)
2452 #ifdef PERL_NEED_MY_HTOLEI
2453 HTOLE(Perl_my_htolei,int)
2455 #ifdef PERL_NEED_MY_LETOHI
2456 LETOH(Perl_my_letohi,int)
2458 #ifdef PERL_NEED_MY_HTOBEI
2459 HTOBE(Perl_my_htobei,int)
2461 #ifdef PERL_NEED_MY_BETOHI
2462 BETOH(Perl_my_betohi,int)
2465 #ifdef PERL_NEED_MY_HTOLEL
2466 HTOLE(Perl_my_htolel,long)
2468 #ifdef PERL_NEED_MY_LETOHL
2469 LETOH(Perl_my_letohl,long)
2471 #ifdef PERL_NEED_MY_HTOBEL
2472 HTOBE(Perl_my_htobel,long)
2474 #ifdef PERL_NEED_MY_BETOHL
2475 BETOH(Perl_my_betohl,long)
2479 Perl_my_swabn(void *ptr, int n)
2481 char *s = (char *)ptr;
2482 char *e = s + (n-1);
2485 PERL_ARGS_ASSERT_MY_SWABN;
2487 for (n /= 2; n > 0; s++, e--, n--) {
2495 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2497 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2506 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2508 PERL_FLUSHALL_FOR_CHILD;
2509 This = (*mode == 'w');
2513 taint_proper("Insecure %s%s", "EXEC");
2515 if (PerlProc_pipe(p) < 0)
2517 /* Try for another pipe pair for error return */
2518 if (PerlProc_pipe(pp) >= 0)
2520 while ((pid = PerlProc_fork()) < 0) {
2521 if (errno != EAGAIN) {
2522 PerlLIO_close(p[This]);
2523 PerlLIO_close(p[that]);
2525 PerlLIO_close(pp[0]);
2526 PerlLIO_close(pp[1]);
2530 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2539 /* Close parent's end of error status pipe (if any) */
2541 PerlLIO_close(pp[0]);
2542 #if defined(HAS_FCNTL) && defined(F_SETFD)
2543 /* Close error pipe automatically if exec works */
2544 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2547 /* Now dup our end of _the_ pipe to right position */
2548 if (p[THIS] != (*mode == 'r')) {
2549 PerlLIO_dup2(p[THIS], *mode == 'r');
2550 PerlLIO_close(p[THIS]);
2551 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2552 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2555 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2556 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2557 /* No automatic close - do it by hand */
2564 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2570 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2576 do_execfree(); /* free any memory malloced by child on fork */
2578 PerlLIO_close(pp[1]);
2579 /* Keep the lower of the two fd numbers */
2580 if (p[that] < p[This]) {
2581 PerlLIO_dup2(p[This], p[that]);
2582 PerlLIO_close(p[This]);
2586 PerlLIO_close(p[that]); /* close child's end of pipe */
2588 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2589 SvUPGRADE(sv,SVt_IV);
2591 PL_forkprocess = pid;
2592 /* If we managed to get status pipe check for exec fail */
2593 if (did_pipes && pid > 0) {
2598 while (n < sizeof(int)) {
2599 n1 = PerlLIO_read(pp[0],
2600 (void*)(((char*)&errkid)+n),
2606 PerlLIO_close(pp[0]);
2608 if (n) { /* Error */
2610 PerlLIO_close(p[This]);
2611 if (n != sizeof(int))
2612 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2614 pid2 = wait4pid(pid, &status, 0);
2615 } while (pid2 == -1 && errno == EINTR);
2616 errno = errkid; /* Propagate errno from kid */
2621 PerlLIO_close(pp[0]);
2622 return PerlIO_fdopen(p[This], mode);
2624 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2625 return my_syspopen4(aTHX_ NULL, mode, n, args);
2627 Perl_croak(aTHX_ "List form of piped open not implemented");
2628 return (PerlIO *) NULL;
2633 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2634 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
2636 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2643 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2647 PERL_ARGS_ASSERT_MY_POPEN;
2649 PERL_FLUSHALL_FOR_CHILD;
2652 return my_syspopen(aTHX_ cmd,mode);
2655 This = (*mode == 'w');
2657 if (doexec && TAINTING_get) {
2659 taint_proper("Insecure %s%s", "EXEC");
2661 if (PerlProc_pipe(p) < 0)
2663 if (doexec && PerlProc_pipe(pp) >= 0)
2665 while ((pid = PerlProc_fork()) < 0) {
2666 if (errno != EAGAIN) {
2667 PerlLIO_close(p[This]);
2668 PerlLIO_close(p[that]);
2670 PerlLIO_close(pp[0]);
2671 PerlLIO_close(pp[1]);
2674 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2677 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2687 PerlLIO_close(pp[0]);
2688 #if defined(HAS_FCNTL) && defined(F_SETFD)
2689 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2692 if (p[THIS] != (*mode == 'r')) {
2693 PerlLIO_dup2(p[THIS], *mode == 'r');
2694 PerlLIO_close(p[THIS]);
2695 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2696 PerlLIO_close(p[THAT]);
2699 PerlLIO_close(p[THAT]);
2702 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2709 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2714 /* may or may not use the shell */
2715 do_exec3(cmd, pp[1], did_pipes);
2718 #endif /* defined OS2 */
2720 #ifdef PERLIO_USING_CRLF
2721 /* Since we circumvent IO layers when we manipulate low-level
2722 filedescriptors directly, need to manually switch to the
2723 default, binary, low-level mode; see PerlIOBuf_open(). */
2724 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2727 #ifdef PERL_USES_PL_PIDSTATUS
2728 hv_clear(PL_pidstatus); /* we have no children */
2734 do_execfree(); /* free any memory malloced by child on vfork */
2736 PerlLIO_close(pp[1]);
2737 if (p[that] < p[This]) {
2738 PerlLIO_dup2(p[This], p[that]);
2739 PerlLIO_close(p[This]);
2743 PerlLIO_close(p[that]);
2745 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2746 SvUPGRADE(sv,SVt_IV);
2748 PL_forkprocess = pid;
2749 if (did_pipes && pid > 0) {
2754 while (n < sizeof(int)) {
2755 n1 = PerlLIO_read(pp[0],
2756 (void*)(((char*)&errkid)+n),
2762 PerlLIO_close(pp[0]);
2764 if (n) { /* Error */
2766 PerlLIO_close(p[This]);
2767 if (n != sizeof(int))
2768 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2770 pid2 = wait4pid(pid, &status, 0);
2771 } while (pid2 == -1 && errno == EINTR);
2772 errno = errkid; /* Propagate errno from kid */
2777 PerlLIO_close(pp[0]);
2778 return PerlIO_fdopen(p[This], mode);
2784 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2786 PERL_ARGS_ASSERT_MY_POPEN;
2787 PERL_FLUSHALL_FOR_CHILD;
2788 /* Call system's popen() to get a FILE *, then import it.
2789 used 0 for 2nd parameter to PerlIO_importFILE;
2792 return PerlIO_importFILE(popen(cmd, mode), 0);
2796 FILE *djgpp_popen();
2798 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2800 PERL_FLUSHALL_FOR_CHILD;
2801 /* Call system's popen() to get a FILE *, then import it.
2802 used 0 for 2nd parameter to PerlIO_importFILE;
2805 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2808 #if defined(__LIBCATAMOUNT__)
2810 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2818 #endif /* !DOSISH */
2820 /* this is called in parent before the fork() */
2822 Perl_atfork_lock(void)
2825 #if defined(USE_ITHREADS)
2826 /* locks must be held in locking order (if any) */
2828 MUTEX_LOCK(&PL_malloc_mutex);
2834 /* this is called in both parent and child after the fork() */
2836 Perl_atfork_unlock(void)
2839 #if defined(USE_ITHREADS)
2840 /* locks must be released in same order as in atfork_lock() */
2842 MUTEX_UNLOCK(&PL_malloc_mutex);
2851 #if defined(HAS_FORK)
2853 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2858 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2859 * handlers elsewhere in the code */
2864 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2865 Perl_croak_nocontext("fork() not available");
2867 #endif /* HAS_FORK */
2872 Perl_dump_fds(pTHX_ const char *const s)
2877 PERL_ARGS_ASSERT_DUMP_FDS;
2879 PerlIO_printf(Perl_debug_log,"%s", s);
2880 for (fd = 0; fd < 32; fd++) {
2881 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2882 PerlIO_printf(Perl_debug_log," %d",fd);
2884 PerlIO_printf(Perl_debug_log,"\n");
2887 #endif /* DUMP_FDS */
2891 dup2(int oldfd, int newfd)
2893 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2896 PerlLIO_close(newfd);
2897 return fcntl(oldfd, F_DUPFD, newfd);
2899 #define DUP2_MAX_FDS 256
2900 int fdtmp[DUP2_MAX_FDS];
2906 PerlLIO_close(newfd);
2907 /* good enough for low fd's... */
2908 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2909 if (fdx >= DUP2_MAX_FDS) {
2917 PerlLIO_close(fdtmp[--fdx]);
2924 #ifdef HAS_SIGACTION
2927 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2930 struct sigaction act, oact;
2933 /* only "parent" interpreter can diddle signals */
2934 if (PL_curinterp != aTHX)
2935 return (Sighandler_t) SIG_ERR;
2938 act.sa_handler = (void(*)(int))handler;
2939 sigemptyset(&act.sa_mask);
2942 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2943 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2945 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2946 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2947 act.sa_flags |= SA_NOCLDWAIT;
2949 if (sigaction(signo, &act, &oact) == -1)
2950 return (Sighandler_t) SIG_ERR;
2952 return (Sighandler_t) oact.sa_handler;
2956 Perl_rsignal_state(pTHX_ int signo)
2958 struct sigaction oact;
2959 PERL_UNUSED_CONTEXT;
2961 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2962 return (Sighandler_t) SIG_ERR;
2964 return (Sighandler_t) oact.sa_handler;
2968 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2971 struct sigaction act;
2973 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2976 /* only "parent" interpreter can diddle signals */
2977 if (PL_curinterp != aTHX)
2981 act.sa_handler = (void(*)(int))handler;
2982 sigemptyset(&act.sa_mask);
2985 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2986 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2988 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2989 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2990 act.sa_flags |= SA_NOCLDWAIT;
2992 return sigaction(signo, &act, save);
2996 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3000 /* only "parent" interpreter can diddle signals */
3001 if (PL_curinterp != aTHX)
3005 return sigaction(signo, save, (struct sigaction *)NULL);
3008 #else /* !HAS_SIGACTION */
3011 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3013 #if defined(USE_ITHREADS) && !defined(WIN32)
3014 /* only "parent" interpreter can diddle signals */
3015 if (PL_curinterp != aTHX)
3016 return (Sighandler_t) SIG_ERR;
3019 return PerlProc_signal(signo, handler);
3030 Perl_rsignal_state(pTHX_ int signo)
3033 Sighandler_t oldsig;
3035 #if defined(USE_ITHREADS) && !defined(WIN32)
3036 /* only "parent" interpreter can diddle signals */
3037 if (PL_curinterp != aTHX)
3038 return (Sighandler_t) SIG_ERR;
3042 oldsig = PerlProc_signal(signo, sig_trap);
3043 PerlProc_signal(signo, oldsig);
3045 PerlProc_kill(PerlProc_getpid(), signo);
3050 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3052 #if defined(USE_ITHREADS) && !defined(WIN32)
3053 /* only "parent" interpreter can diddle signals */
3054 if (PL_curinterp != aTHX)
3057 *save = PerlProc_signal(signo, handler);
3058 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3062 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3064 #if defined(USE_ITHREADS) && !defined(WIN32)
3065 /* only "parent" interpreter can diddle signals */
3066 if (PL_curinterp != aTHX)
3069 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3072 #endif /* !HAS_SIGACTION */
3073 #endif /* !PERL_MICRO */
3075 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3076 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
3078 Perl_my_pclose(pTHX_ PerlIO *ptr)
3081 Sigsave_t hstat, istat, qstat;
3088 const int fd = PerlIO_fileno(ptr);
3091 /* Find out whether the refcount is low enough for us to wait for the
3092 child proc without blocking. */
3093 const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
3095 const bool should_wait = 1;
3098 svp = av_fetch(PL_fdpid,fd,TRUE);
3099 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3101 *svp = &PL_sv_undef;
3103 if (pid == -1) { /* Opened by popen. */
3104 return my_syspclose(ptr);
3107 close_failed = (PerlIO_close(ptr) == EOF);
3110 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3111 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3112 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3114 if (should_wait) do {
3115 pid2 = wait4pid(pid, &status, 0);
3116 } while (pid2 == -1 && errno == EINTR);
3118 rsignal_restore(SIGHUP, &hstat);
3119 rsignal_restore(SIGINT, &istat);
3120 rsignal_restore(SIGQUIT, &qstat);
3128 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3133 #if defined(__LIBCATAMOUNT__)
3135 Perl_my_pclose(pTHX_ PerlIO *ptr)
3140 #endif /* !DOSISH */
3142 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3144 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3148 PERL_ARGS_ASSERT_WAIT4PID;
3151 #ifdef PERL_USES_PL_PIDSTATUS
3154 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3155 pid, rather than a string form. */
3156 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3157 if (svp && *svp != &PL_sv_undef) {
3158 *statusp = SvIVX(*svp);
3159 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3167 hv_iterinit(PL_pidstatus);
3168 if ((entry = hv_iternext(PL_pidstatus))) {
3169 SV * const sv = hv_iterval(PL_pidstatus,entry);
3171 const char * const spid = hv_iterkey(entry,&len);
3173 assert (len == sizeof(Pid_t));
3174 memcpy((char *)&pid, spid, len);
3175 *statusp = SvIVX(sv);
3176 /* The hash iterator is currently on this entry, so simply
3177 calling hv_delete would trigger the lazy delete, which on
3178 aggregate does more work, beacuse next call to hv_iterinit()
3179 would spot the flag, and have to call the delete routine,
3180 while in the meantime any new entries can't re-use that
3182 hv_iterinit(PL_pidstatus);
3183 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3190 # ifdef HAS_WAITPID_RUNTIME
3191 if (!HAS_WAITPID_RUNTIME)
3194 result = PerlProc_waitpid(pid,statusp,flags);
3197 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3198 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3201 #ifdef PERL_USES_PL_PIDSTATUS
3202 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3207 Perl_croak(aTHX_ "Can't do waitpid with flags");
3209 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3210 pidgone(result,*statusp);
3216 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3219 if (result < 0 && errno == EINTR) {
3221 errno = EINTR; /* reset in case a signal handler changed $! */
3225 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3227 #ifdef PERL_USES_PL_PIDSTATUS
3229 S_pidgone(pTHX_ Pid_t pid, int status)
3233 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3234 SvUPGRADE(sv,SVt_IV);
3235 SvIV_set(sv, status);
3240 #if defined(OS2) || defined(EPOC)
3243 int /* Cannot prototype with I32
3245 my_syspclose(PerlIO *ptr)
3248 Perl_my_pclose(pTHX_ PerlIO *ptr)
3251 /* Needs work for PerlIO ! */
3252 FILE * const f = PerlIO_findFILE(ptr);
3253 const I32 result = pclose(f);
3254 PerlIO_releaseFILE(ptr,f);
3262 Perl_my_pclose(pTHX_ PerlIO *ptr)
3264 /* Needs work for PerlIO ! */
3265 FILE * const f = PerlIO_findFILE(ptr);
3266 I32 result = djgpp_pclose(f);
3267 result = (result << 8) & 0xff00;
3268 PerlIO_releaseFILE(ptr,f);
3273 #define PERL_REPEATCPY_LINEAR 4
3275 Perl_repeatcpy(register char *to, register const char *from, I32 len, register IV count)
3277 PERL_ARGS_ASSERT_REPEATCPY;
3282 croak_memory_wrap();
3285 memset(to, *from, count);
3288 IV items, linear, half;
3290 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3291 for (items = 0; items < linear; ++items) {
3292 const char *q = from;
3294 for (todo = len; todo > 0; todo--)
3299 while (items <= half) {
3300 IV size = items * len;
3301 memcpy(p, to, size);
3307 memcpy(p, to, (count - items) * len);
3313 Perl_same_dirent(pTHX_ const char *a, const char *b)
3315 char *fa = strrchr(a,'/');
3316 char *fb = strrchr(b,'/');
3319 SV * const tmpsv = sv_newmortal();
3321 PERL_ARGS_ASSERT_SAME_DIRENT;
3334 sv_setpvs(tmpsv, ".");
3336 sv_setpvn(tmpsv, a, fa - a);
3337 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3340 sv_setpvs(tmpsv, ".");
3342 sv_setpvn(tmpsv, b, fb - b);
3343 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3345 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3346 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3348 #endif /* !HAS_RENAME */
3351 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3352 const char *const *const search_ext, I32 flags)
3355 const char *xfound = NULL;
3356 char *xfailed = NULL;
3357 char tmpbuf[MAXPATHLEN];
3362 #if defined(DOSISH) && !defined(OS2)
3363 # define SEARCH_EXTS ".bat", ".cmd", NULL
3364 # define MAX_EXT_LEN 4
3367 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3368 # define MAX_EXT_LEN 4
3371 # define SEARCH_EXTS ".pl", ".com", NULL
3372 # define MAX_EXT_LEN 4
3374 /* additional extensions to try in each dir if scriptname not found */
3376 static const char *const exts[] = { SEARCH_EXTS };
3377 const char *const *const ext = search_ext ? search_ext : exts;
3378 int extidx = 0, i = 0;
3379 const char *curext = NULL;
3381 PERL_UNUSED_ARG(search_ext);
3382 # define MAX_EXT_LEN 0
3385 PERL_ARGS_ASSERT_FIND_SCRIPT;
3388 * If dosearch is true and if scriptname does not contain path
3389 * delimiters, search the PATH for scriptname.
3391 * If SEARCH_EXTS is also defined, will look for each
3392 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3393 * while searching the PATH.
3395 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3396 * proceeds as follows:
3397 * If DOSISH or VMSISH:
3398 * + look for ./scriptname{,.foo,.bar}
3399 * + search the PATH for scriptname{,.foo,.bar}
3402 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3403 * this will not look in '.' if it's not in the PATH)
3408 # ifdef ALWAYS_DEFTYPES
3409 len = strlen(scriptname);
3410 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3411 int idx = 0, deftypes = 1;
3414 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3417 int idx = 0, deftypes = 1;
3420 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3422 /* The first time through, just add SEARCH_EXTS to whatever we
3423 * already have, so we can check for default file types. */
3425 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3431 if ((strlen(tmpbuf) + strlen(scriptname)
3432 + MAX_EXT_LEN) >= sizeof tmpbuf)
3433 continue; /* don't search dir with too-long name */
3434 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3438 if (strEQ(scriptname, "-"))
3440 if (dosearch) { /* Look in '.' first. */
3441 const char *cur = scriptname;
3443 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3445 if (strEQ(ext[i++],curext)) {
3446 extidx = -1; /* already has an ext */
3451 DEBUG_p(PerlIO_printf(Perl_debug_log,
3452 "Looking for %s\n",cur));
3453 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3454 && !S_ISDIR(PL_statbuf.st_mode)) {
3462 if (cur == scriptname) {
3463 len = strlen(scriptname);
3464 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3466 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3469 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3470 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3475 if (dosearch && !strchr(scriptname, '/')
3477 && !strchr(scriptname, '\\')
3479 && (s = PerlEnv_getenv("PATH")))
3483 bufend = s + strlen(s);
3484 while (s < bufend) {
3487 && *s != ';'; len++, s++) {
3488 if (len < sizeof tmpbuf)
3491 if (len < sizeof tmpbuf)
3494 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3500 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3501 continue; /* don't search dir with too-long name */
3504 && tmpbuf[len - 1] != '/'
3505 && tmpbuf[len - 1] != '\\'
3508 tmpbuf[len++] = '/';
3509 if (len == 2 && tmpbuf[0] == '.')
3511 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3515 len = strlen(tmpbuf);
3516 if (extidx > 0) /* reset after previous loop */
3520 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3521 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3522 if (S_ISDIR(PL_statbuf.st_mode)) {
3526 } while ( retval < 0 /* not there */
3527 && extidx>=0 && ext[extidx] /* try an extension? */
3528 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3533 if (S_ISREG(PL_statbuf.st_mode)
3534 && cando(S_IRUSR,TRUE,&PL_statbuf)
3535 #if !defined(DOSISH)
3536 && cando(S_IXUSR,TRUE,&PL_statbuf)
3540 xfound = tmpbuf; /* bingo! */
3544 xfailed = savepv(tmpbuf);
3547 if (!xfound && !seen_dot && !xfailed &&
3548 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3549 || S_ISDIR(PL_statbuf.st_mode)))
3551 seen_dot = 1; /* Disable message. */
3553 if (flags & 1) { /* do or die? */
3554 /* diag_listed_as: Can't execute %s */
3555 Perl_croak(aTHX_ "Can't %s %s%s%s",
3556 (xfailed ? "execute" : "find"),
3557 (xfailed ? xfailed : scriptname),
3558 (xfailed ? "" : " on PATH"),
3559 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3564 scriptname = xfound;
3566 return (scriptname ? savepv(scriptname) : NULL);
3569 #ifndef PERL_GET_CONTEXT_DEFINED
3572 Perl_get_context(void)
3575 #if defined(USE_ITHREADS)
3576 # ifdef OLD_PTHREADS_API
3578 int error = pthread_getspecific(PL_thr_key, &t)
3580 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3583 # ifdef I_MACH_CTHREADS
3584 return (void*)cthread_data(cthread_self());
3586 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3595 Perl_set_context(void *t)
3598 PERL_ARGS_ASSERT_SET_CONTEXT;
3599 #if defined(USE_ITHREADS)
3600 # ifdef I_MACH_CTHREADS
3601 cthread_set_data(cthread_self(), t);
3604 const int error = pthread_setspecific(PL_thr_key, t);
3606 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3614 #endif /* !PERL_GET_CONTEXT_DEFINED */
3616 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3625 Perl_get_op_names(pTHX)
3627 PERL_UNUSED_CONTEXT;
3628 return (char **)PL_op_name;
3632 Perl_get_op_descs(pTHX)
3634 PERL_UNUSED_CONTEXT;
3635 return (char **)PL_op_desc;
3639 Perl_get_no_modify(pTHX)
3641 PERL_UNUSED_CONTEXT;
3642 return PL_no_modify;
3646 Perl_get_opargs(pTHX)
3648 PERL_UNUSED_CONTEXT;
3649 return (U32 *)PL_opargs;
3653 Perl_get_ppaddr(pTHX)
3656 PERL_UNUSED_CONTEXT;
3657 return (PPADDR_t*)PL_ppaddr;
3660 #ifndef HAS_GETENV_LEN
3662 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3664 char * const env_trans = PerlEnv_getenv(env_elem);
3665 PERL_UNUSED_CONTEXT;
3666 PERL_ARGS_ASSERT_GETENV_LEN;
3668 *len = strlen(env_trans);
3675 Perl_get_vtbl(pTHX_ int vtbl_id)
3677 PERL_UNUSED_CONTEXT;
3679 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3680 ? NULL : PL_magic_vtables + vtbl_id;
3684 Perl_my_fflush_all(pTHX)
3686 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3687 return PerlIO_flush(NULL);
3689 # if defined(HAS__FWALK)
3690 extern int fflush(FILE *);
3691 /* undocumented, unprototyped, but very useful BSDism */
3692 extern void _fwalk(int (*)(FILE *));
3696 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3698 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3699 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3701 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3702 open_max = sysconf(_SC_OPEN_MAX);
3705 open_max = FOPEN_MAX;
3708 open_max = OPEN_MAX;
3719 for (i = 0; i < open_max; i++)
3720 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3721 STDIO_STREAM_ARRAY[i]._file < open_max &&
3722 STDIO_STREAM_ARRAY[i]._flag)
3723 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3727 SETERRNO(EBADF,RMS_IFI);
3734 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3736 if (ckWARN(WARN_IO)) {
3738 = gv && (isGV_with_GP(gv))
3741 const char * const direction = have == '>' ? "out" : "in";
3743 if (name && HEK_LEN(name))
3744 Perl_warner(aTHX_ packWARN(WARN_IO),
3745 "Filehandle %"HEKf" opened only for %sput",
3748 Perl_warner(aTHX_ packWARN(WARN_IO),
3749 "Filehandle opened only for %sput", direction);
3754 Perl_report_evil_fh(pTHX_ const GV *gv)
3756 const IO *io = gv ? GvIO(gv) : NULL;
3757 const PERL_BITFIELD16 op = PL_op->op_type;
3761 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3763 warn_type = WARN_CLOSED;
3767 warn_type = WARN_UNOPENED;
3770 if (ckWARN(warn_type)) {
3772 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3773 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3774 const char * const pars =
3775 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3776 const char * const func =
3778 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3779 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3781 const char * const type =
3783 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3784 ? "socket" : "filehandle");
3785 const bool have_name = name && SvCUR(name);
3786 Perl_warner(aTHX_ packWARN(warn_type),
3787 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3788 have_name ? " " : "",
3789 SVfARG(have_name ? name : &PL_sv_no));
3790 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3792 aTHX_ packWARN(warn_type),
3793 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3794 func, pars, have_name ? " " : "",
3795 SVfARG(have_name ? name : &PL_sv_no)
3800 /* To workaround core dumps from the uninitialised tm_zone we get the
3801 * system to give us a reasonable struct to copy. This fix means that
3802 * strftime uses the tm_zone and tm_gmtoff values returned by
3803 * localtime(time()). That should give the desired result most of the
3804 * time. But probably not always!
3806 * This does not address tzname aspects of NETaa14816.
3811 # ifndef STRUCT_TM_HASZONE
3812 # define STRUCT_TM_HASZONE
3816 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3817 # ifndef HAS_TM_TM_ZONE
3818 # define HAS_TM_TM_ZONE
3823 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3825 #ifdef HAS_TM_TM_ZONE
3827 const struct tm* my_tm;
3828 PERL_ARGS_ASSERT_INIT_TM;
3830 my_tm = localtime(&now);
3832 Copy(my_tm, ptm, 1, struct tm);
3834 PERL_ARGS_ASSERT_INIT_TM;
3835 PERL_UNUSED_ARG(ptm);
3840 * mini_mktime - normalise struct tm values without the localtime()
3841 * semantics (and overhead) of mktime().
3844 Perl_mini_mktime(pTHX_ struct tm *ptm)
3848 int month, mday, year, jday;
3849 int odd_cent, odd_year;
3850 PERL_UNUSED_CONTEXT;
3852 PERL_ARGS_ASSERT_MINI_MKTIME;
3854 #define DAYS_PER_YEAR 365
3855 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3856 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3857 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3858 #define SECS_PER_HOUR (60*60)
3859 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3860 /* parentheses deliberately absent on these two, otherwise they don't work */
3861 #define MONTH_TO_DAYS 153/5
3862 #define DAYS_TO_MONTH 5/153
3863 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3864 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3865 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3866 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3869 * Year/day algorithm notes:
3871 * With a suitable offset for numeric value of the month, one can find
3872 * an offset into the year by considering months to have 30.6 (153/5) days,
3873 * using integer arithmetic (i.e., with truncation). To avoid too much
3874 * messing about with leap days, we consider January and February to be
3875 * the 13th and 14th month of the previous year. After that transformation,
3876 * we need the month index we use to be high by 1 from 'normal human' usage,
3877 * so the month index values we use run from 4 through 15.
3879 * Given that, and the rules for the Gregorian calendar (leap years are those
3880 * divisible by 4 unless also divisible by 100, when they must be divisible
3881 * by 400 instead), we can simply calculate the number of days since some
3882 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3883 * the days we derive from our month index, and adding in the day of the
3884 * month. The value used here is not adjusted for the actual origin which
3885 * it normally would use (1 January A.D. 1), since we're not exposing it.
3886 * We're only building the value so we can turn around and get the
3887 * normalised values for the year, month, day-of-month, and day-of-year.
3889 * For going backward, we need to bias the value we're using so that we find
3890 * the right year value. (Basically, we don't want the contribution of
3891 * March 1st to the number to apply while deriving the year). Having done
3892 * that, we 'count up' the contribution to the year number by accounting for
3893 * full quadracenturies (400-year periods) with their extra leap days, plus
3894 * the contribution from full centuries (to avoid counting in the lost leap
3895 * days), plus the contribution from full quad-years (to count in the normal
3896 * leap days), plus the leftover contribution from any non-leap years.
3897 * At this point, if we were working with an actual leap day, we'll have 0
3898 * days left over. This is also true for March 1st, however. So, we have
3899 * to special-case that result, and (earlier) keep track of the 'odd'
3900 * century and year contributions. If we got 4 extra centuries in a qcent,
3901 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3902 * Otherwise, we add back in the earlier bias we removed (the 123 from
3903 * figuring in March 1st), find the month index (integer division by 30.6),
3904 * and the remainder is the day-of-month. We then have to convert back to
3905 * 'real' months (including fixing January and February from being 14/15 in
3906 * the previous year to being in the proper year). After that, to get
3907 * tm_yday, we work with the normalised year and get a new yearday value for
3908 * January 1st, which we subtract from the yearday value we had earlier,
3909 * representing the date we've re-built. This is done from January 1
3910 * because tm_yday is 0-origin.
3912 * Since POSIX time routines are only guaranteed to work for times since the
3913 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3914 * applies Gregorian calendar rules even to dates before the 16th century
3915 * doesn't bother me. Besides, you'd need cultural context for a given
3916 * date to know whether it was Julian or Gregorian calendar, and that's
3917 * outside the scope for this routine. Since we convert back based on the
3918 * same rules we used to build the yearday, you'll only get strange results
3919 * for input which needed normalising, or for the 'odd' century years which
3920 * were leap years in the Julian calendar but not in the Gregorian one.
3921 * I can live with that.
3923 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3924 * that's still outside the scope for POSIX time manipulation, so I don't
3928 year = 1900 + ptm->tm_year;
3929 month = ptm->tm_mon;
3930 mday = ptm->tm_mday;
3936 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3937 yearday += month*MONTH_TO_DAYS + mday + jday;
3939 * Note that we don't know when leap-seconds were or will be,
3940 * so we have to trust the user if we get something which looks
3941 * like a sensible leap-second. Wild values for seconds will
3942 * be rationalised, however.
3944 if ((unsigned) ptm->tm_sec <= 60) {
3951 secs += 60 * ptm->tm_min;
3952 secs += SECS_PER_HOUR * ptm->tm_hour;
3954 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3955 /* got negative remainder, but need positive time */
3956 /* back off an extra day to compensate */
3957 yearday += (secs/SECS_PER_DAY)-1;
3958 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3961 yearday += (secs/SECS_PER_DAY);
3962 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3965 else if (secs >= SECS_PER_DAY) {
3966 yearday += (secs/SECS_PER_DAY);
3967 secs %= SECS_PER_DAY;
3969 ptm->tm_hour = secs/SECS_PER_HOUR;
3970 secs %= SECS_PER_HOUR;
3971 ptm->tm_min = secs/60;
3973 ptm->tm_sec += secs;
3974 /* done with time of day effects */
3976 * The algorithm for yearday has (so far) left it high by 428.
3977 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3978 * bias it by 123 while trying to figure out what year it
3979 * really represents. Even with this tweak, the reverse
3980 * translation fails for years before A.D. 0001.
3981 * It would still fail for Feb 29, but we catch that one below.
3983 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3984 yearday -= YEAR_ADJUST;
3985 year = (yearday / DAYS_PER_QCENT) * 400;
3986 yearday %= DAYS_PER_QCENT;
3987 odd_cent = yearday / DAYS_PER_CENT;
3988 year += odd_cent * 100;
3989 yearday %= DAYS_PER_CENT;
3990 year += (yearday / DAYS_PER_QYEAR) * 4;
3991 yearday %= DAYS_PER_QYEAR;
3992 odd_year = yearday / DAYS_PER_YEAR;
3994 yearday %= DAYS_PER_YEAR;
3995 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4000 yearday += YEAR_ADJUST; /* recover March 1st crock */
4001 month = yearday*DAYS_TO_MONTH;
4002 yearday -= month*MONTH_TO_DAYS;
4003 /* recover other leap-year adjustment */
4012 ptm->tm_year = year - 1900;
4014 ptm->tm_mday = yearday;
4015 ptm->tm_mon = month;
4019 ptm->tm_mon = month - 1;
4021 /* re-build yearday based on Jan 1 to get tm_yday */
4023 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4024 yearday += 14*MONTH_TO_DAYS + 1;
4025 ptm->tm_yday = jday - yearday;
4026 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4030 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)
4038 PERL_ARGS_ASSERT_MY_STRFTIME;
4040 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4043 mytm.tm_hour = hour;
4044 mytm.tm_mday = mday;
4046 mytm.tm_year = year;
4047 mytm.tm_wday = wday;
4048 mytm.tm_yday = yday;
4049 mytm.tm_isdst = isdst;
4051 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4052 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4057 #ifdef HAS_TM_TM_GMTOFF
4058 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4060 #ifdef HAS_TM_TM_ZONE
4061 mytm.tm_zone = mytm2.tm_zone;
4066 Newx(buf, buflen, char);
4067 len = strftime(buf, buflen, fmt, &mytm);
4069 ** The following is needed to handle to the situation where
4070 ** tmpbuf overflows. Basically we want to allocate a buffer
4071 ** and try repeatedly. The reason why it is so complicated
4072 ** is that getting a return value of 0 from strftime can indicate
4073 ** one of the following:
4074 ** 1. buffer overflowed,
4075 ** 2. illegal conversion specifier, or
4076 ** 3. the format string specifies nothing to be returned(not
4077 ** an error). This could be because format is an empty string
4078 ** or it specifies %p that yields an empty string in some locale.
4079 ** If there is a better way to make it portable, go ahead by
4082 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4085 /* Possibly buf overflowed - try again with a bigger buf */
4086 const int fmtlen = strlen(fmt);
4087 int bufsize = fmtlen + buflen;
4089 Renew(buf, bufsize, char);
4091 buflen = strftime(buf, bufsize, fmt, &mytm);
4092 if (buflen > 0 && buflen < bufsize)
4094 /* heuristic to prevent out-of-memory errors */
4095 if (bufsize > 100*fmtlen) {
4101 Renew(buf, bufsize, char);
4106 Perl_croak(aTHX_ "panic: no strftime");
4112 #define SV_CWD_RETURN_UNDEF \
4113 sv_setsv(sv, &PL_sv_undef); \
4116 #define SV_CWD_ISDOT(dp) \
4117 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4118 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4121 =head1 Miscellaneous Functions
4123 =for apidoc getcwd_sv
4125 Fill the sv with current working directory
4130 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4131 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4132 * getcwd(3) if available
4133 * Comments from the orignal:
4134 * This is a faster version of getcwd. It's also more dangerous
4135 * because you might chdir out of a directory that you can't chdir
4139 Perl_getcwd_sv(pTHX_ register SV *sv)
4143 #ifndef INCOMPLETE_TAINTS
4147 PERL_ARGS_ASSERT_GETCWD_SV;
4151 char buf[MAXPATHLEN];
4153 /* Some getcwd()s automatically allocate a buffer of the given
4154 * size from the heap if they are given a NULL buffer pointer.
4155 * The problem is that this behaviour is not portable. */
4156 if (getcwd(buf, sizeof(buf) - 1)) {
4161 sv_setsv(sv, &PL_sv_undef);
4169 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4173 SvUPGRADE(sv, SVt_PV);
4175 if (PerlLIO_lstat(".", &statbuf) < 0) {
4176 SV_CWD_RETURN_UNDEF;
4179 orig_cdev = statbuf.st_dev;
4180 orig_cino = statbuf.st_ino;
4190 if (PerlDir_chdir("..") < 0) {
4191 SV_CWD_RETURN_UNDEF;
4193 if (PerlLIO_stat(".", &statbuf) < 0) {
4194 SV_CWD_RETURN_UNDEF;
4197 cdev = statbuf.st_dev;
4198 cino = statbuf.st_ino;
4200 if (odev == cdev && oino == cino) {
4203 if (!(dir = PerlDir_open("."))) {
4204 SV_CWD_RETURN_UNDEF;
4207 while ((dp = PerlDir_read(dir)) != NULL) {
4209 namelen = dp->d_namlen;
4211 namelen = strlen(dp->d_name);
4214 if (SV_CWD_ISDOT(dp)) {
4218 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4219 SV_CWD_RETURN_UNDEF;
4222 tdev = statbuf.st_dev;
4223 tino = statbuf.st_ino;
4224 if (tino == oino && tdev == odev) {
4230 SV_CWD_RETURN_UNDEF;
4233 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4234 SV_CWD_RETURN_UNDEF;
4237 SvGROW(sv, pathlen + namelen + 1);
4241 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4244 /* prepend current directory to the front */
4246 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4247 pathlen += (namelen + 1);
4249 #ifdef VOID_CLOSEDIR
4252 if (PerlDir_close(dir) < 0) {
4253 SV_CWD_RETURN_UNDEF;
4259 SvCUR_set(sv, pathlen);
4263 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4264 SV_CWD_RETURN_UNDEF;
4267 if (PerlLIO_stat(".", &statbuf) < 0) {
4268 SV_CWD_RETURN_UNDEF;
4271 cdev = statbuf.st_dev;
4272 cino = statbuf.st_ino;
4274 if (cdev != orig_cdev || cino != orig_cino) {
4275 Perl_croak(aTHX_ "Unstable directory path, "
4276 "current directory changed unexpectedly");
4287 #define VERSION_MAX 0x7FFFFFFF
4290 =for apidoc prescan_version
4292 Validate that a given string can be parsed as a version object, but doesn't
4293 actually perform the parsing. Can use either strict or lax validation rules.
4294 Can optionally set a number of hint variables to save the parsing code
4295 some time when tokenizing.
4300 Perl_prescan_version(pTHX_ const char *s, bool strict,
4301 const char **errstr,
4302 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4303 bool qv = (sqv ? *sqv : FALSE);
4305 int saw_decimal = 0;
4309 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4311 if (qv && isDIGIT(*d))
4312 goto dotted_decimal_version;
4314 if (*d == 'v') { /* explicit v-string */
4319 else { /* degenerate v-string */
4320 /* requires v1.2.3 */
4321 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4324 dotted_decimal_version:
4325 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4326 /* no leading zeros allowed */
4327 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4330 while (isDIGIT(*d)) /* integer part */
4336 d++; /* decimal point */
4341 /* require v1.2.3 */
4342 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4345 goto version_prescan_finish;
4352 while (isDIGIT(*d)) { /* just keep reading */
4354 while (isDIGIT(*d)) {
4356 /* maximum 3 digits between decimal */
4357 if (strict && j > 3) {
4358 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4363 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4366 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4371 else if (*d == '.') {
4373 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4378 else if (!isDIGIT(*d)) {
4384 if (strict && i < 2) {
4385 /* requires v1.2.3 */
4386 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4389 } /* end if dotted-decimal */
4391 { /* decimal versions */
4392 int j = 0; /* may need this later */
4393 /* special strict case for leading '.' or '0' */
4396 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4398 if (*d == '0' && isDIGIT(d[1])) {
4399 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4403 /* and we never support negative versions */
4405 BADVERSION(s,errstr,"Invalid version format (negative version number)");
4408 /* consume all of the integer part */
4412 /* look for a fractional part */
4414 /* we found it, so consume it */
4418 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4421 BADVERSION(s,errstr,"Invalid version format (version required)");
4423 /* found just an integer */
4424 goto version_prescan_finish;
4426 else if ( d == s ) {
4427 /* didn't find either integer or period */
4428 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4430 else if (*d == '_') {
4431 /* underscore can't come after integer part */
4433 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4435 else if (isDIGIT(d[1])) {
4436 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4439 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4443 /* anything else after integer part is just invalid data */
4444 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4447 /* scan the fractional part after the decimal point*/
4449 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4450 /* strict or lax-but-not-the-end */
4451 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4454 while (isDIGIT(*d)) {
4456 if (*d == '.' && isDIGIT(d[-1])) {
4458 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4461 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4463 d = (char *)s; /* start all over again */
4465 goto dotted_decimal_version;
4469 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4472 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4474 if ( ! isDIGIT(d[1]) ) {
4475 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4484 version_prescan_finish:
4488 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4489 /* trailing non-numeric data */
4490 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4498 *ssaw_decimal = saw_decimal;
4505 =for apidoc scan_version
4507 Returns a pointer to the next character after the parsed
4508 version string, as well as upgrading the passed in SV to
4511 Function must be called with an already existing SV like
4514 s = scan_version(s, SV *sv, bool qv);
4516 Performs some preprocessing to the string to ensure that
4517 it has the correct characteristics of a version. Flags the
4518 object if it contains an underscore (which denotes this
4519 is an alpha version). The boolean qv denotes that the version
4520 should be interpreted as if it had multiple decimals, even if
4527 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4532 const char *errstr = NULL;
4533 int saw_decimal = 0;
4537 AV * const av = newAV();
4538 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4540 PERL_ARGS_ASSERT_SCAN_VERSION;
4542 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4544 #ifndef NODEFAULT_SHAREKEYS
4545 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4548 while (isSPACE(*s)) /* leading whitespace is OK */
4551 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4553 /* "undef" is a special case and not an error */
4554 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4555 Perl_croak(aTHX_ "%s", errstr);
4565 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4567 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4568 if ( !qv && width < 3 )
4569 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4571 while (isDIGIT(*pos))
4573 if (!isALPHA(*pos)) {
4579 /* this is atoi() that delimits on underscores */
4580 const char *end = pos;
4584 /* the following if() will only be true after the decimal
4585 * point of a version originally created with a bare
4586 * floating point number, i.e. not quoted in any way
4588 if ( !qv && s > start && saw_decimal == 1 ) {
4592 rev += (*s - '0') * mult;
4594 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4595 || (PERL_ABS(rev) > VERSION_MAX )) {
4596 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4597 "Integer overflow in version %d",VERSION_MAX);
4608 while (--end >= s) {
4610 rev += (*end - '0') * mult;
4612 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4613 || (PERL_ABS(rev) > VERSION_MAX )) {
4614 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4615 "Integer overflow in version");
4624 /* Append revision */
4625 av_push(av, newSViv(rev));
4630 else if ( *pos == '.' )
4632 else if ( *pos == '_' && isDIGIT(pos[1]) )
4634 else if ( *pos == ',' && isDIGIT(pos[1]) )
4636 else if ( isDIGIT(*pos) )
4643 while ( isDIGIT(*pos) )
4648 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4656 if ( qv ) { /* quoted versions always get at least three terms*/
4657 I32 len = av_len(av);
4658 /* This for loop appears to trigger a compiler bug on OS X, as it
4659 loops infinitely. Yes, len is negative. No, it makes no sense.
4660 Compiler in question is:
4661 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4662 for ( len = 2 - len; len > 0; len-- )
4663 av_push(MUTABLE_AV(sv), newSViv(0));
4667 av_push(av, newSViv(0));
4670 /* need to save off the current version string for later */
4672 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4673 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4674 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4676 else if ( s > start ) {
4677 SV * orig = newSVpvn(start,s-start);
4678 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4679 /* need to insert a v to be consistent */
4680 sv_insert(orig, 0, 0, "v", 1);
4682 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4685 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4686 av_push(av, newSViv(0));
4689 /* And finally, store the AV in the hash */
4690 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4692 /* fix RT#19517 - special case 'undef' as string */
4693 if ( *s == 'u' && strEQ(s,"undef") ) {
4701 =for apidoc new_version
4703 Returns a new version object based on the passed in SV:
4705 SV *sv = new_version(SV *ver);
4707 Does not alter the passed in ver SV. See "upg_version" if you
4708 want to upgrade the SV.
4714 Perl_new_version(pTHX_ SV *ver)
4717 SV * const rv = newSV(0);
4718 PERL_ARGS_ASSERT_NEW_VERSION;
4719 if ( sv_isobject(ver) && sv_derived_from(ver, "version") )
4720 /* can just copy directly */
4723 AV * const av = newAV();
4725 /* This will get reblessed later if a derived class*/
4726 SV * const hv = newSVrv(rv, "version");
4727 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4728 #ifndef NODEFAULT_SHAREKEYS
4729 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4735 /* Begin copying all of the elements */
4736 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4737 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4739 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4740 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4742 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4744 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4745 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4748 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4750 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4751 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4754 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4755 /* This will get reblessed later if a derived class*/
4756 for ( key = 0; key <= av_len(sav); key++ )
4758 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4759 av_push(av, newSViv(rev));
4762 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4767 const MAGIC* const mg = SvVSTRING_mg(ver);
4768 if ( mg ) { /* already a v-string */
4769 const STRLEN len = mg->mg_len;
4770 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4771 sv_setpvn(rv,version,len);
4772 /* this is for consistency with the pure Perl class */
4773 if ( isDIGIT(*version) )
4774 sv_insert(rv, 0, 0, "v", 1);
4779 sv_setsv(rv,ver); /* make a duplicate */
4784 return upg_version(rv, FALSE);
4788 =for apidoc upg_version
4790 In-place upgrade of the supplied SV to a version object.
4792 SV *sv = upg_version(SV *sv, bool qv);
4794 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4795 to force this SV to be interpreted as an "extended" version.
4801 Perl_upg_version(pTHX_ SV *ver, bool qv)
4803 const char *version, *s;
4808 PERL_ARGS_ASSERT_UPG_VERSION;
4810 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4814 /* may get too much accuracy */
4816 SV *sv = SvNVX(ver) > 10e50 ? newSV(64) : 0;
4818 #ifdef USE_LOCALE_NUMERIC
4819 char *loc = savepv(setlocale(LC_NUMERIC, NULL));
4820 setlocale(LC_NUMERIC, "C");
4823 Perl_sv_setpvf(aTHX_ sv, "%.9"NVff, SvNVX(ver));
4824 buf = SvPV(sv, len);
4827 len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4830 #ifdef USE_LOCALE_NUMERIC
4831 setlocale(LC_NUMERIC, loc);
4834 while (buf[len-1] == '0' && len > 0) len--;
4835 if ( buf[len-1] == '.' ) len--; /* eat the trailing decimal */
4836 version = savepvn(buf, len);
4840 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4841 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4845 else /* must be a string or something like a string */
4848 version = savepv(SvPV(ver,len));
4850 # if PERL_VERSION > 5
4851 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4852 if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
4853 /* may be a v-string */
4854 char *testv = (char *)version;
4856 for (tlen=0; tlen < len; tlen++, testv++) {
4857 /* if one of the characters is non-text assume v-string */
4858 if (testv[0] < ' ') {
4859 SV * const nsv = sv_newmortal();
4862 int saw_decimal = 0;
4863 sv_setpvf(nsv,"v%vd",ver);
4864 pos = nver = savepv(SvPV_nolen(nsv));
4866 /* scan the resulting formatted string */
4867 pos++; /* skip the leading 'v' */
4868 while ( *pos == '.' || isDIGIT(*pos) ) {
4874 /* is definitely a v-string */
4875 if ( saw_decimal >= 2 ) {
4887 s = scan_version(version, ver, qv);
4889 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4890 "Version string '%s' contains invalid data; "
4891 "ignoring: '%s'", version, s);
4899 Validates that the SV contains valid internal structure for a version object.
4900 It may be passed either the version object (RV) or the hash itself (HV). If
4901 the structure is valid, it returns the HV. If the structure is invalid,
4904 SV *hv = vverify(sv);
4906 Note that it only confirms the bare minimum structure (so as not to get
4907 confused by derived classes which may contain additional hash entries):
4911 =item * The SV is an HV or a reference to an HV
4913 =item * The hash contains a "version" key
4915 =item * The "version" key has a reference to an AV as its value
4923 Perl_vverify(pTHX_ SV *vs)
4927 PERL_ARGS_ASSERT_VVERIFY;
4932 /* see if the appropriate elements exist */
4933 if ( SvTYPE(vs) == SVt_PVHV
4934 && hv_exists(MUTABLE_HV(vs), "version", 7)
4935 && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
4936 && SvTYPE(sv) == SVt_PVAV )
4945 Accepts a version object and returns the normalized floating
4946 point representation. Call like:
4950 NOTE: you can pass either the object directly or the SV
4951 contained within the RV.
4953 The SV returned has a refcount of 1.
4959 Perl_vnumify(pTHX_ SV *vs)
4967 PERL_ARGS_ASSERT_VNUMIFY;
4969 /* extract the HV from the object */
4972 Perl_croak(aTHX_ "Invalid version object");
4974 /* see if various flags exist */
4975 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
4977 if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
4978 width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
4983 /* attempt to retrieve the version array */
4984 if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
4985 return newSVpvs("0");
4991 return newSVpvs("0");
4994 digit = SvIV(*av_fetch(av, 0, 0));
4995 sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
4996 for ( i = 1 ; i < len ; i++ )
4998 digit = SvIV(*av_fetch(av, i, 0));
5000 const int denom = (width == 2 ? 10 : 100);
5001 const div_t term = div((int)PERL_ABS(digit),denom);
5002 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
5005 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5011 digit = SvIV(*av_fetch(av, len, 0));
5012 if ( alpha && width == 3 ) /* alpha version */
5014 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5018 sv_catpvs(sv, "000");
5026 Accepts a version object and returns the normalized string
5027 representation. Call like:
5031 NOTE: you can pass either the object directly or the SV
5032 contained within the RV.
5034 The SV returned has a refcount of 1.
5040 Perl_vnormal(pTHX_ SV *vs)
5047 PERL_ARGS_ASSERT_VNORMAL;
5049 /* extract the HV from the object */
5052 Perl_croak(aTHX_ "Invalid version object");
5054 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5056 av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)));
5061 return newSVpvs("");
5063 digit = SvIV(*av_fetch(av, 0, 0));
5064 sv = Perl_newSVpvf(aTHX_ "v%"IVdf, (IV)digit);
5065 for ( i = 1 ; i < len ; i++ ) {
5066 digit = SvIV(*av_fetch(av, i, 0));
5067 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5072 /* handle last digit specially */
5073 digit = SvIV(*av_fetch(av, len, 0));
5075 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
5077 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5080 if ( len <= 2 ) { /* short version, must be at least three */
5081 for ( len = 2 - len; len != 0; len-- )
5088 =for apidoc vstringify
5090 In order to maintain maximum compatibility with earlier versions
5091 of Perl, this function will return either the floating point
5092 notation or the multiple dotted notation, depending on whether
5093 the original version contained 1 or more dots, respectively.
5095 The SV returned has a refcount of 1.
5101 Perl_vstringify(pTHX_ SV *vs)
5103 PERL_ARGS_ASSERT_VSTRINGIFY;
5105 /* extract the HV from the object */
5108 Perl_croak(aTHX_ "Invalid version object");
5110 if (hv_exists(MUTABLE_HV(vs), "original", sizeof("original") - 1)) {
5112 pv = *hv_fetchs(MUTABLE_HV(vs), "original", FALSE);
5116 return &PL_sv_undef;
5119 if ( hv_exists(MUTABLE_HV(vs), "qv", 2) )
5129 Version object aware cmp. Both operands must already have been
5130 converted into version objects.
5136 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
5139 bool lalpha = FALSE;
5140 bool ralpha = FALSE;
5145 PERL_ARGS_ASSERT_VCMP;
5147 /* extract the HVs from the objects */
5150 if ( ! ( lhv && rhv ) )
5151 Perl_croak(aTHX_ "Invalid version object");
5153 /* get the left hand term */
5154 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(lhv), "version", FALSE)));
5155 if ( hv_exists(MUTABLE_HV(lhv), "alpha", 5 ) )
5158 /* and the right hand term */
5159 rav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rhv), "version", FALSE)));
5160 if ( hv_exists(MUTABLE_HV(rhv), "alpha", 5 ) )
5168 while ( i <= m && retval == 0 )
5170 left = SvIV(*av_fetch(lav,i,0));
5171 right = SvIV(*av_fetch(rav,i,0));
5179 /* tiebreaker for alpha with identical terms */
5180 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
5182 if ( lalpha && !ralpha )
5186 else if ( ralpha && !lalpha)
5192 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
5196 while ( i <= r && retval == 0 )
5198 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
5199 retval = -1; /* not a match after all */
5205 while ( i <= l && retval == 0 )
5207 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
5208 retval = +1; /* not a match after all */
5216 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
5217 # define EMULATE_SOCKETPAIR_UDP
5220 #ifdef EMULATE_SOCKETPAIR_UDP
5222 S_socketpair_udp (int fd[2]) {
5224 /* Fake a datagram socketpair using UDP to localhost. */
5225 int sockets[2] = {-1, -1};
5226 struct sockaddr_in addresses[2];
5228 Sock_size_t size = sizeof(struct sockaddr_in);
5229 unsigned short port;
5232 memset(&addresses, 0, sizeof(addresses));
5235 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
5236 if (sockets[i] == -1)
5237 goto tidy_up_and_fail;
5239 addresses[i].sin_family = AF_INET;
5240 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5241 addresses[i].sin_port = 0; /* kernel choses port. */
5242 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
5243 sizeof(struct sockaddr_in)) == -1)
5244 goto tidy_up_and_fail;
5247 /* Now have 2 UDP sockets. Find out which port each is connected to, and
5248 for each connect the other socket to it. */
5251 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
5253 goto tidy_up_and_fail;
5254 if (size != sizeof(struct sockaddr_in))
5255 goto abort_tidy_up_and_fail;
5256 /* !1 is 0, !0 is 1 */
5257 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
5258 sizeof(struct sockaddr_in)) == -1)
5259 goto tidy_up_and_fail;
5262 /* Now we have 2 sockets connected to each other. I don't trust some other
5263 process not to have already sent a packet to us (by random) so send
5264 a packet from each to the other. */
5267 /* I'm going to send my own port number. As a short.
5268 (Who knows if someone somewhere has sin_port as a bitfield and needs
5269 this routine. (I'm assuming crays have socketpair)) */
5270 port = addresses[i].sin_port;
5271 got = PerlLIO_write(sockets[i], &port, sizeof(port));
5272 if (got != sizeof(port)) {
5274 goto tidy_up_and_fail;
5275 goto abort_tidy_up_and_fail;
5279 /* Packets sent. I don't trust them to have arrived though.
5280 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
5281 connect to localhost will use a second kernel thread. In 2.6 the
5282 first thread running the connect() returns before the second completes,
5283 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
5284 returns 0. Poor programs have tripped up. One poor program's authors'
5285 had a 50-1 reverse stock split. Not sure how connected these were.)
5286 So I don't trust someone not to have an unpredictable UDP stack.
5290 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
5291 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
5295 FD_SET((unsigned int)sockets[0], &rset);
5296 FD_SET((unsigned int)sockets[1], &rset);
5298 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
5299 if (got != 2 || !FD_ISSET(sockets[0], &rset)
5300 || !FD_ISSET(sockets[1], &rset)) {
5301 /* I hope this is portable and appropriate. */
5303 goto tidy_up_and_fail;
5304 goto abort_tidy_up_and_fail;
5308 /* And the paranoia department even now doesn't trust it to have arrive
5309 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
5311 struct sockaddr_in readfrom;
5312 unsigned short buffer[2];
5317 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5318 sizeof(buffer), MSG_DONTWAIT,
5319 (struct sockaddr *) &readfrom, &size);
5321 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5323 (struct sockaddr *) &readfrom, &size);
5327 goto tidy_up_and_fail;
5328 if (got != sizeof(port)
5329 || size != sizeof(struct sockaddr_in)
5330 /* Check other socket sent us its port. */
5331 || buffer[0] != (unsigned short) addresses[!i].sin_port
5332 /* Check kernel says we got the datagram from that socket */
5333 || readfrom.sin_family != addresses[!i].sin_family
5334 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
5335 || readfrom.sin_port != addresses[!i].sin_port)
5336 goto abort_tidy_up_and_fail;
5339 /* My caller (my_socketpair) has validated that this is non-NULL */
5342 /* I hereby declare this connection open. May God bless all who cross
5346 abort_tidy_up_and_fail:
5347 errno = ECONNABORTED;
5351 if (sockets[0] != -1)
5352 PerlLIO_close(sockets[0]);
5353 if (sockets[1] != -1)
5354 PerlLIO_close(sockets[1]);
5359 #endif /* EMULATE_SOCKETPAIR_UDP */
5361 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
5363 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5364 /* Stevens says that family must be AF_LOCAL, protocol 0.
5365 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
5370 struct sockaddr_in listen_addr;
5371 struct sockaddr_in connect_addr;
5376 || family != AF_UNIX
5379 errno = EAFNOSUPPORT;
5387 #ifdef EMULATE_SOCKETPAIR_UDP
5388 if (type == SOCK_DGRAM)
5389 return S_socketpair_udp(fd);
5392 aTHXa(PERL_GET_THX);
5393 listener = PerlSock_socket(AF_INET, type, 0);
5396 memset(&listen_addr, 0, sizeof(listen_addr));
5397 listen_addr.sin_family = AF_INET;
5398 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5399 listen_addr.sin_port = 0; /* kernel choses port. */
5400 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5401 sizeof(listen_addr)) == -1)
5402 goto tidy_up_and_fail;
5403 if (PerlSock_listen(listener, 1) == -1)
5404 goto tidy_up_and_fail;
5406 connector = PerlSock_socket(AF_INET, type, 0);
5407 if (connector == -1)
5408 goto tidy_up_and_fail;
5409 /* We want to find out the port number to connect to. */
5410 size = sizeof(connect_addr);
5411 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5413 goto tidy_up_and_fail;
5414 if (size != sizeof(connect_addr))
5415 goto abort_tidy_up_and_fail;
5416 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
5417 sizeof(connect_addr)) == -1)
5418 goto tidy_up_and_fail;
5420 size = sizeof(listen_addr);
5421 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5424 goto tidy_up_and_fail;
5425 if (size != sizeof(listen_addr))
5426 goto abort_tidy_up_and_fail;
5427 PerlLIO_close(listener);
5428 /* Now check we are talking to ourself by matching port and host on the
5430 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5432 goto tidy_up_and_fail;
5433 if (size != sizeof(connect_addr)
5434 || listen_addr.sin_family != connect_addr.sin_family
5435 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5436 || listen_addr.sin_port != connect_addr.sin_port) {
5437 goto abort_tidy_up_and_fail;
5443 abort_tidy_up_and_fail:
5445 errno = ECONNABORTED; /* This would be the standard thing to do. */
5447 # ifdef ECONNREFUSED
5448 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5450 errno = ETIMEDOUT; /* Desperation time. */
5457 PerlLIO_close(listener);
5458 if (connector != -1)
5459 PerlLIO_close(connector);
5461 PerlLIO_close(acceptor);
5467 /* In any case have a stub so that there's code corresponding
5468 * to the my_socketpair in embed.fnc. */
5470 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5471 #ifdef HAS_SOCKETPAIR
5472 return socketpair(family, type, protocol, fd);
5481 =for apidoc sv_nosharing
5483 Dummy routine which "shares" an SV when there is no sharing module present.
5484 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5485 Exists to avoid test for a NULL function pointer and because it could
5486 potentially warn under some level of strict-ness.
5492 Perl_sv_nosharing(pTHX_ SV *sv)
5494 PERL_UNUSED_CONTEXT;
5495 PERL_UNUSED_ARG(sv);
5500 =for apidoc sv_destroyable
5502 Dummy routine which reports that object can be destroyed when there is no
5503 sharing module present. It ignores its single SV argument, and returns
5504 'true'. Exists to avoid test for a NULL function pointer and because it
5505 could potentially warn under some level of strict-ness.
5511 Perl_sv_destroyable(pTHX_ SV *sv)
5513 PERL_UNUSED_CONTEXT;
5514 PERL_UNUSED_ARG(sv);
5519 Perl_parse_unicode_opts(pTHX_ const char **popt)
5521 const char *p = *popt;
5524 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5528 opt = (U32) atoi(p);
5531 if (*p && *p != '\n' && *p != '\r') {
5532 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5534 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
5540 case PERL_UNICODE_STDIN:
5541 opt |= PERL_UNICODE_STDIN_FLAG; break;
5542 case PERL_UNICODE_STDOUT:
5543 opt |= PERL_UNICODE_STDOUT_FLAG; break;
5544 case PERL_UNICODE_STDERR:
5545 opt |= PERL_UNICODE_STDERR_FLAG; break;
5546 case PERL_UNICODE_STD:
5547 opt |= PERL_UNICODE_STD_FLAG; break;
5548 case PERL_UNICODE_IN:
5549 opt |= PERL_UNICODE_IN_FLAG; break;
5550 case PERL_UNICODE_OUT:
5551 opt |= PERL_UNICODE_OUT_FLAG; break;
5552 case PERL_UNICODE_INOUT:
5553 opt |= PERL_UNICODE_INOUT_FLAG; break;
5554 case PERL_UNICODE_LOCALE:
5555 opt |= PERL_UNICODE_LOCALE_FLAG; break;
5556 case PERL_UNICODE_ARGV:
5557 opt |= PERL_UNICODE_ARGV_FLAG; break;
5558 case PERL_UNICODE_UTF8CACHEASSERT:
5559 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
5561 if (*p != '\n' && *p != '\r') {
5562 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5565 "Unknown Unicode option letter '%c'", *p);
5572 opt = PERL_UNICODE_DEFAULT_FLAGS;
5574 the_end_of_the_opts_parser:
5576 if (opt & ~PERL_UNICODE_ALL_FLAGS)
5577 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
5578 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5586 # include <starlet.h>
5594 * This is really just a quick hack which grabs various garbage
5595 * values. It really should be a real hash algorithm which
5596 * spreads the effect of every input bit onto every output bit,
5597 * if someone who knows about such things would bother to write it.
5598 * Might be a good idea to add that function to CORE as well.
5599 * No numbers below come from careful analysis or anything here,
5600 * except they are primes and SEED_C1 > 1E6 to get a full-width
5601 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5602 * probably be bigger too.
5605 # define SEED_C1 1000003
5606 #define SEED_C4 73819
5608 # define SEED_C1 25747
5609 #define SEED_C4 20639
5613 #define SEED_C5 26107
5615 #ifndef PERL_NO_DEV_RANDOM
5620 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5621 * in 100-ns units, typically incremented ever 10 ms. */
5622 unsigned int when[2];
5624 # ifdef HAS_GETTIMEOFDAY
5625 struct timeval when;
5631 /* This test is an escape hatch, this symbol isn't set by Configure. */
5632 #ifndef PERL_NO_DEV_RANDOM
5633 #ifndef PERL_RANDOM_DEVICE
5634 /* /dev/random isn't used by default because reads from it will block
5635 * if there isn't enough entropy available. You can compile with
5636 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5637 * is enough real entropy to fill the seed. */
5638 # define PERL_RANDOM_DEVICE "/dev/urandom"
5640 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5642 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5651 _ckvmssts(sys$gettim(when));
5652 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5654 # ifdef HAS_GETTIMEOFDAY
5655 PerlProc_gettimeofday(&when,NULL);
5656 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5659 u = (U32)SEED_C1 * when;
5662 u += SEED_C3 * (U32)PerlProc_getpid();
5663 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5664 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5665 u += SEED_C5 * (U32)PTR2UV(&when);
5671 Perl_get_hash_seed(pTHX_ unsigned char *seed_buffer)
5675 const unsigned char * const end= seed_buffer + PERL_HASH_SEED_BYTES;
5677 PERL_ARGS_ASSERT_GET_HASH_SEED;
5679 s= PerlEnv_getenv("PERL_HASH_SEED");
5682 #ifndef USE_HASH_SEED_EXPLICIT
5687 while (isXDIGIT(*s) && seed_buffer < end) {
5688 *seed_buffer = READ_XDIGIT(s) << 4;
5690 *seed_buffer |= READ_XDIGIT(s);
5694 /* should we check for unparsed crap? */
5699 (void)seedDrand01((Rand_seed_t)seed());
5701 while (seed_buffer < end) {
5702 *seed_buffer++ = (unsigned char)(Drand01() * (U8_MAX+1));
5707 #ifdef PERL_GLOBAL_STRUCT
5709 #define PERL_GLOBAL_STRUCT_INIT
5710 #include "opcode.h" /* the ppaddr and check */
5713 Perl_init_global_struct(pTHX)
5715 struct perl_vars *plvarsp = NULL;
5716 # ifdef PERL_GLOBAL_STRUCT
5717 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5718 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5719 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5720 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5721 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5725 plvarsp = PL_VarsPtr;
5726 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5731 # define PERLVAR(prefix,var,type) /**/
5732 # define PERLVARA(prefix,var,n,type) /**/
5733 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
5734 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
5735 # include "perlvars.h"
5740 # ifdef PERL_GLOBAL_STRUCT
5743 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5744 if (!plvarsp->Gppaddr)
5748 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5749 if (!plvarsp->Gcheck)
5751 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5752 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5754 # ifdef PERL_SET_VARS
5755 PERL_SET_VARS(plvarsp);
5757 # undef PERL_GLOBAL_STRUCT_INIT
5762 #endif /* PERL_GLOBAL_STRUCT */
5764 #ifdef PERL_GLOBAL_STRUCT
5767 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5769 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
5770 # ifdef PERL_GLOBAL_STRUCT
5771 # ifdef PERL_UNSET_VARS
5772 PERL_UNSET_VARS(plvarsp);
5774 free(plvarsp->Gppaddr);
5775 free(plvarsp->Gcheck);
5776 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5782 #endif /* PERL_GLOBAL_STRUCT */
5786 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
5787 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
5788 * given, and you supply your own implementation.
5790 * The default implementation reads a single env var, PERL_MEM_LOG,
5791 * expecting one or more of the following:
5793 * \d+ - fd fd to write to : must be 1st (atoi)
5794 * 'm' - memlog was PERL_MEM_LOG=1
5795 * 's' - svlog was PERL_SV_LOG=1
5796 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
5798 * This makes the logger controllable enough that it can reasonably be
5799 * added to the system perl.
5802 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
5803 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5805 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5807 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
5808 * writes to. In the default logger, this is settable at runtime.
5810 #ifndef PERL_MEM_LOG_FD
5811 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5814 #ifndef PERL_MEM_LOG_NOIMPL
5816 # ifdef DEBUG_LEAKING_SCALARS
5817 # define SV_LOG_SERIAL_FMT " [%lu]"
5818 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
5820 # define SV_LOG_SERIAL_FMT
5821 # define _SV_LOG_SERIAL_ARG(sv)
5825 S_mem_log_common(enum mem_log_type mlt, const UV n,
5826 const UV typesize, const char *type_name, const SV *sv,
5827 Malloc_t oldalloc, Malloc_t newalloc,
5828 const char *filename, const int linenumber,
5829 const char *funcname)
5833 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
5835 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
5838 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
5840 /* We can't use SVs or PerlIO for obvious reasons,
5841 * so we'll use stdio and low-level IO instead. */
5842 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5844 # ifdef HAS_GETTIMEOFDAY
5845 # define MEM_LOG_TIME_FMT "%10d.%06d: "
5846 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
5848 gettimeofday(&tv, 0);
5850 # define MEM_LOG_TIME_FMT "%10d: "
5851 # define MEM_LOG_TIME_ARG (int)when
5855 /* If there are other OS specific ways of hires time than
5856 * gettimeofday() (see ext/Time-HiRes), the easiest way is
5857 * probably that they would be used to fill in the struct
5861 int fd = atoi(pmlenv);
5863 fd = PERL_MEM_LOG_FD;
5865 if (strchr(pmlenv, 't')) {
5866 len = my_snprintf(buf, sizeof(buf),
5867 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
5868 PerlLIO_write(fd, buf, len);
5872 len = my_snprintf(buf, sizeof(buf),
5873 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5874 " %s = %"IVdf": %"UVxf"\n",
5875 filename, linenumber, funcname, n, typesize,
5876 type_name, n * typesize, PTR2UV(newalloc));
5879 len = my_snprintf(buf, sizeof(buf),
5880 "realloc: %s:%d:%s: %"IVdf" %"UVuf
5881 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5882 filename, linenumber, funcname, n, typesize,
5883 type_name, n * typesize, PTR2UV(oldalloc),
5887 len = my_snprintf(buf, sizeof(buf),
5888 "free: %s:%d:%s: %"UVxf"\n",
5889 filename, linenumber, funcname,
5894 len = my_snprintf(buf, sizeof(buf),
5895 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
5896 mlt == MLT_NEW_SV ? "new" : "del",
5897 filename, linenumber, funcname,
5898 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
5903 PerlLIO_write(fd, buf, len);
5907 #endif /* !PERL_MEM_LOG_NOIMPL */
5909 #ifndef PERL_MEM_LOG_NOIMPL
5911 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
5912 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
5914 /* this is suboptimal, but bug compatible. User is providing their
5915 own implementation, but is getting these functions anyway, and they
5916 do nothing. But _NOIMPL users should be able to cope or fix */
5918 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
5919 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
5923 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
5925 const char *filename, const int linenumber,
5926 const char *funcname)
5928 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
5929 NULL, NULL, newalloc,
5930 filename, linenumber, funcname);
5935 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
5936 Malloc_t oldalloc, Malloc_t newalloc,
5937 const char *filename, const int linenumber,
5938 const char *funcname)
5940 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
5941 NULL, oldalloc, newalloc,
5942 filename, linenumber, funcname);
5947 Perl_mem_log_free(Malloc_t oldalloc,
5948 const char *filename, const int linenumber,
5949 const char *funcname)
5951 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
5952 filename, linenumber, funcname);
5957 Perl_mem_log_new_sv(const SV *sv,
5958 const char *filename, const int linenumber,
5959 const char *funcname)
5961 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
5962 filename, linenumber, funcname);
5966 Perl_mem_log_del_sv(const SV *sv,
5967 const char *filename, const int linenumber,
5968 const char *funcname)
5970 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
5971 filename, linenumber, funcname);
5974 #endif /* PERL_MEM_LOG */
5977 =for apidoc my_sprintf
5979 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5980 the length of the string written to the buffer. Only rare pre-ANSI systems
5981 need the wrapper function - usually this is a direct call to C<sprintf>.
5985 #ifndef SPRINTF_RETURNS_STRLEN
5987 Perl_my_sprintf(char *buffer, const char* pat, ...)
5990 PERL_ARGS_ASSERT_MY_SPRINTF;
5991 va_start(args, pat);
5992 vsprintf(buffer, pat, args);
5994 return strlen(buffer);
5999 =for apidoc my_snprintf
6001 The C library C<snprintf> functionality, if available and
6002 standards-compliant (uses C<vsnprintf>, actually). However, if the
6003 C<vsnprintf> is not available, will unfortunately use the unsafe
6004 C<vsprintf> which can overrun the buffer (there is an overrun check,
6005 but that may be too late). Consider using C<sv_vcatpvf> instead, or
6006 getting C<vsnprintf>.
6011 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
6015 PERL_ARGS_ASSERT_MY_SNPRINTF;
6016 va_start(ap, format);
6017 #ifdef HAS_VSNPRINTF
6018 retval = vsnprintf(buffer, len, format, ap);
6020 retval = vsprintf(buffer, format, ap);
6023 /* vsprintf() shows failure with < 0 */
6025 #ifdef HAS_VSNPRINTF
6026 /* vsnprintf() shows failure with >= len */
6028 (len > 0 && (Size_t)retval >= len)
6031 Perl_croak_nocontext("panic: my_snprintf buffer overflow");
6036 =for apidoc my_vsnprintf
6038 The C library C<vsnprintf> if available and standards-compliant.
6039 However, if if the C<vsnprintf> is not available, will unfortunately
6040 use the unsafe C<vsprintf> which can overrun the buffer (there is an
6041 overrun check, but that may be too late). Consider using
6042 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
6047 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
6053 PERL_ARGS_ASSERT_MY_VSNPRINTF;
6055 Perl_va_copy(ap, apc);
6056 # ifdef HAS_VSNPRINTF
6057 retval = vsnprintf(buffer, len, format, apc);
6059 retval = vsprintf(buffer, format, apc);
6062 # ifdef HAS_VSNPRINTF
6063 retval = vsnprintf(buffer, len, format, ap);
6065 retval = vsprintf(buffer, format, ap);
6067 #endif /* #ifdef NEED_VA_COPY */
6068 /* vsprintf() shows failure with < 0 */
6070 #ifdef HAS_VSNPRINTF
6071 /* vsnprintf() shows failure with >= len */
6073 (len > 0 && (Size_t)retval >= len)
6076 Perl_croak_nocontext("panic: my_vsnprintf buffer overflow");
6081 Perl_my_clearenv(pTHX)
6084 #if ! defined(PERL_MICRO)
6085 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
6087 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
6088 # if defined(USE_ENVIRON_ARRAY)
6089 # if defined(USE_ITHREADS)
6090 /* only the parent thread can clobber the process environment */
6091 if (PL_curinterp == aTHX)
6092 # endif /* USE_ITHREADS */
6094 # if ! defined(PERL_USE_SAFE_PUTENV)
6095 if ( !PL_use_safe_putenv) {
6097 if (environ == PL_origenviron)
6098 environ = (char**)safesysmalloc(sizeof(char*));
6100 for (i = 0; environ[i]; i++)
6101 (void)safesysfree(environ[i]);
6104 # else /* PERL_USE_SAFE_PUTENV */
6105 # if defined(HAS_CLEARENV)
6107 # elif defined(HAS_UNSETENV)
6108 int bsiz = 80; /* Most envvar names will be shorter than this. */
6109 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
6110 char *buf = (char*)safesysmalloc(bufsiz);
6111 while (*environ != NULL) {
6112 char *e = strchr(*environ, '=');
6113 int l = e ? e - *environ : (int)strlen(*environ);
6115 (void)safesysfree(buf);
6116 bsiz = l + 1; /* + 1 for the \0. */
6117 buf = (char*)safesysmalloc(bufsiz);
6119 memcpy(buf, *environ, l);
6121 (void)unsetenv(buf);
6123 (void)safesysfree(buf);
6124 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
6125 /* Just null environ and accept the leakage. */
6127 # endif /* HAS_CLEARENV || HAS_UNSETENV */
6128 # endif /* ! PERL_USE_SAFE_PUTENV */
6130 # endif /* USE_ENVIRON_ARRAY */
6131 # endif /* PERL_IMPLICIT_SYS || WIN32 */
6132 #endif /* PERL_MICRO */
6135 #ifdef PERL_IMPLICIT_CONTEXT
6137 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
6138 the global PL_my_cxt_index is incremented, and that value is assigned to
6139 that module's static my_cxt_index (who's address is passed as an arg).
6140 Then, for each interpreter this function is called for, it makes sure a
6141 void* slot is available to hang the static data off, by allocating or
6142 extending the interpreter's PL_my_cxt_list array */
6144 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
6146 Perl_my_cxt_init(pTHX_ int *index, size_t size)
6150 PERL_ARGS_ASSERT_MY_CXT_INIT;
6152 /* this module hasn't been allocated an index yet */
6153 #if defined(USE_ITHREADS)
6154 MUTEX_LOCK(&PL_my_ctx_mutex);
6156 *index = PL_my_cxt_index++;
6157 #if defined(USE_ITHREADS)
6158 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6162 /* make sure the array is big enough */
6163 if (PL_my_cxt_size <= *index) {
6164 if (PL_my_cxt_size) {
6165 while (PL_my_cxt_size <= *index)
6166 PL_my_cxt_size *= 2;
6167 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6170 PL_my_cxt_size = 16;
6171 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6174 /* newSV() allocates one more than needed */
6175 p = (void*)SvPVX(newSV(size-1));
6176 PL_my_cxt_list[*index] = p;
6177 Zero(p, size, char);
6181 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6184 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
6189 PERL_ARGS_ASSERT_MY_CXT_INDEX;
6191 for (index = 0; index < PL_my_cxt_index; index++) {
6192 const char *key = PL_my_cxt_keys[index];
6193 /* try direct pointer compare first - there are chances to success,
6194 * and it's much faster.
6196 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
6203 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
6209 PERL_ARGS_ASSERT_MY_CXT_INIT;
6211 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
6213 /* this module hasn't been allocated an index yet */
6214 #if defined(USE_ITHREADS)
6215 MUTEX_LOCK(&PL_my_ctx_mutex);
6217 index = PL_my_cxt_index++;
6218 #if defined(USE_ITHREADS)
6219 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6223 /* make sure the array is big enough */
6224 if (PL_my_cxt_size <= index) {
6225 int old_size = PL_my_cxt_size;
6227 if (PL_my_cxt_size) {
6228 while (PL_my_cxt_size <= index)
6229 PL_my_cxt_size *= 2;
6230 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6231 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6234 PL_my_cxt_size = 16;
6235 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6236 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6238 for (i = old_size; i < PL_my_cxt_size; i++) {
6239 PL_my_cxt_keys[i] = 0;
6240 PL_my_cxt_list[i] = 0;
6243 PL_my_cxt_keys[index] = my_cxt_key;
6244 /* newSV() allocates one more than needed */
6245 p = (void*)SvPVX(newSV(size-1));
6246 PL_my_cxt_list[index] = p;
6247 Zero(p, size, char);
6250 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6251 #endif /* PERL_IMPLICIT_CONTEXT */
6254 Perl_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
6258 const char *vn = NULL;
6259 SV *const module = PL_stack_base[ax];
6261 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
6263 if (items >= 2) /* version supplied as bootstrap arg */
6264 sv = PL_stack_base[ax + 1];
6266 /* XXX GV_ADDWARN */
6268 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6269 if (!sv || !SvOK(sv)) {
6271 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6275 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
6276 SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version")
6277 ? sv : sv_2mortal(new_version(sv));
6278 xssv = upg_version(xssv, 0);
6279 if ( vcmp(pmsv,xssv) ) {
6280 SV *string = vstringify(xssv);
6281 SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
6282 " does not match ", module, string);
6284 SvREFCNT_dec(string);
6285 string = vstringify(pmsv);
6288 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, module, vn,
6291 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, string);
6293 SvREFCNT_dec(string);
6295 Perl_sv_2mortal(aTHX_ xpt);
6296 Perl_croak_sv(aTHX_ xpt);
6302 Perl_xs_apiversion_bootcheck(pTHX_ SV *module, const char *api_p,
6306 SV *compver = Perl_newSVpvn_flags(aTHX_ api_p, api_len, SVs_TEMP);
6309 PERL_ARGS_ASSERT_XS_APIVERSION_BOOTCHECK;
6311 /* This might croak */
6312 compver = upg_version(compver, 0);
6313 /* This should never croak */
6314 runver = new_version(PL_apiversion);
6315 if (vcmp(compver, runver)) {
6316 SV *compver_string = vstringify(compver);
6317 SV *runver_string = vstringify(runver);
6318 xpt = Perl_newSVpvf(aTHX_ "Perl API version %"SVf
6319 " of %"SVf" does not match %"SVf,
6320 compver_string, module, runver_string);
6321 Perl_sv_2mortal(aTHX_ xpt);
6323 SvREFCNT_dec(compver_string);
6324 SvREFCNT_dec(runver_string);
6326 SvREFCNT_dec(runver);
6328 Perl_croak_sv(aTHX_ xpt);
6333 Perl_my_strlcat(char *dst, const char *src, Size_t size)
6335 Size_t used, length, copy;
6338 length = strlen(src);
6339 if (size > 0 && used < size - 1) {
6340 copy = (length >= size - used) ? size - used - 1 : length;
6341 memcpy(dst + used, src, copy);
6342 dst[used + copy] = '\0';
6344 return used + length;
6350 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
6352 Size_t length, copy;
6354 length = strlen(src);
6356 copy = (length >= size) ? size - 1 : length;
6357 memcpy(dst, src, copy);
6364 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
6365 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
6366 long _ftol( double ); /* Defined by VC6 C libs. */
6367 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
6370 PERL_STATIC_INLINE bool
6371 S_gv_has_usable_name(pTHX_ GV *gv)
6375 && HvENAME(GvSTASH(gv))
6376 && (gvp = (GV **)hv_fetch(
6377 GvSTASH(gv), GvNAME(gv),
6378 GvNAMEUTF8(gv) ? -GvNAMELEN(gv) : GvNAMELEN(gv), 0
6384 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
6387 SV * const dbsv = GvSVn(PL_DBsub);
6388 const bool save_taint = TAINT_get; /* Accepted unused var warning under NO_TAINT_SUPPORT */
6390 /* When we are called from pp_goto (svp is null),
6391 * we do not care about using dbsv to call CV;
6392 * it's for informational purposes only.
6395 PERL_ARGS_ASSERT_GET_DB_SUB;
6399 if (!PERLDB_SUB_NN) {
6403 gv_efullname3(dbsv, gv, NULL);
6405 else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
6406 || strEQ(GvNAME(gv), "END")
6407 || ( /* Could be imported, and old sub redefined. */
6408 (GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv))
6410 !( (SvTYPE(*svp) == SVt_PVGV)
6411 && (GvCV((const GV *)*svp) == cv)
6412 /* Use GV from the stack as a fallback. */
6413 && S_gv_has_usable_name(aTHX_ gv = (GV *)*svp)
6417 /* GV is potentially non-unique, or contain different CV. */
6418 SV * const tmp = newRV(MUTABLE_SV(cv));
6419 sv_setsv(dbsv, tmp);
6423 sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv)));
6424 sv_catpvs(dbsv, "::");
6426 dbsv, GvNAME(gv), GvNAMELEN(gv),
6427 GvNAMEUTF8(gv) ? SV_CATUTF8 : SV_CATBYTES
6432 const int type = SvTYPE(dbsv);
6433 if (type < SVt_PVIV && type != SVt_IV)
6434 sv_upgrade(dbsv, SVt_PVIV);
6435 (void)SvIOK_on(dbsv);
6436 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
6438 TAINT_IF(save_taint);
6442 Perl_my_dirfd(pTHX_ DIR * dir) {
6444 /* Most dirfd implementations have problems when passed NULL. */
6449 #elif defined(HAS_DIR_DD_FD)
6452 Perl_die(aTHX_ PL_no_func, "dirfd");
6453 assert(0); /* NOT REACHED */
6459 Perl_get_re_arg(pTHX_ SV *sv) {
6465 sv = MUTABLE_SV(SvRV(sv));
6466 if (SvTYPE(sv) == SVt_REGEXP)
6467 return (REGEXP*) sv;
6475 * c-indentation-style: bsd
6477 * indent-tabs-mode: nil
6480 * ex: set ts=8 sts=4 sw=4 et: