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 */
45 # include <sys/wait.h>
50 # include <sys/select.h>
56 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
57 # define FD_CLOEXEC 1 /* NeXT needs this */
60 /* NOTE: Do not call the next three routines directly. Use the macros
61 * in handy.h, so that we can easily redefine everything to do tracking of
62 * allocated hunks back to the original New to track down any memory leaks.
63 * XXX This advice seems to be widely ignored :-( --AD August 1996.
70 /* Can't use PerlIO to write as it allocates memory */
71 PerlLIO_write(PerlIO_fileno(Perl_error_log),
72 PL_no_mem, strlen(PL_no_mem));
74 NORETURN_FUNCTION_END;
77 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
78 # define ALWAYS_NEED_THX
81 /* paranoid version of system's malloc() */
84 Perl_safesysmalloc(MEM_SIZE size)
86 #ifdef ALWAYS_NEED_THX
92 PerlIO_printf(Perl_error_log,
93 "Allocation too large: %lx\n", size) FLUSH;
96 #endif /* HAS_64K_LIMIT */
97 #ifdef PERL_TRACK_MEMPOOL
102 Perl_croak_nocontext("panic: malloc");
104 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
105 PERL_ALLOC_CHECK(ptr);
107 #ifdef PERL_TRACK_MEMPOOL
108 struct perl_memory_debug_header *const header
109 = (struct perl_memory_debug_header *)ptr;
113 PoisonNew(((char *)ptr), size, char);
116 #ifdef PERL_TRACK_MEMPOOL
117 header->interpreter = aTHX;
118 /* Link us into the list. */
119 header->prev = &PL_memory_debug_header;
120 header->next = PL_memory_debug_header.next;
121 PL_memory_debug_header.next = header;
122 header->next->prev = header;
126 ptr = (Malloc_t)((char*)ptr+sTHX);
128 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
132 #ifndef ALWAYS_NEED_THX
138 return write_no_mem();
144 /* paranoid version of system's realloc() */
147 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
149 #ifdef ALWAYS_NEED_THX
153 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
154 Malloc_t PerlMem_realloc();
155 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
159 PerlIO_printf(Perl_error_log,
160 "Reallocation too large: %lx\n", size) FLUSH;
163 #endif /* HAS_64K_LIMIT */
170 return safesysmalloc(size);
171 #ifdef PERL_TRACK_MEMPOOL
172 where = (Malloc_t)((char*)where-sTHX);
175 struct perl_memory_debug_header *const header
176 = (struct perl_memory_debug_header *)where;
178 if (header->interpreter != aTHX) {
179 Perl_croak_nocontext("panic: realloc from wrong pool");
181 assert(header->next->prev == header);
182 assert(header->prev->next == header);
184 if (header->size > size) {
185 const MEM_SIZE freed_up = header->size - size;
186 char *start_of_freed = ((char *)where) + size;
187 PoisonFree(start_of_freed, freed_up, char);
195 Perl_croak_nocontext("panic: realloc");
197 ptr = (Malloc_t)PerlMem_realloc(where,size);
198 PERL_ALLOC_CHECK(ptr);
200 /* MUST do this fixup first, before doing ANYTHING else, as anything else
201 might allocate memory/free/move memory, and until we do the fixup, it
202 may well be chasing (and writing to) free memory. */
203 #ifdef PERL_TRACK_MEMPOOL
205 struct perl_memory_debug_header *const header
206 = (struct perl_memory_debug_header *)ptr;
209 if (header->size < size) {
210 const MEM_SIZE fresh = size - header->size;
211 char *start_of_fresh = ((char *)ptr) + size;
212 PoisonNew(start_of_fresh, fresh, char);
216 header->next->prev = header;
217 header->prev->next = header;
219 ptr = (Malloc_t)((char*)ptr+sTHX);
223 /* In particular, must do that fixup above before logging anything via
224 *printf(), as it can reallocate memory, which can cause SEGVs. */
226 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
227 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
234 #ifndef ALWAYS_NEED_THX
240 return write_no_mem();
246 /* safe version of system's free() */
249 Perl_safesysfree(Malloc_t where)
251 #ifdef ALWAYS_NEED_THX
256 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
258 #ifdef PERL_TRACK_MEMPOOL
259 where = (Malloc_t)((char*)where-sTHX);
261 struct perl_memory_debug_header *const header
262 = (struct perl_memory_debug_header *)where;
264 if (header->interpreter != aTHX) {
265 Perl_croak_nocontext("panic: free from wrong pool");
268 Perl_croak_nocontext("panic: duplicate free");
270 if (!(header->next) || header->next->prev != header
271 || header->prev->next != header) {
272 Perl_croak_nocontext("panic: bad free");
274 /* Unlink us from the chain. */
275 header->next->prev = header->prev;
276 header->prev->next = header->next;
278 PoisonNew(where, header->size, char);
280 /* Trigger the duplicate free warning. */
288 /* safe version of system's calloc() */
291 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
293 #ifdef ALWAYS_NEED_THX
297 MEM_SIZE total_size = 0;
299 /* Even though calloc() for zero bytes is strange, be robust. */
300 if (size && (count <= MEM_SIZE_MAX / size))
301 total_size = size * count;
303 Perl_croak_nocontext("%s", PL_memory_wrap);
304 #ifdef PERL_TRACK_MEMPOOL
305 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
308 Perl_croak_nocontext("%s", PL_memory_wrap);
311 if (total_size > 0xffff) {
312 PerlIO_printf(Perl_error_log,
313 "Allocation too large: %lx\n", total_size) FLUSH;
316 #endif /* HAS_64K_LIMIT */
318 if ((long)size < 0 || (long)count < 0)
319 Perl_croak_nocontext("panic: calloc");
321 #ifdef PERL_TRACK_MEMPOOL
322 /* Have to use malloc() because we've added some space for our tracking
324 /* malloc(0) is non-portable. */
325 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
327 /* Use calloc() because it might save a memset() if the memory is fresh
328 and clean from the OS. */
330 ptr = (Malloc_t)PerlMem_calloc(count, size);
331 else /* calloc(0) is non-portable. */
332 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
334 PERL_ALLOC_CHECK(ptr);
335 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));
337 #ifdef PERL_TRACK_MEMPOOL
339 struct perl_memory_debug_header *const header
340 = (struct perl_memory_debug_header *)ptr;
342 memset((void*)ptr, 0, total_size);
343 header->interpreter = aTHX;
344 /* Link us into the list. */
345 header->prev = &PL_memory_debug_header;
346 header->next = PL_memory_debug_header.next;
347 PL_memory_debug_header.next = header;
348 header->next->prev = header;
350 header->size = total_size;
352 ptr = (Malloc_t)((char*)ptr+sTHX);
358 #ifndef ALWAYS_NEED_THX
363 return write_no_mem();
367 /* These must be defined when not using Perl's malloc for binary
372 Malloc_t Perl_malloc (MEM_SIZE nbytes)
375 return (Malloc_t)PerlMem_malloc(nbytes);
378 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
381 return (Malloc_t)PerlMem_calloc(elements, size);
384 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
387 return (Malloc_t)PerlMem_realloc(where, nbytes);
390 Free_t Perl_mfree (Malloc_t where)
398 /* copy a string up to some (non-backslashed) delimiter, if any */
401 Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
405 PERL_ARGS_ASSERT_DELIMCPY;
407 for (tolen = 0; from < fromend; from++, tolen++) {
409 if (from[1] != delim) {
416 else if (*from == delim)
427 /* return ptr to little string in big string, NULL if not found */
428 /* This routine was donated by Corey Satten. */
431 Perl_instr(register const char *big, register const char *little)
435 PERL_ARGS_ASSERT_INSTR;
443 register const char *s, *x;
446 for (x=big,s=little; *s; /**/ ) {
457 return (char*)(big-1);
462 /* same as instr but allow embedded nulls */
465 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
467 PERL_ARGS_ASSERT_NINSTR;
471 const char first = *little;
473 bigend -= lend - little++;
475 while (big <= bigend) {
476 if (*big++ == first) {
477 for (x=big,s=little; s < lend; x++,s++) {
481 return (char*)(big-1);
488 /* reverse of the above--find last substring */
491 Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
493 register const char *bigbeg;
494 register const I32 first = *little;
495 register const char * const littleend = lend;
497 PERL_ARGS_ASSERT_RNINSTR;
499 if (little >= littleend)
500 return (char*)bigend;
502 big = bigend - (littleend - little++);
503 while (big >= bigbeg) {
504 register const char *s, *x;
507 for (x=big+2,s=little; s < littleend; /**/ ) {
516 return (char*)(big+1);
521 /* As a space optimization, we do not compile tables for strings of length
522 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
523 special-cased in fbm_instr().
525 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
528 =head1 Miscellaneous Functions
530 =for apidoc fbm_compile
532 Analyses the string in order to make fast searches on it using fbm_instr()
533 -- the Boyer-Moore algorithm.
539 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
542 register const U8 *s;
548 PERL_ARGS_ASSERT_FBM_COMPILE;
550 if (flags & FBMcf_TAIL) {
551 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
552 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
553 if (mg && mg->mg_len >= 0)
556 s = (U8*)SvPV_force_mutable(sv, len);
557 if (len == 0) /* TAIL might be on a zero-length string. */
559 SvUPGRADE(sv, SVt_PVGV);
564 const unsigned char *sb;
565 const U8 mlen = (len>255) ? 255 : (U8)len;
568 Sv_Grow(sv, len + 256 + PERL_FBM_TABLE_OFFSET);
570 = (unsigned char*)(SvPVX_mutable(sv) + len + PERL_FBM_TABLE_OFFSET);
571 s = table - 1 - PERL_FBM_TABLE_OFFSET; /* last char */
572 memset((void*)table, mlen, 256);
574 sb = s - mlen + 1; /* first char (maybe) */
576 if (table[*s] == mlen)
581 Sv_Grow(sv, len + PERL_FBM_TABLE_OFFSET);
583 sv_magic(sv, NULL, PERL_MAGIC_bm, NULL, 0); /* deep magic */
585 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
586 for (i = 0; i < len; i++) {
587 if (PL_freq[s[i]] < frequency) {
589 frequency = PL_freq[s[i]];
592 BmFLAGS(sv) = (U8)flags;
593 BmRARE(sv) = s[rarest];
594 BmPREVIOUS(sv) = rarest;
595 BmUSEFUL(sv) = 100; /* Initial value */
596 if (flags & FBMcf_TAIL)
598 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %lu\n",
599 BmRARE(sv),(unsigned long)BmPREVIOUS(sv)));
602 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
603 /* If SvTAIL is actually due to \Z or \z, this gives false positives
607 =for apidoc fbm_instr
609 Returns the location of the SV in the string delimited by C<str> and
610 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
611 does not have to be fbm_compiled, but the search will not be as fast
618 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
620 register unsigned char *s;
622 register const unsigned char *little
623 = (const unsigned char *)SvPV_const(littlestr,l);
624 register STRLEN littlelen = l;
625 register const I32 multiline = flags & FBMrf_MULTILINE;
627 PERL_ARGS_ASSERT_FBM_INSTR;
629 if ((STRLEN)(bigend - big) < littlelen) {
630 if ( SvTAIL(littlestr)
631 && ((STRLEN)(bigend - big) == littlelen - 1)
633 || (*big == *little &&
634 memEQ((char *)big, (char *)little, littlelen - 1))))
639 if (littlelen <= 2) { /* Special-cased */
641 if (littlelen == 1) {
642 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
643 /* Know that bigend != big. */
644 if (bigend[-1] == '\n')
645 return (char *)(bigend - 1);
646 return (char *) bigend;
654 if (SvTAIL(littlestr))
655 return (char *) bigend;
659 return (char*)big; /* Cannot be SvTAIL! */
662 if (SvTAIL(littlestr) && !multiline) {
663 if (bigend[-1] == '\n' && bigend[-2] == *little)
664 return (char*)bigend - 2;
665 if (bigend[-1] == *little)
666 return (char*)bigend - 1;
670 /* This should be better than FBM if c1 == c2, and almost
671 as good otherwise: maybe better since we do less indirection.
672 And we save a lot of memory by caching no table. */
673 const unsigned char c1 = little[0];
674 const unsigned char c2 = little[1];
679 while (s <= bigend) {
689 goto check_1char_anchor;
700 goto check_1char_anchor;
703 while (s <= bigend) {
708 goto check_1char_anchor;
717 check_1char_anchor: /* One char and anchor! */
718 if (SvTAIL(littlestr) && (*bigend == *little))
719 return (char *)bigend; /* bigend is already decremented. */
722 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
723 s = bigend - littlelen;
724 if (s >= big && bigend[-1] == '\n' && *s == *little
725 /* Automatically of length > 2 */
726 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
728 return (char*)s; /* how sweet it is */
731 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
733 return (char*)s + 1; /* how sweet it is */
737 if (!SvVALID(littlestr)) {
738 char * const b = ninstr((char*)big,(char*)bigend,
739 (char*)little, (char*)little + littlelen);
741 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
742 /* Chop \n from littlestr: */
743 s = bigend - littlelen + 1;
745 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
755 if (littlelen > (STRLEN)(bigend - big))
759 register const unsigned char * const table
760 = little + littlelen + PERL_FBM_TABLE_OFFSET;
761 register const unsigned char *oldlittle;
763 --littlelen; /* Last char found by table lookup */
766 little += littlelen; /* last char */
772 if ((tmp = table[*s])) {
773 if ((s += tmp) < bigend)
777 else { /* less expensive than calling strncmp() */
778 register unsigned char * const olds = s;
783 if (*--s == *--little)
785 s = olds + 1; /* here we pay the price for failure */
787 if (s < bigend) /* fake up continue to outer loop */
796 && (BmFLAGS(littlestr) & FBMcf_TAIL)
797 && memEQ((char *)(bigend - littlelen),
798 (char *)(oldlittle - littlelen), littlelen) )
799 return (char*)bigend - littlelen;
804 /* start_shift, end_shift are positive quantities which give offsets
805 of ends of some substring of bigstr.
806 If "last" we want the last occurrence.
807 old_posp is the way of communication between consequent calls if
808 the next call needs to find the .
809 The initial *old_posp should be -1.
811 Note that we take into account SvTAIL, so one can get extra
812 optimizations if _ALL flag is set.
815 /* If SvTAIL is actually due to \Z or \z, this gives false positives
816 if PL_multiline. In fact if !PL_multiline the authoritative answer
817 is not supported yet. */
820 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
823 register const unsigned char *big;
825 register I32 previous;
827 register const unsigned char *little;
828 register I32 stop_pos;
829 register const unsigned char *littleend;
832 PERL_ARGS_ASSERT_SCREAMINSTR;
834 assert(SvTYPE(littlestr) == SVt_PVGV);
835 assert(SvVALID(littlestr));
838 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
839 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
841 if ( BmRARE(littlestr) == '\n'
842 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
843 little = (const unsigned char *)(SvPVX_const(littlestr));
844 littleend = little + SvCUR(littlestr);
851 little = (const unsigned char *)(SvPVX_const(littlestr));
852 littleend = little + SvCUR(littlestr);
854 /* The value of pos we can start at: */
855 previous = BmPREVIOUS(littlestr);
856 big = (const unsigned char *)(SvPVX_const(bigstr));
857 /* The value of pos we can stop at: */
858 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
859 if (previous + start_shift > stop_pos) {
861 stop_pos does not include SvTAIL in the count, so this check is incorrect
862 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
865 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
870 while (pos < previous + start_shift) {
871 if (!(pos += PL_screamnext[pos]))
876 register const unsigned char *s, *x;
877 if (pos >= stop_pos) break;
878 if (big[pos] != first)
880 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
886 if (s == littleend) {
888 if (!last) return (char *)(big+pos);
891 } while ( pos += PL_screamnext[pos] );
893 return (char *)(big+(*old_posp));
895 if (!SvTAIL(littlestr) || (end_shift > 0))
897 /* Ignore the trailing "\n". This code is not microoptimized */
898 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
899 stop_pos = littleend - little; /* Actual littlestr len */
904 && ((stop_pos == 1) ||
905 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
913 Returns true if the leading len bytes of the strings s1 and s2 are the same
914 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
915 match themselves and their opposite case counterparts. Non-cased and non-ASCII
916 range bytes match only themselves.
923 Perl_foldEQ(const char *s1, const char *s2, register I32 len)
925 register const U8 *a = (const U8 *)s1;
926 register const U8 *b = (const U8 *)s2;
928 PERL_ARGS_ASSERT_FOLDEQ;
931 if (*a != *b && *a != PL_fold[*b])
938 Perl_foldEQ_latin1(const char *s1, const char *s2, register I32 len)
940 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
941 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
942 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
943 * does it check that the strings each have at least 'len' characters */
945 register const U8 *a = (const U8 *)s1;
946 register const U8 *b = (const U8 *)s2;
948 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
951 if (*a != *b && *a != PL_fold_latin1[*b]) {
960 =for apidoc foldEQ_locale
962 Returns true if the leading len bytes of the strings s1 and s2 are the same
963 case-insensitively in the current locale; false otherwise.
969 Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
972 register const U8 *a = (const U8 *)s1;
973 register const U8 *b = (const U8 *)s2;
975 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
978 if (*a != *b && *a != PL_fold_locale[*b])
985 /* copy a string to a safe spot */
988 =head1 Memory Management
992 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
993 string which is a duplicate of C<pv>. The size of the string is
994 determined by C<strlen()>. The memory allocated for the new string can
995 be freed with the C<Safefree()> function.
1001 Perl_savepv(pTHX_ const char *pv)
1003 PERL_UNUSED_CONTEXT;
1008 const STRLEN pvlen = strlen(pv)+1;
1009 Newx(newaddr, pvlen, char);
1010 return (char*)memcpy(newaddr, pv, pvlen);
1014 /* same thing but with a known length */
1019 Perl's version of what C<strndup()> would be if it existed. Returns a
1020 pointer to a newly allocated string which is a duplicate of the first
1021 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
1022 the new string can be freed with the C<Safefree()> function.
1028 Perl_savepvn(pTHX_ const char *pv, register I32 len)
1030 register char *newaddr;
1031 PERL_UNUSED_CONTEXT;
1033 Newx(newaddr,len+1,char);
1034 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1036 /* might not be null terminated */
1037 newaddr[len] = '\0';
1038 return (char *) CopyD(pv,newaddr,len,char);
1041 return (char *) ZeroD(newaddr,len+1,char);
1046 =for apidoc savesharedpv
1048 A version of C<savepv()> which allocates the duplicate string in memory
1049 which is shared between threads.
1054 Perl_savesharedpv(pTHX_ const char *pv)
1056 register char *newaddr;
1061 pvlen = strlen(pv)+1;
1062 newaddr = (char*)PerlMemShared_malloc(pvlen);
1064 return write_no_mem();
1066 return (char*)memcpy(newaddr, pv, pvlen);
1070 =for apidoc savesharedpvn
1072 A version of C<savepvn()> which allocates the duplicate string in memory
1073 which is shared between threads. (With the specific difference that a NULL
1074 pointer is not acceptable)
1079 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1081 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1083 PERL_ARGS_ASSERT_SAVESHAREDPVN;
1086 return write_no_mem();
1088 newaddr[len] = '\0';
1089 return (char*)memcpy(newaddr, pv, len);
1093 =for apidoc savesvpv
1095 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1096 the passed in SV using C<SvPV()>
1102 Perl_savesvpv(pTHX_ SV *sv)
1105 const char * const pv = SvPV_const(sv, len);
1106 register char *newaddr;
1108 PERL_ARGS_ASSERT_SAVESVPV;
1111 Newx(newaddr,len,char);
1112 return (char *) CopyD(pv,newaddr,len,char);
1116 =for apidoc savesharedsvpv
1118 A version of C<savesharedpv()> which allocates the duplicate string in
1119 memory which is shared between threads.
1125 Perl_savesharedsvpv(pTHX_ SV *sv)
1128 const char * const pv = SvPV_const(sv, len);
1130 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1132 return savesharedpvn(pv, len);
1135 /* the SV for Perl_form() and mess() is not kept in an arena */
1144 if (PL_phase != PERL_PHASE_DESTRUCT)
1145 return newSVpvs_flags("", SVs_TEMP);
1150 /* Create as PVMG now, to avoid any upgrading later */
1152 Newxz(any, 1, XPVMG);
1153 SvFLAGS(sv) = SVt_PVMG;
1154 SvANY(sv) = (void*)any;
1156 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1161 #if defined(PERL_IMPLICIT_CONTEXT)
1163 Perl_form_nocontext(const char* pat, ...)
1168 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1169 va_start(args, pat);
1170 retval = vform(pat, &args);
1174 #endif /* PERL_IMPLICIT_CONTEXT */
1177 =head1 Miscellaneous Functions
1180 Takes a sprintf-style format pattern and conventional
1181 (non-SV) arguments and returns the formatted string.
1183 (char *) Perl_form(pTHX_ const char* pat, ...)
1185 can be used any place a string (char *) is required:
1187 char * s = Perl_form("%d.%d",major,minor);
1189 Uses a single private buffer so if you want to format several strings you
1190 must explicitly copy the earlier strings away (and free the copies when you
1197 Perl_form(pTHX_ const char* pat, ...)
1201 PERL_ARGS_ASSERT_FORM;
1202 va_start(args, pat);
1203 retval = vform(pat, &args);
1209 Perl_vform(pTHX_ const char *pat, va_list *args)
1211 SV * const sv = mess_alloc();
1212 PERL_ARGS_ASSERT_VFORM;
1213 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1218 =for apidoc Am|SV *|mess|const char *pat|...
1220 Take a sprintf-style format pattern and argument list. These are used to
1221 generate a string message. If the message does not end with a newline,
1222 then it will be extended with some indication of the current location
1223 in the code, as described for L</mess_sv>.
1225 Normally, the resulting message is returned in a new mortal SV.
1226 During global destruction a single SV may be shared between uses of
1232 #if defined(PERL_IMPLICIT_CONTEXT)
1234 Perl_mess_nocontext(const char *pat, ...)
1239 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1240 va_start(args, pat);
1241 retval = vmess(pat, &args);
1245 #endif /* PERL_IMPLICIT_CONTEXT */
1248 Perl_mess(pTHX_ const char *pat, ...)
1252 PERL_ARGS_ASSERT_MESS;
1253 va_start(args, pat);
1254 retval = vmess(pat, &args);
1260 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1263 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1265 PERL_ARGS_ASSERT_CLOSEST_COP;
1267 if (!o || o == PL_op)
1270 if (o->op_flags & OPf_KIDS) {
1272 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1275 /* If the OP_NEXTSTATE has been optimised away we can still use it
1276 * the get the file and line number. */
1278 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1279 cop = (const COP *)kid;
1281 /* Keep searching, and return when we've found something. */
1283 new_cop = closest_cop(cop, kid);
1289 /* Nothing found. */
1295 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1297 Expands a message, intended for the user, to include an indication of
1298 the current location in the code, if the message does not already appear
1301 C<basemsg> is the initial message or object. If it is a reference, it
1302 will be used as-is and will be the result of this function. Otherwise it
1303 is used as a string, and if it already ends with a newline, it is taken
1304 to be complete, and the result of this function will be the same string.
1305 If the message does not end with a newline, then a segment such as C<at
1306 foo.pl line 37> will be appended, and possibly other clauses indicating
1307 the current state of execution. The resulting message will end with a
1310 Normally, the resulting message is returned in a new mortal SV.
1311 During global destruction a single SV may be shared between uses of this
1312 function. If C<consume> is true, then the function is permitted (but not
1313 required) to modify and return C<basemsg> instead of allocating a new SV.
1319 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1324 PERL_ARGS_ASSERT_MESS_SV;
1326 if (SvROK(basemsg)) {
1332 sv_setsv(sv, basemsg);
1337 if (SvPOK(basemsg) && consume) {
1342 sv_copypv(sv, basemsg);
1345 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1347 * Try and find the file and line for PL_op. This will usually be
1348 * PL_curcop, but it might be a cop that has been optimised away. We
1349 * can try to find such a cop by searching through the optree starting
1350 * from the sibling of PL_curcop.
1353 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1358 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1359 OutCopFILE(cop), (IV)CopLINE(cop));
1360 /* Seems that GvIO() can be untrustworthy during global destruction. */
1361 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1362 && IoLINES(GvIOp(PL_last_in_gv)))
1364 const bool line_mode = (RsSIMPLE(PL_rs) &&
1365 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1366 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1367 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1368 line_mode ? "line" : "chunk",
1369 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1371 if (PL_phase == PERL_PHASE_DESTRUCT)
1372 sv_catpvs(sv, " during global destruction");
1373 sv_catpvs(sv, ".\n");
1379 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1381 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1382 argument list. These are used to generate a string message. If the
1383 message does not end with a newline, then it will be extended with
1384 some indication of the current location in the code, as described for
1387 Normally, the resulting message is returned in a new mortal SV.
1388 During global destruction a single SV may be shared between uses of
1395 Perl_vmess(pTHX_ const char *pat, va_list *args)
1398 SV * const sv = mess_alloc();
1400 PERL_ARGS_ASSERT_VMESS;
1402 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1403 return mess_sv(sv, 1);
1407 Perl_write_to_stderr(pTHX_ SV* msv)
1413 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1415 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1416 && (io = GvIO(PL_stderrgv))
1417 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1418 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1419 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1422 /* SFIO can really mess with your errno */
1425 PerlIO * const serr = Perl_error_log;
1427 do_print(msv, serr);
1428 (void)PerlIO_flush(serr);
1436 =head1 Warning and Dieing
1439 /* Common code used in dieing and warning */
1442 S_with_queued_errors(pTHX_ SV *ex)
1444 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1445 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1446 sv_catsv(PL_errors, ex);
1447 ex = sv_mortalcopy(PL_errors);
1448 SvCUR_set(PL_errors, 0);
1454 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1460 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1461 /* sv_2cv might call Perl_croak() or Perl_warner() */
1462 SV * const oldhook = *hook;
1470 cv = sv_2cv(oldhook, &stash, &gv, 0);
1472 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1482 exarg = newSVsv(ex);
1483 SvREADONLY_on(exarg);
1486 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1490 call_sv(MUTABLE_SV(cv), G_DISCARD);
1499 =for apidoc Am|OP *|die_sv|SV *baseex
1501 Behaves the same as L</croak_sv>, except for the return type.
1502 It should be used only where the C<OP *> return type is required.
1503 The function never actually returns.
1509 Perl_die_sv(pTHX_ SV *baseex)
1511 PERL_ARGS_ASSERT_DIE_SV;
1518 =for apidoc Am|OP *|die|const char *pat|...
1520 Behaves the same as L</croak>, except for the return type.
1521 It should be used only where the C<OP *> return type is required.
1522 The function never actually returns.
1527 #if defined(PERL_IMPLICIT_CONTEXT)
1529 Perl_die_nocontext(const char* pat, ...)
1533 va_start(args, pat);
1539 #endif /* PERL_IMPLICIT_CONTEXT */
1542 Perl_die(pTHX_ const char* pat, ...)
1545 va_start(args, pat);
1553 =for apidoc Am|void|croak_sv|SV *baseex
1555 This is an XS interface to Perl's C<die> function.
1557 C<baseex> is the error message or object. If it is a reference, it
1558 will be used as-is. Otherwise it is used as a string, and if it does
1559 not end with a newline then it will be extended with some indication of
1560 the current location in the code, as described for L</mess_sv>.
1562 The error message or object will be used as an exception, by default
1563 returning control to the nearest enclosing C<eval>, but subject to
1564 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1565 function never returns normally.
1567 To die with a simple string message, the L</croak> function may be
1574 Perl_croak_sv(pTHX_ SV *baseex)
1576 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1577 PERL_ARGS_ASSERT_CROAK_SV;
1578 invoke_exception_hook(ex, FALSE);
1583 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1585 This is an XS interface to Perl's C<die> function.
1587 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1588 argument list. These are used to generate a string message. If the
1589 message does not end with a newline, then it will be extended with
1590 some indication of the current location in the code, as described for
1593 The error message will be used as an exception, by default
1594 returning control to the nearest enclosing C<eval>, but subject to
1595 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1596 function never returns normally.
1598 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1599 (C<$@>) will be used as an error message or object instead of building an
1600 error message from arguments. If you want to throw a non-string object,
1601 or build an error message in an SV yourself, it is preferable to use
1602 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1608 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1610 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1611 invoke_exception_hook(ex, FALSE);
1616 =for apidoc Am|void|croak|const char *pat|...
1618 This is an XS interface to Perl's C<die> function.
1620 Take a sprintf-style format pattern and argument list. These are used to
1621 generate a string message. If the message does not end with a newline,
1622 then it will be extended with some indication of the current location
1623 in the code, as described for L</mess_sv>.
1625 The error message will be used as an exception, by default
1626 returning control to the nearest enclosing C<eval>, but subject to
1627 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1628 function never returns normally.
1630 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1631 (C<$@>) will be used as an error message or object instead of building an
1632 error message from arguments. If you want to throw a non-string object,
1633 or build an error message in an SV yourself, it is preferable to use
1634 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1639 #if defined(PERL_IMPLICIT_CONTEXT)
1641 Perl_croak_nocontext(const char *pat, ...)
1645 va_start(args, pat);
1650 #endif /* PERL_IMPLICIT_CONTEXT */
1653 Perl_croak(pTHX_ const char *pat, ...)
1656 va_start(args, pat);
1663 =for apidoc Am|void|croak_no_modify
1665 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1666 terser object code than using C<Perl_croak>. Less code used on exception code
1667 paths reduces CPU cache pressure.
1673 Perl_croak_no_modify(pTHX)
1675 Perl_croak(aTHX_ "%s", PL_no_modify);
1679 =for apidoc Am|void|warn_sv|SV *baseex
1681 This is an XS interface to Perl's C<warn> function.
1683 C<baseex> is the error message or object. If it is a reference, it
1684 will be used as-is. Otherwise it is used as a string, and if it does
1685 not end with a newline then it will be extended with some indication of
1686 the current location in the code, as described for L</mess_sv>.
1688 The error message or object will by default be written to standard error,
1689 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1691 To warn with a simple string message, the L</warn> function may be
1698 Perl_warn_sv(pTHX_ SV *baseex)
1700 SV *ex = mess_sv(baseex, 0);
1701 PERL_ARGS_ASSERT_WARN_SV;
1702 if (!invoke_exception_hook(ex, TRUE))
1703 write_to_stderr(ex);
1707 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1709 This is an XS interface to Perl's C<warn> function.
1711 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1712 argument list. These are used to generate a string message. If the
1713 message does not end with a newline, then it will be extended with
1714 some indication of the current location in the code, as described for
1717 The error message or object will by default be written to standard error,
1718 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1720 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1726 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1728 SV *ex = vmess(pat, args);
1729 PERL_ARGS_ASSERT_VWARN;
1730 if (!invoke_exception_hook(ex, TRUE))
1731 write_to_stderr(ex);
1735 =for apidoc Am|void|warn|const char *pat|...
1737 This is an XS interface to Perl's C<warn> function.
1739 Take a sprintf-style format pattern and argument list. These are used to
1740 generate a string message. If the message does not end with a newline,
1741 then it will be extended with some indication of the current location
1742 in the code, as described for L</mess_sv>.
1744 The error message or object will by default be written to standard error,
1745 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1747 Unlike with L</croak>, C<pat> is not permitted to be null.
1752 #if defined(PERL_IMPLICIT_CONTEXT)
1754 Perl_warn_nocontext(const char *pat, ...)
1758 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1759 va_start(args, pat);
1763 #endif /* PERL_IMPLICIT_CONTEXT */
1766 Perl_warn(pTHX_ const char *pat, ...)
1769 PERL_ARGS_ASSERT_WARN;
1770 va_start(args, pat);
1775 #if defined(PERL_IMPLICIT_CONTEXT)
1777 Perl_warner_nocontext(U32 err, const char *pat, ...)
1781 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1782 va_start(args, pat);
1783 vwarner(err, pat, &args);
1786 #endif /* PERL_IMPLICIT_CONTEXT */
1789 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1791 PERL_ARGS_ASSERT_CK_WARNER_D;
1793 if (Perl_ckwarn_d(aTHX_ err)) {
1795 va_start(args, pat);
1796 vwarner(err, pat, &args);
1802 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1804 PERL_ARGS_ASSERT_CK_WARNER;
1806 if (Perl_ckwarn(aTHX_ err)) {
1808 va_start(args, pat);
1809 vwarner(err, pat, &args);
1815 Perl_warner(pTHX_ U32 err, const char* pat,...)
1818 PERL_ARGS_ASSERT_WARNER;
1819 va_start(args, pat);
1820 vwarner(err, pat, &args);
1825 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1828 PERL_ARGS_ASSERT_VWARNER;
1829 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1830 SV * const msv = vmess(pat, args);
1832 invoke_exception_hook(msv, FALSE);
1836 Perl_vwarn(aTHX_ pat, args);
1840 /* implements the ckWARN? macros */
1843 Perl_ckwarn(pTHX_ U32 w)
1846 /* If lexical warnings have not been set, use $^W. */
1848 return PL_dowarn & G_WARN_ON;
1850 return ckwarn_common(w);
1853 /* implements the ckWARN?_d macro */
1856 Perl_ckwarn_d(pTHX_ U32 w)
1859 /* If lexical warnings have not been set then default classes warn. */
1863 return ckwarn_common(w);
1867 S_ckwarn_common(pTHX_ U32 w)
1869 if (PL_curcop->cop_warnings == pWARN_ALL)
1872 if (PL_curcop->cop_warnings == pWARN_NONE)
1875 /* Check the assumption that at least the first slot is non-zero. */
1876 assert(unpackWARN1(w));
1878 /* Check the assumption that it is valid to stop as soon as a zero slot is
1880 if (!unpackWARN2(w)) {
1881 assert(!unpackWARN3(w));
1882 assert(!unpackWARN4(w));
1883 } else if (!unpackWARN3(w)) {
1884 assert(!unpackWARN4(w));
1887 /* Right, dealt with all the special cases, which are implemented as non-
1888 pointers, so there is a pointer to a real warnings mask. */
1890 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1892 } while (w >>= WARNshift);
1897 /* Set buffer=NULL to get a new one. */
1899 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1901 const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
1902 PERL_UNUSED_CONTEXT;
1903 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1906 (specialWARN(buffer) ?
1907 PerlMemShared_malloc(len_wanted) :
1908 PerlMemShared_realloc(buffer, len_wanted));
1910 Copy(bits, (buffer + 1), size, char);
1914 /* since we've already done strlen() for both nam and val
1915 * we can use that info to make things faster than
1916 * sprintf(s, "%s=%s", nam, val)
1918 #define my_setenv_format(s, nam, nlen, val, vlen) \
1919 Copy(nam, s, nlen, char); \
1921 Copy(val, s+(nlen+1), vlen, char); \
1922 *(s+(nlen+1+vlen)) = '\0'
1924 #ifdef USE_ENVIRON_ARRAY
1925 /* VMS' my_setenv() is in vms.c */
1926 #if !defined(WIN32) && !defined(NETWARE)
1928 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1932 /* only parent thread can modify process environment */
1933 if (PL_curinterp == aTHX)
1936 #ifndef PERL_USE_SAFE_PUTENV
1937 if (!PL_use_safe_putenv) {
1938 /* most putenv()s leak, so we manipulate environ directly */
1940 register const I32 len = strlen(nam);
1943 /* where does it go? */
1944 for (i = 0; environ[i]; i++) {
1945 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1949 if (environ == PL_origenviron) { /* need we copy environment? */
1955 while (environ[max])
1957 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1958 for (j=0; j<max; j++) { /* copy environment */
1959 const int len = strlen(environ[j]);
1960 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1961 Copy(environ[j], tmpenv[j], len+1, char);
1964 environ = tmpenv; /* tell exec where it is now */
1967 safesysfree(environ[i]);
1968 while (environ[i]) {
1969 environ[i] = environ[i+1];
1974 if (!environ[i]) { /* does not exist yet */
1975 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1976 environ[i+1] = NULL; /* make sure it's null terminated */
1979 safesysfree(environ[i]);
1983 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1984 /* all that work just for this */
1985 my_setenv_format(environ[i], nam, nlen, val, vlen);
1988 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
1989 # if defined(HAS_UNSETENV)
1991 (void)unsetenv(nam);
1993 (void)setenv(nam, val, 1);
1995 # else /* ! HAS_UNSETENV */
1996 (void)setenv(nam, val, 1);
1997 # endif /* HAS_UNSETENV */
1999 # if defined(HAS_UNSETENV)
2001 (void)unsetenv(nam);
2003 const int nlen = strlen(nam);
2004 const int vlen = strlen(val);
2005 char * const new_env =
2006 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2007 my_setenv_format(new_env, nam, nlen, val, vlen);
2008 (void)putenv(new_env);
2010 # else /* ! HAS_UNSETENV */
2012 const int nlen = strlen(nam);
2018 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2019 /* all that work just for this */
2020 my_setenv_format(new_env, nam, nlen, val, vlen);
2021 (void)putenv(new_env);
2022 # endif /* HAS_UNSETENV */
2023 # endif /* __CYGWIN__ */
2024 #ifndef PERL_USE_SAFE_PUTENV
2030 #else /* WIN32 || NETWARE */
2033 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2036 register char *envstr;
2037 const int nlen = strlen(nam);
2044 Newx(envstr, nlen+vlen+2, char);
2045 my_setenv_format(envstr, nam, nlen, val, vlen);
2046 (void)PerlEnv_putenv(envstr);
2050 #endif /* WIN32 || NETWARE */
2052 #endif /* !VMS && !EPOC*/
2054 #ifdef UNLINK_ALL_VERSIONS
2056 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2060 PERL_ARGS_ASSERT_UNLNK;
2062 while (PerlLIO_unlink(f) >= 0)
2064 return retries ? 0 : -1;
2068 /* this is a drop-in replacement for bcopy() */
2069 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2071 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2073 char * const retval = to;
2075 PERL_ARGS_ASSERT_MY_BCOPY;
2077 if (from - to >= 0) {
2085 *(--to) = *(--from);
2091 /* this is a drop-in replacement for memset() */
2094 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2096 char * const retval = loc;
2098 PERL_ARGS_ASSERT_MY_MEMSET;
2106 /* this is a drop-in replacement for bzero() */
2107 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2109 Perl_my_bzero(register char *loc, register I32 len)
2111 char * const retval = loc;
2113 PERL_ARGS_ASSERT_MY_BZERO;
2121 /* this is a drop-in replacement for memcmp() */
2122 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2124 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2126 register const U8 *a = (const U8 *)s1;
2127 register const U8 *b = (const U8 *)s2;
2130 PERL_ARGS_ASSERT_MY_MEMCMP;
2133 if ((tmp = *a++ - *b++))
2138 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2141 /* This vsprintf replacement should generally never get used, since
2142 vsprintf was available in both System V and BSD 2.11. (There may
2143 be some cross-compilation or embedded set-ups where it is needed,
2146 If you encounter a problem in this function, it's probably a symptom
2147 that Configure failed to detect your system's vprintf() function.
2148 See the section on "item vsprintf" in the INSTALL file.
2150 This version may compile on systems with BSD-ish <stdio.h>,
2151 but probably won't on others.
2154 #ifdef USE_CHAR_VSPRINTF
2159 vsprintf(char *dest, const char *pat, void *args)
2163 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2164 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2165 FILE_cnt(&fakebuf) = 32767;
2167 /* These probably won't compile -- If you really need
2168 this, you'll have to figure out some other method. */
2169 fakebuf._ptr = dest;
2170 fakebuf._cnt = 32767;
2175 fakebuf._flag = _IOWRT|_IOSTRG;
2176 _doprnt(pat, args, &fakebuf); /* what a kludge */
2177 #if defined(STDIO_PTR_LVALUE)
2178 *(FILE_ptr(&fakebuf)++) = '\0';
2180 /* PerlIO has probably #defined away fputc, but we want it here. */
2182 # undef fputc /* XXX Should really restore it later */
2184 (void)fputc('\0', &fakebuf);
2186 #ifdef USE_CHAR_VSPRINTF
2189 return 0; /* perl doesn't use return value */
2193 #endif /* HAS_VPRINTF */
2196 #if BYTEORDER != 0x4321
2198 Perl_my_swap(pTHX_ short s)
2200 #if (BYTEORDER & 1) == 0
2203 result = ((s & 255) << 8) + ((s >> 8) & 255);
2211 Perl_my_htonl(pTHX_ long l)
2215 char c[sizeof(long)];
2218 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2219 #if BYTEORDER == 0x12345678
2222 u.c[0] = (l >> 24) & 255;
2223 u.c[1] = (l >> 16) & 255;
2224 u.c[2] = (l >> 8) & 255;
2228 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2229 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2234 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2235 u.c[o & 0xf] = (l >> s) & 255;
2243 Perl_my_ntohl(pTHX_ long l)
2247 char c[sizeof(long)];
2250 #if BYTEORDER == 0x1234
2251 u.c[0] = (l >> 24) & 255;
2252 u.c[1] = (l >> 16) & 255;
2253 u.c[2] = (l >> 8) & 255;
2257 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2258 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2265 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2266 l |= (u.c[o & 0xf] & 255) << s;
2273 #endif /* BYTEORDER != 0x4321 */
2277 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2278 * If these functions are defined,
2279 * the BYTEORDER is neither 0x1234 nor 0x4321.
2280 * However, this is not assumed.
2284 #define HTOLE(name,type) \
2286 name (register type n) \
2290 char c[sizeof(type)]; \
2293 register U32 s = 0; \
2294 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2295 u.c[i] = (n >> s) & 0xFF; \
2300 #define LETOH(name,type) \
2302 name (register type n) \
2306 char c[sizeof(type)]; \
2309 register U32 s = 0; \
2312 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2313 n |= ((type)(u.c[i] & 0xFF)) << s; \
2319 * Big-endian byte order functions.
2322 #define HTOBE(name,type) \
2324 name (register type n) \
2328 char c[sizeof(type)]; \
2331 register U32 s = 8*(sizeof(u.c)-1); \
2332 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2333 u.c[i] = (n >> s) & 0xFF; \
2338 #define BETOH(name,type) \
2340 name (register type n) \
2344 char c[sizeof(type)]; \
2347 register U32 s = 8*(sizeof(u.c)-1); \
2350 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2351 n |= ((type)(u.c[i] & 0xFF)) << s; \
2357 * If we just can't do it...
2360 #define NOT_AVAIL(name,type) \
2362 name (register type n) \
2364 Perl_croak_nocontext(#name "() not available"); \
2365 return n; /* not reached */ \
2369 #if defined(HAS_HTOVS) && !defined(htovs)
2372 #if defined(HAS_HTOVL) && !defined(htovl)
2375 #if defined(HAS_VTOHS) && !defined(vtohs)
2378 #if defined(HAS_VTOHL) && !defined(vtohl)
2382 #ifdef PERL_NEED_MY_HTOLE16
2384 HTOLE(Perl_my_htole16,U16)
2386 NOT_AVAIL(Perl_my_htole16,U16)
2389 #ifdef PERL_NEED_MY_LETOH16
2391 LETOH(Perl_my_letoh16,U16)
2393 NOT_AVAIL(Perl_my_letoh16,U16)
2396 #ifdef PERL_NEED_MY_HTOBE16
2398 HTOBE(Perl_my_htobe16,U16)
2400 NOT_AVAIL(Perl_my_htobe16,U16)
2403 #ifdef PERL_NEED_MY_BETOH16
2405 BETOH(Perl_my_betoh16,U16)
2407 NOT_AVAIL(Perl_my_betoh16,U16)
2411 #ifdef PERL_NEED_MY_HTOLE32
2413 HTOLE(Perl_my_htole32,U32)
2415 NOT_AVAIL(Perl_my_htole32,U32)
2418 #ifdef PERL_NEED_MY_LETOH32
2420 LETOH(Perl_my_letoh32,U32)
2422 NOT_AVAIL(Perl_my_letoh32,U32)
2425 #ifdef PERL_NEED_MY_HTOBE32
2427 HTOBE(Perl_my_htobe32,U32)
2429 NOT_AVAIL(Perl_my_htobe32,U32)
2432 #ifdef PERL_NEED_MY_BETOH32
2434 BETOH(Perl_my_betoh32,U32)
2436 NOT_AVAIL(Perl_my_betoh32,U32)
2440 #ifdef PERL_NEED_MY_HTOLE64
2442 HTOLE(Perl_my_htole64,U64)
2444 NOT_AVAIL(Perl_my_htole64,U64)
2447 #ifdef PERL_NEED_MY_LETOH64
2449 LETOH(Perl_my_letoh64,U64)
2451 NOT_AVAIL(Perl_my_letoh64,U64)
2454 #ifdef PERL_NEED_MY_HTOBE64
2456 HTOBE(Perl_my_htobe64,U64)
2458 NOT_AVAIL(Perl_my_htobe64,U64)
2461 #ifdef PERL_NEED_MY_BETOH64
2463 BETOH(Perl_my_betoh64,U64)
2465 NOT_AVAIL(Perl_my_betoh64,U64)
2469 #ifdef PERL_NEED_MY_HTOLES
2470 HTOLE(Perl_my_htoles,short)
2472 #ifdef PERL_NEED_MY_LETOHS
2473 LETOH(Perl_my_letohs,short)
2475 #ifdef PERL_NEED_MY_HTOBES
2476 HTOBE(Perl_my_htobes,short)
2478 #ifdef PERL_NEED_MY_BETOHS
2479 BETOH(Perl_my_betohs,short)
2482 #ifdef PERL_NEED_MY_HTOLEI
2483 HTOLE(Perl_my_htolei,int)
2485 #ifdef PERL_NEED_MY_LETOHI
2486 LETOH(Perl_my_letohi,int)
2488 #ifdef PERL_NEED_MY_HTOBEI
2489 HTOBE(Perl_my_htobei,int)
2491 #ifdef PERL_NEED_MY_BETOHI
2492 BETOH(Perl_my_betohi,int)
2495 #ifdef PERL_NEED_MY_HTOLEL
2496 HTOLE(Perl_my_htolel,long)
2498 #ifdef PERL_NEED_MY_LETOHL
2499 LETOH(Perl_my_letohl,long)
2501 #ifdef PERL_NEED_MY_HTOBEL
2502 HTOBE(Perl_my_htobel,long)
2504 #ifdef PERL_NEED_MY_BETOHL
2505 BETOH(Perl_my_betohl,long)
2509 Perl_my_swabn(void *ptr, int n)
2511 register char *s = (char *)ptr;
2512 register char *e = s + (n-1);
2515 PERL_ARGS_ASSERT_MY_SWABN;
2517 for (n /= 2; n > 0; s++, e--, n--) {
2525 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2527 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2530 register I32 This, that;
2536 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2538 PERL_FLUSHALL_FOR_CHILD;
2539 This = (*mode == 'w');
2543 taint_proper("Insecure %s%s", "EXEC");
2545 if (PerlProc_pipe(p) < 0)
2547 /* Try for another pipe pair for error return */
2548 if (PerlProc_pipe(pp) >= 0)
2550 while ((pid = PerlProc_fork()) < 0) {
2551 if (errno != EAGAIN) {
2552 PerlLIO_close(p[This]);
2553 PerlLIO_close(p[that]);
2555 PerlLIO_close(pp[0]);
2556 PerlLIO_close(pp[1]);
2560 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2569 /* Close parent's end of error status pipe (if any) */
2571 PerlLIO_close(pp[0]);
2572 #if defined(HAS_FCNTL) && defined(F_SETFD)
2573 /* Close error pipe automatically if exec works */
2574 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2577 /* Now dup our end of _the_ pipe to right position */
2578 if (p[THIS] != (*mode == 'r')) {
2579 PerlLIO_dup2(p[THIS], *mode == 'r');
2580 PerlLIO_close(p[THIS]);
2581 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2582 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2585 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2586 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2587 /* No automatic close - do it by hand */
2594 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2600 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2606 do_execfree(); /* free any memory malloced by child on fork */
2608 PerlLIO_close(pp[1]);
2609 /* Keep the lower of the two fd numbers */
2610 if (p[that] < p[This]) {
2611 PerlLIO_dup2(p[This], p[that]);
2612 PerlLIO_close(p[This]);
2616 PerlLIO_close(p[that]); /* close child's end of pipe */
2618 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2619 SvUPGRADE(sv,SVt_IV);
2621 PL_forkprocess = pid;
2622 /* If we managed to get status pipe check for exec fail */
2623 if (did_pipes && pid > 0) {
2628 while (n < sizeof(int)) {
2629 n1 = PerlLIO_read(pp[0],
2630 (void*)(((char*)&errkid)+n),
2636 PerlLIO_close(pp[0]);
2638 if (n) { /* Error */
2640 PerlLIO_close(p[This]);
2641 if (n != sizeof(int))
2642 Perl_croak(aTHX_ "panic: kid popen errno read");
2644 pid2 = wait4pid(pid, &status, 0);
2645 } while (pid2 == -1 && errno == EINTR);
2646 errno = errkid; /* Propagate errno from kid */
2651 PerlLIO_close(pp[0]);
2652 return PerlIO_fdopen(p[This], mode);
2654 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2655 return my_syspopen4(aTHX_ NULL, mode, n, args);
2657 Perl_croak(aTHX_ "List form of piped open not implemented");
2658 return (PerlIO *) NULL;
2663 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2664 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
2666 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2670 register I32 This, that;
2673 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2677 PERL_ARGS_ASSERT_MY_POPEN;
2679 PERL_FLUSHALL_FOR_CHILD;
2682 return my_syspopen(aTHX_ cmd,mode);
2685 This = (*mode == 'w');
2687 if (doexec && PL_tainting) {
2689 taint_proper("Insecure %s%s", "EXEC");
2691 if (PerlProc_pipe(p) < 0)
2693 if (doexec && PerlProc_pipe(pp) >= 0)
2695 while ((pid = PerlProc_fork()) < 0) {
2696 if (errno != EAGAIN) {
2697 PerlLIO_close(p[This]);
2698 PerlLIO_close(p[that]);
2700 PerlLIO_close(pp[0]);
2701 PerlLIO_close(pp[1]);
2704 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2707 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2718 PerlLIO_close(pp[0]);
2719 #if defined(HAS_FCNTL) && defined(F_SETFD)
2720 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2723 if (p[THIS] != (*mode == 'r')) {
2724 PerlLIO_dup2(p[THIS], *mode == 'r');
2725 PerlLIO_close(p[THIS]);
2726 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2727 PerlLIO_close(p[THAT]);
2730 PerlLIO_close(p[THAT]);
2733 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2740 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2745 /* may or may not use the shell */
2746 do_exec3(cmd, pp[1], did_pipes);
2749 #endif /* defined OS2 */
2751 #ifdef PERLIO_USING_CRLF
2752 /* Since we circumvent IO layers when we manipulate low-level
2753 filedescriptors directly, need to manually switch to the
2754 default, binary, low-level mode; see PerlIOBuf_open(). */
2755 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2758 if ((tmpgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV))) {
2759 SvREADONLY_off(GvSV(tmpgv));
2760 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2761 SvREADONLY_on(GvSV(tmpgv));
2763 #ifdef THREADS_HAVE_PIDS
2764 PL_ppid = (IV)getppid();
2767 #ifdef PERL_USES_PL_PIDSTATUS
2768 hv_clear(PL_pidstatus); /* we have no children */
2774 do_execfree(); /* free any memory malloced by child on vfork */
2776 PerlLIO_close(pp[1]);
2777 if (p[that] < p[This]) {
2778 PerlLIO_dup2(p[This], p[that]);
2779 PerlLIO_close(p[This]);
2783 PerlLIO_close(p[that]);
2785 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2786 SvUPGRADE(sv,SVt_IV);
2788 PL_forkprocess = pid;
2789 if (did_pipes && pid > 0) {
2794 while (n < sizeof(int)) {
2795 n1 = PerlLIO_read(pp[0],
2796 (void*)(((char*)&errkid)+n),
2802 PerlLIO_close(pp[0]);
2804 if (n) { /* Error */
2806 PerlLIO_close(p[This]);
2807 if (n != sizeof(int))
2808 Perl_croak(aTHX_ "panic: kid popen errno read");
2810 pid2 = wait4pid(pid, &status, 0);
2811 } while (pid2 == -1 && errno == EINTR);
2812 errno = errkid; /* Propagate errno from kid */
2817 PerlLIO_close(pp[0]);
2818 return PerlIO_fdopen(p[This], mode);
2821 #if defined(atarist) || defined(EPOC)
2824 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2826 PERL_ARGS_ASSERT_MY_POPEN;
2827 PERL_FLUSHALL_FOR_CHILD;
2828 /* Call system's popen() to get a FILE *, then import it.
2829 used 0 for 2nd parameter to PerlIO_importFILE;
2832 return PerlIO_importFILE(popen(cmd, mode), 0);
2836 FILE *djgpp_popen();
2838 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2840 PERL_FLUSHALL_FOR_CHILD;
2841 /* Call system's popen() to get a FILE *, then import it.
2842 used 0 for 2nd parameter to PerlIO_importFILE;
2845 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2848 #if defined(__LIBCATAMOUNT__)
2850 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2858 #endif /* !DOSISH */
2860 /* this is called in parent before the fork() */
2862 Perl_atfork_lock(void)
2865 #if defined(USE_ITHREADS)
2866 /* locks must be held in locking order (if any) */
2868 MUTEX_LOCK(&PL_malloc_mutex);
2874 /* this is called in both parent and child after the fork() */
2876 Perl_atfork_unlock(void)
2879 #if defined(USE_ITHREADS)
2880 /* locks must be released in same order as in atfork_lock() */
2882 MUTEX_UNLOCK(&PL_malloc_mutex);
2891 #if defined(HAS_FORK)
2893 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2898 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2899 * handlers elsewhere in the code */
2904 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2905 Perl_croak_nocontext("fork() not available");
2907 #endif /* HAS_FORK */
2912 Perl_dump_fds(pTHX_ const char *const s)
2917 PERL_ARGS_ASSERT_DUMP_FDS;
2919 PerlIO_printf(Perl_debug_log,"%s", s);
2920 for (fd = 0; fd < 32; fd++) {
2921 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2922 PerlIO_printf(Perl_debug_log," %d",fd);
2924 PerlIO_printf(Perl_debug_log,"\n");
2927 #endif /* DUMP_FDS */
2931 dup2(int oldfd, int newfd)
2933 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2936 PerlLIO_close(newfd);
2937 return fcntl(oldfd, F_DUPFD, newfd);
2939 #define DUP2_MAX_FDS 256
2940 int fdtmp[DUP2_MAX_FDS];
2946 PerlLIO_close(newfd);
2947 /* good enough for low fd's... */
2948 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2949 if (fdx >= DUP2_MAX_FDS) {
2957 PerlLIO_close(fdtmp[--fdx]);
2964 #ifdef HAS_SIGACTION
2967 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2970 struct sigaction act, oact;
2973 /* only "parent" interpreter can diddle signals */
2974 if (PL_curinterp != aTHX)
2975 return (Sighandler_t) SIG_ERR;
2978 act.sa_handler = (void(*)(int))handler;
2979 sigemptyset(&act.sa_mask);
2982 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2983 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2985 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2986 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2987 act.sa_flags |= SA_NOCLDWAIT;
2989 if (sigaction(signo, &act, &oact) == -1)
2990 return (Sighandler_t) SIG_ERR;
2992 return (Sighandler_t) oact.sa_handler;
2996 Perl_rsignal_state(pTHX_ int signo)
2998 struct sigaction oact;
2999 PERL_UNUSED_CONTEXT;
3001 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
3002 return (Sighandler_t) SIG_ERR;
3004 return (Sighandler_t) oact.sa_handler;
3008 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3011 struct sigaction act;
3013 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
3016 /* only "parent" interpreter can diddle signals */
3017 if (PL_curinterp != aTHX)
3021 act.sa_handler = (void(*)(int))handler;
3022 sigemptyset(&act.sa_mask);
3025 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3026 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
3028 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3029 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3030 act.sa_flags |= SA_NOCLDWAIT;
3032 return sigaction(signo, &act, save);
3036 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3040 /* only "parent" interpreter can diddle signals */
3041 if (PL_curinterp != aTHX)
3045 return sigaction(signo, save, (struct sigaction *)NULL);
3048 #else /* !HAS_SIGACTION */
3051 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3053 #if defined(USE_ITHREADS) && !defined(WIN32)
3054 /* only "parent" interpreter can diddle signals */
3055 if (PL_curinterp != aTHX)
3056 return (Sighandler_t) SIG_ERR;
3059 return PerlProc_signal(signo, handler);
3070 Perl_rsignal_state(pTHX_ int signo)
3073 Sighandler_t oldsig;
3075 #if defined(USE_ITHREADS) && !defined(WIN32)
3076 /* only "parent" interpreter can diddle signals */
3077 if (PL_curinterp != aTHX)
3078 return (Sighandler_t) SIG_ERR;
3082 oldsig = PerlProc_signal(signo, sig_trap);
3083 PerlProc_signal(signo, oldsig);
3085 PerlProc_kill(PerlProc_getpid(), signo);
3090 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3092 #if defined(USE_ITHREADS) && !defined(WIN32)
3093 /* only "parent" interpreter can diddle signals */
3094 if (PL_curinterp != aTHX)
3097 *save = PerlProc_signal(signo, handler);
3098 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3102 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3104 #if defined(USE_ITHREADS) && !defined(WIN32)
3105 /* only "parent" interpreter can diddle signals */
3106 if (PL_curinterp != aTHX)
3109 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3112 #endif /* !HAS_SIGACTION */
3113 #endif /* !PERL_MICRO */
3115 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3116 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
3118 Perl_my_pclose(pTHX_ PerlIO *ptr)
3121 Sigsave_t hstat, istat, qstat;
3128 const int fd = PerlIO_fileno(ptr);
3130 /* Find out whether the refcount is low enough for us to wait for the
3131 child proc without blocking. */
3132 const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
3134 svp = av_fetch(PL_fdpid,fd,TRUE);
3135 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3137 *svp = &PL_sv_undef;
3139 if (pid == -1) { /* Opened by popen. */
3140 return my_syspclose(ptr);
3143 close_failed = (PerlIO_close(ptr) == EOF);
3146 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
3149 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3150 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3151 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3153 if (should_wait) do {
3154 pid2 = wait4pid(pid, &status, 0);
3155 } while (pid2 == -1 && errno == EINTR);
3157 rsignal_restore(SIGHUP, &hstat);
3158 rsignal_restore(SIGINT, &istat);
3159 rsignal_restore(SIGQUIT, &qstat);
3167 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3172 #if defined(__LIBCATAMOUNT__)
3174 Perl_my_pclose(pTHX_ PerlIO *ptr)
3179 #endif /* !DOSISH */
3181 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3183 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3187 PERL_ARGS_ASSERT_WAIT4PID;
3190 #ifdef PERL_USES_PL_PIDSTATUS
3193 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3194 pid, rather than a string form. */
3195 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3196 if (svp && *svp != &PL_sv_undef) {
3197 *statusp = SvIVX(*svp);
3198 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3206 hv_iterinit(PL_pidstatus);
3207 if ((entry = hv_iternext(PL_pidstatus))) {
3208 SV * const sv = hv_iterval(PL_pidstatus,entry);
3210 const char * const spid = hv_iterkey(entry,&len);
3212 assert (len == sizeof(Pid_t));
3213 memcpy((char *)&pid, spid, len);
3214 *statusp = SvIVX(sv);
3215 /* The hash iterator is currently on this entry, so simply
3216 calling hv_delete would trigger the lazy delete, which on
3217 aggregate does more work, beacuse next call to hv_iterinit()
3218 would spot the flag, and have to call the delete routine,
3219 while in the meantime any new entries can't re-use that
3221 hv_iterinit(PL_pidstatus);
3222 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3229 # ifdef HAS_WAITPID_RUNTIME
3230 if (!HAS_WAITPID_RUNTIME)
3233 result = PerlProc_waitpid(pid,statusp,flags);
3236 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3237 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3240 #ifdef PERL_USES_PL_PIDSTATUS
3241 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3246 Perl_croak(aTHX_ "Can't do waitpid with flags");
3248 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3249 pidgone(result,*statusp);
3255 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3258 if (result < 0 && errno == EINTR) {
3260 errno = EINTR; /* reset in case a signal handler changed $! */
3264 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3266 #ifdef PERL_USES_PL_PIDSTATUS
3268 S_pidgone(pTHX_ Pid_t pid, int status)
3272 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3273 SvUPGRADE(sv,SVt_IV);
3274 SvIV_set(sv, status);
3279 #if defined(atarist) || defined(OS2) || defined(EPOC)
3282 int /* Cannot prototype with I32
3284 my_syspclose(PerlIO *ptr)
3287 Perl_my_pclose(pTHX_ PerlIO *ptr)
3290 /* Needs work for PerlIO ! */
3291 FILE * const f = PerlIO_findFILE(ptr);
3292 const I32 result = pclose(f);
3293 PerlIO_releaseFILE(ptr,f);
3301 Perl_my_pclose(pTHX_ PerlIO *ptr)
3303 /* Needs work for PerlIO ! */
3304 FILE * const f = PerlIO_findFILE(ptr);
3305 I32 result = djgpp_pclose(f);
3306 result = (result << 8) & 0xff00;
3307 PerlIO_releaseFILE(ptr,f);
3312 #define PERL_REPEATCPY_LINEAR 4
3314 Perl_repeatcpy(register char *to, register const char *from, I32 len, register I32 count)
3316 PERL_ARGS_ASSERT_REPEATCPY;
3319 memset(to, *from, count);
3321 register char *p = to;
3322 I32 items, linear, half;
3324 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3325 for (items = 0; items < linear; ++items) {
3326 register const char *q = from;
3328 for (todo = len; todo > 0; todo--)
3333 while (items <= half) {
3334 I32 size = items * len;
3335 memcpy(p, to, size);
3341 memcpy(p, to, (count - items) * len);
3347 Perl_same_dirent(pTHX_ const char *a, const char *b)
3349 char *fa = strrchr(a,'/');
3350 char *fb = strrchr(b,'/');
3353 SV * const tmpsv = sv_newmortal();
3355 PERL_ARGS_ASSERT_SAME_DIRENT;
3368 sv_setpvs(tmpsv, ".");
3370 sv_setpvn(tmpsv, a, fa - a);
3371 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3374 sv_setpvs(tmpsv, ".");
3376 sv_setpvn(tmpsv, b, fb - b);
3377 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3379 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3380 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3382 #endif /* !HAS_RENAME */
3385 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3386 const char *const *const search_ext, I32 flags)
3389 const char *xfound = NULL;
3390 char *xfailed = NULL;
3391 char tmpbuf[MAXPATHLEN];
3396 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3397 # define SEARCH_EXTS ".bat", ".cmd", NULL
3398 # define MAX_EXT_LEN 4
3401 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3402 # define MAX_EXT_LEN 4
3405 # define SEARCH_EXTS ".pl", ".com", NULL
3406 # define MAX_EXT_LEN 4
3408 /* additional extensions to try in each dir if scriptname not found */
3410 static const char *const exts[] = { SEARCH_EXTS };
3411 const char *const *const ext = search_ext ? search_ext : exts;
3412 int extidx = 0, i = 0;
3413 const char *curext = NULL;
3415 PERL_UNUSED_ARG(search_ext);
3416 # define MAX_EXT_LEN 0
3419 PERL_ARGS_ASSERT_FIND_SCRIPT;
3422 * If dosearch is true and if scriptname does not contain path
3423 * delimiters, search the PATH for scriptname.
3425 * If SEARCH_EXTS is also defined, will look for each
3426 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3427 * while searching the PATH.
3429 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3430 * proceeds as follows:
3431 * If DOSISH or VMSISH:
3432 * + look for ./scriptname{,.foo,.bar}
3433 * + search the PATH for scriptname{,.foo,.bar}
3436 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3437 * this will not look in '.' if it's not in the PATH)
3442 # ifdef ALWAYS_DEFTYPES
3443 len = strlen(scriptname);
3444 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3445 int idx = 0, deftypes = 1;
3448 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3451 int idx = 0, deftypes = 1;
3454 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3456 /* The first time through, just add SEARCH_EXTS to whatever we
3457 * already have, so we can check for default file types. */
3459 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3465 if ((strlen(tmpbuf) + strlen(scriptname)
3466 + MAX_EXT_LEN) >= sizeof tmpbuf)
3467 continue; /* don't search dir with too-long name */
3468 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3472 if (strEQ(scriptname, "-"))
3474 if (dosearch) { /* Look in '.' first. */
3475 const char *cur = scriptname;
3477 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3479 if (strEQ(ext[i++],curext)) {
3480 extidx = -1; /* already has an ext */
3485 DEBUG_p(PerlIO_printf(Perl_debug_log,
3486 "Looking for %s\n",cur));
3487 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3488 && !S_ISDIR(PL_statbuf.st_mode)) {
3496 if (cur == scriptname) {
3497 len = strlen(scriptname);
3498 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3500 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3503 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3504 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3509 if (dosearch && !strchr(scriptname, '/')
3511 && !strchr(scriptname, '\\')
3513 && (s = PerlEnv_getenv("PATH")))
3517 bufend = s + strlen(s);
3518 while (s < bufend) {
3519 #if defined(atarist) || defined(DOSISH)
3524 && *s != ';'; len++, s++) {
3525 if (len < sizeof tmpbuf)
3528 if (len < sizeof tmpbuf)
3530 #else /* ! (atarist || DOSISH) */
3531 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3534 #endif /* ! (atarist || DOSISH) */
3537 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3538 continue; /* don't search dir with too-long name */
3540 # if defined(atarist) || defined(DOSISH)
3541 && tmpbuf[len - 1] != '/'
3542 && tmpbuf[len - 1] != '\\'
3545 tmpbuf[len++] = '/';
3546 if (len == 2 && tmpbuf[0] == '.')
3548 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3552 len = strlen(tmpbuf);
3553 if (extidx > 0) /* reset after previous loop */
3557 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3558 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3559 if (S_ISDIR(PL_statbuf.st_mode)) {
3563 } while ( retval < 0 /* not there */
3564 && extidx>=0 && ext[extidx] /* try an extension? */
3565 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3570 if (S_ISREG(PL_statbuf.st_mode)
3571 && cando(S_IRUSR,TRUE,&PL_statbuf)
3572 #if !defined(DOSISH)
3573 && cando(S_IXUSR,TRUE,&PL_statbuf)
3577 xfound = tmpbuf; /* bingo! */
3581 xfailed = savepv(tmpbuf);
3584 if (!xfound && !seen_dot && !xfailed &&
3585 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3586 || S_ISDIR(PL_statbuf.st_mode)))
3588 seen_dot = 1; /* Disable message. */
3590 if (flags & 1) { /* do or die? */
3591 Perl_croak(aTHX_ "Can't %s %s%s%s",
3592 (xfailed ? "execute" : "find"),
3593 (xfailed ? xfailed : scriptname),
3594 (xfailed ? "" : " on PATH"),
3595 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3600 scriptname = xfound;
3602 return (scriptname ? savepv(scriptname) : NULL);
3605 #ifndef PERL_GET_CONTEXT_DEFINED
3608 Perl_get_context(void)
3611 #if defined(USE_ITHREADS)
3612 # ifdef OLD_PTHREADS_API
3614 if (pthread_getspecific(PL_thr_key, &t))
3615 Perl_croak_nocontext("panic: pthread_getspecific");
3618 # ifdef I_MACH_CTHREADS
3619 return (void*)cthread_data(cthread_self());
3621 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3630 Perl_set_context(void *t)
3633 PERL_ARGS_ASSERT_SET_CONTEXT;
3634 #if defined(USE_ITHREADS)
3635 # ifdef I_MACH_CTHREADS
3636 cthread_set_data(cthread_self(), t);
3638 if (pthread_setspecific(PL_thr_key, t))
3639 Perl_croak_nocontext("panic: pthread_setspecific");
3646 #endif /* !PERL_GET_CONTEXT_DEFINED */
3648 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3657 Perl_get_op_names(pTHX)
3659 PERL_UNUSED_CONTEXT;
3660 return (char **)PL_op_name;
3664 Perl_get_op_descs(pTHX)
3666 PERL_UNUSED_CONTEXT;
3667 return (char **)PL_op_desc;
3671 Perl_get_no_modify(pTHX)
3673 PERL_UNUSED_CONTEXT;
3674 return PL_no_modify;
3678 Perl_get_opargs(pTHX)
3680 PERL_UNUSED_CONTEXT;
3681 return (U32 *)PL_opargs;
3685 Perl_get_ppaddr(pTHX)
3688 PERL_UNUSED_CONTEXT;
3689 return (PPADDR_t*)PL_ppaddr;
3692 #ifndef HAS_GETENV_LEN
3694 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3696 char * const env_trans = PerlEnv_getenv(env_elem);
3697 PERL_UNUSED_CONTEXT;
3698 PERL_ARGS_ASSERT_GETENV_LEN;
3700 *len = strlen(env_trans);
3707 Perl_get_vtbl(pTHX_ int vtbl_id)
3709 const MGVTBL* result;
3710 PERL_UNUSED_CONTEXT;
3714 result = &PL_vtbl_sv;
3717 result = &PL_vtbl_env;
3719 case want_vtbl_envelem:
3720 result = &PL_vtbl_envelem;
3723 result = &PL_vtbl_sig;
3725 case want_vtbl_sigelem:
3726 result = &PL_vtbl_sigelem;
3728 case want_vtbl_pack:
3729 result = &PL_vtbl_pack;
3731 case want_vtbl_packelem:
3732 result = &PL_vtbl_packelem;
3734 case want_vtbl_dbline:
3735 result = &PL_vtbl_dbline;
3738 result = &PL_vtbl_isa;
3740 case want_vtbl_isaelem:
3741 result = &PL_vtbl_isaelem;
3743 case want_vtbl_arylen:
3744 result = &PL_vtbl_arylen;
3746 case want_vtbl_mglob:
3747 result = &PL_vtbl_mglob;
3749 case want_vtbl_nkeys:
3750 result = &PL_vtbl_nkeys;
3752 case want_vtbl_taint:
3753 result = &PL_vtbl_taint;
3755 case want_vtbl_substr:
3756 result = &PL_vtbl_substr;
3759 result = &PL_vtbl_vec;
3762 result = &PL_vtbl_pos;
3765 result = &PL_vtbl_bm;
3768 result = &PL_vtbl_fm;
3770 case want_vtbl_uvar:
3771 result = &PL_vtbl_uvar;
3773 case want_vtbl_defelem:
3774 result = &PL_vtbl_defelem;
3776 case want_vtbl_regexp:
3777 result = &PL_vtbl_regexp;
3779 case want_vtbl_regdata:
3780 result = &PL_vtbl_regdata;
3782 case want_vtbl_regdatum:
3783 result = &PL_vtbl_regdatum;
3785 #ifdef USE_LOCALE_COLLATE
3786 case want_vtbl_collxfrm:
3787 result = &PL_vtbl_collxfrm;
3790 case want_vtbl_amagic:
3791 result = &PL_vtbl_amagic;
3793 case want_vtbl_amagicelem:
3794 result = &PL_vtbl_amagicelem;
3796 case want_vtbl_backref:
3797 result = &PL_vtbl_backref;
3799 case want_vtbl_utf8:
3800 result = &PL_vtbl_utf8;
3806 return (MGVTBL*)result;
3810 Perl_my_fflush_all(pTHX)
3812 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3813 return PerlIO_flush(NULL);
3815 # if defined(HAS__FWALK)
3816 extern int fflush(FILE *);
3817 /* undocumented, unprototyped, but very useful BSDism */
3818 extern void _fwalk(int (*)(FILE *));
3822 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3824 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3825 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3827 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3828 open_max = sysconf(_SC_OPEN_MAX);
3831 open_max = FOPEN_MAX;
3834 open_max = OPEN_MAX;
3845 for (i = 0; i < open_max; i++)
3846 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3847 STDIO_STREAM_ARRAY[i]._file < open_max &&
3848 STDIO_STREAM_ARRAY[i]._flag)
3849 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3853 SETERRNO(EBADF,RMS_IFI);
3860 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3862 if (ckWARN(WARN_IO)) {
3863 const char * const name
3864 = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3865 const char * const direction = have == '>' ? "out" : "in";
3868 Perl_warner(aTHX_ packWARN(WARN_IO),
3869 "Filehandle %s opened only for %sput",
3872 Perl_warner(aTHX_ packWARN(WARN_IO),
3873 "Filehandle opened only for %sput", direction);
3878 Perl_report_evil_fh(pTHX_ const GV *gv)
3880 const IO *io = gv ? GvIO(gv) : NULL;
3881 const PERL_BITFIELD16 op = PL_op->op_type;
3885 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3887 warn_type = WARN_CLOSED;
3891 warn_type = WARN_UNOPENED;
3894 if (ckWARN(warn_type)) {
3895 const char * const name
3896 = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3897 const char * const pars =
3898 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3899 const char * const func =
3901 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3902 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3904 const char * const type =
3906 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3907 ? "socket" : "filehandle");
3908 if (name && *name) {
3909 Perl_warner(aTHX_ packWARN(warn_type),
3910 "%s%s on %s %s %s", func, pars, vile, type, name);
3911 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3913 aTHX_ packWARN(warn_type),
3914 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3919 Perl_warner(aTHX_ packWARN(warn_type),
3920 "%s%s on %s %s", func, pars, vile, type);
3921 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3923 aTHX_ packWARN(warn_type),
3924 "\t(Are you trying to call %s%s on dirhandle?)\n",
3931 /* To workaround core dumps from the uninitialised tm_zone we get the
3932 * system to give us a reasonable struct to copy. This fix means that
3933 * strftime uses the tm_zone and tm_gmtoff values returned by
3934 * localtime(time()). That should give the desired result most of the
3935 * time. But probably not always!
3937 * This does not address tzname aspects of NETaa14816.
3942 # ifndef STRUCT_TM_HASZONE
3943 # define STRUCT_TM_HASZONE
3947 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3948 # ifndef HAS_TM_TM_ZONE
3949 # define HAS_TM_TM_ZONE
3954 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3956 #ifdef HAS_TM_TM_ZONE
3958 const struct tm* my_tm;
3959 PERL_ARGS_ASSERT_INIT_TM;
3961 my_tm = localtime(&now);
3963 Copy(my_tm, ptm, 1, struct tm);
3965 PERL_ARGS_ASSERT_INIT_TM;
3966 PERL_UNUSED_ARG(ptm);
3971 * mini_mktime - normalise struct tm values without the localtime()
3972 * semantics (and overhead) of mktime().
3975 Perl_mini_mktime(pTHX_ struct tm *ptm)
3979 int month, mday, year, jday;
3980 int odd_cent, odd_year;
3981 PERL_UNUSED_CONTEXT;
3983 PERL_ARGS_ASSERT_MINI_MKTIME;
3985 #define DAYS_PER_YEAR 365
3986 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3987 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3988 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3989 #define SECS_PER_HOUR (60*60)
3990 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3991 /* parentheses deliberately absent on these two, otherwise they don't work */
3992 #define MONTH_TO_DAYS 153/5
3993 #define DAYS_TO_MONTH 5/153
3994 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3995 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3996 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3997 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
4000 * Year/day algorithm notes:
4002 * With a suitable offset for numeric value of the month, one can find
4003 * an offset into the year by considering months to have 30.6 (153/5) days,
4004 * using integer arithmetic (i.e., with truncation). To avoid too much
4005 * messing about with leap days, we consider January and February to be
4006 * the 13th and 14th month of the previous year. After that transformation,
4007 * we need the month index we use to be high by 1 from 'normal human' usage,
4008 * so the month index values we use run from 4 through 15.
4010 * Given that, and the rules for the Gregorian calendar (leap years are those
4011 * divisible by 4 unless also divisible by 100, when they must be divisible
4012 * by 400 instead), we can simply calculate the number of days since some
4013 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
4014 * the days we derive from our month index, and adding in the day of the
4015 * month. The value used here is not adjusted for the actual origin which
4016 * it normally would use (1 January A.D. 1), since we're not exposing it.
4017 * We're only building the value so we can turn around and get the
4018 * normalised values for the year, month, day-of-month, and day-of-year.
4020 * For going backward, we need to bias the value we're using so that we find
4021 * the right year value. (Basically, we don't want the contribution of
4022 * March 1st to the number to apply while deriving the year). Having done
4023 * that, we 'count up' the contribution to the year number by accounting for
4024 * full quadracenturies (400-year periods) with their extra leap days, plus
4025 * the contribution from full centuries (to avoid counting in the lost leap
4026 * days), plus the contribution from full quad-years (to count in the normal
4027 * leap days), plus the leftover contribution from any non-leap years.
4028 * At this point, if we were working with an actual leap day, we'll have 0
4029 * days left over. This is also true for March 1st, however. So, we have
4030 * to special-case that result, and (earlier) keep track of the 'odd'
4031 * century and year contributions. If we got 4 extra centuries in a qcent,
4032 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
4033 * Otherwise, we add back in the earlier bias we removed (the 123 from
4034 * figuring in March 1st), find the month index (integer division by 30.6),
4035 * and the remainder is the day-of-month. We then have to convert back to
4036 * 'real' months (including fixing January and February from being 14/15 in
4037 * the previous year to being in the proper year). After that, to get
4038 * tm_yday, we work with the normalised year and get a new yearday value for
4039 * January 1st, which we subtract from the yearday value we had earlier,
4040 * representing the date we've re-built. This is done from January 1
4041 * because tm_yday is 0-origin.
4043 * Since POSIX time routines are only guaranteed to work for times since the
4044 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
4045 * applies Gregorian calendar rules even to dates before the 16th century
4046 * doesn't bother me. Besides, you'd need cultural context for a given
4047 * date to know whether it was Julian or Gregorian calendar, and that's
4048 * outside the scope for this routine. Since we convert back based on the
4049 * same rules we used to build the yearday, you'll only get strange results
4050 * for input which needed normalising, or for the 'odd' century years which
4051 * were leap years in the Julian calendar but not in the Gregorian one.
4052 * I can live with that.
4054 * This algorithm also fails to handle years before A.D. 1 gracefully, but
4055 * that's still outside the scope for POSIX time manipulation, so I don't
4059 year = 1900 + ptm->tm_year;
4060 month = ptm->tm_mon;
4061 mday = ptm->tm_mday;
4062 /* allow given yday with no month & mday to dominate the result */
4063 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
4066 jday = 1 + ptm->tm_yday;
4075 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4076 yearday += month*MONTH_TO_DAYS + mday + jday;
4078 * Note that we don't know when leap-seconds were or will be,
4079 * so we have to trust the user if we get something which looks
4080 * like a sensible leap-second. Wild values for seconds will
4081 * be rationalised, however.
4083 if ((unsigned) ptm->tm_sec <= 60) {
4090 secs += 60 * ptm->tm_min;
4091 secs += SECS_PER_HOUR * ptm->tm_hour;
4093 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4094 /* got negative remainder, but need positive time */
4095 /* back off an extra day to compensate */
4096 yearday += (secs/SECS_PER_DAY)-1;
4097 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4100 yearday += (secs/SECS_PER_DAY);
4101 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4104 else if (secs >= SECS_PER_DAY) {
4105 yearday += (secs/SECS_PER_DAY);
4106 secs %= SECS_PER_DAY;
4108 ptm->tm_hour = secs/SECS_PER_HOUR;
4109 secs %= SECS_PER_HOUR;
4110 ptm->tm_min = secs/60;
4112 ptm->tm_sec += secs;
4113 /* done with time of day effects */
4115 * The algorithm for yearday has (so far) left it high by 428.
4116 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4117 * bias it by 123 while trying to figure out what year it
4118 * really represents. Even with this tweak, the reverse
4119 * translation fails for years before A.D. 0001.
4120 * It would still fail for Feb 29, but we catch that one below.
4122 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
4123 yearday -= YEAR_ADJUST;
4124 year = (yearday / DAYS_PER_QCENT) * 400;
4125 yearday %= DAYS_PER_QCENT;
4126 odd_cent = yearday / DAYS_PER_CENT;
4127 year += odd_cent * 100;
4128 yearday %= DAYS_PER_CENT;
4129 year += (yearday / DAYS_PER_QYEAR) * 4;
4130 yearday %= DAYS_PER_QYEAR;
4131 odd_year = yearday / DAYS_PER_YEAR;
4133 yearday %= DAYS_PER_YEAR;
4134 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4139 yearday += YEAR_ADJUST; /* recover March 1st crock */
4140 month = yearday*DAYS_TO_MONTH;
4141 yearday -= month*MONTH_TO_DAYS;
4142 /* recover other leap-year adjustment */
4151 ptm->tm_year = year - 1900;
4153 ptm->tm_mday = yearday;
4154 ptm->tm_mon = month;
4158 ptm->tm_mon = month - 1;
4160 /* re-build yearday based on Jan 1 to get tm_yday */
4162 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4163 yearday += 14*MONTH_TO_DAYS + 1;
4164 ptm->tm_yday = jday - yearday;
4165 /* fix tm_wday if not overridden by caller */
4166 if ((unsigned)ptm->tm_wday > 6)
4167 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4171 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)
4179 PERL_ARGS_ASSERT_MY_STRFTIME;
4181 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4184 mytm.tm_hour = hour;
4185 mytm.tm_mday = mday;
4187 mytm.tm_year = year;
4188 mytm.tm_wday = wday;
4189 mytm.tm_yday = yday;
4190 mytm.tm_isdst = isdst;
4192 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4193 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4198 #ifdef HAS_TM_TM_GMTOFF
4199 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4201 #ifdef HAS_TM_TM_ZONE
4202 mytm.tm_zone = mytm2.tm_zone;
4207 Newx(buf, buflen, char);
4208 len = strftime(buf, buflen, fmt, &mytm);
4210 ** The following is needed to handle to the situation where
4211 ** tmpbuf overflows. Basically we want to allocate a buffer
4212 ** and try repeatedly. The reason why it is so complicated
4213 ** is that getting a return value of 0 from strftime can indicate
4214 ** one of the following:
4215 ** 1. buffer overflowed,
4216 ** 2. illegal conversion specifier, or
4217 ** 3. the format string specifies nothing to be returned(not
4218 ** an error). This could be because format is an empty string
4219 ** or it specifies %p that yields an empty string in some locale.
4220 ** If there is a better way to make it portable, go ahead by
4223 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4226 /* Possibly buf overflowed - try again with a bigger buf */
4227 const int fmtlen = strlen(fmt);
4228 int bufsize = fmtlen + buflen;
4230 Renew(buf, bufsize, char);
4232 buflen = strftime(buf, bufsize, fmt, &mytm);
4233 if (buflen > 0 && buflen < bufsize)
4235 /* heuristic to prevent out-of-memory errors */
4236 if (bufsize > 100*fmtlen) {
4242 Renew(buf, bufsize, char);
4247 Perl_croak(aTHX_ "panic: no strftime");
4253 #define SV_CWD_RETURN_UNDEF \
4254 sv_setsv(sv, &PL_sv_undef); \
4257 #define SV_CWD_ISDOT(dp) \
4258 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4259 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4262 =head1 Miscellaneous Functions
4264 =for apidoc getcwd_sv
4266 Fill the sv with current working directory
4271 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4272 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4273 * getcwd(3) if available
4274 * Comments from the orignal:
4275 * This is a faster version of getcwd. It's also more dangerous
4276 * because you might chdir out of a directory that you can't chdir
4280 Perl_getcwd_sv(pTHX_ register SV *sv)
4284 #ifndef INCOMPLETE_TAINTS
4288 PERL_ARGS_ASSERT_GETCWD_SV;
4292 char buf[MAXPATHLEN];
4294 /* Some getcwd()s automatically allocate a buffer of the given
4295 * size from the heap if they are given a NULL buffer pointer.
4296 * The problem is that this behaviour is not portable. */
4297 if (getcwd(buf, sizeof(buf) - 1)) {
4302 sv_setsv(sv, &PL_sv_undef);
4310 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4314 SvUPGRADE(sv, SVt_PV);
4316 if (PerlLIO_lstat(".", &statbuf) < 0) {
4317 SV_CWD_RETURN_UNDEF;
4320 orig_cdev = statbuf.st_dev;
4321 orig_cino = statbuf.st_ino;
4331 if (PerlDir_chdir("..") < 0) {
4332 SV_CWD_RETURN_UNDEF;
4334 if (PerlLIO_stat(".", &statbuf) < 0) {
4335 SV_CWD_RETURN_UNDEF;
4338 cdev = statbuf.st_dev;
4339 cino = statbuf.st_ino;
4341 if (odev == cdev && oino == cino) {
4344 if (!(dir = PerlDir_open("."))) {
4345 SV_CWD_RETURN_UNDEF;
4348 while ((dp = PerlDir_read(dir)) != NULL) {
4350 namelen = dp->d_namlen;
4352 namelen = strlen(dp->d_name);
4355 if (SV_CWD_ISDOT(dp)) {
4359 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4360 SV_CWD_RETURN_UNDEF;
4363 tdev = statbuf.st_dev;
4364 tino = statbuf.st_ino;
4365 if (tino == oino && tdev == odev) {
4371 SV_CWD_RETURN_UNDEF;
4374 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4375 SV_CWD_RETURN_UNDEF;
4378 SvGROW(sv, pathlen + namelen + 1);
4382 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4385 /* prepend current directory to the front */
4387 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4388 pathlen += (namelen + 1);
4390 #ifdef VOID_CLOSEDIR
4393 if (PerlDir_close(dir) < 0) {
4394 SV_CWD_RETURN_UNDEF;
4400 SvCUR_set(sv, pathlen);
4404 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4405 SV_CWD_RETURN_UNDEF;
4408 if (PerlLIO_stat(".", &statbuf) < 0) {
4409 SV_CWD_RETURN_UNDEF;
4412 cdev = statbuf.st_dev;
4413 cino = statbuf.st_ino;
4415 if (cdev != orig_cdev || cino != orig_cino) {
4416 Perl_croak(aTHX_ "Unstable directory path, "
4417 "current directory changed unexpectedly");
4428 #define VERSION_MAX 0x7FFFFFFF
4431 =for apidoc prescan_version
4433 Validate that a given string can be parsed as a version object, but doesn't
4434 actually perform the parsing. Can use either strict or lax validation rules.
4435 Can optionally set a number of hint variables to save the parsing code
4436 some time when tokenizing.
4441 Perl_prescan_version(pTHX_ const char *s, bool strict,
4442 const char **errstr,
4443 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4444 bool qv = (sqv ? *sqv : FALSE);
4446 int saw_decimal = 0;
4450 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4452 if (qv && isDIGIT(*d))
4453 goto dotted_decimal_version;
4455 if (*d == 'v') { /* explicit v-string */
4460 else { /* degenerate v-string */
4461 /* requires v1.2.3 */
4462 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4465 dotted_decimal_version:
4466 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4467 /* no leading zeros allowed */
4468 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4471 while (isDIGIT(*d)) /* integer part */
4477 d++; /* decimal point */
4482 /* require v1.2.3 */
4483 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4486 goto version_prescan_finish;
4493 while (isDIGIT(*d)) { /* just keep reading */
4495 while (isDIGIT(*d)) {
4497 /* maximum 3 digits between decimal */
4498 if (strict && j > 3) {
4499 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4504 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4507 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4512 else if (*d == '.') {
4514 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4519 else if (!isDIGIT(*d)) {
4525 if (strict && i < 2) {
4526 /* requires v1.2.3 */
4527 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4530 } /* end if dotted-decimal */
4532 { /* decimal versions */
4533 /* special strict case for leading '.' or '0' */
4536 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4538 if (*d == '0' && isDIGIT(d[1])) {
4539 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4543 /* consume all of the integer part */
4547 /* look for a fractional part */
4549 /* we found it, so consume it */
4553 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4556 BADVERSION(s,errstr,"Invalid version format (version required)");
4558 /* found just an integer */
4559 goto version_prescan_finish;
4561 else if ( d == s ) {
4562 /* didn't find either integer or period */
4563 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4565 else if (*d == '_') {
4566 /* underscore can't come after integer part */
4568 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4570 else if (isDIGIT(d[1])) {
4571 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4574 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4578 /* anything else after integer part is just invalid data */
4579 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4582 /* scan the fractional part after the decimal point*/
4584 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4585 /* strict or lax-but-not-the-end */
4586 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4589 while (isDIGIT(*d)) {
4591 if (*d == '.' && isDIGIT(d[-1])) {
4593 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4596 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4598 d = (char *)s; /* start all over again */
4600 goto dotted_decimal_version;
4604 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4607 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4609 if ( ! isDIGIT(d[1]) ) {
4610 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4618 version_prescan_finish:
4622 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4623 /* trailing non-numeric data */
4624 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4632 *ssaw_decimal = saw_decimal;
4639 =for apidoc scan_version
4641 Returns a pointer to the next character after the parsed
4642 version string, as well as upgrading the passed in SV to
4645 Function must be called with an already existing SV like
4648 s = scan_version(s, SV *sv, bool qv);
4650 Performs some preprocessing to the string to ensure that
4651 it has the correct characteristics of a version. Flags the
4652 object if it contains an underscore (which denotes this
4653 is an alpha version). The boolean qv denotes that the version
4654 should be interpreted as if it had multiple decimals, even if
4661 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4666 const char *errstr = NULL;
4667 int saw_decimal = 0;
4671 AV * const av = newAV();
4672 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4674 PERL_ARGS_ASSERT_SCAN_VERSION;
4676 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4678 #ifndef NODEFAULT_SHAREKEYS
4679 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4682 while (isSPACE(*s)) /* leading whitespace is OK */
4685 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4687 /* "undef" is a special case and not an error */
4688 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4689 Perl_croak(aTHX_ "%s", errstr);
4699 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4701 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4702 if ( !qv && width < 3 )
4703 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4705 while (isDIGIT(*pos))
4707 if (!isALPHA(*pos)) {
4713 /* this is atoi() that delimits on underscores */
4714 const char *end = pos;
4718 /* the following if() will only be true after the decimal
4719 * point of a version originally created with a bare
4720 * floating point number, i.e. not quoted in any way
4722 if ( !qv && s > start && saw_decimal == 1 ) {
4726 rev += (*s - '0') * mult;
4728 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4729 || (PERL_ABS(rev) > VERSION_MAX )) {
4730 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4731 "Integer overflow in version %d",VERSION_MAX);
4742 while (--end >= s) {
4744 rev += (*end - '0') * mult;
4746 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4747 || (PERL_ABS(rev) > VERSION_MAX )) {
4748 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4749 "Integer overflow in version");
4758 /* Append revision */
4759 av_push(av, newSViv(rev));
4764 else if ( *pos == '.' )
4766 else if ( *pos == '_' && isDIGIT(pos[1]) )
4768 else if ( *pos == ',' && isDIGIT(pos[1]) )
4770 else if ( isDIGIT(*pos) )
4777 while ( isDIGIT(*pos) )
4782 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4790 if ( qv ) { /* quoted versions always get at least three terms*/
4791 I32 len = av_len(av);
4792 /* This for loop appears to trigger a compiler bug on OS X, as it
4793 loops infinitely. Yes, len is negative. No, it makes no sense.
4794 Compiler in question is:
4795 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4796 for ( len = 2 - len; len > 0; len-- )
4797 av_push(MUTABLE_AV(sv), newSViv(0));
4801 av_push(av, newSViv(0));
4804 /* need to save off the current version string for later */
4806 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4807 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4808 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4810 else if ( s > start ) {
4811 SV * orig = newSVpvn(start,s-start);
4812 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4813 /* need to insert a v to be consistent */
4814 sv_insert(orig, 0, 0, "v", 1);
4816 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4819 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4820 av_push(av, newSViv(0));
4823 /* And finally, store the AV in the hash */
4824 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4826 /* fix RT#19517 - special case 'undef' as string */
4827 if ( *s == 'u' && strEQ(s,"undef") ) {
4835 =for apidoc new_version
4837 Returns a new version object based on the passed in SV:
4839 SV *sv = new_version(SV *ver);
4841 Does not alter the passed in ver SV. See "upg_version" if you
4842 want to upgrade the SV.
4848 Perl_new_version(pTHX_ SV *ver)
4851 SV * const rv = newSV(0);
4852 PERL_ARGS_ASSERT_NEW_VERSION;
4853 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4856 AV * const av = newAV();
4858 /* This will get reblessed later if a derived class*/
4859 SV * const hv = newSVrv(rv, "version");
4860 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4861 #ifndef NODEFAULT_SHAREKEYS
4862 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4868 /* Begin copying all of the elements */
4869 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4870 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4872 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4873 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4875 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4877 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4878 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4881 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4883 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4884 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4887 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4888 /* This will get reblessed later if a derived class*/
4889 for ( key = 0; key <= av_len(sav); key++ )
4891 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4892 av_push(av, newSViv(rev));
4895 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4900 const MAGIC* const mg = SvVSTRING_mg(ver);
4901 if ( mg ) { /* already a v-string */
4902 const STRLEN len = mg->mg_len;
4903 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4904 sv_setpvn(rv,version,len);
4905 /* this is for consistency with the pure Perl class */
4906 if ( isDIGIT(*version) )
4907 sv_insert(rv, 0, 0, "v", 1);
4912 sv_setsv(rv,ver); /* make a duplicate */
4917 return upg_version(rv, FALSE);
4921 =for apidoc upg_version
4923 In-place upgrade of the supplied SV to a version object.
4925 SV *sv = upg_version(SV *sv, bool qv);
4927 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4928 to force this SV to be interpreted as an "extended" version.
4934 Perl_upg_version(pTHX_ SV *ver, bool qv)
4936 const char *version, *s;
4941 PERL_ARGS_ASSERT_UPG_VERSION;
4943 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4945 /* may get too much accuracy */
4947 #ifdef USE_LOCALE_NUMERIC
4948 char *loc = setlocale(LC_NUMERIC, "C");
4950 STRLEN len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4951 #ifdef USE_LOCALE_NUMERIC
4952 setlocale(LC_NUMERIC, loc);
4954 while (tbuf[len-1] == '0' && len > 0) len--;
4955 if ( tbuf[len-1] == '.' ) len--; /* eat the trailing decimal */
4956 version = savepvn(tbuf, len);
4959 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4960 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4964 else /* must be a string or something like a string */
4967 version = savepv(SvPV(ver,len));
4969 # if PERL_VERSION > 5
4970 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4971 if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
4972 /* may be a v-string */
4973 char *testv = (char *)version;
4975 for (tlen=0; tlen < len; tlen++, testv++) {
4976 /* if one of the characters is non-text assume v-string */
4977 if (testv[0] < ' ') {
4978 SV * const nsv = sv_newmortal();
4981 int saw_decimal = 0;
4982 sv_setpvf(nsv,"v%vd",ver);
4983 pos = nver = savepv(SvPV_nolen(nsv));
4985 /* scan the resulting formatted string */
4986 pos++; /* skip the leading 'v' */
4987 while ( *pos == '.' || isDIGIT(*pos) ) {
4993 /* is definitely a v-string */
4994 if ( saw_decimal >= 2 ) {
5006 s = scan_version(version, ver, qv);
5008 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
5009 "Version string '%s' contains invalid data; "
5010 "ignoring: '%s'", version, s);
5018 Validates that the SV contains valid internal structure for a version object.
5019 It may be passed either the version object (RV) or the hash itself (HV). If
5020 the structure is valid, it returns the HV. If the structure is invalid,
5023 SV *hv = vverify(sv);
5025 Note that it only confirms the bare minimum structure (so as not to get
5026 confused by derived classes which may contain additional hash entries):
5030 =item * The SV is an HV or a reference to an HV
5032 =item * The hash contains a "version" key