3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * 'Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content.' --Gandalf to Pippin
15 * [p.598 of _The Lord of the Rings_, III/xi: "The PalantÃr"]
18 /* This file contains assorted utility routines.
19 * Which is a polite way of saying any stuff that people couldn't think of
20 * a better place for. Amongst other things, it includes the warning and
21 * dieing stuff, plus wrappers for malloc code.
25 #define PERL_IN_UTIL_C
29 #include "perliol.h" /* For PerlIOUnix_refcnt */
35 # define SIG_ERR ((Sighandler_t) -1)
40 /* Missing protos on LynxOS */
46 # include <sys/select.h>
52 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
53 # define FD_CLOEXEC 1 /* NeXT needs this */
56 /* NOTE: Do not call the next three routines directly. Use the macros
57 * in handy.h, so that we can easily redefine everything to do tracking of
58 * allocated hunks back to the original New to track down any memory leaks.
59 * XXX This advice seems to be widely ignored :-( --AD August 1996.
66 /* Can't use PerlIO to write as it allocates memory */
67 PerlLIO_write(PerlIO_fileno(Perl_error_log),
68 PL_no_mem, strlen(PL_no_mem));
70 NORETURN_FUNCTION_END;
73 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
74 # define ALWAYS_NEED_THX
77 /* paranoid version of system's malloc() */
80 Perl_safesysmalloc(MEM_SIZE size)
82 #ifdef ALWAYS_NEED_THX
88 PerlIO_printf(Perl_error_log,
89 "Allocation too large: %lx\n", size) FLUSH;
92 #endif /* HAS_64K_LIMIT */
93 #ifdef PERL_TRACK_MEMPOOL
97 if ((SSize_t)size < 0)
98 Perl_croak_nocontext("panic: malloc, size=%"UVuf, (UV) size);
100 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
101 PERL_ALLOC_CHECK(ptr);
103 #ifdef PERL_TRACK_MEMPOOL
104 struct perl_memory_debug_header *const header
105 = (struct perl_memory_debug_header *)ptr;
109 PoisonNew(((char *)ptr), size, char);
112 #ifdef PERL_TRACK_MEMPOOL
113 header->interpreter = aTHX;
114 /* Link us into the list. */
115 header->prev = &PL_memory_debug_header;
116 header->next = PL_memory_debug_header.next;
117 PL_memory_debug_header.next = header;
118 header->next->prev = header;
122 ptr = (Malloc_t)((char*)ptr+sTHX);
124 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
128 #ifndef ALWAYS_NEED_THX
134 return write_no_mem();
140 /* paranoid version of system's realloc() */
143 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
145 #ifdef ALWAYS_NEED_THX
149 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
150 Malloc_t PerlMem_realloc();
151 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
155 PerlIO_printf(Perl_error_log,
156 "Reallocation too large: %lx\n", size) FLUSH;
159 #endif /* HAS_64K_LIMIT */
166 return safesysmalloc(size);
167 #ifdef PERL_TRACK_MEMPOOL
168 where = (Malloc_t)((char*)where-sTHX);
171 struct perl_memory_debug_header *const header
172 = (struct perl_memory_debug_header *)where;
174 if (header->interpreter != aTHX) {
175 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
176 header->interpreter, aTHX);
178 assert(header->next->prev == header);
179 assert(header->prev->next == header);
181 if (header->size > size) {
182 const MEM_SIZE freed_up = header->size - size;
183 char *start_of_freed = ((char *)where) + size;
184 PoisonFree(start_of_freed, freed_up, char);
191 if ((SSize_t)size < 0)
192 Perl_croak_nocontext("panic: realloc, size=%"UVuf, (UV)size);
194 ptr = (Malloc_t)PerlMem_realloc(where,size);
195 PERL_ALLOC_CHECK(ptr);
197 /* MUST do this fixup first, before doing ANYTHING else, as anything else
198 might allocate memory/free/move memory, and until we do the fixup, it
199 may well be chasing (and writing to) free memory. */
200 #ifdef PERL_TRACK_MEMPOOL
202 struct perl_memory_debug_header *const header
203 = (struct perl_memory_debug_header *)ptr;
206 if (header->size < size) {
207 const MEM_SIZE fresh = size - header->size;
208 char *start_of_fresh = ((char *)ptr) + size;
209 PoisonNew(start_of_fresh, fresh, char);
213 header->next->prev = header;
214 header->prev->next = header;
216 ptr = (Malloc_t)((char*)ptr+sTHX);
220 /* In particular, must do that fixup above before logging anything via
221 *printf(), as it can reallocate memory, which can cause SEGVs. */
223 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
224 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
231 #ifndef ALWAYS_NEED_THX
237 return write_no_mem();
243 /* safe version of system's free() */
246 Perl_safesysfree(Malloc_t where)
248 #ifdef ALWAYS_NEED_THX
253 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
255 #ifdef PERL_TRACK_MEMPOOL
256 where = (Malloc_t)((char*)where-sTHX);
258 struct perl_memory_debug_header *const header
259 = (struct perl_memory_debug_header *)where;
261 if (header->interpreter != aTHX) {
262 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
263 header->interpreter, aTHX);
266 Perl_croak_nocontext("panic: duplicate free");
269 Perl_croak_nocontext("panic: bad free, header->next==NULL");
270 if (header->next->prev != header || header->prev->next != header) {
271 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
272 "header=%p, ->prev->next=%p",
273 header->next->prev, header,
276 /* Unlink us from the chain. */
277 header->next->prev = header->prev;
278 header->prev->next = header->next;
280 PoisonNew(where, header->size, char);
282 /* Trigger the duplicate free warning. */
290 /* safe version of system's calloc() */
293 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
295 #ifdef ALWAYS_NEED_THX
299 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
300 MEM_SIZE total_size = 0;
303 /* Even though calloc() for zero bytes is strange, be robust. */
304 if (size && (count <= MEM_SIZE_MAX / size)) {
305 #if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
306 total_size = size * count;
310 Perl_croak_nocontext("%s", PL_memory_wrap);
311 #ifdef PERL_TRACK_MEMPOOL
312 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
315 Perl_croak_nocontext("%s", PL_memory_wrap);
318 if (total_size > 0xffff) {
319 PerlIO_printf(Perl_error_log,
320 "Allocation too large: %lx\n", total_size) FLUSH;
323 #endif /* HAS_64K_LIMIT */
325 if ((SSize_t)size < 0 || (SSize_t)count < 0)
326 Perl_croak_nocontext("panic: calloc, size=%"UVuf", count=%"UVuf,
327 (UV)size, (UV)count);
329 #ifdef PERL_TRACK_MEMPOOL
330 /* Have to use malloc() because we've added some space for our tracking
332 /* malloc(0) is non-portable. */
333 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
335 /* Use calloc() because it might save a memset() if the memory is fresh
336 and clean from the OS. */
338 ptr = (Malloc_t)PerlMem_calloc(count, size);
339 else /* calloc(0) is non-portable. */
340 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
342 PERL_ALLOC_CHECK(ptr);
343 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)total_size));
345 #ifdef PERL_TRACK_MEMPOOL
347 struct perl_memory_debug_header *const header
348 = (struct perl_memory_debug_header *)ptr;
350 memset((void*)ptr, 0, total_size);
351 header->interpreter = aTHX;
352 /* Link us into the list. */
353 header->prev = &PL_memory_debug_header;
354 header->next = PL_memory_debug_header.next;
355 PL_memory_debug_header.next = header;
356 header->next->prev = header;
358 header->size = total_size;
360 ptr = (Malloc_t)((char*)ptr+sTHX);
366 #ifndef ALWAYS_NEED_THX
371 return write_no_mem();
375 /* These must be defined when not using Perl's malloc for binary
380 Malloc_t Perl_malloc (MEM_SIZE nbytes)
383 return (Malloc_t)PerlMem_malloc(nbytes);
386 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
389 return (Malloc_t)PerlMem_calloc(elements, size);
392 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
395 return (Malloc_t)PerlMem_realloc(where, nbytes);
398 Free_t Perl_mfree (Malloc_t where)
406 /* copy a string up to some (non-backslashed) delimiter, if any */
409 Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
413 PERL_ARGS_ASSERT_DELIMCPY;
415 for (tolen = 0; from < fromend; from++, tolen++) {
417 if (from[1] != delim) {
424 else if (*from == delim)
435 /* return ptr to little string in big string, NULL if not found */
436 /* This routine was donated by Corey Satten. */
439 Perl_instr(register const char *big, register const char *little)
443 PERL_ARGS_ASSERT_INSTR;
451 register const char *s, *x;
454 for (x=big,s=little; *s; /**/ ) {
465 return (char*)(big-1);
470 /* same as instr but allow embedded nulls. The end pointers point to 1 beyond
471 * the final character desired to be checked */
474 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
476 PERL_ARGS_ASSERT_NINSTR;
480 const char first = *little;
482 bigend -= lend - little++;
484 while (big <= bigend) {
485 if (*big++ == first) {
486 for (x=big,s=little; s < lend; x++,s++) {
490 return (char*)(big-1);
497 /* reverse of the above--find last substring */
500 Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
502 register const char *bigbeg;
503 register const I32 first = *little;
504 register const char * const littleend = lend;
506 PERL_ARGS_ASSERT_RNINSTR;
508 if (little >= littleend)
509 return (char*)bigend;
511 big = bigend - (littleend - little++);
512 while (big >= bigbeg) {
513 register const char *s, *x;
516 for (x=big+2,s=little; s < littleend; /**/ ) {
525 return (char*)(big+1);
530 /* As a space optimization, we do not compile tables for strings of length
531 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
532 special-cased in fbm_instr().
534 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
537 =head1 Miscellaneous Functions
539 =for apidoc fbm_compile
541 Analyses the string in order to make fast searches on it using fbm_instr()
542 -- the Boyer-Moore algorithm.
548 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
551 register const U8 *s;
558 PERL_ARGS_ASSERT_FBM_COMPILE;
560 /* Refuse to fbm_compile a studied scalar, as this gives more flexibility in
561 SV flag usage. No real-world code would ever end up using a studied
562 scalar as a compile-time second argument to index, so this isn't a real
570 if (flags & FBMcf_TAIL) {
571 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
572 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
573 if (mg && mg->mg_len >= 0)
576 s = (U8*)SvPV_force_mutable(sv, len);
577 if (len == 0) /* TAIL might be on a zero-length string. */
579 SvUPGRADE(sv, SVt_PVMG);
584 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
585 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
586 to call SvVALID_off() if the scalar was assigned to.
588 The comment itself (and "deeper magic" below) date back to
589 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
591 where the magic (presumably) was that the scalar had a BM table hidden
594 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
595 the table instead of the previous (somewhat hacky) approach of co-opting
596 the string buffer and storing it after the string. */
598 assert(!mg_find(sv, PERL_MAGIC_bm));
599 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
603 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
605 const U8 mlen = (len>255) ? 255 : (U8)len;
606 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
609 Newx(table, 256, U8);
610 memset((void*)table, mlen, 256);
611 mg->mg_ptr = (char *)table;
614 s += len - 1; /* last char */
617 if (table[*s] == mlen)
623 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
624 for (i = 0; i < len; i++) {
625 if (PL_freq[s[i]] < frequency) {
627 frequency = PL_freq[s[i]];
630 BmRARE(sv) = s[rarest];
631 BmPREVIOUS(sv) = rarest;
632 BmUSEFUL(sv) = 100; /* Initial value */
633 if (flags & FBMcf_TAIL)
635 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
636 BmRARE(sv), BmPREVIOUS(sv)));
639 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
640 /* If SvTAIL is actually due to \Z or \z, this gives false positives
644 =for apidoc fbm_instr
646 Returns the location of the SV in the string delimited by C<str> and
647 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
648 does not have to be fbm_compiled, but the search will not be as fast
655 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
657 register unsigned char *s;
659 register const unsigned char *little
660 = (const unsigned char *)SvPV_const(littlestr,l);
661 register STRLEN littlelen = l;
662 register const I32 multiline = flags & FBMrf_MULTILINE;
664 PERL_ARGS_ASSERT_FBM_INSTR;
666 if ((STRLEN)(bigend - big) < littlelen) {
667 if ( SvTAIL(littlestr)
668 && ((STRLEN)(bigend - big) == littlelen - 1)
670 || (*big == *little &&
671 memEQ((char *)big, (char *)little, littlelen - 1))))
676 switch (littlelen) { /* Special cases for 0, 1 and 2 */
678 return (char*)big; /* Cannot be SvTAIL! */
680 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
681 /* Know that bigend != big. */
682 if (bigend[-1] == '\n')
683 return (char *)(bigend - 1);
684 return (char *) bigend;
692 if (SvTAIL(littlestr))
693 return (char *) bigend;
696 if (SvTAIL(littlestr) && !multiline) {
697 if (bigend[-1] == '\n' && bigend[-2] == *little)
698 return (char*)bigend - 2;
699 if (bigend[-1] == *little)
700 return (char*)bigend - 1;
704 /* This should be better than FBM if c1 == c2, and almost
705 as good otherwise: maybe better since we do less indirection.
706 And we save a lot of memory by caching no table. */
707 const unsigned char c1 = little[0];
708 const unsigned char c2 = little[1];
713 while (s <= bigend) {
723 goto check_1char_anchor;
734 goto check_1char_anchor;
737 while (s <= bigend) {
742 goto check_1char_anchor;
751 check_1char_anchor: /* One char and anchor! */
752 if (SvTAIL(littlestr) && (*bigend == *little))
753 return (char *)bigend; /* bigend is already decremented. */
756 break; /* Only lengths 0 1 and 2 have special-case code. */
759 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
760 s = bigend - littlelen;
761 if (s >= big && bigend[-1] == '\n' && *s == *little
762 /* Automatically of length > 2 */
763 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
765 return (char*)s; /* how sweet it is */
768 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
770 return (char*)s + 1; /* how sweet it is */
774 if (!SvVALID(littlestr)) {
775 char * const b = ninstr((char*)big,(char*)bigend,
776 (char*)little, (char*)little + littlelen);
778 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
779 /* Chop \n from littlestr: */
780 s = bigend - littlelen + 1;
782 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
792 if (littlelen > (STRLEN)(bigend - big))
796 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
797 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
798 register const unsigned char *oldlittle;
800 --littlelen; /* Last char found by table lookup */
803 little += littlelen; /* last char */
809 if ((tmp = table[*s])) {
810 if ((s += tmp) < bigend)
814 else { /* less expensive than calling strncmp() */
815 register unsigned char * const olds = s;
820 if (*--s == *--little)
822 s = olds + 1; /* here we pay the price for failure */
824 if (s < bigend) /* fake up continue to outer loop */
834 && memEQ((char *)(bigend - littlelen),
835 (char *)(oldlittle - littlelen), littlelen) )
836 return (char*)bigend - littlelen;
841 /* start_shift, end_shift are positive quantities which give offsets
842 of ends of some substring of bigstr.
843 If "last" we want the last occurrence.
844 old_posp is the way of communication between consequent calls if
845 the next call needs to find the .
846 The initial *old_posp should be -1.
848 Note that we take into account SvTAIL, so one can get extra
849 optimizations if _ALL flag is set.
852 /* If SvTAIL is actually due to \Z or \z, this gives false positives
853 if PL_multiline. In fact if !PL_multiline the authoritative answer
854 is not supported yet. */
857 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
860 register const unsigned char *big;
861 U32 pos = 0; /* hush a gcc warning */
862 register I32 previous;
864 register const unsigned char *little;
865 register I32 stop_pos;
866 register const unsigned char *littleend;
869 const void *screamnext_raw = NULL; /* hush a gcc warning */
870 bool cant_find = FALSE; /* hush a gcc warning */
872 PERL_ARGS_ASSERT_SCREAMINSTR;
874 assert(SvMAGICAL(bigstr));
875 mg = mg_find(bigstr, PERL_MAGIC_study);
877 assert(SvTYPE(littlestr) == SVt_PVMG);
878 assert(SvVALID(littlestr));
880 if (mg->mg_private == 1) {
881 const U8 *const screamfirst = (U8 *)mg->mg_ptr;
882 const U8 *const screamnext = screamfirst + 256;
884 screamnext_raw = (const void *)screamnext;
886 pos = *old_posp == -1
887 ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
888 cant_find = pos == (U8)~0;
889 } else if (mg->mg_private == 2) {
890 const U16 *const screamfirst = (U16 *)mg->mg_ptr;
891 const U16 *const screamnext = screamfirst + 256;
893 screamnext_raw = (const void *)screamnext;
895 pos = *old_posp == -1
896 ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
897 cant_find = pos == (U16)~0;
898 } else if (mg->mg_private == 4) {
899 const U32 *const screamfirst = (U32 *)mg->mg_ptr;
900 const U32 *const screamnext = screamfirst + 256;
902 screamnext_raw = (const void *)screamnext;
904 pos = *old_posp == -1
905 ? screamfirst[BmRARE(littlestr)] : screamnext[*old_posp];
906 cant_find = pos == (U32)~0;
908 Perl_croak(aTHX_ "panic: unknown study size %u", mg->mg_private);
912 if ( BmRARE(littlestr) == '\n'
913 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
914 little = (const unsigned char *)(SvPVX_const(littlestr));
915 littleend = little + SvCUR(littlestr);
922 little = (const unsigned char *)(SvPVX_const(littlestr));
923 littleend = little + SvCUR(littlestr);
925 /* The value of pos we can start at: */
926 previous = BmPREVIOUS(littlestr);
927 big = (const unsigned char *)(SvPVX_const(bigstr));
928 /* The value of pos we can stop at: */
929 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
930 if (previous + start_shift > stop_pos) {
932 stop_pos does not include SvTAIL in the count, so this check is incorrect
933 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
936 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
941 if (mg->mg_private == 1) {
942 const U8 *const screamnext = (const U8 *const) screamnext_raw;
943 while ((I32)pos < previous + start_shift) {
944 pos = screamnext[pos];
948 } else if (mg->mg_private == 2) {
949 const U16 *const screamnext = (const U16 *const) screamnext_raw;
950 while ((I32)pos < previous + start_shift) {
951 pos = screamnext[pos];
955 } else if (mg->mg_private == 4) {
956 const U32 *const screamnext = (const U32 *const) screamnext_raw;
957 while ((I32)pos < previous + start_shift) {
958 pos = screamnext[pos];
965 if ((I32)pos >= stop_pos) break;
966 if (big[pos] == first) {
967 const unsigned char *s = little;
968 const unsigned char *x = big + pos + 1;
969 while (s < littleend) {
974 if (s == littleend) {
975 *old_posp = (I32)pos;
976 if (!last) return (char *)(big+pos);
980 if (mg->mg_private == 1) {
981 pos = ((const U8 *const)screamnext_raw)[pos];
984 } else if (mg->mg_private == 2) {
985 pos = ((const U16 *const)screamnext_raw)[pos];
988 } else if (mg->mg_private == 4) {
989 pos = ((const U32 *const)screamnext_raw)[pos];
995 return (char *)(big+(*old_posp));
997 if (!SvTAIL(littlestr) || (end_shift > 0))
999 /* Ignore the trailing "\n". This code is not microoptimized */
1000 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
1001 stop_pos = littleend - little; /* Actual littlestr len */
1006 && ((stop_pos == 1) ||
1007 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
1015 Returns true if the leading len bytes of the strings s1 and s2 are the same
1016 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
1017 match themselves and their opposite case counterparts. Non-cased and non-ASCII
1018 range bytes match only themselves.
1025 Perl_foldEQ(const char *s1, const char *s2, register I32 len)
1027 register const U8 *a = (const U8 *)s1;
1028 register const U8 *b = (const U8 *)s2;
1030 PERL_ARGS_ASSERT_FOLDEQ;
1033 if (*a != *b && *a != PL_fold[*b])
1040 Perl_foldEQ_latin1(const char *s1, const char *s2, register I32 len)
1042 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
1043 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
1044 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
1045 * does it check that the strings each have at least 'len' characters */
1047 register const U8 *a = (const U8 *)s1;
1048 register const U8 *b = (const U8 *)s2;
1050 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
1053 if (*a != *b && *a != PL_fold_latin1[*b]) {
1062 =for apidoc foldEQ_locale
1064 Returns true if the leading len bytes of the strings s1 and s2 are the same
1065 case-insensitively in the current locale; false otherwise.
1071 Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
1074 register const U8 *a = (const U8 *)s1;
1075 register const U8 *b = (const U8 *)s2;
1077 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
1080 if (*a != *b && *a != PL_fold_locale[*b])
1087 /* copy a string to a safe spot */
1090 =head1 Memory Management
1094 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1095 string which is a duplicate of C<pv>. The size of the string is
1096 determined by C<strlen()>. The memory allocated for the new string can
1097 be freed with the C<Safefree()> function.
1103 Perl_savepv(pTHX_ const char *pv)
1105 PERL_UNUSED_CONTEXT;
1110 const STRLEN pvlen = strlen(pv)+1;
1111 Newx(newaddr, pvlen, char);
1112 return (char*)memcpy(newaddr, pv, pvlen);
1116 /* same thing but with a known length */
1121 Perl's version of what C<strndup()> would be if it existed. Returns a
1122 pointer to a newly allocated string which is a duplicate of the first
1123 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
1124 the new string can be freed with the C<Safefree()> function.
1130 Perl_savepvn(pTHX_ const char *pv, register I32 len)
1132 register char *newaddr;
1133 PERL_UNUSED_CONTEXT;
1135 Newx(newaddr,len+1,char);
1136 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1138 /* might not be null terminated */
1139 newaddr[len] = '\0';
1140 return (char *) CopyD(pv,newaddr,len,char);
1143 return (char *) ZeroD(newaddr,len+1,char);
1148 =for apidoc savesharedpv
1150 A version of C<savepv()> which allocates the duplicate string in memory
1151 which is shared between threads.
1156 Perl_savesharedpv(pTHX_ const char *pv)
1158 register char *newaddr;
1163 pvlen = strlen(pv)+1;
1164 newaddr = (char*)PerlMemShared_malloc(pvlen);
1166 return write_no_mem();
1168 return (char*)memcpy(newaddr, pv, pvlen);
1172 =for apidoc savesharedpvn
1174 A version of C<savepvn()> which allocates the duplicate string in memory
1175 which is shared between threads. (With the specific difference that a NULL
1176 pointer is not acceptable)
1181 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1183 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1185 PERL_ARGS_ASSERT_SAVESHAREDPVN;
1188 return write_no_mem();
1190 newaddr[len] = '\0';
1191 return (char*)memcpy(newaddr, pv, len);
1195 =for apidoc savesvpv
1197 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1198 the passed in SV using C<SvPV()>
1204 Perl_savesvpv(pTHX_ SV *sv)
1207 const char * const pv = SvPV_const(sv, len);
1208 register char *newaddr;
1210 PERL_ARGS_ASSERT_SAVESVPV;
1213 Newx(newaddr,len,char);
1214 return (char *) CopyD(pv,newaddr,len,char);
1218 =for apidoc savesharedsvpv
1220 A version of C<savesharedpv()> which allocates the duplicate string in
1221 memory which is shared between threads.
1227 Perl_savesharedsvpv(pTHX_ SV *sv)
1230 const char * const pv = SvPV_const(sv, len);
1232 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1234 return savesharedpvn(pv, len);
1237 /* the SV for Perl_form() and mess() is not kept in an arena */
1246 if (PL_phase != PERL_PHASE_DESTRUCT)
1247 return newSVpvs_flags("", SVs_TEMP);
1252 /* Create as PVMG now, to avoid any upgrading later */
1254 Newxz(any, 1, XPVMG);
1255 SvFLAGS(sv) = SVt_PVMG;
1256 SvANY(sv) = (void*)any;
1258 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1263 #if defined(PERL_IMPLICIT_CONTEXT)
1265 Perl_form_nocontext(const char* pat, ...)
1270 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1271 va_start(args, pat);
1272 retval = vform(pat, &args);
1276 #endif /* PERL_IMPLICIT_CONTEXT */
1279 =head1 Miscellaneous Functions
1282 Takes a sprintf-style format pattern and conventional
1283 (non-SV) arguments and returns the formatted string.
1285 (char *) Perl_form(pTHX_ const char* pat, ...)
1287 can be used any place a string (char *) is required:
1289 char * s = Perl_form("%d.%d",major,minor);
1291 Uses a single private buffer so if you want to format several strings you
1292 must explicitly copy the earlier strings away (and free the copies when you
1299 Perl_form(pTHX_ const char* pat, ...)
1303 PERL_ARGS_ASSERT_FORM;
1304 va_start(args, pat);
1305 retval = vform(pat, &args);
1311 Perl_vform(pTHX_ const char *pat, va_list *args)
1313 SV * const sv = mess_alloc();
1314 PERL_ARGS_ASSERT_VFORM;
1315 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1320 =for apidoc Am|SV *|mess|const char *pat|...
1322 Take a sprintf-style format pattern and argument list. These are used to
1323 generate a string message. If the message does not end with a newline,
1324 then it will be extended with some indication of the current location
1325 in the code, as described for L</mess_sv>.
1327 Normally, the resulting message is returned in a new mortal SV.
1328 During global destruction a single SV may be shared between uses of
1334 #if defined(PERL_IMPLICIT_CONTEXT)
1336 Perl_mess_nocontext(const char *pat, ...)
1341 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1342 va_start(args, pat);
1343 retval = vmess(pat, &args);
1347 #endif /* PERL_IMPLICIT_CONTEXT */
1350 Perl_mess(pTHX_ const char *pat, ...)
1354 PERL_ARGS_ASSERT_MESS;
1355 va_start(args, pat);
1356 retval = vmess(pat, &args);
1362 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1365 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1367 PERL_ARGS_ASSERT_CLOSEST_COP;
1369 if (!o || o == PL_op)
1372 if (o->op_flags & OPf_KIDS) {
1374 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1377 /* If the OP_NEXTSTATE has been optimised away we can still use it
1378 * the get the file and line number. */
1380 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1381 cop = (const COP *)kid;
1383 /* Keep searching, and return when we've found something. */
1385 new_cop = closest_cop(cop, kid);
1391 /* Nothing found. */
1397 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1399 Expands a message, intended for the user, to include an indication of
1400 the current location in the code, if the message does not already appear
1403 C<basemsg> is the initial message or object. If it is a reference, it
1404 will be used as-is and will be the result of this function. Otherwise it
1405 is used as a string, and if it already ends with a newline, it is taken
1406 to be complete, and the result of this function will be the same string.
1407 If the message does not end with a newline, then a segment such as C<at
1408 foo.pl line 37> will be appended, and possibly other clauses indicating
1409 the current state of execution. The resulting message will end with a
1412 Normally, the resulting message is returned in a new mortal SV.
1413 During global destruction a single SV may be shared between uses of this
1414 function. If C<consume> is true, then the function is permitted (but not
1415 required) to modify and return C<basemsg> instead of allocating a new SV.
1421 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1426 PERL_ARGS_ASSERT_MESS_SV;
1428 if (SvROK(basemsg)) {
1434 sv_setsv(sv, basemsg);
1439 if (SvPOK(basemsg) && consume) {
1444 sv_copypv(sv, basemsg);
1447 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1449 * Try and find the file and line for PL_op. This will usually be
1450 * PL_curcop, but it might be a cop that has been optimised away. We
1451 * can try to find such a cop by searching through the optree starting
1452 * from the sibling of PL_curcop.
1455 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1460 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1461 OutCopFILE(cop), (IV)CopLINE(cop));
1462 /* Seems that GvIO() can be untrustworthy during global destruction. */
1463 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1464 && IoLINES(GvIOp(PL_last_in_gv)))
1466 const bool line_mode = (RsSIMPLE(PL_rs) &&
1467 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1468 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1469 SVfARG(PL_last_in_gv == PL_argvgv
1471 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1472 line_mode ? "line" : "chunk",
1473 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1475 if (PL_phase == PERL_PHASE_DESTRUCT)
1476 sv_catpvs(sv, " during global destruction");
1477 sv_catpvs(sv, ".\n");
1483 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1485 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1486 argument list. These are used to generate a string message. If the
1487 message does not end with a newline, then it will be extended with
1488 some indication of the current location in the code, as described for
1491 Normally, the resulting message is returned in a new mortal SV.
1492 During global destruction a single SV may be shared between uses of
1499 Perl_vmess(pTHX_ const char *pat, va_list *args)
1502 SV * const sv = mess_alloc();
1504 PERL_ARGS_ASSERT_VMESS;
1506 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1507 return mess_sv(sv, 1);
1511 Perl_write_to_stderr(pTHX_ SV* msv)
1517 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1519 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1520 && (io = GvIO(PL_stderrgv))
1521 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1522 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1523 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1526 /* SFIO can really mess with your errno */
1529 PerlIO * const serr = Perl_error_log;
1531 do_print(msv, serr);
1532 (void)PerlIO_flush(serr);
1540 =head1 Warning and Dieing
1543 /* Common code used in dieing and warning */
1546 S_with_queued_errors(pTHX_ SV *ex)
1548 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1549 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1550 sv_catsv(PL_errors, ex);
1551 ex = sv_mortalcopy(PL_errors);
1552 SvCUR_set(PL_errors, 0);
1558 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1564 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1565 /* sv_2cv might call Perl_croak() or Perl_warner() */
1566 SV * const oldhook = *hook;
1574 cv = sv_2cv(oldhook, &stash, &gv, 0);
1576 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1586 exarg = newSVsv(ex);
1587 SvREADONLY_on(exarg);
1590 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1594 call_sv(MUTABLE_SV(cv), G_DISCARD);
1603 =for apidoc Am|OP *|die_sv|SV *baseex
1605 Behaves the same as L</croak_sv>, except for the return type.
1606 It should be used only where the C<OP *> return type is required.
1607 The function never actually returns.
1613 Perl_die_sv(pTHX_ SV *baseex)
1615 PERL_ARGS_ASSERT_DIE_SV;
1622 =for apidoc Am|OP *|die|const char *pat|...
1624 Behaves the same as L</croak>, except for the return type.
1625 It should be used only where the C<OP *> return type is required.
1626 The function never actually returns.
1631 #if defined(PERL_IMPLICIT_CONTEXT)
1633 Perl_die_nocontext(const char* pat, ...)
1637 va_start(args, pat);
1643 #endif /* PERL_IMPLICIT_CONTEXT */
1646 Perl_die(pTHX_ const char* pat, ...)
1649 va_start(args, pat);
1657 =for apidoc Am|void|croak_sv|SV *baseex
1659 This is an XS interface to Perl's C<die> function.
1661 C<baseex> is the error message or object. If it is a reference, it
1662 will be used as-is. Otherwise it is used as a string, and if it does
1663 not end with a newline then it will be extended with some indication of
1664 the current location in the code, as described for L</mess_sv>.
1666 The error message or object will be used as an exception, by default
1667 returning control to the nearest enclosing C<eval>, but subject to
1668 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1669 function never returns normally.
1671 To die with a simple string message, the L</croak> function may be
1678 Perl_croak_sv(pTHX_ SV *baseex)
1680 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1681 PERL_ARGS_ASSERT_CROAK_SV;
1682 invoke_exception_hook(ex, FALSE);
1687 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1689 This is an XS interface to Perl's C<die> function.
1691 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1692 argument list. These are used to generate a string message. If the
1693 message does not end with a newline, then it will be extended with
1694 some indication of the current location in the code, as described for
1697 The error message will be used as an exception, by default
1698 returning control to the nearest enclosing C<eval>, but subject to
1699 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1700 function never returns normally.
1702 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1703 (C<$@>) will be used as an error message or object instead of building an
1704 error message from arguments. If you want to throw a non-string object,
1705 or build an error message in an SV yourself, it is preferable to use
1706 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1712 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1714 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1715 invoke_exception_hook(ex, FALSE);
1720 =for apidoc Am|void|croak|const char *pat|...
1722 This is an XS interface to Perl's C<die> function.
1724 Take a sprintf-style format pattern and argument list. These are used to
1725 generate a string message. If the message does not end with a newline,
1726 then it will be extended with some indication of the current location
1727 in the code, as described for L</mess_sv>.
1729 The error message will be used as an exception, by default
1730 returning control to the nearest enclosing C<eval>, but subject to
1731 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1732 function never returns normally.
1734 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1735 (C<$@>) will be used as an error message or object instead of building an
1736 error message from arguments. If you want to throw a non-string object,
1737 or build an error message in an SV yourself, it is preferable to use
1738 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1743 #if defined(PERL_IMPLICIT_CONTEXT)
1745 Perl_croak_nocontext(const char *pat, ...)
1749 va_start(args, pat);
1754 #endif /* PERL_IMPLICIT_CONTEXT */
1757 Perl_croak(pTHX_ const char *pat, ...)
1760 va_start(args, pat);
1767 =for apidoc Am|void|croak_no_modify
1769 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1770 terser object code than using C<Perl_croak>. Less code used on exception code
1771 paths reduces CPU cache pressure.
1777 Perl_croak_no_modify(pTHX)
1779 Perl_croak(aTHX_ "%s", PL_no_modify);
1783 =for apidoc Am|void|warn_sv|SV *baseex
1785 This is an XS interface to Perl's C<warn> function.
1787 C<baseex> is the error message or object. If it is a reference, it
1788 will be used as-is. Otherwise it is used as a string, and if it does
1789 not end with a newline then it will be extended with some indication of
1790 the current location in the code, as described for L</mess_sv>.
1792 The error message or object will by default be written to standard error,
1793 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1795 To warn with a simple string message, the L</warn> function may be
1802 Perl_warn_sv(pTHX_ SV *baseex)
1804 SV *ex = mess_sv(baseex, 0);
1805 PERL_ARGS_ASSERT_WARN_SV;
1806 if (!invoke_exception_hook(ex, TRUE))
1807 write_to_stderr(ex);
1811 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1813 This is an XS interface to Perl's C<warn> function.
1815 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1816 argument list. These are used to generate a string message. If the
1817 message does not end with a newline, then it will be extended with
1818 some indication of the current location in the code, as described for
1821 The error message or object will by default be written to standard error,
1822 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1824 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1830 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1832 SV *ex = vmess(pat, args);
1833 PERL_ARGS_ASSERT_VWARN;
1834 if (!invoke_exception_hook(ex, TRUE))
1835 write_to_stderr(ex);
1839 =for apidoc Am|void|warn|const char *pat|...
1841 This is an XS interface to Perl's C<warn> function.
1843 Take a sprintf-style format pattern and argument list. These are used to
1844 generate a string message. If the message does not end with a newline,
1845 then it will be extended with some indication of the current location
1846 in the code, as described for L</mess_sv>.
1848 The error message or object will by default be written to standard error,
1849 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1851 Unlike with L</croak>, C<pat> is not permitted to be null.
1856 #if defined(PERL_IMPLICIT_CONTEXT)
1858 Perl_warn_nocontext(const char *pat, ...)
1862 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1863 va_start(args, pat);
1867 #endif /* PERL_IMPLICIT_CONTEXT */
1870 Perl_warn(pTHX_ const char *pat, ...)
1873 PERL_ARGS_ASSERT_WARN;
1874 va_start(args, pat);
1879 #if defined(PERL_IMPLICIT_CONTEXT)
1881 Perl_warner_nocontext(U32 err, const char *pat, ...)
1885 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1886 va_start(args, pat);
1887 vwarner(err, pat, &args);
1890 #endif /* PERL_IMPLICIT_CONTEXT */
1893 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1895 PERL_ARGS_ASSERT_CK_WARNER_D;
1897 if (Perl_ckwarn_d(aTHX_ err)) {
1899 va_start(args, pat);
1900 vwarner(err, pat, &args);
1906 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1908 PERL_ARGS_ASSERT_CK_WARNER;
1910 if (Perl_ckwarn(aTHX_ err)) {
1912 va_start(args, pat);
1913 vwarner(err, pat, &args);
1919 Perl_warner(pTHX_ U32 err, const char* pat,...)
1922 PERL_ARGS_ASSERT_WARNER;
1923 va_start(args, pat);
1924 vwarner(err, pat, &args);
1929 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1932 PERL_ARGS_ASSERT_VWARNER;
1933 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1934 SV * const msv = vmess(pat, args);
1936 invoke_exception_hook(msv, FALSE);
1940 Perl_vwarn(aTHX_ pat, args);
1944 /* implements the ckWARN? macros */
1947 Perl_ckwarn(pTHX_ U32 w)
1950 /* If lexical warnings have not been set, use $^W. */
1952 return PL_dowarn & G_WARN_ON;
1954 return ckwarn_common(w);
1957 /* implements the ckWARN?_d macro */
1960 Perl_ckwarn_d(pTHX_ U32 w)
1963 /* If lexical warnings have not been set then default classes warn. */
1967 return ckwarn_common(w);
1971 S_ckwarn_common(pTHX_ U32 w)
1973 if (PL_curcop->cop_warnings == pWARN_ALL)
1976 if (PL_curcop->cop_warnings == pWARN_NONE)
1979 /* Check the assumption that at least the first slot is non-zero. */
1980 assert(unpackWARN1(w));
1982 /* Check the assumption that it is valid to stop as soon as a zero slot is
1984 if (!unpackWARN2(w)) {
1985 assert(!unpackWARN3(w));
1986 assert(!unpackWARN4(w));
1987 } else if (!unpackWARN3(w)) {
1988 assert(!unpackWARN4(w));
1991 /* Right, dealt with all the special cases, which are implemented as non-
1992 pointers, so there is a pointer to a real warnings mask. */
1994 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1996 } while (w >>= WARNshift);
2001 /* Set buffer=NULL to get a new one. */
2003 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
2005 const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
2006 PERL_UNUSED_CONTEXT;
2007 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
2010 (specialWARN(buffer) ?
2011 PerlMemShared_malloc(len_wanted) :
2012 PerlMemShared_realloc(buffer, len_wanted));
2014 Copy(bits, (buffer + 1), size, char);
2018 /* since we've already done strlen() for both nam and val
2019 * we can use that info to make things faster than
2020 * sprintf(s, "%s=%s", nam, val)
2022 #define my_setenv_format(s, nam, nlen, val, vlen) \
2023 Copy(nam, s, nlen, char); \
2025 Copy(val, s+(nlen+1), vlen, char); \
2026 *(s+(nlen+1+vlen)) = '\0'
2028 #ifdef USE_ENVIRON_ARRAY
2029 /* VMS' my_setenv() is in vms.c */
2030 #if !defined(WIN32) && !defined(NETWARE)
2032 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2036 /* only parent thread can modify process environment */
2037 if (PL_curinterp == aTHX)
2040 #ifndef PERL_USE_SAFE_PUTENV
2041 if (!PL_use_safe_putenv) {
2042 /* most putenv()s leak, so we manipulate environ directly */
2044 register const I32 len = strlen(nam);
2047 /* where does it go? */
2048 for (i = 0; environ[i]; i++) {
2049 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
2053 if (environ == PL_origenviron) { /* need we copy environment? */
2059 while (environ[max])
2061 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2062 for (j=0; j<max; j++) { /* copy environment */
2063 const int len = strlen(environ[j]);
2064 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2065 Copy(environ[j], tmpenv[j], len+1, char);
2068 environ = tmpenv; /* tell exec where it is now */
2071 safesysfree(environ[i]);
2072 while (environ[i]) {
2073 environ[i] = environ[i+1];
2078 if (!environ[i]) { /* does not exist yet */
2079 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2080 environ[i+1] = NULL; /* make sure it's null terminated */
2083 safesysfree(environ[i]);
2087 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2088 /* all that work just for this */
2089 my_setenv_format(environ[i], nam, nlen, val, vlen);
2092 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
2093 # if defined(HAS_UNSETENV)
2095 (void)unsetenv(nam);
2097 (void)setenv(nam, val, 1);
2099 # else /* ! HAS_UNSETENV */
2100 (void)setenv(nam, val, 1);
2101 # endif /* HAS_UNSETENV */
2103 # if defined(HAS_UNSETENV)
2105 (void)unsetenv(nam);
2107 const int nlen = strlen(nam);
2108 const int vlen = strlen(val);
2109 char * const new_env =
2110 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2111 my_setenv_format(new_env, nam, nlen, val, vlen);
2112 (void)putenv(new_env);
2114 # else /* ! HAS_UNSETENV */
2116 const int nlen = strlen(nam);
2122 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2123 /* all that work just for this */
2124 my_setenv_format(new_env, nam, nlen, val, vlen);
2125 (void)putenv(new_env);
2126 # endif /* HAS_UNSETENV */
2127 # endif /* __CYGWIN__ */
2128 #ifndef PERL_USE_SAFE_PUTENV
2134 #else /* WIN32 || NETWARE */
2137 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2140 register char *envstr;
2141 const int nlen = strlen(nam);
2148 Newx(envstr, nlen+vlen+2, char);
2149 my_setenv_format(envstr, nam, nlen, val, vlen);
2150 (void)PerlEnv_putenv(envstr);
2154 #endif /* WIN32 || NETWARE */
2156 #endif /* !VMS && !EPOC*/
2158 #ifdef UNLINK_ALL_VERSIONS
2160 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2164 PERL_ARGS_ASSERT_UNLNK;
2166 while (PerlLIO_unlink(f) >= 0)
2168 return retries ? 0 : -1;
2172 /* this is a drop-in replacement for bcopy() */
2173 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2175 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
2177 char * const retval = to;
2179 PERL_ARGS_ASSERT_MY_BCOPY;
2181 if (from - to >= 0) {
2189 *(--to) = *(--from);
2195 /* this is a drop-in replacement for memset() */
2198 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
2200 char * const retval = loc;
2202 PERL_ARGS_ASSERT_MY_MEMSET;
2210 /* this is a drop-in replacement for bzero() */
2211 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2213 Perl_my_bzero(register char *loc, register I32 len)
2215 char * const retval = loc;
2217 PERL_ARGS_ASSERT_MY_BZERO;
2225 /* this is a drop-in replacement for memcmp() */
2226 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2228 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
2230 register const U8 *a = (const U8 *)s1;
2231 register const U8 *b = (const U8 *)s2;
2234 PERL_ARGS_ASSERT_MY_MEMCMP;
2237 if ((tmp = *a++ - *b++))
2242 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2245 /* This vsprintf replacement should generally never get used, since
2246 vsprintf was available in both System V and BSD 2.11. (There may
2247 be some cross-compilation or embedded set-ups where it is needed,
2250 If you encounter a problem in this function, it's probably a symptom
2251 that Configure failed to detect your system's vprintf() function.
2252 See the section on "item vsprintf" in the INSTALL file.
2254 This version may compile on systems with BSD-ish <stdio.h>,
2255 but probably won't on others.
2258 #ifdef USE_CHAR_VSPRINTF
2263 vsprintf(char *dest, const char *pat, void *args)
2267 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2268 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2269 FILE_cnt(&fakebuf) = 32767;
2271 /* These probably won't compile -- If you really need
2272 this, you'll have to figure out some other method. */
2273 fakebuf._ptr = dest;
2274 fakebuf._cnt = 32767;
2279 fakebuf._flag = _IOWRT|_IOSTRG;
2280 _doprnt(pat, args, &fakebuf); /* what a kludge */
2281 #if defined(STDIO_PTR_LVALUE)
2282 *(FILE_ptr(&fakebuf)++) = '\0';
2284 /* PerlIO has probably #defined away fputc, but we want it here. */
2286 # undef fputc /* XXX Should really restore it later */
2288 (void)fputc('\0', &fakebuf);
2290 #ifdef USE_CHAR_VSPRINTF
2293 return 0; /* perl doesn't use return value */
2297 #endif /* HAS_VPRINTF */
2300 #if BYTEORDER != 0x4321
2302 Perl_my_swap(pTHX_ short s)
2304 #if (BYTEORDER & 1) == 0
2307 result = ((s & 255) << 8) + ((s >> 8) & 255);
2315 Perl_my_htonl(pTHX_ long l)
2319 char c[sizeof(long)];
2322 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2323 #if BYTEORDER == 0x12345678
2326 u.c[0] = (l >> 24) & 255;
2327 u.c[1] = (l >> 16) & 255;
2328 u.c[2] = (l >> 8) & 255;
2332 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2333 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2338 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2339 u.c[o & 0xf] = (l >> s) & 255;
2347 Perl_my_ntohl(pTHX_ long l)
2351 char c[sizeof(long)];
2354 #if BYTEORDER == 0x1234
2355 u.c[0] = (l >> 24) & 255;
2356 u.c[1] = (l >> 16) & 255;
2357 u.c[2] = (l >> 8) & 255;
2361 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
2362 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
2369 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2370 l |= (u.c[o & 0xf] & 255) << s;
2377 #endif /* BYTEORDER != 0x4321 */
2381 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2382 * If these functions are defined,
2383 * the BYTEORDER is neither 0x1234 nor 0x4321.
2384 * However, this is not assumed.
2388 #define HTOLE(name,type) \
2390 name (register type n) \
2394 char c[sizeof(type)]; \
2397 register U32 s = 0; \
2398 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2399 u.c[i] = (n >> s) & 0xFF; \
2404 #define LETOH(name,type) \
2406 name (register type n) \
2410 char c[sizeof(type)]; \
2413 register U32 s = 0; \
2416 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2417 n |= ((type)(u.c[i] & 0xFF)) << s; \
2423 * Big-endian byte order functions.
2426 #define HTOBE(name,type) \
2428 name (register type n) \
2432 char c[sizeof(type)]; \
2435 register U32 s = 8*(sizeof(u.c)-1); \
2436 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2437 u.c[i] = (n >> s) & 0xFF; \
2442 #define BETOH(name,type) \
2444 name (register type n) \
2448 char c[sizeof(type)]; \
2451 register U32 s = 8*(sizeof(u.c)-1); \
2454 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2455 n |= ((type)(u.c[i] & 0xFF)) << s; \
2461 * If we just can't do it...
2464 #define NOT_AVAIL(name,type) \
2466 name (register type n) \
2468 Perl_croak_nocontext(#name "() not available"); \
2469 return n; /* not reached */ \
2473 #if defined(HAS_HTOVS) && !defined(htovs)
2476 #if defined(HAS_HTOVL) && !defined(htovl)
2479 #if defined(HAS_VTOHS) && !defined(vtohs)
2482 #if defined(HAS_VTOHL) && !defined(vtohl)
2486 #ifdef PERL_NEED_MY_HTOLE16
2488 HTOLE(Perl_my_htole16,U16)
2490 NOT_AVAIL(Perl_my_htole16,U16)
2493 #ifdef PERL_NEED_MY_LETOH16
2495 LETOH(Perl_my_letoh16,U16)
2497 NOT_AVAIL(Perl_my_letoh16,U16)
2500 #ifdef PERL_NEED_MY_HTOBE16
2502 HTOBE(Perl_my_htobe16,U16)
2504 NOT_AVAIL(Perl_my_htobe16,U16)
2507 #ifdef PERL_NEED_MY_BETOH16
2509 BETOH(Perl_my_betoh16,U16)
2511 NOT_AVAIL(Perl_my_betoh16,U16)
2515 #ifdef PERL_NEED_MY_HTOLE32
2517 HTOLE(Perl_my_htole32,U32)
2519 NOT_AVAIL(Perl_my_htole32,U32)
2522 #ifdef PERL_NEED_MY_LETOH32
2524 LETOH(Perl_my_letoh32,U32)
2526 NOT_AVAIL(Perl_my_letoh32,U32)
2529 #ifdef PERL_NEED_MY_HTOBE32
2531 HTOBE(Perl_my_htobe32,U32)
2533 NOT_AVAIL(Perl_my_htobe32,U32)
2536 #ifdef PERL_NEED_MY_BETOH32
2538 BETOH(Perl_my_betoh32,U32)
2540 NOT_AVAIL(Perl_my_betoh32,U32)
2544 #ifdef PERL_NEED_MY_HTOLE64
2546 HTOLE(Perl_my_htole64,U64)
2548 NOT_AVAIL(Perl_my_htole64,U64)
2551 #ifdef PERL_NEED_MY_LETOH64
2553 LETOH(Perl_my_letoh64,U64)
2555 NOT_AVAIL(Perl_my_letoh64,U64)
2558 #ifdef PERL_NEED_MY_HTOBE64
2560 HTOBE(Perl_my_htobe64,U64)
2562 NOT_AVAIL(Perl_my_htobe64,U64)
2565 #ifdef PERL_NEED_MY_BETOH64
2567 BETOH(Perl_my_betoh64,U64)
2569 NOT_AVAIL(Perl_my_betoh64,U64)
2573 #ifdef PERL_NEED_MY_HTOLES
2574 HTOLE(Perl_my_htoles,short)
2576 #ifdef PERL_NEED_MY_LETOHS
2577 LETOH(Perl_my_letohs,short)
2579 #ifdef PERL_NEED_MY_HTOBES
2580 HTOBE(Perl_my_htobes,short)
2582 #ifdef PERL_NEED_MY_BETOHS
2583 BETOH(Perl_my_betohs,short)
2586 #ifdef PERL_NEED_MY_HTOLEI
2587 HTOLE(Perl_my_htolei,int)
2589 #ifdef PERL_NEED_MY_LETOHI
2590 LETOH(Perl_my_letohi,int)
2592 #ifdef PERL_NEED_MY_HTOBEI
2593 HTOBE(Perl_my_htobei,int)
2595 #ifdef PERL_NEED_MY_BETOHI
2596 BETOH(Perl_my_betohi,int)
2599 #ifdef PERL_NEED_MY_HTOLEL
2600 HTOLE(Perl_my_htolel,long)
2602 #ifdef PERL_NEED_MY_LETOHL
2603 LETOH(Perl_my_letohl,long)
2605 #ifdef PERL_NEED_MY_HTOBEL
2606 HTOBE(Perl_my_htobel,long)
2608 #ifdef PERL_NEED_MY_BETOHL
2609 BETOH(Perl_my_betohl,long)
2613 Perl_my_swabn(void *ptr, int n)
2615 register char *s = (char *)ptr;
2616 register char *e = s + (n-1);
2619 PERL_ARGS_ASSERT_MY_SWABN;
2621 for (n /= 2; n > 0; s++, e--, n--) {
2629 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2631 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2634 register I32 This, that;
2640 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2642 PERL_FLUSHALL_FOR_CHILD;
2643 This = (*mode == 'w');
2647 taint_proper("Insecure %s%s", "EXEC");
2649 if (PerlProc_pipe(p) < 0)
2651 /* Try for another pipe pair for error return */
2652 if (PerlProc_pipe(pp) >= 0)
2654 while ((pid = PerlProc_fork()) < 0) {
2655 if (errno != EAGAIN) {
2656 PerlLIO_close(p[This]);
2657 PerlLIO_close(p[that]);
2659 PerlLIO_close(pp[0]);
2660 PerlLIO_close(pp[1]);
2664 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2673 /* Close parent's end of error status pipe (if any) */
2675 PerlLIO_close(pp[0]);
2676 #if defined(HAS_FCNTL) && defined(F_SETFD)
2677 /* Close error pipe automatically if exec works */
2678 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2681 /* Now dup our end of _the_ pipe to right position */
2682 if (p[THIS] != (*mode == 'r')) {
2683 PerlLIO_dup2(p[THIS], *mode == 'r');
2684 PerlLIO_close(p[THIS]);
2685 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2686 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2689 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2690 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2691 /* No automatic close - do it by hand */
2698 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2704 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2710 do_execfree(); /* free any memory malloced by child on fork */
2712 PerlLIO_close(pp[1]);
2713 /* Keep the lower of the two fd numbers */
2714 if (p[that] < p[This]) {
2715 PerlLIO_dup2(p[This], p[that]);
2716 PerlLIO_close(p[This]);
2720 PerlLIO_close(p[that]); /* close child's end of pipe */
2722 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2723 SvUPGRADE(sv,SVt_IV);
2725 PL_forkprocess = pid;
2726 /* If we managed to get status pipe check for exec fail */
2727 if (did_pipes && pid > 0) {
2732 while (n < sizeof(int)) {
2733 n1 = PerlLIO_read(pp[0],
2734 (void*)(((char*)&errkid)+n),
2740 PerlLIO_close(pp[0]);
2742 if (n) { /* Error */
2744 PerlLIO_close(p[This]);
2745 if (n != sizeof(int))
2746 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2748 pid2 = wait4pid(pid, &status, 0);
2749 } while (pid2 == -1 && errno == EINTR);
2750 errno = errkid; /* Propagate errno from kid */
2755 PerlLIO_close(pp[0]);
2756 return PerlIO_fdopen(p[This], mode);
2758 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2759 return my_syspopen4(aTHX_ NULL, mode, n, args);
2761 Perl_croak(aTHX_ "List form of piped open not implemented");
2762 return (PerlIO *) NULL;
2767 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2768 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
2770 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2774 register I32 This, that;
2777 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2781 PERL_ARGS_ASSERT_MY_POPEN;
2783 PERL_FLUSHALL_FOR_CHILD;
2786 return my_syspopen(aTHX_ cmd,mode);
2789 This = (*mode == 'w');
2791 if (doexec && PL_tainting) {
2793 taint_proper("Insecure %s%s", "EXEC");
2795 if (PerlProc_pipe(p) < 0)
2797 if (doexec && PerlProc_pipe(pp) >= 0)
2799 while ((pid = PerlProc_fork()) < 0) {
2800 if (errno != EAGAIN) {
2801 PerlLIO_close(p[This]);
2802 PerlLIO_close(p[that]);
2804 PerlLIO_close(pp[0]);
2805 PerlLIO_close(pp[1]);
2808 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2811 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2821 PerlLIO_close(pp[0]);
2822 #if defined(HAS_FCNTL) && defined(F_SETFD)
2823 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2826 if (p[THIS] != (*mode == 'r')) {
2827 PerlLIO_dup2(p[THIS], *mode == 'r');
2828 PerlLIO_close(p[THIS]);
2829 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2830 PerlLIO_close(p[THAT]);
2833 PerlLIO_close(p[THAT]);
2836 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2843 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2848 /* may or may not use the shell */
2849 do_exec3(cmd, pp[1], did_pipes);
2852 #endif /* defined OS2 */
2854 #ifdef PERLIO_USING_CRLF
2855 /* Since we circumvent IO layers when we manipulate low-level
2856 filedescriptors directly, need to manually switch to the
2857 default, binary, low-level mode; see PerlIOBuf_open(). */
2858 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2860 #ifdef THREADS_HAVE_PIDS
2861 PL_ppid = (IV)getppid();
2864 #ifdef PERL_USES_PL_PIDSTATUS
2865 hv_clear(PL_pidstatus); /* we have no children */
2871 do_execfree(); /* free any memory malloced by child on vfork */
2873 PerlLIO_close(pp[1]);
2874 if (p[that] < p[This]) {
2875 PerlLIO_dup2(p[This], p[that]);
2876 PerlLIO_close(p[This]);
2880 PerlLIO_close(p[that]);
2882 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2883 SvUPGRADE(sv,SVt_IV);
2885 PL_forkprocess = pid;
2886 if (did_pipes && pid > 0) {
2891 while (n < sizeof(int)) {
2892 n1 = PerlLIO_read(pp[0],
2893 (void*)(((char*)&errkid)+n),
2899 PerlLIO_close(pp[0]);
2901 if (n) { /* Error */
2903 PerlLIO_close(p[This]);
2904 if (n != sizeof(int))
2905 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2907 pid2 = wait4pid(pid, &status, 0);
2908 } while (pid2 == -1 && errno == EINTR);
2909 errno = errkid; /* Propagate errno from kid */
2914 PerlLIO_close(pp[0]);
2915 return PerlIO_fdopen(p[This], mode);
2918 #if defined(atarist) || defined(EPOC)
2921 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2923 PERL_ARGS_ASSERT_MY_POPEN;
2924 PERL_FLUSHALL_FOR_CHILD;
2925 /* Call system's popen() to get a FILE *, then import it.
2926 used 0 for 2nd parameter to PerlIO_importFILE;
2929 return PerlIO_importFILE(popen(cmd, mode), 0);
2933 FILE *djgpp_popen();
2935 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2937 PERL_FLUSHALL_FOR_CHILD;
2938 /* Call system's popen() to get a FILE *, then import it.
2939 used 0 for 2nd parameter to PerlIO_importFILE;
2942 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2945 #if defined(__LIBCATAMOUNT__)
2947 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2955 #endif /* !DOSISH */
2957 /* this is called in parent before the fork() */
2959 Perl_atfork_lock(void)
2962 #if defined(USE_ITHREADS)
2963 /* locks must be held in locking order (if any) */
2965 MUTEX_LOCK(&PL_malloc_mutex);
2971 /* this is called in both parent and child after the fork() */
2973 Perl_atfork_unlock(void)
2976 #if defined(USE_ITHREADS)
2977 /* locks must be released in same order as in atfork_lock() */
2979 MUTEX_UNLOCK(&PL_malloc_mutex);
2988 #if defined(HAS_FORK)
2990 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2995 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2996 * handlers elsewhere in the code */
3001 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
3002 Perl_croak_nocontext("fork() not available");
3004 #endif /* HAS_FORK */
3009 Perl_dump_fds(pTHX_ const char *const s)
3014 PERL_ARGS_ASSERT_DUMP_FDS;
3016 PerlIO_printf(Perl_debug_log,"%s", s);
3017 for (fd = 0; fd < 32; fd++) {
3018 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
3019 PerlIO_printf(Perl_debug_log," %d",fd);
3021 PerlIO_printf(Perl_debug_log,"\n");
3024 #endif /* DUMP_FDS */
3028 dup2(int oldfd, int newfd)
3030 #if defined(HAS_FCNTL) && defined(F_DUPFD)
3033 PerlLIO_close(newfd);
3034 return fcntl(oldfd, F_DUPFD, newfd);
3036 #define DUP2_MAX_FDS 256
3037 int fdtmp[DUP2_MAX_FDS];
3043 PerlLIO_close(newfd);
3044 /* good enough for low fd's... */
3045 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
3046 if (fdx >= DUP2_MAX_FDS) {
3054 PerlLIO_close(fdtmp[--fdx]);
3061 #ifdef HAS_SIGACTION
3064 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3067 struct sigaction act, oact;
3070 /* only "parent" interpreter can diddle signals */
3071 if (PL_curinterp != aTHX)
3072 return (Sighandler_t) SIG_ERR;
3075 act.sa_handler = (void(*)(int))handler;
3076 sigemptyset(&act.sa_mask);
3079 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3080 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
3082 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3083 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3084 act.sa_flags |= SA_NOCLDWAIT;
3086 if (sigaction(signo, &act, &oact) == -1)
3087 return (Sighandler_t) SIG_ERR;
3089 return (Sighandler_t) oact.sa_handler;
3093 Perl_rsignal_state(pTHX_ int signo)
3095 struct sigaction oact;
3096 PERL_UNUSED_CONTEXT;
3098 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
3099 return (Sighandler_t) SIG_ERR;
3101 return (Sighandler_t) oact.sa_handler;
3105 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3108 struct sigaction act;
3110 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
3113 /* only "parent" interpreter can diddle signals */
3114 if (PL_curinterp != aTHX)
3118 act.sa_handler = (void(*)(int))handler;
3119 sigemptyset(&act.sa_mask);
3122 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3123 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
3125 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
3126 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
3127 act.sa_flags |= SA_NOCLDWAIT;
3129 return sigaction(signo, &act, save);
3133 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3137 /* only "parent" interpreter can diddle signals */
3138 if (PL_curinterp != aTHX)
3142 return sigaction(signo, save, (struct sigaction *)NULL);
3145 #else /* !HAS_SIGACTION */
3148 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
3150 #if defined(USE_ITHREADS) && !defined(WIN32)
3151 /* only "parent" interpreter can diddle signals */
3152 if (PL_curinterp != aTHX)
3153 return (Sighandler_t) SIG_ERR;
3156 return PerlProc_signal(signo, handler);
3167 Perl_rsignal_state(pTHX_ int signo)
3170 Sighandler_t oldsig;
3172 #if defined(USE_ITHREADS) && !defined(WIN32)
3173 /* only "parent" interpreter can diddle signals */
3174 if (PL_curinterp != aTHX)
3175 return (Sighandler_t) SIG_ERR;
3179 oldsig = PerlProc_signal(signo, sig_trap);
3180 PerlProc_signal(signo, oldsig);
3182 PerlProc_kill(PerlProc_getpid(), signo);
3187 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
3189 #if defined(USE_ITHREADS) && !defined(WIN32)
3190 /* only "parent" interpreter can diddle signals */
3191 if (PL_curinterp != aTHX)
3194 *save = PerlProc_signal(signo, handler);
3195 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
3199 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
3201 #if defined(USE_ITHREADS) && !defined(WIN32)
3202 /* only "parent" interpreter can diddle signals */
3203 if (PL_curinterp != aTHX)
3206 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
3209 #endif /* !HAS_SIGACTION */
3210 #endif /* !PERL_MICRO */
3212 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
3213 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
3215 Perl_my_pclose(pTHX_ PerlIO *ptr)
3218 Sigsave_t hstat, istat, qstat;
3225 const int fd = PerlIO_fileno(ptr);
3228 /* Find out whether the refcount is low enough for us to wait for the
3229 child proc without blocking. */
3230 const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
3232 const bool should_wait = 1;
3235 svp = av_fetch(PL_fdpid,fd,TRUE);
3236 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3238 *svp = &PL_sv_undef;
3240 if (pid == -1) { /* Opened by popen. */
3241 return my_syspclose(ptr);
3244 close_failed = (PerlIO_close(ptr) == EOF);
3247 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
3250 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3251 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3252 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
3254 if (should_wait) do {
3255 pid2 = wait4pid(pid, &status, 0);
3256 } while (pid2 == -1 && errno == EINTR);
3258 rsignal_restore(SIGHUP, &hstat);
3259 rsignal_restore(SIGINT, &istat);
3260 rsignal_restore(SIGQUIT, &qstat);
3268 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3273 #if defined(__LIBCATAMOUNT__)
3275 Perl_my_pclose(pTHX_ PerlIO *ptr)
3280 #endif /* !DOSISH */
3282 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3284 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3288 PERL_ARGS_ASSERT_WAIT4PID;
3291 #ifdef PERL_USES_PL_PIDSTATUS
3294 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3295 pid, rather than a string form. */
3296 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3297 if (svp && *svp != &PL_sv_undef) {
3298 *statusp = SvIVX(*svp);
3299 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3307 hv_iterinit(PL_pidstatus);
3308 if ((entry = hv_iternext(PL_pidstatus))) {
3309 SV * const sv = hv_iterval(PL_pidstatus,entry);
3311 const char * const spid = hv_iterkey(entry,&len);
3313 assert (len == sizeof(Pid_t));
3314 memcpy((char *)&pid, spid, len);
3315 *statusp = SvIVX(sv);
3316 /* The hash iterator is currently on this entry, so simply
3317 calling hv_delete would trigger the lazy delete, which on
3318 aggregate does more work, beacuse next call to hv_iterinit()
3319 would spot the flag, and have to call the delete routine,
3320 while in the meantime any new entries can't re-use that
3322 hv_iterinit(PL_pidstatus);
3323 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3330 # ifdef HAS_WAITPID_RUNTIME
3331 if (!HAS_WAITPID_RUNTIME)
3334 result = PerlProc_waitpid(pid,statusp,flags);
3337 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3338 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
3341 #ifdef PERL_USES_PL_PIDSTATUS
3342 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3347 Perl_croak(aTHX_ "Can't do waitpid with flags");
3349 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3350 pidgone(result,*statusp);
3356 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3359 if (result < 0 && errno == EINTR) {
3361 errno = EINTR; /* reset in case a signal handler changed $! */
3365 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3367 #ifdef PERL_USES_PL_PIDSTATUS
3369 S_pidgone(pTHX_ Pid_t pid, int status)
3373 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3374 SvUPGRADE(sv,SVt_IV);
3375 SvIV_set(sv, status);
3380 #if defined(atarist) || defined(OS2) || defined(EPOC)
3383 int /* Cannot prototype with I32
3385 my_syspclose(PerlIO *ptr)
3388 Perl_my_pclose(pTHX_ PerlIO *ptr)
3391 /* Needs work for PerlIO ! */
3392 FILE * const f = PerlIO_findFILE(ptr);
3393 const I32 result = pclose(f);
3394 PerlIO_releaseFILE(ptr,f);
3402 Perl_my_pclose(pTHX_ PerlIO *ptr)
3404 /* Needs work for PerlIO ! */
3405 FILE * const f = PerlIO_findFILE(ptr);
3406 I32 result = djgpp_pclose(f);
3407 result = (result << 8) & 0xff00;
3408 PerlIO_releaseFILE(ptr,f);
3413 #define PERL_REPEATCPY_LINEAR 4
3415 Perl_repeatcpy(register char *to, register const char *from, I32 len, register IV count)
3417 PERL_ARGS_ASSERT_REPEATCPY;
3420 memset(to, *from, count);
3422 register char *p = to;
3423 IV items, linear, half;
3425 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3426 for (items = 0; items < linear; ++items) {
3427 register const char *q = from;
3429 for (todo = len; todo > 0; todo--)
3434 while (items <= half) {
3435 IV size = items * len;
3436 memcpy(p, to, size);
3442 memcpy(p, to, (count - items) * len);
3448 Perl_same_dirent(pTHX_ const char *a, const char *b)
3450 char *fa = strrchr(a,'/');
3451 char *fb = strrchr(b,'/');
3454 SV * const tmpsv = sv_newmortal();
3456 PERL_ARGS_ASSERT_SAME_DIRENT;
3469 sv_setpvs(tmpsv, ".");
3471 sv_setpvn(tmpsv, a, fa - a);
3472 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3475 sv_setpvs(tmpsv, ".");
3477 sv_setpvn(tmpsv, b, fb - b);
3478 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3480 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3481 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3483 #endif /* !HAS_RENAME */
3486 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3487 const char *const *const search_ext, I32 flags)
3490 const char *xfound = NULL;
3491 char *xfailed = NULL;
3492 char tmpbuf[MAXPATHLEN];
3497 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3498 # define SEARCH_EXTS ".bat", ".cmd", NULL
3499 # define MAX_EXT_LEN 4
3502 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3503 # define MAX_EXT_LEN 4
3506 # define SEARCH_EXTS ".pl", ".com", NULL
3507 # define MAX_EXT_LEN 4
3509 /* additional extensions to try in each dir if scriptname not found */
3511 static const char *const exts[] = { SEARCH_EXTS };
3512 const char *const *const ext = search_ext ? search_ext : exts;
3513 int extidx = 0, i = 0;
3514 const char *curext = NULL;
3516 PERL_UNUSED_ARG(search_ext);
3517 # define MAX_EXT_LEN 0
3520 PERL_ARGS_ASSERT_FIND_SCRIPT;
3523 * If dosearch is true and if scriptname does not contain path
3524 * delimiters, search the PATH for scriptname.
3526 * If SEARCH_EXTS is also defined, will look for each
3527 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3528 * while searching the PATH.
3530 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3531 * proceeds as follows:
3532 * If DOSISH or VMSISH:
3533 * + look for ./scriptname{,.foo,.bar}
3534 * + search the PATH for scriptname{,.foo,.bar}
3537 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3538 * this will not look in '.' if it's not in the PATH)
3543 # ifdef ALWAYS_DEFTYPES
3544 len = strlen(scriptname);
3545 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3546 int idx = 0, deftypes = 1;
3549 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3552 int idx = 0, deftypes = 1;
3555 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3557 /* The first time through, just add SEARCH_EXTS to whatever we
3558 * already have, so we can check for default file types. */
3560 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3566 if ((strlen(tmpbuf) + strlen(scriptname)
3567 + MAX_EXT_LEN) >= sizeof tmpbuf)
3568 continue; /* don't search dir with too-long name */
3569 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3573 if (strEQ(scriptname, "-"))
3575 if (dosearch) { /* Look in '.' first. */
3576 const char *cur = scriptname;
3578 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3580 if (strEQ(ext[i++],curext)) {
3581 extidx = -1; /* already has an ext */
3586 DEBUG_p(PerlIO_printf(Perl_debug_log,
3587 "Looking for %s\n",cur));
3588 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3589 && !S_ISDIR(PL_statbuf.st_mode)) {
3597 if (cur == scriptname) {
3598 len = strlen(scriptname);
3599 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3601 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3604 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3605 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3610 if (dosearch && !strchr(scriptname, '/')
3612 && !strchr(scriptname, '\\')
3614 && (s = PerlEnv_getenv("PATH")))
3618 bufend = s + strlen(s);
3619 while (s < bufend) {
3620 #if defined(atarist) || defined(DOSISH)
3625 && *s != ';'; len++, s++) {
3626 if (len < sizeof tmpbuf)
3629 if (len < sizeof tmpbuf)
3631 #else /* ! (atarist || DOSISH) */
3632 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3635 #endif /* ! (atarist || DOSISH) */
3638 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3639 continue; /* don't search dir with too-long name */
3641 # if defined(atarist) || defined(DOSISH)
3642 && tmpbuf[len - 1] != '/'
3643 && tmpbuf[len - 1] != '\\'
3646 tmpbuf[len++] = '/';
3647 if (len == 2 && tmpbuf[0] == '.')
3649 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3653 len = strlen(tmpbuf);
3654 if (extidx > 0) /* reset after previous loop */
3658 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3659 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3660 if (S_ISDIR(PL_statbuf.st_mode)) {
3664 } while ( retval < 0 /* not there */
3665 && extidx>=0 && ext[extidx] /* try an extension? */
3666 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3671 if (S_ISREG(PL_statbuf.st_mode)
3672 && cando(S_IRUSR,TRUE,&PL_statbuf)
3673 #if !defined(DOSISH)
3674 && cando(S_IXUSR,TRUE,&PL_statbuf)
3678 xfound = tmpbuf; /* bingo! */
3682 xfailed = savepv(tmpbuf);
3685 if (!xfound && !seen_dot && !xfailed &&
3686 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3687 || S_ISDIR(PL_statbuf.st_mode)))
3689 seen_dot = 1; /* Disable message. */
3691 if (flags & 1) { /* do or die? */
3692 /* diag_listed_as: Can't execute %s */
3693 Perl_croak(aTHX_ "Can't %s %s%s%s",
3694 (xfailed ? "execute" : "find"),
3695 (xfailed ? xfailed : scriptname),
3696 (xfailed ? "" : " on PATH"),
3697 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3702 scriptname = xfound;
3704 return (scriptname ? savepv(scriptname) : NULL);
3707 #ifndef PERL_GET_CONTEXT_DEFINED
3710 Perl_get_context(void)
3713 #if defined(USE_ITHREADS)
3714 # ifdef OLD_PTHREADS_API
3716 int error = pthread_getspecific(PL_thr_key, &t)
3718 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3721 # ifdef I_MACH_CTHREADS
3722 return (void*)cthread_data(cthread_self());
3724 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3733 Perl_set_context(void *t)
3736 PERL_ARGS_ASSERT_SET_CONTEXT;
3737 #if defined(USE_ITHREADS)
3738 # ifdef I_MACH_CTHREADS
3739 cthread_set_data(cthread_self(), t);
3742 const int error = pthread_setspecific(PL_thr_key, t);
3744 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3752 #endif /* !PERL_GET_CONTEXT_DEFINED */
3754 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3763 Perl_get_op_names(pTHX)
3765 PERL_UNUSED_CONTEXT;
3766 return (char **)PL_op_name;
3770 Perl_get_op_descs(pTHX)
3772 PERL_UNUSED_CONTEXT;
3773 return (char **)PL_op_desc;
3777 Perl_get_no_modify(pTHX)
3779 PERL_UNUSED_CONTEXT;
3780 return PL_no_modify;
3784 Perl_get_opargs(pTHX)
3786 PERL_UNUSED_CONTEXT;
3787 return (U32 *)PL_opargs;
3791 Perl_get_ppaddr(pTHX)
3794 PERL_UNUSED_CONTEXT;
3795 return (PPADDR_t*)PL_ppaddr;
3798 #ifndef HAS_GETENV_LEN
3800 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3802 char * const env_trans = PerlEnv_getenv(env_elem);
3803 PERL_UNUSED_CONTEXT;
3804 PERL_ARGS_ASSERT_GETENV_LEN;
3806 *len = strlen(env_trans);
3813 Perl_get_vtbl(pTHX_ int vtbl_id)
3815 PERL_UNUSED_CONTEXT;
3817 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3818 ? NULL : PL_magic_vtables + vtbl_id;
3822 Perl_my_fflush_all(pTHX)
3824 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3825 return PerlIO_flush(NULL);
3827 # if defined(HAS__FWALK)
3828 extern int fflush(FILE *);
3829 /* undocumented, unprototyped, but very useful BSDism */
3830 extern void _fwalk(int (*)(FILE *));
3834 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3836 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3837 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3839 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3840 open_max = sysconf(_SC_OPEN_MAX);
3843 open_max = FOPEN_MAX;
3846 open_max = OPEN_MAX;
3857 for (i = 0; i < open_max; i++)
3858 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3859 STDIO_STREAM_ARRAY[i]._file < open_max &&
3860 STDIO_STREAM_ARRAY[i]._flag)
3861 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3865 SETERRNO(EBADF,RMS_IFI);
3872 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3874 if (ckWARN(WARN_IO)) {
3876 = gv && (isGV(gv) || isGV_with_GP(gv))
3877 ? sv_2mortal(newSVhek(GvENAME_HEK((gv))))
3879 const char * const direction = have == '>' ? "out" : "in";
3881 if (name && SvPOK(name) && *SvPV_nolen(name))
3882 Perl_warner(aTHX_ packWARN(WARN_IO),
3883 "Filehandle %"SVf" opened only for %sput",
3886 Perl_warner(aTHX_ packWARN(WARN_IO),
3887 "Filehandle opened only for %sput", direction);
3892 Perl_report_evil_fh(pTHX_ const GV *gv)
3894 const IO *io = gv ? GvIO(gv) : NULL;
3895 const PERL_BITFIELD16 op = PL_op->op_type;
3899 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3901 warn_type = WARN_CLOSED;
3905 warn_type = WARN_UNOPENED;
3908 if (ckWARN(warn_type)) {
3910 = gv && (isGV(gv) || isGV_with_GP(gv)) && GvENAMELEN(gv) ?
3911 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3912 const char * const pars =
3913 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3914 const char * const func =
3916 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3917 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3919 const char * const type =
3921 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3922 ? "socket" : "filehandle");
3923 const bool have_name = name && SvPOK(name) && *SvPV_nolen(name);
3924 Perl_warner(aTHX_ packWARN(warn_type),
3925 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3926 have_name ? " " : "",
3927 SVfARG(have_name ? name : &PL_sv_no));
3928 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3930 aTHX_ packWARN(warn_type),
3931 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3932 func, pars, have_name ? " " : "",
3933 SVfARG(have_name ? name : &PL_sv_no)
3938 /* To workaround core dumps from the uninitialised tm_zone we get the
3939 * system to give us a reasonable struct to copy. This fix means that
3940 * strftime uses the tm_zone and tm_gmtoff values returned by
3941 * localtime(time()). That should give the desired result most of the
3942 * time. But probably not always!
3944 * This does not address tzname aspects of NETaa14816.
3949 # ifndef STRUCT_TM_HASZONE
3950 # define STRUCT_TM_HASZONE
3954 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3955 # ifndef HAS_TM_TM_ZONE
3956 # define HAS_TM_TM_ZONE
3961 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3963 #ifdef HAS_TM_TM_ZONE
3965 const struct tm* my_tm;
3966 PERL_ARGS_ASSERT_INIT_TM;
3968 my_tm = localtime(&now);
3970 Copy(my_tm, ptm, 1, struct tm);
3972 PERL_ARGS_ASSERT_INIT_TM;
3973 PERL_UNUSED_ARG(ptm);
3978 * mini_mktime - normalise struct tm values without the localtime()
3979 * semantics (and overhead) of mktime().
3982 Perl_mini_mktime(pTHX_ struct tm *ptm)
3986 int month, mday, year, jday;
3987 int odd_cent, odd_year;
3988 PERL_UNUSED_CONTEXT;
3990 PERL_ARGS_ASSERT_MINI_MKTIME;
3992 #define DAYS_PER_YEAR 365
3993 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3994 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3995 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3996 #define SECS_PER_HOUR (60*60)
3997 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3998 /* parentheses deliberately absent on these two, otherwise they don't work */
3999 #define MONTH_TO_DAYS 153/5
4000 #define DAYS_TO_MONTH 5/153
4001 /* offset to bias by March (month 4) 1st between month/mday & year finding */
4002 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
4003 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
4004 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
4007 * Year/day algorithm notes:
4009 * With a suitable offset for numeric value of the month, one can find
4010 * an offset into the year by considering months to have 30.6 (153/5) days,
4011 * using integer arithmetic (i.e., with truncation). To avoid too much
4012 * messing about with leap days, we consider January and February to be
4013 * the 13th and 14th month of the previous year. After that transformation,
4014 * we need the month index we use to be high by 1 from 'normal human' usage,
4015 * so the month index values we use run from 4 through 15.
4017 * Given that, and the rules for the Gregorian calendar (leap years are those
4018 * divisible by 4 unless also divisible by 100, when they must be divisible
4019 * by 400 instead), we can simply calculate the number of days since some
4020 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
4021 * the days we derive from our month index, and adding in the day of the
4022 * month. The value used here is not adjusted for the actual origin which
4023 * it normally would use (1 January A.D. 1), since we're not exposing it.
4024 * We're only building the value so we can turn around and get the
4025 * normalised values for the year, month, day-of-month, and day-of-year.
4027 * For going backward, we need to bias the value we're using so that we find
4028 * the right year value. (Basically, we don't want the contribution of
4029 * March 1st to the number to apply while deriving the year). Having done
4030 * that, we 'count up' the contribution to the year number by accounting for
4031 * full quadracenturies (400-year periods) with their extra leap days, plus
4032 * the contribution from full centuries (to avoid counting in the lost leap
4033 * days), plus the contribution from full quad-years (to count in the normal
4034 * leap days), plus the leftover contribution from any non-leap years.
4035 * At this point, if we were working with an actual leap day, we'll have 0
4036 * days left over. This is also true for March 1st, however. So, we have
4037 * to special-case that result, and (earlier) keep track of the 'odd'
4038 * century and year contributions. If we got 4 extra centuries in a qcent,
4039 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
4040 * Otherwise, we add back in the earlier bias we removed (the 123 from
4041 * figuring in March 1st), find the month index (integer division by 30.6),
4042 * and the remainder is the day-of-month. We then have to convert back to
4043 * 'real' months (including fixing January and February from being 14/15 in
4044 * the previous year to being in the proper year). After that, to get
4045 * tm_yday, we work with the normalised year and get a new yearday value for
4046 * January 1st, which we subtract from the yearday value we had earlier,
4047 * representing the date we've re-built. This is done from January 1
4048 * because tm_yday is 0-origin.
4050 * Since POSIX time routines are only guaranteed to work for times since the
4051 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
4052 * applies Gregorian calendar rules even to dates before the 16th century
4053 * doesn't bother me. Besides, you'd need cultural context for a given
4054 * date to know whether it was Julian or Gregorian calendar, and that's
4055 * outside the scope for this routine. Since we convert back based on the
4056 * same rules we used to build the yearday, you'll only get strange results
4057 * for input which needed normalising, or for the 'odd' century years which
4058 * were leap years in the Julian calendar but not in the Gregorian one.
4059 * I can live with that.
4061 * This algorithm also fails to handle years before A.D. 1 gracefully, but
4062 * that's still outside the scope for POSIX time manipulation, so I don't
4066 year = 1900 + ptm->tm_year;
4067 month = ptm->tm_mon;
4068 mday = ptm->tm_mday;
4069 /* allow given yday with no month & mday to dominate the result */
4070 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
4073 jday = 1 + ptm->tm_yday;
4082 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4083 yearday += month*MONTH_TO_DAYS + mday + jday;
4085 * Note that we don't know when leap-seconds were or will be,
4086 * so we have to trust the user if we get something which looks
4087 * like a sensible leap-second. Wild values for seconds will
4088 * be rationalised, however.
4090 if ((unsigned) ptm->tm_sec <= 60) {
4097 secs += 60 * ptm->tm_min;
4098 secs += SECS_PER_HOUR * ptm->tm_hour;
4100 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4101 /* got negative remainder, but need positive time */
4102 /* back off an extra day to compensate */
4103 yearday += (secs/SECS_PER_DAY)-1;
4104 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4107 yearday += (secs/SECS_PER_DAY);
4108 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4111 else if (secs >= SECS_PER_DAY) {
4112 yearday += (secs/SECS_PER_DAY);
4113 secs %= SECS_PER_DAY;
4115 ptm->tm_hour = secs/SECS_PER_HOUR;
4116 secs %= SECS_PER_HOUR;
4117 ptm->tm_min = secs/60;
4119 ptm->tm_sec += secs;
4120 /* done with time of day effects */
4122 * The algorithm for yearday has (so far) left it high by 428.
4123 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4124 * bias it by 123 while trying to figure out what year it
4125 * really represents. Even with this tweak, the reverse
4126 * translation fails for years before A.D. 0001.
4127 * It would still fail for Feb 29, but we catch that one below.
4129 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
4130 yearday -= YEAR_ADJUST;
4131 year = (yearday / DAYS_PER_QCENT) * 400;
4132 yearday %= DAYS_PER_QCENT;
4133 odd_cent = yearday / DAYS_PER_CENT;
4134 year += odd_cent * 100;
4135 yearday %= DAYS_PER_CENT;
4136 year += (yearday / DAYS_PER_QYEAR) * 4;
4137 yearday %= DAYS_PER_QYEAR;
4138 odd_year = yearday / DAYS_PER_YEAR;
4140 yearday %= DAYS_PER_YEAR;
4141 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4146 yearday += YEAR_ADJUST; /* recover March 1st crock */
4147 month = yearday*DAYS_TO_MONTH;
4148 yearday -= month*MONTH_TO_DAYS;
4149 /* recover other leap-year adjustment */
4158 ptm->tm_year = year - 1900;
4160 ptm->tm_mday = yearday;
4161 ptm->tm_mon = month;
4165 ptm->tm_mon = month - 1;
4167 /* re-build yearday based on Jan 1 to get tm_yday */
4169 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4170 yearday += 14*MONTH_TO_DAYS + 1;
4171 ptm->tm_yday = jday - yearday;
4172 /* fix tm_wday if not overridden by caller */
4173 if ((unsigned)ptm->tm_wday > 6)
4174 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4178 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)
4186 PERL_ARGS_ASSERT_MY_STRFTIME;
4188 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4191 mytm.tm_hour = hour;
4192 mytm.tm_mday = mday;
4194 mytm.tm_year = year;
4195 mytm.tm_wday = wday;
4196 mytm.tm_yday = yday;
4197 mytm.tm_isdst = isdst;
4199 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4200 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4205 #ifdef HAS_TM_TM_GMTOFF
4206 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4208 #ifdef HAS_TM_TM_ZONE
4209 mytm.tm_zone = mytm2.tm_zone;
4214 Newx(buf, buflen, char);
4215 len = strftime(buf, buflen, fmt, &mytm);
4217 ** The following is needed to handle to the situation where
4218 ** tmpbuf overflows. Basically we want to allocate a buffer
4219 ** and try repeatedly. The reason why it is so complicated
4220 ** is that getting a return value of 0 from strftime can indicate
4221 ** one of the following:
4222 ** 1. buffer overflowed,
4223 ** 2. illegal conversion specifier, or
4224 ** 3. the format string specifies nothing to be returned(not
4225 ** an error). This could be because format is an empty string
4226 ** or it specifies %p that yields an empty string in some locale.
4227 ** If there is a better way to make it portable, go ahead by
4230 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4233 /* Possibly buf overflowed - try again with a bigger buf */
4234 const int fmtlen = strlen(fmt);
4235 int bufsize = fmtlen + buflen;
4237 Renew(buf, bufsize, char);
4239 buflen = strftime(buf, bufsize, fmt, &mytm);
4240 if (buflen > 0 && buflen < bufsize)
4242 /* heuristic to prevent out-of-memory errors */
4243 if (bufsize > 100*fmtlen) {
4249 Renew(buf, bufsize, char);
4254 Perl_croak(aTHX_ "panic: no strftime");
4260 #define SV_CWD_RETURN_UNDEF \
4261 sv_setsv(sv, &PL_sv_undef); \
4264 #define SV_CWD_ISDOT(dp) \
4265 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4266 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4269 =head1 Miscellaneous Functions
4271 =for apidoc getcwd_sv
4273 Fill the sv with current working directory
4278 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4279 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4280 * getcwd(3) if available
4281 * Comments from the orignal:
4282 * This is a faster version of getcwd. It's also more dangerous
4283 * because you might chdir out of a directory that you can't chdir
4287 Perl_getcwd_sv(pTHX_ register SV *sv)
4291 #ifndef INCOMPLETE_TAINTS
4295 PERL_ARGS_ASSERT_GETCWD_SV;
4299 char buf[MAXPATHLEN];
4301 /* Some getcwd()s automatically allocate a buffer of the given
4302 * size from the heap if they are given a NULL buffer pointer.
4303 * The problem is that this behaviour is not portable. */
4304 if (getcwd(buf, sizeof(buf) - 1)) {
4309 sv_setsv(sv, &PL_sv_undef);
4317 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4321 SvUPGRADE(sv, SVt_PV);
4323 if (PerlLIO_lstat(".", &statbuf) < 0) {
4324 SV_CWD_RETURN_UNDEF;
4327 orig_cdev = statbuf.st_dev;
4328 orig_cino = statbuf.st_ino;
4338 if (PerlDir_chdir("..") < 0) {
4339 SV_CWD_RETURN_UNDEF;
4341 if (PerlLIO_stat(".", &statbuf) < 0) {
4342 SV_CWD_RETURN_UNDEF;
4345 cdev = statbuf.st_dev;
4346 cino = statbuf.st_ino;
4348 if (odev == cdev && oino == cino) {
4351 if (!(dir = PerlDir_open("."))) {
4352 SV_CWD_RETURN_UNDEF;
4355 while ((dp = PerlDir_read(dir)) != NULL) {
4357 namelen = dp->d_namlen;
4359 namelen = strlen(dp->d_name);
4362 if (SV_CWD_ISDOT(dp)) {
4366 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4367 SV_CWD_RETURN_UNDEF;
4370 tdev = statbuf.st_dev;
4371 tino = statbuf.st_ino;
4372 if (tino == oino && tdev == odev) {
4378 SV_CWD_RETURN_UNDEF;
4381 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4382 SV_CWD_RETURN_UNDEF;
4385 SvGROW(sv, pathlen + namelen + 1);
4389 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4392 /* prepend current directory to the front */
4394 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4395 pathlen += (namelen + 1);
4397 #ifdef VOID_CLOSEDIR
4400 if (PerlDir_close(dir) < 0) {
4401 SV_CWD_RETURN_UNDEF;
4407 SvCUR_set(sv, pathlen);
4411 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4412 SV_CWD_RETURN_UNDEF;
4415 if (PerlLIO_stat(".", &statbuf) < 0) {
4416 SV_CWD_RETURN_UNDEF;
4419 cdev = statbuf.st_dev;
4420 cino = statbuf.st_ino;
4422 if (cdev != orig_cdev || cino != orig_cino) {
4423 Perl_croak(aTHX_ "Unstable directory path, "
4424 "current directory changed unexpectedly");
4435 #define VERSION_MAX 0x7FFFFFFF
4438 =for apidoc prescan_version
4440 Validate that a given string can be parsed as a version object, but doesn't
4441 actually perform the parsing. Can use either strict or lax validation rules.
4442 Can optionally set a number of hint variables to save the parsing code
4443 some time when tokenizing.
4448 Perl_prescan_version(pTHX_ const char *s, bool strict,
4449 const char **errstr,
4450 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4451 bool qv = (sqv ? *sqv : FALSE);
4453 int saw_decimal = 0;
4457 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4459 if (qv && isDIGIT(*d))
4460 goto dotted_decimal_version;
4462 if (*d == 'v') { /* explicit v-string */
4467 else { /* degenerate v-string */
4468 /* requires v1.2.3 */
4469 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4472 dotted_decimal_version:
4473 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4474 /* no leading zeros allowed */
4475 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4478 while (isDIGIT(*d)) /* integer part */
4484 d++; /* decimal point */
4489 /* require v1.2.3 */
4490 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4493 goto version_prescan_finish;
4500 while (isDIGIT(*d)) { /* just keep reading */
4502 while (isDIGIT(*d)) {
4504 /* maximum 3 digits between decimal */
4505 if (strict && j > 3) {
4506 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4511 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4514 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4519 else if (*d == '.') {
4521 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4526 else if (!isDIGIT(*d)) {
4532 if (strict && i < 2) {
4533 /* requires v1.2.3 */
4534 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4537 } /* end if dotted-decimal */
4539 { /* decimal versions */
4540 /* special strict case for leading '.' or '0' */
4543 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4545 if (*d == '0' && isDIGIT(d[1])) {
4546 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4550 /* and we never support negative versions */
4552 BADVERSION(s,errstr,"Invalid version format (negative version number)");
4555 /* consume all of the integer part */
4559 /* look for a fractional part */
4561 /* we found it, so consume it */
4565 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
4568 BADVERSION(s,errstr,"Invalid version format (version required)");
4570 /* found just an integer */
4571 goto version_prescan_finish;
4573 else if ( d == s ) {
4574 /* didn't find either integer or period */
4575 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4577 else if (*d == '_') {
4578 /* underscore can't come after integer part */
4580 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4582 else if (isDIGIT(d[1])) {
4583 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4586 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4590 /* anything else after integer part is just invalid data */
4591 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4594 /* scan the fractional part after the decimal point*/
4596 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
4597 /* strict or lax-but-not-the-end */
4598 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4601 while (isDIGIT(*d)) {
4603 if (*d == '.' && isDIGIT(d[-1])) {
4605 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4608 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4610 d = (char *)s; /* start all over again */
4612 goto dotted_decimal_version;
4616 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4619 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4621 if ( ! isDIGIT(d[1]) ) {
4622 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4630 version_prescan_finish:
4634 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
4635 /* trailing non-numeric data */
4636 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4644 *ssaw_decimal = saw_decimal;
4651 =for apidoc scan_version
4653 Returns a pointer to the next character after the parsed
4654 version string, as well as upgrading the passed in SV to
4657 Function must be called with an already existing SV like
4660 s = scan_version(s, SV *sv, bool qv);
4662 Performs some preprocessing to the string to ensure that
4663 it has the correct characteristics of a version. Flags the
4664 object if it contains an underscore (which denotes this
4665 is an alpha version). The boolean qv denotes that the version
4666 should be interpreted as if it had multiple decimals, even if
4673 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4678 const char *errstr = NULL;
4679 int saw_decimal = 0;
4683 AV * const av = newAV();
4684 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4686 PERL_ARGS_ASSERT_SCAN_VERSION;
4688 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4690 #ifndef NODEFAULT_SHAREKEYS
4691 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4694 while (isSPACE(*s)) /* leading whitespace is OK */
4697 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4699 /* "undef" is a special case and not an error */
4700 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4701 Perl_croak(aTHX_ "%s", errstr);
4711 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
4713 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
4714 if ( !qv && width < 3 )
4715 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4717 while (isDIGIT(*pos))
4719 if (!isALPHA(*pos)) {
4725 /* this is atoi() that delimits on underscores */
4726 const char *end = pos;
4730 /* the following if() will only be true after the decimal
4731 * point of a version originally created with a bare
4732 * floating point number, i.e. not quoted in any way
4734 if ( !qv && s > start && saw_decimal == 1 ) {
4738 rev += (*s - '0') * mult;
4740 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4741 || (PERL_ABS(rev) > VERSION_MAX )) {
4742 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4743 "Integer overflow in version %d",VERSION_MAX);
4754 while (--end >= s) {
4756 rev += (*end - '0') * mult;
4758 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4759 || (PERL_ABS(rev) > VERSION_MAX )) {
4760 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4761 "Integer overflow in version");
4770 /* Append revision */
4771 av_push(av, newSViv(rev));
4776 else if ( *pos == '.' )
4778 else if ( *pos == '_' && isDIGIT(pos[1]) )
4780 else if ( *pos == ',' && isDIGIT(pos[1]) )
4782 else if ( isDIGIT(*pos) )
4789 while ( isDIGIT(*pos) )
4794 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4802 if ( qv ) { /* quoted versions always get at least three terms*/
4803 I32 len = av_len(av);
4804 /* This for loop appears to trigger a compiler bug on OS X, as it
4805 loops infinitely. Yes, len is negative. No, it makes no sense.
4806 Compiler in question is:
4807 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4808 for ( len = 2 - len; len > 0; len-- )
4809 av_push(MUTABLE_AV(sv), newSViv(0));
4813 av_push(av, newSViv(0));
4816 /* need to save off the current version string for later */
4818 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
4819 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4820 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
4822 else if ( s > start ) {
4823 SV * orig = newSVpvn(start,s-start);
4824 if ( qv && saw_decimal == 1 && *start != 'v' ) {
4825 /* need to insert a v to be consistent */
4826 sv_insert(orig, 0, 0, "v", 1);
4828 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4831 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
4832 av_push(av, newSViv(0));
4835 /* And finally, store the AV in the hash */
4836 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4838 /* fix RT#19517 - special case 'undef' as string */
4839 if ( *s == 'u' && strEQ(s,"undef") ) {
4847 =for apidoc new_version
4849 Returns a new version object based on the passed in SV:
4851 SV *sv = new_version(SV *ver);
4853 Does not alter the passed in ver SV. See "upg_version" if you
4854 want to upgrade the SV.
4860 Perl_new_version(pTHX_ SV *ver)
4863 SV * const rv = newSV(0);
4864 PERL_ARGS_ASSERT_NEW_VERSION;
4865 if ( sv_isobject(ver) && sv_derived_from(ver, "version") )
4866 /* can just copy directly */
4869 AV * const av = newAV();
4871 /* This will get reblessed later if a derived class*/
4872 SV * const hv = newSVrv(rv, "version");
4873 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4874 #ifndef NODEFAULT_SHAREKEYS
4875 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4881 /* Begin copying all of the elements */
4882 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4883 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
4885 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4886 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
4888 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
4890 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4891 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
4894 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
4896 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4897 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
4900 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
4901 /* This will get reblessed later if a derived class*/
4902 for ( key = 0; key <= av_len(sav); key++ )
4904 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4905 av_push(av, newSViv(rev));
4908 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
4913 const MAGIC* const mg = SvVSTRING_mg(ver);
4914 if ( mg ) { /* already a v-string */
4915 const STRLEN len = mg->mg_len;
4916 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4917 sv_setpvn(rv,version,len);
4918 /* this is for consistency with the pure Perl class */
4919 if ( isDIGIT(*version) )
4920 sv_insert(rv, 0, 0, "v", 1);
4925 sv_setsv(rv,ver); /* make a duplicate */
4930 return upg_version(rv, FALSE);
4934 =for apidoc upg_version
4936 In-place upgrade of the supplied SV to a version object.
4938 SV *sv = upg_version(SV *sv, bool qv);
4940 Returns a pointer to the upgraded SV. Set the boolean qv if you want
4941 to force this SV to be interpreted as an "extended" version.
4947 Perl_upg_version(pTHX_ SV *ver, bool qv)
4949 const char *version, *s;
4954 PERL_ARGS_ASSERT_UPG_VERSION;
4956 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
4960 /* may get too much accuracy */
4962 #ifdef USE_LOCALE_NUMERIC
4963 char *loc = savepv(setlocale(LC_NUMERIC, NULL));
4964 setlocale(LC_NUMERIC, "C");
4966 len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4967 #ifdef USE_LOCALE_NUMERIC
4968 setlocale(LC_NUMERIC, loc);
4971 while (tbuf[len-1] == '0' && len > 0) len--;
4972 if ( tbuf[len-1] == '.' ) len--; /* eat the trailing decimal */
4973 version = savepvn(tbuf, len);
4976 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4977 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4981 else /* must be a string or something like a string */
4984 version = savepv(SvPV(ver,len));
4986 # if PERL_VERSION > 5
4987 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
4988 if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
4989 /* may be a v-string */
4990 char *testv = (char *)version;
4992 for (tlen=0; tlen < len; tlen++, testv++) {
4993 /* if one of the characters is non-text assume v-string */
4994 if (testv[0] < ' ') {
4995 SV * const nsv = sv_newmortal();
4998 int saw_decimal = 0;
4999 sv_setpvf(nsv,"v%vd",ver);
5000 pos = nver = savepv(SvPV_nolen(nsv));
5002 /* scan the resulting formatted string */
5003 pos++; /* skip the leading 'v' */
5004 while ( *pos == '.' || isDIGIT(*pos) ) {
5010 /* is definitely a v-string */
5011 if ( saw_decimal >= 2 ) {