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(char *to, const char *toend, const char *from, const char *fromend, 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(const char *big, const char *little)
432 PERL_ARGS_ASSERT_INSTR;
434 /* libc prior to 4.6.27 did not work properly on a NULL 'little' */
437 return strstr((char*)big, (char*)little);
440 /* same as instr but allow embedded nulls. The end pointers point to 1 beyond
441 * the final character desired to be checked */
444 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
446 PERL_ARGS_ASSERT_NINSTR;
450 const char first = *little;
452 bigend -= lend - little++;
454 while (big <= bigend) {
455 if (*big++ == first) {
456 for (x=big,s=little; s < lend; x++,s++) {
460 return (char*)(big-1);
467 /* reverse of the above--find last substring */
470 Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
473 const I32 first = *little;
474 const char * const littleend = lend;
476 PERL_ARGS_ASSERT_RNINSTR;
478 if (little >= littleend)
479 return (char*)bigend;
481 big = bigend - (littleend - little++);
482 while (big >= bigbeg) {
486 for (x=big+2,s=little; s < littleend; /**/ ) {
495 return (char*)(big+1);
500 /* As a space optimization, we do not compile tables for strings of length
501 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
502 special-cased in fbm_instr().
504 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
507 =head1 Miscellaneous Functions
509 =for apidoc fbm_compile
511 Analyses the string in order to make fast searches on it using fbm_instr()
512 -- the Boyer-Moore algorithm.
518 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
528 PERL_ARGS_ASSERT_FBM_COMPILE;
530 if (isGV_with_GP(sv))
536 if (flags & FBMcf_TAIL) {
537 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
538 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
539 if (mg && mg->mg_len >= 0)
542 s = (U8*)SvPV_force_mutable(sv, len);
543 if (len == 0) /* TAIL might be on a zero-length string. */
545 SvUPGRADE(sv, SVt_PVMG);
550 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
551 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
552 to call SvVALID_off() if the scalar was assigned to.
554 The comment itself (and "deeper magic" below) date back to
555 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
557 where the magic (presumably) was that the scalar had a BM table hidden
560 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
561 the table instead of the previous (somewhat hacky) approach of co-opting
562 the string buffer and storing it after the string. */
564 assert(!mg_find(sv, PERL_MAGIC_bm));
565 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
569 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
571 const U8 mlen = (len>255) ? 255 : (U8)len;
572 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
575 Newx(table, 256, U8);
576 memset((void*)table, mlen, 256);
577 mg->mg_ptr = (char *)table;
580 s += len - 1; /* last char */
583 if (table[*s] == mlen)
589 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
590 for (i = 0; i < len; i++) {
591 if (PL_freq[s[i]] < frequency) {
593 frequency = PL_freq[s[i]];
596 BmRARE(sv) = s[rarest];
597 BmPREVIOUS(sv) = rarest;
598 BmUSEFUL(sv) = 100; /* Initial value */
599 if (flags & FBMcf_TAIL)
601 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
602 BmRARE(sv), BmPREVIOUS(sv)));
605 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
606 /* If SvTAIL is actually due to \Z or \z, this gives false positives
610 =for apidoc fbm_instr
612 Returns the location of the SV in the string delimited by C<big> and
613 C<bigend>. It returns C<NULL> if the string can't be found. The C<sv>
614 does not have to be fbm_compiled, but the search will not be as fast
621 Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
625 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
626 STRLEN littlelen = l;
627 const I32 multiline = flags & FBMrf_MULTILINE;
629 PERL_ARGS_ASSERT_FBM_INSTR;
631 if ((STRLEN)(bigend - big) < littlelen) {
632 if ( SvTAIL(littlestr)
633 && ((STRLEN)(bigend - big) == littlelen - 1)
635 || (*big == *little &&
636 memEQ((char *)big, (char *)little, littlelen - 1))))
641 switch (littlelen) { /* Special cases for 0, 1 and 2 */
643 return (char*)big; /* Cannot be SvTAIL! */
645 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
646 /* Know that bigend != big. */
647 if (bigend[-1] == '\n')
648 return (char *)(bigend - 1);
649 return (char *) bigend;
657 if (SvTAIL(littlestr))
658 return (char *) bigend;
661 if (SvTAIL(littlestr) && !multiline) {
662 if (bigend[-1] == '\n' && bigend[-2] == *little)
663 return (char*)bigend - 2;
664 if (bigend[-1] == *little)
665 return (char*)bigend - 1;
669 /* This should be better than FBM if c1 == c2, and almost
670 as good otherwise: maybe better since we do less indirection.
671 And we save a lot of memory by caching no table. */
672 const unsigned char c1 = little[0];
673 const unsigned char c2 = little[1];
678 while (s <= bigend) {
688 goto check_1char_anchor;
699 goto check_1char_anchor;
702 while (s <= bigend) {
707 goto check_1char_anchor;
716 check_1char_anchor: /* One char and anchor! */
717 if (SvTAIL(littlestr) && (*bigend == *little))
718 return (char *)bigend; /* bigend is already decremented. */
721 break; /* Only lengths 0 1 and 2 have special-case code. */
724 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
725 s = bigend - littlelen;
726 if (s >= big && bigend[-1] == '\n' && *s == *little
727 /* Automatically of length > 2 */
728 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
730 return (char*)s; /* how sweet it is */
733 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
735 return (char*)s + 1; /* how sweet it is */
739 if (!SvVALID(littlestr)) {
740 char * const b = ninstr((char*)big,(char*)bigend,
741 (char*)little, (char*)little + littlelen);
743 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
744 /* Chop \n from littlestr: */
745 s = bigend - littlelen + 1;
747 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
757 if (littlelen > (STRLEN)(bigend - big))
761 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
762 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
763 const unsigned char *oldlittle;
765 --littlelen; /* Last char found by table lookup */
768 little += littlelen; /* last char */
774 if ((tmp = table[*s])) {
775 if ((s += tmp) < bigend)
779 else { /* less expensive than calling strncmp() */
780 unsigned char * const olds = s;
785 if (*--s == *--little)
787 s = olds + 1; /* here we pay the price for failure */
789 if (s < bigend) /* fake up continue to outer loop */
799 && memEQ((char *)(bigend - littlelen),
800 (char *)(oldlittle - littlelen), littlelen) )
801 return (char*)bigend - littlelen;
807 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
810 PERL_ARGS_ASSERT_SCREAMINSTR;
811 PERL_UNUSED_ARG(bigstr);
812 PERL_UNUSED_ARG(littlestr);
813 PERL_UNUSED_ARG(start_shift);
814 PERL_UNUSED_ARG(end_shift);
815 PERL_UNUSED_ARG(old_posp);
816 PERL_UNUSED_ARG(last);
818 /* This function must only ever be called on a scalar with study magic,
819 but those do not happen any more. */
820 Perl_croak(aTHX_ "panic: screaminstr");
827 Returns true if the leading len bytes of the strings s1 and s2 are the same
828 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
829 match themselves and their opposite case counterparts. Non-cased and non-ASCII
830 range bytes match only themselves.
837 Perl_foldEQ(const char *s1, const char *s2, I32 len)
839 const U8 *a = (const U8 *)s1;
840 const U8 *b = (const U8 *)s2;
842 PERL_ARGS_ASSERT_FOLDEQ;
847 if (*a != *b && *a != PL_fold[*b])
854 Perl_foldEQ_latin1(const char *s1, const char *s2, I32 len)
856 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
857 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
858 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
859 * does it check that the strings each have at least 'len' characters */
861 const U8 *a = (const U8 *)s1;
862 const U8 *b = (const U8 *)s2;
864 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
869 if (*a != *b && *a != PL_fold_latin1[*b]) {
878 =for apidoc foldEQ_locale
880 Returns true if the leading len bytes of the strings s1 and s2 are the same
881 case-insensitively in the current locale; false otherwise.
887 Perl_foldEQ_locale(const char *s1, const char *s2, I32 len)
890 const U8 *a = (const U8 *)s1;
891 const U8 *b = (const U8 *)s2;
893 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
898 if (*a != *b && *a != PL_fold_locale[*b])
905 /* copy a string to a safe spot */
908 =head1 Memory Management
912 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
913 string which is a duplicate of C<pv>. The size of the string is
914 determined by C<strlen()>. The memory allocated for the new string can
915 be freed with the C<Safefree()> function.
921 Perl_savepv(pTHX_ const char *pv)
928 const STRLEN pvlen = strlen(pv)+1;
929 Newx(newaddr, pvlen, char);
930 return (char*)memcpy(newaddr, pv, pvlen);
934 /* same thing but with a known length */
939 Perl's version of what C<strndup()> would be if it existed. Returns a
940 pointer to a newly allocated string which is a duplicate of the first
941 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
942 the new string can be freed with the C<Safefree()> function.
948 Perl_savepvn(pTHX_ const char *pv, I32 len)
955 Newx(newaddr,len+1,char);
956 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
958 /* might not be null terminated */
960 return (char *) CopyD(pv,newaddr,len,char);
963 return (char *) ZeroD(newaddr,len+1,char);
968 =for apidoc savesharedpv
970 A version of C<savepv()> which allocates the duplicate string in memory
971 which is shared between threads.
976 Perl_savesharedpv(pTHX_ const char *pv)
983 pvlen = strlen(pv)+1;
984 newaddr = (char*)PerlMemShared_malloc(pvlen);
988 return (char*)memcpy(newaddr, pv, pvlen);
992 =for apidoc savesharedpvn
994 A version of C<savepvn()> which allocates the duplicate string in memory
995 which is shared between threads. (With the specific difference that a NULL
996 pointer is not acceptable)
1001 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1003 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1005 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1010 newaddr[len] = '\0';
1011 return (char*)memcpy(newaddr, pv, len);
1015 =for apidoc savesvpv
1017 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1018 the passed in SV using C<SvPV()>
1024 Perl_savesvpv(pTHX_ SV *sv)
1027 const char * const pv = SvPV_const(sv, len);
1030 PERL_ARGS_ASSERT_SAVESVPV;
1033 Newx(newaddr,len,char);
1034 return (char *) CopyD(pv,newaddr,len,char);
1038 =for apidoc savesharedsvpv
1040 A version of C<savesharedpv()> which allocates the duplicate string in
1041 memory which is shared between threads.
1047 Perl_savesharedsvpv(pTHX_ SV *sv)
1050 const char * const pv = SvPV_const(sv, len);
1052 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1054 return savesharedpvn(pv, len);
1057 /* the SV for Perl_form() and mess() is not kept in an arena */
1066 if (PL_phase != PERL_PHASE_DESTRUCT)
1067 return newSVpvs_flags("", SVs_TEMP);
1072 /* Create as PVMG now, to avoid any upgrading later */
1074 Newxz(any, 1, XPVMG);
1075 SvFLAGS(sv) = SVt_PVMG;
1076 SvANY(sv) = (void*)any;
1078 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1083 #if defined(PERL_IMPLICIT_CONTEXT)
1085 Perl_form_nocontext(const char* pat, ...)
1090 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1091 va_start(args, pat);
1092 retval = vform(pat, &args);
1096 #endif /* PERL_IMPLICIT_CONTEXT */
1099 =head1 Miscellaneous Functions
1102 Takes a sprintf-style format pattern and conventional
1103 (non-SV) arguments and returns the formatted string.
1105 (char *) Perl_form(pTHX_ const char* pat, ...)
1107 can be used any place a string (char *) is required:
1109 char * s = Perl_form("%d.%d",major,minor);
1111 Uses a single private buffer so if you want to format several strings you
1112 must explicitly copy the earlier strings away (and free the copies when you
1119 Perl_form(pTHX_ const char* pat, ...)
1123 PERL_ARGS_ASSERT_FORM;
1124 va_start(args, pat);
1125 retval = vform(pat, &args);
1131 Perl_vform(pTHX_ const char *pat, va_list *args)
1133 SV * const sv = mess_alloc();
1134 PERL_ARGS_ASSERT_VFORM;
1135 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1140 =for apidoc Am|SV *|mess|const char *pat|...
1142 Take a sprintf-style format pattern and argument list. These are used to
1143 generate a string message. If the message does not end with a newline,
1144 then it will be extended with some indication of the current location
1145 in the code, as described for L</mess_sv>.
1147 Normally, the resulting message is returned in a new mortal SV.
1148 During global destruction a single SV may be shared between uses of
1154 #if defined(PERL_IMPLICIT_CONTEXT)
1156 Perl_mess_nocontext(const char *pat, ...)
1161 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1162 va_start(args, pat);
1163 retval = vmess(pat, &args);
1167 #endif /* PERL_IMPLICIT_CONTEXT */
1170 Perl_mess(pTHX_ const char *pat, ...)
1174 PERL_ARGS_ASSERT_MESS;
1175 va_start(args, pat);
1176 retval = vmess(pat, &args);
1182 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1185 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1187 PERL_ARGS_ASSERT_CLOSEST_COP;
1189 if (!o || o == PL_op)
1192 if (o->op_flags & OPf_KIDS) {
1194 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1197 /* If the OP_NEXTSTATE has been optimised away we can still use it
1198 * the get the file and line number. */
1200 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1201 cop = (const COP *)kid;
1203 /* Keep searching, and return when we've found something. */
1205 new_cop = closest_cop(cop, kid);
1211 /* Nothing found. */
1217 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1219 Expands a message, intended for the user, to include an indication of
1220 the current location in the code, if the message does not already appear
1223 C<basemsg> is the initial message or object. If it is a reference, it
1224 will be used as-is and will be the result of this function. Otherwise it
1225 is used as a string, and if it already ends with a newline, it is taken
1226 to be complete, and the result of this function will be the same string.
1227 If the message does not end with a newline, then a segment such as C<at
1228 foo.pl line 37> will be appended, and possibly other clauses indicating
1229 the current state of execution. The resulting message will end with a
1232 Normally, the resulting message is returned in a new mortal SV.
1233 During global destruction a single SV may be shared between uses of this
1234 function. If C<consume> is true, then the function is permitted (but not
1235 required) to modify and return C<basemsg> instead of allocating a new SV.
1241 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1246 PERL_ARGS_ASSERT_MESS_SV;
1248 if (SvROK(basemsg)) {
1254 sv_setsv(sv, basemsg);
1259 if (SvPOK(basemsg) && consume) {
1264 sv_copypv(sv, basemsg);
1267 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1269 * Try and find the file and line for PL_op. This will usually be
1270 * PL_curcop, but it might be a cop that has been optimised away. We
1271 * can try to find such a cop by searching through the optree starting
1272 * from the sibling of PL_curcop.
1275 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1280 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1281 OutCopFILE(cop), (IV)CopLINE(cop));
1282 /* Seems that GvIO() can be untrustworthy during global destruction. */
1283 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1284 && IoLINES(GvIOp(PL_last_in_gv)))
1287 const bool line_mode = (RsSIMPLE(PL_rs) &&
1288 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1289 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1290 SVfARG(PL_last_in_gv == PL_argvgv
1292 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1293 line_mode ? "line" : "chunk",
1294 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1296 if (PL_phase == PERL_PHASE_DESTRUCT)
1297 sv_catpvs(sv, " during global destruction");
1298 sv_catpvs(sv, ".\n");
1304 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1306 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1307 argument list. These are used to generate a string message. If the
1308 message does not end with a newline, then it will be extended with
1309 some indication of the current location in the code, as described for
1312 Normally, the resulting message is returned in a new mortal SV.
1313 During global destruction a single SV may be shared between uses of
1320 Perl_vmess(pTHX_ const char *pat, va_list *args)
1323 SV * const sv = mess_alloc();
1325 PERL_ARGS_ASSERT_VMESS;
1327 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1328 return mess_sv(sv, 1);
1332 Perl_write_to_stderr(pTHX_ SV* msv)
1338 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1340 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1341 && (io = GvIO(PL_stderrgv))
1342 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1343 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1344 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1347 /* SFIO can really mess with your errno */
1350 PerlIO * const serr = Perl_error_log;
1352 do_print(msv, serr);
1353 (void)PerlIO_flush(serr);
1361 =head1 Warning and Dieing
1364 /* Common code used in dieing and warning */
1367 S_with_queued_errors(pTHX_ SV *ex)
1369 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1370 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1371 sv_catsv(PL_errors, ex);
1372 ex = sv_mortalcopy(PL_errors);
1373 SvCUR_set(PL_errors, 0);
1379 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1385 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1386 /* sv_2cv might call Perl_croak() or Perl_warner() */
1387 SV * const oldhook = *hook;
1395 cv = sv_2cv(oldhook, &stash, &gv, 0);
1397 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1407 exarg = newSVsv(ex);
1408 SvREADONLY_on(exarg);
1411 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1415 call_sv(MUTABLE_SV(cv), G_DISCARD);
1424 =for apidoc Am|OP *|die_sv|SV *baseex
1426 Behaves the same as L</croak_sv>, except for the return type.
1427 It should be used only where the C<OP *> return type is required.
1428 The function never actually returns.
1434 Perl_die_sv(pTHX_ SV *baseex)
1436 PERL_ARGS_ASSERT_DIE_SV;
1438 assert(0); /* NOTREACHED */
1443 =for apidoc Am|OP *|die|const char *pat|...
1445 Behaves the same as L</croak>, except for the return type.
1446 It should be used only where the C<OP *> return type is required.
1447 The function never actually returns.
1452 #if defined(PERL_IMPLICIT_CONTEXT)
1454 Perl_die_nocontext(const char* pat, ...)
1458 va_start(args, pat);
1460 assert(0); /* NOTREACHED */
1464 #endif /* PERL_IMPLICIT_CONTEXT */
1467 Perl_die(pTHX_ const char* pat, ...)
1470 va_start(args, pat);
1472 assert(0); /* NOTREACHED */
1478 =for apidoc Am|void|croak_sv|SV *baseex
1480 This is an XS interface to Perl's C<die> function.
1482 C<baseex> is the error message or object. If it is a reference, it
1483 will be used as-is. Otherwise it is used as a string, and if it does
1484 not end with a newline then it will be extended with some indication of
1485 the current location in the code, as described for L</mess_sv>.
1487 The error message or object will be used as an exception, by default
1488 returning control to the nearest enclosing C<eval>, but subject to
1489 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1490 function never returns normally.
1492 To die with a simple string message, the L</croak> function may be
1499 Perl_croak_sv(pTHX_ SV *baseex)
1501 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1502 PERL_ARGS_ASSERT_CROAK_SV;
1503 invoke_exception_hook(ex, FALSE);
1508 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1510 This is an XS interface to Perl's C<die> function.
1512 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1513 argument list. These are used to generate a string message. If the
1514 message does not end with a newline, then it will be extended with
1515 some indication of the current location in the code, as described for
1518 The error message will be used as an exception, by default
1519 returning control to the nearest enclosing C<eval>, but subject to
1520 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1521 function never returns normally.
1523 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1524 (C<$@>) will be used as an error message or object instead of building an
1525 error message from arguments. If you want to throw a non-string object,
1526 or build an error message in an SV yourself, it is preferable to use
1527 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1533 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1535 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1536 invoke_exception_hook(ex, FALSE);
1541 =for apidoc Am|void|croak|const char *pat|...
1543 This is an XS interface to Perl's C<die> function.
1545 Take a sprintf-style format pattern and argument list. These are used to
1546 generate a string message. If the message does not end with a newline,
1547 then it will be extended with some indication of the current location
1548 in the code, as described for L</mess_sv>.
1550 The error message will be used as an exception, by default
1551 returning control to the nearest enclosing C<eval>, but subject to
1552 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1553 function never returns normally.
1555 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1556 (C<$@>) will be used as an error message or object instead of building an
1557 error message from arguments. If you want to throw a non-string object,
1558 or build an error message in an SV yourself, it is preferable to use
1559 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1564 #if defined(PERL_IMPLICIT_CONTEXT)
1566 Perl_croak_nocontext(const char *pat, ...)
1570 va_start(args, pat);
1572 assert(0); /* NOTREACHED */
1575 #endif /* PERL_IMPLICIT_CONTEXT */
1578 Perl_croak(pTHX_ const char *pat, ...)
1581 va_start(args, pat);
1583 assert(0); /* NOTREACHED */
1588 =for apidoc Am|void|croak_no_modify
1590 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1591 terser object code than using C<Perl_croak>. Less code used on exception code
1592 paths reduces CPU cache pressure.
1598 Perl_croak_no_modify()
1600 Perl_croak_nocontext( "%s", PL_no_modify);
1603 /* does not return, used in util.c perlio.c and win32.c
1604 This is typically called when malloc returns NULL.
1611 /* Can't use PerlIO to write as it allocates memory */
1612 PerlLIO_write(PerlIO_fileno(Perl_error_log),
1613 PL_no_mem, sizeof(PL_no_mem)-1);
1617 /* does not return, used only in POPSTACK */
1619 Perl_croak_popstack(void)
1622 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
1627 =for apidoc Am|void|warn_sv|SV *baseex
1629 This is an XS interface to Perl's C<warn> function.
1631 C<baseex> is the error message or object. If it is a reference, it
1632 will be used as-is. Otherwise it is used as a string, and if it does
1633 not end with a newline then it will be extended with some indication of
1634 the current location in the code, as described for L</mess_sv>.
1636 The error message or object will by default be written to standard error,
1637 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1639 To warn with a simple string message, the L</warn> function may be
1646 Perl_warn_sv(pTHX_ SV *baseex)
1648 SV *ex = mess_sv(baseex, 0);
1649 PERL_ARGS_ASSERT_WARN_SV;
1650 if (!invoke_exception_hook(ex, TRUE))
1651 write_to_stderr(ex);
1655 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1657 This is an XS interface to Perl's C<warn> function.
1659 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1660 argument list. These are used to generate a string message. If the
1661 message does not end with a newline, then it will be extended with
1662 some indication of the current location in the code, as described for
1665 The error message or object will by default be written to standard error,
1666 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1668 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1674 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1676 SV *ex = vmess(pat, args);
1677 PERL_ARGS_ASSERT_VWARN;
1678 if (!invoke_exception_hook(ex, TRUE))
1679 write_to_stderr(ex);
1683 =for apidoc Am|void|warn|const char *pat|...
1685 This is an XS interface to Perl's C<warn> function.
1687 Take a sprintf-style format pattern and argument list. These are used to
1688 generate a string message. If the message does not end with a newline,
1689 then it will be extended with some indication of the current location
1690 in the code, as described for L</mess_sv>.
1692 The error message or object will by default be written to standard error,
1693 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1695 Unlike with L</croak>, C<pat> is not permitted to be null.
1700 #if defined(PERL_IMPLICIT_CONTEXT)
1702 Perl_warn_nocontext(const char *pat, ...)
1706 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1707 va_start(args, pat);
1711 #endif /* PERL_IMPLICIT_CONTEXT */
1714 Perl_warn(pTHX_ const char *pat, ...)
1717 PERL_ARGS_ASSERT_WARN;
1718 va_start(args, pat);
1723 #if defined(PERL_IMPLICIT_CONTEXT)
1725 Perl_warner_nocontext(U32 err, const char *pat, ...)
1729 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1730 va_start(args, pat);
1731 vwarner(err, pat, &args);
1734 #endif /* PERL_IMPLICIT_CONTEXT */
1737 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1739 PERL_ARGS_ASSERT_CK_WARNER_D;
1741 if (Perl_ckwarn_d(aTHX_ err)) {
1743 va_start(args, pat);
1744 vwarner(err, pat, &args);
1750 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1752 PERL_ARGS_ASSERT_CK_WARNER;
1754 if (Perl_ckwarn(aTHX_ err)) {
1756 va_start(args, pat);
1757 vwarner(err, pat, &args);
1763 Perl_warner(pTHX_ U32 err, const char* pat,...)
1766 PERL_ARGS_ASSERT_WARNER;
1767 va_start(args, pat);
1768 vwarner(err, pat, &args);
1773 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1776 PERL_ARGS_ASSERT_VWARNER;
1777 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1778 SV * const msv = vmess(pat, args);
1780 invoke_exception_hook(msv, FALSE);
1784 Perl_vwarn(aTHX_ pat, args);
1788 /* implements the ckWARN? macros */
1791 Perl_ckwarn(pTHX_ U32 w)
1794 /* If lexical warnings have not been set, use $^W. */
1796 return PL_dowarn & G_WARN_ON;
1798 return ckwarn_common(w);
1801 /* implements the ckWARN?_d macro */
1804 Perl_ckwarn_d(pTHX_ U32 w)
1807 /* If lexical warnings have not been set then default classes warn. */
1811 return ckwarn_common(w);
1815 S_ckwarn_common(pTHX_ U32 w)
1817 if (PL_curcop->cop_warnings == pWARN_ALL)
1820 if (PL_curcop->cop_warnings == pWARN_NONE)
1823 /* Check the assumption that at least the first slot is non-zero. */
1824 assert(unpackWARN1(w));
1826 /* Check the assumption that it is valid to stop as soon as a zero slot is
1828 if (!unpackWARN2(w)) {
1829 assert(!unpackWARN3(w));
1830 assert(!unpackWARN4(w));
1831 } else if (!unpackWARN3(w)) {
1832 assert(!unpackWARN4(w));
1835 /* Right, dealt with all the special cases, which are implemented as non-
1836 pointers, so there is a pointer to a real warnings mask. */
1838 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1840 } while (w >>= WARNshift);
1845 /* Set buffer=NULL to get a new one. */
1847 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1849 const MEM_SIZE len_wanted =
1850 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
1851 PERL_UNUSED_CONTEXT;
1852 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1855 (specialWARN(buffer) ?
1856 PerlMemShared_malloc(len_wanted) :
1857 PerlMemShared_realloc(buffer, len_wanted));
1859 Copy(bits, (buffer + 1), size, char);
1860 if (size < WARNsize)
1861 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
1865 /* since we've already done strlen() for both nam and val
1866 * we can use that info to make things faster than
1867 * sprintf(s, "%s=%s", nam, val)
1869 #define my_setenv_format(s, nam, nlen, val, vlen) \
1870 Copy(nam, s, nlen, char); \
1872 Copy(val, s+(nlen+1), vlen, char); \
1873 *(s+(nlen+1+vlen)) = '\0'
1875 #ifdef USE_ENVIRON_ARRAY
1876 /* VMS' my_setenv() is in vms.c */
1877 #if !defined(WIN32) && !defined(NETWARE)
1879 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1883 /* only parent thread can modify process environment */
1884 if (PL_curinterp == aTHX)
1887 #ifndef PERL_USE_SAFE_PUTENV
1888 if (!PL_use_safe_putenv) {
1889 /* most putenv()s leak, so we manipulate environ directly */
1891 const I32 len = strlen(nam);
1894 /* where does it go? */
1895 for (i = 0; environ[i]; i++) {
1896 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1900 if (environ == PL_origenviron) { /* need we copy environment? */
1906 while (environ[max])
1908 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1909 for (j=0; j<max; j++) { /* copy environment */
1910 const int len = strlen(environ[j]);
1911 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1912 Copy(environ[j], tmpenv[j], len+1, char);
1915 environ = tmpenv; /* tell exec where it is now */
1918 safesysfree(environ[i]);
1919 while (environ[i]) {
1920 environ[i] = environ[i+1];
1925 if (!environ[i]) { /* does not exist yet */
1926 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1927 environ[i+1] = NULL; /* make sure it's null terminated */
1930 safesysfree(environ[i]);
1934 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1935 /* all that work just for this */
1936 my_setenv_format(environ[i], nam, nlen, val, vlen);
1939 # if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__)
1940 # if defined(HAS_UNSETENV)
1942 (void)unsetenv(nam);
1944 (void)setenv(nam, val, 1);
1946 # else /* ! HAS_UNSETENV */
1947 (void)setenv(nam, val, 1);
1948 # endif /* HAS_UNSETENV */
1950 # if defined(HAS_UNSETENV)
1952 (void)unsetenv(nam);
1954 const int nlen = strlen(nam);
1955 const int vlen = strlen(val);
1956 char * const new_env =
1957 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1958 my_setenv_format(new_env, nam, nlen, val, vlen);
1959 (void)putenv(new_env);
1961 # else /* ! HAS_UNSETENV */
1963 const int nlen = strlen(nam);
1969 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1970 /* all that work just for this */
1971 my_setenv_format(new_env, nam, nlen, val, vlen);
1972 (void)putenv(new_env);
1973 # endif /* HAS_UNSETENV */
1974 # endif /* __CYGWIN__ */
1975 #ifndef PERL_USE_SAFE_PUTENV
1981 #else /* WIN32 || NETWARE */
1984 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1988 const int nlen = strlen(nam);
1995 Newx(envstr, nlen+vlen+2, char);
1996 my_setenv_format(envstr, nam, nlen, val, vlen);
1997 (void)PerlEnv_putenv(envstr);
2001 #endif /* WIN32 || NETWARE */
2005 #ifdef UNLINK_ALL_VERSIONS
2007 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2011 PERL_ARGS_ASSERT_UNLNK;
2013 while (PerlLIO_unlink(f) >= 0)
2015 return retries ? 0 : -1;
2019 /* this is a drop-in replacement for bcopy() */
2020 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2022 Perl_my_bcopy(const char *from, char *to, I32 len)
2024 char * const retval = to;
2026 PERL_ARGS_ASSERT_MY_BCOPY;
2030 if (from - to >= 0) {
2038 *(--to) = *(--from);
2044 /* this is a drop-in replacement for memset() */
2047 Perl_my_memset(char *loc, I32 ch, I32 len)
2049 char * const retval = loc;
2051 PERL_ARGS_ASSERT_MY_MEMSET;
2061 /* this is a drop-in replacement for bzero() */
2062 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2064 Perl_my_bzero(char *loc, I32 len)
2066 char * const retval = loc;
2068 PERL_ARGS_ASSERT_MY_BZERO;
2078 /* this is a drop-in replacement for memcmp() */
2079 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2081 Perl_my_memcmp(const char *s1, const char *s2, I32 len)
2083 const U8 *a = (const U8 *)s1;
2084 const U8 *b = (const U8 *)s2;
2087 PERL_ARGS_ASSERT_MY_MEMCMP;
2092 if ((tmp = *a++ - *b++))
2097 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2100 /* This vsprintf replacement should generally never get used, since
2101 vsprintf was available in both System V and BSD 2.11. (There may
2102 be some cross-compilation or embedded set-ups where it is needed,
2105 If you encounter a problem in this function, it's probably a symptom
2106 that Configure failed to detect your system's vprintf() function.
2107 See the section on "item vsprintf" in the INSTALL file.
2109 This version may compile on systems with BSD-ish <stdio.h>,
2110 but probably won't on others.
2113 #ifdef USE_CHAR_VSPRINTF
2118 vsprintf(char *dest, const char *pat, void *args)
2122 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2123 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2124 FILE_cnt(&fakebuf) = 32767;
2126 /* These probably won't compile -- If you really need
2127 this, you'll have to figure out some other method. */
2128 fakebuf._ptr = dest;
2129 fakebuf._cnt = 32767;
2134 fakebuf._flag = _IOWRT|_IOSTRG;
2135 _doprnt(pat, args, &fakebuf); /* what a kludge */
2136 #if defined(STDIO_PTR_LVALUE)
2137 *(FILE_ptr(&fakebuf)++) = '\0';
2139 /* PerlIO has probably #defined away fputc, but we want it here. */
2141 # undef fputc /* XXX Should really restore it later */
2143 (void)fputc('\0', &fakebuf);
2145 #ifdef USE_CHAR_VSPRINTF
2148 return 0; /* perl doesn't use return value */
2152 #endif /* HAS_VPRINTF */
2155 #if BYTEORDER != 0x4321
2157 Perl_my_swap(pTHX_ short s)
2159 #if (BYTEORDER & 1) == 0
2162 result = ((s & 255) << 8) + ((s >> 8) & 255);
2170 Perl_my_htonl(pTHX_ long l)
2174 char c[sizeof(long)];
2177 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2178 #if BYTEORDER == 0x12345678
2181 u.c[0] = (l >> 24) & 255;
2182 u.c[1] = (l >> 16) & 255;
2183 u.c[2] = (l >> 8) & 255;
2187 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2188 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2193 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2194 u.c[o & 0xf] = (l >> s) & 255;
2202 Perl_my_ntohl(pTHX_ long l)
2206 char c[sizeof(long)];
2209 #if BYTEORDER == 0x1234
2210 u.c[0] = (l >> 24) & 255;
2211 u.c[1] = (l >> 16) & 255;
2212 u.c[2] = (l >> 8) & 255;
2216 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2217 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2224 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2225 l |= (u.c[o & 0xf] & 255) << s;
2232 #endif /* BYTEORDER != 0x4321 */
2236 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2237 * If these functions are defined,
2238 * the BYTEORDER is neither 0x1234 nor 0x4321.
2239 * However, this is not assumed.
2243 #define HTOLE(name,type) \
2249 char c[sizeof(type)]; \
2253 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2254 u.c[i] = (n >> s) & 0xFF; \
2259 #define LETOH(name,type) \
2265 char c[sizeof(type)]; \
2271 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2272 n |= ((type)(u.c[i] & 0xFF)) << s; \
2278 * Big-endian byte order functions.
2281 #define HTOBE(name,type) \
2287 char c[sizeof(type)]; \
2290 U32 s = 8*(sizeof(u.c)-1); \
2291 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2292 u.c[i] = (n >> s) & 0xFF; \
2297 #define BETOH(name,type) \
2303 char c[sizeof(type)]; \
2306 U32 s = 8*(sizeof(u.c)-1); \
2309 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2310 n |= ((type)(u.c[i] & 0xFF)) << s; \
2316 * If we just can't do it...
2319 #define NOT_AVAIL(name,type) \
2323 Perl_croak_nocontext(#name "() not available"); \
2324 return n; /* not reached */ \
2328 #if defined(HAS_HTOVS) && !defined(htovs)
2331 #if defined(HAS_HTOVL) && !defined(htovl)
2334 #if defined(HAS_VTOHS) && !defined(vtohs)
2337 #if defined(HAS_VTOHL) && !defined(vtohl)
2341 #ifdef PERL_NEED_MY_HTOLE16
2343 HTOLE(Perl_my_htole16,U16)
2345 NOT_AVAIL(Perl_my_htole16,U16)
2348 #ifdef PERL_NEED_MY_LETOH16
2350 LETOH(Perl_my_letoh16,U16)
2352 NOT_AVAIL(Perl_my_letoh16,U16)
2355 #ifdef PERL_NEED_MY_HTOBE16
2357 HTOBE(Perl_my_htobe16,U16)
2359 NOT_AVAIL(Perl_my_htobe16,U16)
2362 #ifdef PERL_NEED_MY_BETOH16
2364 BETOH(Perl_my_betoh16,U16)
2366 NOT_AVAIL(Perl_my_betoh16,U16)
2370 #ifdef PERL_NEED_MY_HTOLE32
2372 HTOLE(Perl_my_htole32,U32)
2374 NOT_AVAIL(Perl_my_htole32,U32)
2377 #ifdef PERL_NEED_MY_LETOH32
2379 LETOH(Perl_my_letoh32,U32)
2381 NOT_AVAIL(Perl_my_letoh32,U32)
2384 #ifdef PERL_NEED_MY_HTOBE32
2386 HTOBE(Perl_my_htobe32,U32)
2388 NOT_AVAIL(Perl_my_htobe32,U32)
2391 #ifdef PERL_NEED_MY_BETOH32
2393 BETOH(Perl_my_betoh32,U32)
2395 NOT_AVAIL(Perl_my_betoh32,U32)
2399 #ifdef PERL_NEED_MY_HTOLE64
2401 HTOLE(Perl_my_htole64,U64)
2403 NOT_AVAIL(Perl_my_htole64,U64)
2406 #ifdef PERL_NEED_MY_LETOH64
2408 LETOH(Perl_my_letoh64,U64)
2410 NOT_AVAIL(Perl_my_letoh64,U64)
2413 #ifdef PERL_NEED_MY_HTOBE64
2415 HTOBE(Perl_my_htobe64,U64)
2417 NOT_AVAIL(Perl_my_htobe64,U64)
2420 #ifdef PERL_NEED_MY_BETOH64
2422 BETOH(Perl_my_betoh64,U64)
2424 NOT_AVAIL(Perl_my_betoh64,U64)
2428 #ifdef PERL_NEED_MY_HTOLES
2429 HTOLE(Perl_my_htoles,short)
2431 #ifdef PERL_NEED_MY_LETOHS
2432 LETOH(Perl_my_letohs,short)
2434 #ifdef PERL_NEED_MY_HTOBES
2435 HTOBE(Perl_my_htobes,short)
2437 #ifdef PERL_NEED_MY_BETOHS
2438 BETOH(Perl_my_betohs,short)
2441 #ifdef PERL_NEED_MY_HTOLEI
2442 HTOLE(Perl_my_htolei,int)
2444 #ifdef PERL_NEED_MY_LETOHI
2445 LETOH(Perl_my_letohi,int)
2447 #ifdef PERL_NEED_MY_HTOBEI
2448 HTOBE(Perl_my_htobei,int)
2450 #ifdef PERL_NEED_MY_BETOHI
2451 BETOH(Perl_my_betohi,int)
2454 #ifdef PERL_NEED_MY_HTOLEL
2455 HTOLE(Perl_my_htolel,long)
2457 #ifdef PERL_NEED_MY_LETOHL
2458 LETOH(Perl_my_letohl,long)
2460 #ifdef PERL_NEED_MY_HTOBEL
2461 HTOBE(Perl_my_htobel,long)
2463 #ifdef PERL_NEED_MY_BETOHL
2464 BETOH(Perl_my_betohl,long)
2468 Perl_my_swabn(void *ptr, int n)
2470 char *s = (char *)ptr;
2471 char *e = s + (n-1);
2474 PERL_ARGS_ASSERT_MY_SWABN;
2476 for (n /= 2; n > 0; s++, e--, n--) {
2484 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2486 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2495 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2497 PERL_FLUSHALL_FOR_CHILD;
2498 This = (*mode == 'w');
2502 taint_proper("Insecure %s%s", "EXEC");
2504 if (PerlProc_pipe(p) < 0)
2506 /* Try for another pipe pair for error return */
2507 if (PerlProc_pipe(pp) >= 0)
2509 while ((pid = PerlProc_fork()) < 0) {
2510 if (errno != EAGAIN) {
2511 PerlLIO_close(p[This]);
2512 PerlLIO_close(p[that]);
2514 PerlLIO_close(pp[0]);
2515 PerlLIO_close(pp[1]);
2519 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2528 /* Close parent's end of error status pipe (if any) */
2530 PerlLIO_close(pp[0]);
2531 #if defined(HAS_FCNTL) && defined(F_SETFD)
2532 /* Close error pipe automatically if exec works */
2533 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2536 /* Now dup our end of _the_ pipe to right position */
2537 if (p[THIS] != (*mode == 'r')) {
2538 PerlLIO_dup2(p[THIS], *mode == 'r');
2539 PerlLIO_close(p[THIS]);
2540 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2541 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2544 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2545 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2546 /* No automatic close - do it by hand */
2553 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2559 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2565 do_execfree(); /* free any memory malloced by child on fork */
2567 PerlLIO_close(pp[1]);
2568 /* Keep the lower of the two fd numbers */
2569 if (p[that] < p[This]) {
2570 PerlLIO_dup2(p[This], p[that]);
2571 PerlLIO_close(p[This]);
2575 PerlLIO_close(p[that]); /* close child's end of pipe */
2577 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2578 SvUPGRADE(sv,SVt_IV);
2580 PL_forkprocess = pid;
2581 /* If we managed to get status pipe check for exec fail */
2582 if (did_pipes && pid > 0) {
2587 while (n < sizeof(int)) {
2588 n1 = PerlLIO_read(pp[0],
2589 (void*)(((char*)&errkid)+n),
2595 PerlLIO_close(pp[0]);
2597 if (n) { /* Error */
2599 PerlLIO_close(p[This]);
2600 if (n != sizeof(int))
2601 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2603 pid2 = wait4pid(pid, &status, 0);
2604 } while (pid2 == -1 && errno == EINTR);
2605 errno = errkid; /* Propagate errno from kid */
2610 PerlLIO_close(pp[0]);
2611 return PerlIO_fdopen(p[This], mode);
2613 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2614 return my_syspopen4(aTHX_ NULL, mode, n, args);
2616 Perl_croak(aTHX_ "List form of piped open not implemented");
2617 return (PerlIO *) NULL;
2622 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2623 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2625 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2632 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2636 PERL_ARGS_ASSERT_MY_POPEN;
2638 PERL_FLUSHALL_FOR_CHILD;
2641 return my_syspopen(aTHX_ cmd,mode);
2644 This = (*mode == 'w');
2646 if (doexec && TAINTING_get) {
2648 taint_proper("Insecure %s%s", "EXEC");
2650 if (PerlProc_pipe(p) < 0)
2652 if (doexec && PerlProc_pipe(pp) >= 0)
2654 while ((pid = PerlProc_fork()) < 0) {
2655 if (errno != EAGAIN) {
2656 PerlLIO_close(p[This]);
2657 PerlLIO_close(p[that]);
2659 PerlLIO_close(pp[0]);
2660 PerlLIO_close(pp[1]);
2663 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2666 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2676 PerlLIO_close(pp[0]);
2677 #if defined(HAS_FCNTL) && defined(F_SETFD)
2678 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2681 if (p[THIS] != (*mode == 'r')) {
2682 PerlLIO_dup2(p[THIS], *mode == 'r');
2683 PerlLIO_close(p[THIS]);
2684 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2685 PerlLIO_close(p[THAT]);
2688 PerlLIO_close(p[THAT]);
2691 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2698 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2703 /* may or may not use the shell */
2704 do_exec3(cmd, pp[1], did_pipes);
2707 #endif /* defined OS2 */
2709 #ifdef PERLIO_USING_CRLF
2710 /* Since we circumvent IO layers when we manipulate low-level
2711 filedescriptors directly, need to manually switch to the
2712 default, binary, low-level mode; see PerlIOBuf_open(). */
2713 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2716 #ifdef PERL_USES_PL_PIDSTATUS
2717 hv_clear(PL_pidstatus); /* we have no children */
2723 do_execfree(); /* free any memory malloced by child on vfork */
2725 PerlLIO_close(pp[1]);
2726 if (p[that] < p[This]) {
2727 PerlLIO_dup2(p[This], p[that]);
2728 PerlLIO_close(p[This]);
2732 PerlLIO_close(p[that]);
2734 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2735 SvUPGRADE(sv,SVt_IV);
2737 PL_forkprocess = pid;
2738 if (did_pipes && pid > 0) {
2743 while (n < sizeof(int)) {
2744 n1 = PerlLIO_read(pp[0],
2745 (void*)(((char*)&errkid)+n),
2751 PerlLIO_close(pp[0]);
2753 if (n) { /* Error */
2755 PerlLIO_close(p[This]);
2756 if (n != sizeof(int))
2757 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2759 pid2 = wait4pid(pid, &status, 0);
2760 } while (pid2 == -1 && errno == EINTR);
2761 errno = errkid; /* Propagate errno from kid */
2766 PerlLIO_close(pp[0]);
2767 return PerlIO_fdopen(p[This], mode);
2771 FILE *djgpp_popen();
2773 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2775 PERL_FLUSHALL_FOR_CHILD;
2776 /* Call system's popen() to get a FILE *, then import it.
2777 used 0 for 2nd parameter to PerlIO_importFILE;
2780 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2783 #if defined(__LIBCATAMOUNT__)
2785 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2792 #endif /* !DOSISH */
2794 /* this is called in parent before the fork() */
2796 Perl_atfork_lock(void)
2799 #if defined(USE_ITHREADS)
2800 /* locks must be held in locking order (if any) */
2802 MUTEX_LOCK(&PL_malloc_mutex);
2808 /* this is called in both parent and child after the fork() */
2810 Perl_atfork_unlock(void)
2813 #if defined(USE_ITHREADS)
2814 /* locks must be released in same order as in atfork_lock() */
2816 MUTEX_UNLOCK(&PL_malloc_mutex);
2825 #if defined(HAS_FORK)
2827 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2832 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2833 * handlers elsewhere in the code */
2838 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2839 Perl_croak_nocontext("fork() not available");
2841 #endif /* HAS_FORK */
2846 Perl_dump_fds(pTHX_ const char *const s)
2851 PERL_ARGS_ASSERT_DUMP_FDS;
2853 PerlIO_printf(Perl_debug_log,"%s", s);
2854 for (fd = 0; fd < 32; fd++) {
2855 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2856 PerlIO_printf(Perl_debug_log," %d",fd);
2858 PerlIO_printf(Perl_debug_log,"\n");
2861 #endif /* DUMP_FDS */
2865 dup2(int oldfd, int newfd)
2867 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2870 PerlLIO_close(newfd);
2871 return fcntl(oldfd, F_DUPFD, newfd);
2873 #define DUP2_MAX_FDS 256
2874 int fdtmp[DUP2_MAX_FDS];
2880 PerlLIO_close(newfd);
2881 /* good enough for low fd's... */
2882 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2883 if (fdx >= DUP2_MAX_FDS) {
2891 PerlLIO_close(fdtmp[--fdx]);
2898 #ifdef HAS_SIGACTION
2901 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2904 struct sigaction act, oact;
2907 /* only "parent" interpreter can diddle signals */
2908 if (PL_curinterp != aTHX)
2909 return (Sighandler_t) SIG_ERR;
2912 act.sa_handler = (void(*)(int))handler;
2913 sigemptyset(&act.sa_mask);
2916 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2917 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2919 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2920 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2921 act.sa_flags |= SA_NOCLDWAIT;
2923 if (sigaction(signo, &act, &oact) == -1)
2924 return (Sighandler_t) SIG_ERR;
2926 return (Sighandler_t) oact.sa_handler;
2930 Perl_rsignal_state(pTHX_ int signo)
2932 struct sigaction oact;
2933 PERL_UNUSED_CONTEXT;
2935 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2936 return (Sighandler_t) SIG_ERR;
2938 return (Sighandler_t) oact.sa_handler;
2942 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2945 struct sigaction act;
2947 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2950 /* only "parent" interpreter can diddle signals */
2951 if (PL_curinterp != aTHX)
2955 act.sa_handler = (void(*)(int))handler;
2956 sigemptyset(&act.sa_mask);
2959 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2960 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2962 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2963 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2964 act.sa_flags |= SA_NOCLDWAIT;
2966 return sigaction(signo, &act, save);
2970 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2974 /* only "parent" interpreter can diddle signals */
2975 if (PL_curinterp != aTHX)
2979 return sigaction(signo, save, (struct sigaction *)NULL);
2982 #else /* !HAS_SIGACTION */
2985 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2987 #if defined(USE_ITHREADS) && !defined(WIN32)
2988 /* only "parent" interpreter can diddle signals */
2989 if (PL_curinterp != aTHX)
2990 return (Sighandler_t) SIG_ERR;
2993 return PerlProc_signal(signo, handler);
3004 Perl_rsignal_state(pTHX_ int signo)
3007 Sighandler_t oldsig;
3009 #if defined(USE_ITHREADS) && !defined(WIN32)
3010 /* only "parent" interpreter can diddle signals */
3011 if (PL_curinterp != aTHX)
3012 return (Sighandler_t) SIG_ERR;
3016 oldsig = PerlProc_signal(signo, sig_trap);
3017 PerlProc_signal(signo, oldsig);
3019 PerlProc_kill(PerlProc_getpid(), signo);
3024 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3026 #if defined(USE_ITHREADS) && !defined(WIN32)
3027 /* only "parent" interpreter can diddle signals */
3028 if (PL_curinterp != aTHX)
3031 *save = PerlProc_signal(signo, handler);
3032 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3036 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3038 #if defined(USE_ITHREADS) && !defined(WIN32)
3039 /* only "parent" interpreter can diddle signals */
3040 if (PL_curinterp != aTHX)
3043 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3046 #endif /* !HAS_SIGACTION */
3047 #endif /* !PERL_MICRO */
3049 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3050 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
3052 Perl_my_pclose(pTHX_ PerlIO *ptr)
3055 Sigsave_t hstat, istat, qstat;
3062 const int fd = PerlIO_fileno(ptr);
3065 /* Find out whether the refcount is low enough for us to wait for the
3066 child proc without blocking. */
3067 const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
3069 const bool should_wait = 1;
3072 svp = av_fetch(PL_fdpid,fd,TRUE);
3073 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3075 *svp = &PL_sv_undef;
3077 if (pid == -1) { /* Opened by popen. */
3078 return my_syspclose(ptr);
3081 close_failed = (PerlIO_close(ptr) == EOF);
3084 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3085 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3086 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3088 if (should_wait) do {
3089 pid2 = wait4pid(pid, &status, 0);
3090 } while (pid2 == -1 && errno == EINTR);
3092 rsignal_restore(SIGHUP, &hstat);
3093 rsignal_restore(SIGINT, &istat);
3094 rsignal_restore(SIGQUIT, &qstat);
3102 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3107 #if defined(__LIBCATAMOUNT__)
3109 Perl_my_pclose(pTHX_ PerlIO *ptr)
3114 #endif /* !DOSISH */
3116 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3118 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3122 PERL_ARGS_ASSERT_WAIT4PID;
3125 #ifdef PERL_USES_PL_PIDSTATUS
3128 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3129 pid, rather than a string form. */
3130 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3131 if (svp && *svp != &PL_sv_undef) {
3132 *statusp = SvIVX(*svp);
3133 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3141 hv_iterinit(PL_pidstatus);
3142 if ((entry = hv_iternext(PL_pidstatus))) {
3143 SV * const sv = hv_iterval(PL_pidstatus,entry);
3145 const char * const spid = hv_iterkey(entry,&len);
3147 assert (len == sizeof(Pid_t));
3148 memcpy((char *)&pid, spid, len);
3149 *statusp = SvIVX(sv);
3150 /* The hash iterator is currently on this entry, so simply
3151 calling hv_delete would trigger the lazy delete, which on
3152 aggregate does more work, beacuse next call to hv_iterinit()
3153 would spot the flag, and have to call the delete routine,
3154 while in the meantime any new entries can't re-use that
3156 hv_iterinit(PL_pidstatus);
3157 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3164 # ifdef HAS_WAITPID_RUNTIME
3165 if (!HAS_WAITPID_RUNTIME)
3168 result = PerlProc_waitpid(pid,statusp,flags);
3171 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3172 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3175 #ifdef PERL_USES_PL_PIDSTATUS
3176 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3181 Perl_croak(aTHX_ "Can't do waitpid with flags");
3183 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3184 pidgone(result,*statusp);
3190 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3193 if (result < 0 && errno == EINTR) {
3195 errno = EINTR; /* reset in case a signal handler changed $! */
3199 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3201 #ifdef PERL_USES_PL_PIDSTATUS
3203 S_pidgone(pTHX_ Pid_t pid, int status)
3207 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3208 SvUPGRADE(sv,SVt_IV);
3209 SvIV_set(sv, status);
3217 int /* Cannot prototype with I32
3219 my_syspclose(PerlIO *ptr)
3222 Perl_my_pclose(pTHX_ PerlIO *ptr)
3225 /* Needs work for PerlIO ! */
3226 FILE * const f = PerlIO_findFILE(ptr);
3227 const I32 result = pclose(f);
3228 PerlIO_releaseFILE(ptr,f);
3236 Perl_my_pclose(pTHX_ PerlIO *ptr)
3238 /* Needs work for PerlIO ! */
3239 FILE * const f = PerlIO_findFILE(ptr);
3240 I32 result = djgpp_pclose(f);
3241 result = (result << 8) & 0xff00;
3242 PerlIO_releaseFILE(ptr,f);
3247 #define PERL_REPEATCPY_LINEAR 4
3249 Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
3251 PERL_ARGS_ASSERT_REPEATCPY;
3256 croak_memory_wrap();
3259 memset(to, *from, count);
3262 IV items, linear, half;
3264 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3265 for (items = 0; items < linear; ++items) {
3266 const char *q = from;
3268 for (todo = len; todo > 0; todo--)
3273 while (items <= half) {
3274 IV size = items * len;
3275 memcpy(p, to, size);
3281 memcpy(p, to, (count - items) * len);
3287 Perl_same_dirent(pTHX_ const char *a, const char *b)
3289 char *fa = strrchr(a,'/');
3290 char *fb = strrchr(b,'/');
3293 SV * const tmpsv = sv_newmortal();
3295 PERL_ARGS_ASSERT_SAME_DIRENT;
3308 sv_setpvs(tmpsv, ".");
3310 sv_setpvn(tmpsv, a, fa - a);
3311 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3314 sv_setpvs(tmpsv, ".");
3316 sv_setpvn(tmpsv, b, fb - b);
3317 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3319 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3320 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3322 #endif /* !HAS_RENAME */
3325 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3326 const char *const *const search_ext, I32 flags)
3329 const char *xfound = NULL;
3330 char *xfailed = NULL;
3331 char tmpbuf[MAXPATHLEN];
3336 #if defined(DOSISH) && !defined(OS2)
3337 # define SEARCH_EXTS ".bat", ".cmd", NULL
3338 # define MAX_EXT_LEN 4
3341 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3342 # define MAX_EXT_LEN 4
3345 # define SEARCH_EXTS ".pl", ".com", NULL
3346 # define MAX_EXT_LEN 4
3348 /* additional extensions to try in each dir if scriptname not found */
3350 static const char *const exts[] = { SEARCH_EXTS };
3351 const char *const *const ext = search_ext ? search_ext : exts;
3352 int extidx = 0, i = 0;
3353 const char *curext = NULL;
3355 PERL_UNUSED_ARG(search_ext);
3356 # define MAX_EXT_LEN 0
3359 PERL_ARGS_ASSERT_FIND_SCRIPT;
3362 * If dosearch is true and if scriptname does not contain path
3363 * delimiters, search the PATH for scriptname.
3365 * If SEARCH_EXTS is also defined, will look for each
3366 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3367 * while searching the PATH.
3369 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3370 * proceeds as follows:
3371 * If DOSISH or VMSISH:
3372 * + look for ./scriptname{,.foo,.bar}
3373 * + search the PATH for scriptname{,.foo,.bar}
3376 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3377 * this will not look in '.' if it's not in the PATH)
3382 # ifdef ALWAYS_DEFTYPES
3383 len = strlen(scriptname);
3384 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3385 int idx = 0, deftypes = 1;
3388 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3391 int idx = 0, deftypes = 1;
3394 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3396 /* The first time through, just add SEARCH_EXTS to whatever we
3397 * already have, so we can check for default file types. */
3399 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3405 if ((strlen(tmpbuf) + strlen(scriptname)
3406 + MAX_EXT_LEN) >= sizeof tmpbuf)
3407 continue; /* don't search dir with too-long name */
3408 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3412 if (strEQ(scriptname, "-"))
3414 if (dosearch) { /* Look in '.' first. */
3415 const char *cur = scriptname;
3417 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3419 if (strEQ(ext[i++],curext)) {
3420 extidx = -1; /* already has an ext */
3425 DEBUG_p(PerlIO_printf(Perl_debug_log,
3426 "Looking for %s\n",cur));
3427 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3428 && !S_ISDIR(PL_statbuf.st_mode)) {
3436 if (cur == scriptname) {
3437 len = strlen(scriptname);
3438 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3440 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3443 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3444 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3449 if (dosearch && !strchr(scriptname, '/')
3451 && !strchr(scriptname, '\\')
3453 && (s = PerlEnv_getenv("PATH")))
3457 bufend = s + strlen(s);
3458 while (s < bufend) {
3461 && *s != ';'; len++, s++) {
3462 if (len < sizeof tmpbuf)
3465 if (len < sizeof tmpbuf)
3468 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3474 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3475 continue; /* don't search dir with too-long name */
3478 && tmpbuf[len - 1] != '/'
3479 && tmpbuf[len - 1] != '\\'
3482 tmpbuf[len++] = '/';
3483 if (len == 2 && tmpbuf[0] == '.')
3485 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3489 len = strlen(tmpbuf);
3490 if (extidx > 0) /* reset after previous loop */
3494 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3495 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3496 if (S_ISDIR(PL_statbuf.st_mode)) {
3500 } while ( retval < 0 /* not there */
3501 && extidx>=0 && ext[extidx] /* try an extension? */
3502 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3507 if (S_ISREG(PL_statbuf.st_mode)
3508 && cando(S_IRUSR,TRUE,&PL_statbuf)
3509 #if !defined(DOSISH)
3510 && cando(S_IXUSR,TRUE,&PL_statbuf)
3514 xfound = tmpbuf; /* bingo! */
3518 xfailed = savepv(tmpbuf);
3521 if (!xfound && !seen_dot && !xfailed &&
3522 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3523 || S_ISDIR(PL_statbuf.st_mode)))
3525 seen_dot = 1; /* Disable message. */
3527 if (flags & 1) { /* do or die? */
3528 /* diag_listed_as: Can't execute %s */
3529 Perl_croak(aTHX_ "Can't %s %s%s%s",
3530 (xfailed ? "execute" : "find"),
3531 (xfailed ? xfailed : scriptname),
3532 (xfailed ? "" : " on PATH"),
3533 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3538 scriptname = xfound;
3540 return (scriptname ? savepv(scriptname) : NULL);
3543 #ifndef PERL_GET_CONTEXT_DEFINED
3546 Perl_get_context(void)
3549 #if defined(USE_ITHREADS)
3550 # ifdef OLD_PTHREADS_API
3552 int error = pthread_getspecific(PL_thr_key, &t)
3554 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3557 # ifdef I_MACH_CTHREADS
3558 return (void*)cthread_data(cthread_self());
3560 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3569 Perl_set_context(void *t)
3572 PERL_ARGS_ASSERT_SET_CONTEXT;
3573 #if defined(USE_ITHREADS)
3574 # ifdef I_MACH_CTHREADS
3575 cthread_set_data(cthread_self(), t);
3578 const int error = pthread_setspecific(PL_thr_key, t);
3580 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3588 #endif /* !PERL_GET_CONTEXT_DEFINED */
3590 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3599 Perl_get_op_names(pTHX)
3601 PERL_UNUSED_CONTEXT;
3602 return (char **)PL_op_name;
3606 Perl_get_op_descs(pTHX)
3608 PERL_UNUSED_CONTEXT;
3609 return (char **)PL_op_desc;
3613 Perl_get_no_modify(pTHX)
3615 PERL_UNUSED_CONTEXT;
3616 return PL_no_modify;
3620 Perl_get_opargs(pTHX)
3622 PERL_UNUSED_CONTEXT;
3623 return (U32 *)PL_opargs;
3627 Perl_get_ppaddr(pTHX)
3630 PERL_UNUSED_CONTEXT;
3631 return (PPADDR_t*)PL_ppaddr;
3634 #ifndef HAS_GETENV_LEN
3636 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3638 char * const env_trans = PerlEnv_getenv(env_elem);
3639 PERL_UNUSED_CONTEXT;
3640 PERL_ARGS_ASSERT_GETENV_LEN;
3642 *len = strlen(env_trans);
3649 Perl_get_vtbl(pTHX_ int vtbl_id)
3651 PERL_UNUSED_CONTEXT;
3653 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3654 ? NULL : PL_magic_vtables + vtbl_id;
3658 Perl_my_fflush_all(pTHX)
3660 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3661 return PerlIO_flush(NULL);
3663 # if defined(HAS__FWALK)
3664 extern int fflush(FILE *);
3665 /* undocumented, unprototyped, but very useful BSDism */
3666 extern void _fwalk(int (*)(FILE *));
3670 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3672 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3673 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3675 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3676 open_max = sysconf(_SC_OPEN_MAX);
3679 open_max = FOPEN_MAX;
3682 open_max = OPEN_MAX;
3693 for (i = 0; i < open_max; i++)
3694 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3695 STDIO_STREAM_ARRAY[i]._file < open_max &&
3696 STDIO_STREAM_ARRAY[i]._flag)
3697 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3701 SETERRNO(EBADF,RMS_IFI);
3708 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3710 if (ckWARN(WARN_IO)) {
3712 = gv && (isGV_with_GP(gv))
3715 const char * const direction = have == '>' ? "out" : "in";
3717 if (name && HEK_LEN(name))
3718 Perl_warner(aTHX_ packWARN(WARN_IO),
3719 "Filehandle %"HEKf" opened only for %sput",
3722 Perl_warner(aTHX_ packWARN(WARN_IO),
3723 "Filehandle opened only for %sput", direction);
3728 Perl_report_evil_fh(pTHX_ const GV *gv)
3730 const IO *io = gv ? GvIO(gv) : NULL;
3731 const PERL_BITFIELD16 op = PL_op->op_type;
3735 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3737 warn_type = WARN_CLOSED;
3741 warn_type = WARN_UNOPENED;
3744 if (ckWARN(warn_type)) {
3746 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3747 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3748 const char * const pars =
3749 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3750 const char * const func =
3752 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3753 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3755 const char * const type =
3757 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3758 ? "socket" : "filehandle");
3759 const bool have_name = name && SvCUR(name);
3760 Perl_warner(aTHX_ packWARN(warn_type),
3761 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3762 have_name ? " " : "",
3763 SVfARG(have_name ? name : &PL_sv_no));
3764 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3766 aTHX_ packWARN(warn_type),
3767 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3768 func, pars, have_name ? " " : "",
3769 SVfARG(have_name ? name : &PL_sv_no)
3774 /* To workaround core dumps from the uninitialised tm_zone we get the
3775 * system to give us a reasonable struct to copy. This fix means that
3776 * strftime uses the tm_zone and tm_gmtoff values returned by
3777 * localtime(time()). That should give the desired result most of the
3778 * time. But probably not always!
3780 * This does not address tzname aspects of NETaa14816.
3785 # ifndef STRUCT_TM_HASZONE
3786 # define STRUCT_TM_HASZONE
3790 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3791 # ifndef HAS_TM_TM_ZONE
3792 # define HAS_TM_TM_ZONE
3797 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3799 #ifdef HAS_TM_TM_ZONE
3801 const struct tm* my_tm;
3802 PERL_ARGS_ASSERT_INIT_TM;
3804 my_tm = localtime(&now);
3806 Copy(my_tm, ptm, 1, struct tm);
3808 PERL_ARGS_ASSERT_INIT_TM;
3809 PERL_UNUSED_ARG(ptm);
3814 * mini_mktime - normalise struct tm values without the localtime()
3815 * semantics (and overhead) of mktime().
3818 Perl_mini_mktime(pTHX_ struct tm *ptm)
3822 int month, mday, year, jday;
3823 int odd_cent, odd_year;
3824 PERL_UNUSED_CONTEXT;
3826 PERL_ARGS_ASSERT_MINI_MKTIME;
3828 #define DAYS_PER_YEAR 365
3829 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3830 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3831 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3832 #define SECS_PER_HOUR (60*60)
3833 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3834 /* parentheses deliberately absent on these two, otherwise they don't work */
3835 #define MONTH_TO_DAYS 153/5
3836 #define DAYS_TO_MONTH 5/153
3837 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3838 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3839 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3840 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3843 * Year/day algorithm notes:
3845 * With a suitable offset for numeric value of the month, one can find
3846 * an offset into the year by considering months to have 30.6 (153/5) days,
3847 * using integer arithmetic (i.e., with truncation). To avoid too much
3848 * messing about with leap days, we consider January and February to be
3849 * the 13th and 14th month of the previous year. After that transformation,
3850 * we need the month index we use to be high by 1 from 'normal human' usage,
3851 * so the month index values we use run from 4 through 15.
3853 * Given that, and the rules for the Gregorian calendar (leap years are those
3854 * divisible by 4 unless also divisible by 100, when they must be divisible
3855 * by 400 instead), we can simply calculate the number of days since some
3856 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3857 * the days we derive from our month index, and adding in the day of the
3858 * month. The value used here is not adjusted for the actual origin which
3859 * it normally would use (1 January A.D. 1), since we're not exposing it.
3860 * We're only building the value so we can turn around and get the
3861 * normalised values for the year, month, day-of-month, and day-of-year.
3863 * For going backward, we need to bias the value we're using so that we find
3864 * the right year value. (Basically, we don't want the contribution of
3865 * March 1st to the number to apply while deriving the year). Having done
3866 * that, we 'count up' the contribution to the year number by accounting for
3867 * full quadracenturies (400-year periods) with their extra leap days, plus
3868 * the contribution from full centuries (to avoid counting in the lost leap
3869 * days), plus the contribution from full quad-years (to count in the normal
3870 * leap days), plus the leftover contribution from any non-leap years.
3871 * At this point, if we were working with an actual leap day, we'll have 0
3872 * days left over. This is also true for March 1st, however. So, we have
3873 * to special-case that result, and (earlier) keep track of the 'odd'
3874 * century and year contributions. If we got 4 extra centuries in a qcent,
3875 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3876 * Otherwise, we add back in the earlier bias we removed (the 123 from
3877 * figuring in March 1st), find the month index (integer division by 30.6),
3878 * and the remainder is the day-of-month. We then have to convert back to
3879 * 'real' months (including fixing January and February from being 14/15 in
3880 * the previous year to being in the proper year). After that, to get
3881 * tm_yday, we work with the normalised year and get a new yearday value for
3882 * January 1st, which we subtract from the yearday value we had earlier,
3883 * representing the date we've re-built. This is done from January 1
3884 * because tm_yday is 0-origin.
3886 * Since POSIX time routines are only guaranteed to work for times since the
3887 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3888 * applies Gregorian calendar rules even to dates before the 16th century
3889 * doesn't bother me. Besides, you'd need cultural context for a given
3890 * date to know whether it was Julian or Gregorian calendar, and that's
3891 * outside the scope for this routine. Since we convert back based on the
3892 * same rules we used to build the yearday, you'll only get strange results
3893 * for input which needed normalising, or for the 'odd' century years which
3894 * were leap years in the Julian calendar but not in the Gregorian one.
3895 * I can live with that.
3897 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3898 * that's still outside the scope for POSIX time manipulation, so I don't
3902 year = 1900 + ptm->tm_year;
3903 month = ptm->tm_mon;
3904 mday = ptm->tm_mday;
3910 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3911 yearday += month*MONTH_TO_DAYS + mday + jday;
3913 * Note that we don't know when leap-seconds were or will be,
3914 * so we have to trust the user if we get something which looks
3915 * like a sensible leap-second. Wild values for seconds will
3916 * be rationalised, however.
3918 if ((unsigned) ptm->tm_sec <= 60) {
3925 secs += 60 * ptm->tm_min;
3926 secs += SECS_PER_HOUR * ptm->tm_hour;
3928 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3929 /* got negative remainder, but need positive time */
3930 /* back off an extra day to compensate */
3931 yearday += (secs/SECS_PER_DAY)-1;
3932 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3935 yearday += (secs/SECS_PER_DAY);
3936 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3939 else if (secs >= SECS_PER_DAY) {
3940 yearday += (secs/SECS_PER_DAY);
3941 secs %= SECS_PER_DAY;
3943 ptm->tm_hour = secs/SECS_PER_HOUR;
3944 secs %= SECS_PER_HOUR;
3945 ptm->tm_min = secs/60;
3947 ptm->tm_sec += secs;
3948 /* done with time of day effects */
3950 * The algorithm for yearday has (so far) left it high by 428.
3951 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3952 * bias it by 123 while trying to figure out what year it
3953 * really represents. Even with this tweak, the reverse
3954 * translation fails for years before A.D. 0001.
3955 * It would still fail for Feb 29, but we catch that one below.
3957 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3958 yearday -= YEAR_ADJUST;
3959 year = (yearday / DAYS_PER_QCENT) * 400;
3960 yearday %= DAYS_PER_QCENT;
3961 odd_cent = yearday / DAYS_PER_CENT;
3962 year += odd_cent * 100;
3963 yearday %= DAYS_PER_CENT;
3964 year += (yearday / DAYS_PER_QYEAR) * 4;
3965 yearday %= DAYS_PER_QYEAR;
3966 odd_year = yearday / DAYS_PER_YEAR;
3968 yearday %= DAYS_PER_YEAR;
3969 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3974 yearday += YEAR_ADJUST; /* recover March 1st crock */
3975 month = yearday*DAYS_TO_MONTH;
3976 yearday -= month*MONTH_TO_DAYS;
3977 /* recover other leap-year adjustment */
3986 ptm->tm_year = year - 1900;
3988 ptm->tm_mday = yearday;
3989 ptm->tm_mon = month;
3993 ptm->tm_mon = month - 1;
3995 /* re-build yearday based on Jan 1 to get tm_yday */
3997 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3998 yearday += 14*MONTH_TO_DAYS + 1;
3999 ptm->tm_yday = jday - yearday;
4000 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4004 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)
4012 PERL_ARGS_ASSERT_MY_STRFTIME;
4014 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4017 mytm.tm_hour = hour;
4018 mytm.tm_mday = mday;
4020 mytm.tm_year = year;
4021 mytm.tm_wday = wday;
4022 mytm.tm_yday = yday;
4023 mytm.tm_isdst = isdst;
4025 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4026 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4031 #ifdef HAS_TM_TM_GMTOFF
4032 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4034 #ifdef HAS_TM_TM_ZONE
4035 mytm.tm_zone = mytm2.tm_zone;
4040 Newx(buf, buflen, char);
4041 len = strftime(buf, buflen, fmt, &mytm);
4043 ** The following is needed to handle to the situation where
4044 ** tmpbuf overflows. Basically we want to allocate a buffer
4045 ** and try repeatedly. The reason why it is so complicated
4046 ** is that getting a return value of 0 from strftime can indicate
4047 ** one of the following:
4048 ** 1. buffer overflowed,
4049 ** 2. illegal conversion specifier, or
4050 ** 3. the format string specifies nothing to be returned(not
4051 ** an error). This could be because format is an empty string
4052 ** or it specifies %p that yields an empty string in some locale.
4053 ** If there is a better way to make it portable, go ahead by
4056 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4059 /* Possibly buf overflowed - try again with a bigger buf */
4060 const int fmtlen = strlen(fmt);
4061 int bufsize = fmtlen + buflen;
4063 Renew(buf, bufsize, char);
4065 buflen = strftime(buf, bufsize, fmt, &mytm);
4066 if (buflen > 0 && buflen < bufsize)
4068 /* heuristic to prevent out-of-memory errors */
4069 if (bufsize > 100*fmtlen) {
4075 Renew(buf, bufsize, char);
4080 Perl_croak(aTHX_ "panic: no strftime");
4086 #define SV_CWD_RETURN_UNDEF \
4087 sv_setsv(sv, &PL_sv_undef); \
4090 #define SV_CWD_ISDOT(dp) \
4091 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4092 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4095 =head1 Miscellaneous Functions
4097 =for apidoc getcwd_sv
4099 Fill the sv with current working directory
4104 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4105 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4106 * getcwd(3) if available
4107 * Comments from the orignal:
4108 * This is a faster version of getcwd. It's also more dangerous
4109 * because you might chdir out of a directory that you can't chdir
4113 Perl_getcwd_sv(pTHX_ SV *sv)
4117 #ifndef INCOMPLETE_TAINTS
4121 PERL_ARGS_ASSERT_GETCWD_SV;
4125 char buf[MAXPATHLEN];
4127 /* Some getcwd()s automatically allocate a buffer of the given
4128 * size from the heap if they are given a NULL buffer pointer.
4129 * The problem is that this behaviour is not portable. */
4130 if (getcwd(buf, sizeof(buf) - 1)) {
4135 sv_setsv(sv, &PL_sv_undef);
4143 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4147 SvUPGRADE(sv, SVt_PV);
4149 if (PerlLIO_lstat(".", &statbuf) < 0) {
4150 SV_CWD_RETURN_UNDEF;
4153 orig_cdev = statbuf.st_dev;
4154 orig_cino = statbuf.st_ino;
4164 if (PerlDir_chdir("..") < 0) {
4165 SV_CWD_RETURN_UNDEF;
4167 if (PerlLIO_stat(".", &statbuf) < 0) {
4168 SV_CWD_RETURN_UNDEF;
4171 cdev = statbuf.st_dev;
4172 cino = statbuf.st_ino;
4174 if (odev == cdev && oino == cino) {
4177 if (!(dir = PerlDir_open("."))) {
4178 SV_CWD_RETURN_UNDEF;
4181 while ((dp = PerlDir_read(dir)) != NULL) {
4183 namelen = dp->d_namlen;
4185 namelen = strlen(dp->d_name);
4188 if (SV_CWD_ISDOT(dp)) {
4192 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4193 SV_CWD_RETURN_UNDEF;
4196 tdev = statbuf.st_dev;
4197 tino = statbuf.st_ino;
4198 if (tino == oino && tdev == odev) {
4204 SV_CWD_RETURN_UNDEF;
4207 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4208 SV_CWD_RETURN_UNDEF;
4211 SvGROW(sv, pathlen + namelen + 1);
4215 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4218 /* prepend current directory to the front */
4220 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4221 pathlen += (namelen + 1);
4223 #ifdef VOID_CLOSEDIR
4226 if (PerlDir_close(dir) < 0) {
4227 SV_CWD_RETURN_UNDEF;
4233 SvCUR_set(sv, pathlen);
4237 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4238 SV_CWD_RETURN_UNDEF;
4241 if (PerlLIO_stat(".", &statbuf) < 0) {
4242 SV_CWD_RETURN_UNDEF;
4245 cdev = statbuf.st_dev;
4246 cino = statbuf.st_ino;
4248 if (cdev != orig_cdev || cino != orig_cino) {
4249 Perl_croak(aTHX_ "Unstable directory path, "
4250 "current directory changed unexpectedly");
4261 #define VERSION_MAX 0x7FFFFFFF
4264 =for apidoc prescan_version
4266 Validate that a given string can be parsed as a version object, but doesn't
4267 actually perform the parsing. Can use either strict or lax validation rules.
4268 Can optionally set a number of hint variables to save the parsing code
4269 some time when tokenizing.
4274 Perl_prescan_version(pTHX_ const char *s, bool strict,
4275 const char **errstr,
4276 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4277 bool qv = (sqv ? *sqv : FALSE);
4279 int saw_decimal = 0;
4283 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4285 if (qv && isDIGIT(*d))
4286 goto dotted_decimal_version;
4288 if (*d == 'v') { /* explicit v-string */
4293 else { /* degenerate v-string */
4294 /* requires v1.2.3 */
4295 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4298 dotted_decimal_version:
4299 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4300 /* no leading zeros allowed */
4301 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4304 while (isDIGIT(*d)) /* integer part */
4310 d++; /* decimal point */
4315 /* require v1.2.3 */
4316 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4319 goto version_prescan_finish;
4326 while (isDIGIT(*d)) { /* just keep reading */
4328 while (isDIGIT(*d)) {
4330 /* maximum 3 digits between decimal */
4331 if (strict && j > 3) {
4332 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4337 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4340 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4345 else if (*d == '.') {
4347 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4352 else if (!isDIGIT(*d)) {
4358 if (strict && i < 2) {
4359 /* requires v1.2.3 */
4360 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4363 } /* end if dotted-decimal */
4365 { /* decimal versions */
4366 int j = 0; /* may need this later */
4367 /* special strict case for leading '.' or '0' */
4370 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4372 if (*d == '0' && isDIGIT(d[1])) {
4373 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4377 /* and we never support negative versions */
4379 BADVERSION(s,errstr,"Invalid version format (negative version number)");
4382 /* consume all of the integer part */
4386 /* look for a fractional part */
4388 /* we found it, so consume it */
4392 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4395 BADVERSION(s,errstr,"Invalid version format (version required)");
4397 /* found just an integer */
4398 goto version_prescan_finish;
4400 else if ( d == s ) {
4401 /* didn't find either integer or period */
4402 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4404 else if (*d == '_') {
4405 /* underscore can't come after integer part */
4407 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4409 else if (isDIGIT(d[1])) {
4410 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4413 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4417 /* anything else after integer part is just invalid data */
4418 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4421 /* scan the fractional part after the decimal point*/
4423 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4424 /* strict or lax-but-not-the-end */
4425 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4428 while (isDIGIT(*d)) {
4430 if (*d == '.' && isDIGIT(d[-1])) {
4432 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4435 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4437 d = (char *)s; /* start all over again */
4439 goto dotted_decimal_version;
4443 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4446 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4448 if ( ! isDIGIT(d[1]) ) {
4449 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4458 version_prescan_finish:
4462 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4463 /* trailing non-numeric data */
4464 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4472 *ssaw_decimal = saw_decimal;
4479 =for apidoc scan_version
4481 Returns a pointer to the next character after the parsed
4482 version string, as well as upgrading the passed in SV to
4485 Function must be called with an already existing SV like
4488 s = scan_version(s, SV *sv, bool qv);
4490 Performs some preprocessing to the string to ensure that
4491 it has the correct characteristics of a version. Flags the
4492 object if it contains an underscore (which denotes this
4493 is an alpha version). The boolean qv denotes that the version
4494 should be interpreted as if it had multiple decimals, even if
4501 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4506 const char *errstr = NULL;
4507 int saw_decimal = 0;
4511 AV * const av = newAV();
4512 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4514 PERL_ARGS_ASSERT_SCAN_VERSION;
4516 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4518 #ifndef NODEFAULT_SHAREKEYS
4519 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4522 while (isSPACE(*s)) /* leading whitespace is OK */
4525 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4527 /* "undef" is a special case and not an error */
4528 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4529 Perl_croak(aTHX_ "%s", errstr);
4539 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4541 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4542 if ( !qv && width < 3 )
4543 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4545 while (isDIGIT(*pos))
4547 if (!isALPHA(*pos)) {
4553 /* this is atoi() that delimits on underscores */
4554 const char *end = pos;
4558 /* the following if() will only be true after the decimal
4559 * point of a version originally created with a bare
4560 * floating point number, i.e. not quoted in any way
4562 if ( !qv && s > start && saw_decimal == 1 ) {
4566 rev += (*s - '0') * mult;
4568 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4569 || (PERL_ABS(rev) > VERSION_MAX )) {
4570 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4571 "Integer overflow in version %d",VERSION_MAX);
4582 while (--end >= s) {
4584 rev += (*end - '0') * mult;
4586 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4587 || (PERL_ABS(rev) > VERSION_MAX )) {
4588 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4589 "Integer overflow in version");
4598 /* Append revision */
4599 av_push(av, newSViv(rev));
4604 else if ( *pos == '.' )
4606 else if ( *pos == '_' && isDIGIT(pos[1]) )
4608 else if ( *pos == ',' && isDIGIT(pos[1]) )
4610 else if ( isDIGIT(*pos) )
4617 while ( isDIGIT(*pos) )
4622 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4630 if ( qv ) { /* quoted versions always get at least three terms*/
4631 I32 len = av_len(av);
4632 /* This for loop appears to trigger a compiler bug on OS X, as it
4633 loops infinitely. Yes, len is negative. No, it makes no sense.
4634 Compiler in question is:
4635 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4636 for ( len = 2 - len; len > 0; len-- )
4637 av_push(MUTABLE_AV(sv), newSViv(0));
4641 av_push(av, newSViv(0));
4644 /* need to save off the current version string for later */
4646 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4647 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4648 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4650 else if ( s > start ) {
4651 SV * orig = newSVpvn(start,s-start);
4652 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4653 /* need to insert a v to be consistent */
4654 sv_insert(orig, 0, 0, "v", 1);
4656 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4659 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4660 av_push(av, newSViv(0));
4663 /* And finally, store the AV in the hash */
4664 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4666 /* fix RT#19517 - special case 'undef' as string */
4667 if ( *s == 'u' && strEQ(s,"undef") ) {
4675 =for apidoc new_version
4677 Returns a new version object based on the passed in SV:
4679 SV *sv = new_version(SV *ver);
4681 Does not alter the passed in ver SV. See "upg_version" if you
4682 want to upgrade the SV.
4688 Perl_new_version(pTHX_ SV *ver)
4691 SV * const rv = newSV(0);
4692 PERL_ARGS_ASSERT_NEW_VERSION;
4693 if ( sv_isobject(ver) && sv_derived_from(ver, "version") )
4694 /* can just copy directly */
4697 AV * const av = newAV();
4699 /* This will get reblessed later if a derived class*/
4700 SV * const hv = newSVrv(rv, "version");
4701 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4702 #ifndef NODEFAULT_SHAREKEYS
4703 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4709 /* Begin copying all of the elements */
4710 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4711 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4713 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4714 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4716 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4718 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4719 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4722 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4724 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4725 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4728 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4729 /* This will get reblessed later if a derived class*/
4730 for ( key = 0; key <= av_len(sav); key++ )
4732 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4733 av_push(av, newSViv(rev));
4736 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4741 const MAGIC* const mg = SvVSTRING_mg(ver);
4742 if ( mg ) { /* already a v-string */
4743 const STRLEN len = mg->mg_len;
4744 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4745 sv_setpvn(rv,version,len);
4746 /* this is for consistency with the pure Perl class */
4747 if ( isDIGIT(*version) )
4748 sv_insert(rv, 0, 0, "v", 1);
4753 sv_setsv(rv,ver); /* make a duplicate */
4758 return upg_version(rv, FALSE);
4762 =for apidoc upg_version
4764 In-place upgrade of the supplied SV to a version object.
4766 SV *sv = upg_version(SV *sv, bool qv);
4768 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4769 to force this SV to be interpreted as an "extended" version.
4775 Perl_upg_version(pTHX_ SV *ver, bool qv)
4777 const char *version, *s;
4782 PERL_ARGS_ASSERT_UPG_VERSION;
4784 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4788 /* may get too much accuracy */
4790 SV *sv = SvNVX(ver) > 10e50 ? newSV(64) : 0;
4792 #ifdef USE_LOCALE_NUMERIC
4793 char *loc = savepv(setlocale(LC_NUMERIC, NULL));
4794 setlocale(LC_NUMERIC, "C");
4797 Perl_sv_setpvf(aTHX_ sv, "%.9"NVff, SvNVX(ver));
4798 buf = SvPV(sv, len);
4801 len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4804 #ifdef USE_LOCALE_NUMERIC
4805 setlocale(LC_NUMERIC, loc);
4808 while (buf[len-1] == '0' && len > 0) len--;
4809 if ( buf[len-1] == '.' ) len--; /* eat the trailing decimal */
4810 version = savepvn(buf, len);
4814 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4815 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4819 else /* must be a string or something like a string */
4822 version = savepv(SvPV(ver,len));
4824 # if PERL_VERSION > 5
4825 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4826 if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
4827 /* may be a v-string */
4828 char *testv = (char *)version;
4830 for (tlen=0; tlen < len; tlen++, testv++) {
4831 /* if one of the characters is non-text assume v-string */
4832 if (testv[0] < ' ') {
4833 SV * const nsv = sv_newmortal();
4836 int saw_decimal = 0;
4837 sv_setpvf(nsv,"v%vd",ver);
4838 pos = nver = savepv(SvPV_nolen(nsv));
4840 /* scan the resulting formatted string */
4841 pos++; /* skip the leading 'v' */
4842 while ( *pos == '.' || isDIGIT(*pos) ) {
4848 /* is definitely a v-string */
4849 if ( saw_decimal >= 2 ) {
4861 s = scan_version(version, ver, qv);
4863 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4864 "Version string '%s' contains invalid data; "
4865 "ignoring: '%s'", version, s);
4873 Validates that the SV contains valid internal structure for a version object.
4874 It may be passed either the version object (RV) or the hash itself (HV). If
4875 the structure is valid, it returns the HV. If the structure is invalid,
4878 SV *hv = vverify(sv);
4880 Note that it only confirms the bare minimum structure (so as not to get
4881 confused by derived classes which may contain additional hash entries):
4885 =item * The SV is an HV or a reference to an HV
4887 =item * The hash contains a "version" key
4889 =item * The "version" key has a reference to an AV as its value
4897 Perl_vverify(pTHX_ SV *vs)
4901 PERL_ARGS_ASSERT_VVERIFY;
4906 /* see if the appropriate elements exist */
4907 if ( SvTYPE(vs) == SVt_PVHV
4908 && hv_exists(MUTABLE_HV(vs), "version", 7)
4909 && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
4910 && SvTYPE(sv) == SVt_PVAV )
4919 Accepts a version object and returns the normalized floating
4920 point representation. Call like:
4924 NOTE: you can pass either the object directly or the SV
4925 contained within the RV.
4927 The SV returned has a refcount of 1.
4933 Perl_vnumify(pTHX_ SV *vs)
4941 PERL_ARGS_ASSERT_VNUMIFY;
4943 /* extract the HV from the object */
4946 Perl_croak(aTHX_ "Invalid version object");
4948 /* see if various flags exist */
4949 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
4951 if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
4952 width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
4957 /* attempt to retrieve the version array */
4958 if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
4959 return newSVpvs("0");
4965 return newSVpvs("0");
4968 digit = SvIV(*av_fetch(av, 0, 0));
4969 sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
4970 for ( i = 1 ; i < len ; i++ )
4972 digit = SvIV(*av_fetch(av, i, 0));
4974 const int denom = (width == 2 ? 10 : 100);
4975 const div_t term = div((int)PERL_ABS(digit),denom);
4976 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4979 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4985 digit = SvIV(*av_fetch(av, len, 0));
4986 if ( alpha && width == 3 ) /* alpha version */
4988 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4992 sv_catpvs(sv, "000");
5000 Accepts a version object and returns the normalized string
5001 representation. Call like:
5005 NOTE: you can pass either the object directly or the SV
5006 contained within the RV.
5008 The SV returned has a refcount of 1.
5014 Perl_vnormal(pTHX_ SV *vs)
5021 PERL_ARGS_ASSERT_VNORMAL;
5023 /* extract the HV from the object */
5026 Perl_croak(aTHX_ "Invalid version object");
5028 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5030 av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)));
5035 return newSVpvs("");
5037 digit = SvIV(*av_fetch(av, 0, 0));
5038 sv = Perl_newSVpvf(aTHX_ "v%"IVdf, (IV)digit);
5039 for ( i = 1 ; i < len ; i++ ) {
5040 digit = SvIV(*av_fetch(av, i, 0));
5041 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5046 /* handle last digit specially */
5047 digit = SvIV(*av_fetch(av, len, 0));
5049 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
5051 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5054 if ( len <= 2 ) { /* short version, must be at least three */
5055 for ( len = 2 - len; len != 0; len-- )
5062 =for apidoc vstringify
5064 In order to maintain maximum compatibility with earlier versions
5065 of Perl, this function will return either the floating point
5066 notation or the multiple dotted notation, depending on whether
5067 the original version contained 1 or more dots, respectively.
5069 The SV returned has a refcount of 1.
5075 Perl_vstringify(pTHX_ SV *vs)
5077 PERL_ARGS_ASSERT_VSTRINGIFY;
5079 /* extract the HV from the object */
5082 Perl_croak(aTHX_ "Invalid version object");
5084 if (hv_exists(MUTABLE_HV(vs), "original", sizeof("original") - 1)) {
5086 pv = *hv_fetchs(MUTABLE_HV(vs), "original", FALSE);
5090 return &PL_sv_undef;
5093 if ( hv_exists(MUTABLE_HV(vs), "qv", 2) )
5103 Version object aware cmp. Both operands must already have been
5104 converted into version objects.
5110 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
5113 bool lalpha = FALSE;
5114 bool ralpha = FALSE;
5119 PERL_ARGS_ASSERT_VCMP;
5121 /* extract the HVs from the objects */
5124 if ( ! ( lhv && rhv ) )
5125 Perl_croak(aTHX_ "Invalid version object");
5127 /* get the left hand term */
5128 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(lhv), "version", FALSE)));
5129 if ( hv_exists(MUTABLE_HV(lhv), "alpha", 5 ) )
5132 /* and the right hand term */
5133 rav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rhv), "version", FALSE)));
5134 if ( hv_exists(MUTABLE_HV(rhv), "alpha", 5 ) )
5142 while ( i <= m && retval == 0 )
5144 left = SvIV(*av_fetch(lav,i,0));
5145 right = SvIV(*av_fetch(rav,i,0));
5153 /* tiebreaker for alpha with identical terms */
5154 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
5156 if ( lalpha && !ralpha )
5160 else if ( ralpha && !lalpha)
5166 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
5170 while ( i <= r && retval == 0 )
5172 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
5173 retval = -1; /* not a match after all */
5179 while ( i <= l && retval == 0 )
5181 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
5182 retval = +1; /* not a match after all */
5190 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
5191 # define EMULATE_SOCKETPAIR_UDP
5194 #ifdef EMULATE_SOCKETPAIR_UDP
5196 S_socketpair_udp (int fd[2]) {
5198 /* Fake a datagram socketpair using UDP to localhost. */
5199 int sockets[2] = {-1, -1};
5200 struct sockaddr_in addresses[2];
5202 Sock_size_t size = sizeof(struct sockaddr_in);
5203 unsigned short port;
5206 memset(&addresses, 0, sizeof(addresses));
5209 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
5210 if (sockets[i] == -1)
5211 goto tidy_up_and_fail;
5213 addresses[i].sin_family = AF_INET;
5214 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5215 addresses[i].sin_port = 0; /* kernel choses port. */
5216 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
5217 sizeof(struct sockaddr_in)) == -1)
5218 goto tidy_up_and_fail;
5221 /* Now have 2 UDP sockets. Find out which port each is connected to, and
5222 for each connect the other socket to it. */
5225 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
5227 goto tidy_up_and_fail;
5228 if (size != sizeof(struct sockaddr_in))
5229 goto abort_tidy_up_and_fail;
5230 /* !1 is 0, !0 is 1 */
5231 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
5232 sizeof(struct sockaddr_in)) == -1)
5233 goto tidy_up_and_fail;
5236 /* Now we have 2 sockets connected to each other. I don't trust some other
5237 process not to have already sent a packet to us (by random) so send
5238 a packet from each to the other. */
5241 /* I'm going to send my own port number. As a short.
5242 (Who knows if someone somewhere has sin_port as a bitfield and needs
5243 this routine. (I'm assuming crays have socketpair)) */
5244 port = addresses[i].sin_port;
5245 got = PerlLIO_write(sockets[i], &port, sizeof(port));
5246 if (got != sizeof(port)) {
5248 goto tidy_up_and_fail;
5249 goto abort_tidy_up_and_fail;
5253 /* Packets sent. I don't trust them to have arrived though.
5254 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
5255 connect to localhost will use a second kernel thread. In 2.6 the
5256 first thread running the connect() returns before the second completes,
5257 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
5258 returns 0. Poor programs have tripped up. One poor program's authors'
5259 had a 50-1 reverse stock split. Not sure how connected these were.)
5260 So I don't trust someone not to have an unpredictable UDP stack.
5264 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
5265 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
5269 FD_SET((unsigned int)sockets[0], &rset);
5270 FD_SET((unsigned int)sockets[1], &rset);
5272 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
5273 if (got != 2 || !FD_ISSET(sockets[0], &rset)
5274 || !FD_ISSET(sockets[1], &rset)) {
5275 /* I hope this is portable and appropriate. */
5277 goto tidy_up_and_fail;
5278 goto abort_tidy_up_and_fail;
5282 /* And the paranoia department even now doesn't trust it to have arrive
5283 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
5285 struct sockaddr_in readfrom;
5286 unsigned short buffer[2];
5291 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5292 sizeof(buffer), MSG_DONTWAIT,
5293 (struct sockaddr *) &readfrom, &size);
5295 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5297 (struct sockaddr *) &readfrom, &size);
5301 goto tidy_up_and_fail;
5302 if (got != sizeof(port)
5303 || size != sizeof(struct sockaddr_in)
5304 /* Check other socket sent us its port. */
5305 || buffer[0] != (unsigned short) addresses[!i].sin_port
5306 /* Check kernel says we got the datagram from that socket */
5307 || readfrom.sin_family != addresses[!i].sin_family
5308 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
5309 || readfrom.sin_port != addresses[!i].sin_port)
5310 goto abort_tidy_up_and_fail;
5313 /* My caller (my_socketpair) has validated that this is non-NULL */
5316 /* I hereby declare this connection open. May God bless all who cross
5320 abort_tidy_up_and_fail:
5321 errno = ECONNABORTED;
5325 if (sockets[0] != -1)
5326 PerlLIO_close(sockets[0]);
5327 if (sockets[1] != -1)
5328 PerlLIO_close(sockets[1]);
5333 #endif /* EMULATE_SOCKETPAIR_UDP */
5335 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
5337 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5338 /* Stevens says that family must be AF_LOCAL, protocol 0.
5339 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
5344 struct sockaddr_in listen_addr;
5345 struct sockaddr_in connect_addr;
5350 || family != AF_UNIX
5353 errno = EAFNOSUPPORT;
5361 #ifdef EMULATE_SOCKETPAIR_UDP
5362 if (type == SOCK_DGRAM)
5363 return S_socketpair_udp(fd);
5366 aTHXa(PERL_GET_THX);
5367 listener = PerlSock_socket(AF_INET, type, 0);
5370 memset(&listen_addr, 0, sizeof(listen_addr));
5371 listen_addr.sin_family = AF_INET;
5372 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5373 listen_addr.sin_port = 0; /* kernel choses port. */
5374 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5375 sizeof(listen_addr)) == -1)
5376 goto tidy_up_and_fail;
5377 if (PerlSock_listen(listener, 1) == -1)
5378 goto tidy_up_and_fail;
5380 connector = PerlSock_socket(AF_INET, type, 0);
5381 if (connector == -1)
5382 goto tidy_up_and_fail;
5383 /* We want to find out the port number to connect to. */
5384 size = sizeof(connect_addr);
5385 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5387 goto tidy_up_and_fail;
5388 if (size != sizeof(connect_addr))
5389 goto abort_tidy_up_and_fail;
5390 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
5391 sizeof(connect_addr)) == -1)
5392 goto tidy_up_and_fail;
5394 size = sizeof(listen_addr);
5395 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5398 goto tidy_up_and_fail;
5399 if (size != sizeof(listen_addr))
5400 goto abort_tidy_up_and_fail;
5401 PerlLIO_close(listener);
5402 /* Now check we are talking to ourself by matching port and host on the
5404 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5406 goto tidy_up_and_fail;
5407 if (size != sizeof(connect_addr)
5408 || listen_addr.sin_family != connect_addr.sin_family
5409 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5410 || listen_addr.sin_port != connect_addr.sin_port) {
5411 goto abort_tidy_up_and_fail;
5417 abort_tidy_up_and_fail:
5419 errno = ECONNABORTED; /* This would be the standard thing to do. */
5421 # ifdef ECONNREFUSED
5422 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5424 errno = ETIMEDOUT; /* Desperation time. */
5431 PerlLIO_close(listener);
5432 if (connector != -1)
5433 PerlLIO_close(connector);
5435 PerlLIO_close(acceptor);
5441 /* In any case have a stub so that there's code corresponding
5442 * to the my_socketpair in embed.fnc. */
5444 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5445 #ifdef HAS_SOCKETPAIR
5446 return socketpair(family, type, protocol, fd);
5455 =for apidoc sv_nosharing
5457 Dummy routine which "shares" an SV when there is no sharing module present.
5458 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5459 Exists to avoid test for a NULL function pointer and because it could
5460 potentially warn under some level of strict-ness.
5466 Perl_sv_nosharing(pTHX_ SV *sv)
5468 PERL_UNUSED_CONTEXT;
5469 PERL_UNUSED_ARG(sv);
5474 =for apidoc sv_destroyable
5476 Dummy routine which reports that object can be destroyed when there is no
5477 sharing module present. It ignores its single SV argument, and returns
5478 'true'. Exists to avoid test for a NULL function pointer and because it
5479 could potentially warn under some level of strict-ness.
5485 Perl_sv_destroyable(pTHX_ SV *sv)
5487 PERL_UNUSED_CONTEXT;
5488 PERL_UNUSED_ARG(sv);
5493 Perl_parse_unicode_opts(pTHX_ const char **popt)
5495 const char *p = *popt;
5498 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5502 opt = (U32) atoi(p);
5505 if (*p && *p != '\n' && *p != '\r') {
5506 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5508 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
5514 case PERL_UNICODE_STDIN:
5515 opt |= PERL_UNICODE_STDIN_FLAG; break;
5516 case PERL_UNICODE_STDOUT:
5517 opt |= PERL_UNICODE_STDOUT_FLAG; break;
5518 case PERL_UNICODE_STDERR:
5519 opt |= PERL_UNICODE_STDERR_FLAG; break;
5520 case PERL_UNICODE_STD:
5521 opt |= PERL_UNICODE_STD_FLAG; break;
5522 case PERL_UNICODE_IN:
5523 opt |= PERL_UNICODE_IN_FLAG; break;
5524 case PERL_UNICODE_OUT:
5525 opt |= PERL_UNICODE_OUT_FLAG; break;
5526 case PERL_UNICODE_INOUT:
5527 opt |= PERL_UNICODE_INOUT_FLAG; break;
5528 case PERL_UNICODE_LOCALE:
5529 opt |= PERL_UNICODE_LOCALE_FLAG; break;
5530 case PERL_UNICODE_ARGV:
5531 opt |= PERL_UNICODE_ARGV_FLAG; break;
5532 case PERL_UNICODE_UTF8CACHEASSERT:
5533 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
5535 if (*p != '\n' && *p != '\r') {
5536 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5539 "Unknown Unicode option letter '%c'", *p);
5546 opt = PERL_UNICODE_DEFAULT_FLAGS;
5548 the_end_of_the_opts_parser:
5550 if (opt & ~PERL_UNICODE_ALL_FLAGS)
5551 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
5552 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5560 # include <starlet.h>
5568 * This is really just a quick hack which grabs various garbage
5569 * values. It really should be a real hash algorithm which
5570 * spreads the effect of every input bit onto every output bit,
5571 * if someone who knows about such things would bother to write it.
5572 * Might be a good idea to add that function to CORE as well.
5573 * No numbers below come from careful analysis or anything here,
5574 * except they are primes and SEED_C1 > 1E6 to get a full-width
5575 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5576 * probably be bigger too.
5579 # define SEED_C1 1000003
5580 #define SEED_C4 73819
5582 # define SEED_C1 25747
5583 #define SEED_C4 20639
5587 #define SEED_C5 26107
5589 #ifndef PERL_NO_DEV_RANDOM
5594 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5595 * in 100-ns units, typically incremented ever 10 ms. */
5596 unsigned int when[2];
5598 # ifdef HAS_GETTIMEOFDAY
5599 struct timeval when;
5605 /* This test is an escape hatch, this symbol isn't set by Configure. */
5606 #ifndef PERL_NO_DEV_RANDOM
5607 #ifndef PERL_RANDOM_DEVICE
5608 /* /dev/random isn't used by default because reads from it will block
5609 * if there isn't enough entropy available. You can compile with
5610 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5611 * is enough real entropy to fill the seed. */
5612 # define PERL_RANDOM_DEVICE "/dev/urandom"
5614 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5616 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5625 _ckvmssts(sys$gettim(when));
5626 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5628 # ifdef HAS_GETTIMEOFDAY
5629 PerlProc_gettimeofday(&when,NULL);
5630 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5633 u = (U32)SEED_C1 * when;
5636 u += SEED_C3 * (U32)PerlProc_getpid();
5637 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5638 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5639 u += SEED_C5 * (U32)PTR2UV(&when);
5645 Perl_get_hash_seed(pTHX_ unsigned char *seed_buffer)
5649 const unsigned char * const end= seed_buffer + PERL_HASH_SEED_BYTES;
5651 PERL_ARGS_ASSERT_GET_HASH_SEED;
5653 s= PerlEnv_getenv("PERL_HASH_SEED");
5656 #ifndef USE_HASH_SEED_EXPLICIT
5660 if (s[0] == '0' && s[1] == 'x')
5663 while (isXDIGIT(*s) && seed_buffer < end) {
5664 *seed_buffer = READ_XDIGIT(s) << 4;
5666 *seed_buffer |= READ_XDIGIT(s);
5672 if (*s && !isXDIGIT(*s)) {
5673 Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n");
5675 /* should we check for unparsed crap? */
5680 (void)seedDrand01((Rand_seed_t)seed());
5682 while (seed_buffer < end) {
5683 *seed_buffer++ = (unsigned char)(Drand01() * (U8_MAX+1));
5688 #ifdef PERL_GLOBAL_STRUCT
5690 #define PERL_GLOBAL_STRUCT_INIT
5691 #include "opcode.h" /* the ppaddr and check */
5694 Perl_init_global_struct(pTHX)
5696 struct perl_vars *plvarsp = NULL;
5697 # ifdef PERL_GLOBAL_STRUCT
5698 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5699 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5700 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5701 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5702 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5706 plvarsp = PL_VarsPtr;
5707 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5712 # define PERLVAR(prefix,var,type) /**/
5713 # define PERLVARA(prefix,var,n,type) /**/
5714 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
5715 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
5716 # include "perlvars.h"
5721 # ifdef PERL_GLOBAL_STRUCT
5724 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5725 if (!plvarsp->Gppaddr)
5729 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5730 if (!plvarsp->Gcheck)
5732 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5733 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5735 # ifdef PERL_SET_VARS
5736 PERL_SET_VARS(plvarsp);
5738 # undef PERL_GLOBAL_STRUCT_INIT
5743 #endif /* PERL_GLOBAL_STRUCT */
5745 #ifdef PERL_GLOBAL_STRUCT
5748 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5750 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
5751 # ifdef PERL_GLOBAL_STRUCT
5752 # ifdef PERL_UNSET_VARS
5753 PERL_UNSET_VARS(plvarsp);
5755 free(plvarsp->Gppaddr);
5756 free(plvarsp->Gcheck);
5757 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5763 #endif /* PERL_GLOBAL_STRUCT */
5767 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
5768 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
5769 * given, and you supply your own implementation.
5771 * The default implementation reads a single env var, PERL_MEM_LOG,
5772 * expecting one or more of the following:
5774 * \d+ - fd fd to write to : must be 1st (atoi)
5775 * 'm' - memlog was PERL_MEM_LOG=1
5776 * 's' - svlog was PERL_SV_LOG=1
5777 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
5779 * This makes the logger controllable enough that it can reasonably be
5780 * added to the system perl.
5783 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
5784 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5786 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5788 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
5789 * writes to. In the default logger, this is settable at runtime.
5791 #ifndef PERL_MEM_LOG_FD
5792 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5795 #ifndef PERL_MEM_LOG_NOIMPL
5797 # ifdef DEBUG_LEAKING_SCALARS
5798 # define SV_LOG_SERIAL_FMT " [%lu]"
5799 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
5801 # define SV_LOG_SERIAL_FMT
5802 # define _SV_LOG_SERIAL_ARG(sv)
5806 S_mem_log_common(enum mem_log_type mlt, const UV n,
5807 const UV typesize, const char *type_name, const SV *sv,
5808 Malloc_t oldalloc, Malloc_t newalloc,
5809 const char *filename, const int linenumber,
5810 const char *funcname)
5814 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
5816 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
5819 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
5821 /* We can't use SVs or PerlIO for obvious reasons,
5822 * so we'll use stdio and low-level IO instead. */
5823 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5825 # ifdef HAS_GETTIMEOFDAY
5826 # define MEM_LOG_TIME_FMT "%10d.%06d: "
5827 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
5829 gettimeofday(&tv, 0);
5831 # define MEM_LOG_TIME_FMT "%10d: "
5832 # define MEM_LOG_TIME_ARG (int)when
5836 /* If there are other OS specific ways of hires time than
5837 * gettimeofday() (see ext/Time-HiRes), the easiest way is
5838 * probably that they would be used to fill in the struct
5842 int fd = atoi(pmlenv);
5844 fd = PERL_MEM_LOG_FD;
5846 if (strchr(pmlenv, 't')) {
5847 len = my_snprintf(buf, sizeof(buf),
5848 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
5849 PerlLIO_write(fd, buf, len);
5853 len = my_snprintf(buf, sizeof(buf),
5854 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5855 " %s = %"IVdf": %"UVxf"\n",
5856 filename, linenumber, funcname, n, typesize,
5857 type_name, n * typesize, PTR2UV(newalloc));
5860 len = my_snprintf(buf, sizeof(buf),
5861 "realloc: %s:%d:%s: %"IVdf" %"UVuf
5862 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5863 filename, linenumber, funcname, n, typesize,
5864 type_name, n * typesize, PTR2UV(oldalloc),
5868 len = my_snprintf(buf, sizeof(buf),
5869 "free: %s:%d:%s: %"UVxf"\n",
5870 filename, linenumber, funcname,
5875 len = my_snprintf(buf, sizeof(buf),
5876 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
5877 mlt == MLT_NEW_SV ? "new" : "del",
5878 filename, linenumber, funcname,
5879 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
5884 PerlLIO_write(fd, buf, len);
5888 #endif /* !PERL_MEM_LOG_NOIMPL */
5890 #ifndef PERL_MEM_LOG_NOIMPL
5892 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
5893 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
5895 /* this is suboptimal, but bug compatible. User is providing their
5896 own implementation, but is getting these functions anyway, and they
5897 do nothing. But _NOIMPL users should be able to cope or fix */
5899 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
5900 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
5904 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
5906 const char *filename, const int linenumber,
5907 const char *funcname)
5909 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
5910 NULL, NULL, newalloc,
5911 filename, linenumber, funcname);
5916 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
5917 Malloc_t oldalloc, Malloc_t newalloc,
5918 const char *filename, const int linenumber,
5919 const char *funcname)
5921 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
5922 NULL, oldalloc, newalloc,
5923 filename, linenumber, funcname);
5928 Perl_mem_log_free(Malloc_t oldalloc,
5929 const char *filename, const int linenumber,
5930 const char *funcname)
5932 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
5933 filename, linenumber, funcname);
5938 Perl_mem_log_new_sv(const SV *sv,
5939 const char *filename, const int linenumber,
5940 const char *funcname)
5942 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
5943 filename, linenumber, funcname);
5947 Perl_mem_log_del_sv(const SV *sv,
5948 const char *filename, const int linenumber,
5949 const char *funcname)
5951 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
5952 filename, linenumber, funcname);
5955 #endif /* PERL_MEM_LOG */
5958 =for apidoc my_sprintf
5960 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5961 the length of the string written to the buffer. Only rare pre-ANSI systems
5962 need the wrapper function - usually this is a direct call to C<sprintf>.
5966 #ifndef SPRINTF_RETURNS_STRLEN
5968 Perl_my_sprintf(char *buffer, const char* pat, ...)
5971 PERL_ARGS_ASSERT_MY_SPRINTF;
5972 va_start(args, pat);
5973 vsprintf(buffer, pat, args);
5975 return strlen(buffer);
5980 =for apidoc my_snprintf
5982 The C library C<snprintf> functionality, if available and
5983 standards-compliant (uses C<vsnprintf>, actually). However, if the
5984 C<vsnprintf> is not available, will unfortunately use the unsafe
5985 C<vsprintf> which can overrun the buffer (there is an overrun check,
5986 but that may be too late). Consider using C<sv_vcatpvf> instead, or
5987 getting C<vsnprintf>.
5992 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
5996 PERL_ARGS_ASSERT_MY_SNPRINTF;
5997 va_start(ap, format);
5998 #ifdef HAS_VSNPRINTF
5999 retval = vsnprintf(buffer, len, format, ap);
6001 retval = vsprintf(buffer, format, ap);
6004 /* vsprintf() shows failure with < 0 */
6006 #ifdef HAS_VSNPRINTF
6007 /* vsnprintf() shows failure with >= len */
6009 (len > 0 && (Size_t)retval >= len)
6012 Perl_croak_nocontext("panic: my_snprintf buffer overflow");
6017 =for apidoc my_vsnprintf
6019 The C library C<vsnprintf> if available and standards-compliant.
6020 However, if if the C<vsnprintf> is not available, will unfortunately
6021 use the unsafe C<vsprintf> which can overrun the buffer (there is an
6022 overrun check, but that may be too late). Consider using
6023 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
6028 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
6034 PERL_ARGS_ASSERT_MY_VSNPRINTF;
6036 Perl_va_copy(ap, apc);
6037 # ifdef HAS_VSNPRINTF
6038 retval = vsnprintf(buffer, len, format, apc);
6040 retval = vsprintf(buffer, format, apc);
6043 # ifdef HAS_VSNPRINTF
6044 retval = vsnprintf(buffer, len, format, ap);
6046 retval = vsprintf(buffer, format, ap);
6048 #endif /* #ifdef NEED_VA_COPY */
6049 /* vsprintf() shows failure with < 0 */
6051 #ifdef HAS_VSNPRINTF
6052 /* vsnprintf() shows failure with >= len */
6054 (len > 0 && (Size_t)retval >= len)
6057 Perl_croak_nocontext("panic: my_vsnprintf buffer overflow");
6062 Perl_my_clearenv(pTHX)
6065 #if ! defined(PERL_MICRO)
6066 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
6068 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
6069 # if defined(USE_ENVIRON_ARRAY)
6070 # if defined(USE_ITHREADS)
6071 /* only the parent thread can clobber the process environment */
6072 if (PL_curinterp == aTHX)
6073 # endif /* USE_ITHREADS */
6075 # if ! defined(PERL_USE_SAFE_PUTENV)
6076 if ( !PL_use_safe_putenv) {
6078 if (environ == PL_origenviron)
6079 environ = (char**)safesysmalloc(sizeof(char*));
6081 for (i = 0; environ[i]; i++)
6082 (void)safesysfree(environ[i]);
6085 # else /* PERL_USE_SAFE_PUTENV */
6086 # if defined(HAS_CLEARENV)
6088 # elif defined(HAS_UNSETENV)
6089 int bsiz = 80; /* Most envvar names will be shorter than this. */
6090 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
6091 char *buf = (char*)safesysmalloc(bufsiz);
6092 while (*environ != NULL) {
6093 char *e = strchr(*environ, '=');
6094 int l = e ? e - *environ : (int)strlen(*environ);
6096 (void)safesysfree(buf);
6097 bsiz = l + 1; /* + 1 for the \0. */
6098 buf = (char*)safesysmalloc(bufsiz);
6100 memcpy(buf, *environ, l);
6102 (void)unsetenv(buf);
6104 (void)safesysfree(buf);
6105 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
6106 /* Just null environ and accept the leakage. */
6108 # endif /* HAS_CLEARENV || HAS_UNSETENV */
6109 # endif /* ! PERL_USE_SAFE_PUTENV */
6111 # endif /* USE_ENVIRON_ARRAY */
6112 # endif /* PERL_IMPLICIT_SYS || WIN32 */
6113 #endif /* PERL_MICRO */
6116 #ifdef PERL_IMPLICIT_CONTEXT
6118 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
6119 the global PL_my_cxt_index is incremented, and that value is assigned to
6120 that module's static my_cxt_index (who's address is passed as an arg).
6121 Then, for each interpreter this function is called for, it makes sure a
6122 void* slot is available to hang the static data off, by allocating or
6123 extending the interpreter's PL_my_cxt_list array */
6125 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
6127 Perl_my_cxt_init(pTHX_ int *index, size_t size)
6131 PERL_ARGS_ASSERT_MY_CXT_INIT;
6133 /* this module hasn't been allocated an index yet */
6134 #if defined(USE_ITHREADS)
6135 MUTEX_LOCK(&PL_my_ctx_mutex);
6137 *index = PL_my_cxt_index++;
6138 #if defined(USE_ITHREADS)
6139 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6143 /* make sure the array is big enough */
6144 if (PL_my_cxt_size <= *index) {
6145 if (PL_my_cxt_size) {
6146 while (PL_my_cxt_size <= *index)
6147 PL_my_cxt_size *= 2;
6148 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6151 PL_my_cxt_size = 16;
6152 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6155 /* newSV() allocates one more than needed */
6156 p = (void*)SvPVX(newSV(size-1));
6157 PL_my_cxt_list[*index] = p;
6158 Zero(p, size, char);
6162 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6165 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
6170 PERL_ARGS_ASSERT_MY_CXT_INDEX;
6172 for (index = 0; index < PL_my_cxt_index; index++) {
6173 const char *key = PL_my_cxt_keys[index];
6174 /* try direct pointer compare first - there are chances to success,
6175 * and it's much faster.
6177 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
6184 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
6190 PERL_ARGS_ASSERT_MY_CXT_INIT;
6192 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
6194 /* this module hasn't been allocated an index yet */
6195 #if defined(USE_ITHREADS)
6196 MUTEX_LOCK(&PL_my_ctx_mutex);
6198 index = PL_my_cxt_index++;
6199 #if defined(USE_ITHREADS)
6200 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6204 /* make sure the array is big enough */
6205 if (PL_my_cxt_size <= index) {
6206 int old_size = PL_my_cxt_size;
6208 if (PL_my_cxt_size) {
6209 while (PL_my_cxt_size <= index)
6210 PL_my_cxt_size *= 2;
6211 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6212 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6215 PL_my_cxt_size = 16;
6216 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6217 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6219 for (i = old_size; i < PL_my_cxt_size; i++) {
6220 PL_my_cxt_keys[i] = 0;
6221 PL_my_cxt_list[i] = 0;
6224 PL_my_cxt_keys[index] = my_cxt_key;
6225 /* newSV() allocates one more than needed */
6226 p = (void*)SvPVX(newSV(size-1));
6227 PL_my_cxt_list[index] = p;
6228 Zero(p, size, char);
6231 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6232 #endif /* PERL_IMPLICIT_CONTEXT */
6235 Perl_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
6239 const char *vn = NULL;
6240 SV *const module = PL_stack_base[ax];
6242 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
6244 if (items >= 2) /* version supplied as bootstrap arg */
6245 sv = PL_stack_base[ax + 1];
6247 /* XXX GV_ADDWARN */
6249 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6250 if (!sv || !SvOK(sv)) {
6252 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6256 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
6257 SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version")
6258 ? sv : sv_2mortal(new_version(sv));
6259 xssv = upg_version(xssv, 0);
6260 if ( vcmp(pmsv,xssv) ) {
6261 SV *string = vstringify(xssv);
6262 SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
6263 " does not match ", module, string);
6265 SvREFCNT_dec(string);
6266 string = vstringify(pmsv);
6269 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, module, vn,
6272 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, string);
6274 SvREFCNT_dec(string);
6276 Perl_sv_2mortal(aTHX_ xpt);
6277 Perl_croak_sv(aTHX_ xpt);
6283 Perl_xs_apiversion_bootcheck(pTHX_ SV *module, const char *api_p,
6287 SV *compver = Perl_newSVpvn_flags(aTHX_ api_p, api_len, SVs_TEMP);
6290 PERL_ARGS_ASSERT_XS_APIVERSION_BOOTCHECK;
6292 /* This might croak */
6293 compver = upg_version(compver, 0);
6294 /* This should never croak */
6295 runver = new_version(PL_apiversion);
6296 if (vcmp(compver, runver)) {
6297 SV *compver_string = vstringify(compver);
6298 SV *runver_string = vstringify(runver);
6299 xpt = Perl_newSVpvf(aTHX_ "Perl API version %"SVf
6300 " of %"SVf" does not match %"SVf,
6301 compver_string, module, runver_string);
6302 Perl_sv_2mortal(aTHX_ xpt);
6304 SvREFCNT_dec(compver_string);
6305 SvREFCNT_dec(runver_string);
6307 SvREFCNT_dec(runver);
6309 Perl_croak_sv(aTHX_ xpt);
6314 Perl_my_strlcat(char *dst, const char *src, Size_t size)
6316 Size_t used, length, copy;
6319 length = strlen(src);
6320 if (size > 0 && used < size - 1) {
6321 copy = (length >= size - used) ? size - used - 1 : length;
6322 memcpy(dst + used, src, copy);
6323 dst[used + copy] = '\0';
6325 return used + length;
6331 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
6333 Size_t length, copy;
6335 length = strlen(src);
6337 copy = (length >= size) ? size - 1 : length;
6338 memcpy(dst, src, copy);
6345 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
6346 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
6347 long _ftol( double ); /* Defined by VC6 C libs. */
6348 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
6351 PERL_STATIC_INLINE bool
6352 S_gv_has_usable_name(pTHX_ GV *gv)
6356 && HvENAME(GvSTASH(gv))
6357 && (gvp = (GV **)hv_fetch(
6358 GvSTASH(gv), GvNAME(gv),
6359 GvNAMEUTF8(gv) ? -GvNAMELEN(gv) : GvNAMELEN(gv), 0
6365 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
6368 SV * const dbsv = GvSVn(PL_DBsub);
6369 const bool save_taint = TAINT_get; /* Accepted unused var warning under NO_TAINT_SUPPORT */
6371 /* When we are called from pp_goto (svp is null),
6372 * we do not care about using dbsv to call CV;
6373 * it's for informational purposes only.
6376 PERL_ARGS_ASSERT_GET_DB_SUB;
6380 if (!PERLDB_SUB_NN) {
6384 gv_efullname3(dbsv, gv, NULL);
6386 else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
6387 || strEQ(GvNAME(gv), "END")
6388 || ( /* Could be imported, and old sub redefined. */
6389 (GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv))
6391 !( (SvTYPE(*svp) == SVt_PVGV)
6392 && (GvCV((const GV *)*svp) == cv)
6393 /* Use GV from the stack as a fallback. */
6394 && S_gv_has_usable_name(aTHX_ gv = (GV *)*svp)
6398 /* GV is potentially non-unique, or contain different CV. */
6399 SV * const tmp = newRV(MUTABLE_SV(cv));
6400 sv_setsv(dbsv, tmp);
6404 sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv)));
6405 sv_catpvs(dbsv, "::");
6407 dbsv, GvNAME(gv), GvNAMELEN(gv),
6408 GvNAMEUTF8(gv) ? SV_CATUTF8 : SV_CATBYTES
6413 const int type = SvTYPE(dbsv);
6414 if (type < SVt_PVIV && type != SVt_IV)
6415 sv_upgrade(dbsv, SVt_PVIV);
6416 (void)SvIOK_on(dbsv);
6417 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
6419 TAINT_IF(save_taint);
6423 Perl_my_dirfd(pTHX_ DIR * dir) {
6425 /* Most dirfd implementations have problems when passed NULL. */
6430 #elif defined(HAS_DIR_DD_FD)
6433 Perl_die(aTHX_ PL_no_func, "dirfd");
6434 assert(0); /* NOT REACHED */
6440 Perl_get_re_arg(pTHX_ SV *sv) {
6446 sv = MUTABLE_SV(SvRV(sv));
6447 if (SvTYPE(sv) == SVt_REGEXP)
6448 return (REGEXP*) sv;
6456 * c-indentation-style: bsd
6458 * indent-tabs-mode: nil
6461 * ex: set ts=8 sts=4 sw=4 et: