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 /* paranoid version of system's malloc() */
76 Perl_safesysmalloc(MEM_SIZE size)
82 PerlIO_printf(Perl_error_log,
83 "Allocation too large: %lx\n", size) FLUSH;
86 #endif /* HAS_64K_LIMIT */
87 #ifdef PERL_TRACK_MEMPOOL
92 Perl_croak_nocontext("panic: malloc");
94 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
95 PERL_ALLOC_CHECK(ptr);
96 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
98 #ifdef PERL_TRACK_MEMPOOL
99 struct perl_memory_debug_header *const header
100 = (struct perl_memory_debug_header *)ptr;
104 PoisonNew(((char *)ptr), size, char);
107 #ifdef PERL_TRACK_MEMPOOL
108 header->interpreter = aTHX;
109 /* Link us into the list. */
110 header->prev = &PL_memory_debug_header;
111 header->next = PL_memory_debug_header.next;
112 PL_memory_debug_header.next = header;
113 header->next->prev = header;
117 ptr = (Malloc_t)((char*)ptr+sTHX);
124 return write_no_mem();
129 /* paranoid version of system's realloc() */
132 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
136 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
137 Malloc_t PerlMem_realloc();
138 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
142 PerlIO_printf(Perl_error_log,
143 "Reallocation too large: %lx\n", size) FLUSH;
146 #endif /* HAS_64K_LIMIT */
153 return safesysmalloc(size);
154 #ifdef PERL_TRACK_MEMPOOL
155 where = (Malloc_t)((char*)where-sTHX);
158 struct perl_memory_debug_header *const header
159 = (struct perl_memory_debug_header *)where;
161 if (header->interpreter != aTHX) {
162 Perl_croak_nocontext("panic: realloc from wrong pool");
164 assert(header->next->prev == header);
165 assert(header->prev->next == header);
167 if (header->size > size) {
168 const MEM_SIZE freed_up = header->size - size;
169 char *start_of_freed = ((char *)where) + size;
170 PoisonFree(start_of_freed, freed_up, char);
178 Perl_croak_nocontext("panic: realloc");
180 ptr = (Malloc_t)PerlMem_realloc(where,size);
181 PERL_ALLOC_CHECK(ptr);
183 /* MUST do this fixup first, before doing ANYTHING else, as anything else
184 might allocate memory/free/move memory, and until we do the fixup, it
185 may well be chasing (and writing to) free memory. */
186 #ifdef PERL_TRACK_MEMPOOL
188 struct perl_memory_debug_header *const header
189 = (struct perl_memory_debug_header *)ptr;
192 if (header->size < size) {
193 const MEM_SIZE fresh = size - header->size;
194 char *start_of_fresh = ((char *)ptr) + size;
195 PoisonNew(start_of_fresh, fresh, char);
199 header->next->prev = header;
200 header->prev->next = header;
202 ptr = (Malloc_t)((char*)ptr+sTHX);
206 /* In particular, must do that fixup above before logging anything via
207 *printf(), as it can reallocate memory, which can cause SEGVs. */
209 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
210 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
219 return write_no_mem();
224 /* safe version of system's free() */
227 Perl_safesysfree(Malloc_t where)
229 #if defined(PERL_IMPLICIT_SYS) || defined(PERL_TRACK_MEMPOOL)
234 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
236 #ifdef PERL_TRACK_MEMPOOL
237 where = (Malloc_t)((char*)where-sTHX);
239 struct perl_memory_debug_header *const header
240 = (struct perl_memory_debug_header *)where;
242 if (header->interpreter != aTHX) {
243 Perl_croak_nocontext("panic: free from wrong pool");
246 Perl_croak_nocontext("panic: duplicate free");
248 if (!(header->next) || header->next->prev != header
249 || header->prev->next != header) {
250 Perl_croak_nocontext("panic: bad free");
252 /* Unlink us from the chain. */
253 header->next->prev = header->prev;
254 header->prev->next = header->next;
256 PoisonNew(where, header->size, char);
258 /* Trigger the duplicate free warning. */
266 /* safe version of system's calloc() */
269 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
273 MEM_SIZE total_size = 0;
275 /* Even though calloc() for zero bytes is strange, be robust. */
276 if (size && (count <= MEM_SIZE_MAX / size))
277 total_size = size * count;
279 Perl_croak_nocontext("%s", PL_memory_wrap);
280 #ifdef PERL_TRACK_MEMPOOL
281 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
284 Perl_croak_nocontext("%s", PL_memory_wrap);
287 if (total_size > 0xffff) {
288 PerlIO_printf(Perl_error_log,
289 "Allocation too large: %lx\n", total_size) FLUSH;
292 #endif /* HAS_64K_LIMIT */
294 if ((long)size < 0 || (long)count < 0)
295 Perl_croak_nocontext("panic: calloc");
297 #ifdef PERL_TRACK_MEMPOOL
298 /* Have to use malloc() because we've added some space for our tracking
300 /* malloc(0) is non-portable. */
301 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
303 /* Use calloc() because it might save a memset() if the memory is fresh
304 and clean from the OS. */
306 ptr = (Malloc_t)PerlMem_calloc(count, size);
307 else /* calloc(0) is non-portable. */
308 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
310 PERL_ALLOC_CHECK(ptr);
311 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));
313 #ifdef PERL_TRACK_MEMPOOL
315 struct perl_memory_debug_header *const header
316 = (struct perl_memory_debug_header *)ptr;
318 memset((void*)ptr, 0, total_size);
319 header->interpreter = aTHX;
320 /* Link us into the list. */
321 header->prev = &PL_memory_debug_header;
322 header->next = PL_memory_debug_header.next;
323 PL_memory_debug_header.next = header;
324 header->next->prev = header;
326 header->size = total_size;
328 ptr = (Malloc_t)((char*)ptr+sTHX);
335 return write_no_mem();
338 /* These must be defined when not using Perl's malloc for binary
343 Malloc_t Perl_malloc (MEM_SIZE nbytes)
346 return (Malloc_t)PerlMem_malloc(nbytes);
349 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
352 return (Malloc_t)PerlMem_calloc(elements, size);
355 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
358 return (Malloc_t)PerlMem_realloc(where, nbytes);
361 Free_t Perl_mfree (Malloc_t where)
369 /* copy a string up to some (non-backslashed) delimiter, if any */
372 Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
376 PERL_ARGS_ASSERT_DELIMCPY;
378 for (tolen = 0; from < fromend; from++, tolen++) {
380 if (from[1] != delim) {
387 else if (*from == delim)
398 /* return ptr to little string in big string, NULL if not found */
399 /* This routine was donated by Corey Satten. */
402 Perl_instr(register const char *big, register const char *little)
406 PERL_ARGS_ASSERT_INSTR;
414 register const char *s, *x;
417 for (x=big,s=little; *s; /**/ ) {
428 return (char*)(big-1);
433 /* same as instr but allow embedded nulls */
436 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
438 PERL_ARGS_ASSERT_NINSTR;
442 const char first = *little;
444 bigend -= lend - little++;
446 while (big <= bigend) {
447 if (*big++ == first) {
448 for (x=big,s=little; s < lend; x++,s++) {
452 return (char*)(big-1);
459 /* reverse of the above--find last substring */
462 Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
464 register const char *bigbeg;
465 register const I32 first = *little;
466 register const char * const littleend = lend;
468 PERL_ARGS_ASSERT_RNINSTR;
470 if (little >= littleend)
471 return (char*)bigend;
473 big = bigend - (littleend - little++);
474 while (big >= bigbeg) {
475 register const char *s, *x;
478 for (x=big+2,s=little; s < littleend; /**/ ) {
487 return (char*)(big+1);
492 /* As a space optimization, we do not compile tables for strings of length
493 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
494 special-cased in fbm_instr().
496 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
499 =head1 Miscellaneous Functions
501 =for apidoc fbm_compile
503 Analyses the string in order to make fast searches on it using fbm_instr()
504 -- the Boyer-Moore algorithm.
510 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
513 register const U8 *s;
519 PERL_ARGS_ASSERT_FBM_COMPILE;
521 if (flags & FBMcf_TAIL) {
522 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
523 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
524 if (mg && mg->mg_len >= 0)
527 s = (U8*)SvPV_force_mutable(sv, len);
528 if (len == 0) /* TAIL might be on a zero-length string. */
530 SvUPGRADE(sv, SVt_PVGV);
535 const unsigned char *sb;
536 const U8 mlen = (len>255) ? 255 : (U8)len;
539 Sv_Grow(sv, len + 256 + PERL_FBM_TABLE_OFFSET);
541 = (unsigned char*)(SvPVX_mutable(sv) + len + PERL_FBM_TABLE_OFFSET);
542 s = table - 1 - PERL_FBM_TABLE_OFFSET; /* last char */
543 memset((void*)table, mlen, 256);
545 sb = s - mlen + 1; /* first char (maybe) */
547 if (table[*s] == mlen)
552 Sv_Grow(sv, len + PERL_FBM_TABLE_OFFSET);
554 sv_magic(sv, NULL, PERL_MAGIC_bm, NULL, 0); /* deep magic */
556 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
557 for (i = 0; i < len; i++) {
558 if (PL_freq[s[i]] < frequency) {
560 frequency = PL_freq[s[i]];
563 BmFLAGS(sv) = (U8)flags;
564 BmRARE(sv) = s[rarest];
565 BmPREVIOUS(sv) = rarest;
566 BmUSEFUL(sv) = 100; /* Initial value */
567 if (flags & FBMcf_TAIL)
569 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %lu\n",
570 BmRARE(sv),(unsigned long)BmPREVIOUS(sv)));
573 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
574 /* If SvTAIL is actually due to \Z or \z, this gives false positives
578 =for apidoc fbm_instr
580 Returns the location of the SV in the string delimited by C<str> and
581 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
582 does not have to be fbm_compiled, but the search will not be as fast
589 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
591 register unsigned char *s;
593 register const unsigned char *little
594 = (const unsigned char *)SvPV_const(littlestr,l);
595 register STRLEN littlelen = l;
596 register const I32 multiline = flags & FBMrf_MULTILINE;
598 PERL_ARGS_ASSERT_FBM_INSTR;
600 if ((STRLEN)(bigend - big) < littlelen) {
601 if ( SvTAIL(littlestr)
602 && ((STRLEN)(bigend - big) == littlelen - 1)
604 || (*big == *little &&
605 memEQ((char *)big, (char *)little, littlelen - 1))))
610 if (littlelen <= 2) { /* Special-cased */
612 if (littlelen == 1) {
613 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
614 /* Know that bigend != big. */
615 if (bigend[-1] == '\n')
616 return (char *)(bigend - 1);
617 return (char *) bigend;
625 if (SvTAIL(littlestr))
626 return (char *) bigend;
630 return (char*)big; /* Cannot be SvTAIL! */
633 if (SvTAIL(littlestr) && !multiline) {
634 if (bigend[-1] == '\n' && bigend[-2] == *little)
635 return (char*)bigend - 2;
636 if (bigend[-1] == *little)
637 return (char*)bigend - 1;
641 /* This should be better than FBM if c1 == c2, and almost
642 as good otherwise: maybe better since we do less indirection.
643 And we save a lot of memory by caching no table. */
644 const unsigned char c1 = little[0];
645 const unsigned char c2 = little[1];
650 while (s <= bigend) {
660 goto check_1char_anchor;
671 goto check_1char_anchor;
674 while (s <= bigend) {
679 goto check_1char_anchor;
688 check_1char_anchor: /* One char and anchor! */
689 if (SvTAIL(littlestr) && (*bigend == *little))
690 return (char *)bigend; /* bigend is already decremented. */
693 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
694 s = bigend - littlelen;
695 if (s >= big && bigend[-1] == '\n' && *s == *little
696 /* Automatically of length > 2 */
697 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
699 return (char*)s; /* how sweet it is */
702 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
704 return (char*)s + 1; /* how sweet it is */
708 if (!SvVALID(littlestr)) {
709 char * const b = ninstr((char*)big,(char*)bigend,
710 (char*)little, (char*)little + littlelen);
712 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
713 /* Chop \n from littlestr: */
714 s = bigend - littlelen + 1;
716 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
726 if (littlelen > (STRLEN)(bigend - big))
730 register const unsigned char * const table
731 = little + littlelen + PERL_FBM_TABLE_OFFSET;
732 register const unsigned char *oldlittle;
734 --littlelen; /* Last char found by table lookup */
737 little += littlelen; /* last char */
743 if ((tmp = table[*s])) {
744 if ((s += tmp) < bigend)
748 else { /* less expensive than calling strncmp() */
749 register unsigned char * const olds = s;
754 if (*--s == *--little)
756 s = olds + 1; /* here we pay the price for failure */
758 if (s < bigend) /* fake up continue to outer loop */
767 && (BmFLAGS(littlestr) & FBMcf_TAIL)
768 && memEQ((char *)(bigend - littlelen),
769 (char *)(oldlittle - littlelen), littlelen) )
770 return (char*)bigend - littlelen;
775 /* start_shift, end_shift are positive quantities which give offsets
776 of ends of some substring of bigstr.
777 If "last" we want the last occurrence.
778 old_posp is the way of communication between consequent calls if
779 the next call needs to find the .
780 The initial *old_posp should be -1.
782 Note that we take into account SvTAIL, so one can get extra
783 optimizations if _ALL flag is set.
786 /* If SvTAIL is actually due to \Z or \z, this gives false positives
787 if PL_multiline. In fact if !PL_multiline the authoritative answer
788 is not supported yet. */
791 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
794 register const unsigned char *big;
796 register I32 previous;
798 register const unsigned char *little;
799 register I32 stop_pos;
800 register const unsigned char *littleend;
803 PERL_ARGS_ASSERT_SCREAMINSTR;
805 assert(SvTYPE(littlestr) == SVt_PVGV);
806 assert(SvVALID(littlestr));
809 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
810 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
812 if ( BmRARE(littlestr) == '\n'
813 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
814 little = (const unsigned char *)(SvPVX_const(littlestr));
815 littleend = little + SvCUR(littlestr);
822 little = (const unsigned char *)(SvPVX_const(littlestr));
823 littleend = little + SvCUR(littlestr);
825 /* The value of pos we can start at: */
826 previous = BmPREVIOUS(littlestr);
827 big = (const unsigned char *)(SvPVX_const(bigstr));
828 /* The value of pos we can stop at: */
829 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
830 if (previous + start_shift > stop_pos) {
832 stop_pos does not include SvTAIL in the count, so this check is incorrect
833 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
836 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
841 while (pos < previous + start_shift) {
842 if (!(pos += PL_screamnext[pos]))
847 register const unsigned char *s, *x;
848 if (pos >= stop_pos) break;
849 if (big[pos] != first)
851 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
857 if (s == littleend) {
859 if (!last) return (char *)(big+pos);
862 } while ( pos += PL_screamnext[pos] );
864 return (char *)(big+(*old_posp));
866 if (!SvTAIL(littlestr) || (end_shift > 0))
868 /* Ignore the trailing "\n". This code is not microoptimized */
869 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
870 stop_pos = littleend - little; /* Actual littlestr len */
875 && ((stop_pos == 1) ||
876 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
882 Perl_ibcmp(const char *s1, const char *s2, register I32 len)
884 register const U8 *a = (const U8 *)s1;
885 register const U8 *b = (const U8 *)s2;
887 PERL_ARGS_ASSERT_IBCMP;
890 if (*a != *b && *a != PL_fold[*b])
898 Perl_ibcmp_locale(const char *s1, const char *s2, register I32 len)
901 register const U8 *a = (const U8 *)s1;
902 register const U8 *b = (const U8 *)s2;
904 PERL_ARGS_ASSERT_IBCMP_LOCALE;
907 if (*a != *b && *a != PL_fold_locale[*b])
914 /* copy a string to a safe spot */
917 =head1 Memory Management
921 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
922 string which is a duplicate of C<pv>. The size of the string is
923 determined by C<strlen()>. The memory allocated for the new string can
924 be freed with the C<Safefree()> function.
930 Perl_savepv(pTHX_ const char *pv)
937 const STRLEN pvlen = strlen(pv)+1;
938 Newx(newaddr, pvlen, char);
939 return (char*)memcpy(newaddr, pv, pvlen);
943 /* same thing but with a known length */
948 Perl's version of what C<strndup()> would be if it existed. Returns a
949 pointer to a newly allocated string which is a duplicate of the first
950 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
951 the new string can be freed with the C<Safefree()> function.
957 Perl_savepvn(pTHX_ const char *pv, register I32 len)
959 register char *newaddr;
962 Newx(newaddr,len+1,char);
963 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
965 /* might not be null terminated */
967 return (char *) CopyD(pv,newaddr,len,char);
970 return (char *) ZeroD(newaddr,len+1,char);
975 =for apidoc savesharedpv
977 A version of C<savepv()> which allocates the duplicate string in memory
978 which is shared between threads.
983 Perl_savesharedpv(pTHX_ const char *pv)
985 register char *newaddr;
990 pvlen = strlen(pv)+1;
991 newaddr = (char*)PerlMemShared_malloc(pvlen);
993 return write_no_mem();
995 return (char*)memcpy(newaddr, pv, pvlen);
999 =for apidoc savesharedpvn
1001 A version of C<savepvn()> which allocates the duplicate string in memory
1002 which is shared between threads. (With the specific difference that a NULL
1003 pointer is not acceptable)
1008 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1010 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1012 PERL_ARGS_ASSERT_SAVESHAREDPVN;
1015 return write_no_mem();
1017 newaddr[len] = '\0';
1018 return (char*)memcpy(newaddr, pv, len);
1022 =for apidoc savesvpv
1024 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1025 the passed in SV using C<SvPV()>
1031 Perl_savesvpv(pTHX_ SV *sv)
1034 const char * const pv = SvPV_const(sv, len);
1035 register char *newaddr;
1037 PERL_ARGS_ASSERT_SAVESVPV;
1040 Newx(newaddr,len,char);
1041 return (char *) CopyD(pv,newaddr,len,char);
1045 /* the SV for Perl_form() and mess() is not kept in an arena */
1055 return newSVpvs_flags("", SVs_TEMP);
1060 /* Create as PVMG now, to avoid any upgrading later */
1062 Newxz(any, 1, XPVMG);
1063 SvFLAGS(sv) = SVt_PVMG;
1064 SvANY(sv) = (void*)any;
1066 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1071 #if defined(PERL_IMPLICIT_CONTEXT)
1073 Perl_form_nocontext(const char* pat, ...)
1078 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1079 va_start(args, pat);
1080 retval = vform(pat, &args);
1084 #endif /* PERL_IMPLICIT_CONTEXT */
1087 =head1 Miscellaneous Functions
1090 Takes a sprintf-style format pattern and conventional
1091 (non-SV) arguments and returns the formatted string.
1093 (char *) Perl_form(pTHX_ const char* pat, ...)
1095 can be used any place a string (char *) is required:
1097 char * s = Perl_form("%d.%d",major,minor);
1099 Uses a single private buffer so if you want to format several strings you
1100 must explicitly copy the earlier strings away (and free the copies when you
1107 Perl_form(pTHX_ const char* pat, ...)
1111 PERL_ARGS_ASSERT_FORM;
1112 va_start(args, pat);
1113 retval = vform(pat, &args);
1119 Perl_vform(pTHX_ const char *pat, va_list *args)
1121 SV * const sv = mess_alloc();
1122 PERL_ARGS_ASSERT_VFORM;
1123 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1128 =for apidoc Am|SV *|mess|const char *pat|...
1130 Take a sprintf-style format pattern and argument list. These are used to
1131 generate a string message. If the message does not end with a newline,
1132 then it will be extended with some indication of the current location
1133 in the code, as described for L</mess_sv>.
1135 Normally, the resulting message is returned in a new mortal SV.
1136 During global destruction a single SV may be shared between uses of
1142 #if defined(PERL_IMPLICIT_CONTEXT)
1144 Perl_mess_nocontext(const char *pat, ...)
1149 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1150 va_start(args, pat);
1151 retval = vmess(pat, &args);
1155 #endif /* PERL_IMPLICIT_CONTEXT */
1158 Perl_mess(pTHX_ const char *pat, ...)
1162 PERL_ARGS_ASSERT_MESS;
1163 va_start(args, pat);
1164 retval = vmess(pat, &args);
1170 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1173 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1175 PERL_ARGS_ASSERT_CLOSEST_COP;
1177 if (!o || o == PL_op)
1180 if (o->op_flags & OPf_KIDS) {
1182 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1185 /* If the OP_NEXTSTATE has been optimised away we can still use it
1186 * the get the file and line number. */
1188 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1189 cop = (const COP *)kid;
1191 /* Keep searching, and return when we've found something. */
1193 new_cop = closest_cop(cop, kid);
1199 /* Nothing found. */
1205 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1207 Expands a message, intended for the user, to include an indication of
1208 the current location in the code, if the message does not already appear
1211 C<basemsg> is the initial message or object. If it is a reference, it
1212 will be used as-is and will be the result of this function. Otherwise it
1213 is used as a string, and if it already ends with a newline, it is taken
1214 to be complete, and the result of this function will be the same string.
1215 If the message does not end with a newline, then a segment such as C<at
1216 foo.pl line 37> will be appended, and possibly other clauses indicating
1217 the current state of execution. The resulting message will end with a
1220 Normally, the resulting message is returned in a new mortal SV.
1221 During global destruction a single SV may be shared between uses of this
1222 function. If C<consume> is true, then the function is permitted (but not
1223 required) to modify and return C<basemsg> instead of allocating a new SV.
1229 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1234 PERL_ARGS_ASSERT_MESS_SV;
1236 if (SvROK(basemsg)) {
1242 sv_setsv(sv, basemsg);
1247 if (SvPOK(basemsg) && consume) {
1252 sv_copypv(sv, basemsg);
1255 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1257 * Try and find the file and line for PL_op. This will usually be
1258 * PL_curcop, but it might be a cop that has been optimised away. We
1259 * can try to find such a cop by searching through the optree starting
1260 * from the sibling of PL_curcop.
1263 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1268 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1269 OutCopFILE(cop), (IV)CopLINE(cop));
1270 /* Seems that GvIO() can be untrustworthy during global destruction. */
1271 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1272 && IoLINES(GvIOp(PL_last_in_gv)))
1274 const bool line_mode = (RsSIMPLE(PL_rs) &&
1275 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1276 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1277 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1278 line_mode ? "line" : "chunk",
1279 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1282 sv_catpvs(sv, " during global destruction");
1283 sv_catpvs(sv, ".\n");
1289 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1291 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1292 argument list. These are used to generate a string message. If the
1293 message does not end with a newline, then it will be extended with
1294 some indication of the current location in the code, as described for
1297 Normally, the resulting message is returned in a new mortal SV.
1298 During global destruction a single SV may be shared between uses of
1305 Perl_vmess(pTHX_ const char *pat, va_list *args)
1308 SV * const sv = mess_alloc();
1310 PERL_ARGS_ASSERT_VMESS;
1312 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1313 return mess_sv(sv, 1);
1317 Perl_write_to_stderr(pTHX_ SV* msv)
1323 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1325 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1326 && (io = GvIO(PL_stderrgv))
1327 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1334 SAVESPTR(PL_stderrgv);
1337 PUSHSTACKi(PERLSI_MAGIC);
1341 PUSHs(SvTIED_obj(MUTABLE_SV(io), mg));
1344 call_method("PRINT", G_SCALAR);
1352 /* SFIO can really mess with your errno */
1355 PerlIO * const serr = Perl_error_log;
1357 const char* message = SvPVx_const(msv, msglen);
1359 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1360 (void)PerlIO_flush(serr);
1368 =head1 Warning and Dieing
1371 /* Common code used in dieing and warning */
1374 S_with_queued_errors(pTHX_ SV *ex)
1376 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1377 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1378 sv_catsv(PL_errors, ex);
1379 ex = sv_mortalcopy(PL_errors);
1380 SvCUR_set(PL_errors, 0);
1386 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1392 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1393 /* sv_2cv might call Perl_croak() or Perl_warner() */
1394 SV * const oldhook = *hook;
1402 cv = sv_2cv(oldhook, &stash, &gv, 0);
1404 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1414 exarg = newSVsv(ex);
1415 SvREADONLY_on(exarg);
1418 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1422 call_sv(MUTABLE_SV(cv), G_DISCARD);
1431 =for apidoc Am|OP *|die_sv|SV *baseex
1433 Behaves the same as L</croak_sv>, except for the return type.
1434 It should be used only where the C<OP *> return type is required.
1435 The function never actually returns.
1441 Perl_die_sv(pTHX_ SV *baseex)
1443 PERL_ARGS_ASSERT_DIE_SV;
1450 =for apidoc Am|OP *|die|const char *pat|...
1452 Behaves the same as L</croak>, except for the return type.
1453 It should be used only where the C<OP *> return type is required.
1454 The function never actually returns.
1459 #if defined(PERL_IMPLICIT_CONTEXT)
1461 Perl_die_nocontext(const char* pat, ...)
1465 va_start(args, pat);
1471 #endif /* PERL_IMPLICIT_CONTEXT */
1474 Perl_die(pTHX_ const char* pat, ...)
1477 va_start(args, pat);
1485 =for apidoc Am|void|croak_sv|SV *baseex
1487 This is an XS interface to Perl's C<die> function.
1489 C<baseex> is the error message or object. If it is a reference, it
1490 will be used as-is. Otherwise it is used as a string, and if it does
1491 not end with a newline then it will be extended with some indication of
1492 the current location in the code, as described for L</mess_sv>.
1494 The error message or object will be used as an exception, by default
1495 returning control to the nearest enclosing C<eval>, but subject to
1496 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1497 function never returns normally.
1499 To die with a simple string message, the L</croak> function may be
1506 Perl_croak_sv(pTHX_ SV *baseex)
1508 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1509 PERL_ARGS_ASSERT_CROAK_SV;
1510 invoke_exception_hook(ex, FALSE);
1515 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1517 This is an XS interface to Perl's C<die> function.
1519 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1520 argument list. These are used to generate a string message. If the
1521 message does not end with a newline, then it will be extended with
1522 some indication of the current location in the code, as described for
1525 The error message will be used as an exception, by default
1526 returning control to the nearest enclosing C<eval>, but subject to
1527 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1528 function never returns normally.
1530 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1531 (C<$@>) will be used as an error message or object instead of building an
1532 error message from arguments. If you want to throw a non-string object,
1533 or build an error message in an SV yourself, it is preferable to use
1534 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1540 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1542 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1543 invoke_exception_hook(ex, FALSE);
1548 =for apidoc Am|void|croak|const char *pat|...
1550 This is an XS interface to Perl's C<die> function.
1552 Take a sprintf-style format pattern and argument list. These are used to
1553 generate a string message. If the message does not end with a newline,
1554 then it will be extended with some indication of the current location
1555 in the code, as described for L</mess_sv>.
1557 The error message will be used as an exception, by default
1558 returning control to the nearest enclosing C<eval>, but subject to
1559 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1560 function never returns normally.
1562 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1563 (C<$@>) will be used as an error message or object instead of building an
1564 error message from arguments. If you want to throw a non-string object,
1565 or build an error message in an SV yourself, it is preferable to use
1566 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1571 #if defined(PERL_IMPLICIT_CONTEXT)
1573 Perl_croak_nocontext(const char *pat, ...)
1577 va_start(args, pat);
1582 #endif /* PERL_IMPLICIT_CONTEXT */
1585 Perl_croak(pTHX_ const char *pat, ...)
1588 va_start(args, pat);
1595 =for apidoc Am|void|warn_sv|SV *baseex
1597 This is an XS interface to Perl's C<warn> function.
1599 C<baseex> is the error message or object. If it is a reference, it
1600 will be used as-is. Otherwise it is used as a string, and if it does
1601 not end with a newline then it will be extended with some indication of
1602 the current location in the code, as described for L</mess_sv>.
1604 The error message or object will by default be written to standard error,
1605 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1607 To warn with a simple string message, the L</warn> function may be
1614 Perl_warn_sv(pTHX_ SV *baseex)
1616 SV *ex = mess_sv(baseex, 0);
1617 PERL_ARGS_ASSERT_WARN_SV;
1618 if (!invoke_exception_hook(ex, TRUE))
1619 write_to_stderr(ex);
1623 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1625 This is an XS interface to Perl's C<warn> function.
1627 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1628 argument list. These are used to generate a string message. If the
1629 message does not end with a newline, then it will be extended with
1630 some indication of the current location in the code, as described for
1633 The error message or object will by default be written to standard error,
1634 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1636 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1642 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1644 SV *ex = vmess(pat, args);
1645 PERL_ARGS_ASSERT_VWARN;
1646 if (!invoke_exception_hook(ex, TRUE))
1647 write_to_stderr(ex);
1651 =for apidoc Am|void|warn|const char *pat|...
1653 This is an XS interface to Perl's C<warn> function.
1655 Take a sprintf-style format pattern and argument list. These are used to
1656 generate a string message. If the message does not end with a newline,
1657 then it will be extended with some indication of the current location
1658 in the code, as described for L</mess_sv>.
1660 The error message or object will by default be written to standard error,
1661 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1663 Unlike with L</croak>, C<pat> is not permitted to be null.
1668 #if defined(PERL_IMPLICIT_CONTEXT)
1670 Perl_warn_nocontext(const char *pat, ...)
1674 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1675 va_start(args, pat);
1679 #endif /* PERL_IMPLICIT_CONTEXT */
1682 Perl_warn(pTHX_ const char *pat, ...)
1685 PERL_ARGS_ASSERT_WARN;
1686 va_start(args, pat);
1691 #if defined(PERL_IMPLICIT_CONTEXT)
1693 Perl_warner_nocontext(U32 err, const char *pat, ...)
1697 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1698 va_start(args, pat);
1699 vwarner(err, pat, &args);
1702 #endif /* PERL_IMPLICIT_CONTEXT */
1705 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1707 PERL_ARGS_ASSERT_CK_WARNER_D;
1709 if (Perl_ckwarn_d(aTHX_ err)) {
1711 va_start(args, pat);
1712 vwarner(err, pat, &args);
1718 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1720 PERL_ARGS_ASSERT_CK_WARNER;
1722 if (Perl_ckwarn(aTHX_ err)) {
1724 va_start(args, pat);
1725 vwarner(err, pat, &args);
1731 Perl_warner(pTHX_ U32 err, const char* pat,...)
1734 PERL_ARGS_ASSERT_WARNER;
1735 va_start(args, pat);
1736 vwarner(err, pat, &args);
1741 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1744 PERL_ARGS_ASSERT_VWARNER;
1745 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1746 SV * const msv = vmess(pat, args);
1748 invoke_exception_hook(msv, FALSE);
1752 Perl_vwarn(aTHX_ pat, args);
1756 /* implements the ckWARN? macros */
1759 Perl_ckwarn(pTHX_ U32 w)
1762 /* If lexical warnings have not been set, use $^W. */
1764 return PL_dowarn & G_WARN_ON;
1766 return ckwarn_common(w);
1769 /* implements the ckWARN?_d macro */
1772 Perl_ckwarn_d(pTHX_ U32 w)
1775 /* If lexical warnings have not been set then default classes warn. */
1779 return ckwarn_common(w);
1783 S_ckwarn_common(pTHX_ U32 w)
1785 if (PL_curcop->cop_warnings == pWARN_ALL)
1788 if (PL_curcop->cop_warnings == pWARN_NONE)
1791 /* Check the assumption that at least the first slot is non-zero. */
1792 assert(unpackWARN1(w));
1794 /* Check the assumption that it is valid to stop as soon as a zero slot is
1796 if (!unpackWARN2(w)) {
1797 assert(!unpackWARN3(w));
1798 assert(!unpackWARN4(w));
1799 } else if (!unpackWARN3(w)) {
1800 assert(!unpackWARN4(w));
1803 /* Right, dealt with all the special cases, which are implemented as non-
1804 pointers, so there is a pointer to a real warnings mask. */
1806 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1808 } while (w >>= WARNshift);
1813 /* Set buffer=NULL to get a new one. */
1815 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1817 const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
1818 PERL_UNUSED_CONTEXT;
1819 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1822 (specialWARN(buffer) ?
1823 PerlMemShared_malloc(len_wanted) :
1824 PerlMemShared_realloc(buffer, len_wanted));
1826 Copy(bits, (buffer + 1), size, char);
1830 /* since we've already done strlen() for both nam and val
1831 * we can use that info to make things faster than
1832 * sprintf(s, "%s=%s", nam, val)
1834 #define my_setenv_format(s, nam, nlen, val, vlen) \
1835 Copy(nam, s, nlen, char); \
1837 Copy(val, s+(nlen+1), vlen, char); \
1838 *(s+(nlen+1+vlen)) = '\0'
1840 #ifdef USE_ENVIRON_ARRAY
1841 /* VMS' my_setenv() is in vms.c */
1842 #if !defined(WIN32) && !defined(NETWARE)
1844 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1848 /* only parent thread can modify process environment */
1849 if (PL_curinterp == aTHX)
1852 #ifndef PERL_USE_SAFE_PUTENV
1853 if (!PL_use_safe_putenv) {
1854 /* most putenv()s leak, so we manipulate environ directly */
1856 register const I32 len = strlen(nam);
1859 /* where does it go? */
1860 for (i = 0; environ[i]; i++) {
1861 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1865 if (environ == PL_origenviron) { /* need we copy environment? */
1871 while (environ[max])
1873 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1874 for (j=0; j<max; j++) { /* copy environment */
1875 const int len = strlen(environ[j]);
1876 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1877 Copy(environ[j], tmpenv[j], len+1, char);
1880 environ = tmpenv; /* tell exec where it is now */
1883 safesysfree(environ[i]);
1884 while (environ[i]) {
1885 environ[i] = environ[i+1];
1890 if (!environ[i]) { /* does not exist yet */
1891 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1892 environ[i+1] = NULL; /* make sure it's null terminated */
1895 safesysfree(environ[i]);
1899 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1900 /* all that work just for this */
1901 my_setenv_format(environ[i], nam, nlen, val, vlen);
1904 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
1905 # if defined(HAS_UNSETENV)
1907 (void)unsetenv(nam);
1909 (void)setenv(nam, val, 1);
1911 # else /* ! HAS_UNSETENV */
1912 (void)setenv(nam, val, 1);
1913 # endif /* HAS_UNSETENV */
1915 # if defined(HAS_UNSETENV)
1917 (void)unsetenv(nam);
1919 const int nlen = strlen(nam);
1920 const int vlen = strlen(val);
1921 char * const new_env =
1922 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1923 my_setenv_format(new_env, nam, nlen, val, vlen);
1924 (void)putenv(new_env);
1926 # else /* ! HAS_UNSETENV */
1928 const int nlen = strlen(nam);
1934 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1935 /* all that work just for this */
1936 my_setenv_format(new_env, nam, nlen, val, vlen);
1937 (void)putenv(new_env);
1938 # endif /* HAS_UNSETENV */
1939 # endif /* __CYGWIN__ */
1940 #ifndef PERL_USE_SAFE_PUTENV
1946 #else /* WIN32 || NETWARE */
1949 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1952 register char *envstr;
1953 const int nlen = strlen(nam);
1960 Newx(envstr, nlen+vlen+2, char);
1961 my_setenv_format(envstr, nam, nlen, val, vlen);
1962 (void)PerlEnv_putenv(envstr);
1966 #endif /* WIN32 || NETWARE */
1968 #endif /* !VMS && !EPOC*/
1970 #ifdef UNLINK_ALL_VERSIONS
1972 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
1976 PERL_ARGS_ASSERT_UNLNK;
1978 while (PerlLIO_unlink(f) >= 0)
1980 return retries ? 0 : -1;
1984 /* this is a drop-in replacement for bcopy() */
1985 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1987 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1989 char * const retval = to;
1991 PERL_ARGS_ASSERT_MY_BCOPY;
1993 if (from - to >= 0) {
2001 *(--to) = *(--from);
2007 /* this is a drop-in replacement for memset() */
2010 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2012 char * const retval = loc;
2014 PERL_ARGS_ASSERT_MY_MEMSET;
2022 /* this is a drop-in replacement for bzero() */
2023 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2025 Perl_my_bzero(register char *loc, register I32 len)
2027 char * const retval = loc;
2029 PERL_ARGS_ASSERT_MY_BZERO;
2037 /* this is a drop-in replacement for memcmp() */
2038 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2040 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2042 register const U8 *a = (const U8 *)s1;
2043 register const U8 *b = (const U8 *)s2;
2046 PERL_ARGS_ASSERT_MY_MEMCMP;
2049 if ((tmp = *a++ - *b++))
2054 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2057 /* This vsprintf replacement should generally never get used, since
2058 vsprintf was available in both System V and BSD 2.11. (There may
2059 be some cross-compilation or embedded set-ups where it is needed,
2062 If you encounter a problem in this function, it's probably a symptom
2063 that Configure failed to detect your system's vprintf() function.
2064 See the section on "item vsprintf" in the INSTALL file.
2066 This version may compile on systems with BSD-ish <stdio.h>,
2067 but probably won't on others.
2070 #ifdef USE_CHAR_VSPRINTF
2075 vsprintf(char *dest, const char *pat, void *args)
2079 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2080 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2081 FILE_cnt(&fakebuf) = 32767;
2083 /* These probably won't compile -- If you really need
2084 this, you'll have to figure out some other method. */
2085 fakebuf._ptr = dest;
2086 fakebuf._cnt = 32767;
2091 fakebuf._flag = _IOWRT|_IOSTRG;
2092 _doprnt(pat, args, &fakebuf); /* what a kludge */
2093 #if defined(STDIO_PTR_LVALUE)
2094 *(FILE_ptr(&fakebuf)++) = '\0';
2096 /* PerlIO has probably #defined away fputc, but we want it here. */
2098 # undef fputc /* XXX Should really restore it later */
2100 (void)fputc('\0', &fakebuf);
2102 #ifdef USE_CHAR_VSPRINTF
2105 return 0; /* perl doesn't use return value */
2109 #endif /* HAS_VPRINTF */
2112 #if BYTEORDER != 0x4321
2114 Perl_my_swap(pTHX_ short s)
2116 #if (BYTEORDER & 1) == 0
2119 result = ((s & 255) << 8) + ((s >> 8) & 255);
2127 Perl_my_htonl(pTHX_ long l)
2131 char c[sizeof(long)];
2134 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2135 #if BYTEORDER == 0x12345678
2138 u.c[0] = (l >> 24) & 255;
2139 u.c[1] = (l >> 16) & 255;
2140 u.c[2] = (l >> 8) & 255;
2144 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2145 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2150 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2151 u.c[o & 0xf] = (l >> s) & 255;
2159 Perl_my_ntohl(pTHX_ long l)
2163 char c[sizeof(long)];
2166 #if BYTEORDER == 0x1234
2167 u.c[0] = (l >> 24) & 255;
2168 u.c[1] = (l >> 16) & 255;
2169 u.c[2] = (l >> 8) & 255;
2173 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2174 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2181 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2182 l |= (u.c[o & 0xf] & 255) << s;
2189 #endif /* BYTEORDER != 0x4321 */
2193 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2194 * If these functions are defined,
2195 * the BYTEORDER is neither 0x1234 nor 0x4321.
2196 * However, this is not assumed.
2200 #define HTOLE(name,type) \
2202 name (register type n) \
2206 char c[sizeof(type)]; \
2209 register U32 s = 0; \
2210 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2211 u.c[i] = (n >> s) & 0xFF; \
2216 #define LETOH(name,type) \
2218 name (register type n) \
2222 char c[sizeof(type)]; \
2225 register U32 s = 0; \
2228 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2229 n |= ((type)(u.c[i] & 0xFF)) << s; \
2235 * Big-endian byte order functions.
2238 #define HTOBE(name,type) \
2240 name (register type n) \
2244 char c[sizeof(type)]; \
2247 register U32 s = 8*(sizeof(u.c)-1); \
2248 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2249 u.c[i] = (n >> s) & 0xFF; \
2254 #define BETOH(name,type) \
2256 name (register type n) \
2260 char c[sizeof(type)]; \
2263 register U32 s = 8*(sizeof(u.c)-1); \
2266 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2267 n |= ((type)(u.c[i] & 0xFF)) << s; \
2273 * If we just can't do it...
2276 #define NOT_AVAIL(name,type) \
2278 name (register type n) \
2280 Perl_croak_nocontext(#name "() not available"); \
2281 return n; /* not reached */ \
2285 #if defined(HAS_HTOVS) && !defined(htovs)
2288 #if defined(HAS_HTOVL) && !defined(htovl)
2291 #if defined(HAS_VTOHS) && !defined(vtohs)
2294 #if defined(HAS_VTOHL) && !defined(vtohl)
2298 #ifdef PERL_NEED_MY_HTOLE16
2300 HTOLE(Perl_my_htole16,U16)
2302 NOT_AVAIL(Perl_my_htole16,U16)
2305 #ifdef PERL_NEED_MY_LETOH16
2307 LETOH(Perl_my_letoh16,U16)
2309 NOT_AVAIL(Perl_my_letoh16,U16)
2312 #ifdef PERL_NEED_MY_HTOBE16
2314 HTOBE(Perl_my_htobe16,U16)
2316 NOT_AVAIL(Perl_my_htobe16,U16)
2319 #ifdef PERL_NEED_MY_BETOH16
2321 BETOH(Perl_my_betoh16,U16)
2323 NOT_AVAIL(Perl_my_betoh16,U16)
2327 #ifdef PERL_NEED_MY_HTOLE32
2329 HTOLE(Perl_my_htole32,U32)
2331 NOT_AVAIL(Perl_my_htole32,U32)
2334 #ifdef PERL_NEED_MY_LETOH32
2336 LETOH(Perl_my_letoh32,U32)
2338 NOT_AVAIL(Perl_my_letoh32,U32)
2341 #ifdef PERL_NEED_MY_HTOBE32
2343 HTOBE(Perl_my_htobe32,U32)
2345 NOT_AVAIL(Perl_my_htobe32,U32)
2348 #ifdef PERL_NEED_MY_BETOH32
2350 BETOH(Perl_my_betoh32,U32)
2352 NOT_AVAIL(Perl_my_betoh32,U32)
2356 #ifdef PERL_NEED_MY_HTOLE64
2358 HTOLE(Perl_my_htole64,U64)
2360 NOT_AVAIL(Perl_my_htole64,U64)
2363 #ifdef PERL_NEED_MY_LETOH64
2365 LETOH(Perl_my_letoh64,U64)
2367 NOT_AVAIL(Perl_my_letoh64,U64)
2370 #ifdef PERL_NEED_MY_HTOBE64
2372 HTOBE(Perl_my_htobe64,U64)
2374 NOT_AVAIL(Perl_my_htobe64,U64)
2377 #ifdef PERL_NEED_MY_BETOH64
2379 BETOH(Perl_my_betoh64,U64)
2381 NOT_AVAIL(Perl_my_betoh64,U64)
2385 #ifdef PERL_NEED_MY_HTOLES
2386 HTOLE(Perl_my_htoles,short)
2388 #ifdef PERL_NEED_MY_LETOHS
2389 LETOH(Perl_my_letohs,short)
2391 #ifdef PERL_NEED_MY_HTOBES
2392 HTOBE(Perl_my_htobes,short)
2394 #ifdef PERL_NEED_MY_BETOHS
2395 BETOH(Perl_my_betohs,short)
2398 #ifdef PERL_NEED_MY_HTOLEI
2399 HTOLE(Perl_my_htolei,int)
2401 #ifdef PERL_NEED_MY_LETOHI
2402 LETOH(Perl_my_letohi,int)
2404 #ifdef PERL_NEED_MY_HTOBEI
2405 HTOBE(Perl_my_htobei,int)
2407 #ifdef PERL_NEED_MY_BETOHI
2408 BETOH(Perl_my_betohi,int)
2411 #ifdef PERL_NEED_MY_HTOLEL
2412 HTOLE(Perl_my_htolel,long)
2414 #ifdef PERL_NEED_MY_LETOHL
2415 LETOH(Perl_my_letohl,long)
2417 #ifdef PERL_NEED_MY_HTOBEL
2418 HTOBE(Perl_my_htobel,long)
2420 #ifdef PERL_NEED_MY_BETOHL
2421 BETOH(Perl_my_betohl,long)
2425 Perl_my_swabn(void *ptr, int n)
2427 register char *s = (char *)ptr;
2428 register char *e = s + (n-1);
2431 PERL_ARGS_ASSERT_MY_SWABN;
2433 for (n /= 2; n > 0; s++, e--, n--) {
2441 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2443 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2446 register I32 This, that;
2452 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2454 PERL_FLUSHALL_FOR_CHILD;
2455 This = (*mode == 'w');
2459 taint_proper("Insecure %s%s", "EXEC");
2461 if (PerlProc_pipe(p) < 0)
2463 /* Try for another pipe pair for error return */
2464 if (PerlProc_pipe(pp) >= 0)
2466 while ((pid = PerlProc_fork()) < 0) {
2467 if (errno != EAGAIN) {
2468 PerlLIO_close(p[This]);
2469 PerlLIO_close(p[that]);
2471 PerlLIO_close(pp[0]);
2472 PerlLIO_close(pp[1]);
2476 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2485 /* Close parent's end of error status pipe (if any) */
2487 PerlLIO_close(pp[0]);
2488 #if defined(HAS_FCNTL) && defined(F_SETFD)
2489 /* Close error pipe automatically if exec works */
2490 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2493 /* Now dup our end of _the_ pipe to right position */
2494 if (p[THIS] != (*mode == 'r')) {
2495 PerlLIO_dup2(p[THIS], *mode == 'r');
2496 PerlLIO_close(p[THIS]);
2497 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2498 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2501 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2502 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2503 /* No automatic close - do it by hand */
2510 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2516 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2522 do_execfree(); /* free any memory malloced by child on fork */
2524 PerlLIO_close(pp[1]);
2525 /* Keep the lower of the two fd numbers */
2526 if (p[that] < p[This]) {
2527 PerlLIO_dup2(p[This], p[that]);
2528 PerlLIO_close(p[This]);
2532 PerlLIO_close(p[that]); /* close child's end of pipe */
2534 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2535 SvUPGRADE(sv,SVt_IV);
2537 PL_forkprocess = pid;
2538 /* If we managed to get status pipe check for exec fail */
2539 if (did_pipes && pid > 0) {
2544 while (n < sizeof(int)) {
2545 n1 = PerlLIO_read(pp[0],
2546 (void*)(((char*)&errkid)+n),
2552 PerlLIO_close(pp[0]);
2554 if (n) { /* Error */
2556 PerlLIO_close(p[This]);
2557 if (n != sizeof(int))
2558 Perl_croak(aTHX_ "panic: kid popen errno read");
2560 pid2 = wait4pid(pid, &status, 0);
2561 } while (pid2 == -1 && errno == EINTR);
2562 errno = errkid; /* Propagate errno from kid */
2567 PerlLIO_close(pp[0]);
2568 return PerlIO_fdopen(p[This], mode);
2570 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2571 return my_syspopen4(aTHX_ NULL, mode, n, args);
2573 Perl_croak(aTHX_ "List form of piped open not implemented");
2574 return (PerlIO *) NULL;
2579 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2580 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
2582 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2586 register I32 This, that;
2589 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2593 PERL_ARGS_ASSERT_MY_POPEN;
2595 PERL_FLUSHALL_FOR_CHILD;
2598 return my_syspopen(aTHX_ cmd,mode);
2601 This = (*mode == 'w');
2603 if (doexec && PL_tainting) {
2605 taint_proper("Insecure %s%s", "EXEC");
2607 if (PerlProc_pipe(p) < 0)
2609 if (doexec && PerlProc_pipe(pp) >= 0)
2611 while ((pid = PerlProc_fork()) < 0) {
2612 if (errno != EAGAIN) {
2613 PerlLIO_close(p[This]);
2614 PerlLIO_close(p[that]);
2616 PerlLIO_close(pp[0]);
2617 PerlLIO_close(pp[1]);
2620 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2623 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2634 PerlLIO_close(pp[0]);
2635 #if defined(HAS_FCNTL) && defined(F_SETFD)
2636 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2639 if (p[THIS] != (*mode == 'r')) {
2640 PerlLIO_dup2(p[THIS], *mode == 'r');
2641 PerlLIO_close(p[THIS]);
2642 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2643 PerlLIO_close(p[THAT]);
2646 PerlLIO_close(p[THAT]);
2649 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2656 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2661 /* may or may not use the shell */
2662 do_exec3(cmd, pp[1], did_pipes);
2665 #endif /* defined OS2 */
2667 #ifdef PERLIO_USING_CRLF
2668 /* Since we circumvent IO layers when we manipulate low-level
2669 filedescriptors directly, need to manually switch to the
2670 default, binary, low-level mode; see PerlIOBuf_open(). */
2671 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2674 if ((tmpgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV))) {
2675 SvREADONLY_off(GvSV(tmpgv));
2676 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2677 SvREADONLY_on(GvSV(tmpgv));
2679 #ifdef THREADS_HAVE_PIDS
2680 PL_ppid = (IV)getppid();
2683 #ifdef PERL_USES_PL_PIDSTATUS
2684 hv_clear(PL_pidstatus); /* we have no children */
2690 do_execfree(); /* free any memory malloced by child on vfork */
2692 PerlLIO_close(pp[1]);
2693 if (p[that] < p[This]) {
2694 PerlLIO_dup2(p[This], p[that]);
2695 PerlLIO_close(p[This]);
2699 PerlLIO_close(p[that]);
2701 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2702 SvUPGRADE(sv,SVt_IV);
2704 PL_forkprocess = pid;
2705 if (did_pipes && pid > 0) {
2710 while (n < sizeof(int)) {
2711 n1 = PerlLIO_read(pp[0],
2712 (void*)(((char*)&errkid)+n),
2718 PerlLIO_close(pp[0]);
2720 if (n) { /* Error */
2722 PerlLIO_close(p[This]);
2723 if (n != sizeof(int))
2724 Perl_croak(aTHX_ "panic: kid popen errno read");
2726 pid2 = wait4pid(pid, &status, 0);
2727 } while (pid2 == -1 && errno == EINTR);
2728 errno = errkid; /* Propagate errno from kid */
2733 PerlLIO_close(pp[0]);
2734 return PerlIO_fdopen(p[This], mode);
2737 #if defined(atarist) || defined(EPOC)
2740 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2742 PERL_ARGS_ASSERT_MY_POPEN;
2743 PERL_FLUSHALL_FOR_CHILD;
2744 /* Call system's popen() to get a FILE *, then import it.
2745 used 0 for 2nd parameter to PerlIO_importFILE;
2748 return PerlIO_importFILE(popen(cmd, mode), 0);
2752 FILE *djgpp_popen();
2754 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2756 PERL_FLUSHALL_FOR_CHILD;
2757 /* Call system's popen() to get a FILE *, then import it.
2758 used 0 for 2nd parameter to PerlIO_importFILE;
2761 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2764 #if defined(__LIBCATAMOUNT__)
2766 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2774 #endif /* !DOSISH */
2776 /* this is called in parent before the fork() */
2778 Perl_atfork_lock(void)
2781 #if defined(USE_ITHREADS)
2782 /* locks must be held in locking order (if any) */
2784 MUTEX_LOCK(&PL_malloc_mutex);
2790 /* this is called in both parent and child after the fork() */
2792 Perl_atfork_unlock(void)
2795 #if defined(USE_ITHREADS)
2796 /* locks must be released in same order as in atfork_lock() */
2798 MUTEX_UNLOCK(&PL_malloc_mutex);
2807 #if defined(HAS_FORK)
2809 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2814 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2815 * handlers elsewhere in the code */
2820 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2821 Perl_croak_nocontext("fork() not available");
2823 #endif /* HAS_FORK */
2828 Perl_dump_fds(pTHX_ const char *const s)
2833 PERL_ARGS_ASSERT_DUMP_FDS;
2835 PerlIO_printf(Perl_debug_log,"%s", s);
2836 for (fd = 0; fd < 32; fd++) {
2837 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2838 PerlIO_printf(Perl_debug_log," %d",fd);
2840 PerlIO_printf(Perl_debug_log,"\n");
2843 #endif /* DUMP_FDS */
2847 dup2(int oldfd, int newfd)
2849 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2852 PerlLIO_close(newfd);
2853 return fcntl(oldfd, F_DUPFD, newfd);
2855 #define DUP2_MAX_FDS 256
2856 int fdtmp[DUP2_MAX_FDS];
2862 PerlLIO_close(newfd);
2863 /* good enough for low fd's... */
2864 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2865 if (fdx >= DUP2_MAX_FDS) {
2873 PerlLIO_close(fdtmp[--fdx]);
2880 #ifdef HAS_SIGACTION
2883 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2886 struct sigaction act, oact;
2889 /* only "parent" interpreter can diddle signals */
2890 if (PL_curinterp != aTHX)
2891 return (Sighandler_t) SIG_ERR;
2894 act.sa_handler = (void(*)(int))handler;
2895 sigemptyset(&act.sa_mask);
2898 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2899 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2901 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2902 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2903 act.sa_flags |= SA_NOCLDWAIT;
2905 if (sigaction(signo, &act, &oact) == -1)
2906 return (Sighandler_t) SIG_ERR;
2908 return (Sighandler_t) oact.sa_handler;
2912 Perl_rsignal_state(pTHX_ int signo)
2914 struct sigaction oact;
2915 PERL_UNUSED_CONTEXT;
2917 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2918 return (Sighandler_t) SIG_ERR;
2920 return (Sighandler_t) oact.sa_handler;
2924 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2927 struct sigaction act;
2929 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2932 /* only "parent" interpreter can diddle signals */
2933 if (PL_curinterp != aTHX)
2937 act.sa_handler = (void(*)(int))handler;
2938 sigemptyset(&act.sa_mask);
2941 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2942 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2944 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2945 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2946 act.sa_flags |= SA_NOCLDWAIT;
2948 return sigaction(signo, &act, save);
2952 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2956 /* only "parent" interpreter can diddle signals */
2957 if (PL_curinterp != aTHX)
2961 return sigaction(signo, save, (struct sigaction *)NULL);
2964 #else /* !HAS_SIGACTION */
2967 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2969 #if defined(USE_ITHREADS) && !defined(WIN32)
2970 /* only "parent" interpreter can diddle signals */
2971 if (PL_curinterp != aTHX)
2972 return (Sighandler_t) SIG_ERR;
2975 return PerlProc_signal(signo, handler);
2986 Perl_rsignal_state(pTHX_ int signo)
2989 Sighandler_t oldsig;
2991 #if defined(USE_ITHREADS) && !defined(WIN32)
2992 /* only "parent" interpreter can diddle signals */
2993 if (PL_curinterp != aTHX)
2994 return (Sighandler_t) SIG_ERR;
2998 oldsig = PerlProc_signal(signo, sig_trap);
2999 PerlProc_signal(signo, oldsig);
3001 PerlProc_kill(PerlProc_getpid(), signo);
3006 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3008 #if defined(USE_ITHREADS) && !defined(WIN32)
3009 /* only "parent" interpreter can diddle signals */
3010 if (PL_curinterp != aTHX)
3013 *save = PerlProc_signal(signo, handler);
3014 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3018 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3020 #if defined(USE_ITHREADS) && !defined(WIN32)
3021 /* only "parent" interpreter can diddle signals */
3022 if (PL_curinterp != aTHX)
3025 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3028 #endif /* !HAS_SIGACTION */
3029 #endif /* !PERL_MICRO */
3031 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3032 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
3034 Perl_my_pclose(pTHX_ PerlIO *ptr)
3037 Sigsave_t hstat, istat, qstat;
3045 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
3046 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3048 *svp = &PL_sv_undef;
3050 if (pid == -1) { /* Opened by popen. */
3051 return my_syspclose(ptr);
3054 close_failed = (PerlIO_close(ptr) == EOF);
3057 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
3060 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3061 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3062 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3065 pid2 = wait4pid(pid, &status, 0);
3066 } while (pid2 == -1 && errno == EINTR);
3068 rsignal_restore(SIGHUP, &hstat);
3069 rsignal_restore(SIGINT, &istat);
3070 rsignal_restore(SIGQUIT, &qstat);
3076 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
3079 #if defined(__LIBCATAMOUNT__)
3081 Perl_my_pclose(pTHX_ PerlIO *ptr)
3086 #endif /* !DOSISH */
3088 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3090 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3094 PERL_ARGS_ASSERT_WAIT4PID;
3097 #ifdef PERL_USES_PL_PIDSTATUS
3100 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3101 pid, rather than a string form. */
3102 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3103 if (svp && *svp != &PL_sv_undef) {
3104 *statusp = SvIVX(*svp);
3105 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3113 hv_iterinit(PL_pidstatus);
3114 if ((entry = hv_iternext(PL_pidstatus))) {
3115 SV * const sv = hv_iterval(PL_pidstatus,entry);
3117 const char * const spid = hv_iterkey(entry,&len);
3119 assert (len == sizeof(Pid_t));
3120 memcpy((char *)&pid, spid, len);
3121 *statusp = SvIVX(sv);
3122 /* The hash iterator is currently on this entry, so simply
3123 calling hv_delete would trigger the lazy delete, which on
3124 aggregate does more work, beacuse next call to hv_iterinit()
3125 would spot the flag, and have to call the delete routine,
3126 while in the meantime any new entries can't re-use that
3128 hv_iterinit(PL_pidstatus);
3129 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3136 # ifdef HAS_WAITPID_RUNTIME
3137 if (!HAS_WAITPID_RUNTIME)
3140 result = PerlProc_waitpid(pid,statusp,flags);
3143 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3144 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3147 #ifdef PERL_USES_PL_PIDSTATUS
3148 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3153 Perl_croak(aTHX_ "Can't do waitpid with flags");
3155 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3156 pidgone(result,*statusp);
3162 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3165 if (result < 0 && errno == EINTR) {
3167 errno = EINTR; /* reset in case a signal handler changed $! */
3171 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3173 #ifdef PERL_USES_PL_PIDSTATUS
3175 S_pidgone(pTHX_ Pid_t pid, int status)
3179 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3180 SvUPGRADE(sv,SVt_IV);
3181 SvIV_set(sv, status);
3186 #if defined(atarist) || defined(OS2) || defined(EPOC)
3189 int /* Cannot prototype with I32
3191 my_syspclose(PerlIO *ptr)
3194 Perl_my_pclose(pTHX_ PerlIO *ptr)
3197 /* Needs work for PerlIO ! */
3198 FILE * const f = PerlIO_findFILE(ptr);
3199 const I32 result = pclose(f);
3200 PerlIO_releaseFILE(ptr,f);
3208 Perl_my_pclose(pTHX_ PerlIO *ptr)
3210 /* Needs work for PerlIO ! */
3211 FILE * const f = PerlIO_findFILE(ptr);
3212 I32 result = djgpp_pclose(f);
3213 result = (result << 8) & 0xff00;
3214 PerlIO_releaseFILE(ptr,f);
3219 #define PERL_REPEATCPY_LINEAR 4
3221 Perl_repeatcpy(register char *to, register const char *from, I32 len, register I32 count)
3223 PERL_ARGS_ASSERT_REPEATCPY;
3226 memset(to, *from, count);
3228 register char *p = to;
3229 I32 items, linear, half;
3231 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3232 for (items = 0; items < linear; ++items) {
3233 register const char *q = from;
3235 for (todo = len; todo > 0; todo--)
3240 while (items <= half) {
3241 I32 size = items * len;
3242 memcpy(p, to, size);
3248 memcpy(p, to, (count - items) * len);
3254 Perl_same_dirent(pTHX_ const char *a, const char *b)
3256 char *fa = strrchr(a,'/');
3257 char *fb = strrchr(b,'/');
3260 SV * const tmpsv = sv_newmortal();
3262 PERL_ARGS_ASSERT_SAME_DIRENT;
3275 sv_setpvs(tmpsv, ".");
3277 sv_setpvn(tmpsv, a, fa - a);
3278 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3281 sv_setpvs(tmpsv, ".");
3283 sv_setpvn(tmpsv, b, fb - b);
3284 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3286 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3287 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3289 #endif /* !HAS_RENAME */
3292 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3293 const char *const *const search_ext, I32 flags)
3296 const char *xfound = NULL;
3297 char *xfailed = NULL;
3298 char tmpbuf[MAXPATHLEN];
3303 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3304 # define SEARCH_EXTS ".bat", ".cmd", NULL
3305 # define MAX_EXT_LEN 4
3308 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3309 # define MAX_EXT_LEN 4
3312 # define SEARCH_EXTS ".pl", ".com", NULL
3313 # define MAX_EXT_LEN 4
3315 /* additional extensions to try in each dir if scriptname not found */
3317 static const char *const exts[] = { SEARCH_EXTS };
3318 const char *const *const ext = search_ext ? search_ext : exts;
3319 int extidx = 0, i = 0;
3320 const char *curext = NULL;
3322 PERL_UNUSED_ARG(search_ext);
3323 # define MAX_EXT_LEN 0
3326 PERL_ARGS_ASSERT_FIND_SCRIPT;
3329 * If dosearch is true and if scriptname does not contain path
3330 * delimiters, search the PATH for scriptname.
3332 * If SEARCH_EXTS is also defined, will look for each
3333 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3334 * while searching the PATH.
3336 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3337 * proceeds as follows:
3338 * If DOSISH or VMSISH:
3339 * + look for ./scriptname{,.foo,.bar}
3340 * + search the PATH for scriptname{,.foo,.bar}
3343 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3344 * this will not look in '.' if it's not in the PATH)
3349 # ifdef ALWAYS_DEFTYPES
3350 len = strlen(scriptname);
3351 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3352 int idx = 0, deftypes = 1;
3355 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3358 int idx = 0, deftypes = 1;
3361 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3363 /* The first time through, just add SEARCH_EXTS to whatever we
3364 * already have, so we can check for default file types. */
3366 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3372 if ((strlen(tmpbuf) + strlen(scriptname)
3373 + MAX_EXT_LEN) >= sizeof tmpbuf)
3374 continue; /* don't search dir with too-long name */
3375 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3379 if (strEQ(scriptname, "-"))
3381 if (dosearch) { /* Look in '.' first. */
3382 const char *cur = scriptname;
3384 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3386 if (strEQ(ext[i++],curext)) {
3387 extidx = -1; /* already has an ext */
3392 DEBUG_p(PerlIO_printf(Perl_debug_log,
3393 "Looking for %s\n",cur));
3394 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3395 && !S_ISDIR(PL_statbuf.st_mode)) {
3403 if (cur == scriptname) {
3404 len = strlen(scriptname);
3405 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3407 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3410 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3411 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3416 if (dosearch && !strchr(scriptname, '/')
3418 && !strchr(scriptname, '\\')
3420 && (s = PerlEnv_getenv("PATH")))
3424 bufend = s + strlen(s);
3425 while (s < bufend) {
3426 #if defined(atarist) || defined(DOSISH)
3431 && *s != ';'; len++, s++) {
3432 if (len < sizeof tmpbuf)
3435 if (len < sizeof tmpbuf)
3437 #else /* ! (atarist || DOSISH) */
3438 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3441 #endif /* ! (atarist || DOSISH) */
3444 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3445 continue; /* don't search dir with too-long name */
3447 # if defined(atarist) || defined(DOSISH)
3448 && tmpbuf[len - 1] != '/'
3449 && tmpbuf[len - 1] != '\\'
3452 tmpbuf[len++] = '/';
3453 if (len == 2 && tmpbuf[0] == '.')
3455 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3459 len = strlen(tmpbuf);
3460 if (extidx > 0) /* reset after previous loop */
3464 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3465 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3466 if (S_ISDIR(PL_statbuf.st_mode)) {
3470 } while ( retval < 0 /* not there */
3471 && extidx>=0 && ext[extidx] /* try an extension? */
3472 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3477 if (S_ISREG(PL_statbuf.st_mode)
3478 && cando(S_IRUSR,TRUE,&PL_statbuf)
3479 #if !defined(DOSISH)
3480 && cando(S_IXUSR,TRUE,&PL_statbuf)
3484 xfound = tmpbuf; /* bingo! */
3488 xfailed = savepv(tmpbuf);
3491 if (!xfound && !seen_dot && !xfailed &&
3492 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3493 || S_ISDIR(PL_statbuf.st_mode)))
3495 seen_dot = 1; /* Disable message. */
3497 if (flags & 1) { /* do or die? */
3498 Perl_croak(aTHX_ "Can't %s %s%s%s",
3499 (xfailed ? "execute" : "find"),
3500 (xfailed ? xfailed : scriptname),
3501 (xfailed ? "" : " on PATH"),
3502 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3507 scriptname = xfound;
3509 return (scriptname ? savepv(scriptname) : NULL);
3512 #ifndef PERL_GET_CONTEXT_DEFINED
3515 Perl_get_context(void)
3518 #if defined(USE_ITHREADS)
3519 # ifdef OLD_PTHREADS_API
3521 if (pthread_getspecific(PL_thr_key, &t))
3522 Perl_croak_nocontext("panic: pthread_getspecific");
3525 # ifdef I_MACH_CTHREADS
3526 return (void*)cthread_data(cthread_self());
3528 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3537 Perl_set_context(void *t)
3540 PERL_ARGS_ASSERT_SET_CONTEXT;
3541 #if defined(USE_ITHREADS)
3542 # ifdef I_MACH_CTHREADS
3543 cthread_set_data(cthread_self(), t);
3545 if (pthread_setspecific(PL_thr_key, t))
3546 Perl_croak_nocontext("panic: pthread_setspecific");
3553 #endif /* !PERL_GET_CONTEXT_DEFINED */
3555 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3564 Perl_get_op_names(pTHX)
3566 PERL_UNUSED_CONTEXT;
3567 return (char **)PL_op_name;
3571 Perl_get_op_descs(pTHX)
3573 PERL_UNUSED_CONTEXT;
3574 return (char **)PL_op_desc;
3578 Perl_get_no_modify(pTHX)
3580 PERL_UNUSED_CONTEXT;
3581 return PL_no_modify;
3585 Perl_get_opargs(pTHX)
3587 PERL_UNUSED_CONTEXT;
3588 return (U32 *)PL_opargs;
3592 Perl_get_ppaddr(pTHX)
3595 PERL_UNUSED_CONTEXT;
3596 return (PPADDR_t*)PL_ppaddr;
3599 #ifndef HAS_GETENV_LEN
3601 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3603 char * const env_trans = PerlEnv_getenv(env_elem);
3604 PERL_UNUSED_CONTEXT;
3605 PERL_ARGS_ASSERT_GETENV_LEN;
3607 *len = strlen(env_trans);
3614 Perl_get_vtbl(pTHX_ int vtbl_id)
3616 const MGVTBL* result;
3617 PERL_UNUSED_CONTEXT;
3621 result = &PL_vtbl_sv;
3624 result = &PL_vtbl_env;
3626 case want_vtbl_envelem:
3627 result = &PL_vtbl_envelem;
3630 result = &PL_vtbl_sig;
3632 case want_vtbl_sigelem:
3633 result = &PL_vtbl_sigelem;
3635 case want_vtbl_pack:
3636 result = &PL_vtbl_pack;
3638 case want_vtbl_packelem:
3639 result = &PL_vtbl_packelem;
3641 case want_vtbl_dbline:
3642 result = &PL_vtbl_dbline;
3645 result = &PL_vtbl_isa;
3647 case want_vtbl_isaelem:
3648 result = &PL_vtbl_isaelem;
3650 case want_vtbl_arylen:
3651 result = &PL_vtbl_arylen;
3653 case want_vtbl_mglob:
3654 result = &PL_vtbl_mglob;
3656 case want_vtbl_nkeys:
3657 result = &PL_vtbl_nkeys;
3659 case want_vtbl_taint:
3660 result = &PL_vtbl_taint;
3662 case want_vtbl_substr:
3663 result = &PL_vtbl_substr;
3666 result = &PL_vtbl_vec;
3669 result = &PL_vtbl_pos;
3672 result = &PL_vtbl_bm;
3675 result = &PL_vtbl_fm;
3677 case want_vtbl_uvar:
3678 result = &PL_vtbl_uvar;
3680 case want_vtbl_defelem:
3681 result = &PL_vtbl_defelem;
3683 case want_vtbl_regexp:
3684 result = &PL_vtbl_regexp;
3686 case want_vtbl_regdata:
3687 result = &PL_vtbl_regdata;
3689 case want_vtbl_regdatum:
3690 result = &PL_vtbl_regdatum;
3692 #ifdef USE_LOCALE_COLLATE
3693 case want_vtbl_collxfrm:
3694 result = &PL_vtbl_collxfrm;
3697 case want_vtbl_amagic:
3698 result = &PL_vtbl_amagic;
3700 case want_vtbl_amagicelem:
3701 result = &PL_vtbl_amagicelem;
3703 case want_vtbl_backref:
3704 result = &PL_vtbl_backref;
3706 case want_vtbl_utf8:
3707 result = &PL_vtbl_utf8;
3713 return (MGVTBL*)result;
3717 Perl_my_fflush_all(pTHX)
3719 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3720 return PerlIO_flush(NULL);
3722 # if defined(HAS__FWALK)
3723 extern int fflush(FILE *);
3724 /* undocumented, unprototyped, but very useful BSDism */
3725 extern void _fwalk(int (*)(FILE *));
3729 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3731 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3732 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3734 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3735 open_max = sysconf(_SC_OPEN_MAX);
3738 open_max = FOPEN_MAX;
3741 open_max = OPEN_MAX;
3752 for (i = 0; i < open_max; i++)
3753 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3754 STDIO_STREAM_ARRAY[i]._file < open_max &&
3755 STDIO_STREAM_ARRAY[i]._flag)
3756 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3760 SETERRNO(EBADF,RMS_IFI);
3767 Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
3769 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
3771 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3772 if (ckWARN(WARN_IO)) {
3773 const char * const direction =
3774 (const char *)((op == OP_phoney_INPUT_ONLY) ? "in" : "out");
3776 Perl_warner(aTHX_ packWARN(WARN_IO),
3777 "Filehandle %s opened only for %sput",
3780 Perl_warner(aTHX_ packWARN(WARN_IO),
3781 "Filehandle opened only for %sput", direction);
3788 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3790 warn_type = WARN_CLOSED;
3794 warn_type = WARN_UNOPENED;
3797 if (ckWARN(warn_type)) {
3798 const char * const pars =
3799 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3800 const char * const func =
3802 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3803 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3804 op < 0 ? "" : /* handle phoney cases */
3806 const char * const type =
3808 (OP_IS_SOCKET(op) ||
3809 (gv && io && IoTYPE(io) == IoTYPE_SOCKET) ?
3810 "socket" : "filehandle");
3811 if (name && *name) {
3812 Perl_warner(aTHX_ packWARN(warn_type),
3813 "%s%s on %s %s %s", func, pars, vile, type, name);
3814 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3816 aTHX_ packWARN(warn_type),
3817 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3822 Perl_warner(aTHX_ packWARN(warn_type),
3823 "%s%s on %s %s", func, pars, vile, type);
3824 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3826 aTHX_ packWARN(warn_type),
3827 "\t(Are you trying to call %s%s on dirhandle?)\n",
3835 /* XXX Add documentation after final interface and behavior is decided */
3836 /* May want to show context for error, so would pass Perl_bslash_c(pTHX_ const char* current, const char* start, const bool output_warning)
3837 U8 source = *current;
3839 May want to add eg, WARN_REGEX
3843 Perl_grok_bslash_c(pTHX_ const char source, const bool output_warning)
3848 if (! isASCII(source)) {
3849 Perl_croak(aTHX_ "Character following \"\\c\" must be ASCII");
3852 result = toCTRL(source);
3853 if (! isCNTRL(result)) {
3854 if (source == '{') {
3855 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 \";\"");
3857 else if (output_warning) {
3860 if (! isALNUM(result)) {
3861 clearer[i++] = '\\';
3863 clearer[i++] = result;
3864 clearer[i++] = '\0';
3866 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
3867 "\"\\c%c\" more clearly written simply as \"%s\"",
3876 /* To workaround core dumps from the uninitialised tm_zone we get the
3877 * system to give us a reasonable struct to copy. This fix means that
3878 * strftime uses the tm_zone and tm_gmtoff values returned by
3879 * localtime(time()). That should give the desired result most of the
3880 * time. But probably not always!
3882 * This does not address tzname aspects of NETaa14816.
3887 # ifndef STRUCT_TM_HASZONE
3888 # define STRUCT_TM_HASZONE
3892 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3893 # ifndef HAS_TM_TM_ZONE
3894 # define HAS_TM_TM_ZONE
3899 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3901 #ifdef HAS_TM_TM_ZONE
3903 const struct tm* my_tm;
3904 PERL_ARGS_ASSERT_INIT_TM;
3906 my_tm = localtime(&now);
3908 Copy(my_tm, ptm, 1, struct tm);
3910 PERL_ARGS_ASSERT_INIT_TM;
3911 PERL_UNUSED_ARG(ptm);
3916 * mini_mktime - normalise struct tm values without the localtime()
3917 * semantics (and overhead) of mktime().
3920 Perl_mini_mktime(pTHX_ struct tm *ptm)
3924 int month, mday, year, jday;
3925 int odd_cent, odd_year;
3926 PERL_UNUSED_CONTEXT;
3928 PERL_ARGS_ASSERT_MINI_MKTIME;
3930 #define DAYS_PER_YEAR 365
3931 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3932 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3933 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3934 #define SECS_PER_HOUR (60*60)
3935 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3936 /* parentheses deliberately absent on these two, otherwise they don't work */
3937 #define MONTH_TO_DAYS 153/5
3938 #define DAYS_TO_MONTH 5/153
3939 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3940 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3941 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3942 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3945 * Year/day algorithm notes:
3947 * With a suitable offset for numeric value of the month, one can find
3948 * an offset into the year by considering months to have 30.6 (153/5) days,
3949 * using integer arithmetic (i.e., with truncation). To avoid too much
3950 * messing about with leap days, we consider January and February to be
3951 * the 13th and 14th month of the previous year. After that transformation,
3952 * we need the month index we use to be high by 1 from 'normal human' usage,
3953 * so the month index values we use run from 4 through 15.
3955 * Given that, and the rules for the Gregorian calendar (leap years are those
3956 * divisible by 4 unless also divisible by 100, when they must be divisible
3957 * by 400 instead), we can simply calculate the number of days since some
3958 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3959 * the days we derive from our month index, and adding in the day of the
3960 * month. The value used here is not adjusted for the actual origin which
3961 * it normally would use (1 January A.D. 1), since we're not exposing it.
3962 * We're only building the value so we can turn around and get the
3963 * normalised values for the year, month, day-of-month, and day-of-year.
3965 * For going backward, we need to bias the value we're using so that we find
3966 * the right year value. (Basically, we don't want the contribution of
3967 * March 1st to the number to apply while deriving the year). Having done
3968 * that, we 'count up' the contribution to the year number by accounting for
3969 * full quadracenturies (400-year periods) with their extra leap days, plus
3970 * the contribution from full centuries (to avoid counting in the lost leap
3971 * days), plus the contribution from full quad-years (to count in the normal
3972 * leap days), plus the leftover contribution from any non-leap years.
3973 * At this point, if we were working with an actual leap day, we'll have 0
3974 * days left over. This is also true for March 1st, however. So, we have
3975 * to special-case that result, and (earlier) keep track of the 'odd'
3976 * century and year contributions. If we got 4 extra centuries in a qcent,
3977 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3978 * Otherwise, we add back in the earlier bias we removed (the 123 from
3979 * figuring in March 1st), find the month index (integer division by 30.6),
3980 * and the remainder is the day-of-month. We then have to convert back to
3981 * 'real' months (including fixing January and February from being 14/15 in
3982 * the previous year to being in the proper year). After that, to get
3983 * tm_yday, we work with the normalised year and get a new yearday value for
3984 * January 1st, which we subtract from the yearday value we had earlier,
3985 * representing the date we've re-built. This is done from January 1
3986 * because tm_yday is 0-origin.
3988 * Since POSIX time routines are only guaranteed to work for times since the
3989 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3990 * applies Gregorian calendar rules even to dates before the 16th century
3991 * doesn't bother me. Besides, you'd need cultural context for a given
3992 * date to know whether it was Julian or Gregorian calendar, and that's
3993 * outside the scope for this routine. Since we convert back based on the
3994 * same rules we used to build the yearday, you'll only get strange results
3995 * for input which needed normalising, or for the 'odd' century years which
3996 * were leap years in the Julian calander but not in the Gregorian one.
3997 * I can live with that.
3999 * This algorithm also fails to handle years before A.D. 1 gracefully, but
4000 * that's still outside the scope for POSIX time manipulation, so I don't
4004 year = 1900 + ptm->tm_year;
4005 month = ptm->tm_mon;
4006 mday = ptm->tm_mday;
4007 /* allow given yday with no month & mday to dominate the result */
4008 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
4011 jday = 1 + ptm->tm_yday;
4020 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4021 yearday += month*MONTH_TO_DAYS + mday + jday;
4023 * Note that we don't know when leap-seconds were or will be,
4024 * so we have to trust the user if we get something which looks
4025 * like a sensible leap-second. Wild values for seconds will
4026 * be rationalised, however.
4028 if ((unsigned) ptm->tm_sec <= 60) {
4035 secs += 60 * ptm->tm_min;
4036 secs += SECS_PER_HOUR * ptm->tm_hour;
4038 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4039 /* got negative remainder, but need positive time */
4040 /* back off an extra day to compensate */
4041 yearday += (secs/SECS_PER_DAY)-1;
4042 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4045 yearday += (secs/SECS_PER_DAY);
4046 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4049 else if (secs >= SECS_PER_DAY) {
4050 yearday += (secs/SECS_PER_DAY);
4051 secs %= SECS_PER_DAY;
4053 ptm->tm_hour = secs/SECS_PER_HOUR;
4054 secs %= SECS_PER_HOUR;
4055 ptm->tm_min = secs/60;
4057 ptm->tm_sec += secs;
4058 /* done with time of day effects */
4060 * The algorithm for yearday has (so far) left it high by 428.
4061 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4062 * bias it by 123 while trying to figure out what year it
4063 * really represents. Even with this tweak, the reverse
4064 * translation fails for years before A.D. 0001.
4065 * It would still fail for Feb 29, but we catch that one below.
4067 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
4068 yearday -= YEAR_ADJUST;
4069 year = (yearday / DAYS_PER_QCENT) * 400;
4070 yearday %= DAYS_PER_QCENT;
4071 odd_cent = yearday / DAYS_PER_CENT;
4072 year += odd_cent * 100;
4073 yearday %= DAYS_PER_CENT;
4074 year += (yearday / DAYS_PER_QYEAR) * 4;
4075 yearday %= DAYS_PER_QYEAR;
4076 odd_year = yearday / DAYS_PER_YEAR;
4078 yearday %= DAYS_PER_YEAR;
4079 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4084 yearday += YEAR_ADJUST; /* recover March 1st crock */
4085 month = yearday*DAYS_TO_MONTH;
4086 yearday -= month*MONTH_TO_DAYS;
4087 /* recover other leap-year adjustment */
4096 ptm->tm_year = year - 1900;
4098 ptm->tm_mday = yearday;
4099 ptm->tm_mon = month;
4103 ptm->tm_mon = month - 1;
4105 /* re-build yearday based on Jan 1 to get tm_yday */
4107 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4108 yearday += 14*MONTH_TO_DAYS + 1;
4109 ptm->tm_yday = jday - yearday;
4110 /* fix tm_wday if not overridden by caller */
4111 if ((unsigned)ptm->tm_wday > 6)
4112 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4116 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)
4124 PERL_ARGS_ASSERT_MY_STRFTIME;
4126 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4129 mytm.tm_hour = hour;
4130 mytm.tm_mday = mday;
4132 mytm.tm_year = year;
4133 mytm.tm_wday = wday;
4134 mytm.tm_yday = yday;
4135 mytm.tm_isdst = isdst;
4137 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4138 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4143 #ifdef HAS_TM_TM_GMTOFF
4144 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4146 #ifdef HAS_TM_TM_ZONE
4147 mytm.tm_zone = mytm2.tm_zone;
4152 Newx(buf, buflen, char);
4153 len = strftime(buf, buflen, fmt, &mytm);
4155 ** The following is needed to handle to the situation where
4156 ** tmpbuf overflows. Basically we want to allocate a buffer
4157 ** and try repeatedly. The reason why it is so complicated
4158 ** is that getting a return value of 0 from strftime can indicate
4159 ** one of the following:
4160 ** 1. buffer overflowed,
4161 ** 2. illegal conversion specifier, or
4162 ** 3. the format string specifies nothing to be returned(not
4163 ** an error). This could be because format is an empty string
4164 ** or it specifies %p that yields an empty string in some locale.
4165 ** If there is a better way to make it portable, go ahead by
4168 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4171 /* Possibly buf overflowed - try again with a bigger buf */
4172 const int fmtlen = strlen(fmt);
4173 int bufsize = fmtlen + buflen;
4175 Newx(buf, bufsize, char);
4177 buflen = strftime(buf, bufsize, fmt, &mytm);
4178 if (buflen > 0 && buflen < bufsize)
4180 /* heuristic to prevent out-of-memory errors */
4181 if (bufsize > 100*fmtlen) {
4187 Renew(buf, bufsize, char);
4192 Perl_croak(aTHX_ "panic: no strftime");
4198 #define SV_CWD_RETURN_UNDEF \
4199 sv_setsv(sv, &PL_sv_undef); \
4202 #define SV_CWD_ISDOT(dp) \
4203 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4204 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4207 =head1 Miscellaneous Functions
4209 =for apidoc getcwd_sv
4211 Fill the sv with current working directory
4216 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4217 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4218 * getcwd(3) if available
4219 * Comments from the orignal:
4220 * This is a faster version of getcwd. It's also more dangerous
4221 * because you might chdir out of a directory that you can't chdir
4225 Perl_getcwd_sv(pTHX_ register SV *sv)
4229 #ifndef INCOMPLETE_TAINTS
4233 PERL_ARGS_ASSERT_GETCWD_SV;
4237 char buf[MAXPATHLEN];
4239 /* Some getcwd()s automatically allocate a buffer of the given
4240 * size from the heap if they are given a NULL buffer pointer.
4241 * The problem is that this behaviour is not portable. */
4242 if (getcwd(buf, sizeof(buf) - 1)) {
4247 sv_setsv(sv, &PL_sv_undef);
4255 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4259 SvUPGRADE(sv, SVt_PV);
4261 if (PerlLIO_lstat(".", &statbuf) < 0) {
4262 SV_CWD_RETURN_UNDEF;
4265 orig_cdev = statbuf.st_dev;
4266 orig_cino = statbuf.st_ino;
4276 if (PerlDir_chdir("..") < 0) {
4277 SV_CWD_RETURN_UNDEF;
4279 if (PerlLIO_stat(".", &statbuf) < 0) {
4280 SV_CWD_RETURN_UNDEF;
4283 cdev = statbuf.st_dev;
4284 cino = statbuf.st_ino;
4286 if (odev == cdev && oino == cino) {
4289 if (!(dir = PerlDir_open("."))) {
4290 SV_CWD_RETURN_UNDEF;
4293 while ((dp = PerlDir_read(dir)) != NULL) {
4295 namelen = dp->d_namlen;
4297 namelen = strlen(dp->d_name);
4300 if (SV_CWD_ISDOT(dp)) {
4304 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4305 SV_CWD_RETURN_UNDEF;
4308 tdev = statbuf.st_dev;
4309 tino = statbuf.st_ino;
4310 if (tino == oino && tdev == odev) {
4316 SV_CWD_RETURN_UNDEF;
4319 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4320 SV_CWD_RETURN_UNDEF;
4323 SvGROW(sv, pathlen + namelen + 1);
4327 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4330 /* prepend current directory to the front */
4332 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4333 pathlen += (namelen + 1);
4335 #ifdef VOID_CLOSEDIR
4338 if (PerlDir_close(dir) < 0) {
4339 SV_CWD_RETURN_UNDEF;
4345 SvCUR_set(sv, pathlen);
4349 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4350 SV_CWD_RETURN_UNDEF;
4353 if (PerlLIO_stat(".", &statbuf) < 0) {
4354 SV_CWD_RETURN_UNDEF;
4357 cdev = statbuf.st_dev;
4358 cino = statbuf.st_ino;
4360 if (cdev != orig_cdev || cino != orig_cino) {
4361 Perl_croak(aTHX_ "Unstable directory path, "
4362 "current directory changed unexpectedly");
4373 #define VERSION_MAX 0x7FFFFFFF
4376 =for apidoc prescan_version
4381 Perl_prescan_version(pTHX_ const char *s, bool strict,
4382 const char **errstr,
4383 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4384 bool qv = (sqv ? *sqv : FALSE);
4386 int saw_decimal = 0;
4390 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4392 if (qv && isDIGIT(*d))
4393 goto dotted_decimal_version;
4395 if (*d == 'v') { /* explicit v-string */
4400 else { /* degenerate v-string */
4401 /* requires v1.2.3 */
4402 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4405 dotted_decimal_version:
4406 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4407 /* no leading zeros allowed */
4408 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4411 while (isDIGIT(*d)) /* integer part */
4417 d++; /* decimal point */
4422 /* require v1.2.3 */
4423 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4426 goto version_prescan_finish;
4433 while (isDIGIT(*d)) { /* just keep reading */
4435 while (isDIGIT(*d)) {
4437 /* maximum 3 digits between decimal */
4438 if (strict && j > 3) {
4439 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4444 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4447 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4452 else if (*d == '.') {
4454 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4459 else if (!isDIGIT(*d)) {
4465 if (strict && i < 2) {
4466 /* requires v1.2.3 */
4467 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4470 } /* end if dotted-decimal */
4472 { /* decimal versions */
4473 /* special strict case for leading '.' or '0' */
4476 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4478 if (*d == '0' && isDIGIT(d[1])) {
4479 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4483 /* consume all of the integer part */
4487 /* look for a fractional part */
4489 /* we found it, so consume it */
4493 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4496 BADVERSION(s,errstr,"Invalid version format (version required)");
4498 /* found just an integer */
4499 goto version_prescan_finish;
4501 else if ( d == s ) {
4502 /* didn't find either integer or period */
4503 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4505 else if (*d == '_') {
4506 /* underscore can't come after integer part */
4508 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4510 else if (isDIGIT(d[1])) {
4511 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4514 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4518 /* anything else after integer part is just invalid data */
4519 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4522 /* scan the fractional part after the decimal point*/
4524 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4525 /* strict or lax-but-not-the-end */
4526 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4529 while (isDIGIT(*d)) {
4531 if (*d == '.' && isDIGIT(d[-1])) {
4533 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4536 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4538 d = (char *)s; /* start all over again */
4540 goto dotted_decimal_version;
4544 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4547 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4549 if ( ! isDIGIT(d[1]) ) {
4550 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4558 version_prescan_finish:
4562 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4563 /* trailing non-numeric data */
4564 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4572 *ssaw_decimal = saw_decimal;
4579 =for apidoc scan_version
4581 Returns a pointer to the next character after the parsed
4582 version string, as well as upgrading the passed in SV to
4585 Function must be called with an already existing SV like
4588 s = scan_version(s, SV *sv, bool qv);
4590 Performs some preprocessing to the string to ensure that
4591 it has the correct characteristics of a version. Flags the
4592 object if it contains an underscore (which denotes this
4593 is an alpha version). The boolean qv denotes that the version
4594 should be interpreted as if it had multiple decimals, even if
4601 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4606 const char *errstr = NULL;
4607 int saw_decimal = 0;
4611 AV * const av = newAV();
4612 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4614 PERL_ARGS_ASSERT_SCAN_VERSION;
4616 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4618 #ifndef NODEFAULT_SHAREKEYS
4619 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4622 while (isSPACE(*s)) /* leading whitespace is OK */
4625 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4627 /* "undef" is a special case and not an error */
4628 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4629 Perl_croak(aTHX_ "%s", errstr);
4639 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4641 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4642 if ( !qv && width < 3 )
4643 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4645 while (isDIGIT(*pos))
4647 if (!isALPHA(*pos)) {
4653 /* this is atoi() that delimits on underscores */
4654 const char *end = pos;
4658 /* the following if() will only be true after the decimal
4659 * point of a version originally created with a bare
4660 * floating point number, i.e. not quoted in any way
4662 if ( !qv && s > start && saw_decimal == 1 ) {
4666 rev += (*s - '0') * mult;
4668 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4669 || (PERL_ABS(rev) > VERSION_MAX )) {
4670 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4671 "Integer overflow in version %d",VERSION_MAX);
4682 while (--end >= s) {
4684 rev += (*end - '0') * mult;
4686 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4687 || (PERL_ABS(rev) > VERSION_MAX )) {
4688 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4689 "Integer overflow in version");
4698 /* Append revision */
4699 av_push(av, newSViv(rev));
4704 else if ( *pos == '.' )
4706 else if ( *pos == '_' && isDIGIT(pos[1]) )
4708 else if ( *pos == ',' && isDIGIT(pos[1]) )
4710 else if ( isDIGIT(*pos) )
4717 while ( isDIGIT(*pos) )
4722 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4730 if ( qv ) { /* quoted versions always get at least three terms*/
4731 I32 len = av_len(av);
4732 /* This for loop appears to trigger a compiler bug on OS X, as it
4733 loops infinitely. Yes, len is negative. No, it makes no sense.
4734 Compiler in question is:
4735 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4736 for ( len = 2 - len; len > 0; len-- )
4737 av_push(MUTABLE_AV(sv), newSViv(0));
4741 av_push(av, newSViv(0));
4744 /* need to save off the current version string for later */
4746 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4747 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4748 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4750 else if ( s > start ) {
4751 SV * orig = newSVpvn(start,s-start);
4752 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4753 /* need to insert a v to be consistent */
4754 sv_insert(orig, 0, 0, "v", 1);
4756 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4759 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4760 av_push(av, newSViv(0));
4763 /* And finally, store the AV in the hash */
4764 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4766 /* fix RT#19517 - special case 'undef' as string */
4767 if ( *s == 'u' && strEQ(s,"undef") ) {
4775 =for apidoc new_version
4777 Returns a new version object based on the passed in SV:
4779 SV *sv = new_version(SV *ver);
4781 Does not alter the passed in ver SV. See "upg_version" if you
4782 want to upgrade the SV.
4788 Perl_new_version(pTHX_ SV *ver)
4791 SV * const rv = newSV(0);
4792 PERL_ARGS_ASSERT_NEW_VERSION;
4793 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4796 AV * const av = newAV();
4798 /* This will get reblessed later if a derived class*/
4799 SV * const hv = newSVrv(rv, "version");
4800 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4801 #ifndef NODEFAULT_SHAREKEYS
4802 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4808 /* Begin copying all of the elements */
4809 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4810 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4812 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4813 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4815 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4817 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4818 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4821 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4823 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4824 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4827 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4828 /* This will get reblessed later if a derived class*/
4829 for ( key = 0; key <= av_len(sav); key++ )
4831 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4832 av_push(av, newSViv(rev));
4835 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4840 const MAGIC* const mg = SvVSTRING_mg(ver);
4841 if ( mg ) { /* already a v-string */
4842 const STRLEN len = mg->mg_len;
4843 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4844 sv_setpvn(rv,version,len);
4845 /* this is for consistency with the pure Perl class */
4846 if ( isDIGIT(*version) )
4847 sv_insert(rv, 0, 0, "v", 1);
4852 sv_setsv(rv,ver); /* make a duplicate */
4857 return upg_version(rv, FALSE);
4861 =for apidoc upg_version
4863 In-place upgrade of the supplied SV to a version object.
4865 SV *sv = upg_version(SV *sv, bool qv);
4867 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4868 to force this SV to be interpreted as an "extended" version.
4874 Perl_upg_version(pTHX_ SV *ver, bool qv)
4876 const char *version, *s;
4881 PERL_ARGS_ASSERT_UPG_VERSION;
4883 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4885 /* may get too much accuracy */
4887 #ifdef USE_LOCALE_NUMERIC
4888 char *loc = setlocale(LC_NUMERIC, "C");
4890 STRLEN len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4891 #ifdef USE_LOCALE_NUMERIC
4892 setlocale(LC_NUMERIC, loc);
4894 while (tbuf[len-1] == '0' && len > 0) len--;
4895 if ( tbuf[len-1] == '.' ) len--; /* eat the trailing decimal */
4896 version = savepvn(tbuf, len);
4899 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4900 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4904 else /* must be a string or something like a string */
4907 version = savepv(SvPV(ver,len));
4909 # if PERL_VERSION > 5
4910 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4911 if ( len >= 3 && !instr(version,".") && !instr(version,"_")
4912 && !(*version == 'u' && strEQ(version, "undef"))
4913 && (*version < '0' || *version > '9') ) {
4914 /* may be a v-string */
4915 SV * const nsv = sv_newmortal();
4918 int saw_decimal = 0;
4919 sv_setpvf(nsv,"v%vd",ver);
4920 pos = nver = savepv(SvPV_nolen(nsv));
4922 /* scan the resulting formatted string */
4923 pos++; /* skip the leading 'v' */
4924 while ( *pos == '.' || isDIGIT(*pos) ) {
4930 /* is definitely a v-string */
4931 if ( saw_decimal >= 2 ) {
4940 s = scan_version(version, ver, qv);
4942 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4943 "Version string '%s' contains invalid data; "
4944 "ignoring: '%s'", version, s);
4952 Validates that the SV contains a valid version object.
4954 bool vverify(SV *vobj);
4956 Note that it only confirms the bare minimum structure (so as not to get
4957 confused by derived classes which may contain additional hash entries):
4961 =item * The SV contains a [reference to a] hash
4963 =item * The hash contains a "version" key
4965 =item * The "version" key has [a reference to] an AV as its value
4973 Perl_vverify(pTHX_ SV *vs)
4977 PERL_ARGS_ASSERT_VVERIFY;
4982 /* see if the appropriate elements exist */
4983 if ( SvTYPE(vs) == SVt_PVHV
4984 && hv_exists(MUTABLE_HV(vs), "version", 7)
4985 && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
4986 && SvTYPE(sv) == SVt_PVAV )
4995 Accepts a version object and returns the normalized floating
4996 point representation. Call like:
5000 NOTE: you can pass either the object directly or the SV
5001 contained within the RV.
5007 Perl_vnumify(pTHX_ SV *vs)
5015 PERL_ARGS_ASSERT_VNUMIFY;
5021 Perl_croak(aTHX_ "Invalid version object");
5023 /* see if various flags exist */
5024 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5026 if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
5027 width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
5032 /* attempt to retrieve the version array */
5033 if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
5034 return newSVpvs("0");
5040 return newSVpvs("0");
5043 digit = SvIV(*av_fetch(av, 0, 0));
5044 sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
5045 for ( i = 1 ; i < len ; i++ )
5047 digit = SvIV(*av_fetch(av, i, 0));
5049 const int denom = (width == 2 ? 10 : 100);
5050 const div_t term = div((int)PERL_ABS(digit),denom);
5051 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
5054 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5060 digit = SvIV(*av_fetch(av, len, 0));
5061 if ( alpha && width == 3 ) /* alpha version */
5063 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5067 sv_catpvs(sv, "000");
5075 Accepts a version object and returns the normalized string
5076 representation. Call like:
5080 NOTE: you can pass either the object directly or the SV
5081 contained within the RV.
5087 Perl_vnormal(pTHX_ SV *vs)
5094 PERL_ARGS_ASSERT_VNORMAL;
5100 Perl_croak(aTHX_ "Invalid version object");
5102 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5104 av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)));
5109 return newSVpvs("");
5111 digit = SvIV(*av_fetch(av, 0, 0));
5112 sv = Perl_newSVpvf(aTHX_ "v%"IVdf, (IV)digit);
5113 for ( i = 1 ; i < len ; i++ ) {
5114 digit = SvIV(*av_fetch(av, i, 0));
5115 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5120 /* handle last digit specially */
5121 digit = SvIV(*av_fetch(av, len, 0));
5123 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
5125 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5128 if ( len <= 2 ) { /* short version, must be at least three */
5129 for ( len = 2 - len; len != 0; len-- )
5136 =for apidoc vstringify
5138 In order to maintain maximum compatibility with earlier versions
5139 of Perl, this function will return either the floating point
5140 notation or the multiple dotted notation, depending on whether
5141 the original version contained 1 or more dots, respectively
5147 Perl_vstringify(pTHX_ SV *vs)
5149 PERL_ARGS_ASSERT_VSTRINGIFY;
5155 Perl_croak(aTHX_ "Invalid version object");
5157 if (hv_exists(MUTABLE_HV(vs), "original", sizeof("original") - 1)) {
5159 pv = *hv_fetchs(MUTABLE_HV(vs), "original", FALSE);
5163 return &PL_sv_undef;
5166 if ( hv_exists(MUTABLE_HV(vs), "qv", 2) )
5176 Version object aware cmp. Both operands must already have been
5177 converted into version objects.
5183 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
5186 bool lalpha = FALSE;
5187 bool ralpha = FALSE;
5192 PERL_ARGS_ASSERT_VCMP;
5199 if ( !vverify(lhv) )
5200 Perl_croak(aTHX_ "Invalid version object");
5202 if ( !vverify(rhv) )
5203 Perl_croak(aTHX_ "Invalid version object");
5205 /* get the left hand term */
5206 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(lhv), "version", FALSE)));
5207 if ( hv_exists(MUTABLE_HV(lhv), "alpha", 5 ) )
5210 /* and the right hand term */
5211 rav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rhv), "version", FALSE)));
5212 if ( hv_exists(MUTABLE_HV(rhv), "alpha", 5 ) )
5220 while ( i <= m && retval == 0 )
5222 left = SvIV(*av_fetch(lav,i,0));
5223 right = SvIV(*av_fetch(rav,i,0));
5231 /* tiebreaker for alpha with identical terms */
5232 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
5234 if ( lalpha && !ralpha )
5238 else if ( ralpha && !lalpha)
5244 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
5248 while ( i <= r && retval == 0 )
5250 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
5251 retval = -1; /* not a match after all */
5257 while ( i <= l && retval == 0 )
5259 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
5260 retval = +1; /* not a match after all */
5268 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
5269 # define EMULATE_SOCKETPAIR_UDP
5272 #ifdef EMULATE_SOCKETPAIR_UDP
5274 S_socketpair_udp (int fd[2]) {
5276 /* Fake a datagram socketpair using UDP to localhost. */
5277 int sockets[2] = {-1, -1};
5278 struct sockaddr_in addresses[2];
5280 Sock_size_t size = sizeof(struct sockaddr_in);
5281 unsigned short port;
5284 memset(&addresses, 0, sizeof(addresses));
5287 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
5288 if (sockets[i] == -1)
5289 goto tidy_up_and_fail;
5291 addresses[i].sin_family = AF_INET;
5292 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5293 addresses[i].sin_port = 0; /* kernel choses port. */
5294 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
5295 sizeof(struct sockaddr_in)) == -1)
5296 goto tidy_up_and_fail;
5299 /* Now have 2 UDP sockets. Find out which port each is connected to, and
5300 for each connect the other socket to it. */
5303 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
5305 goto tidy_up_and_fail;
5306 if (size != sizeof(struct sockaddr_in))
5307 goto abort_tidy_up_and_fail;
5308 /* !1 is 0, !0 is 1 */
5309 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
5310 sizeof(struct sockaddr_in)) == -1)
5311 goto tidy_up_and_fail;
5314 /* Now we have 2 sockets connected to each other. I don't trust some other
5315 process not to have already sent a packet to us (by random) so send
5316 a packet from each to the other. */
5319 /* I'm going to send my own port number. As a short.
5320 (Who knows if someone somewhere has sin_port as a bitfield and needs
5321 this routine. (I'm assuming crays have socketpair)) */
5322 port = addresses[i].sin_port;
5323 got = PerlLIO_write(sockets[i], &port, sizeof(port));
5324 if (got != sizeof(port)) {
5326 goto tidy_up_and_fail;
5327 goto abort_tidy_up_and_fail;
5331 /* Packets sent. I don't trust them to have arrived though.
5332 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
5333 connect to localhost will use a second kernel thread. In 2.6 the
5334 first thread running the connect() returns before the second completes,
5335 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
5336 returns 0. Poor programs have tripped up. One poor program's authors'
5337 had a 50-1 reverse stock split. Not sure how connected these were.)
5338 So I don't trust someone not to have an unpredictable UDP stack.
5342 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
5343 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
5347 FD_SET((unsigned int)sockets[0], &rset);
5348 FD_SET((unsigned int)sockets[1], &rset);
5350 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
5351 if (got != 2 || !FD_ISSET(sockets[0], &rset)
5352 || !FD_ISSET(sockets[1], &rset)) {
5353 /* I hope this is portable and appropriate. */
5355 goto tidy_up_and_fail;
5356 goto abort_tidy_up_and_fail;
5360 /* And the paranoia department even now doesn't trust it to have arrive
5361 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
5363 struct sockaddr_in readfrom;
5364 unsigned short buffer[2];
5369 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5370 sizeof(buffer), MSG_DONTWAIT,
5371 (struct sockaddr *) &readfrom, &size);
5373 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5375 (struct sockaddr *) &readfrom, &size);
5379 goto tidy_up_and_fail;
5380 if (got != sizeof(port)
5381 || size != sizeof(struct sockaddr_in)
5382 /* Check other socket sent us its port. */
5383 || buffer[0] != (unsigned short) addresses[!i].sin_port
5384 /* Check kernel says we got the datagram from that socket */
5385 || readfrom.sin_family != addresses[!i].sin_family
5386 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
5387 || readfrom.sin_port != addresses[!i].sin_port)
5388 goto abort_tidy_up_and_fail;
5391 /* My caller (my_socketpair) has validated that this is non-NULL */
5394 /* I hereby declare this connection open. May God bless all who cross
5398 abort_tidy_up_and_fail:
5399 errno = ECONNABORTED;
5403 if (sockets[0] != -1)
5404 PerlLIO_close(sockets[0]);
5405 if (sockets[1] != -1)
5406 PerlLIO_close(sockets[1]);
5411 #endif /* EMULATE_SOCKETPAIR_UDP */
5413 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
5415 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5416 /* Stevens says that family must be AF_LOCAL, protocol 0.
5417 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
5422 struct sockaddr_in listen_addr;
5423 struct sockaddr_in connect_addr;
5428 || family != AF_UNIX
5431 errno = EAFNOSUPPORT;
5439 #ifdef EMULATE_SOCKETPAIR_UDP
5440 if (type == SOCK_DGRAM)
5441 return S_socketpair_udp(fd);
5444 listener = PerlSock_socket(AF_INET, type, 0);
5447 memset(&listen_addr, 0, sizeof(listen_addr));
5448 listen_addr.sin_family = AF_INET;
5449 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5450 listen_addr.sin_port = 0; /* kernel choses port. */
5451 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5452 sizeof(listen_addr)) == -1)
5453 goto tidy_up_and_fail;
5454 if (PerlSock_listen(listener, 1) == -1)
5455 goto tidy_up_and_fail;
5457 connector = PerlSock_socket(AF_INET, type, 0);
5458 if (connector == -1)
5459 goto tidy_up_and_fail;
5460 /* We want to find out the port number to connect to. */
5461 size = sizeof(connect_addr);
5462 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5464 goto tidy_up_and_fail;
5465 if (size != sizeof(connect_addr))
5466 goto abort_tidy_up_and_fail;
5467 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
5468 sizeof(connect_addr)) == -1)
5469 goto tidy_up_and_fail;
5471 size = sizeof(listen_addr);
5472 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5475 goto tidy_up_and_fail;
5476 if (size != sizeof(listen_addr))
5477 goto abort_tidy_up_and_fail;
5478 PerlLIO_close(listener);
5479 /* Now check we are talking to ourself by matching port and host on the
5481 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5483 goto tidy_up_and_fail;
5484 if (size != sizeof(connect_addr)
5485 || listen_addr.sin_family != connect_addr.sin_family
5486 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5487 || listen_addr.sin_port != connect_addr.sin_port) {
5488 goto abort_tidy_up_and_fail;
5494 abort_tidy_up_and_fail:
5496 errno = ECONNABORTED; /* This would be the standard thing to do. */
5498 # ifdef ECONNREFUSED
5499 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5501 errno = ETIMEDOUT; /* Desperation time. */
5508 PerlLIO_close(listener);
5509 if (connector != -1)
5510 PerlLIO_close(connector);
5512 PerlLIO_close(acceptor);
5518 /* In any case have a stub so that there's code corresponding
5519 * to the my_socketpair in global.sym. */
5521 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5522 #ifdef HAS_SOCKETPAIR
5523 return socketpair(family, type, protocol, fd);
5532 =for apidoc sv_nosharing
5534 Dummy routine which "shares" an SV when there is no sharing module present.
5535 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5536 Exists to avoid test for a NULL function pointer and because it could
5537 potentially warn under some level of strict-ness.
5543 Perl_sv_nosharing(pTHX_ SV *sv)
5545 PERL_UNUSED_CONTEXT;
5546 PERL_UNUSED_ARG(sv);
5551 =for apidoc sv_destroyable
5553 Dummy routine which reports that object can be destroyed when there is no
5554 sharing module present. It ignores its single SV argument, and returns
5555 'true'. Exists to avoid test for a NULL function pointer and because it
5556 could potentially warn under some level of strict-ness.
5562 Perl_sv_destroyable(pTHX_ SV *sv)
5564 PERL_UNUSED_CONTEXT;
5565 PERL_UNUSED_ARG(sv);
5570 Perl_parse_unicode_opts(pTHX_ const char **popt)
5572 const char *p = *popt;
5575 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5579 opt = (U32) atoi(p);
5582 if (*p && *p != '\n' && *p != '\r')
5583 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
5588 case PERL_UNICODE_STDIN:
5589 opt |= PERL_UNICODE_STDIN_FLAG; break;
5590 case PERL_UNICODE_STDOUT:
5591 opt |= PERL_UNICODE_STDOUT_FLAG; break;
5592 case PERL_UNICODE_STDERR:
5593 opt |= PERL_UNICODE_STDERR_FLAG; break;
5594 case PERL_UNICODE_STD:
5595 opt |= PERL_UNICODE_STD_FLAG; break;
5596 case PERL_UNICODE_IN:
5597 opt |= PERL_UNICODE_IN_FLAG; break;
5598 case PERL_UNICODE_OUT:
5599 opt |= PERL_UNICODE_OUT_FLAG; break;
5600 case PERL_UNICODE_INOUT:
5601 opt |= PERL_UNICODE_INOUT_FLAG; break;
5602 case PERL_UNICODE_LOCALE:
5603 opt |= PERL_UNICODE_LOCALE_FLAG; break;
5604 case PERL_UNICODE_ARGV:
5605 opt |= PERL_UNICODE_ARGV_FLAG; break;
5606 case PERL_UNICODE_UTF8CACHEASSERT:
5607 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
5609 if (*p != '\n' && *p != '\r')
5611 "Unknown Unicode option letter '%c'", *p);
5617 opt = PERL_UNICODE_DEFAULT_FLAGS;
5619 if (opt & ~PERL_UNICODE_ALL_FLAGS)
5620 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
5621 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5633 * This is really just a quick hack which grabs various garbage
5634 * values. It really should be a real hash algorithm which
5635 * spreads the effect of every input bit onto every output bit,
5636 * if someone who knows about such things would bother to write it.
5637 * Might be a good idea to add that function to CORE as well.
5638 * No numbers below come from careful analysis or anything here,
5639 * except they are primes and SEED_C1 > 1E6 to get a full-width
5640 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5641 * probably be bigger too.
5644 # define SEED_C1 1000003
5645 #define SEED_C4 73819
5647 # define SEED_C1 25747
5648 #define SEED_C4 20639
5652 #define SEED_C5 26107
5654 #ifndef PERL_NO_DEV_RANDOM
5659 # include <starlet.h>
5660 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5661 * in 100-ns units, typically incremented ever 10 ms. */
5662 unsigned int when[2];
5664 # ifdef HAS_GETTIMEOFDAY
5665 struct timeval when;
5671 /* This test is an escape hatch, this symbol isn't set by Configure. */
5672 #ifndef PERL_NO_DEV_RANDOM
5673 #ifndef PERL_RANDOM_DEVICE
5674 /* /dev/random isn't used by default because reads from it will block
5675 * if there isn't enough entropy available. You can compile with
5676 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5677 * is enough real entropy to fill the seed. */
5678 # define PERL_RANDOM_DEVICE "/dev/urandom"
5680 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5682 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5691 _ckvmssts(sys$gettim(when));
5692 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5694 # ifdef HAS_GETTIMEOFDAY
5695 PerlProc_gettimeofday(&when,NULL);
5696 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5699 u = (U32)SEED_C1 * when;
5702 u += SEED_C3 * (U32)PerlProc_getpid();
5703 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5704 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5705 u += SEED_C5 * (U32)PTR2UV(&when);
5711 Perl_get_hash_seed(pTHX)
5714 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
5720 if (s && isDIGIT(*s))
5721 myseed = (UV)Atoul(s);
5723 #ifdef USE_HASH_SEED_EXPLICIT
5727 /* Compute a random seed */
5728 (void)seedDrand01((Rand_seed_t)seed());
5729 myseed = (UV)(Drand01() * (NV)UV_MAX);
5730 #if RANDBITS < (UVSIZE * 8)
5731 /* Since there are not enough randbits to to reach all
5732 * the bits of a UV, the low bits might need extra
5733 * help. Sum in another random number that will
5734 * fill in the low bits. */
5736 (UV)(Drand01() * (NV)((((UV)1) << ((UVSIZE * 8 - RANDBITS))) - 1));
5737 #endif /* RANDBITS < (UVSIZE * 8) */
5738 if (myseed == 0) { /* Superparanoia. */
5739 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5741 Perl_croak(aTHX_ "Your random numbers are not that random");
5744 PL_rehash_seed_set = TRUE;
5751 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5753 const char * const stashpv = CopSTASHPV(c);
5754 const char * const name = HvNAME_get(hv);
5755 PERL_UNUSED_CONTEXT;
5756 PERL_ARGS_ASSERT_STASHPV_HVNAME_MATCH;
5758 if (stashpv == name)
5760 if (stashpv && name)
5761 if (strEQ(stashpv, name))
5768 #ifdef PERL_GLOBAL_STRUCT
5770 #define PERL_GLOBAL_STRUCT_INIT
5771 #include "opcode.h" /* the ppaddr and check */
5774 Perl_init_global_struct(pTHX)
5776 struct perl_vars *plvarsp = NULL;
5777 # ifdef PERL_GLOBAL_STRUCT
5778 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5779 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5780 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5781 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5782 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5786 plvarsp = PL_VarsPtr;
5787 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5793 # define PERLVAR(var,type) /**/
5794 # define PERLVARA(var,n,type) /**/
5795 # define PERLVARI(var,type,init) plvarsp->var = init;
5796 # define PERLVARIC(var,type,init) plvarsp->var = init;
5797 # define PERLVARISC(var,init) Copy(init, plvarsp->var, sizeof(init), char);
5798 # include "perlvars.h"
5804 # ifdef PERL_GLOBAL_STRUCT
5807 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5808 if (!plvarsp->Gppaddr)
5812 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5813 if (!plvarsp->Gcheck)
5815 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5816 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5818 # ifdef PERL_SET_VARS
5819 PERL_SET_VARS(plvarsp);
5821 # undef PERL_GLOBAL_STRUCT_INIT
5826 #endif /* PERL_GLOBAL_STRUCT */
5828 #ifdef PERL_GLOBAL_STRUCT
5831 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5833 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
5834 # ifdef PERL_GLOBAL_STRUCT
5835 # ifdef PERL_UNSET_VARS
5836 PERL_UNSET_VARS(plvarsp);
5838 free(plvarsp->Gppaddr);
5839 free(plvarsp->Gcheck);
5840 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5846 #endif /* PERL_GLOBAL_STRUCT */
5850 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
5851 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
5852 * given, and you supply your own implementation.
5854 * The default implementation reads a single env var, PERL_MEM_LOG,
5855 * expecting one or more of the following:
5857 * \d+ - fd fd to write to : must be 1st (atoi)
5858 * 'm' - memlog was PERL_MEM_LOG=1
5859 * 's' - svlog was PERL_SV_LOG=1
5860 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
5862 * This makes the logger controllable enough that it can reasonably be
5863 * added to the system perl.
5866 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
5867 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5869 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5871 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
5872 * writes to. In the default logger, this is settable at runtime.
5874 #ifndef PERL_MEM_LOG_FD
5875 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5878 #ifndef PERL_MEM_LOG_NOIMPL
5880 # ifdef DEBUG_LEAKING_SCALARS
5881 # define SV_LOG_SERIAL_FMT " [%lu]"
5882 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
5884 # define SV_LOG_SERIAL_FMT
5885 # define _SV_LOG_SERIAL_ARG(sv)
5889 S_mem_log_common(enum mem_log_type mlt, const UV n,
5890 const UV typesize, const char *type_name, const SV *sv,
5891 Malloc_t oldalloc, Malloc_t newalloc,
5892 const char *filename, const int linenumber,
5893 const char *funcname)
5897 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
5899 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
5902 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
5904 /* We can't use SVs or PerlIO for obvious reasons,
5905 * so we'll use stdio and low-level IO instead. */
5906 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5908 # ifdef HAS_GETTIMEOFDAY
5909 # define MEM_LOG_TIME_FMT "%10d.%06d: "
5910 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
5912 gettimeofday(&tv, 0);
5914 # define MEM_LOG_TIME_FMT "%10d: "
5915 # define MEM_LOG_TIME_ARG (int)when
5919 /* If there are other OS specific ways of hires time than
5920 * gettimeofday() (see ext/Time-HiRes), the easiest way is
5921 * probably that they would be used to fill in the struct
5925 int fd = atoi(pmlenv);
5927 fd = PERL_MEM_LOG_FD;
5929 if (strchr(pmlenv, 't')) {
5930 len = my_snprintf(buf, sizeof(buf),
5931 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
5932 PerlLIO_write(fd, buf, len);
5936 len = my_snprintf(buf, sizeof(buf),
5937 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5938 " %s = %"IVdf": %"UVxf"\n",
5939 filename, linenumber, funcname, n, typesize,
5940 type_name, n * typesize, PTR2UV(newalloc));
5943 len = my_snprintf(buf, sizeof(buf),
5944 "realloc: %s:%d:%s: %"IVdf" %"UVuf
5945 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5946 filename, linenumber, funcname, n, typesize,
5947 type_name, n * typesize, PTR2UV(oldalloc),
5951 len = my_snprintf(buf, sizeof(buf),
5952 "free: %s:%d:%s: %"UVxf"\n",
5953 filename, linenumber, funcname,
5958 len = my_snprintf(buf, sizeof(buf),
5959 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
5960 mlt == MLT_NEW_SV ? "new" : "del",
5961 filename, linenumber, funcname,
5962 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
5967 PerlLIO_write(fd, buf, len);
5971 #endif /* !PERL_MEM_LOG_NOIMPL */
5973 #ifndef PERL_MEM_LOG_NOIMPL
5975 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
5976 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
5978 /* this is suboptimal, but bug compatible. User is providing their
5979 own implemenation, but is getting these functions anyway, and they
5980 do nothing. But _NOIMPL users should be able to cope or fix */
5982 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
5983 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
5987 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
5989 const char *filename, const int linenumber,
5990 const char *funcname)
5992 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
5993 NULL, NULL, newalloc,
5994 filename, linenumber, funcname);
5999 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
6000 Malloc_t oldalloc, Malloc_t newalloc,
6001 const char *filename, const int linenumber,
6002 const char *funcname)
6004 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
6005 NULL, oldalloc, newalloc,
6006 filename, linenumber, funcname);
6011 Perl_mem_log_free(Malloc_t oldalloc,
6012 const char *filename, const int linenumber,
6013 const char *funcname)
6015 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
6016 filename, linenumber, funcname);
6021 Perl_mem_log_new_sv(const SV *sv,
6022 const char *filename, const int linenumber,
6023 const char *funcname)
6025 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
6026 filename, linenumber, funcname);
6030 Perl_mem_log_del_sv(const SV *sv,
6031 const char *filename, const int linenumber,
6032 const char *funcname)
6034 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
6035 filename, linenumber, funcname);
6038 #endif /* PERL_MEM_LOG */
6041 =for apidoc my_sprintf
6043 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
6044 the length of the string written to the buffer. Only rare pre-ANSI systems
6045 need the wrapper function - usually this is a direct call to C<sprintf>.
6049 #ifndef SPRINTF_RETURNS_STRLEN
6051 Perl_my_sprintf(char *buffer, const char* pat, ...)
6054 PERL_ARGS_ASSERT_MY_SPRINTF;
6055 va_start(args, pat);
6056 vsprintf(buffer, pat, args);
6058 return strlen(buffer);
6063 =for apidoc my_snprintf
6065 The C library C<snprintf> functionality, if available and
6066 standards-compliant (uses C<vsnprintf>, actually). However, if the
6067 C<vsnprintf> is not available, will unfortunately use the unsafe
6068 C<vsprintf> which can overrun the buffer (there is an overrun check,
6069 but that may be too late). Consider using C<sv_vcatpvf> instead, or
6070 getting C<vsnprintf>.
6075 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
6080 PERL_ARGS_ASSERT_MY_SNPRINTF;
6081 va_start(ap, format);
6082 #ifdef HAS_VSNPRINTF
6083 retval = vsnprintf(buffer, len, format, ap);
6085 retval = vsprintf(buffer, format, ap);
6088 /* vsnprintf() shows failure with >= len, vsprintf() with < 0 */
6089 if (retval < 0 || (len > 0 && (Size_t)retval >= len))
6090 Perl_croak(aTHX_ "panic: my_snprintf buffer overflow");
6095 =for apidoc my_vsnprintf
6097 The C library C<vsnprintf> if available and standards-compliant.
6098 However, if if the C<vsnprintf> is not available, will unfortunately
6099 use the unsafe C<vsprintf> which can overrun the buffer (there is an
6100 overrun check, but that may be too late). Consider using
6101 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
6106 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
6113 PERL_ARGS_ASSERT_MY_VSNPRINTF;
6115 Perl_va_copy(ap, apc);
6116 # ifdef HAS_VSNPRINTF
6117 retval = vsnprintf(buffer, len, format, apc);
6119 retval = vsprintf(buffer, format, apc);
6122 # ifdef HAS_VSNPRINTF
6123 retval = vsnprintf(buffer, len, format, ap);
6125 retval = vsprintf(buffer, format, ap);
6127 #endif /* #ifdef NEED_VA_COPY */
6128 /* vsnprintf() shows failure with >= len, vsprintf() with < 0 */
6129 if (retval < 0 || (len > 0 && (Size_t)retval >= len))
6130 Perl_croak(aTHX_ "panic: my_vsnprintf buffer overflow");
6135 Perl_my_clearenv(pTHX)
6138 #if ! defined(PERL_MICRO)
6139 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
6141 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
6142 # if defined(USE_ENVIRON_ARRAY)
6143 # if defined(USE_ITHREADS)
6144 /* only the parent thread can clobber the process environment */
6145 if (PL_curinterp == aTHX)
6146 # endif /* USE_ITHREADS */
6148 # if ! defined(PERL_USE_SAFE_PUTENV)
6149 if ( !PL_use_safe_putenv) {
6151 if (environ == PL_origenviron)
6152 environ = (char**)safesysmalloc(sizeof(char*));
6154 for (i = 0; environ[i]; i++)
6155 (void)safesysfree(environ[i]);
6158 # else /* PERL_USE_SAFE_PUTENV */
6159 # if defined(HAS_CLEARENV)
6161 # elif defined(HAS_UNSETENV)
6162 int bsiz = 80; /* Most envvar names will be shorter than this. */
6163 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
6164 char *buf = (char*)safesysmalloc(bufsiz);
6165 while (*environ != NULL) {
6166 char *e = strchr(*environ, '=');
6167 int l = e ? e - *environ : (int)strlen(*environ);
6169 (void)safesysfree(buf);
6170 bsiz = l + 1; /* + 1 for the \0. */
6171 buf = (char*)safesysmalloc(bufsiz);
6173 memcpy(buf, *environ, l);
6175 (void)unsetenv(buf);
6177 (void)safesysfree(buf);
6178 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
6179 /* Just null environ and accept the leakage. */
6181 # endif /* HAS_CLEARENV || HAS_UNSETENV */
6182 # endif /* ! PERL_USE_SAFE_PUTENV */
6184 # endif /* USE_ENVIRON_ARRAY */
6185 # endif /* PERL_IMPLICIT_SYS || WIN32 */
6186 #endif /* PERL_MICRO */
6189 #ifdef PERL_IMPLICIT_CONTEXT
6191 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
6192 the global PL_my_cxt_index is incremented, and that value is assigned to
6193 that module's static my_cxt_index (who's address is passed as an arg).
6194 Then, for each interpreter this function is called for, it makes sure a
6195 void* slot is available to hang the static data off, by allocating or
6196 extending the interpreter's PL_my_cxt_list array */
6198 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
6200 Perl_my_cxt_init(pTHX_ int *index, size_t size)
6204 PERL_ARGS_ASSERT_MY_CXT_INIT;
6206 /* this module hasn't been allocated an index yet */
6207 #if defined(USE_ITHREADS)
6208 MUTEX_LOCK(&PL_my_ctx_mutex);
6210 *index = PL_my_cxt_index++;
6211 #if defined(USE_ITHREADS)
6212 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6216 /* make sure the array is big enough */
6217 if (PL_my_cxt_size <= *index) {
6218 if (PL_my_cxt_size) {
6219 while (PL_my_cxt_size <= *index)
6220 PL_my_cxt_size *= 2;
6221 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6224 PL_my_cxt_size = 16;
6225 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6228 /* newSV() allocates one more than needed */
6229 p = (void*)SvPVX(newSV(size-1));
6230 PL_my_cxt_list[*index] = p;
6231 Zero(p, size, char);
6235 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6238 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
6243 PERL_ARGS_ASSERT_MY_CXT_INDEX;
6245 for (index = 0; index < PL_my_cxt_index; index++) {
6246 const char *key = PL_my_cxt_keys[index];
6247 /* try direct pointer compare first - there are chances to success,
6248 * and it's much faster.
6250 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
6257 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
6263 PERL_ARGS_ASSERT_MY_CXT_INIT;
6265 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
6267 /* this module hasn't been allocated an index yet */
6268 #if defined(USE_ITHREADS)
6269 MUTEX_LOCK(&PL_my_ctx_mutex);
6271 index = PL_my_cxt_index++;
6272 #if defined(USE_ITHREADS)
6273 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6277 /* make sure the array is big enough */
6278 if (PL_my_cxt_size <= index) {
6279 int old_size = PL_my_cxt_size;
6281 if (PL_my_cxt_size) {
6282 while (PL_my_cxt_size <= index)
6283 PL_my_cxt_size *= 2;
6284 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6285 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6288 PL_my_cxt_size = 16;
6289 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6290 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6292 for (i = old_size; i < PL_my_cxt_size; i++) {
6293 PL_my_cxt_keys[i] = 0;
6294 PL_my_cxt_list[i] = 0;
6297 PL_my_cxt_keys[index] = my_cxt_key;
6298 /* newSV() allocates one more than needed */
6299 p = (void*)SvPVX(newSV(size-1));
6300 PL_my_cxt_list[index] = p;
6301 Zero(p, size, char);
6304 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6305 #endif /* PERL_IMPLICIT_CONTEXT */
6309 Perl_my_strlcat(char *dst, const char *src, Size_t size)
6311 Size_t used, length, copy;
6314 length = strlen(src);
6315 if (size > 0 && used < size - 1) {
6316 copy = (length >= size - used) ? size - used - 1 : length;
6317 memcpy(dst + used, src, copy);
6318 dst[used + copy] = '\0';
6320 return used + length;
6326 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
6328 Size_t length, copy;
6330 length = strlen(src);
6332 copy = (length >= size) ? size - 1 : length;
6333 memcpy(dst, src, copy);
6340 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
6341 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
6342 long _ftol( double ); /* Defined by VC6 C libs. */
6343 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
6347 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
6350 SV * const dbsv = GvSVn(PL_DBsub);
6351 /* We do not care about using sv to call CV;
6352 * it's for informational purposes only.
6355 PERL_ARGS_ASSERT_GET_DB_SUB;
6358 if (!PERLDB_SUB_NN) {
6359 GV * const gv = CvGV(cv);
6361 if ( svp && ((CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
6362 || strEQ(GvNAME(gv), "END")
6363 || ((GvCV(gv) != cv) && /* Could be imported, and old sub redefined. */
6364 !( (SvTYPE(*svp) == SVt_PVGV)
6365 && (GvCV((const GV *)*svp) == cv) )))) {
6366 /* Use GV from the stack as a fallback. */
6367 /* GV is potentially non-unique, or contain different CV. */
6368 SV * const tmp = newRV(MUTABLE_SV(cv));
6369 sv_setsv(dbsv, tmp);
6373 gv_efullname3(dbsv, gv, NULL);
6377 const int type = SvTYPE(dbsv);
6378 if (type < SVt_PVIV && type != SVt_IV)
6379 sv_upgrade(dbsv, SVt_PVIV);
6380 (void)SvIOK_on(dbsv);
6381 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
6386 Perl_my_dirfd(pTHX_ DIR * dir) {
6388 /* Most dirfd implementations have problems when passed NULL. */
6393 #elif defined(HAS_DIR_DD_FD)
6396 Perl_die(aTHX_ PL_no_func, "dirfd");
6403 Perl_get_re_arg(pTHX_ SV *sv) {
6409 sv = MUTABLE_SV(SvRV(sv));
6410 if (SvTYPE(sv) == SVt_REGEXP)
6411 return (REGEXP*) sv;
6419 * c-indentation-style: bsd
6421 * indent-tabs-mode: t
6424 * ex: set ts=8 sts=4 sw=4 noet: