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
98 Perl_croak_nocontext("panic: malloc");
100 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
101 PERL_ALLOC_CHECK(ptr);
103 #ifdef PERL_TRACK_MEMPOOL
104 struct perl_memory_debug_header *const header
105 = (struct perl_memory_debug_header *)ptr;
109 PoisonNew(((char *)ptr), size, char);
112 #ifdef PERL_TRACK_MEMPOOL
113 header->interpreter = aTHX;
114 /* Link us into the list. */
115 header->prev = &PL_memory_debug_header;
116 header->next = PL_memory_debug_header.next;
117 PL_memory_debug_header.next = header;
118 header->next->prev = header;
122 ptr = (Malloc_t)((char*)ptr+sTHX);
124 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
128 #ifndef ALWAYS_NEED_THX
134 return write_no_mem();
140 /* paranoid version of system's realloc() */
143 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
145 #ifdef ALWAYS_NEED_THX
149 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
150 Malloc_t PerlMem_realloc();
151 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
155 PerlIO_printf(Perl_error_log,
156 "Reallocation too large: %lx\n", size) FLUSH;
159 #endif /* HAS_64K_LIMIT */
166 return safesysmalloc(size);
167 #ifdef PERL_TRACK_MEMPOOL
168 where = (Malloc_t)((char*)where-sTHX);
171 struct perl_memory_debug_header *const header
172 = (struct perl_memory_debug_header *)where;
174 if (header->interpreter != aTHX) {
175 Perl_croak_nocontext("panic: realloc from wrong pool");
177 assert(header->next->prev == header);
178 assert(header->prev->next == header);
180 if (header->size > size) {
181 const MEM_SIZE freed_up = header->size - size;
182 char *start_of_freed = ((char *)where) + size;
183 PoisonFree(start_of_freed, freed_up, char);
191 Perl_croak_nocontext("panic: realloc");
193 ptr = (Malloc_t)PerlMem_realloc(where,size);
194 PERL_ALLOC_CHECK(ptr);
196 /* MUST do this fixup first, before doing ANYTHING else, as anything else
197 might allocate memory/free/move memory, and until we do the fixup, it
198 may well be chasing (and writing to) free memory. */
199 #ifdef PERL_TRACK_MEMPOOL
201 struct perl_memory_debug_header *const header
202 = (struct perl_memory_debug_header *)ptr;
205 if (header->size < size) {
206 const MEM_SIZE fresh = size - header->size;
207 char *start_of_fresh = ((char *)ptr) + size;
208 PoisonNew(start_of_fresh, fresh, char);
212 header->next->prev = header;
213 header->prev->next = header;
215 ptr = (Malloc_t)((char*)ptr+sTHX);
219 /* In particular, must do that fixup above before logging anything via
220 *printf(), as it can reallocate memory, which can cause SEGVs. */
222 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
223 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
230 #ifndef ALWAYS_NEED_THX
236 return write_no_mem();
242 /* safe version of system's free() */
245 Perl_safesysfree(Malloc_t where)
247 #ifdef ALWAYS_NEED_THX
252 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
254 #ifdef PERL_TRACK_MEMPOOL
255 where = (Malloc_t)((char*)where-sTHX);
257 struct perl_memory_debug_header *const header
258 = (struct perl_memory_debug_header *)where;
260 if (header->interpreter != aTHX) {
261 Perl_croak_nocontext("panic: free from wrong pool");
264 Perl_croak_nocontext("panic: duplicate free");
266 if (!(header->next) || header->next->prev != header
267 || header->prev->next != header) {
268 Perl_croak_nocontext("panic: bad free");
270 /* Unlink us from the chain. */
271 header->next->prev = header->prev;
272 header->prev->next = header->next;
274 PoisonNew(where, header->size, char);
276 /* Trigger the duplicate free warning. */
284 /* safe version of system's calloc() */
287 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
289 #ifdef ALWAYS_NEED_THX
293 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
294 MEM_SIZE total_size = 0;
297 /* Even though calloc() for zero bytes is strange, be robust. */
298 if (size && (count <= MEM_SIZE_MAX / size)) {
299 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
300 total_size = size * count;
304 Perl_croak_nocontext("%s", PL_memory_wrap);
305 #ifdef PERL_TRACK_MEMPOOL
306 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
309 Perl_croak_nocontext("%s", PL_memory_wrap);
312 if (total_size > 0xffff) {
313 PerlIO_printf(Perl_error_log,
314 "Allocation too large: %lx\n", total_size) FLUSH;
317 #endif /* HAS_64K_LIMIT */
319 if ((long)size < 0 || (long)count < 0)
320 Perl_croak_nocontext("panic: calloc");
322 #ifdef PERL_TRACK_MEMPOOL
323 /* Have to use malloc() because we've added some space for our tracking
325 /* malloc(0) is non-portable. */
326 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
328 /* Use calloc() because it might save a memset() if the memory is fresh
329 and clean from the OS. */
331 ptr = (Malloc_t)PerlMem_calloc(count, size);
332 else /* calloc(0) is non-portable. */
333 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
335 PERL_ALLOC_CHECK(ptr);
336 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));
338 #ifdef PERL_TRACK_MEMPOOL
340 struct perl_memory_debug_header *const header
341 = (struct perl_memory_debug_header *)ptr;
343 memset((void*)ptr, 0, total_size);
344 header->interpreter = aTHX;
345 /* Link us into the list. */
346 header->prev = &PL_memory_debug_header;
347 header->next = PL_memory_debug_header.next;
348 PL_memory_debug_header.next = header;
349 header->next->prev = header;
351 header->size = total_size;
353 ptr = (Malloc_t)((char*)ptr+sTHX);
359 #ifndef ALWAYS_NEED_THX
364 return write_no_mem();
368 /* These must be defined when not using Perl's malloc for binary
373 Malloc_t Perl_malloc (MEM_SIZE nbytes)
376 return (Malloc_t)PerlMem_malloc(nbytes);
379 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
382 return (Malloc_t)PerlMem_calloc(elements, size);
385 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
388 return (Malloc_t)PerlMem_realloc(where, nbytes);
391 Free_t Perl_mfree (Malloc_t where)
399 /* copy a string up to some (non-backslashed) delimiter, if any */
402 Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
406 PERL_ARGS_ASSERT_DELIMCPY;
408 for (tolen = 0; from < fromend; from++, tolen++) {
410 if (from[1] != delim) {
417 else if (*from == delim)
428 /* return ptr to little string in big string, NULL if not found */
429 /* This routine was donated by Corey Satten. */
432 Perl_instr(register const char *big, register const char *little)
436 PERL_ARGS_ASSERT_INSTR;
444 register const char *s, *x;
447 for (x=big,s=little; *s; /**/ ) {
458 return (char*)(big-1);
463 /* same as instr but allow embedded nulls */
466 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
468 PERL_ARGS_ASSERT_NINSTR;
472 const char first = *little;
474 bigend -= lend - little++;
476 while (big <= bigend) {
477 if (*big++ == first) {
478 for (x=big,s=little; s < lend; x++,s++) {
482 return (char*)(big-1);
489 /* reverse of the above--find last substring */
492 Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
494 register const char *bigbeg;
495 register const I32 first = *little;
496 register const char * const littleend = lend;
498 PERL_ARGS_ASSERT_RNINSTR;
500 if (little >= littleend)
501 return (char*)bigend;
503 big = bigend - (littleend - little++);
504 while (big >= bigbeg) {
505 register const char *s, *x;
508 for (x=big+2,s=little; s < littleend; /**/ ) {
517 return (char*)(big+1);
522 /* As a space optimization, we do not compile tables for strings of length
523 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
524 special-cased in fbm_instr().
526 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
529 =head1 Miscellaneous Functions
531 =for apidoc fbm_compile
533 Analyses the string in order to make fast searches on it using fbm_instr()
534 -- the Boyer-Moore algorithm.
540 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
543 register const U8 *s;
550 PERL_ARGS_ASSERT_FBM_COMPILE;
552 /* Refuse to fbm_compile a studied scalar, as this gives more flexibility in
553 SV flag usage. No real-world code would ever end up using a studied
554 scalar as a compile-time second argument to index, so this isn't a real
562 if (flags & FBMcf_TAIL) {
563 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
564 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
565 if (mg && mg->mg_len >= 0)
568 s = (U8*)SvPV_force_mutable(sv, len);
569 if (len == 0) /* TAIL might be on a zero-length string. */
571 SvUPGRADE(sv, SVt_PVMG);
576 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
577 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
578 to call SvVALID_off() if the scalar was assigned to.
580 The comment itself (and "deeper magic" below) date back to
581 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
583 where the magic (presumably) was that the scalar had a BM table hidden
586 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
587 the table instead of the previous (somewhat hacky) approach of co-opting
588 the string buffer and storing it after the string. */
590 assert(!mg_find(sv, PERL_MAGIC_bm));
591 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
595 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
597 const U8 mlen = (len>255) ? 255 : (U8)len;
598 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
601 Newx(table, 256, U8);
602 memset((void*)table, mlen, 256);
603 mg->mg_ptr = (char *)table;
606 s += len - 1; /* last char */
609 if (table[*s] == mlen)
615 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
616 for (i = 0; i < len; i++) {
617 if (PL_freq[s[i]] < frequency) {
619 frequency = PL_freq[s[i]];
622 BmRARE(sv) = s[rarest];
623 BmPREVIOUS(sv) = rarest;
624 BmUSEFUL(sv) = 100; /* Initial value */
625 if (flags & FBMcf_TAIL)
627 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
628 BmRARE(sv), BmPREVIOUS(sv)));
631 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
632 /* If SvTAIL is actually due to \Z or \z, this gives false positives
636 =for apidoc fbm_instr
638 Returns the location of the SV in the string delimited by C<str> and
639 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
640 does not have to be fbm_compiled, but the search will not be as fast
647 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
649 register unsigned char *s;
651 register const unsigned char *little
652 = (const unsigned char *)SvPV_const(littlestr,l);
653 register STRLEN littlelen = l;
654 register const I32 multiline = flags & FBMrf_MULTILINE;
656 PERL_ARGS_ASSERT_FBM_INSTR;
658 if ((STRLEN)(bigend - big) < littlelen) {
659 if ( SvTAIL(littlestr)
660 && ((STRLEN)(bigend - big) == littlelen - 1)
662 || (*big == *little &&
663 memEQ((char *)big, (char *)little, littlelen - 1))))
668 switch (littlelen) { /* Special cases for 0, 1 and 2 */
670 return (char*)big; /* Cannot be SvTAIL! */
672 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
673 /* Know that bigend != big. */
674 if (bigend[-1] == '\n')
675 return (char *)(bigend - 1);
676 return (char *) bigend;
684 if (SvTAIL(littlestr))
685 return (char *) bigend;
688 if (SvTAIL(littlestr) && !multiline) {
689 if (bigend[-1] == '\n' && bigend[-2] == *little)
690 return (char*)bigend - 2;
691 if (bigend[-1] == *little)
692 return (char*)bigend - 1;
696 /* This should be better than FBM if c1 == c2, and almost
697 as good otherwise: maybe better since we do less indirection.
698 And we save a lot of memory by caching no table. */
699 const unsigned char c1 = little[0];
700 const unsigned char c2 = little[1];
705 while (s <= bigend) {
715 goto check_1char_anchor;
726 goto check_1char_anchor;
729 while (s <= bigend) {
734 goto check_1char_anchor;
743 check_1char_anchor: /* One char and anchor! */
744 if (SvTAIL(littlestr) && (*bigend == *little))
745 return (char *)bigend; /* bigend is already decremented. */
748 break; /* Only lengths 0 1 and 2 have special-case code. */
751 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
752 s = bigend - littlelen;
753 if (s >= big && bigend[-1] == '\n' && *s == *little
754 /* Automatically of length > 2 */
755 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
757 return (char*)s; /* how sweet it is */
760 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
762 return (char*)s + 1; /* how sweet it is */
766 if (!SvVALID(littlestr)) {
767 char * const b = ninstr((char*)big,(char*)bigend,
768 (char*)little, (char*)little + littlelen);
770 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
771 /* Chop \n from littlestr: */
772 s = bigend - littlelen + 1;
774 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
784 if (littlelen > (STRLEN)(bigend - big))
788 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
789 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
790 register const unsigned char *oldlittle;
792 --littlelen; /* Last char found by table lookup */
795 little += littlelen; /* last char */
801 if ((tmp = table[*s])) {
802 if ((s += tmp) < bigend)
806 else { /* less expensive than calling strncmp() */
807 register unsigned char * const olds = s;
812 if (*--s == *--little)
814 s = olds + 1; /* here we pay the price for failure */
816 if (s < bigend) /* fake up continue to outer loop */
826 && memEQ((char *)(bigend - littlelen),
827 (char *)(oldlittle - littlelen), littlelen) )
828 return (char*)bigend - littlelen;
833 /* start_shift, end_shift are positive quantities which give offsets
834 of ends of some substring of bigstr.
835 If "last" we want the last occurrence.
836 old_posp is the way of communication between consequent calls if
837 the next call needs to find the .
838 The initial *old_posp should be -1.
840 Note that we take into account SvTAIL, so one can get extra
841 optimizations if _ALL flag is set.
844 /* If SvTAIL is actually due to \Z or \z, this gives false positives
845 if PL_multiline. In fact if !PL_multiline the authoritative answer
846 is not supported yet. */
849 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
852 register const unsigned char *big;
853 U32 pos = 0; /* hush a gcc warning */
854 register I32 previous;
856 register const unsigned char *little;
857 register I32 stop_pos;
858 register const unsigned char *littleend;
861 const void *screamnext_raw = NULL; /* hush a gcc warning */
862 bool cant_find = FALSE; /* hush a gcc warning */
864 PERL_ARGS_ASSERT_SCREAMINSTR;
866 assert(SvMAGICAL(bigstr));
867 mg = mg_find(bigstr, PERL_MAGIC_study);
869 assert(SvTYPE(littlestr) == SVt_PVMG);
870 assert(SvVALID(littlestr));
872 if (mg->mg_private == 1) {
873 const U8 *const screamfirst = (U8 *)mg->mg_ptr;
874 const U8 *const screamnext = screamfirst + 256;
876 screamnext_raw = (const void *)screamnext;
878 pos = *old_posp == -1
879 ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
880 cant_find = pos == (U8)~0;
881 } else if (mg->mg_private == 2) {
882 const U16 *const screamfirst = (U16 *)mg->mg_ptr;
883 const U16 *const screamnext = screamfirst + 256;
885 screamnext_raw = (const void *)screamnext;
887 pos = *old_posp == -1
888 ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
889 cant_find = pos == (U16)~0;
890 } else if (mg->mg_private == 4) {
891 const U32 *const screamfirst = (U32 *)mg->mg_ptr;
892 const U32 *const screamnext = screamfirst + 256;
894 screamnext_raw = (const void *)screamnext;
896 pos = *old_posp == -1
897 ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
898 cant_find = pos == (U32)~0;
900 Perl_croak(aTHX_ "panic: unknown study size %u", mg->mg_private);
904 if ( BmRARE(littlestr) == '\n'
905 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
906 little = (const unsigned char *)(SvPVX_const(littlestr));
907 littleend = little + SvCUR(littlestr);
914 little = (const unsigned char *)(SvPVX_const(littlestr));
915 littleend = little + SvCUR(littlestr);
917 /* The value of pos we can start at: */
918 previous = BmPREVIOUS(littlestr);
919 big = (const unsigned char *)(SvPVX_const(bigstr));
920 /* The value of pos we can stop at: */
921 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
922 if (previous + start_shift > stop_pos) {
924 stop_pos does not include SvTAIL in the count, so this check is incorrect
925 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
928 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
933 if (mg->mg_private == 1) {
934 const U8 *const screamnext = (const U8 *const) screamnext_raw;
935 while ((I32)pos < previous + start_shift) {
936 pos = screamnext[pos];
940 } else if (mg->mg_private == 2) {
941 const U16 *const screamnext = (const U16 *const) screamnext_raw;
942 while ((I32)pos < previous + start_shift) {
943 pos = screamnext[pos];
947 } else if (mg->mg_private == 4) {
948 const U32 *const screamnext = (const U32 *const) screamnext_raw;
949 while ((I32)pos < previous + start_shift) {
950 pos = screamnext[pos];
957 if ((I32)pos >= stop_pos) break;
958 if (big[pos] == first) {
959 const unsigned char *s = little;
960 const unsigned char *x = big + pos + 1;
961 while (s < littleend) {
966 if (s == littleend) {
967 *old_posp = (I32)pos;
968 if (!last) return (char *)(big+pos);
972 if (mg->mg_private == 1) {
973 pos = ((const U8 *const)screamnext_raw)[pos];
976 } else if (mg->mg_private == 2) {
977 pos = ((const U16 *const)screamnext_raw)[pos];
980 } else if (mg->mg_private == 4) {
981 pos = ((const U32 *const)screamnext_raw)[pos];
987 return (char *)(big+(*old_posp));
989 if (!SvTAIL(littlestr) || (end_shift > 0))
991 /* Ignore the trailing "\n". This code is not microoptimized */
992 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
993 stop_pos = littleend - little; /* Actual littlestr len */
998 && ((stop_pos == 1) ||
999 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
1007 Returns true if the leading len bytes of the strings s1 and s2 are the same
1008 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
1009 match themselves and their opposite case counterparts. Non-cased and non-ASCII
1010 range bytes match only themselves.
1017 Perl_foldEQ(const char *s1, const char *s2, register I32 len)
1019 register const U8 *a = (const U8 *)s1;
1020 register const U8 *b = (const U8 *)s2;
1022 PERL_ARGS_ASSERT_FOLDEQ;
1025 if (*a != *b && *a != PL_fold[*b])
1032 Perl_foldEQ_latin1(const char *s1, const char *s2, register I32 len)
1034 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
1035 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
1036 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
1037 * does it check that the strings each have at least 'len' characters */
1039 register const U8 *a = (const U8 *)s1;
1040 register const U8 *b = (const U8 *)s2;
1042 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
1045 if (*a != *b && *a != PL_fold_latin1[*b]) {
1054 =for apidoc foldEQ_locale
1056 Returns true if the leading len bytes of the strings s1 and s2 are the same
1057 case-insensitively in the current locale; false otherwise.
1063 Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
1066 register const U8 *a = (const U8 *)s1;
1067 register const U8 *b = (const U8 *)s2;
1069 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
1072 if (*a != *b && *a != PL_fold_locale[*b])
1079 /* copy a string to a safe spot */
1082 =head1 Memory Management
1086 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1087 string which is a duplicate of C<pv>. The size of the string is
1088 determined by C<strlen()>. The memory allocated for the new string can
1089 be freed with the C<Safefree()> function.
1095 Perl_savepv(pTHX_ const char *pv)
1097 PERL_UNUSED_CONTEXT;
1102 const STRLEN pvlen = strlen(pv)+1;
1103 Newx(newaddr, pvlen, char);
1104 return (char*)memcpy(newaddr, pv, pvlen);
1108 /* same thing but with a known length */
1113 Perl's version of what C<strndup()> would be if it existed. Returns a
1114 pointer to a newly allocated string which is a duplicate of the first
1115 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
1116 the new string can be freed with the C<Safefree()> function.
1122 Perl_savepvn(pTHX_ const char *pv, register I32 len)
1124 register char *newaddr;
1125 PERL_UNUSED_CONTEXT;
1127 Newx(newaddr,len+1,char);
1128 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1130 /* might not be null terminated */
1131 newaddr[len] = '\0';
1132 return (char *) CopyD(pv,newaddr,len,char);
1135 return (char *) ZeroD(newaddr,len+1,char);
1140 =for apidoc savesharedpv
1142 A version of C<savepv()> which allocates the duplicate string in memory
1143 which is shared between threads.
1148 Perl_savesharedpv(pTHX_ const char *pv)
1150 register char *newaddr;
1155 pvlen = strlen(pv)+1;
1156 newaddr = (char*)PerlMemShared_malloc(pvlen);
1158 return write_no_mem();
1160 return (char*)memcpy(newaddr, pv, pvlen);
1164 =for apidoc savesharedpvn
1166 A version of C<savepvn()> which allocates the duplicate string in memory
1167 which is shared between threads. (With the specific difference that a NULL
1168 pointer is not acceptable)
1173 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1175 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1177 PERL_ARGS_ASSERT_SAVESHAREDPVN;
1180 return write_no_mem();
1182 newaddr[len] = '\0';
1183 return (char*)memcpy(newaddr, pv, len);
1187 =for apidoc savesvpv
1189 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1190 the passed in SV using C<SvPV()>
1196 Perl_savesvpv(pTHX_ SV *sv)
1199 const char * const pv = SvPV_const(sv, len);
1200 register char *newaddr;
1202 PERL_ARGS_ASSERT_SAVESVPV;
1205 Newx(newaddr,len,char);
1206 return (char *) CopyD(pv,newaddr,len,char);
1210 =for apidoc savesharedsvpv
1212 A version of C<savesharedpv()> which allocates the duplicate string in
1213 memory which is shared between threads.
1219 Perl_savesharedsvpv(pTHX_ SV *sv)
1222 const char * const pv = SvPV_const(sv, len);
1224 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1226 return savesharedpvn(pv, len);
1229 /* the SV for Perl_form() and mess() is not kept in an arena */
1238 if (PL_phase != PERL_PHASE_DESTRUCT)
1239 return newSVpvs_flags("", SVs_TEMP);
1244 /* Create as PVMG now, to avoid any upgrading later */
1246 Newxz(any, 1, XPVMG);
1247 SvFLAGS(sv) = SVt_PVMG;
1248 SvANY(sv) = (void*)any;
1250 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1255 #if defined(PERL_IMPLICIT_CONTEXT)
1257 Perl_form_nocontext(const char* pat, ...)
1262 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1263 va_start(args, pat);
1264 retval = vform(pat, &args);
1268 #endif /* PERL_IMPLICIT_CONTEXT */
1271 =head1 Miscellaneous Functions
1274 Takes a sprintf-style format pattern and conventional
1275 (non-SV) arguments and returns the formatted string.
1277 (char *) Perl_form(pTHX_ const char* pat, ...)
1279 can be used any place a string (char *) is required:
1281 char * s = Perl_form("%d.%d",major,minor);
1283 Uses a single private buffer so if you want to format several strings you
1284 must explicitly copy the earlier strings away (and free the copies when you
1291 Perl_form(pTHX_ const char* pat, ...)
1295 PERL_ARGS_ASSERT_FORM;
1296 va_start(args, pat);
1297 retval = vform(pat, &args);
1303 Perl_vform(pTHX_ const char *pat, va_list *args)
1305 SV * const sv = mess_alloc();
1306 PERL_ARGS_ASSERT_VFORM;
1307 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1312 =for apidoc Am|SV *|mess|const char *pat|...
1314 Take a sprintf-style format pattern and argument list. These are used to
1315 generate a string message. If the message does not end with a newline,
1316 then it will be extended with some indication of the current location
1317 in the code, as described for L</mess_sv>.
1319 Normally, the resulting message is returned in a new mortal SV.
1320 During global destruction a single SV may be shared between uses of
1326 #if defined(PERL_IMPLICIT_CONTEXT)
1328 Perl_mess_nocontext(const char *pat, ...)
1333 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1334 va_start(args, pat);
1335 retval = vmess(pat, &args);
1339 #endif /* PERL_IMPLICIT_CONTEXT */
1342 Perl_mess(pTHX_ const char *pat, ...)
1346 PERL_ARGS_ASSERT_MESS;
1347 va_start(args, pat);
1348 retval = vmess(pat, &args);
1354 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1357 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1359 PERL_ARGS_ASSERT_CLOSEST_COP;
1361 if (!o || o == PL_op)
1364 if (o->op_flags & OPf_KIDS) {
1366 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1369 /* If the OP_NEXTSTATE has been optimised away we can still use it
1370 * the get the file and line number. */
1372 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1373 cop = (const COP *)kid;
1375 /* Keep searching, and return when we've found something. */
1377 new_cop = closest_cop(cop, kid);
1383 /* Nothing found. */
1389 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1391 Expands a message, intended for the user, to include an indication of
1392 the current location in the code, if the message does not already appear
1395 C<basemsg> is the initial message or object. If it is a reference, it
1396 will be used as-is and will be the result of this function. Otherwise it
1397 is used as a string, and if it already ends with a newline, it is taken
1398 to be complete, and the result of this function will be the same string.
1399 If the message does not end with a newline, then a segment such as C<at
1400 foo.pl line 37> will be appended, and possibly other clauses indicating
1401 the current state of execution. The resulting message will end with a
1404 Normally, the resulting message is returned in a new mortal SV.
1405 During global destruction a single SV may be shared between uses of this
1406 function. If C<consume> is true, then the function is permitted (but not
1407 required) to modify and return C<basemsg> instead of allocating a new SV.
1413 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1418 PERL_ARGS_ASSERT_MESS_SV;
1420 if (SvROK(basemsg)) {
1426 sv_setsv(sv, basemsg);
1431 if (SvPOK(basemsg) && consume) {
1436 sv_copypv(sv, basemsg);
1439 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1441 * Try and find the file and line for PL_op. This will usually be
1442 * PL_curcop, but it might be a cop that has been optimised away. We
1443 * can try to find such a cop by searching through the optree starting
1444 * from the sibling of PL_curcop.
1447 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1452 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1453 OutCopFILE(cop), (IV)CopLINE(cop));
1454 /* Seems that GvIO() can be untrustworthy during global destruction. */
1455 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1456 && IoLINES(GvIOp(PL_last_in_gv)))
1458 const bool line_mode = (RsSIMPLE(PL_rs) &&
1459 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1460 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1461 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1462 line_mode ? "line" : "chunk",
1463 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1465 if (PL_phase == PERL_PHASE_DESTRUCT)
1466 sv_catpvs(sv, " during global destruction");
1467 sv_catpvs(sv, ".\n");
1473 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1475 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1476 argument list. These are used to generate a string message. If the
1477 message does not end with a newline, then it will be extended with
1478 some indication of the current location in the code, as described for
1481 Normally, the resulting message is returned in a new mortal SV.
1482 During global destruction a single SV may be shared between uses of
1489 Perl_vmess(pTHX_ const char *pat, va_list *args)
1492 SV * const sv = mess_alloc();
1494 PERL_ARGS_ASSERT_VMESS;
1496 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1497 return mess_sv(sv, 1);
1501 Perl_write_to_stderr(pTHX_ SV* msv)
1507 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1509 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1510 && (io = GvIO(PL_stderrgv))
1511 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1512 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1513 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1516 /* SFIO can really mess with your errno */
1519 PerlIO * const serr = Perl_error_log;
1521 do_print(msv, serr);
1522 (void)PerlIO_flush(serr);
1530 =head1 Warning and Dieing
1533 /* Common code used in dieing and warning */
1536 S_with_queued_errors(pTHX_ SV *ex)
1538 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1539 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1540 sv_catsv(PL_errors, ex);
1541 ex = sv_mortalcopy(PL_errors);
1542 SvCUR_set(PL_errors, 0);
1548 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1554 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1555 /* sv_2cv might call Perl_croak() or Perl_warner() */
1556 SV * const oldhook = *hook;
1564 cv = sv_2cv(oldhook, &stash, &gv, 0);
1566 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1576 exarg = newSVsv(ex);
1577 SvREADONLY_on(exarg);
1580 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1584 call_sv(MUTABLE_SV(cv), G_DISCARD);
1593 =for apidoc Am|OP *|die_sv|SV *baseex
1595 Behaves the same as L</croak_sv>, except for the return type.
1596 It should be used only where the C<OP *> return type is required.
1597 The function never actually returns.
1603 Perl_die_sv(pTHX_ SV *baseex)
1605 PERL_ARGS_ASSERT_DIE_SV;
1612 =for apidoc Am|OP *|die|const char *pat|...
1614 Behaves the same as L</croak>, except for the return type.
1615 It should be used only where the C<OP *> return type is required.
1616 The function never actually returns.
1621 #if defined(PERL_IMPLICIT_CONTEXT)
1623 Perl_die_nocontext(const char* pat, ...)
1627 va_start(args, pat);
1633 #endif /* PERL_IMPLICIT_CONTEXT */
1636 Perl_die(pTHX_ const char* pat, ...)
1639 va_start(args, pat);
1647 =for apidoc Am|void|croak_sv|SV *baseex
1649 This is an XS interface to Perl's C<die> function.
1651 C<baseex> is the error message or object. If it is a reference, it
1652 will be used as-is. Otherwise it is used as a string, and if it does
1653 not end with a newline then it will be extended with some indication of
1654 the current location in the code, as described for L</mess_sv>.
1656 The error message or object will be used as an exception, by default
1657 returning control to the nearest enclosing C<eval>, but subject to
1658 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1659 function never returns normally.
1661 To die with a simple string message, the L</croak> function may be
1668 Perl_croak_sv(pTHX_ SV *baseex)
1670 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1671 PERL_ARGS_ASSERT_CROAK_SV;
1672 invoke_exception_hook(ex, FALSE);
1677 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1679 This is an XS interface to Perl's C<die> function.
1681 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1682 argument list. These are used to generate a string message. If the
1683 message does not end with a newline, then it will be extended with
1684 some indication of the current location in the code, as described for
1687 The error message will be used as an exception, by default
1688 returning control to the nearest enclosing C<eval>, but subject to
1689 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1690 function never returns normally.
1692 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1693 (C<$@>) will be used as an error message or object instead of building an
1694 error message from arguments. If you want to throw a non-string object,
1695 or build an error message in an SV yourself, it is preferable to use
1696 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1702 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1704 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1705 invoke_exception_hook(ex, FALSE);
1710 =for apidoc Am|void|croak|const char *pat|...
1712 This is an XS interface to Perl's C<die> function.
1714 Take a sprintf-style format pattern and argument list. These are used to
1715 generate a string message. If the message does not end with a newline,
1716 then it will be extended with some indication of the current location
1717 in the code, as described for L</mess_sv>.
1719 The error message will be used as an exception, by default
1720 returning control to the nearest enclosing C<eval>, but subject to
1721 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1722 function never returns normally.
1724 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1725 (C<$@>) will be used as an error message or object instead of building an
1726 error message from arguments. If you want to throw a non-string object,
1727 or build an error message in an SV yourself, it is preferable to use
1728 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1733 #if defined(PERL_IMPLICIT_CONTEXT)
1735 Perl_croak_nocontext(const char *pat, ...)
1739 va_start(args, pat);
1744 #endif /* PERL_IMPLICIT_CONTEXT */
1747 Perl_croak(pTHX_ const char *pat, ...)
1750 va_start(args, pat);
1757 =for apidoc Am|void|croak_no_modify
1759 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1760 terser object code than using C<Perl_croak>. Less code used on exception code
1761 paths reduces CPU cache pressure.
1767 Perl_croak_no_modify(pTHX)
1769 Perl_croak(aTHX_ "%s", PL_no_modify);
1773 =for apidoc Am|void|warn_sv|SV *baseex
1775 This is an XS interface to Perl's C<warn> function.
1777 C<baseex> is the error message or object. If it is a reference, it
1778 will be used as-is. Otherwise it is used as a string, and if it does
1779 not end with a newline then it will be extended with some indication of
1780 the current location in the code, as described for L</mess_sv>.
1782 The error message or object will by default be written to standard error,
1783 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1785 To warn with a simple string message, the L</warn> function may be
1792 Perl_warn_sv(pTHX_ SV *baseex)
1794 SV *ex = mess_sv(baseex, 0);
1795 PERL_ARGS_ASSERT_WARN_SV;
1796 if (!invoke_exception_hook(ex, TRUE))
1797 write_to_stderr(ex);
1801 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1803 This is an XS interface to Perl's C<warn> function.
1805 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1806 argument list. These are used to generate a string message. If the
1807 message does not end with a newline, then it will be extended with
1808 some indication of the current location in the code, as described for
1811 The error message or object will by default be written to standard error,
1812 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1814 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1820 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1822 SV *ex = vmess(pat, args);
1823 PERL_ARGS_ASSERT_VWARN;
1824 if (!invoke_exception_hook(ex, TRUE))
1825 write_to_stderr(ex);
1829 =for apidoc Am|void|warn|const char *pat|...
1831 This is an XS interface to Perl's C<warn> function.
1833 Take a sprintf-style format pattern and argument list. These are used to
1834 generate a string message. If the message does not end with a newline,
1835 then it will be extended with some indication of the current location
1836 in the code, as described for L</mess_sv>.
1838 The error message or object will by default be written to standard error,
1839 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1841 Unlike with L</croak>, C<pat> is not permitted to be null.
1846 #if defined(PERL_IMPLICIT_CONTEXT)
1848 Perl_warn_nocontext(const char *pat, ...)
1852 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1853 va_start(args, pat);
1857 #endif /* PERL_IMPLICIT_CONTEXT */
1860 Perl_warn(pTHX_ const char *pat, ...)
1863 PERL_ARGS_ASSERT_WARN;
1864 va_start(args, pat);
1869 #if defined(PERL_IMPLICIT_CONTEXT)
1871 Perl_warner_nocontext(U32 err, const char *pat, ...)
1875 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1876 va_start(args, pat);
1877 vwarner(err, pat, &args);
1880 #endif /* PERL_IMPLICIT_CONTEXT */
1883 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1885 PERL_ARGS_ASSERT_CK_WARNER_D;
1887 if (Perl_ckwarn_d(aTHX_ err)) {
1889 va_start(args, pat);
1890 vwarner(err, pat, &args);
1896 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1898 PERL_ARGS_ASSERT_CK_WARNER;
1900 if (Perl_ckwarn(aTHX_ err)) {
1902 va_start(args, pat);
1903 vwarner(err, pat, &args);
1909 Perl_warner(pTHX_ U32 err, const char* pat,...)
1912 PERL_ARGS_ASSERT_WARNER;
1913 va_start(args, pat);
1914 vwarner(err, pat, &args);
1919 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1922 PERL_ARGS_ASSERT_VWARNER;
1923 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1924 SV * const msv = vmess(pat, args);
1926 invoke_exception_hook(msv, FALSE);
1930 Perl_vwarn(aTHX_ pat, args);
1934 /* implements the ckWARN? macros */
1937 Perl_ckwarn(pTHX_ U32 w)
1940 /* If lexical warnings have not been set, use $^W. */
1942 return PL_dowarn & G_WARN_ON;
1944 return ckwarn_common(w);
1947 /* implements the ckWARN?_d macro */
1950 Perl_ckwarn_d(pTHX_ U32 w)
1953 /* If lexical warnings have not been set then default classes warn. */
1957 return ckwarn_common(w);
1961 S_ckwarn_common(pTHX_ U32 w)
1963 if (PL_curcop->cop_warnings == pWARN_ALL)
1966 if (PL_curcop->cop_warnings == pWARN_NONE)
1969 /* Check the assumption that at least the first slot is non-zero. */
1970 assert(unpackWARN1(w));
1972 /* Check the assumption that it is valid to stop as soon as a zero slot is
1974 if (!unpackWARN2(w)) {
1975 assert(!unpackWARN3(w));
1976 assert(!unpackWARN4(w));
1977 } else if (!unpackWARN3(w)) {
1978 assert(!unpackWARN4(w));
1981 /* Right, dealt with all the special cases, which are implemented as non-
1982 pointers, so there is a pointer to a real warnings mask. */
1984 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1986 } while (w >>= WARNshift);
1991 /* Set buffer=NULL to get a new one. */
1993 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1995 const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
1996 PERL_UNUSED_CONTEXT;
1997 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
2000 (specialWARN(buffer) ?
2001 PerlMemShared_malloc(len_wanted) :
2002 PerlMemShared_realloc(buffer, len_wanted));
2004 Copy(bits, (buffer + 1), size, char);
2008 /* since we've already done strlen() for both nam and val
2009 * we can use that info to make things faster than
2010 * sprintf(s, "%s=%s", nam, val)
2012 #define my_setenv_format(s, nam, nlen, val, vlen) \
2013 Copy(nam, s, nlen, char); \
2015 Copy(val, s+(nlen+1), vlen, char); \
2016 *(s+(nlen+1+vlen)) = '\0'
2018 #ifdef USE_ENVIRON_ARRAY
2019 /* VMS' my_setenv() is in vms.c */
2020 #if !defined(WIN32) && !defined(NETWARE)
2022 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2026 /* only parent thread can modify process environment */
2027 if (PL_curinterp == aTHX)
2030 #ifndef PERL_USE_SAFE_PUTENV
2031 if (!PL_use_safe_putenv) {
2032 /* most putenv()s leak, so we manipulate environ directly */
2034 register const I32 len = strlen(nam);
2037 /* where does it go? */
2038 for (i = 0; environ[i]; i++) {
2039 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
2043 if (environ == PL_origenviron) { /* need we copy environment? */
2049 while (environ[max])
2051 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2052 for (j=0; j<max; j++) { /* copy environment */
2053 const int len = strlen(environ[j]);
2054 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2055 Copy(environ[j], tmpenv[j], len+1, char);
2058 environ = tmpenv; /* tell exec where it is now */
2061 safesysfree(environ[i]);
2062 while (environ[i]) {
2063 environ[i] = environ[i+1];
2068 if (!environ[i]) { /* does not exist yet */
2069 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2070 environ[i+1] = NULL; /* make sure it's null terminated */
2073 safesysfree(environ[i]);
2077 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2078 /* all that work just for this */
2079 my_setenv_format(environ[i], nam, nlen, val, vlen);
2082 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
2083 # if defined(HAS_UNSETENV)
2085 (void)unsetenv(nam);
2087 (void)setenv(nam, val, 1);
2089 # else /* ! HAS_UNSETENV */
2090 (void)setenv(nam, val, 1);
2091 # endif /* HAS_UNSETENV */
2093 # if defined(HAS_UNSETENV)
2095 (void)unsetenv(nam);
2097 const int nlen = strlen(nam);
2098 const int vlen = strlen(val);
2099 char * const new_env =
2100 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2101 my_setenv_format(new_env, nam, nlen, val, vlen);
2102 (void)putenv(new_env);
2104 # else /* ! HAS_UNSETENV */
2106 const int nlen = strlen(nam);
2112 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2113 /* all that work just for this */
2114 my_setenv_format(new_env, nam, nlen, val, vlen);
2115 (void)putenv(new_env);
2116 # endif /* HAS_UNSETENV */
2117 # endif /* __CYGWIN__ */
2118 #ifndef PERL_USE_SAFE_PUTENV
2124 #else /* WIN32 || NETWARE */
2127 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2130 register char *envstr;
2131 const int nlen = strlen(nam);
2138 Newx(envstr, nlen+vlen+2, char);
2139 my_setenv_format(envstr, nam, nlen, val, vlen);
2140 (void)PerlEnv_putenv(envstr);
2144 #endif /* WIN32 || NETWARE */
2146 #endif /* !VMS && !EPOC*/
2148 #ifdef UNLINK_ALL_VERSIONS
2150 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2154 PERL_ARGS_ASSERT_UNLNK;
2156 while (PerlLIO_unlink(f) >= 0)
2158 return retries ? 0 : -1;
2162 /* this is a drop-in replacement for bcopy() */
2163 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2165 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2167 char * const retval = to;
2169 PERL_ARGS_ASSERT_MY_BCOPY;
2171 if (from - to >= 0) {
2179 *(--to) = *(--from);
2185 /* this is a drop-in replacement for memset() */
2188 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2190 char * const retval = loc;
2192 PERL_ARGS_ASSERT_MY_MEMSET;
2200 /* this is a drop-in replacement for bzero() */
2201 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2203 Perl_my_bzero(register char *loc, register I32 len)
2205 char * const retval = loc;
2207 PERL_ARGS_ASSERT_MY_BZERO;
2215 /* this is a drop-in replacement for memcmp() */
2216 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2218 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2220 register const U8 *a = (const U8 *)s1;
2221 register const U8 *b = (const U8 *)s2;
2224 PERL_ARGS_ASSERT_MY_MEMCMP;
2227 if ((tmp = *a++ - *b++))
2232 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2235 /* This vsprintf replacement should generally never get used, since
2236 vsprintf was available in both System V and BSD 2.11. (There may
2237 be some cross-compilation or embedded set-ups where it is needed,
2240 If you encounter a problem in this function, it's probably a symptom
2241 that Configure failed to detect your system's vprintf() function.
2242 See the section on "item vsprintf" in the INSTALL file.
2244 This version may compile on systems with BSD-ish <stdio.h>,
2245 but probably won't on others.
2248 #ifdef USE_CHAR_VSPRINTF
2253 vsprintf(char *dest, const char *pat, void *args)
2257 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2258 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2259 FILE_cnt(&fakebuf) = 32767;
2261 /* These probably won't compile -- If you really need
2262 this, you'll have to figure out some other method. */
2263 fakebuf._ptr = dest;
2264 fakebuf._cnt = 32767;
2269 fakebuf._flag = _IOWRT|_IOSTRG;
2270 _doprnt(pat, args, &fakebuf); /* what a kludge */
2271 #if defined(STDIO_PTR_LVALUE)
2272 *(FILE_ptr(&fakebuf)++) = '\0';
2274 /* PerlIO has probably #defined away fputc, but we want it here. */
2276 # undef fputc /* XXX Should really restore it later */
2278 (void)fputc('\0', &fakebuf);
2280 #ifdef USE_CHAR_VSPRINTF
2283 return 0; /* perl doesn't use return value */
2287 #endif /* HAS_VPRINTF */
2290 #if BYTEORDER != 0x4321
2292 Perl_my_swap(pTHX_ short s)
2294 #if (BYTEORDER & 1) == 0
2297 result = ((s & 255) << 8) + ((s >> 8) & 255);
2305 Perl_my_htonl(pTHX_ long l)
2309 char c[sizeof(long)];
2312 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2313 #if BYTEORDER == 0x12345678
2316 u.c[0] = (l >> 24) & 255;
2317 u.c[1] = (l >> 16) & 255;
2318 u.c[2] = (l >> 8) & 255;
2322 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2323 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2328 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2329 u.c[o & 0xf] = (l >> s) & 255;
2337 Perl_my_ntohl(pTHX_ long l)
2341 char c[sizeof(long)];
2344 #if BYTEORDER == 0x1234
2345 u.c[0] = (l >> 24) & 255;
2346 u.c[1] = (l >> 16) & 255;
2347 u.c[2] = (l >> 8) & 255;
2351 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2352 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2359 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2360 l |= (u.c[o & 0xf] & 255) << s;
2367 #endif /* BYTEORDER != 0x4321 */
2371 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2372 * If these functions are defined,
2373 * the BYTEORDER is neither 0x1234 nor 0x4321.
2374 * However, this is not assumed.
2378 #define HTOLE(name,type) \
2380 name (register type n) \
2384 char c[sizeof(type)]; \
2387 register U32 s = 0; \
2388 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2389 u.c[i] = (n >> s) & 0xFF; \
2394 #define LETOH(name,type) \
2396 name (register type n) \
2400 char c[sizeof(type)]; \
2403 register U32 s = 0; \
2406 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2407 n |= ((type)(u.c[i] & 0xFF)) << s; \
2413 * Big-endian byte order functions.
2416 #define HTOBE(name,type) \
2418 name (register type n) \
2422 char c[sizeof(type)]; \
2425 register U32 s = 8*(sizeof(u.c)-1); \
2426 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2427 u.c[i] = (n >> s) & 0xFF; \
2432 #define BETOH(name,type) \
2434 name (register type n) \
2438 char c[sizeof(type)]; \
2441 register U32 s = 8*(sizeof(u.c)-1); \
2444 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2445 n |= ((type)(u.c[i] & 0xFF)) << s; \
2451 * If we just can't do it...
2454 #define NOT_AVAIL(name,type) \
2456 name (register type n) \
2458 Perl_croak_nocontext(#name "() not available"); \
2459 return n; /* not reached */ \
2463 #if defined(HAS_HTOVS) && !defined(htovs)
2466 #if defined(HAS_HTOVL) && !defined(htovl)
2469 #if defined(HAS_VTOHS) && !defined(vtohs)
2472 #if defined(HAS_VTOHL) && !defined(vtohl)
2476 #ifdef PERL_NEED_MY_HTOLE16
2478 HTOLE(Perl_my_htole16,U16)
2480 NOT_AVAIL(Perl_my_htole16,U16)
2483 #ifdef PERL_NEED_MY_LETOH16
2485 LETOH(Perl_my_letoh16,U16)
2487 NOT_AVAIL(Perl_my_letoh16,U16)
2490 #ifdef PERL_NEED_MY_HTOBE16
2492 HTOBE(Perl_my_htobe16,U16)
2494 NOT_AVAIL(Perl_my_htobe16,U16)
2497 #ifdef PERL_NEED_MY_BETOH16
2499 BETOH(Perl_my_betoh16,U16)
2501 NOT_AVAIL(Perl_my_betoh16,U16)
2505 #ifdef PERL_NEED_MY_HTOLE32
2507 HTOLE(Perl_my_htole32,U32)
2509 NOT_AVAIL(Perl_my_htole32,U32)
2512 #ifdef PERL_NEED_MY_LETOH32
2514 LETOH(Perl_my_letoh32,U32)
2516 NOT_AVAIL(Perl_my_letoh32,U32)
2519 #ifdef PERL_NEED_MY_HTOBE32
2521 HTOBE(Perl_my_htobe32,U32)
2523 NOT_AVAIL(Perl_my_htobe32,U32)
2526 #ifdef PERL_NEED_MY_BETOH32
2528 BETOH(Perl_my_betoh32,U32)
2530 NOT_AVAIL(Perl_my_betoh32,U32)
2534 #ifdef PERL_NEED_MY_HTOLE64
2536 HTOLE(Perl_my_htole64,U64)
2538 NOT_AVAIL(Perl_my_htole64,U64)
2541 #ifdef PERL_NEED_MY_LETOH64
2543 LETOH(Perl_my_letoh64,U64)
2545 NOT_AVAIL(Perl_my_letoh64,U64)
2548 #ifdef PERL_NEED_MY_HTOBE64
2550 HTOBE(Perl_my_htobe64,U64)
2552 NOT_AVAIL(Perl_my_htobe64,U64)
2555 #ifdef PERL_NEED_MY_BETOH64
2557 BETOH(Perl_my_betoh64,U64)
2559 NOT_AVAIL(Perl_my_betoh64,U64)
2563 #ifdef PERL_NEED_MY_HTOLES
2564 HTOLE(Perl_my_htoles,short)
2566 #ifdef PERL_NEED_MY_LETOHS
2567 LETOH(Perl_my_letohs,short)
2569 #ifdef PERL_NEED_MY_HTOBES
2570 HTOBE(Perl_my_htobes,short)
2572 #ifdef PERL_NEED_MY_BETOHS
2573 BETOH(Perl_my_betohs,short)
2576 #ifdef PERL_NEED_MY_HTOLEI
2577 HTOLE(Perl_my_htolei,int)
2579 #ifdef PERL_NEED_MY_LETOHI
2580 LETOH(Perl_my_letohi,int)
2582 #ifdef PERL_NEED_MY_HTOBEI
2583 HTOBE(Perl_my_htobei,int)
2585 #ifdef PERL_NEED_MY_BETOHI
2586 BETOH(Perl_my_betohi,int)
2589 #ifdef PERL_NEED_MY_HTOLEL
2590 HTOLE(Perl_my_htolel,long)
2592 #ifdef PERL_NEED_MY_LETOHL
2593 LETOH(Perl_my_letohl,long)
2595 #ifdef PERL_NEED_MY_HTOBEL
2596 HTOBE(Perl_my_htobel,long)
2598 #ifdef PERL_NEED_MY_BETOHL
2599 BETOH(Perl_my_betohl,long)
2603 Perl_my_swabn(void *ptr, int n)
2605 register char *s = (char *)ptr;
2606 register char *e = s + (n-1);
2609 PERL_ARGS_ASSERT_MY_SWABN;
2611 for (n /= 2; n > 0; s++, e--, n--) {
2619 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2621 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2624 register I32 This, that;
2630 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2632 PERL_FLUSHALL_FOR_CHILD;
2633 This = (*mode == 'w');
2637 taint_proper("Insecure %s%s", "EXEC");
2639 if (PerlProc_pipe(p) < 0)
2641 /* Try for another pipe pair for error return */
2642 if (PerlProc_pipe(pp) >= 0)
2644 while ((pid = PerlProc_fork()) < 0) {
2645 if (errno != EAGAIN) {
2646 PerlLIO_close(p[This]);
2647 PerlLIO_close(p[that]);
2649 PerlLIO_close(pp[0]);
2650 PerlLIO_close(pp[1]);
2654 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2663 /* Close parent's end of error status pipe (if any) */
2665 PerlLIO_close(pp[0]);
2666 #if defined(HAS_FCNTL) && defined(F_SETFD)
2667 /* Close error pipe automatically if exec works */
2668 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2671 /* Now dup our end of _the_ pipe to right position */
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]); /* close parent's end of _the_ pipe */
2679 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2680 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2681 /* No automatic close - do it by hand */
2688 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2694 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2700 do_execfree(); /* free any memory malloced by child on fork */
2702 PerlLIO_close(pp[1]);
2703 /* Keep the lower of the two fd numbers */
2704 if (p[that] < p[This]) {
2705 PerlLIO_dup2(p[This], p[that]);
2706 PerlLIO_close(p[This]);
2710 PerlLIO_close(p[that]); /* close child's end of pipe */
2712 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2713 SvUPGRADE(sv,SVt_IV);
2715 PL_forkprocess = pid;
2716 /* If we managed to get status pipe check for exec fail */
2717 if (did_pipes && pid > 0) {
2722 while (n < sizeof(int)) {
2723 n1 = PerlLIO_read(pp[0],
2724 (void*)(((char*)&errkid)+n),
2730 PerlLIO_close(pp[0]);
2732 if (n) { /* Error */
2734 PerlLIO_close(p[This]);
2735 if (n != sizeof(int))
2736 Perl_croak(aTHX_ "panic: kid popen errno read");
2738 pid2 = wait4pid(pid, &status, 0);
2739 } while (pid2 == -1 && errno == EINTR);
2740 errno = errkid; /* Propagate errno from kid */
2745 PerlLIO_close(pp[0]);
2746 return PerlIO_fdopen(p[This], mode);
2748 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2749 return my_syspopen4(aTHX_ NULL, mode, n, args);
2751 Perl_croak(aTHX_ "List form of piped open not implemented");
2752 return (PerlIO *) NULL;
2757 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2758 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
2760 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2764 register I32 This, that;
2767 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2771 PERL_ARGS_ASSERT_MY_POPEN;
2773 PERL_FLUSHALL_FOR_CHILD;
2776 return my_syspopen(aTHX_ cmd,mode);
2779 This = (*mode == 'w');
2781 if (doexec && PL_tainting) {
2783 taint_proper("Insecure %s%s", "EXEC");
2785 if (PerlProc_pipe(p) < 0)
2787 if (doexec && PerlProc_pipe(pp) >= 0)
2789 while ((pid = PerlProc_fork()) < 0) {
2790 if (errno != EAGAIN) {
2791 PerlLIO_close(p[This]);
2792 PerlLIO_close(p[that]);
2794 PerlLIO_close(pp[0]);
2795 PerlLIO_close(pp[1]);
2798 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2801 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2811 PerlLIO_close(pp[0]);
2812 #if defined(HAS_FCNTL) && defined(F_SETFD)
2813 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2816 if (p[THIS] != (*mode == 'r')) {
2817 PerlLIO_dup2(p[THIS], *mode == 'r');
2818 PerlLIO_close(p[THIS]);
2819 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2820 PerlLIO_close(p[THAT]);
2823 PerlLIO_close(p[THAT]);
2826 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2833 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2838 /* may or may not use the shell */
2839 do_exec3(cmd, pp[1], did_pipes);
2842 #endif /* defined OS2 */
2844 #ifdef PERLIO_USING_CRLF
2845 /* Since we circumvent IO layers when we manipulate low-level
2846 filedescriptors directly, need to manually switch to the
2847 default, binary, low-level mode; see PerlIOBuf_open(). */
2848 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2850 #ifdef THREADS_HAVE_PIDS
2851 PL_ppid = (IV)getppid();
2854 #ifdef PERL_USES_PL_PIDSTATUS
2855 hv_clear(PL_pidstatus); /* we have no children */
2861 do_execfree(); /* free any memory malloced by child on vfork */
2863 PerlLIO_close(pp[1]);
2864 if (p[that] < p[This]) {
2865 PerlLIO_dup2(p[This], p[that]);
2866 PerlLIO_close(p[This]);
2870 PerlLIO_close(p[that]);
2872 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2873 SvUPGRADE(sv,SVt_IV);
2875 PL_forkprocess = pid;
2876 if (did_pipes && pid > 0) {
2881 while (n < sizeof(int)) {
2882 n1 = PerlLIO_read(pp[0],
2883 (void*)(((char*)&errkid)+n),
2889 PerlLIO_close(pp[0]);
2891 if (n) { /* Error */
2893 PerlLIO_close(p[This]);
2894 if (n != sizeof(int))
2895 Perl_croak(aTHX_ "panic: kid popen errno read");
2897 pid2 = wait4pid(pid, &status, 0);
2898 } while (pid2 == -1 && errno == EINTR);
2899 errno = errkid; /* Propagate errno from kid */
2904 PerlLIO_close(pp[0]);
2905 return PerlIO_fdopen(p[This], mode);
2908 #if defined(atarist) || defined(EPOC)
2911 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2913 PERL_ARGS_ASSERT_MY_POPEN;
2914 PERL_FLUSHALL_FOR_CHILD;
2915 /* Call system's popen() to get a FILE *, then import it.
2916 used 0 for 2nd parameter to PerlIO_importFILE;
2919 return PerlIO_importFILE(popen(cmd, mode), 0);
2923 FILE *djgpp_popen();
2925 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2927 PERL_FLUSHALL_FOR_CHILD;
2928 /* Call system's popen() to get a FILE *, then import it.
2929 used 0 for 2nd parameter to PerlIO_importFILE;
2932 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2935 #if defined(__LIBCATAMOUNT__)
2937 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2945 #endif /* !DOSISH */
2947 /* this is called in parent before the fork() */
2949 Perl_atfork_lock(void)
2952 #if defined(USE_ITHREADS)
2953 /* locks must be held in locking order (if any) */
2955 MUTEX_LOCK(&PL_malloc_mutex);
2961 /* this is called in both parent and child after the fork() */
2963 Perl_atfork_unlock(void)
2966 #if defined(USE_ITHREADS)
2967 /* locks must be released in same order as in atfork_lock() */
2969 MUTEX_UNLOCK(&PL_malloc_mutex);
2978 #if defined(HAS_FORK)
2980 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2985 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2986 * handlers elsewhere in the code */
2991 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2992 Perl_croak_nocontext("fork() not available");
2994 #endif /* HAS_FORK */
2999 Perl_dump_fds(pTHX_ const char *const s)
3004 PERL_ARGS_ASSERT_DUMP_FDS;
3006 PerlIO_printf(Perl_debug_log,"%s", s);
3007 for (fd = 0; fd < 32; fd++) {
3008 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
3009 PerlIO_printf(Perl_debug_log," %d",fd);
3011 PerlIO_printf(Perl_debug_log,"\n");
3014 #endif /* DUMP_FDS */
3018 dup2(int oldfd, int newfd)
3020 #if defined(HAS_FCNTL) && defined(F_DUPFD)
3023 PerlLIO_close(newfd);
3024 return fcntl(oldfd, F_DUPFD, newfd);
3026 #define DUP2_MAX_FDS 256
3027 int fdtmp[DUP2_MAX_FDS];
3033 PerlLIO_close(newfd);
3034 /* good enough for low fd's... */
3035 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
3036 if (fdx >= DUP2_MAX_FDS) {
3044 PerlLIO_close(fdtmp[--fdx]);
3051 #ifdef HAS_SIGACTION
3054 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3057 struct sigaction act, oact;
3060 /* only "parent" interpreter can diddle signals */
3061 if (PL_curinterp != aTHX)
3062 return (Sighandler_t) SIG_ERR;
3065 act.sa_handler = (void(*)(int))handler;
3066 sigemptyset(&act.sa_mask);
3069 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3070 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
3072 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3073 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3074 act.sa_flags |= SA_NOCLDWAIT;
3076 if (sigaction(signo, &act, &oact) == -1)
3077 return (Sighandler_t) SIG_ERR;
3079 return (Sighandler_t) oact.sa_handler;
3083 Perl_rsignal_state(pTHX_ int signo)
3085 struct sigaction oact;
3086 PERL_UNUSED_CONTEXT;
3088 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
3089 return (Sighandler_t) SIG_ERR;
3091 return (Sighandler_t) oact.sa_handler;
3095 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3098 struct sigaction act;
3100 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
3103 /* only "parent" interpreter can diddle signals */
3104 if (PL_curinterp != aTHX)
3108 act.sa_handler = (void(*)(int))handler;
3109 sigemptyset(&act.sa_mask);
3112 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3113 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
3115 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3116 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3117 act.sa_flags |= SA_NOCLDWAIT;
3119 return sigaction(signo, &act, save);
3123 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3127 /* only "parent" interpreter can diddle signals */
3128 if (PL_curinterp != aTHX)
3132 return sigaction(signo, save, (struct sigaction *)NULL);
3135 #else /* !HAS_SIGACTION */
3138 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3140 #if defined(USE_ITHREADS) && !defined(WIN32)
3141 /* only "parent" interpreter can diddle signals */
3142 if (PL_curinterp != aTHX)
3143 return (Sighandler_t) SIG_ERR;
3146 return PerlProc_signal(signo, handler);
3157 Perl_rsignal_state(pTHX_ int signo)
3160 Sighandler_t oldsig;
3162 #if defined(USE_ITHREADS) && !defined(WIN32)
3163 /* only "parent" interpreter can diddle signals */
3164 if (PL_curinterp != aTHX)
3165 return (Sighandler_t) SIG_ERR;
3169 oldsig = PerlProc_signal(signo, sig_trap);
3170 PerlProc_signal(signo, oldsig);
3172 PerlProc_kill(PerlProc_getpid(), signo);
3177 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3179 #if defined(USE_ITHREADS) && !defined(WIN32)
3180 /* only "parent" interpreter can diddle signals */
3181 if (PL_curinterp != aTHX)
3184 *save = PerlProc_signal(signo, handler);
3185 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3189 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3191 #if defined(USE_ITHREADS) && !defined(WIN32)
3192 /* only "parent" interpreter can diddle signals */
3193 if (PL_curinterp != aTHX)
3196 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3199 #endif /* !HAS_SIGACTION */
3200 #endif /* !PERL_MICRO */
3202 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3203 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
3205 Perl_my_pclose(pTHX_ PerlIO *ptr)
3208 Sigsave_t hstat, istat, qstat;
3215 const int fd = PerlIO_fileno(ptr);
3218 /* Find out whether the refcount is low enough for us to wait for the
3219 child proc without blocking. */
3220 const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
3222 const bool should_wait = 1;
3225 svp = av_fetch(PL_fdpid,fd,TRUE);
3226 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3228 *svp = &PL_sv_undef;
3230 if (pid == -1) { /* Opened by popen. */
3231 return my_syspclose(ptr);
3234 close_failed = (PerlIO_close(ptr) == EOF);
3237 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
3240 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3241 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3242 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3244 if (should_wait) do {
3245 pid2 = wait4pid(pid, &status, 0);
3246 } while (pid2 == -1 && errno == EINTR);
3248 rsignal_restore(SIGHUP, &hstat);
3249 rsignal_restore(SIGINT, &istat);
3250 rsignal_restore(SIGQUIT, &qstat);
3258 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3263 #if defined(__LIBCATAMOUNT__)
3265 Perl_my_pclose(pTHX_ PerlIO *ptr)
3270 #endif /* !DOSISH */
3272 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3274 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3278 PERL_ARGS_ASSERT_WAIT4PID;
3281 #ifdef PERL_USES_PL_PIDSTATUS
3284 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3285 pid, rather than a string form. */
3286 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3287 if (svp && *svp != &PL_sv_undef) {
3288 *statusp = SvIVX(*svp);
3289 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3297 hv_iterinit(PL_pidstatus);
3298 if ((entry = hv_iternext(PL_pidstatus))) {
3299 SV * const sv = hv_iterval(PL_pidstatus,entry);
3301 const char * const spid = hv_iterkey(entry,&len);
3303 assert (len == sizeof(Pid_t));
3304 memcpy((char *)&pid, spid, len);
3305 *statusp = SvIVX(sv);
3306 /* The hash iterator is currently on this entry, so simply
3307 calling hv_delete would trigger the lazy delete, which on
3308 aggregate does more work, beacuse next call to hv_iterinit()
3309 would spot the flag, and have to call the delete routine,
3310 while in the meantime any new entries can't re-use that
3312 hv_iterinit(PL_pidstatus);
3313 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3320 # ifdef HAS_WAITPID_RUNTIME
3321 if (!HAS_WAITPID_RUNTIME)
3324 result = PerlProc_waitpid(pid,statusp,flags);
3327 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3328 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3331 #ifdef PERL_USES_PL_PIDSTATUS
3332 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3337 Perl_croak(aTHX_ "Can't do waitpid with flags");
3339 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3340 pidgone(result,*statusp);
3346 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3349 if (result < 0 && errno == EINTR) {
3351 errno = EINTR; /* reset in case a signal handler changed $! */
3355 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3357 #ifdef PERL_USES_PL_PIDSTATUS
3359 S_pidgone(pTHX_ Pid_t pid, int status)
3363 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3364 SvUPGRADE(sv,SVt_IV);
3365 SvIV_set(sv, status);
3370 #if defined(atarist) || defined(OS2) || defined(EPOC)
3373 int /* Cannot prototype with I32
3375 my_syspclose(PerlIO *ptr)
3378 Perl_my_pclose(pTHX_ PerlIO *ptr)
3381 /* Needs work for PerlIO ! */
3382 FILE * const f = PerlIO_findFILE(ptr);
3383 const I32 result = pclose(f);
3384 PerlIO_releaseFILE(ptr,f);
3392 Perl_my_pclose(pTHX_ PerlIO *ptr)
3394 /* Needs work for PerlIO ! */
3395 FILE * const f = PerlIO_findFILE(ptr);
3396 I32 result = djgpp_pclose(f);
3397 result = (result << 8) & 0xff00;
3398 PerlIO_releaseFILE(ptr,f);
3403 #define PERL_REPEATCPY_LINEAR 4
3405 Perl_repeatcpy(register char *to, register const char *from, I32 len, register I32 count)
3407 PERL_ARGS_ASSERT_REPEATCPY;
3410 memset(to, *from, count);
3412 register char *p = to;
3413 I32 items, linear, half;
3415 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3416 for (items = 0; items < linear; ++items) {
3417 register const char *q = from;
3419 for (todo = len; todo > 0; todo--)
3424 while (items <= half) {
3425 I32 size = items * len;
3426 memcpy(p, to, size);
3432 memcpy(p, to, (count - items) * len);
3438 Perl_same_dirent(pTHX_ const char *a, const char *b)
3440 char *fa = strrchr(a,'/');
3441 char *fb = strrchr(b,'/');
3444 SV * const tmpsv = sv_newmortal();
3446 PERL_ARGS_ASSERT_SAME_DIRENT;
3459 sv_setpvs(tmpsv, ".");
3461 sv_setpvn(tmpsv, a, fa - a);
3462 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3465 sv_setpvs(tmpsv, ".");
3467 sv_setpvn(tmpsv, b, fb - b);
3468 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3470 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3471 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3473 #endif /* !HAS_RENAME */
3476 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3477 const char *const *const search_ext, I32 flags)
3480 const char *xfound = NULL;
3481 char *xfailed = NULL;
3482 char tmpbuf[MAXPATHLEN];
3487 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3488 # define SEARCH_EXTS ".bat", ".cmd", NULL
3489 # define MAX_EXT_LEN 4
3492 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3493 # define MAX_EXT_LEN 4
3496 # define SEARCH_EXTS ".pl", ".com", NULL
3497 # define MAX_EXT_LEN 4
3499 /* additional extensions to try in each dir if scriptname not found */
3501 static const char *const exts[] = { SEARCH_EXTS };
3502 const char *const *const ext = search_ext ? search_ext : exts;
3503 int extidx = 0, i = 0;
3504 const char *curext = NULL;
3506 PERL_UNUSED_ARG(search_ext);
3507 # define MAX_EXT_LEN 0
3510 PERL_ARGS_ASSERT_FIND_SCRIPT;
3513 * If dosearch is true and if scriptname does not contain path
3514 * delimiters, search the PATH for scriptname.
3516 * If SEARCH_EXTS is also defined, will look for each
3517 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3518 * while searching the PATH.
3520 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3521 * proceeds as follows:
3522 * If DOSISH or VMSISH:
3523 * + look for ./scriptname{,.foo,.bar}
3524 * + search the PATH for scriptname{,.foo,.bar}
3527 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3528 * this will not look in '.' if it's not in the PATH)
3533 # ifdef ALWAYS_DEFTYPES
3534 len = strlen(scriptname);
3535 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3536 int idx = 0, deftypes = 1;
3539 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3542 int idx = 0, deftypes = 1;
3545 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3547 /* The first time through, just add SEARCH_EXTS to whatever we
3548 * already have, so we can check for default file types. */
3550 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3556 if ((strlen(tmpbuf) + strlen(scriptname)
3557 + MAX_EXT_LEN) >= sizeof tmpbuf)
3558 continue; /* don't search dir with too-long name */
3559 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3563 if (strEQ(scriptname, "-"))
3565 if (dosearch) { /* Look in '.' first. */
3566 const char *cur = scriptname;
3568 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3570 if (strEQ(ext[i++],curext)) {
3571 extidx = -1; /* already has an ext */
3576 DEBUG_p(PerlIO_printf(Perl_debug_log,
3577 "Looking for %s\n",cur));
3578 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3579 && !S_ISDIR(PL_statbuf.st_mode)) {
3587 if (cur == scriptname) {
3588 len = strlen(scriptname);
3589 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3591 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3594 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3595 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3600 if (dosearch && !strchr(scriptname, '/')
3602 && !strchr(scriptname, '\\')
3604 && (s = PerlEnv_getenv("PATH")))
3608 bufend = s + strlen(s);
3609 while (s < bufend) {
3610 #if defined(atarist) || defined(DOSISH)
3615 && *s != ';'; len++, s++) {
3616 if (len < sizeof tmpbuf)
3619 if (len < sizeof tmpbuf)
3621 #else /* ! (atarist || DOSISH) */
3622 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3625 #endif /* ! (atarist || DOSISH) */
3628 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3629 continue; /* don't search dir with too-long name */
3631 # if defined(atarist) || defined(DOSISH)
3632 && tmpbuf[len - 1] != '/'
3633 && tmpbuf[len - 1] != '\\'
3636 tmpbuf[len++] = '/';
3637 if (len == 2 && tmpbuf[0] == '.')
3639 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3643 len = strlen(tmpbuf);
3644 if (extidx > 0) /* reset after previous loop */
3648 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3649 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3650 if (S_ISDIR(PL_statbuf.st_mode)) {
3654 } while ( retval < 0 /* not there */
3655 && extidx>=0 && ext[extidx] /* try an extension? */
3656 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3661 if (S_ISREG(PL_statbuf.st_mode)
3662 && cando(S_IRUSR,TRUE,&PL_statbuf)
3663 #if !defined(DOSISH)
3664 && cando(S_IXUSR,TRUE,&PL_statbuf)
3668 xfound = tmpbuf; /* bingo! */
3672 xfailed = savepv(tmpbuf);
3675 if (!xfound && !seen_dot && !xfailed &&
3676 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3677 || S_ISDIR(PL_statbuf.st_mode)))
3679 seen_dot = 1; /* Disable message. */
3681 if (flags & 1) { /* do or die? */
3682 Perl_croak(aTHX_ "Can't %s %s%s%s",
3683 (xfailed ? "execute" : "find"),
3684 (xfailed ? xfailed : scriptname),
3685 (xfailed ? "" : " on PATH"),
3686 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3691 scriptname = xfound;
3693 return (scriptname ? savepv(scriptname) : NULL);
3696 #ifndef PERL_GET_CONTEXT_DEFINED
3699 Perl_get_context(void)
3702 #if defined(USE_ITHREADS)
3703 # ifdef OLD_PTHREADS_API
3705 if (pthread_getspecific(PL_thr_key, &t))
3706 Perl_croak_nocontext("panic: pthread_getspecific");
3709 # ifdef I_MACH_CTHREADS
3710 return (void*)cthread_data(cthread_self());
3712 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3721 Perl_set_context(void *t)
3724 PERL_ARGS_ASSERT_SET_CONTEXT;
3725 #if defined(USE_ITHREADS)
3726 # ifdef I_MACH_CTHREADS
3727 cthread_set_data(cthread_self(), t);
3729 if (pthread_setspecific(PL_thr_key, t))
3730 Perl_croak_nocontext("panic: pthread_setspecific");
3737 #endif /* !PERL_GET_CONTEXT_DEFINED */
3739 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3748 Perl_get_op_names(pTHX)
3750 PERL_UNUSED_CONTEXT;
3751 return (char **)PL_op_name;
3755 Perl_get_op_descs(pTHX)
3757 PERL_UNUSED_CONTEXT;
3758 return (char **)PL_op_desc;
3762 Perl_get_no_modify(pTHX)
3764 PERL_UNUSED_CONTEXT;
3765 return PL_no_modify;
3769 Perl_get_opargs(pTHX)
3771 PERL_UNUSED_CONTEXT;
3772 return (U32 *)PL_opargs;
3776 Perl_get_ppaddr(pTHX)
3779 PERL_UNUSED_CONTEXT;
3780 return (PPADDR_t*)PL_ppaddr;
3783 #ifndef HAS_GETENV_LEN
3785 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3787 char * const env_trans = PerlEnv_getenv(env_elem);
3788 PERL_UNUSED_CONTEXT;
3789 PERL_ARGS_ASSERT_GETENV_LEN;
3791 *len = strlen(env_trans);
3798 Perl_get_vtbl(pTHX_ int vtbl_id)
3800 PERL_UNUSED_CONTEXT;
3802 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3803 ? NULL : PL_magic_vtables + vtbl_id;
3807 Perl_my_fflush_all(pTHX)
3809 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3810 return PerlIO_flush(NULL);
3812 # if defined(HAS__FWALK)
3813 extern int fflush(FILE *);
3814 /* undocumented, unprototyped, but very useful BSDism */
3815 extern void _fwalk(int (*)(FILE *));
3819 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3821 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3822 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3824 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3825 open_max = sysconf(_SC_OPEN_MAX);
3828 open_max = FOPEN_MAX;
3831 open_max = OPEN_MAX;
3842 for (i = 0; i < open_max; i++)
3843 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3844 STDIO_STREAM_ARRAY[i]._file < open_max &&
3845 STDIO_STREAM_ARRAY[i]._flag)
3846 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3850 SETERRNO(EBADF,RMS_IFI);
3857 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3859 if (ckWARN(WARN_IO)) {
3860 const char * const name
3861 = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3862 const char * const direction = have == '>' ? "out" : "in";
3865 Perl_warner(aTHX_ packWARN(WARN_IO),
3866 "Filehandle %s opened only for %sput",
3869 Perl_warner(aTHX_ packWARN(WARN_IO),
3870 "Filehandle opened only for %sput", direction);
3875 Perl_report_evil_fh(pTHX_ const GV *gv)
3877 const IO *io = gv ? GvIO(gv) : NULL;
3878 const PERL_BITFIELD16 op = PL_op->op_type;
3882 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3884 warn_type = WARN_CLOSED;
3888 warn_type = WARN_UNOPENED;
3891 if (ckWARN(warn_type)) {
3892 const char * const name
3893 = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3894 const char * const pars =
3895 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3896 const char * const func =
3898 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3899 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3901 const char * const type =
3903 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3904 ? "socket" : "filehandle");
3905 if (name && *name) {
3906 Perl_warner(aTHX_ packWARN(warn_type),
3907 "%s%s on %s %s %s", func, pars, vile, type, name);
3908 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3910 aTHX_ packWARN(warn_type),
3911 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3916 Perl_warner(aTHX_ packWARN(warn_type),
3917 "%s%s on %s %s", func, pars, vile, type);
3918 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3920 aTHX_ packWARN(warn_type),
3921 "\t(Are you trying to call %s%s on dirhandle?)\n",
3928 /* To workaround core dumps from the uninitialised tm_zone we get the
3929 * system to give us a reasonable struct to copy. This fix means that
3930 * strftime uses the tm_zone and tm_gmtoff values returned by
3931 * localtime(time()). That should give the desired result most of the
3932 * time. But probably not always!
3934 * This does not address tzname aspects of NETaa14816.
3939 # ifndef STRUCT_TM_HASZONE
3940 # define STRUCT_TM_HASZONE
3944 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3945 # ifndef HAS_TM_TM_ZONE
3946 # define HAS_TM_TM_ZONE
3951 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3953 #ifdef HAS_TM_TM_ZONE
3955 const struct tm* my_tm;
3956 PERL_ARGS_ASSERT_INIT_TM;
3958 my_tm = localtime(&now);
3960 Copy(my_tm, ptm, 1, struct tm);
3962 PERL_ARGS_ASSERT_INIT_TM;
3963 PERL_UNUSED_ARG(ptm);
3968 * mini_mktime - normalise struct tm values without the localtime()
3969 * semantics (and overhead) of mktime().
3972 Perl_mini_mktime(pTHX_ struct tm *ptm)
3976 int month, mday, year, jday;
3977 int odd_cent, odd_year;
3978 PERL_UNUSED_CONTEXT;
3980 PERL_ARGS_ASSERT_MINI_MKTIME;
3982 #define DAYS_PER_YEAR 365
3983 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3984 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3985 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3986 #define SECS_PER_HOUR (60*60)
3987 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3988 /* parentheses deliberately absent on these two, otherwise they don't work */
3989 #define MONTH_TO_DAYS 153/5
3990 #define DAYS_TO_MONTH 5/153
3991 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3992 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3993 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3994 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3997 * Year/day algorithm notes:
3999 * With a suitable offset for numeric value of the month, one can find
4000 * an offset into the year by considering months to have 30.6 (153/5) days,
4001 * using integer arithmetic (i.e., with truncation). To avoid too much
4002 * messing about with leap days, we consider January and February to be
4003 * the 13th and 14th month of the previous year. After that transformation,
4004 * we need the month index we use to be high by 1 from 'normal human' usage,
4005 * so the month index values we use run from 4 through 15.
4007 * Given that, and the rules for the Gregorian calendar (leap years are those
4008 * divisible by 4 unless also divisible by 100, when they must be divisible
4009 * by 400 instead), we can simply calculate the number of days since some
4010 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
4011 * the days we derive from our month index, and adding in the day of the
4012 * month. The value used here is not adjusted for the actual origin which
4013 * it normally would use (1 January A.D. 1), since we're not exposing it.
4014 * We're only building the value so we can turn around and get the
4015 * normalised values for the year, month, day-of-month, and day-of-year.
4017 * For going backward, we need to bias the value we're using so that we find
4018 * the right year value. (Basically, we don't want the contribution of
4019 * March 1st to the number to apply while deriving the year). Having done
4020 * that, we 'count up' the contribution to the year number by accounting for
4021 * full quadracenturies (400-year periods) with their extra leap days, plus
4022 * the contribution from full centuries (to avoid counting in the lost leap
4023 * days), plus the contribution from full quad-years (to count in the normal
4024 * leap days), plus the leftover contribution from any non-leap years.
4025 * At this point, if we were working with an actual leap day, we'll have 0
4026 * days left over. This is also true for March 1st, however. So, we have
4027 * to special-case that result, and (earlier) keep track of the 'odd'
4028 * century and year contributions. If we got 4 extra centuries in a qcent,
4029 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
4030 * Otherwise, we add back in the earlier bias we removed (the 123 from
4031 * figuring in March 1st), find the month index (integer division by 30.6),
4032 * and the remainder is the day-of-month. We then have to convert back to
4033 * 'real' months (including fixing January and February from being 14/15 in
4034 * the previous year to being in the proper year). After that, to get
4035 * tm_yday, we work with the normalised year and get a new yearday value for
4036 * January 1st, which we subtract from the yearday value we had earlier,
4037 * representing the date we've re-built. This is done from January 1
4038 * because tm_yday is 0-origin.
4040 * Since POSIX time routines are only guaranteed to work for times since the
4041 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
4042 * applies Gregorian calendar rules even to dates before the 16th century
4043 * doesn't bother me. Besides, you'd need cultural context for a given
4044 * date to know whether it was Julian or Gregorian calendar, and that's
4045 * outside the scope for this routine. Since we convert back based on the
4046 * same rules we used to build the yearday, you'll only get strange results
4047 * for input which needed normalising, or for the 'odd' century years which
4048 * were leap years in the Julian calendar but not in the Gregorian one.
4049 * I can live with that.
4051 * This algorithm also fails to handle years before A.D. 1 gracefully, but
4052 * that's still outside the scope for POSIX time manipulation, so I don't
4056 year = 1900 + ptm->tm_year;
4057 month = ptm->tm_mon;
4058 mday = ptm->tm_mday;
4059 /* allow given yday with no month & mday to dominate the result */
4060 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
4063 jday = 1 + ptm->tm_yday;
4072 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4073 yearday += month*MONTH_TO_DAYS + mday + jday;
4075 * Note that we don't know when leap-seconds were or will be,
4076 * so we have to trust the user if we get something which looks
4077 * like a sensible leap-second. Wild values for seconds will
4078 * be rationalised, however.
4080 if ((unsigned) ptm->tm_sec <= 60) {
4087 secs += 60 * ptm->tm_min;
4088 secs += SECS_PER_HOUR * ptm->tm_hour;
4090 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4091 /* got negative remainder, but need positive time */
4092 /* back off an extra day to compensate */
4093 yearday += (secs/SECS_PER_DAY)-1;
4094 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4097 yearday += (secs/SECS_PER_DAY);
4098 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4101 else if (secs >= SECS_PER_DAY) {
4102 yearday += (secs/SECS_PER_DAY);
4103 secs %= SECS_PER_DAY;
4105 ptm->tm_hour = secs/SECS_PER_HOUR;
4106 secs %= SECS_PER_HOUR;
4107 ptm->tm_min = secs/60;
4109 ptm->tm_sec += secs;
4110 /* done with time of day effects */
4112 * The algorithm for yearday has (so far) left it high by 428.
4113 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4114 * bias it by 123 while trying to figure out what year it
4115 * really represents. Even with this tweak, the reverse
4116 * translation fails for years before A.D. 0001.
4117 * It would still fail for Feb 29, but we catch that one below.
4119 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
4120 yearday -= YEAR_ADJUST;
4121 year = (yearday / DAYS_PER_QCENT) * 400;
4122 yearday %= DAYS_PER_QCENT;
4123 odd_cent = yearday / DAYS_PER_CENT;
4124 year += odd_cent * 100;
4125 yearday %= DAYS_PER_CENT;
4126 year += (yearday / DAYS_PER_QYEAR) * 4;
4127 yearday %= DAYS_PER_QYEAR;
4128 odd_year = yearday / DAYS_PER_YEAR;
4130 yearday %= DAYS_PER_YEAR;
4131 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4136 yearday += YEAR_ADJUST; /* recover March 1st crock */
4137 month = yearday*DAYS_TO_MONTH;
4138 yearday -= month*MONTH_TO_DAYS;
4139 /* recover other leap-year adjustment */
4148 ptm->tm_year = year - 1900;
4150 ptm->tm_mday = yearday;
4151 ptm->tm_mon = month;
4155 ptm->tm_mon = month - 1;
4157 /* re-build yearday based on Jan 1 to get tm_yday */
4159 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4160 yearday += 14*MONTH_TO_DAYS + 1;
4161 ptm->tm_yday = jday - yearday;
4162 /* fix tm_wday if not overridden by caller */
4163 if ((unsigned)ptm->tm_wday > 6)
4164 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4168 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)
4176 PERL_ARGS_ASSERT_MY_STRFTIME;
4178 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4181 mytm.tm_hour = hour;
4182 mytm.tm_mday = mday;
4184 mytm.tm_year = year;
4185 mytm.tm_wday = wday;
4186 mytm.tm_yday = yday;
4187 mytm.tm_isdst = isdst;
4189 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4190 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4195 #ifdef HAS_TM_TM_GMTOFF
4196 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4198 #ifdef HAS_TM_TM_ZONE
4199 mytm.tm_zone = mytm2.tm_zone;
4204 Newx(buf, buflen, char);
4205 len = strftime(buf, buflen, fmt, &mytm);
4207 ** The following is needed to handle to the situation where
4208 ** tmpbuf overflows. Basically we want to allocate a buffer
4209 ** and try repeatedly. The reason why it is so complicated
4210 ** is that getting a return value of 0 from strftime can indicate
4211 ** one of the following:
4212 ** 1. buffer overflowed,
4213 ** 2. illegal conversion specifier, or
4214 ** 3. the format string specifies nothing to be returned(not
4215 ** an error). This could be because format is an empty string
4216 ** or it specifies %p that yields an empty string in some locale.
4217 ** If there is a better way to make it portable, go ahead by
4220 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4223 /* Possibly buf overflowed - try again with a bigger buf */
4224 const int fmtlen = strlen(fmt);
4225 int bufsize = fmtlen + buflen;
4227 Renew(buf, bufsize, char);
4229 buflen = strftime(buf, bufsize, fmt, &mytm);
4230 if (buflen > 0 && buflen < bufsize)
4232 /* heuristic to prevent out-of-memory errors */
4233 if (bufsize > 100*fmtlen) {
4239 Renew(buf, bufsize, char);
4244 Perl_croak(aTHX_ "panic: no strftime");
4250 #define SV_CWD_RETURN_UNDEF \
4251 sv_setsv(sv, &PL_sv_undef); \
4254 #define SV_CWD_ISDOT(dp) \
4255 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4256 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4259 =head1 Miscellaneous Functions
4261 =for apidoc getcwd_sv
4263 Fill the sv with current working directory
4268 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4269 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4270 * getcwd(3) if available
4271 * Comments from the orignal:
4272 * This is a faster version of getcwd. It's also more dangerous
4273 * because you might chdir out of a directory that you can't chdir
4277 Perl_getcwd_sv(pTHX_ register SV *sv)
4281 #ifndef INCOMPLETE_TAINTS
4285 PERL_ARGS_ASSERT_GETCWD_SV;
4289 char buf[MAXPATHLEN];
4291 /* Some getcwd()s automatically allocate a buffer of the given
4292 * size from the heap if they are given a NULL buffer pointer.
4293 * The problem is that this behaviour is not portable. */
4294 if (getcwd(buf, sizeof(buf) - 1)) {
4299 sv_setsv(sv, &PL_sv_undef);
4307 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4311 SvUPGRADE(sv, SVt_PV);
4313 if (PerlLIO_lstat(".", &statbuf) < 0) {
4314 SV_CWD_RETURN_UNDEF;
4317 orig_cdev = statbuf.st_dev;
4318 orig_cino = statbuf.st_ino;
4328 if (PerlDir_chdir("..") < 0) {
4329 SV_CWD_RETURN_UNDEF;
4331 if (PerlLIO_stat(".", &statbuf) < 0) {
4332 SV_CWD_RETURN_UNDEF;
4335 cdev = statbuf.st_dev;
4336 cino = statbuf.st_ino;
4338 if (odev == cdev && oino == cino) {
4341 if (!(dir = PerlDir_open("."))) {
4342 SV_CWD_RETURN_UNDEF;
4345 while ((dp = PerlDir_read(dir)) != NULL) {
4347 namelen = dp->d_namlen;
4349 namelen = strlen(dp->d_name);
4352 if (SV_CWD_ISDOT(dp)) {
4356 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4357 SV_CWD_RETURN_UNDEF;
4360 tdev = statbuf.st_dev;
4361 tino = statbuf.st_ino;
4362 if (tino == oino && tdev == odev) {
4368 SV_CWD_RETURN_UNDEF;
4371 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4372 SV_CWD_RETURN_UNDEF;
4375 SvGROW(sv, pathlen + namelen + 1);
4379 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4382 /* prepend current directory to the front */
4384 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4385 pathlen += (namelen + 1);
4387 #ifdef VOID_CLOSEDIR
4390 if (PerlDir_close(dir) < 0) {
4391 SV_CWD_RETURN_UNDEF;
4397 SvCUR_set(sv, pathlen);
4401 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4402 SV_CWD_RETURN_UNDEF;
4405 if (PerlLIO_stat(".", &statbuf) < 0) {
4406 SV_CWD_RETURN_UNDEF;
4409 cdev = statbuf.st_dev;
4410 cino = statbuf.st_ino;
4412 if (cdev != orig_cdev || cino != orig_cino) {
4413 Perl_croak(aTHX_ "Unstable directory path, "
4414 "current directory changed unexpectedly");
4425 #define VERSION_MAX 0x7FFFFFFF
4428 =for apidoc prescan_version
4430 Validate that a given string can be parsed as a version object, but doesn't
4431 actually perform the parsing. Can use either strict or lax validation rules.
4432 Can optionally set a number of hint variables to save the parsing code
4433 some time when tokenizing.
4438 Perl_prescan_version(pTHX_ const char *s, bool strict,
4439 const char **errstr,
4440 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4441 bool qv = (sqv ? *sqv : FALSE);
4443 int saw_decimal = 0;
4447 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4449 if (qv && isDIGIT(*d))
4450 goto dotted_decimal_version;
4452 if (*d == 'v') { /* explicit v-string */
4457 else { /* degenerate v-string */
4458 /* requires v1.2.3 */
4459 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4462 dotted_decimal_version:
4463 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4464 /* no leading zeros allowed */
4465 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4468 while (isDIGIT(*d)) /* integer part */
4474 d++; /* decimal point */
4479 /* require v1.2.3 */
4480 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4483 goto version_prescan_finish;
4490 while (isDIGIT(*d)) { /* just keep reading */
4492 while (isDIGIT(*d)) {
4494 /* maximum 3 digits between decimal */
4495 if (strict && j > 3) {
4496 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4501 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4504 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4509 else if (*d == '.') {
4511 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4516 else if (!isDIGIT(*d)) {
4522 if (strict && i < 2) {
4523 /* requires v1.2.3 */
4524 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4527 } /* end if dotted-decimal */
4529 { /* decimal versions */
4530 /* special strict case for leading '.' or '0' */
4533 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4535 if (*d == '0' && isDIGIT(d[1])) {
4536 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4540 /* and we never support negative versions */
4542 BADVERSION(s,errstr,"Invalid version format (negative version number)");
4545 /* consume all of the integer part */
4549 /* look for a fractional part */
4551 /* we found it, so consume it */
4555 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4558 BADVERSION(s,errstr,"Invalid version format (version required)");
4560 /* found just an integer */
4561 goto version_prescan_finish;
4563 else if ( d == s ) {
4564 /* didn't find either integer or period */
4565 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4567 else if (*d == '_') {
4568 /* underscore can't come after integer part */
4570 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4572 else if (isDIGIT(d[1])) {
4573 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4576 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4580 /* anything else after integer part is just invalid data */
4581 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4584 /* scan the fractional part after the decimal point*/
4586 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4587 /* strict or lax-but-not-the-end */
4588 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4591 while (isDIGIT(*d)) {
4593 if (*d == '.' && isDIGIT(d[-1])) {
4595 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4598 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4600 d = (char *)s; /* start all over again */
4602 goto dotted_decimal_version;
4606 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4609 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4611 if ( ! isDIGIT(d[1]) ) {
4612 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4620 version_prescan_finish:
4624 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4625 /* trailing non-numeric data */
4626 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4634 *ssaw_decimal = saw_decimal;
4641 =for apidoc scan_version
4643 Returns a pointer to the next character after the parsed
4644 version string, as well as upgrading the passed in SV to
4647 Function must be called with an already existing SV like
4650 s = scan_version(s, SV *sv, bool qv);
4652 Performs some preprocessing to the string to ensure that
4653 it has the correct characteristics of a version. Flags the
4654 object if it contains an underscore (which denotes this
4655 is an alpha version). The boolean qv denotes that the version
4656 should be interpreted as if it had multiple decimals, even if
4663 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4668 const char *errstr = NULL;
4669 int saw_decimal = 0;
4673 AV * const av = newAV();
4674 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4676 PERL_ARGS_ASSERT_SCAN_VERSION;
4678 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4680 #ifndef NODEFAULT_SHAREKEYS
4681 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4684 while (isSPACE(*s)) /* leading whitespace is OK */
4687 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4689 /* "undef" is a special case and not an error */
4690 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4691 Perl_croak(aTHX_ "%s", errstr);
4701 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4703 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4704 if ( !qv && width < 3 )
4705 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4707 while (isDIGIT(*pos))
4709 if (!isALPHA(*pos)) {
4715 /* this is atoi() that delimits on underscores */
4716 const char *end = pos;
4720 /* the following if() will only be true after the decimal
4721 * point of a version originally created with a bare
4722 * floating point number, i.e. not quoted in any way
4724 if ( !qv && s > start && saw_decimal == 1 ) {
4728 rev += (*s - '0') * mult;
4730 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4731 || (PERL_ABS(rev) > VERSION_MAX )) {
4732 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4733 "Integer overflow in version %d",VERSION_MAX);
4744 while (--end >= s) {
4746 rev += (*end - '0') * mult;
4748 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4749 || (PERL_ABS(rev) > VERSION_MAX )) {
4750 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4751 "Integer overflow in version");
4760 /* Append revision */
4761 av_push(av, newSViv(rev));
4766 else if ( *pos == '.' )
4768 else if ( *pos == '_' && isDIGIT(pos[1]) )
4770 else if ( *pos == ',' && isDIGIT(pos[1]) )
4772 else if ( isDIGIT(*pos) )
4779 while ( isDIGIT(*pos) )
4784 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4792 if ( qv ) { /* quoted versions always get at least three terms*/
4793 I32 len = av_len(av);
4794 /* This for loop appears to trigger a compiler bug on OS X, as it
4795 loops infinitely. Yes, len is negative. No, it makes no sense.
4796 Compiler in question is:
4797 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4798 for ( len = 2 - len; len > 0; len-- )
4799 av_push(MUTABLE_AV(sv), newSViv(0));
4803 av_push(av, newSViv(0));
4806 /* need to save off the current version string for later */
4808 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4809 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4810 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4812 else if ( s > start ) {
4813 SV * orig = newSVpvn(start,s-start);
4814 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4815 /* need to insert a v to be consistent */
4816 sv_insert(orig, 0, 0, "v", 1);
4818 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4821 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4822 av_push(av, newSViv(0));
4825 /* And finally, store the AV in the hash */
4826 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4828 /* fix RT#19517 - special case 'undef' as string */
4829 if ( *s == 'u' && strEQ(s,"undef") ) {
4837 =for apidoc new_version
4839 Returns a new version object based on the passed in SV:
4841 SV *sv = new_version(SV *ver);
4843 Does not alter the passed in ver SV. See "upg_version" if you
4844 want to upgrade the SV.
4850 Perl_new_version(pTHX_ SV *ver)
4853 SV * const rv = newSV(0);
4854 PERL_ARGS_ASSERT_NEW_VERSION;
4855 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4858 AV * const av = newAV();
4860 /* This will get reblessed later if a derived class*/
4861 SV * const hv = newSVrv(rv, "version");
4862 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4863 #ifndef NODEFAULT_SHAREKEYS
4864 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4870 /* Begin copying all of the elements */
4871 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4872 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4874 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4875 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4877 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4879 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4880 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4883 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4885 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4886 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4889 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4890 /* This will get reblessed later if a derived class*/
4891 for ( key = 0; key <= av_len(sav); key++ )
4893 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4894 av_push(av, newSViv(rev));
4897 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4902 const MAGIC* const mg = SvVSTRING_mg(ver);
4903 if ( mg ) { /* already a v-string */
4904 const STRLEN len = mg->mg_len;
4905 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4906 sv_setpvn(rv,version,len);
4907 /* this is for consistency with the pure Perl class */
4908 if ( isDIGIT(*version) )
4909 sv_insert(rv, 0, 0, "v", 1);
4914 sv_setsv(rv,ver); /* make a duplicate */
4919 return upg_version(rv, FALSE);
4923 =for apidoc upg_version
4925 In-place upgrade of the supplied SV to a version object.
4927 SV *sv = upg_version(SV *sv, bool qv);
4929 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4930 to force this SV to be interpreted as an "extended" version.
4936 Perl_upg_version(pTHX_ SV *ver, bool qv)
4938 const char *version, *s;
4943 PERL_ARGS_ASSERT_UPG_VERSION;
4945 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4947 /* may get too much accuracy */
4949 #ifdef USE_LOCALE_NUMERIC
4950 char *loc = setlocale(LC_NUMERIC, "C");
4952 STRLEN len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4953 #ifdef USE_LOCALE_NUMERIC
4954 setlocale(LC_NUMERIC, loc);
4956 while (tbuf[len-1] == '0' && len > 0) len--;
4957 if ( tbuf[len-1] == '.' ) len--; /* eat the trailing decimal */
4958 version = savepvn(tbuf, len);
4961 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4962 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4966 else /* must be a string or something like a string */
4969 version = savepv(SvPV(ver,len));
4971 # if PERL_VERSION > 5
4972 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4973 if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
4974 /* may be a v-string */
4975 char *testv = (char *)version;
4977 for (tlen=0; tlen < len; tlen++, testv++) {
4978 /* if one of the characters is non-text assume v-string */
4979 if (testv[0] < ' ') {
4980 SV * const nsv = sv_newmortal();
4983 int saw_decimal = 0;
4984 sv_setpvf(nsv,"v%vd",ver);
4985 pos = nver = savepv(SvPV_nolen(nsv));
4987 /* scan the resulting formatted string */
4988 pos++; /* skip the leading 'v' */
4989 while ( *pos == '.' || isDIGIT(*pos) ) {
4995 /* is definitely a v-string */
4996 if ( saw_decimal >= 2 ) {
5008 s = scan_version(version, ver, qv);
5010 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
5011 "Version string '%s' contains invalid data; "
5012 "ignoring: '%s'", version, s);
5020 Validates that the SV contains valid internal structure for a version object.
5021 It may be passed either the version object (RV) or the hash itself (HV). If
5022 the structure is valid, it returns the HV. If the structure is invalid,
5025 SV *hv = vverify(sv);
5027 Note that it only confirms the bare minimum structure (so as not to get
5028 confused by derived classes which may contain additional hash entries):
5032 =item * The SV is an HV or a reference to an HV
5034 =item * The hash contains a "version" key
5036 =item * The "version" key has a reference to an AV as its value
5044 Perl_vverify(pTHX_ SV *vs)
5048 PERL_ARGS_ASSERT_VVERIFY;
5053 /* see if the appropriate elements exist */
5054 if ( SvTYPE(vs) == SVt_PVHV
5055 && hv_exists(MUTABLE_HV(vs), "version", 7)
5056 && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
5057 && SvTYPE(sv) == SVt_PVAV )
5066 Accepts a version object and returns the normalized floating
5067 point representation. Call like:
5071 NOTE: you can pass either the object directly or the SV
5072 contained within the RV.
5074 The SV returned has a refcount of 1.
5080 Perl_vnumify(pTHX_ SV *vs)
5088 PERL_ARGS_ASSERT_VNUMIFY;
5090 /* extract the HV from the object */
5093 Perl_croak(aTHX_ "Invalid version object");
5095 /* see if various flags exist */
5096 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5098 if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
5099 width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
5104 /* attempt to retrieve the version array */
5105 if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
5106 return newSVpvs("0");
5112 return newSVpvs("0");
5115 digit = SvIV(*av_fetch(av, 0, 0));
5116 sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
5117 for ( i = 1 ; i < len ; i++ )
5119 digit = SvIV(*av_fetch(av, i, 0));
5121 const int denom = (width == 2 ? 10 : 100);
5122 const div_t term = div((int)PERL_ABS(digit),denom);
5123 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
5126 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5132 digit = SvIV(*av_fetch(av, len, 0));
5133 if ( alpha && width == 3 ) /* alpha version */
5135 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5139 sv_catpvs(sv, "000");
5147 Accepts a version object and returns the normalized string
5148 representation. Call like:
5152 NOTE: you can pass either the object directly or the SV
5153 contained within the RV.
5155 The SV returned has a refcount of 1.
5161 Perl_vnormal(pTHX_ SV *vs)
5168 PERL_ARGS_ASSERT_VNORMAL;
5170 /* extract the HV from the object */
5173 Perl_croak(aTHX_ "Invalid version object");
5175 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5177 av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)));
5182 return newSVpvs("");
5184 digit = SvIV(*av_fetch(av, 0, 0));
5185 sv = Perl_newSVpvf(aTHX_ "v%"IVdf, (IV)digit);
5186 for ( i = 1 ; i < len ; i++ ) {
5187 digit = SvIV(*av_fetch(av, i, 0));
5188 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5193 /* handle last digit specially */
5194 digit = SvIV(*av_fetch(av, len, 0));
5196 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
5198 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5201 if ( len <= 2 ) { /* short version, must be at least three */
5202 for ( len = 2 - len; len != 0; len-- )
5209 =for apidoc vstringify
5211 In order to maintain maximum compatibility with earlier versions
5212 of Perl, this function will return either the floating point
5213 notation or the multiple dotted notation, depending on whether
5214 the original version contained 1 or more dots, respectively.
5216 The SV returned has a refcount of 1.
5222 Perl_vstringify(pTHX_ SV *vs)
5224 PERL_ARGS_ASSERT_VSTRINGIFY;
5226 /* extract the HV from the object */
5229 Perl_croak(aTHX_ "Invalid version object");
5231 if (hv_exists(MUTABLE_HV(vs), "original", sizeof("original") - 1)) {
5233 pv = *hv_fetchs(MUTABLE_HV(vs), "original", FALSE);
5237 return &PL_sv_undef;
5240 if ( hv_exists(MUTABLE_HV(vs), "qv", 2) )
5250 Version object aware cmp. Both operands must already have been
5251 converted into version objects.
5257 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
5260 bool lalpha = FALSE;
5261 bool ralpha = FALSE;
5266 PERL_ARGS_ASSERT_VCMP;
5268 /* extract the HVs from the objects */
5271 if ( ! ( lhv && rhv ) )
5272 Perl_croak(aTHX_ "Invalid version object");
5274 /* get the left hand term */
5275 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(lhv), "version", FALSE)));
5276 if ( hv_exists(MUTABLE_HV(lhv), "alpha", 5 ) )
5279 /* and the right hand term */
5280 rav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rhv), "version", FALSE)));
5281 if ( hv_exists(MUTABLE_HV(rhv), "alpha", 5 ) )
5289 while ( i <= m && retval == 0 )
5291 left = SvIV(*av_fetch(lav,i,0));
5292 right = SvIV(*av_fetch(rav,i,0));
5300 /* tiebreaker for alpha with identical terms */
5301 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
5303 if ( lalpha && !ralpha )
5307 else if ( ralpha && !lalpha)
5313 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
5317 while ( i <= r && retval == 0 )
5319 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
5320 retval = -1; /* not a match after all */
5326 while ( i <= l && retval == 0 )
5328 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
5329 retval = +1; /* not a match after all */
5337 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
5338 # define EMULATE_SOCKETPAIR_UDP
5341 #ifdef EMULATE_SOCKETPAIR_UDP
5343 S_socketpair_udp (int fd[2]) {
5345 /* Fake a datagram socketpair using UDP to localhost. */
5346 int sockets[2] = {-1, -1};
5347 struct sockaddr_in addresses[2];
5349 Sock_size_t size = sizeof(struct sockaddr_in);
5350 unsigned short port;
5353 memset(&addresses, 0, sizeof(addresses));
5356 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
5357 if (sockets[i] == -1)
5358 goto tidy_up_and_fail;
5360 addresses[i].sin_family = AF_INET;
5361 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5362 addresses[i].sin_port = 0; /* kernel choses port. */
5363 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
5364 sizeof(struct sockaddr_in)) == -1)
5365 goto tidy_up_and_fail;
5368 /* Now have 2 UDP sockets. Find out which port each is connected to, and
5369 for each connect the other socket to it. */
5372 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
5374 goto tidy_up_and_fail;
5375 if (size != sizeof(struct sockaddr_in))
5376 goto abort_tidy_up_and_fail;
5377 /* !1 is 0, !0 is 1 */
5378 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
5379 sizeof(struct sockaddr_in)) == -1)
5380 goto tidy_up_and_fail;
5383 /* Now we have 2 sockets connected to each other. I don't trust some other
5384 process not to have already sent a packet to us (by random) so send
5385 a packet from each to the other. */
5388 /* I'm going to send my own port number. As a short.
5389 (Who knows if someone somewhere has sin_port as a bitfield and needs
5390 this routine. (I'm assuming crays have socketpair)) */
5391 port = addresses[i].sin_port;
5392 got = PerlLIO_write(sockets[i], &port, sizeof(port));
5393 if (got != sizeof(port)) {
5395 goto tidy_up_and_fail;
5396 goto abort_tidy_up_and_fail;
5400 /* Packets sent. I don't trust them to have arrived though.
5401 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
5402 connect to localhost will use a second kernel thread. In 2.6 the
5403 first thread running the connect() returns before the second completes,
5404 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
5405 returns 0. Poor programs have tripped up. One poor program's authors'
5406 had a 50-1 reverse stock split. Not sure how connected these were.)
5407 So I don't trust someone not to have an unpredictable UDP stack.
5411 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
5412 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
5416 FD_SET((unsigned int)sockets[0], &rset);
5417 FD_SET((unsigned int)sockets[1], &rset);
5419 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
5420 if (got != 2 || !FD_ISSET(sockets[0], &rset)
5421 || !FD_ISSET(sockets[1], &rset)) {
5422 /* I hope this is portable and appropriate. */
5424 goto tidy_up_and_fail;
5425 goto abort_tidy_up_and_fail;
5429 /* And the paranoia department even now doesn't trust it to have arrive
5430 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
5432 struct sockaddr_in readfrom;
5433 unsigned short buffer[2];
5438 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5439 sizeof(buffer), MSG_DONTWAIT,
5440 (struct sockaddr *) &readfrom, &size);
5442 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5444 (struct sockaddr *) &readfrom, &size);
5448 goto tidy_up_and_fail;
5449 if (got != sizeof(port)
5450 || size != sizeof(struct sockaddr_in)
5451 /* Check other socket sent us its port. */
5452 || buffer[0] != (unsigned short) addresses[!i].sin_port
5453 /* Check kernel says we got the datagram from that socket */
5454 || readfrom.sin_family != addresses[!i].sin_family
5455 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
5456 || readfrom.sin_port != addresses[!i].sin_port)
5457 goto abort_tidy_up_and_fail;
5460 /* My caller (my_socketpair) has validated that this is non-NULL */
5463 /* I hereby declare this connection open. May God bless all who cross
5467 abort_tidy_up_and_fail:
5468 errno = ECONNABORTED;
5472 if (sockets[0] != -1)
5473 PerlLIO_close(sockets[0]);
5474 if (sockets[1] != -1)
5475 PerlLIO_close(sockets[1]);
5480 #endif /* EMULATE_SOCKETPAIR_UDP */
5482 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
5484 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5485 /* Stevens says that family must be AF_LOCAL, protocol 0.
5486 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
5491 struct sockaddr_in listen_addr;
5492 struct sockaddr_in connect_addr;
5497 || family != AF_UNIX
5500 errno = EAFNOSUPPORT;
5508 #ifdef EMULATE_SOCKETPAIR_UDP
5509 if (type == SOCK_DGRAM)
5510 return S_socketpair_udp(fd);
5513 listener = PerlSock_socket(AF_INET, type, 0);
5516 memset(&listen_addr, 0, sizeof(listen_addr));
5517 listen_addr.sin_family = AF_INET;
5518 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5519 listen_addr.sin_port = 0; /* kernel choses port. */
5520 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5521 sizeof(listen_addr)) == -1)
5522 goto tidy_up_and_fail;
5523 if (PerlSock_listen(listener, 1) == -1)
5524 goto tidy_up_and_fail;
5526 connector = PerlSock_socket(AF_INET, type, 0);
5527 if (connector == -1)
5528 goto tidy_up_and_fail;
5529 /* We want to find out the port number to connect to. */
5530 size = sizeof(connect_addr);
5531 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5533 goto tidy_up_and_fail;
5534 if (size != sizeof(connect_addr))
5535 goto abort_tidy_up_and_fail;
5536 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
5537 sizeof(connect_addr)) == -1)
5538 goto tidy_up_and_fail;
5540 size = sizeof(listen_addr);
5541 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5544 goto tidy_up_and_fail;
5545 if (size != sizeof(listen_addr))
5546 goto abort_tidy_up_and_fail;
5547 PerlLIO_close(listener);
5548 /* Now check we are talking to ourself by matching port and host on the
5550 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5552 goto tidy_up_and_fail;
5553 if (size != sizeof(connect_addr)
5554 || listen_addr.sin_family != connect_addr.sin_family
5555 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5556 || listen_addr.sin_port != connect_addr.sin_port) {
5557 goto abort_tidy_up_and_fail;
5563 abort_tidy_up_and_fail:
5565 errno = ECONNABORTED; /* This would be the standard thing to do. */
5567 # ifdef ECONNREFUSED
5568 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5570 errno = ETIMEDOUT; /* Desperation time. */
5577 PerlLIO_close(listener);
5578 if (connector != -1)
5579 PerlLIO_close(connector);
5581 PerlLIO_close(acceptor);
5587 /* In any case have a stub so that there's code corresponding
5588 * to the my_socketpair in embed.fnc. */
5590 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5591 #ifdef HAS_SOCKETPAIR
5592 return socketpair(family, type, protocol, fd);
5601 =for apidoc sv_nosharing
5603 Dummy routine which "shares" an SV when there is no sharing module present.
5604 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5605 Exists to avoid test for a NULL function pointer and because it could
5606 potentially warn under some level of strict-ness.
5612 Perl_sv_nosharing(pTHX_ SV *sv)
5614 PERL_UNUSED_CONTEXT;
5615 PERL_UNUSED_ARG(sv);
5620 =for apidoc sv_destroyable
5622 Dummy routine which reports that object can be destroyed when there is no
5623 sharing module present. It ignores its single SV argument, and returns
5624 'true'. Exists to avoid test for a NULL function pointer and because it
5625 could potentially warn under some level of strict-ness.
5631 Perl_sv_destroyable(pTHX_ SV *sv)
5633 PERL_UNUSED_CONTEXT;
5634 PERL_UNUSED_ARG(sv);
5639 Perl_parse_unicode_opts(pTHX_ const char **popt)
5641 const char *p = *popt;
5644 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5648 opt = (U32) atoi(p);
5651 if (*p && *p != '\n' && *p != '\r') {
5652 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5654 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
5660 case PERL_UNICODE_STDIN:
5661 opt |= PERL_UNICODE_STDIN_FLAG; break;
5662 case PERL_UNICODE_STDOUT:
5663 opt |= PERL_UNICODE_STDOUT_FLAG; break;
5664 case PERL_UNICODE_STDERR:
5665 opt |= PERL_UNICODE_STDERR_FLAG; break;
5666 case PERL_UNICODE_STD:
5667 opt |= PERL_UNICODE_STD_FLAG; break;
5668 case PERL_UNICODE_IN:
5669 opt |= PERL_UNICODE_IN_FLAG; break;
5670 case PERL_UNICODE_OUT:
5671 opt |= PERL_UNICODE_OUT_FLAG; break;
5672 case PERL_UNICODE_INOUT:
5673 opt |= PERL_UNICODE_INOUT_FLAG; break;
5674 case PERL_UNICODE_LOCALE:
5675 opt |= PERL_UNICODE_LOCALE_FLAG; break;
5676 case PERL_UNICODE_ARGV:
5677 opt |= PERL_UNICODE_ARGV_FLAG; break;
5678 case PERL_UNICODE_UTF8CACHEASSERT:
5679 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
5681 if (*p != '\n' && *p != '\r') {
5682 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5685 "Unknown Unicode option letter '%c'", *p);
5692 opt = PERL_UNICODE_DEFAULT_FLAGS;
5694 the_end_of_the_opts_parser:
5696 if (opt & ~PERL_UNICODE_ALL_FLAGS)
5697 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
5698 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5710 * This is really just a quick hack which grabs various garbage
5711 * values. It really should be a real hash algorithm which
5712 * spreads the effect of every input bit onto every output bit,
5713 * if someone who knows about such things would bother to write it.
5714 * Might be a good idea to add that function to CORE as well.
5715 * No numbers below come from careful analysis or anything here,
5716 * except they are primes and SEED_C1 > 1E6 to get a full-width
5717 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5718 * probably be bigger too.
5721 # define SEED_C1 1000003
5722 #define SEED_C4 73819
5724 # define SEED_C1 25747
5725 #define SEED_C4 20639
5729 #define SEED_C5 26107
5731 #ifndef PERL_NO_DEV_RANDOM
5736 # include <starlet.h>
5737 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5738 * in 100-ns units, typically incremented ever 10 ms. */
5739 unsigned int when[2];
5741 # ifdef HAS_GETTIMEOFDAY
5742 struct timeval when;
5748 /* This test is an escape hatch, this symbol isn't set by Configure. */
5749 #ifndef PERL_NO_DEV_RANDOM
5750 #ifndef PERL_RANDOM_DEVICE
5751 /* /dev/random isn't used by default because reads from it will block
5752 * if there isn't enough entropy available. You can compile with
5753 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5754 * is enough real entropy to fill the seed. */
5755 # define PERL_RANDOM_DEVICE "/dev/urandom"
5757 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5759 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5768 _ckvmssts(sys$gettim(when));
5769 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5771 # ifdef HAS_GETTIMEOFDAY
5772 PerlProc_gettimeofday(&when,NULL);
5773 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5776 u = (U32)SEED_C1 * when;
5779 u += SEED_C3 * (U32)PerlProc_getpid();
5780 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5781 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5782 u += SEED_C5 * (U32)PTR2UV(&when);
5788 Perl_get_hash_seed(pTHX)
5791 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
5797 if (s && isDIGIT(*s))
5798 myseed = (UV)Atoul(s);
5800 #ifdef USE_HASH_SEED_EXPLICIT
5804 /* Compute a random seed */
5805 (void)seedDrand01((Rand_seed_t)seed());
5806 myseed = (UV)(Drand01() * (NV)UV_MAX);
5807 #if RANDBITS < (UVSIZE * 8)
5808 /* Since there are not enough randbits to to reach all
5809 * the bits of a UV, the low bits might need extra
5810 * help. Sum in another random number that will
5811 * fill in the low bits. */
5813 (UV)(Drand01() * (NV)((((UV)1) << ((UVSIZE * 8 - RANDBITS))) - 1));
5814 #endif /* RANDBITS < (UVSIZE * 8) */
5815 if (myseed == 0) { /* Superparanoia. */
5816 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5818 Perl_croak(aTHX_ "Your random numbers are not that random");
5821 PL_rehash_seed_set = TRUE;
5828 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5830 const char * const stashpv = CopSTASHPV(c);
5831 const char * const name = HvNAME_get(hv);
5832 PERL_UNUSED_CONTEXT;
5833 PERL_ARGS_ASSERT_STASHPV_HVNAME_MATCH;
5835 if (stashpv == name)
5837 if (stashpv && name)
5838 if (strEQ(stashpv, name))
5845 #ifdef PERL_GLOBAL_STRUCT
5847 #define PERL_GLOBAL_STRUCT_INIT
5848 #include "opcode.h" /* the ppaddr and check */
5851 Perl_init_global_struct(pTHX)
5853 struct perl_vars *plvarsp = NULL;
5854 # ifdef PERL_GLOBAL_STRUCT
5855 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5856 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5857 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5858 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5859 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5863 plvarsp = PL_VarsPtr;
5864 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5869 # define PERLVAR(prefix,var,type) /**/
5870 # define PERLVARA(prefix,var,n,type) /**/
5871 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
5872 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
5873 # include "perlvars.h"
5878 # ifdef PERL_GLOBAL_STRUCT
5881 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5882 if (!plvarsp->Gppaddr)
5886 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5887 if (!plvarsp->Gcheck)
5889 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5890 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5892 # ifdef PERL_SET_VARS
5893 PERL_SET_VARS(plvarsp);
5895 # undef PERL_GLOBAL_STRUCT_INIT
5900 #endif /* PERL_GLOBAL_STRUCT */
5902 #ifdef PERL_GLOBAL_STRUCT
5905 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5907 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
5908 # ifdef PERL_GLOBAL_STRUCT
5909 # ifdef PERL_UNSET_VARS
5910 PERL_UNSET_VARS(plvarsp);
5912 free(plvarsp->Gppaddr);
5913 free(plvarsp->Gcheck);
5914 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5920 #endif /* PERL_GLOBAL_STRUCT */
5924 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
5925 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
5926 * given, and you supply your own implementation.
5928 * The default implementation reads a single env var, PERL_MEM_LOG,
5929 * expecting one or more of the following:
5931 * \d+ - fd fd to write to : must be 1st (atoi)
5932 * 'm' - memlog was PERL_MEM_LOG=1
5933 * 's' - svlog was PERL_SV_LOG=1
5934 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
5936 * This makes the logger controllable enough that it can reasonably be
5937 * added to the system perl.
5940 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
5941 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5943 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5945 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
5946 * writes to. In the default logger, this is settable at runtime.
5948 #ifndef PERL_MEM_LOG_FD
5949 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5952 #ifndef PERL_MEM_LOG_NOIMPL
5954 # ifdef DEBUG_LEAKING_SCALARS
5955 # define SV_LOG_SERIAL_FMT " [%lu]"
5956 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
5958 # define SV_LOG_SERIAL_FMT
5959 # define _SV_LOG_SERIAL_ARG(sv)
5963 S_mem_log_common(enum mem_log_type mlt, const UV n,
5964 const UV typesize, const char *type_name, const SV *sv,
5965 Malloc_t oldalloc, Malloc_t newalloc,
5966 const char *filename, const int linenumber,
5967 const char *funcname)
5971 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
5973 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
5976 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
5978 /* We can't use SVs or PerlIO for obvious reasons,
5979 * so we'll use stdio and low-level IO instead. */
5980 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5982 # ifdef HAS_GETTIMEOFDAY
5983 # define MEM_LOG_TIME_FMT "%10d.%06d: "
5984 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
5986 gettimeofday(&tv, 0);
5988 # define MEM_LOG_TIME_FMT "%10d: "
5989 # define MEM_LOG_TIME_ARG (int)when
5993 /* If there are other OS specific ways of hires time than
5994 * gettimeofday() (see ext/Time-HiRes), the easiest way is
5995 * probably that they would be used to fill in the struct
5999 int fd = atoi(pmlenv);
6001 fd = PERL_MEM_LOG_FD;
6003 if (strchr(pmlenv, 't')) {
6004 len = my_snprintf(buf, sizeof(buf),
6005 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
6006 PerlLIO_write(fd, buf, len);
6010 len = my_snprintf(buf, sizeof(buf),
6011 "alloc: %s:%d:%s: %"IVdf" %"UVuf
6012 " %s = %"IVdf": %"UVxf"\n",
6013 filename, linenumber, funcname, n, typesize,
6014 type_name, n * typesize, PTR2UV(newalloc));
6017 len = my_snprintf(buf, sizeof(buf),
6018 "realloc: %s:%d:%s: %"IVdf" %"UVuf
6019 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
6020 filename, linenumber, funcname, n, typesize,
6021 type_name, n * typesize, PTR2UV(oldalloc),
6025 len = my_snprintf(buf, sizeof(buf),
6026 "free: %s:%d:%s: %"UVxf"\n",
6027 filename, linenumber, funcname,
6032 len = my_snprintf(buf, sizeof(buf),
6033 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
6034 mlt == MLT_NEW_SV ? "new" : "del",
6035 filename, linenumber, funcname,
6036 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
6041 PerlLIO_write(fd, buf, len);
6045 #endif /* !PERL_MEM_LOG_NOIMPL */
6047 #ifndef PERL_MEM_LOG_NOIMPL
6049 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
6050 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
6052 /* this is suboptimal, but bug compatible. User is providing their
6053 own implementation, but is getting these functions anyway, and they
6054 do nothing. But _NOIMPL users should be able to cope or fix */
6056 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
6057 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
6061 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
6063 const char *filename, const int linenumber,
6064 const char *funcname)
6066 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
6067 NULL, NULL, newalloc,
6068 filename, linenumber, funcname);
6073 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
6074 Malloc_t oldalloc, Malloc_t newalloc,
6075 const char *filename, const int linenumber,
6076 const char *funcname)
6078 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
6079 NULL, oldalloc, newalloc,
6080 filename, linenumber, funcname);
6085 Perl_mem_log_free(Malloc_t oldalloc,
6086 const char *filename, const int linenumber,
6087 const char *funcname)
6089 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
6090 filename, linenumber, funcname);
6095 Perl_mem_log_new_sv(const SV *sv,
6096 const char *filename, const int linenumber,
6097 const char *funcname)
6099 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
6100 filename, linenumber, funcname);
6104 Perl_mem_log_del_sv(const SV *sv,
6105 const char *filename, const int linenumber,
6106 const char *funcname)
6108 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
6109 filename, linenumber, funcname);
6112 #endif /* PERL_MEM_LOG */
6115 =for apidoc my_sprintf
6117 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
6118 the length of the string written to the buffer. Only rare pre-ANSI systems
6119 need the wrapper function - usually this is a direct call to C<sprintf>.
6123 #ifndef SPRINTF_RETURNS_STRLEN
6125 Perl_my_sprintf(char *buffer, const char* pat, ...)
6128 PERL_ARGS_ASSERT_MY_SPRINTF;
6129 va_start(args, pat);
6130 vsprintf(buffer, pat, args);
6132 return strlen(buffer);
6137 =for apidoc my_snprintf
6139 The C library C<snprintf> functionality, if available and
6140 standards-compliant (uses C<vsnprintf>, actually). However, if the
6141 C<vsnprintf> is not available, will unfortunately use the unsafe
6142 C<vsprintf> which can overrun the buffer (there is an overrun check,
6143 but that may be too late). Consider using C<sv_vcatpvf> instead, or
6144 getting C<vsnprintf>.
6149 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
6154 PERL_ARGS_ASSERT_MY_SNPRINTF;
6155 va_start(ap, format);
6156 #ifdef HAS_VSNPRINTF
6157 retval = vsnprintf(buffer, len, format, ap);
6159 retval = vsprintf(buffer, format, ap);
6162 /* vsprintf() shows failure with < 0 */
6164 #ifdef HAS_VSNPRINTF
6165 /* vsnprintf() shows failure with >= len */
6167 (len > 0 && (Size_t)retval >= len)
6170 Perl_croak(aTHX_ "panic: my_snprintf buffer overflow");
6175 =for apidoc my_vsnprintf
6177 The C library C<vsnprintf> if available and standards-compliant.
6178 However, if if the C<vsnprintf> is not available, will unfortunately
6179 use the unsafe C<vsprintf> which can overrun the buffer (there is an
6180 overrun check, but that may be too late). Consider using
6181 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
6186 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
6193 PERL_ARGS_ASSERT_MY_VSNPRINTF;
6195 Perl_va_copy(ap, apc);
6196 # ifdef HAS_VSNPRINTF
6197 retval = vsnprintf(buffer, len, format, apc);
6199 retval = vsprintf(buffer, format, apc);
6202 # ifdef HAS_VSNPRINTF
6203 retval = vsnprintf(buffer, len, format, ap);
6205 retval = vsprintf(buffer, format, ap);
6207 #endif /* #ifdef NEED_VA_COPY */
6208 /* vsprintf() shows failure with < 0 */
6210 #ifdef HAS_VSNPRINTF
6211 /* vsnprintf() shows failure with >= len */
6213 (len > 0 && (Size_t)retval >= len)
6216 Perl_croak(aTHX_ "panic: my_vsnprintf buffer overflow");
6221 Perl_my_clearenv(pTHX)
6224 #if ! defined(PERL_MICRO)
6225 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
6227 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
6228 # if defined(USE_ENVIRON_ARRAY)
6229 # if defined(USE_ITHREADS)
6230 /* only the parent thread can clobber the process environment */
6231 if (PL_curinterp == aTHX)
6232 # endif /* USE_ITHREADS */
6234 # if ! defined(PERL_USE_SAFE_PUTENV)
6235 if ( !PL_use_safe_putenv) {
6237 if (environ == PL_origenviron)
6238 environ = (char**)safesysmalloc(sizeof(char*));
6240 for (i = 0; environ[i]; i++)
6241 (void)safesysfree(environ[i]);
6244 # else /* PERL_USE_SAFE_PUTENV */
6245 # if defined(HAS_CLEARENV)
6247 # elif defined(HAS_UNSETENV)
6248 int bsiz = 80; /* Most envvar names will be shorter than this. */
6249 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
6250 char *buf = (char*)safesysmalloc(bufsiz);
6251 while (*environ != NULL) {
6252 char *e = strchr(*environ, '=');
6253 int l = e ? e - *environ : (int)strlen(*environ);
6255 (void)safesysfree(buf);
6256 bsiz = l + 1; /* + 1 for the \0. */
6257 buf = (char*)safesysmalloc(bufsiz);
6259 memcpy(buf, *environ, l);
6261 (void)unsetenv(buf);
6263 (void)safesysfree(buf);
6264 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
6265 /* Just null environ and accept the leakage. */
6267 # endif /* HAS_CLEARENV || HAS_UNSETENV */
6268 # endif /* ! PERL_USE_SAFE_PUTENV */
6270 # endif /* USE_ENVIRON_ARRAY */
6271 # endif /* PERL_IMPLICIT_SYS || WIN32 */
6272 #endif /* PERL_MICRO */
6275 #ifdef PERL_IMPLICIT_CONTEXT
6277 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
6278 the global PL_my_cxt_index is incremented, and that value is assigned to
6279 that module's static my_cxt_index (who's address is passed as an arg).
6280 Then, for each interpreter this function is called for, it makes sure a
6281 void* slot is available to hang the static data off, by allocating or
6282 extending the interpreter's PL_my_cxt_list array */
6284 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
6286 Perl_my_cxt_init(pTHX_ int *index, size_t size)
6290 PERL_ARGS_ASSERT_MY_CXT_INIT;
6292 /* this module hasn't been allocated an index yet */
6293 #if defined(USE_ITHREADS)
6294 MUTEX_LOCK(&PL_my_ctx_mutex);
6296 *index = PL_my_cxt_index++;
6297 #if defined(USE_ITHREADS)
6298 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6302 /* make sure the array is big enough */
6303 if (PL_my_cxt_size <= *index) {
6304 if (PL_my_cxt_size) {
6305 while (PL_my_cxt_size <= *index)
6306 PL_my_cxt_size *= 2;
6307 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6310 PL_my_cxt_size = 16;
6311 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6314 /* newSV() allocates one more than needed */
6315 p = (void*)SvPVX(newSV(size-1));
6316 PL_my_cxt_list[*index] = p;
6317 Zero(p, size, char);
6321 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6324 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
6329 PERL_ARGS_ASSERT_MY_CXT_INDEX;
6331 for (index = 0; index < PL_my_cxt_index; index++) {
6332 const char *key = PL_my_cxt_keys[index];
6333 /* try direct pointer compare first - there are chances to success,
6334 * and it's much faster.
6336 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
6343 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
6349 PERL_ARGS_ASSERT_MY_CXT_INIT;
6351 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
6353 /* this module hasn't been allocated an index yet */
6354 #if defined(USE_ITHREADS)
6355 MUTEX_LOCK(&PL_my_ctx_mutex);
6357 index = PL_my_cxt_index++;
6358 #if defined(USE_ITHREADS)
6359 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6363 /* make sure the array is big enough */
6364 if (PL_my_cxt_size <= index) {
6365 int old_size = PL_my_cxt_size;
6367 if (PL_my_cxt_size) {
6368 while (PL_my_cxt_size <= index)
6369 PL_my_cxt_size *= 2;
6370 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6371 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6374 PL_my_cxt_size = 16;
6375 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6376 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6378 for (i = old_size; i < PL_my_cxt_size; i++) {
6379 PL_my_cxt_keys[i] = 0;
6380 PL_my_cxt_list[i] = 0;
6383 PL_my_cxt_keys[index] = my_cxt_key;
6384 /* newSV() allocates one more than needed */
6385 p = (void*)SvPVX(newSV(size-1));
6386 PL_my_cxt_list[index] = p;
6387 Zero(p, size, char);
6390 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6391 #endif /* PERL_IMPLICIT_CONTEXT */
6394 Perl_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
6398 const char *vn = NULL;
6399 SV *const module = PL_stack_base[ax];
6401 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
6403 if (items >= 2) /* version supplied as bootstrap arg */
6404 sv = PL_stack_base[ax + 1];
6406 /* XXX GV_ADDWARN */
6408 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6409 if (!sv || !SvOK(sv)) {
6411 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6415 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
6416 SV *pmsv = sv_derived_from(sv, "version")
6417 ? sv : sv_2mortal(new_version(sv));
6418 xssv = upg_version(xssv, 0);
6419 if ( vcmp(pmsv,xssv) ) {
6420 SV *string = vstringify(xssv);
6421 SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
6422 " does not match ", module, string);
6424 SvREFCNT_dec(string);
6425 string = vstringify(pmsv);
6428 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, module, vn,
6431 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, string);
6433 SvREFCNT_dec(string);
6435 Perl_sv_2mortal(aTHX_ xpt);
6436 Perl_croak_sv(aTHX_ xpt);
6442 Perl_xs_apiversion_bootcheck(pTHX_ SV *module, const char *api_p,
6446 SV *compver = Perl_newSVpvn_flags(aTHX_ api_p, api_len, SVs_TEMP);
6449 PERL_ARGS_ASSERT_XS_APIVERSION_BOOTCHECK;
6451 /* This might croak */
6452 compver = upg_version(compver, 0);
6453 /* This should never croak */
6454 runver = new_version(PL_apiversion);
6455 if (vcmp(compver, runver)) {
6456 SV *compver_string = vstringify(compver);
6457 SV *runver_string = vstringify(runver);
6458 xpt = Perl_newSVpvf(aTHX_ "Perl API version %"SVf
6459 " of %"SVf" does not match %"SVf,
6460 compver_string, module, runver_string);
6461 Perl_sv_2mortal(aTHX_ xpt);
6463 SvREFCNT_dec(compver_string);
6464 SvREFCNT_dec(runver_string);
6466 SvREFCNT_dec(runver);
6468 Perl_croak_sv(aTHX_ xpt);
6473 Perl_my_strlcat(char *dst, const char *src, Size_t size)
6475 Size_t used, length, copy;
6478 length = strlen(src);
6479 if (size > 0 && used < size - 1) {
6480 copy = (length >= size - used) ? size - used - 1 : length;
6481 memcpy(dst + used, src, copy);
6482 dst[used + copy] = '\0';
6484 return used + length;
6490 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
6492 Size_t length, copy;
6494 length = strlen(src);
6496 copy = (length >= size) ? size - 1 : length;
6497 memcpy(dst, src, copy);
6504 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
6505 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
6506 long _ftol( double ); /* Defined by VC6 C libs. */
6507 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
6511 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
6514 SV * const dbsv = GvSVn(PL_DBsub);
6515 const bool save_taint = PL_tainted;
6517 /* We do not care about using sv to call CV;
6518 * it's for informational purposes only.
6521 PERL_ARGS_ASSERT_GET_DB_SUB;
6525 if (!PERLDB_SUB_NN) {
6528 if ( svp && ((CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
6529 || strEQ(GvNAME(gv), "END")
6530 || ((GvCV(gv) != cv) && /* Could be imported, and old sub redefined. */
6531 !( (SvTYPE(*svp) == SVt_PVGV)
6532 && (GvCV((const GV *)*svp) == cv)
6533 && (gv = (GV *)*svp)
6537 /* Use GV from the stack as a fallback. */
6538 /* GV is potentially non-unique, or contain different CV. */
6539 SV * const tmp = newRV(MUTABLE_SV(cv));
6540 sv_setsv(dbsv, tmp);
6544 gv_efullname3(dbsv, gv, NULL);
6548 const int type = SvTYPE(dbsv);
6549 if (type < SVt_PVIV && type != SVt_IV)
6550 sv_upgrade(dbsv, SVt_PVIV);
6551 (void)SvIOK_on(dbsv);
6552 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
6554 TAINT_IF(save_taint);
6558 Perl_my_dirfd(pTHX_ DIR * dir) {
6560 /* Most dirfd implementations have problems when passed NULL. */
6565 #elif defined(HAS_DIR_DD_FD)
6568 Perl_die(aTHX_ PL_no_func, "dirfd");
6575 Perl_get_re_arg(pTHX_ SV *sv) {
6581 sv = MUTABLE_SV(SvRV(sv));
6582 if (SvTYPE(sv) == SVt_REGEXP)
6583 return (REGEXP*) sv;
6591 * c-indentation-style: bsd
6593 * indent-tabs-mode: t
6596 * ex: set ts=8 sts=4 sw=4 noet: