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;
300 Perl_croak_memory_wrap();
301 #ifdef PERL_TRACK_MEMPOOL
302 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
305 Perl_croak_memory_wrap();
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 /* saves machine code for a common noreturn idiom typically used in Newx*() */
1619 Perl_croak_memory_wrap(void)
1621 Perl_croak_nocontext("%s",PL_memory_wrap);
1625 /* does not return, used only in POPSTACK */
1627 Perl_croak_popstack(void)
1630 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
1635 =for apidoc Am|void|warn_sv|SV *baseex
1637 This is an XS interface to Perl's C<warn> function.
1639 C<baseex> is the error message or object. If it is a reference, it
1640 will be used as-is. Otherwise it is used as a string, and if it does
1641 not end with a newline then it will be extended with some indication of
1642 the current location in the code, as described for L</mess_sv>.
1644 The error message or object will by default be written to standard error,
1645 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1647 To warn with a simple string message, the L</warn> function may be
1654 Perl_warn_sv(pTHX_ SV *baseex)
1656 SV *ex = mess_sv(baseex, 0);
1657 PERL_ARGS_ASSERT_WARN_SV;
1658 if (!invoke_exception_hook(ex, TRUE))
1659 write_to_stderr(ex);
1663 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1665 This is an XS interface to Perl's C<warn> function.
1667 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1668 argument list. These are used to generate a string message. If the
1669 message does not end with a newline, then it will be extended with
1670 some indication of the current location in the code, as described for
1673 The error message or object will by default be written to standard error,
1674 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1676 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1682 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1684 SV *ex = vmess(pat, args);
1685 PERL_ARGS_ASSERT_VWARN;
1686 if (!invoke_exception_hook(ex, TRUE))
1687 write_to_stderr(ex);
1691 =for apidoc Am|void|warn|const char *pat|...
1693 This is an XS interface to Perl's C<warn> function.
1695 Take a sprintf-style format pattern and argument list. These are used to
1696 generate a string message. If the message does not end with a newline,
1697 then it will be extended with some indication of the current location
1698 in the code, as described for L</mess_sv>.
1700 The error message or object will by default be written to standard error,
1701 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1703 Unlike with L</croak>, C<pat> is not permitted to be null.
1708 #if defined(PERL_IMPLICIT_CONTEXT)
1710 Perl_warn_nocontext(const char *pat, ...)
1714 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1715 va_start(args, pat);
1719 #endif /* PERL_IMPLICIT_CONTEXT */
1722 Perl_warn(pTHX_ const char *pat, ...)
1725 PERL_ARGS_ASSERT_WARN;
1726 va_start(args, pat);
1731 #if defined(PERL_IMPLICIT_CONTEXT)
1733 Perl_warner_nocontext(U32 err, const char *pat, ...)
1737 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1738 va_start(args, pat);
1739 vwarner(err, pat, &args);
1742 #endif /* PERL_IMPLICIT_CONTEXT */
1745 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1747 PERL_ARGS_ASSERT_CK_WARNER_D;
1749 if (Perl_ckwarn_d(aTHX_ err)) {
1751 va_start(args, pat);
1752 vwarner(err, pat, &args);
1758 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1760 PERL_ARGS_ASSERT_CK_WARNER;
1762 if (Perl_ckwarn(aTHX_ err)) {
1764 va_start(args, pat);
1765 vwarner(err, pat, &args);
1771 Perl_warner(pTHX_ U32 err, const char* pat,...)
1774 PERL_ARGS_ASSERT_WARNER;
1775 va_start(args, pat);
1776 vwarner(err, pat, &args);
1781 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1784 PERL_ARGS_ASSERT_VWARNER;
1785 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1786 SV * const msv = vmess(pat, args);
1788 invoke_exception_hook(msv, FALSE);
1792 Perl_vwarn(aTHX_ pat, args);
1796 /* implements the ckWARN? macros */
1799 Perl_ckwarn(pTHX_ U32 w)
1802 /* If lexical warnings have not been set, use $^W. */
1804 return PL_dowarn & G_WARN_ON;
1806 return ckwarn_common(w);
1809 /* implements the ckWARN?_d macro */
1812 Perl_ckwarn_d(pTHX_ U32 w)
1815 /* If lexical warnings have not been set then default classes warn. */
1819 return ckwarn_common(w);
1823 S_ckwarn_common(pTHX_ U32 w)
1825 if (PL_curcop->cop_warnings == pWARN_ALL)
1828 if (PL_curcop->cop_warnings == pWARN_NONE)
1831 /* Check the assumption that at least the first slot is non-zero. */
1832 assert(unpackWARN1(w));
1834 /* Check the assumption that it is valid to stop as soon as a zero slot is
1836 if (!unpackWARN2(w)) {
1837 assert(!unpackWARN3(w));
1838 assert(!unpackWARN4(w));
1839 } else if (!unpackWARN3(w)) {
1840 assert(!unpackWARN4(w));
1843 /* Right, dealt with all the special cases, which are implemented as non-
1844 pointers, so there is a pointer to a real warnings mask. */
1846 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1848 } while (w >>= WARNshift);
1853 /* Set buffer=NULL to get a new one. */
1855 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1857 const MEM_SIZE len_wanted =
1858 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
1859 PERL_UNUSED_CONTEXT;
1860 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1863 (specialWARN(buffer) ?
1864 PerlMemShared_malloc(len_wanted) :
1865 PerlMemShared_realloc(buffer, len_wanted));
1867 Copy(bits, (buffer + 1), size, char);
1868 if (size < WARNsize)
1869 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
1873 /* since we've already done strlen() for both nam and val
1874 * we can use that info to make things faster than
1875 * sprintf(s, "%s=%s", nam, val)
1877 #define my_setenv_format(s, nam, nlen, val, vlen) \
1878 Copy(nam, s, nlen, char); \
1880 Copy(val, s+(nlen+1), vlen, char); \
1881 *(s+(nlen+1+vlen)) = '\0'
1883 #ifdef USE_ENVIRON_ARRAY
1884 /* VMS' my_setenv() is in vms.c */
1885 #if !defined(WIN32) && !defined(NETWARE)
1887 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1891 /* only parent thread can modify process environment */
1892 if (PL_curinterp == aTHX)
1895 #ifndef PERL_USE_SAFE_PUTENV
1896 if (!PL_use_safe_putenv) {
1897 /* most putenv()s leak, so we manipulate environ directly */
1899 const I32 len = strlen(nam);
1902 /* where does it go? */
1903 for (i = 0; environ[i]; i++) {
1904 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1908 if (environ == PL_origenviron) { /* need we copy environment? */
1914 while (environ[max])
1916 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1917 for (j=0; j<max; j++) { /* copy environment */
1918 const int len = strlen(environ[j]);
1919 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1920 Copy(environ[j], tmpenv[j], len+1, char);
1923 environ = tmpenv; /* tell exec where it is now */
1926 safesysfree(environ[i]);
1927 while (environ[i]) {
1928 environ[i] = environ[i+1];
1933 if (!environ[i]) { /* does not exist yet */
1934 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1935 environ[i+1] = NULL; /* make sure it's null terminated */
1938 safesysfree(environ[i]);
1942 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1943 /* all that work just for this */
1944 my_setenv_format(environ[i], nam, nlen, val, vlen);
1947 # if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__)
1948 # if defined(HAS_UNSETENV)
1950 (void)unsetenv(nam);
1952 (void)setenv(nam, val, 1);
1954 # else /* ! HAS_UNSETENV */
1955 (void)setenv(nam, val, 1);
1956 # endif /* HAS_UNSETENV */
1958 # if defined(HAS_UNSETENV)
1960 (void)unsetenv(nam);
1962 const int nlen = strlen(nam);
1963 const int vlen = strlen(val);
1964 char * const new_env =
1965 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1966 my_setenv_format(new_env, nam, nlen, val, vlen);
1967 (void)putenv(new_env);
1969 # else /* ! HAS_UNSETENV */
1971 const int nlen = strlen(nam);
1977 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1978 /* all that work just for this */
1979 my_setenv_format(new_env, nam, nlen, val, vlen);
1980 (void)putenv(new_env);
1981 # endif /* HAS_UNSETENV */
1982 # endif /* __CYGWIN__ */
1983 #ifndef PERL_USE_SAFE_PUTENV
1989 #else /* WIN32 || NETWARE */
1992 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1996 const int nlen = strlen(nam);
2003 Newx(envstr, nlen+vlen+2, char);
2004 my_setenv_format(envstr, nam, nlen, val, vlen);
2005 (void)PerlEnv_putenv(envstr);
2009 #endif /* WIN32 || NETWARE */
2013 #ifdef UNLINK_ALL_VERSIONS
2015 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2019 PERL_ARGS_ASSERT_UNLNK;
2021 while (PerlLIO_unlink(f) >= 0)
2023 return retries ? 0 : -1;
2027 /* this is a drop-in replacement for bcopy() */
2028 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2030 Perl_my_bcopy(const char *from, char *to, I32 len)
2032 char * const retval = to;
2034 PERL_ARGS_ASSERT_MY_BCOPY;
2038 if (from - to >= 0) {
2046 *(--to) = *(--from);
2052 /* this is a drop-in replacement for memset() */
2055 Perl_my_memset(char *loc, I32 ch, I32 len)
2057 char * const retval = loc;
2059 PERL_ARGS_ASSERT_MY_MEMSET;
2069 /* this is a drop-in replacement for bzero() */
2070 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2072 Perl_my_bzero(char *loc, I32 len)
2074 char * const retval = loc;
2076 PERL_ARGS_ASSERT_MY_BZERO;
2086 /* this is a drop-in replacement for memcmp() */
2087 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2089 Perl_my_memcmp(const char *s1, const char *s2, I32 len)
2091 const U8 *a = (const U8 *)s1;
2092 const U8 *b = (const U8 *)s2;
2095 PERL_ARGS_ASSERT_MY_MEMCMP;
2100 if ((tmp = *a++ - *b++))
2105 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2108 /* This vsprintf replacement should generally never get used, since
2109 vsprintf was available in both System V and BSD 2.11. (There may
2110 be some cross-compilation or embedded set-ups where it is needed,
2113 If you encounter a problem in this function, it's probably a symptom
2114 that Configure failed to detect your system's vprintf() function.
2115 See the section on "item vsprintf" in the INSTALL file.
2117 This version may compile on systems with BSD-ish <stdio.h>,
2118 but probably won't on others.
2121 #ifdef USE_CHAR_VSPRINTF
2126 vsprintf(char *dest, const char *pat, void *args)
2130 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2131 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2132 FILE_cnt(&fakebuf) = 32767;
2134 /* These probably won't compile -- If you really need
2135 this, you'll have to figure out some other method. */
2136 fakebuf._ptr = dest;
2137 fakebuf._cnt = 32767;
2142 fakebuf._flag = _IOWRT|_IOSTRG;
2143 _doprnt(pat, args, &fakebuf); /* what a kludge */
2144 #if defined(STDIO_PTR_LVALUE)
2145 *(FILE_ptr(&fakebuf)++) = '\0';
2147 /* PerlIO has probably #defined away fputc, but we want it here. */
2149 # undef fputc /* XXX Should really restore it later */
2151 (void)fputc('\0', &fakebuf);
2153 #ifdef USE_CHAR_VSPRINTF
2156 return 0; /* perl doesn't use return value */
2160 #endif /* HAS_VPRINTF */
2163 #if BYTEORDER != 0x4321
2165 Perl_my_swap(pTHX_ short s)
2167 #if (BYTEORDER & 1) == 0
2170 result = ((s & 255) << 8) + ((s >> 8) & 255);
2178 Perl_my_htonl(pTHX_ long l)
2182 char c[sizeof(long)];
2185 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2186 #if BYTEORDER == 0x12345678
2189 u.c[0] = (l >> 24) & 255;
2190 u.c[1] = (l >> 16) & 255;
2191 u.c[2] = (l >> 8) & 255;
2195 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2196 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2201 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2202 u.c[o & 0xf] = (l >> s) & 255;
2210 Perl_my_ntohl(pTHX_ long l)
2214 char c[sizeof(long)];
2217 #if BYTEORDER == 0x1234
2218 u.c[0] = (l >> 24) & 255;
2219 u.c[1] = (l >> 16) & 255;
2220 u.c[2] = (l >> 8) & 255;
2224 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2225 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2232 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2233 l |= (u.c[o & 0xf] & 255) << s;
2240 #endif /* BYTEORDER != 0x4321 */
2244 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2245 * If these functions are defined,
2246 * the BYTEORDER is neither 0x1234 nor 0x4321.
2247 * However, this is not assumed.
2251 #define HTOLE(name,type) \
2257 char c[sizeof(type)]; \
2261 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2262 u.c[i] = (n >> s) & 0xFF; \
2267 #define LETOH(name,type) \
2273 char c[sizeof(type)]; \
2279 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2280 n |= ((type)(u.c[i] & 0xFF)) << s; \
2286 * Big-endian byte order functions.
2289 #define HTOBE(name,type) \
2295 char c[sizeof(type)]; \
2298 U32 s = 8*(sizeof(u.c)-1); \
2299 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2300 u.c[i] = (n >> s) & 0xFF; \
2305 #define BETOH(name,type) \
2311 char c[sizeof(type)]; \
2314 U32 s = 8*(sizeof(u.c)-1); \
2317 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2318 n |= ((type)(u.c[i] & 0xFF)) << s; \
2324 * If we just can't do it...
2327 #define NOT_AVAIL(name,type) \
2331 Perl_croak_nocontext(#name "() not available"); \
2332 return n; /* not reached */ \
2336 #if defined(HAS_HTOVS) && !defined(htovs)
2339 #if defined(HAS_HTOVL) && !defined(htovl)
2342 #if defined(HAS_VTOHS) && !defined(vtohs)
2345 #if defined(HAS_VTOHL) && !defined(vtohl)
2349 #ifdef PERL_NEED_MY_HTOLE16
2351 HTOLE(Perl_my_htole16,U16)
2353 NOT_AVAIL(Perl_my_htole16,U16)
2356 #ifdef PERL_NEED_MY_LETOH16
2358 LETOH(Perl_my_letoh16,U16)
2360 NOT_AVAIL(Perl_my_letoh16,U16)
2363 #ifdef PERL_NEED_MY_HTOBE16
2365 HTOBE(Perl_my_htobe16,U16)
2367 NOT_AVAIL(Perl_my_htobe16,U16)
2370 #ifdef PERL_NEED_MY_BETOH16
2372 BETOH(Perl_my_betoh16,U16)
2374 NOT_AVAIL(Perl_my_betoh16,U16)
2378 #ifdef PERL_NEED_MY_HTOLE32
2380 HTOLE(Perl_my_htole32,U32)
2382 NOT_AVAIL(Perl_my_htole32,U32)
2385 #ifdef PERL_NEED_MY_LETOH32
2387 LETOH(Perl_my_letoh32,U32)
2389 NOT_AVAIL(Perl_my_letoh32,U32)
2392 #ifdef PERL_NEED_MY_HTOBE32
2394 HTOBE(Perl_my_htobe32,U32)
2396 NOT_AVAIL(Perl_my_htobe32,U32)
2399 #ifdef PERL_NEED_MY_BETOH32
2401 BETOH(Perl_my_betoh32,U32)
2403 NOT_AVAIL(Perl_my_betoh32,U32)
2407 #ifdef PERL_NEED_MY_HTOLE64
2409 HTOLE(Perl_my_htole64,U64)
2411 NOT_AVAIL(Perl_my_htole64,U64)
2414 #ifdef PERL_NEED_MY_LETOH64
2416 LETOH(Perl_my_letoh64,U64)
2418 NOT_AVAIL(Perl_my_letoh64,U64)
2421 #ifdef PERL_NEED_MY_HTOBE64
2423 HTOBE(Perl_my_htobe64,U64)
2425 NOT_AVAIL(Perl_my_htobe64,U64)
2428 #ifdef PERL_NEED_MY_BETOH64
2430 BETOH(Perl_my_betoh64,U64)
2432 NOT_AVAIL(Perl_my_betoh64,U64)
2436 #ifdef PERL_NEED_MY_HTOLES
2437 HTOLE(Perl_my_htoles,short)
2439 #ifdef PERL_NEED_MY_LETOHS
2440 LETOH(Perl_my_letohs,short)
2442 #ifdef PERL_NEED_MY_HTOBES
2443 HTOBE(Perl_my_htobes,short)
2445 #ifdef PERL_NEED_MY_BETOHS
2446 BETOH(Perl_my_betohs,short)
2449 #ifdef PERL_NEED_MY_HTOLEI
2450 HTOLE(Perl_my_htolei,int)
2452 #ifdef PERL_NEED_MY_LETOHI
2453 LETOH(Perl_my_letohi,int)
2455 #ifdef PERL_NEED_MY_HTOBEI
2456 HTOBE(Perl_my_htobei,int)
2458 #ifdef PERL_NEED_MY_BETOHI
2459 BETOH(Perl_my_betohi,int)
2462 #ifdef PERL_NEED_MY_HTOLEL
2463 HTOLE(Perl_my_htolel,long)
2465 #ifdef PERL_NEED_MY_LETOHL
2466 LETOH(Perl_my_letohl,long)
2468 #ifdef PERL_NEED_MY_HTOBEL
2469 HTOBE(Perl_my_htobel,long)
2471 #ifdef PERL_NEED_MY_BETOHL
2472 BETOH(Perl_my_betohl,long)
2476 Perl_my_swabn(void *ptr, int n)
2478 char *s = (char *)ptr;
2479 char *e = s + (n-1);
2482 PERL_ARGS_ASSERT_MY_SWABN;
2484 for (n /= 2; n > 0; s++, e--, n--) {
2492 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2494 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2503 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2505 PERL_FLUSHALL_FOR_CHILD;
2506 This = (*mode == 'w');
2510 taint_proper("Insecure %s%s", "EXEC");
2512 if (PerlProc_pipe(p) < 0)
2514 /* Try for another pipe pair for error return */
2515 if (PerlProc_pipe(pp) >= 0)
2517 while ((pid = PerlProc_fork()) < 0) {
2518 if (errno != EAGAIN) {
2519 PerlLIO_close(p[This]);
2520 PerlLIO_close(p[that]);
2522 PerlLIO_close(pp[0]);
2523 PerlLIO_close(pp[1]);
2527 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2536 /* Close parent's end of error status pipe (if any) */
2538 PerlLIO_close(pp[0]);
2539 #if defined(HAS_FCNTL) && defined(F_SETFD)
2540 /* Close error pipe automatically if exec works */
2541 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2544 /* Now dup our end of _the_ pipe to right position */
2545 if (p[THIS] != (*mode == 'r')) {
2546 PerlLIO_dup2(p[THIS], *mode == 'r');
2547 PerlLIO_close(p[THIS]);
2548 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2549 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2552 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2553 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2554 /* No automatic close - do it by hand */
2561 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2567 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2573 do_execfree(); /* free any memory malloced by child on fork */
2575 PerlLIO_close(pp[1]);
2576 /* Keep the lower of the two fd numbers */
2577 if (p[that] < p[This]) {
2578 PerlLIO_dup2(p[This], p[that]);
2579 PerlLIO_close(p[This]);
2583 PerlLIO_close(p[that]); /* close child's end of pipe */
2585 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2586 SvUPGRADE(sv,SVt_IV);
2588 PL_forkprocess = pid;
2589 /* If we managed to get status pipe check for exec fail */
2590 if (did_pipes && pid > 0) {
2595 while (n < sizeof(int)) {
2596 n1 = PerlLIO_read(pp[0],
2597 (void*)(((char*)&errkid)+n),
2603 PerlLIO_close(pp[0]);
2605 if (n) { /* Error */
2607 PerlLIO_close(p[This]);
2608 if (n != sizeof(int))
2609 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2611 pid2 = wait4pid(pid, &status, 0);
2612 } while (pid2 == -1 && errno == EINTR);
2613 errno = errkid; /* Propagate errno from kid */
2618 PerlLIO_close(pp[0]);
2619 return PerlIO_fdopen(p[This], mode);
2621 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2622 return my_syspopen4(aTHX_ NULL, mode, n, args);
2624 Perl_croak(aTHX_ "List form of piped open not implemented");
2625 return (PerlIO *) NULL;
2630 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2631 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2633 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2640 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2644 PERL_ARGS_ASSERT_MY_POPEN;
2646 PERL_FLUSHALL_FOR_CHILD;
2649 return my_syspopen(aTHX_ cmd,mode);
2652 This = (*mode == 'w');
2654 if (doexec && TAINTING_get) {
2656 taint_proper("Insecure %s%s", "EXEC");
2658 if (PerlProc_pipe(p) < 0)
2660 if (doexec && PerlProc_pipe(pp) >= 0)
2662 while ((pid = PerlProc_fork()) < 0) {
2663 if (errno != EAGAIN) {
2664 PerlLIO_close(p[This]);
2665 PerlLIO_close(p[that]);
2667 PerlLIO_close(pp[0]);
2668 PerlLIO_close(pp[1]);
2671 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2674 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2684 PerlLIO_close(pp[0]);
2685 #if defined(HAS_FCNTL) && defined(F_SETFD)
2686 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2689 if (p[THIS] != (*mode == 'r')) {
2690 PerlLIO_dup2(p[THIS], *mode == 'r');
2691 PerlLIO_close(p[THIS]);
2692 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2693 PerlLIO_close(p[THAT]);
2696 PerlLIO_close(p[THAT]);
2699 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2706 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2711 /* may or may not use the shell */
2712 do_exec3(cmd, pp[1], did_pipes);
2715 #endif /* defined OS2 */
2717 #ifdef PERLIO_USING_CRLF
2718 /* Since we circumvent IO layers when we manipulate low-level
2719 filedescriptors directly, need to manually switch to the
2720 default, binary, low-level mode; see PerlIOBuf_open(). */
2721 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2724 #ifdef PERL_USES_PL_PIDSTATUS
2725 hv_clear(PL_pidstatus); /* we have no children */
2731 do_execfree(); /* free any memory malloced by child on vfork */
2733 PerlLIO_close(pp[1]);
2734 if (p[that] < p[This]) {
2735 PerlLIO_dup2(p[This], p[that]);
2736 PerlLIO_close(p[This]);
2740 PerlLIO_close(p[that]);
2742 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2743 SvUPGRADE(sv,SVt_IV);
2745 PL_forkprocess = pid;
2746 if (did_pipes && pid > 0) {
2751 while (n < sizeof(int)) {
2752 n1 = PerlLIO_read(pp[0],
2753 (void*)(((char*)&errkid)+n),
2759 PerlLIO_close(pp[0]);
2761 if (n) { /* Error */
2763 PerlLIO_close(p[This]);
2764 if (n != sizeof(int))
2765 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2767 pid2 = wait4pid(pid, &status, 0);
2768 } while (pid2 == -1 && errno == EINTR);
2769 errno = errkid; /* Propagate errno from kid */
2774 PerlLIO_close(pp[0]);
2775 return PerlIO_fdopen(p[This], mode);
2779 FILE *djgpp_popen();
2781 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2783 PERL_FLUSHALL_FOR_CHILD;
2784 /* Call system's popen() to get a FILE *, then import it.
2785 used 0 for 2nd parameter to PerlIO_importFILE;
2788 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2791 #if defined(__LIBCATAMOUNT__)
2793 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2800 #endif /* !DOSISH */
2802 /* this is called in parent before the fork() */
2804 Perl_atfork_lock(void)
2807 #if defined(USE_ITHREADS)
2808 /* locks must be held in locking order (if any) */
2810 MUTEX_LOCK(&PL_perlio_mutex);
2813 MUTEX_LOCK(&PL_malloc_mutex);
2819 /* this is called in both parent and child after the fork() */
2821 Perl_atfork_unlock(void)
2824 #if defined(USE_ITHREADS)
2825 /* locks must be released in same order as in atfork_lock() */
2827 MUTEX_UNLOCK(&PL_perlio_mutex);
2830 MUTEX_UNLOCK(&PL_malloc_mutex);
2839 #if defined(HAS_FORK)
2841 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2846 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2847 * handlers elsewhere in the code */
2852 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2853 Perl_croak_nocontext("fork() not available");
2855 #endif /* HAS_FORK */
2860 Perl_dump_fds(pTHX_ const char *const s)
2865 PERL_ARGS_ASSERT_DUMP_FDS;
2867 PerlIO_printf(Perl_debug_log,"%s", s);
2868 for (fd = 0; fd < 32; fd++) {
2869 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2870 PerlIO_printf(Perl_debug_log," %d",fd);
2872 PerlIO_printf(Perl_debug_log,"\n");
2875 #endif /* DUMP_FDS */
2879 dup2(int oldfd, int newfd)
2881 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2884 PerlLIO_close(newfd);
2885 return fcntl(oldfd, F_DUPFD, newfd);
2887 #define DUP2_MAX_FDS 256
2888 int fdtmp[DUP2_MAX_FDS];
2894 PerlLIO_close(newfd);
2895 /* good enough for low fd's... */
2896 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2897 if (fdx >= DUP2_MAX_FDS) {
2905 PerlLIO_close(fdtmp[--fdx]);
2912 #ifdef HAS_SIGACTION
2915 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2918 struct sigaction act, oact;
2921 /* only "parent" interpreter can diddle signals */
2922 if (PL_curinterp != aTHX)
2923 return (Sighandler_t) SIG_ERR;
2926 act.sa_handler = (void(*)(int))handler;
2927 sigemptyset(&act.sa_mask);
2930 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2931 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2933 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2934 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2935 act.sa_flags |= SA_NOCLDWAIT;
2937 if (sigaction(signo, &act, &oact) == -1)
2938 return (Sighandler_t) SIG_ERR;
2940 return (Sighandler_t) oact.sa_handler;
2944 Perl_rsignal_state(pTHX_ int signo)
2946 struct sigaction oact;
2947 PERL_UNUSED_CONTEXT;
2949 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2950 return (Sighandler_t) SIG_ERR;
2952 return (Sighandler_t) oact.sa_handler;
2956 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2959 struct sigaction act;
2961 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2964 /* only "parent" interpreter can diddle signals */
2965 if (PL_curinterp != aTHX)
2969 act.sa_handler = (void(*)(int))handler;
2970 sigemptyset(&act.sa_mask);
2973 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2974 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2976 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2977 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2978 act.sa_flags |= SA_NOCLDWAIT;
2980 return sigaction(signo, &act, save);
2984 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2988 /* only "parent" interpreter can diddle signals */
2989 if (PL_curinterp != aTHX)
2993 return sigaction(signo, save, (struct sigaction *)NULL);
2996 #else /* !HAS_SIGACTION */
2999 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3001 #if defined(USE_ITHREADS) && !defined(WIN32)
3002 /* only "parent" interpreter can diddle signals */
3003 if (PL_curinterp != aTHX)
3004 return (Sighandler_t) SIG_ERR;
3007 return PerlProc_signal(signo, handler);
3018 Perl_rsignal_state(pTHX_ int signo)
3021 Sighandler_t oldsig;
3023 #if defined(USE_ITHREADS) && !defined(WIN32)
3024 /* only "parent" interpreter can diddle signals */
3025 if (PL_curinterp != aTHX)
3026 return (Sighandler_t) SIG_ERR;
3030 oldsig = PerlProc_signal(signo, sig_trap);
3031 PerlProc_signal(signo, oldsig);
3033 PerlProc_kill(PerlProc_getpid(), signo);
3038 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3040 #if defined(USE_ITHREADS) && !defined(WIN32)
3041 /* only "parent" interpreter can diddle signals */
3042 if (PL_curinterp != aTHX)
3045 *save = PerlProc_signal(signo, handler);
3046 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3050 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3052 #if defined(USE_ITHREADS) && !defined(WIN32)
3053 /* only "parent" interpreter can diddle signals */
3054 if (PL_curinterp != aTHX)
3057 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3060 #endif /* !HAS_SIGACTION */
3061 #endif /* !PERL_MICRO */
3063 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3064 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
3066 Perl_my_pclose(pTHX_ PerlIO *ptr)
3069 Sigsave_t hstat, istat, qstat;
3076 const int fd = PerlIO_fileno(ptr);
3079 /* Find out whether the refcount is low enough for us to wait for the
3080 child proc without blocking. */
3081 const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
3083 const bool should_wait = 1;
3086 svp = av_fetch(PL_fdpid,fd,TRUE);
3087 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3089 *svp = &PL_sv_undef;
3091 if (pid == -1) { /* Opened by popen. */
3092 return my_syspclose(ptr);
3095 close_failed = (PerlIO_close(ptr) == EOF);
3098 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3099 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3100 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3102 if (should_wait) do {
3103 pid2 = wait4pid(pid, &status, 0);
3104 } while (pid2 == -1 && errno == EINTR);
3106 rsignal_restore(SIGHUP, &hstat);
3107 rsignal_restore(SIGINT, &istat);
3108 rsignal_restore(SIGQUIT, &qstat);
3116 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3121 #if defined(__LIBCATAMOUNT__)
3123 Perl_my_pclose(pTHX_ PerlIO *ptr)
3128 #endif /* !DOSISH */
3130 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3132 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3136 PERL_ARGS_ASSERT_WAIT4PID;
3139 #ifdef PERL_USES_PL_PIDSTATUS
3142 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3143 pid, rather than a string form. */
3144 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3145 if (svp && *svp != &PL_sv_undef) {
3146 *statusp = SvIVX(*svp);
3147 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3155 hv_iterinit(PL_pidstatus);
3156 if ((entry = hv_iternext(PL_pidstatus))) {
3157 SV * const sv = hv_iterval(PL_pidstatus,entry);
3159 const char * const spid = hv_iterkey(entry,&len);
3161 assert (len == sizeof(Pid_t));
3162 memcpy((char *)&pid, spid, len);
3163 *statusp = SvIVX(sv);
3164 /* The hash iterator is currently on this entry, so simply
3165 calling hv_delete would trigger the lazy delete, which on
3166 aggregate does more work, beacuse next call to hv_iterinit()
3167 would spot the flag, and have to call the delete routine,
3168 while in the meantime any new entries can't re-use that
3170 hv_iterinit(PL_pidstatus);
3171 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3178 # ifdef HAS_WAITPID_RUNTIME
3179 if (!HAS_WAITPID_RUNTIME)
3182 result = PerlProc_waitpid(pid,statusp,flags);
3185 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3186 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3189 #ifdef PERL_USES_PL_PIDSTATUS
3190 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3195 Perl_croak(aTHX_ "Can't do waitpid with flags");
3197 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3198 pidgone(result,*statusp);
3204 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3207 if (result < 0 && errno == EINTR) {
3209 errno = EINTR; /* reset in case a signal handler changed $! */
3213 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3215 #ifdef PERL_USES_PL_PIDSTATUS
3217 S_pidgone(pTHX_ Pid_t pid, int status)
3221 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3222 SvUPGRADE(sv,SVt_IV);
3223 SvIV_set(sv, status);
3231 int /* Cannot prototype with I32
3233 my_syspclose(PerlIO *ptr)
3236 Perl_my_pclose(pTHX_ PerlIO *ptr)
3239 /* Needs work for PerlIO ! */
3240 FILE * const f = PerlIO_findFILE(ptr);
3241 const I32 result = pclose(f);
3242 PerlIO_releaseFILE(ptr,f);
3250 Perl_my_pclose(pTHX_ PerlIO *ptr)
3252 /* Needs work for PerlIO ! */
3253 FILE * const f = PerlIO_findFILE(ptr);
3254 I32 result = djgpp_pclose(f);
3255 result = (result << 8) & 0xff00;
3256 PerlIO_releaseFILE(ptr,f);
3261 #define PERL_REPEATCPY_LINEAR 4
3263 Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
3265 PERL_ARGS_ASSERT_REPEATCPY;
3270 Perl_croak_memory_wrap();
3273 memset(to, *from, count);
3276 IV items, linear, half;
3278 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3279 for (items = 0; items < linear; ++items) {
3280 const char *q = from;
3282 for (todo = len; todo > 0; todo--)
3287 while (items <= half) {
3288 IV size = items * len;
3289 memcpy(p, to, size);
3295 memcpy(p, to, (count - items) * len);
3301 Perl_same_dirent(pTHX_ const char *a, const char *b)
3303 char *fa = strrchr(a,'/');
3304 char *fb = strrchr(b,'/');
3307 SV * const tmpsv = sv_newmortal();
3309 PERL_ARGS_ASSERT_SAME_DIRENT;
3322 sv_setpvs(tmpsv, ".");
3324 sv_setpvn(tmpsv, a, fa - a);
3325 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3328 sv_setpvs(tmpsv, ".");
3330 sv_setpvn(tmpsv, b, fb - b);
3331 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3333 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3334 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3336 #endif /* !HAS_RENAME */
3339 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3340 const char *const *const search_ext, I32 flags)
3343 const char *xfound = NULL;
3344 char *xfailed = NULL;
3345 char tmpbuf[MAXPATHLEN];
3350 #if defined(DOSISH) && !defined(OS2)
3351 # define SEARCH_EXTS ".bat", ".cmd", NULL
3352 # define MAX_EXT_LEN 4
3355 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3356 # define MAX_EXT_LEN 4
3359 # define SEARCH_EXTS ".pl", ".com", NULL
3360 # define MAX_EXT_LEN 4
3362 /* additional extensions to try in each dir if scriptname not found */
3364 static const char *const exts[] = { SEARCH_EXTS };
3365 const char *const *const ext = search_ext ? search_ext : exts;
3366 int extidx = 0, i = 0;
3367 const char *curext = NULL;
3369 PERL_UNUSED_ARG(search_ext);
3370 # define MAX_EXT_LEN 0
3373 PERL_ARGS_ASSERT_FIND_SCRIPT;
3376 * If dosearch is true and if scriptname does not contain path
3377 * delimiters, search the PATH for scriptname.
3379 * If SEARCH_EXTS is also defined, will look for each
3380 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3381 * while searching the PATH.
3383 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3384 * proceeds as follows:
3385 * If DOSISH or VMSISH:
3386 * + look for ./scriptname{,.foo,.bar}
3387 * + search the PATH for scriptname{,.foo,.bar}
3390 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3391 * this will not look in '.' if it's not in the PATH)
3396 # ifdef ALWAYS_DEFTYPES
3397 len = strlen(scriptname);
3398 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3399 int idx = 0, deftypes = 1;
3402 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3405 int idx = 0, deftypes = 1;
3408 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3410 /* The first time through, just add SEARCH_EXTS to whatever we
3411 * already have, so we can check for default file types. */
3413 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3419 if ((strlen(tmpbuf) + strlen(scriptname)
3420 + MAX_EXT_LEN) >= sizeof tmpbuf)
3421 continue; /* don't search dir with too-long name */
3422 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3426 if (strEQ(scriptname, "-"))
3428 if (dosearch) { /* Look in '.' first. */
3429 const char *cur = scriptname;
3431 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3433 if (strEQ(ext[i++],curext)) {
3434 extidx = -1; /* already has an ext */
3439 DEBUG_p(PerlIO_printf(Perl_debug_log,
3440 "Looking for %s\n",cur));
3441 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3442 && !S_ISDIR(PL_statbuf.st_mode)) {
3450 if (cur == scriptname) {
3451 len = strlen(scriptname);
3452 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3454 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3457 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3458 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3463 if (dosearch && !strchr(scriptname, '/')
3465 && !strchr(scriptname, '\\')
3467 && (s = PerlEnv_getenv("PATH")))
3471 bufend = s + strlen(s);
3472 while (s < bufend) {
3475 && *s != ';'; len++, s++) {
3476 if (len < sizeof tmpbuf)
3479 if (len < sizeof tmpbuf)
3482 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3488 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3489 continue; /* don't search dir with too-long name */
3492 && tmpbuf[len - 1] != '/'
3493 && tmpbuf[len - 1] != '\\'
3496 tmpbuf[len++] = '/';
3497 if (len == 2 && tmpbuf[0] == '.')
3499 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3503 len = strlen(tmpbuf);
3504 if (extidx > 0) /* reset after previous loop */
3508 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3509 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3510 if (S_ISDIR(PL_statbuf.st_mode)) {
3514 } while ( retval < 0 /* not there */
3515 && extidx>=0 && ext[extidx] /* try an extension? */
3516 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3521 if (S_ISREG(PL_statbuf.st_mode)
3522 && cando(S_IRUSR,TRUE,&PL_statbuf)
3523 #if !defined(DOSISH)
3524 && cando(S_IXUSR,TRUE,&PL_statbuf)
3528 xfound = tmpbuf; /* bingo! */
3532 xfailed = savepv(tmpbuf);
3535 if (!xfound && !seen_dot && !xfailed &&
3536 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3537 || S_ISDIR(PL_statbuf.st_mode)))
3539 seen_dot = 1; /* Disable message. */
3541 if (flags & 1) { /* do or die? */
3542 /* diag_listed_as: Can't execute %s */
3543 Perl_croak(aTHX_ "Can't %s %s%s%s",
3544 (xfailed ? "execute" : "find"),
3545 (xfailed ? xfailed : scriptname),
3546 (xfailed ? "" : " on PATH"),
3547 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3552 scriptname = xfound;
3554 return (scriptname ? savepv(scriptname) : NULL);
3557 #ifndef PERL_GET_CONTEXT_DEFINED
3560 Perl_get_context(void)
3563 #if defined(USE_ITHREADS)
3564 # ifdef OLD_PTHREADS_API
3566 int error = pthread_getspecific(PL_thr_key, &t)
3568 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3571 # ifdef I_MACH_CTHREADS
3572 return (void*)cthread_data(cthread_self());
3574 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3583 Perl_set_context(void *t)
3586 PERL_ARGS_ASSERT_SET_CONTEXT;
3587 #if defined(USE_ITHREADS)
3588 # ifdef I_MACH_CTHREADS
3589 cthread_set_data(cthread_self(), t);
3592 const int error = pthread_setspecific(PL_thr_key, t);
3594 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3602 #endif /* !PERL_GET_CONTEXT_DEFINED */
3604 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3613 Perl_get_op_names(pTHX)
3615 PERL_UNUSED_CONTEXT;
3616 return (char **)PL_op_name;
3620 Perl_get_op_descs(pTHX)
3622 PERL_UNUSED_CONTEXT;
3623 return (char **)PL_op_desc;
3627 Perl_get_no_modify(pTHX)
3629 PERL_UNUSED_CONTEXT;
3630 return PL_no_modify;
3634 Perl_get_opargs(pTHX)
3636 PERL_UNUSED_CONTEXT;
3637 return (U32 *)PL_opargs;
3641 Perl_get_ppaddr(pTHX)
3644 PERL_UNUSED_CONTEXT;
3645 return (PPADDR_t*)PL_ppaddr;
3648 #ifndef HAS_GETENV_LEN
3650 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3652 char * const env_trans = PerlEnv_getenv(env_elem);
3653 PERL_UNUSED_CONTEXT;
3654 PERL_ARGS_ASSERT_GETENV_LEN;
3656 *len = strlen(env_trans);
3663 Perl_get_vtbl(pTHX_ int vtbl_id)
3665 PERL_UNUSED_CONTEXT;
3667 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3668 ? NULL : PL_magic_vtables + vtbl_id;
3672 Perl_my_fflush_all(pTHX)
3674 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3675 return PerlIO_flush(NULL);
3677 # if defined(HAS__FWALK)
3678 extern int fflush(FILE *);
3679 /* undocumented, unprototyped, but very useful BSDism */
3680 extern void _fwalk(int (*)(FILE *));
3684 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3686 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3687 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3689 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3690 open_max = sysconf(_SC_OPEN_MAX);
3693 open_max = FOPEN_MAX;
3696 open_max = OPEN_MAX;
3707 for (i = 0; i < open_max; i++)
3708 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3709 STDIO_STREAM_ARRAY[i]._file < open_max &&
3710 STDIO_STREAM_ARRAY[i]._flag)
3711 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3715 SETERRNO(EBADF,RMS_IFI);
3722 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3724 if (ckWARN(WARN_IO)) {
3726 = gv && (isGV_with_GP(gv))
3729 const char * const direction = have == '>' ? "out" : "in";
3731 if (name && HEK_LEN(name))
3732 Perl_warner(aTHX_ packWARN(WARN_IO),
3733 "Filehandle %"HEKf" opened only for %sput",
3736 Perl_warner(aTHX_ packWARN(WARN_IO),
3737 "Filehandle opened only for %sput", direction);
3742 Perl_report_evil_fh(pTHX_ const GV *gv)
3744 const IO *io = gv ? GvIO(gv) : NULL;
3745 const PERL_BITFIELD16 op = PL_op->op_type;
3749 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3751 warn_type = WARN_CLOSED;
3755 warn_type = WARN_UNOPENED;
3758 if (ckWARN(warn_type)) {
3760 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3761 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3762 const char * const pars =
3763 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3764 const char * const func =
3766 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3767 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3769 const char * const type =
3771 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3772 ? "socket" : "filehandle");
3773 const bool have_name = name && SvCUR(name);
3774 Perl_warner(aTHX_ packWARN(warn_type),
3775 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3776 have_name ? " " : "",
3777 SVfARG(have_name ? name : &PL_sv_no));
3778 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3780 aTHX_ packWARN(warn_type),
3781 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3782 func, pars, have_name ? " " : "",
3783 SVfARG(have_name ? name : &PL_sv_no)
3788 /* To workaround core dumps from the uninitialised tm_zone we get the
3789 * system to give us a reasonable struct to copy. This fix means that
3790 * strftime uses the tm_zone and tm_gmtoff values returned by
3791 * localtime(time()). That should give the desired result most of the
3792 * time. But probably not always!
3794 * This does not address tzname aspects of NETaa14816.
3799 # ifndef STRUCT_TM_HASZONE
3800 # define STRUCT_TM_HASZONE
3804 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3805 # ifndef HAS_TM_TM_ZONE
3806 # define HAS_TM_TM_ZONE
3811 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3813 #ifdef HAS_TM_TM_ZONE
3815 const struct tm* my_tm;
3816 PERL_ARGS_ASSERT_INIT_TM;
3818 my_tm = localtime(&now);
3820 Copy(my_tm, ptm, 1, struct tm);
3822 PERL_ARGS_ASSERT_INIT_TM;
3823 PERL_UNUSED_ARG(ptm);
3828 * mini_mktime - normalise struct tm values without the localtime()
3829 * semantics (and overhead) of mktime().
3832 Perl_mini_mktime(pTHX_ struct tm *ptm)
3836 int month, mday, year, jday;
3837 int odd_cent, odd_year;
3838 PERL_UNUSED_CONTEXT;
3840 PERL_ARGS_ASSERT_MINI_MKTIME;
3842 #define DAYS_PER_YEAR 365
3843 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3844 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3845 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3846 #define SECS_PER_HOUR (60*60)
3847 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3848 /* parentheses deliberately absent on these two, otherwise they don't work */
3849 #define MONTH_TO_DAYS 153/5
3850 #define DAYS_TO_MONTH 5/153
3851 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3852 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3853 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3854 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3857 * Year/day algorithm notes:
3859 * With a suitable offset for numeric value of the month, one can find
3860 * an offset into the year by considering months to have 30.6 (153/5) days,
3861 * using integer arithmetic (i.e., with truncation). To avoid too much
3862 * messing about with leap days, we consider January and February to be
3863 * the 13th and 14th month of the previous year. After that transformation,
3864 * we need the month index we use to be high by 1 from 'normal human' usage,
3865 * so the month index values we use run from 4 through 15.
3867 * Given that, and the rules for the Gregorian calendar (leap years are those
3868 * divisible by 4 unless also divisible by 100, when they must be divisible
3869 * by 400 instead), we can simply calculate the number of days since some
3870 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3871 * the days we derive from our month index, and adding in the day of the
3872 * month. The value used here is not adjusted for the actual origin which
3873 * it normally would use (1 January A.D. 1), since we're not exposing it.
3874 * We're only building the value so we can turn around and get the
3875 * normalised values for the year, month, day-of-month, and day-of-year.
3877 * For going backward, we need to bias the value we're using so that we find
3878 * the right year value. (Basically, we don't want the contribution of
3879 * March 1st to the number to apply while deriving the year). Having done
3880 * that, we 'count up' the contribution to the year number by accounting for
3881 * full quadracenturies (400-year periods) with their extra leap days, plus
3882 * the contribution from full centuries (to avoid counting in the lost leap
3883 * days), plus the contribution from full quad-years (to count in the normal
3884 * leap days), plus the leftover contribution from any non-leap years.
3885 * At this point, if we were working with an actual leap day, we'll have 0
3886 * days left over. This is also true for March 1st, however. So, we have
3887 * to special-case that result, and (earlier) keep track of the 'odd'
3888 * century and year contributions. If we got 4 extra centuries in a qcent,
3889 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3890 * Otherwise, we add back in the earlier bias we removed (the 123 from
3891 * figuring in March 1st), find the month index (integer division by 30.6),
3892 * and the remainder is the day-of-month. We then have to convert back to
3893 * 'real' months (including fixing January and February from being 14/15 in
3894 * the previous year to being in the proper year). After that, to get
3895 * tm_yday, we work with the normalised year and get a new yearday value for
3896 * January 1st, which we subtract from the yearday value we had earlier,
3897 * representing the date we've re-built. This is done from January 1
3898 * because tm_yday is 0-origin.
3900 * Since POSIX time routines are only guaranteed to work for times since the
3901 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3902 * applies Gregorian calendar rules even to dates before the 16th century
3903 * doesn't bother me. Besides, you'd need cultural context for a given
3904 * date to know whether it was Julian or Gregorian calendar, and that's
3905 * outside the scope for this routine. Since we convert back based on the
3906 * same rules we used to build the yearday, you'll only get strange results
3907 * for input which needed normalising, or for the 'odd' century years which
3908 * were leap years in the Julian calendar but not in the Gregorian one.
3909 * I can live with that.
3911 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3912 * that's still outside the scope for POSIX time manipulation, so I don't
3916 year = 1900 + ptm->tm_year;
3917 month = ptm->tm_mon;
3918 mday = ptm->tm_mday;
3924 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3925 yearday += month*MONTH_TO_DAYS + mday + jday;
3927 * Note that we don't know when leap-seconds were or will be,
3928 * so we have to trust the user if we get something which looks
3929 * like a sensible leap-second. Wild values for seconds will
3930 * be rationalised, however.
3932 if ((unsigned) ptm->tm_sec <= 60) {
3939 secs += 60 * ptm->tm_min;
3940 secs += SECS_PER_HOUR * ptm->tm_hour;
3942 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3943 /* got negative remainder, but need positive time */
3944 /* back off an extra day to compensate */
3945 yearday += (secs/SECS_PER_DAY)-1;
3946 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3949 yearday += (secs/SECS_PER_DAY);
3950 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3953 else if (secs >= SECS_PER_DAY) {
3954 yearday += (secs/SECS_PER_DAY);
3955 secs %= SECS_PER_DAY;
3957 ptm->tm_hour = secs/SECS_PER_HOUR;
3958 secs %= SECS_PER_HOUR;
3959 ptm->tm_min = secs/60;
3961 ptm->tm_sec += secs;
3962 /* done with time of day effects */
3964 * The algorithm for yearday has (so far) left it high by 428.
3965 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3966 * bias it by 123 while trying to figure out what year it
3967 * really represents. Even with this tweak, the reverse
3968 * translation fails for years before A.D. 0001.
3969 * It would still fail for Feb 29, but we catch that one below.
3971 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3972 yearday -= YEAR_ADJUST;
3973 year = (yearday / DAYS_PER_QCENT) * 400;
3974 yearday %= DAYS_PER_QCENT;
3975 odd_cent = yearday / DAYS_PER_CENT;
3976 year += odd_cent * 100;
3977 yearday %= DAYS_PER_CENT;
3978 year += (yearday / DAYS_PER_QYEAR) * 4;
3979 yearday %= DAYS_PER_QYEAR;
3980 odd_year = yearday / DAYS_PER_YEAR;
3982 yearday %= DAYS_PER_YEAR;
3983 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3988 yearday += YEAR_ADJUST; /* recover March 1st crock */
3989 month = yearday*DAYS_TO_MONTH;
3990 yearday -= month*MONTH_TO_DAYS;
3991 /* recover other leap-year adjustment */
4000 ptm->tm_year = year - 1900;
4002 ptm->tm_mday = yearday;
4003 ptm->tm_mon = month;
4007 ptm->tm_mon = month - 1;
4009 /* re-build yearday based on Jan 1 to get tm_yday */
4011 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4012 yearday += 14*MONTH_TO_DAYS + 1;
4013 ptm->tm_yday = jday - yearday;
4014 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4018 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)
4026 PERL_ARGS_ASSERT_MY_STRFTIME;
4028 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4031 mytm.tm_hour = hour;
4032 mytm.tm_mday = mday;
4034 mytm.tm_year = year;
4035 mytm.tm_wday = wday;
4036 mytm.tm_yday = yday;
4037 mytm.tm_isdst = isdst;
4039 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4040 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4045 #ifdef HAS_TM_TM_GMTOFF
4046 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4048 #ifdef HAS_TM_TM_ZONE
4049 mytm.tm_zone = mytm2.tm_zone;
4054 Newx(buf, buflen, char);
4055 len = strftime(buf, buflen, fmt, &mytm);
4057 ** The following is needed to handle to the situation where
4058 ** tmpbuf overflows. Basically we want to allocate a buffer
4059 ** and try repeatedly. The reason why it is so complicated
4060 ** is that getting a return value of 0 from strftime can indicate
4061 ** one of the following:
4062 ** 1. buffer overflowed,
4063 ** 2. illegal conversion specifier, or
4064 ** 3. the format string specifies nothing to be returned(not
4065 ** an error). This could be because format is an empty string
4066 ** or it specifies %p that yields an empty string in some locale.
4067 ** If there is a better way to make it portable, go ahead by
4070 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4073 /* Possibly buf overflowed - try again with a bigger buf */
4074 const int fmtlen = strlen(fmt);
4075 int bufsize = fmtlen + buflen;
4077 Renew(buf, bufsize, char);
4079 buflen = strftime(buf, bufsize, fmt, &mytm);
4080 if (buflen > 0 && buflen < bufsize)
4082 /* heuristic to prevent out-of-memory errors */
4083 if (bufsize > 100*fmtlen) {
4089 Renew(buf, bufsize, char);
4094 Perl_croak(aTHX_ "panic: no strftime");
4100 #define SV_CWD_RETURN_UNDEF \
4101 sv_setsv(sv, &PL_sv_undef); \
4104 #define SV_CWD_ISDOT(dp) \
4105 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4106 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4109 =head1 Miscellaneous Functions
4111 =for apidoc getcwd_sv
4113 Fill the sv with current working directory
4118 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4119 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4120 * getcwd(3) if available
4121 * Comments from the orignal:
4122 * This is a faster version of getcwd. It's also more dangerous
4123 * because you might chdir out of a directory that you can't chdir
4127 Perl_getcwd_sv(pTHX_ SV *sv)
4131 #ifndef INCOMPLETE_TAINTS
4135 PERL_ARGS_ASSERT_GETCWD_SV;
4139 char buf[MAXPATHLEN];
4141 /* Some getcwd()s automatically allocate a buffer of the given
4142 * size from the heap if they are given a NULL buffer pointer.
4143 * The problem is that this behaviour is not portable. */
4144 if (getcwd(buf, sizeof(buf) - 1)) {
4149 sv_setsv(sv, &PL_sv_undef);
4157 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4161 SvUPGRADE(sv, SVt_PV);
4163 if (PerlLIO_lstat(".", &statbuf) < 0) {
4164 SV_CWD_RETURN_UNDEF;
4167 orig_cdev = statbuf.st_dev;
4168 orig_cino = statbuf.st_ino;
4178 if (PerlDir_chdir("..") < 0) {
4179 SV_CWD_RETURN_UNDEF;
4181 if (PerlLIO_stat(".", &statbuf) < 0) {
4182 SV_CWD_RETURN_UNDEF;
4185 cdev = statbuf.st_dev;
4186 cino = statbuf.st_ino;
4188 if (odev == cdev && oino == cino) {
4191 if (!(dir = PerlDir_open("."))) {
4192 SV_CWD_RETURN_UNDEF;
4195 while ((dp = PerlDir_read(dir)) != NULL) {
4197 namelen = dp->d_namlen;
4199 namelen = strlen(dp->d_name);
4202 if (SV_CWD_ISDOT(dp)) {
4206 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4207 SV_CWD_RETURN_UNDEF;
4210 tdev = statbuf.st_dev;
4211 tino = statbuf.st_ino;
4212 if (tino == oino && tdev == odev) {
4218 SV_CWD_RETURN_UNDEF;
4221 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4222 SV_CWD_RETURN_UNDEF;
4225 SvGROW(sv, pathlen + namelen + 1);
4229 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4232 /* prepend current directory to the front */
4234 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4235 pathlen += (namelen + 1);
4237 #ifdef VOID_CLOSEDIR
4240 if (PerlDir_close(dir) < 0) {
4241 SV_CWD_RETURN_UNDEF;
4247 SvCUR_set(sv, pathlen);
4251 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4252 SV_CWD_RETURN_UNDEF;
4255 if (PerlLIO_stat(".", &statbuf) < 0) {
4256 SV_CWD_RETURN_UNDEF;
4259 cdev = statbuf.st_dev;
4260 cino = statbuf.st_ino;
4262 if (cdev != orig_cdev || cino != orig_cino) {
4263 Perl_croak(aTHX_ "Unstable directory path, "
4264 "current directory changed unexpectedly");
4275 #define VERSION_MAX 0x7FFFFFFF
4278 =for apidoc prescan_version
4280 Validate that a given string can be parsed as a version object, but doesn't
4281 actually perform the parsing. Can use either strict or lax validation rules.
4282 Can optionally set a number of hint variables to save the parsing code
4283 some time when tokenizing.
4288 Perl_prescan_version(pTHX_ const char *s, bool strict,
4289 const char **errstr,
4290 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4291 bool qv = (sqv ? *sqv : FALSE);
4293 int saw_decimal = 0;
4297 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4299 if (qv && isDIGIT(*d))
4300 goto dotted_decimal_version;
4302 if (*d == 'v') { /* explicit v-string */
4307 else { /* degenerate v-string */
4308 /* requires v1.2.3 */
4309 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4312 dotted_decimal_version:
4313 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4314 /* no leading zeros allowed */
4315 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4318 while (isDIGIT(*d)) /* integer part */
4324 d++; /* decimal point */
4329 /* require v1.2.3 */
4330 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4333 goto version_prescan_finish;
4340 while (isDIGIT(*d)) { /* just keep reading */
4342 while (isDIGIT(*d)) {
4344 /* maximum 3 digits between decimal */
4345 if (strict && j > 3) {
4346 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4351 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4354 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4359 else if (*d == '.') {
4361 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4366 else if (!isDIGIT(*d)) {
4372 if (strict && i < 2) {
4373 /* requires v1.2.3 */
4374 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4377 } /* end if dotted-decimal */
4379 { /* decimal versions */
4380 int j = 0; /* may need this later */
4381 /* special strict case for leading '.' or '0' */
4384 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4386 if (*d == '0' && isDIGIT(d[1])) {
4387 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4391 /* and we never support negative versions */
4393 BADVERSION(s,errstr,"Invalid version format (negative version number)");
4396 /* consume all of the integer part */
4400 /* look for a fractional part */
4402 /* we found it, so consume it */
4406 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4409 BADVERSION(s,errstr,"Invalid version format (version required)");
4411 /* found just an integer */
4412 goto version_prescan_finish;
4414 else if ( d == s ) {
4415 /* didn't find either integer or period */
4416 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4418 else if (*d == '_') {
4419 /* underscore can't come after integer part */
4421 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4423 else if (isDIGIT(d[1])) {
4424 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4427 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4431 /* anything else after integer part is just invalid data */
4432 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4435 /* scan the fractional part after the decimal point*/
4437 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4438 /* strict or lax-but-not-the-end */
4439 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4442 while (isDIGIT(*d)) {
4444 if (*d == '.' && isDIGIT(d[-1])) {
4446 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4449 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4451 d = (char *)s; /* start all over again */
4453 goto dotted_decimal_version;
4457 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4460 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4462 if ( ! isDIGIT(d[1]) ) {
4463 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4472 version_prescan_finish:
4476 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4477 /* trailing non-numeric data */
4478 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4486 *ssaw_decimal = saw_decimal;
4493 =for apidoc scan_version
4495 Returns a pointer to the next character after the parsed
4496 version string, as well as upgrading the passed in SV to
4499 Function must be called with an already existing SV like
4502 s = scan_version(s, SV *sv, bool qv);
4504 Performs some preprocessing to the string to ensure that
4505 it has the correct characteristics of a version. Flags the
4506 object if it contains an underscore (which denotes this
4507 is an alpha version). The boolean qv denotes that the version
4508 should be interpreted as if it had multiple decimals, even if
4515 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4517 const char *start = s;
4520 const char *errstr = NULL;
4521 int saw_decimal = 0;
4528 PERL_ARGS_ASSERT_SCAN_VERSION;
4530 while (isSPACE(*s)) /* leading whitespace is OK */
4533 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4535 /* "undef" is a special case and not an error */
4536 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4538 Perl_croak(aTHX_ "%s", errstr);
4547 /* Now that we are through the prescan, start creating the object */
4549 hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4550 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4552 #ifndef NODEFAULT_SHAREKEYS
4553 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4557 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4559 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4560 if ( !qv && width < 3 )
4561 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4563 while (isDIGIT(*pos))
4565 if (!isALPHA(*pos)) {
4571 /* this is atoi() that delimits on underscores */
4572 const char *end = pos;
4576 /* the following if() will only be true after the decimal
4577 * point of a version originally created with a bare
4578 * floating point number, i.e. not quoted in any way
4580 if ( !qv && s > start && saw_decimal == 1 ) {
4584 rev += (*s - '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 %d",VERSION_MAX);
4600 while (--end >= s) {
4602 rev += (*end - '0') * mult;
4604 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4605 || (PERL_ABS(rev) > VERSION_MAX )) {
4606 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4607 "Integer overflow in version");
4616 /* Append revision */
4617 av_push(av, newSViv(rev));
4622 else if ( *pos == '.' )
4624 else if ( *pos == '_' && isDIGIT(pos[1]) )
4626 else if ( *pos == ',' && isDIGIT(pos[1]) )
4628 else if ( isDIGIT(*pos) )
4635 while ( isDIGIT(*pos) )
4640 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4648 if ( qv ) { /* quoted versions always get at least three terms*/
4649 I32 len = av_len(av);
4650 /* This for loop appears to trigger a compiler bug on OS X, as it
4651 loops infinitely. Yes, len is negative. No, it makes no sense.
4652 Compiler in question is:
4653 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4654 for ( len = 2 - len; len > 0; len-- )
4655 av_push(MUTABLE_AV(sv), newSViv(0));
4659 av_push(av, newSViv(0));
4662 /* need to save off the current version string for later */
4664 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4665 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4666 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4668 else if ( s > start ) {
4669 SV * orig = newSVpvn(start,s-start);
4670 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4671 /* need to insert a v to be consistent */
4672 sv_insert(orig, 0, 0, "v", 1);
4674 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4677 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4678 av_push(av, newSViv(0));
4681 /* And finally, store the AV in the hash */
4682 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4684 /* fix RT#19517 - special case 'undef' as string */
4685 if ( *s == 'u' && strEQ(s,"undef") ) {
4693 =for apidoc new_version
4695 Returns a new version object based on the passed in SV:
4697 SV *sv = new_version(SV *ver);
4699 Does not alter the passed in ver SV. See "upg_version" if you
4700 want to upgrade the SV.
4706 Perl_new_version(pTHX_ SV *ver)
4709 SV * const rv = newSV(0);
4710 PERL_ARGS_ASSERT_NEW_VERSION;
4711 if ( sv_isobject(ver) && sv_derived_from(ver, "version") )
4712 /* can just copy directly */
4715 AV * const av = newAV();
4717 /* This will get reblessed later if a derived class*/
4718 SV * const hv = newSVrv(rv, "version");
4719 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4720 #ifndef NODEFAULT_SHAREKEYS
4721 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4727 /* Begin copying all of the elements */
4728 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4729 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4731 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4732 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4734 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4736 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4737 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4740 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4742 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4743 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4746 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4747 /* This will get reblessed later if a derived class*/
4748 for ( key = 0; key <= av_len(sav); key++ )
4750 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4751 av_push(av, newSViv(rev));
4754 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4759 const MAGIC* const mg = SvVSTRING_mg(ver);
4760 if ( mg ) { /* already a v-string */
4761 const STRLEN len = mg->mg_len;
4762 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4763 sv_setpvn(rv,version,len);
4764 /* this is for consistency with the pure Perl class */
4765 if ( isDIGIT(*version) )
4766 sv_insert(rv, 0, 0, "v", 1);
4771 sv_setsv(rv,ver); /* make a duplicate */
4776 return upg_version(rv, FALSE);
4780 =for apidoc upg_version
4782 In-place upgrade of the supplied SV to a version object.
4784 SV *sv = upg_version(SV *sv, bool qv);
4786 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4787 to force this SV to be interpreted as an "extended" version.
4793 Perl_upg_version(pTHX_ SV *ver, bool qv)
4795 const char *version, *s;
4800 PERL_ARGS_ASSERT_UPG_VERSION;
4802 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4806 /* may get too much accuracy */
4808 SV *sv = SvNVX(ver) > 10e50 ? newSV(64) : 0;
4810 #ifdef USE_LOCALE_NUMERIC
4811 char *loc = savepv(setlocale(LC_NUMERIC, NULL));
4812 setlocale(LC_NUMERIC, "C");
4815 Perl_sv_setpvf(aTHX_ sv, "%.9"NVff, SvNVX(ver));
4816 buf = SvPV(sv, len);
4819 len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4822 #ifdef USE_LOCALE_NUMERIC
4823 setlocale(LC_NUMERIC, loc);
4826 while (buf[len-1] == '0' && len > 0) len--;
4827 if ( buf[len-1] == '.' ) len--; /* eat the trailing decimal */
4828 version = savepvn(buf, len);
4832 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4833 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4837 else /* must be a string or something like a string */
4840 version = savepv(SvPV(ver,len));
4842 # if PERL_VERSION > 5
4843 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4844 if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
4845 /* may be a v-string */
4846 char *testv = (char *)version;
4848 for (tlen=0; tlen < len; tlen++, testv++) {
4849 /* if one of the characters is non-text assume v-string */
4850 if (testv[0] < ' ') {
4851 SV * const nsv = sv_newmortal();
4854 int saw_decimal = 0;
4855 sv_setpvf(nsv,"v%vd",ver);
4856 pos = nver = savepv(SvPV_nolen(nsv));
4858 /* scan the resulting formatted string */
4859 pos++; /* skip the leading 'v' */
4860 while ( *pos == '.' || isDIGIT(*pos) ) {
4866 /* is definitely a v-string */
4867 if ( saw_decimal >= 2 ) {
4879 s = scan_version(version, ver, qv);
4881 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4882 "Version string '%s' contains invalid data; "
4883 "ignoring: '%s'", version, s);
4891 Validates that the SV contains valid internal structure for a version object.
4892 It may be passed either the version object (RV) or the hash itself (HV). If
4893 the structure is valid, it returns the HV. If the structure is invalid,
4896 SV *hv = vverify(sv);
4898 Note that it only confirms the bare minimum structure (so as not to get
4899 confused by derived classes which may contain additional hash entries):
4903 =item * The SV is an HV or a reference to an HV
4905 =item * The hash contains a "version" key
4907 =item * The "version" key has a reference to an AV as its value
4915 Perl_vverify(pTHX_ SV *vs)
4919 PERL_ARGS_ASSERT_VVERIFY;
4924 /* see if the appropriate elements exist */
4925 if ( SvTYPE(vs) == SVt_PVHV
4926 && hv_exists(MUTABLE_HV(vs), "version", 7)
4927 && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
4928 && SvTYPE(sv) == SVt_PVAV )
4937 Accepts a version object and returns the normalized floating
4938 point representation. Call like:
4942 NOTE: you can pass either the object directly or the SV
4943 contained within the RV.
4945 The SV returned has a refcount of 1.
4951 Perl_vnumify(pTHX_ SV *vs)
4959 PERL_ARGS_ASSERT_VNUMIFY;
4961 /* extract the HV from the object */
4964 Perl_croak(aTHX_ "Invalid version object");
4966 /* see if various flags exist */
4967 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
4969 if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
4970 width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
4975 /* attempt to retrieve the version array */
4976 if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
4977 return newSVpvs("0");
4983 return newSVpvs("0");
4986 digit = SvIV(*av_fetch(av, 0, 0));
4987 sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
4988 for ( i = 1 ; i < len ; i++ )
4990 digit = SvIV(*av_fetch(av, i, 0));
4992 const int denom = (width == 2 ? 10 : 100);
4993 const div_t term = div((int)PERL_ABS(digit),denom);
4994 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4997 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5003 digit = SvIV(*av_fetch(av, len, 0));
5004 if ( alpha && width == 3 ) /* alpha version */
5006 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5010 sv_catpvs(sv, "000");
5018 Accepts a version object and returns the normalized string
5019 representation. Call like:
5023 NOTE: you can pass either the object directly or the SV
5024 contained within the RV.
5026 The SV returned has a refcount of 1.
5032 Perl_vnormal(pTHX_ SV *vs)
5039 PERL_ARGS_ASSERT_VNORMAL;
5041 /* extract the HV from the object */
5044 Perl_croak(aTHX_ "Invalid version object");
5046 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5048 av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)));