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 */
46 # include <sys/select.h>
52 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
53 # define FD_CLOEXEC 1 /* NeXT needs this */
56 /* NOTE: Do not call the next three routines directly. Use the macros
57 * in handy.h, so that we can easily redefine everything to do tracking of
58 * allocated hunks back to the original New to track down any memory leaks.
59 * XXX This advice seems to be widely ignored :-( --AD August 1996.
66 /* Can't use PerlIO to write as it allocates memory */
67 PerlLIO_write(PerlIO_fileno(Perl_error_log),
68 PL_no_mem, strlen(PL_no_mem));
70 NORETURN_FUNCTION_END;
73 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
74 # define ALWAYS_NEED_THX
77 /* paranoid version of system's malloc() */
80 Perl_safesysmalloc(MEM_SIZE size)
82 #ifdef ALWAYS_NEED_THX
88 PerlIO_printf(Perl_error_log,
89 "Allocation too large: %lx\n", size) FLUSH;
92 #endif /* HAS_64K_LIMIT */
93 #ifdef PERL_TRACK_MEMPOOL
97 if ((SSize_t)size < 0)
98 Perl_croak_nocontext("panic: malloc, size=%"UVuf, (UV) size);
100 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
101 PERL_ALLOC_CHECK(ptr);
103 #ifdef PERL_TRACK_MEMPOOL
104 struct perl_memory_debug_header *const header
105 = (struct perl_memory_debug_header *)ptr;
109 PoisonNew(((char *)ptr), size, char);
112 #ifdef PERL_TRACK_MEMPOOL
113 header->interpreter = aTHX;
114 /* Link us into the list. */
115 header->prev = &PL_memory_debug_header;
116 header->next = PL_memory_debug_header.next;
117 PL_memory_debug_header.next = header;
118 header->next->prev = header;
122 ptr = (Malloc_t)((char*)ptr+sTHX);
124 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
128 #ifndef ALWAYS_NEED_THX
134 return write_no_mem();
140 /* paranoid version of system's realloc() */
143 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
145 #ifdef ALWAYS_NEED_THX
149 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
150 Malloc_t PerlMem_realloc();
151 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
155 PerlIO_printf(Perl_error_log,
156 "Reallocation too large: %lx\n", size) FLUSH;
159 #endif /* HAS_64K_LIMIT */
166 return safesysmalloc(size);
167 #ifdef PERL_TRACK_MEMPOOL
168 where = (Malloc_t)((char*)where-sTHX);
171 struct perl_memory_debug_header *const header
172 = (struct perl_memory_debug_header *)where;
174 if (header->interpreter != aTHX) {
175 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
176 header->interpreter, aTHX);
178 assert(header->next->prev == header);
179 assert(header->prev->next == header);
181 if (header->size > size) {
182 const MEM_SIZE freed_up = header->size - size;
183 char *start_of_freed = ((char *)where) + size;
184 PoisonFree(start_of_freed, freed_up, char);
191 if ((SSize_t)size < 0)
192 Perl_croak_nocontext("panic: realloc, size=%"UVuf, (UV)size);
194 ptr = (Malloc_t)PerlMem_realloc(where,size);
195 PERL_ALLOC_CHECK(ptr);
197 /* MUST do this fixup first, before doing ANYTHING else, as anything else
198 might allocate memory/free/move memory, and until we do the fixup, it
199 may well be chasing (and writing to) free memory. */
200 #ifdef PERL_TRACK_MEMPOOL
202 struct perl_memory_debug_header *const header
203 = (struct perl_memory_debug_header *)ptr;
206 if (header->size < size) {
207 const MEM_SIZE fresh = size - header->size;
208 char *start_of_fresh = ((char *)ptr) + size;
209 PoisonNew(start_of_fresh, fresh, char);
213 header->next->prev = header;
214 header->prev->next = header;
216 ptr = (Malloc_t)((char*)ptr+sTHX);
220 /* In particular, must do that fixup above before logging anything via
221 *printf(), as it can reallocate memory, which can cause SEGVs. */
223 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
224 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
231 #ifndef ALWAYS_NEED_THX
237 return write_no_mem();
243 /* safe version of system's free() */
246 Perl_safesysfree(Malloc_t where)
248 #ifdef ALWAYS_NEED_THX
253 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
255 #ifdef PERL_TRACK_MEMPOOL
256 where = (Malloc_t)((char*)where-sTHX);
258 struct perl_memory_debug_header *const header
259 = (struct perl_memory_debug_header *)where;
261 if (header->interpreter != aTHX) {
262 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
263 header->interpreter, aTHX);
266 Perl_croak_nocontext("panic: duplicate free");
269 Perl_croak_nocontext("panic: bad free, header->next==NULL");
270 if (header->next->prev != header || header->prev->next != header) {
271 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
272 "header=%p, ->prev->next=%p",
273 header->next->prev, header,
276 /* Unlink us from the chain. */
277 header->next->prev = header->prev;
278 header->prev->next = header->next;
280 PoisonNew(where, header->size, char);
282 /* Trigger the duplicate free warning. */
290 /* safe version of system's calloc() */
293 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
295 #ifdef ALWAYS_NEED_THX
299 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
300 MEM_SIZE total_size = 0;
303 /* Even though calloc() for zero bytes is strange, be robust. */
304 if (size && (count <= MEM_SIZE_MAX / size)) {
305 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
306 total_size = size * count;
310 Perl_croak_nocontext("%s", PL_memory_wrap);
311 #ifdef PERL_TRACK_MEMPOOL
312 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
315 Perl_croak_nocontext("%s", PL_memory_wrap);
318 if (total_size > 0xffff) {
319 PerlIO_printf(Perl_error_log,
320 "Allocation too large: %lx\n", total_size) FLUSH;
323 #endif /* HAS_64K_LIMIT */
325 if ((SSize_t)size < 0 || (SSize_t)count < 0)
326 Perl_croak_nocontext("panic: calloc, size=%"UVuf", count=%"UVuf,
327 (UV)size, (UV)count);
329 #ifdef PERL_TRACK_MEMPOOL
330 /* Have to use malloc() because we've added some space for our tracking
332 /* malloc(0) is non-portable. */
333 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
335 /* Use calloc() because it might save a memset() if the memory is fresh
336 and clean from the OS. */
338 ptr = (Malloc_t)PerlMem_calloc(count, size);
339 else /* calloc(0) is non-portable. */
340 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
342 PERL_ALLOC_CHECK(ptr);
343 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));
345 #ifdef PERL_TRACK_MEMPOOL
347 struct perl_memory_debug_header *const header
348 = (struct perl_memory_debug_header *)ptr;
350 memset((void*)ptr, 0, total_size);
351 header->interpreter = aTHX;
352 /* Link us into the list. */
353 header->prev = &PL_memory_debug_header;
354 header->next = PL_memory_debug_header.next;
355 PL_memory_debug_header.next = header;
356 header->next->prev = header;
358 header->size = total_size;
360 ptr = (Malloc_t)((char*)ptr+sTHX);
366 #ifndef ALWAYS_NEED_THX
371 return write_no_mem();
375 /* These must be defined when not using Perl's malloc for binary
380 Malloc_t Perl_malloc (MEM_SIZE nbytes)
383 return (Malloc_t)PerlMem_malloc(nbytes);
386 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
389 return (Malloc_t)PerlMem_calloc(elements, size);
392 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
395 return (Malloc_t)PerlMem_realloc(where, nbytes);
398 Free_t Perl_mfree (Malloc_t where)
406 /* copy a string up to some (non-backslashed) delimiter, if any */
409 Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
413 PERL_ARGS_ASSERT_DELIMCPY;
415 for (tolen = 0; from < fromend; from++, tolen++) {
417 if (from[1] != delim) {
424 else if (*from == delim)
435 /* return ptr to little string in big string, NULL if not found */
436 /* This routine was donated by Corey Satten. */
439 Perl_instr(register const char *big, register const char *little)
443 PERL_ARGS_ASSERT_INSTR;
454 for (x=big,s=little; *s; /**/ ) {
465 return (char*)(big-1);
470 /* same as instr but allow embedded nulls. The end pointers point to 1 beyond
471 * the final character desired to be checked */
474 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
476 PERL_ARGS_ASSERT_NINSTR;
480 const char first = *little;
482 bigend -= lend - little++;
484 while (big <= bigend) {
485 if (*big++ == first) {
486 for (x=big,s=little; s < lend; x++,s++) {
490 return (char*)(big-1);
497 /* reverse of the above--find last substring */
500 Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
503 const I32 first = *little;
504 const char * const littleend = lend;
506 PERL_ARGS_ASSERT_RNINSTR;
508 if (little >= littleend)
509 return (char*)bigend;
511 big = bigend - (littleend - little++);
512 while (big >= bigbeg) {
516 for (x=big+2,s=little; s < littleend; /**/ ) {
525 return (char*)(big+1);
530 /* As a space optimization, we do not compile tables for strings of length
531 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
532 special-cased in fbm_instr().
534 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
537 =head1 Miscellaneous Functions
539 =for apidoc fbm_compile
541 Analyses the string in order to make fast searches on it using fbm_instr()
542 -- the Boyer-Moore algorithm.
548 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
558 PERL_ARGS_ASSERT_FBM_COMPILE;
560 if (isGV_with_GP(sv))
566 if (flags & FBMcf_TAIL) {
567 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
568 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
569 if (mg && mg->mg_len >= 0)
572 s = (U8*)SvPV_force_mutable(sv, len);
573 if (len == 0) /* TAIL might be on a zero-length string. */
575 SvUPGRADE(sv, SVt_PVMG);
580 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
581 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
582 to call SvVALID_off() if the scalar was assigned to.
584 The comment itself (and "deeper magic" below) date back to
585 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
587 where the magic (presumably) was that the scalar had a BM table hidden
590 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
591 the table instead of the previous (somewhat hacky) approach of co-opting
592 the string buffer and storing it after the string. */
594 assert(!mg_find(sv, PERL_MAGIC_bm));
595 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
599 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
601 const U8 mlen = (len>255) ? 255 : (U8)len;
602 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
605 Newx(table, 256, U8);
606 memset((void*)table, mlen, 256);
607 mg->mg_ptr = (char *)table;
610 s += len - 1; /* last char */
613 if (table[*s] == mlen)
619 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
620 for (i = 0; i < len; i++) {
621 if (PL_freq[s[i]] < frequency) {
623 frequency = PL_freq[s[i]];
626 BmRARE(sv) = s[rarest];
627 BmPREVIOUS(sv) = rarest;
628 BmUSEFUL(sv) = 100; /* Initial value */
629 if (flags & FBMcf_TAIL)
631 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
632 BmRARE(sv), BmPREVIOUS(sv)));
635 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
636 /* If SvTAIL is actually due to \Z or \z, this gives false positives
640 =for apidoc fbm_instr
642 Returns the location of the SV in the string delimited by C<big> and
643 C<bigend>. It returns C<NULL> if the string can't be found. The C<sv>
644 does not have to be fbm_compiled, but the search will not be as fast
651 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
655 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
656 STRLEN littlelen = l;
657 const I32 multiline = flags & FBMrf_MULTILINE;
659 PERL_ARGS_ASSERT_FBM_INSTR;
661 if ((STRLEN)(bigend - big) < littlelen) {
662 if ( SvTAIL(littlestr)
663 && ((STRLEN)(bigend - big) == littlelen - 1)
665 || (*big == *little &&
666 memEQ((char *)big, (char *)little, littlelen - 1))))
671 switch (littlelen) { /* Special cases for 0, 1 and 2 */
673 return (char*)big; /* Cannot be SvTAIL! */
675 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
676 /* Know that bigend != big. */
677 if (bigend[-1] == '\n')
678 return (char *)(bigend - 1);
679 return (char *) bigend;
687 if (SvTAIL(littlestr))
688 return (char *) bigend;
691 if (SvTAIL(littlestr) && !multiline) {
692 if (bigend[-1] == '\n' && bigend[-2] == *little)
693 return (char*)bigend - 2;
694 if (bigend[-1] == *little)
695 return (char*)bigend - 1;
699 /* This should be better than FBM if c1 == c2, and almost
700 as good otherwise: maybe better since we do less indirection.
701 And we save a lot of memory by caching no table. */
702 const unsigned char c1 = little[0];
703 const unsigned char c2 = little[1];
708 while (s <= bigend) {
718 goto check_1char_anchor;
729 goto check_1char_anchor;
732 while (s <= bigend) {
737 goto check_1char_anchor;
746 check_1char_anchor: /* One char and anchor! */
747 if (SvTAIL(littlestr) && (*bigend == *little))
748 return (char *)bigend; /* bigend is already decremented. */
751 break; /* Only lengths 0 1 and 2 have special-case code. */
754 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
755 s = bigend - littlelen;
756 if (s >= big && bigend[-1] == '\n' && *s == *little
757 /* Automatically of length > 2 */
758 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
760 return (char*)s; /* how sweet it is */
763 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
765 return (char*)s + 1; /* how sweet it is */
769 if (!SvVALID(littlestr)) {
770 char * const b = ninstr((char*)big,(char*)bigend,
771 (char*)little, (char*)little + littlelen);
773 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
774 /* Chop \n from littlestr: */
775 s = bigend - littlelen + 1;
777 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
787 if (littlelen > (STRLEN)(bigend - big))
791 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
792 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
793 const unsigned char *oldlittle;
795 --littlelen; /* Last char found by table lookup */
798 little += littlelen; /* last char */
804 if ((tmp = table[*s])) {
805 if ((s += tmp) < bigend)
809 else { /* less expensive than calling strncmp() */
810 unsigned char * const olds = s;
815 if (*--s == *--little)
817 s = olds + 1; /* here we pay the price for failure */
819 if (s < bigend) /* fake up continue to outer loop */
829 && memEQ((char *)(bigend - littlelen),
830 (char *)(oldlittle - littlelen), littlelen) )
831 return (char*)bigend - littlelen;
837 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
840 PERL_ARGS_ASSERT_SCREAMINSTR;
841 PERL_UNUSED_ARG(bigstr);
842 PERL_UNUSED_ARG(littlestr);
843 PERL_UNUSED_ARG(start_shift);
844 PERL_UNUSED_ARG(end_shift);
845 PERL_UNUSED_ARG(old_posp);
846 PERL_UNUSED_ARG(last);
848 /* This function must only ever be called on a scalar with study magic,
849 but those do not happen any more. */
850 Perl_croak(aTHX_ "panic: screaminstr");
857 Returns true if the leading len bytes of the strings s1 and s2 are the same
858 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
859 match themselves and their opposite case counterparts. Non-cased and non-ASCII
860 range bytes match only themselves.
867 Perl_foldEQ(const char *s1, const char *s2, register I32 len)
869 const U8 *a = (const U8 *)s1;
870 const U8 *b = (const U8 *)s2;
872 PERL_ARGS_ASSERT_FOLDEQ;
875 if (*a != *b && *a != PL_fold[*b])
882 Perl_foldEQ_latin1(const char *s1, const char *s2, register I32 len)
884 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
885 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
886 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
887 * does it check that the strings each have at least 'len' characters */
889 const U8 *a = (const U8 *)s1;
890 const U8 *b = (const U8 *)s2;
892 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
895 if (*a != *b && *a != PL_fold_latin1[*b]) {
904 =for apidoc foldEQ_locale
906 Returns true if the leading len bytes of the strings s1 and s2 are the same
907 case-insensitively in the current locale; false otherwise.
913 Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
916 const U8 *a = (const U8 *)s1;
917 const U8 *b = (const U8 *)s2;
919 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
922 if (*a != *b && *a != PL_fold_locale[*b])
929 /* copy a string to a safe spot */
932 =head1 Memory Management
936 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
937 string which is a duplicate of C<pv>. The size of the string is
938 determined by C<strlen()>. The memory allocated for the new string can
939 be freed with the C<Safefree()> function.
945 Perl_savepv(pTHX_ const char *pv)
952 const STRLEN pvlen = strlen(pv)+1;
953 Newx(newaddr, pvlen, char);
954 return (char*)memcpy(newaddr, pv, pvlen);
958 /* same thing but with a known length */
963 Perl's version of what C<strndup()> would be if it existed. Returns a
964 pointer to a newly allocated string which is a duplicate of the first
965 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
966 the new string can be freed with the C<Safefree()> function.
972 Perl_savepvn(pTHX_ const char *pv, register I32 len)
977 Newx(newaddr,len+1,char);
978 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
980 /* might not be null terminated */
982 return (char *) CopyD(pv,newaddr,len,char);
985 return (char *) ZeroD(newaddr,len+1,char);
990 =for apidoc savesharedpv
992 A version of C<savepv()> which allocates the duplicate string in memory
993 which is shared between threads.
998 Perl_savesharedpv(pTHX_ const char *pv)
1005 pvlen = strlen(pv)+1;
1006 newaddr = (char*)PerlMemShared_malloc(pvlen);
1008 return write_no_mem();
1010 return (char*)memcpy(newaddr, pv, pvlen);
1014 =for apidoc savesharedpvn
1016 A version of C<savepvn()> which allocates the duplicate string in memory
1017 which is shared between threads. (With the specific difference that a NULL
1018 pointer is not acceptable)
1023 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1025 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1027 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1030 return write_no_mem();
1032 newaddr[len] = '\0';
1033 return (char*)memcpy(newaddr, pv, len);
1037 =for apidoc savesvpv
1039 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1040 the passed in SV using C<SvPV()>
1046 Perl_savesvpv(pTHX_ SV *sv)
1049 const char * const pv = SvPV_const(sv, len);
1052 PERL_ARGS_ASSERT_SAVESVPV;
1055 Newx(newaddr,len,char);
1056 return (char *) CopyD(pv,newaddr,len,char);
1060 =for apidoc savesharedsvpv
1062 A version of C<savesharedpv()> which allocates the duplicate string in
1063 memory which is shared between threads.
1069 Perl_savesharedsvpv(pTHX_ SV *sv)
1072 const char * const pv = SvPV_const(sv, len);
1074 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1076 return savesharedpvn(pv, len);
1079 /* the SV for Perl_form() and mess() is not kept in an arena */
1088 if (PL_phase != PERL_PHASE_DESTRUCT)
1089 return newSVpvs_flags("", SVs_TEMP);
1094 /* Create as PVMG now, to avoid any upgrading later */
1096 Newxz(any, 1, XPVMG);
1097 SvFLAGS(sv) = SVt_PVMG;
1098 SvANY(sv) = (void*)any;
1100 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1105 #if defined(PERL_IMPLICIT_CONTEXT)
1107 Perl_form_nocontext(const char* pat, ...)
1112 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1113 va_start(args, pat);
1114 retval = vform(pat, &args);
1118 #endif /* PERL_IMPLICIT_CONTEXT */
1121 =head1 Miscellaneous Functions
1124 Takes a sprintf-style format pattern and conventional
1125 (non-SV) arguments and returns the formatted string.
1127 (char *) Perl_form(pTHX_ const char* pat, ...)
1129 can be used any place a string (char *) is required:
1131 char * s = Perl_form("%d.%d",major,minor);
1133 Uses a single private buffer so if you want to format several strings you
1134 must explicitly copy the earlier strings away (and free the copies when you
1141 Perl_form(pTHX_ const char* pat, ...)
1145 PERL_ARGS_ASSERT_FORM;
1146 va_start(args, pat);
1147 retval = vform(pat, &args);
1153 Perl_vform(pTHX_ const char *pat, va_list *args)
1155 SV * const sv = mess_alloc();
1156 PERL_ARGS_ASSERT_VFORM;
1157 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1162 =for apidoc Am|SV *|mess|const char *pat|...
1164 Take a sprintf-style format pattern and argument list. These are used to
1165 generate a string message. If the message does not end with a newline,
1166 then it will be extended with some indication of the current location
1167 in the code, as described for L</mess_sv>.
1169 Normally, the resulting message is returned in a new mortal SV.
1170 During global destruction a single SV may be shared between uses of
1176 #if defined(PERL_IMPLICIT_CONTEXT)
1178 Perl_mess_nocontext(const char *pat, ...)
1183 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1184 va_start(args, pat);
1185 retval = vmess(pat, &args);
1189 #endif /* PERL_IMPLICIT_CONTEXT */
1192 Perl_mess(pTHX_ const char *pat, ...)
1196 PERL_ARGS_ASSERT_MESS;
1197 va_start(args, pat);
1198 retval = vmess(pat, &args);
1204 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1207 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1209 PERL_ARGS_ASSERT_CLOSEST_COP;
1211 if (!o || o == PL_op)
1214 if (o->op_flags & OPf_KIDS) {
1216 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1219 /* If the OP_NEXTSTATE has been optimised away we can still use it
1220 * the get the file and line number. */
1222 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1223 cop = (const COP *)kid;
1225 /* Keep searching, and return when we've found something. */
1227 new_cop = closest_cop(cop, kid);
1233 /* Nothing found. */
1239 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1241 Expands a message, intended for the user, to include an indication of
1242 the current location in the code, if the message does not already appear
1245 C<basemsg> is the initial message or object. If it is a reference, it
1246 will be used as-is and will be the result of this function. Otherwise it
1247 is used as a string, and if it already ends with a newline, it is taken
1248 to be complete, and the result of this function will be the same string.
1249 If the message does not end with a newline, then a segment such as C<at
1250 foo.pl line 37> will be appended, and possibly other clauses indicating
1251 the current state of execution. The resulting message will end with a
1254 Normally, the resulting message is returned in a new mortal SV.
1255 During global destruction a single SV may be shared between uses of this
1256 function. If C<consume> is true, then the function is permitted (but not
1257 required) to modify and return C<basemsg> instead of allocating a new SV.
1263 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1268 PERL_ARGS_ASSERT_MESS_SV;
1270 if (SvROK(basemsg)) {
1276 sv_setsv(sv, basemsg);
1281 if (SvPOK(basemsg) && consume) {
1286 sv_copypv(sv, basemsg);
1289 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1291 * Try and find the file and line for PL_op. This will usually be
1292 * PL_curcop, but it might be a cop that has been optimised away. We
1293 * can try to find such a cop by searching through the optree starting
1294 * from the sibling of PL_curcop.
1297 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1302 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1303 OutCopFILE(cop), (IV)CopLINE(cop));
1304 /* Seems that GvIO() can be untrustworthy during global destruction. */
1305 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1306 && IoLINES(GvIOp(PL_last_in_gv)))
1309 const bool line_mode = (RsSIMPLE(PL_rs) &&
1310 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1311 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1312 SVfARG(PL_last_in_gv == PL_argvgv
1314 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1315 line_mode ? "line" : "chunk",
1316 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1318 if (PL_phase == PERL_PHASE_DESTRUCT)
1319 sv_catpvs(sv, " during global destruction");
1320 sv_catpvs(sv, ".\n");
1326 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1328 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1329 argument list. These are used to generate a string message. If the
1330 message does not end with a newline, then it will be extended with
1331 some indication of the current location in the code, as described for
1334 Normally, the resulting message is returned in a new mortal SV.
1335 During global destruction a single SV may be shared between uses of
1342 Perl_vmess(pTHX_ const char *pat, va_list *args)
1345 SV * const sv = mess_alloc();
1347 PERL_ARGS_ASSERT_VMESS;
1349 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1350 return mess_sv(sv, 1);
1354 Perl_write_to_stderr(pTHX_ SV* msv)
1360 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1362 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1363 && (io = GvIO(PL_stderrgv))
1364 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1365 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1366 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1369 /* SFIO can really mess with your errno */
1372 PerlIO * const serr = Perl_error_log;
1374 do_print(msv, serr);
1375 (void)PerlIO_flush(serr);
1383 =head1 Warning and Dieing
1386 /* Common code used in dieing and warning */
1389 S_with_queued_errors(pTHX_ SV *ex)
1391 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1392 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1393 sv_catsv(PL_errors, ex);
1394 ex = sv_mortalcopy(PL_errors);
1395 SvCUR_set(PL_errors, 0);
1401 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1407 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1408 /* sv_2cv might call Perl_croak() or Perl_warner() */
1409 SV * const oldhook = *hook;
1417 cv = sv_2cv(oldhook, &stash, &gv, 0);
1419 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1429 exarg = newSVsv(ex);
1430 SvREADONLY_on(exarg);
1433 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1437 call_sv(MUTABLE_SV(cv), G_DISCARD);
1446 =for apidoc Am|OP *|die_sv|SV *baseex
1448 Behaves the same as L</croak_sv>, except for the return type.
1449 It should be used only where the C<OP *> return type is required.
1450 The function never actually returns.
1456 Perl_die_sv(pTHX_ SV *baseex)
1458 PERL_ARGS_ASSERT_DIE_SV;
1460 assert(0); /* NOTREACHED */
1465 =for apidoc Am|OP *|die|const char *pat|...
1467 Behaves the same as L</croak>, except for the return type.
1468 It should be used only where the C<OP *> return type is required.
1469 The function never actually returns.
1474 #if defined(PERL_IMPLICIT_CONTEXT)
1476 Perl_die_nocontext(const char* pat, ...)
1480 va_start(args, pat);
1482 assert(0); /* NOTREACHED */
1486 #endif /* PERL_IMPLICIT_CONTEXT */
1489 Perl_die(pTHX_ const char* pat, ...)
1492 va_start(args, pat);
1494 assert(0); /* NOTREACHED */
1500 =for apidoc Am|void|croak_sv|SV *baseex
1502 This is an XS interface to Perl's C<die> function.
1504 C<baseex> is the error message or object. If it is a reference, it
1505 will be used as-is. Otherwise it is used as a string, and if it does
1506 not end with a newline then it will be extended with some indication of
1507 the current location in the code, as described for L</mess_sv>.
1509 The error message or object will be used as an exception, by default
1510 returning control to the nearest enclosing C<eval>, but subject to
1511 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1512 function never returns normally.
1514 To die with a simple string message, the L</croak> function may be
1521 Perl_croak_sv(pTHX_ SV *baseex)
1523 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1524 PERL_ARGS_ASSERT_CROAK_SV;
1525 invoke_exception_hook(ex, FALSE);
1530 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1532 This is an XS interface to Perl's C<die> function.
1534 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1535 argument list. These are used to generate a string message. If the
1536 message does not end with a newline, then it will be extended with
1537 some indication of the current location in the code, as described for
1540 The error message will be used as an exception, by default
1541 returning control to the nearest enclosing C<eval>, but subject to
1542 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1543 function never returns normally.
1545 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1546 (C<$@>) will be used as an error message or object instead of building an
1547 error message from arguments. If you want to throw a non-string object,
1548 or build an error message in an SV yourself, it is preferable to use
1549 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1555 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1557 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1558 invoke_exception_hook(ex, FALSE);
1563 =for apidoc Am|void|croak|const char *pat|...
1565 This is an XS interface to Perl's C<die> function.
1567 Take a sprintf-style format pattern and argument list. These are used to
1568 generate a string message. If the message does not end with a newline,
1569 then it will be extended with some indication of the current location
1570 in the code, as described for L</mess_sv>.
1572 The error message will be used as an exception, by default
1573 returning control to the nearest enclosing C<eval>, but subject to
1574 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1575 function never returns normally.
1577 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1578 (C<$@>) will be used as an error message or object instead of building an
1579 error message from arguments. If you want to throw a non-string object,
1580 or build an error message in an SV yourself, it is preferable to use
1581 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1586 #if defined(PERL_IMPLICIT_CONTEXT)
1588 Perl_croak_nocontext(const char *pat, ...)
1592 va_start(args, pat);
1594 assert(0); /* NOTREACHED */
1597 #endif /* PERL_IMPLICIT_CONTEXT */
1600 Perl_croak(pTHX_ const char *pat, ...)
1603 va_start(args, pat);
1605 assert(0); /* NOTREACHED */
1610 =for apidoc Am|void|croak_no_modify
1612 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1613 terser object code than using C<Perl_croak>. Less code used on exception code
1614 paths reduces CPU cache pressure.
1620 Perl_croak_no_modify(pTHX)
1622 Perl_croak(aTHX_ "%s", PL_no_modify);
1626 =for apidoc Am|void|warn_sv|SV *baseex
1628 This is an XS interface to Perl's C<warn> function.
1630 C<baseex> is the error message or object. If it is a reference, it
1631 will be used as-is. Otherwise it is used as a string, and if it does
1632 not end with a newline then it will be extended with some indication of
1633 the current location in the code, as described for L</mess_sv>.
1635 The error message or object will by default be written to standard error,
1636 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1638 To warn with a simple string message, the L</warn> function may be
1645 Perl_warn_sv(pTHX_ SV *baseex)
1647 SV *ex = mess_sv(baseex, 0);
1648 PERL_ARGS_ASSERT_WARN_SV;
1649 if (!invoke_exception_hook(ex, TRUE))
1650 write_to_stderr(ex);
1654 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1656 This is an XS interface to Perl's C<warn> function.
1658 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1659 argument list. These are used to generate a string message. If the
1660 message does not end with a newline, then it will be extended with
1661 some indication of the current location in the code, as described for
1664 The error message or object will by default be written to standard error,
1665 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1667 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1673 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1675 SV *ex = vmess(pat, args);
1676 PERL_ARGS_ASSERT_VWARN;
1677 if (!invoke_exception_hook(ex, TRUE))
1678 write_to_stderr(ex);
1682 =for apidoc Am|void|warn|const char *pat|...
1684 This is an XS interface to Perl's C<warn> function.
1686 Take a sprintf-style format pattern and argument list. These are used to
1687 generate a string message. If the message does not end with a newline,
1688 then it will be extended with some indication of the current location
1689 in the code, as described for L</mess_sv>.
1691 The error message or object will by default be written to standard error,
1692 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1694 Unlike with L</croak>, C<pat> is not permitted to be null.
1699 #if defined(PERL_IMPLICIT_CONTEXT)
1701 Perl_warn_nocontext(const char *pat, ...)
1705 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1706 va_start(args, pat);
1710 #endif /* PERL_IMPLICIT_CONTEXT */
1713 Perl_warn(pTHX_ const char *pat, ...)
1716 PERL_ARGS_ASSERT_WARN;
1717 va_start(args, pat);
1722 #if defined(PERL_IMPLICIT_CONTEXT)
1724 Perl_warner_nocontext(U32 err, const char *pat, ...)
1728 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1729 va_start(args, pat);
1730 vwarner(err, pat, &args);
1733 #endif /* PERL_IMPLICIT_CONTEXT */
1736 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1738 PERL_ARGS_ASSERT_CK_WARNER_D;
1740 if (Perl_ckwarn_d(aTHX_ err)) {
1742 va_start(args, pat);
1743 vwarner(err, pat, &args);
1749 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1751 PERL_ARGS_ASSERT_CK_WARNER;
1753 if (Perl_ckwarn(aTHX_ err)) {
1755 va_start(args, pat);
1756 vwarner(err, pat, &args);
1762 Perl_warner(pTHX_ U32 err, const char* pat,...)
1765 PERL_ARGS_ASSERT_WARNER;
1766 va_start(args, pat);
1767 vwarner(err, pat, &args);
1772 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1775 PERL_ARGS_ASSERT_VWARNER;
1776 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1777 SV * const msv = vmess(pat, args);
1779 invoke_exception_hook(msv, FALSE);
1783 Perl_vwarn(aTHX_ pat, args);
1787 /* implements the ckWARN? macros */
1790 Perl_ckwarn(pTHX_ U32 w)
1793 /* If lexical warnings have not been set, use $^W. */
1795 return PL_dowarn & G_WARN_ON;
1797 return ckwarn_common(w);
1800 /* implements the ckWARN?_d macro */
1803 Perl_ckwarn_d(pTHX_ U32 w)
1806 /* If lexical warnings have not been set then default classes warn. */
1810 return ckwarn_common(w);
1814 S_ckwarn_common(pTHX_ U32 w)
1816 if (PL_curcop->cop_warnings == pWARN_ALL)
1819 if (PL_curcop->cop_warnings == pWARN_NONE)
1822 /* Check the assumption that at least the first slot is non-zero. */
1823 assert(unpackWARN1(w));
1825 /* Check the assumption that it is valid to stop as soon as a zero slot is
1827 if (!unpackWARN2(w)) {
1828 assert(!unpackWARN3(w));
1829 assert(!unpackWARN4(w));
1830 } else if (!unpackWARN3(w)) {
1831 assert(!unpackWARN4(w));
1834 /* Right, dealt with all the special cases, which are implemented as non-
1835 pointers, so there is a pointer to a real warnings mask. */
1837 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1839 } while (w >>= WARNshift);
1844 /* Set buffer=NULL to get a new one. */
1846 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1848 const MEM_SIZE len_wanted =
1849 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
1850 PERL_UNUSED_CONTEXT;
1851 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1854 (specialWARN(buffer) ?
1855 PerlMemShared_malloc(len_wanted) :
1856 PerlMemShared_realloc(buffer, len_wanted));
1858 Copy(bits, (buffer + 1), size, char);
1859 if (size < WARNsize)
1860 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
1864 /* since we've already done strlen() for both nam and val
1865 * we can use that info to make things faster than
1866 * sprintf(s, "%s=%s", nam, val)
1868 #define my_setenv_format(s, nam, nlen, val, vlen) \
1869 Copy(nam, s, nlen, char); \
1871 Copy(val, s+(nlen+1), vlen, char); \
1872 *(s+(nlen+1+vlen)) = '\0'
1874 #ifdef USE_ENVIRON_ARRAY
1875 /* VMS' my_setenv() is in vms.c */
1876 #if !defined(WIN32) && !defined(NETWARE)
1878 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1882 /* only parent thread can modify process environment */
1883 if (PL_curinterp == aTHX)
1886 #ifndef PERL_USE_SAFE_PUTENV
1887 if (!PL_use_safe_putenv) {
1888 /* most putenv()s leak, so we manipulate environ directly */
1890 const I32 len = strlen(nam);
1893 /* where does it go? */
1894 for (i = 0; environ[i]; i++) {
1895 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1899 if (environ == PL_origenviron) { /* need we copy environment? */
1905 while (environ[max])
1907 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1908 for (j=0; j<max; j++) { /* copy environment */
1909 const int len = strlen(environ[j]);
1910 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1911 Copy(environ[j], tmpenv[j], len+1, char);
1914 environ = tmpenv; /* tell exec where it is now */
1917 safesysfree(environ[i]);
1918 while (environ[i]) {
1919 environ[i] = environ[i+1];
1924 if (!environ[i]) { /* does not exist yet */
1925 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1926 environ[i+1] = NULL; /* make sure it's null terminated */
1929 safesysfree(environ[i]);
1933 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1934 /* all that work just for this */
1935 my_setenv_format(environ[i], nam, nlen, val, vlen);
1938 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
1939 # if defined(HAS_UNSETENV)
1941 (void)unsetenv(nam);
1943 (void)setenv(nam, val, 1);
1945 # else /* ! HAS_UNSETENV */
1946 (void)setenv(nam, val, 1);
1947 # endif /* HAS_UNSETENV */
1949 # if defined(HAS_UNSETENV)
1951 (void)unsetenv(nam);
1953 const int nlen = strlen(nam);
1954 const int vlen = strlen(val);
1955 char * const new_env =
1956 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1957 my_setenv_format(new_env, nam, nlen, val, vlen);
1958 (void)putenv(new_env);
1960 # else /* ! HAS_UNSETENV */
1962 const int nlen = strlen(nam);
1968 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1969 /* all that work just for this */
1970 my_setenv_format(new_env, nam, nlen, val, vlen);
1971 (void)putenv(new_env);
1972 # endif /* HAS_UNSETENV */
1973 # endif /* __CYGWIN__ */
1974 #ifndef PERL_USE_SAFE_PUTENV
1980 #else /* WIN32 || NETWARE */
1983 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1987 const int nlen = strlen(nam);
1994 Newx(envstr, nlen+vlen+2, char);
1995 my_setenv_format(envstr, nam, nlen, val, vlen);
1996 (void)PerlEnv_putenv(envstr);
2000 #endif /* WIN32 || NETWARE */
2002 #endif /* !VMS && !EPOC*/
2004 #ifdef UNLINK_ALL_VERSIONS
2006 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2010 PERL_ARGS_ASSERT_UNLNK;
2012 while (PerlLIO_unlink(f) >= 0)
2014 return retries ? 0 : -1;
2018 /* this is a drop-in replacement for bcopy() */
2019 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2021 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2023 char * const retval = to;
2025 PERL_ARGS_ASSERT_MY_BCOPY;
2027 if (from - to >= 0) {
2035 *(--to) = *(--from);
2041 /* this is a drop-in replacement for memset() */
2044 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2046 char * const retval = loc;
2048 PERL_ARGS_ASSERT_MY_MEMSET;
2056 /* this is a drop-in replacement for bzero() */
2057 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2059 Perl_my_bzero(register char *loc, register I32 len)
2061 char * const retval = loc;
2063 PERL_ARGS_ASSERT_MY_BZERO;
2071 /* this is a drop-in replacement for memcmp() */
2072 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2074 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2076 const U8 *a = (const U8 *)s1;
2077 const U8 *b = (const U8 *)s2;
2080 PERL_ARGS_ASSERT_MY_MEMCMP;
2083 if ((tmp = *a++ - *b++))
2088 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2091 /* This vsprintf replacement should generally never get used, since
2092 vsprintf was available in both System V and BSD 2.11. (There may
2093 be some cross-compilation or embedded set-ups where it is needed,
2096 If you encounter a problem in this function, it's probably a symptom
2097 that Configure failed to detect your system's vprintf() function.
2098 See the section on "item vsprintf" in the INSTALL file.
2100 This version may compile on systems with BSD-ish <stdio.h>,
2101 but probably won't on others.
2104 #ifdef USE_CHAR_VSPRINTF
2109 vsprintf(char *dest, const char *pat, void *args)
2113 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2114 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2115 FILE_cnt(&fakebuf) = 32767;
2117 /* These probably won't compile -- If you really need
2118 this, you'll have to figure out some other method. */
2119 fakebuf._ptr = dest;
2120 fakebuf._cnt = 32767;
2125 fakebuf._flag = _IOWRT|_IOSTRG;
2126 _doprnt(pat, args, &fakebuf); /* what a kludge */
2127 #if defined(STDIO_PTR_LVALUE)
2128 *(FILE_ptr(&fakebuf)++) = '\0';
2130 /* PerlIO has probably #defined away fputc, but we want it here. */
2132 # undef fputc /* XXX Should really restore it later */
2134 (void)fputc('\0', &fakebuf);
2136 #ifdef USE_CHAR_VSPRINTF
2139 return 0; /* perl doesn't use return value */
2143 #endif /* HAS_VPRINTF */
2146 #if BYTEORDER != 0x4321
2148 Perl_my_swap(pTHX_ short s)
2150 #if (BYTEORDER & 1) == 0
2153 result = ((s & 255) << 8) + ((s >> 8) & 255);
2161 Perl_my_htonl(pTHX_ long l)
2165 char c[sizeof(long)];
2168 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2169 #if BYTEORDER == 0x12345678
2172 u.c[0] = (l >> 24) & 255;
2173 u.c[1] = (l >> 16) & 255;
2174 u.c[2] = (l >> 8) & 255;
2178 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2179 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2184 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2185 u.c[o & 0xf] = (l >> s) & 255;
2193 Perl_my_ntohl(pTHX_ long l)
2197 char c[sizeof(long)];
2200 #if BYTEORDER == 0x1234
2201 u.c[0] = (l >> 24) & 255;
2202 u.c[1] = (l >> 16) & 255;
2203 u.c[2] = (l >> 8) & 255;
2207 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2208 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2215 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2216 l |= (u.c[o & 0xf] & 255) << s;
2223 #endif /* BYTEORDER != 0x4321 */
2227 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2228 * If these functions are defined,
2229 * the BYTEORDER is neither 0x1234 nor 0x4321.
2230 * However, this is not assumed.
2234 #define HTOLE(name,type) \
2236 name (register type n) \
2240 char c[sizeof(type)]; \
2244 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2245 u.c[i] = (n >> s) & 0xFF; \
2250 #define LETOH(name,type) \
2252 name (register type n) \
2256 char c[sizeof(type)]; \
2262 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2263 n |= ((type)(u.c[i] & 0xFF)) << s; \
2269 * Big-endian byte order functions.
2272 #define HTOBE(name,type) \
2274 name (register type n) \
2278 char c[sizeof(type)]; \
2281 U32 s = 8*(sizeof(u.c)-1); \
2282 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2283 u.c[i] = (n >> s) & 0xFF; \
2288 #define BETOH(name,type) \
2290 name (register type n) \
2294 char c[sizeof(type)]; \
2297 U32 s = 8*(sizeof(u.c)-1); \
2300 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2301 n |= ((type)(u.c[i] & 0xFF)) << s; \
2307 * If we just can't do it...
2310 #define NOT_AVAIL(name,type) \
2312 name (register type n) \
2314 Perl_croak_nocontext(#name "() not available"); \
2315 return n; /* not reached */ \
2319 #if defined(HAS_HTOVS) && !defined(htovs)
2322 #if defined(HAS_HTOVL) && !defined(htovl)
2325 #if defined(HAS_VTOHS) && !defined(vtohs)
2328 #if defined(HAS_VTOHL) && !defined(vtohl)
2332 #ifdef PERL_NEED_MY_HTOLE16
2334 HTOLE(Perl_my_htole16,U16)
2336 NOT_AVAIL(Perl_my_htole16,U16)
2339 #ifdef PERL_NEED_MY_LETOH16
2341 LETOH(Perl_my_letoh16,U16)
2343 NOT_AVAIL(Perl_my_letoh16,U16)
2346 #ifdef PERL_NEED_MY_HTOBE16
2348 HTOBE(Perl_my_htobe16,U16)
2350 NOT_AVAIL(Perl_my_htobe16,U16)
2353 #ifdef PERL_NEED_MY_BETOH16
2355 BETOH(Perl_my_betoh16,U16)
2357 NOT_AVAIL(Perl_my_betoh16,U16)
2361 #ifdef PERL_NEED_MY_HTOLE32
2363 HTOLE(Perl_my_htole32,U32)
2365 NOT_AVAIL(Perl_my_htole32,U32)
2368 #ifdef PERL_NEED_MY_LETOH32
2370 LETOH(Perl_my_letoh32,U32)
2372 NOT_AVAIL(Perl_my_letoh32,U32)
2375 #ifdef PERL_NEED_MY_HTOBE32
2377 HTOBE(Perl_my_htobe32,U32)
2379 NOT_AVAIL(Perl_my_htobe32,U32)
2382 #ifdef PERL_NEED_MY_BETOH32
2384 BETOH(Perl_my_betoh32,U32)
2386 NOT_AVAIL(Perl_my_betoh32,U32)
2390 #ifdef PERL_NEED_MY_HTOLE64
2392 HTOLE(Perl_my_htole64,U64)
2394 NOT_AVAIL(Perl_my_htole64,U64)
2397 #ifdef PERL_NEED_MY_LETOH64
2399 LETOH(Perl_my_letoh64,U64)
2401 NOT_AVAIL(Perl_my_letoh64,U64)
2404 #ifdef PERL_NEED_MY_HTOBE64
2406 HTOBE(Perl_my_htobe64,U64)
2408 NOT_AVAIL(Perl_my_htobe64,U64)
2411 #ifdef PERL_NEED_MY_BETOH64
2413 BETOH(Perl_my_betoh64,U64)
2415 NOT_AVAIL(Perl_my_betoh64,U64)
2419 #ifdef PERL_NEED_MY_HTOLES
2420 HTOLE(Perl_my_htoles,short)
2422 #ifdef PERL_NEED_MY_LETOHS
2423 LETOH(Perl_my_letohs,short)
2425 #ifdef PERL_NEED_MY_HTOBES
2426 HTOBE(Perl_my_htobes,short)
2428 #ifdef PERL_NEED_MY_BETOHS
2429 BETOH(Perl_my_betohs,short)
2432 #ifdef PERL_NEED_MY_HTOLEI
2433 HTOLE(Perl_my_htolei,int)
2435 #ifdef PERL_NEED_MY_LETOHI
2436 LETOH(Perl_my_letohi,int)
2438 #ifdef PERL_NEED_MY_HTOBEI
2439 HTOBE(Perl_my_htobei,int)
2441 #ifdef PERL_NEED_MY_BETOHI
2442 BETOH(Perl_my_betohi,int)
2445 #ifdef PERL_NEED_MY_HTOLEL
2446 HTOLE(Perl_my_htolel,long)
2448 #ifdef PERL_NEED_MY_LETOHL
2449 LETOH(Perl_my_letohl,long)
2451 #ifdef PERL_NEED_MY_HTOBEL
2452 HTOBE(Perl_my_htobel,long)
2454 #ifdef PERL_NEED_MY_BETOHL
2455 BETOH(Perl_my_betohl,long)
2459 Perl_my_swabn(void *ptr, int n)
2461 char *s = (char *)ptr;
2462 char *e = s + (n-1);
2465 PERL_ARGS_ASSERT_MY_SWABN;
2467 for (n /= 2; n > 0; s++, e--, n--) {
2475 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2477 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2486 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2488 PERL_FLUSHALL_FOR_CHILD;
2489 This = (*mode == 'w');
2493 taint_proper("Insecure %s%s", "EXEC");
2495 if (PerlProc_pipe(p) < 0)
2497 /* Try for another pipe pair for error return */
2498 if (PerlProc_pipe(pp) >= 0)
2500 while ((pid = PerlProc_fork()) < 0) {
2501 if (errno != EAGAIN) {
2502 PerlLIO_close(p[This]);
2503 PerlLIO_close(p[that]);
2505 PerlLIO_close(pp[0]);
2506 PerlLIO_close(pp[1]);
2510 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2519 /* Close parent's end of error status pipe (if any) */
2521 PerlLIO_close(pp[0]);
2522 #if defined(HAS_FCNTL) && defined(F_SETFD)
2523 /* Close error pipe automatically if exec works */
2524 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2527 /* Now dup our end of _the_ pipe to right position */
2528 if (p[THIS] != (*mode == 'r')) {
2529 PerlLIO_dup2(p[THIS], *mode == 'r');
2530 PerlLIO_close(p[THIS]);
2531 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2532 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2535 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2536 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2537 /* No automatic close - do it by hand */
2544 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2550 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2556 do_execfree(); /* free any memory malloced by child on fork */
2558 PerlLIO_close(pp[1]);
2559 /* Keep the lower of the two fd numbers */
2560 if (p[that] < p[This]) {
2561 PerlLIO_dup2(p[This], p[that]);
2562 PerlLIO_close(p[This]);
2566 PerlLIO_close(p[that]); /* close child's end of pipe */
2568 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2569 SvUPGRADE(sv,SVt_IV);
2571 PL_forkprocess = pid;
2572 /* If we managed to get status pipe check for exec fail */
2573 if (did_pipes && pid > 0) {
2578 while (n < sizeof(int)) {
2579 n1 = PerlLIO_read(pp[0],
2580 (void*)(((char*)&errkid)+n),
2586 PerlLIO_close(pp[0]);
2588 if (n) { /* Error */
2590 PerlLIO_close(p[This]);
2591 if (n != sizeof(int))
2592 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2594 pid2 = wait4pid(pid, &status, 0);
2595 } while (pid2 == -1 && errno == EINTR);
2596 errno = errkid; /* Propagate errno from kid */
2601 PerlLIO_close(pp[0]);
2602 return PerlIO_fdopen(p[This], mode);
2604 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2605 return my_syspopen4(aTHX_ NULL, mode, n, args);
2607 Perl_croak(aTHX_ "List form of piped open not implemented");
2608 return (PerlIO *) NULL;
2613 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2614 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
2616 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2623 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2627 PERL_ARGS_ASSERT_MY_POPEN;
2629 PERL_FLUSHALL_FOR_CHILD;
2632 return my_syspopen(aTHX_ cmd,mode);
2635 This = (*mode == 'w');
2637 if (doexec && PL_tainting) {
2639 taint_proper("Insecure %s%s", "EXEC");
2641 if (PerlProc_pipe(p) < 0)
2643 if (doexec && PerlProc_pipe(pp) >= 0)
2645 while ((pid = PerlProc_fork()) < 0) {
2646 if (errno != EAGAIN) {
2647 PerlLIO_close(p[This]);
2648 PerlLIO_close(p[that]);
2650 PerlLIO_close(pp[0]);
2651 PerlLIO_close(pp[1]);
2654 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2657 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2667 PerlLIO_close(pp[0]);
2668 #if defined(HAS_FCNTL) && defined(F_SETFD)
2669 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2672 if (p[THIS] != (*mode == 'r')) {
2673 PerlLIO_dup2(p[THIS], *mode == 'r');
2674 PerlLIO_close(p[THIS]);
2675 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2676 PerlLIO_close(p[THAT]);
2679 PerlLIO_close(p[THAT]);
2682 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2689 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2694 /* may or may not use the shell */
2695 do_exec3(cmd, pp[1], did_pipes);
2698 #endif /* defined OS2 */
2700 #ifdef PERLIO_USING_CRLF
2701 /* Since we circumvent IO layers when we manipulate low-level
2702 filedescriptors directly, need to manually switch to the
2703 default, binary, low-level mode; see PerlIOBuf_open(). */
2704 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2707 #ifdef PERL_USES_PL_PIDSTATUS
2708 hv_clear(PL_pidstatus); /* we have no children */
2714 do_execfree(); /* free any memory malloced by child on vfork */
2716 PerlLIO_close(pp[1]);
2717 if (p[that] < p[This]) {
2718 PerlLIO_dup2(p[This], p[that]);
2719 PerlLIO_close(p[This]);
2723 PerlLIO_close(p[that]);
2725 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2726 SvUPGRADE(sv,SVt_IV);
2728 PL_forkprocess = pid;
2729 if (did_pipes && pid > 0) {
2734 while (n < sizeof(int)) {
2735 n1 = PerlLIO_read(pp[0],
2736 (void*)(((char*)&errkid)+n),
2742 PerlLIO_close(pp[0]);
2744 if (n) { /* Error */
2746 PerlLIO_close(p[This]);
2747 if (n != sizeof(int))
2748 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2750 pid2 = wait4pid(pid, &status, 0);
2751 } while (pid2 == -1 && errno == EINTR);
2752 errno = errkid; /* Propagate errno from kid */
2757 PerlLIO_close(pp[0]);
2758 return PerlIO_fdopen(p[This], mode);
2764 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2766 PERL_ARGS_ASSERT_MY_POPEN;
2767 PERL_FLUSHALL_FOR_CHILD;
2768 /* Call system's popen() to get a FILE *, then import it.
2769 used 0 for 2nd parameter to PerlIO_importFILE;
2772 return PerlIO_importFILE(popen(cmd, mode), 0);
2776 FILE *djgpp_popen();
2778 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2780 PERL_FLUSHALL_FOR_CHILD;
2781 /* Call system's popen() to get a FILE *, then import it.
2782 used 0 for 2nd parameter to PerlIO_importFILE;
2785 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2788 #if defined(__LIBCATAMOUNT__)
2790 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2798 #endif /* !DOSISH */
2800 /* this is called in parent before the fork() */
2802 Perl_atfork_lock(void)
2805 #if defined(USE_ITHREADS)
2806 /* locks must be held in locking order (if any) */
2808 MUTEX_LOCK(&PL_malloc_mutex);
2814 /* this is called in both parent and child after the fork() */
2816 Perl_atfork_unlock(void)
2819 #if defined(USE_ITHREADS)
2820 /* locks must be released in same order as in atfork_lock() */
2822 MUTEX_UNLOCK(&PL_malloc_mutex);
2831 #if defined(HAS_FORK)
2833 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2838 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2839 * handlers elsewhere in the code */
2844 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2845 Perl_croak_nocontext("fork() not available");
2847 #endif /* HAS_FORK */
2852 Perl_dump_fds(pTHX_ const char *const s)
2857 PERL_ARGS_ASSERT_DUMP_FDS;
2859 PerlIO_printf(Perl_debug_log,"%s", s);
2860 for (fd = 0; fd < 32; fd++) {
2861 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2862 PerlIO_printf(Perl_debug_log," %d",fd);
2864 PerlIO_printf(Perl_debug_log,"\n");
2867 #endif /* DUMP_FDS */
2871 dup2(int oldfd, int newfd)
2873 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2876 PerlLIO_close(newfd);
2877 return fcntl(oldfd, F_DUPFD, newfd);
2879 #define DUP2_MAX_FDS 256
2880 int fdtmp[DUP2_MAX_FDS];
2886 PerlLIO_close(newfd);
2887 /* good enough for low fd's... */
2888 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2889 if (fdx >= DUP2_MAX_FDS) {
2897 PerlLIO_close(fdtmp[--fdx]);
2904 #ifdef HAS_SIGACTION
2907 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2910 struct sigaction act, oact;
2913 /* only "parent" interpreter can diddle signals */
2914 if (PL_curinterp != aTHX)
2915 return (Sighandler_t) SIG_ERR;
2918 act.sa_handler = (void(*)(int))handler;
2919 sigemptyset(&act.sa_mask);
2922 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2923 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2925 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2926 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2927 act.sa_flags |= SA_NOCLDWAIT;
2929 if (sigaction(signo, &act, &oact) == -1)
2930 return (Sighandler_t) SIG_ERR;
2932 return (Sighandler_t) oact.sa_handler;
2936 Perl_rsignal_state(pTHX_ int signo)
2938 struct sigaction oact;
2939 PERL_UNUSED_CONTEXT;
2941 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2942 return (Sighandler_t) SIG_ERR;
2944 return (Sighandler_t) oact.sa_handler;
2948 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2951 struct sigaction act;
2953 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2956 /* only "parent" interpreter can diddle signals */
2957 if (PL_curinterp != aTHX)
2961 act.sa_handler = (void(*)(int))handler;
2962 sigemptyset(&act.sa_mask);
2965 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2966 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2968 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2969 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2970 act.sa_flags |= SA_NOCLDWAIT;
2972 return sigaction(signo, &act, save);
2976 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2980 /* only "parent" interpreter can diddle signals */
2981 if (PL_curinterp != aTHX)
2985 return sigaction(signo, save, (struct sigaction *)NULL);
2988 #else /* !HAS_SIGACTION */
2991 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2993 #if defined(USE_ITHREADS) && !defined(WIN32)
2994 /* only "parent" interpreter can diddle signals */
2995 if (PL_curinterp != aTHX)
2996 return (Sighandler_t) SIG_ERR;
2999 return PerlProc_signal(signo, handler);
3010 Perl_rsignal_state(pTHX_ int signo)
3013 Sighandler_t oldsig;
3015 #if defined(USE_ITHREADS) && !defined(WIN32)
3016 /* only "parent" interpreter can diddle signals */
3017 if (PL_curinterp != aTHX)
3018 return (Sighandler_t) SIG_ERR;
3022 oldsig = PerlProc_signal(signo, sig_trap);
3023 PerlProc_signal(signo, oldsig);
3025 PerlProc_kill(PerlProc_getpid(), signo);
3030 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3032 #if defined(USE_ITHREADS) && !defined(WIN32)
3033 /* only "parent" interpreter can diddle signals */
3034 if (PL_curinterp != aTHX)
3037 *save = PerlProc_signal(signo, handler);
3038 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3042 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3044 #if defined(USE_ITHREADS) && !defined(WIN32)
3045 /* only "parent" interpreter can diddle signals */
3046 if (PL_curinterp != aTHX)
3049 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3052 #endif /* !HAS_SIGACTION */
3053 #endif /* !PERL_MICRO */
3055 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3056 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
3058 Perl_my_pclose(pTHX_ PerlIO *ptr)
3061 Sigsave_t hstat, istat, qstat;
3068 const int fd = PerlIO_fileno(ptr);
3071 /* Find out whether the refcount is low enough for us to wait for the
3072 child proc without blocking. */
3073 const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
3075 const bool should_wait = 1;
3078 svp = av_fetch(PL_fdpid,fd,TRUE);
3079 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3081 *svp = &PL_sv_undef;
3083 if (pid == -1) { /* Opened by popen. */
3084 return my_syspclose(ptr);
3087 close_failed = (PerlIO_close(ptr) == EOF);
3090 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3091 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3092 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3094 if (should_wait) do {
3095 pid2 = wait4pid(pid, &status, 0);
3096 } while (pid2 == -1 && errno == EINTR);
3098 rsignal_restore(SIGHUP, &hstat);
3099 rsignal_restore(SIGINT, &istat);
3100 rsignal_restore(SIGQUIT, &qstat);
3108 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3113 #if defined(__LIBCATAMOUNT__)
3115 Perl_my_pclose(pTHX_ PerlIO *ptr)
3120 #endif /* !DOSISH */
3122 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3124 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3128 PERL_ARGS_ASSERT_WAIT4PID;
3131 #ifdef PERL_USES_PL_PIDSTATUS
3134 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3135 pid, rather than a string form. */
3136 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3137 if (svp && *svp != &PL_sv_undef) {
3138 *statusp = SvIVX(*svp);
3139 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3147 hv_iterinit(PL_pidstatus);
3148 if ((entry = hv_iternext(PL_pidstatus))) {
3149 SV * const sv = hv_iterval(PL_pidstatus,entry);
3151 const char * const spid = hv_iterkey(entry,&len);
3153 assert (len == sizeof(Pid_t));
3154 memcpy((char *)&pid, spid, len);
3155 *statusp = SvIVX(sv);
3156 /* The hash iterator is currently on this entry, so simply
3157 calling hv_delete would trigger the lazy delete, which on
3158 aggregate does more work, beacuse next call to hv_iterinit()
3159 would spot the flag, and have to call the delete routine,
3160 while in the meantime any new entries can't re-use that
3162 hv_iterinit(PL_pidstatus);
3163 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3170 # ifdef HAS_WAITPID_RUNTIME
3171 if (!HAS_WAITPID_RUNTIME)
3174 result = PerlProc_waitpid(pid,statusp,flags);
3177 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3178 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3181 #ifdef PERL_USES_PL_PIDSTATUS
3182 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3187 Perl_croak(aTHX_ "Can't do waitpid with flags");
3189 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3190 pidgone(result,*statusp);
3196 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3199 if (result < 0 && errno == EINTR) {
3201 errno = EINTR; /* reset in case a signal handler changed $! */
3205 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3207 #ifdef PERL_USES_PL_PIDSTATUS
3209 S_pidgone(pTHX_ Pid_t pid, int status)
3213 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3214 SvUPGRADE(sv,SVt_IV);
3215 SvIV_set(sv, status);
3220 #if defined(OS2) || defined(EPOC)
3223 int /* Cannot prototype with I32
3225 my_syspclose(PerlIO *ptr)
3228 Perl_my_pclose(pTHX_ PerlIO *ptr)
3231 /* Needs work for PerlIO ! */
3232 FILE * const f = PerlIO_findFILE(ptr);
3233 const I32 result = pclose(f);
3234 PerlIO_releaseFILE(ptr,f);
3242 Perl_my_pclose(pTHX_ PerlIO *ptr)
3244 /* Needs work for PerlIO ! */
3245 FILE * const f = PerlIO_findFILE(ptr);
3246 I32 result = djgpp_pclose(f);
3247 result = (result << 8) & 0xff00;
3248 PerlIO_releaseFILE(ptr,f);
3253 #define PERL_REPEATCPY_LINEAR 4
3255 Perl_repeatcpy(register char *to, register const char *from, I32 len, register IV count)
3257 PERL_ARGS_ASSERT_REPEATCPY;
3260 memset(to, *from, count);
3263 IV items, linear, half;
3265 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3266 for (items = 0; items < linear; ++items) {
3267 const char *q = from;
3269 for (todo = len; todo > 0; todo--)
3274 while (items <= half) {
3275 IV size = items * len;
3276 memcpy(p, to, size);
3282 memcpy(p, to, (count - items) * len);
3288 Perl_same_dirent(pTHX_ const char *a, const char *b)
3290 char *fa = strrchr(a,'/');
3291 char *fb = strrchr(b,'/');
3294 SV * const tmpsv = sv_newmortal();
3296 PERL_ARGS_ASSERT_SAME_DIRENT;
3309 sv_setpvs(tmpsv, ".");
3311 sv_setpvn(tmpsv, a, fa - a);
3312 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3315 sv_setpvs(tmpsv, ".");
3317 sv_setpvn(tmpsv, b, fb - b);
3318 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3320 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3321 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3323 #endif /* !HAS_RENAME */
3326 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3327 const char *const *const search_ext, I32 flags)
3330 const char *xfound = NULL;
3331 char *xfailed = NULL;
3332 char tmpbuf[MAXPATHLEN];
3337 #if defined(DOSISH) && !defined(OS2)
3338 # define SEARCH_EXTS ".bat", ".cmd", NULL
3339 # define MAX_EXT_LEN 4
3342 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3343 # define MAX_EXT_LEN 4
3346 # define SEARCH_EXTS ".pl", ".com", NULL
3347 # define MAX_EXT_LEN 4
3349 /* additional extensions to try in each dir if scriptname not found */
3351 static const char *const exts[] = { SEARCH_EXTS };
3352 const char *const *const ext = search_ext ? search_ext : exts;
3353 int extidx = 0, i = 0;
3354 const char *curext = NULL;
3356 PERL_UNUSED_ARG(search_ext);
3357 # define MAX_EXT_LEN 0
3360 PERL_ARGS_ASSERT_FIND_SCRIPT;
3363 * If dosearch is true and if scriptname does not contain path
3364 * delimiters, search the PATH for scriptname.
3366 * If SEARCH_EXTS is also defined, will look for each
3367 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3368 * while searching the PATH.
3370 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3371 * proceeds as follows:
3372 * If DOSISH or VMSISH:
3373 * + look for ./scriptname{,.foo,.bar}
3374 * + search the PATH for scriptname{,.foo,.bar}
3377 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3378 * this will not look in '.' if it's not in the PATH)
3383 # ifdef ALWAYS_DEFTYPES
3384 len = strlen(scriptname);
3385 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3386 int idx = 0, deftypes = 1;
3389 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3392 int idx = 0, deftypes = 1;
3395 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3397 /* The first time through, just add SEARCH_EXTS to whatever we
3398 * already have, so we can check for default file types. */
3400 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3406 if ((strlen(tmpbuf) + strlen(scriptname)
3407 + MAX_EXT_LEN) >= sizeof tmpbuf)
3408 continue; /* don't search dir with too-long name */
3409 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3413 if (strEQ(scriptname, "-"))
3415 if (dosearch) { /* Look in '.' first. */
3416 const char *cur = scriptname;
3418 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3420 if (strEQ(ext[i++],curext)) {
3421 extidx = -1; /* already has an ext */
3426 DEBUG_p(PerlIO_printf(Perl_debug_log,
3427 "Looking for %s\n",cur));
3428 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3429 && !S_ISDIR(PL_statbuf.st_mode)) {
3437 if (cur == scriptname) {
3438 len = strlen(scriptname);
3439 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3441 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3444 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3445 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3450 if (dosearch && !strchr(scriptname, '/')
3452 && !strchr(scriptname, '\\')
3454 && (s = PerlEnv_getenv("PATH")))
3458 bufend = s + strlen(s);
3459 while (s < bufend) {
3462 && *s != ';'; len++, s++) {
3463 if (len < sizeof tmpbuf)
3466 if (len < sizeof tmpbuf)
3469 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3475 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3476 continue; /* don't search dir with too-long name */
3479 && tmpbuf[len - 1] != '/'
3480 && tmpbuf[len - 1] != '\\'
3483 tmpbuf[len++] = '/';
3484 if (len == 2 && tmpbuf[0] == '.')
3486 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3490 len = strlen(tmpbuf);
3491 if (extidx > 0) /* reset after previous loop */
3495 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3496 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3497 if (S_ISDIR(PL_statbuf.st_mode)) {
3501 } while ( retval < 0 /* not there */
3502 && extidx>=0 && ext[extidx] /* try an extension? */
3503 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3508 if (S_ISREG(PL_statbuf.st_mode)
3509 && cando(S_IRUSR,TRUE,&PL_statbuf)
3510 #if !defined(DOSISH)
3511 && cando(S_IXUSR,TRUE,&PL_statbuf)
3515 xfound = tmpbuf; /* bingo! */
3519 xfailed = savepv(tmpbuf);
3522 if (!xfound && !seen_dot && !xfailed &&
3523 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3524 || S_ISDIR(PL_statbuf.st_mode)))
3526 seen_dot = 1; /* Disable message. */
3528 if (flags & 1) { /* do or die? */
3529 /* diag_listed_as: Can't execute %s */
3530 Perl_croak(aTHX_ "Can't %s %s%s%s",
3531 (xfailed ? "execute" : "find"),
3532 (xfailed ? xfailed : scriptname),
3533 (xfailed ? "" : " on PATH"),
3534 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3539 scriptname = xfound;
3541 return (scriptname ? savepv(scriptname) : NULL);
3544 #ifndef PERL_GET_CONTEXT_DEFINED
3547 Perl_get_context(void)
3550 #if defined(USE_ITHREADS)
3551 # ifdef OLD_PTHREADS_API
3553 int error = pthread_getspecific(PL_thr_key, &t)
3555 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3558 # ifdef I_MACH_CTHREADS
3559 return (void*)cthread_data(cthread_self());
3561 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3570 Perl_set_context(void *t)
3573 PERL_ARGS_ASSERT_SET_CONTEXT;
3574 #if defined(USE_ITHREADS)
3575 # ifdef I_MACH_CTHREADS
3576 cthread_set_data(cthread_self(), t);
3579 const int error = pthread_setspecific(PL_thr_key, t);
3581 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3589 #endif /* !PERL_GET_CONTEXT_DEFINED */
3591 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3600 Perl_get_op_names(pTHX)
3602 PERL_UNUSED_CONTEXT;
3603 return (char **)PL_op_name;
3607 Perl_get_op_descs(pTHX)
3609 PERL_UNUSED_CONTEXT;
3610 return (char **)PL_op_desc;
3614 Perl_get_no_modify(pTHX)
3616 PERL_UNUSED_CONTEXT;
3617 return PL_no_modify;
3621 Perl_get_opargs(pTHX)
3623 PERL_UNUSED_CONTEXT;
3624 return (U32 *)PL_opargs;
3628 Perl_get_ppaddr(pTHX)
3631 PERL_UNUSED_CONTEXT;
3632 return (PPADDR_t*)PL_ppaddr;
3635 #ifndef HAS_GETENV_LEN
3637 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3639 char * const env_trans = PerlEnv_getenv(env_elem);
3640 PERL_UNUSED_CONTEXT;
3641 PERL_ARGS_ASSERT_GETENV_LEN;
3643 *len = strlen(env_trans);
3650 Perl_get_vtbl(pTHX_ int vtbl_id)
3652 PERL_UNUSED_CONTEXT;
3654 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3655 ? NULL : PL_magic_vtables + vtbl_id;
3659 Perl_my_fflush_all(pTHX)
3661 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3662 return PerlIO_flush(NULL);
3664 # if defined(HAS__FWALK)
3665 extern int fflush(FILE *);
3666 /* undocumented, unprototyped, but very useful BSDism */
3667 extern void _fwalk(int (*)(FILE *));
3671 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3673 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3674 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3676 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3677 open_max = sysconf(_SC_OPEN_MAX);
3680 open_max = FOPEN_MAX;
3683 open_max = OPEN_MAX;
3694 for (i = 0; i < open_max; i++)
3695 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3696 STDIO_STREAM_ARRAY[i]._file < open_max &&
3697 STDIO_STREAM_ARRAY[i]._flag)
3698 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3702 SETERRNO(EBADF,RMS_IFI);
3709 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3711 if (ckWARN(WARN_IO)) {
3713 = gv && (isGV_with_GP(gv))
3716 const char * const direction = have == '>' ? "out" : "in";
3718 if (name && HEK_LEN(name))
3719 Perl_warner(aTHX_ packWARN(WARN_IO),
3720 "Filehandle %"HEKf" opened only for %sput",
3723 Perl_warner(aTHX_ packWARN(WARN_IO),
3724 "Filehandle opened only for %sput", direction);
3729 Perl_report_evil_fh(pTHX_ const GV *gv)
3731 const IO *io = gv ? GvIO(gv) : NULL;
3732 const PERL_BITFIELD16 op = PL_op->op_type;
3736 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3738 warn_type = WARN_CLOSED;
3742 warn_type = WARN_UNOPENED;
3745 if (ckWARN(warn_type)) {
3747 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3748 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3749 const char * const pars =
3750 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3751 const char * const func =
3753 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3754 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3756 const char * const type =
3758 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3759 ? "socket" : "filehandle");
3760 const bool have_name = name && SvCUR(name);
3761 Perl_warner(aTHX_ packWARN(warn_type),
3762 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3763 have_name ? " " : "",
3764 SVfARG(have_name ? name : &PL_sv_no));
3765 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3767 aTHX_ packWARN(warn_type),
3768 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3769 func, pars, have_name ? " " : "",
3770 SVfARG(have_name ? name : &PL_sv_no)
3775 /* To workaround core dumps from the uninitialised tm_zone we get the
3776 * system to give us a reasonable struct to copy. This fix means that
3777 * strftime uses the tm_zone and tm_gmtoff values returned by
3778 * localtime(time()). That should give the desired result most of the
3779 * time. But probably not always!
3781 * This does not address tzname aspects of NETaa14816.
3786 # ifndef STRUCT_TM_HASZONE
3787 # define STRUCT_TM_HASZONE
3791 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3792 # ifndef HAS_TM_TM_ZONE
3793 # define HAS_TM_TM_ZONE
3798 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3800 #ifdef HAS_TM_TM_ZONE
3802 const struct tm* my_tm;
3803 PERL_ARGS_ASSERT_INIT_TM;
3805 my_tm = localtime(&now);
3807 Copy(my_tm, ptm, 1, struct tm);
3809 PERL_ARGS_ASSERT_INIT_TM;
3810 PERL_UNUSED_ARG(ptm);
3815 * mini_mktime - normalise struct tm values without the localtime()
3816 * semantics (and overhead) of mktime().
3819 Perl_mini_mktime(pTHX_ struct tm *ptm)
3823 int month, mday, year, jday;
3824 int odd_cent, odd_year;
3825 PERL_UNUSED_CONTEXT;
3827 PERL_ARGS_ASSERT_MINI_MKTIME;
3829 #define DAYS_PER_YEAR 365
3830 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3831 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3832 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3833 #define SECS_PER_HOUR (60*60)
3834 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3835 /* parentheses deliberately absent on these two, otherwise they don't work */
3836 #define MONTH_TO_DAYS 153/5
3837 #define DAYS_TO_MONTH 5/153
3838 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3839 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3840 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3841 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3844 * Year/day algorithm notes:
3846 * With a suitable offset for numeric value of the month, one can find
3847 * an offset into the year by considering months to have 30.6 (153/5) days,
3848 * using integer arithmetic (i.e., with truncation). To avoid too much
3849 * messing about with leap days, we consider January and February to be
3850 * the 13th and 14th month of the previous year. After that transformation,
3851 * we need the month index we use to be high by 1 from 'normal human' usage,
3852 * so the month index values we use run from 4 through 15.
3854 * Given that, and the rules for the Gregorian calendar (leap years are those
3855 * divisible by 4 unless also divisible by 100, when they must be divisible
3856 * by 400 instead), we can simply calculate the number of days since some
3857 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3858 * the days we derive from our month index, and adding in the day of the
3859 * month. The value used here is not adjusted for the actual origin which
3860 * it normally would use (1 January A.D. 1), since we're not exposing it.
3861 * We're only building the value so we can turn around and get the
3862 * normalised values for the year, month, day-of-month, and day-of-year.
3864 * For going backward, we need to bias the value we're using so that we find
3865 * the right year value. (Basically, we don't want the contribution of
3866 * March 1st to the number to apply while deriving the year). Having done
3867 * that, we 'count up' the contribution to the year number by accounting for
3868 * full quadracenturies (400-year periods) with their extra leap days, plus
3869 * the contribution from full centuries (to avoid counting in the lost leap
3870 * days), plus the contribution from full quad-years (to count in the normal
3871 * leap days), plus the leftover contribution from any non-leap years.
3872 * At this point, if we were working with an actual leap day, we'll have 0
3873 * days left over. This is also true for March 1st, however. So, we have
3874 * to special-case that result, and (earlier) keep track of the 'odd'
3875 * century and year contributions. If we got 4 extra centuries in a qcent,
3876 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3877 * Otherwise, we add back in the earlier bias we removed (the 123 from
3878 * figuring in March 1st), find the month index (integer division by 30.6),
3879 * and the remainder is the day-of-month. We then have to convert back to
3880 * 'real' months (including fixing January and February from being 14/15 in
3881 * the previous year to being in the proper year). After that, to get
3882 * tm_yday, we work with the normalised year and get a new yearday value for
3883 * January 1st, which we subtract from the yearday value we had earlier,
3884 * representing the date we've re-built. This is done from January 1
3885 * because tm_yday is 0-origin.
3887 * Since POSIX time routines are only guaranteed to work for times since the
3888 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3889 * applies Gregorian calendar rules even to dates before the 16th century
3890 * doesn't bother me. Besides, you'd need cultural context for a given
3891 * date to know whether it was Julian or Gregorian calendar, and that's
3892 * outside the scope for this routine. Since we convert back based on the
3893 * same rules we used to build the yearday, you'll only get strange results
3894 * for input which needed normalising, or for the 'odd' century years which
3895 * were leap years in the Julian calendar but not in the Gregorian one.
3896 * I can live with that.
3898 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3899 * that's still outside the scope for POSIX time manipulation, so I don't
3903 year = 1900 + ptm->tm_year;
3904 month = ptm->tm_mon;
3905 mday = ptm->tm_mday;
3911 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3912 yearday += month*MONTH_TO_DAYS + mday + jday;
3914 * Note that we don't know when leap-seconds were or will be,
3915 * so we have to trust the user if we get something which looks
3916 * like a sensible leap-second. Wild values for seconds will
3917 * be rationalised, however.
3919 if ((unsigned) ptm->tm_sec <= 60) {
3926 secs += 60 * ptm->tm_min;
3927 secs += SECS_PER_HOUR * ptm->tm_hour;
3929 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3930 /* got negative remainder, but need positive time */
3931 /* back off an extra day to compensate */
3932 yearday += (secs/SECS_PER_DAY)-1;
3933 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3936 yearday += (secs/SECS_PER_DAY);
3937 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3940 else if (secs >= SECS_PER_DAY) {
3941 yearday += (secs/SECS_PER_DAY);
3942 secs %= SECS_PER_DAY;
3944 ptm->tm_hour = secs/SECS_PER_HOUR;
3945 secs %= SECS_PER_HOUR;
3946 ptm->tm_min = secs/60;
3948 ptm->tm_sec += secs;
3949 /* done with time of day effects */
3951 * The algorithm for yearday has (so far) left it high by 428.
3952 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3953 * bias it by 123 while trying to figure out what year it
3954 * really represents. Even with this tweak, the reverse
3955 * translation fails for years before A.D. 0001.
3956 * It would still fail for Feb 29, but we catch that one below.
3958 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3959 yearday -= YEAR_ADJUST;
3960 year = (yearday / DAYS_PER_QCENT) * 400;
3961 yearday %= DAYS_PER_QCENT;
3962 odd_cent = yearday / DAYS_PER_CENT;
3963 year += odd_cent * 100;
3964 yearday %= DAYS_PER_CENT;
3965 year += (yearday / DAYS_PER_QYEAR) * 4;
3966 yearday %= DAYS_PER_QYEAR;
3967 odd_year = yearday / DAYS_PER_YEAR;
3969 yearday %= DAYS_PER_YEAR;
3970 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3975 yearday += YEAR_ADJUST; /* recover March 1st crock */
3976 month = yearday*DAYS_TO_MONTH;
3977 yearday -= month*MONTH_TO_DAYS;
3978 /* recover other leap-year adjustment */
3987 ptm->tm_year = year - 1900;
3989 ptm->tm_mday = yearday;
3990 ptm->tm_mon = month;
3994 ptm->tm_mon = month - 1;
3996 /* re-build yearday based on Jan 1 to get tm_yday */
3998 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3999 yearday += 14*MONTH_TO_DAYS + 1;
4000 ptm->tm_yday = jday - yearday;
4001 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4005 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)
4013 PERL_ARGS_ASSERT_MY_STRFTIME;
4015 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4018 mytm.tm_hour = hour;
4019 mytm.tm_mday = mday;
4021 mytm.tm_year = year;
4022 mytm.tm_wday = wday;
4023 mytm.tm_yday = yday;
4024 mytm.tm_isdst = isdst;
4026 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4027 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4032 #ifdef HAS_TM_TM_GMTOFF
4033 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4035 #ifdef HAS_TM_TM_ZONE
4036 mytm.tm_zone = mytm2.tm_zone;
4041 Newx(buf, buflen, char);
4042 len = strftime(buf, buflen, fmt, &mytm);
4044 ** The following is needed to handle to the situation where
4045 ** tmpbuf overflows. Basically we want to allocate a buffer
4046 ** and try repeatedly. The reason why it is so complicated
4047 ** is that getting a return value of 0 from strftime can indicate
4048 ** one of the following:
4049 ** 1. buffer overflowed,
4050 ** 2. illegal conversion specifier, or
4051 ** 3. the format string specifies nothing to be returned(not
4052 ** an error). This could be because format is an empty string
4053 ** or it specifies %p that yields an empty string in some locale.
4054 ** If there is a better way to make it portable, go ahead by
4057 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4060 /* Possibly buf overflowed - try again with a bigger buf */
4061 const int fmtlen = strlen(fmt);
4062 int bufsize = fmtlen + buflen;
4064 Renew(buf, bufsize, char);
4066 buflen = strftime(buf, bufsize, fmt, &mytm);
4067 if (buflen > 0 && buflen < bufsize)
4069 /* heuristic to prevent out-of-memory errors */
4070 if (bufsize > 100*fmtlen) {
4076 Renew(buf, bufsize, char);
4081 Perl_croak(aTHX_ "panic: no strftime");
4087 #define SV_CWD_RETURN_UNDEF \
4088 sv_setsv(sv, &PL_sv_undef); \
4091 #define SV_CWD_ISDOT(dp) \
4092 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4093 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4096 =head1 Miscellaneous Functions
4098 =for apidoc getcwd_sv
4100 Fill the sv with current working directory
4105 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4106 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4107 * getcwd(3) if available
4108 * Comments from the orignal:
4109 * This is a faster version of getcwd. It's also more dangerous
4110 * because you might chdir out of a directory that you can't chdir
4114 Perl_getcwd_sv(pTHX_ register SV *sv)
4118 #ifndef INCOMPLETE_TAINTS
4122 PERL_ARGS_ASSERT_GETCWD_SV;
4126 char buf[MAXPATHLEN];
4128 /* Some getcwd()s automatically allocate a buffer of the given
4129 * size from the heap if they are given a NULL buffer pointer.
4130 * The problem is that this behaviour is not portable. */
4131 if (getcwd(buf, sizeof(buf) - 1)) {
4136 sv_setsv(sv, &PL_sv_undef);
4144 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4148 SvUPGRADE(sv, SVt_PV);
4150 if (PerlLIO_lstat(".", &statbuf) < 0) {
4151 SV_CWD_RETURN_UNDEF;
4154 orig_cdev = statbuf.st_dev;
4155 orig_cino = statbuf.st_ino;
4165 if (PerlDir_chdir("..") < 0) {
4166 SV_CWD_RETURN_UNDEF;
4168 if (PerlLIO_stat(".", &statbuf) < 0) {
4169 SV_CWD_RETURN_UNDEF;
4172 cdev = statbuf.st_dev;
4173 cino = statbuf.st_ino;
4175 if (odev == cdev && oino == cino) {
4178 if (!(dir = PerlDir_open("."))) {
4179 SV_CWD_RETURN_UNDEF;
4182 while ((dp = PerlDir_read(dir)) != NULL) {
4184 namelen = dp->d_namlen;
4186 namelen = strlen(dp->d_name);
4189 if (SV_CWD_ISDOT(dp)) {
4193 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4194 SV_CWD_RETURN_UNDEF;
4197 tdev = statbuf.st_dev;
4198 tino = statbuf.st_ino;
4199 if (tino == oino && tdev == odev) {
4205 SV_CWD_RETURN_UNDEF;
4208 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4209 SV_CWD_RETURN_UNDEF;
4212 SvGROW(sv, pathlen + namelen + 1);
4216 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4219 /* prepend current directory to the front */
4221 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4222 pathlen += (namelen + 1);
4224 #ifdef VOID_CLOSEDIR
4227 if (PerlDir_close(dir) < 0) {
4228 SV_CWD_RETURN_UNDEF;
4234 SvCUR_set(sv, pathlen);
4238 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4239 SV_CWD_RETURN_UNDEF;
4242 if (PerlLIO_stat(".", &statbuf) < 0) {
4243 SV_CWD_RETURN_UNDEF;
4246 cdev = statbuf.st_dev;
4247 cino = statbuf.st_ino;
4249 if (cdev != orig_cdev || cino != orig_cino) {
4250 Perl_croak(aTHX_ "Unstable directory path, "
4251 "current directory changed unexpectedly");
4262 #define VERSION_MAX 0x7FFFFFFF
4265 =for apidoc prescan_version
4267 Validate that a given string can be parsed as a version object, but doesn't
4268 actually perform the parsing. Can use either strict or lax validation rules.
4269 Can optionally set a number of hint variables to save the parsing code
4270 some time when tokenizing.
4275 Perl_prescan_version(pTHX_ const char *s, bool strict,
4276 const char **errstr,
4277 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4278 bool qv = (sqv ? *sqv : FALSE);
4280 int saw_decimal = 0;
4284 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4286 if (qv && isDIGIT(*d))
4287 goto dotted_decimal_version;
4289 if (*d == 'v') { /* explicit v-string */
4294 else { /* degenerate v-string */
4295 /* requires v1.2.3 */
4296 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4299 dotted_decimal_version:
4300 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4301 /* no leading zeros allowed */
4302 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4305 while (isDIGIT(*d)) /* integer part */
4311 d++; /* decimal point */
4316 /* require v1.2.3 */
4317 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4320 goto version_prescan_finish;
4327 while (isDIGIT(*d)) { /* just keep reading */
4329 while (isDIGIT(*d)) {
4331 /* maximum 3 digits between decimal */
4332 if (strict && j > 3) {
4333 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4338 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4341 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4346 else if (*d == '.') {
4348 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4353 else if (!isDIGIT(*d)) {
4359 if (strict && i < 2) {
4360 /* requires v1.2.3 */
4361 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4364 } /* end if dotted-decimal */
4366 { /* decimal versions */
4367 /* special strict case for leading '.' or '0' */
4370 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4372 if (*d == '0' && isDIGIT(d[1])) {
4373 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4377 /* and we never support negative versions */
4379 BADVERSION(s,errstr,"Invalid version format (negative version number)");
4382 /* consume all of the integer part */
4386 /* look for a fractional part */
4388 /* we found it, so consume it */
4392 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4395 BADVERSION(s,errstr,"Invalid version format (version required)");
4397 /* found just an integer */
4398 goto version_prescan_finish;
4400 else if ( d == s ) {
4401 /* didn't find either integer or period */
4402 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4404 else if (*d == '_') {
4405 /* underscore can't come after integer part */
4407 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4409 else if (isDIGIT(d[1])) {
4410 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4413 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4417 /* anything else after integer part is just invalid data */
4418 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4421 /* scan the fractional part after the decimal point*/
4423 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4424 /* strict or lax-but-not-the-end */
4425 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4428 while (isDIGIT(*d)) {
4430 if (*d == '.' && isDIGIT(d[-1])) {
4432 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4435 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4437 d = (char *)s; /* start all over again */
4439 goto dotted_decimal_version;
4443 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4446 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4448 if ( ! isDIGIT(d[1]) ) {
4449 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4457 version_prescan_finish:
4461 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4462 /* trailing non-numeric data */
4463 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4471 *ssaw_decimal = saw_decimal;
4478 =for apidoc scan_version
4480 Returns a pointer to the next character after the parsed
4481 version string, as well as upgrading the passed in SV to
4484 Function must be called with an already existing SV like
4487 s = scan_version(s, SV *sv, bool qv);
4489 Performs some preprocessing to the string to ensure that
4490 it has the correct characteristics of a version. Flags the
4491 object if it contains an underscore (which denotes this
4492 is an alpha version). The boolean qv denotes that the version
4493 should be interpreted as if it had multiple decimals, even if
4500 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4505 const char *errstr = NULL;
4506 int saw_decimal = 0;
4510 AV * const av = newAV();
4511 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4513 PERL_ARGS_ASSERT_SCAN_VERSION;
4515 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4517 #ifndef NODEFAULT_SHAREKEYS
4518 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4521 while (isSPACE(*s)) /* leading whitespace is OK */
4524 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4526 /* "undef" is a special case and not an error */
4527 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4528 Perl_croak(aTHX_ "%s", errstr);
4538 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4540 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4541 if ( !qv && width < 3 )
4542 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4544 while (isDIGIT(*pos))
4546 if (!isALPHA(*pos)) {
4552 /* this is atoi() that delimits on underscores */
4553 const char *end = pos;
4557 /* the following if() will only be true after the decimal
4558 * point of a version originally created with a bare
4559 * floating point number, i.e. not quoted in any way
4561 if ( !qv && s > start && saw_decimal == 1 ) {
4565 rev += (*s - '0') * mult;
4567 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4568 || (PERL_ABS(rev) > VERSION_MAX )) {
4569 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4570 "Integer overflow in version %d",VERSION_MAX);
4581 while (--end >= s) {
4583 rev += (*end - '0') * mult;
4585 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4586 || (PERL_ABS(rev) > VERSION_MAX )) {
4587 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4588 "Integer overflow in version");
4597 /* Append revision */
4598 av_push(av, newSViv(rev));
4603 else if ( *pos == '.' )
4605 else if ( *pos == '_' && isDIGIT(pos[1]) )
4607 else if ( *pos == ',' && isDIGIT(pos[1]) )
4609 else if ( isDIGIT(*pos) )
4616 while ( isDIGIT(*pos) )
4621 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4629 if ( qv ) { /* quoted versions always get at least three terms*/
4630 I32 len = av_len(av);
4631 /* This for loop appears to trigger a compiler bug on OS X, as it
4632 loops infinitely. Yes, len is negative. No, it makes no sense.
4633 Compiler in question is:
4634 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4635 for ( len = 2 - len; len > 0; len-- )
4636 av_push(MUTABLE_AV(sv), newSViv(0));
4640 av_push(av, newSViv(0));
4643 /* need to save off the current version string for later */
4645 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4646 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4647 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4649 else if ( s > start ) {
4650 SV * orig = newSVpvn(start,s-start);
4651 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4652 /* need to insert a v to be consistent */
4653 sv_insert(orig, 0, 0, "v", 1);
4655 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4658 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4659 av_push(av, newSViv(0));
4662 /* And finally, store the AV in the hash */
4663 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4665 /* fix RT#19517 - special case 'undef' as string */
4666 if ( *s == 'u' && strEQ(s,"undef") ) {
4674 =for apidoc new_version
4676 Returns a new version object based on the passed in SV:
4678 SV *sv = new_version(SV *ver);
4680 Does not alter the passed in ver SV. See "upg_version" if you
4681 want to upgrade the SV.
4687 Perl_new_version(pTHX_ SV *ver)
4690 SV * const rv = newSV(0);
4691 PERL_ARGS_ASSERT_NEW_VERSION;
4692 if ( sv_isobject(ver) && sv_derived_from(ver, "version") )
4693 /* can just copy directly */
4696 AV * const av = newAV();
4698 /* This will get reblessed later if a derived class*/
4699 SV * const hv = newSVrv(rv, "version");
4700 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4701 #ifndef NODEFAULT_SHAREKEYS
4702 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4708 /* Begin copying all of the elements */
4709 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4710 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4712 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4713 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4715 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4717 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4718 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4721 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4723 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4724 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4727 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4728 /* This will get reblessed later if a derived class*/
4729 for ( key = 0; key <= av_len(sav); key++ )
4731 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4732 av_push(av, newSViv(rev));
4735 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4740 const MAGIC* const mg = SvVSTRING_mg(ver);
4741 if ( mg ) { /* already a v-string */
4742 const STRLEN len = mg->mg_len;
4743 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4744 sv_setpvn(rv,version,len);
4745 /* this is for consistency with the pure Perl class */
4746 if ( isDIGIT(*version) )
4747 sv_insert(rv, 0, 0, "v", 1);
4752 sv_setsv(rv,ver); /* make a duplicate */
4757 return upg_version(rv, FALSE);
4761 =for apidoc upg_version
4763 In-place upgrade of the supplied SV to a version object.
4765 SV *sv = upg_version(SV *sv, bool qv);
4767 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4768 to force this SV to be interpreted as an "extended" version.
4774 Perl_upg_version(pTHX_ SV *ver, bool qv)
4776 const char *version, *s;
4781 PERL_ARGS_ASSERT_UPG_VERSION;
4783 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4787 /* may get too much accuracy */
4789 SV *sv = SvNVX(ver) > 10e50 ? newSV(64) : 0;
4791 #ifdef USE_LOCALE_NUMERIC
4792 char *loc = savepv(setlocale(LC_NUMERIC, NULL));
4793 setlocale(LC_NUMERIC, "C");
4796 Perl_sv_setpvf(aTHX_ sv, "%.9"NVff, SvNVX(ver));
4797 buf = SvPV(sv, len);
4800 len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4803 #ifdef USE_LOCALE_NUMERIC
4804 setlocale(LC_NUMERIC, loc);
4807 while (buf[len-1] == '0' && len > 0) len--;
4808 if ( buf[len-1] == '.' ) len--; /* eat the trailing decimal */
4809 version = savepvn(buf, len);
4813 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4814 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4818 else /* must be a string or something like a string */
4821 version = savepv(SvPV(ver,len));
4823 # if PERL_VERSION > 5
4824 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4825 if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
4826 /* may be a v-string */
4827 char *testv = (char *)version;
4829 for (tlen=0; tlen < len; tlen++, testv++) {
4830 /* if one of the characters is non-text assume v-string */
4831 if (testv[0] < ' ') {
4832 SV * const nsv = sv_newmortal();
4835 int saw_decimal = 0;
4836 sv_setpvf(nsv,"v%vd",ver);
4837 pos = nver = savepv(SvPV_nolen(nsv));
4839 /* scan the resulting formatted string */
4840 pos++; /* skip the leading 'v' */
4841 while ( *pos == '.' || isDIGIT(*pos) ) {
4847 /* is definitely a v-string */
4848 if ( saw_decimal >= 2 ) {
4860 s = scan_version(version, ver, qv);
4862 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4863 "Version string '%s' contains invalid data; "
4864 "ignoring: '%s'", version, s);
4872 Validates that the SV contains valid internal structure for a version object.
4873 It may be passed either the version object (RV) or the hash itself (HV). If
4874 the structure is valid, it returns the HV. If the structure is invalid,
4877 SV *hv = vverify(sv);
4879 Note that it only confirms the bare minimum structure (so as not to get
4880 confused by derived classes which may contain additional hash entries):
4884 =item * The SV is an HV or a reference to an HV
4886 =item * The hash contains a "version" key
4888 =item * The "version" key has a reference to an AV as its value
4896 Perl_vverify(pTHX_ SV *vs)
4900 PERL_ARGS_ASSERT_VVERIFY;
4905 /* see if the appropriate elements exist */
4906 if ( SvTYPE(vs) == SVt_PVHV
4907 && hv_exists(MUTABLE_HV(vs), "version", 7)
4908 && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
4909 && SvTYPE(sv) == SVt_PVAV )
4918 Accepts a version object and returns the normalized floating
4919 point representation. Call like:
4923 NOTE: you can pass either the object directly or the SV
4924 contained within the RV.
4926 The SV returned has a refcount of 1.
4932 Perl_vnumify(pTHX_ SV *vs)
4940 PERL_ARGS_ASSERT_VNUMIFY;
4942 /* extract the HV from the object */
4945 Perl_croak(aTHX_ "Invalid version object");
4947 /* see if various flags exist */
4948 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
4950 if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
4951 width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
4956 /* attempt to retrieve the version array */
4957 if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
4958 return newSVpvs("0");
4964 return newSVpvs("0");
4967 digit = SvIV(*av_fetch(av, 0, 0));
4968 sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
4969 for ( i = 1 ; i < len ; i++ )
4971 digit = SvIV(*av_fetch(av, i, 0));
4973 const int denom = (width == 2 ? 10 : 100);
4974 const div_t term = div((int)PERL_ABS(digit),denom);
4975 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4978 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4984 digit = SvIV(*av_fetch(av, len, 0));
4985 if ( alpha && width == 3 ) /* alpha version */
4987 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4991 sv_catpvs(sv, "000");
4999 Accepts a version object and returns the normalized string
5000 representation. Call like:
5004 NOTE: you can pass either the object directly or the SV
5005 contained within the RV.
5007 The SV returned has a refcount of 1.
5013 Perl_vnormal(pTHX_ SV *vs)
5020 PERL_ARGS_ASSERT_VNORMAL;
5022 /* extract the HV from the object */
5025 Perl_croak(aTHX_ "Invalid version object");
5027 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5029 av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)));
5034 return newSVpvs("");
5036 digit = SvIV(*av_fetch(av, 0, 0));
5037 sv = Perl_newSVpvf(aTHX_ "v%"IVdf, (IV)digit);
5038 for ( i = 1 ; i < len ; i++ ) {
5039 digit = SvIV(*av_fetch(av, i, 0));
5040 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5045 /* handle last digit specially */
5046 digit = SvIV(*av_fetch(av, len, 0));
5048 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
5050 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5053 if ( len <= 2 ) { /* short version, must be at least three */
5054 for ( len = 2 - len; len != 0; len-- )
5061 =for apidoc vstringify
5063 In order to maintain maximum compatibility with earlier versions
5064 of Perl, this function will return either the floating point
5065 notation or the multiple dotted notation, depending on whether
5066 the original version contained 1 or more dots, respectively.
5068 The SV returned has a refcount of 1.
5074 Perl_vstringify(pTHX_ SV *vs)
5076 PERL_ARGS_ASSERT_VSTRINGIFY;
5078 /* extract the HV from the object */
5081 Perl_croak(aTHX_ "Invalid version object");
5083 if (hv_exists(MUTABLE_HV(vs), "original", sizeof("original") - 1)) {
5085 pv = *hv_fetchs(MUTABLE_HV(vs), "original", FALSE);
5089 return &PL_sv_undef;
5092 if ( hv_exists(MUTABLE_HV(vs), "qv", 2) )
5102 Version object aware cmp. Both operands must already have been
5103 converted into version objects.
5109 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
5112 bool lalpha = FALSE;
5113 bool ralpha = FALSE;
5118 PERL_ARGS_ASSERT_VCMP;
5120 /* extract the HVs from the objects */
5123 if ( ! ( lhv && rhv ) )
5124 Perl_croak(aTHX_ "Invalid version object");
5126 /* get the left hand term */
5127 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(lhv), "version", FALSE)));
5128 if ( hv_exists(MUTABLE_HV(lhv), "alpha", 5 ) )
5131 /* and the right hand term */
5132 rav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rhv), "version", FALSE)));
5133 if ( hv_exists(MUTABLE_HV(rhv), "alpha", 5 ) )
5141 while ( i <= m && retval == 0 )
5143 left = SvIV(*av_fetch(lav,i,0));
5144 right = SvIV(*av_fetch(rav,i,0));
5152 /* tiebreaker for alpha with identical terms */
5153 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
5155 if ( lalpha && !ralpha )
5159 else if ( ralpha && !lalpha)
5165 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
5169 while ( i <= r && retval == 0 )
5171 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
5172 retval = -1; /* not a match after all */
5178 while ( i <= l && retval == 0 )
5180 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
5181 retval = +1; /* not a match after all */
5189 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
5190 # define EMULATE_SOCKETPAIR_UDP
5193 #ifdef EMULATE_SOCKETPAIR_UDP
5195 S_socketpair_udp (int fd[2]) {
5197 /* Fake a datagram socketpair using UDP to localhost. */
5198 int sockets[2] = {-1, -1};
5199 struct sockaddr_in addresses[2];
5201 Sock_size_t size = sizeof(struct sockaddr_in);
5202 unsigned short port;
5205 memset(&addresses, 0, sizeof(addresses));
5208 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
5209 if (sockets[i] == -1)
5210 goto tidy_up_and_fail;
5212 addresses[i].sin_family = AF_INET;
5213 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5214 addresses[i].sin_port = 0; /* kernel choses port. */
5215 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
5216 sizeof(struct sockaddr_in)) == -1)
5217 goto tidy_up_and_fail;
5220 /* Now have 2 UDP sockets. Find out which port each is connected to, and
5221 for each connect the other socket to it. */
5224 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
5226 goto tidy_up_and_fail;
5227 if (size != sizeof(struct sockaddr_in))
5228 goto abort_tidy_up_and_fail;
5229 /* !1 is 0, !0 is 1 */
5230 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
5231 sizeof(struct sockaddr_in)) == -1)
5232 goto tidy_up_and_fail;
5235 /* Now we have 2 sockets connected to each other. I don't trust some other
5236 process not to have already sent a packet to us (by random) so send
5237 a packet from each to the other. */
5240 /* I'm going to send my own port number. As a short.
5241 (Who knows if someone somewhere has sin_port as a bitfield and needs
5242 this routine. (I'm assuming crays have socketpair)) */
5243 port = addresses[i].sin_port;
5244 got = PerlLIO_write(sockets[i], &port, sizeof(port));
5245 if (got != sizeof(port)) {
5247 goto tidy_up_and_fail;
5248 goto abort_tidy_up_and_fail;
5252 /* Packets sent. I don't trust them to have arrived though.
5253 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
5254 connect to localhost will use a second kernel thread. In 2.6 the
5255 first thread running the connect() returns before the second completes,
5256 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
5257 returns 0. Poor programs have tripped up. One poor program's authors'
5258 had a 50-1 reverse stock split. Not sure how connected these were.)
5259 So I don't trust someone not to have an unpredictable UDP stack.
5263 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
5264 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
5268 FD_SET((unsigned int)sockets[0], &rset);
5269 FD_SET((unsigned int)sockets[1], &rset);
5271 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
5272 if (got != 2 || !FD_ISSET(sockets[0], &rset)
5273 || !FD_ISSET(sockets[1], &rset)) {
5274 /* I hope this is portable and appropriate. */
5276 goto tidy_up_and_fail;
5277 goto abort_tidy_up_and_fail;
5281 /* And the paranoia department even now doesn't trust it to have arrive
5282 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
5284 struct sockaddr_in readfrom;
5285 unsigned short buffer[2];
5290 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5291 sizeof(buffer), MSG_DONTWAIT,
5292 (struct sockaddr *) &readfrom, &size);
5294 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5296 (struct sockaddr *) &readfrom, &size);
5300 goto tidy_up_and_fail;
5301 if (got != sizeof(port)
5302 || size != sizeof(struct sockaddr_in)
5303 /* Check other socket sent us its port. */
5304 || buffer[0] != (unsigned short) addresses[!i].sin_port
5305 /* Check kernel says we got the datagram from that socket */
5306 || readfrom.sin_family != addresses[!i].sin_family
5307 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
5308 || readfrom.sin_port != addresses[!i].sin_port)
5309 goto abort_tidy_up_and_fail;
5312 /* My caller (my_socketpair) has validated that this is non-NULL */
5315 /* I hereby declare this connection open. May God bless all who cross
5319 abort_tidy_up_and_fail:
5320 errno = ECONNABORTED;
5324 if (sockets[0] != -1)
5325 PerlLIO_close(sockets[0]);
5326 if (sockets[1] != -1)
5327 PerlLIO_close(sockets[1]);
5332 #endif /* EMULATE_SOCKETPAIR_UDP */
5334 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
5336 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5337 /* Stevens says that family must be AF_LOCAL, protocol 0.
5338 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
5343 struct sockaddr_in listen_addr;
5344 struct sockaddr_in connect_addr;
5349 || family != AF_UNIX
5352 errno = EAFNOSUPPORT;
5360 #ifdef EMULATE_SOCKETPAIR_UDP
5361 if (type == SOCK_DGRAM)
5362 return S_socketpair_udp(fd);
5365 listener = PerlSock_socket(AF_INET, type, 0);
5368 memset(&listen_addr, 0, sizeof(listen_addr));
5369 listen_addr.sin_family = AF_INET;
5370 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5371 listen_addr.sin_port = 0; /* kernel choses port. */
5372 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5373 sizeof(listen_addr)) == -1)
5374 goto tidy_up_and_fail;
5375 if (PerlSock_listen(listener, 1) == -1)
5376 goto tidy_up_and_fail;
5378 connector = PerlSock_socket(AF_INET, type, 0);
5379 if (connector == -1)
5380 goto tidy_up_and_fail;
5381 /* We want to find out the port number to connect to. */
5382 size = sizeof(connect_addr);
5383 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5385 goto tidy_up_and_fail;
5386 if (size != sizeof(connect_addr))
5387 goto abort_tidy_up_and_fail;
5388 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
5389 sizeof(connect_addr)) == -1)
5390 goto tidy_up_and_fail;
5392 size = sizeof(listen_addr);
5393 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5396 goto tidy_up_and_fail;
5397 if (size != sizeof(listen_addr))
5398 goto abort_tidy_up_and_fail;
5399 PerlLIO_close(listener);
5400 /* Now check we are talking to ourself by matching port and host on the
5402 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5404 goto tidy_up_and_fail;
5405 if (size != sizeof(connect_addr)
5406 || listen_addr.sin_family != connect_addr.sin_family
5407 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5408 || listen_addr.sin_port != connect_addr.sin_port) {
5409 goto abort_tidy_up_and_fail;
5415 abort_tidy_up_and_fail:
5417 errno = ECONNABORTED; /* This would be the standard thing to do. */
5419 # ifdef ECONNREFUSED
5420 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5422 errno = ETIMEDOUT; /* Desperation time. */
5429 PerlLIO_close(listener);
5430 if (connector != -1)
5431 PerlLIO_close(connector);
5433 PerlLIO_close(acceptor);
5439 /* In any case have a stub so that there's code corresponding
5440 * to the my_socketpair in embed.fnc. */
5442 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5443 #ifdef HAS_SOCKETPAIR
5444 return socketpair(family, type, protocol, fd);
5453 =for apidoc sv_nosharing
5455 Dummy routine which "shares" an SV when there is no sharing module present.
5456 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5457 Exists to avoid test for a NULL function pointer and because it could
5458 potentially warn under some level of strict-ness.
5464 Perl_sv_nosharing(pTHX_ SV *sv)
5466 PERL_UNUSED_CONTEXT;
5467 PERL_UNUSED_ARG(sv);
5472 =for apidoc sv_destroyable
5474 Dummy routine which reports that object can be destroyed when there is no
5475 sharing module present. It ignores its single SV argument, and returns
5476 'true'. Exists to avoid test for a NULL function pointer and because it
5477 could potentially warn under some level of strict-ness.
5483 Perl_sv_destroyable(pTHX_ SV *sv)
5485 PERL_UNUSED_CONTEXT;
5486 PERL_UNUSED_ARG(sv);
5491 Perl_parse_unicode_opts(pTHX_ const char **popt)
5493 const char *p = *popt;
5496 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5500 opt = (U32) atoi(p);
5503 if (*p && *p != '\n' && *p != '\r') {
5504 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5506 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
5512 case PERL_UNICODE_STDIN:
5513 opt |= PERL_UNICODE_STDIN_FLAG; break;
5514 case PERL_UNICODE_STDOUT:
5515 opt |= PERL_UNICODE_STDOUT_FLAG; break;
5516 case PERL_UNICODE_STDERR:
5517 opt |= PERL_UNICODE_STDERR_FLAG; break;
5518 case PERL_UNICODE_STD:
5519 opt |= PERL_UNICODE_STD_FLAG; break;
5520 case PERL_UNICODE_IN:
5521 opt |= PERL_UNICODE_IN_FLAG; break;
5522 case PERL_UNICODE_OUT:
5523 opt |= PERL_UNICODE_OUT_FLAG; break;
5524 case PERL_UNICODE_INOUT:
5525 opt |= PERL_UNICODE_INOUT_FLAG; break;
5526 case PERL_UNICODE_LOCALE:
5527 opt |= PERL_UNICODE_LOCALE_FLAG; break;
5528 case PERL_UNICODE_ARGV:
5529 opt |= PERL_UNICODE_ARGV_FLAG; break;
5530 case PERL_UNICODE_UTF8CACHEASSERT:
5531 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
5533 if (*p != '\n' && *p != '\r') {
5534 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5537 "Unknown Unicode option letter '%c'", *p);
5544 opt = PERL_UNICODE_DEFAULT_FLAGS;
5546 the_end_of_the_opts_parser:
5548 if (opt & ~PERL_UNICODE_ALL_FLAGS)
5549 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
5550 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5558 # include <starlet.h>
5566 * This is really just a quick hack which grabs various garbage
5567 * values. It really should be a real hash algorithm which
5568 * spreads the effect of every input bit onto every output bit,
5569 * if someone who knows about such things would bother to write it.
5570 * Might be a good idea to add that function to CORE as well.
5571 * No numbers below come from careful analysis or anything here,
5572 * except they are primes and SEED_C1 > 1E6 to get a full-width
5573 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5574 * probably be bigger too.
5577 # define SEED_C1 1000003
5578 #define SEED_C4 73819
5580 # define SEED_C1 25747
5581 #define SEED_C4 20639
5585 #define SEED_C5 26107
5587 #ifndef PERL_NO_DEV_RANDOM
5592 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5593 * in 100-ns units, typically incremented ever 10 ms. */
5594 unsigned int when[2];
5596 # ifdef HAS_GETTIMEOFDAY
5597 struct timeval when;
5603 /* This test is an escape hatch, this symbol isn't set by Configure. */
5604 #ifndef PERL_NO_DEV_RANDOM
5605 #ifndef PERL_RANDOM_DEVICE
5606 /* /dev/random isn't used by default because reads from it will block
5607 * if there isn't enough entropy available. You can compile with
5608 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5609 * is enough real entropy to fill the seed. */
5610 # define PERL_RANDOM_DEVICE "/dev/urandom"
5612 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5614 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5623 _ckvmssts(sys$gettim(when));
5624 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5626 # ifdef HAS_GETTIMEOFDAY
5627 PerlProc_gettimeofday(&when,NULL);
5628 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5631 u = (U32)SEED_C1 * when;
5634 u += SEED_C3 * (U32)PerlProc_getpid();
5635 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5636 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5637 u += SEED_C5 * (U32)PTR2UV(&when);
5643 Perl_get_hash_seed(pTHX)
5646 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
5652 if (s && isDIGIT(*s))
5653 myseed = (UV)Atoul(s);
5655 #ifdef USE_HASH_SEED_EXPLICIT
5659 /* Compute a random seed */
5660 (void)seedDrand01((Rand_seed_t)seed());
5661 myseed = (UV)(Drand01() * (NV)UV_MAX);
5662 #if RANDBITS < (UVSIZE * 8)
5663 /* Since there are not enough randbits to to reach all
5664 * the bits of a UV, the low bits might need extra
5665 * help. Sum in another random number that will
5666 * fill in the low bits. */
5668 (UV)(Drand01() * (NV)((((UV)1) << ((UVSIZE * 8 - RANDBITS))) - 1));
5669 #endif /* RANDBITS < (UVSIZE * 8) */
5670 if (myseed == 0) { /* Superparanoia. */
5671 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5673 Perl_croak(aTHX_ "Your random numbers are not that random");
5676 PL_rehash_seed_set = TRUE;
5681 #ifdef PERL_GLOBAL_STRUCT
5683 #define PERL_GLOBAL_STRUCT_INIT
5684 #include "opcode.h" /* the ppaddr and check */
5687 Perl_init_global_struct(pTHX)
5689 struct perl_vars *plvarsp = NULL;
5690 # ifdef PERL_GLOBAL_STRUCT
5691 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5692 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5693 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5694 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5695 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5699 plvarsp = PL_VarsPtr;
5700 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5705 # define PERLVAR(prefix,var,type) /**/
5706 # define PERLVARA(prefix,var,n,type) /**/
5707 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
5708 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
5709 # include "perlvars.h"
5714 # ifdef PERL_GLOBAL_STRUCT
5717 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5718 if (!plvarsp->Gppaddr)
5722 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5723 if (!plvarsp->Gcheck)
5725 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5726 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5728 # ifdef PERL_SET_VARS
5729 PERL_SET_VARS(plvarsp);
5731 # undef PERL_GLOBAL_STRUCT_INIT
5736 #endif /* PERL_GLOBAL_STRUCT */
5738 #ifdef PERL_GLOBAL_STRUCT
5741 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5743 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
5744 # ifdef PERL_GLOBAL_STRUCT
5745 # ifdef PERL_UNSET_VARS
5746 PERL_UNSET_VARS(plvarsp);
5748 free(plvarsp->Gppaddr);
5749 free(plvarsp->Gcheck);
5750 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5756 #endif /* PERL_GLOBAL_STRUCT */
5760 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
5761 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
5762 * given, and you supply your own implementation.
5764 * The default implementation reads a single env var, PERL_MEM_LOG,
5765 * expecting one or more of the following:
5767 * \d+ - fd fd to write to : must be 1st (atoi)
5768 * 'm' - memlog was PERL_MEM_LOG=1
5769 * 's' - svlog was PERL_SV_LOG=1
5770 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
5772 * This makes the logger controllable enough that it can reasonably be
5773 * added to the system perl.
5776 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
5777 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5779 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5781 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
5782 * writes to. In the default logger, this is settable at runtime.
5784 #ifndef PERL_MEM_LOG_FD
5785 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5788 #ifndef PERL_MEM_LOG_NOIMPL
5790 # ifdef DEBUG_LEAKING_SCALARS
5791 # define SV_LOG_SERIAL_FMT " [%lu]"
5792 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
5794 # define SV_LOG_SERIAL_FMT
5795 # define _SV_LOG_SERIAL_ARG(sv)
5799 S_mem_log_common(enum mem_log_type mlt, const UV n,
5800 const UV typesize, const char *type_name, const SV *sv,
5801 Malloc_t oldalloc, Malloc_t newalloc,
5802 const char *filename, const int linenumber,
5803 const char *funcname)
5807 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
5809 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
5812 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
5814 /* We can't use SVs or PerlIO for obvious reasons,
5815 * so we'll use stdio and low-level IO instead. */
5816 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5818 # ifdef HAS_GETTIMEOFDAY
5819 # define MEM_LOG_TIME_FMT "%10d.%06d: "
5820 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
5822 gettimeofday(&tv, 0);
5824 # define MEM_LOG_TIME_FMT "%10d: "
5825 # define MEM_LOG_TIME_ARG (int)when
5829 /* If there are other OS specific ways of hires time than
5830 * gettimeofday() (see ext/Time-HiRes), the easiest way is
5831 * probably that they would be used to fill in the struct
5835 int fd = atoi(pmlenv);
5837 fd = PERL_MEM_LOG_FD;
5839 if (strchr(pmlenv, 't')) {
5840 len = my_snprintf(buf, sizeof(buf),
5841 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
5842 PerlLIO_write(fd, buf, len);
5846 len = my_snprintf(buf, sizeof(buf),
5847 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5848 " %s = %"IVdf": %"UVxf"\n",
5849 filename, linenumber, funcname, n, typesize,
5850 type_name, n * typesize, PTR2UV(newalloc));
5853 len = my_snprintf(buf, sizeof(buf),
5854 "realloc: %s:%d:%s: %"IVdf" %"UVuf
5855 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5856 filename, linenumber, funcname, n, typesize,
5857 type_name, n * typesize, PTR2UV(oldalloc),
5861 len = my_snprintf(buf, sizeof(buf),
5862 "free: %s:%d:%s: %"UVxf"\n",
5863 filename, linenumber, funcname,
5868 len = my_snprintf(buf, sizeof(buf),
5869 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
5870 mlt == MLT_NEW_SV ? "new" : "del",
5871 filename, linenumber, funcname,
5872 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
5877 PerlLIO_write(fd, buf, len);
5881 #endif /* !PERL_MEM_LOG_NOIMPL */
5883 #ifndef PERL_MEM_LOG_NOIMPL
5885 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
5886 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
5888 /* this is suboptimal, but bug compatible. User is providing their
5889 own implementation, but is getting these functions anyway, and they
5890 do nothing. But _NOIMPL users should be able to cope or fix */
5892 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
5893 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
5897 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
5899 const char *filename, const int linenumber,
5900 const char *funcname)
5902 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
5903 NULL, NULL, newalloc,
5904 filename, linenumber, funcname);
5909 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
5910 Malloc_t oldalloc, Malloc_t newalloc,
5911 const char *filename, const int linenumber,
5912 const char *funcname)
5914 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
5915 NULL, oldalloc, newalloc,
5916 filename, linenumber, funcname);
5921 Perl_mem_log_free(Malloc_t oldalloc,
5922 const char *filename, const int linenumber,
5923 const char *funcname)
5925 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
5926 filename, linenumber, funcname);
5931 Perl_mem_log_new_sv(const SV *sv,
5932 const char *filename, const int linenumber,
5933 const char *funcname)
5935 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
5936 filename, linenumber, funcname);
5940 Perl_mem_log_del_sv(const SV *sv,
5941 const char *filename, const int linenumber,
5942 const char *funcname)
5944 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
5945 filename, linenumber, funcname);
5948 #endif /* PERL_MEM_LOG */
5951 =for apidoc my_sprintf
5953 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5954 the length of the string written to the buffer. Only rare pre-ANSI systems
5955 need the wrapper function - usually this is a direct call to C<sprintf>.
5959 #ifndef SPRINTF_RETURNS_STRLEN
5961 Perl_my_sprintf(char *buffer, const char* pat, ...)
5964 PERL_ARGS_ASSERT_MY_SPRINTF;
5965 va_start(args, pat);
5966 vsprintf(buffer, pat, args);
5968 return strlen(buffer);
5973 =for apidoc my_snprintf
5975 The C library C<snprintf> functionality, if available and
5976 standards-compliant (uses C<vsnprintf>, actually). However, if the
5977 C<vsnprintf> is not available, will unfortunately use the unsafe
5978 C<vsprintf> which can overrun the buffer (there is an overrun check,
5979 but that may be too late). Consider using C<sv_vcatpvf> instead, or
5980 getting C<vsnprintf>.
5985 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
5990 PERL_ARGS_ASSERT_MY_SNPRINTF;
5991 va_start(ap, format);
5992 #ifdef HAS_VSNPRINTF
5993 retval = vsnprintf(buffer, len, format, ap);
5995 retval = vsprintf(buffer, format, ap);
5998 /* vsprintf() shows failure with < 0 */
6000 #ifdef HAS_VSNPRINTF
6001 /* vsnprintf() shows failure with >= len */
6003 (len > 0 && (Size_t)retval >= len)
6006 Perl_croak(aTHX_ "panic: my_snprintf buffer overflow");
6011 =for apidoc my_vsnprintf
6013 The C library C<vsnprintf> if available and standards-compliant.
6014 However, if if the C<vsnprintf> is not available, will unfortunately
6015 use the unsafe C<vsprintf> which can overrun the buffer (there is an
6016 overrun check, but that may be too late). Consider using
6017 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
6022 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
6029 PERL_ARGS_ASSERT_MY_VSNPRINTF;
6031 Perl_va_copy(ap, apc);
6032 # ifdef HAS_VSNPRINTF
6033 retval = vsnprintf(buffer, len, format, apc);
6035 retval = vsprintf(buffer, format, apc);
6038 # ifdef HAS_VSNPRINTF
6039 retval = vsnprintf(buffer, len, format, ap);
6041 retval = vsprintf(buffer, format, ap);
6043 #endif /* #ifdef NEED_VA_COPY */
6044 /* vsprintf() shows failure with < 0 */
6046 #ifdef HAS_VSNPRINTF
6047 /* vsnprintf() shows failure with >= len */
6049 (len > 0 && (Size_t)retval >= len)
6052 Perl_croak(aTHX_ "panic: my_vsnprintf buffer overflow");
6057 Perl_my_clearenv(pTHX)
6060 #if ! defined(PERL_MICRO)
6061 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
6063 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
6064 # if defined(USE_ENVIRON_ARRAY)
6065 # if defined(USE_ITHREADS)
6066 /* only the parent thread can clobber the process environment */
6067 if (PL_curinterp == aTHX)
6068 # endif /* USE_ITHREADS */
6070 # if ! defined(PERL_USE_SAFE_PUTENV)
6071 if ( !PL_use_safe_putenv) {
6073 if (environ == PL_origenviron)
6074 environ = (char**)safesysmalloc(sizeof(char*));
6076 for (i = 0; environ[i]; i++)
6077 (void)safesysfree(environ[i]);
6080 # else /* PERL_USE_SAFE_PUTENV */
6081 # if defined(HAS_CLEARENV)
6083 # elif defined(HAS_UNSETENV)
6084 int bsiz = 80; /* Most envvar names will be shorter than this. */
6085 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
6086 char *buf = (char*)safesysmalloc(bufsiz);
6087 while (*environ != NULL) {
6088 char *e = strchr(*environ, '=');
6089 int l = e ? e - *environ : (int)strlen(*environ);
6091 (void)safesysfree(buf);
6092 bsiz = l + 1; /* + 1 for the \0. */
6093 buf = (char*)safesysmalloc(bufsiz);
6095 memcpy(buf, *environ, l);
6097 (void)unsetenv(buf);
6099 (void)safesysfree(buf);
6100 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
6101 /* Just null environ and accept the leakage. */
6103 # endif /* HAS_CLEARENV || HAS_UNSETENV */
6104 # endif /* ! PERL_USE_SAFE_PUTENV */
6106 # endif /* USE_ENVIRON_ARRAY */
6107 # endif /* PERL_IMPLICIT_SYS || WIN32 */
6108 #endif /* PERL_MICRO */
6111 #ifdef PERL_IMPLICIT_CONTEXT
6113 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
6114 the global PL_my_cxt_index is incremented, and that value is assigned to
6115 that module's static my_cxt_index (who's address is passed as an arg).
6116 Then, for each interpreter this function is called for, it makes sure a
6117 void* slot is available to hang the static data off, by allocating or
6118 extending the interpreter's PL_my_cxt_list array */
6120 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
6122 Perl_my_cxt_init(pTHX_ int *index, size_t size)
6126 PERL_ARGS_ASSERT_MY_CXT_INIT;
6128 /* this module hasn't been allocated an index yet */
6129 #if defined(USE_ITHREADS)
6130 MUTEX_LOCK(&PL_my_ctx_mutex);
6132 *index = PL_my_cxt_index++;
6133 #if defined(USE_ITHREADS)
6134 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6138 /* make sure the array is big enough */
6139 if (PL_my_cxt_size <= *index) {
6140 if (PL_my_cxt_size) {
6141 while (PL_my_cxt_size <= *index)
6142 PL_my_cxt_size *= 2;
6143 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6146 PL_my_cxt_size = 16;
6147 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6150 /* newSV() allocates one more than needed */
6151 p = (void*)SvPVX(newSV(size-1));
6152 PL_my_cxt_list[*index] = p;
6153 Zero(p, size, char);
6157 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6160 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
6165 PERL_ARGS_ASSERT_MY_CXT_INDEX;
6167 for (index = 0; index < PL_my_cxt_index; index++) {
6168 const char *key = PL_my_cxt_keys[index];
6169 /* try direct pointer compare first - there are chances to success,
6170 * and it's much faster.
6172 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
6179 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
6185 PERL_ARGS_ASSERT_MY_CXT_INIT;
6187 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
6189 /* this module hasn't been allocated an index yet */
6190 #if defined(USE_ITHREADS)
6191 MUTEX_LOCK(&PL_my_ctx_mutex);
6193 index = PL_my_cxt_index++;
6194 #if defined(USE_ITHREADS)
6195 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6199 /* make sure the array is big enough */
6200 if (PL_my_cxt_size <= index) {
6201 int old_size = PL_my_cxt_size;
6203 if (PL_my_cxt_size) {
6204 while (PL_my_cxt_size <= index)
6205 PL_my_cxt_size *= 2;
6206 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6207 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6210 PL_my_cxt_size = 16;
6211 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6212 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6214 for (i = old_size; i < PL_my_cxt_size; i++) {
6215 PL_my_cxt_keys[i] = 0;
6216 PL_my_cxt_list[i] = 0;
6219 PL_my_cxt_keys[index] = my_cxt_key;
6220 /* newSV() allocates one more than needed */
6221 p = (void*)SvPVX(newSV(size-1));
6222 PL_my_cxt_list[index] = p;
6223 Zero(p, size, char);
6226 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6227 #endif /* PERL_IMPLICIT_CONTEXT */
6230 Perl_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
6234 const char *vn = NULL;
6235 SV *const module = PL_stack_base[ax];
6237 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
6239 if (items >= 2) /* version supplied as bootstrap arg */
6240 sv = PL_stack_base[ax + 1];
6242 /* XXX GV_ADDWARN */
6244 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6245 if (!sv || !SvOK(sv)) {
6247 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6251 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
6252 SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version")
6253 ? sv : sv_2mortal(new_version(sv));
6254 xssv = upg_version(xssv, 0);
6255 if ( vcmp(pmsv,xssv) ) {
6256 SV *string = vstringify(xssv);
6257 SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
6258 " does not match ", module, string);
6260 SvREFCNT_dec(string);
6261 string = vstringify(pmsv);
6264 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, module, vn,
6267 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, string);
6269 SvREFCNT_dec(string);
6271 Perl_sv_2mortal(aTHX_ xpt);
6272 Perl_croak_sv(aTHX_ xpt);
6278 Perl_xs_apiversion_bootcheck(pTHX_ SV *module, const char *api_p,
6282 SV *compver = Perl_newSVpvn_flags(aTHX_ api_p, api_len, SVs_TEMP);
6285 PERL_ARGS_ASSERT_XS_APIVERSION_BOOTCHECK;
6287 /* This might croak */
6288 compver = upg_version(compver, 0);
6289 /* This should never croak */
6290 runver = new_version(PL_apiversion);
6291 if (vcmp(compver, runver)) {
6292 SV *compver_string = vstringify(compver);
6293 SV *runver_string = vstringify(runver);
6294 xpt = Perl_newSVpvf(aTHX_ "Perl API version %"SVf
6295 " of %"SVf" does not match %"SVf,
6296 compver_string, module, runver_string);
6297 Perl_sv_2mortal(aTHX_ xpt);
6299 SvREFCNT_dec(compver_string);
6300 SvREFCNT_dec(runver_string);
6302 SvREFCNT_dec(runver);
6304 Perl_croak_sv(aTHX_ xpt);
6309 Perl_my_strlcat(char *dst, const char *src, Size_t size)
6311 Size_t used, length, copy;
6314 length = strlen(src);
6315 if (size > 0 && used < size - 1) {
6316 copy = (length >= size - used) ? size - used - 1 : length;
6317 memcpy(dst + used, src, copy);
6318 dst[used + copy] = '\0';
6320 return used + length;
6326 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
6328 Size_t length, copy;
6330 length = strlen(src);
6332 copy = (length >= size) ? size - 1 : length;
6333 memcpy(dst, src, copy);
6340 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
6341 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
6342 long _ftol( double ); /* Defined by VC6 C libs. */
6343 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
6346 PERL_STATIC_INLINE bool
6347 S_gv_has_usable_name(pTHX_ GV *gv)
6351 && HvENAME(GvSTASH(gv))
6352 && (gvp = (GV **)hv_fetch(
6353 GvSTASH(gv), GvNAME(gv),
6354 GvNAMEUTF8(gv) ? -GvNAMELEN(gv) : GvNAMELEN(gv), 0
6360 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
6363 SV * const dbsv = GvSVn(PL_DBsub);
6364 const bool save_taint = PL_tainted;
6366 /* When we are called from pp_goto (svp is null),
6367 * we do not care about using dbsv to call CV;
6368 * it's for informational purposes only.
6371 PERL_ARGS_ASSERT_GET_DB_SUB;
6375 if (!PERLDB_SUB_NN) {
6379 gv_efullname3(dbsv, gv, NULL);
6381 else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
6382 || strEQ(GvNAME(gv), "END")
6383 || ( /* Could be imported, and old sub redefined. */
6384 (GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv))
6386 !( (SvTYPE(*svp) == SVt_PVGV)
6387 && (GvCV((const GV *)*svp) == cv)
6388 /* Use GV from the stack as a fallback. */
6389 && S_gv_has_usable_name(aTHX_ gv = (GV *)*svp)
6393 /* GV is potentially non-unique, or contain different CV. */
6394 SV * const tmp = newRV(MUTABLE_SV(cv));
6395 sv_setsv(dbsv, tmp);
6399 sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv)));
6400 sv_catpvs(dbsv, "::");
6402 dbsv, GvNAME(gv), GvNAMELEN(gv),
6403 GvNAMEUTF8(gv) ? SV_CATUTF8 : SV_CATBYTES
6408 const int type = SvTYPE(dbsv);
6409 if (type < SVt_PVIV && type != SVt_IV)
6410 sv_upgrade(dbsv, SVt_PVIV);
6411 (void)SvIOK_on(dbsv);
6412 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
6414 TAINT_IF(save_taint);
6418 Perl_my_dirfd(pTHX_ DIR * dir) {
6420 /* Most dirfd implementations have problems when passed NULL. */
6425 #elif defined(HAS_DIR_DD_FD)
6428 Perl_die(aTHX_ PL_no_func, "dirfd");
6429 assert(0); /* NOT REACHED */
6435 Perl_get_re_arg(pTHX_ SV *sv) {
6441 sv = MUTABLE_SV(SvRV(sv));
6442 if (SvTYPE(sv) == SVt_REGEXP)
6443 return (REGEXP*) sv;
6451 * c-indentation-style: bsd
6453 * indent-tabs-mode: nil
6456 * ex: set ts=8 sts=4 sw=4 et: