3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * 'Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content.' --Gandalf to Pippin
15 * [p.598 of _The Lord of the Rings_, III/xi: "The PalantÃr"]
18 /* This file contains assorted utility routines.
19 * Which is a polite way of saying any stuff that people couldn't think of
20 * a better place for. Amongst other things, it includes the warning and
21 * dieing stuff, plus wrappers for malloc code.
25 #define PERL_IN_UTIL_C
29 #include "perliol.h" /* For PerlIOUnix_refcnt */
35 # define SIG_ERR ((Sighandler_t) -1)
40 /* Missing protos on LynxOS */
45 # include <sys/wait.h>
50 # include <sys/select.h>
56 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
57 # define FD_CLOEXEC 1 /* NeXT needs this */
60 /* NOTE: Do not call the next three routines directly. Use the macros
61 * in handy.h, so that we can easily redefine everything to do tracking of
62 * allocated hunks back to the original New to track down any memory leaks.
63 * XXX This advice seems to be widely ignored :-( --AD August 1996.
70 /* Can't use PerlIO to write as it allocates memory */
71 PerlLIO_write(PerlIO_fileno(Perl_error_log),
72 PL_no_mem, strlen(PL_no_mem));
74 NORETURN_FUNCTION_END;
77 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
78 # define ALWAYS_NEED_THX
81 /* paranoid version of system's malloc() */
84 Perl_safesysmalloc(MEM_SIZE size)
86 #ifdef ALWAYS_NEED_THX
92 PerlIO_printf(Perl_error_log,
93 "Allocation too large: %lx\n", size) FLUSH;
96 #endif /* HAS_64K_LIMIT */
97 #ifdef PERL_TRACK_MEMPOOL
102 Perl_croak_nocontext("panic: malloc");
104 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
105 PERL_ALLOC_CHECK(ptr);
107 #ifdef PERL_TRACK_MEMPOOL
108 struct perl_memory_debug_header *const header
109 = (struct perl_memory_debug_header *)ptr;
113 PoisonNew(((char *)ptr), size, char);
116 #ifdef PERL_TRACK_MEMPOOL
117 header->interpreter = aTHX;
118 /* Link us into the list. */
119 header->prev = &PL_memory_debug_header;
120 header->next = PL_memory_debug_header.next;
121 PL_memory_debug_header.next = header;
122 header->next->prev = header;
126 ptr = (Malloc_t)((char*)ptr+sTHX);
128 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
132 #ifndef ALWAYS_NEED_THX
138 return write_no_mem();
144 /* paranoid version of system's realloc() */
147 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
149 #ifdef ALWAYS_NEED_THX
153 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
154 Malloc_t PerlMem_realloc();
155 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
159 PerlIO_printf(Perl_error_log,
160 "Reallocation too large: %lx\n", size) FLUSH;
163 #endif /* HAS_64K_LIMIT */
170 return safesysmalloc(size);
171 #ifdef PERL_TRACK_MEMPOOL
172 where = (Malloc_t)((char*)where-sTHX);
175 struct perl_memory_debug_header *const header
176 = (struct perl_memory_debug_header *)where;
178 if (header->interpreter != aTHX) {
179 Perl_croak_nocontext("panic: realloc from wrong pool");
181 assert(header->next->prev == header);
182 assert(header->prev->next == header);
184 if (header->size > size) {
185 const MEM_SIZE freed_up = header->size - size;
186 char *start_of_freed = ((char *)where) + size;
187 PoisonFree(start_of_freed, freed_up, char);
195 Perl_croak_nocontext("panic: realloc");
197 ptr = (Malloc_t)PerlMem_realloc(where,size);
198 PERL_ALLOC_CHECK(ptr);
200 /* MUST do this fixup first, before doing ANYTHING else, as anything else
201 might allocate memory/free/move memory, and until we do the fixup, it
202 may well be chasing (and writing to) free memory. */
203 #ifdef PERL_TRACK_MEMPOOL
205 struct perl_memory_debug_header *const header
206 = (struct perl_memory_debug_header *)ptr;
209 if (header->size < size) {
210 const MEM_SIZE fresh = size - header->size;
211 char *start_of_fresh = ((char *)ptr) + size;
212 PoisonNew(start_of_fresh, fresh, char);
216 header->next->prev = header;
217 header->prev->next = header;
219 ptr = (Malloc_t)((char*)ptr+sTHX);
223 /* In particular, must do that fixup above before logging anything via
224 *printf(), as it can reallocate memory, which can cause SEGVs. */
226 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
227 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
234 #ifndef ALWAYS_NEED_THX
240 return write_no_mem();
246 /* safe version of system's free() */
249 Perl_safesysfree(Malloc_t where)
251 #ifdef ALWAYS_NEED_THX
256 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
258 #ifdef PERL_TRACK_MEMPOOL
259 where = (Malloc_t)((char*)where-sTHX);
261 struct perl_memory_debug_header *const header
262 = (struct perl_memory_debug_header *)where;
264 if (header->interpreter != aTHX) {
265 Perl_croak_nocontext("panic: free from wrong pool");
268 Perl_croak_nocontext("panic: duplicate free");
270 if (!(header->next) || header->next->prev != header
271 || header->prev->next != header) {
272 Perl_croak_nocontext("panic: bad free");
274 /* Unlink us from the chain. */
275 header->next->prev = header->prev;
276 header->prev->next = header->next;
278 PoisonNew(where, header->size, char);
280 /* Trigger the duplicate free warning. */
288 /* safe version of system's calloc() */
291 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
293 #ifdef ALWAYS_NEED_THX
297 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
298 MEM_SIZE total_size = 0;
301 /* Even though calloc() for zero bytes is strange, be robust. */
302 if (size && (count <= MEM_SIZE_MAX / size)) {
303 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
304 total_size = size * count;
308 Perl_croak_nocontext("%s", PL_memory_wrap);
309 #ifdef PERL_TRACK_MEMPOOL
310 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
313 Perl_croak_nocontext("%s", PL_memory_wrap);
316 if (total_size > 0xffff) {
317 PerlIO_printf(Perl_error_log,
318 "Allocation too large: %lx\n", total_size) FLUSH;
321 #endif /* HAS_64K_LIMIT */
323 if ((long)size < 0 || (long)count < 0)
324 Perl_croak_nocontext("panic: calloc");
326 #ifdef PERL_TRACK_MEMPOOL
327 /* Have to use malloc() because we've added some space for our tracking
329 /* malloc(0) is non-portable. */
330 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
332 /* Use calloc() because it might save a memset() if the memory is fresh
333 and clean from the OS. */
335 ptr = (Malloc_t)PerlMem_calloc(count, size);
336 else /* calloc(0) is non-portable. */
337 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
339 PERL_ALLOC_CHECK(ptr);
340 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));
342 #ifdef PERL_TRACK_MEMPOOL
344 struct perl_memory_debug_header *const header
345 = (struct perl_memory_debug_header *)ptr;
347 memset((void*)ptr, 0, total_size);
348 header->interpreter = aTHX;
349 /* Link us into the list. */
350 header->prev = &PL_memory_debug_header;
351 header->next = PL_memory_debug_header.next;
352 PL_memory_debug_header.next = header;
353 header->next->prev = header;
355 header->size = total_size;
357 ptr = (Malloc_t)((char*)ptr+sTHX);
363 #ifndef ALWAYS_NEED_THX
368 return write_no_mem();
372 /* These must be defined when not using Perl's malloc for binary
377 Malloc_t Perl_malloc (MEM_SIZE nbytes)
380 return (Malloc_t)PerlMem_malloc(nbytes);
383 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
386 return (Malloc_t)PerlMem_calloc(elements, size);
389 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
392 return (Malloc_t)PerlMem_realloc(where, nbytes);
395 Free_t Perl_mfree (Malloc_t where)
403 /* copy a string up to some (non-backslashed) delimiter, if any */
406 Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
410 PERL_ARGS_ASSERT_DELIMCPY;
412 for (tolen = 0; from < fromend; from++, tolen++) {
414 if (from[1] != delim) {
421 else if (*from == delim)
432 /* return ptr to little string in big string, NULL if not found */
433 /* This routine was donated by Corey Satten. */
436 Perl_instr(register const char *big, register const char *little)
440 PERL_ARGS_ASSERT_INSTR;
448 register const char *s, *x;
451 for (x=big,s=little; *s; /**/ ) {
462 return (char*)(big-1);
467 /* same as instr but allow embedded nulls */
470 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
472 PERL_ARGS_ASSERT_NINSTR;
476 const char first = *little;
478 bigend -= lend - little++;
480 while (big <= bigend) {
481 if (*big++ == first) {
482 for (x=big,s=little; s < lend; x++,s++) {
486 return (char*)(big-1);
493 /* reverse of the above--find last substring */
496 Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
498 register const char *bigbeg;
499 register const I32 first = *little;
500 register const char * const littleend = lend;
502 PERL_ARGS_ASSERT_RNINSTR;
504 if (little >= littleend)
505 return (char*)bigend;
507 big = bigend - (littleend - little++);
508 while (big >= bigbeg) {
509 register const char *s, *x;
512 for (x=big+2,s=little; s < littleend; /**/ ) {
521 return (char*)(big+1);
526 /* As a space optimization, we do not compile tables for strings of length
527 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
528 special-cased in fbm_instr().
530 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
533 =head1 Miscellaneous Functions
535 =for apidoc fbm_compile
537 Analyses the string in order to make fast searches on it using fbm_instr()
538 -- the Boyer-Moore algorithm.
544 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
547 register const U8 *s;
554 PERL_ARGS_ASSERT_FBM_COMPILE;
556 /* Refuse to fbm_compile a studied scalar, as this gives more flexibility in
557 SV flag usage. No real-world code would ever end up using a studied
558 scalar as a compile-time second argument to index, so this isn't a real
566 if (flags & FBMcf_TAIL) {
567 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
568 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
569 if (mg && mg->mg_len >= 0)
572 s = (U8*)SvPV_force_mutable(sv, len);
573 if (len == 0) /* TAIL might be on a zero-length string. */
575 SvUPGRADE(sv, SVt_PVMG);
580 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
581 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
582 to call SvVALID_off() if the scalar was assigned to.
584 The comment itself (and "deeper magic" below) date back to
585 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
587 where the magic (presumably) was that the scalar had a BM table hidden
590 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
591 the table instead of the previous (somewhat hacky) approach of co-opting
592 the string buffer and storing it after the string. */
594 assert(!mg_find(sv, PERL_MAGIC_bm));
595 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
599 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
601 const U8 mlen = (len>255) ? 255 : (U8)len;
602 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
605 Newx(table, 256, U8);
606 memset((void*)table, mlen, 256);
607 mg->mg_ptr = (char *)table;
610 s += len - 1; /* last char */
613 if (table[*s] == mlen)
619 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
620 for (i = 0; i < len; i++) {
621 if (PL_freq[s[i]] < frequency) {
623 frequency = PL_freq[s[i]];
626 BmRARE(sv) = s[rarest];
627 BmPREVIOUS(sv) = rarest;
628 BmUSEFUL(sv) = 100; /* Initial value */
629 if (flags & FBMcf_TAIL)
631 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
632 BmRARE(sv), BmPREVIOUS(sv)));
635 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
636 /* If SvTAIL is actually due to \Z or \z, this gives false positives
640 =for apidoc fbm_instr
642 Returns the location of the SV in the string delimited by C<str> and
643 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
644 does not have to be fbm_compiled, but the search will not be as fast
651 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
653 register unsigned char *s;
655 register const unsigned char *little
656 = (const unsigned char *)SvPV_const(littlestr,l);
657 register STRLEN littlelen = l;
658 register const I32 multiline = flags & FBMrf_MULTILINE;
660 PERL_ARGS_ASSERT_FBM_INSTR;
662 if ((STRLEN)(bigend - big) < littlelen) {
663 if ( SvTAIL(littlestr)
664 && ((STRLEN)(bigend - big) == littlelen - 1)
666 || (*big == *little &&
667 memEQ((char *)big, (char *)little, littlelen - 1))))
672 switch (littlelen) { /* Special cases for 0, 1 and 2 */
674 return (char*)big; /* Cannot be SvTAIL! */
676 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
677 /* Know that bigend != big. */
678 if (bigend[-1] == '\n')
679 return (char *)(bigend - 1);
680 return (char *) bigend;
688 if (SvTAIL(littlestr))
689 return (char *) bigend;
692 if (SvTAIL(littlestr) && !multiline) {
693 if (bigend[-1] == '\n' && bigend[-2] == *little)
694 return (char*)bigend - 2;
695 if (bigend[-1] == *little)
696 return (char*)bigend - 1;
700 /* This should be better than FBM if c1 == c2, and almost
701 as good otherwise: maybe better since we do less indirection.
702 And we save a lot of memory by caching no table. */
703 const unsigned char c1 = little[0];
704 const unsigned char c2 = little[1];
709 while (s <= bigend) {
719 goto check_1char_anchor;
730 goto check_1char_anchor;
733 while (s <= bigend) {
738 goto check_1char_anchor;
747 check_1char_anchor: /* One char and anchor! */
748 if (SvTAIL(littlestr) && (*bigend == *little))
749 return (char *)bigend; /* bigend is already decremented. */
752 break; /* Only lengths 0 1 and 2 have special-case code. */
755 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
756 s = bigend - littlelen;
757 if (s >= big && bigend[-1] == '\n' && *s == *little
758 /* Automatically of length > 2 */
759 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
761 return (char*)s; /* how sweet it is */
764 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
766 return (char*)s + 1; /* how sweet it is */
770 if (!SvVALID(littlestr)) {
771 char * const b = ninstr((char*)big,(char*)bigend,
772 (char*)little, (char*)little + littlelen);
774 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
775 /* Chop \n from littlestr: */
776 s = bigend - littlelen + 1;
778 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
788 if (littlelen > (STRLEN)(bigend - big))
792 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
793 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
794 register const unsigned char *oldlittle;
796 --littlelen; /* Last char found by table lookup */
799 little += littlelen; /* last char */
805 if ((tmp = table[*s])) {
806 if ((s += tmp) < bigend)
810 else { /* less expensive than calling strncmp() */
811 register unsigned char * const olds = s;
816 if (*--s == *--little)
818 s = olds + 1; /* here we pay the price for failure */
820 if (s < bigend) /* fake up continue to outer loop */
830 && memEQ((char *)(bigend - littlelen),
831 (char *)(oldlittle - littlelen), littlelen) )
832 return (char*)bigend - littlelen;
837 /* start_shift, end_shift are positive quantities which give offsets
838 of ends of some substring of bigstr.
839 If "last" we want the last occurrence.
840 old_posp is the way of communication between consequent calls if
841 the next call needs to find the .
842 The initial *old_posp should be -1.
844 Note that we take into account SvTAIL, so one can get extra
845 optimizations if _ALL flag is set.
848 /* If SvTAIL is actually due to \Z or \z, this gives false positives
849 if PL_multiline. In fact if !PL_multiline the authoritative answer
850 is not supported yet. */
853 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
856 register const unsigned char *big;
857 U32 pos = 0; /* hush a gcc warning */
858 register I32 previous;
860 register const unsigned char *little;
861 register I32 stop_pos;
862 register const unsigned char *littleend;
865 const void *screamnext_raw = NULL; /* hush a gcc warning */
866 bool cant_find = FALSE; /* hush a gcc warning */
868 PERL_ARGS_ASSERT_SCREAMINSTR;
870 assert(SvMAGICAL(bigstr));
871 mg = mg_find(bigstr, PERL_MAGIC_study);
873 assert(SvTYPE(littlestr) == SVt_PVMG);
874 assert(SvVALID(littlestr));
876 if (mg->mg_private == 1) {
877 const U8 *const screamfirst = (U8 *)mg->mg_ptr;
878 const U8 *const screamnext = screamfirst + 256;
880 screamnext_raw = (const void *)screamnext;
882 pos = *old_posp == -1
883 ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
884 cant_find = pos == (U8)~0;
885 } else if (mg->mg_private == 2) {
886 const U16 *const screamfirst = (U16 *)mg->mg_ptr;
887 const U16 *const screamnext = screamfirst + 256;
889 screamnext_raw = (const void *)screamnext;
891 pos = *old_posp == -1
892 ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
893 cant_find = pos == (U16)~0;
894 } else if (mg->mg_private == 4) {
895 const U32 *const screamfirst = (U32 *)mg->mg_ptr;
896 const U32 *const screamnext = screamfirst + 256;
898 screamnext_raw = (const void *)screamnext;
900 pos = *old_posp == -1
901 ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
902 cant_find = pos == (U32)~0;
904 Perl_croak(aTHX_ "panic: unknown study size %u", mg->mg_private);
908 if ( BmRARE(littlestr) == '\n'
909 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
910 little = (const unsigned char *)(SvPVX_const(littlestr));
911 littleend = little + SvCUR(littlestr);
918 little = (const unsigned char *)(SvPVX_const(littlestr));
919 littleend = little + SvCUR(littlestr);
921 /* The value of pos we can start at: */
922 previous = BmPREVIOUS(littlestr);
923 big = (const unsigned char *)(SvPVX_const(bigstr));
924 /* The value of pos we can stop at: */
925 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
926 if (previous + start_shift > stop_pos) {
928 stop_pos does not include SvTAIL in the count, so this check is incorrect
929 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
932 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
937 if (mg->mg_private == 1) {
938 const U8 *const screamnext = (const U8 *const) screamnext_raw;
939 while ((I32)pos < previous + start_shift) {
940 pos = screamnext[pos];
944 } else if (mg->mg_private == 2) {
945 const U16 *const screamnext = (const U16 *const) screamnext_raw;
946 while ((I32)pos < previous + start_shift) {
947 pos = screamnext[pos];
951 } else if (mg->mg_private == 4) {
952 const U32 *const screamnext = (const U32 *const) screamnext_raw;
953 while ((I32)pos < previous + start_shift) {
954 pos = screamnext[pos];
961 if ((I32)pos >= stop_pos) break;
962 if (big[pos] == first) {
963 const unsigned char *s = little;
964 const unsigned char *x = big + pos + 1;
965 while (s < littleend) {
970 if (s == littleend) {
971 *old_posp = (I32)pos;
972 if (!last) return (char *)(big+pos);
976 if (mg->mg_private == 1) {
977 pos = ((const U8 *const)screamnext_raw)[pos];
980 } else if (mg->mg_private == 2) {
981 pos = ((const U16 *const)screamnext_raw)[pos];
984 } else if (mg->mg_private == 4) {
985 pos = ((const U32 *const)screamnext_raw)[pos];
991 return (char *)(big+(*old_posp));
993 if (!SvTAIL(littlestr) || (end_shift > 0))
995 /* Ignore the trailing "\n". This code is not microoptimized */
996 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
997 stop_pos = littleend - little; /* Actual littlestr len */
1002 && ((stop_pos == 1) ||
1003 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
1011 Returns true if the leading len bytes of the strings s1 and s2 are the same
1012 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
1013 match themselves and their opposite case counterparts. Non-cased and non-ASCII
1014 range bytes match only themselves.
1021 Perl_foldEQ(const char *s1, const char *s2, register I32 len)
1023 register const U8 *a = (const U8 *)s1;
1024 register const U8 *b = (const U8 *)s2;
1026 PERL_ARGS_ASSERT_FOLDEQ;
1029 if (*a != *b && *a != PL_fold[*b])
1036 Perl_foldEQ_latin1(const char *s1, const char *s2, register I32 len)
1038 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
1039 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
1040 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
1041 * does it check that the strings each have at least 'len' characters */
1043 register const U8 *a = (const U8 *)s1;
1044 register const U8 *b = (const U8 *)s2;
1046 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
1049 if (*a != *b && *a != PL_fold_latin1[*b]) {
1058 =for apidoc foldEQ_locale
1060 Returns true if the leading len bytes of the strings s1 and s2 are the same
1061 case-insensitively in the current locale; false otherwise.
1067 Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
1070 register const U8 *a = (const U8 *)s1;
1071 register const U8 *b = (const U8 *)s2;
1073 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
1076 if (*a != *b && *a != PL_fold_locale[*b])
1083 /* copy a string to a safe spot */
1086 =head1 Memory Management
1090 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1091 string which is a duplicate of C<pv>. The size of the string is
1092 determined by C<strlen()>. The memory allocated for the new string can
1093 be freed with the C<Safefree()> function.
1099 Perl_savepv(pTHX_ const char *pv)
1101 PERL_UNUSED_CONTEXT;
1106 const STRLEN pvlen = strlen(pv)+1;
1107 Newx(newaddr, pvlen, char);
1108 return (char*)memcpy(newaddr, pv, pvlen);
1112 /* same thing but with a known length */
1117 Perl's version of what C<strndup()> would be if it existed. Returns a
1118 pointer to a newly allocated string which is a duplicate of the first
1119 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
1120 the new string can be freed with the C<Safefree()> function.
1126 Perl_savepvn(pTHX_ const char *pv, register I32 len)
1128 register char *newaddr;
1129 PERL_UNUSED_CONTEXT;
1131 Newx(newaddr,len+1,char);
1132 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1134 /* might not be null terminated */
1135 newaddr[len] = '\0';
1136 return (char *) CopyD(pv,newaddr,len,char);
1139 return (char *) ZeroD(newaddr,len+1,char);
1144 =for apidoc savesharedpv
1146 A version of C<savepv()> which allocates the duplicate string in memory
1147 which is shared between threads.
1152 Perl_savesharedpv(pTHX_ const char *pv)
1154 register char *newaddr;
1159 pvlen = strlen(pv)+1;
1160 newaddr = (char*)PerlMemShared_malloc(pvlen);
1162 return write_no_mem();
1164 return (char*)memcpy(newaddr, pv, pvlen);
1168 =for apidoc savesharedpvn
1170 A version of C<savepvn()> which allocates the duplicate string in memory
1171 which is shared between threads. (With the specific difference that a NULL
1172 pointer is not acceptable)
1177 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1179 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1181 PERL_ARGS_ASSERT_SAVESHAREDPVN;
1184 return write_no_mem();
1186 newaddr[len] = '\0';
1187 return (char*)memcpy(newaddr, pv, len);
1191 =for apidoc savesvpv
1193 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1194 the passed in SV using C<SvPV()>
1200 Perl_savesvpv(pTHX_ SV *sv)
1203 const char * const pv = SvPV_const(sv, len);
1204 register char *newaddr;
1206 PERL_ARGS_ASSERT_SAVESVPV;
1209 Newx(newaddr,len,char);
1210 return (char *) CopyD(pv,newaddr,len,char);
1214 =for apidoc savesharedsvpv
1216 A version of C<savesharedpv()> which allocates the duplicate string in
1217 memory which is shared between threads.
1223 Perl_savesharedsvpv(pTHX_ SV *sv)
1226 const char * const pv = SvPV_const(sv, len);
1228 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1230 return savesharedpvn(pv, len);
1233 /* the SV for Perl_form() and mess() is not kept in an arena */
1242 if (PL_phase != PERL_PHASE_DESTRUCT)
1243 return newSVpvs_flags("", SVs_TEMP);
1248 /* Create as PVMG now, to avoid any upgrading later */
1250 Newxz(any, 1, XPVMG);
1251 SvFLAGS(sv) = SVt_PVMG;
1252 SvANY(sv) = (void*)any;
1254 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1259 #if defined(PERL_IMPLICIT_CONTEXT)
1261 Perl_form_nocontext(const char* pat, ...)
1266 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1267 va_start(args, pat);
1268 retval = vform(pat, &args);
1272 #endif /* PERL_IMPLICIT_CONTEXT */
1275 =head1 Miscellaneous Functions
1278 Takes a sprintf-style format pattern and conventional
1279 (non-SV) arguments and returns the formatted string.
1281 (char *) Perl_form(pTHX_ const char* pat, ...)
1283 can be used any place a string (char *) is required:
1285 char * s = Perl_form("%d.%d",major,minor);
1287 Uses a single private buffer so if you want to format several strings you
1288 must explicitly copy the earlier strings away (and free the copies when you
1295 Perl_form(pTHX_ const char* pat, ...)
1299 PERL_ARGS_ASSERT_FORM;
1300 va_start(args, pat);
1301 retval = vform(pat, &args);
1307 Perl_vform(pTHX_ const char *pat, va_list *args)
1309 SV * const sv = mess_alloc();
1310 PERL_ARGS_ASSERT_VFORM;
1311 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1316 =for apidoc Am|SV *|mess|const char *pat|...
1318 Take a sprintf-style format pattern and argument list. These are used to
1319 generate a string message. If the message does not end with a newline,
1320 then it will be extended with some indication of the current location
1321 in the code, as described for L</mess_sv>.
1323 Normally, the resulting message is returned in a new mortal SV.
1324 During global destruction a single SV may be shared between uses of
1330 #if defined(PERL_IMPLICIT_CONTEXT)
1332 Perl_mess_nocontext(const char *pat, ...)
1337 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1338 va_start(args, pat);
1339 retval = vmess(pat, &args);
1343 #endif /* PERL_IMPLICIT_CONTEXT */
1346 Perl_mess(pTHX_ const char *pat, ...)
1350 PERL_ARGS_ASSERT_MESS;
1351 va_start(args, pat);
1352 retval = vmess(pat, &args);
1358 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1361 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1363 PERL_ARGS_ASSERT_CLOSEST_COP;
1365 if (!o || o == PL_op)
1368 if (o->op_flags & OPf_KIDS) {
1370 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1373 /* If the OP_NEXTSTATE has been optimised away we can still use it
1374 * the get the file and line number. */
1376 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1377 cop = (const COP *)kid;
1379 /* Keep searching, and return when we've found something. */
1381 new_cop = closest_cop(cop, kid);
1387 /* Nothing found. */
1393 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1395 Expands a message, intended for the user, to include an indication of
1396 the current location in the code, if the message does not already appear
1399 C<basemsg> is the initial message or object. If it is a reference, it
1400 will be used as-is and will be the result of this function. Otherwise it
1401 is used as a string, and if it already ends with a newline, it is taken
1402 to be complete, and the result of this function will be the same string.
1403 If the message does not end with a newline, then a segment such as C<at
1404 foo.pl line 37> will be appended, and possibly other clauses indicating
1405 the current state of execution. The resulting message will end with a
1408 Normally, the resulting message is returned in a new mortal SV.
1409 During global destruction a single SV may be shared between uses of this
1410 function. If C<consume> is true, then the function is permitted (but not
1411 required) to modify and return C<basemsg> instead of allocating a new SV.
1417 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1422 PERL_ARGS_ASSERT_MESS_SV;
1424 if (SvROK(basemsg)) {
1430 sv_setsv(sv, basemsg);
1435 if (SvPOK(basemsg) && consume) {
1440 sv_copypv(sv, basemsg);
1443 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1445 * Try and find the file and line for PL_op. This will usually be
1446 * PL_curcop, but it might be a cop that has been optimised away. We
1447 * can try to find such a cop by searching through the optree starting
1448 * from the sibling of PL_curcop.
1451 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1456 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1457 OutCopFILE(cop), (IV)CopLINE(cop));
1458 /* Seems that GvIO() can be untrustworthy during global destruction. */
1459 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1460 && IoLINES(GvIOp(PL_last_in_gv)))
1462 const bool line_mode = (RsSIMPLE(PL_rs) &&
1463 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1464 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1465 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1466 line_mode ? "line" : "chunk",
1467 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1469 if (PL_phase == PERL_PHASE_DESTRUCT)
1470 sv_catpvs(sv, " during global destruction");
1471 sv_catpvs(sv, ".\n");
1477 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1479 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1480 argument list. These are used to generate a string message. If the
1481 message does not end with a newline, then it will be extended with
1482 some indication of the current location in the code, as described for
1485 Normally, the resulting message is returned in a new mortal SV.
1486 During global destruction a single SV may be shared between uses of
1493 Perl_vmess(pTHX_ const char *pat, va_list *args)
1496 SV * const sv = mess_alloc();
1498 PERL_ARGS_ASSERT_VMESS;
1500 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1501 return mess_sv(sv, 1);
1505 Perl_write_to_stderr(pTHX_ SV* msv)
1511 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1513 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1514 && (io = GvIO(PL_stderrgv))
1515 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1516 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1517 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1520 /* SFIO can really mess with your errno */
1523 PerlIO * const serr = Perl_error_log;
1525 do_print(msv, serr);
1526 (void)PerlIO_flush(serr);
1534 =head1 Warning and Dieing
1537 /* Common code used in dieing and warning */
1540 S_with_queued_errors(pTHX_ SV *ex)
1542 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1543 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1544 sv_catsv(PL_errors, ex);
1545 ex = sv_mortalcopy(PL_errors);
1546 SvCUR_set(PL_errors, 0);
1552 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1558 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1559 /* sv_2cv might call Perl_croak() or Perl_warner() */
1560 SV * const oldhook = *hook;
1568 cv = sv_2cv(oldhook, &stash, &gv, 0);
1570 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1580 exarg = newSVsv(ex);
1581 SvREADONLY_on(exarg);
1584 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1588 call_sv(MUTABLE_SV(cv), G_DISCARD);
1597 =for apidoc Am|OP *|die_sv|SV *baseex
1599 Behaves the same as L</croak_sv>, except for the return type.
1600 It should be used only where the C<OP *> return type is required.
1601 The function never actually returns.
1607 Perl_die_sv(pTHX_ SV *baseex)
1609 PERL_ARGS_ASSERT_DIE_SV;
1616 =for apidoc Am|OP *|die|const char *pat|...
1618 Behaves the same as L</croak>, except for the return type.
1619 It should be used only where the C<OP *> return type is required.
1620 The function never actually returns.
1625 #if defined(PERL_IMPLICIT_CONTEXT)
1627 Perl_die_nocontext(const char* pat, ...)
1631 va_start(args, pat);
1637 #endif /* PERL_IMPLICIT_CONTEXT */
1640 Perl_die(pTHX_ const char* pat, ...)
1643 va_start(args, pat);
1651 =for apidoc Am|void|croak_sv|SV *baseex
1653 This is an XS interface to Perl's C<die> function.
1655 C<baseex> is the error message or object. If it is a reference, it
1656 will be used as-is. Otherwise it is used as a string, and if it does
1657 not end with a newline then it will be extended with some indication of
1658 the current location in the code, as described for L</mess_sv>.
1660 The error message or object will be used as an exception, by default
1661 returning control to the nearest enclosing C<eval>, but subject to
1662 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1663 function never returns normally.
1665 To die with a simple string message, the L</croak> function may be
1672 Perl_croak_sv(pTHX_ SV *baseex)
1674 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1675 PERL_ARGS_ASSERT_CROAK_SV;
1676 invoke_exception_hook(ex, FALSE);
1681 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1683 This is an XS interface to Perl's C<die> function.
1685 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1686 argument list. These are used to generate a string message. If the
1687 message does not end with a newline, then it will be extended with
1688 some indication of the current location in the code, as described for
1691 The error message will be used as an exception, by default
1692 returning control to the nearest enclosing C<eval>, but subject to
1693 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1694 function never returns normally.
1696 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1697 (C<$@>) will be used as an error message or object instead of building an
1698 error message from arguments. If you want to throw a non-string object,
1699 or build an error message in an SV yourself, it is preferable to use
1700 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1706 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1708 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1709 invoke_exception_hook(ex, FALSE);
1714 =for apidoc Am|void|croak|const char *pat|...
1716 This is an XS interface to Perl's C<die> function.
1718 Take a sprintf-style format pattern and argument list. These are used to
1719 generate a string message. If the message does not end with a newline,
1720 then it will be extended with some indication of the current location
1721 in the code, as described for L</mess_sv>.
1723 The error message will be used as an exception, by default
1724 returning control to the nearest enclosing C<eval>, but subject to
1725 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1726 function never returns normally.
1728 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1729 (C<$@>) will be used as an error message or object instead of building an
1730 error message from arguments. If you want to throw a non-string object,
1731 or build an error message in an SV yourself, it is preferable to use
1732 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1737 #if defined(PERL_IMPLICIT_CONTEXT)
1739 Perl_croak_nocontext(const char *pat, ...)
1743 va_start(args, pat);
1748 #endif /* PERL_IMPLICIT_CONTEXT */
1751 Perl_croak(pTHX_ const char *pat, ...)
1754 va_start(args, pat);
1761 =for apidoc Am|void|croak_no_modify
1763 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1764 terser object code than using C<Perl_croak>. Less code used on exception code
1765 paths reduces CPU cache pressure.
1771 Perl_croak_no_modify(pTHX)
1773 Perl_croak(aTHX_ "%s", PL_no_modify);
1777 =for apidoc Am|void|warn_sv|SV *baseex
1779 This is an XS interface to Perl's C<warn> function.
1781 C<baseex> is the error message or object. If it is a reference, it
1782 will be used as-is. Otherwise it is used as a string, and if it does
1783 not end with a newline then it will be extended with some indication of
1784 the current location in the code, as described for L</mess_sv>.
1786 The error message or object will by default be written to standard error,
1787 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1789 To warn with a simple string message, the L</warn> function may be
1796 Perl_warn_sv(pTHX_ SV *baseex)
1798 SV *ex = mess_sv(baseex, 0);
1799 PERL_ARGS_ASSERT_WARN_SV;
1800 if (!invoke_exception_hook(ex, TRUE))
1801 write_to_stderr(ex);
1805 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1807 This is an XS interface to Perl's C<warn> function.
1809 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1810 argument list. These are used to generate a string message. If the
1811 message does not end with a newline, then it will be extended with
1812 some indication of the current location in the code, as described for
1815 The error message or object will by default be written to standard error,
1816 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1818 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1824 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1826 SV *ex = vmess(pat, args);
1827 PERL_ARGS_ASSERT_VWARN;
1828 if (!invoke_exception_hook(ex, TRUE))
1829 write_to_stderr(ex);
1833 =for apidoc Am|void|warn|const char *pat|...
1835 This is an XS interface to Perl's C<warn> function.
1837 Take a sprintf-style format pattern and argument list. These are used to
1838 generate a string message. If the message does not end with a newline,
1839 then it will be extended with some indication of the current location
1840 in the code, as described for L</mess_sv>.
1842 The error message or object will by default be written to standard error,
1843 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1845 Unlike with L</croak>, C<pat> is not permitted to be null.
1850 #if defined(PERL_IMPLICIT_CONTEXT)
1852 Perl_warn_nocontext(const char *pat, ...)
1856 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1857 va_start(args, pat);
1861 #endif /* PERL_IMPLICIT_CONTEXT */
1864 Perl_warn(pTHX_ const char *pat, ...)
1867 PERL_ARGS_ASSERT_WARN;
1868 va_start(args, pat);
1873 #if defined(PERL_IMPLICIT_CONTEXT)
1875 Perl_warner_nocontext(U32 err, const char *pat, ...)
1879 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1880 va_start(args, pat);
1881 vwarner(err, pat, &args);
1884 #endif /* PERL_IMPLICIT_CONTEXT */
1887 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1889 PERL_ARGS_ASSERT_CK_WARNER_D;
1891 if (Perl_ckwarn_d(aTHX_ err)) {
1893 va_start(args, pat);
1894 vwarner(err, pat, &args);
1900 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1902 PERL_ARGS_ASSERT_CK_WARNER;
1904 if (Perl_ckwarn(aTHX_ err)) {
1906 va_start(args, pat);
1907 vwarner(err, pat, &args);
1913 Perl_warner(pTHX_ U32 err, const char* pat,...)
1916 PERL_ARGS_ASSERT_WARNER;
1917 va_start(args, pat);
1918 vwarner(err, pat, &args);
1923 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1926 PERL_ARGS_ASSERT_VWARNER;
1927 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1928 SV * const msv = vmess(pat, args);
1930 invoke_exception_hook(msv, FALSE);
1934 Perl_vwarn(aTHX_ pat, args);
1938 /* implements the ckWARN? macros */
1941 Perl_ckwarn(pTHX_ U32 w)
1944 /* If lexical warnings have not been set, use $^W. */
1946 return PL_dowarn & G_WARN_ON;
1948 return ckwarn_common(w);
1951 /* implements the ckWARN?_d macro */
1954 Perl_ckwarn_d(pTHX_ U32 w)
1957 /* If lexical warnings have not been set then default classes warn. */
1961 return ckwarn_common(w);
1965 S_ckwarn_common(pTHX_ U32 w)
1967 if (PL_curcop->cop_warnings == pWARN_ALL)
1970 if (PL_curcop->cop_warnings == pWARN_NONE)
1973 /* Check the assumption that at least the first slot is non-zero. */
1974 assert(unpackWARN1(w));
1976 /* Check the assumption that it is valid to stop as soon as a zero slot is
1978 if (!unpackWARN2(w)) {
1979 assert(!unpackWARN3(w));
1980 assert(!unpackWARN4(w));
1981 } else if (!unpackWARN3(w)) {
1982 assert(!unpackWARN4(w));
1985 /* Right, dealt with all the special cases, which are implemented as non-
1986 pointers, so there is a pointer to a real warnings mask. */
1988 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1990 } while (w >>= WARNshift);
1995 /* Set buffer=NULL to get a new one. */
1997 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1999 const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
2000 PERL_UNUSED_CONTEXT;
2001 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
2004 (specialWARN(buffer) ?
2005 PerlMemShared_malloc(len_wanted) :
2006 PerlMemShared_realloc(buffer, len_wanted));
2008 Copy(bits, (buffer + 1), size, char);
2012 /* since we've already done strlen() for both nam and val
2013 * we can use that info to make things faster than
2014 * sprintf(s, "%s=%s", nam, val)
2016 #define my_setenv_format(s, nam, nlen, val, vlen) \
2017 Copy(nam, s, nlen, char); \
2019 Copy(val, s+(nlen+1), vlen, char); \
2020 *(s+(nlen+1+vlen)) = '\0'
2022 #ifdef USE_ENVIRON_ARRAY
2023 /* VMS' my_setenv() is in vms.c */
2024 #if !defined(WIN32) && !defined(NETWARE)
2026 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2030 /* only parent thread can modify process environment */
2031 if (PL_curinterp == aTHX)
2034 #ifndef PERL_USE_SAFE_PUTENV
2035 if (!PL_use_safe_putenv) {
2036 /* most putenv()s leak, so we manipulate environ directly */
2038 register const I32 len = strlen(nam);
2041 /* where does it go? */
2042 for (i = 0; environ[i]; i++) {
2043 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
2047 if (environ == PL_origenviron) { /* need we copy environment? */
2053 while (environ[max])
2055 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2056 for (j=0; j<max; j++) { /* copy environment */
2057 const int len = strlen(environ[j]);
2058 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2059 Copy(environ[j], tmpenv[j], len+1, char);
2062 environ = tmpenv; /* tell exec where it is now */
2065 safesysfree(environ[i]);
2066 while (environ[i]) {
2067 environ[i] = environ[i+1];
2072 if (!environ[i]) { /* does not exist yet */
2073 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2074 environ[i+1] = NULL; /* make sure it's null terminated */
2077 safesysfree(environ[i]);
2081 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2082 /* all that work just for this */
2083 my_setenv_format(environ[i], nam, nlen, val, vlen);
2086 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
2087 # if defined(HAS_UNSETENV)
2089 (void)unsetenv(nam);
2091 (void)setenv(nam, val, 1);
2093 # else /* ! HAS_UNSETENV */
2094 (void)setenv(nam, val, 1);
2095 # endif /* HAS_UNSETENV */
2097 # if defined(HAS_UNSETENV)
2099 (void)unsetenv(nam);
2101 const int nlen = strlen(nam);
2102 const int vlen = strlen(val);
2103 char * const new_env =
2104 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2105 my_setenv_format(new_env, nam, nlen, val, vlen);
2106 (void)putenv(new_env);
2108 # else /* ! HAS_UNSETENV */
2110 const int nlen = strlen(nam);
2116 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2117 /* all that work just for this */
2118 my_setenv_format(new_env, nam, nlen, val, vlen);
2119 (void)putenv(new_env);
2120 # endif /* HAS_UNSETENV */
2121 # endif /* __CYGWIN__ */
2122 #ifndef PERL_USE_SAFE_PUTENV
2128 #else /* WIN32 || NETWARE */
2131 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2134 register char *envstr;
2135 const int nlen = strlen(nam);
2142 Newx(envstr, nlen+vlen+2, char);
2143 my_setenv_format(envstr, nam, nlen, val, vlen);
2144 (void)PerlEnv_putenv(envstr);
2148 #endif /* WIN32 || NETWARE */
2150 #endif /* !VMS && !EPOC*/
2152 #ifdef UNLINK_ALL_VERSIONS
2154 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2158 PERL_ARGS_ASSERT_UNLNK;
2160 while (PerlLIO_unlink(f) >= 0)
2162 return retries ? 0 : -1;
2166 /* this is a drop-in replacement for bcopy() */
2167 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2169 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2171 char * const retval = to;
2173 PERL_ARGS_ASSERT_MY_BCOPY;
2175 if (from - to >= 0) {
2183 *(--to) = *(--from);
2189 /* this is a drop-in replacement for memset() */
2192 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2194 char * const retval = loc;
2196 PERL_ARGS_ASSERT_MY_MEMSET;
2204 /* this is a drop-in replacement for bzero() */
2205 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2207 Perl_my_bzero(register char *loc, register I32 len)
2209 char * const retval = loc;
2211 PERL_ARGS_ASSERT_MY_BZERO;
2219 /* this is a drop-in replacement for memcmp() */
2220 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2222 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2224 register const U8 *a = (const U8 *)s1;
2225 register const U8 *b = (const U8 *)s2;
2228 PERL_ARGS_ASSERT_MY_MEMCMP;
2231 if ((tmp = *a++ - *b++))
2236 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2239 /* This vsprintf replacement should generally never get used, since
2240 vsprintf was available in both System V and BSD 2.11. (There may
2241 be some cross-compilation or embedded set-ups where it is needed,
2244 If you encounter a problem in this function, it's probably a symptom
2245 that Configure failed to detect your system's vprintf() function.
2246 See the section on "item vsprintf" in the INSTALL file.
2248 This version may compile on systems with BSD-ish <stdio.h>,
2249 but probably won't on others.
2252 #ifdef USE_CHAR_VSPRINTF
2257 vsprintf(char *dest, const char *pat, void *args)
2261 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2262 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2263 FILE_cnt(&fakebuf) = 32767;
2265 /* These probably won't compile -- If you really need
2266 this, you'll have to figure out some other method. */
2267 fakebuf._ptr = dest;
2268 fakebuf._cnt = 32767;
2273 fakebuf._flag = _IOWRT|_IOSTRG;
2274 _doprnt(pat, args, &fakebuf); /* what a kludge */
2275 #if defined(STDIO_PTR_LVALUE)
2276 *(FILE_ptr(&fakebuf)++) = '\0';
2278 /* PerlIO has probably #defined away fputc, but we want it here. */
2280 # undef fputc /* XXX Should really restore it later */
2282 (void)fputc('\0', &fakebuf);
2284 #ifdef USE_CHAR_VSPRINTF
2287 return 0; /* perl doesn't use return value */
2291 #endif /* HAS_VPRINTF */
2294 #if BYTEORDER != 0x4321
2296 Perl_my_swap(pTHX_ short s)
2298 #if (BYTEORDER & 1) == 0
2301 result = ((s & 255) << 8) + ((s >> 8) & 255);
2309 Perl_my_htonl(pTHX_ long l)
2313 char c[sizeof(long)];
2316 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2317 #if BYTEORDER == 0x12345678
2320 u.c[0] = (l >> 24) & 255;
2321 u.c[1] = (l >> 16) & 255;
2322 u.c[2] = (l >> 8) & 255;
2326 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2327 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2332 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2333 u.c[o & 0xf] = (l >> s) & 255;
2341 Perl_my_ntohl(pTHX_ long l)
2345 char c[sizeof(long)];
2348 #if BYTEORDER == 0x1234
2349 u.c[0] = (l >> 24) & 255;
2350 u.c[1] = (l >> 16) & 255;
2351 u.c[2] = (l >> 8) & 255;
2355 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2356 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2363 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2364 l |= (u.c[o & 0xf] & 255) << s;
2371 #endif /* BYTEORDER != 0x4321 */
2375 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2376 * If these functions are defined,
2377 * the BYTEORDER is neither 0x1234 nor 0x4321.
2378 * However, this is not assumed.
2382 #define HTOLE(name,type) \
2384 name (register type n) \
2388 char c[sizeof(type)]; \
2391 register U32 s = 0; \
2392 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2393 u.c[i] = (n >> s) & 0xFF; \
2398 #define LETOH(name,type) \
2400 name (register type n) \
2404 char c[sizeof(type)]; \
2407 register U32 s = 0; \
2410 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2411 n |= ((type)(u.c[i] & 0xFF)) << s; \
2417 * Big-endian byte order functions.
2420 #define HTOBE(name,type) \
2422 name (register type n) \
2426 char c[sizeof(type)]; \
2429 register U32 s = 8*(sizeof(u.c)-1); \
2430 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2431 u.c[i] = (n >> s) & 0xFF; \
2436 #define BETOH(name,type) \
2438 name (register type n) \
2442 char c[sizeof(type)]; \
2445 register U32 s = 8*(sizeof(u.c)-1); \
2448 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2449 n |= ((type)(u.c[i] & 0xFF)) << s; \
2455 * If we just can't do it...
2458 #define NOT_AVAIL(name,type) \
2460 name (register type n) \
2462 Perl_croak_nocontext(#name "() not available"); \
2463 return n; /* not reached */ \
2467 #if defined(HAS_HTOVS) && !defined(htovs)
2470 #if defined(HAS_HTOVL) && !defined(htovl)
2473 #if defined(HAS_VTOHS) && !defined(vtohs)
2476 #if defined(HAS_VTOHL) && !defined(vtohl)
2480 #ifdef PERL_NEED_MY_HTOLE16
2482 HTOLE(Perl_my_htole16,U16)
2484 NOT_AVAIL(Perl_my_htole16,U16)
2487 #ifdef PERL_NEED_MY_LETOH16
2489 LETOH(Perl_my_letoh16,U16)
2491 NOT_AVAIL(Perl_my_letoh16,U16)
2494 #ifdef PERL_NEED_MY_HTOBE16
2496 HTOBE(Perl_my_htobe16,U16)
2498 NOT_AVAIL(Perl_my_htobe16,U16)
2501 #ifdef PERL_NEED_MY_BETOH16
2503 BETOH(Perl_my_betoh16,U16)
2505 NOT_AVAIL(Perl_my_betoh16,U16)
2509 #ifdef PERL_NEED_MY_HTOLE32
2511 HTOLE(Perl_my_htole32,U32)
2513 NOT_AVAIL(Perl_my_htole32,U32)
2516 #ifdef PERL_NEED_MY_LETOH32
2518 LETOH(Perl_my_letoh32,U32)
2520 NOT_AVAIL(Perl_my_letoh32,U32)
2523 #ifdef PERL_NEED_MY_HTOBE32
2525 HTOBE(Perl_my_htobe32,U32)
2527 NOT_AVAIL(Perl_my_htobe32,U32)
2530 #ifdef PERL_NEED_MY_BETOH32
2532 BETOH(Perl_my_betoh32,U32)
2534 NOT_AVAIL(Perl_my_betoh32,U32)
2538 #ifdef PERL_NEED_MY_HTOLE64
2540 HTOLE(Perl_my_htole64,U64)
2542 NOT_AVAIL(Perl_my_htole64,U64)
2545 #ifdef PERL_NEED_MY_LETOH64
2547 LETOH(Perl_my_letoh64,U64)
2549 NOT_AVAIL(Perl_my_letoh64,U64)
2552 #ifdef PERL_NEED_MY_HTOBE64
2554 HTOBE(Perl_my_htobe64,U64)
2556 NOT_AVAIL(Perl_my_htobe64,U64)
2559 #ifdef PERL_NEED_MY_BETOH64
2561 BETOH(Perl_my_betoh64,U64)
2563 NOT_AVAIL(Perl_my_betoh64,U64)
2567 #ifdef PERL_NEED_MY_HTOLES
2568 HTOLE(Perl_my_htoles,short)
2570 #ifdef PERL_NEED_MY_LETOHS
2571 LETOH(Perl_my_letohs,short)
2573 #ifdef PERL_NEED_MY_HTOBES
2574 HTOBE(Perl_my_htobes,short)
2576 #ifdef PERL_NEED_MY_BETOHS
2577 BETOH(Perl_my_betohs,short)
2580 #ifdef PERL_NEED_MY_HTOLEI
2581 HTOLE(Perl_my_htolei,int)
2583 #ifdef PERL_NEED_MY_LETOHI
2584 LETOH(Perl_my_letohi,int)
2586 #ifdef PERL_NEED_MY_HTOBEI
2587 HTOBE(Perl_my_htobei,int)
2589 #ifdef PERL_NEED_MY_BETOHI
2590 BETOH(Perl_my_betohi,int)
2593 #ifdef PERL_NEED_MY_HTOLEL
2594 HTOLE(Perl_my_htolel,long)
2596 #ifdef PERL_NEED_MY_LETOHL
2597 LETOH(Perl_my_letohl,long)
2599 #ifdef PERL_NEED_MY_HTOBEL
2600 HTOBE(Perl_my_htobel,long)
2602 #ifdef PERL_NEED_MY_BETOHL
2603 BETOH(Perl_my_betohl,long)
2607 Perl_my_swabn(void *ptr, int n)
2609 register char *s = (char *)ptr;
2610 register char *e = s + (n-1);
2613 PERL_ARGS_ASSERT_MY_SWABN;
2615 for (n /= 2; n > 0; s++, e--, n--) {
2623 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2625 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2628 register I32 This, that;
2634 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2636 PERL_FLUSHALL_FOR_CHILD;
2637 This = (*mode == 'w');
2641 taint_proper("Insecure %s%s", "EXEC");
2643 if (PerlProc_pipe(p) < 0)
2645 /* Try for another pipe pair for error return */
2646 if (PerlProc_pipe(pp) >= 0)
2648 while ((pid = PerlProc_fork()) < 0) {
2649 if (errno != EAGAIN) {
2650 PerlLIO_close(p[This]);
2651 PerlLIO_close(p[that]);
2653 PerlLIO_close(pp[0]);
2654 PerlLIO_close(pp[1]);
2658 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2667 /* Close parent's end of error status pipe (if any) */
2669 PerlLIO_close(pp[0]);
2670 #if defined(HAS_FCNTL) && defined(F_SETFD)
2671 /* Close error pipe automatically if exec works */
2672 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2675 /* Now dup our end of _the_ pipe to right position */
2676 if (p[THIS] != (*mode == 'r')) {
2677 PerlLIO_dup2(p[THIS], *mode == 'r');
2678 PerlLIO_close(p[THIS]);
2679 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2680 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2683 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2684 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2685 /* No automatic close - do it by hand */
2692 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2698 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2704 do_execfree(); /* free any memory malloced by child on fork */
2706 PerlLIO_close(pp[1]);
2707 /* Keep the lower of the two fd numbers */
2708 if (p[that] < p[This]) {
2709 PerlLIO_dup2(p[This], p[that]);
2710 PerlLIO_close(p[This]);
2714 PerlLIO_close(p[that]); /* close child's end of pipe */
2716 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2717 SvUPGRADE(sv,SVt_IV);
2719 PL_forkprocess = pid;
2720 /* If we managed to get status pipe check for exec fail */
2721 if (did_pipes && pid > 0) {
2726 while (n < sizeof(int)) {
2727 n1 = PerlLIO_read(pp[0],
2728 (void*)(((char*)&errkid)+n),
2734 PerlLIO_close(pp[0]);
2736 if (n) { /* Error */
2738 PerlLIO_close(p[This]);
2739 if (n != sizeof(int))
2740 Perl_croak(aTHX_ "panic: kid popen errno read");
2742 pid2 = wait4pid(pid, &status, 0);
2743 } while (pid2 == -1 && errno == EINTR);
2744 errno = errkid; /* Propagate errno from kid */
2749 PerlLIO_close(pp[0]);
2750 return PerlIO_fdopen(p[This], mode);
2752 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2753 return my_syspopen4(aTHX_ NULL, mode, n, args);
2755 Perl_croak(aTHX_ "List form of piped open not implemented");
2756 return (PerlIO *) NULL;
2761 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2762 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
2764 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2768 register I32 This, that;
2771 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2775 PERL_ARGS_ASSERT_MY_POPEN;
2777 PERL_FLUSHALL_FOR_CHILD;
2780 return my_syspopen(aTHX_ cmd,mode);
2783 This = (*mode == 'w');
2785 if (doexec && PL_tainting) {
2787 taint_proper("Insecure %s%s", "EXEC");
2789 if (PerlProc_pipe(p) < 0)
2791 if (doexec && PerlProc_pipe(pp) >= 0)
2793 while ((pid = PerlProc_fork()) < 0) {
2794 if (errno != EAGAIN) {
2795 PerlLIO_close(p[This]);
2796 PerlLIO_close(p[that]);
2798 PerlLIO_close(pp[0]);
2799 PerlLIO_close(pp[1]);
2802 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2805 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2815 PerlLIO_close(pp[0]);
2816 #if defined(HAS_FCNTL) && defined(F_SETFD)
2817 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2820 if (p[THIS] != (*mode == 'r')) {
2821 PerlLIO_dup2(p[THIS], *mode == 'r');
2822 PerlLIO_close(p[THIS]);
2823 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2824 PerlLIO_close(p[THAT]);
2827 PerlLIO_close(p[THAT]);
2830 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2837 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2842 /* may or may not use the shell */
2843 do_exec3(cmd, pp[1], did_pipes);
2846 #endif /* defined OS2 */
2848 #ifdef PERLIO_USING_CRLF
2849 /* Since we circumvent IO layers when we manipulate low-level
2850 filedescriptors directly, need to manually switch to the
2851 default, binary, low-level mode; see PerlIOBuf_open(). */
2852 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2854 #ifdef THREADS_HAVE_PIDS
2855 PL_ppid = (IV)getppid();
2858 #ifdef PERL_USES_PL_PIDSTATUS
2859 hv_clear(PL_pidstatus); /* we have no children */
2865 do_execfree(); /* free any memory malloced by child on vfork */
2867 PerlLIO_close(pp[1]);
2868 if (p[that] < p[This]) {
2869 PerlLIO_dup2(p[This], p[that]);
2870 PerlLIO_close(p[This]);
2874 PerlLIO_close(p[that]);
2876 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2877 SvUPGRADE(sv,SVt_IV);
2879 PL_forkprocess = pid;
2880 if (did_pipes && pid > 0) {
2885 while (n < sizeof(int)) {
2886 n1 = PerlLIO_read(pp[0],
2887 (void*)(((char*)&errkid)+n),
2893 PerlLIO_close(pp[0]);
2895 if (n) { /* Error */
2897 PerlLIO_close(p[This]);
2898 if (n != sizeof(int))
2899 Perl_croak(aTHX_ "panic: kid popen errno read");
2901 pid2 = wait4pid(pid, &status, 0);
2902 } while (pid2 == -1 && errno == EINTR);
2903 errno = errkid; /* Propagate errno from kid */
2908 PerlLIO_close(pp[0]);
2909 return PerlIO_fdopen(p[This], mode);
2912 #if defined(atarist) || defined(EPOC)
2915 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2917 PERL_ARGS_ASSERT_MY_POPEN;
2918 PERL_FLUSHALL_FOR_CHILD;
2919 /* Call system's popen() to get a FILE *, then import it.
2920 used 0 for 2nd parameter to PerlIO_importFILE;
2923 return PerlIO_importFILE(popen(cmd, mode), 0);
2927 FILE *djgpp_popen();
2929 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2931 PERL_FLUSHALL_FOR_CHILD;
2932 /* Call system's popen() to get a FILE *, then import it.
2933 used 0 for 2nd parameter to PerlIO_importFILE;
2936 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2939 #if defined(__LIBCATAMOUNT__)
2941 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2949 #endif /* !DOSISH */
2951 /* this is called in parent before the fork() */
2953 Perl_atfork_lock(void)
2956 #if defined(USE_ITHREADS)
2957 /* locks must be held in locking order (if any) */
2959 MUTEX_LOCK(&PL_malloc_mutex);
2965 /* this is called in both parent and child after the fork() */
2967 Perl_atfork_unlock(void)
2970 #if defined(USE_ITHREADS)
2971 /* locks must be released in same order as in atfork_lock() */
2973 MUTEX_UNLOCK(&PL_malloc_mutex);
2982 #if defined(HAS_FORK)
2984 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2989 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2990 * handlers elsewhere in the code */
2995 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2996 Perl_croak_nocontext("fork() not available");
2998 #endif /* HAS_FORK */
3003 Perl_dump_fds(pTHX_ const char *const s)
3008 PERL_ARGS_ASSERT_DUMP_FDS;
3010 PerlIO_printf(Perl_debug_log,"%s", s);
3011 for (fd = 0; fd < 32; fd++) {
3012 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
3013 PerlIO_printf(Perl_debug_log," %d",fd);
3015 PerlIO_printf(Perl_debug_log,"\n");
3018 #endif /* DUMP_FDS */
3022 dup2(int oldfd, int newfd)
3024 #if defined(HAS_FCNTL) && defined(F_DUPFD)
3027 PerlLIO_close(newfd);
3028 return fcntl(oldfd, F_DUPFD, newfd);
3030 #define DUP2_MAX_FDS 256
3031 int fdtmp[DUP2_MAX_FDS];
3037 PerlLIO_close(newfd);
3038 /* good enough for low fd's... */
3039 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
3040 if (fdx >= DUP2_MAX_FDS) {
3048 PerlLIO_close(fdtmp[--fdx]);
3055 #ifdef HAS_SIGACTION
3058 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3061 struct sigaction act, oact;
3064 /* only "parent" interpreter can diddle signals */
3065 if (PL_curinterp != aTHX)
3066 return (Sighandler_t) SIG_ERR;
3069 act.sa_handler = (void(*)(int))handler;
3070 sigemptyset(&act.sa_mask);
3073 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3074 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
3076 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3077 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3078 act.sa_flags |= SA_NOCLDWAIT;
3080 if (sigaction(signo, &act, &oact) == -1)
3081 return (Sighandler_t) SIG_ERR;
3083 return (Sighandler_t) oact.sa_handler;
3087 Perl_rsignal_state(pTHX_ int signo)
3089 struct sigaction oact;
3090 PERL_UNUSED_CONTEXT;
3092 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
3093 return (Sighandler_t) SIG_ERR;
3095 return (Sighandler_t) oact.sa_handler;
3099 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3102 struct sigaction act;
3104 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
3107 /* only "parent" interpreter can diddle signals */
3108 if (PL_curinterp != aTHX)
3112 act.sa_handler = (void(*)(int))handler;
3113 sigemptyset(&act.sa_mask);
3116 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3117 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
3119 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3120 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3121 act.sa_flags |= SA_NOCLDWAIT;
3123 return sigaction(signo, &act, save);
3127 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3131 /* only "parent" interpreter can diddle signals */
3132 if (PL_curinterp != aTHX)
3136 return sigaction(signo, save, (struct sigaction *)NULL);
3139 #else /* !HAS_SIGACTION */
3142 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3144 #if defined(USE_ITHREADS) && !defined(WIN32)
3145 /* only "parent" interpreter can diddle signals */
3146 if (PL_curinterp != aTHX)
3147 return (Sighandler_t) SIG_ERR;
3150 return PerlProc_signal(signo, handler);
3161 Perl_rsignal_state(pTHX_ int signo)
3164 Sighandler_t oldsig;
3166 #if defined(USE_ITHREADS) && !defined(WIN32)
3167 /* only "parent" interpreter can diddle signals */
3168 if (PL_curinterp != aTHX)
3169 return (Sighandler_t) SIG_ERR;
3173 oldsig = PerlProc_signal(signo, sig_trap);
3174 PerlProc_signal(signo, oldsig);
3176 PerlProc_kill(PerlProc_getpid(), signo);
3181 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3183 #if defined(USE_ITHREADS) && !defined(WIN32)
3184 /* only "parent" interpreter can diddle signals */
3185 if (PL_curinterp != aTHX)
3188 *save = PerlProc_signal(signo, handler);
3189 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3193 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3195 #if defined(USE_ITHREADS) && !defined(WIN32)
3196 /* only "parent" interpreter can diddle signals */
3197 if (PL_curinterp != aTHX)
3200 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3203 #endif /* !HAS_SIGACTION */
3204 #endif /* !PERL_MICRO */
3206 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3207 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
3209 Perl_my_pclose(pTHX_ PerlIO *ptr)
3212 Sigsave_t hstat, istat, qstat;
3219 const int fd = PerlIO_fileno(ptr);
3222 /* Find out whether the refcount is low enough for us to wait for the
3223 child proc without blocking. */
3224 const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
3226 const bool should_wait = 1;
3229 svp = av_fetch(PL_fdpid,fd,TRUE);
3230 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3232 *svp = &PL_sv_undef;
3234 if (pid == -1) { /* Opened by popen. */
3235 return my_syspclose(ptr);
3238 close_failed = (PerlIO_close(ptr) == EOF);
3241 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
3244 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3245 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3246 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3248 if (should_wait) do {
3249 pid2 = wait4pid(pid, &status, 0);
3250 } while (pid2 == -1 && errno == EINTR);
3252 rsignal_restore(SIGHUP, &hstat);
3253 rsignal_restore(SIGINT, &istat);
3254 rsignal_restore(SIGQUIT, &qstat);
3262 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3267 #if defined(__LIBCATAMOUNT__)
3269 Perl_my_pclose(pTHX_ PerlIO *ptr)
3274 #endif /* !DOSISH */
3276 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3278 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3282 PERL_ARGS_ASSERT_WAIT4PID;
3285 #ifdef PERL_USES_PL_PIDSTATUS
3288 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3289 pid, rather than a string form. */
3290 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3291 if (svp && *svp != &PL_sv_undef) {
3292 *statusp = SvIVX(*svp);
3293 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3301 hv_iterinit(PL_pidstatus);
3302 if ((entry = hv_iternext(PL_pidstatus))) {
3303 SV * const sv = hv_iterval(PL_pidstatus,entry);
3305 const char * const spid = hv_iterkey(entry,&len);
3307 assert (len == sizeof(Pid_t));
3308 memcpy((char *)&pid, spid, len);
3309 *statusp = SvIVX(sv);
3310 /* The hash iterator is currently on this entry, so simply
3311 calling hv_delete would trigger the lazy delete, which on
3312 aggregate does more work, beacuse next call to hv_iterinit()
3313 would spot the flag, and have to call the delete routine,
3314 while in the meantime any new entries can't re-use that
3316 hv_iterinit(PL_pidstatus);
3317 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3324 # ifdef HAS_WAITPID_RUNTIME
3325 if (!HAS_WAITPID_RUNTIME)
3328 result = PerlProc_waitpid(pid,statusp,flags);
3331 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3332 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3335 #ifdef PERL_USES_PL_PIDSTATUS
3336 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3341 Perl_croak(aTHX_ "Can't do waitpid with flags");
3343 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3344 pidgone(result,*statusp);
3350 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3353 if (result < 0 && errno == EINTR) {
3355 errno = EINTR; /* reset in case a signal handler changed $! */
3359 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3361 #ifdef PERL_USES_PL_PIDSTATUS
3363 S_pidgone(pTHX_ Pid_t pid, int status)
3367 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3368 SvUPGRADE(sv,SVt_IV);
3369 SvIV_set(sv, status);
3374 #if defined(atarist) || defined(OS2) || defined(EPOC)
3377 int /* Cannot prototype with I32
3379 my_syspclose(PerlIO *ptr)
3382 Perl_my_pclose(pTHX_ PerlIO *ptr)
3385 /* Needs work for PerlIO ! */
3386 FILE * const f = PerlIO_findFILE(ptr);
3387 const I32 result = pclose(f);
3388 PerlIO_releaseFILE(ptr,f);
3396 Perl_my_pclose(pTHX_ PerlIO *ptr)
3398 /* Needs work for PerlIO ! */
3399 FILE * const f = PerlIO_findFILE(ptr);
3400 I32 result = djgpp_pclose(f);
3401 result = (result << 8) & 0xff00;
3402 PerlIO_releaseFILE(ptr,f);
3407 #define PERL_REPEATCPY_LINEAR 4
3409 Perl_repeatcpy(register char *to, register const char *from, I32 len, register I32 count)
3411 PERL_ARGS_ASSERT_REPEATCPY;
3414 memset(to, *from, count);
3416 register char *p = to;
3417 I32 items, linear, half;
3419 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3420 for (items = 0; items < linear; ++items) {
3421 register const char *q = from;
3423 for (todo = len; todo > 0; todo--)
3428 while (items <= half) {
3429 I32 size = items * len;
3430 memcpy(p, to, size);
3436 memcpy(p, to, (count - items) * len);
3442 Perl_same_dirent(pTHX_ const char *a, const char *b)
3444 char *fa = strrchr(a,'/');
3445 char *fb = strrchr(b,'/');
3448 SV * const tmpsv = sv_newmortal();
3450 PERL_ARGS_ASSERT_SAME_DIRENT;
3463 sv_setpvs(tmpsv, ".");
3465 sv_setpvn(tmpsv, a, fa - a);
3466 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3469 sv_setpvs(tmpsv, ".");
3471 sv_setpvn(tmpsv, b, fb - b);
3472 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3474 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3475 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3477 #endif /* !HAS_RENAME */
3480 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3481 const char *const *const search_ext, I32 flags)
3484 const char *xfound = NULL;
3485 char *xfailed = NULL;
3486 char tmpbuf[MAXPATHLEN];
3491 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3492 # define SEARCH_EXTS ".bat", ".cmd", NULL
3493 # define MAX_EXT_LEN 4
3496 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3497 # define MAX_EXT_LEN 4
3500 # define SEARCH_EXTS ".pl", ".com", NULL
3501 # define MAX_EXT_LEN 4
3503 /* additional extensions to try in each dir if scriptname not found */
3505 static const char *const exts[] = { SEARCH_EXTS };
3506 const char *const *const ext = search_ext ? search_ext : exts;
3507 int extidx = 0, i = 0;
3508 const char *curext = NULL;
3510 PERL_UNUSED_ARG(search_ext);
3511 # define MAX_EXT_LEN 0
3514 PERL_ARGS_ASSERT_FIND_SCRIPT;
3517 * If dosearch is true and if scriptname does not contain path
3518 * delimiters, search the PATH for scriptname.
3520 * If SEARCH_EXTS is also defined, will look for each
3521 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3522 * while searching the PATH.
3524 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3525 * proceeds as follows:
3526 * If DOSISH or VMSISH:
3527 * + look for ./scriptname{,.foo,.bar}
3528 * + search the PATH for scriptname{,.foo,.bar}
3531 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3532 * this will not look in '.' if it's not in the PATH)
3537 # ifdef ALWAYS_DEFTYPES
3538 len = strlen(scriptname);
3539 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3540 int idx = 0, deftypes = 1;
3543 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3546 int idx = 0, deftypes = 1;
3549 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3551 /* The first time through, just add SEARCH_EXTS to whatever we
3552 * already have, so we can check for default file types. */
3554 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3560 if ((strlen(tmpbuf) + strlen(scriptname)
3561 + MAX_EXT_LEN) >= sizeof tmpbuf)
3562 continue; /* don't search dir with too-long name */
3563 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3567 if (strEQ(scriptname, "-"))
3569 if (dosearch) { /* Look in '.' first. */
3570 const char *cur = scriptname;
3572 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3574 if (strEQ(ext[i++],curext)) {
3575 extidx = -1; /* already has an ext */
3580 DEBUG_p(PerlIO_printf(Perl_debug_log,
3581 "Looking for %s\n",cur));
3582 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3583 && !S_ISDIR(PL_statbuf.st_mode)) {
3591 if (cur == scriptname) {
3592 len = strlen(scriptname);
3593 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3595 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3598 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3599 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3604 if (dosearch && !strchr(scriptname, '/')
3606 && !strchr(scriptname, '\\')
3608 && (s = PerlEnv_getenv("PATH")))
3612 bufend = s + strlen(s);
3613 while (s < bufend) {
3614 #if defined(atarist) || defined(DOSISH)
3619 && *s != ';'; len++, s++) {
3620 if (len < sizeof tmpbuf)
3623 if (len < sizeof tmpbuf)
3625 #else /* ! (atarist || DOSISH) */
3626 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3629 #endif /* ! (atarist || DOSISH) */
3632 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3633 continue; /* don't search dir with too-long name */
3635 # if defined(atarist) || defined(DOSISH)
3636 && tmpbuf[len - 1] != '/'
3637 && tmpbuf[len - 1] != '\\'
3640 tmpbuf[len++] = '/';
3641 if (len == 2 && tmpbuf[0] == '.')
3643 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3647 len = strlen(tmpbuf);
3648 if (extidx > 0) /* reset after previous loop */
3652 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3653 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3654 if (S_ISDIR(PL_statbuf.st_mode)) {
3658 } while ( retval < 0 /* not there */
3659 && extidx>=0 && ext[extidx] /* try an extension? */
3660 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3665 if (S_ISREG(PL_statbuf.st_mode)
3666 && cando(S_IRUSR,TRUE,&PL_statbuf)
3667 #if !defined(DOSISH)
3668 && cando(S_IXUSR,TRUE,&PL_statbuf)
3672 xfound = tmpbuf; /* bingo! */
3676 xfailed = savepv(tmpbuf);
3679 if (!xfound && !seen_dot && !xfailed &&
3680 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3681 || S_ISDIR(PL_statbuf.st_mode)))
3683 seen_dot = 1; /* Disable message. */
3685 if (flags & 1) { /* do or die? */
3686 Perl_croak(aTHX_ "Can't %s %s%s%s",
3687 (xfailed ? "execute" : "find"),
3688 (xfailed ? xfailed : scriptname),
3689 (xfailed ? "" : " on PATH"),
3690 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3695 scriptname = xfound;
3697 return (scriptname ? savepv(scriptname) : NULL);
3700 #ifndef PERL_GET_CONTEXT_DEFINED
3703 Perl_get_context(void)
3706 #if defined(USE_ITHREADS)
3707 # ifdef OLD_PTHREADS_API
3709 if (pthread_getspecific(PL_thr_key, &t))
3710 Perl_croak_nocontext("panic: pthread_getspecific");
3713 # ifdef I_MACH_CTHREADS
3714 return (void*)cthread_data(cthread_self());
3716 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3725 Perl_set_context(void *t)
3728 PERL_ARGS_ASSERT_SET_CONTEXT;
3729 #if defined(USE_ITHREADS)
3730 # ifdef I_MACH_CTHREADS
3731 cthread_set_data(cthread_self(), t);
3733 if (pthread_setspecific(PL_thr_key, t))
3734 Perl_croak_nocontext("panic: pthread_setspecific");
3741 #endif /* !PERL_GET_CONTEXT_DEFINED */
3743 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3752 Perl_get_op_names(pTHX)
3754 PERL_UNUSED_CONTEXT;
3755 return (char **)PL_op_name;
3759 Perl_get_op_descs(pTHX)
3761 PERL_UNUSED_CONTEXT;
3762 return (char **)PL_op_desc;
3766 Perl_get_no_modify(pTHX)
3768 PERL_UNUSED_CONTEXT;
3769 return PL_no_modify;
3773 Perl_get_opargs(pTHX)
3775 PERL_UNUSED_CONTEXT;
3776 return (U32 *)PL_opargs;
3780 Perl_get_ppaddr(pTHX)
3783 PERL_UNUSED_CONTEXT;
3784 return (PPADDR_t*)PL_ppaddr;
3787 #ifndef HAS_GETENV_LEN
3789 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3791 char * const env_trans = PerlEnv_getenv(env_elem);
3792 PERL_UNUSED_CONTEXT;
3793 PERL_ARGS_ASSERT_GETENV_LEN;
3795 *len = strlen(env_trans);
3802 Perl_get_vtbl(pTHX_ int vtbl_id)
3804 PERL_UNUSED_CONTEXT;
3806 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3807 ? NULL : PL_magic_vtables + vtbl_id;
3811 Perl_my_fflush_all(pTHX)
3813 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3814 return PerlIO_flush(NULL);
3816 # if defined(HAS__FWALK)
3817 extern int fflush(FILE *);
3818 /* undocumented, unprototyped, but very useful BSDism */
3819 extern void _fwalk(int (*)(FILE *));
3823 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3825 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3826 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3828 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3829 open_max = sysconf(_SC_OPEN_MAX);
3832 open_max = FOPEN_MAX;
3835 open_max = OPEN_MAX;
3846 for (i = 0; i < open_max; i++)
3847 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3848 STDIO_STREAM_ARRAY[i]._file < open_max &&
3849 STDIO_STREAM_ARRAY[i]._flag)
3850 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3854 SETERRNO(EBADF,RMS_IFI);
3861 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3863 if (ckWARN(WARN_IO)) {
3864 const char * const name
3865 = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3866 const char * const direction = have == '>' ? "out" : "in";
3869 Perl_warner(aTHX_ packWARN(WARN_IO),
3870 "Filehandle %s opened only for %sput",
3873 Perl_warner(aTHX_ packWARN(WARN_IO),
3874 "Filehandle opened only for %sput", direction);
3879 Perl_report_evil_fh(pTHX_ const GV *gv)
3881 const IO *io = gv ? GvIO(gv) : NULL;
3882 const PERL_BITFIELD16 op = PL_op->op_type;
3886 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3888 warn_type = WARN_CLOSED;
3892 warn_type = WARN_UNOPENED;
3895 if (ckWARN(warn_type)) {
3896 const char * const name
3897 = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3898 const char * const pars =
3899 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3900 const char * const func =
3902 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3903 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3905 const char * const type =
3907 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3908 ? "socket" : "filehandle");
3909 if (name && *name) {
3910 Perl_warner(aTHX_ packWARN(warn_type),
3911 "%s%s on %s %s %s", func, pars, vile, type, name);
3912 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3914 aTHX_ packWARN(warn_type),
3915 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3920 Perl_warner(aTHX_ packWARN(warn_type),
3921 "%s%s on %s %s", func, pars, vile, type);
3922 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3924 aTHX_ packWARN(warn_type),
3925 "\t(Are you trying to call %s%s on dirhandle?)\n",
3932 /* To workaround core dumps from the uninitialised tm_zone we get the
3933 * system to give us a reasonable struct to copy. This fix means that
3934 * strftime uses the tm_zone and tm_gmtoff values returned by
3935 * localtime(time()). That should give the desired result most of the
3936 * time. But probably not always!
3938 * This does not address tzname aspects of NETaa14816.
3943 # ifndef STRUCT_TM_HASZONE
3944 # define STRUCT_TM_HASZONE
3948 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3949 # ifndef HAS_TM_TM_ZONE
3950 # define HAS_TM_TM_ZONE
3955 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3957 #ifdef HAS_TM_TM_ZONE
3959 const struct tm* my_tm;
3960 PERL_ARGS_ASSERT_INIT_TM;
3962 my_tm = localtime(&now);
3964 Copy(my_tm, ptm, 1, struct tm);
3966 PERL_ARGS_ASSERT_INIT_TM;
3967 PERL_UNUSED_ARG(ptm);
3972 * mini_mktime - normalise struct tm values without the localtime()
3973 * semantics (and overhead) of mktime().
3976 Perl_mini_mktime(pTHX_ struct tm *ptm)
3980 int month, mday, year, jday;
3981 int odd_cent, odd_year;
3982 PERL_UNUSED_CONTEXT;
3984 PERL_ARGS_ASSERT_MINI_MKTIME;
3986 #define DAYS_PER_YEAR 365
3987 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3988 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3989 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3990 #define SECS_PER_HOUR (60*60)
3991 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3992 /* parentheses deliberately absent on these two, otherwise they don't work */
3993 #define MONTH_TO_DAYS 153/5
3994 #define DAYS_TO_MONTH 5/153
3995 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3996 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3997 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3998 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
4001 * Year/day algorithm notes:
4003 * With a suitable offset for numeric value of the month, one can find
4004 * an offset into the year by considering months to have 30.6 (153/5) days,
4005 * using integer arithmetic (i.e., with truncation). To avoid too much
4006 * messing about with leap days, we consider January and February to be
4007 * the 13th and 14th month of the previous year. After that transformation,
4008 * we need the month index we use to be high by 1 from 'normal human' usage,
4009 * so the month index values we use run from 4 through 15.
4011 * Given that, and the rules for the Gregorian calendar (leap years are those
4012 * divisible by 4 unless also divisible by 100, when they must be divisible
4013 * by 400 instead), we can simply calculate the number of days since some
4014 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
4015 * the days we derive from our month index, and adding in the day of the
4016 * month. The value used here is not adjusted for the actual origin which
4017 * it normally would use (1 January A.D. 1), since we're not exposing it.
4018 * We're only building the value so we can turn around and get the
4019 * normalised values for the year, month, day-of-month, and day-of-year.
4021 * For going backward, we need to bias the value we're using so that we find
4022 * the right year value. (Basically, we don't want the contribution of
4023 * March 1st to the number to apply while deriving the year). Having done
4024 * that, we 'count up' the contribution to the year number by accounting for
4025 * full quadracenturies (400-year periods) with their extra leap days, plus
4026 * the contribution from full centuries (to avoid counting in the lost leap
4027 * days), plus the contribution from full quad-years (to count in the normal
4028 * leap days), plus the leftover contribution from any non-leap years.
4029 * At this point, if we were working with an actual leap day, we'll have 0
4030 * days left over. This is also true for March 1st, however. So, we have
4031 * to special-case that result, and (earlier) keep track of the 'odd'
4032 * century and year contributions. If we got 4 extra centuries in a qcent,
4033 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
4034 * Otherwise, we add back in the earlier bias we removed (the 123 from
4035 * figuring in March 1st), find the month index (integer division by 30.6),
4036 * and the remainder is the day-of-month. We then have to convert back to
4037 * 'real' months (including fixing January and February from being 14/15 in
4038 * the previous year to being in the proper year). After that, to get
4039 * tm_yday, we work with the normalised year and get a new yearday value for
4040 * January 1st, which we subtract from the yearday value we had earlier,
4041 * representing the date we've re-built. This is done from January 1
4042 * because tm_yday is 0-origin.
4044 * Since POSIX time routines are only guaranteed to work for times since the
4045 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
4046 * applies Gregorian calendar rules even to dates before the 16th century
4047 * doesn't bother me. Besides, you'd need cultural context for a given
4048 * date to know whether it was Julian or Gregorian calendar, and that's
4049 * outside the scope for this routine. Since we convert back based on the
4050 * same rules we used to build the yearday, you'll only get strange results
4051 * for input which needed normalising, or for the 'odd' century years which
4052 * were leap years in the Julian calendar but not in the Gregorian one.
4053 * I can live with that.
4055 * This algorithm also fails to handle years before A.D. 1 gracefully, but
4056 * that's still outside the scope for POSIX time manipulation, so I don't
4060 year = 1900 + ptm->tm_year;
4061 month = ptm->tm_mon;
4062 mday = ptm->tm_mday;
4063 /* allow given yday with no month & mday to dominate the result */
4064 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
4067 jday = 1 + ptm->tm_yday;
4076 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4077 yearday += month*MONTH_TO_DAYS + mday + jday;
4079 * Note that we don't know when leap-seconds were or will be,
4080 * so we have to trust the user if we get something which looks
4081 * like a sensible leap-second. Wild values for seconds will
4082 * be rationalised, however.
4084 if ((unsigned) ptm->tm_sec <= 60) {
4091 secs += 60 * ptm->tm_min;
4092 secs += SECS_PER_HOUR * ptm->tm_hour;
4094 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4095 /* got negative remainder, but need positive time */
4096 /* back off an extra day to compensate */
4097 yearday += (secs/SECS_PER_DAY)-1;
4098 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4101 yearday += (secs/SECS_PER_DAY);
4102 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4105 else if (secs >= SECS_PER_DAY) {
4106 yearday += (secs/SECS_PER_DAY);
4107 secs %= SECS_PER_DAY;
4109 ptm->tm_hour = secs/SECS_PER_HOUR;
4110 secs %= SECS_PER_HOUR;
4111 ptm->tm_min = secs/60;
4113 ptm->tm_sec += secs;
4114 /* done with time of day effects */
4116 * The algorithm for yearday has (so far) left it high by 428.
4117 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4118 * bias it by 123 while trying to figure out what year it
4119 * really represents. Even with this tweak, the reverse
4120 * translation fails for years before A.D. 0001.
4121 * It would still fail for Feb 29, but we catch that one below.
4123 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
4124 yearday -= YEAR_ADJUST;
4125 year = (yearday / DAYS_PER_QCENT) * 400;
4126 yearday %= DAYS_PER_QCENT;
4127 odd_cent = yearday / DAYS_PER_CENT;
4128 year += odd_cent * 100;
4129 yearday %= DAYS_PER_CENT;
4130 year += (yearday / DAYS_PER_QYEAR) * 4;
4131 yearday %= DAYS_PER_QYEAR;
4132 odd_year = yearday / DAYS_PER_YEAR;
4134 yearday %= DAYS_PER_YEAR;
4135 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4140 yearday += YEAR_ADJUST; /* recover March 1st crock */
4141 month = yearday*DAYS_TO_MONTH;
4142 yearday -= month*MONTH_TO_DAYS;
4143 /* recover other leap-year adjustment */
4152 ptm->tm_year = year - 1900;
4154 ptm->tm_mday = yearday;
4155 ptm->tm_mon = month;
4159 ptm->tm_mon = month - 1;
4161 /* re-build yearday based on Jan 1 to get tm_yday */
4163 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4164 yearday += 14*MONTH_TO_DAYS + 1;
4165 ptm->tm_yday = jday - yearday;
4166 /* fix tm_wday if not overridden by caller */
4167 if ((unsigned)ptm->tm_wday > 6)
4168 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4172 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)
4180 PERL_ARGS_ASSERT_MY_STRFTIME;
4182 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4185 mytm.tm_hour = hour;
4186 mytm.tm_mday = mday;
4188 mytm.tm_year = year;
4189 mytm.tm_wday = wday;
4190 mytm.tm_yday = yday;
4191 mytm.tm_isdst = isdst;
4193 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4194 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4199 #ifdef HAS_TM_TM_GMTOFF
4200 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4202 #ifdef HAS_TM_TM_ZONE
4203 mytm.tm_zone = mytm2.tm_zone;
4208 Newx(buf, buflen, char);
4209 len = strftime(buf, buflen, fmt, &mytm);
4211 ** The following is needed to handle to the situation where
4212 ** tmpbuf overflows. Basically we want to allocate a buffer
4213 ** and try repeatedly. The reason why it is so complicated
4214 ** is that getting a return value of 0 from strftime can indicate
4215 ** one of the following:
4216 ** 1. buffer overflowed,
4217 ** 2. illegal conversion specifier, or
4218 ** 3. the format string specifies nothing to be returned(not
4219 ** an error). This could be because format is an empty string
4220 ** or it specifies %p that yields an empty string in some locale.
4221 ** If there is a better way to make it portable, go ahead by
4224 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4227 /* Possibly buf overflowed - try again with a bigger buf */
4228 const int fmtlen = strlen(fmt);
4229 int bufsize = fmtlen + buflen;
4231 Renew(buf, bufsize, char);
4233 buflen = strftime(buf, bufsize, fmt, &mytm);
4234 if (buflen > 0 && buflen < bufsize)
4236 /* heuristic to prevent out-of-memory errors */
4237 if (bufsize > 100*fmtlen) {
4243 Renew(buf, bufsize, char);
4248 Perl_croak(aTHX_ "panic: no strftime");
4254 #define SV_CWD_RETURN_UNDEF \
4255 sv_setsv(sv, &PL_sv_undef); \
4258 #define SV_CWD_ISDOT(dp) \
4259 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4260 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4263 =head1 Miscellaneous Functions
4265 =for apidoc getcwd_sv
4267 Fill the sv with current working directory
4272 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4273 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4274 * getcwd(3) if available
4275 * Comments from the orignal:
4276 * This is a faster version of getcwd. It's also more dangerous
4277 * because you might chdir out of a directory that you can't chdir
4281 Perl_getcwd_sv(pTHX_ register SV *sv)
4285 #ifndef INCOMPLETE_TAINTS
4289 PERL_ARGS_ASSERT_GETCWD_SV;
4293 char buf[MAXPATHLEN];
4295 /* Some getcwd()s automatically allocate a buffer of the given
4296 * size from the heap if they are given a NULL buffer pointer.
4297 * The problem is that this behaviour is not portable. */
4298 if (getcwd(buf, sizeof(buf) - 1)) {
4303 sv_setsv(sv, &PL_sv_undef);
4311 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4315 SvUPGRADE(sv, SVt_PV);
4317 if (PerlLIO_lstat(".", &statbuf) < 0) {
4318 SV_CWD_RETURN_UNDEF;
4321 orig_cdev = statbuf.st_dev;
4322 orig_cino = statbuf.st_ino;
4332 if (PerlDir_chdir("..") < 0) {
4333 SV_CWD_RETURN_UNDEF;
4335 if (PerlLIO_stat(".", &statbuf) < 0) {
4336 SV_CWD_RETURN_UNDEF;
4339 cdev = statbuf.st_dev;
4340 cino = statbuf.st_ino;
4342 if (odev == cdev && oino == cino) {
4345 if (!(dir = PerlDir_open("."))) {
4346 SV_CWD_RETURN_UNDEF;
4349 while ((dp = PerlDir_read(dir)) != NULL) {
4351 namelen = dp->d_namlen;
4353 namelen = strlen(dp->d_name);
4356 if (SV_CWD_ISDOT(dp)) {
4360 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4361 SV_CWD_RETURN_UNDEF;
4364 tdev = statbuf.st_dev;
4365 tino = statbuf.st_ino;
4366 if (tino == oino && tdev == odev) {
4372 SV_CWD_RETURN_UNDEF;
4375 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4376 SV_CWD_RETURN_UNDEF;
4379 SvGROW(sv, pathlen + namelen + 1);
4383 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4386 /* prepend current directory to the front */
4388 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4389 pathlen += (namelen + 1);
4391 #ifdef VOID_CLOSEDIR
4394 if (PerlDir_close(dir) < 0) {
4395 SV_CWD_RETURN_UNDEF;
4401 SvCUR_set(sv, pathlen);
4405 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4406 SV_CWD_RETURN_UNDEF;
4409 if (PerlLIO_stat(".", &statbuf) < 0) {
4410 SV_CWD_RETURN_UNDEF;
4413 cdev = statbuf.st_dev;
4414 cino = statbuf.st_ino;
4416 if (cdev != orig_cdev || cino != orig_cino) {
4417 Perl_croak(aTHX_ "Unstable directory path, "
4418 "current directory changed unexpectedly");
4429 #define VERSION_MAX 0x7FFFFFFF
4432 =for apidoc prescan_version
4434 Validate that a given string can be parsed as a version object, but doesn't
4435 actually perform the parsing. Can use either strict or lax validation rules.
4436 Can optionally set a number of hint variables to save the parsing code
4437 some time when tokenizing.
4442 Perl_prescan_version(pTHX_ const char *s, bool strict,
4443 const char **errstr,
4444 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4445 bool qv = (sqv ? *sqv : FALSE);
4447 int saw_decimal = 0;
4451 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4453 if (qv && isDIGIT(*d))
4454 goto dotted_decimal_version;
4456 if (*d == 'v') { /* explicit v-string */
4461 else { /* degenerate v-string */
4462 /* requires v1.2.3 */
4463 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4466 dotted_decimal_version:
4467 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4468 /* no leading zeros allowed */
4469 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4472 while (isDIGIT(*d)) /* integer part */
4478 d++; /* decimal point */
4483 /* require v1.2.3 */
4484 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4487 goto version_prescan_finish;
4494 while (isDIGIT(*d)) { /* just keep reading */
4496 while (isDIGIT(*d)) {
4498 /* maximum 3 digits between decimal */
4499 if (strict && j > 3) {
4500 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4505 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4508 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4513 else if (*d == '.') {
4515 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4520 else if (!isDIGIT(*d)) {
4526 if (strict && i < 2) {
4527 /* requires v1.2.3 */
4528 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4531 } /* end if dotted-decimal */
4533 { /* decimal versions */
4534 /* special strict case for leading '.' or '0' */
4537 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4539 if (*d == '0' && isDIGIT(d[1])) {
4540 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4544 /* and we never support negative versions */
4546 BADVERSION(s,errstr,"Invalid version format (negative version number)");
4549 /* consume all of the integer part */
4553 /* look for a fractional part */
4555 /* we found it, so consume it */
4559 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4562 BADVERSION(s,errstr,"Invalid version format (version required)");
4564 /* found just an integer */
4565 goto version_prescan_finish;
4567 else if ( d == s ) {
4568 /* didn't find either integer or period */
4569 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4571 else if (*d == '_') {
4572 /* underscore can't come after integer part */
4574 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4576 else if (isDIGIT(d[1])) {
4577 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4580 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4584 /* anything else after integer part is just invalid data */
4585 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4588 /* scan the fractional part after the decimal point*/
4590 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4591 /* strict or lax-but-not-the-end */
4592 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4595 while (isDIGIT(*d)) {
4597 if (*d == '.' && isDIGIT(d[-1])) {
4599 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4602 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4604 d = (char *)s; /* start all over again */
4606 goto dotted_decimal_version;
4610 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4613 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4615 if ( ! isDIGIT(d[1]) ) {
4616 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4624 version_prescan_finish:
4628 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4629 /* trailing non-numeric data */
4630 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4638 *ssaw_decimal = saw_decimal;
4645 =for apidoc scan_version
4647 Returns a pointer to the next character after the parsed
4648 version string, as well as upgrading the passed in SV to
4651 Function must be called with an already existing SV like
4654 s = scan_version(s, SV *sv, bool qv);
4656 Performs some preprocessing to the string to ensure that
4657 it has the correct characteristics of a version. Flags the
4658 object if it contains an underscore (which denotes this
4659 is an alpha version). The boolean qv denotes that the version
4660 should be interpreted as if it had multiple decimals, even if
4667 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4672 const char *errstr = NULL;
4673 int saw_decimal = 0;
4677 AV * const av = newAV();
4678 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4680 PERL_ARGS_ASSERT_SCAN_VERSION;
4682 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4684 #ifndef NODEFAULT_SHAREKEYS
4685 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4688 while (isSPACE(*s)) /* leading whitespace is OK */
4691 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4693 /* "undef" is a special case and not an error */
4694 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4695 Perl_croak(aTHX_ "%s", errstr);
4705 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4707 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4708 if ( !qv && width < 3 )
4709 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4711 while (isDIGIT(*pos))
4713 if (!isALPHA(*pos)) {
4719 /* this is atoi() that delimits on underscores */
4720 const char *end = pos;
4724 /* the following if() will only be true after the decimal
4725 * point of a version originally created with a bare
4726 * floating point number, i.e. not quoted in any way
4728 if ( !qv && s > start && saw_decimal == 1 ) {
4732 rev += (*s - '0') * mult;
4734 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4735 || (PERL_ABS(rev) > VERSION_MAX )) {
4736 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4737 "Integer overflow in version %d",VERSION_MAX);
4748 while (--end >= s) {
4750 rev += (*end - '0') * mult;
4752 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4753 || (PERL_ABS(rev) > VERSION_MAX )) {
4754 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4755 "Integer overflow in version");
4764 /* Append revision */
4765 av_push(av, newSViv(rev));
4770 else if ( *pos == '.' )
4772 else if ( *pos == '_' && isDIGIT(pos[1]) )
4774 else if ( *pos == ',' && isDIGIT(pos[1]) )
4776 else if ( isDIGIT(*pos) )
4783 while ( isDIGIT(*pos) )
4788 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4796 if ( qv ) { /* quoted versions always get at least three terms*/
4797 I32 len = av_len(av);
4798 /* This for loop appears to trigger a compiler bug on OS X, as it
4799 loops infinitely. Yes, len is negative. No, it makes no sense.
4800 Compiler in question is:
4801 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4802 for ( len = 2 - len; len > 0; len-- )
4803 av_push(MUTABLE_AV(sv), newSViv(0));
4807 av_push(av, newSViv(0));
4810 /* need to save off the current version string for later */
4812 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4813 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4814 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4816 else if ( s > start ) {
4817 SV * orig = newSVpvn(start,s-start);
4818 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4819 /* need to insert a v to be consistent */
4820 sv_insert(orig, 0, 0, "v", 1);
4822 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4825 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4826 av_push(av, newSViv(0));
4829 /* And finally, store the AV in the hash */
4830 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4832 /* fix RT#19517 - special case 'undef' as string */
4833 if ( *s == 'u' && strEQ(s,"undef") ) {
4841 =for apidoc new_version
4843 Returns a new version object based on the passed in SV:
4845 SV *sv = new_version(SV *ver);
4847 Does not alter the passed in ver SV. See "upg_version" if you
4848 want to upgrade the SV.
4854 Perl_new_version(pTHX_ SV *ver)
4857 SV * const rv = newSV(0);
4858 PERL_ARGS_ASSERT_NEW_VERSION;
4859 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4862 AV * const av = newAV();
4864 /* This will get reblessed later if a derived class*/
4865 SV * const hv = newSVrv(rv, "version");
4866 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4867 #ifndef NODEFAULT_SHAREKEYS
4868 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4874 /* Begin copying all of the elements */
4875 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4876 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4878 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4879 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4881 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4883 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4884 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4887 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4889 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4890 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4893 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4894 /* This will get reblessed later if a derived class*/
4895 for ( key = 0; key <= av_len(sav); key++ )
4897 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4898 av_push(av, newSViv(rev));
4901 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4906 const MAGIC* const mg = SvVSTRING_mg(ver);
4907 if ( mg ) { /* already a v-string */
4908 const STRLEN len = mg->mg_len;
4909 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4910 sv_setpvn(rv,version,len);
4911 /* this is for consistency with the pure Perl class */
4912 if ( isDIGIT(*version) )
4913 sv_insert(rv, 0, 0, "v", 1);
4918 sv_setsv(rv,ver); /* make a duplicate */
4923 return upg_version(rv, FALSE);
4927 =for apidoc upg_version
4929 In-place upgrade of the supplied SV to a version object.
4931 SV *sv = upg_version(SV *sv, bool qv);
4933 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4934 to force this SV to be interpreted as an "extended" version.
4940 Perl_upg_version(pTHX_ SV *ver, bool qv)
4942 const char *version, *s;
4947 PERL_ARGS_ASSERT_UPG_VERSION;
4949 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4951 /* may get too much accuracy */
4953 #ifdef USE_LOCALE_NUMERIC
4954 char *loc = setlocale(LC_NUMERIC, "C");
4956 STRLEN len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4957 #ifdef USE_LOCALE_NUMERIC
4958 setlocale(LC_NUMERIC, loc);
4960 while (tbuf[len-1] == '0' && len > 0) len--;
4961 if ( tbuf[len-1] == '.' ) len--; /* eat the trailing decimal */
4962 version = savepvn(tbuf, len);
4965 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4966 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4970 else /* must be a string or something like a string */
4973 version = savepv(SvPV(ver,len));
4975 # if PERL_VERSION > 5
4976 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4977 if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
4978 /* may be a v-string */
4979 char *testv = (char *)version;
4981 for (tlen=0; tlen < len; tlen++, testv++) {
4982 /* if one of the characters is non-text assume v-string */
4983 if (testv[0] < ' ') {
4984 SV * const nsv = sv_newmortal();
4987 int saw_decimal = 0;
4988 sv_setpvf(nsv,"v%vd",ver);
4989 pos = nver = savepv(SvPV_nolen(nsv));
4991 /* scan the resulting formatted string */
4992 pos++; /* skip the leading 'v' */
4993 while ( *pos == '.' || isDIGIT(*pos) ) {
4999 /* is definitely a v-string */
5000 if ( saw_decimal >= 2 ) {
5012 s = scan_version(version, ver, qv);
5014 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
5015 "Version string '%s' contains invalid data; "
5016 "ignoring: '%s'", version, s);
5024 Validates that the SV contains valid internal structure for a version object.
5025 It may be passed either the version object (RV) or the hash itself (HV). If
5026 the structure is valid, it returns the HV. If the structure is invalid,
5029 SV *hv = vverify(sv);
5031 Note that it only confirms the bare minimum structure (so as not to get
5032 confused by derived classes which may contain additional hash entries):
5036 =item * The SV is an HV or a reference to an HV
5038 =item * The hash contains a "version" key
5040 =item * The "version" key has a reference to an AV as its value
5048 Perl_vverify(pTHX_ SV *vs)
5052 PERL_ARGS_ASSERT_VVERIFY;
5057 /* see if the appropriate elements exist */
5058 if ( SvTYPE(vs) == SVt_PVHV
5059 && hv_exists(MUTABLE_HV(vs), "version", 7)
5060 && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
5061 && SvTYPE(sv) == SVt_PVAV )
5070 Accepts a version object and returns the normalized floating
5071 point representation. Call like:
5075 NOTE: you can pass either the object directly or the SV
5076 contained within the RV.
5078 The SV returned has a refcount of 1.
5084 Perl_vnumify(pTHX_ SV *vs)
5092 PERL_ARGS_ASSERT_VNUMIFY;
5094 /* extract the HV from the object */
5097 Perl_croak(aTHX_ "Invalid version object");
5099 /* see if various flags exist */
5100 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5102 if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
5103 width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
5108 /* attempt to retrieve the version array */
5109 if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
5110 return newSVpvs("0");
5116 return newSVpvs("0");
5119 digit = SvIV(*av_fetch(av, 0, 0));
5120 sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
5121 for ( i = 1 ; i < len ; i++ )
5123 digit = SvIV(*av_fetch(av, i, 0));
5125 const int denom = (width == 2 ? 10 : 100);
5126 const div_t term = div((int)PERL_ABS(digit),denom);
5127 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
5130 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5136 digit = SvIV(*av_fetch(av, len, 0));
5137 if ( alpha && width == 3 ) /* alpha version */
5139 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
5143 sv_catpvs(sv, "000");
5151 Accepts a version object and returns the normalized string
5152 representation. Call like:
5156 NOTE: you can pass either the object directly or the SV
5157 contained within the RV.
5159 The SV returned has a refcount of 1.
5165 Perl_vnormal(pTHX_ SV *vs)
5172 PERL_ARGS_ASSERT_VNORMAL;
5174 /* extract the HV from the object */
5177 Perl_croak(aTHX_ "Invalid version object");
5179 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
5181 av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)));
5186 return newSVpvs("");
5188 digit = SvIV(*av_fetch(av, 0, 0));
5189 sv = Perl_newSVpvf(aTHX_ "v%"IVdf, (IV)digit);
5190 for ( i = 1 ; i < len ; i++ ) {
5191 digit = SvIV(*av_fetch(av, i, 0));
5192 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5197 /* handle last digit specially */
5198 digit = SvIV(*av_fetch(av, len, 0));
5200 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
5202 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
5205 if ( len <= 2 ) { /* short version, must be at least three */
5206 for ( len = 2 - len; len != 0; len-- )
5213 =for apidoc vstringify
5215 In order to maintain maximum compatibility with earlier versions
5216 of Perl, this function will return either the floating point
5217 notation or the multiple dotted notation, depending on whether
5218 the original version contained 1 or more dots, respectively.
5220 The SV returned has a refcount of 1.
5226 Perl_vstringify(pTHX_ SV *vs)
5228 PERL_ARGS_ASSERT_VSTRINGIFY;
5230 /* extract the HV from the object */
5233 Perl_croak(aTHX_ "Invalid version object");
5235 if (hv_exists(MUTABLE_HV(vs), "original", sizeof("original") - 1)) {
5237 pv = *hv_fetchs(MUTABLE_HV(vs), "original", FALSE);
5241 return &PL_sv_undef;
5244 if ( hv_exists(MUTABLE_HV(vs), "qv", 2) )
5254 Version object aware cmp. Both operands must already have been
5255 converted into version objects.
5261 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
5264 bool lalpha = FALSE;
5265 bool ralpha = FALSE;
5270 PERL_ARGS_ASSERT_VCMP;
5272 /* extract the HVs from the objects */
5275 if ( ! ( lhv && rhv ) )
5276 Perl_croak(aTHX_ "Invalid version object");
5278 /* get the left hand term */
5279 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(lhv), "version", FALSE)));
5280 if ( hv_exists(MUTABLE_HV(lhv), "alpha", 5 ) )
5283 /* and the right hand term */
5284 rav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rhv), "version", FALSE)));
5285 if ( hv_exists(MUTABLE_HV(rhv), "alpha", 5 ) )
5293 while ( i <= m && retval == 0 )
5295 left = SvIV(*av_fetch(lav,i,0));
5296 right = SvIV(*av_fetch(rav,i,0));
5304 /* tiebreaker for alpha with identical terms */
5305 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
5307 if ( lalpha && !ralpha )
5311 else if ( ralpha && !lalpha)
5317 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
5321 while ( i <= r && retval == 0 )
5323 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
5324 retval = -1; /* not a match after all */
5330 while ( i <= l && retval == 0 )
5332 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
5333 retval = +1; /* not a match after all */
5341 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
5342 # define EMULATE_SOCKETPAIR_UDP
5345 #ifdef EMULATE_SOCKETPAIR_UDP
5347 S_socketpair_udp (int fd[2]) {
5349 /* Fake a datagram socketpair using UDP to localhost. */
5350 int sockets[2] = {-1, -1};
5351 struct sockaddr_in addresses[2];
5353 Sock_size_t size = sizeof(struct sockaddr_in);
5354 unsigned short port;
5357 memset(&addresses, 0, sizeof(addresses));
5360 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
5361 if (sockets[i] == -1)
5362 goto tidy_up_and_fail;
5364 addresses[i].sin_family = AF_INET;
5365 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5366 addresses[i].sin_port = 0; /* kernel choses port. */
5367 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
5368 sizeof(struct sockaddr_in)) == -1)
5369 goto tidy_up_and_fail;
5372 /* Now have 2 UDP sockets. Find out which port each is connected to, and
5373 for each connect the other socket to it. */
5376 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
5378 goto tidy_up_and_fail;
5379 if (size != sizeof(struct sockaddr_in))
5380 goto abort_tidy_up_and_fail;
5381 /* !1 is 0, !0 is 1 */
5382 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
5383 sizeof(struct sockaddr_in)) == -1)
5384 goto tidy_up_and_fail;
5387 /* Now we have 2 sockets connected to each other. I don't trust some other
5388 process not to have already sent a packet to us (by random) so send
5389 a packet from each to the other. */
5392 /* I'm going to send my own port number. As a short.
5393 (Who knows if someone somewhere has sin_port as a bitfield and needs
5394 this routine. (I'm assuming crays have socketpair)) */
5395 port = addresses[i].sin_port;
5396 got = PerlLIO_write(sockets[i], &port, sizeof(port));
5397 if (got != sizeof(port)) {
5399 goto tidy_up_and_fail;
5400 goto abort_tidy_up_and_fail;
5404 /* Packets sent. I don't trust them to have arrived though.
5405 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
5406 connect to localhost will use a second kernel thread. In 2.6 the
5407 first thread running the connect() returns before the second completes,
5408 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
5409 returns 0. Poor programs have tripped up. One poor program's authors'
5410 had a 50-1 reverse stock split. Not sure how connected these were.)
5411 So I don't trust someone not to have an unpredictable UDP stack.
5415 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
5416 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
5420 FD_SET((unsigned int)sockets[0], &rset);
5421 FD_SET((unsigned int)sockets[1], &rset);
5423 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
5424 if (got != 2 || !FD_ISSET(sockets[0], &rset)
5425 || !FD_ISSET(sockets[1], &rset)) {
5426 /* I hope this is portable and appropriate. */
5428 goto tidy_up_and_fail;
5429 goto abort_tidy_up_and_fail;
5433 /* And the paranoia department even now doesn't trust it to have arrive
5434 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
5436 struct sockaddr_in readfrom;
5437 unsigned short buffer[2];
5442 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5443 sizeof(buffer), MSG_DONTWAIT,
5444 (struct sockaddr *) &readfrom, &size);
5446 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5448 (struct sockaddr *) &readfrom, &size);
5452 goto tidy_up_and_fail;
5453 if (got != sizeof(port)
5454 || size != sizeof(struct sockaddr_in)
5455 /* Check other socket sent us its port. */
5456 || buffer[0] != (unsigned short) addresses[!i].sin_port
5457 /* Check kernel says we got the datagram from that socket */
5458 || readfrom.sin_family != addresses[!i].sin_family
5459 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
5460 || readfrom.sin_port != addresses[!i].sin_port)
5461 goto abort_tidy_up_and_fail;
5464 /* My caller (my_socketpair) has validated that this is non-NULL */
5467 /* I hereby declare this connection open. May God bless all who cross
5471 abort_tidy_up_and_fail:
5472 errno = ECONNABORTED;
5476 if (sockets[0] != -1)
5477 PerlLIO_close(sockets[0]);
5478 if (sockets[1] != -1)
5479 PerlLIO_close(sockets[1]);
5484 #endif /* EMULATE_SOCKETPAIR_UDP */
5486 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
5488 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5489 /* Stevens says that family must be AF_LOCAL, protocol 0.
5490 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
5495 struct sockaddr_in listen_addr;
5496 struct sockaddr_in connect_addr;
5501 || family != AF_UNIX
5504 errno = EAFNOSUPPORT;
5512 #ifdef EMULATE_SOCKETPAIR_UDP
5513 if (type == SOCK_DGRAM)
5514 return S_socketpair_udp(fd);
5517 listener = PerlSock_socket(AF_INET, type, 0);
5520 memset(&listen_addr, 0, sizeof(listen_addr));
5521 listen_addr.sin_family = AF_INET;
5522 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5523 listen_addr.sin_port = 0; /* kernel choses port. */
5524 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5525 sizeof(listen_addr)) == -1)
5526 goto tidy_up_and_fail;
5527 if (PerlSock_listen(listener, 1) == -1)
5528 goto tidy_up_and_fail;
5530 connector = PerlSock_socket(AF_INET, type, 0);
5531 if (connector == -1)
5532 goto tidy_up_and_fail;
5533 /* We want to find out the port number to connect to. */
5534 size = sizeof(connect_addr);
5535 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5537 goto tidy_up_and_fail;
5538 if (size != sizeof(connect_addr))
5539 goto abort_tidy_up_and_fail;
5540 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
5541 sizeof(connect_addr)) == -1)
5542 goto tidy_up_and_fail;
5544 size = sizeof(listen_addr);
5545 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5548 goto tidy_up_and_fail;
5549 if (size != sizeof(listen_addr))
5550 goto abort_tidy_up_and_fail;
5551 PerlLIO_close(listener);
5552 /* Now check we are talking to ourself by matching port and host on the
5554 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5556 goto tidy_up_and_fail;
5557 if (size != sizeof(connect_addr)
5558 || listen_addr.sin_family != connect_addr.sin_family
5559 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5560 || listen_addr.sin_port != connect_addr.sin_port) {
5561 goto abort_tidy_up_and_fail;
5567 abort_tidy_up_and_fail:
5569 errno = ECONNABORTED; /* This would be the standard thing to do. */
5571 # ifdef ECONNREFUSED
5572 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5574 errno = ETIMEDOUT; /* Desperation time. */
5581 PerlLIO_close(listener);
5582 if (connector != -1)
5583 PerlLIO_close(connector);
5585 PerlLIO_close(acceptor);
5591 /* In any case have a stub so that there's code corresponding
5592 * to the my_socketpair in embed.fnc. */
5594 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5595 #ifdef HAS_SOCKETPAIR
5596 return socketpair(family, type, protocol, fd);
5605 =for apidoc sv_nosharing
5607 Dummy routine which "shares" an SV when there is no sharing module present.
5608 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5609 Exists to avoid test for a NULL function pointer and because it could
5610 potentially warn under some level of strict-ness.
5616 Perl_sv_nosharing(pTHX_ SV *sv)
5618 PERL_UNUSED_CONTEXT;
5619 PERL_UNUSED_ARG(sv);
5624 =for apidoc sv_destroyable
5626 Dummy routine which reports that object can be destroyed when there is no
5627 sharing module present. It ignores its single SV argument, and returns
5628 'true'. Exists to avoid test for a NULL function pointer and because it
5629 could potentially warn under some level of strict-ness.
5635 Perl_sv_destroyable(pTHX_ SV *sv)
5637 PERL_UNUSED_CONTEXT;
5638 PERL_UNUSED_ARG(sv);
5643 Perl_parse_unicode_opts(pTHX_ const char **popt)
5645 const char *p = *popt;
5648 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5652 opt = (U32) atoi(p);
5655 if (*p && *p != '\n' && *p != '\r') {
5656 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5658 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
5664 case PERL_UNICODE_STDIN:
5665 opt |= PERL_UNICODE_STDIN_FLAG; break;
5666 case PERL_UNICODE_STDOUT:
5667 opt |= PERL_UNICODE_STDOUT_FLAG; break;
5668 case PERL_UNICODE_STDERR:
5669 opt |= PERL_UNICODE_STDERR_FLAG; break;
5670 case PERL_UNICODE_STD:
5671 opt |= PERL_UNICODE_STD_FLAG; break;
5672 case PERL_UNICODE_IN:
5673 opt |= PERL_UNICODE_IN_FLAG; break;
5674 case PERL_UNICODE_OUT:
5675 opt |= PERL_UNICODE_OUT_FLAG; break;
5676 case PERL_UNICODE_INOUT:
5677 opt |= PERL_UNICODE_INOUT_FLAG; break;
5678 case PERL_UNICODE_LOCALE:
5679 opt |= PERL_UNICODE_LOCALE_FLAG; break;
5680 case PERL_UNICODE_ARGV:
5681 opt |= PERL_UNICODE_ARGV_FLAG; break;
5682 case PERL_UNICODE_UTF8CACHEASSERT:
5683 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
5685 if (*p != '\n' && *p != '\r') {
5686 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5689 "Unknown Unicode option letter '%c'", *p);
5696 opt = PERL_UNICODE_DEFAULT_FLAGS;
5698 the_end_of_the_opts_parser:
5700 if (opt & ~PERL_UNICODE_ALL_FLAGS)
5701 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
5702 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5714 * This is really just a quick hack which grabs various garbage
5715 * values. It really should be a real hash algorithm which
5716 * spreads the effect of every input bit onto every output bit,
5717 * if someone who knows about such things would bother to write it.
5718 * Might be a good idea to add that function to CORE as well.
5719 * No numbers below come from careful analysis or anything here,
5720 * except they are primes and SEED_C1 > 1E6 to get a full-width
5721 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5722 * probably be bigger too.
5725 # define SEED_C1 1000003
5726 #define SEED_C4 73819
5728 # define SEED_C1 25747
5729 #define SEED_C4 20639
5733 #define SEED_C5 26107
5735 #ifndef PERL_NO_DEV_RANDOM
5740 # include <starlet.h>
5741 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5742 * in 100-ns units, typically incremented ever 10 ms. */
5743 unsigned int when[2];
5745 # ifdef HAS_GETTIMEOFDAY
5746 struct timeval when;
5752 /* This test is an escape hatch, this symbol isn't set by Configure. */
5753 #ifndef PERL_NO_DEV_RANDOM
5754 #ifndef PERL_RANDOM_DEVICE
5755 /* /dev/random isn't used by default because reads from it will block
5756 * if there isn't enough entropy available. You can compile with
5757 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5758 * is enough real entropy to fill the seed. */
5759 # define PERL_RANDOM_DEVICE "/dev/urandom"
5761 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5763 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5772 _ckvmssts(sys$gettim(when));
5773 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5775 # ifdef HAS_GETTIMEOFDAY
5776 PerlProc_gettimeofday(&when,NULL);
5777 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5780 u = (U32)SEED_C1 * when;
5783 u += SEED_C3 * (U32)PerlProc_getpid();
5784 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5785 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5786 u += SEED_C5 * (U32)PTR2UV(&when);
5792 Perl_get_hash_seed(pTHX)
5795 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
5801 if (s && isDIGIT(*s))
5802 myseed = (UV)Atoul(s);
5804 #ifdef USE_HASH_SEED_EXPLICIT
5808 /* Compute a random seed */
5809 (void)seedDrand01((Rand_seed_t)seed());
5810 myseed = (UV)(Drand01() * (NV)UV_MAX);
5811 #if RANDBITS < (UVSIZE * 8)
5812 /* Since there are not enough randbits to to reach all
5813 * the bits of a UV, the low bits might need extra
5814 * help. Sum in another random number that will
5815 * fill in the low bits. */
5817 (UV)(Drand01() * (NV)((((UV)1) << ((UVSIZE * 8 - RANDBITS))) - 1));
5818 #endif /* RANDBITS < (UVSIZE * 8) */
5819 if (myseed == 0) { /* Superparanoia. */
5820 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5822 Perl_croak(aTHX_ "Your random numbers are not that random");
5825 PL_rehash_seed_set = TRUE;
5832 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5834 const char * const stashpv = CopSTASHPV(c);
5835 const char * const name = HvNAME_get(hv);
5836 PERL_UNUSED_CONTEXT;
5837 PERL_ARGS_ASSERT_STASHPV_HVNAME_MATCH;
5839 if (stashpv == name)
5841 if (stashpv && name)
5842 if (strEQ(stashpv, name))
5849 #ifdef PERL_GLOBAL_STRUCT
5851 #define PERL_GLOBAL_STRUCT_INIT
5852 #include "opcode.h" /* the ppaddr and check */
5855 Perl_init_global_struct(pTHX)
5857 struct perl_vars *plvarsp = NULL;
5858 # ifdef PERL_GLOBAL_STRUCT
5859 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5860 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5861 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5862 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5863 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5867 plvarsp = PL_VarsPtr;
5868 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5873 # define PERLVAR(prefix,var,type) /**/
5874 # define PERLVARA(prefix,var,n,type) /**/
5875 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
5876 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
5877 # include "perlvars.h"
5882 # ifdef PERL_GLOBAL_STRUCT
5885 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5886 if (!plvarsp->Gppaddr)
5890 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5891 if (!plvarsp->Gcheck)
5893 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5894 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5896 # ifdef PERL_SET_VARS
5897 PERL_SET_VARS(plvarsp);
5899 # undef PERL_GLOBAL_STRUCT_INIT
5904 #endif /* PERL_GLOBAL_STRUCT */
5906 #ifdef PERL_GLOBAL_STRUCT
5909 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5911 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
5912 # ifdef PERL_GLOBAL_STRUCT
5913 # ifdef PERL_UNSET_VARS
5914 PERL_UNSET_VARS(plvarsp);
5916 free(plvarsp->Gppaddr);
5917 free(plvarsp->Gcheck);
5918 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5924 #endif /* PERL_GLOBAL_STRUCT */
5928 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
5929 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
5930 * given, and you supply your own implementation.
5932 * The default implementation reads a single env var, PERL_MEM_LOG,
5933 * expecting one or more of the following:
5935 * \d+ - fd fd to write to : must be 1st (atoi)
5936 * 'm' - memlog was PERL_MEM_LOG=1
5937 * 's' - svlog was PERL_SV_LOG=1
5938 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
5940 * This makes the logger controllable enough that it can reasonably be
5941 * added to the system perl.
5944 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
5945 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5947 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5949 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
5950 * writes to. In the default logger, this is settable at runtime.
5952 #ifndef PERL_MEM_LOG_FD
5953 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5956 #ifndef PERL_MEM_LOG_NOIMPL
5958 # ifdef DEBUG_LEAKING_SCALARS
5959 # define SV_LOG_SERIAL_FMT " [%lu]"
5960 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
5962 # define SV_LOG_SERIAL_FMT
5963 # define _SV_LOG_SERIAL_ARG(sv)
5967 S_mem_log_common(enum mem_log_type mlt, const UV n,
5968 const UV typesize, const char *type_name, const SV *sv,
5969 Malloc_t oldalloc, Malloc_t newalloc,
5970 const char *filename, const int linenumber,
5971 const char *funcname)
5975 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
5977 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
5980 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
5982 /* We can't use SVs or PerlIO for obvious reasons,
5983 * so we'll use stdio and low-level IO instead. */
5984 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5986 # ifdef HAS_GETTIMEOFDAY
5987 # define MEM_LOG_TIME_FMT "%10d.%06d: "
5988 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
5990 gettimeofday(&tv, 0);
5992 # define MEM_LOG_TIME_FMT "%10d: "
5993 # define MEM_LOG_TIME_ARG (int)when
5997 /* If there are other OS specific ways of hires time than
5998 * gettimeofday() (see ext/Time-HiRes), the easiest way is
5999 * probably that they would be used to fill in the struct
6003 int fd = atoi(pmlenv);
6005 fd = PERL_MEM_LOG_FD;
6007 if (strchr(pmlenv, 't')) {
6008 len = my_snprintf(buf, sizeof(buf),
6009 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
6010 PerlLIO_write(fd, buf, len);
6014 len = my_snprintf(buf, sizeof(buf),
6015 "alloc: %s:%d:%s: %"IVdf" %"UVuf
6016 " %s = %"IVdf": %"UVxf"\n",
6017 filename, linenumber, funcname, n, typesize,
6018 type_name, n * typesize, PTR2UV(newalloc));
6021 len = my_snprintf(buf, sizeof(buf),
6022 "realloc: %s:%d:%s: %"IVdf" %"UVuf
6023 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
6024 filename, linenumber, funcname, n, typesize,
6025 type_name, n * typesize, PTR2UV(oldalloc),
6029 len = my_snprintf(buf, sizeof(buf),
6030 "free: %s:%d:%s: %"UVxf"\n",
6031 filename, linenumber, funcname,
6036 len = my_snprintf(buf, sizeof(buf),
6037 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
6038 mlt == MLT_NEW_SV ? "new" : "del",
6039 filename, linenumber, funcname,
6040 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
6045 PerlLIO_write(fd, buf, len);
6049 #endif /* !PERL_MEM_LOG_NOIMPL */
6051 #ifndef PERL_MEM_LOG_NOIMPL
6053 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
6054 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
6056 /* this is suboptimal, but bug compatible. User is providing their
6057 own implementation, but is getting these functions anyway, and they
6058 do nothing. But _NOIMPL users should be able to cope or fix */
6060 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
6061 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
6065 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
6067 const char *filename, const int linenumber,
6068 const char *funcname)
6070 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
6071 NULL, NULL, newalloc,
6072 filename, linenumber, funcname);
6077 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
6078 Malloc_t oldalloc, Malloc_t newalloc,
6079 const char *filename, const int linenumber,
6080 const char *funcname)
6082 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
6083 NULL, oldalloc, newalloc,
6084 filename, linenumber, funcname);
6089 Perl_mem_log_free(Malloc_t oldalloc,
6090 const char *filename, const int linenumber,
6091 const char *funcname)
6093 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
6094 filename, linenumber, funcname);
6099 Perl_mem_log_new_sv(const SV *sv,
6100 const char *filename, const int linenumber,
6101 const char *funcname)
6103 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
6104 filename, linenumber, funcname);
6108 Perl_mem_log_del_sv(const SV *sv,
6109 const char *filename, const int linenumber,
6110 const char *funcname)
6112 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
6113 filename, linenumber, funcname);
6116 #endif /* PERL_MEM_LOG */
6119 =for apidoc my_sprintf
6121 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
6122 the length of the string written to the buffer. Only rare pre-ANSI systems
6123 need the wrapper function - usually this is a direct call to C<sprintf>.
6127 #ifndef SPRINTF_RETURNS_STRLEN
6129 Perl_my_sprintf(char *buffer, const char* pat, ...)
6132 PERL_ARGS_ASSERT_MY_SPRINTF;
6133 va_start(args, pat);
6134 vsprintf(buffer, pat, args);
6136 return strlen(buffer);
6141 =for apidoc my_snprintf
6143 The C library C<snprintf> functionality, if available and
6144 standards-compliant (uses C<vsnprintf>, actually). However, if the
6145 C<vsnprintf> is not available, will unfortunately use the unsafe
6146 C<vsprintf> which can overrun the buffer (there is an overrun check,
6147 but that may be too late). Consider using C<sv_vcatpvf> instead, or
6148 getting C<vsnprintf>.
6153 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
6158 PERL_ARGS_ASSERT_MY_SNPRINTF;
6159 va_start(ap, format);
6160 #ifdef HAS_VSNPRINTF
6161 retval = vsnprintf(buffer, len, format, ap);
6163 retval = vsprintf(buffer, format, ap);
6166 /* vsprintf() shows failure with < 0 */
6168 #ifdef HAS_VSNPRINTF
6169 /* vsnprintf() shows failure with >= len */
6171 (len > 0 && (Size_t)retval >= len)
6174 Perl_croak(aTHX_ "panic: my_snprintf buffer overflow");
6179 =for apidoc my_vsnprintf
6181 The C library C<vsnprintf> if available and standards-compliant.
6182 However, if if the C<vsnprintf> is not available, will unfortunately
6183 use the unsafe C<vsprintf> which can overrun the buffer (there is an
6184 overrun check, but that may be too late). Consider using
6185 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
6190 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
6197 PERL_ARGS_ASSERT_MY_VSNPRINTF;
6199 Perl_va_copy(ap, apc);
6200 # ifdef HAS_VSNPRINTF
6201 retval = vsnprintf(buffer, len, format, apc);
6203 retval = vsprintf(buffer, format, apc);
6206 # ifdef HAS_VSNPRINTF
6207 retval = vsnprintf(buffer, len, format, ap);
6209 retval = vsprintf(buffer, format, ap);
6211 #endif /* #ifdef NEED_VA_COPY */
6212 /* vsprintf() shows failure with < 0 */
6214 #ifdef HAS_VSNPRINTF
6215 /* vsnprintf() shows failure with >= len */
6217 (len > 0 && (Size_t)retval >= len)
6220 Perl_croak(aTHX_ "panic: my_vsnprintf buffer overflow");
6225 Perl_my_clearenv(pTHX)
6228 #if ! defined(PERL_MICRO)
6229 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
6231 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
6232 # if defined(USE_ENVIRON_ARRAY)
6233 # if defined(USE_ITHREADS)
6234 /* only the parent thread can clobber the process environment */
6235 if (PL_curinterp == aTHX)
6236 # endif /* USE_ITHREADS */
6238 # if ! defined(PERL_USE_SAFE_PUTENV)
6239 if ( !PL_use_safe_putenv) {
6241 if (environ == PL_origenviron)
6242 environ = (char**)safesysmalloc(sizeof(char*));
6244 for (i = 0; environ[i]; i++)
6245 (void)safesysfree(environ[i]);
6248 # else /* PERL_USE_SAFE_PUTENV */
6249 # if defined(HAS_CLEARENV)
6251 # elif defined(HAS_UNSETENV)
6252 int bsiz = 80; /* Most envvar names will be shorter than this. */
6253 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
6254 char *buf = (char*)safesysmalloc(bufsiz);
6255 while (*environ != NULL) {
6256 char *e = strchr(*environ, '=');
6257 int l = e ? e - *environ : (int)strlen(*environ);
6259 (void)safesysfree(buf);
6260 bsiz = l + 1; /* + 1 for the \0. */
6261 buf = (char*)safesysmalloc(bufsiz);
6263 memcpy(buf, *environ, l);
6265 (void)unsetenv(buf);
6267 (void)safesysfree(buf);
6268 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
6269 /* Just null environ and accept the leakage. */
6271 # endif /* HAS_CLEARENV || HAS_UNSETENV */
6272 # endif /* ! PERL_USE_SAFE_PUTENV */
6274 # endif /* USE_ENVIRON_ARRAY */
6275 # endif /* PERL_IMPLICIT_SYS || WIN32 */
6276 #endif /* PERL_MICRO */
6279 #ifdef PERL_IMPLICIT_CONTEXT
6281 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
6282 the global PL_my_cxt_index is incremented, and that value is assigned to
6283 that module's static my_cxt_index (who's address is passed as an arg).
6284 Then, for each interpreter this function is called for, it makes sure a
6285 void* slot is available to hang the static data off, by allocating or
6286 extending the interpreter's PL_my_cxt_list array */
6288 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
6290 Perl_my_cxt_init(pTHX_ int *index, size_t size)
6294 PERL_ARGS_ASSERT_MY_CXT_INIT;
6296 /* this module hasn't been allocated an index yet */
6297 #if defined(USE_ITHREADS)
6298 MUTEX_LOCK(&PL_my_ctx_mutex);
6300 *index = PL_my_cxt_index++;
6301 #if defined(USE_ITHREADS)
6302 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6306 /* make sure the array is big enough */
6307 if (PL_my_cxt_size <= *index) {
6308 if (PL_my_cxt_size) {
6309 while (PL_my_cxt_size <= *index)
6310 PL_my_cxt_size *= 2;
6311 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6314 PL_my_cxt_size = 16;
6315 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6318 /* newSV() allocates one more than needed */
6319 p = (void*)SvPVX(newSV(size-1));
6320 PL_my_cxt_list[*index] = p;
6321 Zero(p, size, char);
6325 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6328 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
6333 PERL_ARGS_ASSERT_MY_CXT_INDEX;
6335 for (index = 0; index < PL_my_cxt_index; index++) {
6336 const char *key = PL_my_cxt_keys[index];
6337 /* try direct pointer compare first - there are chances to success,
6338 * and it's much faster.
6340 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
6347 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
6353 PERL_ARGS_ASSERT_MY_CXT_INIT;
6355 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
6357 /* this module hasn't been allocated an index yet */
6358 #if defined(USE_ITHREADS)
6359 MUTEX_LOCK(&PL_my_ctx_mutex);
6361 index = PL_my_cxt_index++;
6362 #if defined(USE_ITHREADS)
6363 MUTEX_UNLOCK(&PL_my_ctx_mutex);
6367 /* make sure the array is big enough */
6368 if (PL_my_cxt_size <= index) {
6369 int old_size = PL_my_cxt_size;
6371 if (PL_my_cxt_size) {
6372 while (PL_my_cxt_size <= index)
6373 PL_my_cxt_size *= 2;
6374 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6375 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6378 PL_my_cxt_size = 16;
6379 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6380 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6382 for (i = old_size; i < PL_my_cxt_size; i++) {
6383 PL_my_cxt_keys[i] = 0;
6384 PL_my_cxt_list[i] = 0;
6387 PL_my_cxt_keys[index] = my_cxt_key;
6388 /* newSV() allocates one more than needed */
6389 p = (void*)SvPVX(newSV(size-1));
6390 PL_my_cxt_list[index] = p;
6391 Zero(p, size, char);
6394 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6395 #endif /* PERL_IMPLICIT_CONTEXT */
6398 Perl_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
6402 const char *vn = NULL;
6403 SV *const module = PL_stack_base[ax];
6405 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
6407 if (items >= 2) /* version supplied as bootstrap arg */
6408 sv = PL_stack_base[ax + 1];
6410 /* XXX GV_ADDWARN */
6412 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6413 if (!sv || !SvOK(sv)) {
6415 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6419 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
6420 SV *pmsv = sv_derived_from(sv, "version")
6421 ? sv : sv_2mortal(new_version(sv));
6422 xssv = upg_version(xssv, 0);
6423 if ( vcmp(pmsv,xssv) ) {
6424 SV *string = vstringify(xssv);
6425 SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
6426 " does not match ", module, string);
6428 SvREFCNT_dec(string);
6429 string = vstringify(pmsv);
6432 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, module, vn,
6435 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, string);
6437 SvREFCNT_dec(string);
6439 Perl_sv_2mortal(aTHX_ xpt);
6440 Perl_croak_sv(aTHX_ xpt);
6446 Perl_xs_apiversion_bootcheck(pTHX_ SV *module, const char *api_p,
6450 SV *compver = Perl_newSVpvn_flags(aTHX_ api_p, api_len, SVs_TEMP);
6453 PERL_ARGS_ASSERT_XS_APIVERSION_BOOTCHECK;
6455 /* This might croak */
6456 compver = upg_version(compver, 0);
6457 /* This should never croak */
6458 runver = new_version(PL_apiversion);
6459 if (vcmp(compver, runver)) {
6460 SV *compver_string = vstringify(compver);
6461 SV *runver_string = vstringify(runver);
6462 xpt = Perl_newSVpvf(aTHX_ "Perl API version %"SVf
6463 " of %"SVf" does not match %"SVf,
6464 compver_string, module, runver_string);
6465 Perl_sv_2mortal(aTHX_ xpt);
6467 SvREFCNT_dec(compver_string);
6468 SvREFCNT_dec(runver_string);
6470 SvREFCNT_dec(runver);
6472 Perl_croak_sv(aTHX_ xpt);
6477 Perl_my_strlcat(char *dst, const char *src, Size_t size)
6479 Size_t used, length, copy;
6482 length = strlen(src);
6483 if (size > 0 && used < size - 1) {
6484 copy = (length >= size - used) ? size - used - 1 : length;
6485 memcpy(dst + used, src, copy);
6486 dst[used + copy] = '\0';
6488 return used + length;
6494 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
6496 Size_t length, copy;
6498 length = strlen(src);
6500 copy = (length >= size) ? size - 1 : length;
6501 memcpy(dst, src, copy);
6508 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
6509 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
6510 long _ftol( double ); /* Defined by VC6 C libs. */
6511 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
6515 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
6518 SV * const dbsv = GvSVn(PL_DBsub);
6519 const bool save_taint = PL_tainted;
6521 /* We do not care about using sv to call CV;
6522 * it's for informational purposes only.
6525 PERL_ARGS_ASSERT_GET_DB_SUB;
6529 if (!PERLDB_SUB_NN) {
6532 if ( svp && ((CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
6533 || strEQ(GvNAME(gv), "END")
6534 || ((GvCV(gv) != cv) && /* Could be imported, and old sub redefined. */
6535 !( (SvTYPE(*svp) == SVt_PVGV)
6536 && (GvCV((const GV *)*svp) == cv)
6537 && (gv = (GV *)*svp)
6541 /* Use GV from the stack as a fallback. */
6542 /* GV is potentially non-unique, or contain different CV. */
6543 SV * const tmp = newRV(MUTABLE_SV(cv));
6544 sv_setsv(dbsv, tmp);
6548 gv_efullname3(dbsv, gv, NULL);
6552 const int type = SvTYPE(dbsv);
6553 if (type < SVt_PVIV && type != SVt_IV)
6554 sv_upgrade(dbsv, SVt_PVIV);
6555 (void)SvIOK_on(dbsv);
6556 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
6558 TAINT_IF(save_taint);
6562 Perl_my_dirfd(pTHX_ DIR * dir) {
6564 /* Most dirfd implementations have problems when passed NULL. */
6569 #elif defined(HAS_DIR_DD_FD)
6572 Perl_die(aTHX_ PL_no_func, "dirfd");
6579 Perl_get_re_arg(pTHX_ SV *sv) {
6585 sv = MUTABLE_SV(SvRV(sv));
6586 if (SvTYPE(sv) == SVt_REGEXP)
6587 return (REGEXP*) sv;
6595 * c-indentation-style: bsd
6597 * indent-tabs-mode: t
6600 * ex: set ts=8 sts=4 sw=4 noet: