3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * 'Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content.' --Gandalf to Pippin
15 * [p.598 of _The Lord of the Rings_, III/xi: "The PalantÃr"]
18 /* This file contains assorted utility routines.
19 * Which is a polite way of saying any stuff that people couldn't think of
20 * a better place for. Amongst other things, it includes the warning and
21 * dieing stuff, plus wrappers for malloc code.
25 #define PERL_IN_UTIL_C
30 #include "perliol.h" /* For PerlIOUnix_refcnt */
36 # define SIG_ERR ((Sighandler_t) -1)
41 /* Missing protos on LynxOS */
47 # include <sys/select.h>
53 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
54 # define FD_CLOEXEC 1 /* NeXT needs this */
57 /* NOTE: Do not call the next three routines directly. Use the macros
58 * in handy.h, so that we can easily redefine everything to do tracking of
59 * allocated hunks back to the original New to track down any memory leaks.
60 * XXX This advice seems to be widely ignored :-( --AD August 1996.
63 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
64 # define ALWAYS_NEED_THX
67 /* paranoid version of system's malloc() */
70 Perl_safesysmalloc(MEM_SIZE size)
72 #ifdef ALWAYS_NEED_THX
78 PerlIO_printf(Perl_error_log,
79 "Allocation too large: %lx\n", size) FLUSH;
82 #endif /* HAS_64K_LIMIT */
83 #ifdef PERL_TRACK_MEMPOOL
87 if ((SSize_t)size < 0)
88 Perl_croak_nocontext("panic: malloc, size=%"UVuf, (UV) size);
90 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
91 PERL_ALLOC_CHECK(ptr);
93 #ifdef PERL_TRACK_MEMPOOL
94 struct perl_memory_debug_header *const header
95 = (struct perl_memory_debug_header *)ptr;
99 PoisonNew(((char *)ptr), size, char);
102 #ifdef PERL_TRACK_MEMPOOL
103 header->interpreter = aTHX;
104 /* Link us into the list. */
105 header->prev = &PL_memory_debug_header;
106 header->next = PL_memory_debug_header.next;
107 PL_memory_debug_header.next = header;
108 header->next->prev = header;
112 ptr = (Malloc_t)((char*)ptr+sTHX);
114 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
118 #ifndef ALWAYS_NEED_THX
130 /* paranoid version of system's realloc() */
133 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
135 #ifdef ALWAYS_NEED_THX
139 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
140 Malloc_t PerlMem_realloc();
141 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
145 PerlIO_printf(Perl_error_log,
146 "Reallocation too large: %lx\n", size) FLUSH;
149 #endif /* HAS_64K_LIMIT */
156 return safesysmalloc(size);
157 #ifdef PERL_TRACK_MEMPOOL
158 where = (Malloc_t)((char*)where-sTHX);
161 struct perl_memory_debug_header *const header
162 = (struct perl_memory_debug_header *)where;
164 if (header->interpreter != aTHX) {
165 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
166 header->interpreter, aTHX);
168 assert(header->next->prev == header);
169 assert(header->prev->next == header);
171 if (header->size > size) {
172 const MEM_SIZE freed_up = header->size - size;
173 char *start_of_freed = ((char *)where) + size;
174 PoisonFree(start_of_freed, freed_up, char);
181 if ((SSize_t)size < 0)
182 Perl_croak_nocontext("panic: realloc, size=%"UVuf, (UV)size);
184 ptr = (Malloc_t)PerlMem_realloc(where,size);
185 PERL_ALLOC_CHECK(ptr);
187 /* MUST do this fixup first, before doing ANYTHING else, as anything else
188 might allocate memory/free/move memory, and until we do the fixup, it
189 may well be chasing (and writing to) free memory. */
190 #ifdef PERL_TRACK_MEMPOOL
192 struct perl_memory_debug_header *const header
193 = (struct perl_memory_debug_header *)ptr;
196 if (header->size < size) {
197 const MEM_SIZE fresh = size - header->size;
198 char *start_of_fresh = ((char *)ptr) + size;
199 PoisonNew(start_of_fresh, fresh, char);
203 header->next->prev = header;
204 header->prev->next = header;
206 ptr = (Malloc_t)((char*)ptr+sTHX);
210 /* In particular, must do that fixup above before logging anything via
211 *printf(), as it can reallocate memory, which can cause SEGVs. */
213 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
214 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
221 #ifndef ALWAYS_NEED_THX
233 /* safe version of system's free() */
236 Perl_safesysfree(Malloc_t where)
238 #ifdef ALWAYS_NEED_THX
243 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
245 #ifdef PERL_TRACK_MEMPOOL
246 where = (Malloc_t)((char*)where-sTHX);
248 struct perl_memory_debug_header *const header
249 = (struct perl_memory_debug_header *)where;
251 if (header->interpreter != aTHX) {
252 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
253 header->interpreter, aTHX);
256 Perl_croak_nocontext("panic: duplicate free");
259 Perl_croak_nocontext("panic: bad free, header->next==NULL");
260 if (header->next->prev != header || header->prev->next != header) {
261 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
262 "header=%p, ->prev->next=%p",
263 header->next->prev, header,
266 /* Unlink us from the chain. */
267 header->next->prev = header->prev;
268 header->prev->next = header->next;
270 PoisonNew(where, header->size, char);
272 /* Trigger the duplicate free warning. */
280 /* safe version of system's calloc() */
283 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
285 #ifdef ALWAYS_NEED_THX
289 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
290 MEM_SIZE total_size = 0;
293 /* Even though calloc() for zero bytes is strange, be robust. */
294 if (size && (count <= MEM_SIZE_MAX / size)) {
295 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
296 total_size = size * count;
300 Perl_croak_memory_wrap();
301 #ifdef PERL_TRACK_MEMPOOL
302 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
305 Perl_croak_memory_wrap();
308 if (total_size > 0xffff) {
309 PerlIO_printf(Perl_error_log,
310 "Allocation too large: %lx\n", total_size) FLUSH;
313 #endif /* HAS_64K_LIMIT */
315 if ((SSize_t)size < 0 || (SSize_t)count < 0)
316 Perl_croak_nocontext("panic: calloc, size=%"UVuf", count=%"UVuf,
317 (UV)size, (UV)count);
319 #ifdef PERL_TRACK_MEMPOOL
320 /* Have to use malloc() because we've added some space for our tracking
322 /* malloc(0) is non-portable. */
323 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
325 /* Use calloc() because it might save a memset() if the memory is fresh
326 and clean from the OS. */
328 ptr = (Malloc_t)PerlMem_calloc(count, size);
329 else /* calloc(0) is non-portable. */
330 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
332 PERL_ALLOC_CHECK(ptr);
333 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)total_size));
335 #ifdef PERL_TRACK_MEMPOOL
337 struct perl_memory_debug_header *const header
338 = (struct perl_memory_debug_header *)ptr;
340 memset((void*)ptr, 0, total_size);
341 header->interpreter = aTHX;
342 /* Link us into the list. */
343 header->prev = &PL_memory_debug_header;
344 header->next = PL_memory_debug_header.next;
345 PL_memory_debug_header.next = header;
346 header->next->prev = header;
348 header->size = total_size;
350 ptr = (Malloc_t)((char*)ptr+sTHX);
356 #ifndef ALWAYS_NEED_THX
365 /* These must be defined when not using Perl's malloc for binary
370 Malloc_t Perl_malloc (MEM_SIZE nbytes)
373 return (Malloc_t)PerlMem_malloc(nbytes);
376 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
379 return (Malloc_t)PerlMem_calloc(elements, size);
382 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
385 return (Malloc_t)PerlMem_realloc(where, nbytes);
388 Free_t Perl_mfree (Malloc_t where)
396 /* copy a string up to some (non-backslashed) delimiter, if any */
399 Perl_delimcpy(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen)
403 PERL_ARGS_ASSERT_DELIMCPY;
405 for (tolen = 0; from < fromend; from++, tolen++) {
407 if (from[1] != delim) {
414 else if (*from == delim)
425 /* return ptr to little string in big string, NULL if not found */
426 /* This routine was donated by Corey Satten. */
429 Perl_instr(const char *big, const char *little)
432 PERL_ARGS_ASSERT_INSTR;
434 /* libc prior to 4.6.27 did not work properly on a NULL 'little' */
437 return strstr((char*)big, (char*)little);
440 /* same as instr but allow embedded nulls. The end pointers point to 1 beyond
441 * the final character desired to be checked */
444 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
446 PERL_ARGS_ASSERT_NINSTR;
450 const char first = *little;
452 bigend -= lend - little++;
454 while (big <= bigend) {
455 if (*big++ == first) {
456 for (x=big,s=little; s < lend; x++,s++) {
460 return (char*)(big-1);
467 /* reverse of the above--find last substring */
470 Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
473 const I32 first = *little;
474 const char * const littleend = lend;
476 PERL_ARGS_ASSERT_RNINSTR;
478 if (little >= littleend)
479 return (char*)bigend;
481 big = bigend - (littleend - little++);
482 while (big >= bigbeg) {
486 for (x=big+2,s=little; s < littleend; /**/ ) {
495 return (char*)(big+1);
500 /* As a space optimization, we do not compile tables for strings of length
501 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
502 special-cased in fbm_instr().
504 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
507 =head1 Miscellaneous Functions
509 =for apidoc fbm_compile
511 Analyses the string in order to make fast searches on it using fbm_instr()
512 -- the Boyer-Moore algorithm.
518 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
528 PERL_ARGS_ASSERT_FBM_COMPILE;
530 if (isGV_with_GP(sv))
536 if (flags & FBMcf_TAIL) {
537 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
538 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
539 if (mg && mg->mg_len >= 0)
542 s = (U8*)SvPV_force_mutable(sv, len);
543 if (len == 0) /* TAIL might be on a zero-length string. */
545 SvUPGRADE(sv, SVt_PVMG);
550 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
551 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
552 to call SvVALID_off() if the scalar was assigned to.
554 The comment itself (and "deeper magic" below) date back to
555 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
557 where the magic (presumably) was that the scalar had a BM table hidden
560 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
561 the table instead of the previous (somewhat hacky) approach of co-opting
562 the string buffer and storing it after the string. */
564 assert(!mg_find(sv, PERL_MAGIC_bm));
565 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
569 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
571 const U8 mlen = (len>255) ? 255 : (U8)len;
572 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
575 Newx(table, 256, U8);
576 memset((void*)table, mlen, 256);
577 mg->mg_ptr = (char *)table;
580 s += len - 1; /* last char */
583 if (table[*s] == mlen)
589 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
590 for (i = 0; i < len; i++) {
591 if (PL_freq[s[i]] < frequency) {
593 frequency = PL_freq[s[i]];
596 BmRARE(sv) = s[rarest];
597 BmPREVIOUS(sv) = rarest;
598 BmUSEFUL(sv) = 100; /* Initial value */
599 if (flags & FBMcf_TAIL)
601 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
602 BmRARE(sv), BmPREVIOUS(sv)));
605 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
606 /* If SvTAIL is actually due to \Z or \z, this gives false positives
610 =for apidoc fbm_instr
612 Returns the location of the SV in the string delimited by C<big> and
613 C<bigend>. It returns C<NULL> if the string can't be found. The C<sv>
614 does not have to be fbm_compiled, but the search will not be as fast
621 Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
625 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
626 STRLEN littlelen = l;
627 const I32 multiline = flags & FBMrf_MULTILINE;
629 PERL_ARGS_ASSERT_FBM_INSTR;
631 if ((STRLEN)(bigend - big) < littlelen) {
632 if ( SvTAIL(littlestr)
633 && ((STRLEN)(bigend - big) == littlelen - 1)
635 || (*big == *little &&
636 memEQ((char *)big, (char *)little, littlelen - 1))))
641 switch (littlelen) { /* Special cases for 0, 1 and 2 */
643 return (char*)big; /* Cannot be SvTAIL! */
645 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
646 /* Know that bigend != big. */
647 if (bigend[-1] == '\n')
648 return (char *)(bigend - 1);
649 return (char *) bigend;
657 if (SvTAIL(littlestr))
658 return (char *) bigend;
661 if (SvTAIL(littlestr) && !multiline) {
662 if (bigend[-1] == '\n' && bigend[-2] == *little)
663 return (char*)bigend - 2;
664 if (bigend[-1] == *little)
665 return (char*)bigend - 1;
669 /* This should be better than FBM if c1 == c2, and almost
670 as good otherwise: maybe better since we do less indirection.
671 And we save a lot of memory by caching no table. */
672 const unsigned char c1 = little[0];
673 const unsigned char c2 = little[1];
678 while (s <= bigend) {
688 goto check_1char_anchor;
699 goto check_1char_anchor;
702 while (s <= bigend) {
707 goto check_1char_anchor;
716 check_1char_anchor: /* One char and anchor! */
717 if (SvTAIL(littlestr) && (*bigend == *little))
718 return (char *)bigend; /* bigend is already decremented. */
721 break; /* Only lengths 0 1 and 2 have special-case code. */
724 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
725 s = bigend - littlelen;
726 if (s >= big && bigend[-1] == '\n' && *s == *little
727 /* Automatically of length > 2 */
728 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
730 return (char*)s; /* how sweet it is */
733 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
735 return (char*)s + 1; /* how sweet it is */
739 if (!SvVALID(littlestr)) {
740 char * const b = ninstr((char*)big,(char*)bigend,
741 (char*)little, (char*)little + littlelen);
743 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
744 /* Chop \n from littlestr: */
745 s = bigend - littlelen + 1;
747 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
757 if (littlelen > (STRLEN)(bigend - big))
761 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
762 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
763 const unsigned char *oldlittle;
765 --littlelen; /* Last char found by table lookup */
768 little += littlelen; /* last char */
774 if ((tmp = table[*s])) {
775 if ((s += tmp) < bigend)
779 else { /* less expensive than calling strncmp() */
780 unsigned char * const olds = s;
785 if (*--s == *--little)
787 s = olds + 1; /* here we pay the price for failure */
789 if (s < bigend) /* fake up continue to outer loop */
799 && memEQ((char *)(bigend - littlelen),
800 (char *)(oldlittle - littlelen), littlelen) )
801 return (char*)bigend - littlelen;
807 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
810 PERL_ARGS_ASSERT_SCREAMINSTR;
811 PERL_UNUSED_ARG(bigstr);
812 PERL_UNUSED_ARG(littlestr);
813 PERL_UNUSED_ARG(start_shift);
814 PERL_UNUSED_ARG(end_shift);
815 PERL_UNUSED_ARG(old_posp);
816 PERL_UNUSED_ARG(last);
818 /* This function must only ever be called on a scalar with study magic,
819 but those do not happen any more. */
820 Perl_croak(aTHX_ "panic: screaminstr");
827 Returns true if the leading len bytes of the strings s1 and s2 are the same
828 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
829 match themselves and their opposite case counterparts. Non-cased and non-ASCII
830 range bytes match only themselves.
837 Perl_foldEQ(const char *s1, const char *s2, I32 len)
839 const U8 *a = (const U8 *)s1;
840 const U8 *b = (const U8 *)s2;
842 PERL_ARGS_ASSERT_FOLDEQ;
847 if (*a != *b && *a != PL_fold[*b])
854 Perl_foldEQ_latin1(const char *s1, const char *s2, I32 len)
856 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
857 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
858 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
859 * does it check that the strings each have at least 'len' characters */
861 const U8 *a = (const U8 *)s1;
862 const U8 *b = (const U8 *)s2;
864 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
869 if (*a != *b && *a != PL_fold_latin1[*b]) {
878 =for apidoc foldEQ_locale
880 Returns true if the leading len bytes of the strings s1 and s2 are the same
881 case-insensitively in the current locale; false otherwise.
887 Perl_foldEQ_locale(const char *s1, const char *s2, I32 len)
890 const U8 *a = (const U8 *)s1;
891 const U8 *b = (const U8 *)s2;
893 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
898 if (*a != *b && *a != PL_fold_locale[*b])
905 /* copy a string to a safe spot */
908 =head1 Memory Management
912 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
913 string which is a duplicate of C<pv>. The size of the string is
914 determined by C<strlen()>. The memory allocated for the new string can
915 be freed with the C<Safefree()> function.
921 Perl_savepv(pTHX_ const char *pv)
928 const STRLEN pvlen = strlen(pv)+1;
929 Newx(newaddr, pvlen, char);
930 return (char*)memcpy(newaddr, pv, pvlen);
934 /* same thing but with a known length */
939 Perl's version of what C<strndup()> would be if it existed. Returns a
940 pointer to a newly allocated string which is a duplicate of the first
941 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
942 the new string can be freed with the C<Safefree()> function.
948 Perl_savepvn(pTHX_ const char *pv, I32 len)
955 Newx(newaddr,len+1,char);
956 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
958 /* might not be null terminated */
960 return (char *) CopyD(pv,newaddr,len,char);
963 return (char *) ZeroD(newaddr,len+1,char);
968 =for apidoc savesharedpv
970 A version of C<savepv()> which allocates the duplicate string in memory
971 which is shared between threads.
976 Perl_savesharedpv(pTHX_ const char *pv)
983 pvlen = strlen(pv)+1;
984 newaddr = (char*)PerlMemShared_malloc(pvlen);
988 return (char*)memcpy(newaddr, pv, pvlen);
992 =for apidoc savesharedpvn
994 A version of C<savepvn()> which allocates the duplicate string in memory
995 which is shared between threads. (With the specific difference that a NULL
996 pointer is not acceptable)
1001 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1003 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1005 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1010 newaddr[len] = '\0';
1011 return (char*)memcpy(newaddr, pv, len);
1015 =for apidoc savesvpv
1017 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1018 the passed in SV using C<SvPV()>
1024 Perl_savesvpv(pTHX_ SV *sv)
1027 const char * const pv = SvPV_const(sv, len);
1030 PERL_ARGS_ASSERT_SAVESVPV;
1033 Newx(newaddr,len,char);
1034 return (char *) CopyD(pv,newaddr,len,char);
1038 =for apidoc savesharedsvpv
1040 A version of C<savesharedpv()> which allocates the duplicate string in
1041 memory which is shared between threads.
1047 Perl_savesharedsvpv(pTHX_ SV *sv)
1050 const char * const pv = SvPV_const(sv, len);
1052 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1054 return savesharedpvn(pv, len);
1057 /* the SV for Perl_form() and mess() is not kept in an arena */
1066 if (PL_phase != PERL_PHASE_DESTRUCT)
1067 return newSVpvs_flags("", SVs_TEMP);
1072 /* Create as PVMG now, to avoid any upgrading later */
1074 Newxz(any, 1, XPVMG);
1075 SvFLAGS(sv) = SVt_PVMG;
1076 SvANY(sv) = (void*)any;
1078 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1083 #if defined(PERL_IMPLICIT_CONTEXT)
1085 Perl_form_nocontext(const char* pat, ...)
1090 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1091 va_start(args, pat);
1092 retval = vform(pat, &args);
1096 #endif /* PERL_IMPLICIT_CONTEXT */
1099 =head1 Miscellaneous Functions
1102 Takes a sprintf-style format pattern and conventional
1103 (non-SV) arguments and returns the formatted string.
1105 (char *) Perl_form(pTHX_ const char* pat, ...)
1107 can be used any place a string (char *) is required:
1109 char * s = Perl_form("%d.%d",major,minor);
1111 Uses a single private buffer so if you want to format several strings you
1112 must explicitly copy the earlier strings away (and free the copies when you
1119 Perl_form(pTHX_ const char* pat, ...)
1123 PERL_ARGS_ASSERT_FORM;
1124 va_start(args, pat);
1125 retval = vform(pat, &args);
1131 Perl_vform(pTHX_ const char *pat, va_list *args)
1133 SV * const sv = mess_alloc();
1134 PERL_ARGS_ASSERT_VFORM;
1135 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1140 =for apidoc Am|SV *|mess|const char *pat|...
1142 Take a sprintf-style format pattern and argument list. These are used to
1143 generate a string message. If the message does not end with a newline,
1144 then it will be extended with some indication of the current location
1145 in the code, as described for L</mess_sv>.
1147 Normally, the resulting message is returned in a new mortal SV.
1148 During global destruction a single SV may be shared between uses of
1154 #if defined(PERL_IMPLICIT_CONTEXT)
1156 Perl_mess_nocontext(const char *pat, ...)
1161 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1162 va_start(args, pat);
1163 retval = vmess(pat, &args);
1167 #endif /* PERL_IMPLICIT_CONTEXT */
1170 Perl_mess(pTHX_ const char *pat, ...)
1174 PERL_ARGS_ASSERT_MESS;
1175 va_start(args, pat);
1176 retval = vmess(pat, &args);
1182 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1185 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1187 PERL_ARGS_ASSERT_CLOSEST_COP;
1189 if (!o || o == PL_op)
1192 if (o->op_flags & OPf_KIDS) {
1194 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1197 /* If the OP_NEXTSTATE has been optimised away we can still use it
1198 * the get the file and line number. */
1200 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1201 cop = (const COP *)kid;
1203 /* Keep searching, and return when we've found something. */
1205 new_cop = closest_cop(cop, kid);
1211 /* Nothing found. */
1217 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1219 Expands a message, intended for the user, to include an indication of
1220 the current location in the code, if the message does not already appear
1223 C<basemsg> is the initial message or object. If it is a reference, it
1224 will be used as-is and will be the result of this function. Otherwise it
1225 is used as a string, and if it already ends with a newline, it is taken
1226 to be complete, and the result of this function will be the same string.
1227 If the message does not end with a newline, then a segment such as C<at
1228 foo.pl line 37> will be appended, and possibly other clauses indicating
1229 the current state of execution. The resulting message will end with a
1232 Normally, the resulting message is returned in a new mortal SV.
1233 During global destruction a single SV may be shared between uses of this
1234 function. If C<consume> is true, then the function is permitted (but not
1235 required) to modify and return C<basemsg> instead of allocating a new SV.
1241 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1246 PERL_ARGS_ASSERT_MESS_SV;
1248 if (SvROK(basemsg)) {
1254 sv_setsv(sv, basemsg);
1259 if (SvPOK(basemsg) && consume) {
1264 sv_copypv(sv, basemsg);
1267 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1269 * Try and find the file and line for PL_op. This will usually be
1270 * PL_curcop, but it might be a cop that has been optimised away. We
1271 * can try to find such a cop by searching through the optree starting
1272 * from the sibling of PL_curcop.
1275 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1280 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1281 OutCopFILE(cop), (IV)CopLINE(cop));
1282 /* Seems that GvIO() can be untrustworthy during global destruction. */
1283 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1284 && IoLINES(GvIOp(PL_last_in_gv)))
1287 const bool line_mode = (RsSIMPLE(PL_rs) &&
1288 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1289 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1290 SVfARG(PL_last_in_gv == PL_argvgv
1292 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1293 line_mode ? "line" : "chunk",
1294 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1296 if (PL_phase == PERL_PHASE_DESTRUCT)
1297 sv_catpvs(sv, " during global destruction");
1298 sv_catpvs(sv, ".\n");
1304 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1306 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1307 argument list. These are used to generate a string message. If the
1308 message does not end with a newline, then it will be extended with
1309 some indication of the current location in the code, as described for
1312 Normally, the resulting message is returned in a new mortal SV.
1313 During global destruction a single SV may be shared between uses of
1320 Perl_vmess(pTHX_ const char *pat, va_list *args)
1323 SV * const sv = mess_alloc();
1325 PERL_ARGS_ASSERT_VMESS;
1327 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1328 return mess_sv(sv, 1);
1332 Perl_write_to_stderr(pTHX_ SV* msv)
1338 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1340 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1341 && (io = GvIO(PL_stderrgv))
1342 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1343 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1344 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1347 /* SFIO can really mess with your errno */
1350 PerlIO * const serr = Perl_error_log;
1352 do_print(msv, serr);
1353 (void)PerlIO_flush(serr);
1361 =head1 Warning and Dieing
1364 /* Common code used in dieing and warning */
1367 S_with_queued_errors(pTHX_ SV *ex)
1369 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1370 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1371 sv_catsv(PL_errors, ex);
1372 ex = sv_mortalcopy(PL_errors);
1373 SvCUR_set(PL_errors, 0);
1379 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1385 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1386 /* sv_2cv might call Perl_croak() or Perl_warner() */
1387 SV * const oldhook = *hook;
1395 cv = sv_2cv(oldhook, &stash, &gv, 0);
1397 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1407 exarg = newSVsv(ex);
1408 SvREADONLY_on(exarg);
1411 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1415 call_sv(MUTABLE_SV(cv), G_DISCARD);
1424 =for apidoc Am|OP *|die_sv|SV *baseex
1426 Behaves the same as L</croak_sv>, except for the return type.
1427 It should be used only where the C<OP *> return type is required.
1428 The function never actually returns.
1434 Perl_die_sv(pTHX_ SV *baseex)
1436 PERL_ARGS_ASSERT_DIE_SV;
1438 assert(0); /* NOTREACHED */
1443 =for apidoc Am|OP *|die|const char *pat|...
1445 Behaves the same as L</croak>, except for the return type.
1446 It should be used only where the C<OP *> return type is required.
1447 The function never actually returns.
1452 #if defined(PERL_IMPLICIT_CONTEXT)
1454 Perl_die_nocontext(const char* pat, ...)
1458 va_start(args, pat);
1460 assert(0); /* NOTREACHED */
1464 #endif /* PERL_IMPLICIT_CONTEXT */
1467 Perl_die(pTHX_ const char* pat, ...)
1470 va_start(args, pat);
1472 assert(0); /* NOTREACHED */
1478 =for apidoc Am|void|croak_sv|SV *baseex
1480 This is an XS interface to Perl's C<die> function.
1482 C<baseex> is the error message or object. If it is a reference, it
1483 will be used as-is. Otherwise it is used as a string, and if it does
1484 not end with a newline then it will be extended with some indication of
1485 the current location in the code, as described for L</mess_sv>.
1487 The error message or object will be used as an exception, by default
1488 returning control to the nearest enclosing C<eval>, but subject to
1489 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1490 function never returns normally.
1492 To die with a simple string message, the L</croak> function may be
1499 Perl_croak_sv(pTHX_ SV *baseex)
1501 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1502 PERL_ARGS_ASSERT_CROAK_SV;
1503 invoke_exception_hook(ex, FALSE);
1508 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1510 This is an XS interface to Perl's C<die> function.
1512 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1513 argument list. These are used to generate a string message. If the
1514 message does not end with a newline, then it will be extended with
1515 some indication of the current location in the code, as described for
1518 The error message will be used as an exception, by default
1519 returning control to the nearest enclosing C<eval>, but subject to
1520 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1521 function never returns normally.
1523 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1524 (C<$@>) will be used as an error message or object instead of building an
1525 error message from arguments. If you want to throw a non-string object,
1526 or build an error message in an SV yourself, it is preferable to use
1527 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1533 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1535 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1536 invoke_exception_hook(ex, FALSE);
1541 =for apidoc Am|void|croak|const char *pat|...
1543 This is an XS interface to Perl's C<die> function.
1545 Take a sprintf-style format pattern and argument list. These are used to
1546 generate a string message. If the message does not end with a newline,
1547 then it will be extended with some indication of the current location
1548 in the code, as described for L</mess_sv>.
1550 The error message will be used as an exception, by default
1551 returning control to the nearest enclosing C<eval>, but subject to
1552 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1553 function never returns normally.
1555 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1556 (C<$@>) will be used as an error message or object instead of building an
1557 error message from arguments. If you want to throw a non-string object,
1558 or build an error message in an SV yourself, it is preferable to use
1559 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1564 #if defined(PERL_IMPLICIT_CONTEXT)
1566 Perl_croak_nocontext(const char *pat, ...)
1570 va_start(args, pat);
1572 assert(0); /* NOTREACHED */
1575 #endif /* PERL_IMPLICIT_CONTEXT */
1578 Perl_croak(pTHX_ const char *pat, ...)
1581 va_start(args, pat);
1583 assert(0); /* NOTREACHED */
1588 =for apidoc Am|void|croak_no_modify
1590 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1591 terser object code than using C<Perl_croak>. Less code used on exception code
1592 paths reduces CPU cache pressure.
1598 Perl_croak_no_modify()
1600 Perl_croak_nocontext( "%s", PL_no_modify);
1603 /* does not return, used in util.c perlio.c and win32.c
1604 This is typically called when malloc returns NULL.
1611 /* Can't use PerlIO to write as it allocates memory */
1612 PerlLIO_write(PerlIO_fileno(Perl_error_log),
1613 PL_no_mem, sizeof(PL_no_mem)-1);
1617 /* saves machine code for a common noreturn idiom typically used in Newx*() */
1619 Perl_croak_memory_wrap(void)
1621 Perl_croak_nocontext("%s",PL_memory_wrap);
1625 /* does not return, used only in POPSTACK */
1627 Perl_croak_popstack(void)
1630 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
1635 =for apidoc Am|void|warn_sv|SV *baseex
1637 This is an XS interface to Perl's C<warn> function.
1639 C<baseex> is the error message or object. If it is a reference, it
1640 will be used as-is. Otherwise it is used as a string, and if it does
1641 not end with a newline then it will be extended with some indication of
1642 the current location in the code, as described for L</mess_sv>.
1644 The error message or object will by default be written to standard error,
1645 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1647 To warn with a simple string message, the L</warn> function may be
1654 Perl_warn_sv(pTHX_ SV *baseex)
1656 SV *ex = mess_sv(baseex, 0);
1657 PERL_ARGS_ASSERT_WARN_SV;
1658 if (!invoke_exception_hook(ex, TRUE))
1659 write_to_stderr(ex);
1663 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1665 This is an XS interface to Perl's C<warn> function.
1667 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1668 argument list. These are used to generate a string message. If the
1669 message does not end with a newline, then it will be extended with
1670 some indication of the current location in the code, as described for
1673 The error message or object will by default be written to standard error,
1674 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1676 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1682 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1684 SV *ex = vmess(pat, args);
1685 PERL_ARGS_ASSERT_VWARN;
1686 if (!invoke_exception_hook(ex, TRUE))
1687 write_to_stderr(ex);
1691 =for apidoc Am|void|warn|const char *pat|...
1693 This is an XS interface to Perl's C<warn> function.
1695 Take a sprintf-style format pattern and argument list. These are used to
1696 generate a string message. If the message does not end with a newline,
1697 then it will be extended with some indication of the current location
1698 in the code, as described for L</mess_sv>.
1700 The error message or object will by default be written to standard error,
1701 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1703 Unlike with L</croak>, C<pat> is not permitted to be null.
1708 #if defined(PERL_IMPLICIT_CONTEXT)
1710 Perl_warn_nocontext(const char *pat, ...)
1714 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1715 va_start(args, pat);
1719 #endif /* PERL_IMPLICIT_CONTEXT */
1722 Perl_warn(pTHX_ const char *pat, ...)
1725 PERL_ARGS_ASSERT_WARN;
1726 va_start(args, pat);
1731 #if defined(PERL_IMPLICIT_CONTEXT)
1733 Perl_warner_nocontext(U32 err, const char *pat, ...)
1737 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1738 va_start(args, pat);
1739 vwarner(err, pat, &args);
1742 #endif /* PERL_IMPLICIT_CONTEXT */
1745 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1747 PERL_ARGS_ASSERT_CK_WARNER_D;
1749 if (Perl_ckwarn_d(aTHX_ err)) {
1751 va_start(args, pat);
1752 vwarner(err, pat, &args);
1758 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1760 PERL_ARGS_ASSERT_CK_WARNER;
1762 if (Perl_ckwarn(aTHX_ err)) {
1764 va_start(args, pat);
1765 vwarner(err, pat, &args);
1771 Perl_warner(pTHX_ U32 err, const char* pat,...)
1774 PERL_ARGS_ASSERT_WARNER;
1775 va_start(args, pat);
1776 vwarner(err, pat, &args);
1781 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1784 PERL_ARGS_ASSERT_VWARNER;
1785 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1786 SV * const msv = vmess(pat, args);
1788 invoke_exception_hook(msv, FALSE);
1792 Perl_vwarn(aTHX_ pat, args);
1796 /* implements the ckWARN? macros */
1799 Perl_ckwarn(pTHX_ U32 w)
1802 /* If lexical warnings have not been set, use $^W. */
1804 return PL_dowarn & G_WARN_ON;
1806 return ckwarn_common(w);
1809 /* implements the ckWARN?_d macro */
1812 Perl_ckwarn_d(pTHX_ U32 w)
1815 /* If lexical warnings have not been set then default classes warn. */
1819 return ckwarn_common(w);
1823 S_ckwarn_common(pTHX_ U32 w)
1825 if (PL_curcop->cop_warnings == pWARN_ALL)
1828 if (PL_curcop->cop_warnings == pWARN_NONE)
1831 /* Check the assumption that at least the first slot is non-zero. */
1832 assert(unpackWARN1(w));
1834 /* Check the assumption that it is valid to stop as soon as a zero slot is
1836 if (!unpackWARN2(w)) {
1837 assert(!unpackWARN3(w));
1838 assert(!unpackWARN4(w));
1839 } else if (!unpackWARN3(w)) {
1840 assert(!unpackWARN4(w));
1843 /* Right, dealt with all the special cases, which are implemented as non-
1844 pointers, so there is a pointer to a real warnings mask. */
1846 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1848 } while (w >>= WARNshift);
1853 /* Set buffer=NULL to get a new one. */
1855 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1857 const MEM_SIZE len_wanted =
1858 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
1859 PERL_UNUSED_CONTEXT;
1860 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1863 (specialWARN(buffer) ?
1864 PerlMemShared_malloc(len_wanted) :
1865 PerlMemShared_realloc(buffer, len_wanted));
1867 Copy(bits, (buffer + 1), size, char);
1868 if (size < WARNsize)
1869 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
1873 /* since we've already done strlen() for both nam and val
1874 * we can use that info to make things faster than
1875 * sprintf(s, "%s=%s", nam, val)
1877 #define my_setenv_format(s, nam, nlen, val, vlen) \
1878 Copy(nam, s, nlen, char); \
1880 Copy(val, s+(nlen+1), vlen, char); \
1881 *(s+(nlen+1+vlen)) = '\0'
1883 #ifdef USE_ENVIRON_ARRAY
1884 /* VMS' my_setenv() is in vms.c */
1885 #if !defined(WIN32) && !defined(NETWARE)
1887 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1891 /* only parent thread can modify process environment */
1892 if (PL_curinterp == aTHX)
1895 #ifndef PERL_USE_SAFE_PUTENV
1896 if (!PL_use_safe_putenv) {
1897 /* most putenv()s leak, so we manipulate environ directly */
1899 const I32 len = strlen(nam);
1902 /* where does it go? */
1903 for (i = 0; environ[i]; i++) {
1904 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1908 if (environ == PL_origenviron) { /* need we copy environment? */
1914 while (environ[max])
1916 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1917 for (j=0; j<max; j++) { /* copy environment */
1918 const int len = strlen(environ[j]);
1919 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1920 Copy(environ[j], tmpenv[j], len+1, char);
1923 environ = tmpenv; /* tell exec where it is now */
1926 safesysfree(environ[i]);
1927 while (environ[i]) {
1928 environ[i] = environ[i+1];
1933 if (!environ[i]) { /* does not exist yet */
1934 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1935 environ[i+1] = NULL; /* make sure it's null terminated */
1938 safesysfree(environ[i]);
1942 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1943 /* all that work just for this */
1944 my_setenv_format(environ[i], nam, nlen, val, vlen);
1947 # if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__)
1948 # if defined(HAS_UNSETENV)
1950 (void)unsetenv(nam);
1952 (void)setenv(nam, val, 1);
1954 # else /* ! HAS_UNSETENV */
1955 (void)setenv(nam, val, 1);
1956 # endif /* HAS_UNSETENV */
1958 # if defined(HAS_UNSETENV)
1960 if (environ) /* old glibc can crash with null environ */
1961 (void)unsetenv(nam);
1963 const int nlen = strlen(nam);
1964 const int vlen = strlen(val);
1965 char * const new_env =
1966 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1967 my_setenv_format(new_env, nam, nlen, val, vlen);
1968 (void)putenv(new_env);
1970 # else /* ! HAS_UNSETENV */
1972 const int nlen = strlen(nam);
1978 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1979 /* all that work just for this */
1980 my_setenv_format(new_env, nam, nlen, val, vlen);
1981 (void)putenv(new_env);
1982 # endif /* HAS_UNSETENV */
1983 # endif /* __CYGWIN__ */
1984 #ifndef PERL_USE_SAFE_PUTENV
1990 #else /* WIN32 || NETWARE */
1993 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1997 const int nlen = strlen(nam);
2004 Newx(envstr, nlen+vlen+2, char);
2005 my_setenv_format(envstr, nam, nlen, val, vlen);
2006 (void)PerlEnv_putenv(envstr);
2010 #endif /* WIN32 || NETWARE */
2014 #ifdef UNLINK_ALL_VERSIONS
2016 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2020 PERL_ARGS_ASSERT_UNLNK;
2022 while (PerlLIO_unlink(f) >= 0)
2024 return retries ? 0 : -1;
2028 /* this is a drop-in replacement for bcopy() */
2029 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2031 Perl_my_bcopy(const char *from, char *to, I32 len)
2033 char * const retval = to;
2035 PERL_ARGS_ASSERT_MY_BCOPY;
2039 if (from - to >= 0) {
2047 *(--to) = *(--from);
2053 /* this is a drop-in replacement for memset() */
2056 Perl_my_memset(char *loc, I32 ch, I32 len)
2058 char * const retval = loc;
2060 PERL_ARGS_ASSERT_MY_MEMSET;
2070 /* this is a drop-in replacement for bzero() */
2071 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2073 Perl_my_bzero(char *loc, I32 len)
2075 char * const retval = loc;
2077 PERL_ARGS_ASSERT_MY_BZERO;
2087 /* this is a drop-in replacement for memcmp() */
2088 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2090 Perl_my_memcmp(const char *s1, const char *s2, I32 len)
2092 const U8 *a = (const U8 *)s1;
2093 const U8 *b = (const U8 *)s2;
2096 PERL_ARGS_ASSERT_MY_MEMCMP;
2101 if ((tmp = *a++ - *b++))
2106 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2109 /* This vsprintf replacement should generally never get used, since
2110 vsprintf was available in both System V and BSD 2.11. (There may
2111 be some cross-compilation or embedded set-ups where it is needed,
2114 If you encounter a problem in this function, it's probably a symptom
2115 that Configure failed to detect your system's vprintf() function.
2116 See the section on "item vsprintf" in the INSTALL file.
2118 This version may compile on systems with BSD-ish <stdio.h>,
2119 but probably won't on others.
2122 #ifdef USE_CHAR_VSPRINTF
2127 vsprintf(char *dest, const char *pat, void *args)
2131 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2132 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2133 FILE_cnt(&fakebuf) = 32767;
2135 /* These probably won't compile -- If you really need
2136 this, you'll have to figure out some other method. */
2137 fakebuf._ptr = dest;
2138 fakebuf._cnt = 32767;
2143 fakebuf._flag = _IOWRT|_IOSTRG;
2144 _doprnt(pat, args, &fakebuf); /* what a kludge */
2145 #if defined(STDIO_PTR_LVALUE)
2146 *(FILE_ptr(&fakebuf)++) = '\0';
2148 /* PerlIO has probably #defined away fputc, but we want it here. */
2150 # undef fputc /* XXX Should really restore it later */
2152 (void)fputc('\0', &fakebuf);
2154 #ifdef USE_CHAR_VSPRINTF
2157 return 0; /* perl doesn't use return value */
2161 #endif /* HAS_VPRINTF */
2164 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2166 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2175 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2177 PERL_FLUSHALL_FOR_CHILD;
2178 This = (*mode == 'w');
2182 taint_proper("Insecure %s%s", "EXEC");
2184 if (PerlProc_pipe(p) < 0)
2186 /* Try for another pipe pair for error return */
2187 if (PerlProc_pipe(pp) >= 0)
2189 while ((pid = PerlProc_fork()) < 0) {
2190 if (errno != EAGAIN) {
2191 PerlLIO_close(p[This]);
2192 PerlLIO_close(p[that]);
2194 PerlLIO_close(pp[0]);
2195 PerlLIO_close(pp[1]);
2199 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2208 /* Close parent's end of error status pipe (if any) */
2210 PerlLIO_close(pp[0]);
2211 #if defined(HAS_FCNTL) && defined(F_SETFD)
2212 /* Close error pipe automatically if exec works */
2213 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2216 /* Now dup our end of _the_ pipe to right position */
2217 if (p[THIS] != (*mode == 'r')) {
2218 PerlLIO_dup2(p[THIS], *mode == 'r');
2219 PerlLIO_close(p[THIS]);
2220 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2221 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2224 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2225 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2226 /* No automatic close - do it by hand */
2233 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2239 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2245 do_execfree(); /* free any memory malloced by child on fork */
2247 PerlLIO_close(pp[1]);
2248 /* Keep the lower of the two fd numbers */
2249 if (p[that] < p[This]) {
2250 PerlLIO_dup2(p[This], p[that]);
2251 PerlLIO_close(p[This]);
2255 PerlLIO_close(p[that]); /* close child's end of pipe */
2257 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2258 SvUPGRADE(sv,SVt_IV);
2260 PL_forkprocess = pid;
2261 /* If we managed to get status pipe check for exec fail */
2262 if (did_pipes && pid > 0) {
2267 while (n < sizeof(int)) {
2268 n1 = PerlLIO_read(pp[0],
2269 (void*)(((char*)&errkid)+n),
2275 PerlLIO_close(pp[0]);
2277 if (n) { /* Error */
2279 PerlLIO_close(p[This]);
2280 if (n != sizeof(int))
2281 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2283 pid2 = wait4pid(pid, &status, 0);
2284 } while (pid2 == -1 && errno == EINTR);
2285 errno = errkid; /* Propagate errno from kid */
2290 PerlLIO_close(pp[0]);
2291 return PerlIO_fdopen(p[This], mode);
2293 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2294 return my_syspopen4(aTHX_ NULL, mode, n, args);
2296 Perl_croak(aTHX_ "List form of piped open not implemented");
2297 return (PerlIO *) NULL;
2302 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2303 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2305 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2312 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2316 PERL_ARGS_ASSERT_MY_POPEN;
2318 PERL_FLUSHALL_FOR_CHILD;
2321 return my_syspopen(aTHX_ cmd,mode);
2324 This = (*mode == 'w');
2326 if (doexec && TAINTING_get) {
2328 taint_proper("Insecure %s%s", "EXEC");
2330 if (PerlProc_pipe(p) < 0)
2332 if (doexec && PerlProc_pipe(pp) >= 0)
2334 while ((pid = PerlProc_fork()) < 0) {
2335 if (errno != EAGAIN) {
2336 PerlLIO_close(p[This]);
2337 PerlLIO_close(p[that]);
2339 PerlLIO_close(pp[0]);
2340 PerlLIO_close(pp[1]);
2343 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2346 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2356 PerlLIO_close(pp[0]);
2357 #if defined(HAS_FCNTL) && defined(F_SETFD)
2358 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2361 if (p[THIS] != (*mode == 'r')) {
2362 PerlLIO_dup2(p[THIS], *mode == 'r');
2363 PerlLIO_close(p[THIS]);
2364 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2365 PerlLIO_close(p[THAT]);
2368 PerlLIO_close(p[THAT]);
2371 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2378 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2383 /* may or may not use the shell */
2384 do_exec3(cmd, pp[1], did_pipes);
2387 #endif /* defined OS2 */
2389 #ifdef PERLIO_USING_CRLF
2390 /* Since we circumvent IO layers when we manipulate low-level
2391 filedescriptors directly, need to manually switch to the
2392 default, binary, low-level mode; see PerlIOBuf_open(). */
2393 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2396 #ifdef PERL_USES_PL_PIDSTATUS
2397 hv_clear(PL_pidstatus); /* we have no children */
2403 do_execfree(); /* free any memory malloced by child on vfork */
2405 PerlLIO_close(pp[1]);
2406 if (p[that] < p[This]) {
2407 PerlLIO_dup2(p[This], p[that]);
2408 PerlLIO_close(p[This]);
2412 PerlLIO_close(p[that]);
2414 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2415 SvUPGRADE(sv,SVt_IV);
2417 PL_forkprocess = pid;
2418 if (did_pipes && pid > 0) {
2423 while (n < sizeof(int)) {
2424 n1 = PerlLIO_read(pp[0],
2425 (void*)(((char*)&errkid)+n),
2431 PerlLIO_close(pp[0]);
2433 if (n) { /* Error */
2435 PerlLIO_close(p[This]);
2436 if (n != sizeof(int))
2437 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2439 pid2 = wait4pid(pid, &status, 0);
2440 } while (pid2 == -1 && errno == EINTR);
2441 errno = errkid; /* Propagate errno from kid */
2446 PerlLIO_close(pp[0]);
2447 return PerlIO_fdopen(p[This], mode);
2451 FILE *djgpp_popen();
2453 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2455 PERL_FLUSHALL_FOR_CHILD;
2456 /* Call system's popen() to get a FILE *, then import it.
2457 used 0 for 2nd parameter to PerlIO_importFILE;
2460 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2463 #if defined(__LIBCATAMOUNT__)
2465 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2472 #endif /* !DOSISH */
2474 /* this is called in parent before the fork() */
2476 Perl_atfork_lock(void)
2479 #if defined(USE_ITHREADS)
2480 /* locks must be held in locking order (if any) */
2482 MUTEX_LOCK(&PL_perlio_mutex);
2485 MUTEX_LOCK(&PL_malloc_mutex);
2491 /* this is called in both parent and child after the fork() */
2493 Perl_atfork_unlock(void)
2496 #if defined(USE_ITHREADS)
2497 /* locks must be released in same order as in atfork_lock() */
2499 MUTEX_UNLOCK(&PL_perlio_mutex);
2502 MUTEX_UNLOCK(&PL_malloc_mutex);
2511 #if defined(HAS_FORK)
2513 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2518 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2519 * handlers elsewhere in the code */
2524 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2525 Perl_croak_nocontext("fork() not available");
2527 #endif /* HAS_FORK */
2532 Perl_dump_fds(pTHX_ const char *const s)
2537 PERL_ARGS_ASSERT_DUMP_FDS;
2539 PerlIO_printf(Perl_debug_log,"%s", s);
2540 for (fd = 0; fd < 32; fd++) {
2541 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2542 PerlIO_printf(Perl_debug_log," %d",fd);
2544 PerlIO_printf(Perl_debug_log,"\n");
2547 #endif /* DUMP_FDS */
2551 dup2(int oldfd, int newfd)
2553 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2556 PerlLIO_close(newfd);
2557 return fcntl(oldfd, F_DUPFD, newfd);
2559 #define DUP2_MAX_FDS 256
2560 int fdtmp[DUP2_MAX_FDS];
2566 PerlLIO_close(newfd);
2567 /* good enough for low fd's... */
2568 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2569 if (fdx >= DUP2_MAX_FDS) {
2577 PerlLIO_close(fdtmp[--fdx]);
2584 #ifdef HAS_SIGACTION
2587 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2590 struct sigaction act, oact;
2593 /* only "parent" interpreter can diddle signals */
2594 if (PL_curinterp != aTHX)
2595 return (Sighandler_t) SIG_ERR;
2598 act.sa_handler = (void(*)(int))handler;
2599 sigemptyset(&act.sa_mask);
2602 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2603 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2605 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2606 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2607 act.sa_flags |= SA_NOCLDWAIT;
2609 if (sigaction(signo, &act, &oact) == -1)
2610 return (Sighandler_t) SIG_ERR;
2612 return (Sighandler_t) oact.sa_handler;
2616 Perl_rsignal_state(pTHX_ int signo)
2618 struct sigaction oact;
2619 PERL_UNUSED_CONTEXT;
2621 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2622 return (Sighandler_t) SIG_ERR;
2624 return (Sighandler_t) oact.sa_handler;
2628 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2631 struct sigaction act;
2633 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2636 /* only "parent" interpreter can diddle signals */
2637 if (PL_curinterp != aTHX)
2641 act.sa_handler = (void(*)(int))handler;
2642 sigemptyset(&act.sa_mask);
2645 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2646 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2648 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2649 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2650 act.sa_flags |= SA_NOCLDWAIT;
2652 return sigaction(signo, &act, save);
2656 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2660 /* only "parent" interpreter can diddle signals */
2661 if (PL_curinterp != aTHX)
2665 return sigaction(signo, save, (struct sigaction *)NULL);
2668 #else /* !HAS_SIGACTION */
2671 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2673 #if defined(USE_ITHREADS) && !defined(WIN32)
2674 /* only "parent" interpreter can diddle signals */
2675 if (PL_curinterp != aTHX)
2676 return (Sighandler_t) SIG_ERR;
2679 return PerlProc_signal(signo, handler);
2690 Perl_rsignal_state(pTHX_ int signo)
2693 Sighandler_t oldsig;
2695 #if defined(USE_ITHREADS) && !defined(WIN32)
2696 /* only "parent" interpreter can diddle signals */
2697 if (PL_curinterp != aTHX)
2698 return (Sighandler_t) SIG_ERR;
2702 oldsig = PerlProc_signal(signo, sig_trap);
2703 PerlProc_signal(signo, oldsig);
2705 PerlProc_kill(PerlProc_getpid(), signo);
2710 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2712 #if defined(USE_ITHREADS) && !defined(WIN32)
2713 /* only "parent" interpreter can diddle signals */
2714 if (PL_curinterp != aTHX)
2717 *save = PerlProc_signal(signo, handler);
2718 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2722 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2724 #if defined(USE_ITHREADS) && !defined(WIN32)
2725 /* only "parent" interpreter can diddle signals */
2726 if (PL_curinterp != aTHX)
2729 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2732 #endif /* !HAS_SIGACTION */
2733 #endif /* !PERL_MICRO */
2735 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2736 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2738 Perl_my_pclose(pTHX_ PerlIO *ptr)
2741 Sigsave_t hstat, istat, qstat;
2748 const int fd = PerlIO_fileno(ptr);
2751 /* Find out whether the refcount is low enough for us to wait for the
2752 child proc without blocking. */
2753 const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
2755 const bool should_wait = 1;
2758 svp = av_fetch(PL_fdpid,fd,TRUE);
2759 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2761 *svp = &PL_sv_undef;
2763 if (pid == -1) { /* Opened by popen. */
2764 return my_syspclose(ptr);
2767 close_failed = (PerlIO_close(ptr) == EOF);
2770 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
2771 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
2772 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
2774 if (should_wait) do {
2775 pid2 = wait4pid(pid, &status, 0);
2776 } while (pid2 == -1 && errno == EINTR);
2778 rsignal_restore(SIGHUP, &hstat);
2779 rsignal_restore(SIGINT, &istat);
2780 rsignal_restore(SIGQUIT, &qstat);
2788 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
2793 #if defined(__LIBCATAMOUNT__)
2795 Perl_my_pclose(pTHX_ PerlIO *ptr)
2800 #endif /* !DOSISH */
2802 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
2804 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2808 PERL_ARGS_ASSERT_WAIT4PID;
2811 #ifdef PERL_USES_PL_PIDSTATUS
2814 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2815 pid, rather than a string form. */
2816 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2817 if (svp && *svp != &PL_sv_undef) {
2818 *statusp = SvIVX(*svp);
2819 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2827 hv_iterinit(PL_pidstatus);
2828 if ((entry = hv_iternext(PL_pidstatus))) {
2829 SV * const sv = hv_iterval(PL_pidstatus,entry);
2831 const char * const spid = hv_iterkey(entry,&len);
2833 assert (len == sizeof(Pid_t));
2834 memcpy((char *)&pid, spid, len);
2835 *statusp = SvIVX(sv);
2836 /* The hash iterator is currently on this entry, so simply
2837 calling hv_delete would trigger the lazy delete, which on
2838 aggregate does more work, beacuse next call to hv_iterinit()
2839 would spot the flag, and have to call the delete routine,
2840 while in the meantime any new entries can't re-use that
2842 hv_iterinit(PL_pidstatus);
2843 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2850 # ifdef HAS_WAITPID_RUNTIME
2851 if (!HAS_WAITPID_RUNTIME)
2854 result = PerlProc_waitpid(pid,statusp,flags);
2857 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2858 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
2861 #ifdef PERL_USES_PL_PIDSTATUS
2862 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2867 Perl_croak(aTHX_ "Can't do waitpid with flags");
2869 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2870 pidgone(result,*statusp);
2876 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
2879 if (result < 0 && errno == EINTR) {
2881 errno = EINTR; /* reset in case a signal handler changed $! */
2885 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2887 #ifdef PERL_USES_PL_PIDSTATUS
2889 S_pidgone(pTHX_ Pid_t pid, int status)
2893 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
2894 SvUPGRADE(sv,SVt_IV);
2895 SvIV_set(sv, status);
2903 int /* Cannot prototype with I32
2905 my_syspclose(PerlIO *ptr)
2908 Perl_my_pclose(pTHX_ PerlIO *ptr)
2911 /* Needs work for PerlIO ! */
2912 FILE * const f = PerlIO_findFILE(ptr);
2913 const I32 result = pclose(f);
2914 PerlIO_releaseFILE(ptr,f);
2922 Perl_my_pclose(pTHX_ PerlIO *ptr)
2924 /* Needs work for PerlIO ! */
2925 FILE * const f = PerlIO_findFILE(ptr);
2926 I32 result = djgpp_pclose(f);
2927 result = (result << 8) & 0xff00;
2928 PerlIO_releaseFILE(ptr,f);
2933 #define PERL_REPEATCPY_LINEAR 4
2935 Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
2937 PERL_ARGS_ASSERT_REPEATCPY;
2942 Perl_croak_memory_wrap();
2945 memset(to, *from, count);
2948 IV items, linear, half;
2950 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
2951 for (items = 0; items < linear; ++items) {
2952 const char *q = from;
2954 for (todo = len; todo > 0; todo--)
2959 while (items <= half) {
2960 IV size = items * len;
2961 memcpy(p, to, size);
2967 memcpy(p, to, (count - items) * len);
2973 Perl_same_dirent(pTHX_ const char *a, const char *b)
2975 char *fa = strrchr(a,'/');
2976 char *fb = strrchr(b,'/');
2979 SV * const tmpsv = sv_newmortal();
2981 PERL_ARGS_ASSERT_SAME_DIRENT;
2994 sv_setpvs(tmpsv, ".");
2996 sv_setpvn(tmpsv, a, fa - a);
2997 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3000 sv_setpvs(tmpsv, ".");
3002 sv_setpvn(tmpsv, b, fb - b);
3003 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3005 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3006 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3008 #endif /* !HAS_RENAME */
3011 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3012 const char *const *const search_ext, I32 flags)
3015 const char *xfound = NULL;
3016 char *xfailed = NULL;
3017 char tmpbuf[MAXPATHLEN];
3022 #if defined(DOSISH) && !defined(OS2)
3023 # define SEARCH_EXTS ".bat", ".cmd", NULL
3024 # define MAX_EXT_LEN 4
3027 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3028 # define MAX_EXT_LEN 4
3031 # define SEARCH_EXTS ".pl", ".com", NULL
3032 # define MAX_EXT_LEN 4
3034 /* additional extensions to try in each dir if scriptname not found */
3036 static const char *const exts[] = { SEARCH_EXTS };
3037 const char *const *const ext = search_ext ? search_ext : exts;
3038 int extidx = 0, i = 0;
3039 const char *curext = NULL;
3041 PERL_UNUSED_ARG(search_ext);
3042 # define MAX_EXT_LEN 0
3045 PERL_ARGS_ASSERT_FIND_SCRIPT;
3048 * If dosearch is true and if scriptname does not contain path
3049 * delimiters, search the PATH for scriptname.
3051 * If SEARCH_EXTS is also defined, will look for each
3052 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3053 * while searching the PATH.
3055 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3056 * proceeds as follows:
3057 * If DOSISH or VMSISH:
3058 * + look for ./scriptname{,.foo,.bar}
3059 * + search the PATH for scriptname{,.foo,.bar}
3062 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3063 * this will not look in '.' if it's not in the PATH)
3068 # ifdef ALWAYS_DEFTYPES
3069 len = strlen(scriptname);
3070 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3071 int idx = 0, deftypes = 1;
3074 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3077 int idx = 0, deftypes = 1;
3080 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3082 /* The first time through, just add SEARCH_EXTS to whatever we
3083 * already have, so we can check for default file types. */
3085 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3091 if ((strlen(tmpbuf) + strlen(scriptname)
3092 + MAX_EXT_LEN) >= sizeof tmpbuf)
3093 continue; /* don't search dir with too-long name */
3094 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3098 if (strEQ(scriptname, "-"))
3100 if (dosearch) { /* Look in '.' first. */
3101 const char *cur = scriptname;
3103 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3105 if (strEQ(ext[i++],curext)) {
3106 extidx = -1; /* already has an ext */
3111 DEBUG_p(PerlIO_printf(Perl_debug_log,
3112 "Looking for %s\n",cur));
3113 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3114 && !S_ISDIR(PL_statbuf.st_mode)) {
3122 if (cur == scriptname) {
3123 len = strlen(scriptname);
3124 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3126 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3129 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3130 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3135 if (dosearch && !strchr(scriptname, '/')
3137 && !strchr(scriptname, '\\')
3139 && (s = PerlEnv_getenv("PATH")))
3143 bufend = s + strlen(s);
3144 while (s < bufend) {
3147 && *s != ';'; len++, s++) {
3148 if (len < sizeof tmpbuf)
3151 if (len < sizeof tmpbuf)
3154 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3160 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3161 continue; /* don't search dir with too-long name */
3164 && tmpbuf[len - 1] != '/'
3165 && tmpbuf[len - 1] != '\\'
3168 tmpbuf[len++] = '/';
3169 if (len == 2 && tmpbuf[0] == '.')
3171 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3175 len = strlen(tmpbuf);
3176 if (extidx > 0) /* reset after previous loop */
3180 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3181 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3182 if (S_ISDIR(PL_statbuf.st_mode)) {
3186 } while ( retval < 0 /* not there */
3187 && extidx>=0 && ext[extidx] /* try an extension? */
3188 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3193 if (S_ISREG(PL_statbuf.st_mode)
3194 && cando(S_IRUSR,TRUE,&PL_statbuf)
3195 #if !defined(DOSISH)
3196 && cando(S_IXUSR,TRUE,&PL_statbuf)
3200 xfound = tmpbuf; /* bingo! */
3204 xfailed = savepv(tmpbuf);
3207 if (!xfound && !seen_dot && !xfailed &&
3208 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3209 || S_ISDIR(PL_statbuf.st_mode)))
3211 seen_dot = 1; /* Disable message. */
3213 if (flags & 1) { /* do or die? */
3214 /* diag_listed_as: Can't execute %s */
3215 Perl_croak(aTHX_ "Can't %s %s%s%s",
3216 (xfailed ? "execute" : "find"),
3217 (xfailed ? xfailed : scriptname),
3218 (xfailed ? "" : " on PATH"),
3219 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3224 scriptname = xfound;
3226 return (scriptname ? savepv(scriptname) : NULL);
3229 #ifndef PERL_GET_CONTEXT_DEFINED
3232 Perl_get_context(void)
3235 #if defined(USE_ITHREADS)
3236 # ifdef OLD_PTHREADS_API
3238 int error = pthread_getspecific(PL_thr_key, &t)
3240 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3243 # ifdef I_MACH_CTHREADS
3244 return (void*)cthread_data(cthread_self());
3246 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3255 Perl_set_context(void *t)
3258 PERL_ARGS_ASSERT_SET_CONTEXT;
3259 #if defined(USE_ITHREADS)
3260 # ifdef I_MACH_CTHREADS
3261 cthread_set_data(cthread_self(), t);
3264 const int error = pthread_setspecific(PL_thr_key, t);
3266 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3274 #endif /* !PERL_GET_CONTEXT_DEFINED */
3276 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3285 Perl_get_op_names(pTHX)
3287 PERL_UNUSED_CONTEXT;
3288 return (char **)PL_op_name;
3292 Perl_get_op_descs(pTHX)
3294 PERL_UNUSED_CONTEXT;
3295 return (char **)PL_op_desc;
3299 Perl_get_no_modify(pTHX)
3301 PERL_UNUSED_CONTEXT;
3302 return PL_no_modify;
3306 Perl_get_opargs(pTHX)
3308 PERL_UNUSED_CONTEXT;
3309 return (U32 *)PL_opargs;
3313 Perl_get_ppaddr(pTHX)
3316 PERL_UNUSED_CONTEXT;
3317 return (PPADDR_t*)PL_ppaddr;
3320 #ifndef HAS_GETENV_LEN
3322 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3324 char * const env_trans = PerlEnv_getenv(env_elem);
3325 PERL_UNUSED_CONTEXT;
3326 PERL_ARGS_ASSERT_GETENV_LEN;
3328 *len = strlen(env_trans);
3335 Perl_get_vtbl(pTHX_ int vtbl_id)
3337 PERL_UNUSED_CONTEXT;
3339 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3340 ? NULL : PL_magic_vtables + vtbl_id;
3344 Perl_my_fflush_all(pTHX)
3346 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3347 return PerlIO_flush(NULL);
3349 # if defined(HAS__FWALK)
3350 extern int fflush(FILE *);
3351 /* undocumented, unprototyped, but very useful BSDism */
3352 extern void _fwalk(int (*)(FILE *));
3356 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3358 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3359 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3361 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3362 open_max = sysconf(_SC_OPEN_MAX);
3365 open_max = FOPEN_MAX;
3368 open_max = OPEN_MAX;
3379 for (i = 0; i < open_max; i++)
3380 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3381 STDIO_STREAM_ARRAY[i]._file < open_max &&
3382 STDIO_STREAM_ARRAY[i]._flag)
3383 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3387 SETERRNO(EBADF,RMS_IFI);
3394 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3396 if (ckWARN(WARN_IO)) {
3398 = gv && (isGV_with_GP(gv))
3401 const char * const direction = have == '>' ? "out" : "in";
3403 if (name && HEK_LEN(name))
3404 Perl_warner(aTHX_ packWARN(WARN_IO),
3405 "Filehandle %"HEKf" opened only for %sput",
3408 Perl_warner(aTHX_ packWARN(WARN_IO),
3409 "Filehandle opened only for %sput", direction);
3414 Perl_report_evil_fh(pTHX_ const GV *gv)
3416 const IO *io = gv ? GvIO(gv) : NULL;
3417 const PERL_BITFIELD16 op = PL_op->op_type;
3421 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3423 warn_type = WARN_CLOSED;
3427 warn_type = WARN_UNOPENED;
3430 if (ckWARN(warn_type)) {
3432 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3433 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3434 const char * const pars =
3435 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3436 const char * const func =
3438 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3439 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3441 const char * const type =
3443 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3444 ? "socket" : "filehandle");
3445 const bool have_name = name && SvCUR(name);
3446 Perl_warner(aTHX_ packWARN(warn_type),
3447 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3448 have_name ? " " : "",
3449 SVfARG(have_name ? name : &PL_sv_no));
3450 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3452 aTHX_ packWARN(warn_type),
3453 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3454 func, pars, have_name ? " " : "",
3455 SVfARG(have_name ? name : &PL_sv_no)
3460 /* To workaround core dumps from the uninitialised tm_zone we get the
3461 * system to give us a reasonable struct to copy. This fix means that
3462 * strftime uses the tm_zone and tm_gmtoff values returned by
3463 * localtime(time()). That should give the desired result most of the
3464 * time. But probably not always!
3466 * This does not address tzname aspects of NETaa14816.
3471 # ifndef STRUCT_TM_HASZONE
3472 # define STRUCT_TM_HASZONE
3476 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3477 # ifndef HAS_TM_TM_ZONE
3478 # define HAS_TM_TM_ZONE
3483 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3485 #ifdef HAS_TM_TM_ZONE
3487 const struct tm* my_tm;
3488 PERL_ARGS_ASSERT_INIT_TM;
3490 my_tm = localtime(&now);
3492 Copy(my_tm, ptm, 1, struct tm);
3494 PERL_ARGS_ASSERT_INIT_TM;
3495 PERL_UNUSED_ARG(ptm);
3500 * mini_mktime - normalise struct tm values without the localtime()
3501 * semantics (and overhead) of mktime().
3504 Perl_mini_mktime(pTHX_ struct tm *ptm)
3508 int month, mday, year, jday;
3509 int odd_cent, odd_year;
3510 PERL_UNUSED_CONTEXT;
3512 PERL_ARGS_ASSERT_MINI_MKTIME;
3514 #define DAYS_PER_YEAR 365
3515 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3516 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3517 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3518 #define SECS_PER_HOUR (60*60)
3519 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3520 /* parentheses deliberately absent on these two, otherwise they don't work */
3521 #define MONTH_TO_DAYS 153/5
3522 #define DAYS_TO_MONTH 5/153
3523 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3524 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3525 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3526 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3529 * Year/day algorithm notes:
3531 * With a suitable offset for numeric value of the month, one can find
3532 * an offset into the year by considering months to have 30.6 (153/5) days,
3533 * using integer arithmetic (i.e., with truncation). To avoid too much
3534 * messing about with leap days, we consider January and February to be
3535 * the 13th and 14th month of the previous year. After that transformation,
3536 * we need the month index we use to be high by 1 from 'normal human' usage,
3537 * so the month index values we use run from 4 through 15.
3539 * Given that, and the rules for the Gregorian calendar (leap years are those
3540 * divisible by 4 unless also divisible by 100, when they must be divisible
3541 * by 400 instead), we can simply calculate the number of days since some
3542 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3543 * the days we derive from our month index, and adding in the day of the
3544 * month. The value used here is not adjusted for the actual origin which
3545 * it normally would use (1 January A.D. 1), since we're not exposing it.
3546 * We're only building the value so we can turn around and get the
3547 * normalised values for the year, month, day-of-month, and day-of-year.
3549 * For going backward, we need to bias the value we're using so that we find
3550 * the right year value. (Basically, we don't want the contribution of
3551 * March 1st to the number to apply while deriving the year). Having done
3552 * that, we 'count up' the contribution to the year number by accounting for
3553 * full quadracenturies (400-year periods) with their extra leap days, plus
3554 * the contribution from full centuries (to avoid counting in the lost leap
3555 * days), plus the contribution from full quad-years (to count in the normal
3556 * leap days), plus the leftover contribution from any non-leap years.
3557 * At this point, if we were working with an actual leap day, we'll have 0
3558 * days left over. This is also true for March 1st, however. So, we have
3559 * to special-case that result, and (earlier) keep track of the 'odd'
3560 * century and year contributions. If we got 4 extra centuries in a qcent,
3561 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3562 * Otherwise, we add back in the earlier bias we removed (the 123 from
3563 * figuring in March 1st), find the month index (integer division by 30.6),
3564 * and the remainder is the day-of-month. We then have to convert back to
3565 * 'real' months (including fixing January and February from being 14/15 in
3566 * the previous year to being in the proper year). After that, to get
3567 * tm_yday, we work with the normalised year and get a new yearday value for
3568 * January 1st, which we subtract from the yearday value we had earlier,
3569 * representing the date we've re-built. This is done from January 1
3570 * because tm_yday is 0-origin.
3572 * Since POSIX time routines are only guaranteed to work for times since the
3573 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3574 * applies Gregorian calendar rules even to dates before the 16th century
3575 * doesn't bother me. Besides, you'd need cultural context for a given
3576 * date to know whether it was Julian or Gregorian calendar, and that's
3577 * outside the scope for this routine. Since we convert back based on the
3578 * same rules we used to build the yearday, you'll only get strange results
3579 * for input which needed normalising, or for the 'odd' century years which
3580 * were leap years in the Julian calendar but not in the Gregorian one.
3581 * I can live with that.
3583 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3584 * that's still outside the scope for POSIX time manipulation, so I don't
3588 year = 1900 + ptm->tm_year;
3589 month = ptm->tm_mon;
3590 mday = ptm->tm_mday;
3596 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3597 yearday += month*MONTH_TO_DAYS + mday + jday;
3599 * Note that we don't know when leap-seconds were or will be,
3600 * so we have to trust the user if we get something which looks
3601 * like a sensible leap-second. Wild values for seconds will
3602 * be rationalised, however.
3604 if ((unsigned) ptm->tm_sec <= 60) {
3611 secs += 60 * ptm->tm_min;
3612 secs += SECS_PER_HOUR * ptm->tm_hour;
3614 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3615 /* got negative remainder, but need positive time */
3616 /* back off an extra day to compensate */
3617 yearday += (secs/SECS_PER_DAY)-1;
3618 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3621 yearday += (secs/SECS_PER_DAY);
3622 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3625 else if (secs >= SECS_PER_DAY) {
3626 yearday += (secs/SECS_PER_DAY);
3627 secs %= SECS_PER_DAY;
3629 ptm->tm_hour = secs/SECS_PER_HOUR;
3630 secs %= SECS_PER_HOUR;
3631 ptm->tm_min = secs/60;
3633 ptm->tm_sec += secs;
3634 /* done with time of day effects */
3636 * The algorithm for yearday has (so far) left it high by 428.
3637 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3638 * bias it by 123 while trying to figure out what year it
3639 * really represents. Even with this tweak, the reverse
3640 * translation fails for years before A.D. 0001.
3641 * It would still fail for Feb 29, but we catch that one below.
3643 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3644 yearday -= YEAR_ADJUST;
3645 year = (yearday / DAYS_PER_QCENT) * 400;
3646 yearday %= DAYS_PER_QCENT;
3647 odd_cent = yearday / DAYS_PER_CENT;
3648 year += odd_cent * 100;
3649 yearday %= DAYS_PER_CENT;
3650 year += (yearday / DAYS_PER_QYEAR) * 4;
3651 yearday %= DAYS_PER_QYEAR;
3652 odd_year = yearday / DAYS_PER_YEAR;
3654 yearday %= DAYS_PER_YEAR;
3655 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3660 yearday += YEAR_ADJUST; /* recover March 1st crock */
3661 month = yearday*DAYS_TO_MONTH;
3662 yearday -= month*MONTH_TO_DAYS;
3663 /* recover other leap-year adjustment */
3672 ptm->tm_year = year - 1900;
3674 ptm->tm_mday = yearday;
3675 ptm->tm_mon = month;
3679 ptm->tm_mon = month - 1;
3681 /* re-build yearday based on Jan 1 to get tm_yday */
3683 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3684 yearday += 14*MONTH_TO_DAYS + 1;
3685 ptm->tm_yday = jday - yearday;
3686 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3690 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)
3698 PERL_ARGS_ASSERT_MY_STRFTIME;
3700 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3703 mytm.tm_hour = hour;
3704 mytm.tm_mday = mday;
3706 mytm.tm_year = year;
3707 mytm.tm_wday = wday;
3708 mytm.tm_yday = yday;
3709 mytm.tm_isdst = isdst;
3711 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3712 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3717 #ifdef HAS_TM_TM_GMTOFF
3718 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3720 #ifdef HAS_TM_TM_ZONE
3721 mytm.tm_zone = mytm2.tm_zone;
3726 Newx(buf, buflen, char);
3727 len = strftime(buf, buflen, fmt, &mytm);
3729 ** The following is needed to handle to the situation where
3730 ** tmpbuf overflows. Basically we want to allocate a buffer
3731 ** and try repeatedly. The reason why it is so complicated
3732 ** is that getting a return value of 0 from strftime can indicate
3733 ** one of the following:
3734 ** 1. buffer overflowed,
3735 ** 2. illegal conversion specifier, or
3736 ** 3. the format string specifies nothing to be returned(not
3737 ** an error). This could be because format is an empty string
3738 ** or it specifies %p that yields an empty string in some locale.
3739 ** If there is a better way to make it portable, go ahead by
3742 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3745 /* Possibly buf overflowed - try again with a bigger buf */
3746 const int fmtlen = strlen(fmt);
3747 int bufsize = fmtlen + buflen;
3749 Renew(buf, bufsize, char);
3751 buflen = strftime(buf, bufsize, fmt, &mytm);
3752 if (buflen > 0 && buflen < bufsize)
3754 /* heuristic to prevent out-of-memory errors */
3755 if (bufsize > 100*fmtlen) {
3761 Renew(buf, bufsize, char);
3766 Perl_croak(aTHX_ "panic: no strftime");
3772 #define SV_CWD_RETURN_UNDEF \
3773 sv_setsv(sv, &PL_sv_undef); \
3776 #define SV_CWD_ISDOT(dp) \
3777 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3778 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3781 =head1 Miscellaneous Functions
3783 =for apidoc getcwd_sv
3785 Fill the sv with current working directory
3790 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3791 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3792 * getcwd(3) if available
3793 * Comments from the orignal:
3794 * This is a faster version of getcwd. It's also more dangerous
3795 * because you might chdir out of a directory that you can't chdir
3799 Perl_getcwd_sv(pTHX_ SV *sv)
3803 #ifndef INCOMPLETE_TAINTS
3807 PERL_ARGS_ASSERT_GETCWD_SV;
3811 char buf[MAXPATHLEN];
3813 /* Some getcwd()s automatically allocate a buffer of the given
3814 * size from the heap if they are given a NULL buffer pointer.
3815 * The problem is that this behaviour is not portable. */
3816 if (getcwd(buf, sizeof(buf) - 1)) {
3821 sv_setsv(sv, &PL_sv_undef);
3829 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3833 SvUPGRADE(sv, SVt_PV);
3835 if (PerlLIO_lstat(".", &statbuf) < 0) {
3836 SV_CWD_RETURN_UNDEF;
3839 orig_cdev = statbuf.st_dev;
3840 orig_cino = statbuf.st_ino;
3850 if (PerlDir_chdir("..") < 0) {
3851 SV_CWD_RETURN_UNDEF;
3853 if (PerlLIO_stat(".", &statbuf) < 0) {
3854 SV_CWD_RETURN_UNDEF;
3857 cdev = statbuf.st_dev;
3858 cino = statbuf.st_ino;
3860 if (odev == cdev && oino == cino) {
3863 if (!(dir = PerlDir_open("."))) {
3864 SV_CWD_RETURN_UNDEF;
3867 while ((dp = PerlDir_read(dir)) != NULL) {
3869 namelen = dp->d_namlen;
3871 namelen = strlen(dp->d_name);
3874 if (SV_CWD_ISDOT(dp)) {
3878 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3879 SV_CWD_RETURN_UNDEF;
3882 tdev = statbuf.st_dev;
3883 tino = statbuf.st_ino;
3884 if (tino == oino && tdev == odev) {
3890 SV_CWD_RETURN_UNDEF;
3893 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3894 SV_CWD_RETURN_UNDEF;
3897 SvGROW(sv, pathlen + namelen + 1);
3901 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3904 /* prepend current directory to the front */
3906 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3907 pathlen += (namelen + 1);
3909 #ifdef VOID_CLOSEDIR
3912 if (PerlDir_close(dir) < 0) {
3913 SV_CWD_RETURN_UNDEF;
3919 SvCUR_set(sv, pathlen);
3923 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
3924 SV_CWD_RETURN_UNDEF;
3927 if (PerlLIO_stat(".", &statbuf) < 0) {
3928 SV_CWD_RETURN_UNDEF;
3931 cdev = statbuf.st_dev;
3932 cino = statbuf.st_ino;
3934 if (cdev != orig_cdev || cino != orig_cino) {
3935 Perl_croak(aTHX_ "Unstable directory path, "
3936 "current directory changed unexpectedly");
3947 #define VERSION_MAX 0x7FFFFFFF
3950 =for apidoc prescan_version
3952 Validate that a given string can be parsed as a version object, but doesn't
3953 actually perform the parsing. Can use either strict or lax validation rules.
3954 Can optionally set a number of hint variables to save the parsing code
3955 some time when tokenizing.
3960 Perl_prescan_version(pTHX_ const char *s, bool strict,
3961 const char **errstr,
3962 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
3963 bool qv = (sqv ? *sqv : FALSE);
3965 int saw_decimal = 0;
3969 PERL_ARGS_ASSERT_PRESCAN_VERSION;
3971 if (qv && isDIGIT(*d))
3972 goto dotted_decimal_version;
3974 if (*d == 'v') { /* explicit v-string */
3979 else { /* degenerate v-string */
3980 /* requires v1.2.3 */
3981 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
3984 dotted_decimal_version:
3985 if (strict && d[0] == '0' && isDIGIT(d[1])) {
3986 /* no leading zeros allowed */
3987 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
3990 while (isDIGIT(*d)) /* integer part */
3996 d++; /* decimal point */
4001 /* require v1.2.3 */
4002 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4005 goto version_prescan_finish;
4012 while (isDIGIT(*d)) { /* just keep reading */
4014 while (isDIGIT(*d)) {
4016 /* maximum 3 digits between decimal */
4017 if (strict && j > 3) {
4018 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4023 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4026 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4031 else if (*d == '.') {
4033 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4038 else if (!isDIGIT(*d)) {
4044 if (strict && i < 2) {
4045 /* requires v1.2.3 */
4046 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4049 } /* end if dotted-decimal */
4051 { /* decimal versions */
4052 int j = 0; /* may need this later */
4053 /* special strict case for leading '.' or '0' */
4056 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4058 if (*d == '0' && isDIGIT(d[1])) {
4059 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4063 /* and we never support negative versions */
4065 BADVERSION(s,errstr,"Invalid version format (negative version number)");
4068 /* consume all of the integer part */
4072 /* look for a fractional part */
4074 /* we found it, so consume it */
4078 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4081 BADVERSION(s,errstr,"Invalid version format (version required)");
4083 /* found just an integer */
4084 goto version_prescan_finish;
4086 else if ( d == s ) {
4087 /* didn't find either integer or period */
4088 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4090 else if (*d == '_') {
4091 /* underscore can't come after integer part */
4093 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4095 else if (isDIGIT(d[1])) {
4096 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4099 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4103 /* anything else after integer part is just invalid data */
4104 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4107 /* scan the fractional part after the decimal point*/
4109 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4110 /* strict or lax-but-not-the-end */
4111 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4114 while (isDIGIT(*d)) {
4116 if (*d == '.' && isDIGIT(d[-1])) {
4118 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4121 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4123 d = (char *)s; /* start all over again */
4125 goto dotted_decimal_version;
4129 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4132 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4134 if ( ! isDIGIT(d[1]) ) {
4135 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4144 version_prescan_finish:
4148 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4149 /* trailing non-numeric data */
4150 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4158 *ssaw_decimal = saw_decimal;
4165 =for apidoc scan_version
4167 Returns a pointer to the next character after the parsed
4168 version string, as well as upgrading the passed in SV to
4171 Function must be called with an already existing SV like
4174 s = scan_version(s, SV *sv, bool qv);
4176 Performs some preprocessing to the string to ensure that
4177 it has the correct characteristics of a version. Flags the
4178 object if it contains an underscore (which denotes this
4179 is an alpha version). The boolean qv denotes that the version
4180 should be interpreted as if it had multiple decimals, even if
4187 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4189 const char *start = s;
4192 const char *errstr = NULL;
4193 int saw_decimal = 0;
4200 PERL_ARGS_ASSERT_SCAN_VERSION;
4202 while (isSPACE(*s)) /* leading whitespace is OK */
4205 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4207 /* "undef" is a special case and not an error */
4208 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4210 Perl_croak(aTHX_ "%s", errstr);
4219 /* Now that we are through the prescan, start creating the object */
4221 hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4222 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4224 #ifndef NODEFAULT_SHAREKEYS
4225 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4229 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4231 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4232 if ( !qv && width < 3 )
4233 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4235 while (isDIGIT(*pos))
4237 if (!isALPHA(*pos)) {
4243 /* this is atoi() that delimits on underscores */
4244 const char *end = pos;
4248 /* the following if() will only be true after the decimal
4249 * point of a version originally created with a bare
4250 * floating point number, i.e. not quoted in any way
4252 if ( !qv && s > start && saw_decimal == 1 ) {
4256 rev += (*s - '0') * mult;
4258 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4259 || (PERL_ABS(rev) > VERSION_MAX )) {
4260 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4261 "Integer overflow in version %d",VERSION_MAX);
4272 while (--end >= s) {
4274 rev += (*end - '0') * mult;
4276 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4277 || (PERL_ABS(rev) > VERSION_MAX )) {
4278 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4279 "Integer overflow in version");
4288 /* Append revision */
4289 av_push(av, newSViv(rev));
4294 else if ( *pos == '.' )
4296 else if ( *pos == '_' && isDIGIT(pos[1]) )
4298 else if ( *pos == ',' && isDIGIT(pos[1]) )
4300 else if ( isDIGIT(*pos) )
4307 while ( isDIGIT(*pos) )
4312 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4320 if ( qv ) { /* quoted versions always get at least three terms*/
4321 I32 len = av_len(av);
4322 /* This for loop appears to trigger a compiler bug on OS X, as it
4323 loops infinitely. Yes, len is negative. No, it makes no sense.
4324 Compiler in question is:
4325 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4326 for ( len = 2 - len; len > 0; len-- )
4327 av_push(MUTABLE_AV(sv), newSViv(0));
4331 av_push(av, newSViv(0));
4334 /* need to save off the current version string for later */
4336 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4337 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4338 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4340 else if ( s > start ) {
4341 SV * orig = newSVpvn(start,s-start);
4342 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4343 /* need to insert a v to be consistent */
4344 sv_insert(orig, 0, 0, "v", 1);
4346 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4349 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4350 av_push(av, newSViv(0));
4353 /* And finally, store the AV in the hash */
4354 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4356 /* fix RT#19517 - special case 'undef' as string */
4357 if ( *s == 'u' && strEQ(s,"undef") ) {
4365 =for apidoc new_version
4367 Returns a new version object based on the passed in SV:
4369 SV *sv = new_version(SV *ver);
4371 Does not alter the passed in ver SV. See "upg_version" if you
4372 want to upgrade the SV.
4378 Perl_new_version(pTHX_ SV *ver)
4381 SV * const rv = newSV(0);
4382 PERL_ARGS_ASSERT_NEW_VERSION;
4383 if ( sv_isobject(ver) && sv_derived_from(ver, "version") )
4384 /* can just copy directly */
4387 AV * const av = newAV();
4389 /* This will get reblessed later if a derived class*/
4390 SV * const hv = newSVrv(rv, "version");
4391 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4392 #ifndef NODEFAULT_SHAREKEYS
4393 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4399 /* Begin copying all of the elements */
4400 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4401 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4403 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4404 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4406 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4408 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4409 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4412 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4414 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4415 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4418 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4419 /* This will get reblessed later if a derived class*/
4420 for ( key = 0; key <= av_len(sav); key++ )
4422 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4423 av_push(av, newSViv(rev));
4426 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4431 const MAGIC* const mg = SvVSTRING_mg(ver);
4432 if ( mg ) { /* already a v-string */
4433 const STRLEN len = mg->mg_len;
4434 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4435 sv_setpvn(rv,version,len);
4436 /* this is for consistency with the pure Perl class */
4437 if ( isDIGIT(*version) )
4438 sv_insert(rv, 0, 0, "v", 1);
4443 sv_setsv(rv,ver); /* make a duplicate */
4448 return upg_version(rv, FALSE);
4452 =for apidoc upg_version
4454 In-place upgrade of the supplied SV to a version object.
4456 SV *sv = upg_version(SV *sv, bool qv);
4458 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4459 to force this SV to be interpreted as an "extended" version.
4465 Perl_upg_version(pTHX_ SV *ver, bool qv)
4467 const char *version, *s;
4472 PERL_ARGS_ASSERT_UPG_VERSION;
4474 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4478 /* may get too much accuracy */
4480 SV *sv = SvNVX(ver) > 10e50 ? newSV(64) : 0;
4482 #ifdef USE_LOCALE_NUMERIC
4483 char *loc = savepv(setlocale(LC_NUMERIC, NULL));
4484 setlocale(LC_NUMERIC, "C");
4487 Perl_sv_setpvf(aTHX_ sv, "%.9"NVff, SvNVX(ver));
4488 buf = SvPV(sv, len);
4491 len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4494 #ifdef USE_LOCALE_NUMERIC
4495 setlocale(LC_NUMERIC, loc);
4498 while (buf[len-1] == '0' && len > 0) len--;
4499 if ( buf[len-1] == '.' ) len--; /* eat the trailing decimal */
4500 version = savepvn(buf, len);
4504 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4505 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4509 else /* must be a string or something like a string */
4512 version = savepv(SvPV(ver,len));
4514 # if PERL_VERSION > 5
4515 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4516 if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
4517 /* may be a v-string */
4518 char *testv = (char *)version;
4520 for (tlen=0; tlen < len; tlen++, testv++) {
4521 /* if one of the characters is non-text assume v-string */
4522 if (testv[0] < ' ') {
4523 SV * const nsv = sv_newmortal();
4526 int saw_decimal = 0;
4527 sv_setpvf(nsv,"v%vd",ver);
4528 pos = nver = savepv(SvPV_nolen(nsv));
4530 /* scan the resulting formatted string */
4531 pos++; /* skip the leading 'v' */
4532 while ( *pos == '.' || isDIGIT(*pos) ) {
4538 /* is definitely a v-string */
4539 if ( saw_decimal >= 2 ) {
4551 s = scan_version(version, ver, qv);
4553 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4554 "Version string '%s' contains invalid data; "
4555 "ignoring: '%s'", version, s);
4563 Validates that the SV contains valid internal structure for a version object.
4564 It may be passed either the version object (RV) or the hash itself (HV). If
4565 the structure is valid, it returns the HV. If the structure is invalid,
4568 SV *hv = vverify(sv);
4570 Note that it only confirms the bare minimum structure (so as not to get
4571 confused by derived classes which may contain additional hash entries):
4575 =item * The SV is an HV or a reference to an HV
4577 =item * The hash contains a "version" key
4579 =item * The "version" key has a reference to an AV as its value
4587 Perl_vverify(pTHX_ SV *vs)
4591 PERL_ARGS_ASSERT_VVERIFY;
4596 /* see if the appropriate elements exist */
4597 if ( SvTYPE(vs) == SVt_PVHV
4598 && hv_exists(MUTABLE_HV(vs), "version", 7)
4599 && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
4600 && SvTYPE(sv) == SVt_PVAV )
4609 Accepts a version object and returns the normalized floating
4610 point representation. Call like:
4614 NOTE: you can pass either the object directly or the SV
4615 contained within the RV.
4617 The SV returned has a refcount of 1.
4623 Perl_vnumify(pTHX_ SV *vs)
4631 PERL_ARGS_ASSERT_VNUMIFY;
4633 /* extract the HV from the object */
4636 Perl_croak(aTHX_ "Invalid version object");
4638 /* see if various flags exist */
4639 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
4641 if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
4642 width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
4647 /* attempt to retrieve the version array */
4648 if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
4649 return newSVpvs("0");
4655 return newSVpvs("0");
4658 digit = SvIV(*av_fetch(av, 0, 0));
4659 sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
4660 for ( i = 1 ; i < len ; i++ )
4662 digit = SvIV(*av_fetch(av, i, 0));
4664 const int denom = (width == 2 ? 10 : 100);
4665 const div_t term = div((int)PERL_ABS(digit),denom);
4666 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4669 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4675 digit = SvIV(*av_fetch(av, len, 0));
4676 if ( alpha && width == 3 ) /* alpha version */
4678 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4682 sv_catpvs(sv, "000");
4690 Accepts a version object and returns the normalized string
4691 representation. Call like:
4695 NOTE: you can pass either the object directly or the SV
4696 contained within the RV.
4698 The SV returned has a refcount of 1.
4704 Perl_vnormal(pTHX_ SV *vs)
4711 PERL_ARGS_ASSERT_VNORMAL;
4713 /* extract the HV from the object */
4716 Perl_croak(aTHX_ "Invalid version object");
4718 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
4720 av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)));
4725 return newSVpvs("");
4727 digit = SvIV(*av_fetch(av, 0, 0));
4728 sv = Perl_newSVpvf(aTHX_ "v%"IVdf, (IV)digit);
4729 for ( i = 1 ; i < len ; i++ ) {
4730 digit = SvIV(*av_fetch(av, i, 0));
4731 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4736 /* handle last digit specially */
4737 digit = SvIV(*av_fetch(av, len, 0));
4739 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
4741 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4744 if ( len <= 2 ) { /* short version, must be at least three */
4745 for ( len = 2 - len; len != 0; len-- )
4752 =for apidoc vstringify
4754 In order to maintain maximum compatibility with earlier versions
4755 of Perl, this function will return either the floating point
4756 notation or the multiple dotted notation, depending on whether
4757 the original version contained 1 or more dots, respectively.
4759 The SV returned has a refcount of 1.
4765 Perl_vstringify(pTHX_ SV *vs)
4767 PERL_ARGS_ASSERT_VSTRINGIFY;
4769 /* extract the HV from the object */
4772 Perl_croak(aTHX_ "Invalid version object");
4774 if (hv_exists(MUTABLE_HV(vs), "original", sizeof("original") - 1)) {
4776 pv = *hv_fetchs(MUTABLE_HV(vs), "original", FALSE);
4780 return &PL_sv_undef;
4783 if ( hv_exists(MUTABLE_HV(vs), "qv", 2) )
4793 Version object aware cmp. Both operands must already have been
4794 converted into version objects.
4800 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
4803 bool lalpha = FALSE;
4804 bool ralpha = FALSE;
4809 PERL_ARGS_ASSERT_VCMP;
4811 /* extract the HVs from the objects */
4814 if ( ! ( lhv && rhv ) )
4815 Perl_croak(aTHX_ "Invalid version object");
4817 /* get the left hand term */
4818 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(lhv), "version", FALSE)));
4819 if ( hv_exists(MUTABLE_HV(lhv), "alpha", 5 ) )
4822 /* and the right hand term */
4823 rav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rhv), "version", FALSE)));
4824 if ( hv_exists(MUTABLE_HV(rhv), "alpha", 5 ) )
4832 while ( i <= m && retval == 0 )
4834 left = SvIV(*av_fetch(lav,i,0));
4835 right = SvIV(*av_fetch(rav,i,0));
4843 /* tiebreaker for alpha with identical terms */
4844 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
4846 if ( lalpha && !ralpha )
4850 else if ( ralpha && !lalpha)
4856 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
4860 while ( i <= r && retval == 0 )
4862 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
4863 retval = -1; /* not a match after all */
4869 while ( i <= l && retval == 0 )
4871 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
4872 retval = +1; /* not a match after all */
4880 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4881 # define EMULATE_SOCKETPAIR_UDP
4884 #ifdef EMULATE_SOCKETPAIR_UDP
4886 S_socketpair_udp (int fd[2]) {
4888 /* Fake a datagram socketpair using UDP to localhost. */
4889 int sockets[2] = {-1, -1};
4890 struct sockaddr_in addresses[2];
4892 Sock_size_t size = sizeof(struct sockaddr_in);
4893 unsigned short port;
4896 memset(&addresses, 0, sizeof(addresses));
4899 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4900 if (sockets[i] == -1)
4901 goto tidy_up_and_fail;
4903 addresses[i].sin_family = AF_INET;
4904 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4905 addresses[i].sin_port = 0; /* kernel choses port. */
4906 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4907 sizeof(struct sockaddr_in)) == -1)
4908 goto tidy_up_and_fail;
4911 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4912 for each connect the other socket to it. */
4915 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4917 goto tidy_up_and_fail;
4918 if (size != sizeof(struct sockaddr_in))
4919 goto abort_tidy_up_and_fail;
4920 /* !1 is 0, !0 is 1 */
4921 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4922 sizeof(struct sockaddr_in)) == -1)
4923 goto tidy_up_and_fail;
4926 /* Now we have 2 sockets connected to each other. I don't trust some other
4927 process not to have already sent a packet to us (by random) so send
4928 a packet from each to the other. */
4931 /* I'm going to send my own port number. As a short.
4932 (Who knows if someone somewhere has sin_port as a bitfield and needs
4933 this routine. (I'm assuming crays have socketpair)) */
4934 port = addresses[i].sin_port;
4935 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4936 if (got != sizeof(port)) {
4938 goto tidy_up_and_fail;
4939 goto abort_tidy_up_and_fail;
4943 /* Packets sent. I don't trust them to have arrived though.
4944 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4945 connect to localhost will use a second kernel thread. In 2.6 the
4946 first thread running the connect() returns before the second completes,
4947 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4948 returns 0. Poor programs have tripped up. One poor program's authors'
4949 had a 50-1 reverse stock split. Not sure how connected these were.)
4950 So I don't trust someone not to have an unpredictable UDP stack.
4954 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4955 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4959 FD_SET((unsigned int)sockets[0], &rset);
4960 FD_SET((unsigned int)sockets[1], &rset);
4962 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4963 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4964 || !FD_ISSET(sockets[1], &rset)) {
4965 /* I hope this is portable and appropriate. */
4967 goto tidy_up_and_fail;
4968 goto abort_tidy_up_and_fail;
4972 /* And the paranoia department even now doesn't trust it to have arrive
4973 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4975 struct sockaddr_in readfrom;
4976 unsigned short buffer[2];
4981 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4982 sizeof(buffer), MSG_DONTWAIT,
4983 (struct sockaddr *) &readfrom, &size);
4985 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4987 (struct sockaddr *) &readfrom, &size);
4991 goto tidy_up_and_fail;
4992 if (got != sizeof(port)
4993 || size != sizeof(struct sockaddr_in)
4994 /* Check other socket sent us its port. */
4995 || buffer[0] != (unsigned short) addresses[!i].sin_port
4996 /* Check kernel says we got the datagram from that socket */
4997 || readfrom.sin_family != addresses[!i].sin_family
4998 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4999 || readfrom.sin_port != addresses[!i].sin_port)
5000 goto abort_tidy_up_and_fail;
5003 /* My caller (my_socketpair) has validated that this is non-NULL */
5006 /* I hereby declare this connection open. May God bless all who cross
5010 abort_tidy_up_and_fail:
5011 errno = ECONNABORTED;
5015 if (sockets[0] != -1)
5016 PerlLIO_close(sockets[0]);
5017 if (sockets[1] != -1)
5018 PerlLIO_close(sockets[1]);
5023 #endif /* EMULATE_SOCKETPAIR_UDP */
5025 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
5027 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5028 /* Stevens says that family must be AF_LOCAL, protocol 0.
5029 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
5034 struct sockaddr_in listen_addr;
5035 struct sockaddr_in connect_addr;
5040 || family != AF_UNIX
5043 errno = EAFNOSUPPORT;
5051 #ifdef EMULATE_SOCKETPAIR_UDP
5052 if (type == SOCK_DGRAM)
5053 return S_socketpair_udp(fd);
5056 aTHXa(PERL_GET_THX);
5057 listener = PerlSock_socket(AF_INET, type, 0);
5060 memset(&listen_addr, 0, sizeof(listen_addr));
5061 listen_addr.sin_family = AF_INET;
5062 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5063 listen_addr.sin_port = 0; /* kernel choses port. */
5064 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5065 sizeof(listen_addr)) == -1)
5066 goto tidy_up_and_fail;
5067 if (PerlSock_listen(listener, 1) == -1)
5068 goto tidy_up_and_fail;
5070 connector = PerlSock_socket(AF_INET, type, 0);
5071 if (connector == -1)
5072 goto tidy_up_and_fail;
5073 /* We want to find out the port number to connect to. */
5074 size = sizeof(connect_addr);
5075 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5077 goto tidy_up_and_fail;
5078 if (size != sizeof(connect_addr))
5079 goto abort_tidy_up_and_fail;
5080 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
5081 sizeof(connect_addr)) == -1)
5082 goto tidy_up_and_fail;
5084 size = sizeof(listen_addr);
5085 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5088 goto tidy_up_and_fail;
5089 if (size != sizeof(listen_addr))
5090 goto abort_tidy_up_and_fail;
5091 PerlLIO_close(listener);
5092 /* Now check we are talking to ourself by matching port and host on the
5094 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5096 goto tidy_up_and_fail;
5097 if (size != sizeof(connect_addr)
5098 || listen_addr.sin_family != connect_addr.sin_family
5099 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5100 || listen_addr.sin_port != connect_addr.sin_port) {
5101 goto abort_tidy_up_and_fail;
5107 abort_tidy_up_and_fail:
5109 errno = ECONNABORTED; /* This would be the standard thing to do. */
5111 # ifdef ECONNREFUSED
5112 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5114 errno = ETIMEDOUT; /* Desperation time. */
5121 PerlLIO_close(listener);
5122 if (connector != -1)
5123 PerlLIO_close(connector);
5125 PerlLIO_close(acceptor);
5131 /* In any case have a stub so that there's code corresponding
5132 * to the my_socketpair in embed.fnc. */
5134 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5135 #ifdef HAS_SOCKETPAIR
5136 return socketpair(family, type, protocol, fd);
5145 =for apidoc sv_nosharing
5147 Dummy routine which "shares" an SV when there is no sharing module present.
5148 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5149 Exists to avoid test for a NULL function pointer and because it could
5150 potentially warn under some level of strict-ness.
5156 Perl_sv_nosharing(pTHX_ SV *sv)
5158 PERL_UNUSED_CONTEXT;
5159 PERL_UNUSED_ARG(sv);
5164 =for apidoc sv_destroyable
5166 Dummy routine which reports that object can be destroyed when there is no
5167 sharing module present. It ignores its single SV argument, and returns
5168 'true'. Exists to avoid test for a NULL function pointer and because it
5169 could potentially warn under some level of strict-ness.
5175 Perl_sv_destroyable(pTHX_ SV *sv)
5177 PERL_UNUSED_CONTEXT;
5178 PERL_UNUSED_ARG(sv);
5183 Perl_parse_unicode_opts(pTHX_ const char **popt)
5185 const char *p = *popt;
5188 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5192 opt = (U32) atoi(p);
5195 if (*p && *p != '\n' && *p != '\r') {
5196 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5198 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
5204 case PERL_UNICODE_STDIN:
5205 opt |= PERL_UNICODE_STDIN_FLAG; break;
5206 case PERL_UNICODE_STDOUT:
5207 opt |= PERL_UNICODE_STDOUT_FLAG; break;
5208 case PERL_UNICODE_STDERR:
5209 opt |= PERL_UNICODE_STDERR_FLAG; break;
5210 case PERL_UNICODE_STD:
5211 opt |= PERL_UNICODE_STD_FLAG; break;
5212 case PERL_UNICODE_IN:
5213 opt |= PERL_UNICODE_IN_FLAG; break;
5214 case PERL_UNICODE_OUT:
5215 opt |= PERL_UNICODE_OUT_FLAG; break;
5216 case PERL_UNICODE_INOUT:
5217 opt |= PERL_UNICODE_INOUT_FLAG; break;
5218 case PERL_UNICODE_LOCALE:
5219 opt |= PERL_UNICODE_LOCALE_FLAG; break;
5220 case PERL_UNICODE_ARGV:
5221 opt |= PERL_UNICODE_ARGV_FLAG; break;
5222 case PERL_UNICODE_UTF8CACHEASSERT:
5223 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
5225 if (*p != '\n' && *p != '\r') {
5226 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5229 "Unknown Unicode option letter '%c'", *p);
5236 opt = PERL_UNICODE_DEFAULT_FLAGS;
5238 the_end_of_the_opts_parser:
5240 if (opt & ~PERL_UNICODE_ALL_FLAGS)
5241 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
5242 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5250 # include <starlet.h>
5258 * This is really just a quick hack which grabs various garbage
5259 * values. It really should be a real hash algorithm which
5260 * spreads the effect of every input bit onto every output bit,
5261 * if someone who knows about such things would bother to write it.
5262 * Might be a good idea to add that function to CORE as well.
5263 * No numbers below come from careful analysis or anything here,
5264 * except they are primes and SEED_C1 > 1E6 to get a full-width
5265 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5266 * probably be bigger too.
5269 # define SEED_C1 1000003
5270 #define SEED_C4 73819
5272 # define SEED_C1 25747
5273 #define SEED_C4 20639
5277 #define SEED_C5 26107
5279 #ifndef PERL_NO_DEV_RANDOM
5284 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5285 * in 100-ns units, typically incremented ever 10 ms. */
5286 unsigned int when[2];
5288 # ifdef HAS_GETTIMEOFDAY
5289 struct timeval when;
5295 /* This test is an escape hatch, this symbol isn't set by Configure. */
5296 #ifndef PERL_NO_DEV_RANDOM
5297 #ifndef PERL_RANDOM_DEVICE
5298 /* /dev/random isn't used by default because reads from it will block
5299 * if there isn't enough entropy available. You can compile with
5300 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5301 * is enough real entropy to fill the seed. */
5302 # define PERL_RANDOM_DEVICE "/dev/urandom"
5304 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5306 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5315 _ckvmssts(sys$gettim(when));
5316 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5318 # ifdef HAS_GETTIMEOFDAY
5319 PerlProc_gettimeofday(&when,NULL);
5320 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5323 u = (U32)SEED_C1 * when;
5326 u += SEED_C3 * (U32)PerlProc_getpid();
5327 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5328 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5329 u += SEED_C5 * (U32)PTR2UV(&when);
5335 Perl_get_hash_seed(pTHX_ unsigned char * const seed_buffer)
5341 PERL_ARGS_ASSERT_GET_HASH_SEED;
5343 env_pv= PerlEnv_getenv("PERL_HASH_SEED");
5346 #ifndef USE_HASH_SEED_EXPLICIT
5348 /* ignore leading spaces */
5349 while (isSPACE(*env_pv))
5351 #ifdef USE_PERL_PERTURB_KEYS
5352 /* if they set it to "0" we disable key traversal randomization completely */
5353 if (strEQ(env_pv,"0")) {
5354 PL_hash_rand_bits_enabled= 0;
5356 /* otherwise switch to deterministic mode */
5357 PL_hash_rand_bits_enabled= 2;
5360 /* ignore a leading 0x... if it is there */
5361 if (env_pv[0] == '0' && env_pv[1] == 'x')
5364 for( i = 0; isXDIGIT(*env_pv) && i < PERL_HASH_SEED_BYTES; i++ ) {
5365 seed_buffer[i] = READ_XDIGIT(env_pv) << 4;
5366 if ( isXDIGIT(*env_pv)) {
5367 seed_buffer[i] |= READ_XDIGIT(env_pv);
5370 while (isSPACE(*env_pv))
5373 if (*env_pv && !isXDIGIT(*env_pv)) {
5374 Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n");
5376 /* should we check for unparsed crap? */
5377 /* should we warn about unused hex? */
5378 /* should we warn about insufficient hex? */
5383 (void)seedDrand01((Rand_seed_t)seed());
5385 for( i = 0; i < PERL_HASH_SEED_BYTES; i++ ) {
5386 seed_buffer[i] = (unsigned char)(Drand01() * (U8_MAX+1));
5389 #ifdef USE_PERL_PERTURB_KEYS
5390 { /* initialize PL_hash_rand_bits from the hash seed.
5391 * This value is highly volatile, it is updated every
5392 * hash insert, and is used as part of hash bucket chain
5393 * randomization and hash iterator randomization. */
5394 PL_hash_rand_bits= 0xbe49d17f; /* I just picked a number */
5395 for( i = 0; i < sizeof(UV) ; i++ ) {
5396 PL_hash_rand_bits += seed_buffer[i % PERL_HASH_SEED_BYTES];
5397 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,8);
5400 env_pv= PerlEnv_getenv("PERL_PERTURB_KEYS");
5402 if (strEQ(env_pv,"0") || strEQ(env_pv,"NO")) {
5403 PL_hash_rand_bits_enabled= 0;
5404 } else if (strEQ(env_pv,"1") || strEQ(env_pv,"RANDOM")) {
5405 PL_hash_rand_bits_enabled= 1;
5406 } else if (strEQ(env_pv,"2") || strEQ(env_pv,"DETERMINISTIC")) {
5407 PL_hash_rand_bits_enabled= 2;
5409 Perl_warn(aTHX_ "perl: warning: strange setting in '$ENV{PERL_PERTURB_KEYS}': '%s'\n", env_pv);
5415 #ifdef PERL_GLOBAL_STRUCT
5417 #define PERL_GLOBAL_STRUCT_INIT
5418 #include "opcode.h" /* the ppaddr and check */
5421 Perl_init_global_struct(pTHX)
5423 struct perl_vars *plvarsp = NULL;
5424 # ifdef PERL_GLOBAL_STRUCT
5425 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5426 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5427 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5428 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5429 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5433 plvarsp = PL_VarsPtr;
5434 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5439 # define PERLVAR(prefix,var,type) /**/
5440 # define PERLVARA(prefix,var,n,type) /**/
5441 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
5442 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
5443 # include "perlvars.h"
5448 # ifdef PERL_GLOBAL_STRUCT
5451 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5452 if (!plvarsp->Gppaddr)
5456 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5457 if (!plvarsp->Gcheck)
5459 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5460 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5462 # ifdef PERL_SET_VARS
5463 PERL_SET_VARS(plvarsp);
5465 # undef PERL_GLOBAL_STRUCT_INIT
5470 #endif /* PERL_GLOBAL_STRUCT */
5472 #ifdef PERL_GLOBAL_STRUCT
5475 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5477 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
5478 # ifdef PERL_GLOBAL_STRUCT
5479 # ifdef PERL_UNSET_VARS
5480 PERL_UNSET_VARS(plvarsp);
5482 free(plvarsp->Gppaddr);
5483 free(plvarsp->Gcheck);
5484 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5490 #endif /* PERL_GLOBAL_STRUCT */
5494 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
5495 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
5496 * given, and you supply your own implementation.
5498 * The default implementation reads a single env var, PERL_MEM_LOG,
5499 * expecting one or more of the following:
5501 * \d+ - fd fd to write to : must be 1st (atoi)
5502 * 'm' - memlog was PERL_MEM_LOG=1
5503 * 's' - svlog was PERL_SV_LOG=1
5504 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
5506 * This makes the logger controllable enough that it can reasonably be
5507 * added to the system perl.
5510 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
5511 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5513 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5515 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
5516 * writes to. In the default logger, this is settable at runtime.
5518 #ifndef PERL_MEM_LOG_FD
5519 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5522 #ifndef PERL_MEM_LOG_NOIMPL
5524 # ifdef DEBUG_LEAKING_SCALARS
5525 # define SV_LOG_SERIAL_FMT " [%lu]"
5526 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
5528 # define SV_LOG_SERIAL_FMT
5529 # define _SV_LOG_SERIAL_ARG(sv)
5533 S_mem_log_common(enum mem_log_type mlt, const UV n,
5534 const UV typesize, const char *type_name, const SV *sv,
5535 Malloc_t oldalloc, Malloc_t newalloc,
5536 const char *filename, const int linenumber,
5537 const char *funcname)
5541 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
5543 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
5546 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
5548 /* We can't use SVs or PerlIO for obvious reasons,
5549 * so we'll use stdio and low-level IO instead. */
5550 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5552 # ifdef HAS_GETTIMEOFDAY
5553 # define MEM_LOG_TIME_FMT "%10d.%06d: "
5554 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
5556 gettimeofday(&tv, 0);
5558 # define MEM_LOG_TIME_FMT "%10d: "
5559 # define MEM_LOG_TIME_ARG (int)when
5563 /* If there are other OS specific ways of hires time than
5564 * gettimeofday() (see ext/Time-HiRes), the easiest way is
5565 * probably that they would be used to fill in the struct
5569 int fd = atoi(pmlenv);
5571 fd = PERL_MEM_LOG_FD;
5573 if (strchr(pmlenv, 't')) {
5574 len = my_snprintf(buf, sizeof(buf),
5575 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
5576 PerlLIO_write(fd, buf, len);
5580 len = my_snprintf(buf, sizeof(buf),
5581 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5582 " %s = %"IVdf": %"UVxf"\n",
5583 filename, linenumber, funcname, n, typesize,
5584 type_name, n * typesize, PTR2UV(newalloc));
5587 len = my_snprintf(buf, sizeof(buf),
5588 "realloc: %s:%d:%s: %"IVdf" %"UVuf
5589 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5590 filename, linenumber, funcname, n, typesize,
5591 type_name, n * typesize, PTR2UV(oldalloc),
5595 len = my_snprintf(buf, sizeof(buf),
5596 "free: %s:%d:%s: %"UVxf"\n",
5597 filename, linenumber, funcname,
5602 len = my_snprintf(buf, sizeof(buf),
5603 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
5604 mlt == MLT_NEW_SV ? "new" : "del",
5605 filename, linenumber, funcname,
5606 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
5611 PerlLIO_write(fd, buf, len);
5615 #endif /* !PERL_MEM_LOG_NOIMPL */
5617 #ifndef PERL_MEM_LOG_NOIMPL
5619 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
5620 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
5622 /* this is suboptimal, but bug compatible. User is providing their
5623 own implementation, but is getting these functions anyway, and they
5624 do nothing. But _NOIMPL users should be able to cope or fix */
5626 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
5627 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
5631 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
5633 const char *filename, const int linenumber,
5634 const char *funcname)
5636 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
5637 NULL, NULL, newalloc,
5638 filename, linenumber, funcname);
5643 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
5644 Malloc_t oldalloc, Malloc_t newalloc,
5645 const char *filename, const int linenumber,
5646 const char *funcname)
5648 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
5649 NULL, oldalloc, newalloc,
5650 filename, linenumber, funcname);
5655 Perl_mem_log_free(Malloc_t oldalloc,
5656 const char *filename, const int linenumber,
5657 const char *funcname)
5659 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
5660 filename, linenumber, funcname);
5665 Perl_mem_log_new_sv(const SV *sv,
5666 const char *filename, const int linenumber,
5667 const char *funcname)
5669 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
5670 filename, linenumber, funcname);
5674 Perl_mem_log_del_sv(const SV *sv,
5675 const char *filename, const int linenumber,
5676 const char *funcname)
5678 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
5679 filename, linenumber, funcname);
5682 #endif /* PERL_MEM_LOG */
5685 =for apidoc my_sprintf
5687 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5688 the length of the string written to the buffer. Only rare pre-ANSI systems
5689 need the wrapper function - usually this is a direct call to C<sprintf>.
5693 #ifndef SPRINTF_RETURNS_STRLEN
5695 Perl_my_sprintf(char *buffer, const char* pat, ...)
5698 PERL_ARGS_ASSERT_MY_SPRINTF;
5699 va_start(args, pat);
5700 vsprintf(buffer, pat, args);
5702 return strlen(buffer);
5707 =for apidoc my_snprintf
5709 The C library C<snprintf> functionality, if available and
5710 standards-compliant (uses C<vsnprintf>, actually). However, if the
5711 C<vsnprintf> is not available, will unfortunately use the unsafe
5712 C<vsprintf> which can overrun the buffer (there is an overrun check,
5713 but that may be too late). Consider using C<sv_vcatpvf> instead, or
5714 getting C<vsnprintf>.
5719 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
5723 PERL_ARGS_ASSERT_MY_SNPRINTF;
5724 va_start(ap, format);
5725 #ifdef HAS_VSNPRINTF
5726 retval = vsnprintf(buffer, len, format, ap);
5728 retval = vsprintf(buffer, format, ap);
5731 /* vsprintf() shows failure with < 0 */
5733 #ifdef HAS_VSNPRINTF
5734 /* vsnprintf() shows failure with >= len */
5736 (len > 0 && (Size_t)retval >= len)
5739 Perl_croak_nocontext("panic: my_snprintf buffer overflow");
5744 =for apidoc my_vsnprintf
5746 The C library C<vsnprintf> if available and standards-compliant.
5747 However, if if the C<vsnprintf> is not available, will unfortunately
5748 use the unsafe C<vsprintf> which can overrun the buffer (there is an
5749 overrun check, but that may be too late). Consider using
5750 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
5755 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
5761 PERL_ARGS_ASSERT_MY_VSNPRINTF;
5763 Perl_va_copy(ap, apc);
5764 # ifdef HAS_VSNPRINTF
5765 retval = vsnprintf(buffer, len, format, apc);
5767 retval = vsprintf(buffer, format, apc);
5770 # ifdef HAS_VSNPRINTF
5771 retval = vsnprintf(buffer, len, format, ap);
5773 retval = vsprintf(buffer, format, ap);
5775 #endif /* #ifdef NEED_VA_COPY */
5776 /* vsprintf() shows failure with < 0 */
5778 #ifdef HAS_VSNPRINTF
5779 /* vsnprintf() shows failure with >= len */
5781 (len > 0 && (Size_t)retval >= len)
5784 Perl_croak_nocontext("panic: my_vsnprintf buffer overflow");
5789 Perl_my_clearenv(pTHX)
5792 #if ! defined(PERL_MICRO)
5793 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5795 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5796 # if defined(USE_ENVIRON_ARRAY)
5797 # if defined(USE_ITHREADS)
5798 /* only the parent thread can clobber the process environment */
5799 if (PL_curinterp == aTHX)
5800 # endif /* USE_ITHREADS */
5802 # if ! defined(PERL_USE_SAFE_PUTENV)
5803 if ( !PL_use_safe_putenv) {
5805 if (environ == PL_origenviron)
5806 environ = (char**)safesysmalloc(sizeof(char*));
5808 for (i = 0; environ[i]; i++)
5809 (void)safesysfree(environ[i]);
5812 # else /* PERL_USE_SAFE_PUTENV */
5813 # if defined(HAS_CLEARENV)
5815 # elif defined(HAS_UNSETENV)
5816 int bsiz = 80; /* Most envvar names will be shorter than this. */
5817 char *buf = (char*)safesysmalloc(bsiz);
5818 while (*environ != NULL) {
5819 char *e = strchr(*environ, '=');
5820 int l = e ? e - *environ : (int)strlen(*environ);
5822 (void)safesysfree(buf);
5823 bsiz = l + 1; /* + 1 for the \0. */
5824 buf = (char*)safesysmalloc(bsiz);
5826 memcpy(buf, *environ, l);
5828 (void)unsetenv(buf);
5830 (void)safesysfree(buf);
5831 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5832 /* Just null environ and accept the leakage. */
5834 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5835 # endif /* ! PERL_USE_SAFE_PUTENV */
5837 # endif /* USE_ENVIRON_ARRAY */
5838 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5839 #endif /* PERL_MICRO */
5842 #ifdef PERL_IMPLICIT_CONTEXT
5844 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
5845 the global PL_my_cxt_index is incremented, and that value is assigned to
5846 that module's static my_cxt_index (who's address is passed as an arg).
5847 Then, for each interpreter this function is called for, it makes sure a
5848 void* slot is available to hang the static data off, by allocating or
5849 extending the interpreter's PL_my_cxt_list array */
5851 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
5853 Perl_my_cxt_init(pTHX_ int *index, size_t size)
5857 PERL_ARGS_ASSERT_MY_CXT_INIT;
5859 /* this module hasn't been allocated an index yet */
5860 #if defined(USE_ITHREADS)
5861 MUTEX_LOCK(&PL_my_ctx_mutex);
5863 *index = PL_my_cxt_index++;
5864 #if defined(USE_ITHREADS)
5865 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5869 /* make sure the array is big enough */
5870 if (PL_my_cxt_size <= *index) {
5871 if (PL_my_cxt_size) {
5872 while (PL_my_cxt_size <= *index)
5873 PL_my_cxt_size *= 2;
5874 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5877 PL_my_cxt_size = 16;
5878 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5881 /* newSV() allocates one more than needed */
5882 p = (void*)SvPVX(newSV(size-1));
5883 PL_my_cxt_list[*index] = p;
5884 Zero(p, size, char);
5888 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5891 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
5896 PERL_ARGS_ASSERT_MY_CXT_INDEX;
5898 for (index = 0; index < PL_my_cxt_index; index++) {
5899 const char *key = PL_my_cxt_keys[index];
5900 /* try direct pointer compare first - there are chances to success,
5901 * and it's much faster.
5903 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
5910 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
5916 PERL_ARGS_ASSERT_MY_CXT_INIT;
5918 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
5920 /* this module hasn't been allocated an index yet */
5921 #if defined(USE_ITHREADS)
5922 MUTEX_LOCK(&PL_my_ctx_mutex);
5924 index = PL_my_cxt_index++;
5925 #if defined(USE_ITHREADS)
5926 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5930 /* make sure the array is big enough */
5931 if (PL_my_cxt_size <= index) {
5932 int old_size = PL_my_cxt_size;
5934 if (PL_my_cxt_size) {
5935 while (PL_my_cxt_size <= index)
5936 PL_my_cxt_size *= 2;
5937 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5938 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5941 PL_my_cxt_size = 16;
5942 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5943 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5945 for (i = old_size; i < PL_my_cxt_size; i++) {
5946 PL_my_cxt_keys[i] = 0;
5947 PL_my_cxt_list[i] = 0;
5950 PL_my_cxt_keys[index] = my_cxt_key;
5951 /* newSV() allocates one more than needed */
5952 p = (void*)SvPVX(newSV(size-1));
5953 PL_my_cxt_list[index] = p;
5954 Zero(p, size, char);
5957 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5958 #endif /* PERL_IMPLICIT_CONTEXT */
5961 Perl_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
5965 const char *vn = NULL;
5966 SV *const module = PL_stack_base[ax];
5968 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
5970 if (items >= 2) /* version supplied as bootstrap arg */
5971 sv = PL_stack_base[ax + 1];
5973 /* XXX GV_ADDWARN */
5975 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
5976 if (!sv || !SvOK(sv)) {
5978 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
5982 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
5983 SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version")
5984 ? sv : sv_2mortal(new_version(sv));
5985 xssv = upg_version(xssv, 0);
5986 if ( vcmp(pmsv,xssv) ) {
5987 SV *string = vstringify(xssv);
5988 SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
5989 " does not match ", module, string);
5991 SvREFCNT_dec(string);
5992 string = vstringify(pmsv);
5995 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, module, vn,
5998 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, string);
6000 SvREFCNT_dec(string);
6002 Perl_sv_2mortal(aTHX_ xpt);
6003 Perl_croak_sv(aTHX_ xpt);
6009 Perl_xs_apiversion_bootcheck(pTHX_ SV *module, const char *api_p,
6013 SV *compver = Perl_newSVpvn_flags(aTHX_ api_p, api_len, SVs_TEMP);
6016 PERL_ARGS_ASSERT_XS_APIVERSION_BOOTCHECK;
6018 /* This might croak */
6019 compver = upg_version(compver, 0);
6020 /* This should never croak */
6021 runver = new_version(PL_apiversion);
6022 if (vcmp(compver, runver)) {
6023 SV *compver_string = vstringify(compver);
6024 SV *runver_string = vstringify(runver);
6025 xpt = Perl_newSVpvf(aTHX_ "Perl API version %"SVf
6026 " of %"SVf" does not match %"SVf,
6027 compver_string, module, runver_string);
6028 Perl_sv_2mortal(aTHX_ xpt);
6030 SvREFCNT_dec(compver_string);
6031 SvREFCNT_dec(runver_string);
6033 SvREFCNT_dec(runver);
6035 Perl_croak_sv(aTHX_ xpt);
6040 Perl_my_strlcat(char *dst, const char *src, Size_t size)
6042 Size_t used, length, copy;
6045 length = strlen(src);
6046 if (size > 0 && used < size - 1) {
6047 copy = (length >= size - used) ? size - used - 1 : length;
6048 memcpy(dst + used, src, copy);
6049 dst[used + copy] = '\0';
6051 return used + length;
6057 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
6059 Size_t length, copy;
6061 length = strlen(src);
6063 copy = (length >= size) ? size - 1 : length;
6064 memcpy(dst, src, copy);
6071 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
6072 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
6073 long _ftol( double ); /* Defined by VC6 C libs. */
6074 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
6077 PERL_STATIC_INLINE bool
6078 S_gv_has_usable_name(pTHX_ GV *gv)
6082 && HvENAME(GvSTASH(gv))
6083 && (gvp = (GV **)hv_fetch(
6084 GvSTASH(gv), GvNAME(gv),
6085 GvNAMEUTF8(gv) ? -GvNAMELEN(gv) : GvNAMELEN(gv), 0
6091 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
6094 SV * const dbsv = GvSVn(PL_DBsub);
6095 const bool save_taint = TAINT_get;
6097 /* When we are called from pp_goto (svp is null),
6098 * we do not care about using dbsv to call CV;
6099 * it's for informational purposes only.
6102 PERL_ARGS_ASSERT_GET_DB_SUB;
6106 if (!PERLDB_SUB_NN) {
6110 gv_efullname3(dbsv, gv, NULL);
6112 else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
6113 || strEQ(GvNAME(gv), "END")
6114 || ( /* Could be imported, and old sub redefined. */
6115 (GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv))
6117 !( (SvTYPE(*svp) == SVt_PVGV)
6118 && (GvCV((const GV *)*svp) == cv)
6119 /* Use GV from the stack as a fallback. */
6120 && S_gv_has_usable_name(aTHX_ gv = (GV *)*svp)
6124 /* GV is potentially non-unique, or contain different CV. */
6125 SV * const tmp = newRV(MUTABLE_SV(cv));
6126 sv_setsv(dbsv, tmp);
6130 sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv)));
6131 sv_catpvs(dbsv, "::");
6133 dbsv, GvNAME(gv), GvNAMELEN(gv),
6134 GvNAMEUTF8(gv) ? SV_CATUTF8 : SV_CATBYTES
6139 const int type = SvTYPE(dbsv);
6140 if (type < SVt_PVIV && type != SVt_IV)
6141 sv_upgrade(dbsv, SVt_PVIV);
6142 (void)SvIOK_on(dbsv);
6143 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
6145 TAINT_IF(save_taint);
6146 #ifdef NO_TAINT_SUPPORT
6147 PERL_UNUSED_VAR(save_taint);
6152 Perl_my_dirfd(pTHX_ DIR * dir) {
6154 /* Most dirfd implementations have problems when passed NULL. */
6159 #elif defined(HAS_DIR_DD_FD)
6162 Perl_die(aTHX_ PL_no_func, "dirfd");
6163 assert(0); /* NOT REACHED */
6169 Perl_get_re_arg(pTHX_ SV *sv) {
6175 sv = MUTABLE_SV(SvRV(sv));
6176 if (SvTYPE(sv) == SVt_REGEXP)
6177 return (REGEXP*) sv;
6185 * c-indentation-style: bsd
6187 * indent-tabs-mode: nil
6190 * ex: set ts=8 sts=4 sw=4 et: