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
31 # define SIG_ERR ((Sighandler_t) -1)
36 /* Missing protos on LynxOS */
41 # include <sys/wait.h>
46 # include <sys/select.h>
52 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
53 # define FD_CLOEXEC 1 /* NeXT needs this */
56 /* NOTE: Do not call the next three routines directly. Use the macros
57 * in handy.h, so that we can easily redefine everything to do tracking of
58 * allocated hunks back to the original New to track down any memory leaks.
59 * XXX This advice seems to be widely ignored :-( --AD August 1996.
66 /* Can't use PerlIO to write as it allocates memory */
67 PerlLIO_write(PerlIO_fileno(Perl_error_log),
68 PL_no_mem, strlen(PL_no_mem));
70 NORETURN_FUNCTION_END;
73 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
74 # define ALWAYS_NEED_THX
77 /* paranoid version of system's malloc() */
80 Perl_safesysmalloc(MEM_SIZE size)
82 #ifdef ALWAYS_NEED_THX
88 PerlIO_printf(Perl_error_log,
89 "Allocation too large: %lx\n", size) FLUSH;
92 #endif /* HAS_64K_LIMIT */
93 #ifdef PERL_TRACK_MEMPOOL
98 Perl_croak_nocontext("panic: malloc");
100 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
101 PERL_ALLOC_CHECK(ptr);
103 #ifdef PERL_TRACK_MEMPOOL
104 struct perl_memory_debug_header *const header
105 = (struct perl_memory_debug_header *)ptr;
109 PoisonNew(((char *)ptr), size, char);
112 #ifdef PERL_TRACK_MEMPOOL
113 header->interpreter = aTHX;
114 /* Link us into the list. */
115 header->prev = &PL_memory_debug_header;
116 header->next = PL_memory_debug_header.next;
117 PL_memory_debug_header.next = header;
118 header->next->prev = header;
122 ptr = (Malloc_t)((char*)ptr+sTHX);
124 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
128 #ifndef ALWAYS_NEED_THX
134 return write_no_mem();
140 /* paranoid version of system's realloc() */
143 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
145 #ifdef ALWAYS_NEED_THX
149 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
150 Malloc_t PerlMem_realloc();
151 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
155 PerlIO_printf(Perl_error_log,
156 "Reallocation too large: %lx\n", size) FLUSH;
159 #endif /* HAS_64K_LIMIT */
166 return safesysmalloc(size);
167 #ifdef PERL_TRACK_MEMPOOL
168 where = (Malloc_t)((char*)where-sTHX);
171 struct perl_memory_debug_header *const header
172 = (struct perl_memory_debug_header *)where;
174 if (header->interpreter != aTHX) {
175 Perl_croak_nocontext("panic: realloc from wrong pool");
177 assert(header->next->prev == header);
178 assert(header->prev->next == header);
180 if (header->size > size) {
181 const MEM_SIZE freed_up = header->size - size;
182 char *start_of_freed = ((char *)where) + size;
183 PoisonFree(start_of_freed, freed_up, char);
191 Perl_croak_nocontext("panic: realloc");
193 ptr = (Malloc_t)PerlMem_realloc(where,size);
194 PERL_ALLOC_CHECK(ptr);
196 /* MUST do this fixup first, before doing ANYTHING else, as anything else
197 might allocate memory/free/move memory, and until we do the fixup, it
198 may well be chasing (and writing to) free memory. */
199 #ifdef PERL_TRACK_MEMPOOL
201 struct perl_memory_debug_header *const header
202 = (struct perl_memory_debug_header *)ptr;
205 if (header->size < size) {
206 const MEM_SIZE fresh = size - header->size;
207 char *start_of_fresh = ((char *)ptr) + size;
208 PoisonNew(start_of_fresh, fresh, char);
212 header->next->prev = header;
213 header->prev->next = header;
215 ptr = (Malloc_t)((char*)ptr+sTHX);
219 /* In particular, must do that fixup above before logging anything via
220 *printf(), as it can reallocate memory, which can cause SEGVs. */
222 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
223 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
230 #ifndef ALWAYS_NEED_THX
236 return write_no_mem();
242 /* safe version of system's free() */
245 Perl_safesysfree(Malloc_t where)
247 #ifdef ALWAYS_NEED_THX
252 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
254 #ifdef PERL_TRACK_MEMPOOL
255 where = (Malloc_t)((char*)where-sTHX);
257 struct perl_memory_debug_header *const header
258 = (struct perl_memory_debug_header *)where;
260 if (header->interpreter != aTHX) {
261 Perl_croak_nocontext("panic: free from wrong pool");
264 Perl_croak_nocontext("panic: duplicate free");
266 if (!(header->next) || header->next->prev != header
267 || header->prev->next != header) {
268 Perl_croak_nocontext("panic: bad free");
270 /* Unlink us from the chain. */
271 header->next->prev = header->prev;
272 header->prev->next = header->next;
274 PoisonNew(where, header->size, char);
276 /* Trigger the duplicate free warning. */
284 /* safe version of system's calloc() */
287 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
289 #ifdef ALWAYS_NEED_THX
293 MEM_SIZE total_size = 0;
295 /* Even though calloc() for zero bytes is strange, be robust. */
296 if (size && (count <= MEM_SIZE_MAX / size))
297 total_size = size * count;
299 Perl_croak_nocontext("%s", PL_memory_wrap);
300 #ifdef PERL_TRACK_MEMPOOL
301 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
304 Perl_croak_nocontext("%s", PL_memory_wrap);
307 if (total_size > 0xffff) {
308 PerlIO_printf(Perl_error_log,
309 "Allocation too large: %lx\n", total_size) FLUSH;
312 #endif /* HAS_64K_LIMIT */
314 if ((long)size < 0 || (long)count < 0)
315 Perl_croak_nocontext("panic: calloc");
317 #ifdef PERL_TRACK_MEMPOOL
318 /* Have to use malloc() because we've added some space for our tracking
320 /* malloc(0) is non-portable. */
321 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
323 /* Use calloc() because it might save a memset() if the memory is fresh
324 and clean from the OS. */
326 ptr = (Malloc_t)PerlMem_calloc(count, size);
327 else /* calloc(0) is non-portable. */
328 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
330 PERL_ALLOC_CHECK(ptr);
331 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));
333 #ifdef PERL_TRACK_MEMPOOL
335 struct perl_memory_debug_header *const header
336 = (struct perl_memory_debug_header *)ptr;
338 memset((void*)ptr, 0, total_size);
339 header->interpreter = aTHX;
340 /* Link us into the list. */
341 header->prev = &PL_memory_debug_header;
342 header->next = PL_memory_debug_header.next;
343 PL_memory_debug_header.next = header;
344 header->next->prev = header;
346 header->size = total_size;
348 ptr = (Malloc_t)((char*)ptr+sTHX);
354 #ifndef ALWAYS_NEED_THX
359 return write_no_mem();
363 /* These must be defined when not using Perl's malloc for binary
368 Malloc_t Perl_malloc (MEM_SIZE nbytes)
371 return (Malloc_t)PerlMem_malloc(nbytes);
374 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
377 return (Malloc_t)PerlMem_calloc(elements, size);
380 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
383 return (Malloc_t)PerlMem_realloc(where, nbytes);
386 Free_t Perl_mfree (Malloc_t where)
394 /* copy a string up to some (non-backslashed) delimiter, if any */
397 Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
401 PERL_ARGS_ASSERT_DELIMCPY;
403 for (tolen = 0; from < fromend; from++, tolen++) {
405 if (from[1] != delim) {
412 else if (*from == delim)
423 /* return ptr to little string in big string, NULL if not found */
424 /* This routine was donated by Corey Satten. */
427 Perl_instr(register const char *big, register const char *little)
431 PERL_ARGS_ASSERT_INSTR;
439 register const char *s, *x;
442 for (x=big,s=little; *s; /**/ ) {
453 return (char*)(big-1);
458 /* same as instr but allow embedded nulls */
461 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
463 PERL_ARGS_ASSERT_NINSTR;
467 const char first = *little;
469 bigend -= lend - little++;
471 while (big <= bigend) {
472 if (*big++ == first) {
473 for (x=big,s=little; s < lend; x++,s++) {
477 return (char*)(big-1);
484 /* reverse of the above--find last substring */
487 Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
489 register const char *bigbeg;
490 register const I32 first = *little;
491 register const char * const littleend = lend;
493 PERL_ARGS_ASSERT_RNINSTR;
495 if (little >= littleend)
496 return (char*)bigend;
498 big = bigend - (littleend - little++);
499 while (big >= bigbeg) {
500 register const char *s, *x;
503 for (x=big+2,s=little; s < littleend; /**/ ) {
512 return (char*)(big+1);
517 /* As a space optimization, we do not compile tables for strings of length
518 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
519 special-cased in fbm_instr().
521 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
524 =head1 Miscellaneous Functions
526 =for apidoc fbm_compile
528 Analyses the string in order to make fast searches on it using fbm_instr()
529 -- the Boyer-Moore algorithm.
535 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
538 register const U8 *s;
544 PERL_ARGS_ASSERT_FBM_COMPILE;
546 if (flags & FBMcf_TAIL) {
547 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
548 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
549 if (mg && mg->mg_len >= 0)
552 s = (U8*)SvPV_force_mutable(sv, len);
553 if (len == 0) /* TAIL might be on a zero-length string. */
555 SvUPGRADE(sv, SVt_PVGV);
560 const unsigned char *sb;
561 const U8 mlen = (len>255) ? 255 : (U8)len;
564 Sv_Grow(sv, len + 256 + PERL_FBM_TABLE_OFFSET);
566 = (unsigned char*)(SvPVX_mutable(sv) + len + PERL_FBM_TABLE_OFFSET);
567 s = table - 1 - PERL_FBM_TABLE_OFFSET; /* last char */
568 memset((void*)table, mlen, 256);
570 sb = s - mlen + 1; /* first char (maybe) */
572 if (table[*s] == mlen)
577 Sv_Grow(sv, len + PERL_FBM_TABLE_OFFSET);
579 sv_magic(sv, NULL, PERL_MAGIC_bm, NULL, 0); /* deep magic */
581 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
582 for (i = 0; i < len; i++) {
583 if (PL_freq[s[i]] < frequency) {
585 frequency = PL_freq[s[i]];
588 BmFLAGS(sv) = (U8)flags;
589 BmRARE(sv) = s[rarest];
590 BmPREVIOUS(sv) = rarest;
591 BmUSEFUL(sv) = 100; /* Initial value */
592 if (flags & FBMcf_TAIL)
594 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %lu\n",
595 BmRARE(sv),(unsigned long)BmPREVIOUS(sv)));
598 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
599 /* If SvTAIL is actually due to \Z or \z, this gives false positives
603 =for apidoc fbm_instr
605 Returns the location of the SV in the string delimited by C<str> and
606 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
607 does not have to be fbm_compiled, but the search will not be as fast
614 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
616 register unsigned char *s;
618 register const unsigned char *little
619 = (const unsigned char *)SvPV_const(littlestr,l);
620 register STRLEN littlelen = l;
621 register const I32 multiline = flags & FBMrf_MULTILINE;
623 PERL_ARGS_ASSERT_FBM_INSTR;
625 if ((STRLEN)(bigend - big) < littlelen) {
626 if ( SvTAIL(littlestr)
627 && ((STRLEN)(bigend - big) == littlelen - 1)
629 || (*big == *little &&
630 memEQ((char *)big, (char *)little, littlelen - 1))))
635 if (littlelen <= 2) { /* Special-cased */
637 if (littlelen == 1) {
638 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
639 /* Know that bigend != big. */
640 if (bigend[-1] == '\n')
641 return (char *)(bigend - 1);
642 return (char *) bigend;
650 if (SvTAIL(littlestr))
651 return (char *) bigend;
655 return (char*)big; /* Cannot be SvTAIL! */
658 if (SvTAIL(littlestr) && !multiline) {
659 if (bigend[-1] == '\n' && bigend[-2] == *little)
660 return (char*)bigend - 2;
661 if (bigend[-1] == *little)
662 return (char*)bigend - 1;
666 /* This should be better than FBM if c1 == c2, and almost
667 as good otherwise: maybe better since we do less indirection.
668 And we save a lot of memory by caching no table. */
669 const unsigned char c1 = little[0];
670 const unsigned char c2 = little[1];
675 while (s <= bigend) {
685 goto check_1char_anchor;
696 goto check_1char_anchor;
699 while (s <= bigend) {
704 goto check_1char_anchor;
713 check_1char_anchor: /* One char and anchor! */
714 if (SvTAIL(littlestr) && (*bigend == *little))
715 return (char *)bigend; /* bigend is already decremented. */
718 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
719 s = bigend - littlelen;
720 if (s >= big && bigend[-1] == '\n' && *s == *little
721 /* Automatically of length > 2 */
722 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
724 return (char*)s; /* how sweet it is */
727 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
729 return (char*)s + 1; /* how sweet it is */
733 if (!SvVALID(littlestr)) {
734 char * const b = ninstr((char*)big,(char*)bigend,
735 (char*)little, (char*)little + littlelen);
737 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
738 /* Chop \n from littlestr: */
739 s = bigend - littlelen + 1;
741 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
751 if (littlelen > (STRLEN)(bigend - big))
755 register const unsigned char * const table
756 = little + littlelen + PERL_FBM_TABLE_OFFSET;
757 register const unsigned char *oldlittle;
759 --littlelen; /* Last char found by table lookup */
762 little += littlelen; /* last char */
768 if ((tmp = table[*s])) {
769 if ((s += tmp) < bigend)
773 else { /* less expensive than calling strncmp() */
774 register unsigned char * const olds = s;
779 if (*--s == *--little)
781 s = olds + 1; /* here we pay the price for failure */
783 if (s < bigend) /* fake up continue to outer loop */
792 && (BmFLAGS(littlestr) & FBMcf_TAIL)
793 && memEQ((char *)(bigend - littlelen),
794 (char *)(oldlittle - littlelen), littlelen) )
795 return (char*)bigend - littlelen;
800 /* start_shift, end_shift are positive quantities which give offsets
801 of ends of some substring of bigstr.
802 If "last" we want the last occurrence.
803 old_posp is the way of communication between consequent calls if
804 the next call needs to find the .
805 The initial *old_posp should be -1.
807 Note that we take into account SvTAIL, so one can get extra
808 optimizations if _ALL flag is set.
811 /* If SvTAIL is actually due to \Z or \z, this gives false positives
812 if PL_multiline. In fact if !PL_multiline the authoritative answer
813 is not supported yet. */
816 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
819 register const unsigned char *big;
821 register I32 previous;
823 register const unsigned char *little;
824 register I32 stop_pos;
825 register const unsigned char *littleend;
828 PERL_ARGS_ASSERT_SCREAMINSTR;
830 assert(SvTYPE(littlestr) == SVt_PVGV);
831 assert(SvVALID(littlestr));
834 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
835 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
837 if ( BmRARE(littlestr) == '\n'
838 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
839 little = (const unsigned char *)(SvPVX_const(littlestr));
840 littleend = little + SvCUR(littlestr);
847 little = (const unsigned char *)(SvPVX_const(littlestr));
848 littleend = little + SvCUR(littlestr);
850 /* The value of pos we can start at: */
851 previous = BmPREVIOUS(littlestr);
852 big = (const unsigned char *)(SvPVX_const(bigstr));
853 /* The value of pos we can stop at: */
854 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
855 if (previous + start_shift > stop_pos) {
857 stop_pos does not include SvTAIL in the count, so this check is incorrect
858 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
861 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
866 while (pos < previous + start_shift) {
867 if (!(pos += PL_screamnext[pos]))
872 register const unsigned char *s, *x;
873 if (pos >= stop_pos) break;
874 if (big[pos] != first)
876 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
882 if (s == littleend) {
884 if (!last) return (char *)(big+pos);
887 } while ( pos += PL_screamnext[pos] );
889 return (char *)(big+(*old_posp));
891 if (!SvTAIL(littlestr) || (end_shift > 0))
893 /* Ignore the trailing "\n". This code is not microoptimized */
894 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
895 stop_pos = littleend - little; /* Actual littlestr len */
900 && ((stop_pos == 1) ||
901 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
909 Returns true if the leading len bytes of the strings s1 and s2 are the same
910 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
911 match themselves and their opposite case counterparts. Non-cased and non-ASCII
912 range bytes match only themselves.
919 Perl_foldEQ(const char *s1, const char *s2, register I32 len)
921 register const U8 *a = (const U8 *)s1;
922 register const U8 *b = (const U8 *)s2;
924 PERL_ARGS_ASSERT_FOLDEQ;
927 if (*a != *b && *a != PL_fold[*b])
934 Perl_foldEQ_latin1(const char *s1, const char *s2, register I32 len)
936 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
937 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
938 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
939 * does it check that the strings each have at least 'len' characters */
941 register const U8 *a = (const U8 *)s1;
942 register const U8 *b = (const U8 *)s2;
944 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
947 if (*a != *b && *a != PL_fold_latin1[*b]) {
956 =for apidoc foldEQ_locale
958 Returns true if the leading len bytes of the strings s1 and s2 are the same
959 case-insensitively in the current locale; false otherwise.
965 Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
968 register const U8 *a = (const U8 *)s1;
969 register const U8 *b = (const U8 *)s2;
971 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
974 if (*a != *b && *a != PL_fold_locale[*b])
981 /* copy a string to a safe spot */
984 =head1 Memory Management
988 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
989 string which is a duplicate of C<pv>. The size of the string is
990 determined by C<strlen()>. The memory allocated for the new string can
991 be freed with the C<Safefree()> function.
997 Perl_savepv(pTHX_ const char *pv)
1004 const STRLEN pvlen = strlen(pv)+1;
1005 Newx(newaddr, pvlen, char);
1006 return (char*)memcpy(newaddr, pv, pvlen);
1010 /* same thing but with a known length */
1015 Perl's version of what C<strndup()> would be if it existed. Returns a
1016 pointer to a newly allocated string which is a duplicate of the first
1017 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
1018 the new string can be freed with the C<Safefree()> function.
1024 Perl_savepvn(pTHX_ const char *pv, register I32 len)
1026 register char *newaddr;
1027 PERL_UNUSED_CONTEXT;
1029 Newx(newaddr,len+1,char);
1030 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1032 /* might not be null terminated */
1033 newaddr[len] = '\0';
1034 return (char *) CopyD(pv,newaddr,len,char);
1037 return (char *) ZeroD(newaddr,len+1,char);
1042 =for apidoc savesharedpv
1044 A version of C<savepv()> which allocates the duplicate string in memory
1045 which is shared between threads.
1050 Perl_savesharedpv(pTHX_ const char *pv)
1052 register char *newaddr;
1057 pvlen = strlen(pv)+1;
1058 newaddr = (char*)PerlMemShared_malloc(pvlen);
1060 return write_no_mem();
1062 return (char*)memcpy(newaddr, pv, pvlen);
1066 =for apidoc savesharedpvn
1068 A version of C<savepvn()> which allocates the duplicate string in memory
1069 which is shared between threads. (With the specific difference that a NULL
1070 pointer is not acceptable)
1075 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1077 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1079 PERL_ARGS_ASSERT_SAVESHAREDPVN;
1082 return write_no_mem();
1084 newaddr[len] = '\0';
1085 return (char*)memcpy(newaddr, pv, len);
1089 =for apidoc savesvpv
1091 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1092 the passed in SV using C<SvPV()>
1098 Perl_savesvpv(pTHX_ SV *sv)
1101 const char * const pv = SvPV_const(sv, len);
1102 register char *newaddr;
1104 PERL_ARGS_ASSERT_SAVESVPV;
1107 Newx(newaddr,len,char);
1108 return (char *) CopyD(pv,newaddr,len,char);
1112 =for apidoc savesharedsvpv
1114 A version of C<savesharedpv()> which allocates the duplicate string in
1115 memory which is shared between threads.
1121 Perl_savesharedsvpv(pTHX_ SV *sv)
1124 const char * const pv = SvPV_const(sv, len);
1126 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1128 return savesharedpvn(pv, len);
1131 /* the SV for Perl_form() and mess() is not kept in an arena */
1140 if (PL_phase != PERL_PHASE_DESTRUCT)
1141 return newSVpvs_flags("", SVs_TEMP);
1146 /* Create as PVMG now, to avoid any upgrading later */
1148 Newxz(any, 1, XPVMG);
1149 SvFLAGS(sv) = SVt_PVMG;
1150 SvANY(sv) = (void*)any;
1152 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1157 #if defined(PERL_IMPLICIT_CONTEXT)
1159 Perl_form_nocontext(const char* pat, ...)
1164 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1165 va_start(args, pat);
1166 retval = vform(pat, &args);
1170 #endif /* PERL_IMPLICIT_CONTEXT */
1173 =head1 Miscellaneous Functions
1176 Takes a sprintf-style format pattern and conventional
1177 (non-SV) arguments and returns the formatted string.
1179 (char *) Perl_form(pTHX_ const char* pat, ...)
1181 can be used any place a string (char *) is required:
1183 char * s = Perl_form("%d.%d",major,minor);
1185 Uses a single private buffer so if you want to format several strings you
1186 must explicitly copy the earlier strings away (and free the copies when you
1193 Perl_form(pTHX_ const char* pat, ...)
1197 PERL_ARGS_ASSERT_FORM;
1198 va_start(args, pat);
1199 retval = vform(pat, &args);
1205 Perl_vform(pTHX_ const char *pat, va_list *args)
1207 SV * const sv = mess_alloc();
1208 PERL_ARGS_ASSERT_VFORM;
1209 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1214 =for apidoc Am|SV *|mess|const char *pat|...
1216 Take a sprintf-style format pattern and argument list. These are used to
1217 generate a string message. If the message does not end with a newline,
1218 then it will be extended with some indication of the current location
1219 in the code, as described for L</mess_sv>.
1221 Normally, the resulting message is returned in a new mortal SV.
1222 During global destruction a single SV may be shared between uses of
1228 #if defined(PERL_IMPLICIT_CONTEXT)
1230 Perl_mess_nocontext(const char *pat, ...)
1235 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1236 va_start(args, pat);
1237 retval = vmess(pat, &args);
1241 #endif /* PERL_IMPLICIT_CONTEXT */
1244 Perl_mess(pTHX_ const char *pat, ...)
1248 PERL_ARGS_ASSERT_MESS;
1249 va_start(args, pat);
1250 retval = vmess(pat, &args);
1256 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1259 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1261 PERL_ARGS_ASSERT_CLOSEST_COP;
1263 if (!o || o == PL_op)
1266 if (o->op_flags & OPf_KIDS) {
1268 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1271 /* If the OP_NEXTSTATE has been optimised away we can still use it
1272 * the get the file and line number. */
1274 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1275 cop = (const COP *)kid;
1277 /* Keep searching, and return when we've found something. */
1279 new_cop = closest_cop(cop, kid);
1285 /* Nothing found. */
1291 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1293 Expands a message, intended for the user, to include an indication of
1294 the current location in the code, if the message does not already appear
1297 C<basemsg> is the initial message or object. If it is a reference, it
1298 will be used as-is and will be the result of this function. Otherwise it
1299 is used as a string, and if it already ends with a newline, it is taken
1300 to be complete, and the result of this function will be the same string.
1301 If the message does not end with a newline, then a segment such as C<at
1302 foo.pl line 37> will be appended, and possibly other clauses indicating
1303 the current state of execution. The resulting message will end with a
1306 Normally, the resulting message is returned in a new mortal SV.
1307 During global destruction a single SV may be shared between uses of this
1308 function. If C<consume> is true, then the function is permitted (but not
1309 required) to modify and return C<basemsg> instead of allocating a new SV.
1315 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1320 PERL_ARGS_ASSERT_MESS_SV;
1322 if (SvROK(basemsg)) {
1328 sv_setsv(sv, basemsg);
1333 if (SvPOK(basemsg) && consume) {
1338 sv_copypv(sv, basemsg);
1341 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1343 * Try and find the file and line for PL_op. This will usually be
1344 * PL_curcop, but it might be a cop that has been optimised away. We
1345 * can try to find such a cop by searching through the optree starting
1346 * from the sibling of PL_curcop.
1349 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1354 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1355 OutCopFILE(cop), (IV)CopLINE(cop));
1356 /* Seems that GvIO() can be untrustworthy during global destruction. */
1357 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1358 && IoLINES(GvIOp(PL_last_in_gv)))
1360 const bool line_mode = (RsSIMPLE(PL_rs) &&
1361 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1362 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1363 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1364 line_mode ? "line" : "chunk",
1365 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1367 if (PL_phase == PERL_PHASE_DESTRUCT)
1368 sv_catpvs(sv, " during global destruction");
1369 sv_catpvs(sv, ".\n");
1375 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1377 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1378 argument list. These are used to generate a string message. If the
1379 message does not end with a newline, then it will be extended with
1380 some indication of the current location in the code, as described for
1383 Normally, the resulting message is returned in a new mortal SV.
1384 During global destruction a single SV may be shared between uses of
1391 Perl_vmess(pTHX_ const char *pat, va_list *args)
1394 SV * const sv = mess_alloc();
1396 PERL_ARGS_ASSERT_VMESS;
1398 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1399 return mess_sv(sv, 1);
1403 Perl_write_to_stderr(pTHX_ SV* msv)
1409 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1411 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1412 && (io = GvIO(PL_stderrgv))
1413 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1414 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1415 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1418 /* SFIO can really mess with your errno */
1421 PerlIO * const serr = Perl_error_log;
1423 do_print(msv, serr);
1424 (void)PerlIO_flush(serr);
1432 =head1 Warning and Dieing
1435 /* Common code used in dieing and warning */
1438 S_with_queued_errors(pTHX_ SV *ex)
1440 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1441 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1442 sv_catsv(PL_errors, ex);
1443 ex = sv_mortalcopy(PL_errors);
1444 SvCUR_set(PL_errors, 0);
1450 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1456 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1457 /* sv_2cv might call Perl_croak() or Perl_warner() */
1458 SV * const oldhook = *hook;
1466 cv = sv_2cv(oldhook, &stash, &gv, 0);
1468 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1478 exarg = newSVsv(ex);
1479 SvREADONLY_on(exarg);
1482 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1486 call_sv(MUTABLE_SV(cv), G_DISCARD);
1495 =for apidoc Am|OP *|die_sv|SV *baseex
1497 Behaves the same as L</croak_sv>, except for the return type.
1498 It should be used only where the C<OP *> return type is required.
1499 The function never actually returns.
1505 Perl_die_sv(pTHX_ SV *baseex)
1507 PERL_ARGS_ASSERT_DIE_SV;
1514 =for apidoc Am|OP *|die|const char *pat|...
1516 Behaves the same as L</croak>, except for the return type.
1517 It should be used only where the C<OP *> return type is required.
1518 The function never actually returns.
1523 #if defined(PERL_IMPLICIT_CONTEXT)
1525 Perl_die_nocontext(const char* pat, ...)
1529 va_start(args, pat);
1535 #endif /* PERL_IMPLICIT_CONTEXT */
1538 Perl_die(pTHX_ const char* pat, ...)
1541 va_start(args, pat);
1549 =for apidoc Am|void|croak_sv|SV *baseex
1551 This is an XS interface to Perl's C<die> function.
1553 C<baseex> is the error message or object. If it is a reference, it
1554 will be used as-is. Otherwise it is used as a string, and if it does
1555 not end with a newline then it will be extended with some indication of
1556 the current location in the code, as described for L</mess_sv>.
1558 The error message or object will be used as an exception, by default
1559 returning control to the nearest enclosing C<eval>, but subject to
1560 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1561 function never returns normally.
1563 To die with a simple string message, the L</croak> function may be
1570 Perl_croak_sv(pTHX_ SV *baseex)
1572 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1573 PERL_ARGS_ASSERT_CROAK_SV;
1574 invoke_exception_hook(ex, FALSE);
1579 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1581 This is an XS interface to Perl's C<die> function.
1583 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1584 argument list. These are used to generate a string message. If the
1585 message does not end with a newline, then it will be extended with
1586 some indication of the current location in the code, as described for
1589 The error message will be used as an exception, by default
1590 returning control to the nearest enclosing C<eval>, but subject to
1591 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1592 function never returns normally.
1594 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1595 (C<$@>) will be used as an error message or object instead of building an
1596 error message from arguments. If you want to throw a non-string object,
1597 or build an error message in an SV yourself, it is preferable to use
1598 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1604 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1606 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1607 invoke_exception_hook(ex, FALSE);
1612 =for apidoc Am|void|croak|const char *pat|...
1614 This is an XS interface to Perl's C<die> function.
1616 Take a sprintf-style format pattern and argument list. These are used to
1617 generate a string message. If the message does not end with a newline,
1618 then it will be extended with some indication of the current location
1619 in the code, as described for L</mess_sv>.
1621 The error message will be used as an exception, by default
1622 returning control to the nearest enclosing C<eval>, but subject to
1623 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1624 function never returns normally.
1626 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1627 (C<$@>) will be used as an error message or object instead of building an
1628 error message from arguments. If you want to throw a non-string object,
1629 or build an error message in an SV yourself, it is preferable to use
1630 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1635 #if defined(PERL_IMPLICIT_CONTEXT)
1637 Perl_croak_nocontext(const char *pat, ...)
1641 va_start(args, pat);
1646 #endif /* PERL_IMPLICIT_CONTEXT */
1649 Perl_croak(pTHX_ const char *pat, ...)
1652 va_start(args, pat);
1659 =for apidoc Am|void|croak_no_modify
1661 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1662 terser object code than using C<Perl_croak>. Less code used on exception code
1663 paths reduces CPU cache pressure.
1669 Perl_croak_no_modify(pTHX)
1671 Perl_croak(aTHX_ "%s", PL_no_modify);
1675 =for apidoc Am|void|warn_sv|SV *baseex
1677 This is an XS interface to Perl's C<warn> function.
1679 C<baseex> is the error message or object. If it is a reference, it
1680 will be used as-is. Otherwise it is used as a string, and if it does
1681 not end with a newline then it will be extended with some indication of
1682 the current location in the code, as described for L</mess_sv>.
1684 The error message or object will by default be written to standard error,
1685 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1687 To warn with a simple string message, the L</warn> function may be
1694 Perl_warn_sv(pTHX_ SV *baseex)
1696 SV *ex = mess_sv(baseex, 0);
1697 PERL_ARGS_ASSERT_WARN_SV;
1698 if (!invoke_exception_hook(ex, TRUE))
1699 write_to_stderr(ex);
1703 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1705 This is an XS interface to Perl's C<warn> function.
1707 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1708 argument list. These are used to generate a string message. If the
1709 message does not end with a newline, then it will be extended with
1710 some indication of the current location in the code, as described for
1713 The error message or object will by default be written to standard error,
1714 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1716 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1722 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1724 SV *ex = vmess(pat, args);
1725 PERL_ARGS_ASSERT_VWARN;
1726 if (!invoke_exception_hook(ex, TRUE))
1727 write_to_stderr(ex);
1731 =for apidoc Am|void|warn|const char *pat|...
1733 This is an XS interface to Perl's C<warn> function.
1735 Take a sprintf-style format pattern and argument list. These are used to
1736 generate a string message. If the message does not end with a newline,
1737 then it will be extended with some indication of the current location
1738 in the code, as described for L</mess_sv>.
1740 The error message or object will by default be written to standard error,
1741 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1743 Unlike with L</croak>, C<pat> is not permitted to be null.
1748 #if defined(PERL_IMPLICIT_CONTEXT)
1750 Perl_warn_nocontext(const char *pat, ...)
1754 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1755 va_start(args, pat);
1759 #endif /* PERL_IMPLICIT_CONTEXT */
1762 Perl_warn(pTHX_ const char *pat, ...)
1765 PERL_ARGS_ASSERT_WARN;
1766 va_start(args, pat);
1771 #if defined(PERL_IMPLICIT_CONTEXT)
1773 Perl_warner_nocontext(U32 err, const char *pat, ...)
1777 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1778 va_start(args, pat);
1779 vwarner(err, pat, &args);
1782 #endif /* PERL_IMPLICIT_CONTEXT */
1785 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1787 PERL_ARGS_ASSERT_CK_WARNER_D;
1789 if (Perl_ckwarn_d(aTHX_ err)) {
1791 va_start(args, pat);
1792 vwarner(err, pat, &args);
1798 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1800 PERL_ARGS_ASSERT_CK_WARNER;
1802 if (Perl_ckwarn(aTHX_ err)) {
1804 va_start(args, pat);
1805 vwarner(err, pat, &args);
1811 Perl_warner(pTHX_ U32 err, const char* pat,...)
1814 PERL_ARGS_ASSERT_WARNER;
1815 va_start(args, pat);
1816 vwarner(err, pat, &args);
1821 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1824 PERL_ARGS_ASSERT_VWARNER;
1825 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1826 SV * const msv = vmess(pat, args);
1828 invoke_exception_hook(msv, FALSE);
1832 Perl_vwarn(aTHX_ pat, args);
1836 /* implements the ckWARN? macros */
1839 Perl_ckwarn(pTHX_ U32 w)
1842 /* If lexical warnings have not been set, use $^W. */
1844 return PL_dowarn & G_WARN_ON;
1846 return ckwarn_common(w);
1849 /* implements the ckWARN?_d macro */
1852 Perl_ckwarn_d(pTHX_ U32 w)
1855 /* If lexical warnings have not been set then default classes warn. */
1859 return ckwarn_common(w);
1863 S_ckwarn_common(pTHX_ U32 w)
1865 if (PL_curcop->cop_warnings == pWARN_ALL)
1868 if (PL_curcop->cop_warnings == pWARN_NONE)
1871 /* Check the assumption that at least the first slot is non-zero. */
1872 assert(unpackWARN1(w));
1874 /* Check the assumption that it is valid to stop as soon as a zero slot is
1876 if (!unpackWARN2(w)) {
1877 assert(!unpackWARN3(w));
1878 assert(!unpackWARN4(w));
1879 } else if (!unpackWARN3(w)) {
1880 assert(!unpackWARN4(w));
1883 /* Right, dealt with all the special cases, which are implemented as non-
1884 pointers, so there is a pointer to a real warnings mask. */
1886 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1888 } while (w >>= WARNshift);
1893 /* Set buffer=NULL to get a new one. */
1895 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1897 const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
1898 PERL_UNUSED_CONTEXT;
1899 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1902 (specialWARN(buffer) ?
1903 PerlMemShared_malloc(len_wanted) :
1904 PerlMemShared_realloc(buffer, len_wanted));
1906 Copy(bits, (buffer + 1), size, char);
1910 /* since we've already done strlen() for both nam and val
1911 * we can use that info to make things faster than
1912 * sprintf(s, "%s=%s", nam, val)
1914 #define my_setenv_format(s, nam, nlen, val, vlen) \
1915 Copy(nam, s, nlen, char); \
1917 Copy(val, s+(nlen+1), vlen, char); \
1918 *(s+(nlen+1+vlen)) = '\0'
1920 #ifdef USE_ENVIRON_ARRAY
1921 /* VMS' my_setenv() is in vms.c */
1922 #if !defined(WIN32) && !defined(NETWARE)
1924 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1928 /* only parent thread can modify process environment */
1929 if (PL_curinterp == aTHX)
1932 #ifndef PERL_USE_SAFE_PUTENV
1933 if (!PL_use_safe_putenv) {
1934 /* most putenv()s leak, so we manipulate environ directly */
1936 register const I32 len = strlen(nam);
1939 /* where does it go? */
1940 for (i = 0; environ[i]; i++) {
1941 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1945 if (environ == PL_origenviron) { /* need we copy environment? */
1951 while (environ[max])
1953 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1954 for (j=0; j<max; j++) { /* copy environment */
1955 const int len = strlen(environ[j]);
1956 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1957 Copy(environ[j], tmpenv[j], len+1, char);
1960 environ = tmpenv; /* tell exec where it is now */
1963 safesysfree(environ[i]);
1964 while (environ[i]) {
1965 environ[i] = environ[i+1];
1970 if (!environ[i]) { /* does not exist yet */
1971 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1972 environ[i+1] = NULL; /* make sure it's null terminated */
1975 safesysfree(environ[i]);
1979 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1980 /* all that work just for this */
1981 my_setenv_format(environ[i], nam, nlen, val, vlen);
1984 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
1985 # if defined(HAS_UNSETENV)
1987 (void)unsetenv(nam);
1989 (void)setenv(nam, val, 1);
1991 # else /* ! HAS_UNSETENV */
1992 (void)setenv(nam, val, 1);
1993 # endif /* HAS_UNSETENV */
1995 # if defined(HAS_UNSETENV)
1997 (void)unsetenv(nam);
1999 const int nlen = strlen(nam);
2000 const int vlen = strlen(val);
2001 char * const new_env =
2002 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2003 my_setenv_format(new_env, nam, nlen, val, vlen);
2004 (void)putenv(new_env);
2006 # else /* ! HAS_UNSETENV */
2008 const int nlen = strlen(nam);
2014 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2015 /* all that work just for this */
2016 my_setenv_format(new_env, nam, nlen, val, vlen);
2017 (void)putenv(new_env);
2018 # endif /* HAS_UNSETENV */
2019 # endif /* __CYGWIN__ */
2020 #ifndef PERL_USE_SAFE_PUTENV
2026 #else /* WIN32 || NETWARE */
2029 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2032 register char *envstr;
2033 const int nlen = strlen(nam);
2040 Newx(envstr, nlen+vlen+2, char);
2041 my_setenv_format(envstr, nam, nlen, val, vlen);
2042 (void)PerlEnv_putenv(envstr);
2046 #endif /* WIN32 || NETWARE */
2048 #endif /* !VMS && !EPOC*/
2050 #ifdef UNLINK_ALL_VERSIONS
2052 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2056 PERL_ARGS_ASSERT_UNLNK;
2058 while (PerlLIO_unlink(f) >= 0)
2060 return retries ? 0 : -1;
2064 /* this is a drop-in replacement for bcopy() */
2065 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2067 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2069 char * const retval = to;
2071 PERL_ARGS_ASSERT_MY_BCOPY;
2073 if (from - to >= 0) {
2081 *(--to) = *(--from);
2087 /* this is a drop-in replacement for memset() */
2090 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2092 char * const retval = loc;
2094 PERL_ARGS_ASSERT_MY_MEMSET;
2102 /* this is a drop-in replacement for bzero() */
2103 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2105 Perl_my_bzero(register char *loc, register I32 len)
2107 char * const retval = loc;
2109 PERL_ARGS_ASSERT_MY_BZERO;
2117 /* this is a drop-in replacement for memcmp() */
2118 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2120 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2122 register const U8 *a = (const U8 *)s1;
2123 register const U8 *b = (const U8 *)s2;
2126 PERL_ARGS_ASSERT_MY_MEMCMP;
2129 if ((tmp = *a++ - *b++))
2134 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2137 /* This vsprintf replacement should generally never get used, since
2138 vsprintf was available in both System V and BSD 2.11. (There may
2139 be some cross-compilation or embedded set-ups where it is needed,
2142 If you encounter a problem in this function, it's probably a symptom
2143 that Configure failed to detect your system's vprintf() function.
2144 See the section on "item vsprintf" in the INSTALL file.
2146 This version may compile on systems with BSD-ish <stdio.h>,
2147 but probably won't on others.
2150 #ifdef USE_CHAR_VSPRINTF
2155 vsprintf(char *dest, const char *pat, void *args)
2159 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2160 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2161 FILE_cnt(&fakebuf) = 32767;
2163 /* These probably won't compile -- If you really need
2164 this, you'll have to figure out some other method. */
2165 fakebuf._ptr = dest;
2166 fakebuf._cnt = 32767;
2171 fakebuf._flag = _IOWRT|_IOSTRG;
2172 _doprnt(pat, args, &fakebuf); /* what a kludge */
2173 #if defined(STDIO_PTR_LVALUE)
2174 *(FILE_ptr(&fakebuf)++) = '\0';
2176 /* PerlIO has probably #defined away fputc, but we want it here. */
2178 # undef fputc /* XXX Should really restore it later */
2180 (void)fputc('\0', &fakebuf);
2182 #ifdef USE_CHAR_VSPRINTF
2185 return 0; /* perl doesn't use return value */
2189 #endif /* HAS_VPRINTF */
2192 #if BYTEORDER != 0x4321
2194 Perl_my_swap(pTHX_ short s)
2196 #if (BYTEORDER & 1) == 0
2199 result = ((s & 255) << 8) + ((s >> 8) & 255);
2207 Perl_my_htonl(pTHX_ long l)
2211 char c[sizeof(long)];
2214 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2215 #if BYTEORDER == 0x12345678
2218 u.c[0] = (l >> 24) & 255;
2219 u.c[1] = (l >> 16) & 255;
2220 u.c[2] = (l >> 8) & 255;
2224 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2225 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2230 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2231 u.c[o & 0xf] = (l >> s) & 255;
2239 Perl_my_ntohl(pTHX_ long l)
2243 char c[sizeof(long)];
2246 #if BYTEORDER == 0x1234
2247 u.c[0] = (l >> 24) & 255;
2248 u.c[1] = (l >> 16) & 255;
2249 u.c[2] = (l >> 8) & 255;
2253 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2254 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2261 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2262 l |= (u.c[o & 0xf] & 255) << s;
2269 #endif /* BYTEORDER != 0x4321 */
2273 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2274 * If these functions are defined,
2275 * the BYTEORDER is neither 0x1234 nor 0x4321.
2276 * However, this is not assumed.
2280 #define HTOLE(name,type) \
2282 name (register type n) \
2286 char c[sizeof(type)]; \
2289 register U32 s = 0; \
2290 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2291 u.c[i] = (n >> s) & 0xFF; \
2296 #define LETOH(name,type) \
2298 name (register type n) \
2302 char c[sizeof(type)]; \
2305 register U32 s = 0; \
2308 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2309 n |= ((type)(u.c[i] & 0xFF)) << s; \
2315 * Big-endian byte order functions.
2318 #define HTOBE(name,type) \
2320 name (register type n) \
2324 char c[sizeof(type)]; \
2327 register U32 s = 8*(sizeof(u.c)-1); \
2328 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2329 u.c[i] = (n >> s) & 0xFF; \
2334 #define BETOH(name,type) \
2336 name (register type n) \
2340 char c[sizeof(type)]; \
2343 register U32 s = 8*(sizeof(u.c)-1); \
2346 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2347 n |= ((type)(u.c[i] & 0xFF)) << s; \
2353 * If we just can't do it...
2356 #define NOT_AVAIL(name,type) \
2358 name (register type n) \
2360 Perl_croak_nocontext(#name "() not available"); \
2361 return n; /* not reached */ \
2365 #if defined(HAS_HTOVS) && !defined(htovs)
2368 #if defined(HAS_HTOVL) && !defined(htovl)
2371 #if defined(HAS_VTOHS) && !defined(vtohs)
2374 #if defined(HAS_VTOHL) && !defined(vtohl)
2378 #ifdef PERL_NEED_MY_HTOLE16
2380 HTOLE(Perl_my_htole16,U16)
2382 NOT_AVAIL(Perl_my_htole16,U16)
2385 #ifdef PERL_NEED_MY_LETOH16
2387 LETOH(Perl_my_letoh16,U16)
2389 NOT_AVAIL(Perl_my_letoh16,U16)
2392 #ifdef PERL_NEED_MY_HTOBE16
2394 HTOBE(Perl_my_htobe16,U16)
2396 NOT_AVAIL(Perl_my_htobe16,U16)
2399 #ifdef PERL_NEED_MY_BETOH16
2401 BETOH(Perl_my_betoh16,U16)
2403 NOT_AVAIL(Perl_my_betoh16,U16)
2407 #ifdef PERL_NEED_MY_HTOLE32
2409 HTOLE(Perl_my_htole32,U32)
2411 NOT_AVAIL(Perl_my_htole32,U32)
2414 #ifdef PERL_NEED_MY_LETOH32
2416 LETOH(Perl_my_letoh32,U32)
2418 NOT_AVAIL(Perl_my_letoh32,U32)
2421 #ifdef PERL_NEED_MY_HTOBE32
2423 HTOBE(Perl_my_htobe32,U32)
2425 NOT_AVAIL(Perl_my_htobe32,U32)
2428 #ifdef PERL_NEED_MY_BETOH32
2430 BETOH(Perl_my_betoh32,U32)
2432 NOT_AVAIL(Perl_my_betoh32,U32)
2436 #ifdef PERL_NEED_MY_HTOLE64
2438 HTOLE(Perl_my_htole64,U64)
2440 NOT_AVAIL(Perl_my_htole64,U64)
2443 #ifdef PERL_NEED_MY_LETOH64
2445 LETOH(Perl_my_letoh64,U64)
2447 NOT_AVAIL(Perl_my_letoh64,U64)
2450 #ifdef PERL_NEED_MY_HTOBE64
2452 HTOBE(Perl_my_htobe64,U64)
2454 NOT_AVAIL(Perl_my_htobe64,U64)
2457 #ifdef PERL_NEED_MY_BETOH64
2459 BETOH(Perl_my_betoh64,U64)
2461 NOT_AVAIL(Perl_my_betoh64,U64)
2465 #ifdef PERL_NEED_MY_HTOLES
2466 HTOLE(Perl_my_htoles,short)
2468 #ifdef PERL_NEED_MY_LETOHS
2469 LETOH(Perl_my_letohs,short)
2471 #ifdef PERL_NEED_MY_HTOBES
2472 HTOBE(Perl_my_htobes,short)
2474 #ifdef PERL_NEED_MY_BETOHS
2475 BETOH(Perl_my_betohs,short)
2478 #ifdef PERL_NEED_MY_HTOLEI
2479 HTOLE(Perl_my_htolei,int)
2481 #ifdef PERL_NEED_MY_LETOHI
2482 LETOH(Perl_my_letohi,int)
2484 #ifdef PERL_NEED_MY_HTOBEI
2485 HTOBE(Perl_my_htobei,int)
2487 #ifdef PERL_NEED_MY_BETOHI
2488 BETOH(Perl_my_betohi,int)
2491 #ifdef PERL_NEED_MY_HTOLEL
2492 HTOLE(Perl_my_htolel,long)
2494 #ifdef PERL_NEED_MY_LETOHL
2495 LETOH(Perl_my_letohl,long)
2497 #ifdef PERL_NEED_MY_HTOBEL
2498 HTOBE(Perl_my_htobel,long)
2500 #ifdef PERL_NEED_MY_BETOHL
2501 BETOH(Perl_my_betohl,long)
2505 Perl_my_swabn(void *ptr, int n)
2507 register char *s = (char *)ptr;
2508 register char *e = s + (n-1);
2511 PERL_ARGS_ASSERT_MY_SWABN;
2513 for (n /= 2; n > 0; s++, e--, n--) {
2521 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2523 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2526 register I32 This, that;
2532 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2534 PERL_FLUSHALL_FOR_CHILD;
2535 This = (*mode == 'w');
2539 taint_proper("Insecure %s%s", "EXEC");
2541 if (PerlProc_pipe(p) < 0)
2543 /* Try for another pipe pair for error return */
2544 if (PerlProc_pipe(pp) >= 0)
2546 while ((pid = PerlProc_fork()) < 0) {
2547 if (errno != EAGAIN) {
2548 PerlLIO_close(p[This]);
2549 PerlLIO_close(p[that]);
2551 PerlLIO_close(pp[0]);
2552 PerlLIO_close(pp[1]);
2556 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2565 /* Close parent's end of error status pipe (if any) */
2567 PerlLIO_close(pp[0]);
2568 #if defined(HAS_FCNTL) && defined(F_SETFD)
2569 /* Close error pipe automatically if exec works */
2570 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2573 /* Now dup our end of _the_ pipe to right position */
2574 if (p[THIS] != (*mode == 'r')) {
2575 PerlLIO_dup2(p[THIS], *mode == 'r');
2576 PerlLIO_close(p[THIS]);
2577 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2578 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2581 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2582 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2583 /* No automatic close - do it by hand */
2590 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2596 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2602 do_execfree(); /* free any memory malloced by child on fork */
2604 PerlLIO_close(pp[1]);
2605 /* Keep the lower of the two fd numbers */
2606 if (p[that] < p[This]) {
2607 PerlLIO_dup2(p[This], p[that]);
2608 PerlLIO_close(p[This]);
2612 PerlLIO_close(p[that]); /* close child's end of pipe */
2614 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2615 SvUPGRADE(sv,SVt_IV);
2617 PL_forkprocess = pid;
2618 /* If we managed to get status pipe check for exec fail */
2619 if (did_pipes && pid > 0) {
2624 while (n < sizeof(int)) {
2625 n1 = PerlLIO_read(pp[0],
2626 (void*)(((char*)&errkid)+n),
2632 PerlLIO_close(pp[0]);
2634 if (n) { /* Error */
2636 PerlLIO_close(p[This]);
2637 if (n != sizeof(int))
2638 Perl_croak(aTHX_ "panic: kid popen errno read");
2640 pid2 = wait4pid(pid, &status, 0);
2641 } while (pid2 == -1 && errno == EINTR);
2642 errno = errkid; /* Propagate errno from kid */
2647 PerlLIO_close(pp[0]);
2648 return PerlIO_fdopen(p[This], mode);
2650 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2651 return my_syspopen4(aTHX_ NULL, mode, n, args);
2653 Perl_croak(aTHX_ "List form of piped open not implemented");
2654 return (PerlIO *) NULL;
2659 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2660 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
2662 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2666 register I32 This, that;
2669 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2673 PERL_ARGS_ASSERT_MY_POPEN;
2675 PERL_FLUSHALL_FOR_CHILD;
2678 return my_syspopen(aTHX_ cmd,mode);
2681 This = (*mode == 'w');
2683 if (doexec && PL_tainting) {
2685 taint_proper("Insecure %s%s", "EXEC");
2687 if (PerlProc_pipe(p) < 0)
2689 if (doexec && PerlProc_pipe(pp) >= 0)
2691 while ((pid = PerlProc_fork()) < 0) {
2692 if (errno != EAGAIN) {
2693 PerlLIO_close(p[This]);
2694 PerlLIO_close(p[that]);
2696 PerlLIO_close(pp[0]);
2697 PerlLIO_close(pp[1]);
2700 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2703 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2714 PerlLIO_close(pp[0]);
2715 #if defined(HAS_FCNTL) && defined(F_SETFD)
2716 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2719 if (p[THIS] != (*mode == 'r')) {
2720 PerlLIO_dup2(p[THIS], *mode == 'r');
2721 PerlLIO_close(p[THIS]);
2722 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2723 PerlLIO_close(p[THAT]);
2726 PerlLIO_close(p[THAT]);
2729 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2736 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2741 /* may or may not use the shell */
2742 do_exec3(cmd, pp[1], did_pipes);
2745 #endif /* defined OS2 */
2747 #ifdef PERLIO_USING_CRLF
2748 /* Since we circumvent IO layers when we manipulate low-level
2749 filedescriptors directly, need to manually switch to the
2750 default, binary, low-level mode; see PerlIOBuf_open(). */
2751 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2754 if ((tmpgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV))) {
2755 SvREADONLY_off(GvSV(tmpgv));
2756 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2757 SvREADONLY_on(GvSV(tmpgv));
2759 #ifdef THREADS_HAVE_PIDS
2760 PL_ppid = (IV)getppid();
2763 #ifdef PERL_USES_PL_PIDSTATUS
2764 hv_clear(PL_pidstatus); /* we have no children */
2770 do_execfree(); /* free any memory malloced by child on vfork */
2772 PerlLIO_close(pp[1]);
2773 if (p[that] < p[This]) {
2774 PerlLIO_dup2(p[This], p[that]);
2775 PerlLIO_close(p[This]);
2779 PerlLIO_close(p[that]);
2781 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2782 SvUPGRADE(sv,SVt_IV);
2784 PL_forkprocess = pid;
2785 if (did_pipes && pid > 0) {
2790 while (n < sizeof(int)) {
2791 n1 = PerlLIO_read(pp[0],
2792 (void*)(((char*)&errkid)+n),
2798 PerlLIO_close(pp[0]);
2800 if (n) { /* Error */
2802 PerlLIO_close(p[This]);
2803 if (n != sizeof(int))
2804 Perl_croak(aTHX_ "panic: kid popen errno read");
2806 pid2 = wait4pid(pid, &status, 0);
2807 } while (pid2 == -1 && errno == EINTR);
2808 errno = errkid; /* Propagate errno from kid */
2813 PerlLIO_close(pp[0]);
2814 return PerlIO_fdopen(p[This], mode);
2817 #if defined(atarist) || defined(EPOC)
2820 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2822 PERL_ARGS_ASSERT_MY_POPEN;
2823 PERL_FLUSHALL_FOR_CHILD;
2824 /* Call system's popen() to get a FILE *, then import it.
2825 used 0 for 2nd parameter to PerlIO_importFILE;
2828 return PerlIO_importFILE(popen(cmd, mode), 0);
2832 FILE *djgpp_popen();
2834 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2836 PERL_FLUSHALL_FOR_CHILD;
2837 /* Call system's popen() to get a FILE *, then import it.
2838 used 0 for 2nd parameter to PerlIO_importFILE;
2841 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2844 #if defined(__LIBCATAMOUNT__)
2846 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2854 #endif /* !DOSISH */
2856 /* this is called in parent before the fork() */
2858 Perl_atfork_lock(void)
2861 #if defined(USE_ITHREADS)
2862 /* locks must be held in locking order (if any) */
2864 MUTEX_LOCK(&PL_malloc_mutex);
2870 /* this is called in both parent and child after the fork() */
2872 Perl_atfork_unlock(void)
2875 #if defined(USE_ITHREADS)
2876 /* locks must be released in same order as in atfork_lock() */
2878 MUTEX_UNLOCK(&PL_malloc_mutex);
2887 #if defined(HAS_FORK)
2889 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2894 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2895 * handlers elsewhere in the code */
2900 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2901 Perl_croak_nocontext("fork() not available");
2903 #endif /* HAS_FORK */
2908 Perl_dump_fds(pTHX_ const char *const s)
2913 PERL_ARGS_ASSERT_DUMP_FDS;
2915 PerlIO_printf(Perl_debug_log,"%s", s);
2916 for (fd = 0; fd < 32; fd++) {
2917 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2918 PerlIO_printf(Perl_debug_log," %d",fd);
2920 PerlIO_printf(Perl_debug_log,"\n");
2923 #endif /* DUMP_FDS */
2927 dup2(int oldfd, int newfd)
2929 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2932 PerlLIO_close(newfd);
2933 return fcntl(oldfd, F_DUPFD, newfd);
2935 #define DUP2_MAX_FDS 256
2936 int fdtmp[DUP2_MAX_FDS];
2942 PerlLIO_close(newfd);
2943 /* good enough for low fd's... */
2944 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2945 if (fdx >= DUP2_MAX_FDS) {
2953 PerlLIO_close(fdtmp[--fdx]);
2960 #ifdef HAS_SIGACTION
2963 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2966 struct sigaction act, oact;
2969 /* only "parent" interpreter can diddle signals */
2970 if (PL_curinterp != aTHX)
2971 return (Sighandler_t) SIG_ERR;
2974 act.sa_handler = (void(*)(int))handler;
2975 sigemptyset(&act.sa_mask);
2978 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2979 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2981 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2982 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2983 act.sa_flags |= SA_NOCLDWAIT;
2985 if (sigaction(signo, &act, &oact) == -1)
2986 return (Sighandler_t) SIG_ERR;
2988 return (Sighandler_t) oact.sa_handler;
2992 Perl_rsignal_state(pTHX_ int signo)
2994 struct sigaction oact;
2995 PERL_UNUSED_CONTEXT;
2997 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2998 return (Sighandler_t) SIG_ERR;
3000 return (Sighandler_t) oact.sa_handler;
3004 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3007 struct sigaction act;
3009 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
3012 /* only "parent" interpreter can diddle signals */
3013 if (PL_curinterp != aTHX)
3017 act.sa_handler = (void(*)(int))handler;
3018 sigemptyset(&act.sa_mask);
3021 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3022 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
3024 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3025 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3026 act.sa_flags |= SA_NOCLDWAIT;
3028 return sigaction(signo, &act, save);
3032 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3036 /* only "parent" interpreter can diddle signals */
3037 if (PL_curinterp != aTHX)
3041 return sigaction(signo, save, (struct sigaction *)NULL);
3044 #else /* !HAS_SIGACTION */
3047 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3049 #if defined(USE_ITHREADS) && !defined(WIN32)
3050 /* only "parent" interpreter can diddle signals */
3051 if (PL_curinterp != aTHX)
3052 return (Sighandler_t) SIG_ERR;
3055 return PerlProc_signal(signo, handler);
3066 Perl_rsignal_state(pTHX_ int signo)
3069 Sighandler_t oldsig;
3071 #if defined(USE_ITHREADS) && !defined(WIN32)
3072 /* only "parent" interpreter can diddle signals */
3073 if (PL_curinterp != aTHX)
3074 return (Sighandler_t) SIG_ERR;
3078 oldsig = PerlProc_signal(signo, sig_trap);
3079 PerlProc_signal(signo, oldsig);
3081 PerlProc_kill(PerlProc_getpid(), signo);
3086 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3088 #if defined(USE_ITHREADS) && !defined(WIN32)
3089 /* only "parent" interpreter can diddle signals */
3090 if (PL_curinterp != aTHX)
3093 *save = PerlProc_signal(signo, handler);
3094 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3098 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3100 #if defined(USE_ITHREADS) && !defined(WIN32)
3101 /* only "parent" interpreter can diddle signals */
3102 if (PL_curinterp != aTHX)
3105 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3108 #endif /* !HAS_SIGACTION */
3109 #endif /* !PERL_MICRO */
3111 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3112 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
3114 Perl_my_pclose(pTHX_ PerlIO *ptr)
3117 Sigsave_t hstat, istat, qstat;
3125 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
3126 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3128 *svp = &PL_sv_undef;
3130 if (pid == -1) { /* Opened by popen. */
3131 return my_syspclose(ptr);
3134 close_failed = (PerlIO_close(ptr) == EOF);
3137 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
3140 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3141 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3142 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3145 pid2 = wait4pid(pid, &status, 0);
3146 } while (pid2 == -1 && errno == EINTR);
3148 rsignal_restore(SIGHUP, &hstat);
3149 rsignal_restore(SIGINT, &istat);
3150 rsignal_restore(SIGQUIT, &qstat);
3156 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
3159 #if defined(__LIBCATAMOUNT__)
3161 Perl_my_pclose(pTHX_ PerlIO *ptr)
3166 #endif /* !DOSISH */
3168 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3170 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3174 PERL_ARGS_ASSERT_WAIT4PID;
3177 #ifdef PERL_USES_PL_PIDSTATUS
3180 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3181 pid, rather than a string form. */
3182 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3183 if (svp && *svp != &PL_sv_undef) {
3184 *statusp = SvIVX(*svp);
3185 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3193 hv_iterinit(PL_pidstatus);
3194 if ((entry = hv_iternext(PL_pidstatus))) {
3195 SV * const sv = hv_iterval(PL_pidstatus,entry);
3197 const char * const spid = hv_iterkey(entry,&len);
3199 assert (len == sizeof(Pid_t));
3200 memcpy((char *)&pid, spid, len);
3201 *statusp = SvIVX(sv);
3202 /* The hash iterator is currently on this entry, so simply
3203 calling hv_delete would trigger the lazy delete, which on
3204 aggregate does more work, beacuse next call to hv_iterinit()
3205 would spot the flag, and have to call the delete routine,
3206 while in the meantime any new entries can't re-use that
3208 hv_iterinit(PL_pidstatus);
3209 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3216 # ifdef HAS_WAITPID_RUNTIME
3217 if (!HAS_WAITPID_RUNTIME)
3220 result = PerlProc_waitpid(pid,statusp,flags);
3223 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3224 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3227 #ifdef PERL_USES_PL_PIDSTATUS
3228 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3233 Perl_croak(aTHX_ "Can't do waitpid with flags");
3235 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3236 pidgone(result,*statusp);
3242 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3245 if (result < 0 && errno == EINTR) {
3247 errno = EINTR; /* reset in case a signal handler changed $! */
3251 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3253 #ifdef PERL_USES_PL_PIDSTATUS
3255 S_pidgone(pTHX_ Pid_t pid, int status)
3259 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3260 SvUPGRADE(sv,SVt_IV);
3261 SvIV_set(sv, status);
3266 #if defined(atarist) || defined(OS2) || defined(EPOC)
3269 int /* Cannot prototype with I32
3271 my_syspclose(PerlIO *ptr)
3274 Perl_my_pclose(pTHX_ PerlIO *ptr)
3277 /* Needs work for PerlIO ! */
3278 FILE * const f = PerlIO_findFILE(ptr);
3279 const I32 result = pclose(f);
3280 PerlIO_releaseFILE(ptr,f);
3288 Perl_my_pclose(pTHX_ PerlIO *ptr)
3290 /* Needs work for PerlIO ! */
3291 FILE * const f = PerlIO_findFILE(ptr);
3292 I32 result = djgpp_pclose(f);
3293 result = (result << 8) & 0xff00;
3294 PerlIO_releaseFILE(ptr,f);
3299 #define PERL_REPEATCPY_LINEAR 4
3301 Perl_repeatcpy(register char *to, register const char *from, I32 len, register I32 count)
3303 PERL_ARGS_ASSERT_REPEATCPY;
3306 memset(to, *from, count);
3308 register char *p = to;
3309 I32 items, linear, half;
3311 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3312 for (items = 0; items < linear; ++items) {
3313 register const char *q = from;
3315 for (todo = len; todo > 0; todo--)
3320 while (items <= half) {
3321 I32 size = items * len;
3322 memcpy(p, to, size);
3328 memcpy(p, to, (count - items) * len);
3334 Perl_same_dirent(pTHX_ const char *a, const char *b)
3336 char *fa = strrchr(a,'/');
3337 char *fb = strrchr(b,'/');
3340 SV * const tmpsv = sv_newmortal();
3342 PERL_ARGS_ASSERT_SAME_DIRENT;
3355 sv_setpvs(tmpsv, ".");
3357 sv_setpvn(tmpsv, a, fa - a);
3358 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3361 sv_setpvs(tmpsv, ".");
3363 sv_setpvn(tmpsv, b, fb - b);
3364 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3366 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3367 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3369 #endif /* !HAS_RENAME */
3372 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3373 const char *const *const search_ext, I32 flags)
3376 const char *xfound = NULL;
3377 char *xfailed = NULL;
3378 char tmpbuf[MAXPATHLEN];
3383 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3384 # define SEARCH_EXTS ".bat", ".cmd", NULL
3385 # define MAX_EXT_LEN 4
3388 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3389 # define MAX_EXT_LEN 4
3392 # define SEARCH_EXTS ".pl", ".com", NULL
3393 # define MAX_EXT_LEN 4
3395 /* additional extensions to try in each dir if scriptname not found */
3397 static const char *const exts[] = { SEARCH_EXTS };
3398 const char *const *const ext = search_ext ? search_ext : exts;
3399 int extidx = 0, i = 0;
3400 const char *curext = NULL;
3402 PERL_UNUSED_ARG(search_ext);
3403 # define MAX_EXT_LEN 0
3406 PERL_ARGS_ASSERT_FIND_SCRIPT;
3409 * If dosearch is true and if scriptname does not contain path
3410 * delimiters, search the PATH for scriptname.
3412 * If SEARCH_EXTS is also defined, will look for each
3413 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3414 * while searching the PATH.
3416 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3417 * proceeds as follows:
3418 * If DOSISH or VMSISH:
3419 * + look for ./scriptname{,.foo,.bar}
3420 * + search the PATH for scriptname{,.foo,.bar}
3423 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3424 * this will not look in '.' if it's not in the PATH)
3429 # ifdef ALWAYS_DEFTYPES
3430 len = strlen(scriptname);
3431 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3432 int idx = 0, deftypes = 1;
3435 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3438 int idx = 0, deftypes = 1;
3441 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3443 /* The first time through, just add SEARCH_EXTS to whatever we
3444 * already have, so we can check for default file types. */
3446 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3452 if ((strlen(tmpbuf) + strlen(scriptname)
3453 + MAX_EXT_LEN) >= sizeof tmpbuf)
3454 continue; /* don't search dir with too-long name */
3455 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3459 if (strEQ(scriptname, "-"))
3461 if (dosearch) { /* Look in '.' first. */
3462 const char *cur = scriptname;
3464 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3466 if (strEQ(ext[i++],curext)) {
3467 extidx = -1; /* already has an ext */
3472 DEBUG_p(PerlIO_printf(Perl_debug_log,
3473 "Looking for %s\n",cur));
3474 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3475 && !S_ISDIR(PL_statbuf.st_mode)) {
3483 if (cur == scriptname) {
3484 len = strlen(scriptname);
3485 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3487 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3490 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3491 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3496 if (dosearch && !strchr(scriptname, '/')
3498 && !strchr(scriptname, '\\')
3500 && (s = PerlEnv_getenv("PATH")))
3504 bufend = s + strlen(s);
3505 while (s < bufend) {
3506 #if defined(atarist) || defined(DOSISH)
3511 && *s != ';'; len++, s++) {
3512 if (len < sizeof tmpbuf)
3515 if (len < sizeof tmpbuf)
3517 #else /* ! (atarist || DOSISH) */
3518 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3521 #endif /* ! (atarist || DOSISH) */
3524 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3525 continue; /* don't search dir with too-long name */
3527 # if defined(atarist) || defined(DOSISH)
3528 && tmpbuf[len - 1] != '/'
3529 && tmpbuf[len - 1] != '\\'
3532 tmpbuf[len++] = '/';
3533 if (len == 2 && tmpbuf[0] == '.')
3535 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3539 len = strlen(tmpbuf);
3540 if (extidx > 0) /* reset after previous loop */
3544 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3545 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3546 if (S_ISDIR(PL_statbuf.st_mode)) {
3550 } while ( retval < 0 /* not there */
3551 && extidx>=0 && ext[extidx] /* try an extension? */
3552 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3557 if (S_ISREG(PL_statbuf.st_mode)
3558 && cando(S_IRUSR,TRUE,&PL_statbuf)
3559 #if !defined(DOSISH)
3560 && cando(S_IXUSR,TRUE,&PL_statbuf)
3564 xfound = tmpbuf; /* bingo! */
3568 xfailed = savepv(tmpbuf);
3571 if (!xfound && !seen_dot && !xfailed &&
3572 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3573 || S_ISDIR(PL_statbuf.st_mode)))
3575 seen_dot = 1; /* Disable message. */
3577 if (flags & 1) { /* do or die? */
3578 Perl_croak(aTHX_ "Can't %s %s%s%s",
3579 (xfailed ? "execute" : "find"),
3580 (xfailed ? xfailed : scriptname),
3581 (xfailed ? "" : " on PATH"),
3582 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3587 scriptname = xfound;
3589 return (scriptname ? savepv(scriptname) : NULL);
3592 #ifndef PERL_GET_CONTEXT_DEFINED
3595 Perl_get_context(void)
3598 #if defined(USE_ITHREADS)
3599 # ifdef OLD_PTHREADS_API
3601 if (pthread_getspecific(PL_thr_key, &t))
3602 Perl_croak_nocontext("panic: pthread_getspecific");
3605 # ifdef I_MACH_CTHREADS
3606 return (void*)cthread_data(cthread_self());
3608 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3617 Perl_set_context(void *t)
3620 PERL_ARGS_ASSERT_SET_CONTEXT;
3621 #if defined(USE_ITHREADS)
3622 # ifdef I_MACH_CTHREADS
3623 cthread_set_data(cthread_self(), t);
3625 if (pthread_setspecific(PL_thr_key, t))
3626 Perl_croak_nocontext("panic: pthread_setspecific");
3633 #endif /* !PERL_GET_CONTEXT_DEFINED */
3635 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3644 Perl_get_op_names(pTHX)
3646 PERL_UNUSED_CONTEXT;
3647 return (char **)PL_op_name;
3651 Perl_get_op_descs(pTHX)
3653 PERL_UNUSED_CONTEXT;
3654 return (char **)PL_op_desc;
3658 Perl_get_no_modify(pTHX)
3660 PERL_UNUSED_CONTEXT;
3661 return PL_no_modify;
3665 Perl_get_opargs(pTHX)
3667 PERL_UNUSED_CONTEXT;
3668 return (U32 *)PL_opargs;
3672 Perl_get_ppaddr(pTHX)
3675 PERL_UNUSED_CONTEXT;
3676 return (PPADDR_t*)PL_ppaddr;
3679 #ifndef HAS_GETENV_LEN
3681 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3683 char * const env_trans = PerlEnv_getenv(env_elem);
3684 PERL_UNUSED_CONTEXT;
3685 PERL_ARGS_ASSERT_GETENV_LEN;
3687 *len = strlen(env_trans);
3694 Perl_get_vtbl(pTHX_ int vtbl_id)
3696 const MGVTBL* result;
3697 PERL_UNUSED_CONTEXT;
3701 result = &PL_vtbl_sv;
3704 result = &PL_vtbl_env;
3706 case want_vtbl_envelem:
3707 result = &PL_vtbl_envelem;
3710 result = &PL_vtbl_sig;
3712 case want_vtbl_sigelem:
3713 result = &PL_vtbl_sigelem;
3715 case want_vtbl_pack:
3716 result = &PL_vtbl_pack;
3718 case want_vtbl_packelem:
3719 result = &PL_vtbl_packelem;
3721 case want_vtbl_dbline:
3722 result = &PL_vtbl_dbline;
3725 result = &PL_vtbl_isa;
3727 case want_vtbl_isaelem:
3728 result = &PL_vtbl_isaelem;
3730 case want_vtbl_arylen:
3731 result = &PL_vtbl_arylen;
3733 case want_vtbl_mglob:
3734 result = &PL_vtbl_mglob;
3736 case want_vtbl_nkeys:
3737 result = &PL_vtbl_nkeys;
3739 case want_vtbl_taint:
3740 result = &PL_vtbl_taint;
3742 case want_vtbl_substr:
3743 result = &PL_vtbl_substr;
3746 result = &PL_vtbl_vec;
3749 result = &PL_vtbl_pos;
3752 result = &PL_vtbl_bm;
3755 result = &PL_vtbl_fm;
3757 case want_vtbl_uvar:
3758 result = &PL_vtbl_uvar;
3760 case want_vtbl_defelem:
3761 result = &PL_vtbl_defelem;
3763 case want_vtbl_regexp:
3764 result = &PL_vtbl_regexp;
3766 case want_vtbl_regdata:
3767 result = &PL_vtbl_regdata;
3769 case want_vtbl_regdatum:
3770 result = &PL_vtbl_regdatum;
3772 #ifdef USE_LOCALE_COLLATE
3773 case want_vtbl_collxfrm:
3774 result = &PL_vtbl_collxfrm;
3777 case want_vtbl_amagic:
3778 result = &PL_vtbl_amagic;
3780 case want_vtbl_amagicelem:
3781 result = &PL_vtbl_amagicelem;
3783 case want_vtbl_backref:
3784 result = &PL_vtbl_backref;
3786 case want_vtbl_utf8:
3787 result = &PL_vtbl_utf8;
3793 return (MGVTBL*)result;
3797 Perl_my_fflush_all(pTHX)
3799 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3800 return PerlIO_flush(NULL);
3802 # if defined(HAS__FWALK)
3803 extern int fflush(FILE *);
3804 /* undocumented, unprototyped, but very useful BSDism */
3805 extern void _fwalk(int (*)(FILE *));
3809 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3811 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3812 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3814 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3815 open_max = sysconf(_SC_OPEN_MAX);
3818 open_max = FOPEN_MAX;
3821 open_max = OPEN_MAX;
3832 for (i = 0; i < open_max; i++)
3833 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3834 STDIO_STREAM_ARRAY[i]._file < open_max &&
3835 STDIO_STREAM_ARRAY[i]._flag)
3836 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3840 SETERRNO(EBADF,RMS_IFI);
3847 Perl_report_wrongway_fh(pTHX_ const GV *gv, char have)
3849 if (ckWARN(WARN_IO)) {
3850 const char * const name
3851 = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3852 const char * const direction = have == '>' ? "out" : "in";
3855 Perl_warner(aTHX_ packWARN(WARN_IO),
3856 "Filehandle %s opened only for %sput",
3859 Perl_warner(aTHX_ packWARN(WARN_IO),
3860 "Filehandle opened only for %sput", direction);
3865 Perl_report_evil_fh(pTHX_ const GV *gv)
3867 const IO *io = gv ? GvIO(gv) : NULL;
3868 const PERL_BITFIELD16 op = PL_op->op_type;
3872 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3874 warn_type = WARN_CLOSED;
3878 warn_type = WARN_UNOPENED;
3881 if (ckWARN(warn_type)) {
3882 const char * const name
3883 = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3884 const char * const pars =
3885 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3886 const char * const func =
3888 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3889 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3891 const char * const type =
3893 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3894 ? "socket" : "filehandle");
3895 if (name && *name) {
3896 Perl_warner(aTHX_ packWARN(warn_type),
3897 "%s%s on %s %s %s", func, pars, vile, type, name);
3898 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3900 aTHX_ packWARN(warn_type),
3901 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3906 Perl_warner(aTHX_ packWARN(warn_type),
3907 "%s%s on %s %s", func, pars, vile, type);
3908 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3910 aTHX_ packWARN(warn_type),
3911 "\t(Are you trying to call %s%s on dirhandle?)\n",
3918 /* XXX Add documentation after final interface and behavior is decided */
3919 /* May want to show context for error, so would pass Perl_bslash_c(pTHX_ const char* current, const char* start, const bool output_warning)
3920 U8 source = *current;
3922 May want to add eg, WARN_REGEX
3926 Perl_grok_bslash_c(pTHX_ const char source, const bool output_warning)
3931 if (! isASCII(source)) {
3932 Perl_croak(aTHX_ "Character following \"\\c\" must be ASCII");
3935 result = toCTRL(source);
3936 if (! isCNTRL(result)) {
3937 if (source == '{') {
3938 Perl_croak(aTHX_ "It is proposed that \"\\c{\" no longer be valid. It has historically evaluated to\n \";\". If you disagree with this proposal, send email to perl5-porters@perl.org\nOtherwise, or in the meantime, you can work around this failure by changing\n\"\\c{\" to \";\"");
3940 else if (output_warning) {
3943 if (! isALNUM(result)) {
3944 clearer[i++] = '\\';
3946 clearer[i++] = result;
3947 clearer[i++] = '\0';
3949 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
3950 "\"\\c%c\" more clearly written simply as \"%s\"",
3960 Perl_grok_bslash_o(pTHX_ const char *s,
3963 const char** error_msg,
3964 const bool output_warning)
3967 /* Documentation to be supplied when interface nailed down finally
3968 * This returns FALSE if there is an error which the caller need not recover
3969 * from; , otherwise TRUE. In either case the caller should look at *len
3971 * s points to a string that begins with 'o', and the previous character
3973 * uv points to a UV that will hold the output value, valid only if the
3974 * return from the function is TRUE
3975 * len on success will point to the next character in the string past the
3976 * end of this construct.
3977 * on failure, it will point to the failure
3978 * error_msg is a pointer that will be set to an internal buffer giving an
3979 * error message upon failure (the return is FALSE). Untouched if
3981 * output_warning says whether to output any warning messages, or suppress
3986 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3987 | PERL_SCAN_DISALLOW_PREFIX
3988 /* XXX Until the message is improved in grok_oct, handle errors
3990 | PERL_SCAN_SILENT_ILLDIGIT;
3992 PERL_ARGS_ASSERT_GROK_BSLASH_O;
3999 *len = 1; /* Move past the o */
4000 *error_msg = "Missing braces on \\o{}";
4006 *len = 2; /* Move past the o{ */
4007 *error_msg = "Missing right brace on \\o{";
4011 /* Return past the '}' no matter what is inside the braces */
4012 *len = e - s + 2; /* 2 = 1 for the o + 1 for the '}' */
4014 s++; /* Point to first digit */
4016 numbers_len = e - s;
4017 if (numbers_len == 0) {
4018 *error_msg = "Number with no digits";
4022 *uv = NATIVE_TO_UNI(grok_oct(s, &numbers_len, &flags, NULL));
4023 /* Note that if has non-octal, will ignore everything starting with that up
4026 if (output_warning && numbers_len != (STRLEN) (e - s)) {
4027 Perl_ck_warner(aTHX_ packWARN(WARN_DIGIT),
4028 /* diag_listed_as: Non-octal character '%c'. Resolved as "%s" */
4029 "Non-octal character '%c'. Resolved as \"\\o{%.*s}\"",
4038 /* To workaround core dumps from the uninitialised tm_zone we get the
4039 * system to give us a reasonable struct to copy. This fix means that
4040 * strftime uses the tm_zone and tm_gmtoff values returned by
4041 * localtime(time()). That should give the desired result most of the
4042 * time. But probably not always!
4044 * This does not address tzname aspects of NETaa14816.
4049 # ifndef STRUCT_TM_HASZONE
4050 # define STRUCT_TM_HASZONE
4054 #ifdef STRUCT_TM_HASZONE /* Backward compat */
4055 # ifndef HAS_TM_TM_ZONE
4056 # define HAS_TM_TM_ZONE
4061 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
4063 #ifdef HAS_TM_TM_ZONE
4065 const struct tm* my_tm;
4066 PERL_ARGS_ASSERT_INIT_TM;
4068 my_tm = localtime(&now);
4070 Copy(my_tm, ptm, 1, struct tm);
4072 PERL_ARGS_ASSERT_INIT_TM;
4073 PERL_UNUSED_ARG(ptm);
4078 * mini_mktime - normalise struct tm values without the localtime()
4079 * semantics (and overhead) of mktime().
4082 Perl_mini_mktime(pTHX_ struct tm *ptm)
4086 int month, mday, year, jday;
4087 int odd_cent, odd_year;
4088 PERL_UNUSED_CONTEXT;
4090 PERL_ARGS_ASSERT_MINI_MKTIME;
4092 #define DAYS_PER_YEAR 365
4093 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
4094 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
4095 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
4096 #define SECS_PER_HOUR (60*60)
4097 #define SECS_PER_DAY (24*SECS_PER_HOUR)
4098 /* parentheses deliberately absent on these two, otherwise they don't work */
4099 #define MONTH_TO_DAYS 153/5
4100 #define DAYS_TO_MONTH 5/153
4101 /* offset to bias by March (month 4) 1st between month/mday & year finding */
4102 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
4103 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
4104 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
4107 * Year/day algorithm notes:
4109 * With a suitable offset for numeric value of the month, one can find
4110 * an offset into the year by considering months to have 30.6 (153/5) days,
4111 * using integer arithmetic (i.e., with truncation). To avoid too much
4112 * messing about with leap days, we consider January and February to be
4113 * the 13th and 14th month of the previous year. After that transformation,
4114 * we need the month index we use to be high by 1 from 'normal human' usage,
4115 * so the month index values we use run from 4 through 15.
4117 * Given that, and the rules for the Gregorian calendar (leap years are those
4118 * divisible by 4 unless also divisible by 100, when they must be divisible
4119 * by 400 instead), we can simply calculate the number of days since some
4120 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
4121 * the days we derive from our month index, and adding in the day of the
4122 * month. The value used here is not adjusted for the actual origin which
4123 * it normally would use (1 January A.D. 1), since we're not exposing it.
4124 * We're only building the value so we can turn around and get the
4125 * normalised values for the year, month, day-of-month, and day-of-year.
4127 * For going backward, we need to bias the value we're using so that we find
4128 * the right year value. (Basically, we don't want the contribution of
4129 * March 1st to the number to apply while deriving the year). Having done
4130 * that, we 'count up' the contribution to the year number by accounting for
4131 * full quadracenturies (400-year periods) with their extra leap days, plus
4132 * the contribution from full centuries (to avoid counting in the lost leap
4133 * days), plus the contribution from full quad-years (to count in the normal
4134 * leap days), plus the leftover contribution from any non-leap years.
4135 * At this point, if we were working with an actual leap day, we'll have 0
4136 * days left over. This is also true for March 1st, however. So, we have
4137 * to special-case that result, and (earlier) keep track of the 'odd'
4138 * century and year contributions. If we got 4 extra centuries in a qcent,
4139 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
4140 * Otherwise, we add back in the earlier bias we removed (the 123 from
4141 * figuring in March 1st), find the month index (integer division by 30.6),
4142 * and the remainder is the day-of-month. We then have to convert back to
4143 * 'real' months (including fixing January and February from being 14/15 in
4144 * the previous year to being in the proper year). After that, to get
4145 * tm_yday, we work with the normalised year and get a new yearday value for
4146 * January 1st, which we subtract from the yearday value we had earlier,
4147 * representing the date we've re-built. This is done from January 1
4148 * because tm_yday is 0-origin.
4150 * Since POSIX time routines are only guaranteed to work for times since the
4151 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
4152 * applies Gregorian calendar rules even to dates before the 16th century
4153 * doesn't bother me. Besides, you'd need cultural context for a given
4154 * date to know whether it was Julian or Gregorian calendar, and that's
4155 * outside the scope for this routine. Since we convert back based on the
4156 * same rules we used to build the yearday, you'll only get strange results
4157 * for input which needed normalising, or for the 'odd' century years which
4158 * were leap years in the Julian calendar but not in the Gregorian one.
4159 * I can live with that.
4161 * This algorithm also fails to handle years before A.D. 1 gracefully, but
4162 * that's still outside the scope for POSIX time manipulation, so I don't
4166 year = 1900 + ptm->tm_year;
4167 month = ptm->tm_mon;
4168 mday = ptm->tm_mday;
4169 /* allow given yday with no month & mday to dominate the result */
4170 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
4173 jday = 1 + ptm->tm_yday;
4182 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4183 yearday += month*MONTH_TO_DAYS + mday + jday;
4185 * Note that we don't know when leap-seconds were or will be,
4186 * so we have to trust the user if we get something which looks
4187 * like a sensible leap-second. Wild values for seconds will
4188 * be rationalised, however.
4190 if ((unsigned) ptm->tm_sec <= 60) {
4197 secs += 60 * ptm->tm_min;
4198 secs += SECS_PER_HOUR * ptm->tm_hour;
4200 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4201 /* got negative remainder, but need positive time */
4202 /* back off an extra day to compensate */
4203 yearday += (secs/SECS_PER_DAY)-1;
4204 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4207 yearday += (secs/SECS_PER_DAY);
4208 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4211 else if (secs >= SECS_PER_DAY) {
4212 yearday += (secs/SECS_PER_DAY);
4213 secs %= SECS_PER_DAY;
4215 ptm->tm_hour = secs/SECS_PER_HOUR;
4216 secs %= SECS_PER_HOUR;
4217 ptm->tm_min = secs/60;
4219 ptm->tm_sec += secs;
4220 /* done with time of day effects */
4222 * The algorithm for yearday has (so far) left it high by 428.
4223 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4224 * bias it by 123 while trying to figure out what year it
4225 * really represents. Even with this tweak, the reverse
4226 * translation fails for years before A.D. 0001.
4227 * It would still fail for Feb 29, but we catch that one below.
4229 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
4230 yearday -= YEAR_ADJUST;
4231 year = (yearday / DAYS_PER_QCENT) * 400;
4232 yearday %= DAYS_PER_QCENT;
4233 odd_cent = yearday / DAYS_PER_CENT;
4234 year += odd_cent * 100;
4235 yearday %= DAYS_PER_CENT;
4236 year += (yearday / DAYS_PER_QYEAR) * 4;
4237 yearday %= DAYS_PER_QYEAR;
4238 odd_year = yearday / DAYS_PER_YEAR;
4240 yearday %= DAYS_PER_YEAR;
4241 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4246 yearday += YEAR_ADJUST; /* recover March 1st crock */
4247 month = yearday*DAYS_TO_MONTH;
4248 yearday -= month*MONTH_TO_DAYS;
4249 /* recover other leap-year adjustment */
4258 ptm->tm_year = year - 1900;
4260 ptm->tm_mday = yearday;
4261 ptm->tm_mon = month;
4265 ptm->tm_mon = month - 1;
4267 /* re-build yearday based on Jan 1 to get tm_yday */
4269 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4270 yearday += 14*MONTH_TO_DAYS + 1;
4271 ptm->tm_yday = jday - yearday;
4272 /* fix tm_wday if not overridden by caller */
4273 if ((unsigned)ptm->tm_wday > 6)
4274 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4278 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)
4286 PERL_ARGS_ASSERT_MY_STRFTIME;
4288 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4291 mytm.tm_hour = hour;
4292 mytm.tm_mday = mday;
4294 mytm.tm_year = year;
4295 mytm.tm_wday = wday;
4296 mytm.tm_yday = yday;
4297 mytm.tm_isdst = isdst;
4299 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4300 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4305 #ifdef HAS_TM_TM_GMTOFF
4306 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4308 #ifdef HAS_TM_TM_ZONE
4309 mytm.tm_zone = mytm2.tm_zone;
4314 Newx(buf, buflen, char);
4315 len = strftime(buf, buflen, fmt, &mytm);
4317 ** The following is needed to handle to the situation where
4318 ** tmpbuf overflows. Basically we want to allocate a buffer
4319 ** and try repeatedly. The reason why it is so complicated
4320 ** is that getting a return value of 0 from strftime can indicate
4321 ** one of the following:
4322 ** 1. buffer overflowed,
4323 ** 2. illegal conversion specifier, or
4324 ** 3. the format string specifies nothing to be returned(not
4325 ** an error). This could be because format is an empty string
4326 ** or it specifies %p that yields an empty string in some locale.
4327 ** If there is a better way to make it portable, go ahead by
4330 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4333 /* Possibly buf overflowed - try again with a bigger buf */
4334 const int fmtlen = strlen(fmt);
4335 int bufsize = fmtlen + buflen;
4337 Renew(buf, bufsize, char);
4339 buflen = strftime(buf, bufsize, fmt, &mytm);
4340 if (buflen > 0 && buflen < bufsize)
4342 /* heuristic to prevent out-of-memory errors */
4343 if (bufsize > 100*fmtlen) {
4349 Renew(buf, bufsize, char);
4354 Perl_croak(aTHX_ "panic: no strftime");
4360 #define SV_CWD_RETURN_UNDEF \
4361 sv_setsv(sv, &PL_sv_undef); \
4364 #define SV_CWD_ISDOT(dp) \
4365 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4366 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4369 =head1 Miscellaneous Functions
4371 =for apidoc getcwd_sv
4373 Fill the sv with current working directory
4378 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4379 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4380 * getcwd(3) if available
4381 * Comments from the orignal:
4382 * This is a faster version of getcwd. It's also more dangerous
4383 * because you might chdir out of a directory that you can't chdir
4387 Perl_getcwd_sv(pTHX_ register SV *sv)
4391 #ifndef INCOMPLETE_TAINTS
4395 PERL_ARGS_ASSERT_GETCWD_SV;
4399 char buf[MAXPATHLEN];
4401 /* Some getcwd()s automatically allocate a buffer of the given
4402 * size from the heap if they are given a NULL buffer pointer.
4403 * The problem is that this behaviour is not portable. */
4404 if (getcwd(buf, sizeof(buf) - 1)) {
4409 sv_setsv(sv, &PL_sv_undef);
4417 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4421 SvUPGRADE(sv, SVt_PV);
4423 if (PerlLIO_lstat(".", &statbuf) < 0) {
4424 SV_CWD_RETURN_UNDEF;
4427 orig_cdev = statbuf.st_dev;
4428 orig_cino = statbuf.st_ino;
4438 if (PerlDir_chdir("..") < 0) {
4439 SV_CWD_RETURN_UNDEF;
4441 if (PerlLIO_stat(".", &statbuf) < 0) {
4442 SV_CWD_RETURN_UNDEF;
4445 cdev = statbuf.st_dev;
4446 cino = statbuf.st_ino;
4448 if (odev == cdev && oino == cino) {
4451 if (!(dir = PerlDir_open("."))) {
4452 SV_CWD_RETURN_UNDEF;
4455 while ((dp = PerlDir_read(dir)) != NULL) {
4457 namelen = dp->d_namlen;
4459 namelen = strlen(dp->d_name);
4462 if (SV_CWD_ISDOT(dp)) {
4466 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4467 SV_CWD_RETURN_UNDEF;
4470 tdev = statbuf.st_dev;
4471 tino = statbuf.st_ino;
4472 if (tino == oino && tdev == odev) {
4478 SV_CWD_RETURN_UNDEF;
4481 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4482 SV_CWD_RETURN_UNDEF;
4485 SvGROW(sv, pathlen + namelen + 1);
4489 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4492 /* prepend current directory to the front */
4494 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4495 pathlen += (namelen + 1);
4497 #ifdef VOID_CLOSEDIR
4500 if (PerlDir_close(dir) < 0) {
4501 SV_CWD_RETURN_UNDEF;
4507 SvCUR_set(sv, pathlen);
4511 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4512 SV_CWD_RETURN_UNDEF;
4515 if (PerlLIO_stat(".", &statbuf) < 0) {
4516 SV_CWD_RETURN_UNDEF;
4519 cdev = statbuf.st_dev;
4520 cino = statbuf.st_ino;
4522 if (cdev != orig_cdev || cino != orig_cino) {
4523 Perl_croak(aTHX_ "Unstable directory path, "
4524 "current directory changed unexpectedly");
4535 #define VERSION_MAX 0x7FFFFFFF
4538 =for apidoc prescan_version
4540 Validate that a given string can be parsed as a version object, but doesn't
4541 actually perform the parsing. Can use either strict or lax validation rules.
4542 Can optionally set a number of hint variables to save the parsing code
4543 some time when tokenizing.
4548 Perl_prescan_version(pTHX_ const char *s, bool strict,
4549 const char **errstr,
4550 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4551 bool qv = (sqv ? *sqv : FALSE);
4553 int saw_decimal = 0;
4557 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4559 if (qv && isDIGIT(*d))
4560 goto dotted_decimal_version;
4562 if (*d == 'v') { /* explicit v-string */
4567 else { /* degenerate v-string */
4568 /* requires v1.2.3 */
4569 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4572 dotted_decimal_version:
4573 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4574 /* no leading zeros allowed */
4575 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4578 while (isDIGIT(*d)) /* integer part */
4584 d++; /* decimal point */
4589 /* require v1.2.3 */
4590 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4593 goto version_prescan_finish;
4600 while (isDIGIT(*d)) { /* just keep reading */
4602 while (isDIGIT(*d)) {
4604 /* maximum 3 digits between decimal */
4605 if (strict && j > 3) {
4606 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4611 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4614 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4619 else if (*d == '.') {
4621 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4626 else if (!isDIGIT(*d)) {
4632 if (strict && i < 2) {
4633 /* requires v1.2.3 */
4634 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4637 } /* end if dotted-decimal */
4639 { /* decimal versions */
4640 /* special strict case for leading '.' or '0' */
4643 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4645 if (*d == '0' && isDIGIT(d[1])) {
4646 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4650 /* consume all of the integer part */
4654 /* look for a fractional part */
4656 /* we found it, so consume it */
4660 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4663 BADVERSION(s,errstr,"Invalid version format (version required)");
4665 /* found just an integer */
4666 goto version_prescan_finish;
4668 else if ( d == s ) {
4669 /* didn't find either integer or period */
4670 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4672 else if (*d == '_') {
4673 /* underscore can't come after integer part */
4675 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4677 else if (isDIGIT(d[1])) {
4678 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4681 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4685 /* anything else after integer part is just invalid data */
4686 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4689 /* scan the fractional part after the decimal point*/
4691 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4692 /* strict or lax-but-not-the-end */
4693 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4696 while (isDIGIT(*d)) {
4698 if (*d == '.' && isDIGIT(d[-1])) {
4700 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4703 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4705 d = (char *)s; /* start all over again */
4707 goto dotted_decimal_version;
4711 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4714 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4716 if ( ! isDIGIT(d[1]) ) {
4717 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4725 version_prescan_finish:
4729 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4730 /* trailing non-numeric data */
4731 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4739 *ssaw_decimal = saw_decimal;
4746 =for apidoc scan_version
4748 Returns a pointer to the next character after the parsed
4749 version string, as well as upgrading the passed in SV to
4752 Function must be called with an already existing SV like
4755 s = scan_version(s, SV *sv, bool qv);
4757 Performs some preprocessing to the string to ensure that
4758 it has the correct characteristics of a version. Flags the
4759 object if it contains an underscore (which denotes this
4760 is an alpha version). The boolean qv denotes that the version
4761 should be interpreted as if it had multiple decimals, even if
4768 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4773 const char *errstr = NULL;
4774 int saw_decimal = 0;
4778 AV * const av = newAV();
4779 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4781 PERL_ARGS_ASSERT_SCAN_VERSION;
4783 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4785 #ifndef NODEFAULT_SHAREKEYS
4786 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4789 while (isSPACE(*s)) /* leading whitespace is OK */
4792 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4794 /* "undef" is a special case and not an error */
4795 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4796 Perl_croak(aTHX_ "%s", errstr);
4806 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4808 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4809 if ( !qv && width < 3 )
4810 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4812 while (isDIGIT(*pos))
4814 if (!isALPHA(*pos)) {
4820 /* this is atoi() that delimits on underscores */
4821 const char *end = pos;
4825 /* the following if() will only be true after the decimal
4826 * point of a version originally created with a bare
4827 * floating point number, i.e. not quoted in any way
4829 if ( !qv && s > start && saw_decimal == 1 ) {
4833 rev += (*s - '0') * mult;
4835 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4836 || (PERL_ABS(rev) > VERSION_MAX )) {
4837 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4838 "Integer overflow in version %d",VERSION_MAX);
4849 while (--end >= s) {
4851 rev += (*end - '0') * mult;
4853 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4854 || (PERL_ABS(rev) > VERSION_MAX )) {
4855 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4856 "Integer overflow in version");
4865 /* Append revision */
4866 av_push(av, newSViv(rev));
4871 else if ( *pos == '.' )
4873 else if ( *pos == '_' && isDIGIT(pos[1]) )
4875 else if ( *pos == ',' && isDIGIT(pos[1]) )
4877 else if ( isDIGIT(*pos) )
4884 while ( isDIGIT(*pos) )
4889 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4897 if ( qv ) { /* quoted versions always get at least three terms*/
4898 I32 len = av_len(av);
4899 /* This for loop appears to trigger a compiler bug on OS X, as it
4900 loops infinitely. Yes, len is negative. No, it makes no sense.
4901 Compiler in question is:
4902 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4903 for ( len = 2 - len; len > 0; len-- )
4904 av_push(MUTABLE_AV(sv), newSViv(0));
4908 av_push(av, newSViv(0));
4911 /* need to save off the current version string for later */
4913 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4914 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4915 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4917 else if ( s > start ) {
4918 SV * orig = newSVpvn(start,s-start);
4919 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4920 /* need to insert a v to be consistent */
4921 sv_insert(orig, 0, 0, "v", 1);
4923 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4926 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4927 av_push(av, newSViv(0));
4930 /* And finally, store the AV in the hash */
4931 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4933 /* fix RT#19517 - special case 'undef' as string */
4934 if ( *s == 'u' && strEQ(s,"undef") ) {
4942 =for apidoc new_version
4944 Returns a new version object based on the passed in SV:
4946 SV *sv = new_version(SV *ver);
4948 Does not alter the passed in ver SV. See "upg_version" if you
4949 want to upgrade the SV.
4955 Perl_new_version(pTHX_ SV *ver)
4958 SV * const rv = newSV(0);
4959 PERL_ARGS_ASSERT_NEW_VERSION;
4960 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4963 AV * const av = newAV();
4965 /* This will get reblessed later if a derived class*/
4966 SV * const hv = newSVrv(rv, "version");
4967 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4968 #ifndef NODEFAULT_SHAREKEYS
4969 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4975 /* Begin copying all of the elements */
4976 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4977 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4979 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4980 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4982 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4984 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4985 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4988 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4990 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4991 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4994 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4995 /* This will get reblessed later if a derived class*/
4996 for ( key = 0; key <= av_len(sav); key++ )
4998 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4999 av_push(av, newSViv(rev));
5002 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
5007 const MAGIC* const mg = SvVSTRING_mg(ver);
5008 if ( mg ) { /* already a v-string */
5009 const STRLEN len = mg->mg_len;
5010 char * const version = savepvn( (const char*)mg->mg_ptr, len);
5011 sv_setpvn(rv,version,len);
5012 /* this is for consistency with the pure Perl class */
5013 if ( isDIGIT(*version) )
5014 sv_insert(rv, 0, 0, "v", 1);
5019 sv_setsv(rv,ver); /* make a duplicate */
5024 return upg_version(rv, FALSE);
5028 =for apidoc upg_version