3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * 'Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content.' --Gandalf to Pippin
15 * [p.598 of _The Lord of the Rings_, III/xi: "The PalantÃr"]
18 /* This file contains assorted utility routines.
19 * Which is a polite way of saying any stuff that people couldn't think of
20 * a better place for. Amongst other things, it includes the warning and
21 * dieing stuff, plus wrappers for malloc code.
25 #define PERL_IN_UTIL_C
29 #include "perliol.h" /* For PerlIOUnix_refcnt */
35 # define SIG_ERR ((Sighandler_t) -1)
40 /* Missing protos on LynxOS */
46 # include <sys/select.h>
52 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
53 # define FD_CLOEXEC 1 /* NeXT needs this */
56 /* NOTE: Do not call the next three routines directly. Use the macros
57 * in handy.h, so that we can easily redefine everything to do tracking of
58 * allocated hunks back to the original New to track down any memory leaks.
59 * XXX This advice seems to be widely ignored :-( --AD August 1996.
62 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
63 # define ALWAYS_NEED_THX
66 /* paranoid version of system's malloc() */
69 Perl_safesysmalloc(MEM_SIZE size)
71 #ifdef ALWAYS_NEED_THX
77 PerlIO_printf(Perl_error_log,
78 "Allocation too large: %lx\n", size) FLUSH;
81 #endif /* HAS_64K_LIMIT */
82 #ifdef PERL_TRACK_MEMPOOL
86 if ((SSize_t)size < 0)
87 Perl_croak_nocontext("panic: malloc, size=%"UVuf, (UV) size);
89 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
90 PERL_ALLOC_CHECK(ptr);
92 #ifdef PERL_TRACK_MEMPOOL
93 struct perl_memory_debug_header *const header
94 = (struct perl_memory_debug_header *)ptr;
98 PoisonNew(((char *)ptr), size, char);
101 #ifdef PERL_TRACK_MEMPOOL
102 header->interpreter = aTHX;
103 /* Link us into the list. */
104 header->prev = &PL_memory_debug_header;
105 header->next = PL_memory_debug_header.next;
106 PL_memory_debug_header.next = header;
107 header->next->prev = header;
111 ptr = (Malloc_t)((char*)ptr+sTHX);
113 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
117 #ifndef ALWAYS_NEED_THX
129 /* paranoid version of system's realloc() */
132 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
134 #ifdef ALWAYS_NEED_THX
138 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
139 Malloc_t PerlMem_realloc();
140 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
144 PerlIO_printf(Perl_error_log,
145 "Reallocation too large: %lx\n", size) FLUSH;
148 #endif /* HAS_64K_LIMIT */
155 return safesysmalloc(size);
156 #ifdef PERL_TRACK_MEMPOOL
157 where = (Malloc_t)((char*)where-sTHX);
160 struct perl_memory_debug_header *const header
161 = (struct perl_memory_debug_header *)where;
163 if (header->interpreter != aTHX) {
164 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
165 header->interpreter, aTHX);
167 assert(header->next->prev == header);
168 assert(header->prev->next == header);
170 if (header->size > size) {
171 const MEM_SIZE freed_up = header->size - size;
172 char *start_of_freed = ((char *)where) + size;
173 PoisonFree(start_of_freed, freed_up, char);
180 if ((SSize_t)size < 0)
181 Perl_croak_nocontext("panic: realloc, size=%"UVuf, (UV)size);
183 ptr = (Malloc_t)PerlMem_realloc(where,size);
184 PERL_ALLOC_CHECK(ptr);
186 /* MUST do this fixup first, before doing ANYTHING else, as anything else
187 might allocate memory/free/move memory, and until we do the fixup, it
188 may well be chasing (and writing to) free memory. */
189 #ifdef PERL_TRACK_MEMPOOL
191 struct perl_memory_debug_header *const header
192 = (struct perl_memory_debug_header *)ptr;
195 if (header->size < size) {
196 const MEM_SIZE fresh = size - header->size;
197 char *start_of_fresh = ((char *)ptr) + size;
198 PoisonNew(start_of_fresh, fresh, char);
202 header->next->prev = header;
203 header->prev->next = header;
205 ptr = (Malloc_t)((char*)ptr+sTHX);
209 /* In particular, must do that fixup above before logging anything via
210 *printf(), as it can reallocate memory, which can cause SEGVs. */
212 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
213 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
220 #ifndef ALWAYS_NEED_THX
232 /* safe version of system's free() */
235 Perl_safesysfree(Malloc_t where)
237 #ifdef ALWAYS_NEED_THX
242 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
244 #ifdef PERL_TRACK_MEMPOOL
245 where = (Malloc_t)((char*)where-sTHX);
247 struct perl_memory_debug_header *const header
248 = (struct perl_memory_debug_header *)where;
250 if (header->interpreter != aTHX) {
251 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
252 header->interpreter, aTHX);
255 Perl_croak_nocontext("panic: duplicate free");
258 Perl_croak_nocontext("panic: bad free, header->next==NULL");
259 if (header->next->prev != header || header->prev->next != header) {
260 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
261 "header=%p, ->prev->next=%p",
262 header->next->prev, header,
265 /* Unlink us from the chain. */
266 header->next->prev = header->prev;
267 header->prev->next = header->next;
269 PoisonNew(where, header->size, char);
271 /* Trigger the duplicate free warning. */
279 /* safe version of system's calloc() */
282 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
284 #ifdef ALWAYS_NEED_THX
288 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
289 MEM_SIZE total_size = 0;
292 /* Even though calloc() for zero bytes is strange, be robust. */
293 if (size && (count <= MEM_SIZE_MAX / size)) {
294 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
295 total_size = size * count;
300 #ifdef PERL_TRACK_MEMPOOL
301 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
307 if (total_size > 0xffff) {
308 PerlIO_printf(Perl_error_log,
309 "Allocation too large: %lx\n", total_size) FLUSH;
312 #endif /* HAS_64K_LIMIT */
314 if ((SSize_t)size < 0 || (SSize_t)count < 0)
315 Perl_croak_nocontext("panic: calloc, size=%"UVuf", count=%"UVuf,
316 (UV)size, (UV)count);
318 #ifdef PERL_TRACK_MEMPOOL
319 /* Have to use malloc() because we've added some space for our tracking
321 /* malloc(0) is non-portable. */
322 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
324 /* Use calloc() because it might save a memset() if the memory is fresh
325 and clean from the OS. */
327 ptr = (Malloc_t)PerlMem_calloc(count, size);
328 else /* calloc(0) is non-portable. */
329 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
331 PERL_ALLOC_CHECK(ptr);
332 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));
334 #ifdef PERL_TRACK_MEMPOOL
336 struct perl_memory_debug_header *const header
337 = (struct perl_memory_debug_header *)ptr;
339 memset((void*)ptr, 0, total_size);
340 header->interpreter = aTHX;
341 /* Link us into the list. */
342 header->prev = &PL_memory_debug_header;
343 header->next = PL_memory_debug_header.next;
344 PL_memory_debug_header.next = header;
345 header->next->prev = header;
347 header->size = total_size;
349 ptr = (Malloc_t)((char*)ptr+sTHX);
355 #ifndef ALWAYS_NEED_THX
364 /* These must be defined when not using Perl's malloc for binary
369 Malloc_t Perl_malloc (MEM_SIZE nbytes)
372 return (Malloc_t)PerlMem_malloc(nbytes);
375 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
378 return (Malloc_t)PerlMem_calloc(elements, size);
381 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
384 return (Malloc_t)PerlMem_realloc(where, nbytes);
387 Free_t Perl_mfree (Malloc_t where)
395 /* copy a string up to some (non-backslashed) delimiter, if any */
398 Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
402 PERL_ARGS_ASSERT_DELIMCPY;
404 for (tolen = 0; from < fromend; from++, tolen++) {
406 if (from[1] != delim) {
413 else if (*from == delim)
424 /* return ptr to little string in big string, NULL if not found */
425 /* This routine was donated by Corey Satten. */
428 Perl_instr(register const char *big, register const char *little)
432 PERL_ARGS_ASSERT_INSTR;
443 for (x=big,s=little; *s; /**/ ) {
454 return (char*)(big-1);
459 /* same as instr but allow embedded nulls. The end pointers point to 1 beyond
460 * the final character desired to be checked */
463 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
465 PERL_ARGS_ASSERT_NINSTR;
469 const char first = *little;
471 bigend -= lend - little++;
473 while (big <= bigend) {
474 if (*big++ == first) {
475 for (x=big,s=little; s < lend; x++,s++) {
479 return (char*)(big-1);
486 /* reverse of the above--find last substring */
489 Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
492 const I32 first = *little;
493 const char * const littleend = lend;
495 PERL_ARGS_ASSERT_RNINSTR;
497 if (little >= littleend)
498 return (char*)bigend;
500 big = bigend - (littleend - little++);
501 while (big >= bigbeg) {
505 for (x=big+2,s=little; s < littleend; /**/ ) {
514 return (char*)(big+1);
519 /* As a space optimization, we do not compile tables for strings of length
520 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
521 special-cased in fbm_instr().
523 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
526 =head1 Miscellaneous Functions
528 =for apidoc fbm_compile
530 Analyses the string in order to make fast searches on it using fbm_instr()
531 -- the Boyer-Moore algorithm.
537 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
547 PERL_ARGS_ASSERT_FBM_COMPILE;
549 if (isGV_with_GP(sv))
555 if (flags & FBMcf_TAIL) {
556 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
557 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
558 if (mg && mg->mg_len >= 0)
561 s = (U8*)SvPV_force_mutable(sv, len);
562 if (len == 0) /* TAIL might be on a zero-length string. */
564 SvUPGRADE(sv, SVt_PVMG);
569 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
570 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
571 to call SvVALID_off() if the scalar was assigned to.
573 The comment itself (and "deeper magic" below) date back to
574 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
576 where the magic (presumably) was that the scalar had a BM table hidden
579 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
580 the table instead of the previous (somewhat hacky) approach of co-opting
581 the string buffer and storing it after the string. */
583 assert(!mg_find(sv, PERL_MAGIC_bm));
584 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
588 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
590 const U8 mlen = (len>255) ? 255 : (U8)len;
591 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
594 Newx(table, 256, U8);
595 memset((void*)table, mlen, 256);
596 mg->mg_ptr = (char *)table;
599 s += len - 1; /* last char */
602 if (table[*s] == mlen)
608 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
609 for (i = 0; i < len; i++) {
610 if (PL_freq[s[i]] < frequency) {
612 frequency = PL_freq[s[i]];
615 BmRARE(sv) = s[rarest];
616 BmPREVIOUS(sv) = rarest;
617 BmUSEFUL(sv) = 100; /* Initial value */
618 if (flags & FBMcf_TAIL)
620 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
621 BmRARE(sv), BmPREVIOUS(sv)));
624 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
625 /* If SvTAIL is actually due to \Z or \z, this gives false positives
629 =for apidoc fbm_instr
631 Returns the location of the SV in the string delimited by C<big> and
632 C<bigend>. It returns C<NULL> if the string can't be found. The C<sv>
633 does not have to be fbm_compiled, but the search will not be as fast
640 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
644 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
645 STRLEN littlelen = l;
646 const I32 multiline = flags & FBMrf_MULTILINE;
648 PERL_ARGS_ASSERT_FBM_INSTR;
650 if ((STRLEN)(bigend - big) < littlelen) {
651 if ( SvTAIL(littlestr)
652 && ((STRLEN)(bigend - big) == littlelen - 1)
654 || (*big == *little &&
655 memEQ((char *)big, (char *)little, littlelen - 1))))
660 switch (littlelen) { /* Special cases for 0, 1 and 2 */
662 return (char*)big; /* Cannot be SvTAIL! */
664 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
665 /* Know that bigend != big. */
666 if (bigend[-1] == '\n')
667 return (char *)(bigend - 1);
668 return (char *) bigend;
676 if (SvTAIL(littlestr))
677 return (char *) bigend;
680 if (SvTAIL(littlestr) && !multiline) {
681 if (bigend[-1] == '\n' && bigend[-2] == *little)
682 return (char*)bigend - 2;
683 if (bigend[-1] == *little)
684 return (char*)bigend - 1;
688 /* This should be better than FBM if c1 == c2, and almost
689 as good otherwise: maybe better since we do less indirection.
690 And we save a lot of memory by caching no table. */
691 const unsigned char c1 = little[0];
692 const unsigned char c2 = little[1];
697 while (s <= bigend) {
707 goto check_1char_anchor;
718 goto check_1char_anchor;
721 while (s <= bigend) {
726 goto check_1char_anchor;
735 check_1char_anchor: /* One char and anchor! */
736 if (SvTAIL(littlestr) && (*bigend == *little))
737 return (char *)bigend; /* bigend is already decremented. */
740 break; /* Only lengths 0 1 and 2 have special-case code. */
743 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
744 s = bigend - littlelen;
745 if (s >= big && bigend[-1] == '\n' && *s == *little
746 /* Automatically of length > 2 */
747 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
749 return (char*)s; /* how sweet it is */
752 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
754 return (char*)s + 1; /* how sweet it is */
758 if (!SvVALID(littlestr)) {
759 char * const b = ninstr((char*)big,(char*)bigend,
760 (char*)little, (char*)little + littlelen);
762 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
763 /* Chop \n from littlestr: */
764 s = bigend - littlelen + 1;
766 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
776 if (littlelen > (STRLEN)(bigend - big))
780 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
781 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
782 const unsigned char *oldlittle;
784 --littlelen; /* Last char found by table lookup */
787 little += littlelen; /* last char */
793 if ((tmp = table[*s])) {
794 if ((s += tmp) < bigend)
798 else { /* less expensive than calling strncmp() */
799 unsigned char * const olds = s;
804 if (*--s == *--little)
806 s = olds + 1; /* here we pay the price for failure */
808 if (s < bigend) /* fake up continue to outer loop */
818 && memEQ((char *)(bigend - littlelen),
819 (char *)(oldlittle - littlelen), littlelen) )
820 return (char*)bigend - littlelen;
826 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
829 PERL_ARGS_ASSERT_SCREAMINSTR;
830 PERL_UNUSED_ARG(bigstr);
831 PERL_UNUSED_ARG(littlestr);
832 PERL_UNUSED_ARG(start_shift);
833 PERL_UNUSED_ARG(end_shift);
834 PERL_UNUSED_ARG(old_posp);
835 PERL_UNUSED_ARG(last);
837 /* This function must only ever be called on a scalar with study magic,
838 but those do not happen any more. */
839 Perl_croak(aTHX_ "panic: screaminstr");
846 Returns true if the leading len bytes of the strings s1 and s2 are the same
847 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
848 match themselves and their opposite case counterparts. Non-cased and non-ASCII
849 range bytes match only themselves.
856 Perl_foldEQ(const char *s1, const char *s2, register I32 len)
858 const U8 *a = (const U8 *)s1;
859 const U8 *b = (const U8 *)s2;
861 PERL_ARGS_ASSERT_FOLDEQ;
866 if (*a != *b && *a != PL_fold[*b])
873 Perl_foldEQ_latin1(const char *s1, const char *s2, register I32 len)
875 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
876 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
877 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
878 * does it check that the strings each have at least 'len' characters */
880 const U8 *a = (const U8 *)s1;
881 const U8 *b = (const U8 *)s2;
883 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
888 if (*a != *b && *a != PL_fold_latin1[*b]) {
897 =for apidoc foldEQ_locale
899 Returns true if the leading len bytes of the strings s1 and s2 are the same
900 case-insensitively in the current locale; false otherwise.
906 Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
909 const U8 *a = (const U8 *)s1;
910 const U8 *b = (const U8 *)s2;
912 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
917 if (*a != *b && *a != PL_fold_locale[*b])
924 /* copy a string to a safe spot */
927 =head1 Memory Management
931 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
932 string which is a duplicate of C<pv>. The size of the string is
933 determined by C<strlen()>. The memory allocated for the new string can
934 be freed with the C<Safefree()> function.
940 Perl_savepv(pTHX_ const char *pv)
947 const STRLEN pvlen = strlen(pv)+1;
948 Newx(newaddr, pvlen, char);
949 return (char*)memcpy(newaddr, pv, pvlen);
953 /* same thing but with a known length */
958 Perl's version of what C<strndup()> would be if it existed. Returns a
959 pointer to a newly allocated string which is a duplicate of the first
960 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
961 the new string can be freed with the C<Safefree()> function.
967 Perl_savepvn(pTHX_ const char *pv, register I32 len)
974 Newx(newaddr,len+1,char);
975 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
977 /* might not be null terminated */
979 return (char *) CopyD(pv,newaddr,len,char);
982 return (char *) ZeroD(newaddr,len+1,char);
987 =for apidoc savesharedpv
989 A version of C<savepv()> which allocates the duplicate string in memory
990 which is shared between threads.
995 Perl_savesharedpv(pTHX_ const char *pv)
1002 pvlen = strlen(pv)+1;
1003 newaddr = (char*)PerlMemShared_malloc(pvlen);
1007 return (char*)memcpy(newaddr, pv, pvlen);
1011 =for apidoc savesharedpvn
1013 A version of C<savepvn()> which allocates the duplicate string in memory
1014 which is shared between threads. (With the specific difference that a NULL
1015 pointer is not acceptable)
1020 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1022 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1024 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1029 newaddr[len] = '\0';
1030 return (char*)memcpy(newaddr, pv, len);
1034 =for apidoc savesvpv
1036 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1037 the passed in SV using C<SvPV()>
1043 Perl_savesvpv(pTHX_ SV *sv)
1046 const char * const pv = SvPV_const(sv, len);
1049 PERL_ARGS_ASSERT_SAVESVPV;
1052 Newx(newaddr,len,char);
1053 return (char *) CopyD(pv,newaddr,len,char);
1057 =for apidoc savesharedsvpv
1059 A version of C<savesharedpv()> which allocates the duplicate string in
1060 memory which is shared between threads.
1066 Perl_savesharedsvpv(pTHX_ SV *sv)
1069 const char * const pv = SvPV_const(sv, len);
1071 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1073 return savesharedpvn(pv, len);
1076 /* the SV for Perl_form() and mess() is not kept in an arena */
1085 if (PL_phase != PERL_PHASE_DESTRUCT)
1086 return newSVpvs_flags("", SVs_TEMP);
1091 /* Create as PVMG now, to avoid any upgrading later */
1093 Newxz(any, 1, XPVMG);
1094 SvFLAGS(sv) = SVt_PVMG;
1095 SvANY(sv) = (void*)any;
1097 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1102 #if defined(PERL_IMPLICIT_CONTEXT)
1104 Perl_form_nocontext(const char* pat, ...)
1109 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1110 va_start(args, pat);
1111 retval = vform(pat, &args);
1115 #endif /* PERL_IMPLICIT_CONTEXT */
1118 =head1 Miscellaneous Functions
1121 Takes a sprintf-style format pattern and conventional
1122 (non-SV) arguments and returns the formatted string.
1124 (char *) Perl_form(pTHX_ const char* pat, ...)
1126 can be used any place a string (char *) is required:
1128 char * s = Perl_form("%d.%d",major,minor);
1130 Uses a single private buffer so if you want to format several strings you
1131 must explicitly copy the earlier strings away (and free the copies when you
1138 Perl_form(pTHX_ const char* pat, ...)
1142 PERL_ARGS_ASSERT_FORM;
1143 va_start(args, pat);
1144 retval = vform(pat, &args);
1150 Perl_vform(pTHX_ const char *pat, va_list *args)
1152 SV * const sv = mess_alloc();
1153 PERL_ARGS_ASSERT_VFORM;
1154 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1159 =for apidoc Am|SV *|mess|const char *pat|...
1161 Take a sprintf-style format pattern and argument list. These are used to
1162 generate a string message. If the message does not end with a newline,
1163 then it will be extended with some indication of the current location
1164 in the code, as described for L</mess_sv>.
1166 Normally, the resulting message is returned in a new mortal SV.
1167 During global destruction a single SV may be shared between uses of
1173 #if defined(PERL_IMPLICIT_CONTEXT)
1175 Perl_mess_nocontext(const char *pat, ...)
1180 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1181 va_start(args, pat);
1182 retval = vmess(pat, &args);
1186 #endif /* PERL_IMPLICIT_CONTEXT */
1189 Perl_mess(pTHX_ const char *pat, ...)
1193 PERL_ARGS_ASSERT_MESS;
1194 va_start(args, pat);
1195 retval = vmess(pat, &args);
1201 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1204 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1206 PERL_ARGS_ASSERT_CLOSEST_COP;
1208 if (!o || o == PL_op)
1211 if (o->op_flags & OPf_KIDS) {
1213 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1216 /* If the OP_NEXTSTATE has been optimised away we can still use it
1217 * the get the file and line number. */
1219 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1220 cop = (const COP *)kid;
1222 /* Keep searching, and return when we've found something. */
1224 new_cop = closest_cop(cop, kid);
1230 /* Nothing found. */
1236 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1238 Expands a message, intended for the user, to include an indication of
1239 the current location in the code, if the message does not already appear
1242 C<basemsg> is the initial message or object. If it is a reference, it
1243 will be used as-is and will be the result of this function. Otherwise it
1244 is used as a string, and if it already ends with a newline, it is taken
1245 to be complete, and the result of this function will be the same string.
1246 If the message does not end with a newline, then a segment such as C<at
1247 foo.pl line 37> will be appended, and possibly other clauses indicating
1248 the current state of execution. The resulting message will end with a
1251 Normally, the resulting message is returned in a new mortal SV.
1252 During global destruction a single SV may be shared between uses of this
1253 function. If C<consume> is true, then the function is permitted (but not
1254 required) to modify and return C<basemsg> instead of allocating a new SV.
1260 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1265 PERL_ARGS_ASSERT_MESS_SV;
1267 if (SvROK(basemsg)) {
1273 sv_setsv(sv, basemsg);
1278 if (SvPOK(basemsg) && consume) {
1283 sv_copypv(sv, basemsg);
1286 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1288 * Try and find the file and line for PL_op. This will usually be
1289 * PL_curcop, but it might be a cop that has been optimised away. We
1290 * can try to find such a cop by searching through the optree starting
1291 * from the sibling of PL_curcop.
1294 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1299 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1300 OutCopFILE(cop), (IV)CopLINE(cop));
1301 /* Seems that GvIO() can be untrustworthy during global destruction. */
1302 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1303 && IoLINES(GvIOp(PL_last_in_gv)))
1306 const bool line_mode = (RsSIMPLE(PL_rs) &&
1307 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1308 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1309 SVfARG(PL_last_in_gv == PL_argvgv
1311 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1312 line_mode ? "line" : "chunk",
1313 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1315 if (PL_phase == PERL_PHASE_DESTRUCT)
1316 sv_catpvs(sv, " during global destruction");
1317 sv_catpvs(sv, ".\n");
1323 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1325 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1326 argument list. These are used to generate a string message. If the
1327 message does not end with a newline, then it will be extended with
1328 some indication of the current location in the code, as described for
1331 Normally, the resulting message is returned in a new mortal SV.
1332 During global destruction a single SV may be shared between uses of
1339 Perl_vmess(pTHX_ const char *pat, va_list *args)
1342 SV * const sv = mess_alloc();
1344 PERL_ARGS_ASSERT_VMESS;
1346 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1347 return mess_sv(sv, 1);
1351 Perl_write_to_stderr(pTHX_ SV* msv)
1357 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1359 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1360 && (io = GvIO(PL_stderrgv))
1361 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1362 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1363 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1366 /* SFIO can really mess with your errno */
1369 PerlIO * const serr = Perl_error_log;
1371 do_print(msv, serr);
1372 (void)PerlIO_flush(serr);
1380 =head1 Warning and Dieing
1383 /* Common code used in dieing and warning */
1386 S_with_queued_errors(pTHX_ SV *ex)
1388 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1389 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1390 sv_catsv(PL_errors, ex);
1391 ex = sv_mortalcopy(PL_errors);
1392 SvCUR_set(PL_errors, 0);
1398 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1404 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1405 /* sv_2cv might call Perl_croak() or Perl_warner() */
1406 SV * const oldhook = *hook;
1414 cv = sv_2cv(oldhook, &stash, &gv, 0);
1416 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1426 exarg = newSVsv(ex);
1427 SvREADONLY_on(exarg);
1430 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1434 call_sv(MUTABLE_SV(cv), G_DISCARD);
1443 =for apidoc Am|OP *|die_sv|SV *baseex
1445 Behaves the same as L</croak_sv>, 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.
1453 Perl_die_sv(pTHX_ SV *baseex)
1455 PERL_ARGS_ASSERT_DIE_SV;
1457 assert(0); /* NOTREACHED */
1462 =for apidoc Am|OP *|die|const char *pat|...
1464 Behaves the same as L</croak>, except for the return type.
1465 It should be used only where the C<OP *> return type is required.
1466 The function never actually returns.
1471 #if defined(PERL_IMPLICIT_CONTEXT)
1473 Perl_die_nocontext(const char* pat, ...)
1477 va_start(args, pat);
1479 assert(0); /* NOTREACHED */
1483 #endif /* PERL_IMPLICIT_CONTEXT */
1486 Perl_die(pTHX_ const char* pat, ...)
1489 va_start(args, pat);
1491 assert(0); /* NOTREACHED */
1497 =for apidoc Am|void|croak_sv|SV *baseex
1499 This is an XS interface to Perl's C<die> function.
1501 C<baseex> is the error message or object. If it is a reference, it
1502 will be used as-is. Otherwise it is used as a string, and if it does
1503 not end with a newline then it will be extended with some indication of
1504 the current location in the code, as described for L</mess_sv>.
1506 The error message or object will be used as an exception, by default
1507 returning control to the nearest enclosing C<eval>, but subject to
1508 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1509 function never returns normally.
1511 To die with a simple string message, the L</croak> function may be
1518 Perl_croak_sv(pTHX_ SV *baseex)
1520 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1521 PERL_ARGS_ASSERT_CROAK_SV;
1522 invoke_exception_hook(ex, FALSE);
1527 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1529 This is an XS interface to Perl's C<die> function.
1531 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1532 argument list. These are used to generate a string message. If the
1533 message does not end with a newline, then it will be extended with
1534 some indication of the current location in the code, as described for
1537 The error message will be used as an exception, by default
1538 returning control to the nearest enclosing C<eval>, but subject to
1539 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1540 function never returns normally.
1542 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1543 (C<$@>) will be used as an error message or object instead of building an
1544 error message from arguments. If you want to throw a non-string object,
1545 or build an error message in an SV yourself, it is preferable to use
1546 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1552 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1554 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1555 invoke_exception_hook(ex, FALSE);
1560 =for apidoc Am|void|croak|const char *pat|...
1562 This is an XS interface to Perl's C<die> function.
1564 Take a sprintf-style format pattern and argument list. These are used to
1565 generate a string message. If the message does not end with a newline,
1566 then it will be extended with some indication of the current location
1567 in the code, as described for L</mess_sv>.
1569 The error message will be used as an exception, by default
1570 returning control to the nearest enclosing C<eval>, but subject to
1571 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1572 function never returns normally.
1574 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1575 (C<$@>) will be used as an error message or object instead of building an
1576 error message from arguments. If you want to throw a non-string object,
1577 or build an error message in an SV yourself, it is preferable to use
1578 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1583 #if defined(PERL_IMPLICIT_CONTEXT)
1585 Perl_croak_nocontext(const char *pat, ...)
1589 va_start(args, pat);
1591 assert(0); /* NOTREACHED */
1594 #endif /* PERL_IMPLICIT_CONTEXT */
1597 Perl_croak(pTHX_ const char *pat, ...)
1600 va_start(args, pat);
1602 assert(0); /* NOTREACHED */
1607 =for apidoc Am|void|croak_no_modify
1609 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1610 terser object code than using C<Perl_croak>. Less code used on exception code
1611 paths reduces CPU cache pressure.
1617 Perl_croak_no_modify()
1619 Perl_croak_nocontext( "%s", PL_no_modify);
1622 /* does not return, used in util.c perlio.c and win32.c
1623 This is typically called when malloc returns NULL.
1630 /* Can't use PerlIO to write as it allocates memory */
1631 PerlLIO_write(PerlIO_fileno(Perl_error_log),
1632 PL_no_mem, sizeof(PL_no_mem)-1);
1637 =for apidoc Am|void|warn_sv|SV *baseex
1639 This is an XS interface to Perl's C<warn> function.
1641 C<baseex> is the error message or object. If it is a reference, it
1642 will be used as-is. Otherwise it is used as a string, and if it does
1643 not end with a newline then it will be extended with some indication of
1644 the current location in the code, as described for L</mess_sv>.
1646 The error message or object will by default be written to standard error,
1647 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1649 To warn with a simple string message, the L</warn> function may be
1656 Perl_warn_sv(pTHX_ SV *baseex)
1658 SV *ex = mess_sv(baseex, 0);
1659 PERL_ARGS_ASSERT_WARN_SV;
1660 if (!invoke_exception_hook(ex, TRUE))
1661 write_to_stderr(ex);
1665 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1667 This is an XS interface to Perl's C<warn> function.
1669 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1670 argument list. These are used to generate a string message. If the
1671 message does not end with a newline, then it will be extended with
1672 some indication of the current location in the code, as described for
1675 The error message or object will by default be written to standard error,
1676 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1678 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1684 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1686 SV *ex = vmess(pat, args);
1687 PERL_ARGS_ASSERT_VWARN;
1688 if (!invoke_exception_hook(ex, TRUE))
1689 write_to_stderr(ex);
1693 =for apidoc Am|void|warn|const char *pat|...
1695 This is an XS interface to Perl's C<warn> function.
1697 Take a sprintf-style format pattern and argument list. These are used to
1698 generate a string message. If the message does not end with a newline,
1699 then it will be extended with some indication of the current location
1700 in the code, as described for L</mess_sv>.
1702 The error message or object will by default be written to standard error,
1703 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1705 Unlike with L</croak>, C<pat> is not permitted to be null.
1710 #if defined(PERL_IMPLICIT_CONTEXT)
1712 Perl_warn_nocontext(const char *pat, ...)
1716 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1717 va_start(args, pat);
1721 #endif /* PERL_IMPLICIT_CONTEXT */
1724 Perl_warn(pTHX_ const char *pat, ...)
1727 PERL_ARGS_ASSERT_WARN;
1728 va_start(args, pat);
1733 #if defined(PERL_IMPLICIT_CONTEXT)
1735 Perl_warner_nocontext(U32 err, const char *pat, ...)
1739 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1740 va_start(args, pat);
1741 vwarner(err, pat, &args);
1744 #endif /* PERL_IMPLICIT_CONTEXT */
1747 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1749 PERL_ARGS_ASSERT_CK_WARNER_D;
1751 if (Perl_ckwarn_d(aTHX_ err)) {
1753 va_start(args, pat);
1754 vwarner(err, pat, &args);
1760 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1762 PERL_ARGS_ASSERT_CK_WARNER;
1764 if (Perl_ckwarn(aTHX_ err)) {
1766 va_start(args, pat);
1767 vwarner(err, pat, &args);
1773 Perl_warner(pTHX_ U32 err, const char* pat,...)
1776 PERL_ARGS_ASSERT_WARNER;
1777 va_start(args, pat);
1778 vwarner(err, pat, &args);
1783 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1786 PERL_ARGS_ASSERT_VWARNER;
1787 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1788 SV * const msv = vmess(pat, args);
1790 invoke_exception_hook(msv, FALSE);
1794 Perl_vwarn(aTHX_ pat, args);
1798 /* implements the ckWARN? macros */
1801 Perl_ckwarn(pTHX_ U32 w)
1804 /* If lexical warnings have not been set, use $^W. */
1806 return PL_dowarn & G_WARN_ON;
1808 return ckwarn_common(w);
1811 /* implements the ckWARN?_d macro */
1814 Perl_ckwarn_d(pTHX_ U32 w)
1817 /* If lexical warnings have not been set then default classes warn. */
1821 return ckwarn_common(w);
1825 S_ckwarn_common(pTHX_ U32 w)
1827 if (PL_curcop->cop_warnings == pWARN_ALL)
1830 if (PL_curcop->cop_warnings == pWARN_NONE)
1833 /* Check the assumption that at least the first slot is non-zero. */
1834 assert(unpackWARN1(w));
1836 /* Check the assumption that it is valid to stop as soon as a zero slot is
1838 if (!unpackWARN2(w)) {
1839 assert(!unpackWARN3(w));
1840 assert(!unpackWARN4(w));
1841 } else if (!unpackWARN3(w)) {
1842 assert(!unpackWARN4(w));
1845 /* Right, dealt with all the special cases, which are implemented as non-
1846 pointers, so there is a pointer to a real warnings mask. */
1848 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1850 } while (w >>= WARNshift);
1855 /* Set buffer=NULL to get a new one. */
1857 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1859 const MEM_SIZE len_wanted =
1860 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
1861 PERL_UNUSED_CONTEXT;
1862 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1865 (specialWARN(buffer) ?
1866 PerlMemShared_malloc(len_wanted) :
1867 PerlMemShared_realloc(buffer, len_wanted));
1869 Copy(bits, (buffer + 1), size, char);
1870 if (size < WARNsize)
1871 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
1875 /* since we've already done strlen() for both nam and val
1876 * we can use that info to make things faster than
1877 * sprintf(s, "%s=%s", nam, val)
1879 #define my_setenv_format(s, nam, nlen, val, vlen) \
1880 Copy(nam, s, nlen, char); \
1882 Copy(val, s+(nlen+1), vlen, char); \
1883 *(s+(nlen+1+vlen)) = '\0'
1885 #ifdef USE_ENVIRON_ARRAY
1886 /* VMS' my_setenv() is in vms.c */
1887 #if !defined(WIN32) && !defined(NETWARE)
1889 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1893 /* only parent thread can modify process environment */
1894 if (PL_curinterp == aTHX)
1897 #ifndef PERL_USE_SAFE_PUTENV
1898 if (!PL_use_safe_putenv) {
1899 /* most putenv()s leak, so we manipulate environ directly */
1901 const I32 len = strlen(nam);
1904 /* where does it go? */
1905 for (i = 0; environ[i]; i++) {
1906 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1910 if (environ == PL_origenviron) { /* need we copy environment? */
1916 while (environ[max])
1918 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1919 for (j=0; j<max; j++) { /* copy environment */
1920 const int len = strlen(environ[j]);
1921 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1922 Copy(environ[j], tmpenv[j], len+1, char);
1925 environ = tmpenv; /* tell exec where it is now */
1928 safesysfree(environ[i]);
1929 while (environ[i]) {
1930 environ[i] = environ[i+1];
1935 if (!environ[i]) { /* does not exist yet */
1936 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1937 environ[i+1] = NULL; /* make sure it's null terminated */
1940 safesysfree(environ[i]);
1944 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1945 /* all that work just for this */
1946 my_setenv_format(environ[i], nam, nlen, val, vlen);
1949 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
1950 # if defined(HAS_UNSETENV)
1952 (void)unsetenv(nam);
1954 (void)setenv(nam, val, 1);
1956 # else /* ! HAS_UNSETENV */
1957 (void)setenv(nam, val, 1);
1958 # endif /* HAS_UNSETENV */
1960 # if defined(HAS_UNSETENV)
1962 (void)unsetenv(nam);
1964 const int nlen = strlen(nam);
1965 const int vlen = strlen(val);
1966 char * const new_env =
1967 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1968 my_setenv_format(new_env, nam, nlen, val, vlen);
1969 (void)putenv(new_env);
1971 # else /* ! HAS_UNSETENV */
1973 const int nlen = strlen(nam);
1979 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1980 /* all that work just for this */
1981 my_setenv_format(new_env, nam, nlen, val, vlen);
1982 (void)putenv(new_env);
1983 # endif /* HAS_UNSETENV */
1984 # endif /* __CYGWIN__ */
1985 #ifndef PERL_USE_SAFE_PUTENV
1991 #else /* WIN32 || NETWARE */
1994 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1998 const int nlen = strlen(nam);
2005 Newx(envstr, nlen+vlen+2, char);
2006 my_setenv_format(envstr, nam, nlen, val, vlen);
2007 (void)PerlEnv_putenv(envstr);
2011 #endif /* WIN32 || NETWARE */
2013 #endif /* !VMS && !EPOC*/
2015 #ifdef UNLINK_ALL_VERSIONS
2017 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2021 PERL_ARGS_ASSERT_UNLNK;
2023 while (PerlLIO_unlink(f) >= 0)
2025 return retries ? 0 : -1;
2029 /* this is a drop-in replacement for bcopy() */
2030 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2032 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2034 char * const retval = to;
2036 PERL_ARGS_ASSERT_MY_BCOPY;
2040 if (from - to >= 0) {
2048 *(--to) = *(--from);
2054 /* this is a drop-in replacement for memset() */
2057 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2059 char * const retval = loc;
2061 PERL_ARGS_ASSERT_MY_MEMSET;
2071 /* this is a drop-in replacement for bzero() */
2072 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2074 Perl_my_bzero(register char *loc, register I32 len)
2076 char * const retval = loc;
2078 PERL_ARGS_ASSERT_MY_BZERO;
2088 /* this is a drop-in replacement for memcmp() */
2089 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2091 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2093 const U8 *a = (const U8 *)s1;
2094 const U8 *b = (const U8 *)s2;
2097 PERL_ARGS_ASSERT_MY_MEMCMP;
2102 if ((tmp = *a++ - *b++))
2107 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2110 /* This vsprintf replacement should generally never get used, since
2111 vsprintf was available in both System V and BSD 2.11. (There may
2112 be some cross-compilation or embedded set-ups where it is needed,
2115 If you encounter a problem in this function, it's probably a symptom
2116 that Configure failed to detect your system's vprintf() function.
2117 See the section on "item vsprintf" in the INSTALL file.
2119 This version may compile on systems with BSD-ish <stdio.h>,
2120 but probably won't on others.
2123 #ifdef USE_CHAR_VSPRINTF
2128 vsprintf(char *dest, const char *pat, void *args)
2132 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2133 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2134 FILE_cnt(&fakebuf) = 32767;
2136 /* These probably won't compile -- If you really need
2137 this, you'll have to figure out some other method. */
2138 fakebuf._ptr = dest;
2139 fakebuf._cnt = 32767;
2144 fakebuf._flag = _IOWRT|_IOSTRG;
2145 _doprnt(pat, args, &fakebuf); /* what a kludge */
2146 #if defined(STDIO_PTR_LVALUE)
2147 *(FILE_ptr(&fakebuf)++) = '\0';
2149 /* PerlIO has probably #defined away fputc, but we want it here. */
2151 # undef fputc /* XXX Should really restore it later */
2153 (void)fputc('\0', &fakebuf);
2155 #ifdef USE_CHAR_VSPRINTF
2158 return 0; /* perl doesn't use return value */
2162 #endif /* HAS_VPRINTF */
2165 #if BYTEORDER != 0x4321
2167 Perl_my_swap(pTHX_ short s)
2169 #if (BYTEORDER & 1) == 0
2172 result = ((s & 255) << 8) + ((s >> 8) & 255);
2180 Perl_my_htonl(pTHX_ long l)
2184 char c[sizeof(long)];
2187 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2188 #if BYTEORDER == 0x12345678
2191 u.c[0] = (l >> 24) & 255;
2192 u.c[1] = (l >> 16) & 255;
2193 u.c[2] = (l >> 8) & 255;
2197 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2198 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2203 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2204 u.c[o & 0xf] = (l >> s) & 255;
2212 Perl_my_ntohl(pTHX_ long l)
2216 char c[sizeof(long)];
2219 #if BYTEORDER == 0x1234
2220 u.c[0] = (l >> 24) & 255;
2221 u.c[1] = (l >> 16) & 255;
2222 u.c[2] = (l >> 8) & 255;
2226 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2227 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2234 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2235 l |= (u.c[o & 0xf] & 255) << s;
2242 #endif /* BYTEORDER != 0x4321 */
2246 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2247 * If these functions are defined,
2248 * the BYTEORDER is neither 0x1234 nor 0x4321.
2249 * However, this is not assumed.
2253 #define HTOLE(name,type) \
2255 name (register type n) \
2259 char c[sizeof(type)]; \
2263 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2264 u.c[i] = (n >> s) & 0xFF; \
2269 #define LETOH(name,type) \
2271 name (register type n) \
2275 char c[sizeof(type)]; \
2281 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2282 n |= ((type)(u.c[i] & 0xFF)) << s; \
2288 * Big-endian byte order functions.
2291 #define HTOBE(name,type) \
2293 name (register type n) \
2297 char c[sizeof(type)]; \
2300 U32 s = 8*(sizeof(u.c)-1); \
2301 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2302 u.c[i] = (n >> s) & 0xFF; \
2307 #define BETOH(name,type) \
2309 name (register type n) \
2313 char c[sizeof(type)]; \
2316 U32 s = 8*(sizeof(u.c)-1); \
2319 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2320 n |= ((type)(u.c[i] & 0xFF)) << s; \
2326 * If we just can't do it...
2329 #define NOT_AVAIL(name,type) \
2331 name (register type n) \
2333 Perl_croak_nocontext(#name "() not available"); \
2334 return n; /* not reached */ \
2338 #if defined(HAS_HTOVS) && !defined(htovs)
2341 #if defined(HAS_HTOVL) && !defined(htovl)
2344 #if defined(HAS_VTOHS) && !defined(vtohs)
2347 #if defined(HAS_VTOHL) && !defined(vtohl)
2351 #ifdef PERL_NEED_MY_HTOLE16
2353 HTOLE(Perl_my_htole16,U16)
2355 NOT_AVAIL(Perl_my_htole16,U16)
2358 #ifdef PERL_NEED_MY_LETOH16
2360 LETOH(Perl_my_letoh16,U16)
2362 NOT_AVAIL(Perl_my_letoh16,U16)
2365 #ifdef PERL_NEED_MY_HTOBE16
2367 HTOBE(Perl_my_htobe16,U16)
2369 NOT_AVAIL(Perl_my_htobe16,U16)
2372 #ifdef PERL_NEED_MY_BETOH16
2374 BETOH(Perl_my_betoh16,U16)
2376 NOT_AVAIL(Perl_my_betoh16,U16)
2380 #ifdef PERL_NEED_MY_HTOLE32
2382 HTOLE(Perl_my_htole32,U32)
2384 NOT_AVAIL(Perl_my_htole32,U32)
2387 #ifdef PERL_NEED_MY_LETOH32
2389 LETOH(Perl_my_letoh32,U32)
2391 NOT_AVAIL(Perl_my_letoh32,U32)
2394 #ifdef PERL_NEED_MY_HTOBE32
2396 HTOBE(Perl_my_htobe32,U32)
2398 NOT_AVAIL(Perl_my_htobe32,U32)
2401 #ifdef PERL_NEED_MY_BETOH32
2403 BETOH(Perl_my_betoh32,U32)
2405 NOT_AVAIL(Perl_my_betoh32,U32)
2409 #ifdef PERL_NEED_MY_HTOLE64
2411 HTOLE(Perl_my_htole64,U64)
2413 NOT_AVAIL(Perl_my_htole64,U64)
2416 #ifdef PERL_NEED_MY_LETOH64
2418 LETOH(Perl_my_letoh64,U64)
2420 NOT_AVAIL(Perl_my_letoh64,U64)
2423 #ifdef PERL_NEED_MY_HTOBE64
2425 HTOBE(Perl_my_htobe64,U64)
2427 NOT_AVAIL(Perl_my_htobe64,U64)
2430 #ifdef PERL_NEED_MY_BETOH64
2432 BETOH(Perl_my_betoh64,U64)
2434 NOT_AVAIL(Perl_my_betoh64,U64)
2438 #ifdef PERL_NEED_MY_HTOLES
2439 HTOLE(Perl_my_htoles,short)
2441 #ifdef PERL_NEED_MY_LETOHS
2442 LETOH(Perl_my_letohs,short)
2444 #ifdef PERL_NEED_MY_HTOBES
2445 HTOBE(Perl_my_htobes,short)
2447 #ifdef PERL_NEED_MY_BETOHS
2448 BETOH(Perl_my_betohs,short)
2451 #ifdef PERL_NEED_MY_HTOLEI
2452 HTOLE(Perl_my_htolei,int)
2454 #ifdef PERL_NEED_MY_LETOHI
2455 LETOH(Perl_my_letohi,int)
2457 #ifdef PERL_NEED_MY_HTOBEI
2458 HTOBE(Perl_my_htobei,int)
2460 #ifdef PERL_NEED_MY_BETOHI
2461 BETOH(Perl_my_betohi,int)
2464 #ifdef PERL_NEED_MY_HTOLEL
2465 HTOLE(Perl_my_htolel,long)
2467 #ifdef PERL_NEED_MY_LETOHL
2468 LETOH(Perl_my_letohl,long)
2470 #ifdef PERL_NEED_MY_HTOBEL
2471 HTOBE(Perl_my_htobel,long)
2473 #ifdef PERL_NEED_MY_BETOHL
2474 BETOH(Perl_my_betohl,long)
2478 Perl_my_swabn(void *ptr, int n)
2480 char *s = (char *)ptr;
2481 char *e = s + (n-1);
2484 PERL_ARGS_ASSERT_MY_SWABN;
2486 for (n /= 2; n > 0; s++, e--, n--) {
2494 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2496 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2505 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2507 PERL_FLUSHALL_FOR_CHILD;
2508 This = (*mode == 'w');
2512 taint_proper("Insecure %s%s", "EXEC");
2514 if (PerlProc_pipe(p) < 0)
2516 /* Try for another pipe pair for error return */
2517 if (PerlProc_pipe(pp) >= 0)
2519 while ((pid = PerlProc_fork()) < 0) {
2520 if (errno != EAGAIN) {
2521 PerlLIO_close(p[This]);
2522 PerlLIO_close(p[that]);
2524 PerlLIO_close(pp[0]);
2525 PerlLIO_close(pp[1]);
2529 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2538 /* Close parent's end of error status pipe (if any) */
2540 PerlLIO_close(pp[0]);
2541 #if defined(HAS_FCNTL) && defined(F_SETFD)
2542 /* Close error pipe automatically if exec works */
2543 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2546 /* Now dup our end of _the_ pipe to right position */
2547 if (p[THIS] != (*mode == 'r')) {
2548 PerlLIO_dup2(p[THIS], *mode == 'r');
2549 PerlLIO_close(p[THIS]);
2550 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2551 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2554 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2555 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2556 /* No automatic close - do it by hand */
2563 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2569 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2575 do_execfree(); /* free any memory malloced by child on fork */
2577 PerlLIO_close(pp[1]);
2578 /* Keep the lower of the two fd numbers */
2579 if (p[that] < p[This]) {
2580 PerlLIO_dup2(p[This], p[that]);
2581 PerlLIO_close(p[This]);
2585 PerlLIO_close(p[that]); /* close child's end of pipe */
2587 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2588 SvUPGRADE(sv,SVt_IV);
2590 PL_forkprocess = pid;
2591 /* If we managed to get status pipe check for exec fail */
2592 if (did_pipes && pid > 0) {
2597 while (n < sizeof(int)) {
2598 n1 = PerlLIO_read(pp[0],
2599 (void*)(((char*)&errkid)+n),
2605 PerlLIO_close(pp[0]);
2607 if (n) { /* Error */
2609 PerlLIO_close(p[This]);
2610 if (n != sizeof(int))
2611 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2613 pid2 = wait4pid(pid, &status, 0);
2614 } while (pid2 == -1 && errno == EINTR);
2615 errno = errkid; /* Propagate errno from kid */
2620 PerlLIO_close(pp[0]);
2621 return PerlIO_fdopen(p[This], mode);
2623 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2624 return my_syspopen4(aTHX_ NULL, mode, n, args);
2626 Perl_croak(aTHX_ "List form of piped open not implemented");
2627 return (PerlIO *) NULL;
2632 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2633 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
2635 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2642 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2646 PERL_ARGS_ASSERT_MY_POPEN;
2648 PERL_FLUSHALL_FOR_CHILD;
2651 return my_syspopen(aTHX_ cmd,mode);
2654 This = (*mode == 'w');
2656 if (doexec && TAINTING_get) {
2658 taint_proper("Insecure %s%s", "EXEC");
2660 if (PerlProc_pipe(p) < 0)
2662 if (doexec && PerlProc_pipe(pp) >= 0)
2664 while ((pid = PerlProc_fork()) < 0) {
2665 if (errno != EAGAIN) {
2666 PerlLIO_close(p[This]);
2667 PerlLIO_close(p[that]);
2669 PerlLIO_close(pp[0]);
2670 PerlLIO_close(pp[1]);
2673 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2676 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2686 PerlLIO_close(pp[0]);
2687 #if defined(HAS_FCNTL) && defined(F_SETFD)
2688 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2691 if (p[THIS] != (*mode == 'r')) {
2692 PerlLIO_dup2(p[THIS], *mode == 'r');
2693 PerlLIO_close(p[THIS]);
2694 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2695 PerlLIO_close(p[THAT]);
2698 PerlLIO_close(p[THAT]);
2701 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2708 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2713 /* may or may not use the shell */
2714 do_exec3(cmd, pp[1], did_pipes);
2717 #endif /* defined OS2 */
2719 #ifdef PERLIO_USING_CRLF
2720 /* Since we circumvent IO layers when we manipulate low-level
2721 filedescriptors directly, need to manually switch to the
2722 default, binary, low-level mode; see PerlIOBuf_open(). */
2723 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2726 #ifdef PERL_USES_PL_PIDSTATUS
2727 hv_clear(PL_pidstatus); /* we have no children */
2733 do_execfree(); /* free any memory malloced by child on vfork */
2735 PerlLIO_close(pp[1]);
2736 if (p[that] < p[This]) {
2737 PerlLIO_dup2(p[This], p[that]);
2738 PerlLIO_close(p[This]);
2742 PerlLIO_close(p[that]);
2744 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2745 SvUPGRADE(sv,SVt_IV);
2747 PL_forkprocess = pid;
2748 if (did_pipes && pid > 0) {
2753 while (n < sizeof(int)) {
2754 n1 = PerlLIO_read(pp[0],
2755 (void*)(((char*)&errkid)+n),
2761 PerlLIO_close(pp[0]);
2763 if (n) { /* Error */
2765 PerlLIO_close(p[This]);
2766 if (n != sizeof(int))
2767 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2769 pid2 = wait4pid(pid, &status, 0);
2770 } while (pid2 == -1 && errno == EINTR);
2771 errno = errkid; /* Propagate errno from kid */
2776 PerlLIO_close(pp[0]);
2777 return PerlIO_fdopen(p[This], mode);
2783 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2785 PERL_ARGS_ASSERT_MY_POPEN;
2786 PERL_FLUSHALL_FOR_CHILD;
2787 /* Call system's popen() to get a FILE *, then import it.
2788 used 0 for 2nd parameter to PerlIO_importFILE;
2791 return PerlIO_importFILE(popen(cmd, mode), 0);
2795 FILE *djgpp_popen();
2797 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2799 PERL_FLUSHALL_FOR_CHILD;
2800 /* Call system's popen() to get a FILE *, then import it.
2801 used 0 for 2nd parameter to PerlIO_importFILE;
2804 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2807 #if defined(__LIBCATAMOUNT__)
2809 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2817 #endif /* !DOSISH */
2819 /* this is called in parent before the fork() */
2821 Perl_atfork_lock(void)
2824 #if defined(USE_ITHREADS)
2825 /* locks must be held in locking order (if any) */
2827 MUTEX_LOCK(&PL_malloc_mutex);
2833 /* this is called in both parent and child after the fork() */
2835 Perl_atfork_unlock(void)
2838 #if defined(USE_ITHREADS)
2839 /* locks must be released in same order as in atfork_lock() */
2841 MUTEX_UNLOCK(&PL_malloc_mutex);
2850 #if defined(HAS_FORK)
2852 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2857 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2858 * handlers elsewhere in the code */
2863 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2864 Perl_croak_nocontext("fork() not available");
2866 #endif /* HAS_FORK */
2871 Perl_dump_fds(pTHX_ const char *const s)
2876 PERL_ARGS_ASSERT_DUMP_FDS;
2878 PerlIO_printf(Perl_debug_log,"%s", s);
2879 for (fd = 0; fd < 32; fd++) {
2880 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2881 PerlIO_printf(Perl_debug_log," %d",fd);
2883 PerlIO_printf(Perl_debug_log,"\n");
2886 #endif /* DUMP_FDS */
2890 dup2(int oldfd, int newfd)
2892 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2895 PerlLIO_close(newfd);
2896 return fcntl(oldfd, F_DUPFD, newfd);
2898 #define DUP2_MAX_FDS 256
2899 int fdtmp[DUP2_MAX_FDS];
2905 PerlLIO_close(newfd);
2906 /* good enough for low fd's... */
2907 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2908 if (fdx >= DUP2_MAX_FDS) {
2916 PerlLIO_close(fdtmp[--fdx]);
2923 #ifdef HAS_SIGACTION
2926 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2929 struct sigaction act, oact;
2932 /* only "parent" interpreter can diddle signals */
2933 if (PL_curinterp != aTHX)
2934 return (Sighandler_t) SIG_ERR;
2937 act.sa_handler = (void(*)(int))handler;
2938 sigemptyset(&act.sa_mask);
2941 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2942 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2944 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2945 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2946 act.sa_flags |= SA_NOCLDWAIT;
2948 if (sigaction(signo, &act, &oact) == -1)
2949 return (Sighandler_t) SIG_ERR;
2951 return (Sighandler_t) oact.sa_handler;
2955 Perl_rsignal_state(pTHX_ int signo)
2957 struct sigaction oact;
2958 PERL_UNUSED_CONTEXT;
2960 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2961 return (Sighandler_t) SIG_ERR;
2963 return (Sighandler_t) oact.sa_handler;
2967 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2970 struct sigaction act;
2972 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2975 /* only "parent" interpreter can diddle signals */
2976 if (PL_curinterp != aTHX)
2980 act.sa_handler = (void(*)(int))handler;
2981 sigemptyset(&act.sa_mask);
2984 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2985 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2987 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2988 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2989 act.sa_flags |= SA_NOCLDWAIT;
2991 return sigaction(signo, &act, save);
2995 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2999 /* only "parent" interpreter can diddle signals */
3000 if (PL_curinterp != aTHX)
3004 return sigaction(signo, save, (struct sigaction *)NULL);
3007 #else /* !HAS_SIGACTION */
3010 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3012 #if defined(USE_ITHREADS) && !defined(WIN32)
3013 /* only "parent" interpreter can diddle signals */
3014 if (PL_curinterp != aTHX)
3015 return (Sighandler_t) SIG_ERR;
3018 return PerlProc_signal(signo, handler);
3029 Perl_rsignal_state(pTHX_ int signo)
3032 Sighandler_t oldsig;
3034 #if defined(USE_ITHREADS) && !defined(WIN32)
3035 /* only "parent" interpreter can diddle signals */
3036 if (PL_curinterp != aTHX)
3037 return (Sighandler_t) SIG_ERR;
3041 oldsig = PerlProc_signal(signo, sig_trap);
3042 PerlProc_signal(signo, oldsig);
3044 PerlProc_kill(PerlProc_getpid(), signo);
3049 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3051 #if defined(USE_ITHREADS) && !defined(WIN32)
3052 /* only "parent" interpreter can diddle signals */
3053 if (PL_curinterp != aTHX)
3056 *save = PerlProc_signal(signo, handler);
3057 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3061 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3063 #if defined(USE_ITHREADS) && !defined(WIN32)
3064 /* only "parent" interpreter can diddle signals */
3065 if (PL_curinterp != aTHX)
3068 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3071 #endif /* !HAS_SIGACTION */
3072 #endif /* !PERL_MICRO */
3074 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3075 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
3077 Perl_my_pclose(pTHX_ PerlIO *ptr)
3080 Sigsave_t hstat, istat, qstat;
3087 const int fd = PerlIO_fileno(ptr);
3090 /* Find out whether the refcount is low enough for us to wait for the
3091 child proc without blocking. */
3092 const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
3094 const bool should_wait = 1;
3097 svp = av_fetch(PL_fdpid,fd,TRUE);
3098 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3100 *svp = &PL_sv_undef;
3102 if (pid == -1) { /* Opened by popen. */
3103 return my_syspclose(ptr);
3106 close_failed = (PerlIO_close(ptr) == EOF);
3109 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3110 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3111 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3113 if (should_wait) do {
3114 pid2 = wait4pid(pid, &status, 0);
3115 } while (pid2 == -1 && errno == EINTR);
3117 rsignal_restore(SIGHUP, &hstat);
3118 rsignal_restore(SIGINT, &istat);
3119 rsignal_restore(SIGQUIT, &qstat);
3127 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3132 #if defined(__LIBCATAMOUNT__)
3134 Perl_my_pclose(pTHX_ PerlIO *ptr)
3139 #endif /* !DOSISH */
3141 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3143 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3147 PERL_ARGS_ASSERT_WAIT4PID;
3150 #ifdef PERL_USES_PL_PIDSTATUS
3153 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3154 pid, rather than a string form. */
3155 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3156 if (svp && *svp != &PL_sv_undef) {
3157 *statusp = SvIVX(*svp);
3158 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3166 hv_iterinit(PL_pidstatus);
3167 if ((entry = hv_iternext(PL_pidstatus))) {
3168 SV * const sv = hv_iterval(PL_pidstatus,entry);
3170 const char * const spid = hv_iterkey(entry,&len);
3172 assert (len == sizeof(Pid_t));
3173 memcpy((char *)&pid, spid, len);
3174 *statusp = SvIVX(sv);
3175 /* The hash iterator is currently on this entry, so simply
3176 calling hv_delete would trigger the lazy delete, which on
3177 aggregate does more work, beacuse next call to hv_iterinit()
3178 would spot the flag, and have to call the delete routine,
3179 while in the meantime any new entries can't re-use that
3181 hv_iterinit(PL_pidstatus);
3182 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3189 # ifdef HAS_WAITPID_RUNTIME
3190 if (!HAS_WAITPID_RUNTIME)
3193 result = PerlProc_waitpid(pid,statusp,flags);
3196 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3197 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3200 #ifdef PERL_USES_PL_PIDSTATUS
3201 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3206 Perl_croak(aTHX_ "Can't do waitpid with flags");
3208 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3209 pidgone(result,*statusp);
3215 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3218 if (result < 0 && errno == EINTR) {
3220 errno = EINTR; /* reset in case a signal handler changed $! */
3224 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3226 #ifdef PERL_USES_PL_PIDSTATUS
3228 S_pidgone(pTHX_ Pid_t pid, int status)
3232 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3233 SvUPGRADE(sv,SVt_IV);
3234 SvIV_set(sv, status);
3239 #if defined(OS2) || defined(EPOC)
3242 int /* Cannot prototype with I32
3244 my_syspclose(PerlIO *ptr)
3247 Perl_my_pclose(pTHX_ PerlIO *ptr)
3250 /* Needs work for PerlIO ! */
3251 FILE * const f = PerlIO_findFILE(ptr);
3252 const I32 result = pclose(f);
3253 PerlIO_releaseFILE(ptr,f);
3261 Perl_my_pclose(pTHX_ PerlIO *ptr)
3263 /* Needs work for PerlIO ! */
3264 FILE * const f = PerlIO_findFILE(ptr);
3265 I32 result = djgpp_pclose(f);
3266 result = (result << 8) & 0xff00;
3267 PerlIO_releaseFILE(ptr,f);
3272 #define PERL_REPEATCPY_LINEAR 4
3274 Perl_repeatcpy(register char *to, register const char *from, I32 len, register IV count)
3276 PERL_ARGS_ASSERT_REPEATCPY;
3281 croak_memory_wrap();
3284 memset(to, *from, count);
3287 IV items, linear, half;
3289 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3290 for (items = 0; items < linear; ++items) {
3291 const char *q = from;
3293 for (todo = len; todo > 0; todo--)
3298 while (items <= half) {
3299 IV size = items * len;
3300 memcpy(p, to, size);
3306 memcpy(p, to, (count - items) * len);
3312 Perl_same_dirent(pTHX_ const char *a, const char *b)
3314 char *fa = strrchr(a,'/');
3315 char *fb = strrchr(b,'/');
3318 SV * const tmpsv = sv_newmortal();
3320 PERL_ARGS_ASSERT_SAME_DIRENT;
3333 sv_setpvs(tmpsv, ".");
3335 sv_setpvn(tmpsv, a, fa - a);
3336 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3339 sv_setpvs(tmpsv, ".");
3341 sv_setpvn(tmpsv, b, fb - b);
3342 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3344 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3345 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3347 #endif /* !HAS_RENAME */
3350 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3351 const char *const *const search_ext, I32 flags)
3354 const char *xfound = NULL;
3355 char *xfailed = NULL;
3356 char tmpbuf[MAXPATHLEN];
3361 #if defined(DOSISH) && !defined(OS2)
3362 # define SEARCH_EXTS ".bat", ".cmd", NULL
3363 # define MAX_EXT_LEN 4
3366 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3367 # define MAX_EXT_LEN 4
3370 # define SEARCH_EXTS ".pl", ".com", NULL
3371 # define MAX_EXT_LEN 4
3373 /* additional extensions to try in each dir if scriptname not found */
3375 static const char *const exts[] = { SEARCH_EXTS };
3376 const char *const *const ext = search_ext ? search_ext : exts;
3377 int extidx = 0, i = 0;
3378 const char *curext = NULL;
3380 PERL_UNUSED_ARG(search_ext);
3381 # define MAX_EXT_LEN 0
3384 PERL_ARGS_ASSERT_FIND_SCRIPT;
3387 * If dosearch is true and if scriptname does not contain path
3388 * delimiters, search the PATH for scriptname.
3390 * If SEARCH_EXTS is also defined, will look for each
3391 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3392 * while searching the PATH.
3394 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3395 * proceeds as follows:
3396 * If DOSISH or VMSISH:
3397 * + look for ./scriptname{,.foo,.bar}
3398 * + search the PATH for scriptname{,.foo,.bar}
3401 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3402 * this will not look in '.' if it's not in the PATH)
3407 # ifdef ALWAYS_DEFTYPES
3408 len = strlen(scriptname);
3409 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3410 int idx = 0, deftypes = 1;
3413 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3416 int idx = 0, deftypes = 1;
3419 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3421 /* The first time through, just add SEARCH_EXTS to whatever we
3422 * already have, so we can check for default file types. */
3424 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3430 if ((strlen(tmpbuf) + strlen(scriptname)
3431 + MAX_EXT_LEN) >= sizeof tmpbuf)
3432 continue; /* don't search dir with too-long name */
3433 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3437 if (strEQ(scriptname, "-"))
3439 if (dosearch) { /* Look in '.' first. */
3440 const char *cur = scriptname;
3442 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3444 if (strEQ(ext[i++],curext)) {
3445 extidx = -1; /* already has an ext */
3450 DEBUG_p(PerlIO_printf(Perl_debug_log,
3451 "Looking for %s\n",cur));
3452 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3453 && !S_ISDIR(PL_statbuf.st_mode)) {
3461 if (cur == scriptname) {
3462 len = strlen(scriptname);
3463 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3465 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3468 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3469 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3474 if (dosearch && !strchr(scriptname, '/')
3476 && !strchr(scriptname, '\\')
3478 && (s = PerlEnv_getenv("PATH")))
3482 bufend = s + strlen(s);
3483 while (s < bufend) {
3486 && *s != ';'; len++, s++) {
3487 if (len < sizeof tmpbuf)
3490 if (len < sizeof tmpbuf)
3493 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3499 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3500 continue; /* don't search dir with too-long name */
3503 && tmpbuf[len - 1] != '/'
3504 && tmpbuf[len - 1] != '\\'
3507 tmpbuf[len++] = '/';
3508 if (len == 2 && tmpbuf[0] == '.')
3510 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3514 len = strlen(tmpbuf);
3515 if (extidx > 0) /* reset after previous loop */
3519 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3520 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3521 if (S_ISDIR(PL_statbuf.st_mode)) {
3525 } while ( retval < 0 /* not there */
3526 && extidx>=0 && ext[extidx] /* try an extension? */
3527 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3532 if (S_ISREG(PL_statbuf.st_mode)
3533 && cando(S_IRUSR,TRUE,&PL_statbuf)
3534 #if !defined(DOSISH)
3535 && cando(S_IXUSR,TRUE,&PL_statbuf)
3539 xfound = tmpbuf; /* bingo! */
3543 xfailed = savepv(tmpbuf);
3546 if (!xfound && !seen_dot && !xfailed &&
3547 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3548 || S_ISDIR(PL_statbuf.st_mode)))
3550 seen_dot = 1; /* Disable message. */
3552 if (flags & 1) { /* do or die? */
3553 /* diag_listed_as: Can't execute %s */
3554 Perl_croak(aTHX_ "Can't %s %s%s%s",
3555 (xfailed ? "execute" : "find"),
3556 (xfailed ? xfailed : scriptname),
3557 (xfailed ? "" : " on PATH"),
3558 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3563 scriptname = xfound;
3565 return (scriptname ? savepv(scriptname) : NULL);
3568 #ifndef PERL_GET_CONTEXT_DEFINED
3571 Perl_get_context(void)
3574 #if defined(USE_ITHREADS)
3575 # ifdef OLD_PTHREADS_API
3577 int error = pthread_getspecific(PL_thr_key, &t)
3579 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3582 # ifdef I_MACH_CTHREADS
3583 return (void*)cthread_data(cthread_self());
3585 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3594 Perl_set_context(void *t)
3597 PERL_ARGS_ASSERT_SET_CONTEXT;
3598 #if defined(USE_ITHREADS)
3599 # ifdef I_MACH_CTHREADS
3600 cthread_set_data(cthread_self(), t);
3603 const int error = pthread_setspecific(PL_thr_key, t);
3605 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3613 #endif /* !PERL_GET_CONTEXT_DEFINED */
3615 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3624 Perl_get_op_names(pTHX)
3626 PERL_UNUSED_CONTEXT;
3627 return (char **)PL_op_name;
3631 Perl_get_op_descs(pTHX)
3633 PERL_UNUSED_CONTEXT;
3634 return (char **)PL_op_desc;
3638 Perl_get_no_modify(pTHX)
3640 PERL_UNUSED_CONTEXT;
3641 return PL_no_modify;
3645 Perl_get_opargs(pTHX)
3647 PERL_UNUSED_CONTEXT;
3648 return (U32 *)PL_opargs;
3652 Perl_get_ppaddr(pTHX)
3655 PERL_UNUSED_CONTEXT;
3656 return (PPADDR_t*)PL_ppaddr;
3659 #ifndef HAS_GETENV_LEN
3661 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3663 char * const env_trans = PerlEnv_getenv(env_elem);
3664 PERL_UNUSED_CONTEXT;
3665 PERL_ARGS_ASSERT_GETENV_LEN;
3667 *len = strlen(env_trans);
3674 Perl_get_vtbl(pTHX_ int vtbl_id)
3676 PERL_UNUSED_CONTEXT;
3678 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3679 ? NULL : PL_magic_vtables + vtbl_id;
3683 Perl_my_fflush_all(pTHX)
3685 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3686 return PerlIO_flush(NULL);
3688 # if defined(HAS__FWALK)
3689 extern int fflush(FILE *);
3690 /* undocumented, unprototyped, but very useful BSDism */
3691 extern void _fwalk(int (*)(FILE *));
3695 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3697 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3698 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3700 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3701 open_max = sysconf(_SC_OPEN_MAX);
3704 open_max = FOPEN_MAX;
3707 open_max = OPEN_MAX;
3718 for (i = 0; i < open_max; i++)
3719 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3720 STDIO_STREAM_ARRAY[i]._file < open_max &&
3721 STDIO_STREAM_ARRAY[i]._flag)
3722 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3726 SETERRNO(EBADF,RMS_IFI);
3733 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3735 if (ckWARN(WARN_IO)) {
3737 = gv && (isGV_with_GP(gv))
3740 const char * const direction = have == '>' ? "out" : "in";
3742 if (name && HEK_LEN(name))
3743 Perl_warner(aTHX_ packWARN(WARN_IO),
3744 "Filehandle %"HEKf" opened only for %sput",
3747 Perl_warner(aTHX_ packWARN(WARN_IO),
3748 "Filehandle opened only for %sput", direction);
3753 Perl_report_evil_fh(pTHX_ const GV *gv)
3755 const IO *io = gv ? GvIO(gv) : NULL;
3756 const PERL_BITFIELD16 op = PL_op->op_type;
3760 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3762 warn_type = WARN_CLOSED;
3766 warn_type = WARN_UNOPENED;
3769 if (ckWARN(warn_type)) {
3771 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3772 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3773 const char * const pars =
3774 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3775 const char * const func =
3777 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3778 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3780 const char * const type =
3782 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3783 ? "socket" : "filehandle");
3784 const bool have_name = name && SvCUR(name);
3785 Perl_warner(aTHX_ packWARN(warn_type),
3786 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3787 have_name ? " " : "",
3788 SVfARG(have_name ? name : &PL_sv_no));
3789 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3791 aTHX_ packWARN(warn_type),
3792 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3793 func, pars, have_name ? " " : "",
3794 SVfARG(have_name ? name : &PL_sv_no)
3799 /* To workaround core dumps from the uninitialised tm_zone we get the
3800 * system to give us a reasonable struct to copy. This fix means that
3801 * strftime uses the tm_zone and tm_gmtoff values returned by
3802 * localtime(time()). That should give the desired result most of the
3803 * time. But probably not always!
3805 * This does not address tzname aspects of NETaa14816.
3810 # ifndef STRUCT_TM_HASZONE
3811 # define STRUCT_TM_HASZONE
3815 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3816 # ifndef HAS_TM_TM_ZONE
3817 # define HAS_TM_TM_ZONE
3822 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3824 #ifdef HAS_TM_TM_ZONE
3826 const struct tm* my_tm;
3827 PERL_ARGS_ASSERT_INIT_TM;
3829 my_tm = localtime(&now);
3831 Copy(my_tm, ptm, 1, struct tm);
3833 PERL_ARGS_ASSERT_INIT_TM;
3834 PERL_UNUSED_ARG(ptm);
3839 * mini_mktime - normalise struct tm values without the localtime()
3840 * semantics (and overhead) of mktime().
3843 Perl_mini_mktime(pTHX_ struct tm *ptm)
3847 int month, mday, year, jday;
3848 int odd_cent, odd_year;
3849 PERL_UNUSED_CONTEXT;
3851 PERL_ARGS_ASSERT_MINI_MKTIME;
3853 #define DAYS_PER_YEAR 365
3854 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3855 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3856 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3857 #define SECS_PER_HOUR (60*60)
3858 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3859 /* parentheses deliberately absent on these two, otherwise they don't work */
3860 #define MONTH_TO_DAYS 153/5
3861 #define DAYS_TO_MONTH 5/153
3862 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3863 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3864 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3865 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3868 * Year/day algorithm notes:
3870 * With a suitable offset for numeric value of the month, one can find
3871 * an offset into the year by considering months to have 30.6 (153/5) days,
3872 * using integer arithmetic (i.e., with truncation). To avoid too much
3873 * messing about with leap days, we consider January and February to be
3874 * the 13th and 14th month of the previous year. After that transformation,
3875 * we need the month index we use to be high by 1 from 'normal human' usage,
3876 * so the month index values we use run from 4 through 15.
3878 * Given that, and the rules for the Gregorian calendar (leap years are those
3879 * divisible by 4 unless also divisible by 100, when they must be divisible
3880 * by 400 instead), we can simply calculate the number of days since some
3881 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3882 * the days we derive from our month index, and adding in the day of the
3883 * month. The value used here is not adjusted for the actual origin which
3884 * it normally would use (1 January A.D. 1), since we're not exposing it.
3885 * We're only building the value so we can turn around and get the
3886 * normalised values for the year, month, day-of-month, and day-of-year.
3888 * For going backward, we need to bias the value we're using so that we find
3889 * the right year value. (Basically, we don't want the contribution of
3890 * March 1st to the number to apply while deriving the year). Having done
3891 * that, we 'count up' the contribution to the year number by accounting for
3892 * full quadracenturies (400-year periods) with their extra leap days, plus
3893 * the contribution from full centuries (to avoid counting in the lost leap
3894 * days), plus the contribution from full quad-years (to count in the normal
3895 * leap days), plus the leftover contribution from any non-leap years.
3896 * At this point, if we were working with an actual leap day, we'll have 0
3897 * days left over. This is also true for March 1st, however. So, we have
3898 * to special-case that result, and (earlier) keep track of the 'odd'
3899 * century and year contributions. If we got 4 extra centuries in a qcent,
3900 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3901 * Otherwise, we add back in the earlier bias we removed (the 123 from
3902 * figuring in March 1st), find the month index (integer division by 30.6),
3903 * and the remainder is the day-of-month. We then have to convert back to
3904 * 'real' months (including fixing January and February from being 14/15 in
3905 * the previous year to being in the proper year). After that, to get
3906 * tm_yday, we work with the normalised year and get a new yearday value for
3907 * January 1st, which we subtract from the yearday value we had earlier,
3908 * representing the date we've re-built. This is done from January 1
3909 * because tm_yday is 0-origin.
3911 * Since POSIX time routines are only guaranteed to work for times since the
3912 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3913 * applies Gregorian calendar rules even to dates before the 16th century
3914 * doesn't bother me. Besides, you'd need cultural context for a given
3915 * date to know whether it was Julian or Gregorian calendar, and that's
3916 * outside the scope for this routine. Since we convert back based on the
3917 * same rules we used to build the yearday, you'll only get strange results
3918 * for input which needed normalising, or for the 'odd' century years which
3919 * were leap years in the Julian calendar but not in the Gregorian one.
3920 * I can live with that.
3922 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3923 * that's still outside the scope for POSIX time manipulation, so I don't
3927 year = 1900 + ptm->tm_year;
3928 month = ptm->tm_mon;
3929 mday = ptm->tm_mday;
3935 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3936 yearday += month*MONTH_TO_DAYS + mday + jday;
3938 * Note that we don't know when leap-seconds were or will be,
3939 * so we have to trust the user if we get something which looks
3940 * like a sensible leap-second. Wild values for seconds will
3941 * be rationalised, however.
3943 if ((unsigned) ptm->tm_sec <= 60) {
3950 secs += 60 * ptm->tm_min;
3951 secs += SECS_PER_HOUR * ptm->tm_hour;
3953 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3954 /* got negative remainder, but need positive time */
3955 /* back off an extra day to compensate */
3956 yearday += (secs/SECS_PER_DAY)-1;
3957 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3960 yearday += (secs/SECS_PER_DAY);
3961 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3964 else if (secs >= SECS_PER_DAY) {
3965 yearday += (secs/SECS_PER_DAY);
3966 secs %= SECS_PER_DAY;
3968 ptm->tm_hour = secs/SECS_PER_HOUR;
3969 secs %= SECS_PER_HOUR;
3970 ptm->tm_min = secs/60;
3972 ptm->tm_sec += secs;
3973 /* done with time of day effects */
3975 * The algorithm for yearday has (so far) left it high by 428.
3976 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3977 * bias it by 123 while trying to figure out what year it
3978 * really represents. Even with this tweak, the reverse
3979 * translation fails for years before A.D. 0001.
3980 * It would still fail for Feb 29, but we catch that one below.
3982 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3983 yearday -= YEAR_ADJUST;
3984 year = (yearday / DAYS_PER_QCENT) * 400;
3985 yearday %= DAYS_PER_QCENT;
3986 odd_cent = yearday / DAYS_PER_CENT;
3987 year += odd_cent * 100;
3988 yearday %= DAYS_PER_CENT;
3989 year += (yearday / DAYS_PER_QYEAR) * 4;
3990 yearday %= DAYS_PER_QYEAR;
3991 odd_year = yearday / DAYS_PER_YEAR;
3993 yearday %= DAYS_PER_YEAR;
3994 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3999 yearday += YEAR_ADJUST; /* recover March 1st crock */
4000 month = yearday*DAYS_TO_MONTH;
4001 yearday -= month*MONTH_TO_DAYS;
4002 /* recover other leap-year adjustment */
4011 ptm->tm_year = year - 1900;
4013 ptm->tm_mday = yearday;
4014 ptm->tm_mon = month;
4018 ptm->tm_mon = month - 1;
4020 /* re-build yearday based on Jan 1 to get tm_yday */
4022 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4023 yearday += 14*MONTH_TO_DAYS + 1;
4024 ptm->tm_yday = jday - yearday;
4025 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4029 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)
4037 PERL_ARGS_ASSERT_MY_STRFTIME;
4039 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4042 mytm.tm_hour = hour;
4043 mytm.tm_mday = mday;
4045 mytm.tm_year = year;
4046 mytm.tm_wday = wday;
4047 mytm.tm_yday = yday;
4048 mytm.tm_isdst = isdst;
4050 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4051 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4056 #ifdef HAS_TM_TM_GMTOFF
4057 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4059 #ifdef HAS_TM_TM_ZONE
4060 mytm.tm_zone = mytm2.tm_zone;
4065 Newx(buf, buflen, char);
4066 len = strftime(buf, buflen, fmt, &mytm);
4068 ** The following is needed to handle to the situation where
4069 ** tmpbuf overflows. Basically we want to allocate a buffer
4070 ** and try repeatedly. The reason why it is so complicated
4071 ** is that getting a return value of 0 from strftime can indicate
4072 ** one of the following:
4073 ** 1. buffer overflowed,
4074 ** 2. illegal conversion specifier, or
4075 ** 3. the format string specifies nothing to be returned(not
4076 ** an error). This could be because format is an empty string
4077 ** or it specifies %p that yields an empty string in some locale.
4078 ** If there is a better way to make it portable, go ahead by
4081 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4084 /* Possibly buf overflowed - try again with a bigger buf */
4085 const int fmtlen = strlen(fmt);
4086 int bufsize = fmtlen + buflen;
4088 Renew(buf, bufsize, char);
4090 buflen = strftime(buf, bufsize, fmt, &mytm);
4091 if (buflen > 0 && buflen < bufsize)
4093 /* heuristic to prevent out-of-memory errors */
4094 if (bufsize > 100*fmtlen) {
4100 Renew(buf, bufsize, char);
4105 Perl_croak(aTHX_ "panic: no strftime");
4111 #define SV_CWD_RETURN_UNDEF \
4112 sv_setsv(sv, &PL_sv_undef); \
4115 #define SV_CWD_ISDOT(dp) \
4116 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4117 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4120 =head1 Miscellaneous Functions
4122 =for apidoc getcwd_sv
4124 Fill the sv with current working directory
4129 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4130 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4131 * getcwd(3) if available
4132 * Comments from the orignal:
4133 * This is a faster version of getcwd. It's also more dangerous
4134 * because you might chdir out of a directory that you can't chdir
4138 Perl_getcwd_sv(pTHX_ register SV *sv)
4142 #ifndef INCOMPLETE_TAINTS
4146 PERL_ARGS_ASSERT_GETCWD_SV;
4150 char buf[MAXPATHLEN];
4152 /* Some getcwd()s automatically allocate a buffer of the given
4153 * size from the heap if they are given a NULL buffer pointer.
4154 * The problem is that this behaviour is not portable. */
4155 if (getcwd(buf, sizeof(buf) - 1)) {
4160 sv_setsv(sv, &PL_sv_undef);
4168 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4172 SvUPGRADE(sv, SVt_PV);
4174 if (PerlLIO_lstat(".", &statbuf) < 0) {
4175 SV_CWD_RETURN_UNDEF;
4178 orig_cdev = statbuf.st_dev;
4179 orig_cino = statbuf.st_ino;
4189 if (PerlDir_chdir("..") < 0) {
4190 SV_CWD_RETURN_UNDEF;
4192 if (PerlLIO_stat(".", &statbuf) < 0) {
4193 SV_CWD_RETURN_UNDEF;
4196 cdev = statbuf.st_dev;
4197 cino = statbuf.st_ino;
4199 if (odev == cdev && oino == cino) {
4202 if (!(dir = PerlDir_open("."))) {
4203 SV_CWD_RETURN_UNDEF;
4206 while ((dp = PerlDir_read(dir)) != NULL) {
4208 namelen = dp->d_namlen;
4210 namelen = strlen(dp->d_name);
4213 if (SV_CWD_ISDOT(dp)) {
4217 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4218 SV_CWD_RETURN_UNDEF;
4221 tdev = statbuf.st_dev;
4222 tino = statbuf.st_ino;
4223 if (tino == oino && tdev == odev) {
4229 SV_CWD_RETURN_UNDEF;
4232 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4233 SV_CWD_RETURN_UNDEF;
4236 SvGROW(sv, pathlen + namelen + 1);
4240 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4243 /* prepend current directory to the front */
4245 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4246 pathlen += (namelen + 1);
4248 #ifdef VOID_CLOSEDIR
4251 if (PerlDir_close(dir) < 0) {
4252 SV_CWD_RETURN_UNDEF;
4258 SvCUR_set(sv, pathlen);
4262 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4263 SV_CWD_RETURN_UNDEF;
4266 if (PerlLIO_stat(".", &statbuf) < 0) {
4267 SV_CWD_RETURN_UNDEF;
4270 cdev = statbuf.st_dev;
4271 cino = statbuf.st_ino;
4273 if (cdev != orig_cdev || cino != orig_cino) {
4274 Perl_croak(aTHX_ "Unstable directory path, "
4275 "current directory changed unexpectedly");
4286 #define VERSION_MAX 0x7FFFFFFF
4289 =for apidoc prescan_version
4291 Validate that a given string can be parsed as a version object, but doesn't
4292 actually perform the parsing. Can use either strict or lax validation rules.
4293 Can optionally set a number of hint variables to save the parsing code
4294 some time when tokenizing.
4299 Perl_prescan_version(pTHX_ const char *s, bool strict,
4300 const char **errstr,
4301 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4302 bool qv = (sqv ? *sqv : FALSE);
4304 int saw_decimal = 0;
4308 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4310 if (qv && isDIGIT(*d))
4311 goto dotted_decimal_version;
4313 if (*d == 'v') { /* explicit v-string */
4318 else { /* degenerate v-string */
4319 /* requires v1.2.3 */
4320 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4323 dotted_decimal_version:
4324 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4325 /* no leading zeros allowed */
4326 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4329 while (isDIGIT(*d)) /* integer part */
4335 d++; /* decimal point */
4340 /* require v1.2.3 */
4341 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4344 goto version_prescan_finish;
4351 while (isDIGIT(*d)) { /* just keep reading */
4353 while (isDIGIT(*d)) {
4355 /* maximum 3 digits between decimal */
4356 if (strict && j > 3) {
4357 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4362 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4365 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4370 else if (*d == '.') {
4372 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4377 else if (!isDIGIT(*d)) {
4383 if (strict && i < 2) {
4384 /* requires v1.2.3 */
4385 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4388 } /* end if dotted-decimal */
4390 { /* decimal versions */
4391 int j = 0; /* may need this later */
4392 /* special strict case for leading '.' or '0' */
4395 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4397 if (*d == '0' && isDIGIT(d[1])) {
4398 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4402 /* and we never support negative versions */
4404 BADVERSION(s,errstr,"Invalid version format (negative version number)");
4407 /* consume all of the integer part */
4411 /* look for a fractional part */
4413 /* we found it, so consume it */
4417 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4420 BADVERSION(s,errstr,"Invalid version format (version required)");
4422 /* found just an integer */
4423 goto version_prescan_finish;
4425 else if ( d == s ) {
4426 /* didn't find either integer or period */
4427 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4429 else if (*d == '_') {
4430 /* underscore can't come after integer part */
4432 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4434 else if (isDIGIT(d[1])) {
4435 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4438 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4442 /* anything else after integer part is just invalid data */
4443 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4446 /* scan the fractional part after the decimal point*/
4448 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4449 /* strict or lax-but-not-the-end */
4450 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4453 while (isDIGIT(*d)) {
4455 if (*d == '.' && isDIGIT(d[-1])) {
4457 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4460 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4462 d = (char *)s; /* start all over again */
4464 goto dotted_decimal_version;
4468 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4471 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4473 if ( ! isDIGIT(d[1]) ) {
4474 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4483 version_prescan_finish:
4487 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4488 /* trailing non-numeric data */
4489 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4497 *ssaw_decimal = saw_decimal;
4504 =for apidoc scan_version
4506 Returns a pointer to the next character after the parsed
4507 version string, as well as upgrading the passed in SV to
4510 Function must be called with an already existing SV like
4513 s = scan_version(s, SV *sv, bool qv);
4515 Performs some preprocessing to the string to ensure that
4516 it has the correct characteristics of a version. Flags the
4517 object if it contains an underscore (which denotes this
4518 is an alpha version). The boolean qv denotes that the version
4519 should be interpreted as if it had multiple decimals, even if
4526 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4531 const char *errstr = NULL;
4532 int saw_decimal = 0;
4536 AV * const av = newAV();
4537 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4539 PERL_ARGS_ASSERT_SCAN_VERSION;
4541 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4543 #ifndef NODEFAULT_SHAREKEYS
4544 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4547 while (isSPACE(*s)) /* leading whitespace is OK */
4550 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4552 /* "undef" is a special case and not an error */
4553 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4554 Perl_croak(aTHX_ "%s", errstr);
4564 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4566 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4567 if ( !qv && width < 3 )
4568 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4570 while (isDIGIT(*pos))
4572 if (!isALPHA(*pos)) {
4578 /* this is atoi() that delimits on underscores */
4579 const char *end = pos;
4583 /* the following if() will only be true after the decimal
4584 * point of a version originally created with a bare
4585 * floating point number, i.e. not quoted in any way
4587 if ( !qv && s > start && saw_decimal == 1 ) {
4591 rev += (*s - '0') * mult;
4593 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4594 || (PERL_ABS(rev) > VERSION_MAX )) {
4595 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4596 "Integer overflow in version %d",VERSION_MAX);
4607 while (--end >= s) {
4609 rev += (*end - '0') * mult;
4611 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4612 || (PERL_ABS(rev) > VERSION_MAX )) {
4613 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4614 "Integer overflow in version");
4623 /* Append revision */
4624 av_push(av, newSViv(rev));
4629 else if ( *pos == '.' )
4631 else if ( *pos == '_' && isDIGIT(pos[1]) )
4633 else if ( *pos == ',' && isDIGIT(pos[1]) )
4635 else if ( isDIGIT(*pos) )
4642 while ( isDIGIT(*pos) )
4647 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4655 if ( qv ) { /* quoted versions always get at least three terms*/
4656 I32 len = av_len(av);
4657 /* This for loop appears to trigger a compiler bug on OS X, as it
4658 loops infinitely. Yes, len is negative. No, it makes no sense.
4659 Compiler in question is:
4660 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4661 for ( len = 2 - len; len > 0; len-- )
4662 av_push(MUTABLE_AV(sv), newSViv(0));
4666 av_push(av, newSViv(0));
4669 /* need to save off the current version string for later */
4671 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4672 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4673 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4675 else if ( s > start ) {
4676 SV * orig = newSVpvn(start,s-start);
4677 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4678 /* need to insert a v to be consistent */
4679 sv_insert(orig, 0, 0, "v", 1);
4681 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4684 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4685 av_push(av, newSViv(0));
4688 /* And finally, store the AV in the hash */
4689 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4691 /* fix RT#19517 - special case 'undef' as string */
4692 if ( *s == 'u' && strEQ(s,"undef") ) {
4700 =for apidoc new_version
4702 Returns a new version object based on the passed in SV:
4704 SV *sv = new_version(SV *ver);
4706 Does not alter the passed in ver SV. See "upg_version" if you
4707 want to upgrade the SV.
4713 Perl_new_version(pTHX_ SV *ver)
4716 SV * const rv = newSV(0);
4717 PERL_ARGS_ASSERT_NEW_VERSION;
4718 if ( sv_isobject(ver) && sv_derived_from(ver, "version") )
4719 /* can just copy directly */
4722 AV * const av = newAV();
4724 /* This will get reblessed later if a derived class*/
4725 SV * const hv = newSVrv(rv, "version");
4726 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4727 #ifndef NODEFAULT_SHAREKEYS
4728 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4734 /* Begin copying all of the elements */
4735 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4736 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4738 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4739 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4741 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4743 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4744 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4747 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4749 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4750 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4753 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4754 /* This will get reblessed later if a derived class*/
4755 for ( key = 0; key <= av_len(sav); key++ )
4757 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4758 av_push(av, newSViv(rev));
4761 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4766 const MAGIC* const mg = SvVSTRING_mg(ver);
4767 if ( mg ) { /* already a v-string */
4768 const STRLEN len = mg->mg_len;
4769 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4770 sv_setpvn(rv,version,len);
4771 /* this is for consistency with the pure Perl class */
4772 if ( isDIGIT(*version) )
4773 sv_insert(rv, 0, 0, "v", 1);
4778 sv_setsv(rv,ver); /* make a duplicate */
4783 return upg_version(rv, FALSE);
4787 =for apidoc upg_version
4789 In-place upgrade of the supplied SV to a version object.
4791 SV *sv = upg_version(SV *sv, bool qv);
4793 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4794 to force this SV to be interpreted as an "extended" version.
4800 Perl_upg_version(pTHX_ SV *ver, bool qv)
4802 const char *version, *s;
4807 PERL_ARGS_ASSERT_UPG_VERSION;
4809 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4813 /* may get too much accuracy */
4815 SV *sv = SvNVX(ver) > 10e50 ? newSV(64) : 0;
4817 #ifdef USE_LOCALE_NUMERIC
4818 char *loc = savepv(setlocale(LC_NUMERIC, NULL));
4819 setlocale(LC_NUMERIC, "C");
4822 Perl_sv_setpvf(aTHX_ sv, "%.9"NVff, SvNVX(ver));
4823 buf = SvPV(sv, len);
4826 len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4829 #ifdef USE_LOCALE_NUMERIC
4830 setlocale(LC_NUMERIC, loc);
4833 while (buf[len-1] == '0' && len > 0) len--;
4834 if ( buf[len-1] == '.' ) len--; /* eat the trailing decimal */
4835 version = savepvn(buf, len);
4839 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4840 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4844 else /* must be a string or something like a string */
4847 version = savepv(SvPV(ver,len));
4849 # if PERL_VERSION > 5
4850 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4851 if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
4852 /* may be a v-string */
4853 char *testv = (char *)version;
4855 for (tlen=0; tlen < len; tlen++, testv++) {
4856 /* if one of the characters is non-text assume v-string */
4857 if (testv[0] < ' ') {
4858 SV * const nsv = sv_newmortal();
4861 int saw_decimal = 0;
4862 sv_setpvf(nsv,"v%vd",ver);
4863 pos = nver = savepv(SvPV_nolen(nsv));
4865 /* scan the resulting formatted string */
4866 pos++; /* skip the leading 'v' */
4867 while ( *pos == '.' || isDIGIT(*pos) ) {
4873 /* is definitely a v-string */
4874 if ( saw_decimal >= 2 ) {
4886 s = scan_version(version, ver, qv);
4888 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4889 "Version string '%s' contains invalid data; "
4890 "ignoring: '%s'", version, s);
4898 Validates that the SV contains valid internal structure for a version object.
4899 It may be passed either the version object (RV) or the hash itself (HV). If
4900 the structure is valid, it returns the HV. If the structure is invalid,
4903 SV *hv = vverify(sv);
4905 Note that it only confirms the bare minimum structure (so as not to get
4906 confused by derived classes which may contain additional hash entries):
4910 =item * The SV is an HV or a reference to an HV
4912 =item * The hash contains a "version" key
4914 =item * The "version" key has a reference to an AV as its value
4922 Perl_vverify(pTHX_ SV *vs)
4926 PERL_ARGS_ASSERT_VVERIFY;
4931 /* see if the appropriate elements exist */
4932 if ( SvTYPE(vs) == SVt_PVHV
4933 && hv_exists(MUTABLE_HV(vs), "version", 7)
4934 && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
4935 && SvTYPE(sv) == SVt_PVAV )
4944 Accepts a version object and returns the normalized floating
4945 point representation. Call like:
4949 NOTE: you can pass either the object directly or the SV
4950 contained within the RV.
4952 The SV returned has a refcount of 1.
4958 Perl_vnumify(pTHX_ SV *vs)
4966 PERL_ARGS_ASSERT_VNUMIFY;
4968 /* extract the HV from the object */
4971 Perl_croak(aTHX_ "Invalid version object");
4973 /* see if various flags exist */
4974 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
4976 if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
4977 width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
4982 /* attempt to retrieve the version array */
4983 if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
4984 return newSVpvs("0");
4990 return newSVpvs("0");
4993 digit = SvIV(*av_fetch(av, 0, 0));
4994 sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
4995 for ( i = 1 ; i < len ; i++ )
4997 digit = SvIV(*av_fetch(av, i, 0));
4999 const int denom = (width == 2 ? 10 : 100);
5000 const div_t term = div((int)PERL_ABS(digit),denom);
5001 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
5004 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5010 digit = SvIV(*av_fetch(av, len, 0));
5011 if ( alpha && width == 3 ) /* alpha version */
5013 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5017 sv_catpvs(sv, "000");
5025 Accepts a version object and returns the normalized string
5026 representation. Call like:
5030 NOTE: you can pass either the object directly or the SV
5031 contained within the RV.
5033 The SV returned has a refcount of 1.
5039 Perl_vnormal(pTHX_ SV *vs)
5046 PERL_ARGS_ASSERT_VNORMAL;
5048 /* extract the HV from the object */