3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * 'Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content.' --Gandalf to Pippin
15 * [p.598 of _The Lord of the Rings_, III/xi: "The PalantÃr"]
18 /* This file contains assorted utility routines.
19 * Which is a polite way of saying any stuff that people couldn't think of
20 * a better place for. Amongst other things, it includes the warning and
21 * dieing stuff, plus wrappers for malloc code.
25 #define PERL_IN_UTIL_C
29 #include "perliol.h" /* For PerlIOUnix_refcnt */
35 # define SIG_ERR ((Sighandler_t) -1)
40 /* Missing protos on LynxOS */
45 # include <sys/wait.h>
50 # include <sys/select.h>
56 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
57 # define FD_CLOEXEC 1 /* NeXT needs this */
60 /* NOTE: Do not call the next three routines directly. Use the macros
61 * in handy.h, so that we can easily redefine everything to do tracking of
62 * allocated hunks back to the original New to track down any memory leaks.
63 * XXX This advice seems to be widely ignored :-( --AD August 1996.
70 /* Can't use PerlIO to write as it allocates memory */
71 PerlLIO_write(PerlIO_fileno(Perl_error_log),
72 PL_no_mem, strlen(PL_no_mem));
74 NORETURN_FUNCTION_END;
77 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
78 # define ALWAYS_NEED_THX
81 /* paranoid version of system's malloc() */
84 Perl_safesysmalloc(MEM_SIZE size)
86 #ifdef ALWAYS_NEED_THX
92 PerlIO_printf(Perl_error_log,
93 "Allocation too large: %lx\n", size) FLUSH;
96 #endif /* HAS_64K_LIMIT */
97 #ifdef PERL_TRACK_MEMPOOL
102 Perl_croak_nocontext("panic: malloc");
104 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
105 PERL_ALLOC_CHECK(ptr);
107 #ifdef PERL_TRACK_MEMPOOL
108 struct perl_memory_debug_header *const header
109 = (struct perl_memory_debug_header *)ptr;
113 PoisonNew(((char *)ptr), size, char);
116 #ifdef PERL_TRACK_MEMPOOL
117 header->interpreter = aTHX;
118 /* Link us into the list. */
119 header->prev = &PL_memory_debug_header;
120 header->next = PL_memory_debug_header.next;
121 PL_memory_debug_header.next = header;
122 header->next->prev = header;
126 ptr = (Malloc_t)((char*)ptr+sTHX);
128 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
132 #ifndef ALWAYS_NEED_THX
138 return write_no_mem();
144 /* paranoid version of system's realloc() */
147 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
149 #ifdef ALWAYS_NEED_THX
153 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
154 Malloc_t PerlMem_realloc();
155 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
159 PerlIO_printf(Perl_error_log,
160 "Reallocation too large: %lx\n", size) FLUSH;
163 #endif /* HAS_64K_LIMIT */
170 return safesysmalloc(size);
171 #ifdef PERL_TRACK_MEMPOOL
172 where = (Malloc_t)((char*)where-sTHX);
175 struct perl_memory_debug_header *const header
176 = (struct perl_memory_debug_header *)where;
178 if (header->interpreter != aTHX) {
179 Perl_croak_nocontext("panic: realloc from wrong pool");
181 assert(header->next->prev == header);
182 assert(header->prev->next == header);
184 if (header->size > size) {
185 const MEM_SIZE freed_up = header->size - size;
186 char *start_of_freed = ((char *)where) + size;
187 PoisonFree(start_of_freed, freed_up, char);
195 Perl_croak_nocontext("panic: realloc");
197 ptr = (Malloc_t)PerlMem_realloc(where,size);
198 PERL_ALLOC_CHECK(ptr);
200 /* MUST do this fixup first, before doing ANYTHING else, as anything else
201 might allocate memory/free/move memory, and until we do the fixup, it
202 may well be chasing (and writing to) free memory. */
203 #ifdef PERL_TRACK_MEMPOOL
205 struct perl_memory_debug_header *const header
206 = (struct perl_memory_debug_header *)ptr;
209 if (header->size < size) {
210 const MEM_SIZE fresh = size - header->size;
211 char *start_of_fresh = ((char *)ptr) + size;
212 PoisonNew(start_of_fresh, fresh, char);
216 header->next->prev = header;
217 header->prev->next = header;
219 ptr = (Malloc_t)((char*)ptr+sTHX);
223 /* In particular, must do that fixup above before logging anything via
224 *printf(), as it can reallocate memory, which can cause SEGVs. */
226 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
227 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
234 #ifndef ALWAYS_NEED_THX
240 return write_no_mem();
246 /* safe version of system's free() */
249 Perl_safesysfree(Malloc_t where)
251 #ifdef ALWAYS_NEED_THX
256 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
258 #ifdef PERL_TRACK_MEMPOOL
259 where = (Malloc_t)((char*)where-sTHX);
261 struct perl_memory_debug_header *const header
262 = (struct perl_memory_debug_header *)where;
264 if (header->interpreter != aTHX) {
265 Perl_croak_nocontext("panic: free from wrong pool");
268 Perl_croak_nocontext("panic: duplicate free");
270 if (!(header->next) || header->next->prev != header
271 || header->prev->next != header) {
272 Perl_croak_nocontext("panic: bad free");
274 /* Unlink us from the chain. */
275 header->next->prev = header->prev;
276 header->prev->next = header->next;
278 PoisonNew(where, header->size, char);
280 /* Trigger the duplicate free warning. */
288 /* safe version of system's calloc() */
291 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
293 #ifdef ALWAYS_NEED_THX
297 MEM_SIZE total_size = 0;
299 /* Even though calloc() for zero bytes is strange, be robust. */
300 if (size && (count <= MEM_SIZE_MAX / size))
301 total_size = size * count;
303 Perl_croak_nocontext("%s", PL_memory_wrap);
304 #ifdef PERL_TRACK_MEMPOOL
305 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
308 Perl_croak_nocontext("%s", PL_memory_wrap);
311 if (total_size > 0xffff) {
312 PerlIO_printf(Perl_error_log,
313 "Allocation too large: %lx\n", total_size) FLUSH;
316 #endif /* HAS_64K_LIMIT */
318 if ((long)size < 0 || (long)count < 0)
319 Perl_croak_nocontext("panic: calloc");
321 #ifdef PERL_TRACK_MEMPOOL
322 /* Have to use malloc() because we've added some space for our tracking
324 /* malloc(0) is non-portable. */
325 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
327 /* Use calloc() because it might save a memset() if the memory is fresh
328 and clean from the OS. */
330 ptr = (Malloc_t)PerlMem_calloc(count, size);
331 else /* calloc(0) is non-portable. */
332 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
334 PERL_ALLOC_CHECK(ptr);
335 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)total_size));
337 #ifdef PERL_TRACK_MEMPOOL
339 struct perl_memory_debug_header *const header
340 = (struct perl_memory_debug_header *)ptr;
342 memset((void*)ptr, 0, total_size);
343 header->interpreter = aTHX;
344 /* Link us into the list. */
345 header->prev = &PL_memory_debug_header;
346 header->next = PL_memory_debug_header.next;
347 PL_memory_debug_header.next = header;
348 header->next->prev = header;
350 header->size = total_size;
352 ptr = (Malloc_t)((char*)ptr+sTHX);
358 #ifndef ALWAYS_NEED_THX
363 return write_no_mem();
367 /* These must be defined when not using Perl's malloc for binary
372 Malloc_t Perl_malloc (MEM_SIZE nbytes)
375 return (Malloc_t)PerlMem_malloc(nbytes);
378 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
381 return (Malloc_t)PerlMem_calloc(elements, size);
384 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
387 return (Malloc_t)PerlMem_realloc(where, nbytes);
390 Free_t Perl_mfree (Malloc_t where)
398 /* copy a string up to some (non-backslashed) delimiter, if any */
401 Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
405 PERL_ARGS_ASSERT_DELIMCPY;
407 for (tolen = 0; from < fromend; from++, tolen++) {
409 if (from[1] != delim) {
416 else if (*from == delim)
427 /* return ptr to little string in big string, NULL if not found */
428 /* This routine was donated by Corey Satten. */
431 Perl_instr(register const char *big, register const char *little)
435 PERL_ARGS_ASSERT_INSTR;
443 register const char *s, *x;
446 for (x=big,s=little; *s; /**/ ) {
457 return (char*)(big-1);
462 /* same as instr but allow embedded nulls */
465 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
467 PERL_ARGS_ASSERT_NINSTR;
471 const char first = *little;
473 bigend -= lend - little++;
475 while (big <= bigend) {
476 if (*big++ == first) {
477 for (x=big,s=little; s < lend; x++,s++) {
481 return (char*)(big-1);
488 /* reverse of the above--find last substring */
491 Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
493 register const char *bigbeg;
494 register const I32 first = *little;
495 register const char * const littleend = lend;
497 PERL_ARGS_ASSERT_RNINSTR;
499 if (little >= littleend)
500 return (char*)bigend;
502 big = bigend - (littleend - little++);
503 while (big >= bigbeg) {
504 register const char *s, *x;
507 for (x=big+2,s=little; s < littleend; /**/ ) {
516 return (char*)(big+1);
521 /* As a space optimization, we do not compile tables for strings of length
522 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
523 special-cased in fbm_instr().
525 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
528 =head1 Miscellaneous Functions
530 =for apidoc fbm_compile
532 Analyses the string in order to make fast searches on it using fbm_instr()
533 -- the Boyer-Moore algorithm.
539 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
542 register const U8 *s;
548 PERL_ARGS_ASSERT_FBM_COMPILE;
550 if (flags & FBMcf_TAIL) {
551 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
552 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
553 if (mg && mg->mg_len >= 0)
556 s = (U8*)SvPV_force_mutable(sv, len);
557 if (len == 0) /* TAIL might be on a zero-length string. */
559 SvUPGRADE(sv, SVt_PVGV);
564 const unsigned char *sb;
565 const U8 mlen = (len>255) ? 255 : (U8)len;
568 Sv_Grow(sv, len + 256 + PERL_FBM_TABLE_OFFSET);
570 = (unsigned char*)(SvPVX_mutable(sv) + len + PERL_FBM_TABLE_OFFSET);
571 s = table - 1 - PERL_FBM_TABLE_OFFSET; /* last char */
572 memset((void*)table, mlen, 256);
574 sb = s - mlen + 1; /* first char (maybe) */
576 if (table[*s] == mlen)
581 Sv_Grow(sv, len + PERL_FBM_TABLE_OFFSET);
583 sv_magic(sv, NULL, PERL_MAGIC_bm, NULL, 0); /* deep magic */
585 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
586 for (i = 0; i < len; i++) {
587 if (PL_freq[s[i]] < frequency) {
589 frequency = PL_freq[s[i]];
592 BmFLAGS(sv) = (U8)flags;
593 BmRARE(sv) = s[rarest];
594 BmPREVIOUS(sv) = rarest;
595 BmUSEFUL(sv) = 100; /* Initial value */
596 if (flags & FBMcf_TAIL)
598 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %lu\n",
599 BmRARE(sv),(unsigned long)BmPREVIOUS(sv)));
602 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
603 /* If SvTAIL is actually due to \Z or \z, this gives false positives
607 =for apidoc fbm_instr
609 Returns the location of the SV in the string delimited by C<str> and
610 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
611 does not have to be fbm_compiled, but the search will not be as fast
618 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
620 register unsigned char *s;
622 register const unsigned char *little
623 = (const unsigned char *)SvPV_const(littlestr,l);
624 register STRLEN littlelen = l;
625 register const I32 multiline = flags & FBMrf_MULTILINE;
627 PERL_ARGS_ASSERT_FBM_INSTR;
629 if ((STRLEN)(bigend - big) < littlelen) {
630 if ( SvTAIL(littlestr)
631 && ((STRLEN)(bigend - big) == littlelen - 1)
633 || (*big == *little &&
634 memEQ((char *)big, (char *)little, littlelen - 1))))
639 if (littlelen <= 2) { /* Special-cased */
641 if (littlelen == 1) {
642 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
643 /* Know that bigend != big. */
644 if (bigend[-1] == '\n')
645 return (char *)(bigend - 1);
646 return (char *) bigend;
654 if (SvTAIL(littlestr))
655 return (char *) bigend;
659 return (char*)big; /* Cannot be SvTAIL! */
662 if (SvTAIL(littlestr) && !multiline) {
663 if (bigend[-1] == '\n' && bigend[-2] == *little)
664 return (char*)bigend - 2;
665 if (bigend[-1] == *little)
666 return (char*)bigend - 1;
670 /* This should be better than FBM if c1 == c2, and almost
671 as good otherwise: maybe better since we do less indirection.
672 And we save a lot of memory by caching no table. */
673 const unsigned char c1 = little[0];
674 const unsigned char c2 = little[1];
679 while (s <= bigend) {
689 goto check_1char_anchor;
700 goto check_1char_anchor;
703 while (s <= bigend) {
708 goto check_1char_anchor;
717 check_1char_anchor: /* One char and anchor! */
718 if (SvTAIL(littlestr) && (*bigend == *little))
719 return (char *)bigend; /* bigend is already decremented. */
722 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
723 s = bigend - littlelen;
724 if (s >= big && bigend[-1] == '\n' && *s == *little
725 /* Automatically of length > 2 */
726 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
728 return (char*)s; /* how sweet it is */
731 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
733 return (char*)s + 1; /* how sweet it is */
737 if (!SvVALID(littlestr)) {
738 char * const b = ninstr((char*)big,(char*)bigend,
739 (char*)little, (char*)little + littlelen);
741 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
742 /* Chop \n from littlestr: */
743 s = bigend - littlelen + 1;
745 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
755 if (littlelen > (STRLEN)(bigend - big))
759 register const unsigned char * const table
760 = little + littlelen + PERL_FBM_TABLE_OFFSET;
761 register const unsigned char *oldlittle;
763 --littlelen; /* Last char found by table lookup */
766 little += littlelen; /* last char */
772 if ((tmp = table[*s])) {
773 if ((s += tmp) < bigend)
777 else { /* less expensive than calling strncmp() */
778 register unsigned char * const olds = s;
783 if (*--s == *--little)
785 s = olds + 1; /* here we pay the price for failure */
787 if (s < bigend) /* fake up continue to outer loop */
796 && (BmFLAGS(littlestr) & FBMcf_TAIL)
797 && memEQ((char *)(bigend - littlelen),
798 (char *)(oldlittle - littlelen), littlelen) )
799 return (char*)bigend - littlelen;
804 /* start_shift, end_shift are positive quantities which give offsets
805 of ends of some substring of bigstr.
806 If "last" we want the last occurrence.
807 old_posp is the way of communication between consequent calls if
808 the next call needs to find the .
809 The initial *old_posp should be -1.
811 Note that we take into account SvTAIL, so one can get extra
812 optimizations if _ALL flag is set.
815 /* If SvTAIL is actually due to \Z or \z, this gives false positives
816 if PL_multiline. In fact if !PL_multiline the authoritative answer
817 is not supported yet. */
820 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
823 register const unsigned char *big;
825 register I32 previous;
827 register const unsigned char *little;
828 register I32 stop_pos;
829 register const unsigned char *littleend;
832 PERL_ARGS_ASSERT_SCREAMINSTR;
834 assert(SvTYPE(littlestr) == SVt_PVGV);
835 assert(SvVALID(littlestr));
838 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
839 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
841 if ( BmRARE(littlestr) == '\n'
842 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
843 little = (const unsigned char *)(SvPVX_const(littlestr));
844 littleend = little + SvCUR(littlestr);
851 little = (const unsigned char *)(SvPVX_const(littlestr));
852 littleend = little + SvCUR(littlestr);
854 /* The value of pos we can start at: */
855 previous = BmPREVIOUS(littlestr);
856 big = (const unsigned char *)(SvPVX_const(bigstr));
857 /* The value of pos we can stop at: */
858 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
859 if (previous + start_shift > stop_pos) {
861 stop_pos does not include SvTAIL in the count, so this check is incorrect
862 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
865 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
870 while (pos < previous + start_shift) {
871 if (!(pos += PL_screamnext[pos]))
876 register const unsigned char *s, *x;
877 if (pos >= stop_pos) break;
878 if (big[pos] != first)
880 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
886 if (s == littleend) {
888 if (!last) return (char *)(big+pos);
891 } while ( pos += PL_screamnext[pos] );
893 return (char *)(big+(*old_posp));
895 if (!SvTAIL(littlestr) || (end_shift > 0))
897 /* Ignore the trailing "\n". This code is not microoptimized */
898 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
899 stop_pos = littleend - little; /* Actual littlestr len */
904 && ((stop_pos == 1) ||
905 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
913 Returns true if the leading len bytes of the strings s1 and s2 are the same
914 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
915 match themselves and their opposite case counterparts. Non-cased and non-ASCII
916 range bytes match only themselves.
923 Perl_foldEQ(const char *s1, const char *s2, register I32 len)
925 register const U8 *a = (const U8 *)s1;
926 register const U8 *b = (const U8 *)s2;
928 PERL_ARGS_ASSERT_FOLDEQ;
931 if (*a != *b && *a != PL_fold[*b])
938 Perl_foldEQ_latin1(const char *s1, const char *s2, register I32 len)
940 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
941 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
942 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
943 * does it check that the strings each have at least 'len' characters */
945 register const U8 *a = (const U8 *)s1;
946 register const U8 *b = (const U8 *)s2;
948 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
951 if (*a != *b && *a != PL_fold_latin1[*b]) {
960 =for apidoc foldEQ_locale
962 Returns true if the leading len bytes of the strings s1 and s2 are the same
963 case-insensitively in the current locale; false otherwise.
969 Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
972 register const U8 *a = (const U8 *)s1;
973 register const U8 *b = (const U8 *)s2;
975 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
978 if (*a != *b && *a != PL_fold_locale[*b])
985 /* copy a string to a safe spot */
988 =head1 Memory Management
992 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
993 string which is a duplicate of C<pv>. The size of the string is
994 determined by C<strlen()>. The memory allocated for the new string can
995 be freed with the C<Safefree()> function.
1001 Perl_savepv(pTHX_ const char *pv)
1003 PERL_UNUSED_CONTEXT;
1008 const STRLEN pvlen = strlen(pv)+1;
1009 Newx(newaddr, pvlen, char);
1010 return (char*)memcpy(newaddr, pv, pvlen);
1014 /* same thing but with a known length */
1019 Perl's version of what C<strndup()> would be if it existed. Returns a
1020 pointer to a newly allocated string which is a duplicate of the first
1021 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
1022 the new string can be freed with the C<Safefree()> function.
1028 Perl_savepvn(pTHX_ const char *pv, register I32 len)
1030 register char *newaddr;
1031 PERL_UNUSED_CONTEXT;
1033 Newx(newaddr,len+1,char);
1034 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1036 /* might not be null terminated */
1037 newaddr[len] = '\0';
1038 return (char *) CopyD(pv,newaddr,len,char);
1041 return (char *) ZeroD(newaddr,len+1,char);
1046 =for apidoc savesharedpv
1048 A version of C<savepv()> which allocates the duplicate string in memory
1049 which is shared between threads.
1054 Perl_savesharedpv(pTHX_ const char *pv)
1056 register char *newaddr;
1061 pvlen = strlen(pv)+1;
1062 newaddr = (char*)PerlMemShared_malloc(pvlen);
1064 return write_no_mem();
1066 return (char*)memcpy(newaddr, pv, pvlen);
1070 =for apidoc savesharedpvn
1072 A version of C<savepvn()> which allocates the duplicate string in memory
1073 which is shared between threads. (With the specific difference that a NULL
1074 pointer is not acceptable)
1079 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1081 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1083 PERL_ARGS_ASSERT_SAVESHAREDPVN;
1086 return write_no_mem();
1088 newaddr[len] = '\0';
1089 return (char*)memcpy(newaddr, pv, len);
1093 =for apidoc savesvpv
1095 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1096 the passed in SV using C<SvPV()>
1102 Perl_savesvpv(pTHX_ SV *sv)
1105 const char * const pv = SvPV_const(sv, len);
1106 register char *newaddr;
1108 PERL_ARGS_ASSERT_SAVESVPV;
1111 Newx(newaddr,len,char);
1112 return (char *) CopyD(pv,newaddr,len,char);
1116 =for apidoc savesharedsvpv
1118 A version of C<savesharedpv()> which allocates the duplicate string in
1119 memory which is shared between threads.
1125 Perl_savesharedsvpv(pTHX_ SV *sv)
1128 const char * const pv = SvPV_const(sv, len);
1130 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1132 return savesharedpvn(pv, len);
1135 /* the SV for Perl_form() and mess() is not kept in an arena */
1144 if (PL_phase != PERL_PHASE_DESTRUCT)
1145 return newSVpvs_flags("", SVs_TEMP);
1150 /* Create as PVMG now, to avoid any upgrading later */
1152 Newxz(any, 1, XPVMG);
1153 SvFLAGS(sv) = SVt_PVMG;
1154 SvANY(sv) = (void*)any;
1156 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1161 #if defined(PERL_IMPLICIT_CONTEXT)
1163 Perl_form_nocontext(const char* pat, ...)
1168 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1169 va_start(args, pat);
1170 retval = vform(pat, &args);
1174 #endif /* PERL_IMPLICIT_CONTEXT */
1177 =head1 Miscellaneous Functions
1180 Takes a sprintf-style format pattern and conventional
1181 (non-SV) arguments and returns the formatted string.
1183 (char *) Perl_form(pTHX_ const char* pat, ...)
1185 can be used any place a string (char *) is required:
1187 char * s = Perl_form("%d.%d",major,minor);
1189 Uses a single private buffer so if you want to format several strings you
1190 must explicitly copy the earlier strings away (and free the copies when you
1197 Perl_form(pTHX_ const char* pat, ...)
1201 PERL_ARGS_ASSERT_FORM;
1202 va_start(args, pat);
1203 retval = vform(pat, &args);
1209 Perl_vform(pTHX_ const char *pat, va_list *args)
1211 SV * const sv = mess_alloc();
1212 PERL_ARGS_ASSERT_VFORM;
1213 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1218 =for apidoc Am|SV *|mess|const char *pat|...
1220 Take a sprintf-style format pattern and argument list. These are used to
1221 generate a string message. If the message does not end with a newline,
1222 then it will be extended with some indication of the current location
1223 in the code, as described for L</mess_sv>.
1225 Normally, the resulting message is returned in a new mortal SV.
1226 During global destruction a single SV may be shared between uses of
1232 #if defined(PERL_IMPLICIT_CONTEXT)
1234 Perl_mess_nocontext(const char *pat, ...)
1239 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1240 va_start(args, pat);
1241 retval = vmess(pat, &args);
1245 #endif /* PERL_IMPLICIT_CONTEXT */
1248 Perl_mess(pTHX_ const char *pat, ...)
1252 PERL_ARGS_ASSERT_MESS;
1253 va_start(args, pat);
1254 retval = vmess(pat, &args);
1260 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1263 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1265 PERL_ARGS_ASSERT_CLOSEST_COP;
1267 if (!o || o == PL_op)
1270 if (o->op_flags & OPf_KIDS) {
1272 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1275 /* If the OP_NEXTSTATE has been optimised away we can still use it
1276 * the get the file and line number. */
1278 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1279 cop = (const COP *)kid;
1281 /* Keep searching, and return when we've found something. */
1283 new_cop = closest_cop(cop, kid);
1289 /* Nothing found. */
1295 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1297 Expands a message, intended for the user, to include an indication of
1298 the current location in the code, if the message does not already appear
1301 C<basemsg> is the initial message or object. If it is a reference, it
1302 will be used as-is and will be the result of this function. Otherwise it
1303 is used as a string, and if it already ends with a newline, it is taken
1304 to be complete, and the result of this function will be the same string.
1305 If the message does not end with a newline, then a segment such as C<at
1306 foo.pl line 37> will be appended, and possibly other clauses indicating
1307 the current state of execution. The resulting message will end with a
1310 Normally, the resulting message is returned in a new mortal SV.
1311 During global destruction a single SV may be shared between uses of this
1312 function. If C<consume> is true, then the function is permitted (but not
1313 required) to modify and return C<basemsg> instead of allocating a new SV.
1319 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1324 PERL_ARGS_ASSERT_MESS_SV;
1326 if (SvROK(basemsg)) {
1332 sv_setsv(sv, basemsg);
1337 if (SvPOK(basemsg) && consume) {
1342 sv_copypv(sv, basemsg);
1345 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1347 * Try and find the file and line for PL_op. This will usually be
1348 * PL_curcop, but it might be a cop that has been optimised away. We
1349 * can try to find such a cop by searching through the optree starting
1350 * from the sibling of PL_curcop.
1353 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1358 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1359 OutCopFILE(cop), (IV)CopLINE(cop));
1360 /* Seems that GvIO() can be untrustworthy during global destruction. */
1361 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1362 && IoLINES(GvIOp(PL_last_in_gv)))
1364 const bool line_mode = (RsSIMPLE(PL_rs) &&
1365 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1366 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1367 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1368 line_mode ? "line" : "chunk",
1369 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1371 if (PL_phase == PERL_PHASE_DESTRUCT)
1372 sv_catpvs(sv, " during global destruction");
1373 sv_catpvs(sv, ".\n");
1379 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1381 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1382 argument list. These are used to generate a string message. If the
1383 message does not end with a newline, then it will be extended with
1384 some indication of the current location in the code, as described for
1387 Normally, the resulting message is returned in a new mortal SV.
1388 During global destruction a single SV may be shared between uses of
1395 Perl_vmess(pTHX_ const char *pat, va_list *args)
1398 SV * const sv = mess_alloc();
1400 PERL_ARGS_ASSERT_VMESS;
1402 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1403 return mess_sv(sv, 1);
1407 Perl_write_to_stderr(pTHX_ SV* msv)
1413 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1415 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1416 && (io = GvIO(PL_stderrgv))
1417 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1418 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1419 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1422 /* SFIO can really mess with your errno */
1425 PerlIO * const serr = Perl_error_log;
1427 do_print(msv, serr);
1428 (void)PerlIO_flush(serr);
1436 =head1 Warning and Dieing
1439 /* Common code used in dieing and warning */
1442 S_with_queued_errors(pTHX_ SV *ex)
1444 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1445 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1446 sv_catsv(PL_errors, ex);
1447 ex = sv_mortalcopy(PL_errors);
1448 SvCUR_set(PL_errors, 0);
1454 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1460 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1461 /* sv_2cv might call Perl_croak() or Perl_warner() */
1462 SV * const oldhook = *hook;
1470 cv = sv_2cv(oldhook, &stash, &gv, 0);
1472 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1482 exarg = newSVsv(ex);
1483 SvREADONLY_on(exarg);
1486 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1490 call_sv(MUTABLE_SV(cv), G_DISCARD);
1499 =for apidoc Am|OP *|die_sv|SV *baseex
1501 Behaves the same as L</croak_sv>, except for the return type.
1502 It should be used only where the C<OP *> return type is required.
1503 The function never actually returns.
1509 Perl_die_sv(pTHX_ SV *baseex)
1511 PERL_ARGS_ASSERT_DIE_SV;
1518 =for apidoc Am|OP *|die|const char *pat|...
1520 Behaves the same as L</croak>, except for the return type.
1521 It should be used only where the C<OP *> return type is required.
1522 The function never actually returns.
1527 #if defined(PERL_IMPLICIT_CONTEXT)
1529 Perl_die_nocontext(const char* pat, ...)
1533 va_start(args, pat);
1539 #endif /* PERL_IMPLICIT_CONTEXT */
1542 Perl_die(pTHX_ const char* pat, ...)
1545 va_start(args, pat);
1553 =for apidoc Am|void|croak_sv|SV *baseex
1555 This is an XS interface to Perl's C<die> function.
1557 C<baseex> is the error message or object. If it is a reference, it
1558 will be used as-is. Otherwise it is used as a string, and if it does
1559 not end with a newline then it will be extended with some indication of
1560 the current location in the code, as described for L</mess_sv>.
1562 The error message or object will be used as an exception, by default
1563 returning control to the nearest enclosing C<eval>, but subject to
1564 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1565 function never returns normally.
1567 To die with a simple string message, the L</croak> function may be
1574 Perl_croak_sv(pTHX_ SV *baseex)
1576 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1577 PERL_ARGS_ASSERT_CROAK_SV;
1578 invoke_exception_hook(ex, FALSE);
1583 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1585 This is an XS interface to Perl's C<die> function.
1587 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1588 argument list. These are used to generate a string message. If the
1589 message does not end with a newline, then it will be extended with
1590 some indication of the current location in the code, as described for
1593 The error message will be used as an exception, by default
1594 returning control to the nearest enclosing C<eval>, but subject to
1595 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1596 function never returns normally.
1598 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1599 (C<$@>) will be used as an error message or object instead of building an
1600 error message from arguments. If you want to throw a non-string object,
1601 or build an error message in an SV yourself, it is preferable to use
1602 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1608 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1610 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1611 invoke_exception_hook(ex, FALSE);
1616 =for apidoc Am|void|croak|const char *pat|...
1618 This is an XS interface to Perl's C<die> function.
1620 Take a sprintf-style format pattern and argument list. These are used to
1621 generate a string message. If the message does not end with a newline,
1622 then it will be extended with some indication of the current location
1623 in the code, as described for L</mess_sv>.
1625 The error message will be used as an exception, by default
1626 returning control to the nearest enclosing C<eval>, but subject to
1627 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1628 function never returns normally.
1630 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1631 (C<$@>) will be used as an error message or object instead of building an
1632 error message from arguments. If you want to throw a non-string object,
1633 or build an error message in an SV yourself, it is preferable to use
1634 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1639 #if defined(PERL_IMPLICIT_CONTEXT)
1641 Perl_croak_nocontext(const char *pat, ...)
1645 va_start(args, pat);
1650 #endif /* PERL_IMPLICIT_CONTEXT */
1653 Perl_croak(pTHX_ const char *pat, ...)
1656 va_start(args, pat);
1663 =for apidoc Am|void|croak_no_modify
1665 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1666 terser object code than using C<Perl_croak>. Less code used on exception code
1667 paths reduces CPU cache pressure.
1673 Perl_croak_no_modify(pTHX)
1675 Perl_croak(aTHX_ "%s", PL_no_modify);
1679 =for apidoc Am|void|warn_sv|SV *baseex
1681 This is an XS interface to Perl's C<warn> function.
1683 C<baseex> is the error message or object. If it is a reference, it
1684 will be used as-is. Otherwise it is used as a string, and if it does
1685 not end with a newline then it will be extended with some indication of
1686 the current location in the code, as described for L</mess_sv>.
1688 The error message or object will by default be written to standard error,
1689 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1691 To warn with a simple string message, the L</warn> function may be
1698 Perl_warn_sv(pTHX_ SV *baseex)
1700 SV *ex = mess_sv(baseex, 0);
1701 PERL_ARGS_ASSERT_WARN_SV;
1702 if (!invoke_exception_hook(ex, TRUE))
1703 write_to_stderr(ex);
1707 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1709 This is an XS interface to Perl's C<warn> function.
1711 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1712 argument list. These are used to generate a string message. If the
1713 message does not end with a newline, then it will be extended with
1714 some indication of the current location in the code, as described for
1717 The error message or object will by default be written to standard error,
1718 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1720 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1726 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1728 SV *ex = vmess(pat, args);
1729 PERL_ARGS_ASSERT_VWARN;
1730 if (!invoke_exception_hook(ex, TRUE))
1731 write_to_stderr(ex);
1735 =for apidoc Am|void|warn|const char *pat|...
1737 This is an XS interface to Perl's C<warn> function.
1739 Take a sprintf-style format pattern and argument list. These are used to
1740 generate a string message. If the message does not end with a newline,
1741 then it will be extended with some indication of the current location
1742 in the code, as described for L</mess_sv>.
1744 The error message or object will by default be written to standard error,
1745 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1747 Unlike with L</croak>, C<pat> is not permitted to be null.
1752 #if defined(PERL_IMPLICIT_CONTEXT)
1754 Perl_warn_nocontext(const char *pat, ...)
1758 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1759 va_start(args, pat);
1763 #endif /* PERL_IMPLICIT_CONTEXT */
1766 Perl_warn(pTHX_ const char *pat, ...)
1769 PERL_ARGS_ASSERT_WARN;
1770 va_start(args, pat);
1775 #if defined(PERL_IMPLICIT_CONTEXT)
1777 Perl_warner_nocontext(U32 err, const char *pat, ...)
1781 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1782 va_start(args, pat);
1783 vwarner(err, pat, &args);
1786 #endif /* PERL_IMPLICIT_CONTEXT */
1789 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1791 PERL_ARGS_ASSERT_CK_WARNER_D;
1793 if (Perl_ckwarn_d(aTHX_ err)) {
1795 va_start(args, pat);
1796 vwarner(err, pat, &args);
1802 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1804 PERL_ARGS_ASSERT_CK_WARNER;
1806 if (Perl_ckwarn(aTHX_ err)) {
1808 va_start(args, pat);
1809 vwarner(err, pat, &args);
1815 Perl_warner(pTHX_ U32 err, const char* pat,...)
1818 PERL_ARGS_ASSERT_WARNER;
1819 va_start(args, pat);
1820 vwarner(err, pat, &args);
1825 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1828 PERL_ARGS_ASSERT_VWARNER;
1829 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1830 SV * const msv = vmess(pat, args);
1832 invoke_exception_hook(msv, FALSE);
1836 Perl_vwarn(aTHX_ pat, args);
1840 /* implements the ckWARN? macros */
1843 Perl_ckwarn(pTHX_ U32 w)
1846 /* If lexical warnings have not been set, use $^W. */
1848 return PL_dowarn & G_WARN_ON;
1850 return ckwarn_common(w);
1853 /* implements the ckWARN?_d macro */
1856 Perl_ckwarn_d(pTHX_ U32 w)
1859 /* If lexical warnings have not been set then default classes warn. */
1863 return ckwarn_common(w);
1867 S_ckwarn_common(pTHX_ U32 w)
1869 if (PL_curcop->cop_warnings == pWARN_ALL)
1872 if (PL_curcop->cop_warnings == pWARN_NONE)
1875 /* Check the assumption that at least the first slot is non-zero. */
1876 assert(unpackWARN1(w));
1878 /* Check the assumption that it is valid to stop as soon as a zero slot is
1880 if (!unpackWARN2(w)) {
1881 assert(!unpackWARN3(w));
1882 assert(!unpackWARN4(w));
1883 } else if (!unpackWARN3(w)) {
1884 assert(!unpackWARN4(w));
1887 /* Right, dealt with all the special cases, which are implemented as non-
1888 pointers, so there is a pointer to a real warnings mask. */
1890 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1892 } while (w >>= WARNshift);
1897 /* Set buffer=NULL to get a new one. */
1899 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1901 const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
1902 PERL_UNUSED_CONTEXT;
1903 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1906 (specialWARN(buffer) ?
1907 PerlMemShared_malloc(len_wanted) :
1908 PerlMemShared_realloc(buffer, len_wanted));
1910 Copy(bits, (buffer + 1), size, char);
1914 /* since we've already done strlen() for both nam and val
1915 * we can use that info to make things faster than
1916 * sprintf(s, "%s=%s", nam, val)
1918 #define my_setenv_format(s, nam, nlen, val, vlen) \
1919 Copy(nam, s, nlen, char); \
1921 Copy(val, s+(nlen+1), vlen, char); \
1922 *(s+(nlen+1+vlen)) = '\0'
1924 #ifdef USE_ENVIRON_ARRAY
1925 /* VMS' my_setenv() is in vms.c */
1926 #if !defined(WIN32) && !defined(NETWARE)
1928 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1932 /* only parent thread can modify process environment */
1933 if (PL_curinterp == aTHX)
1936 #ifndef PERL_USE_SAFE_PUTENV
1937 if (!PL_use_safe_putenv) {
1938 /* most putenv()s leak, so we manipulate environ directly */
1940 register const I32 len = strlen(nam);
1943 /* where does it go? */
1944 for (i = 0; environ[i]; i++) {
1945 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1949 if (environ == PL_origenviron) { /* need we copy environment? */
1955 while (environ[max])
1957 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1958 for (j=0; j<max; j++) { /* copy environment */
1959 const int len = strlen(environ[j]);
1960 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1961 Copy(environ[j], tmpenv[j], len+1, char);
1964 environ = tmpenv; /* tell exec where it is now */
1967 safesysfree(environ[i]);
1968 while (environ[i]) {
1969 environ[i] = environ[i+1];
1974 if (!environ[i]) { /* does not exist yet */
1975 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1976 environ[i+1] = NULL; /* make sure it's null terminated */
1979 safesysfree(environ[i]);
1983 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1984 /* all that work just for this */
1985 my_setenv_format(environ[i], nam, nlen, val, vlen);
1988 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
1989 # if defined(HAS_UNSETENV)
1991 (void)unsetenv(nam);
1993 (void)setenv(nam, val, 1);
1995 # else /* ! HAS_UNSETENV */
1996 (void)setenv(nam, val, 1);
1997 # endif /* HAS_UNSETENV */
1999 # if defined(HAS_UNSETENV)
2001 (void)unsetenv(nam);
2003 const int nlen = strlen(nam);
2004 const int vlen = strlen(val);
2005 char * const new_env =
2006 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2007 my_setenv_format(new_env, nam, nlen, val, vlen);
2008 (void)putenv(new_env);
2010 # else /* ! HAS_UNSETENV */
2012 const int nlen = strlen(nam);
2018 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2019 /* all that work just for this */
2020 my_setenv_format(new_env, nam, nlen, val, vlen);
2021 (void)putenv(new_env);
2022 # endif /* HAS_UNSETENV */
2023 # endif /* __CYGWIN__ */
2024 #ifndef PERL_USE_SAFE_PUTENV
2030 #else /* WIN32 || NETWARE */
2033 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2036 register char *envstr;
2037 const int nlen = strlen(nam);
2044 Newx(envstr, nlen+vlen+2, char);
2045 my_setenv_format(envstr, nam, nlen, val, vlen);
2046 (void)PerlEnv_putenv(envstr);
2050 #endif /* WIN32 || NETWARE */
2052 #endif /* !VMS && !EPOC*/
2054 #ifdef UNLINK_ALL_VERSIONS
2056 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2060 PERL_ARGS_ASSERT_UNLNK;
2062 while (PerlLIO_unlink(f) >= 0)
2064 return retries ? 0 : -1;
2068 /* this is a drop-in replacement for bcopy() */
2069 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2071 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2073 char * const retval = to;
2075 PERL_ARGS_ASSERT_MY_BCOPY;
2077 if (from - to >= 0) {
2085 *(--to) = *(--from);
2091 /* this is a drop-in replacement for memset() */
2094 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2096 char * const retval = loc;
2098 PERL_ARGS_ASSERT_MY_MEMSET;
2106 /* this is a drop-in replacement for bzero() */
2107 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2109 Perl_my_bzero(register char *loc, register I32 len)
2111 char * const retval = loc;
2113 PERL_ARGS_ASSERT_MY_BZERO;
2121 /* this is a drop-in replacement for memcmp() */
2122 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2124 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2126 register const U8 *a = (const U8 *)s1;
2127 register const U8 *b = (const U8 *)s2;
2130 PERL_ARGS_ASSERT_MY_MEMCMP;
2133 if ((tmp = *a++ - *b++))
2138 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2141 /* This vsprintf replacement should generally never get used, since
2142 vsprintf was available in both System V and BSD 2.11. (There may
2143 be some cross-compilation or embedded set-ups where it is needed,
2146 If you encounter a problem in this function, it's probably a symptom
2147 that Configure failed to detect your system's vprintf() function.
2148 See the section on "item vsprintf" in the INSTALL file.
2150 This version may compile on systems with BSD-ish <stdio.h>,
2151 but probably won't on others.
2154 #ifdef USE_CHAR_VSPRINTF
2159 vsprintf(char *dest, const char *pat, void *args)
2163 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2164 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2165 FILE_cnt(&fakebuf) = 32767;
2167 /* These probably won't compile -- If you really need
2168 this, you'll have to figure out some other method. */
2169 fakebuf._ptr = dest;
2170 fakebuf._cnt = 32767;
2175 fakebuf._flag = _IOWRT|_IOSTRG;
2176 _doprnt(pat, args, &fakebuf); /* what a kludge */
2177 #if defined(STDIO_PTR_LVALUE)
2178 *(FILE_ptr(&fakebuf)++) = '\0';
2180 /* PerlIO has probably #defined away fputc, but we want it here. */
2182 # undef fputc /* XXX Should really restore it later */
2184 (void)fputc('\0', &fakebuf);
2186 #ifdef USE_CHAR_VSPRINTF
2189 return 0; /* perl doesn't use return value */
2193 #endif /* HAS_VPRINTF */
2196 #if BYTEORDER != 0x4321
2198 Perl_my_swap(pTHX_ short s)
2200 #if (BYTEORDER & 1) == 0
2203 result = ((s & 255) << 8) + ((s >> 8) & 255);
2211 Perl_my_htonl(pTHX_ long l)
2215 char c[sizeof(long)];
2218 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2219 #if BYTEORDER == 0x12345678
2222 u.c[0] = (l >> 24) & 255;
2223 u.c[1] = (l >> 16) & 255;
2224 u.c[2] = (l >> 8) & 255;
2228 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2229 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2234 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2235 u.c[o & 0xf] = (l >> s) & 255;
2243 Perl_my_ntohl(pTHX_ long l)
2247 char c[sizeof(long)];
2250 #if BYTEORDER == 0x1234
2251 u.c[0] = (l >> 24) & 255;
2252 u.c[1] = (l >> 16) & 255;
2253 u.c[2] = (l >> 8) & 255;
2257 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2258 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2265 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2266 l |= (u.c[o & 0xf] & 255) << s;
2273 #endif /* BYTEORDER != 0x4321 */
2277 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2278 * If these functions are defined,
2279 * the BYTEORDER is neither 0x1234 nor 0x4321.
2280 * However, this is not assumed.
2284 #define HTOLE(name,type) \
2286 name (register type n) \
2290 char c[sizeof(type)]; \
2293 register U32 s = 0; \
2294 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2295 u.c[i] = (n >> s) & 0xFF; \
2300 #define LETOH(name,type) \
2302 name (register type n) \
2306 char c[sizeof(type)]; \
2309 register U32 s = 0; \
2312 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2313 n |= ((type)(u.c[i] & 0xFF)) << s; \
2319 * Big-endian byte order functions.
2322 #define HTOBE(name,type) \
2324 name (register type n) \
2328 char c[sizeof(type)]; \
2331 register U32 s = 8*(sizeof(u.c)-1); \
2332 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2333 u.c[i] = (n >> s) & 0xFF; \
2338 #define BETOH(name,type) \
2340 name (register type n) \
2344 char c[sizeof(type)]; \
2347 register U32 s = 8*(sizeof(u.c)-1); \
2350 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2351 n |= ((type)(u.c[i] & 0xFF)) << s; \
2357 * If we just can't do it...
2360 #define NOT_AVAIL(name,type) \
2362 name (register type n) \
2364 Perl_croak_nocontext(#name "() not available"); \
2365 return n; /* not reached */ \
2369 #if defined(HAS_HTOVS) && !defined(htovs)
2372 #if defined(HAS_HTOVL) && !defined(htovl)
2375 #if defined(HAS_VTOHS) && !defined(vtohs)
2378 #if defined(HAS_VTOHL) && !defined(vtohl)
2382 #ifdef PERL_NEED_MY_HTOLE16
2384 HTOLE(Perl_my_htole16,U16)
2386 NOT_AVAIL(Perl_my_htole16,U16)
2389 #ifdef PERL_NEED_MY_LETOH16
2391 LETOH(Perl_my_letoh16,U16)
2393 NOT_AVAIL(Perl_my_letoh16,U16)
2396 #ifdef PERL_NEED_MY_HTOBE16
2398 HTOBE(Perl_my_htobe16,U16)
2400 NOT_AVAIL(Perl_my_htobe16,U16)
2403 #ifdef PERL_NEED_MY_BETOH16
2405 BETOH(Perl_my_betoh16,U16)
2407 NOT_AVAIL(Perl_my_betoh16,U16)
2411 #ifdef PERL_NEED_MY_HTOLE32
2413 HTOLE(Perl_my_htole32,U32)
2415 NOT_AVAIL(Perl_my_htole32,U32)
2418 #ifdef PERL_NEED_MY_LETOH32
2420 LETOH(Perl_my_letoh32,U32)
2422 NOT_AVAIL(Perl_my_letoh32,U32)
2425 #ifdef PERL_NEED_MY_HTOBE32
2427 HTOBE(Perl_my_htobe32,U32)
2429 NOT_AVAIL(Perl_my_htobe32,U32)
2432 #ifdef PERL_NEED_MY_BETOH32
2434 BETOH(Perl_my_betoh32,U32)
2436 NOT_AVAIL(Perl_my_betoh32,U32)
2440 #ifdef PERL_NEED_MY_HTOLE64
2442 HTOLE(Perl_my_htole64,U64)
2444 NOT_AVAIL(Perl_my_htole64,U64)
2447 #ifdef PERL_NEED_MY_LETOH64
2449 LETOH(Perl_my_letoh64,U64)
2451 NOT_AVAIL(Perl_my_letoh64,U64)
2454 #ifdef PERL_NEED_MY_HTOBE64
2456 HTOBE(Perl_my_htobe64,U64)
2458 NOT_AVAIL(Perl_my_htobe64,U64)
2461 #ifdef PERL_NEED_MY_BETOH64
2463 BETOH(Perl_my_betoh64,U64)
2465 NOT_AVAIL(Perl_my_betoh64,U64)
2469 #ifdef PERL_NEED_MY_HTOLES
2470 HTOLE(Perl_my_htoles,short)
2472 #ifdef PERL_NEED_MY_LETOHS
2473 LETOH(Perl_my_letohs,short)
2475 #ifdef PERL_NEED_MY_HTOBES
2476 HTOBE(Perl_my_htobes,short)
2478 #ifdef PERL_NEED_MY_BETOHS
2479 BETOH(Perl_my_betohs,short)
2482 #ifdef PERL_NEED_MY_HTOLEI
2483 HTOLE(Perl_my_htolei,int)
2485 #ifdef PERL_NEED_MY_LETOHI
2486 LETOH(Perl_my_letohi,int)
2488 #ifdef PERL_NEED_MY_HTOBEI
2489 HTOBE(Perl_my_htobei,int)
2491 #ifdef PERL_NEED_MY_BETOHI
2492 BETOH(Perl_my_betohi,int)
2495 #ifdef PERL_NEED_MY_HTOLEL
2496 HTOLE(Perl_my_htolel,long)
2498 #ifdef PERL_NEED_MY_LETOHL
2499 LETOH(Perl_my_letohl,long)
2501 #ifdef PERL_NEED_MY_HTOBEL
2502 HTOBE(Perl_my_htobel,long)
2504 #ifdef PERL_NEED_MY_BETOHL
2505 BETOH(Perl_my_betohl,long)
2509 Perl_my_swabn(void *ptr, int n)
2511 register char *s = (char *)ptr;
2512 register char *e = s + (n-1);
2515 PERL_ARGS_ASSERT_MY_SWABN;
2517 for (n /= 2; n > 0; s++, e--, n--) {
2525 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2527 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2530 register I32 This, that;
2536 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2538 PERL_FLUSHALL_FOR_CHILD;
2539 This = (*mode == 'w');
2543 taint_proper("Insecure %s%s", "EXEC");
2545 if (PerlProc_pipe(p) < 0)
2547 /* Try for another pipe pair for error return */
2548 if (PerlProc_pipe(pp) >= 0)
2550 while ((pid = PerlProc_fork()) < 0) {
2551 if (errno != EAGAIN) {
2552 PerlLIO_close(p[This]);
2553 PerlLIO_close(p[that]);
2555 PerlLIO_close(pp[0]);
2556 PerlLIO_close(pp[1]);
2560 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2569 /* Close parent's end of error status pipe (if any) */
2571 PerlLIO_close(pp[0]);
2572 #if defined(HAS_FCNTL) && defined(F_SETFD)
2573 /* Close error pipe automatically if exec works */
2574 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2577 /* Now dup our end of _the_ pipe to right position */
2578 if (p[THIS] != (*mode == 'r')) {
2579 PerlLIO_dup2(p[THIS], *mode == 'r');
2580 PerlLIO_close(p[THIS]);
2581 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2582 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2585 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2586 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2587 /* No automatic close - do it by hand */
2594 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2600 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2606 do_execfree(); /* free any memory malloced by child on fork */
2608 PerlLIO_close(pp[1]);
2609 /* Keep the lower of the two fd numbers */
2610 if (p[that] < p[This]) {
2611 PerlLIO_dup2(p[This], p[that]);
2612 PerlLIO_close(p[This]);
2616 PerlLIO_close(p[that]); /* close child's end of pipe */
2618 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2619 SvUPGRADE(sv,SVt_IV);
2621 PL_forkprocess = pid;
2622 /* If we managed to get status pipe check for exec fail */
2623 if (did_pipes && pid > 0) {
2628 while (n < sizeof(int)) {
2629 n1 = PerlLIO_read(pp[0],
2630 (void*)(((char*)&errkid)+n),
2636 PerlLIO_close(pp[0]);
2638 if (n) { /* Error */
2640 PerlLIO_close(p[This]);
2641 if (n != sizeof(int))
2642 Perl_croak(aTHX_ "panic: kid popen errno read");
2644 pid2 = wait4pid(pid, &status, 0);
2645 } while (pid2 == -1 && errno == EINTR);
2646 errno = errkid; /* Propagate errno from kid */
2651 PerlLIO_close(pp[0]);
2652 return PerlIO_fdopen(p[This], mode);
2654 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2655 return my_syspopen4(aTHX_ NULL, mode, n, args);
2657 Perl_croak(aTHX_ "List form of piped open not implemented");
2658 return (PerlIO *) NULL;
2663 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2664 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
2666 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2670 register I32 This, that;
2673 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2677 PERL_ARGS_ASSERT_MY_POPEN;
2679 PERL_FLUSHALL_FOR_CHILD;
2682 return my_syspopen(aTHX_ cmd,mode);
2685 This = (*mode == 'w');
2687 if (doexec && PL_tainting) {
2689 taint_proper("Insecure %s%s", "EXEC");
2691 if (PerlProc_pipe(p) < 0)
2693 if (doexec && PerlProc_pipe(pp) >= 0)
2695 while ((pid = PerlProc_fork()) < 0) {
2696 if (errno != EAGAIN) {
2697 PerlLIO_close(p[This]);
2698 PerlLIO_close(p[that]);
2700 PerlLIO_close(pp[0]);
2701 PerlLIO_close(pp[1]);
2704 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2707 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2718 PerlLIO_close(pp[0]);
2719 #if defined(HAS_FCNTL) && defined(F_SETFD)
2720 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2723 if (p[THIS] != (*mode == 'r')) {
2724 PerlLIO_dup2(p[THIS], *mode == 'r');
2725 PerlLIO_close(p[THIS]);
2726 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2727 PerlLIO_close(p[THAT]);
2730 PerlLIO_close(p[THAT]);
2733 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2740 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2745 /* may or may not use the shell */
2746 do_exec3(cmd, pp[1], did_pipes);
2749 #endif /* defined OS2 */
2751 #ifdef PERLIO_USING_CRLF
2752 /* Since we circumvent IO layers when we manipulate low-level
2753 filedescriptors directly, need to manually switch to the
2754 default, binary, low-level mode; see PerlIOBuf_open(). */
2755 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2758 if ((tmpgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV))) {
2759 SvREADONLY_off(GvSV(tmpgv));
2760 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2761 SvREADONLY_on(GvSV(tmpgv));
2763 #ifdef THREADS_HAVE_PIDS
2764 PL_ppid = (IV)getppid();
2767 #ifdef PERL_USES_PL_PIDSTATUS
2768 hv_clear(PL_pidstatus); /* we have no children */
2774 do_execfree(); /* free any memory malloced by child on vfork */
2776 PerlLIO_close(pp[1]);
2777 if (p[that] < p[This]) {
2778 PerlLIO_dup2(p[This], p[that]);
2779 PerlLIO_close(p[This]);
2783 PerlLIO_close(p[that]);
2785 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2786 SvUPGRADE(sv,SVt_IV);
2788 PL_forkprocess = pid;
2789 if (did_pipes && pid > 0) {
2794 while (n < sizeof(int)) {
2795 n1 = PerlLIO_read(pp[0],
2796 (void*)(((char*)&errkid)+n),
2802 PerlLIO_close(pp[0]);
2804 if (n) { /* Error */
2806 PerlLIO_close(p[This]);
2807 if (n != sizeof(int))
2808 Perl_croak(aTHX_ "panic: kid popen errno read");
2810 pid2 = wait4pid(pid, &status, 0);
2811 } while (pid2 == -1 && errno == EINTR);
2812 errno = errkid; /* Propagate errno from kid */
2817 PerlLIO_close(pp[0]);
2818 return PerlIO_fdopen(p[This], mode);
2821 #if defined(atarist) || defined(EPOC)
2824 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2826 PERL_ARGS_ASSERT_MY_POPEN;
2827 PERL_FLUSHALL_FOR_CHILD;
2828 /* Call system's popen() to get a FILE *, then import it.
2829 used 0 for 2nd parameter to PerlIO_importFILE;
2832 return PerlIO_importFILE(popen(cmd, mode), 0);
2836 FILE *djgpp_popen();
2838 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2840 PERL_FLUSHALL_FOR_CHILD;
2841 /* Call system's popen() to get a FILE *, then import it.
2842 used 0 for 2nd parameter to PerlIO_importFILE;
2845 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2848 #if defined(__LIBCATAMOUNT__)
2850 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2858 #endif /* !DOSISH */
2860 /* this is called in parent before the fork() */
2862 Perl_atfork_lock(void)
2865 #if defined(USE_ITHREADS)
2866 /* locks must be held in locking order (if any) */
2868 MUTEX_LOCK(&PL_malloc_mutex);
2874 /* this is called in both parent and child after the fork() */
2876 Perl_atfork_unlock(void)
2879 #if defined(USE_ITHREADS)
2880 /* locks must be released in same order as in atfork_lock() */
2882 MUTEX_UNLOCK(&PL_malloc_mutex);
2891 #if defined(HAS_FORK)
2893 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2898 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2899 * handlers elsewhere in the code */
2904 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2905 Perl_croak_nocontext("fork() not available");
2907 #endif /* HAS_FORK */
2912 Perl_dump_fds(pTHX_ const char *const s)
2917 PERL_ARGS_ASSERT_DUMP_FDS;
2919 PerlIO_printf(Perl_debug_log,"%s", s);
2920 for (fd = 0; fd < 32; fd++) {
2921 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2922 PerlIO_printf(Perl_debug_log," %d",fd);
2924 PerlIO_printf(Perl_debug_log,"\n");
2927 #endif /* DUMP_FDS */
2931 dup2(int oldfd, int newfd)
2933 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2936 PerlLIO_close(newfd);
2937 return fcntl(oldfd, F_DUPFD, newfd);
2939 #define DUP2_MAX_FDS 256
2940 int fdtmp[DUP2_MAX_FDS];
2946 PerlLIO_close(newfd);
2947 /* good enough for low fd's... */
2948 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2949 if (fdx >= DUP2_MAX_FDS) {
2957 PerlLIO_close(fdtmp[--fdx]);
2964 #ifdef HAS_SIGACTION
2967 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2970 struct sigaction act, oact;
2973 /* only "parent" interpreter can diddle signals */
2974 if (PL_curinterp != aTHX)
2975 return (Sighandler_t) SIG_ERR;
2978 act.sa_handler = (void(*)(int))handler;
2979 sigemptyset(&act.sa_mask);
2982 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2983 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2985 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2986 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2987 act.sa_flags |= SA_NOCLDWAIT;
2989 if (sigaction(signo, &act, &oact) == -1)
2990 return (Sighandler_t) SIG_ERR;
2992 return (Sighandler_t) oact.sa_handler;
2996 Perl_rsignal_state(pTHX_ int signo)
2998 struct sigaction oact;
2999 PERL_UNUSED_CONTEXT;
3001 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
3002 return (Sighandler_t) SIG_ERR;
3004 return (Sighandler_t) oact.sa_handler;
3008 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3011 struct sigaction act;
3013 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
3016 /* only "parent" interpreter can diddle signals */
3017 if (PL_curinterp != aTHX)
3021 act.sa_handler = (void(*)(int))handler;
3022 sigemptyset(&act.sa_mask);
3025 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3026 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
3028 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3029 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3030 act.sa_flags |= SA_NOCLDWAIT;
3032 return sigaction(signo, &act, save);
3036 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3040 /* only "parent" interpreter can diddle signals */
3041 if (PL_curinterp != aTHX)
3045 return sigaction(signo, save, (struct sigaction *)NULL);
3048 #else /* !HAS_SIGACTION */
3051 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3053 #if defined(USE_ITHREADS) && !defined(WIN32)
3054 /* only "parent" interpreter can diddle signals */
3055 if (PL_curinterp != aTHX)
3056 return (Sighandler_t) SIG_ERR;
3059 return PerlProc_signal(signo, handler);
3070 Perl_rsignal_state(pTHX_ int signo)
3073 Sighandler_t oldsig;
3075 #if defined(USE_ITHREADS) && !defined(WIN32)
3076 /* only "parent" interpreter can diddle signals */
3077 if (PL_curinterp != aTHX)
3078 return (Sighandler_t) SIG_ERR;
3082 oldsig = PerlProc_signal(signo, sig_trap);
3083 PerlProc_signal(signo, oldsig);
3085 PerlProc_kill(PerlProc_getpid(), signo);
3090 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3092 #if defined(USE_ITHREADS) && !defined(WIN32)
3093 /* only "parent" interpreter can diddle signals */
3094 if (PL_curinterp != aTHX)
3097 *save = PerlProc_signal(signo, handler);
3098 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3102 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3104 #if defined(USE_ITHREADS) && !defined(WIN32)
3105 /* only "parent" interpreter can diddle signals */
3106 if (PL_curinterp != aTHX)
3109 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3112 #endif /* !HAS_SIGACTION */
3113 #endif /* !PERL_MICRO */
3115 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3116 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
3118 Perl_my_pclose(pTHX_ PerlIO *ptr)
3121 Sigsave_t hstat, istat, qstat;
3128 const int fd = PerlIO_fileno(ptr);
3131 /* Find out whether the refcount is low enough for us to wait for the
3132 child proc without blocking. */
3133 const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
3135 const bool should_wait = 1;
3138 svp = av_fetch(PL_fdpid,fd,TRUE);
3139 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3141 *svp = &PL_sv_undef;
3143 if (pid == -1) { /* Opened by popen. */
3144 return my_syspclose(ptr);
3147 close_failed = (PerlIO_close(ptr) == EOF);
3150 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
3153 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3154 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3155 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3157 if (should_wait) do {
3158 pid2 = wait4pid(pid, &status, 0);
3159 } while (pid2 == -1 && errno == EINTR);
3161 rsignal_restore(SIGHUP, &hstat);
3162 rsignal_restore(SIGINT, &istat);
3163 rsignal_restore(SIGQUIT, &qstat);
3171 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3176 #if defined(__LIBCATAMOUNT__)
3178 Perl_my_pclose(pTHX_ PerlIO *ptr)
3183 #endif /* !DOSISH */
3185 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3187 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3191 PERL_ARGS_ASSERT_WAIT4PID;
3194 #ifdef PERL_USES_PL_PIDSTATUS
3197 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3198 pid, rather than a string form. */
3199 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3200 if (svp && *svp != &PL_sv_undef) {
3201 *statusp = SvIVX(*svp);
3202 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3210 hv_iterinit(PL_pidstatus);
3211 if ((entry = hv_iternext(PL_pidstatus))) {
3212 SV * const sv = hv_iterval(PL_pidstatus,entry);
3214 const char * const spid = hv_iterkey(entry,&len);
3216 assert (len == sizeof(Pid_t));
3217 memcpy((char *)&pid, spid, len);
3218 *statusp = SvIVX(sv);
3219 /* The hash iterator is currently on this entry, so simply
3220 calling hv_delete would trigger the lazy delete, which on
3221 aggregate does more work, beacuse next call to hv_iterinit()
3222 would spot the flag, and have to call the delete routine,
3223 while in the meantime any new entries can't re-use that
3225 hv_iterinit(PL_pidstatus);
3226 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3233 # ifdef HAS_WAITPID_RUNTIME
3234 if (!HAS_WAITPID_RUNTIME)
3237 result = PerlProc_waitpid(pid,statusp,flags);
3240 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3241 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3244 #ifdef PERL_USES_PL_PIDSTATUS
3245 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3250 Perl_croak(aTHX_ "Can't do waitpid with flags");
3252 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3253 pidgone(result,*statusp);
3259 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3262 if (result < 0 && errno == EINTR) {
3264 errno = EINTR; /* reset in case a signal handler changed $! */
3268 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3270 #ifdef PERL_USES_PL_PIDSTATUS
3272 S_pidgone(pTHX_ Pid_t pid, int status)
3276 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3277 SvUPGRADE(sv,SVt_IV);
3278 SvIV_set(sv, status);
3283 #if defined(atarist) || defined(OS2) || defined(EPOC)
3286 int /* Cannot prototype with I32
3288 my_syspclose(PerlIO *ptr)
3291 Perl_my_pclose(pTHX_ PerlIO *ptr)
3294 /* Needs work for PerlIO ! */
3295 FILE * const f = PerlIO_findFILE(ptr);
3296 const I32 result = pclose(f);
3297 PerlIO_releaseFILE(ptr,f);
3305 Perl_my_pclose(pTHX_ PerlIO *ptr)
3307 /* Needs work for PerlIO ! */
3308 FILE * const f = PerlIO_findFILE(ptr);
3309 I32 result = djgpp_pclose(f);
3310 result = (result << 8) & 0xff00;
3311 PerlIO_releaseFILE(ptr,f);
3316 #define PERL_REPEATCPY_LINEAR 4
3318 Perl_repeatcpy(register char *to, register const char *from, I32 len, register I32 count)
3320 PERL_ARGS_ASSERT_REPEATCPY;
3323 memset(to, *from, count);
3325 register char *p = to;
3326 I32 items, linear, half;
3328 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3329 for (items = 0; items < linear; ++items) {
3330 register const char *q = from;
3332 for (todo = len; todo > 0; todo--)
3337 while (items <= half) {
3338 I32 size = items * len;
3339 memcpy(p, to, size);
3345 memcpy(p, to, (count - items) * len);
3351 Perl_same_dirent(pTHX_ const char *a, const char *b)
3353 char *fa = strrchr(a,'/');
3354 char *fb = strrchr(b,'/');
3357 SV * const tmpsv = sv_newmortal();
3359 PERL_ARGS_ASSERT_SAME_DIRENT;
3372 sv_setpvs(tmpsv, ".");
3374 sv_setpvn(tmpsv, a, fa - a);
3375 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3378 sv_setpvs(tmpsv, ".");
3380 sv_setpvn(tmpsv, b, fb - b);
3381 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3383 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3384 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3386 #endif /* !HAS_RENAME */
3389 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3390 const char *const *const search_ext, I32 flags)
3393 const char *xfound = NULL;
3394 char *xfailed = NULL;
3395 char tmpbuf[MAXPATHLEN];
3400 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3401 # define SEARCH_EXTS ".bat", ".cmd", NULL
3402 # define MAX_EXT_LEN 4
3405 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3406 # define MAX_EXT_LEN 4
3409 # define SEARCH_EXTS ".pl", ".com", NULL
3410 # define MAX_EXT_LEN 4
3412 /* additional extensions to try in each dir if scriptname not found */
3414 static const char *const exts[] = { SEARCH_EXTS };
3415 const char *const *const ext = search_ext ? search_ext : exts;
3416 int extidx = 0, i = 0;
3417 const char *curext = NULL;
3419 PERL_UNUSED_ARG(search_ext);
3420 # define MAX_EXT_LEN 0
3423 PERL_ARGS_ASSERT_FIND_SCRIPT;
3426 * If dosearch is true and if scriptname does not contain path
3427 * delimiters, search the PATH for scriptname.
3429 * If SEARCH_EXTS is also defined, will look for each
3430 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3431 * while searching the PATH.
3433 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3434 * proceeds as follows:
3435 * If DOSISH or VMSISH:
3436 * + look for ./scriptname{,.foo,.bar}
3437 * + search the PATH for scriptname{,.foo,.bar}
3440 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3441 * this will not look in '.' if it's not in the PATH)
3446 # ifdef ALWAYS_DEFTYPES
3447 len = strlen(scriptname);
3448 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3449 int idx = 0, deftypes = 1;
3452 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3455 int idx = 0, deftypes = 1;
3458 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3460 /* The first time through, just add SEARCH_EXTS to whatever we
3461 * already have, so we can check for default file types. */
3463 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3469 if ((strlen(tmpbuf) + strlen(scriptname)
3470 + MAX_EXT_LEN) >= sizeof tmpbuf)
3471 continue; /* don't search dir with too-long name */
3472 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3476 if (strEQ(scriptname, "-"))
3478 if (dosearch) { /* Look in '.' first. */
3479 const char *cur = scriptname;
3481 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3483 if (strEQ(ext[i++],curext)) {
3484 extidx = -1; /* already has an ext */
3489 DEBUG_p(PerlIO_printf(Perl_debug_log,
3490 "Looking for %s\n",cur));
3491 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3492 && !S_ISDIR(PL_statbuf.st_mode)) {
3500 if (cur == scriptname) {
3501 len = strlen(scriptname);
3502 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3504 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3507 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3508 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3513 if (dosearch && !strchr(scriptname, '/')
3515 && !strchr(scriptname, '\\')
3517 && (s = PerlEnv_getenv("PATH")))
3521 bufend = s + strlen(s);
3522 while (s < bufend) {
3523 #if defined(atarist) || defined(DOSISH)
3528 && *s != ';'; len++, s++) {
3529 if (len < sizeof tmpbuf)
3532 if (len < sizeof tmpbuf)
3534 #else /* ! (atarist || DOSISH) */
3535 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3538 #endif /* ! (atarist || DOSISH) */
3541 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3542 continue; /* don't search dir with too-long name */
3544 # if defined(atarist) || defined(DOSISH)
3545 && tmpbuf[len - 1] != '/'
3546 && tmpbuf[len - 1] != '\\'
3549 tmpbuf[len++] = '/';
3550 if (len == 2 && tmpbuf[0] == '.')
3552 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3556 len = strlen(tmpbuf);
3557 if (extidx > 0) /* reset after previous loop */
3561 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3562 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3563 if (S_ISDIR(PL_statbuf.st_mode)) {
3567 } while ( retval < 0 /* not there */
3568 && extidx>=0 && ext[extidx] /* try an extension? */
3569 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3574 if (S_ISREG(PL_statbuf.st_mode)
3575 && cando(S_IRUSR,TRUE,&PL_statbuf)
3576 #if !defined(DOSISH)
3577 && cando(S_IXUSR,TRUE,&PL_statbuf)
3581 xfound = tmpbuf; /* bingo! */
3585 xfailed = savepv(tmpbuf);
3588 if (!xfound && !seen_dot && !xfailed &&
3589 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3590 || S_ISDIR(PL_statbuf.st_mode)))
3592 seen_dot = 1; /* Disable message. */
3594 if (flags & 1) { /* do or die? */
3595 Perl_croak(aTHX_ "Can't %s %s%s%s",
3596 (xfailed ? "execute" : "find"),
3597 (xfailed ? xfailed : scriptname),
3598 (xfailed ? "" : " on PATH"),
3599 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3604 scriptname = xfound;
3606 return (scriptname ? savepv(scriptname) : NULL);
3609 #ifndef PERL_GET_CONTEXT_DEFINED
3612 Perl_get_context(void)
3615 #if defined(USE_ITHREADS)
3616 # ifdef OLD_PTHREADS_API
3618 if (pthread_getspecific(PL_thr_key, &t))
3619 Perl_croak_nocontext("panic: pthread_getspecific");
3622 # ifdef I_MACH_CTHREADS
3623 return (void*)cthread_data(cthread_self());
3625 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3634 Perl_set_context(void *t)
3637 PERL_ARGS_ASSERT_SET_CONTEXT;
3638 #if defined(USE_ITHREADS)
3639 # ifdef I_MACH_CTHREADS
3640 cthread_set_data(cthread_self(), t);
3642 if (pthread_setspecific(PL_thr_key, t))
3643 Perl_croak_nocontext("panic: pthread_setspecific");
3650 #endif /* !PERL_GET_CONTEXT_DEFINED */
3652 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3661 Perl_get_op_names(pTHX)
3663 PERL_UNUSED_CONTEXT;
3664 return (char **)PL_op_name;
3668 Perl_get_op_descs(pTHX)
3670 PERL_UNUSED_CONTEXT;
3671 return (char **)PL_op_desc;
3675 Perl_get_no_modify(pTHX)
3677 PERL_UNUSED_CONTEXT;
3678 return PL_no_modify;
3682 Perl_get_opargs(pTHX)
3684 PERL_UNUSED_CONTEXT;
3685 return (U32 *)PL_opargs;
3689 Perl_get_ppaddr(pTHX)
3692 PERL_UNUSED_CONTEXT;
3693 return (PPADDR_t*)PL_ppaddr;
3696 #ifndef HAS_GETENV_LEN
3698 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3700 char * const env_trans = PerlEnv_getenv(env_elem);
3701 PERL_UNUSED_CONTEXT;
3702 PERL_ARGS_ASSERT_GETENV_LEN;
3704 *len = strlen(env_trans);
3711 Perl_get_vtbl(pTHX_ int vtbl_id)
3713 const MGVTBL* result;
3714 PERL_UNUSED_CONTEXT;
3718 result = &PL_vtbl_sv;
3721 result = &PL_vtbl_env;
3723 case want_vtbl_envelem:
3724 result = &PL_vtbl_envelem;
3727 result = &PL_vtbl_sig;
3729 case want_vtbl_sigelem:
3730 result = &PL_vtbl_sigelem;
3732 case want_vtbl_pack:
3733 result = &PL_vtbl_pack;
3735 case want_vtbl_packelem:
3736 result = &PL_vtbl_packelem;
3738 case want_vtbl_dbline:
3739 result = &PL_vtbl_dbline;
3742 result = &PL_vtbl_isa;
3744 case want_vtbl_isaelem:
3745 result = &PL_vtbl_isaelem;
3747 case want_vtbl_arylen:
3748 result = &PL_vtbl_arylen;
3750 case want_vtbl_mglob:
3751 result = &PL_vtbl_mglob;
3753 case want_vtbl_nkeys:
3754 result = &PL_vtbl_nkeys;
3756 case want_vtbl_taint:
3757 result = &PL_vtbl_taint;
3759 case want_vtbl_substr:
3760 result = &PL_vtbl_substr;
3763 result = &PL_vtbl_vec;
3766 result = &PL_vtbl_pos;
3769 result = &PL_vtbl_bm;
3772 result = &PL_vtbl_fm;
3774 case want_vtbl_uvar:
3775 result = &PL_vtbl_uvar;
3777 case want_vtbl_defelem:
3778 result = &PL_vtbl_defelem;
3780 case want_vtbl_regexp:
3781 result = &PL_vtbl_regexp;
3783 case want_vtbl_regdata:
3784 result = &PL_vtbl_regdata;
3786 case want_vtbl_regdatum:
3787 result = &PL_vtbl_regdatum;
3789 #ifdef USE_LOCALE_COLLATE
3790 case want_vtbl_collxfrm:
3791 result = &PL_vtbl_collxfrm;
3794 case want_vtbl_amagic:
3795 result = &PL_vtbl_amagic;
3797 case want_vtbl_amagicelem:
3798 result = &PL_vtbl_amagicelem;
3800 case want_vtbl_backref:
3801 result = &PL_vtbl_backref;
3803 case want_vtbl_utf8:
3804 result = &PL_vtbl_utf8;
3810 return (MGVTBL*)result;
3814 Perl_my_fflush_all(pTHX)
3816 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3817 return PerlIO_flush(NULL);
3819 # if defined(HAS__FWALK)
3820 extern int fflush(FILE *);
3821 /* undocumented, unprototyped, but very useful BSDism */
3822 extern void _fwalk(int (*)(FILE *));
3826 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3828 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3829 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3831 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3832 open_max = sysconf(_SC_OPEN_MAX);
3835 open_max = FOPEN_MAX;
3838 open_max = OPEN_MAX;
3849 for (i = 0; i < open_max; i++)
3850 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3851 STDIO_STREAM_ARRAY[i]._file < open_max &&
3852 STDIO_STREAM_ARRAY[i]._flag)
3853 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3857 SETERRNO(EBADF,RMS_IFI);
3864 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3866 if (ckWARN(WARN_IO)) {
3867 const char * const name
3868 = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3869 const char * const direction = have == '>' ? "out" : "in";
3872 Perl_warner(aTHX_ packWARN(WARN_IO),
3873 "Filehandle %s opened only for %sput",
3876 Perl_warner(aTHX_ packWARN(WARN_IO),
3877 "Filehandle opened only for %sput", direction);
3882 Perl_report_evil_fh(pTHX_ const GV *gv)
3884 const IO *io = gv ? GvIO(gv) : NULL;
3885 const PERL_BITFIELD16 op = PL_op->op_type;
3889 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3891 warn_type = WARN_CLOSED;
3895 warn_type = WARN_UNOPENED;
3898 if (ckWARN(warn_type)) {
3899 const char * const name
3900 = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3901 const char * const pars =
3902 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3903 const char * const func =
3905 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3906 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3908 const char * const type =
3910 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3911 ? "socket" : "filehandle");
3912 if (name && *name) {
3913 Perl_warner(aTHX_ packWARN(warn_type),
3914 "%s%s on %s %s %s", func, pars, vile, type, name);
3915 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3917 aTHX_ packWARN(warn_type),
3918 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3923 Perl_warner(aTHX_ packWARN(warn_type),
3924 "%s%s on %s %s", func, pars, vile, type);
3925 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3927 aTHX_ packWARN(warn_type),
3928 "\t(Are you trying to call %s%s on dirhandle?)\n",
3935 /* To workaround core dumps from the uninitialised tm_zone we get the
3936 * system to give us a reasonable struct to copy. This fix means that
3937 * strftime uses the tm_zone and tm_gmtoff values returned by
3938 * localtime(time()). That should give the desired result most of the
3939 * time. But probably not always!
3941 * This does not address tzname aspects of NETaa14816.
3946 # ifndef STRUCT_TM_HASZONE
3947 # define STRUCT_TM_HASZONE
3951 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3952 # ifndef HAS_TM_TM_ZONE
3953 # define HAS_TM_TM_ZONE
3958 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3960 #ifdef HAS_TM_TM_ZONE
3962 const struct tm* my_tm;
3963 PERL_ARGS_ASSERT_INIT_TM;
3965 my_tm = localtime(&now);
3967 Copy(my_tm, ptm, 1, struct tm);
3969 PERL_ARGS_ASSERT_INIT_TM;
3970 PERL_UNUSED_ARG(ptm);
3975 * mini_mktime - normalise struct tm values without the localtime()
3976 * semantics (and overhead) of mktime().
3979 Perl_mini_mktime(pTHX_ struct tm *ptm)
3983 int month, mday, year, jday;
3984 int odd_cent, odd_year;
3985 PERL_UNUSED_CONTEXT;
3987 PERL_ARGS_ASSERT_MINI_MKTIME;
3989 #define DAYS_PER_YEAR 365
3990 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3991 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3992 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3993 #define SECS_PER_HOUR (60*60)
3994 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3995 /* parentheses deliberately absent on these two, otherwise they don't work */
3996 #define MONTH_TO_DAYS 153/5
3997 #define DAYS_TO_MONTH 5/153
3998 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3999 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
4000 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
4001 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
4004 * Year/day algorithm notes:
4006 * With a suitable offset for numeric value of the month, one can find
4007 * an offset into the year by considering months to have 30.6 (153/5) days,
4008 * using integer arithmetic (i.e., with truncation). To avoid too much
4009 * messing about with leap days, we consider January and February to be
4010 * the 13th and 14th month of the previous year. After that transformation,
4011 * we need the month index we use to be high by 1 from 'normal human' usage,
4012 * so the month index values we use run from 4 through 15.
4014 * Given that, and the rules for the Gregorian calendar (leap years are those
4015 * divisible by 4 unless also divisible by 100, when they must be divisible
4016 * by 400 instead), we can simply calculate the number of days since some
4017 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
4018 * the days we derive from our month index, and adding in the day of the
4019 * month. The value used here is not adjusted for the actual origin which
4020 * it normally would use (1 January A.D. 1), since we're not exposing it.
4021 * We're only building the value so we can turn around and get the
4022 * normalised values for the year, month, day-of-month, and day-of-year.
4024 * For going backward, we need to bias the value we're using so that we find
4025 * the right year value. (Basically, we don't want the contribution of
4026 * March 1st to the number to apply while deriving the year). Having done
4027 * that, we 'count up' the contribution to the year number by accounting for
4028 * full quadracenturies (400-year periods) with their extra leap days, plus
4029 * the contribution from full centuries (to avoid counting in the lost leap
4030 * days), plus the contribution from full quad-years (to count in the normal
4031 * leap days), plus the leftover contribution from any non-leap years.
4032 * At this point, if we were working with an actual leap day, we'll have 0
4033 * days left over. This is also true for March 1st, however. So, we have
4034 * to special-case that result, and (earlier) keep track of the 'odd'
4035 * century and year contributions. If we got 4 extra centuries in a qcent,
4036 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
4037 * Otherwise, we add back in the earlier bias we removed (the 123 from
4038 * figuring in March 1st), find the month index (integer division by 30.6),
4039 * and the remainder is the day-of-month. We then have to convert back to
4040 * 'real' months (including fixing January and February from being 14/15 in
4041 * the previous year to being in the proper year). After that, to get
4042 * tm_yday, we work with the normalised year and get a new yearday value for
4043 * January 1st, which we subtract from the yearday value we had earlier,
4044 * representing the date we've re-built. This is done from January 1
4045 * because tm_yday is 0-origin.
4047 * Since POSIX time routines are only guaranteed to work for times since the
4048 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
4049 * applies Gregorian calendar rules even to dates before the 16th century
4050 * doesn't bother me. Besides, you'd need cultural context for a given
4051 * date to know whether it was Julian or Gregorian calendar, and that's
4052 * outside the scope for this routine. Since we convert back based on the
4053 * same rules we used to build the yearday, you'll only get strange results
4054 * for input which needed normalising, or for the 'odd' century years which
4055 * were leap years in the Julian calendar but not in the Gregorian one.
4056 * I can live with that.
4058 * This algorithm also fails to handle years before A.D. 1 gracefully, but
4059 * that's still outside the scope for POSIX time manipulation, so I don't
4063 year = 1900 + ptm->tm_year;
4064 month = ptm->tm_mon;
4065 mday = ptm->tm_mday;
4066 /* allow given yday with no month & mday to dominate the result */
4067 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
4070 jday = 1 + ptm->tm_yday;
4079 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4080 yearday += month*MONTH_TO_DAYS + mday + jday;
4082 * Note that we don't know when leap-seconds were or will be,
4083 * so we have to trust the user if we get something which looks
4084 * like a sensible leap-second. Wild values for seconds will
4085 * be rationalised, however.
4087 if ((unsigned) ptm->tm_sec <= 60) {
4094 secs += 60 * ptm->tm_min;
4095 secs += SECS_PER_HOUR * ptm->tm_hour;
4097 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4098 /* got negative remainder, but need positive time */
4099 /* back off an extra day to compensate */
4100 yearday += (secs/SECS_PER_DAY)-1;
4101 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4104 yearday += (secs/SECS_PER_DAY);
4105 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4108 else if (secs >= SECS_PER_DAY) {
4109 yearday += (secs/SECS_PER_DAY);
4110 secs %= SECS_PER_DAY;
4112 ptm->tm_hour = secs/SECS_PER_HOUR;
4113 secs %= SECS_PER_HOUR;
4114 ptm->tm_min = secs/60;
4116 ptm->tm_sec += secs;
4117 /* done with time of day effects */
4119 * The algorithm for yearday has (so far) left it high by 428.
4120 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4121 * bias it by 123 while trying to figure out what year it
4122 * really represents. Even with this tweak, the reverse
4123 * translation fails for years before A.D. 0001.
4124 * It would still fail for Feb 29, but we catch that one below.
4126 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
4127 yearday -= YEAR_ADJUST;
4128 year = (yearday / DAYS_PER_QCENT) * 400;
4129 yearday %= DAYS_PER_QCENT;
4130 odd_cent = yearday / DAYS_PER_CENT;
4131 year += odd_cent * 100;
4132 yearday %= DAYS_PER_CENT;
4133 year += (yearday / DAYS_PER_QYEAR) * 4;
4134 yearday %= DAYS_PER_QYEAR;
4135 odd_year = yearday / DAYS_PER_YEAR;
4137 yearday %= DAYS_PER_YEAR;
4138 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4143 yearday += YEAR_ADJUST; /* recover March 1st crock */
4144 month = yearday*DAYS_TO_MONTH;
4145 yearday -= month*MONTH_TO_DAYS;
4146 /* recover other leap-year adjustment */
4155 ptm->tm_year = year - 1900;
4157 ptm->tm_mday = yearday;
4158 ptm->tm_mon = month;
4162 ptm->tm_mon = month - 1;
4164 /* re-build yearday based on Jan 1 to get tm_yday */
4166 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4167 yearday += 14*MONTH_TO_DAYS + 1;
4168 ptm->tm_yday = jday - yearday;
4169 /* fix tm_wday if not overridden by caller */
4170 if ((unsigned)ptm->tm_wday > 6)
4171 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4175 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)
4183 PERL_ARGS_ASSERT_MY_STRFTIME;
4185 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4188 mytm.tm_hour = hour;
4189 mytm.tm_mday = mday;
4191 mytm.tm_year = year;
4192 mytm.tm_wday = wday;
4193 mytm.tm_yday = yday;
4194 mytm.tm_isdst = isdst;
4196 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4197 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4202 #ifdef HAS_TM_TM_GMTOFF
4203 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4205 #ifdef HAS_TM_TM_ZONE
4206 mytm.tm_zone = mytm2.tm_zone;
4211 Newx(buf, buflen, char);
4212 len = strftime(buf, buflen, fmt, &mytm);
4214 ** The following is needed to handle to the situation where
4215 ** tmpbuf overflows. Basically we want to allocate a buffer
4216 ** and try repeatedly. The reason why it is so complicated
4217 ** is that getting a return value of 0 from strftime can indicate
4218 ** one of the following:
4219 ** 1. buffer overflowed,
4220 ** 2. illegal conversion specifier, or
4221 ** 3. the format string specifies nothing to be returned(not
4222 ** an error). This could be because format is an empty string
4223 ** or it specifies %p that yields an empty string in some locale.
4224 ** If there is a better way to make it portable, go ahead by
4227 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4230 /* Possibly buf overflowed - try again with a bigger buf */
4231 const int fmtlen = strlen(fmt);
4232 int bufsize = fmtlen + buflen;
4234 Renew(buf, bufsize, char);
4236 buflen = strftime(buf, bufsize, fmt, &mytm);
4237 if (buflen > 0 && buflen < bufsize)
4239 /* heuristic to prevent out-of-memory errors */
4240 if (bufsize > 100*fmtlen) {
4246 Renew(buf, bufsize, char);
4251 Perl_croak(aTHX_ "panic: no strftime");
4257 #define SV_CWD_RETURN_UNDEF \
4258 sv_setsv(sv, &PL_sv_undef); \
4261 #define SV_CWD_ISDOT(dp) \
4262 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4263 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4266 =head1 Miscellaneous Functions
4268 =for apidoc getcwd_sv
4270 Fill the sv with current working directory
4275 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4276 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4277 * getcwd(3) if available
4278 * Comments from the orignal:
4279 * This is a faster version of getcwd. It's also more dangerous
4280 * because you might chdir out of a directory that you can't chdir
4284 Perl_getcwd_sv(pTHX_ register SV *sv)
4288 #ifndef INCOMPLETE_TAINTS
4292 PERL_ARGS_ASSERT_GETCWD_SV;
4296 char buf[MAXPATHLEN];
4298 /* Some getcwd()s automatically allocate a buffer of the given
4299 * size from the heap if they are given a NULL buffer pointer.
4300 * The problem is that this behaviour is not portable. */
4301 if (getcwd(buf, sizeof(buf) - 1)) {
4306 sv_setsv(sv, &PL_sv_undef);
4314 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4318 SvUPGRADE(sv, SVt_PV);
4320 if (PerlLIO_lstat(".", &statbuf) < 0) {
4321 SV_CWD_RETURN_UNDEF;
4324 orig_cdev = statbuf.st_dev;
4325 orig_cino = statbuf.st_ino;
4335 if (PerlDir_chdir("..") < 0) {
4336 SV_CWD_RETURN_UNDEF;
4338 if (PerlLIO_stat(".", &statbuf) < 0) {
4339 SV_CWD_RETURN_UNDEF;
4342 cdev = statbuf.st_dev;
4343 cino = statbuf.st_ino;
4345 if (odev == cdev && oino == cino) {
4348 if (!(dir = PerlDir_open("."))) {
4349 SV_CWD_RETURN_UNDEF;
4352 while ((dp = PerlDir_read(dir)) != NULL) {
4354 namelen = dp->d_namlen;
4356 namelen = strlen(dp->d_name);
4359 if (SV_CWD_ISDOT(dp)) {
4363 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4364 SV_CWD_RETURN_UNDEF;
4367 tdev = statbuf.st_dev;
4368 tino = statbuf.st_ino;
4369 if (tino == oino && tdev == odev) {
4375 SV_CWD_RETURN_UNDEF;
4378 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4379 SV_CWD_RETURN_UNDEF;
4382 SvGROW(sv, pathlen + namelen + 1);
4386 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4389 /* prepend current directory to the front */
4391 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4392 pathlen += (namelen + 1);
4394 #ifdef VOID_CLOSEDIR
4397 if (PerlDir_close(dir) < 0) {
4398 SV_CWD_RETURN_UNDEF;
4404 SvCUR_set(sv, pathlen);
4408 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4409 SV_CWD_RETURN_UNDEF;
4412 if (PerlLIO_stat(".", &statbuf) < 0) {
4413 SV_CWD_RETURN_UNDEF;
4416 cdev = statbuf.st_dev;
4417 cino = statbuf.st_ino;
4419 if (cdev != orig_cdev || cino != orig_cino) {
4420 Perl_croak(aTHX_ "Unstable directory path, "
4421 "current directory changed unexpectedly");
4432 #define VERSION_MAX 0x7FFFFFFF
4435 =for apidoc prescan_version
4437 Validate that a given string can be parsed as a version object, but doesn't
4438 actually perform the parsing. Can use either strict or lax validation rules.
4439 Can optionally set a number of hint variables to save the parsing code
4440 some time when tokenizing.
4445 Perl_prescan_version(pTHX_ const char *s, bool strict,
4446 const char **errstr,
4447 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4448 bool qv = (sqv ? *sqv : FALSE);
4450 int saw_decimal = 0;
4454 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4456 if (qv && isDIGIT(*d))
4457 goto dotted_decimal_version;
4459 if (*d == 'v') { /* explicit v-string */
4464 else { /* degenerate v-string */
4465 /* requires v1.2.3 */
4466 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4469 dotted_decimal_version:
4470 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4471 /* no leading zeros allowed */
4472 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4475 while (isDIGIT(*d)) /* integer part */
4481 d++; /* decimal point */
4486 /* require v1.2.3 */
4487 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4490 goto version_prescan_finish;
4497 while (isDIGIT(*d)) { /* just keep reading */
4499 while (isDIGIT(*d)) {
4501 /* maximum 3 digits between decimal */
4502 if (strict && j > 3) {
4503 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4508 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4511 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4516 else if (*d == '.') {
4518 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4523 else if (!isDIGIT(*d)) {
4529 if (strict && i < 2) {
4530 /* requires v1.2.3 */
4531 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4534 } /* end if dotted-decimal */
4536 { /* decimal versions */
4537 /* special strict case for leading '.' or '0' */
4540 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4542 if (*d == '0' && isDIGIT(d[1])) {
4543 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4547 /* consume all of the integer part */
4551 /* look for a fractional part */
4553 /* we found it, so consume it */
4557 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4560 BADVERSION(s,errstr,"Invalid version format (version required)");
4562 /* found just an integer */
4563 goto version_prescan_finish;
4565 else if ( d == s ) {
4566 /* didn't find either integer or period */
4567 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4569 else if (*d == '_') {
4570 /* underscore can't come after integer part */
4572 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4574 else if (isDIGIT(d[1])) {
4575 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4578 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4582 /* anything else after integer part is just invalid data */
4583 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4586 /* scan the fractional part after the decimal point*/
4588 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4589 /* strict or lax-but-not-the-end */
4590 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4593 while (isDIGIT(*d)) {
4595 if (*d == '.' && isDIGIT(d[-1])) {
4597 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4600 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4602 d = (char *)s; /* start all over again */
4604 goto dotted_decimal_version;
4608 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4611 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4613 if ( ! isDIGIT(d[1]) ) {
4614 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4622 version_prescan_finish:
4626 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4627 /* trailing non-numeric data */
4628 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4636 *ssaw_decimal = saw_decimal;
4643 =for apidoc scan_version
4645 Returns a pointer to the next character after the parsed
4646 version string, as well as upgrading the passed in SV to
4649 Function must be called with an already existing SV like
4652 s = scan_version(s, SV *sv, bool qv);
4654 Performs some preprocessing to the string to ensure that
4655 it has the correct characteristics of a version. Flags the
4656 object if it contains an underscore (which denotes this
4657 is an alpha version). The boolean qv denotes that the version
4658 should be interpreted as if it had multiple decimals, even if
4665 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4670 const char *errstr = NULL;
4671 int saw_decimal = 0;
4675 AV * const av = newAV();
4676 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4678 PERL_ARGS_ASSERT_SCAN_VERSION;
4680 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4682 #ifndef NODEFAULT_SHAREKEYS
4683 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4686 while (isSPACE(*s)) /* leading whitespace is OK */
4689 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4691 /* "undef" is a special case and not an error */
4692 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4693 Perl_croak(aTHX_ "%s", errstr);
4703 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4705 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4706 if ( !qv && width < 3 )
4707 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4709 while (isDIGIT(*pos))
4711 if (!isALPHA(*pos)) {
4717 /* this is atoi() that delimits on underscores */
4718 const char *end = pos;
4722 /* the following if() will only be true after the decimal
4723 * point of a version originally created with a bare
4724 * floating point number, i.e. not quoted in any way
4726 if ( !qv && s > start && saw_decimal == 1 ) {
4730 rev += (*s - '0') * mult;
4732 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4733 || (PERL_ABS(rev) > VERSION_MAX )) {
4734 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4735 "Integer overflow in version %d",VERSION_MAX);
4746 while (--end >= s) {
4748 rev += (*end - '0') * mult;
4750 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4751 || (PERL_ABS(rev) > VERSION_MAX )) {
4752 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4753 "Integer overflow in version");
4762 /* Append revision */
4763 av_push(av, newSViv(rev));
4768 else if ( *pos == '.' )
4770 else if ( *pos == '_' && isDIGIT(pos[1]) )
4772 else if ( *pos == ',' && isDIGIT(pos[1]) )
4774 else if ( isDIGIT(*pos) )
4781 while ( isDIGIT(*pos) )
4786 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4794 if ( qv ) { /* quoted versions always get at least three terms*/
4795 I32 len = av_len(av);
4796 /* This for loop appears to trigger a compiler bug on OS X, as it
4797 loops infinitely. Yes, len is negative. No, it makes no sense.
4798 Compiler in question is:
4799 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4800 for ( len = 2 - len; len > 0; len-- )
4801 av_push(MUTABLE_AV(sv), newSViv(0));
4805 av_push(av, newSViv(0));
4808 /* need to save off the current version string for later */
4810 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4811 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4812 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4814 else if ( s > start ) {
4815 SV * orig = newSVpvn(start,s-start);
4816 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4817 /* need to insert a v to be consistent */
4818 sv_insert(orig, 0, 0, "v", 1);
4820 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4823 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4824 av_push(av, newSViv(0));
4827 /* And finally, store the AV in the hash */
4828 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4830 /* fix RT#19517 - special case 'undef' as string */
4831 if ( *s == 'u' && strEQ(s,"undef") ) {
4839 =for apidoc new_version
4841 Returns a new version object based on the passed in SV:
4843 SV *sv = new_version(SV *ver);
4845 Does not alter the passed in ver SV. See "upg_version" if you
4846 want to upgrade the SV.
4852 Perl_new_version(pTHX_ SV *ver)
4855 SV * const rv = newSV(0);
4856 PERL_ARGS_ASSERT_NEW_VERSION;
4857 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4860 AV * const av = newAV();
4862 /* This will get reblessed later if a derived class*/
4863 SV * const hv = newSVrv(rv, "version");
4864 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4865 #ifndef NODEFAULT_SHAREKEYS
4866 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4872 /* Begin copying all of the elements */
4873 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4874 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4876 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4877 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4879 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4881 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4882 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4885 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4887 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4888 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4891 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4892 /* This will get reblessed later if a derived class*/
4893 for ( key = 0; key <= av_len(sav); key++ )
4895 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4896 av_push(av, newSViv(rev));
4899 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4904 const MAGIC* const mg = SvVSTRING_mg(ver);
4905 if ( mg ) { /* already a v-string */
4906 const STRLEN len = mg->mg_len;
4907 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4908 sv_setpvn(rv,version,len);
4909 /* this is for consistency with the pure Perl class */
4910 if ( isDIGIT(*version) )
4911 sv_insert(rv, 0, 0, "v", 1);
4916 sv_setsv(rv,ver); /* make a duplicate */
4921 return upg_version(rv, FALSE);
4925 =for apidoc upg_version
4927 In-place upgrade of the supplied SV to a version object.
4929 SV *sv = upg_version(SV *sv, bool qv);
4931 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4932 to force this SV to be interpreted as an "extended" version.
4938 Perl_upg_version(pTHX_ SV *ver, bool qv)
4940 const char *version, *s;
4945 PERL_ARGS_ASSERT_UPG_VERSION;
4947 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4949 /* may get too much accuracy */
4951 #ifdef USE_LOCALE_NUMERIC
4952 char *loc = setlocale(LC_NUMERIC, "C");
4954 STRLEN len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4955 #ifdef USE_LOCALE_NUMERIC
4956 setlocale(LC_NUMERIC, loc);
4958 while (tbuf[len-1] == '0' && len > 0) len--;
4959 if ( tbuf[len-1] == '.' ) len--; /* eat the trailing decimal */
4960 version = savepvn(tbuf, len);
4963 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4964 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4968 else /* must be a string or something like a string */
4971 version = savepv(SvPV(ver,len));
4973 # if PERL_VERSION > 5
4974 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4975 if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
4976 /* may be a v-string */
4977 char *testv = (char *)version;
4979 for (tlen=0; tlen < len; tlen++, testv++) {
4980 /* if one of the characters is non-text assume v-string */
4981 if (testv[0] < ' ') {
4982 SV * const nsv = sv_newmortal();
4985 int saw_decimal = 0;
4986 sv_setpvf(nsv,"v%vd",ver);
4987 pos = nver = savepv(SvPV_nolen(nsv));
4989 /* scan the resulting formatted string */
4990 pos++; /* skip the leading 'v' */
4991 while ( *pos == '.' || isDIGIT(*pos) ) {
4997 /* is definitely a v-string */
4998 if ( saw_decimal >= 2 ) {
5010 s = scan_version(version, ver, qv);
5012 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
5013 "Version string '%s' contains invalid data; "
5014 "ignoring: '%s'", version, s);
5022 Validates that the SV contains valid internal structure for a version object.
5023 It may be passed either the version object (RV) or the hash itself (HV). If
5024 the structure is valid, it returns the HV. If the structure is invalid,
5027 SV *hv = vverify(sv);
5029 Note that it only confirms the bare minimum structure (so as not to get
5030 confused by derived classes which may contain additional hash entries):
5034 =item * The SV is an HV or a reference to an HV
5036 =item * The hash contains a "version" key
5038 =item * The "version" key has a reference to an AV as its value
5046 Perl_vverify(pTHX_ SV *vs)
5050 PERL_ARGS_ASSERT_VVERIFY;
5055 /* see if the appropriate elements exist */
5056 if ( SvTYPE(vs) == SVt_PVHV
5057 && hv_exists(MUTABLE_HV(vs), "version", 7)
5058 && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
5059 && SvTYPE(sv) == SVt_PVAV )
5068 Accepts a version object and returns the normalized floating
5069 point representation. Call like:
5073 NOTE: you can pass either the object directly or the SV
5074 contained within the RV.
5076 The SV returned has a refcount of 1.
5082 Perl_vnumify(pTHX_ SV *vs)
5090 PERL_ARGS_ASSERT_VNUMIFY;
5092 /* extract the HV from the object */
5095 Perl_croak(aTHX_ "Invalid version object");
5097 /* see if various flags exist */
5098 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5100 if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
5101 width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
5106 /* attempt to retrieve the version array */
5107 if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
5108 return newSVpvs("0");
5114 return newSVpvs("0");
5117 digit = SvIV(*av_fetch(av, 0, 0));
5118 sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
5119 for ( i = 1 ; i < len ; i++ )
5121 digit = SvIV(*av_fetch(av, i, 0));
5123 const int denom = (width == 2 ? 10 : 100);
5124 const div_t term = div((int)PERL_ABS(digit),denom);
5125 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
5128 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5134 digit = SvIV(*av_fetch(av, len, 0));
5135 if ( alpha && width == 3 ) /* alpha version */
5137 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5141 sv_catpvs(sv, "000");
5149 Accepts a version object and returns the normalized string
5150 representation. Call like:
5154 NOTE: you can pass either the object directly or the SV
5155 contained within the RV.
5157 The SV returned has a refcount of 1.
5163 Perl_vnormal(pTHX_ SV *vs)
5170 PERL_ARGS_ASSERT_VNORMAL;
5172 /* extract the HV from the object */
5175 Perl_croak(aTHX_ "Invalid version object");
5177 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5179 av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)));
5184 return newSVpvs("");
5186 digit = SvIV(*av_fetch(av, 0, 0));
5187 sv = Perl_newSVpvf(aTHX_ "v%"IVdf, (IV)digit);
5188 for ( i = 1 ; i < len ; i++ ) {
5189 digit = SvIV(*av_fetch(av, i, 0));
5190 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5195 /* handle last digit specially */
5196 digit = SvIV(*av_fetch(av, len, 0));
5198 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
5200 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5203 if ( len <= 2 ) { /* short version, must be at least three */
5204 for ( len = 2 - len; len != 0; len-- )
5211 =for apidoc vstringify
5213 In order to maintain maximum compatibility with earlier versions
5214 of Perl, this function will return either the floating point
5215 notation or the multiple dotted notation, depending on whether
5216 the original version contained 1 or more dots, respectively.
5218 The SV returned has a refcount of 1.
5224 Perl_vstringify(pTHX_ SV *vs)
5226 PERL_ARGS_ASSERT_VSTRINGIFY;
5228 /* extract the HV from the object */
5231 Perl_croak(aTHX_ "Invalid version object");
5233 if (hv_exists(MUTABLE_HV(vs), "original", sizeof("original") - 1)) {
5235 pv = *hv_fetchs(MUTABLE_HV(vs), "original", FALSE);
5239 return &PL_sv_undef;
5242 if ( hv_exists(MUTABLE_HV(vs), "qv", 2) )
5252 Version object aware cmp. Both operands must already have been
5253 converted into version objects.
5259 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
5262 bool lalpha = FALSE;
5263 bool ralpha = FALSE;
5268 PERL_ARGS_ASSERT_VCMP;
5270 /* extract the HVs from the objects */
5273 if ( ! ( lhv && rhv ) )
5274 Perl_croak(aTHX_ "Invalid version object");
5276 /* get the left hand term */
5277 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(lhv), "version", FALSE)));
5278 if ( hv_exists(MUTABLE_HV(lhv), "alpha", 5 ) )
5281 /* and the right hand term */
5282 rav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rhv), "version", FALSE)));
5283 if ( hv_exists(MUTABLE_HV(rhv), "alpha", 5 ) )
5291 while ( i <= m && retval == 0 )
5293 left = SvIV(*av_fetch(lav,i,0));
5294 right = SvIV(*av_fetch(rav,i,0));
5302 /* tiebreaker for alpha with identical terms */
5303 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
5305 if ( lalpha && !ralpha )
5309 else if ( ralpha && !lalpha)
5315 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
5319 while ( i <= r && retval == 0 )
5321 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
5322 retval = -1; /* not a match after all */
5328 while ( i <= l && retval == 0 )
5330 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
5331 retval = +1; /* not a match after all */
5339 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
5340 # define EMULATE_SOCKETPAIR_UDP
5343 #ifdef EMULATE_SOCKETPAIR_UDP
5345 S_socketpair_udp (int fd[2]) {
5347 /* Fake a datagram socketpair using UDP to localhost. */
5348 int sockets[2] = {-1, -1};
5349 struct sockaddr_in addresses[2];
5351 Sock_size_t size = sizeof(struct sockaddr_in);
5352 unsigned short port;
5355 memset(&addresses, 0, sizeof(addresses));
5358 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
5359 if (sockets[i] == -1)
5360 goto tidy_up_and_fail;
5362 addresses[i].sin_family = AF_INET;
5363 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5364 addresses[i].sin_port = 0; /* kernel choses port. */
5365 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
5366 sizeof(struct sockaddr_in)) == -1)
5367 goto tidy_up_and_fail;
5370 /* Now have 2 UDP sockets. Find out which port each is connected to, and
5371 for each connect the other socket to it. */
5374 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
5376 goto tidy_up_and_fail;
5377 if (size != sizeof(struct sockaddr_in))
5378 goto abort_tidy_up_and_fail;
5379 /* !1 is 0, !0 is 1 */
5380 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
5381 sizeof(struct sockaddr_in)) == -1)
5382 goto tidy_up_and_fail;
5385 /* Now we have 2 sockets connected to each other. I don't trust some other
5386 process not to have already sent a packet to us (by random) so send
5387 a packet from each to the other. */
5390 /* I'm going to send my own port number. As a short.
5391 (Who knows if someone somewhere has sin_port as a bitfield and needs
5392 this routine. (I'm assuming crays have socketpair)) */
5393 port = addresses[i].sin_port;
5394 got = PerlLIO_write(sockets[i], &port, sizeof(port));
5395 if (got != sizeof(port)) {
5397 goto tidy_up_and_fail;
5398 goto abort_tidy_up_and_fail;
5402 /* Packets sent. I don't trust them to have arrived though.
5403 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
5404 connect to localhost will use a second kernel thread. In 2.6 the
5405 first thread running the connect() returns before the second completes,
5406 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
5407 returns 0. Poor programs have tripped up. One poor program's authors'
5408 had a 50-1 reverse stock split. Not sure how connected these were.)
5409 So I don't trust someone not to have an unpredictable UDP stack.
5413 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
5414 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
5418 FD_SET((unsigned int)sockets[0], &rset);
5419 FD_SET((unsigned int)sockets[1], &rset);
5421 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
5422 if (got != 2 || !FD_ISSET(sockets[0], &rset)
5423 || !FD_ISSET(sockets[1], &rset)) {
5424 /* I hope this is portable and appropriate. */
5426 goto tidy_up_and_fail;
5427 goto abort_tidy_up_and_fail;
5431 /* And the paranoia department even now doesn't trust it to have arrive
5432 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
5434 struct sockaddr_in readfrom;
5435 unsigned short buffer[2];
5440 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5441 sizeof(buffer), MSG_DONTWAIT,
5442 (struct sockaddr *) &readfrom, &size);
5444 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5446 (struct sockaddr *) &readfrom, &size);
5450 goto tidy_up_and_fail;
5451 if (got != sizeof(port)
5452 || size != sizeof(struct sockaddr_in)
5453 /* Check other socket sent us its port. */
5454 || buffer[0] != (unsigned short) addresses[!i].sin_port
5455 /* Check kernel says we got the datagram from that socket */
5456 || readfrom.sin_family != addresses[!i].sin_family
5457 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
5458 || readfrom.sin_port != addresses[!i].sin_port)
5459 goto abort_tidy_up_and_fail;
5462 /* My caller (my_socketpair) has validated that this is non-NULL */
5465 /* I hereby declare this connection open. May God bless all who cross
5469 abort_tidy_up_and_fail:
5470 errno = ECONNABORTED;
5474 if (sockets[0] != -1)
5475 PerlLIO_close(sockets[0]);
5476 if (sockets[1] != -1)
5477 PerlLIO_close(sockets[1]);
5482 #endif /* EMULATE_SOCKETPAIR_UDP */
5484 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
5486 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5487 /* Stevens says that family must be AF_LOCAL, protocol 0.
5488 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
5493 struct sockaddr_in listen_addr;
5494 struct sockaddr_in connect_addr;
5499 || family != AF_UNIX
5502 errno = EAFNOSUPPORT;
5510 #ifdef EMULATE_SOCKETPAIR_UDP
5511 if (type == SOCK_DGRAM)
5512 return S_socketpair_udp(fd);
5515 listener = PerlSock_socket(AF_INET, type, 0);
5518 memset(&listen_addr, 0, sizeof(listen_addr));
5519 listen_addr.sin_family = AF_INET;
5520 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5521 listen_addr.sin_port = 0; /* kernel choses port. */
5522 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5523 sizeof(listen_addr)) == -1)
5524 goto tidy_up_and_fail;
5525 if (PerlSock_listen(listener, 1) == -1)
5526 goto tidy_up_and_fail;
5528 connector = PerlSock_socket(AF_INET, type, 0);
5529 if (connector == -1)
5530 goto tidy_up_and_fail;
5531 /* We want to find out the port number to connect to. */
5532 size = sizeof(connect_addr);
5533 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5535 goto tidy_up_and_fail;
5536 if (size != sizeof(connect_addr))
5537 goto abort_tidy_up_and_fail;
5538 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
5539 sizeof(connect_addr)) == -1)
5540 goto tidy_up_and_fail;
5542 size = sizeof(listen_addr);
5543 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5546 goto tidy_up_and_fail;
5547 if (size != sizeof(listen_addr))
5548 goto abort_tidy_up_and_fail;
5549 PerlLIO_close(listener);
5550 /* Now check we are talking to ourself by matching port and host on the
5552 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5554 goto tidy_up_and_fail;
5555 if (size != sizeof(connect_addr)
5556 || listen_addr.sin_family != connect_addr.sin_family
5557 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5558 || listen_addr.sin_port != connect_addr.sin_port) {
5559 goto abort_tidy_up_and_fail;
5565 abort_tidy_up_and_fail:
5567 errno = ECONNABORTED; /* This would be the standard thing to do. */
5569 # ifdef ECONNREFUSED
5570 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5572 errno = ETIMEDOUT; /* Desperation time. */
5579 PerlLIO_close(listener);
5580 if (connector != -1)
5581 PerlLIO_close(connector);
5583 PerlLIO_close(acceptor);
5589 /* In any case have a stub so that there's code corresponding
5590 * to the my_socketpair in global.sym. */
5592 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5593 #ifdef HAS_SOCKETPAIR
5594 return socketpair(family, type, protocol, fd);
5603 =for apidoc sv_nosharing
5605 Dummy routine which "shares" an SV when there is no sharing module present.
5606 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5607 Exists to avoid test for a NULL function pointer and because it could
5608 potentially warn under some level of strict-ness.
5614 Perl_sv_nosharing(pTHX_ SV *sv)
5616 PERL_UNUSED_CONTEXT;
5617 PERL_UNUSED_ARG(sv);
5622 =for apidoc sv_destroyable
5624 Dummy routine which reports that object can be destroyed when there is no
5625 sharing module present. It ignores its single SV argument, and returns
5626 'true'. Exists to avoid test for a NULL function pointer and because it
5627 could potentially warn under some level of strict-ness.
5633 Perl_sv_destroyable(pTHX_ SV *sv)
5635 PERL_UNUSED_CONTEXT;
5636 PERL_UNUSED_ARG(sv);
5641 Perl_parse_unicode_opts(pTHX_ const char **popt)
5643 const char *p = *popt;
5646 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5650 opt = (U32) atoi(p);
5653 if (*p && *p != '\n' && *p != '\r') {
5654 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5656 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
5662 case PERL_UNICODE_STDIN:
5663 opt |= PERL_UNICODE_STDIN_FLAG; break;
5664 case PERL_UNICODE_STDOUT:
5665 opt |= PERL_UNICODE_STDOUT_FLAG; break;
5666 case PERL_UNICODE_STDERR:
5667 opt |= PERL_UNICODE_STDERR_FLAG; break;
5668 case PERL_UNICODE_STD:
5669 opt |= PERL_UNICODE_STD_FLAG; break;
5670 case PERL_UNICODE_IN:
5671 opt |= PERL_UNICODE_IN_FLAG; break;
5672 case PERL_UNICODE_OUT:
5673 opt |= PERL_UNICODE_OUT_FLAG; break;
5674 case PERL_UNICODE_INOUT:
5675 opt |= PERL_UNICODE_INOUT_FLAG; break;
5676 case PERL_UNICODE_LOCALE:
5677 opt |= PERL_UNICODE_LOCALE_FLAG; break;
5678 case PERL_UNICODE_ARGV:
5679 opt |= PERL_UNICODE_ARGV_FLAG; break;
5680 case PERL_UNICODE_UTF8CACHEASSERT:
5681 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
5683 if (*p != '\n' && *p != '\r') {
5684 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5687 "Unknown Unicode option letter '%c'", *p);
5694 opt = PERL_UNICODE_DEFAULT_FLAGS;
5696 the_end_of_the_opts_parser:
5698 if (opt & ~PERL_UNICODE_ALL_FLAGS)
5699 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
5700 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5712 * This is really just a quick hack which grabs various garbage
5713 * values. It really should be a real hash algorithm which
5714 * spreads the effect of every input bit onto every output bit,
5715 * if someone who knows about such things would bother to write it.
5716 * Might be a good idea to add that function to CORE as well.
5717 * No numbers below come from careful analysis or anything here,
5718 * except they are primes and SEED_C1 > 1E6 to get a full-width
5719 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5720 * probably be bigger too.
5723 # define SEED_C1 1000003
5724 #define SEED_C4 73819
5726 # define SEED_C1 25747
5727 #define SEED_C4 20639
5731 #define SEED_C5 26107
5733 #ifndef PERL_NO_DEV_RANDOM
5738 # include <starlet.h>
5739 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5740 * in 100-ns units, typically incremented ever 10 ms. */
5741 unsigned int when[2];
5743 # ifdef HAS_GETTIMEOFDAY
5744 struct timeval when;
5750 /* This test is an escape hatch, this symbol isn't set by Configure. */
5751 #ifndef PERL_NO_DEV_RANDOM
5752 #ifndef PERL_RANDOM_DEVICE
5753 /* /dev/random isn't used by default because reads from it will block
5754 * if there isn't enough entropy available. You can compile with
5755 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5756 * is enough real entropy to fill the seed. */
5757 # define PERL_RANDOM_DEVICE "/dev/urandom"
5759 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5761 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5770 _ckvmssts(sys$gettim(when));
5771 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5773 # ifdef HAS_GETTIMEOFDAY
5774 PerlProc_gettimeofday(&when,NULL);
5775 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5778 u = (U32)SEED_C1 * when;
5781 u += SEED_C3 * (U32)PerlProc_getpid();
5782 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5783 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5784 u += SEED_C5 * (U32)PTR2UV(&when);
5790 Perl_get_hash_seed(pTHX)
5793 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
5799 if (s && isDIGIT(*s))
5800 myseed = (UV)Atoul(s);
5802 #ifdef USE_HASH_SEED_EXPLICIT
5806 /* Compute a random seed */
5807 (void)seedDrand01((Rand_seed_t)seed());
5808 myseed = (UV)(Drand01() * (NV)UV_MAX);
5809 #if RANDBITS < (UVSIZE * 8)
5810 /* Since there are not enough randbits to to reach all
5811 * the bits of a UV, the low bits might need extra
5812 * help. Sum in another random number that will
5813 * fill in the low bits. */
5815 (UV)(Drand01() * (NV)((((UV)1) << ((UVSIZE * 8 - RANDBITS))) - 1));
5816 #endif /* RANDBITS < (UVSIZE * 8) */
5817 if (myseed == 0) { /* Superparanoia. */
5818 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5820 Perl_croak(aTHX_ "Your random numbers are not that random");
5823 PL_rehash_seed_set = TRUE;
5830 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5832 const char * const stashpv = CopSTASHPV(c);
5833 const char * const name = HvNAME_get(hv);
5834 PERL_UNUSED_CONTEXT;
5835 PERL_ARGS_ASSERT_STASHPV_HVNAME_MATCH;
5837 if (stashpv == name)
5839 if (stashpv && name)
5840 if (strEQ(stashpv, name))
5847 #ifdef PERL_GLOBAL_STRUCT
5849 #define PERL_GLOBAL_STRUCT_INIT
5850 #include "opcode.h" /* the ppaddr and check */
5853 Perl_init_global_struct(pTHX)
5855 struct perl_vars *plvarsp = NULL;
5856 # ifdef PERL_GLOBAL_STRUCT
5857 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5858 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5859 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5860 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5861 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5865 plvarsp = PL_VarsPtr;
5866 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5872 # define PERLVAR(var,type) /**/
5873 # define PERLVARA(var,n,type) /**/
5874 # define PERLVARI(var,type,init) plvarsp->var = init;
5875 # define PERLVARIC(var,type,init) plvarsp->var = init;
5876 # define PERLVARISC(var,init) Copy(init, plvarsp->var, sizeof(init), char);
5877 # include "perlvars.h"
5883 # ifdef PERL_GLOBAL_STRUCT
5886 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5887 if (!plvarsp->Gppaddr)
5891 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5892 if (!plvarsp->Gcheck)
5894 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5895 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5897 # ifdef PERL_SET_VARS
5898 PERL_SET_VARS(plvarsp);
5900 # undef PERL_GLOBAL_STRUCT_INIT
5905 #endif /* PERL_GLOBAL_STRUCT */
5907 #ifdef PERL_GLOBAL_STRUCT
5910 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5912 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
5913 # ifdef PERL_GLOBAL_STRUCT
5914 # ifdef PERL_UNSET_VARS
5915 PERL_UNSET_VARS(plvarsp);
5917 free(plvarsp->Gppaddr);
5918 free(plvarsp->Gcheck);
5919 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5925 #endif /* PERL_GLOBAL_STRUCT */
5929 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
5930 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
5931 * given, and you supply your own implementation.
5933 * The default implementation reads a single env var, PERL_MEM_LOG,
5934 * expecting one or more of the following:
5936 * \d+ - fd fd to write to : must be 1st (atoi)
5937 * 'm' - memlog was PERL_MEM_LOG=1
5938 * 's' - svlog was PERL_SV_LOG=1
5939 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
5941 * This makes the logger controllable enough that it can reasonably be
5942 * added to the system perl.
5945 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
5946 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5948 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5950 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
5951 * writes to. In the default logger, this is settable at runtime.
5953 #ifndef PERL_MEM_LOG_FD
5954 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5957 #ifndef PERL_MEM_LOG_NOIMPL
5959 # ifdef DEBUG_LEAKING_SCALARS
5960 # define SV_LOG_SERIAL_FMT " [%lu]"
5961 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
5963 # define SV_LOG_SERIAL_FMT
5964 # define _SV_LOG_SERIAL_ARG(sv)
5968 S_mem_log_common(enum mem_log_type mlt, const UV n,
5969 const UV typesize, const char *type_name, const SV *sv,
5970 Malloc_t oldalloc, Malloc_t newalloc,
5971 const char *filename, const int linenumber,
5972 const char *funcname)
5976 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
5978 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
5981 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
5983 /* We can't use SVs or PerlIO for obvious reasons,
5984 * so we'll use stdio and low-level IO instead. */
5985 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5987 # ifdef HAS_GETTIMEOFDAY
5988 # define MEM_LOG_TIME_FMT "%10d.%06d: "
5989 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
5991 gettimeofday(&tv, 0);
5993 # define MEM_LOG_TIME_FMT "%10d: "
5994 # define MEM_LOG_TIME_ARG (int)when
5998 /* If there are other OS specific ways of hires time than
5999 * gettimeofday() (see ext/Time-HiRes), the easiest way is
6000 * probably that they would be used to fill in the struct
6004 int fd = atoi(pmlenv);
6006 fd = PERL_MEM_LOG_FD;
6008 if (strchr(pmlenv, 't')) {
6009 len = my_snprintf(buf, sizeof(buf),
6010 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
6011 PerlLIO_write(fd, buf, len);
6015 len = my_snprintf(buf, sizeof(buf),
6016 "alloc: %s:%d:%s: %"IVdf" %"UVuf
6017 " %s = %"IVdf": %"UVxf"\n",
6018 filename, linenumber, funcname, n, typesize,
6019 type_name, n * typesize, PTR2UV(newalloc));
6022 len = my_snprintf(buf, sizeof(buf),
6023 "realloc: %s:%d:%s: %"IVdf" %"UVuf
6024 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
6025 filename, linenumber, funcname, n, typesize,
6026 type_name, n * typesize, PTR2UV(oldalloc),
6030 len = my_snprintf(buf, sizeof(buf),
6031 "free: %s:%d:%s: %"UVxf"\n",
6032 filename, linenumber, funcname,
6037 len = my_snprintf(buf, sizeof(buf),
6038 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
6039 mlt == MLT_NEW_SV ? "new" : "del",
6040 filename, linenumber, funcname,
6041 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
6046 PerlLIO_write(fd, buf, len);
6050 #endif /* !PERL_MEM_LOG_NOIMPL */
6052 #ifndef PERL_MEM_LOG_NOIMPL
6054 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
6055 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
6057 /* this is suboptimal, but bug compatible. User is providing their
6058 own implementation, but is getting these functions anyway, and they
6059 do nothing. But _NOIMPL users should be able to cope or fix */
6061 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
6062 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
6066 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
6068 const char *filename, const int linenumber,
6069 const char *funcname)
6071 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
6072 NULL, NULL, newalloc,
6073 filename, linenumber, funcname);
6078 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
6079 Malloc_t oldalloc, Malloc_t newalloc,
6080 const char *filename, const int linenumber,
6081 const char *funcname)
6083 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
6084 NULL, oldalloc, newalloc,
6085 filename, linenumber, funcname);
6090 Perl_mem_log_free(Malloc_t oldalloc,
6091 const char *filename, const int linenumber,
6092 const char *funcname)
6094 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
6095 filename, linenumber, funcname);
6100 Perl_mem_log_new_sv(const SV *sv,
6101 const char *filename, const int linenumber,
6102 const char *funcname)
6104 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
6105 filename, linenumber, funcname);
6109 Perl_mem_log_del_sv(const SV *sv,
6110 const char *filename, const int linenumber,
6111 const char *funcname)
6113 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
6114 filename, linenumber, funcname);
6117 #endif /* PERL_MEM_LOG */
6120 =for apidoc my_sprintf
6122 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
6123 the length of the string written to the buffer. Only rare pre-ANSI systems
6124 need the wrapper function - usually this is a direct call to C<sprintf>.
6128 #ifndef SPRINTF_RETURNS_STRLEN
6130 Perl_my_sprintf(char *buffer, const char* pat, ...)
6133 PERL_ARGS_ASSERT_MY_SPRINTF;
6134 va_start(args, pat);
6135 vsprintf(buffer, pat, args);
6137 return strlen(buffer);
6142 =for apidoc my_snprintf
6144 The C library C<snprintf> functionality, if available and
6145 standards-compliant (uses C<vsnprintf>, actually). However, if the
6146 C<vsnprintf> is not available, will unfortunately use the unsafe
6147 C<vsprintf> which can overrun the buffer (there is an overrun check,
6148 but that may be too late). Consider using C<sv_vcatpvf> instead, or
6149 getting C<vsnprintf>.
6154 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
6159 PERL_ARGS_ASSERT_MY_SNPRINTF;
6160 va_start(ap, format);
6161 #ifdef HAS_VSNPRINTF
6162 retval = vsnprintf(buffer, len, format, ap);
6164 retval = vsprintf(buffer, format, ap);
6167 /* vsprintf() shows failure with < 0 */
6169 #ifdef HAS_VSNPRINTF
6170 /* vsnprintf() shows failure with >= len */
6172 (len > 0 && (Size_t)retval >= len)
6175 Perl_croak(aTHX_ "panic: my_snprintf buffer overflow");
6180 =for apidoc my_vsnprintf
6182 The C library C<vsnprintf> if available and standards-compliant.
6183 However, if if the C<vsnprintf> is not available, will unfortunately
6184 use the unsafe C<vsprintf> which can overrun the buffer (there is an
6185 overrun check, but that may be too late). Consider using
6186 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
6191 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
6198 PERL_ARGS_ASSERT_MY_VSNPRINTF;
6200 Perl_va_copy(ap, apc);
6201 # ifdef HAS_VSNPRINTF
6202 retval = vsnprintf(buffer, len, format, apc);
6204 retval = vsprintf(buffer, format, apc);
6207 # ifdef HAS_VSNPRINTF
6208 retval = vsnprintf(buffer, len, format, ap);
6210 retval = vsprintf(buffer, format, ap);
6212 #endif /* #ifdef NEED_VA_COPY */
6213 /* vsprintf() shows failure with < 0 */
6215 #ifdef HAS_VSNPRINTF
6216 /* vsnprintf() shows failure with >= len */
6218 (len > 0 && (Size_t)retval >= len)
6221 Perl_croak(aTHX_ "panic: my_vsnprintf buffer overflow");
6226 Perl_my_clearenv(pTHX)
6229 #if ! defined(PERL_MICRO)
6230 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
6232 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
6233 # if defined(USE_ENVIRON_ARRAY)
6234 # if defined(USE_ITHREADS)
6235 /* only the parent thread can clobber the process environment */
6236 if (PL_curinterp == aTHX)
6237 # endif /* USE_ITHREADS */
6239 # if ! defined(PERL_USE_SAFE_PUTENV)
6240 if ( !PL_use_safe_putenv) {
6242 if (environ == PL_origenviron)
6243 environ = (char**)safesysmalloc(sizeof(char*));
6245 for (i = 0; environ[i]; i++)
6246 (void)safesysfree(environ[i]);
6249 # else /* PERL_USE_SAFE_PUTENV */
6250 # if defined(HAS_CLEARENV)
6252 # elif defined(HAS_UNSETENV)
6253 int bsiz = 80; /* Most envvar names will be shorter than this. */
6254 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
6255 char *buf = (char*)safesysmalloc(bufsiz);
6256 while (*environ != NULL) {
6257 char *e = strchr(*environ, '=');
6258 int l = e ? e - *environ : (int)strlen(*environ);
6260 (void)safesysfree(buf);
6261 bsiz = l + 1; /* + 1 for the \0. */
6262 buf = (char*)safesysmalloc(bufsiz);
6264 memcpy(buf, *environ, l);
6266 (void)unsetenv(buf);
6268 (void)safesysfree(buf);
6269 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
6270 /* Just null environ and accept the leakage. */
6272 # endif /* HAS_CLEARENV || HAS_UNSETENV */
6273 # endif /* ! PERL_USE_SAFE_PUTENV */
6275 # endif /* USE_ENVIRON_ARRAY */
6276 # endif /* PERL_IMPLICIT_SYS || WIN32 */
6277 #endif /* PERL_MICRO */
6280 #ifdef PERL_IMPLICIT_CONTEXT
6282 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
6283 the global PL_my_cxt_index is incremented, and that value is assigned to
6284 that module's static my_cxt_index (who's address is passed as an arg).
6285 Then, for each interpreter this function is called for, it makes sure a
6286 void* slot is available to hang the static data off, by allocating or
6287 extending the interpreter's PL_my_cxt_list array */
6289 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
6291 Perl_my_cxt_init(pTHX_ int *index, size_t size)
6295 PERL_ARGS_ASSERT_MY_CXT_INIT;
6297 /* this module hasn't been allocated an index yet */
6298 #if defined(USE_ITHREADS)
6299 MUTEX_LOCK(&PL_my_ctx_mutex);
6301 *index = PL_my_cxt_index++;
6302 #if defined(USE_ITHREADS)
6303 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6307 /* make sure the array is big enough */
6308 if (PL_my_cxt_size <= *index) {
6309 if (PL_my_cxt_size) {
6310 while (PL_my_cxt_size <= *index)
6311 PL_my_cxt_size *= 2;
6312 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6315 PL_my_cxt_size = 16;
6316 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6319 /* newSV() allocates one more than needed */
6320 p = (void*)SvPVX(newSV(size-1));
6321 PL_my_cxt_list[*index] = p;
6322 Zero(p, size, char);
6326 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6329 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
6334 PERL_ARGS_ASSERT_MY_CXT_INDEX;
6336 for (index = 0; index < PL_my_cxt_index; index++) {
6337 const char *key = PL_my_cxt_keys[index];
6338 /* try direct pointer compare first - there are chances to success,
6339 * and it's much faster.
6341 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
6348 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
6354 PERL_ARGS_ASSERT_MY_CXT_INIT;
6356 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
6358 /* this module hasn't been allocated an index yet */
6359 #if defined(USE_ITHREADS)
6360 MUTEX_LOCK(&PL_my_ctx_mutex);
6362 index = PL_my_cxt_index++;
6363 #if defined(USE_ITHREADS)
6364 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6368 /* make sure the array is big enough */
6369 if (PL_my_cxt_size <= index) {
6370 int old_size = PL_my_cxt_size;
6372 if (PL_my_cxt_size) {
6373 while (PL_my_cxt_size <= index)
6374 PL_my_cxt_size *= 2;
6375 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6376 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6379 PL_my_cxt_size = 16;
6380 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6381 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6383 for (i = old_size; i < PL_my_cxt_size; i++) {
6384 PL_my_cxt_keys[i] = 0;
6385 PL_my_cxt_list[i] = 0;
6388 PL_my_cxt_keys[index] = my_cxt_key;
6389 /* newSV() allocates one more than needed */
6390 p = (void*)SvPVX(newSV(size-1));
6391 PL_my_cxt_list[index] = p;
6392 Zero(p, size, char);
6395 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6396 #endif /* PERL_IMPLICIT_CONTEXT */
6399 Perl_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
6403 const char *vn = NULL;
6404 SV *const module = PL_stack_base[ax];
6406 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
6408 if (items >= 2) /* version supplied as bootstrap arg */
6409 sv = PL_stack_base[ax + 1];
6411 /* XXX GV_ADDWARN */
6413 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6414 if (!sv || !SvOK(sv)) {
6416 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6420 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
6421 SV *pmsv = sv_derived_from(sv, "version")
6422 ? sv : sv_2mortal(new_version(sv));
6423 xssv = upg_version(xssv, 0);
6424 if ( vcmp(pmsv,xssv) ) {
6425 SV *string = vstringify(xssv);
6426 SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
6427 " does not match ", module, string);
6429 SvREFCNT_dec(string);
6430 string = vstringify(pmsv);
6433 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, module, vn,
6436 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, string);
6438 SvREFCNT_dec(string);
6440 Perl_sv_2mortal(aTHX_ xpt);
6441 Perl_croak_sv(aTHX_ xpt);
6447 Perl_xs_apiversion_bootcheck(pTHX_ SV *module, const char *api_p,
6451 SV *compver = Perl_newSVpvn_flags(aTHX_ api_p, api_len, SVs_TEMP);
6454 PERL_ARGS_ASSERT_XS_APIVERSION_BOOTCHECK;
6456 /* This might croak */
6457 compver = upg_version(compver, 0);
6458 /* This should never croak */
6459 runver = new_version(PL_apiversion);
6460 if (vcmp(compver, runver)) {
6461 SV *compver_string = vstringify(compver);
6462 SV *runver_string = vstringify(runver);
6463 xpt = Perl_newSVpvf(aTHX_ "Perl API version %"SVf
6464 " of %"SVf" does not match %"SVf,
6465 compver_string, module, runver_string);
6466 Perl_sv_2mortal(aTHX_ xpt);
6468 SvREFCNT_dec(compver_string);
6469 SvREFCNT_dec(runver_string);
6471 SvREFCNT_dec(runver);
6473 Perl_croak_sv(aTHX_ xpt);
6478 Perl_my_strlcat(char *dst, const char *src, Size_t size)
6480 Size_t used, length, copy;
6483 length = strlen(src);
6484 if (size > 0 && used < size - 1) {
6485 copy = (length >= size - used) ? size - used - 1 : length;
6486 memcpy(dst + used, src, copy);
6487 dst[used + copy] = '\0';
6489 return used + length;
6495 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
6497 Size_t length, copy;
6499 length = strlen(src);
6501 copy = (length >= size) ? size - 1 : length;
6502 memcpy(dst, src, copy);
6509 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
6510 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
6511 long _ftol( double ); /* Defined by VC6 C libs. */
6512 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
6516 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
6519 SV * const dbsv = GvSVn(PL_DBsub);
6520 const bool save_taint = PL_tainted;
6522 /* We do not care about using sv to call CV;
6523 * it's for informational purposes only.
6526 PERL_ARGS_ASSERT_GET_DB_SUB;
6530 if (!PERLDB_SUB_NN) {
6533 if ( svp && ((CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
6534 || strEQ(GvNAME(gv), "END")
6535 || ((GvCV(gv) != cv) && /* Could be imported, and old sub redefined. */
6536 !( (SvTYPE(*svp) == SVt_PVGV)
6537 && (GvCV((const GV *)*svp) == cv)
6538 && (gv = (GV *)*svp)
6542 /* Use GV from the stack as a fallback. */
6543 /* GV is potentially non-unique, or contain different CV. */
6544 SV * const tmp = newRV(MUTABLE_SV(cv));
6545 sv_setsv(dbsv, tmp);
6549 gv_efullname3(dbsv, gv, NULL);
6553 const int type = SvTYPE(dbsv);
6554 if (type < SVt_PVIV && type != SVt_IV)
6555 sv_upgrade(dbsv, SVt_PVIV);
6556 (void)SvIOK_on(dbsv);
6557 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
6559 TAINT_IF(save_taint);
6563 Perl_my_dirfd(pTHX_ DIR * dir) {
6565 /* Most dirfd implementations have problems when passed NULL. */
6570 #elif defined(HAS_DIR_DD_FD)
6573 Perl_die(aTHX_ PL_no_func, "dirfd");
6580 Perl_get_re_arg(pTHX_ SV *sv) {
6586 sv = MUTABLE_SV(SvRV(sv));
6587 if (SvTYPE(sv) == SVt_REGEXP)
6588 return (REGEXP*) sv;
6596 * c-indentation-style: bsd
6598 * indent-tabs-mode: t
6601 * ex: set ts=8 sts=4 sw=4 noet: